@qratilabs/qrati-connect 2.31.2 → 2.32.1

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 (101) hide show
  1. package/element/704flhtG2.js +3 -0
  2. package/element/B4vKIcyS.js +2 -0
  3. package/element/{DMnbtDXS2.js → B5343djA.js} +1 -1
  4. package/element/BDe40W9d.js +16 -0
  5. package/element/{D1eaRhKY2.js → BE8OExtb.js} +3 -3
  6. package/element/BEljxaTQ2.js +1 -0
  7. package/element/BGkRue2Y2.js +14 -0
  8. package/element/BNljt5mO.js +4 -0
  9. package/element/BOJyFCIG.js +5 -0
  10. package/element/{BWjYmdOz2.js → BPGLsT1I.js} +7 -7
  11. package/element/{BNaRcekR2.js → BSdyruRZ.js} +1 -1
  12. package/element/BTWlllUg.js +2 -0
  13. package/element/BTduHo9u.js +199 -0
  14. package/element/{fQmLbYcp2.js → BfwZT31v.js} +1 -1
  15. package/element/BhoJSelw.js +2 -0
  16. package/element/{BaYMN8qa2.js → Bl8aWOla.js} +93 -93
  17. package/element/BtutZVbU.js +1 -0
  18. package/element/Bu-K2ipV.js +1 -0
  19. package/element/ByZt8Ha92.js +4 -0
  20. package/element/C41v7XyB.js +8 -0
  21. package/element/CKRLHPry.js +32 -0
  22. package/element/CMowDGuy2.js +8 -0
  23. package/element/{D2-DJv4T2.js → CV_RNBLv2.js} +1 -1
  24. package/element/CgFrSWMh.js +3 -0
  25. package/element/CkdxwEVw2.js +17 -0
  26. package/element/D-2JtKSL2.js +3 -0
  27. package/element/D0IYqyql.js +1 -0
  28. package/element/{7IEzYICH2.js → D7LeFN00.js} +24 -24
  29. package/element/DChfs6i_.js +2 -0
  30. package/element/DE9tQHM5.js +36 -0
  31. package/element/{V_pvG6Pc.js → DSORGFbF2.js} +85 -85
  32. package/element/D_F9CJK92.js +4 -0
  33. package/element/Da21-kaH2.js +5 -0
  34. package/element/{BXUp7Zp4.js → DdtKpY372.js} +7 -7
  35. package/element/DgX9Hgrs.js +1 -0
  36. package/element/Dip0ObTA2.js +8 -0
  37. package/element/{Ot24jlyb2.js → DqB6Xl6G.js} +1 -1
  38. package/element/RnyYX1t12.js +8 -0
  39. package/element/ZJzxZBJ5.js +2 -0
  40. package/element/lFDEfCSm.js +1 -0
  41. package/element/web.es.js +1 -48
  42. package/embed/embed.js +1 -1
  43. package/package.json +2 -2
  44. package/element/5r_0x4aK.js +0 -3
  45. package/element/ASQv5Ahv.js +0 -4
  46. package/element/BCmdnJKF.js +0 -1
  47. package/element/BOs_rBYA.js +0 -2
  48. package/element/BWKUiudT.js +0 -2
  49. package/element/BXMw4kNf.js +0 -1
  50. package/element/BYM2GyVF2.js +0 -1
  51. package/element/B_SYJsyF2.js +0 -3
  52. package/element/Bb9ydqSB.js +0 -1
  53. package/element/Bc-phiG6.js +0 -4
  54. package/element/BkIDQGIs.js +0 -1
  55. package/element/Bki5T_lb.js +0 -1
  56. package/element/BpAijsfn.js +0 -3
  57. package/element/Bq48A0Iv.js +0 -1
  58. package/element/BszsxRY6.js +0 -1
  59. package/element/Bvc6t1Gu.js +0 -1
  60. package/element/BxZobjC-.js +0 -2
  61. package/element/C0eP2utz.js +0 -2
  62. package/element/C2WFktw12.js +0 -3
  63. package/element/CDSgxlAB.js +0 -1
  64. package/element/CFRIlHtK2.js +0 -5
  65. package/element/CHYm7f-K2.js +0 -2
  66. package/element/CIcQE2CN2.js +0 -1
  67. package/element/CJ_l5BYI.js +0 -1
  68. package/element/CNyy8GGA.js +0 -7
  69. package/element/CQJ3AK1w.js +0 -1
  70. package/element/CTikdrXC.js +0 -80
  71. package/element/CV7KmbT-.js +0 -17
  72. package/element/CYGIt75r2.js +0 -39
  73. package/element/Cj_TL6Ks2.js +0 -36
  74. package/element/CkBayeWW.js +0 -11
  75. package/element/D54cshAo.js +0 -8
  76. package/element/D5Ja4Yts.js +0 -1
  77. package/element/DJMlQk40.js +0 -8
  78. package/element/DTPNRhMK.js +0 -8
  79. package/element/DWwbkxCM2.js +0 -16
  80. package/element/DXjc6xIy.js +0 -2
  81. package/element/DeK1vU3V2.js +0 -1
  82. package/element/Dl6jcv9I.js +0 -5
  83. package/element/DmpmrPE5.js +0 -1
  84. package/element/Do4y0nPe.js +0 -1
  85. package/element/Dpwx5KMy.js +0 -41
  86. package/element/Dstt_bTH.js +0 -2
  87. package/element/JY9kGm742.js +0 -2
  88. package/element/L4hWU3Nc.js +0 -1
  89. package/element/Te9ieH1R2.js +0 -1
  90. package/element/Z3MoLpu5.js +0 -5
  91. package/element/a_rT1I0D.js +0 -8
  92. package/element/erXAfWWY.js +0 -3
  93. package/element/rlutojb0.js +0 -1
  94. package/element/tbcqJrU_2.js +0 -9
  95. package/element/xPoQq2aN2.js +0 -14
  96. /package/element/{1dmOpMwn2.js → 1dmOpMwn.js} +0 -0
  97. /package/element/{BUDCYszs.js → BUDCYszs2.js} +0 -0
  98. /package/element/{Bo39kG4k2.js → Bo39kG4k.js} +0 -0
  99. /package/element/{CfMNBPpx.js → CfMNBPpx2.js} +0 -0
  100. /package/element/{CtxIOzTC2.js → CtxIOzTC.js} +0 -0
  101. /package/element/{DnIueBGr.js → DnIueBGr2.js} +0 -0
