@copio/sdk 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/THIRD_PARTY_NOTICES.md +34 -0
  2. package/dist/adapters/edge/index.js +2 -0
  3. package/dist/adapters/edge/index.js.map +7 -0
  4. package/dist/adapters/edge/null-edge-detector-adapter.js +2 -0
  5. package/dist/adapters/edge/null-edge-detector-adapter.js.map +7 -0
  6. package/dist/adapters/edge/scanic-wasm-adapter.js +2 -0
  7. package/dist/adapters/edge/scanic-wasm-adapter.js.map +7 -0
  8. package/dist/adapters/image/canvas2d-adapter.js +1 -1
  9. package/dist/adapters/image/index.js +1 -1
  10. package/dist/adapters/image/null-image-processor-adapter.js +1 -1
  11. package/dist/adapters/index.js +1 -1
  12. package/dist/adapters/indexeddb-adapter.js +1 -1
  13. package/dist/adapters/memory-adapter.js +1 -1
  14. package/dist/adapters/ocr/index.js +1 -1
  15. package/dist/adapters/ocr/null-ocr-adapter.js +1 -1
  16. package/dist/adapters/ocr/tesseract-wasm-adapter.js +1 -1
  17. package/dist/adapters/pdf/index.js +1 -1
  18. package/dist/adapters/pdf/null-pdf-adapter.js +1 -1
  19. package/dist/adapters/pdf/pdfkit-adapter.js +1 -1
  20. package/dist/adapters/storage/index.js +1 -1
  21. package/dist/adapters/storage/indexeddb-adapter.js +1 -1
  22. package/dist/adapters/storage/memory-adapter.js +1 -1
  23. package/dist/adapters/sync/index.js +1 -1
  24. package/dist/adapters/sync/null-sync-adapter.js +1 -1
  25. package/dist/adapters/sync/peerjs-adapter.js +1 -1
  26. package/dist/canvas-GKLGWNAJ.js +2 -0
  27. package/dist/cdn.js +189 -1409
  28. package/dist/chunk-25WAHT3G.js +2 -0
  29. package/dist/chunk-2VH2NPXW.js +175 -0
  30. package/dist/{chunk-DIU5BGU5.js → chunk-4D6GC55I.js} +2 -2
  31. package/dist/chunk-6QK7337A.js +2 -0
  32. package/dist/chunk-GLY5CGCY.js +2 -0
  33. package/dist/chunk-GU6OQMYK.js +4 -0
  34. package/dist/chunk-HCCNUPKB.js +2 -0
  35. package/dist/chunk-JIPKWRBK.js +2 -0
  36. package/dist/{chunk-GGERQ3CJ.js → chunk-NM4YYZYB.js} +3 -3
  37. package/dist/chunk-NNSM2I5L.js +2 -0
  38. package/dist/chunk-PBF7V4Z6.js +2 -0
  39. package/dist/chunk-PSGIWIRH.js +2 -0
  40. package/dist/chunk-Q7SOUI6D.js +2 -0
  41. package/dist/chunk-R6Q4OXDG.js +2 -0
  42. package/dist/chunk-SZHKZARU.js +2 -0
  43. package/dist/{chunk-J7HWZNIP.js → chunk-T5CPA7B2.js} +2 -2
  44. package/dist/chunk-V2D55DVU.js +1 -0
  45. package/dist/chunk-VPSUKD6F.js +2 -0
  46. package/dist/chunk-WZZ7FNDX.js +2 -0
  47. package/dist/chunk-ZILTJGT2.js +2 -0
  48. package/dist/core.js +1 -1
  49. package/dist/custom-elements.json +2358 -177
  50. package/dist/export.js +1 -1
  51. package/dist/fs-Y7NMZRBK.js +2 -0
  52. package/dist/handoff-transport-7YFK4RYL.js +2 -0
  53. package/dist/handoff.js +2 -0
  54. package/dist/http-CYZIMVXQ.js +2 -0
  55. package/dist/https-OLG7KUSR.js +2 -0
  56. package/dist/index.js +11 -11
  57. package/dist/ocr.js +1 -1
  58. package/dist/path2d-HD3LU76S.js +2 -0
  59. package/dist/scanic-mlDetector-BCSVQYFV.js +2 -0
  60. package/dist/scanic-ort.wasm.min-MU4NYSP2.js +2 -0
  61. package/dist/scanner.js +3 -1396
  62. package/dist/sync.js +1 -1
  63. package/dist/types/js/adapters/edge/edge-detector-port.d.ts +183 -0
  64. package/dist/types/js/adapters/edge/index.d.ts +3 -0
  65. package/dist/types/js/adapters/edge/null-edge-detector-adapter.d.ts +35 -0
  66. package/dist/types/js/adapters/edge/scanic-wasm-adapter.d.ts +54 -0
  67. package/dist/types/js/adapters/storage/indexeddb-adapter.d.ts +11 -0
  68. package/dist/types/js/adapters/storage/memory-adapter.d.ts +11 -0
  69. package/dist/types/js/adapters/storage/opfs-adapter.d.ts +11 -0
  70. package/dist/types/js/adapters/storage/storage-port.d.ts +27 -0
  71. package/dist/types/js/services/doc-repository.d.ts +6 -1
  72. package/dist/types/js/services/handoff-crypto.d.ts +84 -0
  73. package/dist/types/js/services/handoff-session.d.ts +257 -0
  74. package/dist/types/js/services/handoff-transport.d.ts +51 -0
  75. package/dist/types/js/services/ice-servers.d.ts +33 -1
  76. package/dist/types/js/services/migration-runner.d.ts +100 -0
  77. package/dist/types/js/utils/perspective.d.ts +70 -0
  78. package/dist/types/js/utils/utils.d.ts +19 -1
  79. package/dist/types/sdk/core.d.ts +52 -6
  80. package/dist/types/sdk/elements.d.ts +2 -0
  81. package/dist/types/sdk/events.d.ts +42 -0
  82. package/dist/types/sdk/handoff-session.d.ts +4 -0
  83. package/dist/types/sdk/handoff-styles.d.ts +9 -0
  84. package/dist/types/sdk/handoff.d.ts +108 -0
  85. package/dist/types/sdk/index.d.ts +5 -1
  86. package/dist/types/sdk/models.d.ts +248 -1
  87. package/dist/types/sdk/scanner.d.ts +94 -1
  88. package/dist/types/sdk/styles.d.ts +1 -1
  89. package/dist/types/sdk/version.d.ts +1 -1
  90. package/dist/url-NYR4TEJV.js +2 -0
  91. package/package.json +10 -3
  92. package/sdk/core.js +226 -13
  93. package/sdk/events.js +14 -0
  94. package/sdk/handoff-session.js +26 -0
  95. package/sdk/handoff-styles.js +531 -0
  96. package/sdk/handoff.js +1079 -0
  97. package/sdk/index.js +38 -1
  98. package/sdk/models.js +116 -4
  99. package/sdk/scanner.js +1517 -151
  100. package/sdk/styles.js +305 -22
  101. package/sdk/version.js +1 -1
  102. package/dist/canvas-FAXPLPXN.js +0 -2
  103. package/dist/chunk-4C666HHU.js +0 -2
  104. package/dist/chunk-FQRADJY6.js +0 -2
  105. package/dist/chunk-G5EUMLYT.js +0 -4
  106. package/dist/chunk-K4NR6OAC.js +0 -2
  107. package/dist/chunk-L4OVZN23.js +0 -2
  108. package/dist/chunk-MEE2NNYB.js +0 -2
  109. package/dist/chunk-O7IV7A6O.js +0 -2
  110. package/dist/chunk-Q7XPZMZA.js +0 -1395
  111. package/dist/chunk-WETG2JD7.js +0 -2
  112. package/dist/fs-HJ6WWW73.js +0 -2
  113. package/dist/http-FKJJMT2N.js +0 -2
  114. package/dist/https-MUBFLDZM.js +0 -2
  115. package/dist/path2d-QWN6DFCC.js +0 -2
  116. package/dist/url-ABJ6S2Y6.js +0 -2
package/dist/scanner.js CHANGED
@@ -1,1398 +1,5 @@
1
1
  /* @copio/sdk <copio-scanner> Web Component bundle */
2
- var _t=class{async init(){throw new Error("StoragePort.init() must be implemented by adapter")}async listDocs(){throw new Error("StoragePort.listDocs() must be implemented by adapter")}async getDoc(t){throw new Error("StoragePort.getDoc() must be implemented by adapter")}async saveDoc(t,e){throw new Error("StoragePort.saveDoc() must be implemented by adapter")}async renameDoc(t,e){let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);i.name=e,await this.saveDoc(t,i)}async deleteDoc(t){throw new Error("StoragePort.deleteDoc() must be implemented by adapter")}async savePage(t,e,i){throw new Error("StoragePort.savePage() must be implemented by adapter")}async getPage(t,e){throw new Error("StoragePort.getPage() must be implemented by adapter")}async deletePage(t,e){throw new Error("StoragePort.deletePage() must be implemented by adapter")}subscribe(t){return()=>{}}};var Le=class extends _t{#t=new Map;#r=new Map;#s=new Set;constructor(){super()}async init(){return{kind:"memory",persistent:!1}}listDocsSync(){return Array.from(this.#t.values()).map(t=>({id:t.id,name:t.name,pages:Array.isArray(t.pages)?[...t.pages]:[]}))}async listDocs(){return this.listDocsSync()}getDocSync(t){let e=this.#t.get(t);return e?{id:e.id,name:e.name,pages:Array.isArray(e.pages)?[...e.pages]:[]}:null}async getDoc(t){return this.getDocSync(t)}async saveDoc(t,e){if(!t)throw new Error("Cannot save document without an ID");let i=[];if(Array.isArray(e.pages))i=[...e.pages];else if(typeof e.pages=="string")try{i=JSON.parse(e.pages)}catch{i=[]}this.#t.set(t,{id:t,name:e.name||"",pages:i}),this.#l()}async deleteDoc(t){this.#t.delete(t);let e=`${t}/`;for(let i of this.#r.keys())i.startsWith(e)&&this.#r.delete(i);this.#l()}async renameDoc(t,e){let i=this.#t.get(t);if(!i)throw new Error(`Document "${t}" not found`);i.name=e,this.#l()}async savePage(t,e,i){this.#r.set(`${t}/${e}`,i);let s=this.#t.get(t);if(s){let o=s.pages.findIndex(n=>n.id===e);if(o>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?s.pages[o]={...s.pages[o],...i}:s.pages[o]={...s.pages[o],src:i};else{let n=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i};s.pages.push(n)}}this.#l()}async getPage(t,e){if(this.#r.has(`${t}/${e}`))return this.#r.get(`${t}/${e}`);let i=this.#t.get(t);if(i){let s=i.pages.find(o=>o.id===e);if(s)return s.src??s}return null}async deletePage(t,e){this.#r.delete(`${t}/${e}`);let i=this.#t.get(t);i&&(i.pages=i.pages.filter(s=>s.id!==e)),this.#l()}subscribe(t){return this.#s.add(t),()=>{this.#s.delete(t)}}clear(){this.#t.clear(),this.#r.clear(),this.#l()}#l(){for(let t of this.#s)try{t()}catch(e){console.error("Error in MemoryStorageAdapter subscriber:",e)}}};var se=r=>typeof r;var Ao=se(""),Vn=se(!0),Io=se(0),Wn=se(se),Wi="type",le="default",$r="Listener",xo="Result",Hr="add",de="Has",ni="Ids",re="Table",vo=re+"s",Gn=re+ni,Me="Row",Lo=Me+"Count",Ro=Me+ni,Kn="Sorted"+Me+ni,ri="Cell",Xi=ri+ni,Ji="Value",So=Ji+"s",qn=Ji+ni,at=r=>""+r;var Xn=(r,t="",e)=>r.split(t,e),_r=globalThis,er=Math,Or=er.max,Ur=er.min,Jn=er.floor,Bo=isFinite,H=r=>r==null,ct=(r,t,e)=>H(r)?e?.():t(r),To=r=>r==Ao||r==Vn,Yn=r=>se(r)==Ao,jt=r=>se(r)==Wn,Oe=r=>Array.isArray(r),Vr=(r,t,e)=>r.slice(t,e),Ot=r=>r.length,Mo=()=>{};var Fr=async(r,t,e)=>{try{return await r()}catch(i){t?.(i)}},Wr=(r,t)=>r.includes(t),Yi=(r,t)=>r.every(t),Oo=(r,t)=>Ot(r)===Ot(t)&&Yi(r,((e,i)=>t[i]===e)),ko=(r,t)=>Yi(r,((e,i)=>i==0||t(r[i-1],e)<=0)),Gr=(r,t)=>r.sort(t),Bt=(r,t)=>r.forEach(t),fe=(r,t)=>r.map(t),Po=r=>Uo(r,((t,e)=>t+e),0),si=r=>Ot(r)==0,Uo=(r,t,e)=>r.reduce(t,e),Rt=(r,...t)=>r.push(...t),Eo=r=>r.pop(),Fo=r=>r.shift(),Be=r=>{let t=se(r);return To(t)||t==Io&&Bo(r)?t:void 0};var Qi=(r,t,e,i,s)=>H(s)?r.delCell(t,e,i,!0):r.setCell(t,e,i,s),Kr=(r,t,e)=>H(e)?r.delValue(t):r.setValue(t,e),Yr=r=>t=>Uo(Ue(t),((e,i)=>e+r(i)),0),Fe=r=>r?.size??0,ue=Yr(Fe),Wt=Yr(ue),jr=Yr(Wt),ht=(r,t)=>r?.has(t)??!1,z=r=>H(r)||Fe(r)==0,Ue=r=>[...r?.values()??[]],Te=r=>r.clear(),j=(r,t)=>r?.forEach(t),Nt=(r,t)=>r?.delete(t),oe=Object,Co=r=>oe.getPrototypeOf(r),Qn=oe.isFrozen,jo=oe.entries,Zi=r=>!H(r)&&ct(Co(r),(t=>t==oe.prototype||H(Co(t))),(()=>!0)),Zn=oe.keys,je=oe.freeze,ta=(r=[])=>oe.fromEntries(r),ii=(r,t)=>t in r,zo=(r,t)=>(delete r[t],r),ea=(r,t)=>Bt(jo(r),(([e,i])=>t(i,e))),Vt=(r,t)=>ta(((e,i)=>fe(jo(e),(([s,o])=>i(o,s))))(r,((e,i)=>[i,t(e,i)]))),zt=r=>Zi(r)&&(t=>Ot(Zn(t)))(r)==0;var ee=(r,t,e,i=0)=>H(r)||!Zi(r)||!i&&zt(r)||Qn(r)?(e?.(),!1):(ea(r,((s,o)=>{t(s,o)||zo(r,o)})),!!i||!zt(r)),C=r=>new Map(r),pe=r=>[...r?.keys()??[]],v=(r,t)=>r?.get(t),bt=(r,t)=>j(r,((e,i)=>t(i,e))),T=(r,t,e)=>H(e)?(Nt(r,t),r):r?.set(t,e),dt=(r,t,e,i)=>(ht(r,t)?i?.(v(r,t)):T(r,t,e()),v(r,t)),he=(r,t,e,i=T)=>(Vt(t,((s,o)=>e(r,o,s))),bt(r,(s=>ii(t,s)?0:i(r,s))),r),Lt=(r,t,e,i)=>{let s={};return j(r,((o,n)=>{if(!e?.(o,n)){let c=t?t(o,n):o;i?.(c)||(s[n]=c)}})),s},qr=(r,t,e)=>Lt(r,(i=>Lt(i,t,e)),z,zt),Gi=(r,t,e)=>Lt(r,(i=>qr(i,t,e)),z,zt),ie=(r,t)=>{let e=C();return j(r,((i,s)=>e.set(s,t?.(i)??i))),e},Xr=r=>ie(r,ie),zr=r=>ie(r,Xr),oi=(r,t,e,i,s=0)=>ct((e?dt:v)(r,t[s],s>Ot(t)-2?e:C),(o=>{if(s>Ot(t)-2)return i?.(o)&&T(r,t[s]),o;let n=oi(o,t,e,i,s+1);return z(o)&&T(r,t[s]),n})),yt=r=>new Set(Oe(r)||H(r)?r:[r]),ft=(r,t)=>r?.add(t),ir=(r,t,e,i,s)=>{let o=r.hasRow,n=C(),c=C(),l=C(),d=C(),u=C(),h=C(),g=(x,w,...A)=>{let k=dt(h,x,yt);return Bt(A,(R=>ft(k,R)&&w&&r.callListener(R))),A},m=(x,...w)=>ct(v(h,x),(A=>{Bt(si(w)?Ue(A):w,(k=>{r.delListener(k),Nt(A,k)})),z(A)&&T(h,x)})),E=(x,w)=>{T(n,x,w),ht(c,x)||(T(c,x,t()),T(d,x,C()),T(u,x,C()),s(l))},D=x=>{T(n,x),T(c,x),T(d,x),T(u,x),m(x),s(l)};return[()=>r,()=>pe(n),x=>bt(c,x),x=>ht(c,x),x=>v(n,x),x=>v(c,x),(x,w)=>T(c,x,w),E,(x,w,A,k,R)=>{E(x,w);let U=C(),P=C(),y=v(d,x),B=v(u,x),_=N=>{let V=lt=>r.getCell(w,N,lt),et=v(y,N),nt=o(w,N)?e(k(V,N)):void 0;if(et===nt||Oe(et)&&Oe(nt)&&Oo(et,nt)||T(U,N,[et,nt]),!H(R)){let lt=v(B,N),q=o(w,N)?R(V,N):void 0;lt!=q&&T(P,N,q)}},G=N=>{A((()=>{j(U,(([,V],et)=>T(y,et,V))),j(P,((V,et)=>T(B,et,V)))}),U,P,y,B,N),Te(U),Te(P)};bt(y,_),r.hasTable(w)&&Bt(r.getRowIds(w),(N=>{ht(y,N)||_(N)})),G(!0),m(x),g(x,0,r.addRowListener(w,null,((N,V,et)=>_(et))),r.addTableListener(w,(()=>G())))},D,x=>i(x,l),()=>bt(h,D),g,m]},tr=(r,t)=>Yn(r)?e=>e(r):r??(()=>t??""),ai=(r,t)=>{let e=new WeakMap;return i=>{e.has(i)||e.set(i,r(i));let s=e.get(i);return t?.(s),s}},ia=/^\d+$/,No=()=>{let r=[],t=0;return[e=>(e?Fo(r):null)??""+t++,e=>{ia.test(e)&&Ot(r)<1e3&&Rt(r,e)}]},ci=r=>{let t,[e,i]=No(),s=C();return[(o,n,c,l=[],d=()=>[])=>{t??=r();let u=e(1);return T(s,u,[o,n,c,l,d]),ft(oi(n,c??[""],yt),u),u},(o,n,...c)=>Bt(((l,d=[""])=>{let u=[],h=(g,m)=>m==Ot(d)?Rt(u,g):d[m]===null?j(g,(E=>h(E,m+1))):Bt([d[m],null],(E=>h(v(g,E),m+1)));return h(l,0),u})(o,n),(l=>j(l,(d=>v(s,d)[0](t,...n??[],...c))))),o=>ct(v(s,o),(([,n,c])=>(oi(n,c??[""],void 0,(l=>(Nt(l,o),z(l)?1:0))),T(s,o),i(o),c))),o=>ct(v(s,o),(([n,,c=[],l,d])=>{let u=(...h)=>{let g=Ot(h);g==Ot(c)?n(t,...h,...d(h)):H(c[g])?Bt(l[g]?.(...h)??[],(m=>u(...h,m))):u(...h,c[g])};u()}))]},dc=ai((r=>{let t,e,i,s=100,o=C(),n=C(),c=1,l=C(),d=C(),[u,h,g]=ci((()=>q)),m=C(),E=C(),D=[],x=[],w=(I,F)=>{c=0,r.transaction((()=>{let[rt,Q]=v(m,F);j(rt,((O,W)=>j(O,((X,Z)=>j(X,((K,J)=>Qi(r,W,Z,J,K[I]))))))),j(Q,((O,W)=>Kr(r,W,O[I])))})),c=1},A=I=>{T(m,I),T(E,I),h(d,[I])},k=(I,F)=>Bt(((rt,Q)=>rt.splice(0,Q))(I,F??Ot(I)),A),R=()=>k(D,Ot(D)-s),U=()=>ct(t,(()=>{Rt(D,t),R(),k(x),t=void 0,i=1})),P=()=>{t=Eo(D),i=1},y,B,_=(I="")=>(H(t)&&(t=""+e++,T(m,t,[o,n]),nt(t,I),o=C(),n=C(),i=1),t),G=()=>{si(D)||(((I,...F)=>{I.unshift(...F)})(x,_()),w(0,t),t=Eo(D),i=1)},N=()=>{si(x)||(Rt(D,t),t=Fo(x),w(1,t),i=1)},V=()=>{i&&(h(l),i=0)},et=I=>{let F=_(I);return V(),F},nt=(I,F)=>(lt(I)&&v(E,I)!==F&&(T(E,I,F),h(d,[I])),q),lt=I=>ht(m,I),q={setSize:I=>(s=I,R(),q),addCheckpoint:et,setCheckpoint:nt,getStore:()=>r,getCheckpointIds:()=>[[...D],t,[...x]],forEachCheckpoint:I=>bt(E,I),hasCheckpoint:lt,getCheckpoint:I=>v(E,I),goBackward:()=>(G(),V(),q),goForward:()=>(N(),V(),q),goTo:I=>{let F=Wr(D,I)?G:Wr(x,I)?N:null;for(;!H(F)&&I!=t;)F();return V(),q},addCheckpointIdsListener:I=>u(I,l),addCheckpointListener:(I,F)=>u(F,d,[I]),delListener:I=>(g(I),q),clear:()=>(k(D),k(x),H(t)||A(t),t=void 0,e=0,et(),q),clearForward:()=>(si(x)||(k(x),h(l)),q),destroy:()=>{r.delListener(y),r.delListener(B)},getListenerStats:()=>({checkpointIds:ue(l),checkpoint:ue(d)}),_registerListeners:()=>{y=r.addCellListener(null,null,null,((I,F,rt,Q,O,W)=>{if(c){U();let X=dt(o,F,C),Z=dt(X,rt,C),K=dt(Z,Q,(()=>[W,void 0]));K[1]=O,K[0]===O&&z(T(Z,Q))&&z(T(X,rt))&&z(T(o,F))&&P(),V()}})),B=r.addValueListener(null,((I,F,rt,Q)=>{if(c){U();let O=dt(n,F,(()=>[Q,void 0]));O[1]=rt,O[0]===rt&&z(T(n,F))&&P(),V()}}))}};return je(q.clear())}),(r=>r._registerListeners())),ra=Xn("-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"),hc=C(fe(ra,((r,t)=>[r,t])));var pc=_r.crypto?r=>_r.crypto.getRandomValues(r):r=>fe(r,(()=>Jn(256*er.random())));var sa=JSON.stringify,Nr=JSON.parse,Re=r=>sa(r,((t,e)=>{return i=Map,e instanceof i?oe.fromEntries([...e]):e;var i})),fc=new _r.TextEncoder;var uc=2**36,gc=2**30,mc=2**24,bc=2**18;var $o=(r,t)=>(r??0)<(t??0)?-1:1,yc=ai((r=>{let t=C(),e=C(),[i,s,o]=ci((()=>A)),[n,c,l,d,u,h,g,,m,E,D,x]=ir(r,C,(k=>H(k)?"":Oe(k)?fe(k,at):at(k)),i,s),w=(k,R,U)=>{let P=u(k);j(U,((y,B)=>R(B,(_=>j(y,(G=>_(G,(N=>r.forEachCell(P,G,N)))))))))},A={setIndexDefinition:(k,R,U,P,y,B=$o)=>{let _=H(y)?void 0:([G],[N])=>y(G,N);return m(k,R,((G,N,V,et,nt,lt)=>{let q=0,I=yt(),F=yt(),rt=h(k);if(j(N,(([Q,O],W)=>{let X=yt(Q),Z=yt(O);j(X,(K=>Nt(Z,K)?Nt(X,K):0)),j(X,(K=>{ft(I,K),ct(v(rt,K),(J=>{Nt(J,W),z(J)&&(T(rt,K),q=1)}))})),j(Z,(K=>{ft(I,K),ht(rt,K)||(T(rt,K,yt()),q=1),ft(v(rt,K),W),H(P)||ft(F,K)}))})),G(),z(nt)||(lt?bt(rt,(Q=>ft(F,Q))):bt(V,(Q=>ct(v(et,Q),(O=>Bt(Oe(O)?O:[O],(W=>ft(F,W))))))),j(F,(Q=>{let O=(X,Z)=>B(v(nt,X),v(nt,Z),Q),W=[...v(rt,Q)];ko(W,O)||(T(rt,Q,yt(Gr(W,O))),ft(I,Q))}))),(q||lt)&&!H(_)){let Q=[...rt];ko(Q,_)||(g(k,C(Gr(Q,_))),q=1)}q&&s(t,[k]),j(I,(Q=>s(e,[k,Q])))}),tr(U),ct(P,tr)),A},delIndexDefinition:k=>(E(k),A),getStore:n,getIndexIds:c,forEachIndex:k=>l(((R,U)=>k(R,(P=>w(R,P,U))))),forEachSlice:(k,R)=>w(k,R,h(k)),hasIndex:d,hasSlice:(k,R)=>ht(h(k),R),getTableId:u,getSliceIds:k=>pe(h(k)),getSliceRowIds:(k,R)=>Ue(v(h(k),R)),addIndexIdsListener:D,addSliceIdsListener:(k,R)=>i(R,t,[k]),addSliceRowIdsListener:(k,R,U)=>i(U,e,[k,R]),delListener:k=>(o(k),A),destroy:x,getListenerStats:()=>({sliceIds:ue(t),sliceRowIds:Wt(e)})};return je(A)}));var Ki=r=>[r,r],gt=(r,t=ue)=>t(r[0])+t(r[1]),mt=()=>[C(),C()],Do=r=>[...r],qi=([r,t])=>r===t,ei=(r,t,e)=>T(r,t,v(r,t)==-e?void 0:e),li=()=>{let r,t,e=!1,i=!1,s=0,o=[],n=C(),c=C(),l=C(),d=C(),u=C(),h=C(),g=C(),m=C(),E=C(),D=C(),x=C(),w=C(),A=C(),k=C(),R=yt(),U=C(),P=C(),y=C(),B=C(),_=mt(),G=mt(),N=mt(),V=mt(),et=mt(),nt=mt(),lt=mt(),q=mt(),I=mt(),F=mt(),rt=mt(),Q=mt(),O=mt(),W=mt(),X=mt(),Z=mt(),K=mt(),J=mt(),M=mt(),ot=mt(),pt=mt(),It=mt(),kt=C(),Pt=mt(),[vt,it,Tt,Yt]=ci((()=>Et)),Qt=a=>{if(!ee(a,((f,b)=>Wr([Wi,le],b))))return!1;let p=a[Wi];return!(!To(p)&&p!=Io)&&(Be(a[le])!=p&&zo(a,le),!0)},Dr=Oe,Ai=(a,p)=>(!r||ht(x,p)||Zt(p))&&ee(a,((f,b)=>ce(p,b,f)),(()=>Zt(p))),ce=(a,p,f,b)=>ee(b?f:Ts(f,a,p),((S,L)=>ct(Ii(a,p,L,S),($=>(f[L]=$,!0)),(()=>!1))),(()=>Zt(a,p))),Ii=(a,p,f,b)=>r?ct(v(v(x,a),f),(S=>Be(b)!=S[Wi]?Zt(a,p,f,b,S[le]):b),(()=>Zt(a,p,f,b))):H(Be(b))?Zt(a,p,f,b):b,Je=(a,p)=>ee(p?a:Hn(a),((f,b)=>ct(Bs(b,f),(S=>(a[b]=S,!0)),(()=>!1))),(()=>Qe())),Bs=(a,p)=>t?ct(v(A,a),(f=>Be(p)!=f[Wi]?Qe(a,p,f[le]):p),(()=>Qe(a,p))):H(Be(p))?Qe(a,p):p,Ts=(a,p,f)=>(ct(v(w,p),(([b,S])=>{j(b,((L,$)=>{ii(a,$)||(a[$]=L)})),j(S,(L=>{ii(a,L)||Zt(p,f,L)}))})),a),Hn=a=>(t&&(j(k,((p,f)=>{ii(a,f)||(a[f]=p)})),j(R,(p=>{ii(a,p)||Qe(p)}))),a),Ms=a=>he(x,a,((p,f,b)=>{let S=C(),L=yt();he(dt(x,f,C),b,(($,Y,tt)=>{T($,Y,tt),ct(tt[le],(Ht=>T(S,Y,Ht)),(()=>ft(L,Y)))})),T(w,f,[S,L])}),((p,f)=>{T(x,f),T(w,f)})),Os=a=>he(A,a,((p,f,b)=>{T(A,f,b),ct(b[le],(S=>T(k,f,S)),(()=>ft(R,f)))}),((p,f)=>{T(A,f),T(k,f),Nt(R,f)})),Us=a=>zt(a)?$i():zi(a),Fs=a=>he(y,a,((p,f,b)=>Li(f,b)),((p,f)=>$s(f))),Li=(a,p)=>he(dt(y,a,(()=>(Ws(a,1),T(U,a,No()),T(P,a,C()),C()))),p,((f,b,S)=>Ye(a,f,b,S)),((f,b)=>Hs(a,f,b))),Ye=(a,p,f,b,S)=>he(dt(p,f,(()=>(Gs(a,f,1),C()))),b,((L,$,Y)=>Ar(a,f,L,$,Y)),((L,$)=>_s(a,p,f,L,$,S))),Ar=(a,p,f,b,S)=>{ht(f,b)||Ks(a,p,b,1);let L=v(f,b);S!==L&&(qs(a,p,b,L,S),T(f,b,S))},js=(a,p,f,b,S)=>ct(v(p,f),(L=>Ar(a,f,L,b,S)),(()=>Ye(a,p,f,Ts({[b]:S},a,f)))),zs=a=>zt(a)?Hi():Ni(a),Ns=a=>he(B,a,((p,f,b)=>Ri(f,b)),((p,f)=>Vs(f))),Ri=(a,p)=>{ht(B,a)||Xs(a,1);let f=v(B,a);p!==f&&(Js(a,f,p),T(B,a,p))},Bi=a=>v(y,a)??Li(a,{}),$s=a=>Li(a,{}),Hs=(a,p,f)=>{let[,b]=v(U,a);b(f),Ye(a,p,f,{},!0)},_s=(a,p,f,b,S,L)=>{let $=v(v(w,a)?.[0],S);if(!H($)&&!L)return Ar(a,f,b,S,$);let Y=tt=>{qs(a,f,tt,v(b,tt)),Ks(a,f,tt,-1),T(b,tt)};H($)?Y(S):bt(b,Y),z(b)&&(Gs(a,f,-1),z(T(p,f))&&(Ws(a,-1),T(y,a),T(U,a),T(P,a)))},Vs=a=>{let p=v(k,a);if(!H(p))return Ri(a,p);Js(a,v(B,a)),Xs(a,-1),T(B,a)},Ws=(a,p)=>ei(n,a,p),Gs=(a,p,f)=>ei(dt(d,a,C),p,f)&&T(l,a,dt(l,a,(()=>0))+f),Ks=(a,p,f,b)=>{let S=v(P,a),L=v(S,f)??0;(L==0&&b==1||L==1&&b==-1)&&ei(dt(c,a,C),f,b),T(S,f,L!=-b?L+b:null),ei(dt(dt(u,a,C),p,C),f,b)},qs=(a,p,f,b,S)=>{dt(dt(dt(h,a,C),p,C),f,(()=>[b,0]))[1]=S,o[3]?.(a,p,f,S)},Xs=(a,p)=>ei(g,a,p),Js=(a,p,f)=>{dt(m,a,(()=>[p,0]))[1]=f,o[4]?.(a,f)},Zt=(a,p,f,b,S)=>(Rt(dt(dt(dt(E,a,C),p,C),f,(()=>[])),b),S),Qe=(a,p,f)=>(Rt(dt(D,a,(()=>[])),p),f),Ti=(a,p,f)=>ct(v(v(v(h,a),p),f),(([b,S])=>[!0,b,S]),(()=>[!1,...Ki(Oi(a,p,f))])),Ys=a=>ct(v(m,a),(([p,f])=>[!0,p,f]),(()=>[!1,...Ki(Ui(a))])),Qs=a=>z(E)||z(Z[a])?0:j(a?zr(E):E,((p,f)=>j(p,((b,S)=>j(b,((L,$)=>it(Z[a],[f,S,$],L))))))),Zs=a=>z(D)||z(K[a])?0:j(a?ie(D):D,((p,f)=>it(K[a],[f],p))),Ze=(a,p,f,b)=>{if(!z(a))return it(p,b,(()=>Lt(a))),bt(a,((S,L)=>it(f,[...b??[],S],L==1))),1},to=a=>{let p=Fi();p!=e&&it(_[a],void 0,p);let f=z(F[a]),b=z(O[a])&&z(W[a])&&z(I[a])&&z(rt[a])&&z(nt[a])&&z(lt[a])&&z(q[a])&&f&&z(N[a])&&z(V[a]),S=z(X[a])&&z(Q[a])&&z(et[a])&&z(G[a]);if(!b||!S){let L=a?[ie(n),Xr(c),ie(l),Xr(d),zr(u),zr(h)]:[n,c,l,d,u,h];if(!b){Ze(L[0],N[a],V[a]),j(L[1],((Y,tt)=>Ze(Y,nt[a],lt[a],[tt]))),j(L[2],((Y,tt)=>{Y!=0&&it(q[a],[tt],so(tt))}));let $=yt();j(L[3],((Y,tt)=>{Ze(Y,I[a],rt[a],[tt])&&!f&&(it(F[a],[tt,null]),ft($,tt))})),f||j(L[5],((Y,tt)=>{if(!ht($,tt)){let Ht=yt();j(Y,(te=>j(te,(([_i,Vi],ti)=>Vi!==_i?ft(Ht,ti):Nt(te,ti))))),j(Ht,(te=>it(F[a],[tt,te])))}})),j(L[4],((Y,tt)=>j(Y,((Ht,te)=>Ze(Ht,O[a],W[a],[tt,te])))))}if(!S){let $;j(L[5],((Y,tt)=>{let Ht;j(Y,((te,_i)=>{let Vi;j(te,(([ti,wo],_n)=>{wo!==ti&&(it(X[a],[tt,_i,_n],wo,ti,Ti),$=Ht=Vi=1)})),Vi&&it(Q[a],[tt,_i],Ti)})),Ht&&it(et[a],[tt],Ti)})),$&&it(G[a],void 0,Ti)}}},eo=a=>{let p=ji();p!=i&&it(J[a],void 0,p);let f=z(ot[a])&&z(pt[a]),b=z(It[a])&&z(M[a]);if(!f||!b){let S=a?[ie(g),ie(m)]:[g,m];if(f||Ze(S[0],ot[a],pt[a]),!b){let L;j(S[1],(([$,Y],tt)=>{Y!==$&&(it(It[a],[tt],Y,$,Ys),L=1)})),L&&it(M[a],void 0,Ys)}}},ut=(a,...p)=>(Mr((()=>a(...fe(p,at)))),Et),io=(a,p,f,b,S)=>{let L=Mi(a,p,...f);return vt((()=>{let $=Mi(a,p,...f);Oo($,L)||(L=$,b(Et,a,p,...f,L))}),F[S?1:0],[a,p],[Mt])},Ir=()=>Gi(y),Mt=()=>pe(y),ro=a=>pe(v(P,at(a))),so=a=>Fe(v(y,at(a))),Ie=a=>pe(v(y,at(a))),Mi=(a,p,f,b=0,S)=>{return Zi(a)?Mi(a.tableId,a.cellId,a.descending,a.offset,a.limit):fe(Vr(Gr((L=v(y,at(a)),$=(Y,tt)=>[H(p)?tt:v(Y,at(p)),tt],fe([...L?.entries()??[]],(([Y,tt])=>$(tt,Y)))),(([Y],[tt])=>$o(Y,tt)*(f?-1:1))),b,H(S)?S:b+S),(([,Y])=>Y));var L,$},Lr=(a,p)=>pe(v(v(y,at(a)),at(p))),Oi=(a,p,f)=>v(v(v(y,at(a)),at(p)),at(f)),Rr=()=>Lt(B),Br=()=>pe(B),Ui=a=>v(B,at(a)),Fi=()=>!z(y),oo=a=>ht(y,at(a)),no=(a,p)=>ht(v(P,at(a)),at(p)),ao=(a,p)=>ht(v(y,at(a)),at(p)),co=(a,p,f)=>ht(v(v(y,at(a)),at(p)),at(f)),ji=()=>!z(B),lo=a=>ht(B,at(a)),zi=a=>ut((()=>(p=>ee(p,Ai,Zt))(a)?Fs(a):0)),Ni=a=>ut((()=>Je(a)?Ns(a):0)),ho=a=>(Fr((()=>Us(Nr(a)))),Et),po=a=>ut((()=>{if((r=ee(a,(p=>ee(p,Qt))))&&(Ms(a),!z(y))){let p=Ir();$i(),zi(p)}})),fo=a=>ut((()=>{if(t=(p=>ee(p,Qt))(a)){let p=Rr();Tr(),Hi(),t=!0,Os(a),Ni(p)}})),$i=()=>ut((()=>Fs({}))),uo=a=>ut((p=>ht(y,p)?$s(p):0),a),go=(a,p)=>ut(((f,b)=>ct(v(y,f),(S=>ht(S,b)?Hs(f,S,b):0))),a,p),Hi=()=>ut((()=>Ns({}))),mo=()=>ut((()=>{Ms({}),r=!1})),Tr=()=>ut((()=>{Os({}),t=!1})),Mr=(a,p)=>{if(s!=-1){bo();let f=a();return yo(p),f}},bo=()=>(s!=-1&&s++,s==1&&(o[0]?.(),it(kt)),Et),yo=a=>(s>0&&(s--,s==0&&(s=1,Qs(1),z(h)||to(1),Zs(1),z(m)||eo(1),a?.(Et)&&(j(h,((p,f)=>j(p,((b,S)=>j(b,(([L],$)=>Qi(Et,f,S,$,L))))))),Te(h),j(m,(([p],f)=>Kr(Et,f,p))),Te(m)),it(Pt[0],void 0),s=-1,Qs(0),z(h)||to(0),Zs(0),z(m)||eo(0),o[1]?.(),it(Pt[1],void 0),o[2]?.(),s=0,e=Fi(),i=ji(),Bt([n,c,l,d,u,h,E,g,m,D],Te))),Et),Et={getContent:()=>[Ir(),Rr()],getTables:Ir,getTableIds:Mt,getTable:a=>qr(v(y,at(a))),getTableCellIds:ro,getRowCount:so,getRowIds:Ie,getSortedRowIds:Mi,getRow:(a,p)=>Lt(v(v(y,at(a)),at(p))),getCellIds:Lr,getCell:Oi,getValues:Rr,getValueIds:Br,getValue:Ui,hasTables:Fi,hasTable:oo,hasTableCell:no,hasRow:ao,hasCell:co,hasValues:ji,hasValue:lo,getTablesJson:()=>Re(y),getValuesJson:()=>Re(B),getJson:()=>Re([y,B]),getTablesSchemaJson:()=>Re(x),getValuesSchemaJson:()=>Re(A),getSchemaJson:()=>Re([x,A]),hasTablesSchema:()=>r,hasValuesSchema:()=>t,setContent:a=>ut((()=>{let p=jt(a)?a():a;Dr(p)&&(([f,b])=>{(zt(f)?$i:zi)(f),(zt(b)?Hi:Ni)(b)})(p)})),setTables:zi,setTable:(a,p)=>ut((f=>Ai(p,f)?Li(f,p):0),a),setRow:(a,p,f)=>ut(((b,S)=>ce(b,S,f)?Ye(b,Bi(b),S,f):0),a,p),addRow:(a,p,f=!0)=>Mr((()=>{let b;return ce(a,b,p)&&(a=at(a),Ye(a,Bi(a),b=((S,L)=>{let[$]=v(U,S),Y;do Y=$(L);while(ht(v(y,S),Y));return Y})(a,f?1:0),p)),b})),setPartialRow:(a,p,f)=>ut(((b,S)=>{if(ce(b,S,f,1)){let L=Bi(b);Vt(f,(($,Y)=>js(b,L,S,Y,$)))}}),a,p),setCell:(a,p,f,b)=>ut(((S,L,$)=>ct(Ii(S,L,$,jt(b)?b(Oi(S,L,$)):b),(Y=>js(S,Bi(S),L,$,Y)))),a,p,f),setValues:Ni,setPartialValues:a=>ut((()=>Je(a,1)?Vt(a,((p,f)=>Ri(f,p))):0)),setValue:(a,p)=>ut((f=>ct(Bs(f,jt(p)?p(Ui(f)):p),(b=>Ri(f,b)))),a),applyChanges:a=>ut((()=>{Vt(a[0],((p,f)=>H(p)?uo(f):Vt(p,((b,S)=>H(b)?go(f,S):Vt(b,((L,$)=>Qi(Et,f,S,$,L))))))),Vt(a[1],((p,f)=>Kr(Et,f,p)))})),setTablesJson:ho,setValuesJson:a=>(Fr((()=>zs(Nr(a)))),Et),setJson:a=>ut((()=>Fr((()=>{let[p,f]=Nr(a);Us(p),zs(f)}),(()=>ho(a))))),setTablesSchema:po,setValuesSchema:fo,setSchema:(a,p)=>ut((()=>{po(a),fo(p)})),delTables:$i,delTable:uo,delRow:go,delCell:(a,p,f,b)=>ut(((S,L,$)=>ct(v(y,S),(Y=>ct(v(Y,L),(tt=>ht(tt,$)?_s(S,Y,L,tt,$,b):0))))),a,p,f),delValues:Hi,delValue:a=>ut((p=>ht(B,p)?Vs(p):0),a),delTablesSchema:mo,delValuesSchema:Tr,delSchema:()=>ut((()=>{mo(),Tr()})),transaction:Mr,startTransaction:bo,getTransactionChanges:()=>[Lt(h,((a,p)=>v(n,p)===-1?void 0:Lt(a,((f,b)=>v(v(d,p),b)===-1?void 0:Lt(f,(([,S])=>S),(S=>qi(S)))),z,zt)),z,zt),Lt(m,(([,a])=>a),(a=>qi(a))),1],getTransactionLog:()=>[!z(h),!z(m),Gi(h,Do,qi),Gi(E),Lt(m,Do,qi),Lt(D),Lt(n),qr(d),Gi(u),Lt(g)],finishTransaction:yo,forEachTable:a=>j(y,((p,f)=>a(f,(b=>j(p,((S,L)=>b(L,($=>bt(S,$))))))))),forEachTableCell:(a,p)=>bt(v(P,at(a)),p),forEachRow:(a,p)=>j(v(y,at(a)),((f,b)=>p(b,(S=>bt(f,S))))),forEachCell:(a,p,f)=>bt(v(v(y,at(a)),at(p)),f),forEachValue:a=>bt(B,a),addSortedRowIdsListener:(a,p,f,b,S,L,$)=>Zi(a)?io(a.tableId,a.cellId,[a.descending??!1,a.offset??0,a.limit],p,f):io(a,p,[f,b,S],L,$),addStartTransactionListener:a=>vt(a,kt),addWillFinishTransactionListener:a=>vt(a,Pt[0]),addDidFinishTransactionListener:a=>vt(a,Pt[1]),callListener:a=>(Yt(a),Et),delListener:a=>(Tt(a),Et),getListenerStats:()=>({hasTables:gt(_),tables:gt(G),tableIds:gt(N),hasTable:gt(V),table:gt(et),tableCellIds:gt(nt),hasTableCell:gt(lt,Wt),rowCount:gt(q),rowIds:gt(I),sortedRowIds:gt(F),hasRow:gt(rt,Wt),row:gt(Q,Wt),cellIds:gt(O,Wt),hasCell:gt(W,jr),cell:gt(X,jr),invalidCell:gt(Z,jr),hasValues:gt(J),values:gt(M),valueIds:gt(ot),hasValue:gt(pt),value:gt(It),invalidValue:gt(K),transaction:ue(kt)+gt(Pt)}),isMergeable:()=>!1,createStore:li,addListener:vt,callListeners:it,setInternalListeners:(a,p,f,b,S)=>o=[a,p,f,b,S]};return Vt({[de+vo]:[0,_,[],()=>[Fi()]],[vo]:[0,G],[Gn]:[0,N],[de+re]:[1,V,[Mt],a=>[oo(...a)]],[re]:[1,et,[Mt]],[re+Xi]:[1,nt,[Mt]],[de+re+ri]:[2,lt,[Mt,ro],a=>[no(...a)]],[Lo]:[1,q,[Mt]],[Ro]:[1,I,[Mt]],[de+Me]:[2,rt,[Mt,Ie],a=>[ao(...a)]],[Me]:[2,Q,[Mt,Ie]],[Xi]:[2,O,[Mt,Ie]],[de+ri]:[3,W,[Mt,Ie,Lr],a=>[co(...a)]],[ri]:[3,X,[Mt,Ie,Lr],a=>Ki(Oi(...a))],InvalidCell:[3,Z],[de+So]:[0,J,[],()=>[ji()]],[So]:[0,M],[qn]:[0,ot],[de+Ji]:[1,pt,[Br],a=>[lo(...a)]],[Ji]:[1,It,[Br],a=>Ki(Ui(a[0]))],InvalidValue:[1,K]},(([a,p,f,b],S)=>{Et[Hr+S+$r]=(...L)=>vt(L[a],p[L[a+1]?1:0],a>0?Vr(L,0,a):void 0,f,b)})),je(Et)};var Jr=C([["avg",[(r,t)=>Po(r)/t,(r,t,e)=>r+(t-r)/(e+1),(r,t,e)=>r+(r-t)/(e-1),(r,t,e,i)=>r+(t-e)/i]],["max",[r=>Or(...r),(r,t)=>Or(t,r),(r,t)=>t==r?void 0:r,(r,t,e)=>e==r?void 0:Or(t,r)]],["min",[r=>Ur(...r),(r,t)=>Ur(t,r),(r,t)=>t==r?void 0:r,(r,t,e)=>e==r?void 0:Ur(t,r)]],["sum",[r=>Po(r),(r,t)=>r+t,(r,t)=>r-t,(r,t,e)=>r-e+t]]]),Ho=(r,t,e,i,s,o=!1)=>{if(z(e))return;let[n,c,l,d]=s;return o||=H(r),j(i,(([u,h])=>{o||(r=H(u)?c?.(r,h,t++):H(h)?l?.(r,u,t--):d?.(r,h,u,t),o||=H(r))})),o?n(Ue(e),Fe(e)):r},wc=ai((r=>{let t=C(),[e,i,s]=ci((()=>x)),[o,n,c,l,d,u,h,,g,m,E,D]=ir(r,Mo,(w=>isNaN(w)||H(w)||w===!0||w===!1||w===""?void 0:1*w),e,i),x={setMetricDefinition:(w,A,k,R,U,P,y)=>{let B=jt(k)?[k,U,P,y]:v(Jr,k)??v(Jr,"sum");return g(w,A,((_,G,N,V,et,nt)=>{let lt=u(w),q=Fe(V);nt||=H(lt),_();let I=Ho(lt,q,V,G,B,nt);Bo(I)||(I=void 0),I!=lt&&(h(w,I),i(t,[w],I,lt))}),tr(R,1)),x},delMetricDefinition:w=>(m(w),x),getStore:o,getMetricIds:n,forEachMetric:c,hasMetric:l,getTableId:d,getMetric:u,addMetricIdsListener:E,addMetricListener:(w,A)=>e(A,t,[w]),delListener:w=>(s(w),x),destroy:D,getListenerStats:()=>({metric:ue(t)})};return je(x)})),xc=ai((r=>{let t=r.createStore,e=t(),i=t(),s=C(),{addListener:o,callListeners:n,delListener:c}=i,[l,d,u,h,g,,,m,,E,D,x,w,A]=ir(r,(()=>!0),Mo,o,n),k=(y,B,..._)=>Bt(_,(G=>ft(dt(dt(s,B,C),y,yt),G))),R=y=>{ct(v(s,y),(B=>{bt(B,((_,G)=>j(G,(N=>_.delListener(N))))),Te(B)})),Bt([i,e],(B=>B.delTable(y)))},U=(y,B,_)=>k(B,y,B.addStartTransactionListener(_.startTransaction),B.addDidFinishTransactionListener((()=>_.finishTransaction()))),P={setQueryDefinition:(y,B,_)=>{m(y,B),R(y);let G=[],N=[[null,[B,null,null,[],C()]]],V=[],et=[],nt=[];_({select:(O,W)=>{let X=jt(O)?[Ot(G)+"",O]:[H(W)?O:W,Z=>Z(O,W)];return Rt(G,X),{as:Z=>X[0]=Z}},join:(O,W,X)=>{let Z=H(X)||jt(W)?null:W,K=H(Z)?W:X,J=[O,[O,Z,jt(K)?K:M=>M(K),[],C()]];return Rt(N,J),{as:M=>J[0]=M}},where:(O,W,X)=>Rt(V,jt(O)?O:H(X)?Z=>Z(O)===W:Z=>Z(O,W)===X),group:(O,W,X,Z,K)=>{let J=[O,[O,jt(W)?[W,X,Z,K]:v(Jr,W)??[(M,ot)=>ot]]];return Rt(et,J),{as:M=>J[0]=M}},having:(O,W)=>Rt(nt,jt(O)?O:X=>X(O)===W)});let lt=C(G);if(z(lt))return P;let q=C(N);bt(q,((O,[,W])=>ct(v(q,W),(({3:X})=>H(O)?0:Rt(X,O)))));let I=C(et),F=e;if(z(I)&&si(nt))F=i;else{U(y,F,i);let O=C();bt(I,((K,[J,M])=>ft(dt(O,J,yt),[K,M])));let W=yt();bt(lt,(K=>ht(O,K)?0:ft(W,K)));let X=C(),Z=(K,J,M,ot)=>ct(K,(([pt,It,kt,Pt])=>{bt(J,((vt,[it])=>{let Tt=dt(pt,vt,C),Yt=v(Tt,M),Qt=ot?void 0:it;if(Yt!==Qt){let Dr=yt([[Yt,Qt]]),Ai=Fe(Tt);T(Tt,M,Qt),j(v(O,vt),(([ce,Ii])=>{let Je=Ho(Pt[ce],Ai,Tt,Dr,Ii);Pt[ce]=H(Be(Je))?null:Je}))}})),z(It)||!Yi(nt,(vt=>vt((it=>Pt[it]))))?i.delRow(y,kt):H(kt)?K[2]=i.addRow(y,Pt):i.setRow(y,kt,Pt)}));k(F,y,F.addRowListener(y,null,((K,J,M,ot)=>{let pt=[],It=[],kt=C(),Pt=F.hasRow(y,M),vt=!Pt;j(W,(it=>{let[Tt,Yt,Qt]=ot(y,M,it);Rt(pt,Yt),Rt(It,Qt),vt||=Tt})),bt(O,(it=>{let[Tt,,Yt]=ot(y,M,it);(vt||Tt)&&T(kt,it,[Yt])})),vt&&Z(oi(X,pt,void 0,(([,it])=>(Nt(it,M),z(it)))),kt,M,1),Pt&&Z(oi(X,It,(()=>{let it={};return j(W,(Tt=>it[Tt]=F.getCell(y,M,Tt))),[C(),yt(),void 0,it]}),(([,it])=>{ft(it,M)})),kt,M)})))}U(y,r,F);let rt=(O,W,X,Z)=>{let K=J=>r.getCell(W,X,J);Bt(Z,(J=>{let[M,,ot,pt,It]=v(q,J),kt=ot?.(K,O),[Pt,vt]=v(It,O)??[];kt!=Pt&&(H(vt)||A(y,vt),T(It,O,H(kt)?null:[kt,...w(y,1,r.addRowListener(M,kt,(()=>rt(O,M,kt,pt))))]))})),(J=>{let M=(ot,pt)=>r.getCell(...H(pt)?[B,J,ot]:ot===B?[B,J,pt]:[v(q,ot)?.[0],v(v(q,ot)?.[4],J)?.[0],pt]);F.transaction((()=>Yi(V,(ot=>ot(M)))?bt(lt,((ot,pt)=>Qi(F,y,J,ot,pt(M,J)))):F.delRow(y,J)))})(O)},{3:Q}=v(q,null);return F.transaction((()=>w(y,1,r.addRowListener(B,null,((O,W,X)=>{r.hasRow(B,X)?rt(X,B,X,Q):(F.delRow(y,X),j(q,(({4:Z})=>ct(v(Z,X),(([,K])=>{A(y,K),T(Z,X)})))))}))))),P},delQueryDefinition:y=>(R(y),E(y),P),getStore:l,getQueryIds:d,forEachQuery:u,hasQuery:h,getTableId:g,addQueryIdsListener:y=>D((()=>y(P))),delListener:y=>(c(y),P),destroy:x,getListenerStats:()=>{let{tables:y,tableIds:B,transaction:_,...G}=i.getListenerStats();return G}};return Vt({[re]:[1,1],[re+Xi]:[0,1],[Lo]:[0,1],[Ro]:[0,1],[Kn]:[0,5],[Me]:[1,2],[Xi]:[0,2],[ri]:[1,3]},(([y,B],_)=>{Bt(y?["get","has","forEach"]:["get"],(G=>P[G+xo+_]=(...N)=>i[G+_](...N))),P[Hr+xo+_+$r]=(...G)=>i[Hr+_+$r](...Vr(G,0,B),((N,...V)=>G[B](P,...V)),!0)})),je(P)})),vc=ai((r=>{let t=C(),e=C(),i=C(),s=C(),[o,n,c]=ci((()=>U)),[l,d,u,h,g,m,,,E,D,x,w]=ir(r,(()=>[C(),C(),C(),C()]),(P=>H(P)?void 0:P+""),o,n),A=(P,y,B)=>ct(m(P),(([_,,G])=>{if(!ht(G,y)){let N=yt();if(g(P)!=R(P))ft(N,y);else{let V=y;for(;!H(V)&&!ht(N,V);)ft(N,V),V=v(_,V)}if(B)return N;T(G,y,N)}return v(G,y)})),k=(P,y)=>ct(m(P),(([,,B])=>T(B,y))),R=P=>v(t,P),U={setRelationshipDefinition:(P,y,B,_)=>(T(t,P,B),E(P,y,((G,N)=>{let V=yt(),et=yt(),nt=yt(),[lt,q]=m(P);j(N,(([I,F],rt)=>{H(I)||(ft(et,I),ct(v(q,I),(Q=>{Nt(Q,rt),z(Q)&&T(q,I)}))),H(F)||(ft(et,F),ht(q,F)||T(q,F,yt()),ft(v(q,F),rt)),ft(V,rt),T(lt,rt,F),bt(v(s,P),(Q=>{ht(A(P,Q),rt)&&ft(nt,Q)}))})),G(),j(V,(I=>n(e,[P,I]))),j(et,(I=>n(i,[P,I]))),j(nt,(I=>{k(P,I),n(s,[P,I])}))}),tr(_)),U),delRelationshipDefinition:P=>(T(t,P),D(P),U),getStore:l,getRelationshipIds:d,forEachRelationship:P=>u((y=>P(y,(B=>r.forEachRow(g(y),B))))),hasRelationship:h,getLocalTableId:g,getRemoteTableId:R,getRemoteRowId:(P,y)=>v(m(P)?.[0],y),getLocalRowIds:(P,y)=>Ue(v(m(P)?.[1],y)),getLinkedRowIds:(P,y)=>H(m(P))?[y]:Ue(A(P,y,!0)),addRelationshipIdsListener:x,addRemoteRowIdListener:(P,y,B)=>o(B,e,[P,y]),addLocalRowIdsListener:(P,y,B)=>o(B,i,[P,y]),addLinkedRowIdsListener:(P,y,B)=>(A(P,y),o(B,s,[P,y])),delListener:P=>(k(...c(P)??[]),U),destroy:w,getListenerStats:()=>({remoteRowId:Wt(e),localRowIds:Wt(i),linkedRowIds:Wt(s)})};return je(U)}));var Wo=Promise,oa=globalThis,_o=oa.window,na=1e3,aa=(r,t,e)=>setInterval(r,t*na),ca=clearInterval,$t=r=>r==null,ar=(r,t,e)=>$t(r)?e?.():t(r),Zr=r=>Array.isArray(r),me=r=>r.length,la=(r,t)=>r.test(t),Go=r=>new Wo(r),Ko=async r=>Wo.all(r),qo=r=>{throw new Error(r)},ge=async(r,t,e)=>{try{return await r()}catch(i){t?.(i)}},ts=(r,t)=>r.forEach(t),di=(r,t)=>r.map(t),da=(r,t)=>r.splice(0,t),cr=(r,...t)=>r.push(...t),Xo=r=>r.shift(),ze=Object,Vo=r=>ze.getPrototypeOf(r),ha=ze.entries,pa=r=>!$t(r)&&ar(Vo(r),t=>t==ze.prototype||$t(Vo(t)),()=>!0),fa=ze.keys,ua=ze.freeze,ga=(r=[])=>ze.fromEntries(r),ma=(r,t)=>t in r,ba=(r,t)=>di(ha(r),([e,i])=>t(i,e)),ya=r=>me(fa(r)),rr=r=>pa(r)&&ya(r)==0,wa=r=>r?.size??0,xa=(r,t)=>r?.has(t)??!1,Jo=r=>$t(r)||wa(r)==0,Yo=(r,t)=>r?.forEach(t),Qo=(r,t)=>r?.delete(t),hi=r=>new Map(r),Ut=(r,t)=>r?.get(t),be=(r,t,e)=>$t(e)?(Qo(r,t),r):r?.set(t,e),es=(r,t,e,i)=>(xa(r,t)?i?.(Ut(r,t)):be(r,t,e()),Ut(r,t)),is=(r,t,e,i,s=0)=>ar((e?es:Ut)(r,t[s],s>me(t)-2?e:hi),o=>{if(s>me(t)-2)return i?.(o)&&be(r,t[s]),o;let n=is(o,t,e,i,s+1);return Jo(o)&&be(r,t[s]),n}),va=/^\d+$/,Sa=()=>{let r=[],t=0;return[e=>(e?Xo(r):null)??""+t++,e=>{la(va,e)&&me(r)<1e3&&cr(r,e)}]},ka=r=>new Set(Zr(r)||$t(r)?r:[r]),Pa=(r,t)=>r?.add(t),Ea=(r,t=[""])=>{let e=[],i=(s,o)=>o==me(t)?cr(e,s):t[o]===null?Yo(s,n=>i(n,o+1)):ts([t[o],null],n=>i(Ut(s,n),o+1));return i(r,0),e},Ca=r=>{let t,[e,i]=Sa(),s=hi();return[(o,n,c,l=[],d=()=>[])=>{t??=r();let u=e(1);return be(s,u,[o,n,c,l,d]),Pa(is(n,c??[""],ka),u),u},(o,n,...c)=>ts(Ea(o,n),l=>Yo(l,d=>Ut(s,d)[0](t,...n??[],...c))),o=>ar(Ut(s,o),([,n,c])=>(is(n,c??[""],void 0,l=>(Qo(l,o),Jo(l)?1:0)),be(s,o),i(o),c)),o=>ar(Ut(s,o),([n,,c=[],l,d])=>{let u=(...h)=>{let g=me(h);g==me(c)?n(t,...h,...d(h)):$t(c[g])?ts(l[g]?.(...h)??[],m=>u(...h,m)):u(...h,c[g])};u()})]},sr=hi(),or=hi(),Da=(r=1,t,e)=>r!=1&&t.isMergeable()?[1,t.getMergeableContent,()=>t.getTransactionMergeableChanges(!e),([[i],[s]])=>!rr(i)||!rr(s),t.setDefaultContent]:r!=2?[0,t.getContent,t.getTransactionChanges,([i,s])=>!rr(i)||!rr(s),t.setContent]:qo("Store type not supported by this Persister"),Aa=(r,t,e,i,s,o,n,c={},l=0,d=[])=>{let u=0,h=0,g=0,m,E,D;es(sr,d,()=>0),es(or,d,()=>[]);let x=hi(),[w,A,k,R,U]=Da(n,r,l),[P,y,B]=Ca(()=>J),_=M=>{M!=u&&(u=M,y(x,void 0,u))},G=async()=>{if(!Ut(sr,d)){for(be(sr,d,1);!$t(m=Xo(Ut(or,d)));)await ge(m,o);be(sr,d,0)}},N=M=>{(w&&Zr(M?.[0])?M?.[2]===1?r.applyMergeableChanges:r.setMergeableContent:M?.[2]===1?r.applyChanges:r.setContent)(M)},V=async M=>(u!=2&&(_(1),h++,await K(async()=>{await ge(async()=>{let ot=await t();Zr(ot)?N(ot):M?U(M):qo(`Content is not an array: ${ot}`)},()=>{M&&U(M)}),_(0)})),J),et=async M=>(nt(),await V(M),await ge(async()=>E=await i(async(ot,pt)=>{pt||ot?u!=2&&(_(1),h++,N(pt??ot),_(0)):await V()}),o),J),nt=async()=>(E&&(await ge(()=>s(E),o),E=void 0),J),lt=()=>!$t(E),q=async M=>(u!=1&&(_(2),g++,await K(async()=>{await ge(()=>e(A,M),o),_(0)})),J),I=async()=>(F(),await q(),D=r.addDidFinishTransactionListener(()=>{let M=k();R(M)&&q(M)}),J),F=async()=>(D&&(r.delListener(D),D=void 0),J),rt=()=>!$t(D),Q=async(M,ot=!1)=>{let[pt,It]=ot?[I,et]:[et,I];return await pt(M),await It(M),J},O=async(M=!1)=>{let[ot,pt]=M?[F,nt]:[nt,F];return await ot(),await pt(),J},W=()=>u,X=M=>P(M,x),Z=M=>(B(M),r),K=async(...M)=>(cr(Ut(or,d),...M),await G(),J),J={load:V,startAutoLoad:et,stopAutoLoad:nt,isAutoLoading:lt,save:q,startAutoSave:I,stopAutoSave:F,isAutoSaving:rt,startAutoPersisting:Q,stopAutoPersisting:O,getStatus:W,addStatusListener:X,delListener:Z,schedule:K,getStore:()=>r,destroy:()=>(da(Ut(or,d)),O()),getStats:()=>({loads:h,saves:g}),...c};return ua(J)},Qr=["t","v"],Ia={keyPath:"k"},La=async(r,t)=>{let e=ba(t,(i,s)=>nr(r,"put",{k:s,v:i}));di(await nr(r,"getAllKeys"),i=>ma(t,i)?0:cr(e,nr(r,"delete",i))),await Ko(e)},nr=async(r,t,e)=>Go((i,s)=>{let o=r[t](e);o.onsuccess=()=>i(o.result),o.onerror=()=>s(`objectStore.${t} error`)}),Zo=(r,t,e=1,i)=>{let s=async(o,n=[],c=0)=>Go((l,d)=>{let u=(_o?_o.indexedDB:indexedDB).open(t,c?2:void 0);u.onupgradeneeded=()=>c&&di(Qr,h=>ge(()=>u.result.createObjectStore(h,Ia))),u.onsuccess=()=>ge(async()=>{let h=u.result.transaction(Qr,"readwrite"),g=await Ko(di(Qr,(m,E)=>o(h.objectStore(m),n[E])));u.result.close(),l(g)},h=>{u.result.close(),d(h)}),u.onerror=()=>d("indexedDB.open error")});return Aa(r,async()=>await s(async o=>ga(di(await nr(o,"getAll"),({k:n,v:c})=>[n,c]))),o=>s((n,c)=>La(n,c),o(),1),o=>aa(o,e),o=>ca(o),i,1,{getDbName:()=>t})};var lr=class{#t;#r="blobs";#s=null;constructor(t="copio-blobs"){this.#t=t}async#l(){return this.#s?this.#s:(this.#s=new Promise((t,e)=>{if(typeof indexedDB>"u"){e(new Error("IndexedDB is not available"));return}let i=indexedDB.open(this.#t,1);i.onupgradeneeded=()=>{let s=i.result;s.objectStoreNames.contains(this.#r)||s.createObjectStore(this.#r)},i.onsuccess=()=>t(i.result),i.onerror=()=>e(i.error||new Error("Failed to open blob db"))}),this.#s)}async put(t,e){let i=await this.#l();return new Promise((s,o)=>{let l=i.transaction(this.#r,"readwrite").objectStore(this.#r).put(e,t);l.onsuccess=()=>s(),l.onerror=()=>o(l.error)})}async get(t){let e=await this.#l();return new Promise((i,s)=>{let c=e.transaction(this.#r,"readonly").objectStore(this.#r).get(t);c.onsuccess=()=>i(c.result||null),c.onerror=()=>s(c.error)})}async delete(t){let e=await this.#l();return new Promise((i,s)=>{let c=e.transaction(this.#r,"readwrite").objectStore(this.#r).delete(t);c.onsuccess=()=>i(),c.onerror=()=>s(c.error)})}async deleteByPrefix(t){let e=await this.#l();return new Promise((i,s)=>{let n=e.transaction(this.#r,"readwrite").objectStore(this.#r),c=n.openKeyCursor();c.onsuccess=l=>{let d=l.target.result;d?(typeof d.key=="string"&&d.key.startsWith(t)&&n.delete(d.key),d.continue()):i()},c.onerror=()=>s(c.error)})}async sweepOrphans(t){let e=new Set(t),i=await this.#l(),s=0;return new Promise((o,n)=>{let l=i.transaction(this.#r,"readwrite").objectStore(this.#r),d=l.openKeyCursor();d.onsuccess=u=>{let h=u.target.result;if(h){if(typeof h.key=="string"){let g=h.key.split(":")[0];e.has(g)||(l.delete(h.key),s++)}h.continue()}else o(s)},d.onerror=()=>n(d.error)})}async close(){if(this.#s){try{(await this.#s).close()}catch{}this.#s=null}}};function ye(r,t="image/jpeg"){if(r instanceof Blob)return r;if(typeof r!="string"||!r.startsWith("data:"))return null;let e=r.match(/^data:([^;]+);base64,(.*)$/),i=e?e[1]:t,s=e?e[2]:r.split(",")[1],o=atob(s),n=new Uint8Array(o.length);for(let c=0;c<o.length;c++)n[c]=o.charCodeAt(c);return new Blob([n],{type:i})}async function rs(r){return new Promise((t,e)=>{let i=new FileReader;i.onloadend=()=>t(i.result),i.onerror=e,i.readAsDataURL(r)})}var ne=class extends _t{#t=null;#r=null;#s=null;#l="copio-db";#a=!1;#e=new Set;#c=new Map;#o=new Map;#i=new Map;#n=new Map;#d=null;constructor(t={}){super(),this.#l=t.dbName||"copio-db",t.dbName&&t.dbName!=="copio-db"&&(this.#a=!0),this.#t=t.store||li(),this.#t.hasTable("docs")||this.#t.setTable("docs",{}),this.#r=t.persister||Zo(this.#t,this.#l),this.#s=new lr(`${this.#l}-blobs`)}get store(){return this.#t}get persister(){return this.#r}get blobStore(){return this.#s}#h(t,e){return typeof e=="string"&&e.startsWith("blob:")&&(this.#e.add(e),this.#c.has(t)||this.#c.set(t,[]),this.#c.get(t).push(e)),e}revokeDocUrls(t){let e=this.#c.get(t);if(e){for(let i of e){try{URL.revokeObjectURL(i)}catch{}this.#e.delete(i)}this.#c.delete(t)}for(let[i,s]of this.#o.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(s)}catch{}this.#o.delete(i)}for(let[i,s]of this.#i.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(s)}catch{}this.#i.delete(i)}this.#n.delete(t)}revokeAllUrls(){for(let t of this.#e)try{URL.revokeObjectURL(t)}catch{}this.#e.clear(),this.#c.clear(),this.#o.clear(),this.#i.clear(),this.#n.clear()}async init(){return this.#d?this.#d:(this.#d=(async()=>{this.#a?(await this.#r.load(),this.#r.startAutoLoad(),this.#r.startAutoSave()):await this.#r.load(),await this.sweepOrphans();let t=!0;if(typeof navigator<"u"&&navigator.storage&&navigator.storage.persisted)try{t=await navigator.storage.persisted()}catch{}return{kind:"indexeddb",persistent:t}})(),this.#d)}async sweepOrphans(){let t=Object.keys(this.#t.getTable("docs")||{});return this.#s.sweepOrphans(t)}listDocsSync(){let t=this.#t.getTable("docs");return Object.entries(t||{}).map(([e,i])=>({id:e,name:i.name||"",pages:this.#p(i.pages)}))}async listDocs(){return this.listDocsSync()}getDocSync(t){if(this.#n.has(t))return this.#n.get(t);if(!this.#t.hasRow("docs",t))return null;let e=this.#t.getRow("docs",t);return{id:t,name:e.name||"",pages:this.#p(e.pages)}}async getDoc(t){if(!this.#t.hasRow("docs",t))return null;let e=this.#t.getRow("docs",t),i=this.#p(e.pages),s=await Promise.all(i.map(async n=>{if(!n)return n;let c={...n},l=`${t}:${n.id}`,d=await this.#s.get(`${t}:${n.id}`);d&&(c.blob=d,this.#o.has(l)?c.src=this.#o.get(l):(c.src=this.#h(t,URL.createObjectURL(d)),this.#o.set(l,c.src)));let u=`${t}:${n.id}:orig`,h=await this.#s.get(`${t}:${n.id}:original`);return h?(c.originalBlob=h,this.#i.has(u)?c.originalSrc=this.#i.get(u):(c.originalSrc=this.#h(t,URL.createObjectURL(h)),this.#i.set(u,c.originalSrc))):c.blob&&(c.originalBlob=c.blob,c.originalSrc=c.src),c})),o={id:t,name:e.name||"",pages:s};return this.#n.set(t,o),o}async saveDoc(t,e){if(!t)throw new Error("Cannot save document without an ID");let i=Array.isArray(e.pages)?e.pages:this.#p(e.pages),s=[],o=[],n=[];for(let c of i){if(!c)continue;let l=ye(c.src)||(c.src instanceof Blob?c.src:null)||(c.blob instanceof Blob?c.blob:null),d=l?.type||"image/jpeg",u={id:c.id,name:c.name||"",type:c.type||"image",hasBlob:!0,mimeType:d,edits:c.edits,exif:c.exif,content:c.content,ocrText:c.ocrText??null,ocrConfidence:c.ocrConfidence??null,ocrWords:Array.isArray(c.ocrWords)?c.ocrWords:null,ocrWidth:c.ocrWidth??null,ocrHeight:c.ocrHeight??null};s.push(u);let h=`${t}:${c.id}`,g=`${t}:${c.id}:orig`,m={...c},E=this.#o.get(h),D=typeof c.src=="string"&&c.src.startsWith("data:")||c.src instanceof Blob||c.src&&E&&c.src!==E;if(l)if(m.blob=l,D||!E){if(E){try{URL.revokeObjectURL(E)}catch{}this.#e.delete(E)}let R=this.#h(t,URL.createObjectURL(l));this.#o.set(h,R),m.src=R}else m.src=E;let x=ye(c.originalSrc)||(c.originalSrc instanceof Blob?c.originalSrc:null)||(c.originalBlob instanceof Blob?c.originalBlob:null),w=this.#i.get(g),A=!w&&!x&&(!c.originalSrc||c.originalSrc===c.src);A&&l&&(x=l);let k=typeof c.originalSrc=="string"&&c.originalSrc.startsWith("data:")||c.originalSrc instanceof Blob||A&&!!x;if(x)if(m.originalBlob=x,k||!w){if(w&&k){try{URL.revokeObjectURL(w)}catch{}this.#e.delete(w)}let R=this.#h(t,URL.createObjectURL(x));this.#i.set(g,R),m.originalSrc=R}else m.originalSrc=w;else w?m.originalSrc=w:c.originalSrc?m.originalSrc=c.originalSrc:(m.originalSrc=m.src,m.blob&&(m.originalBlob=m.blob));o.push(m),n.push({pageId:c.id,page:c,srcBlob:l,origBlob:x})}this.#t.setRow("docs",t,{name:e.name||"",pages:JSON.stringify(s)}),this.#n.set(t,{id:t,name:e.name||"",pages:o});for(let c of n){let{pageId:l,page:d,srcBlob:u,origBlob:h}=c;if(!u&&typeof d.src=="string"&&d.src.startsWith("blob:"))try{u=await(await fetch(d.src)).blob()}catch{}if(u&&await this.#s.put(`${t}:${l}`,u),!h&&typeof d.originalSrc=="string"&&d.originalSrc.startsWith("blob:"))try{h=await(await fetch(d.originalSrc)).blob()}catch{}h&&await this.#s.put(`${t}:${l}:original`,h)}}async deleteDoc(t){this.#t.delRow("docs",t),await this.#s.deleteByPrefix(`${t}:`),this.revokeDocUrls(t),this.#n.delete(t)}async renameDoc(t,e){if(!this.#t.hasRow("docs",t))throw new Error(`Document "${t}" not found`);this.#t.setCell("docs",t,"name",e),this.#n.has(t)&&(this.#n.get(t).name=e)}async savePage(t,e,i){let s=await this.getDoc(t);if(!s)throw new Error(`Document ${t} not found`);let o=s.pages.findIndex(l=>l.id===e),n;if(o>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?s.pages[o]={...s.pages[o],...i}:s.pages[o]={...s.pages[o],src:i,blob:i instanceof Blob?i:void 0},n=s.pages[o];else{let l=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i,blob:i instanceof Blob?i:void 0};s.pages.push(l),n=l}let c=ye(n.src)||(n.src instanceof Blob?n.src:null)||(n.blob instanceof Blob?n.blob:null);if(!c&&typeof n.src=="string"&&n.src.startsWith("blob:"))try{c=await(await fetch(n.src)).blob()}catch{}c&&await this.#s.put(`${t}:${e}`,c),await this.saveDoc(t,s)}async getPage(t,e){let i=await this.#s.get(`${t}:${e}`);if(i)return i;let s=this.getDocSync(t);if(!s)return null;let o=s.pages.find(n=>n.id===e);return o?o.content??o.src??o:null}async deletePage(t,e){let i=this.getDocSync(t);if(!i)return;i.pages=i.pages.filter(n=>n.id!==e),this.#t.setRow("docs",t,{name:i.name||"",pages:JSON.stringify(i.pages)}),await this.#s.delete(`${t}:${e}`),await this.#s.delete(`${t}:${e}:original`);let s=`${t}:${e}`;if(this.#o.has(s)){try{URL.revokeObjectURL(this.#o.get(s))}catch{}this.#o.delete(s)}let o=`${t}:${e}:orig`;if(this.#i.has(o)){try{URL.revokeObjectURL(this.#i.get(o))}catch{}this.#i.delete(o)}this.#n.delete(t)}subscribe(t){let e=this.#t.addTableListener("docs",t);return()=>{this.#t.delListener(e)}}#p(t){if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}};async function en(){if(typeof location<"u"&&location.search&&(new URLSearchParams(location.search).has("no-opfs")||new URLSearchParams(location.search).get("storage")==="indexeddb")||typeof navigator>"u"||!navigator.storage||typeof navigator.storage.getDirectory!="function")return!1;try{let r=await navigator.storage.getDirectory();if(!r)return!1;let t=`.copio-probe-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,e=await r.getFileHandle(t,{create:!0}),i=await e.createWritable();if(await i.write(new Uint8Array([1,2,3,4])),await i.close(),(await e.getFile()).size!==4)throw new Error("OPFS probe size mismatch");return await r.removeEntry(t),!0}catch{return!1}}function Ra(r,t,e="store.json"){let i=0,s=null,o=Promise.resolve(),n=0,c=()=>typeof t=="function"?t():t,l=async()=>{await o;let g=c();if(g){i=1;try{let D=await(await(await g.getFileHandle(e)).getFile()).text();D&&D.trim().length>0&&r.setJson(D)}catch{}finally{i=0}}},d=()=>{let g=c();return g?(n++,i=2,o=o.catch(()=>{}).then(async()=>{try{let m=r.getJson(),D=await(await g.getFileHandle(e,{create:!0})).createWritable();await D.write(m),await D.close()}catch(m){console.warn("[OpfsPersister] Failed to save store.json:",m)}finally{n--,n<=0&&(n=0,i=0)}}),o):Promise.resolve()};return{load:l,save:d,startAutoSave:()=>{s||(s=r.addDidFinishTransactionListener(()=>{d()}))},stopAutoSave:()=>{s&&(r.delListener(s),s=null)},getStatus:()=>i,getStore:()=>r}}async function tn(r){let t=[];try{if(typeof r.entries=="function")for await(let e of r.entries())t.push(e);else if(typeof r.values=="function")for await(let e of r.values())t.push([e.name,e])}catch(e){console.warn("[OpfsAdapter] Error reading directory entries:",e)}return t}var pi=class extends _t{#t;#r="copio";#s=null;#l=null;#a=null;#e=null;#c=null;#o=!1;#i=null;#n=new Set;#d=new Map;#h=new Map;#p=new Map;#u=new Map;#g=null;constructor(t={}){super(),this.#t=t,this.#r=t.dirName||"copio",t.store?this.#e=t.store:(this.#e=li(),this.#e.setTable("docs",{})),this.#c=t.persister||Ra(this.#e,()=>this.#l,"store.json")}get store(){return this.#o?this.#i?.store:this.#e}get persister(){return this.#o?this.#i?.persister:this.#c}get isFallback(){return this.#o}get fallbackAdapter(){return this.#i}async#f(){if(this.#o)return!1;if(this.#a&&this.#l)return!0;if(typeof navigator<"u"&&navigator.storage&&typeof navigator.storage.getDirectory=="function")try{return this.#s=await navigator.storage.getDirectory(),this.#l=await this.#s.getDirectoryHandle(this.#r,{create:!0}),this.#a=await this.#l.getDirectoryHandle("docs",{create:!0}),!0}catch(t){return console.warn("[OpfsAdapter] OPFS directory access failed, switching to fallback:",t),await this.#b(),!1}else return await this.#b(),!1}#w(t,e){return typeof e=="string"&&e.startsWith("blob:")&&(this.#n.add(e),this.#d.has(t)||this.#d.set(t,[]),this.#d.get(t).push(e)),e}revokeDocUrls(t){if(this.#o){this.#i?.revokeDocUrls(t);return}let e=this.#d.get(t);if(e){for(let i of e){try{URL.revokeObjectURL(i)}catch{}this.#n.delete(i)}this.#d.delete(t)}for(let[i,s]of this.#h.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(s)}catch{}this.#h.delete(i)}for(let[i,s]of this.#p.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(s)}catch{}this.#p.delete(i)}this.#u.delete(t)}revokeAllUrls(){if(this.#o){this.#i?.revokeAllUrls();return}for(let t of this.#n)try{URL.revokeObjectURL(t)}catch{}this.#n.clear(),this.#d.clear(),this.#h.clear(),this.#p.clear(),this.#u.clear()}async init(){return this.#g?this.#g:(this.#g=(async()=>{if(this.#t.forceFallback)return this.#b();if(!await en())return this.#b();try{await this.#f(),await this.#c.load(),this.#c.startAutoSave(),await this.sweepOrphans();let e=!1;if(typeof navigator<"u"&&navigator.storage&&navigator.storage.persisted)try{e=await navigator.storage.persisted()}catch{}return{kind:"opfs",persistent:e}}catch(e){return console.warn("[OpfsAdapter] OPFS initialization failed, switching to IndexedDB fallback:",e),this.#b()}})(),this.#g)}async#b(){return this.#o=!0,this.#i=new ne(this.#t),{kind:"indexeddb",persistent:(await this.#i.init()).persistent}}async sweepOrphans(){if(this.#o)return this.#i?.sweepOrphans();if(await this.#f(),!this.#a)return 0;let t=0,e=this.#e.getTable("docs")||{},i=new Set(Object.keys(e)),s=new Map;for(let[n,c]of Object.entries(e)){let l=this.#y(c.pages);s.set(n,new Set(l.map(d=>d.id)))}let o=await tn(this.#a);for(let[n,c]of o)if(c.kind==="directory")if(i.has(n)){let l=s.get(n)||new Set,d=c,u=await tn(d);for(let[h]of u){let g=h.replace(/-original\.bin$/,"").replace(/\.bin$/,"");if(!l.has(g))try{await d.removeEntry(h),t++}catch{}}}else try{await this.#a.removeEntry(n,{recursive:!0}),t++}catch{}return t}listDocsSync(){if(this.#o)return this.#i?.listDocsSync();let t=this.#e.getTable("docs");return Object.entries(t||{}).map(([e,i])=>({id:e,name:i.name||"",pages:this.#y(i.pages)}))}async listDocs(){return this.#o?this.#i?.listDocs():this.listDocsSync()}getDocSync(t){if(this.#o)return this.#i?.getDocSync(t);if(this.#u.has(t))return this.#u.get(t);if(!this.#e.hasRow("docs",t))return null;let e=this.#e.getRow("docs",t);return{id:t,name:e.name||"",pages:this.#y(e.pages)}}async getDoc(t){if(this.#o)return this.#i?.getDoc(t);if(await this.#f(),!this.#e.hasRow("docs",t))return null;let e=this.#e.getRow("docs",t),i=this.#y(e.pages),s=null;if(this.#a)try{s=await this.#a.getDirectoryHandle(t)}catch{}let o=await Promise.all(i.map(async c=>{if(!c||!s)return c;let l={...c},d=`${t}:${c.id}`;try{let g=await(await s.getFileHandle(`${c.id}.bin`)).getFile();l.blob=g,this.#h.has(d)?l.src=this.#h.get(d):(l.src=this.#w(t,URL.createObjectURL(g)),this.#h.set(d,l.src))}catch{}let u=`${t}:${c.id}:orig`;try{let g=await(await s.getFileHandle(`${c.id}-original.bin`)).getFile();l.originalBlob=g,this.#p.has(u)?l.originalSrc=this.#p.get(u):(l.originalSrc=this.#w(t,URL.createObjectURL(g)),this.#p.set(u,l.originalSrc))}catch{l.blob&&(l.originalBlob=l.blob,l.originalSrc=l.src)}return l})),n={id:t,name:e.name||"",pages:o};return this.#u.set(t,n),n}async saveDoc(t,e){if(this.#o)return this.#i?.saveDoc(t,e);if(!t)throw new Error("Cannot save document without an ID");let i=Array.isArray(e.pages)?e.pages:this.#y(e.pages),s=[],o=[],n=[];for(let l of i){if(!l)continue;let d=ye(l.src)||(l.src instanceof Blob?l.src:null)||(l.blob instanceof Blob?l.blob:null),u=d?.type||"image/jpeg",h={id:l.id,name:l.name||"",type:l.type||"image",hasBlob:!0,mimeType:u,edits:l.edits,exif:l.exif,content:l.content,ocrText:l.ocrText??null,ocrConfidence:l.ocrConfidence??null,ocrWords:Array.isArray(l.ocrWords)?l.ocrWords:null,ocrWidth:l.ocrWidth??null,ocrHeight:l.ocrHeight??null};s.push(h);let g=`${t}:${l.id}`,m=`${t}:${l.id}:orig`,E={...l},D=this.#h.get(g),x=typeof l.src=="string"&&l.src.startsWith("data:")||l.src instanceof Blob||l.src&&D&&l.src!==D;if(d)if(E.blob=d,x||!D){if(D){try{URL.revokeObjectURL(D)}catch{}this.#n.delete(D)}let U=this.#w(t,URL.createObjectURL(d));this.#h.set(g,U),E.src=U}else E.src=D;let w=ye(l.originalSrc)||(l.originalSrc instanceof Blob?l.originalSrc:null)||(l.originalBlob instanceof Blob?l.originalBlob:null),A=this.#p.get(m),k=!A&&!w&&(!l.originalSrc||l.originalSrc===l.src);k&&d&&(w=d);let R=typeof l.originalSrc=="string"&&l.originalSrc.startsWith("data:")||l.originalSrc instanceof Blob||k&&!!w;if(w)if(E.originalBlob=w,R||!A){if(A&&R){try{URL.revokeObjectURL(A)}catch{}this.#n.delete(A)}let U=this.#w(t,URL.createObjectURL(w));this.#p.set(m,U),E.originalSrc=U}else E.originalSrc=A;else A?E.originalSrc=A:l.originalSrc?E.originalSrc=l.originalSrc:(E.originalSrc=E.src,E.blob&&(E.originalBlob=E.blob));o.push(E),n.push({pageId:l.id,page:l,srcBlob:d,origBlob:w})}if(this.#e.setRow("docs",t,{name:e.name||"",pages:JSON.stringify(s)}),this.#u.set(t,{id:t,name:e.name||"",pages:o}),await this.#f(),this.#o)return this.#i?.saveDoc(t,e);let c=null;if(this.#a)try{c=await this.#a.getDirectoryHandle(t,{create:!0})}catch(l){console.warn(`[OpfsAdapter] Failed to get doc directory "${t}":`,l)}if(c)for(let l of n){let{pageId:d,page:u,srcBlob:h,origBlob:g}=l;if(!h&&typeof u.src=="string"&&u.src.startsWith("blob:"))try{h=await(await fetch(u.src)).blob()}catch{}if(h)try{let E=await(await c.getFileHandle(`${d}.bin`,{create:!0})).createWritable();await E.write(h),await E.close()}catch(m){console.warn(`[OpfsAdapter] Failed writing page file "${d}.bin":`,m)}if(!g&&typeof u.originalSrc=="string"&&u.originalSrc.startsWith("blob:"))try{g=await(await fetch(u.originalSrc)).blob()}catch{}if(g)try{let E=await(await c.getFileHandle(`${d}-original.bin`,{create:!0})).createWritable();await E.write(g),await E.close()}catch{}}}async deleteDoc(t){if(this.#o)return this.#i?.deleteDoc(t);if(this.#e.delRow("docs",t),this.#u.delete(t),this.revokeDocUrls(t),await this.#f(),this.#a)try{await this.#a.removeEntry(t,{recursive:!0})}catch{}}async renameDoc(t,e){if(this.#o)return this.#i?.renameDoc(t,e);if(!this.#e.hasRow("docs",t))throw new Error(`Document "${t}" not found`);this.#e.setCell("docs",t,"name",e),this.#u.has(t)&&(this.#u.get(t).name=e)}async savePage(t,e,i){if(this.#o)return this.#i?.savePage(t,e,i);await this.#f();let s=await this.getDoc(t);if(!s)throw new Error(`Document ${t} not found`);let o=s.pages.findIndex(l=>l.id===e),n;if(o>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?s.pages[o]={...s.pages[o],...i}:s.pages[o]={...s.pages[o],src:i,blob:i instanceof Blob?i:void 0},n=s.pages[o];else{let l=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i,blob:i instanceof Blob?i:void 0};s.pages.push(l),n=l}let c=ye(n.src)||(n.src instanceof Blob?n.src:null)||(n.blob instanceof Blob?n.blob:null);if(!c&&typeof n.src=="string"&&n.src.startsWith("blob:"))try{c=await(await fetch(n.src)).blob()}catch{}if(c&&this.#a)try{let u=await(await(await this.#a.getDirectoryHandle(t,{create:!0})).getFileHandle(`${e}.bin`,{create:!0})).createWritable();await u.write(c),await u.close()}catch(l){console.warn(`[OpfsAdapter] Failed writing page file "${e}.bin":`,l)}await this.saveDoc(t,s)}async getPage(t,e){if(this.#o)return this.#i?.getPage(t,e);if(await this.#f(),this.#a)try{return await(await(await this.#a.getDirectoryHandle(t)).getFileHandle(`${e}.bin`)).getFile()}catch{}let i=this.getDocSync(t);if(!i)return null;let s=i.pages.find(o=>o.id===e);return s?s.content??s.src??s:null}async deletePage(t,e){if(this.#o)return this.#i?.deletePage(t,e);await this.#f();let i=this.getDocSync(t);if(!i)return;if(i.pages=i.pages.filter(n=>n.id!==e),this.#e.setRow("docs",t,{name:i.name||"",pages:JSON.stringify(i.pages)}),this.#a){try{await(await this.#a.getDirectoryHandle(t)).removeEntry(`${e}.bin`)}catch{}try{await(await this.#a.getDirectoryHandle(t)).removeEntry(`${e}-original.bin`)}catch{}}let s=`${t}:${e}`;if(this.#h.has(s)){try{URL.revokeObjectURL(this.#h.get(s))}catch{}this.#h.delete(s)}let o=`${t}:${e}:orig`;if(this.#p.has(o)){try{URL.revokeObjectURL(this.#p.get(o))}catch{}this.#p.delete(o)}this.#u.delete(t)}subscribe(t){if(this.#o)return this.#i?.subscribe(t);let e=this.#e.addTableListener("docs",t);return()=>{this.#e.delListener(e)}}#y(t){if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}};function dr(r={}){return r.forceMemory?new Le:r.forceIndexedDb?new ne(r):r.forceOpfs?new pi(r):typeof navigator<"u"&&navigator.storage&&typeof navigator.storage.getDirectory=="function"?new pi(r):typeof indexedDB<"u"?new ne(r):new Le}function st(r,t,e){return t in r?Object.defineProperty(r,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):r[t]=e,r}var bs=typeof self<"u"?self:global,bi=typeof navigator<"u",Ba=bi&&typeof HTMLImageElement>"u",rn=!(typeof global>"u"||typeof process>"u"||!process.versions||!process.versions.node),ys=bs.Buffer,hr=bs.BigInt,ws=!!ys,pr=r=>gn(r)?void 0:r,Ta=r=>r!==void 0;function gn(r){return r===void 0||(r instanceof Map?r.size===0:Object.values(r).filter(Ta).length===0)}function xt(r){let t=new Error(r);throw delete t.stack,t}function mn(r){return(r=(function(t){for(;t.endsWith("\0");)t=t.slice(0,-1);return t})(r).trim())===""?void 0:r}function sn(r){let t=(function(e){let i=0;return e.ifd0.enabled&&(i+=1024),e.exif.enabled&&(i+=2048),e.makerNote&&(i+=2048),e.userComment&&(i+=1024),e.gps.enabled&&(i+=512),e.interop.enabled&&(i+=100),e.ifd1.enabled&&(i+=1024),i+2048})(r);return r.jfif.enabled&&(t+=50),r.xmp.enabled&&(t+=2e4),r.iptc.enabled&&(t+=14e3),r.icc.enabled&&(t+=6e3),t}var as=r=>String.fromCharCode.apply(null,r),on=typeof TextDecoder<"u"?new TextDecoder("utf-8"):void 0;function bn(r){return on?on.decode(r):ws?Buffer.from(r).toString("utf8"):decodeURIComponent(escape(as(r)))}var qt=class r{static from(t,e){return t instanceof this&&t.le===e?t:new r(t,void 0,void 0,e)}constructor(t,e=0,i,s){if(typeof s=="boolean"&&(this.le=s),Array.isArray(t)&&(t=new Uint8Array(t)),t===0)this.byteOffset=0,this.byteLength=0;else if(t instanceof ArrayBuffer){i===void 0&&(i=t.byteLength-e);let o=new DataView(t,e,i);this._swapDataView(o)}else if(t instanceof Uint8Array||t instanceof DataView||t instanceof r){i===void 0&&(i=t.byteLength-e),(e+=t.byteOffset)+i>t.byteOffset+t.byteLength&&xt("Creating view outside of available memory in ArrayBuffer");let o=new DataView(t.buffer,e,i);this._swapDataView(o)}else if(typeof t=="number"){let o=new DataView(new ArrayBuffer(t));this._swapDataView(o)}else xt("Invalid input argument for BufferView: "+t)}_swapArrayBuffer(t){this._swapDataView(new DataView(t))}_swapBuffer(t){this._swapDataView(new DataView(t.buffer,t.byteOffset,t.byteLength))}_swapDataView(t){this.dataView=t,this.buffer=t.buffer,this.byteOffset=t.byteOffset,this.byteLength=t.byteLength}_lengthToEnd(t){return this.byteLength-t}set(t,e,i=r){return t instanceof DataView||t instanceof r?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t instanceof Uint8Array||xt("BufferView.set(): Invalid data argument."),this.toUint8().set(t,e),new i(this,e,t.byteLength)}subarray(t,e){return e=e||this._lengthToEnd(t),new r(this,t,e)}toUint8(){return new Uint8Array(this.buffer,this.byteOffset,this.byteLength)}getUint8Array(t,e){return new Uint8Array(this.buffer,this.byteOffset+t,e)}getString(t=0,e=this.byteLength){return bn(this.getUint8Array(t,e))}getLatin1String(t=0,e=this.byteLength){let i=this.getUint8Array(t,e);return as(i)}getUnicodeString(t=0,e=this.byteLength){let i=[];for(let s=0;s<e&&t+s<this.byteLength;s+=2)i.push(this.getUint16(t+s));return as(i)}getInt8(t){return this.dataView.getInt8(t)}getUint8(t){return this.dataView.getUint8(t)}getInt16(t,e=this.le){return this.dataView.getInt16(t,e)}getInt32(t,e=this.le){return this.dataView.getInt32(t,e)}getUint16(t,e=this.le){return this.dataView.getUint16(t,e)}getUint32(t,e=this.le){return this.dataView.getUint32(t,e)}getFloat32(t,e=this.le){return this.dataView.getFloat32(t,e)}getFloat64(t,e=this.le){return this.dataView.getFloat64(t,e)}getFloat(t,e=this.le){return this.dataView.getFloat32(t,e)}getDouble(t,e=this.le){return this.dataView.getFloat64(t,e)}getUintBytes(t,e,i){switch(e){case 1:return this.getUint8(t,i);case 2:return this.getUint16(t,i);case 4:return this.getUint32(t,i);case 8:return this.getUint64&&this.getUint64(t,i)}}getUint(t,e,i){switch(e){case 8:return this.getUint8(t,i);case 16:return this.getUint16(t,i);case 32:return this.getUint32(t,i);case 64:return this.getUint64&&this.getUint64(t,i)}}toString(t){return this.dataView.toString(t,this.constructor.name)}ensureChunk(){}};function cs(r,t){xt(`${r} '${t}' was not loaded, try using full build of exifr.`)}var yi=class extends Map{constructor(t){super(),this.kind=t}get(t,e){return this.has(t)||cs(this.kind,t),e&&(t in e||(function(i,s){xt(`Unknown ${i} '${s}'.`)})(this.kind,t),e[t].enabled||cs(this.kind,t)),super.get(t)}keyList(){return Array.from(this.keys())}},Ee=new yi("file parser"),At=new yi("segment parser"),Ce=new yi("file reader"),yn=bs.fetch;function nn(r,t){return(e=r).startsWith("data:")||e.length>1e4?ds(r,t,"base64"):rn&&r.includes("://")?ls(r,t,"url",He):rn?ds(r,t,"fs"):bi?ls(r,t,"url",He):void xt("Invalid input argument");var e}async function ls(r,t,e,i){return Ce.has(e)?ds(r,t,e):i?(async function(s,o){let n=await o(s);return new qt(n)})(r,i):void xt(`Parser ${e} is not loaded`)}async function ds(r,t,e){let i=new(Ce.get(e))(r,t);return await i.read(),i}var He=r=>yn(r).then((t=>t.arrayBuffer())),_e=r=>new Promise(((t,e)=>{let i=new FileReader;i.onloadend=()=>t(i.result||new ArrayBuffer),i.onerror=e,i.readAsArrayBuffer(r)})),hs=class extends Map{get tagKeys(){return this.allKeys||(this.allKeys=Array.from(this.keys())),this.allKeys}get tagValues(){return this.allValues||(this.allValues=Array.from(this.values())),this.allValues}};function Ft(r,t,e){let i=new hs;for(let[s,o]of e)i.set(s,o);if(Array.isArray(t))for(let s of t)r.set(s,i);else r.set(t,i);return i}function xs(r,t,e){let i,s=r.get(t);for(i of e)s.set(i[0],i[1])}var Kt=new Map,We=new Map,Pe=new Map,xe=["chunked","firstChunkSize","firstChunkSizeNode","firstChunkSizeBrowser","chunkSize","chunkLimit"],wi=["jfif","xmp","icc","iptc","ihdr"],Ve=["tiff",...wi],wt=["ifd0","ifd1","exif","gps","interop"],ve=[...Ve,...wt],Se=["makerNote","userComment"],xi=["translateKeys","translateValues","reviveValues","multiSegment"],ke=[...xi,"sanitize","mergeOutput","silentErrors"],fr=class{get translate(){return this.translateKeys||this.translateValues||this.reviveValues}},we=class extends fr{get needed(){return this.enabled||this.deps.size>0}constructor(t,e,i,s){if(super(),st(this,"enabled",!1),st(this,"skip",new Set),st(this,"pick",new Set),st(this,"deps",new Set),st(this,"translateKeys",!1),st(this,"translateValues",!1),st(this,"reviveValues",!1),this.key=t,this.enabled=e,this.parse=this.enabled,this.applyInheritables(s),this.canBeFiltered=wt.includes(t),this.canBeFiltered&&(this.dict=Kt.get(t)),i!==void 0)if(Array.isArray(i))this.parse=this.enabled=!0,this.canBeFiltered&&i.length>0&&this.translateTagSet(i,this.pick);else if(typeof i=="object"){if(this.enabled=!0,this.parse=i.parse!==!1,this.canBeFiltered){let{pick:o,skip:n}=i;o&&o.length>0&&this.translateTagSet(o,this.pick),n&&n.length>0&&this.translateTagSet(n,this.skip)}this.applyInheritables(i)}else i===!0||i===!1?this.parse=this.enabled=i:xt(`Invalid options argument: ${i}`)}applyInheritables(t){let e,i;for(e of xi)i=t[e],i!==void 0&&(this[e]=i)}translateTagSet(t,e){if(this.dict){let i,s,{tagKeys:o,tagValues:n}=this.dict;for(i of t)typeof i=="string"?(s=n.indexOf(i),s===-1&&(s=o.indexOf(Number(i))),s!==-1&&e.add(Number(o[s]))):e.add(i)}else for(let i of t)e.add(i)}finalizeFilters(){!this.enabled&&this.deps.size>0?(this.enabled=!0,ur(this.pick,this.deps)):this.enabled&&this.pick.size>0&&ur(this.pick,this.deps)}},Dt={jfif:!1,tiff:!0,xmp:!1,icc:!1,iptc:!1,ifd0:!0,ifd1:!1,exif:!0,gps:!0,interop:!1,ihdr:void 0,makerNote:!1,userComment:!1,multiSegment:!1,skip:[],pick:[],translateKeys:!0,translateValues:!0,reviveValues:!0,sanitize:!0,mergeOutput:!0,silentErrors:!0,chunked:!0,firstChunkSize:void 0,firstChunkSizeNode:512,firstChunkSizeBrowser:65536,chunkSize:65536,chunkLimit:5},an=new Map,ae=class extends fr{static useCached(t){let e=an.get(t);return e!==void 0||(e=new this(t),an.set(t,e)),e}constructor(t){super(),t===!0?this.setupFromTrue():t===void 0?this.setupFromUndefined():Array.isArray(t)?this.setupFromArray(t):typeof t=="object"?this.setupFromObject(t):xt(`Invalid options argument ${t}`),this.firstChunkSize===void 0&&(this.firstChunkSize=bi?this.firstChunkSizeBrowser:this.firstChunkSizeNode),this.mergeOutput&&(this.ifd1.enabled=!1),this.filterNestedSegmentTags(),this.traverseTiffDependencyTree(),this.checkLoadedPlugins()}setupFromUndefined(){let t;for(t of xe)this[t]=Dt[t];for(t of ke)this[t]=Dt[t];for(t of Se)this[t]=Dt[t];for(t of ve)this[t]=new we(t,Dt[t],void 0,this)}setupFromTrue(){let t;for(t of xe)this[t]=Dt[t];for(t of ke)this[t]=Dt[t];for(t of Se)this[t]=!0;for(t of ve)this[t]=new we(t,!0,void 0,this)}setupFromArray(t){let e;for(e of xe)this[e]=Dt[e];for(e of ke)this[e]=Dt[e];for(e of Se)this[e]=Dt[e];for(e of ve)this[e]=new we(e,!1,void 0,this);this.setupGlobalFilters(t,void 0,wt)}setupFromObject(t){let e;for(e of(wt.ifd0=wt.ifd0||wt.image,wt.ifd1=wt.ifd1||wt.thumbnail,Object.assign(this,t),xe))this[e]=ss(t[e],Dt[e]);for(e of ke)this[e]=ss(t[e],Dt[e]);for(e of Se)this[e]=ss(t[e],Dt[e]);for(e of Ve)this[e]=new we(e,Dt[e],t[e],this);for(e of wt)this[e]=new we(e,Dt[e],t[e],this.tiff);this.setupGlobalFilters(t.pick,t.skip,wt,ve),t.tiff===!0?this.batchEnableWithBool(wt,!0):t.tiff===!1?this.batchEnableWithUserValue(wt,t):Array.isArray(t.tiff)?this.setupGlobalFilters(t.tiff,void 0,wt):typeof t.tiff=="object"&&this.setupGlobalFilters(t.tiff.pick,t.tiff.skip,wt)}batchEnableWithBool(t,e){for(let i of t)this[i].enabled=e}batchEnableWithUserValue(t,e){for(let i of t){let s=e[i];this[i].enabled=s!==!1&&s!==void 0}}setupGlobalFilters(t,e,i,s=i){if(t&&t.length){for(let n of s)this[n].enabled=!1;let o=cn(t,i);for(let[n,c]of o)ur(this[n].pick,c),this[n].enabled=!0}else if(e&&e.length){let o=cn(e,i);for(let[n,c]of o)ur(this[n].skip,c)}}filterNestedSegmentTags(){let{ifd0:t,exif:e,xmp:i,iptc:s,icc:o}=this;this.makerNote?e.deps.add(37500):e.skip.add(37500),this.userComment?e.deps.add(37510):e.skip.add(37510),i.enabled||t.skip.add(700),s.enabled||t.skip.add(33723),o.enabled||t.skip.add(34675)}traverseTiffDependencyTree(){let{ifd0:t,exif:e,gps:i,interop:s}=this;s.needed&&(e.deps.add(40965),t.deps.add(40965)),e.needed&&t.deps.add(34665),i.needed&&t.deps.add(34853),this.tiff.enabled=wt.some((o=>this[o].enabled===!0))||this.makerNote||this.userComment;for(let o of wt)this[o].finalizeFilters()}get onlyTiff(){return!wi.map((t=>this[t].enabled)).some((t=>t===!0))&&this.tiff.enabled}checkLoadedPlugins(){for(let t of Ve)this[t].enabled&&!At.has(t)&&cs("segment parser",t)}};function cn(r,t){let e,i,s,o,n=[];for(s of t){for(o of(e=Kt.get(s),i=[],e))(r.includes(o[0])||r.includes(o[1]))&&i.push(o[0]);i.length&&n.push([s,i])}return n}function ss(r,t){return r!==void 0?r:t!==void 0?t:void 0}function ur(r,t){for(let e of t)r.add(e)}st(ae,"default",Dt);var Xt=class{constructor(t){st(this,"parsers",{}),st(this,"output",{}),st(this,"errors",[]),st(this,"pushToErrors",(e=>this.errors.push(e))),this.options=ae.useCached(t)}async read(t){this.file=await(function(e,i){return typeof e=="string"?nn(e,i):bi&&!Ba&&e instanceof HTMLImageElement?nn(e.src,i):e instanceof Uint8Array||e instanceof ArrayBuffer||e instanceof DataView?new qt(e):bi&&e instanceof Blob?ls(e,i,"blob",_e):void xt("Invalid input argument")})(t,this.options)}setup(){if(this.fileParser)return;let{file:t}=this,e=t.getUint16(0);for(let[i,s]of Ee)if(s.canHandle(t,e))return this.fileParser=new s(this.options,this.file,this.parsers),t[i]=!0;this.file.close&&this.file.close(),xt("Unknown file format")}async parse(){let{output:t,errors:e}=this;return this.setup(),this.options.silentErrors?(await this.executeParsers().catch(this.pushToErrors),e.push(...this.fileParser.errors)):await this.executeParsers(),this.file.close&&this.file.close(),this.options.silentErrors&&e.length>0&&(t.errors=e),pr(t)}async executeParsers(){let{output:t}=this;await this.fileParser.parse();let e=Object.values(this.parsers).map((async i=>{let s=await i.parse();i.assignToOutput(t,s)}));this.options.silentErrors&&(e=e.map((i=>i.catch(this.pushToErrors)))),await Promise.all(e)}async extractThumbnail(){this.setup();let{options:t,file:e}=this,i=At.get("tiff",t);var s;if(e.tiff?s={start:0,type:"tiff"}:e.jpeg&&(s=await this.fileParser.getOrFindSegment("tiff")),s===void 0)return;let o=await this.fileParser.ensureSegmentChunk(s),n=this.parsers.tiff=new i(o,t,e),c=await n.extractThumbnail();return e.close&&e.close(),c}};async function vs(r,t){let e=new Xt(t);return await e.read(r),e.parse()}var Ma=Object.freeze({__proto__:null,parse:vs,Exifr:Xt,fileParsers:Ee,segmentParsers:At,fileReaders:Ce,tagKeys:Kt,tagValues:We,tagRevivers:Pe,createDictionary:Ft,extendDictionary:xs,fetchUrlAsArrayBuffer:He,readBlobAsArrayBuffer:_e,chunkedProps:xe,otherSegments:wi,segments:Ve,tiffBlocks:wt,segmentsAndBlocks:ve,tiffExtractables:Se,inheritables:xi,allFormatters:ke,Options:ae}),gr=class{constructor(t,e,i){st(this,"errors",[]),st(this,"ensureSegmentChunk",(async s=>{let o=s.start,n=s.size||65536;if(this.file.chunked)if(this.file.available(o,n))s.chunk=this.file.subarray(o,n);else try{s.chunk=await this.file.readChunk(o,n)}catch(c){xt(`Couldn't read segment: ${JSON.stringify(s)}. ${c.message}`)}else this.file.byteLength>o+n?s.chunk=this.file.subarray(o,n):s.size===void 0?s.chunk=this.file.subarray(o):xt("Segment unreachable: "+JSON.stringify(s));return s.chunk})),this.extendOptions&&this.extendOptions(t),this.options=t,this.file=e,this.parsers=i}injectSegment(t,e){this.options[t].enabled&&this.createParser(t,e)}createParser(t,e){let i=new(At.get(t))(e,this.options,this.file);return this.parsers[t]=i}createParsers(t){for(let e of t){let{type:i,chunk:s}=e,o=this.options[i];if(o&&o.enabled){let n=this.parsers[i];n&&n.append||n||this.createParser(i,s)}}}async readSegments(t){let e=t.map(this.ensureSegmentChunk);await Promise.all(e)}},Gt=class{static findPosition(t,e){let i=t.getUint16(e+2)+2,s=typeof this.headerLength=="function"?this.headerLength(t,e,i):this.headerLength,o=e+s,n=i-s;return{offset:e,length:i,headerLength:s,start:o,size:n,end:o+n}}static parse(t,e={}){return new this(t,new ae({[this.type]:e}),t).parse()}normalizeInput(t){return t instanceof qt?t:new qt(t)}constructor(t,e={},i){st(this,"errors",[]),st(this,"raw",new Map),st(this,"handleError",(s=>{if(!this.options.silentErrors)throw s;this.errors.push(s.message)})),this.chunk=this.normalizeInput(t),this.file=i,this.type=this.constructor.type,this.globalOptions=this.options=e,this.localOptions=e[this.type],this.canTranslate=this.localOptions&&this.localOptions.translate}translate(){this.canTranslate&&(this.translated=this.translateBlock(this.raw,this.type))}get output(){return this.translated?this.translated:this.raw?Object.fromEntries(this.raw):void 0}translateBlock(t,e){let i=Pe.get(e),s=We.get(e),o=Kt.get(e),n=this.options[e],c=n.reviveValues&&!!i,l=n.translateValues&&!!s,d=n.translateKeys&&!!o,u={};for(let[h,g]of t)c&&i.has(h)?g=i.get(h)(g):l&&s.has(h)&&(g=this.translateValue(g,s.get(h))),d&&o.has(h)&&(h=o.get(h)||h),u[h]=g;return u}translateValue(t,e){return e[t]||e.DEFAULT||t}assignToOutput(t,e){this.assignObjectToOutput(t,this.constructor.type,e)}assignObjectToOutput(t,e,i){if(this.globalOptions.mergeOutput)return Object.assign(t,i);t[e]?Object.assign(t[e],i):t[e]=i}};st(Gt,"headerLength",4),st(Gt,"type",void 0),st(Gt,"multiSegment",!1),st(Gt,"canHandle",(()=>!1));function Oa(r){return r===192||r===194||r===196||r===219||r===221||r===218||r===254}function Ua(r){return r>=224&&r<=239}function Fa(r,t,e){for(let[i,s]of At)if(s.canHandle(r,t,e))return i}var mr=class extends gr{constructor(...t){super(...t),st(this,"appSegments",[]),st(this,"jpegSegments",[]),st(this,"unknownSegments",[])}static canHandle(t,e){return e===65496}async parse(){await this.findAppSegments(),await this.readSegments(this.appSegments),this.mergeMultiSegments(),this.createParsers(this.mergedAppSegments||this.appSegments)}setupSegmentFinderArgs(t){t===!0?(this.findAll=!0,this.wanted=new Set(At.keyList())):(t=t===void 0?At.keyList().filter((e=>this.options[e].enabled)):t.filter((e=>this.options[e].enabled&&At.has(e))),this.findAll=!1,this.remaining=new Set(t),this.wanted=new Set(t)),this.unfinishedMultiSegment=!1}async findAppSegments(t=0,e){this.setupSegmentFinderArgs(e);let{file:i,findAll:s,wanted:o,remaining:n}=this;if(!s&&this.file.chunked&&(s=Array.from(o).some((c=>{let l=At.get(c),d=this.options[c];return l.multiSegment&&d.multiSegment})),s&&await this.file.readWhole()),t=this.findAppSegmentsInRange(t,i.byteLength),!this.options.onlyTiff&&i.chunked){let c=!1;for(;n.size>0&&!c&&(i.canReadNextChunk||this.unfinishedMultiSegment);){let{nextChunkOffset:l}=i,d=this.appSegments.some((u=>!this.file.available(u.offset||u.start,u.length||u.size)));if(c=t>l&&!d?!await i.readNextChunk(t):!await i.readNextChunk(l),(t=this.findAppSegmentsInRange(t,i.byteLength))===void 0)return}}}findAppSegmentsInRange(t,e){e-=2;let i,s,o,n,c,l,{file:d,findAll:u,wanted:h,remaining:g,options:m}=this;for(;t<e;t++)if(d.getUint8(t)===255){if(i=d.getUint8(t+1),Ua(i)){if(s=d.getUint16(t+2),o=Fa(d,t,s),o&&h.has(o)&&(n=At.get(o),c=n.findPosition(d,t),l=m[o],c.type=o,this.appSegments.push(c),!u&&(n.multiSegment&&l.multiSegment?(this.unfinishedMultiSegment=c.chunkNumber<c.chunkCount,this.unfinishedMultiSegment||g.delete(o)):g.delete(o),g.size===0)))break;m.recordUnknownSegments&&(c=Gt.findPosition(d,t),c.marker=i,this.unknownSegments.push(c)),t+=s+1}else if(Oa(i)){if(s=d.getUint16(t+2),i===218&&m.stopAfterSos!==!1)return;m.recordJpegSegments&&this.jpegSegments.push({offset:t,length:s,marker:i}),t+=s+1}}return t}mergeMultiSegments(){if(!this.appSegments.some((e=>e.multiSegment)))return;let t=(function(e,i){let s,o,n,c=new Map;for(let l=0;l<e.length;l++)s=e[l],o=s[i],c.has(o)?n=c.get(o):c.set(o,n=[]),n.push(s);return Array.from(c)})(this.appSegments,"type");this.mergedAppSegments=t.map((([e,i])=>{let s=At.get(e,this.options);return s.handleMultiSegments?{type:e,chunk:s.handleMultiSegments(i)}:i[0]}))}getSegment(t){return this.appSegments.find((e=>e.type===t))}async getOrFindSegment(t){let e=this.getSegment(t);return e===void 0&&(await this.findAppSegments(0,[t]),e=this.getSegment(t)),e}};st(mr,"type","jpeg"),Ee.set("jpeg",mr);var ja=[void 0,1,1,2,4,8,1,1,2,4,8,4,8,4],ps=class extends Gt{parseHeader(){var t=this.chunk.getUint16();t===18761?this.le=!0:t===19789&&(this.le=!1),this.chunk.le=this.le,this.headerParsed=!0}parseTags(t,e,i=new Map){let{pick:s,skip:o}=this.options[e];s=new Set(s);let n=s.size>0,c=o.size===0,l=this.chunk.getUint16(t);t+=2;for(let d=0;d<l;d++){let u=this.chunk.getUint16(t);if(n){if(s.has(u)&&(i.set(u,this.parseTag(t,u,e)),s.delete(u),s.size===0))break}else!c&&o.has(u)||i.set(u,this.parseTag(t,u,e));t+=12}return i}parseTag(t,e,i){let{chunk:s}=this,o=s.getUint16(t+2),n=s.getUint32(t+4),c=ja[o];if(c*n<=4?t+=8:t=s.getUint32(t+8),(o<1||o>13)&&xt(`Invalid TIFF value type. block: ${i.toUpperCase()}, tag: ${e.toString(16)}, type: ${o}, offset ${t}`),t>s.byteLength&&xt(`Invalid TIFF value offset. block: ${i.toUpperCase()}, tag: ${e.toString(16)}, type: ${o}, offset ${t} is outside of chunk size ${s.byteLength}`),o===1)return s.getUint8Array(t,n);if(o===2)return mn(s.getString(t,n));if(o===7)return s.getUint8Array(t,n);if(n===1)return this.parseTagValue(o,t);{let l=new((function(u){switch(u){case 1:return Uint8Array;case 3:return Uint16Array;case 4:return Uint32Array;case 5:return Array;case 6:return Int8Array;case 8:return Int16Array;case 9:return Int32Array;case 10:return Array;case 11:return Float32Array;case 12:return Float64Array;default:return Array}})(o))(n),d=c;for(let u=0;u<n;u++)l[u]=this.parseTagValue(o,t),t+=d;return l}}parseTagValue(t,e){let{chunk:i}=this;switch(t){case 1:return i.getUint8(e);case 3:return i.getUint16(e);case 4:return i.getUint32(e);case 5:return i.getUint32(e)/i.getUint32(e+4);case 6:return i.getInt8(e);case 8:return i.getInt16(e);case 9:return i.getInt32(e);case 10:return i.getInt32(e)/i.getInt32(e+4);case 11:return i.getFloat(e);case 12:return i.getDouble(e);case 13:return i.getUint32(e);default:xt(`Invalid tiff type ${t}`)}}},ui=class extends ps{static canHandle(t,e){return t.getUint8(e+1)===225&&t.getUint32(e+4)===1165519206&&t.getUint16(e+8)===0}async parse(){this.parseHeader();let{options:t}=this;return t.ifd0.enabled&&await this.parseIfd0Block(),t.exif.enabled&&await this.safeParse("parseExifBlock"),t.gps.enabled&&await this.safeParse("parseGpsBlock"),t.interop.enabled&&await this.safeParse("parseInteropBlock"),t.ifd1.enabled&&await this.safeParse("parseThumbnailBlock"),this.createOutput()}safeParse(t){let e=this[t]();return e.catch!==void 0&&(e=e.catch(this.handleError)),e}findIfd0Offset(){this.ifd0Offset===void 0&&(this.ifd0Offset=this.chunk.getUint32(4))}findIfd1Offset(){if(this.ifd1Offset===void 0){this.findIfd0Offset();let t=this.chunk.getUint16(this.ifd0Offset),e=this.ifd0Offset+2+12*t;this.ifd1Offset=this.chunk.getUint32(e)}}parseBlock(t,e){let i=new Map;return this[e]=i,this.parseTags(t,e,i),i}async parseIfd0Block(){if(this.ifd0)return;let{file:t}=this;this.findIfd0Offset(),this.ifd0Offset<8&&xt("Malformed EXIF data"),!t.chunked&&this.ifd0Offset>t.byteLength&&xt(`IFD0 offset points to outside of file.
3
- this.ifd0Offset: ${this.ifd0Offset}, file.byteLength: ${t.byteLength}`),t.tiff&&await t.ensureChunk(this.ifd0Offset,sn(this.options));let e=this.parseBlock(this.ifd0Offset,"ifd0");return e.size!==0?(this.exifOffset=e.get(34665),this.interopOffset=e.get(40965),this.gpsOffset=e.get(34853),this.xmp=e.get(700),this.iptc=e.get(33723),this.icc=e.get(34675),this.options.sanitize&&(e.delete(34665),e.delete(40965),e.delete(34853),e.delete(700),e.delete(33723),e.delete(34675)),e):void 0}async parseExifBlock(){if(this.exif||(this.ifd0||await this.parseIfd0Block(),this.exifOffset===void 0))return;this.file.tiff&&await this.file.ensureChunk(this.exifOffset,sn(this.options));let t=this.parseBlock(this.exifOffset,"exif");return this.interopOffset||(this.interopOffset=t.get(40965)),this.makerNote=t.get(37500),this.userComment=t.get(37510),this.options.sanitize&&(t.delete(40965),t.delete(37500),t.delete(37510)),this.unpack(t,41728),this.unpack(t,41729),t}unpack(t,e){let i=t.get(e);i&&i.length===1&&t.set(e,i[0])}async parseGpsBlock(){if(this.gps||(this.ifd0||await this.parseIfd0Block(),this.gpsOffset===void 0))return;let t=this.parseBlock(this.gpsOffset,"gps");return t&&t.has(2)&&t.has(4)&&(t.set("latitude",ln(...t.get(2),t.get(1))),t.set("longitude",ln(...t.get(4),t.get(3)))),t}async parseInteropBlock(){if(!this.interop&&(this.ifd0||await this.parseIfd0Block(),this.interopOffset!==void 0||this.exif||await this.parseExifBlock(),this.interopOffset!==void 0))return this.parseBlock(this.interopOffset,"interop")}async parseThumbnailBlock(t=!1){if(!this.ifd1&&!this.ifd1Parsed&&(!this.options.mergeOutput||t))return this.findIfd1Offset(),this.ifd1Offset>0&&(this.parseBlock(this.ifd1Offset,"ifd1"),this.ifd1Parsed=!0),this.ifd1}async extractThumbnail(){if(this.headerParsed||this.parseHeader(),this.ifd1Parsed||await this.parseThumbnailBlock(!0),this.ifd1===void 0)return;let t=this.ifd1.get(513),e=this.ifd1.get(514);return this.chunk.getUint8Array(t,e)}get image(){return this.ifd0}get thumbnail(){return this.ifd1}createOutput(){let t,e,i,s={};for(e of wt)if(t=this[e],!gn(t))if(i=this.canTranslate?this.translateBlock(t,e):Object.fromEntries(t),this.options.mergeOutput){if(e==="ifd1")continue;Object.assign(s,i)}else s[e]=i;return this.makerNote&&(s.makerNote=this.makerNote),this.userComment&&(s.userComment=this.userComment),s}assignToOutput(t,e){if(this.globalOptions.mergeOutput)Object.assign(t,e);else for(let[i,s]of Object.entries(e))this.assignObjectToOutput(t,i,s)}};function ln(r,t,e,i){var s=r+t/60+e/3600;return i!=="S"&&i!=="W"||(s*=-1),s}st(ui,"type","tiff"),st(ui,"headerLength",10),At.set("tiff",ui);var za=Object.freeze({__proto__:null,default:Ma,Exifr:Xt,fileParsers:Ee,segmentParsers:At,fileReaders:Ce,tagKeys:Kt,tagValues:We,tagRevivers:Pe,createDictionary:Ft,extendDictionary:xs,fetchUrlAsArrayBuffer:He,readBlobAsArrayBuffer:_e,chunkedProps:xe,otherSegments:wi,segments:Ve,tiffBlocks:wt,segmentsAndBlocks:ve,tiffExtractables:Se,inheritables:xi,allFormatters:ke,Options:ae,parse:vs}),Ss={ifd0:!1,ifd1:!1,exif:!1,gps:!1,interop:!1,sanitize:!1,reviveValues:!0,translateKeys:!1,translateValues:!1,mergeOutput:!1},wn=Object.assign({},Ss,{firstChunkSize:4e4,gps:[1,2,3,4]});async function Na(r){let t=new Xt(wn);await t.read(r);let e=await t.parse();if(e&&e.gps){let{latitude:i,longitude:s}=e.gps;return{latitude:i,longitude:s}}}var xn=Object.assign({},Ss,{tiff:!1,ifd1:!0,mergeOutput:!1});async function $a(r){let t=new Xt(xn);await t.read(r);let e=await t.extractThumbnail();return e&&ws?ys.from(e):e}async function Ha(r){let t=await this.thumbnail(r);if(t!==void 0){let e=new Blob([t]);return URL.createObjectURL(e)}}var vn=Object.assign({},Ss,{firstChunkSize:4e4,ifd0:[274]});async function Sn(r){let t=new Xt(vn);await t.read(r);let e=await t.parse();if(e&&e.ifd0)return e.ifd0[274]}var kn=Object.freeze({1:{dimensionSwapped:!1,scaleX:1,scaleY:1,deg:0,rad:0},2:{dimensionSwapped:!1,scaleX:-1,scaleY:1,deg:0,rad:0},3:{dimensionSwapped:!1,scaleX:1,scaleY:1,deg:180,rad:180*Math.PI/180},4:{dimensionSwapped:!1,scaleX:-1,scaleY:1,deg:180,rad:180*Math.PI/180},5:{dimensionSwapped:!0,scaleX:1,scaleY:-1,deg:90,rad:90*Math.PI/180},6:{dimensionSwapped:!0,scaleX:1,scaleY:1,deg:90,rad:90*Math.PI/180},7:{dimensionSwapped:!0,scaleX:1,scaleY:-1,deg:270,rad:270*Math.PI/180},8:{dimensionSwapped:!0,scaleX:1,scaleY:1,deg:270,rad:270*Math.PI/180}}),Ne=!0,$e=!0;if(typeof navigator=="object"){let r=navigator.userAgent;if(r.includes("iPad")||r.includes("iPhone")){let t=r.match(/OS (\d+)_(\d+)/);if(t){let[,e,i]=t;Ne=Number(e)+.1*Number(i)<13.4,$e=!1}}else if(r.includes("OS X 10")){let[,t]=r.match(/OS X 10[_.](\d+)/);Ne=$e=Number(t)<15}if(r.includes("Chrome/")){let[,t]=r.match(/Chrome\/(\d+)/);Ne=$e=Number(t)<81}else if(r.includes("Firefox/")){let[,t]=r.match(/Firefox\/(\d+)/);Ne=$e=Number(t)<77}}async function _a(r){let t=await Sn(r);return Object.assign({canvas:Ne,css:$e},kn[t])}var fs=class extends qt{constructor(...t){super(...t),st(this,"ranges",new us),this.byteLength!==0&&this.ranges.add(0,this.byteLength)}_tryExtend(t,e,i){if(t===0&&this.byteLength===0&&i){let s=new DataView(i.buffer||i,i.byteOffset,i.byteLength);this._swapDataView(s)}else{let s=t+e;if(s>this.byteLength){let{dataView:o}=this._extend(s);this._swapDataView(o)}}}_extend(t){let e;e=ws?ys.allocUnsafe(t):new Uint8Array(t);let i=new DataView(e.buffer,e.byteOffset,e.byteLength);return e.set(new Uint8Array(this.buffer,this.byteOffset,this.byteLength),0),{uintView:e,dataView:i}}subarray(t,e,i=!1){return e=e||this._lengthToEnd(t),i&&this._tryExtend(t,e),this.ranges.add(t,e),super.subarray(t,e)}set(t,e,i=!1){i&&this._tryExtend(e,t.byteLength,t);let s=super.set(t,e);return this.ranges.add(e,s.byteLength),s}async ensureChunk(t,e){this.chunked&&(this.ranges.available(t,e)||await this.readChunk(t,e))}available(t,e){return this.ranges.available(t,e)}},us=class{constructor(){st(this,"list",[])}get length(){return this.list.length}add(t,e,i=0){let s=t+e,o=this.list.filter((n=>dn(t,n.offset,s)||dn(t,n.end,s)));if(o.length>0){t=Math.min(t,...o.map((c=>c.offset))),s=Math.max(s,...o.map((c=>c.end))),e=s-t;let n=o.shift();n.offset=t,n.length=e,n.end=s,this.list=this.list.filter((c=>!o.includes(c)))}else this.list.push({offset:t,length:e,end:s})}available(t,e){let i=t+e;return this.list.some((s=>s.offset<=t&&i<=s.end))}};function dn(r,t,e){return r<=t&&t<=e}var br=class extends fs{constructor(t,e){super(0),st(this,"chunksRead",0),this.input=t,this.options=e}async readWhole(){this.chunked=!1,await this.readChunk(this.nextChunkOffset)}async readChunked(){this.chunked=!0,await this.readChunk(0,this.options.firstChunkSize)}async readNextChunk(t=this.nextChunkOffset){if(this.fullyRead)return this.chunksRead++,!1;let e=this.options.chunkSize,i=await this.readChunk(t,e);return!!i&&i.byteLength===e}async readChunk(t,e){if(this.chunksRead++,(e=this.safeWrapAddress(t,e))!==0)return this._readChunk(t,e)}safeWrapAddress(t,e){return this.size!==void 0&&t+e>this.size?Math.max(0,this.size-t):e}get nextChunkOffset(){if(this.ranges.list.length!==0)return this.ranges.list[0].length}get canReadNextChunk(){return this.chunksRead<this.options.chunkLimit}get fullyRead(){return this.size!==void 0&&this.nextChunkOffset===this.size}read(){return this.options.chunked?this.readChunked():this.readWhole()}close(){}};Ce.set("blob",class extends br{async readWhole(){this.chunked=!1;let r=await _e(this.input);this._swapArrayBuffer(r)}readChunked(){return this.chunked=!0,this.size=this.input.size,super.readChunked()}async _readChunk(r,t){let e=t?r+t:void 0,i=this.input.slice(r,e),s=await _e(i);return this.set(s,r,!0)}});var Va=Object.freeze({__proto__:null,default:za,Exifr:Xt,fileParsers:Ee,segmentParsers:At,fileReaders:Ce,tagKeys:Kt,tagValues:We,tagRevivers:Pe,createDictionary:Ft,extendDictionary:xs,fetchUrlAsArrayBuffer:He,readBlobAsArrayBuffer:_e,chunkedProps:xe,otherSegments:wi,segments:Ve,tiffBlocks:wt,segmentsAndBlocks:ve,tiffExtractables:Se,inheritables:xi,allFormatters:ke,Options:ae,parse:vs,gpsOnlyOptions:wn,gps:Na,thumbnailOnlyOptions:xn,thumbnail:$a,thumbnailUrl:Ha,orientationOnlyOptions:vn,orientation:Sn,rotations:kn,get rotateCanvas(){return Ne},get rotateCss(){return $e},rotation:_a});Ce.set("url",class extends br{async readWhole(){this.chunked=!1;let r=await He(this.input);r instanceof ArrayBuffer?this._swapArrayBuffer(r):r instanceof Uint8Array&&this._swapBuffer(r)}async _readChunk(r,t){let e=t?r+t-1:void 0,i=this.options.httpHeaders||{};(r||e)&&(i.range=`bytes=${[r,e].join("-")}`);let s=await yn(this.input,{headers:i}),o=await s.arrayBuffer(),n=o.byteLength;if(s.status!==416)return n!==t&&(this.size=r+n),this.set(o,r,!0)}});qt.prototype.getUint64=function(r){let t=this.getUint32(r),e=this.getUint32(r+4);return t<1048575?t<<32|e:typeof hr!==void 0?(console.warn("Using BigInt because of type 64uint but JS can only handle 53b numbers."),hr(t)<<hr(32)|hr(e)):void xt("Trying to read 64b value but JS can only handle 53b numbers.")};var gs=class extends gr{parseBoxes(t=0){let e=[];for(;t<this.file.byteLength-4;){let i=this.parseBoxHead(t);if(e.push(i),i.length===0)break;t+=i.length}return e}parseSubBoxes(t){t.boxes=this.parseBoxes(t.start)}findBox(t,e){return t.boxes===void 0&&this.parseSubBoxes(t),t.boxes.find((i=>i.kind===e))}parseBoxHead(t){let e=this.file.getUint32(t),i=this.file.getString(t+4,4),s=t+8;return e===1&&(e=this.file.getUint64(t+8),s+=8),{offset:t,length:e,kind:i,start:s}}parseBoxFullHead(t){if(t.version!==void 0)return;let e=this.file.getUint32(t.start);t.version=e>>24,t.start+=4}},yr=class extends gs{static canHandle(t,e){if(e!==0)return!1;let i=t.getUint16(2);if(i>50)return!1;let s=16,o=[];for(;s<i;)o.push(t.getString(s,4)),s+=4;return o.includes(this.type)}async parse(){let t=this.file.getUint32(0),e=this.parseBoxHead(t);for(;e.kind!=="meta";)t+=e.length,await this.file.ensureChunk(t,16),e=this.parseBoxHead(t);await this.file.ensureChunk(e.offset,e.length),this.parseBoxFullHead(e),this.parseSubBoxes(e),this.options.icc.enabled&&await this.findIcc(e),this.options.tiff.enabled&&await this.findExif(e)}async registerSegment(t,e,i){await this.file.ensureChunk(e,i);let s=this.file.subarray(e,i);this.createParser(t,s)}async findIcc(t){let e=this.findBox(t,"iprp");if(e===void 0)return;let i=this.findBox(e,"ipco");if(i===void 0)return;let s=this.findBox(i,"colr");s!==void 0&&await this.registerSegment("icc",s.offset+12,s.length)}async findExif(t){let e=this.findBox(t,"iinf");if(e===void 0)return;let i=this.findBox(t,"iloc");if(i===void 0)return;let s=this.findExifLocIdInIinf(e),o=this.findExtentInIloc(i,s);if(o===void 0)return;let[n,c]=o;await this.file.ensureChunk(n,c);let l=4+this.file.getUint32(n);n+=l,c-=l,await this.registerSegment("tiff",n,c)}findExifLocIdInIinf(t){this.parseBoxFullHead(t);let e,i,s,o,n=t.start,c=this.file.getUint16(n);for(n+=2;c--;){if(e=this.parseBoxHead(n),this.parseBoxFullHead(e),i=e.start,e.version>=2&&(s=e.version===3?4:2,o=this.file.getString(i+s+2,4),o==="Exif"))return this.file.getUintBytes(i,s);n+=e.length}}get8bits(t){let e=this.file.getUint8(t);return[e>>4,15&e]}findExtentInIloc(t,e){this.parseBoxFullHead(t);let i=t.start,[s,o]=this.get8bits(i++),[n,c]=this.get8bits(i++),l=t.version===2?4:2,d=t.version===1||t.version===2?2:0,u=c+s+o,h=t.version===2?4:2,g=this.file.getUintBytes(i,h);for(i+=h;g--;){let m=this.file.getUintBytes(i,l);i+=l+d+2+n;let E=this.file.getUint16(i);if(i+=2,m===e)return E>1&&console.warn(`ILOC box has more than one extent but we're only processing one
4
- Please create an issue at https://github.com/MikeKovarik/exifr with this file`),[this.file.getUintBytes(i+c,s),this.file.getUintBytes(i+c+s,o)];i+=E*u}}},wr=class extends yr{};st(wr,"type","heic");var xr=class extends yr{};st(xr,"type","avif"),Ee.set("heic",wr),Ee.set("avif",xr),Ft(Kt,["ifd0","ifd1"],[[256,"ImageWidth"],[257,"ImageHeight"],[258,"BitsPerSample"],[259,"Compression"],[262,"PhotometricInterpretation"],[270,"ImageDescription"],[271,"Make"],[272,"Model"],[273,"StripOffsets"],[274,"Orientation"],[277,"SamplesPerPixel"],[278,"RowsPerStrip"],[279,"StripByteCounts"],[282,"XResolution"],[283,"YResolution"],[284,"PlanarConfiguration"],[296,"ResolutionUnit"],[301,"TransferFunction"],[305,"Software"],[306,"ModifyDate"],[315,"Artist"],[316,"HostComputer"],[317,"Predictor"],[318,"WhitePoint"],[319,"PrimaryChromaticities"],[513,"ThumbnailOffset"],[514,"ThumbnailLength"],[529,"YCbCrCoefficients"],[530,"YCbCrSubSampling"],[531,"YCbCrPositioning"],[532,"ReferenceBlackWhite"],[700,"ApplicationNotes"],[33432,"Copyright"],[33723,"IPTC"],[34665,"ExifIFD"],[34675,"ICC"],[34853,"GpsIFD"],[330,"SubIFD"],[40965,"InteropIFD"],[40091,"XPTitle"],[40092,"XPComment"],[40093,"XPAuthor"],[40094,"XPKeywords"],[40095,"XPSubject"]]),Ft(Kt,"exif",[[33434,"ExposureTime"],[33437,"FNumber"],[34850,"ExposureProgram"],[34852,"SpectralSensitivity"],[34855,"ISO"],[34858,"TimeZoneOffset"],[34859,"SelfTimerMode"],[34864,"SensitivityType"],[34865,"StandardOutputSensitivity"],[34866,"RecommendedExposureIndex"],[34867,"ISOSpeed"],[34868,"ISOSpeedLatitudeyyy"],[34869,"ISOSpeedLatitudezzz"],[36864,"ExifVersion"],[36867,"DateTimeOriginal"],[36868,"CreateDate"],[36873,"GooglePlusUploadCode"],[36880,"OffsetTime"],[36881,"OffsetTimeOriginal"],[36882,"OffsetTimeDigitized"],[37121,"ComponentsConfiguration"],[37122,"CompressedBitsPerPixel"],[37377,"ShutterSpeedValue"],[37378,"ApertureValue"],[37379,"BrightnessValue"],[37380,"ExposureCompensation"],[37381,"MaxApertureValue"],[37382,"SubjectDistance"],[37383,"MeteringMode"],[37384,"LightSource"],[37385,"Flash"],[37386,"FocalLength"],[37393,"ImageNumber"],[37394,"SecurityClassification"],[37395,"ImageHistory"],[37396,"SubjectArea"],[37500,"MakerNote"],[37510,"UserComment"],[37520,"SubSecTime"],[37521,"SubSecTimeOriginal"],[37522,"SubSecTimeDigitized"],[37888,"AmbientTemperature"],[37889,"Humidity"],[37890,"Pressure"],[37891,"WaterDepth"],[37892,"Acceleration"],[37893,"CameraElevationAngle"],[40960,"FlashpixVersion"],[40961,"ColorSpace"],[40962,"ExifImageWidth"],[40963,"ExifImageHeight"],[40964,"RelatedSoundFile"],[41483,"FlashEnergy"],[41486,"FocalPlaneXResolution"],[41487,"FocalPlaneYResolution"],[41488,"FocalPlaneResolutionUnit"],[41492,"SubjectLocation"],[41493,"ExposureIndex"],[41495,"SensingMethod"],[41728,"FileSource"],[41729,"SceneType"],[41730,"CFAPattern"],[41985,"CustomRendered"],[41986,"ExposureMode"],[41987,"WhiteBalance"],[41988,"DigitalZoomRatio"],[41989,"FocalLengthIn35mmFormat"],[41990,"SceneCaptureType"],[41991,"GainControl"],[41992,"Contrast"],[41993,"Saturation"],[41994,"Sharpness"],[41996,"SubjectDistanceRange"],[42016,"ImageUniqueID"],[42032,"OwnerName"],[42033,"SerialNumber"],[42034,"LensInfo"],[42035,"LensMake"],[42036,"LensModel"],[42037,"LensSerialNumber"],[42080,"CompositeImage"],[42081,"CompositeImageCount"],[42082,"CompositeImageExposureTimes"],[42240,"Gamma"],[59932,"Padding"],[59933,"OffsetSchema"],[65e3,"OwnerName"],[65001,"SerialNumber"],[65002,"Lens"],[65100,"RawFile"],[65101,"Converter"],[65102,"WhiteBalance"],[65105,"Exposure"],[65106,"Shadows"],[65107,"Brightness"],[65108,"Contrast"],[65109,"Saturation"],[65110,"Sharpness"],[65111,"Smoothness"],[65112,"MoireFilter"],[40965,"InteropIFD"]]),Ft(Kt,"gps",[[0,"GPSVersionID"],[1,"GPSLatitudeRef"],[2,"GPSLatitude"],[3,"GPSLongitudeRef"],[4,"GPSLongitude"],[5,"GPSAltitudeRef"],[6,"GPSAltitude"],[7,"GPSTimeStamp"],[8,"GPSSatellites"],[9,"GPSStatus"],[10,"GPSMeasureMode"],[11,"GPSDOP"],[12,"GPSSpeedRef"],[13,"GPSSpeed"],[14,"GPSTrackRef"],[15,"GPSTrack"],[16,"GPSImgDirectionRef"],[17,"GPSImgDirection"],[18,"GPSMapDatum"],[19,"GPSDestLatitudeRef"],[20,"GPSDestLatitude"],[21,"GPSDestLongitudeRef"],[22,"GPSDestLongitude"],[23,"GPSDestBearingRef"],[24,"GPSDestBearing"],[25,"GPSDestDistanceRef"],[26,"GPSDestDistance"],[27,"GPSProcessingMethod"],[28,"GPSAreaInformation"],[29,"GPSDateStamp"],[30,"GPSDifferential"],[31,"GPSHPositioningError"]]),Ft(We,["ifd0","ifd1"],[[274,{1:"Horizontal (normal)",2:"Mirror horizontal",3:"Rotate 180",4:"Mirror vertical",5:"Mirror horizontal and rotate 270 CW",6:"Rotate 90 CW",7:"Mirror horizontal and rotate 90 CW",8:"Rotate 270 CW"}],[296,{1:"None",2:"inches",3:"cm"}]]);var gi=Ft(We,"exif",[[34850,{0:"Not defined",1:"Manual",2:"Normal program",3:"Aperture priority",4:"Shutter priority",5:"Creative program",6:"Action program",7:"Portrait mode",8:"Landscape mode"}],[37121,{0:"-",1:"Y",2:"Cb",3:"Cr",4:"R",5:"G",6:"B"}],[37383,{0:"Unknown",1:"Average",2:"CenterWeightedAverage",3:"Spot",4:"MultiSpot",5:"Pattern",6:"Partial",255:"Other"}],[37384,{0:"Unknown",1:"Daylight",2:"Fluorescent",3:"Tungsten (incandescent light)",4:"Flash",9:"Fine weather",10:"Cloudy weather",11:"Shade",12:"Daylight fluorescent (D 5700 - 7100K)",13:"Day white fluorescent (N 4600 - 5400K)",14:"Cool white fluorescent (W 3900 - 4500K)",15:"White fluorescent (WW 3200 - 3700K)",17:"Standard light A",18:"Standard light B",19:"Standard light C",20:"D55",21:"D65",22:"D75",23:"D50",24:"ISO studio tungsten",255:"Other"}],[37385,{0:"Flash did not fire",1:"Flash fired",5:"Strobe return light not detected",7:"Strobe return light detected",9:"Flash fired, compulsory flash mode",13:"Flash fired, compulsory flash mode, return light not detected",15:"Flash fired, compulsory flash mode, return light detected",16:"Flash did not fire, compulsory flash mode",24:"Flash did not fire, auto mode",25:"Flash fired, auto mode",29:"Flash fired, auto mode, return light not detected",31:"Flash fired, auto mode, return light detected",32:"No flash function",65:"Flash fired, red-eye reduction mode",69:"Flash fired, red-eye reduction mode, return light not detected",71:"Flash fired, red-eye reduction mode, return light detected",73:"Flash fired, compulsory flash mode, red-eye reduction mode",77:"Flash fired, compulsory flash mode, red-eye reduction mode, return light not detected",79:"Flash fired, compulsory flash mode, red-eye reduction mode, return light detected",89:"Flash fired, auto mode, red-eye reduction mode",93:"Flash fired, auto mode, return light not detected, red-eye reduction mode",95:"Flash fired, auto mode, return light detected, red-eye reduction mode"}],[41495,{1:"Not defined",2:"One-chip color area sensor",3:"Two-chip color area sensor",4:"Three-chip color area sensor",5:"Color sequential area sensor",7:"Trilinear sensor",8:"Color sequential linear sensor"}],[41728,{1:"Film Scanner",2:"Reflection Print Scanner",3:"Digital Camera"}],[41729,{1:"Directly photographed"}],[41985,{0:"Normal",1:"Custom",2:"HDR (no original saved)",3:"HDR (original saved)",4:"Original (for HDR)",6:"Panorama",7:"Portrait HDR",8:"Portrait"}],[41986,{0:"Auto",1:"Manual",2:"Auto bracket"}],[41987,{0:"Auto",1:"Manual"}],[41990,{0:"Standard",1:"Landscape",2:"Portrait",3:"Night",4:"Other"}],[41991,{0:"None",1:"Low gain up",2:"High gain up",3:"Low gain down",4:"High gain down"}],[41996,{0:"Unknown",1:"Macro",2:"Close",3:"Distant"}],[42080,{0:"Unknown",1:"Not a Composite Image",2:"General Composite Image",3:"Composite Image Captured While Shooting"}]]),hn={1:"No absolute unit of measurement",2:"Inch",3:"Centimeter"};gi.set(37392,hn),gi.set(41488,hn);var os={0:"Normal",1:"Low",2:"High"};function pn(r){return typeof r=="object"&&r.length!==void 0?r[0]:r}function fn(r){let t=Array.from(r).slice(1);return t[1]>15&&(t=t.map((e=>String.fromCharCode(e)))),t[2]!=="0"&&t[2]!==0||t.pop(),t.join(".")}function ns(r){if(typeof r=="string"){var[t,e,i,s,o,n]=r.trim().split(/[-: ]/g).map(Number),c=new Date(t,e-1,i);return Number.isNaN(s)||Number.isNaN(o)||Number.isNaN(n)||(c.setHours(s),c.setMinutes(o),c.setSeconds(n)),Number.isNaN(+c)?r:c}}function fi(r){if(typeof r=="string")return r;let t=[];if(r[1]===0&&r[r.length-1]===0)for(let e=0;e<r.length;e+=2)t.push(un(r[e+1],r[e]));else for(let e=0;e<r.length;e+=2)t.push(un(r[e],r[e+1]));return mn(String.fromCodePoint(...t))}function un(r,t){return r<<8|t}gi.set(41992,os),gi.set(41993,os),gi.set(41994,os),Ft(Pe,["ifd0","ifd1"],[[50827,function(r){return typeof r!="string"?bn(r):r}],[306,ns],[40091,fi],[40092,fi],[40093,fi],[40094,fi],[40095,fi]]),Ft(Pe,"exif",[[40960,fn],[36864,fn],[36867,ns],[36868,ns],[40962,pn],[40963,pn]]),Ft(Pe,"gps",[[0,r=>Array.from(r).join(".")],[7,r=>Array.from(r).join(":")]]);var mi=class extends Gt{static canHandle(t,e){return t.getUint8(e+1)===225&&t.getUint32(e+4)===1752462448&&t.getString(e+4,20)==="http://ns.adobe.com/"}static headerLength(t,e){return t.getString(e+4,34)==="http://ns.adobe.com/xmp/extension/"?79:33}static findPosition(t,e){let i=super.findPosition(t,e);return i.multiSegment=i.extended=i.headerLength===79,i.multiSegment?(i.chunkCount=t.getUint8(e+72),i.chunkNumber=t.getUint8(e+76),t.getUint8(e+77)!==0&&i.chunkNumber++):(i.chunkCount=1/0,i.chunkNumber=-1),i}static handleMultiSegments(t){return t.map((e=>e.chunk.getString())).join("")}normalizeInput(t){return typeof t=="string"?t:qt.from(t).getString()}parse(t=this.chunk){if(!this.localOptions.parse)return t;t=(function(o){let n={},c={};for(let l of Dn)n[l]=[],c[l]=0;return o.replace(qa,((l,d,u)=>{if(d==="<"){let h=++c[u];return n[u].push(h),`${l}#${h}`}return`${l}#${n[u].pop()}`}))})(t);let e=vr.findAll(t,"rdf","Description");e.length===0&&e.push(new vr("rdf","Description",void 0,t));let i,s={};for(let o of e)for(let n of o.properties)i=Ka(n.ns,s),Pn(n,i);return(function(o){let n;for(let c in o)n=o[c]=pr(o[c]),n===void 0&&delete o[c];return pr(o)})(s)}assignToOutput(t,e){if(this.localOptions.parse)for(let[i,s]of Object.entries(e))switch(i){case"tiff":this.assignObjectToOutput(t,"ifd0",s);break;case"exif":this.assignObjectToOutput(t,"exif",s);break;case"xmlns":break;default:this.assignObjectToOutput(t,i,s)}else t.xmp=e}};st(mi,"type","xmp"),st(mi,"multiSegment",!0),At.set("xmp",mi);var ms=class r{static findAll(t){return En(t,/([a-zA-Z0-9-]+):([a-zA-Z0-9-]+)=("[^"]*"|'[^']*')/gm).map(r.unpackMatch)}static unpackMatch(t){let e=t[1],i=t[2],s=t[3].slice(1,-1);return s=Cn(s),new r(e,i,s)}constructor(t,e,i){this.ns=t,this.name=e,this.value=i}serialize(){return this.value}},vr=class r{static findAll(t,e,i){if(e!==void 0||i!==void 0){e=e||"[\\w\\d-]+",i=i||"[\\w\\d-]+";var s=new RegExp(`<(${e}):(${i})(#\\d+)?((\\s+?[\\w\\d-:]+=("[^"]*"|'[^']*'))*\\s*)(\\/>|>([\\s\\S]*?)<\\/\\1:\\2\\3>)`,"gm")}else s=/<([\w\d-]+):([\w\d-]+)(#\d+)?((\s+?[\w\d-:]+=("[^"]*"|'[^']*'))*\s*)(\/>|>([\s\S]*?)<\/\1:\2\3>)/gm;return En(t,s).map(r.unpackMatch)}static unpackMatch(t){let e=t[1],i=t[2],s=t[4],o=t[8];return new r(e,i,s,o)}constructor(t,e,i,s){this.ns=t,this.name=e,this.attrString=i,this.innerXml=s,this.attrs=ms.findAll(i),this.children=r.findAll(s),this.value=this.children.length===0?Cn(s):void 0,this.properties=[...this.attrs,...this.children]}get isPrimitive(){return this.value!==void 0&&this.attrs.length===0&&this.children.length===0}get isListContainer(){return this.children.length===1&&this.children[0].isList}get isList(){let{ns:t,name:e}=this;return t==="rdf"&&(e==="Seq"||e==="Bag"||e==="Alt")}get isListItem(){return this.ns==="rdf"&&this.name==="li"}serialize(){if(this.properties.length===0&&this.value===void 0)return;if(this.isPrimitive)return this.value;if(this.isListContainer)return this.children[0].serialize();if(this.isList)return Ga(this.children.map(Wa));if(this.isListItem&&this.children.length===1&&this.attrs.length===0)return this.children[0].serialize();let t={};for(let e of this.properties)Pn(e,t);return this.value!==void 0&&(t.value=this.value),pr(t)}};function Pn(r,t){let e=r.serialize();e!==void 0&&(t[r.name]=e)}var Wa=r=>r.serialize(),Ga=r=>r.length===1?r[0]:r,Ka=(r,t)=>t[r]?t[r]:t[r]={};function En(r,t){let e,i=[];if(!r)return i;for(;(e=t.exec(r))!==null;)i.push(e);return i}function Cn(r){if((function(i){return i==null||i==="null"||i==="undefined"||i===""||i.trim()===""})(r))return;let t=Number(r);if(!Number.isNaN(t))return t;let e=r.toLowerCase();return e==="true"||e!=="false"&&r.trim()}var Dn=["rdf:li","rdf:Seq","rdf:Bag","rdf:Alt","rdf:Description"],qa=new RegExp(`(<|\\/)(${Dn.join("|")})`,"g"),An=Va;async function In(r){try{return await An.parse(r)||null}catch{return null}}function vi(){return Array.from(crypto.getRandomValues(new Uint8Array(16)),r=>r.toString(16).padStart(2,"0")).join("")}async function Ln(r){if(typeof createImageBitmap>"u"||typeof document>"u"){if(r&&typeof r.arrayBuffer=="function"){let c=await r.arrayBuffer(),l=globalThis.Buffer,d=typeof l<"u"?l.from(c).toString("base64"):btoa(String.fromCharCode(...new Uint8Array(c)));return`data:${r.type||"image/png"};base64,${d}`}if(typeof r=="string")return r}let t=await createImageBitmap(r),s=Math.min(1,1654/t.width,2339/t.height);if(s===1&&(r.type==="image/jpeg"||r.type==="image/jpg"||r.type==="image/png"||r.type==="image/webp"))return t.close(),new Promise((c,l)=>{let d=new FileReader;d.onload=()=>c(d.result),d.onerror=l,d.readAsDataURL(r)});let o=document.createElement("canvas");o.width=Math.round(t.width*s),o.height=Math.round(t.height*s),o.getContext("2d").drawImage(t,0,0,o.width,o.height),t.close();let n=r.type==="image/png"?"image/png":"image/jpeg";return o.toDataURL(n,n==="image/png"?void 0:.82)}function Rn(r,t=21,e=.2,i=128){let{data:s,width:o,height:n}=r,c=o+1,l=new Float64Array((o+1)*(n+1)),d=new Float64Array((o+1)*(n+1)),u=new Uint8Array(o*n);for(let g=0;g<n;g++){let m=0,E=0,D=g*o,x=(g+1)*c,w=g*c;for(let A=0;A<o;A++){let k=(D+A)*4,R=s[k]*77+s[k+1]*150+s[k+2]*29>>8;u[D+A]=R,m+=R,E+=R*R,l[x+A+1]=l[w+A+1]+m,d[x+A+1]=d[w+A+1]+E}}let h=Math.floor(t/2);for(let g=0;g<n;g++){let m=Math.max(0,g-h),E=Math.min(n-1,g+h),D=m*c,x=(E+1)*c;for(let w=0;w<o;w++){let A=Math.max(0,w-h),k=Math.min(o-1,w+h),R=(k-A+1)*(E-m+1),U=l[x+k+1]-l[D+k+1]-l[x+A]+l[D+A],P=d[x+k+1]-d[D+k+1]-d[x+A]+d[D+A],y=U/R,B=Math.max(0,P/R-y*y),_=Math.sqrt(B),G=y*(1+e*(_/i-1)),N=g*o+w,V=u[N]<G?0:255,et=N*4;s[et]=V,s[et+1]=V,s[et+2]=V}}return r}function Sr(r){if(!r||typeof r!="object")return{crop:null,rotation:0,filter:"none"};let t=null;r.crop&&typeof r.crop=="object"&&(r.crop.width>0&&r.crop.height>0?t={x:Math.round(r.crop.x||0),y:Math.round(r.crop.y||0),width:Math.round(r.crop.width),height:Math.round(r.crop.height)}:r.crop.w>0&&r.crop.h>0&&(t={x:Number(r.crop.x)||0,y:Number(r.crop.y)||0,w:Number(r.crop.w)||1,h:Number(r.crop.h)||1}));let e=r.rotation!==void 0?r.rotation:r.rotate,i=(Math.round(Number(e)||0)%360+360)%360,s=r.filter==="bw"?"bw":"none";return{crop:t,rotation:i,filter:s}}function Xa(r){if(!r)return!1;let t=Sr(r);return!!(t.crop||t.rotation!==0||t.filter!=="none")}function kr(r,t){let e=Sr(t),i=r.naturalWidth||r.width||0,s=r.naturalHeight||r.height||0,o=document.createElement("canvas"),n=i,c=s,l=0,d=0;if(e.crop){let g=e.crop;"w"in g&&!("width"in g)?(l=Math.max(0,Math.min(Math.round(g.x*i),i)),d=Math.max(0,Math.min(Math.round(g.y*s),s)),n=Math.max(1,Math.min(Math.round(g.w*i),i-l)),c=Math.max(1,Math.min(Math.round(g.h*s),s-d))):(l=Math.max(0,Math.min(g.x,i)),d=Math.max(0,Math.min(g.y,s)),n=Math.max(1,Math.min(g.width,i-l)),c=Math.max(1,Math.min(g.height,s-d)))}o.width=n,o.height=c,o.getContext("2d").drawImage(r,l,d,n,c,0,0,n,c);let h=o;if(e.rotation!==0){let g=e.rotation,m=document.createElement("canvas");g===90||g===270?(m.width=h.height,m.height=h.width):(m.width=h.width,m.height=h.height);let E=m.getContext("2d");E.translate(m.width/2,m.height/2),E.rotate(g*Math.PI/180),E.drawImage(h,-h.width/2,-h.height/2),h=m}if(e.filter==="bw"){let g=h.getContext("2d"),m=g.getImageData(0,0,h.width,h.height);Rn(m),g.putImageData(m,0,0)}return h}function Bn(r,t){if(!r)return Promise.resolve("");let e=Sr(t);return Xa(e)?new Promise((i,s)=>{let o=new Image;o.onload=()=>{try{let n=r.startsWith("data:image/png"),c=n?"image/png":"image/jpeg",l=kr(o,e);i(l.toDataURL(c,n?void 0:.82))}catch(n){s(n)}},o.onerror=s,o.src=r}):Promise.resolve(r)}var Ge=class{#t=null;#r=new Map;#s=new Map;constructor(t=dr()){this.#t=t}get adapter(){return this.#t}get store(){return this.#t?.store??null}async init(){return this.#t.init()}listDocsSync(){return typeof this.#t.listDocsSync=="function"?this.#t.listDocsSync().map(e=>{let i=this.#e(e.pages);return{id:e.id,name:e.name||"",pageCount:i.length,pages:i}}):[]}async listDocs(){return(await this.#t.listDocs()).map(e=>{let i=this.#e(e.pages);return{id:e.id,name:e.name||"",pageCount:i.length,pages:i}})}getDocSync(t){if(!t)return null;if(typeof this.#t.getDocSync=="function"){let s=this.#t.getDocSync(t);return s?{id:s.id,name:s.name||"",pages:this.#e(s.pages)}:null}let i=this.listDocsSync().find(s=>s.id===t);return i?{id:i.id,name:i.name,pages:i.pages||[]}:null}async getDoc(t){if(!t)return null;if(typeof this.#t.getDoc=="function"){let e=await this.#t.getDoc(t);return e?{id:e.id,name:e.name||"",pages:this.#e(e.pages)}:null}return this.getDocSync(t)}async createDoc(t="Untitled Document",e=[]){let i=vi(),s=this.#e(e),o={id:i,name:t||"Untitled Document",pages:s};return await this.#t.saveDoc(i,o),o}async saveDoc(t,e){if(!t)throw new Error("Cannot save document without an ID");let i=this.#e(e.pages);await this.#t.saveDoc(t,{id:t,name:e.name||"",pages:i})}async renameDoc(t,e){if(typeof this.#t.renameDoc=="function")return this.#t.renameDoc(t,e);let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);i.name=e,await this.saveDoc(t,i)}async deleteDoc(t,{soft:e=!0,timeoutMs:i=5e3}={}){if(!t)return;let s=this.getDocSync(t);if(s){if(this.#l(t),await this.#t.deleteDoc(t),e&&i>0){let o=setTimeout(async()=>{this.#r.delete(t)},i);this.#r.set(t,{doc:s,timerId:o})}return{id:t,name:s.name,undo:()=>this.undoDeleteDoc(t)}}}#l(t){if(this.#r.has(t)){let e=this.#r.get(t);clearTimeout(e.timerId),this.#r.delete(t)}}async undoDeleteDoc(t){let e=this.#r.get(t);return e?(clearTimeout(e.timerId),this.#r.delete(t),await this.#t.saveDoc(t,e.doc),e.doc):null}isSoftDeletedDoc(t){return this.#r.has(t)}async addPages(t,e){let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);let s=Array.isArray(e)?e:[e];i.pages.push(...s),await this.saveDoc(t,i)}async updatePage(t,e,i){let s=await this.getDoc(t);if(!s)throw new Error(`Document "${t}" not found`);let o=s.pages.findIndex(n=>n.id===e);if(o===-1)throw new Error(`Page "${e}" not found in document "${t}"`);s.pages[o]={...s.pages[o],...i},await this.saveDoc(t,s)}async reorderPages(t,e){let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);let s=new Map(i.pages.map(n=>[n.id,n])),o=[];for(let n of e)s.has(n)&&(o.push(s.get(n)),s.delete(n));for(let n of s.values())o.push(n);i.pages=o,await this.saveDoc(t,i)}async deletePage(t,e,{soft:i=!0,timeoutMs:s=5e3}={}){let o=await this.getDoc(t);if(!o)throw new Error(`Document "${t}" not found`);let n=o.pages.findIndex(u=>u.id===e);if(n===-1)return;let[c]=o.pages.splice(n,1);await this.saveDoc(t,o);let l=`${t}:${e}`;if(this.#a(l),!i||s<=0){if(typeof this.#t.deletePage=="function")try{await this.#t.deletePage(t,e)}catch(u){console.warn("[DocRepository] Adapter deletePage error:",u)}return}let d=setTimeout(async()=>{if(this.#s.delete(l),typeof this.#t.deletePage=="function")try{await this.#t.deletePage(t,e)}catch(u){console.warn("[DocRepository] Adapter deletePage error:",u)}},s);return this.#s.set(l,{docId:t,pageId:e,page:c,index:n,timerId:d}),{docId:t,pageId:e,undo:()=>this.undoDeletePage(t,e)}}#a(t){if(this.#s.has(t)){let e=this.#s.get(t);clearTimeout(e.timerId),this.#s.delete(t)}}async undoDeletePage(t,e){let i=`${t}:${e}`,s=this.#s.get(i);if(!s)return null;clearTimeout(s.timerId),this.#s.delete(i);let o=await this.getDoc(t);if(!o)return null;let n=Math.min(s.index,o.pages.length);return o.pages.splice(n,0,s.page),await this.saveDoc(t,o),s.page}isSoftDeletedPage(t,e){return this.#s.has(`${t}:${e}`)}subscribe(t){return this.#t.subscribe(t)}async getAllDocs(){let t=await this.listDocs(),e={};for(let i of t)e[i.id]=i;return e}async exportAll(){let t=await this.listDocs(),e={};for(let i of t){let s=await this.getDoc(i.id),o=[];for(let n of s?.pages||[]){if(!n){o.push(n);continue}let c={...n},l=c.blob instanceof Blob?c.blob:null;if(!l&&typeof c.src=="string"&&c.src.startsWith("blob:"))try{l=await(await fetch(c.src)).blob()}catch{}l&&(c.src=await rs(l));let d=c.originalBlob instanceof Blob?c.originalBlob:null;if(!d&&typeof c.originalSrc=="string"&&c.originalSrc.startsWith("blob:"))try{d=await(await fetch(c.originalSrc)).blob()}catch{}d&&(c.originalSrc=await rs(d)),delete c.blob,delete c.originalBlob,o.push(c)}e[i.id]={name:i.name,pages:JSON.stringify(o)}}return e}async importDocs(t){let e=0;for(let[i,s]of Object.entries(t||{})){await this.getDoc(i)||e++;let n=this.#e(s.pages);await this.saveDoc(i,{name:s.name||"",pages:n})}return e}#e(t){if(Array.isArray(t))return[...t];if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}},Ja=new Ge;var Tn=".";function Mn(){return Tn}function Si(r){typeof r=="string"&&(Tn=r.replace(/\/+$/,"")||".")}var Pr=class{async recognizeImageText(t,e={}){throw new Error("OcrPort.recognizeImageText() must be implemented by adapter")}async recognizeDocumentPages(t,e={}){throw new Error("OcrPort.recognizeDocumentPages() must be implemented by adapter")}async getOcrWorker(t="eng",e=null){throw new Error("OcrPort.getOcrWorker() must be implemented by adapter")}async terminateOcrWorker(){throw new Error("OcrPort.terminateOcrWorker() must be implemented by adapter")}};var Jt=class extends Pr{async recognizeImageText(t,e={}){let i=new Error('Feature "ocr" is disabled or OCR module not opted in');throw i.code="FEATURE_DISABLED",i}async recognizeDocumentPages(t,e={}){let i=new Error('Feature "ocr" is disabled or OCR module not opted in');throw i.code="FEATURE_DISABLED",i}async getOcrWorker(){return null}async terminateOcrWorker(){}};var Er=class{async exportDocumentAsPdf(t,e,i={}){throw new Error("PdfPort.exportDocumentAsPdf() must be implemented by adapter")}async renderPdfPagesToDataUrls(t){throw new Error("PdfPort.renderPdfPagesToDataUrls() must be implemented by adapter")}};var De=class extends Er{async exportDocumentAsPdf(t,e,i={}){let s=new Error('Feature "pdf" is disabled or PDF module not opted in');throw s.code="FEATURE_DISABLED",s}async renderPdfPagesToDataUrls(t){return[]}};var Ae=class{async renderEdits(t,e){throw new Error("ImageProcessorPort.renderEdits() must be implemented by adapter")}async crop(t,e){throw new Error("ImageProcessorPort.crop() must be implemented by adapter")}async rotate(t,e){throw new Error("ImageProcessorPort.rotate() must be implemented by adapter")}async applyFilter(t,e){throw new Error("ImageProcessorPort.applyFilter() must be implemented by adapter")}};function Ya(r){return new Promise((t,e)=>{let i=new Image;i.onload=()=>t(i),i.onerror=e,i.src=r})}var ki=class extends Ae{async renderEdits(t,e={}){if(!t)return"";if(typeof document>"u")return t;try{let i=await Ya(t),s={...e};return e?.crop&&"w"in e.crop&&(s.crop={x:Math.round((e.crop.x||0)*i.naturalWidth),y:Math.round((e.crop.y||0)*i.naturalHeight),width:Math.round((e.crop.w||1)*i.naturalWidth),height:Math.round((e.crop.h||1)*i.naturalHeight)}),e?.rotate!==void 0&&(s.rotation=e.rotate),kr(i,s).toDataURL("image/jpeg",.92)}catch{return t}}async crop(t,e){return this.renderEdits(t,{crop:e})}async rotate(t,e){return this.renderEdits(t,{rotate:e})}async applyFilter(t,e){return this.renderEdits(t,{filter:e})}};var Pi=class extends Ae{async renderEdits(t,e){return t}async crop(t,e){return t}async rotate(t,e){return t}async applyFilter(t,e){return t}};function ks(r={}){let t=r&&r.crop&&typeof r.crop=="object"?{x:Math.max(0,Math.min(1,Number(r.crop.x)||0)),y:Math.max(0,Math.min(1,Number(r.crop.y)||0)),w:Math.max(0,Math.min(1,Number(r.crop.w)||1)),h:Math.max(0,Math.min(1,Number(r.crop.h)||1))}:null,e=0,i=r?.rotate!==void 0?r.rotate:r?.rotation;if(i!==void 0){let o=(Math.round(Number(i)/90)*90%360+360)%360;(o===90||o===180||o===270)&&(e=o)}let s=r&&r.filter==="bw"?"bw":"none";return{crop:t,rotate:e,filter:s}}var Ct=r=>Math.round(r*1e6)/1e6;function Ps(r,t=0){if(!r)return null;let e=(Math.round(Number(t)/90)*90%360+360)%360,{x:i,y:s,w:o,h:n}=r;return e===90?{x:Ct(Math.max(0,Math.min(1,1-s-n))),y:Ct(Math.max(0,Math.min(1,i))),w:Ct(Math.max(.01,Math.min(1,n))),h:Ct(Math.max(.01,Math.min(1,o)))}:e===180?{x:Ct(Math.max(0,Math.min(1,1-i-o))),y:Ct(Math.max(0,Math.min(1,1-s-n))),w:Ct(Math.max(.01,Math.min(1,o))),h:Ct(Math.max(.01,Math.min(1,n)))}:e===270?{x:Ct(Math.max(0,Math.min(1,s))),y:Ct(Math.max(0,Math.min(1,1-i-o))),w:Ct(Math.max(.01,Math.min(1,n))),h:Ct(Math.max(.01,Math.min(1,o)))}:{x:Ct(Math.max(0,Math.min(1,i))),y:Ct(Math.max(0,Math.min(1,s))),w:Ct(Math.max(.01,Math.min(1,o))),h:Ct(Math.max(.01,Math.min(1,n)))}}function Es(r,t=0){return Ps(r,t)}function Cs(r,t=0){return Ps(r,-t)}var St={PAGE_ADDED:"copio:page-added",PAGE_REMOVED:"copio:page-removed",PAGES_CHANGED:"copio:pages-changed",SCAN_COMPLETE:"copio:scan-complete",EXPORT_PROGRESS:"copio:export-progress",EXPORT_COMPLETE:"copio:export-complete",OCR_COMPLETE:"copio:ocr-complete",SYNC_CONNECTED:"copio:sync-connected",ERROR:"copio:error"};function On(r,t,e={}){let i=new CustomEvent(t,{bubbles:!0,composed:!0,cancelable:!0,detail:e});return r&&typeof r.dispatchEvent=="function"&&r.dispatchEvent(i),i}var Is=["crop","rotate","filter","ocr","export","sync"],Ds=["pdf","zip","png","jpg"],As=["eng"],Un={};function Ke(r){return Un[r]?Un[r]:typeof globalThis<"u"&&globalThis.__copio_services__?.[r]?globalThis.__copio_services__[r]:null}function Qa(r){return r?r instanceof Set?new Set(r):Array.isArray(r)?new Set(r.map(t=>String(t).trim().toLowerCase()).filter(Boolean)):typeof r=="string"?new Set(r.split(/[\s,]+/).map(t=>t.trim().toLowerCase()).filter(Boolean)):new Set(Is):new Set(Is)}function Cr(r,t){return r?Array.isArray(r)?r.map(e=>String(e).trim().toLowerCase()).filter(Boolean):typeof r=="string"?r.split(/[\s,]+/).map(e=>e.trim().toLowerCase()).filter(Boolean):[...t]:[...t]}var Ei=class{#t=new Set(Is);#r=[...Ds];#s=[...As];#l=0;#a="";#e=null;#c=null;#o={};#i=!0;#n=!0;#d=null;#h=new Map;#p=new Map;constructor(t={}){this.#e=t.storage||dr(t),this.#c=t.repository||new Ge(this.#e),t.services&&(this.#o={...t.services}),t.imageProcessor?(this.#d=t.imageProcessor,this.#o.imageProcessor=t.imageProcessor):this.getService("imageProcessor")?this.#d=this.getService("imageProcessor"):typeof document<"u"?this.#d=new ki:this.#d=new Pi,t.features!==void 0&&this.setFeatures(t.features),t.exportFormats!==void 0&&(this.#r=Cr(t.exportFormats,Ds)),t.ocrLanguages!==void 0&&(this.#s=Cr(t.ocrLanguages,As)),t.maxPages!==void 0&&(this.#l=Math.max(0,Number(t.maxPages)||0)),t.assetBase!==void 0&&Si(t.assetBase),t.licenseKey!==void 0&&(this.#a=String(t.licenseKey||"")),t.ocr!==void 0?this.ocr=!!t.ocr:t.features!==void 0&&!this.hasFeature("ocr")&&(this.ocr=!1),t.pdf!==void 0?this.pdf=!!t.pdf:t.exportFormats!==void 0&&!this.#r.includes("pdf")&&(this.pdf=!1)}async init(){return this.#e.init()}setService(t,e){this.#o[t]=e}getService(t){return this.#o[t]||Ke(t)}hasFeature(t){return t?this.#t.has(String(t).trim().toLowerCase()):!1}get features(){return Array.from(this.#t)}setFeatures(t){this.#t=Qa(t),this.hasFeature("ocr")?(this.#i=!0,this.getService("ocr")instanceof Jt&&this.setService("ocr",Ke("ocr"))):(this.#i=!1,this.setService("ocr",new Jt))}enableFeature(t){if(t){let e=String(t).trim().toLowerCase();this.#t.add(e),e==="ocr"&&(this.#i=!0,this.getService("ocr")instanceof Jt&&this.setService("ocr",Ke("ocr")))}}disableFeature(t){if(t){let e=String(t).trim().toLowerCase();this.#t.delete(e),e==="ocr"&&(this.#i=!1,this.setService("ocr",new Jt))}}get ocr(){return this.#i&&this.hasFeature("ocr")}set ocr(t){this.#i=!!t,this.#i?(this.enableFeature("ocr"),this.getService("ocr")instanceof Jt&&this.setService("ocr",Ke("ocr"))):(this.disableFeature("ocr"),this.setService("ocr",new Jt))}get pdf(){return this.#n&&this.#r.includes("pdf")}set pdf(t){this.#n=!!t,this.#n?(this.#r.includes("pdf")||this.#r.push("pdf"),this.getService("pdf")instanceof De&&this.setService("pdf",Ke("pdf"))):(this.#r=this.#r.filter(e=>e!=="pdf"),this.setService("pdf",new De))}get exportFormats(){return[...this.#r]}set exportFormats(t){this.#r=Cr(t,Ds),this.#r.includes("pdf")?(this.#n=!0,this.getService("pdf")instanceof De&&this.setService("pdf",Ke("pdf"))):(this.#n=!1,this.setService("pdf",new De))}get ocrLanguages(){return[...this.#s]}set ocrLanguages(t){this.#s=Cr(t,As)}get maxPages(){return this.#l}set maxPages(t){this.#l=Math.max(0,Number(t)||0)}get assetBase(){return Mn()}set assetBase(t){Si(t)}get licenseKey(){return this.#a}set licenseKey(t){this.#a=String(t||"")}get storage(){return this.#e}setStorage(t){t&&(this.#e=t,this.#c=new Ge(this.#e))}#u(t,e){this.#h.has(t)||this.#h.set(t,[]);let i=this.#h.get(t);i.push(e),i.length>50&&i.shift(),this.#p.has(t)&&(this.#p.get(t).length=0)}get imageProcessor(){return this.#d}setImageProcessor(t){t&&(this.#d=t,this.setService("imageProcessor",t))}async renderEdits(t,e){if(!t)return"";let i=ks(e);return this.#d?this.#d.renderEdits(t,i):Bn(t,i)}get docs(){return this.#c}async listDocuments(){return this.#c.listDocs()}async getDocument(t){return this.#c.getDoc(t)}async createDocument(t,e){return this.#c.createDoc(t,e)}async deleteDocument(t,e={}){return this.#c.deleteDoc(t,e)}async undoDeleteDocument(t){return this.#c.undoDeleteDoc(t)}async renameDocument(t,e){return this.#c.renameDoc(t,e)}async addPages(t,e){return this.#c.addPages(t,e)}async deletePage(t,e,i={}){return this.#u(t,{type:"delete",pageId:e}),this.#c.deletePage(t,e,i)}async undoDeletePage(t,e){return this.#c.undoDeletePage(t,e)}async updatePage(t,e,i){return this.#c.updatePage(t,e,i)}async reorderPages(t,e){let i=await this.getDocument(t),s=i?.pages?i.pages.map(o=>o.id):[];return this.#u(t,{type:"reorder",priorOrder:s,newOrder:[...e]}),this.#c.reorderPages(t,e)}async#g(t){if(t)return t;let e=await this.listDocuments();return e.length>0?e[0].id:null}async applyEdit(t,e,i){let s=await this.#g(t),o=s?await this.getDocument(s):null;if(!o||!o.pages)throw new Error(`Document with ID "${s||t}" not found`);let n=o.pages.find(g=>g.id===e);if(!n)throw new Error(`Page with ID "${e}" not found in document "${s}"`);let c={...n.edits||{crop:null,rotate:0,filter:"none"}},l=n.src,d=ks({...c,...i}),u=n.originalSrc||n.src,h=u;return this.#d&&(h=await this.#d.renderEdits(u,d)),await this.updatePage(s,e,{originalSrc:u,src:h,edits:d}),this.#u(s,{type:"edit",pageId:e,priorEdits:c,priorSrc:l,newEdits:d,newSrc:h}),{...n,originalSrc:u,src:h,edits:d}}async undo(t){let e=await this.#g(t),i=e?this.#h.get(e):null;if(!i||i.length===0)return null;let s=i.pop();return this.#p.has(e)||this.#p.set(e,[]),this.#p.get(e).push(s),s.type==="edit"?(await this.updatePage(e,s.pageId,{edits:s.priorEdits,src:s.priorSrc}),{type:"edit",pageId:s.pageId,restoredEdits:s.priorEdits}):s.type==="delete"?(await this.undoDeletePage(e,s.pageId),{type:"delete",pageId:s.pageId}):s.type==="reorder"?(await this.#c.reorderPages(e,s.priorOrder),{type:"reorder",priorOrder:s.priorOrder}):s}async redo(t){let e=await this.#g(t),i=e?this.#p.get(e):null;if(!i||i.length===0)return null;let s=i.pop();return this.#h.has(e)||this.#h.set(e,[]),this.#h.get(e).push(s),s.type==="edit"?(await this.updatePage(e,s.pageId,{edits:s.newEdits,src:s.newSrc}),{type:"edit",pageId:s.pageId,appliedEdits:s.newEdits}):s.type==="delete"?(await this.deletePage(e,s.pageId),{type:"delete",pageId:s.pageId}):s.type==="reorder"?(await this.reorderPages(e,s.newOrder),{type:"reorder",newOrder:s.newOrder}):s}subscribe(t){return this.#c.subscribe(t)}async addFiles(t,e=null){if(!t||t.length===0)return[];let i=Array.from(t),s=[];for(let n of i)if(n.type==="application/pdf"){let c=this.getService("pdf");if(c&&typeof c.renderPdfPagesToDataUrls=="function"){let l=await c.renderPdfPagesToDataUrls(n);for(let d of l)s.push({id:vi(),src:d,originalSrc:d,edits:{crop:null,rotation:0,filter:"none"},type:"image",name:n.name||"PDF Page"})}else console.warn("PDF import service (PdfPort) not registered. Skipping PDF file.")}else if(n.type&&n.type.startsWith("image/")){let c=await Ln(n),l=null;try{l=await In(n)}catch{}s.push({id:vi(),src:c,originalSrc:c,edits:{crop:null,rotation:0,filter:"none"},type:"image",name:n.name||"Captured Image",orientation:l})}if(s.length===0)return[];await this.init();let o=e;if(o)await this.getDocument(o)||await this.#c.saveDoc(o,{name:"Scanned Document",pages:[]});else{let n=await this.listDocuments();n.length>0?o=n[0].id:o=(await this.createDocument("Scanned Document",[])).id}if(this.#l>0){let n=(await this.getDocument(o))?.pages||[],c=Math.max(0,this.#l-n.length);if(c<=0)throw new Error(`Maximum page limit (${this.#l}) reached`);s.splice(c)}return await this.addPages(o,s),s}async getPages(t=null){let e=t;if(!e){let s=await this.listDocuments();if(s.length===0)return[];e=s[0].id}return(await this.getDocument(e))?.pages||[]}async clear(t=null){let e=t;if(!e){let s=await this.listDocuments();if(s.length===0)return;e=s[0].id}let i=await this.getDocument(e);if(!(!i||!i.pages))for(let s of i.pages)await this.deletePage(e,s.id)}async#f(t){if(Array.isArray(t))return{docName:"document",pages:t,docId:null};if(typeof t=="string"){let i=await this.getDocument(t);return{docName:i?.name||"document",pages:i?.pages||[],docId:t}}let e=await this.listDocuments();if(e.length>0){let i=await this.getDocument(e[0].id);return{docName:i?.name||"document",pages:i?.pages||[],docId:e[0].id}}return{docName:"document",pages:[],docId:null}}async exportPdf(t,e={}){if(!this.hasFeature("export")){let n=new Error('Feature "export" is disabled');throw Object.assign(n,{code:"FEATURE_DISABLED"}),n}if(!this.#n||!this.#r.includes("pdf")){let n=new Error('Feature "pdf" is disabled');throw Object.assign(n,{code:"FEATURE_DISABLED"}),n}let{docName:i,pages:s}=await this.#f(t),o=this.getService("pdf")||this.getService("export");if(!o||typeof o.exportDocumentAsPdf!="function")throw new Error("Export service (PdfPort) is not registered. Import @copio/sdk or register an exportService.");return o.exportDocumentAsPdf(i,s,{download:!1,showProgress:!1,onOcrComplete:async()=>{if(typeof t=="string"){let n=await this.#e.getDoc(t);n&&(n.pages=s,await this.#e.saveDoc(t,n))}},...e})}async exportZip(t,e={}){if(!this.hasFeature("export")){let n=new Error('Feature "export" is disabled');throw Object.assign(n,{code:"FEATURE_DISABLED"}),n}let{docName:i,pages:s}=await this.#f(t),o=this.getService("export");if(!o||typeof o.exportDocumentAsImages!="function")throw new Error("Export service is not registered. Import @copio/sdk or register an exportService.");return o.exportDocumentAsImages(i,s,{download:!1,showProgress:!1,...e})}async runOcr(t,e=null,i={}){if(!this.#i||!this.hasFeature("ocr")){let d=new Error('Feature "ocr" is disabled');throw Object.assign(d,{code:"FEATURE_DISABLED"}),d}let{pages:s}=await this.#f(t),o=s;e&&(o=s.filter(d=>d.id===e));let n=this.getService("ocr");if(!n||typeof n.recognizeDocumentPages!="function")throw new Error("OCR service (OcrPort) is not registered. Import @copio/sdk or register an ocrService.");let c=i.lang||this.#s[0]||"eng",l=await n.recognizeDocumentPages(o,{lang:c,...i});if(Array.isArray(l.pagesResults)){for(let d of l.pagesResults){let u=o.find(h=>h.id===d.pageId)||o[d.pageIndex];u&&(u.ocrText=d.text,u.ocrConfidence=d.confidence,u.ocrWords=d.words)}if(typeof t=="string"){let d=await this.#e.getDoc(t);if(d&&Array.isArray(d.pages)){for(let u of l.pagesResults){let h=d.pages.find(g=>g.id===u.pageId)||d.pages[u.pageIndex];h&&(h.ocrText=u.text,h.ocrConfidence=u.confidence,h.ocrWords=u.words)}await this.#e.saveDoc(t,d)}}}return{text:l.combinedText,...l}}async sync(t={}){if(!this.hasFeature("sync")){let i=new Error('Feature "sync" is disabled');throw Object.assign(i,{code:"FEATURE_DISABLED"}),i}let e=this.getService("sync");if(!e)throw new Error("Sync service (SyncPort) is not registered. Import @copio/sdk or register a syncService.");return new e(this.#c,t.onStateChange)}};var zn=null,Fn={success:{slVariant:"success",defaultIcon:"check-circle",defaultDuration:3e3},error:{slVariant:"danger",defaultIcon:"exclamation-octagon",defaultDuration:5e3},danger:{slVariant:"danger",defaultIcon:"exclamation-octagon",defaultDuration:5e3},warning:{slVariant:"warning",defaultIcon:"exclamation-triangle",defaultDuration:4e3},info:{slVariant:"primary",defaultIcon:"info-circle",defaultDuration:4e3},primary:{slVariant:"primary",defaultIcon:"info-circle",defaultDuration:4e3},neutral:{slVariant:"neutral",defaultIcon:"info-circle",defaultDuration:4e3}};function qe(r){zn=r||null}function Xe(){return zn||(typeof document<"u"?document.body:null)}function Za(){let t=customElements.get("sl-alert")?.toastStack;t&&t.querySelectorAll("sl-alert").forEach(i=>{typeof i.hide=="function"&&i.hide()})}async function jn(r,t={}){let e={};if(typeof r=="string"||r instanceof HTMLElement?e={message:r,...t}:r&&typeof r=="object"&&(e={...r,...t}),typeof customElements<"u"&&!customElements.get("sl-alert")&&await Promise.race([customElements.whenDefined("sl-alert"),new Promise(h=>setTimeout(h,200))]),typeof customElements>"u"||!customElements.get("sl-alert"))return null;let i=customElements.get("sl-alert"),s=e.variant||"info",o=Fn[s]||Fn.info,n=e.container||Xe();if(i?.toastStack&&n){let h=i.toastStack;h.parentElement!==n&&n.appendChild(h),n!==document.body?(h.style.position="absolute",h.style.width="auto",h.style.maxWidth="calc(100% - 24px)",h.style.left="12px",h.style.right="12px",h.style.insetInlineStart="12px",h.style.insetInlineEnd="12px",e.position==="top"?(h.style.top="12px",h.style.bottom="auto"):(h.style.top="auto",h.style.bottom="16px"),h.style.maxHeight="100%",h.style.overflow="auto"):(h.style.position="",h.style.width="",h.style.left="",h.style.right="",h.style.top="",h.style.bottom="",h.style.insetInlineStart="",h.style.insetInlineEnd="",h.style.maxHeight="",h.style.maxWidth="",h.style.overflow="")}let c=document.createElement("sl-alert");c.variant=o.slVariant,c.closable=e.closable!==!1,c.duration=e.duration!==void 0?e.duration:o.defaultDuration;let l=e.icon!==void 0?e.icon:o.defaultIcon;if(l){let h=document.createElement("sl-icon");h.slot="icon",h.name=l,c.appendChild(h)}let d=document.createElement("span");if(e.message instanceof HTMLElement?d.appendChild(e.message):e.html?d.innerHTML=e.message||"":d.textContent=e.message||"",e.action){let h=document.createElement("div");h.style.display="flex",h.style.alignItems="center",h.style.justifyContent="space-between",h.style.gap="0.75rem",h.style.width="100%",d.style.flex="1",h.appendChild(d);let g=document.createElement("sl-button");g.size="small",g.variant=e.action.variant||"text",g.textContent=e.action.text||"Action",g.style.color="inherit",g.style.fontWeight="600",g.style.padding="0",g.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),typeof e.action.onClick=="function"&&e.action.onClick(m,c),e.action.autoClose!==!1&&c.hide()}),h.appendChild(g),c.appendChild(h)}else c.appendChild(d);let u=c.toast();return c.toastPromise=u,c}function tc(r,t={}){return Ci.show({message:r,variant:"success",...t})}function ec(r,t={}){return Ci.show({message:r,variant:"error",...t})}function ic(r,t={}){return Ci.show({message:r,variant:"warning",...t})}function rc(r,t={}){return Ci.show({message:r,variant:"info",...t})}function sc(r,t,e={}){return Ci.show({message:r,variant:e?.variant||"primary",icon:e?.icon!==void 0?e.icon:"arrow-counterclockwise",duration:e?.duration!==void 0?e.duration:5e3,closable:e?.closable!==!1,action:{text:e?.actionText||"Undo",onClick:(i,s)=>{typeof t=="function"&&t(i,s)},autoClose:!0},...e})}async function oc(r,t={}){let e={};if(typeof r=="string"?e={message:r,...t}:r&&typeof r=="object"&&(e={...r,...t}),typeof customElements<"u"&&(!customElements.get("sl-alert")||!customElements.get("sl-progress-bar"))&&await Promise.race([Promise.all([customElements.whenDefined("sl-alert"),customElements.whenDefined("sl-progress-bar")]),new Promise(D=>setTimeout(D,200))]),typeof customElements>"u"||!customElements.get("sl-alert"))return{alert:null,progressBar:null,update(){},close(){}};let i=e.container||Xe(),s=document.createElement("sl-alert");s.variant=e.variant||"primary",s.closable=e.closable===!0,s.duration=1/0;let o=e.icon!==void 0?e.icon:"arrow-down-circle";if(o){let D=document.createElement("sl-icon");D.slot="icon",D.name=o,s.appendChild(D)}let n=document.createElement("div");n.className="notify-progress-wrapper",n.style.display="flex",n.style.flexDirection="column",n.style.gap="0.35rem",n.style.minWidth="220px";let c=document.createElement("div");c.style.display="flex",c.style.justifyContent="space-between",c.style.alignItems="center",c.style.gap="0.5rem";let l=document.createElement("span");l.className="notify-progress-message",l.style.fontWeight="500",l.style.fontSize="0.9rem",l.textContent=e.message||"Processing...",c.appendChild(l);let d=document.createElement("span");d.className="notify-progress-status",d.style.fontSize="0.78rem",d.style.color="#64748b",d.style.fontWeight="600";let u=e.done!==void 0?e.done:0,h=e.total!==void 0?e.total:0;h>0?d.textContent=`${u} / ${h}`:e.value!==void 0&&(d.textContent=`${e.value}%`),c.appendChild(d),n.appendChild(c);let g=document.createElement("sl-progress-bar");h>0?g.value=Math.round(u/h*100):e.value!==void 0?g.value=e.value:g.indeterminate=!0,n.appendChild(g),s.appendChild(n);let m=customElements.get("sl-alert");if(m?.toastStack&&i){let D=m.toastStack;D.parentElement!==i&&i.appendChild(D)}return s.toast(),{alert:s,progressBar:g,update({done:D,total:x,value:w,message:A}={}){if(A!==void 0&&(l.textContent=A),x!==void 0&&D!==void 0){g.indeterminate=!1;let k=Math.min(100,Math.max(0,Math.round(D/Math.max(x,1)*100)));g.value=k,d.textContent=`${D} / ${x}`}else w!==void 0&&(g.indeterminate=!1,g.value=Math.min(100,Math.max(0,w)),d.textContent=`${Math.round(g.value)}%`)},close(){typeof s.hide=="function"&&s.hide()}}}var Ci=Object.assign(function(r,t){return jn(r,t)},{show:jn,success:tc,error:ec,warning:ic,info:rc,undo:sc,progress:oc,clear:Za,setContainer:qe,getContainer:Xe});var Ls=`
5
- :host {
6
- all: initial;
7
- display: block;
8
- position: relative;
9
- width: 100%;
10
- height: 100%;
11
- min-height: 200px;
12
- container-type: size;
13
- container-name: copio-scanner;
14
- overflow: hidden;
15
- contain: layout;
16
- box-sizing: border-box;
17
- text-align: left;
18
- direction: ltr;
19
- -webkit-font-smoothing: antialiased;
20
- -moz-osx-font-smoothing: grayscale;
21
- --copio-font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
22
- --copio-font-mono: 'JetBrains Mono', 'SFMono-Regular', Consolas, 'Liberation Mono', monospace;
23
- --copio-color-bg: #0b0f17;
24
- --copio-color-surface: #131b26;
25
- --copio-color-surface-elevated: #1c2736;
26
- --copio-color-surface-overlay: rgba(15, 22, 32, 0.88);
27
- --copio-color-stage-bg: #070a0f;
28
- --copio-color-text: #f1f5f9;
29
- --copio-color-text-muted: #94a3b8;
30
- --copio-color-text-inverse: #090d14;
31
- --copio-color-primary: #38bdf8;
32
- --copio-color-primary-hover: #7dd3fc;
33
- --copio-color-primary-contrast: #06131f;
34
- --copio-color-success: #22c55e;
35
- --copio-color-warning: #f59e0b;
36
- --copio-color-danger: #ef4444;
37
- --copio-color-border: rgba(148, 163, 184, 0.18);
38
- --copio-color-border-strong: rgba(148, 163, 184, 0.34);
39
- --copio-focus-ring: 0 0 0 2px #0b0f17, 0 0 0 4px #38bdf8;
40
- --copio-radius-sm: 6px;
41
- --copio-radius-md: 10px;
42
- --copio-radius-lg: 14px;
43
- --copio-radius-pill: 9999px;
44
- --copio-spacing-xs: 4px;
45
- --copio-spacing-sm: 8px;
46
- --copio-spacing-md: 12px;
47
- --copio-spacing-lg: 16px;
48
- --copio-spacing-xl: 24px;
49
- --copio-touch-target-min: 44px;
50
- --copio-crop-handle-hit: 48px;
51
- --copio-crop-handle-visual: 16px;
52
- --copio-shadow-elevated: 0 12px 32px -4px rgba(0, 0, 0, 0.55);
53
- --copio-transition-fast: 150ms cubic-bezier(0.22, 1, 0.36, 1);
54
- --copio-transition-normal: 240ms cubic-bezier(0.22, 1, 0.36, 1);
55
- --sl-font-sans: var(--copio-font-family);
56
- --sl-font-mono: var(--copio-font-mono);
57
- --sl-color-primary-50: #f0f9ff;
58
- --sl-color-primary-100: #e0f2fe;
59
- --sl-color-primary-200: #bae6fd;
60
- --sl-color-primary-300: #7dd3fc;
61
- --sl-color-primary-400: #38bdf8;
62
- --sl-color-primary-500: #0ea5e9;
63
- --sl-color-primary-600: var(--copio-color-primary);
64
- --sl-color-primary-700: #0369a1;
65
- --sl-color-primary-800: #075985;
66
- --sl-color-primary-900: #0c4a6e;
67
- --sl-color-primary-950: #082f49;
68
- font-family: var(--copio-font-family);
69
- font-size: 14px;
70
- line-height: 1.5;
71
- color: var(--copio-color-text);
72
- background-color: var(--copio-color-bg);
73
- color-scheme: dark;
74
- }
75
-
76
- :host([theme="dark"]),
77
- :host(.copio-theme-dark),
78
- :host-context([data-theme="dark"]),
79
- :host-context(.sl-theme-dark),
80
- :host-context(.theme-dark) {
81
- color-scheme: dark;
82
- }
83
-
84
- /* Light Theme Override */
85
- :host([theme="light"]),
86
- :host(.copio-theme-light),
87
- :host-context([data-theme="light"]),
88
- :host-context(.sl-theme-light),
89
- :host-context(.theme-light) {
90
- --copio-color-bg: #f8fafc;
91
- --copio-color-surface: #ffffff;
92
- --copio-color-surface-elevated: #f1f5f9;
93
- --copio-color-surface-overlay: rgba(255, 255, 255, 0.92);
94
- --copio-color-stage-bg: #1e293b;
95
- --copio-color-text: #0f172a;
96
- --copio-color-text-muted: #475569;
97
- --copio-color-text-inverse: #ffffff;
98
- --copio-color-primary: #0284c7;
99
- --copio-color-primary-hover: #0369a1;
100
- --copio-color-primary-contrast: #ffffff;
101
- --copio-color-success: #16a34a;
102
- --copio-color-warning: #d97706;
103
- --copio-color-danger: #dc2626;
104
- --copio-color-border: rgba(15, 23, 42, 0.12);
105
- --copio-color-border-strong: rgba(15, 23, 42, 0.26);
106
- --copio-focus-ring: 0 0 0 2px #ffffff, 0 0 0 4px #0284c7;
107
- --copio-radius-sm: 6px;
108
- --copio-radius-md: 10px;
109
- --copio-radius-lg: 14px;
110
- --copio-shadow-elevated: 0 12px 28px -4px rgba(15, 23, 42, 0.18);
111
- color-scheme: light;
112
- }
113
-
114
- /* Brand Theme Override (Emerald) */
115
- :host([theme="brand"]),
116
- :host(.copio-theme-brand),
117
- :host-context([data-theme="brand"]),
118
- :host-context(.theme-brand) {
119
- --copio-color-bg: #0f111a;
120
- --copio-color-surface: #181b28;
121
- --copio-color-surface-elevated: #23273a;
122
- --copio-color-surface-overlay: rgba(24, 27, 40, 0.90);
123
- --copio-color-stage-bg: #090a10;
124
- --copio-color-text: #f8fafc;
125
- --copio-color-text-muted: #9ca3af;
126
- --copio-color-text-inverse: #ffffff;
127
- --copio-color-primary: #10b981;
128
- --copio-color-primary-hover: #34d399;
129
- --copio-color-primary-contrast: #042f2e;
130
- --copio-color-success: #10b981;
131
- --copio-color-warning: #f59e0b;
132
- --copio-color-danger: #ef4444;
133
- --copio-color-border: rgba(16, 185, 129, 0.22);
134
- --copio-color-border-strong: rgba(16, 185, 129, 0.42);
135
- --copio-focus-ring: 0 0 0 2px #0f111a, 0 0 0 4px #10b981;
136
- --copio-radius-sm: 4px;
137
- --copio-radius-md: 8px;
138
- --copio-radius-lg: 12px;
139
- --copio-shadow-elevated: 0 12px 32px -4px rgba(0, 0, 0, 0.65);
140
- color-scheme: dark;
141
- }
142
-
143
- /* Auto Theme: follows prefers-color-scheme when theme is auto */
144
- @media (prefers-color-scheme: light) {
145
- :host([theme="auto"]),
146
- :host(.copio-theme-auto) {
147
- --copio-color-bg: #f8fafc;
148
- --copio-color-surface: #ffffff;
149
- --copio-color-surface-elevated: #f1f5f9;
150
- --copio-color-surface-overlay: rgba(255, 255, 255, 0.92);
151
- --copio-color-stage-bg: #1e293b;
152
- --copio-color-text: #0f172a;
153
- --copio-color-text-muted: #475569;
154
- --copio-color-text-inverse: #ffffff;
155
- --copio-color-primary: #0284c7;
156
- --copio-color-primary-hover: #0369a1;
157
- --copio-color-primary-contrast: #ffffff;
158
- --copio-color-success: #16a34a;
159
- --copio-color-warning: #d97706;
160
- --copio-color-danger: #dc2626;
161
- --copio-color-border: rgba(15, 23, 42, 0.12);
162
- --copio-color-border-strong: rgba(15, 23, 42, 0.26);
163
- --copio-focus-ring: 0 0 0 2px #ffffff, 0 0 0 4px #0284c7;
164
- --copio-radius-sm: 6px;
165
- --copio-radius-md: 10px;
166
- --copio-radius-lg: 14px;
167
- --copio-shadow-elevated: 0 12px 28px -4px rgba(15, 23, 42, 0.18);
168
- color-scheme: light;
169
- }
170
- }
171
-
172
- /* ==========================================================================
173
- 2. INTERNAL ELEMENT RESET (Scoped to Shadow DOM)
174
- ========================================================================== */
175
- *, *::before, *::after {
176
- box-sizing: border-box;
177
- }
178
-
179
- ::slotted(*) {
180
- box-sizing: border-box;
181
- }
182
-
183
- /* ==========================================================================
184
- 3. ROOT CONTAINER & COMPONENT SHELL
185
- ========================================================================== */
186
- .copio-scanner-container {
187
- width: 100%;
188
- height: 100%;
189
- position: relative;
190
- display: flex;
191
- flex-direction: column;
192
- overflow: hidden;
193
- box-sizing: border-box;
194
- container-type: size;
195
- container-name: copio-scanner;
196
- contain: layout;
197
- background: var(--copio-color-bg);
198
- color: var(--copio-color-text);
199
- font-family: var(--copio-font-family);
200
- font-size: 14px;
201
- line-height: 1.5;
202
- text-align: left;
203
- direction: ltr;
204
- user-select: none;
205
- }
206
-
207
- /* Header (Shadow Part: header) */
208
- .copio-header {
209
- display: flex;
210
- align-items: center;
211
- justify-content: space-between;
212
- gap: var(--copio-spacing-sm);
213
- padding: var(--copio-spacing-sm) var(--copio-spacing-md);
214
- background: var(--copio-color-surface);
215
- border-bottom: 1px solid var(--copio-color-border);
216
- min-height: 52px;
217
- flex-shrink: 0;
218
- z-index: 5;
219
- box-sizing: border-box;
220
- }
221
-
222
- .copio-header-left {
223
- display: flex;
224
- align-items: center;
225
- gap: var(--copio-spacing-sm);
226
- min-width: 0;
227
- }
228
-
229
- .copio-mode-badge {
230
- display: inline-flex;
231
- align-items: center;
232
- gap: 5px;
233
- font-size: 11px;
234
- font-weight: 600;
235
- padding: 4px 8px;
236
- border-radius: var(--copio-radius-pill);
237
- background: var(--copio-color-surface-elevated);
238
- color: var(--copio-color-primary);
239
- border: 1px solid var(--copio-color-border);
240
- white-space: nowrap;
241
- }
242
-
243
- .copio-title-group {
244
- display: flex;
245
- flex-direction: column;
246
- min-width: 0;
247
- }
248
-
249
- .copio-title {
250
- font-size: 13px;
251
- font-weight: 600;
252
- color: var(--copio-color-text);
253
- margin: 0;
254
- white-space: nowrap;
255
- overflow: hidden;
256
- text-overflow: ellipsis;
257
- }
258
-
259
- .copio-subtitle {
260
- font-size: 11px;
261
- color: var(--copio-color-text-muted);
262
- margin: 0;
263
- white-space: nowrap;
264
- overflow: hidden;
265
- text-overflow: ellipsis;
266
- }
267
-
268
- .copio-header-actions {
269
- display: flex;
270
- align-items: center;
271
- gap: 6px;
272
- flex-shrink: 0;
273
- }
274
-
275
- /* Interactive Stage Switcher Pill (Viewfinder vs Workbench) */
276
- .copio-stage-tabs {
277
- display: inline-flex;
278
- background: var(--copio-color-bg);
279
- padding: 2px;
280
- border-radius: var(--copio-radius-md);
281
- border: 1px solid var(--copio-color-border);
282
- }
283
-
284
- .copio-stage-tab {
285
- appearance: none;
286
- border: none;
287
- background: transparent;
288
- color: var(--copio-color-text-muted);
289
- font-family: inherit;
290
- font-size: 11px;
291
- font-weight: 600;
292
- padding: 6px 10px;
293
- min-height: var(--copio-touch-target-min);
294
- min-width: var(--copio-touch-target-min);
295
- border-radius: var(--copio-radius-sm);
296
- cursor: pointer;
297
- display: inline-flex;
298
- align-items: center;
299
- justify-content: center;
300
- transition: background var(--copio-transition-fast), color var(--copio-transition-fast);
301
- }
302
-
303
- .copio-stage-tab[aria-selected="true"] {
304
- background: var(--copio-color-surface-elevated);
305
- color: var(--copio-color-text);
306
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25);
307
- }
308
-
309
- /* Touch-Safe Interactive Buttons (>=44px touch invariant) */
310
- .copio-btn {
311
- appearance: none;
312
- border: 1px solid var(--copio-color-border);
313
- background: var(--copio-color-surface-elevated);
314
- color: var(--copio-color-text);
315
- font-family: inherit;
316
- font-size: 13px;
317
- font-weight: 600;
318
- min-height: var(--copio-touch-target-min);
319
- min-width: var(--copio-touch-target-min);
320
- padding: 0 12px;
321
- border-radius: var(--copio-radius-md);
322
- display: inline-flex;
323
- align-items: center;
324
- justify-content: center;
325
- gap: 7px;
326
- cursor: pointer;
327
- transition: all var(--copio-transition-fast);
328
- white-space: nowrap;
329
- text-decoration: none;
330
- box-sizing: border-box;
331
- }
332
-
333
- .copio-btn:hover {
334
- background: var(--copio-color-primary-hover);
335
- color: var(--copio-color-primary-contrast);
336
- border-color: var(--copio-color-primary);
337
- }
338
-
339
- .copio-btn-primary {
340
- background: var(--copio-color-primary);
341
- color: var(--copio-color-primary-contrast);
342
- border-color: var(--copio-color-primary);
343
- }
344
-
345
- .copio-btn-danger {
346
- background: rgba(239, 68, 68, 0.15);
347
- color: var(--copio-color-danger);
348
- border-color: rgba(239, 68, 68, 0.35);
349
- }
350
-
351
- .copio-btn-danger:hover {
352
- background: var(--copio-color-danger);
353
- color: #fff;
354
- }
355
-
356
- /* Viewfinder (Shadow Part: viewfinder) */
357
- .copio-viewfinder,
358
- .copio-viewfinder-stage {
359
- position: relative;
360
- flex: 1 1 auto;
361
- display: flex;
362
- flex-direction: column;
363
- justify-content: space-between;
364
- background: var(--copio-color-stage-bg);
365
- overflow: hidden;
366
- min-height: 0;
367
- width: 100%;
368
- }
369
-
370
- .copio-viewfinder-feed,
371
- .copio-camera-feed {
372
- position: absolute;
373
- inset: 0;
374
- display: flex;
375
- align-items: center;
376
- justify-content: center;
377
- padding: 56px 20px 104px 20px;
378
- background: radial-gradient(circle at 50% 45%, #1e293b 0%, #090d14 75%);
379
- }
380
-
381
- /* Framing Guide Overlay (receipt | card | a4 | auto) */
382
- .copio-framing-guide {
383
- position: relative;
384
- display: flex;
385
- align-items: center;
386
- justify-content: center;
387
- max-width: 100%;
388
- max-height: 100%;
389
- border: 1.5px dashed rgba(56, 189, 248, 0.55);
390
- border-radius: 12px;
391
- box-shadow: 0 0 0 9999px rgba(4, 7, 12, 0.52);
392
- transition: all var(--copio-transition-normal);
393
- overflow: hidden;
394
- }
395
-
396
- .copio-framing-guide[data-aspect="receipt"] {
397
- aspect-ratio: 1 / 2.1;
398
- height: 100%;
399
- }
400
-
401
- .copio-framing-guide[data-aspect="card"] {
402
- aspect-ratio: 1.586 / 1;
403
- width: 92%;
404
- max-height: 82%;
405
- }
406
-
407
- .copio-framing-guide[data-aspect="a4"] {
408
- aspect-ratio: 1 / 1.414;
409
- height: 96%;
410
- }
411
-
412
- .copio-framing-guide[data-aspect="auto"] {
413
- width: 94%;
414
- height: 94%;
415
- }
416
-
417
- /* Corner Targeting Brackets */
418
- .copio-corner {
419
- position: absolute;
420
- width: 22px;
421
- height: 22px;
422
- border-color: var(--copio-color-primary);
423
- border-style: solid;
424
- border-width: 0;
425
- pointer-events: none;
426
- z-index: 2;
427
- }
428
- .copio-corner.tl { top: 6px; left: 6px; border-top-width: 3px; border-left-width: 3px; border-top-left-radius: 6px; }
429
- .copio-corner.tr { top: 6px; right: 6px; border-top-width: 3px; border-right-width: 3px; border-top-right-radius: 6px; }
430
- .copio-corner.bl { bottom: 6px; left: 6px; border-bottom-width: 3px; border-left-width: 3px; border-bottom-left-radius: 6px; }
431
- .copio-corner.br { bottom: 6px; right: 6px; border-bottom-width: 3px; border-right-width: 3px; border-bottom-right-radius: 6px; }
432
-
433
- .copio-edge-quad {
434
- position: absolute;
435
- inset: 12px;
436
- border: 1px solid rgba(56, 189, 248, 0.28);
437
- border-radius: 8px;
438
- background: rgba(56, 189, 248, 0.04);
439
- pointer-events: none;
440
- z-index: 1;
441
- }
442
-
443
- .copio-camera-placeholder {
444
- position: relative;
445
- z-index: 2;
446
- display: flex;
447
- flex-direction: column;
448
- align-items: center;
449
- justify-content: center;
450
- gap: 8px;
451
- padding: 16px;
452
- text-align: center;
453
- color: var(--copio-color-text-muted);
454
- font-size: 12px;
455
- font-weight: 500;
456
- }
457
-
458
- .copio-status-dot {
459
- width: 7px;
460
- height: 7px;
461
- border-radius: 50%;
462
- background: var(--copio-color-primary);
463
- box-shadow: 0 0 8px var(--copio-color-primary);
464
- flex-shrink: 0;
465
- }
466
-
467
- /* Top Viewfinder HUD Overlay (Step Pill + Privacy Assurance Badge) */
468
- .copio-viewfinder-hud-top {
469
- position: relative;
470
- z-index: 3;
471
- display: flex;
472
- align-items: center;
473
- justify-content: space-between;
474
- gap: 8px;
475
- padding: 10px 14px;
476
- background: linear-gradient(to bottom, rgba(7, 10, 15, 0.85), transparent);
477
- }
478
-
479
- .copio-step-pill {
480
- display: inline-flex;
481
- align-items: center;
482
- gap: 6px;
483
- padding: 5px 12px;
484
- border-radius: var(--copio-radius-pill);
485
- background: rgba(15, 23, 42, 0.88);
486
- border: 1px solid rgba(56, 189, 248, 0.45);
487
- color: #f8fafc;
488
- font-size: 12px;
489
- font-weight: 600;
490
- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.35);
491
- }
492
-
493
- .copio-privacy-pill {
494
- display: inline-flex;
495
- align-items: center;
496
- gap: 5px;
497
- padding: 4px 9px;
498
- border-radius: var(--copio-radius-pill);
499
- background: rgba(22, 101, 52, 0.35);
500
- border: 1px solid rgba(34, 197, 94, 0.4);
501
- color: #86efac;
502
- font-size: 11px;
503
- font-weight: 500;
504
- }
505
-
506
- /* Shutter Dock (Shadow Part: shutter-dock) */
507
- .copio-shutter-dock {
508
- position: relative;
509
- z-index: 3;
510
- display: flex;
511
- align-items: center;
512
- justify-content: space-between;
513
- gap: 12px;
514
- padding: 12px 16px;
515
- background: var(--copio-color-surface);
516
- border-top: 1px solid var(--copio-color-border);
517
- min-height: 84px;
518
- flex-shrink: 0;
519
- }
520
-
521
- .copio-shutter-side {
522
- flex: 1;
523
- display: flex;
524
- align-items: center;
525
- }
526
-
527
- .copio-shutter-side.right {
528
- justify-content: flex-end;
529
- }
530
-
531
- .copio-shutter-btn {
532
- appearance: none;
533
- width: 64px;
534
- height: 64px;
535
- border-radius: var(--copio-radius-pill);
536
- border: 4px solid var(--copio-color-primary);
537
- background: transparent;
538
- padding: 4px;
539
- cursor: pointer;
540
- display: inline-flex;
541
- align-items: center;
542
- justify-content: center;
543
- transition: transform var(--copio-transition-fast), border-color 150ms ease;
544
- flex-shrink: 0;
545
- }
546
-
547
- .copio-shutter-btn:hover {
548
- transform: scale(1.04);
549
- }
550
-
551
- .copio-shutter-btn:active {
552
- transform: scale(0.94);
553
- }
554
-
555
- .copio-shutter-btn-inner,
556
- .copio-shutter-inner {
557
- width: 100%;
558
- height: 100%;
559
- border-radius: var(--copio-radius-pill);
560
- background: var(--copio-color-primary);
561
- display: flex;
562
- align-items: center;
563
- justify-content: center;
564
- color: var(--copio-color-primary-contrast);
565
- transition: transform var(--copio-transition-fast);
566
- }
567
-
568
- .copio-shutter-btn:active .copio-shutter-btn-inner,
569
- .copio-shutter-btn:active .copio-shutter-inner {
570
- transform: scale(0.88);
571
- }
572
-
573
- /* Stacking Thumbnail Counter Pill in Viewfinder */
574
- .copio-stack-pill {
575
- display: inline-flex;
576
- align-items: center;
577
- gap: 8px;
578
- min-height: var(--copio-touch-target-min);
579
- padding: 4px 12px 4px 6px;
580
- border-radius: var(--copio-radius-md);
581
- background: var(--copio-color-surface-elevated);
582
- border: 1px solid var(--copio-color-primary);
583
- color: var(--copio-color-text);
584
- font-size: 12px;
585
- font-weight: 600;
586
- cursor: pointer;
587
- }
588
-
589
- .copio-stack-thumb {
590
- width: 30px;
591
- height: 36px;
592
- border-radius: 4px;
593
- object-fit: cover;
594
- border: 1px solid rgba(255, 255, 255, 0.35);
595
- background: #000;
596
- }
597
-
598
- /* Workbench & Filmstrip (Shadow Part: workbench) */
599
- .copio-workbench,
600
- .copio-workbench-stage {
601
- position: relative;
602
- flex: 1 1 auto;
603
- display: flex;
604
- flex-direction: column;
605
- background: var(--copio-color-bg);
606
- overflow: hidden;
607
- min-height: 0;
608
- width: 100%;
609
- }
610
-
611
- .copio-workbench-main {
612
- flex: 1;
613
- display: flex;
614
- flex-direction: column;
615
- min-height: 0;
616
- width: 100%;
617
- overflow: hidden;
618
- }
619
-
620
- .copio-stage-canvas,
621
- .copio-canvas-viewport {
622
- position: relative;
623
- flex: 1 1 auto;
624
- display: flex;
625
- flex-direction: column;
626
- align-items: center;
627
- justify-content: center;
628
- overflow: hidden;
629
- padding: 16px 20px 44px 20px;
630
- background: var(--copio-color-stage-bg);
631
- min-height: 180px;
632
- }
633
-
634
- .copio-canvas-viewport.has-card-switcher {
635
- padding-top: 66px;
636
- }
637
-
638
- .copio-canvas-viewport.is-cropping {
639
- padding: 74px 26px 26px 26px;
640
- }
641
-
642
- /* Card Side Switcher */
643
- .copio-card-side-switcher {
644
- position: absolute;
645
- top: 8px;
646
- left: 50%;
647
- transform: translateX(-50%);
648
- z-index: 6;
649
- display: inline-flex;
650
- gap: 4px;
651
- padding: 3px;
652
- background: var(--copio-color-surface-overlay, rgba(15, 22, 32, 0.88));
653
- border: 1px solid var(--copio-color-border-strong);
654
- border-radius: var(--copio-radius-pill);
655
- backdrop-filter: blur(8px);
656
- }
657
-
658
- .copio-side-pill {
659
- appearance: none;
660
- border: none;
661
- background: transparent;
662
- color: var(--copio-color-text-muted);
663
- font-family: inherit;
664
- font-size: 11px;
665
- font-weight: 600;
666
- padding: 6px 12px;
667
- min-height: var(--copio-touch-target-min);
668
- min-width: var(--copio-touch-target-min);
669
- border-radius: var(--copio-radius-pill);
670
- cursor: pointer;
671
- display: inline-flex;
672
- align-items: center;
673
- justify-content: center;
674
- }
675
-
676
- .copio-side-pill[aria-selected="true"] {
677
- background: var(--copio-color-primary);
678
- color: var(--copio-color-primary-contrast);
679
- }
680
-
681
- .copio-stage-figure,
682
- .copio-canvas-wrapper {
683
- position: relative;
684
- display: flex;
685
- align-items: center;
686
- justify-content: center;
687
- max-width: 100%;
688
- max-height: 100%;
689
- }
690
-
691
- .copio-stage-canvas img,
692
- .copio-stage-img,
693
- .copio-stage-image {
694
- display: block;
695
- max-width: 100%;
696
- max-height: 100%;
697
- width: auto;
698
- height: auto;
699
- object-fit: contain;
700
- box-shadow: var(--copio-shadow-elevated);
701
- border-radius: var(--copio-radius-sm);
702
- user-select: none;
703
- }
704
-
705
- .copio-crop-layer {
706
- position: absolute;
707
- inset: 0;
708
- width: 100%;
709
- height: 100%;
710
- overflow: hidden;
711
- z-index: 8;
712
- touch-action: none;
713
- }
714
-
715
- .copio-crop-box {
716
- position: absolute;
717
- border: 2px solid var(--copio-color-primary);
718
- box-shadow: 0 0 0 9999px rgba(5, 8, 14, 0.68);
719
- cursor: move;
720
- touch-action: none;
721
- box-sizing: border-box;
722
- }
723
-
724
- /* Rule-of-thirds crop grid */
725
- .copio-crop-grid {
726
- position: absolute;
727
- inset: 0;
728
- pointer-events: none;
729
- background-image:
730
- linear-gradient(to right, rgba(56, 189, 248, 0.28) 1px, transparent 1px),
731
- linear-gradient(to bottom, rgba(56, 189, 248, 0.28) 1px, transparent 1px);
732
- background-size: 33.333% 33.333%;
733
- }
734
-
735
- /* 48px x 48px Touch Target Handles (exceeds 44px requirement) */
736
- .copio-crop-handle {
737
- position: absolute;
738
- width: var(--copio-crop-handle-hit);
739
- height: var(--copio-crop-handle-hit);
740
- min-width: 44px;
741
- min-height: 44px;
742
- display: flex;
743
- align-items: center;
744
- justify-content: center;
745
- z-index: 10;
746
- touch-action: none;
747
- box-sizing: border-box;
748
- }
749
-
750
- .copio-crop-handle::after {
751
- content: '';
752
- width: var(--copio-crop-handle-visual);
753
- height: var(--copio-crop-handle-visual);
754
- border-radius: 50%;
755
- background: var(--copio-color-primary);
756
- border: 2.5px solid #ffffff;
757
- box-shadow: 0 2px 6px rgba(0, 0, 0, 0.5);
758
- transition: transform 120ms ease;
759
- box-sizing: border-box;
760
- }
761
-
762
- .copio-crop-handle:hover::after,
763
- .copio-crop-handle:active::after {
764
- transform: scale(1.25);
765
- background: var(--copio-color-success, #22c55e);
766
- }
767
-
768
- .copio-crop-handle.nw { top: -24px; left: -24px; cursor: nwse-resize; }
769
- .copio-crop-handle.ne { top: -24px; right: -24px; cursor: nesw-resize; }
770
- .copio-crop-handle.sw { bottom: -24px; left: -24px; cursor: nesw-resize; }
771
- .copio-crop-handle.se { bottom: -24px; right: -24px; cursor: nwse-resize; }
772
- .copio-crop-handle.n, .copio-crop-handle.edge-n { top: -24px; left: calc(50% - 24px); cursor: ns-resize; }
773
- .copio-crop-handle.s, .copio-crop-handle.edge-s { bottom: -24px; left: calc(50% - 24px); cursor: ns-resize; }
774
- .copio-crop-handle.w, .copio-crop-handle.edge-w { left: -24px; top: calc(50% - 24px); cursor: ew-resize; }
775
- .copio-crop-handle.e, .copio-crop-handle.edge-e { right: -24px; top: calc(50% - 24px); cursor: ew-resize; }
776
-
777
- /* Filmstrip & Reorder Tray */
778
- .copio-filmstrip,
779
- .copio-filmstrip-bar {
780
- display: flex;
781
- align-items: center;
782
- gap: 8px;
783
- padding: 8px 12px;
784
- background: var(--copio-color-surface);
785
- border-top: 1px solid var(--copio-color-border);
786
- overflow-x: auto;
787
- min-height: 80px;
788
- flex-shrink: 0;
789
- scrollbar-width: thin;
790
- }
791
-
792
- .copio-filmstrip-scroll {
793
- display: flex;
794
- align-items: center;
795
- gap: 8px;
796
- }
797
-
798
- .copio-filmstrip-item {
799
- display: flex;
800
- flex-direction: column;
801
- align-items: center;
802
- gap: 4px;
803
- flex-shrink: 0;
804
- }
805
-
806
- .copio-thumb-container {
807
- position: relative;
808
- width: 56px;
809
- height: 70px;
810
- border-radius: var(--copio-radius-sm);
811
- overflow: hidden;
812
- background: var(--copio-color-surface-elevated, #1c2736);
813
- border: 2px solid var(--copio-color-border);
814
- cursor: pointer;
815
- transition: all var(--copio-transition-fast);
816
- display: flex;
817
- align-items: center;
818
- justify-content: center;
819
- }
820
-
821
- .copio-filmstrip-item.is-active .copio-thumb-container {
822
- border-color: var(--copio-color-primary);
823
- box-shadow: 0 0 0 2px rgba(56, 189, 248, 0.25);
824
- }
825
-
826
- .copio-thumb-num {
827
- position: absolute;
828
- bottom: 3px;
829
- right: 3px;
830
- min-width: 16px;
831
- height: 16px;
832
- padding: 0 4px;
833
- border-radius: 999px;
834
- background: rgba(15, 23, 42, 0.85);
835
- color: #f8fafc;
836
- font-size: 10px;
837
- font-weight: 700;
838
- display: inline-flex;
839
- align-items: center;
840
- justify-content: center;
841
- }
842
-
843
- .copio-thumb-reorder {
844
- display: flex;
845
- align-items: center;
846
- gap: 4px;
847
- }
848
-
849
- .copio-reorder-btn {
850
- appearance: none;
851
- border: 1px solid var(--copio-color-border);
852
- background: var(--copio-color-surface-elevated);
853
- color: var(--copio-color-text-muted);
854
- border-radius: 4px;
855
- font-size: 9px;
856
- padding: 2px 5px;
857
- cursor: pointer;
858
- }
859
-
860
- .copio-reorder-btn:disabled {
861
- opacity: 0.35;
862
- cursor: not-allowed;
863
- }
864
-
865
- .copio-thumb-img {
866
- max-width: 100%;
867
- max-height: 100%;
868
- width: auto;
869
- height: auto;
870
- object-fit: contain;
871
- }
872
-
873
- /* Edit Action Toolbar & Primary Completion Dock */
874
- .copio-toolbar,
875
- .copio-controls-dock {
876
- display: flex;
877
- flex-direction: column;
878
- gap: 8px;
879
- padding: 10px 12px;
880
- background: var(--copio-color-surface);
881
- border-top: 1px solid var(--copio-color-border);
882
- min-height: 56px;
883
- flex-shrink: 0;
884
- z-index: 6;
885
- }
886
-
887
- .copio-edit-toolbar,
888
- .copio-toolbar-tools {
889
- display: flex;
890
- flex-wrap: wrap;
891
- align-items: center;
892
- gap: 6px;
893
- width: 100%;
894
- }
895
-
896
- .copio-toolbar-tools .copio-tool-btn {
897
- flex: 1 1 56px;
898
- }
899
-
900
- .copio-toolbar-actions {
901
- display: flex;
902
- align-items: center;
903
- gap: 8px;
904
- width: 100%;
905
- }
906
-
907
- .copio-toolbar-actions .copio-btn-primary {
908
- width: 100%;
909
- }
910
-
911
- .copio-tool-btn {
912
- appearance: none;
913
- border: 1px solid var(--copio-color-border);
914
- background: var(--copio-color-surface-elevated);
915
- color: var(--copio-color-text);
916
- font-family: inherit;
917
- font-size: 11px;
918
- font-weight: 600;
919
- min-height: var(--copio-touch-target-min);
920
- min-width: var(--copio-touch-target-min);
921
- padding: 4px 6px;
922
- border-radius: var(--copio-radius-md);
923
- display: flex;
924
- flex-direction: column;
925
- align-items: center;
926
- justify-content: center;
927
- gap: 3px;
928
- cursor: pointer;
929
- transition: all var(--copio-transition-fast);
930
- }
931
-
932
- .copio-tool-btn:hover:not(:disabled) {
933
- border-color: var(--copio-color-border-strong);
934
- background: rgba(255, 255, 255, 0.06);
935
- }
936
-
937
- .copio-tool-btn[aria-pressed="true"] {
938
- background: rgba(56, 189, 248, 0.16);
939
- color: var(--copio-color-primary);
940
- border-color: var(--copio-color-primary);
941
- }
942
-
943
- .copio-tool-btn.danger {
944
- color: #fca5a5;
945
- }
946
-
947
- .copio-tool-btn.danger:hover:not(:disabled) {
948
- background: rgba(239, 68, 68, 0.16);
949
- border-color: rgba(239, 68, 68, 0.45);
950
- }
951
-
952
- .copio-toast-region {
953
- position: absolute;
954
- bottom: 124px;
955
- left: 12px;
956
- right: 12px;
957
- z-index: 30;
958
- display: flex;
959
- flex-direction: column;
960
- gap: 8px;
961
- pointer-events: none;
962
- }
963
-
964
- .copio-toast {
965
- pointer-events: auto;
966
- display: flex;
967
- align-items: center;
968
- justify-content: space-between;
969
- gap: 10px;
970
- padding: 8px 12px;
971
- border-radius: var(--copio-radius-md);
972
- background: #0f172a;
973
- color: #f8fafc;
974
- border: 1px solid var(--copio-color-primary);
975
- box-shadow: var(--copio-shadow-elevated);
976
- font-size: 12px;
977
- font-weight: 500;
978
- position: relative;
979
- overflow: hidden;
980
- }
981
-
982
- .copio-toast-progress {
983
- position: absolute;
984
- bottom: 0;
985
- left: 0;
986
- height: 3px;
987
- background: var(--copio-color-primary);
988
- transition: width 100ms linear;
989
- }
990
-
991
- .copio-toast-undo-btn,
992
- .copio-btn-toast-undo {
993
- appearance: none;
994
- border: 1px solid rgba(56, 189, 248, 0.45);
995
- background: rgba(56, 189, 248, 0.16);
996
- color: #38bdf8;
997
- font-family: inherit;
998
- font-size: 12px;
999
- font-weight: 700;
1000
- min-height: var(--copio-touch-target-min);
1001
- min-width: var(--copio-touch-target-min);
1002
- padding: 0 12px;
1003
- border-radius: var(--copio-radius-sm);
1004
- cursor: pointer;
1005
- flex-shrink: 0;
1006
- }
1007
-
1008
- .copio-ocr-content {
1009
- display: flex;
1010
- flex-direction: column;
1011
- gap: 8px;
1012
- }
1013
-
1014
- .copio-ocr-text {
1015
- margin: 0;
1016
- padding: 10px;
1017
- max-height: 180px;
1018
- overflow: auto;
1019
- background: var(--copio-color-bg);
1020
- color: var(--copio-color-text);
1021
- border: 1px solid var(--copio-color-border);
1022
- border-radius: var(--copio-radius-sm);
1023
- font-family: var(--copio-font-mono);
1024
- font-size: 11px;
1025
- line-height: 1.5;
1026
- white-space: pre-wrap;
1027
- }
1028
-
1029
- .copio-ocr-meta {
1030
- font-size: 11px;
1031
- color: var(--copio-color-text-muted);
1032
- }
1033
-
1034
- /* Slide-up OCR Extraction Sheet */
1035
- .copio-ocr-sheet {
1036
- position: absolute;
1037
- inset: auto 0 0 0;
1038
- max-height: 78%;
1039
- background: var(--copio-color-surface);
1040
- border-top: 1px solid var(--copio-color-primary);
1041
- border-radius: 16px 16px 0 0;
1042
- box-shadow: 0 -16px 40px rgba(0, 0, 0, 0.65);
1043
- z-index: 25;
1044
- display: flex;
1045
- flex-direction: column;
1046
- padding: 14px;
1047
- gap: 10px;
1048
- }
1049
-
1050
- .copio-ocr-header {
1051
- display: flex;
1052
- align-items: center;
1053
- justify-content: space-between;
1054
- gap: 8px;
1055
- }
1056
-
1057
- .copio-ocr-textarea {
1058
- width: 100%;
1059
- min-height: 130px;
1060
- flex: 1;
1061
- resize: none;
1062
- background: var(--copio-color-bg);
1063
- color: var(--copio-color-text);
1064
- border: 1px solid var(--copio-color-border);
1065
- border-radius: var(--copio-radius-sm);
1066
- padding: 10px;
1067
- font-family: var(--copio-font-mono);
1068
- font-size: 11px;
1069
- line-height: 1.5;
1070
- }
1071
-
1072
- /* Container-Scoped Toast Stack */
1073
- .sl-toast-stack,
1074
- .copio-toast-stack-scoped {
1075
- position: absolute !important;
1076
- top: auto !important;
1077
- bottom: 0 !important;
1078
- left: 0 !important;
1079
- right: 0 !important;
1080
- width: 100% !important;
1081
- max-width: 100% !important;
1082
- padding: var(--copio-spacing-md) !important;
1083
- box-sizing: border-box !important;
1084
- z-index: 1000 !important;
1085
- pointer-events: none;
1086
- }
1087
-
1088
- .sl-toast-stack sl-alert,
1089
- .copio-toast-stack-scoped sl-alert {
1090
- pointer-events: auto;
1091
- margin-top: var(--copio-spacing-sm);
1092
- }
1093
-
1094
- /* ==========================================================================
1095
- 4. @container BREAKPOINTS (Strictly Container Queries)
1096
- ========================================================================== */
1097
-
1098
- @container copio-scanner (max-width: 400px) {
1099
- .copio-header {
1100
- padding: 6px 10px;
1101
- min-height: 52px;
1102
- }
1103
- .copio-header-left {
1104
- flex-direction: column;
1105
- align-items: flex-start;
1106
- gap: 2px;
1107
- }
1108
- .copio-mode-badge {
1109
- font-size: 10px;
1110
- padding: 2px 6px;
1111
- }
1112
- .copio-subtitle {
1113
- display: none;
1114
- }
1115
- .copio-filmstrip,
1116
- .copio-filmstrip-bar {
1117
- gap: 6px;
1118
- padding: 6px 8px;
1119
- }
1120
- .copio-tool-btn {
1121
- font-size: 10px;
1122
- padding: 3px 4px;
1123
- }
1124
- .copio-btn {
1125
- padding: 0 8px;
1126
- font-size: 12px;
1127
- }
1128
- }
1129
-
1130
- @container copio-scanner (min-width: 401px) and (max-width: 767px) {
1131
- .copio-header {
1132
- padding: var(--copio-spacing-sm) var(--copio-spacing-md);
1133
- }
1134
- .copio-tool-btn {
1135
- flex-direction: row;
1136
- font-size: 12px;
1137
- gap: 6px;
1138
- }
1139
- }
1140
-
1141
- @container copio-scanner (min-width: 768px) {
1142
- .copio-header {
1143
- padding: var(--copio-spacing-md) var(--copio-spacing-lg);
1144
- }
1145
- .copio-workbench-main {
1146
- flex-direction: row;
1147
- }
1148
- .copio-filmstrip,
1149
- .copio-filmstrip-bar {
1150
- order: -1;
1151
- flex-direction: column;
1152
- width: 168px;
1153
- height: 100%;
1154
- border-top: none;
1155
- border-right: 1px solid var(--copio-color-border);
1156
- overflow-y: auto;
1157
- overflow-x: hidden;
1158
- padding: 12px;
1159
- }
1160
- .copio-filmstrip-scroll {
1161
- flex-direction: column;
1162
- width: 100%;
1163
- }
1164
- .copio-thumb-container {
1165
- width: 112px;
1166
- height: 140px;
1167
- }
1168
- .copio-toolbar,
1169
- .copio-controls-dock {
1170
- flex-direction: row;
1171
- align-items: center;
1172
- justify-content: space-between;
1173
- }
1174
- .copio-toolbar-tools {
1175
- width: auto;
1176
- flex: 1;
1177
- }
1178
- .copio-toolbar-actions {
1179
- width: auto;
1180
- min-width: 200px;
1181
- }
1182
- }
1183
- `,Di=null;function Nn(){if(Di)return Di;if(typeof CSSStyleSheet<"u"&&typeof Document<"u"&&"adoptedStyleSheets"in Document.prototype&&"replaceSync"in CSSStyleSheet.prototype)try{return Di=new CSSStyleSheet,Di.replaceSync(Ls),Di}catch{return null}return null}function $n(r){if(!r)return;let t=Nn();if(t&&"adoptedStyleSheets"in r){let e=r.adoptedStyleSheets||[];e.includes(t)||(r.adoptedStyleSheets=[...e,t])}else if(!r.querySelector("style[data-copio-encapsulated-styles]")){let e=document.createElement("style");e.setAttribute("data-copio-encapsulated-styles",""),e.textContent=Ls,r.appendChild(e)}}var nc=typeof HTMLElement<"u"?HTMLElement:class{},Rs=class extends nc{#t=null;#r=null;#s=null;#l=!1;#a="viewfinder";#e=0;#c=0;#o=!1;#i=!1;#n=null;#d=null;#h=0;#p=null;#u=null;#g=null;onShutter=null;get#f(){return this.docId?this.docId:(this.#u||(this.#u=`doc_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`),this.#u)}static get observedAttributes(){return["mode","aspect","stage","doc-id","features","export-formats","ocr-languages","max-pages","asset-base","license-key","theme","ocr","pdf"]}constructor(){super(),typeof this.attachShadow=="function"&&this.attachShadow({mode:"open"}),this.#w()}#w(){let t={storage:this.#r};typeof this.getAttribute=="function"&&(this.hasAttribute("features")&&(t.features=this.getAttribute("features")),this.hasAttribute("export-formats")&&(t.exportFormats=this.getAttribute("export-formats")),this.hasAttribute("ocr-languages")&&(t.ocrLanguages=this.getAttribute("ocr-languages")),this.hasAttribute("max-pages")&&(t.maxPages=this.getAttribute("max-pages")),this.hasAttribute("asset-base")&&(t.assetBase=this.getAttribute("asset-base")),this.hasAttribute("license-key")&&(t.licenseKey=this.getAttribute("license-key")),this.hasAttribute("ocr")&&(t.ocr=this.getAttribute("ocr")!=="false"),this.hasAttribute("pdf")&&(t.pdf=this.getAttribute("pdf")!=="false")),this.#t=new Ei(t)}connectedCallback(){this.shadowRoot&&($n(this.shadowRoot),this.#y()),typeof qe=="function"&&typeof document<"u"&&Xe()===document.body&&qe(this.shadowRoot?.querySelector(".copio-scanner-container")||this),this.#t&&(this.#s=this.#t.subscribe(async()=>{let t=await this.getPages();this.dispatch(St.PAGES_CHANGED,{pages:t,docId:this.docId}),this.#m()})),this.hasAttribute&&this.hasAttribute("asset-base")&&Si(this.getAttribute("asset-base")),this.#b(),this.#m()}disconnectedCallback(){if(this.#x(),typeof this.#s=="function"&&(this.#s(),this.#s=null),this.#d&&(clearInterval(this.#d),this.#d=null),typeof qe=="function"&&typeof document<"u"){let t=this.shadowRoot?.querySelector(".copio-scanner-container")||this;Xe()===t&&qe(null)}}attributeChangedCallback(t,e,i){if(!(e===i||!this.#t))switch(t){case"features":this.#t.setFeatures(i),this.#b();break;case"export-formats":this.#t.exportFormats=i,this.#b();break;case"ocr-languages":this.#t.ocrLanguages=i;break;case"asset-base":this.#t.assetBase=i;break;case"license-key":this.#t.licenseKey=i;break;case"ocr":this.#t.ocr=i!=="false",this.#b();break;case"pdf":this.#t.pdf=i!=="false",this.#b();break;case"stage":if(i==="viewfinder"||i==="workbench"){this.#a=i;let s=this.shadowRoot;if(s){let o=s.getElementById("viewfinder-section"),n=s.getElementById("workbench-section");o&&n&&(o.style.display=i==="viewfinder"?"flex":"none",n.style.display=i==="workbench"?"flex":"none")}this.#m()}break;case"max-pages":this.#t.maxPages=i,this.#m();break;case"mode":case"aspect":case"theme":this.#m();break}}#b(){if(typeof this.querySelectorAll!="function")return;let t=[];this.shadowRoot&&t.push(this.shadowRoot),t.push(this);for(let e of t){let i=e.querySelectorAll("copio-carousel, copio-row, copio-images");for(let s of i)"ocr"in s&&(s.ocr=this.ocrEnabled),"pdf"in s&&(s.pdf=this.pdf)}}#y(){if(!this.shadowRoot||this.shadowRoot.innerHTML)return;let t="Align Document Inside Frame";this.aspect==="card"?t="Step 1 of 2: Capture Front of ID Card":this.mode==="batch"&&(t="Batch Capture \xB7 Page 1"),this.shadowRoot.innerHTML=`
1184
- <div class="copio-scanner-container copio-scanner-host" part="scanner-root">
1185
- <header class="copio-header" part="header">
1186
- <div class="copio-header-left">
1187
- <span class="copio-mode-badge" id="mode-badge">${(this.mode||"single").toUpperCase()}</span>
1188
- <div class="copio-title-group">
1189
- <h2 class="copio-title" id="header-title">Copio Scanner</h2>
1190
- <p class="copio-subtitle" id="header-subtitle">Non-destructive mobile document scanner</p>
1191
- </div>
1192
- </div>
1193
- <div class="copio-header-actions" part="header-actions">
1194
- <div class="copio-stage-tabs" role="tablist" aria-label="Scanner Stage">
1195
- <button type="button" class="copio-stage-tab" id="tab-viewfinder" role="tab" aria-selected="true">Camera</button>
1196
- <button type="button" class="copio-stage-tab" id="tab-workbench" role="tab" aria-selected="false">Workbench</button>
1197
- </div>
1198
- <slot name="header-actions"></slot>
1199
- </div>
1200
- </header>
1201
-
1202
- <!-- Viewfinder Stage -->
1203
- <div class="copio-viewfinder copio-viewfinder-stage" part="viewfinder" id="viewfinder-section">
1204
- <div class="copio-viewfinder-hud-top">
1205
- <div class="copio-step-pill" id="step-pill">
1206
- <span class="copio-status-dot"></span>
1207
- <span id="step-pill-text">${t}</span>
1208
- </div>
1209
- <div class="copio-privacy-pill" title="100% Local On-Device Processing">
1210
- <span>\u{1F512} 100% Local</span>
1211
- </div>
1212
- </div>
1213
-
1214
- <div class="copio-camera-feed" id="camera-feed">
1215
- <video id="camera-video" autoplay playsinline muted style="display:none; position:absolute; inset:0; width:100%; height:100%; object-fit:cover; z-index:0;"></video>
1216
- <slot name="viewfinder">
1217
- <div class="copio-framing-guide" id="framing-guide" data-aspect="${this.aspect}">
1218
- <span class="copio-corner tl"></span>
1219
- <span class="copio-corner tr"></span>
1220
- <span class="copio-corner bl"></span>
1221
- <span class="copio-corner br"></span>
1222
- <div class="copio-edge-quad"></div>
1223
- <div class="copio-camera-placeholder">
1224
- <svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
1225
- <path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/>
1226
- <circle cx="12" cy="13" r="4"/>
1227
- </svg>
1228
- <span>Position document within guide lines</span>
1229
- </div>
1230
- </div>
1231
- </slot>
1232
- </div>
1233
-
1234
- <div class="copio-shutter-dock" part="shutter-dock">
1235
- <div class="copio-shutter-side left">
1236
- <button type="button" class="copio-btn copio-btn-secondary" id="btn-import-file" title="Import image from file">
1237
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1238
- <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
1239
- <polyline points="17 8 12 3 7 8"/>
1240
- <line x1="12" y1="3" x2="12" y2="15"/>
1241
- </svg>
1242
- <span>Import</span>
1243
- </button>
1244
- </div>
1245
-
1246
- <slot name="shutter-dock">
1247
- <button type="button" class="copio-shutter-btn" id="btn-shutter" aria-label="Capture page">
1248
- <span class="copio-shutter-btn-inner"></span>
1249
- </button>
1250
- </slot>
1251
-
1252
- <div class="copio-shutter-side right">
1253
- <button type="button" class="copio-stack-pill" id="btn-review" title="Review pages" style="display:none;">
1254
- <span id="review-pill-text">Review (0) \u2192</span>
1255
- </button>
1256
- </div>
1257
- </div>
1258
- </div>
1259
-
1260
- <!-- Workbench Stage -->
1261
- <div class="copio-workbench copio-workbench-stage" part="workbench" id="workbench-section" style="display: none;">
1262
- <div class="copio-workbench-main">
1263
- <div class="copio-canvas-viewport" id="canvas-viewport">
1264
- <div class="copio-card-side-switcher" id="card-side-switcher" style="display:none;" role="tablist" aria-label="Card side switcher">
1265
- <button type="button" role="tab" class="copio-side-pill active" id="btn-card-front" aria-selected="true">1. Front Side</button>
1266
- <button type="button" role="tab" class="copio-side-pill" id="btn-card-back" aria-selected="false">2. Back Side</button>
1267
- </div>
1268
-
1269
- <div class="copio-canvas-wrapper" id="canvas-wrapper">
1270
- <img id="stage-img" class="copio-stage-image" alt="Active document page" />
1271
- </div>
1272
- </div>
1273
-
1274
- <!-- Filmstrip Tray -->
1275
- <div class="copio-filmstrip" id="filmstrip-tray" part="filmstrip">
1276
- <div class="copio-filmstrip-scroll" id="filmstrip-scroll">
1277
- <slot name="filmstrip"></slot>
1278
- </div>
1279
- </div>
1280
- </div>
1281
-
1282
- <!-- Bottom Action Toolbar -->
1283
- <footer class="copio-toolbar" part="toolbar" id="workbench-toolbar">
1284
- <div class="copio-toolbar-tools">
1285
- <button type="button" class="copio-tool-btn" id="btn-retake" title="Retake page">
1286
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1287
- <path d="M23 4v6h-6M1 20v-6h6"/>
1288
- <path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/>
1289
- </svg>
1290
- <span>Retake</span>
1291
- </button>
1292
-
1293
- <button type="button" class="copio-tool-btn" id="btn-crop" title="Adjust crop">
1294
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1295
- <path d="M6 2v14a2 2 0 0 0 2 2h14"/>
1296
- <path d="M18 22V8a2 2 0 0 0-2-2H2"/>
1297
- </svg>
1298
- <span id="crop-btn-label">Crop</span>
1299
- </button>
1300
-
1301
- <button type="button" class="copio-tool-btn" id="btn-rotate" title="Rotate 90\xB0">
1302
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1303
- <path d="M21.5 2v6h-6M21.34 15.57a10 10 0 1 1-.57-8.38l5.67-5.67"/>
1304
- </svg>
1305
- <span>Rotate</span>
1306
- </button>
1307
-
1308
- <button type="button" class="copio-tool-btn" id="btn-filter-bw" title="Toggle B&W filter">
1309
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1310
- <circle cx="12" cy="12" r="10"/>
1311
- <path d="M12 2a10 10 0 0 1 0 20z" fill="currentColor"/>
1312
- </svg>
1313
- <span>B&W</span>
1314
- </button>
1315
-
1316
- <button type="button" class="copio-tool-btn" id="btn-ocr" title="Recognize text">
1317
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1318
- <path d="M4 7V4h16v3M9 20h6M12 4v16"/>
1319
- </svg>
1320
- <span>OCR</span>
1321
- </button>
1322
-
1323
- <button type="button" class="copio-tool-btn copio-btn-danger" id="btn-delete" title="Delete active page">
1324
- <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1325
- <polyline points="3 6 5 6 21 6"/>
1326
- <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
1327
- </svg>
1328
- <span>Delete</span>
1329
- </button>
1330
- </div>
1331
-
1332
- <div class="copio-toolbar-actions">
1333
- <slot name="toolbar">
1334
- <button type="button" class="copio-btn copio-btn-primary" id="btn-primary-complete">
1335
- \u2713 Use Photo
1336
- </button>
1337
- </slot>
1338
- </div>
1339
- </footer>
1340
-
1341
- <!-- Scoped OCR Slide-out / Bottom Sheet -->
1342
- <div class="copio-ocr-sheet" id="ocr-sheet" style="display:none;" part="ocr-sheet">
1343
- <div class="copio-ocr-header">
1344
- <strong class="copio-ocr-title">Text Recognition (OCR)</strong>
1345
- <button type="button" class="copio-btn copio-btn-secondary" id="btn-close-ocr">\u2715</button>
1346
- </div>
1347
- <div class="copio-ocr-body" id="ocr-body">
1348
- <p class="copio-ocr-placeholder">Select text or extract full page data...</p>
1349
- </div>
1350
- </div>
1351
-
1352
- <!-- Container-scoped Toast Region (5s undo) -->
1353
- <div class="copio-toast-region" id="toast-region" aria-live="polite"></div>
1354
- </div>
1355
-
1356
- <!-- Hidden input for file picker fallback -->
1357
- <input type="file" id="internal-file-input" accept="image/*" style="display: none;" />
1358
- <slot></slot>
1359
- </div>
1360
- `,this.#A()}#A(){let t=this.shadowRoot;if(!t)return;t.getElementById("tab-viewfinder")?.addEventListener("click",()=>{this.stage="viewfinder"}),t.getElementById("tab-workbench")?.addEventListener("click",()=>{this.stage="workbench"});let e=t.getElementById("internal-file-input");t.getElementById("btn-import-file")?.addEventListener("click",()=>{e?.click()}),e?.addEventListener("change",async i=>{let s=i.target;s.files&&s.files.length>0&&(await this.addFiles(s.files),s.value="")}),t.getElementById("btn-shutter")?.addEventListener("click",async()=>{await this.#R()}),t.getElementById("btn-review")?.addEventListener("click",()=>{this.stage="workbench"}),t.getElementById("btn-retake")?.addEventListener("click",()=>{this.#o=!0,this.#i=!1,this.stage="viewfinder"}),t.getElementById("btn-rotate")?.addEventListener("click",async()=>{await this.#P()}),t.getElementById("btn-filter-bw")?.addEventListener("click",async()=>{await this.#E()}),t.getElementById("btn-crop")?.addEventListener("click",async()=>{await this.#C()}),t.getElementById("btn-delete")?.addEventListener("click",async()=>{await this.#D()}),t.getElementById("btn-ocr")?.addEventListener("click",async()=>{await this.#T()}),t.getElementById("btn-close-ocr")?.addEventListener("click",()=>{this.#M()}),t.getElementById("btn-primary-complete")?.addEventListener("click",async()=>{await this.#O()}),t.getElementById("btn-card-front")?.addEventListener("click",()=>{this.#i=!1,this.#e=0,this.#m()}),t.getElementById("btn-card-back")?.addEventListener("click",()=>{this.#i=!1,this.#e=1,this.#m()}),this.#v()}#v(){let t=this.shadowRoot;if(!t)return;let e=t.getElementById("crop-box"),i=t.querySelectorAll(".copio-crop-handle");if(!e||i.length===0)return;let s=null,o=!1,n=0,c=0,l=null,d=g=>{let m=g.target.closest(".copio-crop-handle");if(m)s=m.getAttribute("data-handle"),o=!1;else if(g.target===e||g.target.classList.contains("copio-crop-grid"))s=null,o=!0;else return;g.preventDefault(),g.stopPropagation(),n=g.clientX,c=g.clientY,l=this.#n?{...this.#n}:{x:.05,y:.05,w:.9,h:.9},window.addEventListener("pointermove",u),window.addEventListener("pointerup",h)},u=g=>{if(!s&&!o||!l)return;let E=(t.getElementById("canvas-wrapper")||t.getElementById("canvas-viewport"))?.getBoundingClientRect()||{width:300,height:400},D=(g.clientX-n)/Math.max(E.width,1),x=(g.clientY-c)/Math.max(E.height,1),{x:w,y:A,w:k,h:R}=l;if(o)w=Math.min(Math.max(0,w+D),1-k),A=Math.min(Math.max(0,A+x),1-R);else if(s){if(s.includes("w")){let U=Math.min(Math.max(0,w+D),w+k-.1);k+=w-U,w=U}if(s.includes("e")&&(k=Math.min(Math.max(.1,k+D),1-w)),s.includes("n")){let U=Math.min(Math.max(0,A+x),A+R-.1);R+=A-U,A=U}s.includes("s")&&(R=Math.min(Math.max(.1,R+x),1-A))}this.#n={x:w,y:A,w:k,h:R},this.#S()},h=()=>{s=null,o=!1,l=null,window.removeEventListener("pointermove",u),window.removeEventListener("pointerup",h)};e.addEventListener("pointerdown",d),i.forEach(g=>{g.addEventListener("pointerdown",d)})}#S(){let t=this.shadowRoot;if(!t||!this.#n)return;let e=t.getElementById("crop-box");e&&(e.style.left=`${(this.#n.x*100).toFixed(1)}%`,e.style.top=`${(this.#n.y*100).toFixed(1)}%`,e.style.width=`${(this.#n.w*100).toFixed(1)}%`,e.style.height=`${(this.#n.h*100).toFixed(1)}%`)}async#m(){if(this.shadowRoot)return this.#p?this.#p:(this.#p=(async()=>{try{await Promise.resolve(),await this.#I()}finally{this.#p=null}})(),this.#p)}async#I(){if(this.shadowRoot)try{let t=await this.getPages();this.#c=t.length;let e=this.shadowRoot,i=e.getElementById("mode-badge");i&&(i.textContent=(this.mode||"single").toUpperCase());let s=e.getElementById("tab-viewfinder"),o=e.getElementById("tab-workbench");s&&s.setAttribute("aria-selected",String(this.#a==="viewfinder")),o&&o.setAttribute("aria-selected",String(this.#a==="workbench"));let n=e.getElementById("viewfinder-section"),c=e.getElementById("workbench-section");n&&c&&(this.#a==="viewfinder"?(n.style.display="flex",c.style.display="none"):(n.style.display="none",c.style.display="flex"));let l=e.getElementById("framing-guide");l&&l.setAttribute("data-aspect",this.aspect||"auto");let d=e.getElementById("step-pill-text");d&&(this.#g?d.textContent="Camera Active \xB7 Tap Shutter to Snap":this.aspect==="card"&&this.maxPages===2?d.textContent=t.length===0?"Step 1 of 2: Capture Front of ID Card":"Step 2 of 2: Capture Back of ID Card":this.aspect==="card"?d.textContent="Align Card Inside Frame":this.mode==="batch"?d.textContent=`Batch Capture \xB7 Page ${t.length+1}`:d.textContent="Align Document Inside Frame");let u=e.getElementById("btn-ocr");u&&(u.style.display=this.ocrEnabled&&this.hasFeature("ocr")?"":"none");let h=e.getElementById("btn-review"),g=e.getElementById("review-pill-text");if(h&&g&&(t.length>0?(h.style.display="inline-flex",g.textContent=`Review (${t.length}) \u2192`):h.style.display="none"),t.length===0){this.#a==="workbench"&&(this.stage="viewfinder");return}this.#e>=t.length&&(this.#e=Math.max(0,t.length-1));let m=t[this.#e],E=e.getElementById("card-side-switcher");if(E){let R=this.aspect==="card"&&this.maxPages===2;E.style.display=R?"flex":"none";let U=e.getElementById("btn-card-front"),P=e.getElementById("btn-card-back");U&&(U.classList.toggle("active",this.#e===0),U.setAttribute("aria-selected",String(this.#e===0))),P&&(P.classList.toggle("active",this.#e===1),P.setAttribute("aria-selected",String(this.#e===1)))}let D=e.getElementById("canvas-viewport");D&&D.classList.toggle("is-cropping",this.#i);let x=e.getElementById("stage-img");if(x)if(this.#i){let R=m.edits?.rotate||0,U=m.edits?.filter||"none",P=m.originalSrc||m.src||"";if(R!==0||U!=="none"){let y=this.#t?await this.#t.renderEdits(P,{rotate:R,filter:U}):P;x.src=y||P}else x.src=P}else x.src=m.src||m.originalSrc||"";let w=e.getElementById("crop-layer");if(this.#i){if(!w){let P=e.getElementById("canvas-wrapper");w=document.createElement("div"),w.className="copio-crop-layer",w.id="crop-layer",w.innerHTML=`
1361
- <div class="copio-crop-box" id="crop-box">
1362
- <div class="copio-crop-grid"></div>
1363
- <span class="copio-crop-handle nw" data-handle="nw"></span>
1364
- <span class="copio-crop-handle ne" data-handle="ne"></span>
1365
- <span class="copio-crop-handle se" data-handle="se"></span>
1366
- <span class="copio-crop-handle sw" data-handle="sw"></span>
1367
- <span class="copio-crop-handle n edge-n" data-handle="n"></span>
1368
- <span class="copio-crop-handle e edge-e" data-handle="e"></span>
1369
- <span class="copio-crop-handle s edge-s" data-handle="s"></span>
1370
- <span class="copio-crop-handle w edge-w" data-handle="w"></span>
1371
- </div>
1372
- `,P?.appendChild(w),this.#v()}w.style.display="block";let R=m.edits?.rotate||0,U=m.edits?.crop;this.#n=U?Es(U,R):{x:.05,y:.05,w:.9,h:.9},this.#S()}else w&&w.remove();let A=e.getElementById("crop-btn-label");A&&(A.textContent=this.#i?"Apply":"Crop");let k=e.getElementById("btn-primary-complete");k&&(this.aspect==="card"&&this.maxPages===2&&t.length===1?k.textContent="Next: Capture Back (Step 2/2) \u2192":this.aspect==="card"&&t.length>=2?k.textContent="\u2713 Complete ID Scan (2 Sides)":this.mode==="batch"?k.textContent=`\u2713 Complete Scan (${t.length} Pages)`:k.textContent="\u2713 Use Photo"),this.#L(t)}catch{}}#L(t){let e=this.shadowRoot;if(!e)return;let i=e.getElementById("filmstrip-scroll");i&&(i.innerHTML="",t.forEach((s,o)=>{let n=document.createElement("div");n.className=`copio-filmstrip-item ${o===this.#e?"is-active":""}`,n.setAttribute("data-index",String(o)),n.innerHTML=`
1373
- <div class="copio-thumb-container">
1374
- <img src="${s.src||s.originalSrc}" alt="Page ${o+1}" class="copio-thumb-img" />
1375
- <span class="copio-thumb-num">${o+1}</span>
1376
- </div>
1377
- ${this.mode==="batch"?`
1378
- <div class="copio-thumb-reorder">
1379
- <button type="button" class="copio-reorder-btn move-left" title="Move Left" ${o===0?"disabled":""}>\u25C0</button>
1380
- <button type="button" class="copio-reorder-btn move-right" title="Move Right" ${o===t.length-1?"disabled":""}>\u25B6</button>
1381
- </div>
1382
- `:""}
1383
- `,n.querySelector(".copio-thumb-container")?.addEventListener("click",()=>{this.#e=o,this.#i=!1,this.#m()}),this.mode==="batch"&&(n.querySelector(".move-left")?.addEventListener("click",async c=>{c.stopPropagation(),await this.#k(o,o-1)}),n.querySelector(".move-right")?.addEventListener("click",async c=>{c.stopPropagation(),await this.#k(o,o+1)})),i.appendChild(n)}))}async#k(t,e){let i=await this.getPages();if(e<0||e>=i.length||t===e)return;let s=i.map(n=>n.id),[o]=s.splice(t,1);s.splice(e,0,o),await this.#t.reorderPages(this.#f,s),this.#e=e,this.#m()}#x(){this.#g&&(this.#g.getTracks().forEach(s=>s.stop()),this.#g=null);let t=this.shadowRoot,e=t?.getElementById("camera-video");e&&(e.srcObject=null,e.style.display="none");let i=t?.querySelector(".copio-camera-placeholder");i&&(i.style.display="")}async#R(){if(typeof this.onShutter=="function"&&await this.onShutter()!==!1)return;let t=this.shadowRoot,e=t?.getElementById("camera-video");if(this.#g&&e&&e.readyState>=2){let o=document.createElement("canvas");o.width=e.videoWidth||1280,o.height=e.videoHeight||720;let n=o.getContext("2d");if(n){n.drawImage(e,0,0,o.width,o.height);let c=await new Promise(l=>o.toBlob(l,"image/jpeg",.92));if(c){this.#x();let l=new File([c],`capture_${Date.now()}.jpg`,{type:"image/jpeg"});await this.addFiles([l]);return}}}if(!(typeof navigator<"u"&&navigator.webdriver===!0)&&typeof navigator<"u"&&navigator.mediaDevices?.getUserMedia&&e)try{this.#g=await navigator.mediaDevices.getUserMedia({video:{facingMode:{ideal:"environment"},width:{ideal:1920},height:{ideal:1080}},audio:!1}),e.srcObject=this.#g,e.style.display="block",await e.play();let o=t?.querySelector(".copio-camera-placeholder");o&&(o.style.display="none");let n=t?.getElementById("step-pill-text");n&&(n.textContent="Camera Active \xB7 Tap Shutter to Snap");return}catch{}let s=t?.getElementById("internal-file-input");s&&typeof s.click=="function"&&s.click()}async#P(){let e=(await this.getPages())[this.#e];if(!e)return;this.#i&&(this.#i=!1,this.#n=null);let s=((e.edits?.rotate||0)+90)%360;await this.#t.applyEdit(this.#f,e.id,{rotate:s}),await this.#m()}async#E(){let e=(await this.getPages())[this.#e];if(!e)return;this.#i&&(this.#i=!1,this.#n=null);let s=(e.edits?.filter||"none")==="bw"?"none":"bw";await this.#t.applyEdit(this.#f,e.id,{filter:s}),await this.#m()}async#C(){let e=(await this.getPages())[this.#e];if(e){if(this.#i){this.#i=!1;let i=this.#n;if(this.#n=null,i){let s=e.edits?.rotate||0,o=Cs(i,s);await this.#t.applyEdit(this.#f,e.id,{crop:o})}}else this.#i=!0;await this.#m()}}async#D(){let t=await this.getPages(),e=t[this.#e];if(!e)return;let i=e.id;await this.#t.deletePage(this.#f,i),this.dispatch(St.PAGE_REMOVED,{pageId:i,docId:this.docId}),this.#e>=t.length-1&&(this.#e=Math.max(0,t.length-2)),this.#B(),await this.#m()}#B(){let t=this.shadowRoot;if(!t)return;let e=t.getElementById("toast-region");if(!e)return;this.#d&&clearInterval(this.#d),this.#h=5;let i=()=>{e.innerHTML=`
1384
- <div class="copio-toast copio-toast-undo">
1385
- <span>Page deleted</span>
1386
- <button type="button" class="copio-btn-toast-undo" id="btn-toast-undo">
1387
- Undo (${this.#h}s)
1388
- </button>
1389
- </div>
1390
- `,t.getElementById("btn-toast-undo")?.addEventListener("click",async()=>{clearInterval(this.#d),this.#d=null,e.innerHTML="",await this.#t.undo(this.#f),await this.#m()})};i(),this.#d=setInterval(()=>{this.#h-=1,this.#h<=0?(clearInterval(this.#d),this.#d=null,e.innerHTML=""):i()},1e3)}async#T(){let t=this.shadowRoot;if(!t)return;let e=t.getElementById("ocr-sheet"),i=t.getElementById("ocr-body");if(!(!e||!i)){e.style.display="block",i.innerHTML='<p class="copio-ocr-loading">Recognizing text...</p>';try{let o=(await this.getPages())[this.#e],n=await this.ocr(o?.id||null),c=n.averageConfidence||0,l=c<=1&&c>0?Math.round(c*100):Math.round(c);i.innerHTML=`
1391
- <div class="copio-ocr-content">
1392
- <pre class="copio-ocr-text">${n.text||"No text detected."}</pre>
1393
- <div class="copio-ocr-meta">
1394
- <span>Confidence: ${l}%</span>
1395
- </div>
1396
- </div>
1397
- `}catch(s){i.innerHTML=`<p class="copio-ocr-error">OCR recognition failed: ${s.message}</p>`}}}#M(){let t=this.shadowRoot;if(!t)return;let e=t.getElementById("ocr-sheet");e&&(e.style.display="none")}async#O(){if(this.aspect==="card"&&this.maxPages===2&&this.#c===1){this.stage="viewfinder";return}let t=await this.getPages();if(this.aspect==="card"&&this.maxPages===2&&t.length===1){this.stage="viewfinder";return}let e=t.map((s,o)=>({id:s.id,pageNumber:o+1,label:s.label||`Page ${o+1}`,originalSrc:s.originalSrc,src:s.src,originalPreserved:!0,dimensions:{width:s.width||0,height:s.height||0},edits:s.edits||{crop:{x:0,y:0,w:1,h:1},rotate:0,filter:"none"},ocrText:s.ocrText||null,blob:s.blob||null})),i={mode:this.mode,aspect:this.aspect,docId:this.docId,pageCount:e.length,pages:e};this.mode==="single"&&(i.page=e[0]||null,this.maxPages>1&&(i.maxPages=this.maxPages)),this.dispatch(St.SCAN_COMPLETE,i)}get theme(){return typeof this.getAttribute=="function"&&this.getAttribute("theme")||"dark"}set theme(t){typeof this.setAttribute=="function"&&(t?this.setAttribute("theme",t):this.removeAttribute("theme"))}get mode(){return typeof this.getAttribute=="function"&&this.getAttribute("mode")||"document"}set mode(t){typeof this.setAttribute=="function"&&this.setAttribute("mode",t)}get aspect(){return typeof this.getAttribute=="function"&&this.getAttribute("aspect")||"auto"}set aspect(t){typeof this.setAttribute=="function"&&this.setAttribute("aspect",t)}get stage(){return this.#a}set stage(t){if(t==="viewfinder"||t==="workbench"){this.#a=t,typeof this.setAttribute=="function"&&this.getAttribute("stage")!==t&&this.setAttribute("stage",t);let e=this.shadowRoot;if(e){let i=e.getElementById("viewfinder-section"),s=e.getElementById("workbench-section");i&&s&&(i.style.display=t==="viewfinder"?"flex":"none",s.style.display=t==="workbench"?"flex":"none")}this.#m()}}get docId(){return typeof this.getAttribute=="function"?this.getAttribute("doc-id"):null}set docId(t){typeof this.setAttribute=="function"&&(t?this.setAttribute("doc-id",t):this.removeAttribute("doc-id"))}async rotateActivePage(){return this.#P()}async toggleActivePageBw(){return this.#E()}async toggleCropMode(){return this.#C()}async deleteActivePageWithUndo(){return this.#D()}setCameraStream(t){this.#x(),this.#g=t}get features(){return this.#t?this.#t.features:[]}set features(t){if(typeof this.setAttribute=="function"){let e=Array.isArray(t)?t.join(" "):String(t||"");this.setAttribute("features",e)}this.#t&&this.#t.setFeatures(t)}hasFeature(t){return this.#t?this.#t.hasFeature(t):!1}get ocrEnabled(){return this.#t?this.#t.ocr:!0}set ocrEnabled(t){let e=!!t;typeof this.setAttribute=="function"&&this.setAttribute("ocr",e?"true":"false"),this.#t&&(this.#t.ocr=e),this.#b()}get pdf(){return this.#t?this.#t.pdf:!0}set pdf(t){let e=!!t;typeof this.setAttribute=="function"&&this.setAttribute("pdf",e?"true":"false"),this.#t&&(this.#t.pdf=e),this.#b()}get exportFormats(){return this.#t?this.#t.exportFormats:[]}set exportFormats(t){if(typeof this.setAttribute=="function"){let e=Array.isArray(t)?t.join(","):String(t||"");this.setAttribute("export-formats",e)}this.#t&&(this.#t.exportFormats=t)}get ocrLanguages(){return this.#t?this.#t.ocrLanguages:[]}set ocrLanguages(t){if(typeof this.setAttribute=="function"){let e=Array.isArray(t)?t.join(","):String(t||"");this.setAttribute("ocr-languages",e)}this.#t&&(this.#t.ocrLanguages=t)}get maxPages(){return this.#t?this.#t.maxPages:0}set maxPages(t){typeof this.setAttribute=="function"&&this.setAttribute("max-pages",String(t)),this.#t&&(this.#t.maxPages=t)}get assetBase(){return this.#t?this.#t.assetBase:""}set assetBase(t){typeof this.setAttribute=="function"&&this.setAttribute("asset-base",String(t||"")),this.#t&&(this.#t.assetBase=t)}get licenseKey(){return this.#t?this.#t.licenseKey:""}set licenseKey(t){typeof this.setAttribute=="function"&&this.setAttribute("license-key",String(t||"")),this.#t&&(this.#t.licenseKey=t)}get storage(){return this.#r}set storage(t){this.#r=t,this.#t&&this.#t.setStorage(t)}get engine(){return this.#t}set engine(t){t instanceof Ei&&(this.#t=t)}dispatch(t,e={}){return On(this,t,e)}async open(){this.#l=!0,typeof this.focus=="function"&&this.focus()}async close(){this.#l=!1,this.#x()}get isOpen(){return this.#l}async capture(){return new Promise(t=>{let e=document.createElement("input");e.type="file",e.accept="image/*",e.capture="environment",e.style.display="none",e.onchange=async()=>{try{if(e.files&&e.files.length>0){let i=await this.addFiles([e.files[0]]);t(i[0]||null)}else t(null)}catch(i){this.dispatch(St.ERROR,{code:"CAPTURE_FAILED",message:i.message,error:i}),t(null)}finally{e.remove()}},e.onerror=()=>{e.remove(),t(null)},document.body.appendChild(e),e.click()})}async addFiles(t){try{let e=await this.getPages(),i=null;if(e.length>0){if(this.mode==="single"&&this.maxPages<=1)await this.#t.clear(this.#f);else if(this.#o||this.maxPages>0&&e.length>=this.maxPages){let n=Math.min(this.#e,e.length-1),c=e[n];c&&(i=n,await this.#t.deletePage(this.#f,c.id))}}this.#o=!1;let s=await this.#t.addFiles(t,this.#f);for(let n=0;n<s.length;n++)this.dispatch(St.PAGE_ADDED,{page:s[n],pageNumber:n+1,docId:this.docId,source:"file"});let o=await this.getPages();if(i!==null&&s.length===1&&i<o.length-1){let n=o.map(l=>l.id),c=n.pop();c&&(n.splice(i,0,c),await this.#t.reorderPages(this.#f,n),o=await this.getPages())}return this.#c=o.length,s.length>0&&(this.#e=i!==null?Math.min(i,Math.max(0,o.length-1)):Math.max(0,o.length-1),this.mode==="single"&&(this.#a="workbench",typeof this.setAttribute=="function"&&this.getAttribute("stage")!=="workbench"&&this.setAttribute("stage","workbench"))),this.dispatch(St.PAGES_CHANGED,{pages:o,docId:this.docId}),this.mode==="single"&&s.length>0&&this.maxPages<=1&&this.dispatch(St.SCAN_COMPLETE,{mode:this.mode,aspect:this.aspect,docId:this.docId,pages:o,page:o[o.length-1]||null,pageCount:o.length}),await this.#m(),s}catch(e){throw this.dispatch(St.ERROR,{code:e.code||"ADD_FILES_FAILED",message:e.message,error:e}),e}}async getPages(){return this.#t.getPages(this.#f)}async clear(){this.#x(),this.#e=0,this.#c=0,this.#o=!1,this.#i=!1,await this.#t.clear(this.#f),this.dispatch(St.PAGES_CHANGED,{pages:[],docId:this.docId}),await this.#m()}async exportPdf(t={}){try{let e=await this.#t.exportPdf(this.#f,t);return this.dispatch(St.EXPORT_COMPLETE,{type:"pdf",format:"pdf",blob:e,searchable:!!t.searchable,docId:this.docId}),e}catch(e){throw this.dispatch(St.ERROR,{code:e.code||"EXPORT_FAILED",message:e.message,error:e}),e}}async exportZip(t={}){try{let e=await this.#t.exportZip(this.#f,t);return this.dispatch(St.EXPORT_COMPLETE,{type:"zip",format:"zip",blob:e,docId:this.docId}),e}catch(e){throw this.dispatch(St.ERROR,{code:e.code||"EXPORT_FAILED",message:e.message,error:e}),e}}async ocr(t=null,e={}){try{let i=await this.#t.runOcr(this.#f,t,e);return this.dispatch(St.OCR_COMPLETE,{text:i.text,pages:i.pagesResults,averageConfidence:i.averageConfidence,docId:this.docId,pageId:t}),i}catch(i){throw this.dispatch(St.ERROR,{code:i.code||"OCR_FAILED",message:i.message,error:i}),i}}async runOcr(t=null,e={}){return this.ocr(t,e)}async sync(t={}){try{return await this.#t.sync({onStateChange:i=>{i&&(i.step==="connected"||i.step==="syncing")&&this.dispatch(St.SYNC_CONNECTED,{peerId:i.peerId,mode:i.mode}),t.onStateChange&&t.onStateChange(i)}})}catch(e){throw this.dispatch(St.ERROR,{code:e.code||"SYNC_FAILED",message:e.message,error:e}),e}}};typeof customElements<"u"&&!customElements.get("copio-scanner")&&customElements.define("copio-scanner",Rs);export{St as COPIO_EVENTS,Rs as CopioScanner,$n as adoptScannerStyles,On as dispatchCopioEvent,Nn as getScannerStyleSheet,Ls as scannerCss};
2
+ var La=Object.defineProperty;var ci=(r,t,e)=>()=>{if(e)throw e[0];try{return r&&(t=r(r=0)),t}catch(i){throw e=[i],i}};var Ma=(r,t)=>{for(var e in t)La(r,e,{get:t[e],enumerable:!0})};function ha(){return Yo}function Li(r){typeof r=="string"&&(Yo=r.replace(/\/+$/,"")||".")}function Vc(r){if(!r)return"";if(/^(https?:|\/\/|data:|blob:)/i.test(r))return r;let t=r.replace(/^\/+/,""),e=Yo;return!e||e==="."?t:`${e}/${t}`}function Wc(r,t){let e=t();if(e)return Promise.resolve(e);if(Fr.has(r))return Fr.get(r);let i=new Promise((o,s)=>{if(typeof document>"u"){s(new Error(`Cannot load script "${r}" in an environment without DOM document.`));return}let n=Vc(r),a=document.querySelector(`script[src="${n}"], script[src="${r}"]`);if(a){if(t()){o(t());return}a.addEventListener("load",()=>o(t()),{once:!0}),a.addEventListener("error",()=>s(new Error(`Failed to load "${r}": Network error`)),{once:!0});return}let c=document.createElement("script");c.src=n,c.async=!0,c.onload=()=>{let h=t();o(h)},c.onerror=()=>{Fr.delete(r),c.remove(),s(new Error(`Failed to load script "${r}": Network error`))},document.head.appendChild(c)});return Fr.set(r,i),i}async function da(){return Wc("js/lib/peerjs.min.js",()=>window.Peer)}var Yo,Fr,Nr=ci(()=>{Yo=".";Fr=new Map});function zr(r){let t=r instanceof Uint8Array?r:new Uint8Array(r),e="",i=32768;for(let s=0;s<t.length;s+=i){let n=t.subarray(s,s+i);e+=String.fromCharCode.apply(null,n)}return globalThis.btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Vr(r){if(typeof r!="string")throw new TypeError("Expected string for base64url decoding");let t=r.replace(/-/g,"+").replace(/_/g,"/");for(;t.length%4!==0;)t+="=";let e=globalThis.atob(t),i=new Uint8Array(e.length);for(let o=0;o<e.length;o++)i[o]=e.charCodeAt(o);return i}function va(r){let t=new TextEncoder().encode(r);return zr(t)}function Sa(r){let t=Vr(r);return new TextDecoder().decode(t)}async function Wr(){let r=globalThis.crypto?.subtle;if(!r)throw new Error("WebCrypto API (crypto.subtle) is not available");return await r.generateKey(xa,!0,["deriveKey","deriveBits"])}async function qr(r){let e=await globalThis.crypto.subtle.exportKey("raw",r);return zr(new Uint8Array(e))}async function Kr(r){let t=globalThis.crypto.subtle,e=Vr(r);return await t.importKey("raw",e,xa,!1,[])}async function Gr(r,t){return await globalThis.crypto.subtle.deriveKey({name:"ECDH",public:t},r,rl,!1,["encrypt","decrypt"])}async function ii(r,t){let e=globalThis.crypto.subtle,i;typeof t=="string"?i=new TextEncoder().encode(t):t instanceof Uint8Array?i=t:t instanceof ArrayBuffer?i=new Uint8Array(t):i=new TextEncoder().encode(JSON.stringify(t));let o=globalThis.crypto.getRandomValues(new Uint8Array(ol)),s=await e.encrypt({name:"AES-GCM",iv:o},r,i);return{iv:zr(o),ciphertext:zr(new Uint8Array(s))}}async function rs(r,t,e){let i=globalThis.crypto.subtle,o=typeof t=="string"?Vr(t):t,s=typeof e=="string"?Vr(e):e,n=await i.decrypt({name:"AES-GCM",iv:o},r,s);return new Uint8Array(n)}async function os(r,t,e){let i=await rs(r,t,e),o=new TextDecoder().decode(i);try{return JSON.parse(o)}catch{return o}}var il,xa,rl,ol,ka=ci(()=>{il="P-256",xa={name:"ECDH",namedCurve:il},rl={name:"AES-GCM",length:256},ol=12});function Hi(r="hnd_"){let t=globalThis.crypto.getRandomValues(new Uint8Array(8)),e="";for(let i=0;i<t.length;i++)e+=t[i].toString(16).padStart(2,"0");return`${r}${e}`}function Ea(r){let t={v:r.v||1,sessionId:r.sessionId,peerId:r.peerId,pubKey:r.pubKey,expiresAt:r.expiresAt};return va(JSON.stringify(t))}function Xr(r){if(!r||typeof r!="string")throw new Error("Invalid handoff token string");let t;try{let e=r.trim();e.startsWith("{")&&e.endsWith("}")?t=JSON.parse(e):t=JSON.parse(Sa(r))}catch(e){throw new Error(`Failed to decode handoff token: ${e.message}`)}if(!t.sessionId||!t.peerId||!t.pubKey||!t.expiresAt)throw new Error("Malformed handoff token: missing required fields");if(Date.now()>t.expiresAt)throw new Error(`Handoff session token has expired at ${new Date(t.expiresAt).toISOString()}`);return t}function al(r,t){let e=Ea(t);return`${r?r.split("#")[0]:""}#handoff=${e}`}function ss(r){if(!r||typeof r!="string")throw new Error("Invalid URL or hash string for handoff");let t=r.indexOf("#"),i=(t!==-1?r.slice(t+1):r).match(/(?:copio-)?handoff=([^&]+)/);if(!i||!i[1])throw new Error("No handoff parameter found in hash");return Xr(i[1])}async function cl(r){if(r instanceof Uint8Array)return r;if(r instanceof ArrayBuffer)return new Uint8Array(r);if(r&&typeof r.arrayBuffer=="function"){let t=await r.arrayBuffer();return new Uint8Array(t)}throw new TypeError("Payload must be a Uint8Array, ArrayBuffer, or Blob")}var sl,nl,Nt,Jr,ns=ci(()=>{ka();sl=64*1024,nl=600*1e3;Nt=class r{#t=null;#r=new Set;#n=new Set;#s=!1;#e=!1;#i="all";static#a=new Map;static register(t,e){return r.#a.set(t,e),()=>r.#a.delete(t)}static has(t){return r.#a.has(t)}static get(t){return r.#a.get(t)}static clearRegistry(){r.#a.clear()}static createLinkedSender(t){let e=r.#a.get(t);if(!e)throw new Error(`No registered loopback host for peerId: ${t}`);let i=new r;return e.#t=i,i.#t=e,e.#s=!1,i.#s=!1,i}static createPair(){let t=new r,e=new r;return t.#t=e,e.#t=t,[t,e]}send(t){if(this.#s)throw new Error("Cannot send on closed LoopbackTransport");if(!this.#t||this.#t.#s)throw new Error("Remote peer disconnected");let e=this.#t;queueMicrotask(()=>{e.#s||e.#l(t)})}#l(t){for(let e of this.#r)try{e(t)}catch(i){console.error("[LoopbackTransport] message handler error:",i)}}onMessage(t){return this.#r.add(t),()=>this.#r.delete(t)}onClose(t){return this.#n.add(t),()=>this.#n.delete(t)}interrupt(){this.#s=!0;for(let t of this.#n)try{t()}catch(e){console.error("[LoopbackTransport] close handler error:",e)}this.#t&&!this.#t.#s&&this.#t.interrupt()}reconnect(t=null){this.#s=!1,t?(this.#t=t,t.#t=this,t.#s=!1):this.#t&&(this.#t.#s=!1)}get forceRelay(){return this.#e}set forceRelay(t){this.#e=!!t}get iceTransportPolicy(){return this.#i}set iceTransportPolicy(t){this.#i=t}async getConnectionInfo(){let t=this.#e||this.#i==="relay";return{transport:t?"turn":"direct",rttMs:t?15:0}}close(){if(!this.#s){this.#s=!0;for(let t of this.#n)try{t()}catch(e){console.error("[LoopbackTransport] close handler error:",e)}if(this.#t&&!this.#t.#s){let t=this.#t;this.#t=null,t.close()}}}get isClosed(){return this.#s}};Jr=class r{#t;#r=null;#n="idle";#s=null;#e=null;#i=null;#a;#l;#o=null;#p=Promise.resolve();#h=new Map;#d=[];#u={stateChange:new Set,connectionInfo:new Set,progress:new Set,page:new Set,complete:new Set,error:new Set};constructor(t={}){if(!t.role||t.role!=="host"&&t.role!=="sender")throw new Error("HandoffSession requires role to be 'host' or 'sender'");this.#t=t.role,this.#a=t.chunkSize||sl,this.#l=t.ttlMs||nl,t.transport&&this.setTransport(t.transport),t.onStateChange&&this.on("stateChange",t.onStateChange),t.onProgress&&this.on("progress",t.onProgress),t.onPage&&this.on("page",t.onPage),t.onComplete&&this.on("complete",t.onComplete),t.onError&&this.on("error",t.onError)}get role(){return this.#t}get state(){return this.#n}get token(){return this.#i}get isConnected(){return this.#n==="connected"||this.#n==="receiving"||this.#n==="sending"||this.#n==="complete"&&!!this.#e&&!!this.#r&&!this.#r.isClosed}on(t,e){return this.#u[t]?(this.#u[t].add(e),()=>this.#u[t].delete(e)):()=>{}}#f(t,e){if(this.#u[t])for(let i of this.#u[t])try{i(e)}catch(o){console.error(`[HandoffSession] error in ${t} listener:`,o)}}#c(t){this.#n!==t&&(this.#n=t,this.#f("stateChange",t),t==="connected"&&this.getConnectionInfo().then(e=>{this.#f("connectionInfo",e)}).catch(()=>{}))}#m(t){let e=t instanceof Error?t:new Error(String(t));this.#c("error"),this.#f("error",e)}setTransport(t){this.#r=t,t.onMessage(e=>{this.#p=this.#p.then(async()=>{await this.#y(e)}).catch(i=>{this.#m(i)})}),t.onClose(()=>{this.#n!=="closed"&&this.#n!=="complete"&&this.#c("disconnected")})}static async createLoopbackPair(t={}){let[e,i]=Nt.createPair(),o=new r({role:"host",transport:e,chunkSize:t.chunkSize,ttlMs:t.ttlMs}),s=new r({role:"sender",transport:i,chunkSize:t.chunkSize,ttlMs:t.ttlMs}),{token:n,url:a}=await o.startHost({baseUrl:t.baseUrl||"https://copio.netlify.app/scan",peerId:t.peerId||Hi("peer_")});return await s.startSender(n),{host:o,sender:s,token:n,url:a}}async startHost(t={}){if(this.#t!=="host")throw new Error("startHost() can only be called on a host session");this.#s=await Wr();let e=await qr(this.#s.publicKey),i=Hi("hnd_"),o=t.peerId||Hi("peer_"),s=Date.now()+this.#l;this.#i={v:1,sessionId:i,peerId:o,pubKey:e,expiresAt:s},t.relayUrl&&(this.#i.relayUrl=t.relayUrl),t.signalingUrl&&(this.#i.signalingUrl=t.signalingUrl),t.iceServers&&(this.#i.iceServers=t.iceServers);let n=t.baseUrl||(typeof location<"u"?`${location.origin}${location.pathname}`:""),a=al(n,this.#i),c=Ea(this.#i);return clearTimeout(this.#o),this.#o=setTimeout(()=>{(this.#n==="waiting"||this.#n==="idle")&&this.#c("expired")},this.#l),this.#c("waiting"),{token:this.#i,url:a,rawToken:c}}async startSender(t){if(this.#t!=="sender")throw new Error("startSender() can only be called on a sender session");let e;if(typeof t=="string"?e=t.includes("#")?ss(t):Xr(t):e=t,!e||!e.sessionId||!e.pubKey)throw new Error("Invalid handoff token");if(Date.now()>e.expiresAt)throw this.#c("expired"),new Error("Handoff session has expired");this.#i=e,this.#c("connecting"),this.#s=await Wr();let i=await qr(this.#s.publicKey),o=await Kr(e.pubKey);if(this.#e=await Gr(this.#s.privateKey,o),!this.#r)throw new Error("Transport must be set before starting sender");this.#r.send({type:"handshake_init",sessionId:e.sessionId,senderPubKey:i})}async reconnect(t=null){if(this.#t!=="sender")throw new Error("reconnect() can only be called on a sender session");if(!this.#i)throw new Error("Cannot reconnect: no session token");if(Date.now()>this.#i.expiresAt)throw this.#c("expired"),new Error("Handoff session has expired");t?this.setTransport(t):this.#r&&typeof this.#r.reconnect=="function"&&this.#r.reconnect(),this.#c("connecting"),this.#s||(this.#s=await Wr());let e=await qr(this.#s.publicKey),i=await Kr(this.#i.pubKey);if(this.#e=await Gr(this.#s.privateKey,i),!this.#r||this.#r.isClosed)throw new Error("Cannot reconnect without active transport");this.#r.send({type:"handshake_init",sessionId:this.#i.sessionId,senderPubKey:e})}async sendPage(t){if(this.#t!=="sender")throw new Error("sendPage() can only be called by sender");if(!this.isConnected||!this.#e)throw new Error(`Cannot send page in state "${this.#n}" (not connected)`);let e=t.id||Hi("page_"),i=typeof t.pageIndex=="number"?t.pageIndex:0,o=t.mimeType||"image/jpeg",s=await cl(t.blob),n=s.byteLength,a=Math.max(1,Math.ceil(n/this.#a));this.#c("sending");let c={type:"page_start",pageId:e,pageIndex:i,mimeType:o,totalBytes:n,totalChunks:a,metadata:t.metadata||{}},h=await ii(this.#e,c);this.#r.send({type:"envelope",iv:h.iv,ciphertext:h.ciphertext});let p=0;for(let m=0;m<a;m++){let y=m*this.#a,S=Math.min(y+this.#a,n),b=s.subarray(y,S),v=await ii(this.#e,b);this.#r.send({type:"chunk_envelope",pageId:e,chunkIndex:m,totalChunks:a,iv:v.iv,ciphertext:v.ciphertext}),p+=b.length;let C={role:"sender",pageId:e,pageIndex:i,chunkIndex:m,totalChunks:a,bytesSent:p,totalBytes:n,percent:Math.round(p/n*100)};this.#f("progress",C)}let d={type:"page_end",pageId:e,totalBytes:n},g=await ii(this.#e,d);this.#r.send({type:"envelope",iv:g.iv,ciphertext:g.ciphertext}),this.#c("connected")}async complete(t={}){if(this.#t!=="sender")throw new Error("complete() can only be called by sender");if(!this.#e)throw new Error("Session is not authenticated");let e={type:"session_complete",docId:t.docId||Hi("doc_"),summary:t.summary||{},completedAt:Date.now()},i=await ii(this.#e,e);this.#r.send({type:"envelope",iv:i.iv,ciphertext:i.ciphertext}),this.#c("complete"),this.#f("complete",e)}async#y(t){if(!(!t||typeof t!="object"))try{this.#t==="host"?await this.#g(t):await this.#b(t)}catch(e){this.#m(e)}}async#g(t){if(t.type==="handshake_init"){if(!this.#i)throw new Error("Host session not initialized");if(t.sessionId!==this.#i.sessionId)throw new Error("Session ID mismatch in handshake");if(Date.now()>this.#i.expiresAt)throw this.#c("expired"),new Error("Handoff session token expired");let e=await Kr(t.senderPubKey);this.#e=await Gr(this.#s.privateKey,e);let i=await ii(this.#e,{type:"handshake_ack",sessionId:this.#i.sessionId,status:"ready"});this.#r.send({type:"envelope",iv:i.iv,ciphertext:i.ciphertext}),clearTimeout(this.#o),this.#c("connected");return}if(t.type==="chunk_envelope"){if(!this.#e)throw new Error("Received chunk before handshake completion");let e=this.#h.get(t.pageId);if(!e)throw new Error(`Received chunk for unknown page: ${t.pageId}`);let i=await rs(this.#e,t.iv,t.ciphertext);e.chunks[t.chunkIndex]=i,e.receivedBytes+=i.length;let o={role:"host",pageId:t.pageId,pageIndex:e.start.pageIndex,chunkIndex:t.chunkIndex,totalChunks:t.totalChunks,bytesReceived:e.receivedBytes,totalBytes:e.start.totalBytes,percent:Math.round(e.receivedBytes/e.start.totalBytes*100)};this.#f("progress",o);return}if(t.type==="envelope"){if(!this.#e)throw new Error("Received envelope before handshake completion");let e=await os(this.#e,t.iv,t.ciphertext);if(e.type==="page_start"){this.#h.set(e.pageId,{start:e,chunks:Array.from({length:e.totalChunks}),receivedBytes:0}),this.#c("receiving");return}if(e.type==="page_end"){let i=this.#h.get(e.pageId);if(!i)throw new Error(`Received page_end for unknown page: ${e.pageId}`);let o=i.start.mimeType||"image/jpeg",s;if(typeof globalThis.Blob=="function")s=new globalThis.Blob(i.chunks,{type:o});else{let a=i.chunks.reduce((p,d)=>p+d.length,0),c=new Uint8Array(a),h=0;for(let p of i.chunks)c.set(p,h),h+=p.length;s=c}let n={id:e.pageId,pageIndex:i.start.pageIndex,mimeType:o,blob:s,metadata:i.start.metadata};this.#d.push(n),this.#h.delete(e.pageId),this.#f("page",n),this.#c("connected");return}if(e.type==="session_complete"){let i={docId:e.docId,pageCount:this.#d.length,pages:[...this.#d],summary:e.summary};this.#c("complete"),this.#f("complete",i);return}}}async#b(t){if(t.type==="envelope"){if(!this.#e)throw new Error("Received envelope without shared key");(await os(this.#e,t.iv,t.ciphertext)).type==="handshake_ack"&&this.#c("connected")}}async getConnectionInfo(){return this.#r&&typeof this.#r.getConnectionInfo=="function"?await this.#r.getConnectionInfo():{transport:"direct",rttMs:0}}close(){if(clearTimeout(this.#o),this.#r){try{this.#r.close()}catch{}this.#r=null}this.#s=null,this.#e=null,this.#h.clear(),this.#d=[],this.#c("closed")}}});function Ca(r){if(!r||typeof r!="string")return null;try{let t=new URL(r),e=t.protocol==="https:"||t.protocol==="wss:",i=e?443:80,o=t.port?parseInt(t.port,10):i,s=t.pathname||"/";return s.endsWith("/")||(s+="/"),{host:t.hostname,port:o,path:s,secure:e,origin:t.origin}}catch{return null}}async function Pa(r={}){if(Array.isArray(r))return r;if(Array.isArray(r?.iceServers)&&r.iceServers.length>0)return r.iceServers;let t=new AbortController,e=setTimeout(()=>t.abort(),dl);if(r?.relayUrl&&typeof r.relayUrl=="string")try{let i=r.relayUrl.replace(/\/$/,""),o=i.endsWith("/ice")?i:`${i}/ice`,s=await fetch(o,{signal:t.signal,cache:"no-store"});if(s.ok){let n=await s.json(),a=Array.isArray(n)?n:n?.iceServers;if(Array.isArray(a)&&a.length>0)return a}}catch(i){console.warn("[Relay] Failed to fetch ICE credentials from custom relayUrl, trying managed relay:",i)}try{let i=await fetch(ll,{signal:t.signal,cache:"no-store"});if(!i.ok)throw new Error(`HTTP ${i.status}`);let o=await i.json();if(!Array.isArray(o)||o.length===0)throw new Error("Empty ICE server list");return[{urls:"stun:stun.l.google.com:19302"},...o]}catch(i){return console.warn("[Sync] Failed to fetch TURN credentials, using STUN only:",i),hl}finally{clearTimeout(e)}}var ll,hl,dl,Ia=ci(()=>{ll="https://copio.metered.live/api/v1/turn/credentials?apiKey=d90f0b0b6bdf180ea68238f5c2185074ce37",hl=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun.relay.metered.ca:80"}],dl=5e3});var Aa={};Ma(Aa,{HandoffPeerTransport:()=>as});var as,Da=ci(()=>{Nr();Ia();ns();as=class{#t;#r=null;#n=null;#s=null;#e=null;#i=null;#a=null;#l=null;#o="all";#p=null;#h=new Set;#d=new Set;#u=new Set;#f=!1;#c=!1;#m=0;#y=5;#g=null;#b=[];#w=null;#I=null;constructor(t={}){if(!t.role||t.role!=="host"&&t.role!=="sender")throw new Error("HandoffPeerTransport requires role to be 'host' or 'sender'");if(this.#t=t.role,this.#r=t.peerId||null,this.#n=t.targetPeerId||null,this.#i=t.iceServers||null,this.#a=t.relayUrl||null,this.#l=t.signalingUrl||null,this.#o=t.iceTransportPolicy||"all",this.#t==="sender"&&!this.#n)throw new Error("Sender transport requires targetPeerId");this.#t==="host"&&this.#r&&this.#T(),t.peerInstance?(this.#s=t.peerInstance,this.#M(this.#s)):this.#k().catch(e=>{console.warn("[HandoffPeerTransport] init error:",e)})}get peerId(){return this.#r}get targetPeerId(){return this.#n}get relayUrl(){return this.#a}get signalingUrl(){return this.#l}get iceTransportPolicy(){return this.#o}get connectionInfo(){return this.#p||{transport:this.#o==="relay"?"turn":"direct",rttMs:0}}async#k(){if(!this.#c)try{let t=this.#i;(!t||t.length===0)&&(t=await Pa({relayUrl:this.#a}));let e=await da();if(this.#c)return;if(!e)throw new Error("PeerJS is not available");let i={iceServers:t};this.#o&&(i.iceTransportPolicy=this.#o);let o={config:i,debug:0},s=this.#l||this.#a;if(s){let n=Ca(s);n&&(o.host=n.host,o.port=n.port,o.path=n.path,o.secure=n.secure)}this.#t==="host"&&this.#r?this.#s=new e(this.#r,o):this.#s=new e(o),this.#M(this.#s)}catch(t){console.warn("[HandoffPeerTransport] init failed:",t),this.#t==="sender"&&!this.#f&&this.#B()}}#T(){this.#w||!this.#r||(this.#w=new Nt,this.#I=Nt.register(this.#r,this.#w),this.#w.onMessage(t=>{this.#N(t)}))}#M(t){t.on("open",e=>{this.#r=e,this.#t==="host"&&this.#T(),this.#t==="sender"&&this.#n&&this.#v()}),t.on("connection",e=>{this.#t==="host"&&this.#A(e)}),t.on("error",e=>{console.warn("[HandoffPeerTransport] peer error:",e),this.#t==="sender"&&!this.#f&&this.#B()}),t.on("close",()=>{this.#R()})}#v(){if(!this.#s||this.#s.destroyed||!this.#n)return;let t=this.#s.connect(this.#n,{reliable:!0});this.#A(t)}#A(t){this.#e=t,t.on("open",()=>{this.#f=!1,this.#m=0,clearTimeout(this.#g);for(let e of this.#u)try{e()}catch(i){console.error("[HandoffPeerTransport] open handler error:",i)}for(;this.#b.length>0;){let e=this.#b.shift();try{t.send(e)}catch(i){console.error("[HandoffPeerTransport] send queued message error:",i)}}}),t.on("data",e=>{this.#N(e)}),t.on("close",()=>{this.#f||(this.#R(),this.#t==="sender"&&this.#B())}),t.on("error",e=>{console.warn("[HandoffPeerTransport] conn error:",e),this.#f||(this.#R(),this.#t==="sender"&&this.#B())})}#B(){if(this.#c||this.#f)return;if(this.#m>=this.#y){console.warn("[HandoffPeerTransport] max reconnect attempts reached");return}clearTimeout(this.#g);let t=Math.min(1e3*Math.pow(2,this.#m),8e3);this.#m++,this.#g=setTimeout(()=>{!this.#c&&!this.#f&&this.reconnect()},t)}reconnect(){if(!this.#c){if(this.#e){try{this.#e.close()}catch{}this.#e=null}this.#s&&!this.#s.destroyed&&this.#s.open?this.#v():this.#k().catch(()=>{})}}send(t){if(this.#c)throw new Error("Cannot send on destroyed HandoffPeerTransport");if(this.#w)try{this.#w.send(t)}catch{}this.#e&&this.#e.open?this.#e.send(t):(this.#t==="sender"||this.#e&&!this.#e.open)&&this.#b.push(t)}#N(t){for(let e of this.#h)try{e(t)}catch(i){console.error("[HandoffPeerTransport] message handler error:",i)}}#R(){for(let t of this.#d)try{t()}catch(e){console.error("[HandoffPeerTransport] close handler error:",e)}}onMessage(t){return this.#h.add(t),()=>this.#h.delete(t)}onClose(t){return this.#d.add(t),()=>this.#d.delete(t)}onOpen(t){if(this.#u.add(t),this.#e&&this.#e.open)try{t()}catch(e){console.error("[HandoffPeerTransport] open handler error:",e)}return()=>this.#u.delete(t)}async getConnectionInfo(){let t=this.#o==="relay",e=this.#e?.peerConnection||this.#e?._peerConnection;if(e&&typeof e.getStats=="function")try{let o=await e.getStats(),s=null;for(let n of o.values())if(n.type==="transport"&&n.selectedCandidatePairId){s=o.get(n.selectedCandidatePairId);break}if(!s){for(let n of o.values())if(n.type==="candidate-pair"&&(n.selected||n.nominated||n.state==="succeeded")){s=n;break}}if(s){let n=o.get(s.localCandidateId),a=o.get(s.remoteCandidateId),c=t||n?.candidateType==="relay"||a?.candidateType==="relay",h=s.currentRoundTripTime??s.roundTripTime??0,p={transport:c?"turn":"direct",rttMs:Math.round(h*1e3)};return this.#p=p,p}}catch(o){console.warn("[HandoffPeerTransport] getStats error:",o)}let i={transport:t?"turn":"direct",rttMs:0};return this.#p=i,i}close(){if(this.#f=!0,this.#c=!0,clearTimeout(this.#g),this.#I&&(this.#I(),this.#I=null),this.#w){try{this.#w.close()}catch{}this.#w=null}if(this.#e){try{this.#e.close()}catch{}this.#e=null}if(this.#s&&!this.#s.destroyed){try{this.#s.destroy()}catch{}this.#s=null}this.#R()}get isClosed(){return this.#f||this.#c}}});var Gt=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")}async getSchemaVersion(){return this._schemaVersion??null}async setSchemaVersion(t){this._schemaVersion=typeof t=="number"?t:null}subscribe(t){return()=>{}}};var Oe=class extends Gt{#t=new Map;#r=new Map;#n=new Set;#s=null;constructor(){super()}async init(){return{kind:"memory",persistent:!1}}listDocsSync(){return Array.from(this.#t.values()).map(t=>({...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?{...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,{...e,id:t,name:e.name||"",pages:i}),this.#e()}async deleteDoc(t){this.#t.delete(t);let e=`${t}/`;for(let i of this.#r.keys())i.startsWith(e)&&this.#r.delete(i);this.#e()}async renameDoc(t,e){let i=this.#t.get(t);if(!i)throw new Error(`Document "${t}" not found`);i.name=e,this.#e()}async savePage(t,e,i){this.#r.set(`${t}/${e}`,i);let o=this.#t.get(t);if(o){let s=o.pages.findIndex(n=>n.id===e);if(s>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?o.pages[s]={...o.pages[s],...i}:o.pages[s]={...o.pages[s],src:i};else{let n=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i};o.pages.push(n)}}this.#e()}async getPage(t,e){if(this.#r.has(`${t}/${e}`))return this.#r.get(`${t}/${e}`);let i=this.#t.get(t);if(i){let o=i.pages.find(s=>s.id===e);if(o)return o.src??o}return null}async deletePage(t,e){this.#r.delete(`${t}/${e}`);let i=this.#t.get(t);i&&(i.pages=i.pages.filter(o=>o.id!==e)),this.#e()}subscribe(t){return this.#n.add(t),()=>{this.#n.delete(t)}}async getSchemaVersion(){return this.#s}async setSchemaVersion(t){this.#s=typeof t=="number"?t:null}clear(){this.#t.clear(),this.#r.clear(),this.#s=null,this.#e()}#e(){for(let t of this.#n)try{t()}catch(e){console.error("Error in MemoryStorageAdapter subscriber:",e)}}};var le=r=>typeof r;var sn=le(""),Ba=le(!0),nn=le(0),Ua=le(le),rr="type",ge="default",po="Listener",Xs="Result",fo="add",me="Has",ui="Ids",ce="Table",Qs=ce+"s",Oa=ce+ui,$e="Row",an=$e+"Count",cn=$e+ui,Fa="Sorted"+$e+ui,di="Cell",ar=di+ui,cr="Value",Ys=cr+"s",Na=cr+ui,ct=r=>""+r;var Ha=(r,t="",e)=>r.split(t,e),uo=globalThis,fr=Math,so=fr.max,no=fr.min,$a=fr.floor,ln=isFinite,J=r=>r==null,lt=(r,t,e)=>J(r)?e?.():t(r),hn=r=>r==sn||r==Ba,_a=r=>le(r)==sn,zt=r=>le(r)==Ua,_e=r=>Array.isArray(r),go=(r,t,e)=>r.slice(t,e),Ot=r=>r.length,dn=()=>{};var ao=async(r,t,e)=>{try{return await r()}catch(i){t?.(i)}},mo=(r,t)=>r.includes(t),lr=(r,t)=>r.every(t),pn=(r,t)=>Ot(r)===Ot(t)&&lr(r,((e,i)=>t[i]===e)),Zs=(r,t)=>lr(r,((e,i)=>i==0||t(r[i-1],e)<=0)),yo=(r,t)=>r.sort(t),Lt=(r,t)=>r.forEach(t),we=(r,t)=>r.map(t),tn=r=>fn(r,((t,e)=>t+e),0),pi=r=>Ot(r)==0,fn=(r,t,e)=>r.reduce(t,e),Tt=(r,...t)=>r.push(...t),en=r=>r.pop(),un=r=>r.shift(),Ne=r=>{let t=le(r);return hn(t)||t==nn&&ln(r)?t:void 0};var hr=(r,t,e,i,o)=>J(o)?r.delCell(t,e,i,!0):r.setCell(t,e,i,o),bo=(r,t,e)=>J(e)?r.delValue(t):r.setValue(t,e),So=r=>t=>fn(je(t),((e,i)=>e+r(i)),0),ze=r=>r?.size??0,xe=So(ze),Xt=So(xe),co=So(Xt),pt=(r,t)=>r?.has(t)??!1,j=r=>J(r)||ze(r)==0,je=r=>[...r?.values()??[]],He=r=>r.clear(),$=(r,t)=>r?.forEach(t),Wt=(r,t)=>r?.delete(t),he=Object,rn=r=>he.getPrototypeOf(r),ja=he.isFrozen,gn=he.entries,dr=r=>!J(r)&&lt(rn(r),(t=>t==he.prototype||J(rn(t))),(()=>!0)),za=he.keys,Ve=he.freeze,Va=(r=[])=>he.fromEntries(r),hi=(r,t)=>t in r,mn=(r,t)=>(delete r[t],r),Wa=(r,t)=>Lt(gn(r),(([e,i])=>t(i,e))),Jt=(r,t)=>Va(((e,i)=>we(gn(e),(([o,s])=>i(s,o))))(r,((e,i)=>[i,t(e,i)]))),Vt=r=>dr(r)&&(t=>Ot(za(t)))(r)==0;var ne=(r,t,e,i=0)=>J(r)||!dr(r)||!i&&Vt(r)||ja(r)?(e?.(),!1):(Wa(r,((o,s)=>{t(o,s)||mn(r,s)})),!!i||!Vt(r)),A=r=>new Map(r),be=r=>[...r?.keys()??[]],P=(r,t)=>r?.get(t),bt=(r,t)=>$(r,((e,i)=>t(i,e))),F=(r,t,e)=>J(e)?(Wt(r,t),r):r?.set(t,e),dt=(r,t,e,i)=>(pt(r,t)?i?.(P(r,t)):F(r,t,e()),P(r,t)),ye=(r,t,e,i=F)=>(Jt(t,((o,s)=>e(r,s,o))),bt(r,(o=>hi(t,o)?0:i(r,o))),r),Rt=(r,t,e,i)=>{let o={};return $(r,((s,n)=>{if(!e?.(s,n)){let a=t?t(s,n):s;i?.(a)||(o[n]=a)}})),o},wo=(r,t,e)=>Rt(r,(i=>Rt(i,t,e)),j,Vt),or=(r,t,e)=>Rt(r,(i=>wo(i,t,e)),j,Vt),ae=(r,t)=>{let e=A();return $(r,((i,o)=>e.set(o,t?.(i)??i))),e},xo=r=>ae(r,ae),lo=r=>ae(r,xo),fi=(r,t,e,i,o=0)=>lt((e?dt:P)(r,t[o],o>Ot(t)-2?e:A),(s=>{if(o>Ot(t)-2)return i?.(s)&&F(r,t[o]),s;let n=fi(s,t,e,i,o+1);return j(s)&&F(r,t[o]),n})),wt=r=>new Set(_e(r)||J(r)?r:[r]),ut=(r,t)=>r?.add(t),ur=(r,t,e,i,o)=>{let s=r.hasRow,n=A(),a=A(),c=A(),h=A(),p=A(),d=A(),g=(b,v,...C)=>{let k=dt(d,b,wt);return Lt(C,(T=>ut(k,T)&&v&&r.callListener(T))),C},m=(b,...v)=>lt(P(d,b),(C=>{Lt(pi(v)?je(C):v,(k=>{r.delListener(k),Wt(C,k)})),j(C)&&F(d,b)})),y=(b,v)=>{F(n,b,v),pt(a,b)||(F(a,b,t()),F(h,b,A()),F(p,b,A()),o(c))},S=b=>{F(n,b),F(a,b),F(h,b),F(p,b),m(b),o(c)};return[()=>r,()=>be(n),b=>bt(a,b),b=>pt(a,b),b=>P(n,b),b=>P(a,b),(b,v)=>F(a,b,v),y,(b,v,C,k,T)=>{y(b,v);let B=A(),E=A(),w=P(h,b),D=P(p,b),H=M=>{let z=at=>r.getCell(v,M,at),et=P(w,M),ot=s(v,M)?e(k(z,M)):void 0;if(et===ot||_e(et)&&_e(ot)&&pn(et,ot)||F(B,M,[et,ot]),!J(T)){let at=P(D,M),G=s(v,M)?T(z,M):void 0;at!=G&&F(E,M,G)}},_=M=>{C((()=>{$(B,(([,z],et)=>F(w,et,z))),$(E,((z,et)=>F(D,et,z)))}),B,E,w,D,M),He(B),He(E)};bt(w,H),r.hasTable(v)&&Lt(r.getRowIds(v),(M=>{pt(w,M)||H(M)})),_(!0),m(b),g(b,0,r.addRowListener(v,null,((M,z,et)=>H(et))),r.addTableListener(v,(()=>_())))},S,b=>i(b,c),()=>bt(d,S),g,m]},pr=(r,t)=>_a(r)?e=>e(r):r??(()=>t??""),gi=(r,t)=>{let e=new WeakMap;return i=>{e.has(i)||e.set(i,r(i));let o=e.get(i);return t?.(o),o}},qa=/^\d+$/,yn=()=>{let r=[],t=0;return[e=>(e?un(r):null)??""+t++,e=>{qa.test(e)&&Ot(r)<1e3&&Tt(r,e)}]},mi=r=>{let t,[e,i]=yn(),o=A();return[(s,n,a,c=[],h=()=>[])=>{t??=r();let p=e(1);return F(o,p,[s,n,a,c,h]),ut(fi(n,a??[""],wt),p),p},(s,n,...a)=>Lt(((c,h=[""])=>{let p=[],d=(g,m)=>m==Ot(h)?Tt(p,g):h[m]===null?$(g,(y=>d(y,m+1))):Lt([h[m],null],(y=>d(P(g,y),m+1)));return d(c,0),p})(s,n),(c=>$(c,(h=>P(o,h)[0](t,...n??[],...a))))),s=>lt(P(o,s),(([,n,a])=>(fi(n,a??[""],void 0,(c=>(Wt(c,s),j(c)?1:0))),F(o,s),i(s),a))),s=>lt(P(o,s),(([n,,a=[],c,h])=>{let p=(...d)=>{let g=Ot(d);g==Ot(a)?n(t,...d,...h(d)):J(a[g])?Lt(c[g]?.(...d)??[],(m=>p(...d,m))):p(...d,a[g])};p()}))]},yl=gi((r=>{let t,e,i,o=100,s=A(),n=A(),a=1,c=A(),h=A(),[p,d,g]=mi((()=>G)),m=A(),y=A(),S=[],b=[],v=(R,N)=>{a=0,r.transaction((()=>{let[tt,Q]=P(m,N);$(tt,((O,V)=>$(O,((K,Y)=>$(K,((W,X)=>hr(r,V,Y,X,W[R]))))))),$(Q,((O,V)=>bo(r,V,O[R])))})),a=1},C=R=>{F(m,R),F(y,R),d(h,[R])},k=(R,N)=>Lt(((tt,Q)=>tt.splice(0,Q))(R,N??Ot(R)),C),T=()=>k(S,Ot(S)-o),B=()=>lt(t,(()=>{Tt(S,t),T(),k(b),t=void 0,i=1})),E=()=>{t=en(S),i=1},w,D,H=(R="")=>(J(t)&&(t=""+e++,F(m,t,[s,n]),ot(t,R),s=A(),n=A(),i=1),t),_=()=>{pi(S)||(((R,...N)=>{R.unshift(...N)})(b,H()),v(0,t),t=en(S),i=1)},M=()=>{pi(b)||(Tt(S,t),t=un(b),v(1,t),i=1)},z=()=>{i&&(d(c),i=0)},et=R=>{let N=H(R);return z(),N},ot=(R,N)=>(at(R)&&P(y,R)!==N&&(F(y,R,N),d(h,[R])),G),at=R=>pt(m,R),G={setSize:R=>(o=R,T(),G),addCheckpoint:et,setCheckpoint:ot,getStore:()=>r,getCheckpointIds:()=>[[...S],t,[...b]],forEachCheckpoint:R=>bt(y,R),hasCheckpoint:at,getCheckpoint:R=>P(y,R),goBackward:()=>(_(),z(),G),goForward:()=>(M(),z(),G),goTo:R=>{let N=mo(S,R)?_:mo(b,R)?M:null;for(;!J(N)&&R!=t;)N();return z(),G},addCheckpointIdsListener:R=>p(R,c),addCheckpointListener:(R,N)=>p(N,h,[R]),delListener:R=>(g(R),G),clear:()=>(k(S),k(b),J(t)||C(t),t=void 0,e=0,et(),G),clearForward:()=>(pi(b)||(k(b),d(c)),G),destroy:()=>{r.delListener(w),r.delListener(D)},getListenerStats:()=>({checkpointIds:xe(c),checkpoint:xe(h)}),_registerListeners:()=>{w=r.addCellListener(null,null,null,((R,N,tt,Q,O,V)=>{if(a){B();let K=dt(s,N,A),Y=dt(K,tt,A),W=dt(Y,Q,(()=>[V,void 0]));W[1]=O,W[0]===O&&j(F(Y,Q))&&j(F(K,tt))&&j(F(s,N))&&E(),z()}})),D=r.addValueListener(null,((R,N,tt,Q)=>{if(a){B();let O=dt(n,N,(()=>[Q,void 0]));O[1]=tt,O[0]===tt&&j(F(n,N))&&E(),z()}}))}};return Ve(G.clear())}),(r=>r._registerListeners())),Ka=Ha("-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"),bl=A(we(Ka,((r,t)=>[r,t])));var wl=uo.crypto?r=>uo.crypto.getRandomValues(r):r=>we(r,(()=>$a(256*fr.random())));var Ga=JSON.stringify,ho=JSON.parse,Fe=r=>Ga(r,((t,e)=>{return i=Map,e instanceof i?he.fromEntries([...e]):e;var i})),xl=new uo.TextEncoder;var vl=2**36,Sl=2**30,kl=2**24,El=2**18;var bn=(r,t)=>(r??0)<(t??0)?-1:1,Cl=gi((r=>{let t=A(),e=A(),[i,o,s]=mi((()=>C)),[n,a,c,h,p,d,g,,m,y,S,b]=ur(r,A,(k=>J(k)?"":_e(k)?we(k,ct):ct(k)),i,o),v=(k,T,B)=>{let E=p(k);$(B,((w,D)=>T(D,(H=>$(w,(_=>H(_,(M=>r.forEachCell(E,_,M)))))))))},C={setIndexDefinition:(k,T,B,E,w,D=bn)=>{let H=J(w)?void 0:([_],[M])=>w(_,M);return m(k,T,((_,M,z,et,ot,at)=>{let G=0,R=wt(),N=wt(),tt=d(k);if($(M,(([Q,O],V)=>{let K=wt(Q),Y=wt(O);$(K,(W=>Wt(Y,W)?Wt(K,W):0)),$(K,(W=>{ut(R,W),lt(P(tt,W),(X=>{Wt(X,V),j(X)&&(F(tt,W),G=1)}))})),$(Y,(W=>{ut(R,W),pt(tt,W)||(F(tt,W,wt()),G=1),ut(P(tt,W),V),J(E)||ut(N,W)}))})),_(),j(ot)||(at?bt(tt,(Q=>ut(N,Q))):bt(z,(Q=>lt(P(et,Q),(O=>Lt(_e(O)?O:[O],(V=>ut(N,V))))))),$(N,(Q=>{let O=(K,Y)=>D(P(ot,K),P(ot,Y),Q),V=[...P(tt,Q)];Zs(V,O)||(F(tt,Q,wt(yo(V,O))),ut(R,Q))}))),(G||at)&&!J(H)){let Q=[...tt];Zs(Q,H)||(g(k,A(yo(Q,H))),G=1)}G&&o(t,[k]),$(R,(Q=>o(e,[k,Q])))}),pr(B),lt(E,pr)),C},delIndexDefinition:k=>(y(k),C),getStore:n,getIndexIds:a,forEachIndex:k=>c(((T,B)=>k(T,(E=>v(T,E,B))))),forEachSlice:(k,T)=>v(k,T,d(k)),hasIndex:h,hasSlice:(k,T)=>pt(d(k),T),getTableId:p,getSliceIds:k=>be(d(k)),getSliceRowIds:(k,T)=>je(P(d(k),T)),addIndexIdsListener:S,addSliceIdsListener:(k,T)=>i(T,t,[k]),addSliceRowIdsListener:(k,T,B)=>i(B,e,[k,T]),delListener:k=>(s(k),C),destroy:b,getListenerStats:()=>({sliceIds:xe(t),sliceRowIds:Xt(e)})};return Ve(C)}));var sr=r=>[r,r],mt=(r,t=xe)=>t(r[0])+t(r[1]),yt=()=>[A(),A()],on=r=>[...r],nr=([r,t])=>r===t,li=(r,t,e)=>F(r,t,P(r,t)==-e?void 0:e),yi=()=>{let r,t,e=!1,i=!1,o=0,s=[],n=A(),a=A(),c=A(),h=A(),p=A(),d=A(),g=A(),m=A(),y=A(),S=A(),b=A(),v=A(),C=A(),k=A(),T=wt(),B=A(),E=A(),w=A(),D=A(),H=yt(),_=yt(),M=yt(),z=yt(),et=yt(),ot=yt(),at=yt(),G=yt(),R=yt(),N=yt(),tt=yt(),Q=yt(),O=yt(),V=yt(),K=yt(),Y=yt(),W=yt(),X=yt(),U=yt(),nt=yt(),ft=yt(),Dt=yt(),Et=A(),Ct=yt(),[St,rt,Bt,ie]=mi((()=>Pt)),re=l=>{if(!ne(l,((u,x)=>mo([rr,ge],x))))return!1;let f=l[rr];return!(!hn(f)&&f!=nn)&&(Ne(l[ge])!=f&&mn(l,ge),!0)},Qr=_e,$i=(l,f)=>(!r||pt(b,f)||oe(f))&&ne(l,((u,x)=>ue(f,x,u)),(()=>oe(f))),ue=(l,f,u,x)=>ne(x?u:hs(u,l,f),((I,L)=>lt(_i(l,f,L,I),(q=>(u[L]=q,!0)),(()=>!1))),(()=>oe(l,f))),_i=(l,f,u,x)=>r?lt(P(P(b,l),u),(I=>Ne(x)!=I[rr]?oe(l,f,u,x,I[ge]):x),(()=>oe(l,f,u,x))):J(Ne(x))?oe(l,f,u,x):x,ri=(l,f)=>ne(f?l:Ra(l),((u,x)=>lt(ls(x,u),(I=>(l[x]=I,!0)),(()=>!1))),(()=>si())),ls=(l,f)=>t?lt(P(C,l),(u=>Ne(f)!=u[rr]?si(l,f,u[ge]):f),(()=>si(l,f))):J(Ne(f))?si(l,f):f,hs=(l,f,u)=>(lt(P(v,f),(([x,I])=>{$(x,((L,q)=>{hi(l,q)||(l[q]=L)})),$(I,(L=>{hi(l,L)||oe(f,u,L)}))})),l),Ra=l=>(t&&($(k,((f,u)=>{hi(l,u)||(l[u]=f)})),$(T,(f=>{hi(l,f)||si(f)}))),l),ds=l=>ye(b,l,((f,u,x)=>{let I=A(),L=wt();ye(dt(b,u,A),x,((q,Z,it)=>{F(q,Z,it),lt(it[ge],(Kt=>F(I,Z,Kt)),(()=>ut(L,Z)))})),F(v,u,[I,L])}),((f,u)=>{F(b,u),F(v,u)})),ps=l=>ye(C,l,((f,u,x)=>{F(C,u,x),lt(x[ge],(I=>F(k,u,I)),(()=>ut(T,u)))}),((f,u)=>{F(C,u),F(k,u),Wt(T,u)})),fs=l=>Vt(l)?Zi():Qi(l),us=l=>ye(w,l,((f,u,x)=>ji(u,x)),((f,u)=>bs(u))),ji=(l,f)=>ye(dt(w,l,(()=>(Ss(l,1),F(B,l,yn()),F(E,l,A()),A()))),f,((u,x,I)=>oi(l,u,x,I)),((u,x)=>ws(l,u,x))),oi=(l,f,u,x,I)=>ye(dt(f,u,(()=>(ks(l,u,1),A()))),x,((L,q,Z)=>Yr(l,u,L,q,Z)),((L,q)=>xs(l,f,u,L,q,I))),Yr=(l,f,u,x,I)=>{pt(u,x)||Es(l,f,x,1);let L=P(u,x);I!==L&&(Cs(l,f,x,L,I),F(u,x,I))},gs=(l,f,u,x,I)=>lt(P(f,u),(L=>Yr(l,u,L,x,I)),(()=>oi(l,f,u,hs({[x]:I},l,u)))),ms=l=>Vt(l)?tr():Yi(l),ys=l=>ye(D,l,((f,u,x)=>zi(u,x)),((f,u)=>vs(u))),zi=(l,f)=>{pt(D,l)||Ps(l,1);let u=P(D,l);f!==u&&(Is(l,u,f),F(D,l,f))},Vi=l=>P(w,l)??ji(l,{}),bs=l=>ji(l,{}),ws=(l,f,u)=>{let[,x]=P(B,l);x(u),oi(l,f,u,{},!0)},xs=(l,f,u,x,I,L)=>{let q=P(P(v,l)?.[0],I);if(!J(q)&&!L)return Yr(l,u,x,I,q);let Z=it=>{Cs(l,u,it,P(x,it)),Es(l,u,it,-1),F(x,it)};J(q)?Z(I):bt(x,Z),j(x)&&(ks(l,u,-1),j(F(f,u))&&(Ss(l,-1),F(w,l),F(B,l),F(E,l)))},vs=l=>{let f=P(k,l);if(!J(f))return zi(l,f);Is(l,P(D,l)),Ps(l,-1),F(D,l)},Ss=(l,f)=>li(n,l,f),ks=(l,f,u)=>li(dt(h,l,A),f,u)&&F(c,l,dt(c,l,(()=>0))+u),Es=(l,f,u,x)=>{let I=P(E,l),L=P(I,u)??0;(L==0&&x==1||L==1&&x==-1)&&li(dt(a,l,A),u,x),F(I,u,L!=-x?L+x:null),li(dt(dt(p,l,A),f,A),u,x)},Cs=(l,f,u,x,I)=>{dt(dt(dt(d,l,A),f,A),u,(()=>[x,0]))[1]=I,s[3]?.(l,f,u,I)},Ps=(l,f)=>li(g,l,f),Is=(l,f,u)=>{dt(m,l,(()=>[f,0]))[1]=u,s[4]?.(l,u)},oe=(l,f,u,x,I)=>(Tt(dt(dt(dt(y,l,A),f,A),u,(()=>[])),x),I),si=(l,f,u)=>(Tt(dt(S,l,(()=>[])),f),u),Wi=(l,f,u)=>lt(P(P(P(d,l),f),u),(([x,I])=>[!0,x,I]),(()=>[!1,...sr(Ki(l,f,u))])),As=l=>lt(P(m,l),(([f,u])=>[!0,f,u]),(()=>[!1,...sr(Gi(l))])),Ds=l=>j(y)||j(Y[l])?0:$(l?lo(y):y,((f,u)=>$(f,((x,I)=>$(x,((L,q)=>rt(Y[l],[u,I,q],L))))))),Rs=l=>j(S)||j(W[l])?0:$(l?ae(S):S,((f,u)=>rt(W[l],[u],f))),ni=(l,f,u,x)=>{if(!j(l))return rt(f,x,(()=>Rt(l))),bt(l,((I,L)=>rt(u,[...x??[],I],L==1))),1},Ts=l=>{let f=Ji();f!=e&&rt(H[l],void 0,f);let u=j(N[l]),x=j(O[l])&&j(V[l])&&j(R[l])&&j(tt[l])&&j(ot[l])&&j(at[l])&&j(G[l])&&u&&j(M[l])&&j(z[l]),I=j(K[l])&&j(Q[l])&&j(et[l])&&j(_[l]);if(!x||!I){let L=l?[ae(n),xo(a),ae(c),xo(h),lo(p),lo(d)]:[n,a,c,h,p,d];if(!x){ni(L[0],M[l],z[l]),$(L[1],((Z,it)=>ni(Z,ot[l],at[l],[it]))),$(L[2],((Z,it)=>{Z!=0&&rt(G[l],[it],Us(it))}));let q=wt();$(L[3],((Z,it)=>{ni(Z,R[l],tt[l],[it])&&!u&&(rt(N[l],[it,null]),ut(q,it))})),u||$(L[5],((Z,it)=>{if(!pt(q,it)){let Kt=wt();$(Z,(se=>$(se,(([er,ir],ai)=>ir!==er?ut(Kt,ai):Wt(se,ai))))),$(Kt,(se=>rt(N[l],[it,se])))}})),$(L[4],((Z,it)=>$(Z,((Kt,se)=>ni(Kt,O[l],V[l],[it,se])))))}if(!I){let q;$(L[5],((Z,it)=>{let Kt;$(Z,((se,er)=>{let ir;$(se,(([ai,Js],Ta)=>{Js!==ai&&(rt(K[l],[it,er,Ta],Js,ai,Wi),q=Kt=ir=1)})),ir&&rt(Q[l],[it,er],Wi)})),Kt&&rt(et[l],[it],Wi)})),q&&rt(_[l],void 0,Wi)}}},Ls=l=>{let f=Xi();f!=i&&rt(X[l],void 0,f);let u=j(nt[l])&&j(ft[l]),x=j(Dt[l])&&j(U[l]);if(!u||!x){let I=l?[ae(g),ae(m)]:[g,m];if(u||ni(I[0],nt[l],ft[l]),!x){let L;$(I[1],(([q,Z],it)=>{Z!==q&&(rt(Dt[l],[it],Z,q,As),L=1)})),L&&rt(U[l],void 0,As)}}},gt=(l,...f)=>(oo((()=>l(...we(f,ct)))),Pt),Ms=(l,f,u,x,I)=>{let L=qi(l,f,...u);return St((()=>{let q=qi(l,f,...u);pn(q,L)||(L=q,x(Pt,l,f,...u,L))}),N[I?1:0],[l,f],[Ut])},Zr=()=>or(w),Ut=()=>be(w),Bs=l=>be(P(E,ct(l))),Us=l=>ze(P(w,ct(l))),Ue=l=>be(P(w,ct(l))),qi=(l,f,u,x=0,I)=>{return dr(l)?qi(l.tableId,l.cellId,l.descending,l.offset,l.limit):we(go(yo((L=P(w,ct(l)),q=(Z,it)=>[J(f)?it:P(Z,ct(f)),it],we([...L?.entries()??[]],(([Z,it])=>q(it,Z)))),(([Z],[it])=>bn(Z,it)*(u?-1:1))),x,J(I)?I:x+I),(([,Z])=>Z));var L,q},to=(l,f)=>be(P(P(w,ct(l)),ct(f))),Ki=(l,f,u)=>P(P(P(w,ct(l)),ct(f)),ct(u)),eo=()=>Rt(D),io=()=>be(D),Gi=l=>P(D,ct(l)),Ji=()=>!j(w),Os=l=>pt(w,ct(l)),Fs=(l,f)=>pt(P(E,ct(l)),ct(f)),Ns=(l,f)=>pt(P(w,ct(l)),ct(f)),Hs=(l,f,u)=>pt(P(P(w,ct(l)),ct(f)),ct(u)),Xi=()=>!j(D),$s=l=>pt(D,ct(l)),Qi=l=>gt((()=>(f=>ne(f,$i,oe))(l)?us(l):0)),Yi=l=>gt((()=>ri(l)?ys(l):0)),_s=l=>(ao((()=>fs(ho(l)))),Pt),js=l=>gt((()=>{if((r=ne(l,(f=>ne(f,re))))&&(ds(l),!j(w))){let f=Zr();Zi(),Qi(f)}})),zs=l=>gt((()=>{if(t=(f=>ne(f,re))(l)){let f=eo();ro(),tr(),t=!0,ps(l),Yi(f)}})),Zi=()=>gt((()=>us({}))),Vs=l=>gt((f=>pt(w,f)?bs(f):0),l),Ws=(l,f)=>gt(((u,x)=>lt(P(w,u),(I=>pt(I,x)?ws(u,I,x):0))),l,f),tr=()=>gt((()=>ys({}))),qs=()=>gt((()=>{ds({}),r=!1})),ro=()=>gt((()=>{ps({}),t=!1})),oo=(l,f)=>{if(o!=-1){Ks();let u=l();return Gs(f),u}},Ks=()=>(o!=-1&&o++,o==1&&(s[0]?.(),rt(Et)),Pt),Gs=l=>(o>0&&(o--,o==0&&(o=1,Ds(1),j(d)||Ts(1),Rs(1),j(m)||Ls(1),l?.(Pt)&&($(d,((f,u)=>$(f,((x,I)=>$(x,(([L],q)=>hr(Pt,u,I,q,L))))))),He(d),$(m,(([f],u)=>bo(Pt,u,f))),He(m)),rt(Ct[0],void 0),o=-1,Ds(0),j(d)||Ts(0),Rs(0),j(m)||Ls(0),s[1]?.(),rt(Ct[1],void 0),s[2]?.(),o=0,e=Ji(),i=Xi(),Lt([n,a,c,h,p,d,y,g,m,S],He))),Pt),Pt={getContent:()=>[Zr(),eo()],getTables:Zr,getTableIds:Ut,getTable:l=>wo(P(w,ct(l))),getTableCellIds:Bs,getRowCount:Us,getRowIds:Ue,getSortedRowIds:qi,getRow:(l,f)=>Rt(P(P(w,ct(l)),ct(f))),getCellIds:to,getCell:Ki,getValues:eo,getValueIds:io,getValue:Gi,hasTables:Ji,hasTable:Os,hasTableCell:Fs,hasRow:Ns,hasCell:Hs,hasValues:Xi,hasValue:$s,getTablesJson:()=>Fe(w),getValuesJson:()=>Fe(D),getJson:()=>Fe([w,D]),getTablesSchemaJson:()=>Fe(b),getValuesSchemaJson:()=>Fe(C),getSchemaJson:()=>Fe([b,C]),hasTablesSchema:()=>r,hasValuesSchema:()=>t,setContent:l=>gt((()=>{let f=zt(l)?l():l;Qr(f)&&(([u,x])=>{(Vt(u)?Zi:Qi)(u),(Vt(x)?tr:Yi)(x)})(f)})),setTables:Qi,setTable:(l,f)=>gt((u=>$i(f,u)?ji(u,f):0),l),setRow:(l,f,u)=>gt(((x,I)=>ue(x,I,u)?oi(x,Vi(x),I,u):0),l,f),addRow:(l,f,u=!0)=>oo((()=>{let x;return ue(l,x,f)&&(l=ct(l),oi(l,Vi(l),x=((I,L)=>{let[q]=P(B,I),Z;do Z=q(L);while(pt(P(w,I),Z));return Z})(l,u?1:0),f)),x})),setPartialRow:(l,f,u)=>gt(((x,I)=>{if(ue(x,I,u,1)){let L=Vi(x);Jt(u,((q,Z)=>gs(x,L,I,Z,q)))}}),l,f),setCell:(l,f,u,x)=>gt(((I,L,q)=>lt(_i(I,L,q,zt(x)?x(Ki(I,L,q)):x),(Z=>gs(I,Vi(I),L,q,Z)))),l,f,u),setValues:Yi,setPartialValues:l=>gt((()=>ri(l,1)?Jt(l,((f,u)=>zi(u,f))):0)),setValue:(l,f)=>gt((u=>lt(ls(u,zt(f)?f(Gi(u)):f),(x=>zi(u,x)))),l),applyChanges:l=>gt((()=>{Jt(l[0],((f,u)=>J(f)?Vs(u):Jt(f,((x,I)=>J(x)?Ws(u,I):Jt(x,((L,q)=>hr(Pt,u,I,q,L))))))),Jt(l[1],((f,u)=>bo(Pt,u,f)))})),setTablesJson:_s,setValuesJson:l=>(ao((()=>ms(ho(l)))),Pt),setJson:l=>gt((()=>ao((()=>{let[f,u]=ho(l);fs(f),ms(u)}),(()=>_s(l))))),setTablesSchema:js,setValuesSchema:zs,setSchema:(l,f)=>gt((()=>{js(l),zs(f)})),delTables:Zi,delTable:Vs,delRow:Ws,delCell:(l,f,u,x)=>gt(((I,L,q)=>lt(P(w,I),(Z=>lt(P(Z,L),(it=>pt(it,q)?xs(I,Z,L,it,q,x):0))))),l,f,u),delValues:tr,delValue:l=>gt((f=>pt(D,f)?vs(f):0),l),delTablesSchema:qs,delValuesSchema:ro,delSchema:()=>gt((()=>{qs(),ro()})),transaction:oo,startTransaction:Ks,getTransactionChanges:()=>[Rt(d,((l,f)=>P(n,f)===-1?void 0:Rt(l,((u,x)=>P(P(h,f),x)===-1?void 0:Rt(u,(([,I])=>I),(I=>nr(I)))),j,Vt)),j,Vt),Rt(m,(([,l])=>l),(l=>nr(l))),1],getTransactionLog:()=>[!j(d),!j(m),or(d,on,nr),or(y),Rt(m,on,nr),Rt(S),Rt(n),wo(h),or(p),Rt(g)],finishTransaction:Gs,forEachTable:l=>$(w,((f,u)=>l(u,(x=>$(f,((I,L)=>x(L,(q=>bt(I,q))))))))),forEachTableCell:(l,f)=>bt(P(E,ct(l)),f),forEachRow:(l,f)=>$(P(w,ct(l)),((u,x)=>f(x,(I=>bt(u,I))))),forEachCell:(l,f,u)=>bt(P(P(w,ct(l)),ct(f)),u),forEachValue:l=>bt(D,l),addSortedRowIdsListener:(l,f,u,x,I,L,q)=>dr(l)?Ms(l.tableId,l.cellId,[l.descending??!1,l.offset??0,l.limit],f,u):Ms(l,f,[u,x,I],L,q),addStartTransactionListener:l=>St(l,Et),addWillFinishTransactionListener:l=>St(l,Ct[0]),addDidFinishTransactionListener:l=>St(l,Ct[1]),callListener:l=>(ie(l),Pt),delListener:l=>(Bt(l),Pt),getListenerStats:()=>({hasTables:mt(H),tables:mt(_),tableIds:mt(M),hasTable:mt(z),table:mt(et),tableCellIds:mt(ot),hasTableCell:mt(at,Xt),rowCount:mt(G),rowIds:mt(R),sortedRowIds:mt(N),hasRow:mt(tt,Xt),row:mt(Q,Xt),cellIds:mt(O,Xt),hasCell:mt(V,co),cell:mt(K,co),invalidCell:mt(Y,co),hasValues:mt(X),values:mt(U),valueIds:mt(nt),hasValue:mt(ft),value:mt(Dt),invalidValue:mt(W),transaction:xe(Et)+mt(Ct)}),isMergeable:()=>!1,createStore:yi,addListener:St,callListeners:rt,setInternalListeners:(l,f,u,x,I)=>s=[l,f,u,x,I]};return Jt({[me+Qs]:[0,H,[],()=>[Ji()]],[Qs]:[0,_],[Oa]:[0,M],[me+ce]:[1,z,[Ut],l=>[Os(...l)]],[ce]:[1,et,[Ut]],[ce+ar]:[1,ot,[Ut]],[me+ce+di]:[2,at,[Ut,Bs],l=>[Fs(...l)]],[an]:[1,G,[Ut]],[cn]:[1,R,[Ut]],[me+$e]:[2,tt,[Ut,Ue],l=>[Ns(...l)]],[$e]:[2,Q,[Ut,Ue]],[ar]:[2,O,[Ut,Ue]],[me+di]:[3,V,[Ut,Ue,to],l=>[Hs(...l)]],[di]:[3,K,[Ut,Ue,to],l=>sr(Ki(...l))],InvalidCell:[3,Y],[me+Ys]:[0,X,[],()=>[Xi()]],[Ys]:[0,U],[Na]:[0,nt],[me+cr]:[1,ft,[io],l=>[$s(...l)]],[cr]:[1,Dt,[io],l=>sr(Gi(l[0]))],InvalidValue:[1,W]},(([l,f,u,x],I)=>{Pt[fo+I+po]=(...L)=>St(L[l],f[L[l+1]?1:0],l>0?go(L,0,l):void 0,u,x)})),Ve(Pt)};var vo=A([["avg",[(r,t)=>tn(r)/t,(r,t,e)=>r+(t-r)/(e+1),(r,t,e)=>r+(r-t)/(e-1),(r,t,e,i)=>r+(t-e)/i]],["max",[r=>so(...r),(r,t)=>so(t,r),(r,t)=>t==r?void 0:r,(r,t,e)=>e==r?void 0:so(t,r)]],["min",[r=>no(...r),(r,t)=>no(t,r),(r,t)=>t==r?void 0:r,(r,t,e)=>e==r?void 0:no(t,r)]],["sum",[r=>tn(r),(r,t)=>r+t,(r,t)=>r-t,(r,t,e)=>r-e+t]]]),wn=(r,t,e,i,o,s=!1)=>{if(j(e))return;let[n,a,c,h]=o;return s||=J(r),$(i,(([p,d])=>{s||(r=J(p)?a?.(r,d,t++):J(d)?c?.(r,p,t--):h?.(r,d,p,t),s||=J(r))})),s?n(je(e),ze(e)):r},Pl=gi((r=>{let t=A(),[e,i,o]=mi((()=>b)),[s,n,a,c,h,p,d,,g,m,y,S]=ur(r,dn,(v=>isNaN(v)||J(v)||v===!0||v===!1||v===""?void 0:1*v),e,i),b={setMetricDefinition:(v,C,k,T,B,E,w)=>{let D=zt(k)?[k,B,E,w]:P(vo,k)??P(vo,"sum");return g(v,C,((H,_,M,z,et,ot)=>{let at=p(v),G=ze(z);ot||=J(at),H();let R=wn(at,G,z,_,D,ot);ln(R)||(R=void 0),R!=at&&(d(v,R),i(t,[v],R,at))}),pr(T,1)),b},delMetricDefinition:v=>(m(v),b),getStore:s,getMetricIds:n,forEachMetric:a,hasMetric:c,getTableId:h,getMetric:p,addMetricIdsListener:y,addMetricListener:(v,C)=>e(C,t,[v]),delListener:v=>(o(v),b),destroy:S,getListenerStats:()=>({metric:xe(t)})};return Ve(b)})),Il=gi((r=>{let t=r.createStore,e=t(),i=t(),o=A(),{addListener:s,callListeners:n,delListener:a}=i,[c,h,p,d,g,,,m,,y,S,b,v,C]=ur(r,(()=>!0),dn,s,n),k=(w,D,...H)=>Lt(H,(_=>ut(dt(dt(o,D,A),w,wt),_))),T=w=>{lt(P(o,w),(D=>{bt(D,((H,_)=>$(_,(M=>H.delListener(M))))),He(D)})),Lt([i,e],(D=>D.delTable(w)))},B=(w,D,H)=>k(D,w,D.addStartTransactionListener(H.startTransaction),D.addDidFinishTransactionListener((()=>H.finishTransaction()))),E={setQueryDefinition:(w,D,H)=>{m(w,D),T(w);let _=[],M=[[null,[D,null,null,[],A()]]],z=[],et=[],ot=[];H({select:(O,V)=>{let K=zt(O)?[Ot(_)+"",O]:[J(V)?O:V,Y=>Y(O,V)];return Tt(_,K),{as:Y=>K[0]=Y}},join:(O,V,K)=>{let Y=J(K)||zt(V)?null:V,W=J(Y)?V:K,X=[O,[O,Y,zt(W)?W:U=>U(W),[],A()]];return Tt(M,X),{as:U=>X[0]=U}},where:(O,V,K)=>Tt(z,zt(O)?O:J(K)?Y=>Y(O)===V:Y=>Y(O,V)===K),group:(O,V,K,Y,W)=>{let X=[O,[O,zt(V)?[V,K,Y,W]:P(vo,V)??[(U,nt)=>nt]]];return Tt(et,X),{as:U=>X[0]=U}},having:(O,V)=>Tt(ot,zt(O)?O:K=>K(O)===V)});let at=A(_);if(j(at))return E;let G=A(M);bt(G,((O,[,V])=>lt(P(G,V),(({3:K})=>J(O)?0:Tt(K,O)))));let R=A(et),N=e;if(j(R)&&pi(ot))N=i;else{B(w,N,i);let O=A();bt(R,((W,[X,U])=>ut(dt(O,X,wt),[W,U])));let V=wt();bt(at,(W=>pt(O,W)?0:ut(V,W)));let K=A(),Y=(W,X,U,nt)=>lt(W,(([ft,Dt,Et,Ct])=>{bt(X,((St,[rt])=>{let Bt=dt(ft,St,A),ie=P(Bt,U),re=nt?void 0:rt;if(ie!==re){let Qr=wt([[ie,re]]),$i=ze(Bt);F(Bt,U,re),$(P(O,St),(([ue,_i])=>{let ri=wn(Ct[ue],$i,Bt,Qr,_i);Ct[ue]=J(Ne(ri))?null:ri}))}})),j(Dt)||!lr(ot,(St=>St((rt=>Ct[rt]))))?i.delRow(w,Et):J(Et)?W[2]=i.addRow(w,Ct):i.setRow(w,Et,Ct)}));k(N,w,N.addRowListener(w,null,((W,X,U,nt)=>{let ft=[],Dt=[],Et=A(),Ct=N.hasRow(w,U),St=!Ct;$(V,(rt=>{let[Bt,ie,re]=nt(w,U,rt);Tt(ft,ie),Tt(Dt,re),St||=Bt})),bt(O,(rt=>{let[Bt,,ie]=nt(w,U,rt);(St||Bt)&&F(Et,rt,[ie])})),St&&Y(fi(K,ft,void 0,(([,rt])=>(Wt(rt,U),j(rt)))),Et,U,1),Ct&&Y(fi(K,Dt,(()=>{let rt={};return $(V,(Bt=>rt[Bt]=N.getCell(w,U,Bt))),[A(),wt(),void 0,rt]}),(([,rt])=>{ut(rt,U)})),Et,U)})))}B(w,r,N);let tt=(O,V,K,Y)=>{let W=X=>r.getCell(V,K,X);Lt(Y,(X=>{let[U,,nt,ft,Dt]=P(G,X),Et=nt?.(W,O),[Ct,St]=P(Dt,O)??[];Et!=Ct&&(J(St)||C(w,St),F(Dt,O,J(Et)?null:[Et,...v(w,1,r.addRowListener(U,Et,(()=>tt(O,U,Et,ft))))]))})),(X=>{let U=(nt,ft)=>r.getCell(...J(ft)?[D,X,nt]:nt===D?[D,X,ft]:[P(G,nt)?.[0],P(P(G,nt)?.[4],X)?.[0],ft]);N.transaction((()=>lr(z,(nt=>nt(U)))?bt(at,((nt,ft)=>hr(N,w,X,nt,ft(U,X)))):N.delRow(w,X)))})(O)},{3:Q}=P(G,null);return N.transaction((()=>v(w,1,r.addRowListener(D,null,((O,V,K)=>{r.hasRow(D,K)?tt(K,D,K,Q):(N.delRow(w,K),$(G,(({4:Y})=>lt(P(Y,K),(([,W])=>{C(w,W),F(Y,K)})))))}))))),E},delQueryDefinition:w=>(T(w),y(w),E),getStore:c,getQueryIds:h,forEachQuery:p,hasQuery:d,getTableId:g,addQueryIdsListener:w=>S((()=>w(E))),delListener:w=>(a(w),E),destroy:b,getListenerStats:()=>{let{tables:w,tableIds:D,transaction:H,..._}=i.getListenerStats();return _}};return Jt({[ce]:[1,1],[ce+ar]:[0,1],[an]:[0,1],[cn]:[0,1],[Fa]:[0,5],[$e]:[1,2],[ar]:[0,2],[di]:[1,3]},(([w,D],H)=>{Lt(w?["get","has","forEach"]:["get"],(_=>E[_+Xs+H]=(...M)=>i[_+H](...M))),E[fo+Xs+H+po]=(..._)=>i[fo+H+po](...go(_,0,D),((M,...z)=>_[D](E,...z)),!0)})),Ve(E)})),Al=gi((r=>{let t=A(),e=A(),i=A(),o=A(),[s,n,a]=mi((()=>B)),[c,h,p,d,g,m,,,y,S,b,v]=ur(r,(()=>[A(),A(),A(),A()]),(E=>J(E)?void 0:E+""),s,n),C=(E,w,D)=>lt(m(E),(([H,,_])=>{if(!pt(_,w)){let M=wt();if(g(E)!=T(E))ut(M,w);else{let z=w;for(;!J(z)&&!pt(M,z);)ut(M,z),z=P(H,z)}if(D)return M;F(_,w,M)}return P(_,w)})),k=(E,w)=>lt(m(E),(([,,D])=>F(D,w))),T=E=>P(t,E),B={setRelationshipDefinition:(E,w,D,H)=>(F(t,E,D),y(E,w,((_,M)=>{let z=wt(),et=wt(),ot=wt(),[at,G]=m(E);$(M,(([R,N],tt)=>{J(R)||(ut(et,R),lt(P(G,R),(Q=>{Wt(Q,tt),j(Q)&&F(G,R)}))),J(N)||(ut(et,N),pt(G,N)||F(G,N,wt()),ut(P(G,N),tt)),ut(z,tt),F(at,tt,N),bt(P(o,E),(Q=>{pt(C(E,Q),tt)&&ut(ot,Q)}))})),_(),$(z,(R=>n(e,[E,R]))),$(et,(R=>n(i,[E,R]))),$(ot,(R=>{k(E,R),n(o,[E,R])}))}),pr(H)),B),delRelationshipDefinition:E=>(F(t,E),S(E),B),getStore:c,getRelationshipIds:h,forEachRelationship:E=>p((w=>E(w,(D=>r.forEachRow(g(w),D))))),hasRelationship:d,getLocalTableId:g,getRemoteTableId:T,getRemoteRowId:(E,w)=>P(m(E)?.[0],w),getLocalRowIds:(E,w)=>je(P(m(E)?.[1],w)),getLinkedRowIds:(E,w)=>J(m(E))?[w]:je(C(E,w,!0)),addRelationshipIdsListener:b,addRemoteRowIdListener:(E,w,D)=>s(D,e,[E,w]),addLocalRowIdsListener:(E,w,D)=>s(D,i,[E,w]),addLinkedRowIdsListener:(E,w,D)=>(C(E,w),s(D,o,[E,w])),delListener:E=>(k(...a(E)??[]),B),destroy:v,getListenerStats:()=>({remoteRowId:Xt(e),localRowIds:Xt(i),linkedRowIds:Xt(o)})};return Ve(B)}));var Sn=Promise,Ja=globalThis,xn=Ja.window,Xa=1e3,Qa=(r,t,e)=>setInterval(r,t*Xa),Ya=clearInterval,qt=r=>r==null,wr=(r,t,e)=>qt(r)?e?.():t(r),Eo=r=>Array.isArray(r),Se=r=>r.length,Za=(r,t)=>r.test(t),kn=r=>new Sn(r),En=async r=>Sn.all(r),Cn=r=>{throw new Error(r)},ve=async(r,t,e)=>{try{return await r()}catch(i){t?.(i)}},Co=(r,t)=>r.forEach(t),bi=(r,t)=>r.map(t),tc=(r,t)=>r.splice(0,t),xr=(r,...t)=>r.push(...t),Pn=r=>r.shift(),We=Object,vn=r=>We.getPrototypeOf(r),ec=We.entries,ic=r=>!qt(r)&&wr(vn(r),t=>t==We.prototype||qt(vn(t)),()=>!0),rc=We.keys,oc=We.freeze,sc=(r=[])=>We.fromEntries(r),nc=(r,t)=>t in r,ac=(r,t)=>bi(ec(r),([e,i])=>t(i,e)),cc=r=>Se(rc(r)),gr=r=>ic(r)&&cc(r)==0,lc=r=>r?.size??0,hc=(r,t)=>r?.has(t)??!1,In=r=>qt(r)||lc(r)==0,An=(r,t)=>r?.forEach(t),Dn=(r,t)=>r?.delete(t),wi=r=>new Map(r),Ht=(r,t)=>r?.get(t),ke=(r,t,e)=>qt(e)?(Dn(r,t),r):r?.set(t,e),Po=(r,t,e,i)=>(hc(r,t)?i?.(Ht(r,t)):ke(r,t,e()),Ht(r,t)),Io=(r,t,e,i,o=0)=>wr((e?Po:Ht)(r,t[o],o>Se(t)-2?e:wi),s=>{if(o>Se(t)-2)return i?.(s)&&ke(r,t[o]),s;let n=Io(s,t,e,i,o+1);return In(s)&&ke(r,t[o]),n}),dc=/^\d+$/,pc=()=>{let r=[],t=0;return[e=>(e?Pn(r):null)??""+t++,e=>{Za(dc,e)&&Se(r)<1e3&&xr(r,e)}]},fc=r=>new Set(Eo(r)||qt(r)?r:[r]),uc=(r,t)=>r?.add(t),gc=(r,t=[""])=>{let e=[],i=(o,s)=>s==Se(t)?xr(e,o):t[s]===null?An(o,n=>i(n,s+1)):Co([t[s],null],n=>i(Ht(o,n),s+1));return i(r,0),e},mc=r=>{let t,[e,i]=pc(),o=wi();return[(s,n,a,c=[],h=()=>[])=>{t??=r();let p=e(1);return ke(o,p,[s,n,a,c,h]),uc(Io(n,a??[""],fc),p),p},(s,n,...a)=>Co(gc(s,n),c=>An(c,h=>Ht(o,h)[0](t,...n??[],...a))),s=>wr(Ht(o,s),([,n,a])=>(Io(n,a??[""],void 0,c=>(Dn(c,s),In(c)?1:0)),ke(o,s),i(s),a)),s=>wr(Ht(o,s),([n,,a=[],c,h])=>{let p=(...d)=>{let g=Se(d);g==Se(a)?n(t,...d,...h(d)):qt(a[g])?Co(c[g]?.(...d)??[],m=>p(...d,m)):p(...d,a[g])};p()})]},mr=wi(),yr=wi(),yc=(r=1,t,e)=>r!=1&&t.isMergeable()?[1,t.getMergeableContent,()=>t.getTransactionMergeableChanges(!e),([[i],[o]])=>!gr(i)||!gr(o),t.setDefaultContent]:r!=2?[0,t.getContent,t.getTransactionChanges,([i,o])=>!gr(i)||!gr(o),t.setContent]:Cn("Store type not supported by this Persister"),bc=(r,t,e,i,o,s,n,a={},c=0,h=[])=>{let p=0,d=0,g=0,m,y,S;Po(mr,h,()=>0),Po(yr,h,()=>[]);let b=wi(),[v,C,k,T,B]=yc(n,r,c),[E,w,D]=mc(()=>X),H=U=>{U!=p&&(p=U,w(b,void 0,p))},_=async()=>{if(!Ht(mr,h)){for(ke(mr,h,1);!qt(m=Pn(Ht(yr,h)));)await ve(m,s);ke(mr,h,0)}},M=U=>{(v&&Eo(U?.[0])?U?.[2]===1?r.applyMergeableChanges:r.setMergeableContent:U?.[2]===1?r.applyChanges:r.setContent)(U)},z=async U=>(p!=2&&(H(1),d++,await W(async()=>{await ve(async()=>{let nt=await t();Eo(nt)?M(nt):U?B(U):Cn(`Content is not an array: ${nt}`)},()=>{U&&B(U)}),H(0)})),X),et=async U=>(ot(),await z(U),await ve(async()=>y=await i(async(nt,ft)=>{ft||nt?p!=2&&(H(1),d++,M(ft??nt),H(0)):await z()}),s),X),ot=async()=>(y&&(await ve(()=>o(y),s),y=void 0),X),at=()=>!qt(y),G=async U=>(p!=1&&(H(2),g++,await W(async()=>{await ve(()=>e(C,U),s),H(0)})),X),R=async()=>(N(),await G(),S=r.addDidFinishTransactionListener(()=>{let U=k();T(U)&&G(U)}),X),N=async()=>(S&&(r.delListener(S),S=void 0),X),tt=()=>!qt(S),Q=async(U,nt=!1)=>{let[ft,Dt]=nt?[R,et]:[et,R];return await ft(U),await Dt(U),X},O=async(U=!1)=>{let[nt,ft]=U?[N,ot]:[ot,N];return await nt(),await ft(),X},V=()=>p,K=U=>E(U,b),Y=U=>(D(U),r),W=async(...U)=>(xr(Ht(yr,h),...U),await _(),X),X={load:z,startAutoLoad:et,stopAutoLoad:ot,isAutoLoading:at,save:G,startAutoSave:R,stopAutoSave:N,isAutoSaving:tt,startAutoPersisting:Q,stopAutoPersisting:O,getStatus:V,addStatusListener:K,delListener:Y,schedule:W,getStore:()=>r,destroy:()=>(tc(Ht(yr,h)),O()),getStats:()=>({loads:d,saves:g}),...a};return oc(X)},ko=["t","v"],wc={keyPath:"k"},xc=async(r,t)=>{let e=ac(t,(i,o)=>br(r,"put",{k:o,v:i}));bi(await br(r,"getAllKeys"),i=>nc(t,i)?0:xr(e,br(r,"delete",i))),await En(e)},br=async(r,t,e)=>kn((i,o)=>{let s=r[t](e);s.onsuccess=()=>i(s.result),s.onerror=()=>o(`objectStore.${t} error`)}),Rn=(r,t,e=1,i)=>{let o=async(s,n=[],a=0)=>kn((c,h)=>{let p=(xn?xn.indexedDB:indexedDB).open(t,a?2:void 0);p.onupgradeneeded=()=>a&&bi(ko,d=>ve(()=>p.result.createObjectStore(d,wc))),p.onsuccess=()=>ve(async()=>{let d=p.result.transaction(ko,"readwrite"),g=await En(bi(ko,(m,y)=>s(d.objectStore(m),n[y])));p.result.close(),c(g)},d=>{p.result.close(),h(d)}),p.onerror=()=>h("indexedDB.open error")});return bc(r,async()=>await o(async s=>sc(bi(await br(s,"getAll"),({k:n,v:a})=>[n,a]))),s=>o((n,a)=>xc(n,a),s(),1),s=>Qa(s,e),s=>Ya(s),i,1,{getDbName:()=>t})};var vr=class{#t;#r="blobs";#n=null;constructor(t="copio-blobs"){this.#t=t}async#s(){return this.#n?this.#n:(this.#n=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 o=i.result;o.objectStoreNames.contains(this.#r)||o.createObjectStore(this.#r)},i.onsuccess=()=>t(i.result),i.onerror=()=>e(i.error||new Error("Failed to open blob db"))}),this.#n)}async put(t,e){let i=await this.#s();return new Promise((o,s)=>{let c=i.transaction(this.#r,"readwrite").objectStore(this.#r).put(e,t);c.onsuccess=()=>o(),c.onerror=()=>s(c.error)})}async get(t){let e=await this.#s();return new Promise((i,o)=>{let a=e.transaction(this.#r,"readonly").objectStore(this.#r).get(t);a.onsuccess=()=>i(a.result||null),a.onerror=()=>o(a.error)})}async delete(t){let e=await this.#s();return new Promise((i,o)=>{let a=e.transaction(this.#r,"readwrite").objectStore(this.#r).delete(t);a.onsuccess=()=>i(),a.onerror=()=>o(a.error)})}async deleteByPrefix(t){let e=await this.#s();return new Promise((i,o)=>{let n=e.transaction(this.#r,"readwrite").objectStore(this.#r),a=n.openKeyCursor();a.onsuccess=c=>{let h=c.target.result;h?(typeof h.key=="string"&&h.key.startsWith(t)&&n.delete(h.key),h.continue()):i()},a.onerror=()=>o(a.error)})}async sweepOrphans(t){let e=new Set(t),i=await this.#s(),o=0;return new Promise((s,n)=>{let c=i.transaction(this.#r,"readwrite").objectStore(this.#r),h=c.openKeyCursor();h.onsuccess=p=>{let d=p.target.result;if(d){if(typeof d.key=="string"){let g=d.key.split(":")[0];e.has(g)||(c.delete(d.key),o++)}d.continue()}else s(o)},h.onerror=()=>n(h.error)})}async close(){if(this.#n){try{(await this.#n).close()}catch{}this.#n=null}}};function Ee(r,t="image/jpeg"){if(r instanceof Blob)return r;if(typeof r!="string"||!r.startsWith("data:"))return null;let e=r.match(/^data:([^;]+);base64,(.*)$/),i=e?e[1]:t,o=e?e[2]:r.split(",")[1],s=atob(o),n=new Uint8Array(s.length);for(let a=0;a<s.length;a++)n[a]=s.charCodeAt(a);return new Blob([n],{type:i})}async function Ao(r){return new Promise((t,e)=>{let i=new FileReader;i.onloadend=()=>t(i.result),i.onerror=e,i.readAsDataURL(r)})}var de=class extends Gt{#t=null;#r=null;#n=null;#s="copio-db";#e=new Set;#i=new Map;#a=new Map;#l=new Map;#o=new Map;#p=null;constructor(t={}){super(),this.#s=t.dbName||"copio-db",this.#t=t.store||yi(),this.#t.hasTable("docs")||this.#t.setTable("docs",{}),this.#r=t.persister||Rn(this.#t,this.#s),this.#n=new vr(`${this.#s}-blobs`)}get store(){return this.#t}get persister(){return this.#r}get blobStore(){return this.#n}#h(t,e){return typeof e=="string"&&e.startsWith("blob:")&&(this.#e.add(e),this.#i.has(t)||this.#i.set(t,[]),this.#i.get(t).push(e)),e}revokeDocUrls(t){let e=this.#i.get(t);if(e){for(let i of e){try{URL.revokeObjectURL(i)}catch{}this.#e.delete(i)}this.#i.delete(t)}for(let[i,o]of this.#a.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(o)}catch{}this.#a.delete(i)}for(let[i,o]of this.#l.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(o)}catch{}this.#l.delete(i)}this.#o.delete(t)}revokeAllUrls(){for(let t of this.#e)try{URL.revokeObjectURL(t)}catch{}this.#e.clear(),this.#i.clear(),this.#a.clear(),this.#l.clear(),this.#o.clear()}async init(){return this.#p?this.#p:(this.#p=(async()=>{await this.#r.load(),typeof this.#r.startAutoLoad=="function"&&this.#r.startAutoLoad(),typeof this.#r.startAutoSave=="function"&&this.#r.startAutoSave(),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.#p)}async sweepOrphans(){let t=Object.keys(this.#t.getTable("docs")||{});return this.#n.sweepOrphans(t)}listDocsSync(){let t=this.#t.getTable("docs");return Object.entries(t||{}).map(([e,i])=>({id:e,name:i.name||"",pages:this.#d(i.pages)}))}async listDocs(){return this.listDocsSync()}getDocSync(t){if(this.#o.has(t))return this.#o.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.#d(e.pages)}}async getDoc(t){if(!this.#t.hasRow("docs",t))return null;let e=this.#t.getRow("docs",t),i=this.#d(e.pages),o=await Promise.all(i.map(async n=>{if(!n)return n;let a={...n},c=`${t}:${n.id}`,h=await this.#n.get(`${t}:${n.id}`);h&&(a.blob=h,this.#a.has(c)?a.src=this.#a.get(c):(a.src=this.#h(t,URL.createObjectURL(h)),this.#a.set(c,a.src)));let p=`${t}:${n.id}:orig`,d=await this.#n.get(`${t}:${n.id}:original`);return d?(a.originalBlob=d,this.#l.has(p)?a.originalSrc=this.#l.get(p):(a.originalSrc=this.#h(t,URL.createObjectURL(d)),this.#l.set(p,a.originalSrc))):a.blob&&(a.originalBlob=a.blob,a.originalSrc=a.src),a})),s={id:t,name:e.name||"",pages:o};return this.#o.set(t,s),s}async saveDoc(t,e){if(!t)throw new Error("Cannot save document without an ID");let i=Array.isArray(e.pages)?e.pages:this.#d(e.pages),o=[],s=[],n=[];for(let a of i){if(!a)continue;let c=Ee(a.src)||(a.src instanceof Blob?a.src:null)||(a.blob instanceof Blob?a.blob:null),h=c?.type||"image/jpeg",p={id:a.id,name:a.name||"",type:a.type||"image",hasBlob:!0,mimeType:h,edits:a.edits,exif:a.exif,content:a.content,ocrText:a.ocrText??null,ocrConfidence:a.ocrConfidence??null,ocrWords:Array.isArray(a.ocrWords)?a.ocrWords:null,ocrWidth:a.ocrWidth??null,ocrHeight:a.ocrHeight??null};o.push(p);let d=`${t}:${a.id}`,g=`${t}:${a.id}:orig`,m={...a},y=this.#a.get(d),S=typeof a.src=="string"&&a.src.startsWith("data:")||a.src instanceof Blob||a.src&&y&&a.src!==y;if(c)if(m.blob=c,S||!y){if(y){try{URL.revokeObjectURL(y)}catch{}this.#e.delete(y)}let T=this.#h(t,URL.createObjectURL(c));this.#a.set(d,T),m.src=T}else m.src=y;let b=Ee(a.originalSrc)||(a.originalSrc instanceof Blob?a.originalSrc:null)||(a.originalBlob instanceof Blob?a.originalBlob:null),v=this.#l.get(g),C=!v&&!b&&(!a.originalSrc||a.originalSrc===a.src);C&&c&&(b=c);let k=typeof a.originalSrc=="string"&&a.originalSrc.startsWith("data:")||a.originalSrc instanceof Blob||C&&!!b;if(b)if(m.originalBlob=b,k||!v){if(v&&k){try{URL.revokeObjectURL(v)}catch{}this.#e.delete(v)}let T=this.#h(t,URL.createObjectURL(b));this.#l.set(g,T),m.originalSrc=T}else m.originalSrc=v;else v?m.originalSrc=v:a.originalSrc?m.originalSrc=a.originalSrc:(m.originalSrc=m.src,m.blob&&(m.originalBlob=m.blob));s.push(m),n.push({pageId:a.id,page:a,srcBlob:c,origBlob:b})}this.#t.setRow("docs",t,{name:e.name||"",pages:JSON.stringify(o)}),this.#o.set(t,{id:t,name:e.name||"",pages:s});for(let a of n){let{pageId:c,page:h,srcBlob:p,origBlob:d}=a;if(!p&&typeof h.src=="string"&&h.src.startsWith("blob:"))try{p=await(await fetch(h.src)).blob()}catch{}if(p&&await this.#n.put(`${t}:${c}`,p),!d&&typeof h.originalSrc=="string"&&h.originalSrc.startsWith("blob:"))try{d=await(await fetch(h.originalSrc)).blob()}catch{}d&&await this.#n.put(`${t}:${c}:original`,d)}}async deleteDoc(t){this.#t.delRow("docs",t),await this.#n.deleteByPrefix(`${t}:`),this.revokeDocUrls(t),this.#o.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.#o.has(t)&&(this.#o.get(t).name=e)}async savePage(t,e,i){let o=await this.getDoc(t);if(!o)throw new Error(`Document ${t} not found`);let s=o.pages.findIndex(c=>c.id===e),n;if(s>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?o.pages[s]={...o.pages[s],...i}:o.pages[s]={...o.pages[s],src:i,blob:i instanceof Blob?i:void 0},n=o.pages[s];else{let c=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i,blob:i instanceof Blob?i:void 0};o.pages.push(c),n=c}let a=Ee(n.src)||(n.src instanceof Blob?n.src:null)||(n.blob instanceof Blob?n.blob:null);if(!a&&typeof n.src=="string"&&n.src.startsWith("blob:"))try{a=await(await fetch(n.src)).blob()}catch{}a&&await this.#n.put(`${t}:${e}`,a),await this.saveDoc(t,o)}async getPage(t,e){let i=await this.#n.get(`${t}:${e}`);if(i)return i;let o=this.getDocSync(t);if(!o)return null;let s=o.pages.find(n=>n.id===e);return s?s.content??s.src??s:null}async deletePage(t,e){let i=this.getDocSync(t);if(!i)return;i.pages=i.pages.filter(n=>n.id!==e),this.#t.setRow("docs",t,{name:i.name||"",pages:JSON.stringify(i.pages)}),await this.#n.delete(`${t}:${e}`),await this.#n.delete(`${t}:${e}:original`);let o=`${t}:${e}`;if(this.#a.has(o)){try{URL.revokeObjectURL(this.#a.get(o))}catch{}this.#a.delete(o)}let s=`${t}:${e}:orig`;if(this.#l.has(s)){try{URL.revokeObjectURL(this.#l.get(s))}catch{}this.#l.delete(s)}this.#o.delete(t)}async getSchemaVersion(){if(this.#t&&this.#t.hasValue("schemaVersion")){let t=this.#t.getValue("schemaVersion");return typeof t=="number"?t:null}return null}async setSchemaVersion(t){this.#t&&(this.#t.setValue("schemaVersion",typeof t=="number"?t:null),this.#r&&typeof this.#r.save=="function"&&await this.#r.save())}subscribe(t){let e=this.#t.addTableListener("docs",t);return()=>{this.#t.delListener(e)}}#d(t){if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}};async function Ln(){if(typeof location<"u"&&location.search&&(new URLSearchParams(location.search).has("no-opfs")||new URLSearchParams(location.search).get("storage")==="indexeddb")||typeof navigator>"u"||!navigator.storage||typeof navigator.storage.getDirectory!="function")return!1;try{let r=await navigator.storage.getDirectory();if(!r)return!1;let t=`.copio-probe-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`,e=await r.getFileHandle(t,{create:!0}),i=await e.createWritable();if(await i.write(new Uint8Array([1,2,3,4])),await i.close(),(await e.getFile()).size!==4)throw new Error("OPFS probe size mismatch");return await r.removeEntry(t),!0}catch{return!1}}function vc(r,t,e="store.json"){let i=0,o=null,s=Promise.resolve(),n=0,a=()=>typeof t=="function"?t():t,c=async()=>{await s;let g=a();if(g){i=1;try{let S=await(await(await g.getFileHandle(e)).getFile()).text();S&&S.trim().length>0&&r.setJson(S)}catch{}finally{i=0}}},h=()=>{let g=a();return g?(n++,i=2,s=s.catch(()=>{}).then(async()=>{try{let m=r.getJson(),S=await(await g.getFileHandle(e,{create:!0})).createWritable();await S.write(m),await S.close()}catch(m){console.warn("[OpfsPersister] Failed to save store.json:",m)}finally{n--,n<=0&&(n=0,i=0)}}),s):Promise.resolve()};return{load:c,save:h,startAutoSave:()=>{o||(o=r.addDidFinishTransactionListener(()=>{h()}))},stopAutoSave:()=>{o&&(r.delListener(o),o=null)},getStatus:()=>i,getStore:()=>r}}async function Tn(r){let t=[];try{if(typeof r.entries=="function")for await(let e of r.entries())t.push(e);else if(typeof r.values=="function")for await(let e of r.values())t.push([e.name,e])}catch(e){console.warn("[OpfsAdapter] Error reading directory entries:",e)}return t}var xi=class extends Gt{#t;#r="copio";#n=null;#s=null;#e=null;#i=null;#a=null;#l=!1;#o=null;#p=new Set;#h=new Map;#d=new Map;#u=new Map;#f=new Map;#c=null;constructor(t={}){super(),this.#t=t,this.#r=t.dirName||"copio",t.store?this.#i=t.store:(this.#i=yi(),this.#i.setTable("docs",{})),this.#a=t.persister||vc(this.#i,()=>this.#s,"store.json")}get store(){return this.#l?this.#o?.store:this.#i}get persister(){return this.#l?this.#o?.persister:this.#a}get isFallback(){return this.#l}get fallbackAdapter(){return this.#o}async#m(){if(this.#l)return!1;if(this.#e&&this.#s)return!0;if(typeof navigator<"u"&&navigator.storage&&typeof navigator.storage.getDirectory=="function")try{return this.#n=await navigator.storage.getDirectory(),this.#s=await this.#n.getDirectoryHandle(this.#r,{create:!0}),this.#e=await this.#s.getDirectoryHandle("docs",{create:!0}),!0}catch(t){return console.warn("[OpfsAdapter] OPFS directory access failed, switching to fallback:",t),await this.#g(),!1}else return await this.#g(),!1}#y(t,e){return typeof e=="string"&&e.startsWith("blob:")&&(this.#p.add(e),this.#h.has(t)||this.#h.set(t,[]),this.#h.get(t).push(e)),e}revokeDocUrls(t){if(this.#l){this.#o?.revokeDocUrls(t);return}let e=this.#h.get(t);if(e){for(let i of e){try{URL.revokeObjectURL(i)}catch{}this.#p.delete(i)}this.#h.delete(t)}for(let[i,o]of this.#d.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(o)}catch{}this.#d.delete(i)}for(let[i,o]of this.#u.entries())if(i.startsWith(`${t}:`)){try{URL.revokeObjectURL(o)}catch{}this.#u.delete(i)}this.#f.delete(t)}revokeAllUrls(){if(this.#l){this.#o?.revokeAllUrls();return}for(let t of this.#p)try{URL.revokeObjectURL(t)}catch{}this.#p.clear(),this.#h.clear(),this.#d.clear(),this.#u.clear(),this.#f.clear()}async init(){return this.#c?this.#c:(this.#c=(async()=>{if(this.#t.forceFallback)return this.#g();if(!await Ln())return this.#g();try{await this.#m(),await this.#a.load(),this.#a.startAutoSave(),await this.sweepOrphans();let e=!1;if(typeof navigator<"u"&&navigator.storage&&navigator.storage.persisted)try{e=await navigator.storage.persisted()}catch{}return{kind:"opfs",persistent:e}}catch(e){return console.warn("[OpfsAdapter] OPFS initialization failed, switching to IndexedDB fallback:",e),this.#g()}})(),this.#c)}async#g(){return this.#l=!0,this.#o=new de(this.#t),{kind:"indexeddb",persistent:(await this.#o.init()).persistent}}async sweepOrphans(){if(this.#l)return this.#o?.sweepOrphans();if(await this.#m(),!this.#e)return 0;let t=0,e=this.#i.getTable("docs")||{},i=new Set(Object.keys(e)),o=new Map;for(let[n,a]of Object.entries(e)){let c=this.#b(a.pages);o.set(n,new Set(c.map(h=>h.id)))}let s=await Tn(this.#e);for(let[n,a]of s)if(a.kind==="directory")if(i.has(n)){let c=o.get(n)||new Set,h=a,p=await Tn(h);for(let[d]of p){let g=d.replace(/-original\.bin$/,"").replace(/\.bin$/,"");if(!c.has(g))try{await h.removeEntry(d),t++}catch{}}}else try{await this.#e.removeEntry(n,{recursive:!0}),t++}catch{}return t}listDocsSync(){if(this.#l)return this.#o?.listDocsSync();let t=this.#i.getTable("docs");return Object.entries(t||{}).map(([e,i])=>({id:e,name:i.name||"",pages:this.#b(i.pages)}))}async listDocs(){return this.#l?this.#o?.listDocs():this.listDocsSync()}getDocSync(t){if(this.#l)return this.#o?.getDocSync(t);if(this.#f.has(t))return this.#f.get(t);if(!this.#i.hasRow("docs",t))return null;let e=this.#i.getRow("docs",t);return{id:t,name:e.name||"",pages:this.#b(e.pages)}}async getDoc(t){if(this.#l)return this.#o?.getDoc(t);if(await this.#m(),!this.#i.hasRow("docs",t))return null;let e=this.#i.getRow("docs",t),i=this.#b(e.pages),o=null;if(this.#e)try{o=await this.#e.getDirectoryHandle(t)}catch{}let s=await Promise.all(i.map(async a=>{if(!a||!o)return a;let c={...a},h=`${t}:${a.id}`;try{let g=await(await o.getFileHandle(`${a.id}.bin`)).getFile();c.blob=g,this.#d.has(h)?c.src=this.#d.get(h):(c.src=this.#y(t,URL.createObjectURL(g)),this.#d.set(h,c.src))}catch{}let p=`${t}:${a.id}:orig`;try{let g=await(await o.getFileHandle(`${a.id}-original.bin`)).getFile();c.originalBlob=g,this.#u.has(p)?c.originalSrc=this.#u.get(p):(c.originalSrc=this.#y(t,URL.createObjectURL(g)),this.#u.set(p,c.originalSrc))}catch{c.blob&&(c.originalBlob=c.blob,c.originalSrc=c.src)}return c})),n={id:t,name:e.name||"",pages:s};return this.#f.set(t,n),n}async saveDoc(t,e){if(this.#l)return this.#o?.saveDoc(t,e);if(!t)throw new Error("Cannot save document without an ID");let i=Array.isArray(e.pages)?e.pages:this.#b(e.pages),o=[],s=[],n=[];for(let c of i){if(!c)continue;let h=Ee(c.src)||(c.src instanceof Blob?c.src:null)||(c.blob instanceof Blob?c.blob:null),p=h?.type||"image/jpeg",d={id:c.id,name:c.name||"",type:c.type||"image",hasBlob:!0,mimeType:p,edits:c.edits,exif:c.exif,content:c.content,ocrText:c.ocrText??null,ocrConfidence:c.ocrConfidence??null,ocrWords:Array.isArray(c.ocrWords)?c.ocrWords:null,ocrWidth:c.ocrWidth??null,ocrHeight:c.ocrHeight??null};o.push(d);let g=`${t}:${c.id}`,m=`${t}:${c.id}:orig`,y={...c},S=this.#d.get(g),b=typeof c.src=="string"&&c.src.startsWith("data:")||c.src instanceof Blob||c.src&&S&&c.src!==S;if(h)if(y.blob=h,b||!S){if(S){try{URL.revokeObjectURL(S)}catch{}this.#p.delete(S)}let B=this.#y(t,URL.createObjectURL(h));this.#d.set(g,B),y.src=B}else y.src=S;let v=Ee(c.originalSrc)||(c.originalSrc instanceof Blob?c.originalSrc:null)||(c.originalBlob instanceof Blob?c.originalBlob:null),C=this.#u.get(m),k=!C&&!v&&(!c.originalSrc||c.originalSrc===c.src);k&&h&&(v=h);let T=typeof c.originalSrc=="string"&&c.originalSrc.startsWith("data:")||c.originalSrc instanceof Blob||k&&!!v;if(v)if(y.originalBlob=v,T||!C){if(C&&T){try{URL.revokeObjectURL(C)}catch{}this.#p.delete(C)}let B=this.#y(t,URL.createObjectURL(v));this.#u.set(m,B),y.originalSrc=B}else y.originalSrc=C;else C?y.originalSrc=C:c.originalSrc?y.originalSrc=c.originalSrc:(y.originalSrc=y.src,y.blob&&(y.originalBlob=y.blob));s.push(y),n.push({pageId:c.id,page:c,srcBlob:h,origBlob:v})}if(this.#i.setRow("docs",t,{name:e.name||"",pages:JSON.stringify(o)}),this.#f.set(t,{id:t,name:e.name||"",pages:s}),await this.#m(),this.#l)return this.#o?.saveDoc(t,e);let a=null;if(this.#e)try{a=await this.#e.getDirectoryHandle(t,{create:!0})}catch(c){console.warn(`[OpfsAdapter] Failed to get doc directory "${t}":`,c)}if(a)for(let c of n){let{pageId:h,page:p,srcBlob:d,origBlob:g}=c;if(!d&&typeof p.src=="string"&&p.src.startsWith("blob:"))try{d=await(await fetch(p.src)).blob()}catch{}if(d)try{let y=await(await a.getFileHandle(`${h}.bin`,{create:!0})).createWritable();await y.write(d),await y.close()}catch(m){console.warn(`[OpfsAdapter] Failed writing page file "${h}.bin":`,m)}if(!g&&typeof p.originalSrc=="string"&&p.originalSrc.startsWith("blob:"))try{g=await(await fetch(p.originalSrc)).blob()}catch{}if(g)try{let y=await(await a.getFileHandle(`${h}-original.bin`,{create:!0})).createWritable();await y.write(g),await y.close()}catch{}}}async deleteDoc(t){if(this.#l)return this.#o?.deleteDoc(t);if(this.#i.delRow("docs",t),this.#f.delete(t),this.revokeDocUrls(t),await this.#m(),this.#e)try{await this.#e.removeEntry(t,{recursive:!0})}catch{}}async renameDoc(t,e){if(this.#l)return this.#o?.renameDoc(t,e);if(!this.#i.hasRow("docs",t))throw new Error(`Document "${t}" not found`);this.#i.setCell("docs",t,"name",e),this.#f.has(t)&&(this.#f.get(t).name=e)}async savePage(t,e,i){if(this.#l)return this.#o?.savePage(t,e,i);await this.#m();let o=await this.getDoc(t);if(!o)throw new Error(`Document ${t} not found`);let s=o.pages.findIndex(c=>c.id===e),n;if(s>=0)typeof i=="object"&&i!==null&&!(i instanceof Blob)?o.pages[s]={...o.pages[s],...i}:o.pages[s]={...o.pages[s],src:i,blob:i instanceof Blob?i:void 0},n=o.pages[s];else{let c=typeof i=="object"&&i!==null&&!(i instanceof Blob)?{id:e,...i}:{id:e,src:i,blob:i instanceof Blob?i:void 0};o.pages.push(c),n=c}let a=Ee(n.src)||(n.src instanceof Blob?n.src:null)||(n.blob instanceof Blob?n.blob:null);if(!a&&typeof n.src=="string"&&n.src.startsWith("blob:"))try{a=await(await fetch(n.src)).blob()}catch{}if(a&&this.#e)try{let p=await(await(await this.#e.getDirectoryHandle(t,{create:!0})).getFileHandle(`${e}.bin`,{create:!0})).createWritable();await p.write(a),await p.close()}catch(c){console.warn(`[OpfsAdapter] Failed writing page file "${e}.bin":`,c)}await this.saveDoc(t,o)}async getPage(t,e){if(this.#l)return this.#o?.getPage(t,e);if(await this.#m(),this.#e)try{return await(await(await this.#e.getDirectoryHandle(t)).getFileHandle(`${e}.bin`)).getFile()}catch{}let i=this.getDocSync(t);if(!i)return null;let o=i.pages.find(s=>s.id===e);return o?o.content??o.src??o:null}async deletePage(t,e){if(this.#l)return this.#o?.deletePage(t,e);await this.#m();let i=this.getDocSync(t);if(!i)return;if(i.pages=i.pages.filter(n=>n.id!==e),this.#i.setRow("docs",t,{name:i.name||"",pages:JSON.stringify(i.pages)}),this.#e){try{await(await this.#e.getDirectoryHandle(t)).removeEntry(`${e}.bin`)}catch{}try{await(await this.#e.getDirectoryHandle(t)).removeEntry(`${e}-original.bin`)}catch{}}let o=`${t}:${e}`;if(this.#d.has(o)){try{URL.revokeObjectURL(this.#d.get(o))}catch{}this.#d.delete(o)}let s=`${t}:${e}:orig`;if(this.#u.has(s)){try{URL.revokeObjectURL(this.#u.get(s))}catch{}this.#u.delete(s)}this.#f.delete(t)}async getSchemaVersion(){if(this.#l&&this.#o)return this.#o.getSchemaVersion();if(this.#i&&this.#i.hasValue("schemaVersion")){let t=this.#i.getValue("schemaVersion");return typeof t=="number"?t:null}return null}async setSchemaVersion(t){if(this.#l&&this.#o)return this.#o.setSchemaVersion(t);this.#i&&(this.#i.setValue("schemaVersion",typeof t=="number"?t:null),this.#a&&typeof this.#a.save=="function"&&await this.#a.save())}subscribe(t){if(this.#l)return this.#o?.subscribe(t);let e=this.#i.addTableListener("docs",t);return()=>{this.#i.delListener(e)}}#b(t){if(Array.isArray(t))return t;if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}};function Sr(r={}){return r.forceMemory?new Oe:r.forceIndexedDb?new de(r):r.forceOpfs?new xi(r):typeof navigator<"u"&&navigator.storage&&typeof navigator.storage.getDirectory=="function"?new xi(r):typeof indexedDB<"u"?new de(r):new Oe}function st(r,t,e){return t in r?Object.defineProperty(r,t,{value:e,enumerable:!0,configurable:!0,writable:!0}):r[t]=e,r}var jo=typeof self<"u"?self:global,Ci=typeof navigator<"u",Sc=Ci&&typeof HTMLImageElement>"u",Mn=!(typeof global>"u"||typeof process>"u"||!process.versions||!process.versions.node),zo=jo.Buffer,kr=jo.BigInt,Vo=!!zo,Er=r=>Wn(r)?void 0:r,kc=r=>r!==void 0;function Wn(r){return r===void 0||(r instanceof Map?r.size===0:Object.values(r).filter(kc).length===0)}function vt(r){let t=new Error(r);throw delete t.stack,t}function qn(r){return(r=(function(t){for(;t.endsWith("\0");)t=t.slice(0,-1);return t})(r).trim())===""?void 0:r}function Bn(r){let t=(function(e){let i=0;return e.ifd0.enabled&&(i+=1024),e.exif.enabled&&(i+=2048),e.makerNote&&(i+=2048),e.userComment&&(i+=1024),e.gps.enabled&&(i+=512),e.interop.enabled&&(i+=100),e.ifd1.enabled&&(i+=1024),i+2048})(r);return r.jfif.enabled&&(t+=50),r.xmp.enabled&&(t+=2e4),r.iptc.enabled&&(t+=14e3),r.icc.enabled&&(t+=6e3),t}var Lo=r=>String.fromCharCode.apply(null,r),Un=typeof TextDecoder<"u"?new TextDecoder("utf-8"):void 0;function Kn(r){return Un?Un.decode(r):Vo?Buffer.from(r).toString("utf8"):decodeURIComponent(escape(Lo(r)))}var Zt=class r{static from(t,e){return t instanceof this&&t.le===e?t:new r(t,void 0,void 0,e)}constructor(t,e=0,i,o){if(typeof o=="boolean"&&(this.le=o),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 s=new DataView(t,e,i);this._swapDataView(s)}else if(t instanceof Uint8Array||t instanceof DataView||t instanceof r){i===void 0&&(i=t.byteLength-e),(e+=t.byteOffset)+i>t.byteOffset+t.byteLength&&vt("Creating view outside of available memory in ArrayBuffer");let s=new DataView(t.buffer,e,i);this._swapDataView(s)}else if(typeof t=="number"){let s=new DataView(new ArrayBuffer(t));this._swapDataView(s)}else vt("Invalid input argument for BufferView: "+t)}_swapArrayBuffer(t){this._swapDataView(new DataView(t))}_swapBuffer(t){this._swapDataView(new DataView(t.buffer,t.byteOffset,t.byteLength))}_swapDataView(t){this.dataView=t,this.buffer=t.buffer,this.byteOffset=t.byteOffset,this.byteLength=t.byteLength}_lengthToEnd(t){return this.byteLength-t}set(t,e,i=r){return t instanceof DataView||t instanceof r?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t instanceof ArrayBuffer&&(t=new Uint8Array(t)),t instanceof Uint8Array||vt("BufferView.set(): Invalid data argument."),this.toUint8().set(t,e),new i(this,e,t.byteLength)}subarray(t,e){return e=e||this._lengthToEnd(t),new r(this,t,e)}toUint8(){return new Uint8Array(this.buffer,this.byteOffset,this.byteLength)}getUint8Array(t,e){return new Uint8Array(this.buffer,this.byteOffset+t,e)}getString(t=0,e=this.byteLength){return Kn(this.getUint8Array(t,e))}getLatin1String(t=0,e=this.byteLength){let i=this.getUint8Array(t,e);return Lo(i)}getUnicodeString(t=0,e=this.byteLength){let i=[];for(let o=0;o<e&&t+o<this.byteLength;o+=2)i.push(this.getUint16(t+o));return Lo(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 Mo(r,t){vt(`${r} '${t}' was not loaded, try using full build of exifr.`)}var Pi=class extends Map{constructor(t){super(),this.kind=t}get(t,e){return this.has(t)||Mo(this.kind,t),e&&(t in e||(function(i,o){vt(`Unknown ${i} '${o}'.`)})(this.kind,t),e[t].enabled||Mo(this.kind,t)),super.get(t)}keyList(){return Array.from(this.keys())}},Te=new Pi("file parser"),At=new Pi("segment parser"),Le=new Pi("file reader"),Gn=jo.fetch;function On(r,t){return(e=r).startsWith("data:")||e.length>1e4?Uo(r,t,"base64"):Mn&&r.includes("://")?Bo(r,t,"url",Ge):Mn?Uo(r,t,"fs"):Ci?Bo(r,t,"url",Ge):void vt("Invalid input argument");var e}async function Bo(r,t,e,i){return Le.has(e)?Uo(r,t,e):i?(async function(o,s){let n=await s(o);return new Zt(n)})(r,i):void vt(`Parser ${e} is not loaded`)}async function Uo(r,t,e){let i=new(Le.get(e))(r,t);return await i.read(),i}var Ge=r=>Gn(r).then((t=>t.arrayBuffer())),Je=r=>new Promise(((t,e)=>{let i=new FileReader;i.onloadend=()=>t(i.result||new ArrayBuffer),i.onerror=e,i.readAsArrayBuffer(r)})),Oo=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 $t(r,t,e){let i=new Oo;for(let[o,s]of e)i.set(o,s);if(Array.isArray(t))for(let o of t)r.set(o,i);else r.set(t,i);return i}function Wo(r,t,e){let i,o=r.get(t);for(i of e)o.set(i[0],i[1])}var Yt=new Map,Qe=new Map,Re=new Map,Pe=["chunked","firstChunkSize","firstChunkSizeNode","firstChunkSizeBrowser","chunkSize","chunkLimit"],Ii=["jfif","xmp","icc","iptc","ihdr"],Xe=["tiff",...Ii],xt=["ifd0","ifd1","exif","gps","interop"],Ie=[...Xe,...xt],Ae=["makerNote","userComment"],Ai=["translateKeys","translateValues","reviveValues","multiSegment"],De=[...Ai,"sanitize","mergeOutput","silentErrors"],Cr=class{get translate(){return this.translateKeys||this.translateValues||this.reviveValues}},Ce=class extends Cr{get needed(){return this.enabled||this.deps.size>0}constructor(t,e,i,o){if(super(),st(this,"enabled",!1),st(this,"skip",new Set),st(this,"pick",new Set),st(this,"deps",new Set),st(this,"translateKeys",!1),st(this,"translateValues",!1),st(this,"reviveValues",!1),this.key=t,this.enabled=e,this.parse=this.enabled,this.applyInheritables(o),this.canBeFiltered=xt.includes(t),this.canBeFiltered&&(this.dict=Yt.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:s,skip:n}=i;s&&s.length>0&&this.translateTagSet(s,this.pick),n&&n.length>0&&this.translateTagSet(n,this.skip)}this.applyInheritables(i)}else i===!0||i===!1?this.parse=this.enabled=i:vt(`Invalid options argument: ${i}`)}applyInheritables(t){let e,i;for(e of Ai)i=t[e],i!==void 0&&(this[e]=i)}translateTagSet(t,e){if(this.dict){let i,o,{tagKeys:s,tagValues:n}=this.dict;for(i of t)typeof i=="string"?(o=n.indexOf(i),o===-1&&(o=s.indexOf(Number(i))),o!==-1&&e.add(Number(s[o]))):e.add(i)}else for(let i of t)e.add(i)}finalizeFilters(){!this.enabled&&this.deps.size>0?(this.enabled=!0,Pr(this.pick,this.deps)):this.enabled&&this.pick.size>0&&Pr(this.pick,this.deps)}},It={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},Fn=new Map,pe=class extends Cr{static useCached(t){let e=Fn.get(t);return e!==void 0||(e=new this(t),Fn.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):vt(`Invalid options argument ${t}`),this.firstChunkSize===void 0&&(this.firstChunkSize=Ci?this.firstChunkSizeBrowser:this.firstChunkSizeNode),this.mergeOutput&&(this.ifd1.enabled=!1),this.filterNestedSegmentTags(),this.traverseTiffDependencyTree(),this.checkLoadedPlugins()}setupFromUndefined(){let t;for(t of Pe)this[t]=It[t];for(t of De)this[t]=It[t];for(t of Ae)this[t]=It[t];for(t of Ie)this[t]=new Ce(t,It[t],void 0,this)}setupFromTrue(){let t;for(t of Pe)this[t]=It[t];for(t of De)this[t]=It[t];for(t of Ae)this[t]=!0;for(t of Ie)this[t]=new Ce(t,!0,void 0,this)}setupFromArray(t){let e;for(e of Pe)this[e]=It[e];for(e of De)this[e]=It[e];for(e of Ae)this[e]=It[e];for(e of Ie)this[e]=new Ce(e,!1,void 0,this);this.setupGlobalFilters(t,void 0,xt)}setupFromObject(t){let e;for(e of(xt.ifd0=xt.ifd0||xt.image,xt.ifd1=xt.ifd1||xt.thumbnail,Object.assign(this,t),Pe))this[e]=Do(t[e],It[e]);for(e of De)this[e]=Do(t[e],It[e]);for(e of Ae)this[e]=Do(t[e],It[e]);for(e of Xe)this[e]=new Ce(e,It[e],t[e],this);for(e of xt)this[e]=new Ce(e,It[e],t[e],this.tiff);this.setupGlobalFilters(t.pick,t.skip,xt,Ie),t.tiff===!0?this.batchEnableWithBool(xt,!0):t.tiff===!1?this.batchEnableWithUserValue(xt,t):Array.isArray(t.tiff)?this.setupGlobalFilters(t.tiff,void 0,xt):typeof t.tiff=="object"&&this.setupGlobalFilters(t.tiff.pick,t.tiff.skip,xt)}batchEnableWithBool(t,e){for(let i of t)this[i].enabled=e}batchEnableWithUserValue(t,e){for(let i of t){let o=e[i];this[i].enabled=o!==!1&&o!==void 0}}setupGlobalFilters(t,e,i,o=i){if(t&&t.length){for(let n of o)this[n].enabled=!1;let s=Nn(t,i);for(let[n,a]of s)Pr(this[n].pick,a),this[n].enabled=!0}else if(e&&e.length){let s=Nn(e,i);for(let[n,a]of s)Pr(this[n].skip,a)}}filterNestedSegmentTags(){let{ifd0:t,exif:e,xmp:i,iptc:o,icc:s}=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),o.enabled||t.skip.add(33723),s.enabled||t.skip.add(34675)}traverseTiffDependencyTree(){let{ifd0:t,exif:e,gps:i,interop:o}=this;o.needed&&(e.deps.add(40965),t.deps.add(40965)),e.needed&&t.deps.add(34665),i.needed&&t.deps.add(34853),this.tiff.enabled=xt.some((s=>this[s].enabled===!0))||this.makerNote||this.userComment;for(let s of xt)this[s].finalizeFilters()}get onlyTiff(){return!Ii.map((t=>this[t].enabled)).some((t=>t===!0))&&this.tiff.enabled}checkLoadedPlugins(){for(let t of Xe)this[t].enabled&&!At.has(t)&&Mo("segment parser",t)}};function Nn(r,t){let e,i,o,s,n=[];for(o of t){for(s of(e=Yt.get(o),i=[],e))(r.includes(s[0])||r.includes(s[1]))&&i.push(s[0]);i.length&&n.push([o,i])}return n}function Do(r,t){return r!==void 0?r:t!==void 0?t:void 0}function Pr(r,t){for(let e of t)r.add(e)}st(pe,"default",It);var te=class{constructor(t){st(this,"parsers",{}),st(this,"output",{}),st(this,"errors",[]),st(this,"pushToErrors",(e=>this.errors.push(e))),this.options=pe.useCached(t)}async read(t){this.file=await(function(e,i){return typeof e=="string"?On(e,i):Ci&&!Sc&&e instanceof HTMLImageElement?On(e.src,i):e instanceof Uint8Array||e instanceof ArrayBuffer||e instanceof DataView?new Zt(e):Ci&&e instanceof Blob?Bo(e,i,"blob",Je):void vt("Invalid input argument")})(t,this.options)}setup(){if(this.fileParser)return;let{file:t}=this,e=t.getUint16(0);for(let[i,o]of Te)if(o.canHandle(t,e))return this.fileParser=new o(this.options,this.file,this.parsers),t[i]=!0;this.file.close&&this.file.close(),vt("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),Er(t)}async executeParsers(){let{output:t}=this;await this.fileParser.parse();let e=Object.values(this.parsers).map((async i=>{let o=await i.parse();i.assignToOutput(t,o)}));this.options.silentErrors&&(e=e.map((i=>i.catch(this.pushToErrors)))),await Promise.all(e)}async extractThumbnail(){this.setup();let{options:t,file:e}=this,i=At.get("tiff",t);var o;if(e.tiff?o={start:0,type:"tiff"}:e.jpeg&&(o=await this.fileParser.getOrFindSegment("tiff")),o===void 0)return;let s=await this.fileParser.ensureSegmentChunk(o),n=this.parsers.tiff=new i(s,t,e),a=await n.extractThumbnail();return e.close&&e.close(),a}};async function qo(r,t){let e=new te(t);return await e.read(r),e.parse()}var Ec=Object.freeze({__proto__:null,parse:qo,Exifr:te,fileParsers:Te,segmentParsers:At,fileReaders:Le,tagKeys:Yt,tagValues:Qe,tagRevivers:Re,createDictionary:$t,extendDictionary:Wo,fetchUrlAsArrayBuffer:Ge,readBlobAsArrayBuffer:Je,chunkedProps:Pe,otherSegments:Ii,segments:Xe,tiffBlocks:xt,segmentsAndBlocks:Ie,tiffExtractables:Ae,inheritables:Ai,allFormatters:De,Options:pe}),Ir=class{constructor(t,e,i){st(this,"errors",[]),st(this,"ensureSegmentChunk",(async o=>{let s=o.start,n=o.size||65536;if(this.file.chunked)if(this.file.available(s,n))o.chunk=this.file.subarray(s,n);else try{o.chunk=await this.file.readChunk(s,n)}catch(a){vt(`Couldn't read segment: ${JSON.stringify(o)}. ${a.message}`)}else this.file.byteLength>s+n?o.chunk=this.file.subarray(s,n):o.size===void 0?o.chunk=this.file.subarray(s):vt("Segment unreachable: "+JSON.stringify(o));return o.chunk})),this.extendOptions&&this.extendOptions(t),this.options=t,this.file=e,this.parsers=i}injectSegment(t,e){this.options[t].enabled&&this.createParser(t,e)}createParser(t,e){let i=new(At.get(t))(e,this.options,this.file);return this.parsers[t]=i}createParsers(t){for(let e of t){let{type:i,chunk:o}=e,s=this.options[i];if(s&&s.enabled){let n=this.parsers[i];n&&n.append||n||this.createParser(i,o)}}}async readSegments(t){let e=t.map(this.ensureSegmentChunk);await Promise.all(e)}},Qt=class{static findPosition(t,e){let i=t.getUint16(e+2)+2,o=typeof this.headerLength=="function"?this.headerLength(t,e,i):this.headerLength,s=e+o,n=i-o;return{offset:e,length:i,headerLength:o,start:s,size:n,end:s+n}}static parse(t,e={}){return new this(t,new pe({[this.type]:e}),t).parse()}normalizeInput(t){return t instanceof Zt?t:new Zt(t)}constructor(t,e={},i){st(this,"errors",[]),st(this,"raw",new Map),st(this,"handleError",(o=>{if(!this.options.silentErrors)throw o;this.errors.push(o.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=Re.get(e),o=Qe.get(e),s=Yt.get(e),n=this.options[e],a=n.reviveValues&&!!i,c=n.translateValues&&!!o,h=n.translateKeys&&!!s,p={};for(let[d,g]of t)a&&i.has(d)?g=i.get(d)(g):c&&o.has(d)&&(g=this.translateValue(g,o.get(d))),h&&s.has(d)&&(d=s.get(d)||d),p[d]=g;return p}translateValue(t,e){return e[t]||e.DEFAULT||t}assignToOutput(t,e){this.assignObjectToOutput(t,this.constructor.type,e)}assignObjectToOutput(t,e,i){if(this.globalOptions.mergeOutput)return Object.assign(t,i);t[e]?Object.assign(t[e],i):t[e]=i}};st(Qt,"headerLength",4),st(Qt,"type",void 0),st(Qt,"multiSegment",!1),st(Qt,"canHandle",(()=>!1));function Cc(r){return r===192||r===194||r===196||r===219||r===221||r===218||r===254}function Pc(r){return r>=224&&r<=239}function Ic(r,t,e){for(let[i,o]of At)if(o.canHandle(r,t,e))return i}var Ar=class extends Ir{constructor(...t){super(...t),st(this,"appSegments",[]),st(this,"jpegSegments",[]),st(this,"unknownSegments",[])}static canHandle(t,e){return e===65496}async parse(){await this.findAppSegments(),await this.readSegments(this.appSegments),this.mergeMultiSegments(),this.createParsers(this.mergedAppSegments||this.appSegments)}setupSegmentFinderArgs(t){t===!0?(this.findAll=!0,this.wanted=new Set(At.keyList())):(t=t===void 0?At.keyList().filter((e=>this.options[e].enabled)):t.filter((e=>this.options[e].enabled&&At.has(e))),this.findAll=!1,this.remaining=new Set(t),this.wanted=new Set(t)),this.unfinishedMultiSegment=!1}async findAppSegments(t=0,e){this.setupSegmentFinderArgs(e);let{file:i,findAll:o,wanted:s,remaining:n}=this;if(!o&&this.file.chunked&&(o=Array.from(s).some((a=>{let c=At.get(a),h=this.options[a];return c.multiSegment&&h.multiSegment})),o&&await this.file.readWhole()),t=this.findAppSegmentsInRange(t,i.byteLength),!this.options.onlyTiff&&i.chunked){let a=!1;for(;n.size>0&&!a&&(i.canReadNextChunk||this.unfinishedMultiSegment);){let{nextChunkOffset:c}=i,h=this.appSegments.some((p=>!this.file.available(p.offset||p.start,p.length||p.size)));if(a=t>c&&!h?!await i.readNextChunk(t):!await i.readNextChunk(c),(t=this.findAppSegmentsInRange(t,i.byteLength))===void 0)return}}}findAppSegmentsInRange(t,e){e-=2;let i,o,s,n,a,c,{file:h,findAll:p,wanted:d,remaining:g,options:m}=this;for(;t<e;t++)if(h.getUint8(t)===255){if(i=h.getUint8(t+1),Pc(i)){if(o=h.getUint16(t+2),s=Ic(h,t,o),s&&d.has(s)&&(n=At.get(s),a=n.findPosition(h,t),c=m[s],a.type=s,this.appSegments.push(a),!p&&(n.multiSegment&&c.multiSegment?(this.unfinishedMultiSegment=a.chunkNumber<a.chunkCount,this.unfinishedMultiSegment||g.delete(s)):g.delete(s),g.size===0)))break;m.recordUnknownSegments&&(a=Qt.findPosition(h,t),a.marker=i,this.unknownSegments.push(a)),t+=o+1}else if(Cc(i)){if(o=h.getUint16(t+2),i===218&&m.stopAfterSos!==!1)return;m.recordJpegSegments&&this.jpegSegments.push({offset:t,length:o,marker:i}),t+=o+1}}return t}mergeMultiSegments(){if(!this.appSegments.some((e=>e.multiSegment)))return;let t=(function(e,i){let o,s,n,a=new Map;for(let c=0;c<e.length;c++)o=e[c],s=o[i],a.has(s)?n=a.get(s):a.set(s,n=[]),n.push(o);return Array.from(a)})(this.appSegments,"type");this.mergedAppSegments=t.map((([e,i])=>{let o=At.get(e,this.options);return o.handleMultiSegments?{type:e,chunk:o.handleMultiSegments(i)}:i[0]}))}getSegment(t){return this.appSegments.find((e=>e.type===t))}async getOrFindSegment(t){let e=this.getSegment(t);return e===void 0&&(await this.findAppSegments(0,[t]),e=this.getSegment(t)),e}};st(Ar,"type","jpeg"),Te.set("jpeg",Ar);var Ac=[void 0,1,1,2,4,8,1,1,2,4,8,4,8,4],Fo=class extends Qt{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:o,skip:s}=this.options[e];o=new Set(o);let n=o.size>0,a=s.size===0,c=this.chunk.getUint16(t);t+=2;for(let h=0;h<c;h++){let p=this.chunk.getUint16(t);if(n){if(o.has(p)&&(i.set(p,this.parseTag(t,p,e)),o.delete(p),o.size===0))break}else!a&&s.has(p)||i.set(p,this.parseTag(t,p,e));t+=12}return i}parseTag(t,e,i){let{chunk:o}=this,s=o.getUint16(t+2),n=o.getUint32(t+4),a=Ac[s];if(a*n<=4?t+=8:t=o.getUint32(t+8),(s<1||s>13)&&vt(`Invalid TIFF value type. block: ${i.toUpperCase()}, tag: ${e.toString(16)}, type: ${s}, offset ${t}`),t>o.byteLength&&vt(`Invalid TIFF value offset. block: ${i.toUpperCase()}, tag: ${e.toString(16)}, type: ${s}, offset ${t} is outside of chunk size ${o.byteLength}`),s===1)return o.getUint8Array(t,n);if(s===2)return qn(o.getString(t,n));if(s===7)return o.getUint8Array(t,n);if(n===1)return this.parseTagValue(s,t);{let c=new((function(p){switch(p){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}})(s))(n),h=a;for(let p=0;p<n;p++)c[p]=this.parseTagValue(s,t),t+=h;return c}}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:vt(`Invalid tiff type ${t}`)}}},Si=class extends Fo{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&&vt("Malformed EXIF data"),!t.chunked&&this.ifd0Offset>t.byteLength&&vt(`IFD0 offset points to outside of file.
3
+ this.ifd0Offset: ${this.ifd0Offset}, file.byteLength: ${t.byteLength}`),t.tiff&&await t.ensureChunk(this.ifd0Offset,Bn(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,Bn(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",Hn(...t.get(2),t.get(1))),t.set("longitude",Hn(...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,o={};for(e of xt)if(t=this[e],!Wn(t))if(i=this.canTranslate?this.translateBlock(t,e):Object.fromEntries(t),this.options.mergeOutput){if(e==="ifd1")continue;Object.assign(o,i)}else o[e]=i;return this.makerNote&&(o.makerNote=this.makerNote),this.userComment&&(o.userComment=this.userComment),o}assignToOutput(t,e){if(this.globalOptions.mergeOutput)Object.assign(t,e);else for(let[i,o]of Object.entries(e))this.assignObjectToOutput(t,i,o)}};function Hn(r,t,e,i){var o=r+t/60+e/3600;return i!=="S"&&i!=="W"||(o*=-1),o}st(Si,"type","tiff"),st(Si,"headerLength",10),At.set("tiff",Si);var Dc=Object.freeze({__proto__:null,default:Ec,Exifr:te,fileParsers:Te,segmentParsers:At,fileReaders:Le,tagKeys:Yt,tagValues:Qe,tagRevivers:Re,createDictionary:$t,extendDictionary:Wo,fetchUrlAsArrayBuffer:Ge,readBlobAsArrayBuffer:Je,chunkedProps:Pe,otherSegments:Ii,segments:Xe,tiffBlocks:xt,segmentsAndBlocks:Ie,tiffExtractables:Ae,inheritables:Ai,allFormatters:De,Options:pe,parse:qo}),Ko={ifd0:!1,ifd1:!1,exif:!1,gps:!1,interop:!1,sanitize:!1,reviveValues:!0,translateKeys:!1,translateValues:!1,mergeOutput:!1},Jn=Object.assign({},Ko,{firstChunkSize:4e4,gps:[1,2,3,4]});async function Rc(r){let t=new te(Jn);await t.read(r);let e=await t.parse();if(e&&e.gps){let{latitude:i,longitude:o}=e.gps;return{latitude:i,longitude:o}}}var Xn=Object.assign({},Ko,{tiff:!1,ifd1:!0,mergeOutput:!1});async function Tc(r){let t=new te(Xn);await t.read(r);let e=await t.extractThumbnail();return e&&Vo?zo.from(e):e}async function Lc(r){let t=await this.thumbnail(r);if(t!==void 0){let e=new Blob([t]);return URL.createObjectURL(e)}}var Qn=Object.assign({},Ko,{firstChunkSize:4e4,ifd0:[274]});async function Yn(r){let t=new te(Qn);await t.read(r);let e=await t.parse();if(e&&e.ifd0)return e.ifd0[274]}var Zn=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}}),qe=!0,Ke=!0;if(typeof navigator=="object"){let r=navigator.userAgent;if(r.includes("iPad")||r.includes("iPhone")){let t=r.match(/OS (\d+)_(\d+)/);if(t){let[,e,i]=t;qe=Number(e)+.1*Number(i)<13.4,Ke=!1}}else if(r.includes("OS X 10")){let[,t]=r.match(/OS X 10[_.](\d+)/);qe=Ke=Number(t)<15}if(r.includes("Chrome/")){let[,t]=r.match(/Chrome\/(\d+)/);qe=Ke=Number(t)<81}else if(r.includes("Firefox/")){let[,t]=r.match(/Firefox\/(\d+)/);qe=Ke=Number(t)<77}}async function Mc(r){let t=await Yn(r);return Object.assign({canvas:qe,css:Ke},Zn[t])}var No=class extends Zt{constructor(...t){super(...t),st(this,"ranges",new Ho),this.byteLength!==0&&this.ranges.add(0,this.byteLength)}_tryExtend(t,e,i){if(t===0&&this.byteLength===0&&i){let o=new DataView(i.buffer||i,i.byteOffset,i.byteLength);this._swapDataView(o)}else{let o=t+e;if(o>this.byteLength){let{dataView:s}=this._extend(o);this._swapDataView(s)}}}_extend(t){let e;e=Vo?zo.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 o=super.set(t,e);return this.ranges.add(e,o.byteLength),o}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)}},Ho=class{constructor(){st(this,"list",[])}get length(){return this.list.length}add(t,e,i=0){let o=t+e,s=this.list.filter((n=>$n(t,n.offset,o)||$n(t,n.end,o)));if(s.length>0){t=Math.min(t,...s.map((a=>a.offset))),o=Math.max(o,...s.map((a=>a.end))),e=o-t;let n=s.shift();n.offset=t,n.length=e,n.end=o,this.list=this.list.filter((a=>!s.includes(a)))}else this.list.push({offset:t,length:e,end:o})}available(t,e){let i=t+e;return this.list.some((o=>o.offset<=t&&i<=o.end))}};function $n(r,t,e){return r<=t&&t<=e}var Dr=class extends No{constructor(t,e){super(0),st(this,"chunksRead",0),this.input=t,this.options=e}async readWhole(){this.chunked=!1,await this.readChunk(this.nextChunkOffset)}async readChunked(){this.chunked=!0,await this.readChunk(0,this.options.firstChunkSize)}async readNextChunk(t=this.nextChunkOffset){if(this.fullyRead)return this.chunksRead++,!1;let e=this.options.chunkSize,i=await this.readChunk(t,e);return!!i&&i.byteLength===e}async readChunk(t,e){if(this.chunksRead++,(e=this.safeWrapAddress(t,e))!==0)return this._readChunk(t,e)}safeWrapAddress(t,e){return this.size!==void 0&&t+e>this.size?Math.max(0,this.size-t):e}get nextChunkOffset(){if(this.ranges.list.length!==0)return this.ranges.list[0].length}get canReadNextChunk(){return this.chunksRead<this.options.chunkLimit}get fullyRead(){return this.size!==void 0&&this.nextChunkOffset===this.size}read(){return this.options.chunked?this.readChunked():this.readWhole()}close(){}};Le.set("blob",class extends Dr{async readWhole(){this.chunked=!1;let r=await Je(this.input);this._swapArrayBuffer(r)}readChunked(){return this.chunked=!0,this.size=this.input.size,super.readChunked()}async _readChunk(r,t){let e=t?r+t:void 0,i=this.input.slice(r,e),o=await Je(i);return this.set(o,r,!0)}});var Bc=Object.freeze({__proto__:null,default:Dc,Exifr:te,fileParsers:Te,segmentParsers:At,fileReaders:Le,tagKeys:Yt,tagValues:Qe,tagRevivers:Re,createDictionary:$t,extendDictionary:Wo,fetchUrlAsArrayBuffer:Ge,readBlobAsArrayBuffer:Je,chunkedProps:Pe,otherSegments:Ii,segments:Xe,tiffBlocks:xt,segmentsAndBlocks:Ie,tiffExtractables:Ae,inheritables:Ai,allFormatters:De,Options:pe,parse:qo,gpsOnlyOptions:Jn,gps:Rc,thumbnailOnlyOptions:Xn,thumbnail:Tc,thumbnailUrl:Lc,orientationOnlyOptions:Qn,orientation:Yn,rotations:Zn,get rotateCanvas(){return qe},get rotateCss(){return Ke},rotation:Mc});Le.set("url",class extends Dr{async readWhole(){this.chunked=!1;let r=await Ge(this.input);r instanceof ArrayBuffer?this._swapArrayBuffer(r):r instanceof Uint8Array&&this._swapBuffer(r)}async _readChunk(r,t){let e=t?r+t-1:void 0,i=this.options.httpHeaders||{};(r||e)&&(i.range=`bytes=${[r,e].join("-")}`);let o=await Gn(this.input,{headers:i}),s=await o.arrayBuffer(),n=s.byteLength;if(o.status!==416)return n!==t&&(this.size=r+n),this.set(s,r,!0)}});Zt.prototype.getUint64=function(r){let t=this.getUint32(r),e=this.getUint32(r+4);return t<1048575?t<<32|e:typeof kr!==void 0?(console.warn("Using BigInt because of type 64uint but JS can only handle 53b numbers."),kr(t)<<kr(32)|kr(e)):void vt("Trying to read 64b value but JS can only handle 53b numbers.")};var $o=class extends Ir{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),o=t+8;return e===1&&(e=this.file.getUint64(t+8),o+=8),{offset:t,length:e,kind:i,start:o}}parseBoxFullHead(t){if(t.version!==void 0)return;let e=this.file.getUint32(t.start);t.version=e>>24,t.start+=4}},Rr=class extends $o{static canHandle(t,e){if(e!==0)return!1;let i=t.getUint16(2);if(i>50)return!1;let o=16,s=[];for(;o<i;)s.push(t.getString(o,4)),o+=4;return s.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 o=this.file.subarray(e,i);this.createParser(t,o)}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 o=this.findBox(i,"colr");o!==void 0&&await this.registerSegment("icc",o.offset+12,o.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 o=this.findExifLocIdInIinf(e),s=this.findExtentInIloc(i,o);if(s===void 0)return;let[n,a]=s;await this.file.ensureChunk(n,a);let c=4+this.file.getUint32(n);n+=c,a-=c,await this.registerSegment("tiff",n,a)}findExifLocIdInIinf(t){this.parseBoxFullHead(t);let e,i,o,s,n=t.start,a=this.file.getUint16(n);for(n+=2;a--;){if(e=this.parseBoxHead(n),this.parseBoxFullHead(e),i=e.start,e.version>=2&&(o=e.version===3?4:2,s=this.file.getString(i+o+2,4),s==="Exif"))return this.file.getUintBytes(i,o);n+=e.length}}get8bits(t){let e=this.file.getUint8(t);return[e>>4,15&e]}findExtentInIloc(t,e){this.parseBoxFullHead(t);let i=t.start,[o,s]=this.get8bits(i++),[n,a]=this.get8bits(i++),c=t.version===2?4:2,h=t.version===1||t.version===2?2:0,p=a+o+s,d=t.version===2?4:2,g=this.file.getUintBytes(i,d);for(i+=d;g--;){let m=this.file.getUintBytes(i,c);i+=c+h+2+n;let y=this.file.getUint16(i);if(i+=2,m===e)return y>1&&console.warn(`ILOC box has more than one extent but we're only processing one
4
+ Please create an issue at https://github.com/MikeKovarik/exifr with this file`),[this.file.getUintBytes(i+a,o),this.file.getUintBytes(i+a+o,s)];i+=y*p}}},Tr=class extends Rr{};st(Tr,"type","heic");var Lr=class extends Rr{};st(Lr,"type","avif"),Te.set("heic",Tr),Te.set("avif",Lr),$t(Yt,["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"]]),$t(Yt,"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"]]),$t(Yt,"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"]]),$t(Qe,["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 ki=$t(Qe,"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"}]]),_n={1:"No absolute unit of measurement",2:"Inch",3:"Centimeter"};ki.set(37392,_n),ki.set(41488,_n);var Ro={0:"Normal",1:"Low",2:"High"};function jn(r){return typeof r=="object"&&r.length!==void 0?r[0]:r}function zn(r){let t=Array.from(r).slice(1);return t[1]>15&&(t=t.map((e=>String.fromCharCode(e)))),t[2]!=="0"&&t[2]!==0||t.pop(),t.join(".")}function To(r){if(typeof r=="string"){var[t,e,i,o,s,n]=r.trim().split(/[-: ]/g).map(Number),a=new Date(t,e-1,i);return Number.isNaN(o)||Number.isNaN(s)||Number.isNaN(n)||(a.setHours(o),a.setMinutes(s),a.setSeconds(n)),Number.isNaN(+a)?r:a}}function vi(r){if(typeof r=="string")return r;let t=[];if(r[1]===0&&r[r.length-1]===0)for(let e=0;e<r.length;e+=2)t.push(Vn(r[e+1],r[e]));else for(let e=0;e<r.length;e+=2)t.push(Vn(r[e],r[e+1]));return qn(String.fromCodePoint(...t))}function Vn(r,t){return r<<8|t}ki.set(41992,Ro),ki.set(41993,Ro),ki.set(41994,Ro),$t(Re,["ifd0","ifd1"],[[50827,function(r){return typeof r!="string"?Kn(r):r}],[306,To],[40091,vi],[40092,vi],[40093,vi],[40094,vi],[40095,vi]]),$t(Re,"exif",[[40960,zn],[36864,zn],[36867,To],[36868,To],[40962,jn],[40963,jn]]),$t(Re,"gps",[[0,r=>Array.from(r).join(".")],[7,r=>Array.from(r).join(":")]]);var Ei=class extends Qt{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:Zt.from(t).getString()}parse(t=this.chunk){if(!this.localOptions.parse)return t;t=(function(s){let n={},a={};for(let c of ra)n[c]=[],a[c]=0;return s.replace(Nc,((c,h,p)=>{if(h==="<"){let d=++a[p];return n[p].push(d),`${c}#${d}`}return`${c}#${n[p].pop()}`}))})(t);let e=Mr.findAll(t,"rdf","Description");e.length===0&&e.push(new Mr("rdf","Description",void 0,t));let i,o={};for(let s of e)for(let n of s.properties)i=Fc(n.ns,o),ta(n,i);return(function(s){let n;for(let a in s)n=s[a]=Er(s[a]),n===void 0&&delete s[a];return Er(s)})(o)}assignToOutput(t,e){if(this.localOptions.parse)for(let[i,o]of Object.entries(e))switch(i){case"tiff":this.assignObjectToOutput(t,"ifd0",o);break;case"exif":this.assignObjectToOutput(t,"exif",o);break;case"xmlns":break;default:this.assignObjectToOutput(t,i,o)}else t.xmp=e}};st(Ei,"type","xmp"),st(Ei,"multiSegment",!0),At.set("xmp",Ei);var _o=class r{static findAll(t){return ea(t,/([a-zA-Z0-9-]+):([a-zA-Z0-9-]+)=("[^"]*"|'[^']*')/gm).map(r.unpackMatch)}static unpackMatch(t){let e=t[1],i=t[2],o=t[3].slice(1,-1);return o=ia(o),new r(e,i,o)}constructor(t,e,i){this.ns=t,this.name=e,this.value=i}serialize(){return this.value}},Mr=class r{static findAll(t,e,i){if(e!==void 0||i!==void 0){e=e||"[\\w\\d-]+",i=i||"[\\w\\d-]+";var o=new RegExp(`<(${e}):(${i})(#\\d+)?((\\s+?[\\w\\d-:]+=("[^"]*"|'[^']*'))*\\s*)(\\/>|>([\\s\\S]*?)<\\/\\1:\\2\\3>)`,"gm")}else o=/<([\w\d-]+):([\w\d-]+)(#\d+)?((\s+?[\w\d-:]+=("[^"]*"|'[^']*'))*\s*)(\/>|>([\s\S]*?)<\/\1:\2\3>)/gm;return ea(t,o).map(r.unpackMatch)}static unpackMatch(t){let e=t[1],i=t[2],o=t[4],s=t[8];return new r(e,i,o,s)}constructor(t,e,i,o){this.ns=t,this.name=e,this.attrString=i,this.innerXml=o,this.attrs=_o.findAll(i),this.children=r.findAll(o),this.value=this.children.length===0?ia(o):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 Oc(this.children.map(Uc));if(this.isListItem&&this.children.length===1&&this.attrs.length===0)return this.children[0].serialize();let t={};for(let e of this.properties)ta(e,t);return this.value!==void 0&&(t.value=this.value),Er(t)}};function ta(r,t){let e=r.serialize();e!==void 0&&(t[r.name]=e)}var Uc=r=>r.serialize(),Oc=r=>r.length===1?r[0]:r,Fc=(r,t)=>t[r]?t[r]:t[r]={};function ea(r,t){let e,i=[];if(!r)return i;for(;(e=t.exec(r))!==null;)i.push(e);return i}function ia(r){if((function(i){return i==null||i==="null"||i==="undefined"||i===""||i.trim()===""})(r))return;let t=Number(r);if(!Number.isNaN(t))return t;let e=r.toLowerCase();return e==="true"||e!=="false"&&r.trim()}var ra=["rdf:li","rdf:Seq","rdf:Bag","rdf:Alt","rdf:Description"],Nc=new RegExp(`(<|\\/)(${ra.join("|")})`,"g"),oa=Bc;var kt=r=>Math.round(r*1e6)/1e6,fe=r=>Math.max(0,Math.min(1,Number(r)||0));function Di(r){if(!r||typeof r!="object")return null;let t=["topLeft","topRight","bottomRight","bottomLeft"],e={};for(let i of t){let o=r[i];if(!o||typeof o!="object"||!Number.isFinite(Number(o.x))||!Number.isFinite(Number(o.y)))return null;e[i]={x:kt(fe(o.x)),y:kt(fe(o.y))}}return e}function Go(r){if(!r||typeof r!="object")return null;let t=fe(r.x),e=fe(r.y),i=fe(t+(Number(r.w)||0)),o=fe(e+(Number(r.h)||0));return{topLeft:{x:kt(t),y:kt(e)},topRight:{x:kt(i),y:kt(e)},bottomRight:{x:kt(i),y:kt(o)},bottomLeft:{x:kt(t),y:kt(o)}}}function Ri(r={}){let t=r&&r.crop&&typeof r.crop=="object"?{x:Math.max(0,Math.min(1,Number(r.crop.x)||0)),y:Math.max(0,Math.min(1,Number(r.crop.y)||0)),w:Math.max(0,Math.min(1,Number(r.crop.w)||1)),h:Math.max(0,Math.min(1,Number(r.crop.h)||1))}:null,e=Di(r?.quad),i=0,o=r?.rotate!==void 0?r.rotate:r?.rotation;if(o!==void 0){let n=(Math.round(Number(o)/90)*90%360+360)%360;(n===90||n===180||n===270)&&(i=n)}let s=r&&r.filter==="bw"?"bw":"none";return{crop:t,quad:e,rotate:i,filter:s}}function Ft(r,t){let e=fe(r.x),i=fe(r.y);return t===90?{x:kt(1-i),y:kt(e)}:t===180?{x:kt(1-e),y:kt(1-i)}:t===270?{x:kt(i),y:kt(1-e)}:{x:kt(e),y:kt(i)}}function Jo(r,t=0){let e=Di(r);if(!e)return null;let i=(Math.round(Number(t)/90)*90%360+360)%360;return i===90?{topLeft:Ft(e.bottomLeft,90),topRight:Ft(e.topLeft,90),bottomRight:Ft(e.topRight,90),bottomLeft:Ft(e.bottomRight,90)}:i===180?{topLeft:Ft(e.bottomRight,180),topRight:Ft(e.bottomLeft,180),bottomRight:Ft(e.topLeft,180),bottomLeft:Ft(e.topRight,180)}:i===270?{topLeft:Ft(e.topRight,270),topRight:Ft(e.bottomRight,270),bottomRight:Ft(e.bottomLeft,270),bottomLeft:Ft(e.topLeft,270)}:e}function Xo(r,t=0){return Jo(r,t)}function Qo(r,t=0){return Jo(r,-t)}function Hc(r){let{topLeft:t,topRight:e,bottomRight:i,bottomLeft:o}=r,s=Math.hypot(e.x-t.x,e.y-t.y),n=Math.hypot(i.x-o.x,i.y-o.y),a=Math.hypot(o.x-t.x,o.y-t.y),c=Math.hypot(i.x-e.x,i.y-e.y);return{width:Math.max(1,Math.round(Math.max(s,n))),height:Math.max(1,Math.round(Math.max(a,c)))}}function $c(r){let t=r.topLeft.x,e=r.topLeft.y,i=r.topRight.x,o=r.topRight.y,s=r.bottomRight.x,n=r.bottomRight.y,a=r.bottomLeft.x,c=r.bottomLeft.y,h=i-s,p=a-s,d=t-i+s-a,g=o-n,m=c-n,y=e-o+n-c,S=h*m-p*g,b=0,v=0;return Math.abs(S)>1e-12&&(b=(d*m-p*y)/S,v=(h*y-d*g)/S),{a:i-t+b*i,b:a-t+v*a,c:t,d:o-e+b*o,e:c-e+v*c,f:e,g:b,h:v}}function _c(r,t,e,i,o,s){let n=new Uint8ClampedArray(o*s*4),{a,b:c,c:h,d:p,e:d,f:g,g:m,h:y}=$c(i),S=t-1,b=e-1;for(let v=0;v<s;v++){let C=(v+.5)/s,k=c*C+h,T=d*C+g,B=y*C+1;for(let E=0;E<o;E++){let w=(E+.5)/o,D=m*w+B;if(Math.abs(D)<1e-12)continue;let H=(a*w+k)/D-.5,_=(p*w+T)/D-.5;H<0?H=0:H>S&&(H=S),_<0?_=0:_>b&&(_=b);let M=H|0,z=_|0,et=M<S?M+1:S,ot=z<b?z+1:b,at=H-M,G=_-z,R=1-at,N=1-G,tt=R*N,Q=at*N,O=R*G,V=at*G,K=(z*t+M)*4,Y=(z*t+et)*4,W=(ot*t+M)*4,X=(ot*t+et)*4,U=(v*o+E)*4;n[U]=Math.round(r[K]*tt+r[Y]*Q+r[W]*O+r[X]*V),n[U+1]=Math.round(r[K+1]*tt+r[Y+1]*Q+r[W+1]*O+r[X+1]*V),n[U+2]=Math.round(r[K+2]*tt+r[Y+2]*Q+r[W+2]*O+r[X+2]*V),n[U+3]=Math.round(r[K+3]*tt+r[Y+3]*Q+r[W+3]*O+r[X+3]*V)}}return n}function sa(r,t){let e=r.naturalWidth||r.width||0,i=r.naturalHeight||r.height||0;if(e<=0||i<=0){let y=document.createElement("canvas");return y.width=1,y.height=1,y}let o;typeof HTMLCanvasElement<"u"&&r instanceof HTMLCanvasElement?o=r:(o=document.createElement("canvas"),o.width=e,o.height=i,o.getContext("2d").drawImage(r,0,0,e,i));let n=o.getContext("2d").getImageData(0,0,e,i),a={topLeft:{x:t.topLeft.x*e,y:t.topLeft.y*i},topRight:{x:t.topRight.x*e,y:t.topRight.y*i},bottomRight:{x:t.bottomRight.x*e,y:t.bottomRight.y*i},bottomLeft:{x:t.bottomLeft.x*e,y:t.bottomLeft.y*i}},{width:c,height:h}=Hc(a),p=_c(n.data,e,i,a,c,h),d=document.createElement("canvas");d.width=c,d.height=h;let g=d.getContext("2d"),m=g.createImageData(c,h);return m.data.set(p),g.putImageData(m,0,0),d}async function na(r){try{return await oa.parse(r)||null}catch{return null}}function Ti(){return Array.from(crypto.getRandomValues(new Uint8Array(16)),r=>r.toString(16).padStart(2,"0")).join("")}async function aa(r){if(typeof createImageBitmap>"u"||typeof document>"u"){if(r&&typeof r.arrayBuffer=="function"){let a=await r.arrayBuffer(),c=globalThis.Buffer,h=typeof c<"u"?c.from(a).toString("base64"):btoa(String.fromCharCode(...new Uint8Array(a)));return`data:${r.type||"image/png"};base64,${h}`}if(typeof r=="string")return r}let t=await createImageBitmap(r),o=Math.min(1,1654/t.width,2339/t.height);if(o===1&&(r.type==="image/jpeg"||r.type==="image/jpg"||r.type==="image/png"||r.type==="image/webp"))return t.close(),new Promise((a,c)=>{let h=new FileReader;h.onload=()=>a(h.result),h.onerror=c,h.readAsDataURL(r)});let s=document.createElement("canvas");s.width=Math.round(t.width*o),s.height=Math.round(t.height*o),s.getContext("2d").drawImage(t,0,0,s.width,s.height),t.close();let n=r.type==="image/png"?"image/png":"image/jpeg";return s.toDataURL(n,n==="image/png"?void 0:.82)}function ca(r,t=21,e=.2,i=128){let{data:o,width:s,height:n}=r,a=s+1,c=new Float64Array((s+1)*(n+1)),h=new Float64Array((s+1)*(n+1)),p=new Uint8Array(s*n);for(let g=0;g<n;g++){let m=0,y=0,S=g*s,b=(g+1)*a,v=g*a;for(let C=0;C<s;C++){let k=(S+C)*4,T=o[k]*77+o[k+1]*150+o[k+2]*29>>8;p[S+C]=T,m+=T,y+=T*T,c[b+C+1]=c[v+C+1]+m,h[b+C+1]=h[v+C+1]+y}}let d=Math.floor(t/2);for(let g=0;g<n;g++){let m=Math.max(0,g-d),y=Math.min(n-1,g+d),S=m*a,b=(y+1)*a;for(let v=0;v<s;v++){let C=Math.max(0,v-d),k=Math.min(s-1,v+d),T=(k-C+1)*(y-m+1),B=c[b+k+1]-c[S+k+1]-c[b+C]+c[S+C],E=h[b+k+1]-h[S+k+1]-h[b+C]+h[S+C],w=B/T,D=Math.max(0,E/T-w*w),H=Math.sqrt(D),_=w*(1+e*(H/i-1)),M=g*s+v,z=p[M]<_?0:255,et=M*4;o[et]=z,o[et+1]=z,o[et+2]=z}}return r}function Br(r){if(!r||typeof r!="object")return{crop:null,quad:null,rotation:0,filter:"none"};let t=null;r.crop&&typeof r.crop=="object"&&(r.crop.width>0&&r.crop.height>0?t={x:Math.round(r.crop.x||0),y:Math.round(r.crop.y||0),width:Math.round(r.crop.width),height:Math.round(r.crop.height)}:r.crop.w>0&&r.crop.h>0&&(t={x:Number(r.crop.x)||0,y:Number(r.crop.y)||0,w:Number(r.crop.w)||1,h:Number(r.crop.h)||1}));let e=Di(r.quad),i=r.rotation!==void 0?r.rotation:r.rotate,o=(Math.round(Number(i)||0)%360+360)%360,s=r.filter==="bw"?"bw":"none";return{crop:t,quad:e,rotation:o,filter:s}}function jc(r){if(!r)return!1;let t=Br(r);return!!(t.crop||t.quad||t.rotation!==0||t.filter!=="none")}function Ur(r,t){let e=Br(t),i=r.naturalWidth||r.width||0,o=r.naturalHeight||r.height||0,s;if(e.quad)s=sa(r,e.quad);else{s=document.createElement("canvas");let a=i,c=o,h=0,p=0;if(e.crop){let g=e.crop;"w"in g&&!("width"in g)?(h=Math.max(0,Math.min(Math.round(g.x*i),i)),p=Math.max(0,Math.min(Math.round(g.y*o),o)),a=Math.max(1,Math.min(Math.round(g.w*i),i-h)),c=Math.max(1,Math.min(Math.round(g.h*o),o-p))):(h=Math.max(0,Math.min(g.x,i)),p=Math.max(0,Math.min(g.y,o)),a=Math.max(1,Math.min(g.width,i-h)),c=Math.max(1,Math.min(g.height,o-p)))}s.width=a,s.height=c,s.getContext("2d").drawImage(r,h,p,a,c,0,0,a,c)}let n=s;if(e.rotation!==0){let a=e.rotation,c=document.createElement("canvas");a===90||a===270?(c.width=n.height,c.height=n.width):(c.width=n.width,c.height=n.height);let h=c.getContext("2d");h.translate(c.width/2,c.height/2),h.rotate(a*Math.PI/180),h.drawImage(n,-n.width/2,-n.height/2),n=c}if(e.filter==="bw"){let a=n.getContext("2d"),c=a.getImageData(0,0,n.width,n.height);ca(c),a.putImageData(c,0,0)}return n}function la(r,t){if(!r)return Promise.resolve("");let e=Br(t);return jc(e)?new Promise((i,o)=>{let s=new Image;s.onload=()=>{try{let n=r.startsWith("data:image/png"),a=n?"image/png":"image/jpeg",c=Ur(s,e);i(c.toDataURL(a,n?void 0:.82))}catch(n){o(n)}},s.onerror=o,s.src=r}):Promise.resolve(r)}var Or=[{version:2,name:"v1-to-v2-noop",description:"Establishes baseline schema versioning and verifies stored document integrity.",async up(r){let t=await r.listDocs();for(let e of t)if(!(!e||!e.id)&&typeof e.pages=="string")try{JSON.parse(e.pages)}catch{e.pages="[]",await r.saveDoc(e.id,e)}}},{version:3,name:"v2-to-v3-quad-edits",description:"Normalizes page edit stacks to include edits.quad for perspective correction (CPO-075).",async up(r){let t=await r.listDocs();for(let e of t){if(!e||!e.id)continue;let i=e.pages,o=!1;if(typeof i=="string"){o=!0;try{i=JSON.parse(i)}catch{continue}}if(!Array.isArray(i))continue;let s=!1;for(let n of i)!n||typeof n!="object"||(!n.edits||typeof n.edits!="object"?(n.edits={crop:null,quad:null,rotate:0,filter:"none"},s=!0):"quad"in n.edits||(n.edits={...n.edits,quad:null},s=!0));s&&(e.pages=o?JSON.stringify(i):i,await r.saveDoc(e.id,e))}}}],Ye=class{static get CURRENT_VERSION(){return 3}static get DEFAULT_MIGRATIONS(){return[...Or]}static async run({storage:t,migrations:e=Or,targetVersion:i=3,onEvent:o,signal:s}){if(!t)throw new Error("MigrationRunner.run requires a valid storage adapter");if(s?.aborted)throw new Error("Migration aborted before execution");let n=await t.getSchemaVersion(),a=n;if(n==null){let d=await t.listDocs();if(!d||d.length===0){await t.setSchemaVersion(i);let g={fresh:!0,fromVersion:null,toVersion:i,applied:[]};return o?.({stage:"complete",...g}),g}a=1}if(a===i)return{fresh:!1,fromVersion:a,toVersion:i,applied:[]};if(a>i)return console.warn(`[CopioMigration] Storage schema version (${a}) is newer than target version (${i}).`),{fresh:!1,fromVersion:a,toVersion:i,applied:[]};let c=e.filter(d=>d.version>a&&d.version<=i).sort((d,g)=>d.version-g.version);if(c.length===0)return await t.setSchemaVersion(i),{fresh:!1,fromVersion:a,toVersion:i,applied:[]};o?.({stage:"start",fromVersion:a,toVersion:i,totalPending:c.length});let h=[];for(let d of c){if(s?.aborted){let g=new Error(`Migration aborted before version ${d.version}`);throw o?.({stage:"error",fromVersion:a,toVersion:i,failedVersion:d.version,error:g}),g}o?.({stage:"progress",version:d.version,name:d.name,fromVersion:a,toVersion:i});try{await d.up(t,{fromVersion:a,toVersion:d.version,signal:s}),await t.setSchemaVersion(d.version),a=d.version,h.push(d.version)}catch(g){throw o?.({stage:"error",fromVersion:a,toVersion:i,failedVersion:d.version,error:g}),g}}let p={fresh:!1,fromVersion:n??1,toVersion:a,applied:h};return o?.({stage:"complete",...p}),p}};var Ze=class{#t=null;#r=new Map;#n=new Map;constructor(t=Sr()){this.#t=t}get adapter(){return this.#t}get store(){return this.#t?.store??null}async init(){let t=await this.#t.init();return await Ye.run({storage:this.#t}),t}async getSchemaVersion(){return this.#t.getSchemaVersion()}listDocsSync(){return typeof this.#t.listDocsSync=="function"?this.#t.listDocsSync().map(e=>{let i=this.#i(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.#i(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 o=this.#t.getDocSync(t);return o?{id:o.id,name:o.name||"",pages:this.#i(o.pages)}:null}let i=this.listDocsSync().find(o=>o.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.#i(e.pages)}:null}return this.getDocSync(t)}async createDoc(t="Untitled Document",e=[]){let i=Ti(),o=this.#i(e),s={id:i,name:t||"Untitled Document",pages:o};return await this.#t.saveDoc(i,s),s}async saveDoc(t,e){if(!t)throw new Error("Cannot save document without an ID");let i=this.#i(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 o=this.getDocSync(t);if(o){if(this.#s(t),await this.#t.deleteDoc(t),e&&i>0){let s=setTimeout(async()=>{this.#r.delete(t)},i);this.#r.set(t,{doc:o,timerId:s})}return{id:t,name:o.name,undo:()=>this.undoDeleteDoc(t)}}}#s(t){if(this.#r.has(t)){let e=this.#r.get(t);clearTimeout(e.timerId),this.#r.delete(t)}}async undoDeleteDoc(t){let e=this.#r.get(t);return e?(clearTimeout(e.timerId),this.#r.delete(t),await this.#t.saveDoc(t,e.doc),e.doc):null}isSoftDeletedDoc(t){return this.#r.has(t)}async addPages(t,e){let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);let o=Array.isArray(e)?e:[e];i.pages.push(...o),await this.saveDoc(t,i)}async updatePage(t,e,i){let o=await this.getDoc(t);if(!o)throw new Error(`Document "${t}" not found`);let s=o.pages.findIndex(n=>n.id===e);if(s===-1)throw new Error(`Page "${e}" not found in document "${t}"`);o.pages[s]={...o.pages[s],...i},await this.saveDoc(t,o)}async reorderPages(t,e){let i=await this.getDoc(t);if(!i)throw new Error(`Document "${t}" not found`);let o=new Map(i.pages.map(n=>[n.id,n])),s=[];for(let n of e)o.has(n)&&(s.push(o.get(n)),o.delete(n));for(let n of o.values())s.push(n);i.pages=s,await this.saveDoc(t,i)}async deletePage(t,e,{soft:i=!0,timeoutMs:o=5e3}={}){let s=await this.getDoc(t);if(!s)throw new Error(`Document "${t}" not found`);let n=s.pages.findIndex(p=>p.id===e);if(n===-1)return;let[a]=s.pages.splice(n,1);await this.saveDoc(t,s);let c=`${t}:${e}`;if(this.#e(c),!i||o<=0){if(typeof this.#t.deletePage=="function")try{await this.#t.deletePage(t,e)}catch(p){console.warn("[DocRepository] Adapter deletePage error:",p)}return}let h=setTimeout(async()=>{if(this.#n.delete(c),typeof this.#t.deletePage=="function")try{await this.#t.deletePage(t,e)}catch(p){console.warn("[DocRepository] Adapter deletePage error:",p)}},o);return this.#n.set(c,{docId:t,pageId:e,page:a,index:n,timerId:h}),{docId:t,pageId:e,undo:()=>this.undoDeletePage(t,e)}}#e(t){if(this.#n.has(t)){let e=this.#n.get(t);clearTimeout(e.timerId),this.#n.delete(t)}}async undoDeletePage(t,e){let i=`${t}:${e}`,o=this.#n.get(i);if(!o)return null;clearTimeout(o.timerId),this.#n.delete(i);let s=await this.getDoc(t);if(!s)return null;let n=Math.min(o.index,s.pages.length);return s.pages.splice(n,0,o.page),await this.saveDoc(t,s),o.page}isSoftDeletedPage(t,e){return this.#n.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 o=await this.getDoc(i.id),s=[];for(let n of o?.pages||[]){if(!n){s.push(n);continue}let a={...n},c=a.blob instanceof Blob?a.blob:null;if(!c&&typeof a.src=="string"&&a.src.startsWith("blob:"))try{c=await(await fetch(a.src)).blob()}catch{}c&&(a.src=await Ao(c));let h=a.originalBlob instanceof Blob?a.originalBlob:null;if(!h&&typeof a.originalSrc=="string"&&a.originalSrc.startsWith("blob:"))try{h=await(await fetch(a.originalSrc)).blob()}catch{}h&&(a.originalSrc=await Ao(h)),delete a.blob,delete a.originalBlob,s.push(a)}e[i.id]={name:i.name,pages:JSON.stringify(s)}}return e}async importDocs(t){let e=0;for(let[i,o]of Object.entries(t||{})){await this.getDoc(i)||e++;let n=this.#i(o.pages);await this.saveDoc(i,{name:o.name||"",pages:n})}return e}#i(t){if(Array.isArray(t))return[...t];if(typeof t=="string")try{return JSON.parse(t)}catch{return[]}return[]}},zc=new Ze;Nr();var ht={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",HANDOFF_CONNECTED:"copio:handoff-connected",CONNECTION_INFO:"copio:connection-info",EDGE_DETECTED:"copio:edge-detected",MIGRATION:"copio:migration",ERROR:"copio:error"};function pa(r,t,e={}){let i=new CustomEvent(t,{bubbles:!0,composed:!0,cancelable:!0,detail:e});return r&&typeof r.dispatchEvent=="function"&&r.dispatchEvent(i),i}var Hr=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 ee=class extends Hr{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 $r=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 Me=class extends $r{async exportDocumentAsPdf(t,e,i={}){let o=new Error('Feature "pdf" is disabled or PDF module not opted in');throw o.code="FEATURE_DISABLED",o}async renderPdfPagesToDataUrls(t){return[]}};var fa=Object.freeze({topLeft:Object.freeze({x:.05,y:.05}),topRight:Object.freeze({x:.95,y:.05}),bottomRight:Object.freeze({x:.95,y:.95}),bottomLeft:Object.freeze({x:.05,y:.95})});function Mt(r=fa){return{topLeft:{x:Number(r.topLeft?.x??.05),y:Number(r.topLeft?.y??.05)},topRight:{x:Number(r.topRight?.x??.95),y:Number(r.topRight?.y??.05)},bottomRight:{x:Number(r.bottomRight?.x??.95),y:Number(r.bottomRight?.y??.95)},bottomLeft:{x:Number(r.bottomLeft?.x??.05),y:Number(r.bottomLeft?.y??.95)}}}function Bi(r){if(!r)return{x:.05,y:.05,w:.9,h:.9};let t=[r.topLeft,r.topRight,r.bottomRight,r.bottomLeft],e=Math.max(0,Math.min(...t.map(c=>Number(c?.x??0)))),i=Math.min(1,Math.max(...t.map(c=>Number(c?.x??1)))),o=Math.max(0,Math.min(...t.map(c=>Number(c?.y??0)))),s=Math.min(1,Math.max(...t.map(c=>Number(c?.y??1)))),n=Math.max(.01,Math.min(1-e,i-e)),a=Math.max(.01,Math.min(1-o,s-o));return{x:Math.round(e*1e3)/1e3,y:Math.round(o*1e3)/1e3,w:Math.round(n*1e3)/1e3,h:Math.round(a*1e3)/1e3}}var Mi=class{async detect(t,e={}){throw new Error("EdgeDetectorPort.detect() must be implemented by adapter")}async getEdgeWorker(){throw new Error("EdgeDetectorPort.getEdgeWorker() must be implemented by adapter")}async terminateEdgeWorker(){throw new Error("EdgeDetectorPort.terminateEdgeWorker() must be implemented by adapter")}};var _r=class extends Mi{#t=!1;constructor(t={}){super(),this.#t=!!t.throwOnDetect}async detect(t,e={}){if(this.#t){let i=new Error('Feature "edge" is disabled or EdgeDetector module not opted in');throw i.code="FEATURE_DISABLED",i}return null}async getEdgeWorker(){return null}async terminateEdgeWorker(){}};var Be=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 qc(r){return new Promise((t,e)=>{let i=new Image;i.onload=()=>t(i),i.onerror=e,i.src=r})}var Ui=class extends Be{async renderEdits(t,e={}){if(!t)return"";if(typeof document>"u")return t;try{let i=await qc(t),o={...e};return e?.crop&&"w"in e.crop&&(o.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&&(o.rotation=e.rotate),Ur(i,o).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 Oi=class extends Be{async renderEdits(t,e){return t}async crop(t,e){return t}async rotate(t,e){return t}async applyFilter(t,e){return t}};var es=["crop","rotate","filter","ocr","export","sync"],Zo=["pdf","zip","png","jpg"],ts=["eng"],ua={};function _t(r){return ua[r]?ua[r]:typeof globalThis<"u"&&globalThis.__copio_services__?.[r]?globalThis.__copio_services__[r]:null}function Gc(r){return r?r instanceof Set?new Set(r):Array.isArray(r)?new Set(r.map(t=>String(t).trim().toLowerCase()).filter(Boolean)):typeof r=="string"?new Set(r.split(/[\s,]+/).map(t=>t.trim().toLowerCase()).filter(Boolean)):new Set(es):new Set(es)}function jr(r,t){return r?Array.isArray(r)?r.map(e=>String(e).trim().toLowerCase()).filter(Boolean):typeof r=="string"?r.split(/[\s,]+/).map(e=>e.trim().toLowerCase()).filter(Boolean):[...t]:[...t]}var Fi=class extends EventTarget{#t=new Set(es);#r=[...Zo];#n=[...ts];#s=0;#e="";#i=null;#a=null;#l={};#o=!0;#p=!0;#h=null;#d=new Map;#u=new Map;#f=[...Or];#c=3;#m="";#y="";#g=null;#b="all";#w=null;constructor(t={}){super(),this.#i=t.storage||Sr(t),this.#a=t.repository||new Ze(this.#i),t.migrations&&(this.#f=[...t.migrations]),t.schemaVersion!==void 0&&(this.#c=t.schemaVersion),t.services&&(this.#l={...t.services}),t.imageProcessor?(this.#h=t.imageProcessor,this.#l.imageProcessor=t.imageProcessor):this.getService("imageProcessor")?this.#h=this.getService("imageProcessor"):typeof document<"u"?this.#h=new Ui:this.#h=new Oi,t.features!==void 0&&this.setFeatures(t.features),t.exportFormats!==void 0&&(this.#r=jr(t.exportFormats,Zo)),t.ocrLanguages!==void 0&&(this.#n=jr(t.ocrLanguages,ts)),t.maxPages!==void 0&&(this.#s=Math.max(0,Number(t.maxPages)||0)),t.assetBase!==void 0&&Li(t.assetBase),t.licenseKey!==void 0&&(this.#e=String(t.licenseKey||"")),t.ocr!==void 0?this.ocr=!!t.ocr:t.features!==void 0&&!this.hasFeature("ocr")&&(this.ocr=!1),t.pdf!==void 0?this.pdf=!!t.pdf:t.exportFormats!==void 0&&!this.#r.includes("pdf")&&(this.pdf=!1),t.relayUrl!==void 0&&(this.#m=String(t.relayUrl||"")),t.signalingUrl!==void 0&&(this.#y=String(t.signalingUrl||"")),t.iceServers!==void 0&&(this.#g=Array.isArray(t.iceServers)?t.iceServers:null),t.iceTransportPolicy!==void 0&&(this.#b=t.iceTransportPolicy||"all")}async init(){return this.#w?this.#w:(this.#w=(async()=>{try{let t=await this.#i.init(),e=await this.#I();return{...t,migration:e}}catch(t){throw this.#w=null,t}})(),this.#w)}async#I(){let t=e=>{let i={...e,engine:this};this.dispatchEvent(new CustomEvent(ht.MIGRATION,{detail:i})),typeof window<"u"&&typeof window.dispatchEvent=="function"&&window.dispatchEvent(new CustomEvent(ht.MIGRATION,{detail:i}))};return Ye.run({storage:this.#i,migrations:this.#f,targetVersion:this.#c,onEvent:t})}async#k(){this.#w?await this.#w:await this.init()}async getSchemaVersion(){return this.#i.getSchemaVersion()}setService(t,e){this.#l[t]=e}getService(t){return this.#l[t]||_t(t)}hasFeature(t){return t?this.#t.has(String(t).trim().toLowerCase()):!1}get features(){return Array.from(this.#t)}setFeatures(t){this.#t=Gc(t),this.hasFeature("ocr")?(this.#o=!0,this.getService("ocr")instanceof ee&&this.setService("ocr",_t("ocr"))):(this.#o=!1,this.setService("ocr",new ee))}enableFeature(t){if(t){let e=String(t).trim().toLowerCase();this.#t.add(e),e==="ocr"&&(this.#o=!0,this.getService("ocr")instanceof ee&&this.setService("ocr",_t("ocr")))}}disableFeature(t){if(t){let e=String(t).trim().toLowerCase();this.#t.delete(e),e==="ocr"&&(this.#o=!1,this.setService("ocr",new ee))}}get ocr(){return this.#o&&this.hasFeature("ocr")}set ocr(t){this.#o=!!t,this.#o?(this.enableFeature("ocr"),this.getService("ocr")instanceof ee&&this.setService("ocr",_t("ocr"))):(this.disableFeature("ocr"),this.setService("ocr",new ee))}get pdf(){return this.#p&&this.#r.includes("pdf")}set pdf(t){this.#p=!!t,this.#p?(this.#r.includes("pdf")||this.#r.push("pdf"),this.getService("pdf")instanceof Me&&this.setService("pdf",_t("pdf"))):(this.#r=this.#r.filter(e=>e!=="pdf"),this.setService("pdf",new Me))}get exportFormats(){return[...this.#r]}set exportFormats(t){this.#r=jr(t,Zo),this.#r.includes("pdf")?(this.#p=!0,this.getService("pdf")instanceof Me&&this.setService("pdf",_t("pdf"))):(this.#p=!1,this.setService("pdf",new Me))}get ocrLanguages(){return[...this.#n]}set ocrLanguages(t){this.#n=jr(t,ts)}get maxPages(){return this.#s}set maxPages(t){this.#s=Math.max(0,Number(t)||0)}get assetBase(){return ha()}set assetBase(t){Li(t)}get licenseKey(){return this.#e}set licenseKey(t){this.#e=String(t||"")}get relayUrl(){return this.#m}set relayUrl(t){this.#m=String(t||"")}get signalingUrl(){return this.#y}set signalingUrl(t){this.#y=String(t||"")}get iceServers(){return this.#g}set iceServers(t){this.#g=Array.isArray(t)?t:null}get iceTransportPolicy(){return this.#b}set iceTransportPolicy(t){this.#b=t||"all"}get edgeDetector(){return this.getService("edge")||_t("edge")||new _r}async detectEdges(t,e={}){let i=this.edgeDetector;return!i||typeof i.detect!="function"?null:i.detect(t,e)}get storage(){return this.#i}setStorage(t){t&&(this.#i=t,this.#a=new Ze(this.#i))}#T(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.#u.has(t)&&(this.#u.get(t).length=0)}get imageProcessor(){return this.#h}setImageProcessor(t){t&&(this.#h=t,this.setService("imageProcessor",t))}async renderEdits(t,e){if(!t)return"";let i=Ri(e);return this.#h?this.#h.renderEdits(t,i):la(t,i)}get docs(){return this.#a}async listDocuments(){return await this.#k(),this.#a.listDocs()}async getDocument(t){return await this.#k(),this.#a.getDoc(t)}async createDocument(t,e){return await this.#k(),this.#a.createDoc(t,e)}async deleteDocument(t,e={}){return await this.#k(),this.#a.deleteDoc(t,e)}async undoDeleteDocument(t){return await this.#k(),this.#a.undoDeleteDoc(t)}async renameDocument(t,e){return await this.#k(),this.#a.renameDoc(t,e)}async addPages(t,e){return await this.#k(),this.#a.addPages(t,e)}async deletePage(t,e,i={}){return await this.#k(),this.#T(t,{type:"delete",pageId:e}),this.#a.deletePage(t,e,i)}async undoDeletePage(t,e){return await this.#k(),this.#a.undoDeletePage(t,e)}async updatePage(t,e,i){return await this.#k(),this.#a.updatePage(t,e,i)}async reorderPages(t,e){let i=await this.getDocument(t),o=i?.pages?i.pages.map(s=>s.id):[];return this.#T(t,{type:"reorder",priorOrder:o,newOrder:[...e]}),this.#a.reorderPages(t,e)}async#M(t){if(t)return t;let e=await this.listDocuments();return e.length>0?e[0].id:null}async applyEdit(t,e,i){let o=await this.#M(t),s=o?await this.getDocument(o):null;if(!s||!s.pages)throw new Error(`Document with ID "${o||t}" not found`);let n=s.pages.find(y=>y.id===e);if(!n)throw new Error(`Page with ID "${e}" not found in document "${o}"`);let a=Ri(n.edits||{crop:null,quad:null,rotate:0,filter:"none"}),c=n.src,h=Ri({...a,...i}),p=n.originalSrc||n.src,d=p;this.#h&&(d=await this.#h.renderEdits(p,h));let g=a.rotate!==h.rotate||JSON.stringify(a.crop)!==JSON.stringify(h.crop)||JSON.stringify(a.quad)!==JSON.stringify(h.quad),m={originalSrc:p,src:d,edits:h,...g?{ocrText:null,ocrConfidence:null,ocrWords:null,ocrWidth:null,ocrHeight:null}:{}};return await this.updatePage(o,e,m),this.#T(o,{type:"edit",pageId:e,priorEdits:a,priorSrc:c,newEdits:h,newSrc:d}),{...n,...m}}async undo(t){let e=await this.#M(t),i=e?this.#d.get(e):null;if(!i||i.length===0)return null;let o=i.pop();return this.#u.has(e)||this.#u.set(e,[]),this.#u.get(e).push(o),o.type==="edit"?(await this.updatePage(e,o.pageId,{edits:o.priorEdits,src:o.priorSrc}),{type:"edit",pageId:o.pageId,restoredEdits:o.priorEdits}):o.type==="delete"?(await this.undoDeletePage(e,o.pageId),{type:"delete",pageId:o.pageId}):o.type==="reorder"?(await this.#a.reorderPages(e,o.priorOrder),{type:"reorder",priorOrder:o.priorOrder}):o}async redo(t){let e=await this.#M(t),i=e?this.#u.get(e):null;if(!i||i.length===0)return null;let o=i.pop();return this.#d.has(e)||this.#d.set(e,[]),this.#d.get(e).push(o),o.type==="edit"?(await this.updatePage(e,o.pageId,{edits:o.newEdits,src:o.newSrc}),{type:"edit",pageId:o.pageId,appliedEdits:o.newEdits}):o.type==="delete"?(await this.deletePage(e,o.pageId),{type:"delete",pageId:o.pageId}):o.type==="reorder"?(await this.reorderPages(e,o.newOrder),{type:"reorder",newOrder:o.newOrder}):o}subscribe(t){return this.#a.subscribe(t)}async addFiles(t,e=null,i={}){if(!t||t.length===0)return[];let o=Array.from(t),s=[];for(let a of o)if(a.type==="application/pdf"){let c=this.getService("pdf");if(c&&typeof c.renderPdfPagesToDataUrls=="function"){let h=await c.renderPdfPagesToDataUrls(a);for(let p of h)s.push({id:Ti(),src:p,originalSrc:p,edits:{crop:null,rotation:0,filter:"none"},type:"image",name:a.name||"PDF Page"})}else console.warn("PDF import service (PdfPort) not registered. Skipping PDF file.")}else if(a.type&&a.type.startsWith("image/")){let c=await aa(a),h=null;try{h=await na(a)}catch{}let p={crop:null,rotation:0,filter:"none"};if(i.prefilledQuad)p.quad=Mt(i.prefilledQuad),p.crop=Bi(i.prefilledQuad);else if(i.autoCrop)try{let m=this.getService("edge");if(m&&typeof m.detect=="function"){let y=await m.detect(c);y&&y.quad&&y.confidence>=.45&&!y.isFallback&&(p.quad=Mt(y.quad),p.crop=Bi(y.quad))}}catch{}let d=Ri(p),g=c;(d.quad||d.crop)&&this.#h&&(g=await this.#h.renderEdits(c,d)),s.push({id:Ti(),src:g,originalSrc:c,edits:d,type:"image",name:a.name||"Captured Image",orientation:h})}if(s.length===0)return[];await this.init();let n=e;if(n)await this.getDocument(n)||await this.#a.saveDoc(n,{name:"Scanned Document",pages:[]});else{let a=await this.listDocuments();a.length>0?n=a[0].id:n=(await this.createDocument("Scanned Document",[])).id}if(this.#s>0){let a=(await this.getDocument(n))?.pages||[],c=Math.max(0,this.#s-a.length);if(c<=0)throw new Error(`Maximum page limit (${this.#s}) reached`);s.splice(c)}return await this.addPages(n,s),s}async getPages(t=null){let e=t;if(!e){let o=await this.listDocuments();if(o.length===0)return[];e=o[0].id}return(await this.getDocument(e))?.pages||[]}async clear(t=null){let e=t;if(!e){let o=await this.listDocuments();if(o.length===0)return;e=o[0].id}let i=await this.getDocument(e);if(!(!i||!i.pages))for(let o of i.pages)await this.deletePage(e,o.id)}async#v(t){if(Array.isArray(t))return{docName:"document",pages:t,docId:null};if(typeof t=="string"){let i=await this.getDocument(t);return{docName:i?.name||"document",pages:i?.pages||[],docId:t}}let e=await this.listDocuments();if(e.length>0){let i=await this.getDocument(e[0].id);return{docName:i?.name||"document",pages:i?.pages||[],docId:e[0].id}}return{docName:"document",pages:[],docId:null}}async exportPdf(t,e={}){if(!this.hasFeature("export")){let n=new Error('Feature "export" is disabled');throw Object.assign(n,{code:"FEATURE_DISABLED"}),n}if(!this.#p||!this.#r.includes("pdf")){let n=new Error('Feature "pdf" is disabled');throw Object.assign(n,{code:"FEATURE_DISABLED"}),n}let{docName:i,pages:o}=await this.#v(t),s=this.getService("pdf")||this.getService("export");if(!s||typeof s.exportDocumentAsPdf!="function")throw new Error("Export service (PdfPort) is not registered. Import @copio/sdk or register an exportService.");return s.exportDocumentAsPdf(i,o,{download:!1,showProgress:!1,onOcrComplete:async()=>{if(typeof t=="string"){let n=await this.#i.getDoc(t);n&&(n.pages=o,await this.#i.saveDoc(t,n))}},...e})}async exportZip(t,e={}){if(!this.hasFeature("export")){let n=new Error('Feature "export" is disabled');throw Object.assign(n,{code:"FEATURE_DISABLED"}),n}let{docName:i,pages:o}=await this.#v(t),s=this.getService("export");if(!s||typeof s.exportDocumentAsImages!="function")throw new Error("Export service is not registered. Import @copio/sdk or register an exportService.");return s.exportDocumentAsImages(i,o,{download:!1,showProgress:!1,...e})}async runOcr(t,e=null,i={}){if(!this.#o||!this.hasFeature("ocr")){let h=new Error('Feature "ocr" is disabled');throw Object.assign(h,{code:"FEATURE_DISABLED"}),h}let{pages:o}=await this.#v(t),s=o;e&&(s=o.filter(h=>h.id===e));let n=this.getService("ocr");if(!n||typeof n.recognizeDocumentPages!="function")throw new Error("OCR service (OcrPort) is not registered. Import @copio/sdk or register an ocrService.");let a=i.lang||this.#n[0]||"eng",c=await n.recognizeDocumentPages(s,{lang:a,...i});if(Array.isArray(c.pagesResults)){for(let h of c.pagesResults){let p=s.find(d=>d.id===h.pageId)||s[h.pageIndex];p&&(p.ocrText=h.text,p.ocrConfidence=h.confidence,p.ocrWords=h.words)}if(typeof t=="string"){let h=await this.#i.getDoc(t);if(h&&Array.isArray(h.pages)){for(let p of c.pagesResults){let d=h.pages.find(g=>g.id===p.pageId)||h.pages[p.pageIndex];d&&(d.ocrText=p.text,d.ocrConfidence=p.confidence,d.ocrWords=p.words)}await this.#i.saveDoc(t,h)}}}return{text:c.combinedText,...c}}async sync(t={}){if(!this.hasFeature("sync")){let i=new Error('Feature "sync" is disabled');throw Object.assign(i,{code:"FEATURE_DISABLED"}),i}let e=this.getService("sync");if(!e)throw new Error("Sync service (SyncPort) is not registered. Import @copio/sdk or register a syncService.");return new e(this.#a,t.onStateChange)}};Nr();var ya=null,ga={success:{slVariant:"success",defaultIcon:"check-circle",defaultDuration:3e3},error:{slVariant:"danger",defaultIcon:"exclamation-octagon",defaultDuration:5e3},danger:{slVariant:"danger",defaultIcon:"exclamation-octagon",defaultDuration:5e3},warning:{slVariant:"warning",defaultIcon:"exclamation-triangle",defaultDuration:4e3},info:{slVariant:"primary",defaultIcon:"info-circle",defaultDuration:4e3},primary:{slVariant:"primary",defaultIcon:"info-circle",defaultDuration:4e3},neutral:{slVariant:"neutral",defaultIcon:"info-circle",defaultDuration:4e3}};function ti(r){ya=r||null}function ei(){return ya||(typeof document<"u"?document.body:null)}function Jc(){let t=customElements.get("sl-alert")?.toastStack;t&&t.querySelectorAll("sl-alert").forEach(i=>{typeof i.hide=="function"&&i.hide()})}async function ma(r,t={}){let e={};if(typeof r=="string"||r instanceof HTMLElement?e={message:r,...t}:r&&typeof r=="object"&&(e={...r,...t}),typeof customElements<"u"&&!customElements.get("sl-alert")&&await Promise.race([customElements.whenDefined("sl-alert"),new Promise(d=>setTimeout(d,200))]),typeof customElements>"u"||!customElements.get("sl-alert"))return null;let i=customElements.get("sl-alert"),o=e.variant||"info",s=ga[o]||ga.info,n=e.container||ei();if(i?.toastStack&&n){let d=i.toastStack;d.parentElement!==n&&n.appendChild(d),n!==document.body?(d.style.position="absolute",d.style.width="auto",d.style.maxWidth="calc(100% - 24px)",d.style.left="12px",d.style.right="12px",d.style.insetInlineStart="12px",d.style.insetInlineEnd="12px",e.position==="top"?(d.style.top="12px",d.style.bottom="auto"):(d.style.top="auto",d.style.bottom="16px"),d.style.maxHeight="100%",d.style.overflow="auto"):(d.style.position="",d.style.width="",d.style.left="",d.style.right="",d.style.top="",d.style.bottom="",d.style.insetInlineStart="",d.style.insetInlineEnd="",d.style.maxHeight="",d.style.maxWidth="",d.style.overflow="")}let a=document.createElement("sl-alert");a.variant=s.slVariant,a.closable=e.closable!==!1,a.duration=e.duration!==void 0?e.duration:s.defaultDuration;let c=e.icon!==void 0?e.icon:s.defaultIcon;if(c){let d=document.createElement("sl-icon");d.slot="icon",d.name=c,a.appendChild(d)}let h=document.createElement("span");if(e.message instanceof HTMLElement?h.appendChild(e.message):e.html?h.innerHTML=e.message||"":h.textContent=e.message||"",e.action){let d=document.createElement("div");d.style.display="flex",d.style.alignItems="center",d.style.justifyContent="space-between",d.style.gap="0.75rem",d.style.width="100%",h.style.flex="1",d.appendChild(h);let g=document.createElement("sl-button");g.size="small",g.variant=e.action.variant||"text",g.textContent=e.action.text||"Action",g.style.color="inherit",g.style.fontWeight="600",g.style.padding="0",g.addEventListener("click",m=>{m.preventDefault(),m.stopPropagation(),typeof e.action.onClick=="function"&&e.action.onClick(m,a),e.action.autoClose!==!1&&a.hide()}),d.appendChild(g),a.appendChild(d)}else a.appendChild(h);let p=a.toast();return a.toastPromise=p,a}function Xc(r,t={}){return jt.show({message:r,variant:"success",...t})}function Qc(r,t={}){return jt.show({message:r,variant:"error",...t})}function Yc(r,t={}){return jt.show({message:r,variant:"warning",...t})}function Zc(r,t={}){return jt.show({message:r,variant:"info",...t})}function tl(r,t,e={}){return jt.show({message:r,variant:e?.variant||"primary",icon:e?.icon!==void 0?e.icon:"arrow-counterclockwise",duration:e?.duration!==void 0?e.duration:5e3,closable:e?.closable!==!1,action:{text:e?.actionText||"Undo",onClick:(i,o)=>{typeof t=="function"&&t(i,o)},autoClose:!0},...e})}async function el(r,t={}){let e={};if(typeof r=="string"?e={message:r,...t}:r&&typeof r=="object"&&(e={...r,...t}),typeof customElements<"u"&&(!customElements.get("sl-alert")||!customElements.get("sl-progress-bar"))&&await Promise.race([Promise.all([customElements.whenDefined("sl-alert"),customElements.whenDefined("sl-progress-bar")]),new Promise(S=>setTimeout(S,200))]),typeof customElements>"u"||!customElements.get("sl-alert"))return{alert:null,progressBar:null,update(){},close(){}};let i=e.container||ei(),o=document.createElement("sl-alert");o.variant=e.variant||"primary",o.closable=e.closable===!0,o.duration=1/0;let s=e.icon!==void 0?e.icon:"arrow-down-circle";if(s){let S=document.createElement("sl-icon");S.slot="icon",S.name=s,o.appendChild(S)}let n=document.createElement("div");n.className="notify-progress-wrapper",n.style.display="flex",n.style.flexDirection="column",n.style.gap="0.35rem",n.style.minWidth="220px";let a=document.createElement("div");a.style.display="flex",a.style.justifyContent="space-between",a.style.alignItems="center",a.style.gap="0.5rem";let c=document.createElement("span");c.className="notify-progress-message",c.style.fontWeight="500",c.style.fontSize="0.9rem",c.textContent=e.message||"Processing...",a.appendChild(c);let h=document.createElement("span");h.className="notify-progress-status",h.style.fontSize="0.78rem",h.style.color="#64748b",h.style.fontWeight="600";let p=e.done!==void 0?e.done:0,d=e.total!==void 0?e.total:0;d>0?h.textContent=`${p} / ${d}`:e.value!==void 0&&(h.textContent=`${e.value}%`),a.appendChild(h),n.appendChild(a);let g=document.createElement("sl-progress-bar");d>0?g.value=Math.round(p/d*100):e.value!==void 0?g.value=e.value:g.indeterminate=!0,n.appendChild(g),o.appendChild(n);let m=customElements.get("sl-alert");if(m?.toastStack&&i){let S=m.toastStack;S.parentElement!==i&&i.appendChild(S)}return o.toast(),{alert:o,progressBar:g,update({done:S,total:b,value:v,message:C}={}){if(C!==void 0&&(c.textContent=C),b!==void 0&&S!==void 0){g.indeterminate=!1;let k=Math.min(100,Math.max(0,Math.round(S/Math.max(b,1)*100)));g.value=k,h.textContent=`${S} / ${b}`}else v!==void 0&&(g.indeterminate=!1,g.value=Math.min(100,Math.max(0,v)),h.textContent=`${Math.round(g.value)}%`)},close(){typeof o.hide=="function"&&o.hide()}}}var jt=Object.assign(function(r,t){return ma(r,t)},{show:ma,success:Xc,error:Qc,warning:Yc,info:Zc,undo:tl,progress:el,clear:Jc,setContainer:ti,getContainer:ei});var is=`:host{all:initial;display:block;position:relative;width:100%;height:100%;min-height:200px;container-type:size;container-name:copio-scanner;overflow:hidden;contain:layout;box-sizing:border-box;text-align:left;direction:ltr;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;--copio-font-family:'Inter',-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;--copio-font-mono:'JetBrains Mono','SFMono-Regular',Consolas,'Liberation Mono',monospace;--copio-color-bg:#0b0f17;--copio-color-surface:#131b26;--copio-color-surface-elevated:#1c2736;--copio-color-surface-overlay:rgba(15,22,32,0.88);--copio-color-stage-bg:#070a0f;--copio-color-text:#f1f5f9;--copio-color-text-muted:#94a3b8;--copio-color-text-inverse:#090d14;--copio-color-primary:#38bdf8;--copio-color-primary-hover:#7dd3fc;--copio-color-primary-contrast:#06131f;--copio-color-success:#22c55e;--copio-color-warning:#f59e0b;--copio-color-danger:#ef4444;--copio-color-border:rgba(148,163,184,0.18);--copio-color-border-strong:rgba(148,163,184,0.34);--copio-focus-ring:0 0 2px #0b0f17,0 0 0 4px #38bdf8;--copio-radius-sm:6px;--copio-radius-md:10px;--copio-radius-lg:14px;--copio-radius-pill:9999px;--copio-spacing-xs:4px;--copio-spacing-sm:8px;--copio-spacing-md:12px;--copio-spacing-lg:16px;--copio-spacing-xl:24px;--copio-touch-target-min:44px;--copio-crop-handle-hit:48px;--copio-crop-handle-visual:16px;--copio-shadow-elevated:0 12px 32px -4px rgba(0,0,0,0.55);--copio-transition-fast:150ms cubic-bezier(0.22,1,0.36,1);--copio-transition-normal:240ms cubic-bezier(0.22,1,0.36,1);font-family:var(--copio-font-family);font-size:14px;line-height:1.5;color:var(--copio-color-text);background-color:var(--copio-color-bg);color-scheme:dark}:host([theme="dark"]),:host(.copio-theme-dark),:host-context([data-theme="dark"]),:host-context(.sl-theme-dark),:host-context(.theme-dark){color-scheme:dark}:host([theme="light"]),:host(.copio-theme-light),:host-context([data-theme="light"]),:host-context(.sl-theme-light),:host-context(.theme-light){--copio-color-bg:#f8fafc;--copio-color-surface:#ffffff;--copio-color-surface-elevated:#f1f5f9;--copio-color-surface-overlay:rgba(255,255,255,0.92);--copio-color-stage-bg:#1e293b;--copio-color-text:#0f172a;--copio-color-text-muted:#475569;--copio-color-text-inverse:#ffffff;--copio-color-primary:#0284c7;--copio-color-primary-hover:#0369a1;--copio-color-primary-contrast:#ffffff;--copio-color-success:#16a34a;--copio-color-warning:#d97706;--copio-color-danger:#dc2626;--copio-color-border:rgba(15,23,42,0.12);--copio-color-border-strong:rgba(15,23,42,0.26);--copio-focus-ring:0 0 2px #ffffff,0 0 0 4px #0284c7;--copio-radius-sm:6px;--copio-radius-md:10px;--copio-radius-lg:14px;--copio-shadow-elevated:0 12px 28px -4px rgba(15,23,42,0.18);color-scheme:light}:host([theme="brand"]),:host(.copio-theme-brand),:host-context([data-theme="brand"]),:host-context(.theme-brand){--copio-color-bg:#0f111a;--copio-color-surface:#181b28;--copio-color-surface-elevated:#23273a;--copio-color-surface-overlay:rgba(24,27,40,0.90);--copio-color-stage-bg:#090a10;--copio-color-text:#f8fafc;--copio-color-text-muted:#9ca3af;--copio-color-text-inverse:#ffffff;--copio-color-primary:#10b981;--copio-color-primary-hover:#34d399;--copio-color-primary-contrast:#042f2e;--copio-color-success:#10b981;--copio-color-warning:#f59e0b;--copio-color-danger:#ef4444;--copio-color-border:rgba(16,185,129,0.22);--copio-color-border-strong:rgba(16,185,129,0.42);--copio-focus-ring:0 0 2px #0f111a,0 0 0 4px #10b981;--copio-radius-sm:4px;--copio-radius-md:8px;--copio-radius-lg:12px;--copio-shadow-elevated:0 12px 32px -4px rgba(0,0,0,0.65);color-scheme:dark}@media (prefers-color-scheme:light){:host([theme="auto"]),:host(.copio-theme-auto){--copio-color-bg:#f8fafc;--copio-color-surface:#ffffff;--copio-color-surface-elevated:#f1f5f9;--copio-color-surface-overlay:rgba(255,255,255,0.92);--copio-color-stage-bg:#1e293b;--copio-color-text:#0f172a;--copio-color-text-muted:#475569;--copio-color-text-inverse:#ffffff;--copio-color-primary:#0284c7;--copio-color-primary-hover:#0369a1;--copio-color-primary-contrast:#ffffff;--copio-color-success:#16a34a;--copio-color-warning:#d97706;--copio-color-danger:#dc2626;--copio-color-border:rgba(15,23,42,0.12);--copio-color-border-strong:rgba(15,23,42,0.26);--copio-focus-ring:0 0 2px #ffffff,0 0 0 4px #0284c7;--copio-radius-sm:6px;--copio-radius-md:10px;--copio-radius-lg:14px;--copio-shadow-elevated:0 12px 28px -4px rgba(15,23,42,0.18);color-scheme:light}}*,*::before,*::after{box-sizing:border-box}::slotted(*){box-sizing:border-box}.copio-scanner-container{width:100%;height:100%;position:relative;display:flex;flex-direction:column;overflow:hidden;box-sizing:border-box;container-type:size;container-name:copio-scanner;contain:layout;background:var(--copio-color-bg);color:var(--copio-color-text);font-family:var(--copio-font-family);font-size:14px;line-height:1.5;text-align:left;direction:ltr;user-select:none}.copio-header{display:flex;align-items:center;justify-content:space-between;gap:var(--copio-spacing-sm);padding:var(--copio-spacing-sm) var(--copio-spacing-md);background:var(--copio-color-surface);border-bottom:1px solid var(--copio-color-border);min-height:52px;flex-shrink:0;z-index:5;box-sizing:border-box}.copio-header-left{display:flex;align-items:center;gap:var(--copio-spacing-sm);min-width:0}.copio-mode-badge{display:inline-flex;align-items:center;gap:5px;font-size:11px;font-weight:600;padding:4px 8px;border-radius:var(--copio-radius-pill);background:var(--copio-color-surface-elevated);color:var(--copio-color-primary);border:1px solid var(--copio-color-border);white-space:nowrap}.copio-title-group{display:flex;flex-direction:column;min-width:0}.copio-title{font-size:13px;font-weight:600;color:var(--copio-color-text);margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.copio-subtitle{font-size:11px;color:var(--copio-color-text-muted);margin:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.copio-header-actions{display:flex;align-items:center;gap:6px;flex-shrink:0}.copio-stage-tabs{display:inline-flex;background:var(--copio-color-bg);padding:2px;border-radius:var(--copio-radius-md);border:1px solid var(--copio-color-border)}.copio-stage-tab{appearance:none;border:none;background:transparent;color:var(--copio-color-text-muted);font-family:inherit;font-size:11px;font-weight:600;padding:6px 10px;min-height:var(--copio-touch-target-min);min-width:var(--copio-touch-target-min);border-radius:var(--copio-radius-sm);cursor:pointer;display:inline-flex;align-items:center;justify-content:center;transition:background var(--copio-transition-fast),color var(--copio-transition-fast)}.copio-stage-tab[aria-selected="true"]{background:var(--copio-color-surface-elevated);color:var(--copio-color-text);box-shadow:0 1px 3px rgba(0,0,0,0.25)}.copio-btn{appearance:none;border:1px solid var(--copio-color-border);background:var(--copio-color-surface-elevated);color:var(--copio-color-text);font-family:inherit;font-size:13px;font-weight:600;min-height:var(--copio-touch-target-min);min-width:var(--copio-touch-target-min);padding:0 12px;border-radius:var(--copio-radius-md);display:inline-flex;align-items:center;justify-content:center;gap:7px;cursor:pointer;transition:all var(--copio-transition-fast);white-space:nowrap;text-decoration:none;box-sizing:border-box}.copio-btn:hover{background:var(--copio-color-primary-hover);color:var(--copio-color-primary-contrast);border-color:var(--copio-color-primary)}.copio-btn-primary{background:var(--copio-color-primary);color:var(--copio-color-primary-contrast);border-color:var(--copio-color-primary)}.copio-btn-danger{background:rgba(239,68,68,0.15);color:var(--copio-color-danger);border-color:rgba(239,68,68,0.35)}.copio-btn-danger:hover{background:var(--copio-color-danger);color:#fff}.copio-viewfinder,.copio-viewfinder-stage{position:relative;flex:1 1 auto;display:flex;flex-direction:column;justify-content:space-between;background:var(--copio-color-stage-bg);overflow:hidden;min-height:0;width:100%}.copio-viewfinder-feed,.copio-camera-feed{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;padding:56px 20px 104px 20px;background:radial-gradient(circle at 50% 45%,#1e293b 0%,#090d14 75%)}.copio-camera-feed.is-shutter-flash::after{content:'';position:absolute;inset:0;background:#ffffff;opacity:0.75;pointer-events:none;z-index:5;animation:copio-shutter-flash 150ms ease-out forwards}@keyframes copio-shutter-flash{0%{opacity:0.75}100%{opacity:0}}.copio-framing-guide{position:relative;display:flex;align-items:center;justify-content:center;max-width:100%;max-height:100%;border:1.5px dashed rgba(56,189,248,0.55);border-radius:12px;box-shadow:0 0 9999px rgba(4,7,12,0.52);transition:all var(--copio-transition-normal);overflow:hidden}.copio-framing-guide[data-aspect="receipt"]{aspect-ratio:1 / 2.1;height:100%}.copio-framing-guide[data-aspect="card"]{aspect-ratio:1.586 / 1;width:92%;max-height:82%}.copio-framing-guide[data-aspect="a4"]{aspect-ratio:1 / 1.414;height:96%}.copio-framing-guide[data-aspect="auto"]{width:94%;height:94%}.copio-corner{position:absolute;width:22px;height:22px;border-color:var(--copio-color-primary);border-style:solid;border-width:0;pointer-events:none;z-index:2}.copio-corner.tl{top:6px;left:6px;border-top-width:3px;border-left-width:3px;border-top-left-radius:6px}.copio-corner.tr{top:6px;right:6px;border-top-width:3px;border-right-width:3px;border-top-right-radius:6px}.copio-corner.bl{bottom:6px;left:6px;border-bottom-width:3px;border-left-width:3px;border-bottom-left-radius:6px}.copio-corner.br{bottom:6px;right:6px;border-bottom-width:3px;border-right-width:3px;border-bottom-right-radius:6px}.copio-edge-quad{position:absolute;inset:12px;border:1px solid rgba(56,189,248,0.28);border-radius:8px;background:rgba(56,189,248,0.04);pointer-events:none;z-index:1}.copio-live-quad-overlay{position:absolute;inset:0;width:100%;height:100%;pointer-events:none;z-index:10;overflow:visible}.copio-live-quad-polygon{fill:rgba(56,189,248,0.18);stroke:var(--copio-color-primary,#38bdf8);stroke-width:3;vector-effect:non-scaling-stroke;stroke-linecap:round;stroke-linejoin:round;filter:drop-shadow(0 0 6px rgba(56,189,248,0.45))}.copio-live-quad-corner{fill:#ffffff;stroke:var(--copio-color-primary,#38bdf8);stroke-width:2.5;filter:drop-shadow(0 0 4px rgba(0,0,0,0.4))}.copio-camera-feed.is-detected .copio-live-quad-polygon{fill:rgba(34,197,94,0.22);stroke:#22c55e;filter:drop-shadow(0 0 8px rgba(34,197,94,0.6))}.copio-camera-feed.is-detected .copio-live-quad-corner{stroke:#22c55e}.copio-camera-feed.is-tracking .copio-edge-quad{opacity:0.1;transition:opacity var(--copio-transition-fast)}.copio-camera-placeholder{position:relative;z-index:2;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;padding:16px;text-align:center;color:var(--copio-color-text-muted);font-size:12px;font-weight:500;cursor:pointer;user-select:none;transition:color var(--copio-transition-fast),transform var(--copio-transition-fast)}.copio-camera-placeholder:hover{color:var(--copio-color-text);transform:scale(1.02)}.copio-status-dot{width:7px;height:7px;border-radius:50%;background:var(--copio-color-primary);box-shadow:0 8px var(--copio-color-primary);flex-shrink:0}.copio-viewfinder-hud-top{position:relative;z-index:3;display:flex;align-items:center;justify-content:space-between;gap:8px;padding:10px 14px;background:linear-gradient(to bottom,rgba(7,10,15,0.85),transparent)}.copio-step-pill{display:inline-flex;align-items:center;gap:6px;padding:5px 12px;border-radius:var(--copio-radius-pill);background:rgba(15,23,42,0.88);border:1px solid rgba(56,189,248,0.45);color:#f8fafc;font-size:12px;font-weight:600;box-shadow:0 4px 12px rgba(0,0,0,0.35)}.copio-privacy-pill{display:inline-flex;align-items:center;gap:5px;padding:4px 9px;border-radius:var(--copio-radius-pill);background:rgba(22,101,52,0.35);border:1px solid rgba(34,197,94,0.4);color:#86efac;font-size:11px;font-weight:500}.copio-shutter-dock{position:relative;z-index:3;display:flex;align-items:center;justify-content:space-between;gap:12px;padding:12px 16px calc(12px + env(safe-area-inset-bottom,0)) 16px;background:var(--copio-color-surface);border-top:1px solid var(--copio-color-border);min-height:84px;flex-shrink:0}.copio-shutter-side{flex:1;display:flex;align-items:center}.copio-shutter-side.right{justify-content:flex-end}.copio-shutter-btn{appearance:none;width:64px;height:64px;border-radius:var(--copio-radius-pill);border:4px solid var(--copio-color-primary);background:transparent;padding:4px;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;transition:transform var(--copio-transition-fast),border-color 150ms ease;flex-shrink:0}.copio-shutter-btn:hover{transform:scale(1.04)}.copio-shutter-btn:active{transform:scale(0.94)}.copio-shutter-btn-inner,.copio-shutter-inner{width:100%;height:100%;border-radius:var(--copio-radius-pill);background:var(--copio-color-primary);display:flex;align-items:center;justify-content:center;color:var(--copio-color-primary-contrast);transition:transform var(--copio-transition-fast)}.copio-shutter-btn:active .copio-shutter-btn-inner,.copio-shutter-btn:active .copio-shutter-inner{transform:scale(0.88)}.copio-stack-pill{display:inline-flex;align-items:center;gap:8px;min-height:var(--copio-touch-target-min);padding:4px 12px 4px 6px;border-radius:var(--copio-radius-md);background:var(--copio-color-surface-elevated);border:1px solid var(--copio-color-primary);color:var(--copio-color-text);font-size:12px;font-weight:600;cursor:pointer}.copio-stack-thumb{width:30px;height:36px;border-radius:4px;object-fit:cover;border:1px solid rgba(255,255,255,0.35);background:#000}.copio-workbench,.copio-workbench-stage{position:relative;flex:1 1 auto;display:flex;flex-direction:column;background:var(--copio-color-bg);overflow:hidden;min-height:0;width:100%}.copio-workbench-main{flex:1;display:flex;flex-direction:column;min-height:0;width:100%;overflow:hidden}.copio-stage-canvas,.copio-canvas-viewport{position:relative;flex:1 1 auto;display:flex;flex-direction:column;align-items:center;justify-content:center;overflow:hidden;padding:16px 20px 44px 20px;background:var(--copio-color-stage-bg);min-height:180px}.copio-canvas-viewport.is-cropping{padding:24px}.copio-canvas-viewport.has-card-switcher{padding-top:66px}.copio-card-side-switcher{position:absolute;top:8px;left:50%;transform:translateX(-50%);z-index:6;display:inline-flex;gap:4px;padding:3px;background:var(--copio-color-surface-overlay,rgba(15,22,32,0.88));border:1px solid var(--copio-color-border-strong);border-radius:var(--copio-radius-pill);backdrop-filter:blur(8px)}.copio-side-pill{appearance:none;border:none;background:transparent;color:var(--copio-color-text-muted);font-family:inherit;font-size:11px;font-weight:600;padding:6px 12px;min-height:var(--copio-touch-target-min);min-width:var(--copio-touch-target-min);border-radius:var(--copio-radius-pill);cursor:pointer;display:inline-flex;align-items:center;justify-content:center}.copio-side-pill[aria-selected="true"]{background:var(--copio-color-primary);color:var(--copio-color-primary-contrast)}.copio-stage-figure,.copio-canvas-wrapper{position:relative;display:flex;align-items:center;justify-content:center;max-width:100%;max-height:100%}.copio-stage-canvas img,.copio-stage-img,.copio-stage-image{display:block;max-width:100%;max-height:100%;width:auto;height:auto;object-fit:contain;box-shadow:var(--copio-shadow-elevated);border-radius:var(--copio-radius-sm);user-select:none}.copio-crop-layer{position:absolute;inset:0;width:100%;height:100%;overflow:visible;z-index:8;touch-action:none}.copio-crop-box{position:absolute;border:2px solid var(--copio-color-primary);box-shadow:0 0 9999px rgba(5,8,14,0.68);cursor:move;touch-action:none;box-sizing:border-box}.copio-crop-grid{position:absolute;inset:0;pointer-events:none;background-image:linear-gradient(to right,rgba(56,189,248,0.28) 1px,transparent 1px),linear-gradient(to bottom,rgba(56,189,248,0.28) 1px,transparent 1px);background-size:33.333% 33.333%}.copio-crop-handle{position:absolute;width:var(--copio-crop-handle-hit);height:var(--copio-crop-handle-hit);min-width:44px;min-height:44px;display:flex;align-items:center;justify-content:center;z-index:10;touch-action:none;box-sizing:border-box}.copio-crop-handle::after{content:'';width:var(--copio-crop-handle-visual);height:var(--copio-crop-handle-visual);border-radius:50%;background:var(--copio-color-primary);border:2.5px solid #ffffff;box-shadow:0 2px 6px rgba(0,0,0,0.5);transition:transform 120ms ease;box-sizing:border-box}.copio-crop-handle:hover::after,.copio-crop-handle:active::after{transform:scale(1.25);background:var(--copio-color-success,#22c55e)}.copio-crop-handle.nw{top:-24px;left:-24px;cursor:nwse-resize}.copio-crop-handle.ne{top:-24px;right:-24px;cursor:nesw-resize}.copio-crop-handle.sw{bottom:-24px;left:-24px;cursor:nesw-resize}.copio-crop-handle.se{bottom:-24px;right:-24px;cursor:nwse-resize}.copio-crop-handle.n,.copio-crop-handle.edge-n{top:-24px;left:calc(50% - 24px);cursor:ns-resize}.copio-crop-handle.s,.copio-crop-handle.edge-s{bottom:-24px;left:calc(50% - 24px);cursor:ns-resize}.copio-crop-handle.w,.copio-crop-handle.edge-w{left:-24px;top:calc(50% - 24px);cursor:ew-resize}.copio-crop-handle.e,.copio-crop-handle.edge-e{right:-24px;top:calc(50% - 24px);cursor:ew-resize}.copio-crop-quad-svg{position:absolute;inset:0;width:100%;height:100%;pointer-events:none;overflow:visible}.copio-crop-mask{fill:rgba(5,8,14,0.68)}.copio-crop-quad-outline{fill:rgba(56,189,248,0.06);stroke:var(--copio-color-primary);stroke-width:2;vector-effect:non-scaling-stroke;pointer-events:auto;cursor:move}.copio-crop-quad-grid{stroke:rgba(56,189,248,0.35);stroke-width:1;vector-effect:non-scaling-stroke;pointer-events:none}.copio-quad-handle{transform:translate(-50%,-50%);cursor:grab}.copio-quad-handle:active{cursor:grabbing}.copio-crop-magnifier{position:absolute;width:96px;height:96px;border-radius:50%;border:2.5px solid var(--copio-color-primary);box-shadow:0 4px 16px rgba(0,0,0,0.55);pointer-events:none;z-index:20;display:none;background:#0b0f17;transform:translate(-50%,-125%)}.copio-filmstrip,.copio-filmstrip-bar{display:flex;align-items:center;gap:8px;padding:8px 12px;background:var(--copio-color-surface);border-top:1px solid var(--copio-color-border);overflow-x:auto;min-height:80px;flex-shrink:0;scrollbar-width:thin}.copio-filmstrip-scroll{display:flex;align-items:center;gap:8px}.copio-filmstrip-item{display:flex;flex-direction:column;align-items:center;gap:4px;flex-shrink:0}.copio-thumb-container{position:relative;width:56px;height:70px;border-radius:var(--copio-radius-sm);overflow:hidden;background:var(--copio-color-surface-elevated,#1c2736);border:2px solid var(--copio-color-border);cursor:pointer;transition:all var(--copio-transition-fast);display:flex;align-items:center;justify-content:center}.copio-filmstrip-item.is-active .copio-thumb-container{border-color:var(--copio-color-primary);box-shadow:0 0 2px rgba(56,189,248,0.25)}.copio-thumb-num{position:absolute;bottom:3px;right:3px;min-width:16px;height:16px;padding:0 4px;border-radius:999px;background:rgba(15,23,42,0.85);color:#f8fafc;font-size:10px;font-weight:700;display:inline-flex;align-items:center;justify-content:center}.copio-thumb-reorder{display:flex;align-items:center;gap:4px}.copio-reorder-btn{appearance:none;border:1px solid var(--copio-color-border);background:var(--copio-color-surface-elevated);color:var(--copio-color-text-muted);border-radius:4px;font-size:9px;padding:2px 5px;cursor:pointer}.copio-reorder-btn:disabled{opacity:0.35;cursor:not-allowed}.copio-thumb-img{max-width:100%;max-height:100%;width:auto;height:auto;object-fit:contain}.copio-toolbar,.copio-controls-dock{display:flex;flex-direction:column;gap:8px;padding:10px 12px calc(10px + env(safe-area-inset-bottom,0)) 12px;background:var(--copio-color-surface);border-top:1px solid var(--copio-color-border);min-height:56px;flex-shrink:0;z-index:6}.copio-edit-toolbar,.copio-toolbar-tools{display:flex;flex-wrap:wrap;align-items:center;gap:4px;width:100%}.copio-toolbar-tools .copio-tool-btn{flex:1 1 0;min-width:0}.copio-toolbar-actions{display:flex;align-items:center;gap:8px;width:100%;flex-shrink:0}.copio-toolbar-actions .copio-btn-primary{width:100%}.copio-tool-btn{appearance:none;border:1px solid var(--copio-color-border);background:var(--copio-color-surface-elevated);color:var(--copio-color-text);font-family:inherit;font-size:11px;font-weight:600;min-height:var(--copio-touch-target-min);min-width:var(--copio-touch-target-min);padding:4px 6px;border-radius:var(--copio-radius-md);display:flex;flex-direction:column;align-items:center;justify-content:center;gap:3px;cursor:pointer;transition:all var(--copio-transition-fast)}.copio-tool-btn:hover:not(:disabled){border-color:var(--copio-color-border-strong);background:rgba(255,255,255,0.06)}.copio-tool-btn[aria-pressed="true"]{background:rgba(56,189,248,0.16);color:var(--copio-color-primary);border-color:var(--copio-color-primary)}.copio-tool-btn.danger{color:#fca5a5}.copio-tool-btn.danger:hover:not(:disabled){background:rgba(239,68,68,0.16);border-color:rgba(239,68,68,0.45)}.copio-toast-region{position:absolute;bottom:124px;left:12px;right:12px;z-index:30;display:flex;flex-direction:column;gap:8px;pointer-events:none}.copio-toast{pointer-events:auto;display:flex;align-items:center;justify-content:space-between;gap:10px;padding:8px 12px;border-radius:var(--copio-radius-md);background:#0f172a;color:#f8fafc;border:1px solid var(--copio-color-primary);box-shadow:var(--copio-shadow-elevated);font-size:12px;font-weight:500;position:relative;overflow:hidden;transition:opacity 200ms ease-out}.copio-toast-warning{border-color:#f59e0b;background:#1c1917;color:#fef3c7}.copio-toast-info{border-color:var(--copio-color-primary);background:#0f172a;color:#f8fafc}.copio-toast-fade-out{opacity:0}.copio-toast-progress{position:absolute;bottom:0;left:0;height:3px;background:var(--copio-color-primary);transition:width 100ms linear}.copio-toast-undo-btn,.copio-btn-toast-undo{appearance:none;border:1px solid rgba(56,189,248,0.45);background:rgba(56,189,248,0.16);color:#38bdf8;font-family:inherit;font-size:12px;font-weight:700;min-height:var(--copio-touch-target-min);min-width:var(--copio-touch-target-min);padding:0 12px;border-radius:var(--copio-radius-sm);cursor:pointer;flex-shrink:0}.copio-ocr-content{display:flex;flex-direction:column;gap:8px}.copio-ocr-text{margin:0;padding:10px;max-height:180px;overflow:auto;background:var(--copio-color-bg);color:var(--copio-color-text);border:1px solid var(--copio-color-border);border-radius:var(--copio-radius-sm);font-family:var(--copio-font-mono);font-size:11px;line-height:1.5;white-space:pre-wrap}.copio-ocr-meta{font-size:11px;color:var(--copio-color-text-muted)}.copio-ocr-sheet{position:absolute;inset:auto 0 0 0;max-height:78%;background:var(--copio-color-surface);border-top:1px solid var(--copio-color-primary);border-radius:16px 16px 0 0;box-shadow:0 -16px 40px rgba(0,0,0,0.65);z-index:25;display:flex;flex-direction:column;padding:14px;gap:10px}.copio-ocr-header{display:flex;align-items:center;justify-content:space-between;gap:8px}.copio-ocr-textarea{width:100%;min-height:130px;flex:1;resize:none;background:var(--copio-color-bg);color:var(--copio-color-text);border:1px solid var(--copio-color-border);border-radius:var(--copio-radius-sm);padding:10px;font-family:var(--copio-font-mono);font-size:11px;line-height:1.5}.sl-toast-stack,.copio-toast-stack-scoped{position:absolute !important;top:auto !important;bottom:0 !important;left:0 !important;right:0 !important;width:100% !important;max-width:100% !important;padding:var(--copio-spacing-md) !important;box-sizing:border-box !important;z-index:1000 !important;pointer-events:none}.sl-toast-stack sl-alert,.copio-toast-stack-scoped sl-alert{pointer-events:auto;margin-top:var(--copio-spacing-sm)}@container copio-scanner (max-width:400px){.copio-header{padding:6px 10px;min-height:52px}.copio-header-left{flex-direction:column;align-items:flex-start;gap:2px}.copio-mode-badge{font-size:10px;padding:2px 6px}.copio-subtitle{display:none}.copio-stage-canvas,.copio-canvas-viewport{min-height:120px;padding:12px}.copio-canvas-viewport.is-cropping{padding:20px}.copio-filmstrip,.copio-filmstrip-bar{gap:6px;padding:6px 8px;min-height:64px}.copio-toolbar,.copio-controls-dock{gap:6px;padding:8px 10px calc(8px + env(safe-area-inset-bottom,0)) 10px}.copio-tool-btn{font-size:10px;padding:3px 4px}.copio-btn{padding:0 8px;font-size:12px}}@container copio-scanner (min-width:401px) and (max-width:767px){.copio-header{padding:var(--copio-spacing-sm) var(--copio-spacing-md)}.copio-tool-btn{flex-direction:row;font-size:12px;gap:6px}}@container copio-scanner (min-width:768px){.copio-header{padding:var(--copio-spacing-md) var(--copio-spacing-lg)}.copio-workbench-main{flex-direction:row}.copio-filmstrip,.copio-filmstrip-bar{order:-1;flex-direction:column;width:168px;height:100%;border-top:none;border-right:1px solid var(--copio-color-border);overflow-y:auto;overflow-x:hidden;padding:12px}.copio-filmstrip-scroll{flex-direction:column;width:100%}.copio-thumb-container{width:112px;height:140px}.copio-toolbar,.copio-controls-dock{flex-direction:row;align-items:center;justify-content:space-between}.copio-toolbar-tools{width:auto;flex:1;gap:6px}.copio-toolbar-tools .copio-tool-btn{flex:1 1 56px;min-width:var(--copio-touch-target-min)}.copio-toolbar-actions{width:auto;min-width:200px}}.copio-handoff-pill{display:inline-flex;align-items:center;gap:6px;padding:4px 10px;background:rgba(2,132,199,0.16);border:1px solid rgba(56,189,248,0.35);border-radius:var(--copio-radius-pill);font-size:11px;font-weight:600;color:var(--copio-color-text);backdrop-filter:blur(8px)}.copio-handoff-dot{width:8px;height:8px;border-radius:50%;background:var(--copio-color-warning);display:inline-block;flex-shrink:0}.copio-handoff-dot.connected{background:var(--copio-color-success);box-shadow:0 8px rgba(34,197,94,0.6)}.copio-handoff-dot.connecting,.copio-handoff-dot.reconnecting{background:var(--copio-color-warning);animation:copio-pulse 1.4s ease-in-out infinite}.copio-handoff-dot.disconnected,.copio-handoff-dot.error{background:var(--copio-color-danger)}.copio-handoff-retry-btn{appearance:none;border:none;background:var(--copio-color-surface-elevated);color:var(--copio-color-text);font-size:10px;font-weight:600;padding:2px 6px;border-radius:var(--copio-radius-sm);cursor:pointer}.copio-handoff-progress-view,.copio-handoff-confirm{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;padding:var(--copio-spacing-xl)}.copio-handoff-progress-view{z-index:50;background:var(--copio-color-surface-overlay,rgba(15,22,32,0.92));backdrop-filter:blur(12px)}.copio-handoff-confirm{z-index:60;background:var(--copio-color-bg)}.copio-handoff-progress-card,.copio-handoff-confirm-card{width:100%;max-width:340px;background:var(--copio-color-surface);border:1px solid var(--copio-color-border-strong);border-radius:var(--copio-radius-lg);padding:var(--copio-spacing-xl);display:flex;flex-direction:column;align-items:center;text-align:center;gap:var(--copio-spacing-md);box-shadow:var(--copio-shadow-elevated)}.copio-handoff-spinner{width:32px;height:32px;border:3px solid rgba(148,163,184,0.2);border-top-color:var(--copio-color-primary);border-radius:50%;animation:copio-spin 0.8s linear infinite}.copio-handoff-progress-title,.copio-handoff-confirm-title{font-size:16px;font-weight:700;color:var(--copio-color-text);margin:0}.copio-handoff-progress-track{width:100%;height:8px;background:var(--copio-color-surface-elevated);border-radius:var(--copio-radius-pill);overflow:hidden;border:1px solid var(--copio-color-border)}.copio-handoff-progress-bar{height:100%;background:linear-gradient(90deg,var(--copio-color-primary),#0284c7);border-radius:var(--copio-radius-pill);transition:width var(--copio-transition-fast)}.copio-handoff-progress-desc,.copio-handoff-confirm-subtitle{font-size:12px;color:var(--copio-color-text-muted);margin:0}.copio-handoff-confirm-icon{width:56px;height:56px;border-radius:50%;background:rgba(34,197,94,0.15);color:var(--copio-color-success);border:1px solid rgba(34,197,94,0.35);display:flex;align-items:center;justify-content:center}.copio-handoff-confirm-badge{display:inline-flex;align-items:center;padding:4px 12px;background:var(--copio-color-surface-elevated);border:1px solid var(--copio-color-border);border-radius:var(--copio-radius-pill);font-size:12px;font-weight:600;color:var(--copio-color-primary)}.copio-handoff-confirm-actions{width:100%;display:flex;flex-direction:column;gap:8px;margin-top:8px}`,Ni=null;function ba(){if(Ni)return Ni;if(typeof CSSStyleSheet<"u"&&typeof Document<"u"&&"adoptedStyleSheets"in Document.prototype&&"replaceSync"in CSSStyleSheet.prototype)try{return Ni=new CSSStyleSheet,Ni.replaceSync(is),Ni}catch{return null}return null}function wa(r){if(!r)return;let t=ba();if(t&&"adoptedStyleSheets"in r){let e=r.adoptedStyleSheets||[];e.includes(t)||(r.adoptedStyleSheets=[...e,t])}else if(!r.querySelector("style[data-copio-encapsulated-styles]")){let e=document.createElement("style");e.setAttribute("data-copio-encapsulated-styles",""),e.textContent=is,r.appendChild(e)}}ns();var pl=typeof HTMLElement<"u"?HTMLElement:class{},cs=class extends pl{#t=null;#r=null;#n=null;#s=!1;#e="viewfinder";#i=0;#a=0;#l=!1;#o=!1;#p=null;#h=null;#d=0;#u=null;#f=null;#c=null;#m=!1;#y=null;#g=!0;#b="ml";#w=!0;#I=!1;#k=null;#T=!1;#M=0;#v=null;#A=null;#B=0;#N=0;#R=0;#O=null;#S=null;#U=null;#x="idle";#j=[];#$=null;#z=0;onShutter=null;get#P(){return this.docId?this.docId:(this.#f||(this.#f=`doc_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,6)}`),this.#f)}static get observedAttributes(){return["mode","aspect","stage","doc-id","features","export-formats","ocr-languages","max-pages","asset-base","license-key","theme","ocr","pdf","handoff","relay-url","ice-servers","signaling-url","ice-transport-policy","edge-detection","edge-model","auto-crop","auto-capture"]}constructor(){super(),typeof this.attachShadow=="function"&&this.attachShadow({mode:"open"}),this.#ct()}#ct(){let t={storage:this.#r};if(typeof this.getAttribute=="function"){this.hasAttribute("features")&&(t.features=this.getAttribute("features")),this.hasAttribute("export-formats")&&(t.exportFormats=this.getAttribute("export-formats")),this.hasAttribute("ocr-languages")&&(t.ocrLanguages=this.getAttribute("ocr-languages")),this.hasAttribute("max-pages")&&(t.maxPages=this.getAttribute("max-pages")),this.hasAttribute("asset-base")&&(t.assetBase=this.getAttribute("asset-base")),this.hasAttribute("license-key")&&(t.licenseKey=this.getAttribute("license-key")),this.hasAttribute("ocr")&&(t.ocr=this.getAttribute("ocr")!=="false"),this.hasAttribute("pdf")&&(t.pdf=this.getAttribute("pdf")!=="false"),this.hasAttribute("edge-detection")&&(this.#g=this.getAttribute("edge-detection")!=="false"),this.hasAttribute("edge-model")&&(this.#b=this.getAttribute("edge-model")==="classical"?"classical":"ml"),this.hasAttribute("auto-crop")&&(this.#w=this.getAttribute("auto-crop")!=="false"),this.hasAttribute("auto-capture")&&(this.#I=this.getAttribute("auto-capture")!=="false"&&this.getAttribute("auto-capture")!==null);for(let e of["relay-url","signaling-url","ice-transport-policy"])this.hasAttribute(e)&&(t[e.replace(/-([a-z])/g,(i,o)=>o.toUpperCase())]=this.getAttribute(e));if(this.hasAttribute("ice-servers"))try{t.iceServers=JSON.parse(this.getAttribute("ice-servers"))}catch{t.iceServers=[{urls:this.getAttribute("ice-servers")}]}}this.#t=new Fi(t),this.#t.addEventListener(ht.MIGRATION,e=>{this.dispatch(ht.MIGRATION,e.detail)})}connectedCallback(){this.shadowRoot&&(wa(this.shadowRoot),this.#lt()),typeof ti=="function"&&typeof document<"u"&&ei()===document.body&&ti(this.shadowRoot?.querySelector(".copio-scanner-container")||this),typeof document<"u"&&document.addEventListener("visibilitychange",this.#K),typeof window<"u"&&window.addEventListener("pagehide",this.#G),this.#t&&(this.#t.init().catch(t=>{console.error("[CopioScanner] Engine initialization failed:",t)}),this.#n=this.#t.subscribe(async()=>{let t=await this.getPages();this.dispatch(ht.PAGES_CHANGED,{pages:t,docId:this.docId}),this.#E()})),this.hasAttribute&&this.hasAttribute("asset-base")&&Li(this.getAttribute("asset-base")),this.#H()&&this.#st().catch(t=>{console.warn("[CopioScanner] Handoff init error:",t)}),this.#F(),this.#E()}disconnectedCallback(){if(typeof document<"u"&&document.removeEventListener("visibilitychange",this.#K),typeof window<"u"&&window.removeEventListener("pagehide",this.#G),this.#q(),this.#L(),this.#y&&(this.#y.width=0,this.#y.height=0,this.#y=null),typeof this.#n=="function"&&(this.#n(),this.#n=null),this.#h&&(clearInterval(this.#h),this.#h=null),typeof ti=="function"&&typeof document<"u"){let t=this.shadowRoot?.querySelector(".copio-scanner-container")||this;ei()===t&&ti(null)}}#K=()=>{typeof document<"u"&&document.visibilityState==="hidden"?this.#c&&(this.#m=!0,this.#L()):typeof document<"u"&&document.visibilityState==="visible"&&(this.#m&&this.#e==="viewfinder"&&(this.#m=!1,this.startCamera().catch(()=>{})),this.#H()&&this.#S&&!this.#S.isConnected&&this.#x!=="complete"&&this.reconnectHandoff().catch(()=>{}))};#G=()=>{this.#L()};attributeChangedCallback(t,e,i){if(!(e===i||!this.#t))switch(t){case"features":this.#t.setFeatures(i),this.#F();break;case"export-formats":this.#t.exportFormats=i,this.#F();break;case"ocr-languages":this.#t.ocrLanguages=i;break;case"asset-base":this.#t.assetBase=i;break;case"license-key":this.#t.licenseKey=i;break;case"ocr":this.#t.ocr=i!=="false",this.#F();break;case"pdf":this.#t.pdf=i!=="false",this.#F();break;case"relay-url":case"signaling-url":case"ice-transport-policy":this.#t&&(this.#t[t.replace(/-([a-z])/g,(o,s)=>s.toUpperCase())]=i);break;case"ice-servers":if(this.#t)try{this.#t.iceServers=JSON.parse(i)}catch{this.#t.iceServers=i?[{urls:i}]:null}break;case"stage":if(i==="viewfinder"||i==="workbench"){this.#e=i,i==="workbench"&&this.#L();let o=this.shadowRoot;if(o){let s=o.getElementById("viewfinder-section"),n=o.getElementById("workbench-section");s&&n&&(s.style.display=i==="viewfinder"?"flex":"none",n.style.display=i==="workbench"?"flex":"none")}this.#E()}break;case"max-pages":this.#t.maxPages=i,this.#E();break;case"mode":case"aspect":case"theme":this.#E();break;case"handoff":i&&i!=="false"?this.#st().catch(()=>{}):i==="false"&&this.#q();break;case"edge-detection":this.edgeDetection=i!=="false";break;case"edge-model":this.edgeModel=i==="classical"?"classical":"ml";break;case"auto-crop":this.autoCrop=i!=="false";break;case"auto-capture":this.autoCapture=i!=="false"&&i!==null;break}}#F(){if(typeof this.querySelectorAll!="function")return;let t=[];this.shadowRoot&&t.push(this.shadowRoot),t.push(this);for(let e of t){let i=e.querySelectorAll("copio-carousel, copio-row, copio-images");for(let o of i)"ocr"in o&&(o.ocr=this.ocrEnabled),"pdf"in o&&(o.pdf=this.pdf)}}#lt(){if(!this.shadowRoot||this.shadowRoot.innerHTML)return;let t="Align Document Inside Frame";this.aspect==="card"?t="Step 1 of 2: Capture Front of ID Card":this.mode==="batch"&&(t="Batch Capture \xB7 Page 1"),this.shadowRoot.innerHTML=`<div class="copio-scanner-container copio-scanner-host" part="scanner-root"><header class="copio-header" part="header"><div class="copio-header-left"><span class="copio-mode-badge" id="mode-badge">${(this.mode||"single").toUpperCase()}</span><div class="copio-title-group"><h2 class="copio-title" id="header-title">Copio Scanner</h2><p class="copio-subtitle" id="header-subtitle">Non-destructive mobile document scanner</p></div></div><div class="copio-header-actions" part="header-actions"><div class="copio-stage-tabs" role="tablist" aria-label="Scanner Stage"><button type="button" class="copio-stage-tab" id="tab-viewfinder" role="tab" aria-selected="true">Camera</button><button type="button" class="copio-stage-tab" id="tab-workbench" role="tab" aria-selected="false">Workbench</button></div><slot name="header-actions"></slot></div></header><div class="copio-viewfinder copio-viewfinder-stage" part="viewfinder" id="viewfinder-section"><div class="copio-viewfinder-hud-top"><div class="copio-step-pill" id="step-pill"><span class="copio-status-dot"></span><span id="step-pill-text">${t}</span></div><div class="copio-handoff-pill" id="handoff-pill" style="display:none;" title="Phone-to-Desktop Handoff"><span class="copio-handoff-dot" id="handoff-dot"></span><span class="copio-handoff-status-text" id="handoff-status-text">Paired with computer</span><button type="button" class="copio-handoff-retry-btn" id="btn-handoff-retry" style="display:none;" title="Retry connection">Retry</button></div><div class="copio-privacy-pill" title="100% Local On-Device Processing"><span>\u{1F512} 100% Local</span></div></div><div class="copio-camera-feed" id="camera-feed"><video id="camera-video" autoplay playsinline webkit-playsinline muted style="display:none; position:absolute; inset:0; width:100%; height:100%; object-fit:cover; z-index:0;"></video><svg class="copio-live-quad-overlay" id="live-quad-overlay" style="display:none;" aria-hidden="true"><polygon class="copio-live-quad-polygon" id="live-quad-polygon" points=""></polygon><circle class="copio-live-quad-corner" id="live-quad-c0" r="5"></circle><circle class="copio-live-quad-corner" id="live-quad-c1" r="5"></circle><circle class="copio-live-quad-corner" id="live-quad-c2" r="5"></circle><circle class="copio-live-quad-corner" id="live-quad-c3" r="5"></circle></svg><slot name="viewfinder"><div class="copio-framing-guide" id="framing-guide" data-aspect="${this.aspect}"><span class="copio-corner tl"></span><span class="copio-corner tr"></span><span class="copio-corner bl"></span><span class="copio-corner br"></span><div class="copio-edge-quad"></div><div class="copio-camera-placeholder"><svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg><span>Position document within guide lines</span></div></div></slot></div><div class="copio-shutter-dock" part="shutter-dock"><div class="copio-shutter-side left"><button type="button" class="copio-btn copio-btn-secondary" id="btn-import-file" title="Import image from file"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" y1="3" x2="12" y2="15"/></svg><span>Import</span></button></div><slot name="shutter-dock"><button type="button" class="copio-shutter-btn" id="btn-shutter" aria-label="Capture page"><span class="copio-shutter-btn-inner"></span></button></slot><div class="copio-shutter-side right"><button type="button" class="copio-stack-pill" id="btn-review" title="Review pages" style="display:none;"><span id="review-pill-text">Review (0) \u2192</span></button></div></div></div><div class="copio-workbench copio-workbench-stage" part="workbench" id="workbench-section" style="display: none;"><div class="copio-workbench-main"><div class="copio-canvas-viewport" id="canvas-viewport"><div class="copio-card-side-switcher" id="card-side-switcher" style="display:none;" role="tablist" aria-label="Card side switcher"><button type="button" role="tab" class="copio-side-pill active" id="btn-card-front" aria-selected="true">1. Front Side</button><button type="button" role="tab" class="copio-side-pill" id="btn-card-back" aria-selected="false">2. Back Side</button></div><div class="copio-canvas-wrapper" id="canvas-wrapper"><img id="stage-img" class="copio-stage-image" alt="Active document page" /></div></div><div class="copio-filmstrip" id="filmstrip-tray" part="filmstrip"><div class="copio-filmstrip-scroll" id="filmstrip-scroll"><slot name="filmstrip"></slot></div></div></div><footer class="copio-toolbar" part="toolbar" id="workbench-toolbar"><div class="copio-toolbar-tools"><button type="button" class="copio-tool-btn" id="btn-retake" title="Retake page"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M23 4v6h-6M1 20v-6h6"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/></svg><span>Retake</span></button><button type="button" class="copio-tool-btn" id="btn-crop" title="Adjust crop"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 2v14a2 2 0 0 0 2 2h14"/><path d="M18 22V8a2 2 0 0 0-2-2H2"/></svg><span id="crop-btn-label">Crop</span></button><button type="button" class="copio-tool-btn" id="btn-rotate" title="Rotate 90\xB0"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21.5 2v6h-6M21.34 15.57a10 10 0 1 1-.57-8.38l5.67-5.67"/></svg><span>Rotate</span></button><button type="button" class="copio-tool-btn" id="btn-filter-bw" title="Toggle B&W filter"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><path d="M12 2a10 10 0 0 1 0 20z" fill="currentColor"/></svg><span>B&W</span></button><button type="button" class="copio-tool-btn" id="btn-ocr" title="Recognize text"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 7V4h16v3M9 20h6M12 4v16"/></svg><span>OCR</span></button><button type="button" class="copio-tool-btn copio-btn-danger" id="btn-delete" title="Delete active page"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/></svg><span>Delete</span></button></div><div class="copio-toolbar-actions"><slot name="toolbar"><button type="button" class="copio-btn copio-btn-primary" id="btn-primary-complete"> \u2713 Use Photo </button></slot></div></footer><div class="copio-ocr-sheet" id="ocr-sheet" style="display:none;" part="ocr-sheet"><div class="copio-ocr-header"><strong class="copio-ocr-title">Text Recognition (OCR)</strong><button type="button" class="copio-btn copio-btn-secondary" id="btn-close-ocr">\u2715</button></div><div class="copio-ocr-body" id="ocr-body"><p class="copio-ocr-placeholder">Select text or extract full page data...</p></div></div><div class="copio-toast-region" id="toast-region" aria-live="polite"></div></div><div class="copio-handoff-progress-view" id="handoff-progress-view" style="display: none;" part="handoff-progress"><div class="copio-handoff-progress-card"><div class="copio-handoff-spinner"></div><h4 class="copio-handoff-progress-title" id="handoff-progress-title">Sending to your computer\u2026</h4><div class="copio-handoff-progress-track"><div class="copio-handoff-progress-bar" id="handoff-progress-bar" style="width: 0%;"></div></div><p class="copio-handoff-progress-desc" id="handoff-progress-desc">Encrypting and streaming pages\u2026</p></div></div><div class="copio-handoff-confirm" id="handoff-confirm-view" style="display: none;" part="handoff-confirm"><div class="copio-handoff-confirm-card"><div class="copio-handoff-confirm-icon"><svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><path d="M20 6L9 17l-5-5"/></svg></div><h3 class="copio-handoff-confirm-title">Sent to your computer</h3><p class="copio-handoff-confirm-subtitle">You can close this tab now.</p><div class="copio-handoff-confirm-badge" id="handoff-confirm-count">1 page transferred</div><div class="copio-handoff-confirm-actions"><button type="button" class="copio-btn copio-btn-secondary" id="btn-handoff-scan-more"> Scan More Documents </button></div></div></div><input type="file" id="internal-file-input" accept="image/*" style="display: none;" /><slot></slot></div>`,this.#ht()}#ht(){let t=this.shadowRoot;if(!t)return;t.getElementById("tab-viewfinder")?.addEventListener("click",()=>{this.stage="viewfinder"}),t.getElementById("tab-workbench")?.addEventListener("click",()=>{this.stage="workbench"});let e=t.getElementById("internal-file-input");t.getElementById("btn-import-file")?.addEventListener("click",()=>{e?.click()}),e?.addEventListener("change",async i=>{let o=i.target;o.files&&o.files.length>0&&(await this.addFiles(o.files),o.value="")}),t.getElementById("btn-shutter")?.addEventListener("click",async()=>{await this.#tt()}),t.getElementById("camera-feed")?.addEventListener("click",async i=>{i.target&&i.target.closest("button, input, a, select")||!this.#c&&this.#e==="viewfinder"&&await this.startCamera().catch(()=>{})}),t.getElementById("btn-review")?.addEventListener("click",()=>{this.stage="workbench"}),t.getElementById("btn-retake")?.addEventListener("click",()=>{this.#l=!0,this.#o=!1,this.stage="viewfinder"}),t.getElementById("btn-rotate")?.addEventListener("click",async()=>{await this.#et()}),t.getElementById("btn-filter-bw")?.addEventListener("click",async()=>{await this.#it()}),t.getElementById("btn-crop")?.addEventListener("click",async()=>{await this.#W()}),t.getElementById("btn-delete")?.addEventListener("click",async()=>{await this.#rt()}),t.getElementById("btn-ocr")?.addEventListener("click",async()=>{await this.#bt()}),t.getElementById("btn-close-ocr")?.addEventListener("click",()=>{this.#wt()}),t.getElementById("btn-primary-complete")?.addEventListener("click",async()=>{await this.#ot()}),t.getElementById("btn-handoff-retry")?.addEventListener("click",()=>{this.reconnectHandoff().catch(()=>{})}),t.getElementById("btn-handoff-scan-more")?.addEventListener("click",async()=>{await this.resetHandoff()}),t.getElementById("btn-card-front")?.addEventListener("click",()=>{this.#o=!1,this.#i=0,this.#E()}),t.getElementById("btn-card-back")?.addEventListener("click",()=>{this.#o=!1,this.#i=1,this.#E()}),this.#J()}#J(){let t=this.shadowRoot;if(!t)return;let e=t.getElementById("crop-quad-outline"),i=t.querySelectorAll(".copio-crop-handle");if(!e||i.length===0)return;let o=null,s=!1,n=0,a=0,c=null,h=(y,S)=>{let b=t.getElementById("crop-magnifier"),v=t.getElementById("stage-img");if(!b||!v||!v.complete||!v.naturalWidth)return;b.style.display="block",b.style.left=`${(y*100).toFixed(2)}%`,b.style.top=`${(S*100).toFixed(2)}%`,b.style.transform=S<.25?"translate(-50%, 35%)":"translate(-50%, -125%)";let C=b.getContext("2d");if(!C)return;let k=2,T=b.width,B=b.height,E=v.naturalWidth,w=v.naturalHeight,D=T/k,H=B/k,_=y*E,M=S*w;C.clearRect(0,0,T,B),C.fillStyle="#0b0f17",C.fillRect(0,0,T,B),C.drawImage(v,_-D/2,M-H/2,D,H,0,0,T,B),C.strokeStyle="rgba(56, 189, 248, 0.9)",C.lineWidth=1.5,C.beginPath(),C.moveTo(T/2-10,B/2),C.lineTo(T/2+10,B/2),C.moveTo(T/2,B/2-10),C.lineTo(T/2,B/2+10),C.stroke()},p=()=>{let y=t.getElementById("crop-magnifier");y&&(y.style.display="none")},d=y=>{let S=y.target.closest(".copio-crop-handle");if(S)o=S.getAttribute("data-corner"),s=!1;else if(y.target===e)o=null,s=!0;else return;y.preventDefault(),y.stopPropagation(),n=y.clientX,a=y.clientY,c=this.#p?Mt(this.#p):{topLeft:{x:.05,y:.05},topRight:{x:.95,y:.05},bottomRight:{x:.95,y:.95},bottomLeft:{x:.05,y:.95}},o&&c[o]&&h(c[o].x,c[o].y),window.addEventListener("pointermove",g),window.addEventListener("pointerup",m)},g=y=>{if(!o&&!s||!c)return;let b=(t.getElementById("canvas-wrapper")||t.getElementById("canvas-viewport"))?.getBoundingClientRect()||{width:300,height:400},v=(y.clientX-n)/Math.max(b.width,1),C=(y.clientY-a)/Math.max(b.height,1),k=Mt(c),T=["topLeft","topRight","bottomRight","bottomLeft"];if(s){let B=-1/0,E=1/0,w=-1/0,D=1/0;for(let M of T)B=Math.max(B,-c[M].x),E=Math.min(E,1-c[M].x),w=Math.max(w,-c[M].y),D=Math.min(D,1-c[M].y);let H=Math.min(Math.max(v,B),E),_=Math.min(Math.max(C,w),D);for(let M of T)k[M].x=c[M].x+H,k[M].y=c[M].y+_}else if(o&&k[o]){let B=Math.min(Math.max(0,c[o].x+v),1),E=Math.min(Math.max(0,c[o].y+C),1);k[o].x=B,k[o].y=E,h(B,E)}this.#p=k,this.#X()},m=()=>{o=null,s=!1,c=null,p(),window.removeEventListener("pointermove",g),window.removeEventListener("pointerup",m)};e.addEventListener("pointerdown",d),i.forEach(y=>{y.addEventListener("pointerdown",d)})}#X(){let t=this.shadowRoot;if(!t||!this.#p)return;let{topLeft:e,topRight:i,bottomRight:o,bottomLeft:s}=this.#p,n=m=>`${(m.x*100).toFixed(2)},${(m.y*100).toFixed(2)}`,a=`${n(e)} ${n(i)} ${n(o)} ${n(s)}`,c=t.getElementById("crop-quad-mask");c&&c.setAttribute("d",`M0,0 H100 V100 H0 Z M${(e.x*100).toFixed(2)},${(e.y*100).toFixed(2)} L${(i.x*100).toFixed(2)},${(i.y*100).toFixed(2)} L${(o.x*100).toFixed(2)},${(o.y*100).toFixed(2)} L${(s.x*100).toFixed(2)},${(s.y*100).toFixed(2)} Z`);let h=t.getElementById("crop-quad-outline");h&&h.setAttribute("points",a);let p=(m,y,S)=>({x:m.x+(y.x-m.x)*S,y:m.y+(y.y-m.y)*S}),d=(m,y,S)=>{let b=t.getElementById(m);b&&(b.setAttribute("x1",(y.x*100).toFixed(2)),b.setAttribute("y1",(y.y*100).toFixed(2)),b.setAttribute("x2",(S.x*100).toFixed(2)),b.setAttribute("y2",(S.y*100).toFixed(2)))};d("crop-grid-v1",p(e,i,1/3),p(s,o,1/3)),d("crop-grid-v2",p(e,i,2/3),p(s,o,2/3)),d("crop-grid-h1",p(e,s,1/3),p(i,o,1/3)),d("crop-grid-h2",p(e,s,2/3),p(i,o,2/3));let g={topLeft:e,topRight:i,bottomRight:o,bottomLeft:s};for(let[m,y]of Object.entries(g)){let S=t.querySelector(`.copio-quad-handle[data-corner="${m}"]`);S&&(S.style.left=`${(y.x*100).toFixed(2)}%`,S.style.top=`${(y.y*100).toFixed(2)}%`)}}async#E(){if(this.shadowRoot)return this.#u?this.#u:(this.#u=(async()=>{try{await Promise.resolve(),await this.#dt()}finally{this.#u=null}})(),this.#u)}async#dt(){if(this.shadowRoot)try{let t=await this.getPages();this.#a=t.length;let e=this.shadowRoot,i=e.getElementById("mode-badge");i&&(i.textContent=(this.mode||"single").toUpperCase());let o=e.getElementById("tab-viewfinder"),s=e.getElementById("tab-workbench");o&&o.setAttribute("aria-selected",String(this.#e==="viewfinder")),s&&s.setAttribute("aria-selected",String(this.#e==="workbench"));let n=e.getElementById("viewfinder-section"),a=e.getElementById("workbench-section");n&&a&&(this.#e==="viewfinder"?(n.style.display="flex",a.style.display="none"):(n.style.display="none",a.style.display="flex"));let c=e.getElementById("framing-guide");c&&c.setAttribute("data-aspect",this.aspect||"auto");let h=e.getElementById("step-pill-text");h&&(this.#c?h.textContent=this.mode==="batch"?`Batch Capture \xB7 Page ${t.length+1}`:"Camera Active \xB7 Tap Shutter to Snap":this.aspect==="card"&&this.maxPages===2?h.textContent=t.length===0?"Step 1 of 2: Capture Front of ID Card":"Step 2 of 2: Capture Back of ID Card":this.aspect==="card"?h.textContent="Align Card Inside Frame":this.mode==="batch"?h.textContent=`Batch Capture \xB7 Page ${t.length+1}`:h.textContent="Align Document Inside Frame");let p=e.getElementById("btn-ocr");p&&(p.style.display=this.ocrEnabled&&this.hasFeature("ocr")?"":"none");let d=e.getElementById("btn-review"),g=e.getElementById("review-pill-text");if(d&&g&&(t.length>0?(d.style.display="inline-flex",g.textContent=`Review (${t.length}) \u2192`):d.style.display="none"),t.length===0){this.#e==="workbench"&&(this.stage="viewfinder");return}this.#i>=t.length&&(this.#i=Math.max(0,t.length-1));let m=t[this.#i],y=e.getElementById("card-side-switcher");if(y){let T=this.aspect==="card"&&this.maxPages===2;y.style.display=T?"flex":"none";let B=e.getElementById("btn-card-front"),E=e.getElementById("btn-card-back");B&&(B.classList.toggle("active",this.#i===0),B.setAttribute("aria-selected",String(this.#i===0))),E&&(E.classList.toggle("active",this.#i===1),E.setAttribute("aria-selected",String(this.#i===1)))}let S=e.getElementById("canvas-viewport");S&&S.classList.toggle("is-cropping",this.#o);let b=e.getElementById("stage-img");if(b)if(this.#o){let T=m.edits?.rotate||0,B=m.edits?.filter||"none",E=m.originalSrc||m.src||"";if(T!==0||B!=="none"){let w=this.#t?await this.#t.renderEdits(E,{rotate:T,filter:B}):E;b.src=w||E}else b.src=E}else b.src=m.src||m.originalSrc||"";let v=e.getElementById("crop-layer");if(this.#o){if(!v){let E=e.getElementById("canvas-wrapper");v=document.createElement("div"),v.className="copio-crop-layer",v.id="crop-layer",v.innerHTML='<svg class="copio-crop-quad-svg" id="crop-quad-svg" viewBox="0 0 100 100" preserveAspectRatio="none"><path class="copio-crop-mask" id="crop-quad-mask" fill-rule="evenodd" d=""></path><line class="copio-crop-quad-grid" id="crop-grid-v1"></line><line class="copio-crop-quad-grid" id="crop-grid-v2"></line><line class="copio-crop-quad-grid" id="crop-grid-h1"></line><line class="copio-crop-quad-grid" id="crop-grid-h2"></line><polygon class="copio-crop-quad-outline" id="crop-quad-outline" points=""></polygon></svg><span class="copio-crop-handle copio-quad-handle" data-corner="topLeft" data-handle="nw"></span><span class="copio-crop-handle copio-quad-handle" data-corner="topRight" data-handle="ne"></span><span class="copio-crop-handle copio-quad-handle" data-corner="bottomRight" data-handle="se"></span><span class="copio-crop-handle copio-quad-handle" data-corner="bottomLeft" data-handle="sw"></span><canvas class="copio-crop-magnifier" id="crop-magnifier" width="96" height="96"></canvas>',E?.appendChild(v),this.#J()}v.style.display="block";let T=m.edits?.rotate||0,B=m.edits?.quad||(m.edits?.crop?Go(m.edits.crop):null)||{topLeft:{x:.05,y:.05},topRight:{x:.95,y:.05},bottomRight:{x:.95,y:.95},bottomLeft:{x:.05,y:.95}};this.#p=Xo(B,T),this.#X()}else v&&v.remove();let C=e.getElementById("crop-btn-label");C&&(C.textContent=this.#o?"Apply":"Crop");let k=e.getElementById("btn-primary-complete");k&&(this.isHandoff?this.aspect==="card"&&this.maxPages===2&&t.length===1?k.textContent="Next: Capture Back (Step 2/2) \u2192":this.aspect==="card"&&t.length>=2?k.textContent="\u2191 Send ID Card to Computer (2 Sides)":this.mode==="batch"?k.textContent=`\u2191 Send ${t.length} Pages to Computer`:k.textContent="\u2191 Send to Computer":this.aspect==="card"&&this.maxPages===2&&t.length===1?k.textContent="Next: Capture Back (Step 2/2) \u2192":this.aspect==="card"&&t.length>=2?k.textContent="\u2713 Complete ID Scan (2 Sides)":this.mode==="batch"?k.textContent=`\u2713 Complete Scan (${t.length} Pages)`:k.textContent="\u2713 Use Photo"),this.#D(),this.#pt(t)}catch{}}#pt(t){let e=this.shadowRoot;if(!e)return;let i=e.getElementById("filmstrip-scroll");i&&(i.innerHTML="",t.forEach((o,s)=>{let n=document.createElement("div");n.className=`copio-filmstrip-item ${s===this.#i?"is-active":""}`,n.setAttribute("data-index",String(s)),n.innerHTML=`<div class="copio-thumb-container"><img src="${o.src||o.originalSrc}" alt="Page ${s+1}" class="copio-thumb-img" /><span class="copio-thumb-num">${s+1}</span></div> ${this.mode==="batch"?` <div class="copio-thumb-reorder"><button type="button" class="copio-reorder-btn move-left" title="Move Left" ${s===0?"disabled":""}>\u25C0</button><button type="button" class="copio-reorder-btn move-right" title="Move Right" ${s===t.length-1?"disabled":""}>\u25B6</button></div> `:""}`,n.querySelector(".copio-thumb-container")?.addEventListener("click",()=>{this.#i=s,this.#o=!1,this.#E()}),this.mode==="batch"&&(n.querySelector(".move-left")?.addEventListener("click",async a=>{a.stopPropagation(),await this.#Q(s,s-1)}),n.querySelector(".move-right")?.addEventListener("click",async a=>{a.stopPropagation(),await this.#Q(s,s+1)})),i.appendChild(n)}))}async#Q(t,e){let i=await this.getPages();if(e<0||e>=i.length||t===e)return;let o=i.map(n=>n.id),[s]=o.splice(t,1);o.splice(e,0,s),await this.#t.reorderPages(this.#P,o),this.#i=e,this.#E()}#ft(t,e="warning",i=4e3){try{if(typeof jt<"u"){let a=this.shadowRoot?.querySelector(".copio-scanner-container")||this;e==="warning"&&typeof jt.warning=="function"?jt.warning(t,{container:a}):typeof jt.info=="function"&&jt.info(t,{container:a})}}catch{}let s=this.shadowRoot?.getElementById("toast-region");if(!s)return;let n=document.createElement("div");n.className=`copio-toast copio-toast-${e}`,n.setAttribute("role","alert"),n.innerHTML=`<span class="copio-toast-msg">${t}</span>`,s.appendChild(n),setTimeout(()=>{n.classList.add("copio-toast-fade-out"),setTimeout(()=>{n.remove()},250)},i)}#Y(t,e){let o=t?.name==="NotAllowedError"||t?.name==="PermissionDeniedError"?"CAMERA_PERMISSION_DENIED":"CAMERA_UNAVAILABLE";this.#ft(e,"warning");let s=this.shadowRoot?.getElementById("step-pill-text");s&&(s.textContent="Camera Unavailable \xB7 Select File"),this.dispatch(ht.ERROR,{code:o,message:e,error:t});let n=this.shadowRoot?.getElementById("internal-file-input");n&&typeof n.click=="function"&&n.click()}#L(){if(this.#_(),this.#V(),this.#c){try{let s=this.#c.getTracks();for(let n of s)n.stop()}catch{}this.#c=null}let t=this.shadowRoot,e=t?.getElementById("camera-video");if(e){try{e.pause()}catch{}e.srcObject=null,e.style.display="none"}let i=t?.querySelector(".copio-camera-placeholder");i&&(i.style.display="");let o=t?.getElementById("step-pill-text");o&&this.#e==="viewfinder"&&(o.textContent=this.mode==="batch"?`Batch Capture \xB7 Page ${this.#a+1}`:"Align Document Inside Frame")}async startCamera(t={}){if(!this.shadowRoot?.getElementById("camera-video"))return null;if(this.#c)return this.#c;if(typeof window<"u"&&window.__WTR_CONFIG__!==void 0&&typeof navigator<"u"&&navigator.webdriver===!0&&!t.force)return null;if(typeof navigator>"u"||!navigator.mediaDevices?.getUserMedia)return this.#Y(new Error("NO_CAMERA_SUPPORT"),"No camera found. Choose a photo from your files instead."),null;let s=[{video:{facingMode:{ideal:"environment"},width:{ideal:1280},height:{ideal:720}},audio:!1},{video:{facingMode:{ideal:"environment"}},audio:!1},{video:{width:{ideal:1280}},audio:!1},{video:!0,audio:!1}],n=null,a=null;for(let c of s)try{if(n=await navigator.mediaDevices.getUserMedia(c),n)break}catch(h){if(a=h,h.name==="NotAllowedError"||h.name==="PermissionDeniedError")break}if(!n){let h=a?.name==="NotAllowedError"||a?.name==="PermissionDeniedError"?"Camera permission denied. Choose a photo from your files instead.":"Camera unavailable. Choose a photo from your files instead.";return this.#Y(a||new Error("CAMERA_UNAVAILABLE"),h),null}return this.setCameraStream(n),n}stopCamera(){this.#L()}_grabFrame(t={}){let i=this.shadowRoot?.getElementById("camera-video");if(!this.#c||!i)return null;let o=i.videoWidth||640,s=i.videoHeight||480;if(o===0||s===0)return null;let n=t.maxWidth||640,a=t.maxHeight||480,c=Math.min(1,n/o,a/s),h=Math.max(1,Math.round(o*c)),p=Math.max(1,Math.round(s*c));if(!this.#y&&typeof document<"u"&&(this.#y=document.createElement("canvas")),!this.#y)return null;this.#y.width=h,this.#y.height=p;let d=this.#y.getContext("2d",{willReadFrequently:!0});if(!d)return null;try{d.drawImage(i,0,0,h,p)}catch{d.fillStyle="#334155",d.fillRect(0,0,h,p)}return t.format==="canvas"?this.#y:d.getImageData(0,0,h,p)}_isCameraActive(){return!!this.#c}#Z(){if(this.#_(),!this.#g||!this.#c||this.#e!=="viewfinder")return;let t=async e=>{if(!this.#c||this.#e!=="viewfinder"||!this.#g){this.#_();return}let i=e-this.#M;!this.#T&&i>=100&&(this.#M=e,await this.#gt(e)),this.#c&&this.#e==="viewfinder"&&this.#g&&(this.#k=requestAnimationFrame(t))};this.#k=requestAnimationFrame(t)}#_(){this.#k!==null&&(cancelAnimationFrame(this.#k),this.#k=null),this.#T=!1}#V(){let t=this.shadowRoot,e=t?.getElementById("live-quad-overlay");e&&(e.style.display="none");let i=t?.getElementById("camera-feed");i&&i.classList.remove("is-detected","is-tracking");let o=t?.getElementById("live-quad-polygon");o&&o.setAttribute("points","");for(let s=0;s<4;s++){let n=t?.getElementById(`live-quad-c${s}`);n&&(n.removeAttribute("cx"),n.removeAttribute("cy"))}this.#v=null,this.#A=null,this.#B=0,this.#N=0,this.#R=0,this.#O=null}#ut(t,e){let i=this.shadowRoot,o=i?.getElementById("live-quad-overlay"),s=i?.getElementById("camera-feed"),n=i?.getElementById("camera-video");if(!o||!s||!t)return;let a=s.clientWidth,c=s.clientHeight;if(a<=0||c<=0)return;let h=n?.videoWidth||640,p=n?.videoHeight||480,d=Math.max(a/h,c/p),g=h*d,m=p*d,y=(a-g)/2,S=(c-m)/2,b=[t.topLeft,t.topRight,t.bottomRight,t.bottomLeft],v=b.map(C=>`${(y+C.x*g).toFixed(1)},${(S+C.y*m).toFixed(1)}`);o.setAttribute("viewBox",`0 0 ${a} ${c}`),o.style.display="block",i.getElementById("live-quad-polygon")?.setAttribute("points",v.join(" "));for(let C=0;C<4;C++){let k=i.getElementById(`live-quad-c${C}`);k&&(k.setAttribute("cx",(y+b[C].x*g).toFixed(1)),k.setAttribute("cy",(S+b[C].y*m).toFixed(1)))}s.classList.add("is-tracking"),s.classList.toggle("is-detected",e>=.7)}async#gt(t){let i=this.shadowRoot?.getElementById("camera-video");if(!i||i.videoWidth===0||i.videoHeight===0)return;let o=this._grabFrame({maxWidth:480,maxHeight:480});if(o){this.#T=!0;try{let s=this.#t?.getService("edge")||_t("edge");if(!s||typeof s.detect!="function")return;let n=this.#b==="ml"?.4:.45,a=await s.detect(o,{maxProcessingDimension:480,enableDetectionCascade:!1,minConfidence:n,fallbackOnLowConfidence:!1,detector:this.#b,ml:{minScore:n}});if(!this.#c||this.#e!=="viewfinder"||!this.#g)return;if(a&&a.quad&&a.confidence>=n&&!a.isFallback){this.#B=0,this.#N=t;let c=.35;if(!this.#v)this.#v=Mt(a.quad);else for(let h of["topLeft","topRight","bottomRight","bottomLeft"])this.#v[h].x=c*a.quad[h].x+(1-c)*this.#v[h].x,this.#v[h].y=c*a.quad[h].y+(1-c)*this.#v[h].y;this.#A={quad:Mt(this.#v),confidence:a.confidence,durationMs:a.durationMs,isFallback:!1},this.#ut(this.#v,a.confidence),this.dispatch(ht.EDGE_DETECTED,{quad:Mt(this.#v),confidence:a.confidence,durationMs:a.durationMs}),this.#I&&a.confidence>=.65&&this.#mt(this.#v,t)}else this.#B++,this.#B>4&&t-this.#N>1200&&(this.#v=null,this.#A=null,this.#R=0,this.#V())}catch(s){typeof console<"u"&&console.warn&&console.warn("[CopioScanner] Live edge detection error:",s)}finally{this.#T=!1}}}#mt(t,e){if(!this.#I||!t)return;let i=[t.topLeft,t.topRight,t.bottomRight,t.bottomLeft],o=0;for(let a=0;a<4;a++){let c=(a+1)%4;o+=i[a].x*i[c].y-i[c].x*i[a].y}if(o=Math.abs(o)/2,o<.15){this.#R=0,this.#O=null;return}if(!this.#O){this.#O=Mt(t),this.#R=e;return}let s=0;for(let a of["topLeft","topRight","bottomRight","bottomLeft"]){let c=t[a].x-this.#O[a].x,h=t[a].y-this.#O[a].y;s+=c*c+h*h}let n=Math.sqrt(s/4);this.#O=Mt(t),n<.015?e-this.#R>=600&&(this.#R=e+1e4,this.#tt()):this.#R=e}async#tt(){if(typeof this.onShutter=="function"&&await this.onShutter()!==!1)return;let t=this.shadowRoot,e=t?.getElementById("camera-video");if(this.#c&&e){let s=t?.getElementById("camera-feed");s&&(s.classList.remove("is-shutter-flash"),s.offsetWidth,s.classList.add("is-shutter-flash"));let n=this.#b==="ml"?.4:.45,a=this.#A?.confidence>=n?Mt(this.#A.quad):null,c=document.createElement("canvas");c.width=e.videoWidth||1280,c.height=e.videoHeight||720;let h=c.getContext("2d");if(h){try{h.drawImage(e,0,0,c.width,c.height)}catch{h.fillStyle="#334155",h.fillRect(0,0,c.width,c.height)}let p=await new Promise(d=>c.toBlob(d,"image/jpeg",.92));if(c.width=0,c.height=0,p){let d=this.mode==="batch";d||this.#L();let g=new File([p],`capture_${Date.now()}.jpg`,{type:"image/jpeg"});await this.addFiles([g],{prefilledQuad:a}),!d&&a&&this.#w&&this.features.includes("crop")&&(this.#o=!0,await this.#E()),d&&this.maxPages>0&&this.#a>=this.maxPages&&(this.#L(),this.stage="workbench");return}}}if(await this.startCamera())return;let o=t?.getElementById("internal-file-input");o&&typeof o.click=="function"&&o.click()}async#et(){let e=(await this.getPages())[this.#i];if(!e)return;this.#o&&(this.#o=!1,this.#p=null);let o=((e.edits?.rotate||0)+90)%360;await this.#t.applyEdit(this.#P,e.id,{rotate:o}),await this.#E()}async#it(){let e=(await this.getPages())[this.#i];if(!e)return;this.#o&&(this.#o=!1,this.#p=null);let o=(e.edits?.filter||"none")==="bw"?"none":"bw";await this.#t.applyEdit(this.#P,e.id,{filter:o}),await this.#E()}async#W(){let e=(await this.getPages())[this.#i];if(e){if(this.#o){this.#o=!1;let i=this.#p;if(this.#p=null,i){let o=e.edits?.rotate||0,s=Qo(i,o),n=Bi(s);await this.#t.applyEdit(this.#P,e.id,{quad:s,crop:n})}}else this.#o=!0;await this.#E()}}async#rt(){let t=await this.getPages(),e=t[this.#i];if(!e)return;let i=e.id;await this.#t.deletePage(this.#P,i),this.dispatch(ht.PAGE_REMOVED,{pageId:i,docId:this.docId}),this.#i>=t.length-1&&(this.#i=Math.max(0,t.length-2)),this.#yt(),await this.#E()}#yt(){let t=this.shadowRoot;if(!t)return;let e=t.getElementById("toast-region");if(!e)return;this.#h&&clearInterval(this.#h),this.#d=5;let i=()=>{e.innerHTML=`<div class="copio-toast copio-toast-undo"><span>Page deleted</span><button type="button" class="copio-btn-toast-undo" id="btn-toast-undo"> Undo (${this.#d}s) </button></div>`,t.getElementById("btn-toast-undo")?.addEventListener("click",async()=>{clearInterval(this.#h),this.#h=null,e.innerHTML="",await this.#t.undo(this.#P),await this.#E()})};i(),this.#h=setInterval(()=>{this.#d-=1,this.#d<=0?(clearInterval(this.#h),this.#h=null,e.innerHTML=""):i()},1e3)}async#bt(){let t=this.shadowRoot;if(!t)return;let e=t.getElementById("ocr-sheet"),i=t.getElementById("ocr-body");if(!(!e||!i)){e.style.display="block",i.innerHTML='<p class="copio-ocr-loading">Recognizing text...</p>';try{let s=(await this.getPages())[this.#i],n=await this.ocr(s?.id||null),a=n.averageConfidence||0,c=a<=1&&a>0?Math.round(a*100):Math.round(a);i.innerHTML=`<div class="copio-ocr-content"><pre class="copio-ocr-text">${n.text||"No text detected."}</pre><div class="copio-ocr-meta"><span>Confidence: ${c}%</span></div></div>`}catch(o){i.innerHTML=`<p class="copio-ocr-error">OCR recognition failed: ${o.message}</p>`}}}#wt(){let t=this.shadowRoot;if(!t)return;let e=t.getElementById("ocr-sheet");e&&(e.style.display="none")}async#ot(){if(this.#o&&await this.#W(),this.aspect==="card"&&this.maxPages===2&&this.#a===1){this.stage="viewfinder";return}let t=await this.getPages();if(this.aspect==="card"&&this.maxPages===2&&t.length===1){this.stage="viewfinder";return}let e=t.map((o,s)=>({id:o.id,pageNumber:s+1,label:o.label||`Page ${s+1}`,originalSrc:o.originalSrc,src:o.src,originalPreserved:!0,dimensions:{width:o.width||0,height:o.height||0},edits:o.edits||{crop:{x:0,y:0,w:1,h:1},rotate:0,filter:"none"},ocrText:o.ocrText||null,blob:o.blob||null})),i={mode:this.mode,aspect:this.aspect,docId:this.docId,pageCount:e.length,pages:e};if(this.mode==="single"&&(i.page=e[0]||null,this.maxPages>1&&(i.maxPages=this.maxPages)),this.isHandoff&&this.#S){await this.#vt(e,i);return}this.dispatch(ht.SCAN_COMPLETE,i)}async completeScan(){return this.#ot()}get handoff(){return typeof this.getAttribute=="function"?this.getAttribute("handoff"):null}set handoff(t){typeof this.setAttribute=="function"&&(t!=null&&(typeof t!="boolean"||t===!0)?this.setAttribute("handoff",typeof t=="string"?t:""):this.removeAttribute("handoff"))}get isHandoff(){return this.#H()}get handoffSession(){return this.#S}get handoffState(){return this.#x}get handoffProgress(){return this.#$}get handoffRetryCount(){return this.#z}attachHandoffSession(t,e=null){this.#q(),this.#S=t,this.#U=e||t?.token||null,this.#nt(t),this.#x=t.isConnected?"connected":t.state==="idle"?"connecting":t.state,this.#D()}async reconnectHandoff(){if(!(!this.#S||!this.#U)&&!(this.#x==="complete"||this.#x==="connecting")){this.#z++,this.#x="reconnecting",this.#D();try{if(Nt.has(this.#U.peerId)){let t=Nt.createLinkedSender(this.#U.peerId);await this.#S.reconnect(t)}else await this.#S.reconnect()}catch(t){console.warn("[CopioScanner] Handoff reconnect failed:",t),this.#x="disconnected",this.#D(t?.message||"Reconnection failed")}}}async resetHandoff(){this.#x=this.#S?.isConnected?"connected":"idle",this.#$=null;let t=this.shadowRoot;if(t){let e=t.getElementById("handoff-confirm-view");e&&(e.style.display="none");let i=t.getElementById("handoff-progress-view");i&&(i.style.display="none")}await this.clear(),this.stage="viewfinder",this.#D()}#H(){return this.#S?!0:typeof this.hasAttribute=="function"&&this.hasAttribute("handoff")?this.getAttribute("handoff")!=="false":typeof window<"u"&&window.location?.hash?/(?:copio-)?handoff=/.test(window.location.hash):!1}async#st(){if(this.#S||!this.#H())return;let t=typeof this.getAttribute=="function"?this.getAttribute("handoff"):null;if(!t&&typeof window<"u"&&window.location?.hash&&(t=window.location.hash),!!t)try{let e=typeof t=="string"&&t.includes("#")?ss(t):Xr(t);this.#U=e,this.#x="connecting",this.#D();let i=null;if(Nt.has(e.peerId))i=Nt.createLinkedSender(e.peerId);else try{let{HandoffPeerTransport:s}=await Promise.resolve().then(()=>(Da(),Aa));i=new s({role:"sender",targetPeerId:e.peerId,relayUrl:e.relayUrl||this.relayUrl,signalingUrl:e.signalingUrl||this.signalingUrl,iceServers:e.iceServers||this.iceServers,iceTransportPolicy:this.iceTransportPolicy})}catch{i=new Nt}let o=new Jr({role:"sender",transport:i});this.#S=o,this.#nt(o),await o.startSender(e)}catch(e){console.warn("[CopioScanner] Handoff sender init failed:",e),this.#x="error",this.#D(e?.message||"Connection error")}}#nt(t){this.#j.push(t.on("stateChange",e=>{e==="closed"?this.#x="disconnected":this.#x=e,e==="connected"&&(this.#z=0,this.dispatch(ht.HANDOFF_CONNECTED,{sessionId:this.#U?.sessionId||"",peerId:this.#U?.peerId||""})),this.#D()}),t.on("connectionInfo",e=>{this.dispatch(ht.CONNECTION_INFO,e)}),t.on("progress",e=>{this.#$=e,this.#xt(e)}),t.on("complete",()=>{this.#x="complete",this.#D()}),t.on("error",e=>{console.warn("[CopioScanner] Handoff session error:",e),this.#x="error",this.#D(e?.message||"Connection error")}))}#q(){for(let t of this.#j)try{t()}catch{}if(this.#j=[],this.#S){try{this.#S.close()}catch{}this.#S=null}this.#U=null,this.#x="idle",this.#$=null}#D(t=""){let e=this.shadowRoot;if(!e)return;let i=e.getElementById("handoff-pill"),o=e.getElementById("handoff-dot"),s=e.getElementById("handoff-status-text"),n=e.getElementById("btn-handoff-retry");if(!i||!o||!s)return;if(!this.#H()){i.style.display="none";return}i.style.display="inline-flex",o.className=`copio-handoff-dot ${this.#x}`;let a={connecting:"Connecting to computer\u2026",connected:"Paired with computer",reconnecting:"Reconnecting to computer\u2026",disconnected:"Disconnected",sending:"Sending to computer\u2026",complete:"Sent to computer \u2713",error:t||"Connection error"};s.textContent=a[this.#x]||"Desktop Handoff",n&&(n.style.display=this.#x==="disconnected"||this.#x==="error"?"inline-block":"none")}#xt(t){let e=this.shadowRoot;if(!e||!t)return;let i=e.getElementById("handoff-progress-bar"),o=e.getElementById("handoff-progress-desc");if(i&&typeof t.percent=="number"&&(i.style.width=`${t.percent}%`),o&&t.bytesSent&&t.totalBytes){let s=Math.round(t.bytesSent/1024),n=Math.round(t.totalBytes/1024);o.textContent=`Streaming chunks: ${s} KB / ${n} KB (${t.percent}%)`}}async#vt(t,e){let i=this.shadowRoot,o=i?.getElementById("handoff-progress-view"),s=i?.getElementById("handoff-progress-bar"),n=i?.getElementById("handoff-progress-title"),a=i?.getElementById("handoff-progress-desc");o&&(o.style.display="flex"),this.#x="sending",this.#D();try{for(let p=0;p<t.length;p++){let d=t[p];n&&(n.textContent=t.length>1?`Sending page ${p+1} of ${t.length}\u2026`:"Sending page to computer\u2026"),a&&(a.textContent="Encrypting with AES-GCM-256\u2026");let g=await this.#St(d),m=!1,y=0;for(;!m&&y<3;)try{this.#S.isConnected||(await this.reconnectHandoff(),await this.#at(6e3)),await this.#S.sendPage({id:d.id,pageIndex:p,mimeType:g.type||"image/jpeg",blob:g,metadata:{width:d.dimensions?.width,height:d.dimensions?.height,label:d.label}}),m=!0}catch(S){if(y++,y>=3)throw S;await this.reconnectHandoff(),await this.#at(6e3)}}n&&(n.textContent="Finalizing scan session\u2026"),s&&(s.style.width="100%"),await this.#S.complete({docId:e.docId,summary:{mode:e.mode,aspect:e.aspect,pageCount:t.length}}),this.#x="complete",o&&(o.style.display="none");let c=i?.getElementById("handoff-confirm-view"),h=i?.getElementById("handoff-confirm-count");c&&(c.style.display="flex"),h&&(h.textContent=`${t.length} page${t.length===1?"":"s"} transferred to desktop`),this.#D(),this.dispatch(ht.SCAN_COMPLETE,e)}catch(c){console.error("[CopioScanner] Handoff streaming error:",c),o&&(o.style.display="none"),this.#x="error",this.#D(c.message),this.dispatch(ht.ERROR,{code:"HANDOFF_STREAMING_FAILED",message:c.message,error:c})}}async#at(t=6e3){if(!this.#S?.isConnected)return new Promise((e,i)=>{let o=setTimeout(()=>{s(),i(new Error("Timeout waiting for handoff connection"))},t),s=this.#S.on("stateChange",n=>{n==="connected"&&(clearTimeout(o),s(),e(void 0))})})}async#St(t){if(t.blob instanceof Blob)return t.blob;let e=t.src||t.originalSrc;if(e&&typeof fetch=="function"&&(e.startsWith("data:")||e.startsWith("blob:")||e.startsWith("http")))try{let o=await(await fetch(e)).blob();if(o&&o.size>0)return o}catch{}if(typeof document<"u"){let i=document.createElement("canvas");i.width=t.dimensions?.width||120,i.height=t.dimensions?.height||160;let o=i.getContext("2d");return o&&(o.fillStyle="#f1f5f9",o.fillRect(0,0,i.width,i.height)),new Promise(s=>{i.toBlob(n=>s(n||new Blob),"image/jpeg")})}return new Blob([],{type:"image/jpeg"})}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.#e}set stage(t){if(t==="viewfinder"||t==="workbench"){this.#e=t,t==="workbench"&&this.#L(),typeof this.setAttribute=="function"&&this.getAttribute("stage")!==t&&this.setAttribute("stage",t);let e=this.shadowRoot;if(e){let i=e.getElementById("viewfinder-section"),o=e.getElementById("workbench-section");i&&o&&(i.style.display=t==="viewfinder"?"flex":"none",o.style.display=t==="workbench"?"flex":"none")}this.#E()}}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.#et()}async toggleActivePageBw(){return this.#it()}async toggleCropMode(){return this.#W()}async deleteActivePageWithUndo(){return this.#rt()}setCameraStream(t){this.#L(),this.#c=t;let e=this.shadowRoot,i=e?.getElementById("camera-video");if(i){i.muted=!0,i.volume=0,i.playsInline=!0,i.setAttribute("playsinline",""),i.setAttribute("webkit-playsinline",""),i.setAttribute("muted","");try{i.srcObject=typeof MediaStream<"u"&&t instanceof MediaStream?t:null}catch{}i.style.display=t?"block":"none",t&&i.srcObject&&i.play().catch(n=>{console.warn("[CopioScanner] Live video element play() error:",n)})}let o=e?.querySelector(".copio-camera-placeholder");o&&(o.style.display=t?"none":"");let s=e?.getElementById("step-pill-text");s&&t&&(s.textContent=this.mode==="batch"?`Batch Capture \xB7 Page ${this.#a+1}`:"Camera Active \xB7 Tap Shutter to Snap"),t&&this.#e==="viewfinder"&&this.#g&&this.#Z()}get features(){return this.#t?this.#t.features:[]}set features(t){this.#C("features",Array.isArray(t)?t.join(" "):String(t||"")),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;this.#C("ocr",e?"true":"false"),this.#t&&(this.#t.ocr=e),this.#F()}get pdf(){return this.#t?this.#t.pdf:!0}set pdf(t){let e=!!t;this.#C("pdf",e?"true":"false"),this.#t&&(this.#t.pdf=e),this.#F()}get exportFormats(){return this.#t?this.#t.exportFormats:[]}set exportFormats(t){this.#C("export-formats",Array.isArray(t)?t.join(","):String(t||"")),this.#t&&(this.#t.exportFormats=t)}get ocrLanguages(){return this.#t?this.#t.ocrLanguages:[]}set ocrLanguages(t){this.#C("ocr-languages",Array.isArray(t)?t.join(","):String(t||"")),this.#t&&(this.#t.ocrLanguages=t)}get maxPages(){return this.#t?this.#t.maxPages:0}set maxPages(t){this.#C("max-pages",String(t)),this.#t&&(this.#t.maxPages=t)}get assetBase(){return this.#t?this.#t.assetBase:""}set assetBase(t){this.#C("asset-base",String(t||"")),this.#t&&(this.#t.assetBase=t)}get licenseKey(){return this.#t?this.#t.licenseKey:""}set licenseKey(t){this.#C("license-key",String(t||"")),this.#t&&(this.#t.licenseKey=t)}#C(t,e){typeof this.setAttribute=="function"&&(e?this.setAttribute(t,typeof e=="object"?JSON.stringify(e):String(e)):this.removeAttribute(t))}get relayUrl(){return this.#t?.relayUrl||""}set relayUrl(t){this.#t&&(this.#t.relayUrl=t),this.#C("relay-url",t)}get signalingUrl(){return this.#t?.signalingUrl||""}set signalingUrl(t){this.#t&&(this.#t.signalingUrl=t),this.#C("signaling-url",t)}get iceServers(){return this.#t?.iceServers||null}set iceServers(t){this.#t&&(this.#t.iceServers=t),this.#C("ice-servers",t)}get iceTransportPolicy(){return this.#t?.iceTransportPolicy||"all"}set iceTransportPolicy(t){this.#t&&(this.#t.iceTransportPolicy=t),this.#C("ice-transport-policy",t)}get storage(){return this.#r}set storage(t){this.#r=t,this.#t&&this.#t.setStorage(t)}get engine(){return this.#t}set engine(t){t instanceof Fi&&(this.#t=t,this.#t.addEventListener(ht.MIGRATION,e=>{this.dispatch(ht.MIGRATION,e.detail)}))}dispatch(t,e={}){return pa(this,t,e)}async open(){this.#s=!0,typeof this.focus=="function"&&this.focus()}async close(){this.#s=!1,this.#L()}get isOpen(){return this.#s}async capture(){return new Promise(t=>{let e=document.createElement("input");e.type="file",e.accept="image/*",e.capture="environment",e.style.display="none",e.onchange=async()=>{try{if(e.files&&e.files.length>0){let i=await this.addFiles([e.files[0]]);t(i[0]||null)}else t(null)}catch(i){this.dispatch(ht.ERROR,{code:"CAPTURE_FAILED",message:i.message,error:i}),t(null)}finally{e.remove()}},e.onerror=()=>{e.remove(),t(null)},document.body.appendChild(e),e.click()})}async addFiles(t,e={}){try{let i=await this.getPages(),o=null;if(i.length>0){if(this.mode==="single"&&this.maxPages<=1)await this.#t.clear(this.#P);else if(this.#l||this.maxPages>0&&i.length>=this.maxPages){let c=Math.min(this.#i,i.length-1),h=i[c];h&&(o=c,await this.#t.deletePage(this.#P,h.id))}}this.#l=!1;let s={autoCrop:this.#w,prefilledQuad:e?.prefilledQuad||null,...e},n=await this.#t.addFiles(t,this.#P,s);for(let c=0;c<n.length;c++)this.dispatch(ht.PAGE_ADDED,{page:n[c],pageNumber:c+1,docId:this.docId,source:"file"});let a=await this.getPages();if(o!==null&&n.length===1&&o<a.length-1){let c=a.map(p=>p.id),h=c.pop();h&&(c.splice(o,0,h),await this.#t.reorderPages(this.#P,c),a=await this.getPages())}return this.#a=a.length,n.length>0&&(this.#i=o!==null?Math.min(o,Math.max(0,a.length-1)):Math.max(0,a.length-1),this.mode==="single"&&(this.#e="workbench",typeof this.setAttribute=="function"&&this.getAttribute("stage")!=="workbench"&&this.setAttribute("stage","workbench"))),this.dispatch(ht.PAGES_CHANGED,{pages:a,docId:this.docId}),this.mode==="single"&&n.length>0&&this.maxPages<=1&&this.dispatch(ht.SCAN_COMPLETE,{mode:this.mode,aspect:this.aspect,docId:this.docId,pages:a,page:a[a.length-1]||null,pageCount:a.length}),await this.#E(),n}catch(i){throw this.dispatch(ht.ERROR,{code:i.code||"ADD_FILES_FAILED",message:i.message,error:i}),i}}async getPages(){return this.#t.getPages(this.#P)}async clear(){this.#L(),this.#i=0,this.#a=0,this.#l=!1,this.#o=!1,await this.#t.clear(this.#P),this.dispatch(ht.PAGES_CHANGED,{pages:[],docId:this.docId}),await this.#E()}async exportPdf(t={}){try{let e=await this.#t.exportPdf(this.#P,t);return this.dispatch(ht.EXPORT_COMPLETE,{type:"pdf",format:"pdf",blob:e,searchable:!!t.searchable,docId:this.docId}),e}catch(e){throw this.dispatch(ht.ERROR,{code:e.code||"EXPORT_FAILED",message:e.message,error:e}),e}}async exportZip(t={}){try{let e=await this.#t.exportZip(this.#P,t);return this.dispatch(ht.EXPORT_COMPLETE,{type:"zip",format:"zip",blob:e,docId:this.docId}),e}catch(e){throw this.dispatch(ht.ERROR,{code:e.code||"EXPORT_FAILED",message:e.message,error:e}),e}}async ocr(t=null,e={}){try{let i=await this.#t.runOcr(this.#P,t,e);return this.dispatch(ht.OCR_COMPLETE,{text:i.text,pages:i.pagesResults,averageConfidence:i.averageConfidence,docId:this.docId,pageId:t}),i}catch(i){throw this.dispatch(ht.ERROR,{code:i.code||"OCR_FAILED",message:i.message,error:i}),i}}async runOcr(t=null,e={}){return this.ocr(t,e)}async sync(t={}){try{return await this.#t.sync({onStateChange:i=>{i&&(i.step==="connected"||i.step==="syncing")&&this.dispatch(ht.SYNC_CONNECTED,{peerId:i.peerId,mode:i.mode}),t.onStateChange&&t.onStateChange(i)}})}catch(e){throw this.dispatch(ht.ERROR,{code:e.code||"SYNC_FAILED",message:e.message,error:e}),e}}get edgeDetection(){return this.#g}set edgeDetection(t){let e=t!==!1&&t!=="false"&&t!==null&&t!==void 0;this.#g!==e&&(this.#g=e,this.#C("edge-detection",String(e)),this.#g?this.#c&&this.#e==="viewfinder"&&this.#Z():(this.#_(),this.#V()))}get edgeModel(){return this.#b}set edgeModel(t){let e=t==="classical"?"classical":"ml";if(this.#b!==e){this.#b=e,this.#C("edge-model",e);let i=this.#t?.getService("edge")||_t("edge");if(i&&"detector"in i&&(i.detector=e),e==="ml"&&i&&typeof i.preloadMl=="function"){let o=this.shadowRoot?.getElementById("step-pill-text"),s=o?.textContent;o&&this.#c&&this.#e==="viewfinder"&&(o.textContent="Loading ML Neural model\u2026"),i.preloadMl().then(()=>{o&&this.#c&&this.#e==="viewfinder"&&this.#b==="ml"&&(o.textContent=this.mode==="batch"?`Batch Capture \xB7 Page ${this.#a+1}`:"Camera Active \xB7 Tap Shutter to Snap")}).catch(n=>{console.warn("[CopioScanner] Failed to load ML Neural edge detector:",n),o&&s&&this.#e==="viewfinder"&&(o.textContent=s)})}}}get autoCrop(){return this.#w}set autoCrop(t){let e=t!==!1&&t!=="false"&&t!==null&&t!==void 0;this.#w!==e&&(this.#w=e,this.#C("auto-crop",String(e)))}get autoCapture(){return this.#I}set autoCapture(t){let e=!!(t&&t!=="false");this.#I!==e&&(this.#I=e,this.#C("auto-capture",String(e)))}getLiveQuad(){return this.#v?Mt(this.#v):null}getLatestDetection(){return this.#A?{quad:Mt(this.#A.quad),confidence:this.#A.confidence,durationMs:this.#A.durationMs,isFallback:this.#A.isFallback}:null}async detectCurrentFrame(t={}){let e=this._grabFrame({maxWidth:t.maxProcessingDimension||480,maxHeight:t.maxProcessingDimension||480});if(!e)return null;let i=this.#t?.getService("edge")||_t("edge");return!i||typeof i.detect!="function"?null:i.detect(e,t)}};typeof customElements<"u"&&!customElements.get("copio-scanner")&&customElements.define("copio-scanner",cs);export{ht as COPIO_EVENTS,cs as CopioScanner,wa as adoptScannerStyles,pa as dispatchCopioEvent,ba as getScannerStyleSheet,is as scannerCss};
1398
5
  //# sourceMappingURL=scanner.js.map