@copio/sdk 0.1.3 → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +154 -151
- package/dist/adapters/image/canvas2d-adapter.js +1 -1
- package/dist/adapters/image/index.js +1 -1
- package/dist/adapters/index.js +1 -1
- package/dist/adapters/indexeddb-adapter.js +1 -1
- package/dist/adapters/pdf/index.js +1 -1
- package/dist/adapters/pdf/pdfkit-adapter.js +1 -1
- package/dist/adapters/storage/index.js +1 -1
- package/dist/adapters/storage/indexeddb-adapter.js +1 -1
- package/dist/cdn.js +42 -1119
- package/dist/{chunk-534NMCRQ.js → chunk-G5EUMLYT.js} +2 -2
- package/dist/{chunk-4YYY7PHH.js → chunk-GGERQ3CJ.js} +11 -11
- package/dist/chunk-K4NR6OAC.js +2 -0
- package/dist/chunk-L4OVZN23.js +2 -0
- package/dist/chunk-NQW6FFN7.js +50 -0
- package/dist/{chunk-DOKG4LX2.js → chunk-O7IV7A6O.js} +2 -2
- package/dist/chunk-Q7XPZMZA.js +1395 -0
- package/dist/core.js +1 -1
- package/dist/custom-elements.json +260 -1770
- package/dist/index.js +2 -2
- package/dist/scanner.js +16 -1120
- package/dist/sync.js +1 -1
- package/dist/types/sdk/elements.d.ts +0 -12
- package/dist/types/sdk/index.d.ts +0 -6
- package/dist/types/sdk/scanner.d.ts +2 -7
- package/dist/types/sdk/version.d.ts +1 -1
- package/package.json +2 -2
- package/sdk/index.js +0 -6
- package/sdk/scanner.js +5 -12
- package/sdk/version.js +1 -1
- package/dist/chunk-4XWSVHFW.js +0 -2472
- package/dist/chunk-5KUKBKWL.js +0 -33
- package/dist/chunk-DY5ZSP4Q.js +0 -2
- package/dist/chunk-IH2AI54D.js +0 -2
- package/dist/chunk-RDCHJL6F.js +0 -2
- package/dist/chunk-XEN5VKAV.js +0 -19
- package/dist/types/js/components/copio-header.d.ts +0 -23
- package/dist/types/js/components/copio-loader.d.ts +0 -6
- package/dist/types/js/core/store.d.ts +0 -2
- package/dist/types/js/routes/add-edit/copio-add-edit-dialog.d.ts +0 -9
- package/dist/types/js/routes/doc/copio-carousel.d.ts +0 -42
- package/dist/types/js/routes/doc/copio-images.d.ts +0 -33
- package/dist/types/js/routes/home/copio-row.d.ts +0 -49
- package/dist/types/js/styles/cropper-styles.d.ts +0 -5
package/dist/scanner.js
CHANGED
|
@@ -1,1090 +1,7 @@
|
|
|
1
1
|
/* @copio/sdk <copio-scanner> Web Component bundle */
|
|
2
|
-
var vh=Object.defineProperty;var is=(s,t,e)=>()=>{if(e)throw e[0];try{return s&&(t=s(s=0)),t}catch(i){throw e=[i],i}};var ss=(s,t)=>{for(var e in t)vh(s,e,{get:t[e],enumerable:!0})};var wo={};ss(wo,{Path2D:()=>iu,createCanvas:()=>eu,default:()=>tu});var tu,eu,iu,xo=is(()=>{tu={},eu=()=>null,iu=globalThis.Path2D||class{}});var Nc={};ss(Nc,{Path2D:()=>ru,createCanvas:()=>nu,default:()=>su});var su,nu,ru,Bc=is(()=>{su={},nu=()=>null,ru=globalThis.Path2D||class{}});var Uc={};ss(Uc,{Path2D:()=>lu,createCanvas:()=>ou,default:()=>au});var au,ou,lu,$c=is(()=>{au={},ou=()=>null,lu=globalThis.Path2D||class{}});var Hc={};ss(Hc,{Path2D:()=>du,createCanvas:()=>hu,default:()=>cu});var cu,hu,du,jc=is(()=>{cu={},hu=()=>null,du=globalThis.Path2D||class{}});var zc={};ss(zc,{Path2D:()=>fu,createCanvas:()=>pu,default:()=>uu});var uu,pu,fu,Vc=is(()=>{uu={},pu=()=>null,fu=globalThis.Path2D||class{}});var Wc={};ss(Wc,{Path2D:()=>bu,createCanvas:()=>mu,default:()=>gu});var gu,mu,bu,Gc=is(()=>{gu={},mu=()=>null,bu=globalThis.Path2D||class{}});var Xe=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 ns=class extends Xe{#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 a=n.pages.findIndex(c=>c.id===e);if(a>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?n.pages[a]={...n.pages[a],...i}:n.pages[a]={...n.pages[a],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(a=>a.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 pi=s=>typeof s;var cl=pi(""),wh=pi(!0),hl=pi(0),xh=pi(pi),Hn="type",Ei="default",ha="Listener",el="Result",da="add",_i="Has",js="Ids",ui="Table",il=ui+"s",Ah=ui+js,ls="Row",dl=ls+"Count",ul=ls+js,Sh="Sorted"+ls+js,Us="Cell",Wn=Us+js,Gn="Value",sl=Gn+"s",Eh=Gn+js,Ot=s=>""+s;var _h=(s,t="",e)=>s.split(t,e),ua=globalThis,Jn=Math,na=Jn.max,ra=Jn.min,Ch=Jn.floor,pl=isFinite,St=s=>s==null,Nt=(s,t,e)=>St(s)?e?.():t(s),fl=s=>s==cl||s==wh,kh=s=>pi(s)==cl,Ue=s=>pi(s)==xh,cs=s=>Array.isArray(s),pa=(s,t,e)=>s.slice(t,e),_e=s=>s.length,gl=()=>{};var aa=async(s,t,e)=>{try{return await s()}catch(i){t?.(i)}},fa=(s,t)=>s.includes(t),qn=(s,t)=>s.every(t),ml=(s,t)=>_e(s)===_e(t)&&qn(s,((e,i)=>t[i]===e)),nl=(s,t)=>qn(s,((e,i)=>i==0||t(s[i-1],e)<=0)),ga=(s,t)=>s.sort(t),ve=(s,t)=>s.forEach(t),Ti=(s,t)=>s.map(t),rl=s=>bl(s,((t,e)=>t+e),0),$s=s=>_e(s)==0,bl=(s,t,e)=>s.reduce(t,e),ye=(s,...t)=>s.push(...t),al=s=>s.pop(),yl=s=>s.shift(),as=s=>{let t=pi(s);return fl(t)||t==hl&&pl(s)?t:void 0};var Xn=(s,t,e,i,n)=>St(n)?s.delCell(t,e,i,!0):s.setCell(t,e,i,n),ma=(s,t,e)=>St(e)?s.delValue(t):s.setValue(t,e),wa=s=>t=>bl(hs(t),((e,i)=>e+s(i)),0),ds=s=>s?.size??0,Pi=wa(ds),Ye=wa(Pi),oa=wa(Ye),$t=(s,t)=>s?.has(t)??!1,vt=s=>St(s)||ds(s)==0,hs=s=>[...s?.values()??[]],os=s=>s.clear(),yt=(s,t)=>s?.forEach(t),He=(s,t)=>s?.delete(t),fi=Object,ol=s=>fi.getPrototypeOf(s),Th=fi.isFrozen,vl=fi.entries,Kn=s=>!St(s)&&Nt(ol(s),(t=>t==fi.prototype||St(ol(t))),(()=>!0)),Ph=fi.keys,us=fi.freeze,Dh=(s=[])=>fi.fromEntries(s),Bs=(s,t)=>t in s,wl=(s,t)=>(delete s[t],s),Mh=(s,t)=>ve(vl(s),(([e,i])=>t(i,e))),Ke=(s,t)=>Dh(((e,i)=>Ti(vl(e),(([n,a])=>i(a,n))))(s,((e,i)=>[i,t(e,i)]))),$e=s=>Kn(s)&&(t=>_e(Ph(t)))(s)==0;var hi=(s,t,e,i=0)=>St(s)||!Kn(s)||!i&&$e(s)||Th(s)?(e?.(),!1):(Mh(s,((n,a)=>{t(n,a)||wl(s,a)})),!!i||!$e(s)),ft=s=>new Map(s),ki=s=>[...s?.keys()??[]],ht=(s,t)=>s?.get(t),Xt=(s,t)=>yt(s,((e,i)=>t(i,e))),bt=(s,t,e)=>St(e)?(He(s,t),s):s?.set(t,e),Ut=(s,t,e,i)=>($t(s,t)?i?.(ht(s,t)):bt(s,t,e()),ht(s,t)),Ci=(s,t,e,i=bt)=>(Ke(t,((n,a)=>e(s,a,n))),Xt(s,(n=>Bs(t,n)?0:i(s,n))),s),be=(s,t,e,i)=>{let n={};return yt(s,((a,c)=>{if(!e?.(a,c)){let l=t?t(a,c):a;i?.(l)||(n[c]=l)}})),n},ba=(s,t,e)=>be(s,(i=>be(i,t,e)),vt,$e),jn=(s,t,e)=>be(s,(i=>ba(i,t,e)),vt,$e),di=(s,t)=>{let e=ft();return yt(s,((i,n)=>e.set(n,t?.(i)??i))),e},ya=s=>di(s,di),la=s=>di(s,ya),Hs=(s,t,e,i,n=0)=>Nt((e?Ut:ht)(s,t[n],n>_e(t)-2?e:ft),(a=>{if(n>_e(t)-2)return i?.(a)&&bt(s,t[n]),a;let c=Hs(a,t,e,i,n+1);return vt(a)&&bt(s,t[n]),c})),Kt=s=>new Set(cs(s)||St(s)?s:[s]),jt=(s,t)=>s?.add(t),Qn=(s,t,e,i,n)=>{let a=s.hasRow,c=ft(),l=ft(),d=ft(),m=ft(),u=ft(),o=ft(),p=(v,r,...h)=>{let b=Ut(o,v,Kt);return ve(h,(A=>jt(b,A)&&r&&s.callListener(A))),h},w=(v,...r)=>Nt(ht(o,v),(h=>{ve($s(r)?hs(h):r,(b=>{s.delListener(b),He(h,b)})),vt(h)&&bt(o,v)})),S=(v,r)=>{bt(c,v,r),$t(l,v)||(bt(l,v,t()),bt(m,v,ft()),bt(u,v,ft()),n(d))},f=v=>{bt(c,v),bt(l,v),bt(m,v),bt(u,v),w(v),n(d)};return[()=>s,()=>ki(c),v=>Xt(l,v),v=>$t(l,v),v=>ht(c,v),v=>ht(l,v),(v,r)=>bt(l,v,r),S,(v,r,h,b,A)=>{S(v,r);let D=ft(),_=ft(),I=ht(m,v),N=ht(u,v),H=K=>{let it=z=>s.getCell(r,K,z),ot=ht(I,K),X=a(r,K)?e(b(it,K)):void 0;if(ot===X||cs(ot)&&cs(X)&&ml(ot,X)||bt(D,K,[ot,X]),!St(A)){let z=ht(N,K),W=a(r,K)?A(it,K):void 0;z!=W&&bt(_,K,W)}},j=K=>{h((()=>{yt(D,(([,it],ot)=>bt(I,ot,it))),yt(_,((it,ot)=>bt(N,ot,it)))}),D,_,I,N,K),os(D),os(_)};Xt(I,H),s.hasTable(r)&&ve(s.getRowIds(r),(K=>{$t(I,K)||H(K)})),j(!0),w(v),p(v,0,s.addRowListener(r,null,((K,it,ot)=>H(ot))),s.addTableListener(r,(()=>j())))},f,v=>i(v,d),()=>Xt(o,f),p,w]},Yn=(s,t)=>kh(s)?e=>e(s):s??(()=>t??""),zs=(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}},Rh=/^\d+$/,xl=()=>{let s=[],t=0;return[e=>(e?yl(s):null)??""+t++,e=>{Rh.test(e)&&_e(s)<1e3&&ye(s,e)}]},Vs=s=>{let t,[e,i]=xl(),n=ft();return[(a,c,l,d=[],m=()=>[])=>{t??=s();let u=e(1);return bt(n,u,[a,c,l,d,m]),jt(Hs(c,l??[""],Kt),u),u},(a,c,...l)=>ve(((d,m=[""])=>{let u=[],o=(p,w)=>w==_e(m)?ye(u,p):m[w]===null?yt(p,(S=>o(S,w+1))):ve([m[w],null],(S=>o(ht(p,S),w+1)));return o(d,0),u})(a,c),(d=>yt(d,(m=>ht(n,m)[0](t,...c??[],...l))))),a=>Nt(ht(n,a),(([,c,l])=>(Hs(c,l??[""],void 0,(d=>(He(d,a),vt(d)?1:0))),bt(n,a),i(a),l))),a=>Nt(ht(n,a),(([c,,l=[],d,m])=>{let u=(...o)=>{let p=_e(o);p==_e(l)?c(t,...o,...m(o)):St(l[p])?ve(d[p]?.(...o)??[],(w=>u(...o,w))):u(...o,l[p])};u()}))]},Xu=zs((s=>{let t,e,i,n=100,a=ft(),c=ft(),l=1,d=ft(),m=ft(),[u,o,p]=Vs((()=>W)),w=ft(),S=ft(),f=[],v=[],r=(Y,et)=>{l=0,s.transaction((()=>{let[rt,ct]=ht(w,et);yt(rt,((st,G)=>yt(st,((x,T)=>yt(x,((R,g)=>Xn(s,G,T,g,R[Y]))))))),yt(ct,((st,G)=>ma(s,G,st[Y])))})),l=1},h=Y=>{bt(w,Y),bt(S,Y),o(m,[Y])},b=(Y,et)=>ve(((rt,ct)=>rt.splice(0,ct))(Y,et??_e(Y)),h),A=()=>b(f,_e(f)-n),D=()=>Nt(t,(()=>{ye(f,t),A(),b(v),t=void 0,i=1})),_=()=>{t=al(f),i=1},I,N,H=(Y="")=>(St(t)&&(t=""+e++,bt(w,t,[a,c]),X(t,Y),a=ft(),c=ft(),i=1),t),j=()=>{$s(f)||(((Y,...et)=>{Y.unshift(...et)})(v,H()),r(0,t),t=al(f),i=1)},K=()=>{$s(v)||(ye(f,t),t=yl(v),r(1,t),i=1)},it=()=>{i&&(o(d),i=0)},ot=Y=>{let et=H(Y);return it(),et},X=(Y,et)=>(z(Y)&&ht(S,Y)!==et&&(bt(S,Y,et),o(m,[Y])),W),z=Y=>$t(w,Y),W={setSize:Y=>(n=Y,A(),W),addCheckpoint:ot,setCheckpoint:X,getStore:()=>s,getCheckpointIds:()=>[[...f],t,[...v]],forEachCheckpoint:Y=>Xt(S,Y),hasCheckpoint:z,getCheckpoint:Y=>ht(S,Y),goBackward:()=>(j(),it(),W),goForward:()=>(K(),it(),W),goTo:Y=>{let et=fa(f,Y)?j:fa(v,Y)?K:null;for(;!St(et)&&Y!=t;)et();return it(),W},addCheckpointIdsListener:Y=>u(Y,d),addCheckpointListener:(Y,et)=>u(et,m,[Y]),delListener:Y=>(p(Y),W),clear:()=>(b(f),b(v),St(t)||h(t),t=void 0,e=0,ot(),W),clearForward:()=>($s(v)||(b(v),o(d)),W),destroy:()=>{s.delListener(I),s.delListener(N)},getListenerStats:()=>({checkpointIds:Pi(d),checkpoint:Pi(m)}),_registerListeners:()=>{I=s.addCellListener(null,null,null,((Y,et,rt,ct,st,G)=>{if(l){D();let x=Ut(a,et,ft),T=Ut(x,rt,ft),R=Ut(T,ct,(()=>[G,void 0]));R[1]=st,R[0]===st&&vt(bt(T,ct))&&vt(bt(x,rt))&&vt(bt(a,et))&&_(),it()}})),N=s.addValueListener(null,((Y,et,rt,ct)=>{if(l){D();let st=Ut(c,et,(()=>[ct,void 0]));st[1]=rt,st[0]===rt&&vt(bt(c,et))&&_(),it()}}))}};return us(W.clear())}),(s=>s._registerListeners())),Ih=_h("-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"),Ku=ft(Ti(Ih,((s,t)=>[s,t])));var Yu=ua.crypto?s=>ua.crypto.getRandomValues(s):s=>Ti(s,(()=>Ch(256*Jn.random())));var Lh=JSON.stringify,ca=JSON.parse,rs=s=>Lh(s,((t,e)=>{return i=Map,e instanceof i?fi.fromEntries([...e]):e;var i})),Ju=new ua.TextEncoder;var Qu=2**36,Zu=2**30,tp=2**24,ep=2**18;var Al=(s,t)=>(s??0)<(t??0)?-1:1,ip=zs((s=>{let t=ft(),e=ft(),[i,n,a]=Vs((()=>h)),[c,l,d,m,u,o,p,,w,S,f,v]=Qn(s,ft,(b=>St(b)?"":cs(b)?Ti(b,Ot):Ot(b)),i,n),r=(b,A,D)=>{let _=u(b);yt(D,((I,N)=>A(N,(H=>yt(I,(j=>H(j,(K=>s.forEachCell(_,j,K)))))))))},h={setIndexDefinition:(b,A,D,_,I,N=Al)=>{let H=St(I)?void 0:([j],[K])=>I(j,K);return w(b,A,((j,K,it,ot,X,z)=>{let W=0,Y=Kt(),et=Kt(),rt=o(b);if(yt(K,(([ct,st],G)=>{let x=Kt(ct),T=Kt(st);yt(x,(R=>He(T,R)?He(x,R):0)),yt(x,(R=>{jt(Y,R),Nt(ht(rt,R),(g=>{He(g,G),vt(g)&&(bt(rt,R),W=1)}))})),yt(T,(R=>{jt(Y,R),$t(rt,R)||(bt(rt,R,Kt()),W=1),jt(ht(rt,R),G),St(_)||jt(et,R)}))})),j(),vt(X)||(z?Xt(rt,(ct=>jt(et,ct))):Xt(it,(ct=>Nt(ht(ot,ct),(st=>ve(cs(st)?st:[st],(G=>jt(et,G))))))),yt(et,(ct=>{let st=(x,T)=>N(ht(X,x),ht(X,T),ct),G=[...ht(rt,ct)];nl(G,st)||(bt(rt,ct,Kt(ga(G,st))),jt(Y,ct))}))),(W||z)&&!St(H)){let ct=[...rt];nl(ct,H)||(p(b,ft(ga(ct,H))),W=1)}W&&n(t,[b]),yt(Y,(ct=>n(e,[b,ct])))}),Yn(D),Nt(_,Yn)),h},delIndexDefinition:b=>(S(b),h),getStore:c,getIndexIds:l,forEachIndex:b=>d(((A,D)=>b(A,(_=>r(A,_,D))))),forEachSlice:(b,A)=>r(b,A,o(b)),hasIndex:m,hasSlice:(b,A)=>$t(o(b),A),getTableId:u,getSliceIds:b=>ki(o(b)),getSliceRowIds:(b,A)=>hs(ht(o(b),A)),addIndexIdsListener:f,addSliceIdsListener:(b,A)=>i(A,t,[b]),addSliceRowIdsListener:(b,A,D)=>i(D,e,[b,A]),delListener:b=>(a(b),h),destroy:v,getListenerStats:()=>({sliceIds:Pi(t),sliceRowIds:Ye(e)})};return us(h)}));var zn=s=>[s,s],Wt=(s,t=Pi)=>t(s[0])+t(s[1]),Gt=()=>[ft(),ft()],ll=s=>[...s],Vn=([s,t])=>s===t,Ns=(s,t,e)=>bt(s,t,ht(s,t)==-e?void 0:e),Di=()=>{let s,t,e=!1,i=!1,n=0,a=[],c=ft(),l=ft(),d=ft(),m=ft(),u=ft(),o=ft(),p=ft(),w=ft(),S=ft(),f=ft(),v=ft(),r=ft(),h=ft(),b=ft(),A=Kt(),D=ft(),_=ft(),I=ft(),N=ft(),H=Gt(),j=Gt(),K=Gt(),it=Gt(),ot=Gt(),X=Gt(),z=Gt(),W=Gt(),Y=Gt(),et=Gt(),rt=Gt(),ct=Gt(),st=Gt(),G=Gt(),x=Gt(),T=Gt(),R=Gt(),g=Gt(),y=Gt(),C=Gt(),k=Gt(),O=Gt(),M=ft(),E=Gt(),[L,$,U,P]=Vs((()=>ce)),F=B=>{if(!hi(B,((J,at)=>fa([Hn,Ei],at))))return!1;let q=B[Hn];return!(!fl(q)&&q!=hl)&&(as(B[Ei])!=q&&wl(B,Ei),!0)},V=cs,Q=(B,q)=>(!s||$t(v,q)||Ne(q))&&hi(B,((J,at)=>Z(q,at,J)),(()=>Ne(q))),Z=(B,q,J,at)=>hi(at?J:dt(J,B,q),((ut,mt)=>Nt(tt(B,q,mt,ut),(At=>(J[mt]=At,!0)),(()=>!1))),(()=>Ne(B,q))),tt=(B,q,J,at)=>s?Nt(ht(ht(v,B),J),(ut=>as(at)!=ut[Hn]?Ne(B,q,J,at,ut[Ei]):at),(()=>Ne(B,q,J,at))):St(as(at))?Ne(B,q,J,at):at,nt=(B,q)=>hi(q?B:lt(B),((J,at)=>Nt(pt(at,J),(ut=>(B[at]=ut,!0)),(()=>!1))),(()=>Si())),pt=(B,q)=>t?Nt(ht(h,B),(J=>as(q)!=J[Hn]?Si(B,q,J[Ei]):q),(()=>Si(B,q))):St(as(q))?Si(B,q):q,dt=(B,q,J)=>(Nt(ht(r,q),(([at,ut])=>{yt(at,((mt,At)=>{Bs(B,At)||(B[At]=mt)})),yt(ut,(mt=>{Bs(B,mt)||Ne(q,J,mt)}))})),B),lt=B=>(t&&(yt(b,((q,J)=>{Bs(B,J)||(B[J]=q)})),yt(A,(q=>{Bs(B,q)||Si(q)}))),B),wt=B=>Ci(v,B,((q,J,at)=>{let ut=ft(),mt=Kt();Ci(Ut(v,J,ft),at,((At,Pt,Mt)=>{bt(At,Pt,Mt),Nt(Mt[Ei],(qe=>bt(ut,Pt,qe)),(()=>jt(mt,Pt)))})),bt(r,J,[ut,mt])}),((q,J)=>{bt(v,J),bt(r,J)})),Tt=B=>Ci(h,B,((q,J,at)=>{bt(h,J,at),Nt(at[Ei],(ut=>bt(b,J,ut)),(()=>jt(A,J)))}),((q,J)=>{bt(h,J),bt(b,J),He(A,J)})),xt=B=>$e(B)?Nn():Fn(B),Dt=B=>Ci(I,B,((q,J,at)=>Rt(J,at)),((q,J)=>ri(J))),Rt=(B,q)=>Ci(Ut(I,B,(()=>(oi(B,1),bt(D,B,xl()),bt(_,B,ft()),ft()))),q,((J,at,ut)=>Bt(B,J,at,ut)),((J,at)=>ai(B,J,at))),Bt=(B,q,J,at,ut)=>Ci(Ut(q,J,(()=>(Qi(B,J,1),ft()))),at,((mt,At,Pt)=>Ht(B,J,mt,At,Pt)),((mt,At)=>ae(B,q,J,mt,At,ut))),Ht=(B,q,J,at,ut)=>{$t(J,at)||Me(B,q,at,1);let mt=ht(J,at);ut!==mt&&(te(B,q,at,mt,ut),bt(J,at,ut))},le=(B,q,J,at,ut)=>Nt(ht(q,J),(mt=>Ht(B,J,mt,at,ut)),(()=>Bt(B,q,J,dt({[at]:ut},B,J)))),Se=B=>$e(B)?Bn():On(B),Oe=B=>Ci(N,B,((q,J,at)=>Te(J,at)),((q,J)=>se(J))),Te=(B,q)=>{$t(N,B)||kn(B,1);let J=ht(N,B);q!==J&&(Zi(B,J,q),bt(N,B,q))},De=B=>ht(I,B)??Rt(B,{}),ri=B=>Rt(B,{}),ai=(B,q,J)=>{let[,at]=ht(D,B);at(J),Bt(B,q,J,{},!0)},ae=(B,q,J,at,ut,mt)=>{let At=ht(ht(r,B)?.[0],ut);if(!St(At)&&!mt)return Ht(B,J,at,ut,At);let Pt=Mt=>{te(B,J,Mt,ht(at,Mt)),Me(B,J,Mt,-1),bt(at,Mt)};St(At)?Pt(ut):Xt(at,Pt),vt(at)&&(Qi(B,J,-1),vt(bt(q,J))&&(oi(B,-1),bt(I,B),bt(D,B),bt(_,B)))},se=B=>{let q=ht(b,B);if(!St(q))return Te(B,q);Zi(B,ht(N,B)),kn(B,-1),bt(N,B)},oi=(B,q)=>Ns(c,B,q),Qi=(B,q,J)=>Ns(Ut(m,B,ft),q,J)&&bt(d,B,Ut(d,B,(()=>0))+J),Me=(B,q,J,at)=>{let ut=ht(_,B),mt=ht(ut,J)??0;(mt==0&&at==1||mt==1&&at==-1)&&Ns(Ut(l,B,ft),J,at),bt(ut,J,mt!=-at?mt+at:null),Ns(Ut(Ut(u,B,ft),q,ft),J,at)},te=(B,q,J,at,ut)=>{Ut(Ut(Ut(o,B,ft),q,ft),J,(()=>[at,0]))[1]=ut,a[3]?.(B,q,J,ut)},kn=(B,q)=>Ns(p,B,q),Zi=(B,q,J)=>{Ut(w,B,(()=>[q,0]))[1]=J,a[4]?.(B,J)},Ne=(B,q,J,at,ut)=>(ye(Ut(Ut(Ut(S,B,ft),q,ft),J,(()=>[])),at),ut),Si=(B,q,J)=>(ye(Ut(f,B,(()=>[])),q),J),Be=(B,q,J)=>Nt(ht(ht(ht(o,B),q),J),(([at,ut])=>[!0,at,ut]),(()=>[!1,...zn(Mn(B,q,J))])),Tn=B=>Nt(ht(w,B),(([q,J])=>[!0,q,J]),(()=>[!1,...zn(Rn(B))])),ts=B=>vt(S)||vt(T[B])?0:yt(B?la(S):S,((q,J)=>yt(q,((at,ut)=>yt(at,((mt,At)=>$(T[B],[J,ut,At],mt))))))),li=B=>vt(f)||vt(R[B])?0:yt(B?di(f):f,((q,J)=>$(R[B],[J],q))),pe=(B,q,J,at)=>{if(!vt(B))return $(q,at,(()=>be(B))),Xt(B,((ut,mt)=>$(J,[...at??[],ut],mt==1))),1},Pn=B=>{let q=In();q!=e&&$(H[B],void 0,q);let J=vt(et[B]),at=vt(st[B])&&vt(G[B])&&vt(Y[B])&&vt(rt[B])&&vt(X[B])&&vt(z[B])&&vt(W[B])&&J&&vt(K[B])&&vt(it[B]),ut=vt(x[B])&&vt(ct[B])&&vt(ot[B])&&vt(j[B]);if(!at||!ut){let mt=B?[di(c),ya(l),di(d),ya(m),la(u),la(o)]:[c,l,d,m,u,o];if(!at){pe(mt[0],K[B],it[B]),yt(mt[1],((Pt,Mt)=>pe(Pt,X[B],z[B],[Mt]))),yt(mt[2],((Pt,Mt)=>{Pt!=0&&$(W[B],[Mt],$o(Mt))}));let At=Kt();yt(mt[3],((Pt,Mt)=>{pe(Pt,Y[B],rt[B],[Mt])&&!J&&($(et[B],[Mt,null]),jt(At,Mt))})),J||yt(mt[5],((Pt,Mt)=>{if(!$t(At,Mt)){let qe=Kt();yt(Pt,(ci=>yt(ci,(([Un,$n],Os)=>$n!==Un?jt(qe,Os):He(ci,Os))))),yt(qe,(ci=>$(et[B],[Mt,ci])))}})),yt(mt[4],((Pt,Mt)=>yt(Pt,((qe,ci)=>pe(qe,st[B],G[B],[Mt,ci])))))}if(!ut){let At;yt(mt[5],((Pt,Mt)=>{let qe;yt(Pt,((ci,Un)=>{let $n;yt(ci,(([Os,tl],yh)=>{tl!==Os&&($(x[B],[Mt,Un,yh],tl,Os,Be),At=qe=$n=1)})),$n&&$(ct[B],[Mt,Un],Be)})),qe&&$(ot[B],[Mt],Be)})),At&&$(j[B],void 0,Be)}}},No=B=>{let q=Ln();q!=i&&$(g[B],void 0,q);let J=vt(C[B])&&vt(k[B]),at=vt(O[B])&&vt(y[B]);if(!J||!at){let ut=B?[di(p),di(w)]:[p,w];if(J||pe(ut[0],C[B],k[B]),!at){let mt;yt(ut[1],(([At,Pt],Mt)=>{Pt!==At&&($(O[B],[Mt],Pt,At,Tn),mt=1)})),mt&&$(y[B],void 0,Tn)}}},Vt=(B,...q)=>(sa((()=>B(...Ti(q,Ot)))),ce),Bo=(B,q,J,at,ut)=>{let mt=Dn(B,q,...J);return L((()=>{let At=Dn(B,q,...J);ml(At,mt)||(mt=At,at(ce,B,q,...J,mt))}),et[ut?1:0],[B,q],[Ee])},Qr=()=>jn(I),Ee=()=>ki(I),Uo=B=>ki(ht(_,Ot(B))),$o=B=>ds(ht(I,Ot(B))),es=B=>ki(ht(I,Ot(B))),Dn=(B,q,J,at=0,ut)=>{return Kn(B)?Dn(B.tableId,B.cellId,B.descending,B.offset,B.limit):Ti(pa(ga((mt=ht(I,Ot(B)),At=(Pt,Mt)=>[St(q)?Mt:ht(Pt,Ot(q)),Mt],Ti([...mt?.entries()??[]],(([Pt,Mt])=>At(Mt,Pt)))),(([Pt],[Mt])=>Al(Pt,Mt)*(J?-1:1))),at,St(ut)?ut:at+ut),(([,Pt])=>Pt));var mt,At},Zr=(B,q)=>ki(ht(ht(I,Ot(B)),Ot(q))),Mn=(B,q,J)=>ht(ht(ht(I,Ot(B)),Ot(q)),Ot(J)),ta=()=>be(N),ea=()=>ki(N),Rn=B=>ht(N,Ot(B)),In=()=>!vt(I),Ho=B=>$t(I,Ot(B)),jo=(B,q)=>$t(ht(_,Ot(B)),Ot(q)),zo=(B,q)=>$t(ht(I,Ot(B)),Ot(q)),Vo=(B,q,J)=>$t(ht(ht(I,Ot(B)),Ot(q)),Ot(J)),Ln=()=>!vt(N),Wo=B=>$t(N,Ot(B)),Fn=B=>Vt((()=>(q=>hi(q,Q,Ne))(B)?Dt(B):0)),On=B=>Vt((()=>nt(B)?Oe(B):0)),Go=B=>(aa((()=>xt(ca(B)))),ce),qo=B=>Vt((()=>{if((s=hi(B,(q=>hi(q,F))))&&(wt(B),!vt(I))){let q=Qr();Nn(),Fn(q)}})),Xo=B=>Vt((()=>{if(t=(q=>hi(q,F))(B)){let q=ta();ia(),Bn(),t=!0,Tt(B),On(q)}})),Nn=()=>Vt((()=>Dt({}))),Ko=B=>Vt((q=>$t(I,q)?ri(q):0),B),Yo=(B,q)=>Vt(((J,at)=>Nt(ht(I,J),(ut=>$t(ut,at)?ai(J,ut,at):0))),B,q),Bn=()=>Vt((()=>Oe({}))),Jo=()=>Vt((()=>{wt({}),s=!1})),ia=()=>Vt((()=>{Tt({}),t=!1})),sa=(B,q)=>{if(n!=-1){Qo();let J=B();return Zo(q),J}},Qo=()=>(n!=-1&&n++,n==1&&(a[0]?.(),$(M)),ce),Zo=B=>(n>0&&(n--,n==0&&(n=1,ts(1),vt(o)||Pn(1),li(1),vt(w)||No(1),B?.(ce)&&(yt(o,((q,J)=>yt(q,((at,ut)=>yt(at,(([mt],At)=>Xn(ce,J,ut,At,mt))))))),os(o),yt(w,(([q],J)=>ma(ce,J,q))),os(w)),$(E[0],void 0),n=-1,ts(0),vt(o)||Pn(0),li(0),vt(w)||No(0),a[1]?.(),$(E[1],void 0),a[2]?.(),n=0,e=In(),i=Ln(),ve([c,l,d,m,u,o,S,p,w,f],os))),ce),ce={getContent:()=>[Qr(),ta()],getTables:Qr,getTableIds:Ee,getTable:B=>ba(ht(I,Ot(B))),getTableCellIds:Uo,getRowCount:$o,getRowIds:es,getSortedRowIds:Dn,getRow:(B,q)=>be(ht(ht(I,Ot(B)),Ot(q))),getCellIds:Zr,getCell:Mn,getValues:ta,getValueIds:ea,getValue:Rn,hasTables:In,hasTable:Ho,hasTableCell:jo,hasRow:zo,hasCell:Vo,hasValues:Ln,hasValue:Wo,getTablesJson:()=>rs(I),getValuesJson:()=>rs(N),getJson:()=>rs([I,N]),getTablesSchemaJson:()=>rs(v),getValuesSchemaJson:()=>rs(h),getSchemaJson:()=>rs([v,h]),hasTablesSchema:()=>s,hasValuesSchema:()=>t,setContent:B=>Vt((()=>{let q=Ue(B)?B():B;V(q)&&(([J,at])=>{($e(J)?Nn:Fn)(J),($e(at)?Bn:On)(at)})(q)})),setTables:Fn,setTable:(B,q)=>Vt((J=>Q(q,J)?Rt(J,q):0),B),setRow:(B,q,J)=>Vt(((at,ut)=>Z(at,ut,J)?Bt(at,De(at),ut,J):0),B,q),addRow:(B,q,J=!0)=>sa((()=>{let at;return Z(B,at,q)&&(B=Ot(B),Bt(B,De(B),at=((ut,mt)=>{let[At]=ht(D,ut),Pt;do Pt=At(mt);while($t(ht(I,ut),Pt));return Pt})(B,J?1:0),q)),at})),setPartialRow:(B,q,J)=>Vt(((at,ut)=>{if(Z(at,ut,J,1)){let mt=De(at);Ke(J,((At,Pt)=>le(at,mt,ut,Pt,At)))}}),B,q),setCell:(B,q,J,at)=>Vt(((ut,mt,At)=>Nt(tt(ut,mt,At,Ue(at)?at(Mn(ut,mt,At)):at),(Pt=>le(ut,De(ut),mt,At,Pt)))),B,q,J),setValues:On,setPartialValues:B=>Vt((()=>nt(B,1)?Ke(B,((q,J)=>Te(J,q))):0)),setValue:(B,q)=>Vt((J=>Nt(pt(J,Ue(q)?q(Rn(J)):q),(at=>Te(J,at)))),B),applyChanges:B=>Vt((()=>{Ke(B[0],((q,J)=>St(q)?Ko(J):Ke(q,((at,ut)=>St(at)?Yo(J,ut):Ke(at,((mt,At)=>Xn(ce,J,ut,At,mt))))))),Ke(B[1],((q,J)=>ma(ce,J,q)))})),setTablesJson:Go,setValuesJson:B=>(aa((()=>Se(ca(B)))),ce),setJson:B=>Vt((()=>aa((()=>{let[q,J]=ca(B);xt(q),Se(J)}),(()=>Go(B))))),setTablesSchema:qo,setValuesSchema:Xo,setSchema:(B,q)=>Vt((()=>{qo(B),Xo(q)})),delTables:Nn,delTable:Ko,delRow:Yo,delCell:(B,q,J,at)=>Vt(((ut,mt,At)=>Nt(ht(I,ut),(Pt=>Nt(ht(Pt,mt),(Mt=>$t(Mt,At)?ae(ut,Pt,mt,Mt,At,at):0))))),B,q,J),delValues:Bn,delValue:B=>Vt((q=>$t(N,q)?se(q):0),B),delTablesSchema:Jo,delValuesSchema:ia,delSchema:()=>Vt((()=>{Jo(),ia()})),transaction:sa,startTransaction:Qo,getTransactionChanges:()=>[be(o,((B,q)=>ht(c,q)===-1?void 0:be(B,((J,at)=>ht(ht(m,q),at)===-1?void 0:be(J,(([,ut])=>ut),(ut=>Vn(ut)))),vt,$e)),vt,$e),be(w,(([,B])=>B),(B=>Vn(B))),1],getTransactionLog:()=>[!vt(o),!vt(w),jn(o,ll,Vn),jn(S),be(w,ll,Vn),be(f),be(c),ba(m),jn(u),be(p)],finishTransaction:Zo,forEachTable:B=>yt(I,((q,J)=>B(J,(at=>yt(q,((ut,mt)=>at(mt,(At=>Xt(ut,At))))))))),forEachTableCell:(B,q)=>Xt(ht(_,Ot(B)),q),forEachRow:(B,q)=>yt(ht(I,Ot(B)),((J,at)=>q(at,(ut=>Xt(J,ut))))),forEachCell:(B,q,J)=>Xt(ht(ht(I,Ot(B)),Ot(q)),J),forEachValue:B=>Xt(N,B),addSortedRowIdsListener:(B,q,J,at,ut,mt,At)=>Kn(B)?Bo(B.tableId,B.cellId,[B.descending??!1,B.offset??0,B.limit],q,J):Bo(B,q,[J,at,ut],mt,At),addStartTransactionListener:B=>L(B,M),addWillFinishTransactionListener:B=>L(B,E[0]),addDidFinishTransactionListener:B=>L(B,E[1]),callListener:B=>(P(B),ce),delListener:B=>(U(B),ce),getListenerStats:()=>({hasTables:Wt(H),tables:Wt(j),tableIds:Wt(K),hasTable:Wt(it),table:Wt(ot),tableCellIds:Wt(X),hasTableCell:Wt(z,Ye),rowCount:Wt(W),rowIds:Wt(Y),sortedRowIds:Wt(et),hasRow:Wt(rt,Ye),row:Wt(ct,Ye),cellIds:Wt(st,Ye),hasCell:Wt(G,oa),cell:Wt(x,oa),invalidCell:Wt(T,oa),hasValues:Wt(g),values:Wt(y),valueIds:Wt(C),hasValue:Wt(k),value:Wt(O),invalidValue:Wt(R),transaction:Pi(M)+Wt(E)}),isMergeable:()=>!1,createStore:Di,addListener:L,callListeners:$,setInternalListeners:(B,q,J,at,ut)=>a=[B,q,J,at,ut]};return Ke({[_i+il]:[0,H,[],()=>[In()]],[il]:[0,j],[Ah]:[0,K],[_i+ui]:[1,it,[Ee],B=>[Ho(...B)]],[ui]:[1,ot,[Ee]],[ui+Wn]:[1,X,[Ee]],[_i+ui+Us]:[2,z,[Ee,Uo],B=>[jo(...B)]],[dl]:[1,W,[Ee]],[ul]:[1,Y,[Ee]],[_i+ls]:[2,rt,[Ee,es],B=>[zo(...B)]],[ls]:[2,ct,[Ee,es]],[Wn]:[2,st,[Ee,es]],[_i+Us]:[3,G,[Ee,es,Zr],B=>[Vo(...B)]],[Us]:[3,x,[Ee,es,Zr],B=>zn(Mn(...B))],InvalidCell:[3,T],[_i+sl]:[0,g,[],()=>[Ln()]],[sl]:[0,y],[Eh]:[0,C],[_i+Gn]:[1,k,[ea],B=>[Wo(...B)]],[Gn]:[1,O,[ea],B=>zn(Rn(B[0]))],InvalidValue:[1,R]},(([B,q,J,at],ut)=>{ce[da+ut+ha]=(...mt)=>L(mt[B],q[mt[B+1]?1:0],B>0?pa(mt,0,B):void 0,J,at)})),us(ce)};var va=ft([["avg",[(s,t)=>rl(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=>na(...s),(s,t)=>na(t,s),(s,t)=>t==s?void 0:s,(s,t,e)=>e==s?void 0:na(t,s)]],["min",[s=>ra(...s),(s,t)=>ra(t,s),(s,t)=>t==s?void 0:s,(s,t,e)=>e==s?void 0:ra(t,s)]],["sum",[s=>rl(s),(s,t)=>s+t,(s,t)=>s-t,(s,t,e)=>s-e+t]]]),Sl=(s,t,e,i,n,a=!1)=>{if(vt(e))return;let[c,l,d,m]=n;return a||=St(s),yt(i,(([u,o])=>{a||(s=St(u)?l?.(s,o,t++):St(o)?d?.(s,u,t--):m?.(s,o,u,t),a||=St(s))})),a?c(hs(e),ds(e)):s},sp=zs((s=>{let t=ft(),[e,i,n]=Vs((()=>v)),[a,c,l,d,m,u,o,,p,w,S,f]=Qn(s,gl,(r=>isNaN(r)||St(r)||r===!0||r===!1||r===""?void 0:1*r),e,i),v={setMetricDefinition:(r,h,b,A,D,_,I)=>{let N=Ue(b)?[b,D,_,I]:ht(va,b)??ht(va,"sum");return p(r,h,((H,j,K,it,ot,X)=>{let z=u(r),W=ds(it);X||=St(z),H();let Y=Sl(z,W,it,j,N,X);pl(Y)||(Y=void 0),Y!=z&&(o(r,Y),i(t,[r],Y,z))}),Yn(A,1)),v},delMetricDefinition:r=>(w(r),v),getStore:a,getMetricIds:c,forEachMetric:l,hasMetric:d,getTableId:m,getMetric:u,addMetricIdsListener:S,addMetricListener:(r,h)=>e(h,t,[r]),delListener:r=>(n(r),v),destroy:f,getListenerStats:()=>({metric:Pi(t)})};return us(v)})),np=zs((s=>{let t=s.createStore,e=t(),i=t(),n=ft(),{addListener:a,callListeners:c,delListener:l}=i,[d,m,u,o,p,,,w,,S,f,v,r,h]=Qn(s,(()=>!0),gl,a,c),b=(I,N,...H)=>ve(H,(j=>jt(Ut(Ut(n,N,ft),I,Kt),j))),A=I=>{Nt(ht(n,I),(N=>{Xt(N,((H,j)=>yt(j,(K=>H.delListener(K))))),os(N)})),ve([i,e],(N=>N.delTable(I)))},D=(I,N,H)=>b(N,I,N.addStartTransactionListener(H.startTransaction),N.addDidFinishTransactionListener((()=>H.finishTransaction()))),_={setQueryDefinition:(I,N,H)=>{w(I,N),A(I);let j=[],K=[[null,[N,null,null,[],ft()]]],it=[],ot=[],X=[];H({select:(st,G)=>{let x=Ue(st)?[_e(j)+"",st]:[St(G)?st:G,T=>T(st,G)];return ye(j,x),{as:T=>x[0]=T}},join:(st,G,x)=>{let T=St(x)||Ue(G)?null:G,R=St(T)?G:x,g=[st,[st,T,Ue(R)?R:y=>y(R),[],ft()]];return ye(K,g),{as:y=>g[0]=y}},where:(st,G,x)=>ye(it,Ue(st)?st:St(x)?T=>T(st)===G:T=>T(st,G)===x),group:(st,G,x,T,R)=>{let g=[st,[st,Ue(G)?[G,x,T,R]:ht(va,G)??[(y,C)=>C]]];return ye(ot,g),{as:y=>g[0]=y}},having:(st,G)=>ye(X,Ue(st)?st:x=>x(st)===G)});let z=ft(j);if(vt(z))return _;let W=ft(K);Xt(W,((st,[,G])=>Nt(ht(W,G),(({3:x})=>St(st)?0:ye(x,st)))));let Y=ft(ot),et=e;if(vt(Y)&&$s(X))et=i;else{D(I,et,i);let st=ft();Xt(Y,((R,[g,y])=>jt(Ut(st,g,Kt),[R,y])));let G=Kt();Xt(z,(R=>$t(st,R)?0:jt(G,R)));let x=ft(),T=(R,g,y,C)=>Nt(R,(([k,O,M,E])=>{Xt(g,((L,[$])=>{let U=Ut(k,L,ft),P=ht(U,y),F=C?void 0:$;if(P!==F){let V=Kt([[P,F]]),Q=ds(U);bt(U,y,F),yt(ht(st,L),(([Z,tt])=>{let nt=Sl(E[Z],Q,U,V,tt);E[Z]=St(as(nt))?null:nt}))}})),vt(O)||!qn(X,(L=>L(($=>E[$]))))?i.delRow(I,M):St(M)?R[2]=i.addRow(I,E):i.setRow(I,M,E)}));b(et,I,et.addRowListener(I,null,((R,g,y,C)=>{let k=[],O=[],M=ft(),E=et.hasRow(I,y),L=!E;yt(G,($=>{let[U,P,F]=C(I,y,$);ye(k,P),ye(O,F),L||=U})),Xt(st,($=>{let[U,,P]=C(I,y,$);(L||U)&&bt(M,$,[P])})),L&&T(Hs(x,k,void 0,(([,$])=>(He($,y),vt($)))),M,y,1),E&&T(Hs(x,O,(()=>{let $={};return yt(G,(U=>$[U]=et.getCell(I,y,U))),[ft(),Kt(),void 0,$]}),(([,$])=>{jt($,y)})),M,y)})))}D(I,s,et);let rt=(st,G,x,T)=>{let R=g=>s.getCell(G,x,g);ve(T,(g=>{let[y,,C,k,O]=ht(W,g),M=C?.(R,st),[E,L]=ht(O,st)??[];M!=E&&(St(L)||h(I,L),bt(O,st,St(M)?null:[M,...r(I,1,s.addRowListener(y,M,(()=>rt(st,y,M,k))))]))})),(g=>{let y=(C,k)=>s.getCell(...St(k)?[N,g,C]:C===N?[N,g,k]:[ht(W,C)?.[0],ht(ht(W,C)?.[4],g)?.[0],k]);et.transaction((()=>qn(it,(C=>C(y)))?Xt(z,((C,k)=>Xn(et,I,g,C,k(y,g)))):et.delRow(I,g)))})(st)},{3:ct}=ht(W,null);return et.transaction((()=>r(I,1,s.addRowListener(N,null,((st,G,x)=>{s.hasRow(N,x)?rt(x,N,x,ct):(et.delRow(I,x),yt(W,(({4:T})=>Nt(ht(T,x),(([,R])=>{h(I,R),bt(T,x)})))))}))))),_},delQueryDefinition:I=>(A(I),S(I),_),getStore:d,getQueryIds:m,forEachQuery:u,hasQuery:o,getTableId:p,addQueryIdsListener:I=>f((()=>I(_))),delListener:I=>(l(I),_),destroy:v,getListenerStats:()=>{let{tables:I,tableIds:N,transaction:H,...j}=i.getListenerStats();return j}};return Ke({[ui]:[1,1],[ui+Wn]:[0,1],[dl]:[0,1],[ul]:[0,1],[Sh]:[0,5],[ls]:[1,2],[Wn]:[0,2],[Us]:[1,3]},(([I,N],H)=>{ve(I?["get","has","forEach"]:["get"],(j=>_[j+el+H]=(...K)=>i[j+H](...K))),_[da+el+H+ha]=(...j)=>i[da+H+ha](...pa(j,0,N),((K,...it)=>j[N](_,...it)),!0)})),us(_)})),rp=zs((s=>{let t=ft(),e=ft(),i=ft(),n=ft(),[a,c,l]=Vs((()=>D)),[d,m,u,o,p,w,,,S,f,v,r]=Qn(s,(()=>[ft(),ft(),ft(),ft()]),(_=>St(_)?void 0:_+""),a,c),h=(_,I,N)=>Nt(w(_),(([H,,j])=>{if(!$t(j,I)){let K=Kt();if(p(_)!=A(_))jt(K,I);else{let it=I;for(;!St(it)&&!$t(K,it);)jt(K,it),it=ht(H,it)}if(N)return K;bt(j,I,K)}return ht(j,I)})),b=(_,I)=>Nt(w(_),(([,,N])=>bt(N,I))),A=_=>ht(t,_),D={setRelationshipDefinition:(_,I,N,H)=>(bt(t,_,N),S(_,I,((j,K)=>{let it=Kt(),ot=Kt(),X=Kt(),[z,W]=w(_);yt(K,(([Y,et],rt)=>{St(Y)||(jt(ot,Y),Nt(ht(W,Y),(ct=>{He(ct,rt),vt(ct)&&bt(W,Y)}))),St(et)||(jt(ot,et),$t(W,et)||bt(W,et,Kt()),jt(ht(W,et),rt)),jt(it,rt),bt(z,rt,et),Xt(ht(n,_),(ct=>{$t(h(_,ct),rt)&&jt(X,ct)}))})),j(),yt(it,(Y=>c(e,[_,Y]))),yt(ot,(Y=>c(i,[_,Y]))),yt(X,(Y=>{b(_,Y),c(n,[_,Y])}))}),Yn(H)),D),delRelationshipDefinition:_=>(bt(t,_),f(_),D),getStore:d,getRelationshipIds:m,forEachRelationship:_=>u((I=>_(I,(N=>s.forEachRow(p(I),N))))),hasRelationship:o,getLocalTableId:p,getRemoteTableId:A,getRemoteRowId:(_,I)=>ht(w(_)?.[0],I),getLocalRowIds:(_,I)=>hs(ht(w(_)?.[1],I)),getLinkedRowIds:(_,I)=>St(w(_))?[I]:hs(h(_,I,!0)),addRelationshipIdsListener:v,addRemoteRowIdListener:(_,I,N)=>a(N,e,[_,I]),addLocalRowIdsListener:(_,I,N)=>a(N,i,[_,I]),addLinkedRowIdsListener:(_,I,N)=>(h(_,I),a(N,n,[_,I])),delListener:_=>(b(...l(_)??[]),D),destroy:r,getListenerStats:()=>({remoteRowId:Ye(e),localRowIds:Ye(i),linkedRowIds:Ye(n)})};return us(D)}));var Cl=Promise,Fh=globalThis,El=Fh.window,Oh=1e3,Nh=(s,t,e)=>setInterval(s,t*Oh),Bh=clearInterval,je=s=>s==null,sr=(s,t,e)=>je(s)?e?.():t(s),Aa=s=>Array.isArray(s),Ri=s=>s.length,Uh=(s,t)=>s.test(t),kl=s=>new Cl(s),Tl=async s=>Cl.all(s),Pl=s=>{throw new Error(s)},Mi=async(s,t,e)=>{try{return await s()}catch(i){t?.(i)}},Sa=(s,t)=>s.forEach(t),Ws=(s,t)=>s.map(t),$h=(s,t)=>s.splice(0,t),nr=(s,...t)=>s.push(...t),Dl=s=>s.shift(),ps=Object,_l=s=>ps.getPrototypeOf(s),Hh=ps.entries,jh=s=>!je(s)&&sr(_l(s),t=>t==ps.prototype||je(_l(t)),()=>!0),zh=ps.keys,Vh=ps.freeze,Wh=(s=[])=>ps.fromEntries(s),Gh=(s,t)=>t in s,qh=(s,t)=>Ws(Hh(s),([e,i])=>t(i,e)),Xh=s=>Ri(zh(s)),Zn=s=>jh(s)&&Xh(s)==0,Kh=s=>s?.size??0,Yh=(s,t)=>s?.has(t)??!1,Ml=s=>je(s)||Kh(s)==0,Rl=(s,t)=>s?.forEach(t),Il=(s,t)=>s?.delete(t),Gs=s=>new Map(s),Re=(s,t)=>s?.get(t),Ii=(s,t,e)=>je(e)?(Il(s,t),s):s?.set(t,e),Ea=(s,t,e,i)=>(Yh(s,t)?i?.(Re(s,t)):Ii(s,t,e()),Re(s,t)),_a=(s,t,e,i,n=0)=>sr((e?Ea:Re)(s,t[n],n>Ri(t)-2?e:Gs),a=>{if(n>Ri(t)-2)return i?.(a)&&Ii(s,t[n]),a;let c=_a(a,t,e,i,n+1);return Ml(a)&&Ii(s,t[n]),c}),Jh=/^\d+$/,Qh=()=>{let s=[],t=0;return[e=>(e?Dl(s):null)??""+t++,e=>{Uh(Jh,e)&&Ri(s)<1e3&&nr(s,e)}]},Zh=s=>new Set(Aa(s)||je(s)?s:[s]),td=(s,t)=>s?.add(t),ed=(s,t=[""])=>{let e=[],i=(n,a)=>a==Ri(t)?nr(e,n):t[a]===null?Rl(n,c=>i(c,a+1)):Sa([t[a],null],c=>i(Re(n,c),a+1));return i(s,0),e},id=s=>{let t,[e,i]=Qh(),n=Gs();return[(a,c,l,d=[],m=()=>[])=>{t??=s();let u=e(1);return Ii(n,u,[a,c,l,d,m]),td(_a(c,l??[""],Zh),u),u},(a,c,...l)=>Sa(ed(a,c),d=>Rl(d,m=>Re(n,m)[0](t,...c??[],...l))),a=>sr(Re(n,a),([,c,l])=>(_a(c,l??[""],void 0,d=>(Il(d,a),Ml(d)?1:0)),Ii(n,a),i(a),l)),a=>sr(Re(n,a),([c,,l=[],d,m])=>{let u=(...o)=>{let p=Ri(o);p==Ri(l)?c(t,...o,...m(o)):je(l[p])?Sa(d[p]?.(...o)??[],w=>u(...o,w)):u(...o,l[p])};u()})]},tr=Gs(),er=Gs(),sd=(s=1,t,e)=>s!=1&&t.isMergeable()?[1,t.getMergeableContent,()=>t.getTransactionMergeableChanges(!e),([[i],[n]])=>!Zn(i)||!Zn(n),t.setDefaultContent]:s!=2?[0,t.getContent,t.getTransactionChanges,([i,n])=>!Zn(i)||!Zn(n),t.setContent]:Pl("Store type not supported by this Persister"),nd=(s,t,e,i,n,a,c,l={},d=0,m=[])=>{let u=0,o=0,p=0,w,S,f;Ea(tr,m,()=>0),Ea(er,m,()=>[]);let v=Gs(),[r,h,b,A,D]=sd(c,s,d),[_,I,N]=id(()=>g),H=y=>{y!=u&&(u=y,I(v,void 0,u))},j=async()=>{if(!Re(tr,m)){for(Ii(tr,m,1);!je(w=Dl(Re(er,m)));)await Mi(w,a);Ii(tr,m,0)}},K=y=>{(r&&Aa(y?.[0])?y?.[2]===1?s.applyMergeableChanges:s.setMergeableContent:y?.[2]===1?s.applyChanges:s.setContent)(y)},it=async y=>(u!=2&&(H(1),o++,await R(async()=>{await Mi(async()=>{let C=await t();Aa(C)?K(C):y?D(y):Pl(`Content is not an array: ${C}`)},()=>{y&&D(y)}),H(0)})),g),ot=async y=>(X(),await it(y),await Mi(async()=>S=await i(async(C,k)=>{k||C?u!=2&&(H(1),o++,K(k??C),H(0)):await it()}),a),g),X=async()=>(S&&(await Mi(()=>n(S),a),S=void 0),g),z=()=>!je(S),W=async y=>(u!=1&&(H(2),p++,await R(async()=>{await Mi(()=>e(h,y),a),H(0)})),g),Y=async()=>(et(),await W(),f=s.addDidFinishTransactionListener(()=>{let y=b();A(y)&&W(y)}),g),et=async()=>(f&&(s.delListener(f),f=void 0),g),rt=()=>!je(f),ct=async(y,C=!1)=>{let[k,O]=C?[Y,ot]:[ot,Y];return await k(y),await O(y),g},st=async(y=!1)=>{let[C,k]=y?[et,X]:[X,et];return await C(),await k(),g},G=()=>u,x=y=>_(y,v),T=y=>(N(y),s),R=async(...y)=>(nr(Re(er,m),...y),await j(),g),g={load:it,startAutoLoad:ot,stopAutoLoad:X,isAutoLoading:z,save:W,startAutoSave:Y,stopAutoSave:et,isAutoSaving:rt,startAutoPersisting:ct,stopAutoPersisting:st,getStatus:G,addStatusListener:x,delListener:T,schedule:R,getStore:()=>s,destroy:()=>($h(Re(er,m)),st()),getStats:()=>({loads:o,saves:p}),...l};return Vh(g)},xa=["t","v"],rd={keyPath:"k"},ad=async(s,t)=>{let e=qh(t,(i,n)=>ir(s,"put",{k:n,v:i}));Ws(await ir(s,"getAllKeys"),i=>Gh(t,i)?0:nr(e,ir(s,"delete",i))),await Tl(e)},ir=async(s,t,e)=>kl((i,n)=>{let a=s[t](e);a.onsuccess=()=>i(a.result),a.onerror=()=>n(`objectStore.${t} error`)}),rr=(s,t,e=1,i)=>{let n=async(a,c=[],l=0)=>kl((d,m)=>{let u=(El?El.indexedDB:indexedDB).open(t,l?2:void 0);u.onupgradeneeded=()=>l&&Ws(xa,o=>Mi(()=>u.result.createObjectStore(o,rd))),u.onsuccess=()=>Mi(async()=>{let o=u.result.transaction(xa,"readwrite"),p=await Tl(Ws(xa,(w,S)=>a(o.objectStore(w),c[S])));u.result.close(),d(p)},o=>{u.result.close(),m(o)}),u.onerror=()=>m("indexedDB.open error")});return nd(s,async()=>await n(async a=>Wh(Ws(await ir(a,"getAll"),({k:c,v:l})=>[c,l]))),a=>n((c,l)=>ad(c,l),a(),1),a=>Nh(a,e),a=>Bh(a),i,1,{getDbName:()=>t})};var fs=Di();fs.setTable("docs",{});var ar=rr(fs,"copio-db");ar.startAutoLoad();ar.startAutoSave();var or=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,a)=>{let d=i.transaction(this.#e,"readwrite").objectStore(this.#e).put(e,t);d.onsuccess=()=>n(),d.onerror=()=>a(d.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=d=>{let m=d.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((a,c)=>{let d=i.transaction(this.#e,"readwrite").objectStore(this.#e),m=d.openKeyCursor();m.onsuccess=u=>{let o=u.target.result;if(o){if(typeof o.key=="string"){let p=o.key.split(":")[0];e.has(p)||(d.delete(o.key),n++)}o.continue()}else a(n)},m.onerror=()=>c(m.error)})}async close(){if(this.#i){try{(await this.#i).close()}catch{}this.#i=null}}};function Li(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],a=atob(n),c=new Uint8Array(a.length);for(let l=0;l<a.length;l++)c[l]=a.charCodeAt(l);return new Blob([c],{type:i})}async function Ca(s){return new Promise((t,e)=>{let i=new FileReader;i.onloadend=()=>t(i.result),i.onerror=e,i.readAsDataURL(s)})}var gi=class extends Xe{#t=null;#e=null;#i=null;#n="copio-db";#r=!1;#s=new Set;#o=new Map;#l=new Map;#a=new Map;#h=new Map;#u=null;constructor(t={}){super(),t.dbName&&t.dbName!=="copio-db"?(this.#n=t.dbName,this.#t=t.store||Di(),this.#t.setTable("docs",{}),this.#e=t.persister||rr(this.#t,this.#n),this.#r=!0):(this.#t=t.store||fs,this.#e=t.persister||ar,this.#n="copio-db"),this.#i=new or(`${this.#n}-blobs`)}get store(){return this.#t}get persister(){return this.#e}get blobStore(){return this.#i}#d(t,e){return typeof e=="string"&&e.startsWith("blob:")&&(this.#s.add(e),this.#o.has(t)||this.#o.set(t,[]),this.#o.get(t).push(e)),e}revokeDocUrls(t){let e=this.#o.get(t);if(e){for(let i of e){try{URL.revokeObjectURL(i)}catch{}this.#s.delete(i)}this.#o.delete(t)}for(let[i,n]of this.#l.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(n)}catch{}this.#l.delete(i)}for(let[i,n]of this.#a.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(n)}catch{}this.#a.delete(i)}this.#h.delete(t)}revokeAllUrls(){for(let t of this.#s)try{URL.revokeObjectURL(t)}catch{}this.#s.clear(),this.#o.clear(),this.#l.clear(),this.#a.clear(),this.#h.clear()}async init(){return this.#u?this.#u:(this.#u=(async()=>{this.#r?(await this.#e.load(),this.#e.startAutoLoad(),this.#e.startAutoSave()):await this.#e.load(),await this.sweepOrphans();let t=!0;if(typeof navigator<"u"&&navigator.storage&&navigator.storage.persisted)try{t=await navigator.storage.persisted()}catch{}return{kind:"indexeddb",persistent:t}})(),this.#u)}async sweepOrphans(){let t=Object.keys(this.#t.getTable("docs")||{});return this.#i.sweepOrphans(t)}listDocsSync(){let t=this.#t.getTable("docs");return Object.entries(t||{}).map(([e,i])=>({id:e,name:i.name||"",pages:this.#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},d=`${t}:${c.id}`,m=await this.#i.get(`${t}:${c.id}`);m&&(l.blob=m,this.#l.has(d)?l.src=this.#l.get(d):(l.src=this.#d(t,URL.createObjectURL(m)),this.#l.set(d,l.src)));let u=`${t}:${c.id}:orig`,o=await this.#i.get(`${t}:${c.id}:original`);return o?(l.originalBlob=o,this.#a.has(u)?l.originalSrc=this.#a.get(u):(l.originalSrc=this.#d(t,URL.createObjectURL(o)),this.#a.set(u,l.originalSrc))):l.blob&&(l.originalBlob=l.blob,l.originalSrc=l.src),l})),a={id:t,name:e.name||"",pages:n};return this.#h.set(t,a),a}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=[],a=[],c=[];for(let l of i){if(!l)continue;let d=Li(l.src)||(l.src instanceof Blob?l.src:null)||(l.blob instanceof Blob?l.blob:null),m=d?.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 o=`${t}:${l.id}`,p=`${t}:${l.id}:orig`,w={...l},S=this.#l.get(o),f=typeof l.src=="string"&&l.src.startsWith("data:")||l.src instanceof Blob||l.src&&S&&l.src!==S;if(d)if(w.blob=d,f||!S){if(S){try{URL.revokeObjectURL(S)}catch{}this.#s.delete(S)}let A=this.#d(t,URL.createObjectURL(d));this.#l.set(o,A),w.src=A}else w.src=S;let v=Li(l.originalSrc)||(l.originalSrc instanceof Blob?l.originalSrc:null)||(l.originalBlob instanceof Blob?l.originalBlob:null),r=this.#a.get(p),h=!r&&!v&&(!l.originalSrc||l.originalSrc===l.src);h&&d&&(v=d);let b=typeof l.originalSrc=="string"&&l.originalSrc.startsWith("data:")||l.originalSrc instanceof Blob||h&&!!v;if(v)if(w.originalBlob=v,b||!r){if(r&&b){try{URL.revokeObjectURL(r)}catch{}this.#s.delete(r)}let A=this.#d(t,URL.createObjectURL(v));this.#a.set(p,A),w.originalSrc=A}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));a.push(w),c.push({pageId:l.id,page:l,srcBlob:d,origBlob:v})}this.#t.setRow("docs",t,{name:e.name||"",pages:JSON.stringify(n)}),this.#h.set(t,{id:t,name:e.name||"",pages:a});for(let l of c){let{pageId:d,page:m,srcBlob:u,origBlob:o}=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}:${d}`,u),!o&&typeof m.originalSrc=="string"&&m.originalSrc.startsWith("blob:"))try{o=await(await fetch(m.originalSrc)).blob()}catch{}o&&await this.#i.put(`${t}:${d}:original`,o)}}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 a=n.pages.findIndex(d=>d.id===e),c;if(a>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?n.pages[a]={...n.pages[a],...i}:n.pages[a]={...n.pages[a],src:i,blob:i instanceof Blob?i:void 0},c=n.pages[a];else{let d=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(d),c=d}let l=Li(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 a=n.pages.find(c=>c.id===e);return a?a.content??a.src??a: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 a=`${t}:${e}:orig`;if(this.#a.has(a)){try{URL.revokeObjectURL(this.#a.get(a))}catch{}this.#a.delete(a)}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 Fl(){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 od(s,t,e="store.json"){let i=0,n=null,a=Promise.resolve(),c=0,l=()=>typeof t=="function"?t():t,d=async()=>{await a;let p=l();if(p){i=1;try{let f=await(await(await p.getFileHandle(e)).getFile()).text();f&&f.trim().length>0&&s.setJson(f)}catch{}finally{i=0}}},m=()=>{let p=l();return p?(c++,i=2,a=a.catch(()=>{}).then(async()=>{try{let w=s.getJson(),f=await(await p.getFileHandle(e,{create:!0})).createWritable();await f.write(w),await f.close()}catch(w){console.warn("[OpfsPersister] Failed to save store.json:",w)}finally{c--,c<=0&&(c=0,i=0)}}),a):Promise.resolve()};return{load:d,save:m,startAutoSave:()=>{n||(n=s.addDidFinishTransactionListener(()=>{m()}))},stopAutoSave:()=>{n&&(s.delListener(n),n=null)},getStatus:()=>i,getStore:()=>s}}async function Ll(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 qs=class extends Xe{#t;#e="copio";#i=null;#n=null;#r=null;#s=null;#o=null;#l=!1;#a=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=Di(),this.#s.setTable("docs",{})):this.#s=fs,this.#o=t.persister||od(this.#s,()=>this.#n,"store.json")}get store(){return this.#l?this.#a?.store:this.#s}get persister(){return this.#l?this.#a?.persister:this.#o}get isFallback(){return this.#l}get fallbackAdapter(){return this.#a}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.#a?.revokeDocUrls(t);return}let e=this.#u.get(t);if(e){for(let i of e){try{URL.revokeObjectURL(i)}catch{}this.#h.delete(i)}this.#u.delete(t)}for(let[i,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.#a?.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 Fl())return this.#m();try{await this.#p(),await this.#o.load(),this.#o.startAutoSave(),await this.sweepOrphans();let e=!1;if(typeof navigator<"u"&&navigator.storage&&navigator.storage.persisted)try{e=await navigator.storage.persisted()}catch{}return{kind:"opfs",persistent:e}}catch(e){return console.warn("[OpfsAdapter] OPFS initialization failed, switching to IndexedDB fallback:",e),this.#m()}})(),this.#g)}async#m(){return this.#l=!0,this.#a=new gi(this.#t),{kind:"indexeddb",persistent:(await this.#a.init()).persistent}}async sweepOrphans(){if(this.#l)return this.#a?.sweepOrphans();if(await this.#p(),!this.#r)return 0;let t=0,e=this.#s.getTable("docs")||{},i=new Set(Object.keys(e)),n=new Map;for(let[c,l]of Object.entries(e)){let d=this.#b(l.pages);n.set(c,new Set(d.map(m=>m.id)))}let a=await Ll(this.#r);for(let[c,l]of a)if(l.kind==="directory")if(i.has(c)){let d=n.get(c)||new Set,m=l,u=await Ll(m);for(let[o]of u){let p=o.replace(/-original\.bin$/,"").replace(/\.bin$/,"");if(!d.has(p))try{await m.removeEntry(o),t++}catch{}}}else try{await this.#r.removeEntry(c,{recursive:!0}),t++}catch{}return t}listDocsSync(){if(this.#l)return this.#a?.listDocsSync();let t=this.#s.getTable("docs");return Object.entries(t||{}).map(([e,i])=>({id:e,name:i.name||"",pages:this.#b(i.pages)}))}async listDocs(){return this.#l?this.#a?.listDocs():this.listDocsSync()}getDocSync(t){if(this.#l)return this.#a?.getDocSync(t);if(this.#f.has(t))return this.#f.get(t);if(!this.#s.hasRow("docs",t))return null;let e=this.#s.getRow("docs",t);return{id:t,name:e.name||"",pages:this.#b(e.pages)}}async getDoc(t){if(this.#l)return this.#a?.getDoc(t);if(await this.#p(),!this.#s.hasRow("docs",t))return null;let e=this.#s.getRow("docs",t),i=this.#b(e.pages),n=null;if(this.#r)try{n=await this.#r.getDirectoryHandle(t)}catch{}let a=await Promise.all(i.map(async l=>{if(!l||!n)return l;let d={...l},m=`${t}:${l.id}`;try{let p=await(await n.getFileHandle(`${l.id}.bin`)).getFile();d.blob=p,this.#d.has(m)?d.src=this.#d.get(m):(d.src=this.#y(t,URL.createObjectURL(p)),this.#d.set(m,d.src))}catch{}let u=`${t}:${l.id}:orig`;try{let p=await(await n.getFileHandle(`${l.id}-original.bin`)).getFile();d.originalBlob=p,this.#c.has(u)?d.originalSrc=this.#c.get(u):(d.originalSrc=this.#y(t,URL.createObjectURL(p)),this.#c.set(u,d.originalSrc))}catch{d.blob&&(d.originalBlob=d.blob,d.originalSrc=d.src)}return d})),c={id:t,name:e.name||"",pages:a};return this.#f.set(t,c),c}async saveDoc(t,e){if(this.#l)return this.#a?.saveDoc(t,e);if(!t)throw new Error("Cannot save document without an ID");let i=Array.isArray(e.pages)?e.pages:this.#b(e.pages),n=[],a=[],c=[];for(let d of i){if(!d)continue;let m=Li(d.src)||(d.src instanceof Blob?d.src:null)||(d.blob instanceof Blob?d.blob:null),u=m?.type||"image/jpeg",o={id:d.id,name:d.name||"",type:d.type||"image",hasBlob:!0,mimeType:u,edits:d.edits,exif:d.exif,content:d.content,ocrText:d.ocrText??null,ocrConfidence:d.ocrConfidence??null,ocrWords:Array.isArray(d.ocrWords)?d.ocrWords:null,ocrWidth:d.ocrWidth??null,ocrHeight:d.ocrHeight??null};n.push(o);let p=`${t}:${d.id}`,w=`${t}:${d.id}:orig`,S={...d},f=this.#d.get(p),v=typeof d.src=="string"&&d.src.startsWith("data:")||d.src instanceof Blob||d.src&&f&&d.src!==f;if(m)if(S.blob=m,v||!f){if(f){try{URL.revokeObjectURL(f)}catch{}this.#h.delete(f)}let D=this.#y(t,URL.createObjectURL(m));this.#d.set(p,D),S.src=D}else S.src=f;let r=Li(d.originalSrc)||(d.originalSrc instanceof Blob?d.originalSrc:null)||(d.originalBlob instanceof Blob?d.originalBlob:null),h=this.#c.get(w),b=!h&&!r&&(!d.originalSrc||d.originalSrc===d.src);b&&m&&(r=m);let A=typeof d.originalSrc=="string"&&d.originalSrc.startsWith("data:")||d.originalSrc instanceof Blob||b&&!!r;if(r)if(S.originalBlob=r,A||!h){if(h&&A){try{URL.revokeObjectURL(h)}catch{}this.#h.delete(h)}let D=this.#y(t,URL.createObjectURL(r));this.#c.set(w,D),S.originalSrc=D}else S.originalSrc=h;else h?S.originalSrc=h:d.originalSrc?S.originalSrc=d.originalSrc:(S.originalSrc=S.src,S.blob&&(S.originalBlob=S.blob));a.push(S),c.push({pageId:d.id,page:d,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:a}),await this.#p(),this.#l)return this.#a?.saveDoc(t,e);let l=null;if(this.#r)try{l=await this.#r.getDirectoryHandle(t,{create:!0})}catch(d){console.warn(`[OpfsAdapter] Failed to get doc directory "${t}":`,d)}if(l)for(let d of c){let{pageId:m,page:u,srcBlob:o,origBlob:p}=d;if(!o&&typeof u.src=="string"&&u.src.startsWith("blob:"))try{o=await(await fetch(u.src)).blob()}catch{}if(o)try{let S=await(await l.getFileHandle(`${m}.bin`,{create:!0})).createWritable();await S.write(o),await S.close()}catch(w){console.warn(`[OpfsAdapter] Failed writing page file "${m}.bin":`,w)}if(!p&&typeof u.originalSrc=="string"&&u.originalSrc.startsWith("blob:"))try{p=await(await fetch(u.originalSrc)).blob()}catch{}if(p)try{let S=await(await l.getFileHandle(`${m}-original.bin`,{create:!0})).createWritable();await S.write(p),await S.close()}catch{}}}async deleteDoc(t){if(this.#l)return this.#a?.deleteDoc(t);if(this.#s.delRow("docs",t),this.#f.delete(t),this.revokeDocUrls(t),await this.#p(),this.#r)try{await this.#r.removeEntry(t,{recursive:!0})}catch{}}async renameDoc(t,e){if(this.#l)return this.#a?.renameDoc(t,e);if(!this.#s.hasRow("docs",t))throw new Error(`Document "${t}" not found`);this.#s.setCell("docs",t,"name",e),this.#f.has(t)&&(this.#f.get(t).name=e)}async savePage(t,e,i){if(this.#l)return this.#a?.savePage(t,e,i);await this.#p();let n=await this.getDoc(t);if(!n)throw new Error(`Document ${t} not found`);let a=n.pages.findIndex(d=>d.id===e),c;if(a>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?n.pages[a]={...n.pages[a],...i}:n.pages[a]={...n.pages[a],src:i,blob:i instanceof Blob?i:void 0},c=n.pages[a];else{let d=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(d),c=d}let l=Li(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(d){console.warn(`[OpfsAdapter] Failed writing page file "${e}.bin":`,d)}await this.saveDoc(t,n)}async getPage(t,e){if(this.#l)return this.#a?.getPage(t,e);if(await this.#p(),this.#r)try{return await(await(await this.#r.getDirectoryHandle(t)).getFileHandle(`${e}.bin`)).getFile()}catch{}let i=this.getDocSync(t);if(!i)return null;let n=i.pages.find(a=>a.id===e);return n?n.content??n.src??n:null}async deletePage(t,e){if(this.#l)return this.#a?.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 a=`${t}:${e}:orig`;if(this.#c.has(a)){try{URL.revokeObjectURL(this.#c.get(a))}catch{}this.#c.delete(a)}this.#f.delete(t)}subscribe(t){if(this.#l)return this.#a?.subscribe(t);let e=this.#s.addTableListener("docs",t);return()=>{this.#s.delListener(e)}}#b(t){if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}};function lr(s={}){return s.forceMemory?new ns:s.forceIndexedDb?new gi(s):s.forceOpfs?new qs(s):typeof navigator<"u"&&navigator.storage&&typeof navigator.storage.getDirectory=="function"?new qs(s):typeof indexedDB<"u"?new gi(s):new ns}function Ft(s,t,e){return t in s?Object.defineProperty(s,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):s[t]=e,s}var $a=typeof self<"u"?self:global,Qs=typeof navigator<"u",ld=Qs&&typeof HTMLImageElement>"u",Ol=!(typeof global>"u"||typeof process>"u"||!process.versions||!process.versions.node),Ha=$a.Buffer,cr=$a.BigInt,ja=!!Ha,hr=s=>Xl(s)?void 0:s,cd=s=>s!==void 0;function Xl(s){return s===void 0||(s instanceof Map?s.size===0:Object.values(s).filter(cd).length===0)}function ee(s){let t=new Error(s);throw delete t.stack,t}function Kl(s){return(s=(function(t){for(;t.endsWith("\0");)t=t.slice(0,-1);return t})(s).trim())===""?void 0:s}function Nl(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 Da=s=>String.fromCharCode.apply(null,s),Bl=typeof TextDecoder<"u"?new TextDecoder("utf-8"):void 0;function Yl(s){return Bl?Bl.decode(s):ja?Buffer.from(s).toString("utf8"):decodeURIComponent(escape(Da(s)))}var Ze=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 a=new DataView(t,e,i);this._swapDataView(a)}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&&ee("Creating view outside of available memory in ArrayBuffer");let a=new DataView(t.buffer,e,i);this._swapDataView(a)}else if(typeof t=="number"){let a=new DataView(new ArrayBuffer(t));this._swapDataView(a)}else ee("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||ee("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 Yl(this.getUint8Array(t,e))}getLatin1String(t=0,e=this.byteLength){let i=this.getUint8Array(t,e);return Da(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 Da(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 Ma(s,t){ee(`${s} '${t}' was not loaded, try using full build of exifr.`)}var Zs=class extends Map{constructor(t){super(),this.kind=t}get(t,e){return this.has(t)||Ma(this.kind,t),e&&(t in e||(function(i,n){ee(`Unknown ${i} '${n}'.`)})(this.kind,t),e[t].enabled||Ma(this.kind,t)),super.get(t)}keyList(){return Array.from(this.keys())}},Hi=new Zs("file parser"),ge=new Zs("segment parser"),ji=new Zs("file reader"),Jl=$a.fetch;function Ul(s,t){return(e=s).startsWith("data:")||e.length>1e4?Ia(s,t,"base64"):Ol&&s.includes("://")?Ra(s,t,"url",bs):Ol?Ia(s,t,"fs"):Qs?Ra(s,t,"url",bs):void ee("Invalid input argument");var e}async function Ra(s,t,e,i){return ji.has(e)?Ia(s,t,e):i?(async function(n,a){let c=await a(n);return new Ze(c)})(s,i):void ee(`Parser ${e} is not loaded`)}async function Ia(s,t,e){let i=new(ji.get(e))(s,t);return await i.read(),i}var bs=s=>Jl(s).then((t=>t.arrayBuffer())),ys=s=>new Promise(((t,e)=>{let i=new FileReader;i.onloadend=()=>t(i.result||new ArrayBuffer),i.onerror=e,i.readAsArrayBuffer(s)})),La=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 Ie(s,t,e){let i=new La;for(let[n,a]of e)i.set(n,a);if(Array.isArray(t))for(let n of t)s.set(n,i);else s.set(t,i);return i}function za(s,t,e){let i,n=s.get(t);for(i of e)n.set(i[0],i[1])}var Qe=new Map,ws=new Map,$i=new Map,Oi=["chunked","firstChunkSize","firstChunkSizeNode","firstChunkSizeBrowser","chunkSize","chunkLimit"],tn=["jfif","xmp","icc","iptc","ihdr"],vs=["tiff",...tn],Jt=["ifd0","ifd1","exif","gps","interop"],Ni=[...vs,...Jt],Bi=["makerNote","userComment"],en=["translateKeys","translateValues","reviveValues","multiSegment"],Ui=[...en,"sanitize","mergeOutput","silentErrors"],dr=class{get translate(){return this.translateKeys||this.translateValues||this.reviveValues}},Fi=class extends dr{get needed(){return this.enabled||this.deps.size>0}constructor(t,e,i,n){if(super(),Ft(this,"enabled",!1),Ft(this,"skip",new Set),Ft(this,"pick",new Set),Ft(this,"deps",new Set),Ft(this,"translateKeys",!1),Ft(this,"translateValues",!1),Ft(this,"reviveValues",!1),this.key=t,this.enabled=e,this.parse=this.enabled,this.applyInheritables(n),this.canBeFiltered=Jt.includes(t),this.canBeFiltered&&(this.dict=Qe.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:a,skip:c}=i;a&&a.length>0&&this.translateTagSet(a,this.pick),c&&c.length>0&&this.translateTagSet(c,this.skip)}this.applyInheritables(i)}else i===!0||i===!1?this.parse=this.enabled=i:ee(`Invalid options argument: ${i}`)}applyInheritables(t){let e,i;for(e of en)i=t[e],i!==void 0&&(this[e]=i)}translateTagSet(t,e){if(this.dict){let i,n,{tagKeys:a,tagValues:c}=this.dict;for(i of t)typeof i=="string"?(n=c.indexOf(i),n===-1&&(n=a.indexOf(Number(i))),n!==-1&&e.add(Number(a[n]))):e.add(i)}else for(let i of t)e.add(i)}finalizeFilters(){!this.enabled&&this.deps.size>0?(this.enabled=!0,ur(this.pick,this.deps)):this.enabled&&this.pick.size>0&&ur(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},$l=new Map,mi=class extends dr{static useCached(t){let e=$l.get(t);return e!==void 0||(e=new this(t),$l.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):ee(`Invalid options argument ${t}`),this.firstChunkSize===void 0&&(this.firstChunkSize=Qs?this.firstChunkSizeBrowser:this.firstChunkSizeNode),this.mergeOutput&&(this.ifd1.enabled=!1),this.filterNestedSegmentTags(),this.traverseTiffDependencyTree(),this.checkLoadedPlugins()}setupFromUndefined(){let t;for(t of Oi)this[t]=fe[t];for(t of Ui)this[t]=fe[t];for(t of Bi)this[t]=fe[t];for(t of Ni)this[t]=new Fi(t,fe[t],void 0,this)}setupFromTrue(){let t;for(t of Oi)this[t]=fe[t];for(t of Ui)this[t]=fe[t];for(t of Bi)this[t]=!0;for(t of Ni)this[t]=new Fi(t,!0,void 0,this)}setupFromArray(t){let e;for(e of Oi)this[e]=fe[e];for(e of Ui)this[e]=fe[e];for(e of Bi)this[e]=fe[e];for(e of Ni)this[e]=new Fi(e,!1,void 0,this);this.setupGlobalFilters(t,void 0,Jt)}setupFromObject(t){let e;for(e of(Jt.ifd0=Jt.ifd0||Jt.image,Jt.ifd1=Jt.ifd1||Jt.thumbnail,Object.assign(this,t),Oi))this[e]=ka(t[e],fe[e]);for(e of Ui)this[e]=ka(t[e],fe[e]);for(e of Bi)this[e]=ka(t[e],fe[e]);for(e of vs)this[e]=new Fi(e,fe[e],t[e],this);for(e of Jt)this[e]=new Fi(e,fe[e],t[e],this.tiff);this.setupGlobalFilters(t.pick,t.skip,Jt,Ni),t.tiff===!0?this.batchEnableWithBool(Jt,!0):t.tiff===!1?this.batchEnableWithUserValue(Jt,t):Array.isArray(t.tiff)?this.setupGlobalFilters(t.tiff,void 0,Jt):typeof t.tiff=="object"&&this.setupGlobalFilters(t.tiff.pick,t.tiff.skip,Jt)}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 a=Hl(t,i);for(let[c,l]of a)ur(this[c].pick,l),this[c].enabled=!0}else if(e&&e.length){let a=Hl(e,i);for(let[c,l]of a)ur(this[c].skip,l)}}filterNestedSegmentTags(){let{ifd0:t,exif:e,xmp:i,iptc:n,icc:a}=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),a.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=Jt.some((a=>this[a].enabled===!0))||this.makerNote||this.userComment;for(let a of Jt)this[a].finalizeFilters()}get onlyTiff(){return!tn.map((t=>this[t].enabled)).some((t=>t===!0))&&this.tiff.enabled}checkLoadedPlugins(){for(let t of vs)this[t].enabled&&!ge.has(t)&&Ma("segment parser",t)}};function Hl(s,t){let e,i,n,a,c=[];for(n of t){for(a of(e=Qe.get(n),i=[],e))(s.includes(a[0])||s.includes(a[1]))&&i.push(a[0]);i.length&&c.push([n,i])}return c}function ka(s,t){return s!==void 0?s:t!==void 0?t:void 0}function ur(s,t){for(let e of t)s.add(e)}Ft(mi,"default",fe);var ti=class{constructor(t){Ft(this,"parsers",{}),Ft(this,"output",{}),Ft(this,"errors",[]),Ft(this,"pushToErrors",(e=>this.errors.push(e))),this.options=mi.useCached(t)}async read(t){this.file=await(function(e,i){return typeof e=="string"?Ul(e,i):Qs&&!ld&&e instanceof HTMLImageElement?Ul(e.src,i):e instanceof Uint8Array||e instanceof ArrayBuffer||e instanceof DataView?new Ze(e):Qs&&e instanceof Blob?Ra(e,i,"blob",ys):void ee("Invalid input argument")})(t,this.options)}setup(){if(this.fileParser)return;let{file:t}=this,e=t.getUint16(0);for(let[i,n]of Hi)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(),ee("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),hr(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 a=await this.fileParser.ensureSegmentChunk(n),c=this.parsers.tiff=new i(a,t,e),l=await c.extractThumbnail();return e.close&&e.close(),l}};async function Va(s,t){let e=new ti(t);return await e.read(s),e.parse()}var hd=Object.freeze({__proto__:null,parse:Va,Exifr:ti,fileParsers:Hi,segmentParsers:ge,fileReaders:ji,tagKeys:Qe,tagValues:ws,tagRevivers:$i,createDictionary:Ie,extendDictionary:za,fetchUrlAsArrayBuffer:bs,readBlobAsArrayBuffer:ys,chunkedProps:Oi,otherSegments:tn,segments:vs,tiffBlocks:Jt,segmentsAndBlocks:Ni,tiffExtractables:Bi,inheritables:en,allFormatters:Ui,Options:mi}),pr=class{constructor(t,e,i){Ft(this,"errors",[]),Ft(this,"ensureSegmentChunk",(async n=>{let a=n.start,c=n.size||65536;if(this.file.chunked)if(this.file.available(a,c))n.chunk=this.file.subarray(a,c);else try{n.chunk=await this.file.readChunk(a,c)}catch(l){ee(`Couldn't read segment: ${JSON.stringify(n)}. ${l.message}`)}else this.file.byteLength>a+c?n.chunk=this.file.subarray(a,c):n.size===void 0?n.chunk=this.file.subarray(a):ee("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,a=this.options[i];if(a&&a.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)}},Je=class{static findPosition(t,e){let i=t.getUint16(e+2)+2,n=typeof this.headerLength=="function"?this.headerLength(t,e,i):this.headerLength,a=e+n,c=i-n;return{offset:e,length:i,headerLength:n,start:a,size:c,end:a+c}}static parse(t,e={}){return new this(t,new mi({[this.type]:e}),t).parse()}normalizeInput(t){return t instanceof Ze?t:new Ze(t)}constructor(t,e={},i){Ft(this,"errors",[]),Ft(this,"raw",new Map),Ft(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=$i.get(e),n=ws.get(e),a=Qe.get(e),c=this.options[e],l=c.reviveValues&&!!i,d=c.translateValues&&!!n,m=c.translateKeys&&!!a,u={};for(let[o,p]of t)l&&i.has(o)?p=i.get(o)(p):d&&n.has(o)&&(p=this.translateValue(p,n.get(o))),m&&a.has(o)&&(o=a.get(o)||o),u[o]=p;return u}translateValue(t,e){return e[t]||e.DEFAULT||t}assignToOutput(t,e){this.assignObjectToOutput(t,this.constructor.type,e)}assignObjectToOutput(t,e,i){if(this.globalOptions.mergeOutput)return Object.assign(t,i);t[e]?Object.assign(t[e],i):t[e]=i}};Ft(Je,"headerLength",4),Ft(Je,"type",void 0),Ft(Je,"multiSegment",!1),Ft(Je,"canHandle",(()=>!1));function dd(s){return s===192||s===194||s===196||s===219||s===221||s===218||s===254}function ud(s){return s>=224&&s<=239}function pd(s,t,e){for(let[i,n]of ge)if(n.canHandle(s,t,e))return i}var fr=class extends pr{constructor(...t){super(...t),Ft(this,"appSegments",[]),Ft(this,"jpegSegments",[]),Ft(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:a,remaining:c}=this;if(!n&&this.file.chunked&&(n=Array.from(a).some((l=>{let d=ge.get(l),m=this.options[l];return d.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:d}=i,m=this.appSegments.some((u=>!this.file.available(u.offset||u.start,u.length||u.size)));if(l=t>d&&!m?!await i.readNextChunk(t):!await i.readNextChunk(d),(t=this.findAppSegmentsInRange(t,i.byteLength))===void 0)return}}}findAppSegmentsInRange(t,e){e-=2;let i,n,a,c,l,d,{file:m,findAll:u,wanted:o,remaining:p,options:w}=this;for(;t<e;t++)if(m.getUint8(t)===255){if(i=m.getUint8(t+1),ud(i)){if(n=m.getUint16(t+2),a=pd(m,t,n),a&&o.has(a)&&(c=ge.get(a),l=c.findPosition(m,t),d=w[a],l.type=a,this.appSegments.push(l),!u&&(c.multiSegment&&d.multiSegment?(this.unfinishedMultiSegment=l.chunkNumber<l.chunkCount,this.unfinishedMultiSegment||p.delete(a)):p.delete(a),p.size===0)))break;w.recordUnknownSegments&&(l=Je.findPosition(m,t),l.marker=i,this.unknownSegments.push(l)),t+=n+1}else if(dd(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,a,c,l=new Map;for(let d=0;d<e.length;d++)n=e[d],a=n[i],l.has(a)?c=l.get(a):l.set(a,c=[]),c.push(n);return Array.from(l)})(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}};Ft(fr,"type","jpeg"),Hi.set("jpeg",fr);var fd=[void 0,1,1,2,4,8,1,1,2,4,8,4,8,4],Fa=class extends Je{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:a}=this.options[e];n=new Set(n);let c=n.size>0,l=a.size===0,d=this.chunk.getUint16(t);t+=2;for(let m=0;m<d;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&&a.has(u)||i.set(u,this.parseTag(t,u,e));t+=12}return i}parseTag(t,e,i){let{chunk:n}=this,a=n.getUint16(t+2),c=n.getUint32(t+4),l=fd[a];if(l*c<=4?t+=8:t=n.getUint32(t+8),(a<1||a>13)&&ee(`Invalid TIFF value type. block: ${i.toUpperCase()}, tag: ${e.toString(16)}, type: ${a}, offset ${t}`),t>n.byteLength&&ee(`Invalid TIFF value offset. block: ${i.toUpperCase()}, tag: ${e.toString(16)}, type: ${a}, offset ${t} is outside of chunk size ${n.byteLength}`),a===1)return n.getUint8Array(t,c);if(a===2)return Kl(n.getString(t,c));if(a===7)return n.getUint8Array(t,c);if(c===1)return this.parseTagValue(a,t);{let d=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}})(a))(c),m=l;for(let u=0;u<c;u++)d[u]=this.parseTagValue(a,t),t+=m;return d}}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:ee(`Invalid tiff type ${t}`)}}},Ks=class extends Fa{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&&ee("Malformed EXIF data"),!t.chunked&&this.ifd0Offset>t.byteLength&&ee(`IFD0 offset points to outside of file.
|
|
3
|
-
this.ifd0Offset: ${this.ifd0Offset}, file.byteLength: ${t.byteLength}`),t.tiff&&await t.ensureChunk(this.ifd0Offset,Nl(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,Nl(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",jl(...t.get(2),t.get(1))),t.set("longitude",jl(...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 Jt)if(t=this[e],!Xl(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 jl(s,t,e,i){var n=s+t/60+e/3600;return i!=="S"&&i!=="W"||(n*=-1),n}Ft(Ks,"type","tiff"),Ft(Ks,"headerLength",10),ge.set("tiff",Ks);var gd=Object.freeze({__proto__:null,default:hd,Exifr:ti,fileParsers:Hi,segmentParsers:ge,fileReaders:ji,tagKeys:Qe,tagValues:ws,tagRevivers:$i,createDictionary:Ie,extendDictionary:za,fetchUrlAsArrayBuffer:bs,readBlobAsArrayBuffer:ys,chunkedProps:Oi,otherSegments:tn,segments:vs,tiffBlocks:Jt,segmentsAndBlocks:Ni,tiffExtractables:Bi,inheritables:en,allFormatters:Ui,Options:mi,parse:Va}),Wa={ifd0:!1,ifd1:!1,exif:!1,gps:!1,interop:!1,sanitize:!1,reviveValues:!0,translateKeys:!1,translateValues:!1,mergeOutput:!1},Ql=Object.assign({},Wa,{firstChunkSize:4e4,gps:[1,2,3,4]});async function md(s){let t=new ti(Ql);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 Zl=Object.assign({},Wa,{tiff:!1,ifd1:!0,mergeOutput:!1});async function bd(s){let t=new ti(Zl);await t.read(s);let e=await t.extractThumbnail();return e&&ja?Ha.from(e):e}async function yd(s){let t=await this.thumbnail(s);if(t!==void 0){let e=new Blob([t]);return URL.createObjectURL(e)}}var tc=Object.assign({},Wa,{firstChunkSize:4e4,ifd0:[274]});async function ec(s){let t=new ti(tc);await t.read(s);let e=await t.parse();if(e&&e.ifd0)return e.ifd0[274]}var ic=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}}),gs=!0,ms=!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;gs=Number(e)+.1*Number(i)<13.4,ms=!1}}else if(s.includes("OS X 10")){let[,t]=s.match(/OS X 10[_.](\d+)/);gs=ms=Number(t)<15}if(s.includes("Chrome/")){let[,t]=s.match(/Chrome\/(\d+)/);gs=ms=Number(t)<81}else if(s.includes("Firefox/")){let[,t]=s.match(/Firefox\/(\d+)/);gs=ms=Number(t)<77}}async function vd(s){let t=await ec(s);return Object.assign({canvas:gs,css:ms},ic[t])}var Oa=class extends Ze{constructor(...t){super(...t),Ft(this,"ranges",new Na),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:a}=this._extend(n);this._swapDataView(a)}}}_extend(t){let e;e=ja?Ha.allocUnsafe(t):new Uint8Array(t);let i=new DataView(e.buffer,e.byteOffset,e.byteLength);return e.set(new Uint8Array(this.buffer,this.byteOffset,this.byteLength),0),{uintView:e,dataView:i}}subarray(t,e,i=!1){return e=e||this._lengthToEnd(t),i&&this._tryExtend(t,e),this.ranges.add(t,e),super.subarray(t,e)}set(t,e,i=!1){i&&this._tryExtend(e,t.byteLength,t);let 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)}},Na=class{constructor(){Ft(this,"list",[])}get length(){return this.list.length}add(t,e,i=0){let n=t+e,a=this.list.filter((c=>zl(t,c.offset,n)||zl(t,c.end,n)));if(a.length>0){t=Math.min(t,...a.map((l=>l.offset))),n=Math.max(n,...a.map((l=>l.end))),e=n-t;let c=a.shift();c.offset=t,c.length=e,c.end=n,this.list=this.list.filter((l=>!a.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 zl(s,t,e){return s<=t&&t<=e}var gr=class extends Oa{constructor(t,e){super(0),Ft(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(){}};ji.set("blob",class extends gr{async readWhole(){this.chunked=!1;let s=await ys(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 ys(i);return this.set(n,s,!0)}});var wd=Object.freeze({__proto__:null,default:gd,Exifr:ti,fileParsers:Hi,segmentParsers:ge,fileReaders:ji,tagKeys:Qe,tagValues:ws,tagRevivers:$i,createDictionary:Ie,extendDictionary:za,fetchUrlAsArrayBuffer:bs,readBlobAsArrayBuffer:ys,chunkedProps:Oi,otherSegments:tn,segments:vs,tiffBlocks:Jt,segmentsAndBlocks:Ni,tiffExtractables:Bi,inheritables:en,allFormatters:Ui,Options:mi,parse:Va,gpsOnlyOptions:Ql,gps:md,thumbnailOnlyOptions:Zl,thumbnail:bd,thumbnailUrl:yd,orientationOnlyOptions:tc,orientation:ec,rotations:ic,get rotateCanvas(){return gs},get rotateCss(){return ms},rotation:vd});ji.set("url",class extends gr{async readWhole(){this.chunked=!1;let s=await bs(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 Jl(this.input,{headers:i}),a=await n.arrayBuffer(),c=a.byteLength;if(n.status!==416)return c!==t&&(this.size=s+c),this.set(a,s,!0)}});Ze.prototype.getUint64=function(s){let t=this.getUint32(s),e=this.getUint32(s+4);return t<1048575?t<<32|e:typeof cr!==void 0?(console.warn("Using BigInt because of type 64uint but JS can only handle 53b numbers."),cr(t)<<cr(32)|cr(e)):void ee("Trying to read 64b value but JS can only handle 53b numbers.")};var Ba=class extends pr{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}},mr=class extends Ba{static canHandle(t,e){if(e!==0)return!1;let i=t.getUint16(2);if(i>50)return!1;let n=16,a=[];for(;n<i;)a.push(t.getString(n,4)),n+=4;return a.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),a=this.findExtentInIloc(i,n);if(a===void 0)return;let[c,l]=a;await this.file.ensureChunk(c,l);let d=4+this.file.getUint32(c);c+=d,l-=d,await this.registerSegment("tiff",c,l)}findExifLocIdInIinf(t){this.parseBoxFullHead(t);let e,i,n,a,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,a=this.file.getString(i+n+2,4),a==="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,a]=this.get8bits(i++),[c,l]=this.get8bits(i++),d=t.version===2?4:2,m=t.version===1||t.version===2?2:0,u=l+n+a,o=t.version===2?4:2,p=this.file.getUintBytes(i,o);for(i+=o;p--;){let w=this.file.getUintBytes(i,d);i+=d+m+2+c;let S=this.file.getUint16(i);if(i+=2,w===e)return S>1&&console.warn(`ILOC box has more than one extent but we're only processing one
|
|
4
|
-
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,a)];i+=S*u}}},br=class extends mr{};Ft(br,"type","heic");var yr=class extends mr{};Ft(yr,"type","avif"),Hi.set("heic",br),Hi.set("avif",yr),Ie(Qe,["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"]]),Ie(Qe,"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"]]),Ie(Qe,"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"]]),Ie(ws,["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 Ys=Ie(ws,"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"}]]),Vl={1:"No absolute unit of measurement",2:"Inch",3:"Centimeter"};Ys.set(37392,Vl),Ys.set(41488,Vl);var Ta={0:"Normal",1:"Low",2:"High"};function Wl(s){return typeof s=="object"&&s.length!==void 0?s[0]:s}function Gl(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,a,c]=s.trim().split(/[-: ]/g).map(Number),l=new Date(t,e-1,i);return Number.isNaN(n)||Number.isNaN(a)||Number.isNaN(c)||(l.setHours(n),l.setMinutes(a),l.setSeconds(c)),Number.isNaN(+l)?s:l}}function Xs(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(ql(s[e+1],s[e]));else for(let e=0;e<s.length;e+=2)t.push(ql(s[e],s[e+1]));return Kl(String.fromCodePoint(...t))}function ql(s,t){return s<<8|t}Ys.set(41992,Ta),Ys.set(41993,Ta),Ys.set(41994,Ta),Ie($i,["ifd0","ifd1"],[[50827,function(s){return typeof s!="string"?Yl(s):s}],[306,Pa],[40091,Xs],[40092,Xs],[40093,Xs],[40094,Xs],[40095,Xs]]),Ie($i,"exif",[[40960,Gl],[36864,Gl],[36867,Pa],[36868,Pa],[40962,Wl],[40963,Wl]]),Ie($i,"gps",[[0,s=>Array.from(s).join(".")],[7,s=>Array.from(s).join(":")]]);var Js=class extends Je{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:Ze.from(t).getString()}parse(t=this.chunk){if(!this.localOptions.parse)return t;t=(function(a){let c={},l={};for(let d of ac)c[d]=[],l[d]=0;return a.replace(Ed,((d,m,u)=>{if(m==="<"){let o=++l[u];return c[u].push(o),`${d}#${o}`}return`${d}#${c[u].pop()}`}))})(t);let e=vr.findAll(t,"rdf","Description");e.length===0&&e.push(new vr("rdf","Description",void 0,t));let i,n={};for(let a of e)for(let c of a.properties)i=Sd(c.ns,n),sc(c,i);return(function(a){let c;for(let l in a)c=a[l]=hr(a[l]),c===void 0&&delete a[l];return hr(a)})(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}};Ft(Js,"type","xmp"),Ft(Js,"multiSegment",!0),ge.set("xmp",Js);var Ua=class s{static findAll(t){return nc(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=rc(n),new s(e,i,n)}constructor(t,e,i){this.ns=t,this.name=e,this.value=i}serialize(){return this.value}},vr=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 nc(t,n).map(s.unpackMatch)}static unpackMatch(t){let e=t[1],i=t[2],n=t[4],a=t[8];return new s(e,i,n,a)}constructor(t,e,i,n){this.ns=t,this.name=e,this.attrString=i,this.innerXml=n,this.attrs=Ua.findAll(i),this.children=s.findAll(n),this.value=this.children.length===0?rc(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 Ad(this.children.map(xd));if(this.isListItem&&this.children.length===1&&this.attrs.length===0)return this.children[0].serialize();let t={};for(let e of this.properties)sc(e,t);return this.value!==void 0&&(t.value=this.value),hr(t)}};function sc(s,t){let e=s.serialize();e!==void 0&&(t[s.name]=e)}var xd=s=>s.serialize(),Ad=s=>s.length===1?s[0]:s,Sd=(s,t)=>t[s]?t[s]:t[s]={};function nc(s,t){let e,i=[];if(!s)return i;for(;(e=t.exec(s))!==null;)i.push(e);return i}function rc(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 ac=["rdf:li","rdf:Seq","rdf:Bag","rdf:Alt","rdf:Description"],Ed=new RegExp(`(<|\\/)(${ac.join("|")})`,"g"),oc=wd;async function wr(s){try{return await oc.parse(s)||null}catch{return null}}function ze(){return Array.from(crypto.getRandomValues(new Uint8Array(16)),s=>s.toString(16).padStart(2,"0")).join("")}async function xr(s){if(typeof createImageBitmap>"u"||typeof document>"u"){if(s&&typeof s.arrayBuffer=="function"){let l=await s.arrayBuffer(),d=globalThis.Buffer,m=typeof d<"u"?d.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,d)=>{let m=new FileReader;m.onload=()=>l(m.result),m.onerror=d,m.readAsDataURL(s)});let a=document.createElement("canvas");a.width=Math.round(t.width*n),a.height=Math.round(t.height*n),a.getContext("2d").drawImage(t,0,0,a.width,a.height),t.close();let c=s.type==="image/png"?"image/png":"image/jpeg";return a.toDataURL(c,c==="image/png"?void 0:.82)}function lc(s,t=21,e=.2,i=128){let{data:n,width:a,height:c}=s,l=a+1,d=new Float64Array((a+1)*(c+1)),m=new Float64Array((a+1)*(c+1)),u=new Uint8Array(a*c);for(let p=0;p<c;p++){let w=0,S=0,f=p*a,v=(p+1)*l,r=p*l;for(let h=0;h<a;h++){let b=(f+h)*4,A=n[b]*77+n[b+1]*150+n[b+2]*29>>8;u[f+h]=A,w+=A,S+=A*A,d[v+h+1]=d[r+h+1]+w,m[v+h+1]=m[r+h+1]+S}}let o=Math.floor(t/2);for(let p=0;p<c;p++){let w=Math.max(0,p-o),S=Math.min(c-1,p+o),f=w*l,v=(S+1)*l;for(let r=0;r<a;r++){let h=Math.max(0,r-o),b=Math.min(a-1,r+o),A=(b-h+1)*(S-w+1),D=d[v+b+1]-d[f+b+1]-d[v+h]+d[f+h],_=m[v+b+1]-m[f+b+1]-m[v+h]+m[f+h],I=D/A,N=Math.max(0,_/A-I*I),H=Math.sqrt(N),j=I*(1+e*(H/i-1)),K=p*a+r,it=u[K]<j?0:255,ot=K*4;n[ot]=it,n[ot+1]=it,n[ot+2]=it}}return s}function Ve(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 Ga(s){if(!s)return!1;let t=Ve(s);return!!(t.crop||t.rotation!==0||t.filter!=="none")}function xs(s,t){let e=Ve(t),i=s.naturalWidth||s.width||0,n=s.naturalHeight||s.height||0,a=document.createElement("canvas"),c=i,l=n,d=0,m=0;if(e.crop){let p=e.crop;"w"in p&&!("width"in p)?(d=Math.max(0,Math.min(Math.round(p.x*i),i)),m=Math.max(0,Math.min(Math.round(p.y*n),n)),c=Math.max(1,Math.min(Math.round(p.w*i),i-d)),l=Math.max(1,Math.min(Math.round(p.h*n),n-m))):(d=Math.max(0,Math.min(p.x,i)),m=Math.max(0,Math.min(p.y,n)),c=Math.max(1,Math.min(p.width,i-d)),l=Math.max(1,Math.min(p.height,n-m)))}a.width=c,a.height=l,a.getContext("2d").drawImage(s,d,m,c,l,0,0,c,l);let o=a;if(e.rotation!==0){let p=e.rotation,w=document.createElement("canvas");p===90||p===270?(w.width=o.height,w.height=o.width):(w.width=o.width,w.height=o.height);let S=w.getContext("2d");S.translate(w.width/2,w.height/2),S.rotate(p*Math.PI/180),S.drawImage(o,-o.width/2,-o.height/2),o=w}if(e.filter==="bw"){let p=o.getContext("2d"),w=p.getImageData(0,0,o.width,o.height);lc(w),p.putImageData(w,0,0)}return o}function sn(s,t){if(!s)return Promise.resolve("");let e=Ve(t);return Ga(e)?new Promise((i,n)=>{let a=new Image;a.onload=()=>{try{let c=s.startsWith("data:image/png"),l=c?"image/png":"image/jpeg",d=xs(a,e);i(d.toDataURL(l,c?void 0:.82))}catch(c){n(c)}},a.onerror=n,a.src=s}):Promise.resolve(s)}var As=class{#t=null;#e=new Map;#i=new Map;constructor(t=lr()){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=ze(),n=this.#s(e),a={id:i,name:t||"Untitled Document",pages:n};return await this.#t.saveDoc(i,a),a}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 a=setTimeout(async()=>{this.#e.delete(t)},i);this.#e.set(t,{doc:n,timerId:a})}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 a=n.pages.findIndex(c=>c.id===e);if(a===-1)throw new Error(`Page "${e}" not found in document "${t}"`);n.pages[a]={...n.pages[a],...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])),a=[];for(let c of e)n.has(c)&&(a.push(n.get(c)),n.delete(c));for(let c of n.values())a.push(c);i.pages=a,await this.saveDoc(t,i)}async deletePage(t,e,{soft:i=!0,timeoutMs:n=5e3}={}){let a=await this.getDoc(t);if(!a)throw new Error(`Document "${t}" not found`);let c=a.pages.findIndex(u=>u.id===e);if(c===-1)return;let[l]=a.pages.splice(c,1);await this.saveDoc(t,a);let d=`${t}:${e}`;if(this.#r(d),!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(d),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(d,{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 a=await this.getDoc(t);if(!a)return null;let c=Math.min(n.index,a.pages.length);return a.pages.splice(c,0,n.page),await this.saveDoc(t,a),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),a=[];for(let c of n?.pages||[]){if(!c){a.push(c);continue}let l={...c},d=l.blob instanceof Blob?l.blob:null;if(!d&&typeof l.src=="string"&&l.src.startsWith("blob:"))try{d=await(await fetch(l.src)).blob()}catch{}d&&(l.src=await Ca(d));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 Ca(m)),delete l.blob,delete l.originalBlob,a.push(l)}e[i.id]={name:i.name,pages:JSON.stringify(a)}}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[]}},_d=new As;var qa=".";function cc(){return qa}function nn(s){typeof s=="string"&&(qa=s.replace(/\/+$/,"")||".")}function Xa(s){if(!s)return"";if(/^(https?:|\/\/|data:|blob:)/i.test(s))return s;let t=s.replace(/^\/+/,""),e=qa;return!e||e==="."?t:`${e}/${t}`}var Ar=new Map;function Cd(s,t){let e=t();if(e)return Promise.resolve(e);if(Ar.has(s))return Ar.get(s);let i=new Promise((n,a)=>{if(typeof document>"u"){a(new Error(`Cannot load script "${s}" in an environment without DOM document.`));return}let c=Xa(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",()=>a(new Error(`Failed to load "${s}": Network error`)),{once:!0});return}let d=document.createElement("script");d.src=c,d.async=!0,d.onload=()=>{let m=t();n(m)},d.onerror=()=>{Ar.delete(s),d.remove(),a(new Error(`Failed to load script "${s}": Network error`))},document.head.appendChild(d)});return Ar.set(s,i),i}async function hc(){return Cd("js/lib/cropper.js",()=>window.Cropper)}var Sr=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 ei=class extends Sr{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 Er=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 zi=class extends Er{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 Vi=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 kd(s){return new Promise((t,e)=>{let i=new Image;i.onload=()=>t(i),i.onerror=e,i.src=s})}var rn=class extends Vi{async renderEdits(t,e={}){if(!t)return"";if(typeof document>"u")return t;try{let i=await kd(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),xs(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 an=class extends Vi{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 Ka(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 a=(Math.round(Number(i)/90)*90%360+360)%360;(a===90||a===180||a===270)&&(e=a)}let n=s&&s.filter==="bw"?"bw":"none";return{crop:t,rotate:e,filter:n}}var he=s=>Math.round(s*1e6)/1e6;function Ya(s,t=0){if(!s)return null;let e=(Math.round(Number(t)/90)*90%360+360)%360,{x:i,y:n,w:a,h:c}=s;return e===90?{x:he(Math.max(0,Math.min(1,1-n-c))),y:he(Math.max(0,Math.min(1,i))),w:he(Math.max(.01,Math.min(1,c))),h:he(Math.max(.01,Math.min(1,a)))}:e===180?{x:he(Math.max(0,Math.min(1,1-i-a))),y:he(Math.max(0,Math.min(1,1-n-c))),w:he(Math.max(.01,Math.min(1,a))),h:he(Math.max(.01,Math.min(1,c)))}:e===270?{x:he(Math.max(0,Math.min(1,n))),y:he(Math.max(0,Math.min(1,1-i-a))),w:he(Math.max(.01,Math.min(1,c))),h:he(Math.max(.01,Math.min(1,a)))}:{x:he(Math.max(0,Math.min(1,i))),y:he(Math.max(0,Math.min(1,n))),w:he(Math.max(.01,Math.min(1,a))),h:he(Math.max(.01,Math.min(1,c)))}}function Ja(s,t=0){return Ya(s,t)}function Qa(s,t=0){return Ya(s,-t)}var ne={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 dc(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 eo=["crop","rotate","filter","ocr","export","sync"],Za=["pdf","zip","png","jpg"],to=["eng"],uc={};function Ss(s){return uc[s]?uc[s]:typeof globalThis<"u"&&globalThis.__copio_services__?.[s]?globalThis.__copio_services__[s]:null}function Td(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(eo):new Set(eo)}function _r(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 on=class{#t=new Set(eo);#e=[...Za];#i=[...to];#n=0;#r="";#s=null;#o=null;#l={};#a=!0;#h=!0;#u=null;#d=new Map;#c=new Map;constructor(t={}){this.#s=t.storage||lr(t),this.#o=t.repository||new As(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 rn:this.#u=new an,t.features!==void 0&&this.setFeatures(t.features),t.exportFormats!==void 0&&(this.#e=_r(t.exportFormats,Za)),t.ocrLanguages!==void 0&&(this.#i=_r(t.ocrLanguages,to)),t.maxPages!==void 0&&(this.#n=Math.max(0,Number(t.maxPages)||0)),t.assetBase!==void 0&&nn(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]||Ss(t)}hasFeature(t){return t?this.#t.has(String(t).trim().toLowerCase()):!1}get features(){return Array.from(this.#t)}setFeatures(t){this.#t=Td(t),this.hasFeature("ocr")?(this.#a=!0,this.getService("ocr")instanceof ei&&this.setService("ocr",Ss("ocr"))):(this.#a=!1,this.setService("ocr",new ei))}enableFeature(t){if(t){let e=String(t).trim().toLowerCase();this.#t.add(e),e==="ocr"&&(this.#a=!0,this.getService("ocr")instanceof ei&&this.setService("ocr",Ss("ocr")))}}disableFeature(t){if(t){let e=String(t).trim().toLowerCase();this.#t.delete(e),e==="ocr"&&(this.#a=!1,this.setService("ocr",new ei))}}get ocr(){return this.#a&&this.hasFeature("ocr")}set ocr(t){this.#a=!!t,this.#a?(this.enableFeature("ocr"),this.getService("ocr")instanceof ei&&this.setService("ocr",Ss("ocr"))):(this.disableFeature("ocr"),this.setService("ocr",new ei))}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 zi&&this.setService("pdf",Ss("pdf"))):(this.#e=this.#e.filter(e=>e!=="pdf"),this.setService("pdf",new zi))}get exportFormats(){return[...this.#e]}set exportFormats(t){this.#e=_r(t,Za),this.#e.includes("pdf")?(this.#h=!0,this.getService("pdf")instanceof zi&&this.setService("pdf",Ss("pdf"))):(this.#h=!1,this.setService("pdf",new zi))}get ocrLanguages(){return[...this.#i]}set ocrLanguages(t){this.#i=_r(t,to)}get maxPages(){return this.#n}set maxPages(t){this.#n=Math.max(0,Number(t)||0)}get assetBase(){return cc()}set assetBase(t){nn(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 As(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=Ka(e);return this.#u?this.#u.renderEdits(t,i):sn(t,i)}get docs(){return this.#o}async listDocuments(){return this.#o.listDocs()}async getDocument(t){return this.#o.getDoc(t)}async createDocument(t,e){return this.#o.createDoc(t,e)}async deleteDocument(t,e={}){return this.#o.deleteDoc(t,e)}async undoDeleteDocument(t){return this.#o.undoDeleteDoc(t)}async renameDocument(t,e){return this.#o.renameDoc(t,e)}async addPages(t,e){return this.#o.addPages(t,e)}async deletePage(t,e,i={}){return this.#f(t,{type:"delete",pageId:e}),this.#o.deletePage(t,e,i)}async undoDeletePage(t,e){return this.#o.undoDeletePage(t,e)}async updatePage(t,e,i){return this.#o.updatePage(t,e,i)}async reorderPages(t,e){let i=await this.getDocument(t),n=i?.pages?i.pages.map(a=>a.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),a=n?await this.getDocument(n):null;if(!a||!a.pages)throw new Error(`Document with ID "${n||t}" not found`);let c=a.pages.find(p=>p.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"}},d=c.src,m=Ka({...l,...i}),u=c.originalSrc||c.src,o=u;return this.#u&&(o=await this.#u.renderEdits(u,m)),await this.updatePage(n,e,{originalSrc:u,src:o,edits:m}),this.#f(n,{type:"edit",pageId:e,priorEdits:l,priorSrc:d,newEdits:m,newSrc:o}),{...c,originalSrc:u,src:o,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.#o.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.#o.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 d=await l.renderPdfPagesToDataUrls(c);for(let m of d)n.push({id:ze(),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 xr(c),d=null;try{d=await wr(c)}catch{}n.push({id:ze(),src:l,originalSrc:l,edits:{crop:null,rotation:0,filter:"none"},type:"image",name:c.name||"Captured Image",orientation:d})}if(n.length===0)return[];await this.init();let a=e;if(a)await this.getDocument(a)||await this.#o.saveDoc(a,{name:"Scanned Document",pages:[]});else{let c=await this.listDocuments();c.length>0?a=c[0].id:a=(await this.createDocument("Scanned Document",[])).id}if(this.#n>0){let c=(await this.getDocument(a))?.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(a,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),a=this.getService("pdf")||this.getService("export");if(!a||typeof a.exportDocumentAsPdf!="function")throw new Error("Export service (PdfPort) is not registered. Import @copio/sdk or register an exportService.");return a.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),a=this.getService("export");if(!a||typeof a.exportDocumentAsImages!="function")throw new Error("Export service is not registered. Import @copio/sdk or register an exportService.");return a.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.#p(t),a=n;e&&(a=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",d=await c.recognizeDocumentPages(a,{lang:l,...i});if(Array.isArray(d.pagesResults)){for(let m of d.pagesResults){let u=a.find(o=>o.id===m.pageId)||a[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 d.pagesResults){let o=m.pages.find(p=>p.id===u.pageId)||m.pages[u.pageIndex];o&&(o.ocrText=u.text,o.ocrConfidence=u.confidence,o.ocrWords=u.words)}await this.#s.saveDoc(t,m)}}}return{text:d.combinedText,...d}}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 pc(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 Ge(s){for(var t=1;t<arguments.length;t++){var e=arguments[t]!=null?arguments[t]:{};t%2?pc(Object(e),!0).forEach(function(i){Pd(s,i,e[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(s,Object.getOwnPropertyDescriptors(e)):pc(Object(e)).forEach(function(i){Object.defineProperty(s,i,Object.getOwnPropertyDescriptor(e,i))})}return s}function Dr(s){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Dr=function(t){return typeof t}:Dr=function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Dr(s)}function Pd(s,t,e){return t in s?Object.defineProperty(s,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):s[t]=e,s}function si(){return si=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},si.apply(this,arguments)}function Dd(s,t){if(s==null)return{};var e={},i=Object.keys(s),n,a;for(a=0;a<i.length;a++)n=i[a],!(t.indexOf(n)>=0)&&(e[n]=s[n]);return e}function Md(s,t){if(s==null)return{};var e=Dd(s,t),i,n;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(s);for(n=0;n<a.length;n++)i=a[n],!(t.indexOf(i)>=0)&&Object.prototype.propertyIsEnumerable.call(s,i)&&(e[i]=s[i])}return e}var Rd="1.15.6";function ii(s){if(typeof window<"u"&&window.navigator)return!!navigator.userAgent.match(s)}var ni=ii(/(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i),mn=ii(/Edge/i),fc=ii(/firefox/i),dn=ii(/safari/i)&&!ii(/chrome/i)&&!ii(/android/i),mo=ii(/iP(ad|od|hone)/i),Ac=ii(/chrome/i)&&ii(/android/i),Sc={capture:!1,passive:!1};function Lt(s,t,e){s.addEventListener(t,e,!ni&&Sc)}function It(s,t,e){s.removeEventListener(t,e,!ni&&Sc)}function Fr(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 Ec(s){return s.host&&s!==document&&s.host.nodeType?s.host:s.parentNode}function Fe(s,t,e,i){if(s){e=e||document;do{if(t!=null&&(t[0]===">"?s.parentNode===e&&Fr(s,t):Fr(s,t))||i&&s===e)return s;if(s===e)break}while(s=Ec(s))}return null}var gc=/\s+/g;function Ce(s,t,e){if(s&&t)if(s.classList)s.classList[e?"add":"remove"](t);else{var i=(" "+s.className+" ").replace(gc," ").replace(" "+t+" "," ");s.className=(i+(e?" "+t:"")).replace(gc," ")}}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 Ts(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 _c(s,t,e){if(s){var i=s.getElementsByTagName(t),n=0,a=i.length;if(e)for(;n<a;n++)e(i[n],n);return i}return[]}function We(){var s=document.scrollingElement;return s||document.documentElement}function Zt(s,t,e,i,n){if(!(!s.getBoundingClientRect&&s!==window)){var a,c,l,d,m,u,o;if(s!==window&&s.parentNode&&s!==We()?(a=s.getBoundingClientRect(),c=a.top,l=a.left,d=a.bottom,m=a.right,u=a.height,o=a.width):(c=0,l=0,d=window.innerHeight,m=window.innerWidth,u=window.innerHeight,o=window.innerWidth),(t||e)&&s!==window&&(n=n||s.parentNode,!ni))do if(n&&n.getBoundingClientRect&&(Et(n,"transform")!=="none"||e&&Et(n,"position")!=="static")){var p=n.getBoundingClientRect();c-=p.top+parseInt(Et(n,"border-top-width")),l-=p.left+parseInt(Et(n,"border-left-width")),d=c+a.height,m=l+a.width;break}while(n=n.parentNode);if(i&&s!==window){var w=Ts(n||s),S=w&&w.a,f=w&&w.d;w&&(c/=f,l/=S,o/=S,u/=f,d=c+u,m=l+o)}return{top:c,left:l,bottom:d,right:m,width:o,height:u}}}function mc(s,t,e){for(var i=vi(s,!0),n=Zt(s)[t];i;){var a=Zt(i)[e],c=void 0;if(e==="top"||e==="left"?c=n>=a:c=n<=a,!c)return i;if(i===We())break;i=vi(i,!1)}return!1}function Ps(s,t,e,i){for(var n=0,a=0,c=s.children;a<c.length;){if(c[a].style.display!=="none"&&c[a]!==_t.ghost&&(i||c[a]!==_t.dragged)&&Fe(c[a],e.draggable,s,!1)){if(n===t)return c[a];n++}a++}return null}function bo(s,t){for(var e=s.lastElementChild;e&&(e===_t.ghost||Et(e,"display")==="none"||t&&!Fr(e,t));)e=e.previousElementSibling;return e||null}function Pe(s,t){var e=0;if(!s||!s.parentNode)return-1;for(;s=s.previousElementSibling;)s.nodeName.toUpperCase()!=="TEMPLATE"&&s!==_t.clone&&(!t||Fr(s,t))&&e++;return e}function bc(s){var t=0,e=0,i=We();if(s)do{var n=Ts(s),a=n.a,c=n.d;t+=s.scrollLeft*a,e+=s.scrollTop*c}while(s!==i&&(s=s.parentNode));return[t,e]}function Id(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 vi(s,t){if(!s||!s.getBoundingClientRect)return We();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 We();if(i||t)return e;i=!0}}while(e=e.parentNode);return We()}function Ld(s,t){if(s&&t)for(var e in t)t.hasOwnProperty(e)&&(s[e]=t[e]);return s}function io(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 un;function Cc(s,t){return function(){if(!un){var e=arguments,i=this;e.length===1?s.call(i,e[0]):s.apply(i,e),un=setTimeout(function(){un=void 0},t)}}}function Fd(){clearTimeout(un),un=void 0}function kc(s,t,e){s.scrollLeft+=t,s.scrollTop+=e}function Tc(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 Pc(s,t,e){var i={};return Array.from(s.children).forEach(function(n){var a,c,l,d;if(!(!Fe(n,t.draggable,s,!1)||n.animated||n===e)){var m=Zt(n);i.left=Math.min((a=i.left)!==null&&a!==void 0?a: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((d=i.bottom)!==null&&d!==void 0?d:-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 xe="Sortable"+new Date().getTime();function Od(){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===_t.ghost)){s.push({target:n,rect:Zt(n)});var a=Ge({},s[s.length-1].rect);if(n.thisAnimationDuration){var c=Ts(n,!0);c&&(a.top-=c.f,a.left-=c.e)}n.fromRect=a}})}},addAnimationState:function(i){s.push(i)},removeAnimationState:function(i){s.splice(Id(s,{target:i}),1)},animateAll:function(i){var n=this;if(!this.options.animation){clearTimeout(t),typeof i=="function"&&i();return}var a=!1,c=0;s.forEach(function(l){var d=0,m=l.target,u=m.fromRect,o=Zt(m),p=m.prevFromRect,w=m.prevToRect,S=l.rect,f=Ts(m,!0);f&&(o.top-=f.f,o.left-=f.e),m.toRect=o,m.thisAnimationDuration&&io(p,o)&&!io(u,o)&&(S.top-o.top)/(S.left-o.left)===(u.top-o.top)/(u.left-o.left)&&(d=Bd(S,p,w,n.options)),io(o,u)||(m.prevFromRect=u,m.prevToRect=o,d||(d=n.options.animation),n.animate(m,S,o,d)),d&&(a=!0,c=Math.max(c,d),clearTimeout(m.animationResetTimer),m.animationResetTimer=setTimeout(function(){m.animationTime=0,m.prevFromRect=null,m.fromRect=null,m.prevToRect=null,m.thisAnimationDuration=null},d),m.thisAnimationDuration=d)}),clearTimeout(t),a?t=setTimeout(function(){typeof i=="function"&&i()},c):typeof i=="function"&&i(),s=[]},animate:function(i,n,a,c){if(c){Et(i,"transition",""),Et(i,"transform","");var l=Ts(this.el),d=l&&l.a,m=l&&l.d,u=(n.left-a.left)/(d||1),o=(n.top-a.top)/(m||1);i.animatingX=!!u,i.animatingY=!!o,Et(i,"transform","translate3d("+u+"px,"+o+"px,0)"),this.forRepaintDummy=Nd(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 Nd(s){return s.offsetWidth}function Bd(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 Es=[],so={initializeByDefault:!0},bn={mount:function(t){for(var e in so)so.hasOwnProperty(e)&&!(e in t)&&(t[e]=so[e]);Es.forEach(function(i){if(i.pluginName===t.pluginName)throw"Sortable: Cannot mount plugin ".concat(t.pluginName," more than once")}),Es.push(t)},pluginEvent:function(t,e,i){var n=this;this.eventCanceled=!1,i.cancel=function(){n.eventCanceled=!0};var a=t+"Global";Es.forEach(function(c){e[c.pluginName]&&(e[c.pluginName][a]&&e[c.pluginName][a](Ge({sortable:e},i)),e.options[c.pluginName]&&e[c.pluginName][t]&&e[c.pluginName][t](Ge({sortable:e},i)))})},initializePlugins:function(t,e,i,n){Es.forEach(function(l){var d=l.pluginName;if(!(!t.options[d]&&!l.initializeByDefault)){var m=new l(t,e,t.options);m.sortable=t,m.options=t.options,t[d]=m,si(i,m.defaults)}});for(var a in t.options)if(t.options.hasOwnProperty(a)){var c=this.modifyOption(t,a,t.options[a]);typeof c<"u"&&(t.options[a]=c)}},getEventProperties:function(t,e){var i={};return Es.forEach(function(n){typeof n.eventProperties=="function"&&si(i,n.eventProperties.call(e[n.pluginName],t))}),i},modifyOption:function(t,e,i){var n;return Es.forEach(function(a){t[a.pluginName]&&a.optionListeners&&typeof a.optionListeners[e]=="function"&&(n=a.optionListeners[e].call(t[a.pluginName],i))}),n}};function Ud(s){var t=s.sortable,e=s.rootEl,i=s.name,n=s.targetEl,a=s.cloneEl,c=s.toEl,l=s.fromEl,d=s.oldIndex,m=s.newIndex,u=s.oldDraggableIndex,o=s.newDraggableIndex,p=s.originalEvent,w=s.putSortable,S=s.extraEventProperties;if(t=t||e&&e[xe],!!t){var f,v=t.options,r="on"+i.charAt(0).toUpperCase()+i.substr(1);window.CustomEvent&&!ni&&!mn?f=new CustomEvent(i,{bubbles:!0,cancelable:!0}):(f=document.createEvent("Event"),f.initEvent(i,!0,!0)),f.to=c||e,f.from=l||e,f.item=n||e,f.clone=a,f.oldIndex=d,f.newIndex=m,f.oldDraggableIndex=u,f.newDraggableIndex=o,f.originalEvent=p,f.pullMode=w?w.lastPutMode:void 0;var h=Ge(Ge({},S),bn.getEventProperties(i,t));for(var b in h)f[b]=h[b];e&&e.dispatchEvent(f),v[r]&&v[r].call(t,f)}}var $d=["evt"],we=function(t,e){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},n=i.evt,a=Md(i,$d);bn.pluginEvent.bind(_t)(t,e,Ge({dragEl:gt,parentEl:Yt,ghostEl:kt,rootEl:zt,nextEl:qi,lastDownEl:Mr,cloneEl:qt,cloneHidden:yi,dragStarted:ln,putSortable:oe,activeSortable:_t.active,originalEvent:n,oldIndex:ks,oldDraggableIndex:pn,newIndex:ke,newDraggableIndex:bi,hideGhostForTarget:Ic,unhideGhostForTarget:Lc,cloneNowHidden:function(){yi=!0},cloneNowShown:function(){yi=!1},dispatchSortableEvent:function(l){me({sortable:e,name:l,originalEvent:n})}},a))};function me(s){Ud(Ge({putSortable:oe,cloneEl:qt,targetEl:gt,rootEl:zt,oldIndex:ks,oldDraggableIndex:pn,newIndex:ke,newDraggableIndex:bi},s))}var gt,Yt,kt,zt,qi,Mr,qt,yi,ks,ke,pn,bi,Cr,oe,Cs=!1,Or=!1,Nr=[],Wi,Le,no,ro,yc,vc,ln,_s,fn,gn=!1,kr=!1,Rr,de,ao=[],uo=!1,Br=[],$r=typeof document<"u",Tr=mo,wc=mn||ni?"cssFloat":"float",Hd=$r&&!Ac&&!mo&&"draggable"in document.createElement("div"),Dc=(function(){if($r){if(ni)return!1;var s=document.createElement("x");return s.style.cssText="pointer-events:auto",s.style.pointerEvents==="auto"}})(),Mc=function(t,e){var i=Et(t),n=parseInt(i.width)-parseInt(i.paddingLeft)-parseInt(i.paddingRight)-parseInt(i.borderLeftWidth)-parseInt(i.borderRightWidth),a=Ps(t,0,e),c=Ps(t,1,e),l=a&&Et(a),d=c&&Et(c),m=l&&parseInt(l.marginLeft)+parseInt(l.marginRight)+Zt(a).width,u=d&&parseInt(d.marginLeft)+parseInt(d.marginRight)+Zt(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(a&&l.float&&l.float!=="none"){var o=l.float==="left"?"left":"right";return c&&(d.clear==="both"||d.clear===o)?"vertical":"horizontal"}return a&&(l.display==="block"||l.display==="flex"||l.display==="table"||l.display==="grid"||m>=n&&i[wc]==="none"||c&&i[wc]==="none"&&m+u>n)?"vertical":"horizontal"},jd=function(t,e,i){var n=i?t.left:t.top,a=i?t.right:t.bottom,c=i?t.width:t.height,l=i?e.left:e.top,d=i?e.right:e.bottom,m=i?e.width:e.height;return n===l||a===d||n+c/2===l+m/2},zd=function(t,e){var i;return Nr.some(function(n){var a=n[xe].options.emptyInsertThreshold;if(!(!a||bo(n))){var c=Zt(n),l=t>=c.left-a&&t<=c.right+a,d=e>=c.top-a&&e<=c.bottom+a;if(l&&d)return i=n}}),i},Rc=function(t){function e(a,c){return function(l,d,m,u){var o=l.options.group.name&&d.options.group.name&&l.options.group.name===d.options.group.name;if(a==null&&(c||o))return!0;if(a==null||a===!1)return!1;if(c&&a==="clone")return a;if(typeof a=="function")return e(a(l,d,m,u),c)(l,d,m,u);var p=(c?l:d).options.group.name;return a===!0||typeof a=="string"&&a===p||a.join&&a.indexOf(p)>-1}}var i={},n=t.group;(!n||Dr(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},Ic=function(){!Dc&&kt&&Et(kt,"display","none")},Lc=function(){!Dc&&kt&&Et(kt,"display","")};$r&&!Ac&&document.addEventListener("click",function(s){if(Or)return s.preventDefault(),s.stopPropagation&&s.stopPropagation(),s.stopImmediatePropagation&&s.stopImmediatePropagation(),Or=!1,!1},!0);var Gi=function(t){if(gt){t=t.touches?t.touches[0]:t;var e=zd(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[xe]._onDragOver(i)}}},Vd=function(t){gt&>.parentNode[xe]._isOutsideThisEl(t.target)};function _t(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=si({},t),s[xe]=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 Mc(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:_t.supportPointer!==!1&&"PointerEvent"in window&&(!dn||mo),emptyInsertThreshold:5};bn.initializePlugins(this,s,e);for(var i in e)!(i in t)&&(t[i]=e[i]);Rc(t);for(var n in this)n.charAt(0)==="_"&&typeof this[n]=="function"&&(this[n]=this[n].bind(this));this.nativeDraggable=t.forceFallback?!1:Hd,this.nativeDraggable&&(this.options.touchStartThreshold=1),t.supportPointer?Lt(s,"pointerdown",this._onTapStart):(Lt(s,"mousedown",this._onTapStart),Lt(s,"touchstart",this._onTapStart)),this.nativeDraggable&&(Lt(s,"dragover",this),Lt(s,"dragenter",this)),Nr.push(this.el),t.store&&t.store.get&&this.sort(t.store.get(this)||[]),si(this,Od())}_t.prototype={constructor:_t,_isOutsideThisEl:function(t){!this.el.contains(t)&&t!==this.el&&(_s=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,a=n.preventOnFilter,c=t.type,l=t.touches&&t.touches[0]||t.pointerType&&t.pointerType==="touch"&&t,d=(l||t).target,m=t.target.shadowRoot&&(t.path&&t.path[0]||t.composedPath&&t.composedPath()[0])||d,u=n.filter;if(Qd(i),!gt&&!(/mousedown|pointerdown/.test(c)&&t.button!==0||n.disabled)&&!m.isContentEditable&&!(!this.nativeDraggable&&dn&&d&&d.tagName.toUpperCase()==="SELECT")&&(d=Fe(d,n.draggable,i,!1),!(d&&d.animated)&&Mr!==d)){if(ks=Pe(d),pn=Pe(d,n.draggable),typeof u=="function"){if(u.call(this,t,d,this)){me({sortable:e,rootEl:m,name:"filter",targetEl:d,toEl:i,fromEl:i}),we("filter",e,{evt:t}),a&&t.preventDefault();return}}else if(u&&(u=u.split(",").some(function(o){if(o=Fe(m,o.trim(),i,!1),o)return me({sortable:e,rootEl:o,name:"filter",targetEl:d,fromEl:i,toEl:i}),we("filter",e,{evt:t}),!0}),u)){a&&t.preventDefault();return}n.handle&&!Fe(m,n.handle,i,!1)||this._prepareDragStart(t,l,d)}}},_prepareDragStart:function(t,e,i){var n=this,a=n.el,c=n.options,l=a.ownerDocument,d;if(i&&!gt&&i.parentNode===a){var m=Zt(i);if(zt=a,gt=i,Yt=gt.parentNode,qi=gt.nextSibling,Mr=i,Cr=c.group,_t.dragged=gt,Wi={target:gt,clientX:(e||t).clientX,clientY:(e||t).clientY},yc=Wi.clientX-m.left,vc=Wi.clientY-m.top,this._lastX=(e||t).clientX,this._lastY=(e||t).clientY,gt.style["will-change"]="all",d=function(){if(we("delayEnded",n,{evt:t}),_t.eventCanceled){n._onDrop();return}n._disableDelayedDragEvents(),!fc&&n.nativeDraggable&&(gt.draggable=!0),n._triggerDragStart(t,e),me({sortable:n,name:"choose",originalEvent:t}),Ce(gt,c.chosenClass,!0)},c.ignore.split(",").forEach(function(u){_c(gt,u.trim(),oo)}),Lt(l,"dragover",Gi),Lt(l,"mousemove",Gi),Lt(l,"touchmove",Gi),c.supportPointer?(Lt(l,"pointerup",n._onDrop),!this.nativeDraggable&&Lt(l,"pointercancel",n._onDrop)):(Lt(l,"mouseup",n._onDrop),Lt(l,"touchend",n._onDrop),Lt(l,"touchcancel",n._onDrop)),fc&&this.nativeDraggable&&(this.options.touchStartThreshold=4,gt.draggable=!0),we("delayStart",this,{evt:t}),c.delay&&(!c.delayOnTouchOnly||e)&&(!this.nativeDraggable||!(mn||ni))){if(_t.eventCanceled){this._onDrop();return}c.supportPointer?(Lt(l,"pointerup",n._disableDelayedDrag),Lt(l,"pointercancel",n._disableDelayedDrag)):(Lt(l,"mouseup",n._disableDelayedDrag),Lt(l,"touchend",n._disableDelayedDrag),Lt(l,"touchcancel",n._disableDelayedDrag)),Lt(l,"mousemove",n._delayedDragTouchMoveHandler),Lt(l,"touchmove",n._delayedDragTouchMoveHandler),c.supportPointer&&Lt(l,"pointermove",n._delayedDragTouchMoveHandler),n._dragStartTimer=setTimeout(d,c.delay)}else d()}},_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&&oo(gt),clearTimeout(this._dragStartTimer),this._disableDelayedDragEvents()},_disableDelayedDragEvents:function(){var t=this.el.ownerDocument;It(t,"mouseup",this._disableDelayedDrag),It(t,"touchend",this._disableDelayedDrag),It(t,"touchcancel",this._disableDelayedDrag),It(t,"pointerup",this._disableDelayedDrag),It(t,"pointercancel",this._disableDelayedDrag),It(t,"mousemove",this._delayedDragTouchMoveHandler),It(t,"touchmove",this._delayedDragTouchMoveHandler),It(t,"pointermove",this._delayedDragTouchMoveHandler)},_triggerDragStart:function(t,e){e=e||t.pointerType=="touch"&&t,!this.nativeDraggable||e?this.options.supportPointer?Lt(document,"pointermove",this._onTouchMove):e?Lt(document,"touchmove",this._onTouchMove):Lt(document,"mousemove",this._onTouchMove):(Lt(gt,"dragend",this),Lt(zt,"dragstart",this._onDragStart));try{document.selection?Ir(function(){document.selection.empty()}):window.getSelection().removeAllRanges()}catch{}},_dragStarted:function(t,e){if(Cs=!1,zt&>){we("dragStarted",this,{evt:e}),this.nativeDraggable&&Lt(document,"dragover",Vd);var i=this.options;!t&&Ce(gt,i.dragClass,!1),Ce(gt,i.ghostClass,!0),_t.active=this,t&&this._appendGhost(),me({sortable:this,name:"start",originalEvent:e})}else this._nulling()},_emulateDragOver:function(){if(Le){this._lastX=Le.clientX,this._lastY=Le.clientY,Ic();for(var t=document.elementFromPoint(Le.clientX,Le.clientY),e=t;t&&t.shadowRoot&&(t=t.shadowRoot.elementFromPoint(Le.clientX,Le.clientY),t!==e);)e=t;if(gt.parentNode[xe]._isOutsideThisEl(t),e)do{if(e[xe]){var i=void 0;if(i=e[xe]._onDragOver({clientX:Le.clientX,clientY:Le.clientY,target:t,rootEl:e}),i&&!this.options.dragoverBubble)break}t=e}while(e=Ec(e));Lc()}},_onTouchMove:function(t){if(Wi){var e=this.options,i=e.fallbackTolerance,n=e.fallbackOffset,a=t.touches?t.touches[0]:t,c=kt&&Ts(kt,!0),l=kt&&c&&c.a,d=kt&&c&&c.d,m=Tr&&de&&bc(de),u=(a.clientX-Wi.clientX+n.x)/(l||1)+(m?m[0]-ao[0]:0)/(l||1),o=(a.clientY-Wi.clientY+n.y)/(d||1)+(m?m[1]-ao[1]:0)/(d||1);if(!_t.active&&!Cs){if(i&&Math.max(Math.abs(a.clientX-this._lastX),Math.abs(a.clientY-this._lastY))<i)return;this._onDragStart(t,!0)}if(kt){c?(c.e+=u-(no||0),c.f+=o-(ro||0)):c={a:1,b:0,c:0,d:1,e:u,f:o};var p="matrix(".concat(c.a,",").concat(c.b,",").concat(c.c,",").concat(c.d,",").concat(c.e,",").concat(c.f,")");Et(kt,"webkitTransform",p),Et(kt,"mozTransform",p),Et(kt,"msTransform",p),Et(kt,"transform",p),no=u,ro=o,Le=a}t.cancelable&&t.preventDefault()}},_appendGhost:function(){if(!kt){var t=this.options.fallbackOnBody?document.body:zt,e=Zt(gt,!0,Tr,!0,t),i=this.options;if(Tr){for(de=t;Et(de,"position")==="static"&&Et(de,"transform")==="none"&&de!==document;)de=de.parentNode;de!==document.body&&de!==document.documentElement?(de===document&&(de=We()),e.top+=de.scrollTop,e.left+=de.scrollLeft):de=We(),ao=bc(de)}kt=gt.cloneNode(!0),Ce(kt,i.ghostClass,!1),Ce(kt,i.fallbackClass,!0),Ce(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",Tr?"absolute":"fixed"),Et(kt,"zIndex","100000"),Et(kt,"pointerEvents","none"),_t.ghost=kt,t.appendChild(kt),Et(kt,"transform-origin",yc/parseInt(kt.style.width)*100+"% "+vc/parseInt(kt.style.height)*100+"%")}},_onDragStart:function(t,e){var i=this,n=t.dataTransfer,a=i.options;if(we("dragStart",this,{evt:t}),_t.eventCanceled){this._onDrop();return}we("setupClone",this),_t.eventCanceled||(qt=Tc(gt),qt.removeAttribute("id"),qt.draggable=!1,qt.style["will-change"]="",this._hideClone(),Ce(qt,this.options.chosenClass,!1),_t.clone=qt),i.cloneId=Ir(function(){we("clone",i),!_t.eventCanceled&&(i.options.removeCloneOnHide||zt.insertBefore(qt,gt),i._hideClone(),me({sortable:i,name:"clone"}))}),!e&&Ce(gt,a.dragClass,!0),e?(Or=!0,i._loopId=setInterval(i._emulateDragOver,50)):(It(document,"mouseup",i._onDrop),It(document,"touchend",i._onDrop),It(document,"touchcancel",i._onDrop),n&&(n.effectAllowed="move",a.setData&&a.setData.call(i,n,gt)),Lt(document,"drop",i),Et(gt,"transform","translateZ(0)")),Cs=!0,i._dragStartId=Ir(i._dragStarted.bind(i,e,t)),Lt(document,"selectstart",i),ln=!0,window.getSelection().removeAllRanges(),dn&&Et(document.body,"user-select","none")},_onDragOver:function(t){var e=this.el,i=t.target,n,a,c,l=this.options,d=l.group,m=_t.active,u=Cr===d,o=l.sort,p=oe||m,w,S=this,f=!1;if(uo)return;function v(et,rt){we(et,S,Ge({evt:t,isOwner:u,axis:w?"vertical":"horizontal",revert:c,dragRect:n,targetRect:a,canSort:o,fromSortable:p,target:i,completed:h,onMove:function(st,G){return Pr(zt,e,gt,n,st,Zt(st),t,G)},changed:b},rt))}function r(){v("dragOverAnimationCapture"),S.captureAnimationState(),S!==p&&p.captureAnimationState()}function h(et){return v("dragOverCompleted",{insertion:et}),et&&(u?m._hideClone():m._showClone(S),S!==p&&(Ce(gt,oe?oe.options.ghostClass:m.options.ghostClass,!1),Ce(gt,l.ghostClass,!0)),oe!==S&&S!==_t.active?oe=S:S===_t.active&&oe&&(oe=null),p===S&&(S._ignoreWhileAnimating=i),S.animateAll(function(){v("dragOverAnimationComplete"),S._ignoreWhileAnimating=null}),S!==p&&(p.animateAll(),p._ignoreWhileAnimating=null)),(i===gt&&!gt.animated||i===e&&!i.animated)&&(_s=null),!l.dragoverBubble&&!t.rootEl&&i!==document&&(gt.parentNode[xe]._isOutsideThisEl(t.target),!et&&Gi(t)),!l.dragoverBubble&&t.stopPropagation&&t.stopPropagation(),f=!0}function b(){ke=Pe(gt),bi=Pe(gt,l.draggable),me({sortable:S,name:"change",toEl:e,newIndex:ke,newDraggableIndex:bi,originalEvent:t})}if(t.preventDefault!==void 0&&t.cancelable&&t.preventDefault(),i=Fe(i,l.draggable,e,!0),v("dragOver"),_t.eventCanceled)return f;if(gt.contains(t.target)||i.animated&&i.animatingX&&i.animatingY||S._ignoreWhileAnimating===i)return h(!1);if(Or=!1,m&&!l.disabled&&(u?o||(c=Yt!==zt):oe===this||(this.lastPutMode=Cr.checkPull(this,m,gt,t))&&d.checkPut(this,m,gt,t))){if(w=this._getDirection(t,i)==="vertical",n=Zt(gt),v("dragOverValid"),_t.eventCanceled)return f;if(c)return Yt=zt,r(),this._hideClone(),v("revert"),_t.eventCanceled||(qi?zt.insertBefore(gt,qi):zt.appendChild(gt)),h(!0);var A=bo(e,l.draggable);if(!A||Xd(t,w,this)&&!A.animated){if(A===gt)return h(!1);if(A&&e===t.target&&(i=A),i&&(a=Zt(i)),Pr(zt,e,gt,n,i,a,t,!!i)!==!1)return r(),A&&A.nextSibling?e.insertBefore(gt,A.nextSibling):e.appendChild(gt),Yt=e,b(),h(!0)}else if(A&&qd(t,w,this)){var D=Ps(e,0,l,!0);if(D===gt)return h(!1);if(i=D,a=Zt(i),Pr(zt,e,gt,n,i,a,t,!1)!==!1)return r(),e.insertBefore(gt,D),Yt=e,b(),h(!0)}else if(i.parentNode===e){a=Zt(i);var _=0,I,N=gt.parentNode!==e,H=!jd(gt.animated&>.toRect||n,i.animated&&i.toRect||a,w),j=w?"top":"left",K=mc(i,"top","top")||mc(gt,"top","top"),it=K?K.scrollTop:void 0;_s!==i&&(I=a[j],gn=!1,kr=!H&&l.invertSwap||N),_=Kd(t,i,a,w,H?1:l.swapThreshold,l.invertedSwapThreshold==null?l.swapThreshold:l.invertedSwapThreshold,kr,_s===i);var ot;if(_!==0){var X=Pe(gt);do X-=_,ot=Yt.children[X];while(ot&&(Et(ot,"display")==="none"||ot===kt))}if(_===0||ot===i)return h(!1);_s=i,fn=_;var z=i.nextElementSibling,W=!1;W=_===1;var Y=Pr(zt,e,gt,n,i,a,t,W);if(Y!==!1)return(Y===1||Y===-1)&&(W=Y===1),uo=!0,setTimeout(Gd,30),r(),W&&!z?e.appendChild(gt):i.parentNode.insertBefore(gt,W?z:i),K&&kc(K,0,it-K.scrollTop),Yt=gt.parentNode,I!==void 0&&!kr&&(Rr=Math.abs(I-Zt(i)[j])),b(),h(!0)}if(e.contains(gt))return h(!1)}return!1},_ignoreWhileAnimating:null,_offMoveEvents:function(){It(document,"mousemove",this._onTouchMove),It(document,"touchmove",this._onTouchMove),It(document,"pointermove",this._onTouchMove),It(document,"dragover",Gi),It(document,"mousemove",Gi),It(document,"touchmove",Gi)},_offUpEvents:function(){var t=this.el.ownerDocument;It(t,"mouseup",this._onDrop),It(t,"touchend",this._onDrop),It(t,"pointerup",this._onDrop),It(t,"pointercancel",this._onDrop),It(t,"touchcancel",this._onDrop),It(document,"selectstart",this)},_onDrop:function(t){var e=this.el,i=this.options;if(ke=Pe(gt),bi=Pe(gt,i.draggable),we("drop",this,{evt:t}),Yt=gt&>.parentNode,ke=Pe(gt),bi=Pe(gt,i.draggable),_t.eventCanceled){this._nulling();return}Cs=!1,kr=!1,gn=!1,clearInterval(this._loopId),clearTimeout(this._dragStartTimer),po(this.cloneId),po(this._dragStartId),this.nativeDraggable&&(It(document,"drop",this),It(e,"dragstart",this._onDragStart)),this._offMoveEvents(),this._offUpEvents(),dn&&Et(document.body,"user-select",""),Et(gt,"transform",""),t&&(ln&&(t.cancelable&&t.preventDefault(),!i.dropBubble&&t.stopPropagation()),kt&&kt.parentNode&&kt.parentNode.removeChild(kt),(zt===Yt||oe&&oe.lastPutMode!=="clone")&&qt&&qt.parentNode&&qt.parentNode.removeChild(qt),gt&&(this.nativeDraggable&&It(gt,"dragend",this),oo(gt),gt.style["will-change"]="",ln&&!Cs&&Ce(gt,oe?oe.options.ghostClass:this.options.ghostClass,!1),Ce(gt,this.options.chosenClass,!1),me({sortable:this,name:"unchoose",toEl:Yt,newIndex:null,newDraggableIndex:null,originalEvent:t}),zt!==Yt?(ke>=0&&(me({rootEl:Yt,name:"add",toEl:Yt,fromEl:zt,originalEvent:t}),me({sortable:this,name:"remove",toEl:Yt,originalEvent:t}),me({rootEl:Yt,name:"sort",toEl:Yt,fromEl:zt,originalEvent:t}),me({sortable:this,name:"sort",toEl:Yt,originalEvent:t})),oe&&oe.save()):ke!==ks&&ke>=0&&(me({sortable:this,name:"update",toEl:Yt,originalEvent:t}),me({sortable:this,name:"sort",toEl:Yt,originalEvent:t})),_t.active&&((ke==null||ke===-1)&&(ke=ks,bi=pn),me({sortable:this,name:"end",toEl:Yt,originalEvent:t}),this.save()))),this._nulling()},_nulling:function(){we("nulling",this),zt=gt=Yt=kt=qi=qt=Mr=yi=Wi=Le=ln=ke=bi=ks=pn=_s=fn=oe=Cr=_t.dragged=_t.ghost=_t.clone=_t.active=null,Br.forEach(function(t){t.checked=!0}),Br.length=no=ro=0},handleEvent:function(t){switch(t.type){case"drop":case"dragend":this._onDrop(t);break;case"dragenter":case"dragover":gt&&(this._onDragOver(t),Wd(t));break;case"selectstart":t.preventDefault();break}},toArray:function(){for(var t=[],e,i=this.el.children,n=0,a=i.length,c=this.options;n<a;n++)e=i[n],Fe(e,c.draggable,this.el,!1)&&t.push(e.getAttribute(c.dataIdAttr)||Jd(e));return t},sort:function(t,e){var i={},n=this.el;this.toArray().forEach(function(a,c){var l=n.children[c];Fe(l,this.options.draggable,n,!1)&&(i[a]=l)},this),e&&this.captureAnimationState(),t.forEach(function(a){i[a]&&(n.removeChild(i[a]),n.appendChild(i[a]))}),e&&this.animateAll()},save:function(){var t=this.options.store;t&&t.set&&t.set(this)},closest:function(t,e){return Fe(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=bn.modifyOption(this,t,e);typeof n<"u"?i[t]=n:i[t]=e,t==="group"&&Rc(i)},destroy:function(){we("destroy",this);var t=this.el;t[xe]=null,It(t,"mousedown",this._onTapStart),It(t,"touchstart",this._onTapStart),It(t,"pointerdown",this._onTapStart),this.nativeDraggable&&(It(t,"dragover",this),It(t,"dragenter",this)),Array.prototype.forEach.call(t.querySelectorAll("[draggable]"),function(e){e.removeAttribute("draggable")}),this._onDrop(),this._disableDelayedDragEvents(),Nr.splice(Nr.indexOf(this.el),1),this.el=t=null},_hideClone:function(){if(!yi){if(we("hideClone",this),_t.eventCanceled)return;Et(qt,"display","none"),this.options.removeCloneOnHide&&qt.parentNode&&qt.parentNode.removeChild(qt),yi=!0}},_showClone:function(t){if(t.lastPutMode!=="clone"){this._hideClone();return}if(yi){if(we("showClone",this),_t.eventCanceled)return;gt.parentNode==zt&&!this.options.group.revertClone?zt.insertBefore(qt,gt):qi?zt.insertBefore(qt,qi):zt.appendChild(qt),this.options.group.revertClone&&this.animate(gt,qt),Et(qt,"display",""),yi=!1}}};function Wd(s){s.dataTransfer&&(s.dataTransfer.dropEffect="move"),s.cancelable&&s.preventDefault()}function Pr(s,t,e,i,n,a,c,l){var d,m=s[xe],u=m.options.onMove,o;return window.CustomEvent&&!ni&&!mn?d=new CustomEvent("move",{bubbles:!0,cancelable:!0}):(d=document.createEvent("Event"),d.initEvent("move",!0,!0)),d.to=t,d.from=s,d.dragged=e,d.draggedRect=i,d.related=n||t,d.relatedRect=a||Zt(t),d.willInsertAfter=l,d.originalEvent=c,s.dispatchEvent(d),u&&(o=u.call(m,d,c)),o}function oo(s){s.draggable=!1}function Gd(){uo=!1}function qd(s,t,e){var i=Zt(Ps(e.el,0,e.options,!0)),n=Pc(e.el,e.options,kt),a=10;return t?s.clientX<n.left-a||s.clientY<i.top&&s.clientX<i.right:s.clientY<n.top-a||s.clientY<i.bottom&&s.clientX<i.left}function Xd(s,t,e){var i=Zt(bo(e.el,e.options.draggable)),n=Pc(e.el,e.options,kt),a=10;return t?s.clientX>n.right+a||s.clientY>i.bottom&&s.clientX>i.left:s.clientY>n.bottom+a||s.clientX>i.right&&s.clientY>i.top}function Kd(s,t,e,i,n,a,c,l){var d=i?s.clientY:s.clientX,m=i?e.height:e.width,u=i?e.top:e.left,o=i?e.bottom:e.right,p=!1;if(!c){if(l&&Rr<m*n){if(!gn&&(fn===1?d>u+m*a/2:d<o-m*a/2)&&(gn=!0),gn)p=!0;else if(fn===1?d<u+Rr:d>o-Rr)return-fn}else if(d>u+m*(1-n)/2&&d<o-m*(1-n)/2)return Yd(t)}return p=p||c,p&&(d<u+m*a/2||d>o-m*a/2)?d>u+m/2?1:-1:0}function Yd(s){return Pe(gt)<Pe(s)?1:-1}function Jd(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 Qd(s){Br.length=0;for(var t=s.getElementsByTagName("input"),e=t.length;e--;){var i=t[e];i.checked&&Br.push(i)}}function Ir(s){return setTimeout(s,0)}function po(s){return clearTimeout(s)}$r&&Lt(document,"touchmove",function(s){(_t.active||Cs)&&s.cancelable&&s.preventDefault()});_t.utils={on:Lt,off:It,css:Et,find:_c,is:function(t,e){return!!Fe(t,e,t,!1)},extend:Ld,throttle:Cc,closest:Fe,toggleClass:Ce,clone:Tc,index:Pe,nextTick:Ir,cancelNextTick:po,detectDirection:Mc,getChild:Ps,expando:xe};_t.get=function(s){return s[xe]};_t.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&&(_t.utils=Ge(Ge({},_t.utils),i.utils)),bn.mount(i)})};_t.create=function(s,t){return new _t(s,t)};_t.version=Rd;var Qt=[],cn,fo,go=!1,lo,co,Ur,hn;function Zd(){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?Lt(document,"dragover",this._handleAutoScroll):this.options.supportPointer?Lt(document,"pointermove",this._handleFallbackAutoScroll):i.touches?Lt(document,"touchmove",this._handleFallbackAutoScroll):Lt(document,"mousemove",this._handleFallbackAutoScroll)},dragOverCompleted:function(e){var i=e.originalEvent;!this.options.dragOverBubble&&!i.rootEl&&this._handleAutoScroll(i)},drop:function(){this.sortable.nativeDraggable?It(document,"dragover",this._handleAutoScroll):(It(document,"pointermove",this._handleFallbackAutoScroll),It(document,"touchmove",this._handleFallbackAutoScroll),It(document,"mousemove",this._handleFallbackAutoScroll)),xc(),Lr(),Fd()},nulling:function(){Ur=fo=cn=go=hn=lo=co=null,Qt.length=0},_handleFallbackAutoScroll:function(e){this._handleAutoScroll(e,!0)},_handleAutoScroll:function(e,i){var n=this,a=(e.touches?e.touches[0]:e).clientX,c=(e.touches?e.touches[0]:e).clientY,l=document.elementFromPoint(a,c);if(Ur=e,i||this.options.forceAutoScrollFallback||mn||ni||dn){ho(e,this.options,l,i);var d=vi(l,!0);go&&(!hn||a!==lo||c!==co)&&(hn&&xc(),hn=setInterval(function(){var m=vi(document.elementFromPoint(a,c),!0);m!==d&&(d=m,Lr()),ho(e,n.options,m,i)},10),lo=a,co=c)}else{if(!this.options.bubbleScroll||vi(l,!0)===We()){Lr();return}ho(e,this.options,vi(l,!1),!1)}}},si(s,{pluginName:"scroll",initializeByDefault:!0})}function Lr(){Qt.forEach(function(s){clearInterval(s.pid)}),Qt=[]}function xc(){clearInterval(hn)}var ho=Cc(function(s,t,e,i){if(t.scroll){var n=(s.touches?s.touches[0]:s).clientX,a=(s.touches?s.touches[0]:s).clientY,c=t.scrollSensitivity,l=t.scrollSpeed,d=We(),m=!1,u;fo!==e&&(fo=e,Lr(),cn=t.scroll,u=t.scrollFn,cn===!0&&(cn=vi(e,!0)));var o=0,p=cn;do{var w=p,S=Zt(w),f=S.top,v=S.bottom,r=S.left,h=S.right,b=S.width,A=S.height,D=void 0,_=void 0,I=w.scrollWidth,N=w.scrollHeight,H=Et(w),j=w.scrollLeft,K=w.scrollTop;w===d?(D=b<I&&(H.overflowX==="auto"||H.overflowX==="scroll"||H.overflowX==="visible"),_=A<N&&(H.overflowY==="auto"||H.overflowY==="scroll"||H.overflowY==="visible")):(D=b<I&&(H.overflowX==="auto"||H.overflowX==="scroll"),_=A<N&&(H.overflowY==="auto"||H.overflowY==="scroll"));var it=D&&(Math.abs(h-n)<=c&&j+b<I)-(Math.abs(r-n)<=c&&!!j),ot=_&&(Math.abs(v-a)<=c&&K+A<N)-(Math.abs(f-a)<=c&&!!K);if(!Qt[o])for(var X=0;X<=o;X++)Qt[X]||(Qt[X]={});(Qt[o].vx!=it||Qt[o].vy!=ot||Qt[o].el!==w)&&(Qt[o].el=w,Qt[o].vx=it,Qt[o].vy=ot,clearInterval(Qt[o].pid),(it!=0||ot!=0)&&(m=!0,Qt[o].pid=setInterval(function(){i&&this.layer===0&&_t.active._onTouchMove(Ur);var z=Qt[this.layer].vy?Qt[this.layer].vy*l:0,W=Qt[this.layer].vx?Qt[this.layer].vx*l:0;typeof u=="function"&&u.call(_t.dragged.parentNode[xe],W,z,s,Ur,Qt[this.layer].el)!=="continue"||kc(Qt[this.layer].el,W,z)}.bind({layer:o}),24))),o++}while(t.bubbleScroll&&p!==d&&(p=vi(p,!1)));go=m}},30),Fc=function(t){var e=t.originalEvent,i=t.putSortable,n=t.dragEl,a=t.activeSortable,c=t.dispatchSortableEvent,l=t.hideGhostForTarget,d=t.unhideGhostForTarget;if(e){var m=i||a;l();var u=e.changedTouches&&e.changedTouches.length?e.changedTouches[0]:e,o=document.elementFromPoint(u.clientX,u.clientY);d(),m&&!m.el.contains(o)&&(c("spill"),this.onSpill({dragEl:n,putSortable:i}))}};function yo(){}yo.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=Ps(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:Fc};si(yo,{pluginName:"revertOnSpill"});function vo(){}vo.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:Fc};si(vo,{pluginName:"removeOnSpill"});_t.mount(new Zd);_t.mount(vo,yo);var Oc=_t;var Ds,yn,vn,Hr,yu={976:(s,t,e)=>{e.d(t,{AnnotationLayer:()=>T,FreeTextAnnotationElement:()=>j,InkAnnotationElement:()=>Y,StampAnnotationElement:()=>G});var i=e(292),n=e(419),a=e(792);function c(R){return Math.floor(255*Math.max(0,Math.min(1,R))).toString(16).padStart(2,"0")}function l(R){return Math.max(0,Math.min(255,255*R))}class d{static CMYK_G([g,y,C,k]){return["G",1-Math.min(1,.3*g+.59*C+.11*y+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 y=c(g);return`#${y}${y}${y}`}static RGB_G([g,y,C]){return["G",.3*g+.59*y+.11*C]}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,y,C,k]){return["RGB",1-Math.min(1,g+k),1-Math.min(1,C+k),1-Math.min(1,y+k)]}static CMYK_rgb([g,y,C,k]){return[l(1-Math.min(1,g+k)),l(1-Math.min(1,C+k)),l(1-Math.min(1,y+k))]}static CMYK_HTML(g){let y=this.CMYK_RGB(g).slice(1);return this.RGB_HTML(y)}static RGB_CMYK([g,y,C]){let k=1-g,O=1-y,M=1-C;return["CMYK",k,O,M,Math.min(k,O,M)]}}var m=e(284);let u=1e3,o=new WeakSet;function p(R){return{width:R[2]-R[0],height:R[3]-R[1]}}class w{static create(g){switch(g.data.annotationType){case i.AnnotationType.LINK:return new f(g);case i.AnnotationType.TEXT:return new v(g);case i.AnnotationType.WIDGET:switch(g.data.fieldType){case"Tx":return new h(g);case"Btn":return g.data.radioButton?new D(g):g.data.checkBox?new A(g):new _(g);case"Ch":return new I(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 j(g);case i.AnnotationType.LINE:return new K(g);case i.AnnotationType.SQUARE:return new it(g);case i.AnnotationType.CIRCLE:return new ot(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 z(g);case i.AnnotationType.HIGHLIGHT:return new et(g);case i.AnnotationType.UNDERLINE:return new rt(g);case i.AnnotationType.SQUIGGLY:return new ct(g);case i.AnnotationType.STRIKEOUT:return new st(g);case i.AnnotationType.STAMP:return new G(g);case i.AnnotationType.FILEATTACHMENT:return new x(g);default:return new S(g)}}}class S{#t=!1;constructor(g,{isRenderable:y=!1,ignoreBorder:C=!1,createQuadrilaterals:k=!1}={}){this.isRenderable=y,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,y&&(this.container=this._createContainer(C)),k&&this._createQuadrilaterals()}static _hasPopupData({titleObj:g,contentsObj:y,richText:C}){return!!(g?.str||y?.str||C?.str)}get hasPopupData(){return S._hasPopupData(this.data)}_createContainer(g){let{data:y,parent:{page:C,viewport:k}}=this,O=document.createElement("section");O.setAttribute("data-annotation-id",y.id),this instanceof r||(O.tabIndex=u),O.style.zIndex=this.parent.zIndex++,y.popupRef&&O.setAttribute("aria-haspopup","dialog"),y.alternativeText&&(O.title=y.alternativeText),y.noRotate&&O.classList.add("norotate");let{pageWidth:M,pageHeight:E,pageX:L,pageY:$}=k.rawDims;if(!y.rect||this instanceof N){let{rotation:Q}=y;return y.hasOwnCanvas||Q===0||this.setRotation(Q,O),O}let{width:U,height:P}=p(y.rect),F=i.Util.normalizeRect([y.rect[0],C.view[3]-y.rect[1]+C.view[1],y.rect[2],C.view[3]-y.rect[3]+C.view[1]]);if(!g&&y.borderStyle.width>0){O.style.borderWidth=`${y.borderStyle.width}px`;let Q=y.borderStyle.horizontalCornerRadius,Z=y.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 D){let nt=`calc(${U}px * var(--scale-factor)) / calc(${P}px * var(--scale-factor))`;O.style.borderRadius=nt}switch(y.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=y.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]-$)/E+"%";let{rotation:V}=y;return y.hasOwnCanvas||V===0?(O.style.width=100*U/M+"%",O.style.height=100*P/E+"%"):this.setRotation(V,O),O}setRotation(g,y=this.container){if(!this.data.rect)return;let{pageWidth:C,pageHeight:k}=this.parent.viewport.rawDims,{width:O,height:M}=p(this.data.rect),E,L;g%180==0?(E=100*O/C,L=100*M/k):(E=100*M/C,L=100*O/k),y.style.width=`${E}%`,y.style.height=`${L}%`,y.setAttribute("data-main-rotation",(360-g)%360)}get _commonActions(){let g=(y,C,k)=>{let O=k.detail[y],M=O[0],E=O.slice(1);k.target.style[C]=d[`${M}_HTML`](E),this.annotationStorage.setValue(this.data.id,{[C]:d[`${M}_rgb`](E)})};return(0,i.shadow)(this,"_commonActions",{display:y=>{let{display:C}=y.detail,k=C%2==1;this.container.style.visibility=k?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:k,noPrint:C===1||C===2})},print:y=>{this.annotationStorage.setValue(this.data.id,{noPrint:!y.detail.print})},hidden:y=>{let{hidden:C}=y.detail;this.container.style.visibility=C?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:C,noView:C})},focus:y=>{setTimeout((()=>y.target.focus({preventScroll:!1})),0)},userName:y=>{y.target.title=y.detail.userName},readonly:y=>{y.target.disabled=y.detail.readonly},required:y=>{this._setRequired(y.target,y.detail.required)},bgColor:y=>{g("bgColor","backgroundColor",y)},fillColor:y=>{g("fillColor","backgroundColor",y)},fgColor:y=>{g("fgColor","color",y)},textColor:y=>{g("textColor","color",y)},borderColor:y=>{g("borderColor","borderColor",y)},strokeColor:y=>{g("strokeColor","borderColor",y)},rotation:y=>{let C=y.detail.rotation;this.setRotation(C),this.annotationStorage.setValue(this.data.id,{rotation:C})}})}_dispatchEventFromSandbox(g,y){let C=this._commonActions;for(let k of Object.keys(y.detail))(g[k]||C[k])?.(y)}_setDefaultPropertiesFromJS(g){if(!this.enableScripting)return;let y=this.annotationStorage.getRawValue(this.data.id);if(!y)return;let C=this._commonActions;for(let[k,O]of Object.entries(y)){let M=C[k];M&&(M({detail:{[k]:O},target:g}),delete y[k])}}_createQuadrilaterals(){if(!this.container)return;let{quadPoints:g}=this.data;if(!g)return;let[y,C,k,O]=this.data.rect;if(g.length===1){let[,{x:Z,y:tt},{x:nt,y:pt}]=g[0];if(k===Z&&O===tt&&y===nt&&C===pt)return}let{style:M}=this.container,E;if(this.#t){let{borderColor:Z,borderWidth:tt}=M;M.borderWidth=0,E=["url('data:image/svg+xml;utf8,",'<svg xmlns="http://www.w3.org/2000/svg"',' preserveAspectRatio="none" viewBox="0 0 1 1">',`<g fill="transparent" stroke="${Z}" stroke-width="${tt}">`],this.container.classList.add("hasBorder")}let L=k-y,$=O-C,{svgFactory:U}=this,P=U.createElement("svg");P.classList.add("quadrilateralsContainer"),P.setAttribute("width",0),P.setAttribute("height",0);let F=U.createElement("defs");P.append(F);let V=U.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 g){let dt=U.createElement("rect"),lt=(nt-y)/L,wt=(O-tt)/$,Tt=(Z-nt)/L,xt=(tt-pt)/$;dt.setAttribute("x",lt),dt.setAttribute("y",wt),dt.setAttribute("width",Tt),dt.setAttribute("height",xt),V.append(dt),E?.push(`<rect vector-effect="non-scaling-stroke" x="${lt}" y="${wt}" width="${Tt}" height="${xt}"/>`)}this.#t&&(E.push("</g></svg>')"),M.backgroundImage=E.join("")),this.container.append(P),this.container.style.clipPath=`url(#${Q})`}_createPopup(){let{container:g,data:y}=this;g.setAttribute("aria-haspopup","dialog");let C=new N({data:{color:y.color,titleObj:y.titleObj,modificationDate:y.modificationDate,contentsObj:y.contentsObj,richText:y.richText,parentRect:y.rect,borderStyle:0,id:`popup_${y.id}`,rotation:y.rotation},parent:this.parent,elements:[this]});this.parent.div.append(C.render())}render(){(0,i.unreachable)("Abstract method `AnnotationElement.render` called")}_getElementsByName(g,y=null){let C=[];if(this._fieldObjects){let k=this._fieldObjects[g];if(k)for(let{page:O,id:M,exportValues:E}of k){if(O===-1||M===y)continue;let L=typeof E=="string"?E:null,$=document.querySelector(`[data-element-id="${M}"]`);!$||o.has($)?C.push({id:M,exportValue:L,domElement:$}):(0,i.warn)(`_getElementsByName - element not allowed: ${M}`)}return C}for(let k of document.getElementsByName(g)){let{exportValue:O}=k,M=k.getAttribute("data-element-id");M!==y&&o.has(k)&&C.push({id:M,exportValue:O,domElement:k})}return C}show(){this.container&&(this.container.hidden=!1),this.popup?.maybeShow()}hide(){this.container&&(this.container.hidden=!0),this.popup?.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){let g=this.getElementsToTriggerPopup();if(Array.isArray(g))for(let y of g)y.classList.add("highlightArea");else g.classList.add("highlightArea")}get _isEditable(){return!1}_editOnDoubleClick(){if(!this._isEditable)return;let{annotationEditorType:g,data:{id:y}}=this;this.container.addEventListener("dblclick",(()=>{this.linkService.eventBus?.dispatch("switchannotationeditormode",{source:this,mode:g,editId:y})}))}}class f extends S{constructor(g,y=null){super(g,{isRenderable:!0,ignoreBorder:!!y?.ignoreBorder,createQuadrilaterals:!0}),this.isTooltipOnly=g.data.isTooltipOnly}render(){let{data:g,linkService:y}=this,C=document.createElement("a");C.setAttribute("data-element-id",g.id);let k=!1;return g.url?(y.addLinkAttributes(C,g.url,g.newWindow),k=!0):g.action?(this._bindNamedAction(C,g.action),k=!0):g.attachment?(this.#e(C,g.attachment,g.attachmentDest),k=!0):g.setOCGState?(this.#i(C,g.setOCGState),k=!0):g.dest?(this._bindLink(C,g.dest),k=!0):(g.actions&&(g.actions.Action||g.actions["Mouse Up"]||g.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(C,g),k=!0),g.resetForm?(this._bindResetFormAction(C,g.resetForm),k=!0):this.isTooltipOnly&&!k&&(this._bindLink(C,""),k=!0)),this.container.classList.add("linkAnnotation"),k&&this.container.append(C),this.container}#t(){this.container.setAttribute("data-internal-link","")}_bindLink(g,y){g.href=this.linkService.getDestinationHash(y),g.onclick=()=>(y&&this.linkService.goToDestination(y),!1),(y||y==="")&&this.#t()}_bindNamedAction(g,y){g.href=this.linkService.getAnchorUrl(""),g.onclick=()=>(this.linkService.executeNamedAction(y),!1),this.#t()}#e(g,y,C=null){g.href=this.linkService.getAnchorUrl(""),g.onclick=()=>(this.downloadManager?.openOrDownloadData(y.content,y.filename,C),!1),this.#t()}#i(g,y){g.href=this.linkService.getAnchorUrl(""),g.onclick=()=>(this.linkService.executeSetOCGState(y),!1),this.#t()}_bindJSAction(g,y){g.href=this.linkService.getAnchorUrl("");let C=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(let k of Object.keys(y.actions)){let O=C.get(k);O&&(g[O]=()=>(this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:y.id,name:k}}),!1))}g.onclick||(g.onclick=()=>!1),this.#t()}_bindResetFormAction(g,y){let C=g.onclick;C||(g.href=this.linkService.getAnchorUrl("")),this.#t(),this._fieldObjects?g.onclick=()=>{C?.();let{fields:k,refs:O,include:M}=y,E=[];if(k.length!==0||O.length!==0){let U=new Set(O);for(let P of k){let F=this._fieldObjects[P]||[];for(let{id:V}of F)U.add(V)}for(let P of Object.values(this._fieldObjects))for(let F of P)U.has(F.id)===M&&E.push(F)}else for(let U of Object.values(this._fieldObjects))E.push(...U);let L=this.annotationStorage,$=[];for(let U of E){let{id:P}=U;switch($.push(P),U.type){case"text":{let V=U.defaultValue||"";L.setValue(P,{value:V});break}case"checkbox":case"radiobutton":{let V=U.defaultValue===U.exportValues;L.setValue(P,{value:V});break}case"combobox":case"listbox":{let V=U.defaultValue||"";L.setValue(P,{value:V});break}default:continue}let F=document.querySelector(`[data-element-id="${P}"]`);F&&(o.has(F)?F.dispatchEvent(new Event("resetform")):(0,i.warn)(`_bindResetFormAction - element not allowed: ${P}`))}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.'),C||(g.onclick=()=>!1))}}class v extends S{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 S{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,y,C,k,O){C.includes("mouse")?g.addEventListener(C,(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(C,(M=>{if(C==="blur"){if(!y.focused||!M.relatedTarget)return;y.focused=!1}else if(C==="focus"){if(y.focused)return;y.focused=!0}O&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:k,value:O(M)}})}))}_setEventListeners(g,y,C,k){for(let[O,M]of C)(M==="Action"||this.data.actions?.[M])&&(M!=="Focus"&&M!=="Blur"||(y||={focused:!1}),this._setEventListener(g,y,O,M,k),M!=="Focus"||this.data.actions?.Blur?M!=="Blur"||this.data.actions?.Focus||this._setEventListener(g,y,"focus","Focus",null):this._setEventListener(g,y,"blur","Blur",null))}_setBackgroundColor(g){let y=this.data.backgroundColor||null;g.style.backgroundColor=y===null?"transparent":i.Util.makeHexColor(y[0],y[1],y[2])}_setTextStyle(g){let y=["left","center","right"],{fontColor:C}=this.data.defaultAppearanceData,k=this.data.defaultAppearanceData.fontSize||9,O=g.style,M,E=L=>Math.round(10*L)/10;if(this.data.multiLine){let L=Math.abs(this.data.rect[3]-this.data.rect[1]-2),$=L/(Math.round(L/(i.LINE_FACTOR*k))||1);M=Math.min(k,E($/i.LINE_FACTOR))}else{let L=Math.abs(this.data.rect[3]-this.data.rect[1]-2);M=Math.min(k,E(L/i.LINE_FACTOR))}O.fontSize=`calc(${M}px * var(--scale-factor))`,O.color=i.Util.makeHexColor(C[0],C[1],C[2]),this.data.textAlignment!==null&&(O.textAlign=y[this.data.textAlignment])}_setRequired(g,y){y?g.setAttribute("required",!0):g.removeAttribute("required"),g.setAttribute("aria-required",y)}}class h extends r{constructor(g){super(g,{isRenderable:g.renderForms||g.data.hasOwnCanvas||!g.data.hasAppearance&&!!g.data.fieldValue})}setPropertyOnSiblings(g,y,C,k){let O=this.annotationStorage;for(let M of this._getElementsByName(g.name,g.id))M.domElement&&(M.domElement[y]=C),O.setValue(M.id,{[k]:C})}render(){let g=this.annotationStorage,y=this.data.id;this.container.classList.add("textWidgetAnnotation");let C=null;if(this.renderForms){let k=g.getValue(y,{value:this.data.fieldValue}),O=k.value||"",M=g.getValue(y,{charLimit:this.data.maxLen}).charLimit;M&&O.length>M&&(O=O.slice(0,M));let E=k.formattedValue||this.data.textContent?.join(`
|
|
5
|
-
`)||null;E&&this.data.comb&&(E=E.replaceAll(/\s+/g,""));let L={userValue:O,formattedValue:E,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(C=document.createElement("textarea"),C.textContent=E??O,this.data.doNotScroll&&(C.style.overflowY="hidden")):(C=document.createElement("input"),C.type="text",C.setAttribute("value",E??O),this.data.doNotScroll&&(C.style.overflowX="hidden")),this.data.hasOwnCanvas&&(C.hidden=!0),o.add(C),C.setAttribute("data-element-id",y),C.disabled=this.data.readOnly,C.name=this.data.fieldName,C.tabIndex=u,this._setRequired(C,this.data.required),M&&(C.maxLength=M),C.addEventListener("input",(U=>{g.setValue(y,{value:U.target.value}),this.setPropertyOnSiblings(C,"value",U.target.value,"value"),L.formattedValue=null})),C.addEventListener("resetform",(U=>{let P=this.data.defaultFieldValue??"";C.value=L.userValue=P,L.formattedValue=null}));let $=U=>{let{formattedValue:P}=L;P!=null&&(U.target.value=P),U.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){C.addEventListener("focus",(P=>{if(L.focused)return;let{target:F}=P;L.userValue&&(F.value=L.userValue),L.lastCommittedValue=F.value,L.commitKey=1,this.data.actions?.Focus||(L.focused=!0)})),C.addEventListener("updatefromsandbox",(P=>{this.showElementAndHideCanvas(P.target);let F={value(V){L.userValue=V.detail.value??"",g.setValue(y,{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(y,{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,g.setValue(y,{value:tt}),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:y,name:"Keystroke",value:tt,willCommit:!0,commitKey:1,selStart:Z.selectionStart,selEnd:Z.selectionEnd}}))}};this._dispatchEventFromSandbox(F,P)})),C.addEventListener("keydown",(P=>{L.commitKey=1;let F=-1;if(P.key==="Escape"?F=0:P.key!=="Enter"||this.data.multiLine?P.key==="Tab"&&(L.commitKey=3):F=2,F===-1)return;let{value:V}=P.target;L.lastCommittedValue!==V&&(L.lastCommittedValue=V,L.userValue=V,this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:y,name:"Keystroke",value:V,willCommit:!0,commitKey:F,selStart:P.target.selectionStart,selEnd:P.target.selectionEnd}}))}));let U=$;$=null,C.addEventListener("blur",(P=>{if(!L.focused||!P.relatedTarget)return;this.data.actions?.Blur||(L.focused=!1);let{value:F}=P.target;L.userValue=F,L.lastCommittedValue!==F&&this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:y,name:"Keystroke",value:F,willCommit:!0,commitKey:L.commitKey,selStart:P.target.selectionStart,selEnd:P.target.selectionEnd}}),U(P)})),this.data.actions?.Keystroke&&C.addEventListener("beforeinput",(P=>{L.lastCommittedValue=null;let{data:F,target:V}=P,{value:Q,selectionStart:Z,selectionEnd:tt}=V,nt=Z,pt=tt;switch(P.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)}P.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:y,name:"Keystroke",value:Q,change:F||"",willCommit:!1,selStart:nt,selEnd:pt}})})),this._setEventListeners(C,L,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(P=>P.target.value))}if($&&C.addEventListener("blur",$),this.data.comb){let U=(this.data.rect[2]-this.data.rect[0])/M;C.classList.add("comb"),C.style.letterSpacing=`calc(${U}px * var(--scale-factor) - 1ch)`}}else C=document.createElement("div"),C.textContent=this.data.fieldValue,C.style.verticalAlign="middle",C.style.display="table-cell",this.data.hasOwnCanvas&&(C.hidden=!0);return this._setTextStyle(C),this._setBackgroundColor(C),this._setDefaultPropertiesFromJS(C),this.container.append(C),this.container}}class b extends r{constructor(g){super(g,{isRenderable:!!g.data.hasOwnCanvas})}}class A extends r{constructor(g){super(g,{isRenderable:g.renderForms})}render(){let g=this.annotationStorage,y=this.data,C=y.id,k=g.getValue(C,{value:y.exportValue===y.fieldValue}).value;typeof k=="string"&&(k=k!=="Off",g.setValue(C,{value:k})),this.container.classList.add("buttonWidgetAnnotation","checkBox");let O=document.createElement("input");return o.add(O),O.setAttribute("data-element-id",C),O.disabled=y.readOnly,this._setRequired(O,this.data.required),O.type="checkbox",O.name=y.fieldName,k&&O.setAttribute("checked",!0),O.setAttribute("exportValue",y.exportValue),O.tabIndex=u,O.addEventListener("change",(M=>{let{name:E,checked:L}=M.target;for(let $ of this._getElementsByName(E,C)){let U=L&&$.exportValue===y.exportValue;$.domElement&&($.domElement.checked=U),g.setValue($.id,{value:U})}g.setValue(C,{value:L})})),O.addEventListener("resetform",(M=>{let E=y.defaultFieldValue||"Off";M.target.checked=E===y.exportValue})),this.enableScripting&&this.hasJSActions&&(O.addEventListener("updatefromsandbox",(M=>{let E={value(L){L.target.checked=L.detail.value!=="Off",g.setValue(C,{value:L.target.checked})}};this._dispatchEventFromSandbox(E,M)})),this._setEventListeners(O,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(M=>M.target.checked))),this._setBackgroundColor(O),this._setDefaultPropertiesFromJS(O),this.container.append(O),this.container}}class D extends r{constructor(g){super(g,{isRenderable:g.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");let g=this.annotationStorage,y=this.data,C=y.id,k=g.getValue(C,{value:y.fieldValue===y.buttonValue}).value;if(typeof k=="string"&&(k=k!==y.buttonValue,g.setValue(C,{value:k})),k)for(let M of this._getElementsByName(y.fieldName,C))g.setValue(M.id,{value:!1});let O=document.createElement("input");if(o.add(O),O.setAttribute("data-element-id",C),O.disabled=y.readOnly,this._setRequired(O,this.data.required),O.type="radio",O.name=y.fieldName,k&&O.setAttribute("checked",!0),O.tabIndex=u,O.addEventListener("change",(M=>{let{name:E,checked:L}=M.target;for(let $ of this._getElementsByName(E,C))g.setValue($.id,{value:!1});g.setValue(C,{value:L})})),O.addEventListener("resetform",(M=>{let E=y.defaultFieldValue;M.target.checked=E!=null&&E===y.buttonValue})),this.enableScripting&&this.hasJSActions){let M=y.buttonValue;O.addEventListener("updatefromsandbox",(E=>{let L={value:$=>{let U=M===$.detail.value;for(let P of this._getElementsByName($.target.name)){let F=U&&P.id===C;P.domElement&&(P.domElement.checked=F),g.setValue(P.id,{value:F})}}};this._dispatchEventFromSandbox(L,E)})),this._setEventListeners(O,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],(E=>E.target.checked))}return this._setBackgroundColor(O),this._setDefaultPropertiesFromJS(O),this.container.append(O),this.container}}class _ extends f{constructor(g){super(g,{ignoreBorder:g.data.hasAppearance})}render(){let g=super.render();g.classList.add("buttonWidgetAnnotation","pushButton");let y=g.lastChild;return this.enableScripting&&this.hasJSActions&&y&&(this._setDefaultPropertiesFromJS(y),y.addEventListener("updatefromsandbox",(C=>{this._dispatchEventFromSandbox({},C)}))),g}}class I extends r{constructor(g){super(g,{isRenderable:g.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");let g=this.annotationStorage,y=this.data.id,C=g.getValue(y,{value:this.data.fieldValue}),k=document.createElement("select");o.add(k),k.setAttribute("data-element-id",y),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",(U=>{let P=this.data.defaultFieldValue;for(let F of k.options)F.selected=F.value===P}));for(let U of this.data.options){let P=document.createElement("option");P.textContent=U.displayValue,P.value=U.exportValue,C.value.includes(U.exportValue)&&(P.setAttribute("selected",!0),O=!1),k.append(P)}let M=null;if(O){let U=document.createElement("option");U.value=" ",U.setAttribute("hidden",!0),U.setAttribute("selected",!0),k.prepend(U),M=()=>{U.remove(),k.removeEventListener("input",M),M=null},k.addEventListener("input",M)}let E=U=>{let P=U?"value":"textContent",{options:F,multiple:V}=k;return V?Array.prototype.filter.call(F,(Q=>Q.selected)).map((Q=>Q[P])):F.selectedIndex===-1?null:F[F.selectedIndex][P]},L=E(!1),$=U=>{let P=U.target.options;return Array.prototype.map.call(P,(F=>({displayValue:F.textContent,exportValue:F.value})))};return this.enableScripting&&this.hasJSActions?(k.addEventListener("updatefromsandbox",(U=>{let P={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(y,{value:E(!0)}),L=E(!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(y,{value:E(!0),items:$(F)}),L=E(!1)},clear(F){for(;k.length!==0;)k.remove(0);g.setValue(y,{value:null,items:[]}),L=E(!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),g.setValue(y,{value:E(!0),items:$(F)}),L=E(!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),g.setValue(y,{value:E(!0),items:$(F)}),L=E(!1)},indices(F){let V=new Set(F.detail.indices);for(let Q of F.target.options)Q.selected=V.has(Q.index);g.setValue(y,{value:E(!0)}),L=E(!1)},editable(F){F.target.disabled=!F.detail.editable}};this._dispatchEventFromSandbox(P,U)})),k.addEventListener("input",(U=>{let P=E(!0);g.setValue(y,{value:P}),U.preventDefault(),this.linkService.eventBus?.dispatch("dispatcheventinsandbox",{source:this,detail:{id:y,name:"Keystroke",value:L,changeEx:P,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"]],(U=>U.target.value))):k.addEventListener("input",(function(U){g.setValue(y,{value:E(!0)})})),this.data.combo&&this._setTextStyle(k),this._setBackgroundColor(k),this._setDefaultPropertiesFromJS(k),this.container.append(k),this.container}}class N extends S{constructor(g){let{data:y,elements:C}=g;super(g,{isRenderable:S._hasPopupData(y)}),this.elements=C}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}),y=[];for(let C of this.elements)C.popup=g,y.push(C.data.id),C.addHighlightArea();return this.container.setAttribute("aria-controls",y.map((C=>`${i.AnnotationPrefix}${C}`)).join(",")),this.container}}class H{#t=this.#m.bind(this);#e=this.#_.bind(this);#i=this.#S.bind(this);#n=this.#b.bind(this);#r=null;#s=null;#o=null;#l=null;#a=null;#h=null;#u=null;#d=!1;#c=null;#f=null;#g=null;#p=null;#y=!1;constructor({container:g,color:y,elements:C,titleObj:k,modificationDate:O,contentsObj:M,richText:E,parent:L,rect:$,parentRect:U,open:P}){this.#s=g,this.#p=k,this.#o=M,this.#g=E,this.#h=L,this.#r=y,this.#f=$,this.#u=U,this.#a=C,this.#l=n.PDFDateString.toDateObject(O),this.trigger=C.flatMap((F=>F.getElementsToTriggerPopup()));for(let F of this.trigger)F.addEventListener("click",this.#n),F.addEventListener("mouseenter",this.#i),F.addEventListener("mouseleave",this.#e),F.classList.add("popupTriggerArea");for(let F of C)F.container?.addEventListener("keydown",this.#t);this.#s.hidden=!0,P&&this.#b()}render(){if(this.#c)return;let{page:{view:g},viewport:{rawDims:{pageWidth:y,pageHeight:C,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((lt=>Math.floor(.7*(255-lt)+lt))))}let E=document.createElement("span");E.className="header";let L=document.createElement("h1");if(E.append(L),{dir:L.dir,str:L.textContent}=this.#p,M.append(E),this.#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()})),E.append(pt)}let $=this.#o,U=this.#g;if(!U?.str||$?.str&&$.str!==U.str){let pt=this._formatContents($);M.append(pt)}else m.XfaLayer.render({xfaHtml:U.html,intent:"richText",div:M}),M.lastChild.classList.add("richText","popupContent");let P=!!this.#u,F=P?this.#u:this.#f;for(let pt of this.#a)if(!F||i.Util.intersect(pt.data.rect,F)!==null){F=pt.data.rect,P=!0;break}let V=i.Util.normalizeRect([F[0],g[3]-F[1]+g[1],F[2],g[3]-F[3]+g[1]]),Q=P?F[2]-F[0]+5:0,Z=V[0]+Q,tt=V[1],{style:nt}=this.#s;nt.left=100*(Z-k)/y+"%",nt.top=100*(tt-O)/C+"%",this.#s.append(M)}_formatContents({str:g,dir:y}){let C=document.createElement("p");C.classList.add("popupContent"),C.dir=y;let k=g.split(/(?:\r\n?|\n)/);for(let O=0,M=k.length;O<M;++O){let E=k[O];C.append(document.createTextNode(E)),O<M-1&&C.append(document.createElement("br"))}return C}#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.#_(),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)}#_(){this.#s.classList.remove("focused"),!this.#d&&this.isVisible&&(this.#s.hidden=!0,this.#s.style.zIndex=parseInt(this.#s.style.zIndex)-1e3)}forceHide(){this.#y=this.isVisible,this.#y&&(this.#s.hidden=!0)}maybeShow(){this.#y&&(this.#y=!1,this.#s.hidden=!1)}get isVisible(){return this.#s.hidden===!1}}class j extends S{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 y of this.textContent){let C=document.createElement("span");C.textContent=y,g.append(C)}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 S{#t=null;constructor(g){super(g,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("lineAnnotation");let g=this.data,{width:y,height:C}=p(g.rect),k=this.svgFactory.create(y,C,!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 S{#t=null;constructor(g){super(g,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("squareAnnotation");let g=this.data,{width:y,height:C}=p(g.rect),k=this.svgFactory.create(y,C,!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",y-O),M.setAttribute("height",C-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 ot extends S{#t=null;constructor(g){super(g,{isRenderable:!0,ignoreBorder:!0})}render(){this.container.classList.add("circleAnnotation");let g=this.data,{width:y,height:C}=p(g.rect),k=this.svgFactory.create(y,C,!0),O=g.borderStyle.width,M=this.#t=this.svgFactory.createElement("svg:ellipse");return M.setAttribute("cx",y/2),M.setAttribute("cy",C/2),M.setAttribute("rx",y/2-O/2),M.setAttribute("ry",C/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 S{#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:y,height:C}=p(g.rect),k=this.svgFactory.create(y,C,!0),O=[];for(let E of g.vertices){let L=E.x-g.rect[0],$=g.rect[3]-E.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 z extends X{constructor(g){super(g),this.containerClassName="polygonAnnotation",this.svgElementName="svg:polygon"}}class W extends S{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 S{#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:y,height:C}=p(g.rect),k=this.svgFactory.create(y,C,!0);for(let O of g.inkLists){let M=[];for(let L of O){let $=L.x-g.rect[0],U=g.rect[3]-L.y;M.push(`${$},${U}`)}M=M.join(" ");let E=this.svgFactory.createElement(this.svgElementName);this.#t.push(E),E.setAttribute("points",M),E.setAttribute("stroke-width",g.borderStyle.width||1),E.setAttribute("stroke","transparent"),E.setAttribute("fill","transparent"),!g.popupRef&&this.hasPopupData&&this._createPopup(),k.append(E)}return this.container.append(k),this.container}getElementsToTriggerPopup(){return this.#t}addHighlightArea(){this.container.classList.add("highlightArea")}}class et extends S{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 rt extends S{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 ct extends S{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 st extends S{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 S{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 x extends S{#t=null;constructor(g){super(g,{isRenderable:!0});let{filename:y,content:C}=this.data.file;this.filename=(0,n.getFilenameFromUrl)(y,!0),this.content=C,this.linkService.eventBus?.dispatch("fileattachmentannotation",{source:this,filename:y,content:C})}render(){this.container.classList.add("fileAttachmentAnnotation");let{container:g,data:y}=this,C;y.hasAppearance||y.fillAlpha===0?C=document.createElement("div"):(C=document.createElement("img"),C.src=`${this.imageResourcesPath}annotation-${/paperclip/i.test(y.name)?"paperclip":"pushpin"}.svg`,y.fillAlpha&&y.fillAlpha<1&&(C.style=`filter: opacity(${Math.round(100*y.fillAlpha)}%);`)),C.addEventListener("dblclick",this.#e.bind(this)),this.#t=C;let{isMac:k}=i.FeatureTest.platform;return g.addEventListener("keydown",(O=>{O.key==="Enter"&&(k?O.metaKey:O.ctrlKey)&&this.#e()})),!y.popupRef&&this.hasPopupData?this._createPopup():C.classList.add("popupTriggerArea"),g.append(C),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:y,annotationCanvasMap:C,page:k,viewport:O}){this.div=g,this.#t=y,this.#e=C,this.page=k,this.viewport=O,this.zIndex=0}#n(g,y){let C=g.firstChild||g;C.id=`${i.AnnotationPrefix}${y}`,this.div.append(g),this.#t?.moveElementInDOM(this.div,g,C,!1)}async render(g){let{annotations:y}=g,C=this.div;(0,n.setLayerDimensions)(C,this.viewport);let k=new Map,O={data:null,layer:C,linkService:g.linkService,downloadManager:g.downloadManager,imageResourcesPath:g.imageResourcesPath||"",renderForms:g.renderForms!==!1,svgFactory:new n.DOMSVGFactory,annotationStorage:g.annotationStorage||new a.AnnotationStorage,enableScripting:g.enableScripting===!0,hasJSActions:g.hasJSActions,fieldObjects:g.fieldObjects,parent:this,elements:null};for(let M of y){if(M.noHTML)continue;let E=M.annotationType===i.AnnotationType.POPUP;if(E){let U=k.get(M.id);if(!U)continue;O.elements=U}else{let{width:U,height:P}=p(M.rect);if(U<=0||P<=0)continue}O.data=M;let L=w.create(O);if(!L.isRenderable)continue;if(!E&&M.popupRef){let U=k.get(M.popupRef);U?U.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 y=this.div;this.viewport=g,(0,n.setLayerDimensions)(y,{rotation:g.rotation}),this.#r(),y.hidden=!1}#r(){if(!this.#e)return;let g=this.div;for(let[y,C]of this.#e){let k=g.querySelector(`[data-annotation-id="${y}"]`);if(!k)continue;let{firstChild:O}=k;O?O.nodeName==="CANVAS"?O.replaceWith(C):O.before(C):k.append(C)}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:()=>d,SerializableEmpty:()=>c});var i=e(292),n=e(310),a=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,o){let p=this.#e.get(u);return p===void 0?o:Object.assign(o,p)}getRawValue(u){return this.#e.get(u)}remove(u){if(this.#e.delete(u),this.#e.size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(let o of this.#e.values())if(o instanceof n.AnnotationEditor)return;this.onAnnotationEditor(null)}}setValue(u,o){let p=this.#e.get(u),w=!1;if(p!==void 0)for(let[S,f]of Object.entries(o))p[S]!==f&&(w=!0,p[S]=f);else w=!0,this.#e.set(u,o);w&&this.#i(),o instanceof n.AnnotationEditor&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(o.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[o,p]of Object.entries(u))this.setValue(o,p)}get size(){return this.#e.size}#i(){this.#t||(this.#t=!0,typeof this.onSetModified=="function"&&this.onSetModified())}resetModified(){this.#t&&(this.#t=!1,typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new d(this)}get serializable(){if(this.#e.size===0)return c;let u=new Map,o=new a.MurmurHash3_64,p=[],w=Object.create(null),S=!1;for(let[f,v]of this.#e){let r=v instanceof n.AnnotationEditor?v.serialize(!1,w):v;r&&(u.set(f,r),o.update(`${f}:${JSON.stringify(r)}`),S||=!!r.bitmap)}if(S)for(let f of u.values())f.bitmap&&p.push(f.bitmap);return u.size>0?{map:u,hash:o.hexdigest(),transfer:p}:c}get editorStats(){let u=null,o=new Map;for(let p of this.#e.values()){if(!(p instanceof n.AnnotationEditor))continue;let w=p.telemetryFinalData;if(!w)continue;let{type:S}=w;o.has(S)||o.set(S,Object.getPrototypeOf(p).constructor),u||=Object.create(null);let f=u[S]||=new Map;for(let[v,r]of Object.entries(w)){if(v==="type")continue;let h=f.get(v);h||(h=new Map,f.set(v,h));let b=h.get(r)??0;h.set(r,b+1)}}for(let[p,w]of o)u[p]=w.computeTelemetryFinalData(u[p]);return u}}class d extends l{#t;constructor(u){super();let{map:o,hash:p,transfer:w}=u.serializable,S=structuredClone(o,w?{transfer:w}:null);this.#t={map:S,hash:p,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 ot=function(M){if(typeof M=="string"||M instanceof URL?M={url:M}:(M instanceof ArrayBuffer||ArrayBuffer.isView(M))&&(M={data:M}),typeof M!="object")throw new Error("Invalid parameter in getDocument, need parameter object.");if(!M.url&&!M.data&&!M.range)throw new Error("Invalid parameter object: need either .data, .range or .url");let E=new Y,{docId:L}=E,$=M.url?z(M.url):null,U=M.data?W(M.data):null,P=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:_,tt=M.worker instanceof x?M.worker:null,nt=M.verbosity,pt=typeof M.docBaseUrl!="string"||(0,l.isDataScheme)(M.docBaseUrl)?null:M.docBaseUrl,dt=typeof M.cMapUrl=="string"?M.cMapUrl:null,lt=M.cMapPacked!==!1,wt=M.CMapReaderFactory||j,Tt=typeof M.standardFontDataUrl=="string"?M.standardFontDataUrl:null,xt=M.StandardFontDataFactory||it,Dt=M.stopAtErrors!==!0,Rt=Number.isInteger(M.maxImageSize)&&M.maxImageSize>-1?M.maxImageSize:-1,Bt=M.isEvalSupported!==!1,Ht=typeof M.isOffscreenCanvasSupported=="boolean"?M.isOffscreenCanvasSupported:!a.isNodeJS,le=Number.isInteger(M.canvasMaxAreaInBytes)?M.canvasMaxAreaInBytes:-1,Se=typeof M.disableFontFace=="boolean"?M.disableFontFace:a.isNodeJS,Oe=M.fontExtraProperties===!0,Te=M.enableXfa===!0,De=M.ownerDocument||globalThis.document,ri=M.disableRange===!0,ai=M.disableStream===!0,ae=M.disableAutoFetch===!0,se=M.pdfBug===!0,oi=Q?Q.length:M.length??NaN,Qi=typeof M.useSystemFonts=="boolean"?M.useSystemFonts:!a.isNodeJS&&!Se,Me=typeof M.useWorkerFetch=="boolean"?M.useWorkerFetch:wt===l.DOMCMapReaderFactory&&xt===l.DOMStandardFontDataFactory&&dt&&Tt&&(0,l.isValidFetchUrl)(dt,document.baseURI)&&(0,l.isValidFetchUrl)(Tt,document.baseURI),te=M.canvasFactory||new H({ownerDocument:De}),kn=M.filterFactory||new K({docId:L,ownerDocument:De});(0,a.setVerbosityLevel)(nt);let Zi={canvasFactory:te,filterFactory:kn};if(Me||(Zi.cMapReaderFactory=new wt({baseUrl:dt,isCompressed:lt}),Zi.standardFontDataFactory=new xt({baseUrl:Tt})),!tt){let Be={verbosity:nt,port:p.GlobalWorkerOptions.workerPort};tt=Be.port?x.fromPort(Be):new x(Be),E._worker=tt}let Ne={docId:L,apiVersion:"4.1.392",data:U,password:V,disableAutoFetch:ae,rangeChunkSize:Z,length:oi,docBaseUrl:pt,enableXfa:Te,evaluatorOptions:{maxImageSize:Rt,disableFontFace:Se,ignoreErrors:Dt,isEvalSupported:Bt,isOffscreenCanvasSupported:Ht,canvasMaxAreaInBytes:le,fontExtraProperties:Oe,useSystemFonts:Qi,cMapUrl:Me?dt:null,standardFontDataUrl:Me?Tt:null}},Si={ignoreErrors:Dt,isEvalSupported:Bt,disableFontFace:Se,fontExtraProperties:Oe,enableXfa:Te,ownerDocument:De,disableAutoFetch:ae,pdfBug:se,styleElement:null};return tt.promise.then((function(){if(E.destroyed)throw new Error("Loading aborted");let Be=X(tt,Ne),Tn=new Promise((function(ts){let li;Q?li=new v.PDFDataTransportStream(Q,{disableRange:ri,disableStream:ai}):U||(li=(pe=>a.isNodeJS?(function(){return typeof fetch<"u"&&typeof Response<"u"&&"body"in Response.prototype})()&&(0,l.isValidFetchUrl)(pe.url)?new r.PDFFetchStream(pe):new b.PDFNodeStream(pe):(0,l.isValidFetchUrl)(pe.url)?new r.PDFFetchStream(pe):new h.PDFNetworkStream(pe))({url:$,length:oi,httpHeaders:P,withCredentials:F,rangeChunkSize:Z,disableRange:ri,disableStream:ai})),ts(li)}));return Promise.all([Be,Tn]).then((function([ts,li]){if(E.destroyed)throw new Error("Loading aborted");let pe=new w.MessageHandler(L,ts,tt.port),Pn=new T(pe,E,li,Si,Zi);E._transport=Pn,pe.send("Ready",null)}))})).catch(E._capability.reject),E},z=function(M){if(M instanceof URL)return M.href;try{return new URL(M,window.location).href}catch{if(a.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(a.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,a.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:()=>ot,version:()=>k});var a=e(292),c=e(792),l=e(419),d=e(10),m=e(573),u=e(923),o=e(814),p=e(164),w=e(178),S=e(62),f=e(626),v=e(585),r=e(94),h=e(457),b=e(786),A=e(50),D=i([m,b]);[m,b]=D.then?(await D)():D;let _=65536,I=100,N=5e3,H=a.isNodeJS?m.NodeCanvasFactory:l.DOMCanvasFactory,j=a.isNodeJS?m.NodeCMapReaderFactory:l.DOMCMapReaderFactory,K=a.isNodeJS?m.NodeFilterFactory:l.DOMFilterFactory,it=a.isNodeJS?m.NodeStandardFontDataFactory:l.DOMStandardFontDataFactory;async function X(M,E){if(M.destroyed)throw new Error("Worker was destroyed");let L=await M.messageHandler.sendWithPromise("GetDocRequest",E,E.data?[E.data.buffer]:null);if(M.destroyed)throw new Error("Worker was destroyed");return L}class 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(E){throw this._worker?.port&&delete this._worker._pendingDestroy,E}this._transport=null,this._worker&&(this._worker.destroy(),this._worker=null)}}class et{constructor(E,L,$=!1,U=null){this.length=E,this.initialData=L,this.progressiveDone=$,this.contentDispositionFilename=U,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(E){this._rangeListeners.push(E)}addProgressListener(E){this._progressListeners.push(E)}addProgressiveReadListener(E){this._progressiveReadListeners.push(E)}addProgressiveDoneListener(E){this._progressiveDoneListeners.push(E)}onDataRange(E,L){for(let $ of this._rangeListeners)$(E,L)}onDataProgress(E,L){this._readyCapability.promise.then((()=>{for(let $ of this._progressListeners)$(E,L)}))}onDataProgressiveRead(E){this._readyCapability.promise.then((()=>{for(let L of this._progressiveReadListeners)L(E)}))}onDataProgressiveDone(){this._readyCapability.promise.then((()=>{for(let E of this._progressiveDoneListeners)E()}))}transportReady(){this._readyCapability.resolve()}requestDataRange(E,L){(0,a.unreachable)("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class rt{constructor(E,L){this._pdfInfo=E,this._transport=L}get annotationStorage(){return this._transport.annotationStorage}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return(0,a.shadow)(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(E){return this._transport.getPage(E)}getPageIndex(E){return this._transport.getPageIndex(E)}getDestinations(){return this._transport.getDestinations()}getDestination(E){return this._transport.getDestination(E)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:E="display"}={}){let{renderingIntent:L}=this._transport.getRenderingIntent(E);return this._transport.getOptionalContentConfig(L)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(E=!1){return this._transport.startCleanup(E||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}class ct{#t=null;#e=!1;constructor(E,L,$,U=!1){this._pageIndex=E,this._pageInfo=L,this._transport=$,this._stats=U?new l.StatTimer:null,this._pdfBug=U,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:E,rotation:L=this.rotate,offsetX:$=0,offsetY:U=0,dontFlip:P=!1}={}){return new l.PageViewport({viewBox:this.view,scale:E,rotation:L,offsetX:$,offsetY:U,dontFlip:P})}getAnnotations({intent:E="display"}={}){let{renderingIntent:L}=this._transport.getRenderingIntent(E);return this._transport.getAnnotations(this._pageIndex,L)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return(0,a.shadow)(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){return this._transport._htmlForXfa?.children[this._pageIndex]||null}render({canvasContext:E,viewport:L,intent:$="display",annotationMode:U=a.AnnotationMode.ENABLE,transform:P=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&a.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=Rt=>{lt.renderTasks.delete(xt),(this._maybeCleanupAfterRender||wt)&&(this.#e=!0),this.#i(!wt),Rt?(xt.capability.reject(Rt),this._abortOperatorList({intentState:lt,reason:Rt instanceof Error?Rt:new Error(Rt)})):xt.capability.resolve(),this._stats?.timeEnd("Rendering"),this._stats?.timeEnd("Overall")},xt=new C({callback:Tt,params:{canvasContext:E,viewport:L,transform:P,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 Dt=xt.task;return Promise.all([lt.displayReadyCapability.promise,V]).then((([Rt,Bt])=>{if(this.destroyed)Tt();else{if(this._stats?.time("Rendering"),!(Bt.renderingIntent&pt))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");xt.initializeGraphics({transparency:Rt,optionalContentConfig:Bt}),xt.operatorListChanged()}})).catch(Tt),Dt}getOperatorList({intent:E="display",annotationMode:L=a.AnnotationMode.ENABLE,printAnnotationStorage:$=null}={}){let U=this._transport.getRenderingIntent(E,L,$,!0),P,F=this._intentStates.get(U.cacheKey);return F||(F=Object.create(null),this._intentStates.set(U.cacheKey,F)),F.opListReadCapability||(P=Object.create(null),P.operatorListChanged=function(){F.operatorList.lastChunk&&(F.opListReadCapability.resolve(F.operatorList),F.renderTasks.delete(P))},F.opListReadCapability=Promise.withResolvers(),(F.renderTasks||=new Set).add(P),F.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},this._stats?.time("Page Request"),this._pumpOperatorList(U)),F.opListReadCapability.promise}streamTextContent({includeMarkedContent:E=!1,disableNormalization:L=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:E===!0,disableNormalization:L===!0},{highWaterMark:100,size:$=>$.items.length})}getTextContent(E={}){if(this._transport._htmlForXfa)return this.getXfa().then(($=>A.XfaText.textContent($)));let L=this.streamTextContent(E);return new Promise((function($,U){let P=L.getReader(),F={items:[],styles:Object.create(null)};(function V(){P.read().then((function({value:Q,done:Z}){Z?$(F):(Object.assign(F.styles,Q.styles),F.items.push(...Q.items),V())}),U)})()}))}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;let E=[];for(let L of this._intentStates.values())if(this._abortOperatorList({intentState:L,reason:new Error("Page was destroyed."),force:!0}),!L.opListReadCapability)for(let $ of L.renderTasks)E.push($.completed),$.cancel();return this.objs.clear(),this.#e=!1,this.#n(),Promise.all(E)}cleanup(E=!1){this.#e=!0;let L=this.#i(!1);return E&&L&&(this._stats&&=new l.StatTimer),L}#i(E=!1){if(this.#n(),!this.#e||this.destroyed)return!1;if(E)return this.#t=setTimeout((()=>{this.#t=null,this.#i(!1)}),N),!1;for(let{renderTasks:L,operatorList:$}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(E,L){let $=this._intentStates.get(L);$&&(this._stats?.timeEnd("Page Request"),$.displayReadyCapability?.resolve(E))}_renderPageChunk(E,L){for(let $=0,U=E.length;$<U;$++)L.operatorList.fnArray.push(E.fnArray[$]),L.operatorList.argsArray.push(E.argsArray[$]);L.operatorList.lastChunk=E.lastChunk,L.operatorList.separateAnnots=E.separateAnnots;for(let $ of L.renderTasks)$.operatorListChanged();E.lastChunk&&this.#i(!0)}_pumpOperatorList({renderingIntent:E,cacheKey:L,annotationStorageSerializable:$}){let{map:U,transfer:P}=$,F=this._transport.messageHandler.sendWithStream("GetOperatorList",{pageIndex:this._pageIndex,intent:E,cacheKey:L,annotationStorage:U},P).getReader(),V=this._intentStates.get(L);V.streamReader=F;let Q=()=>{F.read().then((({value:Z,done:tt})=>{tt?V.streamReader=null:this._transport.destroyed||(this._renderPageChunk(Z,V),Q())}),(Z=>{if(V.streamReader=null,!this._transport.destroyed){if(V.operatorList){V.operatorList.lastChunk=!0;for(let tt of V.renderTasks)tt.operatorListChanged();this.#i(!0)}if(V.displayReadyCapability)V.displayReadyCapability.reject(Z);else{if(!V.opListReadCapability)throw Z;V.opListReadCapability.reject(Z)}}}))};Q()}_abortOperatorList({intentState:E,reason:L,force:$=!1}){if(E.streamReader){if(E.streamReaderCancelTimeout&&(clearTimeout(E.streamReaderCancelTimeout),E.streamReaderCancelTimeout=null),!$){if(E.renderTasks.size>0)return;if(L instanceof l.RenderingCancelledException){let U=I;L.extraDelay>0&&L.extraDelay<1e3&&(U+=L.extraDelay),E.streamReaderCancelTimeout=setTimeout((()=>{E.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:E,reason:L,force:!0})}),U);return}}if(E.streamReader.cancel(new a.AbortException(L.message)).catch((()=>{})),E.streamReader=null,!this._transport.destroyed){for(let[U,P]of this._intentStates)if(P===E){this._intentStates.delete(U);break}this.cleanup()}}}get stats(){return this._stats}}class st{#t=new Set;#e=Promise.resolve();postMessage(E,L){let $={data:structuredClone(E,L?{transfer:L}:null)};this.#e.then((()=>{for(let U of this.#t)U.call(this,$)}))}addEventListener(E,L){this.#t.add(L)}removeEventListener(E,L){this.#t.delete(L)}terminate(){this.#t.clear()}}let G={isWorkerDisabled:!1,fakeWorkerId:0};a.isNodeJS&&(G.isWorkerDisabled=!0,p.GlobalWorkerOptions.workerSrc||="./pdf.worker.mjs"),G.isSameOrigin=function(M,E){let L;try{if(L=new URL(M),!L.origin||L.origin==="null")return!1}catch{return!1}let $=new URL(E,L);return L.origin===$.origin},G.createCDNWrapper=function(M){let E=`await import("${M}");`;return URL.createObjectURL(new Blob([E],{type:"text/javascript"}))};class x{static#t;constructor({name:E=null,port:L=null,verbosity:$=(0,a.getVerbosityLevel)()}={}){if(this.name=E,this.destroyed=!1,this.verbosity=$,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(E){this._port=E,this._messageHandler=new w.MessageHandler("main","worker",E),this._messageHandler.on("ready",(function(){})),this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})}_initialize(){if(!G.isWorkerDisabled&&!x.#e){let{workerSrc:E}=x;try{G.isSameOrigin(window.location.href,E)||(E=G.createCDNWrapper(new URL(E,window.location).href));let L=new Worker(E,{type:"module"}),$=new w.MessageHandler("main","worker",L),U=()=>{L.removeEventListener("error",P),$.destroy(),L.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},P=()=>{this._webWorker||U()};L.addEventListener("error",P),$.on("test",(V=>{L.removeEventListener("error",P),this.destroyed?U():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",P),this.destroyed)U();else try{F()}catch{this._setupFakeWorker()}}));let F=()=>{let V=new Uint8Array;$.send("test",V,[V.buffer])};F();return}catch{(0,a.info)("The worker has been disabled.")}}this._setupFakeWorker()}_setupFakeWorker(){G.isWorkerDisabled||((0,a.warn)("Setting up fake worker."),G.isWorkerDisabled=!0),x._setupFakeWorkerGlobal.then((E=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}let L=new st;this._port=L;let $="fake"+G.fakeWorkerId++,U=new w.MessageHandler($+"_worker",$,L);E.setup(U,L);let P=new w.MessageHandler($,$+"_worker",L);this._messageHandler=P,this._readyCapability.resolve(),P.send("configure",{verbosity:this.verbosity})})).catch((E=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${E.message}".`))}))}destroy(){this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),x.#t?.delete(this._port),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}static fromPort(E){if(!E?.port)throw new Error("PDFWorker.fromPort - invalid method signature.");let L=this.#t?.get(E.port);if(L){if(L._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return L}return new x(E)}static get workerSrc(){if(p.GlobalWorkerOptions.workerSrc)return p.GlobalWorkerOptions.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get#e(){try{return globalThis.pdfjsWorker?.WorkerMessageHandler||null}catch{return null}}static get _setupFakeWorkerGlobal(){return(0,a.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(E,L,$,U,P){this.messageHandler=E,this.loadingTask=L,this.commonObjs=new g,this.fontLoader=new d.FontLoader({ownerDocument:U.ownerDocument,styleElement:U.styleElement}),this._params=U,this.canvasFactory=P.canvasFactory,this.filterFactory=P.filterFactory,this.cMapReaderFactory=P.cMapReaderFactory,this.standardFontDataFactory=P.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=$,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}#r(E,L=null){let $=this.#t.get(E);if($)return $;let U=this.messageHandler.sendWithPromise(E,L);return this.#t.set(E,U),U}get annotationStorage(){return(0,a.shadow)(this,"annotationStorage",new c.AnnotationStorage)}getRenderingIntent(E,L=a.AnnotationMode.ENABLE,$=null,U=!1){let P=a.RenderingIntentFlag.DISPLAY,F=c.SerializableEmpty;switch(E){case"any":P=a.RenderingIntentFlag.ANY;break;case"display":break;case"print":P=a.RenderingIntentFlag.PRINT;break;default:(0,a.warn)(`getRenderingIntent - invalid intent: ${E}`)}switch(L){case a.AnnotationMode.DISABLE:P+=a.RenderingIntentFlag.ANNOTATIONS_DISABLE;break;case a.AnnotationMode.ENABLE:break;case a.AnnotationMode.ENABLE_FORMS:P+=a.RenderingIntentFlag.ANNOTATIONS_FORMS;break;case a.AnnotationMode.ENABLE_STORAGE:P+=a.RenderingIntentFlag.ANNOTATIONS_STORAGE,F=(P&a.RenderingIntentFlag.PRINT&&$ instanceof c.PrintAnnotationStorage?$:this.annotationStorage).serializable;break;default:(0,a.warn)(`getRenderingIntent - invalid annotationMode: ${L}`)}return U&&(P+=a.RenderingIntentFlag.OPLIST),{renderingIntent:P,cacheKey:`${P}_${F.hash}`,annotationStorageSerializable:F}}destroy(){if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),this.#n?.reject(new Error("Worker was destroyed during onPassword callback"));let E=[];for(let $ of this.#e.values())E.push($._destroy());this.#e.clear(),this.#i.clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();let L=this.messageHandler.sendWithPromise("Terminate",null);return E.push(L),Promise.all(E).then((()=>{this.commonObjs.clear(),this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(),(0,o.cleanupTextLayer)(),this._networkStream?.cancelAllRequests(new a.AbortException("Worker was terminated.")),this.messageHandler&&(this.messageHandler.destroy(),this.messageHandler=null),this.destroyCapability.resolve()}),this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){let{messageHandler:E,loadingTask:L}=this;E.on("GetReader",(($,U)=>{(0,a.assert)(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=P=>{this._lastProgress={loaded:P.loaded,total:P.total}},U.onPull=()=>{this._fullReader.read().then((function({value:P,done:F}){F?U.close():((0,a.assert)(P instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),U.enqueue(new Uint8Array(P),1,[P]))})).catch((P=>{U.error(P)}))},U.onCancel=P=>{this._fullReader.cancel(P),U.ready.catch((F=>{if(!this.destroyed)throw F}))}})),E.on("ReaderHeadersReady",($=>{let U=Promise.withResolvers(),P=this._fullReader;return P.headersReady.then((()=>{(!P.isStreamingSupported||!P.isRangeSupported)&&(this._lastProgress&&L.onProgress?.(this._lastProgress),P.onProgress=F=>{L.onProgress?.({loaded:F.loaded,total:F.total})}),U.resolve({isStreamingSupported:P.isStreamingSupported,isRangeSupported:P.isRangeSupported,contentLength:P.contentLength})}),U.reject),U.promise})),E.on("GetRangeReader",(($,U)=>{(0,a.assert)(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");let P=this._networkStream.getRangeReader($.begin,$.end);P?(U.onPull=()=>{P.read().then((function({value:F,done:V}){V?U.close():((0,a.assert)(F instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),U.enqueue(new Uint8Array(F),1,[F]))})).catch((F=>{U.error(F)}))},U.onCancel=F=>{P.cancel(F),U.ready.catch((V=>{if(!this.destroyed)throw V}))}):U.close()})),E.on("GetDoc",(({pdfInfo:$})=>{this._numPages=$.numPages,this._htmlForXfa=$.htmlForXfa,delete $.htmlForXfa,L._capability.resolve(new rt($,this))})),E.on("DocException",(function($){let U;switch($.name){case"PasswordException":U=new a.PasswordException($.message,$.code);break;case"InvalidPDFException":U=new a.InvalidPDFException($.message);break;case"MissingPDFException":U=new a.MissingPDFException($.message);break;case"UnexpectedResponseException":U=new a.UnexpectedResponseException($.message,$.status);break;case"UnknownErrorException":U=new a.UnknownErrorException($.message,$.details);break;default:(0,a.unreachable)("DocException - expected a valid Error.")}L._capability.reject(U)})),E.on("PasswordRequest",($=>{if(this.#n=Promise.withResolvers(),L.onPassword){let U=P=>{P instanceof Error?this.#n.reject(P):this.#n.resolve({password:P})};try{L.onPassword(U,$.code)}catch(P){this.#n.reject(P)}}else this.#n.reject(new a.PasswordException($.message,$.code));return this.#n.promise})),E.on("DataLoaded",($=>{L.onProgress?.({loaded:$.length,total:$.length}),this.downloadInfoCapability.resolve($)})),E.on("StartRenderPage",($=>{this.destroyed||this.#e.get($.pageIndex)._startRenderPage($.transparency,$.cacheKey)})),E.on("commonobj",(([$,U,P])=>{if(this.destroyed||this.commonObjs.has($))return null;switch(U){case"Font":let F=this._params;if("error"in P){let tt=P.error;(0,a.warn)(`Error during font loading: ${tt}`),this.commonObjs.resolve($,tt);break}let V=F.pdfBug&&globalThis.FontInspector?.enabled?(tt,nt)=>globalThis.FontInspector.fontAdded(tt,nt):null,Q=new d.FontFaceObject(P,{isEvalSupported:F.isEvalSupported,disableFontFace:F.disableFontFace,ignoreErrors:F.ignoreErrors,inspectFont:V});this.fontLoader.bind(Q).catch((()=>E.sendWithPromise("FontFallback",{id:$}))).finally((()=>{!F.fontExtraProperties&&Q.data&&(Q.data=null),this.commonObjs.resolve($,Q)}));break;case"CopyLocalImage":let{imageRef:Z}=P;(0,a.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($,structuredClone(nt)),nt.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve($,P);break;default:throw new Error(`Got unknown common object type ${U}`)}return null})),E.on("obj",(([$,U,P,F])=>{if(this.destroyed)return;let V=this.#e.get(U);if(!V.objs.has($))if(V._intentStates.size!==0)switch(P){case"Image":V.objs.resolve($,F),F?.dataLen>a.MAX_IMAGE_SIZE_TO_CACHE&&(V._maybeCleanupAfterRender=!0);break;case"Pattern":V.objs.resolve($,F);break;default:throw new Error(`Got unknown object type ${P}`)}else F?.bitmap?.close()})),E.on("DocProgress",($=>{this.destroyed||L.onProgress?.({loaded:$.loaded,total:$.total})})),E.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.")))),E.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,a.warn)("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");let{map:E,transfer:L}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:E,filename:this._fullReader?.filename??null},L).finally((()=>{this.annotationStorage.resetModified()}))}getPage(E){if(!Number.isInteger(E)||E<=0||E>this._numPages)return Promise.reject(new Error("Invalid page request."));let L=E-1,$=this.#i.get(L);if($)return $;let U=this.messageHandler.sendWithPromise("GetPage",{pageIndex:L}).then((P=>{if(this.destroyed)throw new Error("Transport destroyed");let F=new ct(L,P,this,this._params.pdfBug);return this.#e.set(L,F),F}));return this.#i.set(L,U),U}getPageIndex(E){return typeof E!="object"||E===null||!Number.isInteger(E.num)||E.num<0||!Number.isInteger(E.gen)||E.gen<0?Promise.reject(new Error("Invalid pageIndex request.")):this.messageHandler.sendWithPromise("GetPageIndex",{num:E.num,gen:E.gen})}getAnnotations(E,L){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:E,intent:L})}getFieldObjects(){return this.#r("GetFieldObjects")}hasJSActions(){return this.#r("HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(E){return typeof E!="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:E})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return this.#r("GetDocJSActions")}getPageJSActions(E){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:E})}getStructTree(E){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:E})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(E){return this.#r("GetOptionalContentConfig").then((L=>new f.OptionalContentConfig(L,E)))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){let E="GetMetadata",L=this.#t.get(E);if(L)return L;let $=this.messageHandler.sendWithPromise(E,null).then((U=>({info:U[0],metadata:U[1]?new S.Metadata(U[1]):null,contentDispositionFilename:this._fullReader?.filename??null,contentLength:this._fullReader?.contentLength??null})));return this.#t.set(E,$),$}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(E=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(let L of this.#e.values())if(!L.cleanup())throw new Error(`startCleanup: Page ${L.pageNumber} is currently rendering.`);this.commonObjs.clear(),E||this.fontLoader.clear(),this.#t.clear(),this.filterFactory.destroy(!0),(0,o.cleanupTextLayer)()}}get loadingParams(){let{disableAutoFetch:E,enableXfa:L}=this._params;return(0,a.shadow)(this,"loadingParams",{disableAutoFetch:E,enableXfa:L})}}let R=Symbol("INITIAL_DATA");class g{#t=Object.create(null);#e(E){return this.#t[E]||={...Promise.withResolvers(),data:R}}get(E,L=null){if(L){let U=this.#e(E);return U.promise.then((()=>L(U.data))),null}let $=this.#t[E];if(!$||$.data===R)throw new Error(`Requesting object that isn't resolved yet ${E}.`);return $.data}has(E){let L=this.#t[E];return!!L&&L.data!==R}resolve(E,L=null){let $=this.#e(E);$.data=L,$.resolve()}clear(){for(let E in this.#t){let{data:L}=this.#t[E];L?.bitmap?.close()}this.#t=Object.create(null)}*[Symbol.iterator](){for(let E in this.#t){let{data:L}=this.#t[E];L!==R&&(yield[E,L])}}}class y{#t=null;constructor(E){this.#t=E,this.onContinue=null}get promise(){return this.#t.capability.promise}cancel(E=0){this.#t.cancel(null,E)}get separateAnnots(){let{separateAnnots:E}=this.#t.operatorList;if(!E)return!1;let{annotationCanvasMap:L}=this.#t;return E.form||E.canvas&&L?.size>0}}class C{static#t=new WeakSet;constructor({callback:E,params:L,objs:$,commonObjs:U,annotationCanvasMap:P,operatorList:F,pageIndex:V,canvasFactory:Q,filterFactory:Z,useRequestAnimationFrame:tt=!1,pdfBug:nt=!1,pageColors:pt=null}){this.callback=E,this.params=L,this.objs=$,this.commonObjs=U,this.annotationCanvasMap=P,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 y(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=L.canvasContext.canvas}get completed(){return this.capability.promise.catch((function(){}))}initializeGraphics({transparency:E=!1,optionalContentConfig:L}){if(this.cancelled)return;if(this._canvas){if(C.#t.has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");C.#t.add(this._canvas)}this._pdfBug&&globalThis.StepperManager?.enabled&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());let{canvasContext:$,viewport:U,transform:P,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:P,viewport:U,transparency:E,background:F}),this.operatorListIdx=0,this.graphicsReady=!0,this.graphicsReadyCallback?.()}cancel(E=null,L=0){this.running=!1,this.cancelled=!0,this.gfx?.endDrawing(),C.#t.delete(this._canvas),this.callback(E||new 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(),C.#t.delete(this._canvas),this.callback())))}}let k="4.1.392",O="fcb76a78d";n()}catch(_){n(_)}}))},583:(s,t,e)=>{e.d(t,{BaseCMapReaderFactory:()=>c,BaseCanvasFactory:()=>a,BaseFilterFactory:()=>n,BaseSVGFactory:()=>d,BaseStandardFontDataFactory:()=>l});var i=e(292);class n{constructor(){this.constructor===n&&(0,i.unreachable)("Cannot initialize BaseFilterFactory.")}addFilter(u){return"none"}addHCMFilter(u,o){return"none"}addHighlightHCMFilter(u,o,p,w,S){return"none"}destroy(u=!1){}}class a{constructor(){this.constructor===a&&(0,i.unreachable)("Cannot initialize BaseCanvasFactory.")}create(u,o){if(u<=0||o<=0)throw new Error("Invalid canvas size");let p=this._createCanvas(u,o);return{canvas:p,context:p.getContext("2d")}}reset(u,o,p){if(!u.canvas)throw new Error("Canvas is not specified");if(o<=0||p<=0)throw new Error("Invalid canvas size");u.canvas.width=o,u.canvas.height=p}destroy(u){if(!u.canvas)throw new Error("Canvas is not specified");u.canvas.width=0,u.canvas.height=0,u.canvas=null,u.context=null}_createCanvas(u,o){(0,i.unreachable)("Abstract method `_createCanvas` called.")}}class c{constructor({baseUrl:u=null,isCompressed:o=!0}){this.constructor===c&&(0,i.unreachable)("Cannot initialize BaseCMapReaderFactory."),this.baseUrl=u,this.isCompressed=o}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 o=this.baseUrl+u+(this.isCompressed?".bcmap":""),p=this.isCompressed?i.CMapCompressionType.BINARY:i.CMapCompressionType.NONE;return this._fetchData(o,p).catch((w=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${o}`)}))}_fetchData(u,o){(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 o=`${this.baseUrl}${u}`;return this._fetchData(o).catch((p=>{throw new Error(`Unable to load font data at: ${o}`)}))}_fetchData(u){(0,i.unreachable)("Abstract method `_fetchData` called.")}}class d{constructor(){this.constructor===d&&(0,i.unreachable)("Cannot initialize BaseSVGFactory.")}create(u,o,p=!1){if(u<=0||o<=0)throw new Error("Invalid SVG dimensions");let w=this._createSVG("svg:svg");return w.setAttribute("version","1.1"),p||(w.setAttribute("width",`${u}px`),w.setAttribute("height",`${o}px`)),w.setAttribute("preserveAspectRatio","none"),w.setAttribute("viewBox",`0 0 ${u} ${o}`),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:()=>st});var i=e(292),n=e(419);let a="Fill",c="Stroke",l="Shading";function d(G,x){if(!x)return;let T=x[2]-x[0],R=x[3]-x[1],g=new Path2D;g.rect(x[0],x[1],T,R),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(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,g){let y;if(g===c||g===a){let C=T.current.getClippedPathBoundingBox(g,(0,n.getCurrentTransform)(x))||[0,0,0,0],k=Math.ceil(C[2]-C[0])||1,O=Math.ceil(C[3]-C[1])||1,M=T.cachedCanvases.getCanvas("pattern",k,O,!0),E=M.context;E.clearRect(0,0,E.canvas.width,E.canvas.height),E.beginPath(),E.rect(0,0,E.canvas.width,E.canvas.height),E.translate(-C[0],-C[1]),R=i.Util.transform(R,[1,0,0,1,C[0],C[1]]),E.transform(...T.baseTransform),this.matrix&&E.transform(...this.matrix),d(E,this._bbox),E.fillStyle=this._createGradient(E),E.fill(),y=x.createPattern(M.canvas,"no-repeat");let L=new DOMMatrix(R);y.setTransform(L)}else d(x,this._bbox),y=this._createGradient(x);return y}}function o(G,x,T,R,g,y,C,k){let O=x.coords,M=x.colors,E=G.data,L=4*G.width,$;O[T+1]>O[R+1]&&($=T,T=R,R=$,$=y,y=C,C=$),O[R+1]>O[g+1]&&($=R,R=g,g=$,$=C,C=k,k=$),O[T+1]>O[R+1]&&($=T,T=R,R=$,$=y,y=C,C=$);let U=(O[T]+x.offsetX)*x.scaleX,P=(O[T+1]+x.offsetY)*x.scaleY,F=(O[R]+x.offsetX)*x.scaleX,V=(O[R+1]+x.offsetY)*x.scaleY,Q=(O[g]+x.offsetX)*x.scaleX,Z=(O[g+1]+x.offsetY)*x.scaleY;if(P>=Z)return;let tt=M[y],nt=M[y+1],pt=M[y+2],dt=M[C],lt=M[C+1],wt=M[C+2],Tt=M[k],xt=M[k+1],Dt=M[k+2],Rt=Math.round(P),Bt=Math.round(Z),Ht,le,Se,Oe,Te,De,ri,ai;for(let ae=Rt;ae<=Bt;ae++){if(ae<V){let te=ae<P?0:(P-ae)/(P-V);Ht=U-(U-F)*te,le=tt-(tt-dt)*te,Se=nt-(nt-lt)*te,Oe=pt-(pt-wt)*te}else{let te;te=ae>Z?1:V===Z?0:(V-ae)/(V-Z),Ht=F-(F-Q)*te,le=dt-(dt-Tt)*te,Se=lt-(lt-xt)*te,Oe=wt-(wt-Dt)*te}let se;se=ae<P?0:ae>Z?1:(P-ae)/(P-Z),Te=U-(U-Q)*se,De=tt-(tt-Tt)*se,ri=nt-(nt-xt)*se,ai=pt-(pt-Dt)*se;let oi=Math.round(Math.min(Ht,Te)),Qi=Math.round(Math.max(Ht,Te)),Me=L*ae+4*oi;for(let te=oi;te<=Qi;te++)se=(Ht-te)/(Ht-Te),se<0?se=0:se>1&&(se=1),E[Me++]=le-(le-De)*se|0,E[Me++]=Se-(Se-ri)*se|0,E[Me++]=Oe-(Oe-ai)*se|0,E[Me++]=255}}function p(G,x,T){let R=x.coords,g=x.colors,y,C;switch(x.type){case"lattice":let k=x.verticesPerRow,O=Math.floor(R.length/k)-1,M=k-1;for(y=0;y<O;y++){let E=y*k;for(let L=0;L<M;L++,E++)o(G,T,R[E],R[E+1],R[E+k],g[E],g[E+1],g[E+k]),o(G,T,R[E+k+1],R[E+1],R[E+k],g[E+k+1],g[E+1],g[E+k])}break;case"triangles":for(y=0,C=R.length;y<C;y+=3)o(G,T,R[y],R[y+1],R[y+2],g[y],g[y+1],g[y+2]);break;default:throw new Error("illegal figure")}}class w 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 g=Math.floor(this._bounds[0]),y=Math.floor(this._bounds[1]),C=Math.ceil(this._bounds[2])-g,k=Math.ceil(this._bounds[3])-y,O=Math.min(Math.ceil(Math.abs(C*x[0]*1.1)),3e3),M=Math.min(Math.ceil(Math.abs(k*x[1]*1.1)),3e3),E=C/O,L=k/M,$={coords:this._coords,colors:this._colors,offsetX:-g,offsetY:-y,scaleX:1/E,scaleY:1/L},U=O+4,P=M+4,F=R.getCanvas("mesh",U,P,!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)p(Q,Z,$);return V.putImageData(Q,2,2),{canvas:F.canvas,offsetX:g-2*E,offsetY:y-2*L,scaleX:E,scaleY:L}}getPattern(x,T,R,g){d(x,this._bbox);let y;if(g===l)y=i.Util.singularValueDecompose2dScale((0,n.getCurrentTransform)(x));else if(y=i.Util.singularValueDecompose2dScale(T.baseTransform),this.matrix){let k=i.Util.singularValueDecompose2dScale(this.matrix);y=[y[0]*k[0],y[1]*k[1]]}let C=this._createMeshCanvas(y,g===l?null:this._background,T.cachedCanvases);return g!==l&&(x.setTransform(...T.baseTransform),this.matrix&&x.transform(...this.matrix)),x.translate(C.offsetX,C.offsetY),x.scale(C.scaleX,C.scaleY),x.createPattern(C.canvas,"no-repeat")}}class S extends m{getPattern(){return"hotpink"}}let f=1,v=2;class r{static MAX_PATTERN_SIZE=3e3;constructor(x,T,R,g,y){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=g,this.baseTransform=y}createPatternCanvas(x){let T=this.operatorList,R=this.bbox,g=this.xstep,y=this.ystep,C=this.paintType,k=this.tilingType,O=this.color,M=this.canvasGraphicsFactory;(0,i.info)("TilingType: "+k);let E=R[0],L=R[1],$=R[2],U=R[3],P=i.Util.singularValueDecompose2dScale(this.matrix),F=i.Util.singularValueDecompose2dScale(this.baseTransform),V=[P[0]*F[0],P[1]*F[1]],Q=this.getSizeAndScale(g,this.ctx.canvas.width,V[0]),Z=this.getSizeAndScale(y,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,C,O);let dt=E,lt=L,wt=$,Tt=U;return E<0&&(dt=0,wt+=Math.abs(E)),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 g=Math.max(r.MAX_PATTERN_SIZE,T),y=Math.ceil(x*R);return y>=g?y=g:R=y/x,{scale:R,size:y}}clipBbox(x,T,R,g,y){let C=g-T,k=y-R;x.ctx.rect(T,R,C,k),x.current.updateRectMinMax((0,n.getCurrentTransform)(x.ctx),[T,R,g,y]),x.clip(),x.endPath()}setFillAndStrokeStyleToContext(x,T,R){let g=x.ctx,y=x.current;switch(T){case f:let C=this.ctx;g.fillStyle=C.fillStyle,g.strokeStyle=C.strokeStyle,y.fillColor=C.fillStyle,y.strokeColor=C.strokeStyle;break;case v:let k=i.Util.makeHexColor(R[0],R[1],R[2]);g.fillStyle=k,g.strokeStyle=k,y.fillColor=k,y.strokeColor=k;break;default:throw new i.FormatError(`Unsupported paint type: ${T}`)}}getPattern(x,T,R,g){let y=R;g!==l&&(y=i.Util.transform(y,T.baseTransform),this.matrix&&(y=i.Util.transform(y,this.matrix)));let C=this.createPatternCanvas(T),k=new DOMMatrix(y);k=k.translate(C.offsetX,C.offsetY),k=k.scale(1/C.scaleX,1/C.scaleY);let O=x.createPattern(C.canvas,"repeat");return O.setTransform(k),O}}function h({src:G,srcPos:x=0,dest:T,width:R,height:g,nonBlackColor:y=4294967295,inverseDecode:C=!1}){let k=i.FeatureTest.isLittleEndian?4278190080:255,[O,M]=C?[y,k]:[k,y],E=R>>3,L=7&R,$=G.length;T=new Uint32Array(T.buffer);let U=0;for(let P=0;P<g;P++){for(let V=x+E;x<V;x++){let Q=x<$?G[x]:255;T[U++]=128&Q?M:O,T[U++]=64&Q?M:O,T[U++]=32&Q?M:O,T[U++]=16&Q?M:O,T[U++]=8&Q?M:O,T[U++]=4&Q?M:O,T[U++]=2&Q?M:O,T[U++]=1&Q?M:O}if(L===0)continue;let F=x<$?G[x++]:255;for(let V=0;V<L;V++)T[U++]=F&1<<7-V?M:O}return{srcPos:x,destPos:U}}let b=4096,A=16;class D{constructor(x){this.canvasFactory=x,this.cache=Object.create(null)}getCanvas(x,T,R){let g;return this.cache[x]!==void 0?(g=this.cache[x],this.canvasFactory.reset(g,T,R)):(g=this.canvasFactory.create(T,R),this.cache[x]=g),g}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 _(G,x,T,R,g,y,C,k,O,M){let[E,L,$,U,P,F]=(0,n.getCurrentTransform)(G);if(L===0&&$===0){let V=C*E+P,Q=Math.round(V),Z=k*U+F,tt=Math.round(Z),nt=(C+O)*E+P,pt=Math.abs(Math.round(nt)-Q)||1,dt=(k+M)*U+F,lt=Math.abs(Math.round(dt)-tt)||1;return G.setTransform(Math.sign(E),0,0,Math.sign(U),Q,tt),G.drawImage(x,T,R,g,y,0,0,pt,lt),G.setTransform(E,L,$,U,P,F),[pt,lt]}if(E===0&&U===0){let V=k*$+P,Q=Math.round(V),Z=C*L+F,tt=Math.round(Z),nt=(k+M)*$+P,pt=Math.abs(Math.round(nt)-Q)||1,dt=(C+O)*L+F,lt=Math.abs(Math.round(dt)-tt)||1;return G.setTransform(0,Math.sign(L),Math.sign($),0,Q,tt),G.drawImage(x,T,R,g,y,0,0,lt,pt),G.setTransform(E,L,$,U,P,F),[lt,pt]}return G.drawImage(x,T,R,g,y,C,k,O,M),[Math.hypot(E,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),g=i.Util.applyTransform(T.slice(2),x),y=i.Util.applyTransform([T[0],T[3]],x),C=i.Util.applyTransform([T[2],T[1]],x);this.minX=Math.min(this.minX,R[0],g[0],y[0],C[0]),this.minY=Math.min(this.minY,R[1],g[1],y[1],C[1]),this.maxX=Math.max(this.maxX,R[0],g[0],y[0],C[0]),this.maxY=Math.max(this.maxY,R[1],g[1],y[1],C[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,g,y,C,k,O,M,E){let L=i.Util.bezierBoundingBox(T,R,g,y,C,k,O,M,E);E||this.updateRectMinMax(x,L)}getPathBoundingBox(x=a,T=null){let R=[this.minX,this.minY,this.maxX,this.maxY];if(x===c){T||(0,i.unreachable)("Stroke bounding box must include transform.");let g=i.Util.singularValueDecompose2dScale(T),y=g[0]*this.lineWidth/2,C=g[1]*this.lineWidth/2;R[0]-=y,R[1]-=C,R[2]+=y,R[3]+=C}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=a,T=null){return i.Util.intersect(this.clipBox,this.getPathBoundingBox(x,T))}}function N(G,x){if(typeof ImageData<"u"&&x instanceof ImageData){G.putImageData(x,0,0);return}let T=x.height,R=x.width,g=T%A,y=(T-g)/A,C=g===0?y:y+1,k=G.createImageData(R,A),O,M=0,E=x.data,L=k.data,$,U,P,F;if(x.kind===i.ImageKind.GRAYSCALE_1BPP){let V=E.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($=0;$<C;$++){for(P=$<y?A:g,O=0,U=0;U<P;U++){let dt=V-M,lt=0,wt=dt>tt?R:8*dt-7,Tt=-8&wt,xt=0,Dt=0;for(;lt<Tt;lt+=8)Dt=E[M++],Q[O++]=128&Dt?nt:pt,Q[O++]=64&Dt?nt:pt,Q[O++]=32&Dt?nt:pt,Q[O++]=16&Dt?nt:pt,Q[O++]=8&Dt?nt:pt,Q[O++]=4&Dt?nt:pt,Q[O++]=2&Dt?nt:pt,Q[O++]=1&Dt?nt:pt;for(;lt<wt;lt++)xt===0&&(Dt=E[M++],xt=128),Q[O++]=Dt&xt?nt:pt,xt>>=1}for(;O<Z;)Q[O++]=0;G.putImageData(k,0,$*A)}}else if(x.kind===i.ImageKind.RGBA_32BPP){for(U=0,F=R*A*4,$=0;$<y;$++)L.set(E.subarray(M,M+F)),M+=F,G.putImageData(k,0,U),U+=A;$<C&&(F=R*g*4,L.set(E.subarray(M,M+F)),G.putImageData(k,0,U))}else{if(x.kind!==i.ImageKind.RGB_24BPP)throw new Error(`bad image kind: ${x.kind}`);for(P=A,F=R*P,$=0;$<C;$++){for($>=y&&(P=g,F=R*P),O=0,U=F;U--;)L[O++]=E[M++],L[O++]=E[M++],L[O++]=E[M++],L[O++]=255;G.putImageData(k,0,$*A)}}}function H(G,x){if(x.bitmap){G.drawImage(x.bitmap,0,0);return}let T=x.height,R=x.width,g=T%A,y=(T-g)/A,C=g===0?y:y+1,k=G.createImageData(R,A),O=0,M=x.data,E=k.data;for(let L=0;L<C;L++){let $=L<y?A:g;({srcPos:O}=h({src:M,srcPos:O,dest:E,width:R,height:$,nonBlackColor:0})),G.putImageData(k,0,L*A)}}function j(G,x){let T=["strokeStyle","fillStyle","fillRule","globalAlpha","lineWidth","lineCap","lineJoin","miterLimit","globalCompositeOperation","font","filter"];for(let R of T)G[R]!==void 0&&(x[R]=G[R]);G.setLineDash!==void 0&&(x.setLineDash(G.getLineDash()),x.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:x}=G;x!=="none"&&x!==""&&(G.filter="none")}}function it(G,x,T,R){let g=G.length;for(let y=3;y<g;y+=4){let C=G[y];if(C===0)G[y-3]=x,G[y-2]=T,G[y-1]=R;else if(C<255){let k=255-C;G[y-3]=G[y-3]*C+x*k>>8,G[y-2]=G[y-2]*C+T*k>>8,G[y-1]=G[y-1]*C+R*k>>8}}}function ot(G,x,T){let R=G.length;for(let g=3;g<R;g+=4){let y=T?T[G[g]]:G[g];x[g]=x[g]*y*.00392156862745098|0}}function X(G,x,T){let R=G.length;for(let g=3;g<R;g+=4){let y=77*G[g-3]+152*G[g-2]+28*G[g-1];x[g]=T?x[g]*T[y>>8]>>8:x[g]*y>>16}}function z(G,x,T,R){let g=R[0],y=R[1],C=R[2]-g,k=R[3]-y;C!==0&&k!==0&&((function(M,E,L,$,U,P,F,V,Q,Z,tt){let nt=!!P,pt=nt?P[0]:0,dt=nt?P[1]:0,lt=nt?P[2]:0,wt=U==="Luminosity"?X:ot,Tt=Math.min($,Math.ceil(1048576/L));for(let xt=0;xt<$;xt+=Tt){let Dt=Math.min(Tt,$-xt),Rt=M.getImageData(V-Z,xt+(Q-tt),L,Dt),Bt=E.getImageData(V,xt+Q,L,Dt);nt&&it(Rt.data,pt,dt,lt),wt(Rt.data,Bt.data,F),E.putImageData(Bt,V,xt+Q)}})(x.context,T,C,k,x.subtype,x.backdrop,x.transferMap,g,y,x.offsetX,x.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,x){let T=i.Util.singularValueDecompose2dScale(G);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,g,y,{optionalContentConfig:C,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=g,this.filterFactory=y,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=C,this.cachedCanvases=new D(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:g=null}){let y=this.ctx.canvas.width,C=this.ctx.canvas.height,k=this.ctx.fillStyle;if(this.ctx.fillStyle=g||"#ffffff",this.ctx.fillRect(0,0,y,C),this.ctx.fillStyle=k,R){let O=this.cachedCanvases.getCanvas("transparent",y,C);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),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,g){let y=x.argsArray,C=x.fnArray,k=T||0,O=y.length;if(O===k)return k;let M=O-k>10&&typeof R=="function",E=M?Date.now()+15:0,L=0,$=this.commonObjs,U=this.objs,P;for(;;){if(g!==void 0&&k===g.nextBreakPoint)return g.breakIt(k,R),k;if(P=C[k],P!==i.OPS.dependency)this[P].apply(this,y[k]);else for(let F of y[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()>E)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,g=x.height,y,C,k=Math.max(Math.hypot(T[0],T[1]),1),O=Math.max(Math.hypot(T[2],T[3]),1),M=R,E=g,L="prescale1";for(;k>2&&M>1||O>2&&E>1;){let $=M,U=E;k>2&&M>1&&($=M>=16384?Math.floor(M/2)-1||1:Math.ceil(M/2),k/=M/$),O>2&&E>1&&(U=E>=16384?Math.floor(E/2)-1||1:Math.ceil(E)/2,O/=E/U),y=this.cachedCanvases.getCanvas(L,$,U),C=y.context,C.clearRect(0,0,$,U),C.drawImage(x,0,0,M,E,0,0,$,U),x=y.canvas,M=$,E=U,L=L==="prescale1"?"prescale2":"prescale1"}return{img:x,paintWidth:M,paintHeight:E}}_createMaskCanvas(x){let T=this.ctx,{width:R,height:g}=x,y=this.current.fillColor,C=this.current.patternFill,k=(0,n.getCurrentTransform)(T),O,M,E,L;if((x.bitmap||x.data)&&x.count>1){let wt=x.bitmap||x.data.buffer;M=JSON.stringify(C?k:[k.slice(0,4),y]),O=this._cachedBitmapsMap.get(wt),O||(O=new Map,this._cachedBitmapsMap.set(wt,O));let Tt=O.get(M);if(Tt&&!C)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])};E=Tt}E||(L=this.cachedCanvases.getCanvas("maskCanvas",R,g),H(L.context,x));let $=i.Util.transform(k,[1/R,0,0,-1/g,0,0]);$=i.Util.transform($,[1,0,0,1,0,-g]);let[U,P,F,V]=i.Util.getAxialAlignedBoundingBox([0,0,R,g],$),Q=Math.round(F-U)||1,Z=Math.round(V-P)||1,tt=this.cachedCanvases.getCanvas("fillCanvas",Q,Z),nt=tt.context,pt=U,dt=P;nt.translate(-pt,-dt),nt.transform(...$),E||(E=this._scaleImage(L.canvas,(0,n.getCurrentTransformInverse)(nt)),E=E.img,O&&C&&O.set(M,E)),nt.imageSmoothingEnabled=W((0,n.getCurrentTransform)(nt),x.interpolate),_(nt,E,0,0,E.width,E.height,0,0,R,g),nt.globalCompositeOperation="source-in";let lt=i.Util.transform((0,n.getCurrentTransformInverse)(nt),[1,0,0,1,-pt,-dt]);return nt.fillStyle=C?y.getPattern(T,this,lt,a):y,nt.fillRect(0,0,R,g),O&&!C&&(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,g=this.cachedCanvases.getCanvas(R,x,T);this.suspendedCtx=this.ctx,this.ctx=g.context;let y=this.ctx;y.setTransform(...(0,n.getCurrentTransform)(this.suspendedCtx)),j(this.suspendedCtx,y),(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(E,L){O.translate(E,L),this.__originalTranslate(E,L)},k.scale=function(E,L){O.scale(E,L),this.__originalScale(E,L)},k.transform=function(E,L,$,U,P,F){O.transform(E,L,$,U,P,F),this.__originalTransform(E,L,$,U,P,F)},k.setTransform=function(E,L,$,U,P,F){O.setTransform(E,L,$,U,P,F),this.__originalSetTransform(E,L,$,U,P,F)},k.resetTransform=function(){O.resetTransform(),this.__originalResetTransform()},k.rotate=function(E){O.rotate(E),this.__originalRotate(E)},k.clip=function(E){O.clip(E),this.__originalClip(E)},k.moveTo=function(M,E){O.moveTo(M,E),this.__originalMoveTo(M,E)},k.lineTo=function(M,E){O.lineTo(M,E),this.__originalLineTo(M,E)},k.bezierCurveTo=function(M,E,L,$,U,P){O.bezierCurveTo(M,E,L,$,U,P),this.__originalBezierCurveTo(M,E,L,$,U,P)},k.rect=function(M,E,L,$){O.rect(M,E,L,$),this.__originalRect(M,E,L,$)},k.closePath=function(){O.closePath(),this.__originalClosePath()},k.beginPath=function(){O.beginPath(),this.__originalBeginPath()}})(y,this.suspendedCtx),this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),j(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(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;z(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?(j(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(),j(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(x,T,R,g,y,C){this.ctx.transform(x,T,R,g,y,C),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(x,T,R){let g=this.ctx,y=this.current,C,k,O=y.x,M=y.y,E=(0,n.getCurrentTransform)(g),L=E[0]===0&&E[3]===0||E[1]===0&&E[2]===0,$=L?R.slice(0):null;for(let U=0,P=0,F=x.length;U<F;U++)switch(0|x[U]){case i.OPS.rectangle:O=T[P++],M=T[P++];let V=T[P++],Q=T[P++],Z=O+V,tt=M+Q;g.moveTo(O,M),V===0||Q===0?g.lineTo(Z,tt):(g.lineTo(Z,M),g.lineTo(Z,tt),g.lineTo(O,tt)),L||y.updateRectMinMax(E,[O,M,Z,tt]),g.closePath();break;case i.OPS.moveTo:O=T[P++],M=T[P++],g.moveTo(O,M),L||y.updatePathMinMax(E,O,M);break;case i.OPS.lineTo:O=T[P++],M=T[P++],g.lineTo(O,M),L||y.updatePathMinMax(E,O,M);break;case i.OPS.curveTo:C=O,k=M,O=T[P+4],M=T[P+5],g.bezierCurveTo(T[P],T[P+1],T[P+2],T[P+3],O,M),y.updateCurvePathMinMax(E,C,k,T[P],T[P+1],T[P+2],T[P+3],O,M,$),P+=6;break;case i.OPS.curveTo2:C=O,k=M,g.bezierCurveTo(O,M,T[P],T[P+1],T[P+2],T[P+3]),y.updateCurvePathMinMax(E,C,k,O,M,T[P],T[P+1],T[P+2],T[P+3],$),O=T[P+2],M=T[P+3],P+=4;break;case i.OPS.curveTo3:C=O,k=M,O=T[P+2],M=T[P+3],g.bezierCurveTo(T[P],T[P+1],O,M,O,M),y.updateCurvePathMinMax(E,C,k,T[P],T[P+1],O,M,O,M,$),P+=4;break;case i.OPS.closePath:g.closePath()}L&&y.updateScalingPathMinMax(E,$),y.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),c),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,g=!1;this.current.patternFill&&(T.save(),T.fillStyle=R.getPattern(T,this,(0,n.getCurrentTransformInverse)(T),a),g=!0);let y=this.current.getClippedPathBoundingBox();this.contentVisible&&y!==null&&(this.pendingEOFill?(T.fill("evenodd"),this.pendingEOFill=!1):T.fill()),g&&T.restore(),x&&this.consumePath(y)}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),g=this.current;if(!R)throw new Error(`Can't find font for ${x}`);if(g.fontMatrix=R.fontMatrix||i.FONT_IDENTITY_MATRIX,g.fontMatrix[0]!==0&&g.fontMatrix[3]!==0||(0,i.warn)("Invalid font matrix for font "+x),T<0?(T=-T,g.fontDirection=-1):g.fontDirection=1,this.current.font=R,this.current.fontSize=T,R.isType3Font)return;let y=R.loadedName||"sans-serif",C=R.systemFontInfo?.css||`"${y}", ${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 ${C}`}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,g,y,C){this.current.textMatrix=[x,T,R,g,y,C],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,g){let y=this.ctx,C=this.current,k=C.font,O=C.textRenderingMode,M=C.fontSize/C.fontSizeScale,E=O&i.TextRenderingMode.FILL_STROKE_MASK,L=!!(O&i.TextRenderingMode.ADD_TO_PATH_FLAG),$=C.patternFill&&!k.missingFile,U;(k.disableFontFace||L||$)&&(U=k.getPathGenerator(this.commonObjs,x)),k.disableFontFace||$?(y.save(),y.translate(T,R),y.beginPath(),U(y,M),g&&y.setTransform(...g),E!==i.TextRenderingMode.FILL&&E!==i.TextRenderingMode.FILL_STROKE||y.fill(),E!==i.TextRenderingMode.STROKE&&E!==i.TextRenderingMode.FILL_STROKE||y.stroke(),y.restore()):(E!==i.TextRenderingMode.FILL&&E!==i.TextRenderingMode.FILL_STROKE||y.fillText(x,T,R),E!==i.TextRenderingMode.STROKE&&E!==i.TextRenderingMode.FILL_STROKE||y.strokeText(x,T,R)),L&&(this.pendingTextPaths||=[]).push({transform:(0,n.getCurrentTransform)(y),x:T,y:R,fontSize:M,addToPath:U})}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 g=3;g<T.length;g+=4)if(T[g]>0&&T[g]<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 g=T.fontSize;if(g===0)return;let y=this.ctx,C=T.fontSizeScale,k=T.charSpacing,O=T.wordSpacing,M=T.fontDirection,E=T.textHScale*M,L=x.length,$=R.vertical,U=$?1:-1,P=R.defaultVMetrics,F=g*T.fontMatrix[0],V=T.textRenderingMode===i.TextRenderingMode.FILL&&!R.disableFontFace&&!T.patternFill;y.save(),y.transform(...T.textMatrix),y.translate(T.x,T.y+T.textRise),M>0?y.scale(E,-1):y.scale(E,1);let Q;if(T.patternFill){y.save();let dt=T.fillColor.getPattern(y,this,(0,n.getCurrentTransformInverse)(y),a);Q=(0,n.getCurrentTransform)(y),y.restore(),y.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(C!==1&&(y.scale(C,C),Z/=C),y.lineWidth=Z,R.isInvalidPDFjsFont){let dt=[],lt=0;for(let wt of x)dt.push(wt.unicode),lt+=wt.width;y.fillText(dt.join(""),0,0),T.x+=lt*F*E,y.restore(),this.compose();return}let nt,pt=0;for(nt=0;nt<L;++nt){let dt=x[nt];if(typeof dt=="number"){pt+=U*dt*g/1e3;continue}let lt=!1,wt=(dt.isSpace?O:0)+k,Tt=dt.fontChar,xt=dt.accent,Dt,Rt,Bt=dt.width;if($){let Ht=dt.vmetric||P,le=-(dt.vmetric?Ht[1]:.5*Bt)*F,Se=Ht[2]*F;Bt=Ht?-Ht[0]:Bt,Dt=le/C,Rt=(pt+Se)/C}else Dt=pt/C,Rt=0;if(R.remeasure&&Bt>0){let Ht=1e3*y.measureText(Tt).width/g*C;if(Bt<Ht&&this.isFontSubpixelAAEnabled){let le=Bt/Ht;lt=!0,y.save(),y.scale(le,1),Dt/=le}else Bt!==Ht&&(Dt+=(Bt-Ht)/2e3*g/C)}if(this.contentVisible&&(dt.isInFont||R.missingFile)){if(V&&!xt)y.fillText(Tt,Dt,Rt);else if(this.paintChar(Tt,Dt,Rt,Q),xt){let Ht=Dt+g*xt.offset.x/C,le=Rt-g*xt.offset.y/C;this.paintChar(xt.fontChar,Ht,le,Q)}}pt+=$?Bt*F-wt*M:Bt*F+wt*M,lt&&y.restore()}$?T.y-=pt:T.x+=pt*E,y.restore(),this.compose()}showType3Text(x){let T=this.ctx,R=this.current,g=R.font,y=R.fontSize,C=R.fontDirection,k=g.vertical?1:-1,O=R.charSpacing,M=R.wordSpacing,E=R.textHScale*C,L=R.fontMatrix||i.FONT_IDENTITY_MATRIX,$=x.length,U,P,F,V;if(R.textRenderingMode!==i.TextRenderingMode.INVISIBLE&&y!==0){for(this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null,T.save(),T.transform(...R.textMatrix),T.translate(R.x,R.y),T.scale(E,C),U=0;U<$;++U){if(P=x[U],typeof P=="number"){V=k*P*y/1e3,this.ctx.translate(V,0),R.x+=V*E;continue}let Q=(P.isSpace?M:0)+O,Z=g.charProcOperatorList[P.operatorListId];if(!Z){(0,i.warn)(`Type3 character "${P.operatorListId}" is not available.`);continue}this.contentVisible&&(this.processingType3=P,this.save(),T.scale(y,y),T.transform(...L),this.executeOperatorList(Z),this.restore()),F=i.Util.applyTransform([P.width,0],L)[0]*y+Q,T.translate(F,0),R.x+=F*E}T.restore(),this.processingType3=null}}setCharWidth(x,T){}setCharWidthAndBounds(x,T,R,g,y,C){this.ctx.rect(R,g,y-R,C-g),this.ctx.clip(),this.endPath()}getColorN_Pattern(x){let T;if(x[0]==="TilingPattern"){let R=x[1],g=this.baseTransform||(0,n.getCurrentTransform)(this.ctx),y={createCanvasGraphics:C=>new st(C,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};T=new r(x,R,this.ctx,y,g)}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 g=i.Util.makeHexColor(x,T,R);this.ctx.strokeStyle=g,this.current.strokeColor=g}setFillRGBColor(x,T,R){let g=i.Util.makeHexColor(x,T,R);this.ctx.fillStyle=g,this.current.fillColor=g,this.current.patternFill=!1}_getPattern(x,T=null){let R;return this.cachedPatterns.has(x)?R=this.cachedPatterns.get(x):(R=(function(y){switch(y[0]){case"RadialAxial":return new u(y);case"Mesh":return new w(y);case"Dummy":return new S}throw new Error(`Unknown IR type: ${y[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),l);let g=(0,n.getCurrentTransformInverse)(T);if(g){let{width:y,height:C}=T.canvas,[k,O,M,E]=i.Util.getAxialAlignedBoundingBox([0,0,y,C],g);this.ctx.fillRect(k,O,M-k,E-O)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){(0,i.unreachable)("Should not call beginInlineImage")}beginImageData(){(0,i.unreachable)("Should not call beginImageData")}paintFormXObjectBegin(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],g=T[3]-T[1];this.ctx.rect(T[0],T[1],R,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(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 g=i.Util.getAxialAlignedBoundingBox(x.bbox,(0,n.getCurrentTransform)(T)),y=[0,0,T.canvas.width,T.canvas.height];g=i.Util.intersect(g,y)||[0,0,0,0];let C=Math.floor(g[0]),k=Math.floor(g[1]),O=Math.max(Math.ceil(g[2])-C,1),M=Math.max(Math.ceil(g[3])-k,1),E=1,L=1;O>b&&(E=O/b,O=b),M>b&&(L=M/b,M=b),this.current.startNewPathAndClipBox([0,0,O,M]);let $="groupAt"+this.groupLevel;x.smask&&($+="_smask_"+this.smaskCounter++%2);let U=this.cachedCanvases.getCanvas($,O,M),P=U.context;P.scale(1/E,1/L),P.translate(-C,-k),P.transform(...R),x.smask?this.smaskStack.push({canvas:U.canvas,context:P,offsetX:C,offsetY:k,scaleX:E,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(C,k),T.scale(E,L),T.save()),j(T,P),this.ctx=P,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 g=(0,n.getCurrentTransform)(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...g);let y=i.Util.getAxialAlignedBoundingBox([0,0,T.canvas.width,T.canvas.height],g);this.ctx.drawImage(T.canvas,0,0),this.ctx.restore(),this.compose(y)}}beginAnnotation(x,T,R,g,y){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 C=T[2]-T[0],k=T[3]-T[1];if(y&&this.annotationCanvasMap){(R=R.slice())[4]-=T[0],R[5]-=T[1],(T=T.slice())[0]=T[1]=0,T[2]=C,T[3]=k;let[O,M]=i.Util.singularValueDecompose2dScale((0,n.getCurrentTransform)(this.ctx)),{viewportScale:E}=this,L=Math.ceil(C*this.outputScaleX*E),$=Math.ceil(k*this.outputScaleY*E);this.annotationCanvas=this.canvasFactory.create(L,$);let{canvas:U,context:P}=this.annotationCanvas;this.annotationCanvasMap.set(x,U),this.annotationCanvas.savedCtx=this.ctx,this.ctx=P,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],C,k),this.ctx.clip(),this.endPath()}this.current=new I(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...R),this.transform(...g)}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,g=this.processingType3;if(g&&(g.compiled===void 0&&(g.compiled=(function(O){let{width:M,height:E}=O;if(M>1e3||E>1e3)return null;let L=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),$=M+1,U,P,F,V=new Uint8Array($*(E+1)),Q=M+7&-8,Z=new Uint8Array(Q*E),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),P=1;P<M;P++)Z[tt]!==Z[tt+1]&&(V[P]=Z[tt]?2:1,++nt),tt++;for(Z[tt]!==0&&(V[P]=2,++nt),U=1;U<E;U++){tt=U*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(P=1;P<M;P++)lt=(lt>>2)+(Z[tt+1]?4:0)+(Z[tt-Q+1]?8:0),L[lt]&&(V[F+P]=L[lt],++nt),tt++;if(Z[tt-Q]!==Z[tt]&&(V[F+P]=Z[tt]?2:4,++nt),nt>1e3)return null}for(tt=Q*(E-1),F=U*$,Z[tt]!==0&&(V[F]=8,++nt),P=1;P<M;P++)Z[tt]!==Z[tt+1]&&(V[F+P]=Z[tt]?4:8,++nt),tt++;if(Z[tt]!==0&&(V[F+P]=4,++nt),nt>1e3)return null;let pt=new Int32Array([0,$,-1,0,-$,0,0,0,1]),dt=new Path2D;for(U=0;nt&&U<=E;U++){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 Dt=pt[xt];do lt+=Dt;while(!V[lt]);let Rt=V[lt];Rt!==5&&Rt!==10?(xt=Rt,V[lt]=0):(xt=Rt&51*xt>>4,V[lt]&=xt>>2|xt<<2),dt.lineTo(lt%$,lt/$|0),V[lt]||--nt}while(Tt!==lt);--U}return Z=null,V=null,function(lt){lt.save(),lt.scale(1/M,-1/E),lt.translate(0,-E),lt.fill(dt),lt.beginPath(),lt.restore()}})(x)),g.compiled)){g.compiled(R);return}let y=this._createMaskCanvas(x),C=y.canvas;R.save(),R.setTransform(1,0,0,1,0,0),R.drawImage(C,y.offsetX,y.offsetY),R.restore(),this.compose()}paintImageMaskXObjectRepeat(x,T,R=0,g=0,y,C){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,g,y,0,0);let M=this._createMaskCanvas(x);k.setTransform(1,0,0,1,M.offsetX-O[4],M.offsetY-O[5]);for(let E=0,L=C.length;E<L;E+=2){let $=i.Util.transform(O,[T,R,g,y,C[E],C[E+1]]),[U,P]=i.Util.applyTransform([0,0],$);k.drawImage(M.canvas,U,P)}k.restore(),this.compose()}paintImageMaskXObjectGroup(x){if(!this.contentVisible)return;let T=this.ctx,R=this.current.fillColor,g=this.current.patternFill;for(let y of x){let{data:C,width:k,height:O,transform:M}=y,E=this.cachedCanvases.getCanvas("maskCanvas",k,O),L=E.context;L.save(),H(L,this.getObject(C,y)),L.globalCompositeOperation="source-in",L.fillStyle=g?R.getPattern(L,this,(0,n.getCurrentTransformInverse)(T),a):R,L.fillRect(0,0,k,O),L.restore(),T.save(),T.transform(...M),T.scale(1,-1),_(T,E.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,g){if(!this.contentVisible)return;let y=this.getObject(x);if(!y){(0,i.warn)("Dependent image isn't ready yet");return}let C=y.width,k=y.height,O=[];for(let M=0,E=g.length;M<E;M+=2)O.push({transform:[T,0,0,R,g[M],g[M+1]],x:0,y:0,w:C,h:k});this.paintInlineImageXObjectGroup(y,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:g}=x,y=this.cachedCanvases.getCanvas("inlineImage",R,g),C=y.context;return C.filter=this.current.transferMaps,C.drawImage(T,0,0),C.filter="none",y.canvas}paintInlineImageXObject(x){if(!this.contentVisible)return;let T=x.width,R=x.height,g=this.ctx;if(this.save(),!i.isNodeJS){let{filter:k}=g;k!=="none"&&k!==""&&(g.filter="none")}g.scale(1/T,-1/R);let y;if(x.bitmap)y=this.applyTransferMapsToBitmap(x);else if(typeof HTMLElement=="function"&&x instanceof HTMLElement||!x.data)y=x;else{let k=this.cachedCanvases.getCanvas("inlineImage",T,R).context;N(k,x),y=this.applyTransferMapsToCanvas(k)}let C=this._scaleImage(y,(0,n.getCurrentTransformInverse)(g));g.imageSmoothingEnabled=W((0,n.getCurrentTransform)(g),x.interpolate),_(g,C.img,0,0,C.paintWidth,C.paintHeight,0,-R,T,R),this.compose(),this.restore()}paintInlineImageXObjectGroup(x,T){if(!this.contentVisible)return;let R=this.ctx,g;if(x.bitmap)g=x.bitmap;else{let y=x.width,C=x.height,k=this.cachedCanvases.getCanvas("inlineImage",y,C).context;N(k,x),g=this.applyTransferMapsToCanvas(k)}for(let y of T)R.save(),R.transform(...y.transform),R.scale(1,-1),_(R,g,y.x,y.y,y.w,y.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]),g=Math.hypot(x[1],x[3]);this._cachedGetSinglePixelWidth=Math.max(R,g)/T}}return this._cachedGetSinglePixelWidth}getScaleForStroking(){if(this._cachedScaleForStroking[0]===-1){let{lineWidth:x}=this.current,{a:T,b:R,c:g,d:y}=this.ctx.getTransform(),C,k;if(R===0&&g===0){let O=Math.abs(T),M=Math.abs(y);if(O===M)if(x===0)C=k=1/O;else{let E=O*x;C=k=E<1?1/E:1}else if(x===0)C=1/O,k=1/M;else{let E=O*x,L=M*x;C=E<1?1/E:1,k=L<1?1/L:1}}else{let O=Math.abs(T*y-R*g),M=Math.hypot(T,R),E=Math.hypot(g,y);if(x===0)C=E/O,k=M/O;else{let L=x*O;C=E>L?E/L:1,k=M>L?M/L:1}}this._cachedScaleForStroking[0]=C,this._cachedScaleForStroking[1]=k}return this._cachedScaleForStroking}rescaleAndStroke(x){let{ctx:T}=this,{lineWidth:R}=this.current,[g,y]=this.getScaleForStroking();if(T.lineWidth=R||1,g===1&&y===1){T.stroke();return}let C=T.getLineDash();if(x&&T.save(),T.scale(g,y),C.length>0){let k=Math.max(g,y);T.setLineDash(C.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 G in i.OPS)st.prototype[G]!==void 0&&(st.prototype[i.OPS[G]]=st.prototype[G])},419:(s,t,e)=>{e.d(t,{DOMCMapReaderFactory:()=>u,DOMCanvasFactory:()=>d,DOMFilterFactory:()=>l,DOMSVGFactory:()=>p,DOMStandardFontDataFactory:()=>o,PDFDateString:()=>I,PageViewport:()=>w,PixelsPerInch:()=>c,RenderingCancelledException:()=>S,StatTimer:()=>b,fetchData:()=>m,getColorValues:()=>j,getCurrentTransform:()=>K,getCurrentTransformInverse:()=>it,getFilenameFromUrl:()=>r,getPdfFilenameFromUrl:()=>h,getRGB:()=>H,getXfaPageViewport:()=>N,isDataScheme:()=>f,isPdfFile:()=>v,isValidFetchUrl:()=>A,noContextMenu:()=>D,setLayerDimensions:()=>ot});var i=e(583),n=e(292);let a="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:z,ownerDocument:W=globalThis.document}={}){super(),this.#i=z,this.#n=W}get#o(){return this.#t||=new Map}get#l(){return this.#r||=new Map}get#a(){if(!this.#e){let z=this.#n.createElement("div"),{style:W}=z;W.visibility="hidden",W.contain="strict",W.width=W.height=0,W.position="absolute",W.top=W.left=0,W.zIndex=-1;let Y=this.#n.createElementNS(a,"svg");Y.setAttribute("width",0),Y.setAttribute("height",0),this.#e=this.#n.createElementNS(a,"defs"),z.append(Y),Y.append(this.#e),this.#n.body.append(z)}return this.#e}addFilter(z){if(!z)return"none";let W,Y,et,rt,ct=this.#o.get(z);if(ct)return ct;if(z.length===1){let T=z[0],R=new Array(256);for(let g=0;g<256;g++)R[g]=T[g]/255;rt=W=Y=et=R.join(",")}else{let[T,R,g]=z,y=new Array(256),C=new Array(256),k=new Array(256);for(let O=0;O<256;O++)y[O]=T[O]/255,C[O]=R[O]/255,k[O]=g[O]/255;W=y.join(","),Y=C.join(","),et=k.join(","),rt=`${W}${Y}${et}`}if(ct=this.#o.get(rt),ct)return this.#o.set(z,ct),ct;let st=`g_${this.#i}_transfer_map_${this.#s++}`,G=`url(#${st})`;this.#o.set(z,G),this.#o.set(rt,G);let x=this.#u(st);return this.#c(W,Y,et,x),G}addHCMFilter(z,W){let Y=`${z}-${W}`,et="base",rt=this.#l.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.#l.set(et,rt)),!z||!W))return rt.url;let ct=this.#f(z);z=n.Util.makeHexColor(...ct);let st=this.#f(W);if(W=n.Util.makeHexColor(...st),this.#a.style.color="",z==="#000000"&&W==="#ffffff"||z===W)return rt.url;let G=new Array(256);for(let y=0;y<=255;y++){let C=y/255;G[y]=C<=.03928?C/12.92:((C+.055)/1.055)**2.4}let x=G.join(","),T=`g_${this.#i}_hcm_filter`,R=rt.filter=this.#u(T);this.#c(x,x,x,R),this.#h(R);let g=(y,C)=>{let k=ct[y]/255,O=st[y]/255,M=new Array(C+1);for(let E=0;E<=C;E++)M[E]=k+E/C*(O-k);return M.join(",")};return this.#c(g(0,5),g(1,5),g(2,5),R),rt.url=`url(#${T})`,rt.url}addHighlightHCMFilter(z,W,Y,et,rt){let ct=`${W}-${Y}-${et}-${rt}`,st=this.#l.get(z);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.#l.set(z,st)),!W||!Y))return st.url;let[G,x]=[W,Y].map(this.#f.bind(this)),T=Math.round(.2126*G[0]+.7152*G[1]+.0722*G[2]),R=Math.round(.2126*x[0]+.7152*x[1]+.0722*x[2]),[g,y]=[et,rt].map(this.#f.bind(this));R<T&&([T,R,g,y]=[R,T,y,g]),this.#a.style.color="";let C=(M,E,L)=>{let $=new Array(256),U=(R-T)/L,P=M/255,F=(E-M)/(255*L),V=0;for(let Q=0;Q<=L;Q++){let Z=Math.round(T+Q*U),tt=P+Q*F;for(let nt=V;nt<=Z;nt++)$[nt]=tt;V=Z+1}for(let Q=V;Q<256;Q++)$[Q]=$[V-1];return $.join(",")},k=`g_${this.#i}_hcm_${z}_filter`,O=st.filter=this.#u(k);return this.#h(O),this.#c(C(g[0],y[0],5),C(g[1],y[1],5),C(g[2],y[2],5),O),st.url=`url(#${k})`,st.url}destroy(z=!1){(!z||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(z){let W=this.#n.createElementNS(a,"feColorMatrix");W.setAttribute("type","matrix"),W.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),z.append(W)}#u(z){let W=this.#n.createElementNS(a,"filter");return W.setAttribute("color-interpolation-filters","sRGB"),W.setAttribute("id",z),this.#a.append(W),W}#d(z,W,Y){let et=this.#n.createElementNS(a,W);et.setAttribute("type","discrete"),et.setAttribute("tableValues",Y),z.append(et)}#c(z,W,Y,et){let rt=this.#n.createElementNS(a,"feComponentTransfer");et.append(rt),this.#d(rt,"feFuncR",z),this.#d(rt,"feFuncG",W),this.#d(rt,"feFuncB",Y)}#f(z){return this.#a.style.color=z,H(getComputedStyle(this.#a).getPropertyValue("color"))}}class d extends i.BaseCanvasFactory{constructor({ownerDocument:z=globalThis.document}={}){super(),this._document=z}_createCanvas(z,W){let Y=this._document.createElement("canvas");return Y.width=z,Y.height=W,Y}}async function m(X,z="text"){if(A(X,document.baseURI)){let W=await fetch(X);if(!W.ok)throw new Error(W.statusText);switch(z){case"arraybuffer":return W.arrayBuffer();case"blob":return W.blob();case"json":return W.json()}return W.text()}return new Promise(((W,Y)=>{let et=new XMLHttpRequest;et.open("GET",X,!0),et.responseType=z,et.onreadystatechange=()=>{if(et.readyState===XMLHttpRequest.DONE)if(et.status!==200&&et.status!==0)Y(new Error(et.statusText));else{switch(z){case"arraybuffer":case"blob":case"json":W(et.response);return}W(et.responseText)}},et.send(null)}))}class u extends i.BaseCMapReaderFactory{_fetchData(z,W){return m(z,this.isCompressed?"arraybuffer":"text").then((Y=>({cMapData:Y instanceof ArrayBuffer?new Uint8Array(Y):(0,n.stringToBytes)(Y),compressionType:W})))}}class o extends i.BaseStandardFontDataFactory{_fetchData(z){return m(z,"arraybuffer").then((W=>new Uint8Array(W)))}}class p extends i.BaseSVGFactory{_createSVG(z){return document.createElementNS(a,z)}}class w{constructor({viewBox:z,scale:W,rotation:Y,offsetX:et=0,offsetY:rt=0,dontFlip:ct=!1}){this.viewBox=z,this.scale=W,this.rotation=Y,this.offsetX=et,this.offsetY=rt;let st=(z[2]+z[0])/2,G=(z[3]+z[1])/2,x,T,R,g,y,C,k,O;switch((Y%=360)<0&&(Y+=360),Y){case 180:x=-1,T=0,R=0,g=1;break;case 90:x=0,T=1,R=1,g=0;break;case 270:x=0,T=-1,R=-1,g=0;break;case 0:x=1,T=0,R=0,g=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}ct&&(R=-R,g=-g),x===0?(y=Math.abs(G-z[1])*W+et,C=Math.abs(st-z[0])*W+rt,k=(z[3]-z[1])*W,O=(z[2]-z[0])*W):(y=Math.abs(st-z[0])*W+et,C=Math.abs(G-z[1])*W+rt,k=(z[2]-z[0])*W,O=(z[3]-z[1])*W),this.transform=[x*W,T*W,R*W,g*W,y-x*W*st-R*W*G,C-T*W*st-g*W*G],this.width=k,this.height=O}get rawDims(){let{viewBox:z}=this;return(0,n.shadow)(this,"rawDims",{pageWidth:z[2]-z[0],pageHeight:z[3]-z[1],pageX:z[0],pageY:z[1]})}clone({scale:z=this.scale,rotation:W=this.rotation,offsetX:Y=this.offsetX,offsetY:et=this.offsetY,dontFlip:rt=!1}={}){return new w({viewBox:this.viewBox.slice(),scale:z,rotation:W,offsetX:Y,offsetY:et,dontFlip:rt})}convertToViewportPoint(z,W){return n.Util.applyTransform([z,W],this.transform)}convertToViewportRectangle(z){let W=n.Util.applyTransform([z[0],z[1]],this.transform),Y=n.Util.applyTransform([z[2],z[3]],this.transform);return[W[0],W[1],Y[0],Y[1]]}convertToPdfPoint(z,W){return n.Util.applyInverseTransform([z,W],this.transform)}}class S extends n.BaseException{constructor(z,W=0){super(z,"RenderingCancelledException"),this.extraDelay=W}}function f(X){let z=X.length,W=0;for(;W<z&&X[W].trim()==="";)W++;return X.substring(W,W+5).toLowerCase()==="data:"}function v(X){return typeof X=="string"&&/\.pdf$/i.test(X)}function r(X,z=!1){return z||([X]=X.split(/[#?]/,1)),X.substring(X.lastIndexOf("/")+1)}function h(X,z="document.pdf"){if(typeof X!="string")return z;if(f(X))return(0,n.warn)('getPdfFilenameFromUrl: ignore "data:"-URL for performance reasons.'),z;let W=/[^/?#=]+\.pdf\b(?!.*\.pdf\b)/i,Y=/^(?:(?:[^:]+:)?\/\/[^/]+)?([^?#]*)(\?[^#]*)?(#.*)?$/.exec(X),et=W.exec(Y[1])||W.exec(Y[2])||W.exec(Y[3]);if(et&&(et=et[0],et.includes("%")))try{et=W.exec(decodeURIComponent(et))[0]}catch{}return et||z}class b{started=Object.create(null);times=[];time(z){z in this.started&&(0,n.warn)(`Timer is already running for ${z}`),this.started[z]=Date.now()}timeEnd(z){z in this.started||(0,n.warn)(`Timer has not been started for ${z}`),this.times.push({name:z,start:this.started[z],end:Date.now()}),delete this.started[z]}toString(){let z=[],W=0;for(let{name:Y}of this.times)W=Math.max(Y.length,W);for(let{name:Y,start:et,end:rt}of this.times)z.push(`${Y.padEnd(W)} ${rt-et}ms
|
|
6
|
-
`);return z.join("")}}function A(X,z){try{let{protocol:W}=z?new URL(X,z):new URL(X);return W==="http:"||W==="https:"}catch{return!1}}function D(X){X.preventDefault()}let _;class I{static toDateObject(z){if(!z||typeof z!="string")return null;_||=new RegExp("^D:(\\d{4})(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?(\\d{2})?([Z|+|-])?(\\d{2})?'?(\\d{2})?'?");let W=_.exec(z);if(!W)return null;let Y=parseInt(W[1],10),et=parseInt(W[2],10);et=et>=1&&et<=12?et-1:0;let rt=parseInt(W[3],10);rt=rt>=1&&rt<=31?rt:1;let ct=parseInt(W[4],10);ct=ct>=0&&ct<=23?ct:0;let st=parseInt(W[5],10);st=st>=0&&st<=59?st:0;let G=parseInt(W[6],10);G=G>=0&&G<=59?G:0;let x=W[7]||"Z",T=parseInt(W[8],10);T=T>=0&&T<=23?T:0;let R=parseInt(W[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,G))}}function N(X,{scale:z=1,rotation:W=0}){let{width:Y,height:et}=X.attributes.style,rt=[0,0,parseInt(Y),parseInt(et)];return new w({viewBox:rt,scale:z,rotation:W})}function H(X){if(X.startsWith("#")){let z=parseInt(X.slice(1),16);return[(16711680&z)>>16,(65280&z)>>8,255&z]}return X.startsWith("rgb(")?X.slice(4,-1).split(",").map((z=>parseInt(z))):X.startsWith("rgba(")?X.slice(5,-1).split(",").map((z=>parseInt(z))).slice(0,3):((0,n.warn)(`Not a valid color format: "${X}"`),[0,0,0])}function j(X){let z=document.createElement("span");z.style.visibility="hidden",document.body.append(z);for(let W of X.keys()){z.style.color=W;let Y=window.getComputedStyle(z).color;X.set(W,H(Y))}z.remove()}function K(X){let{a:z,b:W,c:Y,d:et,e:rt,f:ct}=X.getTransform();return[z,W,Y,et,rt,ct]}function it(X){let{a:z,b:W,c:Y,d:et,e:rt,f:ct}=X.getTransform().invertSelf();return[z,W,Y,et,rt,ct]}function ot(X,z,W=!1,Y=!0){if(z instanceof w){let{pageWidth:et,pageHeight:rt}=z.rawDims,{style:ct}=X,st=n.FeatureTest.isCSSRoundSupported,G=`var(--scale-factor) * ${et}px`,x=`var(--scale-factor) * ${rt}px`,T=st?`round(${G}, 1px)`:`calc(${G})`,R=st?`round(${x}, 1px)`:`calc(${x})`;W&&z.rotation%180!=0?(ct.width=R,ct.height=T):(ct.width=T,ct.height=R)}Y&&X.setAttribute("data-main-rotation",z.rotation)}},47:(s,t,e)=>{e.d(t,{DrawLayer:()=>a});var i=e(419),n=e(292);class a{#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 d of this.#i.values())d.remove(),l.append(d);this.#t=l}}else this.#t=l}static get _svgFactory(){return(0,n.shadow)(this,"_svgFactory",new i.DOMSVGFactory)}static#r(l,{x:d=0,y:m=0,width:u=1,height:o=1}={}){let{style:p}=l;p.top=100*m+"%",p.left=100*d+"%",p.width=100*u+"%",p.height=100*o+"%"}#s(l){let d=a._svgFactory.create(1,1,!0);return this.#t.append(d),d.setAttribute("aria-hidden",!0),a.#r(d,l),d}#o(l,d){let m=a._svgFactory.createElement("clipPath");l.append(m);let u=`clip_${d}`;m.setAttribute("id",u),m.setAttribute("clipPathUnits","objectBoundingBox");let o=a._svgFactory.createElement("use");return m.append(o),o.setAttribute("href",`#${d}`),o.classList.add("clip"),u}highlight(l,d,m,u=!1){let o=this.#e++,p=this.#s(l.box);p.classList.add("highlight"),l.free&&p.classList.add("free");let w=a._svgFactory.createElement("defs");p.append(w);let S=a._svgFactory.createElement("path");w.append(S);let f=`path_p${this.pageIndex}_${o}`;S.setAttribute("id",f),S.setAttribute("d",l.toSVGPath()),u&&this.#n.set(o,S);let v=this.#o(w,f),r=a._svgFactory.createElement("use");return p.append(r),p.setAttribute("fill",d),p.setAttribute("fill-opacity",m),r.setAttribute("href",`#${f}`),this.#i.set(o,p),{id:o,clipPathId:`url(#${v})`}}highlightOutline(l){let d=this.#e++,m=this.#s(l.box);m.classList.add("highlightOutline");let u=a._svgFactory.createElement("defs");m.append(u);let o=a._svgFactory.createElement("path");u.append(o);let p=`path_p${this.pageIndex}_${d}`;o.setAttribute("id",p),o.setAttribute("d",l.toSVGPath()),o.setAttribute("vector-effect","non-scaling-stroke");let w;if(l.free){m.classList.add("free");let v=a._svgFactory.createElement("mask");u.append(v),w=`mask_p${this.pageIndex}_${d}`,v.setAttribute("id",w),v.setAttribute("maskUnits","objectBoundingBox");let r=a._svgFactory.createElement("rect");v.append(r),r.setAttribute("width","1"),r.setAttribute("height","1"),r.setAttribute("fill","white");let h=a._svgFactory.createElement("use");v.append(h),h.setAttribute("href",`#${p}`),h.setAttribute("stroke","none"),h.setAttribute("fill","black"),h.setAttribute("fill-rule","nonzero"),h.classList.add("mask")}let S=a._svgFactory.createElement("use");m.append(S),S.setAttribute("href",`#${p}`),w&&S.setAttribute("mask",`url(#${w})`);let f=S.cloneNode();return m.append(f),S.classList.add("mainOutline"),f.classList.add("secondaryOutline"),this.#i.set(d,m),d}finalizeLine(l,d){let m=this.#n.get(l);this.#n.delete(l),this.updateBox(l,d.box),m.setAttribute("d",d.toSVGPath())}updateLine(l,d){this.#i.get(l).firstChild.firstChild.setAttribute("d",d.toSVGPath())}removeFreeHighlight(l){this.remove(l),this.#n.delete(l)}updatePath(l,d){this.#n.get(l).setAttribute("d",d.toSVGPath())}updateBox(l,d){a.#r(this.#i.get(l),d)}show(l,d){this.#i.get(l).classList.toggle("hidden",!d)}rotate(l,d){this.#i.get(l).setAttribute("data-main-rotation",d)}changeColor(l,d){this.#i.get(l).setAttribute("fill",d)}changeOpacity(l,d){this.#i.get(l).setAttribute("fill-opacity",d)}addClass(l,d){this.#i.get(l).classList.add(d)}removeClass(l,d){this.#i.get(l).classList.remove(d)}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:()=>f});var i=e(292),n=e(310),a=e(830),c=e(976);let l=/\r\n?|\n/g;class d 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="";#l=`${this.id}-editor`;#a;#h=null;static _freeTextDefaultContent="";static _internalPadding=0;static _defaultColor=null;static _defaultFontSize=10;static get _keyboardManager(){let r=d.prototype,h=D=>D.isEmpty(),b=a.AnnotationEditorUIManager.TRANSLATE_SMALL,A=a.AnnotationEditorUIManager.TRANSLATE_BIG;return(0,i.shadow)(this,"_keyboardManager",new a.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:h}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],r._translateEmpty,{args:[-A,0],checker:h}],[["ArrowRight","mac+ArrowRight"],r._translateEmpty,{args:[b,0],checker:h}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],r._translateEmpty,{args:[A,0],checker:h}],[["ArrowUp","mac+ArrowUp"],r._translateEmpty,{args:[0,-b],checker:h}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],r._translateEmpty,{args:[0,-A],checker:h}],[["ArrowDown","mac+ArrowDown"],r._translateEmpty,{args:[0,b],checker:h}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],r._translateEmpty,{args:[0,A],checker:h}]]))}static _type="freetext";static _editorType=i.AnnotationEditorType.FREETEXT;constructor(r){super({...r,name:"freeTextEditor"}),this.#s=r.color||d._defaultColor||n.AnnotationEditor._defaultLineColor,this.#a=r.fontSize||d._defaultFontSize}static initialize(r,h){n.AnnotationEditor.initialize(r,h,{strings:["pdfjs-free-text-default-content"]});let b=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(b.getPropertyValue("--freetext-padding"))}static updateDefaultParams(r,h){switch(r){case i.AnnotationEditorParamsType.FREETEXT_SIZE:d._defaultFontSize=h;break;case i.AnnotationEditorParamsType.FREETEXT_COLOR:d._defaultColor=h}}updateParams(r,h){switch(r){case i.AnnotationEditorParamsType.FREETEXT_SIZE:this.#u(h);break;case i.AnnotationEditorParamsType.FREETEXT_COLOR:this.#d(h)}}static get defaultPropertiesToUpdate(){return[[i.AnnotationEditorParamsType.FREETEXT_SIZE,d._defaultFontSize],[i.AnnotationEditorParamsType.FREETEXT_COLOR,d._defaultColor||n.AnnotationEditor._defaultLineColor]]}get propertiesToUpdate(){return[[i.AnnotationEditorParamsType.FREETEXT_SIZE,this.#a],[i.AnnotationEditorParamsType.FREETEXT_COLOR,this.#s]]}#u(r){let h=A=>{this.editorDiv.style.fontSize=`calc(${A}px * var(--scale-factor))`,this.translate(0,-(A-this.#a)*this.parentScale),this.#a=A,this.#f()},b=this.#a;this.addCommands({cmd:h.bind(this,r),undo:h.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 h=A=>{this.#s=this.editorDiv.style.color=A},b=this.#s;this.addCommands({cmd:h.bind(this,r),undo:h.bind(this,b),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:i.AnnotationEditorParamsType.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})}_translateEmpty(r,h){this._uiManager.translateSelectedEditors(r,h,!0)}getInitialTranslation(){let r=this.parentScale;return[-d._internalPadding*r,-(d._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.#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 h of this.editorDiv.childNodes)r.push(d.#g(h));return r.join(`
|
|
7
|
-
`)}#f(){let[r,h]=this.parentDimensions,b;if(this.isAttachedToDOM)b=this.div.getBoundingClientRect();else{let{currentLayer:A,div:D}=this,_=D.style.display;D.style.display="hidden",A.div.append(this.div),b=D.getBoundingClientRect(),D.remove(),D.style.display=_}this.rotation%180==this.parentRotation%180?(this.width=b.width/r,this.height=b.height/h):(this.width=b.height/r,this.height=b.width/h),this.fixAndSetPosition()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();let r=this.#o,h=this.#o=this.#c().trimEnd();if(r===h)return;let b=A=>{this.#o=A,A?(this.#p(),this._uiManager.rebuild(this),this.#f()):this.remove()};this.addCommands({cmd:()=>{b(h)},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){d._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,h;this.width&&(r=this.x,h=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((A=>this.editorDiv?.setAttribute("default-content",A))),this.editorDiv.contentEditable=!0;let{style:b}=this.editorDiv;if(b.fontSize=`calc(${this.#a}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,a.bindEvents)(this,this.div,["dblclick","keydown"]),this.width){let[A,D]=this.parentDimensions;if(this.annotationElementId){let{position:_}=this.#h,[I,N]=this.getInitialTranslation();[I,N]=this.pageTranslationToScreen(I,N);let[H,j]=this.pageDimensions,[K,it]=this.pageTranslation,ot,X;switch(this.rotation){case 0:ot=r+(_[0]-K)/H,X=h+this.height-(_[1]-it)/j;break;case 90:ot=r+(_[0]-K)/H,X=h-(_[1]-it)/j,[I,N]=[N,-I];break;case 180:ot=r-this.width+(_[0]-K)/H,X=h-(_[1]-it)/j,[I,N]=[-I,-N];break;case 270:ot=r+(_[0]-K-this.height*j)/H,X=h+(_[1]-it-this.width*H)/j,[I,N]=[-N,I]}this.setAt(ot*A,X*D,I,N)}else this.setAt(r*A,h*D,this.width*A,this.height*D);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 h=r.clipboardData||window.clipboardData,{types:b}=h;if(b.length===1&&b[0]==="text/plain")return;r.preventDefault();let A=d.#m(h.getData("text")||"").replaceAll(l,`
|
|
8
|
-
`);if(!A)return;let D=window.getSelection();if(!D.rangeCount)return;this.editorDiv.normalize(),D.deleteFromDocument();let _=D.getRangeAt(0);if(!A.includes(`
|
|
9
|
-
`)){_.insertNode(document.createTextNode(A)),this.editorDiv.normalize(),D.collapseToStart();return}let{startContainer:I,startOffset:N}=_,H=[],j=[];if(I.nodeType===Node.TEXT_NODE){let ot=I.parentElement;if(j.push(I.nodeValue.slice(N).replaceAll(l,"")),ot!==this.editorDiv){let X=H;for(let z of this.editorDiv.childNodes)z!==ot?X.push(d.#g(z)):X=j}H.push(I.nodeValue.slice(0,N).replaceAll(l,""))}else if(I===this.editorDiv){let ot=H,X=0;for(let z of this.editorDiv.childNodes)X++===N&&(ot=j),ot.push(d.#g(z))}this.#o=`${H.join(`
|
|
10
|
-
`)}${A}${j.join(`
|
|
11
|
-
`)}`,this.#p();let K=new Range,it=H.reduce(((ot,X)=>ot+X.length),0);for(let{firstChild:ot}of this.editorDiv.childNodes)if(ot.nodeType===Node.TEXT_NODE){let X=ot.nodeValue.length;if(it<=X){K.setStart(ot,it),K.setEnd(ot,it);break}it-=X}D.removeAllRanges(),D.addRange(K)}#p(){if(this.editorDiv.replaceChildren(),this.#o)for(let r of this.#o.split(`
|
|
12
|
-
`)){let h=document.createElement("div");h.append(r?document.createTextNode(r):document.createElement("br")),this.editorDiv.append(h)}}#y(){return this.#o.replaceAll("\xA0"," ")}static#m(r){return r.replaceAll(" ","\xA0")}get contentDiv(){return this.editorDiv}static deserialize(r,h,b){let A=null;if(r instanceof c.FreeTextAnnotationElement){let{data:{defaultAppearanceData:{fontSize:_,fontColor:I},rect:N,rotation:H,id:j},textContent:K,textPosition:it,parent:{page:{pageNumber:ot}}}=r;if(!K||K.length===0)return null;A=r={annotationType:i.AnnotationEditorType.FREETEXT,color:Array.from(I),fontSize:_,value:K.join(`
|
|
13
|
-
`),position:it,pageIndex:ot-1,rect:N,rotation:H,id:j,deleted:!1}}let D=super.deserialize(r,h,b);return D.#a=r.fontSize,D.#s=i.Util.makeHexColor(...r.color),D.#o=d.#m(r.value),D.annotationElementId=r.id||null,D.#h=A,D}serialize(r=!1){if(this.isEmpty())return null;if(this.deleted)return{pageIndex:this.pageIndex,id:this.annotationElementId,deleted:!0};let h=d._internalPadding*this.parentScale,b=this.getRect(h,h),A=n.AnnotationEditor._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:this.#s),D={annotationType:i.AnnotationEditorType.FREETEXT,color:A,fontSize:this.#a,value:this.#y(),pageIndex:this.pageIndex,rect:b,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return r?D:this.annotationElementId&&!this.#b(D)?null:(D.id=this.annotationElementId,D)}#b(r){let{value:h,fontSize:b,color:A,pageIndex:D}=this.#h;return this._hasBeenMoved||r.value!==h||r.fontSize!==b||r.color.some(((_,I)=>_!==A[I]))||r.pageIndex!==D}}var m=e(61),u=e(259),o=e(419);class p extends n.AnnotationEditor{#t=null;#e=0;#i;#n=null;#r=null;#s=null;#o=null;#l=0;#a=null;#h=null;#u=null;#d=!1;#c=this.#C.bind(this);#f=null;#g;#p=null;#y="";#m;#b="";static _defaultColor=null;static _defaultOpacity=1;static _defaultThickness=12;static _l10nPromise;static _type="highlight";static _editorType=i.AnnotationEditorType.HIGHLIGHT;static _freeHighlightId=-1;static _freeHighlight=null;static _freeHighlightClipId="";static get _keyboardManager(){let r=p.prototype;return(0,i.shadow)(this,"_keyboardManager",new a.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||p._defaultColor,this.#m=r.thickness||p._defaultThickness,this.#g=r.opacity||p._defaultOpacity,this.#i=r.boxes||null,this.#b=r.methodOfCreation||"",this.#y=r.text||"",this._isDraggable=!1,r.highlightId>-1?(this.#d=!0,this.#_(r),this.#E()):(this.#t=r.anchorNode,this.#e=r.anchorOffset,this.#o=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 h=new m.Outliner(this.#i,.0025,.001,this._uiManager.direction==="ltr");this.#s=h.getOutlines();let{lastPoint:b}=this.#s.box;this.#f=[(b[0]-this.x)/this.width,(b[1]-this.y)/this.height]}#_({highlightOutlines:r,highlightId:h,clipPathId:b}){if(this.#h=r,this.#s=r.getNewOutline(this.#m/2+1.5,.0025),h>=0)this.#u=h,this.#n=b,this.parent.drawLayer.finalizeLine(h,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,p.#A(this.#h.box,(H-this.rotation+360)%360)),this.parent.drawLayer.updateLine(this.#p,this.#s),this.parent.drawLayer.updateBox(this.#p,p.#A(this.#s.box,H))}let{x:A,y:D,width:_,height:I}=r.box;switch(this.rotation){case 0:this.x=A,this.y=D,this.width=_,this.height=I;break;case 90:{let[H,j]=this.parentDimensions;this.x=D,this.y=1-A,this.width=_*j/H,this.height=I*H/j;break}case 180:this.x=1-A,this.y=1-D,this.width=_,this.height=I;break;case 270:{let[H,j]=this.parentDimensions;this.x=1-D,this.y=A,this.width=_*j/H,this.height=I*H/j;break}}let{lastPoint:N}=this.#s.box;this.#f=[(N[0]-A)/_,(N[1]-D)/I]}static initialize(r,h){n.AnnotationEditor.initialize(r,h),p._defaultColor||=h.highlightColors?.values().next().value||"#fff066"}static updateDefaultParams(r,h){switch(r){case i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:p._defaultColor=h;break;case i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:p._defaultThickness=h}}translateInPage(r,h){}get toolbarPosition(){return this.#f}updateParams(r,h){switch(r){case i.AnnotationEditorParamsType.HIGHLIGHT_COLOR:this.#M(h);break;case i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS:this.#w(h)}}static get defaultPropertiesToUpdate(){return[[i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR,p._defaultColor],[i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS,p._defaultThickness]]}get propertiesToUpdate(){return[[i.AnnotationEditorParamsType.HIGHLIGHT_COLOR,this.color||p._defaultColor],[i.AnnotationEditorParamsType.HIGHLIGHT_THICKNESS,this.#m||p._defaultThickness],[i.AnnotationEditorParamsType.HIGHLIGHT_FREE,this.#d]]}#M(r){let h=A=>{this.color=A,this.parent?.drawLayer.changeColor(this.#u,A),this.#r?.updateColor(A)},b=this.color;this.addCommands({cmd:h.bind(this,r),undo:h.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 h=this.#m,b=A=>{this.#m=A,this.#x(A)};this.addCommands({cmd:b.bind(this,r),undo:b.bind(this,h),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.#k())}getBaseTranslation(){return[0,0]}getRect(r,h){return super.getRect(r,h,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 h=!1;this.parent&&!r?this.#v():r&&(this.#E(r),h=!this.parent&&this.div?.classList.contains("selectedEditor")),super.setParent(r),this.show(this._isVisible),h&&this.select()}#x(r){if(!this.#d)return;this.#_({highlightOutlines:this.#h.getNewOutline(r/2)}),this.fixAndSetPosition();let[h,b]=this.parentDimensions;this.setDims(this.width*h,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.#a&&(this.#a.style.clipPath=this.#n))}static#A({x:r,y:h,width:b,height:A},D){switch(D){case 90:return{x:1-h-A,y:r,width:A,height:b};case 180:return{x:1-r-b,y:1-h-A,width:b,height:A};case 270:return{x:h,y:1-r-b,width:A,height:b}}return{x:r,y:h,width:b,height:A}}rotate(r){let{drawLayer:h}=this.parent,b;this.#d?(r=(r-this.rotation+360)%360,b=p.#A(this.#h.box,r)):b=p.#A(this,r),h.rotate(this.#u,r),h.rotate(this.#p,r),h.updateBox(this.#u,b),h.updateBox(this.#p,p.#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 h=this.#a=document.createElement("div");r.append(h),h.setAttribute("aria-hidden","true"),h.className="internal",h.style.clipPath=this.#n;let[b,A]=this.parentDimensions;return this.setDims(this.width*b,this.height*A),(0,a.bindEvents)(this,this.#a,["pointerover","pointerleave"]),this.enableEditing(),r}pointerover(){this.parent.drawLayer.addClass(this.#p,"hovered")}pointerleave(){this.parent.drawLayer.removeClass(this.#p,"hovered")}#C(r){p._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 h=window.getSelection();r?h.setPosition(this.#t,this.#e):h.setPosition(this.#o,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.#T(!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))}#k(){return this.#d?this.rotation:0}#R(){if(this.#d)return null;let[r,h]=this.pageDimensions,b=this.#i,A=new Array(8*b.length),D=0;for(let{x:_,y:I,width:N,height:H}of b){let j=_*r,K=(1-I-H)*h;A[D]=A[D+4]=j,A[D+1]=A[D+3]=K,A[D+2]=A[D+6]=j+N*r,A[D+5]=A[D+7]=K+H*h,D+=8}return A}#P(r){return this.#h.serialize(r,this.#k())}static startHighlighting(r,h,{target:b,x:A,y:D}){let{x:_,y:I,width:N,height:H}=b.getBoundingClientRect(),j=X=>{this.#L(r,X)},K={capture:!0,passive:!1},it=X=>{X.preventDefault(),X.stopPropagation()},ot=X=>{b.removeEventListener("pointermove",j),window.removeEventListener("blur",ot),window.removeEventListener("pointerup",ot),window.removeEventListener("pointerdown",it,K),window.removeEventListener("contextmenu",o.noContextMenu),this.#I(r,X)};window.addEventListener("blur",ot),window.addEventListener("pointerup",ot),window.addEventListener("pointerdown",it,K),window.addEventListener("contextmenu",o.noContextMenu),b.addEventListener("pointermove",j),this._freeHighlight=new m.FreeOutliner({x:A,y:D},[_,I,N,H],r.scale,this._defaultThickness/2,h,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=r.drawLayer.highlight(this._freeHighlight,this._defaultColor,this._defaultOpacity,!0)}static#L(r,h){this._freeHighlight.add(h)&&r.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)}static#I(r,h){this._freeHighlight.isEmpty()?r.drawLayer.removeFreeHighlight(this._freeHighlightId):r.createAndAddNewEditor(h,!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,h,b){let A=super.deserialize(r,h,b),{rect:[D,_,I,N],color:H,quadPoints:j}=r;A.color=i.Util.makeHexColor(...H),A.#g=r.opacity;let[K,it]=A.pageDimensions;A.width=(I-D)/K,A.height=(N-_)/it;let ot=A.#i=[];for(let X=0;X<j.length;X+=8)ot.push({x:(j[4]-I)/K,y:(N-(1-j[X+5]))/it,width:(j[X+2]-j[X])/K,height:(j[X+5]-j[X+1])/it});return A.#S(),A}serialize(r=!1){if(this.isEmpty()||r)return null;let h=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.#R(),outlines:this.#P(h),pageIndex:this.pageIndex,rect:h,rotation:this.#k(),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);#o=null;#l=new Path2D;#a=!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,h){n.AnnotationEditor.initialize(r,h)}static updateDefaultParams(r,h){switch(r){case i.AnnotationEditorParamsType.INK_THICKNESS:w._defaultThickness=h;break;case i.AnnotationEditorParamsType.INK_COLOR:w._defaultColor=h;break;case i.AnnotationEditorParamsType.INK_OPACITY:w._defaultOpacity=h/100}}updateParams(r,h){switch(r){case i.AnnotationEditorParamsType.INK_THICKNESS:this.#p(h);break;case i.AnnotationEditorParamsType.INK_COLOR:this.#y(h);break;case i.AnnotationEditorParamsType.INK_OPACITY:this.#m(h)}}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 h=A=>{this.thickness=A,this.#N()},b=this.thickness;this.addCommands({cmd:h.bind(this,r),undo:h.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 h=A=>{this.color=A,this.#C()},b=this.color;this.addCommands({cmd:h.bind(this,r),undo:h.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 h=A=>{this.opacity=A,this.#C()};r/=100;let b=this.opacity;this.addCommands({cmd:h.bind(this,r),undo:h.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.#R()),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.#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,h]=this.parentDimensions,b=this.width*r,A=this.height*h;this.setDimensions(b,A)}enableEditMode(){!this.#a&&this.canvas!==null&&(super.enableEditMode(),this._isDraggable=!1,this.canvas.addEventListener("pointerdown",this.#s))}disableEditMode(){this.isInEditMode()&&this.canvas!==null&&(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),this.canvas.removeEventListener("pointerdown",this.#s))}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return this.paths.length===0||this.paths.length===1&&this.paths[0].length===0}#b(){let{parentRotation:r,parentDimensions:[h,b]}=this;switch(r){case 90:return[0,b,b,h];case 180:return[h,b,h,b];case 270:return[h,0,b,h];default:return[0,0,h,b]}}#S(){let{ctx:r,color:h,opacity:b,thickness:A,parentScale:D,scaleFactor:_}=this;r.lineWidth=A*D/_,r.lineCap="round",r.lineJoin="round",r.miterLimit=10,r.strokeStyle=`${h}${(0,a.opacityToHex)(b)}`}#_(r,h){this.canvas.addEventListener("contextmenu",o.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.#P(),this.thickness||=w._defaultThickness,this.color||=w._defaultColor||n.AnnotationEditor._defaultLineColor,this.opacity??=w._defaultOpacity),this.currentPath.push([r,h]),this.#h=!1,this.#S(),this.#g=()=>{this.#v(),this.#g&&window.requestAnimationFrame(this.#g)},window.requestAnimationFrame(this.#g)}#M(r,h){let[b,A]=this.currentPath.at(-1);if(this.currentPath.length>1&&r===b&&h===A)return;let D=this.currentPath,_=this.#l;D.push([r,h]),this.#h=!0,D.length<=2?(_.moveTo(...D[0]),_.lineTo(r,h)):(D.length===3&&(this.#l=_=new Path2D,_.moveTo(...D[0])),this.#E(_,...D.at(-3),...D.at(-2),r,h))}#w(){if(this.currentPath.length===0)return;let r=this.currentPath.at(-1);this.#l.lineTo(...r)}#x(r,h){this.#g=null,r=Math.min(Math.max(r,0),this.canvas.width),h=Math.min(Math.max(h,0),this.canvas.height),this.#M(r,h),this.#w();let b;if(this.currentPath.length!==1)b=this.#A();else{let _=[r,h];b=[[_,_.slice(),_.slice(),_]]}let A=this.#l,D=this.currentPath;this.currentPath=[],this.#l=new Path2D,this.addCommands({cmd:()=>{this.allRawPaths.push(D),this.paths.push(b),this.bezierPath2D.push(A),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.#R()),this.#N())},mustExec:!0})}#v(){if(!this.#h)return;this.#h=!1;let r=Math.ceil(this.thickness*this.parentScale),h=this.currentPath.slice(-3),b=h.map((_=>_[0])),A=h.map((_=>_[1])),{ctx:D}=(Math.min(...b),Math.max(...b),Math.min(...A),Math.max(...A),this);D.save(),D.clearRect(0,0,this.canvas.width,this.canvas.height);for(let _ of this.bezierPath2D)D.stroke(_);D.stroke(this.#l),D.restore()}#E(r,h,b,A,D,_,I){let N=(h+A)/2,H=(b+D)/2,j=(A+_)/2,K=(D+I)/2;r.bezierCurveTo(N+2*(A-N)/3,H+2*(D-H)/3,j+2*(A-j)/3,K+2*(D-K)/3,j,K)}#A(){let r=this.currentPath;if(r.length<=2)return[[r[0],r[0],r.at(-1),r.at(-1)]];let h=[],b,[A,D]=r[0];for(b=1;b<r.length-2;b++){let[it,ot]=r[b],[X,z]=r[b+1],W=(it+X)/2,Y=(ot+z)/2,et=[A+2*(it-A)/3,D+2*(ot-D)/3],rt=[W+2*(it-W)/3,Y+2*(ot-Y)/3];h.push([[A,D],et,rt,[W,Y]]),[A,D]=[W,Y]}let[_,I]=r[b],[N,H]=r[b+1],j=[A+2*(_-A)/3,D+2*(I-D)/3],K=[N+2*(_-N)/3,H+2*(I-H)/3];return h.push([[A,D],j,K,[N,H]]),h}#C(){if(this.isEmpty()){this.#I();return}this.#S();let{canvas:r,ctx:h}=this;h.setTransform(1,0,0,1,0,0),h.clearRect(0,0,r.width,r.height),this.#I();for(let b of this.bezierPath2D)h.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.#_(r.offsetX,r.offsetY))}canvasPointermove(r){r.preventDefault(),this.#M(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",o.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")}#R(){this.#d=new ResizeObserver((r=>{let h=r[0].contentRect;h.width&&h.height&&this.setDimensions(h.width,h.height)})),this.#d.observe(this.div)}get isResizable(){return!this.isEmpty()&&this.#a}render(){if(this.div)return this.div;let r,h;this.width&&(r=this.x,h=this.y),super.render(),this.div.setAttribute("data-l10n-id","pdfjs-ink");let[b,A,D,_]=this.#b();if(this.setAt(b,A,0,0),this.setDims(D,_),this.#k(),this.width){let[I,N]=this.parentDimensions;this.setAspectRatio(this.width*I,this.height*N),this.setAt(r*I,h*N,this.width*I,this.height*N),this.#u=!0,this.#P(),this.setDims(this.width*I,this.height*N),this.#C(),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return this.#R(),this.div}#P(){if(!this.#u)return;let[r,h]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*r),this.canvas.height=Math.ceil(this.height*h),this.#I()}setDimensions(r,h){let b=Math.round(r),A=Math.round(h);if(this.#c===b&&this.#f===A)return;this.#c=b,this.#f=A,this.canvas.style.visibility="hidden";let[D,_]=this.parentDimensions;this.width=r/D,this.height=h/_,this.fixAndSetPosition(),this.#a&&this.#L(r,h),this.#P(),this.#C(),this.canvas.style.visibility="visible",this.fixDims()}#L(r,h){let b=this.#$(),A=(r-b)/this.#e,D=(h-b)/this.#t;this.scaleFactor=Math.min(A,D)}#I(){let r=this.#$()/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+r,this.translationY*this.scaleFactor+r)}static#F(r){let h=new Path2D;for(let b=0,A=r.length;b<A;b++){let[D,_,I,N]=r[b];b===0&&h.moveTo(...D),h.bezierCurveTo(_[0],_[1],I[0],I[1],N[0],N[1])}return h}static#O(r,h,b){let[A,D,_,I]=h;switch(b){case 0:for(let N=0,H=r.length;N<H;N+=2)r[N]+=A,r[N+1]=I-r[N+1];break;case 90:for(let N=0,H=r.length;N<H;N+=2){let j=r[N];r[N]=r[N+1]+A,r[N+1]=j+D}break;case 180:for(let N=0,H=r.length;N<H;N+=2)r[N]=_-r[N],r[N+1]+=D;break;case 270:for(let N=0,H=r.length;N<H;N+=2){let j=r[N];r[N]=_-r[N+1],r[N+1]=I-j}break;default:throw new Error("Invalid rotation")}return r}static#V(r,h,b){let[A,D,_,I]=h;switch(b){case 0:for(let N=0,H=r.length;N<H;N+=2)r[N]-=A,r[N+1]=I-r[N+1];break;case 90:for(let N=0,H=r.length;N<H;N+=2){let j=r[N];r[N]=r[N+1]-D,r[N+1]=j-A}break;case 180:for(let N=0,H=r.length;N<H;N+=2)r[N]=_-r[N],r[N+1]-=D;break;case 270:for(let N=0,H=r.length;N<H;N+=2){let j=r[N];r[N]=I-r[N+1],r[N+1]=_-j}break;default:throw new Error("Invalid rotation")}return r}#W(r,h,b,A){let D=[],_=this.thickness/2,I=r*h+_,N=r*b+_;for(let H of this.paths){let j=[],K=[];for(let it=0,ot=H.length;it<ot;it++){let[X,z,W,Y]=H[it];if(X[0]===Y[0]&&X[1]===Y[1]&&ot===1){let g=r*X[0]+I,y=r*X[1]+N;j.push(g,y),K.push(g,y);break}let et=r*X[0]+I,rt=r*X[1]+N,ct=r*z[0]+I,st=r*z[1]+N,G=r*W[0]+I,x=r*W[1]+N,T=r*Y[0]+I,R=r*Y[1]+N;it===0&&(j.push(et,rt),K.push(et,rt)),j.push(ct,st,G,x,T,R),K.push(ct,st),it===ot-1&&K.push(T,R)}D.push({bezier:w.#O(j,A,this.rotation),points:w.#O(K,A,this.rotation)})}return D}#j(){let r=1/0,h=-1/0,b=1/0,A=-1/0;for(let D of this.paths)for(let[_,I,N,H]of D){let j=i.Util.bezierBoundingBox(..._,...I,...N,...H);r=Math.min(r,j[0]),b=Math.min(b,j[1]),h=Math.max(h,j[2]),A=Math.max(A,j[3])}return[r,b,h,A]}#$(){return this.#a?Math.ceil(this.thickness*this.parentScale):0}#N(r=!1){if(this.isEmpty())return;if(!this.#a){this.#C();return}let h=this.#j(),b=this.#$();this.#e=Math.max(n.AnnotationEditor.MIN_SIZE,h[2]-h[0]),this.#t=Math.max(n.AnnotationEditor.MIN_SIZE,h[3]-h[1]);let A=Math.ceil(b+this.#e*this.scaleFactor),D=Math.ceil(b+this.#t*this.scaleFactor),[_,I]=this.parentDimensions;this.width=A/_,this.height=D/I,this.setAspectRatio(A,D);let N=this.translationX,H=this.translationY;this.translationX=-h[0],this.translationY=-h[1],this.#P(),this.#C(),this.#c=A,this.#f=D,this.setDims(A,D);let j=r?b/this.scaleFactor/2:0;this.translate(N-this.translationX-j,H-this.translationY-j)}static deserialize(r,h,b){if(r instanceof c.InkAnnotationElement)return null;let A=super.deserialize(r,h,b);A.thickness=r.thickness,A.color=i.Util.makeHexColor(...r.color),A.opacity=r.opacity;let[D,_]=A.pageDimensions,I=A.width*D,N=A.height*_,H=A.parentScale,j=r.thickness/2;A.#a=!0,A.#c=Math.round(I),A.#f=Math.round(N);let{paths:K,rect:it,rotation:ot}=r;for(let{bezier:z}of K){z=w.#V(z,it,ot);let W=[];A.paths.push(W);let Y=H*(z[0]-j),et=H*(z[1]-j);for(let ct=2,st=z.length;ct<st;ct+=6){let G=H*(z[ct]-j),x=H*(z[ct+1]-j),T=H*(z[ct+2]-j),R=H*(z[ct+3]-j),g=H*(z[ct+4]-j),y=H*(z[ct+5]-j);W.push([[Y,et],[G,x],[T,R],[g,y]]),Y=g,et=y}let rt=this.#F(W);A.bezierPath2D.push(rt)}let X=A.#j();return A.#e=Math.max(n.AnnotationEditor.MIN_SIZE,X[2]-X[0]),A.#t=Math.max(n.AnnotationEditor.MIN_SIZE,X[3]-X[1]),A.#L(I,N),A}serialize(){if(this.isEmpty())return null;let r=this.getRect(0,0),h=n.AnnotationEditor._colorManager.convert(this.ctx.strokeStyle);return{annotationType:i.AnnotationEditorType.INK,color:h,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 S extends n.AnnotationEditor{#t=null;#e=null;#i=null;#n=null;#r=null;#s="";#o=null;#l=null;#a=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,h){n.AnnotationEditor.initialize(r,h)}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,h){h.pasteEditor(i.AnnotationEditorType.STAMP,{bitmapFile:r.getAsFile()})}#d(r,h=!1){r?(this.#t=r.bitmap,h||(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.#o&&this.div.focus()}#f(){if(this.#e){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(this.#e).then((h=>this.#d(h,!0))).finally((()=>this.#c()));return}if(this.#n){let h=this.#n;this.#n=null,this._uiManager.enableWaiting(!0),this.#i=this._uiManager.imageManager.getFromUrl(h).then((b=>this.#d(b))).finally((()=>this.#c()));return}if(this.#r){let h=this.#r;this.#r=null,this._uiManager.enableWaiting(!0),this.#i=this._uiManager.imageManager.getFromFile(h).then((b=>this.#d(b))).finally((()=>this.#c()));return}let r=document.createElement("input");r.type="file",r.accept=S.supportedTypesStr,this.#i=new Promise((h=>{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();h()})),r.addEventListener("cancel",(()=>{this.remove(),h()}))})).finally((()=>this.#c())),r.click()}remove(){this.#e&&(this.#t=null,this._uiManager.imageManager.deleteId(this.#e),this.#o?.remove(),this.#o=null,this.#l?.disconnect(),this.#l=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,h;if(this.width&&(r=this.x,h=this.y),super.render(),this.div.hidden=!0,this.addAltTextButton(),this.#t?this.#g():this.#f(),this.width){let[b,A]=this.parentDimensions;this.setAt(r*b,h*A,this.width*b,this.height*A)}return this.div}#g(){let{div:r}=this,{width:h,height:b}=this.#t,[A,D]=this.pageDimensions,_=.75;if(this.width)h=this.width*A,b=this.height*D;else if(h>_*A||b>_*D){let j=Math.min(_*A/h,_*D/b);h*=j,b*=j}let[I,N]=this.parentDimensions;this.setDims(h*I/A,b*N/D),this._uiManager.enableWaiting(!1);let H=this.#o=document.createElement("canvas");r.append(H),r.hidden=!1,this.#m(h,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,h){let[b,A]=this.parentDimensions;this.width=r/b,this.height=h/A,this.setDims(r,h),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,h)}),200)}#y(r,h){let{width:b,height:A}=this.#t,D=b,_=A,I=this.#t;for(;D>2*r||_>2*h;){let N=D,H=_;D>2*r&&(D=D>=16384?Math.floor(D/2)-1:Math.ceil(D/2)),_>2*h&&(_=_>=16384?Math.floor(_/2)-1:Math.ceil(_/2));let j=new OffscreenCanvas(D,_);j.getContext("2d").drawImage(I,0,0,N,H,0,0,D,_),I=j.transferToImageBitmap()}return I}#m(r,h){r=Math.ceil(r),h=Math.ceil(h);let b=this.#o;if(!b||b.width===r&&b.height===h)return;b.width=r,b.height=h;let A=this.#h?this.#t:this.#y(r,h);if(this._uiManager.hasMLManager&&!this.hasAltText()){let _=new OffscreenCanvas(r,h);_.getContext("2d").drawImage(A,0,0,A.width,A.height,0,0,r,h),_.convertToBlob().then((I=>{let N=new FileReader;N.onload=()=>{let H=N.result;this._uiManager.mlGuess({service:"image-to-text",request:{imageData:H}}).then((j=>{let K=j?.output||"";this.parent&&K&&!this.hasAltText()&&(this.altTextData={altText:K,decorative:!1})}))},N.readAsDataURL(I)}))}let D=b.getContext("2d");D.filter=this._uiManager.hcmFilter,D.drawImage(A,0,0,A.width,A.height,0,0,r,h)}getImageForAltText(){return this.#o}#b(r){if(r){if(this.#h){let b=this._uiManager.imageManager.getSvgUrl(this.#e);if(b)return b}let h=document.createElement("canvas");return{width:h.width,height:h.height}=this.#t,h.getContext("2d").drawImage(this.#t,0,0),h.toDataURL()}if(this.#h){let[h,b]=this.pageDimensions,A=Math.round(this.width*h*o.PixelsPerInch.PDF_TO_CSS_UNITS),D=Math.round(this.height*b*o.PixelsPerInch.PDF_TO_CSS_UNITS),_=new OffscreenCanvas(A,D);return _.getContext("2d").drawImage(this.#t,0,0,this.#t.width,this.#t.height,0,0,A,D),_.transferToImageBitmap()}return structuredClone(this.#t)}#S(){this.#l=new ResizeObserver((r=>{let h=r[0].contentRect;h.width&&h.height&&this.#p(h.width,h.height)})),this.#l.observe(this.div)}static deserialize(r,h,b){if(r instanceof c.StampAnnotationElement)return null;let A=super.deserialize(r,h,b),{rect:D,bitmapUrl:_,bitmapId:I,isSvg:N,accessibilityData:H}=r;I&&b.imageManager.isValidId(I)?A.#e=I:A.#n=_,A.#h=N;let[j,K]=A.pageDimensions;return A.width=(D[2]-D[0])/j,A.height=(D[3]-D[1])/K,H&&(A.altTextData=H),A}serialize(r=!1,h=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:A,altText:D}=this.altTextData;if(!A&&D&&(b.accessibilityData={type:"Figure",alt:D}),h===null)return b;h.stamps||=new Map;let _=this.#h?(b.rect[2]-b.rect[0])*(b.rect[3]-b.rect[1]):null;if(h.stamps.has(this.#e)){if(this.#h){let I=h.stamps.get(this.#e);_>I.area&&(I.area=_,I.serialized.bitmap.close(),I.serialized.bitmap=this.#b(!1))}}else h.stamps.set(this.#e,{area:_,serialized:b}),b.bitmap=this.#b(!1);return b}}class f{#t;#e=!1;#i=null;#n=null;#r=null;#s=null;#o=null;#l=new Map;#a=!1;#h=!1;#u=!1;#d=null;#c;static _initialized=!1;static#f=new Map([d,w,S,p].map((r=>[r._editorType,r])));constructor({uiManager:r,pageIndex:h,div:b,accessibilityManager:A,annotationLayer:D,drawLayer:_,textLayer:I,viewport:N,l10n:H}){let j=[...f.#f.values()];if(!f._initialized){f._initialized=!0;for(let K of j)K.initialize(H,r)}r.registerEditorTypes(j),this.#c=r,this.pageIndex=h,this.div=b,this.#t=A,this.#i=D,this.viewport=N,this.#d=I,this.drawLayer=_,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:h}=this.div;for(let b of f.#f.values())h.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 h of this.#l.values())if(h.isEmpty()){h.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 h=this.#i.getEditableAnnotations();for(let b of h){if(b.hide(),this.#c.isDeletedAnnotationElement(b.data.id)||r.has(b.data.id))continue;let A=this.deserialize(b);A&&(this.addOrRebuild(A),A.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 A of b){let{id:D}=A.data;r.has(D)||this.#c.isDeletedAnnotationElement(D)||A.show()}}this.#b(),this.isEmpty&&(this.div.hidden=!0);let{classList:h}=this.div;for(let b of f.#f.values())h.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:h}=i.FeatureTest.platform;if(r.button!==0||r.ctrlKey&&h)return;this.#c.showAllEditors("highlight",!0,!0),this.#d.div.classList.add("free"),p.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:h}=r;h&&this.#c.isDeletedAnnotationElement(h)&&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 h=r.render();this.div.append(h),r.isAttachedToDOM=!0}r.fixAndSetPosition(),r.onceAdded(),this.#c.addToAnnotationStorage(r),r._reportTelemetry(r.telemetryInitialData)}}moveEditorInDOM(r){if(!r.isAttachedToDOM)return;let{activeElement:h}=document;r.div.contains(h)&&!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}),h.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 f.#f.get(this.#c.getMode())}#y(r){let h=this.#p;return h?new h.prototype.constructor(r):null}canCreateNewEmptyEditor(){return this.#p?.canCreateNewEmptyEditor()}pasteEditor(r,h){this.#c.updateToolbar(r),this.#c.updateMode(r);let{offsetX:b,offsetY:A}=this.#m(),D=this.getNextId(),_=this.#y({parent:this,id:D,x:b,y:A,uiManager:this.#c,isCentered:!0,...h});_&&this.add(_)}deserialize(r){return f.#f.get(r.annotationType??r.annotationEditorType)?.deserialize(r,this,this.#c)||null}createAndAddNewEditor(r,h,b={}){let A=this.getNextId(),D=this.#y({parent:this,id:A,x:r.offsetX,y:r.offsetY,uiManager:this.#c,isCentered:h,...b});return D&&this.add(D),D}#m(){let{x:r,y:h,width:b,height:A}=this.div.getBoundingClientRect(),D=Math.max(0,r),_=Math.max(0,h),I=(D+Math.min(window.innerWidth,r+b))/2-r,N=(_+Math.min(window.innerHeight,h+A))/2-h,[H,j]=this.viewport.rotation%180==0?[I,N]:[N,I];return{offsetX:H,offsetY:j}}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:h}=i.FeatureTest.platform;!(r.button!==0||r.ctrlKey&&h)&&r.target===this.div&&this.#a&&(this.#a=!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.#a){this.#a=!1;return}let{isMac:h}=i.FeatureTest.platform;if(r.button!==0||r.ctrlKey&&h||r.target!==this.div)return;this.#a=!0;let b=this.#c.getActive();this.#e=!b||b.isEmpty()}findNewParent(r,h,b){let A=this.#c.findParent(h,b);return A===null||A===this?!1:(A.changeParent(r),!0)}destroy(){this.#c.getActive()?.parent===this&&(this.#c.commitOrRemove(),this.#c.setActiveEditor(null)),this.#o&&(clearTimeout(this.#o),this.#o=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,o.setLayerDimensions)(this.div,r);for(let h of this.#c.getEditors(this.pageIndex))this.add(h),h.rebuild();this.updateMode()}update({viewport:r}){this.#c.commitOrRemove(),this.#b();let h=this.viewport.rotation,b=r.rotation;if(this.viewport=r,(0,o.setLayerDimensions)(this.div,{rotation:b}),h!==b)for(let A of this.#l.values())A.rotate(b);this.addInkEditorIfNeeded(!1)}get pageDimensions(){let{pageWidth:r,pageHeight:h}=this.viewport.rawDims;return[r,h]}get scale(){return this.#c.viewParameters.realScale}}},259:(s,t,e)=>{e.d(t,{ColorPicker:()=>c});var i=e(292),n=e(830),a=e(419);class c{#t=this.#g.bind(this);#e=this.#y.bind(this);#i=null;#n=null;#r;#s=null;#o=!1;#l=!1;#a=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:d=null,uiManager:m=null}){d?(this.#l=!1,this.#d=i.AnnotationEditorParamsType.HIGHLIGHT_COLOR,this.#a=d):(this.#l=!0,this.#d=i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR),this.#u=d?._uiManager||m,this.#h=this.#u._eventBus,this.#r=d?.color||this.#u?.highlightColors.values().next().value||"#FFFF98"}renderButton(){let d=this.#i=document.createElement("button");d.className="colorPicker",d.tabIndex="0",d.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-button"),d.setAttribute("aria-haspopup",!0),d.addEventListener("click",this.#p.bind(this)),d.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,d.append(m),d}renderMainDropdown(){let d=this.#s=this.#c();return d.setAttribute("aria-orientation","horizontal"),d.setAttribute("aria-labelledby","highlightColorPickerLabel"),d}#c(){let d=document.createElement("div");d.addEventListener("contextmenu",a.noContextMenu),d.className="dropdown",d.role="listbox",d.setAttribute("aria-multiselectable",!1),d.setAttribute("aria-orientation","vertical"),d.setAttribute("data-l10n-id","pdfjs-editor-colorpicker-dropdown");for(let[m,u]of this.#u.highlightColors){let o=document.createElement("button");o.tabIndex="0",o.role="option",o.setAttribute("data-color",u),o.title=m,o.setAttribute("data-l10n-id",`pdfjs-editor-colorpicker-${m}`);let p=document.createElement("span");o.append(p),p.className="swatch",p.style.backgroundColor=u,o.setAttribute("aria-selected",u===this.#r),o.addEventListener("click",this.#f.bind(this,u)),d.append(o)}return d.addEventListener("keydown",this.#t),d}#f(d,m){m.stopPropagation(),this.#h.dispatch("switchannotationeditorparams",{source:this,type:this.#d,value:d})}_colorSelectFromKeyboard(d){if(d.target===this.#i){this.#p(d);return}let m=d.target.getAttribute("data-color");m&&this.#f(m,d)}_moveToNext(d){this.#m?d.target!==this.#i?d.target.nextSibling?.focus():this.#s.firstChild?.focus():this.#p(d)}_moveToPrevious(d){d.target!==this.#s?.firstChild&&d.target!==this.#i?(this.#m||this.#p(d),d.target.previousSibling?.focus()):this.#m&&this._hideDropdownFromKeyboard()}_moveToBeginning(d){this.#m?this.#s.firstChild?.focus():this.#p(d)}_moveToEnd(d){this.#m?this.#s.lastChild?.focus():this.#p(d)}#g(d){c._keyboardManager.exec(this,d)}#p(d){if(this.#m){this.hideDropdown();return}if(this.#o=d.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(d){this.#s?.contains(d.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.#o})):this.#a?.unselect())}updateColor(d){if(this.#n&&(this.#n.style.backgroundColor=d),!this.#s)return;let m=this.#u.highlightColors.values();for(let u of this.#s.children)u.setAttribute("aria-selected",m.next().value===d)}destroy(){this.#i?.remove(),this.#i=null,this.#n=null,this.#s?.remove(),this.#s=null}}},310:(s,t,e)=>{e.d(t,{AnnotationEditor:()=>d});var i=e(830),n=e(292),a=e(419);class c{#t="";#e=!1;#i=null;#n=null;#r=null;#s=!1;#o=null;static _l10nPromise=null;constructor(o){this.#o=o}static initialize(o){c._l10nPromise||=o}async render(){let o=this.#i=document.createElement("button");o.className="altText";let p=await c._l10nPromise.get("pdfjs-editor-alt-text-button-label");o.textContent=p,o.setAttribute("aria-label",p),o.tabIndex="0",o.addEventListener("contextmenu",a.noContextMenu),o.addEventListener("pointerdown",(S=>S.stopPropagation()));let w=S=>{S.preventDefault(),this.#o._uiManager.editAltText(this.#o)};return o.addEventListener("click",w,{capture:!0}),o.addEventListener("keydown",(S=>{S.target===o&&S.key==="Enter"&&(this.#s=!0,w(S))})),await this.#l(),o}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:o,decorative:p}){(this.#t!==o||this.#e!==p)&&(this.#t=o,this.#e=p,this.#l())}toggle(o=!1){this.#i&&(!o&&this.#r&&(clearTimeout(this.#r),this.#r=null),this.#i.disabled=!o)}destroy(){this.#i?.remove(),this.#i=null,this.#n=null}async#l(){let o=this.#i;if(!o)return;if(!this.#t&&!this.#e){o.classList.remove("done"),this.#n?.remove();return}o.classList.add("done"),c._l10nPromise.get("pdfjs-editor-alt-text-edit-button-label").then((S=>{o.setAttribute("aria-label",S)}));let p=this.#n;if(!p){this.#n=p=document.createElement("span"),p.className="tooltip",p.setAttribute("role","tooltip");let S=p.id=`alt-text-tooltip-${this.#o.id}`;o.setAttribute("aria-describedby",S);let f=100;o.addEventListener("mouseenter",(()=>{this.#r=setTimeout((()=>{this.#r=null,this.#n.classList.add("show"),this.#o._reportTelemetry({action:"alt_text_tooltip"})}),f)})),o.addEventListener("mouseleave",(()=>{this.#r&&(clearTimeout(this.#r),this.#r=null),this.#n?.classList.remove("show")}))}p.innerText=this.#e?await c._l10nPromise.get("pdfjs-editor-alt-text-decorative-tooltip"):this.#t,p.parentNode||o.append(p),this.#o.getImageForAltText()?.setAttribute("aria-describedby",p.id)}}var l=e(362);class d{#t=null;#e=null;#i=!1;#n=!1;#r=null;#s=null;#o=this.focusin.bind(this);#l=this.focusout.bind(this);#a=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;#_=d._zIndex++;static _borderLineWidth=-1;static _colorManager=new i.ColorManager;static _zIndex=1;static _telemetryTimeout=1e3;static get _resizerKeyboardManager(){let o=d.prototype._resizeWithKeyboard,p=i.AnnotationEditorUIManager.TRANSLATE_SMALL,w=i.AnnotationEditorUIManager.TRANSLATE_BIG;return(0,n.shadow)(this,"_resizerKeyboardManager",new i.KeyboardManager([[["ArrowLeft","mac+ArrowLeft"],o,{args:[-p,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],o,{args:[-w,0]}],[["ArrowRight","mac+ArrowRight"],o,{args:[p,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],o,{args:[w,0]}],[["ArrowUp","mac+ArrowUp"],o,{args:[0,-p]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],o,{args:[0,-w]}],[["ArrowDown","mac+ArrowDown"],o,{args:[0,p]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],o,{args:[0,w]}],[["Escape","mac+Escape"],d.prototype._stopResizingWithKeyboard]]))}constructor(o){this.constructor===d&&(0,n.unreachable)("Cannot initialize AnnotationEditor."),this.parent=o.parent,this.id=o.id,this.width=this.height=null,this.pageIndex=o.parent.pageIndex,this.name=o.name,this.div=null,this._uiManager=o.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=o.isCentered,this._structTreeParentId=null;let{rotation:p,rawDims:{pageWidth:w,pageHeight:S,pageX:f,pageY:v}}=this.parent.viewport;this.rotation=p,this.pageRotation=(360+p-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[w,S],this.pageTranslation=[f,v];let[r,h]=this.parentDimensions;this.x=o.x/r,this.y=o.y/h,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(o){let p=new m({id:o.parent.getNextId(),parent:o.parent,uiManager:o._uiManager});p.annotationElementId=o.annotationElementId,p.deleted=!0,p._uiManager.addToAnnotationStorage(p)}static initialize(o,p,w){if(d._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((f=>[f,o.get(f.replaceAll(/([A-Z])/g,(v=>`-${v.toLowerCase()}`)))]))),w?.strings)for(let f of w.strings)d._l10nPromise.set(f,o.get(f));if(d._borderLineWidth!==-1)return;let S=getComputedStyle(document.documentElement);d._borderLineWidth=parseFloat(S.getPropertyValue("--outline-width"))||0}static updateDefaultParams(o,p){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(o){return!1}static paste(o,p){(0,n.unreachable)("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return this.#S}set _isDraggable(o){this.#S=o,this.div?.classList.toggle("draggable",o)}get isEnterHandled(){return!0}center(){let[o,p]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*p/(2*o),this.y+=this.width*o/(2*p);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*p/(2*o),this.y-=this.width*o/(2*p);break;default:this.x-=this.width/2,this.y-=this.height/2}this.fixAndSetPosition()}addCommands(o){this._uiManager.addCommands(o)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=this.#_}setParent(o){o!==null?(this.pageIndex=o.pageIndex,this.pageDimensions=o.pageDimensions):this.#F(),this.parent=o}focusin(o){this._focusEventsAllowed&&(this.#u?this.#u=!1:this.parent.setSelected(this))}focusout(o){if(!this._focusEventsAllowed||!this.isAttachedToDOM)return;o.relatedTarget?.closest(`#${this.id}`)||(o.preventDefault(),this.parent?.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(o,p,w,S){let[f,v]=this.parentDimensions;[w,S]=this.screenToPageTranslation(w,S),this.x=(o+w)/f,this.y=(p+S)/v,this.fixAndSetPosition()}#M([o,p],w,S){[w,S]=this.screenToPageTranslation(w,S),this.x+=w/o,this.y+=S/p,this.fixAndSetPosition()}translate(o,p){this.#M(this.parentDimensions,o,p)}translateInPage(o,p){this.#d||=[this.x,this.y],this.#M(this.pageDimensions,o,p),this.div.scrollIntoView({block:"nearest"})}drag(o,p){this.#d||=[this.x,this.y];let[w,S]=this.parentDimensions;if(this.x+=o/w,this.y+=p/S,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){let{x:b,y:A}=this.div.getBoundingClientRect();this.parent.findNewParent(this,b,A)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:f,y:v}=this,[r,h]=this.getBaseTranslation();f+=r,v+=h,this.div.style.left=`${(100*f).toFixed(2)}%`,this.div.style.top=`${(100*v).toFixed(2)}%`,this.div.scrollIntoView({block:"nearest"})}get _hasBeenMoved(){return!!this.#d&&(this.#d[0]!==this.x||this.#d[1]!==this.y)}getBaseTranslation(){let[o,p]=this.parentDimensions,{_borderLineWidth:w}=d,S=w/o,f=w/p;switch(this.rotation){case 90:return[-S,f];case 180:return[S,f];case 270:return[S,-f];default:return[-S,-f]}}get _mustFixPosition(){return!0}fixAndSetPosition(o=this.rotation){let[p,w]=this.pageDimensions,{x:S,y:f,width:v,height:r}=this;if(v*=p,r*=w,S*=p,f*=w,this._mustFixPosition)switch(o){case 0:S=Math.max(0,Math.min(p-v,S)),f=Math.max(0,Math.min(w-r,f));break;case 90:S=Math.max(0,Math.min(p-r,S)),f=Math.min(w,Math.max(v,f));break;case 180:S=Math.min(p,Math.max(v,S)),f=Math.min(w,Math.max(r,f));break;case 270:S=Math.min(p,Math.max(r,S)),f=Math.max(0,Math.min(w-v,f))}this.x=S/=p,this.y=f/=w;let[h,b]=this.getBaseTranslation();S+=h,f+=b;let{style:A}=this.div;A.left=`${(100*S).toFixed(2)}%`,A.top=`${(100*f).toFixed(2)}%`,this.moveInDOM()}static#w(o,p,w){switch(w){case 90:return[p,-o];case 180:return[-o,-p];case 270:return[-p,o];default:return[o,p]}}screenToPageTranslation(o,p){return d.#w(o,p,this.parentRotation)}pageTranslationToScreen(o,p){return d.#w(o,p,360-this.parentRotation)}#x(o){switch(o){case 90:{let[p,w]=this.pageDimensions;return[0,-p/w,w/p,0]}case 180:return[-1,0,0,-1];case 270:{let[p,w]=this.pageDimensions;return[0,p/w,-w/p,0]}default:return[1,0,0,1]}}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){let{parentScale:o,pageDimensions:[p,w]}=this,S=p*o,f=w*o;return n.FeatureTest.isCSSRoundSupported?[Math.round(S),Math.round(f)]:[S,f]}setDims(o,p){let[w,S]=this.parentDimensions;this.div.style.width=`${(100*o/w).toFixed(2)}%`,this.#n||(this.div.style.height=`${(100*p/S).toFixed(2)}%`)}fixDims(){let{style:o}=this.div,{height:p,width:w}=o,S=w.endsWith("%"),f=!this.#n&&p.endsWith("%");if(S&&f)return;let[v,r]=this.parentDimensions;S||(o.width=`${(100*parseFloat(w)/v).toFixed(2)}%`),this.#n||f||(o.height=`${(100*parseFloat(p)/r).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}#v(){if(this.#r)return;this.#r=document.createElement("div"),this.#r.classList.add("resizers");let o=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"];for(let p of o){let w=document.createElement("div");this.#r.append(w),w.classList.add("resizer",p),w.setAttribute("data-resizer-name",p),w.addEventListener("pointerdown",this.#E.bind(this,p)),w.addEventListener("contextmenu",a.noContextMenu),w.tabIndex=-1}this.div.prepend(this.#r)}#E(o,p){p.preventDefault();let{isMac:w}=n.FeatureTest.platform;if(p.button!==0||p.ctrlKey&&w)return;this.#e?.toggle(!1);let S=this.#C.bind(this,o),f=this._isDraggable;this._isDraggable=!1;let v={passive:!0,capture:!0};this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",S,v);let r=this.x,h=this.y,b=this.width,A=this.height,D=this.parent.div.style.cursor,_=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(p.target).cursor;let I=()=>{this.parent.togglePointerEvents(!0),this.#e?.toggle(!0),this._isDraggable=f,window.removeEventListener("pointerup",I),window.removeEventListener("blur",I),window.removeEventListener("pointermove",S,v),this.parent.div.style.cursor=D,this.div.style.cursor=_,this.#A(r,h,b,A)};window.addEventListener("pointerup",I),window.addEventListener("blur",I)}#A(o,p,w,S){let f=this.x,v=this.y,r=this.width,h=this.height;f===o&&v===p&&r===w&&h===S||this.addCommands({cmd:()=>{this.width=r,this.height=h,this.x=f,this.y=v;let[b,A]=this.parentDimensions;this.setDims(b*r,A*h),this.fixAndSetPosition()},undo:()=>{this.width=w,this.height=S,this.x=o,this.y=p;let[b,A]=this.parentDimensions;this.setDims(b*w,A*S),this.fixAndSetPosition()},mustExec:!0})}#C(o,p){let[w,S]=this.parentDimensions,f=this.x,v=this.y,r=this.width,h=this.height,b=d.MIN_SIZE/w,A=d.MIN_SIZE/S,D=C=>Math.round(1e4*C)/1e4,_=this.#x(this.rotation),I=(C,k)=>[_[0]*C+_[2]*k,_[1]*C+_[3]*k],N=this.#x(360-this.rotation),H,j,K=!1,it=!1;switch(o){case"topLeft":K=!0,H=(C,k)=>[0,0],j=(C,k)=>[C,k];break;case"topMiddle":H=(C,k)=>[C/2,0],j=(C,k)=>[C/2,k];break;case"topRight":K=!0,H=(C,k)=>[C,0],j=(C,k)=>[0,k];break;case"middleRight":it=!0,H=(C,k)=>[C,k/2],j=(C,k)=>[0,k/2];break;case"bottomRight":K=!0,H=(C,k)=>[C,k],j=(C,k)=>[0,0];break;case"bottomMiddle":H=(C,k)=>[C/2,k],j=(C,k)=>[C/2,0];break;case"bottomLeft":K=!0,H=(C,k)=>[0,k],j=(C,k)=>[C,0];break;case"middleLeft":it=!0,H=(C,k)=>[0,k/2],j=(C,k)=>[C,k/2]}let ot=H(r,h),X=j(r,h),z=I(...X),W=D(f+z[0]),Y=D(v+z[1]),et=1,rt=1,[ct,st]=this.screenToPageTranslation(p.movementX,p.movementY);[ct,st]=(G=ct/w,x=st/S,[N[0]*G+N[2]*x,N[1]*G+N[3]*x]);var G,x;if(K){let C=Math.hypot(r,h);et=rt=Math.max(Math.min(Math.hypot(X[0]-ot[0]-ct,X[1]-ot[1]-st)/C,1/r,1/h),b/r,A/h)}else it?et=Math.max(b,Math.min(1,Math.abs(X[0]-ot[0]-ct)))/r:rt=Math.max(A,Math.min(1,Math.abs(X[1]-ot[1]-st)))/h;let T=D(r*et),R=D(h*rt);z=I(...j(T,R));let g=W-z[0],y=Y-z[1];this.width=T,this.height=R,this.x=g,this.y=y,this.setDims(w*T,S*R),this.fixAndSetPosition()}altTextFinish(){this.#e?.finish()}async addEditToolbar(){return this.#a||this.#f?this.#a:(this.#a=new l.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||(c.initialize(d._l10nPromise),this.#e=new c(this),await this.addEditToolbar())}get altTextData(){return this.#e?.data}set altTextData(o){this.#e&&(this.#e.data=o)}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.#l);let[o,p]=this.parentDimensions;this.parentRotation%180!=0&&(this.div.style.maxWidth=`${(100*p/o).toFixed(2)}%`,this.div.style.maxHeight=`${(100*o/p).toFixed(2)}%`);let[w,S]=this.getInitialTranslation();return this.translate(w,S),(0,i.bindEvents)(this,this.div,["pointerdown"]),this.div}pointerdown(o){let{isMac:p}=n.FeatureTest.platform;o.button!==0||o.ctrlKey&&p?o.preventDefault():(this.#u=!0,this._isDraggable?this.#k(o):this.#T(o))}#T(o){let{isMac:p}=n.FeatureTest.platform;o.ctrlKey&&!p||o.shiftKey||o.metaKey&&p?this.parent.toggleSelected(this):this.parent.setSelected(this)}#k(o){let p=this._uiManager.isSelected(this);this._uiManager.setUpDragSession();let w,S;p&&(this.div.classList.add("moving"),w={passive:!0,capture:!0},this.#y=o.clientX,this.#m=o.clientY,S=v=>{let{clientX:r,clientY:h}=v,[b,A]=this.screenToPageTranslation(r-this.#y,h-this.#m);this.#y=r,this.#m=h,this._uiManager.dragSelectedEditors(b,A)},window.addEventListener("pointermove",S,w));let f=()=>{window.removeEventListener("pointerup",f),window.removeEventListener("blur",f),p&&(this.div.classList.remove("moving"),window.removeEventListener("pointermove",S,w)),this.#u=!1,this._uiManager.endDragSession()||this.#T(o)};window.addEventListener("pointerup",f),window.addEventListener("blur",f)}moveInDOM(){this.#p&&clearTimeout(this.#p),this.#p=setTimeout((()=>{this.#p=null,this.parent?.moveEditorInDOM(this)}),0)}_setParentAndPosition(o,p,w){o.changeParent(this),this.x=p,this.y=w,this.fixAndSetPosition()}getRect(o,p,w=this.rotation){let S=this.parentScale,[f,v]=this.pageDimensions,[r,h]=this.pageTranslation,b=o/S,A=p/S,D=this.x*f,_=this.y*v,I=this.width*f,N=this.height*v;switch(w){case 0:return[D+b+r,v-_-A-N+h,D+b+I+r,v-_-A+h];case 90:return[D+A+r,v-_+b+h,D+A+N+r,v-_+b+I+h];case 180:return[D-b-I+r,v-_+A+h,D-b+r,v-_+A+N+h];case 270:return[D-A-N+r,v-_-b-I+h,D-A+r,v-_-b+h];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(o,p){let[w,S,f,v]=o,r=f-w,h=v-S;switch(this.rotation){case 0:return[w,p-v,r,h];case 90:return[w,p-S,h,r];case 180:return[f,p-S,r,h];case 270:return[f,p-v,h,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.#l)}rotate(o){}serialize(o=!1,p=null){(0,n.unreachable)("An editor must be serializable")}static deserialize(o,p,w){let S=new this.prototype.constructor({parent:p,id:p.getNextId(),uiManager:w});S.rotation=o.rotation;let[f,v]=S.pageDimensions,[r,h,b,A]=S.getRectInCurrentCoords(o.rect,v);return S.x=r/f,S.y=h/v,S.width=b/f,S.height=A/v,S}remove(){if(this.div.removeEventListener("focusin",this.#o),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 o of this.#b.values())clearTimeout(o);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(o){if(!this.isResizable||o.target!==this.div||o.key!=="Enter")return;this._uiManager.setSelected(this),this.#s={savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height};let p=this.#r.children;if(!this.#t){this.#t=Array.from(p);let v=this.#R.bind(this),r=this.#P.bind(this);for(let h of this.#t){let b=h.getAttribute("data-resizer-name");h.setAttribute("role","spinbutton"),h.addEventListener("keydown",v),h.addEventListener("blur",r),h.addEventListener("focus",this.#L.bind(this,b)),d._l10nPromise.get(`pdfjs-editor-resizer-label-${b}`).then((A=>h.setAttribute("aria-label",A)))}}let w=this.#t[0],S=0;for(let v of p){if(v===w)break;S++}let f=(360-this.rotation+this.parentRotation)%360/90*(this.#t.length/4);if(f!==S){if(f<S)for(let r=0;r<S-f;r++)this.#r.append(this.#r.firstChild);else if(f>S)for(let r=0;r<f-S;r++)this.#r.firstChild.before(this.#r.lastChild);let v=0;for(let r of p){let h=this.#t[v++].getAttribute("data-resizer-name");d._l10nPromise.get(`pdfjs-editor-resizer-label-${h}`).then((b=>r.setAttribute("aria-label",b)))}}this.#I(0),this.#g=!0,this.#r.firstChild.focus({focusVisible:!0}),o.preventDefault(),o.stopImmediatePropagation()}#R(o){d._resizerKeyboardManager.exec(this,o)}#P(o){this.#g&&o.relatedTarget?.parentNode!==this.#r&&this.#F()}#L(o){this.#h=this.#g?o:""}#I(o){if(this.#t)for(let p of this.#t)p.tabIndex=o}_resizeWithKeyboard(o,p){this.#g&&this.#C(this.#h,{movementX:o,movementY:p})}#F(){if(this.#g=!1,this.#I(-1),this.#s){let{savedX:o,savedY:p,savedWidth:w,savedHeight:S}=this.#s;this.#A(o,p,w,S),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(o,p){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return this.#c}set isEditing(o){this.#c=o,this.parent&&(o?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(o,p){this.#n=!0;let w=o/p,{style:S}=this.div;S.aspectRatio=w,S.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(o,p=!1){if(p){this.#b||=new Map;let{action:w}=o,S=this.#b.get(w);S&&clearTimeout(S),S=setTimeout((()=>{this._reportTelemetry(o),this.#b.delete(w),this.#b.size===0&&(this.#b=null)}),d._telemetryTimeout),this.#b.set(w,S)}else o.type||=this.editorType,this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:o}})}show(o=this._isVisible){this.div.classList.toggle("hidden",!o),this._isVisible=o}enable(){this.div&&(this.div.tabIndex=0),this.#i=!1}disable(){this.div&&(this.div.tabIndex=-1),this.#i=!0}}class m extends d{constructor(o){super(o),this.annotationElementId=o.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,o=0,p=0,w=!0){let S=1/0,f=-1/0,v=1/0,r=-1/0,h=10**-4;for(let{x:H,y:j,width:K,height:it}of u){let ot=Math.floor((H-o)/h)*h,X=Math.ceil((H+K+o)/h)*h,z=Math.floor((j-o)/h)*h,W=Math.ceil((j+it+o)/h)*h,Y=[ot,z,W,!0],et=[X,z,W,!1];this.#e.push(Y,et),S=Math.min(S,ot),f=Math.max(f,X),v=Math.min(v,z),r=Math.max(r,W)}let b=f-S+2*p,A=r-v+2*p,D=S-p,_=v-p,I=this.#e.at(w?-1:-2),N=[I[0],I[2]];for(let H of this.#e){let[j,K,it]=H;H[0]=(j-D)/b,H[1]=(K-_)/A,H[2]=(it-_)/A}this.#t={x:D,y:_,width:b,height:A,lastPoint:N}}getOutlines(){this.#e.sort(((o,p)=>o[0]-p[0]||o[1]-p[1]||o[2]-p[2]));let u=[];for(let o of this.#e)o[3]?(u.push(...this.#l(o)),this.#s(o)):(this.#o(o),u.push(...this.#l(o)));return this.#n(u)}#n(u){let o=[],p=new Set;for(let f of u){let[v,r,h]=f;o.push([v,r,f],[v,h,f])}o.sort(((f,v)=>f[1]-v[1]||f[0]-v[0]));for(let f=0,v=o.length;f<v;f+=2){let r=o[f][2],h=o[f+1][2];r.push(h),h.push(r),p.add(r),p.add(h)}let w=[],S;for(;p.size>0;){let f=p.values().next().value,[v,r,h,b,A]=f;p.delete(f);let D=v,_=r;for(S=[v,h],w.push(S);;){let I;if(p.has(b))I=b;else{if(!p.has(A))break;I=A}p.delete(I),[v,r,h,b,A]=I,D!==v&&(S.push(D,_,v,_===r?r:h),D=v),_=_===r?h:r}S.push(D,_)}return new c(w,this.#t)}#r(u){let o=this.#i,p=0,w=o.length-1;for(;p<=w;){let S=p+w>>1,f=o[S][0];if(f===u)return S;f<u?p=S+1:w=S-1}return w+1}#s([,u,o]){let p=this.#r(u);this.#i.splice(p,0,[u,o])}#o([,u,o]){let p=this.#r(u);for(let w=p;w<this.#i.length;w++){let[S,f]=this.#i[w];if(S!==u)break;if(S===u&&f===o){this.#i.splice(w,1);return}}for(let w=p-1;w>=0;w--){let[S,f]=this.#i[w];if(S!==u)break;if(S===u&&f===o){this.#i.splice(w,1);return}}}#l(u){let[o,p,w]=u,S=[[o,p,w]],f=this.#r(w);for(let v=0;v<f;v++){let[r,h]=this.#i[v];for(let b=0,A=S.length;b<A;b++){let[,D,_]=S[b];if(!(h<=D||_<=r))if(D>=r)if(_>h)S[b][1]=h;else{if(A===1)return[];S.splice(b,1),b--,A--}else S[b][2]=r,_>h&&S.push([o,h,_])}}return S}}class a{toSVGPath(){throw new Error("Abstract method `toSVGPath` must be implemented.")}get box(){throw new Error("Abstract getter `box` must be implemented.")}serialize(u,o){throw new Error("Abstract method `serialize` must be implemented.")}get free(){return this instanceof d}}class c extends a{#t;#e;constructor(u,o){super(),this.#e=u,this.#t=o}toSVGPath(){let u=[];for(let o of this.#e){let[p,w]=o;u.push(`M${p} ${w}`);for(let S=2;S<o.length;S+=2){let f=o[S],v=o[S+1];f===p?(u.push(`V${v}`),w=v):v===w&&(u.push(`H${f}`),p=f)}u.push("Z")}return u.join(" ")}serialize([u,o,p,w],S){let f=[],v=p-u,r=w-o;for(let h of this.#e){let b=new Array(h.length);for(let A=0;A<h.length;A+=2)b[A]=u+h[A]*v,b[A+1]=w-h[A+1]*r;f.push(b)}return f}get box(){return this.#t}}class l{#t;#e=[];#i;#n;#r=[];#s=new Float64Array(18);#o;#l;#a;#h;#u;#d;#c=[];static#f=8;static#g=2;static#p=l.#f+l.#g;constructor({x:u,y:o},p,w,S,f,v=0){this.#t=p,this.#d=S*w,this.#n=f,this.#s.set([NaN,NaN,NaN,NaN,u,o],6),this.#i=v,this.#h=l.#f*w,this.#a=l.#p*w,this.#u=w,this.#c.push(u,o)}get free(){return!0}isEmpty(){return isNaN(this.#s[8])}#y(){let u=this.#s.subarray(4,6),o=this.#s.subarray(16,18),[p,w,S,f]=this.#t;return[(this.#o+(u[0]-o[0])/2-p)/S,(this.#l+(u[1]-o[1])/2-w)/f,(this.#o+(o[0]-u[0])/2-p)/S,(this.#l+(o[1]-u[1])/2-w)/f]}add({x:u,y:o}){this.#o=u,this.#l=o;let[p,w,S,f]=this.#t,[v,r,h,b]=this.#s.subarray(8,12),A=u-h,D=o-b,_=Math.hypot(A,D);if(_<this.#a)return!1;let I=_-this.#h,N=I/_,H=N*A,j=N*D,K=v,it=r;v=h,r=b,h+=H,b+=j,this.#c?.push(u,o);let ot=H/I,X=-j/I*this.#d,z=ot*this.#d;return this.#s.set(this.#s.subarray(2,8),0),this.#s.set([h+X,b+z],4),this.#s.set(this.#s.subarray(14,18),12),this.#s.set([h-X,b-z],16),isNaN(this.#s[6])?(this.#r.length===0&&(this.#s.set([v+X,r+z],2),this.#r.push(NaN,NaN,NaN,NaN,(v+X-p)/S,(r+z-w)/f),this.#s.set([v-X,r-z],14),this.#e.push(NaN,NaN,NaN,NaN,(v-X-p)/S,(r-z-w)/f)),this.#s.set([K,it,v,r,h,b],6),!this.isEmpty()):(this.#s.set([K,it,v,r,h,b],6),Math.abs(Math.atan2(it-r,K-v)-Math.atan2(j,H))<Math.PI/2?([v,r,h,b]=this.#s.subarray(2,6),this.#r.push(NaN,NaN,NaN,NaN,((v+h)/2-p)/S,((r+b)/2-w)/f),[v,r,K,it]=this.#s.subarray(14,18),this.#e.push(NaN,NaN,NaN,NaN,((K+v)/2-p)/S,((it+r)/2-w)/f),!0):([K,it,v,r,h,b]=this.#s.subarray(0,6),this.#r.push(((K+5*v)/6-p)/S,((it+5*r)/6-w)/f,((5*v+h)/6-p)/S,((5*r+b)/6-w)/f,((v+h)/2-p)/S,((r+b)/2-w)/f),[h,b,v,r,K,it]=this.#s.subarray(12,18),this.#e.push(((K+5*v)/6-p)/S,((it+5*r)/6-w)/f,((5*v+h)/6-p)/S,((5*r+b)/6-w)/f,((v+h)/2-p)/S,((r+b)/2-w)/f),!0))}toSVGPath(){if(this.isEmpty())return"";let u=this.#r,o=this.#e,p=this.#s.subarray(4,6),w=this.#s.subarray(16,18),[S,f,v,r]=this.#t,[h,b,A,D]=this.#y();if(isNaN(this.#s[6])&&!this.isEmpty())return`M${(this.#s[2]-S)/v} ${(this.#s[3]-f)/r} L${(this.#s[4]-S)/v} ${(this.#s[5]-f)/r} L${h} ${b} L${A} ${D} L${(this.#s[16]-S)/v} ${(this.#s[17]-f)/r} L${(this.#s[14]-S)/v} ${(this.#s[15]-f)/r} Z`;let _=[];_.push(`M${u[4]} ${u[5]}`);for(let I=6;I<u.length;I+=6)isNaN(u[I])?_.push(`L${u[I+4]} ${u[I+5]}`):_.push(`C${u[I]} ${u[I+1]} ${u[I+2]} ${u[I+3]} ${u[I+4]} ${u[I+5]}`);_.push(`L${(p[0]-S)/v} ${(p[1]-f)/r} L${h} ${b} L${A} ${D} L${(w[0]-S)/v} ${(w[1]-f)/r}`);for(let I=o.length-6;I>=6;I-=6)isNaN(o[I])?_.push(`L${o[I+4]} ${o[I+5]}`):_.push(`C${o[I]} ${o[I+1]} ${o[I+2]} ${o[I+3]} ${o[I+4]} ${o[I+5]}`);return _.push(`L${o[4]} ${o[5]} Z`),_.join(" ")}getOutlines(){let u=this.#r,o=this.#e,p=this.#s,w=p.subarray(4,6),S=p.subarray(16,18),[f,v,r,h]=this.#t,b=new Float64Array((this.#c?.length??0)+2);for(let j=0,K=b.length-2;j<K;j+=2)b[j]=(this.#c[j]-f)/r,b[j+1]=(this.#c[j+1]-v)/h;b[b.length-2]=(this.#o-f)/r,b[b.length-1]=(this.#l-v)/h;let[A,D,_,I]=this.#y();if(isNaN(p[6])&&!this.isEmpty()){let j=new Float64Array(36);return j.set([NaN,NaN,NaN,NaN,(p[2]-f)/r,(p[3]-v)/h,NaN,NaN,NaN,NaN,(p[4]-f)/r,(p[5]-v)/h,NaN,NaN,NaN,NaN,A,D,NaN,NaN,NaN,NaN,_,I,NaN,NaN,NaN,NaN,(p[16]-f)/r,(p[17]-v)/h,NaN,NaN,NaN,NaN,(p[14]-f)/r,(p[15]-v)/h],0),new d(j,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 j=0;j<H;j+=2)isNaN(u[j])?N[j]=N[j+1]=NaN:(N[j]=u[j],N[j+1]=u[j+1]);N.set([NaN,NaN,NaN,NaN,(w[0]-f)/r,(w[1]-v)/h,NaN,NaN,NaN,NaN,A,D,NaN,NaN,NaN,NaN,_,I,NaN,NaN,NaN,NaN,(S[0]-f)/r,(S[1]-v)/h],H),H+=24;for(let j=o.length-6;j>=6;j-=6)for(let K=0;K<6;K+=2)isNaN(o[j+K])?(N[H]=N[H+1]=NaN,H+=2):(N[H]=o[j+K],N[H+1]=o[j+K+1],H+=2);return N.set([NaN,NaN,NaN,NaN,o[4],o[5]],H),new d(N,b,this.#t,this.#u,this.#i,this.#n)}}class d extends a{#t;#e=null;#i;#n;#r;#s;#o;constructor(u,o,p,w,S,f){super(),this.#o=u,this.#r=o,this.#t=p,this.#s=w,this.#i=S,this.#n=f,this.#h(f);let{x:v,y:r,width:h,height:b}=this.#e;for(let A=0,D=u.length;A<D;A+=2)u[A]=(u[A]-v)/h,u[A+1]=(u[A+1]-r)/b;for(let A=0,D=o.length;A<D;A+=2)o[A]=(o[A]-v)/h,o[A+1]=(o[A+1]-r)/b}toSVGPath(){let u=[`M${this.#o[4]} ${this.#o[5]}`];for(let o=6,p=this.#o.length;o<p;o+=6)isNaN(this.#o[o])?u.push(`L${this.#o[o+4]} ${this.#o[o+5]}`):u.push(`C${this.#o[o]} ${this.#o[o+1]} ${this.#o[o+2]} ${this.#o[o+3]} ${this.#o[o+4]} ${this.#o[o+5]}`);return u.push("Z"),u.join(" ")}serialize([u,o,p,w],S){let f=p-u,v=w-o,r,h;switch(S){case 0:r=this.#l(this.#o,u,w,f,-v),h=this.#l(this.#r,u,w,f,-v);break;case 90:r=this.#a(this.#o,u,o,f,v),h=this.#a(this.#r,u,o,f,v);break;case 180:r=this.#l(this.#o,p,o,-f,v),h=this.#l(this.#r,p,o,-f,v);break;case 270:r=this.#a(this.#o,p,w,-f,-v),h=this.#a(this.#r,p,w,-f,-v)}return{outline:Array.from(r),points:[Array.from(h)]}}#l(u,o,p,w,S){let f=new Float64Array(u.length);for(let v=0,r=u.length;v<r;v+=2)f[v]=o+u[v]*w,f[v+1]=p+u[v+1]*S;return f}#a(u,o,p,w,S){let f=new Float64Array(u.length);for(let v=0,r=u.length;v<r;v+=2)f[v]=o+u[v+1]*w,f[v+1]=p+u[v]*S;return f}#h(u){let o=this.#o,p=o[4],w=o[5],S=p,f=w,v=p,r=w,h=p,b=w,A=u?Math.max:Math.min;for(let H=6,j=o.length;H<j;H+=6){if(isNaN(o[H]))S=Math.min(S,o[H+4]),f=Math.min(f,o[H+5]),v=Math.max(v,o[H+4]),r=Math.max(r,o[H+5]),b<o[H+5]?(h=o[H+4],b=o[H+5]):b===o[H+5]&&(h=A(h,o[H+4]));else{let K=i.Util.bezierBoundingBox(p,w,...o.slice(H,H+6));S=Math.min(S,K[0]),f=Math.min(f,K[1]),v=Math.max(v,K[2]),r=Math.max(r,K[3]),b<K[3]?(h=K[2],b=K[3]):b===K[3]&&(h=A(h,K[2]))}p=o[H+4],w=o[H+5]}let D=S-this.#i,_=f-this.#i,I=v-S+2*this.#i,N=r-f+2*this.#i;this.#e={x:D,y:_,width:I,height:N,lastPoint:[h,b]}}get box(){return this.#e}getNewOutline(u,o){let{x:p,y:w,width:S,height:f}=this.#e,[v,r,h,b]=this.#t,A=S*h,D=f*b,_=p*h+v,I=w*b+r,N=new l({x:this.#r[0]*A+_,y:this.#r[1]*D+I},this.#t,this.#s,u,this.#n,o??this.#i);for(let H=2;H<this.#r.length;H+=2)N.add({x:this.#r[H]*A+_,y:this.#r[H+1]*D+I});return N.getOutlines()}}},362:(s,t,e)=>{e.d(t,{EditorToolbar:()=>n,HighlightToolbar:()=>a});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 d=this.#n=document.createElement("div");d.className="buttons",l.append(d);let m=this.#i.toolbarPosition;if(m){let{style:u}=l,o=this.#i._uiManager.direction==="ltr"?1-m[0]:m[0];u.insetInlineEnd=100*o+"%",u.top=`calc(${100*m[1]}% + var(--editor-toolbar-vert-offset))`}return this.#a(),l}static#r(l){l.stopPropagation()}#s(l){this.#i._focusEventsAllowed=!1,l.preventDefault(),l.stopPropagation()}#o(l){this.#i._focusEventsAllowed=!0,l.preventDefault(),l.stopPropagation()}#l(l){l.addEventListener("focusin",this.#s.bind(this),{capture:!0}),l.addEventListener("focusout",this.#o.bind(this),{capture:!0}),l.addEventListener("contextmenu",i.noContextMenu)}hide(){this.#t.classList.add("hidden"),this.#e?.hideDropdown()}show(){this.#t.classList.remove("hidden")}#a(){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",(d=>{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 d=l.renderButton();this.#l(d),this.#n.prepend(d,this.#h)}remove(){this.#t.remove(),this.#e?.destroy(),this.#e=null}}class a{#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 d=this.#t=document.createElement("div");return d.className="buttons",l.append(d),this.#s(),l}#r(l,d){let m=0,u=0;for(let o of l){let p=o.y+o.height;if(p<m)continue;let w=o.x+(d?o.width:0);p>m?(u=w,m=p):d?w>u&&(u=w):w<u&&(u=w)}return[d?1-u:u,m]}show(l,d,m){let[u,o]=this.#r(d,m),{style:p}=this.#e||=this.#n();l.append(this.#e),p.insetInlineEnd=100*u+"%",p.top=`calc(${100*o}% + 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 d=document.createElement("span");l.append(d),d.className="visuallyHidden",d.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:()=>p,KeyboardManager:()=>o,bindEvents:()=>c,opacityToHex:()=>l});var i=e(292),n=e(419),a=e(362);function c(S,f,v){for(let r of v)f.addEventListener(r,S[r].bind(S))}function l(S){return Math.round(Math.min(255,Math.max(1,255*S))).toString(16).padStart(2,"0")}class d{#t=0;constructor(){}get id(){return`${i.AnnotationEditorPrefix}${this.#t++}`}}class m{#t=(0,i.getUuid)();#e=0;#i=null;static get _isSVGFittingCanvas(){let f=new OffscreenCanvas(1,3).getContext("2d"),v=new Image;v.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=v.decode().then((()=>(f.drawImage(v,0,0,1,1,0,0,1,3),new Uint32Array(f.getImageData(0,0,1,1).data.buffer)[0]===0)));return(0,i.shadow)(this,"_isSVGFittingCanvas",r)}async#n(f,v){this.#i||=new Map;let r=this.#i.get(f);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 h;if(typeof v=="string"?(r.url=v,h=await(0,n.fetchData)(v,"blob")):h=r.file=v,h.type==="image/svg+xml"){let b=m._isSVGFittingCanvas,A=new FileReader,D=new Image,_=new Promise(((I,N)=>{D.onload=()=>{r.bitmap=D,r.isSvg=!0,I()},A.onload=async()=>{let H=r.svgUrl=A.result;D.src=await b?`${H}#svgView(preserveAspectRatio(none))`:H},D.onerror=A.onerror=N}));A.readAsDataURL(h),await _}else r.bitmap=await createImageBitmap(h);r.refCounter=1}catch(h){console.error(h),r=null}return this.#i.set(f,r),r&&this.#i.set(r.id,r),r}async getFromFile(f){let{lastModified:v,name:r,size:h,type:b}=f;return this.#n(`${v}_${r}_${h}_${b}`,f)}async getFromUrl(f){return this.#n(f,f)}async getFromId(f){this.#i||=new Map;let v=this.#i.get(f);return v?v.bitmap?(v.refCounter+=1,v):v.file?this.getFromFile(v.file):this.getFromUrl(v.url):null}getSvgUrl(f){let v=this.#i.get(f);return v?.isSvg?v.svgUrl:null}deleteId(f){this.#i||=new Map;let v=this.#i.get(f);v&&(v.refCounter-=1,v.refCounter===0&&(v.bitmap=null))}isValidId(f){return f.startsWith(`image_${this.#t}_`)}}class u{#t=[];#e=!1;#i;#n=-1;constructor(f=128){this.#i=f}add({cmd:f,undo:v,post:r,mustExec:h,type:b=NaN,overwriteIfSameType:A=!1,keepUndo:D=!1}){if(h&&f(),this.#e)return;let _={cmd:f,undo:v,post:r,type:b};if(this.#n===-1){this.#t.length>0&&(this.#t.length=0),this.#n=0,this.#t.push(_);return}if(A&&this.#t[this.#n].type===b){D&&(_.undo=this.#t[this.#n].undo),this.#t[this.#n]=_;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(_)}undo(){if(this.#n===-1)return;this.#e=!0;let{undo:f,post:v}=this.#t[this.#n];f(),v?.(),this.#e=!1,this.#n-=1}redo(){if(this.#n<this.#t.length-1){this.#n+=1,this.#e=!0;let{cmd:f,post:v}=this.#t[this.#n];f(),v?.(),this.#e=!1}}hasSomethingToUndo(){return this.#n!==-1}hasSomethingToRedo(){return this.#n<this.#t.length-1}destroy(){this.#t=null}}class o{constructor(f){this.buffer=[],this.callbacks=new Map,this.allKeys=new Set;let{isMac:v}=i.FeatureTest.platform;for(let[r,h,b={}]of f)for(let A of r){let D=A.startsWith("mac+");v&&D?(this.callbacks.set(A.slice(4),{callback:h,options:b}),this.allKeys.add(A.split("+").at(-1))):!v&&!D&&(this.callbacks.set(A,{callback:h,options:b}),this.allKeys.add(A.split("+").at(-1)))}}#t(f){f.altKey&&this.buffer.push("alt"),f.ctrlKey&&this.buffer.push("ctrl"),f.metaKey&&this.buffer.push("meta"),f.shiftKey&&this.buffer.push("shift"),this.buffer.push(f.key);let v=this.buffer.join("+");return this.buffer.length=0,v}exec(f,v){if(!this.allKeys.has(v.key))return;let r=this.callbacks.get(this.#t(v));if(!r)return;let{callback:h,options:{bubbles:b=!1,args:A=[],checker:D=null}}=r;(!D||D(f,v))&&(h.bind(f,...A,v)(),b||(v.stopPropagation(),v.preventDefault()))}}class p{static _colorsMapping=new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]);get _colors(){let f=new Map([["CanvasText",null],["Canvas",null]]);return(0,n.getColorValues)(f),(0,i.shadow)(this,"_colors",f)}convert(f){let v=(0,n.getRGB)(f);if(!window.matchMedia("(forced-colors: active)").matches)return v;for(let[r,h]of this._colors)if(h.every(((b,A)=>b===v[A])))return p._colorsMapping.get(r);return v}getHexCode(f){let v=this._colors.get(f);return v?i.Util.makeHexColor(...v):f}}class w{#t=null;#e=new Map;#i=new Map;#n=null;#r=null;#s=new u;#o=0;#l=new Set;#a=null;#h=null;#u=new Set;#d=!1;#c=null;#f=null;#g=null;#p=!1;#y=null;#m=new d;#b=!1;#S=!1;#_=null;#M=null;#w=null;#x=i.AnnotationEditorType.NONE;#v=new Set;#E=null;#A=null;#C=null;#T=this.blur.bind(this);#k=this.focus.bind(this);#R=this.copy.bind(this);#P=this.cut.bind(this);#L=this.paste.bind(this);#I=this.keydown.bind(this);#F=this.keyup.bind(this);#O=this.onEditingAction.bind(this);#V=this.onPageChanging.bind(this);#W=this.onScaleChanging.bind(this);#j=this.#nt.bind(this);#$=this.onRotationChanging.bind(this);#N={isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1};#z=[0,0];#B=null;#H=null;#K=null;static TRANSLATE_SMALL=1;static TRANSLATE_BIG=10;static get _keyboardManager(){let f=w.prototype,v=A=>A.#H.contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&A.hasSomethingToControl(),r=(A,{target:D})=>{if(D instanceof HTMLInputElement){let{type:_}=D;return _!=="text"&&_!=="number"}return!0},h=this.TRANSLATE_SMALL,b=this.TRANSLATE_BIG;return(0,i.shadow)(this,"_keyboardManager",new o([[["ctrl+a","mac+meta+a"],f.selectAll,{checker:r}],[["ctrl+z","mac+meta+z"],f.undo,{checker:r}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],f.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"],f.delete,{checker:r}],[["Enter","mac+Enter"],f.addNewEditorFromKeyboard,{checker:(A,{target:D})=>!(D instanceof HTMLButtonElement)&&A.#H.contains(D)&&!A.isEnterHandled}],[[" ","mac+ "],f.addNewEditorFromKeyboard,{checker:(A,{target:D})=>!(D instanceof HTMLButtonElement)&&A.#H.contains(document.activeElement)}],[["Escape","mac+Escape"],f.unselectAll],[["ArrowLeft","mac+ArrowLeft"],f.translateSelectedEditors,{args:[-h,0],checker:v}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],f.translateSelectedEditors,{args:[-b,0],checker:v}],[["ArrowRight","mac+ArrowRight"],f.translateSelectedEditors,{args:[h,0],checker:v}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],f.translateSelectedEditors,{args:[b,0],checker:v}],[["ArrowUp","mac+ArrowUp"],f.translateSelectedEditors,{args:[0,-h],checker:v}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],f.translateSelectedEditors,{args:[0,-b],checker:v}],[["ArrowDown","mac+ArrowDown"],f.translateSelectedEditors,{args:[0,h],checker:v}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],f.translateSelectedEditors,{args:[0,b],checker:v}]]))}constructor(f,v,r,h,b,A,D,_,I){this.#H=f,this.#K=v,this.#n=r,this._eventBus=h,this._eventBus._on("editingaction",this.#O),this._eventBus._on("pagechanging",this.#V),this._eventBus._on("scalechanging",this.#W),this._eventBus._on("rotationchanging",this.#$),this.#rt(),this.#J(),this.#r=b.annotationStorage,this.#c=b.filterFactory,this.#A=A,this.#g=D||null,this.#d=_,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.#W),this._eventBus._off("rotationchanging",this.#$);for(let f of this.#i.values())f.destroy();this.#i.clear(),this.#e.clear(),this.#u.clear(),this.#t=null,this.#v.clear(),this.#s.destroy(),this.#n?.destroy(),this.#y?.hide(),this.#y=null,this.#f&&(clearTimeout(this.#f),this.#f=null),this.#B&&(clearTimeout(this.#B),this.#B=null),this.#at()}async mlGuess(f){return this.#w?.guess(f)||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((f=>f.split("=").map((v=>v.trim()))))):null)}get highlightColorNames(){return(0,i.shadow)(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,(f=>f.reverse()))):null)}setMainHighlightColorPicker(f){this.#M=f}editAltText(f){this.#n?.editAltText(this,f)}onPageChanging({pageNumber:f}){this.#o=f-1}focusMainContainer(){this.#H.focus()}findParent(f,v){for(let r of this.#i.values()){let{x:h,y:b,width:A,height:D}=r.div.getBoundingClientRect();if(f>=h&&f<=h+A&&v>=b&&v<=b+D)return r}return null}disableUserSelect(f=!1){this.#K.classList.toggle("noUserSelect",f)}addShouldRescale(f){this.#u.add(f)}removeShouldRescale(f){this.#u.delete(f)}onScaleChanging({scale:f}){this.commitOrRemove(),this.viewParameters.realScale=f*n.PixelsPerInch.PDF_TO_CSS_UNITS;for(let v of this.#u)v.onScaleChanging()}onRotationChanging({pagesRotation:f}){this.commitOrRemove(),this.viewParameters.rotation=f}#q({anchorNode:f}){return f.nodeType===Node.TEXT_NODE?f.parentElement:f}highlightSelection(f=""){let v=document.getSelection();if(!v||v.isCollapsed)return;let{anchorNode:r,anchorOffset:h,focusNode:b,focusOffset:A}=v,D=v.toString(),_=this.#q(v).closest(".textLayer"),I=this.getSelectionBoxes(_);if(I){v.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(_)){N.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:f,boxes:I,anchorNode:r,anchorOffset:h,focusNode:b,focusOffset:A,text:D});break}}}#st(){let f=document.getSelection();if(!f||f.isCollapsed)return;let v=this.#q(f).closest(".textLayer"),r=this.getSelectionBoxes(v);r&&(this.#y||=new a.HighlightToolbar(this),this.#y.show(v,r,this.direction==="ltr"))}addToAnnotationStorage(f){f.isEmpty()||!this.#r||this.#r.has(f.id)||this.#r.setValue(f.id,f)}#nt(){let f=document.getSelection();if(!f||f.isCollapsed){this.#E&&(this.#y?.hide(),this.#E=null,this.#D({hasSelectedText:!1}));return}let{anchorNode:v}=f;if(v!==this.#E)if(this.#q(f).closest(".textLayer")){if(this.#y?.hide(),this.#E=v,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=h=>{(h.type!=="pointerup"||h.button===0)&&(window.removeEventListener("pointerup",r),window.removeEventListener("blur",r),h.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(f=""){this.#x===i.AnnotationEditorType.HIGHLIGHT?this.highlightSelection(f):this.#d&&this.#st()}#rt(){document.addEventListener("selectionchange",this.#j)}#at(){document.removeEventListener("selectionchange",this.#j)}#ot(){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.#p&&(this.#p=!1,this.#X("main_toolbar")),!this.hasSelection)return;let{activeElement:f}=document;for(let v of this.#v)if(v.div.contains(f)){this.#_=[v,f],v._focusEventsAllowed=!1;break}}focus(){if(!this.#_)return;let[f,v]=this.#_;this.#_=null,v.addEventListener("focusin",(()=>{f._focusEventsAllowed=!0}),{once:!0}),v.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.#R),document.addEventListener("cut",this.#P),document.addEventListener("paste",this.#L)}#tt(){document.removeEventListener("copy",this.#R),document.removeEventListener("cut",this.#P),document.removeEventListener("paste",this.#L)}addEditListeners(){this.#J(),this.#Z()}removeEditListeners(){this.#Q(),this.#tt()}copy(f){if(f.preventDefault(),this.#t?.commitOrRemove(),!this.hasSelection)return;let v=[];for(let r of this.#v){let h=r.serialize(!0);h&&v.push(h)}v.length!==0&&f.clipboardData.setData("application/pdfjs",JSON.stringify(v))}cut(f){this.copy(f),this.delete()}paste(f){f.preventDefault();let{clipboardData:v}=f;for(let b of v.items)for(let A of this.#h)if(A.isHandlingMimeForPasting(b.type)){A.paste(b,this.currentLayer);return}let r=v.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 h=this.currentLayer;try{let b=[];for(let _ of r){let I=h.deserialize(_);if(!I)return;b.push(I)}let A=()=>{for(let _ of b)this.#et(_);this.#it(b)},D=()=>{for(let _ of b)_.remove()};this.addCommands({cmd:A,undo:D,mustExec:!0})}catch(b){(0,i.warn)(`paste: "${b.message}".`)}}keydown(f){this.isShiftKeyDown||f.key!=="Shift"||(this.isShiftKeyDown=!0),this.#x===i.AnnotationEditorType.NONE||this.isEditorHandlingKeyboard||w._keyboardManager.exec(this,f)}keyup(f){this.isShiftKeyDown&&f.key==="Shift"&&(this.isShiftKeyDown=!1,this.#p&&(this.#p=!1,this.#X("main_toolbar")))}onEditingAction({name:f}){switch(f){case"undo":case"redo":case"delete":case"selectAll":this[f]();break;case"highlightSelection":this.highlightSelection("context_menu")}}#D(f){Object.entries(f).some((([v,r])=>this.#N[v]!==r))&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(this.#N,f)}),this.#x===i.AnnotationEditorType.HIGHLIGHT&&f.hasSelectedEditor===!1&&this.#U([[i.AnnotationEditorParamsType.HIGHLIGHT_FREE,!0]]))}#U(f){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:f})}setEditingState(f){f?(this.#ot(),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(f){if(!this.#h){this.#h=f;for(let v of this.#h)this.#U(v.defaultPropertiesToUpdate)}}getId(){return this.#m.id}get currentLayer(){return this.#i.get(this.#o)}getLayer(f){return this.#i.get(f)}get currentPageIndex(){return this.#o}addLayer(f){this.#i.set(f.pageIndex,f),this.#b?f.enable():f.disable()}removeLayer(f){this.#i.delete(f.pageIndex)}updateMode(f,v=null,r=!1){if(this.#x!==f)if(this.#x=f,f!==i.AnnotationEditorType.NONE){this.setEditingState(!0),this.#lt(),this.unselectAll();for(let h of this.#i.values())h.updateMode(f);if(v||!r){if(v){for(let h of this.#e.values())if(h.annotationElementId===v){this.setSelected(h),h.enterInEditMode();break}}}else this.addNewEditorFromKeyboard()}else this.setEditingState(!1),this.#ct()}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(f){f!==this.#x&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:f})}updateParams(f,v){if(this.#h){switch(f){case i.AnnotationEditorParamsType.CREATE:this.currentLayer.addNewEditor();return;case i.AnnotationEditorParamsType.HIGHLIGHT_DEFAULT_COLOR:this.#M?.updateColor(v);break;case i.AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(this.#C||=new Map).set(f,v),this.showAllEditors("highlight",v)}for(let r of this.#v)r.updateParams(f,v);for(let r of this.#h)r.updateDefaultParams(f,v)}}showAllEditors(f,v,r=!1){for(let h of this.#e.values())h.editorType===f&&h.show(v);(this.#C?.get(i.AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL)??!0)!==v&&this.#U([[i.AnnotationEditorParamsType.HIGHLIGHT_SHOW_ALL,v]])}enableWaiting(f=!1){if(this.#S!==f){this.#S=f;for(let v of this.#i.values())f?v.disableClick():v.enableClick(),v.div.classList.toggle("waiting",f)}}#lt(){if(!this.#b){this.#b=!0;for(let f of this.#i.values())f.enable();for(let f of this.#e.values())f.enable()}}#ct(){if(this.unselectAll(),this.#b){this.#b=!1;for(let f of this.#i.values())f.disable();for(let f of this.#e.values())f.disable()}}getEditors(f){let v=[];for(let r of this.#e.values())r.pageIndex===f&&v.push(r);return v}getEditor(f){return this.#e.get(f)}addEditor(f){this.#e.set(f.id,f)}removeEditor(f){f.div.contains(document.activeElement)&&(this.#f&&clearTimeout(this.#f),this.#f=setTimeout((()=>{this.focusMainContainer(),this.#f=null}),0)),this.#e.delete(f.id),this.unselect(f),f.annotationElementId&&this.#l.has(f.annotationElementId)||this.#r?.remove(f.id)}addDeletedAnnotationElement(f){this.#l.add(f.annotationElementId),f.deleted=!0}isDeletedAnnotationElement(f){return this.#l.has(f)}removeDeletedAnnotationElement(f){this.#l.delete(f.annotationElementId),f.deleted=!1}#et(f){let v=this.#i.get(f.pageIndex);v?v.addOrRebuild(f):(this.addEditor(f),this.addToAnnotationStorage(f))}setActiveEditor(f){this.#t!==f&&(this.#t=f,f&&this.#U(f.propertiesToUpdate))}get#ht(){let f=null;for(f of this.#v);return f}updateUI(f){this.#ht===f&&this.#U(f.propertiesToUpdate)}toggleSelected(f){this.#v.has(f)?(this.#v.delete(f),f.unselect(),this.#D({hasSelectedEditor:this.hasSelection})):(this.#v.add(f),f.select(),this.#U(f.propertiesToUpdate),this.#D({hasSelectedEditor:!0}))}setSelected(f){for(let v of this.#v)v!==f&&v.unselect();this.#v.clear(),this.#v.add(f),f.select(),this.#U(f.propertiesToUpdate),this.#D({hasSelectedEditor:!0})}isSelected(f){return this.#v.has(f)}get firstSelectedEditor(){return this.#v.values().next().value}unselect(f){f.unselect(),this.#v.delete(f),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(f){this.#s.add(f),this.#D({hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:this.#G()})}#G(){if(this.#e.size===0)return!0;if(this.#e.size===1)for(let f of this.#e.values())return f.isEmpty();return!1}delete(){if(this.commitOrRemove(),!this.hasSelection)return;let f=[...this.#v];this.addCommands({cmd:()=>{for(let v of f)v.remove()},undo:()=>{for(let v of f)this.#et(v)},mustExec:!0})}commitOrRemove(){this.#t?.commitOrRemove()}hasSomethingToControl(){return this.#t||this.hasSelection}#it(f){for(let v of this.#v)v.unselect();this.#v.clear();for(let v of f)v.isEmpty()||(this.#v.add(v),v.select());this.#D({hasSelectedEditor:this.hasSelection})}selectAll(){for(let f of this.#v)f.commit();this.#it(this.#e.values())}unselectAll(){if(!(this.#t&&(this.#t.commitOrRemove(),this.#x!==i.AnnotationEditorType.NONE))&&this.hasSelection){for(let f of this.#v)f.unselect();this.#v.clear(),this.#D({hasSelectedEditor:!1})}}translateSelectedEditors(f,v,r=!1){if(r||this.commitOrRemove(),!this.hasSelection)return;this.#z[0]+=f,this.#z[1]+=v;let[h,b]=this.#z,A=[...this.#v];this.#B&&clearTimeout(this.#B),this.#B=setTimeout((()=>{this.#B=null,this.#z[0]=this.#z[1]=0,this.addCommands({cmd:()=>{for(let D of A)this.#e.has(D.id)&&D.translateInPage(h,b)},undo:()=>{for(let D of A)this.#e.has(D.id)&&D.translateInPage(-h,-b)},mustExec:!1})}),1e3);for(let D of A)D.translateInPage(f,v)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),this.#a=new Map;for(let f of this.#v)this.#a.set(f,{savedX:f.x,savedY:f.y,savedPageIndex:f.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!this.#a)return!1;this.disableUserSelect(!1);let f=this.#a;this.#a=null;let v=!1;for(let[{x:h,y:b,pageIndex:A},D]of f)D.newX=h,D.newY=b,D.newPageIndex=A,v||=h!==D.savedX||b!==D.savedY||A!==D.savedPageIndex;if(!v)return!1;let r=(h,b,A,D)=>{if(this.#e.has(h.id)){let _=this.#i.get(D);_?h._setParentAndPosition(_,b,A):(h.pageIndex=D,h.x=b,h.y=A)}};return this.addCommands({cmd:()=>{for(let[h,{newX:b,newY:A,newPageIndex:D}]of f)r(h,b,A,D)},undo:()=>{for(let[h,{savedX:b,savedY:A,savedPageIndex:D}]of f)r(h,b,A,D)},mustExec:!0}),!0}dragSelectedEditors(f,v){if(this.#a)for(let r of this.#a.keys())r.drag(f,v)}rebuild(f){if(f.parent===null){let v=this.getLayer(f.pageIndex);v?(v.changeParent(f),v.addOrRebuild(f)):(this.addEditor(f),this.addToAnnotationStorage(f),f.rebuild())}else f.parent.addOrRebuild(f)}get isEditorHandlingKeyboard(){return this.getActive()?.shouldGetKeyboardEvents()||this.#v.size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(f){return this.#t===f}getActive(){return this.#t}getMode(){return this.#x}get imageManager(){return(0,i.shadow)(this,"imageManager",new m)}getSelectionBoxes(f){if(!f)return null;let v=document.getSelection();for(let I=0,N=v.rangeCount;I<N;I++)if(!f.contains(v.getRangeAt(I).commonAncestorContainer))return null;let{x:r,y:h,width:b,height:A}=f.getBoundingClientRect(),D;switch(f.getAttribute("data-main-rotation")){case"90":D=(I,N,H,j)=>({x:(N-h)/A,y:1-(I+H-r)/b,width:j/A,height:H/b});break;case"180":D=(I,N,H,j)=>({x:1-(I+H-r)/b,y:1-(N+j-h)/A,width:H/b,height:j/A});break;case"270":D=(I,N,H,j)=>({x:1-(N+j-h)/A,y:(I-r)/b,width:j/A,height:H/b});break;default:D=(I,N,H,j)=>({x:(I-r)/b,y:(N-h)/A,width:H/b,height:j/A})}let _=[];for(let I=0,N=v.rangeCount;I<N;I++){let H=v.getRangeAt(I);if(!H.collapsed)for(let{x:j,y:K,width:it,height:ot}of H.getClientRects())it!==0&&ot!==0&&_.push(D(j,K,it,ot))}return _.length===0?null:_}}},94:(s,t,e)=>{e.d(t,{PDFFetchStream:()=>d});var i=e(292),n=e(490);function a(o,p,w){return{method:"GET",headers:o,signal:w.signal,mode:"cors",credentials:p?"include":"same-origin",redirect:"follow"}}function c(o){let p=new Headers;for(let w in o){let S=o[w];S!==void 0&&p.append(w,S)}return p}function l(o){return o instanceof Uint8Array?o.buffer:o instanceof ArrayBuffer?o:((0,i.warn)(`getArrayBuffer - unexpected data format: ${o}`),new Uint8Array(o).buffer)}class d{constructor(p){this.source=p,this.isHttp=/^https?:/i.test(p.url),this.httpHeaders=this.isHttp&&p.httpHeaders||{},this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return(0,i.assert)(!this._fullRequestReader,"PDFFetchStream.getFullReader can only be called once."),this._fullRequestReader=new m(this),this._fullRequestReader}getRangeReader(p,w){if(w<=this._progressiveDataLength)return null;let S=new u(this,p,w);return this._rangeRequestReaders.push(S),S}cancelAllRequests(p){this._fullRequestReader?.cancel(p);for(let w of this._rangeRequestReaders.slice(0))w.cancel(p)}}class m{constructor(p){this._stream=p,this._reader=null,this._loaded=0,this._filename=null;let w=p.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 S=w.url;fetch(S,a(this._headers,this._withCredentials,this._abortController)).then((f=>{if(!(0,n.validateResponseStatus)(f.status))throw(0,n.createResponseStatusError)(f.status,S);this._reader=f.body.getReader(),this._headersCapability.resolve();let v=b=>f.headers.get(b),{allowRangeRequests:r,suggestedLength:h}=(0,n.validateRangeRequestCapabilities)({getResponseHeader:v,isHttp:this._stream.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=r,this._contentLength=h||this._contentLength,this._filename=(0,n.extractFilenameFromHeader)(v),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new i.AbortException("Streaming is disabled."))})).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){await this._headersCapability.promise;let{value:p,done:w}=await this._reader.read();return w?{value:p,done:w}:(this._loaded+=p.byteLength,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:l(p),done:!1})}cancel(p){this._reader?.cancel(p),this._abortController.abort()}}class u{constructor(p,w,S){this._stream=p,this._reader=null,this._loaded=0;let f=p.source;this._withCredentials=f.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!f.disableStream,this._abortController=new AbortController,this._headers=c(this._stream.httpHeaders),this._headers.append("Range",`bytes=${w}-${S-1}`);let v=f.url;fetch(v,a(this._headers,this._withCredentials,this._abortController)).then((r=>{if(!(0,n.validateResponseStatus)(r.status))throw(0,n.createResponseStatusError)(r.status,v);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:p,done:w}=await this._reader.read();return w?{value:p,done:w}:(this._loaded+=p.byteLength,this.onProgress?.({loaded:this._loaded}),{value:l(p),done:!1})}cancel(p){this._reader?.cancel(p),this._abortController.abort()}}},10:(s,t,e)=>{e.d(t,{FontFaceObject:()=>a,FontLoader:()=>n});var i=e(292);class n{#t=new Set;constructor({ownerDocument:l=globalThis.document,styleElement:d=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 d=this.styleElement.sheet;d.insertRule(l,d.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:d}){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:o}=l,p=new FontFace(m,u,o);this.addNativeFontFace(p);try{await p.load(),this.#t.add(m),d?.(l)}catch{(0,i.warn)(`Cannot load system font: ${l.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(p)}}else(0,i.unreachable)("Not implemented: loadSystemFont without the Font Loading API.")}async bind(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 d=l.createFontFaceRule();if(d){if(this.insertRule(d),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:d}=this,m={done:!1,complete:function(){for((0,i.assert)(!m.done,"completeRequest() cannot be called twice."),m.done=!0;d.length>0&&d[0].done;){let o=d.shift();setTimeout(o.callback,0)}},callback:l};return d.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,d){function m(_,I){return _.charCodeAt(I)<<24|_.charCodeAt(I+1)<<16|_.charCodeAt(I+2)<<8|255&_.charCodeAt(I+3)}function u(_,I,N,H){return _.substring(0,I)+H+_.substring(I+N)}let o,p,w=this._document.createElement("canvas");w.width=1,w.height=1;let S=w.getContext("2d"),f=0,v=`lt${Date.now()}${this.loadTestFontId++}`,r=this._loadTestFont;r=u(r,976,v.length,v);let h=1482184792,b=m(r,16);for(o=0,p=v.length-3;o<p;o+=4)b=b-h+m(v,o)|0;o<v.length&&(b=b-h+m(v+"XXX",o)|0),r=u(r,16,4,(0,i.string32)(b));let A=`@font-face {font-family:"${v}";src:${`url(data:font/opentype;base64,${btoa(r)});`}}`;this.insertRule(A);let D=this._document.createElement("div");D.style.visibility="hidden",D.style.width=D.style.height="10px",D.style.position="absolute",D.style.top=D.style.left="0px";for(let _ of[l.loadedName,v]){let I=this._document.createElement("span");I.textContent="Hi",I.style.fontFamily=_,D.append(I)}this._document.body.append(D),(function _(I,N){if(++f>30){(0,i.warn)("Load test font never loaded."),N();return}S.font="30px "+I,S.fillText(".",0,20),S.getImageData(0,0,1,1).data[3]>0?N():setTimeout(_.bind(null,I,N))})(v,(()=>{D.remove(),d.complete()}))}}class a{constructor(l,{isEvalSupported:d=!0,disableFontFace:m=!1,ignoreErrors:u=!1,inspectFont:o=null}){this.compiledGlyphs=Object.create(null);for(let p in l)this[p]=l[p];this.isEvalSupported=d!==!1,this.disableFontFace=m===!0,this.ignoreErrors=u===!0,this._inspectFont=o}createNativeFontFace(){if(!this.data||this.disableFontFace)return null;let l;if(this.cssFontInfo){let d={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(d.style=`oblique ${this.cssFontInfo.italicAngle}deg`),l=new FontFace(this.cssFontInfo.fontFamily,this.data,d)}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),d=`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:${d}}`}else m=`@font-face {font-family:"${this.loadedName}";src:${d}}`;return this._inspectFont?.(this,d),m}getPathGenerator(l,d){if(this.compiledGlyphs[d]!==void 0)return this.compiledGlyphs[d];let m;try{m=l.get(this.loadedName+"_path_"+d)}catch(u){if(!this.ignoreErrors)throw u;return(0,i.warn)(`getPathGenerator - ignoring character: "${u}".`),this.compiledGlyphs[d]=function(o,p){}}if(this.isEvalSupported&&i.FeatureTest.isEvalSupported){let u=[];for(let o of m){let p=o.args!==void 0?o.args.join(","):"";u.push("c.",o.cmd,"(",p,`);
|
|
14
|
-
`)}return this.compiledGlyphs[d]=new Function("c","size",u.join(""))}return this.compiledGlyphs[d]=function(u,o){for(let p of m)p.cmd==="scale"&&(p.args=[o,-o]),u[p.cmd].apply(u,p.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 a{constructor(u,o={}){this.url=u,this.isHttp=/^https?:/i.test(u),this.httpHeaders=this.isHttp&&o.httpHeaders||Object.create(null),this.withCredentials=o.withCredentials||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}requestRange(u,o,p){let w={begin:u,end:o};for(let S in p)w[S]=p[S];return this.request(w)}requestFull(u){return this.request(u)}request(u){let o=new XMLHttpRequest,p=this.currXhrId++,w=this.pendingRequests[p]={xhr:o};o.open("GET",this.url),o.withCredentials=this.withCredentials;for(let S in this.httpHeaders){let f=this.httpHeaders[S];f!==void 0&&o.setRequestHeader(S,f)}return this.isHttp&&"begin"in u&&"end"in u?(o.setRequestHeader("Range",`bytes=${u.begin}-${u.end-1}`),w.expectedStatus=206):w.expectedStatus=200,o.responseType="arraybuffer",u.onError&&(o.onerror=function(S){u.onError(o.status)}),o.onreadystatechange=this.onStateChange.bind(this,p),o.onprogress=this.onProgress.bind(this,p),w.onHeadersReceived=u.onHeadersReceived,w.onDone=u.onDone,w.onError=u.onError,w.onProgress=u.onProgress,o.send(null),p}onProgress(u,o){let p=this.pendingRequests[u];p&&p.onProgress?.(o)}onStateChange(u,o){let p=this.pendingRequests[u];if(!p)return;let w=p.xhr;if(w.readyState>=2&&p.onHeadersReceived&&(p.onHeadersReceived(),delete p.onHeadersReceived),w.readyState!==4||!(u in this.pendingRequests))return;if(delete this.pendingRequests[u],w.status===0&&this.isHttp){p.onError?.(w.status);return}let S=w.status||200;if(!(S===200&&p.expectedStatus===206)&&S!==p.expectedStatus){p.onError?.(w.status);return}let f=(function(r){let h=r.response;return typeof h!="string"?h:(0,i.stringToBytes)(h).buffer})(w);if(S===206){let v=w.getResponseHeader("Content-Range"),r=/bytes (\d+)-(\d+)\/(\d+)/.exec(v);p.onDone({begin:parseInt(r[1],10),chunk:f})}else f?p.onDone({begin:0,chunk:f}):p.onError?.(w.status)}getRequestXhr(u){return this.pendingRequests[u].xhr}isPendingRequest(u){return u in this.pendingRequests}abortRequest(u){let o=this.pendingRequests[u].xhr;delete this.pendingRequests[u],o.abort()}}class c{constructor(u){this._source=u,this._manager=new a(u.url,{httpHeaders:u.httpHeaders,withCredentials:u.withCredentials}),this._rangeChunkSize=u.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(u){let o=this._rangeRequestReaders.indexOf(u);o>=0&&this._rangeRequestReaders.splice(o,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,o){let p=new d(this._manager,u,o);return p.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(p),p}cancelAllRequests(u){this._fullRequestReader?.cancel(u);for(let o of this._rangeRequestReaders.slice(0))o.cancel(u)}}class l{constructor(u,o){this._manager=u;let p={onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=o.url,this._fullRequestId=u.requestFull(p),this._headersReceivedCapability=Promise.withResolvers(),this._disableRange=o.disableRange||!1,this._contentLength=o.length,this._rangeChunkSize=o.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,o=this._manager.getRequestXhr(u),p=f=>o.getResponseHeader(f),{allowRangeRequests:w,suggestedLength:S}=(0,n.validateRangeRequestCapabilities)({getResponseHeader:p,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});w&&(this._isRangeSupported=!0),this._contentLength=S||this._contentLength,this._filename=(0,n.extractFilenameFromHeader)(p),this._isRangeSupported&&this._manager.abortRequest(u),this._headersReceivedCapability.resolve()}_onDone(u){if(u&&(this._requests.length>0?this._requests.shift().resolve({value:u.chunk,done:!1}):this._cachedChunks.push(u.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(let o of this._requests)o.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 o of this._requests)o.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 o of this._requests)o.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class d{constructor(u,o,p){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(o,p,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 o=u.chunk;this._requests.length>0?this._requests.shift().resolve({value:o,done:!1}):this._queuedChunk=o,this._done=!0;for(let p of this._requests)p.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(u){this._storedError=(0,n.createResponseStatusError)(u,this._url);for(let o of this._requests)o.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 o=this._queuedChunk;return this._queuedChunk=null,{value:o,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 o of this._requests)o.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:()=>a,validateResponseStatus:()=>d});var i=e(292),n=e(419);function a({getResponseHeader:m,isHttp:u,rangeChunkSize:o,disableRange:p}){let w={allowRangeRequests:!1,suggestedLength:void 0},S=parseInt(m("Content-Length"),10);return!Number.isInteger(S)||(w.suggestedLength=S,S<=2*o)||p||!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 o=(function(w){let S=!0,f=v("filename\\*","i").exec(w);if(f){f=f[1];let _=b(f);return _=unescape(_),_=A(_),_=D(_),h(_)}if(f=(function(I){let N=[],H,j=v("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(H=j.exec(I))!==null;){let[,it,ot,X]=H;if(it=parseInt(it,10),it in N){if(it===0)break}else N[it]=[ot,X]}let K=[];for(let it=0;it<N.length&&it in N;++it){let[ot,X]=N[it];X=b(X),ot&&(X=unescape(X),it===0&&(X=A(X))),K.push(X)}return K.join("")})(w),f)return h(D(f));if(f=v("filename","i").exec(w),f){f=f[1];let _=b(f);return _=D(_),h(_)}function v(_,I){return new RegExp("(?:^|;)\\s*"+_+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',I)}function r(_,I){if(_){if(!/^[\x00-\xFF]+$/.test(I))return I;try{let N=new TextDecoder(_,{fatal:!0}),H=(0,i.stringToBytes)(I);I=N.decode(H),S=!1}catch{}}return I}function h(_){return S&&/[\x80-\xff]/.test(_)&&(_=r("utf-8",_),S&&(_=r("iso-8859-1",_))),_}function b(_){if(_.startsWith('"')){let I=_.slice(1).split('\\"');for(let N=0;N<I.length;++N){let H=I[N].indexOf('"');H!==-1&&(I[N]=I[N].slice(0,H),I.length=N+1),I[N]=I[N].replaceAll(/\\(.)/g,"$1")}_=I.join('"')}return _}function A(_){let I=_.indexOf("'");return I===-1?_:r(_.slice(0,I),_.slice(I+1).replace(/^[^']*'/,""))}function D(_){return!_.startsWith("=?")||/[\x00-\x19\x80-\xff]/.test(_)?_:_.replaceAll(/=\?([\w-]*)\?([QqBb])\?((?:[^?]|\?(?!=))*)\?=/g,(function(I,N,H,j){if(H==="q"||H==="Q")return r(N,j=(j=j.replaceAll("_"," ")).replaceAll(/=([0-9a-fA-F]{2})/g,(function(K,it){return String.fromCharCode(parseInt(it,16))})));try{j=atob(j)}catch{}return r(N,j)}))}return""})(u);if(o.includes("%"))try{o=decodeURIComponent(o)}catch{}if((0,n.isPdfFile)(o))return o}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 d(m){return m===200||m===206}},786:(s,t,e)=>{e.a(s,(async(i,n)=>{try{let p=function(D){let _=u.parse(D);return _.protocol==="file:"||_.host?_:/^[a-z]:[/\\]/i.test(D)?u.parse(`file:///${D}`):(_.host||(_.protocol="file:"),_)},v=function(D,_){return{protocol:D.protocol,auth:D.auth,host:D.hostname,port:D.port,path:D.path,method:"GET",headers:_}};e.d(t,{PDFNodeStream:()=>w});var a=e(292),c=e(490);let l,d,m,u;a.isNodeJS&&(l=await Promise.resolve().then(()=>(xo(),wo)),d=await Promise.resolve().then(()=>(Bc(),Nc)),m=await Promise.resolve().then(()=>($c(),Uc)),u=await Promise.resolve().then(()=>(jc(),Hc)));let o=/^file:\/\/\/[a-zA-Z]:\//;class w{constructor(_){this.source=_,this.url=p(_.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.httpHeaders=this.isHttp&&_.httpHeaders||{},this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){return this._fullRequestReader?._loaded??0}getFullReader(){return(0,a.assert)(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new b(this):new r(this),this._fullRequestReader}getRangeReader(_,I){if(I<=this._progressiveDataLength)return null;let N=this.isFsUrl?new A(this,_,I):new h(this,_,I);return this._rangeRequestReaders.push(N),N}cancelAllRequests(_){this._fullRequestReader?.cancel(_);for(let I of this._rangeRequestReaders.slice(0))I.cancel(_)}}class S{constructor(_){this._url=_.url,this._done=!1,this._storedError=null,this.onProgress=null;let I=_.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 _=this._readableStream.read();return _===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=_.length,this.onProgress?.({loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(_).buffer,done:!1})}cancel(_){this._readableStream?this._readableStream.destroy(_):this._error(_)}_error(_){this._storedError=_,this._readCapability.resolve()}_setReadableStream(_){this._readableStream=_,_.on("readable",(()=>{this._readCapability.resolve()})),_.on("end",(()=>{_.destroy(),this._done=!0,this._readCapability.resolve()})),_.on("error",(I=>{this._error(I)})),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new a.AbortException("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class f{constructor(_){this._url=_.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();let I=_.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 _=this._readableStream.read();return _===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=_.length,this.onProgress?.({loaded:this._loaded}),{value:new Uint8Array(_).buffer,done:!1})}cancel(_){this._readableStream?this._readableStream.destroy(_):this._error(_)}_error(_){this._storedError=_,this._readCapability.resolve()}_setReadableStream(_){this._readableStream=_,_.on("readable",(()=>{this._readCapability.resolve()})),_.on("end",(()=>{_.destroy(),this._done=!0,this._readCapability.resolve()})),_.on("error",(I=>{this._error(I)})),this._storedError&&this._readableStream.destroy(this._storedError)}}class r extends S{constructor(_){super(_);let I=N=>{if(N.statusCode===404){let it=new a.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=it,this._headersCapability.reject(it);return}this._headersCapability.resolve(),this._setReadableStream(N);let H=it=>this._readableStream.headers[it.toLowerCase()],{allowRangeRequests:j,suggestedLength:K}=(0,c.validateRangeRequestCapabilities)({getResponseHeader:H,isHttp:_.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=j,this._contentLength=K||this._contentLength,this._filename=(0,c.extractFilenameFromHeader)(H)};this._request=null,this._url.protocol==="http:"?this._request=d.request(v(this._url,_.httpHeaders),I):this._request=m.request(v(this._url,_.httpHeaders),I),this._request.on("error",(N=>{this._storedError=N,this._headersCapability.reject(N)})),this._request.end()}}class h extends f{constructor(_,I,N){super(_),this._httpHeaders={};for(let j in _.httpHeaders){let K=_.httpHeaders[j];K!==void 0&&(this._httpHeaders[j]=K)}this._httpHeaders.Range=`bytes=${I}-${N-1}`;let H=j=>{if(j.statusCode!==404)this._setReadableStream(j);else{let K=new a.MissingPDFException(`Missing PDF "${this._url}".`);this._storedError=K}};this._request=null,this._url.protocol==="http:"?this._request=d.request(v(this._url,this._httpHeaders),H):this._request=m.request(v(this._url,this._httpHeaders),H),this._request.on("error",(j=>{this._storedError=j})),this._request.end()}}class b extends S{constructor(_){super(_);let I=decodeURIComponent(this._url.path);o.test(this._url.href)&&(I=I.replace(/^\//,"")),l.promises.lstat(I).then((N=>{this._contentLength=N.size,this._setReadableStream(l.createReadStream(I)),this._headersCapability.resolve()}),(N=>{N.code==="ENOENT"&&(N=new a.MissingPDFException(`Missing PDF "${I}".`)),this._storedError=N,this._headersCapability.reject(N)}))}}class A extends f{constructor(_,I,N){super(_);let H=decodeURIComponent(this._url.path);o.test(this._url.href)&&(H=H.replace(/^\//,"")),this._setReadableStream(l.createReadStream(H,{start:I,end:N-1}))}}n()}catch(l){n(l)}}),1)},573:(s,t,e)=>{e.a(s,(async(i,n)=>{try{e.d(t,{NodeCMapReaderFactory:()=>p,NodeCanvasFactory:()=>o,NodeFilterFactory:()=>u,NodeStandardFontDataFactory:()=>w});var a=e(583);let c,l,d;if(e(292).isNodeJS){c=await Promise.resolve().then(()=>(xo(),wo));try{l=await Promise.resolve().then(()=>(Vc(),zc))}catch{}try{d=await Promise.resolve().then(()=>(Gc(),Wc))}catch{}}let m=function(S){return c.promises.readFile(S).then((f=>new Uint8Array(f)))};class u extends a.BaseFilterFactory{}class o extends a.BaseCanvasFactory{_createCanvas(f,v){return l.createCanvas(f,v)}}class p extends a.BaseCMapReaderFactory{_fetchData(f,v){return m(f).then((r=>({cMapData:r,compressionType:v})))}}class w extends a.BaseStandardFontDataFactory{_fetchData(f){return m(f)}}n()}catch(c){n(c)}}),1)},626:(s,t,e)=>{e.d(t,{OptionalContentConfig:()=>l});var i=e(292),n=e(651);let a=Symbol("INTERNAL");class c{#t=!1;#e=!1;#i=!1;#n=!0;constructor(m,{name:u,intent:o,usage:p}){this.#t=!!(m&i.RenderingIntentFlag.DISPLAY),this.#e=!!(m&i.RenderingIntentFlag.PRINT),this.name=u,this.intent=o,this.usage=p}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,o=!1){m!==a&&(0,i.unreachable)("Internal method `_setVisible` called."),this.#i=o,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 o of m.groups)this.#e.set(o.id,new c(u,o));if(m.baseState==="OFF")for(let o of this.#e.values())o._setVisible(a,!1);for(let o of m.on)this.#e.get(o)._setVisible(a,!0);for(let o of m.off)this.#e.get(o)._setVisible(a,!1);this.#i=this.getHash()}}#r(m){let u=m.length;if(u<2)return!0;let o=m[0];for(let p=1;p<u;p++){let w=m[p],S;if(Array.isArray(w))S=this.#r(w);else{if(!this.#e.has(w))return(0,i.warn)(`Optional content group not found: ${w}`),!0;S=this.#e.get(w).visible}switch(o){case"And":if(!S)return!1;break;case"Or":if(S)return!0;break;case"Not":return!S;default:return!0}}return o==="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 o=this.#e.get(m);o?(o._setVisible(a,!!u,!0),this.#t=null):(0,i.warn)(`Optional content group not found: ${m}`)}setOCGState({state:m,preserveRB:u}){let o;for(let p of m){switch(p){case"ON":case"OFF":case"Toggle":o=p;continue}let w=this.#e.get(p);if(w)switch(o){case"ON":w._setVisible(a,!0);break;case"OFF":w._setVisible(a,!1);break;case"Toggle":w._setVisible(a,!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,o]of this.#e)m.update(`${u}:${o.visible}`);return this.#t=m.hexdigest()}}},814:(s,t,e)=>{e.d(t,{cleanupTextLayer:()=>u,renderTextLayer:()=>S,updateTextLayer:()=>f});var i=e(292),n=e(419);let a=30,c=.8,l=new Map,d=null;function m(){if(!d){let v=document.createElement("canvas");v.className="hiddenCanvasElement",document.body.append(v),d=v.getContext("2d",{alpha:!1})}return d}function u(){d?.canvas.remove(),d=null}function o(v,r,h){let b=document.createElement("span"),A={angle:0,canvasWidth:0,hasText:r.str!=="",hasEOL:r.hasEOL,fontSize:0};v._textDivs.push(b);let D=i.Util.transform(v._transform,r.transform),_=Math.atan2(D[1],D[0]),I=h[r.fontName];I.vertical&&(_+=Math.PI/2);let N=v._fontInspectorEnabled&&I.fontSubstitution||I.fontFamily,H=Math.hypot(D[2],D[3]),j=H*(function(Y){let et=l.get(Y);if(et)return et;let rt=m(),ct=rt.font;rt.canvas.width=rt.canvas.height=a,rt.font=`${a}px ${Y}`;let st=rt.measureText(""),G=st.fontBoundingBoxAscent,x=Math.abs(st.fontBoundingBoxDescent);if(G){let R=G/(G+x);return l.set(Y,R),rt.canvas.width=rt.canvas.height=0,rt.font=ct,R}rt.strokeStyle="red",rt.clearRect(0,0,a,a),rt.strokeText("g",0,0);let T=rt.getImageData(0,0,a,a).data;x=0;for(let R=T.length-1-3;R>=0;R-=4)if(T[R]>0){x=Math.ceil(R/4/a);break}rt.clearRect(0,0,a,a),rt.strokeText("A",0,a),T=rt.getImageData(0,0,a,a).data,G=0;for(let R=0,g=T.length;R<g;R+=4)if(T[R]>0){G=a-Math.floor(R/4/a);break}if(rt.canvas.width=rt.canvas.height=0,rt.font=ct,G){let R=G/(G+x);return l.set(Y,R),R}return l.set(Y,c),c})(N),K,it;_===0?(K=D[4],it=D[5]-j):(K=D[4]+j*Math.sin(_),it=D[5]-j*Math.cos(_));let ot="calc(var(--scale-factor)*",X=b.style;v._container===v._rootContainer?(X.left=`${(100*K/v._pageWidth).toFixed(2)}%`,X.top=`${(100*it/v._pageHeight).toFixed(2)}%`):(X.left=`${ot}${K.toFixed(2)}px)`,X.top=`${ot}${it.toFixed(2)}px)`),X.fontSize=`${ot}${H.toFixed(2)}px)`,X.fontFamily=N,A.fontSize=H,b.setAttribute("role","presentation"),b.textContent=r.str,b.dir=r.dir,v._fontInspectorEnabled&&(b.dataset.fontName=I.fontSubstitutionLoadedName||r.fontName),_!==0&&(A.angle=_*(180/Math.PI));let z=!1;if(r.str.length>1)z=!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&&(z=!0)}z&&(A.canvasWidth=I.vertical?r.height:r.width),v._textDivProperties.set(b,A),v._isReadableStream&&v._layoutText(b)}function p(v){let{div:r,scale:h,properties:b,ctx:A,prevFontSize:D,prevFontFamily:_}=v,{style:I}=r,N="";if(b.canvasWidth!==0&&b.hasText){let{fontFamily:H}=I,{canvasWidth:j,fontSize:K}=b;(D!==K||_!==H)&&(A.font=`${K*h}px ${H}`,v.prevFontSize=K,v.prevFontFamily=H);let{width:it}=A.measureText(r.textContent);it>0&&(N=`scaleX(${j*h/it})`)}b.angle!==0&&(N=`rotate(${b.angle}deg) ${N}`),N.length>0&&(I.transform=N)}class w{constructor({textContentSource:r,container:h,viewport:b,textDivs:A,textDivProperties:D,textContentItemsStr:_}){this._textContentSource=r,this._isReadableStream=r instanceof ReadableStream,this._container=this._rootContainer=h,this._textDivs=A||[],this._textContentItemsStr=_||[],this._fontInspectorEnabled=!!globalThis.FontInspector?.enabled,this._reader=null,this._textDivProperties=D||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:H,pageY:j}=b.rawDims;this._transform=[1,0,0,-1,-H,j+N],this._pageWidth=I,this._pageHeight=N,(0,n.setLayerDimensions)(h,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,h){for(let b of r)if(b.str!==void 0)this._textContentItemsStr.push(b.str),o(this,b,h);else if(b.type==="beginMarkedContentProps"||b.type==="beginMarkedContent"){let A=this._container;this._container=document.createElement("span"),this._container.classList.add("markedContent"),b.id!==null&&this._container.setAttribute("id",`${b.id}`),A.append(this._container)}else b.type==="endMarkedContent"&&(this._container=this._container.parentNode)}_layoutText(r){let h=this._layoutTextParams.properties=this._textDivProperties.get(r);if(this._layoutTextParams.div=r,p(this._layoutTextParams),h.hasText&&this._container.append(r),h.hasEOL){let b=document.createElement("br");b.setAttribute("role","presentation"),this._container.append(b)}}_render(){let{promise:r,resolve:h,reject:b}=Promise.withResolvers(),A=Object.create(null);if(this._isReadableStream){let D=()=>{this._reader.read().then((({value:_,done:I})=>{I?h():(Object.assign(A,_.styles),this._processItems(_.items,A),D())}),b)};this._reader=this._textContentSource.getReader(),D()}else{if(!this._textContentSource)throw new Error('No "textContentSource" parameter specified.');{let{items:D,styles:_}=this._textContentSource;this._processItems(D,_),h()}}r.then((()=>{A=null,(function(_){if(_._canceled)return;let I=_._textDivs,N=_._capability;if(I.length>1e5)N.resolve();else{if(!_._isReadableStream)for(let H of I)_._layoutText(H);N.resolve()}})(this)}),this._capability.reject)}}function S(v){let r=new w(v);return r._render(),r}function f({container:v,viewport:r,textDivs:h,textDivProperties:b,mustRotate:A=!0,mustRescale:D=!0}){if(A&&(0,n.setLayerDimensions)(v,{rotation:r.rotation}),D){let _=m(),I={prevFontSize:null,prevFontFamily:null,div:null,scale:r.scale*(globalThis.devicePixelRatio||1),properties:null,ctx:_};for(let N of h)I.properties=b.get(N),I.div=N,p(I)}}},585:(s,t,e)=>{e.d(t,{PDFDataTransportStream:()=>a});var i=e(292),n=e(419);class a{constructor(m,{disableRange:u=!1,disableStream:o=!1}){(0,i.assert)(m,'PDFDataTransportStream - missing required "pdfDataRangeTransport" argument.');let{length:p,initialData:w,progressiveDone:S,contentDispositionFilename:f}=m;if(this._queuedChunks=[],this._progressiveDone=S,this._contentDispositionFilename=f,w?.length>0){let v=w instanceof Uint8Array&&w.byteLength===w.buffer.byteLength?w.buffer:new Uint8Array(w).buffer;this._queuedChunks.push(v)}this._pdfDataRangeTransport=m,this._isStreamingSupported=!o,this._isRangeSupported=!u,this._contentLength=p,this._fullRequestReader=null,this._rangeReaders=[],m.addRangeListener(((v,r)=>{this._onReceiveData({begin:v,chunk:r})})),m.addProgressListener(((v,r)=>{this._onProgress({loaded:v,total:r})})),m.addProgressiveReadListener((v=>{this._onReceiveData({chunk:v})})),m.addProgressiveDoneListener((()=>{this._onProgressiveDone()})),m.transportReady()}_onReceiveData({begin:m,chunk:u}){let o=u instanceof Uint8Array&&u.byteLength===u.buffer.byteLength?u.buffer:new Uint8Array(u).buffer;if(m===void 0)this._fullRequestReader?this._fullRequestReader._enqueue(o):this._queuedChunks.push(o);else{let p=this._rangeReaders.some((function(w){return w._begin!==m?!1:(w._enqueue(o),!0)}));(0,i.assert)(p,"_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 o=new l(this,m,u);return this._pdfDataRangeTransport.requestDataRange(m,u),this._rangeReaders.push(o),o}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,o=!1,p=null){this._stream=m,this._done=o||!1,this._filename=(0,n.isPdfFile)(p)?p: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,o){this._stream=m,this._begin=u,this._end=o,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(a){if(!(typeof Worker<"u"&&a instanceof Worker)&&a!==null)throw new Error("Invalid `workerPort` type.");this.#t=a}static get workerSrc(){return this.#e}static set workerSrc(a){if(typeof a!="string")throw new Error("Invalid `workerSrc` type.");this.#e=a}}},284:(s,t,e)=>{e.d(t,{XfaLayer:()=>n});var i=e(50);class n{static setupStorage(c,l,d,m,u){let o=m.getValue(l,{value:null});switch(d.name){case"textarea":if(o.value!==null&&(c.textContent=o.value),u==="print")break;c.addEventListener("input",(p=>{m.setValue(l,{value:p.target.value})}));break;case"input":if(d.attributes.type==="radio"||d.attributes.type==="checkbox"){if(o.value===d.attributes.xfaOn?c.setAttribute("checked",!0):o.value===d.attributes.xfaOff&&c.removeAttribute("checked"),u==="print")break;c.addEventListener("change",(p=>{m.setValue(l,{value:p.target.checked?p.target.getAttribute("xfaOn"):p.target.getAttribute("xfaOff")})}))}else{if(o.value!==null&&c.setAttribute("value",o.value),u==="print")break;c.addEventListener("input",(p=>{m.setValue(l,{value:p.target.value})}))}break;case"select":if(o.value!==null){c.setAttribute("value",o.value);for(let p of d.children)p.attributes.value===o.value?p.attributes.selected=!0:p.attributes.hasOwnProperty("selected")&&delete p.attributes.selected}c.addEventListener("input",(p=>{let w=p.target.options,S=w.selectedIndex===-1?"":w[w.selectedIndex].value;m.setValue(l,{value:S})}))}}static setAttributes({html:c,element:l,storage:d=null,intent:m,linkService:u}){let{attributes:o}=l,p=c instanceof HTMLAnchorElement;o.type==="radio"&&(o.name=`${o.name}-${m}`);for(let[w,S]of Object.entries(o))if(S!=null)switch(w){case"class":S.length&&c.setAttribute(w,S.join(" "));break;case"dataId":break;case"id":c.setAttribute("data-element-id",S);break;case"style":Object.assign(c.style,S);break;case"textContent":c.textContent=S;break;default:(!p||w!=="href"&&w!=="newWindow")&&c.setAttribute(w,S)}p&&u.addLinkAttributes(c,o.href,o.newWindow),d&&o.dataId&&this.setupStorage(c,o.dataId,l,d)}static render(c){let l=c.annotationStorage,d=c.linkService,m=c.xfaHtml,u=c.intent||"display",o=document.createElement(m.name);m.attributes&&this.setAttributes({html:o,element:m,intent:u,linkService:d});let p=u!=="richText",w=c.div;if(w.append(o),c.viewport){let v=`matrix(${c.viewport.transform.join(",")})`;w.style.transform=v}p&&w.setAttribute("class","xfaLayer xfaFont");let S=[];if(m.children.length===0){if(m.value){let v=document.createTextNode(m.value);o.append(v),p&&i.XfaText.shouldBuildText(m.name)&&S.push(v)}return{textDivs:S}}let f=[[m,-1,o]];for(;f.length>0;){let[v,r,h]=f.at(-1);if(r+1===v.children.length){f.pop();continue}let b=v.children[++f.at(-1)[1]];if(b===null)continue;let{name:A}=b;if(A==="#text"){let _=document.createTextNode(b.value);S.push(_),h.append(_);continue}let D=b?.attributes?.xmlns?document.createElementNS(b.attributes.xmlns,A):document.createElement(A);if(h.append(D),b.attributes&&this.setAttributes({html:D,element:b,storage:l,intent:u,linkService:d}),b.children?.length>0)f.push([b,-1,D]);else if(b.value){let _=document.createTextNode(b.value);p&&i.XfaText.shouldBuildText(A)&&S.push(_),D.append(_)}}for(let v of w.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))v.setAttribute("readOnly",!0);return{textDivs:S}}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(a){let c=[],l={items:c,styles:Object.create(null)};return(function d(m){if(!m)return;let u=null,o=m.name;if(o==="#text")u=m.value;else{if(!i.shouldBuildText(o))return;m?.attributes?.textContent?u=m.attributes.textContent:m.value&&(u=m.value)}if(u!==null&&c.push({str:u}),m.children)for(let p of m.children)d(p)})(a),l}static shouldBuildText(a){return!(a==="textarea"||a==="input"||a==="option"||a==="select")}}},228:(s,t,e)=>{e.a(s,(async(i,n)=>{try{e.d(t,{AbortException:()=>a.AbortException,AnnotationEditorLayer:()=>m.AnnotationEditorLayer,AnnotationEditorParamsType:()=>a.AnnotationEditorParamsType,AnnotationEditorType:()=>a.AnnotationEditorType,AnnotationEditorUIManager:()=>u.AnnotationEditorUIManager,AnnotationLayer:()=>o.AnnotationLayer,AnnotationMode:()=>a.AnnotationMode,CMapCompressionType:()=>a.CMapCompressionType,ColorPicker:()=>p.ColorPicker,DOMSVGFactory:()=>l.DOMSVGFactory,DrawLayer:()=>w.DrawLayer,FeatureTest:()=>a.FeatureTest,GlobalWorkerOptions:()=>S.GlobalWorkerOptions,ImageKind:()=>a.ImageKind,InvalidPDFException:()=>a.InvalidPDFException,MissingPDFException:()=>a.MissingPDFException,OPS:()=>a.OPS,Outliner:()=>f.Outliner,PDFDataRangeTransport:()=>c.PDFDataRangeTransport,PDFDateString:()=>l.PDFDateString,PDFWorker:()=>c.PDFWorker,PasswordResponses:()=>a.PasswordResponses,PermissionFlag:()=>a.PermissionFlag,PixelsPerInch:()=>l.PixelsPerInch,RenderingCancelledException:()=>l.RenderingCancelledException,UnexpectedResponseException:()=>a.UnexpectedResponseException,Util:()=>a.Util,VerbosityLevel:()=>a.VerbosityLevel,XfaLayer:()=>v.XfaLayer,build:()=>c.build,createValidAbsoluteUrl:()=>a.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:()=>a.normalizeUnicode,renderTextLayer:()=>d.renderTextLayer,setLayerDimensions:()=>l.setLayerDimensions,shadow:()=>a.shadow,updateTextLayer:()=>d.updateTextLayer,version:()=>c.version});var a=e(292),c=e(831),l=e(419),d=e(814),m=e(731),u=e(830),o=e(976),p=e(259),w=e(47),S=e(164),f=e(61),v=e(284),r=i([c]);c=(r.then?(await r)():r)[0],n()}catch(h){n(h)}}))},178:(s,t,e)=>{e.d(t,{MessageHandler:()=>f});var i=e(292);let n=1,a=2,c=1,l=2,d=3,m=4,u=5,o=6,p=7,w=8;function S(v){switch(v instanceof Error||typeof v=="object"&&v!==null||(0,i.unreachable)('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),v.name){case"AbortException":return new i.AbortException(v.message);case"MissingPDFException":return new i.MissingPDFException(v.message);case"PasswordException":return new i.PasswordException(v.message,v.code);case"UnexpectedResponseException":return new i.UnexpectedResponseException(v.message,v.status);case"UnknownErrorException":return new i.UnknownErrorException(v.message,v.details);default:return new i.UnknownErrorException(v.message,v.toString())}}class f{constructor(r,h,b){this.sourceName=r,this.targetName=h,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=A=>{let D=A.data;if(D.targetName!==this.sourceName)return;if(D.stream){this.#e(D);return}if(D.callback){let I=D.callbackId,N=this.callbackCapabilities[I];if(!N)throw new Error(`Cannot resolve callback ${I}`);if(delete this.callbackCapabilities[I],D.callback===n)N.resolve(D.data);else{if(D.callback!==a)throw new Error("Unexpected callback case");N.reject(S(D.reason))}return}let _=this.actionHandler[D.action];if(!_)throw new Error(`Unknown action from worker: ${D.action}`);if(D.callbackId){let I=this.sourceName,N=D.sourceName;new Promise((function(H){H(_(D.data))})).then((function(H){b.postMessage({sourceName:I,targetName:N,callback:n,callbackId:D.callbackId,data:H})}),(function(H){b.postMessage({sourceName:I,targetName:N,callback:a,callbackId:D.callbackId,reason:S(H)})}))}else D.streamId?this.#t(D):_(D.data)},b.addEventListener("message",this._onComObjOnMessage)}on(r,h){let b=this.actionHandler;if(b[r])throw new Error(`There is already an actionName called "${r}"`);b[r]=h}send(r,h,b){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:r,data:h},b)}sendWithPromise(r,h,b){let A=this.callbackId++,D=Promise.withResolvers();this.callbackCapabilities[A]=D;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:r,callbackId:A,data:h},b)}catch(_){D.reject(_)}return D.promise}sendWithStream(r,h,b,A){let D=this.streamId++,_=this.sourceName,I=this.targetName,N=this.comObj;return new ReadableStream({start:H=>{let j=Promise.withResolvers();return this.streamControllers[D]={controller:H,startCall:j,pullCall:null,cancelCall:null,isClosed:!1},N.postMessage({sourceName:_,targetName:I,action:r,streamId:D,data:h,desiredSize:H.desiredSize},A),j.promise},pull:H=>{let j=Promise.withResolvers();return this.streamControllers[D].pullCall=j,N.postMessage({sourceName:_,targetName:I,stream:o,streamId:D,desiredSize:H.desiredSize}),j.promise},cancel:H=>{(0,i.assert)(H instanceof Error,"cancel must have a valid reason");let j=Promise.withResolvers();return this.streamControllers[D].cancelCall=j,this.streamControllers[D].isClosed=!0,N.postMessage({sourceName:_,targetName:I,stream:c,streamId:D,reason:S(H)}),j.promise}},b)}#t(r){let h=r.streamId,b=this.sourceName,A=r.sourceName,D=this.comObj,_=this,I=this.actionHandler[r.action],N={enqueue(H,j=1,K){if(this.isCancelled)return;let it=this.desiredSize;this.desiredSize-=j,it>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),D.postMessage({sourceName:b,targetName:A,stream:m,streamId:h,chunk:H},K)},close(){this.isCancelled||(this.isCancelled=!0,D.postMessage({sourceName:b,targetName:A,stream:d,streamId:h}),delete _.streamSinks[h])},error(H){(0,i.assert)(H instanceof Error,"error must have a valid reason"),this.isCancelled||(this.isCancelled=!0,D.postMessage({sourceName:b,targetName:A,stream:u,streamId:h,reason:S(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[h]=N,new Promise((function(H){H(I(r.data,N))})).then((function(){D.postMessage({sourceName:b,targetName:A,stream:w,streamId:h,success:!0})}),(function(H){D.postMessage({sourceName:b,targetName:A,stream:w,streamId:h,reason:S(H)})}))}#e(r){let h=r.streamId,b=this.sourceName,A=r.sourceName,D=this.comObj,_=this.streamControllers[h],I=this.streamSinks[h];switch(r.stream){case w:r.success?_.startCall.resolve():_.startCall.reject(S(r.reason));break;case p:r.success?_.pullCall.resolve():_.pullCall.reject(S(r.reason));break;case o:if(!I){D.postMessage({sourceName:b,targetName:A,stream:p,streamId:h,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(){D.postMessage({sourceName:b,targetName:A,stream:p,streamId:h,success:!0})}),(function(N){D.postMessage({sourceName:b,targetName:A,stream:p,streamId:h,reason:S(N)})}));break;case m:if((0,i.assert)(_,"enqueue should have stream controller"),_.isClosed)break;_.controller.enqueue(r.chunk);break;case d:if((0,i.assert)(_,"close should have stream controller"),_.isClosed)break;_.isClosed=!0,_.controller.close(),this.#i(_,h);break;case u:(0,i.assert)(_,"error should have stream controller"),_.controller.error(S(r.reason)),this.#i(_,h);break;case l:r.success?_.cancelCall.resolve():_.cancelCall.reject(S(r.reason)),this.#i(_,h);break;case c:if(!I)break;new Promise((function(N){N(I.onCancel?.(S(r.reason)))})).then((function(){D.postMessage({sourceName:b,targetName:A,stream:l,streamId:h,success:!0})}),(function(N){D.postMessage({sourceName:b,targetName:A,stream:l,streamId:h,reason:S(N)})})),I.sinkCapability.reject(S(r.reason)),I.isCancelled=!0,delete this.streamSinks[h];break;default:throw new Error("Unexpected stream case")}}async#i(r,h){await Promise.allSettled([r.startCall?.promise,r.pullCall?.promise,r.cancelCall?.promise]),delete this.streamControllers[h]}destroy(){this.comObj.removeEventListener("message",this._onComObjOnMessage)}}},651:(s,t,e)=>{e.d(t,{MurmurHash3_64:()=>c});let i=3285377520,n=4294901760,a=65535;class c{constructor(d){this.h1=d?4294967295&d:i,this.h2=d?4294967295&d:i}update(d){let m,u;if(typeof d=="string"){m=new Uint8Array(2*d.length),u=0;for(let _=0,I=d.length;_<I;_++){let N=d.charCodeAt(_);N<=255?m[u++]=N:(m[u++]=N>>>8,m[u++]=255&N)}}else{if(!ArrayBuffer.isView(d))throw new Error("Invalid data format, must be a string or TypedArray.");m=d.slice(),u=m.byteLength}let o=u>>2,p=u-4*o,w=new Uint32Array(m.buffer,0,o),S=0,f=0,v=this.h1,r=this.h2,h=3432918353,b=461845907,A=11601,D=13715;for(let _=0;_<o;_++)1&_?(S=w[_],S=S*h&n|S*A&a,S=S<<15|S>>>17,S=S*b&n|S*D&a,v^=S,v=v<<13|v>>>19,v=5*v+3864292196):(f=w[_],f=f*h&n|f*A&a,f=f<<15|f>>>17,f=f*b&n|f*D&a,r^=f,r=r<<13|r>>>19,r=5*r+3864292196);switch(S=0,p){case 3:S^=m[4*o+2]<<16;case 2:S^=m[4*o+1]<<8;case 1:S^=m[4*o],S=S*h&n|S*A&a,S=S<<15|S>>>17,S=S*b&n|S*D&a,1&o?v^=S:r^=S}this.h1=v,this.h2=r}hexdigest(){let d=this.h1,m=this.h2;return d^=m>>>1,d=3981806797*d&n|36045*d&a,m=4283543511*m&n|(2950163797*(m<<16|d>>>16)&n)>>>16,d^=m>>>1,d=444984403*d&n|60499*d&a,m=3301882366*m&n|(3120437893*(m<<16|d>>>16)&n)>>>16,d^=m>>>1,(d>>>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:()=>p,AnnotationEditorPrefix:()=>u,AnnotationEditorType:()=>o,AnnotationMode:()=>m,AnnotationPrefix:()=>$,AnnotationType:()=>v,BaseException:()=>z,CMapCompressionType:()=>b,FONT_IDENTITY_MATRIX:()=>a,FeatureTest:()=>y,FormatError:()=>st,IDENTITY_MATRIX:()=>n,ImageKind:()=>f,InvalidPDFException:()=>et,LINE_FACTOR:()=>l,MAX_IMAGE_SIZE_TO_CACHE:()=>c,MissingPDFException:()=>rt,OPS:()=>A,PasswordException:()=>W,PasswordResponses:()=>D,PermissionFlag:()=>w,RenderingIntentFlag:()=>d,TextRenderingMode:()=>S,UnexpectedResponseException:()=>ct,UnknownErrorException:()=>Y,Util:()=>k,VerbosityLevel:()=>h,assert:()=>it,bytesToString:()=>x,createValidAbsoluteUrl:()=>ot,getUuid:()=>L,getVerbosityLevel:()=>N,info:()=>H,isNodeJS:()=>i,normalizeUnicode:()=>E,objectFromMap:()=>g,setVerbosityLevel:()=>I,shadow:()=>X,string32:()=>R,stringToBytes:()=>T,unreachable:()=>K,warn:()=>j});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],a=[.001,0,0,.001,0,0],c=1e7,l=1.35,d={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_",o={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},p={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35},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},S={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},f={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},v={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},h={ERRORS:0,WARNINGS:1,INFOS:5},b={NONE:0,BINARY:1},A={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},D={NEED_PASSWORD:1,INCORRECT_PASSWORD:2},_=h.WARNINGS;function I(U){Number.isInteger(U)&&(_=U)}function N(){return _}function H(U){_>=h.INFOS&&console.log(`Info: ${U}`)}function j(U){_>=h.WARNINGS&&console.log(`Warning: ${U}`)}function K(U){throw new Error(U)}function it(U,P){U||K(P)}function ot(U,P=null,F=null){if(!U)return null;try{if(F&&typeof U=="string"&&(F.addDefaultProtocol&&U.startsWith("www.")&&U.match(/\./g)?.length>=2&&(U=`http://${U}`),F.tryConvertEncoding))try{U=(function(Z){return decodeURIComponent(escape(Z))})(U)}catch{}let V=P?new URL(U,P):new URL(U);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(U,P,F,V=!1){return Object.defineProperty(U,P,{value:F,enumerable:!V,configurable:!0,writable:!1}),F}let z=(function(){function P(F,V){this.constructor===P&&K("Cannot initialize BaseException."),this.message=F,this.name=V}return P.prototype=new Error,P.constructor=P,P})();class W extends z{constructor(P,F){super(P,"PasswordException"),this.code=F}}class Y extends z{constructor(P,F){super(P,"UnknownErrorException"),this.details=F}}class et extends z{constructor(P){super(P,"InvalidPDFException")}}class rt extends z{constructor(P){super(P,"MissingPDFException")}}class ct extends z{constructor(P,F){super(P,"UnexpectedResponseException"),this.status=F}}class st extends z{constructor(P){super(P,"FormatError")}}class G extends z{constructor(P){super(P,"AbortException")}}function x(U){typeof U=="object"&&U?.length!==void 0||K("Invalid argument for bytesToString");let P=U.length,F=8192;if(P<F)return String.fromCharCode.apply(null,U);let V=[];for(let Q=0;Q<P;Q+=F){let Z=Math.min(Q+F,P),tt=U.subarray(Q,Z);V.push(String.fromCharCode.apply(null,tt))}return V.join("")}function T(U){typeof U!="string"&&K("Invalid argument for stringToBytes");let P=U.length,F=new Uint8Array(P);for(let V=0;V<P;++V)F[V]=255&U.charCodeAt(V);return F}function R(U){return String.fromCharCode(U>>24&255,U>>16&255,U>>8&255,255&U)}function g(U){let P=Object.create(null);for(let[F,V]of U)P[F]=V;return P}class y{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 C=Array.from(Array(256).keys(),(U=>U.toString(16).padStart(2,"0")));class k{static makeHexColor(P,F,V){return`#${C[P]}${C[F]}${C[V]}`}static scaleMinMax(P,F){let V;P[0]?(P[0]<0&&(V=F[0],F[0]=F[2],F[2]=V),F[0]*=P[0],F[2]*=P[0],P[3]<0&&(V=F[1],F[1]=F[3],F[3]=V),F[1]*=P[3],F[3]*=P[3]):(V=F[0],F[0]=F[1],F[1]=V,V=F[2],F[2]=F[3],F[3]=V,P[1]<0&&(V=F[1],F[1]=F[3],F[3]=V),F[1]*=P[1],F[3]*=P[1],P[2]<0&&(V=F[0],F[0]=F[2],F[2]=V),F[0]*=P[2],F[2]*=P[2]),F[0]+=P[4],F[1]+=P[5],F[2]+=P[4],F[3]+=P[5]}static transform(P,F){return[P[0]*F[0]+P[2]*F[1],P[1]*F[0]+P[3]*F[1],P[0]*F[2]+P[2]*F[3],P[1]*F[2]+P[3]*F[3],P[0]*F[4]+P[2]*F[5]+P[4],P[1]*F[4]+P[3]*F[5]+P[5]]}static applyTransform(P,F){return[P[0]*F[0]+P[1]*F[2]+F[4],P[0]*F[1]+P[1]*F[3]+F[5]]}static applyInverseTransform(P,F){let V=F[0]*F[3]-F[1]*F[2];return[(P[0]*F[3]-P[1]*F[2]+F[2]*F[5]-F[4]*F[3])/V,(-P[0]*F[1]+P[1]*F[0]+F[4]*F[1]-F[5]*F[0])/V]}static getAxialAlignedBoundingBox(P,F){let V=this.applyTransform(P,F),Q=this.applyTransform(P.slice(2,4),F),Z=this.applyTransform([P[0],P[3]],F),tt=this.applyTransform([P[2],P[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(P){let F=P[0]*P[3]-P[1]*P[2];return[P[3]/F,-P[1]/F,-P[2]/F,P[0]/F,(P[2]*P[5]-P[4]*P[3])/F,(P[4]*P[1]-P[5]*P[0])/F]}static singularValueDecompose2dScale(P){let F=[P[0],P[2],P[1],P[3]],V=P[0]*F[0]+P[1]*F[2],Q=P[0]*F[1]+P[1]*F[3],Z=P[2]*F[0]+P[3]*F[2],tt=P[2]*F[1]+P[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(P){let F=P.slice(0);return P[0]>P[2]&&(F[0]=P[2],F[2]=P[0]),P[1]>P[3]&&(F[1]=P[3],F[3]=P[1]),F}static intersect(P,F){let V=Math.max(Math.min(P[0],P[2]),Math.min(F[0],F[2])),Q=Math.min(Math.max(P[0],P[2]),Math.max(F[0],F[2]));if(V>Q)return null;let Z=Math.max(Math.min(P[1],P[3]),Math.min(F[1],F[3])),tt=Math.min(Math.max(P[1],P[3]),Math.max(F[1],F[3]));return Z>tt?null:[V,Z,Q,tt]}static#t(P,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,Dt=wt*(wt*(wt*P+3*dt*F)+3*Tt*V)+xt*Q,Rt=wt*(wt*(wt*Z+3*dt*tt)+3*Tt*nt)+xt*pt;lt[0]=Math.min(lt[0],Dt),lt[1]=Math.min(lt[1],Rt),lt[2]=Math.max(lt[2],Dt),lt[3]=Math.max(lt[3],Rt)}static#e(P,F,V,Q,Z,tt,nt,pt,dt,lt,wt,Tt){if(Math.abs(dt)<1e-12){Math.abs(lt)>=1e-12&&this.#t(P,F,V,Q,Z,tt,nt,pt,-wt/lt,Tt);return}let xt=lt**2-4*wt*dt;if(xt<0)return;let Dt=Math.sqrt(xt),Rt=2*dt;this.#t(P,F,V,Q,Z,tt,nt,pt,(-lt+Dt)/Rt,Tt),this.#t(P,F,V,Q,Z,tt,nt,pt,(-lt-Dt)/Rt,Tt)}static bezierBoundingBox(P,F,V,Q,Z,tt,nt,pt,dt){return dt?(dt[0]=Math.min(dt[0],P,nt),dt[1]=Math.min(dt[1],F,pt),dt[2]=Math.max(dt[2],P,nt),dt[3]=Math.max(dt[3],F,pt)):dt=[Math.min(P,nt),Math.min(F,pt),Math.max(P,nt),Math.max(F,pt)],this.#e(P,V,Z,nt,F,Q,tt,pt,3*(3*(V-Z)-P+nt),6*(P-2*V+Z),3*(V-P),dt),this.#e(P,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 E(U){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"]])),U.replaceAll(O,((P,F,V)=>F?F.normalize("NFKC"):M.get(V)))}function L(){if(typeof crypto<"u"&&typeof crypto?.randomUUID=="function")return crypto.randomUUID();let U=new Uint8Array(32);if(typeof crypto<"u"&&typeof crypto?.getRandomValues=="function")crypto.getRandomValues(U);else for(let P=0;P<32;P++)U[P]=Math.floor(255*Math.random());return x(U)}let $="pdfjs_internal_id_"}},qc={};function Xi(s){var t=qc[s];if(t!==void 0)return t.exports;var e=qc[s]={exports:{}};return yu[s](e,e.exports,Xi),e.exports}Ds=typeof Symbol=="function"?Symbol("webpack queues"):"__webpack_queues__",yn=typeof Symbol=="function"?Symbol("webpack exports"):"__webpack_exports__",vn=typeof Symbol=="function"?Symbol("webpack error"):"__webpack_error__",Hr=s=>{s&&s.d<1&&(s.d=1,s.forEach((t=>t.r--)),s.forEach((t=>t.r--?t.r++:t())))},Xi.a=(s,t,e)=>{var i;e&&((i=[]).d=-1);var n,a,c,l=new Set,d=s.exports,m=new Promise(((u,o)=>{c=o,a=u}));m[yn]=d,m[Ds]=u=>(i&&u(i),l.forEach(u),m.catch((o=>{}))),s.exports=m,t((u=>{n=(S=>S.map((f=>{if(f!==null&&typeof f=="object"){if(f[Ds])return f;if(f.then){var v=[];v.d=0,f.then((b=>{r[yn]=b,Hr(v)}),(b=>{r[vn]=b,Hr(v)}));var r={};return r[Ds]=b=>b(v),r}}var h={};return h[Ds]=b=>{},h[yn]=f,h})))(u);var o,p=()=>n.map((S=>{if(S[vn])throw S[vn];return S[yn]})),w=new Promise((S=>{(o=()=>S(p)).r=0;var f=v=>v!==i&&!l.has(v)&&(l.add(v),v&&!v.d&&(o.r++,v.push(o)));n.map((v=>v[Ds](f)))}));return o.r?w:p()}),(u=>(u?c(m[vn]=u):a(d),Hr(i)))),i&&i.d<0&&(i.d=0)};Xi.d=(s,t)=>{for(var e in t)Xi.o(t,e)&&!Xi.o(s,e)&&Object.defineProperty(s,e,{enumerable:!0,get:t[e]})};Xi.o=(s,t)=>Object.prototype.hasOwnProperty.call(s,t);var Ct=Xi(228),Ef=(Ct=globalThis.pdfjsLib=await(globalThis.pdfjsLibPromise=Ct)).AbortException,_f=Ct.AnnotationEditorLayer,Cf=Ct.AnnotationEditorParamsType,kf=Ct.AnnotationEditorType,Tf=Ct.AnnotationEditorUIManager,Pf=Ct.AnnotationLayer,Df=Ct.AnnotationMode,Mf=Ct.CMapCompressionType,Rf=Ct.ColorPicker,If=Ct.DOMSVGFactory,Lf=Ct.DrawLayer,Ff=Ct.FeatureTest,Xc=Ct.GlobalWorkerOptions,Of=Ct.ImageKind,Nf=Ct.InvalidPDFException,Bf=Ct.MissingPDFException,Uf=Ct.OPS,$f=Ct.Outliner,Hf=Ct.PDFDataRangeTransport,jf=Ct.PDFDateString,zf=Ct.PDFWorker,Vf=Ct.PasswordResponses,Wf=Ct.PermissionFlag,Gf=Ct.PixelsPerInch,qf=Ct.RenderingCancelledException,Xf=Ct.UnexpectedResponseException,Kf=Ct.Util,Yf=Ct.VerbosityLevel,Jf=Ct.XfaLayer,Qf=Ct.build,Zf=Ct.createValidAbsoluteUrl,tg=Ct.fetchData,Kc=Ct.getDocument,eg=Ct.getFilenameFromUrl,ig=Ct.getPdfFilenameFromUrl,sg=Ct.getXfaPageViewport,ng=Ct.isDataScheme,rg=Ct.isPdfFile,ag=Ct.noContextMenu,og=Ct.normalizeUnicode,lg=Ct.renderTextLayer,cg=Ct.setLayerDimensions,hg=Ct.shadow,dg=Ct.updateTextLayer,ug=Ct.version;Xc.workerSrc=Xa("js/lib/pdf.worker.min.mjs");async function Yc(s,t=2){let e=await Kc({data:s}).promise,i=[];for(let n=1;n<=e.numPages;n++){let a=await e.getPage(n),c=a.getViewport({scale:t}),l=document.createElement("canvas"),d=l.getContext("2d");l.width=c.width,l.height=c.height,await a.render({canvasContext:d,viewport:c}).promise,i.push(l.toDataURL("image/jpeg",.82))}return i}var Zc=null,Jc={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 Ms(s){Zc=s||null}function Rs(){return Zc||(typeof document<"u"?document.body:null)}function wu(){let t=customElements.get("sl-alert")?.toastStack;t&&t.querySelectorAll("sl-alert").forEach(i=>{typeof i.hide=="function"&&i.hide()})}async function Qc(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(o=>setTimeout(o,200))]),typeof customElements>"u"||!customElements.get("sl-alert"))return null;let i=customElements.get("sl-alert"),n=e.variant||"info",a=Jc[n]||Jc.info,c=e.container||Rs();if(i?.toastStack&&c){let o=i.toastStack;o.parentElement!==c&&c.appendChild(o),c!==document.body?(o.style.position="absolute",o.style.width="auto",o.style.maxWidth="calc(100% - 24px)",o.style.left="12px",o.style.right="12px",o.style.insetInlineStart="12px",o.style.insetInlineEnd="12px",e.position==="top"?(o.style.top="12px",o.style.bottom="auto"):(o.style.top="auto",o.style.bottom="16px"),o.style.maxHeight="100%",o.style.overflow="auto"):(o.style.position="",o.style.width="",o.style.left="",o.style.right="",o.style.top="",o.style.bottom="",o.style.insetInlineStart="",o.style.insetInlineEnd="",o.style.maxHeight="",o.style.maxWidth="",o.style.overflow="")}let l=document.createElement("sl-alert");l.variant=a.slVariant,l.closable=e.closable!==!1,l.duration=e.duration!==void 0?e.duration:a.defaultDuration;let d=e.icon!==void 0?e.icon:a.defaultIcon;if(d){let o=document.createElement("sl-icon");o.slot="icon",o.name=d,l.appendChild(o)}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 o=document.createElement("div");o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="space-between",o.style.gap="0.75rem",o.style.width="100%",m.style.flex="1",o.appendChild(m);let p=document.createElement("sl-button");p.size="small",p.variant=e.action.variant||"text",p.textContent=e.action.text||"Action",p.style.color="inherit",p.style.fontWeight="600",p.style.padding="0",p.addEventListener("click",w=>{w.preventDefault(),w.stopPropagation(),typeof e.action.onClick=="function"&&e.action.onClick(w,l),e.action.autoClose!==!1&&l.hide()}),o.appendChild(p),l.appendChild(o)}else l.appendChild(m);let u=l.toast();return l.toastPromise=u,l}function xu(s,t={}){return Ae.show({message:s,variant:"success",...t})}function Au(s,t={}){return Ae.show({message:s,variant:"error",...t})}function Su(s,t={}){return Ae.show({message:s,variant:"warning",...t})}function Eu(s,t={}){return Ae.show({message:s,variant:"info",...t})}function _u(s,t,e={}){return Ae.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 Cu(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(f=>setTimeout(f,200))]),typeof customElements>"u"||!customElements.get("sl-alert"))return{alert:null,progressBar:null,update(){},close(){}};let i=e.container||Rs(),n=document.createElement("sl-alert");n.variant=e.variant||"primary",n.closable=e.closable===!0,n.duration=1/0;let a=e.icon!==void 0?e.icon:"arrow-down-circle";if(a){let f=document.createElement("sl-icon");f.slot="icon",f.name=a,n.appendChild(f)}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 d=document.createElement("span");d.className="notify-progress-message",d.style.fontWeight="500",d.style.fontSize="0.9rem",d.textContent=e.message||"Processing...",l.appendChild(d);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,o=e.total!==void 0?e.total:0;o>0?m.textContent=`${u} / ${o}`:e.value!==void 0&&(m.textContent=`${e.value}%`),l.appendChild(m),c.appendChild(l);let p=document.createElement("sl-progress-bar");o>0?p.value=Math.round(u/o*100):e.value!==void 0?p.value=e.value:p.indeterminate=!0,c.appendChild(p),n.appendChild(c);let w=customElements.get("sl-alert");if(w?.toastStack&&i){let f=w.toastStack;f.parentElement!==i&&i.appendChild(f)}return n.toast(),{alert:n,progressBar:p,update({done:f,total:v,value:r,message:h}={}){if(h!==void 0&&(d.textContent=h),v!==void 0&&f!==void 0){p.indeterminate=!1;let b=Math.min(100,Math.max(0,Math.round(f/Math.max(v,1)*100)));p.value=b,m.textContent=`${f} / ${v}`}else r!==void 0&&(p.indeterminate=!1,p.value=Math.min(100,Math.max(0,r)),m.textContent=`${Math.round(p.value)}%`)},close(){typeof n.hide=="function"&&n.hide()}}}var Ae=Object.assign(function(s,t){return Qc(s,t)},{show:Qc,success:xu,error:Au,warning:Su,info:Eu,undo:_u,progress:Cu,clear:wu,setContainer:Ms,getContainer:Rs});var th=`
|
|
15
|
-
.cropper-container {
|
|
16
|
-
direction: ltr;
|
|
17
|
-
font-size: 0;
|
|
18
|
-
line-height: 0;
|
|
19
|
-
position: relative;
|
|
20
|
-
-ms-touch-action: none;
|
|
21
|
-
touch-action: none;
|
|
22
|
-
-webkit-user-select: none;
|
|
23
|
-
-moz-user-select: none;
|
|
24
|
-
-ms-user-select: none;
|
|
25
|
-
user-select: none;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
.cropper-container img {
|
|
29
|
-
display: block;
|
|
30
|
-
height: 100%;
|
|
31
|
-
image-orientation: 0deg;
|
|
32
|
-
max-height: none !important;
|
|
33
|
-
max-width: none !important;
|
|
34
|
-
min-height: 0 !important;
|
|
35
|
-
min-width: 0 !important;
|
|
36
|
-
width: 100%;
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
.cropper-wrap-box,
|
|
40
|
-
.cropper-canvas,
|
|
41
|
-
.cropper-drag-box,
|
|
42
|
-
.cropper-crop-box,
|
|
43
|
-
.cropper-modal {
|
|
44
|
-
bottom: 0;
|
|
45
|
-
left: 0;
|
|
46
|
-
position: absolute;
|
|
47
|
-
right: 0;
|
|
48
|
-
top: 0;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
.cropper-wrap-box,
|
|
52
|
-
.cropper-canvas {
|
|
53
|
-
overflow: hidden;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
.cropper-drag-box {
|
|
57
|
-
background-color: #fff;
|
|
58
|
-
opacity: 0;
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
.cropper-modal {
|
|
62
|
-
background-color: #000;
|
|
63
|
-
opacity: 0.5;
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
.cropper-view-box {
|
|
67
|
-
display: block;
|
|
68
|
-
height: 100%;
|
|
69
|
-
outline-color: rgba(51, 153, 255, 0.75);
|
|
70
|
-
outline: 1px solid #39f;
|
|
71
|
-
overflow: hidden;
|
|
72
|
-
width: 100%;
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
.cropper-dashed {
|
|
76
|
-
border: 0 dashed #eee;
|
|
77
|
-
display: block;
|
|
78
|
-
opacity: 0.5;
|
|
79
|
-
position: absolute;
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
.cropper-dashed.dashed-h {
|
|
83
|
-
border-bottom-width: 1px;
|
|
84
|
-
border-top-width: 1px;
|
|
85
|
-
height: 33.33333%;
|
|
86
|
-
left: 0;
|
|
87
|
-
top: 33.33333%;
|
|
88
|
-
width: 100%;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
.cropper-dashed.dashed-v {
|
|
92
|
-
border-left-width: 1px;
|
|
93
|
-
border-right-width: 1px;
|
|
94
|
-
height: 100%;
|
|
95
|
-
left: 33.33333%;
|
|
96
|
-
top: 0;
|
|
97
|
-
width: 33.33333%;
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
.cropper-center {
|
|
101
|
-
display: block;
|
|
102
|
-
height: 0;
|
|
103
|
-
left: 50%;
|
|
104
|
-
opacity: 0.75;
|
|
105
|
-
position: absolute;
|
|
106
|
-
top: 50%;
|
|
107
|
-
width: 0;
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
.cropper-center:before,
|
|
111
|
-
.cropper-center:after {
|
|
112
|
-
background-color: #eee;
|
|
113
|
-
content: ' ';
|
|
114
|
-
display: block;
|
|
115
|
-
position: absolute;
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
.cropper-center:before {
|
|
119
|
-
height: 1px;
|
|
120
|
-
left: -3px;
|
|
121
|
-
top: 0;
|
|
122
|
-
width: 7px;
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
.cropper-center:after {
|
|
126
|
-
height: 7px;
|
|
127
|
-
left: 0;
|
|
128
|
-
top: -3px;
|
|
129
|
-
width: 1px;
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
.cropper-face,
|
|
133
|
-
.cropper-line,
|
|
134
|
-
.cropper-point {
|
|
135
|
-
display: block;
|
|
136
|
-
height: 100%;
|
|
137
|
-
opacity: 0.1;
|
|
138
|
-
position: absolute;
|
|
139
|
-
width: 100%;
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
.cropper-face {
|
|
143
|
-
background-color: #fff;
|
|
144
|
-
left: 0;
|
|
145
|
-
top: 0;
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
.cropper-line {
|
|
149
|
-
background-color: #39f;
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
.cropper-line.line-e {
|
|
153
|
-
cursor: ew-resize;
|
|
154
|
-
right: -3px;
|
|
155
|
-
top: 0;
|
|
156
|
-
width: 5px;
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
.cropper-line.line-n {
|
|
160
|
-
cursor: ns-resize;
|
|
161
|
-
height: 5px;
|
|
162
|
-
left: 0;
|
|
163
|
-
top: -3px;
|
|
164
|
-
}
|
|
165
|
-
|
|
166
|
-
.cropper-line.line-w {
|
|
167
|
-
cursor: ew-resize;
|
|
168
|
-
left: -3px;
|
|
169
|
-
top: 0;
|
|
170
|
-
width: 5px;
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
.cropper-line.line-s {
|
|
174
|
-
bottom: -3px;
|
|
175
|
-
cursor: ns-resize;
|
|
176
|
-
height: 5px;
|
|
177
|
-
left: 0;
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
.cropper-point {
|
|
181
|
-
width: var(--copio-crop-handle-hit, 48px);
|
|
182
|
-
height: var(--copio-crop-handle-hit, 48px);
|
|
183
|
-
min-width: 44px;
|
|
184
|
-
min-height: 44px;
|
|
185
|
-
background-color: transparent;
|
|
186
|
-
opacity: 1;
|
|
187
|
-
display: flex;
|
|
188
|
-
align-items: center;
|
|
189
|
-
justify-content: center;
|
|
190
|
-
box-sizing: border-box;
|
|
191
|
-
touch-action: none;
|
|
192
|
-
z-index: 10;
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
.cropper-point::after {
|
|
196
|
-
content: '';
|
|
197
|
-
display: block;
|
|
198
|
-
width: var(--copio-crop-handle-visual, 16px);
|
|
199
|
-
height: var(--copio-crop-handle-visual, 16px);
|
|
200
|
-
border-radius: 50%;
|
|
201
|
-
background-color: var(--copio-color-primary, #38bdf8);
|
|
202
|
-
border: 2.5px solid #ffffff;
|
|
203
|
-
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.5);
|
|
204
|
-
transition: transform 120ms ease;
|
|
205
|
-
box-sizing: border-box;
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
.cropper-point:hover::after,
|
|
209
|
-
.cropper-point:active::after {
|
|
210
|
-
transform: scale(1.25);
|
|
211
|
-
background-color: var(--copio-color-success, #22c55e);
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
.cropper-point.point-e {
|
|
215
|
-
cursor: ew-resize;
|
|
216
|
-
margin-top: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
217
|
-
right: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
218
|
-
top: 50%;
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
.cropper-point.point-n {
|
|
222
|
-
cursor: ns-resize;
|
|
223
|
-
left: 50%;
|
|
224
|
-
margin-left: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
225
|
-
top: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
.cropper-point.point-w {
|
|
229
|
-
cursor: ew-resize;
|
|
230
|
-
left: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
231
|
-
margin-top: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
232
|
-
top: 50%;
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
.cropper-point.point-s {
|
|
236
|
-
bottom: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
237
|
-
cursor: s-resize;
|
|
238
|
-
left: 50%;
|
|
239
|
-
margin-left: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
.cropper-point.point-ne {
|
|
243
|
-
cursor: nesw-resize;
|
|
244
|
-
right: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
245
|
-
top: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
.cropper-point.point-nw {
|
|
249
|
-
cursor: nwse-resize;
|
|
250
|
-
left: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
251
|
-
top: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
.cropper-point.point-sw {
|
|
255
|
-
bottom: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
256
|
-
cursor: nesw-resize;
|
|
257
|
-
left: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
.cropper-point.point-se {
|
|
261
|
-
bottom: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
262
|
-
cursor: nwse-resize;
|
|
263
|
-
right: calc(-1 * var(--copio-crop-handle-hit, 48px) / 2);
|
|
264
|
-
}
|
|
265
|
-
|
|
266
|
-
.cropper-invisible {
|
|
267
|
-
opacity: 0;
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
.cropper-bg {
|
|
271
|
-
background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAQMAAAAlPW0iAAAAA3NCSVQICAjb4U/gAAAABlBMVEXMzMz////TjRV2AAAACXBIWXMAAArrAAAK6wGCiw1aAAAAHHRFWHRTb2Z0d2FyZQBBZG9iZSBGaXJld29ya3MgQ1M26LyyjAAAABFJREFUCJlj+M/AgBVhF/0PAH6/D/HkDxOGAAAAAElFTkSuQmCC');
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
.cropper-hide {
|
|
275
|
-
display: block;
|
|
276
|
-
height: 0;
|
|
277
|
-
position: absolute;
|
|
278
|
-
width: 0;
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
.cropper-hidden {
|
|
282
|
-
display: none !important;
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
.cropper-move {
|
|
286
|
-
cursor: move;
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
.cropper-crop {
|
|
290
|
-
cursor: crosshair;
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
.cropper-disabled .cropper-drag-box,
|
|
294
|
-
.cropper-disabled .cropper-face,
|
|
295
|
-
.cropper-disabled .cropper-line,
|
|
296
|
-
.cropper-disabled .cropper-point {
|
|
297
|
-
cursor: not-allowed;
|
|
298
|
-
}
|
|
299
|
-
`;var jr=class extends HTMLElement{#t=[];#e=null;#i=null;#n=null;#r=!1;#s=null;#o=new Set;#l=null;#a=!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.#o.add(t),t}#d(t){if(this.#o.has(t)){try{URL.revokeObjectURL(t)}catch{}this.#o.delete(t)}}#c(){for(let t of this.#o)try{URL.revokeObjectURL(t)}catch{}this.#o.clear()}#f(){let t=`
|
|
300
|
-
<style>
|
|
301
|
-
${th}
|
|
302
|
-
</style>
|
|
303
|
-
<style>
|
|
304
|
-
.container {
|
|
305
|
-
display: grid;
|
|
306
|
-
grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
|
|
307
|
-
gap: 0.75rem;
|
|
308
|
-
max-width: 100%;
|
|
309
|
-
min-height: 140px;
|
|
310
|
-
padding: 0.5rem;
|
|
311
|
-
border-radius: 8px;
|
|
312
|
-
border: 2px dashed transparent;
|
|
313
|
-
box-sizing: border-box;
|
|
314
|
-
transition: border-color 0.2s, background-color 0.2s;
|
|
315
|
-
}
|
|
316
|
-
.container.drag-over {
|
|
317
|
-
border-color: #3b82f6;
|
|
318
|
-
background-color: rgba(59, 130, 246, 0.08);
|
|
319
|
-
box-shadow: inset 0 0 0 1px rgba(59, 130, 246, 0.2);
|
|
320
|
-
}
|
|
321
|
-
@container copio-scanner (max-width: 400px) {
|
|
322
|
-
.container {
|
|
323
|
-
grid-template-columns: repeat(2, 1fr);
|
|
324
|
-
gap: 0.5rem;
|
|
325
|
-
padding: 0.25rem;
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
@container copio-scanner (min-width: 401px) and (max-width: 767px) {
|
|
329
|
-
.container {
|
|
330
|
-
grid-template-columns: repeat(3, 1fr);
|
|
331
|
-
gap: 0.75rem;
|
|
332
|
-
}
|
|
333
|
-
}
|
|
334
|
-
@container copio-scanner (min-width: 768px) {
|
|
335
|
-
.container {
|
|
336
|
-
grid-template-columns: repeat(4, 1fr);
|
|
337
|
-
gap: 1rem;
|
|
338
|
-
}
|
|
339
|
-
}
|
|
340
|
-
/* Fallbacks if container queries are unsupported or outside named container */
|
|
341
|
-
@supports not (container-type: size) {
|
|
342
|
-
@media (min-width: 640px) {
|
|
343
|
-
.container {
|
|
344
|
-
grid-template-columns: repeat(3, 1fr);
|
|
345
|
-
}
|
|
346
|
-
}
|
|
347
|
-
@media (min-width: 1024px) {
|
|
348
|
-
.container {
|
|
349
|
-
grid-template-columns: repeat(4, 1fr);
|
|
350
|
-
}
|
|
351
|
-
}
|
|
352
|
-
}
|
|
353
|
-
.image-wrapper {
|
|
354
|
-
cursor: grab;
|
|
355
|
-
position: relative;
|
|
356
|
-
user-select: none;
|
|
357
|
-
-webkit-user-select: none;
|
|
358
|
-
width: 100%;
|
|
359
|
-
aspect-ratio: 1;
|
|
360
|
-
}
|
|
361
|
-
.image-wrapper:active {
|
|
362
|
-
cursor: grabbing;
|
|
363
|
-
}
|
|
364
|
-
.image-wrapper.dragging {
|
|
365
|
-
opacity: 0.4;
|
|
366
|
-
cursor: grabbing;
|
|
367
|
-
}
|
|
368
|
-
.image-wrapper.sortable-ghost {
|
|
369
|
-
opacity: 0.2;
|
|
370
|
-
}
|
|
371
|
-
.image-menu {
|
|
372
|
-
position: absolute;
|
|
373
|
-
top: 4px;
|
|
374
|
-
right: 4px;
|
|
375
|
-
}
|
|
376
|
-
img {
|
|
377
|
-
width: 100%;
|
|
378
|
-
height: 100%;
|
|
379
|
-
object-fit: cover;
|
|
380
|
-
border: 1px solid #ccc;
|
|
381
|
-
border-radius: 4px;
|
|
382
|
-
display: block;
|
|
383
|
-
}
|
|
384
|
-
#crop-image {
|
|
385
|
-
max-width: 100%;
|
|
386
|
-
max-height: 100%;
|
|
387
|
-
display: block;
|
|
388
|
-
}
|
|
389
|
-
.crop-wrapper {
|
|
390
|
-
width: 100%;
|
|
391
|
-
height: 360px;
|
|
392
|
-
max-height: min(50vh, 380px);
|
|
393
|
-
min-height: 200px;
|
|
394
|
-
position: relative;
|
|
395
|
-
display: flex;
|
|
396
|
-
align-items: center;
|
|
397
|
-
justify-content: center;
|
|
398
|
-
overflow: visible;
|
|
399
|
-
box-sizing: border-box;
|
|
400
|
-
margin-bottom: 0.5rem;
|
|
401
|
-
}
|
|
402
|
-
sl-dialog::part(base) {
|
|
403
|
-
position: absolute;
|
|
404
|
-
}
|
|
405
|
-
sl-dialog::part(overlay) {
|
|
406
|
-
position: absolute;
|
|
407
|
-
}
|
|
408
|
-
sl-dialog::part(panel) {
|
|
409
|
-
max-width: calc(100% - 20px);
|
|
410
|
-
max-height: calc(100% - 20px);
|
|
411
|
-
}
|
|
412
|
-
.crop-dialog::part(panel) {
|
|
413
|
-
max-width: min(94%, 560px);
|
|
414
|
-
max-height: calc(100% - 16px);
|
|
415
|
-
display: flex;
|
|
416
|
-
flex-direction: column;
|
|
417
|
-
}
|
|
418
|
-
.crop-dialog::part(body) {
|
|
419
|
-
padding: 24px;
|
|
420
|
-
overflow: hidden;
|
|
421
|
-
display: flex;
|
|
422
|
-
align-items: center;
|
|
423
|
-
justify-content: center;
|
|
424
|
-
flex: 1 1 auto;
|
|
425
|
-
min-height: 0;
|
|
426
|
-
}
|
|
427
|
-
@container copio-scanner (max-width: 400px) {
|
|
428
|
-
.crop-wrapper {
|
|
429
|
-
height: 240px;
|
|
430
|
-
max-height: 42cqh;
|
|
431
|
-
min-height: 160px;
|
|
432
|
-
}
|
|
433
|
-
.crop-dialog::part(panel) {
|
|
434
|
-
max-width: calc(100% - 12px);
|
|
435
|
-
max-height: calc(100% - 12px);
|
|
436
|
-
}
|
|
437
|
-
.crop-dialog::part(body) {
|
|
438
|
-
padding: 16px;
|
|
439
|
-
}
|
|
440
|
-
.crop-dialog::part(header) {
|
|
441
|
-
padding: 0.5rem 0.75rem;
|
|
442
|
-
}
|
|
443
|
-
.crop-dialog::part(footer) {
|
|
444
|
-
padding: 0.5rem 0.75rem;
|
|
445
|
-
}
|
|
446
|
-
}
|
|
447
|
-
button.add-btn {
|
|
448
|
-
width: 100%;
|
|
449
|
-
aspect-ratio: 1;
|
|
450
|
-
font-size: 1.6rem;
|
|
451
|
-
border: 2px dashed #888;
|
|
452
|
-
border-radius: 4px;
|
|
453
|
-
background: none;
|
|
454
|
-
cursor: pointer;
|
|
455
|
-
display: flex;
|
|
456
|
-
align-items: center;
|
|
457
|
-
justify-content: center;
|
|
458
|
-
color: #64748b;
|
|
459
|
-
transition: border-color 0.15s, color 0.15s, background-color 0.15s;
|
|
460
|
-
}
|
|
461
|
-
button.add-btn:hover {
|
|
462
|
-
border-color: #3b82f6;
|
|
463
|
-
color: #3b82f6;
|
|
464
|
-
background-color: rgba(59, 130, 246, 0.04);
|
|
465
|
-
}
|
|
466
|
-
dialog {
|
|
467
|
-
border: none;
|
|
468
|
-
border-radius: 6px;
|
|
469
|
-
padding: 1rem;
|
|
470
|
-
}
|
|
471
|
-
dialog::backdrop {
|
|
472
|
-
background: rgba(0, 0, 0, 0.3);
|
|
473
|
-
}
|
|
474
|
-
</style>
|
|
475
|
-
`;this.shadowRoot.innerHTML=`
|
|
476
|
-
${t}
|
|
477
|
-
<div class="container"></div>
|
|
478
|
-
|
|
479
|
-
<input type="file" class="file-input" accept="image/*,application/pdf" multiple style="display: none">
|
|
480
|
-
<input type="file" class="camera-input" accept="image/*" capture="environment" style="display: none">
|
|
481
|
-
|
|
482
|
-
<sl-dialog label="Image Data" class="data-dialog">
|
|
483
|
-
<div class="exif-data" style="font-size: 0.85rem; line-height: 1.6;"></div>
|
|
484
|
-
<sl-button slot="footer" variant="primary" class="close-data">Close</sl-button>
|
|
485
|
-
</sl-dialog>
|
|
486
|
-
|
|
487
|
-
<sl-dialog label="Crop Image" class="crop-dialog" style="--width: min(94%, 560px)">
|
|
488
|
-
<div class="crop-wrapper">
|
|
489
|
-
<img id="crop-image" />
|
|
490
|
-
</div>
|
|
491
|
-
<sl-button slot="footer" variant="default" class="cancel-crop">Cancel</sl-button>
|
|
492
|
-
<sl-button slot="footer" variant="primary" class="apply-crop">Apply</sl-button>
|
|
493
|
-
</sl-dialog>
|
|
494
|
-
`,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"),a=this.shadowRoot.querySelector(".camera-input"),c=!1,l=async h=>{if(c)return;let b=Array.from(h.target?.files||[]);if(b.length!==0){c=!0;try{await this.addFiles(b)}finally{h.target&&(h.target.value=""),c=!1}}};n&&(n.onchange=l,n.addEventListener("change",l,{signal:e})),a&&(a.onchange=l,a.addEventListener("change",l,{signal:e}));let d=0,m=h=>{let b=h.dataTransfer;if(!b)return!1;if(!b.types||b.types.length===0)return!0;let A=Array.from(b.types);return A.includes("Files")||A.some(D=>D.startsWith("image/")||D.startsWith("public.")||D.includes("pdf")||D.includes("file")||D==="text/uri-list")},u=h=>{m(h)&&(h.preventDefault(),d++,S.classList.add("drag-over"))},o=h=>{m(h)&&(h.preventDefault(),h.stopPropagation(),h.dataTransfer&&(h.dataTransfer.dropEffect="copy"),S.classList.add("drag-over"))},p=()=>{d--,d<=0&&(d=0,S.classList.remove("drag-over"))},w=async h=>{d=0,S.classList.remove("drag-over"),h.preventDefault(),h.stopPropagation();let b=[];if(h.dataTransfer?.files?.length>0)b=Array.from(h.dataTransfer.files);else if(h.dataTransfer?.items?.length>0){for(let A of h.dataTransfer.items)if(A.kind==="file"){let D=A.getAsFile();D&&b.push(D)}}else h.detail?.files&&(b=Array.from(h.detail.files));b.length>0&&await this.addFiles(b)},S=this.shadowRoot.querySelector(".container");S&&(S.addEventListener("dragenter",u,{signal:e}),S.addEventListener("dragover",o,{signal:e}),S.addEventListener("dragleave",p,{signal:e}),S.addEventListener("drop",w,{signal:e}),S.addEventListener("dragend",()=>{d=0,S.classList.remove("drag-over")},{signal:e}),S.addEventListener("click",h=>{h.target===S&&n?.click()},{signal:e}));let f=this.shadowRoot.querySelector(".cancel-crop"),v=this.shadowRoot.querySelector(".apply-crop");f&&f.addEventListener("click",()=>this.closeCropDialog(),{signal:e}),v&&v.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((a,c)=>{let l=Ga(a.edits),d=a.edits?.filter==="bw";return`
|
|
495
|
-
<div class="image-wrapper" data-index="${c}">
|
|
496
|
-
<img src="${a.src}" draggable="false">
|
|
497
|
-
<sl-dropdown class="image-menu" data-index="${c}">
|
|
498
|
-
<sl-button slot="trigger" variant="default" size="small" circle>
|
|
499
|
-
<sl-icon name="three-dots-vertical"></sl-icon>
|
|
500
|
-
</sl-button>
|
|
501
|
-
<sl-menu>
|
|
502
|
-
${this.ocr!==!1?`
|
|
503
|
-
<sl-menu-item value="ocr">
|
|
504
|
-
<sl-icon slot="prefix" name="card-text"></sl-icon> Extract Text
|
|
505
|
-
</sl-menu-item>
|
|
506
|
-
<sl-divider></sl-divider>
|
|
507
|
-
`:""}
|
|
508
|
-
<sl-menu-item value="crop">Crop</sl-menu-item>
|
|
509
|
-
<sl-menu-item value="rotate">Rotate</sl-menu-item>
|
|
510
|
-
<sl-menu-item value="threshold">
|
|
511
|
-
<sl-icon slot="prefix" name="${d?"check-lg":"circle"}"></sl-icon>
|
|
512
|
-
${d?"Remove Black & White":"Black & White"}
|
|
513
|
-
</sl-menu-item>
|
|
514
|
-
<sl-menu-item value="reset" ?disabled=${!l}>
|
|
515
|
-
<sl-icon slot="prefix" name="arrow-counterclockwise"></sl-icon>
|
|
516
|
-
Reset to Original
|
|
517
|
-
</sl-menu-item>
|
|
518
|
-
<sl-menu-item value="showdata">Show Data</sl-menu-item>
|
|
519
|
-
<sl-menu-item value="download">Download Image</sl-menu-item>
|
|
520
|
-
<sl-divider></sl-divider>
|
|
521
|
-
<sl-menu-item value="delete">Delete</sl-menu-item>
|
|
522
|
-
</sl-menu>
|
|
523
|
-
</sl-dropdown>
|
|
524
|
-
</div>
|
|
525
|
-
`}).join("");t.innerHTML=`
|
|
526
|
-
${e}
|
|
527
|
-
<button class="add-btn add-image-btn" title="Add image or PDF" aria-label="Add image or PDF">
|
|
528
|
-
<sl-icon name="plus-lg"></sl-icon>
|
|
529
|
-
</button>
|
|
530
|
-
<button class="add-btn add-camera-btn" title="Capture from camera" aria-label="Capture from camera">
|
|
531
|
-
<sl-icon name="camera"></sl-icon>
|
|
532
|
-
</button>
|
|
533
|
-
`;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(a=>{a.querySelector("sl-menu").addEventListener("sl-select",l=>{l.stopPropagation();let d=parseInt(a.dataset.index),m=l.detail.item.value;if(m==="ocr")a.hide(),this.dispatchEvent(new CustomEvent("copio:ocr-page",{bubbles:!0,composed:!0,detail:{page:this.#t[d],pageIndex:d}}));else if(m==="crop")a.hide(),this.openCropDialog(d);else if(m==="rotate")this.rotateImage(d);else if(m==="threshold")this.thresholdImage(d);else if(m==="reset")a.hide(),this.resetImage(d);else if(m==="showdata")a.hide(),this.showImageData(d);else if(m==="download")this.downloadImage(d);else if(m==="delete"){let[u]=this.#t.splice(d,1);this.#g();let o=u.name||`Page ${d+1}`;Ae.undo(`Deleted ${o}`,()=>{this.#t.splice(d,0,u),this.#g(),Ae.success(`Restored ${o}`)},{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=Oc.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 a=this.#t[i];this.#t.splice(i,1),this.#t.splice(n,0,a),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=Ve(e.edits),n.src=e.originalSrc,i.show();let a=await hc(),c=e.edits?.crop,l=()=>{this.#e&&this.#e.destroy(),this.#e=new a(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 d=this.#e.getImageData();this.#e.setData({x:Math.round(c.normalized.x*d.naturalWidth),y:Math.round(c.normalized.y*d.naturalHeight),width:Math.round(c.normalized.w*d.naturalWidth),height:Math.round(c.normalized.h*d.naturalHeight)})}else if(typeof c.w=="number"&&c.w>0){let d=this.#e.getImageData();this.#e.setData({x:Math.round(c.x*d.naturalWidth),y:Math.round(c.y*d.naturalHeight),width:Math.round(c.w*d.naturalWidth),height:Math.round(c.h*d.naturalHeight)})}}catch(d){console.warn("Failed restoring prior crop box:",d)}}})};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,a=i?.naturalHeight||1,c=Math.max(0,Math.min(1,e.x/n)),l=Math.max(0,Math.min(1,e.y/a)),d=Math.max(0,Math.min(1,e.width/n)),m=Math.max(0,Math.min(1,e.height/a));t.edits={...Ve(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(d.toFixed(4)),h:Number(m.toFixed(4))}}};let u=this.#e.getCroppedCanvas();if(u){let o=xs(u,{crop:null,rotation:t.edits.rotation,filter:t.edits.filter}),p=typeof t.originalSrc=="string"&&t.originalSrc.startsWith("data:image/png")||t.originalBlob?.type==="image/png"||t.mimeType==="image/png",w=p?"image/png":"image/jpeg";t.src=o.toDataURL(w,p?void 0:.82)}this.#g(),this.closeCropDialog()}}async rotateImage(t){let e=this.#t[t];e&&(e.originalSrc=e.originalSrc||e.src,e.edits={...Ve(e.edits),rotation:((e.edits?.rotation||0)+90)%360},e.src=await sn(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={...Ve(e.edits),filter:i?"none":"bw"},e.src=await sn(e.originalSrc,e.edits),this.#g(),i?Ae.info("Restored color (removed B&W filter)"):Ae.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(),Ae.success("Reset page to original"))}downloadImage(t){let e=this.#t[t];if(!e)return;let i="jpg",n=e.src,a=!1;if(e.blob instanceof Blob)e.blob.type&&e.blob.type.includes("png")&&(i="png"),n=this.#u(URL.createObjectURL(e.blob)),a=!0;else if(e.src){if(e.src.startsWith("data:")){let d=e.src.match(/^data:(image\/[a-zA-Z+]+);base64,/);d&&d[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(),a&&this.#d(n),Ae.success(`Downloaded "${l}"`)}showImageData(t){let{src:e,exif:i}=this.#t[t],n=this.shadowRoot.querySelector(`img[src="${e}"]`),a=[];if(a.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,d]of Object.entries(i)){if(c.has(l)||d===void 0||d===null)continue;let m=d instanceof Array?d.join(", "):String(d);m.length>200||a.push(`<strong>${l}:</strong> ${m}`)}}else a.push("<em>No EXIF data available</em>");this.shadowRoot.querySelector(".exif-data").innerHTML=a.join("<br>"),this.shadowRoot.querySelector(".data-dialog").show()}async pdfToImages(t){let e=await t.arrayBuffer();return(await Yc(e)).map(n=>({id:ze(),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 a=await this.pdfToImages(n);e.push(...a)}else{let[a,c]=await Promise.all([xr(n),wr(n)]);e.push({id:ze(),src:a,originalSrc:a,edits:{crop:null,rotation:0,filter:"none"},exif:c})}this.#t.push(...e),this.#g();let i=e.length;Ae.success(`Imported ${i} page${i!==1?"s":""}`)}catch(i){console.error("Failed to import files:",i),Ae.error("Failed to import files")}}get ocr(){return this.#a!==!1}set ocr(t){this.#a=!!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:Ve(i.edits)}),this.#r&&this.#g()}};customElements.define("copio-images",jr);var zr=globalThis,Po=zr.ShadowRoot&&(zr.ShadyCSS===void 0||zr.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Do=Symbol(),eh=new WeakMap,Vr=class{constructor(t,e,i){if(this._$cssResult$=!0,i!==Do)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(Po&&t===void 0){let i=e!==void 0&&e.length===1;i&&(t=eh.get(e)),t===void 0&&((this.i=t=new CSSStyleSheet).replaceSync(this.cssText),i&&eh.set(e,t))}return t}toString(){return this.cssText}},ku=s=>new Vr(typeof s=="string"?s:s+"",void 0,Do),Ai=(s,...t)=>{let e=s.length===1?s[0]:t.reduce(((i,n,a)=>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[a+1]),s[0]);return new Vr(e,s,Do)},Tu=(s,t)=>{if(Po)s.adoptedStyleSheets=t.map((e=>e instanceof CSSStyleSheet?e:e.styleSheet));else for(let e of t){let i=document.createElement("style"),n=zr.litNonce;n!==void 0&&i.setAttribute("nonce",n),i.textContent=e.cssText,s.appendChild(i)}},ih=Po?s=>s:s=>s instanceof CSSStyleSheet?(t=>{let e="";for(let i of t.cssRules)e+=i.cssText;return ku(e)})(s):s,{is:Pu,defineProperty:Du,getOwnPropertyDescriptor:Mu,getOwnPropertyNames:Ru,getOwnPropertySymbols:Iu,getPrototypeOf:Lu}=Object,Gr=globalThis,sh=Gr.trustedTypes,Fu=sh?sh.emptyScript:"",Ou=Gr.reactiveElementPolyfillSupport,xn=(s,t)=>s,So={toAttribute(s,t){switch(t){case Boolean:s=s?Fu: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}},dh=(s,t)=>!Pu(s,t),nh={attribute:!0,type:String,converter:So,reflect:!1,useDefault:!1,hasChanged:dh};Symbol.metadata??=Symbol("metadata"),Gr.litPropertyMetadata??=new WeakMap;var wi=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=nh){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&&Du(this.prototype,t,n)}}static getPropertyDescriptor(t,e,i){let{get:n,set:a}=Mu(this.prototype,t)??{get(){return this[e]},set(c){this[e]=c}};return{get:n,set(c){let l=n?.call(this);a?.call(this,c),this.requestUpdate(t,l,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??nh}static o(){if(this.hasOwnProperty(xn("elementProperties")))return;let t=Lu(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=[...Ru(e),...Iu(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(ih(n))}else t!==void 0&&e.push(ih(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 Tu(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 a=(i.converter?.toAttribute!==void 0?i.converter:So).toAttribute(e,i.type);this.m=t,a==null?this.removeAttribute(n):this.setAttribute(n,a),this.m=null}}_$AK(t,e){let i=this.constructor,n=i.u.get(t);if(n!==void 0&&this.m!==n){let a=i.getPropertyOptions(n),c=typeof a.converter=="function"?{fromAttribute:a.converter}:a.converter?.fromAttribute!==void 0?a.converter:So;this.m=n;let l=c.fromAttribute(e,a.type);this[n]=l??this.T?.get(n)??l,this.m=null}}requestUpdate(t,e,i){if(t!==void 0){let n=this.constructor,a=this[t];if(i??=n.getPropertyOptions(t),!((i.hasChanged??dh)(a,e)||i.useDefault&&i.reflect&&a===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:a},c){i&&!(this.T??=new Map).has(t)&&(this.T.set(t,c??e??this[t]),a!==!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,a]of this.v)this[n]=a;this.v=void 0}let i=this.constructor.elementProperties;if(i.size>0)for(let[n,a]of i){let{wrapped:c}=a,l=this[n];c!==!0||this._$AL.has(n)||l===void 0||this.M(n,void 0,a,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){}};wi.elementStyles=[],wi.shadowRootOptions={mode:"open"},wi[xn("elementProperties")]=new Map,wi[xn("finalized")]=new Map,Ou?.({ReactiveElement:wi}),(Gr.reactiveElementVersions??=[]).push("2.1.1");var Mo=globalThis,Wr=Mo.trustedTypes,rh=Wr?Wr.createPolicy("lit-html",{createHTML:s=>s}):void 0,uh="$lit$",xi=`lit$${Math.random().toFixed(9).slice(2)}$`,ph="?"+xi,Nu=`<${ph}>`,Ji=document,An=()=>Ji.createComment(""),Sn=s=>s===null||typeof s!="object"&&typeof s!="function",Ro=Array.isArray,Bu=s=>Ro(s)||typeof s?.[Symbol.iterator]=="function",Ao=`[
|
|
534
|
-
\f\r]`,wn=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,ah=/-->/g,oh=/>/g,Ki=RegExp(`>|${Ao}(?:([^\\s"'>=/]+)(${Ao}*=${Ao}*(?:[^
|
|
535
|
-
\f\r"'\`<>=]|("|')|))|$)`,"g"),lh=/'/g,ch=/"/g,fh=/^(?:script|style|textarea|title)$/i,Io=s=>(t,...e)=>({_$litType$:s,strings:t,values:e}),ie=Io(1),Eg=Io(2),_g=Io(3),Is=Symbol.for("lit-noChange"),re=Symbol.for("lit-nothing"),hh=new WeakMap,Yi=Ji.createTreeWalker(Ji,129);function gh(s,t){if(!Ro(s)||!s.hasOwnProperty("raw"))throw Error("invalid template strings array");return rh!==void 0?rh.createHTML(t):t}var Uu=(s,t)=>{let e=s.length-1,i=[],n,a=t===2?"<svg>":t===3?"<math>":"",c=wn;for(let l=0;l<e;l++){let d=s[l],m,u,o=-1,p=0;for(;p<d.length&&(c.lastIndex=p,u=c.exec(d),u!==null);)p=c.lastIndex,c===wn?u[1]==="!--"?c=ah:u[1]!==void 0?c=oh:u[2]!==void 0?(fh.test(u[2])&&(n=RegExp("</"+u[2],"g")),c=Ki):u[3]!==void 0&&(c=Ki):c===Ki?u[0]===">"?(c=n??wn,o=-1):u[1]===void 0?o=-2:(o=c.lastIndex-u[2].length,m=u[1],c=u[3]===void 0?Ki:u[3]==='"'?ch:lh):c===ch||c===lh?c=Ki:c===ah||c===oh?c=wn:(c=Ki,n=void 0);let w=c===Ki&&s[l+1].startsWith("/>")?" ":"";a+=c===wn?d+Nu:o>=0?(i.push(m),d.slice(0,o)+uh+d.slice(o)+xi+w):d+xi+(o===-2?l:w)}return[gh(s,a+(s[e]||"<?>")+(t===2?"</svg>":t===3?"</math>":"")),i]},En=class s{constructor({strings:t,_$litType$:e},i){let n;this.parts=[];let a=0,c=0,l=t.length-1,d=this.parts,[m,u]=Uu(t,e);if(this.el=s.createElement(m,i),Yi.currentNode=this.el.content,e===2||e===3){let o=this.el.content.firstChild;o.replaceWith(...o.childNodes)}for(;(n=Yi.nextNode())!==null&&d.length<l;){if(n.nodeType===1){if(n.hasAttributes())for(let o of n.getAttributeNames())if(o.endsWith(uh)){let p=u[c++],w=n.getAttribute(o).split(xi),S=/([.?@])?(.*)/.exec(p);d.push({type:1,index:a,name:S[2],strings:w,ctor:S[1]==="."?_o:S[1]==="?"?Co:S[1]==="@"?ko:Fs}),n.removeAttribute(o)}else o.startsWith(xi)&&(d.push({type:6,index:a}),n.removeAttribute(o));if(fh.test(n.tagName)){let o=n.textContent.split(xi),p=o.length-1;if(p>0){n.textContent=Wr?Wr.emptyScript:"";for(let w=0;w<p;w++)n.append(o[w],An()),Yi.nextNode(),d.push({type:2,index:++a});n.append(o[p],An())}}}else if(n.nodeType===8)if(n.data===ph)d.push({type:2,index:a});else{let o=-1;for(;(o=n.data.indexOf(xi,o+1))!==-1;)d.push({type:7,index:a}),o+=xi.length-1}a++}}static createElement(t,e){let i=Ji.createElement("template");return i.innerHTML=t,i}};function Ls(s,t,e=s,i){if(t===Is)return t;let n=i!==void 0?e.N?.[i]:e.O,a=Sn(t)?void 0:t._$litDirective$;return n?.constructor!==a&&(n?._$AO?.(!1),a===void 0?n=void 0:(n=new a(s),n._$AT(s,e,i)),i!==void 0?(e.N??=[])[i]=n:e.O=n),n!==void 0&&(t=Ls(s,n._$AS(s,t.values),n,i)),t}var Eo=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??Ji).importNode(e,!0);Yi.currentNode=n;let a=Yi.nextNode(),c=0,l=0,d=i[0];for(;d!==void 0;){if(c===d.index){let m;d.type===2?m=new _n(a,a.nextSibling,this,t):d.type===1?m=new d.ctor(a,d.name,d.strings,this,t):d.type===6&&(m=new To(a,this,t)),this._$AV.push(m),d=i[++l]}c!==d?.index&&(a=Yi.nextNode(),c++)}return Yi.currentNode=Ji,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++}},_n=class s{get _$AU(){return this._$AM?._$AU??this.D}constructor(t,e,i,n){this.type=2,this._$AH=re,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=Ls(this,t,e),Sn(t)?t===re||t==null||t===""?(this._$AH!==re&&this._$AR(),this._$AH=re):t!==this._$AH&&t!==Is&&this.L(t):t._$litType$!==void 0?this.j(t):t.nodeType!==void 0?this.I(t):Bu(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!==re&&Sn(this._$AH)?this._$AA.nextSibling.data=t:this.I(Ji.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=En.createElement(gh(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===n)this._$AH.V(e);else{let a=new Eo(n,this),c=a.R(this.options);a.V(e),this.I(c),this._$AH=a}}_$AC(t){let e=hh.get(t.strings);return e===void 0&&hh.set(t.strings,e=new En(t)),e}H(t){Ro(this._$AH)||(this._$AH=[],this._$AR());let e=this._$AH,i,n=0;for(let a of t)n===e.length?e.push(i=new s(this.B(An()),this.B(An()),this,this.options)):i=e[n],i._$AI(a),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))}},Fs=class{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,e,i,n,a){this.type=1,this._$AH=re,this._$AN=void 0,this.element=t,this.name=e,this._$AM=n,this.options=a,i.length>2||i[0]!==""||i[1]!==""?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=re}_$AI(t,e=this,i,n){let a=this.strings,c=!1;if(a===void 0)t=Ls(this,t,e,0),c=!Sn(t)||t!==this._$AH&&t!==Is,c&&(this._$AH=t);else{let l=t,d,m;for(t=a[0],d=0;d<a.length-1;d++)m=Ls(this,l[i+d],e,d),m===Is&&(m=this._$AH[d]),c||=!Sn(m)||m!==this._$AH[d],m===re?t=re:t!==re&&(t+=(m??"")+a[d+1]),this._$AH[d]=m}c&&!n&&this.W(t)}W(t){t===re?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??"")}},_o=class extends Fs{constructor(){super(...arguments),this.type=3}W(t){this.element[this.name]=t===re?void 0:t}},Co=class extends Fs{constructor(){super(...arguments),this.type=4}W(t){this.element.toggleAttribute(this.name,!!t&&t!==re)}},ko=class extends Fs{constructor(t,e,i,n,a){super(t,e,i,n,a),this.type=5}_$AI(t,e=this){if((t=Ls(this,t,e,0)??re)===Is)return;let i=this._$AH,n=t===re&&i!==re||t.capture!==i.capture||t.once!==i.once||t.passive!==i.passive,a=t!==re&&(i===re||n);n&&this.element.removeEventListener(this.name,this,i),a&&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)}},To=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){Ls(this,t)}};var $u=Mo.litHtmlPolyfillSupport;$u?.(En,_n),(Mo.litHtmlVersions??=[]).push("3.3.1");var Hu=(s,t,e)=>{let i=e?.renderBefore??t,n=i._$litPart$;if(n===void 0){let a=e?.renderBefore??null;i._$litPart$=n=new _n(t.insertBefore(An(),a),a,void 0,e??{})}return n._$AI(s),n},Lo=globalThis;var ue=class extends wi{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=Hu(e,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this.rt?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this.rt?.setConnected(!1)}render(){return Is}};ue._$litElement$=!0,ue.finalized=!0,Lo.litElementHydrateSupport?.({LitElement:ue});var ju=Lo.litElementPolyfillSupport;ju?.({LitElement:ue});(Lo.litElementVersions??=[]).push("4.2.1");var qr=class extends ue{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=Ai`
|
|
536
|
-
:host {
|
|
537
|
-
display: block;
|
|
538
|
-
position: absolute;
|
|
539
|
-
top: 0;
|
|
540
|
-
left: 0;
|
|
541
|
-
right: 0;
|
|
542
|
-
bottom: 0;
|
|
543
|
-
width: 100%;
|
|
544
|
-
height: 100%;
|
|
545
|
-
z-index: 10;
|
|
546
|
-
overflow: hidden;
|
|
547
|
-
background: #000;
|
|
548
|
-
box-sizing: border-box;
|
|
549
|
-
}
|
|
550
|
-
sl-carousel {
|
|
551
|
-
position: absolute;
|
|
552
|
-
top: 0;
|
|
553
|
-
padding-top: 16px;
|
|
554
|
-
background: white;
|
|
555
|
-
z-index: 4;
|
|
556
|
-
height: 100%;
|
|
557
|
-
width: 100%;
|
|
558
|
-
}
|
|
559
|
-
sl-carousel-item {
|
|
560
|
-
height: 100%;
|
|
561
|
-
}
|
|
562
|
-
.item {
|
|
563
|
-
width: 100%;
|
|
564
|
-
height: 100%;
|
|
565
|
-
background-repeat: no-repeat;
|
|
566
|
-
background-size: contain;
|
|
567
|
-
background-position: center;
|
|
568
|
-
}
|
|
569
|
-
.top-bar {
|
|
570
|
-
position: absolute;
|
|
571
|
-
top: 0;
|
|
572
|
-
left: 0;
|
|
573
|
-
right: 0;
|
|
574
|
-
height: 56px;
|
|
575
|
-
z-index: 10;
|
|
576
|
-
display: flex;
|
|
577
|
-
align-items: center;
|
|
578
|
-
justify-content: space-between;
|
|
579
|
-
padding: 0 16px;
|
|
580
|
-
background: linear-gradient(to bottom, rgba(15, 23, 42, 0.85) 0%, rgba(15, 23, 42, 0.3) 80%, transparent 100%);
|
|
581
|
-
pointer-events: none;
|
|
582
|
-
box-sizing: border-box;
|
|
583
|
-
}
|
|
584
|
-
.top-bar > * {
|
|
585
|
-
pointer-events: auto;
|
|
586
|
-
}
|
|
587
|
-
.top-bar-left {
|
|
588
|
-
display: flex;
|
|
589
|
-
align-items: center;
|
|
590
|
-
gap: 10px;
|
|
591
|
-
min-width: 0;
|
|
592
|
-
}
|
|
593
|
-
.top-bar-right {
|
|
594
|
-
display: flex;
|
|
595
|
-
align-items: center;
|
|
596
|
-
gap: 8px;
|
|
597
|
-
}
|
|
598
|
-
.back {
|
|
599
|
-
font-size: 26px;
|
|
600
|
-
cursor: pointer;
|
|
601
|
-
appearance: none;
|
|
602
|
-
background: rgba(15, 23, 42, 0.6);
|
|
603
|
-
border: 1px solid rgba(255, 255, 255, 0.2);
|
|
604
|
-
border-radius: 8px;
|
|
605
|
-
color: white;
|
|
606
|
-
width: 36px;
|
|
607
|
-
height: 36px;
|
|
608
|
-
display: flex;
|
|
609
|
-
align-items: center;
|
|
610
|
-
justify-content: center;
|
|
611
|
-
transition: background 0.15s;
|
|
612
|
-
}
|
|
613
|
-
.back:hover {
|
|
614
|
-
background: rgba(15, 23, 42, 0.9);
|
|
615
|
-
}
|
|
616
|
-
.doc-heading {
|
|
617
|
-
color: #f8fafc;
|
|
618
|
-
font-size: 1.05rem;
|
|
619
|
-
font-weight: 600;
|
|
620
|
-
white-space: nowrap;
|
|
621
|
-
overflow: hidden;
|
|
622
|
-
text-overflow: ellipsis;
|
|
623
|
-
max-width: 240px;
|
|
624
|
-
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.8);
|
|
625
|
-
}
|
|
626
|
-
.ocr-btn, .export-btn {
|
|
627
|
-
background: rgba(15, 23, 42, 0.75);
|
|
628
|
-
backdrop-filter: blur(8px);
|
|
629
|
-
color: white;
|
|
630
|
-
border: 1px solid rgba(255, 255, 255, 0.2);
|
|
631
|
-
border-radius: 8px;
|
|
632
|
-
padding: 6px 12px;
|
|
633
|
-
height: 36px;
|
|
634
|
-
font-size: 13px;
|
|
635
|
-
display: flex;
|
|
636
|
-
align-items: center;
|
|
637
|
-
gap: 6px;
|
|
638
|
-
cursor: pointer;
|
|
639
|
-
transition: background 0.15s, border-color 0.15s;
|
|
640
|
-
box-sizing: border-box;
|
|
641
|
-
}
|
|
642
|
-
.ocr-btn:hover, .export-btn:hover {
|
|
643
|
-
background: rgba(15, 23, 42, 0.95);
|
|
644
|
-
border-color: rgba(255, 255, 255, 0.4);
|
|
645
|
-
}
|
|
646
|
-
`;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 ie`
|
|
647
|
-
<sl-carousel-item data-id="${t.id}">
|
|
648
|
-
<div class="item" style="background-image: url('${t.src}')"></div>
|
|
649
|
-
</sl-carousel-item>
|
|
650
|
-
`}render(){let t=this.visibleImages[this.activeSlideIndex],e=this.ocr!==!1&&t&&!!t.src;return ie`
|
|
651
|
-
<div class="top-bar">
|
|
652
|
-
<div class="top-bar-left">
|
|
653
|
-
<button class="back" @click=${this.handleBackClick} aria-label="Back">←</button>
|
|
654
|
-
<span class="doc-heading">${this.docName||"Document"}</span>
|
|
655
|
-
</div>
|
|
656
|
-
|
|
657
|
-
<div class="top-bar-right">
|
|
658
|
-
${e?ie`
|
|
659
|
-
<button class="ocr-btn" @click=${this.handleOcrClick} aria-label="Extract text">
|
|
660
|
-
<sl-icon name="card-text"></sl-icon>
|
|
661
|
-
<span>Extract Text</span>
|
|
662
|
-
</button>
|
|
663
|
-
`:""}
|
|
664
|
-
|
|
665
|
-
<sl-dropdown>
|
|
666
|
-
<button slot="trigger" class="export-btn" aria-label="Export document">
|
|
667
|
-
<sl-icon name="box-arrow-up"></sl-icon>
|
|
668
|
-
<span>Export</span>
|
|
669
|
-
<sl-icon name="chevron-down" style="font-size: 0.75rem;"></sl-icon>
|
|
670
|
-
</button>
|
|
671
|
-
<sl-menu @sl-select=${this.handleExportSelect}>
|
|
672
|
-
${this.pdf!==!1?ie`
|
|
673
|
-
<sl-menu-item value="pdf" ?disabled=${this.pageCount===0}>
|
|
674
|
-
<sl-icon slot="prefix" name="file-earmark-pdf"></sl-icon>
|
|
675
|
-
Download as PDF
|
|
676
|
-
</sl-menu-item>
|
|
677
|
-
${this.ocr!==!1?ie`
|
|
678
|
-
<sl-menu-item value="searchable-pdf" ?disabled=${this.pageCount===0}>
|
|
679
|
-
<sl-icon slot="prefix" name="file-earmark-text"></sl-icon>
|
|
680
|
-
Download Searchable PDF
|
|
681
|
-
</sl-menu-item>
|
|
682
|
-
`:""}
|
|
683
|
-
`:""}
|
|
684
|
-
<sl-menu-item value="images" ?disabled=${this.pageCount===0}>
|
|
685
|
-
<sl-icon slot="prefix" name="images"></sl-icon>
|
|
686
|
-
Download as Images (ZIP)
|
|
687
|
-
</sl-menu-item>
|
|
688
|
-
</sl-menu>
|
|
689
|
-
</sl-dropdown>
|
|
690
|
-
</div>
|
|
691
|
-
</div>
|
|
692
|
-
|
|
693
|
-
<sl-carousel
|
|
694
|
-
class="sl-carousel"
|
|
695
|
-
orientation="vertical"
|
|
696
|
-
@sl-slide-change=${this.handleSlideChange}
|
|
697
|
-
>
|
|
698
|
-
${this.visibleImages.map(i=>this.renderItem(i))}
|
|
699
|
-
</sl-carousel>
|
|
700
|
-
`}};customElements.define("copio-carousel",qr);var Xr=class extends ue{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 a=this.querySelector(".dialog-add-edit-input-id"),c=this.querySelector(".dialog-add-edit-input-name"),l=this.querySelector("copio-images");a.value=t,c.value=e,await customElements.whenDefined("copio-images"),l.images=i.map(({id:d,src:m,originalSrc:u,edits:o,exif:p})=>({id:d,src:m,originalSrc:u||m,edits:o||{crop:null,rotation:0,filter:"none"},exif:p})),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"),a=e?.value?.trim();if(!a){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:d,src:m,originalSrc:u,edits:o,exif:p,type:w,name:S,content:f})=>({id:d,src:m,originalSrc:u||m,edits:o||{crop:null,rotation:0,filter:"none"},exif:p,type:w,name:S,content:f})),l=t?.value||ze();this.dispatchEvent(new CustomEvent("dialog:save",{bubbles:!0,composed:!1,detail:{id:l,name:a,pages:c}})),this.querySelector(".dialog-add-edit")?.hide()};render(){return ie`
|
|
701
|
-
<sl-dialog
|
|
702
|
-
label="Add / Edit"
|
|
703
|
-
class="dialog-add-edit"
|
|
704
|
-
style="--width: min(94%, 640px)"
|
|
705
|
-
@sl-after-hide=${this.#i}
|
|
706
|
-
@keydown=${this.#n}
|
|
707
|
-
>
|
|
708
|
-
<div style="min-height: min(65cqh, 420px); min-height: 350px;">
|
|
709
|
-
<sl-input
|
|
710
|
-
disabled
|
|
711
|
-
class="dialog-add-edit-input-id"
|
|
712
|
-
placeholder="id"
|
|
713
|
-
style="display: none"
|
|
714
|
-
></sl-input>
|
|
715
|
-
<div class="dialog-name-field" style="max-width: 300px">
|
|
716
|
-
<sl-input
|
|
717
|
-
class="dialog-add-edit-input-name"
|
|
718
|
-
placeholder="Enter name of document or image"
|
|
719
|
-
@sl-input=${this.#e}
|
|
720
|
-
></sl-input>
|
|
721
|
-
<div
|
|
722
|
-
class="dialog-name-error"
|
|
723
|
-
style="color: #ef4444; font-size: 0.8rem; margin-top: 4px; display: none;"
|
|
724
|
-
>
|
|
725
|
-
Please enter a document name
|
|
726
|
-
</div>
|
|
727
|
-
</div>
|
|
728
|
-
|
|
729
|
-
<copio-images
|
|
730
|
-
style="display: block; margin-top: 1.5rem"
|
|
731
|
-
></copio-images>
|
|
732
|
-
|
|
733
|
-
<br />
|
|
734
|
-
|
|
735
|
-
<sl-button
|
|
736
|
-
class="dialog-add-edit-savebtn"
|
|
737
|
-
style="width: 100%; margin-top: auto;"
|
|
738
|
-
slot="footer"
|
|
739
|
-
variant="primary"
|
|
740
|
-
@click=${this.#r}
|
|
741
|
-
>Save</sl-button
|
|
742
|
-
>
|
|
743
|
-
</div>
|
|
744
|
-
</sl-dialog>
|
|
745
|
-
`}};customElements.define("copio-add-edit-dialog",Xr);var Kr=class extends ue{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=Ai`
|
|
746
|
-
.wrapper {
|
|
747
|
-
margin-left: auto;
|
|
748
|
-
margin-right: auto;
|
|
749
|
-
display: flex;
|
|
750
|
-
justify-content: space-between;
|
|
751
|
-
align-items: center;
|
|
752
|
-
max-width: 768px;
|
|
753
|
-
padding: 10px 12px;
|
|
754
|
-
border-bottom: 1px solid #e2e8f0;
|
|
755
|
-
cursor: pointer;
|
|
756
|
-
user-select: none;
|
|
757
|
-
}
|
|
758
|
-
.inner {
|
|
759
|
-
display: flex;
|
|
760
|
-
align-items: center;
|
|
761
|
-
flex: 1;
|
|
762
|
-
min-width: 0;
|
|
763
|
-
}
|
|
764
|
-
.titles {
|
|
765
|
-
display: flex;
|
|
766
|
-
flex-direction: column;
|
|
767
|
-
margin-left: 12px;
|
|
768
|
-
padding: 2px 0;
|
|
769
|
-
flex: 1;
|
|
770
|
-
min-width: 0;
|
|
771
|
-
}
|
|
772
|
-
.doc-title {
|
|
773
|
-
font-weight: 600;
|
|
774
|
-
font-size: 0.95rem;
|
|
775
|
-
color: #151f2a;
|
|
776
|
-
white-space: nowrap;
|
|
777
|
-
overflow: hidden;
|
|
778
|
-
text-overflow: ellipsis;
|
|
779
|
-
line-height: 1.3;
|
|
780
|
-
}
|
|
781
|
-
.doc-page-count {
|
|
782
|
-
font-size: 0.8rem;
|
|
783
|
-
color: #64748b;
|
|
784
|
-
margin-top: 2px;
|
|
785
|
-
}
|
|
786
|
-
.rename-container {
|
|
787
|
-
display: flex;
|
|
788
|
-
align-items: center;
|
|
789
|
-
gap: 6px;
|
|
790
|
-
width: 100%;
|
|
791
|
-
max-width: 320px;
|
|
792
|
-
}
|
|
793
|
-
.rename-container sl-input {
|
|
794
|
-
flex: 1;
|
|
795
|
-
}
|
|
796
|
-
button {
|
|
797
|
-
appearance: none;
|
|
798
|
-
border: none;
|
|
799
|
-
color: black;
|
|
800
|
-
padding: 3px 4px 3px 7px;
|
|
801
|
-
background: white;
|
|
802
|
-
cursor: pointer;
|
|
803
|
-
}
|
|
804
|
-
`;#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 ie`
|
|
805
|
-
<div class="wrapper" @click=${this.#t}>
|
|
806
|
-
<div class="inner">
|
|
807
|
-
<sl-avatar label="Document icon">
|
|
808
|
-
<sl-icon slot="icon" name="file-earmark-text"></sl-icon>
|
|
809
|
-
</sl-avatar>
|
|
810
|
-
|
|
811
|
-
<div class="titles">
|
|
812
|
-
${this.isRenaming?ie`
|
|
813
|
-
<div class="rename-container" @click=${t=>t.stopPropagation()}>
|
|
814
|
-
<sl-input
|
|
815
|
-
class="rename-input"
|
|
816
|
-
size="small"
|
|
817
|
-
.value=${this.renameValue}
|
|
818
|
-
@sl-input=${t=>this.renameValue=t.target.value}
|
|
819
|
-
@keydown=${this.handleRenameKeyDown}
|
|
820
|
-
></sl-input>
|
|
821
|
-
<sl-icon-button
|
|
822
|
-
name="check-lg"
|
|
823
|
-
label="Save rename"
|
|
824
|
-
@click=${this.commitRename}
|
|
825
|
-
></sl-icon-button>
|
|
826
|
-
<sl-icon-button
|
|
827
|
-
name="x-lg"
|
|
828
|
-
label="Cancel rename"
|
|
829
|
-
@click=${this.cancelRename}
|
|
830
|
-
></sl-icon-button>
|
|
831
|
-
</div>
|
|
832
|
-
`:ie`
|
|
833
|
-
<div class="doc-title">${this.name||"Untitled Document"}</div>
|
|
834
|
-
<div class="doc-page-count">
|
|
835
|
-
${this.pageCount} ${this.pageCount===1?"page":"pages"}
|
|
836
|
-
</div>
|
|
837
|
-
`}
|
|
838
|
-
</div>
|
|
839
|
-
</div>
|
|
840
|
-
|
|
841
|
-
<sl-dropdown>
|
|
842
|
-
<sl-button slot="trigger" variant="default" size="small" circle>
|
|
843
|
-
<sl-icon name="three-dots-vertical"></sl-icon>
|
|
844
|
-
</sl-button>
|
|
845
|
-
<sl-menu @sl-select=${this.#e}>
|
|
846
|
-
<sl-menu-item value="edit">
|
|
847
|
-
<sl-icon slot="prefix" name="sliders"></sl-icon>
|
|
848
|
-
Edit
|
|
849
|
-
</sl-menu-item>
|
|
850
|
-
<sl-menu-item value="rename">
|
|
851
|
-
<sl-icon slot="prefix" name="pencil"></sl-icon>
|
|
852
|
-
Rename
|
|
853
|
-
</sl-menu-item>
|
|
854
|
-
${this.ocr!==!1?ie`
|
|
855
|
-
<sl-menu-item
|
|
856
|
-
value="extract-ocr"
|
|
857
|
-
?disabled=${!this.hasImages}
|
|
858
|
-
title=${this.hasImages?"Extract text with OCR":"No image pages in document"}
|
|
859
|
-
>
|
|
860
|
-
<sl-icon slot="prefix" name="card-text"></sl-icon>
|
|
861
|
-
Extract All Text (OCR)
|
|
862
|
-
</sl-menu-item>
|
|
863
|
-
`:""}
|
|
864
|
-
<sl-divider></sl-divider>
|
|
865
|
-
${this.pdf!==!1?ie`
|
|
866
|
-
<sl-menu-item
|
|
867
|
-
value="download"
|
|
868
|
-
?disabled=${this.pageCount===0}
|
|
869
|
-
title=${this.pageCount===0?"Document is empty":"Download as PDF"}
|
|
870
|
-
>
|
|
871
|
-
<sl-icon slot="prefix" name="file-earmark-pdf"></sl-icon>
|
|
872
|
-
Download as PDF
|
|
873
|
-
</sl-menu-item>
|
|
874
|
-
${this.ocr!==!1?ie`
|
|
875
|
-
<sl-menu-item
|
|
876
|
-
value="download-searchable-pdf"
|
|
877
|
-
?disabled=${this.pageCount===0||!this.hasImages}
|
|
878
|
-
title=${this.pageCount===0?"Document is empty":"Download as Searchable PDF (with OCR text layer)"}
|
|
879
|
-
>
|
|
880
|
-
<sl-icon slot="prefix" name="file-earmark-text"></sl-icon>
|
|
881
|
-
Download Searchable PDF
|
|
882
|
-
</sl-menu-item>
|
|
883
|
-
`:""}
|
|
884
|
-
`:""}
|
|
885
|
-
<sl-menu-item
|
|
886
|
-
value="download-images"
|
|
887
|
-
?disabled=${this.pageCount===0}
|
|
888
|
-
title=${this.pageCount===0?"Document is empty":"Download as Images"}
|
|
889
|
-
>
|
|
890
|
-
<sl-icon slot="prefix" name="images"></sl-icon>
|
|
891
|
-
Download as Images
|
|
892
|
-
</sl-menu-item>
|
|
893
|
-
<sl-divider></sl-divider>
|
|
894
|
-
<sl-menu-item value="delete">
|
|
895
|
-
<sl-icon slot="prefix" name="trash"></sl-icon>
|
|
896
|
-
Delete
|
|
897
|
-
</sl-menu-item>
|
|
898
|
-
</sl-menu>
|
|
899
|
-
</sl-dropdown>
|
|
900
|
-
</div>
|
|
901
|
-
`}};customElements.define("copio-row",Kr);var Yr=class extends ue{static styles=Ai`
|
|
902
|
-
header {
|
|
903
|
-
background-color: #151f2a;
|
|
904
|
-
color: white;
|
|
905
|
-
display: flex;
|
|
906
|
-
align-items: center;
|
|
907
|
-
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
|
|
908
|
-
padding: 8px;
|
|
909
|
-
}
|
|
910
|
-
.header-left,
|
|
911
|
-
.header-right {
|
|
912
|
-
flex: 1;
|
|
913
|
-
display: flex;
|
|
914
|
-
align-items: center;
|
|
915
|
-
}
|
|
916
|
-
.header-right {
|
|
917
|
-
justify-content: flex-end;
|
|
918
|
-
}
|
|
919
|
-
h1 {
|
|
920
|
-
font-size: 24px;
|
|
921
|
-
margin: 0;
|
|
922
|
-
}
|
|
923
|
-
sl-icon-button::part(base) {
|
|
924
|
-
min-width: 44px;
|
|
925
|
-
min-height: 44px;
|
|
926
|
-
display: inline-flex;
|
|
927
|
-
align-items: center;
|
|
928
|
-
justify-content: center;
|
|
929
|
-
}
|
|
930
|
-
`;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 ie`
|
|
931
|
-
<header>
|
|
932
|
-
<div class="header-left">
|
|
933
|
-
<sl-dropdown @sl-show=${this.#t}>
|
|
934
|
-
<sl-icon-button
|
|
935
|
-
slot="trigger"
|
|
936
|
-
name="list"
|
|
937
|
-
label="Menu"
|
|
938
|
-
style="font-size: 1.5rem; color: white;"
|
|
939
|
-
></sl-icon-button>
|
|
940
|
-
<sl-menu @sl-select=${this.#e}>
|
|
941
|
-
<sl-menu-item value="link-device">Link another device</sl-menu-item>
|
|
942
|
-
<sl-menu-item value="clear-cache">Clear cache & update</sl-menu-item>
|
|
943
|
-
<sl-divider></sl-divider>
|
|
944
|
-
<sl-menu-item disabled>
|
|
945
|
-
Storage: ${this._formatBytes(this._storageEstimate?.usage)} / ${this._formatBytes(this._storageEstimate?.quota)}
|
|
946
|
-
</sl-menu-item>
|
|
947
|
-
<sl-menu-item disabled>
|
|
948
|
-
Backend: ${(this.storageKind||"opfs").toUpperCase()} (${this._isPersisted?"Persisted":"Volatile"})
|
|
949
|
-
</sl-menu-item>
|
|
950
|
-
</sl-menu>
|
|
951
|
-
</sl-dropdown>
|
|
952
|
-
</div>
|
|
953
|
-
<h1>COPIO</h1>
|
|
954
|
-
<div class="header-right"></div>
|
|
955
|
-
</header>
|
|
956
|
-
`}};customElements.define("copio-header",Yr);var Jr=class extends ue{disconnectedCallback(){super.disconnectedCallback()}static styles=Ai`
|
|
957
|
-
.lds-roller {
|
|
958
|
-
display: inline-block;
|
|
959
|
-
position: relative;
|
|
960
|
-
width: 80px;
|
|
961
|
-
height: 80px;
|
|
962
|
-
}
|
|
963
|
-
.lds-roller div {
|
|
964
|
-
animation: lds-roller 1.2s cubic-bezier(0.5, 0, 0.5, 1) infinite;
|
|
965
|
-
transform-origin: 40px 40px;
|
|
966
|
-
}
|
|
967
|
-
.lds-roller div:after {
|
|
968
|
-
content: ' ';
|
|
969
|
-
display: block;
|
|
970
|
-
position: absolute;
|
|
971
|
-
width: 7px;
|
|
972
|
-
height: 7px;
|
|
973
|
-
border-radius: 50%;
|
|
974
|
-
background: #fff;
|
|
975
|
-
margin: -4px 0 0 -4px;
|
|
976
|
-
}
|
|
977
|
-
.lds-roller div:nth-child(1) {
|
|
978
|
-
animation-delay: -0.036s;
|
|
979
|
-
}
|
|
980
|
-
.lds-roller div:nth-child(1):after {
|
|
981
|
-
top: 63px;
|
|
982
|
-
left: 63px;
|
|
983
|
-
}
|
|
984
|
-
.lds-roller div:nth-child(2) {
|
|
985
|
-
animation-delay: -0.072s;
|
|
986
|
-
}
|
|
987
|
-
.lds-roller div:nth-child(2):after {
|
|
988
|
-
top: 68px;
|
|
989
|
-
left: 56px;
|
|
990
|
-
}
|
|
991
|
-
.lds-roller div:nth-child(3) {
|
|
992
|
-
animation-delay: -0.108s;
|
|
993
|
-
}
|
|
994
|
-
.lds-roller div:nth-child(3):after {
|
|
995
|
-
top: 71px;
|
|
996
|
-
left: 48px;
|
|
997
|
-
}
|
|
998
|
-
.lds-roller div:nth-child(4) {
|
|
999
|
-
animation-delay: -0.144s;
|
|
1000
|
-
}
|
|
1001
|
-
.lds-roller div:nth-child(4):after {
|
|
1002
|
-
top: 72px;
|
|
1003
|
-
left: 40px;
|
|
1004
|
-
}
|
|
1005
|
-
.lds-roller div:nth-child(5) {
|
|
1006
|
-
animation-delay: -0.18s;
|
|
1007
|
-
}
|
|
1008
|
-
.lds-roller div:nth-child(5):after {
|
|
1009
|
-
top: 71px;
|
|
1010
|
-
left: 32px;
|
|
1011
|
-
}
|
|
1012
|
-
.lds-roller div:nth-child(6) {
|
|
1013
|
-
animation-delay: -0.216s;
|
|
1014
|
-
}
|
|
1015
|
-
.lds-roller div:nth-child(6):after {
|
|
1016
|
-
top: 68px;
|
|
1017
|
-
left: 24px;
|
|
1018
|
-
}
|
|
1019
|
-
.lds-roller div:nth-child(7) {
|
|
1020
|
-
animation-delay: -0.252s;
|
|
1021
|
-
}
|
|
1022
|
-
.lds-roller div:nth-child(7):after {
|
|
1023
|
-
top: 63px;
|
|
1024
|
-
left: 17px;
|
|
1025
|
-
}
|
|
1026
|
-
.lds-roller div:nth-child(8) {
|
|
1027
|
-
animation-delay: -0.288s;
|
|
1028
|
-
}
|
|
1029
|
-
.lds-roller div:nth-child(8):after {
|
|
1030
|
-
top: 56px;
|
|
1031
|
-
left: 12px;
|
|
1032
|
-
}
|
|
1033
|
-
@keyframes lds-roller {
|
|
1034
|
-
0% {
|
|
1035
|
-
transform: rotate(0deg);
|
|
1036
|
-
}
|
|
1037
|
-
100% {
|
|
1038
|
-
transform: rotate(360deg);
|
|
1039
|
-
}
|
|
1040
|
-
}
|
|
1041
|
-
`;render(){return ie`
|
|
1042
|
-
<div
|
|
1043
|
-
style="
|
|
1044
|
-
background: #151f2a;
|
|
1045
|
-
width: 100%;
|
|
1046
|
-
position: absolute;
|
|
1047
|
-
z-index: 5;
|
|
1048
|
-
height: 100%;
|
|
1049
|
-
margin: 0;
|
|
1050
|
-
padding: 0;
|
|
1051
|
-
top: 0;
|
|
1052
|
-
left: 0;
|
|
1053
|
-
"
|
|
1054
|
-
>
|
|
1055
|
-
<img
|
|
1056
|
-
src="copio.svg"
|
|
1057
|
-
style="
|
|
1058
|
-
position: absolute;
|
|
1059
|
-
top: 50%;
|
|
1060
|
-
left: 50%;
|
|
1061
|
-
transform: translate(-50%, -50%);
|
|
1062
|
-
opacity: 0.3;
|
|
1063
|
-
z-index: 1;
|
|
1064
|
-
max-width: 320px;
|
|
1065
|
-
"
|
|
1066
|
-
/>
|
|
1067
|
-
<div
|
|
1068
|
-
class="lds-roller"
|
|
1069
|
-
style="
|
|
1070
|
-
position: absolute;
|
|
1071
|
-
top: calc(50% + -50px);
|
|
1072
|
-
left: 50%;
|
|
1073
|
-
transform: translate(-50%) scale(1);
|
|
1074
|
-
opacity: 0.5;
|
|
1075
|
-
"
|
|
1076
|
-
>
|
|
1077
|
-
<div></div>
|
|
1078
|
-
<div></div>
|
|
1079
|
-
<div></div>
|
|
1080
|
-
<div></div>
|
|
1081
|
-
<div></div>
|
|
1082
|
-
<div></div>
|
|
1083
|
-
<div></div>
|
|
1084
|
-
<div></div>
|
|
1085
|
-
</div>
|
|
1086
|
-
</div>
|
|
1087
|
-
`}};customElements.define("copio-loader",Jr);var Fo=`
|
|
2
|
+
var _t=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 Le=class extends _t{#t=new Map;#r=new Map;#s=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.#l()}async deleteDoc(t){this.#t.delete(t);let e=`${t}/`;for(let i of this.#r.keys())i.startsWith(e)&&this.#r.delete(i);this.#l()}async renameDoc(t,e){let i=this.#t.get(t);if(!i)throw new Error(`Document "${t}" not found`);i.name=e,this.#l()}async savePage(t,e,i){this.#r.set(`${t}/${e}`,i);let s=this.#t.get(t);if(s){let o=s.pages.findIndex(n=>n.id===e);if(o>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?s.pages[o]={...s.pages[o],...i}:s.pages[o]={...s.pages[o],src:i};else{let n=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i};s.pages.push(n)}}this.#l()}async getPage(t,e){if(this.#r.has(`${t}/${e}`))return this.#r.get(`${t}/${e}`);let i=this.#t.get(t);if(i){let s=i.pages.find(o=>o.id===e);if(s)return s.src??s}return null}async deletePage(t,e){this.#r.delete(`${t}/${e}`);let i=this.#t.get(t);i&&(i.pages=i.pages.filter(s=>s.id!==e)),this.#l()}subscribe(t){return this.#s.add(t),()=>{this.#s.delete(t)}}clear(){this.#t.clear(),this.#r.clear(),this.#l()}#l(){for(let t of this.#s)try{t()}catch(e){console.error("Error in MemoryStorageAdapter subscriber:",e)}}};var se=r=>typeof r;var Ao=se(""),Vn=se(!0),Io=se(0),Wn=se(se),Wi="type",le="default",$r="Listener",xo="Result",Hr="add",de="Has",ni="Ids",re="Table",vo=re+"s",Gn=re+ni,Me="Row",Lo=Me+"Count",Ro=Me+ni,Kn="Sorted"+Me+ni,ri="Cell",Xi=ri+ni,Ji="Value",So=Ji+"s",qn=Ji+ni,at=r=>""+r;var Xn=(r,t="",e)=>r.split(t,e),_r=globalThis,er=Math,Or=er.max,Ur=er.min,Jn=er.floor,Bo=isFinite,H=r=>r==null,ct=(r,t,e)=>H(r)?e?.():t(r),To=r=>r==Ao||r==Vn,Yn=r=>se(r)==Ao,jt=r=>se(r)==Wn,Oe=r=>Array.isArray(r),Vr=(r,t,e)=>r.slice(t,e),Ot=r=>r.length,Mo=()=>{};var Fr=async(r,t,e)=>{try{return await r()}catch(i){t?.(i)}},Wr=(r,t)=>r.includes(t),Yi=(r,t)=>r.every(t),Oo=(r,t)=>Ot(r)===Ot(t)&&Yi(r,((e,i)=>t[i]===e)),ko=(r,t)=>Yi(r,((e,i)=>i==0||t(r[i-1],e)<=0)),Gr=(r,t)=>r.sort(t),Bt=(r,t)=>r.forEach(t),fe=(r,t)=>r.map(t),Po=r=>Uo(r,((t,e)=>t+e),0),si=r=>Ot(r)==0,Uo=(r,t,e)=>r.reduce(t,e),Rt=(r,...t)=>r.push(...t),Eo=r=>r.pop(),Fo=r=>r.shift(),Be=r=>{let t=se(r);return To(t)||t==Io&&Bo(r)?t:void 0};var Qi=(r,t,e,i,s)=>H(s)?r.delCell(t,e,i,!0):r.setCell(t,e,i,s),Kr=(r,t,e)=>H(e)?r.delValue(t):r.setValue(t,e),Yr=r=>t=>Uo(Ue(t),((e,i)=>e+r(i)),0),Fe=r=>r?.size??0,ue=Yr(Fe),Wt=Yr(ue),jr=Yr(Wt),ht=(r,t)=>r?.has(t)??!1,z=r=>H(r)||Fe(r)==0,Ue=r=>[...r?.values()??[]],Te=r=>r.clear(),j=(r,t)=>r?.forEach(t),Nt=(r,t)=>r?.delete(t),oe=Object,Co=r=>oe.getPrototypeOf(r),Qn=oe.isFrozen,jo=oe.entries,Zi=r=>!H(r)&&ct(Co(r),(t=>t==oe.prototype||H(Co(t))),(()=>!0)),Zn=oe.keys,je=oe.freeze,ta=(r=[])=>oe.fromEntries(r),ii=(r,t)=>t in r,zo=(r,t)=>(delete r[t],r),ea=(r,t)=>Bt(jo(r),(([e,i])=>t(i,e))),Vt=(r,t)=>ta(((e,i)=>fe(jo(e),(([s,o])=>i(o,s))))(r,((e,i)=>[i,t(e,i)]))),zt=r=>Zi(r)&&(t=>Ot(Zn(t)))(r)==0;var ee=(r,t,e,i=0)=>H(r)||!Zi(r)||!i&&zt(r)||Qn(r)?(e?.(),!1):(ea(r,((s,o)=>{t(s,o)||zo(r,o)})),!!i||!zt(r)),C=r=>new Map(r),pe=r=>[...r?.keys()??[]],v=(r,t)=>r?.get(t),bt=(r,t)=>j(r,((e,i)=>t(i,e))),T=(r,t,e)=>H(e)?(Nt(r,t),r):r?.set(t,e),dt=(r,t,e,i)=>(ht(r,t)?i?.(v(r,t)):T(r,t,e()),v(r,t)),he=(r,t,e,i=T)=>(Vt(t,((s,o)=>e(r,o,s))),bt(r,(s=>ii(t,s)?0:i(r,s))),r),Lt=(r,t,e,i)=>{let s={};return j(r,((o,n)=>{if(!e?.(o,n)){let c=t?t(o,n):o;i?.(c)||(s[n]=c)}})),s},qr=(r,t,e)=>Lt(r,(i=>Lt(i,t,e)),z,zt),Gi=(r,t,e)=>Lt(r,(i=>qr(i,t,e)),z,zt),ie=(r,t)=>{let e=C();return j(r,((i,s)=>e.set(s,t?.(i)??i))),e},Xr=r=>ie(r,ie),zr=r=>ie(r,Xr),oi=(r,t,e,i,s=0)=>ct((e?dt:v)(r,t[s],s>Ot(t)-2?e:C),(o=>{if(s>Ot(t)-2)return i?.(o)&&T(r,t[s]),o;let n=oi(o,t,e,i,s+1);return z(o)&&T(r,t[s]),n})),yt=r=>new Set(Oe(r)||H(r)?r:[r]),ft=(r,t)=>r?.add(t),ir=(r,t,e,i,s)=>{let o=r.hasRow,n=C(),c=C(),l=C(),d=C(),u=C(),h=C(),g=(x,w,...A)=>{let k=dt(h,x,yt);return Bt(A,(R=>ft(k,R)&&w&&r.callListener(R))),A},m=(x,...w)=>ct(v(h,x),(A=>{Bt(si(w)?Ue(A):w,(k=>{r.delListener(k),Nt(A,k)})),z(A)&&T(h,x)})),E=(x,w)=>{T(n,x,w),ht(c,x)||(T(c,x,t()),T(d,x,C()),T(u,x,C()),s(l))},D=x=>{T(n,x),T(c,x),T(d,x),T(u,x),m(x),s(l)};return[()=>r,()=>pe(n),x=>bt(c,x),x=>ht(c,x),x=>v(n,x),x=>v(c,x),(x,w)=>T(c,x,w),E,(x,w,A,k,R)=>{E(x,w);let U=C(),P=C(),y=v(d,x),B=v(u,x),_=N=>{let V=lt=>r.getCell(w,N,lt),et=v(y,N),nt=o(w,N)?e(k(V,N)):void 0;if(et===nt||Oe(et)&&Oe(nt)&&Oo(et,nt)||T(U,N,[et,nt]),!H(R)){let lt=v(B,N),q=o(w,N)?R(V,N):void 0;lt!=q&&T(P,N,q)}},G=N=>{A((()=>{j(U,(([,V],et)=>T(y,et,V))),j(P,((V,et)=>T(B,et,V)))}),U,P,y,B,N),Te(U),Te(P)};bt(y,_),r.hasTable(w)&&Bt(r.getRowIds(w),(N=>{ht(y,N)||_(N)})),G(!0),m(x),g(x,0,r.addRowListener(w,null,((N,V,et)=>_(et))),r.addTableListener(w,(()=>G())))},D,x=>i(x,l),()=>bt(h,D),g,m]},tr=(r,t)=>Yn(r)?e=>e(r):r??(()=>t??""),ai=(r,t)=>{let e=new WeakMap;return i=>{e.has(i)||e.set(i,r(i));let s=e.get(i);return t?.(s),s}},ia=/^\d+$/,No=()=>{let r=[],t=0;return[e=>(e?Fo(r):null)??""+t++,e=>{ia.test(e)&&Ot(r)<1e3&&Rt(r,e)}]},ci=r=>{let t,[e,i]=No(),s=C();return[(o,n,c,l=[],d=()=>[])=>{t??=r();let u=e(1);return T(s,u,[o,n,c,l,d]),ft(oi(n,c??[""],yt),u),u},(o,n,...c)=>Bt(((l,d=[""])=>{let u=[],h=(g,m)=>m==Ot(d)?Rt(u,g):d[m]===null?j(g,(E=>h(E,m+1))):Bt([d[m],null],(E=>h(v(g,E),m+1)));return h(l,0),u})(o,n),(l=>j(l,(d=>v(s,d)[0](t,...n??[],...c))))),o=>ct(v(s,o),(([,n,c])=>(oi(n,c??[""],void 0,(l=>(Nt(l,o),z(l)?1:0))),T(s,o),i(o),c))),o=>ct(v(s,o),(([n,,c=[],l,d])=>{let u=(...h)=>{let g=Ot(h);g==Ot(c)?n(t,...h,...d(h)):H(c[g])?Bt(l[g]?.(...h)??[],(m=>u(...h,m))):u(...h,c[g])};u()}))]},dc=ai((r=>{let t,e,i,s=100,o=C(),n=C(),c=1,l=C(),d=C(),[u,h,g]=ci((()=>q)),m=C(),E=C(),D=[],x=[],w=(I,F)=>{c=0,r.transaction((()=>{let[rt,Q]=v(m,F);j(rt,((O,W)=>j(O,((X,Z)=>j(X,((K,J)=>Qi(r,W,Z,J,K[I]))))))),j(Q,((O,W)=>Kr(r,W,O[I])))})),c=1},A=I=>{T(m,I),T(E,I),h(d,[I])},k=(I,F)=>Bt(((rt,Q)=>rt.splice(0,Q))(I,F??Ot(I)),A),R=()=>k(D,Ot(D)-s),U=()=>ct(t,(()=>{Rt(D,t),R(),k(x),t=void 0,i=1})),P=()=>{t=Eo(D),i=1},y,B,_=(I="")=>(H(t)&&(t=""+e++,T(m,t,[o,n]),nt(t,I),o=C(),n=C(),i=1),t),G=()=>{si(D)||(((I,...F)=>{I.unshift(...F)})(x,_()),w(0,t),t=Eo(D),i=1)},N=()=>{si(x)||(Rt(D,t),t=Fo(x),w(1,t),i=1)},V=()=>{i&&(h(l),i=0)},et=I=>{let F=_(I);return V(),F},nt=(I,F)=>(lt(I)&&v(E,I)!==F&&(T(E,I,F),h(d,[I])),q),lt=I=>ht(m,I),q={setSize:I=>(s=I,R(),q),addCheckpoint:et,setCheckpoint:nt,getStore:()=>r,getCheckpointIds:()=>[[...D],t,[...x]],forEachCheckpoint:I=>bt(E,I),hasCheckpoint:lt,getCheckpoint:I=>v(E,I),goBackward:()=>(G(),V(),q),goForward:()=>(N(),V(),q),goTo:I=>{let F=Wr(D,I)?G:Wr(x,I)?N:null;for(;!H(F)&&I!=t;)F();return V(),q},addCheckpointIdsListener:I=>u(I,l),addCheckpointListener:(I,F)=>u(F,d,[I]),delListener:I=>(g(I),q),clear:()=>(k(D),k(x),H(t)||A(t),t=void 0,e=0,et(),q),clearForward:()=>(si(x)||(k(x),h(l)),q),destroy:()=>{r.delListener(y),r.delListener(B)},getListenerStats:()=>({checkpointIds:ue(l),checkpoint:ue(d)}),_registerListeners:()=>{y=r.addCellListener(null,null,null,((I,F,rt,Q,O,W)=>{if(c){U();let X=dt(o,F,C),Z=dt(X,rt,C),K=dt(Z,Q,(()=>[W,void 0]));K[1]=O,K[0]===O&&z(T(Z,Q))&&z(T(X,rt))&&z(T(o,F))&&P(),V()}})),B=r.addValueListener(null,((I,F,rt,Q)=>{if(c){U();let O=dt(n,F,(()=>[Q,void 0]));O[1]=rt,O[0]===rt&&z(T(n,F))&&P(),V()}}))}};return je(q.clear())}),(r=>r._registerListeners())),ra=Xn("-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"),hc=C(fe(ra,((r,t)=>[r,t])));var pc=_r.crypto?r=>_r.crypto.getRandomValues(r):r=>fe(r,(()=>Jn(256*er.random())));var sa=JSON.stringify,Nr=JSON.parse,Re=r=>sa(r,((t,e)=>{return i=Map,e instanceof i?oe.fromEntries([...e]):e;var i})),fc=new _r.TextEncoder;var uc=2**36,gc=2**30,mc=2**24,bc=2**18;var $o=(r,t)=>(r??0)<(t??0)?-1:1,yc=ai((r=>{let t=C(),e=C(),[i,s,o]=ci((()=>A)),[n,c,l,d,u,h,g,,m,E,D,x]=ir(r,C,(k=>H(k)?"":Oe(k)?fe(k,at):at(k)),i,s),w=(k,R,U)=>{let P=u(k);j(U,((y,B)=>R(B,(_=>j(y,(G=>_(G,(N=>r.forEachCell(P,G,N)))))))))},A={setIndexDefinition:(k,R,U,P,y,B=$o)=>{let _=H(y)?void 0:([G],[N])=>y(G,N);return m(k,R,((G,N,V,et,nt,lt)=>{let q=0,I=yt(),F=yt(),rt=h(k);if(j(N,(([Q,O],W)=>{let X=yt(Q),Z=yt(O);j(X,(K=>Nt(Z,K)?Nt(X,K):0)),j(X,(K=>{ft(I,K),ct(v(rt,K),(J=>{Nt(J,W),z(J)&&(T(rt,K),q=1)}))})),j(Z,(K=>{ft(I,K),ht(rt,K)||(T(rt,K,yt()),q=1),ft(v(rt,K),W),H(P)||ft(F,K)}))})),G(),z(nt)||(lt?bt(rt,(Q=>ft(F,Q))):bt(V,(Q=>ct(v(et,Q),(O=>Bt(Oe(O)?O:[O],(W=>ft(F,W))))))),j(F,(Q=>{let O=(X,Z)=>B(v(nt,X),v(nt,Z),Q),W=[...v(rt,Q)];ko(W,O)||(T(rt,Q,yt(Gr(W,O))),ft(I,Q))}))),(q||lt)&&!H(_)){let Q=[...rt];ko(Q,_)||(g(k,C(Gr(Q,_))),q=1)}q&&s(t,[k]),j(I,(Q=>s(e,[k,Q])))}),tr(U),ct(P,tr)),A},delIndexDefinition:k=>(E(k),A),getStore:n,getIndexIds:c,forEachIndex:k=>l(((R,U)=>k(R,(P=>w(R,P,U))))),forEachSlice:(k,R)=>w(k,R,h(k)),hasIndex:d,hasSlice:(k,R)=>ht(h(k),R),getTableId:u,getSliceIds:k=>pe(h(k)),getSliceRowIds:(k,R)=>Ue(v(h(k),R)),addIndexIdsListener:D,addSliceIdsListener:(k,R)=>i(R,t,[k]),addSliceRowIdsListener:(k,R,U)=>i(U,e,[k,R]),delListener:k=>(o(k),A),destroy:x,getListenerStats:()=>({sliceIds:ue(t),sliceRowIds:Wt(e)})};return je(A)}));var Ki=r=>[r,r],gt=(r,t=ue)=>t(r[0])+t(r[1]),mt=()=>[C(),C()],Do=r=>[...r],qi=([r,t])=>r===t,ei=(r,t,e)=>T(r,t,v(r,t)==-e?void 0:e),li=()=>{let r,t,e=!1,i=!1,s=0,o=[],n=C(),c=C(),l=C(),d=C(),u=C(),h=C(),g=C(),m=C(),E=C(),D=C(),x=C(),w=C(),A=C(),k=C(),R=yt(),U=C(),P=C(),y=C(),B=C(),_=mt(),G=mt(),N=mt(),V=mt(),et=mt(),nt=mt(),lt=mt(),q=mt(),I=mt(),F=mt(),rt=mt(),Q=mt(),O=mt(),W=mt(),X=mt(),Z=mt(),K=mt(),J=mt(),M=mt(),ot=mt(),pt=mt(),It=mt(),kt=C(),Pt=mt(),[vt,it,Tt,Yt]=ci((()=>Et)),Qt=a=>{if(!ee(a,((f,b)=>Wr([Wi,le],b))))return!1;let p=a[Wi];return!(!To(p)&&p!=Io)&&(Be(a[le])!=p&&zo(a,le),!0)},Dr=Oe,Ai=(a,p)=>(!r||ht(x,p)||Zt(p))&&ee(a,((f,b)=>ce(p,b,f)),(()=>Zt(p))),ce=(a,p,f,b)=>ee(b?f:Ts(f,a,p),((S,L)=>ct(Ii(a,p,L,S),($=>(f[L]=$,!0)),(()=>!1))),(()=>Zt(a,p))),Ii=(a,p,f,b)=>r?ct(v(v(x,a),f),(S=>Be(b)!=S[Wi]?Zt(a,p,f,b,S[le]):b),(()=>Zt(a,p,f,b))):H(Be(b))?Zt(a,p,f,b):b,Je=(a,p)=>ee(p?a:Hn(a),((f,b)=>ct(Bs(b,f),(S=>(a[b]=S,!0)),(()=>!1))),(()=>Qe())),Bs=(a,p)=>t?ct(v(A,a),(f=>Be(p)!=f[Wi]?Qe(a,p,f[le]):p),(()=>Qe(a,p))):H(Be(p))?Qe(a,p):p,Ts=(a,p,f)=>(ct(v(w,p),(([b,S])=>{j(b,((L,$)=>{ii(a,$)||(a[$]=L)})),j(S,(L=>{ii(a,L)||Zt(p,f,L)}))})),a),Hn=a=>(t&&(j(k,((p,f)=>{ii(a,f)||(a[f]=p)})),j(R,(p=>{ii(a,p)||Qe(p)}))),a),Ms=a=>he(x,a,((p,f,b)=>{let S=C(),L=yt();he(dt(x,f,C),b,(($,Y,tt)=>{T($,Y,tt),ct(tt[le],(Ht=>T(S,Y,Ht)),(()=>ft(L,Y)))})),T(w,f,[S,L])}),((p,f)=>{T(x,f),T(w,f)})),Os=a=>he(A,a,((p,f,b)=>{T(A,f,b),ct(b[le],(S=>T(k,f,S)),(()=>ft(R,f)))}),((p,f)=>{T(A,f),T(k,f),Nt(R,f)})),Us=a=>zt(a)?$i():zi(a),Fs=a=>he(y,a,((p,f,b)=>Li(f,b)),((p,f)=>$s(f))),Li=(a,p)=>he(dt(y,a,(()=>(Ws(a,1),T(U,a,No()),T(P,a,C()),C()))),p,((f,b,S)=>Ye(a,f,b,S)),((f,b)=>Hs(a,f,b))),Ye=(a,p,f,b,S)=>he(dt(p,f,(()=>(Gs(a,f,1),C()))),b,((L,$,Y)=>Ar(a,f,L,$,Y)),((L,$)=>_s(a,p,f,L,$,S))),Ar=(a,p,f,b,S)=>{ht(f,b)||Ks(a,p,b,1);let L=v(f,b);S!==L&&(qs(a,p,b,L,S),T(f,b,S))},js=(a,p,f,b,S)=>ct(v(p,f),(L=>Ar(a,f,L,b,S)),(()=>Ye(a,p,f,Ts({[b]:S},a,f)))),zs=a=>zt(a)?Hi():Ni(a),Ns=a=>he(B,a,((p,f,b)=>Ri(f,b)),((p,f)=>Vs(f))),Ri=(a,p)=>{ht(B,a)||Xs(a,1);let f=v(B,a);p!==f&&(Js(a,f,p),T(B,a,p))},Bi=a=>v(y,a)??Li(a,{}),$s=a=>Li(a,{}),Hs=(a,p,f)=>{let[,b]=v(U,a);b(f),Ye(a,p,f,{},!0)},_s=(a,p,f,b,S,L)=>{let $=v(v(w,a)?.[0],S);if(!H($)&&!L)return Ar(a,f,b,S,$);let Y=tt=>{qs(a,f,tt,v(b,tt)),Ks(a,f,tt,-1),T(b,tt)};H($)?Y(S):bt(b,Y),z(b)&&(Gs(a,f,-1),z(T(p,f))&&(Ws(a,-1),T(y,a),T(U,a),T(P,a)))},Vs=a=>{let p=v(k,a);if(!H(p))return Ri(a,p);Js(a,v(B,a)),Xs(a,-1),T(B,a)},Ws=(a,p)=>ei(n,a,p),Gs=(a,p,f)=>ei(dt(d,a,C),p,f)&&T(l,a,dt(l,a,(()=>0))+f),Ks=(a,p,f,b)=>{let S=v(P,a),L=v(S,f)??0;(L==0&&b==1||L==1&&b==-1)&&ei(dt(c,a,C),f,b),T(S,f,L!=-b?L+b:null),ei(dt(dt(u,a,C),p,C),f,b)},qs=(a,p,f,b,S)=>{dt(dt(dt(h,a,C),p,C),f,(()=>[b,0]))[1]=S,o[3]?.(a,p,f,S)},Xs=(a,p)=>ei(g,a,p),Js=(a,p,f)=>{dt(m,a,(()=>[p,0]))[1]=f,o[4]?.(a,f)},Zt=(a,p,f,b,S)=>(Rt(dt(dt(dt(E,a,C),p,C),f,(()=>[])),b),S),Qe=(a,p,f)=>(Rt(dt(D,a,(()=>[])),p),f),Ti=(a,p,f)=>ct(v(v(v(h,a),p),f),(([b,S])=>[!0,b,S]),(()=>[!1,...Ki(Oi(a,p,f))])),Ys=a=>ct(v(m,a),(([p,f])=>[!0,p,f]),(()=>[!1,...Ki(Ui(a))])),Qs=a=>z(E)||z(Z[a])?0:j(a?zr(E):E,((p,f)=>j(p,((b,S)=>j(b,((L,$)=>it(Z[a],[f,S,$],L))))))),Zs=a=>z(D)||z(K[a])?0:j(a?ie(D):D,((p,f)=>it(K[a],[f],p))),Ze=(a,p,f,b)=>{if(!z(a))return it(p,b,(()=>Lt(a))),bt(a,((S,L)=>it(f,[...b??[],S],L==1))),1},to=a=>{let p=Fi();p!=e&&it(_[a],void 0,p);let f=z(F[a]),b=z(O[a])&&z(W[a])&&z(I[a])&&z(rt[a])&&z(nt[a])&&z(lt[a])&&z(q[a])&&f&&z(N[a])&&z(V[a]),S=z(X[a])&&z(Q[a])&&z(et[a])&&z(G[a]);if(!b||!S){let L=a?[ie(n),Xr(c),ie(l),Xr(d),zr(u),zr(h)]:[n,c,l,d,u,h];if(!b){Ze(L[0],N[a],V[a]),j(L[1],((Y,tt)=>Ze(Y,nt[a],lt[a],[tt]))),j(L[2],((Y,tt)=>{Y!=0&&it(q[a],[tt],so(tt))}));let $=yt();j(L[3],((Y,tt)=>{Ze(Y,I[a],rt[a],[tt])&&!f&&(it(F[a],[tt,null]),ft($,tt))})),f||j(L[5],((Y,tt)=>{if(!ht($,tt)){let Ht=yt();j(Y,(te=>j(te,(([_i,Vi],ti)=>Vi!==_i?ft(Ht,ti):Nt(te,ti))))),j(Ht,(te=>it(F[a],[tt,te])))}})),j(L[4],((Y,tt)=>j(Y,((Ht,te)=>Ze(Ht,O[a],W[a],[tt,te])))))}if(!S){let $;j(L[5],((Y,tt)=>{let Ht;j(Y,((te,_i)=>{let Vi;j(te,(([ti,wo],_n)=>{wo!==ti&&(it(X[a],[tt,_i,_n],wo,ti,Ti),$=Ht=Vi=1)})),Vi&&it(Q[a],[tt,_i],Ti)})),Ht&&it(et[a],[tt],Ti)})),$&&it(G[a],void 0,Ti)}}},eo=a=>{let p=ji();p!=i&&it(J[a],void 0,p);let f=z(ot[a])&&z(pt[a]),b=z(It[a])&&z(M[a]);if(!f||!b){let S=a?[ie(g),ie(m)]:[g,m];if(f||Ze(S[0],ot[a],pt[a]),!b){let L;j(S[1],(([$,Y],tt)=>{Y!==$&&(it(It[a],[tt],Y,$,Ys),L=1)})),L&&it(M[a],void 0,Ys)}}},ut=(a,...p)=>(Mr((()=>a(...fe(p,at)))),Et),io=(a,p,f,b,S)=>{let L=Mi(a,p,...f);return vt((()=>{let $=Mi(a,p,...f);Oo($,L)||(L=$,b(Et,a,p,...f,L))}),F[S?1:0],[a,p],[Mt])},Ir=()=>Gi(y),Mt=()=>pe(y),ro=a=>pe(v(P,at(a))),so=a=>Fe(v(y,at(a))),Ie=a=>pe(v(y,at(a))),Mi=(a,p,f,b=0,S)=>{return Zi(a)?Mi(a.tableId,a.cellId,a.descending,a.offset,a.limit):fe(Vr(Gr((L=v(y,at(a)),$=(Y,tt)=>[H(p)?tt:v(Y,at(p)),tt],fe([...L?.entries()??[]],(([Y,tt])=>$(tt,Y)))),(([Y],[tt])=>$o(Y,tt)*(f?-1:1))),b,H(S)?S:b+S),(([,Y])=>Y));var L,$},Lr=(a,p)=>pe(v(v(y,at(a)),at(p))),Oi=(a,p,f)=>v(v(v(y,at(a)),at(p)),at(f)),Rr=()=>Lt(B),Br=()=>pe(B),Ui=a=>v(B,at(a)),Fi=()=>!z(y),oo=a=>ht(y,at(a)),no=(a,p)=>ht(v(P,at(a)),at(p)),ao=(a,p)=>ht(v(y,at(a)),at(p)),co=(a,p,f)=>ht(v(v(y,at(a)),at(p)),at(f)),ji=()=>!z(B),lo=a=>ht(B,at(a)),zi=a=>ut((()=>(p=>ee(p,Ai,Zt))(a)?Fs(a):0)),Ni=a=>ut((()=>Je(a)?Ns(a):0)),ho=a=>(Fr((()=>Us(Nr(a)))),Et),po=a=>ut((()=>{if((r=ee(a,(p=>ee(p,Qt))))&&(Ms(a),!z(y))){let p=Ir();$i(),zi(p)}})),fo=a=>ut((()=>{if(t=(p=>ee(p,Qt))(a)){let p=Rr();Tr(),Hi(),t=!0,Os(a),Ni(p)}})),$i=()=>ut((()=>Fs({}))),uo=a=>ut((p=>ht(y,p)?$s(p):0),a),go=(a,p)=>ut(((f,b)=>ct(v(y,f),(S=>ht(S,b)?Hs(f,S,b):0))),a,p),Hi=()=>ut((()=>Ns({}))),mo=()=>ut((()=>{Ms({}),r=!1})),Tr=()=>ut((()=>{Os({}),t=!1})),Mr=(a,p)=>{if(s!=-1){bo();let f=a();return yo(p),f}},bo=()=>(s!=-1&&s++,s==1&&(o[0]?.(),it(kt)),Et),yo=a=>(s>0&&(s--,s==0&&(s=1,Qs(1),z(h)||to(1),Zs(1),z(m)||eo(1),a?.(Et)&&(j(h,((p,f)=>j(p,((b,S)=>j(b,(([L],$)=>Qi(Et,f,S,$,L))))))),Te(h),j(m,(([p],f)=>Kr(Et,f,p))),Te(m)),it(Pt[0],void 0),s=-1,Qs(0),z(h)||to(0),Zs(0),z(m)||eo(0),o[1]?.(),it(Pt[1],void 0),o[2]?.(),s=0,e=Fi(),i=ji(),Bt([n,c,l,d,u,h,E,g,m,D],Te))),Et),Et={getContent:()=>[Ir(),Rr()],getTables:Ir,getTableIds:Mt,getTable:a=>qr(v(y,at(a))),getTableCellIds:ro,getRowCount:so,getRowIds:Ie,getSortedRowIds:Mi,getRow:(a,p)=>Lt(v(v(y,at(a)),at(p))),getCellIds:Lr,getCell:Oi,getValues:Rr,getValueIds:Br,getValue:Ui,hasTables:Fi,hasTable:oo,hasTableCell:no,hasRow:ao,hasCell:co,hasValues:ji,hasValue:lo,getTablesJson:()=>Re(y),getValuesJson:()=>Re(B),getJson:()=>Re([y,B]),getTablesSchemaJson:()=>Re(x),getValuesSchemaJson:()=>Re(A),getSchemaJson:()=>Re([x,A]),hasTablesSchema:()=>r,hasValuesSchema:()=>t,setContent:a=>ut((()=>{let p=jt(a)?a():a;Dr(p)&&(([f,b])=>{(zt(f)?$i:zi)(f),(zt(b)?Hi:Ni)(b)})(p)})),setTables:zi,setTable:(a,p)=>ut((f=>Ai(p,f)?Li(f,p):0),a),setRow:(a,p,f)=>ut(((b,S)=>ce(b,S,f)?Ye(b,Bi(b),S,f):0),a,p),addRow:(a,p,f=!0)=>Mr((()=>{let b;return ce(a,b,p)&&(a=at(a),Ye(a,Bi(a),b=((S,L)=>{let[$]=v(U,S),Y;do Y=$(L);while(ht(v(y,S),Y));return Y})(a,f?1:0),p)),b})),setPartialRow:(a,p,f)=>ut(((b,S)=>{if(ce(b,S,f,1)){let L=Bi(b);Vt(f,(($,Y)=>js(b,L,S,Y,$)))}}),a,p),setCell:(a,p,f,b)=>ut(((S,L,$)=>ct(Ii(S,L,$,jt(b)?b(Oi(S,L,$)):b),(Y=>js(S,Bi(S),L,$,Y)))),a,p,f),setValues:Ni,setPartialValues:a=>ut((()=>Je(a,1)?Vt(a,((p,f)=>Ri(f,p))):0)),setValue:(a,p)=>ut((f=>ct(Bs(f,jt(p)?p(Ui(f)):p),(b=>Ri(f,b)))),a),applyChanges:a=>ut((()=>{Vt(a[0],((p,f)=>H(p)?uo(f):Vt(p,((b,S)=>H(b)?go(f,S):Vt(b,((L,$)=>Qi(Et,f,S,$,L))))))),Vt(a[1],((p,f)=>Kr(Et,f,p)))})),setTablesJson:ho,setValuesJson:a=>(Fr((()=>zs(Nr(a)))),Et),setJson:a=>ut((()=>Fr((()=>{let[p,f]=Nr(a);Us(p),zs(f)}),(()=>ho(a))))),setTablesSchema:po,setValuesSchema:fo,setSchema:(a,p)=>ut((()=>{po(a),fo(p)})),delTables:$i,delTable:uo,delRow:go,delCell:(a,p,f,b)=>ut(((S,L,$)=>ct(v(y,S),(Y=>ct(v(Y,L),(tt=>ht(tt,$)?_s(S,Y,L,tt,$,b):0))))),a,p,f),delValues:Hi,delValue:a=>ut((p=>ht(B,p)?Vs(p):0),a),delTablesSchema:mo,delValuesSchema:Tr,delSchema:()=>ut((()=>{mo(),Tr()})),transaction:Mr,startTransaction:bo,getTransactionChanges:()=>[Lt(h,((a,p)=>v(n,p)===-1?void 0:Lt(a,((f,b)=>v(v(d,p),b)===-1?void 0:Lt(f,(([,S])=>S),(S=>qi(S)))),z,zt)),z,zt),Lt(m,(([,a])=>a),(a=>qi(a))),1],getTransactionLog:()=>[!z(h),!z(m),Gi(h,Do,qi),Gi(E),Lt(m,Do,qi),Lt(D),Lt(n),qr(d),Gi(u),Lt(g)],finishTransaction:yo,forEachTable:a=>j(y,((p,f)=>a(f,(b=>j(p,((S,L)=>b(L,($=>bt(S,$))))))))),forEachTableCell:(a,p)=>bt(v(P,at(a)),p),forEachRow:(a,p)=>j(v(y,at(a)),((f,b)=>p(b,(S=>bt(f,S))))),forEachCell:(a,p,f)=>bt(v(v(y,at(a)),at(p)),f),forEachValue:a=>bt(B,a),addSortedRowIdsListener:(a,p,f,b,S,L,$)=>Zi(a)?io(a.tableId,a.cellId,[a.descending??!1,a.offset??0,a.limit],p,f):io(a,p,[f,b,S],L,$),addStartTransactionListener:a=>vt(a,kt),addWillFinishTransactionListener:a=>vt(a,Pt[0]),addDidFinishTransactionListener:a=>vt(a,Pt[1]),callListener:a=>(Yt(a),Et),delListener:a=>(Tt(a),Et),getListenerStats:()=>({hasTables:gt(_),tables:gt(G),tableIds:gt(N),hasTable:gt(V),table:gt(et),tableCellIds:gt(nt),hasTableCell:gt(lt,Wt),rowCount:gt(q),rowIds:gt(I),sortedRowIds:gt(F),hasRow:gt(rt,Wt),row:gt(Q,Wt),cellIds:gt(O,Wt),hasCell:gt(W,jr),cell:gt(X,jr),invalidCell:gt(Z,jr),hasValues:gt(J),values:gt(M),valueIds:gt(ot),hasValue:gt(pt),value:gt(It),invalidValue:gt(K),transaction:ue(kt)+gt(Pt)}),isMergeable:()=>!1,createStore:li,addListener:vt,callListeners:it,setInternalListeners:(a,p,f,b,S)=>o=[a,p,f,b,S]};return Vt({[de+vo]:[0,_,[],()=>[Fi()]],[vo]:[0,G],[Gn]:[0,N],[de+re]:[1,V,[Mt],a=>[oo(...a)]],[re]:[1,et,[Mt]],[re+Xi]:[1,nt,[Mt]],[de+re+ri]:[2,lt,[Mt,ro],a=>[no(...a)]],[Lo]:[1,q,[Mt]],[Ro]:[1,I,[Mt]],[de+Me]:[2,rt,[Mt,Ie],a=>[ao(...a)]],[Me]:[2,Q,[Mt,Ie]],[Xi]:[2,O,[Mt,Ie]],[de+ri]:[3,W,[Mt,Ie,Lr],a=>[co(...a)]],[ri]:[3,X,[Mt,Ie,Lr],a=>Ki(Oi(...a))],InvalidCell:[3,Z],[de+So]:[0,J,[],()=>[ji()]],[So]:[0,M],[qn]:[0,ot],[de+Ji]:[1,pt,[Br],a=>[lo(...a)]],[Ji]:[1,It,[Br],a=>Ki(Ui(a[0]))],InvalidValue:[1,K]},(([a,p,f,b],S)=>{Et[Hr+S+$r]=(...L)=>vt(L[a],p[L[a+1]?1:0],a>0?Vr(L,0,a):void 0,f,b)})),je(Et)};var Jr=C([["avg",[(r,t)=>Po(r)/t,(r,t,e)=>r+(t-r)/(e+1),(r,t,e)=>r+(r-t)/(e-1),(r,t,e,i)=>r+(t-e)/i]],["max",[r=>Or(...r),(r,t)=>Or(t,r),(r,t)=>t==r?void 0:r,(r,t,e)=>e==r?void 0:Or(t,r)]],["min",[r=>Ur(...r),(r,t)=>Ur(t,r),(r,t)=>t==r?void 0:r,(r,t,e)=>e==r?void 0:Ur(t,r)]],["sum",[r=>Po(r),(r,t)=>r+t,(r,t)=>r-t,(r,t,e)=>r-e+t]]]),Ho=(r,t,e,i,s,o=!1)=>{if(z(e))return;let[n,c,l,d]=s;return o||=H(r),j(i,(([u,h])=>{o||(r=H(u)?c?.(r,h,t++):H(h)?l?.(r,u,t--):d?.(r,h,u,t),o||=H(r))})),o?n(Ue(e),Fe(e)):r},wc=ai((r=>{let t=C(),[e,i,s]=ci((()=>x)),[o,n,c,l,d,u,h,,g,m,E,D]=ir(r,Mo,(w=>isNaN(w)||H(w)||w===!0||w===!1||w===""?void 0:1*w),e,i),x={setMetricDefinition:(w,A,k,R,U,P,y)=>{let B=jt(k)?[k,U,P,y]:v(Jr,k)??v(Jr,"sum");return g(w,A,((_,G,N,V,et,nt)=>{let lt=u(w),q=Fe(V);nt||=H(lt),_();let I=Ho(lt,q,V,G,B,nt);Bo(I)||(I=void 0),I!=lt&&(h(w,I),i(t,[w],I,lt))}),tr(R,1)),x},delMetricDefinition:w=>(m(w),x),getStore:o,getMetricIds:n,forEachMetric:c,hasMetric:l,getTableId:d,getMetric:u,addMetricIdsListener:E,addMetricListener:(w,A)=>e(A,t,[w]),delListener:w=>(s(w),x),destroy:D,getListenerStats:()=>({metric:ue(t)})};return je(x)})),xc=ai((r=>{let t=r.createStore,e=t(),i=t(),s=C(),{addListener:o,callListeners:n,delListener:c}=i,[l,d,u,h,g,,,m,,E,D,x,w,A]=ir(r,(()=>!0),Mo,o,n),k=(y,B,..._)=>Bt(_,(G=>ft(dt(dt(s,B,C),y,yt),G))),R=y=>{ct(v(s,y),(B=>{bt(B,((_,G)=>j(G,(N=>_.delListener(N))))),Te(B)})),Bt([i,e],(B=>B.delTable(y)))},U=(y,B,_)=>k(B,y,B.addStartTransactionListener(_.startTransaction),B.addDidFinishTransactionListener((()=>_.finishTransaction()))),P={setQueryDefinition:(y,B,_)=>{m(y,B),R(y);let G=[],N=[[null,[B,null,null,[],C()]]],V=[],et=[],nt=[];_({select:(O,W)=>{let X=jt(O)?[Ot(G)+"",O]:[H(W)?O:W,Z=>Z(O,W)];return Rt(G,X),{as:Z=>X[0]=Z}},join:(O,W,X)=>{let Z=H(X)||jt(W)?null:W,K=H(Z)?W:X,J=[O,[O,Z,jt(K)?K:M=>M(K),[],C()]];return Rt(N,J),{as:M=>J[0]=M}},where:(O,W,X)=>Rt(V,jt(O)?O:H(X)?Z=>Z(O)===W:Z=>Z(O,W)===X),group:(O,W,X,Z,K)=>{let J=[O,[O,jt(W)?[W,X,Z,K]:v(Jr,W)??[(M,ot)=>ot]]];return Rt(et,J),{as:M=>J[0]=M}},having:(O,W)=>Rt(nt,jt(O)?O:X=>X(O)===W)});let lt=C(G);if(z(lt))return P;let q=C(N);bt(q,((O,[,W])=>ct(v(q,W),(({3:X})=>H(O)?0:Rt(X,O)))));let I=C(et),F=e;if(z(I)&&si(nt))F=i;else{U(y,F,i);let O=C();bt(I,((K,[J,M])=>ft(dt(O,J,yt),[K,M])));let W=yt();bt(lt,(K=>ht(O,K)?0:ft(W,K)));let X=C(),Z=(K,J,M,ot)=>ct(K,(([pt,It,kt,Pt])=>{bt(J,((vt,[it])=>{let Tt=dt(pt,vt,C),Yt=v(Tt,M),Qt=ot?void 0:it;if(Yt!==Qt){let Dr=yt([[Yt,Qt]]),Ai=Fe(Tt);T(Tt,M,Qt),j(v(O,vt),(([ce,Ii])=>{let Je=Ho(Pt[ce],Ai,Tt,Dr,Ii);Pt[ce]=H(Be(Je))?null:Je}))}})),z(It)||!Yi(nt,(vt=>vt((it=>Pt[it]))))?i.delRow(y,kt):H(kt)?K[2]=i.addRow(y,Pt):i.setRow(y,kt,Pt)}));k(F,y,F.addRowListener(y,null,((K,J,M,ot)=>{let pt=[],It=[],kt=C(),Pt=F.hasRow(y,M),vt=!Pt;j(W,(it=>{let[Tt,Yt,Qt]=ot(y,M,it);Rt(pt,Yt),Rt(It,Qt),vt||=Tt})),bt(O,(it=>{let[Tt,,Yt]=ot(y,M,it);(vt||Tt)&&T(kt,it,[Yt])})),vt&&Z(oi(X,pt,void 0,(([,it])=>(Nt(it,M),z(it)))),kt,M,1),Pt&&Z(oi(X,It,(()=>{let it={};return j(W,(Tt=>it[Tt]=F.getCell(y,M,Tt))),[C(),yt(),void 0,it]}),(([,it])=>{ft(it,M)})),kt,M)})))}U(y,r,F);let rt=(O,W,X,Z)=>{let K=J=>r.getCell(W,X,J);Bt(Z,(J=>{let[M,,ot,pt,It]=v(q,J),kt=ot?.(K,O),[Pt,vt]=v(It,O)??[];kt!=Pt&&(H(vt)||A(y,vt),T(It,O,H(kt)?null:[kt,...w(y,1,r.addRowListener(M,kt,(()=>rt(O,M,kt,pt))))]))})),(J=>{let M=(ot,pt)=>r.getCell(...H(pt)?[B,J,ot]:ot===B?[B,J,pt]:[v(q,ot)?.[0],v(v(q,ot)?.[4],J)?.[0],pt]);F.transaction((()=>Yi(V,(ot=>ot(M)))?bt(lt,((ot,pt)=>Qi(F,y,J,ot,pt(M,J)))):F.delRow(y,J)))})(O)},{3:Q}=v(q,null);return F.transaction((()=>w(y,1,r.addRowListener(B,null,((O,W,X)=>{r.hasRow(B,X)?rt(X,B,X,Q):(F.delRow(y,X),j(q,(({4:Z})=>ct(v(Z,X),(([,K])=>{A(y,K),T(Z,X)})))))}))))),P},delQueryDefinition:y=>(R(y),E(y),P),getStore:l,getQueryIds:d,forEachQuery:u,hasQuery:h,getTableId:g,addQueryIdsListener:y=>D((()=>y(P))),delListener:y=>(c(y),P),destroy:x,getListenerStats:()=>{let{tables:y,tableIds:B,transaction:_,...G}=i.getListenerStats();return G}};return Vt({[re]:[1,1],[re+Xi]:[0,1],[Lo]:[0,1],[Ro]:[0,1],[Kn]:[0,5],[Me]:[1,2],[Xi]:[0,2],[ri]:[1,3]},(([y,B],_)=>{Bt(y?["get","has","forEach"]:["get"],(G=>P[G+xo+_]=(...N)=>i[G+_](...N))),P[Hr+xo+_+$r]=(...G)=>i[Hr+_+$r](...Vr(G,0,B),((N,...V)=>G[B](P,...V)),!0)})),je(P)})),vc=ai((r=>{let t=C(),e=C(),i=C(),s=C(),[o,n,c]=ci((()=>U)),[l,d,u,h,g,m,,,E,D,x,w]=ir(r,(()=>[C(),C(),C(),C()]),(P=>H(P)?void 0:P+""),o,n),A=(P,y,B)=>ct(m(P),(([_,,G])=>{if(!ht(G,y)){let N=yt();if(g(P)!=R(P))ft(N,y);else{let V=y;for(;!H(V)&&!ht(N,V);)ft(N,V),V=v(_,V)}if(B)return N;T(G,y,N)}return v(G,y)})),k=(P,y)=>ct(m(P),(([,,B])=>T(B,y))),R=P=>v(t,P),U={setRelationshipDefinition:(P,y,B,_)=>(T(t,P,B),E(P,y,((G,N)=>{let V=yt(),et=yt(),nt=yt(),[lt,q]=m(P);j(N,(([I,F],rt)=>{H(I)||(ft(et,I),ct(v(q,I),(Q=>{Nt(Q,rt),z(Q)&&T(q,I)}))),H(F)||(ft(et,F),ht(q,F)||T(q,F,yt()),ft(v(q,F),rt)),ft(V,rt),T(lt,rt,F),bt(v(s,P),(Q=>{ht(A(P,Q),rt)&&ft(nt,Q)}))})),G(),j(V,(I=>n(e,[P,I]))),j(et,(I=>n(i,[P,I]))),j(nt,(I=>{k(P,I),n(s,[P,I])}))}),tr(_)),U),delRelationshipDefinition:P=>(T(t,P),D(P),U),getStore:l,getRelationshipIds:d,forEachRelationship:P=>u((y=>P(y,(B=>r.forEachRow(g(y),B))))),hasRelationship:h,getLocalTableId:g,getRemoteTableId:R,getRemoteRowId:(P,y)=>v(m(P)?.[0],y),getLocalRowIds:(P,y)=>Ue(v(m(P)?.[1],y)),getLinkedRowIds:(P,y)=>H(m(P))?[y]:Ue(A(P,y,!0)),addRelationshipIdsListener:x,addRemoteRowIdListener:(P,y,B)=>o(B,e,[P,y]),addLocalRowIdsListener:(P,y,B)=>o(B,i,[P,y]),addLinkedRowIdsListener:(P,y,B)=>(A(P,y),o(B,s,[P,y])),delListener:P=>(k(...c(P)??[]),U),destroy:w,getListenerStats:()=>({remoteRowId:Wt(e),localRowIds:Wt(i),linkedRowIds:Wt(s)})};return je(U)}));var Wo=Promise,oa=globalThis,_o=oa.window,na=1e3,aa=(r,t,e)=>setInterval(r,t*na),ca=clearInterval,$t=r=>r==null,ar=(r,t,e)=>$t(r)?e?.():t(r),Zr=r=>Array.isArray(r),me=r=>r.length,la=(r,t)=>r.test(t),Go=r=>new Wo(r),Ko=async r=>Wo.all(r),qo=r=>{throw new Error(r)},ge=async(r,t,e)=>{try{return await r()}catch(i){t?.(i)}},ts=(r,t)=>r.forEach(t),di=(r,t)=>r.map(t),da=(r,t)=>r.splice(0,t),cr=(r,...t)=>r.push(...t),Xo=r=>r.shift(),ze=Object,Vo=r=>ze.getPrototypeOf(r),ha=ze.entries,pa=r=>!$t(r)&&ar(Vo(r),t=>t==ze.prototype||$t(Vo(t)),()=>!0),fa=ze.keys,ua=ze.freeze,ga=(r=[])=>ze.fromEntries(r),ma=(r,t)=>t in r,ba=(r,t)=>di(ha(r),([e,i])=>t(i,e)),ya=r=>me(fa(r)),rr=r=>pa(r)&&ya(r)==0,wa=r=>r?.size??0,xa=(r,t)=>r?.has(t)??!1,Jo=r=>$t(r)||wa(r)==0,Yo=(r,t)=>r?.forEach(t),Qo=(r,t)=>r?.delete(t),hi=r=>new Map(r),Ut=(r,t)=>r?.get(t),be=(r,t,e)=>$t(e)?(Qo(r,t),r):r?.set(t,e),es=(r,t,e,i)=>(xa(r,t)?i?.(Ut(r,t)):be(r,t,e()),Ut(r,t)),is=(r,t,e,i,s=0)=>ar((e?es:Ut)(r,t[s],s>me(t)-2?e:hi),o=>{if(s>me(t)-2)return i?.(o)&&be(r,t[s]),o;let n=is(o,t,e,i,s+1);return Jo(o)&&be(r,t[s]),n}),va=/^\d+$/,Sa=()=>{let r=[],t=0;return[e=>(e?Xo(r):null)??""+t++,e=>{la(va,e)&&me(r)<1e3&&cr(r,e)}]},ka=r=>new Set(Zr(r)||$t(r)?r:[r]),Pa=(r,t)=>r?.add(t),Ea=(r,t=[""])=>{let e=[],i=(s,o)=>o==me(t)?cr(e,s):t[o]===null?Yo(s,n=>i(n,o+1)):ts([t[o],null],n=>i(Ut(s,n),o+1));return i(r,0),e},Ca=r=>{let t,[e,i]=Sa(),s=hi();return[(o,n,c,l=[],d=()=>[])=>{t??=r();let u=e(1);return be(s,u,[o,n,c,l,d]),Pa(is(n,c??[""],ka),u),u},(o,n,...c)=>ts(Ea(o,n),l=>Yo(l,d=>Ut(s,d)[0](t,...n??[],...c))),o=>ar(Ut(s,o),([,n,c])=>(is(n,c??[""],void 0,l=>(Qo(l,o),Jo(l)?1:0)),be(s,o),i(o),c)),o=>ar(Ut(s,o),([n,,c=[],l,d])=>{let u=(...h)=>{let g=me(h);g==me(c)?n(t,...h,...d(h)):$t(c[g])?ts(l[g]?.(...h)??[],m=>u(...h,m)):u(...h,c[g])};u()})]},sr=hi(),or=hi(),Da=(r=1,t,e)=>r!=1&&t.isMergeable()?[1,t.getMergeableContent,()=>t.getTransactionMergeableChanges(!e),([[i],[s]])=>!rr(i)||!rr(s),t.setDefaultContent]:r!=2?[0,t.getContent,t.getTransactionChanges,([i,s])=>!rr(i)||!rr(s),t.setContent]:qo("Store type not supported by this Persister"),Aa=(r,t,e,i,s,o,n,c={},l=0,d=[])=>{let u=0,h=0,g=0,m,E,D;es(sr,d,()=>0),es(or,d,()=>[]);let x=hi(),[w,A,k,R,U]=Da(n,r,l),[P,y,B]=Ca(()=>J),_=M=>{M!=u&&(u=M,y(x,void 0,u))},G=async()=>{if(!Ut(sr,d)){for(be(sr,d,1);!$t(m=Xo(Ut(or,d)));)await ge(m,o);be(sr,d,0)}},N=M=>{(w&&Zr(M?.[0])?M?.[2]===1?r.applyMergeableChanges:r.setMergeableContent:M?.[2]===1?r.applyChanges:r.setContent)(M)},V=async M=>(u!=2&&(_(1),h++,await K(async()=>{await ge(async()=>{let ot=await t();Zr(ot)?N(ot):M?U(M):qo(`Content is not an array: ${ot}`)},()=>{M&&U(M)}),_(0)})),J),et=async M=>(nt(),await V(M),await ge(async()=>E=await i(async(ot,pt)=>{pt||ot?u!=2&&(_(1),h++,N(pt??ot),_(0)):await V()}),o),J),nt=async()=>(E&&(await ge(()=>s(E),o),E=void 0),J),lt=()=>!$t(E),q=async M=>(u!=1&&(_(2),g++,await K(async()=>{await ge(()=>e(A,M),o),_(0)})),J),I=async()=>(F(),await q(),D=r.addDidFinishTransactionListener(()=>{let M=k();R(M)&&q(M)}),J),F=async()=>(D&&(r.delListener(D),D=void 0),J),rt=()=>!$t(D),Q=async(M,ot=!1)=>{let[pt,It]=ot?[I,et]:[et,I];return await pt(M),await It(M),J},O=async(M=!1)=>{let[ot,pt]=M?[F,nt]:[nt,F];return await ot(),await pt(),J},W=()=>u,X=M=>P(M,x),Z=M=>(B(M),r),K=async(...M)=>(cr(Ut(or,d),...M),await G(),J),J={load:V,startAutoLoad:et,stopAutoLoad:nt,isAutoLoading:lt,save:q,startAutoSave:I,stopAutoSave:F,isAutoSaving:rt,startAutoPersisting:Q,stopAutoPersisting:O,getStatus:W,addStatusListener:X,delListener:Z,schedule:K,getStore:()=>r,destroy:()=>(da(Ut(or,d)),O()),getStats:()=>({loads:h,saves:g}),...c};return ua(J)},Qr=["t","v"],Ia={keyPath:"k"},La=async(r,t)=>{let e=ba(t,(i,s)=>nr(r,"put",{k:s,v:i}));di(await nr(r,"getAllKeys"),i=>ma(t,i)?0:cr(e,nr(r,"delete",i))),await Ko(e)},nr=async(r,t,e)=>Go((i,s)=>{let o=r[t](e);o.onsuccess=()=>i(o.result),o.onerror=()=>s(`objectStore.${t} error`)}),Zo=(r,t,e=1,i)=>{let s=async(o,n=[],c=0)=>Go((l,d)=>{let u=(_o?_o.indexedDB:indexedDB).open(t,c?2:void 0);u.onupgradeneeded=()=>c&&di(Qr,h=>ge(()=>u.result.createObjectStore(h,Ia))),u.onsuccess=()=>ge(async()=>{let h=u.result.transaction(Qr,"readwrite"),g=await Ko(di(Qr,(m,E)=>o(h.objectStore(m),n[E])));u.result.close(),l(g)},h=>{u.result.close(),d(h)}),u.onerror=()=>d("indexedDB.open error")});return Aa(r,async()=>await s(async o=>ga(di(await nr(o,"getAll"),({k:n,v:c})=>[n,c]))),o=>s((n,c)=>La(n,c),o(),1),o=>aa(o,e),o=>ca(o),i,1,{getDbName:()=>t})};var lr=class{#t;#r="blobs";#s=null;constructor(t="copio-blobs"){this.#t=t}async#l(){return this.#s?this.#s:(this.#s=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 s=i.result;s.objectStoreNames.contains(this.#r)||s.createObjectStore(this.#r)},i.onsuccess=()=>t(i.result),i.onerror=()=>e(i.error||new Error("Failed to open blob db"))}),this.#s)}async put(t,e){let i=await this.#l();return new Promise((s,o)=>{let l=i.transaction(this.#r,"readwrite").objectStore(this.#r).put(e,t);l.onsuccess=()=>s(),l.onerror=()=>o(l.error)})}async get(t){let e=await this.#l();return new Promise((i,s)=>{let c=e.transaction(this.#r,"readonly").objectStore(this.#r).get(t);c.onsuccess=()=>i(c.result||null),c.onerror=()=>s(c.error)})}async delete(t){let e=await this.#l();return new Promise((i,s)=>{let c=e.transaction(this.#r,"readwrite").objectStore(this.#r).delete(t);c.onsuccess=()=>i(),c.onerror=()=>s(c.error)})}async deleteByPrefix(t){let e=await this.#l();return new Promise((i,s)=>{let n=e.transaction(this.#r,"readwrite").objectStore(this.#r),c=n.openKeyCursor();c.onsuccess=l=>{let d=l.target.result;d?(typeof d.key=="string"&&d.key.startsWith(t)&&n.delete(d.key),d.continue()):i()},c.onerror=()=>s(c.error)})}async sweepOrphans(t){let e=new Set(t),i=await this.#l(),s=0;return new Promise((o,n)=>{let l=i.transaction(this.#r,"readwrite").objectStore(this.#r),d=l.openKeyCursor();d.onsuccess=u=>{let h=u.target.result;if(h){if(typeof h.key=="string"){let g=h.key.split(":")[0];e.has(g)||(l.delete(h.key),s++)}h.continue()}else o(s)},d.onerror=()=>n(d.error)})}async close(){if(this.#s){try{(await this.#s).close()}catch{}this.#s=null}}};function ye(r,t="image/jpeg"){if(r instanceof Blob)return r;if(typeof r!="string"||!r.startsWith("data:"))return null;let e=r.match(/^data:([^;]+);base64,(.*)$/),i=e?e[1]:t,s=e?e[2]:r.split(",")[1],o=atob(s),n=new Uint8Array(o.length);for(let c=0;c<o.length;c++)n[c]=o.charCodeAt(c);return new Blob([n],{type:i})}async function rs(r){return new Promise((t,e)=>{let i=new FileReader;i.onloadend=()=>t(i.result),i.onerror=e,i.readAsDataURL(r)})}var ne=class extends _t{#t=null;#r=null;#s=null;#l="copio-db";#a=!1;#e=new Set;#c=new Map;#o=new Map;#i=new Map;#n=new Map;#d=null;constructor(t={}){super(),this.#l=t.dbName||"copio-db",t.dbName&&t.dbName!=="copio-db"&&(this.#a=!0),this.#t=t.store||li(),this.#t.hasTable("docs")||this.#t.setTable("docs",{}),this.#r=t.persister||Zo(this.#t,this.#l),this.#s=new lr(`${this.#l}-blobs`)}get store(){return this.#t}get persister(){return this.#r}get blobStore(){return this.#s}#h(t,e){return typeof e=="string"&&e.startsWith("blob:")&&(this.#e.add(e),this.#c.has(t)||this.#c.set(t,[]),this.#c.get(t).push(e)),e}revokeDocUrls(t){let e=this.#c.get(t);if(e){for(let i of e){try{URL.revokeObjectURL(i)}catch{}this.#e.delete(i)}this.#c.delete(t)}for(let[i,s]of this.#o.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(s)}catch{}this.#o.delete(i)}for(let[i,s]of this.#i.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(s)}catch{}this.#i.delete(i)}this.#n.delete(t)}revokeAllUrls(){for(let t of this.#e)try{URL.revokeObjectURL(t)}catch{}this.#e.clear(),this.#c.clear(),this.#o.clear(),this.#i.clear(),this.#n.clear()}async init(){return this.#d?this.#d:(this.#d=(async()=>{this.#a?(await this.#r.load(),this.#r.startAutoLoad(),this.#r.startAutoSave()):await this.#r.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.#d)}async sweepOrphans(){let t=Object.keys(this.#t.getTable("docs")||{});return this.#s.sweepOrphans(t)}listDocsSync(){let t=this.#t.getTable("docs");return Object.entries(t||{}).map(([e,i])=>({id:e,name:i.name||"",pages:this.#p(i.pages)}))}async listDocs(){return this.listDocsSync()}getDocSync(t){if(this.#n.has(t))return this.#n.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.#p(e.pages)}}async getDoc(t){if(!this.#t.hasRow("docs",t))return null;let e=this.#t.getRow("docs",t),i=this.#p(e.pages),s=await Promise.all(i.map(async n=>{if(!n)return n;let c={...n},l=`${t}:${n.id}`,d=await this.#s.get(`${t}:${n.id}`);d&&(c.blob=d,this.#o.has(l)?c.src=this.#o.get(l):(c.src=this.#h(t,URL.createObjectURL(d)),this.#o.set(l,c.src)));let u=`${t}:${n.id}:orig`,h=await this.#s.get(`${t}:${n.id}:original`);return h?(c.originalBlob=h,this.#i.has(u)?c.originalSrc=this.#i.get(u):(c.originalSrc=this.#h(t,URL.createObjectURL(h)),this.#i.set(u,c.originalSrc))):c.blob&&(c.originalBlob=c.blob,c.originalSrc=c.src),c})),o={id:t,name:e.name||"",pages:s};return this.#n.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.#p(e.pages),s=[],o=[],n=[];for(let c of i){if(!c)continue;let l=ye(c.src)||(c.src instanceof Blob?c.src:null)||(c.blob instanceof Blob?c.blob:null),d=l?.type||"image/jpeg",u={id:c.id,name:c.name||"",type:c.type||"image",hasBlob:!0,mimeType:d,edits:c.edits,exif:c.exif,content:c.content,ocrText:c.ocrText??null,ocrConfidence:c.ocrConfidence??null,ocrWords:Array.isArray(c.ocrWords)?c.ocrWords:null,ocrWidth:c.ocrWidth??null,ocrHeight:c.ocrHeight??null};s.push(u);let h=`${t}:${c.id}`,g=`${t}:${c.id}:orig`,m={...c},E=this.#o.get(h),D=typeof c.src=="string"&&c.src.startsWith("data:")||c.src instanceof Blob||c.src&&E&&c.src!==E;if(l)if(m.blob=l,D||!E){if(E){try{URL.revokeObjectURL(E)}catch{}this.#e.delete(E)}let R=this.#h(t,URL.createObjectURL(l));this.#o.set(h,R),m.src=R}else m.src=E;let x=ye(c.originalSrc)||(c.originalSrc instanceof Blob?c.originalSrc:null)||(c.originalBlob instanceof Blob?c.originalBlob:null),w=this.#i.get(g),A=!w&&!x&&(!c.originalSrc||c.originalSrc===c.src);A&&l&&(x=l);let k=typeof c.originalSrc=="string"&&c.originalSrc.startsWith("data:")||c.originalSrc instanceof Blob||A&&!!x;if(x)if(m.originalBlob=x,k||!w){if(w&&k){try{URL.revokeObjectURL(w)}catch{}this.#e.delete(w)}let R=this.#h(t,URL.createObjectURL(x));this.#i.set(g,R),m.originalSrc=R}else m.originalSrc=w;else w?m.originalSrc=w:c.originalSrc?m.originalSrc=c.originalSrc:(m.originalSrc=m.src,m.blob&&(m.originalBlob=m.blob));o.push(m),n.push({pageId:c.id,page:c,srcBlob:l,origBlob:x})}this.#t.setRow("docs",t,{name:e.name||"",pages:JSON.stringify(s)}),this.#n.set(t,{id:t,name:e.name||"",pages:o});for(let c of n){let{pageId:l,page:d,srcBlob:u,origBlob:h}=c;if(!u&&typeof d.src=="string"&&d.src.startsWith("blob:"))try{u=await(await fetch(d.src)).blob()}catch{}if(u&&await this.#s.put(`${t}:${l}`,u),!h&&typeof d.originalSrc=="string"&&d.originalSrc.startsWith("blob:"))try{h=await(await fetch(d.originalSrc)).blob()}catch{}h&&await this.#s.put(`${t}:${l}:original`,h)}}async deleteDoc(t){this.#t.delRow("docs",t),await this.#s.deleteByPrefix(`${t}:`),this.revokeDocUrls(t),this.#n.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.#n.has(t)&&(this.#n.get(t).name=e)}async savePage(t,e,i){let s=await this.getDoc(t);if(!s)throw new Error(`Document ${t} not found`);let o=s.pages.findIndex(l=>l.id===e),n;if(o>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?s.pages[o]={...s.pages[o],...i}:s.pages[o]={...s.pages[o],src:i,blob:i instanceof Blob?i:void 0},n=s.pages[o];else{let l=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i,blob:i instanceof Blob?i:void 0};s.pages.push(l),n=l}let c=ye(n.src)||(n.src instanceof Blob?n.src:null)||(n.blob instanceof Blob?n.blob:null);if(!c&&typeof n.src=="string"&&n.src.startsWith("blob:"))try{c=await(await fetch(n.src)).blob()}catch{}c&&await this.#s.put(`${t}:${e}`,c),await this.saveDoc(t,s)}async getPage(t,e){let i=await this.#s.get(`${t}:${e}`);if(i)return i;let s=this.getDocSync(t);if(!s)return null;let o=s.pages.find(n=>n.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(n=>n.id!==e),this.#t.setRow("docs",t,{name:i.name||"",pages:JSON.stringify(i.pages)}),await this.#s.delete(`${t}:${e}`),await this.#s.delete(`${t}:${e}:original`);let s=`${t}:${e}`;if(this.#o.has(s)){try{URL.revokeObjectURL(this.#o.get(s))}catch{}this.#o.delete(s)}let o=`${t}:${e}:orig`;if(this.#i.has(o)){try{URL.revokeObjectURL(this.#i.get(o))}catch{}this.#i.delete(o)}this.#n.delete(t)}subscribe(t){let e=this.#t.addTableListener("docs",t);return()=>{this.#t.delListener(e)}}#p(t){if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}};async function en(){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 r=await navigator.storage.getDirectory();if(!r)return!1;let t=`.copio-probe-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,e=await r.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 r.removeEntry(t),!0}catch{return!1}}function Ra(r,t,e="store.json"){let i=0,s=null,o=Promise.resolve(),n=0,c=()=>typeof t=="function"?t():t,l=async()=>{await o;let g=c();if(g){i=1;try{let D=await(await(await g.getFileHandle(e)).getFile()).text();D&&D.trim().length>0&&r.setJson(D)}catch{}finally{i=0}}},d=()=>{let g=c();return g?(n++,i=2,o=o.catch(()=>{}).then(async()=>{try{let m=r.getJson(),D=await(await g.getFileHandle(e,{create:!0})).createWritable();await D.write(m),await D.close()}catch(m){console.warn("[OpfsPersister] Failed to save store.json:",m)}finally{n--,n<=0&&(n=0,i=0)}}),o):Promise.resolve()};return{load:l,save:d,startAutoSave:()=>{s||(s=r.addDidFinishTransactionListener(()=>{d()}))},stopAutoSave:()=>{s&&(r.delListener(s),s=null)},getStatus:()=>i,getStore:()=>r}}async function tn(r){let t=[];try{if(typeof r.entries=="function")for await(let e of r.entries())t.push(e);else if(typeof r.values=="function")for await(let e of r.values())t.push([e.name,e])}catch(e){console.warn("[OpfsAdapter] Error reading directory entries:",e)}return t}var pi=class extends _t{#t;#r="copio";#s=null;#l=null;#a=null;#e=null;#c=null;#o=!1;#i=null;#n=new Set;#d=new Map;#h=new Map;#p=new Map;#u=new Map;#g=null;constructor(t={}){super(),this.#t=t,this.#r=t.dirName||"copio",t.store?this.#e=t.store:(this.#e=li(),this.#e.setTable("docs",{})),this.#c=t.persister||Ra(this.#e,()=>this.#l,"store.json")}get store(){return this.#o?this.#i?.store:this.#e}get persister(){return this.#o?this.#i?.persister:this.#c}get isFallback(){return this.#o}get fallbackAdapter(){return this.#i}async#f(){if(this.#o)return!1;if(this.#a&&this.#l)return!0;if(typeof navigator<"u"&&navigator.storage&&typeof navigator.storage.getDirectory=="function")try{return this.#s=await navigator.storage.getDirectory(),this.#l=await this.#s.getDirectoryHandle(this.#r,{create:!0}),this.#a=await this.#l.getDirectoryHandle("docs",{create:!0}),!0}catch(t){return console.warn("[OpfsAdapter] OPFS directory access failed, switching to fallback:",t),await this.#b(),!1}else return await this.#b(),!1}#w(t,e){return typeof e=="string"&&e.startsWith("blob:")&&(this.#n.add(e),this.#d.has(t)||this.#d.set(t,[]),this.#d.get(t).push(e)),e}revokeDocUrls(t){if(this.#o){this.#i?.revokeDocUrls(t);return}let e=this.#d.get(t);if(e){for(let i of e){try{URL.revokeObjectURL(i)}catch{}this.#n.delete(i)}this.#d.delete(t)}for(let[i,s]of this.#h.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(s)}catch{}this.#h.delete(i)}for(let[i,s]of this.#p.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(s)}catch{}this.#p.delete(i)}this.#u.delete(t)}revokeAllUrls(){if(this.#o){this.#i?.revokeAllUrls();return}for(let t of this.#n)try{URL.revokeObjectURL(t)}catch{}this.#n.clear(),this.#d.clear(),this.#h.clear(),this.#p.clear(),this.#u.clear()}async init(){return this.#g?this.#g:(this.#g=(async()=>{if(this.#t.forceFallback)return this.#b();if(!await en())return this.#b();try{await this.#f(),await this.#c.load(),this.#c.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.#b()}})(),this.#g)}async#b(){return this.#o=!0,this.#i=new ne(this.#t),{kind:"indexeddb",persistent:(await this.#i.init()).persistent}}async sweepOrphans(){if(this.#o)return this.#i?.sweepOrphans();if(await this.#f(),!this.#a)return 0;let t=0,e=this.#e.getTable("docs")||{},i=new Set(Object.keys(e)),s=new Map;for(let[n,c]of Object.entries(e)){let l=this.#y(c.pages);s.set(n,new Set(l.map(d=>d.id)))}let o=await tn(this.#a);for(let[n,c]of o)if(c.kind==="directory")if(i.has(n)){let l=s.get(n)||new Set,d=c,u=await tn(d);for(let[h]of u){let g=h.replace(/-original\.bin$/,"").replace(/\.bin$/,"");if(!l.has(g))try{await d.removeEntry(h),t++}catch{}}}else try{await this.#a.removeEntry(n,{recursive:!0}),t++}catch{}return t}listDocsSync(){if(this.#o)return this.#i?.listDocsSync();let t=this.#e.getTable("docs");return Object.entries(t||{}).map(([e,i])=>({id:e,name:i.name||"",pages:this.#y(i.pages)}))}async listDocs(){return this.#o?this.#i?.listDocs():this.listDocsSync()}getDocSync(t){if(this.#o)return this.#i?.getDocSync(t);if(this.#u.has(t))return this.#u.get(t);if(!this.#e.hasRow("docs",t))return null;let e=this.#e.getRow("docs",t);return{id:t,name:e.name||"",pages:this.#y(e.pages)}}async getDoc(t){if(this.#o)return this.#i?.getDoc(t);if(await this.#f(),!this.#e.hasRow("docs",t))return null;let e=this.#e.getRow("docs",t),i=this.#y(e.pages),s=null;if(this.#a)try{s=await this.#a.getDirectoryHandle(t)}catch{}let o=await Promise.all(i.map(async c=>{if(!c||!s)return c;let l={...c},d=`${t}:${c.id}`;try{let g=await(await s.getFileHandle(`${c.id}.bin`)).getFile();l.blob=g,this.#h.has(d)?l.src=this.#h.get(d):(l.src=this.#w(t,URL.createObjectURL(g)),this.#h.set(d,l.src))}catch{}let u=`${t}:${c.id}:orig`;try{let g=await(await s.getFileHandle(`${c.id}-original.bin`)).getFile();l.originalBlob=g,this.#p.has(u)?l.originalSrc=this.#p.get(u):(l.originalSrc=this.#w(t,URL.createObjectURL(g)),this.#p.set(u,l.originalSrc))}catch{l.blob&&(l.originalBlob=l.blob,l.originalSrc=l.src)}return l})),n={id:t,name:e.name||"",pages:o};return this.#u.set(t,n),n}async saveDoc(t,e){if(this.#o)return this.#i?.saveDoc(t,e);if(!t)throw new Error("Cannot save document without an ID");let i=Array.isArray(e.pages)?e.pages:this.#y(e.pages),s=[],o=[],n=[];for(let l of i){if(!l)continue;let d=ye(l.src)||(l.src instanceof Blob?l.src:null)||(l.blob instanceof Blob?l.blob:null),u=d?.type||"image/jpeg",h={id:l.id,name:l.name||"",type:l.type||"image",hasBlob:!0,mimeType:u,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};s.push(h);let g=`${t}:${l.id}`,m=`${t}:${l.id}:orig`,E={...l},D=this.#h.get(g),x=typeof l.src=="string"&&l.src.startsWith("data:")||l.src instanceof Blob||l.src&&D&&l.src!==D;if(d)if(E.blob=d,x||!D){if(D){try{URL.revokeObjectURL(D)}catch{}this.#n.delete(D)}let U=this.#w(t,URL.createObjectURL(d));this.#h.set(g,U),E.src=U}else E.src=D;let w=ye(l.originalSrc)||(l.originalSrc instanceof Blob?l.originalSrc:null)||(l.originalBlob instanceof Blob?l.originalBlob:null),A=this.#p.get(m),k=!A&&!w&&(!l.originalSrc||l.originalSrc===l.src);k&&d&&(w=d);let R=typeof l.originalSrc=="string"&&l.originalSrc.startsWith("data:")||l.originalSrc instanceof Blob||k&&!!w;if(w)if(E.originalBlob=w,R||!A){if(A&&R){try{URL.revokeObjectURL(A)}catch{}this.#n.delete(A)}let U=this.#w(t,URL.createObjectURL(w));this.#p.set(m,U),E.originalSrc=U}else E.originalSrc=A;else A?E.originalSrc=A:l.originalSrc?E.originalSrc=l.originalSrc:(E.originalSrc=E.src,E.blob&&(E.originalBlob=E.blob));o.push(E),n.push({pageId:l.id,page:l,srcBlob:d,origBlob:w})}if(this.#e.setRow("docs",t,{name:e.name||"",pages:JSON.stringify(s)}),this.#u.set(t,{id:t,name:e.name||"",pages:o}),await this.#f(),this.#o)return this.#i?.saveDoc(t,e);let c=null;if(this.#a)try{c=await this.#a.getDirectoryHandle(t,{create:!0})}catch(l){console.warn(`[OpfsAdapter] Failed to get doc directory "${t}":`,l)}if(c)for(let l of n){let{pageId:d,page:u,srcBlob:h,origBlob:g}=l;if(!h&&typeof u.src=="string"&&u.src.startsWith("blob:"))try{h=await(await fetch(u.src)).blob()}catch{}if(h)try{let E=await(await c.getFileHandle(`${d}.bin`,{create:!0})).createWritable();await E.write(h),await E.close()}catch(m){console.warn(`[OpfsAdapter] Failed writing page file "${d}.bin":`,m)}if(!g&&typeof u.originalSrc=="string"&&u.originalSrc.startsWith("blob:"))try{g=await(await fetch(u.originalSrc)).blob()}catch{}if(g)try{let E=await(await c.getFileHandle(`${d}-original.bin`,{create:!0})).createWritable();await E.write(g),await E.close()}catch{}}}async deleteDoc(t){if(this.#o)return this.#i?.deleteDoc(t);if(this.#e.delRow("docs",t),this.#u.delete(t),this.revokeDocUrls(t),await this.#f(),this.#a)try{await this.#a.removeEntry(t,{recursive:!0})}catch{}}async renameDoc(t,e){if(this.#o)return this.#i?.renameDoc(t,e);if(!this.#e.hasRow("docs",t))throw new Error(`Document "${t}" not found`);this.#e.setCell("docs",t,"name",e),this.#u.has(t)&&(this.#u.get(t).name=e)}async savePage(t,e,i){if(this.#o)return this.#i?.savePage(t,e,i);await this.#f();let s=await this.getDoc(t);if(!s)throw new Error(`Document ${t} not found`);let o=s.pages.findIndex(l=>l.id===e),n;if(o>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?s.pages[o]={...s.pages[o],...i}:s.pages[o]={...s.pages[o],src:i,blob:i instanceof Blob?i:void 0},n=s.pages[o];else{let l=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i,blob:i instanceof Blob?i:void 0};s.pages.push(l),n=l}let c=ye(n.src)||(n.src instanceof Blob?n.src:null)||(n.blob instanceof Blob?n.blob:null);if(!c&&typeof n.src=="string"&&n.src.startsWith("blob:"))try{c=await(await fetch(n.src)).blob()}catch{}if(c&&this.#a)try{let u=await(await(await this.#a.getDirectoryHandle(t,{create:!0})).getFileHandle(`${e}.bin`,{create:!0})).createWritable();await u.write(c),await u.close()}catch(l){console.warn(`[OpfsAdapter] Failed writing page file "${e}.bin":`,l)}await this.saveDoc(t,s)}async getPage(t,e){if(this.#o)return this.#i?.getPage(t,e);if(await this.#f(),this.#a)try{return await(await(await this.#a.getDirectoryHandle(t)).getFileHandle(`${e}.bin`)).getFile()}catch{}let i=this.getDocSync(t);if(!i)return null;let s=i.pages.find(o=>o.id===e);return s?s.content??s.src??s:null}async deletePage(t,e){if(this.#o)return this.#i?.deletePage(t,e);await this.#f();let i=this.getDocSync(t);if(!i)return;if(i.pages=i.pages.filter(n=>n.id!==e),this.#e.setRow("docs",t,{name:i.name||"",pages:JSON.stringify(i.pages)}),this.#a){try{await(await this.#a.getDirectoryHandle(t)).removeEntry(`${e}.bin`)}catch{}try{await(await this.#a.getDirectoryHandle(t)).removeEntry(`${e}-original.bin`)}catch{}}let s=`${t}:${e}`;if(this.#h.has(s)){try{URL.revokeObjectURL(this.#h.get(s))}catch{}this.#h.delete(s)}let o=`${t}:${e}:orig`;if(this.#p.has(o)){try{URL.revokeObjectURL(this.#p.get(o))}catch{}this.#p.delete(o)}this.#u.delete(t)}subscribe(t){if(this.#o)return this.#i?.subscribe(t);let e=this.#e.addTableListener("docs",t);return()=>{this.#e.delListener(e)}}#y(t){if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}};function dr(r={}){return r.forceMemory?new Le:r.forceIndexedDb?new ne(r):r.forceOpfs?new pi(r):typeof navigator<"u"&&navigator.storage&&typeof navigator.storage.getDirectory=="function"?new pi(r):typeof indexedDB<"u"?new ne(r):new Le}function st(r,t,e){return t in r?Object.defineProperty(r,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):r[t]=e,r}var bs=typeof self<"u"?self:global,bi=typeof navigator<"u",Ba=bi&&typeof HTMLImageElement>"u",rn=!(typeof global>"u"||typeof process>"u"||!process.versions||!process.versions.node),ys=bs.Buffer,hr=bs.BigInt,ws=!!ys,pr=r=>gn(r)?void 0:r,Ta=r=>r!==void 0;function gn(r){return r===void 0||(r instanceof Map?r.size===0:Object.values(r).filter(Ta).length===0)}function xt(r){let t=new Error(r);throw delete t.stack,t}function mn(r){return(r=(function(t){for(;t.endsWith("\0");)t=t.slice(0,-1);return t})(r).trim())===""?void 0:r}function sn(r){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})(r);return r.jfif.enabled&&(t+=50),r.xmp.enabled&&(t+=2e4),r.iptc.enabled&&(t+=14e3),r.icc.enabled&&(t+=6e3),t}var as=r=>String.fromCharCode.apply(null,r),on=typeof TextDecoder<"u"?new TextDecoder("utf-8"):void 0;function bn(r){return on?on.decode(r):ws?Buffer.from(r).toString("utf8"):decodeURIComponent(escape(as(r)))}var qt=class r{static from(t,e){return t instanceof this&&t.le===e?t:new r(t,void 0,void 0,e)}constructor(t,e=0,i,s){if(typeof s=="boolean"&&(this.le=s),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 r){i===void 0&&(i=t.byteLength-e),(e+=t.byteOffset)+i>t.byteOffset+t.byteLength&&xt("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 xt("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=r){return t instanceof DataView||t instanceof r?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t instanceof Uint8Array||xt("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 r(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 bn(this.getUint8Array(t,e))}getLatin1String(t=0,e=this.byteLength){let i=this.getUint8Array(t,e);return as(i)}getUnicodeString(t=0,e=this.byteLength){let i=[];for(let s=0;s<e&&t+s<this.byteLength;s+=2)i.push(this.getUint16(t+s));return as(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 cs(r,t){xt(`${r} '${t}' was not loaded, try using full build of exifr.`)}var yi=class extends Map{constructor(t){super(),this.kind=t}get(t,e){return this.has(t)||cs(this.kind,t),e&&(t in e||(function(i,s){xt(`Unknown ${i} '${s}'.`)})(this.kind,t),e[t].enabled||cs(this.kind,t)),super.get(t)}keyList(){return Array.from(this.keys())}},Ee=new yi("file parser"),At=new yi("segment parser"),Ce=new yi("file reader"),yn=bs.fetch;function nn(r,t){return(e=r).startsWith("data:")||e.length>1e4?ds(r,t,"base64"):rn&&r.includes("://")?ls(r,t,"url",He):rn?ds(r,t,"fs"):bi?ls(r,t,"url",He):void xt("Invalid input argument");var e}async function ls(r,t,e,i){return Ce.has(e)?ds(r,t,e):i?(async function(s,o){let n=await o(s);return new qt(n)})(r,i):void xt(`Parser ${e} is not loaded`)}async function ds(r,t,e){let i=new(Ce.get(e))(r,t);return await i.read(),i}var He=r=>yn(r).then((t=>t.arrayBuffer())),_e=r=>new Promise(((t,e)=>{let i=new FileReader;i.onloadend=()=>t(i.result||new ArrayBuffer),i.onerror=e,i.readAsArrayBuffer(r)})),hs=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 Ft(r,t,e){let i=new hs;for(let[s,o]of e)i.set(s,o);if(Array.isArray(t))for(let s of t)r.set(s,i);else r.set(t,i);return i}function xs(r,t,e){let i,s=r.get(t);for(i of e)s.set(i[0],i[1])}var Kt=new Map,We=new Map,Pe=new Map,xe=["chunked","firstChunkSize","firstChunkSizeNode","firstChunkSizeBrowser","chunkSize","chunkLimit"],wi=["jfif","xmp","icc","iptc","ihdr"],Ve=["tiff",...wi],wt=["ifd0","ifd1","exif","gps","interop"],ve=[...Ve,...wt],Se=["makerNote","userComment"],xi=["translateKeys","translateValues","reviveValues","multiSegment"],ke=[...xi,"sanitize","mergeOutput","silentErrors"],fr=class{get translate(){return this.translateKeys||this.translateValues||this.reviveValues}},we=class extends fr{get needed(){return this.enabled||this.deps.size>0}constructor(t,e,i,s){if(super(),st(this,"enabled",!1),st(this,"skip",new Set),st(this,"pick",new Set),st(this,"deps",new Set),st(this,"translateKeys",!1),st(this,"translateValues",!1),st(this,"reviveValues",!1),this.key=t,this.enabled=e,this.parse=this.enabled,this.applyInheritables(s),this.canBeFiltered=wt.includes(t),this.canBeFiltered&&(this.dict=Kt.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:n}=i;o&&o.length>0&&this.translateTagSet(o,this.pick),n&&n.length>0&&this.translateTagSet(n,this.skip)}this.applyInheritables(i)}else i===!0||i===!1?this.parse=this.enabled=i:xt(`Invalid options argument: ${i}`)}applyInheritables(t){let e,i;for(e of xi)i=t[e],i!==void 0&&(this[e]=i)}translateTagSet(t,e){if(this.dict){let i,s,{tagKeys:o,tagValues:n}=this.dict;for(i of t)typeof i=="string"?(s=n.indexOf(i),s===-1&&(s=o.indexOf(Number(i))),s!==-1&&e.add(Number(o[s]))):e.add(i)}else for(let i of t)e.add(i)}finalizeFilters(){!this.enabled&&this.deps.size>0?(this.enabled=!0,ur(this.pick,this.deps)):this.enabled&&this.pick.size>0&&ur(this.pick,this.deps)}},Dt={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},an=new Map,ae=class extends fr{static useCached(t){let e=an.get(t);return e!==void 0||(e=new this(t),an.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):xt(`Invalid options argument ${t}`),this.firstChunkSize===void 0&&(this.firstChunkSize=bi?this.firstChunkSizeBrowser:this.firstChunkSizeNode),this.mergeOutput&&(this.ifd1.enabled=!1),this.filterNestedSegmentTags(),this.traverseTiffDependencyTree(),this.checkLoadedPlugins()}setupFromUndefined(){let t;for(t of xe)this[t]=Dt[t];for(t of ke)this[t]=Dt[t];for(t of Se)this[t]=Dt[t];for(t of ve)this[t]=new we(t,Dt[t],void 0,this)}setupFromTrue(){let t;for(t of xe)this[t]=Dt[t];for(t of ke)this[t]=Dt[t];for(t of Se)this[t]=!0;for(t of ve)this[t]=new we(t,!0,void 0,this)}setupFromArray(t){let e;for(e of xe)this[e]=Dt[e];for(e of ke)this[e]=Dt[e];for(e of Se)this[e]=Dt[e];for(e of ve)this[e]=new we(e,!1,void 0,this);this.setupGlobalFilters(t,void 0,wt)}setupFromObject(t){let e;for(e of(wt.ifd0=wt.ifd0||wt.image,wt.ifd1=wt.ifd1||wt.thumbnail,Object.assign(this,t),xe))this[e]=ss(t[e],Dt[e]);for(e of ke)this[e]=ss(t[e],Dt[e]);for(e of Se)this[e]=ss(t[e],Dt[e]);for(e of Ve)this[e]=new we(e,Dt[e],t[e],this);for(e of wt)this[e]=new we(e,Dt[e],t[e],this.tiff);this.setupGlobalFilters(t.pick,t.skip,wt,ve),t.tiff===!0?this.batchEnableWithBool(wt,!0):t.tiff===!1?this.batchEnableWithUserValue(wt,t):Array.isArray(t.tiff)?this.setupGlobalFilters(t.tiff,void 0,wt):typeof t.tiff=="object"&&this.setupGlobalFilters(t.tiff.pick,t.tiff.skip,wt)}batchEnableWithBool(t,e){for(let i of t)this[i].enabled=e}batchEnableWithUserValue(t,e){for(let i of t){let s=e[i];this[i].enabled=s!==!1&&s!==void 0}}setupGlobalFilters(t,e,i,s=i){if(t&&t.length){for(let n of s)this[n].enabled=!1;let o=cn(t,i);for(let[n,c]of o)ur(this[n].pick,c),this[n].enabled=!0}else if(e&&e.length){let o=cn(e,i);for(let[n,c]of o)ur(this[n].skip,c)}}filterNestedSegmentTags(){let{ifd0:t,exif:e,xmp:i,iptc:s,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),s.enabled||t.skip.add(33723),o.enabled||t.skip.add(34675)}traverseTiffDependencyTree(){let{ifd0:t,exif:e,gps:i,interop:s}=this;s.needed&&(e.deps.add(40965),t.deps.add(40965)),e.needed&&t.deps.add(34665),i.needed&&t.deps.add(34853),this.tiff.enabled=wt.some((o=>this[o].enabled===!0))||this.makerNote||this.userComment;for(let o of wt)this[o].finalizeFilters()}get onlyTiff(){return!wi.map((t=>this[t].enabled)).some((t=>t===!0))&&this.tiff.enabled}checkLoadedPlugins(){for(let t of Ve)this[t].enabled&&!At.has(t)&&cs("segment parser",t)}};function cn(r,t){let e,i,s,o,n=[];for(s of t){for(o of(e=Kt.get(s),i=[],e))(r.includes(o[0])||r.includes(o[1]))&&i.push(o[0]);i.length&&n.push([s,i])}return n}function ss(r,t){return r!==void 0?r:t!==void 0?t:void 0}function ur(r,t){for(let e of t)r.add(e)}st(ae,"default",Dt);var Xt=class{constructor(t){st(this,"parsers",{}),st(this,"output",{}),st(this,"errors",[]),st(this,"pushToErrors",(e=>this.errors.push(e))),this.options=ae.useCached(t)}async read(t){this.file=await(function(e,i){return typeof e=="string"?nn(e,i):bi&&!Ba&&e instanceof HTMLImageElement?nn(e.src,i):e instanceof Uint8Array||e instanceof ArrayBuffer||e instanceof DataView?new qt(e):bi&&e instanceof Blob?ls(e,i,"blob",_e):void xt("Invalid input argument")})(t,this.options)}setup(){if(this.fileParser)return;let{file:t}=this,e=t.getUint16(0);for(let[i,s]of Ee)if(s.canHandle(t,e))return this.fileParser=new s(this.options,this.file,this.parsers),t[i]=!0;this.file.close&&this.file.close(),xt("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),pr(t)}async executeParsers(){let{output:t}=this;await this.fileParser.parse();let e=Object.values(this.parsers).map((async i=>{let s=await i.parse();i.assignToOutput(t,s)}));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=At.get("tiff",t);var s;if(e.tiff?s={start:0,type:"tiff"}:e.jpeg&&(s=await this.fileParser.getOrFindSegment("tiff")),s===void 0)return;let o=await this.fileParser.ensureSegmentChunk(s),n=this.parsers.tiff=new i(o,t,e),c=await n.extractThumbnail();return e.close&&e.close(),c}};async function vs(r,t){let e=new Xt(t);return await e.read(r),e.parse()}var Ma=Object.freeze({__proto__:null,parse:vs,Exifr:Xt,fileParsers:Ee,segmentParsers:At,fileReaders:Ce,tagKeys:Kt,tagValues:We,tagRevivers:Pe,createDictionary:Ft,extendDictionary:xs,fetchUrlAsArrayBuffer:He,readBlobAsArrayBuffer:_e,chunkedProps:xe,otherSegments:wi,segments:Ve,tiffBlocks:wt,segmentsAndBlocks:ve,tiffExtractables:Se,inheritables:xi,allFormatters:ke,Options:ae}),gr=class{constructor(t,e,i){st(this,"errors",[]),st(this,"ensureSegmentChunk",(async s=>{let o=s.start,n=s.size||65536;if(this.file.chunked)if(this.file.available(o,n))s.chunk=this.file.subarray(o,n);else try{s.chunk=await this.file.readChunk(o,n)}catch(c){xt(`Couldn't read segment: ${JSON.stringify(s)}. ${c.message}`)}else this.file.byteLength>o+n?s.chunk=this.file.subarray(o,n):s.size===void 0?s.chunk=this.file.subarray(o):xt("Segment unreachable: "+JSON.stringify(s));return s.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(At.get(t))(e,this.options,this.file);return this.parsers[t]=i}createParsers(t){for(let e of t){let{type:i,chunk:s}=e,o=this.options[i];if(o&&o.enabled){let n=this.parsers[i];n&&n.append||n||this.createParser(i,s)}}}async readSegments(t){let e=t.map(this.ensureSegmentChunk);await Promise.all(e)}},Gt=class{static findPosition(t,e){let i=t.getUint16(e+2)+2,s=typeof this.headerLength=="function"?this.headerLength(t,e,i):this.headerLength,o=e+s,n=i-s;return{offset:e,length:i,headerLength:s,start:o,size:n,end:o+n}}static parse(t,e={}){return new this(t,new ae({[this.type]:e}),t).parse()}normalizeInput(t){return t instanceof qt?t:new qt(t)}constructor(t,e={},i){st(this,"errors",[]),st(this,"raw",new Map),st(this,"handleError",(s=>{if(!this.options.silentErrors)throw s;this.errors.push(s.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=Pe.get(e),s=We.get(e),o=Kt.get(e),n=this.options[e],c=n.reviveValues&&!!i,l=n.translateValues&&!!s,d=n.translateKeys&&!!o,u={};for(let[h,g]of t)c&&i.has(h)?g=i.get(h)(g):l&&s.has(h)&&(g=this.translateValue(g,s.get(h))),d&&o.has(h)&&(h=o.get(h)||h),u[h]=g;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}};st(Gt,"headerLength",4),st(Gt,"type",void 0),st(Gt,"multiSegment",!1),st(Gt,"canHandle",(()=>!1));function Oa(r){return r===192||r===194||r===196||r===219||r===221||r===218||r===254}function Ua(r){return r>=224&&r<=239}function Fa(r,t,e){for(let[i,s]of At)if(s.canHandle(r,t,e))return i}var mr=class extends gr{constructor(...t){super(...t),st(this,"appSegments",[]),st(this,"jpegSegments",[]),st(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(At.keyList())):(t=t===void 0?At.keyList().filter((e=>this.options[e].enabled)):t.filter((e=>this.options[e].enabled&&At.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:s,wanted:o,remaining:n}=this;if(!s&&this.file.chunked&&(s=Array.from(o).some((c=>{let l=At.get(c),d=this.options[c];return l.multiSegment&&d.multiSegment})),s&&await this.file.readWhole()),t=this.findAppSegmentsInRange(t,i.byteLength),!this.options.onlyTiff&&i.chunked){let c=!1;for(;n.size>0&&!c&&(i.canReadNextChunk||this.unfinishedMultiSegment);){let{nextChunkOffset:l}=i,d=this.appSegments.some((u=>!this.file.available(u.offset||u.start,u.length||u.size)));if(c=t>l&&!d?!await i.readNextChunk(t):!await i.readNextChunk(l),(t=this.findAppSegmentsInRange(t,i.byteLength))===void 0)return}}}findAppSegmentsInRange(t,e){e-=2;let i,s,o,n,c,l,{file:d,findAll:u,wanted:h,remaining:g,options:m}=this;for(;t<e;t++)if(d.getUint8(t)===255){if(i=d.getUint8(t+1),Ua(i)){if(s=d.getUint16(t+2),o=Fa(d,t,s),o&&h.has(o)&&(n=At.get(o),c=n.findPosition(d,t),l=m[o],c.type=o,this.appSegments.push(c),!u&&(n.multiSegment&&l.multiSegment?(this.unfinishedMultiSegment=c.chunkNumber<c.chunkCount,this.unfinishedMultiSegment||g.delete(o)):g.delete(o),g.size===0)))break;m.recordUnknownSegments&&(c=Gt.findPosition(d,t),c.marker=i,this.unknownSegments.push(c)),t+=s+1}else if(Oa(i)){if(s=d.getUint16(t+2),i===218&&m.stopAfterSos!==!1)return;m.recordJpegSegments&&this.jpegSegments.push({offset:t,length:s,marker:i}),t+=s+1}}return t}mergeMultiSegments(){if(!this.appSegments.some((e=>e.multiSegment)))return;let t=(function(e,i){let s,o,n,c=new Map;for(let l=0;l<e.length;l++)s=e[l],o=s[i],c.has(o)?n=c.get(o):c.set(o,n=[]),n.push(s);return Array.from(c)})(this.appSegments,"type");this.mergedAppSegments=t.map((([e,i])=>{let s=At.get(e,this.options);return s.handleMultiSegments?{type:e,chunk:s.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}};st(mr,"type","jpeg"),Ee.set("jpeg",mr);var ja=[void 0,1,1,2,4,8,1,1,2,4,8,4,8,4],ps=class extends Gt{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:s,skip:o}=this.options[e];s=new Set(s);let n=s.size>0,c=o.size===0,l=this.chunk.getUint16(t);t+=2;for(let d=0;d<l;d++){let u=this.chunk.getUint16(t);if(n){if(s.has(u)&&(i.set(u,this.parseTag(t,u,e)),s.delete(u),s.size===0))break}else!c&&o.has(u)||i.set(u,this.parseTag(t,u,e));t+=12}return i}parseTag(t,e,i){let{chunk:s}=this,o=s.getUint16(t+2),n=s.getUint32(t+4),c=ja[o];if(c*n<=4?t+=8:t=s.getUint32(t+8),(o<1||o>13)&&xt(`Invalid TIFF value type. block: ${i.toUpperCase()}, tag: ${e.toString(16)}, type: ${o}, offset ${t}`),t>s.byteLength&&xt(`Invalid TIFF value offset. block: ${i.toUpperCase()}, tag: ${e.toString(16)}, type: ${o}, offset ${t} is outside of chunk size ${s.byteLength}`),o===1)return s.getUint8Array(t,n);if(o===2)return mn(s.getString(t,n));if(o===7)return s.getUint8Array(t,n);if(n===1)return this.parseTagValue(o,t);{let l=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))(n),d=c;for(let u=0;u<n;u++)l[u]=this.parseTagValue(o,t),t+=d;return l}}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:xt(`Invalid tiff type ${t}`)}}},ui=class extends ps{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&&xt("Malformed EXIF data"),!t.chunked&&this.ifd0Offset>t.byteLength&&xt(`IFD0 offset points to outside of file.
|
|
3
|
+
this.ifd0Offset: ${this.ifd0Offset}, file.byteLength: ${t.byteLength}`),t.tiff&&await t.ensureChunk(this.ifd0Offset,sn(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,sn(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",ln(...t.get(2),t.get(1))),t.set("longitude",ln(...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,s={};for(e of wt)if(t=this[e],!gn(t))if(i=this.canTranslate?this.translateBlock(t,e):Object.fromEntries(t),this.options.mergeOutput){if(e==="ifd1")continue;Object.assign(s,i)}else s[e]=i;return this.makerNote&&(s.makerNote=this.makerNote),this.userComment&&(s.userComment=this.userComment),s}assignToOutput(t,e){if(this.globalOptions.mergeOutput)Object.assign(t,e);else for(let[i,s]of Object.entries(e))this.assignObjectToOutput(t,i,s)}};function ln(r,t,e,i){var s=r+t/60+e/3600;return i!=="S"&&i!=="W"||(s*=-1),s}st(ui,"type","tiff"),st(ui,"headerLength",10),At.set("tiff",ui);var za=Object.freeze({__proto__:null,default:Ma,Exifr:Xt,fileParsers:Ee,segmentParsers:At,fileReaders:Ce,tagKeys:Kt,tagValues:We,tagRevivers:Pe,createDictionary:Ft,extendDictionary:xs,fetchUrlAsArrayBuffer:He,readBlobAsArrayBuffer:_e,chunkedProps:xe,otherSegments:wi,segments:Ve,tiffBlocks:wt,segmentsAndBlocks:ve,tiffExtractables:Se,inheritables:xi,allFormatters:ke,Options:ae,parse:vs}),Ss={ifd0:!1,ifd1:!1,exif:!1,gps:!1,interop:!1,sanitize:!1,reviveValues:!0,translateKeys:!1,translateValues:!1,mergeOutput:!1},wn=Object.assign({},Ss,{firstChunkSize:4e4,gps:[1,2,3,4]});async function Na(r){let t=new Xt(wn);await t.read(r);let e=await t.parse();if(e&&e.gps){let{latitude:i,longitude:s}=e.gps;return{latitude:i,longitude:s}}}var xn=Object.assign({},Ss,{tiff:!1,ifd1:!0,mergeOutput:!1});async function $a(r){let t=new Xt(xn);await t.read(r);let e=await t.extractThumbnail();return e&&ws?ys.from(e):e}async function Ha(r){let t=await this.thumbnail(r);if(t!==void 0){let e=new Blob([t]);return URL.createObjectURL(e)}}var vn=Object.assign({},Ss,{firstChunkSize:4e4,ifd0:[274]});async function Sn(r){let t=new Xt(vn);await t.read(r);let e=await t.parse();if(e&&e.ifd0)return e.ifd0[274]}var kn=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}}),Ne=!0,$e=!0;if(typeof navigator=="object"){let r=navigator.userAgent;if(r.includes("iPad")||r.includes("iPhone")){let t=r.match(/OS (\d+)_(\d+)/);if(t){let[,e,i]=t;Ne=Number(e)+.1*Number(i)<13.4,$e=!1}}else if(r.includes("OS X 10")){let[,t]=r.match(/OS X 10[_.](\d+)/);Ne=$e=Number(t)<15}if(r.includes("Chrome/")){let[,t]=r.match(/Chrome\/(\d+)/);Ne=$e=Number(t)<81}else if(r.includes("Firefox/")){let[,t]=r.match(/Firefox\/(\d+)/);Ne=$e=Number(t)<77}}async function _a(r){let t=await Sn(r);return Object.assign({canvas:Ne,css:$e},kn[t])}var fs=class extends qt{constructor(...t){super(...t),st(this,"ranges",new us),this.byteLength!==0&&this.ranges.add(0,this.byteLength)}_tryExtend(t,e,i){if(t===0&&this.byteLength===0&&i){let s=new DataView(i.buffer||i,i.byteOffset,i.byteLength);this._swapDataView(s)}else{let s=t+e;if(s>this.byteLength){let{dataView:o}=this._extend(s);this._swapDataView(o)}}}_extend(t){let e;e=ws?ys.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 s=super.set(t,e);return this.ranges.add(e,s.byteLength),s}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)}},us=class{constructor(){st(this,"list",[])}get length(){return this.list.length}add(t,e,i=0){let s=t+e,o=this.list.filter((n=>dn(t,n.offset,s)||dn(t,n.end,s)));if(o.length>0){t=Math.min(t,...o.map((c=>c.offset))),s=Math.max(s,...o.map((c=>c.end))),e=s-t;let n=o.shift();n.offset=t,n.length=e,n.end=s,this.list=this.list.filter((c=>!o.includes(c)))}else this.list.push({offset:t,length:e,end:s})}available(t,e){let i=t+e;return this.list.some((s=>s.offset<=t&&i<=s.end))}};function dn(r,t,e){return r<=t&&t<=e}var br=class extends fs{constructor(t,e){super(0),st(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(){}};Ce.set("blob",class extends br{async readWhole(){this.chunked=!1;let r=await _e(this.input);this._swapArrayBuffer(r)}readChunked(){return this.chunked=!0,this.size=this.input.size,super.readChunked()}async _readChunk(r,t){let e=t?r+t:void 0,i=this.input.slice(r,e),s=await _e(i);return this.set(s,r,!0)}});var Va=Object.freeze({__proto__:null,default:za,Exifr:Xt,fileParsers:Ee,segmentParsers:At,fileReaders:Ce,tagKeys:Kt,tagValues:We,tagRevivers:Pe,createDictionary:Ft,extendDictionary:xs,fetchUrlAsArrayBuffer:He,readBlobAsArrayBuffer:_e,chunkedProps:xe,otherSegments:wi,segments:Ve,tiffBlocks:wt,segmentsAndBlocks:ve,tiffExtractables:Se,inheritables:xi,allFormatters:ke,Options:ae,parse:vs,gpsOnlyOptions:wn,gps:Na,thumbnailOnlyOptions:xn,thumbnail:$a,thumbnailUrl:Ha,orientationOnlyOptions:vn,orientation:Sn,rotations:kn,get rotateCanvas(){return Ne},get rotateCss(){return $e},rotation:_a});Ce.set("url",class extends br{async readWhole(){this.chunked=!1;let r=await He(this.input);r instanceof ArrayBuffer?this._swapArrayBuffer(r):r instanceof Uint8Array&&this._swapBuffer(r)}async _readChunk(r,t){let e=t?r+t-1:void 0,i=this.options.httpHeaders||{};(r||e)&&(i.range=`bytes=${[r,e].join("-")}`);let s=await yn(this.input,{headers:i}),o=await s.arrayBuffer(),n=o.byteLength;if(s.status!==416)return n!==t&&(this.size=r+n),this.set(o,r,!0)}});qt.prototype.getUint64=function(r){let t=this.getUint32(r),e=this.getUint32(r+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 xt("Trying to read 64b value but JS can only handle 53b numbers.")};var gs=class extends gr{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),s=t+8;return e===1&&(e=this.file.getUint64(t+8),s+=8),{offset:t,length:e,kind:i,start:s}}parseBoxFullHead(t){if(t.version!==void 0)return;let e=this.file.getUint32(t.start);t.version=e>>24,t.start+=4}},yr=class extends gs{static canHandle(t,e){if(e!==0)return!1;let i=t.getUint16(2);if(i>50)return!1;let s=16,o=[];for(;s<i;)o.push(t.getString(s,4)),s+=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 s=this.file.subarray(e,i);this.createParser(t,s)}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 s=this.findBox(i,"colr");s!==void 0&&await this.registerSegment("icc",s.offset+12,s.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 s=this.findExifLocIdInIinf(e),o=this.findExtentInIloc(i,s);if(o===void 0)return;let[n,c]=o;await this.file.ensureChunk(n,c);let l=4+this.file.getUint32(n);n+=l,c-=l,await this.registerSegment("tiff",n,c)}findExifLocIdInIinf(t){this.parseBoxFullHead(t);let e,i,s,o,n=t.start,c=this.file.getUint16(n);for(n+=2;c--;){if(e=this.parseBoxHead(n),this.parseBoxFullHead(e),i=e.start,e.version>=2&&(s=e.version===3?4:2,o=this.file.getString(i+s+2,4),o==="Exif"))return this.file.getUintBytes(i,s);n+=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,[s,o]=this.get8bits(i++),[n,c]=this.get8bits(i++),l=t.version===2?4:2,d=t.version===1||t.version===2?2:0,u=c+s+o,h=t.version===2?4:2,g=this.file.getUintBytes(i,h);for(i+=h;g--;){let m=this.file.getUintBytes(i,l);i+=l+d+2+n;let E=this.file.getUint16(i);if(i+=2,m===e)return E>1&&console.warn(`ILOC box has more than one extent but we're only processing one
|
|
4
|
+
Please create an issue at https://github.com/MikeKovarik/exifr with this file`),[this.file.getUintBytes(i+c,s),this.file.getUintBytes(i+c+s,o)];i+=E*u}}},wr=class extends yr{};st(wr,"type","heic");var xr=class extends yr{};st(xr,"type","avif"),Ee.set("heic",wr),Ee.set("avif",xr),Ft(Kt,["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"]]),Ft(Kt,"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"]]),Ft(Kt,"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"]]),Ft(We,["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 gi=Ft(We,"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"}]]),hn={1:"No absolute unit of measurement",2:"Inch",3:"Centimeter"};gi.set(37392,hn),gi.set(41488,hn);var os={0:"Normal",1:"Low",2:"High"};function pn(r){return typeof r=="object"&&r.length!==void 0?r[0]:r}function fn(r){let t=Array.from(r).slice(1);return t[1]>15&&(t=t.map((e=>String.fromCharCode(e)))),t[2]!=="0"&&t[2]!==0||t.pop(),t.join(".")}function ns(r){if(typeof r=="string"){var[t,e,i,s,o,n]=r.trim().split(/[-: ]/g).map(Number),c=new Date(t,e-1,i);return Number.isNaN(s)||Number.isNaN(o)||Number.isNaN(n)||(c.setHours(s),c.setMinutes(o),c.setSeconds(n)),Number.isNaN(+c)?r:c}}function fi(r){if(typeof r=="string")return r;let t=[];if(r[1]===0&&r[r.length-1]===0)for(let e=0;e<r.length;e+=2)t.push(un(r[e+1],r[e]));else for(let e=0;e<r.length;e+=2)t.push(un(r[e],r[e+1]));return mn(String.fromCodePoint(...t))}function un(r,t){return r<<8|t}gi.set(41992,os),gi.set(41993,os),gi.set(41994,os),Ft(Pe,["ifd0","ifd1"],[[50827,function(r){return typeof r!="string"?bn(r):r}],[306,ns],[40091,fi],[40092,fi],[40093,fi],[40094,fi],[40095,fi]]),Ft(Pe,"exif",[[40960,fn],[36864,fn],[36867,ns],[36868,ns],[40962,pn],[40963,pn]]),Ft(Pe,"gps",[[0,r=>Array.from(r).join(".")],[7,r=>Array.from(r).join(":")]]);var mi=class extends Gt{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:qt.from(t).getString()}parse(t=this.chunk){if(!this.localOptions.parse)return t;t=(function(o){let n={},c={};for(let l of Dn)n[l]=[],c[l]=0;return o.replace(qa,((l,d,u)=>{if(d==="<"){let h=++c[u];return n[u].push(h),`${l}#${h}`}return`${l}#${n[u].pop()}`}))})(t);let e=vr.findAll(t,"rdf","Description");e.length===0&&e.push(new vr("rdf","Description",void 0,t));let i,s={};for(let o of e)for(let n of o.properties)i=Ka(n.ns,s),Pn(n,i);return(function(o){let n;for(let c in o)n=o[c]=pr(o[c]),n===void 0&&delete o[c];return pr(o)})(s)}assignToOutput(t,e){if(this.localOptions.parse)for(let[i,s]of Object.entries(e))switch(i){case"tiff":this.assignObjectToOutput(t,"ifd0",s);break;case"exif":this.assignObjectToOutput(t,"exif",s);break;case"xmlns":break;default:this.assignObjectToOutput(t,i,s)}else t.xmp=e}};st(mi,"type","xmp"),st(mi,"multiSegment",!0),At.set("xmp",mi);var ms=class r{static findAll(t){return En(t,/([a-zA-Z0-9-]+):([a-zA-Z0-9-]+)=("[^"]*"|'[^']*')/gm).map(r.unpackMatch)}static unpackMatch(t){let e=t[1],i=t[2],s=t[3].slice(1,-1);return s=Cn(s),new r(e,i,s)}constructor(t,e,i){this.ns=t,this.name=e,this.value=i}serialize(){return this.value}},vr=class r{static findAll(t,e,i){if(e!==void 0||i!==void 0){e=e||"[\\w\\d-]+",i=i||"[\\w\\d-]+";var s=new RegExp(`<(${e}):(${i})(#\\d+)?((\\s+?[\\w\\d-:]+=("[^"]*"|'[^']*'))*\\s*)(\\/>|>([\\s\\S]*?)<\\/\\1:\\2\\3>)`,"gm")}else s=/<([\w\d-]+):([\w\d-]+)(#\d+)?((\s+?[\w\d-:]+=("[^"]*"|'[^']*'))*\s*)(\/>|>([\s\S]*?)<\/\1:\2\3>)/gm;return En(t,s).map(r.unpackMatch)}static unpackMatch(t){let e=t[1],i=t[2],s=t[4],o=t[8];return new r(e,i,s,o)}constructor(t,e,i,s){this.ns=t,this.name=e,this.attrString=i,this.innerXml=s,this.attrs=ms.findAll(i),this.children=r.findAll(s),this.value=this.children.length===0?Cn(s):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 Ga(this.children.map(Wa));if(this.isListItem&&this.children.length===1&&this.attrs.length===0)return this.children[0].serialize();let t={};for(let e of this.properties)Pn(e,t);return this.value!==void 0&&(t.value=this.value),pr(t)}};function Pn(r,t){let e=r.serialize();e!==void 0&&(t[r.name]=e)}var Wa=r=>r.serialize(),Ga=r=>r.length===1?r[0]:r,Ka=(r,t)=>t[r]?t[r]:t[r]={};function En(r,t){let e,i=[];if(!r)return i;for(;(e=t.exec(r))!==null;)i.push(e);return i}function Cn(r){if((function(i){return i==null||i==="null"||i==="undefined"||i===""||i.trim()===""})(r))return;let t=Number(r);if(!Number.isNaN(t))return t;let e=r.toLowerCase();return e==="true"||e!=="false"&&r.trim()}var Dn=["rdf:li","rdf:Seq","rdf:Bag","rdf:Alt","rdf:Description"],qa=new RegExp(`(<|\\/)(${Dn.join("|")})`,"g"),An=Va;async function In(r){try{return await An.parse(r)||null}catch{return null}}function vi(){return Array.from(crypto.getRandomValues(new Uint8Array(16)),r=>r.toString(16).padStart(2,"0")).join("")}async function Ln(r){if(typeof createImageBitmap>"u"||typeof document>"u"){if(r&&typeof r.arrayBuffer=="function"){let c=await r.arrayBuffer(),l=globalThis.Buffer,d=typeof l<"u"?l.from(c).toString("base64"):btoa(String.fromCharCode(...new Uint8Array(c)));return`data:${r.type||"image/png"};base64,${d}`}if(typeof r=="string")return r}let t=await createImageBitmap(r),s=Math.min(1,1654/t.width,2339/t.height);if(s===1&&(r.type==="image/jpeg"||r.type==="image/jpg"||r.type==="image/png"||r.type==="image/webp"))return t.close(),new Promise((c,l)=>{let d=new FileReader;d.onload=()=>c(d.result),d.onerror=l,d.readAsDataURL(r)});let o=document.createElement("canvas");o.width=Math.round(t.width*s),o.height=Math.round(t.height*s),o.getContext("2d").drawImage(t,0,0,o.width,o.height),t.close();let n=r.type==="image/png"?"image/png":"image/jpeg";return o.toDataURL(n,n==="image/png"?void 0:.82)}function Rn(r,t=21,e=.2,i=128){let{data:s,width:o,height:n}=r,c=o+1,l=new Float64Array((o+1)*(n+1)),d=new Float64Array((o+1)*(n+1)),u=new Uint8Array(o*n);for(let g=0;g<n;g++){let m=0,E=0,D=g*o,x=(g+1)*c,w=g*c;for(let A=0;A<o;A++){let k=(D+A)*4,R=s[k]*77+s[k+1]*150+s[k+2]*29>>8;u[D+A]=R,m+=R,E+=R*R,l[x+A+1]=l[w+A+1]+m,d[x+A+1]=d[w+A+1]+E}}let h=Math.floor(t/2);for(let g=0;g<n;g++){let m=Math.max(0,g-h),E=Math.min(n-1,g+h),D=m*c,x=(E+1)*c;for(let w=0;w<o;w++){let A=Math.max(0,w-h),k=Math.min(o-1,w+h),R=(k-A+1)*(E-m+1),U=l[x+k+1]-l[D+k+1]-l[x+A]+l[D+A],P=d[x+k+1]-d[D+k+1]-d[x+A]+d[D+A],y=U/R,B=Math.max(0,P/R-y*y),_=Math.sqrt(B),G=y*(1+e*(_/i-1)),N=g*o+w,V=u[N]<G?0:255,et=N*4;s[et]=V,s[et+1]=V,s[et+2]=V}}return r}function Sr(r){if(!r||typeof r!="object")return{crop:null,rotation:0,filter:"none"};let t=null;r.crop&&typeof r.crop=="object"&&(r.crop.width>0&&r.crop.height>0?t={x:Math.round(r.crop.x||0),y:Math.round(r.crop.y||0),width:Math.round(r.crop.width),height:Math.round(r.crop.height)}:r.crop.w>0&&r.crop.h>0&&(t={x:Number(r.crop.x)||0,y:Number(r.crop.y)||0,w:Number(r.crop.w)||1,h:Number(r.crop.h)||1}));let e=r.rotation!==void 0?r.rotation:r.rotate,i=(Math.round(Number(e)||0)%360+360)%360,s=r.filter==="bw"?"bw":"none";return{crop:t,rotation:i,filter:s}}function Xa(r){if(!r)return!1;let t=Sr(r);return!!(t.crop||t.rotation!==0||t.filter!=="none")}function kr(r,t){let e=Sr(t),i=r.naturalWidth||r.width||0,s=r.naturalHeight||r.height||0,o=document.createElement("canvas"),n=i,c=s,l=0,d=0;if(e.crop){let g=e.crop;"w"in g&&!("width"in g)?(l=Math.max(0,Math.min(Math.round(g.x*i),i)),d=Math.max(0,Math.min(Math.round(g.y*s),s)),n=Math.max(1,Math.min(Math.round(g.w*i),i-l)),c=Math.max(1,Math.min(Math.round(g.h*s),s-d))):(l=Math.max(0,Math.min(g.x,i)),d=Math.max(0,Math.min(g.y,s)),n=Math.max(1,Math.min(g.width,i-l)),c=Math.max(1,Math.min(g.height,s-d)))}o.width=n,o.height=c,o.getContext("2d").drawImage(r,l,d,n,c,0,0,n,c);let h=o;if(e.rotation!==0){let g=e.rotation,m=document.createElement("canvas");g===90||g===270?(m.width=h.height,m.height=h.width):(m.width=h.width,m.height=h.height);let E=m.getContext("2d");E.translate(m.width/2,m.height/2),E.rotate(g*Math.PI/180),E.drawImage(h,-h.width/2,-h.height/2),h=m}if(e.filter==="bw"){let g=h.getContext("2d"),m=g.getImageData(0,0,h.width,h.height);Rn(m),g.putImageData(m,0,0)}return h}function Bn(r,t){if(!r)return Promise.resolve("");let e=Sr(t);return Xa(e)?new Promise((i,s)=>{let o=new Image;o.onload=()=>{try{let n=r.startsWith("data:image/png"),c=n?"image/png":"image/jpeg",l=kr(o,e);i(l.toDataURL(c,n?void 0:.82))}catch(n){s(n)}},o.onerror=s,o.src=r}):Promise.resolve(r)}var Ge=class{#t=null;#r=new Map;#s=new Map;constructor(t=dr()){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.#e(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.#e(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 s=this.#t.getDocSync(t);return s?{id:s.id,name:s.name||"",pages:this.#e(s.pages)}:null}let i=this.listDocsSync().find(s=>s.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.#e(e.pages)}:null}return this.getDocSync(t)}async createDoc(t="Untitled Document",e=[]){let i=vi(),s=this.#e(e),o={id:i,name:t||"Untitled Document",pages:s};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.#e(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 s=this.getDocSync(t);if(s){if(this.#l(t),await this.#t.deleteDoc(t),e&&i>0){let o=setTimeout(async()=>{this.#r.delete(t)},i);this.#r.set(t,{doc:s,timerId:o})}return{id:t,name:s.name,undo:()=>this.undoDeleteDoc(t)}}}#l(t){if(this.#r.has(t)){let e=this.#r.get(t);clearTimeout(e.timerId),this.#r.delete(t)}}async undoDeleteDoc(t){let e=this.#r.get(t);return e?(clearTimeout(e.timerId),this.#r.delete(t),await this.#t.saveDoc(t,e.doc),e.doc):null}isSoftDeletedDoc(t){return this.#r.has(t)}async addPages(t,e){let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);let s=Array.isArray(e)?e:[e];i.pages.push(...s),await this.saveDoc(t,i)}async updatePage(t,e,i){let s=await this.getDoc(t);if(!s)throw new Error(`Document "${t}" not found`);let o=s.pages.findIndex(n=>n.id===e);if(o===-1)throw new Error(`Page "${e}" not found in document "${t}"`);s.pages[o]={...s.pages[o],...i},await this.saveDoc(t,s)}async reorderPages(t,e){let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);let s=new Map(i.pages.map(n=>[n.id,n])),o=[];for(let n of e)s.has(n)&&(o.push(s.get(n)),s.delete(n));for(let n of s.values())o.push(n);i.pages=o,await this.saveDoc(t,i)}async deletePage(t,e,{soft:i=!0,timeoutMs:s=5e3}={}){let o=await this.getDoc(t);if(!o)throw new Error(`Document "${t}" not found`);let n=o.pages.findIndex(u=>u.id===e);if(n===-1)return;let[c]=o.pages.splice(n,1);await this.saveDoc(t,o);let l=`${t}:${e}`;if(this.#a(l),!i||s<=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 d=setTimeout(async()=>{if(this.#s.delete(l),typeof this.#t.deletePage=="function")try{await this.#t.deletePage(t,e)}catch(u){console.warn("[DocRepository] Adapter deletePage error:",u)}},s);return this.#s.set(l,{docId:t,pageId:e,page:c,index:n,timerId:d}),{docId:t,pageId:e,undo:()=>this.undoDeletePage(t,e)}}#a(t){if(this.#s.has(t)){let e=this.#s.get(t);clearTimeout(e.timerId),this.#s.delete(t)}}async undoDeletePage(t,e){let i=`${t}:${e}`,s=this.#s.get(i);if(!s)return null;clearTimeout(s.timerId),this.#s.delete(i);let o=await this.getDoc(t);if(!o)return null;let n=Math.min(s.index,o.pages.length);return o.pages.splice(n,0,s.page),await this.saveDoc(t,o),s.page}isSoftDeletedPage(t,e){return this.#s.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 s=await this.getDoc(i.id),o=[];for(let n of s?.pages||[]){if(!n){o.push(n);continue}let c={...n},l=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&&(c.src=await rs(l));let d=c.originalBlob instanceof Blob?c.originalBlob:null;if(!d&&typeof c.originalSrc=="string"&&c.originalSrc.startsWith("blob:"))try{d=await(await fetch(c.originalSrc)).blob()}catch{}d&&(c.originalSrc=await rs(d)),delete c.blob,delete c.originalBlob,o.push(c)}e[i.id]={name:i.name,pages:JSON.stringify(o)}}return e}async importDocs(t){let e=0;for(let[i,s]of Object.entries(t||{})){await this.getDoc(i)||e++;let n=this.#e(s.pages);await this.saveDoc(i,{name:s.name||"",pages:n})}return e}#e(t){if(Array.isArray(t))return[...t];if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}},Ja=new Ge;var Tn=".";function Mn(){return Tn}function Si(r){typeof r=="string"&&(Tn=r.replace(/\/+$/,"")||".")}var Pr=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 Jt=class extends Pr{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 Er=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 De=class extends Er{async exportDocumentAsPdf(t,e,i={}){let s=new Error('Feature "pdf" is disabled or PDF module not opted in');throw s.code="FEATURE_DISABLED",s}async renderPdfPagesToDataUrls(t){return[]}};var Ae=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 Ya(r){return new Promise((t,e)=>{let i=new Image;i.onload=()=>t(i),i.onerror=e,i.src=r})}var ki=class extends Ae{async renderEdits(t,e={}){if(!t)return"";if(typeof document>"u")return t;try{let i=await Ya(t),s={...e};return e?.crop&&"w"in e.crop&&(s.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&&(s.rotation=e.rotate),kr(i,s).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 Pi=class extends Ae{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 ks(r={}){let t=r&&r.crop&&typeof r.crop=="object"?{x:Math.max(0,Math.min(1,Number(r.crop.x)||0)),y:Math.max(0,Math.min(1,Number(r.crop.y)||0)),w:Math.max(0,Math.min(1,Number(r.crop.w)||1)),h:Math.max(0,Math.min(1,Number(r.crop.h)||1))}:null,e=0,i=r?.rotate!==void 0?r.rotate:r?.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 s=r&&r.filter==="bw"?"bw":"none";return{crop:t,rotate:e,filter:s}}var Ct=r=>Math.round(r*1e6)/1e6;function Ps(r,t=0){if(!r)return null;let e=(Math.round(Number(t)/90)*90%360+360)%360,{x:i,y:s,w:o,h:n}=r;return e===90?{x:Ct(Math.max(0,Math.min(1,1-s-n))),y:Ct(Math.max(0,Math.min(1,i))),w:Ct(Math.max(.01,Math.min(1,n))),h:Ct(Math.max(.01,Math.min(1,o)))}:e===180?{x:Ct(Math.max(0,Math.min(1,1-i-o))),y:Ct(Math.max(0,Math.min(1,1-s-n))),w:Ct(Math.max(.01,Math.min(1,o))),h:Ct(Math.max(.01,Math.min(1,n)))}:e===270?{x:Ct(Math.max(0,Math.min(1,s))),y:Ct(Math.max(0,Math.min(1,1-i-o))),w:Ct(Math.max(.01,Math.min(1,n))),h:Ct(Math.max(.01,Math.min(1,o)))}:{x:Ct(Math.max(0,Math.min(1,i))),y:Ct(Math.max(0,Math.min(1,s))),w:Ct(Math.max(.01,Math.min(1,o))),h:Ct(Math.max(.01,Math.min(1,n)))}}function Es(r,t=0){return Ps(r,t)}function Cs(r,t=0){return Ps(r,-t)}var St={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 On(r,t,e={}){let i=new CustomEvent(t,{bubbles:!0,composed:!0,cancelable:!0,detail:e});return r&&typeof r.dispatchEvent=="function"&&r.dispatchEvent(i),i}var Is=["crop","rotate","filter","ocr","export","sync"],Ds=["pdf","zip","png","jpg"],As=["eng"],Un={};function Ke(r){return Un[r]?Un[r]:typeof globalThis<"u"&&globalThis.__copio_services__?.[r]?globalThis.__copio_services__[r]:null}function Qa(r){return r?r instanceof Set?new Set(r):Array.isArray(r)?new Set(r.map(t=>String(t).trim().toLowerCase()).filter(Boolean)):typeof r=="string"?new Set(r.split(/[\s,]+/).map(t=>t.trim().toLowerCase()).filter(Boolean)):new Set(Is):new Set(Is)}function Cr(r,t){return r?Array.isArray(r)?r.map(e=>String(e).trim().toLowerCase()).filter(Boolean):typeof r=="string"?r.split(/[\s,]+/).map(e=>e.trim().toLowerCase()).filter(Boolean):[...t]:[...t]}var Ei=class{#t=new Set(Is);#r=[...Ds];#s=[...As];#l=0;#a="";#e=null;#c=null;#o={};#i=!0;#n=!0;#d=null;#h=new Map;#p=new Map;constructor(t={}){this.#e=t.storage||dr(t),this.#c=t.repository||new Ge(this.#e),t.services&&(this.#o={...t.services}),t.imageProcessor?(this.#d=t.imageProcessor,this.#o.imageProcessor=t.imageProcessor):this.getService("imageProcessor")?this.#d=this.getService("imageProcessor"):typeof document<"u"?this.#d=new ki:this.#d=new Pi,t.features!==void 0&&this.setFeatures(t.features),t.exportFormats!==void 0&&(this.#r=Cr(t.exportFormats,Ds)),t.ocrLanguages!==void 0&&(this.#s=Cr(t.ocrLanguages,As)),t.maxPages!==void 0&&(this.#l=Math.max(0,Number(t.maxPages)||0)),t.assetBase!==void 0&&Si(t.assetBase),t.licenseKey!==void 0&&(this.#a=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.#r.includes("pdf")&&(this.pdf=!1)}async init(){return this.#e.init()}setService(t,e){this.#o[t]=e}getService(t){return this.#o[t]||Ke(t)}hasFeature(t){return t?this.#t.has(String(t).trim().toLowerCase()):!1}get features(){return Array.from(this.#t)}setFeatures(t){this.#t=Qa(t),this.hasFeature("ocr")?(this.#i=!0,this.getService("ocr")instanceof Jt&&this.setService("ocr",Ke("ocr"))):(this.#i=!1,this.setService("ocr",new Jt))}enableFeature(t){if(t){let e=String(t).trim().toLowerCase();this.#t.add(e),e==="ocr"&&(this.#i=!0,this.getService("ocr")instanceof Jt&&this.setService("ocr",Ke("ocr")))}}disableFeature(t){if(t){let e=String(t).trim().toLowerCase();this.#t.delete(e),e==="ocr"&&(this.#i=!1,this.setService("ocr",new Jt))}}get ocr(){return this.#i&&this.hasFeature("ocr")}set ocr(t){this.#i=!!t,this.#i?(this.enableFeature("ocr"),this.getService("ocr")instanceof Jt&&this.setService("ocr",Ke("ocr"))):(this.disableFeature("ocr"),this.setService("ocr",new Jt))}get pdf(){return this.#n&&this.#r.includes("pdf")}set pdf(t){this.#n=!!t,this.#n?(this.#r.includes("pdf")||this.#r.push("pdf"),this.getService("pdf")instanceof De&&this.setService("pdf",Ke("pdf"))):(this.#r=this.#r.filter(e=>e!=="pdf"),this.setService("pdf",new De))}get exportFormats(){return[...this.#r]}set exportFormats(t){this.#r=Cr(t,Ds),this.#r.includes("pdf")?(this.#n=!0,this.getService("pdf")instanceof De&&this.setService("pdf",Ke("pdf"))):(this.#n=!1,this.setService("pdf",new De))}get ocrLanguages(){return[...this.#s]}set ocrLanguages(t){this.#s=Cr(t,As)}get maxPages(){return this.#l}set maxPages(t){this.#l=Math.max(0,Number(t)||0)}get assetBase(){return Mn()}set assetBase(t){Si(t)}get licenseKey(){return this.#a}set licenseKey(t){this.#a=String(t||"")}get storage(){return this.#e}setStorage(t){t&&(this.#e=t,this.#c=new Ge(this.#e))}#u(t,e){this.#h.has(t)||this.#h.set(t,[]);let i=this.#h.get(t);i.push(e),i.length>50&&i.shift(),this.#p.has(t)&&(this.#p.get(t).length=0)}get imageProcessor(){return this.#d}setImageProcessor(t){t&&(this.#d=t,this.setService("imageProcessor",t))}async renderEdits(t,e){if(!t)return"";let i=ks(e);return this.#d?this.#d.renderEdits(t,i):Bn(t,i)}get docs(){return this.#c}async listDocuments(){return this.#c.listDocs()}async getDocument(t){return this.#c.getDoc(t)}async createDocument(t,e){return this.#c.createDoc(t,e)}async deleteDocument(t,e={}){return this.#c.deleteDoc(t,e)}async undoDeleteDocument(t){return this.#c.undoDeleteDoc(t)}async renameDocument(t,e){return this.#c.renameDoc(t,e)}async addPages(t,e){return this.#c.addPages(t,e)}async deletePage(t,e,i={}){return this.#u(t,{type:"delete",pageId:e}),this.#c.deletePage(t,e,i)}async undoDeletePage(t,e){return this.#c.undoDeletePage(t,e)}async updatePage(t,e,i){return this.#c.updatePage(t,e,i)}async reorderPages(t,e){let i=await this.getDocument(t),s=i?.pages?i.pages.map(o=>o.id):[];return this.#u(t,{type:"reorder",priorOrder:s,newOrder:[...e]}),this.#c.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 s=await this.#g(t),o=s?await this.getDocument(s):null;if(!o||!o.pages)throw new Error(`Document with ID "${s||t}" not found`);let n=o.pages.find(g=>g.id===e);if(!n)throw new Error(`Page with ID "${e}" not found in document "${s}"`);let c={...n.edits||{crop:null,rotate:0,filter:"none"}},l=n.src,d=ks({...c,...i}),u=n.originalSrc||n.src,h=u;return this.#d&&(h=await this.#d.renderEdits(u,d)),await this.updatePage(s,e,{originalSrc:u,src:h,edits:d}),this.#u(s,{type:"edit",pageId:e,priorEdits:c,priorSrc:l,newEdits:d,newSrc:h}),{...n,originalSrc:u,src:h,edits:d}}async undo(t){let e=await this.#g(t),i=e?this.#h.get(e):null;if(!i||i.length===0)return null;let s=i.pop();return this.#p.has(e)||this.#p.set(e,[]),this.#p.get(e).push(s),s.type==="edit"?(await this.updatePage(e,s.pageId,{edits:s.priorEdits,src:s.priorSrc}),{type:"edit",pageId:s.pageId,restoredEdits:s.priorEdits}):s.type==="delete"?(await this.undoDeletePage(e,s.pageId),{type:"delete",pageId:s.pageId}):s.type==="reorder"?(await this.#c.reorderPages(e,s.priorOrder),{type:"reorder",priorOrder:s.priorOrder}):s}async redo(t){let e=await this.#g(t),i=e?this.#p.get(e):null;if(!i||i.length===0)return null;let s=i.pop();return this.#h.has(e)||this.#h.set(e,[]),this.#h.get(e).push(s),s.type==="edit"?(await this.updatePage(e,s.pageId,{edits:s.newEdits,src:s.newSrc}),{type:"edit",pageId:s.pageId,appliedEdits:s.newEdits}):s.type==="delete"?(await this.deletePage(e,s.pageId),{type:"delete",pageId:s.pageId}):s.type==="reorder"?(await this.reorderPages(e,s.newOrder),{type:"reorder",newOrder:s.newOrder}):s}subscribe(t){return this.#c.subscribe(t)}async addFiles(t,e=null){if(!t||t.length===0)return[];let i=Array.from(t),s=[];for(let n of i)if(n.type==="application/pdf"){let c=this.getService("pdf");if(c&&typeof c.renderPdfPagesToDataUrls=="function"){let l=await c.renderPdfPagesToDataUrls(n);for(let d of l)s.push({id:vi(),src:d,originalSrc:d,edits:{crop:null,rotation:0,filter:"none"},type:"image",name:n.name||"PDF Page"})}else console.warn("PDF import service (PdfPort) not registered. Skipping PDF file.")}else if(n.type&&n.type.startsWith("image/")){let c=await Ln(n),l=null;try{l=await In(n)}catch{}s.push({id:vi(),src:c,originalSrc:c,edits:{crop:null,rotation:0,filter:"none"},type:"image",name:n.name||"Captured Image",orientation:l})}if(s.length===0)return[];await this.init();let o=e;if(o)await this.getDocument(o)||await this.#c.saveDoc(o,{name:"Scanned Document",pages:[]});else{let n=await this.listDocuments();n.length>0?o=n[0].id:o=(await this.createDocument("Scanned Document",[])).id}if(this.#l>0){let n=(await this.getDocument(o))?.pages||[],c=Math.max(0,this.#l-n.length);if(c<=0)throw new Error(`Maximum page limit (${this.#l}) reached`);s.splice(c)}return await this.addPages(o,s),s}async getPages(t=null){let e=t;if(!e){let s=await this.listDocuments();if(s.length===0)return[];e=s[0].id}return(await this.getDocument(e))?.pages||[]}async clear(t=null){let e=t;if(!e){let s=await this.listDocuments();if(s.length===0)return;e=s[0].id}let i=await this.getDocument(e);if(!(!i||!i.pages))for(let s of i.pages)await this.deletePage(e,s.id)}async#f(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 n=new Error('Feature "export" is disabled');throw Object.assign(n,{code:"FEATURE_DISABLED"}),n}if(!this.#n||!this.#r.includes("pdf")){let n=new Error('Feature "pdf" is disabled');throw Object.assign(n,{code:"FEATURE_DISABLED"}),n}let{docName:i,pages:s}=await this.#f(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,s,{download:!1,showProgress:!1,onOcrComplete:async()=>{if(typeof t=="string"){let n=await this.#e.getDoc(t);n&&(n.pages=s,await this.#e.saveDoc(t,n))}},...e})}async exportZip(t,e={}){if(!this.hasFeature("export")){let n=new Error('Feature "export" is disabled');throw Object.assign(n,{code:"FEATURE_DISABLED"}),n}let{docName:i,pages:s}=await this.#f(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,s,{download:!1,showProgress:!1,...e})}async runOcr(t,e=null,i={}){if(!this.#i||!this.hasFeature("ocr")){let d=new Error('Feature "ocr" is disabled');throw Object.assign(d,{code:"FEATURE_DISABLED"}),d}let{pages:s}=await this.#f(t),o=s;e&&(o=s.filter(d=>d.id===e));let n=this.getService("ocr");if(!n||typeof n.recognizeDocumentPages!="function")throw new Error("OCR service (OcrPort) is not registered. Import @copio/sdk or register an ocrService.");let c=i.lang||this.#s[0]||"eng",l=await n.recognizeDocumentPages(o,{lang:c,...i});if(Array.isArray(l.pagesResults)){for(let d of l.pagesResults){let u=o.find(h=>h.id===d.pageId)||o[d.pageIndex];u&&(u.ocrText=d.text,u.ocrConfidence=d.confidence,u.ocrWords=d.words)}if(typeof t=="string"){let d=await this.#e.getDoc(t);if(d&&Array.isArray(d.pages)){for(let u of l.pagesResults){let h=d.pages.find(g=>g.id===u.pageId)||d.pages[u.pageIndex];h&&(h.ocrText=u.text,h.ocrConfidence=u.confidence,h.ocrWords=u.words)}await this.#e.saveDoc(t,d)}}}return{text:l.combinedText,...l}}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.#c,t.onStateChange)}};var zn=null,Fn={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 qe(r){zn=r||null}function Xe(){return zn||(typeof document<"u"?document.body:null)}function Za(){let t=customElements.get("sl-alert")?.toastStack;t&&t.querySelectorAll("sl-alert").forEach(i=>{typeof i.hide=="function"&&i.hide()})}async function jn(r,t={}){let e={};if(typeof r=="string"||r instanceof HTMLElement?e={message:r,...t}:r&&typeof r=="object"&&(e={...r,...t}),typeof customElements<"u"&&!customElements.get("sl-alert")&&await Promise.race([customElements.whenDefined("sl-alert"),new Promise(h=>setTimeout(h,200))]),typeof customElements>"u"||!customElements.get("sl-alert"))return null;let i=customElements.get("sl-alert"),s=e.variant||"info",o=Fn[s]||Fn.info,n=e.container||Xe();if(i?.toastStack&&n){let h=i.toastStack;h.parentElement!==n&&n.appendChild(h),n!==document.body?(h.style.position="absolute",h.style.width="auto",h.style.maxWidth="calc(100% - 24px)",h.style.left="12px",h.style.right="12px",h.style.insetInlineStart="12px",h.style.insetInlineEnd="12px",e.position==="top"?(h.style.top="12px",h.style.bottom="auto"):(h.style.top="auto",h.style.bottom="16px"),h.style.maxHeight="100%",h.style.overflow="auto"):(h.style.position="",h.style.width="",h.style.left="",h.style.right="",h.style.top="",h.style.bottom="",h.style.insetInlineStart="",h.style.insetInlineEnd="",h.style.maxHeight="",h.style.maxWidth="",h.style.overflow="")}let c=document.createElement("sl-alert");c.variant=o.slVariant,c.closable=e.closable!==!1,c.duration=e.duration!==void 0?e.duration:o.defaultDuration;let l=e.icon!==void 0?e.icon:o.defaultIcon;if(l){let h=document.createElement("sl-icon");h.slot="icon",h.name=l,c.appendChild(h)}let d=document.createElement("span");if(e.message instanceof HTMLElement?d.appendChild(e.message):e.html?d.innerHTML=e.message||"":d.textContent=e.message||"",e.action){let h=document.createElement("div");h.style.display="flex",h.style.alignItems="center",h.style.justifyContent="space-between",h.style.gap="0.75rem",h.style.width="100%",d.style.flex="1",h.appendChild(d);let g=document.createElement("sl-button");g.size="small",g.variant=e.action.variant||"text",g.textContent=e.action.text||"Action",g.style.color="inherit",g.style.fontWeight="600",g.style.padding="0",g.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),typeof e.action.onClick=="function"&&e.action.onClick(m,c),e.action.autoClose!==!1&&c.hide()}),h.appendChild(g),c.appendChild(h)}else c.appendChild(d);let u=c.toast();return c.toastPromise=u,c}function tc(r,t={}){return Ci.show({message:r,variant:"success",...t})}function ec(r,t={}){return Ci.show({message:r,variant:"error",...t})}function ic(r,t={}){return Ci.show({message:r,variant:"warning",...t})}function rc(r,t={}){return Ci.show({message:r,variant:"info",...t})}function sc(r,t,e={}){return Ci.show({message:r,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,s)=>{typeof t=="function"&&t(i,s)},autoClose:!0},...e})}async function oc(r,t={}){let e={};if(typeof r=="string"?e={message:r,...t}:r&&typeof r=="object"&&(e={...r,...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(D=>setTimeout(D,200))]),typeof customElements>"u"||!customElements.get("sl-alert"))return{alert:null,progressBar:null,update(){},close(){}};let i=e.container||Xe(),s=document.createElement("sl-alert");s.variant=e.variant||"primary",s.closable=e.closable===!0,s.duration=1/0;let o=e.icon!==void 0?e.icon:"arrow-down-circle";if(o){let D=document.createElement("sl-icon");D.slot="icon",D.name=o,s.appendChild(D)}let n=document.createElement("div");n.className="notify-progress-wrapper",n.style.display="flex",n.style.flexDirection="column",n.style.gap="0.35rem",n.style.minWidth="220px";let c=document.createElement("div");c.style.display="flex",c.style.justifyContent="space-between",c.style.alignItems="center",c.style.gap="0.5rem";let l=document.createElement("span");l.className="notify-progress-message",l.style.fontWeight="500",l.style.fontSize="0.9rem",l.textContent=e.message||"Processing...",c.appendChild(l);let d=document.createElement("span");d.className="notify-progress-status",d.style.fontSize="0.78rem",d.style.color="#64748b",d.style.fontWeight="600";let u=e.done!==void 0?e.done:0,h=e.total!==void 0?e.total:0;h>0?d.textContent=`${u} / ${h}`:e.value!==void 0&&(d.textContent=`${e.value}%`),c.appendChild(d),n.appendChild(c);let g=document.createElement("sl-progress-bar");h>0?g.value=Math.round(u/h*100):e.value!==void 0?g.value=e.value:g.indeterminate=!0,n.appendChild(g),s.appendChild(n);let m=customElements.get("sl-alert");if(m?.toastStack&&i){let D=m.toastStack;D.parentElement!==i&&i.appendChild(D)}return s.toast(),{alert:s,progressBar:g,update({done:D,total:x,value:w,message:A}={}){if(A!==void 0&&(l.textContent=A),x!==void 0&&D!==void 0){g.indeterminate=!1;let k=Math.min(100,Math.max(0,Math.round(D/Math.max(x,1)*100)));g.value=k,d.textContent=`${D} / ${x}`}else w!==void 0&&(g.indeterminate=!1,g.value=Math.min(100,Math.max(0,w)),d.textContent=`${Math.round(g.value)}%`)},close(){typeof s.hide=="function"&&s.hide()}}}var Ci=Object.assign(function(r,t){return jn(r,t)},{show:jn,success:tc,error:ec,warning:ic,info:rc,undo:sc,progress:oc,clear:Za,setContainer:qe,getContainer:Xe});var Ls=`
|
|
1088
5
|
:host {
|
|
1089
6
|
all: initial;
|
|
1090
7
|
display: block;
|
|
@@ -2263,7 +1180,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2263
1180
|
min-width: 200px;
|
|
2264
1181
|
}
|
|
2265
1182
|
}
|
|
2266
|
-
`,
|
|
1183
|
+
`,Di=null;function Nn(){if(Di)return Di;if(typeof CSSStyleSheet<"u"&&typeof Document<"u"&&"adoptedStyleSheets"in Document.prototype&&"replaceSync"in CSSStyleSheet.prototype)try{return Di=new CSSStyleSheet,Di.replaceSync(Ls),Di}catch{return null}return null}function $n(r){if(!r)return;let t=Nn();if(t&&"adoptedStyleSheets"in r){let e=r.adoptedStyleSheets||[];e.includes(t)||(r.adoptedStyleSheets=[...e,t])}else if(!r.querySelector("style[data-copio-encapsulated-styles]")){let e=document.createElement("style");e.setAttribute("data-copio-encapsulated-styles",""),e.textContent=Ls,r.appendChild(e)}}var nc=typeof HTMLElement<"u"?HTMLElement:class{},Rs=class extends nc{#t=null;#r=null;#s=null;#l=!1;#a="viewfinder";#e=0;#c=0;#o=!1;#i=!1;#n=null;#d=null;#h=0;#p=null;#u=null;#g=null;onShutter=null;get#f(){return this.docId?this.docId:(this.#u||(this.#u=`doc_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`),this.#u)}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.#w()}#w(){let t={storage:this.#r};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 Ei(t)}connectedCallback(){this.shadowRoot&&($n(this.shadowRoot),this.#y()),typeof qe=="function"&&typeof document<"u"&&Xe()===document.body&&qe(this.shadowRoot?.querySelector(".copio-scanner-container")||this),this.#t&&(this.#s=this.#t.subscribe(async()=>{let t=await this.getPages();this.dispatch(St.PAGES_CHANGED,{pages:t,docId:this.docId}),this.#m()})),this.hasAttribute&&this.hasAttribute("asset-base")&&Si(this.getAttribute("asset-base")),this.#b(),this.#m()}disconnectedCallback(){if(this.#x(),typeof this.#s=="function"&&(this.#s(),this.#s=null),this.#d&&(clearInterval(this.#d),this.#d=null),typeof qe=="function"&&typeof document<"u"){let t=this.shadowRoot?.querySelector(".copio-scanner-container")||this;Xe()===t&&qe(null)}}attributeChangedCallback(t,e,i){if(!(e===i||!this.#t))switch(t){case"features":this.#t.setFeatures(i),this.#b();break;case"export-formats":this.#t.exportFormats=i,this.#b();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.#b();break;case"pdf":this.#t.pdf=i!=="false",this.#b();break;case"stage":if(i==="viewfinder"||i==="workbench"){this.#a=i;let s=this.shadowRoot;if(s){let o=s.getElementById("viewfinder-section"),n=s.getElementById("workbench-section");o&&n&&(o.style.display=i==="viewfinder"?"flex":"none",n.style.display=i==="workbench"?"flex":"none")}this.#m()}break;case"max-pages":this.#t.maxPages=i,this.#m();break;case"mode":case"aspect":case"theme":this.#m();break}}#b(){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 s of i)"ocr"in s&&(s.ocr=this.ocrEnabled),"pdf"in s&&(s.pdf=this.pdf)}}#y(){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=`
|
|
2267
1184
|
<div class="copio-scanner-container copio-scanner-host" part="scanner-root">
|
|
2268
1185
|
<header class="copio-header" part="header">
|
|
2269
1186
|
<div class="copio-header-left">
|
|
@@ -2440,7 +1357,7 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2440
1357
|
<input type="file" id="internal-file-input" accept="image/*" style="display: none;" />
|
|
2441
1358
|
<slot></slot>
|
|
2442
1359
|
</div>
|
|
2443
|
-
`,this.#
|
|
1360
|
+
`,this.#A()}#A(){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 s=i.target;s.files&&s.files.length>0&&(await this.addFiles(s.files),s.value="")}),t.getElementById("btn-shutter")?.addEventListener("click",async()=>{await this.#R()}),t.getElementById("btn-review")?.addEventListener("click",()=>{this.stage="workbench"}),t.getElementById("btn-retake")?.addEventListener("click",()=>{this.#o=!0,this.#i=!1,this.stage="viewfinder"}),t.getElementById("btn-rotate")?.addEventListener("click",async()=>{await this.#P()}),t.getElementById("btn-filter-bw")?.addEventListener("click",async()=>{await this.#E()}),t.getElementById("btn-crop")?.addEventListener("click",async()=>{await this.#C()}),t.getElementById("btn-delete")?.addEventListener("click",async()=>{await this.#D()}),t.getElementById("btn-ocr")?.addEventListener("click",async()=>{await this.#T()}),t.getElementById("btn-close-ocr")?.addEventListener("click",()=>{this.#M()}),t.getElementById("btn-primary-complete")?.addEventListener("click",async()=>{await this.#O()}),t.getElementById("btn-card-front")?.addEventListener("click",()=>{this.#i=!1,this.#e=0,this.#m()}),t.getElementById("btn-card-back")?.addEventListener("click",()=>{this.#i=!1,this.#e=1,this.#m()}),this.#v()}#v(){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 s=null,o=!1,n=0,c=0,l=null,d=g=>{let m=g.target.closest(".copio-crop-handle");if(m)s=m.getAttribute("data-handle"),o=!1;else if(g.target===e||g.target.classList.contains("copio-crop-grid"))s=null,o=!0;else return;g.preventDefault(),g.stopPropagation(),n=g.clientX,c=g.clientY,l=this.#n?{...this.#n}:{x:.05,y:.05,w:.9,h:.9},window.addEventListener("pointermove",u),window.addEventListener("pointerup",h)},u=g=>{if(!s&&!o||!l)return;let E=(t.getElementById("canvas-wrapper")||t.getElementById("canvas-viewport"))?.getBoundingClientRect()||{width:300,height:400},D=(g.clientX-n)/Math.max(E.width,1),x=(g.clientY-c)/Math.max(E.height,1),{x:w,y:A,w:k,h:R}=l;if(o)w=Math.min(Math.max(0,w+D),1-k),A=Math.min(Math.max(0,A+x),1-R);else if(s){if(s.includes("w")){let U=Math.min(Math.max(0,w+D),w+k-.1);k+=w-U,w=U}if(s.includes("e")&&(k=Math.min(Math.max(.1,k+D),1-w)),s.includes("n")){let U=Math.min(Math.max(0,A+x),A+R-.1);R+=A-U,A=U}s.includes("s")&&(R=Math.min(Math.max(.1,R+x),1-A))}this.#n={x:w,y:A,w:k,h:R},this.#S()},h=()=>{s=null,o=!1,l=null,window.removeEventListener("pointermove",u),window.removeEventListener("pointerup",h)};e.addEventListener("pointerdown",d),i.forEach(g=>{g.addEventListener("pointerdown",d)})}#S(){let t=this.shadowRoot;if(!t||!this.#n)return;let e=t.getElementById("crop-box");e&&(e.style.left=`${(this.#n.x*100).toFixed(1)}%`,e.style.top=`${(this.#n.y*100).toFixed(1)}%`,e.style.width=`${(this.#n.w*100).toFixed(1)}%`,e.style.height=`${(this.#n.h*100).toFixed(1)}%`)}async#m(){if(this.shadowRoot)return this.#p?this.#p:(this.#p=(async()=>{try{await Promise.resolve(),await this.#I()}finally{this.#p=null}})(),this.#p)}async#I(){if(this.shadowRoot)try{let t=await this.getPages();this.#c=t.length;let e=this.shadowRoot,i=e.getElementById("mode-badge");i&&(i.textContent=(this.mode||"single").toUpperCase());let s=e.getElementById("tab-viewfinder"),o=e.getElementById("tab-workbench");s&&s.setAttribute("aria-selected",String(this.#a==="viewfinder")),o&&o.setAttribute("aria-selected",String(this.#a==="workbench"));let n=e.getElementById("viewfinder-section"),c=e.getElementById("workbench-section");n&&c&&(this.#a==="viewfinder"?(n.style.display="flex",c.style.display="none"):(n.style.display="none",c.style.display="flex"));let l=e.getElementById("framing-guide");l&&l.setAttribute("data-aspect",this.aspect||"auto");let d=e.getElementById("step-pill-text");d&&(this.#g?d.textContent="Camera Active \xB7 Tap Shutter to Snap":this.aspect==="card"&&this.maxPages===2?d.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"?d.textContent="Align Card Inside Frame":this.mode==="batch"?d.textContent=`Batch Capture \xB7 Page ${t.length+1}`:d.textContent="Align Document Inside Frame");let u=e.getElementById("btn-ocr");u&&(u.style.display=this.ocrEnabled&&this.hasFeature("ocr")?"":"none");let h=e.getElementById("btn-review"),g=e.getElementById("review-pill-text");if(h&&g&&(t.length>0?(h.style.display="inline-flex",g.textContent=`Review (${t.length}) \u2192`):h.style.display="none"),t.length===0){this.#a==="workbench"&&(this.stage="viewfinder");return}this.#e>=t.length&&(this.#e=Math.max(0,t.length-1));let m=t[this.#e],E=e.getElementById("card-side-switcher");if(E){let R=this.aspect==="card"&&this.maxPages===2;E.style.display=R?"flex":"none";let U=e.getElementById("btn-card-front"),P=e.getElementById("btn-card-back");U&&(U.classList.toggle("active",this.#e===0),U.setAttribute("aria-selected",String(this.#e===0))),P&&(P.classList.toggle("active",this.#e===1),P.setAttribute("aria-selected",String(this.#e===1)))}let D=e.getElementById("canvas-viewport");D&&D.classList.toggle("is-cropping",this.#i);let x=e.getElementById("stage-img");if(x)if(this.#i){let R=m.edits?.rotate||0,U=m.edits?.filter||"none",P=m.originalSrc||m.src||"";if(R!==0||U!=="none"){let y=this.#t?await this.#t.renderEdits(P,{rotate:R,filter:U}):P;x.src=y||P}else x.src=P}else x.src=m.src||m.originalSrc||"";let w=e.getElementById("crop-layer");if(this.#i){if(!w){let P=e.getElementById("canvas-wrapper");w=document.createElement("div"),w.className="copio-crop-layer",w.id="crop-layer",w.innerHTML=`
|
|
2444
1361
|
<div class="copio-crop-box" id="crop-box">
|
|
2445
1362
|
<div class="copio-crop-grid"></div>
|
|
2446
1363
|
<span class="copio-crop-handle nw" data-handle="nw"></span>
|
|
@@ -2452,51 +1369,30 @@ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),
|
|
|
2452
1369
|
<span class="copio-crop-handle s edge-s" data-handle="s"></span>
|
|
2453
1370
|
<span class="copio-crop-handle w edge-w" data-handle="w"></span>
|
|
2454
1371
|
</div>
|
|
2455
|
-
`,
|
|
1372
|
+
`,P?.appendChild(w),this.#v()}w.style.display="block";let R=m.edits?.rotate||0,U=m.edits?.crop;this.#n=U?Es(U,R):{x:.05,y:.05,w:.9,h:.9},this.#S()}else w&&w.remove();let A=e.getElementById("crop-btn-label");A&&(A.textContent=this.#i?"Apply":"Crop");let k=e.getElementById("btn-primary-complete");k&&(this.aspect==="card"&&this.maxPages===2&&t.length===1?k.textContent="Next: Capture Back (Step 2/2) \u2192":this.aspect==="card"&&t.length>=2?k.textContent="\u2713 Complete ID Scan (2 Sides)":this.mode==="batch"?k.textContent=`\u2713 Complete Scan (${t.length} Pages)`:k.textContent="\u2713 Use Photo"),this.#L(t)}catch{}}#L(t){let e=this.shadowRoot;if(!e)return;let i=e.getElementById("filmstrip-scroll");i&&(i.innerHTML="",t.forEach((s,o)=>{let n=document.createElement("div");n.className=`copio-filmstrip-item ${o===this.#e?"is-active":""}`,n.setAttribute("data-index",String(o)),n.innerHTML=`
|
|
2456
1373
|
<div class="copio-thumb-container">
|
|
2457
|
-
<img src="${
|
|
2458
|
-
<span class="copio-thumb-num">${
|
|
1374
|
+
<img src="${s.src||s.originalSrc}" alt="Page ${o+1}" class="copio-thumb-img" />
|
|
1375
|
+
<span class="copio-thumb-num">${o+1}</span>
|
|
2459
1376
|
</div>
|
|
2460
1377
|
${this.mode==="batch"?`
|
|
2461
1378
|
<div class="copio-thumb-reorder">
|
|
2462
|
-
<button type="button" class="copio-reorder-btn move-left" title="Move Left" ${
|
|
2463
|
-
<button type="button" class="copio-reorder-btn move-right" title="Move Right" ${
|
|
1379
|
+
<button type="button" class="copio-reorder-btn move-left" title="Move Left" ${o===0?"disabled":""}>\u25C0</button>
|
|
1380
|
+
<button type="button" class="copio-reorder-btn move-right" title="Move Right" ${o===t.length-1?"disabled":""}>\u25B6</button>
|
|
2464
1381
|
</div>
|
|
2465
1382
|
`:""}
|
|
2466
|
-
`,
|
|
1383
|
+
`,n.querySelector(".copio-thumb-container")?.addEventListener("click",()=>{this.#e=o,this.#i=!1,this.#m()}),this.mode==="batch"&&(n.querySelector(".move-left")?.addEventListener("click",async c=>{c.stopPropagation(),await this.#k(o,o-1)}),n.querySelector(".move-right")?.addEventListener("click",async c=>{c.stopPropagation(),await this.#k(o,o+1)})),i.appendChild(n)}))}async#k(t,e){let i=await this.getPages();if(e<0||e>=i.length||t===e)return;let s=i.map(n=>n.id),[o]=s.splice(t,1);s.splice(e,0,o),await this.#t.reorderPages(this.#f,s),this.#e=e,this.#m()}#x(){this.#g&&(this.#g.getTracks().forEach(s=>s.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#R(){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 n=o.getContext("2d");if(n){n.drawImage(e,0,0,o.width,o.height);let c=await new Promise(l=>o.toBlob(l,"image/jpeg",.92));if(c){this.#x();let l=new File([c],`capture_${Date.now()}.jpg`,{type:"image/jpeg"});await this.addFiles([l]);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 n=t?.getElementById("step-pill-text");n&&(n.textContent="Camera Active \xB7 Tap Shutter to Snap");return}catch{}let s=t?.getElementById("internal-file-input");s&&typeof s.click=="function"&&s.click()}async#P(){let e=(await this.getPages())[this.#e];if(!e)return;this.#i&&(this.#i=!1,this.#n=null);let s=((e.edits?.rotate||0)+90)%360;await this.#t.applyEdit(this.#f,e.id,{rotate:s}),await this.#m()}async#E(){let e=(await this.getPages())[this.#e];if(!e)return;this.#i&&(this.#i=!1,this.#n=null);let s=(e.edits?.filter||"none")==="bw"?"none":"bw";await this.#t.applyEdit(this.#f,e.id,{filter:s}),await this.#m()}async#C(){let e=(await this.getPages())[this.#e];if(e){if(this.#i){this.#i=!1;let i=this.#n;if(this.#n=null,i){let s=e.edits?.rotate||0,o=Cs(i,s);await this.#t.applyEdit(this.#f,e.id,{crop:o})}}else this.#i=!0;await this.#m()}}async#D(){let t=await this.getPages(),e=t[this.#e];if(!e)return;let i=e.id;await this.#t.deletePage(this.#f,i),this.dispatch(St.PAGE_REMOVED,{pageId:i,docId:this.docId}),this.#e>=t.length-1&&(this.#e=Math.max(0,t.length-2)),this.#B(),await this.#m()}#B(){let t=this.shadowRoot;if(!t)return;let e=t.getElementById("toast-region");if(!e)return;this.#d&&clearInterval(this.#d),this.#h=5;let i=()=>{e.innerHTML=`
|
|
2467
1384
|
<div class="copio-toast copio-toast-undo">
|
|
2468
1385
|
<span>Page deleted</span>
|
|
2469
1386
|
<button type="button" class="copio-btn-toast-undo" id="btn-toast-undo">
|
|
2470
|
-
Undo (${this.#
|
|
1387
|
+
Undo (${this.#h}s)
|
|
2471
1388
|
</button>
|
|
2472
1389
|
</div>
|
|
2473
|
-
`,t.getElementById("btn-toast-undo")?.addEventListener("click",async()=>{clearInterval(this.#
|
|
1390
|
+
`,t.getElementById("btn-toast-undo")?.addEventListener("click",async()=>{clearInterval(this.#d),this.#d=null,e.innerHTML="",await this.#t.undo(this.#f),await this.#m()})};i(),this.#d=setInterval(()=>{this.#h-=1,this.#h<=0?(clearInterval(this.#d),this.#d=null,e.innerHTML=""):i()},1e3)}async#T(){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.#e],n=await this.ocr(o?.id||null),c=n.averageConfidence||0,l=c<=1&&c>0?Math.round(c*100):Math.round(c);i.innerHTML=`
|
|
2474
1391
|
<div class="copio-ocr-content">
|
|
2475
|
-
<pre class="copio-ocr-text">${
|
|
1392
|
+
<pre class="copio-ocr-text">${n.text||"No text detected."}</pre>
|
|
2476
1393
|
<div class="copio-ocr-meta">
|
|
2477
|
-
<span>Confidence: ${
|
|
1394
|
+
<span>Confidence: ${l}%</span>
|
|
2478
1395
|
</div>
|
|
2479
1396
|
</div>
|
|
2480
|
-
`}catch(
|
|
2481
|
-
/**!
|
|
2482
|
-
* Sortable 1.15.6
|
|
2483
|
-
* @author RubaXa <trash@rubaxa.org>
|
|
2484
|
-
* @author owenm <owen23355@gmail.com>
|
|
2485
|
-
* @license MIT
|
|
2486
|
-
*/
|
|
2487
|
-
/**
|
|
2488
|
-
* @license
|
|
2489
|
-
* Copyright 2019 Google LLC
|
|
2490
|
-
* SPDX-License-Identifier: BSD-3-Clause
|
|
2491
|
-
*/
|
|
2492
|
-
/**
|
|
2493
|
-
* @license
|
|
2494
|
-
* Copyright 2017 Google LLC
|
|
2495
|
-
* SPDX-License-Identifier: BSD-3-Clause
|
|
2496
|
-
*/
|
|
2497
|
-
/**
|
|
2498
|
-
* @license
|
|
2499
|
-
* Copyright 2022 Google LLC
|
|
2500
|
-
* SPDX-License-Identifier: BSD-3-Clause
|
|
2501
|
-
*/
|
|
1397
|
+
`}catch(s){i.innerHTML=`<p class="copio-ocr-error">OCR recognition failed: ${s.message}</p>`}}}#M(){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.#c===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((s,o)=>({id:s.id,pageNumber:o+1,label:s.label||`Page ${o+1}`,originalSrc:s.originalSrc,src:s.src,originalPreserved:!0,dimensions:{width:s.width||0,height:s.height||0},edits:s.edits||{crop:{x:0,y:0,w:1,h:1},rotate:0,filter:"none"},ocrText:s.ocrText||null,blob:s.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(St.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.#a}set stage(t){if(t==="viewfinder"||t==="workbench"){this.#a=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"),s=e.getElementById("workbench-section");i&&s&&(i.style.display=t==="viewfinder"?"flex":"none",s.style.display=t==="workbench"?"flex":"none")}this.#m()}}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.#E()}async toggleCropMode(){return this.#C()}async deleteActivePageWithUndo(){return this.#D()}setCameraStream(t){this.#x(),this.#g=t}get features(){return this.#t?this.#t.features:[]}set features(t){if(typeof this.setAttribute=="function"){let e=Array.isArray(t)?t.join(" "):String(t||"");this.setAttribute("features",e)}this.#t&&this.#t.setFeatures(t)}hasFeature(t){return this.#t?this.#t.hasFeature(t):!1}get ocrEnabled(){return this.#t?this.#t.ocr:!0}set ocrEnabled(t){let e=!!t;typeof this.setAttribute=="function"&&this.setAttribute("ocr",e?"true":"false"),this.#t&&(this.#t.ocr=e),this.#b()}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.#b()}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.#r}set storage(t){this.#r=t,this.#t&&this.#t.setStorage(t)}get engine(){return this.#t}set engine(t){t instanceof Ei&&(this.#t=t)}dispatch(t,e={}){return On(this,t,e)}async open(){this.#l=!0,typeof this.focus=="function"&&this.focus()}async close(){this.#l=!1,this.#x()}get isOpen(){return this.#l}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(St.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.#f);else if(this.#o||this.maxPages>0&&e.length>=this.maxPages){let n=Math.min(this.#e,e.length-1),c=e[n];c&&(i=n,await this.#t.deletePage(this.#f,c.id))}}this.#o=!1;let s=await this.#t.addFiles(t,this.#f);for(let n=0;n<s.length;n++)this.dispatch(St.PAGE_ADDED,{page:s[n],pageNumber:n+1,docId:this.docId,source:"file"});let o=await this.getPages();if(i!==null&&s.length===1&&i<o.length-1){let n=o.map(l=>l.id),c=n.pop();c&&(n.splice(i,0,c),await this.#t.reorderPages(this.#f,n),o=await this.getPages())}return this.#c=o.length,s.length>0&&(this.#e=i!==null?Math.min(i,Math.max(0,o.length-1)):Math.max(0,o.length-1),this.mode==="single"&&(this.#a="workbench",typeof this.setAttribute=="function"&&this.getAttribute("stage")!=="workbench"&&this.setAttribute("stage","workbench"))),this.dispatch(St.PAGES_CHANGED,{pages:o,docId:this.docId}),this.mode==="single"&&s.length>0&&this.maxPages<=1&&this.dispatch(St.SCAN_COMPLETE,{mode:this.mode,aspect:this.aspect,docId:this.docId,pages:o,page:o[o.length-1]||null,pageCount:o.length}),await this.#m(),s}catch(e){throw this.dispatch(St.ERROR,{code:e.code||"ADD_FILES_FAILED",message:e.message,error:e}),e}}async getPages(){return this.#t.getPages(this.#f)}async clear(){this.#x(),this.#e=0,this.#c=0,this.#o=!1,this.#i=!1,await this.#t.clear(this.#f),this.dispatch(St.PAGES_CHANGED,{pages:[],docId:this.docId}),await this.#m()}async exportPdf(t={}){try{let e=await this.#t.exportPdf(this.#f,t);return this.dispatch(St.EXPORT_COMPLETE,{type:"pdf",format:"pdf",blob:e,searchable:!!t.searchable,docId:this.docId}),e}catch(e){throw this.dispatch(St.ERROR,{code:e.code||"EXPORT_FAILED",message:e.message,error:e}),e}}async exportZip(t={}){try{let e=await this.#t.exportZip(this.#f,t);return this.dispatch(St.EXPORT_COMPLETE,{type:"zip",format:"zip",blob:e,docId:this.docId}),e}catch(e){throw this.dispatch(St.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.#f,t,e);return this.dispatch(St.OCR_COMPLETE,{text:i.text,pages:i.pagesResults,averageConfidence:i.averageConfidence,docId:this.docId,pageId:t}),i}catch(i){throw this.dispatch(St.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(St.SYNC_CONNECTED,{peerId:i.peerId,mode:i.mode}),t.onStateChange&&t.onStateChange(i)}})}catch(e){throw this.dispatch(St.ERROR,{code:e.code||"SYNC_FAILED",message:e.message,error:e}),e}}};typeof customElements<"u"&&!customElements.get("copio-scanner")&&customElements.define("copio-scanner",Rs);export{St as COPIO_EVENTS,Rs as CopioScanner,$n as adoptScannerStyles,On as dispatchCopioEvent,Nn as getScannerStyleSheet,Ls as scannerCss};
|
|
2502
1398
|
//# sourceMappingURL=scanner.js.map
|