@@ -1,85 +1,85 @@
1
- import{r as e,t}from"./DdACKOZr.js";import{E as r,_ as i,c as n,d as o,f as s,g as a,h as l,o as d,p as c,s as u,t as h,v as p,y as m}from"./BXMw4kNf.js";import{c as g,i as f,n as v,s as b}from"./Dpwx5KMy.js";import{t as y}from"./DmpmrPE5.js";import{b as w,i as x,p as S,s as T,x as C,y as F}from"./Bb9ydqSB.js";import{d as k,l as E,n as _,u as M}from"./Z3MoLpu5.js";import{t as U}from"./BszsxRY6.js";import{t as R}from"./Dl6jcv9I.js";import{t as I}from"./BkIDQGIs.js";import{t as P}from"./C0eP2utz.js";import{n as O}from"./Bq48A0Iv.js";import{r as N}from"./JY9kGm742.js";import{t as A}from"./Te9ieH1R2.js";import{t as q}from"./BWjYmdOz2.js";import{a as D,c as L,i as j,o as z,r as $,s as B,t as H}from"./C2WFktw12.js";import{a as V,i as W,n as G,o as X,r as Y,t as K}from"./CHYm7f-K2.js";import{t as Q}from"./DMnbtDXS2.js";import{i as J,n as Z,r as ee,t as te}from"./BXUp7Zp4.js";var re=[];for(let mn=0;mn<256;++mn)re.push((mn+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:n,className:o,disabled:s}){const l=e??t??!1,d=l?"checked":"unchecked",c=a();/* @__PURE__ */
2
- return h("label",{htmlFor:c,className:f("flex items-center gap-2",s&&"cursor-not-allowed opacity-50",!s&&"cursor-pointer"),children:[/* @__PURE__ */h("button",{type:"button",id:c,role:"switch","aria-checked":l,disabled:s,"data-state":d,onBlur:i,onClick:()=>!s&&r?.(!l),className:f("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",!s&&"cursor-pointer",o),children:/* @__PURE__ */h("span",{"data-state":d,style:{transform:l?"translateX(1.25rem)":"translateX(0)"},className:f("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")})}),n&&/* @__PURE__ */h("span",{className:"text-sm font-medium",children:n})]})}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__ */h(K,{open:e,onOpenChange:e=>!e&&r(),children:/* @__PURE__ */h(G,{children:[/* @__PURE__ */h(V,{children:[/* @__PURE__ */h(X,{children:"Some files are too large"}),/* @__PURE__ */h(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__ */h(W,{children:/* @__PURE__ */h(q,{onClick:i,children:"Remove and Upload"})})]})})}function de({open:e,count:t,onResume:r,onDiscard:i}){/* @__PURE__ */
3
- return h(K,{open:e,onOpenChange:e=>!e&&i(),children:/* @__PURE__ */h(G,{children:[/* @__PURE__ */h(V,{children:[/* @__PURE__ */h(X,{children:"Resume your upload?"}),/* @__PURE__ */h(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__ */h(W,{children:[/* @__PURE__ */h(q,{variant:"outlined",onClick:i,children:"Remove All"}),/* @__PURE__ */h(q,{onClick:r,children:"Resume"})]})]})})}var ce=["6a385dabb04f4d8783b14fe1","69ada0f82889f080a9ca53df"],ue=({open:e,onClose:t,onSuccess:r})=>{const{t:i}=N(),[n,o]=l(!1),s=v(),a=s.props?.organizationId??s.organization?._id,{user:d,updateUser:c}=s,u=!!a&&ce.includes(a.trim()),p=u?"https://qrati.com/terms-of-use-wedding-private-events":"https://qrati.com/terms-of-use",m=u?"https://qrati.com/privacy-policy-wedding-private-events":"https://qrati.com/privacy-policy";/* @__PURE__ */
4
- return h(K,{open:e,onOpenChange:e=>!e&&t(),children:/* @__PURE__ */h(G,{className:"text-foreground",children:/* @__PURE__ */h("div",{className:"mx-auto max-w-sm p-4 text-center sm:max-w-lg",children:[
5
- /* @__PURE__ */h(X,{children:i("upload.terms_title","Terms & Conditions")}),
6
- /* @__PURE__ */h(Y,{hidden:!0,children:i("upload.terms_description","Please accept our terms to proceed")}),
7
- /* @__PURE__ */h("div",{className:"mt-4 mb-6",children:/* @__PURE__ */h("p",{className:"bg-background text-foreground text-base",children:[i("upload.terms_prompt","I agree to the")," ",
8
- /* @__PURE__ */h("a",{href:p,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__ */h("a",{href:m,className:"text-info inline-flex items-center gap-1 underline",target:"_blank",rel:"noopener noreferrer",children:i("upload.privacy_policy","Privacy Policy")})," "]})}),
10
- /* @__PURE__ */h(q,{fullWidth:!0,color:"success",disabled:n,loading:n,onClick:async()=>{o(!0);try{const e=await y.post(x.ACCEPT_TERMS,{headers:{"x-org-id":a,Authorization:d?.token?`Bearer ${d.token}`:void 0}}).json();if(e.error)throw new Error(e.error);await c({tcAccepted:!0}),o(!1),r()}catch(e){b(e instanceof Error?e:new Error(String(e)),{component:"TermsAndConditionsModal",tags:["upload","terms-accept"]}),O.error(i("upload.accept_failed","Failed to accept terms"))}o(!1)},children:i("button.accept","Accept")})]})})})},he=({eventSlug:e,locationState:t})=>{const{t:r}=N(),i=e?C.GALLERY(e):C.PUBLIC_EVENTS;/* @__PURE__ */
11
- return h("div",{className:"mx-auto mt-24 w-fit max-w-xl space-y-8",children:[
12
- /* @__PURE__ */h(U,{variant:"h3",align:"center",children:r("upload.event_closed","Upload Closed")}),
13
- /* @__PURE__ */h(U,{variant:"h5",align:"center",color:"muted",children:r("upload.closed_description","This event is no longer accepting uploads.")}),
14
- /* @__PURE__ */h("div",{className:"flex flex-row justify-end",children:/* @__PURE__ */h(_,{to:i,state:t,children:/* @__PURE__ */h(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,d,c,u,h,p,m,g,f,v,b,y){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],k=x[F+3];C[F]=Math.min(255,Math.max(0,Math.round(e*w+t*S+r*T+i*k+255*n))),C[F+1]=Math.min(255,Math.max(0,Math.round(o*w+s*S+a*T+l*k+255*d))),C[F+2]=Math.min(255,Math.max(0,Math.round(c*w+u*S+h*T+p*k+255*m))),C[F+3]=Math.min(255,Math.max(0,Math.round(g*w+f*S+v*T+b*k+255*y)))}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 be(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 ye="\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),d=/* @__PURE__ */new Int32Array(256);let c=0,u=0,h=0;for(let I=0;I<e.length;I+=4)c+=e[I],u+=e[I+1],h+=e[I+2];const p=c/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){v=60;break}}const b=f+n;for(let I=0;I<e.length;I+=4){const t=ve(e[I],e[I+1],e[I+2],b);a[Math.min(255,Math.max(0,Math.round(t.r+t.g+t.b)))]++,l[e[I+1]]++,d[e[I+2]]++}const y=[0],w=[0],x=[0];for(let I=0;I<256;I++)a[I]-s<2&&y.push(I),l[I]-s<2&&w.push(I),d[I]-s<2&&x.push(I);y.push(255),w.push(255),x.push(255);const S=be(y),T=be(w),C=be(x),F=256/Math.max(1,S.high-S.low),k=256/Math.max(1,T.high-T.low),E=256/Math.max(1,C.high-C.low),_=-S.low/256*F,M=-T.low/256*k,U=-C.low/256*E,R=ve(1,1,1,b);return{rR:R.r*F,rG:R.g*F,rB:R.b*F,rA:0,rOff:_,gR:0,gG:k,gB:0,gA:0,gOff:M,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:ye,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=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 d=1;if(l>r){const e=Math.max(.001,1.414-r);d=1-Math.min(.8,(l-r)/e*t)}n[s*i+e]=d}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),d=Math.min(1,t-o),c=n[o*i+r],u=n[o*i+s],h=n[a*i+r];return c+(u-c)*l+(h-c)*d+(c-u-h+n[a*i+s])*l*d};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),d=o(s(i,r),e);n[l]=Math.round(t[l]*d),n[l+1]=Math.round(t[l+1]*d),n[l+2]=Math.round(t[l+2]*d),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),d=Math.min(255,a+20),c=Math.max(0,a-30);o[s]=Math.round(e*(1-t)+l*t),o[s+1]=Math.round(i*(1-t)+d*t),o[s+2]=Math.round(n*(1-t)+c*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 c=0;c<t.length;c+=4)i+=t[c],n+=t[c+1],o+=t[c+2];const s=i/r,a=n/r,l=o/r,d=(s+a+l)/3;return{u_gain_r:d/Math.max(1,s),u_gain_g:d/Math.max(1,a),u_gain_b:d/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,d=n*(e+o+s),c=e*r+n*(s-o)*i+n*d*(1-r),u=o*r+n*(e-s)*i+n*d*(1-r),h=s*r+n*(o-e)*i+n*d*(1-r);a[l]=Math.min(255,Math.max(0,Math.round(255*c))),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,d=0,c=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,d+=t[p+1]*m,c+=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(d),s[h+2]=Math.round(c),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],d=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-d*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,ke=null,Ee=null;function _e(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),b(/* @__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 Me(e,t){const r=_e(e,e.VERTEX_SHADER,Te),i=_e(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),b(/* @__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 Pe(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 Oe(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 Ne(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,d=a.height;if(l>r||d>r){const e=Math.min(r/l,r/d);l=Math.round(l*e),d=Math.round(d*e)}const c=Math.min(150,l),u=Math.max(1,Math.round(c*d/l)),h=new OffscreenCanvas(c,u).getContext("2d");h.drawImage(a,0,0,c,u);const p=h.getImageData(0,0,c,u);let m;if(a.width!==l||a.height!==d){const e=new OffscreenCanvas(l,d);e.getContext("2d").drawImage(a,0,0,l,d),a.close(),m=await createImageBitmap(e,{imageOrientation:"flipY"})}else m=await createImageBitmap(a,{imageOrientation:"flipY"}),a.close();const g=Fe??new OffscreenCanvas(l,d);g.width===l&&g.height===d||(g.width=l,g.height=d),Fe=g;let f=ke;if(f||(f=g.getContext("webgl",{preserveDrawingBuffer:!0,alpha:!0})||g.getContext("experimental-webgl",{preserveDrawingBuffer:!0,alpha:!0}),ke=f),!f||f.isContextLost())return m.close(),ke=null,Fe=null,async function(e,t,r,i,n,o,s="image/webp",a=.85){const l=new OffscreenCanvas(r,i),d=l.getContext("2d"),c=await createImageBitmap(e);d.drawImage(c,0,0,r,i),c.close();const u=[];for(const h of t){const{def:e}=Pe(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=d.getImageData(0,0,r,i);d.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,d,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,d);const b=[Re(f,l,d),Re(f,l,d)],y=f.createBuffer();f.bindBuffer(f.ARRAY_BUFFER,y),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}=Pe(t);if(!n)continue;const o=t.config?.templateId??n;w.has(o)||w.set(o,Me(f,n));const a=w.get(o);if(!a)continue;f.useProgram(a);const c=f.getAttribLocation(a,"a_position");f.bindBuffer(f.ARRAY_BUFFER,y),f.enableVertexAttribArray(c),f.vertexAttribPointer(c,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,d),Ie(f,a,Oe(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=b[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:d,processingTime:Date.now()-o}:{blob:e,appliedFilters:[],width:l,height:d,processingTime:Date.now()-o}}finally{for(const{fbo:e,tex:t}of b)f.deleteFramebuffer(e),f.deleteTexture(t);f.deleteTexture(v),f.deleteBuffer(y)}}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=[],d=[];for(const u of o){const{def:e}=Pe(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),d.push(u.id)}catch(c){console.warn(`[webgl-filter] buildCpuTransform failed for ${u.id}:`,c),b(c instanceof Error?c:/* @__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:d,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 j(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 d=await l.convertToBlob({type:"image/jpeg",quality:.92}),c=await De(d);if(!i.length)return{original:c,processed:c,appliedFilters:[],failedFilters:[],totalExecutionTime:Date.now()-r};let u=c;const h=[],p=[];try{const e=await Ne(d,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(m){for(const e of i)p.push({id:e.id,error:m instanceof Error?m.message:"Unknown error"});b(m instanceof Error?m:/* @__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:c,processed:u,appliedFilters:h,failedFilters:p,totalExecutionTime:Date.now()-r}}var je=/* @__PURE__ */new Map;function ze(e,t,r,i){return`${e}:${JSON.stringify(t)}:${r}x${i}`}function $e(e){const t=je.get(e);return t&&(je.delete(e),je.set(e,t)),t}function Be(e,t){if(je.delete(e),je.set(e,t),je.size>3){const e=je.keys().next().value;void 0!==e&&je.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=s(null),i=s(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 d={...t.perFileFilterSkipped};delete d[e];const c={...t.filterOverrides};return delete c[e],{selectedFiles:t.selectedFiles.filter(t=>t.uid!==e),captions:r,oversizedUids:i,trimRanges:n,originalFiles:o,cropSelections:s,uploadStates:a,filteredThumbs:l,perFileFilterSkipped:d,filterOverrides:c}}),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},d={...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 d[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:d,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:()=>{je.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__ */h(We.Provider,{value:r.current,children:e})}function Xe(e){const t=m(We);if(!t)throw new Error("useUploadStore must be used within UploadStoreProvider");return function(e,t=Ve){const r=n.useSyncExternalStore(e.subscribe,n.useCallback(()=>t(e.getState()),[e,t]),n.useCallback(()=>t(e.getInitialState()),[e,t]));return n.useDebugValue(r),r}(t,e)}function Ye(){const e=m(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 h("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__ */h("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 h("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__ */h("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 h("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__ */h("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 h("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__ */h("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 h("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__ */h("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 h("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__ */h("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 h("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__ */h("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 h("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__ */h("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 h("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__ */h("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 h("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__ */h("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 h("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__ */h("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 dt({className:e}){/* @__PURE__ */
26
- return h("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__ */h("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 ct(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=ct(e);return 0===i.length?null:/* @__PURE__ */h("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 h("div",{className:"space-y-1",children:[
28
- /* @__PURE__ */h("label",{htmlFor:`${e}:${o.key}`,className:"flex items-center justify-between text-sm",children:[/* @__PURE__ */h("span",{children:[o.label,i.length>1&&/* @__PURE__ */h("span",{className:"text-muted-foreground ml-1 text-xs",children:["(",n,")"]})]}),/* @__PURE__ */h("span",{className:"text-muted-foreground",children:String(s)})]}),"number"===o.type&&/* @__PURE__ */h("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__ */h("input",{type:"checkbox",id:`${e}:${o.key}`,checked:s,onChange:t=>r(e,o.key,t.target.checked)})]},`${e}:${o.key}`)})})}var ht=o(()=>import("./CDSgxlAB.js").then(e=>({default:e.ReactCompareSlider})));function pt({open:e,onClose:t,file:r,filters:n,isVideo:o,trimRange:a,overrides:d,onOverrideChange:c,onReset:p}){const[m,g]=l(),[v,b]=l(),[y,w]=l(!0),[x,S]=l(!1),[T,C]=l(!1),[F,k]=l(),[E,_]=l(0),[M,U]=l(!1),[I,P]=l(null),[O,N]=l(null),[A,D]=l(!1),[L,z]=l(!0),[$,B]=l(!0),H=s(null),Y=s(!1),Q=s([]),J=s(null),Z=s(null),te=s(null),re=s(n);re.current=n,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(!!I&&!!O)},[I,O]),i(()=>{I&&(I.muted=L)},[I,L]),i(()=>{if(!e||o)return;let t=!1;return Y.current?S(!0):w(!0),C(!1),(async()=>{const e=await j(r),i=await createImageBitmap(e),o=Math.min(1,1600/Math.max(i.width,i.height)),s=Math.round(i.width*o),a=Math.round(i.height*o),l=new OffscreenCanvas(s,a);if(l.getContext("2d").drawImage(i,0,0,s,a),i.close(),t)return;k(s/a);const d=await l.convertToBlob({type:"image/jpeg",quality:.92});if(t)return;const c=await Ne(d,n,1600,"image/jpeg",.92);if(t)return;const u=URL.createObjectURL(d),h=URL.createObjectURL(c.blob);Q.current.forEach(e=>URL.revokeObjectURL(e)),Q.current=[u,h],g(u),b(h),Y.current=!0})().catch(()=>{t||Y.current||C(!0)}).finally(()=>{t||(w(!1),S(!1))}),()=>{t=!0}},[e,o,r,n]),i(()=>{if(!e||!o||!A)return;const t=I,i=O;if(!t||!i)return;let n=!1,s=null;const l=URL.createObjectURL(r);w(!0),C(!1),_(0);const d=a?.startTime??0,c=d+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;_(15);let e=t.videoWidth||640,r=t.videoHeight||360;const o=Math.min(1,720/Math.max(e,r));e=Math.round(e*o),r=Math.round(r*o),i.width=e,i.height=r,k(e/r);const l=i.getContext("2d",{willReadFrequently:!0});if(!l)return w(!1),void C(!0);if(Math.abs(t.currentTime-d)>.05&&(await new Promise(e=>{const r=()=>{t.removeEventListener("seeked",r),e()};t.addEventListener("seeked",r,{once:!0}),t.currentTime=d}),n))return;_(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 w(!1),void C(!0);_(60),Z.current=g,te.current={w:e,h:r};const f=await Ae(re.current,g,e,r);if(n)return;if(!f.appliedFilters.length)return w(!1),void C(!0);J.current=f.transform,_(100),w(!1),Y.current=!0;const v=a?Math.min(a.endTime,c):Math.min(t.duration||c,c),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>=v||t.currentTime<d){const e=()=>{t.removeEventListener("seeked",e),n||(s=t.requestVideoFrameCallback(b))};return t.addEventListener("seeked",e,{once:!0}),void(t.currentTime=d)}s=t.requestVideoFrameCallback(b)}};s=t.requestVideoFrameCallback(b)},{once:!0}),t.src=l,t.load(),()=>{n=!0,null!==s&&t.cancelVideoFrameCallback(s),t.pause(),t.removeAttribute("src"),t.load(),URL.revokeObjectURL(l)}},[e,o,r,a,A]),i(()=>{if(!e||!o||!A)return;if(!Z.current||!te.current)return;let t=!1;return S(!0),(async()=>{const{w:e,h:r}=te.current,i=await Ae(n,Z.current,e,r);t||i.appliedFilters.length>0&&(J.current=i.transform)})().catch(()=>{}).finally(()=>{t||S(!1)}),()=>{t=!0}},[e,o,n,A]);const ne=M?"100vh":"70vh",oe=!!c&&ct(n).length>0;/* @__PURE__ */
29
- return h(K,{open:e,onOpenChange:e=>!e&&t(),children:/* @__PURE__ */h(G,{className:f(M?"max-w-none rounded-none":"max-w-2xl sm:w-2xl"),children:/* @__PURE__ */h("div",{className:"bg-background",children:[/* @__PURE__ */h(V,{className:"flex-row items-center justify-between space-y-0",children:[/* @__PURE__ */h(X,{children:"Compare original & filtered"}),/* @__PURE__ */h(ee,{size:"sm",variant:"ghost","aria-label":M?"Exit fullscreen":"Fullscreen",tooltip:M?"Exit fullscreen":"Fullscreen",icon:/* @__PURE__ */h(M?lt:dt,{}),onClick:ie})]}),/* @__PURE__ */h("div",{ref:H,className:f("relative p-4 pt-0",M&&"bg-background flex h-screen w-screen items-center justify-center p-0"),children:[M&&/* @__PURE__ */h(ee,{size:"sm",variant:"ghost","aria-label":"Exit fullscreen",tooltip:"Exit fullscreen",className:"absolute top-2 right-2 z-30",icon:/* @__PURE__ */h(lt,{}),onClick:ie}),y&&/* @__PURE__ */h("div",{className:"flex h-64 flex-col items-center justify-center gap-2",children:[/* @__PURE__ */h(R,{}),o&&/* @__PURE__ */h("p",{className:"text-muted-foreground text-sm",children:["Generating preview… ",E,"%"]})]}),T&&!y&&/* @__PURE__ */h("div",{className:"text-muted-foreground flex h-64 items-center justify-center text-sm",children:"Couldn't generate preview."}),x&&!y&&!T&&/* @__PURE__ */h("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__ */h(R,{className:"size-3.5"}),"Updating…"]}),!o&&!y&&!T&&m&&v&&/* @__PURE__ */h(u,{fallback:null,children:/* @__PURE__ */h(ht,{style:{width:"100%",maxHeight:ne,aspectRatio:F},defaultPosition:50,onlyHandleDraggable:!0,itemOne:/* @__PURE__ */h("div",{className:"relative size-full",children:[/* @__PURE__ */h("img",{alt:"Original",className:"size-full object-contain",src:m}),/* @__PURE__ */h(mt,{position:"left",children:"Original"})]}),itemTwo:/* @__PURE__ */h("div",{className:"relative size-full",children:[/* @__PURE__ */h("img",{alt:"Filtered",className:"size-full object-contain",src:v}),/* @__PURE__ */h(mt,{position:"right",children:"Filtered"})]})})}),o&&/* @__PURE__ */h("div",{className:"relative",style:{visibility:y||T?"hidden":"visible"},children:[/* @__PURE__ */h(u,{fallback:null,children:/* @__PURE__ */h(ht,{style:{width:"100%",maxHeight:ne,aspectRatio:F},defaultPosition:50,onlyHandleDraggable:!0,itemOne:/* @__PURE__ */h("div",{className:"relative size-full",children:[/* @__PURE__ */h("video",{ref:P,playsInline:!0,className:"pointer-events-none size-full object-contain"}),/* @__PURE__ */h(mt,{position:"left",children:"Original"})]}),itemTwo:/* @__PURE__ */h("div",{className:"relative size-full",children:[/* @__PURE__ */h("canvas",{ref:N,className:"size-full object-contain"}),/* @__PURE__ */h(mt,{position:"right",children:"Filtered"})]})})}),/* @__PURE__ */h("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__ */h(ee,{size:"sm",variant:"ghost","aria-label":L?"Unmute":"Mute",tooltip:L?"Unmute":"Mute",icon:/* @__PURE__ */h(L?st:at,{}),onClick:()=>z(e=>!e)}),/* @__PURE__ */h(ee,{size:"sm",variant:"ghost","aria-label":$?"Pause":"Play",tooltip:$?"Pause":"Play",icon:/* @__PURE__ */h($?nt:ot,{}),onClick:()=>{I&&(I.paused?(I.play(),B(!0)):(I.pause(),B(!1)))}})]})]}),c&&!M&&/* @__PURE__ */h("div",{className:"mt-4",children:/* @__PURE__ */h(ut,{filters:n,overrides:d,onChange:c})}),oe&&!M&&/* @__PURE__ */h(W,{className:"mt-4",children:[/* @__PURE__ */h(q,{variant:"outlined",color:"foreground",onClick:p,children:"Reset"}),/* @__PURE__ */h(q,{onClick:t,children:"Apply"})]})]})]})})})}function mt({position:e,children:t}){/* @__PURE__ */
30
- return h("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"],bt=({open:e,onClose:t,imageSrc:r,outputSrc:i,aspectRatio:n,initialCrop:o,onCropComplete:a,title:d})=>{const c=s(null),[u,m]=l(null),[g,f]=l(!1),v=s(null),y=p((e,t)=>{const r=c.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)}},[]),w=p(e=>{const t=v.current,r=c.current;var i,o,s,a,l;if(t&&r)if("move"===t.mode)m((i=t.start,o=e.clientX-t.clientX,s=e.clientY-t.clientY,a=r.width,l=r.height,{...i,x:gt(i.x+o,0,a-i.w),y:gt(i.y+s,0,l-i.h)}));else{const{px:i,py:o}=y(e.clientX,e.clientY);m(function(e,t,r,i,n,o,s){const a=t.includes("e")?1:-1,l=t.includes("s")?1:-1,d=a>0?e.x:e.x+e.w,c=l>0?e.y:e.y+e.h,u=a>0?n-d:d,h=l>0?o-c:c;let p=gt((r-d)*a,20,u),m=gt((i-c)*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?d:d-p,y:l>0?c:c-m,w:p,h:m}}(t.start,t.corner,i,o,r.width,r.height,n))}},[n,y]),x=p(()=>{v.current=null,window.removeEventListener("pointermove",w),window.removeEventListener("pointerup",x)},[w]),S=(e,t)=>r=>{u&&(r.preventDefault(),r.stopPropagation(),v.current={mode:e,corner:t,start:u,clientX:r.clientX,clientY:r.clientY},window.addEventListener("pointermove",w),window.addEventListener("pointerup",x))},T=p(()=>{m(null),t()},[t]),C=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 h(K,{open:e,onOpenChange:T,children:/* @__PURE__ */h(G,{className:"flex h-[90vh] min-w-xl flex-col overflow-hidden p-0",children:[
32
- /* @__PURE__ */h("div",{className:"bg-background shrink-0",children:/* @__PURE__ */h(V,{children:[/* @__PURE__ */h(X,{children:d||"Crop Image"}),/* @__PURE__ */h(Y,{className:"sr-only",children:"Drag the box to move it, or drag a corner to resize."})]})}),
33
- /* @__PURE__ */h("div",{className:"flex max-h-[60vh] min-h-0 flex-1 items-center justify-center overflow-hidden bg-black",children:/* @__PURE__ */h("div",{style:{position:"relative",display:"inline-block",lineHeight:0,touchAction:"none"},children:[/* @__PURE__ */h("img",{ref:c,src:r,alt:"Crop preview",draggable:!1,onLoad:()=>{const e=c.current;e&&m(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"}}),u&&/* @__PURE__ */h("div",{onPointerDown:S("move"),style:{position:"absolute",left:`${u.x}px`,top:`${u.y}px`,width:`${u.w}px`,height:`${u.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__ */h("div",{onPointerDown:S("resize",e),style:C(e)},e))})]})}),
34
- /* @__PURE__ */h("div",{className:"border-border bg-background shrink-0 border-t",children:/* @__PURE__ */h(W,{children:[/* @__PURE__ */h(q,{variant:"outlined",onClick:T,disabled:g,children:"Cancel"}),/* @__PURE__ */h(q,{onClick:async()=>{const e=c.current;var t;if(u&&e)try{f(!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=u.x/e.width,s=u.y/e.height,l=u.w/e.width,d=u.h/e.height,c={x:Math.round(o*n.naturalWidth),y:Math.round(s*n.naturalHeight),w:Math.round(l*n.naturalWidth),h:Math.round(d*n.naturalHeight)},h={unit:"%",x:ft(100*o),y:ft(100*s),width:ft(100*l),height:ft(100*d)};a(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,c),h),T()}catch(n){b(n instanceof Error?n:new Error(String(n)),{component:"ImageCropDialog",tags:["upload","crop"]})}finally{f(!1)}},loading:g,disabled:g||!u,children:"Crop"})]})})]})})},yt=({open:e,onClose:t,videoFile:r,activeFilters:n,onTrimComplete:o,title:a="Select 60 Second Clip"})=>{const d=s(null),c=s(null),u=s(null),m=n?.filter(e=>e.enabled)??[],g=m.length>0,[f,v]=l(0),[y,w]=l(0),[x,S]=l(60),[T,C]=l(0),[F,k]=l(!1),[E,_]=l(!1),[M,U]=l(null),[R,I]=l(null),[P,O]=l(0),[N,A]=l({start:0,end:0});i(()=>{if(r&&e){const e=URL.createObjectURL(r);return U(e),()=>URL.revokeObjectURL(e)}},[r,e]),i(()=>{if(!M||!g)return;const e=d.current,t=c.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 d=document.createElement("canvas");d.width=s,d.height=a,d.getContext("2d")?.drawImage(e,0,0,s,a);const c=await new Promise(e=>d.toBlob(e,"image/jpeg",.85));if(r||!c)return;const u=await Ae(m,c,s,a);if(r||!u.appliedFilters.length)return;const h=u.transform,p=()=>{r||(l.drawImage(e,0,0,s,a),l.putImageData(h(l.getImageData(0,0,s,a)),0,0),i=e.requestVideoFrameCallback(p))};p()})()}),e.readyState>=2&&e.paused)try{e.currentTime=e.currentTime+.001}catch{}return()=>{r=!0,null!==i&&e.cancelVideoFrameCallback?.(i)}},[M,g,JSON.stringify(n)]);const D=p(e=>{if(!u.current||0===f)return 0;const t=u.current.getBoundingClientRect();return Math.max(0,Math.min(1,(e-t.left)/t.width))*f},[f]),L=p(e=>0===f?0:e/f*100,[f]),j=(e,t)=>{e.preventDefault(),e.stopPropagation(),I(t),O(e.clientX),A({start:y,end:x})},z=(e,t)=>{e.stopPropagation();const r=e.touches[0];I(t),O(r?.clientX??0),A({start:y,end:x})};i(()=>{if(!R||!u.current)return;const e=e=>{const t=u.current.getBoundingClientRect(),r=(e-P)/t.width*f;if("start"===R){let e=Math.max(0,N.start+r);e=Math.min(e,x-1),x-e>60&&(e=x-60),w(e),d.current&&(d.current.currentTime=e)}else if("end"===R){let e=Math.min(f,N.end+r);e=Math.max(e,y+1),e-y>60&&(e=y+60),S(e)}else if("range"===R){const e=N.end-N.start;let t=N.start+r,i=N.end+r;t<0&&(t=0,i=e),i>f&&(i=f,t=f-e),w(t),S(i),d.current&&(d.current.currentTime=t)}},t=t=>e(t.clientX),r=t=>e(t.touches[0].clientX),i=()=>I(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)}},[R,P,N,f,y,x]);const $=()=>{d.current&&(F?d.current.pause():((T<y||T>=x)&&(d.current.currentTime=y),d.current.play()),k(!F))},B=e=>`${Math.floor(e/60)}:${Math.floor(e%60).toString().padStart(2,"0")}`,H=()=>{w(0),S(60),C(0),k(!1),I(null),d.current&&d.current.pause(),t()},Q=x-y;/* @__PURE__ */
35
- return h(K,{open:e,onOpenChange:H,children:/* @__PURE__ */h(G,{className:"max-h-[90vh] max-w-3xl overflow-y-auto p-0",children:[
36
- /* @__PURE__ */h("div",{className:"bg-background sticky top-0 z-10",children:/* @__PURE__ */h(V,{children:[/* @__PURE__ */h(X,{children:a}),/* @__PURE__ */h(Y,{className:"hidden",children:"Review the video preview and choose the start and end times for the clip you want to keep."})]})}),
37
- /* @__PURE__ */h("div",{className:"space-y-4 p-4",children:[
38
- /* @__PURE__ */h("div",{className:"relative aspect-video w-full overflow-hidden rounded-lg bg-black",children:[M&&/* @__PURE__ */h("video",{ref:d,src:M,className:"size-full object-contain",onLoadedMetadata:()=>{if(d.current){const e=d.current.duration;v(e),w(0),S(Math.min(e,60))}},onTimeUpdate:()=>{if(d.current){const e=d.current.currentTime;C(e),e>=x&&(d.current.pause(),d.current.currentTime=y,k(!1))}},onEnded:()=>k(!1)}),M&&g&&/* @__PURE__ */h("canvas",{ref:c,className:"pointer-events-none absolute inset-0 size-full object-contain"}),
39
- /* @__PURE__ */h("button",{type:"button","aria-label":F?"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__ */h("svg",F?{xmlns:"http://www.w3.org/2000/svg",className:"h-16 w-16 text-white drop-shadow-lg",viewBox:"0 0 24 24",children:/* @__PURE__ */h("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__ */h("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__ */h("div",{className:"absolute bottom-2 left-2 rounded bg-black/70 px-2 py-1 text-sm text-white",children:B(T)})]}),
41
- /* @__PURE__ */h("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[/* @__PURE__ */h("div",{className:"flex items-center gap-2",children:[/* @__PURE__ */h("span",{className:"bg-primary/20 text-primary rounded-full px-3 py-1 text-sm font-medium",children:["Start: ",B(y)]}),/* @__PURE__ */h("span",{className:"bg-primary/20 text-primary rounded-full px-3 py-1 text-sm font-medium",children:["End: ",B(x)]})]}),/* @__PURE__ */h("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__ */h("div",{className:"space-y-1",children:[
43
- /* @__PURE__ */h("div",{className:"relative h-4 select-none",children:(()=>{if(0===f)return[];let e;e=f<=30?10:f<=60?15:f<=120?30:f<=300?60:120;const t=[];for(let i=0;i<=f;i+=e)t.push(i);const r=t[t.length-1];return f-r>.3*e&&t.push(Math.floor(f)),t})().map(e=>/* @__PURE__ */h("span",{className:"text-muted-foreground absolute -translate-x-1/2 text-xs",style:{left:`${L(e)}%`},children:B(e)},e))}),
44
- /* @__PURE__ */h("div",{ref:u,className:"relative h-16 cursor-pointer rounded-lg bg-gray-200 select-none dark:bg-gray-800",onClick:e=>{if(R)return;const t=D(e.clientX);t>=y&&t<=x&&d.current&&(d.current.currentTime=t,C(t))},children:[
45
- /* @__PURE__ */h("div",{className:"absolute inset-y-0 left-0 bg-black/50",style:{width:`${L(y)}%`}}),
46
- /* @__PURE__ */h("div",{className:"absolute inset-y-0 right-0 bg-black/50",style:{width:100-L(x)+"%"}}),
47
- /* @__PURE__ */h("div",{className:"bg-primary/30 border-primary absolute inset-y-0 cursor-grab border-y-2 active:cursor-grabbing",style:{left:`${L(y)}%`,width:`${L(x-y)}%`},onMouseDown:e=>j(e,"range"),onTouchStart:e=>z(e,"range")}),
48
- /* @__PURE__ */h("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(y)}% - 6px)`},onMouseDown:e=>j(e,"start"),onTouchStart:e=>z(e,"start"),children:/* @__PURE__ */h("div",{className:"absolute inset-y-0 left-1/2 w-0.5 -translate-x-1/2 bg-white/50"})}),
49
- /* @__PURE__ */h("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(x)}% - 6px)`},onMouseDown:e=>j(e,"end"),onTouchStart:e=>z(e,"end"),children:/* @__PURE__ */h("div",{className:"absolute inset-y-0 left-1/2 w-0.5 -translate-x-1/2 bg-white/50"})}),
50
- /* @__PURE__ */h("div",{className:"absolute inset-y-0 z-20 w-0.5 bg-white shadow-lg",style:{left:`${L(T)}%`},children:/* @__PURE__ */h("div",{className:"absolute -top-1 left-1/2 h-3 w-3 -translate-x-1/2 rotate-45 bg-white"})}),
51
- /* @__PURE__ */h("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(f))}).map((e,t)=>/* @__PURE__ */h("div",{className:"w-px bg-gray-400/30",style:{height:t%5==0?"100%":"50%"}},t))})]}),
52
- /* @__PURE__ */h("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__ */h("div",{className:"flex items-center justify-center gap-2",children:[
54
- /* @__PURE__ */h(q,{variant:"outlined",size:"sm",onClick:()=>{d.current&&(d.current.currentTime=y,C(y))},children:/* @__PURE__ */h("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5",viewBox:"0 0 24 24",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"M6 6h2v12H6zm3.5 6l8.5 6V6z"})})}),
55
- /* @__PURE__ */h(q,{variant:"outlined",onClick:$,children:/* @__PURE__ */h("svg",F?{xmlns:"http://www.w3.org/2000/svg",className:"h-6 w-6",viewBox:"0 0 24 24",children:/* @__PURE__ */h("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__ */h("path",{fill:"currentColor",d:"M8 5v14l11-7z"})})}),
56
- /* @__PURE__ */h(q,{variant:"outlined",size:"sm",onClick:()=>{d.current&&(d.current.currentTime=x,C(x))},children:/* @__PURE__ */h("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5",viewBox:"0 0 24 24",children:/* @__PURE__ */h("path",{fill:"currentColor",d:"m5 18l8.5-6L5 6zm11 0V6h2v12z"})})})]})]}),
57
- /* @__PURE__ */h("div",{className:"bg-background border-border sticky bottom-0 border-t",children:/* @__PURE__ */h(W,{children:[/* @__PURE__ */h(q,{variant:"outlined",onClick:H,disabled:E,children:"Cancel"}),/* @__PURE__ */h(q,{onClick:async()=>{_(!0);try{o({startTime:y,endTime:x,duration:x-y}),H()}catch(e){b(e instanceof Error?e:new Error(String(e)),{component:"VideoTrimDialog",tags:["upload","trim"]})}finally{_(!1)}},loading:E,disabled:E||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=d(function({uid:e,file:t,onRemove:r,disabled:n,adaRequired:o,showCaption:a=!0,onRetry:d}){const u=z(t),m=!u&&D(t),g=Ye(),v=Xe(t=>t.captions[e]),b=Xe(t=>t.oversizedUids[e]),y=Xe(t=>t.uploadStates[e]),w=Xe(t=>t.trimRanges[e]),x=Xe(t=>t.originalFiles[e])??t,S=Xe(e=>e.videoMuted),T=Xe(e=>e.setVideoMuted),C=Xe(e=>e.activeFilters),F=Xe(e=>e.showFilterChoice),k=Xe(e=>e.skipUploadFilters),E=Xe(t=>t.perFileFilterSkipped[e]),_=Xe(t=>t.filteredThumbs[e]),M=Xe(t=>t.filterOverrides[e]),U=c(()=>{return e=C,(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},[C,M]),I=!!y,O="success"===y?.status,N="error"===y?.status,A=C.length>0&&(!F||!k&&!E),q=C.length>0&&(!F||!k),[L,j]=l(!1),[B,V]=l(),[W,G]=l(!1),[X,Y]=l(!1),{ref:K,inView:J}=function({rootMargin:e,triggerOnce:t}={}){const r=s(null),[n,o]=l(!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]=l();i(()=>{if(!m||!J)return;let e,r=!1;return $(t).then(t=>{r?URL.revokeObjectURL(t):(e=t,ie(t))}),()=>{r=!0,e&&URL.revokeObjectURL(e)}},[t,m,J]);const[ne,oe]=l();i(()=>{if(!m||!L)return;let e,t=!1;return $(x).then(r=>{t?URL.revokeObjectURL(r):(e=r,oe(r))}),()=>{t=!0,e&&URL.revokeObjectURL(e),oe(void 0)}},[x,m,L]);const[se,ae]=l();i(()=>{if(!m||!L||!A)return void ae(void 0);let e=!1;return Le(x,U).then(t=>{e||ae(t.processed)}).catch(()=>{}),()=>{e=!0}},[m,L,A,x,U]);const le=s(null),de=s(null),ce=s(null),ue=s(0),he=s(null),[pe,fe]=l(!1),[ve,be]=l(!1),[ye,we]=l(null),[Te,Ce]=l(null),Fe=p(()=>{const e=le.current;if(!e||ce.current)return;const r=URL.createObjectURL(t);ce.current=r,e.src=r,e.load()},[t]),ke=p(()=>{const e=le.current;e&&(e.removeAttribute("src"),e.load()),ce.current&&(URL.revokeObjectURL(ce.current),ce.current=null)},[]),Ee=p(()=>{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)))},[]),_e=p(()=>{const t=le.current,r=de.current;if(!t||!r||!t.videoWidth)return!1;const{w:i,h:n}=wt(t.videoWidth,t.videoHeight),o=$e(ze(e,U,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,U]),Me=p(()=>{he.current&&(clearTimeout(he.current),he.current=null)},[]),Ue=p(()=>{const t=le.current;if(t&&(ue.current=t.currentTime),Ee(),A){const e=_e();be(e),e&&de.current&&Ce(de.current.toDataURL("image/jpeg",.85))}fe(!1),function(e){Qe===e&&(Qe=null)}(e),Me(),he.current=setTimeout(()=>{ke(),he.current=null},200)},[e,Ee,_e,A,ke,Me]),Re=p(()=>{const t=le.current;if(!t)return;if(pe)return void t.pause();!function(e){Qe&&Qe!==e&&Ke.get(Qe)?.(),Qe=e}(e),Me(),Fe();const r=ue.current||w?.startTime||0,i=()=>{t.currentTime=r,t.play().catch(()=>{})};t.readyState>=1?i():t.addEventListener("loadedmetadata",i,{once:!0})},[pe,Fe,w,e,Me]);return i(()=>{if(!u)return;const t=function(e){return Ke.set(e,()=>le.current?.pause()),()=>{Ke.delete(e),Qe===e&&(Qe=null)}}(e);return()=>{t(),Me(),ke()}},[u,e,ke,Me]),i(()=>{W&&le.current?.pause()},[W]),i(()=>{I&&le.current?.pause()},[I]),i(()=>{ue.current=0},[w]),i(()=>{be(!1),Ce(null)},[A,U,e]),i(()=>{le.current&&(le.current.muted=S)},[S]),i(()=>{if(!u||!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 d=o.getContext("2d");if(!d)return;d.drawImage(i,0,0,o.width,o.height),we(o.toDataURL("image/jpeg",.85))}catch{}finally{n()}}).catch(()=>{}),()=>{e=!0,n()}},[u,J,t]),i(()=>{if(!m||!J||!A||_||X)return;let r=!1;return ge(()=>Le(t,U)).then(t=>{!r&&t.appliedFilters.length&&g.getState().setFilteredThumb(e,t.processed)}).catch(()=>{}),()=>{r=!0}},[m,J,A,_,X,t,U,g,e]),i(()=>{if(!u||!ye||!A||_||X)return;let t=!1;return ge(async()=>{const t=await fetch(ye);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=ze(e,U,n,o);let a=$e(s);if(a||(a=await Ae(U,r,n,o),a.appliedFilters.length&&Be(s,a)),!a.appliedFilters.length)return i.close(),null;const l=new OffscreenCanvas(n,o),d=l.getContext("2d");return d.drawImage(i,0,0,n,o),i.close(),d.putImageData(a.transform(d.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||g.getState().setFilteredThumb(e,i.result)},i.readAsDataURL(r)}).catch(()=>{}),()=>{t=!0}},[u,ye,A,_,X,U,g,e]),i(()=>{if(!(u&&pe&&A&&ye))return;const t=le.current,r=de.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=ze(e,U,o,s);let d=$e(l);if(!d){const e=await fetch(ye);if(!1===e.ok)throw new Error(`Poster fetch failed: ${e.status}`);const t=await e.blob();if(i)return;if(d=await Ae(U,t,o,s),i||!d.appliedFilters.length)return;Be(l,d)}const c=d.transform,u=w?.startTime??0,h=Number.isFinite(t.duration)?t.duration:1/0,p=Math.min(w?.endTime??1/0,h);let m=!1;const g=()=>{if(!i){if(a.drawImage(t,0,0,o,s),a.putImageData(c(a.getImageData(0,0,o,s)),0,0),m||(m=!0,be(!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)}},[u,pe,A,ye,U,w,e]),i(()=>{if(!u||pe||!A||!ye||X)return;let e=!1;return(async()=>{const t=await fetch(ye);if(!1===t.ok)throw new Error(`Poster fetch failed: ${t.status}`);const r=await t.blob(),i=await Le(new File([r],"poster.jpg",{type:"image/jpeg"}),U);e||Ce(i.processed)})().catch(()=>{}),()=>{e=!0}},[u,pe,A,ye,X,U]),/* @__PURE__ */h("div",{className:"group relative",children:[
58
- /* @__PURE__ */h("div",{ref:K,className:f("bg-muted relative h-48 overflow-hidden rounded sm:h-72",b&&"border-destructive border-2"),children:[m&&re&&/* @__PURE__ */h("img",{src:A&&_?_:re,alt:t.name,loading:"lazy",decoding:"async",className:"size-full object-contain"}),m&&q&&/* @__PURE__ */h(Tt,{applied:A&&!!_}),u&&/* @__PURE__ */h("div",{className:"relative size-full",children:[ye&&/* @__PURE__ */h("img",{src:A?Te??_??ye:ye,alt:"",className:f("absolute inset-0 size-full object-contain",pe?"opacity-0":"opacity-100")}),(!pe||A)&&q&&/* @__PURE__ */h(Tt,{applied:A&&!!_}),
59
- /* @__PURE__ */h("video",{ref:le,muted:S,playsInline:!0,loop:!w,preload:"none",onLoadedMetadata:e=>{w&&(e.currentTarget.currentTime=w.startTime)},onTimeUpdate:e=>{if(!w)return;const t=e.currentTarget;t.currentTime>=w.endTime&&(t.currentTime=w.startTime)},onPlaying:()=>fe(!0),onPause:Ue,className:f("size-full object-contain",pe&&!A?"opacity-100":"opacity-0")}),A&&/* @__PURE__ */h("canvas",{ref:de,className:f("pointer-events-none absolute inset-0 size-full object-contain",pe&&ve?"opacity-100":"opacity-0")}),!I&&/* @__PURE__ */h("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__ */h(pe?nt:ot,{className:"text-foreground size-8"})}),!I&&/* @__PURE__ */h("button",{type:"button","aria-label":S?"Unmute videos":"Mute videos",onClick:()=>T(!S),className:"bg-background/60 absolute bottom-2 left-2 z-10 rounded-full p-2 backdrop-blur-sm",children:/* @__PURE__ */h(S?st:at,{className:"text-foreground size-5"})}),w&&!I&&/* @__PURE__ */h("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=w.endTime-w.startTime,`${Math.floor(Ie/60)}:${Math.floor(Ie%60).toString().padStart(2,"0")}`)]})]}),!m&&!u&&/* @__PURE__ */h("div",{className:"flex h-full w-full items-center justify-center",children:/* @__PURE__ */h(it,{className:"text-muted-foreground size-12"})}),b&&/* @__PURE__ */h("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__ */h(Q,{className:"size-4"}),"Exceeds ",xt[b]," limit"]}),I&&!O&&!N&&/* @__PURE__ */h("div",{className:"bg-background/80 absolute inset-0 flex flex-col items-center justify-center gap-3 backdrop-blur-sm",children:[y.bytesTotal>0&&/* @__PURE__ */h("div",{className:"bg-primary/20 absolute bottom-0 left-0 h-full transition-[width] duration-300",style:{width:`${Math.round(y.bytesUploaded/y.bytesTotal*100)}%`}}),
61
- /* @__PURE__ */h("div",{className:"bg-primary/10 flex size-12 items-center justify-center rounded-full",children:/* @__PURE__ */h(R,{className:"size-6"})}),
62
- /* @__PURE__ */h("div",{className:"relative z-10 rounded-full bg-white/80 px-3 py-1 backdrop-blur-sm dark:bg-black/40",children:/* @__PURE__ */h("span",{className:"text-muted-foreground text-sm font-medium",children:"creating"!==y.status&&"queued"!==y.status&&y.bytesTotal>0?`Uploading ${Math.round(y.bytesUploaded/y.bytesTotal*100)}%`:"Uploading"})})]}),O&&/* @__PURE__ */h("div",{className:"bg-background/80 absolute inset-0 flex flex-col items-center justify-center gap-2 p-4 backdrop-blur-sm",children:[/* @__PURE__ */h("div",{className:"bg-success/20 flex size-14 items-center justify-center rounded-full",children:/* @__PURE__ */h(Z,{className:"text-success size-8"})}),/* @__PURE__ */h("span",{className:"text-success text-sm font-medium",children:"Uploaded!"})]}),N&&/* @__PURE__ */h("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__ */h("div",{className:"bg-destructive/20 flex size-14 items-center justify-center rounded-full",children:/* @__PURE__ */h(Q,{className:"text-destructive size-8"})}),
64
- /* @__PURE__ */h("p",{className:"text-destructive text-center text-xs font-medium",children:y?.error??"Upload failed"}),d&&/* @__PURE__ */h("button",{type:"button",onClick:()=>d(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__ */h(H,{className:"size-3.5"}),"Retry"]})]})]}),!n&&/* @__PURE__ */h(ee,{size:"sm",color:"error",variant:"default",className:"absolute top-3 right-3","aria-label":"Remove file",icon:/* @__PURE__ */h(P,{}),onClick:()=>r(e)}),!n&&(m||u)&&/* @__PURE__ */h("div",{className:"absolute top-3 left-3 flex gap-2",children:[
65
- /* @__PURE__ */h(ee,{size:"sm",variant:"default","aria-label":m?"Crop image":"Trim video",icon:/* @__PURE__ */h(m?rt:tt,{}),onClick:()=>m?j(!0):G(!0)}),F&&C.length>0&&!k&&/* @__PURE__ */h(ee,{size:"sm",variant:"default","aria-label":E?"Apply filter":"Skip filter",tooltip:E?"Apply filter":"Skip filter",icon:/* @__PURE__ */h(E?Je:Ze,{}),onClick:()=>g.getState().setFileFilterSkipped(e,!E)}),F&&C.length>0&&!k&&!E&&/* @__PURE__ */h(ee,{size:"sm",variant:"default","aria-label":"Compare original and filtered",tooltip:"Compare original and filtered",icon:/* @__PURE__ */h(et,{}),onClick:()=>{Qe&&(Ke.get(Qe)?.(),Qe=null),Y(!0)}})]}),m&&ne&&/* @__PURE__ */h(bt,{open:L,onClose:()=>j(!1),imageSrc:A&&se?se:ne,outputSrc:ne,title:"Crop Image",initialCrop:B,onCropComplete:(r,i)=>{const n=new File([r],t.name,{type:r.type});V(i),g.getState().replaceFile(e,n,i)}}),u&&W&&/* @__PURE__ */h(yt,{open:W,onClose:()=>G(!1),videoFile:t,activeFilters:A?U:void 0,title:"Select Clip",onTrimComplete:({startTime:t,endTime:r})=>g.getState().setTrimRange(e,{startTime:t,endTime:r})}),X&&/* @__PURE__ */h(pt,{open:X,onClose:()=>Y(!1),file:t,filters:U,isVideo:u,trimRange:w,overrides:M,onOverrideChange:(t,r,i)=>g.getState().setFilterOverride(e,t,r,i),onReset:()=>g.getState().resetFilterOverrides(e)}),a&&/* @__PURE__ */h("div",{className:"mt-2",children:/* @__PURE__ */h(te,{placeholder:o?"Caption (required)":"Caption",value:v??"",onInput:t=>g.getState().setCaption(e,t.target.value),disabled:n,error:o&&!v?.trim()?" ":void 0,className:"text-xs"})})]});var Ie});function Tt({applied:e}){/* @__PURE__ */
66
- return h("div",{className:f("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:n}){const o=Xe(e=>e.hasStarted),s=Xe(e=>e.uploadStates),a=Xe(e=>e.uploadSpeedBps),l=c(()=>{const e=Object.values(s);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,a=e.length;return{succeeded:t,failed:r,percent:o,total:a,allDone:t+r>=a}},[s]),d=!!(o&&l&&l.allDone&&l.failed>0);return 0===n?null:/* @__PURE__ */h("div",{className:"bg-background/85 fixed right-0 bottom-0 left-0 z-2002 overflow-hidden backdrop-blur-sm",children:/* @__PURE__ */h("div",{className:"relative flex items-stretch gap-3",children:[
67
- /* @__PURE__ */h("div",{className:"relative min-w-0 flex-1 overflow-hidden",children:[o&&l&&/* @__PURE__ */h("div",{className:"bg-primary/40 absolute inset-y-0 t-0 text-right transition-[width] duration-300",style:{width:`${l.percent}%`}}),/* @__PURE__ */h("div",{className:"relative flex h-full flex-col justify-center gap-0.5 py-3 pl-3",children:/* @__PURE__ */h("span",o&&l?{className:"text-muted-foreground text-sm font-medium",children:["Uploading",l.failed>0?` · ${l.failed} failed`:""," (",l.percent,"%)"," ",a?/* @__PURE__ */h("span",{className:"text-muted-foreground/70 text-xs",children:["• ",(u=a,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:[n," media selected"]})})]}),o&&d&&/* @__PURE__ */h("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__ */h(H,{className:"size-4"}),"Retry All"]}),o&&!d&&/* @__PURE__ */h("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"}),!o&&/* @__PURE__ */h("button",{type:"button",onClick:e,disabled:i,className:f("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__ */h("span",{className:"flex items-center gap-2",children:[/* @__PURE__ */h(L,{className:"size-4"}),"Upload"]})})]})});var u}function Ft({enabledFileTypes:e,disabled:t,onFileSelect:r,children:i}){const[n,o]=l(!1),a=s(null),d=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),c=p(t=>{if(!t)return;const i=Array.from(t).filter(t=>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))}(t,e));i.length>0&&r(i)},[e,r]);/* @__PURE__ */
68
- return h("div",{role:"button",tabIndex:0,onClick:()=>!t&&a.current?.click(),onKeyDown:e=>{t||"Enter"!==e.key&&" "!==e.key||a.current?.click()},onDragOver:e=>{e.preventDefault(),t||o(!0)},onDragLeave:()=>o(!1),onDrop:p(e=>{e.preventDefault(),o(!1),t||c(e.dataTransfer?.files??null)},[t,c]),children:[/* @__PURE__ */h("input",{ref:a,type:"file",accept:d,multiple:!0,disabled:t,className:"hidden",onChange:e=>{c(e.target.files),e.target.value=""}}),i({isDragActive:n})]})}function kt({enabledFileTypes:e,disabled:t,onFileSelect:r,selectedCount:i,maxCount:n,enableVideo:o}){/* @__PURE__ */
69
- return h("div",{className:"flex w-full justify-center",children:/* @__PURE__ */h(Ft,{enabledFileTypes:e,disabled:t,onFileSelect:r,children:()=>/* @__PURE__ */h("div",{className:f("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__ */h("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__ */h("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__ */h("span",{className:f(t?"text-muted-foreground":"","mt-2 block font-medium"),children:`Select Images ${o?"or Videos (60s)":""} to upload (${i}/${n})`}),
72
- /* @__PURE__ */h("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 Et({enabledFileTypes:e,disabled:t,onFileSelect:r}){/* @__PURE__ */
73
- return h(Ft,{enabledFileTypes:e,disabled:t,onFileSelect:r,children:({isDragActive:e})=>/* @__PURE__ */h("div",{className:f("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__ */h("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 h(Ft,{enabledFileTypes:e,disabled:t,onFileSelect:r,children:()=>/* @__PURE__ */h("div",{className:f("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__ */h("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:"size-4",children:/* @__PURE__ */h("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__ */h("span",{children:"Add more"})]})})}function Mt({uploadDisabled:e,eventName:t,isQuotaLoading:r,remainingUploads:i}){const n=r?"-":i;/* @__PURE__ */
75
- return h("div",{className:"relative overflow-hidden rounded-2xl px-3 pt-6 sm:pt-0",children:[/* @__PURE__ */h("div",{className:"absolute inset-0 opacity-50"}),/* @__PURE__ */h("div",{className:"relative z-10",children:/* @__PURE__ */h("div",{className:"flex flex-col items-center justify-center gap-3",children:/* @__PURE__ */h("div",{className:"flex items-center gap-3",children:/* @__PURE__ */h("div",{className:"space-y-1 text-center",children:[t&&/* @__PURE__ */h(U,{variant:"h4",align:"center",className:"line-clamp-2",children:t}),/* @__PURE__ */h("p",{className:f("text-sm font-medium",e?"text-muted-foreground":"text-foreground"),children:["Remaining Uploads: ",/* @__PURE__ */h("span",{className:"text-primary font-bold",children:n})]})]})})})})]})}var Ut=Object.defineProperty,Rt=Object.getOwnPropertyNames,It=(e,t)=>function(){return e&&(t=(0,e[Rt(e)[0]])(e=0)),t},Pt=(e,t)=>{for(var r in t)Ut(e,r,{get:t[r],enumerable:!0})};function Ot(e){const t=e/255;return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Nt(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 At(e,t,r){const i=Ot(e),n=Ot(t),o=Ot(r),s=.4122214708*i+.5363325363*n+.0514459929*o,a=.2119034982*i+.6806995451*n+.1073969566*o,l=.0883024619*i+.2817188376*n+.6299787005*o,d=Math.cbrt(s),c=Math.cbrt(a),u=Math.cbrt(l),h=.2104542553*d+.793617785*c-.0040720468*u,p=1.9779984951*d-2.428592205*c+.4505937099*u,m=.0259040371*d+.7827717662*c-.808675766*u,g=Math.sqrt(p*p+m*m);let f=Math.atan2(m,p)*(180/Math.PI);return f<0&&(f+=360),{l:h,c:g,h:f}}function qt(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,d=s*s*s,c=a*a*a,u=l*l*l,h=-1.2684380046*d+2.6097574011*c-.3413193965*u,p=-.0041960863*d-.7034186147*c+1.707614701*u;return[Nt(4.0767416621*d-3.3077115913*c+.2309699292*u),Nt(h),Nt(p)]}var Dt,Lt=It({"src/color-space.ts"(){}});function jt(e,t){return(Math.max(e,t)+.05)/(Math.min(e,t)+.05)}function zt(e,t,r,i,n=0){return new Dt(e,t,r,i,n)}var $t=It({"src/color.ts"(){Lt(),Dt=class{constructor(e,t,r,i,n){this._r=e,this._g=t,this._b=r,this.population=i,this.proportion=n}rgb(){return{r:this._r,g:this._g,b:this._b}}hex(){const e=e=>e.toString(16).padStart(2,"0");return`#${e(this._r)}${e(this._g)}${e(this._b)}`}hsl(){return this._hsl||(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 d=0,c=0;if(s!==a){const e=s-a;c=l>.5?e/(2-s-a):e/(s+a),d=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*d),s:Math.round(100*c),l:Math.round(100*l)}}(this._r,this._g,this._b)),this._hsl}oklch(){return this._oklch||(this._oklch=At(this._r,this._g,this._b)),this._oklch}css(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:return`rgb(${this._r}, ${this._g}, ${this._b})`}}array(){return[this._r,this._g,this._b]}toString(){return this.hex()}get textColor(){return this.isDark?"#ffffff":"#000000"}get luminance(){return void 0===this._luminance&&(this._luminance=function(e,t,r){const i=e=>{const t=e/255;return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)};return.2126*i(e)+.7152*i(t)+.0722*i(r)}(this._r,this._g,this._b)),this._luminance}get isDark(){return this.luminance<=.179}get isLight(){return!this.isDark}get contrast(){if(!this._contrast){const e=this.luminance,t=jt(e,1),r=jt(e,0),i=this.isDark?zt(255,255,255,0,0):zt(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 Bt(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"}}function Ht(e,t,r,i){const{ignoreWhite:n=!0,whiteThreshold:o=250,alphaThreshold:s=125,minSaturation:a=0}=i,l=[];for(let d=0;d<t;d+=r){const t=4*d,r=e[t],i=e[t+1],c=e[t+2],u=e[t+3];if(!(void 0!==u&&u<s||n&&r>o&&i>o&&c>o)){if(a>0){const e=Math.max(r,i,c);if(0===e||(e-Math.min(r,i,c))/e<a)continue}l.push([r,i,c])}}return l}function Vt(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)]}function Wt(e,t,r,i,n){const o=t*r,s={ignoreWhite:i.ignoreWhite,whiteThreshold:i.whiteThreshold,alphaThreshold:i.alphaThreshold,minSaturation:i.minSaturation};let a,l=Ht(e,o,i.quality,s);if(0===l.length&&(l=Ht(e,o,i.quality,{...s,ignoreWhite:!1})),0===l.length&&(l=Ht(e,o,i.quality,{...s,ignoreWhite:!1,alphaThreshold:0})),"oklch"===i.colorSpace){const e=function(e){const t=new Array(e.length);for(let r=0;r<e.length;r++){const[i,n,o]=e[r],{l:s,c:a,h:l}=At(i,n,o);t[r]=[Math.round(255*s),Math.round(a/.4*255),Math.round(l/360*255)]}return t}(l);a=n.quantize(e,i.colorCount).map(({color:[e,t,r],population:i})=>({color:qt(e/255,t/255*.4,r/255*360),population:i}))}else a=n.quantize(l,i.colorCount);if(a.length>0){const e=a.reduce((e,t)=>e+t.population,0);return a.map(({color:[t,r,i],population:n})=>zt(t,r,i,n,e>0?n/e:0))}const d=Vt(e,o,i.quality);return d?[zt(d[0],d[1],d[2],1,1)]:null}Pt({},{computeFallbackColor:()=>Vt,createPixelArray:()=>Ht,extractPalette:()=>Wt,validateOptions:()=>Bt});var Gt,Xt=It({"src/pipeline.ts"(){$t(),Lt()}});Pt({},{BrowserPixelLoader:()=>Gt});var Yt,Kt,Qt,Jt,Zt,er=It({"src/loaders/browser.ts"(){Gt=class{async load(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)return this.loadFromImage(e);if("undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement)return this.loadFromCanvas(e);if("undefined"!=typeof ImageData&&e instanceof ImageData)return{data:e.data,width:e.width,height:e.height};if("undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement)return this.loadFromVideo(e);if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return this.loadFromImageBitmap(e);if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return this.loadFromOffscreenCanvas(e);throw new Error("Unsupported source type. Expected HTMLImageElement, HTMLCanvasElement, HTMLVideoElement, ImageData, ImageBitmap, or OffscreenCanvas.")}loadFromImage(e){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.");const t=document.createElement("canvas"),r=t.getContext("2d"),i=t.width=e.naturalWidth,n=t.height=e.naturalHeight;r.drawImage(e,0,0,i,n);try{return{data:r.getImageData(0,0,i,n).data,width:i,height:n}}catch(o){if(o instanceof DOMException&&"SecurityError"===o.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=o,e}throw o}}loadFromCanvas(e){const t=e.getContext("2d"),{width:r,height:i}=e;return{data:t.getImageData(0,0,r,i).data,width:r,height:i}}loadFromVideo(e){if(e.readyState<2)throw new Error('Video is not ready. Wait for the "loadeddata" or "canplay" event before calling getColor/getPalette.');const t=e.videoWidth,r=e.videoHeight;if(!t||!r)throw new Error("Video has no dimensions. It may not have loaded successfully.");const i=document.createElement("canvas"),n=i.getContext("2d");return i.width=t,i.height=r,n.drawImage(e,0,0,t,r),{data:n.getImageData(0,0,t,r).data,width:t,height:r}}loadFromOffscreenCanvas(e){const t=e.getContext("2d");if(!t)throw new Error("Could not get 2D context from OffscreenCanvas.");const{width:r,height:i}=e;return{data:t.getImageData(0,0,r,i).data,width:r,height:i}}loadFromImageBitmap(e){const t=document.createElement("canvas"),r=t.getContext("2d");return t.width=e.width,t.height=e.height,r.drawImage(e,0,0),{data:r.getImageData(0,0,e.width,e.height).data,width:e.width,height:e.height}}}}}),tr=It({"src/worker/worker-script.ts"(){Yt="\n'use strict';\n\n// -------------------------------------------------------------------------\n// Inlined MMCQ (Modified Median Cut Quantization)\n// -------------------------------------------------------------------------\n\nvar SIGBITS = 5;\nvar RSHIFT = 3;\nvar MAX_ITER = 1000;\nvar FRACT_POP = 0.75;\nvar HISTO_SIZE = 32768;\n\nfunction colorIndex(r, g, b) {\n return (r << 10) + (g << 5) + b;\n}\n\nfunction getHisto(pixels) {\n var h = new Uint32Array(HISTO_SIZE);\n for (var i = 0; i < pixels.length; i++) {\n var p = pixels[i];\n h[colorIndex(p[0] >> RSHIFT, p[1] >> RSHIFT, p[2] >> RSHIFT)]++;\n }\n return h;\n}\n\nfunction VBox(r1, r2, g1, g2, b1, b2, histo) {\n this.r1 = r1; this.r2 = r2;\n this.g1 = g1; this.g2 = g2;\n this.b1 = b1; this.b2 = b2;\n this.histo = histo;\n this._count = -1;\n this._volume = -1;\n this._avg = null;\n}\n\nVBox.prototype.volume = function(force) {\n if (this._volume < 0 || force) {\n this._volume = (this.r2 - this.r1 + 1) * (this.g2 - this.g1 + 1) * (this.b2 - this.b1 + 1);\n }\n return this._volume;\n};\n\nVBox.prototype.count = function(force) {\n if (this._count < 0 || force) {\n var n = 0;\n for (var i = this.r1; i <= this.r2; i++)\n for (var j = this.g1; j <= this.g2; j++)\n for (var k = this.b1; k <= this.b2; k++)\n n += this.histo[colorIndex(i, j, k)] || 0;\n this._count = n;\n }\n return this._count;\n};\n\nVBox.prototype.copy = function() {\n return new VBox(this.r1, this.r2, this.g1, this.g2, this.b1, this.b2, this.histo);\n};\n\nVBox.prototype.avg = function(force) {\n if (!this._avg || force) {\n var mult = 1 << RSHIFT;\n if (this.r1 === this.r2 && this.g1 === this.g2 && this.b1 === this.b2) {\n this._avg = [this.r1 << RSHIFT, this.g1 << RSHIFT, this.b1 << RSHIFT];\n } else {\n var ntot = 0, rsum = 0, gsum = 0, bsum = 0;\n for (var i = this.r1; i <= this.r2; i++)\n for (var j = this.g1; j <= this.g2; j++)\n for (var k = this.b1; k <= this.b2; k++) {\n var hval = this.histo[colorIndex(i, j, k)] || 0;\n ntot += hval;\n rsum += hval * (i + 0.5) * mult;\n gsum += hval * (j + 0.5) * mult;\n bsum += hval * (k + 0.5) * mult;\n }\n this._avg = ntot\n ? [~~(rsum / ntot), ~~(gsum / ntot), ~~(bsum / ntot)]\n : [~~(mult * (this.r1 + this.r2 + 1) / 2), ~~(mult * (this.g1 + this.g2 + 1) / 2), ~~(mult * (this.b1 + this.b2 + 1) / 2)];\n }\n }\n return this._avg;\n};\n\nfunction PQueue(comparator) {\n this.contents = [];\n this.sorted = false;\n this.comparator = comparator;\n}\n\nPQueue.prototype.push = function(item) { this.contents.push(item); this.sorted = false; };\nPQueue.prototype.pop = function() {\n if (!this.sorted) { this.contents.sort(this.comparator); this.sorted = true; }\n return this.contents.pop();\n};\nPQueue.prototype.size = function() { return this.contents.length; };\n\nfunction vboxFromPixels(pixels, histo) {\n var rmin = 1e6, rmax = 0, gmin = 1e6, gmax = 0, bmin = 1e6, bmax = 0;\n for (var i = 0; i < pixels.length; i++) {\n var p = pixels[i];\n var rv = p[0] >> RSHIFT, gv = p[1] >> RSHIFT, bv = p[2] >> RSHIFT;\n if (rv < rmin) rmin = rv; if (rv > rmax) rmax = rv;\n if (gv < gmin) gmin = gv; if (gv > gmax) gmax = gv;\n if (bv < bmin) bmin = bv; if (bv > bmax) bmax = bv;\n }\n return new VBox(rmin, rmax, gmin, gmax, bmin, bmax, histo);\n}\n\nfunction medianCutApply(histo, vbox) {\n if (!vbox.count()) return undefined;\n if (vbox.count() === 1) return [vbox.copy(), null];\n\n var rw = vbox.r2 - vbox.r1 + 1;\n var gw = vbox.g2 - vbox.g1 + 1;\n var bw = vbox.b2 - vbox.b1 + 1;\n var maxw = Math.max(rw, gw, bw);\n var total = 0;\n var partialsum = [];\n var lookaheadsum = [];\n var i, j, k, sum;\n\n if (maxw === rw) {\n for (i = vbox.r1; i <= vbox.r2; i++) {\n sum = 0;\n for (j = vbox.g1; j <= vbox.g2; j++)\n for (k = vbox.b1; k <= vbox.b2; k++)\n sum += histo[colorIndex(i, j, k)] || 0;\n total += sum; partialsum[i] = total;\n }\n } else if (maxw === gw) {\n for (i = vbox.g1; i <= vbox.g2; i++) {\n sum = 0;\n for (j = vbox.r1; j <= vbox.r2; j++)\n for (k = vbox.b1; k <= vbox.b2; k++)\n sum += histo[colorIndex(j, i, k)] || 0;\n total += sum; partialsum[i] = total;\n }\n } else {\n for (i = vbox.b1; i <= vbox.b2; i++) {\n sum = 0;\n for (j = vbox.r1; j <= vbox.r2; j++)\n for (k = vbox.g1; k <= vbox.g2; k++)\n sum += histo[colorIndex(j, k, i)] || 0;\n total += sum; partialsum[i] = total;\n }\n }\n\n partialsum.forEach(function(d, idx) { lookaheadsum[idx] = total - d; });\n\n function doCut(color) {\n var dim1 = color + '1', dim2 = color + '2';\n for (var i = vbox[dim1]; i <= vbox[dim2]; i++) {\n if (partialsum[i] > total / 2) {\n var vbox1 = vbox.copy(), vbox2 = vbox.copy();\n var left = i - vbox[dim1], right = vbox[dim2] - i;\n var d2 = left <= right\n ? Math.min(vbox[dim2] - 1, ~~(i + right / 2))\n : Math.max(vbox[dim1], ~~(i - 1 - left / 2));\n while (!partialsum[d2]) d2++;\n var count2 = lookaheadsum[d2];\n while (!count2 && partialsum[d2 - 1]) count2 = lookaheadsum[--d2];\n vbox1[dim2] = d2;\n vbox2[dim1] = d2 + 1;\n return [vbox1, vbox2];\n }\n }\n }\n\n if (maxw === rw) return doCut('r');\n if (maxw === gw) return doCut('g');\n return doCut('b');\n}\n\nfunction iterate(pq, target, histo) {\n var ncolors = pq.size(), niters = 0;\n while (niters < MAX_ITER) {\n if (ncolors >= target) return;\n niters++;\n var vbox = pq.pop();\n if (!vbox.count()) { pq.push(vbox); continue; }\n var result = medianCutApply(histo, vbox);\n if (!result || !result[0]) return;\n pq.push(result[0]);\n if (result[1]) { pq.push(result[1]); ncolors++; }\n }\n}\n\nfunction quantize(pixels, maxColors) {\n if (!pixels.length || maxColors < 2 || maxColors > 256) return [];\n\n var histo = getHisto(pixels);\n var vbox = vboxFromPixels(pixels, histo);\n var pq = new PQueue(function(a, b) { return a.count() - b.count(); });\n pq.push(vbox);\n iterate(pq, FRACT_POP * maxColors, histo);\n\n var pq2 = new PQueue(function(a, b) { return a.count() * a.volume() - b.count() * b.volume(); });\n while (pq.size()) pq2.push(pq.pop());\n iterate(pq2, maxColors, histo);\n\n var results = [];\n while (pq2.size()) {\n var box = pq2.pop();\n results.push({ color: box.avg(), population: box.count() });\n }\n return results;\n}\n\n// -------------------------------------------------------------------------\n// Worker message handler\n// -------------------------------------------------------------------------\n\nself.onmessage = function (e) {\n var data = e.data;\n var id = data.id;\n try {\n var palette = quantize(data.pixels, data.maxColors);\n self.postMessage({ id: id, palette: palette });\n } catch (err) {\n self.postMessage({ id: id, error: err.message || 'Unknown worker error' });\n }\n};\n"}});function rr(){return"undefined"!=typeof Worker}function ir(e,t,r){return new Promise((i,n)=>{if(r?.aborted)return void n(r.reason??new DOMException("Aborted","AbortError"));const o=Jt++;Zt.set(o,{resolve:i,reject:n});const s=()=>{Zt.delete(o),n(r.reason??new DOMException("Aborted","AbortError"))};r?.addEventListener("abort",s,{once:!0});try{(function(){if(Kt)return Kt;if(!rr())throw new Error("Web Workers are not supported in this environment.");return Qt=URL.createObjectURL(new Blob([Yt],{type:"application/javascript"})),(Kt=new Worker(Qt)).onmessage=e=>{const{id:t,palette:r,error:i}=e.data,n=Zt.get(t);if(n)if(Zt.delete(t),i)n.reject(new Error(i));else{const e=r,t=e.reduce((e,t)=>e+t.population,0),i=e.map(({color:[e,r,i],population:n})=>zt(e,r,i,n,t>0?n/t:0));n.resolve(i)}},Kt.onerror=e=>{for(const[,t]of Zt)t.reject(new Error(e.message));Zt.clear()},Kt})().postMessage({id:o,pixels:e,maxColors:t})}catch(a){Zt.delete(o),r?.removeEventListener("abort",s),n(a)}})}function nr(){Kt&&(Kt.terminate(),Kt=null),Qt&&(URL.revokeObjectURL(Qt),Qt=null);for(const[,e]of Zt)e.reject(/* @__PURE__ */new Error("Worker terminated"));Zt.clear()}function or(e,t,r){return(e<<10)+(t<<5)+r}Pt({},{extractInWorker:()=>ir,isWorkerSupported:()=>rr,terminateWorker:()=>nr}),It({"src/worker/manager.ts"(){$t(),tr(),Kt=null,Qt=null,Jt=0,Zt=/* @__PURE__ */new Map}}),Xt(),Xt(),$t(),zt(255,255,255,0),zt(0,0,0,0);var sr=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[or(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[or(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}},ar=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 lr(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 d=t.r1;d<=t.r2;d++){let r=0;for(let i=t.g1;i<=t.g2;i++)for(let n=t.b1;n<=t.b2;n++)r+=e[or(d,i,n)]||0;s+=r,a[d]=s}else if(o===i)for(let d=t.g1;d<=t.g2;d++){let r=0;for(let i=t.r1;i<=t.r2;i++)for(let n=t.b1;n<=t.b2;n++)r+=e[or(i,d,n)]||0;s+=r,a[d]=s}else for(let d=t.b1;d<=t.b2;d++){let r=0;for(let i=t.r1;i<=t.r2;i++)for(let n=t.g1;n<=t.g2;n++)r+=e[or(i,n,d)]||0;s+=r,a[d]=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],d=t[i]-n;let c;for(c=s<=d?Math.min(t[i]-1,~~(n+d/2)):Math.max(t[r],~~(n-1-s/2));!a[c];)c++;let u=l[c];for(;!u&&a[c-1];)u=l[--c];return e[i]=c,o[r]=e[i]+1,[e,o]}}(o===r?"r":o===i?"g":"b")}function dr(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=lr(r,o);if(!s||!s[0])return;e.push(s[0]),s[1]&&(e.push(s[1]),i++)}}er(),Xt(),new Gt;var cr=new class{async init(){}quantize(e,t){return function(e,t){if(!e.length||t<2||t>256)return[];const r=/* @__PURE__ */new Set,i=[];for(const d of e){const e=d.join(",");r.has(e)||(r.add(e),i.push(d))}if(i.length<=t){const t=/* @__PURE__ */new Map;for(const r of e){const e=r.join(",");t.set(e,(t.get(e)||0)+1)}return i.map(e=>({color:e,population:t.get(e.join(","))}))}const n=function(e){const t=new Uint32Array(32768);for(const r of e)t[or(r[0]>>3,r[1]>>3,r[2]>>3)]++;return t}(e),o=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,d=l[2]>>3;e<r?r=e:e>i&&(i=e),t<n?n=t:t>o&&(o=t),d<s?s=d:d>a&&(a=d)}return new sr(r,i,n,o,s,a,t)}(e,n),s=new ar((e,t)=>e.count()-t.count());s.push(o),dr(s,.75*t,n);const a=new ar((e,t)=>e.count()*e.volume()-t.count()*t.volume());for(;s.size();)a.push(s.pop());dr(a,t,n);const l=[];for(;a.size();){const e=a.pop();l.push({color:e.avg(),population:e.count()})}return l}(e,t)}};function ur(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 l=a.getImageData(0,0,n,o),d={};try{d.blurhash=I(l.data,n,o,4,4)}catch(c){console.warn("[media-intrinsics] blurhash encode failed:",c)}try{const e=function(e,t){const r=Bt(t??{}),i=t?.quantizer??cr,n=function(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)return function(e){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.");const t=document.createElement("canvas"),r=t.getContext("2d"),i=t.width=e.naturalWidth,n=t.height=e.naturalHeight;r.drawImage(e,0,0,i,n);try{return{data:r.getImageData(0,0,i,n).data,width:i,height:n}}catch(o){if(o instanceof DOMException&&"SecurityError"===o.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=o,e}throw o}}(e);if("undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement)return function(e){const t=e.getContext("2d"),{width:r,height:i}=e;return{data:t.getImageData(0,0,r,i).data,width:r,height:i}}(e);if("undefined"!=typeof ImageData&&e instanceof ImageData)return{data:e.data,width:e.width,height:e.height};if("undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement)return function(e){if(e.readyState<2)throw new Error('Video is not ready. Wait for the "loadeddata" or "canplay" event before calling getColorSync/getPaletteSync.');const t=e.videoWidth,r=e.videoHeight;if(!t||!r)throw new Error("Video has no dimensions. It may not have loaded successfully.");const i=document.createElement("canvas"),n=i.getContext("2d");return i.width=t,i.height=r,n.drawImage(e,0,0,t,r),{data:n.getImageData(0,0,t,r).data,width:t,height:r}}(e);if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return function(e){const t=document.createElement("canvas"),r=t.getContext("2d");return t.width=e.width,t.height=e.height,r.drawImage(e,0,0),{data:r.getImageData(0,0,e.width,e.height).data,width:e.width,height:e.height}}(e);if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return function(e){const t=e.getContext("2d");if(!t)throw new Error("Could not get 2D context from OffscreenCanvas.");const{width:r,height:i}=e;return{data:t.getImageData(0,0,r,i).data,width:r,height:i}}(e);throw new Error("Unsupported source type. Expected HTMLImageElement, HTMLCanvasElement, HTMLVideoElement, ImageData, ImageBitmap, or OffscreenCanvas.")}(e);return Wt(n.data,n.width,n.height,r,i)}(s,{colorCount:5});e&&(d.colors={palette:e.map(e=>e.hex())})}catch(c){console.warn("[media-intrinsics] palette extraction failed:",c)}return d}function hr(e,t){return Object.hasOwn(e,t)}$t();var{AbortController:pr}=globalThis,{AbortSignal:mr}=globalThis,gr=(e="Aborted",t)=>{const r=new DOMException(e,"AbortError");return null!=t&&hr(t,"cause")&&Object.defineProperty(r,"cause",{__proto__:null,configurable:!0,writable:!0,value:t.cause}),r},fr=class extends Error{isNetworkError;cause;constructor(e,t){super(e),this.cause=t?.cause,this.cause&&hr(this.cause,"isNetworkError")?this.isNetworkError=this.cause.isNetworkError:this.isNetworkError=!1}},vr=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 br(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 yr={__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 wr(e){if(e.type)return e.type;const t=e.name?br(e.name).extension?.toLowerCase():null;return t&&t in yr?yr[t]:"application/octet-stream"}function xr(e){let t="";return e.replace(/[^A-Z0-9]/gi,e=>(t+=`-${function(e){return e.charCodeAt(0).toString(32)}(e)}`,"/"))+t}function Sr(e,t){return!0===e?Object.keys(t):Array.isArray(e)?e:[]}function Tr(e){return e<10?`0${e}`:e.toString()}function Cr(){const e=/* @__PURE__ */new Date;return`${Tr(e.getHours())}:${Tr(e.getMinutes())}:${Tr(e.getSeconds())}`}function Fr(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 kr=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.#d())}#d(){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}#c(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.#c(e,t)}wrapSyncFunction(e,t){return(...r)=>{const i=this.run(()=>(e(...r),queueMicrotask(()=>i.done()),()=>{}),t);return{abortOn:Fr,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=Fr,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 Er(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 _r(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=Er(i,new RegExp(`%\\{${n}\\}`,"g"),e)}return i}var Mr=e=>{throw new Error(`missing string: ${e}`)},Ur=class{locale;constructor(e,{onMissingKey:t=Mr}={}){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 _r(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 _r(r,t)}},Rr=class extends Error{name="UserFacingApiError"},Ir=/* @__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}}),Pr=/* @__PURE__ */t(e=>{var t=Ir();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}}}),Or=/* @__PURE__ */t((e,t)=>{t.exports=Pr()}),Nr=Object.prototype.toString,Ar=/* @__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 qr=/* @__PURE__ */e(Or(),1),Dr=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}},Lr=(e,t,r)=>{const i=r.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=i,e};async function jr(e,t){return new Promise((r,i)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;const n=qr.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 Dr)throw a.originalError;if(a instanceof TypeError&&!function(e){if(!e||(t=e,"[object Error]"!==Nr.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(")"))||Ar.has(r)}(a))throw a;if(Lr(a,o,t),await t.shouldRetry(a)||(n.stop(),i(a)),await t.onFailedAttempt(a),!n.retry(a))throw n.mainError()}catch(l){Lr(l,o,t),s(),i(l)}}})})}var zr=class extends Error{isAuthError;constructor(){super("Authorization required"),this.name="AuthError",this.isAuthError=!0}},$r=class extends Error{statusCode;constructor({statusCode:e,message:t}){super(t),this.name="HttpError",this.statusCode=e}},Br=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 vr(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 zr;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 Rr(t.message);throw new $r({statusCode:e.status,message:r})}(s)}catch(o){if(o.isAuthError||"UserFacingApiError"===o.name||"AbortError"===o.name)throw o;throw new fr(`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 jr(async()=>{const r=this.uppy.getFile(e.id)?.serverToken;if(null!=r)return this.uppy.log(`Connecting to exiting websocket ${r}`),this.#b({file:e,queue:n(),signal:i});const o=await n().wrapPromiseFunction(async(...e)=>{try{return await this.#y(...e)}catch(t){if(t.isAuthError)throw new Dr(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 Dr(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.#b({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}}#y=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#b({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 d,c,u,{isPaused:h}=e;const p=(t,r)=>{null!=d&&d.readyState===d.OPEN?d.send(JSON.stringify({action:t,payload:r??{}})):this.uppy.log(`Cannot send "${t}" to socket ${e.id} because the socket state was ${String(d?.readyState)}`,"warning")};function m(){n.resumableUploads&&p(h?"pause":"resume")}const g=e=>{n.resumableUploads&&(h=e,d&&m())},f=t=>{n.individualCancellation&&t.id===e.id&&(p("cancel"),c?.abort?.(),this.uppy.log(`upload ${e.id} was removed`),o())},v=()=>{p("cancel"),c?.abort?.(),this.uppy.log(`upload ${e.id} was canceled`),o()},b=(t,r)=>{t?.id===e.id&&g(r)},y=()=>g(!0),w=()=>g(!1);this.uppy.on("file-removed",f),this.uppy.on("cancel-all",v),this.uppy.on("upload-pause",b),this.uppy.on("pause-all",y),this.uppy.on("resume-all",w),i=()=>{this.uppy.off("file-removed",f),this.uppy.off("cancel-all",v),this.uppy.off("upload-pause",b),this.uppy.off("pause-all",y),this.uppy.off("resume-all",w)},r.addEventListener("abort",()=>{c?.abort()}),(async()=>{c&&c.abort(),c=new AbortController;const r=t=>{this.uppy.setFileState(e.id,{serverToken:null}),c?.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 jr(async()=>new Promise((t,n)=>{d=new WebSocket(`${l}/api/${a}`),i(),d.addEventListener("close",()=>{d=void 0,n(/* @__PURE__ */new Error("Socket closed unexpectedly"))}),d.addEventListener("error",e=>{this.uppy.log(`Companion socket error ${JSON.stringify(e)}, closing socket`,"warning"),d?.close()}),d.addEventListener("open",()=>{m()}),d.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}),c?.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),d&&d.close(),d=void 0};c.signal.addEventListener("abort",()=>{s()})}),{retries:10,signal:c.signal,onFailedAttempt:()=>{c.signal.aborted||this.uppy.log(`Retrying websocket ${e.id}`)}})})().abortOn(c.signal)}catch(n){if(c.signal.aborted)return;r(n)}})()})}finally{i?.()}}},Hr=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 Ur([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(){}},Vr=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()})}},Wr={debug:()=>{},warn:()=>{},error:(...e)=>console.error(`[Uppy] [${Cr()}]`,...e)},Gr={debug:(...e)=>console.debug(`[Uppy] [${Cr()}]`,...e),warn:(...e)=>console.warn(`[Uppy] [${Cr()}]`,...e),error:(...e)=>console.error(`[Uppy] [${Cr()}]`,...e)},Xr=/* @__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}`}}),Yr=/* @__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}}),Kr=/* @__PURE__ */t((e,t)=>{var r=Yr(),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}}),Qr=/* @__PURE__ */e(Xr(),1),Jr=/* @__PURE__ */e(Kr(),1),Zr={maxFileSize:null,minFileSize:null,maxTotalFileSize:null,maxNumberOfFiles:null,minNumberOfFiles:null,allowedFileTypes:null,requiredMetaFields:[]},ei=class extends Error{isUserFacing;file;constructor(e,t){super(e),this.isUserFacing=t?.isUserFacing??!0,t?.file&&(this.file=t.file)}isRestriction=!0},ti=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 ei(`${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 ei(this.getI18n()("aggregateExceedsSize",{sizeAllowed:(0,Qr.default)(r),size:(0,Qr.default)(i)}))}}validateSingleFile(e){const{maxFileSize:t,minFileSize:r,allowedFileTypes:i}=this.getOpts().restrictions;if(i&&!i.some(t=>t.includes("/")?!!e.type&&(0,Jr.default)(e.type.replace(/;.*?$/,""),t):!("."!==t[0]||!e.extension)&&e.extension.toLowerCase()===t.slice(1).toLowerCase())){const t=i.join(", ");throw new ei(this.getI18n()("youCanOnlyUploadFileTypes",{types:t}),{file:e})}if(t&&null!=e.size&&e.size>t)throw new ei(this.getI18n()("exceedsSize",{size:(0,Qr.default)(t),file:e.name??this.getI18n()("unnamed")}),{file:e});if(r&&null!=e.size&&e.size<r)throw new ei(this.getI18n()("inferiorSize",{size:(0,Qr.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 ei(this.getI18n()("youHaveToAtLeastSelectX",{smart_count:t}))}getMissingRequiredMetaFields(e){const t=new ei(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}}},ri=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)})}},ii=/* @__PURE__ */t((e,t)=>{t.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}}),ni=/* @__PURE__ */t((e,t)=>{var r="object"==typeof global&&global&&global.Object===Object&&global;t.exports=r}),oi=/* @__PURE__ */t((e,t)=>{var r=ni(),i="object"==typeof self&&self&&self.Object===Object&&self,n=r||i||Function("return this")();t.exports=n}),si=/* @__PURE__ */t((e,t)=>{var r=oi();t.exports=function(){return r.Date.now()}}),ai=/* @__PURE__ */t((e,t)=>{var r=/\s/;t.exports=function(e){for(var t=e.length;t--&&r.test(e.charAt(t)););return t}}),li=/* @__PURE__ */t((e,t)=>{var r=ai(),i=/^\s+/;t.exports=function(e){return e?e.slice(0,r(e)+1).replace(i,""):e}}),di=/* @__PURE__ */t((e,t)=>{var r=oi().Symbol;t.exports=r}),ci=/* @__PURE__ */t((e,t)=>{var r=di(),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}}),ui=/* @__PURE__ */t((e,t)=>{var r=Object.prototype.toString;t.exports=function(e){return r.call(e)}}),hi=/* @__PURE__ */t((e,t)=>{var r=di(),i=ci(),n=ui(),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)}}),pi=/* @__PURE__ */t((e,t)=>{t.exports=function(e){return null!=e&&"object"==typeof e}}),mi=/* @__PURE__ */t((e,t)=>{var r=hi(),i=pi();t.exports=function(e){return"symbol"==typeof e||i(e)&&"[object Symbol]"==r(e)}}),gi=/* @__PURE__ */t((e,t)=>{var r=li(),i=ii(),n=mi(),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 d=s.test(e);return d||a.test(e)?l(e.slice(2),d?2:8):o.test(e)?NaN:+e}}),fi=/* @__PURE__ */t((e,t)=>{var r=ii(),i=si(),n=gi(),o=Math.max,s=Math.min;t.exports=function(e,t,a){var l,d,c,u,h,p,m=0,g=!1,f=!1,v=!0;if("function"!=typeof e)throw new TypeError("Expected a function");function b(t){var r=l,i=d;return l=d=void 0,m=t,u=e.apply(i,r)}function y(e){var r=e-p;return void 0===p||r>=t||r<0||f&&e-m>=c}function w(){var e=i();if(y(e))return x(e);h=setTimeout(w,function(e){var r=t-(e-p);return f?s(r,c-(e-m)):r}(e))}function x(e){return h=void 0,v&&l?b(e):(l=d=void 0,u)}function S(){var e=i(),r=y(e);if(l=arguments,d=this,p=e,r){if(void 0===h)return function(e){return m=e,h=setTimeout(w,t),g?b(e):u}(p);if(f)return clearTimeout(h),h=setTimeout(w,t),b(p)}return void 0===h&&(h=setTimeout(w,t)),u}return t=n(t)||0,r(a)&&(g=!!a.leading,c=(f="maxWait"in a)?o(n(a.maxWait)||0,t):c,v="trailing"in a?!!a.trailing:v),S.cancel=function(){void 0!==h&&clearTimeout(h),m=0,l=p=d=h=void 0},S.flush=function(){return void 0===h?u:x(i())},S}}),vi=/* @__PURE__ */t((e,t)=>{var r=fi(),i=ii();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})}}),bi=/* @__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}}),yi={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 wi(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 xi=/* @__PURE__ */e(vi(),1),Si=/* @__PURE__ */e(bi(),1),Ti={totalProgress:0,allowNewUpload:!0,error:null,recoveredState:null},Ci=class e{static VERSION="5.2.0";#C=Object.create(null);#F;#k;#E=(0,Si.default)();#_=/* @__PURE__ */new Set;#M=/* @__PURE__ */new Set;#U=/* @__PURE__ */new Set;defaultLocale;locale;opts;store;i18n;i18nArray;scheduledAutoProceed=null;wasOffline=!1;constructor(t){this.defaultLocale=yi;const r={id:"uppy",autoProceed:!1,allowMultipleUploadBatches:!0,debug:!1,restrictions:Zr,meta:{},onBeforeFileAdded:(e,t)=>!Object.hasOwn(t,e.id),onBeforeUpload:e=>e,store:new ri,logger:Wr,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=Gr),this.log(`Using Core v${e.VERSION}`),this.i18nInit(),this.store=this.opts.store,this.setState({...Ti,plugins:{},files:{},currentUploads:{},capabilities:{uploadProgress:wi(),individualCancellation:!0,resumableUploads:!1},meta:{...this.opts.meta},info:[]}),this.#F=new ti(()=>this.opts,()=>this.i18n),this.#k=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 Ur([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,...Ti})}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({...Ti,files:{}})}addPreProcessor(e){this.#_.add(e)}removePreProcessor(e){return this.#_.delete(e)}addPostProcessor(e){this.#U.add(e)}removePostProcessor(e){return this.#U.delete(e)}addUploader(e){this.#M.add(e)}removeUploader(e){return this.#M.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=[],d=[],c=[],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&&d.push(p),p.error&&c.push(p),(e.preprocess||e.postprocess)&&h.push(p)}return{newFiles:o,startedFiles:s,uploadStartedFiles:a,pausedFiles:l,completeFiles:d,erroredFiles:c,inProgressFiles:n,inProgressNotPausedFiles:u,processingFiles:h,isUploadStarted:a.length>0,isAllComplete:100===t&&d.length===i.length&&0===h.length,isAllErrored:!!r&&c.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}#P(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)}#O(e){let t=!0;for(const r of Object.values(e))this.#P(r)||(t=!1);return t}#N(e){const{allowNewUpload:t}=this.getState();if(!1===t){const t=new ei(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=wr(t),i=function(e,t){return t.name?t.name:"image"===e.split("/")[0]?`${e.split("/")[0]}.${e.split("/")[1]}`:"noname"}(r,t),n=br(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=wr(e);return function(e,t){let r=t||"uppy";return"string"==typeof e.name&&(r+=`-${xr(e.name.toLowerCase())}`),void 0!==e.type&&(r+=`-${e.type}`),e.meta&&"string"==typeof e.meta.relativePath&&(r+=`-${xr(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.#N(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 ei(this.i18n("noDuplicates",{fileName:e.name??this.i18n("unnamed")}),{file:e});if(!1===a&&!o)throw new ei("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")}#j(){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#z(){const e=this.#j(),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.#z();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(Ti)}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,xi.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.#P(e)}),"undefined"!=typeof window&&window.addEventListener&&(window.addEventListener("online",this.#G),window.addEventListener("offline",this.#G),setTimeout(this.#G,3e3))}updateOnlineStatus(){window.navigator.onLine??1?(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.#k(),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.#_,...this.#M,...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.#j().length>0){const t=await this.#z();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.#O(e))throw new ei(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 Fi({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 ki=new TextEncoder,Ei={name:"HMAC",hash:"SHA-256"};async function _i(e){const{subtle:t}=globalThis.crypto;return t.digest(Ei.hash,ki.encode(e))}function Mi(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 Ui(e,t){const{subtle:r}=globalThis.crypto;return r.sign(Ei,await async function(e){const{subtle:t}=globalThis.crypto;return t.importKey("raw","string"==typeof e?ki.encode(e):e,Ei,!1,["sign"])}(e),ki.encode(t))}async function Ri({accountKey:e,accountSecret:t,sessionToken:r,bucketName:i,Key:n,Region:o,expires:s,uploadId:a,partNumber:l}){const d="s3",c=`${d}.${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}/${d}/aws4_request`,f=new URL(`https://${c}${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,Mi(await _i(Fi({CanonicalUri:u,CanonicalQueryString:f.search.slice(1),SignedHeaders:{host:c},HashedPayload:h})))].join("\n"),b=Mi(await Ui(await Ui(await Ui(await Ui(await Ui(`AWS4${t}`,m),o),d),"aws4_request"),v));return f.searchParams.set("X-Amz-Signature",b),f}var Ii={getChunkSize:e=>Math.ceil(e.size/1e4),onProgress(){},onPartComplete(){},onSuccess(){},onError(e){throw e}},Pi=Symbol("pausing upload, not an actual error"),Oi=class{options;#Q=new pr;#J=[];#Z=[];#ee;#te;#re=!1;#ie;#ne;#oe;#se;#ae=e=>e?.cause===Pi?null:this.#ie(e);#le=1e4;#de=5242880;constructor(e,t){this.options={...Ii,...t},this.options.getChunkSize??=Ii.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.#ce()}#ce(){const e=this.#ee.size,t="function"==typeof this.#oe?this.#oe(this.#te):Boolean(this.#oe);if(t&&e>this.#de){let r=Math.max(this.options.getChunkSize(this.#ee),this.#de),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(Pi),this.#Q=new pr,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(Pi),this.#Q=new pr}abort(e){e?.really?this.#me():this.pause()}[Symbol.for("uppy test: getChunkState")](){return this.#Z}};function Ni(e){if(e?.aborted)throw gr("The operation was aborted",{cause:e.reason})}function Ai(e){const t=new URL(e);return t.search="",t.hash="",t.href}var qi=class{#ge;#fe=/* @__PURE__ */new WeakMap;#ve;#be;#ye;#we;#xe;#Se;#Te;#Ce;#Fe;#ke;#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.#be=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.#ke=t.wrapPromiseFunction(e.uploadPartBytes,{priority:1/0})),"getUploadParameters"in e&&(this.#ye=t.wrapPromiseFunction(e.getUploadParameters))}async#_e(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#Me(e,t,r){const{method:i="POST",url:n,fields:o,headers:s}=await this.#ye(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:d,onComplete:c}=t,u=await this.#ke({signature:{url:n,headers:s,method:i},body:a,size:l.size,onProgress:d,onComplete:c,signal:r}).abortOn(r),h=o?.key;return this.#Fe(e,{key:h}),{...u,location:u.location??Ai(n),bucket:o?.bucket,key:h}}async uploadFile(e,t,r){if(Ni(r),1===t.length&&!t[0].shouldUseMultipart)return this.#Me(e,t[0],r);const{uploadId:i,key:n}=await this.getUploadId(e,r);Ni(r);try{const o=await Promise.all(t.map((t,i)=>this.uploadChunk(e,i+1,t,r)));return Ni(r),await this.#Ce(this.#Ee(e),{key:n,uploadId:i,parts:o,signal:r},r).abortOn(r)}catch(o){throw o?.cause!==Pi&&"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(Ni(r),1===t.length&&null!=t[0]&&!t[0].shouldUseMultipart)return this.#Me(e,t[0],r);const{uploadId:i,key:n}=await this.getUploadId(e,r);Ni(r);const o=await this.#we(this.#Ee(e),{uploadId:i,key:n,signal:r},r).abortOn(r);Ni(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 Ni(r),this.#Ce(this.#Ee(e),{key:n,uploadId:i,parts:s,signal:r},r).abortOn(r)}async uploadChunk(e,t,r,i){Ni(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(;;){Ni(i);const s=r.getData(),{onProgress:c,onComplete:u}=r;let h;try{h=await this.#be(this.#Ee(e),{uploadId:n,key:o,partNumber:t,body:s,signal:i}).abortOn(i)}catch(d){const e=l();if(null==e||i.aborted)throw d;await new Promise(t=>setTimeout(t,e));continue}Ni(i);try{return{PartNumber:t,...await this.#ke({signature:h,body:s,size:s.size,onProgress:c,onComplete:u,signal:i}).abortOn(i)}}catch(d){if(!(await this.#_e(d,a)))throw d}}}};function Di(e){if(e?.error){const t=new Error(e.message);throw Object.assign(t,e.error),t}return e}function Li(e){const t=e.Expiration;if(t){const e=Math.floor((new Date(t)-Date.now())/1e3);if(e>9)return e}}function ji({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 zi={allowedMetaFields:!0,limit:6,getTemporarySecurityCredentials:!1,shouldUseMultipart:e=>(e.size||0)>104857600,retryDelays:[0,1e3,3e3,5e3]},$i=class e extends Hr{static VERSION="5.1.0";#Ue;#Re;requests;uploaderEvents;uploaders;constructor(t,r){super(t,{...zi,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 kr(this.opts.limit),this.#Ue=new qi(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 Br(this.uppy,{pluginId:this.id,provider:"AWS",companionUrl:this.opts.endpoint,companionHeaders:this.opts.headers,companionCookiesRule:this.opts.cookiesRule}):("headers"in e&&this.#Pe(),"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)}#Oe(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.#Oe("createMultipartUpload"),Ni(t);const r=Sr(this.opts.allowedMetaFields,e.meta),i=ji({meta:e.meta,allowedMetaFields:r});return this.#Re.post("s3/multipart",{filename:e.name,type:e.type,metadata:i},{signal:t}).then(Di)}listParts(e,{key:t,uploadId:r,signal:i},n){i??=n,this.#Oe("listParts"),Ni(i);const o=encodeURIComponent(t);return this.#Re.get(`s3/multipart/${encodeURIComponent(r)}?key=${o}`,{signal:i}).then(Di)}completeMultipartUpload(e,{key:t,uploadId:r,parts:i,signal:n},o){n??=o,this.#Oe("completeMultipartUpload"),Ni(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(Di)}#Ne;async#Ae(e){if(Ni(e?.signal),null==this.#Ne){const{getTemporarySecurityCredentials:t}=this.opts;!0===t?(this.#Oe("getTemporarySecurityCredentials"),this.#Ne=this.#Re.get("s3/sts",e).then(Di)):this.#Ne=t(e),this.#Ne=await this.#Ne,setTimeout(()=>{this.#Ne=null},500*(Li(this.#Ne.credentials)||0))}return this.#Ne}async createSignedURL(e,t){const r=await this.#Ae(t),i=Li(r.credentials)||604800,{uploadId:n,key:o,partNumber:s}=t;return{method:"PUT",expires:i,fields:{},url:`${await Ri({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.#Oe("signPart"),Ni(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(Di)}abortMultipartUpload(e,{key:t,uploadId:r,signal:i}){this.#Oe("abortMultipartUpload");const n=encodeURIComponent(t),o=encodeURIComponent(r);return this.#Re.delete(`s3/multipart/${o}?key=${n}`,void 0,{signal:i}).then(Di)}getUploadParameters(e,t){this.#Oe("getUploadParameters");const{meta:r}=e,{type:i,name:n}=r,o=ji({meta:r,allowedMetaFields:Sr(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(Ni(l),null==e)throw new Error("Cannot upload to an undefined URL");return new Promise((d,c)=>{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(),c(gr())}),u.addEventListener("timeout",()=>{p();const e=/* @__PURE__ */new Error("Request has expired");e.source={status:403},c(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 c(e)}if(u.status<200||u.status>=300){const e=/* @__PURE__ */new Error("Non 2xx");return e.source=u,void c(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),d({...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,c(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 Oi(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 Vr(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.#je(!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.#je(!0),n};#Pe=()=>{this.#Re?.setCompanionHeaders(this.opts.headers)};#je=e=>{const{capabilities:t}=this.uppy.getState();this.uppy.setState({capabilities:{...t,resumableUploads:e}})};#ze=()=>{this.#je(!0)};install(){this.#je(!0),this.uppy.addPreProcessor(this.#Pe),this.uppy.addUploader(this.#Le),this.uppy.on("cancel-all",this.#ze)}uninstall(){this.uppy.removePreProcessor(this.#Pe),this.uppy.removeUploader(this.#Le),this.uppy.off("cancel-all",this.#ze)}},Bi="undefined"!=typeof window&&(window.indexedDB||window.webkitIndexedDB||window.mozIndexedDB||window.OIndexedDB||window.msIndexedDB),Hi=!!Bi,Vi="uppy-blobs",Wi="files",Gi=864e5,Xi=1048576;function Yi(e){const t=Bi.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(Wi,{keyPath:"id"}).createIndex("store","store",{unique:!1}),t.oldVersion<3){const e=i.objectStore(Wi);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()+Gi,t.update(r)}}(e)}i.oncomplete=()=>{e(r)}},t.onsuccess=t=>{e(t.target.result)},t.onerror=r})}function Ki(e){return new Promise((t,r)=>{e.onsuccess=e=>{t(e.target.result)},e.onerror=r})}var Qi=!1,Ji=class e{#$e;opts;name;static isSupported;constructor(t){this.opts={dbName:Vi,storeName:"default",expires:Gi,maxFileSize:10*Xi,maxTotalSize:300*Xi,...t},this.name=this.opts.storeName;const r=async()=>{const e=await Yi(this.opts.dbName);return this.#$e=e,e};Qi?this.#$e=r():(Qi=!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 Ki((await this.#$e).transaction([Wi],"readonly").objectStore(Wi).index("store").getAll(IDBKeyRange.only(this.name)));return Object.fromEntries(e.map(e=>[e.fileID,e.data]))}async get(e){const{data:t}=await Ki((await this.#$e).transaction([Wi],"readonly").objectStore(Wi).get(this.key(e)));return{id:t.fileID,data:t.data}}async getSize(){const e=(await this.#$e).transaction([Wi],"readonly").objectStore(Wi).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 Ki((await this.#$e).transaction([Wi],"readwrite").objectStore(Wi).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 Ki((await this.#$e).transaction([Wi],"readwrite").objectStore(Wi).delete(this.key(e)))}static async cleanup(){const e=await Yi(Vi),t=e.transaction([Wi],"readwrite").objectStore(Wi).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 Zi(e){try{return JSON.parse(e)}catch{return null}}Ji.isSupported=Hi;var en="uppyState:",tn=class{opts;name;#Be;constructor(e){var t;this.opts={expires:864e5,throttleTime:500,...e},this.name=(t=e.storeName,`${en}${t}`),this.#Be=0===this.opts.throttleTime?this.save:(0,xi.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(en)&&e.push(t)}const t=Date.now();e.forEach(e=>{const r=localStorage.getItem(e);if(!r)return;const i=Zi(r);i?.expires&&i.expires<t&&localStorage.removeItem(e)})}();const e=localStorage.getItem(this.name);if(!e)return;const t=Zi(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()}},rn="undefined"!=typeof navigator&&"serviceWorker"in navigator,nn=class{#$e;name;static isSupported;constructor(e){this.#$e=new Promise((e,t)=>{rn?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})}};nn.isSupported=rn;var on={expires:864e5,serviceWorker:!1},sn=class e extends Hr{static VERSION="5.2.1";#Ve;#We;#Ge;static[Symbol.for("uppy test: throttleTime")];constructor(t,r){super(t,{...on,...r}),this.type="debugger",this.id=this.opts.id||"GoldenRetriever",this.#Ve=new tn({expires:this.opts.expires,storeName:t.getID(),throttleTime:e[Symbol.for("uppy test: throttleTime")]??void 0}),this.opts.serviceWorker&&(this.#We=new nn({storeName:t.getID()})),this.#Ge=new Ji({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},d=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:d}),this.uppy.emit("restored",e.pluginData);const c=Object.keys(l).filter(e=>!i[e]);if(c.length)try{this.uppy.log(`[GoldenRetriever] Cleaning up ${c.length} old files`),await this.#Qe(c)}catch(u){this.uppy.log(`[GoldenRetriever] Could not clean up ${c.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)}},an=e=>408===e||429===e||e>=500,ln=(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)},dn=(e,t)=>{b(t instanceof Error?t:new Error(String(t)),{component:"useUpload",tags:["upload",e,"cleanup"]})};async function cn(e,t,r,i,n){let o="complete failed";for(let a=0;a<3;a+=1){const l=new AbortController,d=()=>l.abort(n?.reason);n?.addEventListener("abort",d,{once:!0});const c=setTimeout(()=>l.abort(),15e3);try{const n=await fetch(x.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||ln(n.status,s))return;if(o=s&&"object"==typeof s&&"string"==typeof s.error?`${s.error} (${n.status})`:`complete failed: ${n.status}`,!an(n.status))throw Object.assign(new Error(o),{retryable:!1})}catch(s){if(n?.aborted)throw s;if(o=s instanceof Error?s.message:String(s),!1===s.retryable)throw s}finally{clearTimeout(c),n?.removeEventListener("abort",d)}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 un(){const e=Ye(),t=v(),r=s(null),n=s(null),o=s(null),a=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()}}}(),l=s(null),d=s(null),c=s({}),u=s({}),h=s(void 0),m=s({}),g=s(!1);i(()=>{const e=t.user;h.current=e?.id??(e?._id?String(e._id):void 0),m.current={organizationId:t.props?.organizationId,token:e?.token}},[t.user,t.props?.organizationId]);const f=p(()=>{const{organizationId:e,token:t}=m.current,r={"Content-Type":"application/json"};return e&&(r["x-org-id"]=e),t&&(r.Authorization=`Bearer ${t}`),r},[]),y=p(({contentId:e,key:t})=>{e&&t&&fetch(x.UPLOAD_ABORT,{method:"POST",headers:f(),body:JSON.stringify({contentId:e,key:t})}).catch(e=>dn("abort",e))},[f]),w=p(()=>{if(!r.current){const t=new Ci({autoProceed:!0}).use(sn,{id:"GoldenRetriever",expires:864e5,serviceWorker:!1}).use($i,{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"}}}}),i=(t,r)=>{if(!t)return;const i=t.meta.uid;if(!a.isCurrentFile(i,t.id))return;e.getState().setUploadState(i,{status:"uploading",bytesUploaded:r.bytesUploaded??0,bytesTotal:r.bytesTotal??0});const o=Date.now(),s=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,(s-l.bytes)/t),i=l.speed>0?.7*l.speed+.3*r:r;n.current={time:o,bytes:s,speed:i},e.getState().setUploadSpeedBps(i)}}else n.current={time:o,bytes:s,speed:0}};t.on("upload-progress",i);const o=r=>{if(!r)return;const i=r.meta.uid,o=a.currentSession();if(!a.isCurrentFile(i,r.id))return;const s=r.meta.contentId,l=r.meta.key,c=r.meta.uploadStartedAt;(async()=>{try{if(await cn(s,l,c?Date.now()-c:void 0,f(),d.current?.signal),!a.isCurrentSession(o)||!a.isCurrentFile(i,r.id))return}catch(u){if(!a.isCurrentSession(o)||!a.isCurrentFile(i,r.id))return;return!1!==u.retryable&&t.setFileMeta(r.id,{completionPending:!0,completionContentId:s,completionKey:l}),e.getState().setUploadState(i,{status:"error",contentId:s,error:u instanceof Error?u.message:String(u)}),b(u instanceof Error?u:new Error(String(u)),{component:"useUpload",tags:["upload","complete"],extra:{uid:i,contentId:s}}),void(s&&!1===u.retryable&&fetch(x.UPLOAD_FAIL,{method:"POST",headers:f(),body:JSON.stringify({contentId:s})}).catch(e=>dn("fail",e)))}if(a.isCurrentSession(o)&&a.isCurrentFile(i,r.id)){e.getState().setUploadState(i,{status:"success",contentId:s}),a.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),!g.current)){g.current=!0;const t=Object.values(e.getState().uploadStates).filter(e=>"success"===e.status).length;t>0&&O.success(`${t} file${1===t?"":"s"} uploaded`)}}})()};t.on("upload-success",o);const s=(t,r)=>{if(!t)return;const i=t.meta.uid;if(!a.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(x.UPLOAD_FAIL,{method:"POST",headers:f(),body:JSON.stringify({contentId:o})}).catch(e=>dn("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",s);const c=a.currentSession(),u=()=>{if(!a.isCurrentSession(c))return;const{eventId:r}=e.getState(),i=[],n={},o={};t.getFiles().forEach(e=>{const s=e.meta,l=s.uid;if(!(l&&s.eventId===r&&s.userId===h.current&&"string"==typeof s.contentId&&"string"==typeof s.key&&"string"==typeof s.uploadUrl&&"string"==typeof s.rawContentType&&e.data instanceof Blob)){try{t.removeFile(e.id)}catch{}return}a.registerFile(l,{uid:l,fileId:e.id,session:a.currentSession(),contentId:"string"==typeof s.contentId?s.contentId:"",key:"string"==typeof s.key?s.key:""});const d=e.data instanceof File?e.data:new File([e.data],e.name,{type:e.type});i.push({uid:l,file:d}),"string"==typeof s.caption&&(n[l]=s.caption),o[l]={status:"uploading",bytesUploaded:e.progress?.bytesUploaded||0,bytesTotal:e.progress?.bytesTotal||e.size||0}}),0!==i.length&&a.isCurrentSession(c)&&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",u),l.current=()=>{"function"==typeof t.off&&(t.off("upload-progress",i),t.off("upload-success",o),t.off("upload-error",s),t.off("restored",u))},r.current=t}return r.current},[e,f,a]);i(()=>{w()},[f,w]);const S=p(async(t,r)=>{const{eventId:i,groupId:n,captions:o,originalFiles:s,trimRanges:l,cropSelections:c,activeFilters:p,showFilterChoice:m,skipUploadFilters:g,perFileFilterSkipped:v,filterOverrides:S}=e.getState();let T=s[t];if(!T)return!1;const C=w();try{if(T=await j(T),!a.isCurrentSession(r))return!1;e.getState().setUploadState(t,{status:"creating",bytesUploaded:0,bytesTotal:T.size,error:void 0});const s=z(T)?"VIDEO":"IMAGE",b=await B(T);if(!a.isCurrentSession(r))return!1;const w=u.current[t]??=await ge(()=>async function(e){try{return await(t=z(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,...ur(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 j(e),r=await createImageBitmap(t);try{return{dimension:{width:r.width,height:r.height},...ur(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}(T));if(!a.isCurrentSession(r))return!1;const F=l[t],k=c[t],E=p.length>0?m&&(v[t]??g):void 0,_=await fetch(x.UPLOAD_CREATE,{method:"POST",headers:f(),signal:d.current?.signal,body:JSON.stringify({eventId:i,groupId:n,uid:t,type:s,fileName:T.name,fileSize:T.size,rawContentType:b,caption:o[t],trimInfo:F?{start:F.startTime,end:F.endTime}:void 0,cropInfo:k,dimension:w.dimension,blurhash:w.blurhash,colors:w.colors,duration:w.duration,filtersSkipped:E,filterOverrides:S[t]})});if(!_.ok){let e=`create failed: ${_.status}`;try{const t=await _.json();t.error&&(e=t.error)}catch{}throw new Error(e)}const{contentId:M,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 _.json());if(!a.isCurrentSession(r))return y({contentId:M,key:U}),!1;const I=a.getAttempt(t)?.fileId;if(I&&C.getFile(I))try{C.removeFile(I)}catch{}const P=C.addFile({name:T.name,type:b,data:T,meta:{uid:t,userId:h.current,contentId:M,key:U,originalContentId:M,originalKey:U,uploadUrl:R,rawContentType:b,eventId:i,groupId:n,type:s,session:r,trimInfo:F?{start:F.startTime,end:F.endTime}:void 0,cropInfo:k,dimension:w.dimension,blurhash:w.blurhash,colors:w.colors,duration:w.duration,filtersSkipped:E,filterOverrides:S[t],completionPending:!1,caption:o[t],uploadStartedAt:Date.now()}});return a.registerFile(t,{uid:t,session:r,fileId:P,contentId:M,key:U}),!0}catch(F){return!a.isCurrentSession(r)||F instanceof DOMException&&"AbortError"===F.name||(e.getState().setUploadState(t,{status:"error",error:F instanceof Error?F.message:String(F)}),b(F instanceof Error?F:new Error(String(F)),{component:"useUpload",tags:["upload","create"],extra:{uid:t}})),!1}},[e,w,f,y,a]),T=p(async()=>{const{selectedFiles:t,oversizedUids:r}=e.getState(),i=t.filter(({uid:e})=>!r[e]);if(0===i.length)return;const n=a.getAttempts(),o=a.beginSession();n.forEach(y),a.clearFiles(),d.current=new AbortController;const s=w();e.getState().setHasStarted(!0),g.current=!1;for(const{uid:a}of i)e.getState().setUploadState(a,{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})=>S(e,o)),a.isCurrentSession(o)?0===s.getFiles().length?(O.error("Could not start upload. Please try again."),void e.getState().setHasStarted(!1)):void(await s.upload()):void 0},[e,w,S,y,a]),C=p(()=>{const t=a.getAttempts();a.invalidate(),d.current?.abort(),c.current={},n.current=null,a.clearFiles(),u.current={},r.current?.cancelAll(),t.forEach(y),e.getState().resetUploader()},[e,y,a]),F=p(async t=>{const r=w();n.current=null;const i=a.getAttempt(t);if(!i)return void(await S(t,a.currentSession()));const o=r.getFile(i.fileId);if(o){const n=o.meta,s=(c.current[t]??0)+1;if(c.current[t]=s,n.completionPending&&"string"==typeof n.completionContentId&&"string"==typeof n.completionKey)return void(await cn(n.completionContentId,n.completionKey,"number"==typeof n.uploadStartedAt?Date.now()-n.uploadStartedAt:void 0,f(),d.current?.signal).then(()=>{if((c.current[t]??0)===s){r.setFileMeta(i.fileId,{completionPending:!1}),e.getState().setUploadState(t,{status:"success",contentId:n.completionContentId}),a.removeFile(t);try{r.removeFile(i.fileId)}catch{}}}).catch(r=>{(c.current[t]??0)===s&&e.getState().setUploadState(t,{status:"error",error:r instanceof Error?r.message:String(r)})}));try{r.removeFile(i.fileId)}catch{}}a.removeFile(t),y(i),c.current[t]=(c.current[t]??0)+1,await S(t,a.currentSession())},[w,S,y,f,a,e]),k=p(()=>{Object.entries(e.getState().uploadStates).filter(([,e])=>"error"===e.status).map(([e])=>e).forEach(e=>F(e))},[e,F]);return i(()=>()=>{const e=a.getAttempts();a.invalidate(),d.current?.abort(),l.current?.(),l.current=null,r.current?.cancelAll(),r.current?.destroy(),r.current=null,a.clearFiles(),e.forEach(y)},[y,a]),{startUpload:T,cancelUpload:C,retryUpload:F,retryAllUploads:k,resumeRestoredUpload:p(()=>{const{restoredUids:t}=e.getState();d.current=new AbortController,e.setState({showRestoreDialog:!1,restoredUids:[]}),Promise.all(t.map(e=>F(e))).then(()=>w().upload())},[e,F]),discardRestoredUpload:p(()=>{const t=w(),{restoredUids:r}=e.getState();r.forEach(r=>{const i=a.getAttempt(r);if(i){try{t.removeFile(i.fileId)}catch{}a.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,w])}}function hn({eventSlug:e,event:t}){const r=v(),n=M(),o=r.props?.organizationId,a=r.user,d=Ye(),c=Xe(e=>e.selectedFiles),u=Xe(e=>e.hasStarted),m=Xe(e=>e.oversizedUids),f=Xe(e=>e.showOversizedModal),k=Xe(e=>e.activeFilters),E=Xe(e=>e.showFilterChoice),_=Xe(e=>e.skipUploadFilters),U=Xe(e=>e.showRestoreDialog),R=Xe(e=>e.restoredUids),[I,P]=l(!1),[N,A]=l(!1),[D,j]=l({}),[$,B]=l(!0);i(()=>{if(!a||!o)return;let t=!1;return B(!0),y.get(x.GET_UPLOAD_COUNT,{searchParams:{eventSlug:e},headers:{"x-org-id":o,...a.token?{Authorization:`Bearer ${a.token}`}:{}}}).json().then(e=>{t||j(e?.data?.uploadCount??{})}).catch(()=>{t||O.error("Failed to fetch upload count")}).finally(()=>{t||B(!1)}),()=>{t=!0}},[a,o,e]);const H=!t.uploadLimit||t.uploadLimit<=0,V=(D[T.APPROVED]??0)+(D[T.IN_REVIEW]??0),W=H?1/0:Math.max(0,(t.uploadLimit??0)-V),G=$,X=H?"Unlimited":W,Y=Math.min(W,100),K=!(t.status===S.OPEN)||u||G,Q=t.enableVideo?[...se,...ae]:se,Z=!!t.ada,ee=!!t.enableCaption||Z,te=function({effectiveFileLimit:e,eventSlug:t}){const r=Ye();return p(i=>{const n=r.getState();if(n.hasStarted)return;const o=e=>`${e.name}-${e.size}-${e.lastModified}`,s=n.selectedFiles,a=new Set(s.map(({file:e})=>o(e))),l=i.filter(e=>{const t=o(e);return!a.has(t)&&(a.add(t),!0)}).map(e=>({uid:ne(),file:e})),d=Math.max(0,e-s.length),c=l.slice(0,d),u=l.length-c.length;u>0&&(O.warn(`${u} file${u>1?"s":""} not added — you've reached your upload limit.`),g("Upload quota limit reached","warning",{component:"UploadPageClient",tags:["upload","quota"],extra:{eventSlug:t,dropped:u,effectiveFileLimit:e}}));const h={};c.forEach(({uid:e,file:t})=>{const r=function(e){const t=z(e),r=t?w:F;return e.size>r?t?"video":"image":void 0}(t);r&&(h[e]=r)}),Object.keys(h).length>0&&(r.getState().addOversizedUids(h),g("File size limit exceeded","warning",{component:"UploadPageClient",tags:["upload","file-size"],extra:{eventSlug:t,oversizedCount:Object.keys(h).length}}));const p={};c.forEach(({uid:e,file:t})=>{p[e]=t}),r.getState().addOriginalFiles(p),r.getState().setSelectedFiles([...s,...c]),c.forEach(({uid:e,file:t})=>{z(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:Y,eventSlug:e}),{startUpload:re,cancelUpload:ie,retryUpload:ce,retryAllUploads:he,resumeRestoredUpload:pe,discardRestoredUpload:ge}=un(),fe=p(()=>{A(!1),u?ie():d.getState().resetUploader()},[u,ie,d]);!function(e){const t=Ye(),r=v(),n=r.props?.organizationId,o=r.user?.token;i(()=>{if(!e||!n)return;let r=!1;return y.get(x.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=>{b(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],d.getState().removeFile(r)},3e3))})};t(d.getState());const r=d.subscribe(t);return()=>{r(),Object.values(e).forEach(clearTimeout)}},[d]),i(()=>{0===c.length&&u&&d.getState().resetUploader()},[c.length,u,d]);const ve=Object.values(Xe(e=>e.uploadStates)).some(e=>"queued"===e.status||"creating"===e.status||"uploading"===e.status);i(()=>{if(!u||!ve)return;const e=e=>{e.preventDefault()};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[u,ve]);const be=p(e=>d.getState().removeFile(e),[d]),ye=p(()=>{if(!Z)return!0;const e=d.getState(),t=e.selectedFiles.some(({uid:t})=>!e.oversizedUids[t]&&!e.captions[t]?.trim());return t&&O.warn("This event requires a caption on every file before uploading."),!t},[Z,d]),we=p(()=>{ye()&&(Object.keys(d.getState().oversizedUids).length>0?d.getState().setShowOversizedModal(!0):re())},[d,re,ye]),xe=p(()=>{!a||a.tcAccepted?we():P(!0)},[a,we]),Se=p(()=>{d.getState().removeOversizedFiles(),ye()&&re()},[d,re,ye]),[Te,Ce]=l(!1),Fe=s(0),ke=K||c.length>=Y;/* @__PURE__ */
76
- return h("div",{className:"bg-background relative min-h-screen px-3 pb-9 lg:px-0",onDragEnter:e=>{e.preventDefault(),ke||(Fe.current+=1,Ce(!0))},onDragOver:e=>e.preventDefault(),onDragLeave:()=>{Fe.current=Math.max(0,Fe.current-1),0===Fe.current&&Ce(!1)},onDrop:p(e=>{if(e.preventDefault(),Fe.current=0,Ce(!1),ke)return;const t=e.dataTransfer?.files;t&&t.length>0&&te(Array.from(t))},[ke,te]),children:[Te&&/* @__PURE__ */h("div",{className:"border-primary bg-background/90 fixed inset-0 z-2003 flex items-center justify-center border-4 border-dashed",children:/* @__PURE__ */h("p",{className:"text-primary text-2xl font-semibold",children:"Drop to add files"})}),
77
- /* @__PURE__ */h("div",{className:"mx-auto max-w-4xl space-y-6",children:[
78
- /* @__PURE__ */h(Mt,{uploadDisabled:K,eventName:t.name,isQuotaLoading:G,remainingUploads:X}),!t.enableVideo&&/* @__PURE__ */h("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===c.length&&!u&&/* @__PURE__ */h(kt,{enabledFileTypes:Q,disabled:K,onFileSelect:te,selectedCount:c.length,maxCount:Y,enableVideo:t.enableVideo})]}),c.length>0&&/* @__PURE__ */h("div",{className:"mx-auto mt-8 w-full max-w-full pb-36 sm:px-0 md:pb-24",children:[E&&k.length>0&&!u&&/* @__PURE__ */h("div",{className:"border-border bg-card mb-4 flex items-center gap-3 rounded-lg border p-3",children:[/* @__PURE__ */h(oe,{checked:!_,onChange:e=>{d.getState().setSkipUploadFilters(!e);const t={};e||c.forEach(({uid:e})=>{t[e]=!0}),d.setState({perFileFilterSkipped:t})},label:"Apply filters"}),/* @__PURE__ */h("span",{className:"text-muted-foreground -ml-1 text-sm",children:"— upload with filters applied"})]}),
79
- /* @__PURE__ */h("div",{className:"flex items-center justify-between py-2",children:[/* @__PURE__ */h("p",{className:"text-muted-foreground text-sm font-medium",children:[c.length," selected"]}),!u&&c.length<Y&&/* @__PURE__ */h(_t,{enabledFileTypes:Q,disabled:K,onFileSelect:te})]}),
80
- /* @__PURE__ */h("div",{className:"grid grid-cols-1 gap-4 py-4 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4",children:c.map(({uid:e,file:t})=>/* @__PURE__ */h(St,{uid:e,file:t,onRemove:be,disabled:u,adaRequired:Z,showCaption:ee,onRetry:ce},e))}),!u&&c.length<Y&&/* @__PURE__ */h(Et,{enabledFileTypes:Q,disabled:K,onFileSelect:te}),!u&&/* @__PURE__ */h(q,{className:"mt-2 w-full gap-2",onClick:xe,disabled:K||0===c.length,children:[/* @__PURE__ */h(L,{className:"size-4"}),"Upload"]}),
81
- /* @__PURE__ */h(Ct,{selectedCount:c.length,onUpload:xe,onCancel:()=>A(!0),onRetryAll:he,uploadDisabled:K||0===c.length})]}),!u&&/* @__PURE__ */h("div",{className:"mx-auto mt-12 max-w-4xl text-center",children:/* @__PURE__ */h(q,{onClick:()=>n(C.GALLERY(e)),children:"View gallery"})}),
82
- /* @__PURE__ */h(le,{open:f,oversizedUids:m,onClose:()=>d.getState().setShowOversizedModal(!1),onRemoveAndUpload:Se}),
83
- /* @__PURE__ */h(de,{open:U,count:R.length,onResume:pe,onDiscard:ge}),
84
- /* @__PURE__ */h(J,{open:N,onOpenChange:A,title:"Cancel upload?",description:u?"Active uploads will be stopped and any in-progress files may be lost.":"Your selected files will be cleared.",cancelText:"Keep uploading",confirmText:u?"Stop upload":"Clear selection",confirmColor:"error",onCancel:()=>A(!1),onConfirm:fe}),
85
- /* @__PURE__ */h(ue,{open:I,onClose:()=>P(!1),onSuccess:()=>{P(!1),we()}})]})}var pn=()=>{const{eventSlug:e}=k(),t=E(),r=M(),{loadingUser:n,user:o}=v();i(()=>{n||o||r("/auth/login",{state:{referrer:t.pathname},replace:!0})},[n,o]);const{loading:a,event:l}=A({eventSlug:e}),d=s(ne());return a||l&&l.status!==S.CLOSED?/* @__PURE__ */h("div",l&&e?{className:"bg-background mx-auto min-h-screen pt-16",children:/* @__PURE__ */h(Ge,{eventId:String(l._id),groupId:d.current,children:/* @__PURE__ */h(hn,{eventSlug:e,event:l})})}:{className:"bg-background min-h-screen"}):/* @__PURE__ */h("div",{className:"bg-background mx-auto min-h-[80] pt-16 pb-36",children:/* @__PURE__ */h(he,{eventSlug:e,locationState:t?.state})})};export{pn as default};
1
+ import{r as e,t}from"./DdACKOZr.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 d,Mt as c,Rt as u,Sn as h,Tn as p,Tt as m,Wt as g,Zt as f,_t as v,cn as b,i as y,it as w,kt as x,ln as S,nn as T,nt as C,on as F,pt as k,sn as E,st as _,vn as M,vt as U,wn as R,xn as I,xt as P,yn as N,yt as O}from"./BTduHo9u.js";import{r as A}from"./ZJzxZBJ5.js";import{t as q}from"./BPGLsT1I.js";import{t as D}from"./B4vKIcyS.js";import{a as L,i as z,n as j,o as $,r as B,s as H}from"./DChfs6i_.js";import{a as V,i as W,n as G,o as X,r as Y,t as K}from"./BhoJSelw.js";import{t as Q}from"./B5343djA.js";import{i as J,n as Z,r as ee,t as te}from"./DdtKpY372.js";var re=[];for(let mn=0;mn<256;++mn)re.push((mn+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,d=l?"checked":"unchecked",c=h();/* @__PURE__ */
2
+ return T("label",{htmlFor:c,className:n("flex items-center gap-2",a&&"cursor-not-allowed opacity-50",!a&&"cursor-pointer"),children:[/* @__PURE__ */T("button",{type:"button",id:c,role:"switch","aria-checked":l,disabled:a,"data-state":d,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__ */T("span",{"data-state":d,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__ */T("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__ */T(K,{open:e,onOpenChange:e=>!e&&r(),children:/* @__PURE__ */T(G,{children:[/* @__PURE__ */T(V,{children:[/* @__PURE__ */T(X,{children:"Some files are too large"}),/* @__PURE__ */T(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__ */T(W,{children:/* @__PURE__ */T(q,{onClick:i,children:"Remove and Upload"})})]})})}function de({open:e,count:t,onResume:r,onDiscard:i}){/* @__PURE__ */
3
+ return T(K,{open:e,onOpenChange:e=>!e&&i(),children:/* @__PURE__ */T(G,{children:[/* @__PURE__ */T(V,{children:[/* @__PURE__ */T(X,{children:"Resume your upload?"}),/* @__PURE__ */T(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__ */T(W,{children:[/* @__PURE__ */T(q,{variant:"outlined",onClick:i,children:"Remove All"}),/* @__PURE__ */T(q,{onClick:r,children:"Resume"})]})]})})}var ce=["6a385dabb04f4d8783b14fe1","69ada0f82889f080a9ca53df"],ue=({open:e,onClose:t,onSuccess:r})=>{const{t:i}=A(),[n,o]=I(!1),s=P(),a=s.props?.organizationId??s.organization?._id,{user:l,updateUser:d}=s,c=!!a&&ce.includes(a.trim()),u=c?"https://qrati.com/terms-of-use-wedding-private-events":"https://qrati.com/terms-of-use",h=c?"https://qrati.com/privacy-policy-wedding-private-events":"https://qrati.com/privacy-policy";/* @__PURE__ */
4
+ return T(K,{open:e,onOpenChange:e=>!e&&t(),children:/* @__PURE__ */T(G,{className:"text-foreground",children:/* @__PURE__ */T("div",{className:"mx-auto max-w-sm p-4 text-center sm:max-w-lg",children:[
5
+ /* @__PURE__ */T(X,{children:i("upload.terms_title","Terms & Conditions")}),
6
+ /* @__PURE__ */T(Y,{hidden:!0,children:i("upload.terms_description","Please accept our terms to proceed")}),
7
+ /* @__PURE__ */T("div",{className:"mt-4 mb-6",children:/* @__PURE__ */T("p",{className:"bg-background text-foreground text-base",children:[i("upload.terms_prompt","I agree to the")," ",
8
+ /* @__PURE__ */T("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__ */T("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__ */T(q,{fullWidth:!0,color:"success",disabled:n,loading:n,onClick:async()=>{o(!0);try{const e=await f.post(x.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 d({tcAccepted:!0}),o(!1),r()}catch(e){m(e instanceof Error?e:new Error(String(e)),{component:"TermsAndConditionsModal",tags:["upload","terms-accept"]}),y.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?d.GALLERY(e):d.PUBLIC_EVENTS;/* @__PURE__ */
11
+ return T("div",{className:"mx-auto mt-24 w-fit max-w-xl space-y-8",children:[
12
+ /* @__PURE__ */T(C,{variant:"h3",align:"center",children:r("upload.event_closed","Upload Closed")}),
13
+ /* @__PURE__ */T(C,{variant:"h5",align:"center",color:"muted",children:r("upload.closed_description","This event is no longer accepting uploads.")}),
14
+ /* @__PURE__ */T("div",{className:"flex flex-row justify-end",children:/* @__PURE__ */T(k,{to:i,state:t,children:/* @__PURE__ */T(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,d,c,u,h,p,m,g,f,v,b,y){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],k=x[F+3];C[F]=Math.min(255,Math.max(0,Math.round(e*w+t*S+r*T+i*k+255*n))),C[F+1]=Math.min(255,Math.max(0,Math.round(o*w+s*S+a*T+l*k+255*d))),C[F+2]=Math.min(255,Math.max(0,Math.round(c*w+u*S+h*T+p*k+255*m))),C[F+3]=Math.min(255,Math.max(0,Math.round(g*w+f*S+v*T+b*k+255*y)))}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 be(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 ye="\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),d=/* @__PURE__ */new Int32Array(256);let c=0,u=0,h=0;for(let I=0;I<e.length;I+=4)c+=e[I],u+=e[I+1],h+=e[I+2];const p=c/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){v=60;break}}const b=f+n;for(let I=0;I<e.length;I+=4){const t=ve(e[I],e[I+1],e[I+2],b);a[Math.min(255,Math.max(0,Math.round(t.r+t.g+t.b)))]++,l[e[I+1]]++,d[e[I+2]]++}const y=[0],w=[0],x=[0];for(let I=0;I<256;I++)a[I]-s<2&&y.push(I),l[I]-s<2&&w.push(I),d[I]-s<2&&x.push(I);y.push(255),w.push(255),x.push(255);const S=be(y),T=be(w),C=be(x),F=256/Math.max(1,S.high-S.low),k=256/Math.max(1,T.high-T.low),E=256/Math.max(1,C.high-C.low),_=-S.low/256*F,M=-T.low/256*k,U=-C.low/256*E,R=ve(1,1,1,b);return{rR:R.r*F,rG:R.g*F,rB:R.b*F,rA:0,rOff:_,gR:0,gG:k,gB:0,gA:0,gOff:M,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:ye,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=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 d=1;if(l>r){const e=Math.max(.001,1.414-r);d=1-Math.min(.8,(l-r)/e*t)}n[s*i+e]=d}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),d=Math.min(1,t-o),c=n[o*i+r],u=n[o*i+s],h=n[a*i+r];return c+(u-c)*l+(h-c)*d+(c-u-h+n[a*i+s])*l*d};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),d=o(s(i,r),e);n[l]=Math.round(t[l]*d),n[l+1]=Math.round(t[l+1]*d),n[l+2]=Math.round(t[l+2]*d),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),d=Math.min(255,a+20),c=Math.max(0,a-30);o[s]=Math.round(e*(1-t)+l*t),o[s+1]=Math.round(i*(1-t)+d*t),o[s+2]=Math.round(n*(1-t)+c*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 c=0;c<t.length;c+=4)i+=t[c],n+=t[c+1],o+=t[c+2];const s=i/r,a=n/r,l=o/r,d=(s+a+l)/3;return{u_gain_r:d/Math.max(1,s),u_gain_g:d/Math.max(1,a),u_gain_b:d/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,d=n*(e+o+s),c=e*r+n*(s-o)*i+n*d*(1-r),u=o*r+n*(e-s)*i+n*d*(1-r),h=s*r+n*(o-e)*i+n*d*(1-r);a[l]=Math.min(255,Math.max(0,Math.round(255*c))),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,d=0,c=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,d+=t[p+1]*m,c+=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(d),s[h+2]=Math.round(c),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],d=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-d*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,ke=null,Ee=null;function _e(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 Me(e,t){const r=_e(e,e.VERTEX_SHADER,Te),i=_e(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 Pe(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 Ne(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,d=a.height;if(l>r||d>r){const e=Math.min(r/l,r/d);l=Math.round(l*e),d=Math.round(d*e)}const c=Math.min(150,l),u=Math.max(1,Math.round(c*d/l)),h=new OffscreenCanvas(c,u).getContext("2d");h.drawImage(a,0,0,c,u);const p=h.getImageData(0,0,c,u);let m;if(a.width!==l||a.height!==d){const e=new OffscreenCanvas(l,d);e.getContext("2d").drawImage(a,0,0,l,d),a.close(),m=await createImageBitmap(e,{imageOrientation:"flipY"})}else m=await createImageBitmap(a,{imageOrientation:"flipY"}),a.close();const g=Fe??new OffscreenCanvas(l,d);g.width===l&&g.height===d||(g.width=l,g.height=d),Fe=g;let f=ke;if(f||(f=g.getContext("webgl",{preserveDrawingBuffer:!0,alpha:!0})||g.getContext("experimental-webgl",{preserveDrawingBuffer:!0,alpha:!0}),ke=f),!f||f.isContextLost())return m.close(),ke=null,Fe=null,async function(e,t,r,i,n,o,s="image/webp",a=.85){const l=new OffscreenCanvas(r,i),d=l.getContext("2d"),c=await createImageBitmap(e);d.drawImage(c,0,0,r,i),c.close();const u=[];for(const h of t){const{def:e}=Pe(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=d.getImageData(0,0,r,i);d.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,d,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,d);const b=[Re(f,l,d),Re(f,l,d)],y=f.createBuffer();f.bindBuffer(f.ARRAY_BUFFER,y),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}=Pe(t);if(!n)continue;const o=t.config?.templateId??n;w.has(o)||w.set(o,Me(f,n));const a=w.get(o);if(!a)continue;f.useProgram(a);const c=f.getAttribLocation(a,"a_position");f.bindBuffer(f.ARRAY_BUFFER,y),f.enableVertexAttribArray(c),f.vertexAttribPointer(c,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,d),Ie(f,a,Ne(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=b[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:d,processingTime:Date.now()-o}:{blob:e,appliedFilters:[],width:l,height:d,processingTime:Date.now()-o}}finally{for(const{fbo:e,tex:t}of b)f.deleteFramebuffer(e),f.deleteTexture(t);f.deleteTexture(v),f.deleteBuffer(y)}}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=[],d=[];for(const u of o){const{def:e}=Pe(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),d.push(u.id)}catch(c){console.warn(`[webgl-filter] buildCpuTransform failed for ${u.id}:`,c),m(c instanceof Error?c:/* @__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:d,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 d=await l.convertToBlob({type:"image/jpeg",quality:.92}),c=await De(d);if(!i.length)return{original:c,processed:c,appliedFilters:[],failedFilters:[],totalExecutionTime:Date.now()-r};let u=c;const h=[],p=[];try{const e=await Oe(d,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:c,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=M(null),i=M(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 d={...t.perFileFilterSkipped};delete d[e];const c={...t.filterOverrides};return delete c[e],{selectedFiles:t.selectedFiles.filter(t=>t.uid!==e),captions:r,oversizedUids:i,trimRanges:n,originalFiles:o,cropSelections:s,uploadStates:a,filteredThumbs:l,perFileFilterSkipped:d,filterOverrides:c}}),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},d={...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 d[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:d,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__ */T(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]),b.useCallback(()=>t(e.getInitialState()),[e,t]));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 T("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__ */T("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 T("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__ */T("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 T("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__ */T("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 T("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__ */T("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 T("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__ */T("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 T("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__ */T("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 T("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__ */T("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 T("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__ */T("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 T("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__ */T("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 T("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__ */T("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 T("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__ */T("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 dt({className:e}){/* @__PURE__ */
26
+ return T("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__ */T("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 ct(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=ct(e);return 0===i.length?null:/* @__PURE__ */T("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 T("div",{className:"space-y-1",children:[
28
+ /* @__PURE__ */T("label",{htmlFor:`${e}:${o.key}`,className:"flex items-center justify-between text-sm",children:[/* @__PURE__ */T("span",{children:[o.label,i.length>1&&/* @__PURE__ */T("span",{className:"text-muted-foreground ml-1 text-xs",children:["(",n,")"]})]}),/* @__PURE__ */T("span",{className:"text-muted-foreground",children:String(s)})]}),"number"===o.type&&/* @__PURE__ */T("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__ */T("input",{type:"checkbox",id:`${e}:${o.key}`,checked:s,onChange:t=>r(e,o.key,t.target.checked)})]},`${e}:${o.key}`)})})}var ht=S(()=>import("./D0IYqyql.js").then(e=>({default:e.ReactCompareSlider})));function pt({open:e,onClose:t,file:r,filters:o,isVideo:s,trimRange:a,overrides:l,onOverrideChange:d,onReset:c}){const[u,h]=I(),[p,m]=I(),[g,f]=I(!0),[v,b]=I(!1),[y,x]=I(!1),[S,C]=I(),[F,k]=I(0),[_,U]=I(!1),[R,P]=I(null),[N,O]=I(null),[A,D]=I(!1),[L,z]=I(!0),[j,$]=I(!0),H=M(null),Y=M(!1),Q=M([]),J=M(null),Z=M(null),te=M(null),re=M(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&&!!N)},[R,N]),i(()=>{R&&(R.muted=L)},[R,L]),i(()=>{if(!e||s)return;let t=!1;return Y.current?b(!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 d=await l.convertToBlob({type:"image/jpeg",quality:.92});if(t)return;const c=await Oe(d,o,1600,"image/jpeg",.92);if(t)return;const u=URL.createObjectURL(d),p=URL.createObjectURL(c.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),b(!1))}),()=>{t=!0}},[e,s,r,o]),i(()=>{if(!e||!s||!A)return;const t=R,i=N;if(!t||!i)return;let n=!1,o=null;const l=URL.createObjectURL(r);f(!0),x(!1),k(0);const d=a?.startTime??0,c=d+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;k(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-d)>.05&&(await new Promise(e=>{const r=()=>{t.removeEventListener("seeked",r),e()};t.addEventListener("seeked",r,{once:!0}),t.currentTime=d}),n))return;k(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);k(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,k(100),f(!1),Y.current=!0;const b=a?Math.min(a.endTime,c):Math.min(t.duration||c,c),y=()=>{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>=b||t.currentTime<d){const e=()=>{t.removeEventListener("seeked",e),n||(o=t.requestVideoFrameCallback(y))};return t.addEventListener("seeked",e,{once:!0}),void(t.currentTime=d)}o=t.requestVideoFrameCallback(y)}};o=t.requestVideoFrameCallback(y)},{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 b(!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||b(!1)}),()=>{t=!0}},[e,s,o,A]);const ne=_?"100vh":"70vh",oe=!!d&&ct(o).length>0;/* @__PURE__ */
29
+ return T(K,{open:e,onOpenChange:e=>!e&&t(),children:/* @__PURE__ */T(G,{className:n(_?"max-w-none rounded-none":"max-w-2xl sm:w-2xl"),children:/* @__PURE__ */T("div",{className:"bg-background",children:[/* @__PURE__ */T(V,{className:"flex-row items-center justify-between space-y-0",children:[/* @__PURE__ */T(X,{children:"Compare original & filtered"}),/* @__PURE__ */T(ee,{size:"sm",variant:"ghost","aria-label":_?"Exit fullscreen":"Fullscreen",tooltip:_?"Exit fullscreen":"Fullscreen",icon:/* @__PURE__ */T(_?lt:dt,{}),onClick:ie})]}),/* @__PURE__ */T("div",{ref:H,className:n("relative p-4 pt-0",_&&"bg-background flex h-screen w-screen items-center justify-center p-0"),children:[_&&/* @__PURE__ */T(ee,{size:"sm",variant:"ghost","aria-label":"Exit fullscreen",tooltip:"Exit fullscreen",className:"absolute top-2 right-2 z-30",icon:/* @__PURE__ */T(lt,{}),onClick:ie}),g&&/* @__PURE__ */T("div",{className:"flex h-64 flex-col items-center justify-center gap-2",children:[/* @__PURE__ */T(w,{}),s&&/* @__PURE__ */T("p",{className:"text-muted-foreground text-sm",children:["Generating preview… ",F,"%"]})]}),y&&!g&&/* @__PURE__ */T("div",{className:"text-muted-foreground flex h-64 items-center justify-center text-sm",children:"Couldn't generate preview."}),v&&!g&&!y&&/* @__PURE__ */T("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__ */T(w,{className:"size-3.5"}),"Updating…"]}),!s&&!g&&!y&&u&&p&&/* @__PURE__ */T(E,{fallback:null,children:/* @__PURE__ */T(ht,{style:{width:"100%",maxHeight:ne,aspectRatio:S},defaultPosition:50,onlyHandleDraggable:!0,itemOne:/* @__PURE__ */T("div",{className:"relative size-full",children:[/* @__PURE__ */T("img",{alt:"Original",className:"size-full object-contain",src:u}),/* @__PURE__ */T(mt,{position:"left",children:"Original"})]}),itemTwo:/* @__PURE__ */T("div",{className:"relative size-full",children:[/* @__PURE__ */T("img",{alt:"Filtered",className:"size-full object-contain",src:p}),/* @__PURE__ */T(mt,{position:"right",children:"Filtered"})]})})}),s&&/* @__PURE__ */T("div",{className:"relative",style:{visibility:g||y?"hidden":"visible"},children:[/* @__PURE__ */T(E,{fallback:null,children:/* @__PURE__ */T(ht,{style:{width:"100%",maxHeight:ne,aspectRatio:S},defaultPosition:50,onlyHandleDraggable:!0,itemOne:/* @__PURE__ */T("div",{className:"relative size-full",children:[/* @__PURE__ */T("video",{ref:P,playsInline:!0,className:"pointer-events-none size-full object-contain"}),/* @__PURE__ */T(mt,{position:"left",children:"Original"})]}),itemTwo:/* @__PURE__ */T("div",{className:"relative size-full",children:[/* @__PURE__ */T("canvas",{ref:O,className:"size-full object-contain"}),/* @__PURE__ */T(mt,{position:"right",children:"Filtered"})]})})}),/* @__PURE__ */T("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__ */T(ee,{size:"sm",variant:"ghost","aria-label":L?"Unmute":"Mute",tooltip:L?"Unmute":"Mute",icon:/* @__PURE__ */T(L?st:at,{}),onClick:()=>z(e=>!e)}),/* @__PURE__ */T(ee,{size:"sm",variant:"ghost","aria-label":j?"Pause":"Play",tooltip:j?"Pause":"Play",icon:/* @__PURE__ */T(j?nt:ot,{}),onClick:()=>{R&&(R.paused?(R.play(),$(!0)):(R.pause(),$(!1)))}})]})]}),d&&!_&&/* @__PURE__ */T("div",{className:"mt-4",children:/* @__PURE__ */T(ut,{filters:o,overrides:l,onChange:d})}),oe&&!_&&/* @__PURE__ */T(W,{className:"mt-4",children:[/* @__PURE__ */T(q,{variant:"outlined",color:"foreground",onClick:c,children:"Reset"}),/* @__PURE__ */T(q,{onClick:t,children:"Apply"})]})]})]})})})}function mt({position:e,children:t}){/* @__PURE__ */
30
+ return T("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"],bt=({open:e,onClose:t,imageSrc:r,outputSrc:i,aspectRatio:n,initialCrop:o,onCropComplete:s,title:a})=>{const l=M(null),[d,c]=I(null),[u,h]=I(!1),p=M(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,d;if(t&&r)if("move"===t.mode)c((i=t.start,o=e.clientX-t.clientX,s=e.clientY-t.clientY,a=r.width,d=r.height,{...i,x:gt(i.x+o,0,a-i.w),y:gt(i.y+s,0,d-i.h)}));else{const{px:i,py:o}=g(e.clientX,e.clientY);c(function(e,t,r,i,n,o,s){const a=t.includes("e")?1:-1,l=t.includes("s")?1:-1,d=a>0?e.x:e.x+e.w,c=l>0?e.y:e.y+e.h,u=a>0?n-d:d,h=l>0?o-c:c;let p=gt((r-d)*a,20,u),m=gt((i-c)*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?d:d-p,y:l>0?c:c-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]),b=(e,t)=>r=>{d&&(r.preventDefault(),r.stopPropagation(),p.current={mode:e,corner:t,start:d,clientX:r.clientX,clientY:r.clientY},window.addEventListener("pointermove",f),window.addEventListener("pointerup",v))},y=R(()=>{c(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 T(K,{open:e,onOpenChange:y,children:/* @__PURE__ */T(G,{className:"flex h-[90vh] min-w-xl flex-col overflow-hidden p-0",children:[
32
+ /* @__PURE__ */T("div",{className:"bg-background shrink-0",children:/* @__PURE__ */T(V,{children:[/* @__PURE__ */T(X,{children:a||"Crop Image"}),/* @__PURE__ */T(Y,{className:"sr-only",children:"Drag the box to move it, or drag a corner to resize."})]})}),
33
+ /* @__PURE__ */T("div",{className:"flex max-h-[60vh] min-h-0 flex-1 items-center justify-center overflow-hidden bg-black",children:/* @__PURE__ */T("div",{style:{position:"relative",display:"inline-block",lineHeight:0,touchAction:"none"},children:[/* @__PURE__ */T("img",{ref:l,src:r,alt:"Crop preview",draggable:!1,onLoad:()=>{const e=l.current;e&&c(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"}}),d&&/* @__PURE__ */T("div",{onPointerDown:b("move"),style:{position:"absolute",left:`${d.x}px`,top:`${d.y}px`,width:`${d.w}px`,height:`${d.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__ */T("div",{onPointerDown:b("resize",e),style:w(e)},e))})]})}),
34
+ /* @__PURE__ */T("div",{className:"border-border bg-background shrink-0 border-t",children:/* @__PURE__ */T(W,{children:[/* @__PURE__ */T(q,{variant:"outlined",onClick:y,disabled:u,children:"Cancel"}),/* @__PURE__ */T(q,{onClick:async()=>{const e=l.current;var t;if(d&&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=d.x/e.width,a=d.y/e.height,l=d.w/e.width,c=d.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(c*n.naturalHeight)},p={unit:"%",x:ft(100*o),y:ft(100*a),width:ft(100*l),height:ft(100*c)};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),y()}catch(n){m(n instanceof Error?n:new Error(String(n)),{component:"ImageCropDialog",tags:["upload","crop"]})}finally{h(!1)}},loading:u,disabled:u||!d,children:"Crop"})]})})]})})},yt=({open:e,onClose:t,videoFile:r,activeFilters:n,onTrimComplete:o,title:s="Select 60 Second Clip"})=>{const a=M(null),l=M(null),d=M(null),c=n?.filter(e=>e.enabled)??[],u=c.length>0,[h,p]=I(0),[g,f]=I(0),[v,b]=I(60),[y,w]=I(0),[x,S]=I(!1),[C,F]=I(!1),[k,E]=I(null),[_,U]=I(null),[P,N]=I(0),[O,A]=I({start:0,end:0});i(()=>{if(r&&e){const e=URL.createObjectURL(r);return E(e),()=>URL.revokeObjectURL(e)}},[r,e]),i(()=>{if(!k||!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 d=document.createElement("canvas");d.width=s,d.height=a,d.getContext("2d")?.drawImage(e,0,0,s,a);const u=await new Promise(e=>d.toBlob(e,"image/jpeg",.85));if(r||!u)return;const h=await Ae(c,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)}},[k,u,JSON.stringify(n)]);const D=R(e=>{if(!d.current||0===h)return 0;const t=d.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),N(e.clientX),A({start:g,end:v})},j=(e,t)=>{e.stopPropagation();const r=e.touches[0];U(t),N(r?.clientX??0),A({start:g,end:v})};i(()=>{if(!_||!d.current)return;const e=e=>{const t=d.current.getBoundingClientRect(),r=(e-P)/t.width*h;if("start"===_){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"===_){let e=Math.min(h,O.end+r);e=Math.max(e,g+1),e-g>60&&(e=g+60),b(e)}else if("range"===_){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),b(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)}},[_,P,O,h,g,v]);const $=()=>{a.current&&(x?a.current.pause():((y<g||y>=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),b(60),w(0),S(!1),U(null),a.current&&a.current.pause(),t()},Q=v-g;/* @__PURE__ */
35
+ return T(K,{open:e,onOpenChange:H,children:/* @__PURE__ */T(G,{className:"max-h-[90vh] max-w-3xl overflow-y-auto p-0",children:[
36
+ /* @__PURE__ */T("div",{className:"bg-background sticky top-0 z-10",children:/* @__PURE__ */T(V,{children:[/* @__PURE__ */T(X,{children:s}),/* @__PURE__ */T(Y,{className:"hidden",children:"Review the video preview and choose the start and end times for the clip you want to keep."})]})}),
37
+ /* @__PURE__ */T("div",{className:"space-y-4 p-4",children:[
38
+ /* @__PURE__ */T("div",{className:"relative aspect-video w-full overflow-hidden rounded-lg bg-black",children:[k&&/* @__PURE__ */T("video",{ref:a,src:k,className:"size-full object-contain",onLoadedMetadata:()=>{if(a.current){const e=a.current.duration;p(e),f(0),b(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)}),k&&u&&/* @__PURE__ */T("canvas",{ref:l,className:"pointer-events-none absolute inset-0 size-full object-contain"}),
39
+ /* @__PURE__ */T("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__ */T("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__ */T("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__ */T("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__ */T("div",{className:"absolute bottom-2 left-2 rounded bg-black/70 px-2 py-1 text-sm text-white",children:B(y)})]}),
41
+ /* @__PURE__ */T("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[/* @__PURE__ */T("div",{className:"flex items-center gap-2",children:[/* @__PURE__ */T("span",{className:"bg-primary/20 text-primary rounded-full px-3 py-1 text-sm font-medium",children:["Start: ",B(g)]}),/* @__PURE__ */T("span",{className:"bg-primary/20 text-primary rounded-full px-3 py-1 text-sm font-medium",children:["End: ",B(v)]})]}),/* @__PURE__ */T("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__ */T("div",{className:"space-y-1",children:[
43
+ /* @__PURE__ */T("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__ */T("span",{className:"text-muted-foreground absolute -translate-x-1/2 text-xs",style:{left:`${L(e)}%`},children:B(e)},e))}),
44
+ /* @__PURE__ */T("div",{ref:d,className:"relative h-16 cursor-pointer rounded-lg bg-gray-200 select-none dark:bg-gray-800",onClick:e=>{if(_)return;const t=D(e.clientX);t>=g&&t<=v&&a.current&&(a.current.currentTime=t,w(t))},children:[
45
+ /* @__PURE__ */T("div",{className:"absolute inset-y-0 left-0 bg-black/50",style:{width:`${L(g)}%`}}),
46
+ /* @__PURE__ */T("div",{className:"absolute inset-y-0 right-0 bg-black/50",style:{width:100-L(v)+"%"}}),
47
+ /* @__PURE__ */T("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__ */T("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__ */T("div",{className:"absolute inset-y-0 left-1/2 w-0.5 -translate-x-1/2 bg-white/50"})}),
49
+ /* @__PURE__ */T("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__ */T("div",{className:"absolute inset-y-0 left-1/2 w-0.5 -translate-x-1/2 bg-white/50"})}),
50
+ /* @__PURE__ */T("div",{className:"absolute inset-y-0 z-20 w-0.5 bg-white shadow-lg",style:{left:`${L(y)}%`},children:/* @__PURE__ */T("div",{className:"absolute -top-1 left-1/2 h-3 w-3 -translate-x-1/2 rotate-45 bg-white"})}),
51
+ /* @__PURE__ */T("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__ */T("div",{className:"w-px bg-gray-400/30",style:{height:t%5==0?"100%":"50%"}},t))})]}),
52
+ /* @__PURE__ */T("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__ */T("div",{className:"flex items-center justify-center gap-2",children:[
54
+ /* @__PURE__ */T(q,{variant:"outlined",size:"sm",onClick:()=>{a.current&&(a.current.currentTime=g,w(g))},children:/* @__PURE__ */T("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5",viewBox:"0 0 24 24",children:/* @__PURE__ */T("path",{fill:"currentColor",d:"M6 6h2v12H6zm3.5 6l8.5 6V6z"})})}),
55
+ /* @__PURE__ */T(q,{variant:"outlined",onClick:$,children:/* @__PURE__ */T("svg",x?{xmlns:"http://www.w3.org/2000/svg",className:"h-6 w-6",viewBox:"0 0 24 24",children:/* @__PURE__ */T("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__ */T("path",{fill:"currentColor",d:"M8 5v14l11-7z"})})}),
56
+ /* @__PURE__ */T(q,{variant:"outlined",size:"sm",onClick:()=>{a.current&&(a.current.currentTime=v,w(v))},children:/* @__PURE__ */T("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-5 w-5",viewBox:"0 0 24 24",children:/* @__PURE__ */T("path",{fill:"currentColor",d:"m5 18l8.5-6L5 6zm11 0V6h2v12z"})})})]})]}),
57
+ /* @__PURE__ */T("div",{className:"bg-background border-border sticky bottom-0 border-t",children:/* @__PURE__ */T(W,{children:[/* @__PURE__ */T(q,{variant:"outlined",onClick:H,disabled:C,children:"Cancel"}),/* @__PURE__ */T(q,{onClick:async()=>{F(!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{F(!1)}},loading:C,disabled:C||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=F(function({uid:e,file:t,onRemove:r,disabled:o,adaRequired:s,showCaption:l=!0,onRetry:d}){const c=L(t),u=!c&&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,b=Xe(e=>e.videoMuted),y=Xe(e=>e.setVideoMuted),x=Xe(e=>e.activeFilters),S=Xe(e=>e.showFilterChoice),C=Xe(e=>e.skipUploadFilters),F=Xe(t=>t.perFileFilterSkipped[e]),k=Xe(t=>t.filteredThumbs[e]),E=Xe(t=>t.filterOverrides[e]),_=N(()=>{return e=x,(t=E)&&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},[x,E]),U=!!g,P="success"===g?.status,O="error"===g?.status,A=x.length>0&&(!S||!C&&!F),q=x.length>0&&(!S||!C),[$,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=M(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,_).then(t=>{e||ae(t.processed)}).catch(()=>{}),()=>{e=!0}},[u,$,A,v,_]);const le=M(null),de=M(null),ce=M(null),ue=M(0),he=M(null),[pe,fe]=I(!1),[ve,be]=I(!1),[ye,we]=I(null),[Te,Ce]=I(null),Fe=R(()=>{const e=le.current;if(!e||ce.current)return;const r=URL.createObjectURL(t);ce.current=r,e.src=r,e.load()},[t]),ke=R(()=>{const e=le.current;e&&(e.removeAttribute("src"),e.load()),ce.current&&(URL.revokeObjectURL(ce.current),ce.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)))},[]),_e=R(()=>{const t=le.current,r=de.current;if(!t||!r||!t.videoWidth)return!1;const{w:i,h:n}=wt(t.videoWidth,t.videoHeight),o=$e(je(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,_]),Me=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=_e();be(e),e&&de.current&&Ce(de.current.toDataURL("image/jpeg",.85))}fe(!1),function(e){Qe===e&&(Qe=null)}(e),Me(),he.current=setTimeout(()=>{ke(),he.current=null},200)},[e,Ee,_e,A,ke,Me]),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),Me(),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,Me]);return i(()=>{if(!c)return;const t=function(e){return Ke.set(e,()=>le.current?.pause()),()=>{Ke.delete(e),Qe===e&&(Qe=null)}}(e);return()=>{t(),Me(),ke()}},[c,e,ke,Me]),i(()=>{W&&le.current?.pause()},[W]),i(()=>{U&&le.current?.pause()},[U]),i(()=>{ue.current=0},[f]),i(()=>{be(!1),Ce(null)},[A,_,e]),i(()=>{le.current&&(le.current.muted=b)},[b]),i(()=>{if(!c||!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 d=o.getContext("2d");if(!d)return;d.drawImage(i,0,0,o.width,o.height),we(o.toDataURL("image/jpeg",.85))}catch{}finally{n()}}).catch(()=>{}),()=>{e=!0,n()}},[c,J,t]),i(()=>{if(!u||!J||!A||k||X)return;let r=!1;return ge(()=>Le(t,_)).then(t=>{!r&&t.appliedFilters.length&&h.getState().setFilteredThumb(e,t.processed)}).catch(()=>{}),()=>{r=!0}},[u,J,A,k,X,t,_,h,e]),i(()=>{if(!c||!ye||!A||k||X)return;let t=!1;return ge(async()=>{const t=await fetch(ye);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,_,n,o);let a=$e(s);if(a||(a=await Ae(_,r,n,o),a.appliedFilters.length&&Be(s,a)),!a.appliedFilters.length)return i.close(),null;const l=new OffscreenCanvas(n,o),d=l.getContext("2d");return d.drawImage(i,0,0,n,o),i.close(),d.putImageData(a.transform(d.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}},[c,ye,A,k,X,_,h,e]),i(()=>{if(!(c&&pe&&A&&ye))return;const t=le.current,r=de.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,_,o,s);let d=$e(l);if(!d){const e=await fetch(ye);if(!1===e.ok)throw new Error(`Poster fetch failed: ${e.status}`);const t=await e.blob();if(i)return;if(d=await Ae(_,t,o,s),i||!d.appliedFilters.length)return;Be(l,d)}const c=d.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(c(a.getImageData(0,0,o,s)),0,0),m||(m=!0,be(!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)}},[c,pe,A,ye,_,f,e]),i(()=>{if(!c||pe||!A||!ye||X)return;let e=!1;return(async()=>{const t=await fetch(ye);if(!1===t.ok)throw new Error(`Poster fetch failed: ${t.status}`);const r=await t.blob(),i=await Le(new File([r],"poster.jpg",{type:"image/jpeg"}),_);e||Ce(i.processed)})().catch(()=>{}),()=>{e=!0}},[c,pe,A,ye,X,_]),/* @__PURE__ */T("div",{className:"group relative",children:[
58
+ /* @__PURE__ */T("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__ */T("img",{src:A&&k?k:re,alt:t.name,loading:"lazy",decoding:"async",className:"size-full object-contain"}),u&&q&&/* @__PURE__ */T(Tt,{applied:A&&!!k}),c&&/* @__PURE__ */T("div",{className:"relative size-full",children:[ye&&/* @__PURE__ */T("img",{src:A?Te??k??ye:ye,alt:"",className:n("absolute inset-0 size-full object-contain",pe?"opacity-0":"opacity-100")}),(!pe||A)&&q&&/* @__PURE__ */T(Tt,{applied:A&&!!k}),
59
+ /* @__PURE__ */T("video",{ref:le,muted:b,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__ */T("canvas",{ref:de,className:n("pointer-events-none absolute inset-0 size-full object-contain",pe&&ve?"opacity-100":"opacity-0")}),!U&&/* @__PURE__ */T("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__ */T(pe?nt:ot,{className:"text-foreground size-8"})}),!U&&/* @__PURE__ */T("button",{type:"button","aria-label":b?"Unmute videos":"Mute videos",onClick:()=>y(!b),className:"bg-background/60 absolute bottom-2 left-2 z-10 rounded-full p-2 backdrop-blur-sm",children:/* @__PURE__ */T(b?st:at,{className:"text-foreground size-5"})}),f&&!U&&/* @__PURE__ */T("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&&!c&&/* @__PURE__ */T("div",{className:"flex h-full w-full items-center justify-center",children:/* @__PURE__ */T(it,{className:"text-muted-foreground size-12"})}),m&&/* @__PURE__ */T("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__ */T(Q,{className:"size-4"}),"Exceeds ",xt[m]," limit"]}),U&&!P&&!O&&/* @__PURE__ */T("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__ */T("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__ */T("div",{className:"bg-primary/10 flex size-12 items-center justify-center rounded-full",children:/* @__PURE__ */T(w,{className:"size-6"})}),
62
+ /* @__PURE__ */T("div",{className:"relative z-10 rounded-full bg-white/80 px-3 py-1 backdrop-blur-sm dark:bg-black/40",children:/* @__PURE__ */T("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"})})]}),P&&/* @__PURE__ */T("div",{className:"bg-background/80 absolute inset-0 flex flex-col items-center justify-center gap-2 p-4 backdrop-blur-sm",children:[/* @__PURE__ */T("div",{className:"bg-success/20 flex size-14 items-center justify-center rounded-full",children:/* @__PURE__ */T(Z,{className:"text-success size-8"})}),/* @__PURE__ */T("span",{className:"text-success text-sm font-medium",children:"Uploaded!"})]}),O&&/* @__PURE__ */T("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__ */T("div",{className:"bg-destructive/20 flex size-14 items-center justify-center rounded-full",children:/* @__PURE__ */T(Q,{className:"text-destructive size-8"})}),
64
+ /* @__PURE__ */T("p",{className:"text-destructive text-center text-xs font-medium",children:g?.error??"Upload failed"}),d&&/* @__PURE__ */T("button",{type:"button",onClick:()=>d(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__ */T(D,{className:"size-3.5"}),"Retry"]})]})]}),!o&&/* @__PURE__ */T(ee,{size:"sm",color:"error",variant:"default",className:"absolute top-3 right-3","aria-label":"Remove file",icon:/* @__PURE__ */T(a,{}),onClick:()=>r(e)}),!o&&(u||c)&&/* @__PURE__ */T("div",{className:"absolute top-3 left-3 flex gap-2",children:[
65
+ /* @__PURE__ */T(ee,{size:"sm",variant:"default","aria-label":u?"Crop image":"Trim video",icon:/* @__PURE__ */T(u?rt:tt,{}),onClick:()=>u?B(!0):G(!0)}),S&&x.length>0&&!C&&/* @__PURE__ */T(ee,{size:"sm",variant:"default","aria-label":F?"Apply filter":"Skip filter",tooltip:F?"Apply filter":"Skip filter",icon:/* @__PURE__ */T(F?Je:Ze,{}),onClick:()=>h.getState().setFileFilterSkipped(e,!F)}),S&&x.length>0&&!C&&!F&&/* @__PURE__ */T(ee,{size:"sm",variant:"default","aria-label":"Compare original and filtered",tooltip:"Compare original and filtered",icon:/* @__PURE__ */T(et,{}),onClick:()=>{Qe&&(Ke.get(Qe)?.(),Qe=null),Y(!0)}})]}),u&&ne&&/* @__PURE__ */T(bt,{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)}}),c&&W&&/* @__PURE__ */T(yt,{open:W,onClose:()=>G(!1),videoFile:t,activeFilters:A?_:void 0,title:"Select Clip",onTrimComplete:({startTime:t,endTime:r})=>h.getState().setTrimRange(e,{startTime:t,endTime:r})}),X&&/* @__PURE__ */T(pt,{open:X,onClose:()=>Y(!1),file:t,filters:_,isVideo:c,trimRange:f,overrides:E,onOverrideChange:(t,r,i)=>h.getState().setFilterOverride(e,t,r,i),onReset:()=>h.getState().resetFilterOverrides(e)}),l&&/* @__PURE__ */T("div",{className:"mt-2",children:/* @__PURE__ */T(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 T("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),d=N(()=>{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]),c=!!(s&&d&&d.allDone&&d.failed>0);return 0===o?null:/* @__PURE__ */T("div",{className:"bg-background/85 fixed right-0 bottom-0 left-0 z-2002 overflow-hidden backdrop-blur-sm",children:/* @__PURE__ */T("div",{className:"relative flex items-stretch gap-3",children:[
67
+ /* @__PURE__ */T("div",{className:"relative min-w-0 flex-1 overflow-hidden",children:[s&&d&&/* @__PURE__ */T("div",{className:"bg-primary/40 absolute inset-y-0 t-0 text-right transition-[width] duration-300",style:{width:`${d.percent}%`}}),/* @__PURE__ */T("div",{className:"relative flex h-full flex-col justify-center gap-0.5 py-3 pl-3",children:/* @__PURE__ */T("span",s&&d?{className:"text-muted-foreground text-sm font-medium",children:["Uploading",d.failed>0?` · ${d.failed} failed`:""," (",d.percent,"%)"," ",l?/* @__PURE__ */T("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&&c&&/* @__PURE__ */T("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__ */T(D,{className:"size-4"}),"Retry All"]}),s&&!c&&/* @__PURE__ */T("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__ */T("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__ */T("span",{className:"flex items-center gap-2",children:[/* @__PURE__ */T(H,{className:"size-4"}),"Upload"]})})]})});var u}function Ft({enabledFileTypes:e,disabled:t,onFileSelect:r,children:i}){const[n,o]=I(!1),s=M(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=Array.from(t).filter(t=>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))}(t,e));i.length>0&&r(i)},[e,r]);/* @__PURE__ */
68
+ return T("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:R(e=>{e.preventDefault(),o(!1),t||l(e.dataTransfer?.files??null)},[t,l]),children:[/* @__PURE__ */T("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 kt({enabledFileTypes:e,disabled:t,onFileSelect:r,selectedCount:i,maxCount:o,enableVideo:s}){/* @__PURE__ */
69
+ return T("div",{className:"flex w-full justify-center",children:/* @__PURE__ */T(Ft,{enabledFileTypes:e,disabled:t,onFileSelect:r,children:()=>/* @__PURE__ */T("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__ */T("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__ */T("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__ */T("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__ */T("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 Et({enabledFileTypes:e,disabled:t,onFileSelect:r}){/* @__PURE__ */
73
+ return T(Ft,{enabledFileTypes:e,disabled:t,onFileSelect:r,children:({isDragActive:e})=>/* @__PURE__ */T("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__ */T("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 T(Ft,{enabledFileTypes:e,disabled:t,onFileSelect:r,children:()=>/* @__PURE__ */T("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__ */T("svg",{xmlns:"http://www.w3.org/2000/svg",width:"1em",height:"1em",viewBox:"0 0 24 24",className:"size-4",children:/* @__PURE__ */T("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__ */T("span",{children:"Add more"})]})})}function Mt({uploadDisabled:e,eventName:t,isQuotaLoading:r,remainingUploads:i}){const o=r?"-":i;/* @__PURE__ */
75
+ return T("div",{className:"relative overflow-hidden rounded-2xl px-3 pt-6 sm:pt-0",children:[/* @__PURE__ */T("div",{className:"absolute inset-0 opacity-50"}),/* @__PURE__ */T("div",{className:"relative z-10",children:/* @__PURE__ */T("div",{className:"flex flex-col items-center justify-center gap-3",children:/* @__PURE__ */T("div",{className:"flex items-center gap-3",children:/* @__PURE__ */T("div",{className:"space-y-1 text-center",children:[t&&/* @__PURE__ */T(C,{variant:"h4",align:"center",className:"line-clamp-2",children:t}),/* @__PURE__ */T("p",{className:n("text-sm font-medium",e?"text-muted-foreground":"text-foreground"),children:["Remaining Uploads: ",/* @__PURE__ */T("span",{className:"text-primary font-bold",children:o})]})]})})})})]})}var Ut=Object.defineProperty,Rt=Object.getOwnPropertyNames,It=(e,t)=>function(){return e&&(t=(0,e[Rt(e)[0]])(e=0)),t},Pt=(e,t)=>{for(var r in t)Ut(e,r,{get:t[r],enumerable:!0})};function Nt(e){const t=e/255;return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function Ot(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 At(e,t,r){const i=Nt(e),n=Nt(t),o=Nt(r),s=.4122214708*i+.5363325363*n+.0514459929*o,a=.2119034982*i+.6806995451*n+.1073969566*o,l=.0883024619*i+.2817188376*n+.6299787005*o,d=Math.cbrt(s),c=Math.cbrt(a),u=Math.cbrt(l),h=.2104542553*d+.793617785*c-.0040720468*u,p=1.9779984951*d-2.428592205*c+.4505937099*u,m=.0259040371*d+.7827717662*c-.808675766*u,g=Math.sqrt(p*p+m*m);let f=Math.atan2(m,p)*(180/Math.PI);return f<0&&(f+=360),{l:h,c:g,h:f}}function qt(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,d=s*s*s,c=a*a*a,u=l*l*l,h=-1.2684380046*d+2.6097574011*c-.3413193965*u,p=-.0041960863*d-.7034186147*c+1.707614701*u;return[Ot(4.0767416621*d-3.3077115913*c+.2309699292*u),Ot(h),Ot(p)]}var Dt,Lt=It({"src/color-space.ts"(){}});function zt(e,t){return(Math.max(e,t)+.05)/(Math.min(e,t)+.05)}function jt(e,t,r,i,n=0){return new Dt(e,t,r,i,n)}var $t=It({"src/color.ts"(){Lt(),Dt=class{constructor(e,t,r,i,n){this._r=e,this._g=t,this._b=r,this.population=i,this.proportion=n}rgb(){return{r:this._r,g:this._g,b:this._b}}hex(){const e=e=>e.toString(16).padStart(2,"0");return`#${e(this._r)}${e(this._g)}${e(this._b)}`}hsl(){return this._hsl||(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 d=0,c=0;if(s!==a){const e=s-a;c=l>.5?e/(2-s-a):e/(s+a),d=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*d),s:Math.round(100*c),l:Math.round(100*l)}}(this._r,this._g,this._b)),this._hsl}oklch(){return this._oklch||(this._oklch=At(this._r,this._g,this._b)),this._oklch}css(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:return`rgb(${this._r}, ${this._g}, ${this._b})`}}array(){return[this._r,this._g,this._b]}toString(){return this.hex()}get textColor(){return this.isDark?"#ffffff":"#000000"}get luminance(){return void 0===this._luminance&&(this._luminance=function(e,t,r){const i=e=>{const t=e/255;return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)};return.2126*i(e)+.7152*i(t)+.0722*i(r)}(this._r,this._g,this._b)),this._luminance}get isDark(){return this.luminance<=.179}get isLight(){return!this.isDark}get contrast(){if(!this._contrast){const e=this.luminance,t=zt(e,1),r=zt(e,0),i=this.isDark?jt(255,255,255,0,0):jt(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 Bt(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"}}function Ht(e,t,r,i){const{ignoreWhite:n=!0,whiteThreshold:o=250,alphaThreshold:s=125,minSaturation:a=0}=i,l=[];for(let d=0;d<t;d+=r){const t=4*d,r=e[t],i=e[t+1],c=e[t+2],u=e[t+3];if(!(void 0!==u&&u<s||n&&r>o&&i>o&&c>o)){if(a>0){const e=Math.max(r,i,c);if(0===e||(e-Math.min(r,i,c))/e<a)continue}l.push([r,i,c])}}return l}function Vt(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)]}function Wt(e,t,r,i,n){const o=t*r,s={ignoreWhite:i.ignoreWhite,whiteThreshold:i.whiteThreshold,alphaThreshold:i.alphaThreshold,minSaturation:i.minSaturation};let a,l=Ht(e,o,i.quality,s);if(0===l.length&&(l=Ht(e,o,i.quality,{...s,ignoreWhite:!1})),0===l.length&&(l=Ht(e,o,i.quality,{...s,ignoreWhite:!1,alphaThreshold:0})),"oklch"===i.colorSpace){const e=function(e){const t=new Array(e.length);for(let r=0;r<e.length;r++){const[i,n,o]=e[r],{l:s,c:a,h:l}=At(i,n,o);t[r]=[Math.round(255*s),Math.round(a/.4*255),Math.round(l/360*255)]}return t}(l);a=n.quantize(e,i.colorCount).map(({color:[e,t,r],population:i})=>({color:qt(e/255,t/255*.4,r/255*360),population:i}))}else a=n.quantize(l,i.colorCount);if(a.length>0){const e=a.reduce((e,t)=>e+t.population,0);return a.map(({color:[t,r,i],population:n})=>jt(t,r,i,n,e>0?n/e:0))}const d=Vt(e,o,i.quality);return d?[jt(d[0],d[1],d[2],1,1)]:null}Pt({},{computeFallbackColor:()=>Vt,createPixelArray:()=>Ht,extractPalette:()=>Wt,validateOptions:()=>Bt});var Gt,Xt=It({"src/pipeline.ts"(){$t(),Lt()}});Pt({},{BrowserPixelLoader:()=>Gt});var Yt,Kt,Qt,Jt,Zt,er=It({"src/loaders/browser.ts"(){Gt=class{async load(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)return this.loadFromImage(e);if("undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement)return this.loadFromCanvas(e);if("undefined"!=typeof ImageData&&e instanceof ImageData)return{data:e.data,width:e.width,height:e.height};if("undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement)return this.loadFromVideo(e);if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return this.loadFromImageBitmap(e);if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return this.loadFromOffscreenCanvas(e);throw new Error("Unsupported source type. Expected HTMLImageElement, HTMLCanvasElement, HTMLVideoElement, ImageData, ImageBitmap, or OffscreenCanvas.")}loadFromImage(e){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.");const t=document.createElement("canvas"),r=t.getContext("2d"),i=t.width=e.naturalWidth,n=t.height=e.naturalHeight;r.drawImage(e,0,0,i,n);try{return{data:r.getImageData(0,0,i,n).data,width:i,height:n}}catch(o){if(o instanceof DOMException&&"SecurityError"===o.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=o,e}throw o}}loadFromCanvas(e){const t=e.getContext("2d"),{width:r,height:i}=e;return{data:t.getImageData(0,0,r,i).data,width:r,height:i}}loadFromVideo(e){if(e.readyState<2)throw new Error('Video is not ready. Wait for the "loadeddata" or "canplay" event before calling getColor/getPalette.');const t=e.videoWidth,r=e.videoHeight;if(!t||!r)throw new Error("Video has no dimensions. It may not have loaded successfully.");const i=document.createElement("canvas"),n=i.getContext("2d");return i.width=t,i.height=r,n.drawImage(e,0,0,t,r),{data:n.getImageData(0,0,t,r).data,width:t,height:r}}loadFromOffscreenCanvas(e){const t=e.getContext("2d");if(!t)throw new Error("Could not get 2D context from OffscreenCanvas.");const{width:r,height:i}=e;return{data:t.getImageData(0,0,r,i).data,width:r,height:i}}loadFromImageBitmap(e){const t=document.createElement("canvas"),r=t.getContext("2d");return t.width=e.width,t.height=e.height,r.drawImage(e,0,0),{data:r.getImageData(0,0,e.width,e.height).data,width:e.width,height:e.height}}}}}),tr=It({"src/worker/worker-script.ts"(){Yt="\n'use strict';\n\n// -------------------------------------------------------------------------\n// Inlined MMCQ (Modified Median Cut Quantization)\n// -------------------------------------------------------------------------\n\nvar SIGBITS = 5;\nvar RSHIFT = 3;\nvar MAX_ITER = 1000;\nvar FRACT_POP = 0.75;\nvar HISTO_SIZE = 32768;\n\nfunction colorIndex(r, g, b) {\n return (r << 10) + (g << 5) + b;\n}\n\nfunction getHisto(pixels) {\n var h = new Uint32Array(HISTO_SIZE);\n for (var i = 0; i < pixels.length; i++) {\n var p = pixels[i];\n h[colorIndex(p[0] >> RSHIFT, p[1] >> RSHIFT, p[2] >> RSHIFT)]++;\n }\n return h;\n}\n\nfunction VBox(r1, r2, g1, g2, b1, b2, histo) {\n this.r1 = r1; this.r2 = r2;\n this.g1 = g1; this.g2 = g2;\n this.b1 = b1; this.b2 = b2;\n this.histo = histo;\n this._count = -1;\n this._volume = -1;\n this._avg = null;\n}\n\nVBox.prototype.volume = function(force) {\n if (this._volume < 0 || force) {\n this._volume = (this.r2 - this.r1 + 1) * (this.g2 - this.g1 + 1) * (this.b2 - this.b1 + 1);\n }\n return this._volume;\n};\n\nVBox.prototype.count = function(force) {\n if (this._count < 0 || force) {\n var n = 0;\n for (var i = this.r1; i <= this.r2; i++)\n for (var j = this.g1; j <= this.g2; j++)\n for (var k = this.b1; k <= this.b2; k++)\n n += this.histo[colorIndex(i, j, k)] || 0;\n this._count = n;\n }\n return this._count;\n};\n\nVBox.prototype.copy = function() {\n return new VBox(this.r1, this.r2, this.g1, this.g2, this.b1, this.b2, this.histo);\n};\n\nVBox.prototype.avg = function(force) {\n if (!this._avg || force) {\n var mult = 1 << RSHIFT;\n if (this.r1 === this.r2 && this.g1 === this.g2 && this.b1 === this.b2) {\n this._avg = [this.r1 << RSHIFT, this.g1 << RSHIFT, this.b1 << RSHIFT];\n } else {\n var ntot = 0, rsum = 0, gsum = 0, bsum = 0;\n for (var i = this.r1; i <= this.r2; i++)\n for (var j = this.g1; j <= this.g2; j++)\n for (var k = this.b1; k <= this.b2; k++) {\n var hval = this.histo[colorIndex(i, j, k)] || 0;\n ntot += hval;\n rsum += hval * (i + 0.5) * mult;\n gsum += hval * (j + 0.5) * mult;\n bsum += hval * (k + 0.5) * mult;\n }\n this._avg = ntot\n ? [~~(rsum / ntot), ~~(gsum / ntot), ~~(bsum / ntot)]\n : [~~(mult * (this.r1 + this.r2 + 1) / 2), ~~(mult * (this.g1 + this.g2 + 1) / 2), ~~(mult * (this.b1 + this.b2 + 1) / 2)];\n }\n }\n return this._avg;\n};\n\nfunction PQueue(comparator) {\n this.contents = [];\n this.sorted = false;\n this.comparator = comparator;\n}\n\nPQueue.prototype.push = function(item) { this.contents.push(item); this.sorted = false; };\nPQueue.prototype.pop = function() {\n if (!this.sorted) { this.contents.sort(this.comparator); this.sorted = true; }\n return this.contents.pop();\n};\nPQueue.prototype.size = function() { return this.contents.length; };\n\nfunction vboxFromPixels(pixels, histo) {\n var rmin = 1e6, rmax = 0, gmin = 1e6, gmax = 0, bmin = 1e6, bmax = 0;\n for (var i = 0; i < pixels.length; i++) {\n var p = pixels[i];\n var rv = p[0] >> RSHIFT, gv = p[1] >> RSHIFT, bv = p[2] >> RSHIFT;\n if (rv < rmin) rmin = rv; if (rv > rmax) rmax = rv;\n if (gv < gmin) gmin = gv; if (gv > gmax) gmax = gv;\n if (bv < bmin) bmin = bv; if (bv > bmax) bmax = bv;\n }\n return new VBox(rmin, rmax, gmin, gmax, bmin, bmax, histo);\n}\n\nfunction medianCutApply(histo, vbox) {\n if (!vbox.count()) return undefined;\n if (vbox.count() === 1) return [vbox.copy(), null];\n\n var rw = vbox.r2 - vbox.r1 + 1;\n var gw = vbox.g2 - vbox.g1 + 1;\n var bw = vbox.b2 - vbox.b1 + 1;\n var maxw = Math.max(rw, gw, bw);\n var total = 0;\n var partialsum = [];\n var lookaheadsum = [];\n var i, j, k, sum;\n\n if (maxw === rw) {\n for (i = vbox.r1; i <= vbox.r2; i++) {\n sum = 0;\n for (j = vbox.g1; j <= vbox.g2; j++)\n for (k = vbox.b1; k <= vbox.b2; k++)\n sum += histo[colorIndex(i, j, k)] || 0;\n total += sum; partialsum[i] = total;\n }\n } else if (maxw === gw) {\n for (i = vbox.g1; i <= vbox.g2; i++) {\n sum = 0;\n for (j = vbox.r1; j <= vbox.r2; j++)\n for (k = vbox.b1; k <= vbox.b2; k++)\n sum += histo[colorIndex(j, i, k)] || 0;\n total += sum; partialsum[i] = total;\n }\n } else {\n for (i = vbox.b1; i <= vbox.b2; i++) {\n sum = 0;\n for (j = vbox.r1; j <= vbox.r2; j++)\n for (k = vbox.g1; k <= vbox.g2; k++)\n sum += histo[colorIndex(j, k, i)] || 0;\n total += sum; partialsum[i] = total;\n }\n }\n\n partialsum.forEach(function(d, idx) { lookaheadsum[idx] = total - d; });\n\n function doCut(color) {\n var dim1 = color + '1', dim2 = color + '2';\n for (var i = vbox[dim1]; i <= vbox[dim2]; i++) {\n if (partialsum[i] > total / 2) {\n var vbox1 = vbox.copy(), vbox2 = vbox.copy();\n var left = i - vbox[dim1], right = vbox[dim2] - i;\n var d2 = left <= right\n ? Math.min(vbox[dim2] - 1, ~~(i + right / 2))\n : Math.max(vbox[dim1], ~~(i - 1 - left / 2));\n while (!partialsum[d2]) d2++;\n var count2 = lookaheadsum[d2];\n while (!count2 && partialsum[d2 - 1]) count2 = lookaheadsum[--d2];\n vbox1[dim2] = d2;\n vbox2[dim1] = d2 + 1;\n return [vbox1, vbox2];\n }\n }\n }\n\n if (maxw === rw) return doCut('r');\n if (maxw === gw) return doCut('g');\n return doCut('b');\n}\n\nfunction iterate(pq, target, histo) {\n var ncolors = pq.size(), niters = 0;\n while (niters < MAX_ITER) {\n if (ncolors >= target) return;\n niters++;\n var vbox = pq.pop();\n if (!vbox.count()) { pq.push(vbox); continue; }\n var result = medianCutApply(histo, vbox);\n if (!result || !result[0]) return;\n pq.push(result[0]);\n if (result[1]) { pq.push(result[1]); ncolors++; }\n }\n}\n\nfunction quantize(pixels, maxColors) {\n if (!pixels.length || maxColors < 2 || maxColors > 256) return [];\n\n var histo = getHisto(pixels);\n var vbox = vboxFromPixels(pixels, histo);\n var pq = new PQueue(function(a, b) { return a.count() - b.count(); });\n pq.push(vbox);\n iterate(pq, FRACT_POP * maxColors, histo);\n\n var pq2 = new PQueue(function(a, b) { return a.count() * a.volume() - b.count() * b.volume(); });\n while (pq.size()) pq2.push(pq.pop());\n iterate(pq2, maxColors, histo);\n\n var results = [];\n while (pq2.size()) {\n var box = pq2.pop();\n results.push({ color: box.avg(), population: box.count() });\n }\n return results;\n}\n\n// -------------------------------------------------------------------------\n// Worker message handler\n// -------------------------------------------------------------------------\n\nself.onmessage = function (e) {\n var data = e.data;\n var id = data.id;\n try {\n var palette = quantize(data.pixels, data.maxColors);\n self.postMessage({ id: id, palette: palette });\n } catch (err) {\n self.postMessage({ id: id, error: err.message || 'Unknown worker error' });\n }\n};\n"}});function rr(){return"undefined"!=typeof Worker}function ir(e,t,r){return new Promise((i,n)=>{if(r?.aborted)return void n(r.reason??new DOMException("Aborted","AbortError"));const o=Jt++;Zt.set(o,{resolve:i,reject:n});const s=()=>{Zt.delete(o),n(r.reason??new DOMException("Aborted","AbortError"))};r?.addEventListener("abort",s,{once:!0});try{(function(){if(Kt)return Kt;if(!rr())throw new Error("Web Workers are not supported in this environment.");return Qt=URL.createObjectURL(new Blob([Yt],{type:"application/javascript"})),(Kt=new Worker(Qt)).onmessage=e=>{const{id:t,palette:r,error:i}=e.data,n=Zt.get(t);if(n)if(Zt.delete(t),i)n.reject(new Error(i));else{const e=r,t=e.reduce((e,t)=>e+t.population,0),i=e.map(({color:[e,r,i],population:n})=>jt(e,r,i,n,t>0?n/t:0));n.resolve(i)}},Kt.onerror=e=>{for(const[,t]of Zt)t.reject(new Error(e.message));Zt.clear()},Kt})().postMessage({id:o,pixels:e,maxColors:t})}catch(a){Zt.delete(o),r?.removeEventListener("abort",s),n(a)}})}function nr(){Kt&&(Kt.terminate(),Kt=null),Qt&&(URL.revokeObjectURL(Qt),Qt=null);for(const[,e]of Zt)e.reject(/* @__PURE__ */new Error("Worker terminated"));Zt.clear()}function or(e,t,r){return(e<<10)+(t<<5)+r}Pt({},{extractInWorker:()=>ir,isWorkerSupported:()=>rr,terminateWorker:()=>nr}),It({"src/worker/manager.ts"(){$t(),tr(),Kt=null,Qt=null,Jt=0,Zt=/* @__PURE__ */new Map}}),Xt(),Xt(),$t(),jt(255,255,255,0),jt(0,0,0,0);var sr=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[or(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[or(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}},ar=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 lr(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 d=t.r1;d<=t.r2;d++){let r=0;for(let i=t.g1;i<=t.g2;i++)for(let n=t.b1;n<=t.b2;n++)r+=e[or(d,i,n)]||0;s+=r,a[d]=s}else if(o===i)for(let d=t.g1;d<=t.g2;d++){let r=0;for(let i=t.r1;i<=t.r2;i++)for(let n=t.b1;n<=t.b2;n++)r+=e[or(i,d,n)]||0;s+=r,a[d]=s}else for(let d=t.b1;d<=t.b2;d++){let r=0;for(let i=t.r1;i<=t.r2;i++)for(let n=t.g1;n<=t.g2;n++)r+=e[or(i,n,d)]||0;s+=r,a[d]=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],d=t[i]-n;let c;for(c=s<=d?Math.min(t[i]-1,~~(n+d/2)):Math.max(t[r],~~(n-1-s/2));!a[c];)c++;let u=l[c];for(;!u&&a[c-1];)u=l[--c];return e[i]=c,o[r]=e[i]+1,[e,o]}}(o===r?"r":o===i?"g":"b")}function dr(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=lr(r,o);if(!s||!s[0])return;e.push(s[0]),s[1]&&(e.push(s[1]),i++)}}er(),Xt(),new Gt;var cr=new class{async init(){}quantize(e,t){return function(e,t){if(!e.length||t<2||t>256)return[];const r=/* @__PURE__ */new Set,i=[];for(const d of e){const e=d.join(",");r.has(e)||(r.add(e),i.push(d))}if(i.length<=t){const t=/* @__PURE__ */new Map;for(const r of e){const e=r.join(",");t.set(e,(t.get(e)||0)+1)}return i.map(e=>({color:e,population:t.get(e.join(","))}))}const n=function(e){const t=new Uint32Array(32768);for(const r of e)t[or(r[0]>>3,r[1]>>3,r[2]>>3)]++;return t}(e),o=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,d=l[2]>>3;e<r?r=e:e>i&&(i=e),t<n?n=t:t>o&&(o=t),d<s?s=d:d>a&&(a=d)}return new sr(r,i,n,o,s,a,t)}(e,n),s=new ar((e,t)=>e.count()-t.count());s.push(o),dr(s,.75*t,n);const a=new ar((e,t)=>e.count()*e.volume()-t.count()*t.volume());for(;s.size();)a.push(s.pop());dr(a,t,n);const l=[];for(;a.size();){const e=a.pop();l.push({color:e.avg(),population:e.count()})}return l}(e,t)}};function ur(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 d=a.getImageData(0,0,n,o),c={};try{c.blurhash=l(d.data,n,o,4,4)}catch(u){console.warn("[media-intrinsics] blurhash encode failed:",u)}try{const e=function(e,t){const r=Bt(t??{}),i=t?.quantizer??cr,n=function(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)return function(e){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.");const t=document.createElement("canvas"),r=t.getContext("2d"),i=t.width=e.naturalWidth,n=t.height=e.naturalHeight;r.drawImage(e,0,0,i,n);try{return{data:r.getImageData(0,0,i,n).data,width:i,height:n}}catch(o){if(o instanceof DOMException&&"SecurityError"===o.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=o,e}throw o}}(e);if("undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement)return function(e){const t=e.getContext("2d"),{width:r,height:i}=e;return{data:t.getImageData(0,0,r,i).data,width:r,height:i}}(e);if("undefined"!=typeof ImageData&&e instanceof ImageData)return{data:e.data,width:e.width,height:e.height};if("undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement)return function(e){if(e.readyState<2)throw new Error('Video is not ready. Wait for the "loadeddata" or "canplay" event before calling getColorSync/getPaletteSync.');const t=e.videoWidth,r=e.videoHeight;if(!t||!r)throw new Error("Video has no dimensions. It may not have loaded successfully.");const i=document.createElement("canvas"),n=i.getContext("2d");return i.width=t,i.height=r,n.drawImage(e,0,0,t,r),{data:n.getImageData(0,0,t,r).data,width:t,height:r}}(e);if("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap)return function(e){const t=document.createElement("canvas"),r=t.getContext("2d");return t.width=e.width,t.height=e.height,r.drawImage(e,0,0),{data:r.getImageData(0,0,e.width,e.height).data,width:e.width,height:e.height}}(e);if("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas)return function(e){const t=e.getContext("2d");if(!t)throw new Error("Could not get 2D context from OffscreenCanvas.");const{width:r,height:i}=e;return{data:t.getImageData(0,0,r,i).data,width:r,height:i}}(e);throw new Error("Unsupported source type. Expected HTMLImageElement, HTMLCanvasElement, HTMLVideoElement, ImageData, ImageBitmap, or OffscreenCanvas.")}(e);return Wt(n.data,n.width,n.height,r,i)}(s,{colorCount:5});e&&(c.colors={palette:e.map(e=>e.hex())})}catch(u){console.warn("[media-intrinsics] palette extraction failed:",u)}return c}function hr(e,t){return Object.hasOwn(e,t)}$t();var{AbortController:pr}=globalThis,{AbortSignal:mr}=globalThis,gr=(e="Aborted",t)=>{const r=new DOMException(e,"AbortError");return null!=t&&hr(t,"cause")&&Object.defineProperty(r,"cause",{__proto__:null,configurable:!0,writable:!0,value:t.cause}),r},fr=class extends Error{isNetworkError;cause;constructor(e,t){super(e),this.cause=t?.cause,this.cause&&hr(this.cause,"isNetworkError")?this.isNetworkError=this.cause.isNetworkError:this.isNetworkError=!1}},vr=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 br(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 yr={__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 wr(e){if(e.type)return e.type;const t=e.name?br(e.name).extension?.toLowerCase():null;return t&&t in yr?yr[t]:"application/octet-stream"}function xr(e){let t="";return e.replace(/[^A-Z0-9]/gi,e=>(t+=`-${function(e){return e.charCodeAt(0).toString(32)}(e)}`,"/"))+t}function Sr(e,t){return!0===e?Object.keys(t):Array.isArray(e)?e:[]}function Tr(e){return e<10?`0${e}`:e.toString()}function Cr(){const e=/* @__PURE__ */new Date;return`${Tr(e.getHours())}:${Tr(e.getMinutes())}:${Tr(e.getSeconds())}`}function Fr(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 kr=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.#d())}#d(){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}#c(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.#c(e,t)}wrapSyncFunction(e,t){return(...r)=>{const i=this.run(()=>(e(...r),queueMicrotask(()=>i.done()),()=>{}),t);return{abortOn:Fr,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=Fr,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 Er(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 _r(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=Er(i,new RegExp(`%\\{${n}\\}`,"g"),e)}return i}var Mr=e=>{throw new Error(`missing string: ${e}`)},Ur=class{locale;constructor(e,{onMissingKey:t=Mr}={}){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 _r(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 _r(r,t)}},Rr=class extends Error{name="UserFacingApiError"},Ir=/* @__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}}),Pr=/* @__PURE__ */t(e=>{var t=Ir();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}}}),Nr=/* @__PURE__ */t((e,t)=>{t.exports=Pr()}),Or=Object.prototype.toString,Ar=/* @__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 qr=/* @__PURE__ */e(Nr(),1),Dr=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}},Lr=(e,t,r)=>{const i=r.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=i,e};async function zr(e,t){return new Promise((r,i)=>{t={...t},t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>!0,t.retries??=10;const n=qr.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 Dr)throw a.originalError;if(a instanceof TypeError&&!function(e){if(!e||(t=e,"[object Error]"!==Or.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(")"))||Ar.has(r)}(a))throw a;if(Lr(a,o,t),await t.shouldRetry(a)||(n.stop(),i(a)),await t.onFailedAttempt(a),!n.retry(a))throw n.mainError()}catch(l){Lr(l,o,t),s(),i(l)}}})})}var jr=class extends Error{isAuthError;constructor(){super("Authorization required"),this.name="AuthError",this.isAuthError=!0}},$r=class extends Error{statusCode;constructor({statusCode:e,message:t}){super(t),this.name="HttpError",this.statusCode=e}},Br=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 vr(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 jr;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 Rr(t.message);throw new $r({statusCode:e.status,message:r})}(s)}catch(o){if(o.isAuthError||"UserFacingApiError"===o.name||"AbortError"===o.name)throw o;throw new fr(`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 zr(async()=>{const r=this.uppy.getFile(e.id)?.serverToken;if(null!=r)return this.uppy.log(`Connecting to exiting websocket ${r}`),this.#b({file:e,queue:n(),signal:i});const o=await n().wrapPromiseFunction(async(...e)=>{try{return await this.#y(...e)}catch(t){if(t.isAuthError)throw new Dr(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 Dr(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.#b({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}}#y=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#b({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 d,c,u,{isPaused:h}=e;const p=(t,r)=>{null!=d&&d.readyState===d.OPEN?d.send(JSON.stringify({action:t,payload:r??{}})):this.uppy.log(`Cannot send "${t}" to socket ${e.id} because the socket state was ${String(d?.readyState)}`,"warning")};function m(){n.resumableUploads&&p(h?"pause":"resume")}const g=e=>{n.resumableUploads&&(h=e,d&&m())},f=t=>{n.individualCancellation&&t.id===e.id&&(p("cancel"),c?.abort?.(),this.uppy.log(`upload ${e.id} was removed`),o())},v=()=>{p("cancel"),c?.abort?.(),this.uppy.log(`upload ${e.id} was canceled`),o()},b=(t,r)=>{t?.id===e.id&&g(r)},y=()=>g(!0),w=()=>g(!1);this.uppy.on("file-removed",f),this.uppy.on("cancel-all",v),this.uppy.on("upload-pause",b),this.uppy.on("pause-all",y),this.uppy.on("resume-all",w),i=()=>{this.uppy.off("file-removed",f),this.uppy.off("cancel-all",v),this.uppy.off("upload-pause",b),this.uppy.off("pause-all",y),this.uppy.off("resume-all",w)},r.addEventListener("abort",()=>{c?.abort()}),(async()=>{c&&c.abort(),c=new AbortController;const r=t=>{this.uppy.setFileState(e.id,{serverToken:null}),c?.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 zr(async()=>new Promise((t,n)=>{d=new WebSocket(`${l}/api/${a}`),i(),d.addEventListener("close",()=>{d=void 0,n(/* @__PURE__ */new Error("Socket closed unexpectedly"))}),d.addEventListener("error",e=>{this.uppy.log(`Companion socket error ${JSON.stringify(e)}, closing socket`,"warning"),d?.close()}),d.addEventListener("open",()=>{m()}),d.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}),c?.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),d&&d.close(),d=void 0};c.signal.addEventListener("abort",()=>{s()})}),{retries:10,signal:c.signal,onFailedAttempt:()=>{c.signal.aborted||this.uppy.log(`Retrying websocket ${e.id}`)}})})().abortOn(c.signal)}catch(n){if(c.signal.aborted)return;r(n)}})()})}finally{i?.()}}},Hr=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 Ur([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(){}},Vr=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()})}},Wr={debug:()=>{},warn:()=>{},error:(...e)=>console.error(`[Uppy] [${Cr()}]`,...e)},Gr={debug:(...e)=>console.debug(`[Uppy] [${Cr()}]`,...e),warn:(...e)=>console.warn(`[Uppy] [${Cr()}]`,...e),error:(...e)=>console.error(`[Uppy] [${Cr()}]`,...e)},Xr=/* @__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}`}}),Yr=/* @__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}}),Kr=/* @__PURE__ */t((e,t)=>{var r=Yr(),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}}),Qr=/* @__PURE__ */e(Xr(),1),Jr=/* @__PURE__ */e(Kr(),1),Zr={maxFileSize:null,minFileSize:null,maxTotalFileSize:null,maxNumberOfFiles:null,minNumberOfFiles:null,allowedFileTypes:null,requiredMetaFields:[]},ei=class extends Error{isUserFacing;file;constructor(e,t){super(e),this.isUserFacing=t?.isUserFacing??!0,t?.file&&(this.file=t.file)}isRestriction=!0},ti=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 ei(`${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 ei(this.getI18n()("aggregateExceedsSize",{sizeAllowed:(0,Qr.default)(r),size:(0,Qr.default)(i)}))}}validateSingleFile(e){const{maxFileSize:t,minFileSize:r,allowedFileTypes:i}=this.getOpts().restrictions;if(i&&!i.some(t=>t.includes("/")?!!e.type&&(0,Jr.default)(e.type.replace(/;.*?$/,""),t):!("."!==t[0]||!e.extension)&&e.extension.toLowerCase()===t.slice(1).toLowerCase())){const t=i.join(", ");throw new ei(this.getI18n()("youCanOnlyUploadFileTypes",{types:t}),{file:e})}if(t&&null!=e.size&&e.size>t)throw new ei(this.getI18n()("exceedsSize",{size:(0,Qr.default)(t),file:e.name??this.getI18n()("unnamed")}),{file:e});if(r&&null!=e.size&&e.size<r)throw new ei(this.getI18n()("inferiorSize",{size:(0,Qr.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 ei(this.getI18n()("youHaveToAtLeastSelectX",{smart_count:t}))}getMissingRequiredMetaFields(e){const t=new ei(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}}},ri=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)})}},ii=/* @__PURE__ */t((e,t)=>{t.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}}),ni=/* @__PURE__ */t((e,t)=>{var r="object"==typeof global&&global&&global.Object===Object&&global;t.exports=r}),oi=/* @__PURE__ */t((e,t)=>{var r=ni(),i="object"==typeof self&&self&&self.Object===Object&&self,n=r||i||Function("return this")();t.exports=n}),si=/* @__PURE__ */t((e,t)=>{var r=oi();t.exports=function(){return r.Date.now()}}),ai=/* @__PURE__ */t((e,t)=>{var r=/\s/;t.exports=function(e){for(var t=e.length;t--&&r.test(e.charAt(t)););return t}}),li=/* @__PURE__ */t((e,t)=>{var r=ai(),i=/^\s+/;t.exports=function(e){return e?e.slice(0,r(e)+1).replace(i,""):e}}),di=/* @__PURE__ */t((e,t)=>{var r=oi().Symbol;t.exports=r}),ci=/* @__PURE__ */t((e,t)=>{var r=di(),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}}),ui=/* @__PURE__ */t((e,t)=>{var r=Object.prototype.toString;t.exports=function(e){return r.call(e)}}),hi=/* @__PURE__ */t((e,t)=>{var r=di(),i=ci(),n=ui(),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)}}),pi=/* @__PURE__ */t((e,t)=>{t.exports=function(e){return null!=e&&"object"==typeof e}}),mi=/* @__PURE__ */t((e,t)=>{var r=hi(),i=pi();t.exports=function(e){return"symbol"==typeof e||i(e)&&"[object Symbol]"==r(e)}}),gi=/* @__PURE__ */t((e,t)=>{var r=li(),i=ii(),n=mi(),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 d=s.test(e);return d||a.test(e)?l(e.slice(2),d?2:8):o.test(e)?NaN:+e}}),fi=/* @__PURE__ */t((e,t)=>{var r=ii(),i=si(),n=gi(),o=Math.max,s=Math.min;t.exports=function(e,t,a){var l,d,c,u,h,p,m=0,g=!1,f=!1,v=!0;if("function"!=typeof e)throw new TypeError("Expected a function");function b(t){var r=l,i=d;return l=d=void 0,m=t,u=e.apply(i,r)}function y(e){var r=e-p;return void 0===p||r>=t||r<0||f&&e-m>=c}function w(){var e=i();if(y(e))return x(e);h=setTimeout(w,function(e){var r=t-(e-p);return f?s(r,c-(e-m)):r}(e))}function x(e){return h=void 0,v&&l?b(e):(l=d=void 0,u)}function S(){var e=i(),r=y(e);if(l=arguments,d=this,p=e,r){if(void 0===h)return function(e){return m=e,h=setTimeout(w,t),g?b(e):u}(p);if(f)return clearTimeout(h),h=setTimeout(w,t),b(p)}return void 0===h&&(h=setTimeout(w,t)),u}return t=n(t)||0,r(a)&&(g=!!a.leading,c=(f="maxWait"in a)?o(n(a.maxWait)||0,t):c,v="trailing"in a?!!a.trailing:v),S.cancel=function(){void 0!==h&&clearTimeout(h),m=0,l=p=d=h=void 0},S.flush=function(){return void 0===h?u:x(i())},S}}),vi=/* @__PURE__ */t((e,t)=>{var r=fi(),i=ii();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})}}),bi=/* @__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}}),yi={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 wi(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 xi=/* @__PURE__ */e(vi(),1),Si=/* @__PURE__ */e(bi(),1),Ti={totalProgress:0,allowNewUpload:!0,error:null,recoveredState:null},Ci=class e{static VERSION="5.2.0";#C=Object.create(null);#F;#k;#E=(0,Si.default)();#_=/* @__PURE__ */new Set;#M=/* @__PURE__ */new Set;#U=/* @__PURE__ */new Set;defaultLocale;locale;opts;store;i18n;i18nArray;scheduledAutoProceed=null;wasOffline=!1;constructor(t){this.defaultLocale=yi;const r={id:"uppy",autoProceed:!1,allowMultipleUploadBatches:!0,debug:!1,restrictions:Zr,meta:{},onBeforeFileAdded:(e,t)=>!Object.hasOwn(t,e.id),onBeforeUpload:e=>e,store:new ri,logger:Wr,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=Gr),this.log(`Using Core v${e.VERSION}`),this.i18nInit(),this.store=this.opts.store,this.setState({...Ti,plugins:{},files:{},currentUploads:{},capabilities:{uploadProgress:wi(),individualCancellation:!0,resumableUploads:!1},meta:{...this.opts.meta},info:[]}),this.#F=new ti(()=>this.opts,()=>this.i18n),this.#k=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 Ur([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,...Ti})}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({...Ti,files:{}})}addPreProcessor(e){this.#_.add(e)}removePreProcessor(e){return this.#_.delete(e)}addPostProcessor(e){this.#U.add(e)}removePostProcessor(e){return this.#U.delete(e)}addUploader(e){this.#M.add(e)}removeUploader(e){return this.#M.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=[],d=[],c=[],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&&d.push(p),p.error&&c.push(p),(e.preprocess||e.postprocess)&&h.push(p)}return{newFiles:o,startedFiles:s,uploadStartedFiles:a,pausedFiles:l,completeFiles:d,erroredFiles:c,inProgressFiles:n,inProgressNotPausedFiles:u,processingFiles:h,isUploadStarted:a.length>0,isAllComplete:100===t&&d.length===i.length&&0===h.length,isAllErrored:!!r&&c.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}#P(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)}#N(e){let t=!0;for(const r of Object.values(e))this.#P(r)||(t=!1);return t}#O(e){const{allowNewUpload:t}=this.getState();if(!1===t){const t=new ei(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=wr(t),i=function(e,t){return t.name?t.name:"image"===e.split("/")[0]?`${e.split("/")[0]}.${e.split("/")[1]}`:"noname"}(r,t),n=br(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=wr(e);return function(e,t){let r=t||"uppy";return"string"==typeof e.name&&(r+=`-${xr(e.name.toLowerCase())}`),void 0!==e.type&&(r+=`-${e.type}`),e.meta&&"string"==typeof e.meta.relativePath&&(r+=`-${xr(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 ei(this.i18n("noDuplicates",{fileName:e.name??this.i18n("unnamed")}),{file:e});if(!1===a&&!o)throw new ei("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(Ti)}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,xi.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.#P(e)}),"undefined"!=typeof window&&window.addEventListener&&(window.addEventListener("online",this.#G),window.addEventListener("offline",this.#G),setTimeout(this.#G,3e3))}updateOnlineStatus(){window.navigator.onLine??1?(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.#k(),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.#_,...this.#M,...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.#N(e))throw new ei(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 Fi({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 ki=new TextEncoder,Ei={name:"HMAC",hash:"SHA-256"};async function _i(e){const{subtle:t}=globalThis.crypto;return t.digest(Ei.hash,ki.encode(e))}function Mi(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 Ui(e,t){const{subtle:r}=globalThis.crypto;return r.sign(Ei,await async function(e){const{subtle:t}=globalThis.crypto;return t.importKey("raw","string"==typeof e?ki.encode(e):e,Ei,!1,["sign"])}(e),ki.encode(t))}async function Ri({accountKey:e,accountSecret:t,sessionToken:r,bucketName:i,Key:n,Region:o,expires:s,uploadId:a,partNumber:l}){const d="s3",c=`${d}.${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}/${d}/aws4_request`,f=new URL(`https://${c}${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,Mi(await _i(Fi({CanonicalUri:u,CanonicalQueryString:f.search.slice(1),SignedHeaders:{host:c},HashedPayload:h})))].join("\n"),b=Mi(await Ui(await Ui(await Ui(await Ui(await Ui(`AWS4${t}`,m),o),d),"aws4_request"),v));return f.searchParams.set("X-Amz-Signature",b),f}var Ii={getChunkSize:e=>Math.ceil(e.size/1e4),onProgress(){},onPartComplete(){},onSuccess(){},onError(e){throw e}},Pi=Symbol("pausing upload, not an actual error"),Ni=class{options;#Q=new pr;#J=[];#Z=[];#ee;#te;#re=!1;#ie;#ne;#oe;#se;#ae=e=>e?.cause===Pi?null:this.#ie(e);#le=1e4;#de=5242880;constructor(e,t){this.options={...Ii,...t},this.options.getChunkSize??=Ii.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.#ce()}#ce(){const e=this.#ee.size,t="function"==typeof this.#oe?this.#oe(this.#te):Boolean(this.#oe);if(t&&e>this.#de){let r=Math.max(this.options.getChunkSize(this.#ee),this.#de),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(Pi),this.#Q=new pr,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(Pi),this.#Q=new pr}abort(e){e?.really?this.#me():this.pause()}[Symbol.for("uppy test: getChunkState")](){return this.#Z}};function Oi(e){if(e?.aborted)throw gr("The operation was aborted",{cause:e.reason})}function Ai(e){const t=new URL(e);return t.search="",t.hash="",t.href}var qi=class{#ge;#fe=/* @__PURE__ */new WeakMap;#ve;#be;#ye;#we;#xe;#Se;#Te;#Ce;#Fe;#ke;#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.#be=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.#ke=t.wrapPromiseFunction(e.uploadPartBytes,{priority:1/0})),"getUploadParameters"in e&&(this.#ye=t.wrapPromiseFunction(e.getUploadParameters))}async#_e(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#Me(e,t,r){const{method:i="POST",url:n,fields:o,headers:s}=await this.#ye(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:d,onComplete:c}=t,u=await this.#ke({signature:{url:n,headers:s,method:i},body:a,size:l.size,onProgress:d,onComplete:c,signal:r}).abortOn(r),h=o?.key;return this.#Fe(e,{key:h}),{...u,location:u.location??Ai(n),bucket:o?.bucket,key:h}}async uploadFile(e,t,r){if(Oi(r),1===t.length&&!t[0].shouldUseMultipart)return this.#Me(e,t[0],r);const{uploadId:i,key:n}=await this.getUploadId(e,r);Oi(r);try{const o=await Promise.all(t.map((t,i)=>this.uploadChunk(e,i+1,t,r)));return Oi(r),await this.#Ce(this.#Ee(e),{key:n,uploadId:i,parts:o,signal:r},r).abortOn(r)}catch(o){throw o?.cause!==Pi&&"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(Oi(r),1===t.length&&null!=t[0]&&!t[0].shouldUseMultipart)return this.#Me(e,t[0],r);const{uploadId:i,key:n}=await this.getUploadId(e,r);Oi(r);const o=await this.#we(this.#Ee(e),{uploadId:i,key:n,signal:r},r).abortOn(r);Oi(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 Oi(r),this.#Ce(this.#Ee(e),{key:n,uploadId:i,parts:s,signal:r},r).abortOn(r)}async uploadChunk(e,t,r,i){Oi(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(;;){Oi(i);const s=r.getData(),{onProgress:c,onComplete:u}=r;let h;try{h=await this.#be(this.#Ee(e),{uploadId:n,key:o,partNumber:t,body:s,signal:i}).abortOn(i)}catch(d){const e=l();if(null==e||i.aborted)throw d;await new Promise(t=>setTimeout(t,e));continue}Oi(i);try{return{PartNumber:t,...await this.#ke({signature:h,body:s,size:s.size,onProgress:c,onComplete:u,signal:i}).abortOn(i)}}catch(d){if(!(await this.#_e(d,a)))throw d}}}};function Di(e){if(e?.error){const t=new Error(e.message);throw Object.assign(t,e.error),t}return e}function Li(e){const t=e.Expiration;if(t){const e=Math.floor((new Date(t)-Date.now())/1e3);if(e>9)return e}}function zi({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 ji={allowedMetaFields:!0,limit:6,getTemporarySecurityCredentials:!1,shouldUseMultipart:e=>(e.size||0)>104857600,retryDelays:[0,1e3,3e3,5e3]},$i=class e extends Hr{static VERSION="5.1.0";#Ue;#Re;requests;uploaderEvents;uploaders;constructor(t,r){super(t,{...ji,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 kr(this.opts.limit),this.#Ue=new qi(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 Br(this.uppy,{pluginId:this.id,provider:"AWS",companionUrl:this.opts.endpoint,companionHeaders:this.opts.headers,companionCookiesRule:this.opts.cookiesRule}):("headers"in e&&this.#Pe(),"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)}#Ne(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.#Ne("createMultipartUpload"),Oi(t);const r=Sr(this.opts.allowedMetaFields,e.meta),i=zi({meta:e.meta,allowedMetaFields:r});return this.#Re.post("s3/multipart",{filename:e.name,type:e.type,metadata:i},{signal:t}).then(Di)}listParts(e,{key:t,uploadId:r,signal:i},n){i??=n,this.#Ne("listParts"),Oi(i);const o=encodeURIComponent(t);return this.#Re.get(`s3/multipart/${encodeURIComponent(r)}?key=${o}`,{signal:i}).then(Di)}completeMultipartUpload(e,{key:t,uploadId:r,parts:i,signal:n},o){n??=o,this.#Ne("completeMultipartUpload"),Oi(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(Di)}#Oe;async#Ae(e){if(Oi(e?.signal),null==this.#Oe){const{getTemporarySecurityCredentials:t}=this.opts;!0===t?(this.#Ne("getTemporarySecurityCredentials"),this.#Oe=this.#Re.get("s3/sts",e).then(Di)):this.#Oe=t(e),this.#Oe=await this.#Oe,setTimeout(()=>{this.#Oe=null},500*(Li(this.#Oe.credentials)||0))}return this.#Oe}async createSignedURL(e,t){const r=await this.#Ae(t),i=Li(r.credentials)||604800,{uploadId:n,key:o,partNumber:s}=t;return{method:"PUT",expires:i,fields:{},url:`${await Ri({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.#Ne("signPart"),Oi(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(Di)}abortMultipartUpload(e,{key:t,uploadId:r,signal:i}){this.#Ne("abortMultipartUpload");const n=encodeURIComponent(t),o=encodeURIComponent(r);return this.#Re.delete(`s3/multipart/${o}?key=${n}`,void 0,{signal:i}).then(Di)}getUploadParameters(e,t){this.#Ne("getUploadParameters");const{meta:r}=e,{type:i,name:n}=r,o=zi({meta:r,allowedMetaFields:Sr(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(Oi(l),null==e)throw new Error("Cannot upload to an undefined URL");return new Promise((d,c)=>{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(),c(gr())}),u.addEventListener("timeout",()=>{p();const e=/* @__PURE__ */new Error("Request has expired");e.source={status:403},c(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 c(e)}if(u.status<200||u.status>=300){const e=/* @__PURE__ */new Error("Non 2xx");return e.source=u,void c(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),d({...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,c(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 Ni(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 Vr(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};#Pe=()=>{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.#Pe),this.uppy.addUploader(this.#Le),this.uppy.on("cancel-all",this.#je)}uninstall(){this.uppy.removePreProcessor(this.#Pe),this.uppy.removeUploader(this.#Le),this.uppy.off("cancel-all",this.#je)}},Bi="undefined"!=typeof window&&(window.indexedDB||window.webkitIndexedDB||window.mozIndexedDB||window.OIndexedDB||window.msIndexedDB),Hi=!!Bi,Vi="uppy-blobs",Wi="files",Gi=864e5,Xi=1048576;function Yi(e){const t=Bi.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(Wi,{keyPath:"id"}).createIndex("store","store",{unique:!1}),t.oldVersion<3){const e=i.objectStore(Wi);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()+Gi,t.update(r)}}(e)}i.oncomplete=()=>{e(r)}},t.onsuccess=t=>{e(t.target.result)},t.onerror=r})}function Ki(e){return new Promise((t,r)=>{e.onsuccess=e=>{t(e.target.result)},e.onerror=r})}var Qi=!1,Ji=class e{#$e;opts;name;static isSupported;constructor(t){this.opts={dbName:Vi,storeName:"default",expires:Gi,maxFileSize:10*Xi,maxTotalSize:300*Xi,...t},this.name=this.opts.storeName;const r=async()=>{const e=await Yi(this.opts.dbName);return this.#$e=e,e};Qi?this.#$e=r():(Qi=!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 Ki((await this.#$e).transaction([Wi],"readonly").objectStore(Wi).index("store").getAll(IDBKeyRange.only(this.name)));return Object.fromEntries(e.map(e=>[e.fileID,e.data]))}async get(e){const{data:t}=await Ki((await this.#$e).transaction([Wi],"readonly").objectStore(Wi).get(this.key(e)));return{id:t.fileID,data:t.data}}async getSize(){const e=(await this.#$e).transaction([Wi],"readonly").objectStore(Wi).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 Ki((await this.#$e).transaction([Wi],"readwrite").objectStore(Wi).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 Ki((await this.#$e).transaction([Wi],"readwrite").objectStore(Wi).delete(this.key(e)))}static async cleanup(){const e=await Yi(Vi),t=e.transaction([Wi],"readwrite").objectStore(Wi).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 Zi(e){try{return JSON.parse(e)}catch{return null}}Ji.isSupported=Hi;var en="uppyState:",tn=class{opts;name;#Be;constructor(e){var t;this.opts={expires:864e5,throttleTime:500,...e},this.name=(t=e.storeName,`${en}${t}`),this.#Be=0===this.opts.throttleTime?this.save:(0,xi.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(en)&&e.push(t)}const t=Date.now();e.forEach(e=>{const r=localStorage.getItem(e);if(!r)return;const i=Zi(r);i?.expires&&i.expires<t&&localStorage.removeItem(e)})}();const e=localStorage.getItem(this.name);if(!e)return;const t=Zi(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()}},rn="undefined"!=typeof navigator&&"serviceWorker"in navigator,nn=class{#$e;name;static isSupported;constructor(e){this.#$e=new Promise((e,t)=>{rn?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})}};nn.isSupported=rn;var on={expires:864e5,serviceWorker:!1},sn=class e extends Hr{static VERSION="5.2.1";#Ve;#We;#Ge;static[Symbol.for("uppy test: throttleTime")];constructor(t,r){super(t,{...on,...r}),this.type="debugger",this.id=this.opts.id||"GoldenRetriever",this.#Ve=new tn({expires:this.opts.expires,storeName:t.getID(),throttleTime:e[Symbol.for("uppy test: throttleTime")]??void 0}),this.opts.serviceWorker&&(this.#We=new nn({storeName:t.getID()})),this.#Ge=new Ji({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},d=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:d}),this.uppy.emit("restored",e.pluginData);const c=Object.keys(l).filter(e=>!i[e]);if(c.length)try{this.uppy.log(`[GoldenRetriever] Cleaning up ${c.length} old files`),await this.#Qe(c)}catch(u){this.uppy.log(`[GoldenRetriever] Could not clean up ${c.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)}},an=e=>408===e||429===e||e>=500,ln=(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)},dn=(e,t)=>{m(t instanceof Error?t:new Error(String(t)),{component:"useUpload",tags:["upload",e,"cleanup"]})};async function cn(e,t,r,i,n){let o="complete failed";for(let a=0;a<3;a+=1){const l=new AbortController,d=()=>l.abort(n?.reason);n?.addEventListener("abort",d,{once:!0});const c=setTimeout(()=>l.abort(),15e3);try{const n=await fetch(x.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||ln(n.status,s))return;if(o=s&&"object"==typeof s&&"string"==typeof s.error?`${s.error} (${n.status})`:`complete failed: ${n.status}`,!an(n.status))throw Object.assign(new Error(o),{retryable:!1})}catch(s){if(n?.aborted)throw s;if(o=s instanceof Error?s.message:String(s),!1===s.retryable)throw s}finally{clearTimeout(c),n?.removeEventListener("abort",d)}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 un(){const e=Ye(),t=P(),r=M(null),n=M(null),o=M(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=M(null),l=M(null),d=M({}),c=M({}),u=M(void 0),h=M({}),p=M(!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(x.UPLOAD_ABORT,{method:"POST",headers:g(),body:JSON.stringify({contentId:e,key:t})}).catch(e=>dn("abort",e))},[g]),v=R(()=>{if(!r.current){const t=new Ci({autoProceed:!0}).use(sn,{id:"GoldenRetriever",expires:864e5,serviceWorker:!1}).use($i,{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,d=r.meta.key,c=r.meta.uploadStartedAt;(async()=>{try{if(await cn(a,d,c?Date.now()-c: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:d}),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"],extra:{uid:i,contentId:a}}),void(a&&!1===u.retryable&&fetch(x.UPLOAD_FAIL,{method:"POST",headers:g(),body:JSON.stringify({contentId:a})}).catch(e=>dn("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&&y.success(`${t} file${1===t?"":"s"} uploaded`)}}})()};t.on("upload-success",o);const d=(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(x.UPLOAD_FAIL,{method:"POST",headers:g(),body:JSON.stringify({contentId:o})}).catch(e=>dn("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",d);const c=s.currentSession(),h=()=>{if(!s.isCurrentSession(c))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 d=e.data instanceof File?e.data:new File([e.data],e.name,{type:e.type});i.push({uid:l,file:d}),"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(c)&&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",d),t.off("restored",h))},r.current=t}return r.current},[e,g,s]);i(()=>{v()},[g,v]);const b=R(async(t,r)=>{const{eventId:i,groupId:n,captions:o,originalFiles:a,trimRanges:d,cropSelections:h,activeFilters:p,showFilterChoice:b,skipUploadFilters:y,perFileFilterSkipped:w,filterOverrides:S}=e.getState();let T=a[t];if(!T)return!1;const C=v();try{if(T=await B(T),!s.isCurrentSession(r))return!1;e.getState().setUploadState(t,{status:"creating",bytesUploaded:0,bytesTotal:T.size,error:void 0});const a=L(T)?"VIDEO":"IMAGE",m=await $(T);if(!s.isCurrentSession(r))return!1;const v=c.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,...ur(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},...ur(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}(T));if(!s.isCurrentSession(r))return!1;const F=d[t],k=h[t],E=p.length>0?b&&(w[t]??y):void 0,_=await fetch(x.UPLOAD_CREATE,{method:"POST",headers:g(),signal:l.current?.signal,body:JSON.stringify({eventId:i,groupId:n,uid:t,type:a,fileName:T.name,fileSize:T.size,rawContentType:m,caption:o[t],trimInfo:F?{start:F.startTime,end:F.endTime}:void 0,cropInfo:k,dimension:v.dimension,blurhash:v.blurhash,colors:v.colors,duration:v.duration,filtersSkipped:E,filterOverrides:S[t]})});if(!_.ok){let e=`create failed: ${_.status}`;try{const t=await _.json();t.error&&(e=t.error)}catch{}throw new Error(e)}const{contentId:M,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 _.json());if(!s.isCurrentSession(r))return f({contentId:M,key:U}),!1;const I=s.getAttempt(t)?.fileId;if(I&&C.getFile(I))try{C.removeFile(I)}catch{}const P=C.addFile({name:T.name,type:m,data:T,meta:{uid:t,userId:u.current,contentId:M,key:U,originalContentId:M,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:k,dimension:v.dimension,blurhash:v.blurhash,colors:v.colors,duration:v.duration,filtersSkipped:E,filterOverrides:S[t],completionPending:!1,caption:o[t],uploadStartedAt:Date.now()}});return s.registerFile(t,{uid:t,session:r,fileId:P,contentId:M,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]),w=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})=>b(e,o)),s.isCurrentSession(o)?0===a.getFiles().length?(y.error("Could not start upload. Please try again."),void e.getState().setHasStarted(!1)):void(await a.upload()):void 0},[e,v,b,f,s]),S=R(()=>{const t=s.getAttempts();s.invalidate(),l.current?.abort(),d.current={},n.current=null,s.clearFiles(),c.current={},r.current?.cancelAll(),t.forEach(f),e.getState().resetUploader()},[e,f,s]),T=R(async t=>{const r=v();n.current=null;const i=s.getAttempt(t);if(!i)return void(await b(t,s.currentSession()));const o=r.getFile(i.fileId);if(o){const n=o.meta,a=(d.current[t]??0)+1;if(d.current[t]=a,n.completionPending&&"string"==typeof n.completionContentId&&"string"==typeof n.completionKey)return void(await cn(n.completionContentId,n.completionKey,"number"==typeof n.uploadStartedAt?Date.now()-n.uploadStartedAt:void 0,g(),l.current?.signal).then(()=>{if((d.current[t]??0)===a){r.setFileMeta(i.fileId,{completionPending:!1}),e.getState().setUploadState(t,{status:"success",contentId:n.completionContentId}),s.removeFile(t);try{r.removeFile(i.fileId)}catch{}}}).catch(r=>{(d.current[t]??0)===a&&e.getState().setUploadState(t,{status:"error",error:r instanceof Error?r.message:String(r)})}));try{r.removeFile(i.fileId)}catch{}}s.removeFile(t),f(i),d.current[t]=(d.current[t]??0)+1,await b(t,s.currentSession())},[v,b,f,g,s,e]),C=R(()=>{Object.entries(e.getState().uploadStates).filter(([,e])=>"error"===e.status).map(([e])=>e).forEach(e=>T(e))},[e,T]);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:w,cancelUpload:S,retryUpload:T,retryAllUploads:C,resumeRestoredUpload:R(()=>{const{restoredUids:t}=e.getState();l.current=new AbortController,e.setState({showRestoreDialog:!1,restoredUids:[]}),Promise.all(t.map(e=>T(e))).then(()=>v().upload())},[e,T]),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 hn({eventSlug:e,event:t}){const r=P(),n=U(),a=r.props?.organizationId,l=r.user,h=Ye(),p=Xe(e=>e.selectedFiles),v=Xe(e=>e.hasStarted),b=Xe(e=>e.oversizedUids),w=Xe(e=>e.showOversizedModal),S=Xe(e=>e.activeFilters),C=Xe(e=>e.showFilterChoice),F=Xe(e=>e.skipUploadFilters),k=Xe(e=>e.showRestoreDialog),E=Xe(e=>e.restoredUids),[_,N]=I(!1),[O,A]=I(!1),[D,z]=I({}),[j,$]=I(!0);i(()=>{if(!l||!a)return;let t=!1;return $(!0),f.get(x.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||y.error("Failed to fetch upload count")}).finally(()=>{t||$(!1)}),()=>{t=!0}},[l,a,e]);const B=!t.uploadLimit||t.uploadLimit<=0,V=(D[c.APPROVED]??0)+(D[c.IN_REVIEW]??0),W=B?1/0:Math.max(0,(t.uploadLimit??0)-V),G=j,X=B?"Unlimited":W,Y=Math.min(W,100),K=!(t.status===u.OPEN)||v||G,Q=t.enableVideo?[...se,...ae]:se,Z=!!t.ada,ee=!!t.enableCaption||Z,te=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,d=new Set(l.map(({file:e})=>a(e))),c=i.filter(e=>{const t=a(e);return!d.has(t)&&(d.add(t),!0)}).map(e=>({uid:ne(),file:e})),u=Math.max(0,e-l.length),h=c.slice(0,u),p=c.length-h.length;p>0&&(y.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:Y,eventSlug:e}),{startUpload:re,cancelUpload:ie,retryUpload:ce,retryAllUploads:he,resumeRestoredUpload:pe,discardRestoredUpload:ge}=un(),fe=R(()=>{A(!1),v?ie():h.getState().resetUploader()},[v,ie,h]);!function(e){const t=Ye(),r=P(),n=r.props?.organizationId,o=r.user?.token;i(()=>{if(!e||!n)return;let r=!1;return f.get(x.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 ve=Object.values(Xe(e=>e.uploadStates)).some(e=>"queued"===e.status||"creating"===e.status||"uploading"===e.status);i(()=>{if(!v||!ve)return;const e=e=>{e.preventDefault()};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[v,ve]);const be=R(e=>h.getState().removeFile(e),[h]),ye=R(()=>{if(!Z)return!0;const e=h.getState(),t=e.selectedFiles.some(({uid:t})=>!e.oversizedUids[t]&&!e.captions[t]?.trim());return t&&y.warn("This event requires a caption on every file before uploading."),!t},[Z,h]),we=R(()=>{ye()&&(Object.keys(h.getState().oversizedUids).length>0?h.getState().setShowOversizedModal(!0):re())},[h,re,ye]),xe=R(()=>{!l||l.tcAccepted?we():N(!0)},[l,we]),Se=R(()=>{h.getState().removeOversizedFiles(),ye()&&re()},[h,re,ye]),[Te,Ce]=I(!1),Fe=M(0),ke=K||p.length>=Y;/* @__PURE__ */
76
+ return T("div",{className:"bg-background relative min-h-screen px-3 pb-9 lg:px-0",onDragEnter:e=>{e.preventDefault(),ke||(Fe.current+=1,Ce(!0))},onDragOver:e=>e.preventDefault(),onDragLeave:()=>{Fe.current=Math.max(0,Fe.current-1),0===Fe.current&&Ce(!1)},onDrop:R(e=>{if(e.preventDefault(),Fe.current=0,Ce(!1),ke)return;const t=e.dataTransfer?.files;t&&t.length>0&&te(Array.from(t))},[ke,te]),children:[Te&&/* @__PURE__ */T("div",{className:"border-primary bg-background/90 fixed inset-0 z-2003 flex items-center justify-center border-4 border-dashed",children:/* @__PURE__ */T("p",{className:"text-primary text-2xl font-semibold",children:"Drop to add files"})}),
77
+ /* @__PURE__ */T("div",{className:"mx-auto max-w-4xl space-y-6",children:[
78
+ /* @__PURE__ */T(Mt,{uploadDisabled:K,eventName:t.name,isQuotaLoading:G,remainingUploads:X}),!t.enableVideo&&/* @__PURE__ */T("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__ */T(kt,{enabledFileTypes:Q,disabled:K,onFileSelect:te,selectedCount:p.length,maxCount:Y,enableVideo:t.enableVideo})]}),p.length>0&&/* @__PURE__ */T("div",{className:"mx-auto mt-8 w-full max-w-full pb-36 sm:px-0 md:pb-24",children:[C&&S.length>0&&!v&&/* @__PURE__ */T("div",{className:"border-border bg-card mb-4 flex items-center gap-3 rounded-lg border p-3",children:[/* @__PURE__ */T(oe,{checked:!F,onChange:e=>{h.getState().setSkipUploadFilters(!e);const t={};e||p.forEach(({uid:e})=>{t[e]=!0}),h.setState({perFileFilterSkipped:t})},label:"Apply filters"}),/* @__PURE__ */T("span",{className:"text-muted-foreground -ml-1 text-sm",children:"— upload with filters applied"})]}),
79
+ /* @__PURE__ */T("div",{className:"flex items-center justify-between py-2",children:[/* @__PURE__ */T("p",{className:"text-muted-foreground text-sm font-medium",children:[p.length," selected"]}),!v&&p.length<Y&&/* @__PURE__ */T(_t,{enabledFileTypes:Q,disabled:K,onFileSelect:te})]}),
80
+ /* @__PURE__ */T("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__ */T(St,{uid:e,file:t,onRemove:be,disabled:v,adaRequired:Z,showCaption:ee,onRetry:ce},e))}),!v&&p.length<Y&&/* @__PURE__ */T(Et,{enabledFileTypes:Q,disabled:K,onFileSelect:te}),!v&&/* @__PURE__ */T(q,{className:"mt-2 w-full gap-2",onClick:xe,disabled:K||0===p.length,children:[/* @__PURE__ */T(H,{className:"size-4"}),"Upload"]}),
81
+ /* @__PURE__ */T(Ct,{selectedCount:p.length,onUpload:xe,onCancel:()=>A(!0),onRetryAll:he,uploadDisabled:K||0===p.length})]}),!v&&/* @__PURE__ */T("div",{className:"mx-auto mt-12 max-w-4xl text-center",children:/* @__PURE__ */T(q,{onClick:()=>n(d.GALLERY(e)),children:"View gallery"})}),
82
+ /* @__PURE__ */T(le,{open:w,oversizedUids:b,onClose:()=>h.getState().setShowOversizedModal(!1),onRemoveAndUpload:Se}),
83
+ /* @__PURE__ */T(de,{open:k,count:E.length,onResume:pe,onDiscard:ge}),
84
+ /* @__PURE__ */T(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:fe}),
85
+ /* @__PURE__ */T(ue,{open:_,onClose:()=>N(!1),onSuccess:()=>{N(!1),we()}})]})}var pn=()=>{const{eventSlug:e}=O(),t=v(),r=U(),{loadingUser:n,user:o}=P();i(()=>{n||o||r("/auth/login",{state:{referrer:t.pathname},replace:!0})},[n,o]);const{loading:s,event:a}=_({eventSlug:e}),l=M(ne());return s||a&&a.status!==u.CLOSED?/* @__PURE__ */T("div",a&&e?{className:"bg-background mx-auto min-h-screen pt-16",children:/* @__PURE__ */T(Ge,{eventId:String(a._id),groupId:l.current,children:/* @__PURE__ */T(hn,{eventSlug:e,event:a})})}:{className:"bg-background min-h-screen"}):/* @__PURE__ */T("div",{className:"bg-background mx-auto min-h-[80] pt-16 pb-36",children:/* @__PURE__ */T(he,{eventSlug:e,locationState:t?.state})})};export{pn as default};