@qratilabs/qrati-connect 2.32.2 → 2.33.0

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 (72) hide show
  1. package/element/B60TJHpn.js +1 -0
  2. package/element/{DiQrTagI2.js → BX09gwBu.js} +1 -1
  3. package/element/{BZSy_Rh42.js → BgmJHB_q.js} +18 -18
  4. package/element/{CDBzc1CZ.js → BhPQW37y.js} +1 -1
  5. package/element/BhUO8wHu.js +16 -0
  6. package/element/BhYfK52W.js +207 -0
  7. package/element/BjDK8Ljd.js +85 -0
  8. package/element/Bjbk1Zhj.js +1 -0
  9. package/element/BlsbPO0-.js +1 -0
  10. package/element/{DFRMtMLz.js → Bpjf4eY9.js} +1 -1
  11. package/element/{DUS9pix12.js → BtLTtkX8.js} +1 -1
  12. package/element/{CaTxtEbg.js → BuT9kfma.js} +1 -1
  13. package/element/Bx-BFs7B.js +4 -0
  14. package/element/{DtBnBN-i.js → BzXQkPAW.js} +1 -1
  15. package/element/{D-U23_J5.js → CGJtMtq6.js} +36 -36
  16. package/element/CVlMw3Vf.js +3 -0
  17. package/element/CYHy0vN3.js +1 -0
  18. package/element/CZJLtvF9.js +4 -0
  19. package/element/CfNXbM5H.js +2 -0
  20. package/element/ChW2P7vL.js +2 -0
  21. package/element/CrZvMeF8.js +8 -0
  22. package/element/{DdQWa3ny.js → Crg6P9Om.js} +1 -1
  23. package/element/{BOsbbHJ0.js → D9jzGMeN.js} +3 -3
  24. package/element/DExU6-v2.js +5 -0
  25. package/element/{CmcA5dp5.js → DMAkdDxr.js} +32 -32
  26. package/element/DMPvw0Jw.js +3 -0
  27. package/element/DjFlbVE4.js +8 -0
  28. package/element/{DO2-BnvU.js → DjKx2bl9.js} +3 -2
  29. package/element/{DRD9__VZ.js → DkrE1H9J.js} +1 -1
  30. package/element/DnrkqfsH.js +14 -0
  31. package/element/ILtcTVir.js +93 -0
  32. package/element/{BOweSM9Y.js → PxjP9VKW.js} +1 -1
  33. package/element/{DjOFnmwA.js → RLxieWpc.js} +1 -1
  34. package/element/{GwDdmgYd.js → SAPFe3AV.js} +1 -1
  35. package/element/ThvpIBOm.js +4 -0
  36. package/element/X8kQCV14.js +5 -0
  37. package/element/{CoARa5_i.js → ZWATOkpE.js} +1 -1
  38. package/element/{CE0UwtGX.js → k9JmIPl-.js} +7 -7
  39. package/element/{iDDlbtVI.js → pRu0r7dI.js} +1 -1
  40. package/element/plowVrDm.js +4 -0
  41. package/element/{XVFdeOm22.js → qTO-oPOF.js} +1 -1
  42. package/element/web.es.js +1 -1
  43. package/element/x3_URwMQ.js +3 -0
  44. package/element/{BeaTNG7m.js → xPFFaUda.js} +1 -1
  45. package/embed/embed.js +1 -1
  46. package/package.json +1 -1
  47. package/element/3CNVs83G2.js +0 -4
  48. package/element/B2ryYFFr.js +0 -4
  49. package/element/BNHdfdME.js +0 -1
  50. package/element/BP08t9Jp2.js +0 -8
  51. package/element/BRwZXuo82.js +0 -3
  52. package/element/BiCaKAmb.js +0 -4
  53. package/element/Bv4TkNQ42.js +0 -85
  54. package/element/BypLxR3J.js +0 -16
  55. package/element/C7zv6hcG.js +0 -1
  56. package/element/CD73UkPZ.js +0 -2
  57. package/element/CGlyix6P.js +0 -93
  58. package/element/Cr5o77zq.js +0 -199
  59. package/element/D3OYeY482.js +0 -8
  60. package/element/DVo8WBwP2.js +0 -4
  61. package/element/DXFmV-Ty2.js +0 -14
  62. package/element/Da6CorI52.js +0 -5
  63. package/element/DdACKOZr.js +0 -1
  64. package/element/DnnkdZ6w2.js +0 -3
  65. package/element/DsU4DxSM.js +0 -3
  66. package/element/OnH8Izqn.js +0 -1
  67. package/element/_d0Pbeg3.js +0 -5
  68. package/element/cjsXyqlO2.js +0 -1
  69. package/element/tvCSWnLG.js +0 -2
  70. /package/element/{BUDCYszs2.js → BUDCYszs.js} +0 -0
  71. /package/element/{CfMNBPpx2.js → CfMNBPpx.js} +0 -0
  72. /package/element/{DnIueBGr2.js → DnIueBGr.js} +0 -0
