@copio/sdk 0.1.4 → 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/dist/cdn.js +1 -1
- package/dist/{chunk-IBF5HCYT.js → chunk-O7IV7A6O.js} +2 -2
- package/dist/{chunk-FFRDPFTS.js → chunk-Q7XPZMZA.js} +2 -2
- package/dist/core.js +1 -1
- package/dist/custom-elements.json +1 -1
- package/dist/index.js +1 -1
- package/dist/types/sdk/version.d.ts +1 -1
- package/package.json +2 -2
- package/sdk/version.js +1 -1
package/dist/cdn.js
CHANGED
|
@@ -6,7 +6,7 @@ ${u.text}`:u.text).join(`
|
|
|
6
6
|
|
|
7
7
|
`),v=Math.round(d/g.length);return{pagesResults:g,combinedText:m,averageConfidence:v}}async function hi(){if(Pe){try{await Pe.terminate()}catch(n){console.warn("Error during OCR worker termination:",n)}Pe=null,mr=null,li=null}}var Ys,Pe,mr,li,Js=ke(()=>{ii();Ni();Ys=[{code:"eng",label:"English",flag:"\u{1F1EC}\u{1F1E7}"},{code:"spa",label:"Spanish (Espa\xF1ol)",flag:"\u{1F1EA}\u{1F1F8}"},{code:"fra",label:"French (Fran\xE7ais)",flag:"\u{1F1EB}\u{1F1F7}"},{code:"deu",label:"German (Deutsch)",flag:"\u{1F1E9}\u{1F1EA}"},{code:"ita",label:"Italian (Italiano)",flag:"\u{1F1EE}\u{1F1F9}"},{code:"por",label:"Portuguese (Portugu\xEAs)",flag:"\u{1F1F5}\u{1F1F9}"},{code:"nld",label:"Dutch (Nederlands)",flag:"\u{1F1F3}\u{1F1F1}"},{code:"pol",label:"Polish (Polski)",flag:"\u{1F1F5}\u{1F1F1}"},{code:"rus",label:"Russian (\u0420\u0443\u0441\u0441\u043A\u0438\u0439)",flag:"\u{1F1F7}\u{1F1FA}"},{code:"chi_sim",label:"Chinese Simplified (\u7B80\u4F53\u4E2D\u6587)",flag:"\u{1F1E8}\u{1F1F3}"},{code:"chi_tra",label:"Chinese Traditional (\u7E41\u9AD4\u4E2D\u6587)",flag:"\u{1F1F9}\u{1F1FC}"},{code:"jpn",label:"Japanese (\u65E5\u672C\u8A9E)",flag:"\u{1F1EF}\u{1F1F5}"},{code:"kor",label:"Korean (\uD55C\uAD6D\uC5B4)",flag:"\u{1F1F0}\u{1F1F7}"},{code:"ara",label:"Arabic (\u0627\u0644\u0639\u0631\u0628\u064A\u0629)",flag:"\u{1F1F8}\u{1F1E6}"},{code:"hin",label:"Hindi (\u0939\u093F\u0928\u094D\u0926\u0940)",flag:"\u{1F1EE}\u{1F1F3}"},{code:"tur",label:"Turkish (T\xFCrk\xE7e)",flag:"\u{1F1F9}\u{1F1F7}"},{code:"vie",label:"Vietnamese (Ti\u1EBFng Vi\u1EC7t)",flag:"\u{1F1FB}\u{1F1F3}"}],Pe=null,mr=null,li=null});var za={};Re(za,{Path2D:()=>jh,createCanvas:()=>Hh,default:()=>$h});var $h,Hh,jh,Va=ke(()=>{$h={},Hh=()=>null,jh=globalThis.Path2D||class{}});var jc={};Re(jc,{Path2D:()=>Wh,createCanvas:()=>Vh,default:()=>zh});var zh,Vh,Wh,zc=ke(()=>{zh={},Vh=()=>null,Wh=globalThis.Path2D||class{}});var Vc={};Re(Vc,{Path2D:()=>Xh,createCanvas:()=>qh,default:()=>Gh});var Gh,qh,Xh,Wc=ke(()=>{Gh={},qh=()=>null,Xh=globalThis.Path2D||class{}});var Gc={};Re(Gc,{Path2D:()=>Jh,createCanvas:()=>Yh,default:()=>Kh});var Kh,Yh,Jh,qc=ke(()=>{Kh={},Yh=()=>null,Jh=globalThis.Path2D||class{}});var Xc={};Re(Xc,{Path2D:()=>td,createCanvas:()=>Zh,default:()=>Qh});var Qh,Zh,td,Kc=ke(()=>{Qh={},Zh=()=>null,td=globalThis.Path2D||class{}});var Yc={};Re(Yc,{Path2D:()=>sd,createCanvas:()=>id,default:()=>ed});var ed,id,sd,Jc=ke(()=>{ed={},id=()=>null,sd=globalThis.Path2D||class{}});var wr={};Re(wr,{BUILD_DATE:()=>vc,COPIO_EVENTS:()=>Vt,Canvas2DAdapter:()=>$e,CopioDocOcrDialog:()=>Qs,CopioEngine:()=>Oi,CopioScanner:()=>zs,CopioSyncDialog:()=>Zs,DocRepository:()=>ti,Document:()=>Us,ImageProcessorPort:()=>_e,IndexedDbStorageAdapter:()=>Se,LicenseManager:()=>br,MemoryStorageAdapter:()=>qe,NullImageProcessorAdapter:()=>Li,NullOcrAdapter:()=>de,NullPdfAdapter:()=>Ee,NullSyncAdapter:()=>rn,OcrPort:()=>Be,OpfsStorageAdapter:()=>Si,Page:()=>Fi,PdfKitAdapter:()=>Vi,PdfPort:()=>Ue,PeerJsAdapter:()=>nn,SUPPORTED_LANGUAGES:()=>Ys,ScanSession:()=>$s,StoragePort:()=>he,SyncManager:()=>di,SyncPort:()=>He,TesseractWasmAdapter:()=>zi,VERSION:()=>wc,adoptScannerStyles:()=>ur,clearNotifications:()=>Pa,createDefaultAdapter:()=>ns,dispatchCopioEvent:()=>lr,docRepository:()=>ds,exportDocumentAsImages:()=>Ha,exportDocumentAsPdf:()=>tn,extractExif:()=>Jn,fileToBase64:()=>Qn,getAssetBase:()=>ir,getContainer:()=>ai,getCroppedSrc:()=>ya,getOcrWorker:()=>ms,getRegisteredService:()=>si,getScannerStyleSheet:()=>dr,hasActiveEdits:()=>cr,loadCropper:()=>yc,loadJsZip:()=>nr,loadPdfKit:()=>sr,loadPeerJs:()=>rr,loadQrCode:()=>ar,loadScript:()=>ei,loadTesseract:()=>or,normalizeEditStack:()=>us,notify:()=>Dt,probeOpfs:()=>Un,randomId:()=>Di,recognizeDocumentPages:()=>Hi,recognizeImageText:()=>bs,registerService:()=>ni,renderPdfPagesToDataUrls:()=>vr,resolveAssetUrl:()=>Ne,rotateSrc:()=>ba,scannerCss:()=>js,setAssetBase:()=>Ii,setContainer:()=>ri,terminateOcrWorker:()=>hi,thresholdSrc:()=>ma});var he=class{async init(){throw new Error("StoragePort.init() must be implemented by adapter")}async listDocs(){throw new Error("StoragePort.listDocs() must be implemented by adapter")}async getDoc(t){throw new Error("StoragePort.getDoc() must be implemented by adapter")}async saveDoc(t,e){throw new Error("StoragePort.saveDoc() must be implemented by adapter")}async renameDoc(t,e){let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);i.name=e,await this.saveDoc(t,i)}async deleteDoc(t){throw new Error("StoragePort.deleteDoc() must be implemented by adapter")}async savePage(t,e,i){throw new Error("StoragePort.savePage() must be implemented by adapter")}async getPage(t,e){throw new Error("StoragePort.getPage() must be implemented by adapter")}async deletePage(t,e){throw new Error("StoragePort.deletePage() must be implemented by adapter")}subscribe(t){return()=>{}}};var qe=class extends he{#t=new Map;#e=new Map;#i=new Set;constructor(){super()}async init(){return{kind:"memory",persistent:!1}}listDocsSync(){return Array.from(this.#t.values()).map(t=>({id:t.id,name:t.name,pages:Array.isArray(t.pages)?[...t.pages]:[]}))}async listDocs(){return this.listDocsSync()}getDocSync(t){let e=this.#t.get(t);return e?{id:e.id,name:e.name,pages:Array.isArray(e.pages)?[...e.pages]:[]}:null}async getDoc(t){return this.getDocSync(t)}async saveDoc(t,e){if(!t)throw new Error("Cannot save document without an ID");let i=[];if(Array.isArray(e.pages))i=[...e.pages];else if(typeof e.pages=="string")try{i=JSON.parse(e.pages)}catch{i=[]}this.#t.set(t,{id:t,name:e.name||"",pages:i}),this.#n()}async deleteDoc(t){this.#t.delete(t);let e=`${t}/`;for(let i of this.#e.keys())i.startsWith(e)&&this.#e.delete(i);this.#n()}async renameDoc(t,e){let i=this.#t.get(t);if(!i)throw new Error(`Document "${t}" not found`);i.name=e,this.#n()}async savePage(t,e,i){this.#e.set(`${t}/${e}`,i);let r=this.#t.get(t);if(r){let o=r.pages.findIndex(g=>g.id===e);if(o>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?r.pages[o]={...r.pages[o],...i}:r.pages[o]={...r.pages[o],src:i};else{let g=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i};r.pages.push(g)}}this.#n()}async getPage(t,e){if(this.#e.has(`${t}/${e}`))return this.#e.get(`${t}/${e}`);let i=this.#t.get(t);if(i){let r=i.pages.find(o=>o.id===e);if(r)return r.src??r}return null}async deletePage(t,e){this.#e.delete(`${t}/${e}`);let i=this.#t.get(t);i&&(i.pages=i.pages.filter(r=>r.id!==e)),this.#n()}subscribe(t){return this.#i.add(t),()=>{this.#i.delete(t)}}clear(){this.#t.clear(),this.#e.clear(),this.#n()}#n(){for(let t of this.#i)try{t()}catch(e){console.error("Error in MemoryStorageAdapter subscriber:",e)}}};var Je=n=>typeof n;var yo=Je(""),sl=Je(!0),vo=Je(0),nl=Je(Je),wn="type",pi="default",Ir="Listener",lo="Result",Lr="add",fi="Has",_s="Ids",Ye="Table",ho=Ye+"s",rl=Ye+_s,Qi="Row",wo=Qi+"Count",xo=Qi+_s,al="Sorted"+Qi+_s,As="Cell",En=As+_s,_n="Value",uo=_n+"s",ol=_n+_s,Rt=n=>""+n;var cl=(n,t="",e)=>n.split(t,e),Fr=globalThis,Rn=Math,Pr=Rn.max,Tr=Rn.min,ll=Rn.floor,Ao=isFinite,At=n=>n==null,Mt=(n,t,e)=>At(n)?e?.():t(n),So=n=>n==yo||n==sl,hl=n=>Je(n)==yo,ve=n=>Je(n)==nl,Zi=n=>Array.isArray(n),Or=(n,t,e)=>n.slice(t,e),ce=n=>n.length,Eo=()=>{};var kr=async(n,t,e)=>{try{return await n()}catch(i){t?.(i)}},Nr=(n,t)=>n.includes(t),Cn=(n,t)=>n.every(t),_o=(n,t)=>ce(n)===ce(t)&&Cn(n,((e,i)=>t[i]===e)),po=(n,t)=>Cn(n,((e,i)=>i==0||t(n[i-1],e)<=0)),Br=(n,t)=>n.sort(t),re=(n,t)=>n.forEach(t),bi=(n,t)=>n.map(t),fo=n=>Co(n,((t,e)=>t+e),0),Ss=n=>ce(n)==0,Co=(n,t,e)=>n.reduce(t,e),ne=(n,...t)=>n.push(...t),go=n=>n.pop(),Po=n=>n.shift(),Yi=n=>{let t=Je(n);return So(t)||t==vo&&Ao(n)?t:void 0};var Pn=(n,t,e,i,r)=>At(r)?n.delCell(t,e,i,!0):n.setCell(t,e,i,r),Ur=(n,t,e)=>At(e)?n.delValue(t):n.setValue(t,e),zr=n=>t=>Co(ts(t),((e,i)=>e+n(i)),0),es=n=>n?.size??0,yi=zr(es),De=zr(yi),Rr=zr(De),Ft=(n,t)=>n?.has(t)??!1,yt=n=>At(n)||es(n)==0,ts=n=>[...n?.values()??[]],Ji=n=>n.clear(),bt=(n,t)=>n?.forEach(t),xe=(n,t)=>n?.delete(t),Qe=Object,mo=n=>Qe.getPrototypeOf(n),dl=Qe.isFrozen,To=Qe.entries,Tn=n=>!At(n)&&Mt(mo(n),(t=>t==Qe.prototype||At(mo(t))),(()=>!0)),ul=Qe.keys,is=Qe.freeze,pl=(n=[])=>Qe.fromEntries(n),xs=(n,t)=>t in n,ko=(n,t)=>(delete n[t],n),fl=(n,t)=>re(To(n),(([e,i])=>t(i,e))),Me=(n,t)=>pl(((e,i)=>bi(To(e),(([r,o])=>i(o,r))))(n,((e,i)=>[i,t(e,i)]))),we=n=>Tn(n)&&(t=>ce(ul(t)))(n)==0;var Xe=(n,t,e,i=0)=>At(n)||!Tn(n)||!i&&we(n)||dl(n)?(e?.(),!1):(fl(n,((r,o)=>{t(r,o)||ko(n,o)})),!!i||!we(n)),ft=n=>new Map(n),mi=n=>[...n?.keys()??[]],ht=(n,t)=>n?.get(t),Ht=(n,t)=>bt(n,((e,i)=>t(i,e))),mt=(n,t,e)=>At(e)?(xe(n,t),n):n?.set(t,e),Lt=(n,t,e,i)=>(Ft(n,t)?i?.(ht(n,t)):mt(n,t,e()),ht(n,t)),gi=(n,t,e,i=mt)=>(Me(t,((r,o)=>e(n,o,r))),Ht(n,(r=>xs(t,r)?0:i(n,r))),n),se=(n,t,e,i)=>{let r={};return bt(n,((o,g)=>{if(!e?.(o,g)){let d=t?t(o,g):o;i?.(d)||(r[g]=d)}})),r},$r=(n,t,e)=>se(n,(i=>se(i,t,e)),yt,we),xn=(n,t,e)=>se(n,(i=>$r(i,t,e)),yt,we),Ke=(n,t)=>{let e=ft();return bt(n,((i,r)=>e.set(r,t?.(i)??i))),e},Hr=n=>Ke(n,Ke),Mr=n=>Ke(n,Hr),Es=(n,t,e,i,r=0)=>Mt((e?Lt:ht)(n,t[r],r>ce(t)-2?e:ft),(o=>{if(r>ce(t)-2)return i?.(o)&&mt(n,t[r]),o;let g=Es(o,t,e,i,r+1);return yt(o)&&mt(n,t[r]),g})),jt=n=>new Set(Zi(n)||At(n)?n:[n]),Nt=(n,t)=>n?.add(t),Mn=(n,t,e,i,r)=>{let o=n.hasRow,g=ft(),d=ft(),m=ft(),v=ft(),u=ft(),a=ft(),p=(y,s,...c)=>{let f=Lt(a,y,jt);return re(c,(w=>Nt(f,w)&&s&&n.callListener(w))),c},x=(y,...s)=>Mt(ht(a,y),(c=>{re(Ss(s)?ts(c):s,(f=>{n.delListener(f),xe(c,f)})),yt(c)&&mt(a,y)})),T=(y,s)=>{mt(g,y,s),Ft(d,y)||(mt(d,y,t()),mt(v,y,ft()),mt(u,y,ft()),r(m))},l=y=>{mt(g,y),mt(d,y),mt(v,y),mt(u,y),x(y),r(m)};return[()=>n,()=>mi(g),y=>Ht(d,y),y=>Ft(d,y),y=>ht(g,y),y=>ht(d,y),(y,s)=>mt(d,y,s),T,(y,s,c,f,w)=>{T(y,s);let R=ft(),S=ft(),D=ht(v,y),N=ht(u,y),H=Y=>{let it=z=>n.getCell(s,Y,z),ot=ht(D,Y),K=o(s,Y)?e(f(it,Y)):void 0;if(ot===K||Zi(ot)&&Zi(K)&&_o(ot,K)||mt(R,Y,[ot,K]),!At(w)){let z=ht(N,Y),W=o(s,Y)?w(it,Y):void 0;z!=W&&mt(S,Y,W)}},j=Y=>{c((()=>{bt(R,(([,it],ot)=>mt(D,ot,it))),bt(S,((it,ot)=>mt(N,ot,it)))}),R,S,D,N,Y),Ji(R),Ji(S)};Ht(D,H),n.hasTable(s)&&re(n.getRowIds(s),(Y=>{Ft(D,Y)||H(Y)})),j(!0),x(y),p(y,0,n.addRowListener(s,null,((Y,it,ot)=>H(ot))),n.addTableListener(s,(()=>j())))},l,y=>i(y,m),()=>Ht(a,l),p,x]},kn=(n,t)=>hl(n)?e=>e(n):n??(()=>t??""),Cs=(n,t)=>{let e=new WeakMap;return i=>{e.has(i)||e.set(i,n(i));let r=e.get(i);return t?.(r),r}},gl=/^\d+$/,Ro=()=>{let n=[],t=0;return[e=>(e?Po(n):null)??""+t++,e=>{gl.test(e)&&ce(n)<1e3&&ne(n,e)}]},Ps=n=>{let t,[e,i]=Ro(),r=ft();return[(o,g,d,m=[],v=()=>[])=>{t??=n();let u=e(1);return mt(r,u,[o,g,d,m,v]),Nt(Es(g,d??[""],jt),u),u},(o,g,...d)=>re(((m,v=[""])=>{let u=[],a=(p,x)=>x==ce(v)?ne(u,p):v[x]===null?bt(p,(T=>a(T,x+1))):re([v[x],null],(T=>a(ht(p,T),x+1)));return a(m,0),u})(o,g),(m=>bt(m,(v=>ht(r,v)[0](t,...g??[],...d))))),o=>Mt(ht(r,o),(([,g,d])=>(Es(g,d??[""],void 0,(m=>(xe(m,o),yt(m)?1:0))),mt(r,o),i(o),d))),o=>Mt(ht(r,o),(([g,,d=[],m,v])=>{let u=(...a)=>{let p=ce(a);p==ce(d)?g(t,...a,...v(a)):At(d[p])?re(m[p]?.(...a)??[],(x=>u(...a,x))):u(...a,d[p])};u()}))]},hd=Cs((n=>{let t,e,i,r=100,o=ft(),g=ft(),d=1,m=ft(),v=ft(),[u,a,p]=Ps((()=>W)),x=ft(),T=ft(),l=[],y=[],s=(X,et)=>{d=0,n.transaction((()=>{let[st,ct]=ht(x,et);bt(st,((nt,G)=>bt(nt,((A,_)=>bt(A,((I,h)=>Pn(n,G,_,h,I[X]))))))),bt(ct,((nt,G)=>Ur(n,G,nt[X])))})),d=1},c=X=>{mt(x,X),mt(T,X),a(v,[X])},f=(X,et)=>re(((st,ct)=>st.splice(0,ct))(X,et??ce(X)),c),w=()=>f(l,ce(l)-r),R=()=>Mt(t,(()=>{ne(l,t),w(),f(y),t=void 0,i=1})),S=()=>{t=go(l),i=1},D,N,H=(X="")=>(At(t)&&(t=""+e++,mt(x,t,[o,g]),K(t,X),o=ft(),g=ft(),i=1),t),j=()=>{Ss(l)||(((X,...et)=>{X.unshift(...et)})(y,H()),s(0,t),t=go(l),i=1)},Y=()=>{Ss(y)||(ne(l,t),t=Po(y),s(1,t),i=1)},it=()=>{i&&(a(m),i=0)},ot=X=>{let et=H(X);return it(),et},K=(X,et)=>(z(X)&&ht(T,X)!==et&&(mt(T,X,et),a(v,[X])),W),z=X=>Ft(x,X),W={setSize:X=>(r=X,w(),W),addCheckpoint:ot,setCheckpoint:K,getStore:()=>n,getCheckpointIds:()=>[[...l],t,[...y]],forEachCheckpoint:X=>Ht(T,X),hasCheckpoint:z,getCheckpoint:X=>ht(T,X),goBackward:()=>(j(),it(),W),goForward:()=>(Y(),it(),W),goTo:X=>{let et=Nr(l,X)?j:Nr(y,X)?Y:null;for(;!At(et)&&X!=t;)et();return it(),W},addCheckpointIdsListener:X=>u(X,m),addCheckpointListener:(X,et)=>u(et,v,[X]),delListener:X=>(p(X),W),clear:()=>(f(l),f(y),At(t)||c(t),t=void 0,e=0,ot(),W),clearForward:()=>(Ss(y)||(f(y),a(m)),W),destroy:()=>{n.delListener(D),n.delListener(N)},getListenerStats:()=>({checkpointIds:yi(m),checkpoint:yi(v)}),_registerListeners:()=>{D=n.addCellListener(null,null,null,((X,et,st,ct,nt,G)=>{if(d){R();let A=Lt(o,et,ft),_=Lt(A,st,ft),I=Lt(_,ct,(()=>[G,void 0]));I[1]=nt,I[0]===nt&&yt(mt(_,ct))&&yt(mt(A,st))&&yt(mt(o,et))&&S(),it()}})),N=n.addValueListener(null,((X,et,st,ct)=>{if(d){R();let nt=Lt(g,et,(()=>[ct,void 0]));nt[1]=st,nt[0]===st&&yt(mt(g,et))&&S(),it()}}))}};return is(W.clear())}),(n=>n._registerListeners())),ml=cl("-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"),dd=ft(bi(ml,((n,t)=>[n,t])));var ud=Fr.crypto?n=>Fr.crypto.getRandomValues(n):n=>bi(n,(()=>ll(256*Rn.random())));var bl=JSON.stringify,Dr=JSON.parse,Ki=n=>bl(n,((t,e)=>{return i=Map,e instanceof i?Qe.fromEntries([...e]):e;var i})),pd=new Fr.TextEncoder;var fd=2**36,gd=2**30,md=2**24,bd=2**18;var Mo=(n,t)=>(n??0)<(t??0)?-1:1,yd=Cs((n=>{let t=ft(),e=ft(),[i,r,o]=Ps((()=>c)),[g,d,m,v,u,a,p,,x,T,l,y]=Mn(n,ft,(f=>At(f)?"":Zi(f)?bi(f,Rt):Rt(f)),i,r),s=(f,w,R)=>{let S=u(f);bt(R,((D,N)=>w(N,(H=>bt(D,(j=>H(j,(Y=>n.forEachCell(S,j,Y)))))))))},c={setIndexDefinition:(f,w,R,S,D,N=Mo)=>{let H=At(D)?void 0:([j],[Y])=>D(j,Y);return x(f,w,((j,Y,it,ot,K,z)=>{let W=0,X=jt(),et=jt(),st=a(f);if(bt(Y,(([ct,nt],G)=>{let A=jt(ct),_=jt(nt);bt(A,(I=>xe(_,I)?xe(A,I):0)),bt(A,(I=>{Nt(X,I),Mt(ht(st,I),(h=>{xe(h,G),yt(h)&&(mt(st,I),W=1)}))})),bt(_,(I=>{Nt(X,I),Ft(st,I)||(mt(st,I,jt()),W=1),Nt(ht(st,I),G),At(S)||Nt(et,I)}))})),j(),yt(K)||(z?Ht(st,(ct=>Nt(et,ct))):Ht(it,(ct=>Mt(ht(ot,ct),(nt=>re(Zi(nt)?nt:[nt],(G=>Nt(et,G))))))),bt(et,(ct=>{let nt=(A,_)=>N(ht(K,A),ht(K,_),ct),G=[...ht(st,ct)];po(G,nt)||(mt(st,ct,jt(Br(G,nt))),Nt(X,ct))}))),(W||z)&&!At(H)){let ct=[...st];po(ct,H)||(p(f,ft(Br(ct,H))),W=1)}W&&r(t,[f]),bt(X,(ct=>r(e,[f,ct])))}),kn(R),Mt(S,kn)),c},delIndexDefinition:f=>(T(f),c),getStore:g,getIndexIds:d,forEachIndex:f=>m(((w,R)=>f(w,(S=>s(w,S,R))))),forEachSlice:(f,w)=>s(f,w,a(f)),hasIndex:v,hasSlice:(f,w)=>Ft(a(f),w),getTableId:u,getSliceIds:f=>mi(a(f)),getSliceRowIds:(f,w)=>ts(ht(a(f),w)),addIndexIdsListener:l,addSliceIdsListener:(f,w)=>i(w,t,[f]),addSliceRowIdsListener:(f,w,R)=>i(R,e,[f,w]),delListener:f=>(o(f),c),destroy:y,getListenerStats:()=>({sliceIds:yi(t),sliceRowIds:De(e)})};return is(c)}));var An=n=>[n,n],Ut=(n,t=yi)=>t(n[0])+t(n[1]),$t=()=>[ft(),ft()],bo=n=>[...n],Sn=([n,t])=>n===t,ws=(n,t,e)=>mt(n,t,ht(n,t)==-e?void 0:e),Ts=()=>{let n,t,e=!1,i=!1,r=0,o=[],g=ft(),d=ft(),m=ft(),v=ft(),u=ft(),a=ft(),p=ft(),x=ft(),T=ft(),l=ft(),y=ft(),s=ft(),c=ft(),f=ft(),w=jt(),R=ft(),S=ft(),D=ft(),N=ft(),H=$t(),j=$t(),Y=$t(),it=$t(),ot=$t(),K=$t(),z=$t(),W=$t(),X=$t(),et=$t(),st=$t(),ct=$t(),nt=$t(),G=$t(),A=$t(),_=$t(),I=$t(),h=$t(),b=$t(),C=$t(),P=$t(),O=$t(),M=ft(),E=$t(),[L,U,B,k]=Ps((()=>Qt)),F=$=>{if(!Xe($,((J,at)=>Nr([wn,pi],at))))return!1;let q=$[wn];return!(!So(q)&&q!=vo)&&(Yi($[pi])!=q&&ko($,pi),!0)},V=Zi,Q=($,q)=>(!n||Ft(y,q)||be(q))&&Xe($,((J,at)=>Z(q,at,J)),(()=>be(q))),Z=($,q,J,at)=>Xe(at?J:dt(J,$,q),((ut,gt)=>Mt(tt($,q,gt,ut),(xt=>(J[gt]=xt,!0)),(()=>!1))),(()=>be($,q))),tt=($,q,J,at)=>n?Mt(ht(ht(y,$),J),(ut=>Yi(at)!=ut[wn]?be($,q,J,at,ut[pi]):at),(()=>be($,q,J,at))):At(Yi(at))?be($,q,J,at):at,rt=($,q)=>Xe(q?$:lt($),((J,at)=>Mt(pt(at,J),(ut=>($[at]=ut,!0)),(()=>!1))),(()=>ui())),pt=($,q)=>t?Mt(ht(c,$),(J=>Yi(q)!=J[wn]?ui($,q,J[pi]):q),(()=>ui($,q))):At(Yi(q))?ui($,q):q,dt=($,q,J)=>(Mt(ht(s,q),(([at,ut])=>{bt(at,((gt,xt)=>{xs($,xt)||($[xt]=gt)})),bt(ut,(gt=>{xs($,gt)||be(q,J,gt)}))})),$),lt=$=>(t&&(bt(f,((q,J)=>{xs($,J)||($[J]=q)})),bt(w,(q=>{xs($,q)||ui(q)}))),$),vt=$=>gi(y,$,((q,J,at)=>{let ut=ft(),gt=jt();gi(Lt(y,J,ft),at,((xt,_t,Pt)=>{mt(xt,_t,Pt),Mt(Pt[pi],(Te=>mt(ut,_t,Te)),(()=>Nt(gt,_t)))})),mt(s,J,[ut,gt])}),((q,J)=>{mt(y,J),mt(s,J)})),Et=$=>gi(c,$,((q,J,at)=>{mt(c,J,at),Mt(at[pi],(ut=>mt(f,J,ut)),(()=>Nt(w,J)))}),((q,J)=>{mt(c,J),mt(f,J),xe(w,J)})),wt=$=>we($)?mn():fn($),Ct=$=>gi(D,$,((q,J,at)=>Tt(J,at)),((q,J)=>je(J))),Tt=($,q)=>gi(Lt(D,$,(()=>(Ve($,1),mt(R,$,Ro()),mt(S,$,ft()),ft()))),q,((J,at,ut)=>It($,J,at,ut)),((J,at)=>ze($,J,at))),It=($,q,J,at,ut)=>gi(Lt(q,J,(()=>(Wi($,J,1),ft()))),at,((gt,xt,_t)=>Ot($,J,gt,xt,_t)),((gt,xt)=>Yt($,q,J,gt,xt,ut))),Ot=($,q,J,at,ut)=>{Ft(J,at)||pe($,q,at,1);let gt=ht(J,at);ut!==gt&&(Gt($,q,at,gt,ut),mt(J,at,ut))},Jt=($,q,J,at,ut)=>Mt(ht(q,J),(gt=>Ot($,J,gt,at,ut)),(()=>It($,q,J,dt({[at]:ut},$,J)))),ae=$=>we($)?bn():gn($),me=$=>gi(N,$,((q,J,at)=>le(J,at)),((q,J)=>Xt(J))),le=($,q)=>{Ft(N,$)||an($,1);let J=ht(N,$);q!==J&&(Gi($,J,q),mt(N,$,q))},ue=$=>ht(D,$)??Tt($,{}),je=$=>Tt($,{}),ze=($,q,J)=>{let[,at]=ht(R,$);at(J),It($,q,J,{},!0)},Yt=($,q,J,at,ut,gt)=>{let xt=ht(ht(s,$)?.[0],ut);if(!At(xt)&&!gt)return Ot($,J,at,ut,xt);let _t=Pt=>{Gt($,J,Pt,ht(at,Pt)),pe($,J,Pt,-1),mt(at,Pt)};At(xt)?_t(ut):Ht(at,_t),yt(at)&&(Wi($,J,-1),yt(mt(q,J))&&(Ve($,-1),mt(D,$),mt(R,$),mt(S,$)))},Xt=$=>{let q=ht(f,$);if(!At(q))return le($,q);Gi($,ht(N,$)),an($,-1),mt(N,$)},Ve=($,q)=>ws(g,$,q),Wi=($,q,J)=>ws(Lt(v,$,ft),q,J)&&mt(m,$,Lt(m,$,(()=>0))+J),pe=($,q,J,at)=>{let ut=ht(S,$),gt=ht(ut,J)??0;(gt==0&&at==1||gt==1&&at==-1)&&ws(Lt(d,$,ft),J,at),mt(ut,J,gt!=-at?gt+at:null),ws(Lt(Lt(u,$,ft),q,ft),J,at)},Gt=($,q,J,at,ut)=>{Lt(Lt(Lt(a,$,ft),q,ft),J,(()=>[at,0]))[1]=ut,o[3]?.($,q,J,ut)},an=($,q)=>ws(p,$,q),Gi=($,q,J)=>{Lt(x,$,(()=>[q,0]))[1]=J,o[4]?.($,J)},be=($,q,J,at,ut)=>(ne(Lt(Lt(Lt(T,$,ft),q,ft),J,(()=>[])),at),ut),ui=($,q,J)=>(ne(Lt(l,$,(()=>[])),q),J),ye=($,q,J)=>Mt(ht(ht(ht(a,$),q),J),(([at,ut])=>[!0,at,ut]),(()=>[!1,...An(hn($,q,J))])),on=$=>Mt(ht(x,$),(([q,J])=>[!0,q,J]),(()=>[!1,...An(dn($))])),qi=$=>yt(T)||yt(_[$])?0:bt($?Mr(T):T,((q,J)=>bt(q,((at,ut)=>bt(at,((gt,xt)=>U(_[$],[J,ut,xt],gt))))))),We=$=>yt(l)||yt(I[$])?0:bt($?Ke(l):l,((q,J)=>U(I[$],[J],q))),te=($,q,J,at)=>{if(!yt($))return U(q,at,(()=>se($))),Ht($,((ut,gt)=>U(J,[...at??[],ut],gt==1))),1},cn=$=>{let q=un();q!=e&&U(H[$],void 0,q);let J=yt(et[$]),at=yt(nt[$])&&yt(G[$])&&yt(X[$])&&yt(st[$])&&yt(K[$])&&yt(z[$])&&yt(W[$])&&J&&yt(Y[$])&&yt(it[$]),ut=yt(A[$])&&yt(ct[$])&&yt(ot[$])&&yt(j[$]);if(!at||!ut){let gt=$?[Ke(g),Hr(d),Ke(m),Hr(v),Mr(u),Mr(a)]:[g,d,m,v,u,a];if(!at){te(gt[0],Y[$],it[$]),bt(gt[1],((_t,Pt)=>te(_t,K[$],z[$],[Pt]))),bt(gt[2],((_t,Pt)=>{_t!=0&&U(W[$],[Pt],Xa(Pt))}));let xt=jt();bt(gt[3],((_t,Pt)=>{te(_t,X[$],st[$],[Pt])&&!J&&(U(et[$],[Pt,null]),Nt(xt,Pt))})),J||bt(gt[5],((_t,Pt)=>{if(!Ft(xt,Pt)){let Te=jt();bt(_t,(Ge=>bt(Ge,(([yn,vn],vs)=>vn!==yn?Nt(Te,vs):xe(Ge,vs))))),bt(Te,(Ge=>U(et[$],[Pt,Ge])))}})),bt(gt[4],((_t,Pt)=>bt(_t,((Te,Ge)=>te(Te,nt[$],G[$],[Pt,Ge])))))}if(!ut){let xt;bt(gt[5],((_t,Pt)=>{let Te;bt(_t,((Ge,yn)=>{let vn;bt(Ge,(([vs,co],el)=>{co!==vs&&(U(A[$],[Pt,yn,el],co,vs,ye),xt=Te=vn=1)})),vn&&U(ct[$],[Pt,yn],ye)})),Te&&U(ot[$],[Pt],ye)})),xt&&U(j[$],void 0,ye)}}},Wa=$=>{let q=pn();q!=i&&U(h[$],void 0,q);let J=yt(C[$])&&yt(P[$]),at=yt(O[$])&&yt(b[$]);if(!J||!at){let ut=$?[Ke(p),Ke(x)]:[p,x];if(J||te(ut[0],C[$],P[$]),!at){let gt;bt(ut[1],(([xt,_t],Pt)=>{_t!==xt&&(U(O[$],[Pt],_t,xt,on),gt=1)})),gt&&U(b[$],void 0,on)}}},Bt=($,...q)=>(Cr((()=>$(...bi(q,Rt)))),Qt),Ga=($,q,J,at,ut)=>{let gt=ln($,q,...J);return L((()=>{let xt=ln($,q,...J);_o(xt,gt)||(gt=xt,at(Qt,$,q,...J,gt))}),et[ut?1:0],[$,q],[oe])},xr=()=>xn(D),oe=()=>mi(D),qa=$=>mi(ht(S,Rt($))),Xa=$=>es(ht(D,Rt($))),Xi=$=>mi(ht(D,Rt($))),ln=($,q,J,at=0,ut)=>{return Tn($)?ln($.tableId,$.cellId,$.descending,$.offset,$.limit):bi(Or(Br((gt=ht(D,Rt($)),xt=(_t,Pt)=>[At(q)?Pt:ht(_t,Rt(q)),Pt],bi([...gt?.entries()??[]],(([_t,Pt])=>xt(Pt,_t)))),(([_t],[Pt])=>Mo(_t,Pt)*(J?-1:1))),at,At(ut)?ut:at+ut),(([,_t])=>_t));var gt,xt},Ar=($,q)=>mi(ht(ht(D,Rt($)),Rt(q))),hn=($,q,J)=>ht(ht(ht(D,Rt($)),Rt(q)),Rt(J)),Sr=()=>se(N),Er=()=>mi(N),dn=$=>ht(N,Rt($)),un=()=>!yt(D),Ka=$=>Ft(D,Rt($)),Ya=($,q)=>Ft(ht(S,Rt($)),Rt(q)),Ja=($,q)=>Ft(ht(D,Rt($)),Rt(q)),Qa=($,q,J)=>Ft(ht(ht(D,Rt($)),Rt(q)),Rt(J)),pn=()=>!yt(N),Za=$=>Ft(N,Rt($)),fn=$=>Bt((()=>(q=>Xe(q,Q,be))($)?Ct($):0)),gn=$=>Bt((()=>rt($)?me($):0)),to=$=>(kr((()=>wt(Dr($)))),Qt),eo=$=>Bt((()=>{if((n=Xe($,(q=>Xe(q,F))))&&(vt($),!yt(D))){let q=xr();mn(),fn(q)}})),io=$=>Bt((()=>{if(t=(q=>Xe(q,F))($)){let q=Sr();_r(),bn(),t=!0,Et($),gn(q)}})),mn=()=>Bt((()=>Ct({}))),so=$=>Bt((q=>Ft(D,q)?je(q):0),$),no=($,q)=>Bt(((J,at)=>Mt(ht(D,J),(ut=>Ft(ut,at)?ze(J,ut,at):0))),$,q),bn=()=>Bt((()=>me({}))),ro=()=>Bt((()=>{vt({}),n=!1})),_r=()=>Bt((()=>{Et({}),t=!1})),Cr=($,q)=>{if(r!=-1){ao();let J=$();return oo(q),J}},ao=()=>(r!=-1&&r++,r==1&&(o[0]?.(),U(M)),Qt),oo=$=>(r>0&&(r--,r==0&&(r=1,qi(1),yt(a)||cn(1),We(1),yt(x)||Wa(1),$?.(Qt)&&(bt(a,((q,J)=>bt(q,((at,ut)=>bt(at,(([gt],xt)=>Pn(Qt,J,ut,xt,gt))))))),Ji(a),bt(x,(([q],J)=>Ur(Qt,J,q))),Ji(x)),U(E[0],void 0),r=-1,qi(0),yt(a)||cn(0),We(0),yt(x)||Wa(0),o[1]?.(),U(E[1],void 0),o[2]?.(),r=0,e=un(),i=pn(),re([g,d,m,v,u,a,T,p,x,l],Ji))),Qt),Qt={getContent:()=>[xr(),Sr()],getTables:xr,getTableIds:oe,getTable:$=>$r(ht(D,Rt($))),getTableCellIds:qa,getRowCount:Xa,getRowIds:Xi,getSortedRowIds:ln,getRow:($,q)=>se(ht(ht(D,Rt($)),Rt(q))),getCellIds:Ar,getCell:hn,getValues:Sr,getValueIds:Er,getValue:dn,hasTables:un,hasTable:Ka,hasTableCell:Ya,hasRow:Ja,hasCell:Qa,hasValues:pn,hasValue:Za,getTablesJson:()=>Ki(D),getValuesJson:()=>Ki(N),getJson:()=>Ki([D,N]),getTablesSchemaJson:()=>Ki(y),getValuesSchemaJson:()=>Ki(c),getSchemaJson:()=>Ki([y,c]),hasTablesSchema:()=>n,hasValuesSchema:()=>t,setContent:$=>Bt((()=>{let q=ve($)?$():$;V(q)&&(([J,at])=>{(we(J)?mn:fn)(J),(we(at)?bn:gn)(at)})(q)})),setTables:fn,setTable:($,q)=>Bt((J=>Q(q,J)?Tt(J,q):0),$),setRow:($,q,J)=>Bt(((at,ut)=>Z(at,ut,J)?It(at,ue(at),ut,J):0),$,q),addRow:($,q,J=!0)=>Cr((()=>{let at;return Z($,at,q)&&($=Rt($),It($,ue($),at=((ut,gt)=>{let[xt]=ht(R,ut),_t;do _t=xt(gt);while(Ft(ht(D,ut),_t));return _t})($,J?1:0),q)),at})),setPartialRow:($,q,J)=>Bt(((at,ut)=>{if(Z(at,ut,J,1)){let gt=ue(at);Me(J,((xt,_t)=>Jt(at,gt,ut,_t,xt)))}}),$,q),setCell:($,q,J,at)=>Bt(((ut,gt,xt)=>Mt(tt(ut,gt,xt,ve(at)?at(hn(ut,gt,xt)):at),(_t=>Jt(ut,ue(ut),gt,xt,_t)))),$,q,J),setValues:gn,setPartialValues:$=>Bt((()=>rt($,1)?Me($,((q,J)=>le(J,q))):0)),setValue:($,q)=>Bt((J=>Mt(pt(J,ve(q)?q(dn(J)):q),(at=>le(J,at)))),$),applyChanges:$=>Bt((()=>{Me($[0],((q,J)=>At(q)?so(J):Me(q,((at,ut)=>At(at)?no(J,ut):Me(at,((gt,xt)=>Pn(Qt,J,ut,xt,gt))))))),Me($[1],((q,J)=>Ur(Qt,J,q)))})),setTablesJson:to,setValuesJson:$=>(kr((()=>ae(Dr($)))),Qt),setJson:$=>Bt((()=>kr((()=>{let[q,J]=Dr($);wt(q),ae(J)}),(()=>to($))))),setTablesSchema:eo,setValuesSchema:io,setSchema:($,q)=>Bt((()=>{eo($),io(q)})),delTables:mn,delTable:so,delRow:no,delCell:($,q,J,at)=>Bt(((ut,gt,xt)=>Mt(ht(D,ut),(_t=>Mt(ht(_t,gt),(Pt=>Ft(Pt,xt)?Yt(ut,_t,gt,Pt,xt,at):0))))),$,q,J),delValues:bn,delValue:$=>Bt((q=>Ft(N,q)?Xt(q):0),$),delTablesSchema:ro,delValuesSchema:_r,delSchema:()=>Bt((()=>{ro(),_r()})),transaction:Cr,startTransaction:ao,getTransactionChanges:()=>[se(a,(($,q)=>ht(g,q)===-1?void 0:se($,((J,at)=>ht(ht(v,q),at)===-1?void 0:se(J,(([,ut])=>ut),(ut=>Sn(ut)))),yt,we)),yt,we),se(x,(([,$])=>$),($=>Sn($))),1],getTransactionLog:()=>[!yt(a),!yt(x),xn(a,bo,Sn),xn(T),se(x,bo,Sn),se(l),se(g),$r(v),xn(u),se(p)],finishTransaction:oo,forEachTable:$=>bt(D,((q,J)=>$(J,(at=>bt(q,((ut,gt)=>at(gt,(xt=>Ht(ut,xt))))))))),forEachTableCell:($,q)=>Ht(ht(S,Rt($)),q),forEachRow:($,q)=>bt(ht(D,Rt($)),((J,at)=>q(at,(ut=>Ht(J,ut))))),forEachCell:($,q,J)=>Ht(ht(ht(D,Rt($)),Rt(q)),J),forEachValue:$=>Ht(N,$),addSortedRowIdsListener:($,q,J,at,ut,gt,xt)=>Tn($)?Ga($.tableId,$.cellId,[$.descending??!1,$.offset??0,$.limit],q,J):Ga($,q,[J,at,ut],gt,xt),addStartTransactionListener:$=>L($,M),addWillFinishTransactionListener:$=>L($,E[0]),addDidFinishTransactionListener:$=>L($,E[1]),callListener:$=>(k($),Qt),delListener:$=>(B($),Qt),getListenerStats:()=>({hasTables:Ut(H),tables:Ut(j),tableIds:Ut(Y),hasTable:Ut(it),table:Ut(ot),tableCellIds:Ut(K),hasTableCell:Ut(z,De),rowCount:Ut(W),rowIds:Ut(X),sortedRowIds:Ut(et),hasRow:Ut(st,De),row:Ut(ct,De),cellIds:Ut(nt,De),hasCell:Ut(G,Rr),cell:Ut(A,Rr),invalidCell:Ut(_,Rr),hasValues:Ut(h),values:Ut(b),valueIds:Ut(C),hasValue:Ut(P),value:Ut(O),invalidValue:Ut(I),transaction:yi(M)+Ut(E)}),isMergeable:()=>!1,createStore:Ts,addListener:L,callListeners:U,setInternalListeners:($,q,J,at,ut)=>o=[$,q,J,at,ut]};return Me({[fi+ho]:[0,H,[],()=>[un()]],[ho]:[0,j],[rl]:[0,Y],[fi+Ye]:[1,it,[oe],$=>[Ka(...$)]],[Ye]:[1,ot,[oe]],[Ye+En]:[1,K,[oe]],[fi+Ye+As]:[2,z,[oe,qa],$=>[Ya(...$)]],[wo]:[1,W,[oe]],[xo]:[1,X,[oe]],[fi+Qi]:[2,st,[oe,Xi],$=>[Ja(...$)]],[Qi]:[2,ct,[oe,Xi]],[En]:[2,nt,[oe,Xi]],[fi+As]:[3,G,[oe,Xi,Ar],$=>[Qa(...$)]],[As]:[3,A,[oe,Xi,Ar],$=>An(hn(...$))],InvalidCell:[3,_],[fi+uo]:[0,h,[],()=>[pn()]],[uo]:[0,b],[ol]:[0,C],[fi+_n]:[1,P,[Er],$=>[Za(...$)]],[_n]:[1,O,[Er],$=>An(dn($[0]))],InvalidValue:[1,I]},(([$,q,J,at],ut)=>{Qt[Lr+ut+Ir]=(...gt)=>L(gt[$],q[gt[$+1]?1:0],$>0?Or(gt,0,$):void 0,J,at)})),is(Qt)};var jr=ft([["avg",[(n,t)=>fo(n)/t,(n,t,e)=>n+(t-n)/(e+1),(n,t,e)=>n+(n-t)/(e-1),(n,t,e,i)=>n+(t-e)/i]],["max",[n=>Pr(...n),(n,t)=>Pr(t,n),(n,t)=>t==n?void 0:n,(n,t,e)=>e==n?void 0:Pr(t,n)]],["min",[n=>Tr(...n),(n,t)=>Tr(t,n),(n,t)=>t==n?void 0:n,(n,t,e)=>e==n?void 0:Tr(t,n)]],["sum",[n=>fo(n),(n,t)=>n+t,(n,t)=>n-t,(n,t,e)=>n-e+t]]]),Do=(n,t,e,i,r,o=!1)=>{if(yt(e))return;let[g,d,m,v]=r;return o||=At(n),bt(i,(([u,a])=>{o||(n=At(u)?d?.(n,a,t++):At(a)?m?.(n,u,t--):v?.(n,a,u,t),o||=At(n))})),o?g(ts(e),es(e)):n},vd=Cs((n=>{let t=ft(),[e,i,r]=Ps((()=>y)),[o,g,d,m,v,u,a,,p,x,T,l]=Mn(n,Eo,(s=>isNaN(s)||At(s)||s===!0||s===!1||s===""?void 0:1*s),e,i),y={setMetricDefinition:(s,c,f,w,R,S,D)=>{let N=ve(f)?[f,R,S,D]:ht(jr,f)??ht(jr,"sum");return p(s,c,((H,j,Y,it,ot,K)=>{let z=u(s),W=es(it);K||=At(z),H();let X=Do(z,W,it,j,N,K);Ao(X)||(X=void 0),X!=z&&(a(s,X),i(t,[s],X,z))}),kn(w,1)),y},delMetricDefinition:s=>(x(s),y),getStore:o,getMetricIds:g,forEachMetric:d,hasMetric:m,getTableId:v,getMetric:u,addMetricIdsListener:T,addMetricListener:(s,c)=>e(c,t,[s]),delListener:s=>(r(s),y),destroy:l,getListenerStats:()=>({metric:yi(t)})};return is(y)})),wd=Cs((n=>{let t=n.createStore,e=t(),i=t(),r=ft(),{addListener:o,callListeners:g,delListener:d}=i,[m,v,u,a,p,,,x,,T,l,y,s,c]=Mn(n,(()=>!0),Eo,o,g),f=(D,N,...H)=>re(H,(j=>Nt(Lt(Lt(r,N,ft),D,jt),j))),w=D=>{Mt(ht(r,D),(N=>{Ht(N,((H,j)=>bt(j,(Y=>H.delListener(Y))))),Ji(N)})),re([i,e],(N=>N.delTable(D)))},R=(D,N,H)=>f(N,D,N.addStartTransactionListener(H.startTransaction),N.addDidFinishTransactionListener((()=>H.finishTransaction()))),S={setQueryDefinition:(D,N,H)=>{x(D,N),w(D);let j=[],Y=[[null,[N,null,null,[],ft()]]],it=[],ot=[],K=[];H({select:(nt,G)=>{let A=ve(nt)?[ce(j)+"",nt]:[At(G)?nt:G,_=>_(nt,G)];return ne(j,A),{as:_=>A[0]=_}},join:(nt,G,A)=>{let _=At(A)||ve(G)?null:G,I=At(_)?G:A,h=[nt,[nt,_,ve(I)?I:b=>b(I),[],ft()]];return ne(Y,h),{as:b=>h[0]=b}},where:(nt,G,A)=>ne(it,ve(nt)?nt:At(A)?_=>_(nt)===G:_=>_(nt,G)===A),group:(nt,G,A,_,I)=>{let h=[nt,[nt,ve(G)?[G,A,_,I]:ht(jr,G)??[(b,C)=>C]]];return ne(ot,h),{as:b=>h[0]=b}},having:(nt,G)=>ne(K,ve(nt)?nt:A=>A(nt)===G)});let z=ft(j);if(yt(z))return S;let W=ft(Y);Ht(W,((nt,[,G])=>Mt(ht(W,G),(({3:A})=>At(nt)?0:ne(A,nt)))));let X=ft(ot),et=e;if(yt(X)&&Ss(K))et=i;else{R(D,et,i);let nt=ft();Ht(X,((I,[h,b])=>Nt(Lt(nt,h,jt),[I,b])));let G=jt();Ht(z,(I=>Ft(nt,I)?0:Nt(G,I)));let A=ft(),_=(I,h,b,C)=>Mt(I,(([P,O,M,E])=>{Ht(h,((L,[U])=>{let B=Lt(P,L,ft),k=ht(B,b),F=C?void 0:U;if(k!==F){let V=jt([[k,F]]),Q=es(B);mt(B,b,F),bt(ht(nt,L),(([Z,tt])=>{let rt=Do(E[Z],Q,B,V,tt);E[Z]=At(Yi(rt))?null:rt}))}})),yt(O)||!Cn(K,(L=>L((U=>E[U]))))?i.delRow(D,M):At(M)?I[2]=i.addRow(D,E):i.setRow(D,M,E)}));f(et,D,et.addRowListener(D,null,((I,h,b,C)=>{let P=[],O=[],M=ft(),E=et.hasRow(D,b),L=!E;bt(G,(U=>{let[B,k,F]=C(D,b,U);ne(P,k),ne(O,F),L||=B})),Ht(nt,(U=>{let[B,,k]=C(D,b,U);(L||B)&&mt(M,U,[k])})),L&&_(Es(A,P,void 0,(([,U])=>(xe(U,b),yt(U)))),M,b,1),E&&_(Es(A,O,(()=>{let U={};return bt(G,(B=>U[B]=et.getCell(D,b,B))),[ft(),jt(),void 0,U]}),(([,U])=>{Nt(U,b)})),M,b)})))}R(D,n,et);let st=(nt,G,A,_)=>{let I=h=>n.getCell(G,A,h);re(_,(h=>{let[b,,C,P,O]=ht(W,h),M=C?.(I,nt),[E,L]=ht(O,nt)??[];M!=E&&(At(L)||c(D,L),mt(O,nt,At(M)?null:[M,...s(D,1,n.addRowListener(b,M,(()=>st(nt,b,M,P))))]))})),(h=>{let b=(C,P)=>n.getCell(...At(P)?[N,h,C]:C===N?[N,h,P]:[ht(W,C)?.[0],ht(ht(W,C)?.[4],h)?.[0],P]);et.transaction((()=>Cn(it,(C=>C(b)))?Ht(z,((C,P)=>Pn(et,D,h,C,P(b,h)))):et.delRow(D,h)))})(nt)},{3:ct}=ht(W,null);return et.transaction((()=>s(D,1,n.addRowListener(N,null,((nt,G,A)=>{n.hasRow(N,A)?st(A,N,A,ct):(et.delRow(D,A),bt(W,(({4:_})=>Mt(ht(_,A),(([,I])=>{c(D,I),mt(_,A)})))))}))))),S},delQueryDefinition:D=>(w(D),T(D),S),getStore:m,getQueryIds:v,forEachQuery:u,hasQuery:a,getTableId:p,addQueryIdsListener:D=>l((()=>D(S))),delListener:D=>(d(D),S),destroy:y,getListenerStats:()=>{let{tables:D,tableIds:N,transaction:H,...j}=i.getListenerStats();return j}};return Me({[Ye]:[1,1],[Ye+En]:[0,1],[wo]:[0,1],[xo]:[0,1],[al]:[0,5],[Qi]:[1,2],[En]:[0,2],[As]:[1,3]},(([D,N],H)=>{re(D?["get","has","forEach"]:["get"],(j=>S[j+lo+H]=(...Y)=>i[j+H](...Y))),S[Lr+lo+H+Ir]=(...j)=>i[Lr+H+Ir](...Or(j,0,N),((Y,...it)=>j[N](S,...it)),!0)})),is(S)})),xd=Cs((n=>{let t=ft(),e=ft(),i=ft(),r=ft(),[o,g,d]=Ps((()=>R)),[m,v,u,a,p,x,,,T,l,y,s]=Mn(n,(()=>[ft(),ft(),ft(),ft()]),(S=>At(S)?void 0:S+""),o,g),c=(S,D,N)=>Mt(x(S),(([H,,j])=>{if(!Ft(j,D)){let Y=jt();if(p(S)!=w(S))Nt(Y,D);else{let it=D;for(;!At(it)&&!Ft(Y,it);)Nt(Y,it),it=ht(H,it)}if(N)return Y;mt(j,D,Y)}return ht(j,D)})),f=(S,D)=>Mt(x(S),(([,,N])=>mt(N,D))),w=S=>ht(t,S),R={setRelationshipDefinition:(S,D,N,H)=>(mt(t,S,N),T(S,D,((j,Y)=>{let it=jt(),ot=jt(),K=jt(),[z,W]=x(S);bt(Y,(([X,et],st)=>{At(X)||(Nt(ot,X),Mt(ht(W,X),(ct=>{xe(ct,st),yt(ct)&&mt(W,X)}))),At(et)||(Nt(ot,et),Ft(W,et)||mt(W,et,jt()),Nt(ht(W,et),st)),Nt(it,st),mt(z,st,et),Ht(ht(r,S),(ct=>{Ft(c(S,ct),st)&&Nt(K,ct)}))})),j(),bt(it,(X=>g(e,[S,X]))),bt(ot,(X=>g(i,[S,X]))),bt(K,(X=>{f(S,X),g(r,[S,X])}))}),kn(H)),R),delRelationshipDefinition:S=>(mt(t,S),l(S),R),getStore:m,getRelationshipIds:v,forEachRelationship:S=>u((D=>S(D,(N=>n.forEachRow(p(D),N))))),hasRelationship:a,getLocalTableId:p,getRemoteTableId:w,getRemoteRowId:(S,D)=>ht(x(S)?.[0],D),getLocalRowIds:(S,D)=>ts(ht(x(S)?.[1],D)),getLinkedRowIds:(S,D)=>At(x(S))?[D]:ts(c(S,D,!0)),addRelationshipIdsListener:y,addRemoteRowIdListener:(S,D,N)=>o(N,e,[S,D]),addLocalRowIdsListener:(S,D,N)=>o(N,i,[S,D]),addLinkedRowIdsListener:(S,D,N)=>(c(S,D),o(N,r,[S,D])),delListener:S=>(f(...d(S)??[]),R),destroy:s,getListenerStats:()=>({remoteRowId:De(e),localRowIds:De(i),linkedRowIds:De(r)})};return is(R)}));var Fo=Promise,yl=globalThis,Io=yl.window,vl=1e3,wl=(n,t,e)=>setInterval(n,t*vl),xl=clearInterval,Ae=n=>n==null,On=(n,t,e)=>Ae(n)?e?.():t(n),Wr=n=>Array.isArray(n),wi=n=>n.length,Al=(n,t)=>n.test(t),Oo=n=>new Fo(n),No=async n=>Fo.all(n),Bo=n=>{throw new Error(n)},vi=async(n,t,e)=>{try{return await n()}catch(i){t?.(i)}},Gr=(n,t)=>n.forEach(t),ks=(n,t)=>n.map(t),Sl=(n,t)=>n.splice(0,t),Nn=(n,...t)=>n.push(...t),Uo=n=>n.shift(),ss=Object,Lo=n=>ss.getPrototypeOf(n),El=ss.entries,_l=n=>!Ae(n)&&On(Lo(n),t=>t==ss.prototype||Ae(Lo(t)),()=>!0),Cl=ss.keys,Pl=ss.freeze,Tl=(n=[])=>ss.fromEntries(n),kl=(n,t)=>t in n,Rl=(n,t)=>ks(El(n),([e,i])=>t(i,e)),Ml=n=>wi(Cl(n)),Dn=n=>_l(n)&&Ml(n)==0,Dl=n=>n?.size??0,Il=(n,t)=>n?.has(t)??!1,$o=n=>Ae(n)||Dl(n)==0,Ho=(n,t)=>n?.forEach(t),jo=(n,t)=>n?.delete(t),Rs=n=>new Map(n),fe=(n,t)=>n?.get(t),xi=(n,t,e)=>Ae(e)?(jo(n,t),n):n?.set(t,e),qr=(n,t,e,i)=>(Il(n,t)?i?.(fe(n,t)):xi(n,t,e()),fe(n,t)),Xr=(n,t,e,i,r=0)=>On((e?qr:fe)(n,t[r],r>wi(t)-2?e:Rs),o=>{if(r>wi(t)-2)return i?.(o)&&xi(n,t[r]),o;let g=Xr(o,t,e,i,r+1);return $o(o)&&xi(n,t[r]),g}),Ll=/^\d+$/,Fl=()=>{let n=[],t=0;return[e=>(e?Uo(n):null)??""+t++,e=>{Al(Ll,e)&&wi(n)<1e3&&Nn(n,e)}]},Ol=n=>new Set(Wr(n)||Ae(n)?n:[n]),Nl=(n,t)=>n?.add(t),Bl=(n,t=[""])=>{let e=[],i=(r,o)=>o==wi(t)?Nn(e,r):t[o]===null?Ho(r,g=>i(g,o+1)):Gr([t[o],null],g=>i(fe(r,g),o+1));return i(n,0),e},Ul=n=>{let t,[e,i]=Fl(),r=Rs();return[(o,g,d,m=[],v=()=>[])=>{t??=n();let u=e(1);return xi(r,u,[o,g,d,m,v]),Nl(Xr(g,d??[""],Ol),u),u},(o,g,...d)=>Gr(Bl(o,g),m=>Ho(m,v=>fe(r,v)[0](t,...g??[],...d))),o=>On(fe(r,o),([,g,d])=>(Xr(g,d??[""],void 0,m=>(jo(m,o),$o(m)?1:0)),xi(r,o),i(o),d)),o=>On(fe(r,o),([g,,d=[],m,v])=>{let u=(...a)=>{let p=wi(a);p==wi(d)?g(t,...a,...v(a)):Ae(d[p])?Gr(m[p]?.(...a)??[],x=>u(...a,x)):u(...a,d[p])};u()})]},In=Rs(),Ln=Rs(),$l=(n=1,t,e)=>n!=1&&t.isMergeable()?[1,t.getMergeableContent,()=>t.getTransactionMergeableChanges(!e),([[i],[r]])=>!Dn(i)||!Dn(r),t.setDefaultContent]:n!=2?[0,t.getContent,t.getTransactionChanges,([i,r])=>!Dn(i)||!Dn(r),t.setContent]:Bo("Store type not supported by this Persister"),Hl=(n,t,e,i,r,o,g,d={},m=0,v=[])=>{let u=0,a=0,p=0,x,T,l;qr(In,v,()=>0),qr(Ln,v,()=>[]);let y=Rs(),[s,c,f,w,R]=$l(g,n,m),[S,D,N]=Ul(()=>h),H=b=>{b!=u&&(u=b,D(y,void 0,u))},j=async()=>{if(!fe(In,v)){for(xi(In,v,1);!Ae(x=Uo(fe(Ln,v)));)await vi(x,o);xi(In,v,0)}},Y=b=>{(s&&Wr(b?.[0])?b?.[2]===1?n.applyMergeableChanges:n.setMergeableContent:b?.[2]===1?n.applyChanges:n.setContent)(b)},it=async b=>(u!=2&&(H(1),a++,await I(async()=>{await vi(async()=>{let C=await t();Wr(C)?Y(C):b?R(b):Bo(`Content is not an array: ${C}`)},()=>{b&&R(b)}),H(0)})),h),ot=async b=>(K(),await it(b),await vi(async()=>T=await i(async(C,P)=>{P||C?u!=2&&(H(1),a++,Y(P??C),H(0)):await it()}),o),h),K=async()=>(T&&(await vi(()=>r(T),o),T=void 0),h),z=()=>!Ae(T),W=async b=>(u!=1&&(H(2),p++,await I(async()=>{await vi(()=>e(c,b),o),H(0)})),h),X=async()=>(et(),await W(),l=n.addDidFinishTransactionListener(()=>{let b=f();w(b)&&W(b)}),h),et=async()=>(l&&(n.delListener(l),l=void 0),h),st=()=>!Ae(l),ct=async(b,C=!1)=>{let[P,O]=C?[X,ot]:[ot,X];return await P(b),await O(b),h},nt=async(b=!1)=>{let[C,P]=b?[et,K]:[K,et];return await C(),await P(),h},G=()=>u,A=b=>S(b,y),_=b=>(N(b),n),I=async(...b)=>(Nn(fe(Ln,v),...b),await j(),h),h={load:it,startAutoLoad:ot,stopAutoLoad:K,isAutoLoading:z,save:W,startAutoSave:X,stopAutoSave:et,isAutoSaving:st,startAutoPersisting:ct,stopAutoPersisting:nt,getStatus:G,addStatusListener:A,delListener:_,schedule:I,getStore:()=>n,destroy:()=>(Sl(fe(Ln,v)),nt()),getStats:()=>({loads:a,saves:p}),...d};return Pl(h)},Vr=["t","v"],jl={keyPath:"k"},zl=async(n,t)=>{let e=Rl(t,(i,r)=>Fn(n,"put",{k:r,v:i}));ks(await Fn(n,"getAllKeys"),i=>kl(t,i)?0:Nn(e,Fn(n,"delete",i))),await No(e)},Fn=async(n,t,e)=>Oo((i,r)=>{let o=n[t](e);o.onsuccess=()=>i(o.result),o.onerror=()=>r(`objectStore.${t} error`)}),zo=(n,t,e=1,i)=>{let r=async(o,g=[],d=0)=>Oo((m,v)=>{let u=(Io?Io.indexedDB:indexedDB).open(t,d?2:void 0);u.onupgradeneeded=()=>d&&ks(Vr,a=>vi(()=>u.result.createObjectStore(a,jl))),u.onsuccess=()=>vi(async()=>{let a=u.result.transaction(Vr,"readwrite"),p=await No(ks(Vr,(x,T)=>o(a.objectStore(x),g[T])));u.result.close(),m(p)},a=>{u.result.close(),v(a)}),u.onerror=()=>v("indexedDB.open error")});return Hl(n,async()=>await r(async o=>Tl(ks(await Fn(o,"getAll"),({k:g,v:d})=>[g,d]))),o=>r((g,d)=>zl(g,d),o(),1),o=>wl(o,e),o=>xl(o),i,1,{getDbName:()=>t})};var Bn=class{#t;#e="blobs";#i=null;constructor(t="copio-blobs"){this.#t=t}async#n(){return this.#i?this.#i:(this.#i=new Promise((t,e)=>{if(typeof indexedDB>"u"){e(new Error("IndexedDB is not available"));return}let i=indexedDB.open(this.#t,1);i.onupgradeneeded=()=>{let r=i.result;r.objectStoreNames.contains(this.#e)||r.createObjectStore(this.#e)},i.onsuccess=()=>t(i.result),i.onerror=()=>e(i.error||new Error("Failed to open blob db"))}),this.#i)}async put(t,e){let i=await this.#n();return new Promise((r,o)=>{let m=i.transaction(this.#e,"readwrite").objectStore(this.#e).put(e,t);m.onsuccess=()=>r(),m.onerror=()=>o(m.error)})}async get(t){let e=await this.#n();return new Promise((i,r)=>{let d=e.transaction(this.#e,"readonly").objectStore(this.#e).get(t);d.onsuccess=()=>i(d.result||null),d.onerror=()=>r(d.error)})}async delete(t){let e=await this.#n();return new Promise((i,r)=>{let d=e.transaction(this.#e,"readwrite").objectStore(this.#e).delete(t);d.onsuccess=()=>i(),d.onerror=()=>r(d.error)})}async deleteByPrefix(t){let e=await this.#n();return new Promise((i,r)=>{let g=e.transaction(this.#e,"readwrite").objectStore(this.#e),d=g.openKeyCursor();d.onsuccess=m=>{let v=m.target.result;v?(typeof v.key=="string"&&v.key.startsWith(t)&&g.delete(v.key),v.continue()):i()},d.onerror=()=>r(d.error)})}async sweepOrphans(t){let e=new Set(t),i=await this.#n(),r=0;return new Promise((o,g)=>{let m=i.transaction(this.#e,"readwrite").objectStore(this.#e),v=m.openKeyCursor();v.onsuccess=u=>{let a=u.target.result;if(a){if(typeof a.key=="string"){let p=a.key.split(":")[0];e.has(p)||(m.delete(a.key),r++)}a.continue()}else o(r)},v.onerror=()=>g(v.error)})}async close(){if(this.#i){try{(await this.#i).close()}catch{}this.#i=null}}};function Ai(n,t="image/jpeg"){if(n instanceof Blob)return n;if(typeof n!="string"||!n.startsWith("data:"))return null;let e=n.match(/^data:([^;]+);base64,(.*)$/),i=e?e[1]:t,r=e?e[2]:n.split(",")[1],o=atob(r),g=new Uint8Array(o.length);for(let d=0;d<o.length;d++)g[d]=o.charCodeAt(d);return new Blob([g],{type:i})}async function Kr(n){return new Promise((t,e)=>{let i=new FileReader;i.onloadend=()=>t(i.result),i.onerror=e,i.readAsDataURL(n)})}var Se=class extends he{#t=null;#e=null;#i=null;#n="copio-db";#r=!1;#s=new Set;#o=new Map;#c=new Map;#a=new Map;#h=new Map;#u=null;constructor(t={}){super(),this.#n=t.dbName||"copio-db",t.dbName&&t.dbName!=="copio-db"&&(this.#r=!0),this.#t=t.store||Ts(),this.#t.hasTable("docs")||this.#t.setTable("docs",{}),this.#e=t.persister||zo(this.#t,this.#n),this.#i=new Bn(`${this.#n}-blobs`)}get store(){return this.#t}get persister(){return this.#e}get blobStore(){return this.#i}#d(t,e){return typeof e=="string"&&e.startsWith("blob:")&&(this.#s.add(e),this.#o.has(t)||this.#o.set(t,[]),this.#o.get(t).push(e)),e}revokeDocUrls(t){let e=this.#o.get(t);if(e){for(let i of e){try{URL.revokeObjectURL(i)}catch{}this.#s.delete(i)}this.#o.delete(t)}for(let[i,r]of this.#c.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(r)}catch{}this.#c.delete(i)}for(let[i,r]of this.#a.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(r)}catch{}this.#a.delete(i)}this.#h.delete(t)}revokeAllUrls(){for(let t of this.#s)try{URL.revokeObjectURL(t)}catch{}this.#s.clear(),this.#o.clear(),this.#c.clear(),this.#a.clear(),this.#h.clear()}async init(){return this.#u?this.#u:(this.#u=(async()=>{this.#r?(await this.#e.load(),this.#e.startAutoLoad(),this.#e.startAutoSave()):await this.#e.load(),await this.sweepOrphans();let t=!0;if(typeof navigator<"u"&&navigator.storage&&navigator.storage.persisted)try{t=await navigator.storage.persisted()}catch{}return{kind:"indexeddb",persistent:t}})(),this.#u)}async sweepOrphans(){let t=Object.keys(this.#t.getTable("docs")||{});return this.#i.sweepOrphans(t)}listDocsSync(){let t=this.#t.getTable("docs");return Object.entries(t||{}).map(([e,i])=>({id:e,name:i.name||"",pages:this.#l(i.pages)}))}async listDocs(){return this.listDocsSync()}getDocSync(t){if(this.#h.has(t))return this.#h.get(t);if(!this.#t.hasRow("docs",t))return null;let e=this.#t.getRow("docs",t);return{id:t,name:e.name||"",pages:this.#l(e.pages)}}async getDoc(t){if(!this.#t.hasRow("docs",t))return null;let e=this.#t.getRow("docs",t),i=this.#l(e.pages),r=await Promise.all(i.map(async g=>{if(!g)return g;let d={...g},m=`${t}:${g.id}`,v=await this.#i.get(`${t}:${g.id}`);v&&(d.blob=v,this.#c.has(m)?d.src=this.#c.get(m):(d.src=this.#d(t,URL.createObjectURL(v)),this.#c.set(m,d.src)));let u=`${t}:${g.id}:orig`,a=await this.#i.get(`${t}:${g.id}:original`);return a?(d.originalBlob=a,this.#a.has(u)?d.originalSrc=this.#a.get(u):(d.originalSrc=this.#d(t,URL.createObjectURL(a)),this.#a.set(u,d.originalSrc))):d.blob&&(d.originalBlob=d.blob,d.originalSrc=d.src),d})),o={id:t,name:e.name||"",pages:r};return this.#h.set(t,o),o}async saveDoc(t,e){if(!t)throw new Error("Cannot save document without an ID");let i=Array.isArray(e.pages)?e.pages:this.#l(e.pages),r=[],o=[],g=[];for(let d of i){if(!d)continue;let m=Ai(d.src)||(d.src instanceof Blob?d.src:null)||(d.blob instanceof Blob?d.blob:null),v=m?.type||"image/jpeg",u={id:d.id,name:d.name||"",type:d.type||"image",hasBlob:!0,mimeType:v,edits:d.edits,exif:d.exif,content:d.content,ocrText:d.ocrText??null,ocrConfidence:d.ocrConfidence??null,ocrWords:Array.isArray(d.ocrWords)?d.ocrWords:null,ocrWidth:d.ocrWidth??null,ocrHeight:d.ocrHeight??null};r.push(u);let a=`${t}:${d.id}`,p=`${t}:${d.id}:orig`,x={...d},T=this.#c.get(a),l=typeof d.src=="string"&&d.src.startsWith("data:")||d.src instanceof Blob||d.src&&T&&d.src!==T;if(m)if(x.blob=m,l||!T){if(T){try{URL.revokeObjectURL(T)}catch{}this.#s.delete(T)}let w=this.#d(t,URL.createObjectURL(m));this.#c.set(a,w),x.src=w}else x.src=T;let y=Ai(d.originalSrc)||(d.originalSrc instanceof Blob?d.originalSrc:null)||(d.originalBlob instanceof Blob?d.originalBlob:null),s=this.#a.get(p),c=!s&&!y&&(!d.originalSrc||d.originalSrc===d.src);c&&m&&(y=m);let f=typeof d.originalSrc=="string"&&d.originalSrc.startsWith("data:")||d.originalSrc instanceof Blob||c&&!!y;if(y)if(x.originalBlob=y,f||!s){if(s&&f){try{URL.revokeObjectURL(s)}catch{}this.#s.delete(s)}let w=this.#d(t,URL.createObjectURL(y));this.#a.set(p,w),x.originalSrc=w}else x.originalSrc=s;else s?x.originalSrc=s:d.originalSrc?x.originalSrc=d.originalSrc:(x.originalSrc=x.src,x.blob&&(x.originalBlob=x.blob));o.push(x),g.push({pageId:d.id,page:d,srcBlob:m,origBlob:y})}this.#t.setRow("docs",t,{name:e.name||"",pages:JSON.stringify(r)}),this.#h.set(t,{id:t,name:e.name||"",pages:o});for(let d of g){let{pageId:m,page:v,srcBlob:u,origBlob:a}=d;if(!u&&typeof v.src=="string"&&v.src.startsWith("blob:"))try{u=await(await fetch(v.src)).blob()}catch{}if(u&&await this.#i.put(`${t}:${m}`,u),!a&&typeof v.originalSrc=="string"&&v.originalSrc.startsWith("blob:"))try{a=await(await fetch(v.originalSrc)).blob()}catch{}a&&await this.#i.put(`${t}:${m}:original`,a)}}async deleteDoc(t){this.#t.delRow("docs",t),await this.#i.deleteByPrefix(`${t}:`),this.revokeDocUrls(t),this.#h.delete(t)}async renameDoc(t,e){if(!this.#t.hasRow("docs",t))throw new Error(`Document "${t}" not found`);this.#t.setCell("docs",t,"name",e),this.#h.has(t)&&(this.#h.get(t).name=e)}async savePage(t,e,i){let r=await this.getDoc(t);if(!r)throw new Error(`Document ${t} not found`);let o=r.pages.findIndex(m=>m.id===e),g;if(o>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?r.pages[o]={...r.pages[o],...i}:r.pages[o]={...r.pages[o],src:i,blob:i instanceof Blob?i:void 0},g=r.pages[o];else{let m=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i,blob:i instanceof Blob?i:void 0};r.pages.push(m),g=m}let d=Ai(g.src)||(g.src instanceof Blob?g.src:null)||(g.blob instanceof Blob?g.blob:null);if(!d&&typeof g.src=="string"&&g.src.startsWith("blob:"))try{d=await(await fetch(g.src)).blob()}catch{}d&&await this.#i.put(`${t}:${e}`,d),await this.saveDoc(t,r)}async getPage(t,e){let i=await this.#i.get(`${t}:${e}`);if(i)return i;let r=this.getDocSync(t);if(!r)return null;let o=r.pages.find(g=>g.id===e);return o?o.content??o.src??o:null}async deletePage(t,e){let i=this.getDocSync(t);if(!i)return;i.pages=i.pages.filter(g=>g.id!==e),this.#t.setRow("docs",t,{name:i.name||"",pages:JSON.stringify(i.pages)}),await this.#i.delete(`${t}:${e}`),await this.#i.delete(`${t}:${e}:original`);let r=`${t}:${e}`;if(this.#c.has(r)){try{URL.revokeObjectURL(this.#c.get(r))}catch{}this.#c.delete(r)}let o=`${t}:${e}:orig`;if(this.#a.has(o)){try{URL.revokeObjectURL(this.#a.get(o))}catch{}this.#a.delete(o)}this.#h.delete(t)}subscribe(t){let e=this.#t.addTableListener("docs",t);return()=>{this.#t.delListener(e)}}#l(t){if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}};async function Un(){if(typeof location<"u"&&location.search&&(new URLSearchParams(location.search).has("no-opfs")||new URLSearchParams(location.search).get("storage")==="indexeddb")||typeof navigator>"u"||!navigator.storage||typeof navigator.storage.getDirectory!="function")return!1;try{let n=await navigator.storage.getDirectory();if(!n)return!1;let t=`.copio-probe-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,e=await n.getFileHandle(t,{create:!0}),i=await e.createWritable();if(await i.write(new Uint8Array([1,2,3,4])),await i.close(),(await e.getFile()).size!==4)throw new Error("OPFS probe size mismatch");return await n.removeEntry(t),!0}catch{return!1}}function Vl(n,t,e="store.json"){let i=0,r=null,o=Promise.resolve(),g=0,d=()=>typeof t=="function"?t():t,m=async()=>{await o;let p=d();if(p){i=1;try{let l=await(await(await p.getFileHandle(e)).getFile()).text();l&&l.trim().length>0&&n.setJson(l)}catch{}finally{i=0}}},v=()=>{let p=d();return p?(g++,i=2,o=o.catch(()=>{}).then(async()=>{try{let x=n.getJson(),l=await(await p.getFileHandle(e,{create:!0})).createWritable();await l.write(x),await l.close()}catch(x){console.warn("[OpfsPersister] Failed to save store.json:",x)}finally{g--,g<=0&&(g=0,i=0)}}),o):Promise.resolve()};return{load:m,save:v,startAutoSave:()=>{r||(r=n.addDidFinishTransactionListener(()=>{v()}))},stopAutoSave:()=>{r&&(n.delListener(r),r=null)},getStatus:()=>i,getStore:()=>n}}async function Vo(n){let t=[];try{if(typeof n.entries=="function")for await(let e of n.entries())t.push(e);else if(typeof n.values=="function")for await(let e of n.values())t.push([e.name,e])}catch(e){console.warn("[OpfsAdapter] Error reading directory entries:",e)}return t}var Si=class extends he{#t;#e="copio";#i=null;#n=null;#r=null;#s=null;#o=null;#c=!1;#a=null;#h=new Set;#u=new Map;#d=new Map;#l=new Map;#f=new Map;#g=null;constructor(t={}){super(),this.#t=t,this.#e=t.dirName||"copio",t.store?this.#s=t.store:(this.#s=Ts(),this.#s.setTable("docs",{})),this.#o=t.persister||Vl(this.#s,()=>this.#n,"store.json")}get store(){return this.#c?this.#a?.store:this.#s}get persister(){return this.#c?this.#a?.persister:this.#o}get isFallback(){return this.#c}get fallbackAdapter(){return this.#a}async#p(){if(this.#c)return!1;if(this.#r&&this.#n)return!0;if(typeof navigator<"u"&&navigator.storage&&typeof navigator.storage.getDirectory=="function")try{return this.#i=await navigator.storage.getDirectory(),this.#n=await this.#i.getDirectoryHandle(this.#e,{create:!0}),this.#r=await this.#n.getDirectoryHandle("docs",{create:!0}),!0}catch(t){return console.warn("[OpfsAdapter] OPFS directory access failed, switching to fallback:",t),await this.#m(),!1}else return await this.#m(),!1}#y(t,e){return typeof e=="string"&&e.startsWith("blob:")&&(this.#h.add(e),this.#u.has(t)||this.#u.set(t,[]),this.#u.get(t).push(e)),e}revokeDocUrls(t){if(this.#c){this.#a?.revokeDocUrls(t);return}let e=this.#u.get(t);if(e){for(let i of e){try{URL.revokeObjectURL(i)}catch{}this.#h.delete(i)}this.#u.delete(t)}for(let[i,r]of this.#d.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(r)}catch{}this.#d.delete(i)}for(let[i,r]of this.#l.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(r)}catch{}this.#l.delete(i)}this.#f.delete(t)}revokeAllUrls(){if(this.#c){this.#a?.revokeAllUrls();return}for(let t of this.#h)try{URL.revokeObjectURL(t)}catch{}this.#h.clear(),this.#u.clear(),this.#d.clear(),this.#l.clear(),this.#f.clear()}async init(){return this.#g?this.#g:(this.#g=(async()=>{if(this.#t.forceFallback)return this.#m();if(!await Un())return this.#m();try{await this.#p(),await this.#o.load(),this.#o.startAutoSave(),await this.sweepOrphans();let e=!1;if(typeof navigator<"u"&&navigator.storage&&navigator.storage.persisted)try{e=await navigator.storage.persisted()}catch{}return{kind:"opfs",persistent:e}}catch(e){return console.warn("[OpfsAdapter] OPFS initialization failed, switching to IndexedDB fallback:",e),this.#m()}})(),this.#g)}async#m(){return this.#c=!0,this.#a=new Se(this.#t),{kind:"indexeddb",persistent:(await this.#a.init()).persistent}}async sweepOrphans(){if(this.#c)return this.#a?.sweepOrphans();if(await this.#p(),!this.#r)return 0;let t=0,e=this.#s.getTable("docs")||{},i=new Set(Object.keys(e)),r=new Map;for(let[g,d]of Object.entries(e)){let m=this.#b(d.pages);r.set(g,new Set(m.map(v=>v.id)))}let o=await Vo(this.#r);for(let[g,d]of o)if(d.kind==="directory")if(i.has(g)){let m=r.get(g)||new Set,v=d,u=await Vo(v);for(let[a]of u){let p=a.replace(/-original\.bin$/,"").replace(/\.bin$/,"");if(!m.has(p))try{await v.removeEntry(a),t++}catch{}}}else try{await this.#r.removeEntry(g,{recursive:!0}),t++}catch{}return t}listDocsSync(){if(this.#c)return this.#a?.listDocsSync();let t=this.#s.getTable("docs");return Object.entries(t||{}).map(([e,i])=>({id:e,name:i.name||"",pages:this.#b(i.pages)}))}async listDocs(){return this.#c?this.#a?.listDocs():this.listDocsSync()}getDocSync(t){if(this.#c)return this.#a?.getDocSync(t);if(this.#f.has(t))return this.#f.get(t);if(!this.#s.hasRow("docs",t))return null;let e=this.#s.getRow("docs",t);return{id:t,name:e.name||"",pages:this.#b(e.pages)}}async getDoc(t){if(this.#c)return this.#a?.getDoc(t);if(await this.#p(),!this.#s.hasRow("docs",t))return null;let e=this.#s.getRow("docs",t),i=this.#b(e.pages),r=null;if(this.#r)try{r=await this.#r.getDirectoryHandle(t)}catch{}let o=await Promise.all(i.map(async d=>{if(!d||!r)return d;let m={...d},v=`${t}:${d.id}`;try{let p=await(await r.getFileHandle(`${d.id}.bin`)).getFile();m.blob=p,this.#d.has(v)?m.src=this.#d.get(v):(m.src=this.#y(t,URL.createObjectURL(p)),this.#d.set(v,m.src))}catch{}let u=`${t}:${d.id}:orig`;try{let p=await(await r.getFileHandle(`${d.id}-original.bin`)).getFile();m.originalBlob=p,this.#l.has(u)?m.originalSrc=this.#l.get(u):(m.originalSrc=this.#y(t,URL.createObjectURL(p)),this.#l.set(u,m.originalSrc))}catch{m.blob&&(m.originalBlob=m.blob,m.originalSrc=m.src)}return m})),g={id:t,name:e.name||"",pages:o};return this.#f.set(t,g),g}async saveDoc(t,e){if(this.#c)return this.#a?.saveDoc(t,e);if(!t)throw new Error("Cannot save document without an ID");let i=Array.isArray(e.pages)?e.pages:this.#b(e.pages),r=[],o=[],g=[];for(let m of i){if(!m)continue;let v=Ai(m.src)||(m.src instanceof Blob?m.src:null)||(m.blob instanceof Blob?m.blob:null),u=v?.type||"image/jpeg",a={id:m.id,name:m.name||"",type:m.type||"image",hasBlob:!0,mimeType:u,edits:m.edits,exif:m.exif,content:m.content,ocrText:m.ocrText??null,ocrConfidence:m.ocrConfidence??null,ocrWords:Array.isArray(m.ocrWords)?m.ocrWords:null,ocrWidth:m.ocrWidth??null,ocrHeight:m.ocrHeight??null};r.push(a);let p=`${t}:${m.id}`,x=`${t}:${m.id}:orig`,T={...m},l=this.#d.get(p),y=typeof m.src=="string"&&m.src.startsWith("data:")||m.src instanceof Blob||m.src&&l&&m.src!==l;if(v)if(T.blob=v,y||!l){if(l){try{URL.revokeObjectURL(l)}catch{}this.#h.delete(l)}let R=this.#y(t,URL.createObjectURL(v));this.#d.set(p,R),T.src=R}else T.src=l;let s=Ai(m.originalSrc)||(m.originalSrc instanceof Blob?m.originalSrc:null)||(m.originalBlob instanceof Blob?m.originalBlob:null),c=this.#l.get(x),f=!c&&!s&&(!m.originalSrc||m.originalSrc===m.src);f&&v&&(s=v);let w=typeof m.originalSrc=="string"&&m.originalSrc.startsWith("data:")||m.originalSrc instanceof Blob||f&&!!s;if(s)if(T.originalBlob=s,w||!c){if(c&&w){try{URL.revokeObjectURL(c)}catch{}this.#h.delete(c)}let R=this.#y(t,URL.createObjectURL(s));this.#l.set(x,R),T.originalSrc=R}else T.originalSrc=c;else c?T.originalSrc=c:m.originalSrc?T.originalSrc=m.originalSrc:(T.originalSrc=T.src,T.blob&&(T.originalBlob=T.blob));o.push(T),g.push({pageId:m.id,page:m,srcBlob:v,origBlob:s})}if(this.#s.setRow("docs",t,{name:e.name||"",pages:JSON.stringify(r)}),this.#f.set(t,{id:t,name:e.name||"",pages:o}),await this.#p(),this.#c)return this.#a?.saveDoc(t,e);let d=null;if(this.#r)try{d=await this.#r.getDirectoryHandle(t,{create:!0})}catch(m){console.warn(`[OpfsAdapter] Failed to get doc directory "${t}":`,m)}if(d)for(let m of g){let{pageId:v,page:u,srcBlob:a,origBlob:p}=m;if(!a&&typeof u.src=="string"&&u.src.startsWith("blob:"))try{a=await(await fetch(u.src)).blob()}catch{}if(a)try{let T=await(await d.getFileHandle(`${v}.bin`,{create:!0})).createWritable();await T.write(a),await T.close()}catch(x){console.warn(`[OpfsAdapter] Failed writing page file "${v}.bin":`,x)}if(!p&&typeof u.originalSrc=="string"&&u.originalSrc.startsWith("blob:"))try{p=await(await fetch(u.originalSrc)).blob()}catch{}if(p)try{let T=await(await d.getFileHandle(`${v}-original.bin`,{create:!0})).createWritable();await T.write(p),await T.close()}catch{}}}async deleteDoc(t){if(this.#c)return this.#a?.deleteDoc(t);if(this.#s.delRow("docs",t),this.#f.delete(t),this.revokeDocUrls(t),await this.#p(),this.#r)try{await this.#r.removeEntry(t,{recursive:!0})}catch{}}async renameDoc(t,e){if(this.#c)return this.#a?.renameDoc(t,e);if(!this.#s.hasRow("docs",t))throw new Error(`Document "${t}" not found`);this.#s.setCell("docs",t,"name",e),this.#f.has(t)&&(this.#f.get(t).name=e)}async savePage(t,e,i){if(this.#c)return this.#a?.savePage(t,e,i);await this.#p();let r=await this.getDoc(t);if(!r)throw new Error(`Document ${t} not found`);let o=r.pages.findIndex(m=>m.id===e),g;if(o>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?r.pages[o]={...r.pages[o],...i}:r.pages[o]={...r.pages[o],src:i,blob:i instanceof Blob?i:void 0},g=r.pages[o];else{let m=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i,blob:i instanceof Blob?i:void 0};r.pages.push(m),g=m}let d=Ai(g.src)||(g.src instanceof Blob?g.src:null)||(g.blob instanceof Blob?g.blob:null);if(!d&&typeof g.src=="string"&&g.src.startsWith("blob:"))try{d=await(await fetch(g.src)).blob()}catch{}if(d&&this.#r)try{let u=await(await(await this.#r.getDirectoryHandle(t,{create:!0})).getFileHandle(`${e}.bin`,{create:!0})).createWritable();await u.write(d),await u.close()}catch(m){console.warn(`[OpfsAdapter] Failed writing page file "${e}.bin":`,m)}await this.saveDoc(t,r)}async getPage(t,e){if(this.#c)return this.#a?.getPage(t,e);if(await this.#p(),this.#r)try{return await(await(await this.#r.getDirectoryHandle(t)).getFileHandle(`${e}.bin`)).getFile()}catch{}let i=this.getDocSync(t);if(!i)return null;let r=i.pages.find(o=>o.id===e);return r?r.content??r.src??r:null}async deletePage(t,e){if(this.#c)return this.#a?.deletePage(t,e);await this.#p();let i=this.getDocSync(t);if(!i)return;if(i.pages=i.pages.filter(g=>g.id!==e),this.#s.setRow("docs",t,{name:i.name||"",pages:JSON.stringify(i.pages)}),this.#r){try{await(await this.#r.getDirectoryHandle(t)).removeEntry(`${e}.bin`)}catch{}try{await(await this.#r.getDirectoryHandle(t)).removeEntry(`${e}-original.bin`)}catch{}}let r=`${t}:${e}`;if(this.#d.has(r)){try{URL.revokeObjectURL(this.#d.get(r))}catch{}this.#d.delete(r)}let o=`${t}:${e}:orig`;if(this.#l.has(o)){try{URL.revokeObjectURL(this.#l.get(o))}catch{}this.#l.delete(o)}this.#f.delete(t)}subscribe(t){if(this.#c)return this.#a?.subscribe(t);let e=this.#s.addTableListener("docs",t);return()=>{this.#s.delListener(e)}}#b(t){if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}};function ns(n={}){return n.forceMemory?new qe:n.forceIndexedDb?new Se(n):n.forceOpfs?new Si(n):typeof navigator<"u"&&navigator.storage&&typeof navigator.storage.getDirectory=="function"?new Si(n):typeof indexedDB<"u"?new Se(n):new qe}function kt(n,t,e){return t in n?Object.defineProperty(n,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):n[t]=e,n}var la=typeof self<"u"?self:global,Fs=typeof navigator<"u",Wl=Fs&&typeof HTMLImageElement>"u",Wo=!(typeof global>"u"||typeof process>"u"||!process.versions||!process.versions.node),ha=la.Buffer,$n=la.BigInt,da=!!ha,Hn=n=>sc(n)?void 0:n,Gl=n=>n!==void 0;function sc(n){return n===void 0||(n instanceof Map?n.size===0:Object.values(n).filter(Gl).length===0)}function qt(n){let t=new Error(n);throw delete t.stack,t}function nc(n){return(n=(function(t){for(;t.endsWith("\0");)t=t.slice(0,-1);return t})(n).trim())===""?void 0:n}function Go(n){let t=(function(e){let i=0;return e.ifd0.enabled&&(i+=1024),e.exif.enabled&&(i+=2048),e.makerNote&&(i+=2048),e.userComment&&(i+=1024),e.gps.enabled&&(i+=512),e.interop.enabled&&(i+=100),e.ifd1.enabled&&(i+=1024),i+2048})(n);return n.jfif.enabled&&(t+=50),n.xmp.enabled&&(t+=2e4),n.iptc.enabled&&(t+=14e3),n.icc.enabled&&(t+=6e3),t}var Zr=n=>String.fromCharCode.apply(null,n),qo=typeof TextDecoder<"u"?new TextDecoder("utf-8"):void 0;function rc(n){return qo?qo.decode(n):da?Buffer.from(n).toString("utf8"):decodeURIComponent(escape(Zr(n)))}var Fe=class n{static from(t,e){return t instanceof this&&t.le===e?t:new n(t,void 0,void 0,e)}constructor(t,e=0,i,r){if(typeof r=="boolean"&&(this.le=r),Array.isArray(t)&&(t=new Uint8Array(t)),t===0)this.byteOffset=0,this.byteLength=0;else if(t instanceof ArrayBuffer){i===void 0&&(i=t.byteLength-e);let o=new DataView(t,e,i);this._swapDataView(o)}else if(t instanceof Uint8Array||t instanceof DataView||t instanceof n){i===void 0&&(i=t.byteLength-e),(e+=t.byteOffset)+i>t.byteOffset+t.byteLength&&qt("Creating view outside of available memory in ArrayBuffer");let o=new DataView(t.buffer,e,i);this._swapDataView(o)}else if(typeof t=="number"){let o=new DataView(new ArrayBuffer(t));this._swapDataView(o)}else qt("Invalid input argument for BufferView: "+t)}_swapArrayBuffer(t){this._swapDataView(new DataView(t))}_swapBuffer(t){this._swapDataView(new DataView(t.buffer,t.byteOffset,t.byteLength))}_swapDataView(t){this.dataView=t,this.buffer=t.buffer,this.byteOffset=t.byteOffset,this.byteLength=t.byteLength}_lengthToEnd(t){return this.byteLength-t}set(t,e,i=n){return t instanceof DataView||t instanceof n?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t instanceof Uint8Array||qt("BufferView.set(): Invalid data argument."),this.toUint8().set(t,e),new i(this,e,t.byteLength)}subarray(t,e){return e=e||this._lengthToEnd(t),new n(this,t,e)}toUint8(){return new Uint8Array(this.buffer,this.byteOffset,this.byteLength)}getUint8Array(t,e){return new Uint8Array(this.buffer,this.byteOffset+t,e)}getString(t=0,e=this.byteLength){return rc(this.getUint8Array(t,e))}getLatin1String(t=0,e=this.byteLength){let i=this.getUint8Array(t,e);return Zr(i)}getUnicodeString(t=0,e=this.byteLength){let i=[];for(let r=0;r<e&&t+r<this.byteLength;r+=2)i.push(this.getUint16(t+r));return Zr(i)}getInt8(t){return this.dataView.getInt8(t)}getUint8(t){return this.dataView.getUint8(t)}getInt16(t,e=this.le){return this.dataView.getInt16(t,e)}getInt32(t,e=this.le){return this.dataView.getInt32(t,e)}getUint16(t,e=this.le){return this.dataView.getUint16(t,e)}getUint32(t,e=this.le){return this.dataView.getUint32(t,e)}getFloat32(t,e=this.le){return this.dataView.getFloat32(t,e)}getFloat64(t,e=this.le){return this.dataView.getFloat64(t,e)}getFloat(t,e=this.le){return this.dataView.getFloat32(t,e)}getDouble(t,e=this.le){return this.dataView.getFloat64(t,e)}getUintBytes(t,e,i){switch(e){case 1:return this.getUint8(t,i);case 2:return this.getUint16(t,i);case 4:return this.getUint32(t,i);case 8:return this.getUint64&&this.getUint64(t,i)}}getUint(t,e,i){switch(e){case 8:return this.getUint8(t,i);case 16:return this.getUint16(t,i);case 32:return this.getUint32(t,i);case 64:return this.getUint64&&this.getUint64(t,i)}}toString(t){return this.dataView.toString(t,this.constructor.name)}ensureChunk(){}};function ta(n,t){qt(`${n} '${t}' was not loaded, try using full build of exifr.`)}var Os=class extends Map{constructor(t){super(),this.kind=t}get(t,e){return this.has(t)||ta(this.kind,t),e&&(t in e||(function(i,r){qt(`Unknown ${i} '${r}'.`)})(this.kind,t),e[t].enabled||ta(this.kind,t)),super.get(t)}keyList(){return Array.from(this.keys())}},Ri=new Os("file parser"),ie=new Os("segment parser"),Mi=new Os("file reader"),ac=la.fetch;function Xo(n,t){return(e=n).startsWith("data:")||e.length>1e4?ia(n,t,"base64"):Wo&&n.includes("://")?ea(n,t,"url",os):Wo?ia(n,t,"fs"):Fs?ea(n,t,"url",os):void qt("Invalid input argument");var e}async function ea(n,t,e,i){return Mi.has(e)?ia(n,t,e):i?(async function(r,o){let g=await o(r);return new Fe(g)})(n,i):void qt(`Parser ${e} is not loaded`)}async function ia(n,t,e){let i=new(Mi.get(e))(n,t);return await i.read(),i}var os=n=>ac(n).then((t=>t.arrayBuffer())),cs=n=>new Promise(((t,e)=>{let i=new FileReader;i.onloadend=()=>t(i.result||new ArrayBuffer),i.onerror=e,i.readAsArrayBuffer(n)})),sa=class extends Map{get tagKeys(){return this.allKeys||(this.allKeys=Array.from(this.keys())),this.allKeys}get tagValues(){return this.allValues||(this.allValues=Array.from(this.values())),this.allValues}};function ge(n,t,e){let i=new sa;for(let[r,o]of e)i.set(r,o);if(Array.isArray(t))for(let r of t)n.set(r,i);else n.set(t,i);return i}function ua(n,t,e){let i,r=n.get(t);for(i of e)r.set(i[0],i[1])}var Le=new Map,hs=new Map,ki=new Map,_i=["chunked","firstChunkSize","firstChunkSizeNode","firstChunkSizeBrowser","chunkSize","chunkLimit"],Ns=["jfif","xmp","icc","iptc","ihdr"],ls=["tiff",...Ns],zt=["ifd0","ifd1","exif","gps","interop"],Ci=[...ls,...zt],Pi=["makerNote","userComment"],Bs=["translateKeys","translateValues","reviveValues","multiSegment"],Ti=[...Bs,"sanitize","mergeOutput","silentErrors"],jn=class{get translate(){return this.translateKeys||this.translateValues||this.reviveValues}},Ei=class extends jn{get needed(){return this.enabled||this.deps.size>0}constructor(t,e,i,r){if(super(),kt(this,"enabled",!1),kt(this,"skip",new Set),kt(this,"pick",new Set),kt(this,"deps",new Set),kt(this,"translateKeys",!1),kt(this,"translateValues",!1),kt(this,"reviveValues",!1),this.key=t,this.enabled=e,this.parse=this.enabled,this.applyInheritables(r),this.canBeFiltered=zt.includes(t),this.canBeFiltered&&(this.dict=Le.get(t)),i!==void 0)if(Array.isArray(i))this.parse=this.enabled=!0,this.canBeFiltered&&i.length>0&&this.translateTagSet(i,this.pick);else if(typeof i=="object"){if(this.enabled=!0,this.parse=i.parse!==!1,this.canBeFiltered){let{pick:o,skip:g}=i;o&&o.length>0&&this.translateTagSet(o,this.pick),g&&g.length>0&&this.translateTagSet(g,this.skip)}this.applyInheritables(i)}else i===!0||i===!1?this.parse=this.enabled=i:qt(`Invalid options argument: ${i}`)}applyInheritables(t){let e,i;for(e of Bs)i=t[e],i!==void 0&&(this[e]=i)}translateTagSet(t,e){if(this.dict){let i,r,{tagKeys:o,tagValues:g}=this.dict;for(i of t)typeof i=="string"?(r=g.indexOf(i),r===-1&&(r=o.indexOf(Number(i))),r!==-1&&e.add(Number(o[r]))):e.add(i)}else for(let i of t)e.add(i)}finalizeFilters(){!this.enabled&&this.deps.size>0?(this.enabled=!0,zn(this.pick,this.deps)):this.enabled&&this.pick.size>0&&zn(this.pick,this.deps)}},ee={jfif:!1,tiff:!0,xmp:!1,icc:!1,iptc:!1,ifd0:!0,ifd1:!1,exif:!0,gps:!0,interop:!1,ihdr:void 0,makerNote:!1,userComment:!1,multiSegment:!1,skip:[],pick:[],translateKeys:!0,translateValues:!0,reviveValues:!0,sanitize:!0,mergeOutput:!0,silentErrors:!0,chunked:!0,firstChunkSize:void 0,firstChunkSizeNode:512,firstChunkSizeBrowser:65536,chunkSize:65536,chunkLimit:5},Ko=new Map,Ze=class extends jn{static useCached(t){let e=Ko.get(t);return e!==void 0||(e=new this(t),Ko.set(t,e)),e}constructor(t){super(),t===!0?this.setupFromTrue():t===void 0?this.setupFromUndefined():Array.isArray(t)?this.setupFromArray(t):typeof t=="object"?this.setupFromObject(t):qt(`Invalid options argument ${t}`),this.firstChunkSize===void 0&&(this.firstChunkSize=Fs?this.firstChunkSizeBrowser:this.firstChunkSizeNode),this.mergeOutput&&(this.ifd1.enabled=!1),this.filterNestedSegmentTags(),this.traverseTiffDependencyTree(),this.checkLoadedPlugins()}setupFromUndefined(){let t;for(t of _i)this[t]=ee[t];for(t of Ti)this[t]=ee[t];for(t of Pi)this[t]=ee[t];for(t of Ci)this[t]=new Ei(t,ee[t],void 0,this)}setupFromTrue(){let t;for(t of _i)this[t]=ee[t];for(t of Ti)this[t]=ee[t];for(t of Pi)this[t]=!0;for(t of Ci)this[t]=new Ei(t,!0,void 0,this)}setupFromArray(t){let e;for(e of _i)this[e]=ee[e];for(e of Ti)this[e]=ee[e];for(e of Pi)this[e]=ee[e];for(e of Ci)this[e]=new Ei(e,!1,void 0,this);this.setupGlobalFilters(t,void 0,zt)}setupFromObject(t){let e;for(e of(zt.ifd0=zt.ifd0||zt.image,zt.ifd1=zt.ifd1||zt.thumbnail,Object.assign(this,t),_i))this[e]=Yr(t[e],ee[e]);for(e of Ti)this[e]=Yr(t[e],ee[e]);for(e of Pi)this[e]=Yr(t[e],ee[e]);for(e of ls)this[e]=new Ei(e,ee[e],t[e],this);for(e of zt)this[e]=new Ei(e,ee[e],t[e],this.tiff);this.setupGlobalFilters(t.pick,t.skip,zt,Ci),t.tiff===!0?this.batchEnableWithBool(zt,!0):t.tiff===!1?this.batchEnableWithUserValue(zt,t):Array.isArray(t.tiff)?this.setupGlobalFilters(t.tiff,void 0,zt):typeof t.tiff=="object"&&this.setupGlobalFilters(t.tiff.pick,t.tiff.skip,zt)}batchEnableWithBool(t,e){for(let i of t)this[i].enabled=e}batchEnableWithUserValue(t,e){for(let i of t){let r=e[i];this[i].enabled=r!==!1&&r!==void 0}}setupGlobalFilters(t,e,i,r=i){if(t&&t.length){for(let g of r)this[g].enabled=!1;let o=Yo(t,i);for(let[g,d]of o)zn(this[g].pick,d),this[g].enabled=!0}else if(e&&e.length){let o=Yo(e,i);for(let[g,d]of o)zn(this[g].skip,d)}}filterNestedSegmentTags(){let{ifd0:t,exif:e,xmp:i,iptc:r,icc:o}=this;this.makerNote?e.deps.add(37500):e.skip.add(37500),this.userComment?e.deps.add(37510):e.skip.add(37510),i.enabled||t.skip.add(700),r.enabled||t.skip.add(33723),o.enabled||t.skip.add(34675)}traverseTiffDependencyTree(){let{ifd0:t,exif:e,gps:i,interop:r}=this;r.needed&&(e.deps.add(40965),t.deps.add(40965)),e.needed&&t.deps.add(34665),i.needed&&t.deps.add(34853),this.tiff.enabled=zt.some((o=>this[o].enabled===!0))||this.makerNote||this.userComment;for(let o of zt)this[o].finalizeFilters()}get onlyTiff(){return!Ns.map((t=>this[t].enabled)).some((t=>t===!0))&&this.tiff.enabled}checkLoadedPlugins(){for(let t of ls)this[t].enabled&&!ie.has(t)&&ta("segment parser",t)}};function Yo(n,t){let e,i,r,o,g=[];for(r of t){for(o of(e=Le.get(r),i=[],e))(n.includes(o[0])||n.includes(o[1]))&&i.push(o[0]);i.length&&g.push([r,i])}return g}function Yr(n,t){return n!==void 0?n:t!==void 0?t:void 0}function zn(n,t){for(let e of t)n.add(e)}kt(Ze,"default",ee);var Oe=class{constructor(t){kt(this,"parsers",{}),kt(this,"output",{}),kt(this,"errors",[]),kt(this,"pushToErrors",(e=>this.errors.push(e))),this.options=Ze.useCached(t)}async read(t){this.file=await(function(e,i){return typeof e=="string"?Xo(e,i):Fs&&!Wl&&e instanceof HTMLImageElement?Xo(e.src,i):e instanceof Uint8Array||e instanceof ArrayBuffer||e instanceof DataView?new Fe(e):Fs&&e instanceof Blob?ea(e,i,"blob",cs):void qt("Invalid input argument")})(t,this.options)}setup(){if(this.fileParser)return;let{file:t}=this,e=t.getUint16(0);for(let[i,r]of Ri)if(r.canHandle(t,e))return this.fileParser=new r(this.options,this.file,this.parsers),t[i]=!0;this.file.close&&this.file.close(),qt("Unknown file format")}async parse(){let{output:t,errors:e}=this;return this.setup(),this.options.silentErrors?(await this.executeParsers().catch(this.pushToErrors),e.push(...this.fileParser.errors)):await this.executeParsers(),this.file.close&&this.file.close(),this.options.silentErrors&&e.length>0&&(t.errors=e),Hn(t)}async executeParsers(){let{output:t}=this;await this.fileParser.parse();let e=Object.values(this.parsers).map((async i=>{let r=await i.parse();i.assignToOutput(t,r)}));this.options.silentErrors&&(e=e.map((i=>i.catch(this.pushToErrors)))),await Promise.all(e)}async extractThumbnail(){this.setup();let{options:t,file:e}=this,i=ie.get("tiff",t);var r;if(e.tiff?r={start:0,type:"tiff"}:e.jpeg&&(r=await this.fileParser.getOrFindSegment("tiff")),r===void 0)return;let o=await this.fileParser.ensureSegmentChunk(r),g=this.parsers.tiff=new i(o,t,e),d=await g.extractThumbnail();return e.close&&e.close(),d}};async function pa(n,t){let e=new Oe(t);return await e.read(n),e.parse()}var ql=Object.freeze({__proto__:null,parse:pa,Exifr:Oe,fileParsers:Ri,segmentParsers:ie,fileReaders:Mi,tagKeys:Le,tagValues:hs,tagRevivers:ki,createDictionary:ge,extendDictionary:ua,fetchUrlAsArrayBuffer:os,readBlobAsArrayBuffer:cs,chunkedProps:_i,otherSegments:Ns,segments:ls,tiffBlocks:zt,segmentsAndBlocks:Ci,tiffExtractables:Pi,inheritables:Bs,allFormatters:Ti,Options:Ze}),Vn=class{constructor(t,e,i){kt(this,"errors",[]),kt(this,"ensureSegmentChunk",(async r=>{let o=r.start,g=r.size||65536;if(this.file.chunked)if(this.file.available(o,g))r.chunk=this.file.subarray(o,g);else try{r.chunk=await this.file.readChunk(o,g)}catch(d){qt(`Couldn't read segment: ${JSON.stringify(r)}. ${d.message}`)}else this.file.byteLength>o+g?r.chunk=this.file.subarray(o,g):r.size===void 0?r.chunk=this.file.subarray(o):qt("Segment unreachable: "+JSON.stringify(r));return r.chunk})),this.extendOptions&&this.extendOptions(t),this.options=t,this.file=e,this.parsers=i}injectSegment(t,e){this.options[t].enabled&&this.createParser(t,e)}createParser(t,e){let i=new(ie.get(t))(e,this.options,this.file);return this.parsers[t]=i}createParsers(t){for(let e of t){let{type:i,chunk:r}=e,o=this.options[i];if(o&&o.enabled){let g=this.parsers[i];g&&g.append||g||this.createParser(i,r)}}}async readSegments(t){let e=t.map(this.ensureSegmentChunk);await Promise.all(e)}},Ie=class{static findPosition(t,e){let i=t.getUint16(e+2)+2,r=typeof this.headerLength=="function"?this.headerLength(t,e,i):this.headerLength,o=e+r,g=i-r;return{offset:e,length:i,headerLength:r,start:o,size:g,end:o+g}}static parse(t,e={}){return new this(t,new Ze({[this.type]:e}),t).parse()}normalizeInput(t){return t instanceof Fe?t:new Fe(t)}constructor(t,e={},i){kt(this,"errors",[]),kt(this,"raw",new Map),kt(this,"handleError",(r=>{if(!this.options.silentErrors)throw r;this.errors.push(r.message)})),this.chunk=this.normalizeInput(t),this.file=i,this.type=this.constructor.type,this.globalOptions=this.options=e,this.localOptions=e[this.type],this.canTranslate=this.localOptions&&this.localOptions.translate}translate(){this.canTranslate&&(this.translated=this.translateBlock(this.raw,this.type))}get output(){return this.translated?this.translated:this.raw?Object.fromEntries(this.raw):void 0}translateBlock(t,e){let i=ki.get(e),r=hs.get(e),o=Le.get(e),g=this.options[e],d=g.reviveValues&&!!i,m=g.translateValues&&!!r,v=g.translateKeys&&!!o,u={};for(let[a,p]of t)d&&i.has(a)?p=i.get(a)(p):m&&r.has(a)&&(p=this.translateValue(p,r.get(a))),v&&o.has(a)&&(a=o.get(a)||a),u[a]=p;return u}translateValue(t,e){return e[t]||e.DEFAULT||t}assignToOutput(t,e){this.assignObjectToOutput(t,this.constructor.type,e)}assignObjectToOutput(t,e,i){if(this.globalOptions.mergeOutput)return Object.assign(t,i);t[e]?Object.assign(t[e],i):t[e]=i}};kt(Ie,"headerLength",4),kt(Ie,"type",void 0),kt(Ie,"multiSegment",!1),kt(Ie,"canHandle",(()=>!1));function Xl(n){return n===192||n===194||n===196||n===219||n===221||n===218||n===254}function Kl(n){return n>=224&&n<=239}function Yl(n,t,e){for(let[i,r]of ie)if(r.canHandle(n,t,e))return i}var Wn=class extends Vn{constructor(...t){super(...t),kt(this,"appSegments",[]),kt(this,"jpegSegments",[]),kt(this,"unknownSegments",[])}static canHandle(t,e){return e===65496}async parse(){await this.findAppSegments(),await this.readSegments(this.appSegments),this.mergeMultiSegments(),this.createParsers(this.mergedAppSegments||this.appSegments)}setupSegmentFinderArgs(t){t===!0?(this.findAll=!0,this.wanted=new Set(ie.keyList())):(t=t===void 0?ie.keyList().filter((e=>this.options[e].enabled)):t.filter((e=>this.options[e].enabled&&ie.has(e))),this.findAll=!1,this.remaining=new Set(t),this.wanted=new Set(t)),this.unfinishedMultiSegment=!1}async findAppSegments(t=0,e){this.setupSegmentFinderArgs(e);let{file:i,findAll:r,wanted:o,remaining:g}=this;if(!r&&this.file.chunked&&(r=Array.from(o).some((d=>{let m=ie.get(d),v=this.options[d];return m.multiSegment&&v.multiSegment})),r&&await this.file.readWhole()),t=this.findAppSegmentsInRange(t,i.byteLength),!this.options.onlyTiff&&i.chunked){let d=!1;for(;g.size>0&&!d&&(i.canReadNextChunk||this.unfinishedMultiSegment);){let{nextChunkOffset:m}=i,v=this.appSegments.some((u=>!this.file.available(u.offset||u.start,u.length||u.size)));if(d=t>m&&!v?!await i.readNextChunk(t):!await i.readNextChunk(m),(t=this.findAppSegmentsInRange(t,i.byteLength))===void 0)return}}}findAppSegmentsInRange(t,e){e-=2;let i,r,o,g,d,m,{file:v,findAll:u,wanted:a,remaining:p,options:x}=this;for(;t<e;t++)if(v.getUint8(t)===255){if(i=v.getUint8(t+1),Kl(i)){if(r=v.getUint16(t+2),o=Yl(v,t,r),o&&a.has(o)&&(g=ie.get(o),d=g.findPosition(v,t),m=x[o],d.type=o,this.appSegments.push(d),!u&&(g.multiSegment&&m.multiSegment?(this.unfinishedMultiSegment=d.chunkNumber<d.chunkCount,this.unfinishedMultiSegment||p.delete(o)):p.delete(o),p.size===0)))break;x.recordUnknownSegments&&(d=Ie.findPosition(v,t),d.marker=i,this.unknownSegments.push(d)),t+=r+1}else if(Xl(i)){if(r=v.getUint16(t+2),i===218&&x.stopAfterSos!==!1)return;x.recordJpegSegments&&this.jpegSegments.push({offset:t,length:r,marker:i}),t+=r+1}}return t}mergeMultiSegments(){if(!this.appSegments.some((e=>e.multiSegment)))return;let t=(function(e,i){let r,o,g,d=new Map;for(let m=0;m<e.length;m++)r=e[m],o=r[i],d.has(o)?g=d.get(o):d.set(o,g=[]),g.push(r);return Array.from(d)})(this.appSegments,"type");this.mergedAppSegments=t.map((([e,i])=>{let r=ie.get(e,this.options);return r.handleMultiSegments?{type:e,chunk:r.handleMultiSegments(i)}:i[0]}))}getSegment(t){return this.appSegments.find((e=>e.type===t))}async getOrFindSegment(t){let e=this.getSegment(t);return e===void 0&&(await this.findAppSegments(0,[t]),e=this.getSegment(t)),e}};kt(Wn,"type","jpeg"),Ri.set("jpeg",Wn);var Jl=[void 0,1,1,2,4,8,1,1,2,4,8,4,8,4],na=class extends Ie{parseHeader(){var t=this.chunk.getUint16();t===18761?this.le=!0:t===19789&&(this.le=!1),this.chunk.le=this.le,this.headerParsed=!0}parseTags(t,e,i=new Map){let{pick:r,skip:o}=this.options[e];r=new Set(r);let g=r.size>0,d=o.size===0,m=this.chunk.getUint16(t);t+=2;for(let v=0;v<m;v++){let u=this.chunk.getUint16(t);if(g){if(r.has(u)&&(i.set(u,this.parseTag(t,u,e)),r.delete(u),r.size===0))break}else!d&&o.has(u)||i.set(u,this.parseTag(t,u,e));t+=12}return i}parseTag(t,e,i){let{chunk:r}=this,o=r.getUint16(t+2),g=r.getUint32(t+4),d=Jl[o];if(d*g<=4?t+=8:t=r.getUint32(t+8),(o<1||o>13)&&qt(`Invalid TIFF value type. block: ${i.toUpperCase()}, tag: ${e.toString(16)}, type: ${o}, offset ${t}`),t>r.byteLength&&qt(`Invalid TIFF value offset. block: ${i.toUpperCase()}, tag: ${e.toString(16)}, type: ${o}, offset ${t} is outside of chunk size ${r.byteLength}`),o===1)return r.getUint8Array(t,g);if(o===2)return nc(r.getString(t,g));if(o===7)return r.getUint8Array(t,g);if(g===1)return this.parseTagValue(o,t);{let m=new((function(u){switch(u){case 1:return Uint8Array;case 3:return Uint16Array;case 4:return Uint32Array;case 5:return Array;case 6:return Int8Array;case 8:return Int16Array;case 9:return Int32Array;case 10:return Array;case 11:return Float32Array;case 12:return Float64Array;default:return Array}})(o))(g),v=d;for(let u=0;u<g;u++)m[u]=this.parseTagValue(o,t),t+=v;return m}}parseTagValue(t,e){let{chunk:i}=this;switch(t){case 1:return i.getUint8(e);case 3:return i.getUint16(e);case 4:return i.getUint32(e);case 5:return i.getUint32(e)/i.getUint32(e+4);case 6:return i.getInt8(e);case 8:return i.getInt16(e);case 9:return i.getInt32(e);case 10:return i.getInt32(e)/i.getInt32(e+4);case 11:return i.getFloat(e);case 12:return i.getDouble(e);case 13:return i.getUint32(e);default:qt(`Invalid tiff type ${t}`)}}},Ds=class extends na{static canHandle(t,e){return t.getUint8(e+1)===225&&t.getUint32(e+4)===1165519206&&t.getUint16(e+8)===0}async parse(){this.parseHeader();let{options:t}=this;return t.ifd0.enabled&&await this.parseIfd0Block(),t.exif.enabled&&await this.safeParse("parseExifBlock"),t.gps.enabled&&await this.safeParse("parseGpsBlock"),t.interop.enabled&&await this.safeParse("parseInteropBlock"),t.ifd1.enabled&&await this.safeParse("parseThumbnailBlock"),this.createOutput()}safeParse(t){let e=this[t]();return e.catch!==void 0&&(e=e.catch(this.handleError)),e}findIfd0Offset(){this.ifd0Offset===void 0&&(this.ifd0Offset=this.chunk.getUint32(4))}findIfd1Offset(){if(this.ifd1Offset===void 0){this.findIfd0Offset();let t=this.chunk.getUint16(this.ifd0Offset),e=this.ifd0Offset+2+12*t;this.ifd1Offset=this.chunk.getUint32(e)}}parseBlock(t,e){let i=new Map;return this[e]=i,this.parseTags(t,e,i),i}async parseIfd0Block(){if(this.ifd0)return;let{file:t}=this;this.findIfd0Offset(),this.ifd0Offset<8&&qt("Malformed EXIF data"),!t.chunked&&this.ifd0Offset>t.byteLength&&qt(`IFD0 offset points to outside of file.
|
|
8
8
|
this.ifd0Offset: ${this.ifd0Offset}, file.byteLength: ${t.byteLength}`),t.tiff&&await t.ensureChunk(this.ifd0Offset,Go(this.options));let e=this.parseBlock(this.ifd0Offset,"ifd0");return e.size!==0?(this.exifOffset=e.get(34665),this.interopOffset=e.get(40965),this.gpsOffset=e.get(34853),this.xmp=e.get(700),this.iptc=e.get(33723),this.icc=e.get(34675),this.options.sanitize&&(e.delete(34665),e.delete(40965),e.delete(34853),e.delete(700),e.delete(33723),e.delete(34675)),e):void 0}async parseExifBlock(){if(this.exif||(this.ifd0||await this.parseIfd0Block(),this.exifOffset===void 0))return;this.file.tiff&&await this.file.ensureChunk(this.exifOffset,Go(this.options));let t=this.parseBlock(this.exifOffset,"exif");return this.interopOffset||(this.interopOffset=t.get(40965)),this.makerNote=t.get(37500),this.userComment=t.get(37510),this.options.sanitize&&(t.delete(40965),t.delete(37500),t.delete(37510)),this.unpack(t,41728),this.unpack(t,41729),t}unpack(t,e){let i=t.get(e);i&&i.length===1&&t.set(e,i[0])}async parseGpsBlock(){if(this.gps||(this.ifd0||await this.parseIfd0Block(),this.gpsOffset===void 0))return;let t=this.parseBlock(this.gpsOffset,"gps");return t&&t.has(2)&&t.has(4)&&(t.set("latitude",Jo(...t.get(2),t.get(1))),t.set("longitude",Jo(...t.get(4),t.get(3)))),t}async parseInteropBlock(){if(!this.interop&&(this.ifd0||await this.parseIfd0Block(),this.interopOffset!==void 0||this.exif||await this.parseExifBlock(),this.interopOffset!==void 0))return this.parseBlock(this.interopOffset,"interop")}async parseThumbnailBlock(t=!1){if(!this.ifd1&&!this.ifd1Parsed&&(!this.options.mergeOutput||t))return this.findIfd1Offset(),this.ifd1Offset>0&&(this.parseBlock(this.ifd1Offset,"ifd1"),this.ifd1Parsed=!0),this.ifd1}async extractThumbnail(){if(this.headerParsed||this.parseHeader(),this.ifd1Parsed||await this.parseThumbnailBlock(!0),this.ifd1===void 0)return;let t=this.ifd1.get(513),e=this.ifd1.get(514);return this.chunk.getUint8Array(t,e)}get image(){return this.ifd0}get thumbnail(){return this.ifd1}createOutput(){let t,e,i,r={};for(e of zt)if(t=this[e],!sc(t))if(i=this.canTranslate?this.translateBlock(t,e):Object.fromEntries(t),this.options.mergeOutput){if(e==="ifd1")continue;Object.assign(r,i)}else r[e]=i;return this.makerNote&&(r.makerNote=this.makerNote),this.userComment&&(r.userComment=this.userComment),r}assignToOutput(t,e){if(this.globalOptions.mergeOutput)Object.assign(t,e);else for(let[i,r]of Object.entries(e))this.assignObjectToOutput(t,i,r)}};function Jo(n,t,e,i){var r=n+t/60+e/3600;return i!=="S"&&i!=="W"||(r*=-1),r}kt(Ds,"type","tiff"),kt(Ds,"headerLength",10),ie.set("tiff",Ds);var Ql=Object.freeze({__proto__:null,default:ql,Exifr:Oe,fileParsers:Ri,segmentParsers:ie,fileReaders:Mi,tagKeys:Le,tagValues:hs,tagRevivers:ki,createDictionary:ge,extendDictionary:ua,fetchUrlAsArrayBuffer:os,readBlobAsArrayBuffer:cs,chunkedProps:_i,otherSegments:Ns,segments:ls,tiffBlocks:zt,segmentsAndBlocks:Ci,tiffExtractables:Pi,inheritables:Bs,allFormatters:Ti,Options:Ze,parse:pa}),fa={ifd0:!1,ifd1:!1,exif:!1,gps:!1,interop:!1,sanitize:!1,reviveValues:!0,translateKeys:!1,translateValues:!1,mergeOutput:!1},oc=Object.assign({},fa,{firstChunkSize:4e4,gps:[1,2,3,4]});async function Zl(n){let t=new Oe(oc);await t.read(n);let e=await t.parse();if(e&&e.gps){let{latitude:i,longitude:r}=e.gps;return{latitude:i,longitude:r}}}var cc=Object.assign({},fa,{tiff:!1,ifd1:!0,mergeOutput:!1});async function th(n){let t=new Oe(cc);await t.read(n);let e=await t.extractThumbnail();return e&&da?ha.from(e):e}async function eh(n){let t=await this.thumbnail(n);if(t!==void 0){let e=new Blob([t]);return URL.createObjectURL(e)}}var lc=Object.assign({},fa,{firstChunkSize:4e4,ifd0:[274]});async function hc(n){let t=new Oe(lc);await t.read(n);let e=await t.parse();if(e&&e.ifd0)return e.ifd0[274]}var dc=Object.freeze({1:{dimensionSwapped:!1,scaleX:1,scaleY:1,deg:0,rad:0},2:{dimensionSwapped:!1,scaleX:-1,scaleY:1,deg:0,rad:0},3:{dimensionSwapped:!1,scaleX:1,scaleY:1,deg:180,rad:180*Math.PI/180},4:{dimensionSwapped:!1,scaleX:-1,scaleY:1,deg:180,rad:180*Math.PI/180},5:{dimensionSwapped:!0,scaleX:1,scaleY:-1,deg:90,rad:90*Math.PI/180},6:{dimensionSwapped:!0,scaleX:1,scaleY:1,deg:90,rad:90*Math.PI/180},7:{dimensionSwapped:!0,scaleX:1,scaleY:-1,deg:270,rad:270*Math.PI/180},8:{dimensionSwapped:!0,scaleX:1,scaleY:1,deg:270,rad:270*Math.PI/180}}),rs=!0,as=!0;if(typeof navigator=="object"){let n=navigator.userAgent;if(n.includes("iPad")||n.includes("iPhone")){let t=n.match(/OS (\d+)_(\d+)/);if(t){let[,e,i]=t;rs=Number(e)+.1*Number(i)<13.4,as=!1}}else if(n.includes("OS X 10")){let[,t]=n.match(/OS X 10[_.](\d+)/);rs=as=Number(t)<15}if(n.includes("Chrome/")){let[,t]=n.match(/Chrome\/(\d+)/);rs=as=Number(t)<81}else if(n.includes("Firefox/")){let[,t]=n.match(/Firefox\/(\d+)/);rs=as=Number(t)<77}}async function ih(n){let t=await hc(n);return Object.assign({canvas:rs,css:as},dc[t])}var ra=class extends Fe{constructor(...t){super(...t),kt(this,"ranges",new aa),this.byteLength!==0&&this.ranges.add(0,this.byteLength)}_tryExtend(t,e,i){if(t===0&&this.byteLength===0&&i){let r=new DataView(i.buffer||i,i.byteOffset,i.byteLength);this._swapDataView(r)}else{let r=t+e;if(r>this.byteLength){let{dataView:o}=this._extend(r);this._swapDataView(o)}}}_extend(t){let e;e=da?ha.allocUnsafe(t):new Uint8Array(t);let i=new DataView(e.buffer,e.byteOffset,e.byteLength);return e.set(new Uint8Array(this.buffer,this.byteOffset,this.byteLength),0),{uintView:e,dataView:i}}subarray(t,e,i=!1){return e=e||this._lengthToEnd(t),i&&this._tryExtend(t,e),this.ranges.add(t,e),super.subarray(t,e)}set(t,e,i=!1){i&&this._tryExtend(e,t.byteLength,t);let r=super.set(t,e);return this.ranges.add(e,r.byteLength),r}async ensureChunk(t,e){this.chunked&&(this.ranges.available(t,e)||await this.readChunk(t,e))}available(t,e){return this.ranges.available(t,e)}},aa=class{constructor(){kt(this,"list",[])}get length(){return this.list.length}add(t,e,i=0){let r=t+e,o=this.list.filter((g=>Qo(t,g.offset,r)||Qo(t,g.end,r)));if(o.length>0){t=Math.min(t,...o.map((d=>d.offset))),r=Math.max(r,...o.map((d=>d.end))),e=r-t;let g=o.shift();g.offset=t,g.length=e,g.end=r,this.list=this.list.filter((d=>!o.includes(d)))}else this.list.push({offset:t,length:e,end:r})}available(t,e){let i=t+e;return this.list.some((r=>r.offset<=t&&i<=r.end))}};function Qo(n,t,e){return n<=t&&t<=e}var Gn=class extends ra{constructor(t,e){super(0),kt(this,"chunksRead",0),this.input=t,this.options=e}async readWhole(){this.chunked=!1,await this.readChunk(this.nextChunkOffset)}async readChunked(){this.chunked=!0,await this.readChunk(0,this.options.firstChunkSize)}async readNextChunk(t=this.nextChunkOffset){if(this.fullyRead)return this.chunksRead++,!1;let e=this.options.chunkSize,i=await this.readChunk(t,e);return!!i&&i.byteLength===e}async readChunk(t,e){if(this.chunksRead++,(e=this.safeWrapAddress(t,e))!==0)return this._readChunk(t,e)}safeWrapAddress(t,e){return this.size!==void 0&&t+e>this.size?Math.max(0,this.size-t):e}get nextChunkOffset(){if(this.ranges.list.length!==0)return this.ranges.list[0].length}get canReadNextChunk(){return this.chunksRead<this.options.chunkLimit}get fullyRead(){return this.size!==void 0&&this.nextChunkOffset===this.size}read(){return this.options.chunked?this.readChunked():this.readWhole()}close(){}};Mi.set("blob",class extends Gn{async readWhole(){this.chunked=!1;let n=await cs(this.input);this._swapArrayBuffer(n)}readChunked(){return this.chunked=!0,this.size=this.input.size,super.readChunked()}async _readChunk(n,t){let e=t?n+t:void 0,i=this.input.slice(n,e),r=await cs(i);return this.set(r,n,!0)}});var sh=Object.freeze({__proto__:null,default:Ql,Exifr:Oe,fileParsers:Ri,segmentParsers:ie,fileReaders:Mi,tagKeys:Le,tagValues:hs,tagRevivers:ki,createDictionary:ge,extendDictionary:ua,fetchUrlAsArrayBuffer:os,readBlobAsArrayBuffer:cs,chunkedProps:_i,otherSegments:Ns,segments:ls,tiffBlocks:zt,segmentsAndBlocks:Ci,tiffExtractables:Pi,inheritables:Bs,allFormatters:Ti,Options:Ze,parse:pa,gpsOnlyOptions:oc,gps:Zl,thumbnailOnlyOptions:cc,thumbnail:th,thumbnailUrl:eh,orientationOnlyOptions:lc,orientation:hc,rotations:dc,get rotateCanvas(){return rs},get rotateCss(){return as},rotation:ih});Mi.set("url",class extends Gn{async readWhole(){this.chunked=!1;let n=await os(this.input);n instanceof ArrayBuffer?this._swapArrayBuffer(n):n instanceof Uint8Array&&this._swapBuffer(n)}async _readChunk(n,t){let e=t?n+t-1:void 0,i=this.options.httpHeaders||{};(n||e)&&(i.range=`bytes=${[n,e].join("-")}`);let r=await ac(this.input,{headers:i}),o=await r.arrayBuffer(),g=o.byteLength;if(r.status!==416)return g!==t&&(this.size=n+g),this.set(o,n,!0)}});Fe.prototype.getUint64=function(n){let t=this.getUint32(n),e=this.getUint32(n+4);return t<1048575?t<<32|e:typeof $n!==void 0?(console.warn("Using BigInt because of type 64uint but JS can only handle 53b numbers."),$n(t)<<$n(32)|$n(e)):void qt("Trying to read 64b value but JS can only handle 53b numbers.")};var oa=class extends Vn{parseBoxes(t=0){let e=[];for(;t<this.file.byteLength-4;){let i=this.parseBoxHead(t);if(e.push(i),i.length===0)break;t+=i.length}return e}parseSubBoxes(t){t.boxes=this.parseBoxes(t.start)}findBox(t,e){return t.boxes===void 0&&this.parseSubBoxes(t),t.boxes.find((i=>i.kind===e))}parseBoxHead(t){let e=this.file.getUint32(t),i=this.file.getString(t+4,4),r=t+8;return e===1&&(e=this.file.getUint64(t+8),r+=8),{offset:t,length:e,kind:i,start:r}}parseBoxFullHead(t){if(t.version!==void 0)return;let e=this.file.getUint32(t.start);t.version=e>>24,t.start+=4}},qn=class extends oa{static canHandle(t,e){if(e!==0)return!1;let i=t.getUint16(2);if(i>50)return!1;let r=16,o=[];for(;r<i;)o.push(t.getString(r,4)),r+=4;return o.includes(this.type)}async parse(){let t=this.file.getUint32(0),e=this.parseBoxHead(t);for(;e.kind!=="meta";)t+=e.length,await this.file.ensureChunk(t,16),e=this.parseBoxHead(t);await this.file.ensureChunk(e.offset,e.length),this.parseBoxFullHead(e),this.parseSubBoxes(e),this.options.icc.enabled&&await this.findIcc(e),this.options.tiff.enabled&&await this.findExif(e)}async registerSegment(t,e,i){await this.file.ensureChunk(e,i);let r=this.file.subarray(e,i);this.createParser(t,r)}async findIcc(t){let e=this.findBox(t,"iprp");if(e===void 0)return;let i=this.findBox(e,"ipco");if(i===void 0)return;let r=this.findBox(i,"colr");r!==void 0&&await this.registerSegment("icc",r.offset+12,r.length)}async findExif(t){let e=this.findBox(t,"iinf");if(e===void 0)return;let i=this.findBox(t,"iloc");if(i===void 0)return;let r=this.findExifLocIdInIinf(e),o=this.findExtentInIloc(i,r);if(o===void 0)return;let[g,d]=o;await this.file.ensureChunk(g,d);let m=4+this.file.getUint32(g);g+=m,d-=m,await this.registerSegment("tiff",g,d)}findExifLocIdInIinf(t){this.parseBoxFullHead(t);let e,i,r,o,g=t.start,d=this.file.getUint16(g);for(g+=2;d--;){if(e=this.parseBoxHead(g),this.parseBoxFullHead(e),i=e.start,e.version>=2&&(r=e.version===3?4:2,o=this.file.getString(i+r+2,4),o==="Exif"))return this.file.getUintBytes(i,r);g+=e.length}}get8bits(t){let e=this.file.getUint8(t);return[e>>4,15&e]}findExtentInIloc(t,e){this.parseBoxFullHead(t);let i=t.start,[r,o]=this.get8bits(i++),[g,d]=this.get8bits(i++),m=t.version===2?4:2,v=t.version===1||t.version===2?2:0,u=d+r+o,a=t.version===2?4:2,p=this.file.getUintBytes(i,a);for(i+=a;p--;){let x=this.file.getUintBytes(i,m);i+=m+v+2+g;let T=this.file.getUint16(i);if(i+=2,x===e)return T>1&&console.warn(`ILOC box has more than one extent but we're only processing one
|
|
9
|
-
Please create an issue at https://github.com/MikeKovarik/exifr with this file`),[this.file.getUintBytes(i+d,r),this.file.getUintBytes(i+d+r,o)];i+=T*u}}},Xn=class extends qn{};kt(Xn,"type","heic");var Kn=class extends qn{};kt(Kn,"type","avif"),Ri.set("heic",Xn),Ri.set("avif",Kn),ge(Le,["ifd0","ifd1"],[[256,"ImageWidth"],[257,"ImageHeight"],[258,"BitsPerSample"],[259,"Compression"],[262,"PhotometricInterpretation"],[270,"ImageDescription"],[271,"Make"],[272,"Model"],[273,"StripOffsets"],[274,"Orientation"],[277,"SamplesPerPixel"],[278,"RowsPerStrip"],[279,"StripByteCounts"],[282,"XResolution"],[283,"YResolution"],[284,"PlanarConfiguration"],[296,"ResolutionUnit"],[301,"TransferFunction"],[305,"Software"],[306,"ModifyDate"],[315,"Artist"],[316,"HostComputer"],[317,"Predictor"],[318,"WhitePoint"],[319,"PrimaryChromaticities"],[513,"ThumbnailOffset"],[514,"ThumbnailLength"],[529,"YCbCrCoefficients"],[530,"YCbCrSubSampling"],[531,"YCbCrPositioning"],[532,"ReferenceBlackWhite"],[700,"ApplicationNotes"],[33432,"Copyright"],[33723,"IPTC"],[34665,"ExifIFD"],[34675,"ICC"],[34853,"GpsIFD"],[330,"SubIFD"],[40965,"InteropIFD"],[40091,"XPTitle"],[40092,"XPComment"],[40093,"XPAuthor"],[40094,"XPKeywords"],[40095,"XPSubject"]]),ge(Le,"exif",[[33434,"ExposureTime"],[33437,"FNumber"],[34850,"ExposureProgram"],[34852,"SpectralSensitivity"],[34855,"ISO"],[34858,"TimeZoneOffset"],[34859,"SelfTimerMode"],[34864,"SensitivityType"],[34865,"StandardOutputSensitivity"],[34866,"RecommendedExposureIndex"],[34867,"ISOSpeed"],[34868,"ISOSpeedLatitudeyyy"],[34869,"ISOSpeedLatitudezzz"],[36864,"ExifVersion"],[36867,"DateTimeOriginal"],[36868,"CreateDate"],[36873,"GooglePlusUploadCode"],[36880,"OffsetTime"],[36881,"OffsetTimeOriginal"],[36882,"OffsetTimeDigitized"],[37121,"ComponentsConfiguration"],[37122,"CompressedBitsPerPixel"],[37377,"ShutterSpeedValue"],[37378,"ApertureValue"],[37379,"BrightnessValue"],[37380,"ExposureCompensation"],[37381,"MaxApertureValue"],[37382,"SubjectDistance"],[37383,"MeteringMode"],[37384,"LightSource"],[37385,"Flash"],[37386,"FocalLength"],[37393,"ImageNumber"],[37394,"SecurityClassification"],[37395,"ImageHistory"],[37396,"SubjectArea"],[37500,"MakerNote"],[37510,"UserComment"],[37520,"SubSecTime"],[37521,"SubSecTimeOriginal"],[37522,"SubSecTimeDigitized"],[37888,"AmbientTemperature"],[37889,"Humidity"],[37890,"Pressure"],[37891,"WaterDepth"],[37892,"Acceleration"],[37893,"CameraElevationAngle"],[40960,"FlashpixVersion"],[40961,"ColorSpace"],[40962,"ExifImageWidth"],[40963,"ExifImageHeight"],[40964,"RelatedSoundFile"],[41483,"FlashEnergy"],[41486,"FocalPlaneXResolution"],[41487,"FocalPlaneYResolution"],[41488,"FocalPlaneResolutionUnit"],[41492,"SubjectLocation"],[41493,"ExposureIndex"],[41495,"SensingMethod"],[41728,"FileSource"],[41729,"SceneType"],[41730,"CFAPattern"],[41985,"CustomRendered"],[41986,"ExposureMode"],[41987,"WhiteBalance"],[41988,"DigitalZoomRatio"],[41989,"FocalLengthIn35mmFormat"],[41990,"SceneCaptureType"],[41991,"GainControl"],[41992,"Contrast"],[41993,"Saturation"],[41994,"Sharpness"],[41996,"SubjectDistanceRange"],[42016,"ImageUniqueID"],[42032,"OwnerName"],[42033,"SerialNumber"],[42034,"LensInfo"],[42035,"LensMake"],[42036,"LensModel"],[42037,"LensSerialNumber"],[42080,"CompositeImage"],[42081,"CompositeImageCount"],[42082,"CompositeImageExposureTimes"],[42240,"Gamma"],[59932,"Padding"],[59933,"OffsetSchema"],[65e3,"OwnerName"],[65001,"SerialNumber"],[65002,"Lens"],[65100,"RawFile"],[65101,"Converter"],[65102,"WhiteBalance"],[65105,"Exposure"],[65106,"Shadows"],[65107,"Brightness"],[65108,"Contrast"],[65109,"Saturation"],[65110,"Sharpness"],[65111,"Smoothness"],[65112,"MoireFilter"],[40965,"InteropIFD"]]),ge(Le,"gps",[[0,"GPSVersionID"],[1,"GPSLatitudeRef"],[2,"GPSLatitude"],[3,"GPSLongitudeRef"],[4,"GPSLongitude"],[5,"GPSAltitudeRef"],[6,"GPSAltitude"],[7,"GPSTimeStamp"],[8,"GPSSatellites"],[9,"GPSStatus"],[10,"GPSMeasureMode"],[11,"GPSDOP"],[12,"GPSSpeedRef"],[13,"GPSSpeed"],[14,"GPSTrackRef"],[15,"GPSTrack"],[16,"GPSImgDirectionRef"],[17,"GPSImgDirection"],[18,"GPSMapDatum"],[19,"GPSDestLatitudeRef"],[20,"GPSDestLatitude"],[21,"GPSDestLongitudeRef"],[22,"GPSDestLongitude"],[23,"GPSDestBearingRef"],[24,"GPSDestBearing"],[25,"GPSDestDistanceRef"],[26,"GPSDestDistance"],[27,"GPSProcessingMethod"],[28,"GPSAreaInformation"],[29,"GPSDateStamp"],[30,"GPSDifferential"],[31,"GPSHPositioningError"]]),ge(hs,["ifd0","ifd1"],[[274,{1:"Horizontal (normal)",2:"Mirror horizontal",3:"Rotate 180",4:"Mirror vertical",5:"Mirror horizontal and rotate 270 CW",6:"Rotate 90 CW",7:"Mirror horizontal and rotate 90 CW",8:"Rotate 270 CW"}],[296,{1:"None",2:"inches",3:"cm"}]]);var Is=ge(hs,"exif",[[34850,{0:"Not defined",1:"Manual",2:"Normal program",3:"Aperture priority",4:"Shutter priority",5:"Creative program",6:"Action program",7:"Portrait mode",8:"Landscape mode"}],[37121,{0:"-",1:"Y",2:"Cb",3:"Cr",4:"R",5:"G",6:"B"}],[37383,{0:"Unknown",1:"Average",2:"CenterWeightedAverage",3:"Spot",4:"MultiSpot",5:"Pattern",6:"Partial",255:"Other"}],[37384,{0:"Unknown",1:"Daylight",2:"Fluorescent",3:"Tungsten (incandescent light)",4:"Flash",9:"Fine weather",10:"Cloudy weather",11:"Shade",12:"Daylight fluorescent (D 5700 - 7100K)",13:"Day white fluorescent (N 4600 - 5400K)",14:"Cool white fluorescent (W 3900 - 4500K)",15:"White fluorescent (WW 3200 - 3700K)",17:"Standard light A",18:"Standard light B",19:"Standard light C",20:"D55",21:"D65",22:"D75",23:"D50",24:"ISO studio tungsten",255:"Other"}],[37385,{0:"Flash did not fire",1:"Flash fired",5:"Strobe return light not detected",7:"Strobe return light detected",9:"Flash fired, compulsory flash mode",13:"Flash fired, compulsory flash mode, return light not detected",15:"Flash fired, compulsory flash mode, return light detected",16:"Flash did not fire, compulsory flash mode",24:"Flash did not fire, auto mode",25:"Flash fired, auto mode",29:"Flash fired, auto mode, return light not detected",31:"Flash fired, auto mode, return light detected",32:"No flash function",65:"Flash fired, red-eye reduction mode",69:"Flash fired, red-eye reduction mode, return light not detected",71:"Flash fired, red-eye reduction mode, return light detected",73:"Flash fired, compulsory flash mode, red-eye reduction mode",77:"Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected",79:"Flash fired, compulsory flash mode, red-eye reduction mode, return light detected",89:"Flash fired, auto mode, red-eye reduction mode",93:"Flash fired, auto mode, return light not detected, red-eye reduction mode",95:"Flash fired, auto mode, return light detected, red-eye reduction mode"}],[41495,{1:"Not defined",2:"One-chip color area sensor",3:"Two-chip color area sensor",4:"Three-chip color area sensor",5:"Color sequential area sensor",7:"Trilinear sensor",8:"Color sequential linear sensor"}],[41728,{1:"Film Scanner",2:"Reflection Print Scanner",3:"Digital Camera"}],[41729,{1:"Directly photographed"}],[41985,{0:"Normal",1:"Custom",2:"HDR (no original saved)",3:"HDR (original saved)",4:"Original (for HDR)",6:"Panorama",7:"Portrait HDR",8:"Portrait"}],[41986,{0:"Auto",1:"Manual",2:"Auto bracket"}],[41987,{0:"Auto",1:"Manual"}],[41990,{0:"Standard",1:"Landscape",2:"Portrait",3:"Night",4:"Other"}],[41991,{0:"None",1:"Low gain up",2:"High gain up",3:"Low gain down",4:"High gain down"}],[41996,{0:"Unknown",1:"Macro",2:"Close",3:"Distant"}],[42080,{0:"Unknown",1:"Not a Composite Image",2:"General Composite Image",3:"Composite Image Captured While Shooting"}]]),Zo={1:"No absolute unit of measurement",2:"Inch",3:"Centimeter"};Is.set(37392,Zo),Is.set(41488,Zo);var Jr={0:"Normal",1:"Low",2:"High"};function tc(n){return typeof n=="object"&&n.length!==void 0?n[0]:n}function ec(n){let t=Array.from(n).slice(1);return t[1]>15&&(t=t.map((e=>String.fromCharCode(e)))),t[2]!=="0"&&t[2]!==0||t.pop(),t.join(".")}function Qr(n){if(typeof n=="string"){var[t,e,i,r,o,g]=n.trim().split(/[-: ]/g).map(Number),d=new Date(t,e-1,i);return Number.isNaN(r)||Number.isNaN(o)||Number.isNaN(g)||(d.setHours(r),d.setMinutes(o),d.setSeconds(g)),Number.isNaN(+d)?n:d}}function Ms(n){if(typeof n=="string")return n;let t=[];if(n[1]===0&&n[n.length-1]===0)for(let e=0;e<n.length;e+=2)t.push(ic(n[e+1],n[e]));else for(let e=0;e<n.length;e+=2)t.push(ic(n[e],n[e+1]));return nc(String.fromCodePoint(...t))}function ic(n,t){return n<<8|t}Is.set(41992,Jr),Is.set(41993,Jr),Is.set(41994,Jr),ge(ki,["ifd0","ifd1"],[[50827,function(n){return typeof n!="string"?rc(n):n}],[306,Qr],[40091,Ms],[40092,Ms],[40093,Ms],[40094,Ms],[40095,Ms]]),ge(ki,"exif",[[40960,ec],[36864,ec],[36867,Qr],[36868,Qr],[40962,tc],[40963,tc]]),ge(ki,"gps",[[0,n=>Array.from(n).join(".")],[7,n=>Array.from(n).join(":")]]);var Ls=class extends Ie{static canHandle(t,e){return t.getUint8(e+1)===225&&t.getUint32(e+4)===1752462448&&t.getString(e+4,20)==="http://ns.adobe.com/"}static headerLength(t,e){return t.getString(e+4,34)==="http://ns.adobe.com/xmp/extension/"?79:33}static findPosition(t,e){let i=super.findPosition(t,e);return i.multiSegment=i.extended=i.headerLength===79,i.multiSegment?(i.chunkCount=t.getUint8(e+72),i.chunkNumber=t.getUint8(e+76),t.getUint8(e+77)!==0&&i.chunkNumber++):(i.chunkCount=1/0,i.chunkNumber=-1),i}static handleMultiSegments(t){return t.map((e=>e.chunk.getString())).join("")}normalizeInput(t){return typeof t=="string"?t:Fe.from(t).getString()}parse(t=this.chunk){if(!this.localOptions.parse)return t;t=(function(o){let g={},d={};for(let m of gc)g[m]=[],d[m]=0;return o.replace(oh,((m,v,u)=>{if(v==="<"){let a=++d[u];return g[u].push(a),`${m}#${a}`}return`${m}#${g[u].pop()}`}))})(t);let e=Yn.findAll(t,"rdf","Description");e.length===0&&e.push(new Yn("rdf","Description",void 0,t));let i,r={};for(let o of e)for(let g of o.properties)i=ah(g.ns,r),uc(g,i);return(function(o){let g;for(let d in o)g=o[d]=Hn(o[d]),g===void 0&&delete o[d];return Hn(o)})(r)}assignToOutput(t,e){if(this.localOptions.parse)for(let[i,r]of Object.entries(e))switch(i){case"tiff":this.assignObjectToOutput(t,"ifd0",r);break;case"exif":this.assignObjectToOutput(t,"exif",r);break;case"xmlns":break;default:this.assignObjectToOutput(t,i,r)}else t.xmp=e}};kt(Ls,"type","xmp"),kt(Ls,"multiSegment",!0),ie.set("xmp",Ls);var ca=class n{static findAll(t){return pc(t,/([a-zA-Z0-9-]+):([a-zA-Z0-9-]+)=("[^"]*"|'[^']*')/gm).map(n.unpackMatch)}static unpackMatch(t){let e=t[1],i=t[2],r=t[3].slice(1,-1);return r=fc(r),new n(e,i,r)}constructor(t,e,i){this.ns=t,this.name=e,this.value=i}serialize(){return this.value}},Yn=class n{static findAll(t,e,i){if(e!==void 0||i!==void 0){e=e||"[\\w\\d-]+",i=i||"[\\w\\d-]+";var r=new RegExp(`<(${e}):(${i})(#\\d+)?((\\s+?[\\w\\d-:]+=("[^"]*"|'[^']*'))*\\s*)(\\/>|>([\\s\\S]*?)<\\/\\1:\\2\\3>)`,"gm")}else r=/<([\w\d-]+):([\w\d-]+)(#\d+)?((\s+?[\w\d-:]+=("[^"]*"|'[^']*'))*\s*)(\/>|>([\s\S]*?)<\/\1:\2\3>)/gm;return pc(t,r).map(n.unpackMatch)}static unpackMatch(t){let e=t[1],i=t[2],r=t[4],o=t[8];return new n(e,i,r,o)}constructor(t,e,i,r){this.ns=t,this.name=e,this.attrString=i,this.innerXml=r,this.attrs=ca.findAll(i),this.children=n.findAll(r),this.value=this.children.length===0?fc(r):void 0,this.properties=[...this.attrs,...this.children]}get isPrimitive(){return this.value!==void 0&&this.attrs.length===0&&this.children.length===0}get isListContainer(){return this.children.length===1&&this.children[0].isList}get isList(){let{ns:t,name:e}=this;return t==="rdf"&&(e==="Seq"||e==="Bag"||e==="Alt")}get isListItem(){return this.ns==="rdf"&&this.name==="li"}serialize(){if(this.properties.length===0&&this.value===void 0)return;if(this.isPrimitive)return this.value;if(this.isListContainer)return this.children[0].serialize();if(this.isList)return rh(this.children.map(nh));if(this.isListItem&&this.children.length===1&&this.attrs.length===0)return this.children[0].serialize();let t={};for(let e of this.properties)uc(e,t);return this.value!==void 0&&(t.value=this.value),Hn(t)}};function uc(n,t){let e=n.serialize();e!==void 0&&(t[n.name]=e)}var nh=n=>n.serialize(),rh=n=>n.length===1?n[0]:n,ah=(n,t)=>t[n]?t[n]:t[n]={};function pc(n,t){let e,i=[];if(!n)return i;for(;(e=t.exec(n))!==null;)i.push(e);return i}function fc(n){if((function(i){return i==null||i==="null"||i==="undefined"||i===""||i.trim()===""})(n))return;let t=Number(n);if(!Number.isNaN(t))return t;let e=n.toLowerCase();return e==="true"||e!=="false"&&n.trim()}var gc=["rdf:li","rdf:Seq","rdf:Bag","rdf:Alt","rdf:Description"],oh=new RegExp(`(<|\\/)(${gc.join("|")})`,"g"),mc=sh;async function Jn(n){try{return await mc.parse(n)||null}catch{return null}}function Di(){return Array.from(crypto.getRandomValues(new Uint8Array(16)),n=>n.toString(16).padStart(2,"0")).join("")}async function Qn(n){if(typeof createImageBitmap>"u"||typeof document>"u"){if(n&&typeof n.arrayBuffer=="function"){let d=await n.arrayBuffer(),m=globalThis.Buffer,v=typeof m<"u"?m.from(d).toString("base64"):btoa(String.fromCharCode(...new Uint8Array(d)));return`data:${n.type||"image/png"};base64,${v}`}if(typeof n=="string")return n}let t=await createImageBitmap(n),r=Math.min(1,1654/t.width,2339/t.height);if(r===1&&(n.type==="image/jpeg"||n.type==="image/jpg"||n.type==="image/png"||n.type==="image/webp"))return t.close(),new Promise((d,m)=>{let v=new FileReader;v.onload=()=>d(v.result),v.onerror=m,v.readAsDataURL(n)});let o=document.createElement("canvas");o.width=Math.round(t.width*r),o.height=Math.round(t.height*r),o.getContext("2d").drawImage(t,0,0,o.width,o.height),t.close();let g=n.type==="image/png"?"image/png":"image/jpeg";return o.toDataURL(g,g==="image/png"?void 0:.82)}function ga(n,t=21,e=.2,i=128){let{data:r,width:o,height:g}=n,d=o+1,m=new Float64Array((o+1)*(g+1)),v=new Float64Array((o+1)*(g+1)),u=new Uint8Array(o*g);for(let p=0;p<g;p++){let x=0,T=0,l=p*o,y=(p+1)*d,s=p*d;for(let c=0;c<o;c++){let f=(l+c)*4,w=r[f]*77+r[f+1]*150+r[f+2]*29>>8;u[l+c]=w,x+=w,T+=w*w,m[y+c+1]=m[s+c+1]+x,v[y+c+1]=v[s+c+1]+T}}let a=Math.floor(t/2);for(let p=0;p<g;p++){let x=Math.max(0,p-a),T=Math.min(g-1,p+a),l=x*d,y=(T+1)*d;for(let s=0;s<o;s++){let c=Math.max(0,s-a),f=Math.min(o-1,s+a),w=(f-c+1)*(T-x+1),R=m[y+f+1]-m[l+f+1]-m[y+c]+m[l+c],S=v[y+f+1]-v[l+f+1]-v[y+c]+v[l+c],D=R/w,N=Math.max(0,S/w-D*D),H=Math.sqrt(N),j=D*(1+e*(H/i-1)),Y=p*o+s,it=u[Y]<j?0:255,ot=Y*4;r[ot]=it,r[ot+1]=it,r[ot+2]=it}}return n}function ma(n,t=21,e=.2,i=128){return new Promise(r=>{let o=new Image;o.onload=()=>{let g=document.createElement("canvas");g.width=o.width,g.height=o.height;let d=g.getContext("2d");d.drawImage(o,0,0);let m=d.getImageData(0,0,g.width,g.height);ga(m,t,e,i),d.putImageData(m,0,0);let v=n.startsWith("data:image/png"),u=v?"image/png":"image/jpeg";r(g.toDataURL(u,v?void 0:.82))},o.src=n})}function ba(n){return new Promise(t=>{let e=new Image;e.onload=()=>{let i=document.createElement("canvas");i.width=e.height,i.height=e.width;let r=i.getContext("2d");r.translate(i.width/2,i.height/2),r.rotate(Math.PI/2),r.drawImage(e,-e.width/2,-e.height/2);let o=n.startsWith("data:image/png"),g=o?"image/png":"image/jpeg";t(i.toDataURL(g,o?void 0:.82))},e.src=n})}function ya(n,t=""){if(!n)return"";let e=n.getCroppedCanvas(),i=t.startsWith("data:image/png"),r=i?"image/png":"image/jpeg";return e.toDataURL(r,i?void 0:.82)}function Zn(n){if(!n||typeof n!="object")return{crop:null,rotation:0,filter:"none"};let t=null;n.crop&&typeof n.crop=="object"&&(n.crop.width>0&&n.crop.height>0?t={x:Math.round(n.crop.x||0),y:Math.round(n.crop.y||0),width:Math.round(n.crop.width),height:Math.round(n.crop.height)}:n.crop.w>0&&n.crop.h>0&&(t={x:Number(n.crop.x)||0,y:Number(n.crop.y)||0,w:Number(n.crop.w)||1,h:Number(n.crop.h)||1}));let e=n.rotation!==void 0?n.rotation:n.rotate,i=(Math.round(Number(e)||0)%360+360)%360,r=n.filter==="bw"?"bw":"none";return{crop:t,rotation:i,filter:r}}function ch(n){if(!n)return!1;let t=Zn(n);return!!(t.crop||t.rotation!==0||t.filter!=="none")}function tr(n,t){let e=Zn(t),i=n.naturalWidth||n.width||0,r=n.naturalHeight||n.height||0,o=document.createElement("canvas"),g=i,d=r,m=0,v=0;if(e.crop){let p=e.crop;"w"in p&&!("width"in p)?(m=Math.max(0,Math.min(Math.round(p.x*i),i)),v=Math.max(0,Math.min(Math.round(p.y*r),r)),g=Math.max(1,Math.min(Math.round(p.w*i),i-m)),d=Math.max(1,Math.min(Math.round(p.h*r),r-v))):(m=Math.max(0,Math.min(p.x,i)),v=Math.max(0,Math.min(p.y,r)),g=Math.max(1,Math.min(p.width,i-m)),d=Math.max(1,Math.min(p.height,r-v)))}o.width=g,o.height=d,o.getContext("2d").drawImage(n,m,v,g,d,0,0,g,d);let a=o;if(e.rotation!==0){let p=e.rotation,x=document.createElement("canvas");p===90||p===270?(x.width=a.height,x.height=a.width):(x.width=a.width,x.height=a.height);let T=x.getContext("2d");T.translate(x.width/2,x.height/2),T.rotate(p*Math.PI/180),T.drawImage(a,-a.width/2,-a.height/2),a=x}if(e.filter==="bw"){let p=a.getContext("2d"),x=p.getImageData(0,0,a.width,a.height);ga(x),p.putImageData(x,0,0)}return a}function bc(n,t){if(!n)return Promise.resolve("");let e=Zn(t);return ch(e)?new Promise((i,r)=>{let o=new Image;o.onload=()=>{try{let g=n.startsWith("data:image/png"),d=g?"image/png":"image/jpeg",m=tr(o,e);i(m.toDataURL(d,g?void 0:.82))}catch(g){r(g)}},o.onerror=r,o.src=n}):Promise.resolve(n)}var ti=class{#t=null;#e=new Map;#i=new Map;constructor(t=ns()){this.#t=t}get adapter(){return this.#t}get store(){return this.#t?.store??null}async init(){return this.#t.init()}listDocsSync(){return typeof this.#t.listDocsSync=="function"?this.#t.listDocsSync().map(e=>{let i=this.#s(e.pages);return{id:e.id,name:e.name||"",pageCount:i.length,pages:i}}):[]}async listDocs(){return(await this.#t.listDocs()).map(e=>{let i=this.#s(e.pages);return{id:e.id,name:e.name||"",pageCount:i.length,pages:i}})}getDocSync(t){if(!t)return null;if(typeof this.#t.getDocSync=="function"){let r=this.#t.getDocSync(t);return r?{id:r.id,name:r.name||"",pages:this.#s(r.pages)}:null}let i=this.listDocsSync().find(r=>r.id===t);return i?{id:i.id,name:i.name,pages:i.pages||[]}:null}async getDoc(t){if(!t)return null;if(typeof this.#t.getDoc=="function"){let e=await this.#t.getDoc(t);return e?{id:e.id,name:e.name||"",pages:this.#s(e.pages)}:null}return this.getDocSync(t)}async createDoc(t="Untitled Document",e=[]){let i=Di(),r=this.#s(e),o={id:i,name:t||"Untitled Document",pages:r};return await this.#t.saveDoc(i,o),o}async saveDoc(t,e){if(!t)throw new Error("Cannot save document without an ID");let i=this.#s(e.pages);await this.#t.saveDoc(t,{id:t,name:e.name||"",pages:i})}async renameDoc(t,e){if(typeof this.#t.renameDoc=="function")return this.#t.renameDoc(t,e);let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);i.name=e,await this.saveDoc(t,i)}async deleteDoc(t,{soft:e=!0,timeoutMs:i=5e3}={}){if(!t)return;let r=this.getDocSync(t);if(r){if(this.#n(t),await this.#t.deleteDoc(t),e&&i>0){let o=setTimeout(async()=>{this.#e.delete(t)},i);this.#e.set(t,{doc:r,timerId:o})}return{id:t,name:r.name,undo:()=>this.undoDeleteDoc(t)}}}#n(t){if(this.#e.has(t)){let e=this.#e.get(t);clearTimeout(e.timerId),this.#e.delete(t)}}async undoDeleteDoc(t){let e=this.#e.get(t);return e?(clearTimeout(e.timerId),this.#e.delete(t),await this.#t.saveDoc(t,e.doc),e.doc):null}isSoftDeletedDoc(t){return this.#e.has(t)}async addPages(t,e){let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);let r=Array.isArray(e)?e:[e];i.pages.push(...r),await this.saveDoc(t,i)}async updatePage(t,e,i){let r=await this.getDoc(t);if(!r)throw new Error(`Document "${t}" not found`);let o=r.pages.findIndex(g=>g.id===e);if(o===-1)throw new Error(`Page "${e}" not found in document "${t}"`);r.pages[o]={...r.pages[o],...i},await this.saveDoc(t,r)}async reorderPages(t,e){let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);let r=new Map(i.pages.map(g=>[g.id,g])),o=[];for(let g of e)r.has(g)&&(o.push(r.get(g)),r.delete(g));for(let g of r.values())o.push(g);i.pages=o,await this.saveDoc(t,i)}async deletePage(t,e,{soft:i=!0,timeoutMs:r=5e3}={}){let o=await this.getDoc(t);if(!o)throw new Error(`Document "${t}" not found`);let g=o.pages.findIndex(u=>u.id===e);if(g===-1)return;let[d]=o.pages.splice(g,1);await this.saveDoc(t,o);let m=`${t}:${e}`;if(this.#r(m),!i||r<=0){if(typeof this.#t.deletePage=="function")try{await this.#t.deletePage(t,e)}catch(u){console.warn("[DocRepository] Adapter deletePage error:",u)}return}let v=setTimeout(async()=>{if(this.#i.delete(m),typeof this.#t.deletePage=="function")try{await this.#t.deletePage(t,e)}catch(u){console.warn("[DocRepository] Adapter deletePage error:",u)}},r);return this.#i.set(m,{docId:t,pageId:e,page:d,index:g,timerId:v}),{docId:t,pageId:e,undo:()=>this.undoDeletePage(t,e)}}#r(t){if(this.#i.has(t)){let e=this.#i.get(t);clearTimeout(e.timerId),this.#i.delete(t)}}async undoDeletePage(t,e){let i=`${t}:${e}`,r=this.#i.get(i);if(!r)return null;clearTimeout(r.timerId),this.#i.delete(i);let o=await this.getDoc(t);if(!o)return null;let g=Math.min(r.index,o.pages.length);return o.pages.splice(g,0,r.page),await this.saveDoc(t,o),r.page}isSoftDeletedPage(t,e){return this.#i.has(`${t}:${e}`)}subscribe(t){return this.#t.subscribe(t)}async getAllDocs(){let t=await this.listDocs(),e={};for(let i of t)e[i.id]=i;return e}async exportAll(){let t=await this.listDocs(),e={};for(let i of t){let r=await this.getDoc(i.id),o=[];for(let g of r?.pages||[]){if(!g){o.push(g);continue}let d={...g},m=d.blob instanceof Blob?d.blob:null;if(!m&&typeof d.src=="string"&&d.src.startsWith("blob:"))try{m=await(await fetch(d.src)).blob()}catch{}m&&(d.src=await Kr(m));let v=d.originalBlob instanceof Blob?d.originalBlob:null;if(!v&&typeof d.originalSrc=="string"&&d.originalSrc.startsWith("blob:"))try{v=await(await fetch(d.originalSrc)).blob()}catch{}v&&(d.originalSrc=await Kr(v)),delete d.blob,delete d.originalBlob,o.push(d)}e[i.id]={name:i.name,pages:JSON.stringify(o)}}return e}async importDocs(t){let e=0;for(let[i,r]of Object.entries(t||{})){await this.getDoc(i)||e++;let g=this.#s(r.pages);await this.saveDoc(i,{name:r.name||"",pages:g})}return e}#s(t){if(Array.isArray(t))return[...t];if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}},ds=new ti;ii();var vc="2026-11-06T14:30:44.258Z",wc="0.1.4";var Be=class{async recognizeImageText(t,e={}){throw new Error("OcrPort.recognizeImageText() must be implemented by adapter")}async recognizeDocumentPages(t,e={}){throw new Error("OcrPort.recognizeDocumentPages() must be implemented by adapter")}async getOcrWorker(t="eng",e=null){throw new Error("OcrPort.getOcrWorker() must be implemented by adapter")}async terminateOcrWorker(){throw new Error("OcrPort.terminateOcrWorker() must be implemented by adapter")}};var de=class extends Be{async recognizeImageText(t,e={}){let i=new Error('Feature "ocr" is disabled or OCR module not opted in');throw i.code="FEATURE_DISABLED",i}async recognizeDocumentPages(t,e={}){let i=new Error('Feature "ocr" is disabled or OCR module not opted in');throw i.code="FEATURE_DISABLED",i}async getOcrWorker(){return null}async terminateOcrWorker(){}};var Ue=class{async exportDocumentAsPdf(t,e,i={}){throw new Error("PdfPort.exportDocumentAsPdf() must be implemented by adapter")}async renderPdfPagesToDataUrls(t){throw new Error("PdfPort.renderPdfPagesToDataUrls() must be implemented by adapter")}};var Ee=class extends Ue{async exportDocumentAsPdf(t,e,i={}){let r=new Error('Feature "pdf" is disabled or PDF module not opted in');throw r.code="FEATURE_DISABLED",r}async renderPdfPagesToDataUrls(t){return[]}};var _e=class{async renderEdits(t,e){throw new Error("ImageProcessorPort.renderEdits() must be implemented by adapter")}async crop(t,e){throw new Error("ImageProcessorPort.crop() must be implemented by adapter")}async rotate(t,e){throw new Error("ImageProcessorPort.rotate() must be implemented by adapter")}async applyFilter(t,e){throw new Error("ImageProcessorPort.applyFilter() must be implemented by adapter")}};function lh(n){return new Promise((t,e)=>{let i=new Image;i.onload=()=>t(i),i.onerror=e,i.src=n})}var $e=class extends _e{async renderEdits(t,e={}){if(!t)return"";if(typeof document>"u")return t;try{let i=await lh(t),r={...e};return e?.crop&&"w"in e.crop&&(r.crop={x:Math.round((e.crop.x||0)*i.naturalWidth),y:Math.round((e.crop.y||0)*i.naturalHeight),width:Math.round((e.crop.w||1)*i.naturalWidth),height:Math.round((e.crop.h||1)*i.naturalHeight)}),e?.rotate!==void 0&&(r.rotation=e.rotate),tr(i,r).toDataURL("image/jpeg",.92)}catch{return t}}async crop(t,e){return this.renderEdits(t,{crop:e})}async rotate(t,e){return this.renderEdits(t,{rotate:e})}async applyFilter(t,e){return this.renderEdits(t,{filter:e})}};var Li=class extends _e{async renderEdits(t,e){return t}async crop(t,e){return t}async rotate(t,e){return t}async applyFilter(t,e){return t}};function us(n={}){let t=n&&n.crop&&typeof n.crop=="object"?{x:Math.max(0,Math.min(1,Number(n.crop.x)||0)),y:Math.max(0,Math.min(1,Number(n.crop.y)||0)),w:Math.max(0,Math.min(1,Number(n.crop.w)||1)),h:Math.max(0,Math.min(1,Number(n.crop.h)||1))}:null,e=0,i=n?.rotate!==void 0?n.rotate:n?.rotation;if(i!==void 0){let o=(Math.round(Number(i)/90)*90%360+360)%360;(o===90||o===180||o===270)&&(e=o)}let r=n&&n.filter==="bw"?"bw":"none";return{crop:t,rotate:e,filter:r}}function cr(n){if(!n)return!1;let t=n.rotate!==void 0?n.rotate:n.rotation;return!!(n.crop||t&&t!==0||n.filter&&n.filter!=="none")}var Zt=n=>Math.round(n*1e6)/1e6;function wa(n,t=0){if(!n)return null;let e=(Math.round(Number(t)/90)*90%360+360)%360,{x:i,y:r,w:o,h:g}=n;return e===90?{x:Zt(Math.max(0,Math.min(1,1-r-g))),y:Zt(Math.max(0,Math.min(1,i))),w:Zt(Math.max(.01,Math.min(1,g))),h:Zt(Math.max(.01,Math.min(1,o)))}:e===180?{x:Zt(Math.max(0,Math.min(1,1-i-o))),y:Zt(Math.max(0,Math.min(1,1-r-g))),w:Zt(Math.max(.01,Math.min(1,o))),h:Zt(Math.max(.01,Math.min(1,g)))}:e===270?{x:Zt(Math.max(0,Math.min(1,r))),y:Zt(Math.max(0,Math.min(1,1-i-o))),w:Zt(Math.max(.01,Math.min(1,g))),h:Zt(Math.max(.01,Math.min(1,o)))}:{x:Zt(Math.max(0,Math.min(1,i))),y:Zt(Math.max(0,Math.min(1,r))),w:Zt(Math.max(.01,Math.min(1,o))),h:Zt(Math.max(.01,Math.min(1,g)))}}function xa(n,t=0){return wa(n,t)}function Aa(n,t=0){return wa(n,-t)}var Fi=class{constructor(t){this.id=t.id,this.src=t.src,this.originalSrc=t.originalSrc||t.src,this.edits=us(t.edits),this.name=t.name||"Page",this.type=t.type||"image",this.orientation=t.orientation||1,this.ocrText=t.ocrText||null,this.ocrConfidence=t.ocrConfidence??null,this.ocrWords=Array.isArray(t.ocrWords)?t.ocrWords:null,this.ocrWidth=typeof t.ocrWidth=="number"?t.ocrWidth:null,this.ocrHeight=typeof t.ocrHeight=="number"?t.ocrHeight:null}get isModified(){return cr(this.edits)}toJSON(){return{id:this.id,src:this.src,originalSrc:this.originalSrc,edits:this.edits,name:this.name,type:this.type,orientation:this.orientation,ocrText:this.ocrText,ocrConfidence:this.ocrConfidence,ocrWords:this.ocrWords,ocrWidth:this.ocrWidth,ocrHeight:this.ocrHeight}}},Us=class{constructor(t){this.id=t.id,this.name=t.name||"Untitled Document",this.pages=Array.isArray(t.pages)?t.pages.map(e=>e instanceof Fi?e:new Fi(e)):[],this.createdAt=t.createdAt||Date.now(),this.updatedAt=t.updatedAt||Date.now()}get pageCount(){return this.pages.length}toJSON(){return{id:this.id,name:this.name,pages:this.pages.map(t=>t.toJSON()),createdAt:this.createdAt,updatedAt:this.updatedAt}}},$s=class{constructor(t={}){this.mode=t.mode==="single"?"single":"batch",this.aspect=t.aspect||"auto",this.docId=t.docId||null,this.maxPages=Math.max(0,Number(t.maxPages)||0),this.stage="viewfinder",this.activePageIndex=0,this.history=[],this.future=[]}pushHistory(t){this.history.push(t),this.future=[],this.history.length>50&&this.history.shift()}undo(){if(this.history.length===0)return null;let t=this.history.pop();return this.future.push(t),t}redo(){if(this.future.length===0)return null;let t=this.future.pop();return this.history.push(t),t}};var Vt={PAGE_ADDED:"copio:page-added",PAGE_REMOVED:"copio:page-removed",PAGES_CHANGED:"copio:pages-changed",SCAN_COMPLETE:"copio:scan-complete",EXPORT_PROGRESS:"copio:export-progress",EXPORT_COMPLETE:"copio:export-complete",OCR_COMPLETE:"copio:ocr-complete",SYNC_CONNECTED:"copio:sync-connected",ERROR:"copio:error"};function lr(n,t,e={}){let i=new CustomEvent(t,{bubbles:!0,composed:!0,cancelable:!0,detail:e});return n&&typeof n.dispatchEvent=="function"&&n.dispatchEvent(i),i}var _a=["crop","rotate","filter","ocr","export","sync"],Sa=["pdf","zip","png","jpg"],Ea=["eng"],Ca={};function ni(n,t){!n||!t||(Ca[n]=t,typeof globalThis<"u"&&(globalThis.__copio_services__=globalThis.__copio_services__||{},globalThis.__copio_services__[n]=t))}function si(n){return Ca[n]?Ca[n]:typeof globalThis<"u"&&globalThis.__copio_services__?.[n]?globalThis.__copio_services__[n]:null}function hh(n){return n?n instanceof Set?new Set(n):Array.isArray(n)?new Set(n.map(t=>String(t).trim().toLowerCase()).filter(Boolean)):typeof n=="string"?new Set(n.split(/[\s,]+/).map(t=>t.trim().toLowerCase()).filter(Boolean)):new Set(_a):new Set(_a)}function hr(n,t){return n?Array.isArray(n)?n.map(e=>String(e).trim().toLowerCase()).filter(Boolean):typeof n=="string"?n.split(/[\s,]+/).map(e=>e.trim().toLowerCase()).filter(Boolean):[...t]:[...t]}var Oi=class{#t=new Set(_a);#e=[...Sa];#i=[...Ea];#n=0;#r="";#s=null;#o=null;#c={};#a=!0;#h=!0;#u=null;#d=new Map;#l=new Map;constructor(t={}){this.#s=t.storage||ns(t),this.#o=t.repository||new ti(this.#s),t.services&&(this.#c={...t.services}),t.imageProcessor?(this.#u=t.imageProcessor,this.#c.imageProcessor=t.imageProcessor):this.getService("imageProcessor")?this.#u=this.getService("imageProcessor"):typeof document<"u"?this.#u=new $e:this.#u=new Li,t.features!==void 0&&this.setFeatures(t.features),t.exportFormats!==void 0&&(this.#e=hr(t.exportFormats,Sa)),t.ocrLanguages!==void 0&&(this.#i=hr(t.ocrLanguages,Ea)),t.maxPages!==void 0&&(this.#n=Math.max(0,Number(t.maxPages)||0)),t.assetBase!==void 0&&Ii(t.assetBase),t.licenseKey!==void 0&&(this.#r=String(t.licenseKey||"")),t.ocr!==void 0?this.ocr=!!t.ocr:t.features!==void 0&&!this.hasFeature("ocr")&&(this.ocr=!1),t.pdf!==void 0?this.pdf=!!t.pdf:t.exportFormats!==void 0&&!this.#e.includes("pdf")&&(this.pdf=!1)}async init(){return this.#s.init()}setService(t,e){this.#c[t]=e}getService(t){return this.#c[t]||si(t)}hasFeature(t){return t?this.#t.has(String(t).trim().toLowerCase()):!1}get features(){return Array.from(this.#t)}setFeatures(t){this.#t=hh(t),this.hasFeature("ocr")?(this.#a=!0,this.getService("ocr")instanceof de&&this.setService("ocr",si("ocr"))):(this.#a=!1,this.setService("ocr",new de))}enableFeature(t){if(t){let e=String(t).trim().toLowerCase();this.#t.add(e),e==="ocr"&&(this.#a=!0,this.getService("ocr")instanceof de&&this.setService("ocr",si("ocr")))}}disableFeature(t){if(t){let e=String(t).trim().toLowerCase();this.#t.delete(e),e==="ocr"&&(this.#a=!1,this.setService("ocr",new de))}}get ocr(){return this.#a&&this.hasFeature("ocr")}set ocr(t){this.#a=!!t,this.#a?(this.enableFeature("ocr"),this.getService("ocr")instanceof de&&this.setService("ocr",si("ocr"))):(this.disableFeature("ocr"),this.setService("ocr",new de))}get pdf(){return this.#h&&this.#e.includes("pdf")}set pdf(t){this.#h=!!t,this.#h?(this.#e.includes("pdf")||this.#e.push("pdf"),this.getService("pdf")instanceof Ee&&this.setService("pdf",si("pdf"))):(this.#e=this.#e.filter(e=>e!=="pdf"),this.setService("pdf",new Ee))}get exportFormats(){return[...this.#e]}set exportFormats(t){this.#e=hr(t,Sa),this.#e.includes("pdf")?(this.#h=!0,this.getService("pdf")instanceof Ee&&this.setService("pdf",si("pdf"))):(this.#h=!1,this.setService("pdf",new Ee))}get ocrLanguages(){return[...this.#i]}set ocrLanguages(t){this.#i=hr(t,Ea)}get maxPages(){return this.#n}set maxPages(t){this.#n=Math.max(0,Number(t)||0)}get assetBase(){return ir()}set assetBase(t){Ii(t)}get licenseKey(){return this.#r}set licenseKey(t){this.#r=String(t||"")}get storage(){return this.#s}setStorage(t){t&&(this.#s=t,this.#o=new ti(this.#s))}#f(t,e){this.#d.has(t)||this.#d.set(t,[]);let i=this.#d.get(t);i.push(e),i.length>50&&i.shift(),this.#l.has(t)&&(this.#l.get(t).length=0)}get imageProcessor(){return this.#u}setImageProcessor(t){t&&(this.#u=t,this.setService("imageProcessor",t))}async renderEdits(t,e){if(!t)return"";let i=us(e);return this.#u?this.#u.renderEdits(t,i):bc(t,i)}get docs(){return this.#o}async listDocuments(){return this.#o.listDocs()}async getDocument(t){return this.#o.getDoc(t)}async createDocument(t,e){return this.#o.createDoc(t,e)}async deleteDocument(t,e={}){return this.#o.deleteDoc(t,e)}async undoDeleteDocument(t){return this.#o.undoDeleteDoc(t)}async renameDocument(t,e){return this.#o.renameDoc(t,e)}async addPages(t,e){return this.#o.addPages(t,e)}async deletePage(t,e,i={}){return this.#f(t,{type:"delete",pageId:e}),this.#o.deletePage(t,e,i)}async undoDeletePage(t,e){return this.#o.undoDeletePage(t,e)}async updatePage(t,e,i){return this.#o.updatePage(t,e,i)}async reorderPages(t,e){let i=await this.getDocument(t),r=i?.pages?i.pages.map(o=>o.id):[];return this.#f(t,{type:"reorder",priorOrder:r,newOrder:[...e]}),this.#o.reorderPages(t,e)}async#g(t){if(t)return t;let e=await this.listDocuments();return e.length>0?e[0].id:null}async applyEdit(t,e,i){let r=await this.#g(t),o=r?await this.getDocument(r):null;if(!o||!o.pages)throw new Error(`Document with ID "${r||t}" not found`);let g=o.pages.find(p=>p.id===e);if(!g)throw new Error(`Page with ID "${e}" not found in document "${r}"`);let d={...g.edits||{crop:null,rotate:0,filter:"none"}},m=g.src,v=us({...d,...i}),u=g.originalSrc||g.src,a=u;return this.#u&&(a=await this.#u.renderEdits(u,v)),await this.updatePage(r,e,{originalSrc:u,src:a,edits:v}),this.#f(r,{type:"edit",pageId:e,priorEdits:d,priorSrc:m,newEdits:v,newSrc:a}),{...g,originalSrc:u,src:a,edits:v}}async undo(t){let e=await this.#g(t),i=e?this.#d.get(e):null;if(!i||i.length===0)return null;let r=i.pop();return this.#l.has(e)||this.#l.set(e,[]),this.#l.get(e).push(r),r.type==="edit"?(await this.updatePage(e,r.pageId,{edits:r.priorEdits,src:r.priorSrc}),{type:"edit",pageId:r.pageId,restoredEdits:r.priorEdits}):r.type==="delete"?(await this.undoDeletePage(e,r.pageId),{type:"delete",pageId:r.pageId}):r.type==="reorder"?(await this.#o.reorderPages(e,r.priorOrder),{type:"reorder",priorOrder:r.priorOrder}):r}async redo(t){let e=await this.#g(t),i=e?this.#l.get(e):null;if(!i||i.length===0)return null;let r=i.pop();return this.#d.has(e)||this.#d.set(e,[]),this.#d.get(e).push(r),r.type==="edit"?(await this.updatePage(e,r.pageId,{edits:r.newEdits,src:r.newSrc}),{type:"edit",pageId:r.pageId,appliedEdits:r.newEdits}):r.type==="delete"?(await this.deletePage(e,r.pageId),{type:"delete",pageId:r.pageId}):r.type==="reorder"?(await this.reorderPages(e,r.newOrder),{type:"reorder",newOrder:r.newOrder}):r}subscribe(t){return this.#o.subscribe(t)}async addFiles(t,e=null){if(!t||t.length===0)return[];let i=Array.from(t),r=[];for(let g of i)if(g.type==="application/pdf"){let d=this.getService("pdf");if(d&&typeof d.renderPdfPagesToDataUrls=="function"){let m=await d.renderPdfPagesToDataUrls(g);for(let v of m)r.push({id:Di(),src:v,originalSrc:v,edits:{crop:null,rotation:0,filter:"none"},type:"image",name:g.name||"PDF Page"})}else console.warn("PDF import service (PdfPort) not registered. Skipping PDF file.")}else if(g.type&&g.type.startsWith("image/")){let d=await Qn(g),m=null;try{m=await Jn(g)}catch{}r.push({id:Di(),src:d,originalSrc:d,edits:{crop:null,rotation:0,filter:"none"},type:"image",name:g.name||"Captured Image",orientation:m})}if(r.length===0)return[];await this.init();let o=e;if(o)await this.getDocument(o)||await this.#o.saveDoc(o,{name:"Scanned Document",pages:[]});else{let g=await this.listDocuments();g.length>0?o=g[0].id:o=(await this.createDocument("Scanned Document",[])).id}if(this.#n>0){let g=(await this.getDocument(o))?.pages||[],d=Math.max(0,this.#n-g.length);if(d<=0)throw new Error(`Maximum page limit (${this.#n}) reached`);r.splice(d)}return await this.addPages(o,r),r}async getPages(t=null){let e=t;if(!e){let r=await this.listDocuments();if(r.length===0)return[];e=r[0].id}return(await this.getDocument(e))?.pages||[]}async clear(t=null){let e=t;if(!e){let r=await this.listDocuments();if(r.length===0)return;e=r[0].id}let i=await this.getDocument(e);if(!(!i||!i.pages))for(let r of i.pages)await this.deletePage(e,r.id)}async#p(t){if(Array.isArray(t))return{docName:"document",pages:t,docId:null};if(typeof t=="string"){let i=await this.getDocument(t);return{docName:i?.name||"document",pages:i?.pages||[],docId:t}}let e=await this.listDocuments();if(e.length>0){let i=await this.getDocument(e[0].id);return{docName:i?.name||"document",pages:i?.pages||[],docId:e[0].id}}return{docName:"document",pages:[],docId:null}}async exportPdf(t,e={}){if(!this.hasFeature("export")){let g=new Error('Feature "export" is disabled');throw Object.assign(g,{code:"FEATURE_DISABLED"}),g}if(!this.#h||!this.#e.includes("pdf")){let g=new Error('Feature "pdf" is disabled');throw Object.assign(g,{code:"FEATURE_DISABLED"}),g}let{docName:i,pages:r}=await this.#p(t),o=this.getService("pdf")||this.getService("export");if(!o||typeof o.exportDocumentAsPdf!="function")throw new Error("Export service (PdfPort) is not registered. Import @copio/sdk or register an exportService.");return o.exportDocumentAsPdf(i,r,{download:!1,showProgress:!1,onOcrComplete:async()=>{if(typeof t=="string"){let g=await this.#s.getDoc(t);g&&(g.pages=r,await this.#s.saveDoc(t,g))}},...e})}async exportZip(t,e={}){if(!this.hasFeature("export")){let g=new Error('Feature "export" is disabled');throw Object.assign(g,{code:"FEATURE_DISABLED"}),g}let{docName:i,pages:r}=await this.#p(t),o=this.getService("export");if(!o||typeof o.exportDocumentAsImages!="function")throw new Error("Export service is not registered. Import @copio/sdk or register an exportService.");return o.exportDocumentAsImages(i,r,{download:!1,showProgress:!1,...e})}async runOcr(t,e=null,i={}){if(!this.#a||!this.hasFeature("ocr")){let v=new Error('Feature "ocr" is disabled');throw Object.assign(v,{code:"FEATURE_DISABLED"}),v}let{pages:r}=await this.#p(t),o=r;e&&(o=r.filter(v=>v.id===e));let g=this.getService("ocr");if(!g||typeof g.recognizeDocumentPages!="function")throw new Error("OCR service (OcrPort) is not registered. Import @copio/sdk or register an ocrService.");let d=i.lang||this.#i[0]||"eng",m=await g.recognizeDocumentPages(o,{lang:d,...i});if(Array.isArray(m.pagesResults)){for(let v of m.pagesResults){let u=o.find(a=>a.id===v.pageId)||o[v.pageIndex];u&&(u.ocrText=v.text,u.ocrConfidence=v.confidence,u.ocrWords=v.words)}if(typeof t=="string"){let v=await this.#s.getDoc(t);if(v&&Array.isArray(v.pages)){for(let u of m.pagesResults){let a=v.pages.find(p=>p.id===u.pageId)||v.pages[u.pageIndex];a&&(a.ocrText=u.text,a.ocrConfidence=u.confidence,a.ocrWords=u.words)}await this.#s.saveDoc(t,v)}}}return{text:m.combinedText,...m}}async sync(t={}){if(!this.hasFeature("sync")){let i=new Error('Feature "sync" is disabled');throw Object.assign(i,{code:"FEATURE_DISABLED"}),i}let e=this.getService("sync");if(!e)throw new Error("Sync service (SyncPort) is not registered. Import @copio/sdk or register a syncService.");return new e(this.#o,t.onStateChange)}};ii();Ni();var js=`
|
|
9
|
+
Please create an issue at https://github.com/MikeKovarik/exifr with this file`),[this.file.getUintBytes(i+d,r),this.file.getUintBytes(i+d+r,o)];i+=T*u}}},Xn=class extends qn{};kt(Xn,"type","heic");var Kn=class extends qn{};kt(Kn,"type","avif"),Ri.set("heic",Xn),Ri.set("avif",Kn),ge(Le,["ifd0","ifd1"],[[256,"ImageWidth"],[257,"ImageHeight"],[258,"BitsPerSample"],[259,"Compression"],[262,"PhotometricInterpretation"],[270,"ImageDescription"],[271,"Make"],[272,"Model"],[273,"StripOffsets"],[274,"Orientation"],[277,"SamplesPerPixel"],[278,"RowsPerStrip"],[279,"StripByteCounts"],[282,"XResolution"],[283,"YResolution"],[284,"PlanarConfiguration"],[296,"ResolutionUnit"],[301,"TransferFunction"],[305,"Software"],[306,"ModifyDate"],[315,"Artist"],[316,"HostComputer"],[317,"Predictor"],[318,"WhitePoint"],[319,"PrimaryChromaticities"],[513,"ThumbnailOffset"],[514,"ThumbnailLength"],[529,"YCbCrCoefficients"],[530,"YCbCrSubSampling"],[531,"YCbCrPositioning"],[532,"ReferenceBlackWhite"],[700,"ApplicationNotes"],[33432,"Copyright"],[33723,"IPTC"],[34665,"ExifIFD"],[34675,"ICC"],[34853,"GpsIFD"],[330,"SubIFD"],[40965,"InteropIFD"],[40091,"XPTitle"],[40092,"XPComment"],[40093,"XPAuthor"],[40094,"XPKeywords"],[40095,"XPSubject"]]),ge(Le,"exif",[[33434,"ExposureTime"],[33437,"FNumber"],[34850,"ExposureProgram"],[34852,"SpectralSensitivity"],[34855,"ISO"],[34858,"TimeZoneOffset"],[34859,"SelfTimerMode"],[34864,"SensitivityType"],[34865,"StandardOutputSensitivity"],[34866,"RecommendedExposureIndex"],[34867,"ISOSpeed"],[34868,"ISOSpeedLatitudeyyy"],[34869,"ISOSpeedLatitudezzz"],[36864,"ExifVersion"],[36867,"DateTimeOriginal"],[36868,"CreateDate"],[36873,"GooglePlusUploadCode"],[36880,"OffsetTime"],[36881,"OffsetTimeOriginal"],[36882,"OffsetTimeDigitized"],[37121,"ComponentsConfiguration"],[37122,"CompressedBitsPerPixel"],[37377,"ShutterSpeedValue"],[37378,"ApertureValue"],[37379,"BrightnessValue"],[37380,"ExposureCompensation"],[37381,"MaxApertureValue"],[37382,"SubjectDistance"],[37383,"MeteringMode"],[37384,"LightSource"],[37385,"Flash"],[37386,"FocalLength"],[37393,"ImageNumber"],[37394,"SecurityClassification"],[37395,"ImageHistory"],[37396,"SubjectArea"],[37500,"MakerNote"],[37510,"UserComment"],[37520,"SubSecTime"],[37521,"SubSecTimeOriginal"],[37522,"SubSecTimeDigitized"],[37888,"AmbientTemperature"],[37889,"Humidity"],[37890,"Pressure"],[37891,"WaterDepth"],[37892,"Acceleration"],[37893,"CameraElevationAngle"],[40960,"FlashpixVersion"],[40961,"ColorSpace"],[40962,"ExifImageWidth"],[40963,"ExifImageHeight"],[40964,"RelatedSoundFile"],[41483,"FlashEnergy"],[41486,"FocalPlaneXResolution"],[41487,"FocalPlaneYResolution"],[41488,"FocalPlaneResolutionUnit"],[41492,"SubjectLocation"],[41493,"ExposureIndex"],[41495,"SensingMethod"],[41728,"FileSource"],[41729,"SceneType"],[41730,"CFAPattern"],[41985,"CustomRendered"],[41986,"ExposureMode"],[41987,"WhiteBalance"],[41988,"DigitalZoomRatio"],[41989,"FocalLengthIn35mmFormat"],[41990,"SceneCaptureType"],[41991,"GainControl"],[41992,"Contrast"],[41993,"Saturation"],[41994,"Sharpness"],[41996,"SubjectDistanceRange"],[42016,"ImageUniqueID"],[42032,"OwnerName"],[42033,"SerialNumber"],[42034,"LensInfo"],[42035,"LensMake"],[42036,"LensModel"],[42037,"LensSerialNumber"],[42080,"CompositeImage"],[42081,"CompositeImageCount"],[42082,"CompositeImageExposureTimes"],[42240,"Gamma"],[59932,"Padding"],[59933,"OffsetSchema"],[65e3,"OwnerName"],[65001,"SerialNumber"],[65002,"Lens"],[65100,"RawFile"],[65101,"Converter"],[65102,"WhiteBalance"],[65105,"Exposure"],[65106,"Shadows"],[65107,"Brightness"],[65108,"Contrast"],[65109,"Saturation"],[65110,"Sharpness"],[65111,"Smoothness"],[65112,"MoireFilter"],[40965,"InteropIFD"]]),ge(Le,"gps",[[0,"GPSVersionID"],[1,"GPSLatitudeRef"],[2,"GPSLatitude"],[3,"GPSLongitudeRef"],[4,"GPSLongitude"],[5,"GPSAltitudeRef"],[6,"GPSAltitude"],[7,"GPSTimeStamp"],[8,"GPSSatellites"],[9,"GPSStatus"],[10,"GPSMeasureMode"],[11,"GPSDOP"],[12,"GPSSpeedRef"],[13,"GPSSpeed"],[14,"GPSTrackRef"],[15,"GPSTrack"],[16,"GPSImgDirectionRef"],[17,"GPSImgDirection"],[18,"GPSMapDatum"],[19,"GPSDestLatitudeRef"],[20,"GPSDestLatitude"],[21,"GPSDestLongitudeRef"],[22,"GPSDestLongitude"],[23,"GPSDestBearingRef"],[24,"GPSDestBearing"],[25,"GPSDestDistanceRef"],[26,"GPSDestDistance"],[27,"GPSProcessingMethod"],[28,"GPSAreaInformation"],[29,"GPSDateStamp"],[30,"GPSDifferential"],[31,"GPSHPositioningError"]]),ge(hs,["ifd0","ifd1"],[[274,{1:"Horizontal (normal)",2:"Mirror horizontal",3:"Rotate 180",4:"Mirror vertical",5:"Mirror horizontal and rotate 270 CW",6:"Rotate 90 CW",7:"Mirror horizontal and rotate 90 CW",8:"Rotate 270 CW"}],[296,{1:"None",2:"inches",3:"cm"}]]);var Is=ge(hs,"exif",[[34850,{0:"Not defined",1:"Manual",2:"Normal program",3:"Aperture priority",4:"Shutter priority",5:"Creative program",6:"Action program",7:"Portrait mode",8:"Landscape mode"}],[37121,{0:"-",1:"Y",2:"Cb",3:"Cr",4:"R",5:"G",6:"B"}],[37383,{0:"Unknown",1:"Average",2:"CenterWeightedAverage",3:"Spot",4:"MultiSpot",5:"Pattern",6:"Partial",255:"Other"}],[37384,{0:"Unknown",1:"Daylight",2:"Fluorescent",3:"Tungsten (incandescent light)",4:"Flash",9:"Fine weather",10:"Cloudy weather",11:"Shade",12:"Daylight fluorescent (D 5700 - 7100K)",13:"Day white fluorescent (N 4600 - 5400K)",14:"Cool white fluorescent (W 3900 - 4500K)",15:"White fluorescent (WW 3200 - 3700K)",17:"Standard light A",18:"Standard light B",19:"Standard light C",20:"D55",21:"D65",22:"D75",23:"D50",24:"ISO studio tungsten",255:"Other"}],[37385,{0:"Flash did not fire",1:"Flash fired",5:"Strobe return light not detected",7:"Strobe return light detected",9:"Flash fired, compulsory flash mode",13:"Flash fired, compulsory flash mode, return light not detected",15:"Flash fired, compulsory flash mode, return light detected",16:"Flash did not fire, compulsory flash mode",24:"Flash did not fire, auto mode",25:"Flash fired, auto mode",29:"Flash fired, auto mode, return light not detected",31:"Flash fired, auto mode, return light detected",32:"No flash function",65:"Flash fired, red-eye reduction mode",69:"Flash fired, red-eye reduction mode, return light not detected",71:"Flash fired, red-eye reduction mode, return light detected",73:"Flash fired, compulsory flash mode, red-eye reduction mode",77:"Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected",79:"Flash fired, compulsory flash mode, red-eye reduction mode, return light detected",89:"Flash fired, auto mode, red-eye reduction mode",93:"Flash fired, auto mode, return light not detected, red-eye reduction mode",95:"Flash fired, auto mode, return light detected, red-eye reduction mode"}],[41495,{1:"Not defined",2:"One-chip color area sensor",3:"Two-chip color area sensor",4:"Three-chip color area sensor",5:"Color sequential area sensor",7:"Trilinear sensor",8:"Color sequential linear sensor"}],[41728,{1:"Film Scanner",2:"Reflection Print Scanner",3:"Digital Camera"}],[41729,{1:"Directly photographed"}],[41985,{0:"Normal",1:"Custom",2:"HDR (no original saved)",3:"HDR (original saved)",4:"Original (for HDR)",6:"Panorama",7:"Portrait HDR",8:"Portrait"}],[41986,{0:"Auto",1:"Manual",2:"Auto bracket"}],[41987,{0:"Auto",1:"Manual"}],[41990,{0:"Standard",1:"Landscape",2:"Portrait",3:"Night",4:"Other"}],[41991,{0:"None",1:"Low gain up",2:"High gain up",3:"Low gain down",4:"High gain down"}],[41996,{0:"Unknown",1:"Macro",2:"Close",3:"Distant"}],[42080,{0:"Unknown",1:"Not a Composite Image",2:"General Composite Image",3:"Composite Image Captured While Shooting"}]]),Zo={1:"No absolute unit of measurement",2:"Inch",3:"Centimeter"};Is.set(37392,Zo),Is.set(41488,Zo);var Jr={0:"Normal",1:"Low",2:"High"};function tc(n){return typeof n=="object"&&n.length!==void 0?n[0]:n}function ec(n){let t=Array.from(n).slice(1);return t[1]>15&&(t=t.map((e=>String.fromCharCode(e)))),t[2]!=="0"&&t[2]!==0||t.pop(),t.join(".")}function Qr(n){if(typeof n=="string"){var[t,e,i,r,o,g]=n.trim().split(/[-: ]/g).map(Number),d=new Date(t,e-1,i);return Number.isNaN(r)||Number.isNaN(o)||Number.isNaN(g)||(d.setHours(r),d.setMinutes(o),d.setSeconds(g)),Number.isNaN(+d)?n:d}}function Ms(n){if(typeof n=="string")return n;let t=[];if(n[1]===0&&n[n.length-1]===0)for(let e=0;e<n.length;e+=2)t.push(ic(n[e+1],n[e]));else for(let e=0;e<n.length;e+=2)t.push(ic(n[e],n[e+1]));return nc(String.fromCodePoint(...t))}function ic(n,t){return n<<8|t}Is.set(41992,Jr),Is.set(41993,Jr),Is.set(41994,Jr),ge(ki,["ifd0","ifd1"],[[50827,function(n){return typeof n!="string"?rc(n):n}],[306,Qr],[40091,Ms],[40092,Ms],[40093,Ms],[40094,Ms],[40095,Ms]]),ge(ki,"exif",[[40960,ec],[36864,ec],[36867,Qr],[36868,Qr],[40962,tc],[40963,tc]]),ge(ki,"gps",[[0,n=>Array.from(n).join(".")],[7,n=>Array.from(n).join(":")]]);var Ls=class extends Ie{static canHandle(t,e){return t.getUint8(e+1)===225&&t.getUint32(e+4)===1752462448&&t.getString(e+4,20)==="http://ns.adobe.com/"}static headerLength(t,e){return t.getString(e+4,34)==="http://ns.adobe.com/xmp/extension/"?79:33}static findPosition(t,e){let i=super.findPosition(t,e);return i.multiSegment=i.extended=i.headerLength===79,i.multiSegment?(i.chunkCount=t.getUint8(e+72),i.chunkNumber=t.getUint8(e+76),t.getUint8(e+77)!==0&&i.chunkNumber++):(i.chunkCount=1/0,i.chunkNumber=-1),i}static handleMultiSegments(t){return t.map((e=>e.chunk.getString())).join("")}normalizeInput(t){return typeof t=="string"?t:Fe.from(t).getString()}parse(t=this.chunk){if(!this.localOptions.parse)return t;t=(function(o){let g={},d={};for(let m of gc)g[m]=[],d[m]=0;return o.replace(oh,((m,v,u)=>{if(v==="<"){let a=++d[u];return g[u].push(a),`${m}#${a}`}return`${m}#${g[u].pop()}`}))})(t);let e=Yn.findAll(t,"rdf","Description");e.length===0&&e.push(new Yn("rdf","Description",void 0,t));let i,r={};for(let o of e)for(let g of o.properties)i=ah(g.ns,r),uc(g,i);return(function(o){let g;for(let d in o)g=o[d]=Hn(o[d]),g===void 0&&delete o[d];return Hn(o)})(r)}assignToOutput(t,e){if(this.localOptions.parse)for(let[i,r]of Object.entries(e))switch(i){case"tiff":this.assignObjectToOutput(t,"ifd0",r);break;case"exif":this.assignObjectToOutput(t,"exif",r);break;case"xmlns":break;default:this.assignObjectToOutput(t,i,r)}else t.xmp=e}};kt(Ls,"type","xmp"),kt(Ls,"multiSegment",!0),ie.set("xmp",Ls);var ca=class n{static findAll(t){return pc(t,/([a-zA-Z0-9-]+):([a-zA-Z0-9-]+)=("[^"]*"|'[^']*')/gm).map(n.unpackMatch)}static unpackMatch(t){let e=t[1],i=t[2],r=t[3].slice(1,-1);return r=fc(r),new n(e,i,r)}constructor(t,e,i){this.ns=t,this.name=e,this.value=i}serialize(){return this.value}},Yn=class n{static findAll(t,e,i){if(e!==void 0||i!==void 0){e=e||"[\\w\\d-]+",i=i||"[\\w\\d-]+";var r=new RegExp(`<(${e}):(${i})(#\\d+)?((\\s+?[\\w\\d-:]+=("[^"]*"|'[^']*'))*\\s*)(\\/>|>([\\s\\S]*?)<\\/\\1:\\2\\3>)`,"gm")}else r=/<([\w\d-]+):([\w\d-]+)(#\d+)?((\s+?[\w\d-:]+=("[^"]*"|'[^']*'))*\s*)(\/>|>([\s\S]*?)<\/\1:\2\3>)/gm;return pc(t,r).map(n.unpackMatch)}static unpackMatch(t){let e=t[1],i=t[2],r=t[4],o=t[8];return new n(e,i,r,o)}constructor(t,e,i,r){this.ns=t,this.name=e,this.attrString=i,this.innerXml=r,this.attrs=ca.findAll(i),this.children=n.findAll(r),this.value=this.children.length===0?fc(r):void 0,this.properties=[...this.attrs,...this.children]}get isPrimitive(){return this.value!==void 0&&this.attrs.length===0&&this.children.length===0}get isListContainer(){return this.children.length===1&&this.children[0].isList}get isList(){let{ns:t,name:e}=this;return t==="rdf"&&(e==="Seq"||e==="Bag"||e==="Alt")}get isListItem(){return this.ns==="rdf"&&this.name==="li"}serialize(){if(this.properties.length===0&&this.value===void 0)return;if(this.isPrimitive)return this.value;if(this.isListContainer)return this.children[0].serialize();if(this.isList)return rh(this.children.map(nh));if(this.isListItem&&this.children.length===1&&this.attrs.length===0)return this.children[0].serialize();let t={};for(let e of this.properties)uc(e,t);return this.value!==void 0&&(t.value=this.value),Hn(t)}};function uc(n,t){let e=n.serialize();e!==void 0&&(t[n.name]=e)}var nh=n=>n.serialize(),rh=n=>n.length===1?n[0]:n,ah=(n,t)=>t[n]?t[n]:t[n]={};function pc(n,t){let e,i=[];if(!n)return i;for(;(e=t.exec(n))!==null;)i.push(e);return i}function fc(n){if((function(i){return i==null||i==="null"||i==="undefined"||i===""||i.trim()===""})(n))return;let t=Number(n);if(!Number.isNaN(t))return t;let e=n.toLowerCase();return e==="true"||e!=="false"&&n.trim()}var gc=["rdf:li","rdf:Seq","rdf:Bag","rdf:Alt","rdf:Description"],oh=new RegExp(`(<|\\/)(${gc.join("|")})`,"g"),mc=sh;async function Jn(n){try{return await mc.parse(n)||null}catch{return null}}function Di(){return Array.from(crypto.getRandomValues(new Uint8Array(16)),n=>n.toString(16).padStart(2,"0")).join("")}async function Qn(n){if(typeof createImageBitmap>"u"||typeof document>"u"){if(n&&typeof n.arrayBuffer=="function"){let d=await n.arrayBuffer(),m=globalThis.Buffer,v=typeof m<"u"?m.from(d).toString("base64"):btoa(String.fromCharCode(...new Uint8Array(d)));return`data:${n.type||"image/png"};base64,${v}`}if(typeof n=="string")return n}let t=await createImageBitmap(n),r=Math.min(1,1654/t.width,2339/t.height);if(r===1&&(n.type==="image/jpeg"||n.type==="image/jpg"||n.type==="image/png"||n.type==="image/webp"))return t.close(),new Promise((d,m)=>{let v=new FileReader;v.onload=()=>d(v.result),v.onerror=m,v.readAsDataURL(n)});let o=document.createElement("canvas");o.width=Math.round(t.width*r),o.height=Math.round(t.height*r),o.getContext("2d").drawImage(t,0,0,o.width,o.height),t.close();let g=n.type==="image/png"?"image/png":"image/jpeg";return o.toDataURL(g,g==="image/png"?void 0:.82)}function ga(n,t=21,e=.2,i=128){let{data:r,width:o,height:g}=n,d=o+1,m=new Float64Array((o+1)*(g+1)),v=new Float64Array((o+1)*(g+1)),u=new Uint8Array(o*g);for(let p=0;p<g;p++){let x=0,T=0,l=p*o,y=(p+1)*d,s=p*d;for(let c=0;c<o;c++){let f=(l+c)*4,w=r[f]*77+r[f+1]*150+r[f+2]*29>>8;u[l+c]=w,x+=w,T+=w*w,m[y+c+1]=m[s+c+1]+x,v[y+c+1]=v[s+c+1]+T}}let a=Math.floor(t/2);for(let p=0;p<g;p++){let x=Math.max(0,p-a),T=Math.min(g-1,p+a),l=x*d,y=(T+1)*d;for(let s=0;s<o;s++){let c=Math.max(0,s-a),f=Math.min(o-1,s+a),w=(f-c+1)*(T-x+1),R=m[y+f+1]-m[l+f+1]-m[y+c]+m[l+c],S=v[y+f+1]-v[l+f+1]-v[y+c]+v[l+c],D=R/w,N=Math.max(0,S/w-D*D),H=Math.sqrt(N),j=D*(1+e*(H/i-1)),Y=p*o+s,it=u[Y]<j?0:255,ot=Y*4;r[ot]=it,r[ot+1]=it,r[ot+2]=it}}return n}function ma(n,t=21,e=.2,i=128){return new Promise(r=>{let o=new Image;o.onload=()=>{let g=document.createElement("canvas");g.width=o.width,g.height=o.height;let d=g.getContext("2d");d.drawImage(o,0,0);let m=d.getImageData(0,0,g.width,g.height);ga(m,t,e,i),d.putImageData(m,0,0);let v=n.startsWith("data:image/png"),u=v?"image/png":"image/jpeg";r(g.toDataURL(u,v?void 0:.82))},o.src=n})}function ba(n){return new Promise(t=>{let e=new Image;e.onload=()=>{let i=document.createElement("canvas");i.width=e.height,i.height=e.width;let r=i.getContext("2d");r.translate(i.width/2,i.height/2),r.rotate(Math.PI/2),r.drawImage(e,-e.width/2,-e.height/2);let o=n.startsWith("data:image/png"),g=o?"image/png":"image/jpeg";t(i.toDataURL(g,o?void 0:.82))},e.src=n})}function ya(n,t=""){if(!n)return"";let e=n.getCroppedCanvas(),i=t.startsWith("data:image/png"),r=i?"image/png":"image/jpeg";return e.toDataURL(r,i?void 0:.82)}function Zn(n){if(!n||typeof n!="object")return{crop:null,rotation:0,filter:"none"};let t=null;n.crop&&typeof n.crop=="object"&&(n.crop.width>0&&n.crop.height>0?t={x:Math.round(n.crop.x||0),y:Math.round(n.crop.y||0),width:Math.round(n.crop.width),height:Math.round(n.crop.height)}:n.crop.w>0&&n.crop.h>0&&(t={x:Number(n.crop.x)||0,y:Number(n.crop.y)||0,w:Number(n.crop.w)||1,h:Number(n.crop.h)||1}));let e=n.rotation!==void 0?n.rotation:n.rotate,i=(Math.round(Number(e)||0)%360+360)%360,r=n.filter==="bw"?"bw":"none";return{crop:t,rotation:i,filter:r}}function ch(n){if(!n)return!1;let t=Zn(n);return!!(t.crop||t.rotation!==0||t.filter!=="none")}function tr(n,t){let e=Zn(t),i=n.naturalWidth||n.width||0,r=n.naturalHeight||n.height||0,o=document.createElement("canvas"),g=i,d=r,m=0,v=0;if(e.crop){let p=e.crop;"w"in p&&!("width"in p)?(m=Math.max(0,Math.min(Math.round(p.x*i),i)),v=Math.max(0,Math.min(Math.round(p.y*r),r)),g=Math.max(1,Math.min(Math.round(p.w*i),i-m)),d=Math.max(1,Math.min(Math.round(p.h*r),r-v))):(m=Math.max(0,Math.min(p.x,i)),v=Math.max(0,Math.min(p.y,r)),g=Math.max(1,Math.min(p.width,i-m)),d=Math.max(1,Math.min(p.height,r-v)))}o.width=g,o.height=d,o.getContext("2d").drawImage(n,m,v,g,d,0,0,g,d);let a=o;if(e.rotation!==0){let p=e.rotation,x=document.createElement("canvas");p===90||p===270?(x.width=a.height,x.height=a.width):(x.width=a.width,x.height=a.height);let T=x.getContext("2d");T.translate(x.width/2,x.height/2),T.rotate(p*Math.PI/180),T.drawImage(a,-a.width/2,-a.height/2),a=x}if(e.filter==="bw"){let p=a.getContext("2d"),x=p.getImageData(0,0,a.width,a.height);ga(x),p.putImageData(x,0,0)}return a}function bc(n,t){if(!n)return Promise.resolve("");let e=Zn(t);return ch(e)?new Promise((i,r)=>{let o=new Image;o.onload=()=>{try{let g=n.startsWith("data:image/png"),d=g?"image/png":"image/jpeg",m=tr(o,e);i(m.toDataURL(d,g?void 0:.82))}catch(g){r(g)}},o.onerror=r,o.src=n}):Promise.resolve(n)}var ti=class{#t=null;#e=new Map;#i=new Map;constructor(t=ns()){this.#t=t}get adapter(){return this.#t}get store(){return this.#t?.store??null}async init(){return this.#t.init()}listDocsSync(){return typeof this.#t.listDocsSync=="function"?this.#t.listDocsSync().map(e=>{let i=this.#s(e.pages);return{id:e.id,name:e.name||"",pageCount:i.length,pages:i}}):[]}async listDocs(){return(await this.#t.listDocs()).map(e=>{let i=this.#s(e.pages);return{id:e.id,name:e.name||"",pageCount:i.length,pages:i}})}getDocSync(t){if(!t)return null;if(typeof this.#t.getDocSync=="function"){let r=this.#t.getDocSync(t);return r?{id:r.id,name:r.name||"",pages:this.#s(r.pages)}:null}let i=this.listDocsSync().find(r=>r.id===t);return i?{id:i.id,name:i.name,pages:i.pages||[]}:null}async getDoc(t){if(!t)return null;if(typeof this.#t.getDoc=="function"){let e=await this.#t.getDoc(t);return e?{id:e.id,name:e.name||"",pages:this.#s(e.pages)}:null}return this.getDocSync(t)}async createDoc(t="Untitled Document",e=[]){let i=Di(),r=this.#s(e),o={id:i,name:t||"Untitled Document",pages:r};return await this.#t.saveDoc(i,o),o}async saveDoc(t,e){if(!t)throw new Error("Cannot save document without an ID");let i=this.#s(e.pages);await this.#t.saveDoc(t,{id:t,name:e.name||"",pages:i})}async renameDoc(t,e){if(typeof this.#t.renameDoc=="function")return this.#t.renameDoc(t,e);let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);i.name=e,await this.saveDoc(t,i)}async deleteDoc(t,{soft:e=!0,timeoutMs:i=5e3}={}){if(!t)return;let r=this.getDocSync(t);if(r){if(this.#n(t),await this.#t.deleteDoc(t),e&&i>0){let o=setTimeout(async()=>{this.#e.delete(t)},i);this.#e.set(t,{doc:r,timerId:o})}return{id:t,name:r.name,undo:()=>this.undoDeleteDoc(t)}}}#n(t){if(this.#e.has(t)){let e=this.#e.get(t);clearTimeout(e.timerId),this.#e.delete(t)}}async undoDeleteDoc(t){let e=this.#e.get(t);return e?(clearTimeout(e.timerId),this.#e.delete(t),await this.#t.saveDoc(t,e.doc),e.doc):null}isSoftDeletedDoc(t){return this.#e.has(t)}async addPages(t,e){let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);let r=Array.isArray(e)?e:[e];i.pages.push(...r),await this.saveDoc(t,i)}async updatePage(t,e,i){let r=await this.getDoc(t);if(!r)throw new Error(`Document "${t}" not found`);let o=r.pages.findIndex(g=>g.id===e);if(o===-1)throw new Error(`Page "${e}" not found in document "${t}"`);r.pages[o]={...r.pages[o],...i},await this.saveDoc(t,r)}async reorderPages(t,e){let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);let r=new Map(i.pages.map(g=>[g.id,g])),o=[];for(let g of e)r.has(g)&&(o.push(r.get(g)),r.delete(g));for(let g of r.values())o.push(g);i.pages=o,await this.saveDoc(t,i)}async deletePage(t,e,{soft:i=!0,timeoutMs:r=5e3}={}){let o=await this.getDoc(t);if(!o)throw new Error(`Document "${t}" not found`);let g=o.pages.findIndex(u=>u.id===e);if(g===-1)return;let[d]=o.pages.splice(g,1);await this.saveDoc(t,o);let m=`${t}:${e}`;if(this.#r(m),!i||r<=0){if(typeof this.#t.deletePage=="function")try{await this.#t.deletePage(t,e)}catch(u){console.warn("[DocRepository] Adapter deletePage error:",u)}return}let v=setTimeout(async()=>{if(this.#i.delete(m),typeof this.#t.deletePage=="function")try{await this.#t.deletePage(t,e)}catch(u){console.warn("[DocRepository] Adapter deletePage error:",u)}},r);return this.#i.set(m,{docId:t,pageId:e,page:d,index:g,timerId:v}),{docId:t,pageId:e,undo:()=>this.undoDeletePage(t,e)}}#r(t){if(this.#i.has(t)){let e=this.#i.get(t);clearTimeout(e.timerId),this.#i.delete(t)}}async undoDeletePage(t,e){let i=`${t}:${e}`,r=this.#i.get(i);if(!r)return null;clearTimeout(r.timerId),this.#i.delete(i);let o=await this.getDoc(t);if(!o)return null;let g=Math.min(r.index,o.pages.length);return o.pages.splice(g,0,r.page),await this.saveDoc(t,o),r.page}isSoftDeletedPage(t,e){return this.#i.has(`${t}:${e}`)}subscribe(t){return this.#t.subscribe(t)}async getAllDocs(){let t=await this.listDocs(),e={};for(let i of t)e[i.id]=i;return e}async exportAll(){let t=await this.listDocs(),e={};for(let i of t){let r=await this.getDoc(i.id),o=[];for(let g of r?.pages||[]){if(!g){o.push(g);continue}let d={...g},m=d.blob instanceof Blob?d.blob:null;if(!m&&typeof d.src=="string"&&d.src.startsWith("blob:"))try{m=await(await fetch(d.src)).blob()}catch{}m&&(d.src=await Kr(m));let v=d.originalBlob instanceof Blob?d.originalBlob:null;if(!v&&typeof d.originalSrc=="string"&&d.originalSrc.startsWith("blob:"))try{v=await(await fetch(d.originalSrc)).blob()}catch{}v&&(d.originalSrc=await Kr(v)),delete d.blob,delete d.originalBlob,o.push(d)}e[i.id]={name:i.name,pages:JSON.stringify(o)}}return e}async importDocs(t){let e=0;for(let[i,r]of Object.entries(t||{})){await this.getDoc(i)||e++;let g=this.#s(r.pages);await this.saveDoc(i,{name:r.name||"",pages:g})}return e}#s(t){if(Array.isArray(t))return[...t];if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}},ds=new ti;ii();var vc="2026-11-06T14:33:27.433Z",wc="0.1.5";var Be=class{async recognizeImageText(t,e={}){throw new Error("OcrPort.recognizeImageText() must be implemented by adapter")}async recognizeDocumentPages(t,e={}){throw new Error("OcrPort.recognizeDocumentPages() must be implemented by adapter")}async getOcrWorker(t="eng",e=null){throw new Error("OcrPort.getOcrWorker() must be implemented by adapter")}async terminateOcrWorker(){throw new Error("OcrPort.terminateOcrWorker() must be implemented by adapter")}};var de=class extends Be{async recognizeImageText(t,e={}){let i=new Error('Feature "ocr" is disabled or OCR module not opted in');throw i.code="FEATURE_DISABLED",i}async recognizeDocumentPages(t,e={}){let i=new Error('Feature "ocr" is disabled or OCR module not opted in');throw i.code="FEATURE_DISABLED",i}async getOcrWorker(){return null}async terminateOcrWorker(){}};var Ue=class{async exportDocumentAsPdf(t,e,i={}){throw new Error("PdfPort.exportDocumentAsPdf() must be implemented by adapter")}async renderPdfPagesToDataUrls(t){throw new Error("PdfPort.renderPdfPagesToDataUrls() must be implemented by adapter")}};var Ee=class extends Ue{async exportDocumentAsPdf(t,e,i={}){let r=new Error('Feature "pdf" is disabled or PDF module not opted in');throw r.code="FEATURE_DISABLED",r}async renderPdfPagesToDataUrls(t){return[]}};var _e=class{async renderEdits(t,e){throw new Error("ImageProcessorPort.renderEdits() must be implemented by adapter")}async crop(t,e){throw new Error("ImageProcessorPort.crop() must be implemented by adapter")}async rotate(t,e){throw new Error("ImageProcessorPort.rotate() must be implemented by adapter")}async applyFilter(t,e){throw new Error("ImageProcessorPort.applyFilter() must be implemented by adapter")}};function lh(n){return new Promise((t,e)=>{let i=new Image;i.onload=()=>t(i),i.onerror=e,i.src=n})}var $e=class extends _e{async renderEdits(t,e={}){if(!t)return"";if(typeof document>"u")return t;try{let i=await lh(t),r={...e};return e?.crop&&"w"in e.crop&&(r.crop={x:Math.round((e.crop.x||0)*i.naturalWidth),y:Math.round((e.crop.y||0)*i.naturalHeight),width:Math.round((e.crop.w||1)*i.naturalWidth),height:Math.round((e.crop.h||1)*i.naturalHeight)}),e?.rotate!==void 0&&(r.rotation=e.rotate),tr(i,r).toDataURL("image/jpeg",.92)}catch{return t}}async crop(t,e){return this.renderEdits(t,{crop:e})}async rotate(t,e){return this.renderEdits(t,{rotate:e})}async applyFilter(t,e){return this.renderEdits(t,{filter:e})}};var Li=class extends _e{async renderEdits(t,e){return t}async crop(t,e){return t}async rotate(t,e){return t}async applyFilter(t,e){return t}};function us(n={}){let t=n&&n.crop&&typeof n.crop=="object"?{x:Math.max(0,Math.min(1,Number(n.crop.x)||0)),y:Math.max(0,Math.min(1,Number(n.crop.y)||0)),w:Math.max(0,Math.min(1,Number(n.crop.w)||1)),h:Math.max(0,Math.min(1,Number(n.crop.h)||1))}:null,e=0,i=n?.rotate!==void 0?n.rotate:n?.rotation;if(i!==void 0){let o=(Math.round(Number(i)/90)*90%360+360)%360;(o===90||o===180||o===270)&&(e=o)}let r=n&&n.filter==="bw"?"bw":"none";return{crop:t,rotate:e,filter:r}}function cr(n){if(!n)return!1;let t=n.rotate!==void 0?n.rotate:n.rotation;return!!(n.crop||t&&t!==0||n.filter&&n.filter!=="none")}var Zt=n=>Math.round(n*1e6)/1e6;function wa(n,t=0){if(!n)return null;let e=(Math.round(Number(t)/90)*90%360+360)%360,{x:i,y:r,w:o,h:g}=n;return e===90?{x:Zt(Math.max(0,Math.min(1,1-r-g))),y:Zt(Math.max(0,Math.min(1,i))),w:Zt(Math.max(.01,Math.min(1,g))),h:Zt(Math.max(.01,Math.min(1,o)))}:e===180?{x:Zt(Math.max(0,Math.min(1,1-i-o))),y:Zt(Math.max(0,Math.min(1,1-r-g))),w:Zt(Math.max(.01,Math.min(1,o))),h:Zt(Math.max(.01,Math.min(1,g)))}:e===270?{x:Zt(Math.max(0,Math.min(1,r))),y:Zt(Math.max(0,Math.min(1,1-i-o))),w:Zt(Math.max(.01,Math.min(1,g))),h:Zt(Math.max(.01,Math.min(1,o)))}:{x:Zt(Math.max(0,Math.min(1,i))),y:Zt(Math.max(0,Math.min(1,r))),w:Zt(Math.max(.01,Math.min(1,o))),h:Zt(Math.max(.01,Math.min(1,g)))}}function xa(n,t=0){return wa(n,t)}function Aa(n,t=0){return wa(n,-t)}var Fi=class{constructor(t){this.id=t.id,this.src=t.src,this.originalSrc=t.originalSrc||t.src,this.edits=us(t.edits),this.name=t.name||"Page",this.type=t.type||"image",this.orientation=t.orientation||1,this.ocrText=t.ocrText||null,this.ocrConfidence=t.ocrConfidence??null,this.ocrWords=Array.isArray(t.ocrWords)?t.ocrWords:null,this.ocrWidth=typeof t.ocrWidth=="number"?t.ocrWidth:null,this.ocrHeight=typeof t.ocrHeight=="number"?t.ocrHeight:null}get isModified(){return cr(this.edits)}toJSON(){return{id:this.id,src:this.src,originalSrc:this.originalSrc,edits:this.edits,name:this.name,type:this.type,orientation:this.orientation,ocrText:this.ocrText,ocrConfidence:this.ocrConfidence,ocrWords:this.ocrWords,ocrWidth:this.ocrWidth,ocrHeight:this.ocrHeight}}},Us=class{constructor(t){this.id=t.id,this.name=t.name||"Untitled Document",this.pages=Array.isArray(t.pages)?t.pages.map(e=>e instanceof Fi?e:new Fi(e)):[],this.createdAt=t.createdAt||Date.now(),this.updatedAt=t.updatedAt||Date.now()}get pageCount(){return this.pages.length}toJSON(){return{id:this.id,name:this.name,pages:this.pages.map(t=>t.toJSON()),createdAt:this.createdAt,updatedAt:this.updatedAt}}},$s=class{constructor(t={}){this.mode=t.mode==="single"?"single":"batch",this.aspect=t.aspect||"auto",this.docId=t.docId||null,this.maxPages=Math.max(0,Number(t.maxPages)||0),this.stage="viewfinder",this.activePageIndex=0,this.history=[],this.future=[]}pushHistory(t){this.history.push(t),this.future=[],this.history.length>50&&this.history.shift()}undo(){if(this.history.length===0)return null;let t=this.history.pop();return this.future.push(t),t}redo(){if(this.future.length===0)return null;let t=this.future.pop();return this.history.push(t),t}};var Vt={PAGE_ADDED:"copio:page-added",PAGE_REMOVED:"copio:page-removed",PAGES_CHANGED:"copio:pages-changed",SCAN_COMPLETE:"copio:scan-complete",EXPORT_PROGRESS:"copio:export-progress",EXPORT_COMPLETE:"copio:export-complete",OCR_COMPLETE:"copio:ocr-complete",SYNC_CONNECTED:"copio:sync-connected",ERROR:"copio:error"};function lr(n,t,e={}){let i=new CustomEvent(t,{bubbles:!0,composed:!0,cancelable:!0,detail:e});return n&&typeof n.dispatchEvent=="function"&&n.dispatchEvent(i),i}var _a=["crop","rotate","filter","ocr","export","sync"],Sa=["pdf","zip","png","jpg"],Ea=["eng"],Ca={};function ni(n,t){!n||!t||(Ca[n]=t,typeof globalThis<"u"&&(globalThis.__copio_services__=globalThis.__copio_services__||{},globalThis.__copio_services__[n]=t))}function si(n){return Ca[n]?Ca[n]:typeof globalThis<"u"&&globalThis.__copio_services__?.[n]?globalThis.__copio_services__[n]:null}function hh(n){return n?n instanceof Set?new Set(n):Array.isArray(n)?new Set(n.map(t=>String(t).trim().toLowerCase()).filter(Boolean)):typeof n=="string"?new Set(n.split(/[\s,]+/).map(t=>t.trim().toLowerCase()).filter(Boolean)):new Set(_a):new Set(_a)}function hr(n,t){return n?Array.isArray(n)?n.map(e=>String(e).trim().toLowerCase()).filter(Boolean):typeof n=="string"?n.split(/[\s,]+/).map(e=>e.trim().toLowerCase()).filter(Boolean):[...t]:[...t]}var Oi=class{#t=new Set(_a);#e=[...Sa];#i=[...Ea];#n=0;#r="";#s=null;#o=null;#c={};#a=!0;#h=!0;#u=null;#d=new Map;#l=new Map;constructor(t={}){this.#s=t.storage||ns(t),this.#o=t.repository||new ti(this.#s),t.services&&(this.#c={...t.services}),t.imageProcessor?(this.#u=t.imageProcessor,this.#c.imageProcessor=t.imageProcessor):this.getService("imageProcessor")?this.#u=this.getService("imageProcessor"):typeof document<"u"?this.#u=new $e:this.#u=new Li,t.features!==void 0&&this.setFeatures(t.features),t.exportFormats!==void 0&&(this.#e=hr(t.exportFormats,Sa)),t.ocrLanguages!==void 0&&(this.#i=hr(t.ocrLanguages,Ea)),t.maxPages!==void 0&&(this.#n=Math.max(0,Number(t.maxPages)||0)),t.assetBase!==void 0&&Ii(t.assetBase),t.licenseKey!==void 0&&(this.#r=String(t.licenseKey||"")),t.ocr!==void 0?this.ocr=!!t.ocr:t.features!==void 0&&!this.hasFeature("ocr")&&(this.ocr=!1),t.pdf!==void 0?this.pdf=!!t.pdf:t.exportFormats!==void 0&&!this.#e.includes("pdf")&&(this.pdf=!1)}async init(){return this.#s.init()}setService(t,e){this.#c[t]=e}getService(t){return this.#c[t]||si(t)}hasFeature(t){return t?this.#t.has(String(t).trim().toLowerCase()):!1}get features(){return Array.from(this.#t)}setFeatures(t){this.#t=hh(t),this.hasFeature("ocr")?(this.#a=!0,this.getService("ocr")instanceof de&&this.setService("ocr",si("ocr"))):(this.#a=!1,this.setService("ocr",new de))}enableFeature(t){if(t){let e=String(t).trim().toLowerCase();this.#t.add(e),e==="ocr"&&(this.#a=!0,this.getService("ocr")instanceof de&&this.setService("ocr",si("ocr")))}}disableFeature(t){if(t){let e=String(t).trim().toLowerCase();this.#t.delete(e),e==="ocr"&&(this.#a=!1,this.setService("ocr",new de))}}get ocr(){return this.#a&&this.hasFeature("ocr")}set ocr(t){this.#a=!!t,this.#a?(this.enableFeature("ocr"),this.getService("ocr")instanceof de&&this.setService("ocr",si("ocr"))):(this.disableFeature("ocr"),this.setService("ocr",new de))}get pdf(){return this.#h&&this.#e.includes("pdf")}set pdf(t){this.#h=!!t,this.#h?(this.#e.includes("pdf")||this.#e.push("pdf"),this.getService("pdf")instanceof Ee&&this.setService("pdf",si("pdf"))):(this.#e=this.#e.filter(e=>e!=="pdf"),this.setService("pdf",new Ee))}get exportFormats(){return[...this.#e]}set exportFormats(t){this.#e=hr(t,Sa),this.#e.includes("pdf")?(this.#h=!0,this.getService("pdf")instanceof Ee&&this.setService("pdf",si("pdf"))):(this.#h=!1,this.setService("pdf",new Ee))}get ocrLanguages(){return[...this.#i]}set ocrLanguages(t){this.#i=hr(t,Ea)}get maxPages(){return this.#n}set maxPages(t){this.#n=Math.max(0,Number(t)||0)}get assetBase(){return ir()}set assetBase(t){Ii(t)}get licenseKey(){return this.#r}set licenseKey(t){this.#r=String(t||"")}get storage(){return this.#s}setStorage(t){t&&(this.#s=t,this.#o=new ti(this.#s))}#f(t,e){this.#d.has(t)||this.#d.set(t,[]);let i=this.#d.get(t);i.push(e),i.length>50&&i.shift(),this.#l.has(t)&&(this.#l.get(t).length=0)}get imageProcessor(){return this.#u}setImageProcessor(t){t&&(this.#u=t,this.setService("imageProcessor",t))}async renderEdits(t,e){if(!t)return"";let i=us(e);return this.#u?this.#u.renderEdits(t,i):bc(t,i)}get docs(){return this.#o}async listDocuments(){return this.#o.listDocs()}async getDocument(t){return this.#o.getDoc(t)}async createDocument(t,e){return this.#o.createDoc(t,e)}async deleteDocument(t,e={}){return this.#o.deleteDoc(t,e)}async undoDeleteDocument(t){return this.#o.undoDeleteDoc(t)}async renameDocument(t,e){return this.#o.renameDoc(t,e)}async addPages(t,e){return this.#o.addPages(t,e)}async deletePage(t,e,i={}){return this.#f(t,{type:"delete",pageId:e}),this.#o.deletePage(t,e,i)}async undoDeletePage(t,e){return this.#o.undoDeletePage(t,e)}async updatePage(t,e,i){return this.#o.updatePage(t,e,i)}async reorderPages(t,e){let i=await this.getDocument(t),r=i?.pages?i.pages.map(o=>o.id):[];return this.#f(t,{type:"reorder",priorOrder:r,newOrder:[...e]}),this.#o.reorderPages(t,e)}async#g(t){if(t)return t;let e=await this.listDocuments();return e.length>0?e[0].id:null}async applyEdit(t,e,i){let r=await this.#g(t),o=r?await this.getDocument(r):null;if(!o||!o.pages)throw new Error(`Document with ID "${r||t}" not found`);let g=o.pages.find(p=>p.id===e);if(!g)throw new Error(`Page with ID "${e}" not found in document "${r}"`);let d={...g.edits||{crop:null,rotate:0,filter:"none"}},m=g.src,v=us({...d,...i}),u=g.originalSrc||g.src,a=u;return this.#u&&(a=await this.#u.renderEdits(u,v)),await this.updatePage(r,e,{originalSrc:u,src:a,edits:v}),this.#f(r,{type:"edit",pageId:e,priorEdits:d,priorSrc:m,newEdits:v,newSrc:a}),{...g,originalSrc:u,src:a,edits:v}}async undo(t){let e=await this.#g(t),i=e?this.#d.get(e):null;if(!i||i.length===0)return null;let r=i.pop();return this.#l.has(e)||this.#l.set(e,[]),this.#l.get(e).push(r),r.type==="edit"?(await this.updatePage(e,r.pageId,{edits:r.priorEdits,src:r.priorSrc}),{type:"edit",pageId:r.pageId,restoredEdits:r.priorEdits}):r.type==="delete"?(await this.undoDeletePage(e,r.pageId),{type:"delete",pageId:r.pageId}):r.type==="reorder"?(await this.#o.reorderPages(e,r.priorOrder),{type:"reorder",priorOrder:r.priorOrder}):r}async redo(t){let e=await this.#g(t),i=e?this.#l.get(e):null;if(!i||i.length===0)return null;let r=i.pop();return this.#d.has(e)||this.#d.set(e,[]),this.#d.get(e).push(r),r.type==="edit"?(await this.updatePage(e,r.pageId,{edits:r.newEdits,src:r.newSrc}),{type:"edit",pageId:r.pageId,appliedEdits:r.newEdits}):r.type==="delete"?(await this.deletePage(e,r.pageId),{type:"delete",pageId:r.pageId}):r.type==="reorder"?(await this.reorderPages(e,r.newOrder),{type:"reorder",newOrder:r.newOrder}):r}subscribe(t){return this.#o.subscribe(t)}async addFiles(t,e=null){if(!t||t.length===0)return[];let i=Array.from(t),r=[];for(let g of i)if(g.type==="application/pdf"){let d=this.getService("pdf");if(d&&typeof d.renderPdfPagesToDataUrls=="function"){let m=await d.renderPdfPagesToDataUrls(g);for(let v of m)r.push({id:Di(),src:v,originalSrc:v,edits:{crop:null,rotation:0,filter:"none"},type:"image",name:g.name||"PDF Page"})}else console.warn("PDF import service (PdfPort) not registered. Skipping PDF file.")}else if(g.type&&g.type.startsWith("image/")){let d=await Qn(g),m=null;try{m=await Jn(g)}catch{}r.push({id:Di(),src:d,originalSrc:d,edits:{crop:null,rotation:0,filter:"none"},type:"image",name:g.name||"Captured Image",orientation:m})}if(r.length===0)return[];await this.init();let o=e;if(o)await this.getDocument(o)||await this.#o.saveDoc(o,{name:"Scanned Document",pages:[]});else{let g=await this.listDocuments();g.length>0?o=g[0].id:o=(await this.createDocument("Scanned Document",[])).id}if(this.#n>0){let g=(await this.getDocument(o))?.pages||[],d=Math.max(0,this.#n-g.length);if(d<=0)throw new Error(`Maximum page limit (${this.#n}) reached`);r.splice(d)}return await this.addPages(o,r),r}async getPages(t=null){let e=t;if(!e){let r=await this.listDocuments();if(r.length===0)return[];e=r[0].id}return(await this.getDocument(e))?.pages||[]}async clear(t=null){let e=t;if(!e){let r=await this.listDocuments();if(r.length===0)return;e=r[0].id}let i=await this.getDocument(e);if(!(!i||!i.pages))for(let r of i.pages)await this.deletePage(e,r.id)}async#p(t){if(Array.isArray(t))return{docName:"document",pages:t,docId:null};if(typeof t=="string"){let i=await this.getDocument(t);return{docName:i?.name||"document",pages:i?.pages||[],docId:t}}let e=await this.listDocuments();if(e.length>0){let i=await this.getDocument(e[0].id);return{docName:i?.name||"document",pages:i?.pages||[],docId:e[0].id}}return{docName:"document",pages:[],docId:null}}async exportPdf(t,e={}){if(!this.hasFeature("export")){let g=new Error('Feature "export" is disabled');throw Object.assign(g,{code:"FEATURE_DISABLED"}),g}if(!this.#h||!this.#e.includes("pdf")){let g=new Error('Feature "pdf" is disabled');throw Object.assign(g,{code:"FEATURE_DISABLED"}),g}let{docName:i,pages:r}=await this.#p(t),o=this.getService("pdf")||this.getService("export");if(!o||typeof o.exportDocumentAsPdf!="function")throw new Error("Export service (PdfPort) is not registered. Import @copio/sdk or register an exportService.");return o.exportDocumentAsPdf(i,r,{download:!1,showProgress:!1,onOcrComplete:async()=>{if(typeof t=="string"){let g=await this.#s.getDoc(t);g&&(g.pages=r,await this.#s.saveDoc(t,g))}},...e})}async exportZip(t,e={}){if(!this.hasFeature("export")){let g=new Error('Feature "export" is disabled');throw Object.assign(g,{code:"FEATURE_DISABLED"}),g}let{docName:i,pages:r}=await this.#p(t),o=this.getService("export");if(!o||typeof o.exportDocumentAsImages!="function")throw new Error("Export service is not registered. Import @copio/sdk or register an exportService.");return o.exportDocumentAsImages(i,r,{download:!1,showProgress:!1,...e})}async runOcr(t,e=null,i={}){if(!this.#a||!this.hasFeature("ocr")){let v=new Error('Feature "ocr" is disabled');throw Object.assign(v,{code:"FEATURE_DISABLED"}),v}let{pages:r}=await this.#p(t),o=r;e&&(o=r.filter(v=>v.id===e));let g=this.getService("ocr");if(!g||typeof g.recognizeDocumentPages!="function")throw new Error("OCR service (OcrPort) is not registered. Import @copio/sdk or register an ocrService.");let d=i.lang||this.#i[0]||"eng",m=await g.recognizeDocumentPages(o,{lang:d,...i});if(Array.isArray(m.pagesResults)){for(let v of m.pagesResults){let u=o.find(a=>a.id===v.pageId)||o[v.pageIndex];u&&(u.ocrText=v.text,u.ocrConfidence=v.confidence,u.ocrWords=v.words)}if(typeof t=="string"){let v=await this.#s.getDoc(t);if(v&&Array.isArray(v.pages)){for(let u of m.pagesResults){let a=v.pages.find(p=>p.id===u.pageId)||v.pages[u.pageIndex];a&&(a.ocrText=u.text,a.ocrConfidence=u.confidence,a.ocrWords=u.words)}await this.#s.saveDoc(t,v)}}}return{text:m.combinedText,...m}}async sync(t={}){if(!this.hasFeature("sync")){let i=new Error('Feature "sync" is disabled');throw Object.assign(i,{code:"FEATURE_DISABLED"}),i}let e=this.getService("sync");if(!e)throw new Error("Sync service (SyncPort) is not registered. Import @copio/sdk or register a syncService.");return new e(this.#o,t.onStateChange)}};ii();Ni();var js=`
|
|
10
10
|
:host {
|
|
11
11
|
all: initial;
|
|
12
12
|
display: block;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as F,b as m,c as O,j as R,k as L}from"./chunk-G5EUMLYT.js";import{a as N}from"./chunk-KH5JE65X.js";import{c as D}from"./chunk-K4NR6OAC.js";import{c as P}from"./chunk-L4OVZN23.js";import{a as f}from"./chunk-U3V3VZGO.js";import{a as w}from"./chunk-5OTO5WFV.js";import{a as B,b as v}from"./chunk-ZT72PD2C.js";var g=class{#e=null;#t=new Map;#i=new Map;constructor(e=D()){this.#e=e}get adapter(){return this.#e}get store(){return this.#e?.store??null}async init(){return this.#e.init()}listDocsSync(){return typeof this.#e.listDocsSync=="function"?this.#e.listDocsSync().map(t=>{let s=this.#r(t.pages);return{id:t.id,name:t.name||"",pageCount:s.length,pages:s}}):[]}async listDocs(){return(await this.#e.listDocs()).map(t=>{let s=this.#r(t.pages);return{id:t.id,name:t.name||"",pageCount:s.length,pages:s}})}getDocSync(e){if(!e)return null;if(typeof this.#e.getDocSync=="function"){let r=this.#e.getDocSync(e);return r?{id:r.id,name:r.name||"",pages:this.#r(r.pages)}:null}let s=this.listDocsSync().find(r=>r.id===e);return s?{id:s.id,name:s.name,pages:s.pages||[]}:null}async getDoc(e){if(!e)return null;if(typeof this.#e.getDoc=="function"){let t=await this.#e.getDoc(e);return t?{id:t.id,name:t.name||"",pages:this.#r(t.pages)}:null}return this.getDocSync(e)}async createDoc(e="Untitled Document",t=[]){let s=m(),r=this.#r(t),o={id:s,name:e||"Untitled Document",pages:r};return await this.#e.saveDoc(s,o),o}async saveDoc(e,t){if(!e)throw new Error("Cannot save document without an ID");let s=this.#r(t.pages);await this.#e.saveDoc(e,{id:e,name:t.name||"",pages:s})}async renameDoc(e,t){if(typeof this.#e.renameDoc=="function")return this.#e.renameDoc(e,t);let s=await this.getDoc(e);if(!s)throw new Error(`Document "${e}" not found`);s.name=t,await this.saveDoc(e,s)}async deleteDoc(e,{soft:t=!0,timeoutMs:s=5e3}={}){if(!e)return;let r=this.getDocSync(e);if(r){if(this.#n(e),await this.#e.deleteDoc(e),t&&s>0){let o=setTimeout(async()=>{this.#t.delete(e)},s);this.#t.set(e,{doc:r,timerId:o})}return{id:e,name:r.name,undo:()=>this.undoDeleteDoc(e)}}}#n(e){if(this.#t.has(e)){let t=this.#t.get(e);clearTimeout(t.timerId),this.#t.delete(e)}}async undoDeleteDoc(e){let t=this.#t.get(e);return t?(clearTimeout(t.timerId),this.#t.delete(e),await this.#e.saveDoc(e,t.doc),t.doc):null}isSoftDeletedDoc(e){return this.#t.has(e)}async addPages(e,t){let s=await this.getDoc(e);if(!s)throw new Error(`Document "${e}" not found`);let r=Array.isArray(t)?t:[t];s.pages.push(...r),await this.saveDoc(e,s)}async updatePage(e,t,s){let r=await this.getDoc(e);if(!r)throw new Error(`Document "${e}" not found`);let o=r.pages.findIndex(i=>i.id===t);if(o===-1)throw new Error(`Page "${t}" not found in document "${e}"`);r.pages[o]={...r.pages[o],...s},await this.saveDoc(e,r)}async reorderPages(e,t){let s=await this.getDoc(e);if(!s)throw new Error(`Document "${e}" not found`);let r=new Map(s.pages.map(i=>[i.id,i])),o=[];for(let i of t)r.has(i)&&(o.push(r.get(i)),r.delete(i));for(let i of r.values())o.push(i);s.pages=o,await this.saveDoc(e,s)}async deletePage(e,t,{soft:s=!0,timeoutMs:r=5e3}={}){let o=await this.getDoc(e);if(!o)throw new Error(`Document "${e}" not found`);let i=o.pages.findIndex(h=>h.id===t);if(i===-1)return;let[a]=o.pages.splice(i,1);await this.saveDoc(e,o);let u=`${e}:${t}`;if(this.#d(u),!s||r<=0){if(typeof this.#e.deletePage=="function")try{await this.#e.deletePage(e,t)}catch(h){console.warn("[DocRepository] Adapter deletePage error:",h)}return}let c=setTimeout(async()=>{if(this.#i.delete(u),typeof this.#e.deletePage=="function")try{await this.#e.deletePage(e,t)}catch(h){console.warn("[DocRepository] Adapter deletePage error:",h)}},r);return this.#i.set(u,{docId:e,pageId:t,page:a,index:i,timerId:c}),{docId:e,pageId:t,undo:()=>this.undoDeletePage(e,t)}}#d(e){if(this.#i.has(e)){let t=this.#i.get(e);clearTimeout(t.timerId),this.#i.delete(e)}}async undoDeletePage(e,t){let s=`${e}:${t}`,r=this.#i.get(s);if(!r)return null;clearTimeout(r.timerId),this.#i.delete(s);let o=await this.getDoc(e);if(!o)return null;let i=Math.min(r.index,o.pages.length);return o.pages.splice(i,0,r.page),await this.saveDoc(e,o),r.page}isSoftDeletedPage(e,t){return this.#i.has(`${e}:${t}`)}subscribe(e){return this.#e.subscribe(e)}async getAllDocs(){let e=await this.listDocs(),t={};for(let s of e)t[s.id]=s;return t}async exportAll(){let e=await this.listDocs(),t={};for(let s of e){let r=await this.getDoc(s.id),o=[];for(let i of r?.pages||[]){if(!i){o.push(i);continue}let a={...i},u=a.blob instanceof Blob?a.blob:null;if(!u&&typeof a.src=="string"&&a.src.startsWith("blob:"))try{u=await(await fetch(a.src)).blob()}catch{}u&&(a.src=await P(u));let c=a.originalBlob instanceof Blob?a.originalBlob:null;if(!c&&typeof a.originalSrc=="string"&&a.originalSrc.startsWith("blob:"))try{c=await(await fetch(a.originalSrc)).blob()}catch{}c&&(a.originalSrc=await P(c)),delete a.blob,delete a.originalBlob,o.push(a)}t[s.id]={name:s.name,pages:JSON.stringify(o)}}return t}async importDocs(e){let t=0;for(let[s,r]of Object.entries(e||{})){await this.getDoc(s)||t++;let i=this.#r(r.pages);await this.saveDoc(s,{name:r.name||"",pages:i})}return t}#r(e){if(Array.isArray(e))return[...e];if(typeof e=="string")try{return JSON.parse(e)}catch{return[]}return[]}},W=new g;var k="2026-11-06T14:30:44.258Z",z="0.1.4";function S(n={}){let e=n&&n.crop&&typeof n.crop=="object"?{x:Math.max(0,Math.min(1,Number(n.crop.x)||0)),y:Math.max(0,Math.min(1,Number(n.crop.y)||0)),w:Math.max(0,Math.min(1,Number(n.crop.w)||1)),h:Math.max(0,Math.min(1,Number(n.crop.h)||1))}:null,t=0,s=n?.rotate!==void 0?n.rotate:n?.rotation;if(s!==void 0){let o=(Math.round(Number(s)/90)*90%360+360)%360;(o===90||o===180||o===270)&&(t=o)}let r=n&&n.filter==="bw"?"bw":"none";return{crop:e,rotate:t,filter:r}}function U(n){if(!n)return!1;let e=n.rotate!==void 0?n.rotate:n.rotation;return!!(n.crop||e&&e!==0||n.filter&&n.filter!=="none")}var d=n=>Math.round(n*1e6)/1e6;function M(n,e=0){if(!n)return null;let t=(Math.round(Number(e)/90)*90%360+360)%360,{x:s,y:r,w:o,h:i}=n;return t===90?{x:d(Math.max(0,Math.min(1,1-r-i))),y:d(Math.max(0,Math.min(1,s))),w:d(Math.max(.01,Math.min(1,i))),h:d(Math.max(.01,Math.min(1,o)))}:t===180?{x:d(Math.max(0,Math.min(1,1-s-o))),y:d(Math.max(0,Math.min(1,1-r-i))),w:d(Math.max(.01,Math.min(1,o))),h:d(Math.max(.01,Math.min(1,i)))}:t===270?{x:d(Math.max(0,Math.min(1,r))),y:d(Math.max(0,Math.min(1,1-s-o))),w:d(Math.max(.01,Math.min(1,i))),h:d(Math.max(.01,Math.min(1,o)))}:{x:d(Math.max(0,Math.min(1,s))),y:d(Math.max(0,Math.min(1,r))),w:d(Math.max(.01,Math.min(1,o))),h:d(Math.max(.01,Math.min(1,i)))}}function j(n,e=0){return M(n,e)}function G(n,e=0){return M(n,-e)}var y=class{constructor(e){this.id=e.id,this.src=e.src,this.originalSrc=e.originalSrc||e.src,this.edits=S(e.edits),this.name=e.name||"Page",this.type=e.type||"image",this.orientation=e.orientation||1,this.ocrText=e.ocrText||null,this.ocrConfidence=e.ocrConfidence??null,this.ocrWords=Array.isArray(e.ocrWords)?e.ocrWords:null,this.ocrWidth=typeof e.ocrWidth=="number"?e.ocrWidth:null,this.ocrHeight=typeof e.ocrHeight=="number"?e.ocrHeight:null}get isModified(){return U(this.edits)}toJSON(){return{id:this.id,src:this.src,originalSrc:this.originalSrc,edits:this.edits,name:this.name,type:this.type,orientation:this.orientation,ocrText:this.ocrText,ocrConfidence:this.ocrConfidence,ocrWords:this.ocrWords,ocrWidth:this.ocrWidth,ocrHeight:this.ocrHeight}}},A=class{constructor(e){this.id=e.id,this.name=e.name||"Untitled Document",this.pages=Array.isArray(e.pages)?e.pages.map(t=>t instanceof y?t:new y(t)):[],this.createdAt=e.createdAt||Date.now(),this.updatedAt=e.updatedAt||Date.now()}get pageCount(){return this.pages.length}toJSON(){return{id:this.id,name:this.name,pages:this.pages.map(e=>e.toJSON()),createdAt:this.createdAt,updatedAt:this.updatedAt}}},b=class{constructor(e={}){this.mode=e.mode==="single"?"single":"batch",this.aspect=e.aspect||"auto",this.docId=e.docId||null,this.maxPages=Math.max(0,Number(e.maxPages)||0),this.stage="viewfinder",this.activePageIndex=0,this.history=[],this.future=[]}pushHistory(e){this.history.push(e),this.future=[],this.history.length>50&&this.history.shift()}undo(){if(this.history.length===0)return null;let e=this.history.pop();return this.future.push(e),e}redo(){if(this.future.length===0)return null;let e=this.future.pop();return this.history.push(e),e}};var H={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 J(n,e,t={}){let s=new CustomEvent(e,{bubbles:!0,composed:!0,cancelable:!0,detail:t});return n&&typeof n.dispatchEvent=="function"&&n.dispatchEvent(s),s}var I=["crop","rotate","filter","ocr","export","sync"],_=["pdf","zip","png","jpg"],T=["eng"],C={};function Se(n,e){!n||!e||(C[n]=e,typeof globalThis<"u"&&(globalThis.__copio_services__=globalThis.__copio_services__||{},globalThis.__copio_services__[n]=e))}function p(n){return C[n]?C[n]:typeof globalThis<"u"&&globalThis.__copio_services__?.[n]?globalThis.__copio_services__[n]:null}function K(n){return n?n instanceof Set?new Set(n):Array.isArray(n)?new Set(n.map(e=>String(e).trim().toLowerCase()).filter(Boolean)):typeof n=="string"?new Set(n.split(/[\s,]+/).map(e=>e.trim().toLowerCase()).filter(Boolean)):new Set(I):new Set(I)}function x(n,e){return n?Array.isArray(n)?n.map(t=>String(t).trim().toLowerCase()).filter(Boolean):typeof n=="string"?n.split(/[\s,]+/).map(t=>t.trim().toLowerCase()).filter(Boolean):[...e]:[...e]}var $=class{#e=new Set(I);#t=[..._];#i=[...T];#n=0;#d="";#r=null;#s=null;#l={};#a=!0;#h=!0;#o=null;#c=new Map;#u=new Map;constructor(e={}){this.#r=e.storage||D(e),this.#s=e.repository||new g(this.#r),e.services&&(this.#l={...e.services}),e.imageProcessor?(this.#o=e.imageProcessor,this.#l.imageProcessor=e.imageProcessor):this.getService("imageProcessor")?this.#o=this.getService("imageProcessor"):typeof document<"u"?this.#o=new L:this.#o=new N,e.features!==void 0&&this.setFeatures(e.features),e.exportFormats!==void 0&&(this.#t=x(e.exportFormats,_)),e.ocrLanguages!==void 0&&(this.#i=x(e.ocrLanguages,T)),e.maxPages!==void 0&&(this.#n=Math.max(0,Number(e.maxPages)||0)),e.assetBase!==void 0&&v(e.assetBase),e.licenseKey!==void 0&&(this.#d=String(e.licenseKey||"")),e.ocr!==void 0?this.ocr=!!e.ocr:e.features!==void 0&&!this.hasFeature("ocr")&&(this.ocr=!1),e.pdf!==void 0?this.pdf=!!e.pdf:e.exportFormats!==void 0&&!this.#t.includes("pdf")&&(this.pdf=!1)}async init(){return this.#r.init()}setService(e,t){this.#l[e]=t}getService(e){return this.#l[e]||p(e)}hasFeature(e){return e?this.#e.has(String(e).trim().toLowerCase()):!1}get features(){return Array.from(this.#e)}setFeatures(e){this.#e=K(e),this.hasFeature("ocr")?(this.#a=!0,this.getService("ocr")instanceof f&&this.setService("ocr",p("ocr"))):(this.#a=!1,this.setService("ocr",new f))}enableFeature(e){if(e){let t=String(e).trim().toLowerCase();this.#e.add(t),t==="ocr"&&(this.#a=!0,this.getService("ocr")instanceof f&&this.setService("ocr",p("ocr")))}}disableFeature(e){if(e){let t=String(e).trim().toLowerCase();this.#e.delete(t),t==="ocr"&&(this.#a=!1,this.setService("ocr",new f))}}get ocr(){return this.#a&&this.hasFeature("ocr")}set ocr(e){this.#a=!!e,this.#a?(this.enableFeature("ocr"),this.getService("ocr")instanceof f&&this.setService("ocr",p("ocr"))):(this.disableFeature("ocr"),this.setService("ocr",new f))}get pdf(){return this.#h&&this.#t.includes("pdf")}set pdf(e){this.#h=!!e,this.#h?(this.#t.includes("pdf")||this.#t.push("pdf"),this.getService("pdf")instanceof w&&this.setService("pdf",p("pdf"))):(this.#t=this.#t.filter(t=>t!=="pdf"),this.setService("pdf",new w))}get exportFormats(){return[...this.#t]}set exportFormats(e){this.#t=x(e,_),this.#t.includes("pdf")?(this.#h=!0,this.getService("pdf")instanceof w&&this.setService("pdf",p("pdf"))):(this.#h=!1,this.setService("pdf",new w))}get ocrLanguages(){return[...this.#i]}set ocrLanguages(e){this.#i=x(e,T)}get maxPages(){return this.#n}set maxPages(e){this.#n=Math.max(0,Number(e)||0)}get assetBase(){return B()}set assetBase(e){v(e)}get licenseKey(){return this.#d}set licenseKey(e){this.#d=String(e||"")}get storage(){return this.#r}setStorage(e){e&&(this.#r=e,this.#s=new g(this.#r))}#f(e,t){this.#c.has(e)||this.#c.set(e,[]);let s=this.#c.get(e);s.push(t),s.length>50&&s.shift(),this.#u.has(e)&&(this.#u.get(e).length=0)}get imageProcessor(){return this.#o}setImageProcessor(e){e&&(this.#o=e,this.setService("imageProcessor",e))}async renderEdits(e,t){if(!e)return"";let s=S(t);return this.#o?this.#o.renderEdits(e,s):R(e,s)}get docs(){return this.#s}async listDocuments(){return this.#s.listDocs()}async getDocument(e){return this.#s.getDoc(e)}async createDocument(e,t){return this.#s.createDoc(e,t)}async deleteDocument(e,t={}){return this.#s.deleteDoc(e,t)}async undoDeleteDocument(e){return this.#s.undoDeleteDoc(e)}async renameDocument(e,t){return this.#s.renameDoc(e,t)}async addPages(e,t){return this.#s.addPages(e,t)}async deletePage(e,t,s={}){return this.#f(e,{type:"delete",pageId:t}),this.#s.deletePage(e,t,s)}async undoDeletePage(e,t){return this.#s.undoDeletePage(e,t)}async updatePage(e,t,s){return this.#s.updatePage(e,t,s)}async reorderPages(e,t){let s=await this.getDocument(e),r=s?.pages?s.pages.map(o=>o.id):[];return this.#f(e,{type:"reorder",priorOrder:r,newOrder:[...t]}),this.#s.reorderPages(e,t)}async#g(e){if(e)return e;let t=await this.listDocuments();return t.length>0?t[0].id:null}async applyEdit(e,t,s){let r=await this.#g(e),o=r?await this.getDocument(r):null;if(!o||!o.pages)throw new Error(`Document with ID "${r||e}" not found`);let i=o.pages.find(E=>E.id===t);if(!i)throw new Error(`Page with ID "${t}" not found in document "${r}"`);let a={...i.edits||{crop:null,rotate:0,filter:"none"}},u=i.src,c=S({...a,...s}),h=i.originalSrc||i.src,l=h;return this.#o&&(l=await this.#o.renderEdits(h,c)),await this.updatePage(r,t,{originalSrc:h,src:l,edits:c}),this.#f(r,{type:"edit",pageId:t,priorEdits:a,priorSrc:u,newEdits:c,newSrc:l}),{...i,originalSrc:h,src:l,edits:c}}async undo(e){let t=await this.#g(e),s=t?this.#c.get(t):null;if(!s||s.length===0)return null;let r=s.pop();return this.#u.has(t)||this.#u.set(t,[]),this.#u.get(t).push(r),r.type==="edit"?(await this.updatePage(t,r.pageId,{edits:r.priorEdits,src:r.priorSrc}),{type:"edit",pageId:r.pageId,restoredEdits:r.priorEdits}):r.type==="delete"?(await this.undoDeletePage(t,r.pageId),{type:"delete",pageId:r.pageId}):r.type==="reorder"?(await this.#s.reorderPages(t,r.priorOrder),{type:"reorder",priorOrder:r.priorOrder}):r}async redo(e){let t=await this.#g(e),s=t?this.#u.get(t):null;if(!s||s.length===0)return null;let r=s.pop();return this.#c.has(t)||this.#c.set(t,[]),this.#c.get(t).push(r),r.type==="edit"?(await this.updatePage(t,r.pageId,{edits:r.newEdits,src:r.newSrc}),{type:"edit",pageId:r.pageId,appliedEdits:r.newEdits}):r.type==="delete"?(await this.deletePage(t,r.pageId),{type:"delete",pageId:r.pageId}):r.type==="reorder"?(await this.reorderPages(t,r.newOrder),{type:"reorder",newOrder:r.newOrder}):r}subscribe(e){return this.#s.subscribe(e)}async addFiles(e,t=null){if(!e||e.length===0)return[];let s=Array.from(e),r=[];for(let i of s)if(i.type==="application/pdf"){let a=this.getService("pdf");if(a&&typeof a.renderPdfPagesToDataUrls=="function"){let u=await a.renderPdfPagesToDataUrls(i);for(let c of u)r.push({id:m(),src:c,originalSrc:c,edits:{crop:null,rotation:0,filter:"none"},type:"image",name:i.name||"PDF Page"})}else console.warn("PDF import service (PdfPort) not registered. Skipping PDF file.")}else if(i.type&&i.type.startsWith("image/")){let a=await O(i),u=null;try{u=await F(i)}catch{}r.push({id:m(),src:a,originalSrc:a,edits:{crop:null,rotation:0,filter:"none"},type:"image",name:i.name||"Captured Image",orientation:u})}if(r.length===0)return[];await this.init();let o=t;if(o)await this.getDocument(o)||await this.#s.saveDoc(o,{name:"Scanned Document",pages:[]});else{let i=await this.listDocuments();i.length>0?o=i[0].id:o=(await this.createDocument("Scanned Document",[])).id}if(this.#n>0){let i=(await this.getDocument(o))?.pages||[],a=Math.max(0,this.#n-i.length);if(a<=0)throw new Error(`Maximum page limit (${this.#n}) reached`);r.splice(a)}return await this.addPages(o,r),r}async getPages(e=null){let t=e;if(!t){let r=await this.listDocuments();if(r.length===0)return[];t=r[0].id}return(await this.getDocument(t))?.pages||[]}async clear(e=null){let t=e;if(!t){let r=await this.listDocuments();if(r.length===0)return;t=r[0].id}let s=await this.getDocument(t);if(!(!s||!s.pages))for(let r of s.pages)await this.deletePage(t,r.id)}async#p(e){if(Array.isArray(e))return{docName:"document",pages:e,docId:null};if(typeof e=="string"){let s=await this.getDocument(e);return{docName:s?.name||"document",pages:s?.pages||[],docId:e}}let t=await this.listDocuments();if(t.length>0){let s=await this.getDocument(t[0].id);return{docName:s?.name||"document",pages:s?.pages||[],docId:t[0].id}}return{docName:"document",pages:[],docId:null}}async exportPdf(e,t={}){if(!this.hasFeature("export")){let i=new Error('Feature "export" is disabled');throw Object.assign(i,{code:"FEATURE_DISABLED"}),i}if(!this.#h||!this.#t.includes("pdf")){let i=new Error('Feature "pdf" is disabled');throw Object.assign(i,{code:"FEATURE_DISABLED"}),i}let{docName:s,pages:r}=await this.#p(e),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(s,r,{download:!1,showProgress:!1,onOcrComplete:async()=>{if(typeof e=="string"){let i=await this.#r.getDoc(e);i&&(i.pages=r,await this.#r.saveDoc(e,i))}},...t})}async exportZip(e,t={}){if(!this.hasFeature("export")){let i=new Error('Feature "export" is disabled');throw Object.assign(i,{code:"FEATURE_DISABLED"}),i}let{docName:s,pages:r}=await this.#p(e),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(s,r,{download:!1,showProgress:!1,...t})}async runOcr(e,t=null,s={}){if(!this.#a||!this.hasFeature("ocr")){let c=new Error('Feature "ocr" is disabled');throw Object.assign(c,{code:"FEATURE_DISABLED"}),c}let{pages:r}=await this.#p(e),o=r;t&&(o=r.filter(c=>c.id===t));let i=this.getService("ocr");if(!i||typeof i.recognizeDocumentPages!="function")throw new Error("OCR service (OcrPort) is not registered. Import @copio/sdk or register an ocrService.");let a=s.lang||this.#i[0]||"eng",u=await i.recognizeDocumentPages(o,{lang:a,...s});if(Array.isArray(u.pagesResults)){for(let c of u.pagesResults){let h=o.find(l=>l.id===c.pageId)||o[c.pageIndex];h&&(h.ocrText=c.text,h.ocrConfidence=c.confidence,h.ocrWords=c.words)}if(typeof e=="string"){let c=await this.#r.getDoc(e);if(c&&Array.isArray(c.pages)){for(let h of u.pagesResults){let l=c.pages.find(E=>E.id===h.pageId)||c.pages[h.pageIndex];l&&(l.ocrText=h.text,l.ocrConfidence=h.confidence,l.ocrWords=h.words)}await this.#r.saveDoc(e,c)}}}return{text:u.combinedText,...u}}async sync(e={}){if(!this.hasFeature("sync")){let s=new Error('Feature "sync" is disabled');throw Object.assign(s,{code:"FEATURE_DISABLED"}),s}let t=this.getService("sync");if(!t)throw new Error("Sync service (SyncPort) is not registered. Import @copio/sdk or register a syncService.");return new t(this.#s,e.onStateChange)}};export{g as a,W as b,k as c,z as d,S as e,U as f,M as g,j as h,G as i,y as j,A as k,b as l,H as m,J as n,I as o,_ as p,T as q,Se as r,p as s,$ as t};
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{a as F,b as m,c as O,j as R,k as L}from"./chunk-G5EUMLYT.js";import{a as N}from"./chunk-KH5JE65X.js";import{c as D}from"./chunk-K4NR6OAC.js";import{c as P}from"./chunk-L4OVZN23.js";import{a as f}from"./chunk-U3V3VZGO.js";import{a as w}from"./chunk-5OTO5WFV.js";import{a as B,b as v}from"./chunk-ZT72PD2C.js";var g=class{#e=null;#t=new Map;#i=new Map;constructor(e=D()){this.#e=e}get adapter(){return this.#e}get store(){return this.#e?.store??null}async init(){return this.#e.init()}listDocsSync(){return typeof this.#e.listDocsSync=="function"?this.#e.listDocsSync().map(t=>{let s=this.#r(t.pages);return{id:t.id,name:t.name||"",pageCount:s.length,pages:s}}):[]}async listDocs(){return(await this.#e.listDocs()).map(t=>{let s=this.#r(t.pages);return{id:t.id,name:t.name||"",pageCount:s.length,pages:s}})}getDocSync(e){if(!e)return null;if(typeof this.#e.getDocSync=="function"){let r=this.#e.getDocSync(e);return r?{id:r.id,name:r.name||"",pages:this.#r(r.pages)}:null}let s=this.listDocsSync().find(r=>r.id===e);return s?{id:s.id,name:s.name,pages:s.pages||[]}:null}async getDoc(e){if(!e)return null;if(typeof this.#e.getDoc=="function"){let t=await this.#e.getDoc(e);return t?{id:t.id,name:t.name||"",pages:this.#r(t.pages)}:null}return this.getDocSync(e)}async createDoc(e="Untitled Document",t=[]){let s=m(),r=this.#r(t),o={id:s,name:e||"Untitled Document",pages:r};return await this.#e.saveDoc(s,o),o}async saveDoc(e,t){if(!e)throw new Error("Cannot save document without an ID");let s=this.#r(t.pages);await this.#e.saveDoc(e,{id:e,name:t.name||"",pages:s})}async renameDoc(e,t){if(typeof this.#e.renameDoc=="function")return this.#e.renameDoc(e,t);let s=await this.getDoc(e);if(!s)throw new Error(`Document "${e}" not found`);s.name=t,await this.saveDoc(e,s)}async deleteDoc(e,{soft:t=!0,timeoutMs:s=5e3}={}){if(!e)return;let r=this.getDocSync(e);if(r){if(this.#n(e),await this.#e.deleteDoc(e),t&&s>0){let o=setTimeout(async()=>{this.#t.delete(e)},s);this.#t.set(e,{doc:r,timerId:o})}return{id:e,name:r.name,undo:()=>this.undoDeleteDoc(e)}}}#n(e){if(this.#t.has(e)){let t=this.#t.get(e);clearTimeout(t.timerId),this.#t.delete(e)}}async undoDeleteDoc(e){let t=this.#t.get(e);return t?(clearTimeout(t.timerId),this.#t.delete(e),await this.#e.saveDoc(e,t.doc),t.doc):null}isSoftDeletedDoc(e){return this.#t.has(e)}async addPages(e,t){let s=await this.getDoc(e);if(!s)throw new Error(`Document "${e}" not found`);let r=Array.isArray(t)?t:[t];s.pages.push(...r),await this.saveDoc(e,s)}async updatePage(e,t,s){let r=await this.getDoc(e);if(!r)throw new Error(`Document "${e}" not found`);let o=r.pages.findIndex(i=>i.id===t);if(o===-1)throw new Error(`Page "${t}" not found in document "${e}"`);r.pages[o]={...r.pages[o],...s},await this.saveDoc(e,r)}async reorderPages(e,t){let s=await this.getDoc(e);if(!s)throw new Error(`Document "${e}" not found`);let r=new Map(s.pages.map(i=>[i.id,i])),o=[];for(let i of t)r.has(i)&&(o.push(r.get(i)),r.delete(i));for(let i of r.values())o.push(i);s.pages=o,await this.saveDoc(e,s)}async deletePage(e,t,{soft:s=!0,timeoutMs:r=5e3}={}){let o=await this.getDoc(e);if(!o)throw new Error(`Document "${e}" not found`);let i=o.pages.findIndex(h=>h.id===t);if(i===-1)return;let[a]=o.pages.splice(i,1);await this.saveDoc(e,o);let u=`${e}:${t}`;if(this.#d(u),!s||r<=0){if(typeof this.#e.deletePage=="function")try{await this.#e.deletePage(e,t)}catch(h){console.warn("[DocRepository] Adapter deletePage error:",h)}return}let c=setTimeout(async()=>{if(this.#i.delete(u),typeof this.#e.deletePage=="function")try{await this.#e.deletePage(e,t)}catch(h){console.warn("[DocRepository] Adapter deletePage error:",h)}},r);return this.#i.set(u,{docId:e,pageId:t,page:a,index:i,timerId:c}),{docId:e,pageId:t,undo:()=>this.undoDeletePage(e,t)}}#d(e){if(this.#i.has(e)){let t=this.#i.get(e);clearTimeout(t.timerId),this.#i.delete(e)}}async undoDeletePage(e,t){let s=`${e}:${t}`,r=this.#i.get(s);if(!r)return null;clearTimeout(r.timerId),this.#i.delete(s);let o=await this.getDoc(e);if(!o)return null;let i=Math.min(r.index,o.pages.length);return o.pages.splice(i,0,r.page),await this.saveDoc(e,o),r.page}isSoftDeletedPage(e,t){return this.#i.has(`${e}:${t}`)}subscribe(e){return this.#e.subscribe(e)}async getAllDocs(){let e=await this.listDocs(),t={};for(let s of e)t[s.id]=s;return t}async exportAll(){let e=await this.listDocs(),t={};for(let s of e){let r=await this.getDoc(s.id),o=[];for(let i of r?.pages||[]){if(!i){o.push(i);continue}let a={...i},u=a.blob instanceof Blob?a.blob:null;if(!u&&typeof a.src=="string"&&a.src.startsWith("blob:"))try{u=await(await fetch(a.src)).blob()}catch{}u&&(a.src=await P(u));let c=a.originalBlob instanceof Blob?a.originalBlob:null;if(!c&&typeof a.originalSrc=="string"&&a.originalSrc.startsWith("blob:"))try{c=await(await fetch(a.originalSrc)).blob()}catch{}c&&(a.originalSrc=await P(c)),delete a.blob,delete a.originalBlob,o.push(a)}t[s.id]={name:s.name,pages:JSON.stringify(o)}}return t}async importDocs(e){let t=0;for(let[s,r]of Object.entries(e||{})){await this.getDoc(s)||t++;let i=this.#r(r.pages);await this.saveDoc(s,{name:r.name||"",pages:i})}return t}#r(e){if(Array.isArray(e))return[...e];if(typeof e=="string")try{return JSON.parse(e)}catch{return[]}return[]}},W=new g;var k="2026-11-06T14:33:27.433Z",z="0.1.5";function S(n={}){let e=n&&n.crop&&typeof n.crop=="object"?{x:Math.max(0,Math.min(1,Number(n.crop.x)||0)),y:Math.max(0,Math.min(1,Number(n.crop.y)||0)),w:Math.max(0,Math.min(1,Number(n.crop.w)||1)),h:Math.max(0,Math.min(1,Number(n.crop.h)||1))}:null,t=0,s=n?.rotate!==void 0?n.rotate:n?.rotation;if(s!==void 0){let o=(Math.round(Number(s)/90)*90%360+360)%360;(o===90||o===180||o===270)&&(t=o)}let r=n&&n.filter==="bw"?"bw":"none";return{crop:e,rotate:t,filter:r}}function U(n){if(!n)return!1;let e=n.rotate!==void 0?n.rotate:n.rotation;return!!(n.crop||e&&e!==0||n.filter&&n.filter!=="none")}var d=n=>Math.round(n*1e6)/1e6;function M(n,e=0){if(!n)return null;let t=(Math.round(Number(e)/90)*90%360+360)%360,{x:s,y:r,w:o,h:i}=n;return t===90?{x:d(Math.max(0,Math.min(1,1-r-i))),y:d(Math.max(0,Math.min(1,s))),w:d(Math.max(.01,Math.min(1,i))),h:d(Math.max(.01,Math.min(1,o)))}:t===180?{x:d(Math.max(0,Math.min(1,1-s-o))),y:d(Math.max(0,Math.min(1,1-r-i))),w:d(Math.max(.01,Math.min(1,o))),h:d(Math.max(.01,Math.min(1,i)))}:t===270?{x:d(Math.max(0,Math.min(1,r))),y:d(Math.max(0,Math.min(1,1-s-o))),w:d(Math.max(.01,Math.min(1,i))),h:d(Math.max(.01,Math.min(1,o)))}:{x:d(Math.max(0,Math.min(1,s))),y:d(Math.max(0,Math.min(1,r))),w:d(Math.max(.01,Math.min(1,o))),h:d(Math.max(.01,Math.min(1,i)))}}function j(n,e=0){return M(n,e)}function G(n,e=0){return M(n,-e)}var y=class{constructor(e){this.id=e.id,this.src=e.src,this.originalSrc=e.originalSrc||e.src,this.edits=S(e.edits),this.name=e.name||"Page",this.type=e.type||"image",this.orientation=e.orientation||1,this.ocrText=e.ocrText||null,this.ocrConfidence=e.ocrConfidence??null,this.ocrWords=Array.isArray(e.ocrWords)?e.ocrWords:null,this.ocrWidth=typeof e.ocrWidth=="number"?e.ocrWidth:null,this.ocrHeight=typeof e.ocrHeight=="number"?e.ocrHeight:null}get isModified(){return U(this.edits)}toJSON(){return{id:this.id,src:this.src,originalSrc:this.originalSrc,edits:this.edits,name:this.name,type:this.type,orientation:this.orientation,ocrText:this.ocrText,ocrConfidence:this.ocrConfidence,ocrWords:this.ocrWords,ocrWidth:this.ocrWidth,ocrHeight:this.ocrHeight}}},A=class{constructor(e){this.id=e.id,this.name=e.name||"Untitled Document",this.pages=Array.isArray(e.pages)?e.pages.map(t=>t instanceof y?t:new y(t)):[],this.createdAt=e.createdAt||Date.now(),this.updatedAt=e.updatedAt||Date.now()}get pageCount(){return this.pages.length}toJSON(){return{id:this.id,name:this.name,pages:this.pages.map(e=>e.toJSON()),createdAt:this.createdAt,updatedAt:this.updatedAt}}},b=class{constructor(e={}){this.mode=e.mode==="single"?"single":"batch",this.aspect=e.aspect||"auto",this.docId=e.docId||null,this.maxPages=Math.max(0,Number(e.maxPages)||0),this.stage="viewfinder",this.activePageIndex=0,this.history=[],this.future=[]}pushHistory(e){this.history.push(e),this.future=[],this.history.length>50&&this.history.shift()}undo(){if(this.history.length===0)return null;let e=this.history.pop();return this.future.push(e),e}redo(){if(this.future.length===0)return null;let e=this.future.pop();return this.history.push(e),e}};var H={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 J(n,e,t={}){let s=new CustomEvent(e,{bubbles:!0,composed:!0,cancelable:!0,detail:t});return n&&typeof n.dispatchEvent=="function"&&n.dispatchEvent(s),s}var I=["crop","rotate","filter","ocr","export","sync"],_=["pdf","zip","png","jpg"],T=["eng"],C={};function Se(n,e){!n||!e||(C[n]=e,typeof globalThis<"u"&&(globalThis.__copio_services__=globalThis.__copio_services__||{},globalThis.__copio_services__[n]=e))}function p(n){return C[n]?C[n]:typeof globalThis<"u"&&globalThis.__copio_services__?.[n]?globalThis.__copio_services__[n]:null}function K(n){return n?n instanceof Set?new Set(n):Array.isArray(n)?new Set(n.map(e=>String(e).trim().toLowerCase()).filter(Boolean)):typeof n=="string"?new Set(n.split(/[\s,]+/).map(e=>e.trim().toLowerCase()).filter(Boolean)):new Set(I):new Set(I)}function x(n,e){return n?Array.isArray(n)?n.map(t=>String(t).trim().toLowerCase()).filter(Boolean):typeof n=="string"?n.split(/[\s,]+/).map(t=>t.trim().toLowerCase()).filter(Boolean):[...e]:[...e]}var $=class{#e=new Set(I);#t=[..._];#i=[...T];#n=0;#d="";#r=null;#s=null;#l={};#a=!0;#h=!0;#o=null;#c=new Map;#u=new Map;constructor(e={}){this.#r=e.storage||D(e),this.#s=e.repository||new g(this.#r),e.services&&(this.#l={...e.services}),e.imageProcessor?(this.#o=e.imageProcessor,this.#l.imageProcessor=e.imageProcessor):this.getService("imageProcessor")?this.#o=this.getService("imageProcessor"):typeof document<"u"?this.#o=new L:this.#o=new N,e.features!==void 0&&this.setFeatures(e.features),e.exportFormats!==void 0&&(this.#t=x(e.exportFormats,_)),e.ocrLanguages!==void 0&&(this.#i=x(e.ocrLanguages,T)),e.maxPages!==void 0&&(this.#n=Math.max(0,Number(e.maxPages)||0)),e.assetBase!==void 0&&v(e.assetBase),e.licenseKey!==void 0&&(this.#d=String(e.licenseKey||"")),e.ocr!==void 0?this.ocr=!!e.ocr:e.features!==void 0&&!this.hasFeature("ocr")&&(this.ocr=!1),e.pdf!==void 0?this.pdf=!!e.pdf:e.exportFormats!==void 0&&!this.#t.includes("pdf")&&(this.pdf=!1)}async init(){return this.#r.init()}setService(e,t){this.#l[e]=t}getService(e){return this.#l[e]||p(e)}hasFeature(e){return e?this.#e.has(String(e).trim().toLowerCase()):!1}get features(){return Array.from(this.#e)}setFeatures(e){this.#e=K(e),this.hasFeature("ocr")?(this.#a=!0,this.getService("ocr")instanceof f&&this.setService("ocr",p("ocr"))):(this.#a=!1,this.setService("ocr",new f))}enableFeature(e){if(e){let t=String(e).trim().toLowerCase();this.#e.add(t),t==="ocr"&&(this.#a=!0,this.getService("ocr")instanceof f&&this.setService("ocr",p("ocr")))}}disableFeature(e){if(e){let t=String(e).trim().toLowerCase();this.#e.delete(t),t==="ocr"&&(this.#a=!1,this.setService("ocr",new f))}}get ocr(){return this.#a&&this.hasFeature("ocr")}set ocr(e){this.#a=!!e,this.#a?(this.enableFeature("ocr"),this.getService("ocr")instanceof f&&this.setService("ocr",p("ocr"))):(this.disableFeature("ocr"),this.setService("ocr",new f))}get pdf(){return this.#h&&this.#t.includes("pdf")}set pdf(e){this.#h=!!e,this.#h?(this.#t.includes("pdf")||this.#t.push("pdf"),this.getService("pdf")instanceof w&&this.setService("pdf",p("pdf"))):(this.#t=this.#t.filter(t=>t!=="pdf"),this.setService("pdf",new w))}get exportFormats(){return[...this.#t]}set exportFormats(e){this.#t=x(e,_),this.#t.includes("pdf")?(this.#h=!0,this.getService("pdf")instanceof w&&this.setService("pdf",p("pdf"))):(this.#h=!1,this.setService("pdf",new w))}get ocrLanguages(){return[...this.#i]}set ocrLanguages(e){this.#i=x(e,T)}get maxPages(){return this.#n}set maxPages(e){this.#n=Math.max(0,Number(e)||0)}get assetBase(){return B()}set assetBase(e){v(e)}get licenseKey(){return this.#d}set licenseKey(e){this.#d=String(e||"")}get storage(){return this.#r}setStorage(e){e&&(this.#r=e,this.#s=new g(this.#r))}#f(e,t){this.#c.has(e)||this.#c.set(e,[]);let s=this.#c.get(e);s.push(t),s.length>50&&s.shift(),this.#u.has(e)&&(this.#u.get(e).length=0)}get imageProcessor(){return this.#o}setImageProcessor(e){e&&(this.#o=e,this.setService("imageProcessor",e))}async renderEdits(e,t){if(!e)return"";let s=S(t);return this.#o?this.#o.renderEdits(e,s):R(e,s)}get docs(){return this.#s}async listDocuments(){return this.#s.listDocs()}async getDocument(e){return this.#s.getDoc(e)}async createDocument(e,t){return this.#s.createDoc(e,t)}async deleteDocument(e,t={}){return this.#s.deleteDoc(e,t)}async undoDeleteDocument(e){return this.#s.undoDeleteDoc(e)}async renameDocument(e,t){return this.#s.renameDoc(e,t)}async addPages(e,t){return this.#s.addPages(e,t)}async deletePage(e,t,s={}){return this.#f(e,{type:"delete",pageId:t}),this.#s.deletePage(e,t,s)}async undoDeletePage(e,t){return this.#s.undoDeletePage(e,t)}async updatePage(e,t,s){return this.#s.updatePage(e,t,s)}async reorderPages(e,t){let s=await this.getDocument(e),r=s?.pages?s.pages.map(o=>o.id):[];return this.#f(e,{type:"reorder",priorOrder:r,newOrder:[...t]}),this.#s.reorderPages(e,t)}async#g(e){if(e)return e;let t=await this.listDocuments();return t.length>0?t[0].id:null}async applyEdit(e,t,s){let r=await this.#g(e),o=r?await this.getDocument(r):null;if(!o||!o.pages)throw new Error(`Document with ID "${r||e}" not found`);let i=o.pages.find(E=>E.id===t);if(!i)throw new Error(`Page with ID "${t}" not found in document "${r}"`);let a={...i.edits||{crop:null,rotate:0,filter:"none"}},u=i.src,c=S({...a,...s}),h=i.originalSrc||i.src,l=h;return this.#o&&(l=await this.#o.renderEdits(h,c)),await this.updatePage(r,t,{originalSrc:h,src:l,edits:c}),this.#f(r,{type:"edit",pageId:t,priorEdits:a,priorSrc:u,newEdits:c,newSrc:l}),{...i,originalSrc:h,src:l,edits:c}}async undo(e){let t=await this.#g(e),s=t?this.#c.get(t):null;if(!s||s.length===0)return null;let r=s.pop();return this.#u.has(t)||this.#u.set(t,[]),this.#u.get(t).push(r),r.type==="edit"?(await this.updatePage(t,r.pageId,{edits:r.priorEdits,src:r.priorSrc}),{type:"edit",pageId:r.pageId,restoredEdits:r.priorEdits}):r.type==="delete"?(await this.undoDeletePage(t,r.pageId),{type:"delete",pageId:r.pageId}):r.type==="reorder"?(await this.#s.reorderPages(t,r.priorOrder),{type:"reorder",priorOrder:r.priorOrder}):r}async redo(e){let t=await this.#g(e),s=t?this.#u.get(t):null;if(!s||s.length===0)return null;let r=s.pop();return this.#c.has(t)||this.#c.set(t,[]),this.#c.get(t).push(r),r.type==="edit"?(await this.updatePage(t,r.pageId,{edits:r.newEdits,src:r.newSrc}),{type:"edit",pageId:r.pageId,appliedEdits:r.newEdits}):r.type==="delete"?(await this.deletePage(t,r.pageId),{type:"delete",pageId:r.pageId}):r.type==="reorder"?(await this.reorderPages(t,r.newOrder),{type:"reorder",newOrder:r.newOrder}):r}subscribe(e){return this.#s.subscribe(e)}async addFiles(e,t=null){if(!e||e.length===0)return[];let s=Array.from(e),r=[];for(let i of s)if(i.type==="application/pdf"){let a=this.getService("pdf");if(a&&typeof a.renderPdfPagesToDataUrls=="function"){let u=await a.renderPdfPagesToDataUrls(i);for(let c of u)r.push({id:m(),src:c,originalSrc:c,edits:{crop:null,rotation:0,filter:"none"},type:"image",name:i.name||"PDF Page"})}else console.warn("PDF import service (PdfPort) not registered. Skipping PDF file.")}else if(i.type&&i.type.startsWith("image/")){let a=await O(i),u=null;try{u=await F(i)}catch{}r.push({id:m(),src:a,originalSrc:a,edits:{crop:null,rotation:0,filter:"none"},type:"image",name:i.name||"Captured Image",orientation:u})}if(r.length===0)return[];await this.init();let o=t;if(o)await this.getDocument(o)||await this.#s.saveDoc(o,{name:"Scanned Document",pages:[]});else{let i=await this.listDocuments();i.length>0?o=i[0].id:o=(await this.createDocument("Scanned Document",[])).id}if(this.#n>0){let i=(await this.getDocument(o))?.pages||[],a=Math.max(0,this.#n-i.length);if(a<=0)throw new Error(`Maximum page limit (${this.#n}) reached`);r.splice(a)}return await this.addPages(o,r),r}async getPages(e=null){let t=e;if(!t){let r=await this.listDocuments();if(r.length===0)return[];t=r[0].id}return(await this.getDocument(t))?.pages||[]}async clear(e=null){let t=e;if(!t){let r=await this.listDocuments();if(r.length===0)return;t=r[0].id}let s=await this.getDocument(t);if(!(!s||!s.pages))for(let r of s.pages)await this.deletePage(t,r.id)}async#p(e){if(Array.isArray(e))return{docName:"document",pages:e,docId:null};if(typeof e=="string"){let s=await this.getDocument(e);return{docName:s?.name||"document",pages:s?.pages||[],docId:e}}let t=await this.listDocuments();if(t.length>0){let s=await this.getDocument(t[0].id);return{docName:s?.name||"document",pages:s?.pages||[],docId:t[0].id}}return{docName:"document",pages:[],docId:null}}async exportPdf(e,t={}){if(!this.hasFeature("export")){let i=new Error('Feature "export" is disabled');throw Object.assign(i,{code:"FEATURE_DISABLED"}),i}if(!this.#h||!this.#t.includes("pdf")){let i=new Error('Feature "pdf" is disabled');throw Object.assign(i,{code:"FEATURE_DISABLED"}),i}let{docName:s,pages:r}=await this.#p(e),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(s,r,{download:!1,showProgress:!1,onOcrComplete:async()=>{if(typeof e=="string"){let i=await this.#r.getDoc(e);i&&(i.pages=r,await this.#r.saveDoc(e,i))}},...t})}async exportZip(e,t={}){if(!this.hasFeature("export")){let i=new Error('Feature "export" is disabled');throw Object.assign(i,{code:"FEATURE_DISABLED"}),i}let{docName:s,pages:r}=await this.#p(e),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(s,r,{download:!1,showProgress:!1,...t})}async runOcr(e,t=null,s={}){if(!this.#a||!this.hasFeature("ocr")){let c=new Error('Feature "ocr" is disabled');throw Object.assign(c,{code:"FEATURE_DISABLED"}),c}let{pages:r}=await this.#p(e),o=r;t&&(o=r.filter(c=>c.id===t));let i=this.getService("ocr");if(!i||typeof i.recognizeDocumentPages!="function")throw new Error("OCR service (OcrPort) is not registered. Import @copio/sdk or register an ocrService.");let a=s.lang||this.#i[0]||"eng",u=await i.recognizeDocumentPages(o,{lang:a,...s});if(Array.isArray(u.pagesResults)){for(let c of u.pagesResults){let h=o.find(l=>l.id===c.pageId)||o[c.pageIndex];h&&(h.ocrText=c.text,h.ocrConfidence=c.confidence,h.ocrWords=c.words)}if(typeof e=="string"){let c=await this.#r.getDoc(e);if(c&&Array.isArray(c.pages)){for(let h of u.pagesResults){let l=c.pages.find(E=>E.id===h.pageId)||c.pages[h.pageIndex];l&&(l.ocrText=h.text,l.ocrConfidence=h.confidence,l.ocrWords=h.words)}await this.#r.saveDoc(e,c)}}}return{text:u.combinedText,...u}}async sync(e={}){if(!this.hasFeature("sync")){let s=new Error('Feature "sync" is disabled');throw Object.assign(s,{code:"FEATURE_DISABLED"}),s}let t=this.getService("sync");if(!t)throw new Error("Sync service (SyncPort) is not registered. Import @copio/sdk or register a syncService.");return new t(this.#s,e.onStateChange)}};export{g as a,W as b,k as c,z as d,S as e,U as f,M as g,j as h,G as i,y as j,A as k,b as l,H as m,J as n,I as o,_ as p,T as q,Se as r,p as s,$ as t};
|
|
2
|
+
//# sourceMappingURL=chunk-O7IV7A6O.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{h as L,i as M,m as c,n as z,t as A}from"./chunk-
|
|
1
|
+
import{h as L,i as M,m as c,n as z,t as A}from"./chunk-O7IV7A6O.js";import{a as S,b as I}from"./chunk-YNY65JUJ.js";import{b as R}from"./chunk-ZT72PD2C.js";var P=`
|
|
2
2
|
:host {
|
|
3
3
|
all: initial;
|
|
4
4
|
display: block;
|
|
@@ -1392,4 +1392,4 @@ import{h as L,i as M,m as c,n as z,t as A}from"./chunk-IBF5HCYT.js";import{a as
|
|
|
1392
1392
|
</div>
|
|
1393
1393
|
</div>
|
|
1394
1394
|
`}catch(i){o.innerHTML=`<p class="copio-ocr-error">OCR recognition failed: ${i.message}</p>`}}}#T(){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.#g===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((i,r)=>({id:i.id,pageNumber:r+1,label:i.label||`Page ${r+1}`,originalSrc:i.originalSrc,src:i.src,originalPreserved:!0,dimensions:{width:i.width||0,height:i.height||0},edits:i.edits||{crop:{x:0,y:0,w:1,h:1},rotate:0,filter:"none"},ocrText:i.ocrText||null,blob:i.blob||null})),o={mode:this.mode,aspect:this.aspect,docId:this.docId,pageCount:e.length,pages:e};this.mode==="single"&&(o.page=e[0]||null,this.maxPages>1&&(o.maxPages=this.maxPages)),this.dispatch(c.SCAN_COMPLETE,o)}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.#n}set stage(t){if(t==="viewfinder"||t==="workbench"){this.#n=t,typeof this.setAttribute=="function"&&this.getAttribute("stage")!==t&&this.setAttribute("stage",t);let e=this.shadowRoot;if(e){let o=e.getElementById("viewfinder-section"),i=e.getElementById("workbench-section");o&&i&&(o.style.display=t==="viewfinder"?"flex":"none",i.style.display=t==="workbench"?"flex":"none")}this.#o()}}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.#k()}async toggleActivePageBw(){return this.#E()}async toggleCropMode(){return this.#S()}async deleteActivePageWithUndo(){return this.#C()}setCameraStream(t){this.#d(),this.#c=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.#p()}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.#p()}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.#b}set storage(t){this.#b=t,this.#t&&this.#t.setStorage(t)}get engine(){return this.#t}set engine(t){t instanceof A&&(this.#t=t)}dispatch(t,e={}){return z(this,t,e)}async open(){this.#m=!0,typeof this.focus=="function"&&this.focus()}async close(){this.#m=!1,this.#d()}get isOpen(){return this.#m}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 o=await this.addFiles([e.files[0]]);t(o[0]||null)}else t(null)}catch(o){this.dispatch(c.ERROR,{code:"CAPTURE_FAILED",message:o.message,error:o}),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(),o=null;if(e.length>0){if(this.mode==="single"&&this.maxPages<=1)await this.#t.clear(this.#r);else if(this.#f||this.maxPages>0&&e.length>=this.maxPages){let a=Math.min(this.#e,e.length-1),s=e[a];s&&(o=a,await this.#t.deletePage(this.#r,s.id))}}this.#f=!1;let i=await this.#t.addFiles(t,this.#r);for(let a=0;a<i.length;a++)this.dispatch(c.PAGE_ADDED,{page:i[a],pageNumber:a+1,docId:this.docId,source:"file"});let r=await this.getPages();if(o!==null&&i.length===1&&o<r.length-1){let a=r.map(p=>p.id),s=a.pop();s&&(a.splice(o,0,s),await this.#t.reorderPages(this.#r,a),r=await this.getPages())}return this.#g=r.length,i.length>0&&(this.#e=o!==null?Math.min(o,Math.max(0,r.length-1)):Math.max(0,r.length-1),this.mode==="single"&&(this.#n="workbench",typeof this.setAttribute=="function"&&this.getAttribute("stage")!=="workbench"&&this.setAttribute("stage","workbench"))),this.dispatch(c.PAGES_CHANGED,{pages:r,docId:this.docId}),this.mode==="single"&&i.length>0&&this.maxPages<=1&&this.dispatch(c.SCAN_COMPLETE,{mode:this.mode,aspect:this.aspect,docId:this.docId,pages:r,page:r[r.length-1]||null,pageCount:r.length}),await this.#o(),i}catch(e){throw this.dispatch(c.ERROR,{code:e.code||"ADD_FILES_FAILED",message:e.message,error:e}),e}}async getPages(){return this.#t.getPages(this.#r)}async clear(){this.#d(),this.#e=0,this.#g=0,this.#f=!1,this.#i=!1,await this.#t.clear(this.#r),this.dispatch(c.PAGES_CHANGED,{pages:[],docId:this.docId}),await this.#o()}async exportPdf(t={}){try{let e=await this.#t.exportPdf(this.#r,t);return this.dispatch(c.EXPORT_COMPLETE,{type:"pdf",format:"pdf",blob:e,searchable:!!t.searchable,docId:this.docId}),e}catch(e){throw this.dispatch(c.ERROR,{code:e.code||"EXPORT_FAILED",message:e.message,error:e}),e}}async exportZip(t={}){try{let e=await this.#t.exportZip(this.#r,t);return this.dispatch(c.EXPORT_COMPLETE,{type:"zip",format:"zip",blob:e,docId:this.docId}),e}catch(e){throw this.dispatch(c.ERROR,{code:e.code||"EXPORT_FAILED",message:e.message,error:e}),e}}async ocr(t=null,e={}){try{let o=await this.#t.runOcr(this.#r,t,e);return this.dispatch(c.OCR_COMPLETE,{text:o.text,pages:o.pagesResults,averageConfidence:o.averageConfidence,docId:this.docId,pageId:t}),o}catch(o){throw this.dispatch(c.ERROR,{code:o.code||"OCR_FAILED",message:o.message,error:o}),o}}async runOcr(t=null,e={}){return this.ocr(t,e)}async sync(t={}){try{return await this.#t.sync({onStateChange:o=>{o&&(o.step==="connected"||o.step==="syncing")&&this.dispatch(c.SYNC_CONNECTED,{peerId:o.peerId,mode:o.mode}),t.onStateChange&&t.onStateChange(o)}})}catch(e){throw this.dispatch(c.ERROR,{code:e.code||"SYNC_FAILED",message:e.message,error:e}),e}}};typeof customElements<"u"&&!customElements.get("copio-scanner")&&customElements.define("copio-scanner",B);export{P as a,T as b,O as c,B as d};
|
|
1395
|
-
//# sourceMappingURL=chunk-
|
|
1395
|
+
//# sourceMappingURL=chunk-Q7XPZMZA.js.map
|
package/dist/core.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as o,b as p,c as q,d as r,e as x,f as y,g as z,h as A,i as B,j as C,k as D,l as E,m as F,n as G,o as H,p as I,q as J,r as K,s as L,t as M}from"./chunk-
|
|
1
|
+
import{a as o,b as p,c as q,d as r,e as x,f as y,g as z,h as A,i as B,j as C,k as D,l as E,m as F,n as G,o as H,p as I,q as J,r as K,s as L,t as M}from"./chunk-O7IV7A6O.js";import"./chunk-4GEMGDRU.js";import{a as e,b as f,c as g,d as h,e as i,f as j,g as k,h as l,i as m,j as n,k as v}from"./chunk-G5EUMLYT.js";import{a as w}from"./chunk-KH5JE65X.js";import{a as u}from"./chunk-ULTSZWZO.js";import{c as d}from"./chunk-K4NR6OAC.js";import{d as c}from"./chunk-L4OVZN23.js";import{a as s}from"./chunk-U3V3VZGO.js";import"./chunk-6DSLE3AY.js";import{a as t}from"./chunk-5OTO5WFV.js";import"./chunk-O6FQFVKY.js";import"./chunk-ZT72PD2C.js";import{a as b}from"./chunk-FQRADJY6.js";import{a}from"./chunk-DIU5BGU5.js";import"./chunk-4C666HHU.js";export{q as BUILD_DATE,F as COPIO_EVENTS,v as Canvas2DAdapter,M as CopioEngine,I as DEFAULT_EXPORT_FORMATS,H as DEFAULT_FEATURES,J as DEFAULT_OCR_LANGUAGES,o as DocRepository,D as Document,u as ImageProcessorPort,c as IndexedDbStorageAdapter,b as MemoryStorageAdapter,w as NullImageProcessorAdapter,s as NullOcrAdapter,t as NullPdfAdapter,C as Page,E as ScanSession,a as StoragePort,r as VERSION,n as applyEdits,h as applySauvolaToImageData,d as createDefaultAdapter,A as cropOriginalToRotated,B as cropRotatedToOriginal,G as dispatchCopioEvent,p as docRepository,e as extractExif,g as fileToBase64,k as getCroppedSrc,L as getRegisteredService,y as hasActiveEdits,x as normalizeEditStack,l as normalizeEdits,f as randomId,K as registerService,m as renderEditsToCanvas,z as rotateCrop,j as rotateSrc,i as thresholdSrc};
|
|
2
2
|
//# sourceMappingURL=core.js.map
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as ge,b as he,c as me,d as fe}from"./chunk-
|
|
1
|
+
import{a as ge,b as he,c as me,d as fe}from"./chunk-Q7XPZMZA.js";import{a as N,b as c,c as V,d as F,e as ee,f as te,j as se,k as re,l as oe,m as ie,n as ae,r as a,s as ne,t as le}from"./chunk-O7IV7A6O.js";import{a as o,b,c as ye}from"./chunk-NQW6FFN7.js";import"./chunk-V6E2SSSW.js";import{a as Te}from"./chunk-2AB5L3Y2.js";import{a as Ce}from"./chunk-J7HWZNIP.js";import{a as Ae}from"./chunk-NEEWG3OP.js";import"./chunk-PUJYN435.js";import{a as u}from"./chunk-4ICUYKSR.js";import"./chunk-CWCS22CQ.js";import{a as ve,b as x}from"./chunk-GGERQ3CJ.js";import"./chunk-4GEMGDRU.js";import{a as I,b as R,c as k,e as D,f as E,g as _,k as d}from"./chunk-G5EUMLYT.js";import{a as Y}from"./chunk-KH5JE65X.js";import{a as X}from"./chunk-ULTSZWZO.js";import{a as O,b as P,c as w}from"./chunk-K4NR6OAC.js";import{d as $}from"./chunk-L4OVZN23.js";import{a as Z}from"./chunk-U3V3VZGO.js";import{a as Q}from"./chunk-6DSLE3AY.js";import{a as H}from"./chunk-5OTO5WFV.js";import{a as q}from"./chunk-O6FQFVKY.js";import{b as f}from"./chunk-WETG2JD7.js";import{a as g,b as ue,c as xe,d as h,e as m}from"./chunk-FAVTIE3M.js";import{a as be,b as Se,c as S}from"./chunk-MEE2NNYB.js";import{a as ce,b as pe,c as de,d as n}from"./chunk-YNY65JUJ.js";import{a as M,b as L,c as z,d as U,e as W,f as B,g as K,h as G,i as j,j as J}from"./chunk-ZT72PD2C.js";import{a as T}from"./chunk-FQRADJY6.js";import{a as C}from"./chunk-DIU5BGU5.js";import"./chunk-4C666HHU.js";var p=class extends b{#e=null;static properties={isOpen:{type:Boolean,state:!0},docId:{type:String,state:!0},docName:{type:String,state:!0},pages:{type:Array,state:!0},lang:{type:String,state:!0},step:{type:String,state:!0},progress:{type:Number,state:!0},statusMessage:{type:String,state:!0},resultText:{type:String,state:!0},confidence:{type:Number,state:!0},copied:{type:Boolean,state:!0}};createRenderRoot(){return this}disconnectedCallback(){super.disconnectedCallback(),this.#e&&(this.#e.abort(),this.#e=null),m(),this.isOpen=!1}constructor(){super(),this.isOpen=!1,this.docId="",this.docName="",this.pages=[],this.lang="eng",this.step="processing",this.progress=0,this.statusMessage="Starting OCR engine...",this.resultText="",this.confidence=0,this.copied=!1,this._pageIndex=null,this.#e=null}open(e,r,s,t="eng"){this._pageIndex=null,this._openInternal(e,r,s,t)}openPage(e,r,s,t,i="eng"){this._pageIndex=t,this._openInternal(e,r,[s],i)}_openInternal(e,r,s,t){if(this.#e&&(this.#e.abort(),this.#e=null),this.docId=e,this.docName=r||"Document",this.pages=s||[],this.lang=t,this.progress=0,this.resultText="",this.confidence=0,this.copied=!1,(this.pages||[]).filter(l=>l.src).length===0){this.step="empty",this.statusMessage="This document does not contain any image pages for text recognition.",this.isOpen=!0;return}this.step="processing",this.statusMessage=typeof window<"u"&&!window.Tesseract?"Downloading OCR engine...":"Starting OCR engine...",this.isOpen=!0,this.startOcr(t)}cancel=()=>{this.#e&&(this.#e.abort(),this.#e=null),this.close()};close=()=>{this.#e&&(this.#e.abort(),this.#e=null),this.isOpen=!1};async startOcr(e="eng"){this.#e&&(this.#e.abort(),this.#e=null),this.#e=new AbortController;let{signal:r}=this.#e;try{let s=await h(this.pages,{lang:e,abortSignal:r,onPageProgress:({overallProgress:t,message:i})=>{this.isOpen&&!r.aborted&&(this.progress=Math.round((t||0)*100),this.statusMessage=i)}});if(this.isOpen&&!r.aborted&&(this.step="done",this.resultText=s.combinedText||"",this.confidence=s.averageConfidence||0,n.success("Text recognition complete"),this.docId&&Array.isArray(s.pagesResults)))try{let t=await c.getDoc(this.docId);if(t&&Array.isArray(t.pages)){for(let i of s.pagesResults){let l=t.pages.find(A=>A.id===i.pageId)||t.pages[i.pageIndex];l&&(l.ocrText=i.text,l.ocrConfidence=i.confidence,l.ocrWords=i.words)}await c.saveDoc(this.docId,t)}}catch(t){console.warn("Could not persist OCR results to document:",t)}}catch(s){if(s.name==="AbortError"||r.aborted)return;console.error("Document OCR Error:",s),this.isOpen&&(this.step="error",this.statusMessage=s.message||"Text recognition failed",n.error(s.message||"Text recognition failed"))}finally{this.#e?.signal===r&&(this.#e=null)}}handleLangChange=e=>{let r=e.target.value;this.lang=r,this.step="processing",this.progress=0,this.statusMessage="Starting OCR engine with new language...",this.startOcr(r)};handleTextInput=e=>{this.resultText=e.target.value};copyText=async()=>{if(this.resultText)try{await navigator.clipboard.writeText(this.resultText),this.copied=!0,n.success("Copied text to clipboard"),setTimeout(()=>{this.copied=!1},2e3)}catch(e){console.error("Failed to copy text:",e),n.error("Failed to copy text to clipboard")}};downloadText=()=>{if(!this.resultText)return;let e=(this.docName||"document").replace(/[/\\?%*:|"<>]/g,"_"),r=new Blob([this.resultText],{type:"text/plain;charset=utf-8"}),s=URL.createObjectURL(r),t=document.createElement("a");t.href=s,t.download=`${e}-ocr.txt`,t.click(),URL.revokeObjectURL(s),n.success(`Exported OCR text (${e}-ocr.txt)`)};get _isSinglePage(){return this._pageIndex!==null}get _dialogLabel(){return this._isSinglePage?`Extract Text \u2014 ${this.docName} (Page ${this._pageIndex+1})`:`Extract All Text \u2014 ${this.docName}`}render(){return this.isOpen?o`
|
|
2
2
|
<sl-dialog
|
|
3
3
|
label="${this._dialogLabel}"
|
|
4
4
|
open
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export declare const BUILD_DATE: string;
|
|
2
|
-
export declare const VERSION = "0.1.
|
|
2
|
+
export declare const VERSION = "0.1.5";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@copio/sdk",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.5",
|
|
4
4
|
"description": "Embeddable Web Components and Headless Services for Document Scanning, OCR, Editing, and P2P Sync.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -95,4 +95,4 @@
|
|
|
95
95
|
"oxlint": "^1.88.0",
|
|
96
96
|
"typescript": "^7.0.2"
|
|
97
97
|
}
|
|
98
|
-
}
|
|
98
|
+
}
|
package/sdk/version.js
CHANGED