@@ -0,0 +1,85 @@
1
+ import{r as e,t}from"./BlsbPO0-.js";import{An as r,Cn as i,Ct as n,Et as o,Gt as s,I as a,K as l,Kt as c,Mt as d,Rt as u,Sn as h,Tn as p,Tt as m,Wt as g,Zt as f,_n as v,_t as y,gn as b,hn as w,i as x,it as S,kt as T,mn as C,nt as F,pt as M,st as E,un as k,vn as _,vt as U,wn as R,xn as I,xt as N,yn as P,yt as O}from"./BhYfK52W.js";import{r as A}from"./Bpjf4eY9.js";import{t as q}from"./k9JmIPl-.js";import{t as D}from"./Crg6P9Om.js";import{a as L,i as z,n as j,o as $,r as B,s as H}from"./CfNXbM5H.js";import{a as V,i as W,n as G,o as X,r as Y,t as K}from"./DjKx2bl9.js";import{t as Q}from"./RLxieWpc.js";import{i as J,n as Z,r as ee,t as te}from"./BtLTtkX8.js";var re=[];for(let yn=0;yn<256;++yn)re.push((yn+256).toString(16).slice(1));var ie=/* @__PURE__ */new Uint8Array(16);function ne(e,t,r){return t||e||!crypto.randomUUID?function(e,t,r){const i=(e=e||{}).random??e.rng?.()??crypto.getRandomValues(ie);if(i.length<16)throw new Error("Random bytes length must be >= 16");if(i[6]=15&i[6]|64,i[8]=63&i[8]|128,t){if((r=r||0)<0||r+16>t.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[r+e]=i[e];return t}return function(e,t=0){return(re[e[t+0]]+re[e[t+1]]+re[e[t+2]]+re[e[t+3]]+"-"+re[e[t+4]]+re[e[t+5]]+"-"+re[e[t+6]]+re[e[t+7]]+"-"+re[e[t+8]]+re[e[t+9]]+"-"+re[e[t+10]]+re[e[t+11]]+re[e[t+12]]+re[e[t+13]]+re[e[t+14]]+re[e[t+15]]).toLowerCase()}(i)}(e,t,r):crypto.randomUUID()}function oe({checked:e,defaultChecked:t,onChange:r,onBlur:i,label:o,className:s,disabled:a}){const l=e??t??!1,c=l?"checked":"unchecked",d=h();/* @__PURE__ */
2
+ return k("label",{htmlFor:d,className:n("flex items-center gap-2",a&&"cursor-not-allowed opacity-50",!a&&"cursor-pointer"),children:[/* @__PURE__ */k("button",{type:"button",id:d,role:"switch","aria-checked":l,disabled:a,"data-state":c,onBlur:i,onClick:()=>!a&&r?.(!l),className:n("peer relative inline-flex h-6 w-11 shrink-0 items-center rounded-full border-2 transition-colors","border-border bg-muted","focus-visible:ring-2 focus-visible:ring-offset-2","data-[state=checked]:border-primary data-[state=checked]:bg-primary","disabled:cursor-not-allowed disabled:opacity-50",!a&&"cursor-pointer",s),children:/* @__PURE__ */k("span",{"data-state":c,style:{transform:l?"translateX(1.25rem)":"translateX(0)"},className:n("pointer-events-none block size-5 translate-x-0 rounded-full shadow transition-transform","border-border bg-background border","data-[state=checked]:bg-primary-foreground data-[state=checked]:translate-x-5 data-[state=checked]:border-transparent")})}),o&&/* @__PURE__ */k("span",{className:"text-sm font-medium",children:o})]})}var se=["jpg","jpeg","png","webp","heic","tiff","bmp","avif"],ae=["mp4","webm","ogg","mov","avi","flv","wmv","mkv","3gp","m4v","mpg","mpeg"];function le({open:e,oversizedUids:t,onClose:r,onRemoveAndUpload:i}){const n=Object.values(t),o=n.filter(e=>"image"===e).length,s=n.filter(e=>"video"===e).length,a=[];return o>0&&a.push(`${o} image${o>1?"s":""}`),s>0&&a.push(`${s} video${s>1?"s":""}`),/* @__PURE__ */k(K,{open:e,onOpenChange:e=>!e&&r(),children:/* @__PURE__ */k(G,{children:[/* @__PURE__ */k(V,{children:[/* @__PURE__ */k(X,{children:"Some files are too large"}),/* @__PURE__ */k(Y,{children:[a.join(" and ")," exceed",1===n.length?"s":""," the size limit (25 MB for images, 250 MB for videos) and won't be uploaded."]})]}),/* @__PURE__ */k(W,{children:/* @__PURE__ */k(q,{onClick:i,children:"Remove and Upload"})})]})})}function ce({open:e,count:t,onResume:r,onDiscard:i}){/* @__PURE__ */
3
+ return k(K,{open:e,onOpenChange:e=>!e&&i(),children:/* @__PURE__ */k(G,{children:[/* @__PURE__ */k(V,{children:[/* @__PURE__ */k(X,{children:"Resume your upload?"}),/* @__PURE__ */k(Y,{children:["We found ",t," unfinished upload",t>1?"s":""," from your last visit. Resume where you left off, or remove ",t>1?"them":"it"," and start over."]})]}),/* @__PURE__ */k(W,{children:[/* @__PURE__ */k(q,{variant:"outlined",onClick:i,children:"Remove All"}),/* @__PURE__ */k(q,{onClick:r,children:"Resume"})]})]})})}var de=["6a385dabb04f4d8783b14fe1","69ada0f82889f080a9ca53df"],ue=({open:e,onClose:t,onSuccess:r})=>{const{t:i}=A(),[n,o]=I(!1),s=N(),a=s.props?.organizationId??s.organization?._id,{user:l,updateUser:c}=s,d=!!a&&de.includes(a.trim()),u=d?"https://qrati.com/terms-of-use-wedding-private-events":"https://qrati.com/terms-of-use",h=d?"https://qrati.com/privacy-policy-wedding-private-events":"https://qrati.com/privacy-policy";/* @__PURE__ */
4
+ return k(K,{open:e,onOpenChange:e=>!e&&t(),children:/* @__PURE__ */k(G,{className:"text-foreground",children:/* @__PURE__ */k("div",{className:"mx-auto max-w-sm p-4 text-center sm:max-w-lg",children:[
5
+ /* @__PURE__ */k(X,{children:i("upload.terms_title","Terms & Conditions")}),
6
+ /* @__PURE__ */k(Y,{hidden:!0,children:i("upload.terms_description","Please accept our terms to proceed")}),
7
+ /* @__PURE__ */k("div",{className:"mt-4 mb-6",children:/* @__PURE__ */k("p",{className:"bg-background text-foreground text-base",children:[i("upload.terms_prompt","I agree to the")," ",
8
+ /* @__PURE__ */k("a",{href:u,className:"text-info inline-flex items-center gap-1 underline",target:"_blank",rel:"noopener noreferrer",children:i("upload.terms_of_use","Terms of Use")})," ",i("upload.and","and")," ",
9
+ /* @__PURE__ */k("a",{href:h,className:"text-info inline-flex items-center gap-1 underline",target:"_blank",rel:"noopener noreferrer",children:i("upload.privacy_policy","Privacy Policy")})," "]})}),
10
+ /* @__PURE__ */k(q,{fullWidth:!0,color:"success",disabled:n,loading:n,onClick:async()=>{o(!0);try{const e=await f.post(T.ACCEPT_TERMS,{headers:{"x-org-id":a,Authorization:l?.token?`Bearer ${l.token}`:void 0}}).json();if(e.error)throw new Error(e.error);await c({tcAccepted:!0}),o(!1),r()}catch(e){m(e instanceof Error?e:new Error(String(e)),{component:"TermsAndConditionsModal",tags:["upload","terms-accept"]}),x.error(i("upload.accept_failed","Failed to accept terms"))}o(!1)},children:i("button.accept","Accept")})]})})})},he=({eventSlug:e,locationState:t})=>{const{t:r}=A(),i=e?c.GALLERY(e):c.PUBLIC_EVENTS;/* @__PURE__ */
11
+ return k("div",{className:"mx-auto mt-24 w-fit max-w-xl space-y-8",children:[
12
+ /* @__PURE__ */k(F,{variant:"h3",align:"center",children:r("upload.event_closed","Upload Closed")}),
13
+ /* @__PURE__ */k(F,{variant:"h5",align:"center",color:"muted",children:r("upload.closed_description","This event is no longer accepting uploads.")}),
14
+ /* @__PURE__ */k("div",{className:"flex flex-row justify-end",children:/* @__PURE__ */k(M,{to:i,state:t,children:/* @__PURE__ */k(q,{children:r("button.back_to_events","Back to Events")})})})]})};function pe(e,t){let r=0;const i=[],n=()=>{if(r>=e)return;const t=i.shift();t&&t()};return function(e){return new Promise((o,s)=>{i.push(()=>{r++;const i=()=>function(e){let t;return Promise.race([e.finally(()=>clearTimeout(t)),new Promise((e,r)=>{t=setTimeout(()=>r(/* @__PURE__ */new Error("media task timed out")),3e4)})])}(e()).then(o,s).finally(()=>{r--,n()});t?setTimeout(i,0):i()}),n()})}}var me=pe(2,!1),ge=pe(1,!0);function fe(e,t,r,i,n,o,s,a,l,c,d,u,h,p,m,g,f,v,y,b){return w=>{const{data:x,width:S,height:T}=w,C=new Uint8ClampedArray(x.length);for(let F=0;F<x.length;F+=4){const w=x[F],S=x[F+1],T=x[F+2],M=x[F+3];C[F]=Math.min(255,Math.max(0,Math.round(e*w+t*S+r*T+i*M+255*n))),C[F+1]=Math.min(255,Math.max(0,Math.round(o*w+s*S+a*T+l*M+255*c))),C[F+2]=Math.min(255,Math.max(0,Math.round(d*w+u*S+h*T+p*M+255*m))),C[F+3]=Math.min(255,Math.max(0,Math.round(g*w+f*S+v*T+y*M+255*b)))}return new ImageData(C,S,T)}}function ve(e,t,r,i){const n=Math.cos(i*Math.PI/180),o=Math.sin(i*Math.PI/180);return{r:(.299+.701*n+.168*o)*e,g:(.587-.587*n+.33*o)*t,b:(.114-.114*n-.497*o)*r}}function ye(e){let t=255,r=0,i=0;for(let n=1;n<e.length;n++){const o=e[n]-e[n-1];o>i&&(i=o,t=e[n],r=e[n-1])}return{low:r,high:t}}var be="\nprecision highp float;\nuniform sampler2D u_image;\nuniform vec4 u_row0; uniform float u_off0;\nuniform vec4 u_row1; uniform float u_off1;\nuniform vec4 u_row2; uniform float u_off2;\nuniform vec4 u_row3; uniform float u_off3;\nvarying vec2 v_texCoord;\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n gl_FragColor = clamp(vec4(\n dot(u_row0, c) + u_off0,\n dot(u_row1, c) + u_off1,\n dot(u_row2, c) + u_off2,\n dot(u_row3, c) + u_off3\n ), 0.0, 1.0);\n}".trim(),we=[{id:"underwater-correction",name:"Underwater Color Correction",description:"Restores colors absorbed by water — boosts red channel via histogram normalization",category:"color-correction",analyze(e,t){const r=t.blue_boost??1,i=t.hue_shift??0,n=t.intensity??1,o=function(e,t,r,i=1,n=0){const o=t*r,s=o/2e3,a=/* @__PURE__ */new Int32Array(256),l=/* @__PURE__ */new Int32Array(256),c=/* @__PURE__ */new Int32Array(256);let d=0,u=0,h=0;for(let I=0;I<e.length;I+=4)d+=e[I],u+=e[I+1],h+=e[I+2];const p=d/o,m=u/o,g=h/o;let f=0,v=p;for(;v<60;){const e=ve(p,m,g,f);if(v=e.r+e.g+e.b,f++,f>120)break}const y=f+n;for(let I=0;I<e.length;I+=4){const t=ve(e[I],e[I+1],e[I+2],y);a[Math.min(255,Math.max(0,Math.round(t.r+t.g+t.b)))]++,l[e[I+1]]++,c[e[I+2]]++}const b=[0],w=[0],x=[0];for(let I=0;I<256;I++)a[I]-s<2&&b.push(I),l[I]-s<2&&w.push(I),c[I]-s<2&&x.push(I);b.push(255),w.push(255),x.push(255);const S=ye(b),T=ye(w),C=ye(x),F=256/Math.max(1,S.high-S.low),M=256/Math.max(1,T.high-T.low),E=256/Math.max(1,C.high-C.low),k=-S.low/256*F,_=-T.low/256*M,U=-C.low/256*E,R=ve(1,1,1,y);return{rR:R.r*F,rG:R.g*F,rB:R.b*F,rA:0,rOff:k,gR:0,gG:M,gB:0,gA:0,gOff:_,bR:0,bG:0,bB:E*i,bA:0,bOff:U,aR:0,aG:0,aB:0,aA:1,aOff:0}}(e.data,e.width,e.height,r,i);return{u_row0:[1*(1-n)+o.rR*n,o.rG*n,o.rB*n,o.rA*n],u_off0:o.rOff*n,u_row1:[o.gR*n,1*(1-n)+o.gG*n,o.gB*n,o.gA*n],u_off1:o.gOff*n,u_row2:[o.bR*n,o.bG*n,1*(1-n)+o.bB*n,o.bA*n],u_off2:o.bOff*n,u_row3:[o.aR,o.aG,o.aB,o.aA],u_off3:o.aOff}},fragShader:be,buildCpuTransform(e){const t=e.u_row0,r=e.u_row1,i=e.u_row2,n=e.u_row3;return fe(t[0],t[1],t[2],t[3],e.u_off0,r[0],r[1],r[2],r[3],e.u_off1,i[0],i[1],i[2],i[3],e.u_off2,n[0],n[1],n[2],n[3],e.u_off3)},defaultVariables:{intensity:1,blue_boost:1,hue_shift:0},variableSchema:[{key:"intensity",type:"number",label:"Intensity",min:0,max:1,step:.05,default:1},{key:"blue_boost",type:"number",label:"Blue boost",min:.5,max:2,step:.05,default:1},{key:"hue_shift",type:"number",label:"Hue shift",min:-30,max:30,step:1,default:0}]},{id:"vignette",name:"Vignette Effect",description:"Darken image corners for dramatic effect",category:"stylistic",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_vignette_strength;\nuniform float u_vignette_radius;\nvarying vec2 v_texCoord;\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n vec2 uv = v_texCoord * 2.0 - 1.0;\n float dist = length(uv);\n float factor = 1.0;\n if (dist > u_vignette_radius) {\n float falloff = max(0.001, 1.414 - u_vignette_radius);\n float t = (dist - u_vignette_radius) / falloff;\n factor = 1.0 - clamp(t * u_vignette_strength, 0.0, 0.8);\n }\n gl_FragColor = vec4(c.rgb * factor, c.a);\n}".trim(),buildCpuTransform(e){const t=e.u_vignette_strength??.5,r=e.u_vignette_radius??.7,i=64,n=/* @__PURE__ */new Float32Array(4096);for(let s=0;s<i;s++)for(let e=0;e<i;e++){const o=e/63*2-1,a=s/63*2-1,l=Math.sqrt(o*o+a*a);let c=1;if(l>r){const e=Math.max(.001,1.414-r);c=1-Math.min(.8,(l-r)/e*t)}n[s*i+e]=c}const o=(e,t)=>{const r=Math.min(63,Math.floor(e)),o=Math.min(63,Math.floor(t)),s=Math.min(63,r+1),a=Math.min(63,o+1),l=Math.min(1,e-r),c=Math.min(1,t-o),d=n[o*i+r],u=n[o*i+s],h=n[a*i+r];return d+(u-d)*l+(h-d)*c+(d-u-h+n[a*i+s])*l*c};return e=>{const{data:t,width:r,height:i}=e,n=new Uint8ClampedArray(t.length),s=(e,t)=>e/Math.max(1,t-1)*63;for(let a=0;a<i;a++){const e=s(a,i);for(let i=0;i<r;i++){const l=4*(a*r+i),c=o(s(i,r),e);n[l]=Math.round(t[l]*c),n[l+1]=Math.round(t[l+1]*c),n[l+2]=Math.round(t[l+2]*c),n[l+3]=t[l+3]}}return new ImageData(n,r,i)}},defaultVariables:{vignette_strength:.5,vignette_radius:.7},variableSchema:[{key:"vignette_strength",type:"number",label:"Vignette strength",min:0,max:1,step:.05,default:.5},{key:"vignette_radius",type:"number",label:"Vignette radius",min:0,max:1,step:.05,default:.7}]},{id:"sepia",name:"Sepia Tone",description:"Apply warm sepia tone for vintage look",category:"stylistic",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_sepia_intensity;\nvarying vec2 v_texCoord;\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n float gray = dot(c.rgb, vec3(0.299, 0.587, 0.114));\n vec3 sepia = vec3(\n min(1.0, gray + 40.0 / 255.0),\n min(1.0, gray + 20.0 / 255.0),\n max(0.0, gray - 30.0 / 255.0)\n );\n gl_FragColor = vec4(mix(c.rgb, sepia, u_sepia_intensity), c.a);\n}".trim(),buildCpuTransform(e){const t=e.u_sepia_intensity??.8;return e=>{const{data:r,width:i,height:n}=e,o=new Uint8ClampedArray(r.length);for(let s=0;s<r.length;s+=4){const e=r[s],i=r[s+1],n=r[s+2],a=.299*e+.587*i+.114*n,l=Math.min(255,a+40),c=Math.min(255,a+20),d=Math.max(0,a-30);o[s]=Math.round(e*(1-t)+l*t),o[s+1]=Math.round(i*(1-t)+c*t),o[s+2]=Math.round(n*(1-t)+d*t),o[s+3]=r[s+3]}return new ImageData(o,i,n)}},defaultVariables:{sepia_intensity:.8},variableSchema:[{key:"sepia_intensity",type:"number",label:"Sepia intensity",min:0,max:1,step:.05,default:.8}]},{id:"auto-white-balance",name:"Auto White Balance",description:"Grey-world white balance — equalises channel averages from image analysis",category:"color-correction",analyze(e){const t=e.data,r=e.width*e.height;let i=0,n=0,o=0;for(let d=0;d<t.length;d+=4)i+=t[d],n+=t[d+1],o+=t[d+2];const s=i/r,a=n/r,l=o/r,c=(s+a+l)/3;return{u_gain_r:c/Math.max(1,s),u_gain_g:c/Math.max(1,a),u_gain_b:c/Math.max(1,l)}},fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_gain_r;\nuniform float u_gain_g;\nuniform float u_gain_b;\nvarying vec2 v_texCoord;\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n gl_FragColor = vec4(\n clamp(c.r * u_gain_r, 0.0, 1.0),\n clamp(c.g * u_gain_g, 0.0, 1.0),\n clamp(c.b * u_gain_b, 0.0, 1.0),\n c.a\n );\n}".trim(),buildCpuTransform:e=>fe(e.u_gain_r??1,0,0,0,0,0,e.u_gain_g??1,0,0,0,0,0,e.u_gain_b??1,0,0,0,0,0,1,0),defaultVariables:{},variableSchema:[]},{id:"grayscale",name:"Black & White",description:"Convert image to grayscale using luminance weights",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nvarying vec2 v_texCoord;\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n float gray = dot(c.rgb, vec3(0.299, 0.587, 0.114));\n gl_FragColor = vec4(vec3(gray), c.a);\n}".trim(),buildCpuTransform:()=>e=>{const{data:t,width:r,height:i}=e,n=new Uint8ClampedArray(t.length);for(let o=0;o<t.length;o+=4){const e=.299*t[o]+.587*t[o+1]+.114*t[o+2];n[o]=n[o+1]=n[o+2]=Math.round(e),n[o+3]=t[o+3]}return new ImageData(n,r,i)},defaultVariables:{},variableSchema:[]},{id:"invert",name:"Invert Colors",description:"Invert all color channels for a negative effect",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nvarying vec2 v_texCoord;\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n gl_FragColor = vec4(1.0 - c.rgb, c.a);\n}".trim(),buildCpuTransform:()=>e=>{const{data:t,width:r,height:i}=e,n=new Uint8ClampedArray(t.length);for(let o=0;o<t.length;o+=4)n[o]=255-t[o],n[o+1]=255-t[o+1],n[o+2]=255-t[o+2],n[o+3]=t[o+3];return new ImageData(n,r,i)},defaultVariables:{},variableSchema:[]},{id:"brightness-contrast",name:"Brightness & Contrast",description:"Adjust overall brightness and contrast",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_brightness;\nuniform float u_contrast;\nvarying vec2 v_texCoord;\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n vec3 col = c.rgb + u_brightness;\n col = (col - 0.5) * u_contrast + 0.5;\n gl_FragColor = vec4(clamp(col, 0.0, 1.0), c.a);\n}".trim(),buildCpuTransform(e){const t=e.u_brightness??0,r=e.u_contrast??1;return e=>{const{data:i,width:n,height:o}=e,s=new Uint8ClampedArray(i.length);for(let a=0;a<i.length;a+=4){for(let e=0;e<3;e++){let n=i[a+e]/255+t;n=(n-.5)*r+.5,s[a+e]=Math.min(255,Math.max(0,Math.round(255*n)))}s[a+3]=i[a+3]}return new ImageData(s,n,o)}},defaultVariables:{brightness:0,contrast:1},variableSchema:[{key:"brightness",type:"number",label:"Brightness",min:-.5,max:.5,step:.05,default:0},{key:"contrast",type:"number",label:"Contrast",min:0,max:2,step:.05,default:1}]},{id:"saturation",name:"Saturation",description:"Increase or decrease color saturation",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_saturation;\nvarying vec2 v_texCoord;\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n float gray = dot(c.rgb, vec3(0.299, 0.587, 0.114));\n gl_FragColor = vec4(mix(vec3(gray), c.rgb, u_saturation), c.a);\n}".trim(),buildCpuTransform(e){const t=e.u_saturation??1;return e=>{const{data:r,width:i,height:n}=e,o=new Uint8ClampedArray(r.length);for(let s=0;s<r.length;s+=4){const e=r[s],i=r[s+1],n=r[s+2],a=.299*e+.587*i+.114*n;o[s]=Math.round(a+(e-a)*t),o[s+1]=Math.round(a+(i-a)*t),o[s+2]=Math.round(a+(n-a)*t),o[s+3]=r[s+3]}return new ImageData(o,i,n)}},defaultVariables:{saturation:1.2},variableSchema:[{key:"saturation",type:"number",label:"Saturation",min:0,max:2,step:.05,default:1.2}]},{id:"hue-rotate",name:"Hue Shift",description:"Rotate the hue of all colors",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_hue_shift;\nvarying vec2 v_texCoord;\n\nvec3 hueShift(vec3 color, float hue) {\n vec3 k = vec3(0.57735, 0.57735, 0.57735);\n float cosAngle = cos(hue);\n float sinAngle = sin(hue);\n return color * cosAngle + cross(k, color) * sinAngle + k * dot(k, color) * (1.0 - cosAngle);\n}\n\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n float rad = u_hue_shift * 3.14159265 / 180.0;\n gl_FragColor = vec4(hueShift(c.rgb, rad), c.a);\n}".trim(),buildCpuTransform(e){const t=(e.u_hue_shift??0)*Math.PI/180,r=Math.cos(t),i=Math.sin(t),n=1/Math.sqrt(3);return e=>{const{data:t,width:o,height:s}=e,a=new Uint8ClampedArray(t.length);for(let l=0;l<t.length;l+=4){const e=t[l]/255,o=t[l+1]/255,s=t[l+2]/255,c=n*(e+o+s),d=e*r+n*(s-o)*i+n*c*(1-r),u=o*r+n*(e-s)*i+n*c*(1-r),h=s*r+n*(o-e)*i+n*c*(1-r);a[l]=Math.min(255,Math.max(0,Math.round(255*d))),a[l+1]=Math.min(255,Math.max(0,Math.round(255*u))),a[l+2]=Math.min(255,Math.max(0,Math.round(255*h))),a[l+3]=t[l+3]}return new ImageData(a,o,s)}},defaultVariables:{hue_shift:30},variableSchema:[{key:"hue_shift",type:"number",label:"Hue shift",min:0,max:360,step:5,default:30}]},{id:"gaussian-blur",name:"Soft Blur",description:"Apply a gentle Gaussian-like blur",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_blur_radius;\nuniform vec2 u_resolution;\nvarying vec2 v_texCoord;\n\nvoid main() {\n vec2 off = u_blur_radius / u_resolution;\n vec4 sum = texture2D(u_image, v_texCoord) * 0.25;\n sum += texture2D(u_image, v_texCoord + vec2(off.x, 0.0)) * 0.125;\n sum += texture2D(u_image, v_texCoord - vec2(off.x, 0.0)) * 0.125;\n sum += texture2D(u_image, v_texCoord + vec2(0.0, off.y)) * 0.125;\n sum += texture2D(u_image, v_texCoord - vec2(0.0, off.y)) * 0.125;\n sum += texture2D(u_image, v_texCoord + vec2(off.x, off.y)) * 0.0625;\n sum += texture2D(u_image, v_texCoord - vec2(off.x, off.y)) * 0.0625;\n sum += texture2D(u_image, v_texCoord + vec2(off.x, -off.y)) * 0.0625;\n sum += texture2D(u_image, v_texCoord - vec2(off.x, -off.y)) * 0.0625;\n gl_FragColor = sum;\n}".trim(),buildCpuTransform(e){const t=Math.max(1,Math.round(e.u_blur_radius??2)),r=[[0,0],[t,0],[-t,0],[0,t],[0,-t],[t,t],[-t,-t],[t,-t],[-t,t]],i=[.25,.125,.125,.125,.125,.0625,.0625,.0625,.0625];return e=>{const{data:t,width:n,height:o}=e,s=new Uint8ClampedArray(t.length);for(let a=0;a<o;a++)for(let e=0;e<n;e++){let l=0,c=0,d=0,u=0;for(let s=0;s<9;s++){const h=Math.min(n-1,Math.max(0,e+r[s][0])),p=4*(Math.min(o-1,Math.max(0,a+r[s][1]))*n+h),m=i[s];l+=t[p]*m,c+=t[p+1]*m,d+=t[p+2]*m,u+=t[p+3]*m}const h=4*(a*n+e);s[h]=Math.round(l),s[h+1]=Math.round(c),s[h+2]=Math.round(d),s[h+3]=Math.round(u)}return new ImageData(s,n,o)}},defaultVariables:{blur_radius:2},variableSchema:[{key:"blur_radius",type:"number",label:"Blur radius",min:0,max:8,step:.5,default:2}]},{id:"sharpen",name:"Sharpen",description:"Enhance edge detail for a crisper look",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_sharpen_amount;\nuniform vec2 u_resolution;\nvarying vec2 v_texCoord;\n\nvoid main() {\n vec2 off = 1.0 / u_resolution;\n vec4 c = texture2D(u_image, v_texCoord);\n vec4 left = texture2D(u_image, v_texCoord + vec2(-off.x, 0.0));\n vec4 right = texture2D(u_image, v_texCoord + vec2(off.x, 0.0));\n vec4 up = texture2D(u_image, v_texCoord + vec2(0.0, off.y));\n vec4 down = texture2D(u_image, v_texCoord + vec2(0.0, -off.y));\n vec4 edge = left + right + up + down - 4.0 * c;\n gl_FragColor = vec4(clamp(c.rgb - edge.rgb * u_sharpen_amount, 0.0, 1.0), c.a);\n}".trim(),buildCpuTransform(e){const t=e.u_sharpen_amount??.8;return e=>{const{data:r,width:i,height:n}=e,o=new Uint8ClampedArray(r.length),s=(e,t,o)=>r[4*(Math.min(n-1,Math.max(0,e))*i+Math.min(i-1,Math.max(0,t)))+o];for(let a=0;a<n;a++)for(let e=0;e<i;e++){const n=4*(a*i+e);for(let i=0;i<3;i++){const l=r[n+i],c=s(a,e-1,i)+s(a,e+1,i)+s(a+1,e,i)+s(a-1,e,i)-4*l;o[n+i]=Math.min(255,Math.max(0,Math.round(l-c*t)))}o[n+3]=r[n+3]}return new ImageData(o,i,n)}},defaultVariables:{sharpen_amount:.8},variableSchema:[{key:"sharpen_amount",type:"number",label:"Sharpen amount",min:0,max:3,step:.1,default:.8}]},{id:"edge-detect",name:"Edge Detect",description:"Highlight edges using gradient detection",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_edge_intensity;\nuniform vec2 u_resolution;\nvarying vec2 v_texCoord;\n\nvoid main() {\n vec2 off = 1.0 / u_resolution;\n vec4 c = texture2D(u_image, v_texCoord);\n vec4 left = texture2D(u_image, v_texCoord + vec2(-off.x, 0.0));\n vec4 right = texture2D(u_image, v_texCoord + vec2(off.x, 0.0));\n vec4 up = texture2D(u_image, v_texCoord + vec2(0.0, off.y));\n vec4 down = texture2D(u_image, v_texCoord + vec2(0.0, -off.y));\n vec3 edge = abs(left.rgb - right.rgb) + abs(up.rgb - down.rgb);\n float gray = dot(edge, vec3(0.299, 0.587, 0.114));\n vec3 result = mix(c.rgb, vec3(gray), u_edge_intensity);\n gl_FragColor = vec4(result, c.a);\n}".trim(),buildCpuTransform(e){const t=e.u_edge_intensity??1;return e=>{const{data:r,width:i,height:n}=e,o=new Uint8ClampedArray(r.length),s=(e,t,o)=>r[4*(Math.min(n-1,Math.max(0,e))*i+Math.min(i-1,Math.max(0,t)))+o]/255;for(let a=0;a<n;a++)for(let e=0;e<i;e++){const n=4*(a*i+e),l=.299*(Math.abs(s(a,e-1,0)-s(a,e+1,0))+Math.abs(s(a+1,e,0)-s(a-1,e,0)))+.587*(Math.abs(s(a,e-1,1)-s(a,e+1,1))+Math.abs(s(a+1,e,1)-s(a-1,e,1)))+.114*(Math.abs(s(a,e-1,2)-s(a,e+1,2))+Math.abs(s(a+1,e,2)-s(a-1,e,2)));for(let e=0;e<3;e++){const i=r[n+e]/255;o[n+e]=Math.min(255,Math.max(0,Math.round(255*(i*(1-t)+l*t))))}o[n+3]=r[n+3]}return new ImageData(o,i,n)}},defaultVariables:{edge_intensity:1},variableSchema:[{key:"edge_intensity",type:"number",label:"Edge intensity",min:0,max:1,step:.05,default:1}]},{id:"warm-tone",name:"Warm Tone",description:"Add warm orange-yellow tones",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_warmth;\nvarying vec2 v_texCoord;\n\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n vec3 warm = c.rgb + vec3(0.08, 0.03, -0.05) * u_warmth;\n gl_FragColor = vec4(clamp(warm, 0.0, 1.0), c.a);\n}".trim(),buildCpuTransform(e){const t=e.u_warmth??.5;return e=>{const{data:r,width:i,height:n}=e,o=new Uint8ClampedArray(r.length);for(let s=0;s<r.length;s+=4)o[s]=Math.min(255,Math.max(0,Math.round(r[s]+20.4*t))),o[s+1]=Math.min(255,Math.max(0,Math.round(r[s+1]+7.65*t))),o[s+2]=Math.min(255,Math.max(0,Math.round(r[s+2]-12.75*t))),o[s+3]=r[s+3];return new ImageData(o,i,n)}},defaultVariables:{warmth:.5},variableSchema:[{key:"warmth",type:"number",label:"Warmth",min:0,max:1,step:.05,default:.5}]},{id:"cool-tone",name:"Cool Tone",description:"Add cool blue-cyan tones",category:"utility",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform float u_coolness;\nvarying vec2 v_texCoord;\n\nvoid main() {\n vec4 c = texture2D(u_image, v_texCoord);\n vec3 cool = c.rgb + vec3(-0.05, 0.02, 0.08) * u_coolness;\n gl_FragColor = vec4(clamp(cool, 0.0, 1.0), c.a);\n}".trim(),buildCpuTransform(e){const t=e.u_coolness??.5;return e=>{const{data:r,width:i,height:n}=e,o=new Uint8ClampedArray(r.length);for(let s=0;s<r.length;s+=4)o[s]=Math.min(255,Math.max(0,Math.round(r[s]-12.75*t))),o[s+1]=Math.min(255,Math.max(0,Math.round(r[s+1]+5.1*t))),o[s+2]=Math.min(255,Math.max(0,Math.round(r[s+2]+20.4*t))),o[s+3]=r[s+3];return new ImageData(o,i,n)}},defaultVariables:{coolness:.5},variableSchema:[{key:"coolness",type:"number",label:"Coolness",min:0,max:1,step:.05,default:.5}]},{id:"custom-script",name:"Custom Shader",description:"Write a custom GLSL fragment shader",category:"custom",fragShader:"\nprecision highp float;\nuniform sampler2D u_image;\nuniform vec2 u_resolution;\nvarying vec2 v_texCoord;\nvoid main() {\n // Your custom shader here.\n // Example — invert colours:\n // vec4 c = texture2D(u_image, v_texCoord);\n // gl_FragColor = vec4(1.0 - c.rgb, c.a);\n gl_FragColor = texture2D(u_image, v_texCoord);\n}".trim(),defaultVariables:{},variableSchema:[]}];function xe(e){return we.find(t=>t.id===e)}function Se(e,t){if(e){if("number"===e.type){if("number"!=typeof t||!Number.isFinite(t))return;const r=e.min??-1/0,i=e.max??1/0;return Math.min(i,Math.max(r,t))}return"boolean"===e.type?"boolean"==typeof t?t:void 0:"string"==typeof t?t:void 0}}var Te="\nattribute vec2 a_position;\nvarying vec2 v_texCoord;\nvoid main() {\n gl_Position = vec4(a_position, 0.0, 1.0);\n v_texCoord = a_position * 0.5 + 0.5;\n}".trim(),Ce=new Float32Array([-1,-1,1,-1,-1,1,-1,1,1,-1,1,1]),Fe=null,Me=null,Ee=null;function ke(e,t,r){const i=e.createShader(t);if(!i)return null;if(e.shaderSource(i,r),e.compileShader(i),!e.getShaderParameter(i,e.COMPILE_STATUS)){const r=e.getShaderInfoLog(i);return console.warn("[webgl-filter] shader error:",r),m(/* @__PURE__ */new Error(`WebGL shader compilation failed: ${r}`),{component:"webgl-filter-engine",tags:["upload","filter","webgl","shader"],extra:{shaderType:t===e.VERTEX_SHADER?"vertex":"fragment"}}),e.deleteShader(i),null}return i}function _e(e,t){const r=ke(e,e.VERTEX_SHADER,Te),i=ke(e,e.FRAGMENT_SHADER,t);if(!r||!i)return e.deleteShader(r),e.deleteShader(i),null;const n=e.createProgram();if(e.attachShader(n,r),e.attachShader(n,i),e.linkProgram(n),e.deleteShader(r),e.deleteShader(i),!e.getProgramParameter(n,e.LINK_STATUS)){const r=e.getProgramInfoLog(n);return console.warn("[webgl-filter] link error:",r),m(/* @__PURE__ */new Error(`WebGL program link failed: ${r}`),{component:"webgl-filter-engine",tags:["upload","filter","webgl","link"],extra:{fragmentLength:t.length}}),e.deleteProgram(n),null}return n}function Ue(e){const t=e.createTexture();return e.bindTexture(e.TEXTURE_2D,t),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),t}function Re(e,t,r){const i=Ue(e);e.texImage2D(e.TEXTURE_2D,0,e.RGBA,t,r,0,e.RGBA,e.UNSIGNED_BYTE,null);const n=e.createFramebuffer();return e.bindFramebuffer(e.FRAMEBUFFER,n),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,i,0),e.bindFramebuffer(e.FRAMEBUFFER,null),{fbo:n,tex:i}}function Ie(e,t,r){for(const[i,n]of Object.entries(r)){const r=e.getUniformLocation(t,i);if(r)if("number"!=typeof n)switch(n.length){case 2:e.uniform2fv(r,n);break;case 3:e.uniform3fv(r,n);break;case 4:e.uniform4fv(r,n)}else e.uniform1f(r,n)}}function Ne(e){const t=e.config,r=t?.templateId,i=t?.fragShader;if(r){const e=xe(r);return{def:e??null,fragShader:e?.fragShader??null}}return i?{def:null,fragShader:i}:{def:null,fragShader:null}}function Pe(e){const t=e.config?.variables??{},r={};for(const[i,n]of Object.entries(t))"number"==typeof n&&(r[`u_${i}`]=n);return r}async function Oe(e,t,r,i="image/webp",n=.85){const o=Date.now(),s=t.filter(e=>e.enabled);if(!s.length)return{blob:e,appliedFilters:[],width:0,height:0,processingTime:0};const a=await createImageBitmap(e);let l=a.width,c=a.height;if(l>r||c>r){const e=Math.min(r/l,r/c);l=Math.round(l*e),c=Math.round(c*e)}const d=Math.min(150,l),u=Math.max(1,Math.round(d*c/l)),h=new OffscreenCanvas(d,u).getContext("2d");h.drawImage(a,0,0,d,u);const p=h.getImageData(0,0,d,u);let m;if(a.width!==l||a.height!==c){const e=new OffscreenCanvas(l,c);e.getContext("2d").drawImage(a,0,0,l,c),a.close(),m=await createImageBitmap(e,{imageOrientation:"flipY"})}else m=await createImageBitmap(a,{imageOrientation:"flipY"}),a.close();const g=Fe??new OffscreenCanvas(l,c);g.width===l&&g.height===c||(g.width=l,g.height=c),Fe=g;let f=Me;if(f||(f=g.getContext("webgl",{preserveDrawingBuffer:!0,alpha:!0})||g.getContext("experimental-webgl",{preserveDrawingBuffer:!0,alpha:!0}),Me=f),!f||f.isContextLost())return m.close(),Me=null,Fe=null,async function(e,t,r,i,n,o,s="image/webp",a=.85){const l=new OffscreenCanvas(r,i),c=l.getContext("2d"),d=await createImageBitmap(e);c.drawImage(d,0,0,r,i),d.close();const u=[];for(const h of t){const{def:e}=Ne(h);if(!e?.buildCpuTransform)continue;const t=e.analyze?e.analyze(n,h.config?.variables??{}):{},o={},s=h.config?.variables??{};for(const[r,i]of Object.entries(s))"number"==typeof i&&(o[`u_${r}`]=i);const a=e.buildCpuTransform({...t,...o},r,i),l=c.getImageData(0,0,r,i);c.putImageData(a(l),0,0),u.push(h.id)}return u.length?{blob:await l.convertToBlob({type:s,quality:a}),appliedFilters:u,width:r,height:i,processingTime:Date.now()-o}:{blob:e,appliedFilters:[],width:r,height:i,processingTime:Date.now()-o}}(e,s,l,c,p,o,i,n);const v=Ue(f);f.bindTexture(f.TEXTURE_2D,v),f.texImage2D(f.TEXTURE_2D,0,f.RGBA,f.RGBA,f.UNSIGNED_BYTE,m),m.close(),f.viewport(0,0,l,c);const y=[Re(f,l,c),Re(f,l,c)],b=f.createBuffer();f.bindBuffer(f.ARRAY_BUFFER,b),f.bufferData(f.ARRAY_BUFFER,Ce,f.STATIC_DRAW);const w=Ee??/* @__PURE__ */new Map;Ee=w;const x=[];let S=v,T=0;try{for(let e=0;e<s.length;e++){const t=s[e],r=e===s.length-1,{def:i,fragShader:n}=Ne(t);if(!n)continue;const o=t.config?.templateId??n;w.has(o)||w.set(o,_e(f,n));const a=w.get(o);if(!a)continue;f.useProgram(a);const d=f.getAttribLocation(a,"a_position");f.bindBuffer(f.ARRAY_BUFFER,b),f.enableVertexAttribArray(d),f.vertexAttribPointer(d,2,f.FLOAT,!1,0,0),f.activeTexture(f.TEXTURE0),f.bindTexture(f.TEXTURE_2D,S),f.uniform1i(f.getUniformLocation(a,"u_image"),0);const u=f.getUniformLocation(a,"u_resolution");if(u&&f.uniform2f(u,l,c),Ie(f,a,Pe(t)),i?.analyze&&Ie(f,a,i.analyze(p,t.config?.variables??{})),r)f.bindFramebuffer(f.FRAMEBUFFER,null),f.drawArrays(f.TRIANGLES,0,6);else{const e=y[T];f.bindFramebuffer(f.FRAMEBUFFER,e.fbo),f.drawArrays(f.TRIANGLES,0,6),S=e.tex,T=1-T}x.push(t.id)}return x.length?{blob:await g.convertToBlob({type:i,quality:n}),appliedFilters:x,width:l,height:c,processingTime:Date.now()-o}:{blob:e,appliedFilters:[],width:l,height:c,processingTime:Date.now()-o}}finally{for(const{fbo:e,tex:t}of y)f.deleteFramebuffer(e),f.deleteTexture(t);f.deleteTexture(v),f.deleteBuffer(b)}}async function Ae(e,t,r,i){const n=Date.now(),o=e.filter(e=>e.enabled),s=e=>e;if(!o.length)return{transform:s,appliedFilters:[],processingTime:0};let a=null;try{const e=await createImageBitmap(t),r=Math.min(64,e.width),i=Math.round(r*e.height/e.width),n=new OffscreenCanvas(r,Math.max(1,i)).getContext("2d");n.drawImage(e,0,0,r,Math.max(1,i)),e.close(),a=n.getImageData(0,0,r,Math.max(1,i))}catch{}const l=[],c=[];for(const u of o){const{def:e}=Ne(u);if(!e?.buildCpuTransform)continue;const t=u.config?.variables??{},n=e.analyze&&a?e.analyze(a,t):{},o={};for(const[r,i]of Object.entries(t))"number"==typeof i&&(o[`u_${r}`]=i);try{const t=e.buildCpuTransform({...n,...o},r,i);l.push(t),c.push(u.id)}catch(d){console.warn(`[webgl-filter] buildCpuTransform failed for ${u.id}:`,d),m(d instanceof Error?d:/* @__PURE__ */new Error(`buildCpuTransform failed for ${u.id}`),{component:"webgl-filter-engine",tags:["upload","filter","cpu-transform"],extra:{filterId:u.id}})}}return l.length?{transform:1===l.length?l[0]:e=>l.reduce((e,t)=>t(e),e),appliedFilters:c,processingTime:Date.now()-n}:{transform:s,appliedFilters:[],processingTime:Date.now()-n}}var qe=800;async function De(e){return new Promise((t,r)=>{const i=new FileReader;i.onload=()=>t(i.result),i.onerror=()=>r(/* @__PURE__ */new Error("FileReader failed")),i.readAsDataURL(e)})}async function Le(e,t){const r=Date.now(),i=t.filter(e=>e.enabled),n=await B(e);let o,s;const a=await createImageBitmap(n,{resizeWidth:qe});if(o=a.width,s=a.height,s>qe){const e=qe/s;o=Math.round(o*e),s=qe}const l=new OffscreenCanvas(o,s);l.getContext("2d").drawImage(a,0,0,o,s),a.close();const c=await l.convertToBlob({type:"image/jpeg",quality:.92}),d=await De(c);if(!i.length)return{original:d,processed:d,appliedFilters:[],failedFilters:[],totalExecutionTime:Date.now()-r};let u=d;const h=[],p=[];try{const e=await Oe(c,i,qe,"image/jpeg",.92);e.appliedFilters.length>0&&(u=await De(e.blob),h.push(...e.appliedFilters));for(const t of i)e.appliedFilters.includes(t.id)||p.push({id:t.id,error:"Filter not applied"})}catch(g){for(const e of i)p.push({id:e.id,error:g instanceof Error?g.message:"Unknown error"});m(g instanceof Error?g:/* @__PURE__ */new Error("Filter preview failed"),{component:"client-filter-engine",tags:["upload","filter-preview","webgl"],extra:{filterCount:i.length,failedFilters:p.map(e=>e.id)}})}return{original:d,processed:u,appliedFilters:h,failedFilters:p,totalExecutionTime:Date.now()-r}}var ze=/* @__PURE__ */new Map;function je(e,t,r,i){return`${e}:${JSON.stringify(t)}:${r}x${i}`}function $e(e){const t=ze.get(e);return t&&(ze.delete(e),ze.set(e,t)),t}function Be(e,t){if(ze.delete(e),ze.set(e,t),ze.size>3){const e=ze.keys().next().value;void 0!==e&&ze.delete(e)}}var He=e=>{let t;const r=/* @__PURE__ */new Set,i=(e,i)=>{const n="function"==typeof e?e(t):e;if(!Object.is(n,t)){const e=t;t=(null!=i?i:"object"!=typeof n||null===n)?n:Object.assign({},t,n),r.forEach(r=>r(t,e))}},n=()=>t,o={setState:i,getState:n,getInitialState:()=>s,subscribe:e=>(r.add(e),()=>r.delete(e))},s=t=e(i,n,o);return o},Ve=e=>e;var We=r(null);function Ge({children:e,...t}){const r=_(null),i=_(t);return r.current&&t.eventId===i.current.eventId&&t.groupId===i.current.groupId||(r.current=function(e){return(t=t=>({eventId:e.eventId,groupId:e.groupId,selectedFiles:[],originalFiles:{},captions:{},hasStarted:!1,oversizedUids:{},showOversizedModal:!1,trimRanges:{},cropSelections:{},videoMuted:!0,uploadStates:{},uploadSpeedBps:0,showRestoreDialog:!1,restoredUids:[],activeFilters:[],showFilterChoice:!1,skipUploadFilters:!1,perFileFilterSkipped:{},filteredThumbs:{},filterOverrides:{},setSelectedFiles:e=>t(t=>({selectedFiles:"function"==typeof e?e(t.selectedFiles):e})),addOriginalFiles:e=>t(t=>({originalFiles:{...t.originalFiles,...e}})),removeFile:e=>t(t=>{if(!t.selectedFiles.some(t=>t.uid===e))return t;const r={...t.captions};delete r[e];const i={...t.oversizedUids};delete i[e];const n={...t.trimRanges};delete n[e];const o={...t.originalFiles};delete o[e];const s={...t.cropSelections};delete s[e];const a={...t.uploadStates};t.hasStarted||delete a[e];const l={...t.filteredThumbs};delete l[e];const c={...t.perFileFilterSkipped};delete c[e];const d={...t.filterOverrides};return delete d[e],{selectedFiles:t.selectedFiles.filter(t=>t.uid!==e),captions:r,oversizedUids:i,trimRanges:n,originalFiles:o,cropSelections:s,uploadStates:a,filteredThumbs:l,perFileFilterSkipped:c,filterOverrides:d}}),setCaption:(e,r)=>t(t=>({captions:{...t.captions,[e]:r}})),setHasStarted:e=>t({hasStarted:e}),addOversizedUids:e=>t(t=>({oversizedUids:{...t.oversizedUids,...e}})),removeOversizedFiles:()=>t(e=>{const t=new Set(Object.keys(e.oversizedUids)),r={...e.captions},i={...e.trimRanges},n={...e.originalFiles},o={...e.cropSelections},s={...e.uploadStates},a={...e.filteredThumbs},l={...e.perFileFilterSkipped},c={...e.filterOverrides};return t.forEach(e=>{delete r[e],delete i[e],delete n[e],delete o[e],delete s[e],delete a[e],delete l[e],delete c[e]}),{selectedFiles:e.selectedFiles.filter(e=>!t.has(e.uid)),captions:r,trimRanges:i,originalFiles:n,cropSelections:o,uploadStates:s,filteredThumbs:a,perFileFilterSkipped:l,filterOverrides:c,oversizedUids:{},showOversizedModal:!1}}),setShowOversizedModal:e=>t({showOversizedModal:e}),replaceFile:(e,r,i)=>t(t=>{const n={...t.cropSelections};i&&(n[e]=i);const o={...t.filteredThumbs};return delete o[e],{selectedFiles:t.selectedFiles.map(t=>t.uid===e?{...t,file:r}:t),cropSelections:n,filteredThumbs:o}}),setTrimRange:(e,r)=>t(t=>({trimRanges:{...t.trimRanges,[e]:r}})),setVideoMuted:e=>t({videoMuted:e}),setUploadState:(e,r)=>t(t=>({uploadStates:{...t.uploadStates,[e]:{...t.uploadStates[e],...r}}})),setUploadSpeedBps:e=>t({uploadSpeedBps:e}),setActiveFilters:(e,r)=>t({activeFilters:e,showFilterChoice:r}),setSkipUploadFilters:e=>t({skipUploadFilters:e}),setFileFilterSkipped:(e,r)=>t(t=>({perFileFilterSkipped:{...t.perFileFilterSkipped,[e]:r}})),setFilterOverride:(e,r,i,n)=>t(t=>{const o={...t.filteredThumbs};return delete o[e],{filterOverrides:{...t.filterOverrides,[e]:{...t.filterOverrides[e],[r]:{...t.filterOverrides[e]?.[r],[i]:n}}},filteredThumbs:o}}),resetFilterOverrides:e=>t(t=>{const r={...t.filterOverrides};delete r[e];const i={...t.filteredThumbs};return delete i[e],{filterOverrides:r,filteredThumbs:i}}),setFilteredThumb:(e,r)=>t(t=>({filteredThumbs:{...t.filteredThumbs,[e]:r}})),resetUploader:()=>{ze.clear(),t({selectedFiles:[],originalFiles:{},captions:{},hasStarted:!1,oversizedUids:{},showOversizedModal:!1,trimRanges:{},cropSelections:{},uploadStates:{},uploadSpeedBps:0,skipUploadFilters:!1,perFileFilterSkipped:{},filteredThumbs:{},filterOverrides:{}})}}))?He(t):He;var t}(t),i.current=t),/* @__PURE__ */k(We.Provider,{value:r.current,children:e})}function Xe(e){const t=p(We);if(!t)throw new Error("useUploadStore must be used within UploadStoreProvider");return function(e,t=Ve){const r=b.useSyncExternalStore(e.subscribe,b.useCallback(()=>t(e.getState()),[e,t]),()=>t(e.getInitialState()));return b.useDebugValue(r),r}(t,e)}function Ye(){const e=p(We);if(!e)throw new Error("useUploadStoreInstance must be used within UploadStoreProvider");return e}var Ke=/* @__PURE__ */new Map,Qe=null;function Je({className:e}){/* @__PURE__ */
15
+ return k("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */k("path",{fill:"currentColor",d:"m20 7l-.95-2.05L17 4l2.05-.95L20 1l.95 2.05L23 4l-2.05.95L20 7ZM8.5 7l-.95-2.05L5.5 4l2.05-.95L8.5 1l.95 2.05L11.5 4l-2.05.95L8.5 7ZM20 18.5l-.95-2.05L17 15.5l2.05-.95l.95-2.05l.95 2.05l2.05.95l-2.05.95L20 18.5ZM5.1 21.7l-2.8-2.8q-.3-.3-.3-.725t.3-.725L13.45 6.3q.3-.3.725-.3t.725.3l2.8 2.8q.3.3.3.725t-.3.725L6.55 21.7q-.3.3-.725.3t-.725-.3Zm9.075-10.475l1.4-1.4l-1.4-1.4l-1.4 1.4l1.4 1.4Z"})})}function Ze({className:e}){/* @__PURE__ */
16
+ return k("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */k("path",{fill:"currentColor",d:"m19.55 6.025l-.5-1.075l-1.075-.5Q17.7 4.325 17.7 4t.275-.45l1.075-.5l.5-1.075q.125-.275.45-.275t.45.275l.5 1.075l1.075.5q.275.125.275.45t-.275.45l-1.075.5l-.5 1.075q-.125.275-.45.275t-.45-.275Zm-4 6.675L11.3 8.45l2.15-2.15q.3-.3.725-.3t.725.3l2.8 2.8q.3.3.3.725t-.3.725l-2.15 2.15Zm3.55 9.2l-6.4-6.35l-6.15 6.15q-.3.3-.725.3t-.725-.3l-2.8-2.85q-.275-.275-.275-.7t.275-.7l6.15-6.15L2.1 4.9q-.3-.3-.3-.7t.3-.7q.275-.275.7-.275t.7.275l17 17q.275.275.275.7t-.275.7q-.3.3-.7.3t-.7-.3Z"})})}function et({className:e}){/* @__PURE__ */
17
+ return k("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */k("path",{fill:"currentColor",d:"M10 21H5q-.825 0-1.412-.587T3 19V5q0-.825.588-1.412T5 3h5V2q0-.425.288-.712T11 1t.713.288T12 2v20q0 .425-.288.713T11 23t-.712-.288T10 22zm-5-3h5v-6zm9 3v-9l5 6V5h-5V3h5q.825 0 1.413.588T21 5v14q0 .825-.587 1.413T19 21z"})})}function tt({className:e}){/* @__PURE__ */
18
+ return k("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */k("path",{fill:"currentColor",d:"m12 14l-2.35 2.35q.2.375.275.8T10 18q0 1.65-1.175 2.825T6 22t-2.825-1.175T2 18t1.175-2.825T6 14q.425 0 .85.075t.8.275L10 12L7.65 9.65q-.375.2-.8.275T6 10q-1.65 0-2.825-1.175T2 6t1.175-2.825T6 2t2.825 1.175T10 6q0 .425-.075.85t-.275.8L20.6 18.6q.675.675.3 1.538T19.575 21q-.275 0-.537-.112t-.463-.313zm3-3l-2-2l5.575-5.575q.2-.2.463-.312T19.574 3q.95 0 1.313.875t-.313 1.55zM7.413 7.413Q8 6.825 8 6t-.587-1.412T6 4t-1.412.588T4 6t.588 1.413T6 8t1.413-.587m4.937 4.937q.15-.15.15-.35t-.15-.35t-.35-.15t-.35.15t-.15.35t.15.35t.35.15t.35-.15m-4.937 7.063Q8 18.825 8 18t-.587-1.412T6 16t-1.412.588T4 18t.588 1.413T6 20t1.413-.587"})})}function rt({className:e}){/* @__PURE__ */
19
+ return k("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */k("path",{fill:"currentColor",d:"M17 22v-3H7q-.825 0-1.412-.587T5 17V7H2q-.425 0-.712-.288T1 6t.288-.712T2 5h3V2q0-.425.288-.712T6 1t.713.288T7 2v15h15q.425 0 .713.288T23 18t-.288.713T22 19h-3v3q0 .425-.288.713T18 23t-.712-.288T17 22m0-7V7H9V5h8q.825 0 1.413.588T19 7v8z"})})}function it({className:e}){/* @__PURE__ */
20
+ return k("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */k("path",{fill:"currentColor",d:"M6 22q-.825 0-1.412-.587T4 20V4q0-.825.588-1.412T6 2h7.175q.4 0 .763.15t.637.425l4.85 4.85q.275.275.425.638t.15.762V20q0 .825-.587 1.413T18 22zm7-14q0 .425.288.713T14 9h4l-5-5z"})})}function nt({className:e}){/* @__PURE__ */
21
+ return k("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */k("path",{fill:"currentColor",d:"M16 19q-.825 0-1.412-.587T14 17V7q0-.825.588-1.412T16 5t1.413.588T18 7v10q0 .825-.587 1.413T16 19m-8 0q-.825 0-1.412-.587T6 17V7q0-.825.588-1.412T8 5t1.413.588T10 7v10q0 .825-.587 1.413T8 19"})})}function ot({className:e}){/* @__PURE__ */
22
+ return k("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */k("path",{fill:"currentColor",d:"M8 17.175V6.825q0-.425.3-.713t.7-.287q.125 0 .263.037t.262.113l8.15 5.175q.225.15.338.375t.112.475t-.112.475t-.338.375l-8.15 5.175q-.125.075-.262.113T9 18.175q-.4 0-.7-.288t-.3-.712"})})}function st({className:e}){/* @__PURE__ */
23
+ return k("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */k("path",{fill:"currentColor",d:"M16.775 19.575q-.275.175-.55.325t-.575.275q-.375.175-.762 0t-.538-.575q-.15-.375.038-.737t.562-.538q.1-.05.188-.1t.187-.1L12 14.8v2.775q0 .675-.612.938T10.3 18.3L7 15H4q-.425 0-.712-.288T3 14v-4q0-.425.288-.712T4 9h2.2L2.1 4.9q-.275-.275-.275-.7t.275-.7t.7-.275t.7.275l17 17q.275.275.275.7t-.275.7t-.7.275t-.7-.275zm2.225-7.6q0-2.075-1.1-3.787t-2.95-2.563q-.375-.175-.55-.537t-.05-.738q.15-.4.538-.575t.787 0Q18.1 4.85 19.55 7.05T21 11.975q0 .825-.15 1.638t-.425 1.562q-.2.55-.612.688t-.763.012t-.562-.45t-.013-.75q.275-.65.4-1.312T19 11.975m-4.225-3.55Q15.6 8.95 16.05 10t.45 2v.25q0 .125-.025.25q-.05.325-.35.425t-.55-.15L14.3 11.5q-.15-.15-.225-.337T14 10.775V8.85q0-.3.263-.437t.512.012M9.75 6.95Q9.6 6.8 9.6 6.6t.15-.35l.55-.55q.475-.475 1.087-.213t.613.938V8q0 .35-.3.475t-.55-.125z"})})}function at({className:e}){/* @__PURE__ */
24
+ return k("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */k("path",{fill:"currentColor",d:"M19 11.975q0-2.075-1.1-3.787t-2.95-2.563q-.375-.175-.55-.537t-.05-.738q.15-.4.538-.575t.787 0Q18.1 4.85 19.55 7.063T21 11.974t-1.45 4.913t-3.875 3.287q-.4.175-.788 0t-.537-.575q-.125-.375.05-.737t.55-.538q1.85-.85 2.95-2.562t1.1-3.788M7 15H4q-.425 0-.712-.288T3 14v-4q0-.425.288-.712T4 9h3l3.3-3.3q.475-.475 1.088-.213t.612.938v11.15q0 .675-.612.938T10.3 18.3zm9.5-3q0 1.05-.475 1.988t-1.25 1.537q-.25.15-.513.013T14 15.1V8.85q0-.3.263-.437t.512.012q.775.625 1.25 1.575t.475 2"})})}function lt({className:e}){/* @__PURE__ */
25
+ return k("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */k("path",{fill:"currentColor",d:"M6 18H4q-.425 0-.712-.288T3 17t.288-.712T4 16h3q.425 0 .713.288T8 17v3q0 .425-.288.713T7 21t-.712-.288T6 20zm12 0v2q0 .425-.288.713T17 21t-.712-.288T16 20v-3q0-.425.288-.712T17 16h3q.425 0 .713.288T21 17t-.288.713T20 18zM6 6V4q0-.425.288-.712T7 3t.713.288T8 4v3q0 .425-.288.713T7 8H4q-.425 0-.712-.288T3 7t.288-.712T4 6zm12 0h2q.425 0 .713.288T21 7t-.288.713T20 8h-3q-.425 0-.712-.288T16 7V4q0-.425.288-.712T17 3t.713.288T18 4z"})})}function ct({className:e}){/* @__PURE__ */
26
+ return k("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:e,"aria-hidden":"true",focusable:"false",children:/* @__PURE__ */k("path",{fill:"currentColor",d:"M5 19h2q.425 0 .713.288T8 20t-.288.713T7 21H4q-.425 0-.712-.288T3 20v-3q0-.425.288-.712T4 16t.713.288T5 17zm14 0v-2q0-.425.288-.712T20 16t.713.288T21 17v3q0 .425-.288.713T20 21h-3q-.425 0-.712-.288T16 20t.288-.712T17 19zM5 5v2q0 .425-.288.713T4 8t-.712-.288T3 7V4q0-.425.288-.712T4 3h3q.425 0 .713.288T8 4t-.288.713T7 5zm14 0h-2q-.425 0-.712-.288T16 4t.288-.712T17 3h3q.425 0 .713.288T21 4v3q0 .425-.288.713T20 8t-.712-.288T19 7z"})})}function dt(e){return e.flatMap(e=>{const t=e.config.adjustableKeys;if(!t?.length||!e.config.templateId)return[];const r=xe(e.config.templateId);return r?r.variableSchema.filter(e=>t.includes(e.key)).map(t=>({filterId:e.id,filterName:e.name,v:t})):[]})}function ut({filters:e,overrides:t,onChange:r}){const i=dt(e);return 0===i.length?null:/* @__PURE__ */k("div",{className:"space-y-4",children:i.map(({filterId:e,filterName:n,v:o})=>{const s=t?.[e]?.[o.key]??o.default;/* @__PURE__ */
27
+ return k("div",{className:"space-y-1",children:[
28
+ /* @__PURE__ */k("label",{htmlFor:`${e}:${o.key}`,className:"flex items-center justify-between text-sm",children:[/* @__PURE__ */k("span",{children:[o.label,i.length>1&&/* @__PURE__ */k("span",{className:"text-muted-foreground ml-1 text-xs",children:["(",n,")"]})]}),/* @__PURE__ */k("span",{className:"text-muted-foreground",children:String(s)})]}),"number"===o.type&&/* @__PURE__ */k("input",{type:"range",id:`${e}:${o.key}`,className:"w-full",value:s,min:o.min,max:o.max,step:o.step,onInput:t=>r(e,o.key,parseFloat(t.target.value))}),"boolean"===o.type&&/* @__PURE__ */k("input",{type:"checkbox",id:`${e}:${o.key}`,checked:s,onChange:t=>r(e,o.key,t.target.checked)})]},`${e}:${o.key}`)})})}var ht=v(()=>import("./xPFFaUda.js").then(e=>({default:e.ReactCompareSlider})));function pt({open:e,onClose:t,file:r,filters:o,isVideo:s,trimRange:a,overrides:l,onOverrideChange:c,onReset:d}){const[u,h]=I(),[p,m]=I(),[g,f]=I(!0),[v,y]=I(!1),[b,x]=I(!1),[T,C]=I(),[F,M]=I(0),[E,U]=I(!1),[R,N]=I(null),[P,O]=I(null),[A,D]=I(!1),[L,z]=I(!0),[j,$]=I(!0),H=_(null),Y=_(!1),Q=_([]),J=_(null),Z=_(null),te=_(null),re=_(o);re.current=o,i(()=>()=>{Q.current.forEach(e=>URL.revokeObjectURL(e))},[]);const ie=()=>{document.fullscreenElement?document.exitFullscreen():H.current?.requestFullscreen()};i(()=>{const e=()=>U(!!document.fullscreenElement);return document.addEventListener("fullscreenchange",e),()=>document.removeEventListener("fullscreenchange",e)},[]),i(()=>{D(!!R&&!!P)},[R,P]),i(()=>{R&&(R.muted=L)},[R,L]),i(()=>{if(!e||s)return;let t=!1;return Y.current?y(!0):f(!0),x(!1),(async()=>{const e=await B(r),i=await createImageBitmap(e),n=Math.min(1,1600/Math.max(i.width,i.height)),s=Math.round(i.width*n),a=Math.round(i.height*n),l=new OffscreenCanvas(s,a);if(l.getContext("2d").drawImage(i,0,0,s,a),i.close(),t)return;C(s/a);const c=await l.convertToBlob({type:"image/jpeg",quality:.92});if(t)return;const d=await Oe(c,o,1600,"image/jpeg",.92);if(t)return;const u=URL.createObjectURL(c),p=URL.createObjectURL(d.blob);Q.current.forEach(e=>URL.revokeObjectURL(e)),Q.current=[u,p],h(u),m(p),Y.current=!0})().catch(()=>{t||Y.current||x(!0)}).finally(()=>{t||(f(!1),y(!1))}),()=>{t=!0}},[e,s,r,o]),i(()=>{if(!e||!s||!A)return;const t=R,i=P;if(!t||!i)return;let n=!1,o=null;const l=URL.createObjectURL(r);f(!0),x(!1),M(0);const c=a?.startTime??0,d=c+5,u=e=>new Promise(t=>{let r=!1;const i=()=>{r||(r=!0,t())};"function"==typeof e.requestVideoFrameCallback?e.requestVideoFrameCallback(i):requestAnimationFrame(i),setTimeout(i,600)}),h=e=>{const t=e.data;for(let r=3;r<t.length;r+=4)if(0!==t[r])return!1;return!0};return t.addEventListener("loadeddata",async()=>{if(n)return;M(15);let e=t.videoWidth||640,r=t.videoHeight||360;const s=Math.min(1,720/Math.max(e,r));e=Math.round(e*s),r=Math.round(r*s),i.width=e,i.height=r,C(e/r);const l=i.getContext("2d",{willReadFrequently:!0});if(!l)return f(!1),void x(!0);if(Math.abs(t.currentTime-c)>.05&&(await new Promise(e=>{const r=()=>{t.removeEventListener("seeked",r),e()};t.addEventListener("seeked",r,{once:!0}),t.currentTime=c}),n))return;M(40);const p=new OffscreenCanvas(e,r),m=p.getContext("2d",{willReadFrequently:!0});let g=null;t.muted=!0;try{await t.play()}catch{}if(n)return;for(let i=0;i<6&&!n;i++){if(await u(t),n)return;if(m.drawImage(t,0,0,e,r),!h(m.getImageData(0,0,e,r))){g=await p.convertToBlob({type:"image/jpeg",quality:.85});break}if(t.paused)break}if(n)return;if(!g)return f(!1),void x(!0);M(60),Z.current=g,te.current={w:e,h:r};const v=await Ae(re.current,g,e,r);if(n)return;if(!v.appliedFilters.length)return f(!1),void x(!0);J.current=v.transform,M(100),f(!1),Y.current=!0;const y=a?Math.min(a.endTime,d):Math.min(t.duration||d,d),b=()=>{if(!n){if(l.drawImage(t,0,0,e,r),J.current&&l.putImageData(J.current(l.getImageData(0,0,e,r)),0,0),t.currentTime>=y||t.currentTime<c){const e=()=>{t.removeEventListener("seeked",e),n||(o=t.requestVideoFrameCallback(b))};return t.addEventListener("seeked",e,{once:!0}),void(t.currentTime=c)}o=t.requestVideoFrameCallback(b)}};o=t.requestVideoFrameCallback(b)},{once:!0}),t.src=l,t.load(),()=>{n=!0,null!==o&&t.cancelVideoFrameCallback(o),t.pause(),t.removeAttribute("src"),t.load(),URL.revokeObjectURL(l)}},[e,s,r,a,A]),i(()=>{if(!e||!s||!A)return;if(!Z.current||!te.current)return;let t=!1;return y(!0),(async()=>{const{w:e,h:r}=te.current,i=await Ae(o,Z.current,e,r);t||i.appliedFilters.length>0&&(J.current=i.transform)})().catch(()=>{}).finally(()=>{t||y(!1)}),()=>{t=!0}},[e,s,o,A]);const ne=E?"100vh":"70vh",oe=!!c&&dt(o).length>0;/* @__PURE__ */
29
+ return k(K,{open:e,onOpenChange:e=>!e&&t(),children:/* @__PURE__ */k(G,{className:n(E?"max-w-none rounded-none":"max-w-2xl sm:w-2xl"),children:/* @__PURE__ */k("div",{className:"bg-background",children:[/* @__PURE__ */k(V,{className:"flex-row items-center justify-between space-y-0",children:[/* @__PURE__ */k(X,{children:"Compare original & filtered"}),/* @__PURE__ */k(ee,{size:"sm",variant:"ghost","aria-label":E?"Exit fullscreen":"Fullscreen",tooltip:E?"Exit fullscreen":"Fullscreen",icon:/* @__PURE__ */k(E?lt:ct,{}),onClick:ie})]}),/* @__PURE__ */k("div",{ref:H,className:n("relative p-4 pt-0",E&&"bg-background flex h-screen w-screen items-center justify-center p-0"),children:[E&&/* @__PURE__ */k(ee,{size:"sm",variant:"ghost","aria-label":"Exit fullscreen",tooltip:"Exit fullscreen",className:"absolute top-2 right-2 z-30",icon:/* @__PURE__ */k(lt,{}),onClick:ie}),g&&/* @__PURE__ */k("div",{className:"flex h-64 flex-col items-center justify-center gap-2",children:[/* @__PURE__ */k(S,{}),s&&/* @__PURE__ */k("p",{className:"text-muted-foreground text-sm",children:["Generating preview… ",F,"%"]})]}),b&&!g&&/* @__PURE__ */k("div",{className:"text-muted-foreground flex h-64 items-center justify-center text-sm",children:"Couldn't generate preview."}),v&&!g&&!b&&/* @__PURE__ */k("div",{className:"bg-background/90 text-muted-foreground absolute top-16 left-1/2 z-20 flex -translate-x-1/2 items-center gap-1.5 rounded-full px-3 py-1 text-xs shadow",children:[/* @__PURE__ */k(S,{className:"size-3.5"}),"Updating…"]}),!s&&!g&&!b&&u&&p&&/* @__PURE__ */k(w,{fallback:null,children:/* @__PURE__ */k(ht,{style:{width:"100%",maxHeight:ne,aspectRatio:T},defaultPosition:50,onlyHandleDraggable:!0,itemOne:/* @__PURE__ */k("div",{className:"relative size-full",children:[/* @__PURE__ */k("img",{alt:"Original",className:"size-full object-contain",src:u}),/* @__PURE__ */k(mt,{position:"left",children:"Original"})]}),itemTwo:/* @__PURE__ */k("div",{className:"relative size-full",children:[/* @__PURE__ */k("img",{alt:"Filtered",className:"size-full object-contain",src:p}),/* @__PURE__ */k(mt,{position:"right",children:"Filtered"})]})})}),s&&/* @__PURE__ */k("div",{className:"relative",style:{visibility:g||b?"hidden":"visible"},children:[/* @__PURE__ */k(w,{fallback:null,children:/* @__PURE__ */k(ht,{style:{width:"100%",maxHeight:ne,aspectRatio:T},defaultPosition:50,onlyHandleDraggable:!0,itemOne:/* @__PURE__ */k("div",{className:"relative size-full",children:[/* @__PURE__ */k("video",{ref:N,playsInline:!0,className:"pointer-events-none size-full object-contain"}),/* @__PURE__ */k(mt,{position:"left",children:"Original"})]}),itemTwo:/* @__PURE__ */k("div",{className:"relative size-full",children:[/* @__PURE__ */k("canvas",{ref:O,className:"size-full object-contain"}),/* @__PURE__ */k(mt,{position:"right",children:"Filtered"})]})})}),/* @__PURE__ */k("div",{className:"bg-background/80 absolute bottom-2 left-1/2 z-20 flex -translate-x-1/2 gap-1 rounded-full p-1 shadow",children:[/* @__PURE__ */k(ee,{size:"sm",variant:"ghost","aria-label":L?"Unmute":"Mute",tooltip:L?"Unmute":"Mute",icon:/* @__PURE__ */k(L?st:at,{}),onClick:()=>z(e=>!e)}),/* @__PURE__ */k(ee,{size:"sm",variant:"ghost","aria-label":j?"Pause":"Play",tooltip:j?"Pause":"Play",icon:/* @__PURE__ */k(j?nt:ot,{}),onClick:()=>{R&&(R.paused?(R.play(),$(!0)):(R.pause(),$(!1)))}})]})]}),c&&!E&&/* @__PURE__ */k("div",{className:"mt-4",children:/* @__PURE__ */k(ut,{filters:o,overrides:l,onChange:c})}),oe&&!E&&/* @__PURE__ */k(W,{className:"mt-4",children:[/* @__PURE__ */k(q,{variant:"outlined",color:"foreground",onClick:d,children:"Reset"}),/* @__PURE__ */k(q,{onClick:t,children:"Apply"})]})]})]})})})}function mt({position:e,children:t}){/* @__PURE__ */
30
+ return k("div",{className:"bg-background/80 text-foreground pointer-events-none absolute bottom-2 z-10 rounded-full px-2 py-0.5 text-[10px] font-semibold shadow "+("left"===e?"left-2":"right-2"),children:t})}var gt=(e,t,r)=>Math.min(Math.max(e,t),r),ft=e=>Math.max(0,Math.min(100,e)),vt=["nw","ne","sw","se"],yt=({open:e,onClose:t,imageSrc:r,outputSrc:i,aspectRatio:n,initialCrop:o,onCropComplete:s,title:a})=>{const l=_(null),[c,d]=I(null),[u,h]=I(!1),p=_(null),g=R((e,t)=>{const r=l.current.getBoundingClientRect();return{px:Math.min(Math.max(e-r.left,0),r.width),py:Math.min(Math.max(t-r.top,0),r.height)}},[]),f=R(e=>{const t=p.current,r=l.current;var i,o,s,a,c;if(t&&r)if("move"===t.mode)d((i=t.start,o=e.clientX-t.clientX,s=e.clientY-t.clientY,a=r.width,c=r.height,{...i,x:gt(i.x+o,0,a-i.w),y:gt(i.y+s,0,c-i.h)}));else{const{px:i,py:o}=g(e.clientX,e.clientY);d(function(e,t,r,i,n,o,s){const a=t.includes("e")?1:-1,l=t.includes("s")?1:-1,c=a>0?e.x:e.x+e.w,d=l>0?e.y:e.y+e.h,u=a>0?n-c:c,h=l>0?o-d:d;let p=gt((r-c)*a,20,u),m=gt((i-d)*l,20,h);return s&&(m=p/s,m<20&&(m=20,p=m*s),m>h&&(m=h,p=m*s),p>u&&(p=u,m=p/s)),{x:a>0?c:c-p,y:l>0?d:d-m,w:p,h:m}}(t.start,t.corner,i,o,r.width,r.height,n))}},[n,g]),v=R(()=>{p.current=null,window.removeEventListener("pointermove",f),window.removeEventListener("pointerup",v)},[f]),y=(e,t)=>r=>{c&&(r.preventDefault(),r.stopPropagation(),p.current={mode:e,corner:t,start:c,clientX:r.clientX,clientY:r.clientY},window.addEventListener("pointermove",f),window.addEventListener("pointerup",v))},b=R(()=>{d(null),t()},[t]),w=e=>({position:"absolute",width:"14px",height:"14px",background:"#fff",border:"1px solid rgba(0,0,0,.4)",borderRadius:"2px",touchAction:"none",cursor:`${e}-resize`,...e.includes("n")?{top:"-7px"}:{bottom:"-7px"},...e.includes("w")?{left:"-7px"}:{right:"-7px"}});/* @__PURE__ */
31
+ return k(K,{open:e,onOpenChange:b,children:/* @__PURE__ */k(G,{className:"flex h-[90vh] min-w-xl flex-col overflow-hidden p-0",children:[
32
+ /* @__PURE__ */k("div",{className:"bg-background shrink-0",children:/* @__PURE__ */k(V,{children:[/* @__PURE__ */k(X,{children:a||"Crop Image"}),/* @__PURE__ */k(Y,{className:"sr-only",children:"Drag the box to move it, or drag a corner to resize."})]})}),
33
+ /* @__PURE__ */k("div",{className:"flex max-h-[60vh] min-h-0 flex-1 items-center justify-center overflow-hidden bg-black",children:/* @__PURE__ */k("div",{style:{position:"relative",display:"inline-block",lineHeight:0,touchAction:"none"},children:[/* @__PURE__ */k("img",{ref:l,src:r,alt:"Crop preview",draggable:!1,onLoad:()=>{const e=l.current;e&&d(o?{x:o.x/100*e.width,y:o.y/100*e.height,w:o.width/100*e.width,h:o.height/100*e.height}:function(e,t,r){let i=.9*e,n=.9*t;return r&&(n=i/r,n>.9*t&&(n=.9*t,i=n*r)),{x:(e-i)/2,y:(t-n)/2,w:i,h:n}}(e.width,e.height,n))},style:{display:"block",maxWidth:"100%",maxHeight:"50vh",width:"auto",height:"auto",userSelect:"none"}}),c&&/* @__PURE__ */k("div",{onPointerDown:y("move"),style:{position:"absolute",left:`${c.x}px`,top:`${c.y}px`,width:`${c.w}px`,height:`${c.h}px`,border:"1px dashed rgba(255,255,255,.9)",boxShadow:"0 0 0 9999px rgba(0,0,0,.5)",cursor:"move",touchAction:"none",boxSizing:"border-box"},children:vt.map(e=>/* @__PURE__ */k("div",{onPointerDown:y("resize",e),style:w(e)},e))})]})}),
34
+ /* @__PURE__ */k("div",{className:"border-border bg-background shrink-0 border-t",children:/* @__PURE__ */k(W,{children:[/* @__PURE__ */k(q,{variant:"outlined",onClick:b,disabled:u,children:"Cancel"}),/* @__PURE__ */k(q,{onClick:async()=>{const e=l.current;var t;if(c&&e)try{h(!0);const n=i&&i!==r?await(t=i,new Promise((e,r)=>{const i=new Image;i.onload=()=>e(i),i.onerror=()=>r(/* @__PURE__ */new Error("Failed to load image")),i.src=t})):e,o=c.x/e.width,a=c.y/e.height,l=c.w/e.width,d=c.h/e.height,u={x:Math.round(o*n.naturalWidth),y:Math.round(a*n.naturalHeight),w:Math.round(l*n.naturalWidth),h:Math.round(d*n.naturalHeight)},p={unit:"%",x:ft(100*o),y:ft(100*a),width:ft(100*l),height:ft(100*d)};s(await function(e,t){const r=document.createElement("canvas");r.width=t.w,r.height=t.h;const i=r.getContext("2d");return i?(i.drawImage(e,t.x,t.y,t.w,t.h,0,0,t.w,t.h),new Promise((e,t)=>{r.toBlob(r=>{r?e(r):t(/* @__PURE__ */new Error("Canvas is empty"))},"image/jpeg",.95)})):Promise.reject(/* @__PURE__ */new Error("Failed to get canvas context"))}(n,u),p),b()}catch(n){m(n instanceof Error?n:new Error(String(n)),{component:"ImageCropDialog",tags:["upload","crop"]})}finally{h(!1)}},loading:u,disabled:u||!c,children:"Crop"})]})})]})})},bt=({open:e,onClose:t,videoFile:r,activeFilters:n,onTrimComplete:o,title:s="Select 60 Second Clip"})=>{const a=_(null),l=_(null),c=_(null),d=n?.filter(e=>e.enabled)??[],u=d.length>0,[h,p]=I(0),[g,f]=I(0),[v,y]=I(60),[b,w]=I(0),[x,S]=I(!1),[T,C]=I(!1),[F,M]=I(null),[E,U]=I(null),[N,P]=I(0),[O,A]=I({start:0,end:0});i(()=>{if(r&&e){const e=URL.createObjectURL(r);return M(e),()=>URL.revokeObjectURL(e)}},[r,e]),i(()=>{if(!F||!u)return;const e=a.current,t=l.current;if(!e||!t||!e.requestVideoFrameCallback)return;let r=!1,i=null,n=!1;if(i=e.requestVideoFrameCallback(()=>{(async()=>{if(n||r||!e.videoWidth)return;n=!0;const o=Math.min(1,640/Math.max(e.videoWidth,e.videoHeight)),s=Math.max(1,Math.round(e.videoWidth*o)),a=Math.max(1,Math.round(e.videoHeight*o));t.width=s,t.height=a;const l=t.getContext("2d",{willReadFrequently:!0});if(!l)return;const c=document.createElement("canvas");c.width=s,c.height=a,c.getContext("2d")?.drawImage(e,0,0,s,a);const u=await new Promise(e=>c.toBlob(e,"image/jpeg",.85));if(r||!u)return;const h=await Ae(d,u,s,a);if(r||!h.appliedFilters.length)return;const p=h.transform,m=()=>{r||(l.drawImage(e,0,0,s,a),l.putImageData(p(l.getImageData(0,0,s,a)),0,0),i=e.requestVideoFrameCallback(m))};m()})()}),e.readyState>=2&&e.paused)try{e.currentTime=e.currentTime+.001}catch{}return()=>{r=!0,null!==i&&e.cancelVideoFrameCallback?.(i)}},[F,u,JSON.stringify(n)]);const D=R(e=>{if(!c.current||0===h)return 0;const t=c.current.getBoundingClientRect();return Math.max(0,Math.min(1,(e-t.left)/t.width))*h},[h]),L=R(e=>0===h?0:e/h*100,[h]),z=(e,t)=>{e.preventDefault(),e.stopPropagation(),U(t),P(e.clientX),A({start:g,end:v})},j=(e,t)=>{e.stopPropagation();const r=e.touches[0];U(t),P(r?.clientX??0),A({start:g,end:v})};i(()=>{if(!E||!c.current)return;const e=e=>{const t=c.current.getBoundingClientRect(),r=(e-N)/t.width*h;if("start"===E){let e=Math.max(0,O.start+r);e=Math.min(e,v-1),v-e>60&&(e=v-60),f(e),a.current&&(a.current.currentTime=e)}else if("end"===E){let e=Math.min(h,O.end+r);e=Math.max(e,g+1),e-g>60&&(e=g+60),y(e)}else if("range"===E){const e=O.end-O.start;let t=O.start+r,i=O.end+r;t<0&&(t=0,i=e),i>h&&(i=h,t=h-e),f(t),y(i),a.current&&(a.current.currentTime=t)}},t=t=>e(t.clientX),r=t=>e(t.touches[0].clientX),i=()=>U(null);return document.addEventListener("mousemove",t),document.addEventListener("mouseup",i),document.addEventListener("touchmove",r),document.addEventListener("touchend",i),()=>{document.removeEventListener("mousemove",t),document.removeEventListener("mouseup",i),document.removeEventListener("touchmove",r),document.removeEventListener("touchend",i)}},[E,N,O,h,g,v]);const $=()=>{a.current&&(x?a.current.pause():((b<g||b>=v)&&(a.current.currentTime=g),a.current.play()),S(!x))},B=e=>`${Math.floor(e/60)}:${Math.floor(e%60).toString().padStart(2,"0")}`,H=()=>{f(0),y(60),w(0),S(!1),U(null),a.current&&a.current.pause(),t()},Q=v-g;/* @__PURE__ */
35
+ return k(K,{open:e,onOpenChange:H,children:/* @__PURE__ */k(G,{className:"max-h-[90vh] max-w-3xl overflow-y-auto p-0",children:[
36
+ /* @__PURE__ */k("div",{className:"bg-background sticky top-0 z-10",children:/* @__PURE__ */k(V,{children:[/* @__PURE__ */k(X,{children:s}),/* @__PURE__ */k(Y,{className:"hidden",children:"Review the video preview and choose the start and end times for the clip you want to keep."})]})}),
37
+ /* @__PURE__ */k("div",{className:"space-y-4 p-4",children:[
38
+ /* @__PURE__ */k("div",{className:"relative aspect-video w-full overflow-hidden rounded-lg bg-black",children:[F&&/* @__PURE__ */k("video",{ref:a,src:F,className:"size-full object-contain",onLoadedMetadata:()=>{if(a.current){const e=a.current.duration;p(e),f(0),y(Math.min(e,60))}},onTimeUpdate:()=>{if(a.current){const e=a.current.currentTime;w(e),e>=v&&(a.current.pause(),a.current.currentTime=g,S(!1))}},onEnded:()=>S(!1)}),F&&u&&/* @__PURE__ */k("canvas",{ref:l,className:"pointer-events-none absolute inset-0 size-full object-contain"}),
39
+ /* @__PURE__ */k("button",{type:"button","aria-label":x?"Pause video":"Play video",onClick:$,className:"absolute inset-0 flex items-center justify-center bg-black/20 opacity-0 transition-opacity hover:opacity-100",children:/* @__PURE__ */k("svg",x?{xmlns:"http://www.w3.org/2000/svg",className:"h-16 w-16 text-white drop-shadow-lg",viewBox:"0 0 24 24",children:/* @__PURE__ */k("path",{fill:"currentColor",d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10s10-4.48 10-10S17.52 2 12 2m-1 14H9V8h2zm4 0h-2V8h2z"})}:{xmlns:"http://www.w3.org/2000/svg",className:"h-16 w-16 text-white drop-shadow-lg",viewBox:"0 0 24 24",children:/* @__PURE__ */k("path",{fill:"currentColor",d:"M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10s10-4.48 10-10S17.52 2 12 2m-2 14.5v-9l6 4.5z"})})}),
40
+ /* @__PURE__ */k("div",{className:"absolute bottom-2 left-2 rounded bg-black/70 px-2 py-1 text-sm text-white",children:B(b)})]}),
41
+ /* @__PURE__ */k("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[/* @__PURE__ */k("div",{className:"flex items-center gap-2",children:[/* @__PURE__ */k("span",{className:"bg-primary/20 text-primary rounded-full px-3 py-1 text-sm font-medium",children:["Start: ",B(g)]}),/* @__PURE__ */k("span",{className:"bg-primary/20 text-primary rounded-full px-3 py-1 text-sm font-medium",children:["End: ",B(v)]})]}),/* @__PURE__ */k("span",{className:"rounded-full px-3 py-1 text-sm font-medium "+(Q<=60?"bg-green-500/20 text-green-600":"bg-red-500/20 text-red-600"),children:[B(Q)," / ",B(60)]})]}),
42
+ /* @__PURE__ */k("div",{className:"space-y-1",children:[
43
+ /* @__PURE__ */k("div",{className:"relative h-4 select-none",children:(()=>{if(0===h)return[];let e;e=h<=30?10:h<=60?15:h<=120?30:h<=300?60:120;const t=[];for(let i=0;i<=h;i+=e)t.push(i);const r=t[t.length-1];return h-r>.3*e&&t.push(Math.floor(h)),t})().map(e=>/* @__PURE__ */k("span",{className:"text-muted-foreground absolute -translate-x-1/2 text-xs",style:{left:`${L(e)}%`},children:B(e)},e))}),
44
+ /* @__PURE__ */k("div",{ref:c,className:"relative h-16 cursor-pointer rounded-lg bg-gray-200 select-none dark:bg-gray-800",onClick:e=>{if(E)return;const t=D(e.clientX);t>=g&&t<=v&&a.current&&(a.current.currentTime=t,w(t))},children:[
45
+ /* @__PURE__ */k("div",{className:"absolute inset-y-0 left-0 bg-black/50",style:{width:`${L(g)}%`}}),
46
+ /* @__PURE__ */k("div",{className:"absolute inset-y-0 right-0 bg-black/50",style:{width:100-L(v)+"%"}}),
47
+ /* @__PURE__ */k("div",{className:"bg-primary/30 border-primary absolute inset-y-0 cursor-grab border-y-2 active:cursor-grabbing",style:{left:`${L(g)}%`,width:`${L(v-g)}%`},onMouseDown:e=>z(e,"range"),onTouchStart:e=>j(e,"range")}),
48
+ /* @__PURE__ */k("div",{className:"border-primary bg-primary absolute inset-y-0 z-10 w-3 cursor-ew-resize rounded-l-md border-2 transition-transform hover:scale-x-125",style:{left:`calc(${L(g)}% - 6px)`},onMouseDown:e=>z(e,"start"),onTouchStart:e=>j(e,"start"),children:/* @__PURE__ */k("div",{className:"absolute inset-y-0 left-1/2 w-0.5 -translate-x-1/2 bg-white/50"})}),
49
+ /* @__PURE__ */k("div",{className:"border-primary bg-primary absolute inset-y-0 z-10 w-3 cursor-ew-resize rounded-r-md border-2 transition-transform hover:scale-x-125",style:{left:`calc(${L(v)}% - 6px)`},onMouseDown:e=>z(e,"end"),onTouchStart:e=>j(e,"end"),children:/* @__PURE__ */k("div",{className:"absolute inset-y-0 left-1/2 w-0.5 -translate-x-1/2 bg-white/50"})}),
50
+ /* @__PURE__ */k("div",{className:"absolute inset-y-0 z-20 w-0.5 bg-white shadow-lg",style:{left:`${L(b)}%`},children:/* @__PURE__ */k("div",{className:"absolute -top-1 left-1/2 h-3 w-3 -translate-x-1/2 rotate-45 bg-white"})}),
51
+ /* @__PURE__ */k("div",{className:"pointer-events-none absolute inset-x-0 bottom-0 flex h-2 justify-between px-0",children:Array.from({length:Math.min(50,Math.ceil(h))}).map((e,t)=>/* @__PURE__ */k("div",{className:"w-px bg-gray-400/30",style:{height:t%5==0?"100%":"50%"}},t))})]}),
52
+ /* @__PURE__ */k("p",{className:"text-muted-foreground text-center text-xs",children:"Drag the handles to adjust selection • Drag the center to move the range • Click to seek"})]}),
53
+ /* @__PURE__ */k("div",{className:"flex items-center justify-center gap-2",children:[
54
+ /* @__PURE__ */k(q,{variant:"outlined",size:"sm",onClick:()=>{a.current&&(a.current.currentTime=g,w(g))},children:/* @__PURE__ */k("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5",viewBox:"0 0 24 24",children:/* @__PURE__ */k("path",{fill:"currentColor",d:"M6 6h2v12H6zm3.5 6l8.5 6V6z"})})}),
55
+ /* @__PURE__ */k(q,{variant:"outlined",onClick:$,children:/* @__PURE__ */k("svg",x?{xmlns:"http://www.w3.org/2000/svg",className:"h-6 w-6",viewBox:"0 0 24 24",children:/* @__PURE__ */k("path",{fill:"currentColor",d:"M6 19h4V5H6zm8-14v14h4V5z"})}:{xmlns:"http://www.w3.org/2000/svg",className:"h-6 w-6",viewBox:"0 0 24 24",children:/* @__PURE__ */k("path",{fill:"currentColor",d:"M8 5v14l11-7z"})})}),
56
+ /* @__PURE__ */k(q,{variant:"outlined",size:"sm",onClick:()=>{a.current&&(a.current.currentTime=v,w(v))},children:/* @__PURE__ */k("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5",viewBox:"0 0 24 24",children:/* @__PURE__ */k("path",{fill:"currentColor",d:"m5 18l8.5-6L5 6zm11 0V6h2v12z"})})})]})]}),
57
+ /* @__PURE__ */k("div",{className:"bg-background border-border sticky bottom-0 border-t",children:/* @__PURE__ */k(W,{children:[/* @__PURE__ */k(q,{variant:"outlined",onClick:H,disabled:T,children:"Cancel"}),/* @__PURE__ */k(q,{onClick:async()=>{C(!0);try{o({startTime:g,endTime:v,duration:v-g}),H()}catch(e){m(e instanceof Error?e:new Error(String(e)),{component:"VideoTrimDialog",tags:["upload","trim"]})}finally{C(!1)}},loading:T,disabled:T||Q>60,children:"Confirm Selection"})]})})]})})};function wt(e,t){const r=Math.min(1,360/e);return{w:Math.round(e*r),h:Math.round(t*r)}}var xt={image:"25 MB",video:"250 MB"},St=C(function({uid:e,file:t,onRemove:r,disabled:o,adaRequired:s,showCaption:l=!0,onRetry:c}){const d=L(t),u=!d&&z(t),h=Ye(),p=Xe(t=>t.captions[e]),m=Xe(t=>t.oversizedUids[e]),g=Xe(t=>t.uploadStates[e]),f=Xe(t=>t.trimRanges[e]),v=Xe(t=>t.originalFiles[e])??t,y=Xe(e=>e.videoMuted),b=Xe(e=>e.setVideoMuted),w=Xe(e=>e.activeFilters),x=Xe(e=>e.showFilterChoice),T=Xe(e=>e.skipUploadFilters),C=Xe(t=>t.perFileFilterSkipped[e]),F=Xe(t=>t.filteredThumbs[e]),M=Xe(t=>t.filterOverrides[e]),E=P(()=>{return e=w,(t=M)&&0!==Object.keys(t).length?e.map(e=>{const r=t[e.id],i=e.config.adjustableKeys;if(!r||!i?.length)return e;const n=e.config.templateId?xe(e.config.templateId):void 0;if(!n)return e;const o={...e.config.variables};let s=!1;for(const t of i){if(!(t in r))continue;const e=Se(n.variableSchema.find(e=>e.key===t),r[t]);void 0!==e&&(o[t]=e,s=!0)}return s?{...e,config:{...e.config,variables:o}}:e}):e;var e,t},[w,M]),U=!!g,N="success"===g?.status,O="error"===g?.status,A=w.length>0&&(!x||!T&&!C),q=w.length>0&&(!x||!T),[$,B]=I(!1),[H,V]=I(),[W,G]=I(!1),[X,Y]=I(!1),{ref:K,inView:J}=function({rootMargin:e,triggerOnce:t}={}){const r=_(null),[n,o]=I(!1);return i(()=>{const i=r.current;if(!i)return;const n=new IntersectionObserver(e=>{for(const r of e)r.isIntersecting?(o(!0),t&&n.disconnect()):t||o(!1)},{rootMargin:e});return n.observe(i),()=>n.disconnect()},[e,t]),{ref:r,inView:n}}({rootMargin:"200px",triggerOnce:!0}),[re,ie]=I();i(()=>{if(!u||!J)return;let e,r=!1;return j(t).then(t=>{r?URL.revokeObjectURL(t):(e=t,ie(t))}),()=>{r=!0,e&&URL.revokeObjectURL(e)}},[t,u,J]);const[ne,oe]=I();i(()=>{if(!u||!$)return;let e,t=!1;return j(v).then(r=>{t?URL.revokeObjectURL(r):(e=r,oe(r))}),()=>{t=!0,e&&URL.revokeObjectURL(e),oe(void 0)}},[v,u,$]);const[se,ae]=I();i(()=>{if(!u||!$||!A)return void ae(void 0);let e=!1;return Le(v,E).then(t=>{e||ae(t.processed)}).catch(()=>{}),()=>{e=!0}},[u,$,A,v,E]);const le=_(null),ce=_(null),de=_(null),ue=_(0),he=_(null),[pe,fe]=I(!1),[ve,ye]=I(!1),[be,we]=I(null),[Te,Ce]=I(null),Fe=R(()=>{const e=le.current;if(!e||de.current)return;const r=URL.createObjectURL(t);de.current=r,e.src=r,e.load()},[t]),Me=R(()=>{const e=le.current;e&&(e.removeAttribute("src"),e.load()),de.current&&(URL.revokeObjectURL(de.current),de.current=null)},[]),Ee=R(()=>{const e=le.current;if(!e||!e.videoWidth)return;const t=Math.min(1,640/e.videoWidth),r=document.createElement("canvas");r.width=e.videoWidth*t,r.height=e.videoHeight*t;const i=r.getContext("2d");i&&(i.drawImage(e,0,0,r.width,r.height),we(r.toDataURL("image/jpeg",.85)))},[]),ke=R(()=>{const t=le.current,r=ce.current;if(!t||!r||!t.videoWidth)return!1;const{w:i,h:n}=wt(t.videoWidth,t.videoHeight),o=$e(je(e,E,i,n));if(!o)return!1;r.width=i,r.height=n;const s=r.getContext("2d");return!!s&&(s.drawImage(t,0,0,i,n),s.putImageData(o.transform(s.getImageData(0,0,i,n)),0,0),!0)},[e,E]),_e=R(()=>{he.current&&(clearTimeout(he.current),he.current=null)},[]),Ue=R(()=>{const t=le.current;if(t&&(ue.current=t.currentTime),Ee(),A){const e=ke();ye(e),e&&ce.current&&Ce(ce.current.toDataURL("image/jpeg",.85))}fe(!1),function(e){Qe===e&&(Qe=null)}(e),_e(),he.current=setTimeout(()=>{Me(),he.current=null},200)},[e,Ee,ke,A,Me,_e]),Re=R(()=>{const t=le.current;if(!t)return;if(pe)return void t.pause();!function(e){Qe&&Qe!==e&&Ke.get(Qe)?.(),Qe=e}(e),_e(),Fe();const r=ue.current||f?.startTime||0,i=()=>{t.currentTime=r,t.play().catch(()=>{})};t.readyState>=1?i():t.addEventListener("loadedmetadata",i,{once:!0})},[pe,Fe,f,e,_e]);return i(()=>{if(!d)return;const t=function(e){return Ke.set(e,()=>le.current?.pause()),()=>{Ke.delete(e),Qe===e&&(Qe=null)}}(e);return()=>{t(),_e(),Me()}},[d,e,Me,_e]),i(()=>{W&&le.current?.pause()},[W]),i(()=>{U&&le.current?.pause()},[U]),i(()=>{ue.current=0},[f]),i(()=>{ye(!1),Ce(null)},[A,E,e]),i(()=>{le.current&&(le.current.muted=y)},[y]),i(()=>{if(!d||!J)return;let e=!1,r=null,i=null;const n=()=>{i&&(i.pause(),i.removeAttribute("src"),i.load(),i=null),r&&(URL.revokeObjectURL(r),r=null)};return me(async()=>{if(!e)try{if(r=URL.createObjectURL(t),i=document.createElement("video"),i.preload="metadata",i.muted=!0,i.playsInline=!0,await new Promise((e,t)=>{if(!i)return t(/* @__PURE__ */new Error("no probe"));const n=()=>{i?.removeEventListener("loadedmetadata",n),i?.removeEventListener("error",o),e()},o=()=>{i?.removeEventListener("loadedmetadata",n),i?.removeEventListener("error",o),t(/* @__PURE__ */new Error("video load error"))};i.addEventListener("loadedmetadata",n),i.addEventListener("error",o),i.src=r,i.load()}),e||!i)return;const n=Math.min(.5,.05*(i.duration||0)||.1);if(await new Promise((e,t)=>{if(!i)return t(/* @__PURE__ */new Error("no probe"));const r=()=>{i?.removeEventListener("seeked",r),i?.removeEventListener("error",o),e()},o=()=>{i?.removeEventListener("seeked",r),i?.removeEventListener("error",o),t(/* @__PURE__ */new Error("video seek error"))};i.addEventListener("seeked",r),i.addEventListener("error",o),i.currentTime=n}),e||!i)return;const o=document.createElement("canvas"),s=i.videoWidth||640,a=i.videoHeight||360,l=Math.min(1,640/s);o.width=s*l,o.height=a*l;const c=o.getContext("2d");if(!c)return;c.drawImage(i,0,0,o.width,o.height),we(o.toDataURL("image/jpeg",.85))}catch{}finally{n()}}).catch(()=>{}),()=>{e=!0,n()}},[d,J,t]),i(()=>{if(!u||!J||!A||F||X)return;let r=!1;return ge(()=>Le(t,E)).then(t=>{!r&&t.appliedFilters.length&&h.getState().setFilteredThumb(e,t.processed)}).catch(()=>{}),()=>{r=!0}},[u,J,A,F,X,t,E,h,e]),i(()=>{if(!d||!be||!A||F||X)return;let t=!1;return ge(async()=>{const t=await fetch(be);if(!1===t.ok)throw new Error(`Poster fetch failed: ${t.status}`);const r=await t.blob(),i=await createImageBitmap(r),{w:n,h:o}=wt(i.width,i.height),s=je(e,E,n,o);let a=$e(s);if(a||(a=await Ae(E,r,n,o),a.appliedFilters.length&&Be(s,a)),!a.appliedFilters.length)return i.close(),null;const l=new OffscreenCanvas(n,o),c=l.getContext("2d");return c.drawImage(i,0,0,n,o),i.close(),c.putImageData(a.transform(c.getImageData(0,0,n,o)),0,0),l.convertToBlob({type:"image/jpeg",quality:.85})}).then(r=>{if(t||!r)return;const i=new FileReader;i.onload=()=>{t||h.getState().setFilteredThumb(e,i.result)},i.readAsDataURL(r)}).catch(()=>{}),()=>{t=!0}},[d,be,A,F,X,E,h,e]),i(()=>{if(!(d&&pe&&A&&be))return;const t=le.current,r=ce.current;if(!t||!r)return;let i=!1,n=null;return(async()=>{if(!t.videoWidth)return;const{w:o,h:s}=wt(t.videoWidth,t.videoHeight);r.width=o,r.height=s;const a=r.getContext("2d");if(!a)return;const l=je(e,E,o,s);let c=$e(l);if(!c){const e=await fetch(be);if(!1===e.ok)throw new Error(`Poster fetch failed: ${e.status}`);const t=await e.blob();if(i)return;if(c=await Ae(E,t,o,s),i||!c.appliedFilters.length)return;Be(l,c)}const d=c.transform,u=f?.startTime??0,h=Number.isFinite(t.duration)?t.duration:1/0,p=Math.min(f?.endTime??1/0,h);let m=!1;const g=()=>{if(!i){if(a.drawImage(t,0,0,o,s),a.putImageData(d(a.getImageData(0,0,o,s)),0,0),m||(m=!0,ye(!0)),t.currentTime>=p||t.currentTime<u){const e=()=>{t.removeEventListener("seeked",e),i||(n=t.requestVideoFrameCallback(g))};return t.addEventListener("seeked",e,{once:!0}),void(t.currentTime=u)}n=t.requestVideoFrameCallback(g)}};n=t.requestVideoFrameCallback(g)})().catch(()=>{}),()=>{i=!0,null!==n&&t.cancelVideoFrameCallback(n)}},[d,pe,A,be,E,f,e]),i(()=>{if(!d||pe||!A||!be||X)return;let e=!1;return(async()=>{const t=await fetch(be);if(!1===t.ok)throw new Error(`Poster fetch failed: ${t.status}`);const r=await t.blob(),i=new File([r],"poster.jpg",{type:"image/jpeg"}),n=await Le(i,E);e||Ce(n.processed)})().catch(()=>{}),()=>{e=!0}},[d,pe,A,be,X,E]),/* @__PURE__ */k("div",{className:"group relative",children:[
58
+ /* @__PURE__ */k("div",{ref:K,className:n("bg-muted relative h-48 overflow-hidden rounded sm:h-72",m&&"border-destructive border-2"),children:[u&&re&&/* @__PURE__ */k("img",{src:A&&F?F:re,alt:t.name,loading:"lazy",decoding:"async",className:"size-full object-contain"}),u&&q&&/* @__PURE__ */k(Tt,{applied:A&&!!F}),d&&/* @__PURE__ */k("div",{className:"relative size-full",children:[be&&/* @__PURE__ */k("img",{src:A?Te??F??be:be,alt:"",className:n("absolute inset-0 size-full object-contain",pe?"opacity-0":"opacity-100")}),(!pe||A)&&q&&/* @__PURE__ */k(Tt,{applied:A&&!!F}),
59
+ /* @__PURE__ */k("video",{ref:le,muted:y,playsInline:!0,loop:!f,preload:"none",onLoadedMetadata:e=>{f&&(e.currentTarget.currentTime=f.startTime)},onTimeUpdate:e=>{if(!f)return;const t=e.currentTarget;t.currentTime>=f.endTime&&(t.currentTime=f.startTime)},onPlaying:()=>fe(!0),onPause:Ue,className:n("size-full object-contain",pe&&!A?"opacity-100":"opacity-0")}),A&&/* @__PURE__ */k("canvas",{ref:ce,className:n("pointer-events-none absolute inset-0 size-full object-contain",pe&&ve?"opacity-100":"opacity-0")}),!U&&/* @__PURE__ */k("button",{type:"button","aria-label":pe?"Pause":"Play",onClick:Re,className:"bg-background/60 absolute top-1/2 left-1/2 z-10 -translate-x-1/2 -translate-y-1/2 rounded-full p-3 backdrop-blur-sm",children:/* @__PURE__ */k(pe?nt:ot,{className:"text-foreground size-8"})}),!U&&/* @__PURE__ */k("button",{type:"button","aria-label":y?"Unmute videos":"Mute videos",onClick:()=>b(!y),className:"bg-background/60 absolute bottom-2 left-2 z-10 rounded-full p-2 backdrop-blur-sm",children:/* @__PURE__ */k(y?st:at,{className:"text-foreground size-5"})}),f&&!U&&/* @__PURE__ */k("div",{className:"absolute bottom-3 left-1/2 -translate-x-1/2 rounded bg-black/70 px-2 py-1 text-xs text-white",children:["Trimmed: ",(Ie=f.endTime-f.startTime,`${Math.floor(Ie/60)}:${Math.floor(Ie%60).toString().padStart(2,"0")}`)]})]}),!u&&!d&&/* @__PURE__ */k("div",{className:"flex h-full w-full items-center justify-center",children:/* @__PURE__ */k(it,{className:"text-muted-foreground size-12"})}),m&&/* @__PURE__ */k("div",{className:"bg-destructive/75 absolute inset-x-0 top-0 flex items-center justify-center gap-1 p-2 text-center text-xs font-semibold text-white backdrop-blur-sm",children:[
60
+ /* @__PURE__ */k(Q,{className:"size-4"}),"Exceeds ",xt[m]," limit"]}),U&&!N&&!O&&/* @__PURE__ */k("div",{className:"bg-background/80 absolute inset-0 flex flex-col items-center justify-center gap-3 backdrop-blur-sm",children:[g.bytesTotal>0&&/* @__PURE__ */k("div",{className:"bg-primary/20 absolute bottom-0 left-0 h-full transition-[width] duration-300",style:{width:`${Math.round(g.bytesUploaded/g.bytesTotal*100)}%`}}),
61
+ /* @__PURE__ */k("div",{className:"bg-primary/10 flex size-12 items-center justify-center rounded-full",children:/* @__PURE__ */k(S,{className:"size-6"})}),
62
+ /* @__PURE__ */k("div",{className:"relative z-10 rounded-full bg-white/80 px-3 py-1 backdrop-blur-sm dark:bg-black/40",children:/* @__PURE__ */k("span",{className:"text-muted-foreground text-sm font-medium",children:"creating"!==g.status&&"queued"!==g.status&&g.bytesTotal>0?`Uploading ${Math.round(g.bytesUploaded/g.bytesTotal*100)}%`:"Uploading"})})]}),N&&/* @__PURE__ */k("div",{className:"bg-background/80 absolute inset-0 flex flex-col items-center justify-center gap-2 p-4 backdrop-blur-sm",children:[/* @__PURE__ */k("div",{className:"bg-success/20 flex size-14 items-center justify-center rounded-full",children:/* @__PURE__ */k(Z,{className:"text-success size-8"})}),/* @__PURE__ */k("span",{className:"text-success text-sm font-medium",children:"Uploaded!"})]}),O&&/* @__PURE__ */k("div",{className:"bg-background/80 absolute inset-0 flex flex-col items-center justify-center gap-3 p-4 backdrop-blur-sm",children:[
63
+ /* @__PURE__ */k("div",{className:"bg-destructive/20 flex size-14 items-center justify-center rounded-full",children:/* @__PURE__ */k(Q,{className:"text-destructive size-8"})}),
64
+ /* @__PURE__ */k("p",{className:"text-destructive text-center text-xs font-medium",children:g?.error??"Upload failed"}),c&&/* @__PURE__ */k("button",{type:"button",onClick:()=>c(e),className:"border-destructive text-destructive hover:bg-destructive/10 flex items-center gap-1.5 rounded-full border px-3 py-1.5 text-xs font-semibold",children:[/* @__PURE__ */k(D,{className:"size-3.5"}),"Retry"]})]})]}),!o&&/* @__PURE__ */k(ee,{size:"sm",color:"error",variant:"default",className:"absolute top-3 right-3","aria-label":"Remove file",icon:/* @__PURE__ */k(a,{}),onClick:()=>r(e)}),!o&&(u||d)&&/* @__PURE__ */k("div",{className:"absolute top-3 left-3 flex gap-2",children:[
65
+ /* @__PURE__ */k(ee,{size:"sm",variant:"default","aria-label":u?"Crop image":"Trim video",icon:/* @__PURE__ */k(u?rt:tt,{}),onClick:()=>u?B(!0):G(!0)}),x&&w.length>0&&!T&&/* @__PURE__ */k(ee,{size:"sm",variant:"default","aria-label":C?"Apply filter":"Skip filter",tooltip:C?"Apply filter":"Skip filter",icon:/* @__PURE__ */k(C?Je:Ze,{}),onClick:()=>h.getState().setFileFilterSkipped(e,!C)}),x&&w.length>0&&!T&&!C&&/* @__PURE__ */k(ee,{size:"sm",variant:"default","aria-label":"Compare original and filtered",tooltip:"Compare original and filtered",icon:/* @__PURE__ */k(et,{}),onClick:()=>{Qe&&(Ke.get(Qe)?.(),Qe=null),Y(!0)}})]}),u&&ne&&/* @__PURE__ */k(yt,{open:$,onClose:()=>B(!1),imageSrc:A&&se?se:ne,outputSrc:ne,title:"Crop Image",initialCrop:H,onCropComplete:(r,i)=>{const n=new File([r],t.name,{type:r.type});V(i),h.getState().replaceFile(e,n,i)}}),d&&W&&/* @__PURE__ */k(bt,{open:W,onClose:()=>G(!1),videoFile:t,activeFilters:A?E:void 0,title:"Select Clip",onTrimComplete:({startTime:t,endTime:r})=>h.getState().setTrimRange(e,{startTime:t,endTime:r})}),X&&/* @__PURE__ */k(pt,{open:X,onClose:()=>Y(!1),file:t,filters:E,isVideo:d,trimRange:f,overrides:M,onOverrideChange:(t,r,i)=>h.getState().setFilterOverride(e,t,r,i),onReset:()=>h.getState().resetFilterOverrides(e)}),l&&/* @__PURE__ */k("div",{className:"mt-2",children:/* @__PURE__ */k(te,{placeholder:s?"Caption (required)":"Caption",value:p??"",onInput:t=>h.getState().setCaption(e,t.target.value),disabled:o,error:s&&!p?.trim()?" ":void 0,className:"text-xs"})})]});var Ie});function Tt({applied:e}){/* @__PURE__ */
66
+ return k("div",{className:n("absolute right-2 bottom-2 z-10 flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-semibold shadow",e?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"),children:e?"Filtered":"Original"})}function Ct({onUpload:e,onCancel:t,onRetryAll:r,uploadDisabled:i,selectedCount:o}){const s=Xe(e=>e.hasStarted),a=Xe(e=>e.uploadStates),l=Xe(e=>e.uploadSpeedBps),c=P(()=>{const e=Object.values(a);if(0===e.length)return null;const t=e.filter(e=>"success"===e.status).length,r=e.filter(e=>"error"===e.status).length,i=e.reduce((e,t)=>e+(t.bytesTotal||0),0),n=e.reduce((e,t)=>e+("success"===t.status?t.bytesTotal||0:t.bytesUploaded||0),0),o=i>0?Math.round(n/i*100):0,s=e.length;return{succeeded:t,failed:r,percent:o,total:s,allDone:t+r>=s}},[a]),d=!!(s&&c&&c.allDone&&c.failed>0);return 0===o?null:/* @__PURE__ */k("div",{className:"bg-background/85 fixed right-0 bottom-0 left-0 z-2002 overflow-hidden backdrop-blur-sm",children:/* @__PURE__ */k("div",{className:"relative flex items-stretch gap-3",children:[
67
+ /* @__PURE__ */k("div",{className:"relative min-w-0 flex-1 overflow-hidden",children:[s&&c&&/* @__PURE__ */k("div",{className:"bg-primary/40 absolute inset-y-0 t-0 text-right transition-[width] duration-300",style:{width:`${c.percent}%`}}),/* @__PURE__ */k("div",{className:"relative flex h-full flex-col justify-center gap-0.5 py-3 pl-3",children:/* @__PURE__ */k("span",s&&c?{className:"text-muted-foreground text-sm font-medium",children:["Uploading",c.failed>0?` · ${c.failed} failed`:""," (",c.percent,"%)"," ",l?/* @__PURE__ */k("span",{className:"text-muted-foreground/70 text-xs",children:["• ",(u=l,u<=0?"":u<1048576?`${(u/1024).toFixed(0)} KB/s`:`${(u/1048576).toFixed(1)} MB/s`)]}):null]}:{className:"text-muted-foreground text-sm font-medium",children:[o," media selected"]})})]}),s&&d&&/* @__PURE__ */k("button",{type:"button",onClick:r,className:"border-primary text-primary hover:bg-primary/10 flex shrink-0 items-center gap-1.5 border px-4 py-2.5 text-sm font-semibold",children:[/* @__PURE__ */k(D,{className:"size-4"}),"Retry All"]}),s&&!d&&/* @__PURE__ */k("button",{type:"button",onClick:t,className:"shrink-0 px-2 py-2.5 text-sm font-semibold text-destructive hover:bg-red-50 dark:hover:bg-red-950/20",children:"Cancel"}),!s&&/* @__PURE__ */k("button",{type:"button",onClick:e,disabled:i,className:n("bg-primary text-primary-foreground shrink-0 bg-linear-to-r px-6 py-2.5 text-sm font-semibold transition-colors","disabled:cursor-not-allowed disabled:opacity-50"),children:/* @__PURE__ */k("span",{className:"flex items-center gap-2",children:[/* @__PURE__ */k(H,{className:"size-4"}),"Upload"]})})]})});var u}function Ft(e,t){return e.filter(e=>function(e,t){const r=e.name.lastIndexOf("."),i=r>0&&r<e.name.length-1?e.name.slice(r+1).toLowerCase():void 0;return i?t.includes(i):e.type.startsWith("image/")?t.some(e=>se.includes(e)):!!e.type.startsWith("video/")&&t.some(e=>ae.includes(e))}(e,t))}function Mt({enabledFileTypes:e,disabled:t,onFileSelect:r,children:i}){const[n,o]=I(!1),s=_(null),a=function(e){const t=e.filter(e=>se.includes(e)),r=e.filter(e=>ae.includes(e)),i=[];return t.length>0&&i.push("image/*",...t.map(e=>`.${e}`)),r.length>0&&i.push("video/*",...r.map(e=>`.${e}`)),i.join(",")}(e),l=R(t=>{if(!t)return;const i=Ft(Array.from(t),e);i.length>0&&r(i)},[e,r]),c=R(e=>{e.preventDefault(),o(!1),t||l(e.dataTransfer?.files??null)},[t,l]);/* @__PURE__ */
68
+ return k("div",{role:"button",tabIndex:0,onClick:()=>!t&&s.current?.click(),onKeyDown:e=>{t||"Enter"!==e.key&&" "!==e.key||s.current?.click()},onDragOver:e=>{e.preventDefault(),t||o(!0)},onDragLeave:()=>o(!1),onDrop:c,children:[/* @__PURE__ */k("input",{ref:s,type:"file",accept:a,multiple:!0,disabled:t,className:"hidden",onChange:e=>{l(e.target.files),e.target.value=""}}),i({isDragActive:n})]})}function Et({enabledFileTypes:e,disabled:t,onFileSelect:r,selectedCount:i,maxCount:o,enableVideo:s}){/* @__PURE__ */
69
+ return k("div",{className:"flex w-full justify-center",children:/* @__PURE__ */k(Mt,{enabledFileTypes:e,disabled:t,onFileSelect:r,children:()=>/* @__PURE__ */k("div",{className:n("w-full rounded border-2 px-3 sm:px-12 md:px-36 lg:px-64 border-dashed py-36 text-center transition-colors lg:py-52",t?"border-border hover:cursor-not-allowed":"border-primary hover:bg-primary/10 hover:cursor-pointer"),children:[
70
+ /* @__PURE__ */k("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:"text-primary mx-auto size-16",children:/* @__PURE__ */k("path",{fill:"currentColor",d:"M4.25 14q.15.575.363 1.1t.487 1q.225.375.175.8t-.325.7t-.688.263t-.637-.363q-.525-.8-.888-1.65t-.562-1.8q-.1-.4.163-.725T3.025 13t.763.275t.462.725m.85-6.1q-.275.475-.487 1T4.25 10q-.125.45-.462.725T3.025 11t-.687-.3t-.163-.7q.2-.975.575-1.875t.9-1.65q.225-.325.625-.337t.675.262t.325.7t-.175.8m2.775 10.95q.5.3 1.025.525t1.075.375q.425.125.7.45t.275.75t-.3.675t-.7.175q-.925-.2-1.787-.55T6.5 20.375q-.35-.225-.387-.638t.237-.712q.3-.3.725-.35t.8.175m2.15-14.6q-.55.15-1.062.363t-1.013.512q-.4.225-.837.188t-.738-.338t-.275-.7t.375-.625q.825-.525 1.713-.887t1.837-.563q.375-.075.675.175t.3.675t-.275.75t-.7.45m6.05 14.625q.375-.225.813-.187t.737.337t.275.713t-.375.612q-.8.525-1.7.888t-1.85.562q-.4.075-.712-.175t-.313-.675t.288-.75t.712-.45q.575-.15 1.1-.362t1.025-.513m-2.1-14.625q-.425-.125-.7-.45T13 3.05t.3-.675t.675-.175q.95.2 1.85.563t1.7.887q.35.225.375.625t-.25.7q-.3.3-.725.35T16.1 5.15q-.525-.3-1.05-.525t-1.075-.375m5.775 9.725q.125-.425.463-.7t.762-.275t.687.325t.163.725q-.2.95-.587 1.825T20.35 17.5q-.225.325-.625.35t-.675-.25t-.325-.712t.175-.813q.275-.5.488-1.012t.362-1.088M18.9 7.9q-.225-.375-.175-.8t.325-.7t.675-.25t.625.35q.55.8.925 1.675T21.85 10q.075.4-.188.7t-.687.3t-.763-.275T19.75 10q-.15-.575-.362-1.1t-.488-1m-7.637 8.813q-.288-.288-.288-.713v-5.125l-1.875 1.9q-.3.3-.712.3t-.713-.3t-.312-.712t.287-.713l3.625-3.65q.275-.275.7-.275t.7.275l3.575 3.575q.3.3.313.725t-.288.725t-.725.3t-.725-.3l-1.85-1.85V16q0 .425-.287.713t-.713.287t-.712-.288"})}),
71
+ /* @__PURE__ */k("span",{className:n(t?"text-muted-foreground":"","mt-2 block font-medium"),children:`Select Images ${s?"or Videos (60s)":""} to upload (${i}/${o})`}),
72
+ /* @__PURE__ */k("div",{className:"text-muted-foreground mt-3 w-full text-center text-xs italic",children:"* Only your new, original photos will be eligible for upload."})]})})})}function kt({enabledFileTypes:e,disabled:t,onFileSelect:r}){/* @__PURE__ */
73
+ return k(Mt,{enabledFileTypes:e,disabled:t,onFileSelect:r,children:({isDragActive:e})=>/* @__PURE__ */k("div",{className:n("mt-2 mb-4 rounded border-2 border-dashed px-4 py-24 text-center text-sm transition-colors",t?"border-border text-muted-foreground cursor-not-allowed":e?"border-primary bg-primary/15 text-primary cursor-copy":"border-border text-primary hover:bg-primary/5 hover:border-primary cursor-pointer"),children:/* @__PURE__ */k("span",{className:"text-lg font-medium",children:e?"Drop to add files...":"+ Add more files"})})})}function _t({enabledFileTypes:e,disabled:t,onFileSelect:r}){/* @__PURE__ */
74
+ return k(Mt,{enabledFileTypes:e,disabled:t,onFileSelect:r,children:()=>/* @__PURE__ */k("div",{className:n("inline-flex items-center gap-1.5 rounded-lg border px-3 py-1.5 text-sm font-medium transition-colors",t?"border-border text-muted-foreground cursor-not-allowed":"border-primary text-primary hover:bg-primary/5 cursor-pointer"),children:[/* @__PURE__ */k("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:"size-4",children:/* @__PURE__ */k("path",{fill:"currentColor",d:"M11 13v3q0 .425.288.713T12 17t.713-.288T13 16v-3h3q.425 0 .713-.288T17 12t-.288-.712T16 11h-3V8q0-.425-.288-.712T12 7t-.712.288T11 8v3H8q-.425 0-.712.288T7 12t.288.713T8 13zm1 9q-2.075 0-3.9-.788t-3.175-2.137T2.788 15.9T2 12t.788-3.9t2.137-3.175T8.1 2.788T12 2t3.9.788t3.175 2.137T21.213 8.1T22 12t-.788 3.9t-2.137 3.175t-3.175 2.138T12 22m0-2q3.35 0 5.675-2.325T20 12t-2.325-5.675T12 4T6.325 6.325T4 12t2.325 5.675T12 20m0-8"})}),/* @__PURE__ */k("span",{children:"Add more"})]})})}function Ut({uploadDisabled:e,eventName:t,isQuotaLoading:r,remainingUploads:i}){const o=r?"-":i;/* @__PURE__ */
75
+ return k("div",{className:"relative overflow-hidden rounded-2xl px-3 pt-6 sm:pt-0",children:[/* @__PURE__ */k("div",{className:"absolute inset-0 opacity-50"}),/* @__PURE__ */k("div",{className:"relative z-10",children:/* @__PURE__ */k("div",{className:"flex flex-col items-center justify-center gap-3",children:/* @__PURE__ */k("div",{className:"flex items-center gap-3",children:/* @__PURE__ */k("div",{className:"space-y-1 text-center",children:[t&&/* @__PURE__ */k(F,{variant:"h4",align:"center",className:"line-clamp-2",children:t}),/* @__PURE__ */k("p",{className:n("text-sm font-medium",e?"text-muted-foreground":"text-foreground"),children:["Remaining Uploads: ",/* @__PURE__ */k("span",{className:"text-primary font-bold",children:o})]})]})})})})]})}var Rt,It=Object.defineProperty,Nt=Object.getOwnPropertyNames,Pt=(e,t)=>function(){return e&&(t=(0,e[Nt(e)[0]])(e=0)),t};function Ot(e){return function(e){return"display-p3"===e||"auto"===e}(e)&&function(){if(void 0!==Rt)return Rt;try{const e=document.createElement("canvas").getContext("2d",{colorSpace:"display-p3"});Rt=!!e&&"display-p3"===e.getContextAttributes?.().colorSpace}catch{Rt=!1}return Rt}()?"display-p3":"srgb"}function At(e,t,r,i){try{return"display-p3"===i?e.getImageData(0,0,t,r,{colorSpace:"display-p3"}):e.getImageData(0,0,t,r)}catch(n){if(n instanceof DOMException&&"SecurityError"===n.name){const e=/* @__PURE__ */new Error('Image is tainted by cross-origin data. Add crossorigin="anonymous" to the <img> tag and ensure the server sends appropriate CORS headers.');throw e.cause=n,e}throw n}}function qt(e,t,r,i){const n=Ot(r),o=document.createElement("canvas");o.width=e,o.height=t;const s="display-p3"===n?o.getContext("2d",{colorSpace:"display-p3"}):o.getContext("2d");return i(s),{data:At(s,e,t,n).data,width:e,height:t,colorSpace:n}}function Dt(e,t,r,i){const n=Ot(i);return{data:At(e,t,r,n).data,width:t,height:r,colorSpace:n}}var Lt,zt=Pt({"src/loaders/canvas-utils.ts"(){}});function jt(e){const t=e/255;return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function $t(e){const t=e<=.0031308?12.92*e:1.055*Math.pow(e,1/2.4)-.055;return Math.round(Math.max(0,Math.min(255,255*t)))}function Bt(e,t){const r=[[0,0,0],[0,0,0],[0,0,0]];for(let i=0;i<3;i++)for(let n=0;n<3;n++)r[i][n]=e[i][0]*t[0][n]+e[i][1]*t[1][n]+e[i][2]*t[2][n];return r}function Ht(e){const[t,r,i]=e[0],[n,o,s]=e[1],[a,l,c]=e[2],d=o*c-s*l,u=-(n*c-s*a),h=n*l-o*a,p=1/(t*d+r*u+i*h);return[[d*p,(i*l-r*c)*p,(r*s-i*o)*p],[u*p,(t*c-i*a)*p,(i*n-t*s)*p],[h*p,(r*a-t*l)*p,(t*o-r*n)*p]]}function Vt(e,t,r,i){return[e[0][0]*t+e[0][1]*r+e[0][2]*i,e[1][0]*t+e[1][1]*r+e[1][2]*i,e[2][0]*t+e[2][1]*r+e[2][2]*i]}((e,t)=>{for(var r in t)It(e,r,{get:t[r],enumerable:!0})})({},{BrowserPixelLoader:()=>Lt}),Pt({"src/loaders/browser.ts"(){zt(),Lt=class{async load(e,t,r="srgb"){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)return this.loadFromImage(e,r);if("undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement)return this.loadFromCanvas(e,r);if("undefined"!=typeof ImageData&&e instanceof ImageData)return{data:e.data,width:e.width,height:e.height,colorSpace:e.colorSpace??"srgb"};if("undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement)return this.loadFromVideo(e,r);if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return this.loadFromImageBitmap(e,r);if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return this.loadFromOffscreenCanvas(e,r);throw new Error("Unsupported source type. Expected HTMLImageElement, HTMLCanvasElement, HTMLVideoElement, ImageData, ImageBitmap, or OffscreenCanvas.")}loadFromImage(e,t){if(!e.complete)throw new Error('Image has not finished loading. Wait for the "load" event before calling getColor/getPalette.');if(!e.naturalWidth)throw new Error("Image has no dimensions. It may not have loaded successfully.");return qt(e.naturalWidth,e.naturalHeight,t,t=>t.drawImage(e,0,0,e.naturalWidth,e.naturalHeight))}loadFromCanvas(e,t){return Dt(e.getContext("2d"),e.width,e.height,t)}loadFromVideo(e,t){if(e.readyState<2)throw new Error('Video is not ready. Wait for the "loadeddata" or "canplay" event before calling getColor/getPalette.');const r=e.videoWidth,i=e.videoHeight;if(!r||!i)throw new Error("Video has no dimensions. It may not have loaded successfully.");return qt(r,i,t,t=>t.drawImage(e,0,0,r,i))}loadFromOffscreenCanvas(e,t){const r=e.getContext("2d");if(!r)throw new Error("Could not get 2D context from OffscreenCanvas.");return Dt(r,e.width,e.height,t)}loadFromImageBitmap(e,t){return qt(e.width,e.height,t,t=>t.drawImage(e,0,0))}}}});var Wt=[[.4865709486,.2656676932,.1982172852],[.2289745641,.6917385218,.0792869141],[0,.0451133819,1.0439443689]],Gt=Bt([[.8189330101,.3618667424,-.1288597137],[.0329845436,.9293118715,.0361456387],[.0482003018,.2643662691,.633851707]],Wt),Xt=Ht(Gt),Yt=Bt(Ht([[.4123907993,.3575843394,.1804807884],[.2126390059,.7151686788,.0721923154],[.0193308187,.1191947798,.9505321522]]),Wt),Kt=Ht(Yt),Qt=[.2126,.7152,.0722];function Jt(e,t,r,i="srgb"){if("display-p3"===i)return function(e,t,r){const[i,n,o]=Vt(Gt,jt(e),jt(t),jt(r));return function(e,t,r){const i=.2104542553*e+.793617785*t-.0040720468*r,n=1.9779984951*e-2.428592205*t+.4505937099*r,o=.0259040371*e+.7827717662*t-.808675766*r,s=Math.sqrt(n*n+o*o);let a=Math.atan2(o,n)*(180/Math.PI);return a<0&&(a+=360),{l:i,c:s,h:a}}(Math.cbrt(i),Math.cbrt(n),Math.cbrt(o))}(e,t,r);const n=jt(e),o=jt(t),s=jt(r),a=.4122214708*n+.5363325363*o+.0514459929*s,l=.2119034982*n+.6806995451*o+.1073969566*s,c=.0883024619*n+.2817188376*o+.6299787005*s,d=Math.cbrt(a),u=Math.cbrt(l),h=Math.cbrt(c),p=.2104542553*d+.793617785*u-.0040720468*h,m=1.9779984951*d-2.428592205*u+.4505937099*h,g=.0259040371*d+.7827717662*u-.808675766*h,f=Math.sqrt(m*m+g*g);let v=Math.atan2(g,m)*(180/Math.PI);return v<0&&(v+=360),{l:p,c:f,h:v}}function Zt(e,t,r,i="srgb"){if("display-p3"===i)return function(e,t,r){const[i,n,o]=function(e,t,r){const i=r*(Math.PI/180),n=t*Math.cos(i),o=t*Math.sin(i),s=e+.3963377774*n+.2158037573*o,a=e-.1055613458*n-.0638541728*o,l=e-.0894841775*n-1.291485548*o;return[s*s*s,a*a*a,l*l*l]}(e,t,r),[s,a,l]=Vt(Xt,i,n,o);return[$t(s),$t(a),$t(l)]}(e,t,r);const n=r*(Math.PI/180),o=t*Math.cos(n),s=t*Math.sin(n),a=e+.3963377774*o+.2158037573*s,l=e-.1055613458*o-.0638541728*s,c=e-.0894841775*o-1.291485548*s,d=a*a*a,u=l*l*l,h=c*c*c,p=-1.2684380046*d+2.6097574011*u-.3413193965*h,m=-.0041960863*d-.7034186147*u+1.707614701*h;return[$t(4.0767416621*d-3.3077115913*u+.2309699292*h),$t(p),$t(m)]}function er(e,t,r){const[i,n,o]=Vt(Yt,jt(e),jt(t),jt(r));return[$t(i),$t(n),$t(o)]}function tr(e,t){return(Math.max(e,t)+.05)/(Math.min(e,t)+.05)}var rr=class{constructor(e,t,r,i,n,o="srgb"){this._r=e,this._g=t,this._b=r,this.gamut=o,this.population=i,this.proportion=n}get srgb(){return this._srgb||(this._srgb="display-p3"===this.gamut?er(this._r,this._g,this._b):[this._r,this._g,this._b]),this._srgb}rgb(e="srgb"){if(e===this.gamut)return{r:this._r,g:this._g,b:this._b};const[t,r,i]="display-p3"===e?function(e,t,r){const[i,n,o]=Vt(Kt,jt(e),jt(t),jt(r));return[$t(i),$t(n),$t(o)]}(this._r,this._g,this._b):this.srgb;return{r:t,g:r,b:i}}hex(){const[e,t,r]=this.srgb,i=e=>e.toString(16).padStart(2,"0");return`#${i(e)}${i(t)}${i(r)}`}hsl(){if(!this._hsl){const[e,t,r]=this.srgb;this._hsl=function(e,t,r){const i=e/255,n=t/255,o=r/255,s=Math.max(i,n,o),a=Math.min(i,n,o),l=(s+a)/2;let c=0,d=0;if(s!==a){const e=s-a;d=l>.5?e/(2-s-a):e/(s+a),c=s===i?((n-o)/e+(n<o?6:0))/6:s===n?((o-i)/e+2)/6:((i-n)/e+4)/6}return{h:Math.round(360*c),s:Math.round(100*d),l:Math.round(100*l)}}(e,t,r)}return this._hsl}oklch(){return this._oklch||(this._oklch=Jt(this._r,this._g,this._b,this.gamut)),this._oklch}css(e){if(void 0===e){if("display-p3"===this.gamut){const e=e=>+(e/255).toFixed(4);return`color(display-p3 ${e(this._r)} ${e(this._g)} ${e(this._b)})`}e="rgb"}switch(e){case"hsl":{const{h:e,s:t,l:r}=this.hsl();return`hsl(${e}, ${t}%, ${r}%)`}case"oklch":{const{l:e,c:t,h:r}=this.oklch();return`oklch(${e.toFixed(3)} ${t.toFixed(3)} ${r.toFixed(1)})`}default:{const[e,t,r]=this.srgb;return`rgb(${e}, ${t}, ${r})`}}}array(){return[...this.srgb]}toString(){return this.hex()}get textColor(){return this.isDark?"#ffffff":"#000000"}get luminance(){return void 0===this._luminance&&(this._luminance=function(e,t,r,i="srgb"){const n=jt(e),o=jt(t),s=jt(r),[a,l,c]="display-p3"===i?Wt[1]:Qt;return a*n+l*o+c*s}(this._r,this._g,this._b,this.gamut)),this._luminance}get isDark(){return this.luminance<=.179}get isLight(){return!this.isDark}get contrast(){if(!this._contrast){const e=this.luminance,t=tr(e,1),r=tr(e,0),i=this.isDark?ir(255,255,255,0,0):ir(0,0,0,0,0);this._contrast={white:Math.round(100*t)/100,black:Math.round(100*r)/100,foreground:i}}return this._contrast}};function ir(e,t,r,i,n=0,o="srgb"){return new rr(e,t,r,i,n,o)}function nr(e,t){if("number"!=typeof e||!Number.isFinite(e))throw new Error(`region.${t} must be a finite number between 0 and 1 (received ${String(e)})`);if(e<0||e>1)throw new Error(`region.${t} must be between 0 and 1 (received ${e}). Region coordinates are fractions of the image size, not pixels.`);return e}function or(e){if(null===e||"object"!=typeof e)throw new Error("region must be an object of the form { x, y, width, height } with values between 0 and 1");const t=nr(e.x,"x"),r=nr(e.y,"y"),i=nr(e.width,"width"),n=nr(e.height,"height");if(i<=0||n<=0)throw new Error(`region.width and region.height must be greater than 0 (received ${i} and ${n})`);const o=Math.min(i,1-t),s=Math.min(n,1-r);if(o<=0||s<=0)throw new Error(`region is outside the image: x=${t}, y=${r} leaves no area to sample`);return{x:t,y:r,width:o,height:s}}function sr(e,t,r,i){const{ignoreWhite:n=!0,whiteThreshold:o=250,alphaThreshold:s=125,minSaturation:a=0}=i,l=[];for(let c=0;c<t;c+=r){const t=4*c,r=e[t],i=e[t+1],d=e[t+2],u=e[t+3];if(!(void 0!==u&&u<s||n&&r>o&&i>o&&d>o)){if(a>0){const e=Math.max(r,i,d);if(0===e||(e-Math.min(r,i,d))/e<a)continue}l.push([r,i,d])}}return l}function ar(e,t,r,i,n,o="srgb"){const s=t*r,a={ignoreWhite:i.ignoreWhite,whiteThreshold:i.whiteThreshold,alphaThreshold:i.alphaThreshold,minSaturation:i.minSaturation};let l=sr(e,s,i.quality,a);0===l.length&&(l=sr(e,s,i.quality,{...a,ignoreWhite:!1})),0===l.length&&(l=sr(e,s,i.quality,{...a,ignoreWhite:!1,alphaThreshold:0}));const c=o,d=function(e,t,r){return"srgb"===r||"display-p3"!==t?"srgb":"auto"===r?e.some(([e,t,r])=>function(e,t,r){const[i,n,o]=Vt(Yt,jt(e),jt(t),jt(r));return i<-.001||i>1.001||n<-.001||n>1.001||o<-.001||o>1.001}(e,t,r))?"display-p3":"srgb":"display-p3"}(l,c,i.gamut),u=e=>c===d?e:er(e[0],e[1],e[2]);let h;const p=/* @__PURE__ */new Set,m=[];for(const b of l){const e=b.join(",");if(!p.has(e)&&(p.add(e),m.push(b),m.length>i.colorCount))break}if(m.length<=i.colorCount){const e=/* @__PURE__ */new Map;for(const t of l){const r=t.join(",");e.set(r,(e.get(r)||0)+1)}h=m.map(t=>({color:t,population:e.get(t.join(","))}))}else if("oklch"===i.colorSpace){const e=function(e,t="srgb"){const r=new Array(e.length);for(let i=0;i<e.length;i++){const[n,o,s]=e[i],{l:a,c:l,h:c}=Jt(n,o,s,t);r[i]=[Math.round(255*a),Math.round(l/.4*255),Math.round(c/360*255)]}return r}(l,c);h=function(e,t="srgb"){return e.map(({color:[e,r,i],population:n})=>({color:Zt(e/255,r/255*.4,i/255*360,t),population:n}))}(n.quantize(e,i.colorCount),c)}else h=n.quantize(l,i.colorCount);if(h.length>0){const e=h.reduce((e,t)=>e+t.population,0);return h.map(({color:t,population:r})=>{const[i,n,o]=u(t);return ir(i,n,o,r,e>0?r/e:0,d)})}const g=function(e,t,r){let i=0,n=0,o=0,s=0;for(let a=0;a<t;a+=r){const t=4*a;i+=e[t],n+=e[t+1],o+=e[t+2],s++}return 0===s?null:[Math.round(i/s),Math.round(n/s),Math.round(o/s)]}(e,s,i.quality);if(!g)return null;const[f,v,y]=u(g);return[ir(f,v,y,1,1,d)]}function lr(e,t,r){return(e<<10)+(t<<5)+r}ir(255,255,255,0),ir(0,0,0,0);var cr=class e{constructor(e,t,r,i,n,o,s){this.r1=e,this.r2=t,this.g1=r,this.g2=i,this.b1=n,this.b2=o,this.histo=s}volume(e=!1){return(void 0===this._volume||e)&&(this._volume=(this.r2-this.r1+1)*(this.g2-this.g1+1)*(this.b2-this.b1+1)),this._volume}count(e=!1){if(void 0===this._count||e){let e=0;for(let t=this.r1;t<=this.r2;t++)for(let r=this.g1;r<=this.g2;r++)for(let i=this.b1;i<=this.b2;i++)e+=this.histo[lr(t,r,i)]||0;this._count=e}return this._count}copy(){return new e(this.r1,this.r2,this.g1,this.g2,this.b1,this.b2,this.histo)}avg(e=!1){if(void 0===this._avg||e){const e=8;if(this.r1===this.r2&&this.g1===this.g2&&this.b1===this.b2)this._avg=[this.r1<<3,this.g1<<3,this.b1<<3];else{let t=0,r=0,i=0,n=0;for(let o=this.r1;o<=this.r2;o++)for(let s=this.g1;s<=this.g2;s++)for(let a=this.b1;a<=this.b2;a++){const l=this.histo[lr(o,s,a)]||0;t+=l,r+=l*(o+.5)*e,i+=l*(s+.5)*e,n+=l*(a+.5)*e}this._avg=t?[~~(r/t),~~(i/t),~~(n/t)]:[~~(e*(this.r1+this.r2+1)/2),~~(e*(this.g1+this.g2+1)/2),~~(e*(this.b1+this.b2+1)/2)]}}return this._avg}},dr=class{constructor(e){this.comparator=e,this.contents=[],this.sorted=!1}sort(){this.contents.sort(this.comparator),this.sorted=!0}push(e){this.contents.push(e),this.sorted=!1}peek(e){return this.sorted||this.sort(),this.contents[e??this.contents.length-1]}pop(){return this.sorted||this.sort(),this.contents.pop()}size(){return this.contents.length}map(e){return this.contents.map(e)}};function ur(e,t){if(!t.count())return;if(1===t.count())return[t.copy(),null];const r=t.r2-t.r1+1,i=t.g2-t.g1+1,n=t.b2-t.b1+1,o=Math.max(r,i,n);let s=0;const a=[],l=[];if(o===r)for(let c=t.r1;c<=t.r2;c++){let r=0;for(let i=t.g1;i<=t.g2;i++)for(let n=t.b1;n<=t.b2;n++)r+=e[lr(c,i,n)]||0;s+=r,a[c]=s}else if(o===i)for(let c=t.g1;c<=t.g2;c++){let r=0;for(let i=t.r1;i<=t.r2;i++)for(let n=t.b1;n<=t.b2;n++)r+=e[lr(i,c,n)]||0;s+=r,a[c]=s}else for(let c=t.b1;c<=t.b2;c++){let r=0;for(let i=t.r1;i<=t.r2;i++)for(let n=t.g1;n<=t.g2;n++)r+=e[lr(i,n,c)]||0;s+=r,a[c]=s}return a.forEach((e,t)=>{l[t]=s-e}),function(e){const r=e+"1",i=e+"2";for(let n=t[r];n<=t[i];n++)if(a[n]>s/2){const e=t.copy(),o=t.copy(),s=n-t[r],c=t[i]-n;let d;for(d=s<=c?Math.min(t[i]-1,~~(n+c/2)):Math.max(t[r],~~(n-1-s/2));!a[d];)d++;let u=l[d];for(;!u&&a[d-1];)u=l[--d];return e[i]=d,o[r]=e[i]+1,[e,o]}}(o===r?"r":o===i?"g":"b")}function hr(e,t,r){let i=e.size(),n=0;for(;n<1e3;){if(i>=t)return;n++;const o=e.pop();if(!o.count()){e.push(o);continue}const s=ur(r,o);if(!s||!s[0])return;e.push(s[0]),s[1]&&(e.push(s[1]),i++)}}zt();var pr=new class{async init(){}quantize(e,t){return function(e,t){if(!e.length||t<2||t>256)return[];const r=function(e){const t=new Uint32Array(32768);for(const r of e)t[lr(r[0]>>3,r[1]>>3,r[2]>>3)]++;return t}(e),i=function(e,t){let r=1e6,i=0,n=1e6,o=0,s=1e6,a=0;for(const l of e){const e=l[0]>>3,t=l[1]>>3,c=l[2]>>3;e<r?r=e:e>i&&(i=e),t<n?n=t:t>o&&(o=t),c<s?s=c:c>a&&(a=c)}return new cr(r,i,n,o,s,a,t)}(e,r),n=new dr((e,t)=>e.count()-t.count());n.push(i),hr(n,.75*t,r);const o=new dr((e,t)=>e.count()*e.volume()-t.count()*t.volume());for(;n.size();)o.push(n.pop());hr(o,t,r);const s=[];for(;o.size();){const e=o.pop();s.push({color:e.avg(),population:e.count()})}return s}(e,t)}};function mr(e,t){const r=function(e){let{colorCount:t,quality:r}=e;if(void 0!==t&&Number.isInteger(t)){if(1===t)throw new Error("colorCount should be between 2 and 20. To get one color, call getColor() instead of getPalette()");t=Math.max(t,2),t=Math.min(t,20)}else t=10;return(void 0===r||!Number.isInteger(r)||r<1)&&(r=10),{colorCount:t,quality:r,ignoreWhite:void 0===e.ignoreWhite||!!e.ignoreWhite,whiteThreshold:"number"==typeof e.whiteThreshold?e.whiteThreshold:250,alphaThreshold:"number"==typeof e.alphaThreshold?e.alphaThreshold:125,minSaturation:"number"==typeof e.minSaturation?Math.max(0,Math.min(1,e.minSaturation)):0,colorSpace:e.colorSpace??"oklch",gamut:e.gamut??"srgb",region:void 0!==e.region?or(e.region):void 0}}(t??{}),i=t?.quantizer??pr,n=function(e,t){if(!t)return e;const{width:r,height:i}=e;if(!r||!i)return e;const n=function(e,t,r){const{x:i,y:n,width:o,height:s}=or(e),a=Math.min(Math.max(Math.round(i*t),0),Math.max(t-1,0)),l=Math.min(Math.max(Math.round(n*r),0),Math.max(r-1,0));return{left:a,top:l,width:Math.min(Math.max(Math.round(o*t),1),t-a),height:Math.min(Math.max(Math.round(s*r),1),r-l)}}(t,r,i);if(0===n.left&&0===n.top&&n.width===r&&n.height===i)return e;const o=4*n.width,s=(a=e.data,l=o*n.height,a instanceof Uint8ClampedArray?new Uint8ClampedArray(l):new Uint8Array(l));var a,l;for(let c=0;c<n.height;c++){const t=4*((n.top+c)*r+n.left);s.set(e.data.subarray(t,t+o),c*o)}return{data:s,width:n.width,height:n.height,colorSpace:e.colorSpace}}(function(e,t){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)return function(e,t){if(!e.complete)throw new Error('Image has not finished loading. Wait for the "load" event before calling getColorSync/getPaletteSync.');if(!e.naturalWidth)throw new Error("Image has no dimensions. It may not have loaded successfully.");return qt(e.naturalWidth,e.naturalHeight,t,t=>t.drawImage(e,0,0,e.naturalWidth,e.naturalHeight))}(e,t);if("undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement)return Dt(e.getContext("2d"),e.width,e.height,t);if("undefined"!=typeof ImageData&&e instanceof ImageData)return{data:e.data,width:e.width,height:e.height,colorSpace:e.colorSpace??"srgb"};if("undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement)return function(e,t){if(e.readyState<2)throw new Error('Video is not ready. Wait for the "loadeddata" or "canplay" event before calling getColorSync/getPaletteSync.');const r=e.videoWidth,i=e.videoHeight;if(!r||!i)throw new Error("Video has no dimensions. It may not have loaded successfully.");return qt(r,i,t,t=>t.drawImage(e,0,0,r,i))}(e,t);if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return qt(e.width,e.height,t,t=>t.drawImage(e,0,0));if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas){const r=e.getContext("2d");if(!r)throw new Error("Could not get 2D context from OffscreenCanvas.");return Dt(r,e.width,e.height,t)}throw new Error("Unsupported source type. Expected HTMLImageElement, HTMLCanvasElement, HTMLVideoElement, ImageData, ImageBitmap, or OffscreenCanvas.")}(e,r.gamut),r.region);return ar(n.data,n.width,n.height,r,i,n.colorSpace??"srgb")}function gr(e,t,r){if(t<=0||r<=0)return{};const i=Math.min(1,128/Math.max(t,r)),n=Math.max(1,Math.round(t*i)),o=Math.max(1,Math.round(r*i)),s=new OffscreenCanvas(n,o),a=s.getContext("2d",{willReadFrequently:!0});if(!a)return{};a.drawImage(e,0,0,n,o);const c=a.getImageData(0,0,n,o),d={};try{d.blurhash=l(c.data,n,o,4,4)}catch(u){console.warn("[media-intrinsics] blurhash encode failed:",u)}try{const e=mr(s,{colorCount:5});e&&(d.colors={palette:e.map(e=>e.hex())})}catch(u){console.warn("[media-intrinsics] palette extraction failed:",u)}return d}function fr(e,t){return Object.hasOwn(e,t)}var{AbortController:vr}=globalThis,{AbortSignal:yr}=globalThis,br=(e="Aborted",t)=>{const r=new DOMException(e,"AbortError");return null!=t&&fr(t,"cause")&&Object.defineProperty(r,"cause",{__proto__:null,configurable:!0,writable:!0,value:t.cause}),r},wr=class extends Error{isNetworkError;cause;constructor(e,t){super(e),this.cause=t?.cause,this.cause&&fr(this.cause,"isNetworkError")?this.isNetworkError=this.cause.isNetworkError:this.isNetworkError=!1}},xr=class extends Error{cause;isNetworkError;request;constructor(e,t=null){super("This looks like a network error, the endpoint might be blocked by an internet provider or a firewall."),this.cause=e,this.isNetworkError=!0,this.request=t}};function Sr(e){const t=e.lastIndexOf(".");return-1===t||t===e.length-1?{name:e,extension:void 0}:{name:e.slice(0,t),extension:e.slice(t+1)}}var Tr={__proto__:null,md:"text/markdown",markdown:"text/markdown",mp4:"video/mp4",mp3:"audio/mp3",svg:"image/svg+xml",jpg:"image/jpeg",png:"image/png",webp:"image/webp",gif:"image/gif",heic:"image/heic",heif:"image/heif",yaml:"text/yaml",yml:"text/yaml",csv:"text/csv",tsv:"text/tab-separated-values",tab:"text/tab-separated-values",avi:"video/x-msvideo",mks:"video/x-matroska",mkv:"video/x-matroska",mov:"video/quicktime",dicom:"application/dicom",doc:"application/msword",msg:"application/vnd.ms-outlook",docm:"application/vnd.ms-word.document.macroenabled.12",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",dot:"application/msword",dotm:"application/vnd.ms-word.template.macroenabled.12",dotx:"application/vnd.openxmlformats-officedocument.wordprocessingml.template",xla:"application/vnd.ms-excel",xlam:"application/vnd.ms-excel.addin.macroenabled.12",xlc:"application/vnd.ms-excel",xlf:"application/x-xliff+xml",xlm:"application/vnd.ms-excel",xls:"application/vnd.ms-excel",xlsb:"application/vnd.ms-excel.sheet.binary.macroenabled.12",xlsm:"application/vnd.ms-excel.sheet.macroenabled.12",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xlt:"application/vnd.ms-excel",xltm:"application/vnd.ms-excel.template.macroenabled.12",xltx:"application/vnd.openxmlformats-officedocument.spreadsheetml.template",xlw:"application/vnd.ms-excel",txt:"text/plain",text:"text/plain",conf:"text/plain",log:"text/plain",pdf:"application/pdf",zip:"application/zip","7z":"application/x-7z-compressed",rar:"application/x-rar-compressed",tar:"application/x-tar",gz:"application/gzip",dmg:"application/x-apple-diskimage"};function Cr(e){if(e.type)return e.type;const t=e.name?Sr(e.name).extension?.toLowerCase():null;return t&&t in Tr?Tr[t]:"application/octet-stream"}function Fr(e){let t="";return e.replace(/[^A-Z0-9]/gi,e=>(t+=`-${function(e){return e.charCodeAt(0).toString(32)}(e)}`,"/"))+t}function Mr(e,t){return!0===e?Object.keys(t):Array.isArray(e)?e:[]}function Er(e){return e<10?`0${e}`:e.toString()}function kr(){const e=/* @__PURE__ */new Date;return`${Er(e.getHours())}:${Er(e.getMinutes())}:${Er(e.getSeconds())}`}function _r(e){if(null!=e){const t=()=>this.abort(e.reason);e.addEventListener("abort",t,{once:!0});const r=()=>{e.removeEventListener("abort",t)};this.then?.(r,r)}return this}var Ur=class{#e=0;#t=[];#r=!1;#i;#n=1;#o;#s;limit;constructor(e){this.limit="number"!=typeof e||0===e?1/0:e}#a(e){this.#e+=1;let t,r=!1;try{t=e()}catch(i){throw this.#e-=1,i}return{abort:e=>{r||(r=!0,this.#e-=1,t?.(e),this.#l())},done:()=>{r||(r=!0,this.#e-=1,this.#l())}}}#l(){queueMicrotask(()=>this.#c())}#c(){if(this.#r||this.#e>=this.limit)return;if(0===this.#t.length)return;const e=this.#t.shift();if(null==e)throw new Error("Invariant violation: next is null");const t=this.#a(e.fn);e.abort=t.abort,e.done=t.done}#d(e,t){const r={fn:e,priority:t?.priority||0,abort:()=>{this.#u(r)},done:()=>{throw new Error("Cannot mark a queued request as done: this indicates a bug")}},i=this.#t.findIndex(e=>r.priority>e.priority);return-1===i?this.#t.push(r):this.#t.splice(i,0,r),r}#u(e){const t=this.#t.indexOf(e);-1!==t&&this.#t.splice(t,1)}run(e,t){return!this.#r&&this.#e<this.limit?this.#a(e):this.#d(e,t)}wrapSyncFunction(e,t){return(...r)=>{const i=this.run(()=>(e(...r),queueMicrotask(()=>i.done()),()=>{}),t);return{abortOn:_r,abort(){i.abort()}}}}wrapPromiseFunction(e,t){return(...r)=>{let i;const n=new Promise((n,o)=>{i=this.run(()=>{let t,s;try{s=Promise.resolve(e(...r))}catch(a){s=Promise.reject(a)}return s.then(e=>{t?o(t):(i.done(),n(e))},e=>{t?o(t):(i.done(),o(e))}),e=>{t=function(e){return new Error("Cancelled",{cause:e})}(e)}},t)});return n.abort=e=>{i.abort(e)},n.abortOn=_r,n}}resume(){this.#r=!1,clearTimeout(this.#i);for(let e=0;e<this.limit;e++)this.#l()}#h=()=>this.resume();pause(e=null){this.#r=!0,clearTimeout(this.#i),null!=e&&(this.#i=setTimeout(this.#h,e))}rateLimit(e){clearTimeout(this.#s),this.pause(e),this.limit>1&&Number.isFinite(this.limit)&&(this.#o=this.limit-1,this.limit=this.#n,this.#s=setTimeout(this.#p,e))}#p=()=>{if(this.#r)this.#s=setTimeout(this.#p,0);else{this.#n=this.limit,this.limit=Math.ceil((this.#o+this.#n)/2);for(let e=this.#n;e<=this.limit;e++)this.#l();this.#o-this.#n>3?this.#s=setTimeout(this.#p,2e3):this.#n=Math.floor(this.#n/2)}};get isPaused(){return this.#r}};function Rr(e,t,r){const i=[];return e.forEach(e=>"string"!=typeof e?i.push(e):t[Symbol.split](e).forEach((e,t,n)=>{""!==e&&i.push(e),t<n.length-1&&i.push(r)})),i}function Ir(e,t){const r=/\$/g;let i=[e];if(null==t)return i;for(const n of Object.keys(t))if("_"!==n){let e=t[n];"string"==typeof e&&(e=r[Symbol.replace](e,"$$$$")),i=Rr(i,new RegExp(`%\\{${n}\\}`,"g"),e)}return i}var Nr=e=>{throw new Error(`missing string: ${e}`)},Pr=class{locale;constructor(e,{onMissingKey:t=Nr}={}){this.locale={strings:{},pluralize:e=>1===e?0:1},Array.isArray(e)?e.forEach(this.#m,this):this.#m(e),this.#g=t}#g;#m(e){if(!e?.strings)return;const t=this.locale;Object.assign(this.locale,{strings:{...t.strings,...e.strings},pluralize:e.pluralize||t.pluralize})}translate(e,t){return this.translateArray(e,t).join("")}translateArray(e,t){let r=this.locale.strings[e];if(null==r&&(this.#g(e),r=e),"object"==typeof r){if(t&&void 0!==t.smart_count)return Ir(r[this.locale.pluralize(t.smart_count)],t);throw new Error("Attempted to use a string with plural forms, but no value was given for %{smart_count}")}if("string"!=typeof r)throw new Error("string was not a string");return Ir(r,t)}},Or=class extends Error{name="UserFacingApiError"},Ar=/* @__PURE__ */t((e,t)=>{function r(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}t.exports=r,r.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},r.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},r.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=/* @__PURE__ */(new Date).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(/* @__PURE__ */new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(void 0===r){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1)}var i=this;return this._timer=setTimeout(function(){i._attempts++,i._operationTimeoutCb&&(i._timeout=setTimeout(function(){i._operationTimeoutCb(i._attempts)},i._operationTimeout),i._options.unref&&i._timeout.unref()),i._fn(i._attempts)},r),this._options.unref&&this._timer.unref(),!0},r.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout)),this._operationStart=/* @__PURE__ */(new Date).getTime(),this._fn(this._attempts)},r.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},r.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},r.prototype.start=r.prototype.try,r.prototype.errors=function(){return this._errors},r.prototype.attempts=function(){return this._attempts},r.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,r=0,i=0;i<this._errors.length;i++){var n=this._errors[i],o=n.message,s=(e[o]||0)+1;e[o]=s,s>=r&&(t=n,r=s)}return t}}),qr=/* @__PURE__ */t(e=>{var t=Ar();e.operation=function(r){return new t(e.timeouts(r),{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var i=[],n=0;n<t.retries;n++)i.push(this.createTimeout(n,t));return e&&e.forever&&!i.length&&i.push(this.createTimeout(n,t)),i.sort(function(e,t){return e-t}),i},e.createTimeout=function(e,t){var r=t.randomize?Math.random()+1:1,i=Math.round(r*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return Math.min(i,t.maxTimeout)},e.wrap=function(t,r,i){if(r instanceof Array&&(i=r,r=null),!i)for(var n in i=[],t)"function"==typeof t[n]&&i.push(n);for(var o=0;o<i.length;o++){var s=i[o],a=t[s];t[s]=function(i){var n=e.operation(r),o=Array.prototype.slice.call(arguments,1),s=o.pop();o.push(function(e){n.retry(e)||(e&&(arguments[0]=n.mainError()),s.apply(this,arguments))}),n.attempt(function(){i.apply(t,o)})}.bind(t,a),t[s].options=r}}}),Dr=/* @__PURE__ */t((e,t)=>{t.exports=qr()}),Lr=Object.prototype.toString,zr=/* @__PURE__ */new Set(["network error","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);var jr=/* @__PURE__ */e(Dr(),1),$r=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}},Br=(e,t,r)=>{const i=r.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=i,e};async function Hr(e,t){return new Promise((r,i)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;const n=jr.operation(t),o=()=>{n.stop(),i(t.signal?.reason)};t.signal&&!t.signal.aborted&&t.signal.addEventListener("abort",o,{once:!0});const s=()=>{t.signal?.removeEventListener("abort",o),n.stop()};n.attempt(async o=>{try{const t=await e(o);s(),r(t)}catch(a){try{if(!(a instanceof Error))throw new TypeError(`Non-error was thrown: "${a}". You should only throw errors.`);if(a instanceof $r)throw a.originalError;if(a instanceof TypeError&&!function(e){if(!e||(t=e,"[object Error]"!==Lr.call(t))||"TypeError"!==e.name||"string"!=typeof e.message)return!1;var t;const{message:r,stack:i}=e;return"Load failed"===r||r.startsWith("Load failed (")&&r.endsWith(")")?void 0===i||"__sentry_captured__"in e:!!r.startsWith("error sending request for url")||!!("Failed to fetch"===r||r.startsWith("Failed to fetch (")&&r.endsWith(")"))||zr.has(r)}(a))throw a;if(Br(a,o,t),await t.shouldRetry(a)||(n.stop(),i(a)),await t.onFailedAttempt(a),!n.retry(a))throw n.mainError()}catch(l){Br(l,o,t),s(),i(l)}}})})}var Vr=class extends Error{isAuthError;constructor(){super("Authorization required"),this.name="AuthError",this.isAuthError=!0}},Wr=class extends Error{statusCode;constructor({statusCode:e,message:t}){super(t),this.name="HttpError",this.statusCode=e}},Gr=class{static VERSION="5.1.1";#f;uppy;opts;constructor(e,t){this.uppy=e,this.opts=t,this.onReceiveResponse=this.onReceiveResponse.bind(this),this.#f=t.companionHeaders}setCompanionHeaders(e){this.#f=e}[Symbol.for("uppy test: getCompanionHeaders")](){return this.#f}get hostname(){const{companion:e}=this.uppy.getState(),t=this.opts.companionUrl;return(e?.[t]?e[t]:t).replace(/\/$/,"")}async headers(e=!1){return{Accept:"application/json",...e?void 0:{"Content-Type":"application/json"},...this.#f}}onReceiveResponse(e){const{headers:t}=e,r=this.uppy.getState().companion||{},i=this.opts.companionUrl;t.has("i-am")&&t.get("i-am")!==r[i]&&this.uppy.setState({companion:{...r,[i]:t.get("i-am")}})}#v(e){return/^(https?:|)\/\//.test(e)?e:`${this.hostname}/${e}`}async request({path:e,method:t="GET",data:r,skipPostResponse:i,signal:n}){try{const o=await this.headers(!r),s=await function(...e){return fetch(...e).catch(e=>{throw"AbortError"===e.name?e:new xr(e)})}(this.#v(e),{method:t,signal:n,headers:o,credentials:this.opts.companionCookiesRule||"same-origin",body:r?JSON.stringify(r):null});return i||this.onReceiveResponse(s),await async function(e){if(401===e.status)throw new Vr;if(e.ok)return e.json();let t,r=`Failed request with status: ${e.status}. ${e.statusText}`;try{t=await e.json(),t.message&&(r=`${r} message: ${t.message}`),t.requestId&&(r=`${r} request-Id: ${t.requestId}`)}catch(i){throw new Error(r,{cause:i})}if(e.status>=400&&e.status<=499&&t.message)throw new Or(t.message);throw new Wr({statusCode:e.status,message:r})}(s)}catch(o){if(o.isAuthError||"UserFacingApiError"===o.name||"AbortError"===o.name)throw o;throw new wr(`Could not ${t} ${this.#v(e)}`,{cause:o})}}async get(e,t){return this.request({...t,path:e})}async post(e,t,r){return this.request({...r,path:e,method:"POST",data:t})}async delete(e,t,r){return this.request({...r,path:e,method:"DELETE",data:t})}async uploadRemoteFile(e,t,r){try{const{signal:i,getQueue:n}=r||{};return await Hr(async()=>{const r=this.uppy.getFile(e.id)?.serverToken;if(null!=r)return this.uppy.log(`Connecting to exiting websocket ${r}`),this.#y({file:e,queue:n(),signal:i});const o=await n().wrapPromiseFunction(async(...e)=>{try{return await this.#b(...e)}catch(t){if(t.isAuthError)throw new $r(t);if(null==t.cause)throw t;const e=t.cause,r=()=>[408,409,429,418,423].includes(e.statusCode)||e.statusCode>=500&&e.statusCode<=599&&![501,505].includes(e.statusCode);if("HttpError"===e.name&&!r())throw new $r(e);throw e}},{priority:-1})({file:e,postBody:t,signal:i}).abortOn(i);return this.uppy.getFile(e.id)?(this.uppy.setFileState(e.id,{serverToken:o}),this.#y({file:this.uppy.getFile(e.id),queue:n(),signal:i})):void 0},{retries:10,signal:i,onFailedAttempt:e=>this.uppy.log(`Retrying upload due to: ${e.message}`,"warning")})}catch(i){if("AbortError"===i.name)return;throw this.uppy.emit("upload-error",e,i),i}}#b=async({file:e,postBody:t,signal:r})=>{if(null==e.remote?.url)throw new Error("Cannot connect to an undefined URL");return(await this.post(e.remote.url,{...e.remote.body,...t},{signal:r})).token};async#y({file:e,queue:t,signal:r}){let i;const{capabilities:n}=this.uppy.getState();try{return await new Promise((o,s)=>{const a=e.serverToken,l=function(e){const t=/^(?:https?:\/\/|\/\/)?(?:[^@\n]+@)?([^\n]+)/i.exec(e)?.[1];return`${/^http:\/\//i.test(e)?"ws":"wss"}://${t}`}(e.remote.companionUrl);let c,d,u,{isPaused:h}=e;const p=(t,r)=>{null!=c&&c.readyState===c.OPEN?c.send(JSON.stringify({action:t,payload:r??{}})):this.uppy.log(`Cannot send "${t}" to socket ${e.id} because the socket state was ${String(c?.readyState)}`,"warning")};function m(){n.resumableUploads&&p(h?"pause":"resume")}const g=e=>{n.resumableUploads&&(h=e,c&&m())},f=t=>{n.individualCancellation&&t.id===e.id&&(p("cancel"),d?.abort?.(),this.uppy.log(`upload ${e.id} was removed`),o())},v=()=>{p("cancel"),d?.abort?.(),this.uppy.log(`upload ${e.id} was canceled`),o()},y=(t,r)=>{t?.id===e.id&&g(r)},b=()=>g(!0),w=()=>g(!1);this.uppy.on("file-removed",f),this.uppy.on("cancel-all",v),this.uppy.on("upload-pause",y),this.uppy.on("pause-all",b),this.uppy.on("resume-all",w),i=()=>{this.uppy.off("file-removed",f),this.uppy.off("cancel-all",v),this.uppy.off("upload-pause",y),this.uppy.off("pause-all",b),this.uppy.off("resume-all",w)},r.addEventListener("abort",()=>{d?.abort()}),(async()=>{d&&d.abort(),d=new AbortController;const r=t=>{this.uppy.setFileState(e.id,{serverToken:null}),d?.abort?.(),s(t)};function i(){clearTimeout(u),h||(u=setTimeout(()=>r(/* @__PURE__ */new Error("Timeout waiting for message from Companion socket")),3e5))}try{await t.wrapPromiseFunction(async()=>{await Hr(async()=>new Promise((t,n)=>{c=new WebSocket(`${l}/api/${a}`),i(),c.addEventListener("close",()=>{c=void 0,n(/* @__PURE__ */new Error("Socket closed unexpectedly"))}),c.addEventListener("error",e=>{this.uppy.log(`Companion socket error ${JSON.stringify(e)}, closing socket`,"warning"),c?.close()}),c.addEventListener("open",()=>{m()}),c.addEventListener("message",t=>{i();try{const{action:r,payload:i}=JSON.parse(t.data);switch(r){case"progress":!function(e,t,r){const{progress:i,bytesUploaded:n,bytesTotal:o}=t;i&&(e.uppy.log(`Upload progress: ${i}`),e.uppy.emit("upload-progress",r,{uploadStarted:r.progress.uploadStarted??0,bytesUploaded:n,bytesTotal:o}))}(this,i,this.uppy.getFile(e.id));break;case"success":{const t=i.response?.responseText;this.uppy.emit("upload-success",this.uppy.getFile(e.id),{uploadURL:i.url,status:i.response?.status??200,body:t?JSON.parse(t):void 0}),d?.abort?.(),o();break}case"error":{const{message:e}=i.error;throw Object.assign(new Error(e),{cause:i.error})}default:this.uppy.log(`Companion socket unknown action ${r}`,"warning")}}catch(n){r(n)}});const s=()=>{this.uppy.log(`Closing socket ${e.id}`),clearTimeout(u),c&&c.close(),c=void 0};d.signal.addEventListener("abort",()=>{s()})}),{retries:10,signal:d.signal,onFailedAttempt:()=>{d.signal.aborted||this.uppy.log(`Retrying websocket ${e.id}`)}})})().abortOn(d.signal)}catch(n){if(d.signal.aborted)return;r(n)}})()})}finally{i?.()}}},Xr=class{uppy;opts;id;defaultLocale;i18n;i18nArray;type;VERSION;constructor(e,t){this.uppy=e,this.opts=t??{}}getPluginState(){const{plugins:e}=this.uppy.getState();return e?.[this.id]||{}}setPluginState(e){const{plugins:t}=this.uppy.getState();this.uppy.setState({plugins:{...t,[this.id]:{...t[this.id],...e}}})}setOptions(e){this.opts={...this.opts,...e},this.setPluginState(void 0),this.i18nInit()}i18nInit(){const e=new Pr([this.defaultLocale,this.uppy.locale,this.opts.locale]);this.i18n=e.translate.bind(e),this.i18nArray=e.translateArray.bind(e),this.setPluginState(void 0)}addTarget(e){throw new Error("Extend the addTarget method to add your plugin to another plugin's target")}install(){}uninstall(){}update(e){}afterUpdate(){}},Yr=class{#w;#x=[];constructor(e){this.#w=e}on(e,t){return this.#x.push([e,t]),this.#w.on(e,t)}remove(){for(const[e,t]of this.#x.splice(0))this.#w.off(e,t)}onFilePause(e,t){this.on("upload-pause",(r,i)=>{e===r?.id&&t(i)})}onFileRemove(e,t){this.on("file-removed",r=>{e===r.id&&t(r.id)})}onPause(e,t){this.on("upload-pause",(r,i)=>{e===r?.id&&t(i)})}onRetry(e,t){this.on("upload-retry",r=>{e===r?.id&&t()})}onRetryAll(e,t){this.on("retry-all",()=>{this.#w.getFile(e)&&t()})}onPauseAll(e,t){this.on("pause-all",()=>{this.#w.getFile(e)&&t()})}onCancelAll(e,t){this.on("cancel-all",(...r)=>{this.#w.getFile(e)&&t(...r)})}onResumeAll(e,t){this.on("resume-all",()=>{this.#w.getFile(e)&&t()})}},Kr={debug:()=>{},warn:()=>{},error:(...e)=>console.error(`[Uppy] [${kr()}]`,...e)},Qr={debug:(...e)=>console.debug(`[Uppy] [${kr()}]`,...e),warn:(...e)=>console.warn(`[Uppy] [${kr()}]`,...e),error:(...e)=>console.error(`[Uppy] [${kr()}]`,...e)},Jr=/* @__PURE__ */t((e,t)=>{t.exports=function(e){if("number"!=typeof e||Number.isNaN(e))throw new TypeError("Expected a number, got "+typeof e);const t=e<0;let r=Math.abs(e);if(t&&(r=-r),0===r)return"0 B";const i=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],n=Math.min(Math.floor(Math.log(r)/Math.log(1024)),i.length-1),o=Number(r/1024**n),s=i[n];return`${o>=10||o%1==0?Math.round(o):o.toFixed(1)} ${s}`}}),Zr=/* @__PURE__ */t((e,t)=>{function r(e,t){this.text=e=e||"",this.hasWild=~e.indexOf("*"),this.separator=t,this.parts=e.split(t)}r.prototype.match=function(e){var t,r,i=!0,n=this.parts,o=n.length;if("string"==typeof e||e instanceof String)if(this.hasWild||this.text==e){for(r=(e||"").split(this.separator),t=0;i&&t<o;t++)"*"!==n[t]&&(i=t<r.length&&n[t]===r[t]);i=i&&r}else i=!1;else if("function"==typeof e.splice)for(i=[],t=e.length;t--;)this.match(e[t])&&(i[i.length]=e[t]);else if("object"==typeof e)for(var s in i={},e)this.match(s)&&(i[s]=e[s]);return i},t.exports=function(e,t,i){var n=new r(e,i||/[\/\.]/);return void 0!==t?n.match(t):n}}),ei=/* @__PURE__ */t((e,t)=>{var r=Zr(),i=/[\/\+\.]/;t.exports=function(e,t){function n(t){var n=r(t,e,i);return n&&n.length>=2}return t?n(t.split(";")[0]):n}}),ti=/* @__PURE__ */e(Jr(),1),ri=/* @__PURE__ */e(ei(),1),ii={maxFileSize:null,minFileSize:null,maxTotalFileSize:null,maxNumberOfFiles:null,minNumberOfFiles:null,allowedFileTypes:null,requiredMetaFields:[]},ni=class extends Error{isUserFacing;file;constructor(e,t){super(e),this.isUserFacing=t?.isUserFacing??!0,t?.file&&(this.file=t.file)}isRestriction=!0},oi=class{getI18n;getOpts;constructor(e,t){this.getI18n=t,this.getOpts=()=>{const t=e();if(null!=t.restrictions?.allowedFileTypes&&!Array.isArray(t.restrictions.allowedFileTypes))throw new TypeError("`restrictions.allowedFileTypes` must be an array");return t}}validateAggregateRestrictions(e,t){const{maxTotalFileSize:r,maxNumberOfFiles:i}=this.getOpts().restrictions;if(i&&e.filter(e=>!e.isGhost).length+t.length>i)throw new ni(`${this.getI18n()("youCanOnlyUploadX",{smart_count:i})}`);if(r){const i=[...e,...t].reduce((e,t)=>e+(t.size??0),0);if(i>r)throw new ni(this.getI18n()("aggregateExceedsSize",{sizeAllowed:(0,ti.default)(r),size:(0,ti.default)(i)}))}}validateSingleFile(e){const{maxFileSize:t,minFileSize:r,allowedFileTypes:i}=this.getOpts().restrictions;if(i&&!i.some(t=>t.includes("/")?!!e.type&&(0,ri.default)(e.type.replace(/;.*?$/,""),t):!("."!==t[0]||!e.extension)&&e.extension.toLowerCase()===t.slice(1).toLowerCase())){const t=i.join(", ");throw new ni(this.getI18n()("youCanOnlyUploadFileTypes",{types:t}),{file:e})}if(t&&null!=e.size&&e.size>t)throw new ni(this.getI18n()("exceedsSize",{size:(0,ti.default)(t),file:e.name??this.getI18n()("unnamed")}),{file:e});if(r&&null!=e.size&&e.size<r)throw new ni(this.getI18n()("inferiorSize",{size:(0,ti.default)(r)}),{file:e})}validate(e,t){t.forEach(e=>{this.validateSingleFile(e)}),this.validateAggregateRestrictions(e,t)}validateMinNumberOfFiles(e){const{minNumberOfFiles:t}=this.getOpts().restrictions;if(t&&Object.keys(e).length<t)throw new ni(this.getI18n()("youHaveToAtLeastSelectX",{smart_count:t}))}getMissingRequiredMetaFields(e){const t=new ni(this.getI18n()("missingRequiredMetaFieldOnFile",{fileName:e.name??this.getI18n()("unnamed")})),{requiredMetaFields:r}=this.getOpts().restrictions,i=[];for(const n of r)Object.hasOwn(e.meta,n)&&""!==e.meta[n]||i.push(n);return{missingFields:i,error:t}}},si=class{static VERSION="5.0.0";state={};#S=/* @__PURE__ */new Set;getState(){return this.state}setState(e){const t={...this.state},r={...this.state,...e};this.state=r,this.#T(t,r,e)}subscribe(e){return this.#S.add(e),()=>{this.#S.delete(e)}}#T(...e){this.#S.forEach(t=>{t(...e)})}},ai=/* @__PURE__ */t((e,t)=>{t.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}}),li=/* @__PURE__ */t((e,t)=>{var r="object"==typeof global&&global&&global.Object===Object&&global;t.exports=r}),ci=/* @__PURE__ */t((e,t)=>{var r=li(),i="object"==typeof self&&self&&self.Object===Object&&self,n=r||i||Function("return this")();t.exports=n}),di=/* @__PURE__ */t((e,t)=>{var r=ci();t.exports=function(){return r.Date.now()}}),ui=/* @__PURE__ */t((e,t)=>{var r=/\s/;t.exports=function(e){for(var t=e.length;t--&&r.test(e.charAt(t)););return t}}),hi=/* @__PURE__ */t((e,t)=>{var r=ui(),i=/^\s+/;t.exports=function(e){return e?e.slice(0,r(e)+1).replace(i,""):e}}),pi=/* @__PURE__ */t((e,t)=>{var r=ci().Symbol;t.exports=r}),mi=/* @__PURE__ */t((e,t)=>{var r=pi(),i=Object.prototype,n=i.hasOwnProperty,o=i.toString,s=r?r.toStringTag:void 0;t.exports=function(e){var t=n.call(e,s),r=e[s];try{e[s]=void 0;var i=!0}catch(l){}var a=o.call(e);return i&&(t?e[s]=r:delete e[s]),a}}),gi=/* @__PURE__ */t((e,t)=>{var r=Object.prototype.toString;t.exports=function(e){return r.call(e)}}),fi=/* @__PURE__ */t((e,t)=>{var r=pi(),i=mi(),n=gi(),o=r?r.toStringTag:void 0;t.exports=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":o&&o in Object(e)?i(e):n(e)}}),vi=/* @__PURE__ */t((e,t)=>{t.exports=function(e){return null!=e&&"object"==typeof e}}),yi=/* @__PURE__ */t((e,t)=>{var r=fi(),i=vi();t.exports=function(e){return"symbol"==typeof e||i(e)&&"[object Symbol]"==r(e)}}),bi=/* @__PURE__ */t((e,t)=>{var r=hi(),i=ai(),n=yi(),o=/^[-+]0x[0-9a-f]+$/i,s=/^0b[01]+$/i,a=/^0o[0-7]+$/i,l=parseInt;t.exports=function(e){if("number"==typeof e)return e;if(n(e))return NaN;if(i(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=i(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=r(e);var c=s.test(e);return c||a.test(e)?l(e.slice(2),c?2:8):o.test(e)?NaN:+e}}),wi=/* @__PURE__ */t((e,t)=>{var r=ai(),i=di(),n=bi(),o=Math.max,s=Math.min;t.exports=function(e,t,a){var l,c,d,u,h,p,m=0,g=!1,f=!1,v=!0;if("function"!=typeof e)throw new TypeError("Expected a function");function y(t){var r=l,i=c;return l=c=void 0,m=t,u=e.apply(i,r)}function b(e){var r=e-p;return void 0===p||r>=t||r<0||f&&e-m>=d}function w(){var e=i();if(b(e))return x(e);h=setTimeout(w,function(e){var r=t-(e-p);return f?s(r,d-(e-m)):r}(e))}function x(e){return h=void 0,v&&l?y(e):(l=c=void 0,u)}function S(){var e=i(),r=b(e);if(l=arguments,c=this,p=e,r){if(void 0===h)return function(e){return m=e,h=setTimeout(w,t),g?y(e):u}(p);if(f)return clearTimeout(h),h=setTimeout(w,t),y(p)}return void 0===h&&(h=setTimeout(w,t)),u}return t=n(t)||0,r(a)&&(g=!!a.leading,d=(f="maxWait"in a)?o(n(a.maxWait)||0,t):d,v="trailing"in a?!!a.trailing:v),S.cancel=function(){void 0!==h&&clearTimeout(h),m=0,l=p=c=h=void 0},S.flush=function(){return void 0===h?u:x(i())},S}}),xi=/* @__PURE__ */t((e,t)=>{var r=wi(),i=ai();t.exports=function(e,t,n){var o=!0,s=!0;if("function"!=typeof e)throw new TypeError("Expected a function");return i(n)&&(o="leading"in n?!!n.leading:o,s="trailing"in n?!!n.trailing:s),r(e,t,{leading:o,maxWait:t,trailing:s})}}),Si=/* @__PURE__ */t((e,t)=>{t.exports=function(){var e={},t=e._fns={};return e.emit=function(e,r,i,n,o,s,a){var l=function(e){for(var r=t[e]?t[e]:[],i=e.indexOf(":"),n=-1===i?[e]:[e.substring(0,i),e.substring(i+1)],o=Object.keys(t),s=0,a=o.length;s<a;s++){var l=o[s];if("*"===l&&(r=r.concat(t[l])),2===n.length&&n[0]===l){r=r.concat(t[l]);break}}return r}(e);l.length&&function(e,t,r){for(var i=0,n=t.length;i<n&&t[i];i++)t[i].event=e,t[i].apply(t[i],r)}(e,l,[r,i,n,o,s,a])},e.on=function(e,r){t[e]||(t[e]=[]),t[e].push(r)},e.once=function(t,r){this.on(t,function i(){r.apply(this,arguments),e.off(t,i)})},e.off=function(e,t){var r=[];if(e&&t)for(var i=this._fns[e],n=0,o=i?i.length:0;n<o;n++)i[n]!==t&&r.push(i[n]);r.length?this._fns[e]=r:delete this._fns[e]},e}}),Ti={strings:{addBulkFilesFailed:{0:"Failed to add %{smart_count} file due to an internal error",1:"Failed to add %{smart_count} files due to internal errors"},youCanOnlyUploadX:{0:"You can only upload %{smart_count} file",1:"You can only upload %{smart_count} files"},youHaveToAtLeastSelectX:{0:"You have to select at least %{smart_count} file",1:"You have to select at least %{smart_count} files"},aggregateExceedsSize:"You selected %{size} of files, but maximum allowed size is %{sizeAllowed}",exceedsSize:"%{file} exceeds maximum allowed size of %{size}",missingRequiredMetaField:"Missing required meta fields",missingRequiredMetaFieldOnFile:"Missing required meta fields in %{fileName}",inferiorSize:"This file is smaller than the allowed size of %{size}",youCanOnlyUploadFileTypes:"You can only upload: %{types}",noMoreFilesAllowed:"Cannot add more files",noDuplicates:"Cannot add the duplicate file '%{fileName}', it already exists",companionError:"Connection with Companion failed",authAborted:"Authentication aborted",companionUnauthorizeHint:"To unauthorize to your %{provider} account, please go to %{url}",failedToUpload:"Failed to upload %{file}",noInternetConnection:"No Internet connection",connectedToInternet:"Connected to the Internet",noFilesFound:"You have no files or folders here",noSearchResults:"Unfortunately, there are no results for this search",selectX:{0:"Select %{smart_count}",1:"Select %{smart_count}"},allFilesFromFolderNamed:"All files from folder %{name}",openFolderNamed:"Open folder %{name}",cancel:"Cancel",logOut:"Log out",logIn:"Log in",pickFiles:"Pick files",pickPhotos:"Pick photos",filter:"Filter",resetFilter:"Reset filter",loading:"Loading...",loadedXFiles:"Loaded %{numFiles} files",authenticateWithTitle:"Please authenticate with %{pluginName} to select files",authenticateWith:"Connect to %{pluginName}",signInWithGoogle:"Sign in with Google",searchImages:"Search for images",enterTextToSearch:"Enter text to search for images",search:"Search",resetSearch:"Reset search",emptyFolderAdded:"No files were added from empty folder",addedNumFiles:"Added %{numFiles} file(s)",folderAlreadyAdded:'The folder "%{folder}" was already added',folderAdded:{0:"Added %{smart_count} file from %{folder}",1:"Added %{smart_count} files from %{folder}"},additionalRestrictionsFailed:"%{count} additional restrictions were not fulfilled",unnamed:"Unnamed",pleaseWait:"Please wait"}};function Ci(e){if(null==e&&"undefined"!=typeof navigator&&(e=navigator.userAgent),!e)return!0;const t=/Edge\/(\d+\.\d+)/.exec(e);if(!t)return!0;const r=t[1].split(".",2),i=parseInt(r[0],10),n=parseInt(r[1],10);return i<15||15===i&&n<15063||i>18||18===i&&n>=18218}var Fi=/* @__PURE__ */e(xi(),1),Mi=/* @__PURE__ */e(Si(),1),Ei={totalProgress:0,allowNewUpload:!0,error:null,recoveredState:null},ki=class e{static VERSION="5.2.0";#C=Object.create(null);#F;#M;#E=(0,Mi.default)();#k=/* @__PURE__ */new Set;#_=/* @__PURE__ */new Set;#U=/* @__PURE__ */new Set;defaultLocale;locale;opts;store;i18n;i18nArray;scheduledAutoProceed=null;wasOffline=!1;constructor(t){this.defaultLocale=Ti;const r={id:"uppy",autoProceed:!1,allowMultipleUploadBatches:!0,debug:!1,restrictions:ii,meta:{},onBeforeFileAdded:(e,t)=>!Object.hasOwn(t,e.id),onBeforeUpload:e=>e,store:new si,logger:Kr,infoTimeout:5e3},i={...r,...t};this.opts={...i,restrictions:{...r.restrictions,...t?.restrictions}},t?.logger&&t.debug?this.log("You are using a custom `logger`, but also set `debug: true`, which uses built-in logger to output logs to console. Ignoring `debug: true` and using your custom `logger`.","warning"):t?.debug&&(this.opts.logger=Qr),this.log(`Using Core v${e.VERSION}`),this.i18nInit(),this.store=this.opts.store,this.setState({...Ei,plugins:{},files:{},currentUploads:{},capabilities:{uploadProgress:Ci(),individualCancellation:!0,resumableUploads:!1},meta:{...this.opts.meta},info:[]}),this.#F=new oi(()=>this.opts,()=>this.i18n),this.#M=this.store.subscribe((e,t,r)=>{this.emit("state-update",e,t,r),this.updateAll(t)}),this.opts.debug&&"undefined"!=typeof window&&(window[this.opts.id]=this),this.#R()}emit(e,...t){this.#E.emit(e,...t)}on(e,t){return this.#E.on(e,t),this}once(e,t){return this.#E.once(e,t),this}off(e,t){return this.#E.off(e,t),this}updateAll(e){this.iteratePlugins(t=>{t.update(e)})}setState(e){this.store.setState(e)}getState(){return this.store.getState()}patchFilesState(e){const t=this.getState().files;this.setState({files:{...t,...Object.fromEntries(Object.entries(e).map(([e,r])=>[e,{...t[e],...r}]))}})}setFileState(e,t){if(!this.getState().files[e])throw new Error(`Can’t set state for ${e} (the file could have been removed)`);this.patchFilesState({[e]:t})}i18nInit(){const e=new Pr([this.defaultLocale,this.opts.locale],{onMissingKey:e=>this.log(`Missing i18n string: ${e}`,"error")});this.i18n=e.translate.bind(e),this.i18nArray=e.translateArray.bind(e),this.locale=e.locale}setOptions(e){this.opts={...this.opts,...e,restrictions:{...this.opts.restrictions,...e?.restrictions}},e.meta&&this.setMeta(e.meta),this.i18nInit(),e.locale&&this.iteratePlugins(t=>{t.setOptions(e)}),this.setState(void 0)}resetProgress(){const e={percentage:0,bytesUploaded:!1,uploadComplete:!1,uploadStarted:null},t={...this.getState().files},r=Object.create(null);Object.keys(t).forEach(i=>{r[i]={...t[i],progress:{...t[i].progress,...e},tus:void 0,transloadit:void 0}}),this.setState({files:r,...Ei})}clear(){const{capabilities:e,currentUploads:t}=this.getState();if(Object.keys(t).length>0&&!e.individualCancellation)throw new Error("The installed uploader plugin does not allow removing files during an upload.");this.setState({...Ei,files:{}})}addPreProcessor(e){this.#k.add(e)}removePreProcessor(e){return this.#k.delete(e)}addPostProcessor(e){this.#U.add(e)}removePostProcessor(e){return this.#U.delete(e)}addUploader(e){this.#_.add(e)}removeUploader(e){return this.#_.delete(e)}setMeta(e){const t={...this.getState().meta,...e},r={...this.getState().files};Object.keys(r).forEach(t=>{r[t]={...r[t],meta:{...r[t].meta,...e}}}),this.log("Adding metadata:"),this.log(e),this.setState({meta:t,files:r})}setFileMeta(e,t){const r={...this.getState().files};if(!r[e])return void this.log(`Was trying to set metadata for a file that has been removed: ${e}`);const i={...r[e].meta,...t};r[e]={...r[e],meta:i},this.setState({files:r})}getFile(e){return this.getState().files[e]}getFiles(){const{files:e}=this.getState();return Object.values(e)}getFilesByIds(e){return e.map(e=>this.getFile(e))}getObjectOfFilesPerState(){const{files:e,totalProgress:t,error:r}=this.getState(),i=Object.values(e),n=[],o=[],s=[],a=[],l=[],c=[],d=[],u=[],h=[];for(const p of i){const{progress:e}=p;!e.uploadComplete&&e.uploadStarted&&(n.push(p),p.isPaused||u.push(p)),e.uploadStarted||o.push(p),(e.uploadStarted||e.preprocess||e.postprocess)&&s.push(p),e.uploadStarted&&a.push(p),p.isPaused&&l.push(p),e.uploadComplete&&c.push(p),p.error&&d.push(p),(e.preprocess||e.postprocess)&&h.push(p)}return{newFiles:o,startedFiles:s,uploadStartedFiles:a,pausedFiles:l,completeFiles:c,erroredFiles:d,inProgressFiles:n,inProgressNotPausedFiles:u,processingFiles:h,isUploadStarted:a.length>0,isAllComplete:100===t&&c.length===i.length&&0===h.length,isAllErrored:!!r&&d.length===i.length,isAllPaused:0!==n.length&&l.length===n.length,isUploadInProgress:n.length>0,isSomeGhost:i.some(e=>e.isGhost)}}#I(e){for(const n of e)n.isRestriction?this.emit("restriction-failed",n.file,n):this.emit("error",n,n.file),this.log(n,"warning");const t=e.filter(e=>e.isUserFacing),r=t.slice(0,4),i=t.slice(4);r.forEach(({message:e,details:t=""})=>{this.info({message:e,details:t},"error",this.opts.infoTimeout)}),i.length>0&&this.info({message:this.i18n("additionalRestrictionsFailed",{count:i.length})})}validateRestrictions(e,t=this.getFiles()){try{this.#F.validate(t,[e])}catch(r){return r}return null}validateSingleFile(e){try{this.#F.validateSingleFile(e)}catch(t){return t.message}return null}validateAggregateRestrictions(e){const t=this.getFiles();try{this.#F.validateAggregateRestrictions(t,e)}catch(r){return r.message}return null}#N(e){const{missingFields:t,error:r}=this.#F.getMissingRequiredMetaFields(e);return t.length>0?(this.setFileState(e.id,{missingRequiredMetaFields:t,error:r.message}),this.log(r.message),this.emit("restriction-failed",e,r),!1):(0===t.length&&e.missingRequiredMetaFields&&this.setFileState(e.id,{missingRequiredMetaFields:[]}),!0)}#P(e){let t=!0;for(const r of Object.values(e))this.#N(r)||(t=!1);return t}#O(e){const{allowNewUpload:t}=this.getState();if(!1===t){const t=new ni(this.i18n("noMoreFilesAllowed"),{file:e});throw this.#I([t]),t}}checkIfFileAlreadyExists(e){const{files:t}=this.getState();return!(!t[e]||t[e].isGhost)}#A(e){const t=e instanceof File?{name:e.name,type:e.type,size:e.size,data:e,meta:{},isRemote:!1,source:void 0,preview:void 0}:e,r=Cr(t),i=function(e,t){return t.name?t.name:"image"===e.split("/")[0]?`${e.split("/")[0]}.${e.split("/")[1]}`:"noname"}(r,t),n=Sr(i).extension,o=function(e,t){if(function(e){return!(!e.isRemote||!e.remote)&&/* @__PURE__ */new Set(["box","dropbox","drive","facebook","unsplash"]).has(e.remote.provider)}(e))return e.id;const r=Cr(e);return function(e,t){let r=t||"uppy";return"string"==typeof e.name&&(r+=`-${Fr(e.name.toLowerCase())}`),void 0!==e.type&&(r+=`-${e.type}`),e.meta&&"string"==typeof e.meta.relativePath&&(r+=`-${Fr(e.meta.relativePath.toLowerCase())}`),void 0!==e.data?.size&&(r+=`-${e.data.size}`),void 0!==e.data.lastModified&&(r+=`-${e.data.lastModified}`),r}({...e,type:r},t)}(t,this.getID()),s={...t.meta,name:i,type:r},a=Number.isFinite(t.data.size)?t.data.size:null;return{source:t.source||"",id:o,name:i,extension:n||"",meta:{...this.getState().meta,...s},type:r,progress:{percentage:0,bytesUploaded:!1,bytesTotal:a,uploadComplete:!1,uploadStarted:null},size:a,isGhost:!1,...t.isRemote?{isRemote:!0,remote:t.remote,data:t.data}:{isRemote:!1,data:t.data},preview:t.preview}}#q(){this.opts.autoProceed&&!this.scheduledAutoProceed&&(this.scheduledAutoProceed=setTimeout(()=>{this.scheduledAutoProceed=null,this.upload().catch(e=>{e.isRestriction||this.log(e.stack||e.message||e)})},4))}#D(e){let{files:t}=this.getState(),r={...t};const i=[],n=[];for(const s of e)try{let e=this.#A(s);this.#O(e);const n=t[e.id],o=n?.isGhost;if(o&&!e.isRemote){if(null==e.data)throw new Error("File data is missing");e={...n,isGhost:!1,data:e.data},this.log(`Replaced the blob in the restored ghost file: ${e.name}, ${e.id}`)}const a=this.opts.onBeforeFileAdded(e,r);if(t=this.getState().files,r={...t,...r},!a&&this.checkIfFileAlreadyExists(e.id))throw new ni(this.i18n("noDuplicates",{fileName:e.name??this.i18n("unnamed")}),{file:e});if(!1===a&&!o)throw new ni("Cannot add the file because onBeforeFileAdded returned false.",{isUserFacing:!1,file:e});"object"==typeof a&&null!==a&&(e=a),this.#F.validateSingleFile(e),r[e.id]=e,i.push(e)}catch(o){n.push(o)}try{this.#F.validateAggregateRestrictions(Object.values(t),i)}catch(o){return n.push(o),{nextFilesState:t,validFilesToAdd:[],errors:n}}return{nextFilesState:r,validFilesToAdd:i,errors:n}}addFile(e){const{nextFilesState:t,validFilesToAdd:r,errors:i}=this.#D([e]),n=i.filter(e=>e.isRestriction);if(this.#I(n),i.length>0)throw i[0];this.setState({files:t});const[o]=r;return this.emit("file-added",o),this.emit("files-added",r),this.log(`Added file: ${o.name}, ${o.id}, mime type: ${o.type}`),this.#q(),o.id}addFiles(e){const{nextFilesState:t,validFilesToAdd:r,errors:i}=this.#D(e),n=i.filter(e=>e.isRestriction);this.#I(n);const o=i.filter(e=>!e.isRestriction);if(o.length>0){let e="Multiple errors occurred while adding files:\n";if(o.forEach(t=>{e+=`\n * ${t.message}`}),this.info({message:this.i18n("addBulkFilesFailed",{smart_count:o.length}),details:e},"error",this.opts.infoTimeout),"function"==typeof AggregateError)throw new AggregateError(o,e);{const t=new Error(e);throw t.errors=o,t}}this.setState({files:t}),r.forEach(e=>{this.emit("file-added",e)}),this.emit("files-added",r),r.length>5?this.log(`Added batch of ${r.length} files`):Object.values(r).forEach(e=>{this.log(`Added file: ${e.name}\n id: ${e.id}\n type: ${e.type}`)}),r.length>0&&this.#q()}removeFiles(e){const{files:t,currentUploads:r}=this.getState(),i={...t},n={...r},o=Object.create(null);function s(e){return void 0===o[e]}e.forEach(e=>{t[e]&&(o[e]=t[e],delete i[e])}),Object.keys(n).forEach(e=>{const t=r[e].fileIDs.filter(s);if(0===t.length)return void delete n[e];const{capabilities:i}=this.getState();if(t.length!==r[e].fileIDs.length&&!i.individualCancellation)throw new Error("The installed uploader plugin does not allow removing files during an upload.");n[e]={...r[e],fileIDs:t}});const a={currentUploads:n,files:i};0===Object.keys(i).length&&(a.allowNewUpload=!0,a.error=null,a.recoveredState=null),this.setState(a),this.#L();const l=Object.keys(o);l.forEach(e=>{this.emit("file-removed",o[e])}),l.length>5?this.log(`Removed ${l.length} files`):this.log(`Removed files: ${l.join(", ")}`)}removeFile(e){this.removeFiles([e])}pauseResume(e){if(!this.getState().capabilities.resumableUploads||this.getFile(e).progress.uploadComplete)return;const t=this.getFile(e),r=!t.isPaused;return this.setFileState(e,{isPaused:r}),this.emit("upload-pause",t,r),r}pauseAll(){const e={...this.getState().files};Object.keys(e).filter(t=>!e[t].progress.uploadComplete&&e[t].progress.uploadStarted).forEach(t=>{const r={...e[t],isPaused:!0};e[t]=r}),this.setState({files:e}),this.emit("pause-all")}resumeAll(){const e={...this.getState().files};Object.keys(e).filter(t=>!e[t].progress.uploadComplete&&e[t].progress.uploadStarted).forEach(t=>{const r={...e[t],isPaused:!1,error:null};e[t]=r}),this.setState({files:e}),this.emit("resume-all")}#z(){const{files:e}=this.getState();return Object.keys(e).filter(t=>{const r=e[t];return r.error&&(!r.missingRequiredMetaFields||0===r.missingRequiredMetaFields.length)})}async#j(){const e=this.#z(),t={...this.getState().files};if(e.forEach(e=>{t[e]={...t[e],isPaused:!1,error:null}}),this.setState({files:t,error:null}),this.emit("retry-all",this.getFilesByIds(e)),0===e.length)return{successful:[],failed:[]};const r=this.#$(e,{forceAllowNewUpload:!0});return this.#B(r)}async retryAll(){const e=await this.#j();return this.emit("complete",e),e}cancelAll(){this.emit("cancel-all");const{files:e}=this.getState(),t=Object.keys(e);t.length&&this.removeFiles(t),this.setState(Ei)}retryUpload(e){this.setFileState(e,{error:null,isPaused:!1}),this.emit("upload-retry",this.getFile(e));const t=this.#$([e],{forceAllowNewUpload:!0});return this.#B(t)}logout(){this.iteratePlugins(e=>{e.provider?.logout?.()})}#H=(e,t)=>{const r=e?this.getFile(e.id):void 0;if(null==e||!r)return void this.log(`Not setting progress for a file that has been removed: ${e?.id}`);if(100===r.progress.percentage)return void this.log(`Not setting progress for a file that has been already uploaded: ${e.id}`);const i={bytesTotal:t.bytesTotal,percentage:null!=t.bytesTotal&&Number.isFinite(t.bytesTotal)&&t.bytesTotal>0?Math.round(t.bytesUploaded/t.bytesTotal*100):void 0};null!=r.progress.uploadStarted?this.setFileState(e.id,{progress:{...r.progress,...i,bytesUploaded:t.bytesUploaded}}):this.setFileState(e.id,{progress:{...r.progress,...i}}),this.#L()};#V(){const e=this.#W();let t=null;null!=e&&(t=Math.round(100*e),t>100?t=100:t<0&&(t=0)),this.emit("progress",t??0),this.setState({totalProgress:t??0})}#L=(0,Fi.default)(()=>this.#V(),500,{leading:!0,trailing:!0});[Symbol.for("uppy test: updateTotalProgress")](){return this.#V()}#W(){const e=this.getFiles().filter(e=>e.progress.uploadStarted||e.progress.preprocess||e.progress.postprocess);if(0===e.length)return 0;if(e.every(e=>e.progress.uploadComplete))return 1;const t=e=>null!=e.progress.bytesTotal&&0!==e.progress.bytesTotal,r=e.filter(t),i=e.filter(e=>!t(e));if(r.every(e=>e.progress.uploadComplete)&&i.length>0&&!i.every(e=>e.progress.uploadComplete))return null;const n=r.reduce((e,t)=>e+(t.progress.bytesTotal??0),0),o=r.reduce((e,t)=>e+(t.progress.bytesUploaded||0),0);return 0===n?0:o/n}#R(){const e=(e,t,r)=>{let i=e.message||"Unknown error";e.details&&(i+=` ${e.details}`),this.setState({error:i}),null!=t&&t.id in this.getState().files&&this.setFileState(t.id,{error:i,response:r})};this.on("error",e),this.on("upload-error",(t,r,i)=>{if(e(r,t,i),"object"==typeof r&&r.message){this.log(r.message,"error");const e=new Error(this.i18n("failedToUpload",{file:t?.name??""}));e.isUserFacing=!0,e.details=r.message,r.details&&(e.details+=` ${r.details}`),this.#I([e])}else this.#I([r])});let t=null;this.on("upload-stalled",(e,r)=>{const{message:i}=e,n=r.map(e=>e.meta.name).join(", ");t||(this.info({message:i,details:n},"warning",this.opts.infoTimeout),t=setTimeout(()=>{t=null},this.opts.infoTimeout)),this.log(`${i} ${n}`.trim(),"warning")}),this.on("upload",()=>{this.setState({error:null})}),this.on("upload-start",e=>{const t=e.filter(e=>{const t=null!=e&&this.getFile(e.id);return t||this.log(`Not setting progress for a file that has been removed: ${e?.id}`),t}),r=Object.fromEntries(t.map(e=>[e.id,{progress:{uploadStarted:Date.now(),uploadComplete:!1,bytesUploaded:0,bytesTotal:e.size}}]));this.patchFilesState(r)}),this.on("upload-progress",this.#H),this.on("upload-success",(e,t)=>{if(null==e||!this.getFile(e.id))return void this.log(`Not setting progress for a file that has been removed: ${e?.id}`);const r=this.getFile(e.id).progress,i=this.#U.size>0;this.setFileState(e.id,{progress:{...r,postprocess:i?{mode:"indeterminate"}:void 0,uploadComplete:!0,...!i&&{complete:!0},percentage:100,bytesUploaded:r.bytesTotal},response:t,uploadURL:t.uploadURL,isPaused:!1}),null==e.size&&this.setFileState(e.id,{size:t.bytesUploaded||r.bytesTotal}),this.#L()}),this.on("preprocess-progress",(e,t)=>{null!=e&&this.getFile(e.id)?this.setFileState(e.id,{progress:{...this.getFile(e.id).progress,preprocess:t}}):this.log(`Not setting progress for a file that has been removed: ${e?.id}`)}),this.on("preprocess-complete",e=>{if(null==e||!this.getFile(e.id))return void this.log(`Not setting progress for a file that has been removed: ${e?.id}`);const t={...this.getState().files};t[e.id]={...t[e.id],progress:{...t[e.id].progress}},delete t[e.id].progress.preprocess,this.setState({files:t})}),this.on("postprocess-progress",(e,t)=>{null!=e&&this.getFile(e.id)?this.setFileState(e.id,{progress:{...this.getState().files[e.id].progress,postprocess:t}}):this.log(`Not setting progress for a file that has been removed: ${e?.id}`)}),this.on("postprocess-complete",e=>{const t=e&&this.getFile(e.id);if(null==t)return void this.log(`Not setting progress for a file that has been removed: ${e?.id}`);const{postprocess:r,...i}=t.progress;this.patchFilesState({[t.id]:{progress:{...i,complete:!0}}})}),this.on("restored",()=>{this.#L()}),this.on("dashboard:file-edit-complete",e=>{e&&this.#N(e)}),"undefined"!=typeof window&&window.addEventListener&&(window.addEventListener("online",this.#G),window.addEventListener("offline",this.#G),setTimeout(this.#G,3e3))}updateOnlineStatus(){window.navigator.onLine??!0?(this.emit("is-online"),this.wasOffline&&(this.emit("back-online"),this.info(this.i18n("connectedToInternet"),"success",3e3),this.wasOffline=!1)):(this.emit("is-offline"),this.info(this.i18n("noInternetConnection"),"error",0),this.wasOffline=!0)}#G=this.updateOnlineStatus.bind(this);getID(){return this.opts.id}use(e,...t){if("function"!=typeof e)throw new TypeError(`Expected a plugin class, but got ${null===e?"null":typeof e}. Please verify that the plugin was imported and spelled correctly.`);const r=new e(this,...t),i=r.id;if(!i)throw new Error("Your plugin must have an id");if(!r.type)throw new Error("Your plugin must have a type");const n=this.getPlugin(i);if(n){const e=`Already found a plugin named '${n.id}'. Tried to use: '${i}'.\nUppy plugins must have unique \`id\` options.`;throw new Error(e)}return e.VERSION&&this.log(`Using ${i} v${e.VERSION}`),r.type in this.#C?this.#C[r.type].push(r):this.#C[r.type]=[r],r.install(),this.emit("plugin-added",r),this}getPlugin(e){for(const t of Object.values(this.#C)){const r=t.find(t=>t.id===e);if(null!=r)return r}}[Symbol.for("uppy test: getPlugins")](e){return this.#C[e]}iteratePlugins(e){Object.values(this.#C).flat(1).forEach(e)}removePlugin(e){this.log(`Removing plugin ${e.id}`),this.emit("plugin-remove",e),e.uninstall&&e.uninstall();const t=this.#C[e.type],r=t.findIndex(t=>t.id===e.id);-1!==r&&t.splice(r,1);const i={plugins:{...this.getState().plugins,[e.id]:void 0}};this.setState(i)}destroy(){this.log(`Closing Uppy instance ${this.opts.id}: removing all files and uninstalling plugins`),this.cancelAll(),this.#M(),this.iteratePlugins(e=>{this.removePlugin(e)}),"undefined"!=typeof window&&window.removeEventListener&&(window.removeEventListener("online",this.#G),window.removeEventListener("offline",this.#G))}hideInfo(){const{info:e}=this.getState();this.setState({info:e.slice(1)}),this.emit("info-hidden")}info(e,t="info",r=3e3){const i="object"==typeof e;this.setState({info:[...this.getState().info,{type:t,message:i?e.message:e,details:i?e.details:null}]}),setTimeout(()=>this.hideInfo(),r),this.emit("info-visible")}log(e,t){const{logger:r}=this.opts;switch(t){case"error":r.error(e);break;case"warning":r.warn(e);break;default:r.debug(e)}}#X=/* @__PURE__ */new Map;registerRequestClient(e,t){this.#X.set(e,t)}getRequestClientForFile(e){if(!("remote"in e)||!e.remote)throw new Error(`Tried to get RequestClient for a non-remote file ${e.id}`);const t=this.#X.get(e.remote.requestClientId);if(null==t)throw new Error(`requestClientId "${e.remote.requestClientId}" not registered for file "${e.id}"`);return t}async restore(e){this.log(`Core: Running restored upload "${e}"`);const t=await this.#B(e);return this.emit("complete",t),t}#$(e,t={}){const{forceAllowNewUpload:r=!1}=t,{allowNewUpload:i,currentUploads:n}=this.getState();if(!i&&!r)throw new Error("Cannot create a new upload: already uploading.");const o=((e=21)=>{let t="",r=0|e;for(;r-- >0;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[64*Math.random()|0];return t})();return this.emit("upload",o,this.getFilesByIds(e)),this.setState({allowNewUpload:!1!==this.opts.allowMultipleUploadBatches&&!1!==this.opts.allowMultipleUploads,currentUploads:{...n,[o]:{fileIDs:e,step:0,result:{}}}}),o}[Symbol.for("uppy test: createUpload")](...e){return this.#$(...e)}#Y(e){const{currentUploads:t}=this.getState();return t[e]}addResultData(e,t){if(!this.#Y(e))return void this.log(`Not setting result for an upload that has been removed: ${e}`);const{currentUploads:r}=this.getState(),i={...r[e],result:{...r[e].result,...t}};this.setState({currentUploads:{...r,[e]:i}})}#K(e){const{[e]:t,...r}=this.getState().currentUploads;this.setState({currentUploads:r})}async#B(e){const t=()=>{const{currentUploads:t}=this.getState();return t[e]};let r=t();if(!r)throw new Error("Nonexistent upload");const i=[...this.#k,...this.#_,...this.#U];try{for(let n=r.step||0;n<i.length;n++){const o=i[n];this.setState({currentUploads:{...this.getState().currentUploads,[e]:{...r,step:n}}});const{fileIDs:s}=r;if(await o(s,e),r=t(),!r)break}}catch(o){throw this.#K(e),o}if(r){r.fileIDs.forEach(e=>{const t=this.getFile(e);t?.progress.postprocess&&this.emit("postprocess-complete",t)});const i=r.fileIDs.map(e=>this.getFile(e)),n=i.filter(e=>!e.error),o=i.filter(e=>e.error);this.addResultData(e,{successful:n,failed:o,uploadID:e}),r=t()}let n;return r&&(n=r.result,this.#K(e)),null==n&&(this.log(`Not setting result for an upload that has been removed: ${e}`),n={successful:[],failed:[],uploadID:e}),n}async upload(){this.#C.uploader?.length||this.log("No uploader type plugins are used","warning");let{files:e}=this.getState();if(this.#z().length>0){const t=await this.#j();if(!(this.getFiles().filter(e=>null==e.progress.uploadStarted).length>0))return this.emit("complete",t),t;({files:e}=this.getState())}const t=this.opts.onBeforeUpload(e);if(!1===t)throw new Error("Not starting the upload because onBeforeUpload returned false");t&&"object"==typeof t&&(e=t,this.setState({files:e}));try{if(this.#F.validateMinNumberOfFiles(e),!this.#P(e))throw new ni(this.i18n("missingRequiredMetaField"));const{currentUploads:t}=this.getState(),r=Object.values(t).flatMap(e=>e.fileIDs),i=Object.keys(e).filter(e=>{const t=this.getFile(e);return t&&!t.progress.uploadStarted&&!r.includes(e)}),n=this.#$(i),o=await this.#B(n);return this.emit("complete",o),o}catch(r){throw this.#I([r]),r}}};function _i({method:e="PUT",CanonicalUri:t="/",CanonicalQueryString:r="",SignedHeaders:i,HashedPayload:n}){const o=Object.keys(i).map(e=>e.toLowerCase()).sort();return[e,t,r,...o.map(e=>`${e}:${i[e]}`),"",o.join(";"),n].join("\n")}var Ui=new TextEncoder,Ri={name:"HMAC",hash:"SHA-256"};async function Ii(e){const{subtle:t}=globalThis.crypto;return t.digest(Ri.hash,Ui.encode(e))}function Ni(e){const t=new Uint8Array(e);let r="";for(let i=0;i<t.length;i++)r+=t[i].toString(16).padStart(2,"0");return r}async function Pi(e,t){const{subtle:r}=globalThis.crypto;return r.sign(Ri,await async function(e){const{subtle:t}=globalThis.crypto;return t.importKey("raw","string"==typeof e?Ui.encode(e):e,Ri,!1,["sign"])}(e),Ui.encode(t))}async function Oi({accountKey:e,accountSecret:t,sessionToken:r,bucketName:i,Key:n,Region:o,expires:s,uploadId:a,partNumber:l}){const c="s3",d=`${c}.${o}.amazonaws.com`,u=`/${i}/${encodeURI(n).replace(/[;?:@&=+$,#!'()*]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)}`,h="UNSIGNED-PAYLOAD",p=/* @__PURE__ */(new Date).toISOString().replace(/[-:]|\.\d+/g,""),m=p.slice(0,8),g=`${m}/${o}/${c}/aws4_request`,f=new URL(`https://${d}${u}`);f.searchParams.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),f.searchParams.set("X-Amz-Content-Sha256",h),f.searchParams.set("X-Amz-Credential",`${e}/${g}`),f.searchParams.set("X-Amz-Date",p),f.searchParams.set("X-Amz-Expires",s),f.searchParams.set("X-Amz-Security-Token",r),f.searchParams.set("X-Amz-SignedHeaders","host"),l&&f.searchParams.set("partNumber",l),a&&f.searchParams.set("uploadId",a),f.searchParams.set("x-id",l&&a?"UploadPart":"PutObject");const v=["AWS4-HMAC-SHA256",p,g,Ni(await Ii(_i({CanonicalUri:u,CanonicalQueryString:f.search.slice(1),SignedHeaders:{host:d},HashedPayload:h})))].join("\n"),y=Ni(await Pi(await Pi(await Pi(await Pi(await Pi(`AWS4${t}`,m),o),c),"aws4_request"),v));return f.searchParams.set("X-Amz-Signature",y),f}var Ai={getChunkSize:e=>Math.ceil(e.size/1e4),onProgress(){},onPartComplete(){},onSuccess(){},onError(e){throw e}},qi=Symbol("pausing upload, not an actual error"),Di=class{options;#Q=new vr;#J=[];#Z=[];#ee;#te;#re=!1;#ie;#ne;#oe;#se;#ae=e=>e?.cause===qi?null:this.#ie(e);#le=1e4;#ce=5242880;constructor(e,t){this.options={...Ai,...t},this.options.getChunkSize??=Ai.getChunkSize,this.#ee=e,this.#te=t.file,this.#ne=this.options.onSuccess,this.#ie=this.options.onError,this.#oe=this.options.shouldUseMultipart,this.#se=t.uploadId&&t.key,this.#de()}#de(){const e=this.#ee.size,t="function"==typeof this.#oe?this.#oe(this.#te):Boolean(this.#oe);if(t&&e>this.#ce){let r=Math.max(this.options.getChunkSize(this.#ee),this.#ce),i=Math.floor(e/r);i>this.#le&&(i=this.#le,r=e/this.#le),this.#J=Array(i);for(let n=0,o=0;n<e;n+=r,o++){const i=Math.min(e,n+r),s=()=>{const e=n;return this.#ee.slice(e,i)};if(this.#J[o]={getData:s,onProgress:this.#ue(o),onComplete:this.#he(o),shouldUseMultipart:t},this.#se){const t=n+r>e?e-n:r;this.#J[o].setAsUploaded=()=>{this.#J[o]=null,this.#Z[o].uploaded=t}}}}else this.#J=[{getData:()=>this.#ee,onProgress:this.#ue(0),onComplete:this.#he(0),shouldUseMultipart:t}];this.#Z=this.#J.map(()=>({uploaded:0}))}#$(){this.options.companionComm.uploadFile(this.#te,this.#J,this.#Q.signal).then(this.#ne,this.#ae),this.#re=!0}#pe(){this.options.companionComm.resumeUploadFile(this.#te,this.#J,this.#Q.signal).then(this.#ne,this.#ae)}#ue=e=>t=>{if(!t.lengthComputable)return;this.#Z[e].uploaded=function(e){if("string"==typeof e)return parseInt(e,10);if("number"==typeof e)return e;throw new TypeError("Expected a number")}(t.loaded);const r=this.#Z.reduce((e,t)=>e+t.uploaded,0);this.options.onProgress(r,this.#ee.size)};#he=e=>t=>{this.#J[e]=null,this.#Z[e].etag=t,this.#Z[e].done=!0;const r={PartNumber:e+1,ETag:t};this.options.onPartComplete(r)};#me(){this.#Q.abort(),this.options.companionComm.abortFileUpload(this.#te).catch(e=>this.options.log(e))}start(){this.#re?(this.#Q.signal.aborted||this.#Q.abort(qi),this.#Q=new vr,this.#pe()):this.#se?(this.options.companionComm.restoreUploadFile(this.#te,{uploadId:this.options.uploadId,key:this.options.key}),this.#pe()):this.#$()}pause(){this.#Q.abort(qi),this.#Q=new vr}abort(e){e?.really?this.#me():this.pause()}[Symbol.for("uppy test: getChunkState")](){return this.#Z}};function Li(e){if(e?.aborted)throw br("The operation was aborted",{cause:e.reason})}function zi(e){const t=new URL(e);return t.search="",t.hash="",t.href}var ji=class{#ge;#fe=/* @__PURE__ */new WeakMap;#ve;#ye;#be;#we;#xe;#Se;#Te;#Ce;#Fe;#Me;#Ee;constructor(e,t,r,i){this.#Se=e,this.#Fe=r,this.#Ee=i,this.setOptions(t)}setOptions(e){const t=this.#Se;"abortMultipartUpload"in e&&(this.#ge=t.wrapPromiseFunction(e.abortMultipartUpload,{priority:1})),"createMultipartUpload"in e&&(this.#ve=t.wrapPromiseFunction(e.createMultipartUpload,{priority:-1})),"signPart"in e&&(this.#ye=t.wrapPromiseFunction(e.signPart)),"listParts"in e&&(this.#we=t.wrapPromiseFunction(e.listParts)),"completeMultipartUpload"in e&&(this.#Ce=t.wrapPromiseFunction(e.completeMultipartUpload,{priority:1})),"retryDelays"in e&&(this.#Te=e.retryDelays??[]),"uploadPartBytes"in e&&(this.#Me=t.wrapPromiseFunction(e.uploadPartBytes,{priority:1/0})),"getUploadParameters"in e&&(this.#be=t.wrapPromiseFunction(e.getUploadParameters))}async#ke(e,t){const r=this.#Se,i=e?.source?.status;if(null==i)return!1;if(403===i&&"Request has expired"===e.message){if(!r.isPaused){if(1===r.limit||null==this.#xe){const e=t.next();if(null==e||e.done)return!1;this.#xe=e.value}r.rateLimit(0),await new Promise(e=>setTimeout(e,this.#xe))}}else if(429===i){if(!r.isPaused){const e=t.next();if(null==e||e.done)return!1;r.rateLimit(e.value)}}else{if(i>400&&i<500&&409!==i)return!1;if("undefined"!=typeof navigator&&!1===navigator.onLine)r.isPaused||(r.pause(),window.addEventListener("online",()=>{r.resume()},{once:!0}));else{const e=t.next();if(null==e||e.done)return!1;await new Promise(t=>setTimeout(t,e.value))}}return!0}async getUploadId(e,t){let r;for(;;){if(null==e.data)throw new Error("File data is empty");if(r=this.#fe.get(e.data),null==r)break;try{return await r}catch{}}const i=this.#ve(this.#Ee(e),t),n=()=>{if(null==e.data)throw new Error("File data is empty");i.abort(t.reason),this.#fe.delete(e.data)};return t.addEventListener("abort",n,{once:!0}),this.#fe.set(e.data,i),i.then(async r=>{if(t.removeEventListener("abort",n),this.#Fe(e,r),null==e.data)throw new Error("File data is empty");this.#fe.set(e.data,r)},()=>{if(t.removeEventListener("abort",n),null==e.data)throw new Error("File data is empty");this.#fe.delete(e.data)}),i}async abortFileUpload(e){if(null==e.data)throw new Error("File data is empty");const t=this.#fe.get(e.data);if(null==t)return;let r;this.#fe.delete(e.data),this.#Fe(e,Object.create(null));try{r=await t}catch{return}await this.#ge(this.#Ee(e),r)}async#_e(e,t,r){const{method:i="POST",url:n,fields:o,headers:s}=await this.#be(this.#Ee(e),{signal:r}).abortOn(r);let a;const l=t.getData();if("POST"===i.toUpperCase()){const e=new FormData;Object.entries(o).forEach(([t,r])=>e.set(t,r)),e.set("file",l),a=e}else a=l;const{onProgress:c,onComplete:d}=t,u=await this.#Me({signature:{url:n,headers:s,method:i},body:a,size:l.size,onProgress:c,onComplete:d,signal:r}).abortOn(r),h=o?.key;return this.#Fe(e,{key:h}),{...u,location:u.location??zi(n),bucket:o?.bucket,key:h}}async uploadFile(e,t,r){if(Li(r),1===t.length&&!t[0].shouldUseMultipart)return this.#_e(e,t[0],r);const{uploadId:i,key:n}=await this.getUploadId(e,r);Li(r);try{const o=await Promise.all(t.map((t,i)=>this.uploadChunk(e,i+1,t,r)));return Li(r),await this.#Ce(this.#Ee(e),{key:n,uploadId:i,parts:o,signal:r},r).abortOn(r)}catch(o){throw o?.cause!==qi&&"AbortError"!==o?.name&&this.abortFileUpload(e),o}}restoreUploadFile(e,t){if(null==e.data)throw new Error("File data is empty");this.#fe.set(e.data,t)}async resumeUploadFile(e,t,r){if(Li(r),1===t.length&&null!=t[0]&&!t[0].shouldUseMultipart)return this.#_e(e,t[0],r);const{uploadId:i,key:n}=await this.getUploadId(e,r);Li(r);const o=await this.#we(this.#Ee(e),{uploadId:i,key:n,signal:r},r).abortOn(r);Li(r);const s=await Promise.all(t.map((t,i)=>{const n=i+1,s=o.find(({PartNumber:e})=>e===n);return null==s?this.uploadChunk(e,n,t,r):(t?.setAsUploaded?.(),{PartNumber:n,ETag:s.ETag})}));return Li(r),this.#Ce(this.#Ee(e),{key:n,uploadId:i,parts:s,signal:r},r).abortOn(r)}async uploadChunk(e,t,r,i){Li(i);const{uploadId:n,key:o}=await this.getUploadId(e,i),s=this.#Te.values(),a=this.#Te.values(),l=()=>{const e=s.next();return null==e||e.done?null:e.value};for(;;){Li(i);const s=r.getData(),{onProgress:d,onComplete:u}=r;let h;try{h=await this.#ye(this.#Ee(e),{uploadId:n,key:o,partNumber:t,body:s,signal:i}).abortOn(i)}catch(c){const e=l();if(null==e||i.aborted)throw c;await new Promise(t=>setTimeout(t,e));continue}Li(i);try{return{PartNumber:t,...await this.#Me({signature:h,body:s,size:s.size,onProgress:d,onComplete:u,signal:i}).abortOn(i)}}catch(c){if(!(await this.#ke(c,a)))throw c}}}};function $i(e){if(e?.error){const t=new Error(e.message);throw Object.assign(t,e.error),t}return e}function Bi(e){const t=e.Expiration;if(t){const e=Math.floor((new Date(t)-Date.now())/1e3);if(e>9)return e}}function Hi({meta:e,allowedMetaFields:t,querify:r=!1}){const i=t??Object.keys(e);return e?Object.fromEntries(i.filter(t=>null!=e[t]).map(t=>[r?`metadata[${t}]`:t,String(e[t])])):{}}var Vi={allowedMetaFields:!0,limit:6,getTemporarySecurityCredentials:!1,shouldUseMultipart:e=>(e.size||0)>104857600,retryDelays:[0,1e3,3e3,5e3]},Wi=class e extends Xr{static VERSION="5.1.0";#Ue;#Re;requests;uploaderEvents;uploaders;constructor(t,r){super(t,{...Vi,uploadPartBytes:e.uploadPartBytes,createMultipartUpload:null,listParts:null,abortMultipartUpload:null,completeMultipartUpload:null,signPart:null,getUploadParameters:null,...r}),this.type="uploader",this.id=this.opts.id||"AwsS3Multipart",this.#Ie(r);const i={createMultipartUpload:this.createMultipartUpload,listParts:this.listParts,abortMultipartUpload:this.abortMultipartUpload,completeMultipartUpload:this.completeMultipartUpload,signPart:r?.getTemporarySecurityCredentials?this.createSignedURL:this.signPart,getUploadParameters:r?.getTemporarySecurityCredentials?this.createSignedURL:this.getUploadParameters};for(const e of Object.keys(i))null==this.opts[e]&&(this.opts[e]=i[e].bind(this));this.requests=this.opts.rateLimitedQueue??new Ur(this.opts.limit),this.#Ue=new ji(this.requests,this.opts,this.#Fe,this.#Ee),this.uploaders=Object.create(null),this.uploaderEvents=Object.create(null)}[Symbol.for("uppy test: getClient")](){return this.#Re}#Ie(e){null!=e&&("endpoint"in e||"companionUrl"in e||"headers"in e||"companionHeaders"in e||"cookiesRule"in e||"companionCookiesRule"in e)&&("companionUrl"in e&&!("endpoint"in e)&&this.uppy.log("`companionUrl` option has been removed in @uppy/aws-s3, use `endpoint` instead.","warning"),"companionHeaders"in e&&!("headers"in e)&&this.uppy.log("`companionHeaders` option has been removed in @uppy/aws-s3, use `headers` instead.","warning"),"companionCookiesRule"in e&&!("cookiesRule"in e)&&this.uppy.log("`companionCookiesRule` option has been removed in @uppy/aws-s3, use `cookiesRule` instead.","warning"),"endpoint"in e?this.#Re=new Gr(this.uppy,{pluginId:this.id,provider:"AWS",companionUrl:this.opts.endpoint,companionHeaders:this.opts.headers,companionCookiesRule:this.opts.cookiesRule}):("headers"in e&&this.#Ne(),"cookiesRule"in e&&(this.#Re.opts.companionCookiesRule=e.cookiesRule)))}setOptions(e){this.#Ue.setOptions(e),super.setOptions(e),this.#Ie(e)}resetUploaderReferences(e,t){this.uploaders[e]&&(this.uploaders[e].abort({really:t?.abort||!1}),this.uploaders[e]=null),this.uploaderEvents[e]&&(this.uploaderEvents[e].remove(),this.uploaderEvents[e]=null)}#Pe(e){if(!this.#Re)throw new Error(`Expected a \`endpoint\` option containing a URL, or if you are not using Companion, a custom \`${e}\` implementation.`)}createMultipartUpload(e,t){this.#Pe("createMultipartUpload"),Li(t);const r=Mr(this.opts.allowedMetaFields,e.meta),i=Hi({meta:e.meta,allowedMetaFields:r});return this.#Re.post("s3/multipart",{filename:e.name,type:e.type,metadata:i},{signal:t}).then($i)}listParts(e,{key:t,uploadId:r,signal:i},n){i??=n,this.#Pe("listParts"),Li(i);const o=encodeURIComponent(t);return this.#Re.get(`s3/multipart/${encodeURIComponent(r)}?key=${o}`,{signal:i}).then($i)}completeMultipartUpload(e,{key:t,uploadId:r,parts:i,signal:n},o){n??=o,this.#Pe("completeMultipartUpload"),Li(n);const s=encodeURIComponent(t),a=encodeURIComponent(r);return this.#Re.post(`s3/multipart/${a}/complete?key=${s}`,{parts:i.map(({ETag:e,PartNumber:t})=>({ETag:e,PartNumber:t}))},{signal:n}).then($i)}#Oe;async#Ae(e){if(Li(e?.signal),null==this.#Oe){const{getTemporarySecurityCredentials:t}=this.opts;!0===t?(this.#Pe("getTemporarySecurityCredentials"),this.#Oe=this.#Re.get("s3/sts",e).then($i)):this.#Oe=t(e),this.#Oe=await this.#Oe,setTimeout(()=>{this.#Oe=null},500*(Bi(this.#Oe.credentials)||0))}return this.#Oe}async createSignedURL(e,t){const r=await this.#Ae(t),i=Bi(r.credentials)||604800,{uploadId:n,key:o,partNumber:s}=t;return{method:"PUT",expires:i,fields:{},url:`${await Oi({accountKey:r.credentials.AccessKeyId,accountSecret:r.credentials.SecretAccessKey,sessionToken:r.credentials.SessionToken,expires:i,bucketName:r.bucket,Region:r.region,Key:o??`${crypto.randomUUID()}-${e.name}`,uploadId:n,partNumber:s})}`,headers:{"Content-Type":e.type}}}signPart(e,{uploadId:t,key:r,partNumber:i,signal:n}){if(this.#Pe("signPart"),Li(n),null==t||null==r||null==i)throw new Error("Cannot sign without a key, an uploadId, and a partNumber");const o=encodeURIComponent(r);return this.#Re.get(`s3/multipart/${encodeURIComponent(t)}/${i}?key=${o}`,{signal:n}).then($i)}abortMultipartUpload(e,{key:t,uploadId:r,signal:i}){this.#Pe("abortMultipartUpload");const n=encodeURIComponent(t),o=encodeURIComponent(r);return this.#Re.delete(`s3/multipart/${o}?key=${n}`,void 0,{signal:i}).then($i)}getUploadParameters(e,t){this.#Pe("getUploadParameters");const{meta:r}=e,{type:i,name:n}=r,o=Hi({meta:r,allowedMetaFields:Mr(this.opts.allowedMetaFields,e.meta),querify:!0}),s=new URLSearchParams({filename:n,type:i,...o});return this.#Re.get(`s3/params?${s}`,t)}static async uploadPartBytes({signature:{url:e,expires:t,headers:r,method:i="PUT"},body:n,size:o=n.size,onProgress:s,onComplete:a,signal:l}){if(Li(l),null==e)throw new Error("Cannot upload to an undefined URL");return new Promise((c,d)=>{const u=new XMLHttpRequest;function h(){u.abort()}function p(){l?.removeEventListener("abort",h)}u.open(i,e,!0),r&&Object.keys(r).forEach(e=>{u.setRequestHeader(e,r[e])}),u.responseType="text","number"==typeof t&&(u.timeout=1e3*t),l?.addEventListener("abort",h),u.upload.addEventListener("progress",e=>{s(e)}),u.addEventListener("abort",()=>{p(),d(br())}),u.addEventListener("timeout",()=>{p();const e=/* @__PURE__ */new Error("Request has expired");e.source={status:403},d(e)}),u.addEventListener("load",()=>{if(p(),403===u.status&&u.responseText.includes("<Message>Request has expired</Message>")){const e=/* @__PURE__ */new Error("Request has expired");return e.source=u,void d(e)}if(u.status<200||u.status>=300){const e=/* @__PURE__ */new Error("Non 2xx");return e.source=u,void d(e)}s?.({loaded:o,lengthComputable:!0});const e=u.getAllResponseHeaders().trim().split(/[\r\n]+/),t={__proto__:null};for(const i of e){const e=i.split(": ");t[e.shift()]=e.join(": ")}const{etag:r,location:n}=t;"POST"===i.toUpperCase()&&null==n&&console.error("@uppy/aws-s3: Could not read the Location header. This likely means CORS is not configured correctly on the S3 Bucket. See https://uppy.io/docs/aws-s3/#setting-up-your-s3-bucket"),null!=r?(a?.(r),c({...t,ETag:r})):console.error("@uppy/aws-s3: Could not read the ETag header. This likely means CORS is not configured correctly on the S3 Bucket. See https://uppy.io/docs/aws-s3/#setting-up-your-s3-bucket")}),u.addEventListener("error",e=>{p();const t=/* @__PURE__ */new Error("Unknown error");t.source=e.target,d(t)}),u.send(n)})}#Fe=(e,{key:t,uploadId:r})=>{const i=this.uppy.getFile(e.id);null!=i&&this.uppy.setFileState(e.id,{s3Multipart:{...i.s3Multipart,key:t,uploadId:r}})};#Ee=e=>this.uppy.getFile(e.id)||e;#qe(e){return new Promise((t,r)=>{if(null==e.data)throw new Error("File data is empty");const i=new Di(e.data,{companionComm:this.#Ue,log:(...e)=>this.uppy.log(...e),getChunkSize:this.opts.getChunkSize?this.opts.getChunkSize.bind(this):void 0,onProgress:(t,r)=>{const i=this.uppy.getFile(e.id);this.uppy.emit("upload-progress",i,{uploadStarted:i.progress.uploadStarted??0,bytesUploaded:t,bytesTotal:r})},onError:t=>{this.uppy.log(t),this.uppy.emit("upload-error",e,t),this.resetUploaderReferences(e.id),r(t)},onSuccess:r=>{const i={body:{...r},status:200,uploadURL:r.location};this.resetUploaderReferences(e.id),this.uppy.emit("upload-success",this.#Ee(e),i),r.location&&this.uppy.log(`Download ${e.name} from ${r.location}`),t(void 0)},onPartComplete:t=>{this.uppy.emit("s3-multipart:part-uploaded",this.#Ee(e),t)},file:e,shouldUseMultipart:this.opts.shouldUseMultipart,...e.s3Multipart});this.uploaders[e.id]=i;const n=new Yr(this.uppy);this.uploaderEvents[e.id]=n,n.onFileRemove(e.id,r=>{i.abort(),this.resetUploaderReferences(e.id,{abort:!0}),t(`upload ${r} was removed`)}),n.onCancelAll(e.id,()=>{i.abort(),this.resetUploaderReferences(e.id,{abort:!0}),t(`upload ${e.id} was canceled`)}),n.onFilePause(e.id,e=>{e?i.pause():i.start()}),n.onPauseAll(e.id,()=>{i.pause()}),n.onResumeAll(e.id,()=>{i.start()}),i.start()})}#De(e){return{..."remote"in e&&e.remote?.body,protocol:"s3-multipart",size:e.data.size,metadata:e.meta}}#Le=async e=>{if(0===e.length)return;const t=this.uppy.getFilesByIds(e).filter(e=>!(e=>"error"in e&&!!e.error)(e)&&!(e=>e.progress.uploadComplete)(e)),r=function(e){return e.filter(e=>!e.progress?.uploadStarted||!e.isRestored)}(t);this.uppy.emit("upload-start",r);const i=t.map(e=>{if(e.isRemote){const t=()=>this.requests;this.#ze(!1);const r=new AbortController,i=t=>{t.id===e.id&&r.abort()};this.uppy.on("file-removed",i);const n=this.uppy.getRequestClientForFile(e).uploadRemoteFile(e,this.#De(e),{signal:r.signal,getQueue:t});return this.requests.wrapSyncFunction(()=>{this.uppy.off("file-removed",i)},{priority:-1})(),n}return this.#qe(e)}),n=await Promise.allSettled(i);return this.#ze(!0),n};#Ne=()=>{this.#Re?.setCompanionHeaders(this.opts.headers)};#ze=e=>{const{capabilities:t}=this.uppy.getState();this.uppy.setState({capabilities:{...t,resumableUploads:e}})};#je=()=>{this.#ze(!0)};install(){this.#ze(!0),this.uppy.addPreProcessor(this.#Ne),this.uppy.addUploader(this.#Le),this.uppy.on("cancel-all",this.#je)}uninstall(){this.uppy.removePreProcessor(this.#Ne),this.uppy.removeUploader(this.#Le),this.uppy.off("cancel-all",this.#je)}},Gi="undefined"!=typeof window&&(window.indexedDB||window.webkitIndexedDB||window.mozIndexedDB||window.OIndexedDB||window.msIndexedDB),Xi=!!Gi,Yi="uppy-blobs",Ki="files",Qi=864e5,Ji=1048576;function Zi(e){const t=Gi.open(e,3);return new Promise((e,r)=>{t.onupgradeneeded=t=>{const r=t.target.result,i=t.currentTarget.transaction;if(t.oldVersion<2&&r.createObjectStore(Ki,{keyPath:"id"}).createIndex("store","store",{unique:!1}),t.oldVersion<3){const e=i.objectStore(Ki);e.createIndex("expires","expires",{unique:!1}),function(e){e.openCursor().onsuccess=e=>{const t=e.target.result;if(!t)return;const r=t.value;r.expires=Date.now()+Qi,t.update(r)}}(e)}i.oncomplete=()=>{e(r)}},t.onsuccess=t=>{e(t.target.result)},t.onerror=r})}function en(e){return new Promise((t,r)=>{e.onsuccess=e=>{t(e.target.result)},e.onerror=r})}var tn=!1,rn=class e{#$e;opts;name;static isSupported;constructor(t){this.opts={dbName:Yi,storeName:"default",expires:Qi,maxFileSize:10*Ji,maxTotalSize:300*Ji,...t},this.name=this.opts.storeName;const r=async()=>{const e=await Zi(this.opts.dbName);return this.#$e=e,e};tn?this.#$e=r():(tn=!0,this.#$e=e.cleanup().then(r,r))}get ready(){return Promise.resolve(this.#$e)}key(e){return`${this.name}!${e}`}async list(){const e=await en((await this.#$e).transaction([Ki],"readonly").objectStore(Ki).index("store").getAll(IDBKeyRange.only(this.name)));return Object.fromEntries(e.map(e=>[e.fileID,e.data]))}async get(e){const{data:t}=await en((await this.#$e).transaction([Ki],"readonly").objectStore(Ki).get(this.key(e)));return{id:t.fileID,data:t.data}}async getSize(){const e=(await this.#$e).transaction([Ki],"readonly").objectStore(Ki).index("store").openCursor(IDBKeyRange.only(this.name));return new Promise((t,r)=>{let i=0;e.onsuccess=e=>{const r=e.target.result;r?(i+=r.value.data.size,r.continue()):t(i)},e.onerror=()=>{r(/* @__PURE__ */new Error("Could not retrieve stored blobs size"))}})}async put(e){if(null!=e.data.size&&e.data.size>this.opts.maxFileSize)throw new Error("File is too big to store.");if(await this.getSize()>this.opts.maxTotalSize)throw new Error("No space left");return en((await this.#$e).transaction([Ki],"readwrite").objectStore(Ki).add({id:this.key(e.id),fileID:e.id,store:this.name,expires:Date.now()+this.opts.expires,data:e.data}))}async delete(e){return en((await this.#$e).transaction([Ki],"readwrite").objectStore(Ki).delete(this.key(e)))}static async cleanup(){const e=await Zi(Yi),t=e.transaction([Ki],"readwrite").objectStore(Ki).index("expires").openCursor(IDBKeyRange.upperBound(Date.now()));await new Promise((e,r)=>{t.onsuccess=t=>{const r=t.target.result;r?(r.delete(),r.continue()):e()},t.onerror=r}),e.close()}};function nn(e){try{return JSON.parse(e)}catch{return null}}rn.isSupported=Xi;var on="uppyState:",sn=class{opts;name;#Be;constructor(e){var t;this.opts={expires:864e5,throttleTime:500,...e},this.name=(t=e.storeName,`${on}${t}`),this.#Be=0===this.opts.throttleTime?this.save:(0,Fi.default)(this.save,this.opts.throttleTime,{leading:!0,trailing:!0})}#He;load=()=>{!function(){const e=[];for(let r=0;r<localStorage.length;r++){const t=localStorage.key(r);t?.startsWith(on)&&e.push(t)}const t=Date.now();e.forEach(e=>{const r=localStorage.getItem(e);if(!r)return;const i=nn(r);i?.expires&&i.expires<t&&localStorage.removeItem(e)})}();const e=localStorage.getItem(this.name);if(!e)return;const t=nn(e);return t?(this.#He=t,t.metadata):void 0};get=()=>this.#He?.metadata;save=()=>{if(null===this.#He)return void localStorage.removeItem(this.name);const e=JSON.stringify(this.#He);localStorage.setItem(this.name,e)};set=e=>{this.#He=null===e?null:{metadata:e,expires:Date.now()+this.opts.expires},this.#Be()}},an="undefined"!=typeof navigator&&"serviceWorker"in navigator,ln=class{#$e;name;static isSupported;constructor(e){this.#$e=new Promise((e,t)=>{an?navigator.serviceWorker.controller?e():navigator.serviceWorker.addEventListener("controllerchange",()=>{e()}):t(/* @__PURE__ */new Error("Unsupported"))}).then(e=>{this.#$e=e}),this.name=e.storeName}get ready(){return Promise.resolve(this.#$e)}async list(){return await this.#$e,new Promise((e,t)=>{const r=i=>{i.data.store===this.name&&("uppy/ALL_FILES"===i.data.type?(e(i.data.files),navigator.serviceWorker.removeEventListener("message",r)):t())};navigator.serviceWorker.addEventListener("message",r),navigator.serviceWorker.controller.postMessage({type:"uppy/GET_FILES",store:this.name})})}async put(e){await this.#$e,navigator.serviceWorker.controller.postMessage({type:"uppy/ADD_FILE",store:this.name,file:e})}async delete(e){await this.#$e,navigator.serviceWorker.controller.postMessage({type:"uppy/REMOVE_FILE",store:this.name,fileID:e})}};ln.isSupported=an;var cn={expires:864e5,serviceWorker:!1},dn=class e extends Xr{static VERSION="5.2.1";#Ve;#We;#Ge;static[Symbol.for("uppy test: throttleTime")];constructor(t,r){super(t,{...cn,...r}),this.type="debugger",this.id=this.opts.id||"GoldenRetriever",this.#Ve=new sn({expires:this.opts.expires,storeName:t.getID(),throttleTime:e[Symbol.for("uppy test: throttleTime")]??void 0}),this.opts.serviceWorker&&(this.#We=new ln({storeName:t.getID()})),this.#Ge=new rn({expires:this.opts.expires,...this.opts.indexedDB||{},storeName:t.getID()})}async#Xe(){const e=this.#Ve.load();if(!e)return;const t=e.currentUploads||{},r=Object.entries(e.files||{}),i=Object.fromEntries(r.every(([,e])=>e.progress.complete&&!e.error)?[]:r),n=Object.entries(i);this.uppy.log(`[GoldenRetriever] Recovered ${Object.keys(t).length} current uploads and ${n.length} files from Local Storage`);const o=n.length>0;o||this.uppy.log("[GoldenRetriever] No files need to be loaded, restored only processing state...");const[s,a]=await Promise.all([this.#Ye(),this.#Ke()]),l={...s,...a},c=Object.fromEntries(n.map(([e,t])=>{if(t.isRemote)return[e,{...t,isRestored:!0,data:{size:null}}];const r=l[e];return[e,t.progress.uploadComplete||null!=r?{...t,isRestored:!0,isGhost:!1,data:r}:{...t,isRestored:!0,isGhost:!0,data:void 0}]}));this.uppy.setState({recoveredState:o?e:null,currentUploads:o?t:{},files:c}),this.uppy.emit("restored",e.pluginData);const d=Object.keys(l).filter(e=>!i[e]);if(d.length)try{this.uppy.log(`[GoldenRetriever] Cleaning up ${d.length} old files`),await this.#Qe(d)}catch(u){this.uppy.log(`[GoldenRetriever] Could not clean up ${d.length} old files`,"warning"),this.uppy.log(u)}}#Je=({pluginData:e,...t})=>{const r=this.#Ve.get();this.#Ve.set({...r??{currentUploads:{},files:{}},...t,pluginData:{...r?.pluginData,...e}})};async#Ye(){if(!this.#We)return{};try{const e=await this.#We.list(),t=Object.keys(e).length;return this.uppy.log(t>0?`[GoldenRetriever] Successfully recovered ${t} blobs from Service Worker!`:"[GoldenRetriever] No blobs found in Service Worker"),e}catch(e){return this.uppy.log("[GoldenRetriever] Failed to recover blobs from Service Worker","warning"),this.uppy.log(e),{}}}async#Ke(){try{const e=await this.#Ge.list(),t=Object.keys(e).length;return this.uppy.log(t>0?`[GoldenRetriever] Successfully recovered ${t} blobs from IndexedDB!`:"[GoldenRetriever] No blobs found in IndexedDB"),e}catch(e){return this.uppy.log("[GoldenRetriever] Failed to recover blobs from IndexedDB","warning"),this.uppy.log(e),{}}}async#Qe(e){await Promise.all(e.map(async e=>{try{await Promise.all([this.#We?.delete(e),this.#Ge.delete(e)])}catch(t){this.uppy.log(`[GoldenRetriever] Could not remove file ${e} from all stores`,"warning"),this.uppy.log(t)}})),e.length>0&&this.uppy.log(`[GoldenRetriever] Removed ${e.length} blobs`)}async[Symbol.for("uppy test: deleteBlobs")](e){return this.#Qe(e)}#Ze=async e=>{const{id:t,data:r,isRemote:i}=e;i||null==r||await Promise.all([this.#We?.put({id:t,data:r}).catch(e=>{this.uppy.log("[GoldenRetriever] Could not store file in Service Worker","warning"),this.uppy.log(e)}),this.#Ge.put({id:t,data:r}).catch(e=>{e instanceof Event&&e.target instanceof IDBRequest&&"ConstraintError"===e.target.error?.name||(this.uppy.log("[GoldenRetriever] Could not store file in IndexedDB","warning"),this.uppy.log(e))})])};#et=(e,t,r)=>{if(t.currentUploads!==e.currentUploads){const{currentUploads:e}=this.uppy.getState();this.#Je({currentUploads:e})}if(t.files!==e.files){Object.values(e.files).some(e=>!e.progress.complete)&&(0===Object.values(t.files).length||Object.values(t.files).every(e=>e.progress.complete&&!e.error))&&(this.uppy.log("[GoldenRetriever] All files have been uploaded and processed successfully, clearing recovery state"),this.uppy.setState({recoveredState:null}));const r=Object.fromEntries(Object.entries(t.files).map(([e,{data:t,preview:r,...i}])=>[e,i]));this.#Je({files:r});const i=Object.values(t.files).filter(t=>null==e.files[t.id]),n=Object.values(t.files).flatMap(t=>{const r=e.files[t.id];return null!=r&&t.data!==r.data?[t]:[]}),o=[...Object.values(e.files).filter(e=>{const r=t.files[e.id];return null==r||r.progress.uploadComplete&&!e.progress.uploadComplete}),...n],s=[...i,...n];(async()=>{await this.#Qe(o.map(e=>e.id));for(const e of s)await this.#Ze(e);s.length>0&&this.uppy.log(`[GoldenRetriever] Added ${s.length} blobs`)})()}};#tt=()=>{this.uppy.log("[GoldenRetriever] Restore confirmed, proceeding...");const{currentUploads:e}=this.uppy.getState();Object.keys(e).length>0?(this.uppy.resumeAll(),Object.keys(e).forEach(e=>{this.uppy.restore(e)})):this.uppy.upload(),this.uppy.setState({recoveredState:null})};#rt=e=>{this.#Je({pluginData:e})};install(){this.#Xe(),this.uppy.on("state-update",this.#et),this.uppy.on("restore-confirmed",this.#tt),this.uppy.on("restore:plugin-data-changed",this.#rt)}uninstall(){this.uppy.off("state-update",this.#et),this.uppy.off("restore-confirmed",this.#tt),this.uppy.off("restore:plugin-data-changed",this.#rt)}},un=e=>408===e||429===e||e>=500,hn=(e,t)=>{if(e<400||e>=500||!t||"object"!=typeof t)return!1;const r=t;return[r.code,r.error,r.detail].some(e=>"upload_already_completed"===e||"Upload already completed"===e)},pn=(e,t)=>{m(t instanceof Error?t:new Error(String(t)),{component:"useUpload",tags:["upload",e,"cleanup"]})};async function mn(e,t,r,i,n){let o="complete failed";for(let a=0;a<3;a+=1){const l=new AbortController,c=()=>l.abort(n?.reason);n?.addEventListener("abort",c,{once:!0});const d=setTimeout(()=>l.abort(),15e3);try{const n=await fetch(T.UPLOAD_COMPLETE,{method:"POST",headers:i,signal:l.signal,body:JSON.stringify({contentId:e,key:t,clientUploadMs:r})});let s;try{s=await n.json()}catch{}if(n.ok||hn(n.status,s))return;if(o=s&&"object"==typeof s&&"string"==typeof s.error?`${s.error} (${n.status})`:`complete failed: ${n.status}`,!un(n.status))throw Object.assign(new Error(o),{retryable:!1,status:n.status})}catch(s){if(n?.aborted)throw s;if(o=s instanceof Error?s.message:String(s),!1===s.retryable)throw s}finally{clearTimeout(d),n?.removeEventListener("abort",c)}a<2&&await new Promise((e,t)=>{const r=setTimeout(e,250*2**a);n?.addEventListener("abort",()=>{clearTimeout(r),t(new DOMException("Aborted","AbortError"))},{once:!0})})}throw new Error(o)}function gn(){const e=Ye(),t=N(),r=_(null),n=_(null),o=_(null),s=o.current??=function(){let e=0;const t=/* @__PURE__ */new Map;return{beginSession:()=>++e,currentSession:()=>e,invalidate:()=>{e++},isCurrentSession:t=>t===e,registerFile:(e,r)=>{t.set(e,r)},getAttempt:e=>t.get(e),getAttempts:()=>Array.from(t.values()),removeFile:e=>{t.delete(e)},isCurrentFile:(r,i)=>{const n=t.get(r);return n?.session===e&&n.fileId===i},clearFiles:()=>{t.clear()}}}(),a=_(null),l=_(null),c=_({}),d=_({}),u=_(void 0),h=_({}),p=_(!1);i(()=>{const e=t.user;u.current=e?.id??(e?._id?String(e._id):void 0),h.current={organizationId:t.props?.organizationId,token:e?.token}},[t.user,t.props?.organizationId]);const g=R(()=>{const{organizationId:e,token:t}=h.current,r={"Content-Type":"application/json"};return e&&(r["x-org-id"]=e),t&&(r.Authorization=`Bearer ${t}`),r},[]),f=R(({contentId:e,key:t})=>e&&t?fetch(T.UPLOAD_ABORT,{signal:AbortSignal.timeout(15e3),method:"POST",headers:g(),body:JSON.stringify({contentId:e,key:t})}).then(e=>e.ok||410===e.status).catch(e=>(pn("abort",e),!1)):Promise.resolve(!0),[g]),v=R(()=>{if(!r.current){const t=new ki({autoProceed:!0}).use(dn,{id:"GoldenRetriever",expires:864e5,serviceWorker:!1}).use(Wi,{shouldUseMultipart:!1,getUploadParameters:async e=>{const t=e.meta;return{method:"PUT",url:t.uploadUrl,fields:{},headers:{"Content-Type":t.rawContentType??e.type??"application/octet-stream","If-None-Match":"*"}}}}),i=(t,r)=>{if(!t)return;const i=t.meta.uid;if(!s.isCurrentFile(i,t.id))return;e.getState().setUploadState(i,{status:"uploading",bytesUploaded:r.bytesUploaded??0,bytesTotal:r.bytesTotal??0});const o=Date.now(),a=Object.values(e.getState().uploadStates).reduce((e,t)=>e+(t.bytesUploaded||0),0),l=n.current;if(l){const t=(o-l.time)/1e3;if(t>=.5){const r=Math.max(0,(a-l.bytes)/t),i=l.speed>0?.7*l.speed+.3*r:r;n.current={time:o,bytes:a,speed:i},e.getState().setUploadSpeedBps(i)}}else n.current={time:o,bytes:a,speed:0}};t.on("upload-progress",i);const o=r=>{if(!r)return;const i=r.meta.uid,o=s.currentSession();if(!s.isCurrentFile(i,r.id))return;const a=r.meta.contentId,c=r.meta.key,d=r.meta.uploadStartedAt;(async()=>{try{if(await mn(a,c,d?Date.now()-d:void 0,g(),l.current?.signal),!s.isCurrentSession(o)||!s.isCurrentFile(i,r.id))return}catch(u){if(!s.isCurrentSession(o)||!s.isCurrentFile(i,r.id))return;return!1!==u.retryable&&t.setFileMeta(r.id,{completionPending:!0,completionContentId:a,completionKey:c}),e.getState().setUploadState(i,{status:"error",contentId:a,error:u instanceof Error?u.message:String(u)}),m(u instanceof Error?u:new Error(String(u)),{component:"useUpload",tags:["upload","complete"],level:403===u.status?"warning":"error",extra:{uid:i,contentId:a}}),void(a&&!1===u.retryable&&fetch(T.UPLOAD_FAIL,{method:"POST",headers:g(),body:JSON.stringify({contentId:a})}).catch(e=>pn("fail",e)))}if(s.isCurrentSession(o)&&s.isCurrentFile(i,r.id)){e.getState().setUploadState(i,{status:"success",contentId:a}),s.removeFile(i);try{t.removeFile(r.id)}catch{}if(Object.values(e.getState().uploadStates).every(e=>"success"===e.status||"error"===e.status)&&(n.current=null,e.getState().setUploadSpeedBps(0),!p.current)){p.current=!0;const t=Object.values(e.getState().uploadStates).filter(e=>"success"===e.status).length;t>0&&x.success(`${t} file${1===t?"":"s"} uploaded`)}}})()};t.on("upload-success",o);const c=(t,r)=>{if(!t)return;const i=t.meta.uid;if(!s.isCurrentFile(i,t.id))return;const o=t.meta.contentId;e.getState().setUploadState(i,{status:"error",error:r instanceof Error?r.message:String(r)}),o&&fetch(T.UPLOAD_FAIL,{method:"POST",headers:g(),body:JSON.stringify({contentId:o})}).catch(e=>pn("fail",e)),Object.values(e.getState().uploadStates).every(e=>"success"===e.status||"error"===e.status)&&(n.current=null,e.getState().setUploadSpeedBps(0))};t.on("upload-error",c);const d=s.currentSession(),h=()=>{if(!s.isCurrentSession(d))return;const{eventId:r}=e.getState(),i=[],n={},o={};t.getFiles().forEach(e=>{const a=e.meta,l=a.uid;if(!(l&&a.eventId===r&&a.userId===u.current&&"string"==typeof a.contentId&&"string"==typeof a.key&&"string"==typeof a.uploadUrl&&"string"==typeof a.rawContentType&&e.data instanceof Blob)){try{t.removeFile(e.id)}catch{}return}s.registerFile(l,{uid:l,fileId:e.id,session:s.currentSession(),contentId:"string"==typeof a.contentId?a.contentId:"",key:"string"==typeof a.key?a.key:""});const c=e.data instanceof File?e.data:new File([e.data],e.name,{type:e.type});i.push({uid:l,file:c}),"string"==typeof a.caption&&(n[l]=a.caption),o[l]={status:"uploading",bytesUploaded:e.progress?.bytesUploaded||0,bytesTotal:e.progress?.bytesTotal||e.size||0}}),0!==i.length&&s.isCurrentSession(d)&&e.setState(e=>({selectedFiles:[...e.selectedFiles,...i],originalFiles:{...e.originalFiles,...Object.fromEntries(i.map(({uid:e,file:t})=>[e,t]))},captions:{...e.captions,...n},uploadStates:{...e.uploadStates,...o},hasStarted:!0,showRestoreDialog:!0,restoredUids:i.map(e=>e.uid)}))};t.on("restored",h),a.current=()=>{"function"==typeof t.off&&(t.off("upload-progress",i),t.off("upload-success",o),t.off("upload-error",c),t.off("restored",h))},r.current=t}return r.current},[e,g,s]);i(()=>{v()},[g,v]);const y=R(async(t,r)=>{const{eventId:i,groupId:n,captions:o,originalFiles:a,trimRanges:c,cropSelections:h,activeFilters:p,showFilterChoice:y,skipUploadFilters:b,perFileFilterSkipped:w,filterOverrides:x}=e.getState();let S=a[t];if(!S)return!1;const C=v();try{if(S=await B(S),!s.isCurrentSession(r))return!1;e.getState().setUploadState(t,{status:"creating",bytesUploaded:0,bytesTotal:S.size,error:void 0});const a=L(S)?"VIDEO":"IMAGE",m=await $(S);if(!s.isCurrentSession(r))return!1;const v=d.current[t]??=await ge(()=>async function(e){try{return await(t=L(e)?function(e){return new Promise((t,r)=>{const i=URL.createObjectURL(e),n=document.createElement("video");n.muted=!0,n.playsInline=!0,n.preload="auto";let o=!1;const s=(e,s)=>{o||(o=!0,n.removeAttribute("src"),n.load(),URL.revokeObjectURL(i),e?t(e):r(s??/* @__PURE__ */new Error("video intrinsics failed")))};n.onloadedmetadata=()=>{try{n.currentTime=Math.min(.1,n.duration||.1)}catch{}},n.onseeked=()=>{const e=n.videoWidth,t=n.videoHeight,r={...e>0&&t>0&&{dimension:{width:e,height:t}},...Number.isFinite(n.duration)&&n.duration>0&&{duration:n.duration}};try{s({...r,...gr(n,e,t)})}catch(i){console.warn("[media-intrinsics] video frame sample failed:",i),s(r)}},n.onerror=()=>s(void 0,/* @__PURE__ */new Error("video load failed")),n.src=i})}(e):async function(e){const t=await B(e),r=await createImageBitmap(t);try{return{dimension:{width:r.width,height:r.height},...gr(r,r.width,r.height)}}finally{r.close()}}(e),new Promise((e,r)=>{const i=setTimeout(()=>r(/* @__PURE__ */new Error("intrinsics timeout")),8e3);t.then(t=>{clearTimeout(i),e(t)},e=>{clearTimeout(i),r(e)})}))}catch(r){return console.warn("[media-intrinsics] extraction failed:",r),{}}var t}(S));if(!s.isCurrentSession(r))return!1;const F=c[t],M=h[t],E=p.length>0?y&&(w[t]??b):void 0,k=await fetch(T.UPLOAD_CREATE,{method:"POST",headers:g(),signal:l.current?.signal,body:JSON.stringify({eventId:i,groupId:n,uid:t,type:a,fileName:S.name,fileSize:S.size,rawContentType:m,caption:o[t],trimInfo:F?{start:F.startTime,end:F.endTime}:void 0,cropInfo:M,dimension:v.dimension,blurhash:v.blurhash,colors:v.colors,duration:v.duration,filtersSkipped:E,filterOverrides:x[t]})});if(!k.ok){let e=`create failed: ${k.status}`;try{const t=await k.json();t.error&&(e=t.error)}catch{}throw new Error(e)}const{contentId:_,key:U,uploadUrl:R}=function(e){if(!(e&&"object"==typeof e&&"string"==typeof e.contentId&&"string"==typeof e.key&&"string"==typeof e.uploadUrl&&e.contentId&&e.key&&e.uploadUrl))throw new Error("create response missing upload identifiers");try{const t=new URL(e.uploadUrl);if("http:"!==t.protocol&&"https:"!==t.protocol)throw new Error("unsupported upload URL protocol")}catch{throw new Error("create response contains an invalid upload URL")}return e}(await k.json());if(!s.isCurrentSession(r))return f({contentId:_,key:U}),!1;const I=s.getAttempt(t)?.fileId;if(I&&C.getFile(I))try{C.removeFile(I)}catch{}const N=C.addFile({name:S.name,type:m,data:S,meta:{uid:t,userId:u.current,contentId:_,key:U,originalContentId:_,originalKey:U,uploadUrl:R,rawContentType:m,eventId:i,groupId:n,type:a,session:r,trimInfo:F?{start:F.startTime,end:F.endTime}:void 0,cropInfo:M,dimension:v.dimension,blurhash:v.blurhash,colors:v.colors,duration:v.duration,filtersSkipped:E,filterOverrides:x[t],completionPending:!1,caption:o[t],uploadStartedAt:Date.now()}});return s.registerFile(t,{uid:t,session:r,fileId:N,contentId:_,key:U}),!0}catch(F){return!s.isCurrentSession(r)||F instanceof DOMException&&"AbortError"===F.name||(e.getState().setUploadState(t,{status:"error",error:F instanceof Error?F.message:String(F)}),m(F instanceof Error?F:new Error(String(F)),{component:"useUpload",tags:["upload","create"],extra:{uid:t}})),!1}},[e,v,g,f,s]),b=R(async()=>{const{selectedFiles:t,oversizedUids:r}=e.getState(),i=t.filter(({uid:e})=>!r[e]);if(0===i.length)return;const n=s.getAttempts(),o=s.beginSession();n.forEach(f),s.clearFiles(),l.current=new AbortController;const a=v();e.getState().setHasStarted(!0),p.current=!1;for(const{uid:s}of i)e.getState().setUploadState(s,{status:"queued",bytesUploaded:0,bytesTotal:0});return await async function(e,t,r){const i=new Array(e.length);let n=0;const o=Array.from({length:Math.min(4,e.length)},async()=>{for(;n<e.length;){const t=n++;i[t]=await r(e[t])}});return await Promise.all(o),i}(i,0,({uid:e})=>y(e,o)),s.isCurrentSession(o)?0===a.getFiles().length?(x.error("Could not start upload. Please try again."),void e.getState().setHasStarted(!1)):void(await a.upload()):void 0},[e,v,y,f,s]),w=R(()=>{const t=s.getAttempts();s.invalidate(),l.current?.abort(),c.current={},n.current=null,s.clearFiles(),d.current={},r.current?.cancelAll(),t.forEach(f),e.getState().resetUploader()},[e,f,s]),S=R(async t=>{const r=v();n.current=null;const i=s.currentSession(),o=s.getAttempt(t);if(!o)return void(await y(t,i)&&await r.upload());const a=r.getFile(o.fileId);if(a){const i=a.meta,n=(c.current[t]??0)+1;if(c.current[t]=n,i.completionPending&&"string"==typeof i.completionContentId&&"string"==typeof i.completionKey)return void(await mn(i.completionContentId,i.completionKey,"number"==typeof i.uploadStartedAt?Date.now()-i.uploadStartedAt:void 0,g(),l.current?.signal).then(()=>{if((c.current[t]??0)===n){r.setFileMeta(o.fileId,{completionPending:!1}),e.getState().setUploadState(t,{status:"success",contentId:i.completionContentId}),s.removeFile(t);try{r.removeFile(o.fileId)}catch{}}}).catch(r=>{(c.current[t]??0)===n&&e.getState().setUploadState(t,{status:"error",error:r instanceof Error?r.message:String(r)})}));try{r.removeFile(o.fileId)}catch{}}e.getState().setUploadState(t,{status:"creating",error:void 0});const d=await f(o);s.isCurrentSession(i)&&(d?(s.removeFile(t),c.current[t]=(c.current[t]??0)+1,await y(t,i)&&await r.upload()):e.getState().setUploadState(t,{status:"error",error:"Could not reset upload. Please try again."}))},[v,y,f,g,s,e]),C=R(()=>{Object.entries(e.getState().uploadStates).filter(([,e])=>"error"===e.status).map(([e])=>e).forEach(e=>S(e))},[e,S]);return i(()=>()=>{const e=s.getAttempts();s.invalidate(),l.current?.abort(),a.current?.(),a.current=null,r.current?.cancelAll(),r.current?.destroy(),r.current=null,s.clearFiles(),e.forEach(f)},[f,s]),{startUpload:b,cancelUpload:w,retryUpload:S,retryAllUploads:C,resumeRestoredUpload:R(()=>{const{restoredUids:t}=e.getState();l.current=new AbortController,e.setState({showRestoreDialog:!1,restoredUids:[]}),Promise.all(t.map(e=>S(e)))},[e,S]),discardRestoredUpload:R(()=>{const t=v(),{restoredUids:r}=e.getState();r.forEach(r=>{const i=s.getAttempt(r);if(i){try{t.removeFile(i.fileId)}catch{}s.removeFile(r)}e.getState().removeFile(r)}),e.setState(e=>{const t={...e.uploadStates};return r.forEach(e=>delete t[e]),{showRestoreDialog:!1,restoredUids:[],uploadStates:t,hasStarted:0!==e.selectedFiles.length&&e.hasStarted}})},[e,v])}}function fn({eventSlug:e,event:t}){const r=N(),n=U(),a=r.props?.organizationId,l=r.user,h=Ye(),p=Xe(e=>e.selectedFiles),v=Xe(e=>e.hasStarted),y=Xe(e=>e.oversizedUids),b=Xe(e=>e.showOversizedModal),w=Xe(e=>e.activeFilters),S=Xe(e=>e.showFilterChoice),C=Xe(e=>e.skipUploadFilters),F=Xe(e=>e.showRestoreDialog),M=Xe(e=>e.restoredUids),[E,P]=I(!1),[O,A]=I(!1),[D,z]=I({}),[j,$]=I(!0),[B,V]=I(0),[W,G]=I(!1),X=Xe(e=>Object.values(e.uploadStates).filter(e=>"success"===e.status).length),Y=_(0);i(()=>{X>Y.current&&V(e=>e+1),Y.current=X},[X]),i(()=>{if(!l||!a)return;let t=!1;return 0===B?$(!0):G(!0),f.get(T.GET_UPLOAD_COUNT,{searchParams:{eventSlug:e},headers:{"x-org-id":a,...l.token?{Authorization:`Bearer ${l.token}`}:{}}}).json().then(e=>{t||z(e?.data?.uploadCount??{})}).catch(()=>{t||x.error("Failed to fetch upload count")}).finally(()=>{t||($(!1),G(!1))}),()=>{t=!0}},[l,a,e,B]);const K=!t.uploadLimit||t.uploadLimit<=0,Q=(D[d.APPROVED]??0)+(D[d.IN_REVIEW]??0),Z=K?1/0:Math.max(0,(t.uploadLimit??0)-Q),ee=j,te=K?"Unlimited":Z,re=Math.min(Z,100),ie=!(t.status===u.OPEN)||v||ee||W,de=t.enableVideo?[...se,...ae]:se,he=!!t.enableCaption,pe=function({effectiveFileLimit:e,eventSlug:t}){const r=Ye();return R(i=>{const n=r.getState();if(n.hasStarted)return;const a=e=>`${e.name}-${e.size}-${e.lastModified}`,l=n.selectedFiles,c=new Set(l.map(({file:e})=>a(e))),d=i.filter(e=>{const t=a(e);return!c.has(t)&&(c.add(t),!0)}).map(e=>({uid:ne(),file:e})),u=Math.max(0,e-l.length),h=d.slice(0,u),p=d.length-h.length;p>0&&(x.warn(`${p} file${p>1?"s":""} not added — you've reached your upload limit.`),o("Upload quota limit reached","warning",{component:"UploadPageClient",tags:["upload","quota"],extra:{eventSlug:t,dropped:p,effectiveFileLimit:e}}));const m={};h.forEach(({uid:e,file:t})=>{const r=function(e){const t=L(e),r=t?s:g;return e.size>r?t?"video":"image":void 0}(t);r&&(m[e]=r)}),Object.keys(m).length>0&&(r.getState().addOversizedUids(m),o("File size limit exceeded","warning",{component:"UploadPageClient",tags:["upload","file-size"],extra:{eventSlug:t,oversizedCount:Object.keys(m).length}}));const f={};h.forEach(({uid:e,file:t})=>{f[e]=t}),r.getState().addOriginalFiles(f),r.getState().setSelectedFiles([...l,...h]),h.forEach(({uid:e,file:t})=>{L(t)&&me(()=>{return e=t,new Promise(t=>{const r=URL.createObjectURL(e),i=document.createElement("video");i.preload="metadata";let n=!1;const o=e=>{n||(n=!0,clearTimeout(s),i.removeAttribute("src"),i.load(),URL.revokeObjectURL(r),t(e))},s=setTimeout(()=>o(0),1e4);i.onloadedmetadata=()=>o(i.duration),i.onerror=()=>o(0),i.src=r});var e}).then(t=>{t>60&&r.getState().setTrimRange(e,{startTime:0,endTime:60})}).catch(()=>{})})},[e,t,r])}({effectiveFileLimit:re,eventSlug:e}),{startUpload:ge,cancelUpload:fe,retryUpload:ve,retryAllUploads:ye,resumeRestoredUpload:be,discardRestoredUpload:we}=gn(),xe=R(()=>{A(!1),v?fe():h.getState().resetUploader()},[v,fe,h]);!function(e){const t=Ye(),r=N(),n=r.props?.organizationId,o=r.user?.token;i(()=>{if(!e||!n)return;let r=!1;return f.get(T.GET_POST_PROCESSING_SETTINGS,{searchParams:{eventId:e},headers:{"x-org-id":n,...o?{Authorization:`Bearer ${o}`}:{}}}).json().then(e=>{if(r||!e?.data)return;const i=e.data.filters??[],n=e.data.showChoice??!1;t.getState().setActiveFilters(i,n&&i.length>0)}).catch(e=>{m(e instanceof Error?e:/* @__PURE__ */new Error("Failed to load upload filters"),{component:"useUploadFilters",tags:["upload","filters"]})}),()=>{r=!0}},[e,n,o,t])}(t._id?String(t._id):void 0),i(()=>{const e={},t=t=>{Object.entries(t.uploadStates).forEach(([r,i])=>{"success"!==i.status||e[r]||t.selectedFiles.some(e=>e.uid===r)&&(e[r]=setTimeout(()=>{delete e[r],h.getState().removeFile(r)},3e3))})};t(h.getState());const r=h.subscribe(t);return()=>{r(),Object.values(e).forEach(clearTimeout)}},[h]),i(()=>{0===p.length&&v&&h.getState().resetUploader()},[p.length,v,h]);const Se=Object.values(Xe(e=>e.uploadStates)).some(e=>"queued"===e.status||"creating"===e.status||"uploading"===e.status);i(()=>{if(!v||!Se)return;const e=e=>{e.preventDefault()};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[v,Se]);const Te=R(e=>h.getState().removeFile(e),[h]),Ce=R(()=>{Object.keys(h.getState().oversizedUids).length>0?h.getState().setShowOversizedModal(!0):ge()},[h,ge]),Fe=R(()=>{!l||l.tcAccepted?Ce():P(!0)},[l,Ce]),Me=R(()=>{h.getState().removeOversizedFiles(),ge()},[h,ge]),[Ee,ke]=I(!1),_e=_(0),Ue=ie||p.length>=re,Re=R(e=>{if(e.preventDefault(),_e.current=0,ke(!1),Ue)return;const t=e.dataTransfer?.files;t&&t.length>0&&pe(Ft(Array.from(t),de))},[Ue,pe,de]);/* @__PURE__ */
76
+ return k("div",{className:"bg-background relative min-h-screen px-3 pb-9 lg:px-0",onDragEnter:e=>{e.preventDefault(),Ue||(_e.current+=1,ke(!0))},onDragOver:e=>e.preventDefault(),onDragLeave:()=>{_e.current=Math.max(0,_e.current-1),0===_e.current&&ke(!1)},onDrop:Re,children:[Ee&&/* @__PURE__ */k("div",{className:"border-primary bg-background/90 fixed inset-0 z-2003 flex items-center justify-center border-4 border-dashed",children:/* @__PURE__ */k("p",{className:"text-primary text-2xl font-semibold",children:"Drop to add files"})}),
77
+ /* @__PURE__ */k("div",{className:"mx-auto max-w-4xl space-y-6",children:[
78
+ /* @__PURE__ */k(Ut,{uploadDisabled:ie,eventName:t.name,isQuotaLoading:ee,remainingUploads:te}),!t.enableVideo&&/* @__PURE__ */k("div",{className:"mx-auto max-w-lg rounded border border-blue-500/20 bg-blue-500/10 p-3 text-center text-sm font-medium text-blue-600 dark:text-blue-400",children:"Video upload turned off by event admin"}),0===p.length&&!v&&/* @__PURE__ */k(Et,{enabledFileTypes:de,disabled:ie,onFileSelect:pe,selectedCount:p.length,maxCount:re,enableVideo:t.enableVideo})]}),p.length>0&&/* @__PURE__ */k("div",{className:"mx-auto mt-8 w-full max-w-full pb-36 sm:px-0 md:pb-24",children:[S&&w.length>0&&!v&&/* @__PURE__ */k("div",{className:"border-border bg-card mb-4 flex items-center gap-3 rounded-lg border p-3",children:[/* @__PURE__ */k(oe,{checked:!C,onChange:e=>{h.getState().setSkipUploadFilters(!e);const t={};e||p.forEach(({uid:e})=>{t[e]=!0}),h.setState({perFileFilterSkipped:t})},label:"Apply filters"}),/* @__PURE__ */k("span",{className:"text-muted-foreground -ml-1 text-sm",children:"— upload with filters applied"})]}),
79
+ /* @__PURE__ */k("div",{className:"flex items-center justify-between py-2",children:[/* @__PURE__ */k("p",{className:"text-muted-foreground text-sm font-medium",children:[p.length," selected"]}),!v&&p.length<re&&/* @__PURE__ */k(_t,{enabledFileTypes:de,disabled:ie,onFileSelect:pe})]}),
80
+ /* @__PURE__ */k("div",{className:"grid grid-cols-1 gap-4 py-4 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4",children:p.map(({uid:e,file:t})=>/* @__PURE__ */k(St,{uid:e,file:t,onRemove:Te,disabled:v,showCaption:he,onRetry:ve},e))}),!v&&p.length<re&&/* @__PURE__ */k(kt,{enabledFileTypes:de,disabled:ie,onFileSelect:pe}),!v&&/* @__PURE__ */k(q,{className:"mt-2 w-full gap-2",onClick:Fe,disabled:ie||0===p.length,children:[/* @__PURE__ */k(H,{className:"size-4"}),"Upload"]}),
81
+ /* @__PURE__ */k(Ct,{selectedCount:p.length,onUpload:Fe,onCancel:()=>A(!0),onRetryAll:ye,uploadDisabled:ie||0===p.length})]}),!v&&/* @__PURE__ */k("div",{className:"mx-auto mt-12 max-w-4xl text-center",children:/* @__PURE__ */k(q,{onClick:()=>n(c.GALLERY(e)),children:"View gallery"})}),
82
+ /* @__PURE__ */k(le,{open:b,oversizedUids:y,onClose:()=>h.getState().setShowOversizedModal(!1),onRemoveAndUpload:Me}),
83
+ /* @__PURE__ */k(ce,{open:F,count:M.length,onResume:be,onDiscard:we}),
84
+ /* @__PURE__ */k(J,{open:O,onOpenChange:A,title:"Cancel upload?",description:v?"Active uploads will be stopped and any in-progress files may be lost.":"Your selected files will be cleared.",cancelText:"Keep uploading",confirmText:v?"Stop upload":"Clear selection",confirmColor:"error",onCancel:()=>A(!1),onConfirm:xe}),
85
+ /* @__PURE__ */k(ue,{open:E,onClose:()=>P(!1),onSuccess:()=>{P(!1),Ce()}})]})}var vn=()=>{const{eventSlug:e}=O(),t=y(),r=U(),{loadingUser:n,user:o}=N();i(()=>{n||o||r("/auth/login",{state:{referrer:t.pathname},replace:!0})},[n,o]);const{loading:s,event:a}=E({eventSlug:e}),l=_(ne());return s||a&&a.status!==u.CLOSED?/* @__PURE__ */k("div",a&&e?{className:"bg-background mx-auto min-h-screen pt-16",children:/* @__PURE__ */k(Ge,{eventId:String(a._id),groupId:l.current,children:/* @__PURE__ */k(fn,{eventSlug:e,event:a})})}:{className:"bg-background min-h-screen"}):/* @__PURE__ */k("div",{className:"bg-background mx-auto min-h-[80] pt-16 pb-36",children:/* @__PURE__ */k(he,{eventSlug:e,locationState:t?.state})})};export{vn as default};