PageSourceSearch

https://vrew.ai/try/assets/scene-B7kE8RMp.js

js vrew.ai collected 2026-10-02 05:04:01 UTC 2,386,568 bytes, 4,263 lines download raw bytes

1const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/waveformSource-Do6U9AL6.js","assets/styles-BqRY-fqL.js","assets/vendor-McMLrVo2.js","assets/vendor-Dj3b7yF9.css","assets/json/_name_-D5nKX5TO.js","assets/styles-DNma5Vng.css"])))=>i.map(i=>d[i]);
2import{x as z,cR as je,aX as X,i as DS,A as ze,v as he,o as Ve,U as Ie,p as ce,ad as fn,aa as ee,t as A,ar as Mr,cM as Ps,a8 as xe,an as M0,a9 as Nt,b1 as al,ga as wX,gb as NX,b7 as aU,g2 as s0,bL as Na,al as Xe,g as h,C as _,dv as fi,gc as PX,gd as $C,B as C,d1 as Wt,ge as bX,M as P,g1 as Ib,c0 as jr,gf as bx,gg as iU,fK as du,bX as Ci,aE as sg,a5 as LX,bn as Ht,cK as MX,gh as vu,n as ae,ak as os,cL as QA,b as Ha,a as Ba,a0 as Fe,cN as DX,gi as sU,a1 as Tc,d_ as kX,c2 as FX,ej as Ea,eg as UX,r as VX,Z as GX,e as Vr,bZ as Ne,gj as xg,K as m,a6 as g,gk as WX,gl as HX,F as It,aY as zi,b5 as Fc,ac as xU,aq as ZA,gm as cU,gn as lU,aT as dU,aU as $A,bp as uU,ab as ey,aQ as jX,ao as Ux,go as zX,aP as YX,at as BX,au as KX,bK as Tb,cq as pU,I as $t,bh as Ut,by as Oe,bc as Tr,eO as _o,ae as D,co as yo,gp as td,gq as ZE,ax as tt,aw as Fs,bY as de,gr as Sb,bo as So,gs as wu,cT as ti,q as Oo,gt as pf,aA as ye,bj as tn,aF as gt,bb as Ho,dB as $E,gu as XX,G as ue,eM as Gl,gv as fU,eN as vh,bg as Go,cS as gU,bx as ft,W as Z,O as gx,fX as eR,ah as Vx,fM as Ob,bk as Ee,H as tr,ey as Gx,ez as em,gw as _U,be as JX,bf as tR,bd as EU,E as ra,z as wi,Q as x0,m as Ge,y as on,$ as pn,bv as D0,gx as qa,ai as J,gy as Ye,fm as od,b6 as Ni,gz as Ce,a$ as qX,aZ as Wx,b0 as QX,gA as mU,aJ as _e,gB as ZX,bl as co,gC as kS,gD as $X,dh as b0,gE as ty,w as ma,a_ as wh,cW as Gt,gF as Ji,gG as Nh,cg as Wl,gH as cg,S as k0,gI as hU,N as Cb,gJ as oy,gK as ry,gL as ny,gM as _x,gN as FS,gO as e6,g3 as rs,gP as uu,du as Jx,gQ as IU,gR as TU,ft as Uc,gS as lg,gT as Rb,gU as t6,gV as o6,fu as Ph,gW as Ab,bm as Nu,gX as kd,gY as r6,gZ as n6,g_ as ff,g$ as a6,h0 as tm,h1 as i6,h2 as yb,h3 as s6,h4 as x6,h5 as c6,h6 as l6,h7 as d6,h8 as om,h9 as u6,dg as gi,dY as Ed,ha as bh,hb as p6,hc as SU,hd as OU,e5 as Yt,d6 as ay,eG as dg,he as f6,fy as nr,hf as CU,hg as g6,cc as Fo,hh as gf,fN as k_,cd as _6,D as _f,J as so,hi as E6,hj as m6,f9 as US,fb as VS,ba as mi,fq as _i,bN as Fd,bO as gs,aC as Lh,eF as h6,hk as I6,hl as vb,az as no,dd as wb,hm as ug,k as il,hn as T6,ho as S6,aK as ws,b$ as RU,aH as Pu,hp as O6,hq as AU,hr as Nb,hs as C6,ht as yU,dG as ro,hu as Hx,av as Dn,h as iy,j as sy,cf as gn,hv as R6,P as kn,hw as Sc,hx as rd,hy as pu,hz as $d,hA as Ef,hB as A6,d7 as bs,hC as y6,hD as v6,da as oR,dp as GS,hE as WS,hF as w6,a2 as _n,a3 as Bo,a4 as Ko,hG as vU,b9 as N6,hH as wU,hI as Hl,hJ as Pb,hK as bb,g0 as mf,hL as HS,hM as P6,c7 as Yi,hN as NU,hO as PU,hP as b6,cx as rR,hQ as L6,hR as rr,hS as M6,hT as D6,hU as 
2nR,hV as Mh,ch as k6,dc as F6,hW as Dh,hX as U6,ds as F_,hY as V6,hZ as G6,h_ as hf,bu as Ct,fn as et,c1 as Fr,h$ as W6,i0 as H6,i1 as j6,i2 as z6,i3 as Y6,i4 as B6,T as ot,i5 as K6,i6 as Lb,i7 as vE,i8 as X6,i9 as J6,b_ as Ls,ia as q6,bM as bU,dy as Mb,dw as Db,df as LU,c as Q6,ib as rm,ic as MU,id as DU,ie as kU,ig as kh,ih as Z6,ii as $6,ij as e9,ik as t9,il as o9,im as r9,c6 as kb,eZ as aR,a7 as en,aG as If,aM as FU,aN as UU,dq as nm,aB as Fh,cn as xy,ay as Kr,aI as eu,io as Si,cQ as es,cj as Fb,ip as jS,iq as Vc,ir as Uh,is as tu,it as am,am as Po,bi as io,f1 as Is,iu as U_,iv as n9,iw as a9,ix as $o,iy as Js,iz as VU,iA as xo,iB as Qn,iC as Ze,b4 as wE,iD as NE,fp as Ub,iE as im,iF as sm,eq as iR,ep as Gc,eP as i9,iG as s9,iH as GU,eQ as xm,eR as WU,Y as cm,iI as nd,fF as o0,cX as x9,V as Zt,iJ as c9,iK as HU,fP as lm,iL as cy,iM as e2,iN as ly,fW as jU,fU as zU,iO as l9,f as Wo,fE as Dl,iP as zS,aL as d9,iQ as YS,fe as u9,fJ as Oc}from"./styles-BqRY-fqL.js";import{$ as Eo,aI as na,as as Cn,cV as BS,m as b,r as it,l as rn,cq as Es,R as jt,cW as p9,cX as V_,S as Xr,b as at,v as fr,cY as dy,by as ad,cZ as Vb,c_ as f9,c$ as Sr,aw as YU,bV as g9,d0 as _9,bS as E9,d1 as m9,ax as h9,ay as I9,bU as T9,az as S9,d2 as O9,d3 as C9,d4 as R9,c as In,bA as A9,cG as sR,p as vt,d5 as X0,a4 as y9,aG as An,d6 as jx,g as qe,a5 as Vh,d7 as PE,d8 as v9,d9 as BU,aM as Ma,aO as zt,aN as At,aR as aa,af as Fn,an as Qt,am as t2,da as KU,db as xR,dc as XU,bz as jn,dd as w9,bG as Gr,aP as dm,aQ as Bt,de as o2,df as N9,aK as Tt,aL as er,ba as jl,h as bc,aU as St,cD as JU,dg as qU,dh as P9,di as QU,av as Qr,aT as c0,dj as Tf,dk as Fa,dl as ZU,q as un,dm as b9,dn as sl,aH as r2,ae as Wc,W as zr,cj as Lx,dp as KS,dq as L9,be as n2,aW as a2,dr as $U,bl as ta,b9 as md,bd as um,aZ as id,ds as M9,dt as D9,du as e1,dv as k9,s as F9,dw as U9,dx as Gb,dy as V9,dz as Wb,dA as G9,dB as W9,dC as cR,aX as uy,bc as wl,dD as H9,dE as Hb,dF as j9,dG as XS,dH as jb,dI as zb,dJ as z9,dK as Y9,dL as B9,dM as Hc,bg as K9,bC as X9,dN as t1,at as o1,dO as J9,au as q9,cs as Q9,a2 as Z9,dP as r1,aY as n1,dQ as JS,dR as Yb,aV as a1,bN as Bb,cF as i1,dS as s1,aS as x1,dT as hd,dU as sd,dV as xl,dW as cl,dX as $9,dY as jp,dZ as py,d_ as lR,d$ as mx,e0 as dR,e1 as eJ,e2 as c1,e3 as tJ,e4 as oJ,e5 as rJ,e6 as fu,e7 as G_,e8 as nJ,bx as aJ,e9 as iJ,ea as sJ,a$ as xJ,b4 as uR,eb as cJ,ec as Kb,ed as lJ,ar as dJ,ee as De,e as qx,ef as uJ,X as Xb,eg as Jb,eh as Cc,ei as pJ,ej as fy,bP as Gh,ek as fJ,bB as pm,b6 as gJ,a_ as _J,el as EJ,b7 as mJ,bv as hJ,em as qb}from"./vendor-McMLrVo2.js";import{r as IJ,b as TJ,R as Qb,c as SJ,V as OJ,e as pR,h as CJ}from"./json/_name_-D5nKX5TO.js";var l1=(e=>(e[e.IMAGE=z.IMAGE]="IMAGE",e[e.VIDEO=z.VIDEO]="VIDEO",e))(l1||{}),RJ=(e=>(e.CLICK_CONTEXT_MENU="click_context_menu",e.PREVIEW="preview",e))(RJ||{}),AJ=(e=>(e.UNMOUNT="unmount",e.CLICK_OUTSIDE="click_outside",e))(AJ||{});const pg=e=>{if(e===void 0)return{top:0,right:0,bottom:0,left:0};const t=/inset\(([^)]+)\)/,o=e.match(t);if(o&&o[1]){const r=o[1].split(/%\s+/).map(n=>parseFloat(n));return{top:r[0]/100,right:r[1]/100,bottom:r[2]/100,left:r[3]/100}}return{top:0,right:0,bottom:0,left:0}},fR=e=>{const{top:t,right:o,bottom:r,left:n}=pg(e);return t!==0||o!==0||r!==0||n!==0},iJe=(e,t,o)=>{if(!e||!t&&!o)return e;const r=pg(e),n=o?r.bottom:r.top,a=t?r.left:r.right,i=o?r.top:r.bottom,s=t?r.right:r.left;return"inset("+n*100+"% "+a*100+"% "+i*100+"% "+s*100+"%)"},d1=(e,t,o)=>{const r=Math.cos(o),n=Math.sin(o),a=r*e-n*t,i=n*e+r*t;return{rx:a,ry:i}},Zb=(e,t,o)=>{const{x:r,y:n}={x:e/2,y:t/2},{rx:a,ry:i}=d1(r,n,o),s=a-r,x=i-n;return{xOffset:s,yOffset:x}},sJe=(e,t,o,r,n=0,a=1,i=1)=>{const s=n/360*2*Math.PI,{rx:x,ry:c}=d1(r,e,s),{w:l,h:d}={w:a,h:i},{cw:u,ch:p}={cw:a-r-t,ch:i-e-o},{xOffset:f,yOffset:E}=Zb(l,d,s),{xOffset:T,yOffset:O}=Zb(u,p,s);return{xOffset:x-f+T,yOffset:c-E+O}},xJe=(e,t,o)=>({clipPath:"inset(0px 0px 0px 0px)",objectPosition:-e.left*t/(1-e.left-e.right)+`px
3                 `+-e.top*o/(1-e.top-e.bottom)+"px"}),cJe=e=>({width:100/(1-e.left-e.right)+"%",height:100/(1-e.top-e.bottom)+"%"}),yJ=e=>Eo(l1).isValue(e.type),lJe=e=>({trackId:e.trackId,assetId:e.assetId,assetType:e.assetType,expandedPosition:{x:e.x,y:e.y,zIndex:e.zIndex},expandedSize:{width:e.width,height:e.height},enterReason:e.enterReason}),$b=5,dJe="$vrew",uJe="$vrew-image-modal",pJe="N1RBGBKuZBWP5wwIkX4ZGyvu2DratVEi",vJ="google.com",wJ="https://vrew.channel.io/support-bots",NJ=4,xd="#ffffff",u1="#000000",Ri="#00000000",p1=!0;class PJ{_buffer=[];_size;constructor(t){this._size=t}push(t){this._buffer.push(t),this._buffer.length>this._size&&this._buffer.shift()}pop(){return this._buffer.shift()}getAll(){return this._buffer}clear(){this._buffer.length=0}get length(){return this._buffer.length}get size(){return this._size}}const Ae=(e=je.UNKNOWN_ERR,t,o,r)=>{const n=bE(t)?t.type:LJ(t)?je.NETWORK_FAILED_ERR:e,a=f1(t)||bE(t)?t.message:"",i=a?a+`
4    `+(o??"")+": "+qr(t):(o??"")+": "+qr(t),s=bE(t)&&t.errorArgs!==void 0?t.errorArgs:r;return{__internal:"MediaProcessingError",type:n,message:i,errorArgs:s}},bE=e=>typeof e=="object"&&e!==null&&"__internal"in e,f1=e=>e instanceof Error,bJ=e=>e instanceof DOMException,LJ=e=>f1(e)&&e.name==="TypeError"&&e.message==="Network request failed",MJ=e=>{if(bJ(e))return"DOMException "+e.name+"("+e.code+"): "+e.message;const t=Object.getOwnPropertyNames(e);try{return JSON.stringify(e,t)}catch(o){return"{"+t.map(n=>n+": "+e[n]).join(", ")+"} (stringify failed: "+o+")"}},qr=e=>{switch(typeof e){case"string":return e;case"undefined":return"undefined";case"function":return"function "+e.name;case"number":case"bigint":case"symbol":case"boolean":return e.toString();case"object":return e!==null?MJ(e):"null"}},fJe=e=>bE(e)&&(e.type===je.DISK_WRITE_ERR||e.type===je.DISK_NO_SPACE),Ud=e=>e!==null?"@"+e+" |":"|",DJ=(e,t,o,r,n)=>{const a=i=>i instanceof X?i.as.ms("round"):i;return{info:(i,...s)=>e.info(Ud(a(i)),...s),warn:(i,...s)=>e.warn(Ud(a(i)),...s),error:(i,...s)=>
4e.error(Ud(a(i)),...s),verbose:(i,...s)=>{if(!o()){const x="["+na.local().toFormat("yyyy-MM-dd'T'HH:mm:ss:SSSZZ")+"]";n.push(x+" "+t+" "+Ud(a(i))+" "+s.map(String).join(" "));return}e.info(Ud(a(i)),...s)},debug:(i,...s)=>{if(!r())return;const x="["+na.local().toFormat("yyyy-MM-dd'T'HH:mm:ss:SSSZZ")+"]";console.log(x+" "+t+" "+Ud(a(i)),...s)}}},g1="vrew.core.flags",kJ=()=>{try{if(typeof sessionStorage>"u")return{};const e=sessionStorage.getItem(g1);if(!e)return{};const t=JSON.parse(e);return typeof t!="object"||t===null||Array.isArray(t)?{}:t}catch{return{}}},FJ=e=>{try{if(typeof sessionStorage>"u")return;sessionStorage.setItem(g1,JSON.stringify(e))}catch{}},gJe=e=>{const t=new PJ(100),o=kJ(),r={...e.flags,...o};fa={getLogger:a=>{if(!fa)throw Ae(je.LOGIC_ERR,"CoreGlobal is null while getting logger");const i=e.loggerFactory(a);return DJ(i,a,()=>fa?.flags.isVerbose??!1,()=>fa?.flags.isDev??!1,t)},getLogs:()=>{if(fa===null)throw Ae(je.LOGIC_ERR,"CoreGlobal is null while getting logs");return`==CORE_LOG_START==
5`+t.getAll().join(`
6`)+`
7==CORE_LOG_END==`},clearLogs:()=>{if(fa===null)throw Ae(je.LOGIC_ERR,"CoreGlobal is null while clearing logs");t.clear()},flags:r}},_Je=e=>{if(!fa)throw Ae(je.LOGIC_ERR,"CoreGlobal is null while setting flags");Object.assign(fa.flags,e),FJ(fa.flags)},Qa=e=>{if(fa===null)throw Ae(je.LOGIC_ERR,"CoreGlobal is null while getting flag "+e);return fa.flags[e]??!1};let fa=null;const nn=e=>{if(fa===null)throw Ae(je.LOGIC_ERR,"CoreGlobal is null while getting logger");return fa.getLogger(e)},EJe=()=>{if(fa===null)throw Ae(je.LOGIC_ERR,"CoreGlobal is null while getting logs");return fa.getLogs()},mJe=()=>{if(fa===null)throw Ae(je.LOGIC_ERR,"CoreGlobal is null while clearing logs");fa.clearLogs()},UJ=(e,t,o,r=!1)=>{let n=0,a=e.length-1,i=0;if(e.length!==0){for(;n<=a;)i=Math.floor((n+a)/2),o(e[i],t)<=0?a=i-1:n=i+1;return n<e.length&&o(e[n],t)===0||r?n:void 0}},VJ=(e,t)=>Math.round(e*Math.pow(10,t))/Math.pow(10,t),Rc=(e,t)=>{const o=e.as.us("raw")+.5,r=o*t/1e6;return Math.floor(r)},_1=(e,t)=>{if(t<=0||e<0)return X.zero();const o=Math.round(e*1e6/t);return X.fromUS(o)},qS=(e,t)=>Math.round(e.as.sec()*t),QS=(e,t)=>_1(Rc(e,t)+1,t),E1=(e,t,o,r)=>e.lt(r)&&o.lt(t),hJe=(e,t=!1,o=!1)=>{const r=Math.max(0,e),n=Math.floor(r/3600),a=Math.floor(r%3600/60),i=Math.floor(r%60),s=c=>c.toString().padStart(2,"0");let x;if(t&&n===0?x=s(a)+":"+s(i):x=s(n)+":"+s(a)+":"+s(i),o){const c=Math.floor(r%1*100);x+="."+c.toString().padStart(2,"0")}return x};let GJ=class{_fps;_slices=[];_currentSliceIndex=-1;_currentSliceOffset=X.zero();constructor(t){this._fps=t}set fps(t){this._fps=t}get currentSliceIndex(){return this._currentSliceIndex}get timeslices(){return this._slices}get ended(){const t=this._currentSlice;return!t||this._currentSliceIndex<this._slices.length-1?!1:QS(this._currentSliceOffset,this._fps).gte(t.durationInVideo)}seek(t){if(this._slices.length===0){this._currentSliceIndex=-1,this._currentSliceOffset=X.zero();return}const o=this._slices.findIndex(n=>{const a=n.startInVideo.add(n.durationInVideo);return n.startInVideo.lte(t)&&t.lt(a)});if(o!==-1){this._currentSliceIndex=o,this._currentSliceOffset=t.sub(this._slices[o].startInVideo);return}const r=this._slices.findIndex(n=>n.startInVideo.gt(t));r===0?(this._currentSliceIndex=0,this._currentSliceOffset=X.zero()):r>0?(this._currentSliceIndex=r-1,this._currentSliceOffset=this._slices[this._currentSliceIndex].durationInVideo):(this._currentSliceIndex=this._slices.length-1,this._currentSliceOffset=this._slices[this._currentSliceIndex].durationInVideo)}init(t,o){this.clear(),this._slices.push(...gy(t)),o&&this.seek(o)}get duration(){const t=this._slices.at(-1);return t?t.startInVideo.add(t.durationInVideo):X.zero()}get currentTime(){const t=this._currentSlice;return t?t.startInVideo.add(this._currentSliceOffset):null}get _currentSlice(){return this._slices[this._currentSliceIndex]??null}clear(){this._slices.length=0,this._currentSliceIndex=-1,this._currentSliceOffset=X.zero()}current(){const t=this._currentSlice;if(!t)return null;const o=Rc(this._currentSliceOffset,this._fps);if(o<0)return null;const r=_1(o,this._fps);if(r.gte(t.durationInVideo))return null;const n=t.startInProject.add(r),a=t.startInVideo.add(r),i=this._getDuration(t,n);return[n,a,i]}next(){const t=this._currentSlice,o=QS(this._currentSliceOffset,this._fps);if(t&&o.lt(t.durationInVideo)){this._currentSliceOffset=o;const r=t.startInProject.add(this._currentSliceOffset),n=t.startInVideo.add(this._currentSliceOffset),a=this._getDuration(t,r);return[r,n,a]}else if(this._currentSliceIndex<this._slices.length-1){this._currentSliceIndex++,this._currentSliceOffset=X.zero();const r=this._slices[this._currentSliceIndex],n=r.startInProject.add(this._currentSliceOffset),a=r.startInVideo.add(this._currentSliceOffset),i=this._getDuration(r,n);return[n,a,i]}else return null}_getDuration(t,o){const r=QS(this._currentSliceOffset,this._fps),n=t.startInProject.add(r),a=n.sub(o),i=t.durationInVideo.sub(this._currentSliceOffset);return X.min(a,i)}};const gy=e=>e.reduce((t,o)=>{if(o.durationInProject===0)return t;const r=t.at(-1);return t.push({startInProject:X.fromMS(o.startInProject),durationInProject:X.fromMS(o.durationInProject),startInVideo:r?r.startInVideo.add(r.durationInVideo):X.zero(),durationInVideo:X.fromMS(o.durationInProject)}),t},[]),m1=(e,t)=>{if(e===t)return!0;
7if(e.length!==t.length)return!1;for(let o=0;o<e.length;o++)if(e[o].startInProject!==t[o].startInProject||e[o].durationInProject!==t[o].durationInProject)return!1;return!0},WJ=(e,t)=>{if(e.length===0)return X.zero();const o=UJ(e,t,(i,s)=>i.startInProject.gt(s)?-1:1,!0),r=(o??e.length)-1;if(r<0)return X.zero();const n=e[r],a=X.max(X.zero(),X.min(t.sub(n.startInProject),n.durationInProject));return n.startInVideo.add(a)},gR=e=>e!=null,_y=e=>!!e,h1=()=>Cn(10),I1=async e=>new Promise((t,o)=>{const r=new FileReader;r.onloadend=()=>{const n=r.result;if(typeof n!="string"){const a=n===null?"null":"ArrayBuffer",i="type mismatch in toBase64: read as "+a+", blob type "+e.type+", blob size "+e.size+", state: "+r.readyState;o(Error(i))}else t(n)},r.readAsDataURL(e)}),js=(e,t,o)=>Math.max(t,Math.min(e,o)),gu=e=>new Promise(t=>setTimeout(t,e)),Ey=(e,t,o)=>{const r=setTimeout(()=>o(),t);return e.then(()=>clearTimeout(r),()=>clearTimeout(r)),e},HJ=(e,t)=>{let o;return new Promise((r,n)=>{o=setTimeout(()=>n(new Error("Timeout")),t),e.then(r,n).finally(()=>clearTimeout(o))})},T1=async(e,t,o,r)=>{let n;for(let a=0;a<=t;a++)try{if(a>0&&n)try{r?.(n,a),await gu(o(a))}catch{}return await e()}catch(i){n=i}throw n},jJ=(e,t)=>{const o=new OffscreenCanvas(e,t);o.width=e,o.height=t;const r=o.getContext("2d");if(!r)throw Ae(je.LOGIC_ERR,"cannot get bitmaprenderer context in htmlVideoRenderer");return{canvas:o,context:r}},zJ=async(e,t)=>{const{canvas:o,context:r}=jJ(e.width,e.height);return t?.type==="image/jpeg"&&(r.fillStyle="black",r.fillRect(0,0,o.width,o.height)),r.drawImage(e,0,0),o.convertToBlob(t)},S1=["SecurityError","NotSupportedError","InvalidStateError","DataCloneError"];async function Lc(e,t,o,r,n,a){let x=0;for(;x<4;)try{return await createImageBitmap(e,t)}catch(c){if(c instanceof DOMException&&S1.includes(c.name))throw Ae(je.BITMAP_CREATION_ERR,c);if(x++,x===4)throw Ae(je.BITMAP_CREATION_ERR,"createImageBitmap failed",qr(c));const l=Math.floor(Math.random()*10),d=10*(1<<x-1)+l;await gu(d)}throw Ae(je.LOGIC_ERR,"createImageBitmap failed after max attempts")}const O1=async e=>{let r=0;for(;r<4;)try{return e.transferToImageBitmap()}catch(n){if(n instanceof DOMException&&S1.includes(n.name))throw Ae(je.BITMAP_CREATION_ERR,n);r++;const a=Math.floor(Math.random()*10),i=10*(1<<r-1)+a;await gu(i)}throw Ae(je.BITMAP_CREATION_ERR,"Error in transferToImageBitmap")},TJe=e=>e instanceof VideoFrame?e.displayWidth:e.width,SJe=e=>e instanceof VideoFrame?e.displayHeight:e.height,$s=e=>{try{e instanceof VideoFrame&&e.close(),e instanceof ImageBitmap&&e.close()}catch{}},my=async e=>{if(e instanceof ImageBitmap)return e;if(e instanceof VideoFrame){const t=await Lc(e);return e.close(),t}return O1(e)},YJ=/url\(\s*(['"]?)data:image\/svg\+xml;\s*(?:utf8|charset\s*=\s*utf-8)\s*,([\s\S]*?)\1\s*\)/gi,eL=(e,t)=>{if(t.tagName==="style"){const o=e.textContent||"",r=o.replace(YJ,(n,a,i)=>{if(!i.includes("<svg"))return n;try{const s=i.trim(),x=decodeURIComponent(s),c=x.replace(/\\\r?\n/g,"").replace(/\r?\n/g,""),l=new TextEncoder,d=l.encode(c);let u="";for(let f=0;f<d.length;f+=32768)u+=String.fromCharCode(...d.subarray(f,f+32768));return'url("data:image/svg+xml;base64,'+btoa(u)+'")'}catch{return n}});e.textContent=r}},BJ=["perspectiveAspectRatio"],KJ=["iframe","frame","frameset","object","embed","applet","script","link","a","meta","base","form","input","button","textarea","select","option","video","audio","source","track","img","picture"],XJ=["src","srcset","poster","href","xlink:href","action","formaction","data","target","download"],C1=e=>{BS.addHook("uponSanitizeElement",eL);try{return BS.sanitize(e,{USE_PROFILES:{html:!0,svg:!0,svgFilters:!0},FORCE_BODY:!0,SANITIZE_DOM:!1,ADD_ATTR:BJ,FORBID_TAGS:KJ,FORBID_ATTR:XJ})}finally{BS.removeHook("uponSanitizeElement",eL)}},JJ=e=>e,OJe=e=>e,CJe=e=>e,qJ="/try/assets/vrewAgent-BZNJStpt.svg",QJ="/try/assets/auto-image-video-insert-CgJ750he.svg",ZJ="/try/assets/ic_about-B4PehjXr.svg",$J="/try/assets/ic_add_ai_stylized_caption-B_QZlq-2.svg",eq="/try/assets/ic_add_designed_textbox-CvX_E61N.svg",tq="/try/assets/ic_add_textbox-qy0Su1Jr.svg",oq="/try/assets/ic_announcement-yDvgQ-L
7h.svg",rq="/try/assets/ic_auto_split_scenes-Chn6fAhH.svg",nq="/try/assets/ic_bold_toggle-BpYSAOmc.svg",aq="/try/assets/ic_browser-DMg5S1wL.svg",iq="/try/assets/ic_caption_size-D_zEY717.svg",sq="/try/assets/ic_character-CIzKIOtK.svg",xq="/try/assets/ic_client_linebreak-VxA21CwJ.svg",cq="/try/assets/ic_cloud-BdloXXQj.svg",lq="/try/assets/ic_copy-CXCR5uKY.svg",dq="/try/assets/ic_copy_caption-B2sISC_K.svg",uq="/try/assets/ic_copy_translated_caption-DcNQFR-F.svg",pq="/try/assets/ic_create_frame_pack-bJOS6OJE.svg",fq="/try/assets/ic_current_file_info-DkjVzILo.svg",gq="/try/assets/ic_cut-DrZWv-UC.svg",_q="/try/assets/ic_delete_blanks-WqOR5CBz.svg",Eq="/try/assets/ic_diagnostic-CVWN89je.svg",mq="/try/assets/ic_discord-xzHe-Gjv.svg",hq="/try/assets/ic_divide_clip-HA8ae1Qo.svg",R1="/try/assets/ic_effect_filter-pH5-NUrv.svg",Iq="/try/assets/ic_experiment_flask-DOUWnJ_Q.svg",Tq="/try/assets/ic_export-D73OnKjz.svg",Sq="/try/assets/ic_export_video-CKYYBEox.svg",Oq="/try/assets/ic_feedback-DEGmVX-R.svg",Cq="/try/assets/ic_format_copy-Cq0oBzcY.svg",Rq="/try/assets/ic_format_delete-BaNGneyN.svg",Aq="/try/assets/ic_free_source-9oa4_M6w.svg",tL="/try/assets/ic_generate_image-CoE8xDer.svg",oL="/try/assets/ic_generate_video-BgtVV4aK.svg",yq="/try/assets/ic_asset_menu_animation-jYWa8scj.svg",vq="/try/assets/ic_import_script-DW6ZVrSJ.svg",wq="/try/assets/ic_import_subtitle-Dhifetjv.svg",
7Nq="/try/assets/ic_import_timecode_text-CIlxoVFw.svg",Pq="/try/assets/ic_insert_blank_clip-CCb-DllA.svg",bq="/try/assets/ic_insert_freeze_word-wGclZqbi.svg",Lq="/try/assets/ic_insert_image_and_video-CdYyohgB.svg",Mq="/try/assets/ic_italic_toggle-CLOEQOYJ.svg",Dq="/try/assets/ic_local-BOdsWn7z.svg",kq="/try/assets/ic_mac-DFkXUy1V.svg",Fq="/try/assets/ic_mac_small-BarIoJr-.svg",Uq="/try/assets/ic_marker-C58alFJf.svg",Vq="/try/assets/ic_menu_find-CFdtneqU.svg",Gq="/try/assets/ic_merge_clips-OT86tygG.svg",Wq="/try/assets/ic_myvrew_tab_logo_gray-CEgzf-LA.svg",Hq="/try/assets/ic_new_window-Cz5qIX3F.svg",jq="/try/assets/ic_opacity-Ce0Jk5E4.svg",zq="/try/assets/ic_open_project-BsJUGb9d.svg",Yq="/try/assets/ic_original_view-DqF1nty8.svg",Bq="/try/assets/ic_overdub_large-DJBwm-Tz.svg",Kq="/try/assets/ic_paste-C93E9ese.svg",Xq="/try/assets/ic_pause-CzFPERVX.svg",Jq="/try/assets/ic_play-TamDgoeS.svg",qq="/try/assets/ic_playbackrate-DA6GrB5c.svg",Qq="/try/assets/ic_position-CqRMNhoy.svg",Zq="/try/assets/ic_record-iVEVQPVR.svg",$q="/try/assets/ic_redo-Cb9aKilc.svg",eQ="/try/assets/ic_remove_caption-CCT7o1o5.svg",tQ="/try/assets/ic_remove_translated_caption-C1vkYliu.svg",rL="/try/assets/ic_save-BQMJhNqA.svg",oQ="/try/assets/ic_save_a_copy-BXx7qv_i.svg",rQ="/try/assets/ic_save_cloud_check-BtZo1X_3.svg",nQ="/try/assets/ic_scene_add-DebJwYfK.svg",aQ="/try/assets/ic_select_asset-Bvt5vec1.svg",iQ="/try/assets/ic_select_background-DDqI_uXn.svg",sQ="/try/assets/ic_select_clip-DnMwRhd2.svg",xQ="/try/assets/ic_select_highlight_color-BaTcp-iq.svg",cQ="/try/assets/ic_select_spacing-feiIg7vf.svg",lQ="/try/assets/ic_select_text_color-DPRbvkU4.svg",dQ="/try/assets/ic_select_text_outline_color-D32QPYfc.svg",uQ="/try/assets/ic_select_text_shadow_color-JrN21D05.svg",pQ="/try/assets/ic_setting-Ffv3m3uP.svg",fQ="/try/assets/ic_shortcut-BpWsSnEw.svg",gQ="/try/assets/ic_simple_asset_character-CmXB-cEM.svg",_Q="/try/assets/ic_simple_asset_image-BZ_f9qG0.svg",EQ="/try/assets/ic_simple_asset_shape-DS_tno7w.svg",mQ="/try/assets/ic_simple_asset_tts_dubbing-CK13onkP.svg",hQ="/try/assets/ic_simple_asset_tts_effect-C84bvw8B.svg",IQ="/try/assets/ic_simple_asset_video-BlVPx8Mv.svg",TQ="/try/assets/ic_simple_bgm-3YtGmRas.svg",SQ="/try/assets/ic_simple_clip_web_asset_bubble-BG4WlRjm.svg",OQ="/try/assets/ic_simple_designed_text_bubble-BIgGPnro.svg",CQ="/try/assets/ic_simple_sound_effect-kvzj8_cF.svg",RQ="/try/assets/ic_startmode-CHXIFVTU.svg",AQ="/try/assets/ic_template-C5WwIyeE.svg",yQ="/try/assets/ic_textbox_settings_panel-CXyTmHOD.svg",vQ="/try/assets/ic_thumbnail_generator-CwgqQIpO.svg",W_="/try/assets/ic_toggle_feature_search-sWTsyY6G.svg",wQ="/try/assets/ic_toolbar_bgm-B56aUcIm.svg",
7NQ="/try/assets/ic_toolbar_clip_bg_color-D-QBl-48.svg",PQ="/try/assets/ic_toolbar_denoise-D0Hi1zFA.svg",bQ="/try/assets/ic_toolbar_feature_search-BBbVMxDH.svg",LQ="/try/assets/ic_toolbar_frame_pack-B9D_4diA.svg",MQ="/try/assets/ic_toolbar_shape-DpnKcS4Z.svg",DQ="/try/assets/ic_toolbar_sound_effect-C4wsNnx-.svg",kQ="/try/assets/ic_transition-z9Cu9CHs.svg",FQ="/try/assets/ic_translate-CYjtHjsV.svg",UQ="/try/assets/ic_ubuntu-C8bYr23W.svg",VQ="/try/assets/ic_ubuntu_small-DJyf7AzB.svg",GQ="/try/assets/ic_undo-Ks4HQoS0.svg",WQ="/try/assets/ic_vdrop_upload-CecI_Zk7.svg",HQ="/try/assets/ic_videoTransform-DO8rJuzl.svg",jQ="/try/assets/ic_video_remix-4ozPHe9o.svg",zQ="/try/assets/ic_vocal_dictionary-CNp7_Kzb.svg",YQ="/try/assets/ic_volume_effect-RwLoS13z.svg",BQ="/try/assets/ic_windows-D88V-3fM.svg",KQ="/try/assets/ic_windows_small-CxWQ4Pmi.svg",XQ="/try/assets/main_icon_classic-DM_Vcufh.svg",JQ="/try/assets/main_icon_instagram-DIurf5Jo.svg",qQ="/try/assets/main_icon_original-hBude1Ot.svg",QQ="/try/assets/main_icon_square-DHtP7hCl.svg",ZQ="/try/assets/main_icon_vertical-DAth8WBh.svg",$Q="/try/assets/main_icon_widescreen-CUwmF6uS.svg",eZ="/try/assets/ic_insert_tts-Dsc82185.svg",tZ="/try/assets/ic_insert_tts_effect-CL6BRhFK.svg",oZ="/try/assets/ic_tts_dubbing-DF8Npook.svg",rZ="/try/assets/ic_user_tts-D2SSItEv.svg",nZ="/try/assets/ic_user_tts_speaker_list-CUhLLDxl.svg",le={VIDEO_REMIX:jQ,EXPORT_VIDEO:Sq,EXPORT_AS:Tq,VDROP_UPLOAD:WQ,CURRENT_VIDEO_FILE:fq,OPEN_PROJECT:zq,PLAY:Jq,PAUSE:Xq,ADD_VIDEO_FILE:nQ,START_MODAL:RQ,NEW_WINDOW:Hq,THUMBNAIL_GENERATOR:vQ,VIDEO_RATIO_INIT:qQ,VIDEO_RATIO_CLASSIC:XQ,VIDEO_RATIO_WIDE_SCREEN:$Q,VIDEO_RATIO_SQUARE:QQ,VIDEO_RATIO_VERTICAL:ZQ,VIDEO_RATIO_INSTAGRAM:JQ,LOCAL_SAVE:rL,BROWSER_SAVE:rL,SAVE_A_COPY:oQ,CLOUD_SAVE_CHECK:rQ,SAVE_TO_COMPUTER:Dq,SAVE_IN_BROWSER:aq,UPLOAD_TO_CLOUD:cq,UNDO:GQ,REDO:$q,COPY:lq,CUT:gq,PASTE:Kq,VREW_AGENT:qJ,MERGE:Gq,DIVIDE:hq,TRUNCATE_SILENT:_q,MARKER:Uq,OVERDUB:Bq,SELECT_CLIP:sQ,SELECT_ASSET:aQ,SELECT_ASSET_AI_IMAGE:tL,SELECT_ASSET_AI_VIDEO:oL,SELECT_ASSET_IMAGE:_Q,SELECT_ASSET_VIDEO:IQ,SELECT_ASSET_DESIGNED_TEXT:OQ,SELECT_ASSET_TEXT:SQ,SELECT_ASSET_BGM:TQ,SELECT_ASSET_SOUND_EFFECT:CQ,SELECT_ASSET_TTS_EFFECT:hQ,SELECT_ASSET_TTS_DUBBING:mQ,SELECT_ASSET_SHAPE:EQ,SELECT_ASSET_CHARACTER:gQ,VIDEO_LOCK:W_,ORIGINAL_VIEW:Yq,FIND:Vq,CLIENT_LINEBREAK:xq,CAPTION_CORRECTION:DS.magicWand,AUTO_SPLIT_SCENES:rq,TRANSLATE_CAPTION:FQ,IMPORT_TIMECODE_TEXT:Nq,IMPORT_SCRIPT:vq,IMPORT_SUBTITLE:wq,CAPTION_ON:W_,COPY_CAPTION:dq,COPY_TRANSLATED_CAPTION:uq,REMOVE_CAPTION:eQ,REMOVE_TRANSLATED_CAPTION:tQ,SPELLCHECK_TOGGLE:W_,CAPTION_SETTING_DELETE:Rq,SAVED_CAPTION_FORMATS:Cq,FORMAT_APPLY_BOLD:nq,FORMAT_APPLY_ITALIC:Mq,FORMAT_FONT_SIZE:iq,FORMAT_TEXT_COLOR:lQ,FORMAT_OUTLINE_COLOR:dQ,TEXT_BACKGROUND_COLOR:iQ,TEXT_HIGHLIGHT_COLOR:xQ,TEXT_SHADOW_COLOR:uQ,TEXT_SPACING:cQ,FORMAT_OPEN_ADVANCED:yQ,CAPTION_POSITION:Qq,CAPTION_ANIMATION:yq,FREE_SOURCE:Aq,INSERT_BLANK_CLIP:Pq,INSERT_FREEZE_WORD:bq,INSERT_TEXTBOX:tq,INSERT_DESIGNED_TEXTBOX:eq,INSERT_AI_STYLIZED_CAPTION:$J,INSERT_IMAGE_AND_VIDEO:Lq,INSERT_SHAPE:MQ,GENERATE_IMAGE:tL,GENERATE_VIDEO:oL,INSERT_AUTO_GENERATED_IMAGE:QJ,CHARACTER:sq,INSERT_BGM:wQ,INSERT_SOUND_EFFECT:DQ,RECORD:Zq,INSERT_TTS:eZ,TTS_EFFECT:tZ,TTS_DUBBING:oZ,USER_TTS:rZ,USER_TTS_SPEAKER_LIST:nZ,INSERT_FRAMEPACK:LQ,CREATE_FRAMEPACK:pq,INSERT_TEMPLATE:AQ,FLIP_HORIZONTAL:DS.flipHorizontal,FLIP_VERTICAL:DS.flipVertical,EFFECT_FILTER:R1,EFFECT_ZOOM:HQ,EFFECT_DENOISE:PQ,EFFECT_TRANSITION:kQ,EFFECT_VOLUME:YQ,EFFECT_PLAYBACKRATE:qq,CLIP_BG_COLOR:NQ,FEEDBACK:Oq,SETTING:pQ,DIAGNOSTIC:Eq,SHORTCUT:fQ,ABOUT:ZJ,ANNOUNCEMENT:oq,USER_INFO:Wq,DISCORD:mq,DOWNLOAD_WIN:BQ,DOWNLOAD_WIN_SMALL:KQ,DOWNLOAD_LINUX:UQ,DOWNLOAD_LINUX_SMALL:VQ,DOWNLOAD_MAC:kq,DOWNLOAD_MAC_SMALL:Fq,FEATURE_SEARCH:bQ,FORMAT_OPACITY:jq,VOCAL_DICTIONARY:zQ,TOGGLE_PRONUNCIATION:W_,EXPERIMENT:Iq},aZ="2",iZ={"x-api-version":aZ},sZ=60,RJe=["16:9","4:3","1:1","3:4","9:16"],Ac={REGULAR_V1:"genvideo-regular-v1",REGULAR_V2:"genvideo-regular-v2",PROMO_V1:"genvideo-promo-v1",PROMO_V2:"genvideo-promo-v2"},AJe=100,xZ=40,cZ=.01,lZ=3600,dZ=1,uZ=32e4,A1=7200,y1=0,v1=1,w1=3e3,Wh=10,pZ=4*1024*1024*1024,yJe=1e3,vJe=60,Un=1,fZ=.5,gZ=4,wJe=.25,NJe=["0.25","0.5","0.75","1","1.25","1.5","1.75","2","3","4"],PJe="VREW-BLANK-VIDEO-ELEMENT-ID",zx=44100,bJe=.001,_Z=-5,EZ=5,LJe=0,MJe="neutral",nL="auto",DJe=void 0,kJe="none",FJe="-",N1="v1",mZ=1,P1="_characteristic",b1=["aws_neural","aws_newscaster"],hZ=new Set([P1,...b1]),UJe=e=>hZ.has(e),aL=400,L1=[.5,.7,.8,.9,.95,.96,.97,.98,.99,.995],M1=5,VJe=1024*1024*1024*49,fg="sources",gg="media",D1="snapshots",hy="cloud_project",IZ="proxy",vn=3,k1="projects",GJe=.8,H_="max-age=86400, public",TZ="x-amz-meta-hash",iL="x-amz-meta-origfilename",jc=1024*1024*100,SZ=5*1024*1024*1024,F1=/<ETag>(["']?)(.*?)\1<\/ETag>
7/,OZ=1024*1024*100,_u=.5,Iy=.5,Ty=15,CZ="media",Mx="project.json",RZ=/\.vrew~$/,_R="html",ER="xml",j_="png",Hh="mp3",Ao="uc-0010-simple-textbox",Al=Ao,AZ=`
8<style>
9.`+Al+` {
10  text-align: var(--textbox-align);
11  line-height: 1.4;
12  font-size: 25px;
13  color: white;
14  font-family: initial;
15  font-weight: initial;
16  display: flex;
17  align-items: center;
18  justify-content: var(--textbox-align);
19  width: 100%;
20  overflow: visible;
21}
22.`+Al+` .textarea {
23  white-space: pre-wrap;
24  word-wrap: break-word;
25  background-color: var(--textbox-color);
26  width: fit-content;
27  padding: 3px 0px 1px 0px;
28}
29.`+Al+` .textarea p {
30  margin-block-start: 0px;
31  margin-block-end: 0px;
32  padding: 0px 5px;
33  line-height: var(--textbox-lineheight);
34}
35.`+Al+` .textarea p span {
36  vertical-align: bottom;
37}
38.`+Al+` .textarea .ql-blank p {
39  padding: 0px;
40}
41.`+Al+` .textarea .ql-blank p > span {
42  background-color: transparent !important;
43}
44</style>
45<div class="`+Al+`">
46  <div class="textarea" id="textarea"></div>
47</div>`,yZ=.3,vZ=1,U1=.01,V1=60,Sy=0,$r="/try/assets/thumbnail_default-gGeB64vG.png",wZ="/try/assets/ic_bookmark_hover-CW9u77Qy.svg",NZ="/try/assets/ic_bookmark_normal_light-DHKA4Wkb.svg",PZ="/try/assets/ic_bookmark_selected_hover_light-XcL2o7bC.svg",bZ="/try/assets/ic_bookmark_selected_light-Dub-ONmd.svg",LZ={light:{normal:NZ,hover:wZ,selected:bZ,selectedHover:PZ}},MZ="/try/assets/ic_clip_bg_color_menu-DMuoI-qP.svg",DZ="/try/assets/ic_playbackrate_badge-UIGxeWBP.svg",kZ="/try/assets/ic_source_volume_loud-Q8q7BS8D.svg",FZ="/try/assets/ic_source_volume_mute-CcYStgit.svg",UZ="/try/assets/ic_source_volume_quiet-DXmWNMVh.svg",VZ="/try/assets/ic_transition_black_fade_out-mwMQMCDH.svg",GZ="/try/assets/ic_transition_circle_open-DEwWCcsY.svg",WZ="/try/assets/ic_transition_color_distance-BEaUkvmU.svg",HZ="/try/assets/ic_transition_cross_fade-ByRahndC.svg",jZ="/try/assets/ic_transition_default-Cx3q7biO.svg",zZ="/try/assets/ic_transition_directional_warp-DG3d9Hrg.svg",YZ="/try/assets/ic_transition_directional_wipe-BXA2yHx_.svg",BZ="/try/assets/ic_transition_dreamy-BAnAuaLO.svg",KZ="/try/assets/ic_transition_glitch_memories-NovnM2KM.svg",XZ="/try/assets/ic_transition_grayscale_fade-CiIegm69.svg",JZ="/try/assets/ic_transition_iris-B-_srNUE.svg",qZ="/try/assets/ic_transition_linear_blur-BO9sSIpB.svg",QZ="/try/assets/ic_transition_morph-Cf9jBDDc.svg",ZZ="/try/assets/ic_transition_pixelize-Bs-NwxkS.svg",$Z="/try/assets/ic_transition_radial-CdVKfhP9.svg",e$="/try/assets/ic_transition_simple_zoom-BwUpww4i.svg",t$="/try/assets/ic_transition_vertical_wipe-Drdf8wyP.svg",o$="/try/assets/ic_transition_white_fade_out-B-QF6Xvq.svg",r$="/try/assets/ic_transition_wind-B2Qfvcxh.svg",n$="/try/assets/ic_transition_window_blind-D-DBwl-6.svg",a$="/try/assets/ic_transition_wipe_down-hCngGTWm.svg",i$="/try/assets/ic_transition_wipe_left-BAssS1Jb.svg",s$="/try/assets/ic_transition_wipe_right-bEWjQfKW.svg",x$="/try/assets/ic_transition_wipe_up-Cn2sntKI.svg",c$="/try/assets/ic_videoTransform_badge-Bg8m-wIN.svg",wr={playbackRate:DZ,videoTransform:c$,sourceVolume:{loud:kZ,quiet:UZ,mute:FZ},background:{default:MZ},transition:{default:jZ,blackFadeOut:VZ,circleOpen:GZ,colorDistance:WZ,crossFade:HZ,directionalWarp:zZ,directionalWipe:YZ,dreamy:BZ,glitchMemories:KZ,grayScale:XZ,iris:JZ,linearBlur:qZ,morph:QZ,pixelize:ZZ,radial:$Z,simpleZoom:e$,verticalWipe:t$,whiteFadeOut:o$,wind:r$,windowBlind:n$,wipeDown:a$,wipeLeft:i$,wipeRight:s$,wipeUp:x$},filter:R1},Oy="/try/assets/ic_info_outlined-DzSs2NMH.svg",l$="/try/assets/thumbnail_black_fade_out-rE_wU2gf.png",d$="/try/assets/thumbnail_circle_open-Cre6o7Cc.png",u$="/try/assets/thumbnail_color_distance-Bns1cyq6.png",p$="/try/assets/thumbnail_cross_fade-C0S9d_vX.png",f$="/try/assets/thumbnail_directional_warp--1WtmdUC.png",g$="/try/assets/thumbnail_directional_wipe-DKGzZDB6.png",_$="/try/assets/thumbnail_dreamy-DBeQMJkh.png",E$="/try/assets/thumbnail_glitch_memories-_OCrC4AO.png",m$="/try/assets/thumbnail_gray_scale_fade-DnhZnfiL.png",h$="/try/assets/thumbnail_iris-BccTdkRi.png",I$="/try/assets/thumbnail_linear_blur-T4WlG5LN.png",T$="/try/assets/thumbnail_morph-BeawSVXm.png",sL="/try/assets/thumbnail_none-1665Dttj.png",S$="/try/assets/thumbnail_pixelize-BqocCCmq.png",O$="/try/assets/thumbnail_radial-DgynFoIm.png",C$="/try/assets/thumbnail_simple_zoom-DJccn4ui.png",R$="/try/assets/thumbnail_vertical_wipe-BMP8OcJD.png",A$="/try/assets/thumbnail_white_fade_out--biqSWGJ.png",y$="/try/assets/thumbnail_wind-BkQzb6IK.png",v$="/try/assets/thumbnail_window_blind-kKM-CB2f.png",w$="/try/assets/thumbnail_wipe_down-DvG41wjP.png",N$="/try/assets/thumbnail_wipe_left-B7O2cuXo.png",P$="/try/assets/thumbnail_wipe_right-DLg1kkQ4.png",b$="/try/assets/thumbnail_wipe_up-ByqTFlHR.png",L$="/try/assets/black_fade_out-CBXGpOCE.gif",M$="/try/assets/circle_open-Ds2twqL_.gif",D$="/try/assets/color_distance-7CUWI33q.gif",k$="/try/assets/cross_fade-BFDDjzzE.gif",F$="/try/assets/directional_warp-8fXW8NaZ.gif",U$="/try/assets/directional_wipe-DfJhJOIr.gif",V$="/try/assets/dreamy-CHjih83N.gif",G$="/try/assets/glitch_memories-yOdYfMTF.gif",W$="/try/assets/gray_scale_fade-56JqfjeI.gif",H$="/try/assets/iris-DBAw19HK.gif",j$="/try/assets/linear_blur-DyuUph58.gif",z$="/try/assets/morph-DjRop_6X.gif",Y$="/try/assets/pixelize-CN6cwfyM.gif",B$="/try/assets/radial-BxC9YdeA.gif",K$="/try/assets/simple_zoom-DZ5TZmXY.gif",X$="/try/assets/vertical_wipe-DpptoWAU.gif",J$="/try/assets/white_fade_out-CMBiZ-7q.gif",q$="/try/assets/wind-zIr1XsKb.gif",Q$="/try/assets/window_blind-Brf11_gT.gif",Z$="/try/assets/wipe_down-CCWnPbXW.gif",$$="/try/assets/wipe_left-CjU-NZm6.gif",eee="/try/assets/wipe_right-DQ00pvZS.gif",tee="/try/assets/wipe_up-U7Fq-ym4.gif",Vt={gif:{BLACK_FADE_OUT:L$,CI
47RCLE_OPEN:M$,COLOR_DISTANCE:D$,CROSS_FADE:k$,DIRECTIONAL_WIPE:U$,DIRECTIONAL_WARP:F$,DREAMY:V$,GLITCH_MEMORIES:G$,GRAY_SCALE:W$,IRIS:H$,LINEAR_BLUR:j$,MORPH:z$,NONE:sL,PIXELIZE:Y$,RADIAL:B$,SIMPLE_ZOOM:K$,WIPE_LEFT:$$,WIPE_RIGHT:eee,WIPE_UP:tee,VERTICAL_WIPE:X$,WHITE_FADE_OUT:J$,WIND:q$,WINDOW_BLIND:Q$,WIPE_DOWN:Z$},thumbnail:{BLACK_FADE_OUT:l$,CIRCLE_OPEN:d$,COLOR_DISTANCE:u$,CROSS_FADE:p$,DIRECTIONAL_WIPE:g$,DIRECTIONAL_WARP:f$,DREAMY:_$,GLITCH_MEMORIES:E$,GRAY_SCALE:m$,IRIS:h$,LINEAR_BLUR:I$,MORPH:T$,NONE:sL,PIXELIZE:S$,RADIAL:O$,SIMPLE_ZOOM:C$,WIPE_LEFT:N$,WIPE_RIGHT:P$,WIPE_UP:b$,VERTICAL_WIPE:R$,WHITE_FADE_OUT:A$,WIND:y$,WINDOW_BLIND:v$,WIPE_DOWN:w$}},oee="/try/assets/ic_check_blue-4XB-pn8u.svg",ree="/try/assets/ic_check_small--KQVpZyN.svg",nee="/try/assets/ic_arrow_tts_license-B_62WfBY.svg",aee="/try/assets/ic_check-7pOQyDel.svg",iee="/try/assets/ic_copy-ZyD92Bdp.svg",see="/try/assets/ic_license_tts_dark-Citk0x9J.svg",xee="/try/assets/ic_license_tts_light-DmgqT6yc.svg",cee="/try/assets/ic_license_tts_light_mint-ChQ_ElZQ.svg",lee="/try/assets/ic_license_tts_normal-C915z59m.svg",dee="/try/assets/ic_license_tts_normal_mint-02B8Tj6F.svg",uee="/try/assets/ic_tts_cancel_disabled_xs-DXYgKrih.svg",pee="/try/assets/ic_tts_cancel_xs-JavZ3Bix.svg",fee="/try/assets/ic_tts_effect_input_box_arrow-Bph_fUAE.svg",gee="/try/assets/ic_tts_license_icon-B_sotASo.svg",_ee="/try/assets/ic_tts_modify_text-CJAasQgk.svg",Eee="/try/assets/ic_tts_reset_filter-dC_LFacX.svg",mee="/try/assets/ic_tts_sample_loading-DNBO02qV.svg",hee="/try/assets/ic_tts_sample_playing-DxJjznTA.svg",Iee="/try/assets/ic_tts_sample_playing_xs-CRLen7Lw.svg",Tee="/try/assets/ic_tts_sample_xs-DGcxDuEC.svg",See="/try/assets/ic_tts_setting_arrow-CCp5ywIZ.svg",Oee="/try/assets/ic_tts_setting_enabled-C8qmtr8G.svg",Cee="/try/assets/ic_tts_setting_sm-CGKvrfCn.svg",Ree="/try/assets/ic_tts_setting_xs-CY-pfMQ-.svg",Aee="/try/assets/ic_tts_submit_disabled_xs-SB30o6aA.svg",yee="/try/assets/ic_tts_submit_loading_xs-BeL0RGhN.svg",vee="/try/assets/ic_tts_submit_xs-0fI2TvzK.svg",wee="/try/assets/ic_tts_tag_characteristic-DvuBF6dP.svg",Nee="/try/assets/ic_tts_tag_free-B888vk89.svg",Pee="/try/assets/ic_tts_tag_multilingual-HMXSJyiU.svg",bee="/try/assets/ic_tts_tag_recommended-DS0rAShS.svg",Lee="/try/assets/ic_tts_tag_style-CTJnbEJ-.svg",Mee="/try/assets/ic_tts_tag_usertts-Qgv4fuE6.svg",Dee={normal:{xs:Ree,sm:Cee},enabled:{md:Oee}},kee={normal:{xs:Tee},playing:{xs:Iee,md:hee},loading:{dark:mee}},Fee={normal:LZ.light.normal},Uee={normal:ree,blue:oee},Vee={normal:{xs:vee},disabled:{xs:Aee},loading:{xs:yee}},Gee={normal:{xs:pee},disabled:{xs:uee}},Wee={normal:lee,light:xee,dark:see,"normal-mint":dee,"light-mint":cee,arrow:nee},Hee={copy:iee,copyComplete:aee},jee=gee,zee=fee,Yee={recommended:bee,free:Nee,characteristic:wee,style:Lee,user:Mee,multilingual:Pee},xL={setting:Dee,sample:kee,bookmark:Fee,check:Uee,submit:Vee,cancel:Gee,license:Wee,licenseShowMore:jee,effectInputBoxArrow:zee,copy:Hee,resetFilter:Eee,modifyText:_ee,settingArrow:See,tag:Yee},Us=()=>!1,mR={cmdReceived:()=>!1,on:()=>mR,off:()=>mR,getDebugVal:()=>{},setDebugVal:()=>{}},Mo=()=>mR,Id=e=>G1(e.type),G1=e=>e===ze.SoundEffect||e===ze.TTSEffect||e===ze.TTSDubbing;var Bee=(e=>(e.INTRO="intro",e.SETTING="setting",e.GENERATING="generating",e))(Bee||{}),Kee=(e=>(e.READ_FILE="read_file",e.GENERATE_ATV="generate_atv",e.MAKE_CLIP="make_clip",e.APPLY_ASSETS="apply_assets",e))(Kee||{});const WJe=1024*1024*100,HJe=500*1024*1024,jJe="500 MB",zJe=61,YJe="1",BJe=30*1024*1024,KJe=20,W1=he.VERTICAL,Xee={width:1080,height:1920},XJe=88;var vp=(e=>(e.TOO_LONG_VIDEO="too_long_video",e.TOO_LARGE_VIDEO="too_large_video",e.UNSUPPORTED_FORMAT="unsupported_format",e.LOAD_FAILED="load_failed",e))(vp||{});const JJe=3e3,qJe={isBGMOn:!0,isVideoSoundOn:!1,captionPosition:"bottom"},Cy=()=>Ve().getBool(Ie.LICENSE_AGREED,!1),hR=e=>{Ve().set(Ie.LICENSE_AGREED,e)},H1="cfm_replacer_v2",LE=10,fm=[ce.Korean,ce.English];var j1=(e=>(e.overdub="overdub",e))(j1||{});const QJe=(e,t=0)=>{const o=Ve(),r=o.getObject(Ie.FEATURE_ONBOARDING_TRIGGERED);return!r[e]&&(r[e]=t,o.set(Ie.FEATURE_ONBOARDING_TRIGGERED,{...r})),r[e]},ZJe=e=>{const t=Ve(),o=t.getObject(Ie.FEATURE_ONBOARDING_TRIGGERED);t.set(Ie.FEATURE_ONBOARDING_TRIGGERED,{...o,[e]:o[e]+1})},Ry="/try/assets/ic_crown-BfCbR3DE.svg",Jee="/try/assets/ic_gift_box_fill-B360lyOf.svg",qee=e=>{const{size:t,isPremiumTrial:o,...r}=e;return b.jsx(fn,{...r,src:o?Jee:Ry,w:t,h:t,maskColor:ee.orange[500]})},Qee=(e,t,o)=>{const r=A("toolbar.app_download_label"),n=Mr()?"mac":Ps()?"win":"linux",a=A(n==="mac"?"toolbar.app_download_mac":n==="win"?"toolbar.app_download_win":"toolbar.app_download_linux"),i={small:{mac:le.DOWNLOAD_MAC_SMALL,win:le.DOWNLOAD_WIN_SMALL,linux:le.DOWNLOAD_LINUX_SMALL},large:{mac:le.DOWNLOAD_MAC,win:le.DOWNLOAD_WIN,linux:le.DOWNLOAD_LINUX}},s=i[e][n],x=o?pMe(t,o):t;return{label:r,tooltip:a,iconSrc:s,handleClick:x}},Zee=({onClick:e,ga:t})=>{const{label:o,tooltip:r,iconSrc:n,handleClick:a}=Qee("large",e,t);return b.jsx(M0,{content:r,children:b.jsxs($ee,{onClick:a,children:[b.jsx(fn,{w:20,h:20,src:n,maskColor:ee.mint[600],css:{maskSize:"unset",maskRepeat:"no-repeat",maskPosition:"center"}}),b.jsx(Nt,{children:o})]})})},$ee=xe("button",{"&&":{h:40,px:12,py:10,w:"unset",minW:100,border:`1px solid ${ee.mint[500]}`},gap:8,borderRadius:8,display:"flex",flex:"1 0 auto",flexDirection:"row",alignItems:"center",justifyContent:"center",color:ee.mint[600],fontWeight:500,fontSize:14,lineHeight:"20px",outline:"none",bg:"none","&:hover":{bg:ee.gray[50]}}),ete=xe("div",{display:"inline-block",flex:"0 0 auto",minWidth:0}),tte=it.forwardRef((e,t)=>
47{const{css:o,rest:r,children:n,className:a}=al(e);return b.jsx(ete,{ref:t,css:o,className:a,...r,children:n})}),IR="& > *:not(style) ~ *:not(style)",ote=(e,t)=>rn.isArray(e)?e.map(o=>{if(o!==void 0)return t(o)}).filter(wX):rn.isObject(e)?Object.keys(e).reduce((o,r)=>(o[r]=t(e[r]),o),{}):t(e),rte=e=>{const{spacing:t,direction:o}=e,r={column:{marginTop:t,marginEnd:0,marginBottom:0,marginLeft:0},row:{marginTop:0,marginEnd:0,marginBottom:0,marginLeft:t},"column-reverse":{marginTop:0,marginEnd:0,marginBottom:t,marginLeft:0},"row-reverse":{marginTop:0,marginEnd:t,marginBottom:0,marginLeft:0}};return{flexDirection:o,[IR]:ote(o,n=>r[n])}},nte=xe("div",{display:"flex"}),Ay=it.forwardRef((e,t)=>{const{isInline:o,direction:r,align:n,justify:a,spacing:i="0.5rem",wrap:s,shouldWrapChildren:x,...c}=e,{css:l,rest:d,children:u,className:p}=al(c),f=o?"row":r??"column",E=it.useMemo(()=>rte({direction:f,spacing:i}),[f,i]),T=it.useMemo(()=>{const S=NX(u);return x?S.map((R,y)=>{const v=typeof R.key<"u"?R.key:y;return b.jsx(tte,{children:R},v)}):S},[x,u]),O=aU(l,{alignItems:n,justifyContent:a,flexWrap:s,flexDirection:E.flexDirection,[IR]:E[IR]});return b.jsx(nte,{ref:t,className:p,css:O,...d,children:T})}),$Je=it.forwardRef((e,t)=>b.jsx(Ay,{align:"center",direction:"row",ref:t,...e})),eqe=it.forwardRef((e,t)=>b.jsx(Ay,{align:"center",direction:"column",ref:t,...e})),z_=e=>jt.createElement("div",{className:"content"},jt.createElement("div",{className:"marker"}),e),Ki={success:(e,t)=>Es.success(z_(e),t),info:(e,t)=>Es.info(z_(e),t),error:(e,t)=>Es.error(z_(e),t),warn:(e,t)=>Es.warn(z_(e),t),isActive:e=>Es.isActive(e),popup:(e,t)=>Es(e,t),dismiss:e=>Es.dismiss(e),update:(e,t)=>Es.update(e,t),clearWaitingQueue:Es.clearWaitingQueue},ate=e=>e===void 0?{...zp("id",Na.DEFAULT),containerId:s0.TOP_CENTER}:{...e,containerId:s0.TOP_CENTER},zp=(e,t,o=1e3,r,n=!0)=>({position:"top-center",className:t,autoClose:o,draggable:!1,closeOnClick:!1,closeButton:n,toastId:e,onClose:r,containerId:s0.TOP_CENTER,transition:p9({collapse:!0,enter:"not-using",exit:"not-using",collapseDuration:0,duration:[200,0]})}),ite=(e,t)=>{switch(To.dismiss(void 0),e){case Na.PLAYBACK_RATE:{const o=zp("playbackToast",Na.PLAYBACK_RATE,500,void 0);To.popup(t+"x",o);break}case Na.IMPORT_SCRIPT:{const o=zp("importScriptToast",Na.IMPORT_SCRIPT,1e3,void 0,!1);To.popup(t,o);break}case Na.DECRYPT_DOCS_PW:{const o=zp("decryptDocsPwToast",Na.DECRYPT_DOCS_PW,2e3,void 0,!1);To.popup(t,o);break}case Na.TTS_DUMMY_CLIP:{const o=To.generateToastOption("abortDummyClip",Na.WITH_BUTTON,!1);To.popup(t,o);break}}},To={isActive:Ki.isActive,popup:(e,t)=>Ki.popup(e,ate(t)),dismiss:Ki.dismiss,generateToastOption:zp,clearWaitingQueue:()=>Ki.clearWaitingQueue({containerId:s0.TOP_CENTER}),generateToastComponent:e=>jt.createElement("div",{className:"content"},jt.createElement("div",{className:"desc"},e)),generateToastComponentWithButton:(e,t,o)=>jt.createElement("div",{className:"content"},jt.createElement("div",{className:"desc"},e),jt.createElement("button",{className:"cancel-button",onClick:o},t))},Ep=e=>e===void 0?{containerId:s0.TOP_RIGHT}:{...e,containerId:s0.TOP_RIGHT},ste=e=>e===void 0?{containerId:s0.TOP_RIGHT}:{...e,containerId:s0.TOP_RIGHT},xte=(e,t=1e3,o)=>({position:"top-right",autoClose:t,draggable:!1,closeOnClick:!1,closeButton:!0,toastId:e,onClose:o}),xt={success:(e,t)=>Ki.success(e,Ep(t)),info:(e,t)=>Ki.info(e,Ep(t)),error:(e,t)=>Ki.error(e,Ep(t)),warn:(e,t)=>Ki.warn(e,Ep(t)),popup:(e,t)=>Ki.popup(e,Ep(t)),update:(e,t)=>Ki.update(e,ste(t)),isActive:Ki.isActive,dismiss:Ki.dismiss,clearWaitingQueue:()=>{Ki.clearWaitingQueue({containerId:s0.TOP_RIGHT})},generateToastOption:xte},cte=e=>{const t=async()=>{h("CopyLinkModal.tsx").info("onClickCopy() clicked."),await navigator.clipboard.writeText(e),To.popup(A("free_source_panel.detail_license_copy_complete"))};return b.jsxs(Ay,{className:"--url-error-container",children:[b.jsx("div",{children:A("error.open_url")}),b.jsx("br",{}),b.jsx("button",{onClick:t,style:{background:"transparent",border:"transparent"},className:"--url",children:b.jsx("div",{style:{textAlign:"start",color:ee.mint[600]},children:e})}),b.jsx(Xe,{justify:"center",align:"center",children:b.jsx("button",{onClick:t,style:{background:"transparent",border:"transparent"},className:"--copy-button",children:b.jsx(Xe,{style:{width:"fit-content",border:`1px solid ${ee.gray[125]}`,borderRadius:4,backgroundColor:ee.gray[0],padding:"8px 20px",color:ee.gray[750]}
47,children:A("context.image_copy")})})}),b.jsx("br",{})]})},tqe=3600*2,oqe="_denoised",rqe="m4a",nqe=1,lte=95,dte=lte-1,ute=1e3,pte=300*1e3,aqe=dte/pte*ute,fte=1,cL=900,gte=/[?&]vrew_ad_method=(\w*)/,_te=/[?&]_vrewAdMethod=(\w*)/,Ete="va",mte="signUp",hte="oauthSignIn",Ite="auth-token-request",z1="target",Y1="web",B1="electron",lL="signUpRedirect",Tte="https://docs.channel.io/vrew-kr/ko/articles/%EA%B3%B5%EC%A7%80-%EA%B5%AC%EB%B2%84%EC%A0%84-OS-%EC%A7%80%EC%9B%90%EC%9D%B4-%EC%A2%85%EB%A3%8C%EB%90%98%EC%97%88%EC%8A%B5%EB%8B%88%EB%8B%A4-2024216-64a8c3c9",Ste="https://vrewjp.imweb.me/notice/?bmode=view&idx=18052161&back_url=&t=board&page=",Ote="https://vrew-help.notion.site/2e6aeadd0019492494226e9fc5db7827?pvs=4",jh=e=>e==="manebi"||e==="malgnsoft",Cte={manebi:{title:"referral.manebi_title",content:"referral.manebi_content"},classu:{title:"referral.classu_title",content:"referral.classu_content"},malgnsoft:{title:"referral.malgnsoft_title",content:"referral.malgnsoft_content"},affiliate:void 0},Rte=async e=>{const t=e?Cte[e]:void 0;if(t===void 0)return;const o={bodyClassName:"general-modal",title:A(t.title),content:A(t.content),yesStr:A("popup.confirm")};await Y().popup(o)},Ate="manebi",yte="classu",vte="malgnsoft",wte=e=>{switch(e){case Ate:return"manebi";case yte:return"classu";case vte:return"malgnsoft";default:return}};var mt=(e=>(e.YES="yes",e.NO="no",e.CLOSE="close",e.CANCEL="cancel",e))(mt||{}),mc=(e=>(e.YES="YES",e.NO="NO",e.UNDEFINED="",e))(mc||{}),st=(e=>(e.NULL="NULL",e.STARTMODE="STARTMODE",e.LOGIN="LOGIN",e.ABOUT="ABOUT",e.SELECT_LANGUAGE="SELECT_LANGUAGE",e.IMPORT_VIDEO_WITHOUT_AUDIO="IMPORT_VIDEO_WITHOUT_AUDIO",e.CHOOSE_EXPORT_OPTIONS="CHOOSE_EXPORT_OPTIONS",e.CHOOSE_CAPTION_VIDEO_EXPORT_OPTIONS="CHOOSE_CAPTION_VIDEO_EXPORT_OPTIONS",e.EXPORT_SYNC_CAUTION="EXPORT_SYNC_CAUTION",e.CHOOSE_AUDIO_EXPORT_OPTIONS="CHOOSE_AUDIO_EXPORT_OPTIONS",e.CHOOSE_IMAGE_EXPORT_OPTIONS="CHOOSE_IMAGE_EXPORT_OPTIONS",e.CHOOSE_TEXT_EXPORT_OPTIONS="CHOOSE_TEXT_EXPORT_OPTIONS",e.CHOOSE_VIDEO_IMPORT_OPTIONS="CHOOSE_VIDEO_IMPORT_OPTIONS",e.FEEDBACK="FEEDBACK",e.DIAGNOSTIC="DIAGNOSTIC",e.SHORTCUT="SHORTCUT",e.LOST_VIDEO="LOST_VIDEO",e.WARN_DIFFERENT_MEDIA_DURATION="WARN_DIFFERENT_MEDIA_DURATION",e.IMPORT_SUBTITLE="IMPORT_SUBTITLE",e.IMPORT_TIMECODE_TEXT="IMPORT_TIMECODE_TEXT",e.IMPORT_SCRIPT="IMPORT_SCRIPT",e.RESTORE_AUTOSAVE="RESTORE_AUTOSAVE",e.EXPORT_VIDEO_EDITOR_XML="EXPORT_VIDEO_EDITOR_XML",e.ANNOUNCEMENT="ANNOUNCEMENT",e.FILE_INFO="FILE_INFO",e.TRANSLATE="TRANSLATE",e.CHOOSE_CAPTION_EXPORT_OPTIONS="CHOOSE_CAPTION_EXPORT_OPTIONS",e.DROP_FILE="DROP_FILE",e.SETTING="SETTING",e.OPEN_PROJECT="OPEN_PROJECT",e.INSERT_ASSET_CLIP="INSERT_IMAGE_CLIP",e.VIDEO_TRIM="VIDEO_TRIM",e.KENBURNS_CUSTOM="KENBURNS_CUSTOM",e.RECORDER="RECORDER",e.TTS="TTS",e.MULTI_FILE_UPLOAD="MULTI_FILE_UPLOAD",e.INIT_THEME="INIT_THEME",e.TXT_TO_VIDEO="TXT_TO_VIDEO",e.SHORTS="SHORTS",e.CHARACTER_REQUEST="CHARACTER_REQUEST",e.PAYMENT_PLAN_MANAGEMENT="PAYMENT_PLAN_MANAGEMENT",e.PROFILE_EDIT="PROFILE_EDIT",e.ADD_USAGE="ADD_USAGE",e.IMPORT_DOCS="IMPORT_DOCS",e.IMPORT_IMAGES="IMPORT_IMAGES",e.NEED_PLAN_UPGRADE="NEED_PLAN_UPGRADE",e.CREATE_FRAMEPACK="CREATE_TEMPLATE",e.VIDEO_REMIX="VIDEO_REMIX",e.WAITING_CLIPBOARD="WAITING_CLIPBOARD",e.THUMBNAIL_GENERATOR="THUMBNAIL_GENERATOR",e.VREWMARK_ALTERNATIVE_FORM="VREWMARK_ALTERNATIVE_FORM",e.CHOOSE_CLOUD_UPLOAD_OPTIONS="CHOOSE_CLOUD_UPLOAD_OPTIONS",e.CLOUD_BACKUP_DOWNLOAD="CLOUD_BACKUP_DOWNLOAD",e.USER_TTS="USER_TTS",e.USER_TTS_SPEAKER_LIST="USER_TTS_SPEAKER_LIST",e.TYPEFORM="TYPEFORM",e.VREW_SURVEY="ONBOARDING_SURVEY",e.RESET_PASSWORD="RESET_PASSWORD",e.STARTUP_OPTION="STARTUP_OPTION",e.VOCAL_DICT_EDIT="VOCAL_DICT_EDIT",e.EXPERIMENT="EXPERIMENT",e.VDROP="VDROP",e.MIGRATE_CLOUD_PROJECT="MIGRATE_CLOUD_PROJECT",e.WEB_SAVE_PROJECT="WEB_SAVE_PROJECT",e.MANAGE_BROWSER_PROJECTS="MANAGE_BROWSER_PROJECTS",e.ASSET_TO_VIDEO="ASSET_TO_VIDEO",e.OVERDUB_ONBOARDING="OVERDUB_ONBOARDING",e.SUBSCRIPTION_CONSENT="SUBSCRIPTION_CONSENT",e.CAPTION_CORRECTION_RESULT="CAPTION_CORRECTION_RESULT",e.TEMPLATE_LIST="TEMPLATE_LIST",e.CREDIT_NOT_ENOUGH="CREDIT_NOT_ENOUGH",e.CREDIT_WARNING="CREDIT_WARNING",e.AI_STYLIZED_CAPTION="AI_STYLIZED_CAPTION",e))(st||{}),K1=(e=>(e.YES="yes",e.NO="no",e))(K1||{}),Nte=(e=>(e[e.NULL=0]="NULL",e[e.UPLOADING=1]="UPLOADING",e))(Nte||{}),zl=(e=>(e.CONFIRM="confirm",e.CANCEL="cancel",e.FIND="find",e))(zl||{});const Pte="modal-content";var Xt=(e=>(e.SEND_EMAIL="sendEmail",e.DELETE_USER="deleteUser",e.SET_USAGE="setUsage",e.CLEAR_USAGE="clearUsage",e.RESET_PASSWORD="resetPassword",e.CLEAR_USER="clearUser",e.INSPECT="inspect",e.DELETE_LOCAL_STORAGE="deleteLocalStorage",e.DELETE_USER_ASSETS_IN_IDB="deleteUserAssetsInIdb",e.GET_CER="getCer",e.PRINT_MEMORY="printMemory",e.TABKEY_RESET_NOTICE="tabkeyResetNotice",e.RESET_SURVEY_TOAST="resetSurveyToast",e.CID="cid",e.SET_SIZE="setSize",e.NEW_INSTALL="newInstall",e.STATISTICS="statistics",e.ERROR_CODE="errorCode",e.SPLIT_MEDIA="splitMedia",e.GA="ga",e.ADJUST_VIDEO_PLAYBACK="adjustVideoPlayback",e.IPC_LOG="ipcLog",e.ULTRACAPTION="ultracaption",e.STT_TYPE_REQ="sttTypeReq",e.HWACCEL="hwaccel",e.SMART_UPDOW
47N="smart_updown",e.RECORD_EXPORT="recordExport",e.CLEAN_PROJECT_HISTORY="cleanProjectHistory",e.EXPORT_BEHAVIOR="export-behavior",e.SCROLL_MODE="scroll-mode",e.CHARACTER="character",e.ONBOARDING_TOUR="onboardingTour",e.ONBOARDING_START_MODAL="onboardingStartModal",e.RUN_HARDCUT_ANALYSIS="runHardcutAnalysis",e.UPDATE_READY="updateReady",e.UPDATE_STATUS="updateStatus",e.SHOW_MANUAL_DOWNLOAD="showManualDownload",e.SOFT_LIMIT="softLimit",e.FORCED_UPDATE="forcedUpdate",e.SET_QUOTA="setQuota",e.DISABLE_QUOTA="disableQuota",e.CHECK_LOGIN="checkLogin",e.ADD_USAGE="addUsage",e.SCENE_CONTROL="sceneControl",e.SKIP_FRONT_LOGIN_CHECK="skipFrontLoginCheck",e.PREREGISTRATION="preRegistration",e.SLOW_SAVE="slowSave",e.NEW_TTS="newTTS",e.NEW_TTS_ACTING="newTTSActing",e.TTS_DISABLE_CACHE="ttsDisableCache",e.TTS_MOCK_RESPONSE="ttsMockResponse",e.TTS_RANDOMLY_FAIL="ttsRandomlyFail",e.SKIP_TTS_PREPROCESSING="skipTTSPreprocessing",e.SHOW_TTS_SPEAKER_INFO="showTtsSpeakerInfo",e.INSERT_TTS_CLIPS="insertTtsClips",e.CHANGE_VREWMARK_PERIOD="changeVrewmarkPeriod",e.FORCE_IMAGEGEN_VREWSERVER="forceImagegenVrewserver",e.SHOW_NEW_FEATURE_IMAGE="showNewFeatureImage",e.SKIP_STANDARD_PLAN_CHECK="skipStandardPlanCheck",e.CHARACTER_LIMIT_EXCEED="characterLimitExceed",e.TTV_EMPTY_ASSET_CLIP="ttvEmptyAssetClip",e.PROJECT_INFO_MGR="projectInfoMgr",e.CROP_IMAGE="cropImage",e.OPEN_TYPEFORM="openTypeform",e.BGM_PLAY_RANGES="bgmPlayRanges",e.OPEN_VREW_SURVEY="openVrewsurvey",e.TRANSLATION="translation",e.APPLY_SHEET="applySheet",e.APPLY_LOKALISE_BY_KEY="applyLokaliseByKey",e.RESET_APPLIED_SHEET="resetAppliedSheet",e.SCENE_PERF_LOG="scenePerfLog",e.REDUCER_PERF_LOG="reducerPerfLog",e.EXPORT_VERBOSE="exportVerbose",e.INSTALL_CODE="installCode",e.QUILL_FORMAT="quillFormat",e.QUILL_CONTENTS="quillContents",e.UID="uid",e.REDUX="redux",e.OPEN_EVENT_SURVEY="openEventSurvey",e.DID_YOU_KNOW="didYouKnow",e.LOGIN="login",e.USER_TTS="userTTS",e.SHOW_QUOTA_WARNING="showQuotaWarning",e.SHOW_STARTUP_OPTION_MODAL="showStartupOptionModal",e.REQUEST_VISUAL_ASSETS_FAIL="requestVisualAssetsFail",e.SHOW_NEW_FEATURE_TOOLTIP="showNewFeatureTooltip",e.CONTROL_VCLOUD_STATUS="controlVCloudStatus",e.GET_FILE_HASH="getFileHash",e.OPFS_CLEAR="opfsClear",e.OPFS_PRINT_TREE="opfsPrintTree",e.OPFS_ADD_FILES="opfsAddFiles",e.OPFS_ESTIMATE="opfsEstimate",e.OPFS_CACHE_TTL="opfsCacheTtl",e.OPFS_MIGRATE_TO_LEGACY="opfsMigrateToLegacy",e.IMPORT_BROWSER_PROJECT="importBrowserProject",e.CLEAN_BROWSER_LOGS="cleanBrowserLogs",e.REFRESH_TOKEN="refreshToken",e.REMOVE_FFMPEG="removeFfmpeg",e.MEDIA_STORE="mediaStore",e.SET_EXPORT_DEV="setExportDev",e.TTV_VERSION="ttvVersion",e.START_MODAL_VERSION="startModalVersion",e.LOAD_DEMO="loadDemo",e.NEW_EXPORT_ERROR="newExportError",e.TOO_MANY_ACCOUNT="tooManyAccount",e.SAVE_INFO="saveInfo",e.AGENT_IMAGE_FORCE_EXPIRE="agentImageForceExpire",e.AGENT_IMAGE_PARTIAL_FAIL="agentImagePartialFail",e.SHOW_CREDIT="showCredit",e.CHECK_CREDIT="checkCredit",e.GEN_ASSET_MODELS_FETCH_FAIL="genAssetModelsFetchFail",e.GEN_ASSET_MODEL_FORCE_DISABLED="genAssetModelForceDisabled",e.GEN_ASSET_MODEL_FORCE_DEPRECATED="genAssetModelForceDeprecated",e.SELECT_AGENT_MODEL="selectAgentModel",e.SET_CORE_FLAGS="setCoreFlags",e.TOGGLE_AUTOSAVE="toggleAutosave",e.PREPARE_TTV_PLAN_FAIL="prepareTtvPlanFail",e.GEN_ASSET_FORCE_FAIL="genAssetForceFail",e.DISABLE_GENERATE_QUEUE_LIMIT="disableGenerateQueueLimit",e.PANEL_PICKER="panelPicker",e.TTV_STYLE_FETCH_FAIL="ttvStyleFetchFail",e.SUBSCRIPTION_DATE_STRINGS="subscriptionDateStrings",e.NSFW_IMAGE_FAIL="nsfwImageFail",e))(Xt||{}),bte=(e=>(e.TOAST="toast",e))(bte||{});const Lte=(e,t)=>e?t?A("error.code",{errorCode:e+"/"+t,interpolation:{escapeValue:!1}})+`
48`:A("error.code",{errorCode:e})+`
49`:"",Mte=(e,t)=>
49{if(e===void 0||t===void 0||PX.includes(t))return"";const{sceneIndex:o,clipIndex:r}=e;return h("errorCodes.ts").warn("Error occurred while exporting the "+(o+1)+"th Scene, "+(r+1)+"th clip."),A("export.export_error_clip_index",{sceneIndex:o+1,clipIndex:r+1})},iqe=(e,t)=>{if(!e)return t;const o={[fi.NETWORK_REQUEST_FAILED]:_.C_FIREBASE_NETWORK_REQUEST_FAILED,[fi.TOO_MANY_ATTEMPTS_TRY_LATER]:_.C_AUTHENTIFICATION_TOO_MANY_ATTEMPTS},r=o[e];return r||t},Ot=(e,t)=>{let o;if(t.firebaseErr&&(o=TR(t.firebaseErr)),!o)switch(e){case _.A_AUTH_LOGIN_DELETED_USER:o="error.login_deleted_user";break;case _.A_AUTH_DATABASE_ACCESS_ERROR:o="error.api_auth_failed";break;case _.A_AUTH_REFERRAL_TYPE_ERROR:o="error.referral_type_error";break;case _.A_AUTH_REFERRAL_CODE_ERROR:o="error.referral_code_error";break;case _.A_AUTH_UNVERIFIED_USER:o="error.unverified_user";break;case _.A_AUTH_DELETE_FROM_FIREBASE_ERROR:o="error.api_auth_failed";break;case _.A_AUTH_FIREBASE_DB_MISMATCH:o="error.firebase_db_mismatch";break;case _.A_AUTH_INVALID_AUTH_API_RESPONSE:o="error.invalid_auth_api_response";break;case _.A_AUTH_JSONIFY_ERROR:o="error.invalid_auth_api_response";break;case _.A_AUTH_FETCH_USER_ERROR:o="error.fetch_user_error";break;case _.C_AUDIO_REVERSED_PHASE_ERROR:o="error.audio_reversed_phase";break;case _.C_AUDIO_MULTI_TRACK_ERROR:o="error.audio_multi_track";break;case _.C_LOCAL_FILE_FETCH_FAILED:o="error.local_file_fetch_failed";break;case _.C_AUDIO_SEND_FAILED:o="error.audio_send_failed";break;case _.C_VREW_FILE_INVALID_FORMAT:o="vrewfile.invalid_format";break;case _.C_VREW_FILE_INCOMPATIBLE_VERSION:case _.D_ERR_VREW_FILE_INCOMPATIBLE_VERSION:o="vrewfile.incompatible_version";break;case _.C_MEDIA_NO_AUDIO_TRACK:o="error.load_failed_audio_track_not_found";break;case _.C_MEDIA_INCOMPATIBLE_AUDIO_CODEC:o="error.load_failed_audio_track_incompatible_codec";break;case _.C_MEDIA_INCOMPATIBLE_VIDEO_CODEC:o="error.load_failed_video_track_incompatible_codec";break;case _.C_TIMECODE_TEXT_TIMECODE_MISMATCH:o="import.timecode_text_error_timecode_mismatch",t.errorArg?.empty&&(o="import.timecode_text_error_empty");break;case _.C_AUDIO_GUID_FETCH_FAILED:o="error.server_connection_error";break;case _.C_AUDIO_RECEIVE_TRANSCRIPT_WAIT_FAILED:o="error.server_error";break;case _.C_AUDIO_RECEIVE_TRANSCRIPT_LONG_AUDIO:o="error.server_error_long_audio";break;case _.C_MEDIA_RELOAD_ERROR:o="error.player_reload_failed";break;case _.C_EXPORT_INPUT_OUTPUT_SAME_FILE:o="error.input_output_same_file";break;case _.C_VREW_FILE_IN_SHARED_FOLDER_READ:o="error.project_file_no_shared_folder_read";break;case _.C_VREW_FILE_IN_SHARED_FOLDER_WRITE:o="error.project_file_no_shared_folder_write";break;case _.C_GLSL_INIT_ERROR:o="error.filter_init_failed";break;case _.C_IMPORT_SHARED_FOLDER_READ:o="error.import_no_shared_folder_read";break;case _.C_MEDIA_INCOMPATIBLE_VIDEO_TYPE:o="error.media_incompatible_video_type";break;case _.C_MEDIA_INCOMPATIBLE_CONTAINER:o="error.media_incompatible_container";break;case _.C_AUDIO_DURATION_EXCEED_LIMIT:o="error.audio_duration_exceed_limit";break;case _.C_INVALID_VREW_EXT_TYPE:o="error.invalid_vrew_ext_type";break;case _.C_APP_VERSION_IS_LOW:o="error.app_version_is_low";break;case _.C_FIREBASE_NETWORK_REQUEST_FAILED:o=TR(fi.NETWORK_REQUEST_FAILED);break;case _.C_EMAIL_RESEND_ERROR:o="error.email_resend_failed";break;case _.C_API_GATEWAY_NETWORK_REQUEST_FAILED:o="error.download_failed";break;case _.C_MEDIA_INCOMPATIBLE_IMAGE:o="error.media_incompatible_image";break;case _.C_SCRIPT_IMPORT_ERROR:o="import.load_script_error";break;case _.C_SUBTITLE_IMPORT_ERROR:o="import.load_subtitle_error";break;case _.C_SUBTITLE_IMPORT_NO_LINE_ERROR:o="import.load_subtitle_no_line_error";break;case _.C_TF_MODEL_LOAD_ERROR:o="error.tf_model_load_error";break;case _.C_SCRIPT_IMPORT_NO_SOURCE_ERROR:o="error.script_import_no_source";break;case _.C_SCRIPT_IMPORT_EMPTY_SCRIPT_ERROR:o="import.load_empty_script";break;case _.C_TTS_GENERAL_ERROR:o="error.tts_general_error";break;case _.C_TTS_NETWORK_ERROR:o="error.tts_network_error";break;case _.C_TTS_FETCH_SPEAKER_LIST_ERROR:case _.C_TTS_AI_VOICE_SEARCH_ERROR:o="error.tts_fetch_speaker_list_error";break;
49case _.C_USER_TTS_GENERAL_ERROR:o="error.user_tts_general_error";break;case _.C_USER_TTS_NETWORK_ERROR:o="error.user_tts_network_error";break;case _.C_VDROP_USER_CANCELED:o="error.vdrop_download_canceled";break;case _.C_VDROP_SESSION_EXPIRED:o="error.vdrop_session_expired";break;case _.C_VDROP_NETWORK_ERROR:o="error.vdrop_download_failed";break;case _.C_CUSTOM_PROJECT_LIST_OPEN_ERROR:o="error.custom_project_list_open_error";break;case _.C_ASSET_VIDEO_TOO_BIG_ERROR:o="error.asset_video_too_big";break;case _.C_GIF_IMPORT_GENERAL_ERROR:o="import.load_gif_error";break;case _.C_DND_ASSET_IMPORT_ERROR:o="import.load_asset_general_error";break;case _.C_HARDCUT_DELTA_ANALYSIS_ERROR:o="error.hardcut_delta_analysis_error";break;case _.C_TTS_API_SERVER_ERROR:case _.C_USER_TTS_API_SERVER_ERROR:o="error.tts_api_server_error";break;case _.D_ERR_DOWNLOAD_FAILED:o="error.download_failed";break;case _.C_DISK_NO_SPACE:case _.D_ERR_NOSPACE:o="error.no_space";break;case _.D_ERR_SOURCE_FILE_LOST:o="error.source_file_lost";break;case _.D_ERR_FFMPEG_MALLOC_FAILED:o="error.ffmpeg_malloc_failed";break;case _.D_ERR_PERMISSION_DENIED:o="error.permission_denied";break;case _.D_ERR_UNLINK_BUSY:o="error.unlink_busy";break;case _.D_ERR_INVALID_CUBE_FORMAT:o="error.invalid_cube_format";break;case _.D_ERR_FILTER_FILE_PARSING_FAILED:o="export.export_error_filter_init";break;case _.D_ERR_LIBASS_CRASH:o="export.export_error_libass_crash";break;case _.D_ERR_MEDIA_INVALID_DATA:o="error.media_invalid_data";break;case _.D_ERR_NOSPACE_TARGET_DISK:o="error.no_space_target_disk";break;case _.D_ERR_VREW_BANNED_SUSPICIOUS:o="error.vrew_banned_suspicious";break;case _.D_ERR_HWACCEL_DRIVER_VERSION_LOW:o="error.hwaccel_driver_version_low";break;case _.D_ERR_FFMPEG_MEDIA_INCOMPATIBLE:o="error.media_incompatible";break;case _.C_IMAGE_GENERATION_ERROR:case _.C_IMAGE_GENERATION_NETWORK_ERROR:case _.C_PROMPT_GENERATION_ERROR:o="error.image_generation_error";break;case _.C_PDF_IMPORT_ERROR:case _.C_PDF_RENDER_TIMEOUT:o="error.pdf_import_error";break;case _.C_INVALID_PDF_ERROR:o="error.invalid_pdf_error";break;case _.C_LOGIN_REQUIRED_ERROR:o="error.login_required_feature";break;case _.C_EMAIL_VERIFY_REQUIRED_ERROR:o="error.login_verify_required";break;case _.C_PAYMENT_GENERAL_ERRROR:o="error.payment_general_error";break;case _.C_PAYMENT_RESCHEDULE_ERROR:o="error.payment_reschedule_error";break;case _.C_PAYMENT_UNSUBSCRIBE_ERROR:o="error.payment_unsubscribe_error";break;case _.C_AI_STYLIZED_CAPTION_PREPARE_IMAGE_FAILED:o="error.ai_stylized_caption_prepare_image_failed";break;case _.C_AI_STYLIZED_CAPTION_UPLOAD_IMAGE_FAILED:o="error.ai_stylized_caption_upload_image_failed";break;case _.C_AI_STYLIZED_CAPTION_START_JOB_FAILED:o="error.ai_stylized_caption_start_job_failed";break;case _.C_AI_STYLIZED_CAPTION_CREDIT_CHECK_FAILED:o="error.ai_stylized_caption_credit_check_failed";break;case _.C_AI_STYLIZED_CAPTION_GENERATION_FAILED:o="error.ai_stylized_caption_generation_failed";break;case _.C_AI_STYLIZED_CAPTION_LOAD_RESULT_FAILED:o="error.ai_stylized_caption_load_result_failed";break;case _.C_AI_STYLIZED_CAPTION_LOAD_PRICING_FAILED:o="error.ai_stylized_caption_load_pricing_failed";break;case _.C_AI_STYLIZED_CAPTION_PERMISSION_DENIED:o="error.ai_stylized_caption_permission_denied";break;case _.C_AI_STYLIZED_CAPTION_TEMPORARY_FAILED:o="error.ai_stylized_caption_temporary_failed";break;case _.C_AI_STYLIZED_CAPTION_SERVICE_UNAVAILABLE:o="error.ai_stylized_caption_service_unavailable";break;case _.C_PAYMENT_DUPLICATE_ERROR:o="error.payment_duplicate_error";break;case _.C_PAYMENT_NETWORK_ERROR:o="error.payment_network_error";break;case _.C_PAYMENT_AUTHORIZATION_ERROR:o="error.payment_authorization_error";break;case _.C_PAYMENT_INCONSISTENCY_ERROR:o="error.payment_inconsistency_error";break;case _.C_PAYMENT_DB_ERROR:o="error.payment_db_error";break;case _.C_PAYMENT_EXPIRED_ERROR:o="error.payment_expired_error";break;case _.C_TTS_WEMAKEVOICE_ERROR:o="error.wemakevoice_server_error";break;case _.C_VIDEO_REMIX_GENERATE_SUMMARY_FAILED:o="error.generate_summary_failed";break;case _.C_GENERATE_SUMMARY_INVALID_RESULT:o="error.generate_summary_invalid_result";break;case _.C_EXTRACT_HIGHLIGHT_FALIED:o="error.create_highlight_failed";break;case _.C_VIDEO_ASSET_LOST:o="error.export_video_asset_lost";break;case _.C_CHARACTER_ASSET_LOST:o="error.export_character_asset_lost";break;case _.C_DEVICE_TOO_MANY_FREE_ACCOUNT:o="error.device_too_many_free_accounts";break;
49case _.C_CHARACTER_STUDIO_GENERAL_ERROR:o="error.character_studio_general_error";break;case _.C_RAY_DIFFUSION_SERVER_WAITING:o="error.ray_diffusion_server_waiting";break;case _.C_IMAGE_DOWNLOAD_ERROR:o="error.download_image_failed";break;case _.C_NSFW_CONTENT_DETECTED:o="error.nsfw_content_detected";break;case _.C_TTV_EMPTY_ASSET_CLIP_EXISTS:o="error.ttv_empty_asset_clip_exists";break;case _.C_API_AUTH_FAILED:o="error.api_auth_failed";break;case _.C_USER_TTS_SAMPLE_VOICE_ERROR:o="error.user_tts_sample_voice_error";break;case _.C_TTV_GENERAL_ERROR:case _.C_TTV_TTS_STATE_NOT_EXISTS:o="error.ttv_general_error";break;case _.C_UNSPECIFIED_ERROR:o="error.unspecified_error";break;case _.C_ASSET_IMPORT_GENERAL_ERROR:o="error.asset_import_general_error";break;case _.C_MEDIAINFO_NOT_EXIST:o="error.mediaInfo_not_exist";break;case _.C_OAUTH_PASSWORD_RESET_NOT_ALLOWED:o="error.unable_to_sign_in_with_email";break;case _.C_STOCK_NETWORK_ERROR:o="error.stock_network_error";break;case _.C_IMAGE_GENERATION_PREPARE_ERROR:o="error.image_generation_prepare_error";break;case _.C_VIDEO_GENERATION_PREPARE_ERROR:o="error.video_generation_prepare_error";break;case _.C_NETWORK_REQUEST_FAILED:o="error.no_network";break;case _.C_TTV_IMAGE_GENERATION_FAILED:o="error.ttv_image_generation_failed";break;case _.C_TTV_PLAN_POLLING_TIMEOUT:case _.C_TTV_PLAN_GENERATION_ERROR:o="error.ttv_prompt_generation_failed";break;case _.C_TTS_VOCAL_DICTIONARY_FETCH_ERROR:o="error.tts_vocal_dictionary_fetch_error";break;case _.C_REQUEST_QUOTA_EXCEEDED_ERROR:o="error.request_quota_exceeded_error";break;case _.A_AUTH_INSUFFICIENT_CREDIT:o="error.request_quota_exceeded_error";break;case _.C_VCLOUD_SESSION_CONFLICT:o="error.vcloud_session_conflict";break;case _.C_PROXY_CONVERT_FAILED:o="error.failed_to_convert";break;case _.D_ERR_PROXY_DIR_INIT_FAILED:o="error.proxy_dir_init_failed";break;case _.C_VIDEO_GENERATION_ERROR:case _.C_VIDEO_GENERATION_NETWORK_ERROR:o="error.video_generation_error";break;case _.C_VIDEO_CONTENT_FILTERED:o="error.video_content_filtered";break;case _.C_VIDEO_CONTENT_FILTERED_PERSON:o="error.video_content_filtered_person";break;case _.C_VIDEO_INSERT_FAILED:o="error.video_insert_failed";break;case _.A_AUTH_AUTH_TOKEN_ERROR:o="error.auth_token_error";break;case _.C_ATV_GENERAL_ERROR:case _.C_ATV_GENERATE_PROMPT_ERROR:case _.C_ATV_IMPORT_FILE_ERROR:o="atv.general_error";break;case _.C_ATV_UPLOAD_ERROR:o="atv.upload_error";break;case _.C_ATV_GENERATE_SCRIPT_ERROR:o="atv.generate_script_error";break;case _.C_ATV_CREATE_CLIP_ERROR:case _.C_ATV_SPLIT_CLIP_ERROR:o="atv.create_clip_error";break;case _.C_AGENT_GENERAL_ERROR:o="vrew_agent.general_error";break;case _.C_AGENT_SERVER_MAINTENANCE:o="vrew_agent.server_maintenance";break;case _.C_AGENT_CLIENT_VERSION_DEPRECATED:o="vrew_agent.client_version_deprecated";break;case _.C_AGENT_SERVER_UNAVAILABLE:o="vrew_agent.server_unavailable";break;case _.C_AGENT_SESSION_NOT_FOUND:case _.C_AGENT_INIT_SESSION_FAILED:o="vrew_agent.error_restart_chat";break;case _.C_AGENT_API_SERVER_ERROR:case _.C_AGENT_UNSUPPORTED_MODEL:o="vrew_agent.error_try_again";break;case _.C_VCLOUD_PROJECT_TOO_LARGE:o="error.vcloud_project_too_large";break;case _.C_REFERENCE_IMAGE_IMPORT_FAILED:o="genimage_engine.reference_images_import_failed";break;case _.C_REFERENCE_IMAGE_UPLOAD_FAILED:o="genimage_engine.reference_image_upload_failed";break;case _.C_VIDEO_REFERENCE_UPLOAD_FAILED:o="genimage_engine.video_attachment_failed";break;case _.C_CAPTION_CORRECTION_ERROR:o="caption_correction.error_default";break}const r=Mte(t.errorArg?.absoluteClipIndex,e),n=t.excludeErrorCode?"":Lte(e,t.subErrorCode),a=t.errorArg?.errorPointMsg?t.errorArg.errorPointMsg+`
50`:r?r+`
51`:"",i=A(o??t.defaultKey,{...t.errorArg,interpolation:{escapeValue:!1}}),s=n||a?`
52`+i:i,x=t.errorDescKey?`
53
54`+A(t.errorDescKey):"";return n+a+s+x},TR=e=>{let t;switch(e){case fi.INVALID_EMAIL:t="error.firebase_invalid_email";break;case fi.EMAIL_NOT_FOUND:case fi.USER_NOT_FOUND:t="error.firebase_user_not_found";break;case fi.TOO_MANY_REQUESTS:t="error.firebase_too_many_requests";break;case fi.INVALID_PASSWORD:t="error.firebase_wrong_password";break;case fi.EMAIL_EXISTS:t="error.firebase_email_already_exists";break;case fi.NETWORK_REQUEST_FAILED:t="error.firebase_network_request_failed";break;case fi.TOO_MANY_ATTEMPTS_TRY_LATER:t="error.firebase_restapi_too_many_attempts_try_later";break;case fi.OPERATION_NOT_ALLOWED:t="error.firebase_operation_not_allowed";break;case fi.INVALID_IDP_RESPONSE:t="error.firebase_invalid_idp_response";break;case _.C_VDROP_FILE_SIZE_LIMIT_EXCEEDED:t="error.vdrop_file_size_limit_exceeded";break}return A(t||"error.firebase_general_error")},sqe=e=>Object.values(_).includes(e)?e:void 0,xqe=async(e,t)=>{try{return await be().fetchSignUpProviderIdFromDatabase(e)===vJ?A("error.unable_to_sign_in_with_email"):TR(t)}catch(o){return(await Dy("fetchSignUpProviderIdFromDatabase",o))?.dis
54playMessage}},Dte=e=>{const t={};for(const[o,r]of Object.entries(e))r!==null&&typeof r=="object"&&!Array.isArray(r)?Object.assign(t,r):t[o]=r;return t},kte=(e,t)=>e.reduce((o,r,n)=>(t(r)&&o.push(n),o),[]),X1=e=>{if(e.length<=1)return!0;for(let t=1;t<e.length;t++)if(e[t]!==e[t-1]+1)return!1;return!0},J1=(e,t)=>[...e].sort((o,r)=>o-r),Se=e=>e!==void 0,gm=(e,t,o)=>o.indexOf(e)===t,ri=e=>e!==null,yy=e=>e!=null,Fte=e=>!!e,cqe=(e,t)=>e.length>t.length?e.map((o,r)=>[e[r],t[r]]):t.map((o,r)=>[e[r],t[r]]),Ute=(e,t)=>{for(let o=e.length-1;o>=0;o--)if(t(e[o]))return o;return-1},Vte="search",Gte=()=>{const e=window.location.search,t=e.match(gte);if(t)return t[1]===Vte?Ete:t[1];const o=e.match(_te);return o?o[1]:""},vy=()=>{const e=window.location.search,t=new URLSearchParams(e),o={utm_source:"",utm_medium:"",utm_campaign:""};let r=!1;if(t.forEach((n,a)=>{$C.includes(a)&&(r=!0,o[a]=n)}),r)return o};class Wte{downloadUrl;constructor(){this.downloadUrl=void 0,this.initializeSignInListener(),this.initializeSignUpListener(),this.requestAuthTokenIfSignUpRedirected()}openUrl(t,o){try{return window.open(t),Promise.resolve()}catch{const n=new C(_.C_FAILED_TO_OPEN_URL,void 0,"Failed to open URL");return o?o(n,t):sz(n,t),Promise.resolve()}}openWindow=async(t,o,r)=>{sessionStorage.setItem(Wt.OPEN_LAST_FILE_KEY,String(r)),window.open(window.location.href,"_blank")};getOpenLastFile=()=>{const t=sessionStorage.getItem(Wt.OPEN_LAST_FILE_KEY);return sessionStorage.removeItem(Wt.OPEN_LAST_FILE_KEY),Promise.resolve(t==null?!0:t==="true")};closeWindowByUser=()=>Promise.reject();disagreeLicense=()=>{};addCloseHandler=()=>{};removeCloseHandler=()=>{};isUpdateReady=()=>Promise.resolve(!1);getUpdateProgress=async()=>({status:"unsupported",percent:0});requestRestart=async()=>(window.location.reload(),!0);getCidContext=async()=>Promise.resolve(void 0);storeCidContext=async t=>Promise.resolve();getDeviceInfo=async()=>{const t=await zo();return{deviceId:"try_"+t,deviceName:"try_"+t,machineId:("try_"+t).slice(0,8)}};getSystemInfo=async t=>
54{const o=await this.getSystemSummary(t);return{cpu:{brand:"not available",manufacturer:"not available",speedInGHz:0},mem:{totalInBytes:0,usedInBytes:0},gpu:{gpus:[]},fs:{fileSystems:[]},os:{platform:"not available",distro:"not available",release:"not available",arch:"not available"},summary:o}};getSystemSummary=async t=>{const o=await bX();h("browser.ts").debug("highEntropyValues: "+JSON.stringify(o)+`,
55      navigator.userAgent: `+navigator.userAgent+`,
56      `);let r="";o&&(r+="from high entropy values: "+o.architecture+"-"+o.bitness),navigator.userAgent&&(r+=`
57        from navigator.userAgent: `,/arm/i.test(navigator.userAgent)?r+="arm":/aarch64/i.test(navigator.userAgent)?r+="arm64":/win64|x86_64|wow64|amd64/i.test(navigator.userAgent)?r+="x86-64":r+="unknown"),r+=", hardwareConcurrency: "+navigator.hardwareConcurrency;let n="";const a=navigator.deviceMemory??"unknown size";n+="device memory(estimated): "+a+"GB";const i=performance.memory?.jsHeapSizeLimit??0;n+=", heap: "+i/1024/1024+"MB";let s="";try{const E=await navigator.gpu?.requestAdapter?.();if(E){const O=E.info?E.info.vendor+" "+E.info.architecture+", fallback: "+E.info.isFallbackAdapter:"unknown",{maxBindGroups:S,maxBindingsPerBindGroup:R,maxBindGroupsPlusVertexBuffers:y,maxBufferSize:v,maxTextureDimension2D:w,maxTextureArrayLayers:N,maxComputeInvocationsPerWorkgroup:M,maxComputeWorkgroupStorageSize:k,maxColorAttachments:F}=E.limits;s+=`
58          webgpu status: `+O+`
59          details:
60            maxBindGroups: `+S+`
61            maxBindingsPerBindGroup: `+R+`
62            maxBindGroupsPlusVertexBuffers: `+y+`
63            maxBufferSize: `+v+`
64            maxTextureDimension2D: `+w+`
65            maxTextureArrayLayers: `+N+`
66            maxComputeInvocationsPerWorkgroup: `+M+`
67            maxComputeWorkgroupStorageSize: `+k+`
68            maxColorAttachments: `+F+`
69        `}else s+=`
70          no webgpu adapter
71        `;const T=(O,S)=>{const R=document.createElement("canvas"),y=R.getContext(O),v=y?.getExtension("WEBGL_debug_renderer_info");if(y&&v){const w=y.getParameter(v.UNMASKED_VENDOR_WEBGL),N=y.getParameter(v.UNMASKED_RENDERER_WEBGL);s+="  "+S+" vendor: "+w+"("+v.UNMASKED_VENDOR_WEBGL+"), "+S+" renderer: "+N+"("+v.UNMASKED_RENDERER_WEBGL+")"}else s+="  no "+S+" context";try{const w=R.getContext(O,{failIfMajorPerformanceCaveat:!0});s+="  "+S+" failIfMajorPerformanceCaveat: "+(w?"ok":"blocked")+`
72        `}catch(w){s+="  "+S+" fails to get context with failIfMajorPerformanceCaveat: "+P(w)+`
73        `}};T("webgl","gl"),T("webgl2","gl2")}catch(E){s+="Error occurred while getting webgpu status: "+P(E)}const{quota:x,usage:c,remaining:l}=await Ib.estimate(),d=await Ib.isPersistent(),u=(c/x*100).toFixed(2),p="[OPFS] "+u+"% ("+jr(l)+" free), persistent: "+d;let f="";return o&&(f+="[HE]",o.platform&&(f+=" Platform: "+o.platform+" "+o.platformVersion+" (mobile: "+o.mobile+")"),o.brands&&(f+=(o.platform?", ":"")+"Brands: "+o.brands.map(E=>E.brand+" "+E.version).join(", ")+" ")),f+="[RDD] "+bx()+" "+iU(),Promise.resolve({cpu:r,mem:n,gpu:s,fs:p,totalMem:"",usedMem:"",os:f})};getFsInfo=async()=>Promise.resolve(void 0);getDiskInfoForPath=async()=>Promise.resolve(void 0);getDownloadUrl=async()=>(this.downloadUrl===void 0&&(this.downloadUrl=(await wOe(!1,!1)).url),this.downloadUrl);sendSignInEvent=()=>{};sendSignOutEvent=()=>{};windowInitialized=async()=>{const t=vy();if(t){const o=JSON.stringify(t);du.set(Ci.UTM_PARAMETERS_KEY,o)}};showInspect=()=>{};updateIconProgressBar=()=>{};isM1Arch=()=>!1;isInstalledInApplicationsOnMac=()=>!1;attachVrewSaveLogs=()=>Promise.resolve();hasDebugFlag=()=>!1;deprecatedClose=()=>{window.close(),window.setTimeout(()=>{document.visibilityState!=="hidden"&&(h("browser.ts").warn("window.close() was blocked while closing deprecated UT browser build."),document.title="Vrew user test build expired",document.body.replaceChildren(Hte()))},100)};getInstallCode=()=>{const t=du.get(Ci.INSTALL_CODE);if(t)return t;const o=Gte();return o?(du.set(Ci.INSTALL_CODE,o),o):""};getProjectOpenHistory=()=>Promise.resolve([]);setProjectOpenHistory=t=>Promise.resolve();bringToFront=()=>Promise.resolve();
73getSupportedImageFiles=()=>sg;getSupportedImageMimeTypes=()=>["jpeg","png","bmp"];getFcpxVersion=async()=>Promise.resolve("");getPrevLogFiles=async()=>{const t=h("browser.ts");if(!(t instanceof LX))return[];const o=Ht("logs"),r=await o.readDir("","file");return(await Promise.all(r.map(async i=>{const s=await o.readFile(i),x=await s?.getFile();return{fileName:i,mtime:x?.lastModified||0,blob:x}}))).sort((i,s)=>i.mtime-s.mtime).slice(-3).filter(i=>i.fileName!==t.currentLogFile()).map(i=>({name:i.fileName,blob:i.blob}))};getWindowId=()=>1;getWindowCount=()=>1;setUpdatePolicy=t=>Promise.resolve();getUpdatePolicy=()=>Promise.resolve(MX);getUpdatePolicyChanged=()=>!1;isDeprecatedOS=()=>!1;triggerDeeplinkListener=()=>Promise.resolve();initializeSignInListener=()=>{window.addEventListener("message",async t=>{if(V_.level!==Xr.Local&&t.origin!==window.location.origin||t.data.host!==hte||!t.data.params)return;h("browser.ts").info("[BrowserFrame] Received oauthSignIn event.");const o=JSON.parse(decodeURIComponent(escape(atob(t.data.params))));await ky(o.credential,o.credentialType,o.providerId,o.installCode,o.deeplinkAction,o.signUp,o.webCid,o.gclid)})};initializeSignUpListener=()=>{window.addEventListener("message",async t=>{if(V_.level!==Xr.Local&&t.origin!==window.location.origin||t.data.host!==mte||!t.data.params)return;h("browser.ts").info("[BrowserFrame] signUp event received: "+t.data.params);const o=JSON.parse(decodeURIComponent(escape(atob(t.data.params))));await Fy(o.sessionId,o.uid,o.installCode,o.webCid,o.gclid)})};requestAuthTokenIfSignUpRedirected=()=>{const t=new URLSearchParams(window.location.search),o=t.has(lL);let r;try{r=window.opener?.location?.origin}catch{r=void 0}if(o&&(r===window.location.origin||V_.level===Xr.Local)){h("browser.ts").info("[BrowserFrame] opener found. request auth token.");const n=new URL(window.location.href);n.searchParams.delete(lL),window.history.replaceState(null,"",n.toString()),window.opener.postMessage({message:Ite},V_.level===Xr.Local?"*":window.location.origin)}};getZoomLevel=async()=>Promise.resolve(void 0)}const Hte=()=>{const e=document.createElement("div");e.style.display="flex",e.style.minHeight="100vh",e.style.alignItems="center",e.style.justifyContent="center",e.style.background="#f7f8fa",e.style.color="#2b2b2b",e.style.fontFamily='Pretendard, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif',e.style.textAlign="center",e.style.padding="24px";const t=document.createElement("div");t.style.maxWidth="420px";const o=document.createElement("h1");o.textContent="User test build expired",o.style.margin="0 0 12px",o.style.fontSize="20px",o.style.fontWeight="700";const r=document.createElement("p");return r.textContent="This Vrew user test build is no longer available. Please use the latest build.",r.style.margin="0",r.style.fontSize="14px",r.style.lineHeight="1.6",t.append(o,r),e.append(t),e};var Ts=(e=>(e[e.OK=0]="OK",e[e.CANCEL=1]="CANCEL",e))(Ts||{});const yc=[],jte=new Date().getTime()/1e3,zte=1e3*60,Yte=4,q1=async e=>{try{const t=e.getHeapStatistics?.(),o=await e.getProcessMemoryInfo?.(),r=e.getSystemMemoryInfo?.(),n=e.getBlinkMemoryInfo?.();if(t&&o&&r)return"heapTotal: "+jr(t?.totalHeapSize*1024)+", heapUsed: "+jr(t?.usedHeapSize*1024)+", (sysTotal: "+jr(r?.total*1024)+", sysFree: "+jr(r?.free*1024)+", private "+jr(o?.private*1024)+", shared "+jr(o?.shared*1024)+", malloced "+jr(t?.mallocedMemory*1024)+", peakMalloced "+jr(t?.peakMallocedMemory*1024)+", blinkAlloc "+jr(n?.allocated*1024)+", blinkMarked "+jr(n?.marked*1024)+", blinkTotal "+jr(n?.total*1024)+")"}catch(t){h("diagnostic.ts").error("Cannot retrieve memory stat : "+P(t))}},lqe=()=>{at()===!1||!window.process||setInterval(async()=>{const e=await q1(window.process);e&&(yc.length>=Yte?(h("diagnostic.ts").info("[MEMORY] "+e),yc.splice(0,yc.length)):yc.push(e))},zte)},dqe=async()=>{if(at()===!1||!window.process)return;const e=h("diagnostic.ts"),t=await q1(window.process),o=["[MEMORY] Last "+(yc.length+1)+" memory stats :",...yc,t].filter(Se).join(vu);e.info(o),yc.splice(0,yc.length)},Bte=()=>new Date().getTime()/1e3-jte;var Kte=(e=>(e.USER_CLOSE="user_close",e.AGREEMENT_DISAGREE="agreement_disagree",e.AUTO_UPDATE="auto_update",e.CONFIG_
73CHANGED="config_chagned",e.UT_BINARY_DEPRECATED="ut_binary_deprecated",e))(Kte||{});class Xte{closeHandlers=[];updatingQuitRequested;relaunchRequested;isDarwinM1Arch;isInstalledInApplicationsOnMacOs;systemInfoRet;startWithDebugFlag;installCode;updateReady;windowId;windowCount;updatePolicyChanged;isDeprecatedOSVersion;openUrlCount=0;openUrlFirstClickTime=0;constructor(){this.monitorClose(),this.updatingQuitRequested=!1,this.relaunchRequested=!1,this.isDarwinM1Arch=!1,this.isInstalledInApplicationsOnMacOs=!1,this.startWithDebugFlag=!1,this.installCode="",this.updateReady=!1,this.windowId=0,this.windowCount=0,this.updatePolicyChanged=!1,this.isDeprecatedOSVersion=!1,this.initializeSignOutListener(),this.initializeSignInListener(),this.initializeSignUpListener(),this.initializeWindowCountChangedListener(),this.initializeOpenModalListener()}async openUrl(t,o){const a=Date.now();this.openUrlCount===0||a>this.openUrlFirstClickTime+2e3?(this.openUrlCount=1,this.openUrlFirstClickTime=a):(this.openUrlCount++,this.openUrlCount>=3&&(this.openUrlCount=0,Y().info(A("common.open_url_alert"))));try{return await(await ae())("electron.openUrl",{url:t}),Promise.resolve()}catch{const s=new C(_.D_FAILED_TO_OPEN_URL,void 0,"Failed to open URL");return o?o(s,t):sz(s,t),Promise.resolve()}}openWindow=async(t,o,r)=>(await ae())("electron.openWindow",{vrewfilePath:t,restoreFile:o,openLastFile:r});getOpenLastFile=async()=>(await(await ae())("electron.getWindowConfig")).openLastFile??!0;disagreeLicense=()=>this.closeWindow("agreement_disagree");addCloseHandler=t=>{!this.closeHandlers.includes(t)&&this.closeHandlers.push(t)};removeCloseHandler=t=>{const o=this.closeHandlers.indexOf(t);o>=0&&this.closeHandlers.splice(o,1)};isUpdateReady=async()=>this.updateReady?!0:(this.updateReady=await(await ae())("isUpdateReady"),this.updateReady);getUpdateProgress=async()=>(await ae())("getUpdateProgress");requestRestart=async(t,o)=>(o?P0.DONT_SAVE:await Ch(t?"UPDATE":"CONFIG_CHANGED"))===P0.CANCEL?!1:(t?(this.updatingQuitRequested=!0,await(await ae())("quitAndInstallUpdate")):(this.relaunchRequested=!0,await(await ae())("quitandRestart")),!0);getCidContext=async()=>(await ae())("electron.getCidContext");storeCidContext=async t=>(await ae())("electron.storeCidContext",t);getDeviceInfo=async()=>({...await(await ae())("electron.getDeviceInfo")});getSystemInfo=async t=>{if(this.systemInfoRet&&(t===void 0||!t))return this.systemInfoRet;const o=await(await ae())("electron.getSystemInfo",{needRefresh:t});return this.systemInfoRet=o,o};getSystemSummary=async t=>
73(await this.getSystemInfo(t)).summary;getFsInfo=async()=>await(await ae())("electron.getFsInfo");getDiskInfoForPath=async t=>(await ae())("electron.getDiskInfoForPath",{targetPath:t});getDownloadUrl=()=>Promise.resolve("");initializeSignInListener=async()=>{const t=(r,n,a,i)=>{if(a||!i){h("local.ts").error("receiving signIn event with error :"+JSON.stringify(a)+" or no result from other window.");return}h("local.ts").info("receiving signIn event from other window."),be().autoLogin()};(await ae())("electron.signInBroadcast",void 0,void 0,void 0,{silentArg:!0,listenOnly:!0,customListener:t});const o=async(r,n,a,i)=>{if(a||!i){h("local.ts").error("receiving oauthSignIn event with error :"+JSON.stringify(a)+" or no result from other window.");return}this.moveWindowToTop(),this.installCode=i.installCode,h("local.ts").info("[LocalFrame] Received oauthSignIn event."),await ky(i.credential,i.credentialType,i.providerId,i.installCode,i.deeplinkAction,i.signUp,i.webCid,i.gclid)};(await ae())("electron.oauthSignIn",void 0,void 0,void 0,{silentArg:!0,listenOnly:!0,customListener:o})};initializeSignOutListener=async()=>{const t=async(o,r,n,a)=>{h("local.ts").info("receiveing sign out event.."),be().signOut(!1)};(await ae())("electron.signOutBroadcast",void 0,void 0,void 0,{silentArg:!0,listenOnly:!0,customListener:t})};initializeSignUpListener=async()=>{const t=async(o,r,n,a)=>{if(n||!a){const d="receiving signUp event with error :"+JSON.stringify(n)+".";h("local.ts").error(d);return}const{uid:i,installCode:s,webCid:x,sessionId:c,gclid:l}=a;h("local.ts").info("receiving signUp event with uid :"+i+", installCode : "+s+", webCid : "+x),this.moveWindowToTop(),this.installCode=s,await Fy(c,i,s,x,l)};(await ae())("electron.signUp",void 0,void 0,void 0,{listenOnly:!0,customListener:t})};initializeOpenModalListener=async()=>{const t=async(o,r,n,a)=>{if(n||!a){h("local.ts").error("receiving openModal event with error: "+JSON.stringify(n));return}h("local.ts").info("[LocalFrame] Received openModal deep link: "+a.modal),a.modal==="feedback"&&(this.moveWindowToTop(),Y().openModal(st.FEEDBACK,{openD
73ataTransferDirectly:!0}))};(await ae())("electron.openModal",void 0,void 0,void 0,{listenOnly:!0,customListener:t})};initializeWindowCountChangedListener=async()=>{const t=h("local.ts"),o=(r,n,a,i)=>{if(a||!i){t.error("windowCountChanged error:"+JSON.stringify(a)+" or no result from other window.");return}t.info("windowCount changed: "+i.windowCount),this.windowCount=i.windowCount};(await ae())("electron.windowCountChanged",void 0,void 0,void 0,{silentArg:!0,listenOnly:!0,customListener:o})};sendSignInEvent=async()=>{h("local.ts").info("sending signIn event to other windows."),(await ae())("electron.signIn",void 0,void 0,void 0,{silentArg:!0})};sendSignOutEvent=async()=>{h("local.ts").info("sending signOut event to other windows."),(await ae())("electron.signOut")};windowInitialized=async()=>{const t=h("local.ts");t.info("initialize window creation");const o=await(await ae())("electron.windowInitialized");this.isDarwinM1Arch=o.isM1Arch,this.isInstalledInApplicationsOnMacOs=o.isInstalledInApplicationsOnMac,this.startWithDebugFlag=o.hasDebugFlag,this.installCode=o.installCode,this.windowId=o.windowId,this.windowCount=o.windowCount,this.isDeprecatedOSVersion=o.isDeprecatedOS,this.installCode&&t.info("install code : "+this.installCode),t.info("windowId: "+this.windowId+", windowCount: "+this.windowCount)};showInspect=async()=>(h("local.ts").info("show inspect tool."),(await ae())("electron.showInspect"));moveWindowToTop=async()=>(h("local.ts").info("move window to top."),(await ae())("electron.moveWindowToTop"));updateIconProgressBar=async t=>{(await ae())("electron.updateIconProgressBar",{progressValue:t})};isM1Arch=()=>this.isDarwinM1Arch;isInstalledInApplicationsOnMac=()=>this.isInstalledInApplicationsOnMacOs;attachVrewSaveLogs=async()=>(await ae())("electron.attachVrewSaveLogs");getInstallCode=()=>this.installCode;monitorClose=async()=>{for(;;){if(await this.waitUntilClosing(),await I().flush(),this.updatingQuitRequested){this.closeWindow("auto_update");break}if(this.relaunchRequested){this.closeWindow("config_chagned");break}if(await this.executeCloseHandlers()!==!1){this.closeWindow("user_close");break}}};waitUntilClosing=async()=>(await ae())("electron.waitUntilClosing");closeWindow=async t=>(h("local.ts").info("Uptime at close : "+os(Bte())),(await ae())("electron.closeWindow",{reason:t}));closeWindowByUser=async()=>await this.executeCloseHandlers()===!1?!1:(this.closeWindow("user_close"),!0);executeCloseHandlers=async()=>{for(const o of this.closeHandlers.slice().reverse())if(await o()===Ts.CANCEL)return!1;const t=await Ch("USER_CLOSE");return await I().flush(),t!==P0.CANCEL};hasDebugFlag=()=>this.startWithDebugFlag;deprecatedClose=()=>this.closeWindow("ut_binary_deprecated");getProjectOpenHistory=async()=>(await ae())("electron.getLocalProjectHistory");setProjectOpenHistory=async t=>(await ae())("electron.setLocalProjectHistory",{projectOpenHistoryLogs:t},void 0,void 0,{silentArg:!0});bringToFront=async()=>(await ae())("electron.bringToFront");getSupportedImageFiles=()=>[...sg,"gif"];getSupportedImageMimeTypes=()=>["jpeg","png","bmp","gif"];getFcpxVersion=async()=>Mr()?(await ae())("electron.getFcpxVersion"):"";getPrevLogFiles=async()=>(await(await ae())("electron.getPrevLogFiles")).map(o=>({name:o}));getWindowId=()=>this.windowId;getWindowCount=()=>this.windowCount;setUpdatePolicy=async t=>(this.updatePolicyChanged=!0,(await ae())("electron.setUpdatePolicy",{updatePolicy:t}));getUpdatePolicy=async()=>(await ae())("electron.getUpdatePolicy");getUpdatePolicyChanged=()=>this.updatePolicyChanged;isDeprecatedOS=()=>this.isDeprecatedOSVersion;triggerDeeplinkListener=async()=>(h("local.ts").info("triggerDeeplinkListener"),(await ae())("electron.triggerDeeplinkListener"));getZoomLevel=async()=>{try{return(await ae())("electron.getZoomLevel")}catch{return}}}const qs={needSave:!1,title:"",status:"none"},Jte="e-",qte="w-",Q1=()=>qs.title,hx=e=>{const{needSave:t,status:o,title:r}=e;if(t!==void 0&&(qs.needSave=t),r&&(qs.title=r),!qs.title)return;o&&o!==qs.status&&o!=="offline"&&(qs.status=o);const n={saved:A("frameStatus.saved_to_cloud"),saving:A("frameStatus.saving_to_cloud"),offline:A("frameStatus.offline"),device:A("frameStatus.saved_to_device")}[o??qs.status],a="●",i=qs.needSave?a+" "+qs.title:qs.title,s=Ba().VREW_UT,x=fr.level===Xr.Release?void 0:fr.level,c=fr.level===Xr.Release?void 0:new Date(QA).toLocaleStr
73ing(),l=["Vrew",x,Ha(),s,c].filter(d=>d).join(" ");h("frame.ts").info("title "+i+" ("+l+") "+(n?"- "+n:"")+". status: "+o+" and lastStatus: "+qs.status),window.document.title=i+" ("+l+") "+(n?"- "+n:"")};let ZS;const pt=()=>(!ZS&&(ZS=new(at()?Xte:Wte)),ZS),Qte=new Date(0).toISOString();let di;const Zte=async e=>{if(e&&at()){const a=await pt().getCidContext();return h("frame.ts").info("Stored cid context "+JSON.stringify(a)),a}if(window.localStorage===void 0)return;const t=window.localStorage.getItem(Ci.CID_NAME),o=window.localStorage.getItem(Ci.CID_TIMESTAMP),r=window.localStorage.getItem(Ci.WEB_CID);if(t===null)return;const n={cid:t,timestamp:o??void 0,webCid:r??void 0};return h("frame.ts").info("Stored cid context "+JSON.stringify(n)),n},SR=async(e,t,o,r)=>{e&&at()?await pt().storeCidContext({cid:t,timestamp:o,webCid:r}):window.localStorage!==void 0&&(window.localStorage.setItem(Ci.CID_NAME,t),window.localStorage.setItem(Ci.CID_TIMESTAMP,o),r&&window.localStorage.setItem(Ci.WEB_CID,r))},_g=async()=>{if(di)return di;const e=await Zte(Ps());if(di)return di;if(e===void 0){const t=dy.v4(),o=at()?Jte:qte;di={cid:""+o+t.slice(o.length),timestamp:new Date().toISOString(),isNewUser:!0,webCid:void 0},await SR(Ps(),di.cid,di.timestamp,di.webCid)}else if(e.timestamp===void 0)di={cid:e.cid,timestamp:Qte,isNewUser:!1,webCid:e.webCid},await SR(Ps(),di.cid,di.timestamp,di.webCid);else{const t=XCe(e.timestamp),o=3600*24,r=t<o;di={cid:e.cid,timestamp:e.timestamp,isNewUser:r,webCid:e.webCid}}return di},$te=e=>{const t=/\[linux\] (.+)/i,o=/(Windows \d+\.?\d*)/,r=/\[darwin\] (.+)/,n=e.match(o)||e.match(r)||e.match(t);return n?n[1]:null},eoe=e=>{const t=[],o=e.match(/\[HE\] Platform: (.*?)(?=\s*Brands|$)/),r=e.match(/Brands: (.*?)(?=\s*\[RDD\]|$)/),n=o?.[1].trim(),a=r?.[1].trim();if(n||a){const x=[n,a].filter(yy).join(", ");t.push("[HE]: "+x)}const i=e.match(/\[RDD\](.*)/),s=i?.[1].trim();return s&&s!=="Unknown"&&(n||a?t.push("[RDD]: "+s):t.push(s)),t.join(" ")},toe=(e,t)=>{const o=eoe(e);if(o)return""+o+(t?" (m1)":"");const r=$te(e);return r?""+r+(t?" (m1)":""):""+e+(t?" (m1)":"")},ooe=2e3,roe=6e4,zh=e=>{switch(e){case"ready":return"ready";case"not-started":case"checking":case"downloading":return"preparing";default:return pt().isDeprecatedOS()?"legacyOs":"manual"}},noe=async()=>{const e=Mo(),t=e.getDebugVal(Xt.UPDATE_STATUS);return t?{status:t,percent:0}
73:(e.getDebugVal(Xt.UPDATE_READY),pt().getUpdateProgress().catch(o=>(h("updateProgress.ts").warn("Error during getting update status : "+P(o)),{status:"failed",percent:0})))};let $S,dL=0;const Z1=async()=>{const e=await noe(),t=Date.now();return $S?.status!==e.status||$S?.percent!==e.percent?($S=e,dL=t,e):zh(e.status)==="preparing"&&t-dL>=roe?{...e,status:"failed"}:e},aoe=e=>{const[t,o]=it.useState(e);return it.useEffect(()=>{let r=!1;const n=async()=>{const i=await Z1();!r&&o(i)};n();const a=setInterval(n,ooe);return()=>{r=!0,clearInterval(a)}},[]),t},ioe=()=>{if(Ps())return"windows";if(Mr())return"macos";if(DX())return"linux"},soe=async()=>{const e=h("updateProgress.ts"),t=await pt().getUpdatePolicy().catch(o=>(e.warn("Error during getting update policy : "+P(o)),void 0));pt().openUrl(bOe({channel:t==="stable"?"stable":void 0,os:ioe()}))},xoe=()=>{const e=Fe();pt().openUrl(e===ce.Korean?Tte:e===ce.Japanese?Ste:Ote)},coe=async e=>{if(e==="legacyOs"){xoe();return}await soe()},loe=e=>{const t=Math.floor(e.percent);switch(zh(e.status)){case"ready":return A("deprecation.forced_update_ready");case"manual":return A("deprecation.forced_update_failed");case"legacyOs":return A("deprecation.legacyos_announce");case"preparing":return`${A("deprecation.forced_update_preparing")}${t>0?` (${t}%)`:""}`}},doe=({initial:e,onPhaseChange:t})=>{const o=aoe(e)??e,r=zh(o.status);return it.useEffect(()=>t(r)),b.jsxs("div",{children:[b.jsx("p",{children:A("deprecation.forced_update_content")}),b.jsx("br",{}),b.jsx("p",{children:loe(o)})]})},uoe=e=>{switch(e){case"manual":return A("deprecation.forced_update_download_manually");case"legacyOs":return A("deprecation.legacyos_announce_link_label");default:return A("deprecation.forced_update_action")}},poe=async()=>{for(;;){const e=await Z1();let t=zh(e.status),o=!1;const r={bodyClassName:"general-modal",title:A("deprecation.forced_update_title"),content:b.jsx(doe,{initial:e,onPhaseChange:a=>{a===t||o||Y().isLastShownMessage(r)&&(t=a,o=!0,Y().closeLastShownMessage())}}),yesStr:uoe(t),disableConfirm:t==="preparing",noStr:A("popup.exit"),shouldCloseOnEsc:!1,shouldCloseOnOverlayClick:!1,showHeaderCancel:!1},n=await Y().popup(r);if(!o){if(n!==mt.YES){if(await pt().closeWindowByUser().catch(i=>(h("forcedUpdate.tsx").warn(`Error during closing window : ${P(i)}`),!1)))return;continue}if(t==="ready"){if(await pt().requestRestart(!0).catch(i=>(h("forcedUpdate.tsx").warn(`Error during requesting restart : ${P(i)}`),!1)))return;continue}await coe(t)}}};var _r=(e=>(e.UPDATE_CAPTION="UPDATE_CAPTION",e.RESET_CAPTION="RESET_CAPTION",e.IMPORT_CAPTION="IMPORT_CAPTION",e.IMPORT_SUBTITLE="IMPORT_SUBTITLE",e.IMPORT_MATCHED_SCRIPT="IMPORT_MATCHED_SCRIPT",e.CHANGE_CAPTION_DISPLAY_MODE="CHANGE_CAPTION_DISPLAY_MODE",e.CHANGE_CAPTION_SETTING="CHANGE_CAPTION_SETTING",e.CHANGE_CAPTION_SETTING_COLLAPSED="CHANGE_CAPTION_SETTING_COLLAPSED",e.DELETE_CAPTION_SETTING="DELETE_CAPTION_SETTING",e.DELETE_CAPTION_SETTING_CLIPS="DELETE_CAPTION_SETTING_CLIPS",e.REMOVE_CAPTION_ON_CLIPS="REMOVE_CAPTION_ON_CLIPS",e.ADJUST_CAPTION_HEIGHT="ADJUST_CAPTION_HEIGHT",e.UPDATE_CAPTION_DELTA="UPDATE_CAPTION_DELTA",e.UPDATE_CAPTION_ATTRIBUTE="UPDATE_CAPTION_ATTRIBUTE",e.SET_CAPTION_EFFECT="SET_CAPTION_EFFECT",e.MOVE_CAPTION_TEXTBOX="MOVE_CAPTION_TEXTBOX",e.RESIZE_CAPTION_TEXTBOX="RESIZE_CAPTION_TEXTBOX",e.ROTATE_CAPTION_TEXTBOX="ROTATE_CAPTION_TEXTBOX",e.TRANSFORM_CAPTION_TEXTBOX="TRANSFORM_CAPTION_TEXTBOX",e.RESET_CAPTION_HEIGHT="RESET_CAPTION_HEIGHT",e.DISASSEMBLE_CAPTION_GROUP="DISASSEMBLE_CAPTION_GROUP",e))(_r||{}),Ke=(e=>(e[e.ORIGINAL=0]="ORIGINAL",e[e.TRANSLATE=1]="TRANSLATE",e))(Ke||{}),Nl=(e=>(e.STROKE="STROKE",e.OPAQUEBOX="OPAQUEBOX",e.NORMAL="NORMAL",e.SHADOW="SHADOW",e.HIGHLIGHT="HIGHLIGHT",e))(Nl||{}),OR=(e=>(e[e.P_00_25=25]="P_00_25",e[e.P_01_50=50]="P_01_50",e[e.P_02_75=75]="P_02_75",e[e.P_03_90=90]="P_03_90",e[e.P_04_100=100]="P_04_100",e[e.P_05_110=110]="P_05_110",e[e.P_06_125=125]="P_06_125",e[e.P_07_150=150]="P_07_150",e[e.P_08_200=200]="P_08_200",e[e.P_09_250=250]="P_09_250",e[e.P_10_300=300]="P_10_300",e))(OR||{}),foe=(e=>(e[e.MIN=25]="MIN",e[e.MAX=5e3]="MAX",e))(foe||{}),goe=(e=>(e[e.OUTLINE=1]="OUTLINE",e[e.OPAQUEBOX=4]="OPAQUEBOX",e))(goe||{}),_oe=(e=>(e.BASIC="basic",e.CLIP="clip",e))(_oe||{}),Ai=(e=>(e.LEFT="left",e.CENTER="center",e.RIGHT="right",e))(Ai||{}),oo=(e=>(e.TOP="top",e.MIDDLE="middle",e.BOTTOM="bottom",e.CUSTOM="custom",e))(oo||{}),Xa=(e=>(e.ALL="all",e.CAPTION="caption",e.MULTIPLE_CAPTIONS="multiple_captions",e.TEXTBOX="textbox",e.DESIGN_TEXTBOX="design_textbox",e))(Xa||{}),Ms=(e=>(e.WORD="word",e.CHAR="char",e))(Ms||{});const wy="textarea",Eoe=.01;var moe=(e=>(e.ALL="all",e.CLIP="clip",e))(moe||{}),ar=(e=>(e.TRANSCRIPT="TRANSCRIPT",e.MANUAL="MANUAL",e))(ar||{});const hoe={0:!0,1:!0},Ioe={0:!0,1:!1},Toe={0:!1,1:!0},Soe={0:!1,1:!1},Sf={SHOW_ALL:hoe,ORIGINAL_ONLY:Ioe,TRANSLATED_ONLY:Toe,NONE:Soe},$1=Sf.ORIGINAL_ONLY,go={DEFAULT_STYLE:"STROKE",DEFAULT_SIZE:100,NOTO_FONT_FAMILY_LEGACY:"Noto Sans KR Bold",NOTO_FONT_FAMILY_JP_LEGACY:"Noto Sans JP Bold",DEFAULT_OUTLINE_THICKNESS_DEPRECATED:6,DEFAULT_TEXT_COLOR:"#ffffff",DEFAULT_STYLE_COLOR:"#000000",TEXTBOX_RECENT_COLOR_NUM:8,RECENT_FONT_FAMILY_NUM:5,VIRTUAL_YRES:1080,DEFAULT_CAPTION_POS:{xOffsetCenter:0,xOffsetLeft:0,xOffsetRight:0,yOffsetMiddle:0,yOffsetTop:0,yOffsetBottom:0,xAlign:"center",yAlign:"bottom"},SLIDE_RANGE:100,HORIZONTAL_MAX_RANGE:420,VERTICAL_MAX_RANGE:240,OUTLINE_WIDTH:6};var Yh=(e=>(e.HORIZONTAL="horizontal",e.VERTICAL="vertical",e))(Yh||{});const Eu={PRETENDARD_FONT_FAMILY:{type:"web",fontName:"Pretendard-Vrew",weight:700,psName:"Pretendard",fullName:"Pretendard",lineHeightRatio:1.34,path:"https://stock-resources.vrew.ai/fonts/Pretendard-Bold.woff2",vrewDisplayName:"Pretendard",lang:["ko","en","es"],category:"Sans Serif"},NOTO_FONT_FAMILY_JP:{type:"web",fontName:"Noto Sans JP-Vrew",vrewDisplayName:"Noto Sans JP",weight:700,psName:"NotoSansCJKjp-Bold",fullName:"Noto Sans JP Bold",lineHeightRatio:1.48,path:"https://stock-resources.vrew.ai/fonts/NotoSansJP-Bold.woff2",lang:["ja"],category:"Sans Serif"},NOTO_FONT_FAMILY_TC:{type:"web",fontName:"Noto Sans TC-Vrew",weight:700,psName:"NotoSansTC-Bold",fullName:"Noto Sans TC Bold",lineHeightRatio:1.48,vrewDisplayName:"Noto Sans TC",path:"https://stock-resources.vrew.ai/fonts/NotoSansTC-Bold.woff2",lang:["zh"],category:"Sans Serif"}},_m={captionStyle:go.DEFAULT_STYLE,captionSize:go.DEFAULT_SIZE,captionFontFamily:Eu.PRETENDARD_FONT_FAMILY.fontName,weight:Eu.PRETENDARD_FONT_FAMILY.weight,textColor:"#FFFFFF",outlineColor:"#000000",shadowColor:"#000000",opaqueboxColor:"#000000",opaqueboxAlpha:1,captionLineHeightRatio:Eu.PRETENDARD_FONT_FAMILY.lineHeightRatio,outlineWidth:go.DEFAULT_OUTLINE_THICKNESS_DEPRECATED,captionPosInfo:go.DEFAULT_CAPTION_POS}
73,Ny="center",eV="bottom",Bh=0,Ooe=99999,Coe=["font","size"],Eg={captionStyleSetting:{mediaId:Ao,yAlign:eV,yOffset:0,xOffset:Bh,rotation:0,width:.96,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:Ri},{attributeName:"--textbox-align",type:"textbox-align",value:Ny}],scaleFactor:sU},quillStyle:{size:"100",color:go.DEFAULT_TEXT_COLOR,font:"Pretendard-Vrew_700","outline-color":go.DEFAULT_STYLE_COLOR,"outline-width":"4","outline-on":"true"}};var tV=(e=>(e.ALL="all",e.BOOKMARKED="favorites",e.RECOMMENDED="recommended",e.USER_TTS="user_tts",e))(tV||{}),ME=(e=>(e.FREE="free",e.ONE_CREDIT_PER_100_CHARACTERS="one_credit_per_100_characters",e.TEN_CREDITS_PER_100_CHARACTERS="ten_credits_per_100_characters",e))(ME||{}),Roe=(e=>(e.Korean="ko",e.English="en",e.Japanese="ja",e.Spanish="es",e.Taiwanese="zh",e))(Roe||{}),Aoe=(e=>(e.None="None",e))(Aoe||{}),yoe=(e=>(e.VREWMARK_PERMISSION="VREWMARK_PERMISSION",e))(yoe||{}),voe=(e=>(e.Line="line",e.DashedLine="dashed-line",e.Arrow="arrow",e.DashedArrow="dashed-arrow",e.DoubleArrow="double-arrow",e.Cross="cross",e.Square="square",e.Deprecated_RoundedSquare="rounded-square",e.Triangle="triangle",e.Oval="oval",e))(voe||{}),woe=(e=>(e.VREW="vrew",e.PEXEL="pexel",e.PIXABAY="pixabay",e.OPENMOJI="openmoji",e.GIPHY="giphy",e.UNKNOWN="unknown",e.STABILITY="stability",e.RAY_DIFFUSION="ray_diffusion",e))(woe||{}),Noe=(e=>(e[e.FRONT_NORMAL=0]="FRONT_NORMAL",e[e.SILENT=1]="SILENT",e[e.ENTER=2]="ENTER",e[e.SOUND=3]="SOUND",e[e.LAUGHTER=4]="LAUGHTER",e[e.CLAP=5]="CLAP",e[e.FILLER=6]="FILLER",e[e.AUDIO_EVENT=8]="AUDIO_EVENT",e))(Noe||{});const Em={BASIC:"basic",PLUS:"plus"},Poe=Em.BASIC,uqe={[Em.BASIC]:"BASIC",[Em.PLUS]:"PLUS"};var boe=(e=>(e[e.SHOULD_DO_SURVEY=0]="SHOULD_DO_SURVEY",e[e.JOINED_SURVEY=1]="JOINED_SURVEY",e[e.IGNORED_SURVEY=2]="IGNORED_SURVEY",e))(boe||{}),Loe=(e=>(e.SHORT="SHORT",e.MID="MID",e.LONG="LONG",e.TITLE="TITLE",e.NAME="NAME",e.NUM_TEN="NUM_TEN",e.NUM_ZERO="NUM_ZERO",e))(Loe||{}),Moe=(e=>(e.PRETENDARD="PRETENDARD",e.GMARKET_SANS="GMARKET_SANS",e.GMARKET_SANS_LIGHT="GMARKET_SANS_LIGHT",e.BM_BRUSHSTROKE="BM_BRUSHSTROKE",e.BM_KIRANGHAERANG="BM_KIRANGHAERANG",e.JALNAN_ROUND="JALNAN_ROUND",e.CAFE24_CURSIVE="CAFE24_CURSIVE",e.CAFE24_SSURROUND="CAFE24_SSURROUND",e.CAFE24_SSURROUND_AIR="CAFE24_SSURROUND_AIR",e.CAFE24_DANGJUNGHAE="CAFE24_DANGJUNGHAE",e.MARUBURI_SERIF="MARUBURI_SERIF",e.COOKIERUN="COOKIERUN",e.VITRO_CORE="VITRO_CORE",e.RECIPE_KOREA="RECIPE_KOREA",e.JUA="JUA",e.NANUM_SQUARE_ROUND="NANUM_SQUARE_ROUND",e.BAZZI="BAZZI",e.BM_DOHYEON="BM_DOHYEON",e.SEBANG="SEBANG",e.SEBANG_BOLD="SEBANG_BOLD",e.GMARKET_SANS_MEDIUM="GMARKET_SANS_MEDIUM",e.SB_AGGRO_MEDIUM="SB_AGGRO_MEDIUM",e.SB_AGGRO_BOLD="SB_AGGRO_BOLD",e.BM_HANNA_11YRS="BM_HANNA_11YRS",e.VITRO_CORE_LIGHT="VITRO_CORE_LIGHT",e.COOKIERUN_BLACK="COOKIE_RUN_BLACK",e.BLACK_HAN_SANS="BLACK_HAN_SANS",e.S_CORE_DREAM_BLACK="S_CORE_DREAM_BLACK",e.NANUM_SQUARE_ROUND_REGULAR="NANUM_SQUARE_ROUND_REGULAR",e.NANUM_SQUARE_NEO_EXTRA_BOLD="NANUM_SQUARE_NEO_EXTRA_BOLD",e.KCC_EUNYOUNG="KCC_EUNYOUNG",e.PYEONGCHANG_PEACE_LIGHT="PYEONGCHANG_PEACE_LIGHT",e.MONTSERRAT_ALTERNATES_EXTRA_BOLD="MONTSERRAT_ALTERNATES_EXTRA_BOLD",e.OSWALD_SEMI_BOLD="OSWALD_SEMI_BOLD",e.MONTSERRAT_SEMI_BOLD="MONTSERRAT_SEMI_BOLD",e.POPPINS_EXTRA_BOLD="POPPINS_EXTRA_BOLD",e.IBM_PLEX_SANS_SEMI_BOLD="IBM_PLEX_SANS_SEMI_BOLD",e.PERMANENT_MARKER_REGULAR="PERMANENT_MARKER_REGULAR",e))(Moe||{}),Doe=(e=>(e.BASIC_TEXT="BASIC_TEXT",e.CAPTION="CAPTION",e.SPEECH_BUBBLE="SPEECH_BUBBLE",e.ANIMATED="ANIMATED",e))(Doe||{}),Kt=(e=>(e.MOV="mov",e.MP3="mp3",e.WAV="wav",e.M4A="m4a",e.PNG="png",e.GIF="gif",e.TXT="txt",e.SRT="srt",e.XML="xml",e.FCPXML="fcpxml",e.HLS="m3u8",e.MP4="mp4",e.WEBM="webm",e))(Kt||{}),koe=(e=>(e.TRANSPARENT_CAPTION_VIDEO="transparentCaptionVideo",e.AUDIO="audio",e.IMAGE="image",e.TEXT_FILE="textFile",e.CAPTION_FILE="captionFile",e.PREMIERE_PRO_XML="premiereProXml",e.FINAL_CUT_XML="finalCutXml",e.DAVINCI_XML="davinciXml",e.VIDEO="video",e.VREW_PROJECT="vrewProject",e))(koe||{}),Of=(e=>(e[e.LOCAL=0]="LOCAL",e[e.BROWSER=1]="BROWSER",e))(Of||{}),Jn=(e=>(e[e.VIDEO_EXPORT_WATCH=0]="VIDEO_EXPORT_WATCH",e[e.IMAGE_EXPORT_WATCH=1]="IMAGE_EXPORT_WATCH",e[e.AUDIO_EXPORT_WATCH=2]="AUDIO_EXPORT_WATCH",e[e.AUDIO_CONCAT_WATCH=3]="AUDIO_CONCAT_WATCH",e[e.WEBASSET_EXPORT_WATCH=4]="WEBASSET_EXPORT_WATCH",e[e.STATIC_FRAME_EXPORT_WATCH=5]="STATIC_FRAME_EXPORT_WATCH",e))(Jn||{}),V=(e=>(e[e.VIDEO=0]="VIDEO",e[e.CAPTION_VIDEO=1]="CAPTION_VIDEO",e[e.AUDIO_MP3=2]="AUDIO_MP3",e[e.AUDIO_WAV=3]="AUDIO_WAV",e[e.AUDIO_AAC=4]="AUDIO_AAC",e[e.TRANSCODING_VIDEO=5]="TRANSCODING_VIDEO",e[e.TRANSCODING_AUDIO=6]="TRANSCODING_AUDIO",e[e.CONVERTING_GIF=7]="
73CONVERTING_GIF",e[e.STREAM=8]="STREAM",e[e.IMAGE=9]="IMAGE",e[e.ANIMATED_IMAGE=10]="ANIMATED_IMAGE",e[e.SPLIT_MEDIA=11]="SPLIT_MEDIA",e[e.STATIC_FRAME=12]="STATIC_FRAME",e[e.PROXY_VIDEO=13]="PROXY_VIDEO",e))(V||{}),F0=(e=>(e[e.REGULAR=23]="REGULAR",e[e.HIGH=18]="HIGH",e[e.SUPER_HIGH=13]="SUPER_HIGH",e))(F0||{}),e0=(e=>(e.DEFAULT="default",e.AUTO="auto",e.FPS_30="fps_30",e.FPS_60="fps_60",e.CAPTION_VIDEO="caption_video",e))(e0||{}),gr=(e=>(e.NONE="none",e.NVENC="nvenc",e.QSV="qsv",e.VIDEOTOOLBOX="videotoolbox",e.AMF="amf",e))(gr||{}),CR=(e=>(e.PNG="png",e.PRORES="prores",e))(CR||{}),Foe=(e=>(e.REGULAR="regular",e.HIGH="high",e.SUPER_HIGH="super_high",e))(Foe||{});const Uoe=e=>{switch(e){case 23:return"regular";case 13:return"super_high";default:return"high"}};var Vo=(e=>(e.ALL_CLIPS="ALL_CLIPS",e.SCENE_CLIPS="SCENE_CLIPS",e.SELECTED_CLIPS="SELECTED_CLIPS",e.CURRENT_POSITION_WORD="CURRENT_POSITION_WORD",e))(Vo||{}),Py=(e=>(e.WITH_LINE_BREAK="WITH_LINE_BREAK",e.WITHOUT_LINE_BREAK="WITHOUT_LINE_BREAK",e))(Py||{}),Dr=(e=>(e[e.SUCCESS=0]="SUCCESS",e[e.USER_CANCELED=1]="USER_CANCELED",e[e.FAILED=2]="FAILED",e[e.NOT_STARTED=3]="NOT_STARTED",e))(Dr||{}),Yp=(e=>(e.NONE="NONE",e.BY_NEW_LINE="BY_NEW_LINE",e.BY_SKIP_LINE="BY_SKIP_LINE",e))(Yp||{}),oV=(e=>(e.WITHOUT_TIMECODE="without_timecode",e.WITH_TIMECODE="with_timecode",e))(oV||{}),qn=(e=>(e.NO_LOOP="NO_LOOP",e.MANUAL_LOOP="MANUAL_LOOP",e.STREAM_LOOP="STREAM_LOOP",e.FREEZE="FREEZE",e))(qn||{}),Voe=(e=>(e.EMPTY="empty",e.REORDER="reorder",e.INPUT_SCRIPT="input_script",e.SETTINGS="settings",e.SELECT_VOICE="select_voice",e.CREATING="creating",e))(Voe||{}),rV=(e=>(e.SLIDE="slide",e.LIST="list",e))(rV||{}),l0=(e=>(e[e.ALIGN_SENTENCE=0]="ALIGN_SENTENCE",e[e.FORCE_ALIGN_LENGTH=1]="FORCE_ALIGN_LENGTH",e))(l0||{}),by=(e=>(e.STT="stt",e.CLIENT="client",e))(by||{});const pqe={0:"video_analysis.align_sentence_title",1:"video_analysis.force_align_length_title"},fqe={0:"video_analysis.align_sentence",1:"video_analysis.force_align_length"},Goe={[ce.Korean]:30,[ce.Japanese]:30,[ce.Taiwanese]:18,[ce.English]:55,[ce.Spanish]:55},Jd={[ce.Korean]:12,[ce.Japanese]:12,[ce.Taiwanese]:6,[ce.English]:20,[ce.Spanish]:20},Woe={[ce.Korean]:54,[ce.Japanese]:54,[ce.Taiwanese]:33,[ce.English]:100,[ce.Spanish]:100},Hoe={[ce.Korean]:{maxLineLength:Jd[ce.Korean],mode:1,isDefaultOption:!0,mostRecentLineLengthEdit:"none"},[ce.Japanese]:{maxLineLength:Jd[ce.Japanese],mode:1,isDefaultOption:!0,mostRecentLineLengthEdit:"none"},[ce.Taiwanese]:{maxLineLength:Jd[ce.Taiwanese],mode:1,isDefaultOption:!0,mostRecentLineLengthEdit:"none"},[ce.English]:{maxLineLength:Jd[ce.English],mode:1,isDefaultOption:!0,mostRecentLineLengthEdit:"none"},[ce.Spanish]:{maxLineLength:Jd[ce.Spanish],mode:1,isDefaultOption:!0,mostRecentLineLengthEdit:"none"}},joe={[ce.Korean]:{min:12,max:54,default:30},[ce.Japanese]:{min:12,max:54,default:30},[ce.Taiwanese]:{min:6,max:33,default:18},[ce.English]:{min:20,max:100,default:55},[ce.Spanish]:{min:20,max:100,default:55}},zoe={[ce.Korean]:{min:12,max:54,default:30},[ce.Japanese]:{min:12,max:54,default:42},[ce.Taiwanese]:{min:6,max:33,default:18},[ce.English]:{min:20,max:100,default:42},[ce.Spanish]:{min:20,max:100,default:55}},Yoe={1:joe,2:zoe},Boe={[ce.Korean]:{0:["샘플 자막 입니다.","원하는 자막 서식과","길이를 골라보세요!"],1:["샘플","자막","입니다.","원하는","자막","서식과","길이를","골라보세요!"]},[ce.Japanese]:{0:["サンプル字幕です。","お好きな字幕の書式と","長さを選んでください。"],1:["サンプル","字幕","です。","お好きな","字幕の","書式と","長さを","選んで","ください。"]},[ce.Taiwanese]:{0:["這是一個示例說明。","選擇你最喜歡的字幕格式和長度!"],1:["這","是","一","個","示","例","說","明。","選","擇","你","最","喜","歡","的","字","幕","格","式","和","長","度!"]},[ce.English]:{0:["This is a","sample caption.","Choose your favorite caption format","and length!"],1:["This","is","a","sample","caption.","Choose","your","favorite","caption","format","and","length!"]},[ce.Spanish]:{0:["Este es un","título de muestra.","¡Elijan su formato","y su longitud favoritos!"],1:["Este","es","un","título","de","muestra.","¡Elijan","su","formato","y","su","longitud","favoritos!"]}},gqe={[ce.Korean]:{0:["안녕 안녕하세요","저는 개발자로 일하고 있는","홍길동입니다"],1:["안녕","안녕하세요","저는","개발자로","일하고","있는","홍길동입니다","제가","좋아하는",`
74과일은`,"복숭아","이고"]},[ce.Japanese]:{0:["皆さん皆様","パンダについて","ご存知でしょうか",`
75パンダは主に中国に生息する`],1:["皆さん","皆様","パンダ","について","ご存知","でしょ","う","か","パンダ",`
76は`,"主","に","中国","に","生息","する","白黒","の","クマ","さん","で","竹","が","大好き","です"]},[ce.Taiwanese]:{0:["karen","今天還是在家","工作的一天","今天要開的主題","還是通過一天"],1:["karen","今","天","還","是","在","家","工","作","的","一","天","今","天","要","開","的","主","題","還","是","通","過","一","天"]},[ce.English]:{0:["Peaches are","my favorite fruit.","And in my free time,","I like to watch YouTube."],1:["Hi.","Hello,","I'm","Henry.","And","I'm","a","developer.","Peaches","are","my","favorite","fruit.","And","in","my","free","time,"]},[ce.Spanish]:{0:["evaluar competencias","y las competencias","donde se desarrollan","solo en la escuela"],1:["Yaiza","pizza","diciendo","eso","y","pizza","caro","evaluar","buenas","cositas","evaluar","competencias","y","las","competencias"]}},uL={[ce.Korean]:void 0,[ce.Japanese]:void 0,[ce.Taiwanese]:void 0,[ce.English]:void 0,[ce.Spanish]:void 0};var pr=(e=>(e.ESCAPE="ESCAPE",e.SPACE="SPACE",e.TAB="TAB",e.SHIFT_TAB="SHIFT_TAB",e.BUTTON="BUTTON",e.PREVIEW_CLICK="PREVIEW_CLICK",e.CTRL_P="CTRL_P",e.F4="F4",e.F5="F5",e.AUTO="AUTO",e.KENBURNS_PREVIEW="KENBURNS_PREVIEW",e.CHARACTER_PREVIEW="CHARACTER_PREVIEW",e.TEXTBOX_PREVIEW="TEXTBOX_PREVIEW",e.ASSET_EFFECT_PREVIEW="ASSET_EFFECT_PREVIEW",e.TRANSITION_PREVIEW="TRANSITION_PREVIEW",e))(pr||{}),uo=(e=>(e.PLAY_ALL="PLAY_ALL",e.PLAY_CLIP="PLAY_CLIP",e.PLAY_WORDS="PLAY_WORDS",e.PLAY_DEFAULT="PLAY_DEFAULT",e.PLAY_ASSET_ANIMATION="PLAY_ASSET_ANIMATION",e.PLAY_TRANSITION="PLAY_TRANSITION",e))(uo||{}),Koe=(e=>(e.LOAD_VIDEO="EVENT_LOAD_VIDEO",e.LOAD_AUDIO="EVENT_LOAD_AUDIO",e.CLEAR_MEDIA="EVENT_CLEAR_MEDIA",e.PLAY="EVENT_PLAY",e.REGENERATE_WORD_TIMES="EVENT_REGENERATE_WORD_TIMES",e.LOAD_ASSET_AUDIO="EVENT_LOAD_ASSET_AUDIO",e))(Koe||{}),bu=(e=>(e.GRID="GRID",e.SHORTS_GUIDE="SHORTS_GUIDE",e))(bu||{}),Ga=(e=>(e.ADD_MEDIA_ID="ADD_MEDIA_ID",e.ADD_AUDIO_ID="ADD_AUDIO_ID",e.RECEIVE_VIDEO="RECEIVE_VIDEO",e.RECEIVE_AUDIO="RECEIVE_AUDIO",e.CLEAR_MEDIA="CLEAR_MEDIA",e.UPDATE_VIDEO_MOVE_POSITION="UPDATE_VIDEO_MOVE_POSITION",e.CLEAR_EVENT_QUEUE="CLEAR_EVENT_QUEUE",e.PLAYBACK_SESSION_CHANGED="PLAYBACK_SESSION_CHANGED",e.CAPTION="CAPTION",e.UPDATE_THUMBNAIL="UPDATE_THUMBNAIL",e.ADD_BGM="ADD_BGM",e.LOAD_ASSET_AUDIO="LOAD_ASSET_AUDIO",e.CHANGE_ASSET_VOLUMES="CHANGE_ASSET_VOLUMES",e.ADD_SOUND_EFFECT="ADD_SOUND_EFFECT",e.ADD_SOUND_EFFECTS="ADD_SOUND_EFFECTS",e.LOAD_SOUND_EFFECT="LOAD_SOUND_EFFECT",e.MODIFY_SOUND_EFFECTS="MODIFY_SOUND_EFFECTS",e.CHANGE_AUDIO_OFFSET="CHANGE_AUDIO_OFFSET",e.TOGGLE_FADE_IN_OUT="TOGGLE_FADE_IN_OUT",e))(Ga||{}),ke=(e=>(e.EXPORT_SETTING="export_setting",e.EXPORT_SETTING_FRAME_RATE="exportSettingFrameRate",e.LAST_TTS_SETTING="lastTTSSetting",e.EXPORT_TEXT_SETTING_TIMECODE="exportTextSettingTimeCode",e.EXPORT_TEXT_SETTING_LINEBREAK="exportTextSettingLinebreak",e.SETTING="setting",e.RECENT_FONTS="recentFonts",e.LAST_CAPTION_FONT="lastCaptionFont",e.LAST_USED_CAPTION_TEXT_COLOR="lastUsedCaptionTextColor",e.LAST_USED_CAPTION_OUTLINE_COLOR="lastUsedCaptionOutlineColor",e.LAST_USED_CAPTION_BACKGROUND_COLOR="lastUsedCaptionBackgroundColor",e.LAST_USED_CAPTION_HIGHLIGHT_COLOR="lastUsedCaptionHighlightColor",e.LAST_USED_CAPTION_SHADOW_COLOR="lastUsedCaptionShadowColor",e.LAST_USED_CAPTION_OUTLINE_WIDTH="lastUsedCaptionOutlineWidth",e.BOOKMARK_FONTS="bookmarkFonts",e.LEGACY_BOOKMARK_TTS_SPEAKERS="bookmarkTTSSpeakers",e.BOOKMARK_TTS_SETTINGS="bookmarkTTSSettings",e.RECENT_MARKER_ID="recentMarkerId",e.RECENT_SOUND_EFFECT="recentSoundEffects",e.BOOKMARK_SOUND_EFFECT="bookmarkSoundEffects",e.RECENT_MUSIC="recentMusics",e.BOOKMARK_MUSIC="bookmarkMusics",e.LEGACY_LINEBREAK_MODE="linebreakMode",e.LEGACY_LINEBREAK_MAX_LINE_LENGTH="linebreakMaxLineLength",e.DIVIDE_WORD_ON_HARDCUT="divideWordOnHardcut",e.DIVIDE_CLIP_ON_HARDCUT="divideClipOnHardcut",e.EXPORT_TYPE="exportType",e.LEGACY_TTS_MODAL_FILTERS="ttsModalFilters",e.LEGACY_TTS_MODAL_FILTERS_2="ttsModalFilters_2",e.LEGACY_TTS_MODAL_FILTERS_3="ttsModalFilters_3",e.TTS_MODAL_FILTERS_4="ttsModalFilters_4",e.TTS_MODAL_SHOW_TYPE="ttsModalShowType",e.TTS_MODAL_SHOW_TYPE_2="ttsModalShowType_2",e.LEGACY_THEME="theme",e.THEME="theme_2",e.SHORTS_LINEBREAK_SETTING="shortsLineBreakSetting",e.BOOKMARK_CHARACTER="bookmarkCharacters",e.CHANNELTOK_ACTIVE="channelTokActive",e.CAPTION_LENGTH_LIMIT="captionLengthLimit",e.EDIT_DETAIL_TIME_UNIT="editDetailTimeUnit",e.LEGACY_FEEDBACK_SEND_CURRENT_FILE="feedbackSendCurrentFile",e.LEGACY_TTV_TITLE="ttvTitle",e.GENIMAGE_STYLE_AI_IMAGE_MODAL="genImageStyleAIImageModal",e.GENIMAGE_STYLE_AI_IMAGE_AUTO_INSERT_PANEL="genImageStyleAIImageAutoInsertPanel",e.GENIMAGE_STYLE_TTV_MODAL="genImageStyleTTVModal",e.GENIMAGE_STYLE_THUMBNAIL_GEN="thumbnailGenGenImageStyle",e.GENIMAGE_FILL_TYPE="genImageFillType",e.GENIMAGE_COUNT="genImageCount",e.GENIMAGE_RATIO="genImageRatio",e.TTV_IMAGE_ON="ttvImageOn",e.TTV_ASSET_INSERTION_FREQUENCY="ttvAssetInsertionFrequency",e.TTV_TTS_ON="ttvTTSOn",e.TTV_BGM_O
76N="ttvBgmOn",e.TTV_VIDEO_RATIO="ttvVideoRatio",e.LEGACY_TTV_CAPTION_OPTIONS="ttvCaptionOptions",e.TTV_VIDEO_ON="ttvVideoOn",e.TTV_VIDEO_MUTE="ttvVideoMute",e.LEGACY_TTV_MUSIC_TYPE="ttvMusicType",e.LEGACY_TTV_PREVIEW_FOLD="ttvPreviewFold",e.PANEL_SCROLL_VALUE="panelScrollValue",e.LAST_USED_TRANSLATE_ENGINE="lastUsedTranslateEngine",e.MERGE_SCENE_OPTION="mergeSceneOption",e.SHORTS_OVERLAY_GUIDE="shortsOverlayGuide",e.DOCS_TTS_TOGGLE="docsTTSToggle",e.DOCS_IMPORT_TEXT_TOGGLE="docsImportTextToggle",e.DOCS_SCRIPT_MODE="docsScriptMode",e.DOCS_LANGUAGE_OPTION="docsLanguageOption",e.IMAGES_TTS_TOGGLE="imagesTTSToggle",e.IMAGES_ANIMATION_TOGGLE="imagesAnimationToggle",e.IMAGES_SCRIPT_INPUT_MODE="imagesScriptInputMode",e.IMAGES_VIDEO_RATIO="imagesVideoRatio",e.IMAGES_FILL_TYPE="imagesFillType",e.AUTO_LOGIN="autoLogin",e.SCENE_LIST_HEADER="sceneListHeader",e.LEGACY_NUM_GENERATE_IMAGE="numGeneratedImage",e.LEGACY_LAST_IMAGE_GENERATE_TIMESTAMP="lastImageGenerateTimestamp",e.LEGACY_USING_REAL_DARK_BETA="usingRealDarkBeta",e.CREDIT_WARNING_THRESHOLDS="creditWarningThresholds",e.CREDIT_WARNING_EXPIRE_AT="creditWarningExpireAt",e.EDIT_OVERLAY="editOverlay",e.DISABLE_VREW_MARK="disableVrewMark",e.LAST_OPEN_DIR_LIST="lastOpenDirList",e.IMPORT_SCRIPT_SETTING="importScriptSetting",e.LEGACY_RECOMMENDED_SUBJECTS="recommendedSubjects",e.LEGACY_VIDEO_STYLES="videoStyles",e.LEGACY_VIDEO_STYLE_GUIDE_TOOLTIP_SHOW="videoStyleGuideTooltipShow",e.LEGACY_VIDEO_STYLE_LIST_GUIDE_TOOLTIP_SHOW="videoStyleListGuideTooltipShow",e.DOWNLOADS_DIR="downloadDir",e.EDIT_VREWMARK_ALTERNATIVE_INFOS="editVrewMarkAlternativeInfo",e.STT_TIER="sttTier",e.LOGIN_HINTS="loginHints",e.SAVE_TRAILING_SINGLE_DOT="saveTrailingSingleDot",e.AI_WRITING_MODE="aiWritingMode",e.LEGACY_FRAME_CAPTURE_GUIDE="frameCaptureGuide",e.CHARACTER_GEN_IMAGE_STYLE="characterGenImageStyle",e.CHARACTER_GEN_IMAGE_COUNT="characterGenImageCount",e.CHARACTER_STUDIO_GUIDE="characterStudioGuide",e.CHARACTER_STUDIO_IMAGE_UPDATE_SHOWN_COUNT="characterStudioImageUpdateShownCount",e.USE_BETA_EXPORT="useBetaExport",e.SPACER_TIME="spacerTime",e.FREEZE_WORD_TIME="freezeWordTime",e.LEGACY_TTV_FREE_VIDEO_TOOLTIP_SHOW="ttvFreeVideoTooltipShow",e.LEGACY_SHOW_USER_TTS_PURPOSE_SURVEY="showUserTTSPurposeSurvey",e.STT_LINEBREAK_SETTING="sttLinebreakSetting",e.CLIENT_LINEBREAK_SETTING="clientLinebreakSetting",e.LEGACY_LINEBREAK_VERSION="linebreakVersion",e.CONTEXT_FLOATING_MENU_ASSET_INSERT_SHORTCUTS="contextFloatingMenuAssetInsertShortcuts",e.CONTEXT_FLOATING_MENU_CLIP_EFFECT_SHORTCUTS="contextFloatingMenuClipEffectShortcuts",e.VREW_VERSION_HISTORY="vrewVersionHistory",e.ASSET_IMPORT_METHOD="assetImportMethod",e.FEATURE_SEARCHED_PATHS="featureSearchedPath",e.FEATURE_SEARCHED_TIMESTAMP="featureSearchedTimestamp",e.GENIMAGE_ENGINE_AI_IMAGE_MODAL="genImageEngineAIImageModal",e.LEGACY_GENIMAGE_ENGINE_AI_IMAGE_MODAL_CHAT="genImageEngineAIImageModalChat",e.GENIMAGE_ENGINE_AI_IMAGE_AUTO_INSERT_PANEL="genImageEngineAIAutoInsertPanel",e.GENIMAGE_ENGINE_TTV_MODAL="genImageEngineTTVModal",e.STARTUP_OPTION="startupOption",e.VOCAL_DICTIONARY_ENABLED="vocalDictionaryEnabled",e.CLIP_THUMBNAIL_VISIBILITY="clipThumbnailVisibility",e.AUTO_SPLIT_SCENE_ENABLED="autoSplitSceneEnabled",e.AUTO_CAPTION_CORRECTION="autoCaptionCorrection",e.STT_ADVANCED_SETTINGS_COLLAPSED="sttAdvancedSettingsCollapsed",e.GENIMAGE_USER_GUIDANCE_TTV_MODAL="genImageUserGuidanceTTVModal",e.GENIMAGE_USER_GUIDANCE_AI_IMAGE_AUTO_INSERT_PANEL="genImageUserGuidanceAIImageAutoInsertPanel",e.LEGACY_GENIMAGE_UPSCALE_ON_TTV_MODAL="genImageUpscaleOnTTVModal",e.LEGACY_GENIMAGE_UPSCALE_ON_AI_IMAGE_MODAL="genImageUpscaleOnAIImageModal",e.LEGACY_GENIMAGE_UPSCALE_ON_AI_IMAGE_MODAL_CHAT="genImageUpscaleOnAIImageModalChat",e.LEGACY_GENIMAGE_UPSCALE_ON_AI_IMAGE_AUTO_INSERT_PANEL="genImageUpscaleOnAIImageAutoInsertPanel",e.GENIMAGE_HIGH_RESOLUTION_ON_AI_IMAGE_PANEL="genImageHighResolutionOnAIImagePanel",e.GENIMAGE_HIGH_RESOLUTION_ON_AI_IMAGE_AUTO_INSERT_PANEL="genImageHighResolutionOnAIImageAutoInsertPanel",e.TTV_SCRIPT_SETTING="ttvScriptSetting",e.TTV_LAST_SCRIPT="ttvLastScript",e.VIDEO_STYLES_V2="videoStylesV2",e.LEGACY_TTV_V1_MIGRATION_POPUP="ttvV1MigrationPopup",e.TTV_STYLE="ttvStyle",e.TTV_STYLE_DEPRECATED_TOOLTIP_SHOW="ttvStyleDeprecatedTooltipShow",e.INCLUDE_IMAGE_AI_IMAGE_AUTO_INSERT_PANEL="includeImageAIImageAutoInsertPanel",e.SHORTS_IMAGE_RATIO_AI_IMAGE_AUTO_INSERT_PANEL="shortsImageRatioAIImageAutoInsertPanel",e.VIEW_MODE="viewMode",e.NEWLINE_MODE="newlineMode",e.SHOW_ASSETS_IN_SCRIPT="showAssetsInScript",e.AUTO_SPLIT_SCENES="autoSplitScenes",e.PREPARE_PROXY="prepareProxy",e.EXPORT_SETTING_HWACCEL_IN_BROWSER="exportSettingHwaccelInBrowser",e.USE_GENVIDEO_ON_GENERATE_MODAL="useGenVideoOnGenerateModal",e.LEGACY_GENVIDEO_ENGINE_ON_GENERATE_MODAL="genVideoEngineOnGenerateModal",e.GENVIDEO_RATIO="genVideoRatio",e.LEGACY_GENVIDEO_ARCHIVE_ON_GENERATE_MODAL="genVideoArchiveOnGenerateModal",e.GENERATE_MODAL_INPUT_RATIO="genImageModalInputRatio",e.OVERDUB_USAGE_TOOLTIP_SUPPRESSED="overdubUsageTooltipSuppressed",e.START_MODAL_IMPORT_METHOD="startModalImportMethod",e.START_MODAL_HISTORY="startModalHistory",e.ATV_SETTING="atvSetting",e.SCENE_PANEL_OPEN="scenePanelOpen",e.TTV_VERSION="ttvVersion",e.START_MODAL_VERSION="startModalVersion",e.START_MODAL_SHORTS_FEATURE="startModalShortsFeature",e.DEFAULT_CAPTION_DISPLAY_MODE="defaultCaptionDisplayMode",e.AUDIO_ENCODE_MODE="defaultAudioEncodeMode",e.TEMPLATE_DEFAULT_INSERT_POSITION="templateDefaultInsertPosition",e.SMART_AI_DUBBING_AUTO_MUTE="smartAIDubbingAutoMute",e.SMART_AI_DUBBING_AUTO_FREEZE_WORD="smartAIDubbingAutoFreezeWord",e.AUTO_FIT_SPACER_TO_VIDEO="autoFitSpacerToVideo",e.TTS_SPLIT_AT_PUNCTUATION="ttsSplitAtPunctuation",e.STT_AI_IMAGE_ON="sttAiImageOn",e.STT_SHORTS_IMAGE_RATIO="sttShortsImageRatio",e.STT_VIDEO_ON="sttVideoOn",e.USE_BETA_EXPORT_AUDIO="useBetaExportAudio",e.STT_GENIMAGE_STYLE="sttGenImageStyle",e.STT_GENIMAGE_FILL_TYPE="sttGenImageFillType",e.STT_GENIMAGE_USER_GUIDANCE="sttGenImageUserGuidance",e.LEGACY_STT_GENIMAGE_UPSCALE_ON="sttGenImageUpscaleOn",e.STT_GENIMAGE_HIGH_RESOLUTION_ON="sttGenImageHighResolutionOn",e.STT_GENIMAGE_ENGINE="sttGenImageEngine",e.STT_VIDEO_MUTE="sttVideoMute",e.STT_VIDEO_RATIO="sttVideoRatio",e.LEGACY_GENIMAGE_MODEL_BY_TIER="genImageModelByTier",e.LEGACY_GEN_VIDEO_PANEL_STYLE="genVideoPanelStyle",e.LEGACY_GEN_VIDEO_PANEL_RATIO="genVideoPanelRatio",e.DESKTOP_SHORTCUT_RESTORE_ENABLED="desktopShortcutRestoreEnabled",e.TTV_MEDIA_SETTING_V5="ttvMediaSettingV5",e.TTV_SCRIPT_SETTING_V5="ttvScriptSettingV5",e.GEN_VIDEO_PANEL_LAST_USED_SETTING="genVideoPanelLastUsedSetting",e))(ke||{});let eO;const Xoe=()=>(!eO&&(eO={export_setting:{quality:F0.HIGH,resolution:void 0}
76,exportSettingFrameRate:e0.DEFAULT,exportTextSettingTimeCode:oV.WITHOUT_TIMECODE,exportTextSettingLinebreak:Yp.BY_SKIP_LINE,lastTTSSetting:{},setting:{useWordDeleteButton:!0},recentFonts:[],lastCaptionFont:void 0,lastUsedCaptionTextColor:void 0,lastUsedCaptionOutlineColor:void 0,lastUsedCaptionOutlineWidth:void 0,lastUsedCaptionBackgroundColor:void 0,lastUsedCaptionHighlightColor:void 0,lastUsedCaptionShadowColor:void 0,bookmarkFonts:[],bookmarkTTSSpeakers:[],bookmarkTTSSettings:[],recentMarkerId:void 0,recentSoundEffects:[],bookmarkSoundEffects:[],recentMusics:[],bookmarkMusics:[],linebreakMode:l0.ALIGN_SENTENCE,linebreakMaxLineLength:void 0,divideWordOnHardcut:!1,divideClipOnHardcut:!1,exportType:void 0,ttsModalFilters:{age:[],gender:[],lang:[]},ttsModalFilters_2:null,ttsModalFilters_3:null,ttsModalFilters_4:null,ttsModalShowType:tV.ALL,ttsModalShowType_2:null,theme:{theme:GX.LIGHT},theme_2:VX.LIGHT,shortsLineBreakSetting:Hoe,bookmarkCharacters:[],channelTokActive:null,captionLengthLimit:{isLimited:!1,lastLength:xZ},editDetailTimeUnit:cZ,feedbackSendCurrentFile:!1,ttvTitle:"",genImageStyleAIImageModal:"none",genImageStyleAIImageAutoInsertPanel:"none",genImageStyleTTVModal:"none",thumbnailGenGenImageStyle:UX,genImageFillType:"none",genImageCount:1,genImageRatio:null,panelScrollValue:{all:0},lastUsedTranslateEngine:{engine:Ea.GPT},mergeSceneOption:!1,shortsOverlayGuide:!0,docsTTSToggle:!1,docsImportTextToggle:!0,docsScriptMode:"ai_script",docsLanguageOption:null,imagesTTSToggle:!0,imagesAnimationToggle:!0,imagesScriptInputMode:rV.LIST,imagesVideoRatio:he.WIDE_SCREEN,imagesFillType:"cut",autoLogin:!0,ttvBgmOn:!0,ttvVideoOn:!0,ttvVideoMute:!0,ttvMusicType:"active",ttvImageOn:!0,ttvAssetInsertionFrequency:"frequent",ttvTTSOn:!0,ttvVideoRatio:he.WIDE_SCREEN,ttvCaptionOptions:{length:"short",position:"middle",autoAnimation:!0},ttvPreviewFold:!1,sceneListHeader:!0,numGeneratedImage:0,lastImageGenerateTimestamp:0,usingRealDarkBeta:!1,creditWarningThresholds:L1,creditWarningExpireAt:"",editOverlay:{[bu.GRID]:!1,[bu.SHORTS_GUIDE]:!1},disableVrewMark:!1,lastOpenDirList:[],importScriptSetting:{linebreak:!0,punctuation:!1,slash:!1},recommendedSubjects:{},videoStyles:{},videoStyleGuideTooltipShow:0,videoStyleListGuideTooltipShow:0,downloadDir:"",editVrewMarkAlternativeInfo:[],sttTier:Poe,loginHints:[],saveTrailingSingleDot:null,aiWritingMode:null,frameCaptureGuide:!0,characterGenImageStyle:void 0,characterGenImageCount:NJ,characterStudioGuide:!0,characterStudioImageUpdateShownCount:0,useBetaExport:!0,spacerTime:yZ,freezeWordTime:vZ,ttvFreeVideoTooltipShow:!0,showUserTTSPurposeSurvey:[],sttLinebreakSetting:uL,clientLinebreakSetting:uL,linebreakVersion:1,contextFloatingMenuAssetInsertShortcuts:[],contextFloatingMenuClipEffectShortcuts:[],vrewVersionHistory:[],assetImportMethod:"vdrop.import_option_from_PC",featureSearchedPath:[],featureSearchedTimestamp:void 0,genImageEngineAIImageModal:Tc.GPT_IMAGE_2_LOW,genImageEngineAIImageModalChat:null,genImageEngineAIAutoInsertPanel:Tc.GPT_IMAGE_2_LOW,genImageEngineTTVModal:Tc.GPT_IMAGE_2_LOW,startupOption:FX.OPEN_LAST_PROJECT,vocalDictionaryEnabled:!0,clipThumbnailVisibility:!0,autoSplitSceneEnabled:!1,autoCaptionCorrection:!0,sttAdvancedSettingsCollapsed:!0,genImageUserGuidanceTTVModal:"",genImageUserGuidanceAIImageAutoInsertPanel:"",genImageUpscaleOnTTVModal:null,genImageUpscaleOnAIImageModal:null,genImageUpscaleOnAIImageModalChat:null,genImageUpscaleOnAIImageAutoInsertPanel:null,genImageHighResolutionOnAIImagePanel:!1,genImageHighResolutionOnAIImageAutoInsertPanel:!1,ttvScriptSetting:{none:void 0},ttvLastScript:"",videoStylesV2:{none:void 0},ttvV1MigrationPopup:"expanded",ttvStyle:void 0,ttvStyleDeprecatedTooltipShow:{vrew_style_22:!0,vrew_style_23:!0},includeImageAIImageAutoInsertPanel:!0,shortsImageRatioAIImageAutoInsertPanel:he.VERTICAL,viewMode:"clips",newlineMode:!1,showAssetsInScript:!0,autoSplitScenes:!1,prepareProxy:!1,exportSettingHwaccelInBrowser:!0,useGenVideoOnGenerateModal:!1,genVideoEngineOnGenerateModal:null,genVideoRatio:null,genVideoArchiveOnGenerateModal:!1,genImageModalInputRatio:null,overdubUsageTooltipSuppressed:!1,startModalImportMethod:"pc",startModalHistory:[],atvSetting:void 0,scenePanelOpen:null,ttvVersion:"2",startModalVersion:"A",startModalShortsFeature:kX.ASSET_TO_VIDEO,defaultCaptionDisplayMode:$1,defaultAudioEncodeMode:"default",templateDefaultInsertPosition:"end",smartAIDubbingAutoMute:!0,smartAIDubbingAutoFreezeWord:!0,autoFitSpacerToVideo:!1,ttsSplitAtPunctuation:null,sttAiImageOn:!1,sttShortsImageRatio:he.VERTICAL,sttVideoOn:!1,useBetaExportAudio:!0,sttGenImageStyle:"none",sttGenImageFillType:"none",sttGenImageUserGuidance:"",sttGenImageUpscaleOn:null,
76sttGenImageHighResolutionOn:!1,sttGenImageEngine:Tc.GPT_IMAGE_2_LOW,sttVideoMute:!0,sttVideoRatio:he.WIDE_SCREEN,genImageModelByTier:{},genVideoPanelStyle:"none",genVideoPanelRatio:null,genVideoPanelLastUsedSetting:{mode:"create",settingsByMode:{}},desktopShortcutRestoreEnabled:null,ttvMediaSettingV5:void 0,ttvScriptSettingV5:void 0}),eO),Mt=e=>{const t=Ve().getObject(Ie.LAST_USED_SETTING,{}),o=Xoe();return t[e]??o[e]},po=(e,t)=>{const o=Ve().getObject(Ie.LAST_USED_SETTING,{});Ve().set(Ie.LAST_USED_SETTING,{...o,[e]:t})};var nV=(e=>(e[e.PLANNED=0]="PLANNED",e[e.EMERGENCY=1]="EMERGENCY",e))(nV||{}),Joe=(e=>(e.VREWMARK_PERMISSION="VREWMARK_PERMISSION",e))(Joe||{});const aV=e=>{const t=new Date(e.start),o=new Date(e.end),r=p=>p.getFullYear()+". "+(p.getMonth()+1)+". "+p.getDate()+" ("+p.toLocaleString(window.navigator.language||"en",{weekday:"short"})+")",n=p=>p.getHours()+":"+ZN(p.getMinutes(),2),a=r(t),i=r(o),s=a+" "+n(t),x=(a===i?"":i+" ")+n(o),c=e.maintenanceType===nV.EMERGENCY?A("maintenance.desc_emergency"):A("maintenance.desc_planned"),l=A("maintenance.duration",{start:s,end:x}),d=jt.createElement("div",void 0,[...c.split(`
77`).map(p=>jt.createElement("div",void 0,p)),jt.createElement("br"),jt.createElement("div",void 0,l)]);return{bodyClassName:"general-modal",title:A("maintenance.title"),content:d,yesStr:A("popup.confirm")}};var Ix=(e=>(e.SIGN_OUT="auth.sign_out",e.SIGN_IN="auth.sign_in",e.USER_INFO_UPDATED="auth.user_info_updated",e))(Ix||{});const qoe=new ad.EventEmitter,Ly=()=>qoe,pL=5,mg=()=>Vr()&&Mo().getDebugVal(Xt.CHECK_LOGIN)===void 0,Vn=async e=>{if(Mo().getDebugVal(Xt.SKIP_FRONT_LOGIN_CHECK),mg())return!0;const o=h("auth.ts"),r=be().getUserInfo();if(r===void 0)return o.info("No user info on "+e+". ask login."),await uP(),!1;const n=r.emailVerified===!1?r.email:r.parentEmail!==""&&r.parentEmailVerified===!1?r.parentEmail:void 0;if(n){o.info("User info "+JSON.stringify(r)+" on "+e+". ask verify.");const a=p0(A("login.verify_needed_msg",{email:r.email,verifyEmail:n}));return await Y().info(a),!1}return!0},Qoe=(e,t)=>async()=>{await Vn(e)&&t()},My=async e=>{const t=e.emailVerified===!1?e.email:e.parentEmail!==""&&e.parentEmailVerified===!1?e.parentEmail:void 0;if(t){const o=p0(A("login.verify_needed_msg",{email:e.email,verifyEmail:t}));await Y().info(o);return}},Zoe=async e=>{await Vn("onClickInsertTTS")&&e()};class iV{loginHints;cryptoKey;constructor(){this.cryptoKey=this.getCryptoKey(),this.loginHints=this.loadLoginHints()}getCryptoKey=()=>IJ.cryptoKey;getLoginHints=()=>this.loginHints;encrypt=t=>Vb.encrypt(t,this.cryptoKey).toString();decrypt=t=>Vb.decrypt(t,this.cryptoKey).toString(f9.enc.Utf8);loadLoginHints=()=>this.cryptoKey?Mt(ke.LOGIN_HINTS).map(o=>({id:this.decrypt(o.id),lastUsedDateTime:o.lastUsedDateTime})).sort((o,r)=>o.lastUsedDateTime>r.lastUsedDateTime?-1:1).slice(0,pL):[];encryptLoginHint=t=>({...t,id:this.encrypt(t.id)});updateStorage=()=>{const t=this.loginHints.map(this.encryptLoginHint);po(ke.LOGIN_HINTS,t)};updateLoginHint=t=>{const o=this.loginHints.filter(n=>n.id!==t),r={id:t,lastUsedDateTime:Date.now()};this.loginHints=[r,...o].sort((n,a)=>n.lastUsedDateTime>a.lastUsedDateTime?-1:1).slice(0,pL),this.updateStorage()};addLoginHint=t=>{const o={id:t,lastUsedDateTime:Date.now()},r=[o,...this.loginHints].slice(0,5);this.loginHints=r,this.updateStorage()};removeLoginHint=t=>{const o=this.loginHints.filter(r=>r.id!==t);this.loginHints=o,this.updateStorage()}}let tO=null;const sV=()=>(!tO&&(tO=new iV),tO),RR=async()=>{await wo()&&await F2("/user-last-chat-created",{method:"POST"}).catch(e=>{h("auth.ts").warn("Failed to update last chat: "+P(e))})},vl=(e,t)=>{if(e.error)throw h("auth.ts").error(t+" api failed: "+P(e.error)),new C(e.error.errorCode,{firebaseErr:e.error.firebaseCode},e.error.msg)},xV=e=>{if(!e.error&&(!e.user||!e.session))throw new C(_.A_AUTH_INVALID_AUTH_API_RESPONSE,void 0,"Invalid response from SignInResponse")},AR=e=>{if(e.maintenance)throw new C(_.C_UPLOAD_SERVER_MAINTENANCE,{...e.maintenance},"Vrew Maintenance")},yR=e=>{if(e.versionTooLow)throw new C(_.C_APP_VERSION_IS_LOW,void 0,"Version too low")},DE=async(e,t,o=_.A_AUTH_GERNAL_ERROR)=>{const r=Ne(t)?t:new C(o,void 0,xg(t)?t.message:"Unknown error"),n=await Dy(e,r);n&&await Y().error(n.errorCode,n.displayMessage)},Dy=async(e,t)=>{if(Ne(t)){const{errorCode:o,message:r,errorArgs:n}=t;let a;if(o===_.C_APP_VERSION_IS_LOW){await poe();return}else if(o===_.C_UPLOAD_SERVER_MAINTENANCE){const s=aV({maintenanceType:t.errorArgs.maintenanceType,start:t.errorArgs.start,end:t.errorArgs.end});await Y().popup(s);return}else o===_.A_AUTH_LOGIN_DELETED_USER&&(a={...n,email:r});h("auth.ts").error("["+o+"] "+e+" "+r),br(e,"error",{error:"["+o+"] "+r});const i=Ot(o,{defaultKey:"error.api_auth_failed",errorArg:a,firebaseErr:n.firebaseErr});return{errorCode:o,displayMessage:i}}else return h("auth.ts").error("["+e+"] Unknown error occurred: "+P(t)),br(e,"error",{error:t}),{errorCode:_.A_AUTH_GERNAL_ERROR,displayMessage:A("error.unknown_auth_error")}},ky=async(e,t,o,r,n,a,i,s)=>{h("auth.ts").info("[handleOAuth] deeplinkAction: "+n+", signUp: "+a+", webCid: "+i+", providerId: "+o+", installCode: "+r+", credential: "+e+", credentialType: "+t+", gclid: "+s),n==="delete_account"?await $oe(e,t,o,r):(n==="oauthSignIn"||n===void 0)&&await ere(e,t,o,r,a,i,s)},$oe=async(e,t,o,r)=>{const n=be().getUserInfo()?.email,a=await be().getEmailFromGoogleAccessToken(e);if(n!==a){xt.error(A("error.failed_to_re_sign_in"));return}await be().oauthSignIn(e,t,o,!0,r,"",!1,void 0),await Wbe()},ere=async(e,t,o,r,n,a,i)=>{const s=wte(r),x=s?{referralType:s,referralCode:""}:void 0;await be().oauthSignIn(e,t,o,!0,r,a,n,i,x)},Fy=async(e,t,o,r,n)=>{h("auth.ts").info("[handleDeeplinkSignUp] sessionId: "+e+", uid: "+t+", installCode: "+o+", webCid: "+r+", gclid: "+n),hR(!0),await be().sessionSignIn(e,o,r,n)},tre=async()=>{const e=Fe();try{const t=await Zs("/get-experiment-info",{method:"POST",body:JSON.stringify({language:e})});return await me(t,_.A_AUTH_GERNAL_ERROR)}catch(t){return h("auth.ts").warn("Failed to get experiment info: "+P(t)),[]}},ore=async()=>
77{const e=be();await e.waitUntilInitialized();const t=e.getUserInfo()?.uid;if(t)return t;if(e.getUserInfo()===void 0&&await uP()==="login_success"){const n=e.getUserInfo()?.uid;if(n)return n}const o=e.getUserInfo();if(o!==void 0){const r="uid is invalid but userInfo exists: "+JSON.stringify(o);throw h("auth.ts").error(r),new C(_.C_LOGIN_REQUIRED_ERROR,{},r)}throw h("auth.ts").warn("uid is invalid and userInfo does not exist"),new C(_.C_LOGIN_REQUIRED_ERROR)},Uy=e=>{if(!at()||mg()||e!=="")return;const t=h("auth.ts"),o=be().getUserInfo();if(o){const n="uid is invalid but userInfo exists: "+JSON.stringify(o);throw t.error(n),new C(_.C_EMAIL_VERIFY_REQUIRED_ERROR,{email:o.email},n)}throw t.error("uid is invalid and userInfo does not exist"),new C(_.C_LOGIN_REQUIRED_ERROR)},rre=e=>{try{return Uy(e),!0}catch{return!1}},vR=e=>{const t=Y();t.getModalProps(st.LOGIN)?.resolve(e),t.closeModal(st.LOGIN)},nre=Object.freeze(Object.defineProperty({__proto__:null,AuthEvent:Ix,LoginHintManager:iV,authErrorHandler:DE,closeLoginModal:vR,ensureLogin:Vn,executeActionIfLoggedIn:Zoe,fetchExperimentInfo:tre,getAuthErrorDisplayMessage:Dy,getAuthEventEmitter:Ly,getLoginHintManager:sV,handleDeeplinkSignUp:Fy,handleOAuth:ky,isLoggedIn:rre,requireUid:ore,showVerifyEmailError:My,skipLocalLoginCheck:mg,throwIfInvalidSignInResponse:xV,throwIfMaintenance:AR,throwIfNotLoggedIn:Uy,throwIfResponseError:vl,throwIfVersionTooLow:yR,updateUserLastChatCreated:RR,withLogin:Qoe},Symbol.toStringTag,{value:"Module"})),are=/[\x00-\x1f\x7f"\\]/g,cV=e=>e.replace(are,t=>"\\"+t.charCodeAt(0).toString(16)+" "),lV=e=>'"'+cV(e)+'"',dV=e=>e.map(t=>`@font-face {
78  font-family: `+lV(t.fontName)+`;
79  src: url("`+cV(t.path)+`") format("woff2");
80  font-weight: `+t.weight+`;
81}`).join(`
82`),wR=(e,t)=>e+"_"+t,zc=e=>{const t=e.lastIndexOf("_");if(t===-1)return{fontName:e,weight:0};const o=e.slice(t+1);return/^\d+$/.test(o)?{fontName:e.slice(0,t),weight:Number(o)}:{fontName:e,weight:0}},ki={OPEN_USER_TTS_MODAL:"open_user_tts_modal",CONFIRM_AGREEMENT:"confirm_agreement",CHECK_RECORDING_GUIDE:"check_recording_guide",RECORD_SENTENCE:"record_sentence",PLAYBACK_RECORDING:"playback_recording",CONFIRM_RECORDING:"confirm_recording",SEND_TRAINING_REQUEST:"send_training_request",TRAINING_REQUEST_RESULT:"training_request_result",TRAINING_DONE:"training_done",SEND_REGISTER_REQUEST:"send_register_request",REGISTER_REQUEST_RESULT:"register_request_result",LEAVE_USER_TTS_MODAL:"leave_user_tts_modal",CLICK_USER_TTS:"click_user_tts",CLICK_USER_TTS_SPEAKER_LIST:"click_user_tts_speaker_list"},ire=(e,t)=>I().event(m.USER_TTS,g.TTS_REQUEST,void 0,void 0,JSON.stringify({...e,triggerSource:t})),sre=e=>{I().event(m.USER_TTS,ki.OPEN_USER_TTS_MODAL,void 0,void 0,JSON.stringify({entryPoint:e}))},_qe=(e,t,o)=>{I().event(m.USER_TTS,g.CLICK_START_BUTTON,void 0,void 0,JSON.stringify({speakerId:e,language:t,userTTSVersion:o}))},Eqe=(e,t)=>{I().event(m.USER_TTS,ki.CONFIRM_AGREEMENT,void 0,void 0,JSON.stringify({speakerId:e,userTTSVersion:t}))},mqe=e=>{I().event(m.USER_TTS,ki.CHECK_RECORDING_GUIDE,void 0,void 0,JSON.stringify({speakerId:e,userTTSVersion:"v1"}))},hqe=(e,t,o,r,n)=>{const a={speakerId:e,sentenceIndex:t,isReRecording:o,audioLengthInMs:r,userTTSVersion:n};I().event(m.USER_TTS,ki.RECORD_SENTENCE,void 0,void 0,JSON.stringify(a))},Iqe=(e,t,o)=>{const r={speakerId:e,sentenceIndex:t,userTTSVersion:o};I().event(m.USER_TTS,ki.PLAYBACK_RECORDING,void 0,void 0,JSON.stringify(r))},Tqe=(e,t)=>{I().event(m.USER_TTS,ki.CONFIRM_RECORDING,void 0,void 0,JSON.stringify({speakerId:e,userTTSVersion:t}))},xre=e=>{I().event(m.USER_TTS,ki.SEND_TRAINING_REQUEST,void 0,void 0,JSON.stringify({speakerId:e,userTTSVersion:"v1"}))},fL=(e,t)=>{I().event(m.USER_TTS,ki.TRAINING_REQUEST_RESULT,void 0,void 0,JSON.stringify({speakerId:e,result:t,userTTSVersion:"v1"}))},gL=(e,t,o)=>{const r={speakerId:e,isSuccess:t,timeTakenToTrainInMin:o,userTTSVersion:"v1"};I().event(m.USER_TTS,ki.TRAINING_DONE,void 0,void 0,JSON.stringify(r))},cre=e=>{I().event(m.USER_TTS,ki.SEND_REGISTER_REQUEST,void 0,void 0,JSON.stringify({speakerId:e,userTTSVersion:"v2"}))},_L=(e,t,o)=>{I().event(m.USER_TTS,ki.REGISTER_REQUEST_RESULT,void 0,void 0,JSON.stringify({speakerId:e,result:t,timeTakenInSec:o,userTTSVersion:"v2"}))},Sqe=(e,t,o,r)=>{const n={speakerId:e,currentStage:t,userTTSVersion:o,sentenceIdx:r};I().event(m.USER_TTS,ki.LEAVE_USER_TTS_MODAL,void 0,void 0,JSON.stringify(n))},Oqe=()=>{I().event(m.TOOLBAR_USER_TTS,ki.CLICK_USER_TTS)},Cqe=()=>
82{I().event(m.TOOLBAR_USER_TTS,ki.CLICK_USER_TTS_SPEAKER_LIST)},lre=Sr.object({title:Sr.string().min(1),desc:Sr.string().min(1),link:Sr.url()});Sr.object({banner:Sr.record(Sr.string(),Sr.array(lre))});Sr.object({user:Sr.string().min(1),host:Sr.string().min(1)});Sr.object({user:Sr.string().min(1),host:Sr.string().min(1),role:Sr.enum(["ro_role","rw_role"]),expiresAt:Sr.iso.datetime().optional()});Sr.object({user:Sr.string().min(1),host:Sr.string().min(1),role:Sr.enum(["ro_role","rw_role"])});Sr.object({deviceId:Sr.string().min(1)});Sr.object({deviceId:Sr.string().min(1),skip:Sr.boolean()});const vc=1e3,Rqe=60,Aqe=183,dre=e=>e.toFixed(3),yqe=100,vqe=60,uV=300,Bp=100,pV=65535,Y_={STOCK_FREE:"stock-free",STOCK_STANDARD:"stock-standard",STOCK_TYPECAST:"stock-typecast",USER_TTS:"user-tts"},fV={REGULAR:"tts-regular-pricing-release-4.6.0"},ure={[fV.REGULAR]:{classes:{[Y_.STOCK_FREE]:{creditsPer100Chars:0},[Y_.STOCK_STANDARD]:{creditsPer100Chars:1},[Y_.STOCK_TYPECAST]:{creditsPer100Chars:10},[Y_.USER_TTS]:{creditsPer100Chars:1}}}},pre=fV.REGULAR,wqe=1,fre={BASIC:1},gre={DEFAULT:1,BASIC:1,PLUS:5},wp=e=>typeof e=="object"&&e!==null,NR=e=>{if(!wp(e))throw new Error("TTS speaker is missing or invalid");const t=e.creditsPer100Chars;if(typeof t!="number"||!Number.isSafeInteger(t)||t<0||t>pV)throw new Error("TTS pricing is missing or invalid for speaker: "+(typeof e.speakerId=="string"?e.speakerId:"unknown"))},_re=e=>{if(!wp(e))throw new Error("TTS voice list is missing or invalid");if(typeof e.pricingPolicyVersion!="string"||e.pricingPolicyVersion.trim().length===0)throw new Error("TTS pricing policy version is missing or invalid");if(!wp(e.allVoices))throw new Error("TTS stock voice list is missing or invalid");if(Object.values(e.allVoices).forEach(t=>{if(!wp(t))throw new Error("TTS provider voice list is missing or invalid");Object.values(t).forEach(NR)}),!wp(e.defaultVoices))throw new Error("TTS default voice list is missing or invalid");Object.values(e.defaultVoices).forEach(NR)},Ere=e=>{if(!Array.isArray(e))throw new Error("UserTTS voice list is missing or invalid");e.forEach(NR)};class mre extends HX{get=t=>window.sessionStorage.getItem(t)||"";set=(t,o)=>{window.sessionStorage.setItem(t,this.stringifyValue(o))};remove=t=>window.sessionStorage.removeItem(t);has=t=>window.sessionStorage.getItem(t)!==null}let oO;const ir=()=>(!oO&&(oO=window.sessionStorage?new mre:new WX),oO),Ta=e=>Ve().getObject(Ie.FEATURE_USED)[e]===!0,wn=(e,t=!1)=>{const o=Ve(),r=o.getObject(Ie.FEATURE_USED);r[e]||(o.set(Ie.FEATURE_USED,{...r,[e]:!0}),t&&GDe(e))};let hre=!1;const Vy=()=>hre||!Cy(),Ire=()=>{Vy()&&wn(It.AUTO_CAPTION_CORRECTION_TOOLTIP)},Nqe=()=>{Ire()},Tre=e=>Object.entries(e).filter(gV).map(([o])=>o),gV=([e,t])=>{if(Vy()&&!t.showOnFirstUse||Ta(e)||Sre(e)>=10)return!1;const r=_V();return!(r&&r!==e)},Sre=e=>Ve().getObject(Ie.NEW_FEATURE_DISPLAY_COUNT)[e]??0,Ore=e=>{const t=Ve(),o=t.getObject(Ie.NEW_FEATURE_DISPLAY_COUNT);t.set(Ie.NEW_FEATURE_DISPLAY_COUNT,{...o,[e]:(o[e]??0)+1})},_V=()=>ir().get(Wt.NEW_FEATURE),Cre=e=>{ir().set(Wt.NEW_FEATURE,e)},Rre={bg:xU.black(.4),c:Fc.white,backdropFilter:"blur(4px)"},EV={"fill-mint":{border:ee.mint[500],bg:ee.mint[500],fg:ee.gray[0],divider:zi.gray[0](.5)},"fill-gray":{border:ee.gray[100],bg:ee.gray[100],fg:ee.gray[700],divider:zi.gray[0](.5)},"fill-tangerine":{border:ee.tangerine[500],bg:ee.tangerine[500],fg:ee.gray[0],divider:zi.gray[0](.5)},"fill-black-alpha":{border:"transparent",bg:xU.black(.4),fg:Fc.white,divider:zi.gray[0](.5)},"outline-mint":{border:ee.mint[500],bg:ee.gray[0],fg:ee.mint[600],divider:zi.mint[500](.5)},"outline-gray":{border:ee.gray[125],bg:ee.gray[0],fg:ee.gray[700],divider:zi.gray[125](.5)},"ghost-mint":{border:"transparent",bg:"transparent",fg:ee.mint[600],divider:zi.mint[500](.5)},"ghost-gray":{border:"transparent",bg:"transparent",fg:ee.gray[700],divider:zi.gray[700](.16)},"ghost-tangerine":{border:"transparent",bg:"transparent",fg:ee.tangerine[500],divider:zi.tangerine[500](.5)},"ghost-lemon":{border:"transparent",bg:"transparent",fg:ee.lemon[500],divider:zi.lemon[500](.5)},"ghost-white":{border:"transparent",bg:"transparent",fg:ee.gray[0],divider:zi.gray[0](.5)}},Are=e=>{const t=EV[e];return e==="fill-black-alpha"?{...Rre}:e.startsWith("fill")?{bg:t.bg,c:t.fg}:e.startsWith("outline")?{bg:t.bg,borderColor:t.border,c:t.fg}:{c:t.fg}},mV=e=>Object.fromEntries(e.map(t=>[t,Are(t)])),yre=mV(["fill-mint","fill-gray","fill-tangerine","fill-black-alpha","outline-mint","outline-gray","ghost-mint","ghost-gray","ghost-tangerine"]),vre=mV(["fill-mint","fill-gray","fill-tangerine","fill-black-alpha","outline-mint","outline-gray","ghost-mint","ghost-gray","ghost-tangerine","ghost-lemon","ghost-white"]),B_=e=>{const t=EV[e];return{"--seg-border":t.border,"--seg-bg":t.bg,"--seg-fg":t.fg,"--seg-divider":t.divider}},wre={"fill-mint":B_("fill-mint"),"fill-gray":B_("fill-gray"),"outline-mint":B_("outline-mint"),"outline-gray":B_("outline-gray")},kl={lg:{h:48,radius:12},md:{h:40,radius:12}
82,sm:{h:32,radius:10},xs:{h:24,radius:8}},Np={lg:{fontSize:16,fontWeight:700,lineHeight:"24px"},md:{fontSize:14,fontWeight:500,lineHeight:"20px"},sm:{fontSize:14,fontWeight:500,lineHeight:"20px"},xs:{fontSize:13,fontWeight:500,lineHeight:"19.5px"}},Pp={lg:{px:16,gap:6},md:{px:12,gap:6},sm:{px:8,gap:4},xs:{px:6,gap:4}},Nre={lg:{...kl.lg,...Np.lg,...Pp.lg},md:{...kl.md,...Np.md,...Pp.md},sm:{...kl.sm,...Np.sm,...Pp.sm},xs:{...kl.xs,...Np.xs,...Pp.xs}},K_=e=>{const{h:t,radius:o}=kl[e];return{w:t,h:t,radius:o}},Pre={lg:K_("lg"),md:K_("md"),sm:K_("sm"),xs:K_("xs")},rO=e=>{const t=Np[e];return{h:kl[e].h,radius:kl[e].radius,"--seg-fs":t.fontSize+"px","--seg-fw":""+t.fontWeight,"--seg-lh":t.lineHeight}},bre={sm:rO("sm"),md:rO("md"),lg:rO("lg")},EL=e=>{const{variant:t="fill-mint",size:o="md",tooltip:r,leftIcon:n,rightIcon:a,fullWidth:i=!1,pressed:s=!1,loading:x=!1,type:c="button",disabled:l,ref:d,...u}=e,{css:p,className:f,rest:E,children:T}=al(u);return b.jsx(M0,{content:r,children:b.jsxs(Lre,{ref:d,type:c,variant:t,size:o,fullWidth:i,pressed:s,disabled:l||x,"aria-busy":x,css:p,className:f,...E,children:[x?b.jsx(nO,{size:o,children:b.jsx(uU,{color:"currentColor",style:{margin:0}})}):n&&b.jsx(nO,{size:o,children:n}),T&&b.jsx(Mre,{children:T}),a&&b.jsx(nO,{size:o,children:a})]})})},Lre=xe("button",ZA,{...$A,...dU,...lU,w:"fit-content",whiteSpace:"nowrap",variants:{size:Nre,variant:yre,fullWidth:{true:{w:"100%",flexShrink:1}},pressed:{true:cU,false:{}}},defaultVariants:{variant:"fill-mint",size:"lg",pressed:!1}}),Mre=xe("span",{position:"relative",zIndex:1}),nO=xe("span",{position:"relative",zIndex:1,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,"& svg, & img":{display:"block",width:"100%",height:"100%"},variants:{size:{lg:{w:24,h:24},md:{w:20,h:20},sm:{w:16,h:16},xs:{w:16,h:16}}}}),Dre=xe("hr",{flexShrink:0,h:1,minH:1,border:"none",bg:ee.gray[125],my:4,px:4,backgroundClip:"content-box"}),kre=200,Fre=160,hV=4,IV=1,TV=({css:e,minWidth:t,...o})=>b.jsx(Ure,{...o,css:{minW:t,...e}}),Ure=xe(Xe,{flexDirection:"column",p:hV,bg:ee.gray[0],radius:12,border:`${IV}px solid ${ee.gray[100]}`,boxShadow:jX.md,z:ey.MODAL_DROPDOWN,outline:"none",fontFamily:"'Pretendard-Vrew', 'Noto Sans KR-Vrew', 'Noto Sans JP-Vrew', 'Noto Sans TC-Vrew', Helvetica, Arial, sans-serif",WebkitFontSmoothing:"antialiased",MozOsxFontSmoothing:"grayscale"}),Vre="var(--radix-dropdown-menu-trigger-width)",Gre=({side:e="bottom",align:t="start",sideOffset:o=4,alignOffset:r,preventAutoFocus:n,minWidth:a=kre,matchTriggerWidth:i,css:s,children:x})=>b.jsx(YU,{children:b.jsx(g9,{asChild:!0,side:e,align:t,sideOffset:o,alignOffset:r,...n&&{onOpenAutoFocus:c=>c.preventDefault()},onCloseAutoFocus:n?c=>c.preventDefault():void 0,children:b.jsx(TV,{minWidth:a,css:i?{minW:`max(${a}px, ${Vre})`,...s}:s,children:x})})}),Wre=({icon:e,children:t})=>b.jsxs(Hre,{children:[e&&b.jsx(Ux,{name:e,size:16,color:"currentColor"}),t]}),Hre=xe(_9,{display:"flex",alignItems:"flex-start",gap:4,width:0,minWidth:"100%",px:8,py:4,fontSize:12,fontWeight:400,lineHeight:"16px",whiteSpace:"normal",overflowWrap:"anywhere",c:ee.mint[600]}),SV=({icon:e,active:t,destructive:o,shortcut:r,tooltip:n,trailing:a,children:i,...s})=>{const x=b.jsxs(b.Fragment,{children:[e&&b.jsx(Ux,{name:e,size:16,color:"currentColor"}),i,r&&b.jsx(OV,{children:r}),a&&b.jsx(jre,{children:a})]});if(s.asButton){const{asButton:d,...u}=s;return b.jsx(M0,{content:n,children:b.jsx(zre,{active:t,destructive:o,...u,children:x})})}const{asButton:c,...l}=s;return b.jsx(M0,{content:n,children:b.jsx(RV,{active:t,destructive:o,...l,children:x})})},Pqe=({icon:e,shortcut:t,children:o,...r})=>b.jsxs(RV,{static:!0,...r,children:[e&&b.jsx(Ux,{name:e,size:16,color:"currentColor"}),o,t&&b.jsx(OV,{children:t})]}),jre=xe("span",{display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginLeft:"auto"}),OV=xe("span",{marginLeft:"auto",fontWeight:400,c:ee.gray[400]}),CV={position:"relative",display:"flex",alignItems:"center",gap:4,w:"100%",minH:32,px:8,py:4,border:"none",bg:"transparent",radius:8,cursor:"pointer",fontSize:14,fontWeight:500,lineHeight:"20px",c:ee.gray[900],textAlign:"left",outline:"none",userSelect:"none",overflow:"hidden",
82whiteSpace:"nowrap","&::after":{content:'""',position:"absolute",inset:0,borderRadius:"inherit",backgroundColor:ee.gray[900],opacity:0,transition:"opacity 0.1s ease-out",pointerEvents:"none"},'&:hover:not(:disabled)::after, &[data-highlighted]::after, &[data-state="open"]::after':{opacity:.06},"&:active:not(:disabled):not([data-disabled])::after":{opacity:.12},"&:disabled, &[data-disabled]":{cursor:"not-allowed",opacity:.36},"&:disabled::after, &[data-disabled]::after":{display:"none"},variants:{destructive:{true:{c:ee.tangerine[500]}},active:{true:{c:ee.mint[500]}},static:{true:{cursor:"default",c:ee.gray[550],"&::after":{display:"none"}}}}},RV=xe("div",CV),zre=xe("button",CV),Yre=({disabled:e,preventClose:t,onClick:o,...r})=>b.jsx(E9,{asChild:!0,disabled:e,onClick:n=>n.stopPropagation(),onSelect:n=>{t&&n.preventDefault(),o?.(n)},children:b.jsx(SV,{...r})}),Bre=(e,t,{wheel:o=!0}={})=>{it.useEffect(()=>{if(e)return o&&window.addEventListener("wheel",t,{passive:!0}),window.addEventListener("blur",t),()=>{o&&window.removeEventListener("wheel",t),window.removeEventListener("blur",t)}},[e,t,o])},Kre=({modal:e=!1,open:t,onOpenChange:o,shouldOpen:r,allowClick:n,children:a,...i})=>{const[s,x]=it.useState(r??!1),c=t!==void 0,l=(c?t:s)||(r??!1),d=it.useCallback(f=>{c||x(f),o?.(f)},[c,o]),u=it.useCallback(async f=>{if(n&&!await n(f)){d(!1);return}d(f)},[n,d]),p=it.useCallback(()=>d(!1),[d]);return Bre(l,p),b.jsx(m9,{open:l,modal:e,onOpenChange:u,...i,children:a})},Xre=2,Jre=Xre+hV+IV,qre=({children:e})=>b.jsx(YU,{children:b.jsx(h9,{asChild:!0,sideOffset:Jre,children:b.jsx(TV,{minWidth:Fre,children:e})})}),Qre=({disabled:e,...t})=>b.jsx(I9,{asChild:!0,disabled:e,children:b.jsx(SV,{...t,trailing:b.jsx(Ux,{name:"chevronRight",size:16,color:ee.gray[550]})})}),kE={Root:Kre,Trigger:T9,Content:Gre,Item:Yre,Separator:Dre,Sub:S9,SubTrigger:Qre,SubContent:qre,Description:Wre},AV={...$A,display:"flex",alignItems:"center",justifyContent:"center",border:"none",bg:"var(--seg-bg)",c:"var(--seg-fg)",cursor:"pointer","&:disabled":{cursor:"not-allowed"},"&:disabled span":{opacity:YX}},yV=xe(Xe,ZA,{display:"inline-flex",alignItems:"center",overflow:"hidden",bg:"var(--seg-bg)",border:"1px solid var(--seg-border)",radius:12,variants:{variant:wre,size:bre,fullWidth:{true:{display:"flex",w:"100%"}},disabled:{true:zX}}}),vV=xe("button",{...AV,flex:1,gap:6,h:"100%",minW:0,px:16}),wV=xe(Nt,{fontSize:"var(--seg-fs)",fontWeight:"var(--seg-fw)",lineHeight:"var(--seg-lh)",c:"inherit",whiteSpace:"nowrap"}),NV=xe("button",AV),PR=xe(Nt,{bg:"var(--seg-divider)",alignSelf:"center",variants:{orientation:{vertical:{w:1,h:"80%"},horizontal:{h:1,w:"60%"}}},defaultVariants:{orientation:"vertical"}}),Zre=({children:e,leftIcon:t,onClick:o,dropdown:r,dropdownMinWidth:n,placement:a="bottom",disabled:i=!1,variant:s="outline-mint",size:x="md",fullWidth:c=!1})=>{const[l,d]=it.useState(!1),u=it.useRef(null),[p,f]=it.useState(),E=T=>{T&&f(u.current?.offsetWidth),d(T)};return b.jsxs(kE.Root,{open:l,onOpenChange:E,children:[b.jsxs(yV,{ref:u,variant:s,size:x,disabled:i,fullWidth:c,children:[b.jsxs(ene,{type:"button",size:x,disabled:i,onClick:o,children:[t,b.jsx(wV,{children:e})]}),b.jsx(PR,{orientation:"vertical"}),b.jsx(kE.Trigger,{asChild:!0,disabled:i,children:b.jsx($re,{type:"button",size:x,children:b.jsx(Ux,{name:l?"chevronUp":"chevronDown",size:16,color:"currentColor"})})})]}),b.jsx(kE.Content,{side:a,align:"end",minWidth:n??p,children:r})]})},bqe=Object.assign(Zre,{Item:kE.Item}),$re=xe(NV,{flexShrink:0,h:"100%",'&[data-state="open"]::after':{opacity:.06},variants:{size:{sm:{w:32},md:{w:40},lg:{w:40}}}}),ene=xe(vV,{variants:{size:{sm:Pp.sm,md:{},lg:{}}}}),Lqe=({children:e,leftIcon:t,onClick:o,onIncrement:r,onDecrement:n,disabled:a=!1,loading:i=!1,incrementDisabled:s=!1,decrementDisabled:x=!1,incrementTooltip:c,decrementTooltip:l,className:d,onKeyDown:u,variant:p="outline-mint",size:f="md",fullWidth:E=!1})=>b.jsxs(yV,{className:d,variant:p,size:f,disabled:a,fullWidth:E,children:[b.jsxs(vV,{type:"button",disabled:a,"aria-busy":i,css:i?{pointerEvents:"none"}:void 0,onClick:i?void 0:o,onKeyDown:u,children:[i?b.jsx(uU,{color:"currentColor",style:{margin:0}}):t,b.jsx(wV,{children:e})]}),b.jsx(PR,{orientation:"vertical"}),b.jsxs(tne,{children:[b.jsx(M0,{content:c??void 0,children:b.jsx(mL,{children:b.jsx(hL,{type:"button",disabled:a||s,onClick:r,children:b.jsx(Ux,{name:"chevronUp",size:16,color:"currentColor"})})})}),b.jsx(PR,{orientation:"horizontal"}),b.jsx(M0,{content:l??void 0,children:b.jsx(mL,{children:b.jsx(hL,{type:"button",disabled:a||x,onClick:n,children:b.jsx(Ux,{name:"chevronDown",size:16,color:"currentColor"})})})})]})]}),tne=xe(Xe,{flexDirection:"column",w:40,h:"100%"}),mL=xe("span",{flex:1,display:"flex",minH:0}),hL=xe(NV,{w:"100%",h:"100%",minH:0}),Mqe=e=>{const{icon:t,variant:o="fill-gray",size:r="md",tooltip:n,pressed:a=!1,t
82ype:i="button",ref:s,children:x,...c}=e,{css:l,rest:d,className:u}=al(c);return b.jsx(M0,{content:n,children:b.jsx(rne,{ref:s,type:i,variant:o,size:r,pressed:a,css:l,className:u,...d,children:b.jsx(Ux,{name:t,size:one[r],color:"currentColor",pos:"relative",z:1})})})},one={lg:24,md:20,sm:16,xs:16},rne=xe("button",ZA,{...$A,...dU,...lU,variants:{size:Pre,variant:vre,pressed:{true:cU,false:{}}},[KX]:BX.button}),nne=({titleStringKey:e,descStringKey:t,confirm:o,cancel:r,checkbox:n})=>{const[a,i]=it.useState(n?.defaultChecked??!1),[s,x]=it.useState(!1),c=async l=>{if(!s){x(!0);try{await l()}finally{x(!1)}}};return b.jsxs(Xe,{w:"100%",direction:"column",gap:16,children:[b.jsxs(Xe,{direction:"column",gap:8,children:[b.jsx(Tb,{size:"h13",weight:600,children:A(e)}),t!==void 0&&b.jsx(Tb,{size:"h16",weight:400,color:ee.gray[850],children:A(t)})]}),n!==void 0&&b.jsx(pU,{checked:a,disabled:s,onCheckedChange:l=>{s||i(l===!0)},label:A(n.stringKey),size:"sm"}),b.jsxs(Xe,{gap:8,w:"100%",children:[b.jsx(EL,{variant:"fill-mint",fullWidth:!0,disabled:s,onClick:()=>{c(()=>o.onClick(n===void 0?void 0:a))},children:A(o.stringKey)}),b.jsx(EL,{variant:"outline-gray",fullWidth:!0,disabled:s,onClick:()=>{c(()=>r.onClick(n===void 0?void 0:a))},children:A(r.stringKey)})]})]})},ane=dre(1e3),Cf=O9,Dqe=R9,kqe=C9,ine={uid:"",name:"",email:"",parentEmail:"",emailVerified:!1,parentEmailVerified:!1,authUpdateCounter:0,userAccOverdubMonthly:0,userTrialAccOverdub:0,userCloudStorageLimit:y1,userTTSSpeakerLimit:v1,userOverdubLimit:Wh,credits:[]},PV=In({name:"user",initialState:ine,reducers:{setUser:(e,t)=>{const o=e.authUpdateCounter;Object.assign(e,t.payload),e.authUpdateCounter=o+1}}}),Fqe=PV.reducer,{setUser:Uqe}=PV.actions,Rf="/try/assets/ic_credit_new-C2dO8B1d.svg",bV="/try/assets/ic_eraser-DVz06xRy.svg",LV="/try/assets/ic_modal_close-BA-yEyr4.svg",sne="/try/assets/ic_credit_ai_image-DWVPTTIC.svg",xne="/try/assets/ic_credit_microphone-CHWOUob6.svg",cne="/try/assets/ic_credit_translate-6LsguD-G.svg",lne="/try/assets/ic_credit_voice-CJAwi77l.svg",bR=Object.values(ure[pre].classes).flatMap(e=>e!==void 0&&e.creditsPer100Chars>0?[e.creditsPer100Chars]:[]);if(bR.length===0)throw new Error("Current TTS pricing policy has no paid billing class");const dne=`${Bp/Math.max(...bR)}~${Bp/Math.min(...bR)}`,une=[{icon:xne,featureKey:"credit.exchange_transcription",value:String(gre.BASIC),valueKey:void 0,unitKey:"credit.exchange_unit_minute"},{icon:lne,featureKey:"credit.exchange_ai_voice",value:dne,valueKey:void 0,unitKey:"credit.exchange_unit_characters"},{icon:cne,featureKey:"credit.exchange_translation",value:String(uV),valueKey:void 0,unitKey:"credit.exchange_unit_characters"},{icon:sne,featureKey:"credit.exchange_ai_image_video",value:String(fre.BASIC),valueKey:void 0,unitKey:"credit.exchange_unit_image_video"}],MV=()=>{const[e,t]=it.useState(!1),o=it.useRef(null);return it.useEffect(()=>{e&&o.current?.scrollIntoView({behavior:"smooth",block:"nearest"})},[e]),b.jsxs(pne,{children:[b.jsxs(fne,{onClick:()=>t(r=>!r),children:[b.jsx(gne,{css:e?{transform:"rotate(90deg)"}:{},children:"›"}),b.jsx(_ne,{children:A("credit.accordion_title")})]}),e&&b.jsxs(Ene,{ref:o,children:[b.jsx(mne,{children:b.jsxs(A9,{i18nKey:"credit.accordion_what_you_get_with_credit",children:[b.jsx(Ine,{src:Rf}),b.jsx(hne,{children:A("credit.accordion_one_credit")})]})}),une.map(r=>b.jsxs(Tne,{children:[b.jsxs(Sne,{children:[b.jsx(fn,{w:16,h:16,src:r.icon,maskColor:ee.gray[750]}),b.jsx(Nt,{children:A(r.featureKey)})]}),b.jsx(One,{children:A(r.unitKey,{amount:r.value})})]},r.featureKey))]})]})},pne=xe(Nt,{w:"100%"}),fne=xe(Xe,{alignItems:"center",gap:4,cursor:"pointer","&:hover":{opacity:.8}}),gne=xe(Nt,{fontSize:16,fontWeight:500,c:ee.gray[550],w:20,textAlign:"center",transition:"transform 0.2s ease"}),_ne=xe(Nt,{fontSize:14,fontWeight:500,c:ee.gray[550]}),Ene=xe(Nt,{mt:12,border:`1px solid ${ee.gray[100]}`,borderRadius:20,overflow:"hidden"}),mne=xe(Xe,{alignItems:"center",justifyContent:"center",fontSize:13,fontWeight:500,c:ee.gray[550],bg:ee.gray[25],borderBottom:`1px solid ${ee.gray[100]}`,px:20,py:12}
82),hne=xe(Nt,{fontSize:13,fontWeight:700,c:ee.gray[850]}),Ine=xe(fn,{w:16,h:16,bg:ee.mint[500],mx:2,verticalAlign:"middle"}),Tne=xe(Xe,{alignItems:"center",gap:12,px:20,py:16,borderBottom:`1px solid ${ee.gray[100]}`,"&:last-child":{borderBottom:"none"}}),Sne=xe(Xe,{flex:1,alignItems:"center",gap:4,fontSize:14,fontWeight:500,c:ee.gray[850]}),One=xe(Nt,{fontSize:13,fontWeight:500,c:ee.gray[550]}),DV=xe(Xe,{position:"fixed",top:0,left:0,right:0,bottom:0,bg:"rgba(0, 0, 0, 0.3)",alignItems:"center",justifyContent:"center",zIndex:ey.MODAL_OVERLAY}),kV=xe(Xe,{flexDirection:"column",bg:ee.gray[0],borderRadius:20,w:440,boxShadow:"0px 8px 28px 0px rgba(0, 0, 0, 0.1)",userSelect:"none"}),FV=xe(Xe,{alignItems:"center",justifyContent:"space-between",pl:28,pr:20,pt:20,pb:16,flexShrink:0}),UV=xe(Nt,{fontSize:20,fontWeight:700,lineHeight:"29px",c:ee.gray[850]}),VV=xe(Xe,{w:32,h:32,alignItems:"center",justifyContent:"center",cursor:"pointer",borderRadius:8,flexShrink:0,"&:hover":{bg:ee.gray[50]}}),GV=xe(Xe,{flexDirection:"column",gap:24,p:28,flex:1,overflowY:"auto",minH:0}),WV=xe(Nt,{fontSize:16,fontWeight:400,lineHeight:"24px",c:ee.gray[850]}),HV=xe(Xe,{gap:8,px:28,pt:16,pb:28,flexShrink:0}),jV=xe(Xe,{flex:1,h:40,minW:120,bg:ee.gray[100],borderRadius:8,alignItems:"center",justifyContent:"center",fontSize:14,fontWeight:500,c:ee.gray[750],cursor:"pointer","&:hover":{bg:ee.gray[125]}}),zV=xe(Xe,{flex:1,h:40,minW:120,bg:ee.mint[500],borderRadius:8,alignItems:"center",justifyContent:"center",gap:8,fontSize:14,fontWeight:500,c:Fc.gray[0],cursor:"pointer","&:hover":{bg:ee.mint[550]}}),YV=xe(Xe,{alignItems:"center",gap:4,fontSize:13,fontWeight:500,lineHeight:"19.5px",c:ee.gray[550]}),Cne=({myCredits:e,creditsRequired:t,isEraserAvailable:o,hideRequired:r=!1,onClose:n,onAction:a})=>{const i=Cf(D2),s=Cf(bN),x=eG(i,s),c=o?A("credit.not_enough_desc_eraser"):A("credit.not_enough_desc_upgrade"),l=o?A("credit.usage_history_eraser"):A("credit.upgrade");return b.jsx(DV,{children:b.jsxs(Rne,{onClick:d=>d.stopPropagation(),children:[b.jsxs(FV,{children:[b.jsx(UV,{children:A("credit.not_enough_title")}),b.jsx(VV,{onClick:n,children:b.jsx(fn,{src:LV,w:20,h:20,maskColor:ee.gray[500]})})]}),b.jsxs(GV,{children:[b.jsx(WV,{children:c}),b.jsxs(Ane,{children:[b.jsxs(Xe,{gap:12,children:[b.jsxs(IL,{children:[b.jsx(TL,{children:A("credit.remaining_credits")}),b.jsxs(Xe,{align:"center",gap:2,children:[b.jsx(fn,{src:Rf,w:20,h:20,maskColor:Fc.tangerine[600]}),b.jsx(yne,{children:Wy(e)})]})]}),!r&&b.jsxs(IL,{children:[b.jsx(TL,{children:A("credit.required")}),b.jsxs(Xe,{align:"center",gap:2,children:[b.jsx(fn,{src:Rf,w:20,h:20,maskColor:ee.gray[850]}),b.jsx(vne,{children:Jne(t)})]})]})]}),b.jsxs(YV,{children:[b.jsx(fn,{src:Oy,w:16,h:16,maskColor:ee.gray[550]}),b.jsx(Nt,{children:A("credit.next_recharge",{date:x,interpolation:{escapeValue:!1}})})]})]}),b.jsx(MV,{})]}),b.jsxs(HV,{children:[b.jsx(jV,{onClick:n,children:A("credit.cancel")}),b.jsxs(zV,{onClick:a,children:[o?b.jsx(fn,{maskColor:"white",src:bV,w:16,h:16}):b.jsx(fn,{maskColor:"white",src:Ry,w:20,h:20}),b.jsx(Nt,{children:l})]})]})]})})},Rne=xe(kV,{h:440}),Ane=xe(Xe,{flexDirection:"column",gap:12,bg:ee.gray[50],borderRadius:20,p:12}),IL=xe(Xe,{flex:1,flexDirection:"column",gap:6,bg:ee.gray[0],border:`1px solid ${ee.gray[100]}`,borderRadius:16,p:16}),TL=xe(Nt,{fontSize:13,fontWeight:500,lineHeight:"19.5px",c:ee.gray[550]}),yne=xe(Nt,{fontSize:20,fontWeight:500,lineHeight:"29px",c:Fc.tangerine[600]}),vne=xe(Nt,{fontSize:20,fontWeight:500,lineHeight:"29px",c:ee.gray[850]}),wne=({remaining:e,total:t,barColor:o="mint"})=>{const r=t>0?(t-e)/t:0,n=$t(Math.floor(r*100),0,100),a=o==="tangerine"?ee.tangerine[400]:ee.mint[500];return b.jsx(Nne,{children:b.jsx(Pne,{css:{width:`${n}%`,background:a}})})},Nne=xe(Nt,{h:6,w:"100%",bg:ee.gray[125],borderRadius:999,overflow:"hidden"}),Pne=xe(Nt,{h:6,borderRadius:999,transition:"width 0.3s ease"}),bne=(e,t)=>{const o=e===2;return o&&!t?A("credit.warning_low_upgrade"):o&&t?A("credit.warning_low_eraser"):!o&&!t?A("credit.warning_usage_upgrade"):A("credit.warning_usage_eraser")},Lne=({tier:e,usagePercent:t,totalCredits:o,isEraserAvailable:r,onClose:n,onAction:a})=>{const i=Cf(D2),s=Cf(bN),x=eG(i,s),c=e===2?"tangerine":"mint",l=Math.round(o*(1-t/100)),d=r?A("credit.usage_history_eraser"):A("credit.upgrade"),u=bne(e,r);return b.jsx(DV,{children:b.jsxs(Mne,{onClick:p=>p.stopPropagation(),children:[b.jsxs(FV,{children:[b.jsx(UV,{children:A("credit.warning_title",{percent:t})}),b.jsx(VV,{onClick:n,children:b.jsx(fn,{src:LV,w:20,h:20,maskColor:ee.gray[500]})})]}
82),b.jsxs(GV,{children:[b.jsx(WV,{children:u}),b.jsxs(Dne,{children:[b.jsxs(Xe,{direction:"column",gap:12,children:[b.jsxs(Xe,{align:"center",gap:4,children:[b.jsx(fn,{src:Rf,w:16,h:16,maskColor:ee.gray[850]}),b.jsx(kne,{children:A("credit.percent_used",{percent:t})})]}),b.jsxs(Xe,{direction:"column",gap:4,children:[b.jsx(wne,{remaining:l,total:o,barColor:c}),b.jsxs(Xe,{align:"center",gap:2,css:{alignSelf:"flex-end"},children:[b.jsx(fn,{src:Rf,w:12,h:12,maskColor:ee.gray[600]}),b.jsx(Fne,{children:A("credit.total_per_month",{total:Wy(o)})})]})]})]}),b.jsxs(YV,{children:[b.jsx(fn,{src:Oy,w:16,h:16,maskColor:ee.gray[550]}),b.jsx(Nt,{children:A("credit.next_recharge",{date:x,interpolation:{escapeValue:!1}})})]})]}),b.jsx(MV,{})]}),b.jsxs(HV,{children:[b.jsx(jV,{onClick:n,children:A("credit.maybe_later")}),b.jsxs(zV,{onClick:a,children:[r?b.jsx(fn,{maskColor:"white",src:bV,w:16,h:16}):b.jsx(fn,{maskColor:"white",src:Ry,w:20,h:20}),b.jsx(Nt,{children:d})]})]})]})})},Mne=xe(kV,{h:440}),Dne=xe(Xe,{flexDirection:"column",gap:8,bg:ee.gray[25],border:`1px solid ${ee.gray[100]}`,borderRadius:16,p:16}),kne=xe(Nt,{fontSize:15,fontWeight:500,lineHeight:"22px",c:ee.gray[850]}),Fne=xe(Nt,{fontSize:12,fontWeight:400,lineHeight:"16px",c:ee.gray[550]}),Aa={FREE:0,LIGHT:1,STANDARD:2,BUSINESS:3,CUSTOM:4},Une={[Ut.DELETE_VREW_MARK]:Aa.LIGHT,[Ut.GENERATE_IMAGE_DOWNLOAD]:Aa.LIGHT,[Ut.GENERATE_VIDEO_DOWNLOAD]:Aa.LIGHT,[Ut.GENERATE_IMAGE_ONE_TIME_LIMIT]:Aa.LIGHT,[Ut.SHARED_CLIPBOARD]:Aa.STANDARD,[Ut.USER_FRAMEPACK]:Aa.STANDARD,[Ut.TTS_CLIP_MAX_INPUT]:Aa.LIGHT,[Ut.ADVANCED_AI_WRITING]:Aa.STANDARD,[Ut.CHARACTER_ANIMATION]:Aa.STANDARD,[Ut.VCLOUD]:Aa.LIGHT,[Ut.USER_TTS_SPEAKER]:Aa.FREE,[Ut.TTV_SCRIPT_LIMIT]:Aa.LIGHT,[Ut.USAGE_ERASER]:Aa.STANDARD,[Ut.OVERDUB]:Aa.STANDARD};class Vne{currentUserPlan=void 0;isPlanTypeValid=t=>Object.keys(Aa).includes(t);initialize=t=>{if(!this.isPlanTypeValid(t)){this.currentUserPlan="FREE";return}this.currentUserPlan=t};updateCurrentUserPlan=t=>{this.currentUserPlan=t};isPremiumFeatureAvailable=t=>{if(Mo().getDebugVal(Xt.SKIP_STANDARD_PLAN_CHECK),!this.currentUserPlan)return!1;const o=Une[t];return Aa[this.currentUserPlan]>=o}}let aO;const ba=()=>(!aO&&(aO=new Vne),aO),Kh=e=>{switch(e){case Ut.SHARED_CLIPBOARD:return"copy_paste";case Ut.USER_FRAMEPACK:return"user_template";case Ut.DELETE_VREW_MARK:return"vrew_mark";case Ut.ADVANCED_AI_WRITING:return"ai_writing";case Ut.GENERATE_IMAGE_DOWNLOAD:return"ai_image_download";case Ut.GENERATE_VIDEO_DOWNLOAD:return"ai_video_download";case Ut.CHARACTER_ANIMATION:return"character_animation";case Ut.GENERATE_IMAGE_ONE_TIME_LIMIT:return"image_onetime_limit";case Ut.TTS_CLIP_MAX_INPUT:return"tts_clip_max_input";case Ut.VCLOUD:return"vcloud";case Ut.TTV_SCRIPT_LIMIT:return"ttv_script_limit";case Ut.USER_TTS_SPEAKER:return"user_tts_speaker";case Ut.OVERDUB:return"overdub";default:return"unknown"}},Xh=async e=>{const t=be().getUserInfo()?.uid;if(t===void 0){h("premiumFeatureManager.ts").error("uid is undefined");return}if(await wo()){const o={uid:t,featureType:e};try{const r=await jf("/premium-feature-usage",{method:"POST",body:JSON.stringify(o)}).then(n=>{if(!n.ok)throw new Error("Error response at recordPremiumFeatureUsage. status: "+n.status);return n.json()});if(r.result==="error")throw r}catch(r){h("premiumFeatureManager.ts").error("/premium-feature-usage api failed for "+t+" : "+P(r))}}else{h("premiumFeatureManager.ts").error("user not logged in.");return}},BV=e=>
82{const t=$e().getUserTTSSpeakers();if(e.provider===Oe.UserTTS){const o=t?.find(r=>r.speakerId===e.speakerId);if(o)return o}return e},Af=(e,t)=>{if(e===Oe.UserTTS){const a=$e().getUserTTSSpeakers()?.find(i=>i.speakerId===t);return a?.provider===e?a:void 0}const o=$e().getStockTTSSpeakerList();if(!o)return;const r=e===Oe.VrewVA_deprecated?Oe.Vrew:e,n=Object.values(o.allVoices[r]??{}).find(a=>a.speakerId===t);return n?.provider===r?n:void 0},KV=e=>{const t=$e().getStockTTSSpeakerList();if(!t)return;for(const n of Object.values(t.allVoices)){const a=Object.values(n).find(i=>i.speakerId===e);if(a)return a}return $e().getUserTTSSpeakers()?.find(n=>n.speakerId===e)},Gne=3e4,Gy=(e,t)=>e+":"+t,SL=e=>{const t=new Map;for(const o of e?.groups??[])for(const r of o.speakers)t.set(Gy(r.provider,r.speakerId),o.creditsPer100Chars);return t};class Wne{latestTTSDiscountResponse;latestTTSDiscountUid;displayedRegularPricingPolicyVersion;latestRefreshRequestId=0;listeners=new Set;authSyncPromise;inflightRefresh;lastRefresh;getCurrentUid=()=>be().getUserInfo()?.uid;getDiscountResponse=t=>t!==void 0&&this.latestTTSDiscountUid===t?this.latestTTSDiscountResponse:void 0;setDiscountResponse=(t,o)=>{this.latestTTSDiscountResponse=t,this.latestTTSDiscountUid=o,this.listeners.forEach(r=>r())};clearCache=()=>{this.latestRefreshRequestId+=1,this.latestTTSDiscountResponse=void 0,this.latestTTSDiscountUid=void 0,this.inflightRefresh=void 0,this.lastRefresh=void 0,this.listeners.forEach(t=>t())};getKnownRegularPricingPolicyVersion=(t=!0)=>{const o=$e().getStockTTSSpeakerList()?.pricingPolicyVersion;return t?this.displayedRegularPricingPolicyVersion??o:o};hasCurrentPricing=(t,o=!0)=>{const r=this.getDiscountResponse(t);return r!==void 0&&r.pricingPolicyVersion===this.getKnownRegularPricingPolicyVersion(o)};getDiscountMapForUid=(t,o)=>{if(t===void 0)return SL(void 0);const r=this.getDiscountResponse(t);return SL(r?.pricingPolicyVersion===o?r:void 0)};getDiscountMap=t=>this.getDiscountMapForUid(this.getCurrentUid(),t);getDiscountedPrice=(t,o,r,n)=>this.getDiscountMapForUid(t,o).get(Gy(r,n));shouldRefreshForAppliedPricing=(t,o,r)=>{if(t===void 0||o===void 0)return!1;const n=Af(t.provider,t.speakerId)?.creditsPer100Chars,a=this.getDiscountedPrice(r??this.getCurrentUid(),o.pricingPolicyVersion,t.provider,t.speakerId)??n;return t.pricingPolicyVersion===o.pricingPolicyVersion&&t.discountPolicyVersion!==o.discountPolicyVersion||a!==void 0&&t.creditsPer100Chars<a};getExpectedPricing=({provider:t,speakerId:o,uid:r=this.getCurrentUid()})=>{const n=$e().getStockTTSSpeakerList(),a=this.displayedRegularPricingPolicyVersion??n?.pricingPolicyVersion,i=this.getDiscountResponse(r);if(a===void 0)return;if(i===void 0||i.pricingPolicyVersion!==a)return{pricingPolicyVersion:a,discountPolicyVersion:null};const s=this.getDiscountedPrice(r,a,t,o);return{pricingPolicyVersion:i.pricingPolicyVersion,discountPolicyVersion:s!==void 0?i.discountPolicyVersion:null}};setDisplayedRegularPricingPolicyVersion=t=>{this.displayedRegularPricingPolicyVersion=t};clearDisplayedRegularPricingPolicyVersion=t=>{this.displayedRegularPricingPolicyVersion===t&&(this.displayedRegularPricingPolicyVersion=void 0)};refreshCurrentUserDiscounts=({waitForStockPricing:t=!1,force:o=!1}={})=>{const r=this.getCurrentUid();if(r===void 0)return Promise.resolve(!1);if(this.inflightRefresh?.uid===r&&(this.inflightRefresh.waitForStockPricing||!t))return this.inflightRefresh.promise;this.lastRefresh?.uid!==r&&(this.lastRefresh=void 0);const n=this.lastRefresh?.completedAt;if(!o&&n!==void 0&&Date.now()-n<Gne)return Promise.resolve(this.hasCurrentPricing(r,!1));const a=++this.latestRefreshRequestId,i=(async()=>{const s=await KOe();if(a!==this.latestRefreshRequestId||r!==this.getCurrentUid()||s===void 0)return!1;const x=$e();return this.getKnownRegularPricingPolicyVersion(!t)!==s.pricingPolicyVersion&&(await x.refetchStockTTSSpeakerList(),a!==this.latestRefreshRequestId||r!==this.getCurrentUid()||this.getKnownRegularPricingPolicyVersion(!1)!==s.pricingPolicyVersion)?!1:(this.setDiscountResponse(s,r),!0)})().catch(()=>!1).finally(()=>{this.inflightRefresh?.promise===i&&(this.inflightRefresh=void 0),a===this.latestRefreshRequestId&&(this.lastRefresh={uid:r,completedAt:Date.now()})});return this.inflightRefresh={uid:r,waitForStockPricing:t,promise:i},i};ensureAuthSync=()=>(this.authSyncPromise===void 0&&(this.authSyncPromise=sR(()=>Promise.resolve().then(()=>nre),void 0).then(({AuthEvent:t,getAuthEventEmitter:o})=>{const r=o();r.on(t.SIGN_IN,()=>
82{this.refreshCurrentUserDiscounts({waitForStockPricing:!0,force:!0})}),r.on(t.SIGN_OUT,this.clearCache)})),this.authSyncPromise);initialize=async()=>{await this.ensureAuthSync(),await be().waitUntilInitialized(),this.getCurrentUid()!==void 0&&await this.refreshCurrentUserDiscounts({waitForStockPricing:!0})};refresh=async({force:t=!1}={})=>{await this.ensureAuthSync(),await this.refreshCurrentUserDiscounts({force:t})};ensurePricingLoaded=async t=>(await this.ensureAuthSync(),t!==this.getCurrentUid()?!1:this.hasCurrentPricing(t,!1)?!0:(await this.refreshCurrentUserDiscounts({waitForStockPricing:!0}),this.hasCurrentPricing(t,!1)));subscribe=t=>(this.listeners.add(t),()=>{this.listeners.delete(t)})}let OL;const Yl=()=>(OL??=new Wne,OL),XV=e=>{if(!e||e.provider===Oe.UserTTS)return!1;const t=Af(e.provider,e.speakerId),o=$e().getStockTTSSpeakerList()?.pricingPolicyVersion;return t===void 0||o!==e.pricingPolicyVersion||e.discountPolicyVersion===null&&t.creditsPer100Chars!==e.creditsPer100Chars},Hne=(e,t)=>{const o=Af(e,t);if(!o)throw new C(_.C_TTS_FETCH_SPEAKER_LIST_ERROR,void 0,"Cannot resolve TTS pricing for speaker: "+t);const r=$e().getStockTTSSpeakerList()?.pricingPolicyVersion;return(r===void 0?void 0:Yl().getDiscountMap(r).get(Gy(e,t)))??o.creditsPer100Chars},JV=e=>{const{creditsPer100Chars:t,...o}=e;return o},qV=e=>({...e,speaker:JV(e.speaker)});var hg=(e=>(e.TTS="tts",e.STT="stt",e.CAPTION_CORRECTION="caption_correction",e.TRANSLATE="translate",e.DENOISE="denoise",e.TTV="ttv",e.AI_IMAGE_GENERATE="ai_image_generate",e.AI_VIDEO_GENERATE="ai_video_generate",e.AI_IMAGE_AUTO_INSERT_CONTEXT="ai_image_auto_insert_context",e.AI_IMAGE_AUTO_INSERT_PANEL="ai_image_auto_insert_panel",e.AI_IMAGE_AUTO_INSERT_STT_MODAL="ai_image_auto_insert_stt_modal",e.AI_STYLIZED_CAPTION="ai_stylized_caption",e.VREW_AGENT="vrew_agent",e.AGENT_AI_IMAGE="agent_ai_image",e.AGENT_AI_VIDEO="agent_ai_video",e.THUMBNAIL_GENERATOR="thumbnail_generator",e.ATV="atv",e.VIDEO_REMIX="video_remix",e.CHARACTER_STUDIO_TEXT="character_studio_text",e.CHARACTER_STUDIO_IMAGE="character_studio_image",e.CHARACTER_STUDIO_POSE="character_studio_pose",e.DEBUG="debug",e))(hg||{});const QV={STT:{DEFAULT:"AI Transcription",BASIC:"AI Transcription",PLUS:"AI Transcription",MIGRATION:"AI Transcription"},CAPTION_CORRECTION:{DEFAULT:"AI Caption Correction"},DENOISE:{DEFAULT:"AI Transcription"},TTS:{DEFAULT:"AI Voice Generation",MIGRATION:"AI Voice Generation"},TRANSLATE:{DEFAULT:"AI Translation",MIGRATION:"AI Translation"},AI_IMAGE:{BASIC:"AI Image/Video",PRO:"AI Image/Video",PLUS:"AI Image/Video",BASIC_UPSCALE:"AI Image/Video",PRO_UPSCALE:"AI Image/Video",PLUS_UPSCALE:"AI Image/Video",SDXL:"AI Image/Video",SDXL_UPSCALE:"AI Image/Video",FLUX_2_KLEIN:"AI Image/Video",FLUX_1_DEV:"AI Image/Video",FLUX_1_DEV_UPSCALE:"AI Image/Video",GPT_IMAGE_2_LOW:"AI Image/Video",GPT_IMAGE_2_LOW_UPSCALE:"AI Image/Video",GPT_IMAGE_2_LOW_HIGHRES:"AI Image/Video",FLUX_1_1_PRO:"AI Image/Video",FLUX_1_1_PRO_UPSCALE:"AI Image/Video",SEEDREAM:"AI Image/Video",SEEDREAM_UPSCALE:"AI Image/Video",SEEDREAM_HIGHRES:"AI Image/Video",GPT_IMAGE_2_MEDIUM:"AI Image/Video",GPT_IMAGE_2_MEDIUM_UPSCALE:"AI Image/Video",GPT_IMAGE_2_MEDIUM_HIGHRES:"AI Image/Video",MIGRATION:"AI Image/Video"},AI_STYLIZED_CAPTION:{AI_STYLIZED_CAPTION_CREATE:"AI Stylized Caption",AI_STYLIZED_CAPTION_MODIFY:"AI Stylized Caption",AI_STYLIZED_CAPTION_CREATE_PROMO_260617:"AI Stylized Caption",AI_STYLIZED_CAPTION_MODIFY_PROMO_260617:"AI Stylized Caption"},AI_VIDEO:{BASIC:"AI Image/Video",PRO:"AI Image/Video",PRO_ARCHIVE:"AI Image/Video",SEEDANCE_1_PRO:"AI Image/Video",SEEDANCE_1_5_PRO:"AI Image/Video",SEEDANCE_1_5_PRO_ARCHIVE:"AI Image/Video",KLING_V3:"AI Image/Video",KLING_V3_ARCHIVE:"AI Image/Video",SEEDANCE_2_0:"AI Image/Video",SEEDANCE_2_0_ARCHIVE:"AI Image/Video",SEEDANCE_2_0_FAST:"AI Image/Video",SEEDANCE_2_0_FAST_ARCHIVE:"AI Image/Video",SEEDANCE_2_0_MINI:"AI Image/Video",SEEDANCE_2_0_MINI_ARCHIVE:"AI Image/Video",VEO_3_1:"AI Image/Video",VEO_3_1_ARCHIVE:"AI Image/Video",VEO_3_1_FAST:"AI Image/Video",VEO_3_1_FAST_ARCHIVE:"AI Image/Video",VEO_3_1_LITE:"AI Image/Video",VEO_3_1_LITE_ARCHIVE:"AI Image/Video",SEEDANCE_1_PRO_REGULAR_V2:"AI Image/Video",SEEDANCE_1_5_PRO_REGULAR_V2:"AI Image/Video",SEEDANCE_1_5_PRO_ARCHIVE_REGULAR_V2:"AI Image/Video",KLING_V3_REGULAR_V2:"AI Image/Video",KLING_V3_ARCHIVE_REGULAR_V2:"AI Image/Video",GEMINI_OMNI_FLASH_REGULAR_V2:"AI Image/Video",GEMINI_OMNI_FLASH_ARCHIVE_REGULAR_V2:"AI Image/Video",SEEDANCE_2_0_REGULAR_V2:"AI Image/Video",SEEDANCE_2_0_ARCHIVE_REGULAR_V2:"AI Image/Video",SEEDANCE_2_0_FAST_REGULAR_V2:"AI Image/Video",SEEDANCE_2_0_FAST_ARCHIVE_REGULAR_V2:"AI Image/Video",SEEDANCE_2_0_MINI_REGULAR_V2:"AI Image/Video",SEEDANCE_2_0_MINI_ARCHIVE_REGULAR_V2:"AI Image/Video",SEEDANCE_2_5_REGULAR_V2:"AI Image/Video",SEEDANCE_2_5_ARCHIVE_REGULAR_V2:"AI Image/Video",VEO_3_1_REGULAR_V2:"AI Image/Video",VEO_3_1_ARCHIVE_REGULAR_V2:"AI Image/Video",VEO_3_1_FAST_REGULAR_V2:"AI Image/Video",VEO_3_1_FAST_ARCHIVE_REGULAR_V2:"AI Image/Video",VEO_3_1_LITE_REGULAR_V2:"AI Image/Video",VEO_3_1_LITE_ARCHIVE_REGULAR_V2:"AI Image/Video",SEEDANCE_2_0_PROMO_V1:"AI Image/Video",SEEDANCE_2_0_ARCHIVE_PROMO_V1:"AI Image/Video",SEEDANCE_2_0_FAST_PROMO_V1:"AI Image/Video",SEEDANCE_2_0_FAST_ARCHIVE_PROMO_V1:"AI Image/Video",SEEDANCE_2_0_MINI_PROMO_V1:"AI Image/Video",SEEDANCE_2_0_MINI_ARCHIVE_PROMO_V1:"AI Image/Video",KLING_V3_PROMO_V1:"AI Image/Video",KLING_V3_ARCHIVE_PROMO_V1:"AI Image/Video",VEO_3_1_PROMO_V1:"AI Image/Video",VEO_3_1_ARCHIVE_PROMO_V1:"AI Image/Video",VEO_3_1_FAST_PROMO_V1:"AI Image/Video",VEO_3_1_FAST_ARCHIVE_PROMO_V1:"AI Image/Video",VEO_3_1_LITE_PROMO_V1:"AI Image/Video",VEO_3_1_LITE_ARCHIVE_PROMO_V1:"AI Image/Video",SEEDANCE_2_0_PROMO_V2:"AI Image/Video",SEEDANCE_2_0_ARCHIVE_PROMO_V2:"AI Image/Video",SEEDANCE_2_0_FAST_PROMO_V2:"AI Image/Video",SEEDANCE_2_0_FAST_ARCHIVE_PROMO_V2:"AI Image/Video",SEEDANCE_2_0_MINI_PROMO_V2:"AI Image/Video",SEEDANCE_2_0_MINI_ARCHIVE_PROMO_V2:"AI Image/Video",SEEDANCE_2_5_PROMO_V2:"AI Image/Video",SEEDANCE_2_5_ARCHIVE_PROMO_V2:"AI Image/Video",KLING_V3_PROMO_V2:"AI Image/Video",KLING_V3_ARCHIVE_PROMO_V2:"AI Image/Video",GEMINI_OMNI_FLASH_PROMO_V2:"AI Image/Video",GEMINI_OMNI_FLASH_ARCHIVE_PROMO_V2:"AI Image/Video",VEO_3_1_PROMO_V2:"AI Image/Video",VEO_3_1_ARCHIVE_PROMO_V2:"AI Image/Video",VEO_3_1_FAST_PROMO_V2:"AI Image/Video",VEO_3_1_FAST_ARCHIVE_PROMO_V2:"AI Image/Video",VEO_3_1_LITE_PROMO_V2:"AI Image/Video",VEO_3_1_LITE_ARCHIVE_PROMO_V2:"AI Image/Video"},VIDEO_ANALYSIS:{DEFAULT:"AI Image/Video"},AI_CHARACTER:{LIP_OPEN:"AI Image/Video",LIP_CLOSED:"AI Image/Video",POSE:"AI Image/Video"}
82,VREW_AGENT:"Vrew Agent",COUPON:{BONUS:"Bonus Code",ADMIN_ADJUST:"Admin Adjust"},USAGE_ERASER:{DEFAULT:"Usage Eraser"},PLAN:null},Vqe=e=>{const t=QV[e];if(!t)return null;if(typeof t=="string")return t;const o=new Set(Object.values(t));return o.size===1?[...o][0]:null},Gqe=["AI Transcription","AI Caption Correction","AI Voice Generation","AI Translation","AI Image/Video","Vrew Agent","AI Stylized Caption","Bonus Code","Admin Adjust","Usage Eraser"],Wqe={"AI Transcription":"credit.exchange_transcription","AI Caption Correction":"credit.exchange_caption_correction","AI Voice Generation":"credit.exchange_ai_voice","AI Translation":"credit.exchange_translation","AI Image/Video":"credit.exchange_ai_image_video","Vrew Agent":"credit.exchange_vrew_agent","AI Stylized Caption":"credit.exchange_ai_stylized_caption","Bonus Code":"credit.filter_bonus_code","Admin Adjust":"credit.filter_admin_adjust","Usage Eraser":"credit.filter_usage_eraser"},jne=e=>e===0?0:e>0?Math.floor(e*vc)/vc:-(Math.floor(-e*vc)/vc),zne=(e,t)=>jne(e/t),Yne=(e,t)=>{if(!Number.isSafeInteger(e)||e<0)throw new Error("Invalid TTS character count: "+e);if(!Number.isSafeInteger(t)||t<0||t>pV)throw new Error("Invalid TTS price: "+t);if(!Number.isSafeInteger(vc)||vc<=0||!Number.isSafeInteger(Bp)||Bp<=0)throw new Error("Invalid TTS credit precision configuration");const o=vc/Bp;if(!Number.isSafeInteger(o)||o<=0)throw new Error("Invalid TTS credit precision configuration");if(t>0&&e>Math.floor(Number.MAX_SAFE_INTEGER/t))throw new Error("TTS credit amount is too large");const r=e*t;if(r>Math.floor(Number.MAX_SAFE_INTEGER/o))throw new Error("TTS credit amount is too large");return r*o},Bne=(e,t)=>Yne(e,t)/vc,LR=(e,t,o)=>Bne(e,Hne(t,o)),Kne=(e,t)=>{const o=zy(e,t);if(!o)return;const r=o.expireAt,n=Mt(ke.CREDIT_WARNING_EXPIRE_AT);r!==n&&(po(ke.CREDIT_WARNING_THRESHOLDS,L1),po(ke.CREDIT_WARNING_EXPIRE_AT,r))},ZV=async(e,t,o,r,n=!1)=>{const a=Y();await new Promise(i=>{const s=()=>{a.closeLastShownMessage(),i()},x=()=>{if(a.closeLastShownMessage(),i(),o)HN(g.LIMIT_POPUP);
82else{const l=be().getUserInfo()?.uid??"";AT(l,{source:g.LIMIT_POPUP,origin:{type:"usage_limit",creditTrigger:r}})}},c={title:"",showFooterButtons:!1,content:jt.createElement(Cne,{myCredits:e,creditsRequired:t,isEraserAvailable:o,hideRequired:n,onClose:s,onAction:x})};a.popup(c,()=>i())})},Xne=async(e,t,o,r,n)=>{const a=Y();await new Promise(i=>{const s=()=>{a.closeLastShownMessage(),i()},x=()=>{if(a.closeLastShownMessage(),i(),r)HN(g.LIMIT_POPUP);else{const l=be().getUserInfo()?.uid??"";AT(l,{source:g.LIMIT_POPUP,origin:{type:"usage_limit",creditTrigger:n}})}},c={title:"",showFooterButtons:!1,content:jt.createElement(Lne,{tier:e,usagePercent:t,totalCredits:o,isEraserAvailable:r,onClose:s,onAction:x})};a.popup(c,()=>i())})},$V=()=>(Mo().getDebugVal(Xt.DISABLE_QUOTA),!Vr()||Mo().getDebugVal(Xt.SET_QUOTA)!==void 0),Jh=async(e,t)=>{if(!$V())return!1;if(!await Vn("checkAndAlertQuota"))return!0;let o;try{o=(await be().fetchUserInfo())?.credits}catch(c){return h("credit.ts").error("[credit] checkAndAlertQuota: fetchUserInfo failed, blocking operation",c),!0}if(!o||o.length===0)return h("credit.ts").error("[credit] checkAndAlertQuota: empty credits, blocking operation"),!0;const r=Ig(o)??0,n=jy(o)??0,a=ba().isPremiumFeatureAvailable(Ut.USAGE_ERASER);if(Mo().getDebugVal(Xt.CHECK_CREDIT),e>r)return Bz(r,e,t),await ZV(r,e,a,t),!0;const i=Number.isFinite(r)&&Number.isFinite(n)&&n>0?Math.min(1,Math.max(0,1-r/n)):0,s=Mt(ke.CREDIT_WARNING_THRESHOLDS);if(!Array.isArray(s)||s.length===0)return!1;const x=s.findIndex(c=>i<c);if(x>0||x===-1){const c=x===-1?s[s.length-1]:s[x-1];po(ke.CREDIT_WARNING_THRESHOLDS,x===-1?[]:s.slice(x));const l=.9,d=c>=l?2:1,u=Math.round(i*100);cUe(u,t),await Xne(d,u,n,a,t)}return!1},Hqe=async(e,t)=>{if(!$V())return!1;if(!await Vn("checkAndAlertNoCredit"))return!0;let o=t;if(o===void 0)try{o=(await be().fetchUserInfo())?.credits}catch(a){return h("credit.ts").error("[credit] checkAndAlertNoCredit: fetchUserInfo failed, blocking operation",a),!0}const r=o?Ig(o)??0:0;if(r>0)return!1;const n=ba().isPremiumFeatureAvailable(Ut.USAGE_ERASER);return Bz(r,0,e),await ZV(r,0,n,e,!0),!0},jqe=e=>{if(e?.paidAt)return vx(e.paidAt,!0)+" - "+vx(wD(e.expiredAt),!0);const t=new Date,o=new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth(),1)),r=new Date(Date.UTC(t.getUTCFullYear(),t.getUTCMonth()+1,1));return vx(o,!0)+" - "+vx(wD(r),!0)},eG=(e,t)=>{const o=zy(e,t)?.expireAt;return o?vx(o):""},Wy=e=>Math.floor(e).toLocaleString("en-US"),Jne=e=>Math.ceil(e).toLocaleString("en-US"),zqe=e=>(Math.ceil(e*100-1e-9)/100||0).toLocaleString("en-US",{maximumFractionDigits:2}),Yqe=e=>e>=0?Math.ceil(e):-Math.ceil(-e),Hy=e=>{const t=Number(e);return Number.isFinite(t)?t:0},tG=e=>new Date(e.expireAt)<new Date,Ig=e=>{if(e.length===0)return;const t=e.filter(o=>!tG(o));if(t.length!==0)return t.reduce((o,r)=>o+Hy(r.creditBalance),0)},jy=e=>{if(e.length===0)return;const t=e.filter(o=>!tG(o));if(t.length!==0)return t.reduce((o,r)=>o+Hy(r.givenCredit),0)},zy=(e,t)=>e.find(o=>o.creditType===(t?"PAID_MONTHLY":"FREE_MONTHLY")),CL=e=>new Date(e.getFullYear(),e.getMonth(),e.getDate()),Bqe=(e,t)=>{const o=CL(e).toISOString(),r=CL(t);r.setDate(r.getDate()+1);const n=r.toISOString();return{fromUtc:o,toUtc:n}},Kqe=(e,t)=>{const o=QV[e];if(!o)return null;if(typeof o=="string")return o;const r=o,n=t??"DEFAULT",a=r[n];return a||(r.DEFAULT??null)},qne=e=>{switch(e){case"min":return"credit_rate.minute_count";case"char":return"credit_rate.character_count";case"image":return"credit_rate.image_no_count";case"video":return"credit_rate.video_per_second_count"}}
82,Xqe=e=>{const t=A("credit_rate.credit_count",{count:e.credit}),o=A(qne(e.type),{count:e.count});return A("credit_rate.common_separator",{credit:t,unit:o})},zn=e=>e,ii=e=>e,Jqe=e=>e,pe=e=>e,Yc=e=>e,RL=e=>e,ur=e=>e,mu=e=>e,kr=e=>e,Je=e=>e,Yy=e=>e,Qne=(e,t)=>e[t],Zne=(e,t,o)=>{e[t]=o},$ne=(e,t)=>{delete e[t]},L={get:Qne,set:Zne,remove:$ne},xr=e=>Eo(z).isValue(e.type),Wa=e=>Eo(ze).isValue(e.type),Gn=e=>e.type===z.IMAGE,oG=e=>e.type===z.LOTTIE,mn=e=>e.type===z.VIDEO,qqe=(e,t,o,r)=>{const n=L.get(e,t);if(!n||!xr(n))return e;const a=r?.clearFillType??!1;return vt(e,i=>{const s=L.get(i,t);!s||!xr(s)||(o.xPos!==void 0&&(s.xPos=o.xPos),o.yPos!==void 0&&(s.yPos=o.yPos),o.width!==void 0&&(s.width=o.width),o.height!==void 0&&(s.height=o.height),o.rotation!==void 0&&(s.rotation=o.rotation),a&&(mn(s)?s.fillType=void 0:Gn(s)&&s.stats&&(s.stats.fillType=void 0)))})},J0=e=>e.type===z.VIDEO,f0=e=>e.type===z.SHAPE,Qx=e=>e.dimensionType===Tr.ONE,i2=e=>e.dimensionType===Tr.TWO,Tg=e=>e.type===z.SIMPLE_CHARACTER,Wn=e=>e.type===z.WEB,rG=e=>e.type===z.IMAGE||e.type===z.WEB||e.type===z.SHAPE||e.type===z.VIDEO||e.type===ze.SoundEffect||e.type===ze.BGM,Rr=e=>e.type===z.WATERMARK,nG=e=>x2(e),s2=e=>qh(e)||dl(e),By=e=>eae(e)||x2(e),cd=e=>Ky(e)||ll(e)||qh(e)||dl(e),eae=e=>e.type===ze.TTSClip,x2=e=>e.type===ze.Overdub,Ky=e=>e.type===ze.SoundEffect,ll=e=>e.type===ze.BGM,qh=e=>
82e.type===ze.TTSEffect,dl=e=>e.type===ze.TTSDubbing,U0=e=>e.type===ze.VideoAudio,Xy=e=>{const t=eo(e.mediaId),o=t?.videoAudioMetaInfo?.duration;return typeof o=="number"?pe(o):void 0},tae=e=>e.mediaId!==_o&&e.fileLocation!==D.REMOTE,aG=e=>e.mediaId!==_o&&e.fileLocation!==D.PACKAGED&&e.fileLocation!==D.REMOTE,Jy=e=>e.fileLocation===D.REMOTE,oae=e=>Jy(e)&&e.type==="AVMedia",rae=e=>e.some(Jy),iG=e=>e.fileLocation===D.LOCAL,nae=e=>e.some(iG),AL=e=>e.filter(iG).map(t=>t.path),aae=(e,t)=>({...e,fileLocation:D.LOCAL_TMP,path:t}),iae=(e,t)=>{const{url:o,proxyInfo:r,...n}=e;return{...n,fileLocation:D.IN_MEMORY,blob:t}},yL="vrew-file",sae="localfile",xae="/local",an=e=>{if(!e)return e;const t=e.toLowerCase();if(t.startsWith("http://")||t.startsWith("https://")||t.startsWith("blob:")||t.startsWith("data:")||t.startsWith(yL+":"))return e;const o=/^\/(assets|worklet|libav|locales|src|@fs)\//;if(o.test(e)||e.startsWith("/try/")&&o.test("/"+e.slice(5)))return e;let n=e;if(t.startsWith("file://"))try{const c=new URL(e),l=decodeURIComponent(c.pathname);n=/^\/[A-Za-z]:\//.test(l)?l.slice(1):l}catch{return e}const a=/^[A-Za-z]:[\\/]/.test(n)||n.startsWith("\\\\"),i=(a?n.replace(/\\/g,"/"):n).split("/"),s=i.map(c=>c&&encodeURIComponent(c)).join("/"),x=s.startsWith("/")?s:"/"+s;return yL+"://"+sae+xae+x};class cae{_downloadPromises=new Map;_failureRecords=new Map;_progressCallbacks=new Map;_withDownloadLimit=tf(20);_MAX_RETRIES=3;async downloadToOpfs(t,o,r,n,a=!1,i){if(!a&&await n.existsFile(r))return;const s=this._failureRecords.get(t);if(s?.failed){const l=!navigator.onLine,d=l?"Download failed - Network offline: "+t:"Download previously failed ("+s.attemptCount+" attempts): "+t,u=l?_.C_NETWORK_OFFLINE:_.C_FILE_DOWNLOAD_FAILED;throw h("DownloadManager.ts").error(d),new C(u,{mediaId:t},d)}i&&(!this._progressCallbacks.has(t)&&this._progressCallbacks.set(t,new Set),this._progressCallbacks.get(t).add(i));const x=this._downloadPromises.get(t);if(x){try{await x}finally{i&&(this._progressCallbacks.get(t)?.delete(i),this._progressCallbacks.get(t)?.size===0&&this._progressCallbacks.delete(t))}return}const c=this._withDownloadLimit(async()=>this._executeDownloadToOpfs(t,o,r,n,a));this._downloadPromises.set(t,c);try{await c}finally{this._downloadPromises.delete(t),this._progressCallbacks.delete(t)}}async _executeDownloadToOpfs(t,o,r,n,a=!1){const i=this._failureRecords.get(t),s=(i?.attemptCount??0)+1;try{await n.existsFile(r)&&a&&(await n.deleteFile(r),h("DownloadManager.ts").info("[DownloadManager] Deleted existing file for overwrite: "+r)),h("DownloadManager.ts").info("[DownloadManager] Streaming (attempt "+s+"/"+this._MAX_RETRIES+"): "+r);let c;if(o.type==="path"?c=await fetch(an(o.value)):c=await Z7(()=>fetch(o.value,{credentials:"include"}),{maxRetry:3}),!c.ok||!c.body){const p="cannot fetch response for mediaId: "+t+", source: "+o.value+", status: "+c.status+", statusText: "+c.statusText;throw new C(_.C_FILE_DOWNLOAD_RESPONSE_ERROR,{mediaId:t},p)}let l=c.body;const d=c.headers.get("content-length"),u=d?parseInt(d,10):void 0;if(u){let p=0;const f=this._progressCallbacks;l=c.body.pipeThrough(new TransformStream({transform(E,T){p+=E.byteLength;const O=Math.round(p*100/u),S=f.get(t);S&&S.size>
820&&S.forEach(R=>{try{R(O)}catch(y){h("DownloadManager.ts").warn("[DownloadManager] Progress callback error: "+t,y)}}),T.enqueue(E)}}))}await n.saveFile(r,l),this._failureRecords.delete(t),h("DownloadManager.ts").info("[DownloadManager] Success: "+r)}catch(x){const c=!navigator.onLine,l=c?"Network offline - failed to download: "+r+", source: "+o.value:"failed to download to OPFS: "+r+", source: "+o.value+", error: "+P(x),d=s>=this._MAX_RETRIES;this._failureRecords.set(t,{attemptCount:s,lastAttempt:Date.now(),lastError:l,failed:d}),h("DownloadManager.ts").error("[DownloadManager] Failed (attempt "+s+"/"+this._MAX_RETRIES+"): "+t,l);let u;throw c?u=_.C_NETWORK_OFFLINE:Ne(x)?u=x.errorCode:u=_.C_FILE_DOWNLOAD_GENERAL_ERROR,new C(u,{mediaId:t},l)}}async registerProgressCallback(t,o){!this._progressCallbacks.has(t)&&this._progressCallbacks.set(t,new Set),this._progressCallbacks.get(t).add(o)}async unregisterProgressCallback(t,o){this._progressCallbacks.get(t)?.delete(o),this._progressCallbacks.get(t)?.size===0&&this._progressCallbacks.delete(t)}clearFailureRecord(t){this._failureRecords.delete(t)}clear(){this._downloadPromises.clear(),this._failureRecords.clear(),this._progressCallbacks.clear()}}class lae{_memoryCache=new Map;_blobUrlCache=new Map;_downloadQueue=new Map;_downloadManager;_opfsConfig;constructor(t){this._opfsConfig=t,this._downloadManager=new cae}updateConfig(t){this._opfsConfig=t}saveToMemory(t,o){this._memoryCache.set(t,o)}getFromMemory(t){return this._memoryCache.get(t)??null}async hasCached(t,o){try{if(this._memoryCache.has(t))return!0;const r=Ht(this._opfsConfig.namespace),n=this._buildFilePath(t,o);return r.existsFile(n)}catch(r){return h("CacheManager.ts").warn("[CacheManager] hasCached failed: "+t,P(r)),!1}}removeFromMemory(t){this._memoryCache.delete(t),this._revokeBlobUrl(t)}getBlobUrl(t){const o=this._blobUrlCache.get(t);if(o)return o;const r=this._memoryCache.get(t);if(!r)return null;const n=URL.createObjectURL(r);return this._blobUrlCache.set(t,n),n}_revokeBlobUrl(t){const o=this._blobUrlCache.get(t);o&&(URL.revokeObjectURL(o),this._blobUrlCache.delete(t))}async getFromOpfs(t,o){try{const r=Ht(this._opfsConfig.namespace),n=this._buildFilePath(t,o);return await r.getFileAsBlob(n)}catch(r){return h("CacheManager.ts").warn("[CacheManager] OPFS read failed: "+t,P(r)),null}}async saveToOpfs(t,o,r,n=!1){const a=Ht(this._opfsConfig.namespace),i=this._buildFilePath(t,o);if(n)await a.existsFile(i)&&await a.deleteFile(i);else if(await a.existsFile(i))return;await a.saveFile(i,r.stream())}async downloadAndCache(t,o,r,n){const a=this._downloadQueue.get(t);if(a){n&&await this._downloadManager.registerProgressCallback(t,n);try{await a}finally{n&&await this._downloadManager.unregisterProgressCallback(t,n)}return}const i=this._executeDownloadAndCache(t,o,r,n);this._downloadQueue.set(t,i);try{await i}finally{this._downloadQueue.delete(t)}}async _executeDownloadAndCache(t,o,r,n){const a=Ht(this._opfsConfig.namespace),i=yo(o.value),s=this._buildFilePath(t,i);!r.overwrite&&await a.existsFile(s)||(r.clearPreviousFailure&&this._downloadManager.clearFailureRecord(t),await this._downloadManager.downloadToOpfs(t,o,s,a,r.overwrite,n))}clear(){this._memoryCache.clear(),this._revokeAllBlobUrls(),this._downloadQueue.clear(),this._downloadManager.clear()}_revokeAllBlobUrls(){for(const t of this._blobUrlCache.values())URL.revokeObjectURL(t);this._blobUrlCache.clear()}async ensureCached(t,o,r=!1){const n=Ht(this._opfsConfig.namespace),a=yo(o.value),i=this._buildFilePath(t,a);if(!(!r&&await n.existsFile(i)))try{await this.downloadAndCache(t,o,{clearPreviousFailure:!0,overwrite:r})}catch(s){h("CacheManager.ts").warn("[CacheManager] Background cache failed (non-critical): "+t,P(s))}}async getOrFetch(t,o,r){const n=this.getFromMemory(t);if(n)return n;const a=yo(o.value),i=await this.getFromOpfs(t,a);if(i)return i;try{await this.downloadAndCache(t,o,{clearPreviousFailure:!1,overwrite:!1},r);const s=await this.getFromOpfs(t,a);if(s)return s}catch(s){h("CacheManager.ts").warn("[CacheManager] Stream fetch failed, trying blob fallback: "+t,P(s))}try{const s=await this._fetchBlob(o);return this.saveToOpfs(t,a,s,!1).catch(x=>
82{h("CacheManager.ts").warn("[CacheManager] Background OPFS save failed: "+t,P(x))}),s}catch(s){return h("CacheManager.ts").error("[CacheManager] All fetch attempts failed: "+t,P(s)),null}}async _fetchBlob(t){let o;if(t.type==="path"?o=await fetch(an(t.value)):o=await Z7(()=>fetch(t.value,{credentials:"include"}),{maxRetry:3}),!o.ok){const r="[fetchBlob] Fetch failed: "+o.status+" "+o.statusText;throw h("CacheManager.ts").error(r),new C(_.C_NETWORK_REQUEST_FAILED,{},r)}return await o.blob()}_buildFilePath(t,o){return this._opfsConfig.pathPrefix+"/"+t+"."+o}}class ou{static _instance=null;_blobs=new Map;_preloadPromise=null;constructor(){}static getInstance(){return!ou._instance&&(ou._instance=new ou),ou._instance}startPreload(){!this._preloadPromise&&(this._preloadPromise=this._preloadAll())}async getBlob(t,o){this._preloadPromise&&await this._preloadPromise;const r=this._blobs.get(o);return r||this._fetchSingle(t,o)}async _preloadAll(){const t=h("PackagedBlobCache.ts");t.info("[PackagedBlobCache] Starting preload of "+td.length+" files");const o=await Promise.allSettled(td.map(async n=>{try{const a=await fetch(n.path);if(a.ok){const i=await a.blob();this._blobs.set(n.mediaId,i),t.info("[PackagedBlobCache] Preloaded: "+n.mediaId+", size: "+i.size)}else t.warn("[PackagedBlobCache] Failed to preload (HTTP "+a.status+"): "+n.mediaId)}catch(a){t.warn("[PackagedBlobCache] Failed to preload: "+n.mediaId,P(a))}})),r=o.filter(n=>n.status==="rejected").length;r>0&&t.warn("[PackagedBlobCache] "+r+" files failed to preload"),t.info("[PackagedBlobCache] Preload complete")}async _fetchSingle(t,o){const r=h("PackagedBlobCache.ts");r.info("[PackagedBlobCache] On-demand fetch: "+o);try{const n=await fetch(t);if(n.ok){const a=await n.blob();return this._blobs.set(o,a),r.info("[PackagedBlobCache] Fetched: "+o+", size: "+a.size),a}r.warn("[PackagedBlobCache] Fetch failed (HTTP "+n.status+"): "+o)}catch(n){r.error("[PackagedBlobCache] Fetch error: "+o,P(n))}return null}}class Sg{constructor(t,o){this.context=t,this.expectedLocation=o}context;expectedLocation;validateLocation(t){if(t.fileLocation!==this.expectedLocation)throw new C(_.C_LOGIC_ERROR,{},this.constructor.name+": Expected "+this.expectedLocation+", got "+t.fileLocation)}async cacheBlob(t,o,r=!1){await this.context.cacheManager.ensureCached(t,o,r)}async resolveBlob(t,o,r){return this.context.cacheManager.getOrFetch(t,o,r)}async checkCached(t,o){return this.context.cacheManager.hasCached(t,o)}toFileInfo(t){return t}async prepare(t){return this.validateLocation(t),t.broken?this.toFileInfo(t):await this.doPrepare(t)}}class dae extends Sg{constructor(t){super(t,D.IN_MEMORY)}async doPrepare(t){try{const{mediaId:o,blob:r}=t,n=X0.getExtension(r.type)||await Bs(r);return await Ue().putMediaCache(o,r,n),this.context.cacheManager.saveToMemory(o,r),this.toFileInfo(t)}catch(o){const r="failed to register: mediaId: "+t.mediaId+", error: "+P(o),n=Ne(o)?o.errorCode:_.C_LOGIC_ERROR;throw new C(n,{},r)}}async cache(t,o=!1){return Promise.resolve()}async hasCached(t,o){return this.context.cacheManager.getFromMemory(t)!==null}async getBlob(t,o,r){return this.context.cacheManager.getFromMemory(t)}remove(t){this.context.cacheManager.removeFromMemory(t)}toFileInfo(t){const{blob:o,...r}=t;return r}}class uae extends Sg{constructor(t){super(t,D.LOCAL)}async doPrepare(t){return this.toFileInfo(t)}async cache(t,o=!1){return Promise.resolve()}async hasCached(t,o){const r=yo(o.path);return this.checkCached(t,r)}async getBlob(t,o,r){return this.resolveBlob(t,{type:"path",value:o.path},r)}remove(){}toFileInfo(t){return t}}class pae extends Sg{constructor(t){super(t,D.LOCAL_TMP)}async doPrepare(t){const o=yo(t.path)||ZE,r=await Ue().putLocalCache({mediaId:t.mediaId,ext:o,pathInfo:{path:t.path,preserveOriginal:!0}});return this.toFileInfo({...t,path:r.resolvedPath})}async cache(t,o=!1){return Promise.resolve()}async hasCached(t,o){const r=yo(o.path);return this.checkCached(t,r)}async getBlob(t,o,r){return this.resolveBlob(t,{type:"path",value:o.path},r)}remove(){}toFileInfo(t){return t}}class fae extends Sg{constructor(t){super(t,D.PACKAGED)}async doPrepare(t){return this.toFileInfo(t)}async cache(t,o=!1){return Promise.resolve()}async hasCached(t,o){return!0}async getBlob(t,o,r){return this.context.packagedBlobCache.getBlob(o.path,t)}remove(){}toFileInfo(t){return t}}class gae extends Sg{constructor(t){super(t,D.REMOTE)}async doPrepare(t){return this.toFileInfo(t)}async cache(t,o=!1){await this.cacheBlob(t.mediaId,{type:"url",value:t.url},o)}async hasCached(t,o){const r=yo(o.url);return this.checkCached(t,r)}async getBlob(t,o,r){return this.resolveBlob(t,{type:"url",value:o.url},r)}remove(){}toFileInfo(t){return t}}class iO{_fileHandlers;_fileInfosMap=new Map;_cacheManager;_packagedBlobCache;_context;constructor(t){this._cacheManager=new lae(t),this._packagedBlobCache=ou.getInstance(),this._context={cacheManager:this._cacheManager,packagedBlobCache:this._packagedBlobCache},this._fileHandlers={[D.PACKAGED]:new fae(this._context),[D.IN_MEMORY]:new dae(this._context),[D.LOCAL]:new uae(this._context),[D.LOCAL_TMP]:new pae(this._context),[D.REMOTE]:new gae(this._context)},this._registerPackagedMetadata()}updateOpfsConfig(t){this._cacheManager.updateConfig(t),h("FileManager.ts").info("[FileManager] Config updated to namespace: "+t.namespace)}async add(t,o={}){const r=t.mediaId;if(this.getFileInfo(r))return;const a=this._getHandler(t.fileLocation),i=o.skipPrepare?a.toFileInfo(t):await a.prepare(t);
82this._fileInfosMap.set(r,i),this._executeBackgroundCache(a,i,o)}async update(t,o={}){const r=t.mediaId;if(!this.getFileInfo(r)){const s="File not found for update: "+r;throw h("FileManager.ts").error(s),new C(_.C_LOGIC_ERROR,{mediaId:r},s)}const a=this._getHandler(t.fileLocation),i=await a.prepare(t);this._fileInfosMap.set(r,i),this._executeBackgroundCache(a,i,o,!0)}async _executeBackgroundCache(t,o,r,n=!1){o.broken||(await t.cache(o,n),r.onBlobReady?.(o.mediaId))}async getBlob(t,o){const r=this.getFileInfo(t);return r?this._getHandler(r.fileLocation).getBlob(t,r,o):(h("FileManager.ts").info("[FileManager] File info not found: "+t),null)}async hasCached(t){const o=this.getFileInfo(t);return o?this._getHandler(o.fileLocation).hasCached(t,o):!1}remove(t){const o=this.getFileInfo(t);return o?(this._getHandler(o.fileLocation).remove(t),this._fileInfosMap.delete(t),!0):!1}clear(){const t=new Map;for(const[o,r]of this._fileInfosMap.entries())if(r.fileLocation!==D.PACKAGED){const n=t.get(r.fileLocation)??[];n.push(o),t.set(r.fileLocation,n)}for(const[o,r]of t.entries()){const n=this._getHandler(o);for(const a of r)n.remove(a)}this._fileInfosMap.clear(),this._cacheManager.clear(),this._registerPackagedMetadata(),h("FileManager.ts").info("[FileManager] Cleared all data")}getFileInfo(t){return this._fileInfosMap.get(t)}getAllFiles(){return Array.from(this._fileInfosMap.values())}getAVMediaFiles(){return this.getAllFiles().filter(t=>t.type==="AVMedia")}getImageFiles(){return this.getAllFiles().filter(t=>t.type==="Image")}getInMemoryBlobUrl(t){const o=this.getFileInfo(t);return!o||o.fileLocation!==D.IN_MEMORY?null:this._cacheManager.getBlobUrl(t)}getInMemoryFileBlob(t){const o=this.getFileInfo(t);return!o||o.fileLocation!==D.IN_MEMORY?null:this._cacheManager.getFromMemory(t)}getMediaUrl(t){const o=this.getFileInfo(t);return o?o.fileLocation===D.LOCAL||o.fileLocation===D.LOCAL_TMP?an(o.path):o.fileLocation===D.PACKAGED?o.path:"url"in o?o.url:o.fileLocation===D.IN_MEMORY?this._cacheManager.getBlobUrl(t):null:null}getFileSrcUrl(t){return this.getMediaUrl(t)}getProxyInfo(t){const o=this.getFileInfo(t);if(o&&o.fileLocation===D.REMOTE)return o.proxyInfo}async promoteToRemote(t,o,r){const n=this.getFileInfo(t);if(!n){const a="promoteToRemote: file not found for "+t;throw new C(_.C_LOGIC_ERROR,{mediaId:t},a)}if(!(n.fileLocation===D.REMOTE&&n.url===o.url))try{const a=this._createRemoteFileInfo(n,o),i=this._getHandler(D.REMOTE),s=await i.prepare(a);this._fileInfosMap.set(t,s),n.fileLocation!==D.REMOTE&&(await r(),this._getHandler(n.fileLocation).remove(t)),h("FileManager.ts").info("[FileManager] promoteToRemote successfully for mediaId: "+t),this._executeBackgroundCache(i,s,{})}catch(a){const i="[FileManager] promoteToRemote failed: "+t;h("FileManager.ts").error(i,P(a));const s=Ne(a)?a.errorCode:_.C_LOGIC_ERROR;throw new C(s,{mediaId:t},i)}}async saveBlobToCache(t,o,r,n=!1){try{await this._cacheManager.saveToOpfs(t,r,o,n)}catch(a){h("FileManager.ts").warn("[FileManager] Failed to save blob to cache: "+t,P(a))}}_getHandler(t){const o=this._fileHandlers[t];if(!o){const r="No handler for fileLocation: "+t;throw h("FileManager.ts").error(r),new C(_.C_LOGIC_ERROR,{},r)}return o}_registerPackagedMetadata(){td.forEach(t=>{const o={type:"Image",mediaId:t.mediaId,name:t.name,fileLocation:D.PACKAG
82ED,sourceOrigin:tt.VREW_RESOURCE,path:t.path,fileSize:t.fileSize,isTransparent:t.isTransparent};this._fileInfosMap.set(t.mediaId,o),this._getHandler(D.PACKAGED).prepare(o)})}_createRemoteFileInfo(t,o){const r={mediaId:t.mediaId,name:t.name,fileLocation:D.REMOTE,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,url:o.url,proxyInfo:o.proxy};if(t.type==="AVMedia")return{...r,type:"AVMedia",sourceType:t.sourceType,videoAudioMetaInfo:t.videoAudioMetaInfo};switch(t.type){case"Image":return{...r,type:"Image",isTransparent:t.isTransparent};case"Html":return{...r,type:"Html",rawHtml:t.rawHtml};case"Svg":return{...r,type:"Svg",rawSvg:t.rawSvg};default:{const n="Unsupported file type: "+JSON.stringify(t);throw h("FileManager.ts").error(n),new C(_.C_LOGIC_ERROR,{},"Unsupported file type: "+JSON.stringify(t))}}}}var Kp=(e=>(e.UNKNOWN="unknown",e.IOS="iOS",e.ANDROID="Android",e))(Kp||{}),Ds=(e=>(e.PROJECT="project",e.SCENE="scene",e.CLIP="clip",e.ASSET="asset",e))(Ds||{}),c2=(e=>(e.TOOLBAR="toolbar",e.CONTEXT_FLOATING_MENU="context-floating-menu",e.FILEINFO_MODAL="fileinfo-modal",e.DRAG_AND_DROP="drag-and-drop",e.SCENE_PANEL_CLICK="scene-panel-click",e.SCENE_PANEL_DRAG_AND_DROP="scene-panel-drag-and-drop",e.VDROP_MODAL="vdrop-modal",e.ATV_MODAL="atv-modal",e))(c2||{}),l2=(e=>(e.PC="pc",e.VDROP="vdrop",e))(l2||{}),Lu=(e=>(e.TRANSCODE="transcode",e.RECOVERY="recovery",e.PROXY="proxy",e))(Lu||{});const vL=e=>({in:X.zero(),out:X.max(X.zero(),X.fromSec(e))}),_ae=e=>e===Fs.LOOP,Eae=e=>e==="main"?Fs.FREEZE:Fs.LOOP,mae=(e,t,o)=>{const r={...e};return(o===void 0?Object.values(t):o.map(a=>t[a]).filter(Boolean)).forEach(a=>{const i=a.trackIds.map(x=>r[x]).find(mn);if(i===void 0)return;if(a.role==="main"){i.endBehavior!==Fs.FREEZE&&(r[i.trackId]={...i,endBehavior:Fs.FREEZE}),a.trackIds.forEach(x=>{const c=r[x];c!==void 0&&c.type===ze.VideoAudio&&c.loop!==!1&&(r[x]={...c,loop:!1})});return}const s=_ae(i.endBehavior);a.trackIds.forEach(x=>{const c=r[x];c!==void 0&&c.type===ze.VideoAudio&&c.loop!==s&&(r[x]={...c,loop:s})})}),r},wL=e=>{if(e.audioInfo&&e.videoInfo)return{duration:e.duration,presumedDevice:e.presumedDevice,mediaContainer:e.mediaContainer,audioInfo:{codec:e.audioInfo.codec,sampleRate:e.audioInfo.sampleRate,channelCount:e.audioInfo.channelCount},videoInfo:{size:e.videoInfo.size,frameRate:e.videoInfo.frameRate,codec:e.videoInfo.codec,colorSpace:e.videoInfo.colorSpace,hasAlphaChannel:e.videoInfo.hasAlphaChannel}};if(e.audioInfo)return{duration:e.duration,presumedDevice:e.presumedDevice,mediaContainer:e.mediaContainer,audioInfo:{codec:e.audioInfo.codec,sampleRate:e.audioInfo.sampleRate,channelCount:e.audioInfo.channelCount}};if(e.videoInfo)return{duration:e.duration,presumedDevice:e.presumedDevice,mediaContainer:e.mediaContainer,videoInfo:{size:e.videoInfo.size,frameRate:e.videoInfo.frameRate,codec:e.videoInfo.codec,colorSpace:e.videoInfo.colorSpace,hasAlphaChannel:e.videoInfo.hasAlphaChannel}};throw new C(_.C_MEDIA_NO_AUDIO_VIDEO_TRACK,{},"Media file info is invalid: no audio or video info")},NL=e=>{const{mediaId:t,fileLocation:o,fileSize:r,name:n,videoAudioMetaInfo:a}=e;if(o===D.IN_MEMORY)return{type:"AVMedia",sourceOrigin:tt.USER,mediaId:t,videoAudioMetaInfo:a,fileSize:r,sourceType:de.VIDEO_AUDIO,name:n,fileLocation:D.IN_MEMORY};if(o===D.LOCAL){const{path:s,relativePath:x}=e;return{type:"AVMedia",sourceOrigin:tt.USER,mediaId:t,videoAudioMetaInfo:a,fileSize:r,sourceType:de.VIDEO_AUDIO,name:n,fileLocation:D.LOCAL,path:s,relativePath:x}}if(o===D.LOCAL_TMP){const{path:s}=e;return{type:"AVMedia",sourceOrigin:tt.USER,mediaId:t,videoAudioMetaInfo:a,fileSize:r,sourceType:de.VIDEO_AUDIO,name:n,fileLocation:D.LOCAL_TMP,path:s}}if(o===D.PACKAGED){const{path:s}=e;return{type:"AVMedia",sourceOrigin:tt.USER,mediaId:t,videoAudioMetaInfo:a,fileSize:r,sourceType:de.VIDEO_AUDIO,name:n,fileLocation:D.PACKAG
82ED,path:s}}if(o===D.REMOTE){const{url:s,proxyInfo:x}=e;return{type:"AVMedia",sourceOrigin:tt.USER,mediaId:t,videoAudioMetaInfo:a,fileSize:r,sourceType:de.VIDEO_AUDIO,name:n,fileLocation:D.REMOTE,url:s,proxyInfo:x}}const i="[createMainVideoAudioInfo] Unsupported fileLocation: "+o;throw h("managerUtil.ts").error(i),new C(_.C_STT_GENERAL_ERROR,{},i)},sG=e=>{if(e.videoProxyUrl&&e.audioProxyUrls)return{videoProxyUrl:e.videoProxyUrl,audioProxyUrls:e.audioProxyUrls};if(e.videoProxyUrl)return{videoProxyUrl:e.videoProxyUrl};if(e.audioProxyUrls)return{audioProxyUrls:e.audioProxyUrls}},hae=(e,t)=>{if(e.fileLocation!==D.IN_MEMORY)return e;if(!t)throw new C(_.C_LOGIC_ERROR,{},"[combineFileInput] No blob provided for in-memory file: "+e.mediaId);return{...e,blob:t}},Iae=(e,t)=>e.fileLocation===D.IN_MEMORY?e.broken===!0||!t:Bc(e)&&e.broken===!0,PL=(e,t,o=!1)=>{if(Iae(e,t))return Sb;if(o&&e.fileLocation===D.REMOTE&&e.proxyInfo?.videoProxyUrl)return e.proxyInfo.videoProxyUrl;if(e.fileLocation!==D.IN_MEMORY){const r=s_(e.mediaId);if(r)return r}return t?URL.createObjectURL(t):Sb},Tae=e=>e.type==="AVMedia"&&e.videoAudioMetaInfo.audioInfo!==void 0&&[de.TTS_EFFECT,de.TTS_DUBBING,de.SOUND_EFFECT,de.BGM].includes(e.sourceType),yf=e=>e.type==="AVMedia"&&(e.sourceType===de.VIDEO_AUDIO||e.sourceType===de.TTS||e.sourceType===de.OVERDUB),Zr=e=>e.type==="AVMedia"&&e.sourceType===de.VIDEO_AUDIO,MR=e=>e.type==="AVMedia"&&e.sourceType===de.ASSET_VIDEO,Sae=e=>e.type==="AVMedia"&&e.sourceFileType==="VIDEO_AUDIO",DR=e=>e===void 0||e.size===0,Bc=e=>e.fileLocation===D.LOCAL||e.fileLocation===D.LOCAL_TMP,Qqe=e=>e?"path"in e?mu(e.path):"url"in e?mu(e.url):mu(e.name):null,bL=(e,t)=>{if(e.length!==t.length)return!1;for(let o=0;o<e.length;o++)if(e[o].mediaId!==t[o].mediaId||e[o].fileLocation!==t[o].fileLocation)return!1;return!0};let qy=null;const Zqe=e=>{qy=e},ld=()=>qy,q0=()=>qy?.playing===!0,kR=new Set;let xG=0;const $qe=()=>xG,eQe=e=>(kR.add(e),()=>{kR.delete(e)}),sO=()=>{xG+=1;for(const e of kR)e()};let cG=null,lG=null;const tQe=e=>{cG=e},oQe=e=>{lG=e},ks=()=>cG?.(),Og=()=>lG??void 0;var g0=(e=>(e.SET_PROGRESS_STATE="SET_PROGRESS_STATE",e.UPDATE_CAPTION_SELECTION_CHANGED="UPDATE_CAPTION_SELECTION_CHANGED",e.SET_CAPTION_LENGTH_LIMIT="SET_CAPTION_LENGTH_LIMIT",e.UPDATE_RENDER_RANGE_INFO="UPDATE_RENDER_RANGE_INFO",e.CLOSE_DOWNLOAD_PROMOTION_BANNER="CLOSE_DOWNLOAD_PROMOTION_BANNER",e.SET_ASSET_DRAGGING_RANGE="SET_ASSET_DRAGGING_RANGE",e.SET_IS_READY_TO_OPEN_PROJECT="SET_IS_READY_TO_OPEN_PROJECT",e.CHANGE_LAST_USED_BLANK_OPTION="CHANGE_LAST_USED_BLANK_OPTION",e.OPEN_CLIP_GAP_MENU="OPEN_CLIP_GAP_FLOATING_MENU",e.CLOSE_CLIP_GAP_MENU="CLOSE_CLIP_GAP_FLOATING_MENU",e.SET_BLANK_CONTROL_INFO="SET_BLANK_CONTROL_INFO",e.SET_RENDER_RANGE="SET_RENDER_RANGE",e.SET_PENDING_SCROLL_STATE="SET_PENDING_SCROLL_STATE",e))(g0||{}),Oae=(e=>(e.PAYLOAD_UPDATED="payloadUpdated",e))(Oae||{});class Cae extends ad.EventEmitter{constructor(t){super(),this.type=t,this._actions=y9({openProgress:()=>Rae(t),closeProgress:()=>Aae(t),toggleProgress:(o,r)=>yae(o,r)},Og())}type;_actions;_payload=null;getEventEmitter(){return this}openProgress(t,o=!0){this._payload=t,this._actions.openProgress(this.type),this._actions.toggleProgress(this.type,o)}closeProgress(){this._payload=null,this._actions.closeProgress(this.type)}minimizeProgress(){this._actions.toggleProgress(this.type,!1)}expandProgress(){this._actions.toggleProgress(this.type,!0)}getPayload(){return this._payload}getProps(t){const o=this._payload;
82return o!==null?{type:this.type,expanded:t,payload:o}:null}setPayload(t){this._payload=t,this.emit("payloadUpdated",this.type,t)}}let ni=class FE{static _detailedProgressMap={};static getInstance(t){return!FE._detailedProgressMap[t]&&(FE._detailedProgressMap[t]=new Cae(t)),FE._detailedProgressMap[t]}constructor(){}};const Rae=e=>({type:g0.SET_PROGRESS_STATE,payload:{type:e,state:"open"}}),Aae=e=>({type:g0.SET_PROGRESS_STATE,payload:{type:e,state:"close"}}),yae=(e,t)=>({type:g0.SET_PROGRESS_STATE,payload:{type:e,state:t?"expand":"minimize"}}),Qh=e=>ni.getInstance(e).getPayload()!==null,Qy=(e,t)=>{ni.getInstance(e).openProgress(t,!0)},Zy=e=>{ni.getInstance(e).closeProgress()},xO=new Map,cO=new Map,hu=h("vcloud/cacheMigration"),vae=async(e,t,o,r)=>{const n=xO.get(e);if(n)return hu.debug("[Cache Migration] Migration already in progress for: "+t+"."+o+", returning existing promise"),await n;const a=Ht(So.CLOUD_CACHE),i=Ht(wu),s=(async()=>{try{return await a.saveFile(e,r.stream()),await i.deleteFile(e),hu.info("[Cache Migration] Successfully migrated blob: "+t+"."+o),await a.getFileAsBlob(e)}catch(x){return hu.warn("[Cache Migration] Failed to migrate blob: "+t+"."+o+", error: "+P(x)),null}finally{xO.delete(e)}})();return xO.set(e,s),await s},wae=async(e,t,o,r)=>{const n=cO.get(e);if(n)return hu.debug("[Cache Migration] Migration already in progress for: "+t+"."+o+", returning existing promise"),await n;const a=Ht(So.CLOUD_CACHE),i=Ht(wu),s=(async()=>{try{const x=await r.getFile();return await a.saveFile(e,x.stream()),await i.deleteFile(e),hu.info("[Cache Migration] Successfully migrated file handle: "+t+"."+o),await a.readFile(e)}catch(x){return hu.warn("[Cache Migration] Failed to migrate file handle: "+t+"."+o+", error: "+P(x)),null}finally{cO.delete(e)}})();return cO.set(e,s),await s},r0=h("vcloud/cache"),ul=(e,t,o)=>e+"/"+gg+"/"+t+"."+o,X_=e=>""+e,Cg=async(e,t,o)=>{const r=ul(e,t,o),n=Ht(So.CLOUD_CACHE),a=await n.getFileAsBlob(r);if(a)return r0.debug("[Cache] Found in "+So.CLOUD_CACHE+": "+t+"."+o),a;const i=Ht(wu),s=await i.getFileAsBlob(r);return s?(r0.info("[Cache] Found in "+wu+", migrating: "+t+"."+o),await vae(r,t,o,s)):(r0.debug("[Cache] Not found: "+t+"."+o),null)},dG=async(e,t,o)=>{const r=ul(e,t,o),n=Ht(So.CLOUD_CACHE),a=await n.readFile(r);if(a)return r0.debug("[Cache] Found handle in "+So.CLOUD_CACHE+": "+t+"."+o),a;const i=Ht(wu),s=await i.readFile(r);return s?(r0.info("[Cache] Found handle in "+wu+", migrating: "+t+"."+o),await wae(r,t,o,s)):(r0.debug("[Cache] Handle not found: "+t+"."+o),null)},Rg=async(e,t)=>{const o=Ht(So.CLOUD_CACHE);try{await o.saveFile(e,t)}catch(r){throw r0.error("[Cache File Locally] Failed to cache: "+e,r),r}},Nae=async(e,t)=>{try{return await Rg(e,t),!0}catch{return!1}},Pae=async(e,t,o)=>{try{const r=Object.keys(t);if(r.length===0)return;r0.info("[copyCacheBetweenProjects] Start copying "+r.length+" files to "+e);const n=Ht(So.CLOUD_CACHE),a=An(5);let i=0;await Promise.all(r.map(s=>a(async()=>{if(o?.signal.aborted)return;const x=t[s],c=yo(x.path);try{const l=await En(s);if(!l)return;const d=ul(e,s,c);if(await n.existsFile(d))return;await n.saveFile(d,l.stream()),i++}catch(l){r0.warn("[copyCacheBetweenProjects] Failed to copy file to target project "+e+" mediaId: "+s+", error: "+P(l))}}))),r0.info("[copyCacheBetweenProjects] Completed: "+i+"/"+r.length+" files copied")}catch(r){r0.warn("[copyCacheBetweenProjects] Failed to copy cache between projects targetProjectId: "+e+", error: "+P(r))}};var ie=(e=>(e.INVALID="INVALID",e.VIDEO_AUDIO="VIDEO_AUDIO",e.IMAGE="IMAGE",e.FILTER="FILTER",e.TTS="TTS",e.BGM="BGM",e.SOUND_EFFECT="SOUND_EFFECT",e.ASSET_VIDEO="ASSET_VIDEO",e.TTS_EFFECT="TTS_EFFECT",e.CHARACTER="CHARACTER",e.SIMPLE_CHARACTER="SIMPLE_CHARACTER",e.TTS_DUBBING="TTS_DUBBING",e.WATERMARK="WATERMARK",e.SHAPE="SHAPE",e.TEXTBOX="TEXTBOX",e.OVERDUB="OVERDUB",e))(ie||{}),bae=(e=>(e.POSE_JSON="POSE_JSON",e.SVG="SVG",e))(bae||{});function lO(e,t){return t>=Ty}function dO(e,t){return t<Ty}class Lae{constructor(t){this.version=t}version;getDownloadUrl(t){if(t.fileLocation!==D.REMOTE)throw new Error("Not remote file: "+t.mediaId);if(lO(t,this.version))return t.url;if(dO(t,this.version))return t.path;throw new Error("Unsupported file version: "+this.version)}getFileType(t){if(lO(t,this.version))return t.type;if(dO(t,this.version))switch(t.type){case ie.VIDEO_AUDIO:case ie.ASSET_VIDEO:case ie.SOUND_EFFECT:case ie.TTS:case ie.TTS_EFFECT:case ie.TTS_DUBBING:case ie.BGM:case ie.OVERDUB:return"AVMedia";case ie.IMAGE:case ie.FILTER:case ie.WATERMARK:return"Image";case ie.SHAPE:return"Svg";case ie.TEXTBOX:return"Html";default:return"AVMedia"}else throw new Error("Unsupported file version: "+this.version)}_shouldPreloadFile(t){if(lO(t,this.version))return!(t.fileLocation===D.REMOTE&&t.type==="AVMedia"&&t.sourceFileType===ie.VIDEO_AUDIO);if(dO(t,this.version))return t.fileLocation===D.REMOTE&&t.type!==ie.VIDEO_AUDIO;throw new Error("Unsupported file version: "+this.version)}createPreloadableCloudFileMap(t){const o={},r=t.filter(n=>n.fileLocation===D.REMOTE);
82for(const n of r)try{if(n.type===ie.INVALID)throw new C(_.C_LOGIC_ERROR,{},"[createPreloadableCloudFileMap] Invalid file type should not be processed: "+n.mediaId);if(!this._shouldPreloadFile(n))continue;const a=this.getDownloadUrl(n);o[n.mediaId]={mediaId:n.mediaId,downloadUrl:a,ext:yo(a),type:this.getFileType(n),fileSize:n.fileSize}}catch(a){h("CloudFileAdapter.ts").warn("Failed to resolve cloud file for "+n.mediaId+": "+a)}return o}}const $y=e=>new Lae(e.version).createPreloadableCloudFileMap(e.files),Mae=/[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f-\x9f]/gu,Dae=/(?:^|[^\uD800-\uDBFF])([\uDC00-\uDFFF])/gu,kae=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/gu,ev=e=>e.trim(),dd=e=>!e.match(/^\s*$/),tv=e=>e.split(/\n/).map(ev).filter(dd),ov=e=>Uae(Fae(e)),Fae=e=>e.replaceAll(Mae,""),LL=typeof Intl<"u"&&typeof Intl.Segmenter=="function"?new Intl.Segmenter(void 0,{granularity:"grapheme"}):null,d2=e=>LL?Array.from(LL.segment(e),({segment:t})=>t):Array.from(e),Uae=e=>e.replace(kae,"").replace(Dae,(t,o)=>o!==void 0?t.slice(0,t.length-o.length):""),uG=(e,t,o=0)=>e[o]===t[o]?uG(e,t,o+1):o,Vae=(e,t)=>{const o=/\/|\\/,r=x=>x.includes("."),n=(r(e)?ti(e):e).split(o).filter(dd),a=t.split(o).filter(dd),i=uG(n,a);return[n.length===i?".":n.slice(i).map(()=>".."),...a.slice(i)].join("/")},ML=(e,t)=>{const o=t?"\\":"/";return(t?"":"/")+e.join(o).split(/\/|\\/).filter(dd).filter(r=>r!==".").reduce((r,n)=>n===".."?(r.length===1&&t||r.pop(),r):(r.push(n),r),[]).join(o)},Gae=(e,t)=>{const o=jx.basename(e);return jx.join(t,o)},Wae=(e,t)=>{const o=jx.dirname(e);return jx.join(o,t)},a0=(...e)=>{if(!Ps())return jx.join(...e);const t=e.filter(Boolean).join("\\").replace(/\//g,"\\");return/^[\\]{2}[^\\]/.test(t)?t:t.replace(/^[\\]{2,}/,"\\")},pG=e=>a0(e,Mx),fG=(e,t)=>{if(e.endsWith(pf)){const o=e.replace("."+pf,"");return a0(t,o)}return a0(t,e)},Zh=(e,t)=>a0(t,fg,e),gG=async(e,t)=>e.fileLocation===D.REMOTE?await rN(e.url,t):e.name||null,$h=async(e,t)=>{const o=h("downloadUtils.ts");try{if(Oo()){const a=await Ue().existsFolder(e);o.info("path : "+e+", validPath : "+a),a&&await Ue().deleteFolder(e),o.info("delete error project done. path : "+e);return}if(!t?.projectId||!t?.uid){o.warn("projectInfo is not valid. projectId: "+t?.projectId+", uid: "+t?.uid);return}const r=Ht(So.BROWSER_PROJECT),n=Xf(t.uid,t.projectId);try{await r.removeDir(n),o.info("delete error project done. OPFS path : "+n)}catch(a){o.warn("failed to delete OPFS project path: "+n+", err:"+P(a))}}catch(r){o.error("failed to delete error project. err:"+P(r));return}};class u2{pool;maxLength;startTime;constructor(t){this.pool=[],this.maxLength=t,this.startTime=new Date().getTime()}start(){this.startTime=new Date().getTime()}reset(){this.pool=[],this.startTime=new Date().getTime()}supply(t){if(t===0)return 0;const o=new Date().getTime()-this.startTime;if(o===0)return 0;const r=Math.round(o/t);return this.pool.push(r),this.pool.length>this.maxLength&&this.pool.shift(),(this.pool.reduce((i,s)=>i+s,0)/this.pool.length-o)/1e3}}var rv=(e=>(e[e.MIGRATE_CONFIRM=0]="MIGRATE_CONFIRM",e[e.TITLE_INPUT=1]="TITLE_INPUT",e[e.PREPARING=2]="PREPARING",e[e.UPLOADING=3]="UPLOADING",e[e.UPLOAD_DONE=4]="UPLOAD_DONE",e[e.UPLOAD_ERROR=5]="UPLOAD_ERROR",e[e.UPLOAD_CANCEL=6]="UPLOAD_CANCEL",e))(rv||{}),mm=(e=>(e.SYNC_PROJECTS="vcloud.syncProjects",e))(mm||{}),Hae=(e=>(e[e.IDLE=0]="IDLE",e[e.NAME_INPUT=1]="NAME_INPUT",e[e.DOWNLOADING=2]="DOWNLOADING",e[e.DOWNLOAD_DONE=3]="DOWNLOAD_DONE",e[e.DOWNLOAD_ERROR=4]="DOWNLOAD_ERROR",e[e.DELETE=5]="DELETE",e))(Hae||{}),fc=(e=>(e.ADD="add",e.UPDATE_PROGRESS="updateProgress",e.UPLOAD_FAIL="uploadFail",e.REMOVE="remove",e))(fc||{}),jae=(e=>(e.ADD_MEDIA="ADD_MEDIA",e.REMOVE_MEDIA="REMOVE_MEDIA",e.UPDATE_PROGRESS="UPDATE_PROGRESS",e))(jae||{});const rQe={addMedia:e=>({type:"ADD_MEDIA",mediaId:e}),removeMedia:e=>({type:"REMOVE_MEDIA",mediaId:e}),updateProgress:(e,t)=>({type:"UPDATE_PROGRESS",mediaId:e,progress:t})},nQe=(e,t)=>{switch(t.type){case"ADD_MEDIA":{if(e.progressMap.has(t.mediaId)){const r=e.progressMap.get(t.mediaId);if(r!==void 0&&r!==100)return e}const o=new Map(e.progressMap);return o.set(t.mediaId,0),{progressMap:o}}case"REMOVE_MEDIA":{const o=new Map(e.progressMap);return o.delete(t.mediaId),{progressMap:o}}case"UPDATE_PROGRESS":{if(!e.progressMap.has(t.mediaId))return e;const o=new Map(e.progressMap);return o.set(t.mediaId,t.progress),{progressMap:o}}default:return e}},aQe=e=>e.progressMap.size===0?0:Array.from(e.progressMap.values()).reduce((o,r)=>o+r,0)/e.progressMap.size,zae=(e,t)=>{const o=Object.values(e).reduce((s,x)=>s+x.fileSize,0),r={};Object.values(e).forEach(s=>{r[s.mediaId]=s.fileSize});const n={},a=new u2(10);return a.start(),(s,x,c)=>{const{progressSum:l,remainSec:d}=s4(c,r,o,n,a),u={progressRatio:l,isDone:s,isError:!!x,remainSec:d>0?d:void 0};t(u)}},Yae=(e,t,o,r)=>{const n=Lt();l4(e,t,o).filter(a=>
82n.isMediaInProgress(a)).forEach(a=>{n.emit(fc.REMOVE,a),x1e(r)})},iQe=(e,t)=>({updateProgress:(o,r)=>{r.progressRatio&&t(r.progressRatio),r.isError&&e({type:"SET_UPLOAD_STATE",payload:rv.UPLOAD_ERROR}),e({type:"SET_UPLOAD_TEXT",payload:o})}}),eI=async e=>{const r=Date.now(),n=r+432e5,a=async()=>{const i=await LOe(e,r),s=h("vcloudProgress.ts");switch(i){case"COMPLETE":{s.info("vcloud upload is completed. projectId: "+e+", status: "+i);return}case"EXPIRED":{s.info("vcloud project is expired. projectId: "+e+". status: "+i);return}case"PENDING":{Date.now()>n&&s.info(`
83          vcloud upload is pending but time limit has expired. projectId: `+e+". status: "+i),s.info("vcloud upload is pending. projectId: "+e+". status: "+i),setTimeout(a,3e4);return}case"ERROR":{s.error("An error ocurred getting vcloud upload progress. projectId: "+e+". status: "+i),setTimeout(a,3e4);return}default:{s.error("An unknown status ocurred getting vcloud upload progress. projectId: "+e+". status: "+i);return}}};a()};class Jo{elapsed;elapsedLaps;lastStarted;lastLap;constructor(){this.elapsed=[],this.elapsedLaps=[],this.lastStarted=Date.now(),this.lastLap=Date.now()}pause=()=>{this.lastStarted===void 0||this.lastLap===void 0||(this.elapsed.push(Date.now()-this.lastStarted),this.elapsedLaps.push(Date.now()-this.lastLap),this.lastStarted=void 0,this.lastLap=void 0)};resume=()=>{if(this.lastStarted!==void 0||this.lastLap!==void 0)return;const t=Date.now();this.lastStarted=t,this.lastLap=t};reset=()=>{this.elapsed=[],this.elapsedLaps=[],this.lastStarted=Date.now(),this.lastLap=Date.now()};getElapsedSec=()=>{const t=this.elapsed.reduce((r,n)=>r+n,0),o=this.lastStarted===void 0?0:Date.now()-this.lastStarted;return(t+o)/1e3};lap=()=>{const t=this.elapsedLaps.reduce((r,n)=>r+n,0),o=this.lastLap===void 0?0:Date.now()-this.lastLap;return this.elapsedLaps=[],this.lastLap=Date.now(),(t+o)/1e3}}const Bae=5e3,hm=async(e,t)=>{const o=uT(e);if(o){h("mediaLoader.ts").info("[getCloudFileblob] mediaInfo is "+JSON.stringify(o));const{projectId:n,mediaId:a,ext:i}=o,s=await Cg(n,a,i);if(s)return s}const r=await fetch(e,{credentials:"include",signal:t});if(!r.ok)throw new C(_.C_VCLOUD_DOWNLOAD_FILE_NOT_CREATED);return await r.blob()},nv=async(e,t,o,r)=>{const n=h("mediaLoader.ts"),a={},i=An(10),s=new Map,x=Object.keys(t);n.info("[loadCloudMediaBlobs] Downloading "+x.length+" files to cache");const c=(u,p,f)=>{const E=p==="Html"?$e().getWebTexboxHtml(u):void 0;E?(a[u]=new Blob([E],{type:"text/html"}),n.warn("[loadCloudMediaBlobs] recovered empty Html blob for "+u)):n.warn("[loadCloudMediaBlobs] empty "+p+" blob, leaving broken: "+u),LUe(u,p,!!E),o?.(!1,!1,{progressRatio:1,type:ha(f),mediaId:u})},l=async u=>{if(r?.signal.aborted)throw new C(_.C_VCLOUD_USER_DOWNLOAD_CANCELED);const p=t[u],f=s.get(p.type)??{hit:0,miss:0};if(!s.has(p.type)&&s.set(p.type,f),p.fileSize===0&&(p.type==="Html"||p.type==="Svg")){c(u,p.type,p.downloadUrl);return}const E=await Cg(e,u,p.ext);if(E){f.hit+=1,n.info("Using OPFS cache for mediaId="+u),a[u]=new Blob([E],{type:E.type}),o?.(!1,!1,{progressRatio:1,type:ha(p.downloadUrl),mediaId:u});return}else f.miss+=1;n.info("Downloading mediaId="+u+" from "+p.downloadUrl);const T=new Jo,O=await fetch(p.downloadUrl,{credentials:"include",signal:r?.signal}),S=Number(O.headers.get("Content-Length"));if(!O.ok||!O.body)throw new C(_.C_VCLOUD_MEDIA_FILE_ERROR,{},"Failed to fetch "+u+": "+O.status+" "+O.statusText);const R=ul(e,u,p.ext),y=Ht(So.CLOUD_CACHE);let v=O.body;if(S){let M=0;v=O.body.pipeThrough(new TransformStream({transform(k,F){M+=k.byteLength;const G=Math.min(M/S,1);o?.(!1,!1,{progressRatio:G,type:ha(p.downloadUrl),mediaId:u}),F.enqueue(k)}}))}await Rg(R,v);const w=pe(T.getElapsedSec());PUe(S,p.ext,w);const N=await y.getFileAsBlob(R);if(!N)throw new C(_.C_VCLOUD_MEDIA_FILE_ERROR,{},"Failed to get cached blob for "+u);a[u]=new Blob([N],{type:N.type}),o?.(!1,!1,{progressRatio:1,type:ha(p.downloadUrl),mediaId:u})};if(x.some(u=>{const p=t[u];return p.fileSize===0&&p.type==="Html"&&u!==Ao})){let u;await Promise.race([$e().getWebAssets().catch(()=>null),new Promise(p=>{u=setTimeout(p,Bae)})]),clearTimeout(u)}try{return await Promise.all(x.map(u=>i(()=>l(u)))),n.info("[loadCloudMediaBlobs] Loaded "+Object.keys(a).length+" blobs"),$Ue(s),a}
83catch(u){const p=ye(u)??_.C_VCLOUD_USER_DOWNLOAD_CANCELED;if(r?.signal.aborted||p===_.C_VCLOUD_USER_DOWNLOAD_CANCELED)throw n.info("[loadCloudMediaBlobsNow] User canceled download"),new C(_.C_VCLOUD_USER_DOWNLOAD_CANCELED);const f="[loadCloudMediaBlobsNow] failed to load media blobs: "+P(u);throw n.error(f),new C(p,{},f)}},Kae=async(e,t)=>{const o=h("mediaLoader.ts"),r={},n=t.filter(i=>i.fileLocation===D.IN_MEMORY&&!ia(i.mediaId));if(n.length===0)return r;o.info("[loadCachedInmemoryBlobs] Checking OPFS cache for "+n.length+" inmemory files");const a=An(10);return await Promise.all(n.map(i=>a(async()=>{const s=yo(i.name),x=await Cg(e,i.mediaId,s);x&&(r[i.mediaId]=new Blob([x],{type:x.type}),o.info("[loadCachedInmemoryBlobs] Found cached blob for mediaId="+i.mediaId))}))),o.info("[loadCachedInmemoryBlobs] Loaded "+Object.keys(r).length+" blobs from OPFS cache"),r},Xae=async(e,t,o,r)=>{const n=$y(t),a=zae(n,o),[i,s]=await Promise.all([nv(e,n,a,r),Kae(e,t.files)]);return a(!0,!1),{...i,...s}},Jae=e=>e?e.startsWith("./")||e.startsWith("../"):!1,uO=(e,t)=>{if(!e||!Jae(e))return e;try{return new URL(e,t).href}catch(o){return h("mediaLoader.ts").warn('Failed to convert relative URL "'+e+'" with baseURL "'+t+'". Error: '+P(o)),e}},qae=(e,t)=>{if(!e.version||e.version<Ty)return e;let o=t;try{const r=new URL(b7()).origin,n=new URL(t).pathname;o=""+r+n}catch(r){return h("mediaLoader.ts").error('Failed to getting cf baseURL from baseURL "'+t+'". Error: '+P(r)),e}return{...e,files:e.files.map(r=>{const n={...r};return n.url&&(n.url=uO(n.url,o)),n.proxyInfo?.videoProxyUrl&&(n.proxyInfo={...n.proxyInfo,videoProxyUrl:uO(n.proxyInfo.videoProxyUrl,o)}),n.proxyInfo?.audioProxyUrls?.length&&(n.proxyInfo={...n.proxyInfo,audioProxyUrls:n.proxyInfo.audioProxyUrls.map(a=>uO(a,o))}),n})}},av=async(e,t)=>{try{const o="snapshots/"+t+"/project.json",r={methodType:"GET",name:o},n=await Nd(e,r);if(n.result!=="GET")return h("mediaLoader.ts").error("Cannot get signed URL for Vrew file, result: "+JSON.stringify(n)),null;const a=await fetch(n.url);if(!a.ok)throw new Error("Failed to fetch Vrew file from "+n.url);const i=await a.json();return qae(i,n.url)}catch(o){const r="Failed to load Vrew file data. err:"+P(o);return h("mediaLoader.ts").error(r),null}},Ex=e=>{if(e.aborted)throw new C(_.C_VCLOUD_USER_DOWNLOAD_CANCELED)},Qae=async(e,t,o,r,n,a,i=!1)=>{const s=h("browserDownloader.ts"),x=be().getUserInfo()?.uid??tn,c=Object.fromEntries(e.files.map(p=>[p.mediaId,p.fileSize])),l=new Jo,d=tN(),u=qe.v4();try{s.info("[Downloading] : browser download started for cloudProjectId : "+o),await ol(o);const p=u0(r,c,Gs.DOWNLOAD,n,0,.3),f=$y(e),E=await nv(o,f,p,a);Ex(a.signal);const T=await H2(e,E);Ex(a.signal),s.info("[Downloading] : loadVrewFileData done. vrewFileData.files.length="+T.files.length);const O=u0(r,c,Gs.DOWNLOAD,n,.3,1),S=await $ae(o,u,T.files,x,O,a.signal,d);Ex(a.signal);const R=await tie(T,u,S);Ex(a.signal);const y=j2(R);s.info("[Downloading] : create local project json done"),Ex(a.signal);const v=Ht(So.BROWSER_PROJECT),w=SA(x,u),N=new TextEncoder,M=N.encode(JSON.stringify(y)),k=new ReadableStream({start(B){B.enqueue(M),B.close()}});await v.saveFile(w,k,!0);const F=new Blob([JSON.stringify(y)],{type:"application/json"});d.snapshotSize=F.size,Ex(a.signal),!i&&await XT().saveProjectInfoToIndexedDB({savePath:u,uid:x,projectName:t,totalSize:d.snapshotSize+d.totalMediaFileSize+d.totalSourceFileSize}),!i&&BN(o);const G=pe(l.getElapsedSec());return CP(o,d,G),{result:"success",projectId:u}}catch(p){const f=ye(p)??_.C_VCLOUD_DOWNLOAD_ERROR;if(s.info("start to handle download error. projectId:"+o+", newProjectId:"+u+", error :"+P(p)),await $h("",{projectId:u,uid:x}),a.signal.aborted||f===_.C_VCLOUD_USER_DOWNLOAD_CANCELED){const O="User canceled download cloud project, projectId: "+o;throw s.info(O),new C(_.C_VCLOUD_USER_DOWNLOAD_CANCELED)}const E=pe(l.getElapsedSec());RP(o,E);const T="falied to download cloud project, projectId: "+o+". error "+P(p);return s.error(T),{result:"error",errorCode:f,msg:T}}},Zae=async({file:e,downloadPath:t,downloadProgress:o,downloadAbortSignal:r,projectId:n})=>{const a=h("browserDownloader.ts"),i=new Jo;
83if(r.aborted)throw new C(_.C_VCLOUD_USER_DOWNLOAD_CANCELED);try{const s=yo(e.name),x=await Cg(n,e.mediaId,s);if(Ex(r),!x||x.size===0)return a.warn("[saveInMemoryFileBrowser] blob not found or empty for mediaId: "+e.mediaId),!1;await Ht(So.BROWSER_PROJECT).saveFile(t,x.stream(),!0),a.info("[saveInMemoryFileBrowser] saved mediaId="+e.mediaId+" to OPFS at "+t+", size="+jr(x.size)+", "+i.getElapsedSec()+"s");const l={mediaId:e.mediaId,type:ha(t),progressRatio:1};return o(!1,!1,l),!0}catch(s){return a.error("[saveInMemoryFileBrowser] failed for mediaId="+e.mediaId+": "+P(s)),!1}},$ae=async(e,t,o,r,n,a,i)=>{const s=h("browserDownloader.ts"),x=An(10),c=[],l=o.map(d=>x(async()=>{if(Ex(a),d.mediaId===_o){s.info("[Downloading] : skip blank video file. fileId:"+d.mediaId);return}const u=Zr(d),p=yo(d.name),f=B5(r,t,d.mediaId,p);if(dT(i,d.fileSize,u?"source":"media"),d.fileLocation===D.REMOTE){await eie({downloadPath:f,remotePath:d.url,downloadProgress:n,downloadAbortSignal:a,mediaId:d.mediaId,fileSize:d.fileSize});return}if(d.fileLocation===D.IN_MEMORY){!await Zae({file:d,downloadPath:f,downloadProgress:n,downloadAbortSignal:a,projectId:e})&&c.push(d.mediaId);return}if(d.fileLocation===D.LOCAL||d.fileLocation===D.LOCAL_TMP){s.warn("[Downloading] LOCAL/LOCAL_TMP not supported in browser for mediaId="+d.mediaId+", skipping"),c.push(d.mediaId);return}s.warn("[Downloading] unsupported fileLocation: "+d.fileLocation+" for mediaId="+d.mediaId+", skipping"),c.push(d.mediaId)}));try{return await Promise.all(l),c.length>0&&s.info("[Downloading] skipped "+c.length+" files"),new Set(c)}catch(d){const u=ye(d)??_.C_VCLOUD_DOWNLOAD_ERROR;if(a.aborted||u===_.C_VCLOUD_USER_DOWNLOAD_CANCELED)throw s.info("User canceled download files"),new C(_.C_VCLOUD_USER_DOWNLOAD_CANCELED);const p="failed to download files. err:"+P(d);throw s.error(p),Ne(d)?d:new C(u)}},eie=async({downloadPath:e,remotePath:t,downloadProgress:o,downloadAbortSignal:r,mediaId:n,fileSize:a})=>{const i=h("browserDownloader.ts"),s=new Jo;if(r.aborted)throw i.info("[Downloading] User canceled download, remotePath: "+t),new C(_.C_VCLOUD_USER_DOWNLOAD_CANCELED);try{const x=await hm(t,r);if(Ex(r),x.size===0)throw i.info("[Downloading] fileSize is 0, downloaded blob size:"+x.size+", expected fileSize:"+a+". mediaId:"+n+", remotePath:"+t),new C(_.C_VCLOUD_DOWNLOAD_FILE_NOT_CREATED);await Ht(So.BROWSER_PROJECT).saveFile(e,x.stream(),!0),i.info("[Downloading] : mediaId is "+n+", saved to OPFS at "+e+", fileSize is "+jr(x.size)+", "+s.getElapsedSec()+"s");const l={mediaId:n,type:ha(e),progressRatio:1};o(!1,!1,l)}catch(x){const c=ye(x)??_.C_VCLOUD_DOWNLOAD_FILE_NOT_CREATED;if(r.aborted||c===_.C_VCLOUD_USER_DOWNLOAD_CANCELED)throw i.info("[Downloading] User canceled download, remotePath: "+t),new C(_.C_VCLOUD_USER_DOWNLOAD_CANCELED);const l="failed to download media. remotePath:"+t+", err:"+P(x);throw i.error(l),new C(c)}},tie=async(e,t,o=new Set)=>{const r=h("browserDownloader.ts");try{const n=An(10),a=await Promise.all(e.files.map(x=>n(async()=>{const c={...x};if(o.has(c.mediaId))return r.info("[createProjectJsonFromSnapshotBrowser] keeping mediaId="+c.mediaId+" info as-is (file was not downloaded)"),c;if(Zr(c)){if(ia(c.mediaId))return{mediaId:c.mediaId,sourceOrigin:c.sourceOrigin,fileSize:c.fileSize,name:c.name,type:"AVMedia",videoAudioMetaInfo:c.videoAudioMetaInfo,sourceType:c.sourceType,fileLocation:D.IN_MEMORY};const d=await gG(c,e.projectId);return d?(r.info("[createProjectJsonFromSnapshotBrowser] updating name for "+x.mediaId+": "+x.name+" → "+d),{mediaId:c.mediaId,sourceOrigin:c.sourceOrigin,fileSize:c.fileSize,name:d,type:"AVMedia",videoAudioMetaInfo:c.videoAudioMetaInfo,sourceType:c.sourceType,fileLocation:D.IN_MEMORY}):(r.warn("[createProjectJsonFromSnapshotBrowser] missing origName for mediaId="+c.mediaId+", skipping"),null)}return{...c,fileLocation:D.IN_MEMORY}}))),i=a.filter(x=>x!==null);r.info("[createProjectJsonFromSnapshotBrowser] processed files count="+i.length+" (skipped="+(a.length-i.length)+")");const s=vt(e,x=>{x.projectId=t,x.files=i});return r.info("[createProjectJsonFromSnapshotBrowser] update vrewFileData.projectId="+t),s}catch(n){const a=ye(n)??_.C_VCLOUD_DOWNLOAD_ERROR,i="[createProjectJsonFromSnapshotBrowser] failed to create local project json. err:"+P(n);throw r.error(i),new C(a,{},i)}},oie=async(e,t,o,r,n,a,i,s,x=!1)=>{const c=h("electronDownloader.ts"),l=a0(n,r),d=Object.fromEntries(t.files.map(f=>[f.mediaId,f.fileSize])),u=new Jo,p=tN();try{await Ue().createFolder(l,fg),c.info("[Downloading] : creating folder (downloadPath: "+l+") for cloudProjectId : "+o+" done."),await ol(o);const f=u0(a,d,Gs.DOWNLOAD,i,0,.3),E=$y(t),T=await nv(o,E,f,s),O=await H2(t,T);c.info("[Downloading] : loadVrewFileData done. vrewFileData.files.length="+O.files.length);const S=u0(a,d,Gs.DOWNLOAD,i,.3,1),R=await xie(o,O.files,l,S,s.signal,e,p),y=await aie(O,l,R),v=j2(y);c.info("[Downloading] : create local project json done"),await Ue().addFile(pG(l),JSON.stringify(v),"utf8");const w=new Blob([JSON.stringify(v)],{type:"application/json"});p.snapshotSize=w.size,await Ue().createVrewFileForVCloudProject({projectPath:l,filename:r+".vrew"}),c.info("[Downloading] : Create Vrew File done. downloadPath : "+l),!x&&BN(o);const N=pe(u.getElapsedSec());return CP(o,p,N),{result:"success",projectId:y.projectId}}catch(f){const E=ye(f)??_.C_VCLOUD_DOWNLOAD_ERROR;if(c.info("start to handle download error. projectId:"+o+", error :"+P(f)),await $h(n),s.signal.aborted||E===_.C_VCLOUD_
83USER_DOWNLOAD_CANCELED){const S="User canceled download cloud project, projectId: "+o;throw c.info(S),new C(_.C_VCLOUD_USER_DOWNLOAD_CANCELED)}const T=pe(u.getElapsedSec());RP(o,T);const O="falied to download cloud project, projectId: "+o+". error "+P(f);return c.error(O),{result:"error",errorCode:E,msg:O}}},tI=async(e,t,o)=>{const r=new Jo,n=uT(e);if(n){h("electronDownloader.ts").info("[downloadCloudFileToLocal] mediaInfo is "+JSON.stringify(n));const{projectId:x,mediaId:c,ext:l}=n,d=await _G(x,c,l,t);if(d){const u=r.getElapsedSec();return _k(pe(u),l,"opfs"),d}}const{name:a}=await Ue().downloadFile(e,t,void 0,o);h("electronDownloader.ts").info("[downloadCloudFileToLocal] downloadedFilePath: "+a+", downloadId: "+o);const i=r.getElapsedSec(),s=yo(a);return _k(pe(i),s,"cloud"),a},_G=async(e,t,o,r)=>{try{const n=await dG(e,t,o);if(!n)return h("electronDownloader.ts").info("[getLocalPathFromOpfs] "+t+"."+o+" not found in opfs"),null;const a=yn(),i=await a.writeStreamFileToLocal(n,r);return h("electronDownloader.ts").info("[getLocalPathFromOpfs] "+t+"."+o+" done"),i.name}catch(n){return h("electronDownloader.ts").error("OPFS read error for "+t+"."+o+", fallback: "+P(n)),null}},rie=(e,t)=>{if(e.fileLocation===D.REMOTE)return!t||!Oo()?gt(e.url):e.name;if(t&&Oo())return e.name;const o=yo(e.name);return e.mediaId+"."+o},nie=async({downloadPath:e,remotePath:t,downloadProgress:o,downloadAbortSignal:r,downloadId:n,mediaId:a,fileSize:i})=>{const s=h("electronDownloader.ts"),x=new Jo;if(r.aborted)throw s.info("[Downloading] User canceled download, remotePath: "+t),new C(_.C_VCLOUD_USER_DOWNLOAD_CANCELED);try{const c=await tI(t,e,n);if(!c||c==="")throw s.info("[Downloading] downloading remotePath : "+t+" for mediaId : "+a+" failed. download path:"+e),new C(_.C_VCLOUD_DOWNLOAD_FILE_NOT_CREATED);const l=await Ue().getFileInfo(c);if(l.size===0)throw s.info("[Downloading] fileSize is 0, downloadedFile size:"+l.size+", fileSize:"+i+". mediaId:"+a+", remotePath:"+t),new C(_.C_VCLOUD_DOWNLOAD_FILE_NOT_CREATED);s.info("[Downloading] : mediaId is "+a+", downloadedFile is "+c+", remotePath is "+t+" done. download fileSize is "+jr(l.size)+", "+x.getElapsedSec()+"s");const d={mediaId:a,type:ha(e),progressRatio:1};o(!1,!1,d)}catch(c){const l=ye(c)??_.C_VCLOUD_DOWNLOAD_FILE_NOT_CREATED;if(r.aborted||l===_.C_VCLOUD_USER_DOWNLOAD_CANCELED)throw s.info("[Downloading] User canceled download, remotePath: "+t),new C(_.C_VCLOUD_USER_DOWNLOAD_CANCELED);const d="failed to download media. remotePath:"+t+", err:"+P(c);throw s.error(d),new C(l)}},aie=async(e,t,o=new Set)=>{const r=h("electronDownloader.ts");try{const n=qe.v4(),a=An(10),i=await Promise.all(e.files.map(c=>a(async()=>{const l={...c};if(o.has(l.mediaId))return r.info("[createProjectJsonFromSnapshotElectron] keeping mediaId="+l.mediaId+" info as-is (file was not downloaded)"),l;if(Zr(l)){if(ia(l.mediaId))return{mediaId:l.mediaId,sourceOrigin:l.sourceOrigin,fileSize:l.fileSize,name:l.name,type:"AVMedia",videoAudioMetaInfo:l.videoAudioMetaInfo,sourceType:l.sourceType,fileLocation:D.IN_MEMORY};const u=await gG(l,e.projectId);if(!u)return r.warn("[createProjectJsonFromSnapshotElectron] missing origName for mediaId="+l.mediaId+", skipping"),null;const p=Zh(u,t);return r.info("[createProjectJsonFromSnapshotElectron] mapping "+l.mediaId+" → "+p),{mediaId:l.mediaId,sourceOrigin:l.sourceOrigin,fileSize:l.fileSize,name:l.name,type:"AVMedia",videoAudioMetaInfo:l.videoAudioMetaInfo,sourceType:l.sourceType,fileLocation:D.LOCAL,path:p}}return MR(l)?{mediaId:l.mediaId,sourceOrigin:l.sourceOrigin,fileSize:l.fileSize,name:l.name,type:"AVMedia",videoAudioMetaInfo:l.videoAudioMetaInfo,sourceType:l.sourceType,fileLocation:D.LOCAL_TMP,path:""}:{...l,fileLocation:D.IN_MEMORY}}))),s=i.filter(c=>c!==null);r.info("[createProjectJsonFromSnapshotElectron] processed files count="+s.length+" (skipped="+(i.length-s.length)+")");const x=vt(e,c=>{c.projectId=n,c.files=s});return r.info("[createProjectJsonFromSnapshotElectron] update vrewFileData.projectId="+n),x}catch(n){const a=ye(n)??_.C_VCLOUD_DOWNLOAD_ERROR,i="[createProjectJsonFromSnapshotElectron] failed to create local project json. err:"+P(n);throw r.error(i),new C(a,{},i)}},iie=async({file:e,downloadPath:t,downloadProgress:o,downloadAbortSignal:r,projectId:n})=>{const a=h("electronDownloader.ts"),i=new Jo;
83if(r.aborted)throw new C(_.C_VCLOUD_USER_DOWNLOAD_CANCELED);try{const s=yo(e.name),x=await dG(n,e.mediaId,s);if(!x)return a.warn("[saveInMemoryFileElectron] file handle not found for mediaId: "+e.mediaId),!1;await yn().writeStreamFileToLocal(x,t),a.info("[saveInMemoryFileElectron] saved mediaId="+e.mediaId+" to "+t+", "+i.getElapsedSec()+"s");const l={mediaId:e.mediaId,type:ha(t),progressRatio:1};return o(!1,!1,l),!0}catch(s){return a.error("[saveInMemoryFileElectron] failed for mediaId="+e.mediaId+": "+P(s)),!1}},sie=async({file:e,downloadPath:t,downloadProgress:o,downloadAbortSignal:r})=>{const n=h("electronDownloader.ts"),a=new Jo;if(r.aborted)throw new C(_.C_VCLOUD_USER_DOWNLOAD_CANCELED);if(e.fileLocation!==D.LOCAL&&e.fileLocation!==D.LOCAL_TMP)return!1;const i=e.path;if(!await Ue().existsFile(e.path))return n.warn("[copyLocalFileElectron] invalid source path for mediaId="+e.mediaId+", path="+i),!1;try{await Ue().copyFile(i,t),n.info("[copyLocalFileElectron] copied mediaId="+e.mediaId+" from "+i+" to "+t+", "+a.getElapsedSec()+"s");const x={mediaId:e.mediaId,type:ha(t),progressRatio:1};return o(!1,!1,x),!0}catch(x){return n.error("[copyLocalFileElectron] failed for mediaId="+e.mediaId+": "+P(x)),!1}},xie=async(e,t,o,r,n,a,i)=>{const s=h("electronDownloader.ts"),x=An(10),c=[],l=t.map(d=>x(async()=>{if(d.mediaId===_o){s.info("[Downloading] : skip blank video file. fileId:"+d.mediaId);return}const u=Zr(d),p=rie(d,u),f=u?Zh(p,o):fG(p,o);if(dT(i,d.fileSize,u?"source":"media"),d.fileLocation===D.REMOTE){await nie({downloadPath:f,remotePath:d.url,downloadProgress:r,downloadAbortSignal:n,downloadId:a,mediaId:d.mediaId,fileSize:d.fileSize});return}if(d.fileLocation===D.IN_MEMORY){!await iie({file:d,downloadPath:f,downloadProgress:r,downloadAbortSignal:n,projectId:e})&&c.push(d.mediaId);return}if(d.fileLocation===D.LOCAL||d.fileLocation===D.LOCAL_TMP){!await sie({file:d,downloadPath:f,downloadProgress:r,downloadAbortSignal:n})&&c.push(d.mediaId);return}s.warn("[Downloading] unsupported fileLocation: "+d.fileLocation+" for mediaId="+d.mediaId+", skipping"),c.push(d.mediaId)}));try{return await Promise.all(l),c.length>0&&s.info("[Downloading] skipped "+c.length+" files"),new Set(c)}catch(d){const u=ye(d)??_.C_VCLOUD_DOWNLOAD_ERROR;if(n.aborted||u===_.C_VCLOUD_USER_DOWNLOAD_CANCELED)throw s.info("User canceled download files"),new C(_.C_VCLOUD_USER_DOWNLOAD_CANCELED);const p="failed to download files. err:"+P(d);throw s.error(p),Ne(d)?d:new C(u)}},cie=async(e,t,o,r,n,a,i,s,x=!1)=>Oo()?oie(e,t,o,r,n,a,i,s,x):Qae(t,r,o,a,i,s,x);class lie{static async enrichFilesAndBlobs(t,o){const r={...o},n={},a=new Set;return this.ensureBlankVideoBlob(r),await this.validateAndEnrichFiles(t,r,n,a),{blobs:r,extractedTexts:n,brokenMediaIds:a}}static ensureBlankVideoBlob(t){!t[_o]&&(t[_o]=se().getBlankVideoInfo().blankAudioBlob,h("VrewFileAdaptor.ts").info("Created blank audio blob for "+_o))}static async validateAndEnrichFiles(t,o,r,n){const a=An(10);await Promise.all(t.map(i=>a(()=>this.validateAndEnrichFile(i,o,r,n)))),h("VrewFileAdaptor.ts").info("[VrewFileDataLoadAdaptor.validateAndEnrichFiles] Validated and enriched "+t.length+" files")}static async validateAndEnrichFile(t,o,r,n){await this.validateFile(t,o,n),(t.type==="Svg"||t.type==="Html")&&await this.extractTextContent(t,o,r,n)}static async validateFile(t,o,r){t.fileLocation===D.IN_MEMORY?this.validateInMemoryBlob(t,o,r):(t.fileLocation===D.LOCAL_TMP||t.fileLocation===D.LOCAL)&&!await Ue().existsFile(t.path)&&(this.markAsBroken(t.mediaId,r),h("VrewFileAdaptor.ts").warn("File does not exist for asset: "+t.mediaId+", path: "+t.path))}static validateInMemoryBlob(t,o,r){const n=o[t.mediaId];(!n||n.size===0)&&(this.markAsBroken(t.mediaId,r),o[t.mediaId]=se().getDummyBlob(),h("VrewFileAdaptor.ts").warn("Missing or empty blob for asset: "+t.mediaId+", name: "+t.name))}static async extractTextContent(t,o,r,n){const a=o[t.mediaId];if(a)r[t.mediaId]=await a.text();else{this.markAsBroken(t.mediaId,n);const i=se().getDummyBlob();o[t.mediaId]=i,r[t.mediaId]=await i.text(),h("VrewFileAdaptor.ts").warn("Blob is null for "+t.type+": "+t.mediaId+", using dummy blob")}}static markAsBroken(t,o){o.add(t)}}class die{usedAssets={};usedAudioTransforms={};usedOverdubInfos={};
83usedBackgroundMap={};baseSourceMediaIds;usedFilterMediaIds;usedReferenceMediaIds;usedAssetMediaIds;usedAudioMediaIds;usedAssetIds;usedBackgroundIds;usedOverdubIds;constructor(t,o,r,n,a){this.usedAssetIds=t.getUsedAssetIds(),this.baseSourceMediaIds=t.getBaseSourceMediaIds(),this.usedFilterMediaIds=new Set,this.usedReferenceMediaIds=t.getUsedReferenceMediaIds(),this.usedOverdubIds=t.getUsedOverdubIds(),this.usedAssetMediaIds=t.getActiveAssetMediaIds(o),this.usedAudioMediaIds=t.getActiveAudioMediaIds(r),this.usedAssetIds.forEach(i=>{const s=L.get(o,i);if(s){L.set(this.usedAssets,i,s.track);const c=s.track.filterEffect?.filterMediaId;c&&this.usedFilterMediaIds.add(c)}const x=L.get(r,i);x&&L.set(this.usedAudioTransforms,i,x)}),this.usedBackgroundIds=t.getUsedBackgroundIds(),this.usedBackgroundIds.forEach(i=>{const s=L.get(a,i);s&&L.set(this.usedBackgroundMap,i,s)}),this.usedOverdubIds.forEach(i=>{const s=L.get(n,i);s&&L.set(this.usedOverdubInfos,i,s)})}getBaseSourceMediaIds=()=>this.baseSourceMediaIds;getUsedFilterMediaIds=()=>this.usedFilterMediaIds;getUsedReferenceMediaIds=()=>this.usedReferenceMediaIds;getUsedAssetMediaIds=()=>this.usedAssetMediaIds;getUsedAudioMediaIds=()=>this.usedAudioMediaIds;getUsedAssets=()=>this.usedAssets;getUsedAudioTransforms=()=>this.usedAudioTransforms;getUsedBackgroundIds=()=>this.usedBackgroundIds;getUsedBackgroundMap=()=>this.usedBackgroundMap;getUsedOverdubInfos=()=>this.usedOverdubInfos}class Yx{usedAssets={};usedAudioTransforms={};usedOverdubInfos={};usedBackgroundMap={};watermarkMediaId;baseSourceMediaIds;usedFilterMediaIds;usedReferenceMediaIds;usedAssetMediaIds;usedAudioMediaIds;usedBackgroundIds;denoiseMap;constructor(t,o,r,n,a,i,s){const x=new die(t,o,r,n,a);this.usedAssets=x.getUsedAssets(),this.usedAudioTransforms=x.getUsedAudioTransforms(),this.usedOverdubInfos=x.getUsedOverdubInfos(),this.baseSourceMediaIds=x.getBaseSourceMediaIds(),this.usedFilterMediaIds=new Set(x.getUsedFilterMediaIds()),this.usedReferenceMediaIds=x.getUsedReferenceMediaIds(),this.usedAssetMediaIds=x.getUsedAssetMediaIds(),this.usedAudioMediaIds=x.getUsedAudioMediaIds(),this.usedBackgroundIds=x.getUsedBackgroundIds(),this.usedBackgroundMap=x.getUsedBackgroundMap(),this.denoiseMap=i,this.watermarkMediaId=s?.mediaId;const c=s?.filterEffect?.filterMediaId;c&&this.usedFilterMediaIds.add(c)}getUsedAssets=()=>({usedAssets:this.usedAssets,usedAudioTransforms:this.usedAudioTransforms,usedOverdubInfos:this.usedOverdubInfos});getUsedBackground=()=>({usedBackgroundIds:this.usedBackgroundIds,usedBackgroundMap:this.usedBackgroundMap});getFileDataAndBlobs=async()=>{const t=new Set;this.baseSourceMediaIds.forEach(s=>{t.add(s);const x=L.get(this.denoiseMap,s);x&&t.add(x)});const o=new Set([...t,...this.usedAssetMediaIds,...this.usedAudioMediaIds,...this.watermarkMediaId?[this.watermarkMediaId]:[]]),r=new Set([...o,...this.usedReferenceMediaIds]),n=s=>s.sourceOrigin===tt.USER&&this.usedFilterMediaIds.has(s.mediaId),a=W2().filter(s=>r.has(s.mediaId)||n(s)).map(s=>this.usedReferenceMediaIds.has(s.mediaId)&&!o.has(s.mediaId)&&!n(s)?Yx.stripNestedReferenceMediaIds(s):s),i={};for(const s of a){if(s.fileLocation!==D.IN_MEMORY)continue;const x=await En(s.mediaId);x&&(i[s.mediaId]=x)}return{files:a,blobs:i}};static stripNestedReferenceMediaIds=t=>t.type==="Image"?t.visualAIGenerationMeta?{...t,visualAIGenerationMeta:{...t.visualAIGenerationMeta,referenceMediaIds:void 0,userReferenceMediaIds:void 0}}:t:t.type==="AVMedia"&&t.visualAIGenerationMeta?{...t,visualAIGenerationMeta:{...t.visualAIGenerationMeta,referenceMediaIds:void 0,userReferenceMediaIds:void 0}}:t;static putProjectMediaIds=t=>t.filter(o=>ia(o.mediaId)?!1:o.fileLocation===D.IN_MEMORY||o.fileLocation===D.LOCAL_TMP).map(o=>o.mediaId);static extractCacheableCloudMediaIds=t=>t.filter(o=>!Zr(o)).map(o=>o.mediaId)}const uie=async(e,t,o,r,n,a,i,s)=>{const x=h("downloadV1.ts"),c=n+"/"+r,l=u0(a,Object.fromEntries(t.medias.map(u=>[u.fileId,u.fileSize])),Gs.DOWNLOAD,i),d=new Jo;try{await Ue().createFolder(c,fg),x.info("[Downloading] : creating folder (downloadPath: "+c+") for projectId : "+o+" done.");const u=await mie(t,c,l,s.signal,e);await Ue().createVrewFileForVCloudProject({projectPath:c,filename:r+".vrew"}),x.info("[Downloading] : Create Vrew File done. downloadPath : "+c),BN(o),l(!0,!1);const p=pe(d.getElapsedSec());return CP(o,u,p),{result:"success",projectId:o}}catch(u){l(!1,!0);const p=ye(u)??_.C_VCLOUD_DOWNLOAD_ERROR;if(x.info("start to handle download error. projectId:"+o+", error :"+P(u)),await $h(n),s.signal.aborted||p===_.C_VCLOUD_
83USER_DOWNLOAD_CANCELED){const T="User canceled download cloud project, projectId: "+o;throw x.info(T),new C(_.C_VCLOUD_USER_DOWNLOAD_CANCELED)}const f=pe(d.getElapsedSec());RP(o,f);const E="falied to download cloud project, projectId: "+o+". error "+P(u);return x.error(E),{result:"error",errorCode:p,msg:E}}},EG=async(e,t,o,r,n)=>{const a=h("downloadV1.ts"),i=new Jo,{filename:s,signedUrl:x}=t,c=Ue();if(r.aborted)throw a.info("[Downloading] User canceled download, fileId: "+t.fileId),new C(_.C_VCLOUD_USER_DOWNLOAD_CANCELED);try{const{name:l}=await Ue().downloadFile(x,e,void 0,n);if(!l||l==="")throw a.info("[Downloading] downloading "+s+" failed. download path:"+e+", uploaded Path: "+s),new C(_.C_VCLOUD_DOWNLOAD_FILE_NOT_CREATED);const d=await c.getFileInfo(l);if(d.size!==t.fileSize)throw a.info("[Downloading] fileSize mismatch, downloadedFile size:"+d.size+", uploadedFile size:"+t.fileSize),new C(_.C_VCLOUD_DOWNLOAD_FILE_NOT_CREATED);const u={mediaId:t.fileId,type:ha(e),progressRatio:1};o(!1,!1,u),a.info("[Downloading] : fileName is "+s+", fileId is "+t.fileId+", downloadedFile is "+l+" done, "+i.getElapsedSec()+"s");return}catch(l){const d=ye(l)??_.C_VCLOUD_DOWNLOAD_FILE_NOT_CREATED;if(r.aborted||d===_.C_VCLOUD_USER_DOWNLOAD_CANCELED)throw a.info("[Downloading] User canceled download, fileId: "+t.fileId),new C(_.C_VCLOUD_USER_DOWNLOAD_CANCELED);const u="failed to download media. filename:"+s+", downloadPath:"+e+", err:"+P(l);throw a.error(u),new C(d)}},pie=async(e,t,o,r,n)=>{try{const a=pG(t);return await EG(a,e,o,r,n),a}catch(a){if(r.aborted||ye(a)===_.C_VCLOUD_USER_DOWNLOAD_CANCELED)throw h("downloadV1.ts").info("User canceled download cloud project snapshot."),new C(_.C_VCLOUD_USER_DOWNLOAD_CANCELED);const i="failed to download snapshot. err:"+P(a);throw h("downloadV1.ts").error(i),Ne(a)?a:new C(_.C_VCLOUD_DOWNLOAD_ERROR)}},fie=async(e,t,o)=>{try{await Ue().addFile(e,JSON.stringify(t),"utf8"),h("downloadV1.ts").info("successfully created project json file for vcloud, projectPath : "+e)}catch(r){if(o.aborted||ye(r)===_.C_VCLOUD_USER_DOWNLOAD_CANCELED)throw h("downloadV1.ts").info("User canceled in creating project json file."),new C(_.C_VCLOUD_USER_DOWNLOAD_CANCELED);const n="failed to create project json file. err:"+P(r);throw h("downloadV1.ts").error(n),new C(_.C_VCLOUD_DOWNLOAD_FILE_NOT_CREATED)}},gie=(e,t,o,r)=>{if(t.includes(o.fileId))return{type:"media",path:fG(o.filename,r)};const a=L.get(e,o.fileId);if(a)return{type:"source",path:Zh(a,r)}},_ie=async(e,t,o,r,n,a,i,s)=>{const x=gie(e,t,o,r);if(x===void 0){const d="[Downloading] : "+o.filename+", fileId : "+o.fileId+" is not in vrewJson";h("downloadV1.ts").warn(d);return}const{path:c,type:l}=x;dT(n,o.fileSize,l==="source"?"source":"media");try{await EG(c,o,a,i,s)}catch(d){if(i.aborted||ye(d)===_.C_VCLOUD_USER_DOWNLOAD_CANCELED)throw h("downloadV1.ts").info("User canceled download project, media"),new C(_.C_VCLOUD_USER_DOWNLOAD_CANCELED);const u="failed to download media. filename:"+o.filename+", downloadPath:"+c+", err:"+P(d);throw h("downloadV1.ts").error(u),Ne(d)?d:new C(_.C_VCLOUD_DOWNLOAD_ERROR)}},Eie=async(e,t,o)=>{const r=h("downloadV1.ts");r.info("Trying to fetch project.json. path: "+e);try{const n=await fetch(an(e)).then(x=>me(x,_.C_VCLOUD_DOWNLOAD_ERROR)),{sourceFileMap:a,mediaFileList:i,convertedJson:s}=hie(n,t);return{sourceFileMap:a,mediaFileList:i,convertedJson:s}}catch(n){if(o.aborted||Ho(n)===_.C_VCLOUD_USER_DOWNLOAD_CANCELED)throw r.info("user canceled in getMediaSourceAndJsonFromProject"),new C(_.C_VCLOUD_USER_DOWNLOAD_CANCELED);const a="failed to get media source and json from project. err:"+P(n);throw r.error(a),new C(_.C_VCLOUD_DOWNLOAD_ERROR)}},mie=async(e,t,o,r,n)=>{try{const a=tN();a.snapshotSize=e.snapshot.fileSize,dT(a,e.snapshot.fileSize,"snapshot");const i=await pie(e.snapshot,t,o,r,n),{sourceFileMap:s,mediaFileList:x,convertedJson:c}=await Eie(i,t,r);await fie(i,c,r);for await(const l of e.medias)h("downloadV1.ts").info("start to download media file. filename:"+l.filename+", fileId:"+l.fileId+", fileSize : "+jr(l.fileSize)+" downloadPath:"+t),await _ie(s,x,l,t,a,o,r,n);return a}
83catch(a){if(r.aborted||ye(a)===_.C_VCLOUD_USER_DOWNLOAD_CANCELED)throw h("downloadV1.ts").info("User canceled download cloud project files."),new C(_.C_VCLOUD_USER_DOWNLOAD_CANCELED);const i="failed to download files. err:"+P(a);throw h("downloadV1.ts").error(i),Ne(a)?a:new C(_.C_VCLOUD_DOWNLOAD_ERROR)}},hie=(e,t)=>{const o=h("downloadV1.ts"),r=Yx.putProjectMediaIds(e.files);r.length>0&&o.info("parseProjectJsonAndFiles mediaFileList length: "+r.length);const n={},a={...e,files:e.files.map(i=>{if(Zr(i)&&i.fileLocation===D.LOCAL){const s=gt(i.path);return o.info("filename "+s+", fileId "+i.mediaId+" is converted to cloud path"),L.set(n,i.mediaId,s),{...i,path:Zh(s,t)}}return i})};return{sourceFileMap:n,mediaFileList:r,convertedJson:a}};var iv=(e=>(e[e.NO_UPLOADS=0]="NO_UPLOADS",e[e.UPLOADS_CANCELED=1]="UPLOADS_CANCELED",e[e.STAY_IN_PROJECT=2]="STAY_IN_PROJECT",e))(iv||{});const sv=async()=>{const e=Lt();if(!e.hasOngoingCloudOperations())return 0;const t=e.getInProgressMediaIds(),o=h("vcloudUploadConfirm.ts");o.info("[confirmBackgroun
83dUploads] "+t.length+" uploads in progress, hasOngoingOperations: true");const r=Y(),n=Math.max(t.length,1),a={bodyClassName:"general-modal",title:A("popup.title_confirm"),content:A("vcloud.background_upload_in_progress",{count:n}),yesStr:A("vcloud.abort_upload"),noStr:A("vcloud.continue_upload")};return await r.popup(a)===mt.YES?(o.info("[confirmBackgroundUploads] User chose to cancel uploads"),gk("abort",t.length),e.abortAllUploads(),1):(o.info("[confirmBackgroundUploads] User chose to keep current project"),gk("continue",t.length),2)},Iie=async()=>{switch(await sv()){case 0:case 1:return Ts.OK;case 2:return Ts.CANCEL}},Tie=4,Sie=8,mG=(e,t)=>Math.floor(e/t);class Oie{constructor(t){this._sampleRate=t,this._worker=Vh(new Worker(new URL("/try/assets/wsola-B5zbWANh.js",import.meta.url),{type:"module"}))}_sampleRate;_worker;process=async(t,o,r=Tie,n=Sie)=>{const{output:a}=await this._worker.wsola([t],this._sampleRate,o,{slideStride:r,diffStride:n,overlapIdx:0,processIdx:0}),i=mG(t.length,o),s=new Float32Array(i);return s.set(a[0]),s}}class Cie{static _sampleRate=zx;static _processor=null;static getProcessor(t){return(this._processor===null||this._sampleRate!==t)&&(this._sampleRate=t,this._processor=new Oie(t)),this._processor}}const xv=async(e,t,o,r,n)=>Cie.getProcessor(e).process(t,o,r,n),cv={overdub_onboarding_start_menu:{B:"B"},ttv_version_5:{B:"B"}},hG=()=>({overdub_onboarding_start_menu:{activationRatio:1,variantDetails:{A:{ratio:.5},B:{ratio:.5}}},monthly_subscription_consent_banner_due:{activationRatio:1,variantDetails:{A:{ratio:.5},B:{ratio:.5}}},ttv_version_5:{activationRatio:1,variantDetails:{A:{ratio:.5},B:{ratio:.5}}}}),IG="NOT_TARGET",Rie=e=>{const t=h("abTest.ts");if(Aie(e)){const a=ls(e);return t.info("[ABTest] already initialized; "+e+": "+a),!1}const o=hG()[e];if(Math.random()<=o.activationRatio){const a=yie(e);DL(e,a),BFe(e,a),t.info("[ABTest] variant activated; "+e+": "+a)}else DL(e,IG),t.info("[ABTest] excluded from testing; "+e);return!0},Aie=e=>Ve().getObject(Ie.ABTEST)[e]!==void 0,ls=e=>{const t=Ve().getObject(Ie.ABTEST),o=t[e];return o===void 0||o===IG?null:o},yie=e=>{const t=h("abTest.ts"),o=hG()[e],r=Math.random();let n=0,a=null;for(const[i,{ratio:s}]of Object.entries(o.variantDetails))n+=s,r<=n&&!a&&(a=i);return a&&Math.abs(n-1)<.01?a:(t.error("[ABTest] "+e+" has invalid variant configuration."),Object.keys(o.variantDetails)[0])},DL=(e,t)=>{const o=Ve().getObject(Ie.ABTEST),r={...o,[e]:t};Ve().set(Ie.ABTEST,r)};let Mu=class{_promise;constructor(){this._promise=Promise.resolve()}next(t){const o={run:()=>{}},r=new Promise((n,a)=>{o.run=()=>{try{const i=t();return i&&i instanceof Promise?i.then(n).catch(a):(n(i),i)}catch(i){return a(i),i}}});return this._promise=this._promise.then(o.run,o.run),r}};const vf=e=>vie(e),vie=e=>PE(e),xQe=(e,t)=>v9(e,t),TG=({native:e,remote:t,logger:o,workerLabel:r,onDeath:n})=>{let a=null;const i=new Set,s=x=>{if(a)return;const c=new Error(r+" died: "+x);a=c,i.forEach(l=>l(c)),i.clear(),e.terminate(),o.warn(null,"worker died: "+x),n()};return e.onerror=x=>{s(x.message||"error event")},e.onmessageerror=()=>{s("message deserialization failed")},new Proxy(t,{get:(x,c,l)=>{const d=Reflect.get(x,c,l);return typeof d!="function"?d:(...u)=>a?Promise.reject(a):new Promise((p,f)=>{i.add(f);try{Promise.resolve(d(...u)).then(E=>{i.delete(f),p(E)},E=>{i.delete(f),f(E)})}catch(E){i.delete(f),f(E)}})}})},kL="MediaSourceAudioReader";class wie{_strand=new Mu;_worker=null;_media=null;_logger=nn(kL);async read(t){return this._strand.next(async()=>{const o=await this._ensureOpen(t);if(o!==null)try{return await o.readAudio(t.time.as.ms(),t.duration.as.ms(),t.sampleRate,t.numberOfChannels,t.playbackRate)}catch(r){return this._logger.error(null,"error while reading audio "+t.infoId+": "+qr(r)),await this._destroy(),void 0}})}async destroy(){return this._strand.next(()=>this._destroy())}async _ensureOpen(t){const o=Nie(this._media,t);if(this._worker!==null&&o)return this._worker;try{const r=nn(kL+"#"+t.infoId);if(this._worker!==null)await this._worker.reset(t.infoId,t.source,vf(r),Qa("isVerbose"),Qa("isDev"));else{await this._destroy();const n=this._createWorker();await n.init(t.infoId,t.source,vf(r),Qa("isVerbose"),Qa("isDev")),this._worker=n}return this._media={infoId:t.infoId,source:t.source},this._logger=r,this._worker}catch(r){return this._logger.error(null,"error while opening reader "+t.infoId+": "+qr(r)),await this._destroy(),null}}_createWorker(){return Vh(new Worker(new URL("/try/assets/mediaSourceAudioReader.worker-DURWn3HP.js",import.meta.url),{type:"module"}))}async _destroy(){const t=this._worker;this._worker=null,this._media=null,await t?.destroy().catch(()=>{})}}const Nie=(e,t)=>e!==null&&e.infoId===t.infoId&&Pie(e.source,t.source),Pie=(e,t)=>e.kind==="uri"&&t.kind==="uri"?e.uri===t.uri:e.kind==="blob"&&t.kind==="blob"?e.blob===t.blob:!1;let pO=null;const bie=()=>(pO===null&&(pO=new wie),pO),Lie=async e=>{const t=e.source??await Mie(e.mediaId);if(t!==void 0)return bie().read({infoId:e.mediaId,source:t,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,playbackRate:JJ(e.playbackRate??1),time:X.fromSec(e.time),duration:X.fromSec(e.duration)})},Mie=async e=>{const[{getAVMediaFileInfo:t},{resolveWaveformMediaSource:o}]=await Promise.all([sR(()=>Promise.resolve().then(()=>CRe),void 0),sR(()=>import("./waveformSource-Do6U9AL6.js"),__vite__mapDeps([0,1,2,3,4,5]))]),r=t(e);
83if(r?.videoAudioMetaInfo.audioInfo)return o(r)},SG=()=>Qa("forceCorePlayerEngine"),Die=async(e,t)=>{const o=h("overdub.ts"),r=await V2(t),n={uid:e,base64Audio:r};await yr(_.A_AUTH_GERNAL_ERROR,"No idToken or uid at uploadContextAudioToServer",h("overdub.ts"));const a={method:"POST",body:JSON.stringify(n)},i=await Pn("/upload-overdub-context-audio",a),s=await me(i,_.C_NETWORK_REQUEST_FAILED);if(s.result==="error"){const x="Error during uploading context audio: "+JSON.stringify(s);throw new C(_.C_OVERDUB_UPLOAD_CONTEXT_AUDIO_FAILED,{},x)}return o.info("Uploaded overdub context audio successfully, requestId: "+s.requestId),{requestId:s.requestId}},kie=async(e,t,o)=>{const{deviceId:r,deviceName:n,machineId:a}=await Ia(),i=await zo(),s=Xo(),x={uid:e,deviceId:r,deviceName:n,machineId:a,cid:i,requestId:t,clientType:s,version:H1,...o};await yr(_.A_AUTH_GERNAL_ERROR,"No idToken or uid at requestOverdubToServer",h("overdub.ts"));const c={method:"POST",body:JSON.stringify(x)},l=await Pn("/request-overdub",c),d=await me(l,_.C_NETWORK_REQUEST_FAILED);if(d.result==="pending"&&h("overdub.ts").info("Reached the API Gateway connection keep-alive limit. but continue process, requestId: "+t),d.result==="error"){const u="Error during overdub request: "+JSON.stringify(d);throw new C(_.C_OVERDUB_REQUEST_FAILED,{},u)}return{sid:d.sid}},Fie=async(e,t,o)=>{const{deviceId:r,deviceName:n,machineId:a}=await Ia(),i=await zo(),s=Xo(),x={uid:e,deviceId:r,deviceName:n,machineId:a,cid:i,clientType:s,targetText:t,audioLanguage:o},c={method:"POST",body:JSON.stringify(x)},l=x.uid===tn?wT:Pn,d=await l("/request-overdub-demo",c),u=await me(d,_.C_NETWORK_REQUEST_FAILED);if(u.result==="error"){const p="Error during overdub demo request: "+JSON.stringify(u);throw new C(_.C_OVERDUB_REQUEST_FAILED,{},p)}return u},Uie=async(e,t,o,r)=>{const{deviceId:n,deviceName:a,machineId:i}=await Ia(),s=await zo(),x=Xo(),c={uid:e,deviceId:n,requestId:o,deviceName:a,machineId:i,cid:s,sid:t,clientType:x,version:H1,isDemo:r},l=3;for(let d=0;d<l;d++){const u=await Vie(c);switch(u.result){case"success":{const p=u.base64Audio.split(",")[1]||u.base64Audio,f=BU.from(p,"base64");return new Blob([f],{type:"audio/mp3"})}case"error":{const p="Error during get overdub audio: "+JSON.stringify(u);throw new C(_.C_OVERDUB_DOWNLOAD_AUDIO_FAILED,{},p)}
83case"pending":h("overdub.ts").info("getOverdubAudio pending requestId: "+o+", count: "+(d+1));break}await new Promise(p=>setTimeout(p,1e3))}throw new C(_.C_OVERDUB_DOWNLOAD_AUDIO_FAILED)},Vie=async e=>{const t={method:"POST",body:JSON.stringify(e)},o=e.uid===tn?wT:Pn,r=await o("/get-overdub-audio",t);return await me(r,_.C_NETWORK_REQUEST_FAILED)},Gie="/try/assets/ic_ext_link_black-D-yRPtSy.svg";var Kc=(e=>(e.NULL="null",e.EXPORT_ALL="export_all",e.EXPORT_VIDEO="export_video",e.EXPORT_IMAGE="export_image",e.EXPORT_AUDIO="export_audio",e.EXPORT_XML="export_xml",e.EXPORT_CAPTION="export_cation",e.EXPORT_TEXT="export_text",e.IMPORT_VIDEO="import_video",e.NEW_EXPORT="new_export",e.PROCESS_TTV="process_ttv",e.INIT="init",e))(Kc||{});const Wie=["export_video","export_image","export_audio","export_xml","export_cation","export_text","new_export"];var FR=(e=>(e[e.SHOULD_DO_SURVEY=0]="SHOULD_DO_SURVEY",e[e.JOINED_SURVEY=1]="JOINED_SURVEY",e[e.IGNORED_SURVEY=2]="IGNORED_SURVEY",e))(FR||{});const Hie="debugEventSurveyKey";var Ss=(e=>(e.USER_TTS_FEEDBACK="user_tts_feedback",e.STT_FEEDBACK="stt_feedback",e.TTV_FEEDBACK="ttv_feedback",e.DENOISE_FEEDBACK="denoise_feedback",e.OVERDUB_FEEDBACK="overdub_feedback",e.ATV_FEEDBACK="atv_feedback",e))(Ss||{});const jie=async e=>{try{const t=await zo(),o=be().getUserInfo()?.uid,n=await si("/get-survey-info/v3",{method:"POST",body:JSON.stringify({cid:t,uid:o,language:e})}).then(s=>s.json());if(n.error)return h("survey.tsx").error(`get-survey-info internal error : ${n.error}`),null;if(n.result===null)return null;let a=n.result.timingTypes.filter(s=>Object.values(Kc).includes(s)).map(s=>s);return a.includes(Kc.EXPORT_ALL)&&(a=[...a,...Wie]),{...n.result,timingTypes:a}}catch(t){return h("survey.tsx").error(`Failed to get survey info ${P(t)}`),null}},FL=async(e,t)=>{try{const o=await zo(),r=be().getUserInfo()?.uid,a=await si("/update-survey-user-status",{method:"PUT",body:JSON.stringify({cid:o,uid:r,surveyType:e,userStatus:t})}).then(i=>i.json());a.error&&h("survey.tsx").error(`update-survey-user-status internal error : ${a.error}`)}catch(o){h("survey.tsx").error(`Failed to update surveyUserStatus ${P(o)}`)}}
83,zie=async e=>{try{const t=await zo(),o=be().getUserInfo()?.uid,n=await si("/update-survey-display-cnt",{method:"PUT",body:JSON.stringify({cid:t,uid:o,surveyType:e})}).then(a=>a.json());n.error&&h("survey.tsx").error(`update-display-cnt internal error : ${n.error}`)}catch(t){h("survey.tsx").error(`Failed to update displayCnt ${P(t)}`)}},OG={eventCount:0,hasShown:!1},CG=()=>Ve().getObject(Ie.EVENT_SURVEY),RG=e=>{Ve().set(Ie.EVENT_SURVEY,e)},Yie=(e,t=OG)=>{const o=CG();return o[e]||(o[e]=t,RG(o)),o[e]},AG=(e,t)=>{const o=CG();o[e]=t(o[e]||OG),RG(o)},Bie=(e,t=1)=>{AG(e,o=>(o.eventCount+=t,o))},fO=e=>{AG(e,t=>(t.hasShown=!0,t.lastShown=new Date().toISOString(),t))},Kie={[Ss.USER_TTS_FEEDBACK]:{typeformEvent:"USER_TTS_FEEDBACK",activateThreshold:2,isEmbed:!0},[Ss.STT_FEEDBACK]:{typeformEvent:"STT_FEEDBACK",activateThreshold:2,isEmbed:!1},[Ss.TTV_FEEDBACK]:{typeformEvent:"TTV_FEEDBACK",activateThreshold:2,isEmbed:!1},[Ss.DENOISE_FEEDBACK]:{typeformEvent:"DENOISE_FEEDBACK",activateThreshold:2,isEmbed:!1},[Ss.OVERDUB_FEEDBACK]:{typeformEvent:"OVERDUB_FEEDBACK",activateThreshold:2,isEmbed:!0},[Ss.ATV_FEEDBACK]:{typeformEvent:"ATV_FEEDBACK",activateThreshold:0,isEmbed:!1}},yG=(e,t,o,r)=>{const n=h("survey.tsx");let a=!1;const i=t,{eventSurveyType:s,...x}=e,c=Kie[s];if(c===void 0){n.warn(`Invalid surveyType: ${s}`);return}const{typeformEvent:l,activateThreshold:d,isEmbed:u}=c,p=uRe(l);if(p===null){n.info(`No registered typeformId for ${l} (${s}).`);return}const f=async()=>{const y=await zo(),v=be().getUserInfo()?.uid??tn,w=Ha(),N={cid:y,uid:v,version:w,...x};u?Y().popup(az(p,N)):pt().openUrl(wG(p,N)),a=!0,xt.dismiss(i),fO(t),Fz(p)},E=()=>{a||kz(p)},T=()=>xt.popup(vG(o??A(`event_survey.${s}`),f,u),xt.generateToastOption(i,!1,E));if(t===Hie){T();return}const{eventCount:O,hasShown:S,lastShown:R}=Yie(t);O<d?Bie(t,1):S?R||fO(t):(fO(t),T())},vG=(e,t,o,r)=>b.jsxs("div",{className:"survey-text",children:[b.jsx("div",{className:"textrow",children:b.jsx("span",{children:e})}),b.jsx("div",{className:"toastbtnrow",children:b.jsxs(Xie,{className:"cancel",onClick:t,children:[r??A("survey.toast_button"),!o&&b.jsx(fn,{maskColor:ee.gray[850],src:Gie,w:14,h:14,ml:6})]})})]}),Xie=xe("button",{justifyContent:"center",color:ee.gray[850]}),Jie=async e=>{setTimeout(()=>{window.addEventListener("mousedown",()=>{qie(e)},{once:!0})},2e3)},wG=(e,t)=>{const o=Object.keys(t).map(r=>`${r}=${t[r]}`).join("&");return`${XX}/${e}#${o}`},qie=e=>{let t=!1;const{surveyType:o,displayCnt:r}=e;zie(o);const n=(()=>{switch(e.actionType){case"typeform":return e.typeformId;case"redirect":return e.redirectUrl;case"upgrade":return"go_to_upgrade"}})();Dke(n,r);const a=async()=>{t=!0;const s=await zo(),x=be().getUserInfo()?.uid??tn;switch(e.actionType){case"typeform":e.displayMode==="embed"?Y().popup(az(e.typeformId,{cid:s,uid:x})):pt().openUrl(wG(e.typeformId,{cid:s,uid:x}));break;case"redirect":pt().openUrl(e.redirectUrl);break;case"upgrade":{if(!await Vn("displaySurveyToast")){h("survey.tsx").error("start payment and upgrade need ensured login");break}const c=await be().fetchUserInfo(),l=c?.planInfo;if(Kz(l===void 0?$E.NEW:$E.UPGRADE,{source:g.MOVE_TO_SURVEY,origin:{type:"manual"}}),l===void 0){const d=jh(c?.referralInfo?.referralType);WN(d);break}g7(l);break}}xt.dismiss(n)},i=()=>{t?(Fz(n),FL(o,FR.JOINED_SURVEY)):(kz(n),FL(o,FR.IGNORED_SURVEY))};xt.popup(vG(e.displayMsg??A("survey.toast_contents"),a,e.actionType==="typeform"&&e.displayMode==="embed",e.confirmMsg),xt.generateToastOption(n,!1,i))},Xp=e=>e===Gl,cQe=e=>{const t=fU.find(o=>o[e]!==void 0);return ur(t?.[e]??vh)},lQe=e=>td.some(t=>t.mediaId===e),NG=e=>e.some(t=>t.filterEffect!==void 0),Qie=e=>{const t=PG(e);return oP().filter(o=>o.sourceOrigin===tt.USER&&t.has(o.mediaId))},dQe=e=>Qie(e).length>0,uQe=()=>{const e=td.map(t=>t.mediaId);return oP().filter(t=>t.sourceOrigin===tt.VREW_RESOURCE&&e.includes(t.mediaId))},Zie=e=>Array.from(PG(e)),PG=e=>{const t=new Set;return Object.values(e).filter(xr).forEach(o=>{const r=o.filterEffect?.filterMediaId;r&&t.add(r)}),t},UL=e=>ur(ue(e,2)),$ie=(e,t)=>e===void 0||t===void 0?e===t:Math.abs(UL(e)-UL(t))<.01,pQe=(e,t)=>e===void 0||t===void 0?e===t:e.filterMediaId===t.filterMediaId&&$ie(e.alpha,t.alpha),lv=e=>mn(e)||Gn(e),ese=e=>e.some(t=>lv(t)&&(t.editInfo?.flip?.horizontal||t.editInfo?.flip?.vertical)),Im=e=>{const t=e?.flip?.vertical??!1,o=e?.flip?.horizontal??!1;return t&&o?Go.VERTICAL_HORIZONTAL:t?Go.VERTICAL:o?Go.HORIZONTAL:Go.NONE},tse=e=>({scaleX:e?.horizontal===!0?-1:1,scaleY:e?.vertical===!0?-1:1});function Tm(e,t,o){return{from:e,to:t,...o?{type:o}:{}}}function fQe(e,t){return e.length===0?null:e.reduce((r,n)=>({type:t,from:Math.min(r.from,n),to:Math.max(r.to,n+1)}),{type:t,from:Number.MAX_SAFE_INTEGER,to:Number.MIN_SAFE_INTEGER})}const Xc=e=>({...e,from:Math.min(e.from,e.to),to:Math.max(e.from,e.to)}),bG=e=>{const t=Xc(e);return Array.from({length:t.to-t.from},(o,r)=>t.from+r)},LG=(e,t)=>
83{const o=Xc(e);return o.from<=t&&t<o.to};function gQe(e,t){const o="type"in e,r="type"in t;if(o!==r)throw new Error("Cannot find union between Range and TypedRange");if(o&&r&&e.type!==t.type)throw new Error("Cannot find union between different TypedRanges");const n=Xc(e),a=Xc(t);return{...o?{type:e.type}:{},from:Math.min(n.from,a.from),to:Math.max(n.to,a.to)}}const ose=(e,t)=>{const o=Xc(e),r=Xc(t);return o.to>r.from&&o.from<r.to};function _Qe(e,t){const o="type"in e,r="type"in t;if(o!==r)throw new Error("Cannot find intersection between Range and TypedRange");if(o&&r&&e.type!==t.type)throw new Error("Cannot find intersection between different TypedRanges");if(!ose(e,t))return null;const n=Xc(e),a=Xc(t);return{...o?{type:e.type}:{},from:Math.max(n.from,a.from),to:Math.min(n.to,a.to)}}const MG=async(e,t)=>{if(!t.toLowerCase().endsWith(".wav"))return null;try{const r=e.slice(0,44),n=await r.arrayBuffer();if(n.byteLength<44)return null;const a=new DataView(n);if(String.fromCharCode(a.getUint8(0),a.getUint8(1),a.getUint8(2),a.getUint8(3))!=="RIFF"||String.fromCharCode(a.getUint8(8),a.getUint8(9),a.getUint8(10),a.getUint8(11))!=="WAVE"||String.fromCharCode(a.getUint8(12),a.getUint8(13),a.getUint8(14),a.getUint8(15))!=="fmt ")return null;const c=a.getUint16(22,!0),l=a.getUint32(24,!0),d=a.getUint32(28,!0),u=a.getUint16(34,!0),p=u/8,f=l*c*p;return{isValid:Math.abs(d-f)<1,expectedByteRate:f,actualByteRate:d}}catch(o){return h("wavValidation.ts").warn("WAV validation failed: "+P(o)+", name: "+t),null}},rse=async(e,t)=>{if(!e.toLowerCase().endsWith(".wav"))return null;try{const o=an(e),r=await fetch(o);if(!r.ok)return h("wavValidation.ts").warn("Failed to fetch file: "+e),null;const n=await r.blob();return MG(n,t)}catch(o){return h("wavValidation.ts").warn("WAV validation from path failed: "+P(o)+", path: "+e),null}},nse=async e=>(await Promise.all(e.map(async({path:o,blob:r,name:n})=>{let a=null;return r?a=await MG(r,n):a=await rse(o,n),{name:n,validation:a}}))).filter(o=>o.validation!==null&&!o.validation.isValid),ase=()=>{const e="external_link.error_wav_invalid_byterate",t=A(e);if(gU.test(t))return t},ise=async e=>{if(e.length===0)return!0;const t=e[0].name,o=e.length,r=A("wav_validation.invalid_byterate_warning",{filename:t,filecount:o}),n=ase();sse(o);const a=await Y().popup({bodyClassName:"general-modal",title:A("popup.title_warning"),content:r,yesStr:A("wav_validation.continue"),noStr:n?A("wav_validation.view_solution"):void 0,showHeaderCancel:!0});return a===mt.NO&&n?(pt().openUrl(n),!1):a===mt.YES},sse=e=>{I().event(m.WARNING,g.WARN_INVALID_WAV_HEADER,void 0,void 0,JSON.stringify({fileCount:e}))},xse=async()=>(await OA("start_new_project"),Fe()===ce.English&&po(ke.START_MODAL_VERSION,"B"),Y().openModal(st.STARTMODE)),DG=()=>{Y().closeModal(st.STARTMODE)};var Sm=(e=>(e.SKIP_TRANSCRIBE="SKIP_TRANSCRIBE",e.NO_AUDIO_TRACK="NO_AUDIO_TRACK",e.TRANSCRIBE="TRANSCRIBE",e))(Sm||{}),kG=(e=>(e.SKIP_TRANSCRIBE="FILE_SKIP_TRANSCRIBE",e.NO_AUDIO_TRACK="FILE_NO_AUDIO_TRACK",e.TRANSCRIBE="FILE_TRANSCRIBE",e))(kG||{}),cse=(e=>(e.BLOB="BLOB",e.URL="URL",e.PATH="PATH",e))(cse||{}),lse=(e=>(e.RANDOM="random",e.WHISPER="whisper",e.AWS="aws",e.GOOGLE="google",e.ELEVENLABS="elevenlabs",e))(lse||{});const EQe=5,mQe=1,hQe=600*1e3,IQe=3600*1e3,TQe=180*1e3,SQe=[],FG=async(e,t,o,r,n=!1,a)=>{DG();const i=e.filter(s=>s.path.toLowerCase().endsWith(".wav")).map(s=>({path:s.path,blob:s.blob,name:gt(s.path)}));if(i.length>0){const s=await nse(i);if(s.length>0&&!await ise(s))return}if(e.length===1&&e[0].mediaFileInfo&&e[0].mediaFileInfo.audioInfo===void 0){Y().openModal(st.IMPORT_VIDEO_WITHOUT_AUDIO,{path:e[0].path,blob:e[0].blob??null,addSceneIndex:t,mediaFileInfo:e[0].mediaFileInfo,importMethod:o,startMedia:r,execContext:a,mediaId:e[0].mediaId});return}dse({fileList:e,addSceneIndex:t,startMedia:r,mergeSceneOption:n,importMethod:o,execContext:a})},dse=e=>{_ke(),Y().openModal(st.SELECT_LANGUAGE,e)},OQe=async(e,t,o,r=!1,n,a)=>{Y().closeModal(st.MULTI_FILE_UPLOAD),DG();const i=await Qg(e,void 0,!0,a,!0);i.length!==0&&FG(i,t,o,n,r,a)},use=()=>{for(const e of ca())if(!ia(e.mediaId)&&N_e(e))return!0;return!1},pse=()=>ca().filter(e=>e.fileLocation===D.LOCAL),CQe=()=>ca().filter(e=>e.fileLocation===D.REMOTE),RQe=()=>ca().filter(e=>!(ia(e.mediaId)||e.fileLocation===D.LOCAL_TMP)),pl=e=>Hs(e)?.videoAudioMetaInfo.videoInfo!==void 0&&!ia(e),UG=e=>(e.actingOptions?.length??0)>0,AQe=e=>{const t=Vr()||Mo().getDebugVal(Xt.NEW_TTS_ACTING)!==void 0;return(e.actingOptions??[]).filter(o=>t||A("tts.acting_"+o)!=="tts.acting_"+o)},fse=e=>{const t=e.actingOptions??[];return t.includes(nL)?nL:t[0]},Vs=(e,t)=>{const o=e.actingOptions??[];return t!==void 0&&o.includes(t)?t:fse(e)},yQe=e=>e!==void 0&&e!=="none",dv=(e,t)=>(e.speaker?Vs(e.speaker,e.acting):e.acting)===(t.speaker?Vs(t.speaker,t.acting):t.acting),V0=(e,t)=>o=>o.pipe(Ma((r,n)=>zt(e(r,n)).pipe(At(a=>({val:a,idx:n}))),t),aa(),At(r=>r.sort((n,a)=>n.idx-a.idx)),At(r=>r.map(({val:n})=>n)));var gse=(e=>(e.TTS_SPLIT_CAUSE="tts_split_cause",e))(gse||{});const _se=e=>{I().event(m.TTS,"tts_split_cause",void 0,void 0,JSON.stringify(e))},Om=".。。",UE=e=>{const t=/\s\s+/g;return e.replace(t," ").trim()},Ese=e=>{const t=/\u00A0/g;return e.replace(t," ")},VG=e=>{if(Om.split("").some(o=>e.endsWith(o.repeat(2))))return e;const t=new RegExp("["+Om+"]{1}$","g");return e.replace(t,"")},mse=(e,t)=>lx("/tokenize-ja",{body:JSON.stringify({mode:t,to:"hiragana",text:e}),method:"POST"}).then(r=>{if(!r.ok)throw h("text.ts").error("Tokenizing response is not ok, status: "+r.status),new C(_.C_TTS_TOKENIZE_ERROR);return r.json()}).then(r=>{if(r.result)return r.result;throw h("text.ts").error("Tokenizing error: "+P(r.error)),new C(_.C_TTS_TOKENIZE_ERROR)}),hse=(e,t)=>{const o={text:e,mode:t===ft.Taiwanese?"traditional":"simplified"};return lx("/tokenize-zh",{body:JSON.stringify(o),method:"POST"}).then(r=>{if(!r.ok)throw h("text.ts").error("Tokenizing response is not ok, status: "+r.status),new C(_.C_TTS_TOKENIZE_ERROR);return r.json()}).then(r=>{if(r.result)return r.result;throw h("text.ts").error("Tokenizing error: "+P(r.error)),new C(_.C_TTS_TOKENIZE_ERROR)})},Ise=e=>{const t=`)}]」』>"'’”»›》〉⟩〕〛〙〗)]}】`,o=[];let r="";for(let n=0;n<e.length;n++){const a=r[r.length-1];if(r+=e[n],Om.includes(e[n])){if(!!(a&&a.match(/\d/)))continue;let s=n+1;for(;s<e.length&&t.includes(e[s]);)r+=e[s],s++;n=s-1,o.push(r),r=""}}return r&&o.push(r),o.map(ev).filter(dd)},VL=`[)\\]}>"'’”»›》〉⟩〕〛〙〗)]}】」』]`,Tse=new RegExp("(\\u3002+"+VL+"*|[\\uff01\\uff1f]+"+VL+"*|(?<!\\.[a-zA-Z])[.\\uff0e\\uff61!\\u0021?\\u003f\\u2026]+(?=\\s))","u");function GG(e){const t=e.split(Tse),o=[];for(let r=0;r<t.length;r+=2){const n=(t[r]+(t[r+1]||"")).trim();n&&o.push(n)}return o}const Sse=e=>e.replace(/[\u2018-\u2019]/g,"'"),WG=e=>{const t="、,,.!?!?",o=""+t+Om;return e.replace(new RegExp("[\\s"+o+"]+(["+o+"])","g"),"$1").split(" ").filter(r=>r.length!==0&&!r.match(new RegExp("^["+o+"]+$"))).join(" ")},Ose=e=>t=>t.split(e).map(ev).filter(dd),GL=()=>({children:{},replacement:null}),Cse=e=>{if(e.length===0)return null;const t=GL();for(const{from:o,to:r}of e){let n=t;for(const a of o)n.children[a]===void 0&&(n.children[a]=GL()),n=n.children[a];n.replacement=r}return t},Rse=(e,t,o)=>{if(t===null)return[];const r=[];for(let n=0;n<e.length;n++){let a=t,i=n,s=null,x=n,c=null,l=n;for(;i<e.length&&e[i]in a.children;)a=a.children[e[i]],a.replacement!==null&&(s=c,x=l,c=a.replacement,l=i),i++;
83if(c!==null){if(o?.([n,l+1])){s!==null&&(r.push({from:e.slice(n,x+1),to:s}),n=x);continue}r.push({from:e.slice(n,l+1),to:c}),n=l}}return r},HG={build:Cse,match:Rse},uv=(e,t,o)=>{const r=/^\d/,n=/\d$/,a=/\d/,i=/^[.,]$/,s=e.substring(t,o),x=(c,l)=>{let d=c;for(;d>=0&&d<e.length&&i.test(e[d]);)d+=l;return d};if(r.test(s)){const c=x(t-1,-1);if(c>=0&&a.test(e[c]))return!0}if(n.test(s)){const c=x(o,1);if(c<e.length&&a.test(e[c]))return!0}return!1};var jG=(e=>(e.TRANSLATE="TRANSLATE",e))(jG||{}),Jc=(e=>(e.AFRIKAANS="af",e.ALBANIAN="sq",e.AMHARIC="am",e.ARABIC="ar",e.ARMENIAN="hy",e.AZERBAIJANI="az",e.BASQUE="eu",e.BELARUSIAN="be",e.BENGALI="bn",e.BOSNIAN="bs",e.BULGARIAN="bg",e.CATALAN="ca",e.CEBUANO="ceb",e.CHINESE_SIMPLIFIED="zh-CN",e.CORSICAN="co",e.CROATIAN="hr",e.CZECH="cs",e.DANISH="da",e.DUTCH="nl",e.ESPERANTO="eo",e.ESTONIAN="et",e.FINNISH="fi",e.FRENCH="fr",e.FRISIAN="fy",e.GALICIAN="gl",e.GEORGIAN="ka",e.GERMAN="de",e.GREEK="el",e.GUJARATI="gu",e.HAITIAN_CREOLE="ht",e.HAUSA="ha",e.HAWAIIAN="haw",e.HEBREW="he",e.HINDI="hi",e.HMONG="hmn",e.HUNGARIAN="hu",e.ICELANDIC="is",e.IGBO="ig",e.INDONESIAN="id",e.IRISH="ga",e.ITALIAN="it",e.JAVANESE="jv",e.KANNADA="kn",e.KAZAKH="kk",e.KHMER="km",e.KINYARWANDA="rw",e.KURDISH="ku",e.KYRGYZ="ky",e.LAO="lo",e.LATIN="la",e.LATVIAN="lv",e.LITHUANIAN="lt",e.LUXEMBOURGISH="lb",e.MACEDONIAN="mk",e.MALAGASY="mg",e.MALAY="ms",e.MALAYALAM="ml",e.MALTESE="mt",e.MAORI="mi",e.MARATHI="mr",e.MONGOLIAN="mn",e.MYANMAR="my",e.NEPALI="ne",e.NORWEGIAN="no",e.NYANJA="ny",e.ODIA="or",e.PASHTO="ps",e.PERSIAN="fa",e.POLISH="pl",e.PORTUGUESE="pt",e.PUNJABI="pa",e.ROMANIAN="ro",e.RUSSIAN="ru",e.SAMOAN="sm",e.SCOTS_GAELIC="gd",e.SERBIAN="sr",e.SESOTHO="st",e.SHONA="sn",e.SINDHI="sd",e.SINHALA="si",e.SLOVAK="sk",e.SLOVENIAN="sl",e.SOMALI="so",e.SUNDANESE="su",e.SWAHILI="sw",e.SWEDISH="sv",e.TAGALOG="tl",e.TAJIK="tg",e.TAMIL="ta",e.TATAR="tt",e.TELUGU="te",e.THAI="th",e.TURKISH="tr",e.TURKMEN="tk",e.UKRAINIAN="uk",e.URDU="ur",e.UYGHUR="ug",e.UZBEK="uz",e.VIETNAMESE="vi",e.WELSH="cy",e.XHOSA="xh",e.YIDDISH="yi",e.YORUBA="yo",e.ZULU="zu",e))(Jc||{}),zG=(e=>(e[e.RE_TRANSLATE=0]="RE_TRANSLATE",e[e.TRANSLATE_TO_NEW_LANGUAGE=1]="TRANSLATE_TO_NEW_LANGUAGE",e))(zG||{});const Ase="ruby-tag",yse="ruby",vse="text-animation",wse=["bold","italic","strike","underline"],Nse=["outline-on","secondary-outline-on","background-on","shadow-on"],Ro={bold:"bold",italic:"italic",strike:"strike",underline:"underline",font:"font",size:"size",color:"color",outlineOn:"outline-on",secondaryOutlineOn:"secondary-outline-on",backgroundOn:"background-on",shadowOn:"shadow-on",outlineColor:"outline-color",outlineWidth:"outline-width",secondaryOutlineColor:"secondary-outline-color",secondaryOutlineWidth:"secondary-outline-width",background:"background",backgroundAlpha:"background-alpha",backgroundRadius:"background-radius",backgroundPaddingSide:"background-padding-side",backgroundPaddingTop:"background-padding-top",backgroundPaddingBottom:"background-padding-bottom",shadowColor:"shadow-color",shadowColorAlpha:"shadow-color-alpha",shadowPositionX:"shadow-position-x",shadowPositionY:"shadow-position-y",shadowBlurRadius:"shadow-blur-radius",letterSpacing:"letter-spacing",lineHeight:"line-height"},Pse=[yse,Ase],bse=["font","size","color","outline-color","outline-width","secondary-outline-color","secondary-outline-width","background","background-alpha","background-radius","background-padding-side","background-padding-top","background-padding-bottom","shadow-color","shadow-color-alpha","shadow-position-x","shadow-position-y","shadow-blur-radius",Ro.letterSpacing,Ro.lineHeight],YG=[vse],oI=[...wse,...Nse,...bse,...Pse,...YG],vQe="true",wQe="";class Pr{_seconds;constructor(t){this._seconds=t}static max(...t){let o=Pr.fromSec(-1/0);for(const r of t)o=o.as.sec()>r.as.sec()?o:r;return o}static min(...t){let o=Pr.fromSec(1/0);for(const r of t)o=o.as.sec()<r.as.sec()?o:r;return o}get as(){return{us:(t="raw",o=0)=>Pr.round(this._toUS(),t,o),ms:(t="raw",o=0)=>Pr.round(this._toMS(),t,o),sec:(t="raw",o=0)=>Pr.round(this._seconds,t,o),min:(t="raw",o=0)=>Pr.round(this._toMin(),t,o),hour:(t="raw",o=0)=>Pr.round(this._toHour(),t,o)}}static zero(){return new Pr(0)}static fromUS(t){return new Pr(t/1e6)}_toUS(){return this._seconds*1e6}static fromMS(t){return new Pr(t/1e3)}_toMS(){return this._seconds*1e3}static fromSec(t){return new Pr(t)}static fromMin(t){return new Pr(t*60)}_toMin(){return this._seconds/60}static fromHour(t){return new Pr(t*3600)}_toHour(){return this._seconds/3600}add(t){return new Pr(this._seconds+t._seconds)}sub(t){return new Pr(this._seconds-t._seconds)}mul(t){return new Pr(this._seconds*t)}div(t){if(t===0)throw new Error("Division by zero at Time.div");return new Pr(this._seconds/t)}mod(t,o=1e-10){const r=this._seconds%t._seconds;return new Pr(Math.abs(r)<o?0:r)}lt(t){return this._seconds<t._seconds}lte(t){return this._seconds<=t._seconds}gt(t){return this._seconds>t._seconds}gte(t){return this._seconds>=t._seconds}eq(t,o=Number.EPSILON){return Math.abs(this._seconds-t._seconds)<o}static round(t,o="round",r){const n=Math.pow(10,r);return{raw:i=>
83i,round:Math.round,floor:Math.floor,ceil:Math.ceil}[o](t*n)/n}}const Iu=e=>Math.floor(e*1e3),BG=e=>e*1e3,pv=e=>e/1e3,NQe=e=>e/1e3/60,PQe=e=>e/60,WL=e=>e/1024/1024,Lse="/try/assets/ic_asset_effect_direction_down-BuFxKVET.svg",Mse="/try/assets/ic_asset_effect_direction_left-vzKouTEX.svg",Dse="/try/assets/ic_asset_effect_direction_none-DpGOWDcm.svg",kse="/try/assets/ic_asset_effect_direction_right-CFwzIWY-.svg",Fse="/try/assets/ic_asset_effect_direction_up-B0r0cueB.svg",gO="/try/assets/img_animation_dummy-DawZ33YV.png";var bp=(e=>(e.ASSET="asset",e.CAPTION="caption",e))(bp||{}),KG=(e=>(e.IMAGE="image",e.WEB="web",e.SHAPE="shape",e))(KG||{}),Ir=(e=>(e.ZOOM_OUT="zoom-out",e.ZOOM_IN="zoom-in",e.LEFT_TO_RIGHT="left-to-right",e.RIGHT_TO_LEFT="right-to-left",e.TOP_TO_BOTTOM="top-to-bottom",e.BOTTOM_TO_TOP="bottom-to-top",e.CUSTOM="custom",e.MAGIC_VERTICAL="magic-vertical",e.MAGIC_HORIZONTAL="magic-horizontal",e.MAGIC_SQUARE="magic-square",e))(Ir||{}),Use=(e=>(e.TEXT_FLOATING_MENU="text_floating_menu",e.ANNOUNCEMENT_IMAGE="announcement_image",e))(Use||{}),Mc=(e=>(e.TYPING="typing",e.TYPING_UP="typing_up",e.TYPING_DOWN="typing_down",e))(Mc||{}),Me=(e=>(e.BLINK_ONCE="blink-once",e.FADE_IN="fade-in",e.FADE_IN_DOWN="fade-in-down",e.FADE_IN_UP="fade-in-up",e.FADE_IN_LEFT="fade-in-left",e.FADE_IN_RIGHT="fade-in-right",e.RUBBER_BAND_ONCE="rubber-band-once",e.TADA_ONCE="tada-once",e.SHAKE_X_ONCE="shake-x-once",e.SHAKE_Y_ONCE="shake-y-once",e.SWING_ONCE="swing-once",e.HEART_BEAT_ONCE="heart-beat-once",e.POP_IN_ONCE="pop-in-once",e.FLIP_ONCE="flip-once",e.FLIP_IN_X="flip-in-x",e.FLIP_IN_Y="flip-in-y",e.SLIDE_IN_RIGHT="slide-in-right",e.SLIDE_IN_LEFT="slide-in-left",e.ROTATE_IN="rotate-in",e.ROTATE_IN_DOWN_LEFT="rotate-in-down-left",e.ROTATE_IN_DOWN_RIGHT="rotate-in-down-right",e.ROLL_IN="roll-in",e.FOCUS_IN="focus-in",e.FOCUS_IN_DOWN="focus-in-down",e.FOCUS_IN_LEFT="focus-in-left",e.FOCUS_IN_RIGHT="focus-in-right",e.FOCUS_IN_UP="focus-in-up",e.POPPING_IN="popping-in",e.POPPING_IN_DOWN="popping-in-down",e.POPPING_IN_LEFT="popping-in-left",e.POPPING_IN_RIGHT="popping-in-right",e.POPPING_IN_UP="popping-in-up",e.POPPING_ONCE="popping-once",e.MOVING_IN_UP="moving-in-up",e.MOVING_IN_DOWN="moving-in-down",e.MOVING_IN_LEFT="moving-in-left",e.MOVING_IN_RIGHT="moving-in-right",e))(Me||{}),Qe=(e=>(e.FADE_OUT="fade-out",e.FADE_OUT_DOWN="fade-out-down",e.FADE_OUT_UP="fade-out-up",e.FADE_OUT_LEFT="fade-out-left",e.FADE_OUT_RIGHT="fade-out-right",e.FLIP_OUT_X="flip-out-x",e.FLIP_OUT_Y="flip-out-y",e.SLIDE_OUT_RIGHT="slide-out-right",e.SLIDE_OUT_LEFT="slide-out-left",e.ROTATE_OUT="rotate-out",e.ROTATE_OUT_DOWN_LEFT="rotate-out-down-left",e.ROTATE_OUT_DOWN_RIGHT="rotate-out-down-right",e.ROLL_OUT="roll-out",e.FOCUS_OUT="focus-out",e.FOCUS_OUT_DOWN="focus-out-down",e.FOCUS_OUT_LEFT="focus-out-left",e.FOCUS_OUT_RIGHT="focus-out-right",e.FOCUS_OUT_UP="focus-out-up",e.POPPING_OUT="popping-out",e.POPPING_OUT_DOWN="popping-out-down",e.POPPING_OUT_LEFT="popping-out-left",e.POPPING_OUT_RIGHT="popping-out-right",e.POPPING_OUT_UP="popping-out-up",e.MOVING_OUT_UP="moving-out-up",e.MOVING_OUT_DOWN="moving-out-down",e.MOVING_OUT_LEFT="moving-out-left",e.MOVING_OUT_RIGHT="moving-out-right",e))(Qe||{}),rI=(e=>(e.FADE_IN_OUT="fade-in-out",e))(rI||{}),hr=(e=>(e.BLINK="blink",e.TADA="tada",e.SHAKE_X="shake-x",e.SHAKE_Y="shake-y",e.SWING="swing",e.HEART_BEAT="heart-beat",e.POP_IN="pop-in",e.RUBBER_BAND="rubber-band",e.FLIP="flip",e.POPPING="popping",e))(hr||{}),ao=(e=>(e.FADE="fade",e.FLIP="flip",e.FLIP_HIGHLIGHT="flip-highlight",e.FLY="fly",e.ROTATE="rotate",e.ROLL="roll",e.FOCUS="focus",e.ZOOM_DIRECTION="zoom-direction",e.ZOOM_IN="zoom-in",e.ZOOM_CUSTOM="zoom-custom",e.TADA="tada",e.SHAKE="shake",e.SWING="swing",e.RUBBER_BAND="rubber-band",e.HEART_BEAT="heart-beat",e.POP_IN="pop_in",e.BLINK="blink",e.POPPING="pop",e.POPPING_HIGHLIGHT="pop-highlight",e.TYPING="typing",e.MOVING="moving",e))(ao||{}),Jp=(e=>(e.IN="IN",e.OUT="OUT",e.INOUT="INOUT",e))(Jp||{}),Pl=(e=>(e.UP="UP",e.DOWN="DOWN",e.LEFT="LEFT",e.RIGHT="RIGHT",e.NONE="NONE",e))(Pl||{}),Cm=(e=>(e.ONCE="ONCE",e.LOOP="LOOP",e))(Cm||{});const bQe=e=>Eo(Cm).isValue(e),LQe=e=>Eo(Pl).isValue(e),MQe=e=>Eo(Jp).isValue(e);var Vse=(e=>(e.INOUT="INOUT",e.HIGHLIGHT="HIGHLIGHT",e.ZOOM="ZOOM",e))(Vse||{});const XG=[{type:"top-to-bottom",menuState:"ZOOM",preset:"zoom-direction",isDefault:!0,options:{direction:"UP",timing:void 0,interval:void 0}},{type:"bottom-to-top",menuState:"ZOOM",preset:"zoom-direction",isDefault:!1,options:{direction:"DOWN",timing:void 0,interval:void 0}},{type:"right-to-left",menuState:"ZOOM",preset:"zoom-direction",isDefault:!1,options:{direction:"RIGHT",timing:void 0,interval:void 0}},{type:"left-to-right",menuState:"ZOOM",preset:"zoom-direction",isDefault:!1,options:{direction:"LEFT",timing:void 0,interval:void 0}}
83,{type:"zoom-in",menuState:"ZOOM",preset:"zoom-in",isDefault:!0,options:{direction:"UP",timing:void 0,interval:void 0}},{type:"zoom-out",menuState:"ZOOM",preset:"zoom-in",isDefault:!1,options:{direction:"DOWN",timing:void 0,interval:void 0}},{type:"custom",menuState:"ZOOM",preset:"zoom-custom",isDefault:!0,options:{direction:void 0,timing:void 0,interval:void 0}},{type:"typing",menuState:"INOUT",preset:"typing",isDefault:!0,options:{direction:"NONE",timing:"IN",interval:void 0}},{type:"typing_up",menuState:"INOUT",preset:"typing",isDefault:!1,options:{direction:"UP",timing:"IN",interval:void 0}},{type:"typing_down",menuState:"INOUT",preset:"typing",isDefault:!1,options:{direction:"DOWN",timing:"IN",interval:void 0}},{type:"fade-in",menuState:"INOUT",preset:"fade",isDefault:!0,options:{direction:"NONE",timing:"IN",interval:void 0}},{type:"fade-in-up",menuState:"INOUT",preset:"fade",isDefault:!1,options:{direction:"UP",timing:"IN",interval:void 0}},{type:"fade-in-down",menuState:"INOUT",preset:"fade",isDefault:!1,options:{direction:"DOWN",timing:"IN",interval:void 0}},{type:"fade-in-right",menuState:"INOUT",preset:"fade",isDefault:!1,options:{direction:"RIGHT",timing:"IN",interval:void 0}},{type:"fade-in-left",menuState:"INOUT",preset:"fade",isDefault:!1,options:{direction:"LEFT",timing:"IN",interval:void 0}},{type:"fade-out",menuState:"INOUT",preset:"fade",isDefault:!1,options:{direction:"NONE",timing:"OUT",interval:void 0}},{type:"fade-out-up",menuState:"INOUT",preset:"fade",isDefault:!1,options:{direction:"UP",timing:"OUT",interval:void 0}},{type:"fade-out-down",menuState:"INOUT",preset:"fade",isDefault:!1,options:{direction:"DOWN",timing:"OUT",interval:void 0}},{type:"fade-out-right",menuState:"INOUT",preset:"fade",isDefault:!1,options:{direction:"RIGHT",timing:"OUT",interval:void 0}},{type:"fade-out-left",menuState:"INOUT",preset:"fade",isDefault:!1,options:{direction:"LEFT",timing:"OUT",interval:void 0}},{type:"fade-in-out",menuState:"INOUT",preset:"fade",isDefault:!1,options:{direction:"NONE",timing:"INOUT",interval:void 0}},{type:"roll-in",menuState:"INOUT",preset:"roll",isDefault:!0,options:{direction:void 0,timing:"IN",interval:void 0}},{type:"roll-out",menuState:"INOUT",preset:"roll",isDefault:!1,options:{direction:void 0,timing:"OUT",interval:void 0}},{type:"focus-in",menuState:"INOUT",preset:"focus",isDefault:!0,options:{direction:"NONE",timing:"IN",interval:void 0}},{type:"focus-in-up",menuState:"INOUT",preset:"focus",isDefault:!1,options:{direction:"UP",timing:"IN",interval:void 0}},{type:"focus-in-down",menuState:"INOUT",preset:"focus",isDefault:!1,options:{direction:"DOWN",timing:"IN",interval:void 0}},{type:"focus-in-right",menuState:"INOUT",preset:"focus",isDefault:!1,options:{direction:"RIGHT",timing:"IN",interval:void 0}},{type:"focus-in-left",menuState:"INOUT",preset:"focus",isDefault:!1,options:{direction:"LEFT",timing:"IN",interval:void 0}},{type:"focus-out",menuState:"INOUT",preset:"focus",isDefault:!1,options:{direction:"NONE",timing:"OUT",interval:void 0}},{type:"focus-out-up",menuState:"INOUT",preset:"focus",isDefault:!1,options:{direction:"UP",timing:"OUT",interval:void 0}},{type:"focus-out-down",menuState:"INOUT",preset:"focus",isDefault:!1,options:{direction:"DOWN",timing:"OUT",interval:void 0}},{type:"focus-out-right",menuState:"INOUT",preset:"focus",isDefault:!1,options:{direction:"RIGHT",timing:"OUT",interval:void 0}},{type:"focus-out-left",menuState:"INOUT",preset:"focus",isDefault:!1,options:{direction:"LEFT",timing:"OUT",interval:void 0}},{type:"flip-in-x",menuState:"INOUT",preset:"flip",isDefault:!0,options:{direction:"UP",timing:"IN",interval:void 0}},{type:"flip-in-y",menuState:"INOUT",preset:"flip",isDefault:!1,options:{direction:"RIGHT",timing:"IN",interval:void 0}},{type:"flip-out-x",menuState:"INOUT",preset:"flip",isDefault:!1,options:{direction:"UP",timing:"OUT",interval:void 0}},{type:"flip-out-y",menuState:"INOUT",preset:"flip",isDefault:!1,options:{direction:"RIGHT",timing:"OUT",interval:void 0}},{type:"rotate-in",menuState:"INOUT",preset:"rotate",isDefault:!0,options:{direction:"NONE",timing:"IN",interval:void 0}},{type:"rotate-in-down-right",menuState:"INOUT",preset:"rotate",isDefault:!1,options:{direction:"RIGHT",timing:"IN",interval:void 0}},{type:"rotate-in-down-left",menuState:"INOUT",preset:"rotate",isDefault:!1,options:{direction:"LEFT",timing:"IN",interval:void 0}},{type:"rotate-out",menuState:"INOUT",preset:"rotate",isDefault:!1,options:{direction:"NONE",timing:"OUT",interval:void 0}},{type:"rotate-out-down-right",menuState:"INOUT",preset:"rotate",isDefault:!1,options:{direction:"RIGHT",timing:"OUT",interval:void 0}},{type:"rotate-out-down-left",menuState:"INOUT",preset:"rotate",isDefault:!1,options:{direction:"LEFT",timing:"OUT",interval:void 0}},{type:"slide-in-right",menuState:"INOUT",preset:"fly",isDefault:!0,options:{direction:"RIGHT",timing:"IN",interval:void 0}},{type:"slide-in-left",menuState:"INOUT",preset:"fly",isDefault:!1,options:{direction:"LEFT",timing:"IN",interval:void 0}},{type:"slide-out-right",menuState:"INOUT",preset:"fly",isDefault:!1,options:{direction:"RIGHT",timing:"OUT",interval:void 0}},{type:"slide-out-left",menuState:"INOUT",preset:"fly",isDefault:!1,options:{direction:"LEFT",timing:"OUT",interval:void 0}},{type:"popping-in",menuState:"INOUT",preset:"pop",isDefault:!0,options:{direction:"NONE",timing:"IN",interval:void 0}},{type:"popping-in-up",menuState:"INOUT",preset:"pop",isDefault:!1,options:{direction:"UP",timing:"IN",interval:void 0}},{type:"popping-in-down",menuState:"INOUT",preset:"pop",isDefault:!1,options:{direction:"DOWN",timing:"IN",interval:void 0}},{type:"popping-in-right",menuState:"INOUT",preset:"pop",isDefault:!1,options:{direction:"RIGHT",timing:"IN",interval:void 0}},{type:"popping-in-left",menuState:"INOUT",preset:"pop",isDefault:!1,options:{direction:"LEFT",timing:"IN",interval:void 0}},{type:"popping-out",menuState:"INOUT",preset:"pop",isDefault:!1,options:{direction:"NONE",timing:"OUT",interval:void 0}},{type:"popping-out-up",menuState:"INOUT",preset:"pop",isDefault:!1,options:{direction:"UP",timing:"OUT",interval:void 0}},{type:"popping-out-down",menuState:"INOUT",preset:"pop",isDefault:!1,options:{direction:"DOWN",timing:"OUT",interval:void 0}},{type:"popping-out-right",menuState:"INOUT",preset:"pop",isDefault:!1,options:{direction:"RIGHT",timing:"OUT",interval:void 0}},{type:"popping-out-left",menuState:"INOUT",preset:"pop",isDefault:!1,options:{direction:"LEFT",timing:"OUT",interval:void 0}},{type:"tada-once",menuState:"HIGHLIGHT",preset:"tada",isDefault:!0,options:{direction:void 0,timing:void 0,interval:"ONCE"}},{type:"tada",menuState:"HIGHLIGHT",preset:"tada",isDefault:!1,options:{direction:void 0,timing:void 0,interval:"LOOP"}},{type:"shake-y-once",menuState:"HIGHLIGHT",preset:"shake",isDefault:!0,options:{direction:"UP",timing:void 0,interval:"ONCE"}},{type:"shake-y",menuState:"HIGHLIGHT",preset:"shake",isDefault:!1,options:{direction:"UP",timing:void 0,interval:"LOOP"}},{type:"shake-x-once",menuState:"HIGHLIGHT",preset:"shake",isDefault:!1,options:{direction:"RIGHT",timing:void 0,interval:"ONCE"}},{type:"shake-x",menuState:"HIGHLIGHT",preset:"shake",isDefault:!1,options:{direction:"RIGHT",timing:void 0,interval:"LOOP"}},{type:"swing-once",menuState:"HIGHLIGHT",preset:"swing",isDefault:!0,options:{direction:void 0,timing:void 0,interval:"ONCE"}},{type:"swing",menuState:"HIGHLIGHT",preset:"swing",isDefault:!1,options:{direction:void 0,timing:void 0,interval:"LOOP"}},{type:"rubber-band-once",menuState:"HIGHLIGHT",preset:"rubber-band",isDefault:!0,options:{direction:void 0,timing:void 0,interval:"ONCE"}},{type:"rubber-band",menuState:"HIGHLIGHT",preset:"rubber-band",isDefault:!1,options:{direction:void 0,timing:void 0,interval:"LOOP"}},{type:"heart-beat-once",menuState:"HIGHLIGHT",preset:"heart-beat",isDefault:!0,options:{direction:void 0,timing:void 0,interval:"ONCE"}},{type:"heart-beat",menuState:"HIGHLIGHT",preset:"heart-beat",isDefault:!1,options:{direction:void 0,timing:void 0,interval:"LOOP"}},{type:"flip-once",menuState:"HIGHLIGHT",preset:"flip-highlight",isDefault:!0,options:{direction:void 0,timing:void 0,interval:"ONCE"}},{type:"flip",menuState:"HIGHLIGHT",preset:"flip-highlight",isDefault:!1,options:{direction:void 0,timing:void 0,interval:"LOOP"}},{type:"pop-in-once",menuState:"HIGHLIGHT",preset:"pop_in",isDefault:!0,options:{direction:void 0,timing:void 0,interval:"ONCE"}},{type:"pop-in",menuState:"HIGHLIGHT",preset:"pop_in",isDefault:!1,options:{direction:void 0,timing:void 0,interval:"LOOP"}},{type:"blink-once",menuState:"HIGHLIGHT",preset:"blink",isDefault:!0,options:{direction:void 0,timing:void 0,interval:"ONCE"}},{type:"blink",menuState:"HIGHLIGHT",preset:"blink",isDefault:!1,options:{direction:void 0,timing:void 0,interval:"LOOP"}},{type:"popping-once",menuState:"HIGHLIGHT",preset:"pop-highlight",isDefault:!0,options:{direction:void 0,timing:void 0,interval:"ONCE"}}
83,{type:"moving-in-up",menuState:"INOUT",preset:"moving",isDefault:!0,options:{direction:"UP",timing:"IN",interval:void 0}},{type:"moving-in-down",menuState:"INOUT",preset:"moving",isDefault:!1,options:{direction:"DOWN",timing:"IN",interval:void 0}},{type:"moving-in-left",menuState:"INOUT",preset:"moving",isDefault:!1,options:{direction:"LEFT",timing:"IN",interval:void 0}},{type:"moving-in-right",menuState:"INOUT",preset:"moving",isDefault:!1,options:{direction:"RIGHT",timing:"IN",interval:void 0}},{type:"moving-out-up",menuState:"INOUT",preset:"moving",isDefault:!1,options:{direction:"UP",timing:"OUT",interval:void 0}},{type:"moving-out-down",menuState:"INOUT",preset:"moving",isDefault:!1,options:{direction:"DOWN",timing:"OUT",interval:void 0}},{type:"moving-out-left",menuState:"INOUT",preset:"moving",isDefault:!1,options:{direction:"LEFT",timing:"OUT",interval:void 0}},{type:"moving-out-right",menuState:"INOUT",preset:"moving",isDefault:!1,options:{direction:"RIGHT",timing:"OUT",interval:void 0}},{type:"popping",menuState:"HIGHLIGHT",preset:"pop-highlight",isDefault:!1,options:{direction:void 0,timing:void 0,interval:"LOOP"}}];var we=(e=>(e.INSERT_CURSOR="INSERT_CURSOR",e.CORRECTING="CORRECTING",e.CLIP="CLIP",e.ELEMENT="ELEMENT",e.DISABLED="DISABLED",e.CAPTION="CAPTION",e.WATERMARK="WATERMARK",e))(we||{}),Tu=(e=>(e.CLICK="CLICK",e.ENTER_KEY="ENTER_KEY",e.F2_KEY="F2_KEY",e.FLOATING_MENU="FLOATING_MENU",e))(Tu||{}),lo=(e=>(e.MOVE_CURSOR_TO_LEFT="MOVE_CURSOR_TO_LEFT",e.MOVE_CURSOR_TO_RIGHT="MOVE_CURSOR_TO_RIGHT",e.MOVE_CURSOR_TO_POSITION="MOVE_CURSOR_TO_POSITION",e.MOVE_CURSOR_TO_THE_FIRST_OF_PARAGRAPH="MOVE_CURSOR_TO_THE_FIRST_OF_PARAGRAPH",e.MOVE_CURSOR_TO_THE_LAST_OF_PARAGRAPH="MOVE_CURSOR_TO_THE_LAST_OF_PARAGRAPH",e.MOVE_CURSOR_TO_THE_FIRST_OF_LINE="MOVE_CURSOR_TO_THE_FIRST_OF_LINE",e.MOVE_CURSOR_TO_THE_LAST_OF_LINE="MOVE_CURSOR_TO_THE_LAST_OF_LINE",e.MOVE_CURSOR_TO_THE_TOP="MOVE_CURSOR_TO_THE_TOP",e.MOVE_CURSOR_TO_THE_BOTTOM="MOVE_CURSOR_TO_THE_BOTTOM",e.SELECT_ALL="SELECT_ALL",e.SPECIALKEY_FUNCTIONS="SPECIALKEY_FUNCTIONS",e.SET_CORRECTING_FOCUS="SET_CORRECTING_FOCUS",e.SET_WORD_CORRECTOR_RANGE="SET_WORD_CORRECTOR_RANGE",e.MOVE_CURSOR_TO_NEXT_WORD="MOVE_CURSOR_TO_NEXT_WORD",e.MOVE_CURSOR_TO_PREV_WORD="MOVE_CURSOR_TO_PREV_WORD",e.DESELECT_CURSOR="DESELECT_CURSOR",e.MOVE_CURSOR_TO_SELECTED_ELEMENT="MOVE_CURSOR_TO_SELECTED_ELEMENT",e.CURSOR_TEXT_SELECT="CURSOR_ADD_TEXT_SELECTION",e.SELECT_CAPTION_OVERLAY="SELECT_CAPTION_OVERLAY",e.USE_DISABLED_CURSOR="USE_DISABLED_CURSOR",e.SELECT_CLIPS_BY_SELECTION_BOX="SELECT_CLIPS_BY_SELECTION_BOX",e.SELECT_CLIPS_BY_GLOBAL_CLIP_CHUNKS="SELECT_CLIPS_BY_GLOBAL_CLIP_CHUNKS",e.TOGGLE_WORD_CORRECTOR="TOGGLE_WORD_CORRECTOR",e.MOVE_CURSOR_TO_WORD_IN_NEXT_CLIP="MOVE_CURSOR_TO_WORD_IN_NEXT_CLIP",e.MOVE_CURSOR_TO_WORD_IN_PREV_CLIP="MOVE_CURSOR_TO_WORD_IN_PREV_CLIP",e.MOVE_CURSOR_TO_CAPTIONFIELD="MOVE_CURSOR_TO_CAPTIONFIELD",e.MOVE_CURSOR_TO_CAPTIONFIELD_AND_PAUSE="MOVE_CURSOR_TO_CAPTIONFIELD_AND_PAUSE",e.MOVE_CURSOR_TO_SPECIFIC_POSITION="MOVE_CURSOR_TO_SPECIFIC_POSITION",e.MOVE_CURSOR_TO_SELECTED_WATERMARK="MOVE_CURSOR_TO_SELECTED_WATERMARK",e.MOVE_CURSOR_TO_SELECTED_ELEMENTS="MOVE_GLOBAL_CURSOR_TO_SELECTED_ELEMENTS",e.DESELECT_MULTI_ELEMENTS="DESELECT_MULTI_ELEMENTS",e.DESELECT_GLOBAL_MULTI_ELEMENTS="DESELECT_GLOBAL_MULTI_ELEMENTS",e.SET_SELECTED_FROM_ASSET_LIST="SET_SELECTED_FROM_ASSET_LIST",e.INSERT_CURSOR_TO_POSITION="INSERT_CURSOR_TO_POSITION",e.SELECT_GLOBAL_CLIPS_BY_RANGE="SELECT_GLOBAL_CLIPS_BY_RANGE",e.MOVE_CURSOR_TO_SPECIFIC_GLOBAL_POSITION="MOVE_CURSOR_TO_SPECIFIC_GLOBAL_POSITION",e.MOVE_GLOBAL_DISABLED_CURSOR_TO_SPECIFIC_POSITION="MOVE_GLOBAL_DISABLED_CURSOR_TO_SPECIFIC_POSITION",e.UPDATE_CURSOR_POSITION="UPDATE_CURSOR_POSITION",e.TOGGLE_CLIP_SELECTION="TOGGLE_CLIP_SELECTION",e.TOGGLE_SCENE_CLIPS_SELECTION="TOGGLE_SCENE_CLIPS_SELECTION",e.SELECT_CLIPS_BY_SHIFT="SELECT_CLIP_RANGE",e.EXTEND_CLIP_SELECTION="EXTEND_CLIP_SELECTION",e))(lo||{}),Bx=(e=>(e.KEYBOARD_UP="KEYBOARD_UP",e.KEYBOARD_DOWN="KEYBOARD_DOWN",e.MOUSE="MOUSE",e.WORD_CLICK="WORD_CLICK",e))(Bx||{});const Gse=(e,t)=>{let o=null;
83if(document.caretRangeFromPoint!==void 0)o=document.caretRangeFromPoint(e,t);else if(document.caretPositionFromPoint!==void 0){const r=document.caretPositionFromPoint(e,t);r&&(o=document.createRange(),o.setStart(r.offsetNode,r.offset))}return o},JG=(e,t,o=[])=>{if(e.hasChildNodes())for(let n=0;n<e.childNodes.length;++n){const a=[...o,n],i=e.childNodes[n];if(t===i)return a;if(i.hasChildNodes()&&o.length<2){const s=JG(i,t,a);if(s)return s}}},Wse=(e,t)=>{if(t.length===0)return;const[o,...r]=t,n=e.childNodes[o];return n&&r.length?Wse(n,r):n},Hse=(e,t,o)=>{if(!e)return null;const r=e.getBoundingClientRect(),{"padding-left":n,"padding-right":a,"padding-top":i,"padding-bottom":s,"line-height":x,"font-size":c}=zse(e,["padding-left","padding-right","padding-top","padding-bottom","line-height","font-size"]),l=$t(t,r.left+n,r.right-a),d=(x-c)/2||0,u=$t(o,r.top+(i+d),r.bottom-(s+d));return Gse(l,u)},jse=(e,t,o=0)=>{const r=e.getPropertyValue(t),n=parseFloat(r);return isNaN(n)?o:n},zse=(e,t,o,r=0)=>{const n=getComputedStyle(e,o),a=new Map;return t.forEach(s=>{a.set(s,jse(n,s,r))}),Object.fromEntries(a)},DQe=e=>{if(e===null)return;if(e.innerText.length===0)return 0;const t=window.getSelection();if(t&&t.rangeCount){const o=t.getRangeAt(0),r=o.commonAncestorContainer;return!r||!r.parentNode?void 0:o.startOffset}},kQe=e=>{if(e.innerText.length===0||e.innerText.length===1&&e.innerText.endsWith(`
84`))return 0;const t=window.getSelection();if(t&&t.rangeCount){const o=t.getRangeAt(0);let r;if(o.commonAncestorContainer.parentNode===e?r=o.commonAncestorContainer:o.commonAncestorContainer.parentNode&&o.commonAncestorContainer.parentNode.parentNode===e&&(r=o.commonAncestorContainer.parentNode),!r||!r.parentNode)return;let n=0;for(const a of r.parentNode.childNodes){if(a===r)break;if(a instanceof Text)n+=a.length+1;else if(a instanceof HTMLBRElement)n++;else if(a instanceof HTMLDivElement){const i=a;i.innerText.length===1&&i.innerText.endsWith(`
85`)?n+=a.innerText.length:n+=a.innerText.length+1}}return o.startOffset+n}},FQe=e=>{const t=Yse(e.innerText);return t.endsWith(`
86`)?t.length-1:t.length},Yse=e=>e.endsWith(`
87`)?e.slice(0,e.length-1).replace(/(\r\n|\r|\n){2}/g,"$1")+`
88`:e.replace(/(\r\n|\r|\n){2}/g,"$1"),UQe=()=>{const e=window.getSelection();e&&e.removeAllRanges()},VQe=()=>{const e=document.getSelection();if(!e)return!1;const{anchorNode:t,anchorOffset:o,focusNode:r,focusOffset:n}=e;return!(!t||!r||o===n&&t===r)},GQe=(e,t,o,r,n)=>{if(!e)return;const a=Hse(e,r,n);if(a===null)return;const i=JG(e,a.startContainer);return{captionIndex:t,globalClipIndex:o,initCaretPosition:i?{childIndices:i,offset:a.startOffset}:void 0}},qG=e=>e?e.getBoundingClientRect():null,QG=(e,t)=>document.getElementById("captionField-"+_2e(e,t)),Ag=e=>document.getElementById(e.id.toString())?.getBoundingClientRect(),Qi=e=>{if(e.id===void 0)return null;const t=fv();if(!t)return null;const o=$G(e.id)??eW(e.id);if(!o)return null;const r=o.getBoundingClientRect(),n=t.getBoundingClientRect();return{left:r.left-n.left,top:r.top-n.top+t.scrollTop,width:r.width,height:r.height}},WQe=(e,t)=>{const o=document.querySelector("."+Vx.EDITOR_PAGE),r=fv(),n=document.querySelector("."+Vx.TOOLBAR);if(!r||!n||!o)return{x:-1,y:-1};const a=e-r.offsetLeft-o.offsetLeft,i=t-r.offsetTop-o.offsetTop-n.offsetHeight+r.scrollTop;return{x:a,y:i}},HQe=(e,t,o)=>{let r=e,n=!1,a=-1;const i=s=>{if(!s.classList.contains("horizontal-separator"))return!1;const x=s.offsetLeft+s.offsetParent.offsetLeft,c=s.offsetTop+s.offsetParent.offsetTop;return t.x>=x&&t.x<=x+s.offsetWidth&&t.y>=c-2&&t.y<=c+s.offsetHeight+2};for(;r&&!r.classList.contains("transcript");){const s=r.dataset[Ob.WORD];if(s)return s;if(r.classList.contains("words")||r.classList.contains("caption")||i(r))n=!0;else if(n){const x=r.dataset[Ob.CLIP];if(x){a=parseInt(x,void 0);break}}r=r.parentElement}if(a>=0){const s=(p,f,E,T)=>(p-E)*(p-E)+(f-T)*(f-T),x=o[a];let c=Number.MAX_VALUE,l,d=!0,u=-1;for(let p=x.words.length-1;p>=0;p--){const f=Qi(x.words[p]);if(!f)continue;if(u!==f.top&&(u>=0&&(d=!1),u=f.top),!d&&t.y>f.top+f.height)break;const E=s(f.left,f.top,t.x,t.y);E<c&&(l=x.words[p].id,c=E)}return l}},Bse=(e,t)=>{if(e.type===Z.ENTER)return gx.LEFT;const o=Qi(e);if(!o)return gx.LEFT;const r=t.x-o.left,n=Math.abs(r),a=t.y-o.top,i=Math.abs(o.left+o.width-1-t.x);return Math.abs(o.left+(o.width-1)/2-t.x)<o.width*eR/2&&a>=0&&r>=0?gx.MIDDLE:n<i?gx.LEFT:a<0?gx.LEFT:gx.RIGHT},ZG=e=>{const t=document.getElementById("clip-"+e);return t===null?null:{left:t.offsetLeft,top:t.offsetTop,width:t.offsetWidth,height:t.offsetHeight}},Kse=()=>{const e=window.getSelection();if(e&&e.rangeCount!==0){const t=e.getRangeAt(0).cloneRange();t.collapse(!0);const o=t.getClientRects();return o.length===0?e.anchorNode?(t.selectNodeContents(e.anchorNode),t.getBoundingClientRect().x):0:o[o.length-1].x}return 0},jQe=e=>{const t=e.getBoundingClientRect(),o=window.getSelection();if(o&&o.rangeCount!==0){const r=o.getRangeAt(0).cloneRange();r.collapse(!0);const n=r.getClientRects();if(n.length===0){if(o.anchorNode){r.selectNodeContents(o.anchorNode);const i=r.getBoundingClientRect();if(t.top+i.height>i.top||i.height===0)return!0}return!1}const a=n[n.length-1];if(t.top+a.height>a.top)return!0}return!1},zQe=e=>{const t=e.getBoundingClientRect(),o=window.getSelection();if(o&&o.rangeCount!==0){const r=o.getRangeAt(0).cloneRange();r.collapse(!0);const n=r.getClientRects();if(n.length===0){if(o.anchorNode){r.selectNodeContents(o.anchorNode);const i=r.getBoundingClientRect();if(t.bottom-i.height<i.bottom||i.height===0)return!0}return!1}const a=n[n.length-1];if(t.bottom-a.height<a.bottom)return!0}return!1},YQe=(e,t,o)=>Math.max(Math.abs(e.x-t.x),Math.abs(e.y-t.y))>=o,BQe=e=>"scene-"+e,Xse=e=>"scene-header-"+e,Jse=e=>Vx.CLIP_WRAPPER+"-"+e,Td=e=>"clip-"+e,qse=e=>e,Qse=e=>"word-wrapper-"+e,Zse=e=>"asset-overlay-"+e,KQe=(e,t)=>"sentence-gap-menu-"+e+"-"+t,XQe=()=>document.body.clientWidth,JQe=()=>document.body.clientHeight,qQe=(e,t)=>e.closest("."+t),QQe=(e,t)=>e.closest("."+t)!==null,ZQe=(e,t)=>{const{clientX:o}=e,{left:r,width:n}=t.getBoundingClientRect(),a=r+n,i=t.offsetWidth-t.clientWidth;return o>=a-i&&o<=a},$Qe=()=>{const e=document.querySelector("."+Vx.TOOLBAR);return e instanceof HTMLElement?e:null},eZe=()=>{const e=document.querySelector("."+Vx.EDITOR_PAGE);return e instanceof HTMLElement?e:null},fv=()=>{const e=document.querySelector("."+Vx.TRANSCRIPT);return e instanceof HTMLElement?e:null},$se=e=>{const t=document.getElementById(Xse(e));return t instanceof HTMLElement?t:null},e0e=e=>{const t=document.getElementById(Jse(e));return t instanceof HTMLElement?t:null},$G=e=>{const t=document.getElementById(qse(e));return t instanceof HTMLElement?t:null},eW=e=>{const t=document.getElementById(Qse(e));return t instanceof HTMLElement?t:null},tZe=e=>{const t=document.getElementById(Zse(e));return t instanceof HTMLElement?t:null},oZe=e=>{const t=e.id,o=Number(e.getAttribute("data-position")),r=Number(e.getAttribute("data-global-clip-index")),n=Number(e.getAttribute("data-local-index")),a=e.getAttribute("data-is-tts-clip")==="true",i=e.getAttribute("data-is-spacer")==="true",s=e.getAttribute("data-is-enter")==="true";
88return isNaN(o)||isNaN(r)||isNaN(n)?null:{id:t,position:o,globalClipIndex:r,localIndex:n,isTTSClip:a,isSpacer:i,isEnter:s}},tW=e=>e.startsWith("clip-")?e.substring(5):null,rZe=e=>{const t=tW(e.id),o=Number(e.getAttribute("data-global-clip-index"));return t===null||isNaN(o)?null:{id:t,globalClipIndex:o}},nZe=e=>{const t=tW(e.id),o=Number(e.getAttribute("data-global-position"));return t===null||isNaN(o)?null:{id:t,globalPosition:o}},aZe=e=>{const t=Number(e.getAttribute("data-global-position"));return isNaN(t)?null:{globalPosition:t}},iZe=(e,t)=>{const{left:o,width:r}=e.getBoundingClientRect(),n=r/3;return t<=o+n?"left":t<=o+n*2?"center":"right"},sZe=(e,t)=>{const{left:o,width:r}=e.getBoundingClientRect(),n=o+r*(.5-eR/2),a=o+r*(.5+eR/2);return t<n?"left":t<=a?"center":"right"},UR=e=>{const t=Td(e),o=document.getElementById(t);return o instanceof HTMLElement?o:null},_O=e=>UR(e)?.querySelector(".words")??null;var K=(e=>(e.STARTMODAL="STARTMODAL",e.START_WITH_VIDEO_AND_AUDIO="START_WITH_VIDEO_AND_AUDIO",e.START_WITH_TEXT="START_WITH_TEXT",e.START_WITH_VDROP="START_WITH_VDROP",e.START_WITH_PDF="START_WITH_PDF",e.START_WITH_IMAGE="START_WITH_IMAGE",e.START_WITH_RECORD="START_WITH_RECORD",e.START_WITH_AI_CLIP="START_WITH_AI_CLIP",e.START_WITH_SHORTS="START_WITH_SHORTS",e.START_WITH_SHORTS_FRAMEPACK="START_WITH_SHORTS_FRAMEPACK",e.START_WITH_ASSET="START_WITH_ASSET",e.OPEN_PROJECT="OPEN_PROJECT",e.NEW_TAB="NEW_TAB",e.NEW_WINDOW="NEW_WINDOW",e.PLAY="PLAY",e.PAUSE="PAUSE",e.ADD_VIDEO_FILE="ADD_VIDEO_FILE",e.ADD_VIDEO_FILE_FROM_PC="ADD_VIDEO_FILE_FROM_PC",e.ADD_VIDEO_FILE_FROM_PHONE="ADD_VIDEO_FILE_FROM_PHONE",e.ADD_VIDEO_FILE_FROM_RECORD="ADD_VIDEO_FILE_FROM_RECORD",e.VIDEO_REMIX="VIDEO_REMIX",e.VIDEO_RATIO="VIDEO_RATIO",e.SAVE="SAVE",e.SAVE_A_COPY="SAVE_A_COPY",e.SAVE_AS="SAVE_AS",e.SAVE_IN_BROWSER="SAVE_IN_BROWSER",e.SAVE_TO_COMPUTER="SAVE_TO_COMPUTER",e.UPLOAD_TO_CLOUD="UPLOAD_TO_CLOUD",e.EXPORT_VIDEO="EXPORT_VIDEO",e.EXPORT_AS="EXPORT_AS",e.EXPORT_CAPTION="EXPORT_CAPTION",e.EXPORT_TEXT="EXPORT_TEXT",e.EXPORT_PREMIERE="EXPORT_PREMIERE",e.EXPORT_FCPX="EXPORT_FCPX",e.EXPORT_DAVINCI="EXPORT_DAVINCI",e.EXPORT_CAPTION_VIDEO="EXPORT_CAPTION_VIDEO",e.EXPORT_AUDIO="EXPORT_AUDIO",e.EXPORT_IMAGE="EXPORT_IMAGE",e.EXPORT_VREW_PROJECT="EXPORT_VREW_PROJECT",e.THUMBNAIL_GENERATOR="THUMBNAIL_GENERATOR",e.VDROP_UPLOAD="VDROP_UPLOAD",e.CURRENT_VIDEO_FILE="CURRENT_VIDEO_FILE",e.UNDO="UNDO",e.REDO="REDO",e.SELECT_CLIP="SELECT_CLIP",e.SELECT_CLIP_CURRENT="SELECT_CLIP_CURRENT",e.SELECT_CLIP_ALL="SELECT_CLIP_ALL",e.SELECT_CLIP_RANGE_MENU="SELECT_CLIP_RANGE_MENU",e.SELECT_CLIP_RANGE="SELECT_CLIP_RANGE",e.SELECT_SCENE_CLIP_RANGE_MENU="SELECT_SCENE_CLIP_RANGE_MENU",e.SELECT_SCENE_CLIP_RANGE="SELECT_SCENE_CLIP_RANGE",e.SELECT_CLIP_ODD="SELECT_CLIP_ODD",e.SELECT_CLIP_EVEN="SELECT_CLIP_EVEN",e.SELECT_CLIP_REVERSED="SELECT_CLIP_REVERSED",e.SELECT_CLIP_TTS="SELECT_CLIP_TTS",e.SELECT_CLIP_ALL_TTS="SELECT_CLIP_ALL_TTS",e.SELECT_CLIP_SAME_TTS="SELECT_CLIP_SAME_TTS",e.SELECT_ASSET="SELECT_ASSET",e.SELECT_ASSET_AI_IMAGE="SELECT_ASSET_AI_IMAGE",e.SELECT_ASSET_AI_VIDEO="SELECT_ASSET_AI_VIDEO",e.SELECT_ASSET_IMAGE="SELECT_ASSET_IMAGE",e.SELECT_ASSET_VIDEO="SELECT_ASSET_VIDEO",e.SELECT_ASSET_DESIGNED_TEXT="SELECT_ASSET_DESIGNED_TEXT",e.SELECT_ASSET_TEXT="SELECT_ASSET_TEXT",e.SELECT_ASSET_BGM="SELECT_ASSET_BGM",e.SELECT_ASSET_SOUND_EFFECT="SELECT_ASSET_SOUND_EFFECT",e.SELECT_ASSET_TTS_EFFECT="SELECT_ASSET_TTS_EFFECT",e.SELECT_ASSET_TTS_DUBBING="SELECT_ASSET_TTS_DUBBING",e.SELECT_ASSET_SHAPE="SELECT_ASSET_SHAPE",e.SELECT_ASSET_CHARACTER="SELECT_ASSET_CHARACTER",e.SELECT_ASSET_LOTTIE="SELECT_ASSET_LOTTIE",e.COPY="COPY",e.CUT="CUT",e.PASTE="PASTE",e.VREW_AGENT="VREW_AGENT",e.VIDEO_LOCK="VIDEO_LOCK",e.MERGE="MERGE",e.DIVIDE="DIVIDE",e.CLIENT_LINEBREAK="CLIENT_LINEBREAK",e.CAPTION_CORRECTION="CAPTION_CORRECTION",e.AUTO_SPLIT_SCENES="AUTO_SPLIT_SCENES",e.MARKER="MARKER",e.TRUNCATE_SILENT="TRUNCATE_SILENT",e.ORIGINAL_VIEW="ORIGINAL_VIEW",e.FIND="FIND",e.OVERDUB="OVERDUB",e.IMPORT_TIMECODE_TEXT="IMPORT_TIMECODE_TEXT",e.IMPORT_SCRIPT="IMPORT_SCRIPT",e.IMPORT_SUBTITLE="IMPORT_SUBTITLE",e.CAPTION_ON="CAPTION_ON",e.ORIGINAL_CAPTION_ON="ORIGINAL_CAPTION_ON",e.COPY_CAPTION="COPY_CAPTION",e.COPY_ORIGINAL_CAPTION="COPY_ORIGINAL_CAPTION",e.COPY_SELECTED_CAPTION="COPY_SELECTED_CAPTION",e.COPY_SELECTED_ORIGINAL_CAPTION="COPY_SELECTED_ORIGINAL_CAPTION",e.REMOVE_CAPTION="REMOVE_CAPTION",e.REMOVE_ORIGINAL_CAPTION="REMOVE_ORIGINAL_CAPTION",e.REMOVE_SELECTED_CAPTION="REMOVE_SELECTED_CAPTION",e.REMOVE_SELECTED_ORIGINAL_CAPTION="REMOVE_SELECTED_ORIGINAL_CAPTION",e.TRANSLATE_CAPTION="TRANSLATE_CAPTION",e.RE_TRANSLATE="RE_TRANSLATE",e.TRANSLATE_TO_NEW_LANGUAGE="TRANSLATE_TO_NEW_LANGUAGE",e.ADD_TRANSLATE_CAPTION="ADD_TRANSLATE_CAPTION",e.TRANSLATED_CAPTION_ON="TRANSLATED_CAPTION_ON",e.COPY_TRANSLATED_CAPTION="COPY_TRANSLATED_CAPTION",e.COPY_SELECTED_TRANSLATED_CAPTION="COPY_SELECTED_TRANSLATED_CAPTION",e.REMOVE_TRANSLATED_CAPTION="REMOVE_TRANSLATED_CAPTION",e.REMOVE_SELECTED_TRANSLATED_CAPTION="REMOVE_SELECTED_TRANSLATED_CAPTION",e.SPELLCHECK_TOGGLE="SPELLCHECK_TOGGLE",e.CAPTION_SETTING_DELETE="CAPTION_SETTING_DELETE",e.SAVED_CAPTION_FORMATS="SAVED_CAPTION_FORMATS",e.FORMAT_TARGET_ARROW="FORMAT_TARGET_ARROW",e.FORMAT_APPLY_BOLD="FORMAT_APPLY_BOLD",e.FORMAT_APPLY_ITALIC="FORMAT_APPLY_ITALIC",e.FORMAT_FONT_FAMILY="FORMAT_FONT_FAMILY",e.FORMAT_FONT_SIZE="FORMAT_FONT_SIZE",e.FORMAT_TEXT_COLOR="FORMAT_TEXT_COLOR",e.FORMAT_OUTLINE_COLOR="FORMAT_OUTLINE_COLOR",e.TEXT_BACKGROUND_COLOR="TEXT_BACKGROUND_COLOR",e.TEXT_HIGHLIGHT_COLOR="TEXT_HIGHLIGHT_COLOR",e.TEXT_SHADOW_COLOR="TEXT_SHADOW_COLOR",e.TEXT_SPACING="TEXT_SPACING",e.ADVANCED_SETTINGS="ADVANCED_SETTINGS",e.DESIGN_TEXT_CUSTOM_ATTRIBUTES="DESIGN_TEXT_CUSTOM_ATTRIBUTES",e.CAPTION_POSITION="CAPTION_POSITION",e.CAPTION_ANIMATION="CAPTION_ANIMATION",e.SHOW_FORMAT_TAB="SHOW_FORMAT_TAB",e.INSERT_TEXTBOX="INSERT_TEXTBOX",e.INSERT_DESIGNED_TEXTBOX="INSERT_DESIGNED_TEXTBOX",e.INSERT_AI_STYLIZED_CAPTION="INSERT_AI_STYLIZED_CAPTION",e.INSERT_IMAGE_AND_VIDEO="INSERT_IMAGE_AND_VIDEO",e.FREE_SOURCE="FREE_SOURCE",e.FREE_IMAGE="FREE_IMAGE",e.FREE_VIDEO="FREE_VIDEO",e.GIPHY="GIPHY",e.INSERT_SHAPE="INSERT_SHAPE",e.GENERATE_IMAGE="GENERATE_IMAGE",e.GENERATE_VIDEO="GENERATE_VIDEO",e.INSERT_AUTO_GENERATED_IMAGE="INSERT_AUTO_GENERATED_IMAGE",e.CHARACTER="CHARACTER",e.INSERT_BGM="INSERT_BGM",e.RECORD="RECORD",e.INSERT_SOUND_EFFECT="INSERT_SOUND_EFFECT",e.INSERT_BLANKS="INSERT_BLANKS",e.INSERT_BLANK_CLIP="INSERT_BLANK_CLIP",e.INSERT_BLANK_WORD="INSERT_BLANK_WORD",e.INSERT_FREEZE_WORD="INSERT_FREEZE_WORD",e.INSERT_LOTTIE="INSERT_LOTTIE",e.INSERT_TTS_CLIP="INSERT_TTS_CLIP",e.TTS_CLIP_INSERT="TTS_CLIP_INSERT",e.TTS_TEXT_MODIFY="TTS_TEXT_MODIFY",e.TTS_VOICE_MODIFY="TTS_VOICE_MODIFY",e.TTS_EFFECT="TTS_EFFECT",e.TTS_DUBBING="TTS_DUBBING",e.TTS_DUBBING_ALL="TTS_DUBBING_ALL",e.TTS_DUBBING_ALL_ORIGINAL="TTS_DUBBING_ALL_ORIGINAL",e.TTS_DUBBING_ALL_TRANSLATED="TTS_DUBBING_ALL_TRANSLATED",e.TTS_DUBBING_SCENE="TTS_DUBBING_SCENE",e.TTS_DUBBING_SCENE_ORIGINAL="TTS_DUBBING_SCENE_ORIGINAL",e.TTS_DUBBING_SCENE_TRANSLATED="TTS_DUBBING_SCENE_TRANSLATED",e.TTS_DUBBING_SELECTED_CLIPS="TTS_DUBBING_SELECTED_CLIPS",e.TTS_DUBBING_SELECTED_CLIPS_ORIGINAL="TTS_DUBBING_SELECTED_CLIPS_ORIGINAL",e.TTS_DUBBING_SELECTED_CLIPS_TRANSLATED="TTS_DUBBING_SELECTED_CLIPS_TRANSLATED",e.TTS_DUBBING_CURRENT_CLIP="TTS_DUBBING_CURRENT_CLIP",e.TTS_DUBBING_CURRENT_CLIP_ORIGINAL="TTS_DUBBING_CURRENT_CLIP_ORIGINAL",e.TTS_DUBBING_CURRENT_CLIP_TRANSLATED="TTS_DUBBING_CURRENT_CLIP_TRANSLATED",e.TTS_DUBBING_MODIFY_ALL="TTS_DUBBING_MODIFY_ALL",e.TTS_DUBBING_DELETE_ALL="TTS_DUBBING_DELETE_ALL",e.USER_TTS="USER_TTS",e.USER_TTS_SPEA
88KER_LIST="USER_TTS_SPEAKER_LIST",e.VOCAL_DICTIONARY="VOCAL_DICTIONARY",e.TOGGLE_PRONUNCIATION="TOGGLE_PRONUNCIATION",e.INSERT_FRAMEPACK="INSERT_FRAMEPACK",e.CREATE_FRAMEPACK="CREATE_FRAMEPACK",e.INSERT_TEMPLATE="INSERT_TEMPLATE",e.EFFECT_FILTER="EFFECT_FILTER",e.FLIP_HORIZONTAL="FLIP_HORIZONTAL",e.FLIP_VERTICAL="FLIP_VERTICAL",e.EFFECT_ZOOM="EFFECT_ZOOM",e.EFFECT_DENOISE="EFFECT_DENOISE",e.EFFECT_TRANSITION="EFFECT_TRANSITION",e.EFFECT_VOLUME="EFFECT_VOLUME",e.EFFECT_PLAYBACKRATE="EFFECT_PLAYBACKRATE",e.CLIP_BG_COLOR="CLIP_BG_COLOR",e.USER_INFO="USER_INFO",e.SETTINGS="SETTINGS",e.SETTINGS_LANGUAGE="SETTINGS_LANGUAGE",e.SETTINGS_THEME="SETTINGS_THEME",e.SETTINGS_PREVIEW_LOCATION="SETTINGS_PREVIEW_LOCATION",e.SETTINGS_SAFE_EDIT_MODE="SETTINGS_SAFE_EDIT_MODE",e.SETTINGS_WORD_DELETE_BUTTON="SETTINGS_WORD_DELETE_BUTTON",e.SETTINGS_THUMBNAIL_PREVIEW="SETTINGS_THUMBNAIL_PREVIEW",e.SETTINGS_SPELLCHECK="SETTINGS_SPELLCHECK",e.SETTINGS_PERIODS_IN_SUBTITLES="SETTINGS_PERIODS_IN_SUBTITLES",e.SETTINGS_LONG_CAPTION_WARNING="SETTINGS_LONG_CAPTION_WARNING",e.SETTINGS_HWACCEL="SETTINGS_HWACCEL",e.SETTINGS_BACKUP="SETTINGS_BACKUP",e.SETTINGS_PROXY="SETTINGS_PROXY",e.FEEDBACK="FEEDBACK",e.FEEDBACK_CHAT="FEEDBACK_CHAT",e.FEEDBACK_REPORT="FEEDBACK_REPORT",e.DIAGNOSTIC="DIAGNOSTIC",e.SHORTCUT="SHORTCUT",e.ABOUT="ABOUT",e.ANNOUNCEMENT="ANNOUNCEMENT",e.COMMUNITY="COMMUNITY",e.FEATURE_SEARCH="FEATURE_SEARCH",e.EXPERIMENT="EXPERIMENT",e))(K||{});const oW=(e,{videoRatio:t,lastUsedBlankOption:o})=>{switch(e){case K.STARTMODAL:case K.START_WITH_VIDEO_AND_AUDIO:case K.START_WITH_TEXT:case K.START_WITH_VDROP:case K.START_WITH_PDF:case K.START_WITH_IMAGE:case K.START_WITH_RECORD:case K.START_WITH_AI_CLIP:case K.START_WITH_SHORTS:case K.START_WITH_SHORTS_FRAMEPACK:case K.START_WITH_ASSET:return le.START_MODAL;case K.NEW_WINDOW:case K.NEW_TAB:return le.NEW_WINDOW;case K.OPEN_PROJECT:return le.OPEN_PROJECT;case K.PLAY:return le.PLAY;case K.PAUSE:return le.PAUSE;case K.ADD_VIDEO_FILE:case K.ADD_VIDEO_FILE_FROM_PC:case K.ADD_VIDEO_FILE_FROM_PHONE:case K.ADD_VIDEO_FILE_FROM_RECORD:return le.ADD_VIDEO_FILE;case K.VIDEO_REMIX:return le.VIDEO_REMIX;case K.VIDEO_RATIO:switch(t){case he.CLASSIC:return le.VIDEO_RATIO_CLASSIC;case he.WIDE_SCREEN:return le.VIDEO_RATIO_WIDE_SCREEN;case he.SQUARE:return le.VIDEO_RATIO_SQUARE;case he.VERTICAL:return le.VIDEO_RATIO_VERTICAL;case he.INSTAGRAM:return le.VIDEO_RATIO_INSTAGRAM;default:return le.VIDEO_RATIO_INIT}case K.SAVE:{const r=se().getSaveProjectType();return r===Ee.CLOUD?le.CLOUD_SAVE_CHECK:r===Ee.BROWSER?le.BROWSER_SAVE:le.LOCAL_SAVE}case K.SAVE_A_COPY:case K.SAVE_AS:return le.SAVE_A_COPY;case K.SAVE_TO_COMPUTER:return le.SAVE_TO_COMPUTER;case K.SAVE_IN_BROWSER:return le.SAVE_IN_BROWSER;case K.UPLOAD_TO_CLOUD:return le.UPLOAD_TO_CLOUD;case K.EXPORT_VIDEO:return le.EXPORT_VIDEO;case K.EXPORT_AS:case K.EXPORT_CAPTION:case K.EXPORT_TEXT:case K.EXPORT_PREMIERE:case K.EXPORT_FCPX:case K.EXPORT_DAVINCI:case K.EXPORT_CAPTION_VIDEO:case K.EXPORT_AUDIO:case K.EXPORT_IMAGE:case K.EXPORT_VREW_PROJECT:return le.EXPORT_AS;case K.THUMBNAIL_GENERATOR:return le.THUMBNAIL_GENERATOR;case K.VDROP_UPLOAD:return le.VDROP_UPLOAD;case K.CURRENT_VIDEO_FILE:return le.CURRENT_VIDEO_FILE;case K.UNDO:return le.UNDO;case K.REDO:return le.REDO;case K.SELECT_CLIP:case K.SELECT_CLIP_CURRENT:case K.SELECT_CLIP_ALL:case K.SELECT_SCENE_CLIP_RANGE_MENU:case K.SELECT_SCENE_CLIP_RANGE:case K.SELECT_CLIP_RANGE_MENU:case K.SELECT_CLIP_RANGE:case K.SELECT_CLIP_ODD:case K.SELECT_CLIP_EVEN:case K.SELECT_CLIP_REVERSED:case K.SELECT_CLIP_TTS:case K.SELECT_CLIP_ALL_TTS:case K.SELECT_CLIP_SAME_TTS:return le.SELECT_CLIP;case K.SELECT_ASSET:return le.SELECT_ASSET;case K.SELECT_ASSET_AI_IMAGE:return le.SELECT_ASSET_AI_IMAGE;case K.SELECT_ASSET_AI_VIDEO:return le.SELECT_ASSET_AI_VIDEO;case K.SELECT_ASSET_IMAGE:return le.SELECT_ASSET_IMAGE;case K.SELECT_ASSET_VIDEO:return le.SELECT_ASSET_VIDEO;case K.SELECT_ASSET_DESIGNED_TEXT:return le.SELECT_ASSET_DESIGNED_TEXT;case K.SELECT_ASSET_TEXT:return le.SELECT_ASSET_TEXT;case K.SELECT_ASSET_BGM:return le.SELECT_ASSET_BGM;case K.SELECT_ASSET_SOUND_EFFECT:return le.SELECT_ASSET_SOUND_EFFECT;case K.SELECT_ASSET_TTS_EFFECT:return le.SELECT_ASSET_TTS_EFFECT;case K.SELECT_ASSET_TTS_DUBBING:return le.SELECT_ASSET_TTS_DUBBING;case K.SELECT_ASSET_SHAPE:return le.SELECT_ASSET_SHAPE;case K.SELECT_ASSET_CHARACTER:return le.SELECT_ASSET_CHARACTER;case K.SELECT_ASSET_LOTTIE:return le.SELECT_ASSET;
88case K.COPY:return le.COPY;case K.CUT:return le.CUT;case K.PASTE:return le.PASTE;case K.VREW_AGENT:return le.VREW_AGENT;case K.VIDEO_LOCK:return le.VIDEO_LOCK;case K.MERGE:return le.MERGE;case K.DIVIDE:return le.DIVIDE;case K.CLIENT_LINEBREAK:return le.CLIENT_LINEBREAK;case K.CAPTION_CORRECTION:return le.CAPTION_CORRECTION;case K.AUTO_SPLIT_SCENES:return le.AUTO_SPLIT_SCENES;case K.MARKER:return le.MARKER;case K.OVERDUB:return le.OVERDUB;case K.TRUNCATE_SILENT:return le.TRUNCATE_SILENT;case K.ORIGINAL_VIEW:return le.ORIGINAL_VIEW;case K.FIND:return le.FIND;case K.IMPORT_TIMECODE_TEXT:return le.IMPORT_TIMECODE_TEXT;case K.IMPORT_SCRIPT:return le.IMPORT_SCRIPT;case K.IMPORT_SUBTITLE:return le.IMPORT_SUBTITLE;case K.CAPTION_ON:case K.ORIGINAL_CAPTION_ON:return le.CAPTION_ON;case K.COPY_CAPTION:case K.COPY_ORIGINAL_CAPTION:case K.COPY_SELECTED_CAPTION:case K.COPY_SELECTED_ORIGINAL_CAPTION:return le.COPY_CAPTION;case K.REMOVE_CAPTION:case K.REMOVE_ORIGINAL_CAPTION:case K.REMOVE_SELECTED_CAPTION:case K.REMOVE_SELECTED_ORIGINAL_CAPTION:return le.REMOVE_CAPTION;case K.TRANSLATE_CAPTION:case K.RE_TRANSLATE:case K.TRANSLATE_TO_NEW_LANGUAGE:case K.ADD_TRANSLATE_CAPTION:return le.TRANSLATE_CAPTION;case K.TRANSLATED_CAPTION_ON:return le.CAPTION_ON;case K.COPY_TRANSLATED_CAPTION:case K.COPY_SELECTED_TRANSLATED_CAPTION:return le.COPY_TRANSLATED_CAPTION;case K.REMOVE_TRANSLATED_CAPTION:case K.REMOVE_SELECTED_TRANSLATED_CAPTION:return le.REMOVE_TRANSLATED_CAPTION;case K.SPELLCHECK_TOGGLE:return le.SPELLCHECK_TOGGLE;case K.CAPTION_SETTING_DELETE:return le.CAPTION_SETTING_DELETE;case K.SAVED_CAPTION_FORMATS:return le.SAVED_CAPTION_FORMATS;case K.FORMAT_APPLY_BOLD:return le.FORMAT_APPLY_BOLD;case K.FORMAT_APPLY_ITALIC:return le.FORMAT_APPLY_ITALIC;case K.FORMAT_FONT_FAMILY:return le.FORMAT_TEXT_COLOR;case K.FORMAT_FONT_SIZE:return le.FORMAT_FONT_SIZE;case K.FORMAT_TEXT_COLOR:return le.FORMAT_TEXT_COLOR;case K.FORMAT_OUTLINE_COLOR:return le.FORMAT_OUTLINE_COLOR;case K.TEXT_BACKGROUND_COLOR:return le.TEXT_BACKGROUND_COLOR;case K.TEXT_HIGHLIGHT_COLOR:return le.TEXT_HIGHLIGHT_COLOR;case K.TEXT_SHADOW_COLOR:return le.TEXT_SHADOW_COLOR;case K.ADVANCED_SETTINGS:return le.FORMAT_OPEN_ADVANCED;case K.CAPTION_POSITION:return le.CAPTION_POSITION;case K.CAPTION_ANIMATION:return le.CAPTION_ANIMATION;case K.TEXT_SPACING:return le.TEXT_SPACING;case K.INSERT_TEXTBOX:return le.INSERT_TEXTBOX;case K.INSERT_DESIGNED_TEXTBOX:return le.INSERT_DESIGNED_TEXTBOX;case K.INSERT_AI_STYLIZED_CAPTION:return le.INSERT_AI_STYLIZED_CAPTION;case K.INSERT_IMAGE_AND_VIDEO:return le.INSERT_IMAGE_AND_VIDEO;case K.FREE_SOURCE:case K.FREE_IMAGE:case K.FREE_VIDEO:case K.GIPHY:return le.FREE_SOURCE;case K.INSERT_SHAPE:return le.INSERT_SHAPE;case K.GENERATE_IMAGE:return le.GENERATE_IMAGE;case K.GENERATE_VIDEO:return le.GENERATE_VIDEO;case K.INSERT_AUTO_GENERATED_IMAGE:return le.INSERT_AUTO_GENERATED_IMAGE;case K.CHARACTER:return le.CHARACTER;case K.INSERT_BGM:return le.INSERT_BGM;case K.RECORD:return le.RECORD;case K.INSERT_SOUND_EFFECT:return le.INSERT_SOUND_EFFECT;case K.INSERT_BLANKS:return o==="freeze_word"?le.INSERT_FREEZE_WORD:le.INSERT_BLANK_CLIP;case K.INSERT_BLANK_CLIP:case K.INSERT_BLANK_WORD:return le.INSERT_BLANK_CLIP;case K.INSERT_FREEZE_WORD:return le.INSERT_FREEZE_WORD;case K.INSERT_LOTTIE:return"";case K.INSERT_TTS_CLIP:case K.TTS_CLIP_INSERT:case K.TTS_TEXT_MODIFY:case K.TTS_VOICE_MODIFY:return le.INSERT_TTS;case K.TTS_EFFECT:return le.TTS_EFFECT;case K.TTS_DUBBING:case K.TTS_DUBBING_ALL:case K.TTS_DUBBING_ALL_ORIGINAL:case K.TTS_DUBBING_ALL_TRANSLATED:case K.TTS_DUBBING_SCENE:case K.TTS_DUBBING_SCENE_ORIGINAL:case K.TTS_DUBBING_SCENE_TRANSLATED:case K.TTS_DUBBING_SELECTED_CLIPS:case K.TTS_DUBBING_SELECTED_CLIPS_ORIGINAL:case K.TTS_DUBBING_SELECTED_CLIPS_TRANSLATED:case K.TTS_DUBBING_CURRENT_CLIP:case K.TTS_DUBBING_CURRENT_CLIP_ORIGINAL:case K.TTS_DUBBING_CURRENT_CLIP_TRANSLATED:return le.TTS_DUBBING;case K.TTS_DUBBING_MODIFY_ALL:case K.TTS_DUBBING_DELETE_ALL:return le.TTS_DUBBING;case K.USER_TTS:return le.USER_TTS;
88case K.USER_TTS_SPEAKER_LIST:return le.USER_TTS_SPEAKER_LIST;case K.INSERT_FRAMEPACK:return le.INSERT_FRAMEPACK;case K.CREATE_FRAMEPACK:return le.CREATE_FRAMEPACK;case K.INSERT_TEMPLATE:return le.INSERT_TEMPLATE;case K.EFFECT_FILTER:return le.EFFECT_FILTER;case K.FLIP_HORIZONTAL:return le.FLIP_HORIZONTAL;case K.FLIP_VERTICAL:return le.FLIP_VERTICAL;case K.EFFECT_ZOOM:return le.EFFECT_ZOOM;case K.EFFECT_DENOISE:return le.EFFECT_DENOISE;case K.EFFECT_TRANSITION:return le.EFFECT_TRANSITION;case K.EFFECT_VOLUME:return le.EFFECT_VOLUME;case K.EFFECT_PLAYBACKRATE:return le.EFFECT_PLAYBACKRATE;case K.CLIP_BG_COLOR:return le.CLIP_BG_COLOR;case K.USER_INFO:return le.USER_INFO;case K.SETTINGS:case K.SETTINGS_LANGUAGE:case K.SETTINGS_THEME:case K.SETTINGS_PREVIEW_LOCATION:case K.SETTINGS_SAFE_EDIT_MODE:case K.SETTINGS_WORD_DELETE_BUTTON:case K.SETTINGS_THUMBNAIL_PREVIEW:case K.SETTINGS_SPELLCHECK:case K.SETTINGS_PERIODS_IN_SUBTITLES:case K.SETTINGS_LONG_CAPTION_WARNING:case K.SETTINGS_HWACCEL:case K.SETTINGS_BACKUP:case K.SETTINGS_PROXY:return le.SETTING;case K.FEEDBACK:case K.FEEDBACK_REPORT:case K.FEEDBACK_CHAT:return le.FEEDBACK;case K.DIAGNOSTIC:return le.DIAGNOSTIC;case K.SHORTCUT:return le.SHORTCUT;case K.ABOUT:return le.ABOUT;case K.ANNOUNCEMENT:return le.ANNOUNCEMENT;case K.COMMUNITY:return le.DISCORD;case K.DESIGN_TEXT_CUSTOM_ATTRIBUTES:case K.FORMAT_TARGET_ARROW:case K.SHOW_FORMAT_TAB:case K.TOGGLE_PRONUNCIATION:return le.TOGGLE_PRONUNCIATION;case K.FEATURE_SEARCH:return le.FEATURE_SEARCH;case K.VOCAL_DICTIONARY:return le.VOCAL_DICTIONARY;case K.EXPERIMENT:return le.EXPERIMENT}},t0e=new Set([K.UPLOAD_TO_CLOUD,K.SAVE_TO_COMPUTER,K.SAVE_IN_BROWSER]),xZe=(e,t)=>{if(t0e.has(e))return oW(e,{videoRatio:t.videoRatio,lastUsedBlankOption:t.lastUsedBlankOption})},o0e={[K.STARTMODAL]:ee.mint[500]},cZe=e=>o0e[e]??void 0,r0e=e=>gv(e.globalClips,e.props.globalCaptionStyle),n0e=e=>gv(e.globalClips,e.globalCaptionStyle),gv=(e,t)=>{const o=e.flatMap(a=>a.captions.flatMap(i=>i)).filter(a=>a.style),r=o.flatMap(a=>a.text).flatMap(a=>a.ops).flatMap(a=>a.attributes).filter(Se),n=r.map(a=>Mm(a)).map(a=>wR(a.fontName,a.weight));if(t){const{fontName:a,weight:i}=el(t),s=wR(a,i);n.push(s)}return Array.from(new Set(n))},a0e=e=>e===ce.Japanese?Eu.NOTO_FONT_FAMILY_JP:e===ce.Taiwanese?Eu.NOTO_FONT_FAMILY_TC:Eu.PRETENDARD_FONT_FAMILY,rW=()=>$e().getSystemFontFamilies(),nI=()=>$e().getWebFontFamilies(),lZe=()=>nI().filter(e=>e.psName!=="BlackHanSans-Regular"),dZe=()=>$e().getInvalidFontInfos(),uZe=e=>{switch(Math.round(e/100)*100){case 100:return"Thin";case 200:return"Extra light";case 300:return"Light";case 400:return"Normal";case 500:return"Medium";case 600:return"Semi bold";case 700:return"Bold";case 800:return"Extra bold";case 900:return"Black";default:return""+e}},pZe=()=>{const e=ke.RECENT_FONTS;return Mt(e).filter(r=>r.psName!=="BlackHanSans-Regular")},fZe=e=>{const t=ke.RECENT_FONTS,o=Mt(t);if(o.length>0){if(o[0].fontName===e.fontName&&o[0].weight===e.weight)return;o.unshift(e);const r=o.filter((n,a,i)=>a===i.findIndex(s=>s.fontName===n.fontName&&s.weight===n.weight)).slice(0,go.RECENT_FONT_FAMILY_NUM);po(t,r)}else po(t,[e])},i0e=()=>{const e=ke.LAST_CAPTION_FONT;return Mt(e)},gZe=e=>{const t=ke.LAST_CAPTION_FONT,o=Mt(t);o!==void 0&&o.fontName===e.fontName&&o.weight===e.weight||po(t,e)},_Ze=()=>Mt(ke.BOOKMARK_FONTS),EZe=e=>{po(ke.BOOKMARK_FONTS,e)},_v=()=>$e().getInvalidFontInfos().map(t=>t.fontName).filter((t,o,r)=>r.indexOf(t)===o),Ev=e=>{const t=r0e(e);return $e().resetInvalidFontInfos(t),$e().hasInvalidFonts()},s0e=()=>{const e=ks();if(!e)return!1;const t=rt(e),o=n0e(t);return $e().resetInvalidFontInfos(o),$e().hasInvalidFonts()},mv=async e=>{if(e.length===0)return;kke();const t=Y(),o={bodyClassName:"invalid-font-modal",content:vSe(e),yesStr:A("popup.confirm")};return t.popup(o)},Rm=(e,t,o)=>o.find(n=>n.fontName===e&&n.weight===t),nW=(e,t)=>!e||!t?void 0:Rm(e,t,rW())??Rm(e,t,nI()),hv=(e,t)=>Rm(e,t,rW())===void 0&&Rm(e,t,nI())!==void 0,aW={None:"Pretendard-Vrew_700",en:"Pretendard-Vrew_700",ko:"Pretendard-Vrew_700",es:"Pretendard-Vrew_700",zh:"Noto Sans TC-Vrew_700",ja:"Noto Sans JP-Vrew_700"}
88,mZe=()=>[{name:"All",label:A("font.category_all")},{name:"Sans Serif",label:A("font.category_sans_serif")},{name:"Serif",label:A("font.category_serif")},{name:"HandWriting",label:A("font.category_handwriting")},{name:"Rounds",label:A("font.category_rounds")}],x0e=(e,t)=>{if(e<0)return!1;const o=t.at(-1);if(!o)return!1;const r=o.startPosition+o.words.length-1;return e<=r},hZe=(e,t)=>{const o=e.at(t.globalClipIndex);if(o===void 0)throw new Error("Global clip is undefined");if(o.words.length<=t.localIndex)throw new Error("Word index is out of bounds");return o.startPosition+t.localIndex},Q0=e=>e.type===Z.SPACER&&e.freeze===!0,Du=e=>e===Sy,IZe=(e,t,o,r)=>{const n=t?Q0(t):!1,a=n?t?.originalStartTime??0:(t?.originalStartTime??0)+(t?.originalDuration??0),i=A0e(t,o,r);return{id:ct(),text:"",timelineStart:pe(0),aligned:!1,type:Z.SPACER,duration:pe(e),originalDuration:pe(e),originalStartTime:a,truncatedWords:[],assetIds:i,playbackRate:Tv(t,o),freeze:!0}},c0e=(e,t,o)=>{const{existingAssetId:r,anchorAsset:n,mediaId:a,sourceIn:i}=o,{audio:s,...x}=n;let c,l,d;if(r!==void 0){const p=L.get(e,r);if(p?.role==="main"){const f=p.trackIds.map(O=>L.get(t,O)).filter(O=>O!==void 0),E=f.find(mn),T=f.find(U0);E&&pl(E.mediaId)&&(c=r,l=E.trackId,d=T?.trackId)}}c??=ho(),l??=Rt(),s&&(d??=Rt()),L.set(t,l,{...x,trackId:l,mediaId:a,sourceIn:i});const u=[l];return s&&d&&(L.set(t,d,{...s,trackId:d,mediaId:a,sourceIn:i}),u.push(d)),{assetId:c,assetEntry:{trackIds:u,role:"main",rangeType:tr.WORD}}},TZe=(e,t,o)=>vt({globalClips:e,assetEntries:t,trackEntries:o},n=>{let a,i=!1,s;for(const x of n.globalClips)for(const c of x.words){if(Q0(c)){c.originalStartTime=(a?.originalStartTime??0)+(a?.originalDuration??0);const l=WR(c,n.assetEntries);if(!i&&a&&(s=jL(a,n.assetEntries,n.trackEntries),i=!0),!s){c.assetIds=[...l];continue}const d=s.asset.mediaId,u=pe((s.asset.sourceIn??0)+(a?.duration??0)),p=jL(c,n.assetEntries,n.trackEntries),{assetId:f,assetEntry:E}=c0e(n.assetEntries,n.trackEntries,{existingAssetId:p?.assetId,anchorAsset:s.asset,mediaId:d,sourceIn:u});L.set(n.assetEntries,f,E),c.assetIds=[f,...l];continue}else if(c.type===Z.ENTER){c.originalStartTime=(a?.originalStartTime??0)+(a?.originalDuration??0);continue}a=c,s=void 0,i=!1}}),SZe=e=>Fn(e).alpha(1).isEqual(xd),OZe=e=>Fn(e).alpha(1).isEqual(u1),EO=e=>Fn(e).alpha()===0,iW=[["#38571A","dark_green"],["#6F760A","dark_lime"],["#785800","dark_yellow"],["#7B2900","dark_orange"],["#831100","dark_red"],["#551029","dark_pink"],["#450D59","dark_purple"],["#012F7B","dark_blue"],["#004D65","dark_teal"],["#76BB40","green"],["#D9EC37","lime"],["#FCC700","yellow"],["#FF6A00","orange"],["#FF4015","red"],["#B92D5D","pink"],["#982ABC","purple"],["#0061FD","blue"],["#00A1D8","teal"],["#B1DD8B","light_green"],["#EAF28F","light_lime"],["#FED977","light_yellow"],["#FEA57D","light_orange"],["#FF8C82","light_red"],["#EE719E","light_pink"],["#D357FE","light_purple"],["#74A7FF","light_blue"],["#52D6FC","light_teal"],["#DEEED4","pale_green"],["#F6FADB","pale_lime"],["#FEF1D5","pale_yellow"],["#FFE2D6","pale_orange"],["#FFDAD8","pale_red"],["#F9D3E0","pale_pink"],["#EFCAFE","pale_purple"],["#D2E2FE","pale_blue"],["#CBF0FF","pale_teal"]],HL=9,Am={withTransparent:[["#000000","black"],["#D6D6D6","light_gray"],[xd,"white"],[Ri,"transparent"]],plain:[["#000000","black"],["#5C5C5C","dark_gray"],["#D6D6D6","light_gray"],[xd,"white"]]},sW=[["#000000","black"],["#E6E6E6","light_gray"],["#75BC3F","green"],["#FCC800","yellow"],["#FF6A03","orange"],["#FF4017","red"],["#BA2C5D","pink"],["#982ABB","purple"],["#0062FE","blue"],["#008CB4","teal"],["#666666","gray"],[xd,"white"],["#CCE8B4","light_green"],["#FDE3A8","light_yellow"],["#FEC5AB","light_orange"],["#FFB5AE","light_red"],["#F4A4C0","light_pink"],["#E391FD","light_purple"],["#A8C6FF","light_blue"]],VR={withTransparent:[Ri,"transparent"],plain:["#93E3FC","light_teal"]},CZe=(e,t)=>{if(t==="large")return(e?Am.withTransparent:Am.plain).flatMap(([n],a)=>[...iW.slice(a*HL,(a+1)*HL).map(([i])=>i),n]);const o=e?VR.withTransparent:VR.plain;return[...sW,o].map(([r])=>r)},l0e=Object.fromEntries([...iW,...Am.withTransparent,...Am.plain,...sW,VR.plain].filter(([e])=>Fn(e).alpha()!==0).map(([e,t])=>[Fn(e).toHex().toLowerCase(),t])),RZe=e=>{const t=Fn(e);return t.alpha()===0?"transparent":l0e[t.toHex().toLowerCase()]},AZe=(e,t)=>{const o=Fn(e);switch(t){case"color-hex":return o.toHex();case"color-rgb":{const{r,g:n,b:a}=o.toRgb();return r+","+n+","+a}}},yZe=(e,t)=>{switch(t){case"color-hex":return e;case"color-rgb":return"rgb("+e+")"}},vZe=e=>Fn(e).isValid();class d0e{quill=null;getQuill=()=>{if(!this.quill){const t=document.createElement("div"),o=new t2(t);this.quill=o}return this.quill};trimEndNewLine=t=>t.replace(/\n$/,"");toText=t=>{const o=[];t.forEach(n=>{typeof n.insert=="string"&&o.push(n.insert)});const r=o.join("");return this.trimEndNewLine(r)};diff=(t,o)=>t.diff(o);fromText=(t,o)=>{const r=new Qt(t.length>0&&o?[{insert:t,attributes:o},{insert:`
89`}]:[{insert:t+`
90`}]);return this.refineDelta(r)};getAllAttributes=t=>t.ops.map(r=>r.attributes).filter(Se);getAttributeFromDiff=(t,o)=>{const r=this.toText(t),n=this.diff(this.fromText(r),this.fromText(o));return this.getAttribute(t,n.ops.at(0)?.retain??0)};getAttribute=(t,o)=>{const r=t;if(r.length()<o||o<0)return r.ops.at(-1)?.attributes;let n=0;for(const a of r.ops){const{insert:i}=a;if(typeof i=="string"){if(n+i.length>=o)return a.attributes;n+=i.length}}return r.ops.at(-1)?.attributes};applyAttribute=(t,o)=>{const r=t.ops.map(n=>n.insert!==void 0?{...n,attributes:o}:n);return new Qt(r)};applyChange=(t,o)=>t.compose(o);refineDelta=t=>{const o=this.getQuill();return o.setContents(t),o.getContents()};slice=(t,o)=>{const r=t.slice(0,o),n=t.slice(o),a=this.insertTailingNewLine(r),i=this.removeStartingSpace(n);return[a,i]};applyDefaultAttributes=(t,o)=>{const r=t.ops.map(n=>{if(n.insert===void 0)return n;if(n.attributes&&n.attributes["ruby-tag"]&&o.size){const a=parseInt(o.size),i=a/2;return{...n,attributes:{...o,...n.attributes,size:i.toString()}}}return{...n,attributes:{...o,...n.attributes}}});return new Qt(r)};updateStyle=(t,o)=>{const r=t.ops.map(n=>{if(n.insert===void 0)return n;if(n.attributes&&n.attributes["ruby-tag"]&&o.size){const a=parseInt(o.size),i=a/2;return{...n,attributes:{...n.attributes,...o,size:i.toString()}}}return{...n,attributes:{...n.attributes,...o}}});return new Qt(r)};isEmpty=t=>this.getQuillText(t)===`
91`;getQuillText=t=>{const o=this.getQuill();return o.setContents(t),o.getText()};concat=(t,o,r)=>{if(this.isEmpty(t))return o;let n=Math.max(this.getQuillText(t).length-1,0);const a=this.getQuill();a.setContents(t),r&&(a.insertText(n," "),n++),o.forEach(s=>{typeof s.insert=="string"&&(a.insertText(n,s.insert,s.attributes??{}),n+=s.insert.length)});const i=a.getContents();return this.removeTailingNewLine(i)};insertTailingNewLine=t=>{if(t.length()===0)return this.fromText("");const o=t.ops.slice(0,-1),r=t.ops.at(-1);return!r||r.insert===void 0?t:new Qt([...o,{...r,insert:r.insert+`
92`}])};removeTailingNewLine=t=>{if(t.length()===0)return this.fromText("");const o=t.ops.slice(0,-1),r=t.ops.at(-1);return!r||typeof r.insert!="string"?t:r.insert===`
93`?new Qt(o):new Qt([...o,{...r,insert:r.insert.slice(0,-1)}])};removeStartingSpace=t=>{if(t.length()===0)return this.fromText("");const[o,...r]=t.ops;return!o||typeof o.insert!="string"?t:new Qt([{...o,insert:o.insert.trimStart()},...r])}}let mO;const wt=()=>(!mO&&(mO=new d0e),mO),wZe=e=>{const t=e.map(a=>a.color).filter(Se),o=e.map(a=>a["background-on"]==="true"?a.background:void 0).filter(Se).filter(a=>!EO(a)),r=e.map(a=>a["outline-on"]==="true"?a["outline-color"]:void 0).filter(Se).filter(a=>!EO(a)),n=e.map(a=>a["shadow-on"]==="true"?a["shadow-color"]:void 0).filter(Se).filter(a=>!EO(a));return{appliedFontColors:t,appliedHighlightColors:o,appliedOutlineColors:r,appliedShadowColors:n}},xW=(e,t)=>
93{const o=[];return e.forEach(r=>{r.attributes?.[t]&&o.push(r.attributes[t])}),o},cW=(e,t)=>{const o=e.endsWith(`
94`)?e:e+`
95`;return new Qt().insert(o,t)},u0e=e=>e.filter(t=>typeof t.insert=="string").map(t=>t.insert).join(""),NZe=(e,t,o="left")=>{let r=0,n,a;return e.eachLine((i,s)=>{if(t>=r&&t<r+i.length()){n=s;const x=rn.clamp(t-r-(o==="left"?1:0),0,i.length()-1);return a=i.slice(x,x+1).ops[0]?.attributes,!1}return r+=i.length()+1,!0}),{...n,...a}},p0e=(e,t)=>e.length===0?e:e.map(o=>({...o,id:ct(),assetIds:o.assetIds.map(r=>{const n=L.get(t,r);if(n!==void 0)return n;const a=ho();return L.set(t,r,a),a}),truncatedWords:p0e(o.truncatedWords,t)})),PZe=(function*(){let e=Math.floor(new Date().getTime()/1e3);for(;;)yield e++})(),Iv=e=>e===0?Gx.SPACE:Gx.TEXT,bZe=()=>Gx.TEXT,f0e=e=>ue(e,2)>=1?em.TEXT_MAX_SEC:em.TEXT,g0e=e=>e===0?Gx.SPACE:ue(e,2)>=1?" "+em.TEXT_MAX_SEC+" ":" "+em.TEXT+" ",_0e=(e,t=!1)=>e<Gx.TYPE2_MAX_SEC&&!t?"":ue(e,e<Gx.FRACTION_SHOW_SEC?1:0)+A("silent_section.second_unit"),LZe=e=>{const t=document.getElementById(e.id.toString());return t?t.getBoundingClientRect().width:0},E0e=(e,t)=>(e&&t&&e.assetIds.filter(o=>t.assetIds.find(r=>r===o)))??[],ym=(e,t,o)=>({id:ct(),text:"",timelineStart:pe(0),duration:pe(e),aligned:!1,type:Z.SPACER,originalDuration:e,originalStartTime:0,truncatedWords:[],assetIds:[...E0e(t,o)],playbackRate:Tv(t,o)}),aI=(e,t)=>{const o=Math.floor(e),r=e%1,n=new Array(o).fill(ym(1,t)).map(i=>({...i,id:ct()})),a=r>0?[ym(r,t)]:[];return[...n,...a]},VE=e=>{const t=document.getElementById(e.id.toString());return t&&t.offsetParent?t.offsetTop+t.offsetParent.offsetTop:void 0},Dx=(e,t)=>{if(e.length>0){const o=e[e.length-1];if(t?.preserveEmptyWords||o.duration>0||o.text.length>0)return e.push({originalStartTime:o.originalStartTime+o.duration,id:ct(),timelineStart:Sd(o),duration:pe(0),text:"",playbackRate:Un,type:Z.ENTER,aligned:!1,originalDuration:0,truncatedWords:[],assetIds:[]}),!0;o.type!==Z.ENTER&&(e[e.length-1]={...o,type:Z.ENTER})}return!1},m0e=(e,t,o=!1)=>{for(let r=t-1;r>=0;r--){const n=sn(e,r);if(n.duration!==0||o&&n.type===Z.ENTER)return r}return t},lW=(e,t,o=!1)=>{const r=Upe(e);for(let n=t+1;n<r;n++){const a=sn(e,n);if(a.duration!==0||o&&a.type===Z.ENTER)return n}return t},h0e=(e,t,o=!1)=>{const r=Vpe(e);for(let n=t+1;n<r;n++){const a=d0(e,t);if(a.duration!==0||o&&a.type===Z.ENTER)return n}return t},I0e=(e,t,o)=>t[Ke.ORIGINAL].style?!1:ud(e,!0,!0,Ar(o))===wt().toText(t[Ke.ORIGINAL].text),MZe=(e,t,o,r)=>{const n=ss(e,o,r),a=ss(t,o,r);return n.visualMediaId?.at(0)===a.visualMediaId?.at(0)&&n.audioMediaId?.at(0)===a.audioMediaId?.at(0)?GCe(e.originalStartTime+e.originalDuration,t.originalStartTime):!1},T0e=e=>Math.round(e*10)/10<=Gx.DEFAULT_MINIMUM_SEC,DZe=e=>e===Z.NORMAL||e===Z.LAUGHTER||e===Z.CLAP||e===Z.FILLER||e===Z.AUDIO_EVENT,S0e=e=>{switch(e.type){case Z.CLAP:return A("transcript.word_clap");case Z.LAUGHTER:return A("transcript.word_laughter");case Z.FILLER:return A("transcript.word_filler");case Z.AUDIO_EVENT:return e.text}return e.text},kZe=e=>{const{text:t,type:o}=e,r=sr(e);switch(o){case Z.NORMAL:return t;case Z.LAUGHTER:case Z.CLAP:case Z.FILLER:case Z.AUDIO_EVENT:{const n=S0e(e),a=_0e(r);return"("+n+(a.length>0?" "+a:"")+")"}case Z.SILENT:case Z.ENTER:case Z.SOUND:case Z.SPACER:return" "}},yg=(e,t)=>{const o=e.map(a=>({...a,id:ct()})),r=Tw(),n={id:t??ct(),startPosition:0,words:o,assetIds:[],captionMode:ar.MANUAL,captions:r,dirty:{video:!1,caption:!1,blankDeleted:!1},translationModified:{source:!1,result:!1}};return Dx(n.words),n},FZe=e=>{const{text:t,type:o}=e,r=sr(e);switch(o){case Z.NORMAL:return t;case Z.ENTER:return"";case Z.SILENT:return"["+Iv(r)+"]";case Z.SOUND:return"[?]";case Z.LAUGHTER:return"["+A("transcript.word_laughter")+"]";case Z.CLAP:return"["+A("transcript.word_clap")+"]";case Z.FILLER:return"["+A("transcript.word_filler")+"]";case Z.AUDIO_EVENT:return"["+t+"]";case Z.SPACER:return""}},O0e=(e,t,o)=>{const r=o?" ":"",n=[e.text,t.text].filter(x=>x!=="").join(r),a=e.pronunciation,i=t.pronunciation,s=a===void 0&&i===void 0?void 0:[a||e.text,i||t.text].filter(x=>x!=="").join(r);return{text:n,pronunciation:s}},UZe=e=>{const{text:t,type:o}=e,r=sr(e);switch(o){case Z.NORMAL:return t;case Z.ENTER:return Gx.SPACE;case Z.SILENT:return""+Iv(r);case Z.SOUND:return""+g0e(r);case Z.LAUGHTER:return A("transcript.word_laughter");case Z.CLAP:return A("transcript.word_clap");case Z.FILLER:return A("transcript.word_filler");case Z.AUDIO_EVENT:return t;case Z.SPACER:return""}},VZe=e=>{const{text:t,type:o}=e,r=sr(e);switch(o){case Z.NORMAL:return t;case Z.ENTER:return"";case Z.SILENT:return"("+Iv(r)+")";case Z.SOUND:return"("+f0e(r)+")";case Z.LAUGHTER:return"("+A("transcript.word_laughter")+")";case Z.CLAP:return"("+A("transcript.word_clap")+")";case Z.FILLER:return"("+A("transcript.word_filler")+")";case Z.AUDIO_EVENT:return"("+t+")";case Z.SPACER:return r>=1?""+Gx.TEXT+r+A("silent_section.second_unit"):""}},ru={[Z.NORMAL]:"normal",[Z.SILENT]:"silent",[Z.ENTER]:"enter",[Z.SOUND]:"sound",[Z.LAUGHTER]:"laughter",[Z.CLAP]:"clap",[Z.FILLER]:"filler",[Z.SPACER]:"spacer",[Z.AUDIO_EVENT]:"audio_event"},GZe=e=>{const t=document.createElement("div");return e.forEach(o=>{const r=document.getElementById(o.id)?.cloneNode(!0);r&&(r.removeAttribute("id"),r.removeAttribute("data-word-id"),r.childNodes.forEac
95h(n=>{if(n.nodeType===Node.ELEMENT_NODE){const a=n;a.className.includes(Vx.DOUBLE_CLICK_DELETE_BUTTON)&&a.remove()}}),t.appendChild(r))}),t},C0e=e=>e.duration===0&&e.type!==Z.ENTER,WZe=e=>e.hardcutWordMeta?.webPlayDelta??0,iI=e=>e[e.length-2],HZe=(e,t)=>t===e.words.length-2,jZe=(e,t,o)=>{const r=lH(e,t),n=e!==null&&o===e.globalClipIndex;return r&&n},zZe=e=>{if(e!==null)return{background:"linear-gradient(to right, "+ee.purple[50]+" "+e+"%, transparent "+e+"%)"}},Tv=(e,t)=>e&&e.playbackRate!==Un?e.playbackRate:t&&t.playbackRate!==Un?t.playbackRate:Un,Rn=e=>e.duration/e.playbackRate,sI=e=>e.reduce((t,o)=>t+Rn(o),0),sr=e=>e.duration,fl=e=>pe(e.reduce((t,o)=>t+sr(o),0)),Sd=e=>pe(ue(e.timelineStart+Rn(e),2)),dW=(e,t,o,r)=>{const n=sr(t);if(e<=0||e>=n)return null;const a=zn({}),i=ii({}),s=[];for(const l of t.assetIds){const d=L.get(r,l);if(!d)continue;if(d.role!=="main"){s.push(l);continue}const u=d.trackIds.map(T=>L.get(o,T)).filter(Se),p=[];for(const T of u)if(Wa(T)||mn(T)){const O=pe(ue(T.sourceIn+e,2));L.set(a,T.trackId,{...T,sourceOut:O});const S={...T,trackId:Rt(),sourceIn:O};L.set(a,S.trackId,S),p.push(S.trackId)}else{const O={...T,trackId:Rt()};L.set(a,O.trackId,O),p.push(O.trackId)}const f={...d,trackIds:p},E=ho();L.set(i,E,f),s.push(E)}const x={...t,duration:pe(ue(e,2))},c={...t,id:ct(),timelineStart:pe(ue(t.timelineStart+e/t.playbackRate,2)),duration:pe(ue(n-e,2)),assetIds:s};return{splitWords:[x,c],newAssetEntries:i,newTrackEntries:a}},R0e=(e,t)=>e.assetIds.find(o=>L.get(t,o)?.role==="main"),uW=(e,t)=>e.assetIds.map(o=>L.get(t,o)).filter(o=>o?.role==="main"),qc=(e,t,o)=>uW(e,o).flatMap(r=>r.trackIds.map(n=>L.get(t,n)).filter(Se)),pW=(e,t,o)=>qc(e,t,o).filter(xr),GR=(e,t,o)=>qc(e,t,o).find(xr),Sv=(e,t,o)=>qc(e,t,o).find(mn),oi=(e,t,o)=>qc(e,t,o).find(Wa),jL=(e,t,o)=>{if(!e)return;const r=R0e(e,t);if(!r)return;const n=L.get(t,r);if(!n||n.role!=="main")return;const a=n.trackIds.map(c=>L.get(o,c)).filter(c=>c!==void 0),i=a.find(c=>mn(c));if(!i||!pl(i.mediaId))return;const s=a.find(c=>U0(c)),x={...i,...s?{audio:s}:{}};return{assetId:r,asset:x}},WR=(e,t)=>{const o=[];for(const r of e.assetIds){const n=L.get(t,r);n&&n.role==="sub"&&o.push(r)}return o},YZe=(e,t,o)=>{const r=[],n=[];for(const a of e.assetIds){const i=L.get(o,a);if(!i||i.role!=="sub")continue;const s=i.trackIds.map(c=>L.get(t,c)).filter(Se);s.length>0&&s.every(c=>Wa(c)&&Id(c))?r.push(a):n.push(a)}return{soundEffectAssetIds:r,otherSubAssetIds:n}},A0e=(e,t,o)=>!e||!t?[]:WR(e,o).filter(r=>WR(t,o).includes(r)),zL=(e,t)=>{const o=uW(e,t).flatMap(r=>r.trackIds);return[...new Set(o)]},gl=(e,t,o)=>{const r=[],n=[];
95return qc(e,t,o).forEach(i=>{xr(i)?r.push(i.mediaId):n.push(i.mediaId)}),{visualMediaIds:r,audioMediaIds:n}},ss=(e,t,o)=>{const{visualMediaIds:r,audioMediaIds:n}=gl(e,t,o);return{visualMediaId:r.at(0),audioMediaId:n.at(0)}},BZe=(e,t,o)=>{if(!e||e.type!==Z.ENTER)return{word:e,isEnterFallback:!1};if(o!==null&&o>0){const r=d0(t,o-1);return Q0(r)?{word:r,isEnterFallback:!1}:{word:r,isEnterFallback:!0}}return{word:void 0,isEnterFallback:!1}},p2=e=>e.etc,KZe=e=>p2(e).pendingScrollState,y0e=e=>p2(e).activeProgresses,XZe=e=>p2(e).assetDraggingRange,v0e=e=>p2(e).isCaptionSelected,JZe=e=>p2(e).isReadyToOpenProject,w0e=e=>p2(e).lastUsedBlankOption,qZe=[],Te=KU({memoize:xR,memoizeOptions:{maxSize:1},argsMemoize:xR,argsMemoizeOptions:{maxSize:1}}),fW=e=>rt(e).overdubStates,vg=e=>rt(e).overdubInfosMap,QZe=Te(fW,e=>{const t=new Set;for(const o of Object.values(e))o.groupWordIds.forEach(r=>{t.add(r)});return t}),Ov=e=>e.edit,N0e={type:"none"},gW=In({name:"dragState",initialState:N0e,reducers:{setDragState:(e,t)=>t.payload}}),ZZe=gW.reducer,{setDragState:$Ze}=gW.actions,_W=e=>Ov(e).dragState,Cv=e=>_W(e).type,P0e=e=>Cv(e)!=="none",e$e=e=>Cv(e)==="element",t$e=e=>Cv(e)==="insert",b0e=e=>{const t=_W(e);return t.type==="clip"?t:null},o$e=e=>b0e(e)?.clipDropTarget??null,L0e=null,EW=In({name:"selectingClipRange",initialState:L0e,reducers:{setSelectingClipRange:(e,t)=>
95t.payload}}),r$e=EW.reducer,{setSelectingClipRange:n$e}=EW.actions,M0e=e=>Ov(e).selectingClipRange,ja=e=>e.ui,D0e={activeOverlay:{[bu.GRID]:!1,[bu.SHORTS_GUIDE]:!1}},mW=In({name:"previewGuides",initialState:D0e,reducers:{togglePreviewGuide:(e,t)=>{e.activeOverlay[t.payload]=!e.activeOverlay[t.payload]}}}),a$e=mW.reducer,{togglePreviewGuide:i$e}=mW.actions,k0e=e=>ja(e).previewGuides.activeOverlay;var F0e=(e=>(e[e.READY=0]="READY",e[e.SUCCESS=1]="SUCCESS",e[e.FAILED=2]="FAILED",e))(F0e||{}),U0e=(e=>(e[e.READY=0]="READY",e[e.WAIT=1]="WAIT",e))(U0e||{}),bo=(e=>(e.HOME="home",e.FILE="file",e.EDIT="edit",e.CAPTION="caption",e.FORMAT="format",e.SETTING="setting",e.HELP="help",e.INSERT="insert",e.EFFECT="effect",e.MYVREW="myvrew",e.RIGHT_TAB="right-tab",e.TEMPLATE="template",e.AI_VOICE="ai_voice",e))(bo||{}),nt=(e=>(e.ALL_CLIPS="ALL_CLIPS",e.SCENE_CLIPS="SCENE_CLIPS",e.SELECTED_CLIPS="SELECTED_CLIPS",e.CURRENT_CLIP="CURRENT_CLIP",e.CURRENT_WORD="CURRENT_WORD",e.SELECTED_WORDS="SELECTED_WORDS",e.FOLLOW_SELECTED_ELEMENT="FOLLOW_SELECTED_ELEMENT",e))(nt||{}),V0e=(e=>(e.ALL_SCENES="ALL_SCENES",e.CURRENT_SCENE="CURRENT_SCENE",e))(V0e||{}),Io=(e=>(e[e.DURATION=0]="DURATION",e[e.R_FRAME_RATE=1]="R_FRAME_RATE",e[e.TIMECODE_ALLTRACK=2]="TIMECODE_ALLTRACK",e[e.TIMECODE_VIDEOTRACK=3]="TIMECODE_VIDEOTRACK",e[e.BITRATE=4]="BITRATE",e[e.SAMPLED_PACKETS_INFO=5]="SAMPLED_PACKETS_INFO",e[e.CODEC_STRINGS=6]="CODEC_STRINGS",e[e.SAMPLE_RATE=7]="SAMPLE_RATE",e[e.AUDIO_STREAM=8]="AUDIO_STREAM",e[e.NUM_FRAMES=9]="NUM_FRAMES",e[e.COLOR_SPACE=10]="COLOR_SPACE",e[e.AUDIO_CODEC=11]="AUDIO_CODEC",e[e.AUDIO_CHANNEL_COUNT=12]="AUDIO_CHANNEL_COUNT",e))(Io||{}),G0e=(e=>(e.SELECTED="selected",e.CLIP="clip",e.WORD="word",e.PREVIEW="preview",e.SCENE="scene",e.TOOLBAR="toolbar",e.PANEL="panel",e.NEW_PROJECT_SCENE="new_project_scene",e.USER_ASSET_PANEL="user_asset_panel",e))(G0e||{}),W0e=(e=>(e.CLIP="clip",e.WORD="word",e))(W0e||{}),H0e=(e=>(e.PRESET="preset",e.RECENT="recent",e.CUSTOM="custom",e.EYE_DROPPER="eyeDropper",e))(H0e||{}),j0e=(e=>(e[e.PC=0]="PC",e[e.PHONE_QR=1]="PHONE_QR",e))(j0e||{});const z0e=e=>e.errorInfo!==void 0&&e.status!=="processing",Y0e=(e,t=!0)=>{const o=Object.values(e.deltas).map(r=>r.ops.map(n=>n.insert??"").join("")).join(`
96`);return t?o.trim():o},B0e=e=>{let t=0;for(const o of Object.keys(e)){const r=e[o];for(const n of r.ops)typeof n.insert!="string"||n.attributes===void 0||n.attributes.size===void 0||(t=Math.max(t,parseInt(n.attributes.size)))}return t||tR},K0e=e=>{for(const t of Object.keys(e)){const o=e[t];for(const r of o.ops)if(!(typeof r.insert!="string"||r.attributes===void 0)&&r.attributes.ruby)return!0}return!1},hW=e=>{const t=B0e(e),o=t/EU*1.2;return K0e(e)?o*1.5:o},s$e=e=>{const t=e.customAttributes.map(r=>[r.attributeName,r.value]),o=hW(e.deltas);return t.push(["--textbox-lineheight",o+"px"]),Object.fromEntries(t)},X0e="VREW_TEXTBOX_EXPORT_VIDEO_WRAPPER",J0e=e=>`
97<style>
98#`+e+` {
99  <% attrs.forEach((attr) => { %><%- attr.attributeName %>: <%- attr.value %>;<% }) %>
100}
101</style>
102`,IW=(e,t,o)=>{const r=hW(o),n={attributeName:"--textbox-lineheight",type:"textbox-lineheight",value:r+"px"};return XU(J0e(e))({attrs:[...t,n]})},q0e=(e,t)=>`
103<style>
104#`+e+` * {
105  animation-play-state: paused !important;
106  animation-delay: -`+t+`s !important;
107}
108</style>
109`,Q0e=e=>{const t=e.flatMap(r=>Object.values(r.deltas).flatMap(n=>n.ops.flatMap(a=>a.attributes?.font)).filter(Fte));return[...new Set(t)].flatMap(r=>nI().filter(n=>{const{fontName:a}=zc(r);return n.fontName.toUpperCase()===a.toUpperCase()})).map(r=>r.path?{fontName:r.fontName,path:r.path,weight:r.weight}:void 0).filter(Se)},TW=e=>"<style> #"+e+" { font-size: "+JX+"px; } #"+e+" * { font-kerning: normal }</style>",Z0e=["bold","italic","font","size","color","background","outline-color","shadow-color"],Dc=()=>Z0e,$0e=`
110<style>
111.`+Ao+` {
112  text-align: var(--textbox-align);
113  line-height: 1.4;
114  font-size: 25px;
115  color: white;
116  font-family: initial;
117  font-weight: initial;
118
119  display: flex;
120  align-items: center;
121  justify-content: var(--textbox-align);
122  width: 100%;
123  overflow: visible;
124}
125.`+Ao+` .textarea {
126  white-space: pre-wrap;
127  word-wrap: break-word;
128
129  background-color: var(--textbox-color);
130  width: fit-content;
131  padding: 3px 0px 1px 0px;
132}
133.`+Ao+` .textarea p {
134  margin-block-start: 0px;
135  margin-block-end: 0px;
136  padding: 0px 5px;
137  line-height: var(--textbox-lineheight);
138}
139.`+Ao+` .textarea p span { 
140  vertical-align: bottom;
141}
142.`+Ao+` .textarea .ql-blank p {
143  padding: 0px;
144}
145.`+Ao+` .textarea .ql-blank p > span {
146  background-color: transparent !important;
147}
148</style>
149<div class="`+Ao+`">
150  <div class="textarea" id="textarea"></div>
151</div>`,Qc=()=>$0e,SW=()=>[{attributeName:"--textbox-color",type:"color-hex",value:Ri},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],YL=e=>{const t={size:"200",color:"#ffffff",font:aW[e]};return{mediaId:Ao,html:Qc(),deltas:{textarea:new Qt().insert(""+A("asset.textbox_placeholder"),t)},enabledInlineTypes:Dc(),customAttributes:SW(),webAssetDefaultAttributes:t,tags:[]}},exe=(e,t)=>{const o={size:"150",color:xd,font:aW[t]};return{mediaId:Ao,html:Qc(),deltas:{textarea:new Qt().insert(e,o).insert(`
152`)},enabledInlineTypes:Dc(),customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],webAssetDefaultAttributes:o,tags:[]}},txe={LONG:"asset.textbox_placeholder_long",MID:"asset.textbox_placeholder",SHORT:"asset.textbox_placeholder_short",NAME:"asset.textbox_placeholder_name",TITLE:"asset.textbox_placeholder_title",NUM_ZERO:"asset.textbox_placeholder_num_zero",NUM_TEN:"asset.textbox_placeholder_num_ten"},oxe=(e,t)=>{const o=Object.entries(e).map(r=>{const[n,a]=r;if(!Wn(a))return r;if(a.mediaId===Ao){const x=a.customAttributes.some(d=>d.attributeName==="--textbox-color")===!1,c=x?SW():a.customAttributes,l={...a,customAttributes:c};return[n,l]}const i=t.find(x=>x.mediaId===a.mediaId);if(i===void 0)return r;const s={...a,enabledInlineTypes:oI.filter(x=>i.enabledInlineTypes.indexOf(x)>-1),loop:i.loop??!1,durationSeconds:i.durationSeconds??0};return[n,s]});return Object.fromEntries(o)},x$e=(e,t)=>
152{const o=Ve().getObject(e);return Array.isArray(o)?o.slice(0,go.TEXTBOX_RECENT_COLOR_NUM):[t]},c$e=(e,t)=>{const o=Ve().getObject(e),r=Array.isArray(o)?o:[],n=[t,...r.filter(a=>!Fn(a).isEqual(t))].slice(0,go.TEXTBOX_RECENT_COLOR_NUM);return Ve().set(e,n),n},Rv=(e,t,o)=>{const r=rxe(e,t,o);return t*r/_U},rxe=(e,t,o)=>{const r=e/t;return Math.min(1,r/o)},nxe=(e,t)=>{const o=Fe(),r=t[e.defaultFont][o],n={...e.defaultStyles,font:r},a=XU(e.html)({webAssetId:e.webAssetId});return{mediaId:e.webAssetId,customAttributes:e.customAttributes,html:a,enabledInlineTypes:oI.filter(s=>e.enabledInlineTypes.indexOf(s)>-1),webAssetDefaultAttributes:n,deltas:Object.fromEntries(Object.entries(e.placeholders).map(([s,x])=>[s,new Qt().insert(A(txe[x]),n).insert(`
153`)])),loop:e.loop,durationSeconds:e.durationSeconds,tags:e.tags}},l$e=()=>Ve().getNumber(Ie.LAST_TEXTBOX_VERSION,0),Fl=e=>e.durationSeconds===0,d$e=e=>Wn(e)&&e.mediaId===Ao,axe=(e,t,o,r)=>{const n="translate("+e+"px, "+t+"px)",a="translate(-50%, -50%) scale("+o+") translate(50%, 50%)",i="rotate("+r+"deg)";return n+" "+a+" "+i},rt=e=>e.snapshots.present.transcript,He=e=>rt(e).globalClips,za=e=>e.globalClips,ixe=e=>rt(e).sceneNames,mo=Te(He,ixe,(e,t)=>qK(ci(e),t)),u$e=Te(mo,e=>e.map(t=>t.id)),xI=Te(e=>e,e=>{const{globalClips:t,sceneNames:o}=e,r=ci(t);return qK(r,o)}),p$e=Te(rt,e=>{const{globalClips:t}=e;return aT(t).length>1}),f$e=e=>mo(e).length,lt=e=>rt(e).trackEntries,ht=e=>rt(e).assetEntries,f2=Te(lt,ht,(e,t)=>G4(e,t)),Av=e=>f2(e).audioTransformsMap,g$e=jn(lt,(e,t)=>t,(e,t)=>Wg(t,e))((e,t)=>t),cI=e=>f2(e).assetInfos,wg=e=>f2(e).watermark,jo=e=>rt(e).globalCursor,Ng=e=>e.globalCursor,_$e=e=>jo(e).lastMoveMethod,sxe=e=>Ng(e).globalPosition,xxe=e=>{const t=jo(e);return t.cursorMode===we.INSERT_CURSOR&&t.globalClipRange===null&&t.globalWordRange===null},_l=e=>{const t=xI(e),{globalCursor:o}=e;return bce(o,t,e.globalClips)},Tn=e=>_l(rt(e)),Pg=e=>jo(e).globalPosition,E$e=(e,t)=>Pg(e)===t,lI=e=>Tn(e).position,OW=Te(He,jo,(e,t)=>t.globalPosition===null?(h("selector.ts").error("Invalid position during globalClipIndexSelector."),-1):Er(e,t.globalPosition,!0)),m$e=Te(za,Ng,(e,t)=>t.globalPosition===null?(h("selector.ts").error("Invalid position during globalClipIndexSelector."),-1):Er(e,t.globalPosition,!0)),h$e=(e,t)=>
153OW(e)===t,Zx=e=>jo(e).cursorMode,cxe=e=>jo(e).editCaption,CW=e=>jo(e).correctingInfo,ds=e=>jo(e).globalWordRange,I$e=e=>jo(e).isDraggingWord===!0,T$e=e=>jo(e).webModelTextSelection,lxe=[],_0=e=>{const t=jo(e);return t.selectedElements.length>0?t.selectedElements:lxe},S$e=Te(_0,e=>e.map(t=>t.id)),dxe=[],O$e=Te(_0,lt,ht,(e,t,o)=>e.length===0?dxe:e.map(r=>{const{type:n,id:a}=r,i=L.get(o,a);if(!i)return;const s=i.trackIds.map(x=>L.get(t,x)).filter(Se);if(n===ra.ASSET){const x=s.find(l=>xr(l)&&!Rr(l));if(!x)return;const c=s.find(U0);return{elementId:a,element:c?{...x,audio:c}:x,rangeType:i.rangeType}}else if(n===ra.AUDIO){const x=s.find(cd);return x?{elementId:a,element:x,rangeType:G1(x.type)?tr.WORD:tr.CLIP}:void 0}}).filter(Se)),C$e=e=>jo(e).selectedFromAssetList,R$e=e=>jo(e).selectedWatermarkId,xa=Te(He,Pg,(e,t)=>y_(e,t)),A$e=Te(He,xa,(e,t)=>t,(e,t,o)=>x0e(o,e)?y_(e,o)===t:!1),$x=e=>mo(e)[xa(e)],yv=e=>Tn(e).globalClipRange,RW=e=>_l(e).globalClipRange,uxe=e=>_l(e).globalWordRange,AW=Te(mo,ds,(e,t)=>AI(t,e)),pxe=Te(xI,uxe,(e,t)=>AI(t,e)),g2=e=>{const t=new Set,o=[];let r=e;for(;r;)o.push(r),r=r.next??null;for(let n=o.length-1;n>=0;n--){const{from:a,to:i,inverted:s}=o[n],x=Math.min(a,i),c=Math.max(a,i);for(let l=x;l<c;l++)s?t.delete(l):t.add(l)}return t},yW=jn(e=>e,e=>g2(e))({keySelector:e=>e,cacheObject:new w9({cacheSize:3})}),Nn=Te(yv,e=>yW(e)),vv=Te(RW,e=>yW(e)),Od=Te(Nn,e=>Array.from(e)),wv=Te(za,sxe,(e,t)=>y_(e,t)),fxe=e=>$x(e).id,Do=e=>$x(e).clips,gxe=e=>Nn(e).size>1,_xe=Te(za,wv,vv,(e,t,o)=>{const r=new Set;return o.forEach(n=>{const a=SH(n,e,t);a!==void 0&&r.add(a)}),r}),Z0=e=>_xe(rt(e)),bg=Te(He,Nn,(e,t)=>{const o=ci(e),r=o.map(n=>n.id);return e.map((n,a)=>
153{if(!t.has(a))return;const i=QK(r,n.sceneId),s=o[i];if(!s){const c="Invalid sceneId: "+n.sceneId+", globalSceneIds: "+JSON.stringify(r);if(h("selector.ts").error(c),wi())throw new C(_.C_LOGIC_ERROR,void 0,c);return}const x=s.clips[a-s.globalClipRange.from];if(!x){const c="Invalid sceneId: "+n.sceneId+", globalSceneIds: "+JSON.stringify(r);if(h("selector.ts").error(c),wi())throw new C(_.C_LOGIC_ERROR,void 0,c);return}return x}).filter(Se)}),_2=Te(He,Nn,(e,t)=>e.filter((o,r)=>t.has(r))),dI=e=>vW(e).clips,vW=Te(xI,wv,(e,t)=>e[t]),wW=Te(jo,({cursorMode:e,globalWordRange:t})=>(e===we.INSERT_CURSOR||e===we.DISABLED)&&t!==null&&t.from!==t.to),Exe=Te(Ng,({cursorMode:e,globalWordRange:t})=>e===we.INSERT_CURSOR&&t!==null&&t.from!==t.to),y$e=e=>bg(e).length>0,v$e=Te(He,(e,t)=>t,(e,t)=>aT(e).findIndex(n=>n===t)),w$e=Te(RW,e=>{if(!e)return null;const{from:t,to:o}=e;return t===o?null:{start:t<o?t:o,end:(t<o?o:t)-1}}),BL=Te(Nn,e=>{const t=[...e].sort((r,n)=>r-n);return t.length===0?null:t.every((r,n)=>n===t.length-1||r+1===t[n+1])?{start:t[0],end:t[t.length-1]}:null}),NW=Te(Nn,e=>{const t=J1([...e]);return t.length===0?null:X1(t)?{start:t[0],end:t[t.length-1]}:null}),mxe=Te(vv,e=>{const t=J1([...e]);return t.length===0?null:X1(t)?{start:t[0],end:t[t.length-1]}:null}),$0=Te(wW,ds,He,(e,t,o)=>{if(!e)return[];if(!t)return[];const r=o[t.globalClipIndex],n=r.startPosition+t.from,a=r.startPosition+t.to,i=Math.min(n,a),s=Math.max(n,a);return x0(i,s)}),Nv=Te(Exe,pxe,dI,(e,t,o)=>{if(!e)return[];if(!t)return[];const r=o[t.clipIndex],n=r.startPosition+t.from,a=r.startPosition+t.to,i=Math.min(n,a),s=Math.max(n,a);return x0(i,s)}),N$e=Te(He,$0,(e,t)=>t.length!==1?null:d0(e,t[0])),P$e=Te(He,ds,(e,t)=>{if(t===null)return null;const o=e.at(t.globalClipIndex);if(o===void 0)return null;const r=t.from,n=t.to,a=Math.min(r,n),i=Math.max(r,n);return o.words.slice(a,i)}),PW=Te(Zx,cxe,(e,t)=>e===we.CAPTION&&t!==null),E2=Te(Do,Tn,(e,t)=>t.position===null?(h("selector.ts").error("Invalid position during clipIndexSelector."),-1):Co(e,t.position,!0)),ec=Te(He,jo,(e,t)=>t.globalPosition===null?(h("selector.ts").error("Invalid position during globalClipIndexSelector."),-1):Er(e,t.globalPosition,!0)),uI=Te(He,ec,(e,t)=>e[t]),b$e=Te(za,Ng,(e,t)=>t.globalPosition===null?(h("selector.ts").error("Invalid position during globalClipIndexSelectorFromTranscript."),-1):Er(e,t.globalPosition,!0)),bW=Te(dI,_l,(e,t)=>t.position===null?(h("selector.ts").error("Invalid position during clipIndexSelectorFromTranscript."),-1):Co(e,t.position,!0)),pI=Te(dI,bW,(e,t)=>e[t]),Lg=Te(Do,E2,(e,t)=>e[t]?e[t]:void 0),tc=e=>rt(e).projectAudioLanguage,Pv=e=>rt(e).audioLanguagesMap,Fi=e=>rt(e).ttsClipInfosMap,hxe=e=>rt(e).denoiseMap,Mg=e=>rt(e).showOriginal,Dg=e=>e.original,Ixe=e=>e.originalBackup,fI=e=>e.videoplay,Txe=e=>fI(e).sessionStateVersion,Sxe=()=>ld(),bv=Te(Txe,Sxe,(e,t)=>t?.sessionState.snapshot??null),kg=Te(bv,e=>{const t=e?.playCursor;return t==null?null:{sceneIndex:t.sceneIndex,position:t.sceneLocalPosition}}),L$e=e=>fI(e).mediaIds,Oxe=Te(kg,mo,(e,t)=>{if(!e)return null;const{sceneIndex:o,position:r}=e;return ku(r,o,t)}),M$e=Te(Oxe,(e,t)=>t,(e,t)=>e===t),D$e=e=>bv(e)?.active??!1,k$e=e=>k0e(e),m2=e=>e.trackEntries,h2=e=>e.assetEntries,gI=Te(m2,h2,(e,t)=>G4(e,t)),Cxe=Te(gI,({audioTransformsMap:e})=>e),_I=Te(gI,({assetInfos:e})=>e),Rxe=Te(gI,({watermark:e})=>e),LW=Te(za,m2,h2,(e,t,o)=>s5(e,t,o)),I2=e=>rt(e).videoRatio,MW=e=>Axe(e).playingRangeInfo,Axe=Te(bv,e=>{const t=e?.playingContext??null,o=t?.playingRangeInfo??null;return{active:t!==null,sessionType:o?"selection":"all",playMethod:t?.playMethod??null,playStartClipIndex:t?.playStartClipIndex??null,lastPlayType:t?.lastPlayType??null,playingRangeInfo:o}}),F$e=Te(MW,(e,t)=>t,(e,t)=>e?e.visualStartWordId===t:!1),U$e=Te(MW,(e,t)=>t,(e,t)=>e?e.visualEndWordId===t:!1),T2=e=>rt(e).translateInfo,oc=e=>T2(e)!==null,V$e=jn(ec,oc,(e,t)=>t,(e,t,o)=>o,(e,t,o,r)=>t&&e===o&&r===Ke.ORIGINAL)((e,t,o)=>t+"-"+o),G$e=e=>T2(e)?.target??null,Lv=Te(He,e=>TH(e)),W$e=e=>fI(e).mediaChangeCounter,xn=e=>rt(e).captionDisplayMode,Mv=e=>{const t=xn(e);return t[Ke.ORIGINAL]||t[Ke.TRANSLATE]},yxe=e=>e.snapshots.present.action.lastUndoableActionType,vxe=Te(wW,ds,He,(e,t,o)=>{if(!e||!t)return null;const r=o[t.globalClipIndex],n=t.from,a=t.to,i=Math.min(n,a),s=Math.max(n,a),x=r.words[i].timelineStart,c=sI(r.words.slice(i,s));return{start:x,duration:c}}),H$e=Te(vxe,He,Nn,M0e,(e,t,o,r)=>{if(e)return[e];const n=new Set([...o,...r!==null?bG(r):[]]),a=[...n].sort().map(i=>t[i]).filter(Se);return Wpe(a)}),EI=e=>rt(e).ttsStates,zs=e=>EI(e).clip,mI=(e,t)=>L.get(zs(e),t),j$e=jn(lt,ht,Fi,(e,t)=>t.words,(e,t,o,r)=>Pw(r,e,t,o))((e,t)=>ai(t)),wxe=jn(lt,ht,Fi,(e,t)=>t,(e,t,o,r)=>jg(r,e,t,o))((e,t)=>ai(t));jn(lt,ht,(e,t)=>t,(e,t,o)=>oi(o,e,t))((e,t)=>t.id);const Nxe=jn(lt,ht,(e,t)=>t,(e,t,o)=>{for(const r of o.words){const n=oi(r,e,t);if(n)return n}})((e,t)=>ai(t)),Pxe=jn(lt,ht,(e,t)=>t,(e,t,o)=>{const r=iT(o,e,t);return r.length>0?r:void 0})((e,t)=>ai(t)),z$e=jn(mo,Tn,xa,Z0,(e,t)=>t,(e,t,o,r,n)=>{const{selectedElements:a}=t,i=RI(a);switch(n){case nt.ALL_CLIPS:return e.reduce((s,x)=>s+x.clips.length,0);case nt.CURRENT_CLIP:return 1;case nt.SCENE_CLIPS:return e[o].clips.length;case nt.SELECTED_CLIPS:return r.size;
153case nt.FOLLOW_SELECTED_ELEMENT:return i?e[o].clips.filter(s=>s.assetIds.includes(i)).length:0;case nt.CURRENT_WORD:case nt.SELECTED_WORDS:return 1;default:return 0}})((e,t)=>t),Dv=Te(mo,e=>e.reduce((o,r)=>o+r.clips.length,0)),Y$e=e=>Te(He,Nn,(t,o)=>{const r=[];return t.forEach((n,a)=>{e==="ALL"?n.markerId!==void 0&&r.push({...n,clipIndex:a,isSelected:o.has(a)}):n.markerId===e&&r.push({...n,clipIndex:a,isSelected:o.has(a)})}),r}),B$e=e=>Te(rt,t=>t.markerNames[e]),K$e=Te(Fi,lt,ht,(e,t)=>t,(e,t,o,r)=>{const n=jg(r,t,o,e);return n?Kx(n,e)??null:null}),Fg=e=>rt(e).soundEffectTimelineRanges,E0=e=>rt(e).assetTimelineRanges,DW=Te(rt,e=>LW(e)),X$e=Te(Do,Av,(e,t)=>{const o=e.flatMap(r=>r.assetIds.map(n=>L.get(t,n)?.track)).filter(r=>r!==void 0&&eo(r.mediaId)?.sourceOrigin===tt.USER&&r.type===ze.BGM).map(r=>r.mediaId);return[...new Set(o)]}),J$e=Te(Do,Av,(e,t)=>{const o=e.flatMap(r=>r.words.flatMap(n=>n.assetIds.map(a=>L.get(t,a)?.track))).filter(r=>r!==void 0&&eo(r.mediaId)?.sourceOrigin===tt.USER&&r.type===ze.SoundEffect).map(r=>r.mediaId);return[...new Set(o)]}),q$e=e=>e.snapshots.past,Q$e=e=>e.snapshots.future,bxe=Te(ht,lt,(e,t)=>{const o=new Set;return Object.entries(e).forEach(([r,n])=>{if(n.role!=="sub")return;n.trackIds.some(i=>{const s=L.get(t,i);return s!==void 0&&xr(s)})&&o.add(Je(r))}),o}),qp=Object.freeze([]),Lxe=jn(He,E0,bxe,ht,(e,t)=>t,(e,t,o,r,n)=>{const a=L.get(r,n);if(!a)return qp;const i=L.get(t,n);if(!i)return qp;const s=a.rangeType===tr.CLIP?e.slice(i.globalClipRange.from,i.globalClipRange.to):[e[i.globalClipRange.from]].filter(Se);if(s.length===0)return qp;const x=[],c=new Set;return s.forEach(l=>{l.assetIds.forEach(d=>{o.has(d)&&!c.has(d)&&(c.add(d),x.push(d))}),l.words.forEach(d=>{d.assetIds.forEach(u=>{o.has(u)&&!c.has(u)&&(c.add(u),x.push(u))})})}),x})((e,t)=>t),Mxe=(e,t)=>t?Lxe(e,t)??qp:qp,Dxe=e=>rt(e).backgroundMap,kv=e=>EI(e).effect,Fv=Te(kv,(e,t)=>t,(e,t)=>L.get(e,t)??null),kxe=Te(kv,e=>Object.values(e).filter(rT).find(t=>t.variant===Ge.EFFECT)),Z$e=Te(kv,e=>Object.values(e).length>0),Uv=Te(Tn,Do,rt,Z0,(e,t,o,r)=>{const{position:n,cursorMode:a,selectedElements:i,webModelTextSelection:s,editCaption:x}=e,{selectedAssetIds:c}=rc(i),{captionDisplayMode:l}=o,d=_I(o);if(t.length===0)return{target:Xa.ALL};const u=Co(t,n),p=t[u];if(r.size===1)return{target:Xa.CAPTION};if(r.size>1)return{target:Xa.MULTIPLE_CAPTIONS};if(a===we.ELEMENT&&c.length===1){c.length>1&&h("selector.ts").warn("Multiple assets are selected");const T=L.get(d,c[0]);if(T&&Wn(T.track))return{target:T.track.mediaId===Ao?Xa.TEXTBOX:Xa.DESIGN_TEXTBOX,asset:T.track,assetId:c[0]}}if(s?.captionIndex!==void 0)return{target:Xa.CAPTION};const f=x?.captionIndex,E=OH(p,l,f);return a===we.CAPTION&&f!==void 0&&p.captions.at(f)?.style!==void 0?{target:Xa.CAPTION}:E?{target:Xa.CAPTION}:{target:Xa.ALL}}),$$e=Te(rt,Do,E2,(e,t,o)=>{const{globalCaptionStyle:r}=e,n=t.at(o);if(!n||n.captionMode!==ar.MANUAL)return r;const a=n.captions.at(0);return a?m2e(a,r):r}),eet=Te(jo,rt,Nn,(e,t,o)=>{const{cursorMode:r,selectedElements:n,webModelTextSelection:a,editCaption:i,globalPosition:s}=e,{selectedAssetIds:x}=rc(n),{globalCaptionStyle:c,captionDisplayMode:l}=t,d=_I(t),u=za(t);if(u.length===0)return Dc();const p=s===null?0:Er(u,s);if(r===we.ELEMENT&&x.length===1){x.length>1&&h("selector.ts").warn("Multiple assets are selected");const T=L.get(d,x[0]);if(T&&Wn(T.track))return T.track.enabledInlineTypes}const f=w2(u,p,o,l,a,i);if(f){const{targetGlobalClipIndices:T,captionIndex:O}=f;if(O===void 0){const N=T.flatMap(k=>{const F=u[k];return F===void 0?(h("selector.ts").error("invalid clipIndex "+k+", clips len: "+u.length+" is undefined, "+JSON.stringify(Array.from(o))+", "+JSON.stringify(l)+", "+JSON.stringify(a)+", "+JSON.stringify(i)),[]):F.captions.map(B=>B.style?.mediaId)}).filter(Se);if(new Set(N).size>1)return Coe}const S=T[0],R=O??Ke.ORIGINAL,{style:y}=u.at(S)?.captions.at(R)??{style:void 0},v=y??c.captionStyleSetting,{mediaId:w}=v;return $e().getWebTextboxInlineTypes(w)??Dc()}const{mediaId:E}=c.captionStyleSetting;return $e().getWebTextboxInlineTypes(E)??Dc()}),tet=Te(jo,rt,Nn,(e,t,o)=>{const{cursorMode:r,selectedElements:n,webModelTextSelection:a,edit
153Caption:i,globalPosition:s}=e,{selectedAssetIds:x}=rc(n),{globalCaptionStyle:c,captionDisplayMode:l}=t,d=_I(t),u=za(t);if(u.length===0)return[];const p=s===null?0:Er(u,s);if(r===we.ELEMENT&&x.length===1){x.length>1&&h("selector.ts").warn("Multiple assets are selected");const T=L.get(d,x[0]);if(T&&Wn(T.track))return T.track.customAttributes}const f=w2(u,p,o,l,a,i);if(f){const{targetGlobalClipIndices:T,captionIndex:O}=f;if(O===void 0){const N=T.flatMap(k=>u[k].captions.map(B=>B.style?.mediaId)).filter(Se);if(new Set(N).size>1)return[]}const S=T[0],R=O??Ke.ORIGINAL,{style:y}=u.at(S)?.captions.at(R)??{style:void 0},v=y??c.captionStyleSetting,{customAttributes:w}=v;return w}const{customAttributes:E}=c.captionStyleSetting;return E}),Vv=Te(jo,rt,Nn,(e,t,o)=>{const{webModelTextSelection:r,editCaption:n,globalPosition:a}=e,{globalCaptionStyle:i,captionDisplayMode:s}=t,x=za(t);if(x.length===0)return i.captionStyleSetting;const c=a===null?0:Er(x,a),l=w2(x,c,o,s,r,n);if(l){const{targetGlobalClipIndices:d,captionIndex:u}=l,p=d[0],f=u??Ke.ORIGINAL,{style:E}=x.at(p)?.captions.at(f)??{style:void 0};return E??i.captionStyleSetting}return i.captionStyleSetting}),oet=Te(jo,rt,Nn,(e,t,o)=>{const{webModelTextSelection:r,editCaption:n,globalPosition:a}=e,{globalCaptionStyle:i,captionDisplayMode:s}=t,x=za(t);if(x.length===0)return[i.captionStyleSetting.assetEffectInfo];const c=a===null?0:Er(x,a),l=w2(x,c,o,s,r,n);if(l===null)return[i.captionStyleSetting.assetEffectInfo];const{targetGlobalClipIndices:d,captionIndex:u}=l;return d.flatMap(p=>{const f=x.at(p)?.captions??[];return(u===void 0?f:[f.at(u)]).map(T=>(T?.style??i.captionStyleSetting).assetEffectInfo)})}),hI=Te(Vv,e=>{const{xOffset:t,yOffset:o,yAlign:r,customAttributes:n}=e,a=n.find(s=>s.attributeName==="--textbox-align")?.value??Ny;return{xAlign:{start:Ai.LEFT,center:Ai.CENTER,end:Ai.RIGHT}[a],yAlign:Ow(r),xOffset:t,yOffset:o}}),S2=Te(jo,rt,lt,ht,Nn,(e,t,o,r,n)=>{const{cursorMode:a,selectedElements:i,webModelTextSelection:s,editCaption:x,globalPosition:c}=e,{selectedAssetIds:l}=rc(i),d=za(t),{globalCaptionStyle:u,projectAudioLanguage:p,captionDisplayMode:f}=t;if(d.length===0)return wt().fromText("");const E=c===null?0:Er(d,c);if(a===we.ELEMENT&&l.length===1){const y=L.get(r,l[0]);if(y){const v=y.trackIds.map(w=>L.get(o,w)).find(w=>w!==void 0&&Wn(w));if(v){const{deltas:w}=v;if(s){const{deltaId:N}=s;return new Qt(w[N])}return new Qt(w[Object.keys(w)[0]])}}}const T=w2(d,E,n,f,s,x),{quillStyle:O}=u,S=Ar(on(p));if(T){const{targetGlobalClipIndices:y,captionIndex:v}=T,w=y[0],N=v??Ke.ORIGINAL,{text:M,style:k}=d.at(w)?.captions.at(N)??{text:wt().fromText(""),style:void 0};if(k)return M;const F=Hn(d[w],S,N);return wt().fromText(F,O)}const R=Hn(d[E],S,Ke.ORIGINAL);return cW(R,O)}),ret=Te($x,e=>{for(const t of e.clips){const o=t.words.find(r=>r.hardcutWordMeta!==void 0);if(o!==void 0)return o}}),Gv=Te(Do,kg,Tn,AW,(e,t,o,r)=>{if(t?.position!==void 0)return t.position;if(!r)return o.position;const{from:n,to:a,clipIndex:i}=r,s=e[i];return s?s.startPosition+Math.min(n,a):o.position}),net=Te(He,kg,jo,ds,mo,(e,t,o,r,n)=>{if(t?.position!==void 0){const c=n[t.sceneIndex];return c?t.position+e[c.globalClipRange.from].startPosition:null}if(!r)return o.globalPosition;const{from:a,to:i,globalClipIndex:s}=r,x=e[s];return x?x.startPosition+Math.min(a,i):o.globalPosition}),Fxe=Te(Tn,kg,Do,E2,Gv,(e,t,o,r,n)=>e.globalWordRange||t?.position!==void 0?o.at(Co(o,n)):o.at(r)),aet=Te(ds,kg,Do,E2,Gv,(e,t,o,r,n)=>e||t?.position!==void 0?o.at(Co(o,n)+1):o.at(r+1)),iet=jn(e=>e.snapshots.present.transcript.projectAudioLanguage,e=>e.snapshots.present.transcript.globalCaptionStyle,(e,t)=>t,(e,t,o)=>o,(e,t,o,r)=>Dm(o,r,e,t))((e,t,o,r)=>t.id+"-"+r+"-"+o),kW=e=>EI(e).dubbing,set=e=>e.textedit,Wv=e=>EI(e).batch,Uxe=e=>rt(e).ttsStates,II=e=>e.ttsStates,xet=e=>II(e).clip,cet=e=>II(e).effect,det=e=>II(e).dubbing,uet=e=>II(e).batch,pet=Te(Do,E2,cI,lI,(e,t,o,r)=>{const n={},a=e[t];if(a===void 0)return n;if(a.assetIds.forEach(i=>{const s=L.get(o,i);s&&L.set(n,i,s)}),r!==null){const i=sn(e,r);i&&i.assetIds.forEach(s=>{const x=L.get(o,s);x&&L.set(n,s,x)})}return n}),Vxe=Te(He,zs,Nn,(e,t,o)=>[...o].filter(r=>{const n=e.at(r);return n&&!FW(t,n)})),qd=(e,t)=>L.get(e,ai(t))!==void 0,FW=(e,t)=>
153L.get(e,t.clipId)!==void 0,fet=Te(He,Uxe,(e,t)=>e.map((o,r)=>FW(t.clip,o)?r:null).filter(ri)),UW=Te(zs,e=>Object.values(e).filter(z0e)),TI=(e,t)=>{if(!t)return null;const o=lt(e),r=L.get(o,t);return!r||!xr(r)?null:r},ex=e=>rt(e).globalCaptionStyle,Gxe=e=>ex(e).captionStyleSetting,O2=Te(_0,e=>RI(e)),get=Te(_0,e=>vce(e)),_et=e=>Nn(e).size===0&&ds(e)===null&&_0(e).length===0&&!P0e(e)&&!kxe(e),Wxe=Te(mo,xa,(e,t)=>e[t].globalClipRange),Eet=Te(NW,Wxe,(e,t)=>{if(!e)return!1;const{from:o,to:r}=t;return o===e.start&&r-1===e.end}),met=Te(mo,NW,(e,t)=>t===null?!1:e.some(o=>o.globalClipRange.from===t.start&&o.globalClipRange.to===t.end+1)),het=jn(I2,w0e,(e,t)=>t,(e,t,o)=>oW(o,{videoRatio:j0(e),lastUsedBlankOption:t}))((e,t)=>t),Iet=e=>_l(e).position,VW=e=>rt(e).globalVideoTransform,Tet=e=>Uv(e).target,Oet=Te(S2,ex,(e,t)=>{const o=e.reduce((i,s)=>{if(s.attributes){const x=Mm(s.attributes);if(x.fontName&&x.weight!==0)return i.push(x),i}return i},[]),r=t.quillStyle,{fontName:n,weight:a}=o.at(0)??Mm(r);return n?nW(n,a):void 0}),Cet=Te(S2,ex,(e,t)=>{const o=e.reduce((n,a)=>{if(a.attributes){const i=parseInt(a.attributes.size);if(!isNaN(i))return n.push(i),n}return n},[]),r=el(t);return o.at(0)??r.size}),Ret=Te(S2,ex,(e,t)=>{const o=e.reduce((n,a)=>{if(a.attributes?.["outline-width"]){const i=parseInt(a.attributes["outline-width"]);if(!isNaN(i))return n.push(i),n}return n},[]),r=el(t);return o.at(0)??r.outlineInfo?.outlineWidth}),Aet=Te(S2,ex,(e,t)=>{const o=xW(e,Ro.letterSpacing).at(0);return o?parseFloat(o):el(t).letterSpacing}),yet=Te(S2,ex,(e,t)=>{const o=xW(e,Ro.lineHeight).at(0);return o?parseFloat(o):el(t).lineHeight}),vet=e=>hI(e).xAlign,wet=e=>hI(e).yAlign,Net=e=>hI(e).xOffset,Pet=e=>hI(e).yOffset,bet=Te(Vv,e=>e.customAttributes.find(t=>t.attributeName==="--textbox-align")!==void 0),Let=Te(S2,e=>wt().getAllAttributes(e)),Met=jn(Nxe,Pxe,(e,t)=>t,(e,t,o)=>CH(o,e,t))((e,t)=>ai(t)),Det=Te(_2,lt,ht,(e,t,o)=>e.map(r=>{let n;for(const i of r.words)if(n=oi(i,t,o),n)break;const a=iT(r,t,o);return CH(r,n,a)}).reduce((r,n)=>{for(const a in r)r[a]||=n[a];return r},{"playback-rate":!1,"video-transform":!1,"source-volume":!1,background:!1,transition:!1,filter:!1})),ket=Te(O2,E0,He,(e,t,o)=>{if(!e)return[];const r=L.get(t,e);if(!r)return[];const n=o.at(r.globalClipRange.from);if(!n)return[];if(n.assetIds.includes(e)){const i=r.globalClipRange.from,s=r.globalClipRange.to;return o.slice(i,s).flatMap(x=>x.assetIds).filter(gm)}return n.words.slice(r.wordInClipRange.from,r.wordInClipRange.to).flatMap(i=>i.assetIds).filter(gm)}),Fet=e=>rt(e).autoScrollingWhilePlaying,Uet=Te(uI,$0,Pg,ht,lt,Fi,Pv,vg,(e,t,o,r,n,a,i,s)=>{if(o===null||!e)return[pn.None];const x=t.length>0?t:[o],c=new Set,l=new Set;for(const d of x){const u=e.words[d-e.startPosition];if(!u)continue;const{audioMediaId:p}=ss(u,n,r);if(Q0(u)){l.add(pn.None);continue}const f=bH(u,n,r);if(f){const O=L.get(s,f);if(!O){l.add(pn.None);continue}const S=O.originWords.at(0);if(!S){l.add(pn.None);continue}const{audioMediaId:R}=ss(S,n,r);if(!R){l.add(pn.None);continue}if(c.has(R))continue;c.add(R);const y=L.get(i,R);l.add(y??pn.None);continue}if(!p||c.has(p))continue;c.add(p);const E=Kx(p,a);if(E){const O=E.speaker.lang,S=D0(O);l.add(S);continue}const T=L.get(i,p);T?l.add(T):l.add(pn.None)}return Array.from(l)}),GW=Te(lt,ht,(e,t)=>t,(e,t,o)=>gl(o,e,t)),Vet=(e,t)=>GW(e,t).visualMediaIds.at(0),Get=(e,t)=>GW(e,t).audioMediaIds.at(0),SI=(e,t)=>{switch(t){case nt.CURRENT_CLIP:{const o=uI(e);return o?[o]:[]}case nt.SELECTED_CLIPS:return _2(e);case nt.SCENE_CLIPS:return Do(e);case nt.ALL_CLIPS:return He(e);default:return[]}},Wet=(e,t)=>{const o=SI(e,t),r=lt(e),n=ht(e),a=o.map(i=>iT(i,r,n).find(lv)).filter(i=>i!==void 0);return a.length===0?{horizontal:!1,vertical:!1}:{horizontal:a.every(i=>i.editInfo?.flip?.horizontal===!0),vertical:a.every(i=>i.editInfo?.flip?.vertical===!0)}},Het=Te(CW,xa,He,(e,t,o)=>{if(e===void 0)return null;const r=ci(o),{from:n,to:a}=e.wordPositionRange,i=ku(n,t,r),s=ku(a,t,r);return i===null||s===null?null:{type:"GLOBAL_POSITION",from:i,to:s}}),Hxe=5,WW=40,HW=280,KL=70,Hv=()=>document.getElementsByClassName(Vx.TRANSCRIPT)[0],Ul=(e,t)=>(t===void 0&&(t=Hv()),t?t.scrollTop=e:-1),vm=(()=>{let e;(r=>{r.AsIs="default",r.AlwaysTop="always-top",r.OverflowToTop="overflow-to-top"})(e||(e={}));let t="overflow-to-top",o=!1;return(r,n,a,i)=>{o||(o=!0,Mo().on(Xt.SCROLL_MODE,O=>{const S=O[0];S==="default"||S==="always-top"||S==="overflow-to-top"?t=S:S==="0"?t="default":S==="1"?t="always-top":S==="2"&&(t="overflow-to-top")}));const s=Hv();if(!s)return;const x=()=>a<0?n*Hxe:a,c=(T,O)=>{(i?T-O:T)<s.scrollTop&&Ul(T-O,s)},l=()=>{(i?r+n-s.clientHeight+E:r+n-s.clientHeight)>s.scrollTop&&Ul(r+n-s.clientHeight+E,s)},d=()=>{(i?r-E:r)>s.scrollTop&&Ul(r-E,s)},u=()=>{(i?r+n-s.clientHeight+E:r+n-s.clientHeight)>s.scrollTop&&Ul(r-E,s)},p=u,f=(T=>{switch(T){case"default":return l;case"always-top":return d;case"overflow-to-top":return u;default:return p}})(t),E=x();c(r,E),f()}})(),jv=(e,t,o=!1,r="top")=>{const n=r==="top"?WW:window.innerHeight-HW,a=sn(e,t),i=Qi(a);if(!i){const s=Co(e,t),x=e[s].id,c=ZG(x);if(!c)return;vm(c.top,c.height,n,o);return}vm(i.top,i.height,n,o)},jxe=(e,t,o=!1,r="top")=>{const n=r==="top"?WW:window.innerHeight-HW,a=d0(e,t),i=Qi(a);if(!i){const s=Er(e,t),x=e[s].clipId,c=ZG(x);if(!c)return;vm(c.top,c.height,n,o);return}vm(i.top,i.height,n,o)},wm=(e,t,o=!1,r="top")=>{setTimeout(()=>{jv(e,t,o,r)},0)},jet=(e,t,o=!1,r="top")=>{setTimeout(()=>{jxe(e,t,o,r)},0)},zet=(e,t)=>{if(!t)return;const o=t.getBoundingClientRect(),r=o.height+o.top-KL,n=o.top+KL;e>
153r?Ul(t.scrollTop+e-r,t):e<n&&Ul(t.scrollTop+e-n,t)},jW=e=>{const t=e(),o=lI(t),r=Do(t);if(o===null){h("scroll.ts").error("Invalid position at moveScrollByState()");return}jv(r,o)},zxe=()=>{const e=Hv();!e||!(e instanceof HTMLElement)||Ul(0,e)},Yxe=(e,t)=>{switch(e){case"scene":return $se(t);case"clip":return e0e(t);case"word":return $G(t)??eW(t)}},Bxe=(e,t,o)=>{const r=e.getBoundingClientRect(),n=t.getBoundingClientRect(),a=40;switch(o){case"start":return n.top-r.top-a;case"nearest":{const i=n.top-r.top<a,s=r.bottom-n.bottom<a;return i?n.top-r.top-a:s?n.bottom-r.bottom+a:0}}},Yet=({type:e,id:t,block:o="start"})=>{const r=Yxe(e,t);if(r===null)return;const n=fv();n!==null&&(dRe("scrollIntoView"),n.scrollBy({top:Bxe(n,r,o)}))},Bet=e=>{const t=Kxe(e);if(t===null)return;const o=t.getBoundingClientRect(),r=e.getBoundingClientRect(),n=r.top<o.top?r.top-o.top:r.bottom>o.bottom?r.bottom-o.bottom:0;n!==0&&t.scrollBy({top:n,behavior:"smooth"})},Kxe=e=>{let t=e.parentElement;for(;t!==null;){if(t.scrollHeight>t.clientHeight&&Xxe(t))return t;t=t.parentElement}return null},Xxe=e=>{const{overflowY:t}=getComputedStyle(e);return t==="auto"||t==="scroll"||t==="overlay"?!0:t==="hidden"?e.hasAttribute("data-radix-scroll-area-viewport"):!1},zv=(e,t,o,r)=>{let n=t,a=t,i;return sH(e,t,!r,(s,x)=>{const c=VE(s);return c===void 0||Math.abs(c-o)<3?!0:(i===void 0&&(i=c,n=x),Math.abs(c-i)<3?(a=x,!0):!1)}),i===void 0&&(i=o,n=a=t),n>a&&([n,a]=[a,n]),{wordsInSearch:kpe(e,n,a+1),wordsStartPosition:n}},Qp=(e,t,o,r)=>{if(r===void 0||!o)return e;const{left:n,top:a,width:i,height:s}=o,{x,y:c}=r;if((n<x&&x<n+i&&a<c&&c<a+s)===!1)return e;const d=5;if(t){if(x-n>=i/2)return e+1}else if(x-n>i-d)return e+1;return e},Ket=(e,t,o,r)=>{const a=xs(e[t]),i=sn(e,a),s=Qi(i);if(!s)return a;const x=s.top+10,{wordsInSearch:c,wordsStartPosition:l}=zv(e,a,x,!0),d=c.map((u,p)=>({weight:Math.abs(Ag(u).left-o),index:p,word:u}));if(Mo().getDebugVal(Xt.SMART_UPDOWN)===void 0){const u=l+d[0].index;return Qp(u,d[0].word.type===Z.SILENT,Qi(d[0].word),r)}},Jxe=(e,t,o,r)=>{const a=C2(e[t+1]),i=sn(e,a),s=Qi(i);if(!s)return a;const x=s.top+-10,{wordsInSearch:c,wordsStartPosition:l}=zv(e,a,x,!1),d=c.map((u,p)=>({weight:Math.abs(Ag(u).left-o),index:p,word:u}));if(Mo().getDebugVal(Xt.SMART_UPDOWN)===void 0){const u=l+d[0].index;return Qp(u,d[0].word.type===Z.SILENT,Qi(d[0].word),r)}},Xet=(e,t,o,r,n,a)=>{const{position:i,cursorMode:s,globalWordRange:x}=t,c=AI(x,n);if(i===null)return h("cursor.ts").error("Invalid position of calcPosition()"),0;let l=i,d=i;if(c!==null){const{from:N,to:M}=G0(c),k=e[c.clipIndex].startPosition;l=N+k,d=M+k}const u=s===we.INSERT_CURSOR&&c!==null&&!o,p=u?r===Bx.KEYBOARD_DOWN?d:l:i,f=sn(e,p),E=sn(e,p),T=Qi(E),O=Qi(f);if(!T||!O)return i;const S=T.top,{wordsInSearch:R,wordsStartPosition:y}=zv(e,p,S,r===Bx.KEYBOARD_UP);if(R.length===0)return Qp(i,E.type===Z.SILENT,T,a);const v=(N,M)=>Math.abs(M?M.left-N.left:-N.left),w=R.map((N,M)=>({weight:v(O,Qi(N)),index:M,word:N}));return w.length===0?Qp(Wm(e,R[0].id),R[0].type===Z.SILENT,Qi(R[0]),a):(w.sort((N,M)=>N.weight-M.weight),Qp(y+w[0].index,w[0].word.type===Z.SILENT,Qi(w[0].word),a))},Jet=(e,t)=>e.lastMoveMethod===Bx.WORD_CLICK&&e.globalWordRange&&e.globalWordRange.from>=t,qxe=e=>({...e,from:e.to,to:e.from}),G0=e=>{const t=e.from<e.to?e.from:e.to,o=e.from<e.to?e.to:e.from;return{...e,from:t,to:o}},Yv=e=>{const t=e.from<e.to?e.from:e.to,o=e.from<e.to?e.to:e.from;return{from:t,to:o,globalClipIndex:e.globalClipIndex}},Bv=e=>{const t=G0(e);return t.to-t.from},qet=(e,t,o)=>{if(t===null||Bv(t)!==1)return o;const{from:r,clipIndex:n}=G0(t),a=e[n];return Nm(a,r)},Qet=e=>{const t=e.from<e.to?e.from:e.to,o=e.from<e.to?e.to:e.from;return{from:t,to:o}},Zet=(e,t,o,r,n)=>{if(e.position===null)return h("cursor.ts").error("Invalid position at selectOneWordRight()"),e;const a=e.position,i=Co(t,a),s=t[i],x=e.globalWordRange?e.globalWordRange.from:a-s.startPosition;return $c.insertCursor(s.startPosition,x===0?null:{from:0,to:x,globalClipIndex:jw(i,n,r)},o)},$et=(e,t,o,r,n)=>{if(e.position===null)return h("cursor.ts").error("Invalid position at selectOneWordRight()"),e;const a=e.position,i=Co(t,a),s=jw(i,n,r),x=t[i],c=e.globalWordRange?e.globalWordRange.to:a-x.startPosition,l=Ys(x);return $c.insertCursor(x.startPosition+l,{from:c,to:l,globalClipIndex:s},o)},ett=(e,t)=>e.length===0?!1:t===e[0].startPosition,Qxe=(e,t)=>{if(e.length===0)return!1;const o=e[e.length-1];return t===o.startPosition+o.words.length-1},Kv=(e,t)=>e===t.startPosition,ttt=(e,t)=>e===t.startPosition,Xv=(e,t)=>e===t.startPosition+t.words.length-1,XL=(e,t)=>e===t.startPosition+t.words.length-1,ott=(e,t)=>{if(e.length<t||Kg(e,t)){if(Vr())throw new Error("invaild globalClipIndex "+t+" on getStartPosOfPrevGlobalClip");return h("cursor.ts").warn("invaild globalClipIndex "+t+" on getStartPosOfPrevGlobalClip"),wf(e[t])}const o=e[t-1];return wf(o)},rtt=(e,t)=>{if(e.length<t||tl(e,t)){if(Vr())throw new Error("invaild clipIndex "+t+" on getStartPosOfNextClip");return h("cursor.ts").warn("invaild clipIndex "+t+" on getStartPosOfNextClip"),xs(e[t])}const o=e[t];return xs(o)+1},ntt=(e,t)=>{if(e.length<t||tl(e,t)){if(Vr())throw new Error("invaild globalClipIndex "+t+" on getNextClipStartPos");return h("cursor.ts").warn("invaild globalClipIndex "+t+" on getNextClipStartPos"),HR(e[t])}const o=e[t];return HR(o)+1},xs=e=>e.startPosition+e.words.length-1,C2=e=>e.startPosition,HR=e=>e.startPosition+e.words.length-1,wf=e=>e.startPosition,att=(e,t,o,r,n,a=null)=>{const i=ci(e),s=i[t].globalClipRange.from+r,x=s+1;return $c.clipCursor(o,{from:s,to:x},n,a)},itt=(e,t,o,r,n,a=null)=>{const i=ci(e),{clips:s,globalClipRange:x}=i[t],c=x.from+r,l=c+1;return $c.clipCursor(o,{from:c,to:l,fromWord:o-s[r].startPosition},n,a)},OI=e=>e.from>e.to,Jv=e=>e.from<e.to,Zc=e=>{const t=g2(e);return e!==null&&[...t].length===1},zW=e=>e!==null&&Math.abs(e.from-e.to)===1,Zxe=e=>e.sort((o,r)=>o-r).reduce((o,r)=>{const n=o.at(-1);if(n===void 0)return[[r,r]];const[a,i]=n;return r===i+1?(o.pop(),o.push([a,r]),o):(o.push([r,r]),o)},[]).map(([o,r])=>({from:o,to:r+1})).reduceRight((o,r)=>({...r,next:o??void 0}),null),stt=(e,t)=>{if(Zc(t)&&Jv(t)){const{from:r,to:n}=BW(t),a=n-1;return Nf(e,{from:r,to:a})}const o=t.to-1;return Nf(e,{from:t.from,to:o})},xtt=(e,t)=>{if(Zc(t)&&OI(t)){const{from:r,to:n}=BW(t),a=n+1;return Nf(e,{from:r,to:a})}const o=t.to+1;return Nf(e,{from:t.from,to:o})},ctt=(e,t,o)=>{let{from:r,to:n}=t;return r>o?(n=o,r=Jv(t)?r+1:r):(n=o+1,r=OI(t)?r-1:r),{...Nf(e,{from:r,to:n}),fromWord:t.fromWord}},ltt=(e,t)=>t.from<t.to?e[t.to-1].startPosition+e[t.to-1].words.length-1:e[t.to].startPosition,dtt=(e,t,o)=>{const r=o-e.startPosition;return t.from===r?null:{...t,to:r}},utt=(e,t,o)=>{const r=e===Bx.WORD_CLICK&&Bv(t)===1,n=!OI(t);return r&&(n&&o==="left"||!n&&o==="right")?qxe(t):t},ptt=(e,t)=>zW(t)&&Jv(t)?null:YW(e,{...t,to:t.to-1}),ftt=(e,t)=>zW(t)&&OI(t)?null:YW(e,{...t,from:t.from,to:t.to+1}),Nf=(e,t)=>
153{const{from:o,to:r}=t;return{from:$t(o,0,e.length),to:$t(r,0,e.length)}},YW=(e,t)=>{const{from:o,to:r}=t;return{...t,from:$t(o,0,e.words.length-1),to:$t(r,0,e.words.length-1)}},BW=e=>({from:e.to,to:e.from}),Su=(e,t)=>$c.insertCursor(e,null,t),gtt=(e,t)=>{const o=e.startPosition+e.words.length-1;return Su(o,t)},_tt=(e,t)=>m0e(e,t,!0),Ett=(e,t)=>lW(e,t,!0),$xe=(e,t)=>h0e(e,t,!0),ns=(e,t)=>{const o=t-e.startPosition;return o<0||o>e.words.length-1?(h("cursor.ts").error("positionToLocalIndexInClip: Invalid position:"+t+", clip startPosition:"+e.startPosition),0):o},CI=(e,t)=>{const o=t-e.startPosition;return o<0||o>e.words.length-1?(h("cursor.ts").error("globalPositionToLocalIndexInClip: Invalid position:"+t+", clip startPosition:"+e.startPosition),0):o},Nm=(e,t)=>{const o=e.startPosition+t,r=C2(e),n=xs(e);return o<r||o>n?(h("cursor.ts").error("localIndexInClipToPosition: Invalid position:"+o+", clip positions:"+r+"~"+n),0):o},mtt=(e,t)=>{const o=e.startPosition+t,r=wf(e),n=HR(e);return o<r||o>n?(h("cursor.ts").error("localIndexInGlobalClipToGlobalPosition: Invalid position:"+o+", clip positions:"+r+"~"+n),0):o},htt=e=>Math.min(e.from,e.to),Itt=e=>Math.max(e.from,e.to),ece=(e,t,o,r)=>({cursorMode:we.INSERT_CURSOR,position:e,globalWordRange:t,globalClipRange:null,selectedElements:[],webModelTextSelection:null,lastMoveMethod:o,isDraggingWord:r,editCaption:null,selectedWatermarkId:null}),Ttt=({globalPosition:e,globalWordRange:t=null,lastMoveMethod:o=null,isDraggingWord:r=!1})=>({cursorMode:we.INSERT_CURSOR,globalPosition:e,globalWordRange:t,globalClipRange:null,selectedElements:[],webModelTextSelection:null,lastMoveMethod:o,isDraggingWord:r,editCaption:null,selectedWatermarkId:null}),tce=(e,t,o,r=null)=>
153({cursorMode:we.CLIP,position:e,globalWordRange:r,globalClipRange:t,selectedElements:[],webModelTextSelection:null,lastMoveMethod:o,editCaption:null,selectedWatermarkId:null}),oce=(e,t,o,r)=>({cursorMode:we.DISABLED,position:e,globalWordRange:o,globalClipRange:t,selectedElements:[],webModelTextSelection:null,lastMoveMethod:r,editCaption:null,selectedWatermarkId:null}),rce=(e,t,o)=>({cursorMode:we.CORRECTING,position:e,globalWordRange:null,globalClipRange:null,selectedElements:[],webModelTextSelection:null,lastMoveMethod:t,correctingInfo:o,editCaption:null,selectedWatermarkId:null}),nce=(e,t,o)=>({cursorMode:we.WATERMARK,position:e,globalWordRange:null,globalClipRange:null,lastMoveMethod:t,selectedElements:[],webModelTextSelection:null,editCaption:null,selectedWatermarkId:o}),ace=(e,t,o,r)=>({cursorMode:we.CAPTION,position:e,globalWordRange:null,globalClipRange:null,lastMoveMethod:t,selectedElements:[],webModelTextSelection:r,editCaption:o,selectedWatermarkId:null}),ice=(e,t,o,r,n,a,i)=>({cursorMode:n.length===0?we.INSERT_CURSOR:we.ELEMENT,position:e,globalWordRange:t,globalClipRange:o,lastMoveMethod:r,selectedElements:n,webModelTextSelection:a,editCaption:null,selectedFromAssetList:i,selectedWatermarkId:null}),sce=(e,t,o,r,n,a,i)=>({cursorMode:n.length===0?we.INSERT_CURSOR:we.ELEMENT,globalPosition:e,globalWordRange:t,globalClipRange:o,lastMoveMethod:r,selectedElements:n,webModelTextSelection:a,editCaption:null,selectedFromAssetList:i,selectedWatermarkId:null}),xce=(e,t)=>({...e,selectedFromAssetList:t}),cce=(e,t,o)=>vt(e,r=>{r.globalCursor=$W(o,e.globalClips,t)}),lce=(e,t,o)=>vt(e,r=>{r.globalCursor=o}),dce=(e,t,o,r)=>vt(e,n=>{n.globalCursor=$W(o,r,t)}),uce=(e,t,o=null,r=null)=>
153({cursorMode:we.CLIP,globalPosition:e,globalWordRange:r,globalClipRange:t,selectedElements:[],webModelTextSelection:null,lastMoveMethod:o,editCaption:null,selectedWatermarkId:null}),pce=(e,t,o,r)=>({cursorMode:we.CAPTION,globalPosition:e,globalWordRange:null,globalClipRange:null,lastMoveMethod:t,selectedElements:[],webModelTextSelection:r,editCaption:o,selectedWatermarkId:null}),fce=(e,t,o,r)=>({cursorMode:we.DISABLED,globalPosition:e,globalWordRange:o,globalClipRange:t,selectedElements:[],webModelTextSelection:null,lastMoveMethod:r,editCaption:null,selectedWatermarkId:null}),$c={insertCursor:ece,clipCursor:tce,disabledCursor:oce,correctingCursor:rce,elementCursor:ice,elementGlobalCursor:sce,selectedFromAssetListCursor:xce,captionCursor:ace,transcript:cce,globalTranscript:lce,transcriptWithNewScene:dce,watermarkCursor:nce,globalClipCursor:uce,globalCaptionCursor:pce,globalDisabledCursor:fce},Stt=(e,t)=>{const o=e.words.length-1;return t.from===o?null:{...t,to:o}},Ott=(e,t)=>t.from===0?null:{...t,to:0},KW=(e,t)=>{const o=VE(t);if(o===void 0)return[];const r=e.words.findIndex(a=>VE(a)===o),n=[];for(const[a,i]of e.words.slice(r).entries()){const s=VE(i);if(s===void 0||s===o)n.push({word:i,index:r+a});else break}return n},JL=(e,t,o)=>{const r=e[t],n=sn(e,o),a=KW(r,n);return a.length===0?r.startPosition:r.startPosition+a[0].index},qL=(e,t,o,r=!1)=>{const n=e[t],a=sn(e,o),i=KW(n,a);if(i.length===0)return n.startPosition+n.words.length-1;const s=n.startPosition+n.words.length-1,x=n.startPosition+i[i.length-1].index;return x!==s&&r?x+1:x},Ctt=(e,t,o)=>{const r=e[t],n=JL(e,t,o),a=n===C2(r);if(o!==n||a)return n;const i=o-1;return JL(e,t,i)},Rtt=(e,t,o,r=!0)=>{const n=e[t],a=qL(e,t,o,r),i=a===xs(n);if(o!==a||i)return a;const s=o+1;return qL(e,t,s,r)},XW=(e,t,o,r)=>{const{globalPosition:n,cursorMode:a,globalWordRange:i}=t;if(n===null||r&&a!==we.CAPTION)return!1;switch(a){case we.CORRECTING:case we.DISABLED:return!1;case we.CAPTION:case we.CLIP:case we.ELEMENT:return!0}const s=CI(e,n),x=Ys(e);return s===x&&i===null?(xt.info(A(o?"transcript.invalid_cut":"transcript.invalid_copy")),!1):!0},JW=(e,t)=>{const o=Do(e),r=q0(),n=Tn(e),{position:a,globalClipRange:i}=n;if(a===null||r)return!1;const s=zs(e),x=o.length-1,c=Co(o,a),l=gce(i),d=o.at(c),u=o.at(c-1),p=o.at(c+1);switch(n.cursorMode){case we.CORRECTING:case we.DISABLED:case we.ELEMENT:return xt.info(A("transcript.merge_invalid_cursor_mode")),!1}switch(t){case qa.CLIPS:{if(!l)return xt.info(A("transcript.merge_incontinuous_clips")),!1;if(bg(e).some(E=>qd(s,E)))return i0(A("tts.error_merge_in_modifying")),!1;break}case qa.PREV:if(c===0)return xt.info(A("transcript.invalid_merge_direction_forward")),!1;if(u&&qd(s,u)||d&&qd(s,d))return i0(A("tts.error_merge_in_modifying")),!1;break;case qa.NEXT:case qa.DEFAULT:if(c===x)return xt.info(A("transcript.invalid_merge_direction_backward")),!1;if(d&&qd(s,d)||p&&qd(s,p))return i0(A("tts.error_merge_in_modifying")),!1;break}return!0},qW=(e,t)=>{const{cursorMode:o}=e;if(t)return!1;switch(o){case we.CLIP:{const{globalClipRange:r}=e;if(!Zc(r))return xt.info(A("transcript.split_invalid_cursor_mode")),!1;break}case we.INSERT_CURSOR:case we.CAPTION:break;default:return xt.info(A("transcript.split_invalid_cursor_mode")),!1}return!0},gce=e=>{if(e===null)return!1;const t=g2(e),o=Math.max(...t),r=Math.min(...t),n=t.size;return o-r+1===n},_ce=e=>{if(e.length===0)return 0;const t=e[e.length-1];return t.startPosition+t.words.length-1},Ece=(e,t,o,r,n,a)=>{if(r==="left"){let x=e.from;return n===e.from&&e.from>0&&(x=e.from===t.startPosition?Math.max(e.from-2,0):Math.max(e.from-1,0)),{...e,from:x,to:Math.max(e.to-1,0)}}const i=_ce(o);let s=e.to;return a!==e.to-1?s=Math.max(e.to-1,0):xs(t)===e.to&&(s=Math.min(e.to+1,i)),{...e,to:s}},Att=e=>e[0].startPosition,mce=e=>e===null?!1:g2(e).size>=2,hce=(e,t)=>{if(t===null)return!1;const{from:o,to:r}=G0(t);return o===0||r===Ys(e)},ytt=(e,t,o,r,n)=>{const a=ci(e),{clips:i}=a[t],{position:s}=o;if(s===null)return;const x=Co(i,s),c=eJe(a,t);if(tl(i,x)){if(c)return;{const d=t+1,u=a[d].clips,p=0;return wm(u,p),{cursor:Su(p,n),sceneIndex:d}}}else{const d=Co(i,s),u=sn(i,s),p=Ag(u);
153if(!p){const O=x+1,S=i[O],R=C2(S);return{cursor:Su(R,n),sceneIndex:t}}const f=r!==null?Kse():p.left,E=Jxe(i,d,f);return wm(i,E),{cursor:Su(E,n),sceneIndex:t}}},vtt=(e,t,o,r,n,a,i,s)=>{const{clips:x}=t[e],{editCaption:c,position:l}=o;if(l===null||i===null)return;const d=Co(x,l),u=Kg(x,d),p=$9e(t,e);if(u)if(p){zxe();return}else{const f=e-1,E=t[f],T=E.clips,O=T.length-1,S=T[O],R=xs(S);return wm(T,R),{cursor:r!==null?$c.captionCursor(R,n,{captionIndex:r,globalClipIndex:E.globalClipRange.from+O},null):Su(R,n),sceneIndex:f}}else{const f=s?.specifyPosition!==void 0?Co(x,s.specifyPosition):d-1,E=x[f],T=s?.specifyPosition!==void 0?s.specifyPosition:xs(E),O=f!==d?r!==null?Tce(a,i,jw(f,e,a),r):null:c;return wm(x,T),{cursor:O?$c.captionCursor(T,n,O,null):Su(T,n),sceneIndex:e}}},wtt=e=>0,Ntt=e=>e.words.length-1,Ice=(e,t,o)=>Co(e,t)===Co(e,o),Ptt=(e,t,o,r)=>{const n={globalClipIndex:o,captionIndex:r},a=e[o],i=d0(e,t),s=Ag(i),x=QG(a,r),c=qG(x);if(!s||!x||!c||Mo().getDebugVal(Xt.SMART_UPDOWN)===void 0)return n},Tce=(e,t,o,r)=>{const n={globalClipIndex:o,captionIndex:r},a=e[o],i=d0(e,t),s=Ag(i),x=QG(a,r),c=qG(x);if(!s||!x||!c||Mo().getDebugVal(Xt.SMART_UPDOWN)===void 0)return n},Sce=(e,t)=>{const o=Td(ai(t)),r=document.getElementById(o);if(!(r instanceof HTMLElement))return!1;const{offsetWidth:n,offsetLeft:a}=r;return n/2+a<e.x},btt=(e,t,o,r)=>{const n=d0(e,t),a=o?Bse(n,o):gx.LEFT;return r?a===gx.LEFT?t:t+1:a===gx.RIGHT?t+1:t},Oce=(e,t,o)=>{if(o===null)return Er(e,t,!0);const{from:r,to:n}=o;return r>n?r-1:r},Ltt=(e,t,o,r)=>{const n=Oce(e,t,o);return Math.abs(r-n)+1},Mtt=(e,t,o,r,n,a)=>{const i=Cce(e,o,t,r),s=QW(a,t.globalClipRange,n),x=ZW(a,t.globalWordRange,r);return{...t,position:i,globalClipRange:s,globalWordRange:x}},Cce=(e,t,o,r)=>{const n=C2(t[r]);if(o.position===null)return n;const a=sn(e,o.position).id,i=Wm(t,a,!0);return i===-1?n:i},QW=(e,t,o)=>{const r=Array.from(g2(t),n=>n>o?n+e:n);return Zxe(r)},ZW=(e,t,o)=>t===null?null:{...t,globalClipIndex:t.globalClipIndex+(t.globalClipIndex>o?e:0)},Dtt=(e,t,o,r,n)=>{const a=Rce(e,o,t,r),i=QW(n,t.globalClipRange,r),s=ZW(n,t.globalWordRange,r);return{...t,globalPosition:a,globalClipRange:i,globalWordRange:s}},Rce=(e,t,o,r)=>{const n=t.length===0?null:wf(t[Math.min(r,t.length-1)]);if(o.globalPosition===null)return n;const a=d0(e,o.globalPosition).id,i=iH(t,a,!0);return i===-1?n:i},rc=e=>{const t=[],o=[];return e.forEach(r=>{r.type===ra.ASSET?t.push(r.id):r.type===ra.AUDIO?o.push(r.id):h("cursor.ts").error("Unknown element type: "+r.type)}),{selectedAssetIds:t,selectedAudioIds:o}},Ace=e=>e.length===1&&e[0].type===ra.ASSET,yce=e=>e.length===1&&e[0].type===ra.AUDIO,RI=e=>Ace(e)?e[0].id:null,vce=e=>yce(e)?e[0].id:null,wce=e=>e===we.ELEMENT,Nce=e=>e===ra.ASSET,Pce=e=>e===ra.AUDIO,wc=Gr((e,t)=>{if(e===null)return null;if(e===0&&t.length===0)return 0;const o=Er(t,e),r=t[o];if(!r)return h("cursor.ts").error("Cannot get clip by position: "+e+", globalClips num: "+t.length+", clipIndex: "+o),0;const n=t.findIndex(i=>i.sceneId===r.sceneId);if(n===-1)return h("cursor.ts").error("Cannot get clip of "+r.sceneId+" of clipIdx: "+o),0;const a=t[n];return e-a.startPosition}),ku=Gr((e,t,o)=>{if(e===null)return null;let r=0;for(let n=0;n<t;++n){const a=o[n],i=a?.clips.at(-1);if(!a||!i){const x=o.map(l=>""+l.clips.length).join(","),c="Cannot get position of "+e+" with sceneIndex "+t+", clip lengths: "+x;if(h("cursor.ts").error(c),Vr())throw new Error(c);return 0}const s=i.startPosition+i.words.length;r+=s}return r+e}),ktt=(e,t,o)=>e===null?null:{from:e.from,to:e.to,globalClipIndex:Kpe(e.clipIndex,t,o)},AI=(e,t)=>e===null?null:{from:e.from,to:e.to,clipIndex:Bpe(e.globalClipIndex,t)},bce=Gr((e,t,o)=>{const r=wc(e.globalPosition,o);return{cursorMode:e.cursorMode,position:r,globalWordRange:e.globalWordRange,globalClipRange:e.globalClipRange,selectedElements:e.selectedElements,webModelTextSelection:e.webModelTextSelection,isDraggingWord:e.isDraggingWord,correctingInfo:e.correctingInfo,lastMoveMethod:e.lastMoveMethod,editCaption:e.editCaption,selectedFromAssetList:e.selectedFromAssetList,selectedWatermarkId:e.selectedWatermarkId}}),$W=Gr((e,t,o)=>{const r=ci(t),n=ku(e.position,o,r);return{cursorMode:e.cursorMode,globalPosition:n,globalWordRange:e.globalWordRange,globalClipRange:e.globalClipRange,selectedElements:e.selectedElements,webModelTextSelection:e.webModelTextSelection,isDraggingWord:e.isDraggingWord,correctingInfo:e.correctingInfo,lastMoveMethod:e.lastMoveMethod,editCaption:e.editCaption,selectedFromAssetList:e.selectedFromAssetList,selectedWatermarkId:e.selectedWatermarkId}}),Ftt=e=>"globalPosition"in e,Lce=(e,t,o)=>t===null?!0:Er(e,t)!==Er(e,o),Utt=(e,t)=>{const{globalClips:o,globalCursor:r}=e,n=_l(e);
153if(r.globalPosition===t)return e;const a=y_(o,t),i=ci(o),s=i[a];if(!s)return e;const x=wc(t,o);if(x===null)return e;const c=vt(n,l=>{n.editCaption===null&&(l.position=x,l.lastMoveMethod=null)});return e.autoScrollingWhilePlaying&&n.editCaption===null&&Lce(o,r.globalPosition,t)&&jv(s.clips,x),$c.transcript(e,a,c)},Mce=e=>{const t=e[e.length-1];return t.startPosition+t.words.length-1},Vtt=(e,t)=>t&&(e===J.LEFT||e===J.RIGHT||e===J.UP||e===J.DOWN||e===J.SHIFT_LEFT||e===J.SHIFT_RIGHT||e===J.SHIFT_UP||e===J.SHIFT_DOWN),Gtt=(e,t)=>{const o=Er(e,t),r=e[o];return{globalClipIndex:o,from:t-r.startPosition,to:t-r.startPosition+1}},Dce="/try/assets/shape-arrow-C0M9CHVk.svg",kce="/try/assets/shape-cross-c3gqnR-X.svg",Fce="/try/assets/shape-dashed-arrow-XzxeGepy.svg",Uce="/try/assets/shape-dashed-line-DpHpiW0q.svg",Vce="/try/assets/shape-double-arrow-C0bkJh8z.svg",QL="/try/assets/shape-line-bMlFgQwU.svg",Gce="/try/assets/shape-oval-KBF9Q6Hx.svg",Wce="/try/assets/shape-rounded-square-BDSTssCP.svg",Hce="/try/assets/shape-square-BSghP7vU.svg",jce
153="/try/assets/shape-triangle-TQRkFvL8.svg",zce=e=>x_(e)?.rawSvg,Yce=(e,t)=>({type:"shape",id:e.shapeId,shapeType:e.shapeKey,stockSite:"vrew",width:142,height:142,srcUrl:e.thumbnailPath,option:e.defaultStyles,searchTags:e.searchTags,order:t*2+4}),yI=e=>Qx(e)?e.hasHead?e.stroke.isDashed?Ye.DashedArrow:e?.shapeOfHead==="double"?Ye.DoubleArrow:Ye.Arrow:e.stroke.isDashed?Ye.DashedLine:Ye.Line:i2(e)?e.shapeSource:Ye.Line,Bce=(e,t)=>{const o=L.get(t,e);return o&&f0(o)?yI(o):void 0},Wtt=(e,t,o)=>{const r=L.get(o,e);if(r)for(const n of r.trackIds){const a=Bce(n,t);if(a!==void 0)return a}},Htt=e=>{switch(yI(e)){case Ye.DashedArrow:case Ye.Arrow:return{stroke:Ie.LAST_SHAPE_ARROW_COLOR};case Ye.DashedLine:case Ye.Line:return{stroke:Ie.LAST_SHAPE_LINE_COLOR};default:return{}}},Kce=e=>{switch(yI(e)){case Ye.DashedArrow:return Fce;case Ye.Arrow:return Dce;case Ye.DashedLine:return Uce;case Ye.Line:return QL;case Ye.Square:return Hce;case Ye.Deprecated_RoundedSquare:return Wce;case Ye.Oval:return Gce;case Ye.Triangle:return jce;case Ye.Cross:return kce;case Ye.DoubleArrow:return Vce;default:return QL}},jtt=e=>
153{const t=$e().getStockShapeInfo()?.presets;return t===void 0?[]:t.filter(o=>o.searchTags.includes(e))},ztt=["shape_keyword.line","shape_keyword.arrow","shape_keyword.triangle","shape_keyword.square","shape_keyword.circle"],Ytt=(e,t,o)=>{const r=Qx(e),n=r?e.width/e.stroke.width:t*e.width/e.height;if(n>o){const s=o/n,x=e.stroke.width*(1/e.width),c=r?-.5:0,l=r?0:(1-s)/2;return{...e,stroke:{...e.stroke,width:x},width:1,height:s,xPos:c,yPos:l,rotation:0}}const a=n/o,i=e.stroke.width*(a/e.width);return{...e,stroke:{...e.stroke,width:i},width:a,height:1,xPos:(1-a)/2,yPos:0,zIndex:0}},Xce=e=>e===Ye.Square||e===Ye.Oval||e===Ye.Triangle||e===Ye.Cross,Btt=e=>Xce(e.shapeType),Ktt=[Ye.Line,Ye.DashedLine,Ye.Arrow,Ye.DashedArrow,Ye.DoubleArrow,Ye.Cross,Ye.Square,Ye.Triangle,Ye.Oval],Xtt=(e,t,o=e.width)=>{if(Qx(e)){if(e.hasHead){const r=t*4;return Math.max(o,r*Math.sqrt(2))}return Math.max(o,t)}return o},Pi=(e,t)=>{const o=Ve().getObject(e),r=Array.isArray(o)?o[0]:t;return String(r)},ZL=e=>typeof e=="string"?e:void 0,hO=e=>typeof e=="number"?e:void 0,$L=e=>typeof e=="boolean"?e:void 0,tx=e=>{const t=ZL(e.strokeColor),o=hO(e.strokeWidth),r=$L(e.strokeDashed),n=$L(e.strokeRounded),a=hO(e.aspectRatio),i=ZL(e.planeColor),s=hO(e.cornerRounding);return{strokeColor:t,strokeWidth:o,strokeDashed:r,strokeRounded:n,aspectRatio:a,planeColor:i,cornerRounding:s}},Ug=(e,t=Jce,o="part")=>{const r=t/e,n=o==="part"?.4:Math.min(r,1),a=n/r,i=(1-n)/2,s=(1-a)/2;return{width:n,height:a,xPos:i,yPos:s}},ox=.01,rx=!0,Vg=!1,Jce=1,e3=0,qce=(e,t,o,r,n)=>{const a=Pi(Ie.LAST_SHAPE_LINE_COLOR,Ni),i=tx(n);return{trackId:e,type:z.SHAPE,dimensionType:Tr.ONE,stroke:{color:i.strokeColor??a,width:i.strokeWidth??ox,isRounded:i.strokeRounded??rx,isDashed:!1},xPos:.3,yPos:.5,rotation:0,width:.4,height:0,mediaId:t,zIndex:o,hasHead:!1}},Qce=(e,t,o,r,n)=>{const a=Pi(Ie.LAST_SHAPE_LINE_COLOR,Ni),i=tx(n);return{trackId:e,type:z.SHAPE,dimensionType:Tr.ONE,stroke:{color:i.strokeColor??a,width:i.strokeWidth??ox,isRounded:i.strokeRounded??rx,isDashed:!0},xPos:.3,yPos:.5,rotation:0,width:.4,height:0,mediaId:t,zIndex:o,hasHead:!1}},Zce=(e,t,o,r,n)=>{const a=Pi(Ie.LAST_SHAPE_ARROW_COLOR,Ni),i=tx(n);return{trackId:e,type:z.SHAPE,dimensionType:Tr.ONE,stroke:{color:i.strokeColor??a,width:i.strokeWidth??ox,isRounded:i.strokeRounded??rx,isDashed:!1},xPos:.3,yPos:.5,rotation:0,width:.4,height:0,mediaId:t,zIndex:o,hasHead:!0,shapeOfHead:"single"}},$ce=(e,t,o,r,n)=>{const a=Pi(Ie.LAST_SHAPE_ARROW_COLOR,Ni),i=tx(n);return{trackId:e,type:z.SHAPE,dimensionType:Tr.ONE,stroke:{color:i.strokeColor??a,width:i.strokeWidth??ox,isRounded:i.strokeRounded??rx,isDashed:!0},xPos:.3,yPos:.5,rotation:0,width:.4,height:0,mediaId:t,zIndex:o,hasHead:!0,shapeOfHead:"single"}},ele=(e,t,o,r,n)=>{const a=Pi(Ie.LAST_SHAPE_ARROW_COLOR,Ni),i=tx(n);return{trackId:e,type:z.SHAPE,dimensionType:Tr.ONE,stroke:{color:i.strokeColor??a,width:i.strokeWidth??ox,isRounded:i.strokeRounded??rx,isDashed:!1},xPos:.3,yPos:.5,rotation:0,width:.4,height:0,mediaId:t,zIndex:o,hasHead:!0,shapeOfHead:"double"}},tle=(e,t,o,r,n,a)=>{const i=Pi(Ie.LAST_SHAPE_LINE_COLOR,Ni),s=tx(n),{width:x,height:c,xPos:l,yPos:d}=Ug(r,s.aspectRatio,a);return{trackId:e,type:z.SHAPE,dimensionType:Tr.TWO,mediaId:t,zIndex:o,shapeType:od.DEFAULT,shapeSource:Ye.Cross,stroke:{color:s.strokeColor??i,width:s.strokeWidth??ox,isDashed:s.strokeDashed??Vg,isRounded:s.strokeRounded??rx},width:x,height:c,xPos:l,yPos:d,rotation:0}},ole=(e,t,o,r,n,a)=>{const i=Pi(Ie.LAST_SHAPE_LINE_COLOR,Ni),s=Pi(Ie.LAST_SHAPE_PLANE_COLOR,Ni),x=tx(n),{width:c,height:l,xPos:d,yPos:u}=Ug(r,x.aspectRatio,a);return{trackId:e,type:z.SHAPE,dimensionType:Tr.TWO,mediaId:t,zIndex:o,shapeType:od.DEFAULT,shapeSource:Ye.Oval,stroke:{color:x.strokeColor??i,width:x.strokeWidth??ox,isDashed:x.strokeDashed??Vg,isRounded:x.strokeRounded??rx},plane:{color:x.planeColor??s},width:c,height:l,xPos:d,yPos:u,rotation:0}},rle=(e,t,o,r,n,a)=>{const i=Pi(Ie.LAST_SHAPE_LINE_COLOR,Ni),s=Pi(Ie.LAST_SHAPE_PLANE_COLOR,Ni),x=tx(n),{width:c,height:l,xPos:d,yPos:u}=Ug(r,x.aspectRatio,a);return{trackId:e,type:z.SHAPE,dimensionType:Tr.TWO,mediaId:t,zIndex:o,shapeType:od.DEFAULT,shapeSource:Ye.Square,stroke:{color:x.strokeColor??i,width:x.strokeWidth??ox,isDashed:x.strokeDashed??Vg,isRounded:x.strokeRounded??rx},plane:{color:x.planeColor??s},cornerRounding:x.cornerRounding??e3,width:c,height:l,xPos:d,yPos:u,rotation:0}},nle=(e,t,o,r,n,a)=>{const i=Pi(Ie.LAST_SHAPE_LINE_COLOR,Ni),s=Pi(Ie.LAST_SHAPE_PLANE_COLOR,Ni),x=tx(n),{width:c,height:l,xPos:d,yPos:u}=Ug(r,x.aspectRatio,a);return{trackId:e,type:z.SHAPE,dimensionType:Tr.TWO,mediaId:t,zIndex:o,shapeType:od.DEFAULT,shapeSource:Ye.Deprecated_RoundedSquare,stroke:{color:x.strokeColor??i,width:x.strokeWidth??ox,isDashed:x.strokeDashed??Vg,isRounded:x.strokeRounded??rx},plane:{color:x.planeColor??s},width:c,height:l,xPos:d,yPos:u,rotation:0}},ale=(e,t,o,r,n,a)=>{const i=Pi(Ie.LAST_SHAPE_LINE_COLOR,Ni),s=Pi(Ie.LAST_SHAPE_PLANE_COLOR,Ni),x=tx(n),{width:c,height:l,xPos:d,yPos:u}=Ug(r,x.aspectRatio,a);return{trackId:e,type:z.SHAPE,dimensionType:Tr.TWO,mediaId:t,zIndex:o,shapeType:od.DEFAULT,shapeSource:Ye.Triangle,stroke:{color:x.strokeColor??i,width:x.strokeWidth??ox,isDashed:x.strokeDashed??Vg,isRounded:x.strokeRounded??rx},plane:{color:x.planeColor??s},cornerRounding:x.cornerRounding??e3,width:c,height:l,xPos:d,yPos:u,rotation:0}},ile={[Ye.Line]:qce,[Ye.Arrow]:Zce,[Ye.DashedLine]:Qce,[Ye.DashedArrow]:$ce,[Ye.DoubleArrow]:ele,[Ye.Cross]:tle,[Ye.Square]:rle,[Ye.Deprecated_RoundedSquare]:nle,[Ye.Triangle]:ale,[Ye.Oval]:ole},jR=[{name:"asset-effect-fade-in",keyframes:`@keyframes asset-effect-fade-in {
154      from {
155        opacity: 0;
156      }
157      to {
158        opacity: 1;
159      }
160    }`},{name:"asset-effect-fade-in-down",keyframes:`@keyframes asset-effect-fade-in-down {
161      0% {
162        opacity: 0;
163        transform: translate3d(0, -100%, 0);
164      }
165      100% {
166        opacity: 1;
167        transform: translate3d(0, 0, 0);
168      }
169    }`},{name:"asset-effect-fade-in-left",keyframes:`@keyframes asset-effect-fade-in-left {
170      0% {
171        opacity: 0;
172        transform: translate3d(100%, 0, 0);
173      }
174      100% {
175        opacity: 1;
176        transform: translate3d(0, 0, 0);
177      }
178    }`},{name:"asset-effect-fade-in-right",keyframes:`@keyframes asset-effect-fade-in-right {
179      0% {
180        opacity: 0;
181        transform: translate3d(-100%, 0, 0);
182      }
183      100% {
184        opacity: 1;
185        transform: translate3d(0, 0, 0);
186      }
187    }`},{name:"asset-effect-fade-in-up",keyframes:`@keyframes asset-effect-fade-in-up {
188      0% {
189        opacity: 0;
190        transform: translate3d(0, 100%, 0);
191      }
192      100% {
193        opacity: 1;
194        transform: translate3d(0, 0, 0);
195      }
196    }`},{name:"asset-effect-fade-out",keyframes:`@keyframes asset-effect-fade-out {
197      from {
198        opacity: 1;
199      }
200      to {
201        opacity: 0;
202      }
203    }`},{name:"asset-effect-fade-out-down",keyframes:`@keyframes asset-effect-fade-out-down {
204      0% {
205        opacity: 1;
206        transform: translate3d(0, 0, 0);
207      }
208      100% {
209        opacity: 0;
210        transform: translate3d(0, 100%, 0);
211      }
212    }`},{name:"asset-effect-fade-out-left",keyframes:`@keyframes asset-effect-fade-out-left {
213      0% {
214        opacity: 1;
215        transform: translate3d(0, 0, 0);
216      }
217      100% {
218        opacity: 0;
219        transform: translate3d(-100%, 0, 0);
220      }
221    }`},{name:"asset-effect-fade-out-right",keyframes:`@keyframes asset-effect-fade-out-right {
222      0% {
223        opacity: 1;
224        transform: translate3d(0, 0, 0);
225      }
226      100% {
227        opacity: 0;
228        transform: translate3d(100%, 0, 0);
229      }
230    }`},{name:"asset-effect-fade-out-up",keyframes:`@keyframes asset-effect-fade-out-up {
231      0% {
232        opacity: 1;
233        transform: translate3d(0, 0, 0);
234      }
235      100% {
236        opacity: 0;
237        transform: translate3d(0, -100%, 0);
238      }
239    }`},{name:"asset-effect-fade-in-out",keyframes:`@keyframes asset-effect-fade-in-out {
240      0% {
241        opacity: 0;
242      }
243      20% {
244        opacity: 1;
245      }
246      80% {
247        opacity: 1;
248      }
249      100% {
250        opacity: 0;
251      }
252    }`},{name:"asset-effect-blink",keyframes:`@keyframes asset-effect-blink {
253      0% {
254        opacity: 1;
255      }
256      50% {
257        opacity: 0;
258      }
259      100% {
260        opacity: 1;
261      }
262    }`},{name:"asset-effect-rubber-band",keyframes:`@keyframes asset-effect-rubber-band {
263      0% {
264        transform: scale3d(1, 1, 1);
265      }
266      30% {
267        transform: scale3d(1.25, 0.75, 1);
268      }
269      40% {
270        transform: scale3d(0.75, 1.25, 1);
271      }
272      50% {
273        transform: scale3d(1.15, 0.85, 1);
274      }
275      65% {
276        transform: scale3d(0.95, 1.05, 1);
277      }
278      75% {
279        transform: scale3d(1.05, 0.95, 1);
280      }
281      100% {
282        transform: scale3d(1, 1, 1);
283      }
284    }`},{name:"asset-effect-pop-in",keyframes:`@keyframes asset-effect-pop-in {
285      0% {
286        opacity: 0;
287        transform: scale(0.1) rotate(30deg);
288        transform-origin: center bottom;
289      }
290      50% {
291        transform: rotate(-10deg);
292      }
293      70% {
294        transform: rotate(3deg);
295      }
296      100% {
297        opacity: 1;
298        transform: scale(1);
299      }
300    }`},{name:"asset-effect-tada",keyframes:`@keyframes asset-effect-tada {
301      0% {
302        transform: scale(1);
303      }
304      10%, 20% {
305        transform: scale(0.9) rotate(-3deg);
306      }
307      30%, 50%, 70%, 90% {
308        transform: scale(1.1) rotate(3deg);
309      }
310      40%, 60%, 80% {
311        transform: scale(1.1) rotate(-3deg);
312      }
313      100% {
314        transform: scale(1);
315      }
316    }`},{name:"asset-effect-shake-x",keyframes:`@keyframes asset-effect-shake-x {
317      0%, 100% {
318        transform: translate3d(0, 0, 0);
319      }
320      10%, 30%, 50%, 70%, 90% {
321        transform: translate3d(-10px, 0, 0);
322      }
323      20%, 40%, 60%, 80% {
324        transform: translate3d(10px, 0, 0);
325      }
326    }`},{name:"asset-effect-shake-y",keyframes:`@keyframes asset-effect-shake-y {
327      0%, 100% {
328        transform: translate3d(0, 0, 0);
329      }
330      10%, 30%, 50%, 70%, 90% {
331        transform: translate3d(0, -10px, 0);
332      }
333      20%, 40%, 60%, 80% {
334        transform: translate3d(0, 10px, 0);
335      }
336    }`},{name:"asset-effect-swing",keyframes:`@keyframes asset-effect-swing {
337      20% {
338        transform: rotate3d(0, 0, 1, 15deg);
339      }
340      40% {
341        transform: rotate3d(0, 0, 1, -10deg);
342      }
343      60% {
344        transform: rotate3d(0, 0, 1, 5deg);
345      }
346      80% {
347        transform: rotate3d(0, 0, 1, -5deg);
348      }
349      100% {
350        transform: rotate3d(0, 0, 1, 0deg);
351      }
352    }`},{name:"asset-effect-heart-beat",keyframes:`@keyframes asset-effect-heart-beat {
353      0%, 28%, 70% {
354        transform: scale(1);
355      }
356      14%, 42% {
357        transform: scale(1.5);
358      }
359    }`},{name:"asset-effect-flip",keyframes:`@keyframes asset-effect-flip {
360      0%,
361  100% {
362    transform: perspective(400px) scale3d(1, 1, 1) translate3d(0, 0, 0)
363      rotate3d(0, 1, 0, 0deg);
364    animation-timing-function: ease-in;
365  }
366  40% {
367    transform: perspective(400px) scale3d(1, 1, 1)
368      translate3d(0, 0, 150px) rotate3d(0, 1, 0, -190deg);
369    animation-timing-function: ease-out;
370  }
371  50% {
372    transform: perspective(400px) scale3d(1, 1, 1)
373      translate3d(0, 0, 150px) rotate3d(0, 1, 0, -170deg);
374    animation-timing-function: ease-in;
375  }
376  80% {
377    transform: perspective(400px) scale3d(0.95, 0.95, 0.95)
378      translate3d(0, 0, 0) rotate3d(0, 1, 0, 0deg);
379    animation-timing-function: ease-in;
380  }
381    }`},{name:"asset-effect-flip-in-x",keyframes:`@keyframes asset-effect-flip-in-x {
382      0% {
383        transform: perspective(400px) rotate3d(1, 0, 0, 90deg);
384        animation-timing-function: ease-in;
385        opacity: 0;
386      }
387      40% {
388        transform: perspective(400px) rotate3d(1, 0, 0, -20deg);
389        animation-timing-function: ease-in;
390      }
391      60% {
392        transform: perspective(400px) rotate3d(1, 0, 0, 10deg);
393        opacity: 1;
394      }
395      80% {
396        transform: perspective(400px) rotate3d(1, 0, 0, -5deg);
397      }
398      100% {
399        transform: perspective(400px);
400      }
401    }`},{name:"asset-effect-flip-in-y",keyframes:`@keyframes asset-effect-flip-in-y {
402      0% {
403        transform: perspective(400px) rotate3d(0, 1, 0, 90deg);
404        animation-timing-function: ease-in;
405        opacity: 0;
406      }
407      40% {
408        transform: perspective(400px) rotate3d(0, 1, 0, -20deg);
409        animation-timing-function: ease-in;
410      }
411      60% {
412        transform: perspective(400px) rotate3d(0, 1, 0, 10deg);
413        opacity: 1;
414      }
415      80% {
416        transform: perspective(400px) rotate3d(0, 1, 0, -5deg);
417      }
418      100% {
419        transform: perspective(400px);
420      }
421    }`},{name:"asset-effect-flip-out-x",keyframes:`@keyframes asset-effect-flip-out-x {
422      0% {
423        transform: perspective(400px);
424      }
425      30% {
426        transform: perspective(400px) rotate3d(1, 0, 0, -20deg);
427        opacity: 1;
428      }
429      100% {
430        transform: perspective(400px) rotate3d(1, 0, 0, 90deg);
431        opacity: 0;
432      }
433    }`},{name:"asset-effect-flip-out-y",keyframes:`@keyframes asset-effect-flip-out-y {
434      0% {
435        transform: perspective(400px);
436      }
437      30% {
438        transform: perspective(400px) rotate3d(0, 1, 0, -15deg);
439        opacity: 1;
440      }
441      100% {
442        transform: perspective(400px) rotate3d(0, 1, 0, 90deg);
443        opacity: 0;
444      }
445    }`},{name:"asset-effect-rotate-in",keyframes:`@keyframes asset-effect-rotate-in {
446      0% {
447        transform: rotate3d(0, 0, 1, -200deg);
448        opacity: 0;
449      }
450      100% {
451        transform: translate3d(0, 0, 0);
452        opacity: 1;
453      }
454    }`},{name:"asset-effect-rotate-in-down-left",keyframes:`@keyframes asset-effect-rotate-in-down-left {
455      0% {
456        transform: rotate3d(0, 0, 1, 45deg);
457        opacity: 0;
458      }
459      100% {
460        transform: translate3d(0, 0, 0);
461        opacity: 1;
462      }
463    }`},{name:"asset-effect-rotate-in-down-right",keyframes:`@keyframes asset-effect-rotate-in-down-right {
464      0% {
465        transform: rotate3d(0, 0, 1, -45deg);
466        opacity: 0;
467      }
468      100% {
469        transform: translate3d(0, 0, 0);
470        opacity: 1;
471      }
472    }`},{name:"asset-effect-rotate-out",keyframes:`@keyframes asset-effect-rotate-out {
473      0% {
474        opacity: 1;
475      }
476      100% {
477        transform: rotate3d(0, 0, 1, 200deg);
478        opacity: 0;
479      }
480    }`},{name:"asset-effect-rotate-out-down-left",keyframes:`@keyframes asset-effect-rotate-out-down-left {
481      0% {
482        opacity: 1;
483      }
484      100% {
485        transform: rotate3d(0, 0, 1, -45deg);
486        opacity: 0;
487      }
488    }`},{name:"asset-effect-rotate-out-down-right",keyframes:`@keyframes asset-effect-rotate-out-down-right {
489      0% {
490        opacity: 1;
491      }
492      100% {
493        transform: rotate3d(0, 0, 1, 45deg);
494        opacity: 0;
495      }
496    }`},{name:"asset-effect-roll-in",keyframes:`@keyframes asset-effect-roll-in {
497      0% {
498        opacity: 0;
499        transform: translate3d(-100%, 0, 0) rotate3d(0, 0, 1, -120deg);
500      }
501      100% {
502        opacity: 1;
503        transform: translate3d(0, 0, 0);
504      }
505    }`},{name:"asset-effect-roll-out",keyframes:`@keyframes asset-effect-roll-out {
506      0% {
507        opacity: 1;
508      }
509      100% {
510        opacity: 0;
511        transform: translate3d(100%, 0, 0) rotate3d(0, 0, 1, 120deg);
512      }
513    }`},{name:"asset-effect-focus-in",keyframes:`@keyframes asset-effect-focus-in {
514      0% {
515        opacity: 0;
516        transform: scale3d(0.3, 0.3, 0.3);
517      }
518      50% {
519        opacity: 1;
520      }
521      100% {
522        opacity: 1;
523        transform: scale3d(1, 1, 1);
524      }
525    }`},{name:"asset-effect-focus-in-down",keyframes:`@keyframes asset-effect-focus-in-down {
526      0% {
527        opacity: 0;
528        transform: scale3d(0.1, 0.1, 0.1) translate3d(0, -1000px, 0);
529        animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19);
530      }
531      60% {
532        opacity: 1;
533        transform: scale3d(0.475, 0.475, 0.475) translate3d(0, 60px, 0);
534        animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1);
535      }
536      100% {
537        opacity: 1;
538        transform: scale3d(1, 1, 1) translate3d(0, 0, 0);
539      }
540    }`},{name:"asset-effect-focus-in-left",keyframes:`@keyframes asset-effect-focus-in-left {
541      0% {
542        opacity: 0;
543        transform: scale3d(0.1, 0.1, 0.1) translate3d(1000px, 0, 0);
544        animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19);
545      }
546      60% {
547        opacity: 1;
548        transform: scale3d(0.475, 0.475, 0.475) translate3d(-10px, 0, 0);
549        animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1);
550      }
551      100% {
552        opacity: 1;
553        transform: scale3d(1, 1, 1) translate3d(0, 0, 0);
554      }
555    }`},{name:"asset-effect-focus-in-right",keyframes:`@keyframes asset-effect-focus-in-right {
556      0% {
557        opacity: 0;
558        transform: scale3d(0.1, 0.1, 0.1) translate3d(-1000px, 0, 0);
559        animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19);
560      }
561      60% {
562        opacity: 1;
563        transform: scale3d(0.475, 0.475, 0.475) translate3d(10px, 0, 0);
564        animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1);
565      }
566      100% {
567        opacity: 1;
568        transform: scale3d(1, 1, 1) translate3d(0, 0, 0);
569      }
570    }`},{name:"asset-effect-focus-in-up",keyframes:`@keyframes asset-effect-focus-in-up {
571      0% {
572        opacity: 0;
573        transform: scale3d(0.1, 0.1, 0.1) translate3d(0, 1000px, 0);
574        animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19);
575      }
576      60% {
577        opacity: 1;
578        transform: scale3d(0.475, 0.475, 0.475) translate3d(0, -60px, 0);
579        animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1);
580      }
581      100% {
582        opacity: 1;
583        transform: scale3d(1, 1, 1) translate3d(0, 0, 0);
584      }
585    }`},{name:"asset-effect-focus-out",keyframes:`@keyframes asset-effect-focus-out {
586      0% {
587        opacity: 1;
588      }
589      50% {
590        opacity: 0;
591        transform: scale3d(0.3, 0.3, 0.3);
592      }
593      100% {
594        opacity: 0;
595      }
596    }`},{name:"asset-effect-focus-out-down",keyframes:`@keyframes asset-effect-focus-out-down {
597      40% {
598        opacity: 1;
599        transform: scale3d(0.475, 0.475, 0.475) translate3d(0, -60px, 0);
600        animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19);
601      }
602      100% {
603        opacity: 0;
604        transform: scale3d(0.1, 0.1, 0.1) translate3d(0, 2000px, 0);
605        animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1);
606      }
607    }`},{name:"asset-effect-focus-out-left",keyframes:`@keyframes asset-effect-focus-out-left {
608      40% {
609        opacity: 1;
610        transform: scale3d(0.475, 0.475, 0.475) translate3d(42px, 0, 0);
611      }
612      100% {
613        opacity: 0;
614        transform: scale(0.1) translate3d(-2000px, 0, 0);
615      }
616    }`},{name:"asset-effect-focus-out-right",keyframes:`@keyframes asset-effect-focus-out-right {
617      40% {
618        opacity: 1;
619        transform: scale3d(0.475, 0.475, 0.475) translate3d(-42px, 0, 0);
620      }
621      100% {
622        opacity: 0;
623        transform: scale(0.1) translate3d(2000px, 0, 0);
624      }
625    }`},{name:"asset-effect-focus-out-up",keyframes:`@keyframes asset-effect-focus-out-up {
626      40% {
627        opacity: 1;
628        transform: scale3d(0.475, 0.475, 0.475) translate3d(0, 60px, 0);
629        animation-timing-function: cubic-bezier(0.55, 0.055, 0.675, 0.19);
630      }
631      100% {
632        opacity: 0;
633        transform: scale3d(0.1, 0.1, 0.1) translate3d(0, -2000px, 0);
634        animation-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1);
635      }
636    }`},{name:"asset-effect-slide-in-right",keyframes:`@keyframes asset-effect-slide-in-right {
637      0% {
638        transform: translate3d(-100%, 0, 0) skewX(30deg);
639        opacity: 0;
640      }
641      60% {
642        transform: translate3d(-50%, 0, 0) skewX(-20deg);
643        opacity: 0.6;
644      }
645      80% {
646        transform: translate3d(-20%, 0, 0) skewX(5deg);
647        opacity: 0.9;
648      }
649      100% {
650        transform: translate3d(0, 0, 0) skewX(0deg);
651        opacity: 1;
652      }
653    }`},{name:"asset-effect-slide-in-left",keyframes:`@keyframes asset-effect-slide-in-left {
654      0% {
655        transform: translate3d(100%, 0, 0) skewX(-30deg);
656        opacity: 0;
657      }
658      60% {
659        transform: translate3d(50%, 0, 0) skewX(20deg);
660        opacity: 0.5;
661      }
662      80% {
663        transform: translate3d(20%, 0, 0) skewX(-5deg);
664        opacity: 0.8;
665      }
666      100% {
667        transform: translate3d(0, 0, 0) skewX(0deg);
668        opacity: 1;
669      }
670    }`},{name:"asset-effect-slide-out-left",keyframes:`@keyframes asset-effect-slide-out-left {
671      0% {
672        transform: translate3d(0, 0, 0) skewX(0deg);
673        opacity: 1;
674      }
675      20% {
676        transform: translate3d(-20%, 0, 0) skewX(5deg);
677        opacity: 0.9;
678      }
679      40% {
680        transform: translate3d(-50%, 0, 0) skewX(-20deg);
681        opacity: 0.6;
682      }
683      100% {
684        transform: translate3d(-100%, 0, 0) skewX(30deg);
685        opacity: 0;
686      }
687    }`},{name:"asset-effect-slide-out-right",keyframes:`@keyframes asset-effect-slide-out-right {
688      0% {
689        transform: translate3d(0, 0, 0) skewX(0deg);
690        opacity: 1;
691      }
692      20% {
693        transform: translate3d(20%, 0, 0) skewX(-5deg);
694        opacity: 0.9;
695      }
696      40% {
697        transform: translate3d(50%, 0, 0) skewX(20deg);
698        opacity: 0.6;
699      }
700      100% {
701        transform: translate3d(100%, 0, 0) skewX(-30deg);
702        opacity: 0;
703      }
704    }`},{name:"asset-effect-moving-in-up",keyframes:`@keyframes asset-effect-moving-in-up {
705      0% {
706        transform: translate3d(0, 100vh, 0);
707        opacity: 1;
708      }
709      100% {
710        transform: translate3d(0, 0, 0);
711        opacity: 1;
712      }
713    }`},{name:"asset-effect-moving-in-down",keyframes:`@keyframes asset-effect-moving-in-down {
714      0% {
715        transform: translate3d(0, -100vh, 0);
716        opacity: 1;
717      }
718      100% {
719        transform: translate3d(0, 0, 0);
720        opacity: 1;
721      }
722    }`},{name:"asset-effect-moving-in-left",keyframes:`@keyframes asset-effect-moving-in-left {
723      0% {
724        transform: translate3d(100vw, 0, 0);
725        opacity: 1;
726      }
727      100% {
728        transform: translate3d(0, 0, 0);
729        opacity: 1;
730      }
731    }`},{name:"asset-effect-moving-in-right",keyframes:`@keyframes asset-effect-moving-in-right {
732      0% {
733        transform: translate3d(-100vw, 0, 0);
734        opacity: 1;
735      }
736      100% {
737        transform: translate3d(0, 0, 0);
738        opacity: 1;
739      }
740    }`},{name:"asset-effect-moving-out-up",keyframes:`@keyframes asset-effect-moving-out-up {
741      0% {
742        transform: translate3d(0, 0, 0);
743        opacity: 1;
744      }
745      100% {
746        transform: translate3d(0, -100vh, 0);
747        opacity: 1;
748      }
749    }`},{name:"asset-effect-moving-out-down",keyframes:`@keyframes asset-effect-moving-out-down {
750      0% {
751        transform: translate3d(0, 0, 0);
752        opacity: 1;
753      }
754      100% {
755        transform: translate3d(0, 100vh, 0);
756        opacity: 1;
757      }
758    }`},{name:"asset-effect-moving-out-left",keyframes:`@keyframes asset-effect-moving-out-left {
759      0% {
760        transform: translate3d(0, 0, 0);
761        opacity: 1;
762      }
763      100% {
764        transform: translate3d(-100vw, 0, 0);
765        opacity: 1;
766      }
767    }`},{name:"asset-effect-moving-out-right",keyframes:`@keyframes asset-effect-moving-out-right {
768      0% {
769        transform: translate3d(0, 0, 0);
770        opacity: 1;
771      }
772      100% {
773        transform: translate3d(100vw, 0, 0);
774        opacity: 1;
775      }
776    }`},{name:"asset-effect-popping",keyframes:`@keyframes asset-effect-popping {
777      0% {
778        opacity: 0;
779        transform: scale3d(0.3, 0.3, 0.3);
780      }
781      20% {
782        opacity: 1;
783        transform: scale3d(1.1, 1.1, 1.1);
784      }
785    }`},{name:"asset-effect-popping-in",keyframes:`@keyframes asset-effect-popping-in {
786      0% {
787        opacity: 0;
788        transform: scale3d(0.3, 0.3, 0.3);
789      }
790      20% {
791        transform: scale3d(1.1, 1.1, 1.1);
792      }
793      40% {
794        transform: scale3d(0.9, 0.9, 0.9);
795      }
796      60% {
797        opacity: 1;
798        transform: scale3d(1.03, 1.03, 1.03);
799      }
800      80% {
801        transform: scale3d(0.97, 0.97, 0.97);
802      }
803      to {
804        opacity: 1;
805        transform: scale3d(1, 1, 1);
806      }
807    }`},{name:"asset-effect-popping-in-down",keyframes:`@keyframes asset-effect-popping-in-down {
808      0% {
809        opacity: 0;
810        transform: translate3d(0, -3000px, 0) scaleY(3);
811      }
812      40% {
813        opacity: 1;
814        transform: translate3d(0, 25px, 0) scaleY(0.9);
815      }
816      65% {
817        transform: translate3d(0, -10px, 0) scaleY(0.95);
818      }
819      80% {
820        transform: translate3d(0, 5px, 0) scaleY(0.985);
821      }
822    }`},{name:"asset-effect-popping-in-right",keyframes:`@keyframes asset-effect-popping-in-right {
823        0% {
824          opacity: 0;
825          transform: translate3d(-3000px, 0, 0) scaleX(3);
826        }
827        60% {
828          opacity: 1;
829          transform: translate3d(25px, 0, 0) scaleX(1);
830        }
831        75% {
832          transform: translate3d(-10px, 0, 0) scaleX(0.98);
833        }
834        90% {
835          transform: translate3d(5px, 0, 0) scaleX(0.995);
836        }
837        to {
838          transform: translate3d(0, 0, 0);
839        }
840    }`},{name:"asset-effect-popping-in-left",keyframes:`@keyframes asset-effect-popping-in-left {
841      from {
842        opacity: 0;
843        transform: translate3d(3000px, 0, 0) scaleX(3);
844      }
845      60% {
846        opacity: 1;
847        transform: translate3d(-25px, 0, 0) scaleX(1);
848      }
849      75% {
850        transform: translate3d(10px, 0, 0) scaleX(0.98);
851      }
852      90% {
853        -webkit-transform: translate3d(-5px, 0, 0) scaleX(0.995);
854        transform: translate3d(-5px, 0, 0) scaleX(0.995);
855      }
856      to {
857        -webkit-transform: translate3d(0, 0, 0);
858        transform: translate3d(0, 0, 0);
859      }
860    }`},{name:"asset-effect-popping-in-up",keyframes:`@keyframes asset-effect-popping-in-up {
861      from {
862        opacity: 0;
863        transform: translate3d(0, 3000px, 0) scaleY(5);
864      }
865      60% {
866        opacity: 1;
867        transform: translate3d(0, -20px, 0) scaleY(0.9);
868      }
869      75% {
870        transform: translate3d(0, 10px, 0) scaleY(0.95);
871      }
872      90% {
873        transform: translate3d(0, -5px, 0) scaleY(0.985);
874      }
875      to {
876        transform: translate3d(0, 0, 0);
877      }
878    }`},{name:"asset-effect-popping-out",keyframes:`@keyframes asset-effect-popping-out {
879      20% {
880        transform: scale3d(0.9, 0.9, 0.9);
881      }
882      50%,
883      55% {
884        opacity: 1;
885        transform: scale3d(1.1, 1.1, 1.1);
886      }
887      to {
888        opacity: 0;
889        transform: scale3d(0.3, 0.3, 0.3);
890      }
891    }`},{name:"asset-effect-popping-out-down",keyframes:`@keyframes asset-effect-popping-out-down {
892      20% {
893        transform: translate3d(0, 10px, 0) scaleY(0.985);
894      }
895      40%,
896      45% {
897        opacity: 1;
898        transform: translate3d(0, -20px, 0) scaleY(0.9);
899      }
900      to {
901        opacity: 0;
902        transform: translate3d(0, 2000px, 0) scaleY(3);
903      }
904    }`},{name:"asset-effect-popping-out-left",keyframes:`@keyframes asset-effect-popping-out-left {
905      20% {
906        opacity: 1;
907        transform: translate3d(20px, 0, 0) scaleX(0.9);
908      }
909      to {
910        opacity: 0;
911        transform: translate3d(-2000px, 0, 0) scaleX(2);
912      }
913    }`},{name:"asset-effect-popping-out-right",keyframes:`@keyframes asset-effect-popping-out-right {
914      20% {
915        opacity: 1;
916        transform: translate3d(-20px, 0, 0) scaleX(0.9);
917      }
918      to {
919        opacity: 0;
920        transform: translate3d(2000px, 0, 0) scaleX(2);
921      }
922    }`},{name:"asset-effect-popping-out-up",keyframes:`@keyframes asset-effect-popping-out-up {
923      20% {
924        transform: translate3d(0, -10px, 0) scaleY(0.985);
925      }
926      40%,
927      45% {
928        opacity: 1;
929        transform: translate3d(0, 20px, 0) scaleY(0.9);
930      }
931      to {
932        opacity: 0;
933        transform: translate3d(0, -2000px, 0) scaleY(3);
934      }
935    }`},{name:"asset-effect-typing",keyframes:`@keyframes asset-effect-typing {
936      0% {
937        opacity: 1;
938      }
939      100% {
940        opacity: 1;
941      }
942    }
943    `},{name:"asset-effect-typing-down",keyframes:`@keyframes asset-effect-typing-down {
944      0% {
945        left: 0;
946        top: -10px;
947        opacity: 1;
948      }
949      100% {
950        left: 0;
951        top: 0;
952        opacity: 1;
953      }
954    }
955    `},{name:"asset-effect-typing-up",keyframes:`@keyframes asset-effect-typing-up {
956      0% {
957        left: 0;
958        top: 10px;
959        opacity: 1;
960      }
961      100% {
962        left: 0;
963        top: 0;
964        opacity: 1;
965      }
966    }
967    `}],vI=e=>{const t=[Ir.ZOOM_OUT,Ir.ZOOM_IN,Ir.LEFT_TO_RIGHT,Ir.RIGHT_TO_LEFT,Ir.TOP_TO_BOTTOM,Ir.BOTTOM_TO_TOP,Ir.MAGIC_SQUARE,Ir.MAGIC_HORIZONTAL],o=e?t.filter(n=>!e.includes(n)):t,r=Math.floor(Math.random()*o.length);return o[r]},wI=(e,t,o,r)=>{const n=r??{small:.77,middle:.7,big:.63,center:.5,padding:.08},{small:a,middle:i,big:s,center:x,padding:c}=n,l=t/(o||1),{left:d,right:u,top:p,bottom:f}=dle(i,l,c);switch(e){case Ir.ZOOM_OUT:return{from:{scale:s,centerX:x,centerY:x},to:{scale:a,centerX:x,centerY:x}};case Ir.ZOOM_IN:case Ir.MAGIC_SQUARE:return{from:{scale:a,centerX:x,centerY:x},to:{scale:s,centerX:x,centerY:x}};case Ir.LEFT_TO_RIGHT:return{from:{scale:i,centerX:d,centerY:x},to:{scale:i,centerX:u,centerY:x}};case Ir.TOP_TO_BOTTOM:case Ir.MAGIC_VERTICAL:return{from:{scale:i,centerX:x,centerY:p},to:{scale:i,centerX:x,centerY:f}};case Ir.RIGHT_TO_LEFT:case Ir.MAGIC_HORIZONTAL:return{from:{scale:i,centerX:u,centerY:x},to:{scale:i,centerX:d,centerY:x}};case Ir.BOTTOM_TO_TOP:return{from:{scale:i,centerX:x,centerY:f},to:{scale:i,centerX:x,centerY:p}};default:return{from:{scale:i,centerX:x,centerY:x},to:{scale:i,centerX:x,centerY:x}}}},sle={scale:.5,centerX:.5,centerY:.5},eM=(e,t,o,r)=>{if(e.eq(Pr.zero()))return sle;const n=t.as.sec()/e.as.sec(),a=o.scale+(r.scale-o.scale)*n,i=o.centerX+(r.centerX-o.centerX)*n,s=o.centerY+(r.centerY-o.centerY)*n;return{scale:a,centerX:i,centerY:s}},t3=.3,Pm=1,IO={topLeftPos:{x:0,y:0},scale:{w:1,h:1}},o3=e=>{const{xPos:t,yPos:o,width:r,height:n}=e;if(![t,o,r,n].every(Number.isFinite)||r<=0||n<=0)return IO;const a=Math.max(t,0),i=Math.max(o,0),s=Math.min(t+r,1),x=Math.min(o+n,1),c=s-a,l=x-i;return c<=0||l<=0||a===t&&i===o&&s===t+r&&x===o+n?IO:{topLeftPos:{x:t-a,y:o-i},scale:{w:c/r,h:l/n}}},xle=e=>{const{scale:t}=o3(e),o=1/Math.max(t.w,t.h);return Number.isFinite(o)&&o>Pm?o:Pm},cle=(e,t)=>
967{const o=xle(e),r=$t(Number.isFinite(t)?t:Pm,t3,o),n=o3(e),a=e.width>0&&Number.isFinite(e.width)?n.topLeftPos.x/e.width:0,i=e.height>0&&Number.isFinite(e.height)?n.topLeftPos.y/e.height:0;return{maxScale:o,minCenterX:r/2+a*r,maxCenterX:1+r*(.5+a-n.scale.w),minCenterY:r/2+i*r,maxCenterY:1+r*(.5+i-n.scale.h)}},lle=(e,t,o)=>{const r=n=>{const a=cle(o,n.scale);return{scale:$t(Number.isFinite(n.scale)?n.scale:Pm,t3,a.maxScale),centerX:$t(Number.isFinite(n.centerX)?n.centerX:.5,a.minCenterX,a.maxCenterX),centerY:$t(Number.isFinite(n.centerY)?n.centerY:.5,a.minCenterY,a.maxCenterY)}};return{from:r(e),to:r(t)}},dle=(e,t,o=.5)=>{const r=t<1,n=Math.max(r?e/2:e/2/t,.5-o),a=1-n,i=Math.max(r?e/2*t:e/2,.5-o),s=1-i;return{left:n,right:a,top:i,bottom:s}},Jtt=e=>{const t=XG.find(o=>o.type===e)?.preset;return!e||!t?"context.image_asset_effects":n3[t]},ule=(e,t,o,r,n,a)=>{if(o<0)return"-0s";if(as(e))return n?"-0s":"-"+ue(o%Ua(a),3)+"s";if(El(e))return"-"+o+"s";if(W0(e)&&t)return"-"+r+"s";if(Jr(e))return t?"-"+r+"s":"-"+o+"s"},ple=e=>!e||!ax(e)?0:e.startDelay/1e3,qtt=(e,t,o,r,n,a,i,s)=>{const x=ple(r.assetEffectInfo);if(!r.assetEffectInfo||nx(r.assetEffectInfo.type))return{};const c=r.assetEffectInfo.type,l=i3(r.assetEffectInfo,Iu(pe(ue(t-e,2))));if(l.duration===0)return{};const d=Ua(l.duration)/(Jr(c)?2:1),u=0,p=o-(e+x),f=o-(t-d),E=f>=u;if(i&&!W0(c)&&!Jr(c)||!n&&a)return{};const O=ule(r.assetEffectInfo?.type,E,p,f,n,l.duration);if(O===void 0)return{};const S=bI(c).styleObject,R=n&&(x<=0||s===!0)?"running":"paused";return{...S,animationPlayState:R,animationDelay:O,animationFillMode:"forwards",animationName:R2(c,E),animationDuration:Ua(l.duration)+"s",animationIterationCount:as(c)?"infinite":"1",...i&&W0(c)&&Jr(c)?{opacity:0}:{}}},nx=e=>Eo(Mc).isValue(e),El=e=>Eo(Me).isValue(e),W0=e=>Eo(Qe).isValue(e),ax=e=>!W0(e.type),Jr=e=>Eo(rI).isValue(e),as=e=>Eo(hr).isValue(e),NI=e=>Eo(Ir).isValue(e),fle=e=>NI(e)?!1:El(e)||W0(e)||Jr(e)||as(e)||nx(e),Qtt=e=>NI(e)?!1:!W0(e),Ztt=e=>e&&"duration"in e&&typeof e.duration=="number",PI=e=>Eo(KG).isValue(e.type),$tt=e=>!xr(e)||!PI(e)?!1:e.assetEffectInfo!==void 0?!0:"kenburnsAnimationInfo"in e&&e.kenburnsAnimationInfo!==void 0,R2=(e,t=!1)=>{if(e===void 0)return"";switch(e){case Me.FADE_IN:return"asset-effect-fade-in";case Me.FADE_IN_DOWN:return"asset-effect-fade-in-down";case Me.FADE_IN_LEFT:return"asset-effect-fade-in-left";case Me.FADE_IN_RIGHT:return"asset-effect-fade-in-right";case Me.FADE_IN_UP:return"asset-effect-fade-in-up";case Qe.FADE_OUT:return"asset-effect-fade-out";case Qe.FADE_OUT_DOWN:return"asset-effect-fade-out-down";case Qe.FADE_OUT_LEFT:return"asset-effect-fade-out-left";case Qe.FADE_OUT_RIGHT:return"asset-effect-fade-out-right";case Qe.FADE_OUT_UP:return"asset-effect-fade-out-up";case rI.FADE_IN_OUT:return t?"asset-effect-fade-out":"asset-effect-fade-in";case Me.BLINK_ONCE:case hr.BLINK:return"asset-effect-blink";case Me.RUBBER_BAND_ONCE:case hr.RUBBER_BAND:return"asset-effect-rubber-band";case hr.POP_IN:case Me.POP_IN_ONCE:return"asset-effect-pop-in";case hr.TADA:case Me.TADA_ONCE:return"asset-effect-tada";case hr.SHAKE_X:case Me.SHAKE_X_ONCE:return"asset-effect-shake-x";case hr.SHAKE_Y:case Me.SHAKE_Y_ONCE:return"asset-effect-shake-y";case hr.SWING:case Me.SWING_ONCE:return"asset-effect-swing";case hr.HEART_BEAT:case Me.HEART_BEAT_ONCE:return"asset-effect-heart-beat";case hr.FLIP:case Me.FLIP_ONCE:return"asset-effect-flip";case Me.FLIP_IN_X:return"asset-effect-flip-in-x";case Me.FLIP_IN_Y:return"asset-effect-flip-in-y";case Qe.FLIP_OUT_X:return"asset-effect-flip-out-x";case Qe.FLIP_OUT_Y:return"asset-effect-flip-out-y";case Me.SLIDE_IN_RIGHT:return"asset-effect-slide-in-right";case Me.SLIDE_IN_LEFT:return"asset-effect-slide-in-left";case Qe.SLIDE_OUT_LEFT:return"asset-effect-slide-out-left";case Qe.SLIDE_OUT_RIGHT:return"asset-effect-slide-out-right";case Me.MOVING_IN_UP:return"asset-effect-moving-in-up";case Me.MOVING_IN_DOWN:return"asset-effect-moving-in-down";case Me.MOVING_IN_LEFT:return"asset-effect-moving-in-left";case Me.MOVING_IN_RIGHT:return"asset-effect-moving-in-right";case Qe.MOVING_OUT_UP:return"asset-effect-moving-out-up";case Qe.MOVING_OUT_DOWN:return"asset-effect-moving-out-down";
967case Qe.MOVING_OUT_LEFT:return"asset-effect-moving-out-left";case Qe.MOVING_OUT_RIGHT:return"asset-effect-moving-out-right";case Me.ROTATE_IN:return"asset-effect-rotate-in";case Me.ROTATE_IN_DOWN_LEFT:return"asset-effect-rotate-in-down-left";case Me.ROTATE_IN_DOWN_RIGHT:return"asset-effect-rotate-in-down-right";case Qe.ROTATE_OUT:return"asset-effect-rotate-out";case Qe.ROTATE_OUT_DOWN_LEFT:return"asset-effect-rotate-out-down-left";case Qe.ROTATE_OUT_DOWN_RIGHT:return"asset-effect-rotate-out-down-right";case Me.ROLL_IN:return"asset-effect-roll-in";case Qe.ROLL_OUT:return"asset-effect-roll-out";case Me.FOCUS_IN:return"asset-effect-focus-in";case Me.FOCUS_IN_DOWN:return"asset-effect-focus-in-down";case Me.FOCUS_IN_LEFT:return"asset-effect-focus-in-left";case Me.FOCUS_IN_RIGHT:return"asset-effect-focus-in-right";case Me.FOCUS_IN_UP:return"asset-effect-focus-in-up";case Qe.FOCUS_OUT:return"asset-effect-focus-out";case Qe.FOCUS_OUT_DOWN:return"asset-effect-focus-out-down";case Qe.FOCUS_OUT_LEFT:return"asset-effect-focus-out-left";case Qe.FOCUS_OUT_RIGHT:return"asset-effect-focus-out-right";case Qe.FOCUS_OUT_UP:return"asset-effect-focus-out-up";case hr.POPPING:case Me.POPPING_ONCE:return"asset-effect-popping";case Me.POPPING_IN:return"asset-effect-popping-in";case Me.POPPING_IN_DOWN:return"asset-effect-popping-in-down";case Me.POPPING_IN_LEFT:return"asset-effect-popping-in-left";case Me.POPPING_IN_RIGHT:return"asset-effect-popping-in-right";case Me.POPPING_IN_UP:return"asset-effect-popping-in-up";case Qe.POPPING_OUT:return"asset-effect-popping-out";case Qe.POPPING_OUT_DOWN:return"asset-effect-popping-out-down";case Qe.POPPING_OUT_LEFT:return"asset-effect-popping-out-left";case Qe.POPPING_OUT_RIGHT:return"asset-effect-popping-out-right";case Qe.POPPING_OUT_UP:return"asset-effect-popping-out-up";case Mc.TYPING:return"asset-effect-typing";case Mc.TYPING_UP:return"asset-effect-typing-up";case Mc.TYPING_DOWN:return"asset-effect-typing-down";default:return""}},bI=e=>{switch(e){case hr.HEART_BEAT:case Me.HEART_BEAT_ONCE:return{styleObject:{animationTimingFunction:"ease-in-out"},styleText:"animation-timing-function: ease-in-out"};case Me.SLIDE_IN_RIGHT:case Me.SLIDE_IN_LEFT:return{styleObject:{animationTimingFunction:"ease-out"},styleText:"animation-timing-function: ease-out"};case Qe.SLIDE_OUT_LEFT:case Qe.SLIDE_OUT_RIGHT:return{styleObject:{animationTimingFunction:"ease-in"},styleText:"animation-timing-function: ease-in"};case Me.MOVING_IN_UP:case Me.MOVING_IN_DOWN:case Me.MOVING_IN_LEFT:case Me.MOVING_IN_RIGHT:return{styleObject:{animationTimingFunction:"cubic-bezier(0,.4,.15,1)"},styleText:"animation-timing-function:cubic-bezier(0,.4,.15,1)"};case Qe.MOVING_OUT_UP:case Qe.MOVING_OUT_DOWN:case Qe.MOVING_OUT_LEFT:case Qe.MOVING_OUT_RIGHT:return{styleObject:{animationTimingFunction:"cubic-bezier(.4,0,1,.15)"},styleText:"animation-timing-function: cubic-bezier(.4,0,1,.15)"};case hr.FLIP:case Me.FLIP_ONCE:return{styleObject:{backfaceVisibility:"visible"},styleText:"backface-visibility: visible"};case Me.FLIP_IN_X:case Me.FLIP_IN_Y:case Qe.FLIP_OUT_X:case Qe.FLIP_OUT_Y:return{styleObject:{backfaceVisibility:"visible !important"},styleText:"backface-visibility: visible !important"};case hr.SWING:case Me.SWING_ONCE:return{styleObject:{transformOrigin:"top center"},styleText:"transform-origin: top center"};case Me.ROTATE_IN:case Qe.ROTATE_OUT:return{styleObject:{transformOrigin:"center"},styleText:"transform-origin: center"};case Me.ROTATE_IN_DOWN_LEFT:case Qe.ROTATE_OUT_DOWN_LEFT:return{styleObject:{transformOrigin:"left bottom"},styleText:"transform-origin: left bottom"};case Me.ROTATE_IN_DOWN_RIGHT:case Qe.ROTATE_OUT_DOWN_RIGHT:return{styleObject:{transformOrigin:"right bottom"},styleText:"transform-origin: right bottom"};case Qe.FOCUS_OUT_DOWN:case Qe.FOCUS_OUT_UP:return{styleObject:{transformOrigin:"center bottom"},styleText:"transform-origin: center bottom"};case Qe.FOCUS_OUT_LEFT:return{styleObject:{transformOrigin:"left center"},styleText:"transform-origin: left center"};case Qe.FOCUS_OUT_RIGHT:return{styleObject:{transformOrigin:"right center"},styleText:"transform-origin: right center"};default:return{styleObject:{},styleText:""}}},eot=()=>
967{jR.forEach((t,o)=>{const r=Math.floor(o/25)+1;if(o%25===0){const n=jR.slice(o,o+25).map(i=>xRe(i.keyframes)),a=document.createElement("style");a.id="animation-"+r,a.innerHTML=n.join(`
968`),document.head.appendChild(a)}})},LI=e=>{const t=jR.find(o=>o.name===e);return t?t.keyframes:""},r3=e=>{if(e.type===Ce.IMAGE||e.type===Ce.WEB||e.type===Ce.SHAPE){const{uniqueId:t,assetId:o}=e.animationExportInfo??{},r=t??o;return e.asset.mediaId+"-"+r}if(e.type===Ce.CAPTION){const t=_a(e),{uniqueId:o,assetId:r}=t.animationExportInfo??{},n=o??r;return e.asset.mediaId+"-"+n}return""+e.asset.mediaId},tot=e=>e===void 0?A("asset_animations.preset_none"):A(n3[e]),oot=e=>gle[e],rot=e=>_le[e],n3={[ao.FADE]:"asset_animations.preset_fade",[ao.FLIP]:"asset_animations.preset_flip",[ao.FLIP_HIGHLIGHT]:"asset_animations.preset_flip",[ao.FOCUS]:"asset_animations.preset_focus",[ao.FLY]:"asset_animations.preset_slide",[ao.ROTATE]:"asset_animations.preset_rotate",[ao.ROLL]:"asset_animations.preset_roll",[ao.ZOOM_IN]:"asset_animations.preset_zoom_in",[ao.ZOOM_DIRECTION]:"asset_animations.preset_zoom_direction",[ao.ZOOM_CUSTOM]:"asset_animations.preset_zoom_custom",[ao.TADA]:"asset_animations.preset_tada",[ao.SHAKE]:"asset_animations.preset_shake",[ao.SWING]:"asset_animations.preset_swing",[ao.RUBBER_BAND]:"asset_animations.preset_rubber_band",[ao.HEART_BEAT]:"asset_animations.preset_heart_beat",[ao.POP_IN]:"asset_animations.preset_pop_in",[ao.BLINK]:"asset_animations.preset_blink",[ao.POPPING]:"asset_animations.preset_popping",[ao.POPPING_HIGHLIGHT]:"asset_animations.preset_popping",[ao.TYPING]:"asset_animations.preset_typing",[ao.MOVING]:"asset_animations.preset_moving"},gle={[Jp.IN]:"asset_animations.option_timing_in",[Jp.OUT]:"asset_animations.option_timing_out",[Jp.INOUT]:"asset_animations.option_timing_in_out",[Cm.ONCE]:"asset_animations.option_interval_once",[Cm.LOOP]:"asset_animations.option_interval_loop"},_le={[Pl.NONE]:Dse,[Pl.LEFT]:Mse,[Pl.RIGHT]:kse,[Pl.UP]:Fse,[Pl.DOWN]:Lse},qv=(e,t)=>{const o=XG.find(n=>n.type===e)?.preset,r={...t};switch(o){case ao.FADE:r.fadeCount++;break;case ao.FLIP:r.flipCount++;break;case ao.FLIP_HIGHLIGHT:r.flipHighlightCount++;break;case ao.FLY:r.flyCount++;break;case ao.ROTATE:r.rotateCount++;break;case ao.ROLL:r.rollCount++;break;case ao.FOCUS:r.focusCount++;break;case ao.TADA:r.tadaCount++;break;case ao.SWING:r.swingCount++;break;case ao.SHAKE:r.shakeCount++;break;case ao.RUBBER_BAND:r.rubberBandCount++;break;case ao.HEART_BEAT:r.heartBeatCount++;break;case ao.POP_IN:r.popInCount++;break;case ao.BLINK:r.blinkCount++;break;case ao.POPPING:r.popCount++;break;case ao.TYPING:r.typingCount++;break;case ao.MOVING:r.movingCount++;break}return r},tM=e=>!!(e.type===Ce.IMAGE&&e.animationExportInfo?.isDynamicInPiece)||!!(e.type===Ce.WEB&&e.animationExportInfo.isDynamicInPiece)||!!(e.type===Ce.SHAPE&&e.animationExportInfo?.isDynamicInPiece),Ele=e=>e.type===Ce.IMAGE&&e.animationExportInfo?.animationInfo!==void 0||!!(e.type===Ce.WEB&&e.animationExportInfo?.animationInfo!==void 0&&Fl(e.asset))||e.type===Ce.SHAPE&&e.animationExportInfo?.animationInfo!==void 0,mp=({isDynamicInPiece:e,pieceStart:t,pieceDuration:o,assetStart:r,assetDuration:n,animationInfo:a,assetId:i,uniqueId:s})=>({isDynamicInPiece:e,assetId:i,pieceStartTime:t,pieceDuration:o,startTimelineTime:r,duration:n,animationInfo:a,uniqueId:s}),mle=e=>e.map(hle).filter(Se),hle=e=>{switch(e.type){case z.IMAGE:return e.assetEffectInfo||e.kenburnsAnimationInfo;case z.SHAPE:case z.WEB:return e.assetEffectInfo;default:return}},not=async(e,t,o,r,n,a,i)=>{const{selectedAssetIds:s,selectedAudioIds:x}=rc(e);if(x.length>0)return;if(s.length>0){const l=s.reduce((S,R)=>{const y=L.get(o,R);if(!y)return S;const v=y.trackIds.map(N=>L.get(t,N)).filter(Se),w=v.filter(N=>!(!N||!xr(N)||!PI(N)||Wn(N)&&!Fl(N)));return w.length===0?S:{filteredAssetIds:[...S.filteredAssetIds,R],filteredTargetTracks:[...S.filteredTargetTracks,...w]}},{filteredAssetIds:[],filteredTargetTracks:[]}),{filteredAssetIds:d,filteredTargetTracks:u}=l;if(d.length===0||u.length===0)return;const p=u.map(S=>S.trackId),f=mle(u),E=Ile(u),T=a[d[0]],O=Iu(pe(ue(T?.timelineEnd-T?.timelineStart,2)));switch(E){case z.IMAGE:{const S=u.length===1?await En(u[0].mediaId):void 0,R=S?URL.createObjectURL(S):gO;return{type:bp.ASSET,trackIds:p,appliedAnimationAssetType:z.IMAGE,appliedAnimations:f,imageUrl:R,assetDurationMs:O}}case z.WEB:return{type:bp.ASSET,trackIds:p,appliedAnimationAssetType:z.WEB,appliedAnimations:f,imageUrl:u.every(Wn)?void 0:gO,assetDurationMs:O};case z.SHAPE:{const S=u[0],R=S.type===z.SHAPE?Kce(S):gO;return{type:bp.ASSET,trackIds:p,appliedAnimationAssetType:z.SHAPE,appliedAnimations:f,imageUrl:R,assetDurationMs:O}}default:return}}const c=i?Iu(ac(i)):Wx;return{type:bp.CAPTION,appliedAnimations:(r.target===Xa.TEXTBOX||r.target===Xa.DESIGN_TEXTBOX?[r.asset.assetEffectInfo]:n).filter(Se),assetDurationMs:c}},Ile=e=>{if(e.every(Gn))return z.IMAGE;if(e.every(Wn))return z.WEB;if(e.every(f0))return z.SHAPE},aot=(e,t,o,r,n)=>{if(NI(t)){IFe(t);return}if(fle(t))switch(e){case z.IMAGE:TFe(t,o,r);break;case z.WEB:AFe(t,o,r);break;case z.SHAPE:OFe(t,o,r,n);break}},iot=(e,t,o,r)=>{if(t.length===0)return;if(e.length>1)vFe();else switch(o){case z.IMAGE:SFe();break;case z.WEB:yFe();break;case z.SHAPE:CFe(r);break}const n=t.every(NI);o===z.IMAGE&&n&&RFe()},Tle=({quill:e,text:t,currTime:o,animationName:r,animDuration:n,animStartDelay:a,assetDuration:i,isStaticAnimation:s,isPaused:x,isSelected:c})=>{const l=pv(a3({animationDurationMs:Iu(pe(n)),animationStartDelayMs:Iu(pe(a)),assetDurationMs:Iu(pe(i))}));if(l===0)return;const d=new Qt,u=Array.from(t),p=l/u.length;u.forEach((f,E)=>{const T=a+E*p-o,O=ue(T,2),S=O===0?.001:O,R=O>
9680,y=Sle({charIdx:E,animationName:r,textDuration:p,animationDelay:S,isStaticAnimation:s,isPaused:x,isSelected:c,shouldHideInStatic:R});d.retain(f.length,{"text-animation":y})}),e.updateContents(d)},Sle=({charIdx:e,animationName:t,textDuration:o,animationDelay:r,isStaticAnimation:n,isPaused:a,isSelected:i,shouldHideInStatic:s})=>{const x=n&&!s,c=!s,l=i||x||c?"1":"0";return{charIdx:""+e,animationName:i?"":t,animationDuration:o+"s",animationDelay:r+"s",animationFillMode:"forwards",animationTimingFunction:"ease-in-out",animationPlayState:a?"paused":"running",opacity:l,position:"relative"}},sot=e=>{const t=new Qt().retain(e.length(),Object.fromEntries(YG.map(o=>[o,null])));return e.compose(t)},Ua=e=>pv(Yc(e)),Cd=e=>pv(Yc(e)),a3=({animationDurationMs:e,animationStartDelayMs:t,assetDurationMs:o})=>{if(e<=0)return Yc(0);const r=Math.min(Math.max(o-t,0),qX);return Yc(Math.min(e,r))},xot=({animationStartDelayMs:e,assetDurationMs:t})=>{if(e<=0)return Yc(0);const o=Math.min(t,QX);return Yc(Math.min(e,o))},i3=(e,t)=>({...e,duration:a3({animationDurationMs:e.duration,animationStartDelayMs:ax(e)?e.startDelay:0,assetDurationMs:t})}),MI=(e,t)=>{if(t<=0||!e)return;const o=BG(pe(t)),r=i3(e,o);return r.duration>0?r:void 0},cot=(e,t,o)=>{const r=e*1e3-t*1e3;return o-r};let Ns=class{future=null;current=null;_isResolved=!1;promise(t=!1){return t&&this.reset(),this.current?this.current:this.current=new Promise((o,r)=>{this.future={resolve:o,reject:r}})}resolve(t,o=!0){if(!this.future)throw new Error("No promise");this._isResolved||(this.future.resolve(t),this._isResolved=!0,o&&this.reset())}reject(t,o=!0){if(!this.future)throw new Error("No promise");this.future.reject(t),o&&this.reset()}reset(){return this.current=null,this.future=null,this._isResolved=!1,this}},Qv=class{dataArray=[];maxSize;eqFn;constructor(t,o=(r,n)=>r===n){this.maxSize=t,this.eqFn=o}set(t,o){const r=this.dataArray.findIndex(n=>this.eqFn(n.key,t));r>-1&&this.dataArray.splice(r,1),this.dataArray.length===this.maxSize-1&&this.dataArray.shift(),this.dataArray.push({key:t,value:o})}get(t){const o=this.dataArray.findIndex(r=>this.eqFn(r.key,t));if(o>-1){const r=this.dataArray.splice(o,1)[0];return this.dataArray.push(r),r.value}}has(t){return this.dataArray.some(o=>this.eqFn(o.key,t))}};const Ole=e=>e?.missingFramePackBehavior??"throw",Cle=(e,t,o)=>{const r=zce(e.mediaId);if(!r){if(Ole(o)==="empty")return"";throw new Error("Shape frame pack not found: "+e.mediaId)}return rn.template(r)({strokeWidth:t.strokeWidth,strokeColor:e.stroke.color,planeColor:e.plane?.color,width:t.width,height:t.height,isDashed:e.stroke.isDashed,isRounded:e.stroke.isRounded,cornerRounding:e.cornerRounding,randomId:ct()})},Rle=(e,t,o)=>{const r=t.width,n=t.strokeWidth,a=!e.hasHead,i=e.shapeOfHead==="double",s=e.stroke.isRounded,x=e.stroke.isDashed;if(a)return`<svg
969      viewBox="0 0 `+r+" "+n+`"
970      xmlns="http://www.w3.org/2000/svg"
971      style="width: `+r+"px;height: "+n+`px; overflow: visible"
972    >
973      <line
974        x1="`+n/2+`"
975        y1="`+n/2+`"
976        x2="`+(r-n/2)+`"
977        y2="`+n/2+`"
978        stroke="`+e.stroke.color+`"
979        stroke-width="`+n+`"
980        stroke-linecap="`+(s?"round":"square")+`"
981        stroke-dasharray="`+(x?2.2*n+" "+2.2*n:"0")+`"
982      />
983    </svg>`;const c=n*4,l=n*4,d=o?.limitWidthForArrow??!0,u=d?Math.max(r,c*Math.sqrt(2)):r,p=n*8,f=Fn(e.stroke.color).alpha(1).toHex(),E=Fn(e.stroke.color).alpha();return i?`<svg
984      viewBox="0 0 `+u+" "+p+`"
985      xmlns="http://www.w3.org/2000/svg"
986      style="width: `+u+"px;height: "+p+"px;opacity:"+E+`; overflow: hidden"
987    >
988      <line
989        x1="`+n*Math.sqrt(2)+`"
990        y1="`+p/2+`"
991        x2="`+(u-n*Math.sqrt(2))+`"
992        y2="`+p/2+`"
993        stroke="`+f+`"
994        stroke-width="`+n+`"
995        stroke-linecap="`+(s?"round":"square")+`"
996        stroke-dasharray="`+(x?2.2*n+" "+2.2*n:"0")+`"
997      />
998      <polyline
999        points="`+l+","+(p-c)/2+" "+(s?n/2:n)+","+p/2+" "+l+","+(p+c)/2+`"
1000        fill="none"
1001        stroke="`+f+`"
1002        stroke-width="`+n+`"
1003        stroke-linecap="`+(s?"round":"square")+`"
1004        stroke-linejoin="`+(s?"round":"inherit")+`"
1005      />
1006      <polyline
1007        points="`+(u-l)+","+(p-c)/2+" "+(s?u-n/2:u-n)+","+p/2+" "+(u-l)+","+(p+c)/2+`"
1008        fill="none"
1009        stroke="`+f+`"
1010        stroke-width="`+n+`"
1011        stroke-linecap="`+(s?"round":"square")+`"
1012        stroke-linejoin="`+(s?"round":"inherit")+`"
1013      />
1014    </svg>`:`<svg
1015    viewBox="0 0 `+u+" "+p+`"
1016    xmlns="http://www.w3.org/2000/svg"
1017    style="width: `+u+"px;height: "+p+"px;opacity:"+E+`; overflow: hidden"
1018  >
1019    <line
1020      x1="`+n*Math.sqrt(2)+`"
1021      y1="`+p/2+`"
1022      x2="`+(u-n/2)+`"
1023      y2="`+p/2+`"
1024      stroke="`+f+`"
1025      stroke-width="`+n+`"
1026      stroke-linecap="`+(s?"round":"square")+`"
1027      stroke-dasharray="`+(x?2.2*n+" "+2.2*n:"0")+`"
1028    />
1029    <polyline
1030      points="`+l+","+(p-c)/2+" "+(s?n/2:n)+","+p/2+" "+l+","+(p+c)/2+`"
1031      fill="none"
1032      stroke="`+f+`"
1033      stroke-width="`+n+`"
1034      stroke-linecap="`+(s?"round":"square")+`"
1035      stroke-linejoin="`+(s?"round":"inherit")+`"
1036    />
1037  </svg>`},s3=(e,t,o)=>i2(e)?Cle(e,{width:t.width,height:t.height,strokeWidth:t.strokeWidth},o):Qx(e)?Rle(e,{width:t.width,strokeWidth:t.strokeWidth},o):"",Ale=(e,t)=>{const o=document.createElement("div"),r=s3(e,{width:e.width*t.width,height:e.height*t.height,strokeWidth:e.stroke.width*t.width});return o.innerHTML=r,o},yle=(e,t)=>{const o=document.createElement("div"),r=x3(e,t);o.setAttribute("style",r);const n=s3(e,{width:e.width*t.width,height:e.height*t.height,strokeWidth:e.stroke.width*t.width});return o.innerHTML=n,o},x3=(e,t)=>{const o=e.width*t.width,r=e.height*t.height,n=e.xPos*t.width,a=e.yPos*t.height;if(i2(e))return Bl({position:"absolute",width:o+"px",height:r+"px",transform:"translate("+n+"px, "+a+"px) rotate("+e.rotation+"deg)"});if(Qx(e)){const i=e.stroke.width*t.width;if(!e.hasHead)return Bl({position:"absolute",width:o+"px",height:i+"px",transform:"translate("+n+"px, "+(a-i/2)+"px) rotate("+e.rotation+"deg)","transform-origin":"left 50%"});{const x=r*4,c=i*8,l=Math.max(o,x*Math.sqrt(2))+"px",d=c+"px",u="translate("+n+"px, "+(a-c/2)+"px) rotate("+e.rotation+"deg)";return Bl({position:"absolute",width:l,height:d,transform:u,"transform-origin":"left 50%"})}}else return""},oM=e=>!e.animationExportInfo.isDynamicInPiece&&e.asset.durationSeconds===0,Zv=e=>{switch(e.type){case Ce.WEB:return oM(e);case Ce.SHAPE:return!e.animationExportInfo?.isDynamicInPiece;case Ce.IMAGE:return!e.animationExportInfo?.isDynamicInPiece&&e.asset.kenburnsAnimationInfo===void 0;case Ce.CAPTION:return oM(_a(e));default:return!1}},rM=e=>e.every(Zv),$v=async(e,t,o,r,n,a)=>{if(e.length===0)return[];const s=e.sort(({asset:l},{asset:d})=>l.zIndex-d.zIndex).reduce((l,d)=>{const u=l.at(-1);return u===void 0?l.push([d]):Zv(d)&&rM(u)?u.push(d):l.push([d]),l},[]),x=dm(s.map(async l=>rM(l)?[await wle(l,t,await r.createTempFolder(mU),o,n,a)]:l)).pipe(At(l=>l.flat()));return await Bt(x)},vle=(e,t)=>e+"/"+t+".png",wle=async(e,t,o,r,n,a)=>{const[i]=v2(t),s=Cn();try{const x=(await Promise.all(e.map(f=>Ple(f,t,n,a)))).filter(Se),c=await ow(Nle(e));x.forEach(f=>i.appendChild(f)),document.body.insertBefore(i,document.querySelector("#root"));const l=await o2(i,{fontEmbedCSS:c,canvasWidth:t.width/window.devicePixelRatio,canvasHeight:t.height/window.devicePixelRatio});if(l===null)throw h("staticAssetRenderer.ts").error("blob is null when exporting static assets "+JSON.stringify(e)+"}"),new C(_.C_TEXTBOX_RENDER_ERROR);const d=vle(o,s);await r.addFile(d,await l.arrayBuffer(),"binary");const u=Math.min(...e.map(({asset:f})=>f.zIndex));return ble(t,s,d,u)}catch(x){throw h("staticAssetRenderer.ts").error(P(x)),new C(_.C_TEXTBOX_RENDER_ERROR)}finally{i.remove()}},Nle=e=>{const t=e.filter(n=>n.type===Ce.WEB),o=e.filter(n=>n.type===Ce.CAPTION).map(_a);return[...t,...o].map(({asset:n})=>n)},Ple=async(e,t,o,r)=>{switch(e.type){case Ce.WEB:return zR(e.asset,kI(e.asset,t),e.asset.durationSeconds,e.animationExportInfo.duration,o);case Ce.SHAPE:return yle(e.asset,t);case Ce.IMAGE:return Ble(e.asset,t,r);case Ce.CAPTION:return Yle(e,t,o)}},ble=(e,t,o,r)=>({type:Ce.COMPOSITED_IMAGE,asset:{trackId:Rt(),height:1,width:1,importType:_e.UNKNOWN,mediaId:t,originalWidthHeightRatio:e.width/e.height,rotation:0,type:z.IMAGE,xPos:0,yPos:0,zIndex:r},assetId:Cn(),path:o}),nM=1,Lle=e=>[Ce.LOTTIE,Ce.WEB,Ce.IMAGE,Ce.CAPTION,Ce.SHAPE].includes(e),ew=async(e,t,o,r,n,a,i,s,x)=>{const c=h("asset.ts"),l=e.flatMap(S=>[...S.exportAssets,...S.exportCaptionModels].filter(v=>Lle(v.type))).filter(S=>!Zv(S)),d=l.filter(S=>!(S.type===Ce.SHAPE&&S.animationExportInfo?.isDynamicInPiece===!1||S.type===Ce.IMAGE&&S.asset.kenburnsAnimationInfo!==void 0||S.type===Ce.IMAGE&&S.animationExportInfo?.isDynamicInPiece===!1||S.type===Ce.WEB&&S.animationExportInfo.isDynamicInPiece===!1||S.type===Ce.CAPTION&&_a(S)?.animationExportInfo.isDynamicInPiece===!1)),u=N9(d,(S,R)=>
1037{if(S.type===Ce.IMAGE&&S.animationExportInfo!==void 0&&R.type===Ce.IMAGE&&R.animationExportInfo!==void 0||S.type===Ce.SHAPE&&S.animationExportInfo!==void 0&&R.type===Ce.SHAPE&&R.animationExportInfo!==void 0)return S.animationExportInfo.uniqueId===R.animationExportInfo.uniqueId;if(S.type===Ce.WEB&&R.type===Ce.WEB)return Fl(S.asset)&&Fl(R.asset)?S.animationExportInfo.uniqueId===R.animationExportInfo.uniqueId:S.animationExportInfo.assetId===R.animationExportInfo.assetId;if(S.type===Ce.CAPTION&&R.type===Ce.CAPTION)return _a(S).animationExportInfo.uniqueId===_a(R).animationExportInfo.uniqueId;if(S.type===Ce.CAPTION&&R.type===Ce.WEB||S.type===Ce.WEB&&R.type===Ce.CAPTION){const y=S.type===Ce.CAPTION?_a(S):S,v=R.type===Ce.CAPTION?_a(R):R;return Fl(y.asset)&&Fl(v.asset)?y.animationExportInfo.uniqueId===v.animationExportInfo.uniqueId:y.animationExportInfo.assetId===v.animationExportInfo.assetId}return S.asset.mediaId===R.asset.mediaId}),p=u.reduce((S,R)=>S+nM,0);let f=0;if(p===0)return{};c.info("exportFrame totalCount: "+p),i(f,p);const E=Tt(...u).pipe(Ma(S=>{if(s())throw new C(_.C_ENCODING_USER_CANCELED);return zt(Dle(S,r,t,o,n,a,s,x)).pipe(er(()=>{f=f+nM,i(f,p)}),jl(Se),At(R=>[r3(S),R]))},5),aa()),T=await Bt(E);return Object.fromEntries(T)},Mle=async(e,t,o,r,n,a,i,s)=>{const x=_a(e),c=x.animationExportInfo,l=x.animationExportInfo?.animationInfo,d=l!==void 0&&as(l.type),u=e.yAlign===oo.CUSTOM,p=await ow([e[Ke.ORIGINAL]?.asset,e[Ke.TRANSLATE]?.asset].filter(Se));u?await d3(x.asset,o,p,n,t,a,x.animationExportInfo,i,s):await Hle(e,o,n,t,p,a,i,s);const f=c.pieceDuration??Ua(l?.duration??Wx),E=Math.max(Math.ceil(f*o),1);return{frameDirectory:r,frameFormat:n,frameRate:o,loop:d,frames:E}},Dle=async(e,t,o,r,n,a,i,s)=>{const x=await a.createTempFolder(mU),c=x+"/"+ZX;switch(e.type){case Ce.IMAGE:{const{asset:l}=e,d=e.animationExportInfo?.pieceDuration??Ua(Yc(e.animationExportInfo?.duration??Wx)),u=Math.max(Math.ceil(d*r),1),p=e.animationExportInfo?.animationInfo,f=p!==void 0&&as(p.type);return await Gle(l,o,r,c,t,n,e.animationExportInfo,i),{frameDirectory:x,frameFormat:c,frameRate:r,loop:f,frames:u}}case Ce.SHAPE:{const{asset:l}=e,d=e.animationExportInfo?.pieceDuration??Ua(Yc(e.animationExportInfo?.duration??Wx)),u=Math.max(Math.ceil(d*r),1),p=e.animationExportInfo?.animationInfo,f=p!==void 0&&as(p.type);return await jle(l,r,c,t,n,e.animationExportInfo,i),{frameDirectory:x,frameFormat:c,frameRate:r,loop:f,frames:u}}case Ce.WEB:{const{asset:l}=e,d=await ow([l]);if(e.animationExportInfo.animationInfo!==void 0){const p=e.animationExportInfo.pieceDuration??Ua(e.animationExportInfo.animationInfo.duration),f=Math.max(Math.ceil(p*r),1),E=e.animationExportInfo.animationInfo,T=E!==void 0&&as(E.type);return await d3(l,r,d,c,t,n,e.animationExportInfo,i,s),{frameDirectory:x,frameFormat:c,frameRate:r,loop:T,frames:f}}const u=Math.max(l.durationSeconds*r,1);return await zle(l,d,c,u,t,n,s),{frameDirectory:x,frameFormat:c,frameRate:r,loop:l.loop,frames:u}}case Ce.LOTTIE:{const{asset:l}=e;return await Kle(),{frameDirectory:x,frameFormat:c,frameRate:l.frameRate,loop:!0,frames:l.frameLength}}case Ce.CAPTION:return Mle(e,t,r,x,c,n,i,s)}},tw=e=>{const t=R2(e);return LI(t)},A2=async(e,t,o)=>{const r=await o2(e,o);if(r===null)throw h("asset.ts").error("blob is null when exporting "+t+" for animation"),new C(_.C_GENERATE_ANIMATION_FRAME_ERROR);return r},y2=async(e,t,o,r,n)=>{let i;const s=await r.arrayBuffer();for(let x=e;x<t;x+=1e3){i=o.replace("%d",x.toString()),await n.addFile(i,s,"binary");const c=x0(x+1,Math.min(t,x+1e3)).map(l=>o.replace("%d",l.toString()));await n.links({sourcePath:i,targetPaths:c})}},Fu=async(e,t,o,r)=>{const n=await e.arrayBuffer(),a=o.replace("%d",t.toString());return r.addFile(a,n,"binary")},TO=async(e,t,o,r,n,a,i,s,x,c,l,d,u,p=0,f)=>{if(!l)return;const E=Jr(l)&&p>0,T=E?"asset-effect-fade-in-out":R2(l),O=bI(l).styleObject;a.style.animationName=""+T,a.style.animationDuration=r+"s",a.style.animationPlayState="paused",a.style.animationFillMode="forwards",Object.assign(a.style,O);const S=document.createElement("style"),R=E?LI("asset-effect-fade-in-out"):tw(l);S.textContent=""+R,a.appendChild(S);try{let y=d;if(p>0){a.style.animationDelay="0s";const N=await A2(e,t.mediaId,{skipFonts:!0,canvasWidth:o.width/window.devicePixelRatio,canvasHeight:o.height/window.devicePixelRatio});await y2(y,y+p,s,N,i),y+=p}
1037const v=await kle(t,e,o,n,a,x,c,u),w=v.length;if(f!==void 0&&w>0)for(let N=0;N<f;N++){const M=v[N%w];await Fu(M,y+N,s,i)}else await Promise.all(v.map((N,M)=>Fu(N,y+M,s,i)))}catch(y){throw Ne(y)?y:(h("asset.ts").error(P(y)),new C(_.C_IMAGE_ANIMATION_ERROR))}},kle=async(e,t,o,r,n,a,i,s)=>{const x=h("asset.ts"),c=[];for(let l=a;l<i;l++){if(s())throw new C(_.C_ENCODING_USER_CANCELED);n.style.animationDelay="-"+l*r+"s";try{const d=await o2(t,{skipFonts:!0,canvasWidth:o.width/window.devicePixelRatio,canvasHeight:o.height/window.devicePixelRatio});if(d===null){const u="blob is null when exporting "+e.mediaId+" shape";throw x.error(u),new C(_.C_GENERATE_ANIMATION_FRAME_ERROR,void 0,u)}else c.push(d)}catch(d){if(Ne(d))throw d;const u="Error during shape exporting "+e.mediaId+" shape: "+P(d);throw x.error(u),new C(_.C_GENERATE_ANIMATION_FRAME_ERROR,void 0,u)}}return c},SO=async(e,t,o,r,n,a,i,s,x,c,l,d,u,p=0,f,E=0)=>{if(!l)return;const T=Jr(l)&&E>0,O=T?"asset-effect-fade-in-out":R2(l),S=bI(l).styleObject;a.style.animationName=""+O,a.style.animationDuration=r+"s",a.style.animationPlayState="paused",a.style.animationFillMode="forwards",Object.assign(a.style,S);const R=document.createElement("style"),y=T?LI("asset-effect-fade-in-out"):tw(l);R.textContent=""+y,a.appendChild(R);try{let v=d;if(p>0){a.style.animationDelay="0s";const M=await A2(e,t.mediaId,{skipFonts:!0,canvasWidth:o.width/window.devicePixelRatio,canvasHeight:o.height/window.devicePixelRatio});await y2(v,v+p,s,M,i),v+=p}const w=await Fle(t,e,o,n,a,x,c,u),N=w.length;if(f!==void 0&&N>0)for(let M=0;M<f;M++){const k=w[M%N];await Fu(k,v+M,s,i)}else await Promise.all(w.map((M,k)=>Fu(M,v+k,s,i)))}catch(v){throw Ne(v)?v:(h("asset.ts").error(P(v)),new C(_.C_IMAGE_ANIMATION_ERROR))}},Fle=async(e,t,o,r,n,a,i,s)=>{const x=h("asset.ts"),c=[];for(let l=a;l<i;l++){if(s())throw new C(_.C_ENCODING_USER_CANCELED);n.style.animationDelay="-"+l*r+"s";try{const d=await o2(t,{skipFonts:!0,canvasWidth:o.width/window.devicePixelRatio,canvasHeight:o.height/window.devicePixelRatio});if(d===null){const u="blob is null when exporting "+e.mediaId+" image";throw x.error(u),new C(_.C_GENERATE_ANIMATION_FRAME_ERROR,void 0,u)}else c.push(d)}catch(d){if(Ne(d))throw d;const u="Error during image exporting "+e.mediaId+" image: "+P(d);throw x.error(u),new C(_.C_GENERATE_ANIMATION_FRAME_ERROR,void 0,u)}}return c},Ule=async(e,t,o,r,n,a,i)=>{const s=`
1038      width : `+o.width*r.width+`px;
1039      height : `+o.height*r.height+`px;
1040      z-index : `+o.zIndex+`;
1041  `;e.setAttribute("style",s);try{const x=await A2(t,o.mediaId,{skipFonts:!0,canvasWidth:r.width/window.devicePixelRatio,canvasHeight:r.height/window.devicePixelRatio});await y2(0,n,i,x,a)}catch(x){throw h("asset.ts").error(P(x)),new C(_.C_SHAPE_ANIMATION_ERROR)}},c3=(e,t,o)=>{const r="editInfo"in t?t.editInfo?.crop:void 0,n=pg(r),a=1-n.left-n.r
1041ight,i=1-n.top-n.bottom,s=t.width/a*o.width,x=t.height/i*o.height;e.style.transform="translate("+-s*n.left+"px, "+-x*n.top+"px)",e.style.width=s+"px",e.style.height=x+"px",e.style.clipPath=r??""},Vle=async(e,t,o,r,n,a,i)=>{e.style.zIndex=""+o.zIndex;try{const s=await A2(t,o.mediaId,{skipFonts:!0,canvasWidth:r.width/window.devicePixelRatio,canvasHeight:r.height/window.devicePixelRatio});await y2(0,n,i,s,a)}catch(s){throw h("asset.ts").error(P(s)),new C(_.C_IMAGE_ANIMATION_ERROR)}},Gle=async(e,t,o,r,n,a,i,s)=>{if(!i)return;const{animationInfo:x,pieceStartTime:c,pieceDuration:l,startTimelineTime:d,duration:u}=i;if(c===void 0||l===void 0||x===void 0)return;const{type:p,duration:f}=x,E=ax(x)?Cd(x.startDelay):0,T=d+E,O=Math.max(0,u-E),S=Ua(f),R=Jr(p)&&E>0?O:E>0?Math.min(O,S):S,y=Math.ceil(R*o),v=R/(y||1),[w]=v2(n),N=p3(e,n),M=e.editInfo?.opacity;M&&M!==1&&(N.style.opacity=String(M)),w.insertBefore(N,null),document.body.insertBefore(w,document.body.querySelector("#root"));try{const k=t!==void 0?t[e.mediaId]:"";if(!k)throw new C(_.C_LOGIC_ERROR,{},"No image path found for image "+e.mediaId);const F=document.createElement("div");N.insertBefore(F,null);const G=document.createElement("img");F.insertBefore(G,null),c3(G,e,n),G.src=an(k);const B=c+l;if(as(p)){const te=E>0?Math.max(0,Math.ceil((T-c)*o)):0,ne=te>0?Math.ceil(l*o)-te:void 0;await SO(w,e,n,R,v,F,a,r,0,y,p,0,s,te,ne,E),w.remove();return}if(El(p)||Jr(p)){const te=E>0?Math.max(0,Math.ceil((T-c)*o)):0,ne=Math.max(c-T,0),oe=Math.ceil(ne*o),re=Math.ceil(Math.max(0,(B-T)*o));await SO(w,e,n,R,v,F,a,r,oe,re,p,0,s,te,void 0,E),w.remove();return}const W=d+u,Q=W-R,j=Q-c,$=Math.floor(j*o);Q>c&&await Vle(G,w,e,n,$,a,r);const q=$>0?0:Math.floor((c-Q)*o),H=Math.ceil(Math.max(0,(B-Q)*o)),U=$>0?$:0;await SO(w,e,n,R,v,F,a,r,q,H,p,U,s,void 0,void 0,E)}catch(k){throw Ne(k)?k:(h("asset.ts").error(P(k)),new C(_.C_IMAGE_ANIMATION_ERROR))}finally{w.remove()}},Wle=async(e,t,o,r,n,a,i,s,x,c,l,d,u,p,f,E=0)=>{const T=h("asset.ts"),O=[];for(let S=x;S<c;S++){if(d())throw new C(_.C_ENCODING_USER_CANCELED);const R=S*s,y=R+E,v=l&&nx(l)?y:R;t.innerHTML=rw(o,n,l,i,v,!1,u,p,f);try{const w=await o2(e,{fontEmbedCSS:a,canvasWidth:r.width/window.devicePixelRatio,canvasHeight:r.height/window.devicePixelRatio});if(w===null){const N="blob is null when exporting "+o.mediaId+" textbox";throw h("asset.ts").error(N),new C(_.C_GENERATE_ANIMATION_FRAME_ERROR,void 0,N)}else O.push(w)}catch(w){if(Ne(w))throw w;const N="Error during exporting "+o.mediaId+" textbox: "+P(w);throw T.error(N),new C(_.C_GENERATE_ANIMATION_FRAME_ERROR,void 0,N)}}return O},Ou=async(e,t,o,r,n,a,i,s,x,c,l,d,u,p,f,E,T,O=0,S,R=0)=>{if(!u)return;const y=Jr(u)&&R>0,v=y?"asset-effect-fade-in-out":void 0;try{let w=p;if(O>0){t.innerHTML=rw(o,n,u,i,0,!0,E,T);const k=await A2(e,o.mediaId,{fontEmbedCSS:a,canvasWidth:r.width/window.devicePixelRatio,canvasHeight:r.height/window.devicePixelRatio});await y2(w,w+O,c,k,x),w+=O}const N=await Wle(e,t,o,r,n,a,i,s,l,d,u,f,E,T,v,R),M=N.length;if(S!==void 0&&M>0)for(let k=0;k<S;k++){const F=N[k%M];await Fu(F,w+k,c,x)}else await Promise.all(N.map((k,F)=>Fu(k,w+F,c,x)))}catch(w){throw Ne(w)?w:(h("asset.ts").error(P(w)),new C(_.C_WEB_ANIMATION_ERROR))}},l3=async(e,t,o,r,n,a,i,s,x,c,l)=>{t.innerHTML=rw(o,n,void 0,0,0,!0,c,l);try{const d=await A2(e,o.mediaId,{fontEmbedCSS:a,canvasWidth:r.width/window.devicePixelRatio,canvasHeight:r.height/window.devicePixelRatio});await y2(0,i,x,d,s)}catch(d){throw h("asset.ts").error(P(d)),new C(_.C_WEB_ANIMATION_ERROR)}},Hle=async(e,t,o,r,n,a,i,s)=>{const x=_a(e),c=e.captionType,{animationExportInfo:l}=x,{animationInfo:d,pieceStartTime:u,pieceDuration:p,startTimelineTime:f,duration:E}=l;if(u===void 0||p===void 0||d===void 0)return;const{type:T,duration:O}=d,[S]=v2(r),[R]=u3(e,r);let y,v;const w=x.asset;
1041if([Ke.ORIGINAL,Ke.TRANSLATE].forEach(Q=>{const j=e[Q];if(j===void 0)return;const $=Q===c,q=j.asset,[H,U]=DI(D3(q,r));H.innerHTML=nw(q,U,q.durationSeconds,E,s),$?(v=H,y=U):H.style.visibility="hidden",R.appendChild(H)}),S.insertBefore(R,null),document.body.insertBefore(S,document.body.querySelector("#root")),y===void 0||v===void 0)return;const N=ax(d)?Cd(d.startDelay):0,M=f+N,k=Math.max(0,E-N),F=Ua(O),G=Jr(T)&&N>0?k:N>0?Math.min(k,F):F,B=Math.ceil(G*t),W=G/(B||1);try{const Q=u+p;if(El(T)||Jr(T)||nx(T)){const oe=N>0?Math.max(0,Math.ceil((M-u)*t)):0,re=Math.max(u-M,0),ge=Math.ceil(re*t),fe=Math.ceil(Math.max(0,(Q-M)*t));await Ou(S,v,w,r,y,n,G,W,a,o,ge,fe,T,0,i,E,s,oe,void 0,N),S.remove();return}if(as(T)){const oe=N>0?Math.max(0,Math.ceil((M-u)*t)):0,re=oe>0?Math.ceil(p*t)-oe:void 0;await Ou(S,v,w,r,y,n,G,W,a,o,0,B,T,0,i,E,s,oe,re,N),S.remove();return}const j=f+E,$=j-G,q=$-u,H=Math.floor(q*t);$>u&&await l3(S,v,w,r,y,n,H,a,o,E,s);const U=H>0?0:Math.floor((u-$)*t),te=Math.ceil(Math.max(0,(Q-$)*t)),ne=H>0?H:0;await Ou(S,v,w,r,y,n,G,W,a,o,U,te,T,ne,i,E,s)}catch(Q){throw h("asset.ts").error(P(Q)),Ne(Q)?Q:new C(_.C_WEB_ANIMATION_ERROR)}finally{S.remove()}},d3=async(e,t,o,r,n,a,i,s,x)=>{if(!i)return;const{animationInfo:c,pieceStartTime:l,pieceDuration:d,startTimelineTime:u,duration:p}=i;if(l===void 0||d===void 0||c===void 0)return;const{type:f,duration:E}=c,T=ax(c)?Cd(c.startDelay):0,O=u+T,S=Math.max(0,p-T),R=Ua(E),y=Jr(f)&&T>0?S:T>0?Math.min(S,R):R,v=Math.ceil(y*t),w=y/(v||1),N=kI(e,n),[M]=v2(n),[k,F]=DI(N);M.insertBefore(k,null),document.body.insertBefore(M,document.body.querySelector("#root"));const G=l+d;try{if(as(f)){const U=T>0?Math.max(0,Math.ceil((O-l)*t)):0,te=U>0?Math.ceil(d*t)-U:void 0;await Ou(M,k,e,n,F,o,y,w,a,r,0,v,f,0,s,p,x,U,te,T),M.remove();return}if(El(f)||Jr(f)||nx(f)){const U=T>0?Math.max(0,Math.ceil((O-l)*t)):0,te=Math.max(l-O,0),ne=Math.ceil(te*t),oe=Math.ceil(Math.max(0,(G-O)*t));await Ou(M,k,e,n,F,o,y,w,a,r,ne,oe,f,0,s,p,x,U,void 0,T),M.remove();return}const B=u+p,W=B-y,Q=W-l,j=Math.floor(Q*t);W>l&&await l3(M,k,e,n,F,o,j,a,r,p,x);const $=j>0?0:Math.floor((l-W)*t),q=Math.ceil(Math.max(0,(G-W)*t)),H=j>0?j:0;await Ou(M,k,e,n,F,o,y,w,a,r,$,q,f,H,s,p,x)}catch(B){throw h("asset.ts").error(P(B)),Ne(B)?B:new C(_.C_WEB_ANIMATION_ERROR)}finally{M.remove()}},jle=async(e,t,o,r,n,a,i)=>{if(!a)return;const{animationInfo:s,pieceStartTime:x,pieceDuration:c,startTimelineTime:l,duration:d}=a;if(x===void 0||c===void 0||s===void 0)return;const{type:u,duration:p}=s,f=ax(s)?Cd(s.startDelay):0,E=l+f,T=Math.max(0,d-f),O=Ua(p),S=Jr(u)&&f>0?T:f>0?Math.min(T,O):O,R=Math.ceil(S*t),y=S/(R||1),[v]=v2(r),w=Xle(e,r);v.insertBefore(w,null),document.body.insertBefore(v,document.body.querySelector("#root"));try{const N=Ale(e,r);w.insertBefore(N,null);const M=x+c;if(as(u)){const k=f>0?Math.max(0,Math.ceil((E-x)*t)):0,F=k>0?Math.ceil(c*t)-k:void 0;await TO(v,e,r,S,y,N,n,o,0,R,u,0,i,k,F),v.remove();return}if(El(u)||Jr(u)){const k=f>0?Math.max(0,Math.ceil((E-x)*t)):0,F=Math.max(x-E,0),G=Math.ceil(F*t),B=Math.ceil(Math.max(0,(M-E)*t));await TO(v,e,r,S,y,N,n,o,G,B,u,0,i,k),v.remove();return}if(W0(u)){const k=l+d,F=k-S,G=F-x,B=Math.floor(G*t);F>x&&await Ule(N,v,e,r,B,n,o);const W=B>0?0:Math.floor((x-F)*t),Q=Math.ceil(Math.max(0,(M-F)*t)),j=B>0?B:0;await TO(v,e,r,S,y,N,n,o,W,Q,u,j,i);return}}catch(N){throw Ne(N)?N:(h("asset.ts").error(P(N)),new C(_.C_SHAPE_ANIMATION_ERROR))}finally{v.remove()}},zle=async(e,t,o,r,n,a,i)=>{const s=kI(e,n),x=e.durationSeconds/(r||1),[c]=v2(n),[l,d]=DI(s);c.insertBefore(l,null),document.body.insertBefore(c,document.body.querySelector("#root"));try{for await(const u of x0(0,r)){l.innerHTML=nw(e,d,u*x,null,i);const p=await o2(c,{fontEmbedCSS:t,canvasWidth:n.width/window.devicePixelRatio,canvasHeight:n.height/window.devicePixelRatio});if(p===null)throw h("asset.ts").error("blob is null when exporting "+e.mediaId+" textbox"),new C(_.C_TEXTBOX_RENDER_ERROR);await a.addFile(o.replace("%d",u.toString()),await p.arrayBuffer(),"binary")}}catch(u){throw h("asset.ts").error(P(u)),new C(_.C_TEXTBOX_RENDER_ERROR)}finally{c.remove()}},u3=(e,t)=>
1041{const o=ct(),r=document.createElement("div");r.setAttribute("id",o);const{width:n,height:a}=t,i=e.yAlign,s=Rv(n,a,e.asset.scaleFactor),x=Eoe*a/s,c=Bl({position:"absolute",display:"flex","flex-direction":"column","align-items":"center",gap:x+"px","transform-origin":"top left",transform:k3(i,s,t.width,t.height)});return r.setAttribute("style",c),[r,o]},Yle=(e,t,o)=>{const r=e.captionType;if(e.yAlign===oo.CUSTOM){const a=_a(e);return zR(a.asset,kI(a.asset,t),a.asset.durationSeconds,a.animationExportInfo.duration,o)}const[n]=u3(e,t);return[Ke.ORIGINAL,Ke.TRANSLATE].forEach(a=>{const i=e[a];if(i===void 0)return;const{asset:s}=i,x=D3(s,t),c=zR(s,x,s.durationSeconds,i.animationExportInfo.duration,o);a!==r&&(c.style.visibility="hidden"),n.appendChild(c)}),n},zR=(e,t,o,r,n)=>{try{const[a,i]=DI(t);return a.innerHTML=nw(e,i,o,r,n),a}catch(a){throw h("asset.ts").error(P(a)),new C(_.C_TEXTBOX_RENDER_ERROR)}},Ble=async(e,t,o)=>{try{const r=o.find(x=>x.mediaId===e.mediaId)?.blob;if(!r)throw new C(_.C_IMAGE_RENDER_ERROR,{},"image file not found: "+e.mediaId);const n=await V2(r),a=p3(e,t),i=e.editInfo?.opacity;i&&i!==1&&(a.style.opacity=String(i));const s=document.createElement("img");return s.src=n,c3(s,e,t),a.appendChild(s),a}catch(r){throw h("asset.ts").error(P(r)),new C(_.C_IMAGE_RENDER_ERROR)}},Kle=async(e,t)=>{throw new Error("not implemented")},v2=e=>{const t=document.createElement("div"),o=ct();return t.setAttribute("style","position:absolute; z-index:-999999; width:"+e.width+"px; height:"+e.height+"px; will-change:transform; forced-color-adjust:none;"),t.setAttribute("id",o),[t,o]},Bl=e=>Object.entries(e).map(([t,o])=>t+":"+o).join(";"),ow=async e=>{const t=Q0e(e),o=await Promise.all(t.map(async r=>{const n=aM().get(r.path);if(n!==void 0)return{...r,path:n};const a=await fetch(r.path).then(s=>s.blob()).catch(s=>{throw h("asset.ts").error("Error during getWebFontCSS: "+P(s)+", path: "+r.path),s}),i=await V2(a);return aM().set(r.path,i),{...r,path:i}}));return dV(o)},rw=(e,t,o,r,n,a=!1,i,s,x)=>{const c="webrender-"+e.mediaId,l=x??R2(o),d=f3(e,c,n,a,i,s),u=x?LI(x):tw(o),p=o&&nx(o)?"":"-"+n+"s",f=`
1042  <style>
1043  .`+e.mediaId+"."+c+` {
1044    animation-name: `+l+`;
1045    animation-duration: `+r+`s;
1046    animation-play-state: paused !important;
1047    animation-delay: `+p+` !important;
1048    animation-fill-mode: forwards !important;
1049    `+bI(o).styleText+`
1050  }
1051
1052  `+u+`
1053
1054  </style>`;return`
1055  `+TW(t)+`
1056  `+IW(t,e.customAttributes,e.deltas)+`
1057  `+(n!==void 0?f:"")+`
1058  `+d+`
1059  `},nw=(e,t,o,r,n)=>{let a=0;e.assetEffectInfo&&nx(e.assetEffectInfo?.type)&&(a=Ua(e.assetEffectInfo.duration)+Cd(e.assetEffectInfo.startDelay));const i=f3(e,void 0,a,!0,r,n);return`
1060  `+(o!==null?q0e(t,o):"")+`
1061  `+TW(t)+`
1062  `+IW(t,e.customAttributes,e.deltas)+`
1063  `+i+`
1064  `},p3=(e,t)=>{const o=document.createElement("div"),r=Jle(e,t);return o.setAttribute("style",r),o},Xle=(e,t)=>{const o=document.createElement("div"),r=x3(e,t);return o.setAttribute("style",r),o},Jle=(e,t)=>{const o=e.width*t.width,r=e.height*t.height,n=e.xPos*t.width,a=e.yPos*t.height,{scaleX:i,scaleY:s}="editInfo"in e?tse(e.editInfo?.flip):{scaleX:1,scaleY:1};return Bl({position:"absolute",width:o+"px",height:r+"px",transform:"translate("+n+"px, "+a+"px) rotate("+e.rotation+"deg) scale("+i+", "+s+")"})},DI=e=>{const t=document.createElement("div");t.setAttribute("style",e);const o=X0e+"-"+ct();return t.setAttribute("id",o),[t,o]},kI=(e,t)=>{const o=e.width*t.width,r=e.xPos*t.width,n=e.yPos*t.height,a=Rv(t.width,t.height,e.scaleFactor);return Bl({position:"absolute",width:o/a+"px","transform-origin":"center",transform:axe(r,n,a,e.rotation)})},f3=(e,t,o,r=!1,n,a)=>{const i=new DOMParser,s=e.mediaId===Ao?Qc():a.find(c=>c.mediaId===e.mediaId)?.rawHtml??Qc(),x=i.parseFromString(C1(s),"text/html");for(const c in e.deltas){const l=document.createElement("div"),d=new t2(l);if(d.setContents(e.deltas[c]),e.assetEffectInfo&&nx(e.assetEffectInfo.type)&&o!==null&&n!==null){const E=R2(e.assetEffectInfo.type),T=d.getText();Tle({quill:d,text:T,currTime:o,animationName:E,animDuration:Ua(e.assetEffectInfo.duration),animStartDelay:ax(e.assetEffectInfo)?Cd(e.assetEffectInfo.startDelay):0,assetDuration:n,isStaticAnimation:r,isPau
1064sed:!1,isSelected:!1})}if(d.getText().replace(`
1065`,"").length===0)continue;const p=ov(l.getElementsByClassName("ql-editor")[0].innerHTML),f=x.querySelector("#"+c);if(t){const E=x.querySelector("."+e.mediaId);E&&E.classList.add(t)}f&&(f.innerHTML=p)}return x.documentElement.innerHTML};let OO;const aM=()=>(!OO&&(OO=new Qv(30)),OO),bi=e=>{const t=e.join("|");return new RegExp("\\.("+t+")$","i")};var qle=(e=>(e.AAC="aac",e.MP3="mp3",e.PCM="wav",e.FLAC="flac",e.OPUS="opus",e.VORBIS="vorbis",e))(qle||{});class g3{_worker=Vh(new Worker(new URL("/try/assets/mediaHandlerWorker-CYkB9vfb.js",import.meta.url),{type:"module"}));async init(t){await this._worker.init(PE(t))}async _toBlob(t){return typeof t=="string"?this.fetchBlobForPath(t):t}async getMediaFileInfo(t){const o=await this._toBlob(t),r=await this._worker.probeMediaInfo(o);if(r.videoInfo&&r.audioInfo)return{duration:r.duration,videoInfo:{size:{width:r.videoInfo.size.width,height:r.videoInfo.size.height,rotation:r.videoInfo.size.rotation,paspH:r.videoInfo.size.paspH,paspV:r.videoInfo.size.paspV},frameRate:r.videoInfo.frameRate,codec:r.videoInfo.codec,colorSpace:r.videoInfo.colorSpace?.[0],hasAlphaChannel:r.videoInfo.hasAlphaChannel,pixFmt:r.videoInfo.pixFmt},audioInfo:{sampleRate:r.audioInfo.sampleRate,codec:r.audioInfo.codec,channelCount:r.audioInfo.channelCount},mediaContainer:r.container};if(r.videoInfo)return{duration:r.duration,videoInfo:{size:{width:r.videoInfo.size.width,height:r.videoInfo.size.height,rotation:r.videoInfo.size.rotation,paspH:r.videoInfo.size.paspH,paspV:r.videoInfo.size.paspV},frameRate:r.videoInfo.frameRate,codec:r.videoInfo.codec,colorSpace:r.videoInfo.colorSpace?.[0],hasAlphaChannel:r.videoInfo.hasAlphaChannel,pixFmt:r.videoInfo.pixFmt},mediaContainer:r.container};if(r.audioInfo)return{duration:r.duration,audioInfo:{sampleRate:r.audioInfo.sampleRate,codec:r.audioInfo.codec,channelCount:r.audioInfo.channelCount},mediaContainer:r.container};throw new C(_.C_MEDIA_NO_AUDIO_VIDEO_TRACK)}async getAudioTrackNum(t){try{const o=await this._toBlob(t);return(await this._worker.probeMediaInfo(o)).audioTrackNum}catch{return 1}}async getVideoKeyFrameInterval(t){try{const o=await this._toBlob(t);return await this._worker.getVideoKeyFrameInterval(o)}catch{return 0}}async getTimecode(t){try{const o=await this._toBlob(t),r=await this._worker.getTimecode(o);return r||void 0}catch{return}}async getBitRate(t){const o=await this._toBlob(t);return(await this._worker.probeMediaInfo(o)).bitRate}async getColorSpace(t){try{const o=await this._toBlob(t);return(await this._worker.probeMediaInfo(o)).videoInfo?.colorSpace}catch{return}}async getAudioMetaInfo(t){try{const o=await this._toBlob(t),r=await this._worker.probeMediaInfo(o);return r.audioInfo?(r.audioInfo.codec=/^pcm_\s*/.test(r.audioInfo.codec)?"wav":r.audioInfo.codec,{duration:r.duration,sampleRate:r.audioInfo.sampleRate,codec:r.audioInfo.codec,channelCount:r.audioInfo.channelCount}):void 0}catch{return}}async getUnsupportedAudioStreamIndices(t){try{const o=await this._toBlob(t);return(await this._worker.probeMediaInfo(o)).unsupportedAudioStreamIndices}catch{return[]}}async extractAudio(t,o,r){const n=await this._worker.extractAudio(t,o,PE(r));return{codec:o,blob:n}}async convertToMP3(t,o,r,n){return await this._worker.convertToMP3(t,o,r,PE(n))}async sliceAudio(t,o,r,n){return await this._worker.sliceAudio(t,o,r,n)}async convertHLS(t){return await this._worker.convertHLS(t)}async getNumberOfChannels(t){const o=await this.fetchBlobForPath(t);return await this._worker.getNumberOfChannels(o)}async convertGifToWebm(t){return this._worker.convertGifToWebm(t)}}class Qle extends g3{async fetchBlobForPath(t){try{const o=await fetch(t);if(!o.ok)throw new Error("Failed to fetch file: "+o.statusText);return await o.blob()}catch(o){const r=o instanceof Error?o.message:"Unknown error";throw new Error("Failed to fetch file at "+t+": "+r)}}}class Zle extends g3{async fetchBlobForPath(t){const o=an(t);try{const r=await fetch(o);if(!r.ok)throw new Error("Failed to fetch file: "+r.statusText);return await r.blob()}catch(r){const n=r instanceof Error?r.message:"Unknown error";throw new Error("Failed to fetch file at "+t+": "+n)}}}let hp=null,Vd=null;const ix=async e=>
1065hp&&Vd===null?hp:Vd||(hp=at()?new Zle:new Qle,Vd=(async()=>(await hp.init(e),Vd=null,hp))(),Vd);class $le{get ready(){return!1}guessElapsed=()=>0;encodeUserVideos=()=>{throw new C(_.C_LOGIC_ERROR)};encode=()=>{throw new C(_.C_LOGIC_ERROR)};checkFfmpegExist=t=>Promise.resolve(!1);downloadFfmpeg=t=>Promise.resolve(!1);abort=()=>{throw new C(_.C_LOGIC_ERROR)};extractAudio=(t,o,r=!1,n=!1)=>{throw new C(_.C_LOGIC_ERROR)};sliceAudio=(t,o,r,n)=>{throw new C(_.C_LOGIC_ERROR)};extractAudioFragment=(t,o,r,n)=>{throw new C(_.C_LOGIC_ERROR)};clearExtractedAudioTempFile=()=>{throw new C(_.C_LOGIC_ERROR)};getMediaFileInfo=async t=>{const o=Ht(So.AUDIO_TEMP);return(await ix(o)).getMediaFileInfo(t)};getAudioTrackNum=()=>Promise.resolve(1);getMediaFileStartTimes=()=>Promise.resolve(void 0);getTimecode=()=>Promise.resolve(void 0);getRFrameRate=()=>Promise.resolve(void 0);getBitRate=async()=>{};getColorSpace=()=>Promise.resolve(void 0);getVideoKeyFrameInterval=()=>Promise.resolve(0);initAvailableHwAccel=()=>Promise.resolve(!0);updateAvailableHwAccel=t=>Promise.resolve(!0);getAvailableHwAccel=()=>gr.NONE;checkPhaseReverse=()=>Promise.resolve(!1);getAudioMetaInfo=t=>Promise.resolve(void 0);splitMedia=()=>Promise.resolve({paths:[]});getUnknownCodecAudioStream=()=>Promise.resolve([])}class ede{onWatch;totalImages;accumulatedImages;watchType;constructor(t,o){this.totalImages=t,this.accumulatedImages=0,this.watchType=o}watch=t=>{};next=t=>{this.accumulatedImages+=1,this.report()};reset=()=>{};report=()=>{this.onWatch&&this.onWatch(this.accumulatedImages,this.totalImages,this.watchType)}}class C0{static TimeExpression=/(\d+):(\d+):(\d+).(\d+)/;static MillisTable=[3600*1e3,60*1e3,1e3,1];onWatch;onResult;accumulatedMillis;totalMillis;watchType;constructor(t,o){this.totalMillis=t,this.accumulatedMillis=0,this.watchType=o}watch=t=>{const o=this.getMillis(t);o===void 0||o===0||this.report(o+this.accumulatedMillis)};result=(t,o)=>{this.onResult&&this.onResult(t,o)};next=t=>{this.accumulatedMillis+=t*1e3};reset=()=>{this.accumulatedMillis=0};getMillis(t){let o;if(!(typeof t=="string"&&(t.length<12?t+="0":t.length>12&&(t=t.substring(0,13)),o=t.match(C0.TimeExpression),!o)))return typeof t=="number"?t:o?.slice(1,5).reduce((r,n,a)=>r+ +n*C0.MillisTable[a],0)}report(t){if(!this.onWatch)return;let o=995,r=1e3;t/this.totalMillis<.995&&(o=t,r=this.totalMillis),this.onWatch(o,r,this.watchType)}}class tde{_listeners={};on(t,o){return!this._listeners[t]&&(this._listeners[t]=[]),this._listeners[t].push(o),this}off(t,o){if(!this._listeners[t])return this;const r=this._listeners[t].indexOf(o);return r!==-1&&this._listeners[t].splice(r,1),this}subscribe(t,o){return this.on(t,o),()=>this.off(t,o)}emit(t,...o){this._listeners[t]&&this._listeners[t].forEach(r=>{r(...o)})}clear(){this._listeners={}}}const aw="_proxy";var ode=(e=>(e.CHANGE="change",e))(ode||{});const rde=".mp4";class nc extends tde{static _instance=null;static _instancePromise=null;_registered=new Set;_active=new Set;_proxyDirPath="";_logger=h("ProxyFileManager.ts");isInitialized=!1;constructor(){super(),se().getEventEmitter().on(co.NEWFILE,(t,o,r)=>{r&&this.resetProxyActivation()}).on(co.VREW_FILE_OPENED,this.resetProxyActivation).on(co.TMP_PROJECT_OPENED,this.resetProxyActivation)}static async _createAndInit(){const t=new nc;return await t._init(),this._instance=t,t}static getInstance(){return this._instance?Promise.resolve(this._instance):this._instancePromise?this._instancePromise:(this._instancePromise=this._createAndInit(),this._instancePromise)}async _init(){try{const t=await Ue().initializeProxy();this._proxyDirPath=t.proxyDir,t.mediaIds.forEach(o=>this._registered.add(o)),this._logger.info("Proxy Manager initialized. "+t.mediaIds.length+" proxies"),this.isInitialized=!0}catch(t){this._logger.error("Failed to initialize proxy manager: "+P(t));const o=Ne(t)?t:new C(_.D_ERR_PROXY_DIR_INIT_FAILED),r=Ot(o.errorCode,{defaultKey:"error.proxy_dir_init_failed"});Y().error(o.errorCode,r)}}getProxySavePath(){return this._proxyDirPath}hasProxyFile(t){return this._registered.has(t)}registerProxyInfo(t){this._registered.add(t)}getInactivatedProxies(){return[...this._registered].filter(t=>!this._active.has(t))}getActivatedProxies(){return[...this._active]}setProxyActivation(t,o){if(!this._registered.has(t)){this._logger.warn("Proxy file for "+t+" not found");return}
1065o?this._active.add(t):this._active.delete(t),this.emit("change")}resetProxyActivation=()=>{this._active.clear(),this.emit("change")};getProxyFilePath(t){return jx.join(this._proxyDirPath,""+t+aw+rde)}cleanup(){this._registered.clear(),this._active.clear(),this.emit("change")}isProxyEnabled(){return this._active.size>0}}var Ur=(e=>(e.EXPORT="EXPORT",e.UPLOADING="UPLOADING",e.DENOISE="DENOISE",e.TTS="TTS",e.VCLOUD="VCLOUD",e.PROXY_VIDEO="PROXY_VIDEO",e.AUTO_SPLIT_SCENES="AUTO_SPLIT_SCENES",e.GENERATE_IMAGE="GENERATE_IMAGE",e.GENERATE_VIDEO="GENERATE_VIDEO",e.DUBBING="DUBBING",e.CAPTION_CORRECTION="CAPTION_CORRECTION",e.USER_TTS="USER_TTS",e.GENERATE_ASSETS="GENERATE_ASSETS",e.AI_STYLIZED_CAPTION="AI_STYLIZED_CAPTION",e))(Ur||{});const uot=async(e,t,o,r)=>{const n=h("proxyVideo.ts"),a=await nc.getInstance();if(await H0(V.TRANSCODING_VIDEO)===!1||e.fileLocation!==D.LOCAL&&e.fileLocation!==D.LOCAL_TMP)return;const i={origFile:e.path,totalSeconds:e.videoAudioMetaInfo.duration,videoSize:e.videoAudioMetaInfo.videoInfo?.size,mediaId:e.mediaId},{proxySetting:s,mediaPieces:x}=A_e(i),c=[],l={onCancel:()=>{},onStart:()=>{},onProgress:(f,E)=>{const T=E>0?f/E:0;r(T)},onEnd:(f,E)=>{c.push(...E),t()},onError:()=>{o()},onResult:()=>{}};if((await qt().encodeUserVideos(x,Kt.MP4,l,s)).type!==Dr.SUCCESS||c.length===0){n.info("Proxy video conversion failed or was canceled for "+e.mediaId+".");return}await qt().getMediaFileInfo(c[0]);const u={path:c[0]},p=ade(u.path);p&&a.registerProxyInfo(p)},nde=e=>{const n=Math.sqrt(518400/(e.width*e.height)),a=Math.floor(e.width*n),i=Math.floor(e.height*n),s=a-a%4,x=i-i%4;return{width:s,height:x}},ade=e=>{const t=e.split("/").pop();if(!t)return;const o=new RegExp("(.+)"+aw+"\\.mp4$"),r=t.match(o);if(r)return r[1]},ide=()=>{const e=se();return Oo()&&!e.isCloudProject()&&ca().some(E3)},_3=async(e,t)=>{e();const o=await nc.getInstance(),r=ca().filter(i=>!o.hasProxyFile(i.mediaId)&&E3(i));if(r.length===0){ide()&&t();return}const n=se().isCloudProject();if(o.isInitialized===!1||n)return;const a=ni.getInstance(Ur.PROXY_VIDEO);if(Qh(Ur.PROXY_VIDEO)){a.setPayload({files:r});return}a.openProgress({files:r,onDone:t})},sde=(e,t,o)=>{const r=Gae(t,o);return Wae(r,e+aw)},E3=e=>{const t=Hs(e.mediaId);if(t===void 0)return!1;const o=1e6,r=o*20,n=3840*2160,a=t.videoAudioMetaInfo.videoInfo;if(a===void 0)return!1;const i=a.size.width*a.size.height,s=t&&t.videoAudioMetaInfo.duration>0?O_e(t.fileSize,t.videoAudioMetaInfo.duration):o;return i>=n||s>=r},FI=e=>e.filter(t=>t.sourceType===de.VIDEO_AUDIO||t.sourceType===de.TTS),m3=e=>e.filter(t=>t.sourceType===de.TTS||t.sourceType===de.OVERDUB),UI=e=>e.filter(t=>t.sourceType===de.ASSET_VIDEO),h3=e=>e.filter(t=>t.sourceType===de.BGM||t.sourceType===de.SOUND_EFFECT||t.sourceType===de.TTS_EFFECT||t.sourceType===de.TTS_DUBBING),iw=e=>e.filter(t=>t.sourceType===de.IMAGE||t.sourceType===de.FILTER||t.sourceType===de.WATERMARK),sw=e=>e.filter(t=>t.sourceType===de.TEXTBOX),xde=1024;function cde(e){if(!(e.length<4||e[0]!==26||e[1]!==69||e[2]!==223||e[3]!==163)){for(let t=4;t+2<e.length;t++)if(e[t]===66&&e[t+1]===130){const o=e[t+2];if((o&128)===0)continue;const r=o&127,n=t+3;if(r<=0||n+r>e.length)continue;let a="";for(let i=0;i<r;i++)a+=String.fromCharCode(e[n+i]);return a}}}function lde(e,t){return e==="mkv"&&t==="webm"?"webm":e}const dde=(e,t,o)=>e.assetIds.flatMap(r=>{const n=L.get(t,r);return n?n.trackIds.flatMap(a=>{const i=L.get(o,a);return i&&mn(i)?[i]:[]}):[]}),VI=(e,t,o)=>{const r=dde(e,t,o);return r.length===1?r[0]:void 0},Gg=(e,t)=>{const o=Math.max(0,e);return pe(Math.max(0,t-o))},xw=(e,t,o)=>{if(kS(e,2)===kS(o,2))return null;const r=ur(kS(t/e,2));return!Number.isFinite(r)||r<fZ||r>gZ?null:r},ude=(e,t,o,r)=>{const n=VI(e,t,o);if(!n)return!1;const a=Gg(n.sourceIn,r);return xw(a,ac(e),pe(cs(e)))!==null},pde=(e,t)=>{const o=$X(e-t,2);return!Number.isFinite(o)||o<=U1||o>V1?null:pe(o)},fde=(e,t)=>{const o=Xy(e);return o===void 0?null:pde(Gg(e.sourceIn,o),t)},gde=(e,t,o,r,n)=>{let a=0;return{spacerTargets:e.map(s=>{if(s.insertionWordIndices.length!==1)return{...s,playDuration:n};const x=t[s.globalClipIndex];if(!x)return{...s,playDuration:n};const c=VI(x,o,r);if(!c)return{...s,playDuration:n};const l=fde(c,pe(cs(x)));return l===null?{...s,playDuration:n}:(a++,{...s,playDuration:l})}),autoFitApplied:a}},pot=(e,t,o)=>e.some(r=>{const n=VI(r,t,o);if(!n)return!1;const a=Xy(n);if(a===void 0)return!1;const i=Gg(n.sourceIn,a);return xw(i,ac(r),pe(cs(r)))!==null}),fot=(e,t,o,r,n)=>{const a=e*n;if(r===Fs.LOOP){if(o===0)return pe(t);const s=o-t;return a<s?pe(t+a):pe((a-s)%o)}const i=Math.max(0,o-t);return pe(t+Math.min(a,i))};var Kl=(e=>(e[e.WITH_CAPTION=0]="WITH_CAPTION",e[e.WITHOUT_CAPTION=1]="WITHOUT_CAPTION",e[e.IMAGE=2]="IMAGE",e[e.CAPTION_TRANSPARENT_VIDEO=3]="CAPTION_TRANSPARENT_VIDEO",e))(Kl||{});const _de=(e,t)=>{if(e.length!==t.length)return!1;const o=e.filter(x=>x.type===Ce.SIMPLE_CHARACTER),r=t.filter(x=>x.type===Ce.SIMPLE_CHARACTER);if(o.length!==r.length||!o.every(x=>r.some(c=>
1065Object.keys(c).every(d=>bc(c[d],x[d])))))return!1;let a=!0;for(let x=0;x<e.length;x++){const c=e[x];for(let l=0;l<t.length;l++){const d=t[l];if((c.type===Ce.WEB&&d.type===Ce.WEB||c.type===Ce.IMAGE&&d.type===Ce.IMAGE||c.type===Ce.SHAPE&&d.type===Ce.SHAPE)&&c.asset.mediaId===d.asset.mediaId&&(c.animationExportInfo?.animationInfo!==d.animationExportInfo?.animationInfo||c.animationExportInfo?.isDynamicInPiece!==d.animationExportInfo?.isDynamicInPiece)){a=!1;break}}}if(!a)return!1;const i=e.map(x=>x.asset),s=t.map(x=>x.asset);return i.every(x=>s.some(c=>Object.keys(c).every(d=>x[d]===c[d])))},Ede=(e,t,o)=>Object.keys(t).filter(a=>{const i=L.get(t,a);return i===void 0||i.role!=="sub"?!1:i.trackIds.map(x=>L.get(e,x)).some(x=>x&&s2(x))}).map(a=>o[Je(a)]).filter(Se),mde=(e,t,o)=>{const r=o+Rn(e);return t.some(n=>o<=n.timelineStart&&n.timelineStart<r||o<n.timelineEnd&&n.timelineEnd<=r||o>n.timelineStart&&r<n.timelineEnd)},hde=(e,t,o)=>{for(const r of e.assetIds){const n=L.get(t,r);if(n)return L.get(o,n)}},GI=(e,t,o,r,n,a,i,s,x,c,l,d=[])=>{const{captionStrings:u}=r,p=[];o.forEach(T=>{const O=L.get(t,T);O&&p.push(O.asset)});let f=a,E=0;return e.filter(T=>sr(T)!==0).map(T=>{const{wordSubAssetWithAssetIds:O,wordMainAssetWithAssetIds:S}=T.assetIds.reduce((j,$)=>{const q=L.get(t,$);return q&&(q.role==="sub"?j.wordSubAssetWithAssetIds.push(q.asset):j.wordMainAssetWithAssetIds.push(q.asset)),j},{wordSubAssetWithAssetIds:[],wordMainAssetWithAssetIds:[]}),R=[...p,...O].sort((j,$)=>j.asset.zIndex-$.asset.zIndex).map(j=>iM(j,Rn(T),f)).map(j=>bde(j,T,d,a+E)),y=r.exportCaptionModels.map(j=>{const{captionType:$}=j,q=_a(j),H=iM(q,Rn(T),f);return{...j,[$]:H}});let v;for(let j=R.length-1;j>=0;j--){const $=R[j];if(!(($.type===Ce.IMAGE||$.type===Ce.SHAPE)&&$.asset.assetEffectInfo)&&($.type===Ce.IMAGE||$.type===Ce.VIDEO)&&$.isTransparent===!1){const{xPos:q,yPos:H,width:U,height:te}=$.asset;if(q<=0&&H<=0&&q+U>=1&&H+te>=1){v=j;break}}}const w=v===void 0?R:R.slice(v),N=Rn(T),M=hde(T,s,x),k=S.find(j=>j.type===Ce.VIDEO),F=k??S.find(j=>j.type!==Ce.CAPTION&&j.type!==Ce.COMPOSITED_IMAGE),G=F?.asset.filterEffect,B=F?.asset,W=B&&lv(B)?Im(B.editInfo):void 0,Q={captions:u,exportCaptionModels:y,exportAssets:w,visualMedia:k?.asset.mediaId?{mediaId:k.asset.mediaId,start:k.asset.sourceIn,end:k.asset.sourceIn+N}:void 0,audioMedia:k?.asset.audio?.mediaId?{mediaId:k.asset.audio.mediaId,start:k.asset.audio.sourceIn,end:k.asset.audio.sourceIn+N}:void 0,clipIndex:n,playbackRate:Q0(T)?k?Sy:1:T.playbackRate,videoTransform:c,volume:k?.asset.audio?.volume,pieceTimelineInProject:f,timelineDuration:N,background:l,clipId:i,filterEffect:G,flip:W,wordIds:[T.id],exportOverdubInfo:M};return f+=N,E+=N,Q}).reduce((T,O)=>{const S=T[T.length-1],R=Pde(O,S);if(T.length>0&&R){const y=Rde(O,S),v=Mde(O,S);T.pop(),T.push({captions:u,exportCaptionModels:v,exportAssets:y,visualMedia:S.visualMedia&&O.visualMedia?{...S.visualMedia,end:S.visualMedia.end+(O.visualMedia.end-O.visualMedia.start)}:S.visualMedia?{...S.visualMedia,end:S.visualMedia.end+O.timelineDuration}:void 0,audioMedia:S.audioMedia&&O.audioMedia?{...S.audioMedia,end:S.audioMedia.end+(O.audioMedia.end-O.audioMedia.start)}:S.audioMedia?{...S.audioMedia,end:S.audioMedia.end+O.timelineDuration}:void 0,clipIndex:n,playbackRate:S.playbackRate,videoTransform:c,pieceTimelineInProject:S.pieceTimelineInProject,timelineDuration:S.timelineDuration+O.timelineDuration,background:l,clipId:i,filterEffect:S.filterEffect,flip:S.flip,volume:S.volume,wordIds:S.wordIds.concat(O.wordIds)})}else T.push(O);return T},[])},Ide=(e,t,o,r,n,a=[])=>ty(e.map((i,s)=>{const x=i.backgroundId?L.get(n,i.backgroundId):void 0;return GI(i.words,t,i.assetIds,{captionStrings:[],exportCaptionModels:[]},s,vo(i),i.id,o,r,i.videoTransform,x,a)})),Tde=(e,t,o,r,n,a,i,s,x=[])=>ty(e.map((c,l)=>{const d=c.backgroundId?L.get(n,c.backgroundId):void 0;return GI(c.words,t,c.assetIds,Ew(c,a,i,s),l,vo(c),c.id,o,r,c.videoTransform,d,x)})),Sde=(e,t,o,r,n,a,i,s,x=[])=>e.map((c,l)=>{const d=c.backgroundId?L.get(n,c.backgroundId):void 0;return GI(c.words,t,c.assetIds,Ew(c,a,i,s),l,vo(c),c.id,o,r,c.videoTransform,d,x)[0]}
1065),Ode=(e,t,o,r,n,a,i,s=[])=>{const x=c=>{const l=L.get(t,c)?.asset;return l&&(Wn(l.asset)||f0(l.asset))};return ty(e.map((c,l)=>{const d=c.assetIds.filter(x),u=c.words.map(p=>({...p,assetIds:p.assetIds.filter(x)}));return GI(u,t,d,Ew(c,o,r,n),l,vo(c),c.id,a,i,void 0,void 0,s)}))},WI=(e,t,o,r,n,a,i,s,x,c)=>{switch(a){case 0:return Tde(e,t,o,r,n,i,s,x,c);case 1:return Ide(e,t,o,r,n,c);case 2:return Sde(e,t,o,r,n,i,s,x,c);case 3:return Ode(e,t,i,s,x,o,r,c)}},iM=(e,t,o)=>{if(!Ele(e))return e;if(e.animationExportInfo!==void 0&&e.animationExportInfo.animationInfo!==void 0){const r=e.animationExportInfo.startTimelineTime,n=e.animationExportInfo.duration,a=e.animationExportInfo.animationInfo,i=e.animationExportInfo.assetId,s=Cde(o,t,r,n,a,i);return{...e,animationExportInfo:s}}return e},Cde=(e,t,o,r,n,a)=>{const i=Cn(10),{type:s}=n;if(as(s))return mp({isDynamicInPiece:!0,pieceStart:e,pieceDuration:t,assetStart:o,assetDuration:r,animationInfo:n,assetId:a,uniqueId:i});const x=o+r,c=e+t,l=Math.max(0,x-Ua(n.duration)),d=ax(n)?Cd(n.startDelay):0,u=Ua(n.duration),p=Math.max(0,r-d),f=Math.min(p,u),E=o+d+f,T=e<E&&o<c,O=e<x&&l<c;return Jr(s)&&d>0&&(T||O)?mp({isDynamicInPiece:!0,pieceStart:e,pieceDuration:t,assetStart:o,assetDuration:r,animationInfo:n,assetId:a,uniqueId:i}):T&&(El(s)||Jr(s)||nx(n.type))?mp({isDynamicInPiece:!0,pieceStart:e,pieceDuration:t,assetStart:o,assetDuration:r,animationInfo:Jr(s)&&d===0?{type:Me.FADE_IN,duration:n.duration,startDelay:wh}:n,assetId:a,uniqueId:i}):O&&(W0(s)||Jr(s))?mp({isDynamicInPiece:!0,pieceStart:e,pieceDuration:t,assetStart:o,assetDuration:r,animationInfo:Jr(s)&&d===0?{type:Qe.FADE_OUT,duration:n.duration}:n,assetId:a,uniqueId:i}):mp({isDynamicInPiece:!1,pieceStart:e,pieceDuration:t,assetStart:o,assetDuration:r,animationInfo:void 0,assetId:a,uniqueId:i})},Rde=(e,t)=>e.exportAssets.map(o=>{if(!tM(o))return o;const r=t.exportAssets.filter(tM).find(n=>n.animationExportInfo?.assetId===o.animationExportInfo?.assetId&&n.animationExportInfo?.animationInfo===o.animationExportInfo?.animationInfo);return r===void 0?o:r.animationExportInfo&&o.animationExportInfo&&r.animationExportInfo.pieceDuration&&o.animationExportInfo.pieceDuration?{...r,animationExportInfo:{...r.animationExportInfo,pieceDuration:r.animationExportInfo.pieceDuration+o.animationExportInfo.pieceDuration}}:r}),Lp=e=>e.reduce((t,o)=>t+(o.visualMedia?o.visualMedia.end-o.visualMedia.start:o.audioMedia?o.audioMedia.end-o.audioMedia.start:o.timelineDuration),0),HI=e=>{const t=new Set,o=new Set;return e.forEach(r=>{r.visualMedia&&t.add(r.visualMedia.mediaId),r.audioMedia&&t.add(r.audioMedia.mediaId),r.exportAssets.forEach(n=>o.add(n.asset.mediaId))}),{mediaIds:Array.from(t.values()).filter(r=>r.length>0),assetMediaIds:Array.from(o.values()).filter(r=>r.length>0)}},Ade=e=>{const{asset:t}=e,o=J0(t)?t.sourceIn:0,r=e.type===Ce.VIDEO?eo(t.mediaId)?.videoAudioMetaInfo.duration:e.type===Ce.SIMPLE_CHARACTER?e.webmDuration??null:null;return{frontOffset:o,duration:r}},yde=(e,t)=>{const o=(e.pieceTimelineInProject??0)-t,{visualMedia:r}=e,n=r?.start??0,a=r?.end??e.timelineDuration;e.exportAssets=wde(e.exportAssets,{pieceTimelineTime:o,pieceStart:n,pieceEnd:a,playbackRate:e.playbackRate})},vde=2,wde=(e,t)=>{const{pieceTimelineTime:o,pieceStart:r,pieceEnd:n,playbackRate:a}=t,i=[];return e.forEach(s=>{if(s.type!==Ce.VIDEO&&s.type!==Ce.SIMPLE_CHARACTER){i.push(s);return}const{frontOffset:x,duration:c}=Ade(s);if(!c){i.push(s);return}const{timelineStart:l,timelineEnd:d}=s.videoExportInfo,u=ue(x+(o-l),3),p=ue(u+(n-r),3),f=u<0?-u:0,E=QCe(u+f,p+f,c);if(s.type===Ce.VIDEO&&s.asset.endBehavior===Fs.FREEZE){const S=s.asset,R=Number.isFinite(c??NaN)?pe(c):pe(0),y=Gg(S.sourceIn,R);if(y<=0){const{start:w,end:N}=AD(u+f,p+f,c);i.push({...s,videoExportInfo:{timelineStart:l,timelineEnd:d,revisedStart:w,revisedEnd:N,startOffsetInPiece:0,videoLoopMode:qn.NO_LOOP}});return}const v=(n-r-y)/a;if(Number.isFinite(v)&&v>0){const w={timelineStart:l,timelineEnd:d,revisedStart:Math.max(0,x),revisedEnd:Math.max(0,x)+y,startOffsetInPiece:0,videoLoopMode:qn.FREEZE,freezeDurationSec:v};i.push({...s,videoExportInfo:w});return}}
1065const T=E.length<=1?qn.NO_LOOP:E.length<=vde?qn.MANUAL_LOOP:qn.STREAM_LOOP;switch(T){case qn.NO_LOOP:case qn.STREAM_LOOP:{const{start:O,end:S}=AD(u+f,p+f,c),R={timelineStart:l,timelineEnd:d,revisedStart:O,revisedEnd:S,startOffsetInPiece:0,videoLoopMode:T},y={...s,videoExportInfo:R};i.push(y);break}case qn.MANUAL_LOOP:{let O=0;E.forEach(S=>{const{start:R,end:y}=S,v={timelineStart:l,timelineEnd:d,revisedStart:R,revisedEnd:y,startOffsetInPiece:O,videoLoopMode:T},w={...s,videoExportInfo:v};i.push(w),O=O+(y-R)})}}}),i},Nde=(e,t)=>t?e.exportCaptionModels.every((r,n)=>{const a=t.exportCaptionModels[n],i=_a(a),s=_a(r);return s.asset.mediaId!==i.asset.mediaId?!1:s.animationExportInfo.animationInfo===void 0&&i.animationExportInfo.animationInfo===void 0?!0:!(s.animationExportInfo.animationInfo===void 0||i.animationExportInfo.animationInfo===void 0||s.animationExportInfo.animationInfo!==i.animationExportInfo.animationInfo||s.animationExportInfo.animationInfo===i.animationExportInfo.animationInfo&&s.animationExportInfo.isDynamicInPiece!==i.animationExportInfo.isDynamicInPiece)}):!1,Pde=(e,t)=>{if(!t)return!1;const o=t.visualMedia?t.visualMedia.start+t.timelineDuration*t.playbackRate:0,r=t.audioMedia?t.audioMedia.start+t.timelineDuration*t.playbackRate:0;let n=!1;if(e.visualMedia===void 0&&e.audioMedia===void 0&&(t.visualMedia===void 0&&t.audioMedia===void 0&&(n=!0),!n)){const l=t.audioMedia?Yu(t.audioMedia.mediaId):void 0;l?.sourceType===de.TTS&&(Math.abs(l.videoAudioMetaInfo.duration-r)<b0||l.videoAudioMetaInfo.duration<r)&&(n=!0)}if(!n){const l=e.visualMedia?.mediaId===t.visualMedia?.mediaId&&e.audioMedia?.mediaId===t.audioMedia?.mediaId,d=Math.abs((e.visualMedia?.start??0)-o)<b0&&Math.abs((e.audioMedia?.start??0)-r)<b0;if(!l||!d)return!1}const a=(e.volume??ma)===(t.volume??ma),i=e.playbackRate===t.playbackRate,s=bc(e.filterEffect,t.filterEffect),x=e.exportOverdubInfo||t.exportOverdubInfo;return!a||!i||!s||x||!Nde(e,t)?!1:_de(e.exportAssets,t.exportAssets)},bde=(e,t,o,r)=>{if(e.type===Ce.SIMPLE_CHARACTER){const n=t.type===Z.NORMAL||mde(t,o,r),a=n&&e.webmDuration!==void 0&&e.asset.isMouthApplied?e.asset.pose.speakingMediaId:e.asset.pose.silentMediaId;if(!a)throw new C(_.C_LOGIC_ERROR,{},"[updateSimpleCharExportAsset] Cannot find mediaId for simple character. appearance: "+e.asset.mediaId+". wordType:"+n+" ");return{...e,mediaId:a,isVoiceWord:n,asset:{...e.asset,mediaId:a}}}return e},Lde=(e,t)=>{if(e.visualMedia!==void 0||e.audioMedia!==void 0)return!0;const o=e.timelineDuration;for(const r of e.exportAssets){if(r.type!==Ce.VIDEO||r.asset.sourceIn!==0)continue;const n=t.find(i=>i.mediaId===r.asset.mediaId),a=n?.videoAudioMetaInfo.duration||0;if(Math.abs(a-o)<b0)return!1}return!0},Mde=(e,t)=>e.exportCaptionModels.map((r,n)=>{const a=t.exportCaptionModels[n],i=_a(a),s=_a(r);if(s.animationExportInfo&&i.animationExportInfo&&s.animationExportInfo.animationInfo===i.animationExportInfo.animationInfo&&s.animationExportInfo.pieceDuration&&i.animationExportInfo.pieceDuration){const x={...i,animationExportInfo:{...i.animationExportInfo,pieceDuration:i.animationExportInfo.pieceDuration+s.animationExportInfo.pieceDuration}};return{...a,[a.captionType]:x}}return r});function Dde(e){return e?e.alpha_mode==="1"||e.ALPHA_MODE==="1":!1}class ut{inNodes;filter;resolvedArgs;constructor(t,o,r){this.inNodes=r,this.filter=t,this.resolvedArgs=Object.keys(o).map(n=>n!==""?n+"="+o[n]:o[n]).join(":")}build(t=!0){const o=this.inNodes.length>1,r=t?" [node_out]":"";if(!o){const s=this.inNodes[0];if(s instanceof ut){const x=this.resolvedArgs?this.filter+"="+this.resolvedArgs:this.filter;return s.build(!1)+", "+x+r}return"["+s+"] "+this.filter+"="+this.resolvedArgs+r}const n=this.inNodes.filter(s=>s instanceof ut),a=n.map(s=>s.build(!1)).map((s,x)=>s+" [node"+x+"];").join(`
1066`)+`
1067`,i=this.inNodes.map(s=>s instanceof ut?"[node"+n.indexOf(s)+"]":"["+s+"]").join("");return""+a+i+" "+this.filter+"="+this.resolvedArgs+r}}const kde=2,Fde=e=>e.replace(/\\/g,"\\\\\\\\").replace(":","\\\\:").replace(/'/g,"\\\\\\'"),Ude=(e,t=0)=>{const r=Math.max(0,e-.2),n=new ut("trim",{start:r,end:e},[t]),a=new ut("reverse",{},[n]),i=new ut("select",{expr:"eq(n\\,0)"},[a]);return new ut("setpts",{expr:"PTS-STARTPTS"},[i])},jI=(e,t,o,r,n,a,i,s,x,c,l,d,u,p,f,E,T=0,O=1,S)=>{const{scaledSize:R,videoTransformInfo:y}=y_e(e,l,x,p),v=lw(i),{zoomX:w,zoomY:N,xPos:M,yPos:k}=y,F=R.width*w,G=R.height*N,B=Du(r)?Ude(v,T):T,W=S===void 0?Vw(c):"#00000000",Q=new ut("fps",{fps:o,start_time:0},[B]),j=u===Go.VERTICAL||u===Go.VERTICAL_HORIZONTAL?new ut("vflip",{},[Q]):Q,$=u===Go.HORIZONTAL||u===Go.VERTICAL_HORIZONTAL?new ut("hflip",{},[j]):j,q=p?.rotation??0,H=q*Math.PI/180,U=p?.rotation?new ut("rotate",{angle:H,ow:"rotw("+H+")",oh:"roth("+H+")"},[$]):$,te=(q>180?360-q:q)*Math.PI/180,ne=Math.abs(Math.cos(te)),oe=Math.sin(te),re=(l?.width??1)/(l?.height??1),ge=ne+oe/re,fe=ne+oe*re,ve=(()=>
1067{if(!E)return U;const Sn=new ut("zscale",{t:"linear"},[U]),mr=new ut("format",{"":"gbrpf32le"},[Sn]),Wi=new ut("zscale",{p:Ji.BT709},[mr]),dr=new ut("tonemap",{tonemap:"hable",desat:"0"},[Wi]);return new ut("zscale",{t:Ji.BT709},[dr])})(),yt=new ut("scale",{w:F*ge,h:G*fe,...E?{}:{in_color_matrix:"input",out_color_matrix:"bt709"}},[ve]),Le=(ge-1)/2*F,We=(fe-1)/2*G,kt=(()=>{if(p===void 0)return yt;const Sn=(M+w-1)*R.width+Le>0,mr=M*R.width-Le<0,Wi=(k+N-1)*R.height+We>0,dr=k*R.height-We<0,Hi=Math.floor(F*ge-(Sn?Le+(M+w-1)*R.width:0)-(mr?Le+-M*R.width:0)),ji=Math.floor(G*fe-(Wi?We+(k+N-1)*R.height:0)-(dr?We+-k*R.height:0));if(Hi<2||ji<2){const cc=new ut("drawbox",{w:2,h:2,x:0,y:0,color:W},[Q]);return new ut("crop",{w:2,h:2,x:0,y:0},[cc])}if(!dr&&!Sn&&!Wi&&!mr)return yt;const xp=mr?Le-M*R.width:0,cp=dr?We-k*R.height:0;return new ut("crop",{w:Hi,h:ji,x:xp,y:cp},[yt])})(),bt=(()=>{if(!p)return kt;const Sn=(M+w-1)*R.width+Le>0,mr=M*R.width-Le<0,Wi=(k+N-1)*R.height+We>0,dr=k*R.height-We<0;if(dr&&Sn&&Wi&&mr)return kt;const Hi=mr?0:Math.floor(R.width*M)-Le,ji=dr?0:Math.floor(R.height*k)-We;return new ut("pad",{w:R.width,h:R.height,x:Hi,y:ji,color:W},[kt])})(),Jt=new ut("pad",{w:e.width,h:e.height,x:"(ow-iw)/2",y:"(oh-ih)/2",color:W},[bt]),Ft=new ut("tpad",{stop:-1,stop_mode:"clone"},[Jt]),Pe=Du(r)||r===1?Ft:new ut("setpts",{expr:(1/r).toFixed(3)+"*PTS"},[Ft]),_t=d?new ut("lut3d",{file:Fde(d),interp:"trilinear"},[Pe]):Pe,No=new ut("setsar",{sar:"1/1"},[_t]),ko=S===void 0?No:new ut("overlay",{x:0,y:0},[S,No]),dt=t.reduce((Sn,mr,Wi)=>{const{asset:dr}=mr;if(f0(dr)||Wn(dr)||Gn(dr)&&dr.assetEffectInfo&&mr.type===Ce.IMAGE&&mr.animationExportInfo){const Rl=new ut("scale",{w:e.width,h:e.height,in_range:"pc",in_color_matrix:"rgb",out_color_matrix:"bt709"},[O+Wi]);return new ut("overlay",{x:0,y:0},[Sn,Rl])}const Hi="editInfo"in dr?dr.editInfo:void 0,ji=pg(Hi?.crop),xp=1-ji.left-ji.right,cp=1-ji.top-ji.bottom,cc=Math.round(dr.width*e.width),Ld=Math.round(dr.height*e.height),lp=Math.round(cc/xp),dp=Math.round(Ld/cp),up=Math.round(dr.xPos*e.width+cc/2),pp=Math.round(dr.yPos*e.height+Ld/2),RS=Math.round(dr.rotation*3.14/180*100)/100;if(Gn(dr)&&dr.kenburnsAnimationInfo&&mr.type===Ce.IMAGE&&mr.animationExportInfo){const Rl=due({...dr.kenburnsAnimationInfo,...mr.animationExportInfo},Wi,s,n,a,o,lp,dp,i||void 0,O),gp=pM(Rl,ji,cc,Ld),_p=dr.rotation*Math.PI/180,L_=uM(gp,Im(Hi)),M_=YR(L_,_p),D_=Hi?.opacity??Cb,LS=D_!==1?new ut("colorchannelmixer",{aa:D_.toFixed(2)},[new ut("format",{pix_fmts:"rgba"},[M_])]):M_;return new ut("overlay",{x:up+"-w/2",y:pp+"-h/2"},[Sn,LS])}const v_=mr.type===Ce.VIDEO||mr.type===Ce.SIMPLE_CHARACTER&&rge(mr)?mr:null,lc=v_?.videoExportInfo,Md=(lc?.startOffsetInPiece??0)+v,AS=lc?.revisedStart??0,yS=lc?.revisedEnd??0,w_=yS-AS,vS=lc?gue(new ut("fps",{fps:o,start_time:0},[O+Wi]),lp,dp):O3(O+Wi,lp,dp),wS=pM(vS,ji,cc,Ld),NS=uM(wS,Im(Hi)),N_=YR(NS,RS),P_=Hi?.opacity??Cb,fp=P_!==1?new ut("colorchannelmixer",{aa:P_.toFixed(2)},[new ut("format",{pix_fmts:"rgba"},[N_])]):N_,PS=(Rl,gp,_p)=>Math.abs(Rl+gp-_p)<1e-6,b_=lc?.videoLoopMode??qn.NO_LOOP,Dd=lc?.freezeDurationSec,bS=b_===qn.FREEZE&&typeof Dd=="number"&&Number.isFinite(Dd)&&Dd>0?new ut("tpad",{stop_mode:"clone",stop_duration:Dd},[fp]):fp;return v_&&b_===qn.MANUAL_LOOP?new ut("overlay",{x:up+"-w/2",y:pp+"-h/2",enable:PS(Md,w_,a)?"gte(t\\,"+Md.toFixed(3)+")":"'between(t\\,"+Md.toFixed(3)+","+(Md+w_).toFixed(3)+")'"},[Sn,fp]):new ut("overlay",{x:up+"-w/2",y:pp+"-h/2"},[Sn,bS])},ko),vr=O+t.length;return{videoFilterOptions:(f?_ue(f,dt,e,vr):dt).build(),outFilterName:"[node_out]"}},sM=(e,t,o,r,n)=>{const a=t[e.mediaId],i=e.type;if(!a){const O="No "+i+" path found for mediaId "+e.mediaId+" in "+i+"Paths "+JSON.stringify(t)+", "+i+" "+JSON.stringify(e)+`
1068  `;if(i===z.VIDEO)throw new C(_.C_VIDEO_ASSET_LOST,{},O);if(i===z.SIMPLE_CHARACTER)throw new C(_.C_CHARACTER_ASSET_LOST,{},O)}const s=1,x=Math.max(o-s,0),c=o-x,l=r===qn.STREAM_LOOP?["-stream_loop","-1"]:[],d=x?["-ss",x.toFixed(3)]:[],u=c?["-itsoffset",(-c).toFixed(3)]:[],p=n?.[e.mediaId],f=mn(e)&&(p!==void 0?p:e.hasAlphaChannel),E=f||Tg(e)?["-c:v","libvpx-vp9"]:[],T=["-i",a];return[...l,...d,...u,...E,...T]},CO=e=>
1068["-i",e],Vde=(e,t,o)=>{if(e.type!==Ce.WEB&&e.type!==Ce.IMAGE)return["-itsoffset",""+o];if(e.type===Ce.WEB&&e.asset.durationSeconds===0&&e.asset.assetEffectInfo===void 0||e.animationExportInfo===void 0)return["-itsoffset",""+o];const{startTimelineTime:r,animationInfo:n}=e.animationExportInfo,a=t-r,i=n!==void 0&&(El(n.type)||W0(n.type)||nx(n.type)),s=n!==void 0&&Jr(n.type);if(i||s)return["-itsoffset",""+o];if(n!==void 0&&as(n.type)){const c=ue(a%Ua(n.duration),3);return["-itsoffset",(o-c).toFixed(3)]}if(Wn(e.asset)){const c=ue(e.asset.loop?a%e.asset.durationSeconds:a,3);return["-itsoffset",(o-c).toFixed(3)]}return["-itsoffset",""+o]},Gde=(e,t)=>t.type!==Ce.WEB&&t.type!==Ce.IMAGE&&t.type!==Ce.SHAPE&&t.type!==Ce.CAPTION?!1:e.loop,Wde=(e,t,o,r)=>{const n=["-framerate",""+e.frameRate],a=Gde(e,o)?["-loop","1"]:[],i=Vde(o.type===Ce.CAPTION?_a(o):o,r,t),s=["-i",e.frameFormat];return[...n,...a,...i,...s]},zI=(e,t,o,r,n,a,i)=>e.flatMap(s=>{const{asset:x}=s;if(s.type===Ce.COMPOSITED_IMAGE)return CO(s.path);if(Tg(x)){const l=s.asset.mediaId,d=t[l];if(d)return CO(d);if(r[l]){const p=s.videoExportInfo,f=p?.revisedStart??0,E=(p?.startOffsetInPiece??0)+n,T=f-E,O=p?.videoLoopMode??qn.NO_LOOP;return sM(x,r,T,O,i)}throw new C(_.C_LOGIC_ERROR,{},"No path found for simpleCharacter "+l)}if(Gn(x)&&x.assetEffectInfo===void 0){const l=t[s.asset.mediaId];if(!l)throw new C(_.C_LOGIC_ERROR,{},"No image path found for image "+s.asset.mediaId);return CO(l)}if(J0(x)){const l=s.videoExportInfo,d=l?.revisedStart??0,u=(l?.startOffsetInPiece??0)+n,p=d-u,f=l?.videoLoopMode??qn.NO_LOOP;return sM(x,r,p,f,i)}const c=o[r3(s)];if(c===void 0)throw new C(_.C_LOGIC_ERROR,{},"Cannot find rendered asset frame for asset "+s.asset.mediaId+" with type "+s.type);return Wde(c,n,s,a)}),Hde=(e,t,o)=>o?["-loop","1","-i",o]:["-f","lavfi","-i","color=color="+Vw(t)+":size="+e.width+"x"+e.height],jde=(e,t,o,r,n,a,i,s,x,c,l,d,u,p,f,E,T,O,S,R,y,v,w,N,M,k,F,G,B)=>{const W=n-r,Q=F===!0&&a!==Kt.MP4,j=F===!0&&a===Kt.MP4,$=Q||j,q=R?KI(r):null,H=lw(q),U=j?1:0,{videoFilterOptions:te,outFilterName:ne}=jI(x,p,f,E,T,W,q,O,S,y,c,v,w,N,M,k,U,U+1,j?0:void 0),oe=zI(p,l,d,u,H,O,G),re=M?["-i",M.watermarkPath]:[],ge=q?q.inputSeek:r,fe=j?Hde(x,y,B):[];return[["-hide_banner"],["-y"],["-max_error_rate","1"],fe,["-ss",ge.toFixed(3)],$?["-c:v","libvpx-vp9"]:[],["-i",e],oe,re,q?["-ss",q.outputSeek.toFixed(3)]:[],["-t",W.toFixed(3)],["-filter_complex",te],a===Kt.MP4?BI(s,i,x,c,t):["-c:v",Q?"libvpx-vp9":"libvpx"],["-pix_fmt",Q?"yuva420p":"yuv420p"],["-colorspace","bt709"],["-color_primaries","bt709"],["-color_trc","bt709"],["-preset","fast"],["-an"],["-map",ne],[o]].flat()},I3=(e,t,o)=>{const r=Vw(o);return[["-hide_banner"],["-y"],["-max_error_rate","1"],["-f","lavfi","-i","color=color="+r+":size="+t.width+"x"+t.height],["-frames:v","1"],[e]].flat()},zde=(e,t,o,r,n,a,i,s,x,c,l,d,u,p,f,E,T,O,S,R)=>{const y=T?KI(a):null,v=lw(y),{videoFilterOptions:w,outFilterName:N}=jI(s,x,u,p,f,i-a,y,E,he.INIT,O,void 0,void 0,void 0,void 0,S),M=y!==null?y.inputSeek:a,k=zI(x,c,l,d,v,E,R),F=S?["-i",S.watermarkPath]:[];return[["-hide_banner"],["-y"],["-max_error_rate","1"],["-loop","1"],["-ss",M.toFixed(3)],["-i",t],k,F,y!==null?["-ss",y.outputSeek.toFixed(3)]:[],["-t",(i-a).toFixed(3)],["-filter_complex",w],BI(n,r,s,s,o),["-pix_fmt","yuv420p"],["-colorspace","bt709"],["-color_primaries","bt709"],["-color_trc","bt709"],["-an"],["-map",N],[e]].flat()},T3=(e,t,o,r,n,a,i,s,x)=>{const c=r-o,l=n===1&&x===void 0,d=KI(o),u=l?d.inputSeek:o,p=[],f=rue(n);p.push(...f),p.push("apad"),x!==void 0&&x!==ma&&p.push("volume="+x.toFixed(3)),p.push("aresample=async=1000"),p.push("asetpts=PTS-STARTPTS");const E=p.join(","),T=s?dw(e):void 0;return[["-hide_banner"],["-y"],["-max_error_rate","1"],["-ss",u.toFixed(3)],T?["-f",T]:[],["-i",e],l?["-ss",d.outputSeek.toFixed(3)]:[],["-t",c.toFixed(3)],p.length>0?["-filter:a",E]:[],["-vn"],i?["-ar",""+i]:[],a?["-ac","2"]:[],["-c:a","pcm_s16le"],["-map","0:a"],[t]].flat()},bm=(e,t,o)=>{const r=o||zx,n="anullsrc=channel_layout=stereo:sample_rate="+r;return[["-hide_banner"],["-y"],["-f","lavfi"],["-i",n],["-t",e.toFixed(3)],["-ac","2"],["-c:a","pcm_s16le"],[t]].flat()},S3=(e,t,o)=>[["-hide_banner"],["-y"],t!==null?["-i",t]:[],["-i",e],t!==null?["-c:v","copy"]:["-vn"],["-c:a","pcm_s16le"],["-af","afade=d=0.001, areverse, afade=d=0.001, areverse"],t!==null?["-map","0:v:0","-map","1:a?"]:[],[o]].flat(),YI=e=>{const t=o=>o.replace(/'/g,"'\\''");return e.map(o=>"file '"+t(o)+"'").join(`
1069`)},cw=(e,t,o,r)=>{const n=ry.test(o),a=ny.test(o),i=oy.test(o),s=i?void 0:Eue(t),x=s?[s.type==="simple"?"-af":"-filter_complex",s.filter]:[],c=s?["-map",s.type==="simple"?"0:a?":"[n
1069ode_out]:a"]:[],l=r?["-metadata","comment="+r]:[];return[["-hide_banner"],["-y"],["-safe","0"],["-f","concat"],["-i",e],t?["-i",t]:[],n?[]:["-c:v","copy"],x,n?[]:["-map","0:V"],c,t?["-ac","2"]:[],a?["-b:a","320k","-write_xing","0"]:[],["-map_chapters","-1"],l,[o]].flat()},Yde=(e,t,o,r,n,a,i,s)=>{const x=e===CR.PNG?"png":"prores_ks",c=e===CR.PNG?[]:["-pix_fmt","yuva444p10le","-profile:v","4444"],l=zI(t,{},o,{},0,i),{videoFilterOptions:d,outFilterName:u}=jI(r,t,hU,1,a,a,null,0,he.INIT,{type:k0.SOLID,color:"#00000000"},void 0),p=[["-f","lavfi"],["-i","[email protected]:size="+r.width+"x"+r.height+",format=rgba"]].flat();return[["-hide_banner"],["-y"],p,l,["-an"],["-t",a.toFixed(3)],["-s",r.width+"x"+r.height],d?["-filter_complex",d]:[],["-c:v",x],c,["-r",""+s],["-map",u],[n]].flat()},Bde=(e,t)=>[["-hide_banner"],["-y"],["-f","concat"],["-safe","0"],["-i",e],["-c","copy"],[t]].flat(),va=(e,t)=>{let r=null,n=!1,a=!1,i=!1,s=!1;switch(t){case Io.DURATION:r="format=duration";break;case Io.R_FRAME_RATE:n=!0,r="stream=r_frame_rate";break;case Io.TIMECODE_ALLTRACK:case Io.TIMECODE_VIDEOTRACK:n=t===Io.TIMECODE_VIDEOTRACK,r="stream_tags=timecode";break;case Io.BITRATE:r="format=bit_rate";break;case Io.CODEC_STRINGS:r="stream=codec_tag_string";break;case Io.SAMPLE_RATE:r="stream=sample_rate";break;case Io.AUDIO_STREAM:r="stream",s=!0;break;case Io.NUM_FRAMES:r="stream=nb_frames";break;case Io.COLOR_SPACE:n=!0,r="stream=pix_fmt,color_space,color_range";break;case Io.SAMPLED_PACKETS_INFO:n=!0,a=!0,i=!0,r="packet=flags,pts_time";break;case Io.AUDIO_CODEC:s=!0,r="stream=index,codec_name",i=!0;break;case Io.AUDIO_CHANNEL_COUNT:s=!0,r="stream=channels";break;default:return[]}const x=[["-loglevel","error"],["-show_entries",r],["-print_format",i?"json":"default=noprint_wrappers=1:nokey=1"],[e]];return n?x.unshift(["-select_streams","v"]):s&&x.unshift(["-select_streams","a"]),a&&x.unshift(["-read_intervals","0%180"]),x.flat()},Kde=(e,t,o,r,n,a,i)=>{const s=r||a?[]:["-ac","1"],x=r?["-c:a","copy"]:["-c:a",o],c=!r&&i?["-af","aresample=first_pts=0"]:[],l=n?["-xerror"]:[],d=o===Gt.MP3?["-b:a","320k"]:[];return[["-hide_banner"],["-y"],["-max_error_rate","1"],["-i",e],["-vn"],[...s],[...x],[...c],[...l],[...d],[t]].flat()},Xde=(e,t,o,r)=>[["-hide_banner"],["-y"],["-max_error_rate","1"],["-i",e],["-vn"],["-ss",o.toString()],["-t",r.toString()],["-c","copy"],[t]].flat(),Jde=(e,t,o,r,n)=>[["-hide_banner"],["-y"],["-max_error_rate","1"],["-ss",r.toString()],["-i",e],["-vn"],["-t",n.toString()],["-ac","1"],["-af","aresample=async=1000"],o?["-c:a",o]:[],[t]].flat(),qde=(e,t,o,r,n,a,i,s,x,c)=>{const l=r?BI(o,a,r,void 0,i):["-c:v","h264","-crf",""+a],d=["zscale=t=linear","format=gbrpf32le","zscale=p="+Ji.BT709,"tonemap=tonemap=hable:desat=0","zscale=t="+Ji.BT709],u=n?"scale='trunc(iw*sqrt("+n+"/(iw*ih))/4)*4:trunc(ih*sqrt("+n+"/(iw*ih))/4)*4'":void 0,p=[s?d:"scale=in_color_matrix=input:out_color_matrix="+Ji.BT709,u,"pad=ceil(iw/2)*2:ceil(ih/2)*2","format=yuv420p"].filter(Boolean).join(","),f=x*2,E=c.flatMap(T=>["-map","-0:"+T]);return[["-hide_banner"],["-y"],["-max_error_rate","1"],["-i",e],l,["-map","0:V?"],["-map","0:a?"],E,["-vf",p],["-g",""+f],["-r",""+x],["-colorspace",""+Ji.BT709],["-color_primaries",""+Ji.BT709],["-color_trc",""+Ji.BT709],["-movflags","use_metadata_tags"],["-max_muxing_queue_size","4096"],["-metadata","comment="+Nh.TRANSCODING],[t]].flat()},Qde=(e,t,o,r)=>[["-hide_banner"],["-y"],["-max_error_rate","1"],["-i",e],["-c",""+cg.VP9],["-vf","scale=w=iw:h=ih"],["-b:v","0"],["-crf",""+o],["-vsync","cfr"],["-r",""+r],["-g","8"],["-metadata","comment="+Nh.TRANSCODING_GIF],[t]].flat(),xM=(e,t,o,r,n,a,i,s,x,c,l,d,u,p,f,E)=>{const T=KI(r),{videoFilterOptions:O,outFilterName:S}=jI(d||t,n,Wl,1,x,x,T,c,he.INIT,l,d?t:void 0,u,p,f,void 0,E),R=zI(n,a,i,s,0,c);return[["-hide_banner"],["-y"],["-max_error_rate","1"],["-ss",T.inputSeek.toFixed(3)],["-i",e],R,["-ss",T.outputSeek.toFixed(3)],O?["-filter_complex",O]:[],["-vframes","1"],["-map",S],[""+o]].flat()},Zde=(e,t)=>[["-hide_banner"],["-y"],["-max_error_rate","1"],["-f","image2"],["-framerate",kde.toString()],["-i",e],[t]].flat(),BI=(e,t,o,r,n)=>{switch(e){case gr.NVENC:return["-c:v","h264_nvenc","-qp",""+t];case gr.AMF:return["-c:v","h264_amf","-quality","balanced","-qp_i",""+t,"-qp_p",""+t,"-qp_b",""+t];case gr.QSV:return["-c:v","h264_qsv","-global_quality",""+t];case gr.VIDEOTOOLBOX:return["-c:v","h264_videotoolbox","-b:v",$de(o,r,t,n)];default:return["-c:v","h264","-crf",""+t]}},$de=(e,t,o,r)=>{const n=t?oA(e,t):e;let a=null,i=null;if(_x.forEach(l=>{const d=Math.abs(n.width*n.height-l.size.width*l.size.height);(i===null||d<i)&&(i=d,a=l)}),a===null)return"8M";let s=0;switch(a){case _x[0]:s=2;break;case _x[1]:s=5;break;case _x[2]:s=8;break;case _x[3]:s=16;break;case _x[4]:s=40;break}switch(o){case F0.REGULAR:s=s/2;break;case F0.HIGH:s=s*3/4;break}const x=r/(1024*1024);return Math.max(s,x)+"M"},eue=(e,t,o,r,n)=>{const a=r===gr.NONE||n===void 0?[]:BI(r,F0.REGULAR,n,void 0,0);return[["-hide_banner"],["-y"],["-max_error_rate","1"],["-i",e],a,n?["-s:v:0",n.width+"x"+n.height]:["-c:v","copy"],["-an"],["-f","hls"],["-hls_segment_type","fmp4"],["-hls_playlist_type","vod"],["-hls_fmp4_init_filename","
1069init.mp4"],["-loglevel","verbose"],[t]].flat()},tue=e=>[["-hide_banner"],["-i",e],["-ss","0"],["-t","10:00"],["-af","channelsplit,axcorrelate=size=1024:algo=fast"],["-f","s8"],["pipe:1"]].flat(),KI=e=>e<FS?{inputSeek:0,outputSeek:e}:{inputSeek:e-FS,outputSeek:FS},lw=e=>e===null?0:e.outputSeek,oue=(e,t,o,r,n)=>{const a=[];if(Object.keys(e).forEach((x,c)=>{const l=e[x],{resultTimelineTime:d,duration:u,startOffset:p,trimmedDuration:f,mediaId:E,volume:T,mediaStart:O,numLoop:S,fadeIn:R,fadeOut:y}=l,v=o.find(oe=>oe.mediaId===E),w=r.find(oe=>oe.mediaId===E),N=w?.videoAudioMetaInfo.duration||v?.videoAudioMetaInfo.duration;if(!w&&!v||!N||N===0||u===0)return;const M=Math.floor(d*1e3),k=w?.videoAudioMetaInfo.audioInfo?.sampleRate??v?.videoAudioMetaInfo.audioInfo?.sampleRate??16e3,F=!!v,G=F?0:p,B=F?N:f,W=O+p,Q=O+p+u,j=S>1?new ut("aloop",{loop:S,start:Math.floor(k*G),size:Math.floor(k*B)},[c+":a"]):c+":a",$=new ut("atrim",{start:W.toFixed(3),end:Q.toFixed(3)},[j]),q=new ut("volume",{volume:T},[$]),H=R?new ut("afade",{type:"in",start_time:W.toFixed(3),duration:YE(u)},[q]):q,U=y?new ut("afade",{type:"out",start_time:(Q-YE(u)).toFixed(3),duration:YE(u)},[H]):H,te=new ut("adelay",{delays:M+":all=1"},[U]),ne=new ut("apad",{whole_dur:t.toFixed(3)},[te]);a.push(ne)}),a.length===0)return null;const i=a.length>1?new ut("amix",{inputs:a.length,normalize:"false"},[...a]):a[0];return new ut("aformat",{channel_layouts:"stereo"},[i]).build()},rue=e=>{if(Du(e))return[];if(e<0)throw new C(_.C_LOGIC_ERROR,{},"Playback rate must be non-negative");const o=[];let r=e;for(;r<.5-1e-4;)o.push(.5),r/=.5;for(;r>2+1e-4;)o.push(2),r/=2;return Math.abs(r-1)>1e-4&&o.push(parseFloat(r.toFixed(5))),o.map(n=>"atempo="+n)},nue=(e,t)=>[["-hide_banner"],["-i",e],["-c","copy"],["-map","0:v?"],["-map","0:a?"],["-f","segment"],["-segment_time","01:00:00"],["-segment_start_number","1"],["-reset_timestamps","1"],[t]].flat(),aue=(e,t,o,r)=>{const n=e.map(i=>{const s=r?dw(i):void 0;return s?["-f",s,"-i",i]:["-i",i]});return[["-hide_banner"],["-y"],["-max_error_rate","1"],...n,["-filter_complex",t],["-map","[node_out]"],["-ac","2"],["-b:a","320k"],["-write_xing","0"],[o]].flat()},RO=(e,t,o)=>{const r=ue(e,2),n=ue(t,2),a=ue(n-r,2);return r+"+((on-"+o+")/(duration-"+o+"))*("+a+")"},iue=(e,t,o)=>new ut("scale",{w:t,h:o,force_original_aspect_ratio:1,in_range:"pc",in_color_matrix:"rgb",out_color_matrix:"bt709"},e),sue=(e,t,o)=>{const r=new ut("format",{"":"rgba"},e);return new ut("pad",{"":t*3+":"+o*3+":(ow-iw)/2:(oh-ih)/2:#00000000"},[r])},AO=(e,...t)=>t.reduce((o,r)=>r(o),e),Ip=e=>e,cM=e=>t=>"("+t+")+("+e+")",lM=e=>t=>"("+t+")-("+e+")",yO=e=>t=>"("+t+")*("+e+")",dM=e=>t=>"("+t+")/("+e+")",xue=(e,t,o,r,n)=>{const{from:a,to:i}=e,s=e.duration*1e3,x=eM(Pr.fromMS(s),Pr.fromMS(t),a,i),c=eM(Pr.fromMS(s),Pr.fromMS(o),a,i),l=RO(x.centerX,c.centerX,r),d=RO(x.centerY,c.centerY,r),u=RO(1/x.scale,1/c.scale,r),p="(0.5/zoom)",f=AO(l,n?cM("1"):Ip,n?dM("3"):Ip,lM(p),yO("iw")),E=AO(d,n?cM("1"):Ip,n?dM("3"):Ip,lM(p),yO("ih")),T=AO(u,n?yO("3"):Ip);return{x:f,y:E,z:T}},cue=(e,t,o,r,n,a,i,s,x,c)=>{const{x:l,y:d,z:u}=xue(t,o,r,i,c);return new ut("zoompan",{x:l,y:d,z:u,d:a,fps:n,s:s+"x"+x},e)},lue=e=>{const t=o=>o.centerX-o.scale/2<0||o.centerX+o.scale/2>1||o.centerY-o.scale/2<0||o.centerY+o.scale/2>1;return t(e.from)||t(e.to)},due=(e,t,o,r,n,a,i,s,x,c=1)=>{const l=lue(e),d=e.startTimelineTime*1e3,u=o*1e3,p=u+r*1e3,f=u-d,E=p-d,T=Math.ceil((x?.outputSeek??0)*a),O=Math.ceil((n+(x?.outputSeek??0))*a),S=24e7,R=i*s*(l?9:1),y=$t(Math.floor(Math.sqrt(S/R)),1,6),v=i*y,w=s*y,N=iue([c+t],v,w),M=l?sue([N],v,w):N;return cue([M],e,f,E,a,O,T,i,s,l)},uue=e=>{const t=[...Array(e).keys()].map(n=>n+":a"),o=new ut("amix",{inputs:e,normalize:"false"},t);return new ut("aformat",{channel_layouts:"stereo"},[o]).build()},pue=(e,t,o)=>{const r=uue(e.length),n=e.map(i=>{const s=o?dw(i):void 0;return s?["-f",s,"-i",i]:["-i",i]});return[["-hide_banner"],["-y"],["-max_error_rate","1"],...n,["-filter_complex",r],["-map","[node_out]"],["-ac","2"],["-b:a","320k"],["-write_xing","0"],[t]].flat()},fue=e=>[["-hide_banner"],["-y"],["-max_error_rate","1"],["-threads","1"],["-i",e],["-filter:v","select='gt(scene,"+e6+")',showinfo"],["-an"],["-f","null"]].flat(),gue=(e,t,o)=>new ut("scale",{w:t,h:o,in_color_matrix:"input",out_color_matrix:"bt709"},[e]),O3=(e,t,o)=>new ut("scale",{w:t,h:o,in_range:"pc",in_color_matrix:"rgb",out_color_matrix:"bt709"},[e]),YR=(e,t)=>
1069t===0?e:new ut("rotate",{angle:t,c:"none",ow:"rotw("+t+")",oh:"roth("+t+")"},[e]),uM=(e,t)=>{if(t===void 0||t===Go.NONE)return e;const o=t===Go.VERTICAL||t===Go.VERTICAL_HORIZONTAL?new ut("vflip",{},[e]):e;return t===Go.HORIZONTAL||t===Go.VERTICAL_HORIZONTAL?new ut("hflip",{},[o]):o},pM=(e,t,o,r)=>{const{top:n,right:a,bottom:i,left:s}=t,x=1-s-a,c=1-n-i,l=o/x,d=r/c;return new ut("crop",{w:o,h:r,x:l*s,y:d*n},[e])},_ue=(e,t,o,r)=>{const{ratioX:n,ratioY:a,timelineStart:i,timelineEnd:s,width:x,height:c,rotateDegree:l}=e,d=Math.round(x*o.width),u=Math.round(c*o.height),p=Math.round(n*o.width+d/2),f=Math.round(a*o.height+u/2),E=l*Math.PI/180,T=O3(r,d,u),O=YR(T,E);return new ut("overlay",{x:p+"-w/2",y:f+"-h/2",enable:"'between(t,"+i+","+s+")'"},[t,O])},Eue=e=>{if(e===null)return{type:"simple",filter:"aresample=async=1000"};const t=new ut("aresample",{async:"1000"},["0:a"]),o=new ut("aformat",{sample_fmts:"fltp",sample_rates:"44100",channel_layouts:"stereo"},[t]);return{type:"complex",filter:new ut("amerge",{inputs:2},[o,1]).build()}},dw=e=>{if(ny.test(e))return"mp3"},fM=({currentHwAccel:e,fallbackHwAccel:t,isDriverVersionError:o,isSilentEncodingType:r})=>{if(e!==gr.NONE){if(t!==void 0&&t!==gr.NONE&&t!==e)return{nextHwAccel:t,needAskUser:!1};if(r)return{nextHwAccel:gr.NONE,needAskUser:!1};if(!o)return{nextHwAccel:gr.NONE,needAskUser:!0}}};class vO{fs=yn();tempFS;path;inputFilePath;isCanceled;audioSampleRate;mainMediaInfos;mainAudioInfos;assetVideoInfos;assetAudioInfos;targetType;constructor(t,o,r,n,a,i,s){if(r!==Kt.MP3&&r!==Kt.WAV&&r!==Kt.M4A)throw new C(_.C_LOGIC_ERROR);this.tempFS=new Oi,this.path=o,this.inputFilePath={},this.isCanceled=a,this.audioSampleRate=s,this.targetType=r,this.mainMediaInfos=FI(t),this.mainAudioInfos=m3(t),this.assetVideoInfos=UI(t),this.assetAudioInfos=h3(t)}prepare=async()=>{this.inputFilePath={...await fw(this.mainMediaInfos,this.tempFS),...await this.fs.prepareMainAudioFiles(this.tempFS,this.mainAudioInfos)}};encode=async(t,o,r,n)=>{const{exportByClip:a,mediaTrackMap:i}=n;if(this.inputFilePath===null)throw new C(_.C_LOGIC_ERROR);for(const f of Object.values(this.inputFilePath))if(f===o)throw new C(_.C_EXPORT_INPUT_OUTPUT_SAME_FILE);const s=await rs(t,async f=>{const E=f.audioMedia?f.audioMedia.end-f.audioMedia.start:f.timelineDuration;try{const T=await this.cut(f,r);return r.next(E),{path:T,clipIndex:f.clipIndex}}catch(T){const O=f.clipId&&Yg(f.clipId),S=ye(T)??_.C_EXPORT_GENERAL_ERROR,R=Ho(T)??{},y=Jx(T)??P(T);throw new C(S,{...R,absoluteClipIndex:O},y)}}),x=a?y3(s):[s],c=v3(x),l=a?await _w(c,n,this.targetType,o):[o],d=t.reduce((f,E)=>f+(E.audioMedia?E.audioMedia.end-E.audioMedia.start:E.timelineDuration),0),u=await w3(i,d,this.assetVideoInfos,this.assetAudioInfos,this.tempFS,f=>this.ffmpegRunEncoding(f,void 0,!0));let p=0;for(const f of c)await this.concat(f,u,l[p++],r);return{}};cleanup=async()=>{if(this.tempFS.clearAll(),this.inputFilePath!==null)return gw(this.path,this.inputFilePath)};cut=async(t,o)=>{const r=h("localAudioEncoding.ts");if(this.isCanceled())throw new C(_.C_ENCODING_USER_CANCELED);const n=t.audioMedia?.mediaId?this.mainMediaInfos.find(p=>p.mediaId===t.audioMedia?.mediaId)??this.mainAudioInfos.find(p=>p.mediaId===t.audioMedia?.mediaId):void 0;if(t.audioMedia?.mediaId!==void 0&&n===void 0)throw new C(_.C_LOGIC_ERROR,void 0,"Cannot find mediaInfo for "+t.audioMedia?.mediaId);const a=n===void 0||Ym(n.videoAudioMetaInfo),i=t.exportOverdubInfo?wH(t.exportOverdubInfo,t.audioMedia?t.audioMedia.end-t.audioMedia.start:t.timelineDuration):t.audioMedia?{start:t.audioMedia.start,end:t.audioMedia.end,playbackRate:t.playbackRate,mediaId:t.audioMedia.mediaId}:{start:void 0,end:void 0,playbackRate:t.playbackRate,mediaId:void 0};if(this.inputFilePath===null||i.mediaId!==void 0&&this.inputFilePath[i.mediaId]===void 0)throw new C(_.C_LOGIC_ERROR);const s=Object.keys(this.inputFilePath).length>1,x=await this.tempFS.getTempFileName(uu),c=i.mediaId?i.end-i.start:t.timelineDuration;let l=!1,d;for(let p=0;p<2;++p){const f=a&&!t.exportOverdubInfo||Du(i.playbackRate)||i.mediaId===void 0?bm(c,x,this.audioSampleRate):T3(this.inputFilePath[i.mediaId],x,i.start,i.end,i.playbackRate,s,this.audioSampleRate,l,t.volume);try{d=await this.ffmpegRunEncoding(f,o)}catch(E){const T="Error duing audio encoding: "+P(E);if(r.warn(T),ye(E)===_.D_ERR_FFMPEG_DEMUX_STREAM_FAILED){r.info("Trying again with extension guessed input format."),l=!0;continue}throw E}break}if(!d){const p="audioResult is undefined";throw new C(_.C_LOGIC_ERROR,{},p)}if(d.userCanceled)throw new C(_.C_ENCODING_USER_CANCELED);if(!a&&d.outputStreamEmpty&&(h("localAudioEncoding.ts").info("Output stream is empty, add silent audio."),d=await this.ffmpegRunEncoding(bm(c,x,this.audioSampleRate)),d.userCanceled))throw new C(_.C_ENCODING_USER_CANCELED);const u=await this.ffmpegRunEncoding(S3(d.name,null,await this.tempFS.getTempFileName(uu)),o);if(u.userCanceled)throw new C(_.C_ENCODING_USER_CANCELED);return Promise.resolve(u.name)}
1069;concat=async(t,o,r,n)=>{const a=await this.tempFS.getTempFileName("txt");if(await this.fs.addFile(a,YI(t),"utf8"),(await this.ffmpegRunEncoding(cw(a,o,r,Nh.AUDIO),n)).userCanceled)throw new C(_.C_ENCODING_USER_CANCELED)};ffmpegRunEncoding=async(t,o,r)=>(await ae())("ffmpeg.ffmpegRunEncoding",{lgpl:r??!1,args:t,runType:"audio"},o?o.watch:void 0)}class mue{tempFS;isCanceled;fs=yn();textboxInfos;imageInfos;constructor(t,o,r,n,a,i,s){this.tempFS=new Oi,this.isCanceled=a,this.textboxInfos=sw(t),this.imageInfos=iw(t)}prepare=()=>Promise.resolve();encode=async(t,o,r,n,a)=>{const{size:i}=n;if(n.option===void 0)throw new C(_.C_LOGIC_ERROR,void 0,"Invalid option : undefined");const{captionVideoTypeOption:s}=n.option;if(!s?.codec)throw new C(_.C_LOGIC_ERROR,void 0,"Invalid option : no codec on "+JSON.stringify(n.option));const x=await ew(t,void 0,hU,i,this.fs,this.tempFS,(f,E)=>a.onProgress(f,E,Jn.WEBASSET_EXPORT_WATCH),this.isCanceled,this.textboxInfos),c=Object.values(rn.groupBy(t,f=>f.clipIndex)),l=new X7,d=zt(c).pipe(St(f=>zt(f).pipe(St(async E=>{try{const T=f.findIndex(y=>y===E),O=[...E.exportAssets,...E.exportCaptionModels],S=await $v(O,i,this.fs,this.tempFS,this.textboxInfos,this.imageInfos),R={...E,exportAssets:S};return this.makePieceVideo(f.length,R,T,l,x,s.codec,i,n.videoFrameRate,r)}catch(T){const O=E.clipId&&Yg(E.clipId),S=ye(T)??_.C_EXPORT_GENERAL_ERROR,R=Ho(T)??{},y=Jx(T)??P(T);throw new C(S,{...R,absoluteClipIndex:O},y)}}))),aa()),u=await Bt(d),p=u.filter(f=>f!=="");return await this.concat(p,o,r),{}};cleanup=async()=>this.tempFS.clearAll();makePieceVideo=async(t,o,r,n,a,i,s,x,c)=>{if(this.isCanceled())throw new C(_.C_ENCODING_USER_CANCELED);const l=h("localCaptionVideoEncoding.ts"),d=new Jo,u=await this.tempFS.getTempFileName(uu,"v"+r),p=o.visualMedia?o.visualMedia.end-o.visualMedia.start:o.timelineDuration,f=Math.max(0,p+n.delta);if(f===0)return l.warn("Cut["+(r+1)+"/"+t+"] : reqDuration is 0 ("+p+"+"+n.delta+"), skipping"),"";const E=await this.ffmpegRunEncoding(Yde(i,o.exportAssets,a,s,u,f,o.pieceTimelineInProject,x),c);if(E.userCanceled)throw new C(_.C_ENCODING_USER_CANCELED);const T=await this.ffprobeRun(va(E.name,Io.DURATION),!1),O=parseFloat(T.result);if(isNaN(O))throw new C(_.C_LOGIC_ERROR,void 0,"Cut duration is invalid: "+T.result);if(O===0)return l.warn("Cut["+(r+1)+"/"+t+"] : acutalDuration is 0, skipping"),"";const S=f-O;n.accumulate(p,O,S);const R=o.visualMedia?o.visualMedia.end-o.visualMedia.start:o.timelineDuration;c.next(R);const y=d.getElapsedSec(),v=y/(R||.01),{clipIndex:w}=o;return l.info("Cut["+(r+1)+"/"+t+", "+R.toFixed(1)+"s, clipIdx:"+w+", caption: "+o.captions[0]?.slice(0,3)+"]: "+y.toFixed(1)+"s, ratio: "+v.toFixed(1)),E.name};ffmpegRunEncoding=async(t,o)=>(await ae())("ffmpeg.ffmpegRunEncoding",{lgpl:!1,args:t,runType:"caption"},o?o.watch:void 0);concat=async(t,o,r)=>{if(this.isCanceled())throw new C(_.C_ENCODING_USER_CANCELED);const n=await this.tempFS.getTempFileName("txt","concat");if(await yn().addFile(n,YI(t),"utf8"),(await this.ffmpegRunEncoding(Bde(n,o),r)).userCanceled)throw Ue().deleteFiles([o]),new C(_.C_ENCODING_USER_CANCELED)};ffprobeRun=async(t,o)=>(await ae())("ffmpeg.ffprobeRun",{args:t,allowEmpty:o})}const hue=2,gM=30,Iue=2;class Tue{path;tempFs;fs;constructor(t,o,r,n,a){this.path=Object.values(o)[0],this.tempFs=new Oi,this.fs=yn()}prepare=()=>Promise.resolve();encode=async(t,o,r,n)=>{const{stableGifPath:a,stableFps:i}
1069=await this.getStableParams(this.path,r);if((await this.ffmpegRunEncoding(Qde(a,o,n.quality,i),r,o)).userCanceled)throw await Ue().deleteFiles([o]),new C(_.C_ENCODING_USER_CANCELED);return{}};cleanup=async()=>{};getStableParams=async(t,o)=>{let r=t;const n=await this.getNumFrames(t);if(n===hue){const s=new Array(Iue);s.fill(t);const x=await this.tempFs.getTempFileName("txt","gifConcat"),c=await this.tempFs.getTempFileName("gif",qe.v4());if(await this.fs.addFile(x,YI(s),"utf8"),(await this.ffmpegRunEncoding(cw(x,null,c),o,c)).userCanceled)throw await Ue().deleteFiles([x,c]),new C(_.C_ENCODING_USER_CANCELED);r=c}const a=await this.getDuration(r),i=ue(a/n,2);if(i<gM){const s=IU(gM/i,0);return{stableGifPath:r,stableFps:ue(i*s,2)}}return{stableGifPath:r,stableFps:i}};getNumFrames=async t=>{const o=await this.ffprobeRun(va(t,Io.NUM_FRAMES));if(o.result==="")throw new C(_.C_GIF_IMPORT_GENERAL_ERROR);const r=parseInt(o.result);if(isNaN(r))throw new C(_.C_GIF_IMPORT_GENERAL_ERROR);return r};getDuration=async t=>{const o=await this.ffprobeRun(va(t,Io.DURATION));if(o.result==="")throw new C(_.C_GIF_IMPORT_GENERAL_ERROR);const r=parseFloat(o.result);if(isNaN(r))throw new C(_.C_GIF_IMPORT_GENERAL_ERROR);return r};ffprobeRun=async t=>(await ae())("ffmpeg.ffprobeRun",{args:t,allowEmpty:!0});ffmpegRunEncoding=async(t,o,r)=>(await ae())("ffmpeg.ffmpegRunEncoding",{lgpl:!1,args:t,runType:"transcode"},o.watch)}const got=Fc.black,_ot=e=>{switch(e.type){case k0.SOLID:return{backgroundColor:e.color};case k0.GRADIENT:return{background:"linear-gradient("+Object.entries(e.gradient).reduce(([t,o])=>o+" "+t+"%","")+")"};default:return{}}},C3=e=>{switch(e.type){case k0.SOLID:return"solid-"+e.color;case k0.GRADIENT:return"gradient-"+Object.entries(e.gradient).map(([t,o])=>t+":"+o).join("_");default:return""}},Eot=(e,t)=>{const o=new Set;if(e.length===0)return{selectedBgColor:void 0,isDiverse:!1,isBgColorApplied:!1};if(e.forEach(r=>{if(r.backgroundId){const n=L.get(t,r.backgroundId),a=n?.type===k0.SOLID?n.color:void 0;o.add(a??void 0)}else o.add(void 0)}),o.size===1){const[r]=o;return{selectedBgColor:r,isDiverse:!1,isBgColorApplied:r!==void 0}}return{selectedBgColor:void 0,isDiverse:!0,isBgColorApplied:!1}};class _M{fs=yn();tempFS;path;targetType;mainMediaInfos;imageInfos;assetVideoInfos;textboxInfos;inputFilePath;backgroundImagePathMap={};isCanceled;animImageBasePath;constructor(t,o,r,n,a,i,s){this.tempFS=new Oi,this.path=o,this.targetType=r,this.inputFilePath={},this.isCanceled=a,this.animImageBasePath="",this.mainMediaInfos=FI(t),this.imageInfos=iw(t),this.assetVideoInfos=UI(t),this.textboxInfos=sw(t)}prepare=async()=>{this.inputFilePath={...await fw(this.mainMediaInfos,this.tempFS)},this.animImageBasePath=await this.tempFS.getTempFileName(void 0,void 0,void 0,!0)};encode=async(t,o,r,n)=>{const{size:a}=n;if(this.inputFilePath===null)throw h("localImageEncoding.ts").error("Tried to encode when there is no input file given"),new C(_.C_LOGIC_ERROR);const i=await _w(t,n,this.targetType,o,this.animImageBasePath),s=await this.fs.prepareImageFiles(this.tempFS,this.imageInfos),x={};for(const u of this.assetVideoInfos)x[u.mediaId]=await uw(u.mediaId,u.originalPath,this.tempFS);const c=new Jo,l=await ew(t,s,1,a,this.fs,this.tempFS,(u,p)=>{},this.isCanceled,this.textboxInfos),d=c.getElapsedSec();try{if(await rs(t,async(u,p)=>{try{const f=u.visualMedia?u.visualMedia.end-u.visualMedia.start:u.timelineDuration,E=new Date().getTime(),T=[...u.exportAssets,...u.exportCaptionModels],O=await $v(T,a,this.fs,this.tempFS,this.textboxInfos,this.imageInfos),S={...u,exportAssets:O},R=S.filterEffect?await this.fs.prepareFilterFileByEffect(this.tempFS,S.filterEffect,this.imageInfos):void 0,y=await this.processPieceImage(S,i[p],a,r,s,l,x,S.visualMedia&&S.visualMedia.mediaId===_o?void 0:R,S.flip);r.next(f);const v=new Date().getTime();return h("localImageEncoding.ts").debug("Image["+(p+1)+"/"+t.length+"] : "+(v-E)/1e3),y}catch(f){const E=u.clipId&&Yg(u.clipId),T=ye(f)??_.C_EXPORT_GENERAL_ERROR,O=Ho(f)??{},S=Jx(f)??P(f);throw new C(T,{...O,absoluteClipIndex:E},S)}}),n.type===V.ANIMATED_IMAGE){const u="%0"+t.length.toString().length+"d";await this.ffmpegRunEncoding(Zde(this.animImageBasePath+"_"+u+"."+Kt.PNG,o)),this.fs.deleteFiles(i)}}catch(u){throw h("localImageEncoding.ts").info("Deleting all result image files..."),this.fs.deleteFiles(i),u}return{encodingPerformance:{elapsedWebassetPrepareSec:d}}};cleanup=async()=>
1069{if(this.tempFS.clearAll(),this.inputFilePath!==null)return gw(this.path,this.inputFilePath)};processPieceImage=async(t,o,r,n,a,i,s,x,c)=>await this.processImage(t.visualMedia?.start??0,t.visualMedia?.mediaId,o,n,t.exportAssets,a,i,s,r,t.timelineDuration,t.pieceTimelineInProject,t.background??TU,x,c,t.videoTransform);processImage=async(t,o,r,n,a,i,s,x,c,l,d,u,p,f,E)=>{if(this.isCanceled())throw new C(_.C_ENCODING_USER_CANCELED);if(o===void 0){const N=await this.getBackgroundImagePath(c,u),M={width:128,height:128},k=await this.ffmpegRunEncoding(xM(N,M,r,t,a,i,s,x,l,d,u,c,p,f,E),n,N);if(k.userCanceled)throw new C(_.C_ENCODING_USER_CANCELED);const F=await this.ffprobeRun(va(k.name,Io.DURATION),!1);return Promise.resolve({name:k.name,duration:F.result})}if(this.inputFilePath===null||this.inputFilePath[o]===void 0)throw new C(_.C_LOGIC_ERROR);const T=this.mainMediaInfos.find(N=>N.mediaId===o);if(T===void 0)throw new C(_.C_LOGIC_ERROR,void 0,"Invalid sourcefile information");const O=await this.getInputFilePath(o,c,u),S={width:128,height:128},R=T.videoAudioMetaInfo.videoInfo?I0(T.videoAudioMetaInfo.videoInfo.size):S,y=P2(T.videoAudioMetaInfo.videoInfo?.colorSpace),v=await this.ffmpegRunEncoding(xM(O,R,r,t,a,i,s,x,l,d,u,c,p,f,E,y),n,this.inputFilePath[o]);if(v.userCanceled)throw new C(_.C_ENCODING_USER_CANCELED);const w=await this.ffprobeRun(va(v.name,Io.DURATION),!1);return Promise.resolve({name:v.name,duration:w.result})};getInputFilePath=async(t,o,r)=>pl(t)?this.inputFilePath[t]:await this.getBackgroundImagePath(o,r);getBackgroundImagePath=async(t,o)=>{const r=C3(o),n=L.get(this.backgroundImagePathMap,r);if(n)return n;const a=await this.tempFS.getTempFileName("png","backimg"),i=I3(a,t,o),s=await this.ffmpegRunEncoding(i,void 0);if(s.userCanceled)throw new C(_.C_ENCODING_USER_CANCELED);return L.set(this.backgroundImagePathMap,r,s.name),s.name};ffmpegRunEncoding=async(t,o,r)=>(await ae())("ffmpeg.ffmpegRunEncoding",{lgpl:!1,args:t,runType:"image"},o?o.watch:void 0);ffprobeRun=async(t,o)=>(await ae())("ffmpeg.ffprobeRun",{args:t,allowEmpty:o})}class EM{fs=yn();tempFS;targetType;encodingQuality;videoFrameRate;audioSampleRate;mainMediaInfos;mainAudioInfos;assetVideoInfos;assetAudioInfos;imageInfos;textboxInfos;inputFilePath;path;videotoolboxBitrate;mainMediaAlphaByMediaId;assetVideoAlphaByMediaId;isCanceled;cmds;ffmpegPath;ffprobePath;constructor(t,o,r,n,a,i,s){this.tempFS=new Oi,this.path=o,this.targetType=r,this.encodingQuality=n,this.inputFilePath={},this.videotoolboxBitrate={},this.mainMediaAlphaByMediaId={},this.assetVideoAlphaByMediaId={},this.isCanceled=a,this.videoFrameRate=i,this.audioSampleRate=s,this.cmds=[],this.mainMediaInfos=FI(t),this.mainAudioInfos=m3(t),this.assetVideoInfos=UI(t),this.assetAudioInfos=h3(t),this.imageInfos=iw(t),this.textboxInfos=sw(t)}prepare=async t=>{if(this.inputFilePath={...await fw(this.mainMediaInfos,this.tempFS),...await this.fs.prepareMainAudioFiles(this.tempFS,this.mainAudioInfos)},t===gr.VIDEOTOOLBOX)for(const o of Object.keys(this.inputFilePath)){const r=this.inputFilePath[o],n=await qt().getBitRate(r)||0;this.videotoolboxBitrate[o]=n}for(const o of this.mainMediaInfos){const r=this.inputFilePath[o.mediaId];if(r===void 0)continue;const n=await qt().getMediaFileInfo(r);this.mainMediaAlphaByMediaId[o.mediaId]=n.videoInfo?.hasAlphaChannel??!1}if(!this.ffmpegPath){const o=await(await ae())("ffmpeg.getFFmpegPath",{lgpl:!1});this.ffmpegPath=o.ffmpeg,this.ffprobePath=o.ffprobe}};encode=async(t,o,r,n,a,i)=>{const s=h("localVideoEncoding.ts"),{size:x,exportByClip:c,mediaTrackMap:l,videoRatio:d,assetTimelineRanges:u,watermark:p}=n,f=d??he.INIT;if(this.inputFilePath===null)throw new C(_.C_LOGIC_ERROR,{},"inputFilePath is null.");for(const H of Object.values(this.inputFilePath))if(H===o)throw new C(_.C_EXPORT_INPUT_OUTPUT_SAME_FILE);this.isRecordExport()&&this.tempFS.setBasePath(ti(o));const E={elapsedPrepareGlRendererSec:0,elapsedPrepareMediaFilesSec:0,elapsedPrepareFilterFileSec:0,elapsedWebassetPrepareSec:0,elapsedPieceEncodingTotalSec:0,elapsedConcatSec:0,elapsedBgmEncodeSec:0},T=new Jo;E.elapsedPrepareGlRendererSec=T.lap();const O=await this.fs.prepareImageFiles(this.tempFS,this.imageInfos);E.elapsedPrepareMediaFilesSec=T.lap();const S=new X7,R=await ew(t,O,this.videoFrameRate,x,this.fs,this.tempFS,(H,U)=>
1069a.onProgress(H,U,Jn.WEBASSET_EXPORT_WATCH),this.isCanceled,this.textboxInfos);E.elapsedWebassetPrepareSec=T.lap();const y={},v=[];for(const H of this.assetVideoInfos){const U=await uw(H.mediaId,H.originalPath,this.tempFS);y[H.mediaId]=U,v.push({...H,originalPath:U});const te=await qt().getMediaFileInfo(U);this.assetVideoAlphaByMediaId[H.mediaId]=te.videoInfo?.hasAlphaChannel??!1}const w=this.imageInfos.find(H=>H.mediaId===p?.mediaId),N=p&&w?{watermarkPath:await Aue(this.tempFS,w.mediaId,w.blob),width:p.width,height:p.height,rotateDegree:p.rotation,ratioX:p.xPos,ratioY:p.yPos,timelineStart:Uc.TIMELINE_START,timelineEnd:Uc.TIMELINE_END}:void 0,M=zt(t).pipe(St(async H=>{try{const{clipIndex:U}=H,te=H.filterEffect?await this.fs.prepareFilterFileByEffect(this.tempFS,H.filterEffect,this.imageInfos):void 0,ne=t.findIndex(Ft=>Ft===H),oe=H.visualMedia?H.visualMedia.end-H.visualMedia.start:H.timelineDuration,re=ne>0?t[ne-1]:null,ge=new Date().getTime(),fe=re!==null&&re.visualMedia!==void 0&&H.visualMedia!==void 0&&re.visualMedia.mediaId===H.visualMedia.mediaId&&Math.abs(re.visualMedia.end-H.visualMedia.start)<b0&&H.visualMedia.mediaId!==_o,ve=[...H.exportAssets,...H.exportCaptionModels],yt=await $v(ve,x,this.fs,this.tempFS,this.textboxInfos,this.imageInfos),Le={...H,exportAssets:yt},We=await this.processPiece(ne,Le,fe,S,O,R,y,n.hwAccel,x,r,f,te,u,N);r.next(oe);const kt=new Date().getTime(),bt=(kt-ge)/1e3,Jt=bt/(oe||.01);return s.info("Cut["+(ne+1)+"/"+t.length+", "+oe.toFixed(1)+"s, clipIdx:"+U+", caption: "+H.captions[0]?.slice(0,3)+"] : "+bt.toFixed(1)+"s, ratio: "+Jt.toFixed(1)),{path:We.name,clipIndex:U}}catch(U){const te=H.clipId&&Yg(H.clipId),ne=ye(U)??_.C_EXPORT_GENERAL_ERROR,oe=Ho(U)??{},re=Jx(U)??P(U);throw new C(ne,{...oe,absoluteClipIndex:te},re)}})),k=await Bt(M.pipe(aa()));E.elapsedPieceEncodingTotalSec=T.lap(),T.pause();const F=k.filter(H=>H&&H.path),G=c?y3(F):[F],B=v3(G),W=c?await _w(B,n,this.targetType,o):[o];T.resume();const Q=t.reduce((H,U)=>H+(U.visualMedia?U.visualMedia.end-U.visualMedia.start:U.timelineDuration),0),j=await w3(l,Q,v,this.assetAudioInfos,this.tempFS,H=>this.ffmpegRunEncoding(H,void 0,!0));E.elapsedBgmEncodeSec=T.lap();let $=0;for(const H of B)await this.concat(H,j,W[$++],i),!this.isRecordExport()&&this.tempFS.clear(H).catch(U=>{h("localVideoEncoding.ts").warn("Error during delete "+JSON.stringify(H)+": "+P(U))});return E.elapsedConcatSec=T.lap(),{outputBitRate:await qt().getBitRate(o)||0,encodingPerformance:E}};cleanup=async()=>{if(await this.saveArgs(),!this.isRecordExport()&&this.tempFS.clearAll(),this.inputFilePath!==null)return gw(this.path,this.inputFilePath)};processPiece=async(t,o,r,n,a,i,s,x,c,l,d,u,p,f)=>{const E=Lde(o,this.assetVideoInfos);let T=0,O=o;if(E){T=r?n.lastPieceDelta:0;const M=n.delta-T;O={...o,visualMedia:o.visualMedia?{...o.visualMedia,start:o.visualMedia.start-T,end:Math.max(o.visualMedia.start-T+.01,o.visualMedia.end+M)}:void 0,audioMedia:o.audioMedia?{...o.audioMedia,start:o.audioMedia.start-T,end:Math.max(o.audioMedia.start-T+.01,o.audioMedia.end+M)}:void 0,timelineDuration:Math.max(o.timelineDuration+T+M,.01)}}else h("localVideoEncoding.ts").info("turn off piece encoding length adjustment for "+t+"th piece");if(p&&yde(O,T),O.visualMedia&&O.visualMedia.start<0)throw new C(_.C_LOGIC_ERROR,{},"word start time is negative : "+O.visualMedia.start);if(O.audioMedia&&O.audioMedia.start<0)throw new C(_.C_LOGIC_ERROR,{},"audio start time is negative : "+O.audioMedia.start);const S=await this.cut(t,O,x,a,i,s,c,l,d,O.visualMedia?.mediaId===_o?void 0:u,O.flip,o.videoTransform,f),R=parseFloat(S.duration);if(isNaN(R))throw new C(_.C_LOGIC_ERROR,void 0,"Cut duration is invalid: "+S.duration);const y=o.visualMedia?o.visualMedia.end-o.visualMedia.start:o.timelineDuration,v=O.visualMedia?O.visualMedia.end-O.visualMedia.start:O.timelineDuration,w=o.visualMedia&&O.visualMedia?o.visualMedia.end-O.visualMedia.end:o.timelineDuration-O.timelineDuration,N=v+w-R;return n.accumulate(y,R,N),S};cut=async(t,o,r,n,a,i,s,x,c,l,d,u,p)=>{const f=h("localVideoEncoding.ts"),{visualMedia:E,audioMedia:T,exportAssets:O,playbackRate:S,pieceTimelineInProject:R,timelineDuration:y,background:v=TU,volume:w}=o;if(this.isCanceled())throw new C(_.C_ENCODING_USER_CANCELED);if(this.inputFilePath===null||E?.mediaId!==void 0&&this.inputFilePath[E?.mediaId]===void 0)throw new C(_.C_LOGIC_ERROR,void 0,"Undefined inputFilePath");const N=E?.mediaId!==void 0?this.mainMediaInfos.find(re=>re.mediaId===E?.mediaId):void 0;if(E?.mediaId!==void 0&&!N||N&&N.videoAudioMetaInfo.videoInfo===void 0&&N.videoAudioMetaInfo.audioInfo===void 0)throw new C(_.C_LOGIC_ERROR,void 0,"Invalid sourcefile information "+JSON.stringify(N));const M=p?this.getValidWatermarkInfo(p,o):void 0,k=M!==void 0,F=oge(o,k);let G=[];if(N?.videoAudioMetaInfo.videoInfo&&E!==void 0&&E.mediaId!==_o){const re=I0(N.videoAudioMetaInfo.videoInfo.size),ge=P2(N.videoAudioMetaInfo.videoInfo.colorSpace),fe=this.mainMediaAlphaByMediaId[E.mediaId]??!1,ve=fe&&v.type!==k0.SOLID?await this.getBackgroun
1069dImagePath(s,v):void 0;G=jde(this.inputFilePath[E.mediaId],this.videotoolboxBitrate[E.mediaId]??0,await this.tempFS.getTempFileName(uu,"v"+t),E.start,E.end,this.targetType,this.encodingQuality,r,s,re,n,a,i,O,this.videoFrameRate,S,y,R,c,F,v,l,d,u,M,ge,fe,this.assetVideoAlphaByMediaId,ve)}else{const re=await this.getBackgroundImagePath(s,v);G=zde(await this.tempFS.getTempFileName(uu,"v"+t),re,0,this.encodingQuality,r,0,y,s,O,n,a,i,this.videoFrameRate,S,y,R,F,v,M,this.assetVideoAlphaByMediaId)}const B=await this.ffmpegRunEncoding(G,x);if(B.userCanceled)throw new C(_.C_ENCODING_USER_CANCELED);const W=await this.ffprobeRun(va(B.name,Io.DURATION),!1);if(parseFloat(W.result)===0)return{name:"",duration:W.result};const j=Object.keys(this.inputFilePath).length>1,$=T?.mediaId?this.mainMediaInfos.find(re=>re.mediaId===T?.mediaId)??this.mainAudioInfos.find(re=>re.mediaId===T?.mediaId):void 0;if(T?.mediaId!==void 0&&$===void 0)throw new C(_.C_LOGIC_ERROR,void 0,"Cannot find mediaInfo for audioMediaId: "+T?.mediaId);const q=$===void 0||Ym($.videoAudioMetaInfo),H=await this.tempFS.getTempFileName(uu,"a"+t),U=parseFloat(W.result);let te=!1,ne;for(let re=0;re<2;++re){const ge=o.exportOverdubInfo?wH(o.exportOverdubInfo,U):T?{start:T.start,end:T.start+U,playbackRate:S,mediaId:T.mediaId}:{start:void 0,end:void 0,playbackRate:S,mediaId:void 0},fe=q&&!o.exportOverdubInfo||Du(S)||ge.mediaId===void 0?bm(U,H,this.audioSampleRate):T3(this.inputFilePath[ge.mediaId],H,ge.start,ge.end,ge.playbackRate,j,this.audioSampleRate,te,w);try{ne=await this.ffmpegRunEncoding(fe,void 0)}catch(ve){const yt="Error duing audio encoding: "+P(ve);if(f.warn(yt),ye(ve)===_.D_ERR_FFMPEG_DEMUX_STREAM_FAILED){f.info("Trying again with extension guessed input format."),te=!0;continue}throw ve}break}if(!ne){const re="audioResult is undefined";throw new C(_.C_LOGIC_ERROR,{},re)}if(ne.userCanceled)throw new C(_.C_ENCODING_USER_CANCELED);if(!q&&ne.outputStreamEmpty&&(h("localVideoEncoding.ts").info("Output stream is empty, add silent audio."),ne=await this.ffmpegRunEncoding(bm(U,H,this.audioSampleRate),void 0),ne.userCanceled))throw new C(_.C_ENCODING_USER_CANCELED);const oe=await this.ffmpegRunEncoding(S3(ne.name,B.name,await this.tempFS.getTempFileName("mov","va"+t)),void 0);if(oe.userCanceled)throw new C(_.C_ENCODING_USER_CANCELED);if(!this.isRecordExport()){const re=[ne.name,B.name];this.tempFS.clear(re).catch(ge=>{h("localVideoEncoding.ts").warn("Error during delete "+JSON.stringify(re)+": "+P(ge))})}return Promise.resolve({name:oe.name,duration:W.result})};concat=async(t,o,r,n)=>{const a=await this.tempFS.getTempFileName("txt","concat");return await this.fs.addFile(a,YI(t),"utf8"),this.ffmpegRunEncoding(cw(a,o,r,Nh.VIDEO),n)};ffmpegRunEncoding=async(t,o,r)=>(this.recordArgs(!0,t),(await ae())("ffmpeg.ffmpegRunEncoding",{lgpl:r??!1,args:t,runType:"videoCut"},o?o.watch:void 0));ffprobeRun=async(t,o)=>(this.recordArgs(!1,t),(await ae())("ffmpeg.ffprobeRun",{args:t,allowEmpty:o}));backgroundImagePathMap={};getValidWatermarkInfo=(t,o)=>{const{timelineDuration:r,pieceTimelineInProject:n}=o,a=n+r;return t.timelineStart<=a&&t.timelineEnd>=n?{...t,timelineStart:Math.max(t.timelineStart-n,0),timelineEnd:Math.min(t.timelineEnd-n,r)}:void 0};getBackgroundImagePath=async(t,o)=>{const r=C3(o),n=L.get(this.backgroundImagePathMap,r);if(n)return n;const a=await this.tempFS.getTempFileName("png","backimg"),i=I3(a,t,o),s=await this.ffmpegRunEncoding(i,void 0);if(s.userCanceled)throw new C(_.C_ENCODING_USER_CANCELED);return L.set(this.backgroundImagePathMap,r,s.name),s.name};isRecordExport=()=>(Mo().getDebugVal(Xt.RECORD_EXPORT),!1);recordArgs=async(t,o)=>{if(!this.isRecordExport())return;const r=(t?this.ffmpegPath:this.ffprobePath)||"",n=this.tempFS.getBasePath();if(!n){h("localVideoEncoding.ts").error("isRecordExport but no basePath.");return}h("localVideoEncoding.ts").info(n);let a=!1;const i=[r,...o].map((s,x,c)=>{const l=s==="-i",d=s==="-af"||s==="-filter_complex"||s==="-vf",u=c.length-1===x,p=x===0||c[x-1]==="-i"||u,f=p?s.replace(n,"").replace(/\\/g,"/"):s,E=f.includes(" ")?'"'+f+'"':f,T=!a&&(l||d||u),O=!u&&p,S=(T?`\\
1070 `:"")+E+(O?` \\
1071`:""),R=S.replace(/\n/g,`
1072    `);return a=p,R}).join(" ");this.cmds.push(i)};saveArgs=async()=>
1072{if(!this.isRecordExport())return;const t=await this.tempFS.getTempFileName("sh","ffmpeg-cmds",!0),o=`#!/bin/bash
1073
1074set -e
1075
1076`+this.cmds.join(`
1077
1078`);await this.fs.addFile(t,o,"utf8")}}const R3={width:0,height:0};class Sue{path;inputFilePath;mediaId;constructor(t,o,r,n,a){this.mediaId=Object.keys(o)[0],this.path=Object.values(o)[0],this.inputFilePath=this.path}prepare=async()=>{const t=await A3(this.mediaId,this.path);this.inputFilePath=t[1]};encode=async(t,o,r,n)=>{const{size:a,option:{streamEncodingOption:i}}=n;if(!i)throw new C(_.C_LOGIC_ERROR,void 0,"LocalVideoStreamEncoding should have option.");const{baseFolder:s}=i;if((await this.ffmpegRunEncoding(eue(this.inputFilePath,o,this.mediaId,n.hwAccel,a===R3?void 0:a),s,r,o)).userCanceled)throw new C(_.C_ENCODING_USER_CANCELED);return{}};cleanup=async()=>{};ffmpegRunEncoding=async(t,o,r,n)=>(await ae())("ffmpeg.ffmpegRunEncoding",{lgpl:!1,args:t,runType:"streaming",cwd:o},r.watch,r.result)}class J_{path;constructor(t,o,r,n,a){this.path=Object.values(o)[0]}prepare=()=>Promise.resolve();encode=async(t,o,r,n)=>{const{size:a,hwAccel:i,quality:s}=n,x=a===lg?void 0:a,c=n.videoBitRate??(i===gr.VIDEOTOOLBOX&&await qt().getBitRate(this.path)||0),l=await qt().getMediaFileInfo(this.path),d=l.videoInfo?.frameRate,u=Oue(d),p=P2((await qt().getColorSpace(this.path))?.[2]),f=await qt().getUnknownCodecAudioStream(this.path),E=l.videoInfo?.size,T=E&&x&&(x.width!==E.width||x.height!==E.height),O=T?x.width*x.height:void 0;if((await this.ffmpegRunEncoding(qde(this.path,o,i,x,O,s,c,p,u,f),r,o)).userCanceled)throw await Ue().deleteFiles([o]),new C(_.C_ENCODING_USER_CANCELED);return{}};cleanup=async()=>{};ffmpegRunEncoding=async(t,o,r)=>(await ae())("ffmpeg.ffmpegRunEncoding",{lgpl:!1,args:t,runType:"transcode"},o.watch)}const Oue=e=>e===void 0?Rb:e>=o6?t6:Rb,Cue=200,mM=async e=>{const t=e?A("export.export_error_hwaccel_retry_2?"):A("export.export_error_hwaccel_retry?"),o=A("export.export_error_hwaccel_desc"),r=t+`
1079
1080`+o,n={bodyClassName:"general-modal",title:A("popup.title_confirm"),content:r,yesStr:A("popup.yes"),noStr:A("popup.no")};return await Y().popup(n)===mt.YES},A3=async(e,t,o)=>{if(Bf(t))return[e,await tI(t)];const r=Hs(e);if(r?.fileLocation===D.IN_MEMORY&&o){const n=r.type==="AVMedia"&&r?.videoAudioMetaInfo.videoInfo?"mp4":"mp3",a=await fetch(t).then(i=>i.blob());return pw(n,e,a,o)}return[e,t]},uw=async(e,t,o)=>{if(Bf(t))return tI(t);if(t.startsWith("blob:")){const r=await fetch(t).then(a=>a.blob()),[,n]=await pw("mp4",e,r,o);return n}return t},pw=async(e,t,o,r)=>{const n=await r.getTempFileName(e);return await yn().addFile(n,await o.arrayBuffer(),"binary"),[t,n]},Rue=async(e,t,o)=>{h("local.ts").info("Preparing local background audio file for mediaId:"+o+" to export.");const r=t.find(x=>x.mediaId===o);if(r===void 0)throw new C(_.C_BGM_ERROR,{},"audioInfo cannot be undefined");const n=r.videoAudioMetaInfo?.audioInfo?.codec||Gt.MP3,a=HE(n),i=r.blob;if(!i){const x="[prepareAudioFile] Blob cannot be null for mediaId: "+o;throw h("local.ts").error(x),new C(_.C_MEDIA_BLOB_LOST,{},x)}const s=await e.getTempFileName("."+a,o,!0);return await yn().addFile(s,await i.arrayBuffer(),"binary"),s},Aue=async(e,t,o)=>{h("local.ts").info("Preparing local watermark file for mediaId:"+t+" to export.");const r=await e.getTempFileName(".png",t,!0);return await yn().addFile(r,await o.arrayBuffer(),"binary"),r},fw=async(e,t)=>{const o=e.map(async n=>{const{mediaId:a,originalPath:i,fileLocation:s,blob:x,videoAudioMetaInfo:c}=n;if(s===D.IN_MEMORY&&x){const l=c.videoInfo?"mp4":"mp3";return pw(l,a,x,t)}return A3(a,i,t)}),r=await Promise.all(o);return Object.fromEntries(r)},gw=async(e,t)=>{const o=yn(),r=Object.entries(e).reduce((n,[a,i])=>(Bf(i)&&n.push(i),n),[]);return o.deleteFiles(r)},_w=async(e,t,o,r,n)=>{const a=e.map((s,x)=>{const c=e.length.toString().length,l=ZN(x+1,c),d=gt(se().getCurrentProjectPath()),u=d.lastIndexOf("."),p=u===-1?d:d.substr(0,u);switch(t.type){case V.IMAGE:case V.AUDIO_MP3:case V.AUDIO_WAV:case V.AUDIO_AAC:return r+"/"+p+"_"+l+"."+o;case V.VIDEO:return r+"/"+p+"_exported_"+l+"."+o;case V.ANIMATED_IMAGE:return n!==void 0?n+"_"+l+"."+Kt.PNG:"";default:return""}}),i=await yn().getExistingFiles(a);if(i.length!==0){const s=gt(i[0]),x={bodyClassName:"general-modal",title:A("popup.title_confirm"),content:A("export.overwrite_file?",{number:i.length,filename:s}),yesStr:A("popup.confirm"),noStr:A("popup.cancel")};if(await Y().popup(x)!==mt.YES)throw new C(_.C_ENCODING_USER_CANCELED)}return a},y3=e=>e.reduce((t,o)=>{if(t.length===0)return[[o]];const r=t.length-1,n=t[r][0].clipIndex;if(o.clipIndex!==n)return t.concat([[o]]);const i=t[r],s=i.concat(o);return t.slice(0,r).concat([s])},[]),v3=e=>e.map(t=>t.map(o=>o.path)),mot=async(e,t)=>await(await ae())("ffmpeg.getShotBoundaryInfo",{lgpl:!0,args:fue(e),runType:"shotBoundaryDetection"},t);class yue{ready;canceled;audioTempFSMap={};availableHwAccel;fallbackHwAccel;constructor(){this.ready=!0,this.canceled=!1,this.availableHwAccel=gr.NONE}guessElapsed=t=>t*500;encodeUserVideos=async(t,o,r,n)=>{const a=new Jo,i=n.type,s=[];let x;for(let f=0;f<t.length;f++){const{path:E,pieces:T}=t[f],O=new J_([],E,o,n.quality,()=>this.canceled);try{await O.prepare();const S=i===V.TRANSCODING_VIDEO||i===V.TRANSCODING_AUDIO,R=await nc.getInstance(),y=R.getProxySavePath(),[v,w]=Object.entries(E)[0],N=i===V.PROXY_VIDEO,M=N?sde(v,w,y):S?w:se().getCurrentProjectPath(),k=zu(this.getDefaultExportName(M,i),!S&&!N),F={name:k};let G;const B=Lp(T),W=n.type===(V.AUDIO_MP3||V.AUDIO_WAV||V.AUDIO_AAC)?Jn.AUDIO_EXPORT_WATCH:Jn.VIDEO_EXPORT_WATCH;x=new C0(B*1e3,W),G=new C0(1,Jn.AUDIO_CONCAT_WATCH);const Q=!n.exportByClip&&!this.validFileFormat(F.name,i)?"."+o:"",j=F.name+Q;for(x.onWatch=($,q,H)=>r.onProgress($,q,f),G!==void 0&&(G.onWatch=($,q,H)=>r.onProgress($,q,f)),r.onStart();;){try{await O.encode(T,j,x,n),s.push(j)}catch($){const q=ye($);if(n.hwAccel!==gr.NONE&&(q===_.D_ERR_HWACCEL_ENCODE_FAILED||q===_.D_ERR_HWACCEL_DRIVER_VERSION_LOW||q===_.D_ERR_FFMPEG_CUT_PROCESS_FAILED)){const H=q===_.D_ERR_FFMPEG_CUT_PROCESS_FAILED,U=i===V.TRANSCODING_VIDEO||i===V.STREAM||i===V.PROXY_VIDEO,te=fM({currentHwAccel:n.hwAccel,fallbackHwAccel:this.fallbackHwAccel,isDriverVersionError:q===_.D_ERR_HWACCEL_DRIVER_VERSION_LOW,isSilentEncodingType:U});if(te!==void 0&&(te.needAskUser===!1||await mM(H))){h("local.ts").info("hwaccel fallback: "+n.hwAccel+" -> "+te.nextHwAccel+" ("+q+")");const oe=H?_.D_ERR_FFMPEG_CUT_PROCESS_FAILED+"-2":q;aE(oe,n.exportId),H===!1&&te.nextHwAccel===gr.NONE&&Ve().set(Ie.USE_HWACCEL,!1),n={...n,hwAccel:te.nextHwAccel},x.reset(),a.reset();continue}}throw $}break}}catch(S){const R=Ne(S)?S:new C(_.C_LOGIC_ERROR,{},P(S)),y=a.getElapsedSec(),v=Eo(V).getKeyOrDefault(i,"unknown"),w=os(y,!0);return R.errorCode===_.C_ENCODING_USER_CANCELED?(r.onCancel(),h("local.ts").info("Encoding canceled (type : "+v+") elapsed "+w+"."),{type:Dr.USER_CANCELED,elapsedSec:y}):(aE(R.errorCode,n.exportId),r.onError(R),h("local.ts").info("Encoding error (type : "+v+") elapsed "+w+". Error: "+R.message),{type:Dr.FAILED,elapsedSec:y})}finally{await O.cleanup()}}this.canceled=!1;const c=a.getElapsedSec(),l=Eo(V).getKeyOrDefault(i,"unknown"),d=os(c,!0);h("local.ts").info("Encoding (type : "+l+") elapsed "+d+".");const u=s.map(f=>gt(f)).join(", "),p=A("export.filename_done",{filename:u});return h("local.ts").info("Encoding done, calling onEnd("+p+")"),r.onEnd(p,s),{type:Dr.SUCCESS,elapsedSec:c}};encode=async(t,o,r,n,a,i)=>{if(!o)throw new Error("Path is empty");const s=i.type,x=i.exportId,c={[V.VIDEO]:EM,[V.CAPTION_VIDEO]:mue,[V.AUDIO_MP3]:vO,[V.AUDIO_WAV]:vO,[V.AUDIO_AAC]:vO,[V.TRANSCODING_VIDEO]:J_,[V.TRANSCODING_AUDIO]:J_,[V.CONVERTING_GIF]:Tue,[V.STREAM]:Sue,[V.IMAGE]:_M,[V.ANIMATED_IMAGE]:_M,[V.SPLIT_MEDIA]:void 0,[V.STATIC_FRAME]:EM,[V.PROXY_VIDEO]:J_}[s];if(!c)throw new C(_.C_LOGIC_ERROR,{},"Invalid encoding type");const l=new c(t,o,n,i.quality,()=>this.canceled,i.videoFrameRate,i.audioSampleRate),d={type:Dr.FAILED,elapsedSec:0},u=new Jo,p=Lp(r);try{const f={[V.VIDEO]:A("toolbar.export_video_title"),[V.CAPTION_VIDEO]:A("toolbar.export_caption_video_title"),[V.AUDIO_MP3]:A("toolbar.export_audio_title"),[V.AUDIO_WAV]:A("toolbar.export_audio_title"),[V.AUDIO_AAC]:A("toolbar.export_audio_title"),[V.TRANSCODING_VIDEO]:A("transcode.title"),[V.TRANSCODING_AUDIO]:A("transcode.title"),[V.CONVERTING_GIF]:"",[V.STREAM]:A("transcode.title"),[V.IMAGE]:A("export.image_title"),[V.ANIMATED_IMAGE]:A("export.image_title"),[V.SPLIT_MEDIA]:"",[V.STATIC_FRAME]:"TODO: static frame title",[V.PROXY_VIDEO]:A("transcode.title")},E=f[s];await l.prepare(i.hwAccel);let T,O,S;if(s===V.IMAGE||i.exportByClip)u.pause(),T=await yn().showOpenDialog([n],void 0,E,U2(),!0),u.resume(),O=new ede(r.length,Jn.IMAGE_EXPORT_WATCH);else if(s===V.STREAM)T={name:Object.keys(o)[0]+"."+Ph},O=new C0(p*1e3,Jn.VIDEO_EXPORT_WATCH),O.onResult=(M,k)=>a.onResult(M,k);else if(s===V.CONVERTING_GIF){const N=new Oi,M=Object.values(o)[0],k=M?gt(M).replace(/\.gif$/g,""):void 0;T={name:await N.getTempFileName("webm",k,!0)};const G=await this.getDuration(M),B=G??1;O=new C0(B*1e3,Jn.VIDEO_EXPORT_WATCH),O.onResult=(W,Q)=>a.onResult(W,Q)}else if(s===V.STATIC_FRAME)T={name:i.option.staticFrameEncodingOption?.outputPathName+".mp4"},O=new C0(p*1e3,Jn.STATIC_FRAME_EXPORT_WATCH),O.onResult=(N,M)=>a.onResult(N,M);else{const N=s===V.TRANSCODING_VIDEO||s===V.TRANSCODING_AUDIO?Object.values(o)[0]:se().getCurrentProjectPath(),M=zu(this.getDefaultExportName(N,s),!0);u.pause(),T=await yn().showSaveDialog(n,E,M),u.resume();const k=Lp(r),F=i.type===(V.AUDIO_MP3||V.AUDIO_WAV||V.AUDIO_AAC)?Jn.AUDIO_EXPORT_WATCH:Jn.VIDEO_EXPORT_WATCH;O=new C0(k*1e3,F),S=new C0(1,Jn.AUDIO_CONCAT_WATCH)}if(!T||!T.name)return a.onCancel(),d.type=Dr.USER_CANCELED,d;i.triggerSurveyToast&&i.triggerSurveyToast();const R=!i.exportByClip&&!this.validFileFormat(T.name,s)?"."+n:"",y=T.name+R;O.onWatch=(N,M,k)=>a.onProgress(N,M,k),S!==void 0&&(S.onWatch=(N,M,k)=>a.onProgress(N,M,k)),a.onStart();let v;for(;;){try{v=await l.encode(r,y,O,i,a,S)}catch(N){const M=ye(N);if(i.hwAccel!==gr.NONE&&(M===_.D_ERR_HWACCEL_ENCODE_FAILED||M===_.D_ERR_HWACCEL_DRIVER_VERSION_LOW||M===_.D_ERR_FFMPEG_CUT_PROCESS_FAILED)){const k=M===_.D_ERR_FFMPEG_CUT_PROCESS_FAILED,F=s===V.TRANSCODING_VIDEO||s===V.STREAM||s===V.STATIC_FRAME,G=fM({currentHwAccel:i.hwAccel,fallbackHwAccel:this.fallbackHwAccel,isDriverVersionError:M===_.D_ERR_HWACCEL_DRIVER_VERSION_LOW,isSilentEncodingType:F});if(G!==void 0&&(G.needAskUser===!1||await mM(k))){h("local.ts").info("hwaccel fallback: "+i.hwAccel+" -> "+G.nextHwAccel+" ("+M+")");const W=k?_.D_ERR_FFMPEG_CUT_PROCESS_FAILED+"-2":M;aE(W,x),k===!1&&G.nextHwAccel===gr.NONE&&Ve().set(Ie.USE_HWACCEL,!1),i={...i,hwAccel:G.nextHwAccel},O.reset(),u.reset();continue}}throw N}break}const w=s===V.IMAGE?A("export.filetype_done",{filetype:A("filetype.image")}):A("export.filename_done",{filename:gt(y),interpolation:{escapeValue:!1}});a.onEnd(w,y),d.type=Dr.SUCCESS,d.encodingPerformance=v?.encodingPerformance,d.outputBitRate=v?.outputBitRate}catch(f){const E=Ne(f)?f:new C(_.C_LOGIC_ERROR,{},P(f));E.errorCode===_.C_ENCODING_USER_CANCELED?(a.onCancel(),d.type=Dr.USER_CANCELED):(aE(E.errorCode,x),a.onError(E),d.type=Dr.FAILED)}finally{this.canceled=!1,await l.cleanup();const f=u.getElapsedSec();if(d.elapsedSec=f,d.type===Dr.SUCCESS&&s!==V.TRANSCODING_VIDEO&&s!==V.STREAM&&s!==V.STATIC_FRAME){const S=Math.round(f/60),R=Lp(r),y=Math.round(R/60),v=(i.filterAppliedClipCount??0)>0;pke(v,y,S,x)}const E=os(f,!0),T=f/(p||.01),O=d.type===Dr.SUCCESS?", exportRatio: "+T.toFixed(1):"";h("local.ts").info("Exporting done, id: "+x+", result: "+d.type+", elapsed "+E+O+".")}return d};checkFfmpegExist=async t=>(await ae())("ffmpeg.checkExist",{lgpl:t});downloadFfmpeg=async(t,o)=>(await ae())("ffmpeg.download",{lgpl:t},o||(r=>{}));abort=async()=>{this.canceled=!0,(await ae())("ffmpeg.ffmpegKill")};extractAudio=async(t,o,r,n)=>{if(ry.test(t)&&!n&&!Ab.test(t))return{path:t,tempfile:"",codec:o};const a=o!==Gt.PCM&&!n,i=a?o:Gt.MP3,s=HE(i),x=new Oi,c=await x.getTempFileName("."+s);this.audioTempFSMap[c]=x;const l=async f=>(await ae())("ffmpeg.ffmpegRunExtractAudio",f),d=Kde.bind(null,t,c,i),u={lgpl:!0,args:d(a,!0,r,n),runType:"audio"};let p;try{p=await l(u)}catch(f){const E=["Error occurred during extracting audio with demuxing "+a+".",P(f)+". Retry with full audio encoding."].join("");h("local.ts").info(E),p=await l({...u,args:d(!1,!1,!1,n)})}return{path:p.name,tempfile:c,codec:i}};sliceAudio=async(t,o,r,n)=>{const a=HE(o),i=new Oi,s=await i.getTempFileName("."+a);this.audioTempFSMap[s]=i;const x=Xde(t,s,r,n);return{path:(await(await ae())("ffmpeg.ffmpegRunExtractAudio",{lgpl:!0,args:x,runType:"audio"},()=>{})).name,tempfile:s}};extractAudioFragment=async(t,o,r,n)=>{o===null&&(o=Gt.AAC);const a=HE(o),i=new Oi,s=r+"~"+n,x=await i.getTempFileName("."+a,s);this.audioTempFSMap[x]=i;const c=Jde(t,x,o,r,n);try{return{path:(await(await ae())("ffmpeg.ffmpegRunExtractAudio",{lgpl:!0,args:c,runType:"audioFragment"},()=>{})).name,tempfile:x}}
1080catch(l){if(ye(l)===_.D_ERR_FFMPEG_IMPORT_AUDIO_FAILED){const d={startMin:Math.floor(r/60),startSec:Math.floor(r)%60,endMin:Math.floor(Math.ceil(r+n)/60),endSec:Math.ceil(r+n)%60};throw new C(_.D_ERR_FFMPEG_IMPORT_AUDIO_FAILED,d)}throw l}};clearExtractedAudioTempFile=async t=>{const o=this.audioTempFSMap[t];o&&(delete this.audioTempFSMap[t],o.clearAll())};getVideoKeyFrameInterval=async t=>{try{const o=await(await ae())("ffmpeg.ffprobeRun",{args:va(t,Io.SAMPLED_PACKETS_INFO),allowEmpty:!0,quiet:!0});if(o.result==="")return 0;const r=JSON.parse(o.result).packets.map(i=>({pts_time:parseFloat(i.pts_time),flags:i.flags})),n=r.filter(i=>i.flags.includes("K")),a=n.slice(1).reduce((i,s,x)=>{const c=s.pts_time-n[x].pts_time;return i>c?i:c},0);return rn.round(a,2)}catch(o){return h("local.ts").error("error on getVideoKeyFrameInterval: "+P(o)),0}};getMediaFileInfo=async t=>{try{const{rawOutput:o,streams:r}=await(await ae())("ffmpeg.ffprobeRunInfo",{path:t}),n=this.getVideoInfo(o),a=r.find(R=>R.codec_type==="video"),i=r.find(R=>R.codec_type==="audio"),s=this.parseChannelCountFromStream(i,t),x=this.getAudioInfo(o),c=x?{...x,channelCount:s}:void 0;let l=this.getMediaContainer(o);if(l==="mkv")try{const R=await(await ae())("fs.readFile",{path:t,length:xde});l=lde(l,cde(new Uint8Array(R)))}catch{}const d=/ *Duration: (\S*), /,u=o.match(d),p=u&&u[1],f=this.parseColorSpaceFromStream(a),E=Dde(a?.tags),T=p?p.split(":").map(Number).reduce((R,y)=>60*R+y,0):0,O=Number.isFinite(T)?T:0,S=this.getPresumedDevice(o);if(n&&c)return{videoInfo:{size:{width:n.size.width,height:n.size.height,rotation:n.size.rotation,paspH:n.size.paspH,paspV:n.size.paspV},frameRate:n.frameRate,codec:n.codec,colorSpace:f,hasAlphaChannel:E,pixFmt:a?.pix_fmt},audioInfo:{sampleRate:c.sampleRate,codec:c.codec,channelCount:c.channelCount},duration:O,presumedDevice:S,mediaContainer:l};if(n&&!c)return{videoInfo:{size:{width:n.size.width,height:n.size.height,rotation:n.size.rotation,paspH:n.size.paspH,paspV:n.size.paspV},frameRate:n.frameRate,codec:n.codec,colorSpace:f,hasAlphaChannel:E,pixFmt:a?.pix_fmt},duration:O,presumedDevice:S,mediaContainer:l};if(!n&&c)return{audioInfo:{sampleRate:c.sampleRate,codec:c.codec,channelCount:c.channelCount},duration:O,presumedDevice:S,mediaContainer:l};throw new C(_.C_MEDIA_NO_AUDIO_VIDEO_TRACK)}catch(o){if(ye(o)===_.D_ERR_MEDIA_INVALID_DATA){const r=t.split("."),n=r[r.length-1];throw new C(_.D_ERR_MEDIA_INVALID_DATA,{videoType:n})}throw o}};getAudioTrackNum=async t=>{try{const{rawOutput:o}=await(await ae())("ffmpeg.ffprobeRunInfo",{path:t}),r=/ *Stream.*Audio: (\S*)[ ,].* (\d+) Hz/g;return[...o.matchAll(r)].length}catch(o){return h("local.ts").error("error on getAudioTrackNum: "+P(o)),1}};getMediaFileStartTimes=async t=>{try{const{rawOutput:o,streams:r}=await(await ae())("ffmpeg.ffprobeRunInfo",{path:t}),n=this.parseContainerStartTime(o),a=r.find(c=>c.codec_type==="audio"),i=r.find(c=>c.codec_type==="video"),s=this.parseStartTimeFromStream(a),x=this.parseStartTimeFromStream(i);return s!==void 0&&x!==void 0&&n!==void 0?{audio:s,video:x,container:n}:s!==void 0&&n!==void 0?{audio:s,container:n}:x!==void 0&&n!==void 0?{video:x,container:n}:void 0}catch(o){return h("local.ts").error("error on getMediaFileStartTimes: "+P(o)),void 0}};getVideoCodec=async t=>{const{rawOutput:o}=await(await ae())("ffmpeg.ffprobeRunInfo",{path:t}),r=/ *Stream.*Video: (\S*) /,n=o.match(r);if(!n)return null;const a=n[1],i=/ *Duration: (\S*), /,s=o.match(i);if(!s)return null;const x=s[1].split(":").reduce((c,l)=>60*c+Number(l),0);return{codec:a,duration:x}};getTimecode=async t=>{const o=/Drop frame is only allowed with /,r=await this.getHuristicTimecodeResult(t);h("local.ts").info("timecode detect result : "+JSON.stringify(r));const n=/(\d\d):(\d\d):(\d\d)([:;.])(\d\d)/,a=r.result.match(n);if(!a||a&&a.length!==6)return;const i=parseInt(a[1],void 0)*60*60+parseInt(a[2],void 0)*60+parseInt(a[3],void 0),s=a[4]===":",x=parseInt(a[5],void 0),c=o.test(r.error);return{sec:i,ff:x,isNonDrop:s,forceNonDrop:c}};getRFrameRate=async t=>{const o=await(await ae())("ffmpeg.ffprobeRun",{args:va(t,Io.R_FRAME_RATE),allowEmpty:!0}
1080),r=/(\d+)\/(\d+)/,n=o.result.match(r);if(!n||n&&n.length!==3)return;const a=parseInt(n[1],void 0),i=parseInt(n[2],void 0);return{numerator:a,denominator:i}};getBitRate=async t=>{const o=await(await ae())("ffmpeg.ffprobeRun",{args:va(t,Io.BITRATE),allowEmpty:!0});if(o.result!=="")return parseInt(o.result,void 0)};getColorSpace=async t=>{const o=await(await ae())("ffmpeg.ffprobeRun",{args:va(t,Io.COLOR_SPACE),allowEmpty:!0});if(o.result!=="")return o.result.split(`
1081`)};getDuration=async t=>{const o=await(await ae())("ffmpeg.ffprobeRun",{args:va(t,Io.DURATION),allowEmpty:!0});if(o.result!=="")return parseFloat(o.result)};initAvailableHwAccel=async()=>{const{hw:t,fallbackHw:o}=await(await ae())("ffmpeg.get_available_encoder",{needRefresh:!1});return this.availableHwAccel=t,this.fallbackHwAccel=o,Promise.resolve(!0)};updateAvailableHwAccel=async t=>{if(this.availableHwAccel!==gr.NONE)return Promise.resolve(!0);const{hw:o,fallbackHw:r}=await(await ae())("ffmpeg.get_available_encoder",{needRefresh:t});return this.availableHwAccel=o,this.fallbackHwAccel=r,Promise.resolve(!0)};getAvailableHwAccel=()=>this.availableHwAccel;checkPhaseReverse=async t=>{const o=tue(t),r=await(await ae())("ffmpeg.phaseReverseInfo",{args:o}).catch(c=>(h("local.ts").error("error while checking phase reverse : "+P(c)),{})),n=128,a=.5,i=r[n]??0,s=Object.values(r).reduce((c,l)=>c+l,0),x=i>s*a;return h("local.ts").info("allSamples : "+s+", reversedSamples : "+i+", phaseReversed : "+x),x};getAudioMetaInfo=async t=>{const o=await(await ae())("ffmpeg.ffprobeRun",{args:va(t,Io.DURATION),allowEmpty:!0}),r=await(await ae())("ffmpeg.ffprobeRun",{args:va(t,Io.SAMPLE_RATE),allowEmpty:!0}),n=await(await ae())("ffmpeg.ffprobeRun",{args:va(t,Io.CODEC_STRINGS),allowEmpty:!0});if(!(o.result===""||r.result===""||n.result===""))return{duration:parseFloat(o.result),sampleRate:parseInt(r.result),codec:n.result}};splitMedia=async(t,o,r)=>{const n=Nu(gt(t)),a=yo(t),i=""+o+JU.sep+n+"_part%d."+a,s=nue(t,i);return(await ae())("ffmpeg.splitMedia",{args:s,destFolder:o},void 0,r)};getUnknownCodecAudioStream=async t=>{try{const o=await(await ae())("ffmpeg.ffprobeRun",{args:va(t,Io.AUDIO_CODEC),quiet:!0,allowEmpty:!0});return o.result===""?[]:JSON.parse(o.result).streams.filter(n=>n.codec_name===void 0).map(n=>n.index)}catch(o){return h("local.ts").warn("error on getUnknownCodecAudioStream: "+P(o)),[]}};getVideoInfo=t=>{const o=h("local.ts"),r=/ *Stream.*(Video: (?:(?! *Stream)[\s\S])*(Stream)?)/,n=t.match(r);if(!n){o.info("No video stream on "+t);return}const a=n[1],i=a.match(/Video: (\w+)/),s=i?i[1]:cg.H264,x=a.match(/ ((\d+\.)?\d+k?) fps/),c=x&&x[1]?x[1].endsWith("k")?1e3*parseFloat(x[1].slice(0,-1)):parseFloat(x[1]):30,l=a.match(/(\w*).* (\d+)x(\d+)/);if(!l){if(/\(attached pic\)/.test(a)||/\(timed thumbnails\)/.test(a)){o.info("Video stream is attached_pic or timed_thumbnails, treating as non-video.");return}return o.warn("Video stream exists but resolution could not be parsed. Using fallback values."),{size:lg,frameRate:c,codec:s}}const d=parseFloat(l[2]),u=parseFloat(l[3]),p=a.match(/SAR (\d+):(\d+) /),f=p&&p[1]!=="1"&&p[2]!=="1"?parseFloat(p[1]):void 0,E=p&&p[1]!=="1"&&p[2]!=="1"?parseFloat(p[2]):void 0,T=a.match(/rotate *: (\d*)/),O=T&&T[1]?parseFloat(T[1]):void 0;return{size:{width:d,height:u,paspH:f,paspV:E,rotation:O},frameRate:c,codec:s}};getPresumedDevice=t=>{const o=/com.apple.quicktime.make: Apple/,r=/com.android.version/;return t.match(o)?Kp.IOS:t.match(r)?Kp.ANDROID:Kp.UNKNOWN};getAudioInfo=t=>{const o=/ *Stream.*Audio: (\S*)[ ,].* (\d+) Hz(?:,\s*([^,]+))?/g,r=[...t.matchAll(o)];if(r.length===0)return h("local.ts").info("cannot find pattern from "+t),void 0;const n=r[0],a=/^pcm_\s*/.test(n[1])?Gt.PCM:n[1],i=parseFloat(n[2]);return{codec:a,sampleRate:i}};getMediaContainer=t=>{const o=t.match(/Input #\d+, (.*?)(?:, from|,|$)/),r=o?.[1],n=t.match(/major_brand\s*:\s*(\S*)/),a=n?.[1],i=r?.split(",").map(s=>s.trim());if(i)return this.getContainerFormat(i,a)};getContainerFormat=(t,o)=>{const r=(o||"").trim(),n=t.includes("matroska")||t.includes("webm");if(r&&!n){if(r==="M4A"||r==="M4B")return"m4a";if(r.startsWith("qt"))return"mov";if(r.startsWith("3gp"))return"3gp";if(["isom","iso2","iso3","iso4","iso5","iso6","mp41","mp42"].includes(r))return t.includes("m4a")?"m4a":"mp4"}if(t.length>0){const a=t[0];return a==="matroska"||a==="webm"?"mkv":a.toLowerCase()}};parseContainerStartTime=t=>{const o=t.match(/ *Duration: (\S*), start: (\S*), bitrate: ([^,]+),/);if(o){const r=o[2],n=parseFloat(r);return Number.isNaN(n)||!Number.isFinite(n)?void 0:Math.round(n*1e3)}};getDefaultExportName=(t,o)=>{const r=EA(t),n={[V.CAPTION_VIDEO]:{postfix:x6,ext:s6},[V.TRANSCODING_VIDEO]:{postfix:yb,ext:kd},[V.TRANSCODING_AUDIO]:{postfix:yb,ext:tm},[V.CONVERTING_GIF]:{postfix:"",ext:i6},[V.STREAM]:{postfix:"",ext:kd},[V.VIDEO]:{postfix:ige(EA(gt(t)))?A("export.export_file_postfix"):"",ext:kd},[V.AUDIO_MP3]:{postfix:"",ext:tm},[V.AUDIO_WAV]:{postfix:"",ext:a6},[V.AUDIO_AAC]:{postfix:"",ext:ff},[V.IMAGE]:{postfix:"",ext:n6},[V.ANIMATED_IMAGE]:{postfix:"",ext:r6},[V.SPLIT_MEDIA]:{postfix:"",ext:kd},[V.STATIC_FRAME]:{postfix:"",ext:kd},[V.PROXY_VIDEO]:{postfix:"",ext:kd}},a=n[o];return""+r+a.postfix+a.ext};validFileFormat=(t,o)=>{switch(o){case V.TRANSCODING_VIDEO:case V.VIDEO:return c6.test(t);case V.AUDIO_MP3:return ny.test(t);case V.AUDIO_WAV:return Ab.test(t);default:return!0}};getHuristicTimecodeResult=async t=>{const o=async s=>(await ae())("ffmpeg.ffprobeRun",{args:va(t,s),allowEmpty:!0});if(l6.test(t))return o(Io.TIMECODE_ALLTRACK);const r=await o(Io.TIMECODE_VIDEOTRACK);if(r.result)return r;const n=await o(Io.TIMECODE_ALLTRACK);return!n.result||(await o(Io.CODEC_STRINGS)).result.includes(d6)?n:{result:"",error:""}};parseChannelCountFromStream=(t,o)=>{const r=t?.channels;
1081if(!(r===void 0||Number.isNaN(r))){if(r>10){const n="suspicious channel count "+r+", filename: "+o;h("local.ts").warn(null,n)}return r}};parseStartTimeFromStream=t=>{if(!t||!t.start_time)return;const o=parseFloat(t.start_time);if(!(Number.isNaN(o)||!Number.isFinite(o)))return Math.round(o*1e3)};parseColorSpaceFromStream=t=>{if(!t)return;const o=t.color_space?.toLowerCase();if(o)switch(o){case"bt709":return Ji.BT709;case"bt2020":case"bt2020nc":case"bt2020c":return Ji.BT2020;case"bt2100":return Ji.BT2100;default:return}}}const BR=async(e,t,o,r,n,a,i)=>{const s=h("local.ts"),x=Object.keys(e),c=x.reduce((E,T)=>(E[T]=e[T].exportInfo,E),{}),l=oue(c,t,o,r);if(l===null)return[];const d=x.map(E=>e[E].inputPath),u=await n.getTempFileName(tm),p=aue(d,l,u,a),f=p.reduce((E,T)=>E+T.length+1,Cue);if(f>eRe()){const E="audioTrackArgs len : "+f+", audio transforms num : "+x.length+", split it.";if(s.info(E),x.length<2){const v="Still too long cmd line len but cannot split anymore.";throw s.error(v),new C(_.C_LOGIC_ERROR,void 0,v)}const T=Math.floor(x.length/2),O=x.slice(0,T),S=x.slice(T),R=O.reduce((v,w)=>(v[w]=e[w],v),{}),y=S.reduce((v,w)=>(v[w]=e[w],v),{});return[...await BR(R,t,o,r,n,a,i),...await BR(y,t,o,r,n,a,i)]}return await i(p),[u]},w3=async(e,t,o,r,n,a)=>{const i=h("local.ts");if(e===void 0)return null;const s=Object.keys(e);if(s.length===0)return null;i.info("combining "+s.length+" audio transforms.");const x={};for(const p of s){const f=e[p],E=f.mediaId,T=o.find(S=>S.mediaId===E);if(T){const S=await uw(E,T.originalPath,n);x[p]={exportInfo:f,inputPath:S};continue}const O=await Rue(n,r,E);x[p]={exportInfo:f,inputPath:O}}let c=!1,l=[];for(let p=0;p<2;++p){try{l=await BR(x,t,o,r,n,c,a)}catch(f){const E="Error duing assetAudio input encoding: "+P(f);if(i.warn(E),ye(f)===_.D_ERR_FFMPEG_DEMUX_STREAM_FAILED){i.info("Trying again with extension guessed input format."),c=!0;continue}throw f}break}if(l.length<2)return l[0]??null;i.info("mixing "+l.length+" audio track files into one audio track file");const d=await n.getTempFileName(tm);let u=!1;for(let p=0;p<2;++p){const f=pue(l,d,u);try{await a(f)}catch(E){const T="Error duing assetAudio concat encoding: "+P(E);if(i.warn(T),ye(E)===_.D_ERR_FFMPEG_DEMUX_STREAM_FAILED){i.info("Trying again with extension guessed input format."),u=!0;continue}throw E}break}return d},vue={[Of.BROWSER]:$le,[Of.LOCAL]:yue};class wue{mode;encoders;constructor(){this.mode=at()?Of.LOCAL:Of.BROWSER,this.encoders={}}guessElapsed=t=>this.current.guessElapsed(t);encode=(t,o,r,n,a,i)=>this.current.encode(t,o,r,n,a,i);encodeUserVideos=(t,o,r,n)=>this.current.encodeUserVideos(t,o,r,n);splitMedia=(t,o,r)=>this.current.splitMedia(t,o,r);checkFfmpegExist=t=>this.current.checkFfmpegExist(t);downloadFfmpeg=(t,o)=>this.current.downloadFfmpeg(t,o);get ready(){return this.current.ready}abort=()=>this.current.abort();extractAudio=(t,o,r=!1,n=!1)=>this.current.extractAudio(t,o,r,n);sliceAudio=(t,o,r,n)=>this.current.sliceAudio(t,o,r,n);extractAudioFragment=(t,o,r,n)=>this.current.extractAudioFragment(t,o,r,n);clearExtractedAudioTempFile=t=>this.current.clearExtractedAudioTempFile(t);get current(){const t=this.encoders[this.mode];if(t)return t;const o=new vue[this.mode];return this.encoders[this.mode]=o,o}getMediaFileInfo=t=>this.current.getMediaFileInfo(t);getMediaFileStartTimes=t=>this.current.getMediaFileStartTimes(t);getAudioTrackNum=t=>this.current.getAudioTrackNum(t);getVideoKeyFrameInterval=t=>this.current.getVideoKeyFrameInterval(t);getTimecode=t=>this.current.getTimecode(t);getRFrameRate=t=>this.current.getRFrameRate(t);initAvailableHwAccel=()=>this.current.initAvailableHwAccel();updateAvailableHwAccel=t=>this.current.updateAvailableHwAccel(t);getAvailableHwAccel=()=>this.current.getAvailableHwAccel();getBitRate=t=>this.current.getBitRate(t);getColorSpace=t=>this.current.getColorSpace(t);checkPhaseReverse=t=>this.current.checkPhaseReverse(t);getAudioMetaInfo=t=>this.current.getAudioMetaInfo(t);getUnknownCodecAudioStream=t=>this.current.getUnknownCodecAudioStream(t)}let wO;const qt=()=>(!wO&&(wO=new wue),wO);var Nue=(e=>(e[e.FORMAT=0]="FORMAT",e[e.ASSET=1]="ASSET",e[e.EFFECT=2]="EFFECT",e))(Nue||{});const Pue="ts",hM="e1",bue="1.6",IM=.7,Lue=-.2,N3=.05,Mue="6",Due="-6",kue="1",Fue=.07,Uue=315,TM="Apple SD Gothic Neo",Vue="맑은고딕",Gue=255,SM=10,Wue=6,P3=30,b3=1;class Hue{videoInfoList;clipData=[];captionStyles;fromMacOsX;
1081styleDefCache={};totalClipDuration=0;sequenceNumerator;sequenceDenominator;forDavinci;styleNameCount=0;lang;equalFormat;fcpxDefaultStrokeWidth;constructor(t,o,r,n,a){this.videoInfoList=t,this.forDavinci=n===gi.DAVINCI,this.captionStyles=r,this.fromMacOsX=o,this.lang=a,this.equalFormat=this.checkSizeAndRate(),this.equalFormat?(this.sequenceNumerator=t[0].rNumerator,this.sequenceDenominator=t[0].rDenominator):(this.sequenceNumerator=P3,this.sequenceDenominator=b3),this.fcpxDefaultStrokeWidth=Due}async generate(t,o,r,n){const a=await pt().getFcpxVersion(),i=Bue(a);h("fcpx.ts").info("Current fcpx version "+a+", "+(i?"old":"new")+" stroke width applied."),i&&(this.fcpxDefaultStrokeWidth=Mue),this.initClipData(t,o,r,n);const s=this.getClips(),x=(()=>{const u=[],p=this.getFormats(),f=this.getAssets();return Array.isArray(p)?p.forEach(E=>u.push({format:E})):u.push({format:p}),Array.isArray(f)?f.forEach(E=>u.push({asset:E})):u.push({asset:f}),u.push({effect:{"@id":hM,"@name":"Custom","@uid":".../Titles.localized/Build In:Out.localized/Custom.localized/Custom.moti"}}),u})(),c={"#comment":"Generated by Vrew "+Ha()+" : at "+new Date().toLocaleString(),fcpxml:{"@version":bue,"import-options":{option:{"@value":"1","@key":"suppress warnings"}},resources:x,library:{event:{project:{"@name":gt(se().getCurrentProjectPath()).replace(bi(Ed),"").replace(bh,"").slice(0,Gue),sequence:{"@duration":this.getTimeStr(this.sequenceNumerator,this.getNearestMultiple(this.totalClipDuration)),"@format":this.idGenerator(0,this.getSequenceId()),"@tcStart":"0s",spine:s.map(u=>({["@name"in u[0]?"asset-clip":"gap"]:u}))}}}}}};return qU.create(c,{version:"1.0",encoding:"utf-8",invalidCharReplacement:"",separateArrayItems:!0}).end({pretty:!0})}getNearestMultiple=(t,o)=>{o===void 0&&(o=this.sequenceDenominator);const r=t%o;return r>o/2?t+(o-r):t-r};initClipData=(t,o,r,n)=>{let a,i=0;const s=WI(t,o,{},{},{},Kl.WITH_CAPTION,this.lang,r,n).map(l=>{if((!l.visualMedia?.mediaId||l.visualMedia?.mediaId===_o)&&(!l.audioMedia?.mediaId||l.audioMedia?.mediaId===_o)){const S=this.getNearestMultiple(Math.round(l.timelineDuration*this.sequenceNumerator)),R=i;i+=S;let y=null;return l.clipIndex!==a&&l.captions&&(a=l.clipIndex,y=l.captions),{clipIndex:l.clipIndex,duration:S,offset:R,captions:y||void 0,captionDuration:y?-1:void 0,visualInfoIndex:-1,audioInfoIndex:-1}}const d=l.visualMedia?.mediaId?this.getVideoInfoIndex(l.visualMedia.mediaId):-1,u=l.audioMedia?.mediaId?this.getVideoInfoIndex(l.audioMedia.mediaId):-1;if(d===-1&&u===-1)throw new C(_.C_LOGIC_ERROR,{},"Neither visual nor audio timecode source found for clip with mediaId");let p;if(d!==-1&&l.visualMedia){const S=this.videoInfoList[d],R=Math.round((l.visualMedia.start+S.timecode.sec)*this.sequenceNumerator)+S.timecode.ff*this.sequenceNumerator*S.rDenominator/S.rNumerator;p=this.getNearestMultiple(R)}let f;if(u!==-1&&l.audioMedia){const S=this.videoInfoList[u],R=Math.round((l.audioMedia.start+S.timecode.sec)*this.sequenceNumerator)+S.timecode.ff*this.sequenceNumerator*S.rDenominator/S.rNumerator;f=this.getNearestMultiple(R)}const E=this.getNearestMultiple(Math.round(l.timelineDuration*this.sequenceNumerator)),T=i;i+=E;let O=null;return l.clipIndex!==a&&l.captions&&(a=l.clipIndex,O=l.captions),{clipIndex:l.clipIndex,visualStart:p,audioStart:f,duration:E,offset:T,captions:O||void 0,captionDuration:O?-1:void 0,visualInfoIndex:d,audioInfoIndex:u}});let x=-1,c=0;a=void 0;for(let l=0;l<s.length;l++)a!==void 0&&(a===s[l].clipIndex?c+=s[l].duration:(s[x].captionDuration=c,a=void 0,c=0)),a===void 0&&s[l].captions&&(a=s[l].clipIndex,x=l,c=s[l].duration);a!==void 0&&(s[x].captionDuration=c),this.clipData=s,this.totalClipDuration=i};getTimeStr(t,o){return o+"/"+t+"s"}checkSizeAndRate=()=>{const t=this.videoInfoList.filter(i=>!i.isAudio);if(t.length===0)return this.videoInfoList.length>0;const o=t[0].width,r=t[0].height,n=t[0].rNumerator,a=t[0].rDenominator;for(let i=1;i<t.length;i++)if(t[i].width!==o||t[i].height!==r||t[i].rDenominator!==a||t[i].rNumerator!==n)return!1;return!0};getLineNum(t){let o=1;for(let r=0;r<t.length;r++)t[r]===`
1082`&&o++;return o}getColorStr(t){const{r:o,g:r,b:n}=Fn(t).toRgb(),a=Fn(t).alpha();return o+" "+r+" "+n+" "+a}getVideoInfoIndex(t){return this.videoInfoList.findIndex(r=>r.mediaId===t)}getClips(){const t=(o,r,n,a)=>
1082{if(!o.captions||o.captionDuration===void 0)return;const i=r?o.captions[1]:o.captions[0],s=ov(i||""),x=s.trim();if(x==="")return;const c=n+this.getLineNum(x),l=""+Pue+this.styleNameCount;this.styleNameCount=this.styleNameCount+1;const d=o.audioStart??o.visualStart??0,u={"@lane":a.toString(),"@name":s.substring(0,30),"@ref":hM,"@offset":this.getTimeStr(this.sequenceNumerator,d),"@start":this.getTimeStr(this.sequenceNumerator,o.offset),"@duration":this.getTimeStr(this.sequenceNumerator,o.captionDuration),text:{"text-style":{"@ref":l,"#text":x}},"text-style-def":{"@id":l,"text-style":this.getTextStyle(c)}};if(this.forDavinci){const{size:p,yAlign:f,yOffset:E}=el(this.captionStyles),T=p??100,O=Math.round(go.VIRTUAL_YRES*(KR(f,0)+E)),S=T*IM/1080,R=l2e(O,S,r,c);u["adjust-transform"]={"@position":"0 "+R,"@scale":"1 1","@anchor":"0 0"}}return u};return this.clipData.map(o=>{const r=this.clipData.some(x=>x.captions&&x.captions[1]!==void 0&&x.captions[1]!==""),n=t(o,!1,r?this.getLineNum(o.captions?.[1]||""):0,r?2:1),a=r?t(o,!0,0,1):void 0;if(o.visualInfoIndex===-1&&o.audioInfoIndex===-1){const x={"@start":this.getTimeStr(this.sequenceNumerator,0),"@offset":this.getTimeStr(this.sequenceNumerator,o.offset),"@duration":this.getTimeStr(this.sequenceNumerator,o.duration)},c=[];return a&&c.push({...x,title:a}),n?c.push({...x,title:n}):c.length===0&&c.push(x),c}if(o.visualInfoIndex===o.audioInfoIndex&&o.visualInfoIndex!==-1&&o.visualStart===o.audioStart){const x={"@name":this.videoInfoList[o.visualInfoIndex].name,"@ref":this.idGenerator(1,o.visualInfoIndex+1,"both"),"@start":this.getTimeStr(this.sequenceNumerator,o.visualStart),"@offset":this.getTimeStr(this.sequenceNumerator,o.offset),"@duration":this.getTimeStr(this.sequenceNumerator,o.duration)},c=[];return a&&c.push({...x,title:a}),n?c.push({...x,title:n}):c.push(x),c}if(o.visualInfoIndex===-1&&o.audioInfoIndex!==-1){const x=o.audioStart??0,c={"@name":this.videoInfoList[o.audioInfoIndex].name,"@ref":this.idGenerator(1,o.audioInfoIndex+1,"both"),"@start":this.getTimeStr(this.sequenceNumerator,x),"@offset":this.getTimeStr(this.sequenceNumerator,o.offset),"@duration":this.getTimeStr(this.sequenceNumerator,o.duration)},l=[];return a&&l.push({...c,title:a}),n?l.push({...c,title:n}):l.push(c),l}const s=[];if(o.visualInfoIndex!==-1&&o.visualStart!==void 0){const x={"@name":this.videoInfoList[o.visualInfoIndex].name,"@ref":this.idGenerator(1,o.visualInfoIndex+1,"video"),"@start":this.getTimeStr(this.sequenceNumerator,o.visualStart),"@offset":this.getTimeStr(this.sequenceNumerator,o.offset),"@duration":this.getTimeStr(this.sequenceNumerator,o.duration)};a&&s.push({...x,title:a}),n?s.push({...x,title:n}):s.push(x)}else if(n||a){const x={"@start":this.getTimeStr(this.sequenceNumerator,0),"@offset":this.getTimeStr(this.sequenceNumerator,o.offset),"@duration":this.getTimeStr(this.sequenceNumerator,o.duration)};a&&s.push({...x,title:a}),n&&s.push({...x,title:n})}if(o.audioInfoIndex!==-1&&o.audioStart!==void 0){const x={"@name":this.videoInfoList[o.audioInfoIndex].name,"@ref":this.idGenerator(1,o.audioInfoIndex+1,"audio"),"@start":this.getTimeStr(this.sequenceNumerator,o.audioStart),"@offset":this.getTimeStr(this.sequenceNumerator,o.offset),"@duration":this.getTimeStr(this.sequenceNumerator,o.duration)};s.push(x)}return s})}getTextStyle(t){if(this.styleDefCache[t])return this.styleDefCache[t];const o=el(this.captionStyles),r=o.size??go.DEFAULT_SIZE,n=Math.round(r*IM),a=p=>p.toFixed(1).toString(),i={"@alignment":"center","@fontColor":this.getColorStr(o.color??go.DEFAULT_TEXT_COLOR)},s=hv(o.fontName,o.weight);let x=o.fontName;this.forDavinci?s&&(x=this.fromMacOsX?TM:Vue):(s||!this.fromMacOsX)&&(x=TM),i["@font"]=x,i["@fontSize"]=n.toString(),i["@lineSpacing"]=this.forDavinci?0:a(n*Lue);const c=Math.round(go.VIRTUAL_YRES*(KR(o.yAlign,0)+o.yOffset)),l=d2e(c)+n*(t-1)*(1-N3);i["@baseline"]=this.forDavinci?0:a(l);const d=this.forDavinci?kue:this.fcpxDefaultStrokeWidth;if(o.shadowInfo){i["@shadowColor"]=this.getColorStr(o.shadowInfo.shadowColor??go.DEFAULT_STYLE_COLOR);const p=(n*Fue).toFixed(1);i["@shadowOffset"]=p+" "+Uue}const u=g2e(this.captionStyles.captionStyleSetting);return u&&(i["@strokeColor"]=this.getColorStr(u)),i["@strokeWidth"]=d,this.styleDefCac
1082he[t]=i,i}getSequenceId=()=>this.equalFormat?1:0;getFormats(){const t={"@id":this.idGenerator(0,this.getSequenceId()),"@frameDuration":this.getTimeStr(this.sequenceNumerator,this.sequenceDenominator)};if(this.equalFormat){const o=this.videoInfoList.find(r=>!r.isAudio);return o&&(t["@width"]=o.width,t["@height"]=o.height),t}else{const o=se().getInitProjectVideoSize();t["@width"]=o.width,t["@height"]=o.height;const r=this.videoInfoList.map((n,a)=>{const i={"@id":this.idGenerator(0,a+1)};return!n.isAudio&&(i["@frameDuration"]=this.getTimeStr(n.rNumerator,n.rDenominator),i["@width"]=n.width,i["@height"]=n.height),i});return[t,...r]}}getFilePath(t){return this.forDavinci?this.fromMacOsX?"file://"+t.replace(/\\/g,"/"):"file://localhost/"+t.replace(/\\/g,"/"):p6(gt(t))}getAssets(){const t=new Map;this.clipData.forEach(r=>{if(r.visualInfoIndex===-1&&r.audioInfoIndex===-1)return;if(r.visualInfoIndex===r.audioInfoIndex&&r.visualInfoIndex!==-1&&r.visualStart===r.audioStart){const a=r.visualInfoIndex,i=t.get(a);i?(i.usedAsBoth=!0,i.firstBothStart===void 0&&(i.firstBothStart=r.visualStart)):t.set(a,{usedAsBoth:!0,usedAsVideo:!1,usedAsAudio:!1,firstBothStart:r.visualStart})}else if(r.visualInfoIndex===-1&&r.audioInfoIndex!==-1){const a=r.audioInfoIndex,i=r.audioStart??0,s=t.get(a);s?(s.usedAsBoth=!0,s.firstBothStart===void 0&&(s.firstBothStart=i)):t.set(a,{usedAsBoth:!0,usedAsVideo:!1,usedAsAudio:!1,firstBothStart:i})}else{if(r.visualInfoIndex!==-1&&r.visualStart!==void 0){const a=t.get(r.visualInfoIndex);a?(a.usedAsVideo=!0,a.firstVisualStart===void 0&&(a.firstVisualStart=r.visualStart)):t.set(r.visualInfoIndex,{usedAsBoth:!1,usedAsVideo:!0,usedAsAudio:!1,firstVisualStart:r.visualStart})}if(r.audioInfoIndex!==-1&&r.audioStart!==void 0){const a=t.get(r.audioInfoIndex);a?(a.usedAsAudio=!0,a.firstAudioStart===void 0&&(a.firstAudioStart=r.audioStart)):t.set(r.audioInfoIndex,{usedAsBoth:!1,usedAsVideo:!1,usedAsAudio:!0,firstAudioStart:r.audioStart})}}});const o=[];return t.forEach((r,n)=>{const a=this.videoInfoList[n],i=s=>{const x={"@src":this.getFilePath(a.sourcePath),"@format":this.idGenerator(0,this.equalFormat?1:n+1),"@duration":this.getTimeStr(a.rNumerator,this.getNearestMultiple(a.duration*a.rNumerator,a.rDenominator)),"@name":a.name};return s!==void 0&&(x["@start"]=this.getTimeStr(this.sequenceNumerator,s)),x};if(r.usedAsBoth){const s=r.firstBothStart??r.firstVisualStart??r.firstAudioStart;o.push({"@id":this.idGenerator(1,n+1,"both"),...i(s),"@hasAudio":1,"@hasVideo":""+(a.isAudio?0:1)})}r.usedAsVideo&&o.push({"@id":this.idGenerator(1,n+1,"video"),...i(r.firstVisualStart),"@hasAudio":0,"@hasVideo":1}),r.usedAsAudio&&o.push({"@id":this.idGenerator(1,n+1,"audio"),...i(r.firstAudioStart),"@hasAudio":1,"@hasVideo":0})}),o}idGenerator(t,o,r){let n="";switch(t){case 0:n="f";break;case 1:n="a";break;case 2:n="e";break}if(t===1&&r&&r!=="both"){const a=r==="video"?"v":"a";return""+n+o+a}return""+n+o}}const L3=async e=>{const t={numerator:P3,denominator:b3};try{const o=await qt().getRFrameRate(e);return o===void 0?t:o}catch(o){return h("fcpx.ts").error("Failed to get frame rate from source file. Using default frame rate : "+P(o)),t}},jue=async(e,t)=>{let r={sec:0,ff:0,isNonDrop:!0,forceNonDrop:!1};if(u6.test(e)){const n=await qt().getTimecode(e);if(n!==void 0){let a=n.sec;const{numerator:i,denominator:s}=t,x=i/s%1===0;if(n.isNonDrop&&x===!1&&n.forceNonDrop===!1){h("fcpx.ts").info("Timecode is non drop-frame, but adjust sec as drop frame, because frame rate is ntsc type. numerator:"+i+", denominator:"+s);const l=Math.round(i/s),d=l/(i/s);a=a*d}r={...n,sec:a}}}return r},zue=(e,t)=>Number.isInteger(e)?{numerator:e,denominator:1}:{numerator:Math.round(e)*1e3,denominator:1001},Yue=async(e,t,o,r,n,a,i,s,x)=>{let c=!1;const l=await Promise.all(o.filter(u=>u.mediaId!==_o).map(async u=>{if(u.fileLocation!==D.LOCAL&&u.fileLocation!==D.LOCAL_TMP){const M="[getFCPXFormatXMLForFCPXandDaVinci] Failed to get url info for mediaId: "+u.mediaId;throw h("fcpx.ts").error(M),new C(_.C_LOGIC_ERROR,{mediaId:u.mediaId},M)}const p=u.path,f=s!==null?zue(s):await L3(p),E=f.numerator,T=f.denominator,O=u.videoAudioMetaInfo.videoInfo,S=u.videoAudioMetaInfo.duration,R=u.videoAudioMetaInfo.videoInfo===void 0,y=await jue(p,f);let v=om.width,w=om.height;if(O){const M=I0(O.size);v=M.width,w=M.height}else!R&&(c=!0);
1082return{width:v,height:w,rNumerator:E,rDenominator:T,sourcePath:p,name:u.name,isAudio:R,duration:S,mediaId:u.mediaId,timecode:y}}));return c?(h("fcpx.ts").error("FCPXml export error",c,l.length),""):new Hue(l,r,n,a,i).generate(e,t,x,n)},Bue=e=>{if(e==="")return!1;const t=e.match(/(\d+)\.?(\d+)?\.?/);if(t&&t[1]){const o=parseFloat(t[1]),r=t[2]?parseFloat(t[2])??0:0;if(o<SM||o===SM&&r<Wue)return!0}else h("fcpx.ts").warn("Parsing fcpx version "+e+" failed.");return!1},Kue=80,Ar=e=>[ce.Japanese,ce.Taiwanese,Jc.LAO,Jc.CHINESE_SIMPLIFIED].includes(e)===!1,Xue=(e,t)=>{const r=on(t);return e.map(a=>Hn(a,Ar(r),0))},Jue=(e,t,o)=>{const{maxLineLength:r,mode:n}=t;if(e===pn.None)return"";const a=Ar(e)?" ":"",i=o[e][n],s=z0(x0(0,i.length),r,(x,c)=>{const l=i.slice(0,x+1).join(a);return c-l.replace(`
1083`,"").length+1},!0);return i.slice(0,s).join(a)},ud=(e,t=!0,o=!0,r=!0)=>{const n=r?" ":"";let a="";e.forEach(s=>{const x=s.hardcutWordMeta?"":n;s.type!==Z.AUDIO_EVENT&&s.text&&(a=a.concat(x,s.text))});const i=o?LT(a):a;return t?i.trim():i},que=(e,t,o,r=!0,n=!0)=>{const{captionMode:a,captions:i}=e;return o===0&&a===ar.TRANSCRIPT?ud(e.words,r,n,t):i[o]?u0e(i[o].text):""},Hn=(e,t,o,r=!0,n=!0)=>{const{captionMode:a,captions:i}=e;return o===0&&a===ar.TRANSCRIPT?ud(e.words,r,n,t):i[o]?wt().toText(i[o].text):""},Que=(e,t,o)=>e.captions.map((r,n)=>o[n]?Hn(e,t,n):void 0).filter(r=>r!==void 0).join(`
1084`),Ew=(e,t,o,r)=>{const n=e.captions.map((x,c)=>o[c]?Hn(e,Ar(on(t)),c):void 0).filter(Se),a={[Ke.ORIGINAL]:void 0,[Ke.TRANSLATE]:void 0};
1084[Ke.ORIGINAL,Ke.TRANSLATE].forEach(x=>{if(!o[x])return;const l=Dm(e,x,t,r);L.set(a,x,l)});const i={[Ke.ORIGINAL]:void 0,[Ke.TRANSLATE]:void 0};[Ke.ORIGINAL,Ke.TRANSLATE].forEach(x=>{const c=a[x];if(c===void 0)return;const{webModel:l}=c,d=cs(e),u=MI(l.assetEffectInfo,BG(pe(d))),p={assetId:qe(),startTimelineTime:vo(e),duration:d,animationInfo:u},f={type:Ce.WEB,asset:l,animationExportInfo:p};L.set(i,x,f)});const s=[Ke.ORIGINAL,Ke.TRANSLATE].map(x=>{const c=a[x];if(c===void 0)return;const{webModel:l,yAlign:d}=c;return{type:Ce.CAPTION,asset:l,captionType:x,yAlign:d,[Ke.ORIGINAL]:a[Ke.ORIGINAL]?.yAlign===d?i[Ke.ORIGINAL]:void 0,[Ke.TRANSLATE]:a[Ke.TRANSLATE]?.yAlign===d?i[Ke.TRANSLATE]:void 0,timeline:{timelineStart:vo(e),duration:cs(e)}}}).filter(Se);return{captionStrings:n,exportCaptionModels:s}},Lm=e=>Math.round(e*100)*10,Zue=(e,t,o)=>e.map(r=>{const n=Ar(t),a=vo(r),i=cs(r),s=Que(r,n,o);return{start:Lm(a),end:Lm(a+i),text:s}}),$ue=(e,t)=>{const o=e.map((r,n)=>{const a=vo(r),i=cs(r),s=t[n]?.text||"";return{start:Lm(a),end:Lm(a+i),text:s}}).map(r=>({...r,text:r.text.replace(/\n*$/,"")})).filter(r=>r.text.trim().length>0);return QU(o)},e2e=(e,t,o)=>{const r=Zue(e,t,o).map(n=>({...n,text:ov(n.text.trim().replace(/\r(?!\n)/g,"").replace(/^(?:[\t ]*(?:\r?\n))+/gm,""))})).filter(n=>n.text.length>0);return QU(r)},Zp=(e,t)=>{const o=new Ns,r=new FileReader;return r.onload=()=>{o.resolve(r.result)},r.onerror=()=>{h("caption.ts").error("Error during read blob: "+r.error),o.reject(new C(_.C_SYSTEM_API_ERROR))},r.readAsText(e,t),o.promise()},t2e={[ce.Japanese]:OU,[ce.Korean]:SU},o2e=async(e,t,o)=>{const r=t2e[t];if(!r)return Zp(e,o[0]);let n="";for(let a=0;a<o.length;++a){const i=o[a],s=await Zp(e,i);if(a===0&&(n=s),r.test(s.slice(0,100)))return h("caption.ts").info("Encoding "+i+" matched this text."),s}return h("caption.ts").info("No encoding matched for this text. using first one."),n},r2e=async(e,t)=>{try{const o=await e.arrayBuffer(),r=new Uint8Array(o),n=P9.analyse(r);
1084if(h("caption.ts").info("Encoding guess result : "+JSON.stringify(n)+", audioLanguage : "+t),n.length===0)return Zp(e);if(n.length===1||n[0].confidence>=Kue)return Zp(e,n[0].name);const a=n.map(i=>i.name);return o2e(e,t,a)}catch(o){return h("caption.ts").error("Error during detect encoding : "+P(o)),Zp(e)}},n2e=async(e,t)=>{try{const o=await VK(e).catch(r=>{throw dg.test(e.name)?new C(_.C_IMPORT_SHARED_FOLDER_READ):new C(_.C_LOCAL_FILE_FETCH_FAILED)});return r2e(o,t)}catch(o){const r=ye(o)??_.C_LOCAL_FILE_FETCH_FAILED;if(r===_.C_IMPORT_SHARED_FOLDER_READ)h("caption.ts").error("trying to load shared folder path "+e.name);else{const a=P(o);h("caption.ts").error(a)}const n=Ot(r,{defaultKey:"error.local_file_fetch_failed"});return Y().error(r,n),mP(r),null}},a2e=()=>{const e=Ve().getNumber(Ie.LAST_CAPTION_SIZE);return Eo(OR).isValue(e)?e:OR.P_04_100},i2e=()=>{const e=Ve().getObject(Ie.LEGACY_LAST_CAPTION_FONT_FAMILY);if(Array.isArray(e))return e[0]},s2e=()=>Ve().getNumber(Ie.LEGACY_LAST_CAPTION_WEIGHT,700),mw=(e,t)=>{const o=t===Yh.HORIZONTAL?go.HORIZONTAL_MAX_RANGE:go.VERTICAL_MAX_RANGE,r=e/o;return Math.round(r*go.SLIDE_RANGE)},x2e=e=>{const t=i0e(),o=i2e(),r=o?s2e():void 0,n=a0e(Fe()),a=a2e(),i=t?.fontName??o??n.fontName,s=t?.weight??r??n.weight,x=Mt(ke.LAST_USED_CAPTION_TEXT_COLOR)??go.DEFAULT_TEXT_COLOR,c=Mt(ke.LAST_USED_CAPTION_OUTLINE_COLOR)??go.DEFAULT_STYLE_COLOR,l=Mt(ke.LAST_USED_CAPTION_OUTLINE_WIDTH)??go.OUTLINE_WIDTH,d=Mt(ke.LAST_USED_CAPTION_SHADOW_COLOR)??Ri,u=Mt(ke.LAST_USED_CAPTION_BACKGROUND_COLOR)??Ri,p=Ve().getNumber(Ie.LAST_CAPTION_POS_INFO_X,Bh),f=Ve().getNumber(Ie.LAST_CAPTION_POS_INFO_Y),E=hw(Ve().get(Ie.LAST_CAPTION_POS_INFO_X_ALIGN,Ai.CENTER)),T=Iw(Ve().get(Ie.LAST_CAPTION_POS_INFO_Y_ALIGN,oo.BOTTOM)),O=Fn(u).toRgbString(),S={...Eg.captionStyleSetting,yAlign:T,xOffset:p,yOffset:f,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:O},{attributeName:"--textbox-align",type:"textbox-align",value:E}],scaleFactor:e},R={font:i+"_"+s,size:a.toString(),color:x.toLowerCase()};return l&&(R["outline-on"]="true",R["outline-color"]=c.toLowerCase(),R["outline-width"]=""+l),d!==Ri&&(R["shadow-on"]="true",R["shadow-color"]=d.toLowerCase(),R["shadow-blur-radius"]="4",R["shadow-color-alpha"]="0.5"),{captionStyleSetting:S,quillStyle:R}},hw=e=>({[Ai.LEFT]:"start",[Ai.CENTER]:"center",[Ai.RIGHT]:"end"})[e],Iw=e=>({[oo.TOP]:"top",[oo.MIDDLE]:"middle",[oo.BOTTOM]:"bottom",[oo.CUSTOM]:"custom"})[e],c2e=e=>{const r=go.VIRTUAL_YRES;return .5+(1-e/r)*(-.5-.5)},l2e=(e,t,o,r)=>{const n=go.VIRTUAL_YRES,a=1-e/n,i=(-.5+t/2)*100,s=(-.5+n/1080+t/2)*100,x=i+a*(s-i);return o?x:x+t*100*(1-N3)*(r-1)},d2e=e=>{const t=go.VIRTUAL_YRES,o=1-e/t,r=-540;return r+o*(540-r)},u2e=(e,t,o,r,n)=>{const{captions:a}=t;return a.map((i,s)=>{if(s===0&&r)return{text:wt().fromText("")};const x=Ar(o[s]),{text:c,style:l}=e[s],d=p2e(t,x,s,n);return{text:wt().concat(c,d,x),style:l}})},p2e=(e,t,o,r)=>{const n=e.captions[o];if(e.captionMode===ar.MANUAL)return n.text;const a=Hn(e,t,o,!0);return wt().fromText(a,r.quillStyle)},hot=e=>{const{translateInfo:t,projectAudioLanguage:o}=e;return t!==null?[t.source,t.target]:[on(o)]},Iot=(e,t,o,r)=>!r[t]||!e?!1:(e.style??o.captionStyleSetting).assetEffectInfo!==void 0,XI=e=>e[Ke.ORIGINAL]&&e[Ke.TRANSLATE]?"both":e[Ke.ORIGINAL]&&!e[Ke.TRANSLATE]?"original":!e[Ke.ORIGINAL]&&e[Ke.TRANSLATE]?"translate":"none",Tw=()=>[{text:wt().fromText("")},{text:wt().fromText("")}],f2e=e=>J7()?e:VG(e),Sw=e=>[{text:wt().fromText(e)},{text:wt().fromText("")}],Xl=e=>Sw(f2e(e)),g2e=e=>e?e.customAttributes.find(o=>o.attributeName==="--textbox-color")?.value:void 0,Mm=e=>{const{font:t}=e;if(!t||typeof t!="string")return{fontName:"",weight:0};const{fontName:o,weight:r}=zc(t);return{fontName:o,weight:r}},el=e=>{const{captionStyleSetting:t,quillStyle:o}=e,{fontName:r,weight:n}=Mm(o),a=o["outline-on"]==="true",i=a?{outlineColor:o["outline-color"],outlineWidth:o["outline-width"]?parseInt(o["outline-width"]):void 0,secondOutlineColor:o["secondary-outline-color"],secondOutlineWidth:o["secondary-outline-width"]?parseInt(o["secondary-outline-width"]):void 0}:void 0,s=o["shadow-on"]==="true",x=s?{shadowColor:o["shadow-color"],shadowBlurRadius:o["shadow-blur-radius"]?parseInt(o["shadow-blur-radius"]):void 0,shadowPositionX:o["shadow-position-x"]?parseInt(o["shadow-position-x"]):void 0,shadowPositionY:o["shadow-position-y"]?parseInt(o["shadow-position-y"]):void 0}:void 0,c={fontName:r,weight:n,size:o.size?parseInt(o.size):void 0,color:o.color,bold:o.bold==="true",italic:o.italic==="true",strike:o.strike==="true",underline:o.underline==="true",outlineInfo:i,shadowInfo:x,letterSpacing:o["letter-spacing"]?parseFloat(o["letter-spacing"]):void 0,lineHeight:o["line-height"]?parseFloat(o["line-height"]):void 0};return{...t,...c}},_2e=(e,t)=>
1084ai(e)+"-"+t,Tot=(e,t)=>({webModel:E2e(e,t),captionType:Ke.ORIGINAL,yAlign:Ow(t.captionStyleSetting.yAlign)}),E2e=(e,t)=>{const{captionStyleSetting:o,quillStyle:r}=t,{mediaId:n,customAttributes:a,assetEffectInfo:i,rotation:s,xOffset:x,width:c,yOffset:l,scaleFactor:d}=o,u={[wy]:wt().fromText(e,r)},p=$e().getWebTextboxInlineTypes(n)??Dc();return{trackId:Rt(),mediaId:n,type:z.WEB,deltas:u,loop:!1,durationSeconds:0,importType:Yt.UNKNOWN,enabledInlineTypes:p,customAttributes:a,xPos:x,yPos:l,height:ay,width:c,rotation:s,zIndex:ey.SHORTS_CAPTION_PREVIEW,assetEffectInfo:i,scaleFactor:d}},Dm=(e,t,o,r)=>{const{text:n,style:a,updateReason:i}=e.captions[t],{quillStyle:s}=r,x=a??r.captionStyleSetting,{mediaId:c,customAttributes:l,assetEffectInfo:d,rotation:u,xOffset:p,width:f,yAlign:E,yOffset:T,scaleFactor:O}=x,S=que(e,Ar(on(o)),t),R=a?n:cW(S,s),y={[wy]:R};return{webModel:{trackId:Rt(),mediaId:c,deltas:y,enabledInlineTypes:$e().getWebTextboxInlineTypes(c)??Dc(),customAttributes:l,loop:!1,xPos:p,yPos:T,width:f,height:ay,durationSeconds:0,rotation:u,zIndex:Ooe+t,type:z.WEB,importType:Yt.UNKNOWN,assetEffectInfo:d,updateReason:i,scaleFactor:O},yAlign:Ow(E),captionType:t}},m2e=(e,t)=>{if(!e.style)return t;const{style:o,text:r}=e,n=rn.cloneDeep(o),a=r.ops.find(i=>i!==void 0)?.attributes;return{captionStyleSetting:n,quillStyle:a??{}}},KR=(e,t)=>({top:.1,middle:(1-t)/2,bottom:.97-t,custom:0})[e],h2e=e=>({top:.1,middle:.5,bottom:.97,custom:0})[e],M3=(e,t)=>{const o=e.customAttributes.find(r=>r.attributeName===t.attributeName);o!==void 0&&(o.value=t.value)},Sot=(e,t)=>{po(ke.CAPTION_LENGTH_LIMIT,{isLimited:e,lastLength:t})},Oot=()=>{const{isLimited:e,lastLength:t}=Mt(ke.CAPTION_LENGTH_LIMIT);return{isLimited:e,lastLength:t}},Cot=(e,t,o,r)=>{const{quillStyle:n}=o;if(!e)return{text:wt().fromText("")};if(t===""){const d=wt().fromText(""),u=e.style?wt().getAttribute(e.text,0)??n:void 0;return{text:u?wt().applyAttribute(d,u):d,style:e.style,height:void 0,updateReason:r}}const a=e.style?wt().getAttributeFromDiff(e.text,t)??n:void 0,i=wt().toText(e.text),s=wt().diff(wt().fromText(i),wt().fromText(t)),x=a?wt().applyAttribute(s,a):s;return{text:wt().applyChange(e.text,x),style:e.style,height:void 0,updateReason:r}},q_=(e,t,o)=>{if(wt().isEmpty(e.text))return!1;if(e.style===void 0)return!bc(t,o);const r=o.quillStyle,n=e.text.ops.map(s=>s.attributes).filter(Se);for(const s of n)if(!bc(r,s))return!0;const a=o.captionStyleSetting,i=e.style;return!bc(a,i)},Rot=(e,t)=>o=>{const r=o(),n=Do(r),a=mo(r),i=Tn(r).position,s=bg(r),x=rt(r).globalCaptionStyle;if(e===nt.ALL_CLIPS){for(const c of a)for(const l of c.clips)if(l.captions.some(u=>q_(u,x,t)))return!0}else if(e===nt.SCENE_CLIPS)for(const c of n){const{captions:l}=c;if(l.some(u=>q_(u,x,t)))return!0}else if(e===nt.CURRENT_CLIP){const c=Co(n,i),l=n[c];return l===void 0?!1:l.captions.some(d=>q_(d,x,t))}else if(e===nt.SELECTED_CLIPS)for(const c of s){const{captions:l}=c;if(l.some(u=>q_(u,x,t)))return!0}return!1},I2e=e=>e.map((o,r)=>{const n=qI(o)??JI(o);return"["+r+", "+n+"]"}).join(`
1085`),Aot=e=>e.reduce((o,r)=>{const n=qI(r)??JI(r);return o+n},""),yot=e=>e.reduce((o,r)=>{const n=qI(r)??(r.dirty.caption?"":JI(r));return o+n},""),JI=e=>e.words.filter(o=>o.type!==Z.AUDIO_EVENT).map(o=>o.text).join(" ").trim(),qI=e=>{const t=e.captions[0].text.ops.map(o=>o.insert).join("").replace(/\n/g,"").trim();return t.length>0?t:null},T2e=e=>qI(e)??JI(e),vot=(e,t,o,r,n,a,i)=>{const s=(n-o)/e,x=(a-r)/t,c=i/e;return{xPos:s,yPos:x,width:c}},wot=(e,t)=>{const{left:o,top:r,width:n,height:a}=e.getBoundingClientRect(),i=[o+n/2,r+a/2],s=e.clientWidth,x=e.clientHeight,c=s*t,l=x*t;return{left:i[0]-c/2,top:i[1]-l/2,width:c}},_a=e=>{const t=e[e.captionType];if(t===void 0)throw h("caption.ts").error("exportWebModel is undefined while extracting it from ExportCaptionModel."),new C(_.C_LOGIC_ERROR);return t},D3=(e,t)=>{const o=e.width*t.width,r=Rv(t.width,t.height,e.scaleFactor),n="translate("+e.xPos*t.width/r+"px, "+e.yPos*t.height/r+"px)",a="rotate("+e.rotation+"deg)";return Bl({position:"relative",width:o/r+"px","transform-origin":"center",transform:n+" "+a})},S2e=e=>{switch(e){case oo.TOP:return 0;case oo.MIDDLE:return 50;case oo.BOTTOM:return 100;default:return 0}},k3=(e,t,o,r)=>{const n="translate("+.5*o+"px, "+h2e(e)*r+"px)",a="scale("+t+")",i="translate(-50%, -"+S2e(e)+"%)";return n+" "+a+" "+i},Not=(e,t,o,r)=>({pointerEvents:"none",transformOrigin:"top left",transform:k3(e,t,o,r)}),Pot=e=>({[oo.TOP]:Q_(e,oo.TOP),[oo.MIDDLE]:Q_(e,oo.MIDDLE),[oo.BOTTOM]:Q_(e,oo.BOTTOM),[oo.CUSTOM]:Q_(e,oo.CUSTOM)}),Q_=(e,t)=>[e[Ke.ORIGINAL],e[Ke.TRANSLATE]].filter(Se).filter(r=>r.yAlign===t),Ow=e=>{switch(e){case"top":return oo.TOP;case"middle":return oo.MIDDLE;case"bottom":return oo.BOTTOM;
1085case"custom":return oo.CUSTOM}},OM=(e,t,o,r,n,a,i)=>{const s=N2(e,n,a,i)?ar.MANUAL:o.captionMode===ar.TRANSCRIPT||I0e(e,t,r[Ke.ORIGINAL])?ar.TRANSCRIPT:ar.MANUAL,x=vt(t,c=>{o.captionMode!==ar.MANUAL&&s===ar.MANUAL&&(c[Ke.ORIGINAL]=Sw(ud(e,!0,!0,Ar(r[Ke.ORIGINAL])))[Ke.ORIGINAL])});return{captionMode:s,captionModel:x}},bot=(e,t)=>e?.captionIndex===t?.captionIndex&&e?.globalClipIndex===t?.globalClipIndex&&e?.initCaretPosition===t?.initCaretPosition,Lot=(e,t,o=!1)=>{const r=t.find(n=>n.attributeName===e);if(!(r?.value===Ri&&!o))return r?.value},w2=(e,t,o,r,n,a)=>{const i=e.at(t);if(i===void 0)return h("caption.ts").error("globalClip is undefined at getGlobalClipCaptionStyleContext()"),null;const{captions:s}=i,x=n?.captionIndex!==void 0&&s.at(n.captionIndex)?.style!==void 0?{targetGlobalClipIndices:[n.globalClipIndex],captionIndex:n.captionIndex}:null,c=a!==null&&s.at(a.captionIndex)?.style!==void 0?{targetGlobalClipIndices:[a.globalClipIndex],captionIndex:a.captionIndex}:null,l=n?.captionIndex??a?.captionIndex,d=OH(i,r,l),u=O2e(o,d,t);return x??c??u},O2e=(e,t,o)=>e.size!==0?{targetGlobalClipIndices:Array.from(e)}:t?{targetGlobalClipIndices:[o]}:null,C2e=.7;let hs;const F3=()=>{if(hs===void 0){hs=[];const e=Ve().getObject(Ie.LAST_USED_TARGET_LANGUAGES);Array.isArray(e)&&e.forEach(t=>{hs?.push(t)})}return[...hs]},Mot=()=>{const e=F3();if(e.length!==0)return e[e.length-1]},R2e=e=>{if(hs!==void 0){for(let t=0;t<hs.length;t++)hs[t]===e&&hs.splice(t,1);hs.length===5&&hs.splice(0,1),hs.push(e),Ve().set(Ie.LAST_USED_TARGET_LANGUAGES,hs)}},U3=async(e,t)=>{const o=h("translate.ts"),r="/merge-clause",n=e.length,a={language:t,clauses:e},i=await eh(r,{method:"POST",body:JSON.stringify(a)}).then(l=>l.json()).catch(l=>{throw o.error("During linebreaker, error occurred : "+P(l)),new C(_.C_LINEBREAKER_FAILED_ERROR)});if(i.error)throw o.error("Error occurred on linebreaker server: "+i.error.message),new C(_.C_LINEBREAKER_FAILED_ERROR);o.info("mergedClauseIndices: "+JSON.stringify(i,void 0,4));const s=i.groupedClauseIndices||[],x=y2e(s,e,t),c=x.reduce((l,d)=>l+d.numClause,0);if(c!==n)throw new C(_.C_LOGIC_ERROR,{},"sum of numClauseSum "+c+" must be same as caption length "+n);return x},CM=e=>e===ce.Taiwanese?"zh-TW":e,A2e=async(e,t,o,r,n,a)=>{const i=h("translate.ts"),s=a?a+", ":"";if(i.info("translate start. "+s+"numSentence:"+e.length+", engine:"+r.engine),e.join("").length===0)return{translations:e,numInconsistentLangSentence:0,engineInfo:r,sid:void 0};const x=await v2e(e,r,CM(t),CM(o),n,a);if(x.error)throw i.error("Error occurred on operator server: "+x.error),new C(_.C_TRANSLATION_FAILED_ERROR,{engine:r.engine});x.sid===void 0&&i.error("Error fail to get translate sid}");let c=0;const l=x?.body.map(u=>(u.detectedSourceLanguage&&u.detectedSourceLanguage!==t&&(c+=1),N2e(u.translatedText)))||[];i.info("translate "+s+" done.");const d=x.sid;return{translations:l,numInconsistentLangSentence:c,engineInfo:r,sid:d}},km=async(e,t)=>{const o=h("translate.ts"),r="/split-sentence",n=e.map(l=>({sentence:l.text,targetSplitNumber:l.numClause})),a={sentenceSplitPayloads:n,language:t},i=await eh(r,{method:"POST",body:JSON.stringify(a)}).then(l=>l.json()).catch(l=>{throw o.error("During linebreaker split, error occurred : "+P(l)),new C(_.C_LINEBREAKER_FAILED_ERROR)});if(i.error)throw o.error("Error occurred on linebreaker server: "+i.error.message),new C(_.C_LINEBREAKER_FAILED_ERROR);const s=i.splittedSentences||[];return o.info("splitted sentence done."),s.forEach((l,d)=>{l.splittedSentence.length!==n[d].targetSplitNumber&&o.error("split targets's target split number is different to result splitted sentences' sentence number.:"+JSON.stringify(l)+" "+JSON.stringify(n[d]))}),s.map(l=>l.splittedSentence).flat().map(l=>(l=J7()===!1?VG(l):l,{text:l}))},y2e=(e,t,o)=>{const r=o===ce.Japanese?"":" ",n=e.flat(),a=t.map((s,x)=>x).filter(s=>!n.includes(s)).map(s=>[s]);return e.concat(a).filter(s=>s.length>0).sort((s,x)=>s[0]-x[0]).map(s=>({text:s.map(c=>t[c]).join(r),numClause:s.length,indices:s}))},Dot=e=>e.map((t,o)=>o).filter(t=>wt().toText(e[t].captions[0].text)!==""||e[t].captionMode!==ar.MANUAL),V3=e=>{const t=[];return e.forEach((o,r)=>
1085{o.translationModified.source===!0&&o.translationModified.result===!1&&Hn(o,!1,Ke.ORIGINAL)!==""&&t.push(r)}),t},Uu=async(e,t,o,r,n,a,i)=>{const c=t.engine===Ea.GPT,l=c?5:void 0,d=c?3:e.length,u=FT(e,d),p=e.length,f=e.join("").length;yke(p,f,o,r,t,n);const E=zt(u).pipe(V0(async(T,O)=>await A2e(T,o,r,t,a,i!==void 0?i+"-"+O:void 0),l));return await Bt(E)},v2e=async(e,t,o,r,n,a)=>{if(at()&&n===""&&!mg()){const E=be().getUserInfo();if(E){const T="uid is invalid but userInfo "+JSON.stringify(E);throw new C(_.C_EMAIL_VERIFY_REQUIRED_ERROR,{email:E.email},T)}throw new C(_.C_LOGIN_REQUIRED_ERROR)}const i=h("translate.ts"),s=await zo(),{deviceId:x,deviceName:c,machineId:l}=await Ia(),d=new Date().getTimezoneOffset(),u=-d,p="POST",f={text:e,source:o,target:r,platform:t.engine,uid:n,cid:s,deviceId:x,deviceName:c,machineId:l,timezoneMin:u,clientType:Xo()};try{const E=await AOe(p,f,n==="",a),{error:T}=E;if(T){const O="Error occurred. type : "+T.type+", msg : "+T.msg;if(i.error(O),T.type==="low_version"){const S={version:Ha()};throw new C(_.C_APP_VERSION_IS_LOW,S,O)}throw T.type==="device_too_many_free_account"?new C(_.C_DEVICE_TOO_MANY_FREE_ACCOUNT,{},O):T.type==="quota_exceeded"?new C(_.C_REQUEST_QUOTA_EXCEEDED_ERROR,{engine:t.engine},O):new C(_.C_TRANSLATION_FAILED_ERROR,{engine:t.engine},O)}return E}catch(E){if(Ne(E))throw E;const T="Error occurred during translation : "+P(E);throw new C(_.C_TRANSLATION_FAILED_ERROR,{engine:t.engine},T)}},G3=async(e,t)=>{if(at()&&e===""&&!mg()){const d=be().getUserInfo();if(d){const u="uid is invalid but userInfo "+JSON.stringify(d);throw new C(_.C_EMAIL_VERIFY_REQUIRED_ERROR,{email:d.email},u)}throw new C(_.C_LOGIN_REQUIRED_ERROR)}const o=h("translate.ts"),r=await zo(),{deviceId:n,deviceName:a,machineId:i}=await Ia(),s=new Date().getTimezoneOffset(),x=-s,c="POST",l={uid:e,cid:r,sids:t,deviceId:n,deviceName:a,machineId:i,timezoneMin:x,clientType:Xo()};o.info("request translate done. translate_usage sids length: "+t.length);try{const d=await yOe(c,l,e===""),{error:u}=d;if(u){const p="Error occurred. type : "+u.type+", msg : "+u.msg;if(u.type==="low_version"){const f={version:Ha()};throw new C(_.C_APP_VERSION_IS_LOW,f,p)}throw new C(_.C_TRANSLATION_FAILED_ERROR,{},p)}o.info("translated character count reflected in the usage : "+d.charCount)}catch(d){const u="Error occurred during translation done : "+P(d);o.error(u)}},W3=(e,t,o)=>{const r=Ot(e,{defaultKey:t,errorArg:o,errorDescKey:"common.no_usage_deduction"});Y().error(e,r)},w2e=e=>{if(e.length===0)return[];const t=[];let o=[],r;return e.sort((n,a)=>n-a).forEach(n=>{!(r!==void 0&&n-r===1)&&o.length>0&&(t.push(o),o=[]),o.push(n),r=n}),t.push(o),t},N2e=(function(){const e=document.createElement("div");function t(o){return o&&typeof o=="string"&&(o=o.replace(/<script[^>]*>([\S\s]*?)<\/script>/gim,""),o=o.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gim,""),e.innerHTML=o,o=e.textContent||"",e.textContent=""),o}return t})(),P2e=(e,t,o)=>{if(e.length===0)return[];const r=e.slice(),n=r.sort((c,l)=>c-l),a=n[0],i=n[n.length-1],s=[],x=[];for(let c=Math.max(0,a-t);c<a;c++)s.push(c);for(let c=Math.min(o,i+1);c<=Math.min(o,i+t);c++)x.push(c);return[...new Set(s.concat(n).concat(x))].sort((c,l)=>c-l)},b2e=(e,t,o)=>{const r=e.map(s=>P2e(s,t,o)),n=[];let a=r[0],i;for(let s=1;s<r.length;s++)i=r[s],Cw(a,i).length?a=L2e(a,i):(n.push(a),a=i);return a.length&&n.push(a),n},L2e=(e,t)=>[...new Set([...e,...t])].sort((r,n)=>r-n),Cw=(e,t)=>e.filter(o=>t.includes(o)),NO=(e,t,o,r,n=!1)=>{const a=n?A("translation.on_retranslation"):A("translation.on_translation",{numClip:t}),i=A("translation.warn");return ySe(a,{progressRatio:e,progressStageText:o,progressWarnText:i},r)},M2e=(e,t,o,r)=>{const n=[],a=[],i=r.filter(s=>Cw(s,o).length);return e.forEach((s,x)=>{(o.includes(s)||i.flat().includes(s))&&(n.push(s),a.push(t[x]))}),{clipIndices:n,captions:a}},Fm=e=>Object.keys(ce).some(t=>ce[t]===e),D2e=(e,t)=>{const o=jt.createElement("div",{className:"two-line"},A("translation.caution_translated_to_new_language",{currentTargetLanguage:XR(e),newTargetLanguage:XR(t)}).split(`
1086`).map((r,n)=>jt.createElement("div",n===0?{className:"first-line"}:void 0,jt.createElement(Qr,void 0,r))));return{bodyClassName:"general-modal",title:A("translation.caution_header"),content:o,yesStr:A("translation.caution_overwrite"),noStr:A("translation.cancel")}},k2e=e=>{const t=A("translation.engine_failed_fallback?",{original:AM(e),fallback:AM(Ea.GOOGLE)});return{bodyClassName:"general-modal",title:A("translation.caution_header"),content:t,yesStr:A("popup.yes"),noStr:A("popup.no")}},XR=e=>A("translation_language."+e),RM=(e,t)=>e.map(o=>{const r={label:XR(o),value:o};return t!==void 0&&(r.className=t.get(o)===void 0||t.get(o)===!1?"":"chosen"),r}),kot=e=>
1086{const t=F3().reverse(),o=RM(t,e),r=Object.values(ce),n=Object.values(Jc),a=r.concat(n),i=RM(a,e),s=Fe();if(i.sort((c,l)=>{const d=A("translation_language."+c.value),u=A("translation_language."+l.value);return d.localeCompare(u,s)}),o.length>0){const c={type:"separator"};o.push(c)}return o.concat(i)},F2e=e=>e.filter(r=>r.translationModified.source===!1).length/e.length>C2e,U2e=(e,t,o,r)=>{const n=h("translate.ts");let a=[],i=[];return o.forEach((s,x)=>{const c=t[x],l=r[x].map(f=>f.indices),d=l.map(f=>f.map(E=>c[E]));n.info(`indices For sentences:
1087`+JSON.stringify(l)+` 
1088original Indices for sentences: 
1089`+d);const{clipIndices:u,captions:p}=M2e(c,s,e,d);n.info(`extract target clip Included sentence: clipIndices for all sentence:
1090`+JSON.stringify(d)+` => result: 
1091`+JSON.stringify(u)+` and captions: 
1092`+JSON.stringify(p,void 0,4)),a=a.concat(u),i=i.concat(p)}),{paddedTargetIndices:a,paddedTranslatedCaptions:i}},AM=e=>({[Ea.XL8]:"XL8",[Ea.PAPAGO]:"PAPAGO",[Ea.GOOGLE]:"Google",[Ea.GPT]:"GPT"})[e],H3=async e=>!!(e>0&&await Jh(zne(e,uV),hg.TRANSLATE));class Rw{options;constructor(t){this.options=t}getFirstOrNull(t){return t.length>0?t[0]:null}toTTSString(t,o,r){const n=this.preprocessInputText(t,r),a=this.applyInputReplaceRules(n);return a.length===0?null:{raw:t,textAspectLang:o,processed:a}}async getTextAspectLang(t,o){const r=Tt(t).pipe(St(n=>lx("/detect-tts-language",{body:JSON.stringify({payload:n.map(a=>({text:a,givenLanguage:o}))}),method:"POST"})),St(n=>me(n,_.C_TTS_NETWORK_ERROR)),At(n=>{if(n.error||!n.aspectLangs)throw new Error(n.error?.msg??"aspectLangs is undefined");return n.aspectLangs}),c0(n=>(h("ttsInputProcessor.ts").error("TTS Language Detection Failed, error: "+P(n)),Tt(Array(t.length).fill(o)))));return await Bt(r)}preprocessInputText(t,o){const r=o?t.slice(0,j2e(o)):t,n=Ese(r),a=/[\u2013\u2014\u2e3b]/g,i=/[\x00-\x19]/g,s=/[\u2000-\u2012\u2015-\u2bff]/g,x=/[\u3003\u3004]|[\u3007-\u303f]|[\u3099-\u309c]|[\u309f]|[\u30a0]|[\u30fb]|[\u30f7-\u30fa]|[\u30ff]|[\u3164]/g,c=/[\ud800-\udbff]|[\udc00-\udfff]/,l=/[(-+]|[:->]|[[-`]|[{-~]|[@/]|^['"]|['"]$/g,d=/[\uff08-\uff0b]|[\uff0d]|[\uff1a-\uff1e]|[\uff3b-\uff40]|[\uff5b-\uff5e]|[\uff20\uff0f]|^[\uff07]|[\uff07]|[\uffe3]$/g,u=/[\uff5f-\uff60]|[\uff62-\uff64]|[\uff66-\uffee]/g,p=/[\u0080-\u00a0]|[\u00a2-\u00be]/g,f=new RegExp(i.source+"|"+s.source+"|"+x.source+"|"+c.source+"|"+l.source+"|"+d.source+"|"+u.source+"|"+p.source,"g");Mo().getDebugVal(Xt.SKIP_TTS_PREPROCESSING);const E=WG(Sse(n)).replace(a," ");return this.logTrimmedChars(f,E),UE(E.replace(f,""))}applyInputReplaceRules(t){const o=this.options?.replaceRules;if(!o)return t;let r=0,n="";for(;r<t.length;){const a=r,i=o.find(({from:s})=>{const x=a,c=a+s.length;return t.substring(x,c)===s&&!uv(t,x,c)});i?(n+=i.to,r+=i.from.length):(n+=t[r],r++)}return n}logTrimmedChars(t,o){const r=o.match(t);r?.length&&h("ttsInputProcessor.ts").info("trimmed characters while tts preprocessing: "+r.toString())}}class Um extends Rw{async processInput(t,o){const r=this.options?.skipProcessing?[t]:tv(t),n=this.options?.skipProcessing||this.options?.skipSplitAtPunc?r:r.flatMap(l=>Ise(WG(l))),a=r.filter(l=>this.toTTSString(l,o,Ge.CLIP)!==null).length,i=n.filter(l=>this.toTTSString(l,o,Ge.CLIP)!==null).length,s=await this.getTextAspectLang(n,o),x=await this.addTextAspectLang(n,s),c=this.getTTSStringGroup(this.options?.maxLineMode?await this.withLineBreak(x,this.options.maxLineMode,o):x);if(c.length!==0){const l=lpe(a,i,c.length);_se({...l,speakerLang:o,maxLineMode:this.options?.maxLineMode??"none"})}return c}async withLineBreak(t,o,r){const n=zt(t).pipe(V0(({text:x,textAspectLang:c})=>{const l=this.getMaxLineLength(o,c);return zt(this.breakWithRetry(x,c,l)).pipe(Fa(),c0(d=>(h("ttsInputProcessor.ts").error("Error in splitting a text into linebreaker: "+P(d)+", input: "+x+", lang: "+c),Tt(x))))},10)),a=await Bt(n),i=await this.getTextAspectLang(a,r);return await this.addTextAspectLang(a,i)}async breakWithRetry(t,o,r){if(t.length<=r)return[t];const n=Math.ceil(t.length/r),a=3;let i=[];for(let x=0;x<a;x++)if(i=await this.breakByLinebreaker(t,o,n+x),i.every(c=>c.length<=r))return i;const s=[];for(const x of i)x.length>r?s.push(...await this.splitOversized(x,o,r)):s.push(x);return s}async splitOversized(t,o,r,n=5){if(t.length<=r||n<=0)return[t];const a=Math.ceil(t.length/r),i=await this.breakByLinebreaker(t,o,a),s=[];for(const x of i)x.length>r?s.push(...await this.splitOversized(x,o,r,n-1)):s.push(x);return s}getTTSStringGroup(t){return t.map(({text:o,textAspectLang:r})=>this.toTTSString(o,r,Ge.CLIP)).filter(ri)}async breakByLinebreaker(t,o,r){return(await km([{text:t,numClause:r}],D0(o))).map(({text:i})=>i)}async addTextAspectLang(t,o){const r=Tf(t,o).pipe(At(([n,a])=>({text:n,textAspectLang:a})),aa());return Bt(r)}getMaxLineLength(t,o){const r={long:{[ce.Korean]:120,[ce.English]:160,[ce.Spanish]:160,[ce.Japanese]:120,[ce.Taiwanese]:80},middle:{[ce.Korean]:60,[ce.English]:80,[ce.Spanish]:80,[ce.Japanese]:60,[ce.Taiwanese]:40},short:{[ce.Korean]:50,[ce.English]:70,[ce.Spanish]:70,[ce.Japanese]:50,[ce.Taiwanese]:35}},n=D0(o);return r[t][n]}}class V2e extends Rw{type;constructor(t,o){super(o),this.type=t}async processInput(t,o){const r=await this.getTextAspectLang([t],o),n=this.toTTSString(t,r[0],this.type);return n?[n]:[]}}class G2e extends Rw{processInput(){return Promise.resolve([])}}const QI=()=>{const e=Mt(ke.TTS_SPLIT_AT_PUNCTUATION);return e!==null?e:Fe()!==ce.English},Fot=(e,t=1e3)=>{xt.info(e,{autoClose:t})},i0=e=>{xt.error(e)},j3=(e,t)=>{const o=Hn(e,!1,t).split(""),r=o.filter(a=>CU.test(a)).length,n=o.length===0||r/o.length<.5;return Hn(e,n,t)},z3=async e=>(await Bt(zt(e).pipe(ZU(t=>t.ttsFileInfo.text.textAspectLang),Ma(t=>t.pipe(aa())),At(t=>({num:t.length,lang:t[0].ttsFileInfo.text.textAspectLang})),aa()))).at(0)?.lang,Wg=(e,t)=>Object.values(t).find(o=>s2(o)&&o.mediaId===e),Kx=(e,t)=>L.get(t,e),pd=(e,t)=>L.get(t,e)!==void 0,Y3=e=>{switch(e){case ce.English:return ft.English;case ce.Japanese:return ft.Japanese;case ce.Korean:return ft.Korean;case ce.Spanish:return ft.Spanish;case ce.Taiwanese:return ft.Taiwanese;default:return ft.Korean}},B3=e=>
1092{const t=$e().getStockTTSSpeakerList();if(t===void 0)throw h("ttsMisc.ts").error("No speaker list found"),new C(_.C_TTS_FETCH_SPEAKER_LIST_ERROR);return t.defaultVoices[e]},ZI=e=>{if(e.provider===Oe.UserTTS){if($e().getUserTTSSpeakers()===void 0)throw new C(_.C_TTS_FETCH_SPEAKER_LIST_ERROR);const a=Af(e.provider,e.speakerId);return a&&$I(a,e)?a:void 0}const t=$e().getStockTTSSpeakerList();if(!t)throw new C(_.C_TTS_FETCH_SPEAKER_LIST_ERROR);const o=e.provider===Oe.VrewVA_deprecated?Oe.Vrew:e.provider,r=L.get(t.allVoices,o);if(r)return e.speakerId!==void 0?Af(e.provider,e.speakerId):Object.values(r).find(n=>n.name===e.name)},Uot=e=>Object.values(e.allVoices).flatMap(t=>Object.values(t)),us=e=>e?H2e(e):W2e(),W2e=()=>{const e=Fe(),t=Mt(ke.LAST_TTS_SETTING),{speaker:o,...r}=t,n=B3(Y3(e)),a=o?ZI(o)??n:n,i={...o,...a},s=Aw(i,r.emotion),x=Wu(i,s,r.emotionIntensity),c=Vs(i,r.acting),l=yw(i,r.version),d=K3(r.effect);return{pitch:0,speed:0,volume:0,speaker:i,...r,emotion:s,emotionIntensity:x,acting:c,version:l,effect:d}},H2e=e=>{const t=B2e(e.speaker),o=Aw(t,e.emotion),r=Wu(t,o,e.emotionIntensity),n=Vs(t,e.acting),a=yw(t,e.version),i=K3(e.effect);return{pitch:e.pitch,speed:e.speed,volume:e.volume,speaker:t,emotion:o,emotionIntensity:r,acting:n,version:a,effect:i}},Hg=e=>{po(ke.LAST_TTS_SETTING,qV(e))},j2e=e=>{let t;switch((o=>{o[o.CLIP=1e4]="CLIP",o[o.DUBBING=aL]="DUBBING",o[o.EFFECT=aL]="EFFECT",o[o.BATCH=1e4]="BATCH"})(t||(t={})),e){case Ge.CLIP:return 1e4;case Ge.DUBBING:return t.DUBBING;case Ge.EFFECT:return t.EFFECT;case Ge.BATCH:return 1e4}},Vot=(e,t)=>e.length>w1&&!t,Got=(e,t,o)=>{let r=0;return e.forEach(n=>{n.words.forEach(a=>{a.assetIds.forEach(i=>{const s=L.get(o,i);if(s?.role!=="sub")return;const x=s.trackIds.map(c=>L.get(t,c));for(const c of x)c&&dl(c)&&r++})})}),r},Aw=(e,t)=>{if(!(t===void 0||e.emotions===void 0))return e.emotions.includes(t)?t:"neutral"},yw=(e,t)=>{if(e.versions!==void 0)return t&&e.versions.includes(t)?t:e.versions.at(-1)},K3=e=>{if(e!==void 0&&f6.includes(e))return e},vw=(e,t)=>!e&&t==="neutral"||!t&&e==="neutral"?!0:e===t,Wot=e=>e!==void 0&&e.length>1,$I=(e,t)=>e.speakerId===t.speakerId&&e.provider===t.provider&&e.lang===t.lang,Hot=(e,t)=>$I(e.speaker,t.speaker)&&e.volume===t.volume&&e.speed===t.speed&&(e.pitch===t.pitch||!ope(e.speaker))&&vw(e.emotion,t.emotion)&&Lw(e,t)&&dv(e,t)&&e.version===t.version&&e.effect===t.effect,jot=(e,t)=>{if(e.speakerId!==t.speakerId)return!1;const o=KV(e.speakerId),r={...e,speaker:o},n={...t,speaker:o};return e.volume===t.volume&&e.speed===t.speed&&e.pitch===t.pitch&&vw(e.emotion,t.emotion)&&Lw(r,n)&&dv(r,n)&&e.version===t.version&&e.effect===t.effect},Vm=e=>e.speaker.provider===Oe.Google||e.speaker.provider===Oe.Clova||e.speaker.provider===Oe.Wemakevoice_deprecated||e.speaker.provider===Oe.KT||e.speaker.provider===Oe.Voicevox||e.speaker.provider===Oe.Polly||e.speaker.provider===Oe.Typecast,Vu=e=>e.speaker.provider===Oe.Vrew||e.speaker.provider===Oe.UserTTS&&e.speaker.versions?.at(-1)!=="v2"||e.speaker.provider===Oe.Google||e.speaker.provider===Oe.Clova||e.speaker.provider===Oe.Wemakevoice_deprecated||e.speaker.provider===Oe.KT||e.speaker.provider===Oe.Voicevox||e.speaker.provider===Oe.Polly,JR=e=>{const t=e.speaker,o=Aw(t,e.emotion),r=Wu(t,o,e.emotionIntensity),n=Vs(t,e.acting),a=yw(t,e.version),i=Vm(e)?e.volume:0,s=Vu(e)?e.speed:0;return{...e,emotion:o,emotionIntensity:r,acting:n,version:a,volume:i,speed:s}},ww=e=>{const t=JR(e),o=t.version??N1;return{provider:t.speaker.provider,speakerId:t.speaker.speakerId,lang:t.speaker.lang,emotion:t.emotion,emotionIntensity:t.emotionIntensity,acting:t.acting,version:o,speed:t.speed,pitch:t.pitch,volume:t.volume}},Nw=(e,t)=>({...t,text:e}),N2=(e,t,o,r)=>Pw(e,t,o,r)==="pure",jg=(e,t,o,r)=>{if(!N2(e.words,t,o,r))return;const n=IH(e.words,t,o).at(0);if(n)return ss(n,t,o).audioMediaId},z2e=(e,t,o,r)=>e.map(n=>jg(n,t,o,r)).filter(Se).map(n=>Kx(n,r)).filter(Se),Pw=(e,t,o,r)=>{const n=IH(e,t,o);if(n.length===0)return"none";const a=Xg(n,t,o);if(a.length===0)return"none";const i=a.some(x=>pd(x,r)),s=a.some(x=>!pd(x,r));return i&&s?"mixed":i?"pure":"none"},sx=(e,t)=>t===Oe.UserTTS?e:""+A("tts_speaker."+e),bw=(e,t)=>t===Oe.UserTTS?e:A("tts_speaker."+e,{lng:ce.English}),eT=e=>{switch(e){case Oe.Google:return"Google";case Oe.Clova:return"Clova Voice";case Oe.Vrew:case Oe.VrewVA_deprecated:case Oe.UserTTS:return"Vrew";case Oe.Wemakevoice_deprecated:return"We Make Voice";case Oe.KT:return"Humelo";case Oe.Voicevox:return"Voicevox";case Oe.Polly:return"AWS Polly";case Oe.Elevenlabs:return"Elevenlabs";case Oe.Gemini:return"Gemini";case Oe.Typecast:return"Typecast"}},zg=(e,t,o,r)=>vd({files:e,blobs:t,dispatchType:Ee.MEDIA,projectOption:o,startMedia:r}),tT=e=>{const{text:t,...o}=e;return{ttsString:t,voiceSetting:o}},Gu=e=>typeof e.contents=="string"?e.contents.length:e.contents.reduce((t,{text:o})=>t+o.length,0),Y2e=e=>Array.isArray(e)?e[0]:e,B2e=e=>{const t=ZI(e);if(t)return t;const o=e.provider===Oe.UserTTS,r=o?"tts_deleted_user_speaker_toast":"tts_deleted_speaker_toast",n=o?"tts.deleted_user_speaker_toast":"tts.deleted_speaker_toast",a=To.generateToastOption(r,Na.WITH_BUTTON,!1);return To.popup(A(n,{speaker:sx(e.name,e.provider)}),a),B3(e.lang)},K2e=(e,t,o,r)=>{const n=new Map;return Xg(e.words,t,o).filter(a=>pd(a,r)).map(a=>{const i=Kx(a,r);if(i)return{provider:i.speaker.provider,speakerId:i.speaker.speakerId,name:i.speaker.name,version:i.version}}).filter(Se).forEach(a=>{!n.has(a.speakerId)&&n.set(a.speakerId,a)}),Array.from(n.values())},zot=(e,t,o,r)=>K2e(e,t,o,r).map(a=>a.speakerId),X2e=e=>e.name+"-"+e.provider+"-"+e.emotion+"-"+e.effect,J2e=(e,t,o,r)=>{const n=new Map;return Xg(e.words,t,o).filter(a=>pd(a,r)).map(a=>{const i=Kx(a,r);if(i)return i}).filter(Se).forEach(a=>{const{speaker:i,emotion:s,effect:x}=tT(a).voiceSetting,c={name:i.name,provider:i.provider,emotion:s,effect:x},l=X2e(c);!n.has(l)&&n.set(l,c)}),Array.from(n.values())},Yot=(e,t)=>
1092t.some(o=>e.has(o)),q2e=(e,t)=>{if(!e&&!t)return"";const o=e?A("tts.emotion_"+e):"",r=t?A("tts.effect_"+t):"",n=e&&t?", ":"";return" ("+o+n+r+")"},X3=e=>{const{name:t,provider:o,emotion:r,effect:n}=e,a=sx(t,o),i=q2e(r,n);return""+a+i},Q2e=e=>e.length===1?X3(e[0]):A("smart_tooltip.clip_guide_cut_tts_misc",{count:e.length}),Z2e=e=>{const t=Ve().getArray(Ie.VOICEVOX_LICENSE_CHECKED);if(t.includes(e.speakerId))return;Y().popup(Obe(A("tts.voicevox_license_"+(e.speakerId??e.name))));const o=[...t,e.speakerId];Ve().set(Ie.VOICEVOX_LICENSE_CHECKED,o)},$2e=async e=>{const t=e.map(o=>A("caption_format.clip_label")+" "+(o+1)).join(", ");return Y().popup(ql(A("tts.errored_clip_exists")+`
1093
1094`+t))},Bot=()=>(Mo().getDebugVal(Xt.SHOW_TTS_SPEAKER_INFO),!1),J3=(e,t,o,r,n)=>{if(e!==Oe.UserTTS)return;const a=Ss.USER_TTS_FEEDBACK+"_"+t;yG({eventSurveyType:Ss.USER_TTS_FEEDBACK,speakerid:t,speakerlang:r,userttsversion:n},a,A("event_survey."+Ss.USER_TTS_FEEDBACK,{speakerName:o}))},epe=async e=>e===0?!0:!await Jh(e,hg.TTS),Kot=e=>({speakerId:e.speaker.speakerId,volume:e.volume,speed:e.speed,pitch:e.pitch,emotion:e.emotion,emotionIntensity:Wu(e.speaker,e.emotion,e.emotionIntensity),acting:Vs(e.speaker,e.acting),version:e.version,effect:e.effect}),PO=e=>e.tags?.includes(P1)??!1,Xot=()=>Vr()||Mo().getDebugVal(Xt.NEW_TTS)!==void 0,Jot=e=>{const{name:t,provider:o,badge:r}=e;return{notOnClient:A("tts_speaker."+t)==="tts_speaker."+t&&o!==Oe.UserTTS,deprecated:r==="Deprecated"||r==="Disabled"}},tpe=e=>e===Oe.Elevenlabs||e===Oe.Gemini||e===Oe.Typecast,ope=e=>e.provider!==Oe.Elevenlabs&&!e.tags?.some(t=>b1.includes(t)),rpe=(e,t)=>e?.provider===Oe.Typecast&&(t==="happy"||t==="sad"||t==="angry")&&e.emotions?.includes(t)===!0,Wu=(e,t,o)=>{if(rpe(e,t))return o===void 0||!Number.isFinite(o)?mZ:$t(o,1,2)},Lw=(e,t)=>Wu(e.speaker,e.emotion,e.emotionIntensity)===Wu(t.speaker,t.emotion,t.emotionIntensity),npe=e=>{const t=KV(e.speakerId);return t?{speaker:t,volume:e.volume,speed:e.speed,pitch:e.pitch,emotion:e.emotion,emotionIntensity:e.emotionIntensity,acting:Vs(t,e.acting),version:e.version,effect:e.effect}:null},oT=e=>new G2e().preprocessInputText(e),qot=e=>Da(e)?e.map(t=>t.contents).join(" "):typeof e.contents=="string"?e.contents:e.contents.map(t=>t.text).join(" "),Qot=e=>{const{speaker:t,volume:o,speed:r,pitch:n,emotion:a,emotionIntensity:i,version:s,effect:x}=e;return t.speakerId+"-"+o+"-"+r+"-"+n+"-"+a+"-"+i+"-"+s+"-"+x+"-"+Vs(t,e.acting)},ape=()=>Mt(ke.BOOKMARK_TTS_SETTINGS),Zot=()=>ape().map(npe).filter(ri),Mw=e=>{const t=ud(e.words,!0,!0,!1).split(""),o=t.filter(n=>CU.test(n)).length,r=t.length===0||o/t.length<.5;return ud(e.words,!0,!0,r)},Da=e=>Array.isArray(e)&&e.every(ipe),ipe=e=>e.type===Ge.CLIP,rT=e=>"globalPosition"in e,Gm=e=>e.variant==="INSERT",spe=(e,t)=>({...Nw({raw:"",processed:"",textAspectLang:e.speaker.lang},e),duration:t,errorInfo:{reason:nr.NOT_COMPLETED,msg:"tts.not_completed"}}),xpe=e=>{const t=e.provider==="voicevox",o=tpe(e.provider);if(!t)return{licenseDesc:A("tts.license"),voiceInfo:o?A("tts.speaker_desc_multilingual"):void 0,showMoreUrl:A("tts.license_link")};const r=e.speakerId,n=e.name;return{licenseDesc:A("tts.voicevox_license_"+(r??n))}},$ot=e=>{const t=sx(e.name,e.provider),o=e.provider==="voicevox",r=xpe(e);return{speakerName:t,isVoicevoxSpeaker:o,licenseInfo:r}},q3=(e,t)=>{const o=zn({}),r=ii({}),n=s=>{if(typeof t=="string")return t;let x=0;for(const c of t)if(x+=c.wordCount,s<x)return c.mediaId;return t[t.length-1].mediaId},a=vt(e.words,s=>{s.forEach((x,c)=>{if(x.type===Z.ENTER)return;const l=sr(x),d=x.originalStartTime,u={trackId:Rt(),sourceIn:pe(d),sourceOut:pe(d+l),mediaId:n(c),type:ze.TTSClip,volume:ma,loop:!1,playbackRate:Un},p={trackIds:[u.trackId],role:"main",rangeType:tr.WORD},f=ho();x.assetIds.push(f),L.set(o,u.trackId,u),L.set(r,f,p)})});return{clip:{...e,words:a},trackEntries:o,assetEntries:r}},cpe=(e,t,o,r)=>{const n=L.get(o,r);if(!n||n.role!=="sub"||!n.trackIds.some(i=>{const s=L.get(t,i);return s&&dl(s)}))return null;for(let i=0;i<e.length;i++)for(const s of e[i].words)if(s.assetIds.includes(r))return{globalClip:e[i],clipIndex:i};return null},lpe=(e,t,o)=>({numSplitByNewline:Math.max(0,e-1),numSplitByPunctuation:Math.max(0,t-e),numSplitByOversized:Math.max(0,o-t),numTotal:o}),dpe={[ME.FREE]:0,[ME.ONE_CREDIT_PER_100_CHARACTERS]:1,[ME.TEN_CREDITS_PER_100_CHARACTERS]:10},ert=(e,t)=>t.length===0||t.some(o=>e.creditsPer100Chars===dpe[o]),Pf={durationOfChar:.25,matchScore:10,localMatchR
1094ange:200,localMatchOverlapRange:10},upe=e=>{const t=e.reduce((r,n)=>r+(n.type===Z.NORMAL?d2(n.text).length:0),0),o=e.reduce((r,n)=>r+(n.type===Z.NORMAL?n.duration:0),0);Pf.durationOfChar=o/t},ppe=(e,t,o,r,n)=>(o===Ms.WORD?e.split(Ar(t)?/\s/:/\n/):d2(e)).filter(i=>i!=="").map(i=>({text:i,lineIndex:r,uniqueWordIndex:n})),Q3=(e,t,o)=>{if(e.type!==Z.NORMAL&&e.type!==Z.SOUND)return[];if(o===Ms.WORD)return[{text:e.text,wordIndex:t,uniqueWordIndex:void 0}];{const r=e.type===Z.NORMAL?e.text:" ".repeat(Math.round(e.duration/Pf.durationOfChar));return d2(r).map(n=>({text:n,wordIndex:t,uniqueWordIndex:void 0}))}},Z3=(e,t)=>{if(e=e.toLowerCase(),t=t.toLowerCase(),e===t)return e.length;if(!e.length||!t.length)return 0;const o=(n,a)=>n*t.length+a,r=new Array(e.length*t.length);for(let n=0;n<e.length;n++)for(let a=0;a<t.length;a++)r[o(n,a)]=Math.max(n>0?r[o(n-1,a)]:0,a>0?r[o(n,a-1)]:0,(n>0&&a>0?r[o(n-1,a-1)]:0)+(e[n]===t[a]?1:0));return r[o(e.length-1,t.length-1)]},$3=(e,t,o,r,n)=>{if(e.length===0||t.length===0)return[];let a;o===Ms.WORD?n!==void 0?a=(E,T)=>{const O=e[E].uniqueWordIndex,S=t[T].uniqueWordIndex;return n[O][S]}:a=(E,T)=>Z3(e[E].text,t[T].text):a=(E,T)=>e[E].text.toLowerCase()===t[T].text.toLowerCase()?Pf.matchScore:e[E].text===" "?1:0;const i=Array(e.length).fill(null).map(E=>new Int32Array(t.length)),s=(E,T,O)=>({scoreWhenMatched:(E>0&&T>0?i[E-1][T-1]:0)+O,scoreIgnoringCurrentSource:(E>0?i[E-1][T]:0)+(r?O:0),scoreIgnoringCurrentTarget:T>0?i[E][T-1]:0});for(let E=0;E<e.length;E++)for(let T=0;T<t.length;T++){const O=a(E,T),{scoreWhenMatched:S,scoreIgnoringCurrentSource:R,scoreIgnoringCurrentTarget:y}=s(E,T,O);i[E][T]=Math.max(S,R,y)}const x=t.reduce((E,T)=>Math.max(T.lineIndex,E),0),c=Array(x+1).fill(null).map(()=>Array(0));let l=-1;const d=new Map,u=(E,T,O)=>{const S=t[T].lineIndex,R=e[E].wordIndex;if(o===Ms.WORD)c[S].push(R);else{if(l!==R&&d.size!==0){const[y]=[...d.entries()].reduce((v,w)=>v[1]>w[1]?v:w);c[y].push(l),d.clear()}d.set(S,(d.get(S)||0)+O),l=R}};let p=e.length-1,f=t.length-1;for(;p>=0&&f>=0;){const E=a(p,f),T=i[p][f],{scoreWhenMatched:O,scoreIgnoringCurrentSource:S,scoreIgnoringCurrentTarget:R}=s(p,f,E);if(T===O)u(p,f,E),p--,f--;else if(T===S)u(p,f,E),p--;else if(T===R)f--;else throw new C(_.C_LOGIC_ERROR)}if(o===Ms.CHAR&&d.size!==0){const[E]=[...d.entries()].reduce((T,O)=>T[1]>O[1]?T:O);c[E].push(l),d.clear()}return c.forEach(E=>{E.reverse()}),c},fpe=async(e,t,o)=>{const r=new Set(e.map(p=>p.text)),n=new Set(t.map(p=>p.text)),a=[...r.values()].filter(p=>n.has(p)).sort(),i=new Set(a),s=a.length,x=(p,f)=>{const E=[...f.values()].filter(O=>!i.has(O)).sort(),T=(O,S)=>O===S?0:S<O?-1:1;return p.forEach(O=>{O.uniqueWordIndex=z0(a,O.text,T),O.uniqueWordIndex===void 0&&(O.uniqueWordIndex=s+z0(E,O.text,T))}),[...a,...E]},c=x(e,r),l=x(t,n),d=Math.floor(c.length/100),u=Array(c.length).fill(null).map(()=>Array(l.length));for(let p=0;p<c.length;p++){for(let f=0;f<l.length;f++)p<s&&f<s&&p>f?u[p][f]=u[f][p]:u[p][f]=Z3(c[p],l[f]);o!==void 0&&p%d===0&&(o(Math.round(100*p/c.length)),await Fo(0))}return u},yM=async(e,t,o,r,n,a)=>{const i=e.flatMap((l,d)=>Q3(l,d+t,r)),s=o.flatMap((l,d)=>ppe(l,n,r,d));if(i.length===0)throw new C(_.C_SCRIPT_IMPORT_NO_SOURCE_ERROR);if(s.length===0)throw new C(_.C_SCRIPT_IMPORT_EMPTY_SCRIPT_ERROR);const x=r===Ms.WORD?await fpe(i,s,a):void 0;return $3(i,s,r,r===Ms.WORD&&Ar(n)===!1,x)},gpe=(e,t,o,r)=>{const n=Ar(r)?Ms.WORD:Ms.CHAR,a=o.map((s,x)=>({text:s.trim(),wordIndex:x,uniqueWordIndex:void 0})),i=e.flatMap((s,x)=>Q3(s,x,n)).map(s=>({...s,lineIndex:s.wordIndex<t?0:1}));if(i.length>=2){const s=$3(a,i,n,!1,void 0);return s[1]?.length>0?s[1][0]:a.length}else return Math.round(a.length*t/e.filter(x=>x.type!==Z.ENTER).length)},_pe=async(e,t,o,r,n)=>{const{linebreak:a,punctuation:i,slash:s}=n,x=Nc(t),c=x.flatMap(T=>T.words).filter(T=>T.type!==Z.ENTER);upe(c);const l=a?tv(e):[e],d=i?l.flatMap(GG):l,u=s?d.flatMap(Ose(/\/\/\//)):d,p=await yM(c,0,u,Ms.WORD,o,r);if(!Ar(o)){const T=Pf.localMatchRange,O=Pf.localMatchOverlapRange;for(let S=0;S<u.length;S+=T-O){const R=Math.min(S+T,u.length),y=u.slice(S,R),v=p.slice(S,R).flat();if(v.length===0)continue;const w=Math.min(...v),N=Math.max(...v),M=c.slice(w,N+1),k=await yM(M,w,y,Ms.CHAR,o);p.splice(S,k.length,...k)}}const f=u.reduce((T,O,S)=>(T.length===0||p[S].length!==0?T.push(O):T[T.length-1]+=`
1095`+O,T),[]);p[0].length===0&&f.splice(0,2,[f[0],f[1]].join(`
1096`));const E=p.filter(T=>T.length!==0).map(T=>Math.min(...T));return E[0]=0,{allClips:x,allClipWords:c,matchResult:E,mergedCaptions:f}},Epe=(e,t)=>{if(e.length===0)throw new C(_.C_TIMECODE_TEXT_TIMECODE_MISMATCH,{empty:!0});const o=t.reduce((r,n,a)=>
1096{if(a>=e.length)return r;const i=e[a].timecode;return!(Math.abs(vo(n)-i)<1)&&r.push(a),r},[]);if(o.length>0)throw new C(_.C_TIMECODE_TEXT_TIMECODE_MISMATCH,{clipCount:o.length,indices:o.slice(0,10).map(r=>r+1).join(", ")+(o.length>10?"...":"")})},mpe=e=>{const t=[],o=/^(\d\d?:\d\d:\d\d)(?:\s*)(.*)/,r=/^(\d\d:\d\d:\d\d),\d\d\d --> /,n=/^\d+$/,a=s=>s.split(":").reduce((x,c)=>60*x+Number(c),0);let i=!1;return e.split(/[\r\n]/).filter(s=>s).forEach((s,x,c)=>{const l=s.match(o);if(l===null){if(c[x+1]!==void 0&&r.test(c[x+1])&&n.test(s))return;if(t.length>0){const T=t[t.length-1],O=i&&T.text.length===0?s:""+vu+s;T.text+=O}return}const d=s.match(r);if(d){i=!0;const E=a(d[1]);t.push({timecode:E,text:""});return}const[,u,p]=l,f=a(u);t.push({timecode:f,text:p})}),t},trt=(e,t,o,r,n)=>{const a=mpe(e),i=a.length>t.length*.1;if(n&&!i)return!1;try{Epe(a,t);const x=a.map(c=>c.text);r(Ke.ORIGINAL,!0),o(x,0),xt.success(A("import.timecode_text_success")),tDe(n)}catch(x){const c=ye(x),l=Ho(x);h("textImport.ts").warn("Timecode text import error : "+P(x)+`
1097      Error arguments : `+l+`
1098      Timecode original imported Text : 
1099`+e.substr(0,100).replace(g6,"x")),PDe(l);const d=Ot(c,{errorArg:l,defaultKey:"import.timecode_text_error",errorDescKey:l?.empty?"import.timecode_text_error_empty_info":void 0});let u;if(c===_.C_TIMECODE_TEXT_TIMECODE_MISMATCH&&l?.clipCount&&l?.indices){const p=A("import.timecode_text_error_mismatch_info",l);u=jt.createElement("div",{},[jt.createElement("div",{},d),jt.createElement("div",{},p),jt.createElement("div",{className:un("title","bullet"),style:{"margin-top":"30px","margin-bottom":"14px"}},A("import.timecode_text_error_mismatch_clip")),jt.createElement("div",{className:"inner-box"},l.indices)])}Y().error(c,u||d,u&&"large")}return!0},qR=(e,t)=>t===void 0||e===Z.SPACER?e:t.trim().length===0?e!==Z.SILENT?Z.SOUND:Z.SILENT:e===Z.LAUGHTER||e===Z.CLAP||e===Z.FILLER||e===Z.AUDIO_EVENT?e:Z.NORMAL,ort=(e,t,o,r,n,a)=>{const i=sn(e,t);if(!i)return null;const s=Co(e,t,!0);if(s===-1)return null;const x=vt(e,d=>{const u=d[s],p=ns(u,t);u.words[p].duration=pe(ue(sr(i)+(o==="right"?r:-r),2))});if(i.type===Z.SPACER)return{clips:x,trackEntries:n};let c=!1;const l=vt(n,d=>{i.assetIds.map(p=>L.get(a,p)).filter(p=>p?.role==="main").flatMap(p=>p.trackIds).forEach(p=>{const f=L.get(d,p);if(!(!f||!Wa(f)&&!mn(f)||nG(f)))if(o==="left"){const E=pe(ue(f.sourceIn+r,2));(E<0||E>f.sourceOut)&&(c=!0),f.sourceIn=E}else{const E=pe(ue(f.sourceOut+r,2));(E<0||f.sourceIn>E)&&(c=!0),f.sourceOut=E}})});return c?null:{clips:x,trackEntries:l}},rrt=(e,t,o,r,n,a)=>{const i=o-t,s=i===1,x=i===2;if(!s&&!x)return null;const c=sn(e,t),l=sn(e,o);if(!c||!l)return null;const d=sr(c),u=fl([c,l]);if(d+r<=0||d+r>=u)return null;const p=Co(e,t,!0),f=Co(e,o,!0);if(p===-1||f===-1||x&&p===f)return null;const T=vt(n,S=>{const R=zL(c,a),y=zL(l,a);R.forEach(v=>{const w=L.get(S,v);!w||!Wa(w)&&!mn(w)||(w.sourceOut=pe(ue(w.sourceOut+r,2)))}),y.forEach(v=>{const w=L.get(S,v);!w||!Wa(w)&&!mn(w)||(w.sourceIn=pe(ue(w.sourceIn+r,2)))})});return{clips:vt(e,S=>{const R=S[p],y=S[f],v=ns(R,t),w=ns(y,o);R.words[v].duration=pe(ue(sr(R.words[v])+r,2)),y.words[w].duration=pe(ue(sr(y.words[w])-r,2)),R.dirty.video=!0,y.dirty.video=!0}),trackEntries:T}},hpe=(e,t,o,r,n,a,i)=>{const s=qpe(e,t,o,r,n,a,i),x=Object.fromEntries(Object.entries(r).filter(([c])=>{const l=L.get(i,c);if(!l)return!1;const d=l.trackIds.map(u=>L.get(a,u)).filter(Se);return d.length===0?!1:!d.every(ll)}));return{correctedClip:s,newAssetIdMap:x}},bf=(e,t,o,r,n,a,i)=>{if(!(0<=t&&t<o&&o<=e.length))throw new C(_.C_LOGIC_ERROR,void 0,"Invalid index range ["+t+", "+o+") given when there are "+e.length+" clips.");const s=e.slice(t,o),x=Xpe(e,t,o),c={startClipIndex:t,endClipIndex:o-1},l=Jpe(e,c,x),d=Tpe(s,r,n),{correctedClip:u,newAssetIdMap:p}=hpe(e,c,d,l,x,a,i);return{newClips:[...e.slice(0,t),u,...e.slice(o)],newAssetIdMap:p}},Ipe=(e,t,o,r,n,a)=>Kg(e,t)?{newClips:e,newAssetIdMap:{}}:bf(e,t-1,t+1,o,r,n,a),eH=(e,t,o,r,n,a)=>tl(e,t)?{newClips:e,newAssetIdMap:{}}:bf(e,t,t+2,o,r,n,a),Tpe=(e,t,o)=>{let r,n;const a=[e.some(p=>p.captions[Ke.ORIGINAL].style!==void 0),e.some(p=>p.captions[Ke.TRANSLATE].style!==void 0)];let i=[{text:wt().fromText(""),style:a[Ke.ORIGINAL]?e.at(0)?.captions[Ke.ORIGINAL].style??o.captionStyleSetting:void 0},{text:wt().fromText(""),style:a[Ke.TRANSLATE]?e.at(0)?.captions[Ke.TRANSLATE].style??o.captionStyleSetting:void 0}];const s=e.some(p=>p.captionMode===ar.MANUAL),x=[],c=[],l=AH(e[0]);for(const p of e){if(Ys(p)<=0)throw new C(_.C_LOGIC_ERROR,void 0,"Invalid clip with 0 words.");p.words.forEach(f=>{f.type!==Z.ENTER&&x.push({...f,playbackRate:l})}),i=u2e(i,p,t,!s,o),r===void 0&&p.markerId!==void 0&&(r=p.markerId),!n&&p.backgroundId&&
1099(n=p.backgroundId);for(const f of p.assetIds)c.includes(f)||c.push(f)}const d=sT(e[e.length-1].transitionModel,x);return Dx(x,{preserveEmptyWords:!0}),{...e[0],words:x,captions:i,captionMode:s?ar.MANUAL:ar.TRANSCRIPT,markerId:r,assetIds:c,dirty:{video:!0,caption:e.reduce((p,f)=>p||f.dirty.caption,!1),blankDeleted:e.reduce((p,f)=>p||f.dirty.blankDeleted,!1)},translationModified:{source:e.some(p=>p.translationModified.source),result:e.some(p=>p.translationModified.result)},videoTransform:e[0].videoTransform,backgroundId:n,transitionModel:d}},nrt=(e,t,o,r)=>{if(o.globalPosition===null)return;const{cursorMode:n,globalPosition:a}=o,i=Er(t,a),s=mxe(r);switch(e){case qa.DEFAULT:case qa.NEXT:return i+1===t.length?void 0:{startIndex:i,endIndex:i+2};case qa.CLIPS:return n===we.CLIP&&s!==null?{startIndex:s.start,endIndex:s.end+1}:void 0;default:return i===0?void 0:{startIndex:i-1,endIndex:i+1}}},vM=(e,t,o=0)=>{for(let r=o;r<e.length;r+=1)if(e[r].words.at(0)?.id===t)return r},Spe=(e,t,o,r,n,a)=>{const i=[];for(let x=0;x<t.length;x+=1){const c=t[x],l=vM(e,c);if(l===void 0)continue;const d=t[x+1],u=d?vM(e,d):e.length;i.push({from:l,to:u??e.length,type:"CLIP"})}const s=(x,{from:c,to:l})=>{if(c+1===l)return x.newClips.push(e[c]),x;const{newClips:d,newAssetIdMap:u}=bf(e,c,l,o,r,n,a);return x.newClips.push(d[c]),x.newAssetIdMap=Ah(x.newAssetIdMap,u),x};return i.reduce(s,{newClips:[],newAssetIdMap:{}})},Ope=(e,t,o,r="right")=>{const n=p=>p.trackIds.map(f=>L.get(e,f)).filter(Se),a=n(t),i=n(o),s=new Set,x=[],c=[],l=(p,f)=>{for(const E of p)By(E)||U0(E)||mn(E)?f.push(E):s.add(E.trackId)};l(a,x),l(i,c);const d=[];for(const p of x)for(const f of c){const E=p.mediaId===f.mediaId,T=$Ce(p.sourceOut,f.sourceIn);if(E&&T){const O=r==="left"?f:p,S={...O,trackId:Rt(),sourceIn:p.sourceIn,sourceOut:f.sourceOut};d.push(S)}}return{newMainAsset:{trackIds:[...Array.from(s),...d.map(p=>p.trackId)],role:"main",rangeType:tr.WORD},newMainTracks:d}},Cpe=(e,t,o="right",r,n)=>{const a=T=>{const O=new Set;let S;for(const R of T.assetIds){const y=L.get(n,R);y&&(y.role==="sub"?O.add(R):S=y)}return{mainAsset:S,subAssetIds:O}},{mainAsset:i,subAssetIds:s}=a(e),{mainAsset:x,subAssetIds:c}=a(t);if(!i||!x)return null;const{newMainAsset:l,newMainTracks:d}=Ope(r,i,x,o),u=ho(),p=new Set([...s,...c]),f=vt(n,T=>{L.set(T,u,l)}),E=vt(r,T=>{for(const O of d)L.set(T,O.trackId,O)});return{assetIds:[u,...Array.from(p)],assetEntries:f,trackEntries:E}},art=(e,t,o,r,n,a,i,s)=>{const x=o-t,c=x===1,l=x===2;if(!c&&!l)return null;const d=sn(e,t),u=sn(e,o);if(!d||!u)return null;const p=Co(e,t),f=Co(e,o),E=p===f;if(l&&E)return null;const T=Cpe(d,u,r,i,s);if(!T)return null;const{assetIds:O,assetEntries:S,trackEntries:R}=T,y=fl([d,u]),v=r==="left"?u:d,w={...v,hardcutWordMeta:d.hardcutWordMeta,duration:y,type:qR(v.type,n),text:n.trim(),pronunciation:a?.trim(),assetIds:O},N=vt(e,F=>{if(E){const G=F[p],B=ns(G,t);G.words.splice(B,2,w),G.dirty.video=!0,G.translationModified.source=!0}else{const G=F[p],B=F[f],W=ns(G,t),Q=ns(B,o);r==="left"?(B.words.splice(Q,1,w),B.dirty.video=!0,B.translationModified.source=!0,G.words.splice(W,1),G.dirty.video=!0,G.translationModified.source=!0):(G.words.splice(W,1,w),G.dirty.video=!0,G.translationModified.source=!0,B.words.splice(Q,1),B.dirty.video=!0,B.translationModified.source=!0)}}),M=E?[p]:[p,f];return{convertedClips:vt(N,F=>{M.forEach(G=>{F[G]=Rh(F[G],R,S)})}),mergedTrackEntries:R,mergedAssetEntries:S}},irt=(e,t,o,r,n,a,i,s,x)=>{const{position:c}=t;if(c===null)return{clips:e,position:0,newAssetIdMap:{}};const l=Co(e,c),{newClips:d,newAssetIdMap:u}=Rpe(e,n,o,t,r,a,i,s,x),p=r&&t.globalWordRange?d[l].startPosition:d[l+1].startPosition;return{clips:d,position:p,newAssetIdMap:u}},Rpe=(e,t,o,r,n,a,i,s,x)=>{const{position:c,globalWordRange:l,globalClipRange:d}=r;if(c===null)return{newClips:e,newAssetIdMap:{}};const u=sn(e,c),p=Co(e,c),f=e[p],E=uH(f),T=mce(d),O=Zc(d);if(u.type===Z.ENTER&&Ys(f)===0||E||T)return{newClips:e,newAssetIdMap:{}};const R=!l&&(Kv(c,f)||Xv(c,f)||O);if(l){if(!hce(f,l))return ype(e,t,o,AI(r.globalWordRange,a),n,i,s,x);const{from:v,to:w}=l,[N,M]=[v,w].sort((G,B)=>G-B),k=N===0?f.startPosition+M:f.startPosition+N;return QR(e,t,o,k,n,i,s,x)}else{const y=R?Gpe(f):c;return QR(e,t,o,y,n,i,s,x)}},Ape=(e,t,o,r,n)=>{const a="([{「『([{【〖〈《〔〘〚<⟨",i=Ar(n),s=wt().toText(
1099o.text),x=i?s.match(/\s*\S+\s*/g):s.length>0?d2(s):null;let c=0;if(x===null||r===0&&e.captionMode===ar.TRANSCRIPT)return{front:{text:wt().fromText("")},back:{text:wt().fromText("")}};for(r===0?c=gpe(e.words,t,x,n):c=Math.round(x.length*(t/e.words.filter(p=>p.type!==Z.ENTER).length));c>0&&c<=x.length&&a.includes(x[c-1]);)c=c-1;const l=x.slice(0,c).join("").trimEnd(),[d,u]=wt().slice(o.text,l.length).map(p=>({style:o.style,text:p}));return{front:d,back:u}},Lf=(e,t,o,r,n,a)=>{if(t<=0||t>=Ys(e))return{newClips:[e],newAssetIdMap:{}};const i={},s=e.words,x=s.slice(0,t),c=new Set(x.map(k=>k.assetIds).flat()),l=s.slice(t).map(k=>{const F=k.assetIds.map(G=>{if(c.has(G)){const B=L.get(i,G);if(B===void 0){const W=Je(qe());return L.set(i,G,W),W}return B}return G});return{...k,assetIds:F}}),d={...n};for(const[k,F]of Object.entries(i)){const G=L.get(d,Je(k));G&&L.set(d,F,G)}const u=jg(e,r,n,a),p=u?Kx(u,a):void 0,f=o.map(k=>p?D0(p.text.textAspectLang):k),E=e.captions.map((k,F)=>Ape(e,t,k,F,f[F])),T=E.map(k=>k.front),O=E.map(k=>k.back),{captionMode:S,captionModel:R}=OM(x,T,e,o,r,d,a),{captionMode:y,captionModel:v}=OM(l,O,e,o,r,d,a),w=Rh({...e,words:x,startPosition:0,captions:R,captionMode:S,videoTransform:e.videoTransform?{...e.videoTransform}:void 0,dirty:{...e.dirty,video:!0},transitionModel:void 0},r,d),N=Hw(e)?"clipId":"id",M=Rh({...e,[N]:ct(),words:l,startPosition:0,captions:v,captionMode:y,dirty:{...e.dirty,video:!0},transitionModel:e.transitionModel&&sT(e.transitionModel,l)},r,d);return Dx(w.words,{preserveEmptyWords:!0}),{newClips:[w,M],newAssetIdMap:i}},Mf=(e,t)=>{if(Object.keys(t).length===0)return e;const o={...e};for(const[r,n]of Object.entries(t)){const a=L.get(o,Je(r));a&&L.set(o,n,a)}return o},QR=(e,t,o,r,n,a,i,s)=>{const x=Co(e,r),c=e[x],l=ns(c,r),{newClips:d,newAssetIdMap:u}=Lf(c,l,t,a,i,s),p=d.map(S=>S.id),f=x+1,E=[...e.slice(0,x),...d,...e.slice(x+1)],T=ed(E),O=E.length>f+1;if(n&&O){const S=f,R=Mf(i,u),y=eH(T,S,t,o,a,R),v={...u,...y.newAssetIdMap};return p.pop(),{newClips:y.newClips,newAssetIdMap:v}}return{newClips:T,newAssetIdMap:u}},ype=(e,t,o,r,n,a,i,s)=>{if(r===null)return{newClips:e,newAssetIdMap:{}};const x=r.clipIndex,c=e[x],{from:l,to:d}=G0(r),u=d-l,{newClips:[p,f],newAssetIdMap:E}=Lf(c,l,t,a,i,s),T=Mf(i,E),{newClips:[O,S],newAssetIdMap:R}=Lf(f,u,t,a,T,s),y={...E,...R},v=Mf(i,y),w=[p,O,S];w.map(W=>W.id);const[N,M]=[x,x+2],k=[...e.slice(0,x),...w,...e.slice(x+1)],F=ed(k),G=0<N,B=k.length>M;if(n){let W=F,Q=y;if(G){const j=Ipe(W,N,t,o,a,v);W=j.newClips,Q=Ah(Q,j.newAssetIdMap)}if(B){const j=eH(W,G?M-1:M,t,o,a,v);W=j.newClips,Q=Ah(Q,j.newAssetIdMap)}return{newClips:W,newAssetIdMap:Q}}return{newClips:F,newAssetIdMap:y}},vpe=([e,t],o,r)=>{const n=pe(sr(o)),[a,i]=wpe(o.text,n,r),[s,x]=Npe(o.pronunciation,n,r);return[{...e,text:a,type:qR(o.type,a),pronunciation:a===s?void 0:s},{...t,text:i,type:qR(o.type,i),pronunciation:i===x?void 0:x}]},srt=(e,t,o,r)=>{const n=pe(ue(t,2)),a=dW(n,e,o,r);if(!a)return null;const[i,s]=vpe(a.splitWords,e,n);return{splitWords:[i,{...s,hardcutWordMeta:void 0}],newAssetEntries:{...r,...a.newAssetEntries},newTrackEntries:{...o,...a.newTrackEntries}}},wpe=(e,t,o)=>{const r=d2(e);if(r.length<=1)return[e,e];const n=$t(1,r.length*o/t,r.length-1),a=r.slice(0,n).join(""),i=r.slice(n).join("");return[a,i]},Npe=(e,t,o)=>{if(e===void 0)return[void 0,void 0];const r=d2(e);if(r.length<=1)return[e,e];const n=$t(1,r.length*o/t,r.length-1),a=r.slice(0,n).join(""),i=r.slice(n).join("");return[a,i]},xrt=(e,t,o,r,n,a)=>{const i=e.words;if(e.words.length<=t)return{newClips:[e],newAssetIdMap:{}};const s=[e],x={};let c=n;const l=Math.floor(i.length/t);for(let d=0;d<l;d++){const u=s.pop();if(u===void 0)continue;const{newClips:p,newAssetIdMap:f}=Lf(u,t,o,r,c,a);s.push(...p),Object.assign(x,f),c=Mf(c,f)}return{newClips:s,newAssetIdMap:x}},Ppe=(e,t,o,r,n,a)=>{const i=e.words.map(p=>p.id),s=rn.intersection(i,t);if(s.length===0)return{newClips:[e],newAssetIdMap:{}};const x=[],c={};let l=n,d=0,u=e;for(const p of s){const f=i.indexOf(p);if(f<=0)continue;if(f===i.length-1){x.push(u),u=void 0;break}const E=Lf(u,f-d,o,r,l,a),[T,O]=E.newClips;x.push(T),Object.assign(c,E.newAssetIdMap),l=Mf(l,E.newAssetIdMap),u=O,d=f}return u!==void 0&&x.push(u),{newClips:x,newAssetIdMap:c}},bpe=(e,t,o,r,n,a)=>{const i=[],s={};for(const x of e){const c=x.words.map(u=>u.id),l=rn.intersection(c,t);if(l.length===0){i.push(x);continue}const d=Ppe(x,l,o,r,n,a);i.push(...d.newClips),Object.assign(s,d.newAssetIdMap)}return{newClips:i,newAssetIdMap:s}};var Mn=(e=>
1099(e.LOCAL="LOCAL",e.CLOUD="CLOUD",e.BROWSER="BROWSER",e))(Mn||{}),Mp=(e=>(e[e.NONE=0]="NONE",e[e.VERTICAL=1]="VERTICAL",e[e.HORIZONTAL=2]="HORIZONTAL",e[e.VERTICAL_HORIZONTAL=3]="VERTICAL_HORIZONTAL",e))(Mp||{}),Dp=(e=>(e.EXAMPLE="EXAMPLE",e.ONBOARDING="ONBOARDING",e))(Dp||{}),Ei=(e=>(e.VIDEO_AUDIO="video_audio",e.MULTI_VIDEO="multi_video",e.RECORD="record",e.AI_VOICE="ai_voice",e.VDROP="vdrop",e.SHORTS="shorts",e.DOCS_TO_VIDEO="docs_to_video",e.IMAGES_TO_VIDEO="images_to_video",e.TEXT_TO_VIDEO="text_to_video",e.DRAG_AND_DROP="drag_and_drop",e.ASSET_TO_VIDEO="asset_to_video",e.TEMPLATE="template",e.UNKNOWN="unknown",e))(Ei||{}),tH=(e=>(e.NEW="new",e.SAVE_AS="save_as",e))(tH||{}),Or=(e=>(e.SCENE="scene",e.CLIP="clip",e.GLOBAL_CLIP="global_clip",e.WORD="word",e))(Or||{});class Li{usedAssetIds;usedMainAssetIds;usedSubAssetIds;usedSourceMediaIds;baseSourceMediaIds;usedReferenceMediaIds;usedBackgroundIds;usedOverdubIds;denoiseMap;integrity;overdubInfosMap;trackEntries;assetEntries;constructor(t,o,r,n,a){this.overdubInfosMap=t??{},this.usedAssetIds=new Set(o),this.usedMainAssetIds=new Set,this.usedSubAssetIds=new Set,this.usedSourceMediaIds=new Set,this.baseSourceMediaIds=new Set,this.usedReferenceMediaIds=new Set,this.usedBackgroundIds=new Set,this.usedOverdubIds=new Set,this.integrity={duplicateMainAssetIds:new Set,mainAssetIdsInClip:new Set},this.trackEntries=r??zn({}),this.assetEntries=n??ii({}),this.denoiseMap=a??{}}getBaseMediaId(t){return Object.entries(this.denoiseMap).find(([,r])=>r===t)?.[0]??t}addUsedSourceMediaId=t=>{this.usedSourceMediaIds.add(t),this.baseSourceMediaIds.add(this.getBaseMediaId(t))};addUsedReferenceMediaId=t=>{this.usedSourceMediaIds.add(t),this.usedReferenceMediaIds.add(t)};isSceneRange(t){return t.type===Or.SCENE}isClipRange(t){return t.type===Or.CLIP}isGlobalClipRange(t){return t.type===Or.GLOBAL_CLIP}isWordRange(t){return t.type===Or.WORD}collectFrom(t,o){const r=o?.checkDuplicateMainAsset??!1;if(this.isSceneRange(t))t.model.forEach(n=>this.collectFromScene(n,r));else if(this.isClipRange(t)||this.isGlobalClipRange(t))t.model.forEach(n=>this.collectFromClip(n,r));else if(this.isWordRange(t))t.model.forEach(n=>this.collectFromWord(n,r));else return h("UsedMediaCollector.ts").info("Invalid range: "+JSON.stringify(t)),this;return this}collectFromWord(t,o){if(t===void 0){h("UsedMediaCollector.ts").error("word is undefined at collectFromWord()");return}t.assetIds.forEach(a=>{this.usedAssetIds.add(a);const i=L.get(this.assetEntries,a);i&&(i.role==="main"?(o&&this.usedMainAssetIds.has(a)&&this.integrity.duplicateMainAssetIds.add(a),this.usedMainAssetIds.add(a)):this.usedSubAssetIds.add(a))}),t.truncatedWords.forEach(a=>{a.assetIds.forEach(i=>{this.usedAssetIds.add(i);const s=L.get(this.assetEntries,i);s&&(s.role==="main"?this.usedMainAssetIds.add(i):this.usedSubAssetIds.add(i))})}),qc(t,this.trackEntries,this.assetEntries).forEach(a=>{this.addUsedSourceMediaId(a.mediaId)});const n=bH(t,this.trackEntries,this.assetEntries);if(n){const a=L.get(this.overdubInfosMap,n);a&&(this.usedOverdubIds.add(n),a.originWords.forEach(i=>{i.assetIds.forEach(s=>{this.usedAssetIds.add(s)})}))}}collectFromClip(t,o){if(t===void 0){h("UsedMediaCollector.ts").error("clip is undefined at collectFromClip()");return}t.assetIds.forEach(r=>{this.usedAssetIds.add(r);const n=L.get(this.assetEntries,r);if(n)if(n.role==="main"){this.integrity.mainAssetIdsInClip.add(r);return}else this.usedSubAssetIds.add(r)}),t.words.forEach(r=>this.collectFromWord(r,o)),t.backgroundId&&this.usedBackgroundIds.add(t.backgroundId)}collectFromScene(t,o){t.clips.forEach(r=>this.collectFromClip(r,o))}build=()=>{this.collectDirectReferenceMediaIds();const t=this.getIntegrityErrorMessages();if(t.length>0){const o=t.join(`
1100`);h("UsedMediaCollector.ts").warn(o),(wi()||fr.level===Xr.Hotfix)&&Y().popup({title:"Errors at UsedMediaCollector",content:o})}return this.addUsedSourceMediaId(_o),new oH(this.usedAssetIds,this.usedMainAssetIds,this.usedSubAssetIds,this.usedSourceMediaIds,this.baseSourceMediaIds,this.usedReferenceMediaIds,this.usedOverdubIds,this.usedBackgroun
1100dIds)};getUsedAssetTrackMediaIds=()=>{const t=new Set;return this.usedAssetIds.forEach(o=>{const r=L.get(this.assetEntries,o);r&&r.trackIds.forEach(n=>{const a=L.get(this.trackEntries,n);a&&t.add(a.mediaId)})}),t};collectDirectReferenceMediaIds=()=>{[...new Set([...this.usedSourceMediaIds,...this.getUsedAssetTrackMediaIds()])].forEach(o=>{const r=oa(o)?.visualAIGenerationMeta??eo(o)?.visualAIGenerationMeta;r?.referenceMediaIds?.forEach(n=>{this.addUsedReferenceMediaId(n)}),r?.userReferenceMediaIds?.forEach(n=>{this.addUsedReferenceMediaId(n)})})};getIntegrityErrorMessages=()=>{const t=this.getIntegrityIssueFlags(),o=[];return t.duplicateMainAsset&&o.push("Duplicate main asset: "+[...this.integrity.duplicateMainAssetIds].join(", ")),t.mainAssetInClip&&o.push("Main asset in clip: "+[...this.integrity.mainAssetIdsInClip].join(", ")),o};getIntegrityIssueFlags=()=>({duplicateMainAsset:this.integrity.duplicateMainAssetIds.size>0,mainAssetInClip:this.integrity.mainAssetIdsInClip.size>0})}class oH{usedAssetIds;usedMainAssetIds;usedSubAssetIds;usedSourceMediaIds;baseSourceMediaIds;usedReferenceMediaIds;usedOverdubIds;usedBackgroundIds;constructor(t,o,r,n,a,i,s,x){this.usedAssetIds=t,this.usedMainAssetIds=o,this.usedSubAssetIds=r,this.usedSourceMediaIds=n,this.baseSourceMediaIds=a,this.usedReferenceMediaIds=i,this.usedOverdubIds=s,this.usedBackgroundIds=x}getUsedAssetIds(){return this.usedAssetIds}getUsedMainAssetIds(){return this.usedMainAssetIds}getUsedSubAssetIds(){return this.usedSubAssetIds}getUsedSourceMediaIds(){return this.usedSourceMediaIds}getBaseSourceMediaIds(){return this.baseSourceMediaIds}getUsedReferenceMediaIds(){return this.usedReferenceMediaIds}getUsedOverdubIds(){return this.usedOverdubIds}getUsedBackgroundIds(){return this.usedBackgroundIds}getActiveAssetMediaIds(t){const o=new Set;return this.usedAssetIds.forEach(r=>{const n=L.get(t,r);n&&(o.add(n.track.mediaId),Tg(n.track)&&(o.add(n.track.pose.silentMediaId),n.track.pose.speakingMediaId&&o.add(n.track.pose.speakingMediaId)))}),o}getActiveAudioMediaIds(t){const o=new Set;return this.usedAssetIds.forEach(r=>{const n=L.get(t,r);n&&o.add(n.track.mediaId)}),o}getActiveAudioTypeMap(t){const o={};return this.usedAssetIds.forEach(r=>{const n=L.get(t,r);if(!n)return;const{mediaId:a,type:i}=n.track;o[a]=i}),o}}const dc=(e,t)=>new Set([...e,...t]),Lpe=(e,t)=>new oH(dc(e.getUsedAssetIds(),t.getUsedAssetIds()),dc(e.getUsedMainAssetIds(),t.getUsedMainAssetIds()),dc(e.getUsedSubAssetIds(),t.getUsedSubAssetIds()),dc(e.getUsedSourceMediaIds(),t.getUsedSourceMediaIds()),dc(e.getBaseSourceMediaIds(),t.getBaseSourceMediaIds()),dc(e.getUsedReferenceMediaIds(),t.getUsedReferenceMediaIds()),dc(e.getUsedOverdubIds(),t.getUsedOverdubIds()),dc(e.getUsedBackgroundIds(),t.getUsedBackgroundIds())),Mpe=(e,t,o,r)=>new Li(void 0,void 0,t,o,r).collectFrom({type:Or.SCENE,model:e}).build(),crt=(e,t,o,r)=>Mpe(e,t,o,r).getBaseSourceMediaIds(),rH=(e,t)=>cH(e,t)?0:t-e.startPosition,nH=(e,t)=>cH(e,t)?0:t-e.startPosition,sn=Gr((e,t)=>{const o=z0(e,t,rH);if(o!==void 0){const n=e[o],a=t-n.startPosition,i=n.words[a];if(i)return{...i,newline:a===0}}const r="invalid position "+t+" at getWordByPosition()";if(Vr())throw new Error(r);return h("clip.ts").warn(r),{...e[0].words[0],newline:!1}}),Dpe=(e,t)=>{if(e.length===0)return;const o=sn(e,t);return o.type===Z.ENTER?t>0?sn(e,t-1):void 0:o},d0=Gr((e,t)=>{const o=z0(e,t,nH);if(o!==void 0){const r=e[o],n=t-r.startPosition,a=r.words[n];if(a)return{...a,newline:n===0}}if(Vr())throw new Error("invalid global position "+t+" at getWordByGlobalPosition()");return h("clip.ts").warn("invalid position "+t+" at getWordByPosition()"),{...e[0].words[0],newline:!1}}),lrt=Gr((e,t,o,r)=>{try{const n=(c,l)=>{const d=qc(c.words[0],o,r),u=d.find(p=>mn(p)||U0(p));if(!u)throw new C(_.C_LOGIC_ERROR,{},"Target track not found");return l-u.sourceIn},a=(c,l)=>{const d=qc(c,o,r),u=d.find(p=>mn(p)||U0(p));if(!u)throw new C(_.C_LOGIC_ERROR,{},"Target track not found");return l-u.sourceIn},i=z0(e,t,n,!0);if(i===void 0)return;const s=e[i-1],x=z0(s.words,t,a,!0);return x===void 0?void 0:{word:{...s.words[x-1]},position:s.startPosition+x-1,clipInd:i-1}}catch(n){return h("clip.ts").error(P(n)),void 0}}),drt=Gr((e,t)=>
1100{if(t<0||t>=e.words.length){if(Vr())throw new Error("invalid localIndex "+t+" at getWordByLocalIndexInClip()");return h("clip.ts").warn("invalid localIndex "+t+" at getWordByLocalIndexInClip()"),{...e.words[0],newline:!1}}return{...e.words[t],newline:t===0}}),Co=Gr((e,t,o=!1)=>{if(t===null)return h("clip.ts").error("invalid position "+t+" at getClipIndexByPosition()"),0;const r=z0(e,t,rH);if(r!==void 0)return r;if(o)return-1;if(Vr())throw new Error("invalid position "+t+" at getClipIndexByPosition()");return h("clip.ts").warn("invalid position "+t+" at getClipIndexByPosition()"),0}),Er=Gr((e,t,o=!1)=>{if(t===null)return h("clip.ts").error("null position at getGlobalClipIndexByPosition()"),0;const r=z0(e,t,nH);if(r!==void 0)return r;if(o)return-1;if(wi())throw new Error("invalid position "+t+" at getGlobalClipIndexByPosition(), "+new Error().stack);return h("clip.ts").warn("invalid position "+t+" at getGlobalClipIndexByPosition()"),0}),nT=(e,t)=>{const o=[],r=e[t.globalClipIndex],{from:n,to:a}=Yv(t);return Array.prototype.push.apply(o,r.words.map((i,s)=>({...i,newline:s===0})).filter((i,s)=>s>=n&&s<a)),o},aH=e=>e.map(t=>t.words.map((o,r)=>
1100({...o,newline:r===0}))).flat(),kpe=(e,t,o)=>{const r=[];return sH(e,t,!0,(n,a)=>a>=o?!1:(r.push(n),!0)),r},Fpe=(e,t,o=!1)=>{const r=e.words.findIndex(n=>n.id===t);if(r!==-1)return r;if(o)return-1;if(Vr())throw new Error("invalid wordId "+t+" at getWordPositionInClipByWordId()");return h("clip.ts").warn("invalid wordId "+t+" at getWordPositionInClipByWordId()"),0},Wm=(e,t,o=!1)=>{for(let r=0,n=e.length;r<n;r+=1){const a=e[r].words.findIndex(i=>i.id===t);if(a!==-1)return a+e[r].startPosition}if(o)return-1;if(Vr())throw new Error("invalid wordId "+t+" at getPositionByWordId()");return h("clip.ts").warn("invalid wordId "+t+" at getPositionByWordId()"),0},iH=(e,t,o=!1)=>{for(let r=0,n=e.length;r<n;r+=1){const a=e[r].words.findIndex(i=>i.id===t);if(a!==-1)return a+e[r].startPosition}if(o)return-1;if(Vr())throw new Error("invalid wordId "+t+" at getPositionByWordId()");return h("clip.ts").warn("invalid wordId "+t+" at getGlobalPositionByWordId()"),0},Dw=(e,t,o=!1)=>{for(let r=0,n=e.length;r<n;r+=1)if(e[r].id===t)return r;if(o)return-1;if(Vr())throw new Error("invalid clipId "+t+" at getPositionByClipId()");return h("clip.ts").warn("invalid clipId "+t+" at getPositionByClipId()"),0},ml=(e,t,o=!1)=>{for(let r=0,n=e.length;r<n;r+=1)if(e[r].clipId===t)return r;if(o)return-1;if(Vr())throw new Error("invalid global clipId "+t+" at getGlobalClipIndexByClipId()");return h("clip.ts").warn("invalid global clipId "+t+" at getGlobalClipIndexByClipId()"),0},Yg=e=>{const t=ks(),o=He(t),r=Ute(o,a=>a.clipId===e),n=Hm(r,o);if(r===-1||n===-1){if(Vr())throw new Error("invalid clipId "+e+" at getSceneIndexAndClipIndexByClipId()");return h("clip.ts").warn("invalid clipId "+e+" at getSceneIndexAndClipIndexByClipId()"),{sceneIndex:0,clipIndex:0}}return{sceneIndex:n,clipIndex:r}},Upe=e=>{const t=e.length;if(t===0)return 0;const o=e[t-1];return o.startPosition+o.words.length},Vpe=e=>{const t=e.length;if(t===0)return 0;const o=e[t-1];return o?o.startPosition+o.words.length:0},sH=(e,t,o,r)=>{let n=Co(e,t),a=e[n],i=t-a.startPosition,s;const x=o?1:-1;for(;s=a.words[i],r(s,a.startPosition+i)!==!1;)if(i+=x,i<0||i>=a.words.length){if(n+=x,n<0||n>=e.length)break;a=e[n],i=o?0:a.words.length-1}},urt=(e,t)=>{if(e.length===0)return 0;const o=(()=>{for(const n of e)if(t<hl(n))return n;return e[e.length-1]})(),r=(()=>{const{words:n}=o,a=n.findIndex(i=>Sd(i)>t);return a===-1?n.length-1:a})();return o.startPosition+r},prt=(e,t)=>{if(e.length===0)return 0;const[o,r]=(()=>{for(let d=1,u=e.length;d<u;d+=1){const p=e[d];if(t<vo(p))return[e[d-1],p]}return[e[e.length-1],void 0]})(),n=(()=>{const{words:d}=o,u=d.length;for(let p=0;p<u-1;p++){const f=d[p],E=Sd(f);if(E>t)return[{idx:p,wordStartTime:f.timelineStart},{idx:p+1,wordStartTime:E}]}return[{idx:u-1,wordStartTime:d[u-1].timelineStart},void 0]})();if(n===void 0)return o.startPosition+o.words.length;const[a,i]=n,s=a.wordStartTime,x=i?.wordStartTime??(r?vo(r):void 0)??1/0,c=Math.abs(s-t),l=Math.abs(x-t);return o.startPosition+a.idx+(c<l?0:1)},xH=(e,t,o,r)=>(o.length>0?aH(o):t?nT(e,t):[]).reduce((i,s)=>{if(s.type===Z.ENTER)return[...i,[]];const x=i.length>0?i[i.length-1]:[],c=[...x,s];return[...i.slice(0,-1),c]},[]).map(i=>ud(i,void 0,!1,Ar(on(r)))).join(""+vu+vu),cH=(e,t)=>t==null?!1:t>=e.startPosition&&t<e.startPosition+e.words.length,frt=(e,t)=>t===null?!1:t>=e.startPosition&&t<e.startPosition+e.words.length,lH=(e,t)=>{if(e===null)return!1;const{from:o,to:r}=Yv(e);return o<=t&&t<r},grt=(e,t,o,r)=>e.globalClipIndex!==o?!1:lH(e,t-r[o].startPosition),_rt=(e,t)=>e.flatMap(o=>o.words.map((r,n)=>[r,n+o.startPosition])).filter(([,o])=>o>t).find(([o])=>o.duration>0)?.[1],Ert=(e,t)=>e.flatMap(o=>o.words.map((r,n)=>[r,n+o.startPosition])).filter(([,o])=>o<t).reverse().find(([o])=>o.duration>0)?.[1],ac=e=>fl(e.words),Bg=e=>pe(e.reduce((t,o)=>t+ac(o),0)),cs=e=>sI(e.words),Df=e=>ue(sI(e.words),2),dH=e=>{const t=hl(e[e.length-1]),o=vo(e[0]);return t-o},Nc=Gr(e=>e.map(t=>t.clips).flat()),mrt=Gr((e,t,o,r)=>{if(t===null)return;const n=Dpe(e,t);if(!n)return;const{visualMediaId:a}=ss(n,o,r);return a}),Kg=(e,t)=>e.length===0?!1:t===0,tl=(e,t)=>
1100e.length===0?!1:t===e.length-1,Gpe=e=>C2(e)+Math.ceil(Ys(e)/2),Ys=e=>e.words.length-1,uH=e=>Ys(e)<=1,pH=e=>{let t=null;return e[0]?t=0:e[1]&&(t=1),t},fH=e=>{let t=null;return e[1]?t=1:e[0]&&(t=0),t},gH=(e,t)=>{for(let o=e+1;t[o]!==void 0;o++)if(t[o])return o;return null},_H=(e,t)=>{for(let o=e-1;t[o]!==void 0;o--)if(t[o])return o;return null},Wpe=e=>e.map(t=>({start:vo(t),duration:Df(t)})).sort((t,o)=>t.start-o.start<0?-1:1).reduce((t,o)=>{const r=t[t.length-1];return r&&Math.abs(r.start+r.duration-o.start)<b0?(t.pop(),t.push({start:r.start,duration:r.duration+o.duration}),t):(t.push(o),t)},[]),kw=e=>e.filter(t=>t.type!==Z.ENTER),Xg=(e,t,o)=>{const r=new Set;return e.forEach(n=>{const{visualMediaIds:a,audioMediaIds:i}=gl(n,t,o);a.forEach(s=>r.add(s)),i.forEach(s=>r.add(s))}),Array.from(r.values())},EH=(e,t,o)=>{const r=new Set;return e.forEach(n=>{const{visualMediaIds:a}=gl(n,t,o);a.forEach(i=>r.add(i))}),Array.from(r.values())},Fw=(e,t)=>(e&&t&&e&&e.assetIds.filter(o=>t.assetIds.find(r=>r===o)))??[],Uw=(e,t,o,r)=>{const n=aI(o,e?iI(e.words):void 0);return{...yg(n,r),assetIds:Fw(e,t)}},mH=(e,t)=>e.map(o=>({...yg(aI(t)),captions:Sw(o)})),hrt=(e,t,o,r,n)=>{const a=aI(o,e?iI(e.words):void 0);return{...yg(a,n),assetIds:[...Fw(e,t),r]}},Irt=(e,t)=>e.words.every(o=>iN(o,t)),Trt=(e,t,o)=>o.map(r=>({...r,assetIds:[...r.assetIds,...Fw(e,t)]})),Srt=(e,t,o,r)=>{const n=Co(e,t),a=e[n],i=ns(a,t),s=vt(a,p=>{p.words=p.words.filter((f,E)=>!(C0e(f)&&E===i))}),x=Ys(s)===0,c=e.slice(0,n),l=e.slice(n+1),d=Rh(s,o,r),u=x?[...c,...l]:[...c,d,...l];return ed(u)},Ort=e=>ed(e.filter(t=>ac(t)>0)),hH=(e,t)=>e.find(o=>o.clipId===t),Hpe=(e,t,o)=>EH(kw(e.words),t,o).some(n=>!pl(n)),jpe=(e,t,o)=>!o&&e===t,Vw=e=>{const t=/var\(([a-z-0-9,\s]+)\)/;if(e.type===k0.SOLID){if(e.color.match(t))throw h("clip.ts").error("CSS Color Variable is not supported: "+e.color),new C(_.C_LOGIC_ERROR);return e.color||"black"}return"black"},Gw=(e,t,o)=>{const r=new Set;return e.forEach(n=>{Xg(n.words,t,o).forEach(i=>r.add(i))}),Array.from(r)},Crt=(e,t)=>{const o=ac(e),r=vo(e);return{timelineStart:r,timelineEnd:r+o,wordInClipRange:Tm(0,e.words.length,"WORD_IN_CLIP"),globalClipRange:Tm(t,t+1,"GLOBAL_CLIP")}},Rrt=(e,t,o,r)=>{if(!t)return[];const n=g2(t),a=new Li(void 0,void 0,o,r).collectFrom({type:Or.GLOBAL_CLIP,model:Array.from(n).map(s=>e.at(s)).filter(Se)}).build(),i=a.getUsedSubAssetIds();return CS(i,o,r)},Art=(e,t,o)=>{const r=new Li(void 0,void 0,t,o).collectFrom({type:Or.CLIP,model:[e]}).build(),n=r.getUsedSubAssetIds();return CS(n,t,o)},IH=(e,t,o)=>e.filter(r=>ss(r,t,o).audioMediaId===gf||r.type!==Z.SPACER&&r.type!==Z.ENTER&&!(r.type===Z.SILENT&&iN(r,o))),yrt=(e,t)=>{const o={};return{duplicatedClips:e.map(n=>{const a=ND(n.assetIds,o).map(Je);return{...n,clipId:ct(),sceneId:t,words:n.words.map(i=>({...i,id:ct(),assetIds:ND(i.assetIds,o).map(Je)})),assetIds:a}}),newAssetIdMap:o}},zpe=()=>Gr((e,t)=>({id:e.clipId,startPosition:e.startPosition-t,words:e.words,assetIds:e.assetIds,videoTransform:e.videoTransform,captionMode:e.captionMode,captions:e.captions,markerId:e.markerId,dirty:e.dirty,translationModified:e.translationModified,backgroundId:e.backgroundId,transitionModel:e.transitionModel})),wM=new Map,kf=(e,t)=>{const{clipId:o}=e;let r=wM.get(o);return!r&&(r=zpe(),wM.set(o,r)),r(e,t)},Ww=(e,t)=>({sceneId:t,clipId:e.id,startPosition:e.startPosition,words:e.words,assetIds:e.assetIds,videoTransform:e.videoTransform,captionMode:e.captionMode,captions:e.captions,markerId:e.markerId,dirty:e.dirty,translationModified:e.translationModified,backgroundId:e.backgroundId,transitionModel:e.transitionModel}),Ype=Gr((e,t)=>e.map(o=>Ww(o,t))),Bpe=Gr((e,t)=>{let o=0;if(t.length===0)return o;for(let a=0;a<t.length;a++){const i=t[a],s=i.clips.length;if(e<o+s)return e-o;o+=i.clips.length}const r=t.map(a=>""+a.clips.length).join(","),n="Cannot get clipIndex from globalClipIdx "+e+" with scenes with clip lengths: "+r;if(h("clip.ts").error(n),Vr())throw new Error(n);return 0}),Kpe=Gr((e,t,o)=>{const r=t[o];if(!r){const n="Error in fromClipIndex: sceneIndex "+o+" is out of range of "+t.length+" scenes";if(h("clip.ts").error(n),Vr())throw new Error(n);return 0}return r.globalClipRange.from+e}),vrt=(e,t)=>kte(t,o=>o.assetIds.includes(e)),Xpe=(e,t=0,o=e.length-1)=>e.reduce((r,n,a)=>(a<t||a>o||n.assetIds.forEach(i=>
1100{const s=L.get(r,i);s?s.endClipIndex=a:L.set(r,i,{startClipIndex:a,endClipIndex:a})}),r),{}),Jpe=(e,t,o)=>{const r=t.startClipIndex,n=t.endClipIndex,a=s=>{const x=L.get(o,s);if(!x)return!1;const c=x.startClipIndex<=r,l=x.endClipIndex>=n;return c&&!l||!c&&l};return e.flatMap(s=>s.assetIds).filter(a).reduce((s,x)=>{const c=L.get(s,x),l=c??ho();return L.set(s,x,l),s},{})},qpe=(e,t,o,r,n,a,i)=>{const s=[],x={},c=t.startClipIndex,l=t.endClipIndex;for(const[d,u]of Object.entries(n)){const p=Je(d);if(u.startClipIndex<=c&&u.endClipIndex>=l){s.push(p);continue}const f=L.get(i,p);if(!f)continue;const E=f.trackIds.map(S=>L.get(a,S)).filter(Se);if(E.length===0)continue;if(E.every(ll)){s.push(p);continue}const T=Math.max(u.startClipIndex,c),O=Math.min(u.endClipIndex,l);x[p]={startWordId:e[T].words[0].id,endWordId:iI(e[O].words).id}}return vt(o,d=>{Object.entries(x).forEach(([u,p])=>{const f=Je(u),E=L.get(r,f)??f,T=d.words.findIndex(S=>S.id===p.startWordId),O=d.words.findIndex(S=>S.id===p.endWordId);d.words.slice(T,O+1).forEach(S=>{S.assetIds.push(E)})}),d.assetIds=s})},TH=e=>{if(e.length===0)return 0;const t=e[e.length-1];return hl(t)},aT=Gr(e=>ci(e).map(o=>o.id)),wrt=(e,t,o,r,n,a,i,s)=>{let x=e;o.forEach((l,d)=>{const u=t[l].id;let p=Wm(x,u),f=Co(x,p);const{newClips:E}=QR(x,r,n,p,!1,a,i,s);if(x=ed(E),p=Wm(x,u),f=Co(x,p),f-(d-1)>1){const{newClips:T}=bf(x,d-1,f,r,n,a,i);x=ed(T)}});const{newClips:c}=bf(x,o.length-1,x.length,r,n,a,i);return x=ed(c),x},Nrt=(e,t,o,r)=>vt(e,n=>{const a=[...e.captions];a[o]={text:wt().fromText(t)},t!==Hn(e,Ar(r),0)&&(n.captionMode=ar.MANUAL,n.captions=a,n.dirty={...n.dirty,caption:!0})}),Hw=e=>e.clipId!==void 0,ai=e=>Hw(e)?e.clipId:e.id,Prt=(e,t,o,r,n,a,i)=>{const s=pEe(e,t);if(t.length!==s.length){const d="Error in realignClipsBySentences: sentences length "+t.length+" !== startWordIds length "+s.length;throw h("clip.ts").error(d),new C(_.C_CLIENT_LINEBREAK_ERROR,{},d)}const x=bpe(e,s,o,n,a,i),c=Spe(x.newClips,s,o,r,n,a),l=Ah(x.newAssetIdMap,c.newAssetIdMap);return{newClips:c.newClips,newAssetIdMap:l}},brt=(e,t)=>{let o=0;const r=[...e];for(const n of t){const{oldChunk:a,newClips:i}=n,s=i.length,x=a.to-a.from,c=a.from;r.splice(o+c,x,...i),o+=s-x}return r},Lrt=e=>{let t=0;const o=[];for(const r of e){const{oldChunk:n,newClips:a}=r,i=n.from,s=a.length,x=n.to-n.from,c={type:"CLIP",from:i+t,to:i+s+t};o.push(c),t+=s-x}return o},Mrt=e=>e.reduce((t,o)=>({from:o.from,to:o.to,next:t??void 0}),null),SH=(e,t,o)=>{const r=ci(t),n=r[o];if(!n){const a="Error in getLocalClipIdx: sceneIndex "+o+" is out of range of "+r.length+" scenes";if(h("clip.ts").error(a),wi())throw new C(_.C_LOGIC_ERROR,{},a);return}if(LG(n.globalClipRange,e))return e-n.globalClipRange.from},jw=Gr((e,t,o)=>{const r=ci(o),n=r[t];if(!n){const a="Error in toGlobalClipIndex: sceneIndex "+t+" is out of range of "+r.length+" scenes";if(h("clip.ts").error(a),wi())throw new C(_.C_LOGIC_ERROR,{},a);return 0}return n.globalClipRange.from+e}),Hm=Gr((e,t)=>{const o=ci(t);for(let r=0;r<o.length;r++){const n=o[r];if(LG(n.globalClipRange,e))return r}return-1}),OH=(e,t,o)=>o!==void 0?e.captions[o].style!==void 0:e.captions.some((r,n)=>t[n]&&r.style),Drt=(e,t)=>e.map(o=>Hn(o,Ar(t),Ke.ORIGINAL)).join(" "),CH=(e,t,o)=>({"playback-rate":!RH(e),"video-transform":e.videoTransform!==void 0||o!==void 0&&ese(o),"source-volume":t!==void 0&&t.volume!==1,background:e.backgroundId!==void 0,transition:e.transitionModel!==void 0,filter:o!==void 0&&NG(o)}),NM=3,krt=(e,t,o,r,n)=>{switch(e){case k_.AUDIO:case k_.VIDEO:return A("smart_tooltip.clip_guide_cut_desc");case k_.BLANK:return A("smart_tooltip.blank_clip_guide");case k_.TTS:{const a=J2e(t,o,r,n),i=a.slice(0,NM),s=a.slice(NM),x=i.map(X3).join(`
1101`),c=s.length>0?Q2e(s):"";return x+`
1102`+c}}},RH=e=>e.words.every(t=>t.playbackRate===Un),AH=e=>e.words.at(0)?.playbackRate??Un,vo=e=>e.words.at(0)?.timelineStart??pe(0),hl=e=>{const t=e.words.at(-1);return t?Sd(t):pe(0)},yH=(e,t)=>vt(e,o=>{o.forEach(r=>{const n=r.assetIds.filter(a=>!t.has(a));r.assetIds.length!==n.length&&(r.assetIds=n),r.words.forEach(a=>{const i=a.assetIds.filter(s=>!t.has(s));a.assetIds.length!==i.length&&(a.assetIds=i)})})}),Qpe=(e,t,o,r)=>{const n=zn({}),a=ii({});return{clips:t.map(s=>{const x=Uw(o,r,e,s),c=x.words.map(l=>{if(l.type===Z.ENTER)return l;const d={trackId:Rt(),sourceIn:pe(0),sourceOut:pe(sr(l)),mediaId:gf,type:ze.TTSClip,volume:ma,loop:!1,playbackRate:Un},u={trackIds:[d.trackId],role:"main",rangeType:tr.WORD},p=ho();return L.set(n,d.trackId,d),L.set(a,p,u),{...l,assetIds:[...l.assetIds,p]}});return{...x,words:c}}),trackEntries:n,assetEntries:a}},iT=(e,t,o)=>e.words.flatMap(r=>pW(r,t,o)),Frt=(e,t,o,r)=>{const n=e[t];if(!n)return[];const a=n.words[o],i=n.words[r-1];return!a||!i?[]:[{startTime:a.timelineStart,endTime:Sd(i)}]},Urt=(e,t)=>{if(t.length===0||e.length===0)return[];const o=[...t].sort((n,a)=>n-a),r=[];for(const n of o){const a=e[n];a&&r.push({startTime:vo(a),endTime:hl(a)})}return r},Vrt=(e,t,o)=>{if(e.length===0)return[];try{const r=d0(e,t),n=d0(e,o-1);return[{startTime:r.timelineStart,endTime:Sd(n)}]}catch{return[]}};var Re=(e=>(e.NONE="none",e.CROSS_FADE="cross_fade",e.LINEAR_BLUR="linear_blur",e.DIRECTIONAL_WARP="directional_warp",e.GLITCH_MEMORIES="glitch_memories",e.PIXELIZE="pixelize",e.WIND="wind",e.VERTICAL_WIPE="vertical_wipe",e.SIMPLE_ZOOM="simple_zoom",e.WIPE_LEFT="wipe_left",e.WIPE_RIGHT="wipe_right",e.WIPE_UP="wipe_up",e.WIPE_DOWN="wipe_down",e.IRIS="iris",e.DREAMY="dreamy",e.RADIAL="radial",e.WINDOW_BLIND="window_blind",e.CIRCLE_OPEN="circle_open",e.DIRECTIONAL_WIPE="directional_wipe",e.MORPH="morph",e.BLACK_FADE_OUT="black_fade_out",e.WHITE_FADE_OUT="white_fade_out",e.COLOR_DISTANCE="color_distance",e.GRAY_SCALE_FADE="gray_scale_fade",e))(Re||{}),or=(e=>(e[e.NONE=0]="NONE",e[e.CROSS_FADE=1]="CROSS_FADE",e[e.LINEAR_BLUR=2]="LINEAR_BLUR",e[e.DIRECTIONAL_WARP=3]="DIRECTIONAL_WARP",e[e.GLITCH_MEMORIES=4]="GLITCH_MEMORIES",e[e.PIXELIZE=5]="PIXELIZE",e[e.WIND=6]="WIND",e[e.VERTICAL_WIPE=7]="VERTICAL_WIPE",e[e.SIMPLE_ZOOM=8]="SIMPLE_ZOOM",e[e.WIPE_LEFT=9]="WIPE_LEFT",e[e.WIPE_RIGHT=10]="WIPE_RIGHT",e[e.WIPE_UP=11]="WIPE_UP",e[e.WIPE_DOWN=12]="WIPE_DOWN",e[e.IRIS=13]="IRIS",e[e.DREAMY=14]="DREAMY",e[e.RADIAL=15]="RADIAL",e[e.WINDOW_BLIND=16]="WINDOW_BLIND",e[e.CIRCLE_OPEN=17]="CIRCLE_OPEN",e[e.DIRECTIONAL_WIPE=18]="DIRECTIONAL_WIPE",e[e.MORPH=19]="MORPH",e[e.BLACK_FADE_OUT=20]="BLACK_FADE_OUT",e[e.WHITE_FADE_OUT=2
11021]="WHITE_FADE_OUT",e[e.COLOR_DISTANCE=22]="COLOR_DISTANCE",e[e.GRAY_SCALE_FADE=23]="GRAY_SCALE_FADE",e))(or||{}),Zpe=(e=>(e.PREVIEW="preview",e.EXPORT="export",e))(Zpe||{});const sT=(e,t)=>{if(e===void 0)return;const o=ue(sI(t),2),{nextTimelineStartOffset:r,nextDuration:n}=o>=e.duration?{nextTimelineStartOffset:o-e.duration,nextDuration:e.duration}:{nextTimelineStartOffset:0,nextDuration:o};return e.timelineStartOffset===r&&e.duration===n?e:{...e,timelineStartOffset:r,duration:n}},Grt=e=>{if(e.transitionModel===void 0)return;const{duration:t}=e.transitionModel,{words:o}=e,{position:r}=$pe(e,t),n=o.length-1;return new Set(Array.from({length:n-r},(a,i)=>r+i))},$pe=(e,t)=>{const{words:o}=e;let r=0;for(let n=o.length-1;n>0;n--){const a=o[n];if(r+=Rn(a),r>=t)return{position:n,remainingDuration:r-t}}return{position:0,remainingDuration:0}},Wrt=async(e,t)=>{if(pl(e)===!1||e===_o)return null;const o=gd(e);let r,n=!1;if(o)r=o;else{const a=await En(e);if(!a)return null;r=URL.createObjectURL(a),n=!0}try{return await sN(r,t)??null}finally{n&&URL.revokeObjectURL(r)}},Hrt=(e,t,o,r,n,a,i,s,x,c,l)=>{const d=o*s,u=r*x,p=n*s,f=a*x,E=i*(Math.PI/180),T=l===Go.HORIZONTAL||l===Go.VERTICAL_HORIZONTAL?-1:1,O=l===Go.VERTICAL||l===Go.VERTICAL_HORIZONTAL?-1:1;e.save(),e.globalAlpha=c,e.translate(d+p/2,u+f/2),e.rotate(E),e.scale(T,O),e.drawImage(t,-p/2,-f/2,p,f),e.restore()},jrt=(e,t)=>{if(e===void 0||e.transitionModel===void 0)return!1;const o=vo(e)+e.transitionModel.timelineStartOffset,r=o+e.transitionModel.duration;return t>o&&t<=r},efe={[Re.BLACK_FADE_OUT]:wr.transition.blackFadeOut,[Re.CIRCLE_OPEN]:wr.transition.circleOpen,[Re.COLOR_DISTANCE]:wr.transition.colorDistance,[Re.CROSS_FADE]:wr.transition.crossFade,[Re.DIRECTIONAL_WARP]:wr.transition.directionalWarp,[Re.DIRECTIONAL_WIPE]:wr.transition.directionalWipe,[Re.DREAMY]:wr.transition.dreamy,[Re.GLITCH_MEMORIES]:wr.transition.glitchMemories,[Re.GRAY_SCALE_FADE]:wr.transition.grayScale,[Re.IRIS]:wr.transition.iris,[Re.LINEAR_BLUR]:wr.transition.linearBlur,[Re.MORPH]:wr.transition.morph,[Re.PIXELIZE]:wr.transition.pixelize,[Re.RADIAL]:wr.transition.radial,[Re.SIMPLE_ZOOM]:wr.transition.simpleZoom,[Re.VERTICAL_WIPE]:wr.transition.verticalWipe,[Re.WHITE_FADE_OUT]:wr.transition.whiteFadeOut,[Re.WIND]:wr.transition.wind,[Re.WINDOW_BLIND]:wr.transition.windowBlind,[Re.WIPE_DOWN]:wr.transition.wipeDown,[Re.WIPE_LEFT]:wr.transition.wipeLeft,[Re.WIPE_RIGHT]:wr.transition.wipeRight,[Re.WIPE_UP]:wr.transition.wipeUp},zrt=(e,t)=>t===void 0||t.type===Re.NONE?"":e?efe[t.type]:wr.transition.default,tfe=e=>e.some(t=>t.transitionModel!==void 0),ofe=async(e,t,o,r,n,a,i,s,x,c,l)=>{const{contextWords:d,targetIndexs:u}=afe(o.words,r,x,c,l);if(d.length===r.length)return{result:"error",errorMsg:"Context exceeded",noContext:!0};const p=Date.now(),f=o.words.filter(O=>r.includes(O.id)),E=f.map(O=>O.text).join(" "),T=f.some(O=>PH(O,x,c));BUe(r.length,E.length,n.length,T,a);try{const O=r[0],S=o.words.findIndex(j=>j.id===O),R=S>=0?o.startPosition+S:void 0,y=s(R);let v,w;if(i){const{requestId:j,sid:$}=await Fie(e,n,a);v=j,w=$}else{let j;if(SG())j=await sfe(d,x,c);else{if(!y){const U="Failed to get audioInfo during overdub";throw new C(_.C_AUDIO_FRAGMENT_LOAD_GENERAL_ERROR,{},U)}j=await ife(d,y,x,c)}const{requestId:$}=await Die(e,j);v=$;const q=rfe(d,u,n,a),{sid:H}=await kie(e,v,q);w=H}if(v===void 0||w===void 0)return{result:"error",errorMsg:"requestId or sid is undefined",noContext:!1};const N=await Uie(e,w,v,i),M=await be().fetchUserInfo(),k=!ba().isPremiumFeatureAvailable(Ut.OVERDUB),F=M&&k?Math.max(0,(M.planInfo?.overdubLimit??Wh)-M.featureUsage.trialAccOverdub):void 0,G=await Yw(N),B=_6((Date.now()-p)/1e3,2);KUe(f.length,E.length,n.length,T,B,F);const W="mp3",Q=qe.v4();return{result:"success",mediaId:Q,audioDuration:G,fileName:Q+"."+W,blob:N}}catch(O){return XUe(f.length,E.length,n.length,T,a),{result:"error",errorMsg:P(O),noContext:!1}}},rfe=(e,t,o,r)=>{const n=e.map(s=>s.text).join(" "),a=nfe(e,t),i=oT(o);return{contextText:n,sourceTextRangeIdx:a.sourceTextRange,sourceAudioRangeSec:a.sourceAudioRange,targetText:i,audioLanguage:r}},nfe=(e,t)=>
1102{if(t.length===0){const s="positions is empty";throw new C(_.C_LOGIC_ERROR,void 0,s)}const o=e.slice(0,t[0]).reduce((s,x)=>({textStartIdx:s.textStartIdx+(x.text.length+1),startTime:s.startTime+x.duration}),{textStartIdx:0,startTime:0}),r=t.at(-1),n=e.slice(t[0],r+1).reduce((s,x)=>({textEndIdx:s.textEndIdx+x.text.length+1,endTime:s.endTime+x.duration}),{textEndIdx:o.textStartIdx-1,endTime:o.startTime}),a=[o.textStartIdx,n.textEndIdx],i=[ue(o.startTime,2),ue(n.endTime,2)];return{sourceTextRange:a,sourceAudioRange:i}},afe=(e,t,o,r,n)=>{const a=e.filter(l=>{const{audioMediaId:d}=ss(l,o,r);return[Z.NORMAL,Z.SOUND].includes(l.type)&&d&&!pd(d,n)}),i=a.reduce((l,d,u)=>(t.includes(d.id)&&l.push(u),l),[]);let s=i[0],x=i[i.length-1],c=i.reduce((l,d)=>l+sr(a[d]),0);for(;;){let l=!1;const d=s>0,u=x<a.length-1;if(d&&u){const p=c+sr(a[s-1])+sr(a[x+1]);if(p<=LE){s--,x++,c=p,l=!0;continue}}if(!l&&d){const p=c+sr(a[s-1]);p<=LE&&(s--,c=p,l=!0)}if(!l&&u){const p=c+sr(a[x+1]);p<=LE&&(x++,c=p,l=!0)}if(!l)break}return{contextWords:a.slice(s,x+1),targetIndexs:i.map(l=>l-s)}},ife=async(e,t,o,r)=>{const n=t.audioSamples,a=[],i=fl(e);for(const l of e){const d=oi(l,o,r);if(!d)throw new C(_.C_LOGIC_ERROR,{},"Audio media track not found");const{mediaId:u,sourceIn:p}=d,f=n[u],E=Math.round(p*t.sampleRate),T=Math.round((p+sr(l))*t.sampleRate),O=await f.getSampleSlice(E,T);a.push(O)}const s=kH($N(a)),x=Jg(s.buffer,{isFloat:!1,numChannels:1,sampleRate:t.sampleRate,numFrames:Math.floor(t.sampleRate*i)});return new Blob([x],{type:"audio/wav"})},sfe=async(e,t,o)=>{const r=[],n=fl(e),a=zx;for(const x of e){const c=oi(x,t,o);if(!c)throw new C(_.C_LOGIC_ERROR,{},"Audio media track not found");const{mediaId:l,sourceIn:d}=c,u=await Lie({mediaId:l,sampleRate:a,numberOfChannels:1,time:d,duration:sr(x)});if(!u)throw new C(_.C_AUDIO_FRAGMENT_LOAD_GENERAL_ERROR,{},"Failed to read context audio during overdub");r.push(u[0])}const i=kH($N(r)),s=Jg(i.buffer,{isFloat:!1,numChannels:1,sampleRate:a,numFrames:Math.floor(a*n)});return new Blob([s],{type:"audio/wav"})},Yrt=(e,t,o,r,n)=>{const a=e.words.slice(0,t[0]),i=e.words.slice(t[1]),s=e.words.slice(t[0],t[1]),x=[...new Set(s.flatMap(d=>d.assetIds.filter(u=>L.get(n,u)?.role==="sub"))),o],c={...s[0],type:Z.NORMAL,text:r,duration:fl(s),assetIds:x},l=[...a,c,...i];return{...e,words:l,transitionModel:e.transitionModel&&sT(e.transitionModel,l)}},Brt=(e,t,o,r,n,a,i)=>{const s=e.words.at(o-1),x=e.words.at(o+1),c=t.assetIds.filter(f=>L.get(i,f)?.role==="sub"),l=r.originWords.map((f,E)=>{const T=f.assetIds.filter(S=>L.get(i,S)?.role==="main"),O=T.concat(c).filter(S=>{const R=L.get(i,S);if(!R)return!1;const y=R.trackIds.map(w=>L.get(a,w));return y.length===0?!1:y.every(w=>w&&Wa(w)&&Id(w))?E===0:!0});return{id:ct(),text:f.text,timelineStart:pe(0),duration:f.duration,aligned:f.aligned,type:f.wordType,originalDuration:f.originalDuration,originalStartTime:f.originalStartTime,pronunciation:f.pronunciation,hardcutWordMeta:f.hardcutWordMeta,truncatedWords:[],assetIds:O,playbackRate:Tv(s,x)}}),d=e.words.slice(0,o),u=e.words.slice(o+1),p=[...d,...l,...u];return{...e,words:p,transitionModel:e.transitionModel&&sT(e.transitionModel,p)}},vH=(e,t)=>e/t,wH=(e,t)=>{const o=vH(e.audioDuration,t);return{start:0,end:t,playbackRate:o,mediaId:e.mediaId}},xfe=(e,t,o,r,n,a)=>{if(o==="script")return xt.info(A("overdub.script_view_mode_not_supported_toast")),!1;if(e.length===t.length)return xt.info(A("overdub.no_context_words_toast")),!1;const i=new Set(e.flatMap(p=>gl(p,r,n).audioMediaIds)),s=i.size;return Array.from(i).some(p=>pd(p,a))?(xt.info(A("overdub.tts_word_included_toast")),gC(!1,s),!1):e.every(p=>(p.type===Z.NORMAL||p.type===Z.SOUND)&&oi(p,r,n)!==void 0)?s>1?(xt.info(A("overdub.need_same_media_toast")),gC(!0,s),!1):e.every((p,f)=>{const E=e[f+1];if(!E)return!0;const T=oi(p,r,n),O=oi(E,r,n);return!T||!O?!(T!==void 0||O!==void 0):Math.abs(T.sourceOut-O.sourceIn)<b0})?e.some(p=>{const{audioMediaId:f}=ss(p,r,n);return f?!eo(f)?.videoAudioMetaInfo.audioInfo:!0})?(xt.info(A("overdub.source_audio_not_found_toast")),!1):e.reduce((p,f)=>p+f.duration,0)>LE?(xt.info(A("overdub.selected_duration_too_long_toast")),!1):!0:(xt.info(A("overdub.need_continuous_word_toast")),gC(!0,s),!1):(xt.info(A("overdub.unable_word_toast")),!1)},Krt=(e,t,o)=>{const r=o.groupWordIds,n=e.words.slice(t,t+r.length).map(a=>a.id);return r.every(a=>n.includes(a))},Xrt=(e,t)=>{const o=Object.values(e).filter(r=>r.groupWordIds.some(n=>t.includes(n))).map(r=>r.groupWordIds[0]);return vt(e,r=>{o.forEach(n=>{L.remove(r,n)})})},Jrt=(e,t)=>{const o=L.get(t,e);if(o)return o.originWords.map(r=>r.text).join(" ")},NH=e=>{const t=eo(e.mediaId);if(!t)throw new C(_.C_MEDIA_LOST,{},"Audio info not found");return{duration:t.videoAudioMetaInfo.duration}},qrt=e=>{const t=Fe();return fm.includes(t)||e.every(o=>fm.includes(o))},Qrt=(e,t)=>e!==we.INSERT_CURSOR||t.length===0||t.some(o=>!fm.includes(o)),cfe=e=>{yG({eventSurveyType:Ss.OVERDUB_FEEDBACK,word_lang:e},Ss.OVERDUB_FEEDBACK)},Zrt=e=>e===ce.Korean?25:100,lfe=async e=>{if(!await Vn("ensureOverdubQuota"))return!1;const t=ba().isPremiumFeatureAvailable(Ut.OVERDUB);return!e&&!t?(Y().openModal(st.NEED_PLAN_UPGRADE,{premiumFeatureType:Ut.OVERDUB}),!1):!0},$rt=()=>{const e=ls("overdub_onboarding_start_menu");return be().getUserInfo()!==void 0&&e===cv.overdub_onboarding_start_menu.B},PH=(e,t,o)=>{const r=oi(e,t,o);return r!==void 0&&x2(r)},bH=(e,t,o)=>{const r=oi(e,t,o);if(!(!r||!x2(r)))return r.overdubId},dfe=(e,t,o)=>{const r=oi(e,t,o);return r&&x2(r)?r:void 0},ent=(e,t,o)=>{if(e.length===0)return null;if(e.length===1){const s=GR(e[0],t,o);return s?{...s,trackId:Rt()}:null}const r=e[0],n=GR(r,t,o);if(!n)return null;const a=fl(e);return mn(n)?{...n,trackId:Rt(),sourceIn:pe(n.sourceIn),sourceOut:pe(n.sourceIn+a)}:{...n,trackId:Rt()}}
1102,PM=.001,ufe=1,pfe=1;class nu{static decode=t=>(!nu.instance&&(nu.instance=new nu),new Promise((o,r)=>{nu.instance.audioCtx.decodeAudioData(t,n=>{o(n)},n=>r(n))}));static instance;audioCtx;constructor(){const t=window.AudioContext||window.webkitAudioContext;this.audioCtx=new t({sampleRate:zx})}}const Rd=nu.decode,zw=(e,t,o,r)=>{if(o>0){const n=Math.round(o*t);for(let a=n;a>=0;a--){const i=e[a]*(a/n);e[a]=i}}if(r>0){const n=Math.round(r*t);for(let a=n;a>=0;a--)e[e.length-a-1]=e[e.length-a-1]*(a/n)}return e},tnt=e=>{if(e.copyFromChannel){const t=new Float32Array(e.length);return e.copyFromChannel(t,0,0),t}return e.getChannelData(0)},ffe=(e,t)=>{if(e.copyToChannel){e.copyToChannel(t,0,0);return}e.getChannelData(0).set(t)},LH=(e,t)=>{if(t.length===0)return null;const o=e.createBuffer(1,t.length,e.sampleRate);ffe(o,t);const r=e.createBufferSource();return r.buffer=o,r},MH=(e,t,o)=>Math.ceil(e*t/o),gfe=(e,t,o,r,n,a)=>e.map((i,s)=>{const x=i.word,c=dfe(x,r,n);if(c){if(!L.get(a,c.overdubId))throw new C(_.C_AUDIO_SAMPLE_MANIPULATION_ERROR);return Afe(i,c,t,o)}const l=oi(x,r,n),d=Math.round(((l?.sourceIn??0)+(s===0?o:0))*t.sampleRate),u=Math.round(((l?.sourceIn??0)+sr(x))*t.sampleRate);return{startIndex:d,endIndex:u,playbackRate:x.playbackRate,volume:l?.volume,mediaId:l?.mediaId,forceMute:Q0(x)}}).reduce((i,s)=>{const x=i[i.length-1];return i.length>0&&x&&x.endIndex===s.startIndex&&x.volume===s.volume&&x.mediaId===s.mediaId&&x.forceMute===s.forceMute&&x.playbackRate===s.playbackRate?(x.endIndex=s.endIndex,i):(i.push(s),i)},[]).filter(i=>i.endIndex-i.startIndex>0),ont=async(e,t,o,r,n,a,i,s,x)=>{const c=h("sample.ts"),l=gfe(o,t,r,i,s,x),d=MH(n,t.sampleRate,a),u=l.reduce((S,R)=>{const y=R.playbackRate*a,v=R.endIndex-R.startIndex,w=y===1?v:mG(v,y);return S+w},0),p=l.reduce((S,R)=>{const y=R.playbackRate*a;return S+Math.ceil(1/y)},0)+1;if(u>d+p)throw c.error("generateRangeBuffer: writeLen exceeds playbackLen beyond expected drift",JSON.stringify({writeLen:u,playbackLen:d,maxExpectedDrift:p})),new C(_.C_AUDIO_SAMPLE_MANIPULATION_ERROR);const f=new Float32Array(Math.max(u,d));let E=0;const T=l.map(async S=>{const{mediaId:R,startIndex:y,endIndex:v,forceMute:w,volume:N}=S,M=S.playbackRate*a;if(!R){E+=Math.floor((v-y)/M);return}const k=e[R];if(!k){const B=Object.keys(e).length;throw c.error("No mediaSample for "+R+", samples len :"+B),new C(_.C_AUDIO_FRAGMENT_LOAD_GENERAL_ERROR)}const F=E,G=k.getSampleSlice(y,v).then(async B=>{const W=w?0:N??ma,Q=B.map(q=>q*W),j=M===1?Q:await xv(t.sampleRate,Q,M),$=zw(j,t.sampleRate,PM,PM);if(F<0)throw c.error("range out of bounds",JSON.stringify({setIndex:F,decaySampleLen:$.length,totalSampleLen:f.length})),new C(_.C_AUDIO_SAMPLE_MANIPULATION_ERROR);f.set($,F)});return E+=Math.floor((v-y)/M),G});await Promise.all(T);const O=f.slice(0,d);return LH(t,O)},rnt=async(e,t,o,r,n,a,i)=>{const s=h("sample.ts"),x={};let c=0,l=!0;if(o.forEach(f=>{const{playTargetSubMediaTracks:E,word:T}=f;E.forEach(O=>{const{mediaId:S,assetId:R,startTime:y,duration:v,fadeInDuration:w,fadeOutDuration:N}=O;l=!1;const M=L.get(i,R),k=M?.trackIds.map(G=>L.get(a,G)).filter(Se).find(cd),F=k?.volume??1;if(x[R]){const G=x[R];G.endTime=Math.max(y+v,G.endTime),G.fadeOutDuration=Math.max(N,G.fadeOutDuration)}else x[R]={frontOffset:c,startTime:y,endTime:y+v,volume:F,mediaId:S,fadeInDuration:w,fadeOutDuration:N}}),c=c+Rn(T)}),l)return null;const d=new Float32Array(MH(r,t.sampleRate,n));d.fill(0);const u=Object.entries(x).map(async([f,E])=>{const{frontOffset:T,startTime:O,endTime:S,mediaId:R,volume:y,fadeInDuration:v,fadeOutDuration:w}=E,N=e[R];if(!N){s.error("[GenerateMediaBufferError] Sample is not currectly set in player for media:"+R+". ");return}const M=L.get(i,f),k=M?.trackIds.map(ne=>L.get(a,ne)).find(ne=>ne!==void 0&&cd(ne));if(!k){s.error("[GenerateMediaBufferError] audioTrack is not found for assetId:"+f+". ");return}const F=eo(R);if(!F){s.error("[GenerateMediaBufferError] audioInfo is not found for mediaId:"+R+". ");return}const{sourceIn:G,sourceOut:B,loop:W}=k,Q=$t(B,G,F.videoAudioMetaInfo.duration);if(Q===G)return;const j=W?Nfe(O,S,G,Q):[Pfe(O,S,G,Q)],$=j.map(({startTime:ne,endTime:oe})=>[Math.round(ne*t.sampleRate),Math.round(oe*t.sampleRate)]).map(([ne,oe])=>N.getSampleSlice(ne,oe)),q=await Promise.all($),H=$N(q);let U=n===1?H:await xv(t.sampleRate,H,n);(v>0||w>0)&&(U=zw(U,t.sampleRate,v,w));const te=Math.round(T*t.sampleRate);for(let ne=0;ne<U.length;ne++)d[te+ne]+=U[ne]*y});return await Promise.all(u),LH(t,d)},DH=e=>{const t=Int16Array.from(e.getChannelData(0),x=>{const c=x<0?x*32768:x*32767;return Math.max(-32768,Math.min(32768,c))}),o=1,{sampleRate:r}=e,n=128,a=new b9.Mp3Encoder(o,r,n),i=[];let s=a.encodeBuffer(t);return i.push(s),s=a.flush(),s.length>0&&i.push(s),i},Jg=(e,t)=>{if(t){const o=_fe(Object.assign({}
1102,t)),r=new Uint8Array(o.length+e.byteLength);return r.set(o,0),r.set(new Uint8Array(e),o.length),r}else{const o=new Uint8Array(e.byteLength);return o.set(new Uint8Array(e),0),o}},kH=e=>{const t=new Int16Array(e.length);for(let o=0;o<e.length;o++){const r=e[o],n=$t(r,-1,1);t[o]=n*32767}return t};function _fe(e){const t=e.numFrames,o=e.numChannels||2,r=e.sampleRate||zx,n=e.isFloat?4:2,a=e.isFloat?3:1,i=o*n,s=r*i,x=t*i,c=new ArrayBuffer(44),l=new DataView(c);let d=0;function u(E){for(let T=0;T<E.length;T++)l.setUint8(d+T,E.charCodeAt(T));d+=E.length}function p(E){l.setUint32(d,E,!0),d+=4}function f(E){l.setUint16(d,E,!0),d+=2}return u("RIFF"),p(x+36),u("WAVE"),u("fmt "),p(16),f(a),f(o),p(r),p(s),f(i),f(n*8),u("data"),p(x),new Uint8Array(c)}const bM=async e=>await fetch(e).then(o=>o.blob()).then(o=>o.slice(0,o.size,"audio/mp4")).catch(o=>{throw new C(_.C_LOCAL_FILE_FETCH_FAILED,{},o.message)}),Efe=async(e,t)=>Promise.all([e,...t].map(o=>fetch(o).then(r=>r.blob()).then(r=>r.slice(0,r.size,"audio/mp4")))).catch(o=>{throw new C(_.C_LOCAL_FILE_FETCH_FAILED,{},o.message)}),nnt=async(e,t=!1,o=!1)=>{if(!Oo())throw new C(_.C_LOGIC_ERROR);const r=qt(),n=await r.getMediaFileInfo(e);if(n.audioInfo===void 0)return{audioBlob:null,audioChunks:[],mediaFileInfo:n,codec:null};const a=Eo(Gt).getKeyOrDefault(n.audioInfo.codec);if(!a)throw new C(_.C_LOGIC_ERROR);if(n.duration>A1)throw await mfe(e,n.duration),new C(_.C_UPLOAD_USER_CANCELED);const i=[],s=await r.getMediaFileStartTimes(e),x=s?.audio!==void 0&&s.audio!==s.container;if(x){const c=s.audio-s.container;h("sample.ts").info("normalize start time while extracting. audio offset: "+c+"ms"),c1e({audioOffsetMS:c,durationSec:n.duration})}try{const{path:c,tempfile:l,codec:d}=await r.extractAudio(e,Gt[a],o,x);i.push(l);const u=an(c);if(dg.test(u))throw h("sample.ts").error("trying to load shared folder path "+u),new C(_.C_IMPORT_SHARED_FOLDER_READ);if(t){const S=await bM(u);return{audioBlob:S,mediaFileInfo:n,audioChunks:[S],codec:d}}const{numChunks:p,chunkDuration:f}=FH(n.duration);if(p===1){const S=await bM(u);return{audioBlob:S,mediaFileInfo:n,audioChunks:[S],codec:d}}const E=await Promise.all(x0(0,p).map(S=>r.sliceAudio(l||c,d,S*f,f).then(({path:R,tempfile:y})=>(i.push(y),an(R))))),[T,...O]=await Efe(u,E);return{audioBlob:T,mediaFileInfo:n,audioChunks:O,codec:d}}finally{i.forEach(c=>r.clearExtractedAudioTempFile(c))}},FH=e=>{const t=Math.ceil(e/lZ),o=e/t;return{numChunks:t,chunkDuration:o}},mfe=async(e,t)=>Oo()&&e&&t>A1?(oFe(t),w_e(e,t),!0):!1,ant=async(e,t,o,r=!1,n=!1)=>{const a=Ht(So.AUDIO_TEMP),i=await ix(a),s=await i.getMediaFileInfo(t);if(s.audioInfo===void 0)return{audioBlob:null,audioChunks:[],codec:null};const x=Eo(Gt).getKeyOrDefault(s.audioInfo.codec);if(!x)throw new C(_.C_LOGIC_ERROR);try{const c=s.videoInfo===void 0,l=Gt[x]===Gt.PCM,d=c||e!==null&&ry.test(e);let u,p;if(l){const O=n?s.audioInfo.channelCount:void 0;u=await i.convertToMP3(t,O??dZ,uZ,o),p=Gt.MP3}else if(d)u=t,p=Gt[x];else{const O=await i.extractAudio(t,Gt[x],o);u=O.blob,p=O.codec}if(!u)return{audioBlob:null,audioChunks:[],codec:null};if(r)return{audioBlob:u,audioChunks:[u],codec:p};const{numChunks:f,chunkDuration:E}=FH(s.duration);if(f===1)return{audioBlob:u,audioChunks:[u],codec:p};const T=await Promise.all(x0(0,f).map(O=>i.sliceAudio(u,p,O*E,E)));return{audioBlob:u,audioChunks:T,codec:p}}catch(c){throw h("sample.ts").error("Failed to extract audio data from blob: "+P(c)),c}},hfe=(e,t,o)=>Bt(zt(UH(e)).pipe(St(Rd),St(Tfe(t)),St(Ife(o)),At(DH),At(VH))),UH=e=>e.arrayBuffer(),Ife=e=>async t=>{if(e===1)return t;const o=new OfflineAudioContext(t.numberOfChannels,t.length,t.sampleRate),r=[];for(let a=0;a<t.numberOfChannels;a++){const i=t.getChannelData(a),s=await xv(t.sampleRate,i,e,ufe,pfe);r.push(s)}const n=o.createBuffer(t.numberOfChannels,r[0].length,t.sampleRate);for(let a=0;a<r.length;a++)n.copyToChannel(r[a],a);return n},Tfe=e=>async t=>{if(e===1)return t;const o=new OfflineAudioContext(t.numberOfChannels,t.length,t.sampleRate),r=o.createBufferSource();r.buffer=Sfe(e,t);const n=o.createGain();return n.gain.value=e,r.connect(n),n.connect(o.destination),r.start(0),await o.startRendering()},VH=e=>new Blob(e,{type:"audio/mpeg"}),Sfe=(e,t)=>
1102{if(e<1)return t;for(let o=0;o<t.numberOfChannels;o++){const r=t.getChannelData(o);for(let n=0;n<r.length;n++)Math.abs(r[n])*e>1&&(r[n]=Math.sign(r[n])/e)}return t},Ofe=(e,t)=>Bt(zt(UH(e)).pipe(St(Rd),St(Rfe(t)),At(DH),At(VH),c0(o=>(h("sample.ts").error("Failed to apply room effect... "+P(o)),Promise.resolve(e)))));let Z_;const bO=()=>(Z_===void 0&&(Z_=new Map),Z_),Cfe=async e=>{if(bO().has(e))return bO().get(e);const t=await qo("/room-effect",{method:"POST",body:JSON.stringify({type:e})}).then(n=>me(n,_.C_TTS_NETWORK_ERROR));if(t.result==="error"){h("sample.ts").error("Failed to load impulse response from stock server. type: "+e+". msg: "+t.msg);return}const o=t.url,r=await fetch(o).then(n=>n.arrayBuffer()).then(n=>Rd(n));return bO().set(e,r),r},Rfe=e=>async t=>{const o=await Cfe(e);if(o===void 0)return t;const r=new OfflineAudioContext(t.numberOfChannels,t.length,zx),n=r.createConvolver();n.buffer=o;const a=r.createBufferSource();return a.buffer=t,a.connect(n),n.connect(r.destination),a.start(0),await r.startRendering()},Afe=(e,t,o,r)=>{const n=e.word,a=NH(t),i=vH(a.duration,sr(n)),s=a.duration,x=r===0?0:Math.round(r*o.sampleRate*i),c=Math.round(s*o.sampleRate);return{startIndex:x,endIndex:c,playbackRate:i*n.playbackRate,mediaId:t.mediaId,volume:t.volume,forceMute:Q0(n)}},yfe=e=>{switch(e){case Gt.AAC:return"audio/mp4";case Gt.MP3:return"audio/mp3";case Gt.OPUS:case Gt.VORBIS:return"audio/webm";case Gt.FLAC:return"audio/flac";case Gt.PCM:return"audio/wav";default:return"audio/mp3"}},Yw=async e=>(await Rd(await e.arrayBuffer())).duration,int=(e,t)=>e.every(o=>t(o.element)),ZR=(e,t)=>{const o=e.videoAudioMetaInfo.duration,r=$t(t.sourceIn,0,o);return $t(t.sourceOut,r,o)-r},vfe=(e,t,o,r,n)=>{const a=r-o,i=t-e,s=Math.min(n+i,r),x={startTime:n,endTime:s},c=s-n,l=i-c;if(l<=0)return[x];const d=Math.floor(l/a),u=Array.from({length:d},()=>({startTime:o,endTime:r})),p=o+t%a,f={startTime:o,endTime:p};return[x,...u,f]},wfe=(e,t,o)=>t+e%(o-t),Nfe=(e,t,o,r)=>{const n=wfe(e,o,r);return vfe(e,t,o,r,n)},Pfe=(e,t,o,r)=>({startTime:o+e,endTime:Math.min(o+t,r)});var bfe=(e=>(e.LOW="low",e.REGULAR="regular",e.HIGH="high",e))(bfe||{}),GH=(e=>(e.TRANSITION="transition",e))(GH||{}),Lfe=(e=>(e.THUMBNAIL="thumbnail",e.IMAGE="image",e.IMAGE_GIF="image_gif",e.VIDEO_ONLY="video_only",e.VIDEO_AUDIO="video_audio",e.AUDIO_ONLY="audio_only",e))(Lfe||{}),Mfe=(e=>(e.VIDEO="video",e.AUDIO="audio",e.IMAGE="image",e))(Mfe||{}),Dfe=(e=>(e.ERROR="ERROR",e.CANCELLED="CANCELLED",e.SUCCESS="SUCCESS",e))(Dfe||{}),kfe=(e=>(e.USER_CANCEL="USER_CANCEL",e.DURATION_ZERO="DURATION_ZERO",e))(kfe||{});const Ffe=23.976,Ufe=29.97,Vfe=59.94,Gfe=.1,WH=e=>"square",Wfe=(e,t)=>{const o={[ce.Korean]:"MalgunGothicBold",[ce.English]:"SegoeUI-Bold",[ce.Japanese]:"YuGothic-Bold",[ce.Spanish]:"SegoeUI-Bold",[ce.Taiwanese]:"NotoSansTC-Bold"},r={[ce.Korean]:"AppleSDGothicNeo-Regular",[ce.English]:"LucidaGrande-Bold",[ce.Japanese]:"HiraginoSans-W6",[ce.Spanish]:"LucidaGrande-Bold",[ce.Taiwanese]:"NotoSansTC-Bold"};return t?r[e]||r[_f]:o[e]||o[_f]},Hfe=(e,t,o,r)=>{if(!hv(e,t)){const a=nW(e,t);if(a&&a.weight===t)return a.psName}return Wfe(r,o)},jfe=e=>e.width*9===e.height*16,zfe=(e,t,o,r,n,a,i,s)=>{const x=gt(s),c={"@id":x,name:x,pathurl:s,media:{video:{samplecharacteristics:{width:o.width,height:o.height,anamorphic:jfe(o),pixelaspectratio:WH(),fielddominance:"none"}},audio:{in:0,out:r,channelcount:2,duration:r}}};return e.filter(d=>d.visualMedia!==void 0).map((d,u)=>{const{start:p,end:f}=d.visualMedia,E=d.timelineStart,T=d.timelineStart+d.timelineDuration,O=d.visualMedia.mediaId===d.audioMedia?.mediaId,S=[{mediatype:"video",trackindex:t+1,clipindex:u+1}];return O&&S.push({mediatype:"audio",trackindex:t*2+1,clipindex:u+1,groupindex:u+1},{mediatype:"audio",trackindex:t*2+2,clipindex:u+1,groupindex:u+1}),{name:x,enabled:!0,rate:{timebase:n,ntsc:a},in:p*i,out:f*i,start:E*i,end:T*i,file:c,link:S}})},HH=(e,t)=>{const o=Hs(e),r=Hs(t);return o?r?o.videoAudioMetaInfo.videoInfo===void 0?1:r.videoAudioMetaInfo.videoInfo===void 0||e<t?-1:1:-1:1},Yfe=(e,t,o,r,n,a)=>Object.keys(e).sort(HH).map((s,x)=>{const c=Hs(s),l=c?.fileLocation===D.LOCAL||c?.fileLocation===D.LOCAL_TMP?c.path:"",d=e[s];return{clipitem:c!==void 0&&c.videoAudioMetaInfo.videoInfo===void 0?[]:zfe(d,x,t,o,r,n,a,l)}}).filter(s=>s.clipitem&&s.clipitem.length>0),Bfe=e=>e.reduce((t,o)=>{const r=o.timelineDuration;if(t.length===0)return[{...o,pieceTimelineInProject:0,timelineDuration:r}];const n=t[t.length-1],a=n.pieceTimelineInProject+n.timelineDuration;if(n.clipIndex===o.clipIndex){const i={...n,timelineDuration:n.timelineDuration+r};return t.pop(),t.push(i),t}return t.push({...o,pieceTimelineInProject:a,timelineDuration:r}),t},[]),Kfe=(e,t,o)=>[{parameterid:"part1",name:"Text Settings",value:""},{parameterid:"str",name:"Text",value:{"#raw":e||""}},{parameterid:"font",name:"Font",value:o},{parameterid:"style",name:"Style",valuemin:1,valuemax:1,valuelist:{valueentry:[{name:"Regular",value:"1"}]},value:1},{parameterid:"align",name:"Alignment",valuemin:1,valuemax:3,valuelist:{valueentry:[{name:"Left",value:"1"},{name:"Center",value:"2"},{name:"Right",value:"3"}]},value:"2"},{parameterid:"size",name:"Size",valuemin:0,valuemax:200,value:24}
1102,{parameterid:"track",name:"Tracking",valuemin:0,valuemax:100,value:1},{parameterid:"lead",name:"Leading",valuemin:-100,valuemax:100,value:0},{parameterid:"aspect",name:"Aspect",valuemin:0,valuemax:4,value:1},{parameterid:"linewidth",name:"Line Width",valuemin:0,valuemax:200,value:2},{parameterid:"linesoft",name:"Line Softness",valuemin:0,valuemax:100,value:5},{parameterid:"textopacity",name:"Text Opacity",valuemin:0,valuemax:100,value:100},{parameterid:"center",name:"Center",value:{horiz:0,vert:t}},{parameterid:"textcolor",name:"Text Color",value:{alpha:255,red:255,green:255,blue:255}},{parameterid:"supertext",name:"Text Graphic"},{parameterid:"linecolor",name:"Line Color",value:{alpha:255,red:0,green:0,blue:0}},{parameterid:"superline",name:"Line Graphic"},{parameterid:"part2",name:"Background Settings",value:void 0},{parameterid:"xscale",name:"Horizontal Size",valuemin:0,valuemax:200,value:0},{parameterid:"yscale",name:"Vertical Size",valuemin:0,valuemax:200,value:0},{parameterid:"xoffset",name:"Horizontal Offset",valuemin:-100,valuemax:100,value:0},{parameterid:"yoffset",name:"Vertical Offset",valuemin:-100,valuemax:100,value:0},{parameterid:"backsoft",name:"Back Soft",valuemin:0,valuemax:100,value:0},{parameterid:"backopacity",name:"Back Opacity",valuemin:0,valuemax:100,value:50},{parameterid:"backcolor",name:"Back Color",value:{alpha:255,red:255,green:255,blue:255}},{parameterid:"superback",name:"Back Graphic"},{parameterid:"crop",name:"Crop",value:!1},{parameterid:"autokern",name:"Auto Kerning",value:!0}],LM=(e,t,o,r,n,a,i,s)=>Bfe(e).filter(l=>l.captions).map(l=>{const d=a,u=i,p=l.captions.length===0?null:s?l.captions[0]:l.captions[1];if(!p)return;const f="Outline Text"+(s?1:2),E=l.pieceTimelineInProject,T=E+l.timelineDuration;return{"@id":f,name:p,duration:t,rate:{timebase:o,ntsc:r},start:E*n,end:T*n,in:E*n,out:T*n,enabled:!0,anamorphic:!1,alphatype:"black",masterclipid:f,effect:{name:"Outline Text",effectid:"Outline Text",effectcategory:"Text",effecttype:"generator",mediatype:"video",parameter:Kfe(p,d,u)},sourcetrack:{mediatype:"video"}}}).filter(Se),Xfe=(e,t,o,r,n,a,i)=>{const s=gt(a);let x=!0;const c=e.filter(p=>p.audioMedia!==void 0),l=(p,f,E)=>{const T=n&&x?{"@id":s,name:s,pathurl:a,rate:{timebase:t,ntsc:o},media:{audio:{in:0,out:i,channelcount:2,duration:i}}}:void 0;x=!1;const{start:O,end:S}=p.audioMedia;return{name:s,enabled:!0,in:O*r,out:S*r,start:f*r,end:(f+p.timelineDuration)*r,file:T||{"@id":s},sourcetrack:{mediatype:"audio",trackindex:E}}},d=c.map(p=>l(p,p.timelineStart,1)),u=c.map(p=>l(p,p.timelineStart,2));return{left:d,right:u}},Jfe=(e,t,o,r,n)=>Object.keys(e).sort(HH).map(i=>{const s=Hs(i),x=s?.fileLocation===D.LOCAL||s?.fileLocation===D.LOCAL_TMP?s.path:"",c=s!==void 0&&s.videoAudioMetaInfo.videoInfo===void 0,l=e[i],d=Xfe(l,t,o,r,c,x,n),u={clipitem:d.left},p={clipitem:d.right};return[u,p]}).flat(),GE=e=>e.pieceTimelineInProject+e.timelineDuration,qfe=(e,t)=>{const o=t-GE(e),r=o*e.playbackRate;return{...e,timelineDuration:e.timelineDuration+o,visualMedia:e.visualMedia?{...e.visualMedia,end:e.visualMedia.end+r}:void 0,audioMedia:e.audioMedia?{...e.audioMedia,end:e.audioMedia.end+r}:void 0}},Qfe=(e,t)=>{const o=e.pieceTimelineInProject-t,r=o*e.playbackRate;return{...e,pieceTimelineInProject:t,timelineDuration:e.timelineDuration+o,visualMedia:e.visualMedia?{...e.visualMedia,start:e.visualMedia.start-r}:void 0,audioMedia:e.audioMedia?{...e.audioMedia,start:e.audioMedia.start-r}:void 0}},Zfe=(e,t)=>{const o=1/e,r=[],n=t.length;for(let a=0;a<n;++a){const i=t[a];if(i.timelineDuration>=o){r.push(i);continue}const s=r[r.length-1];if(s!==void 0&&Math.abs(GE(s)-i.pieceTimelineInProject)<b0){r.pop(),r.push(qfe(s,GE(i)));continue}const c=t[a+1];if(c!==void 0&&Math.abs(GE(i)-c.pieceTimelineInProject)<b0){r.push(Qfe(c,i.pieceTimelineInProject)),++a;continue}}return r},$fe=(e,t,o,r,n,a,i,s,x,c,l)=>{const d=Yfe(t,o,i,r,n,a),u=e.some(R=>R.captions&&R.captions.length>0&&R.captions[Ke.ORIGINAL]!==""),p=e.some(R=>R.captions&&R.captions.length>1&&R.captions[Ke.TRANSLATE]!==""),f=u&&p?-.05:0,E=u&&p?Gfe/2:0,T=u?{generatoritem:LM(e,i,r,n,a,s+f,x,!0)}:null,O=p?{generatoritem:LM(e,i,r,n,a,s+E,x,!1)}:null,S=[];return S.push(...d),T&&S.push(T),O&&S.push(O),S},ege=e=>{const t=[Ffe,Ufe,Vfe];for(const o of t)if(Math.abs(e-o)<b0)return!0;return!1},jH=e=>{const o=e.map(r=>{const n=Hs(r)??Yu(r);if(!n)return h("fcp.ts").error("No sourceFileInfo for "+r),void 0;if(n.videoAudioMetaInfo.videoInfo)return n.videoAudioMetaInfo.videoInfo.frameRate}).filter(Se).filter((r,n,a)=>a.indexOf(r)===n);return o.length===1?o[0]:60},zH=(e,t,o,r,n,a)=>{const i="&#13;",s=WI(e,t,{},{},{},Kl.WITH_CAPTION,o,n,a),x=r===Py.WITHOUT_LINE_BREAK?" ":i;return s.map(l=>{const d=l.captions.length===0?l.captions:l.captions.map(u=>u.replace(/&/gm,"&").replace(/</gm,"<").replace(/>/gm,">").replace(/\u2028/gm," ").split(`
1103`).map(p=>p.replace(/ /gm,"&")).map(p=>p.trim()).map(p=>p.replace(/&/gm," ")).join(x));return{...l,captions:d}})},tge=(e,t,o,r,n,a,i,s,x,c,l,d)=>{const u=zH(e,t,n,x,l,d),{mediaIds:p}=HI(u),f=c??jH(p),E=ege(f),T=E?Math.round(f):f;h("fcp.ts").info("Exporting premiere xml with "+T+"fps, (selectedFPS: "+c+"), ntsc: "+E+", fontFamily: "+i+", fontWeight: "+s);const O=o*f,S=Zfe(T,u),R=se().getInitProjectVideoSize(),y=c2e(a),v=Hfe(i,s,r,n),w={width:R.width>0?R.width:om.width,height:R.height>0?R.height:om.height,anamorphic:!1,pixelaspectratio:WH(),fielddominance:"none"},N={in:0,out:O,channelcount:2,duration:O},M={},k={};let F=0;
1103S.forEach($=>{const q={...$,timelineStart:F};F+=$.timelineDuration;const H=$.visualMedia?.mediaId,U=$.audioMedia?.mediaId;if(H){const te=M[H];te?te.push(q):M[H]=[q]}if(U){const te=k[U];te?te.push(q):k[U]=[q]}});const G=$fe(S,M,R,T,E,f,O,y,v),B=Jfe(k,T,E,f,O),W=gt(se().getCurrentProjectPath()),Q={xmeml:{"@version":"5",sequence:{"@id":"video",name:W.replace(bi(Ed),"").replace(bh,""),duration:O,rate:{timebase:T,ntsc:E},media:{video:{format:{samplecharacteristics:w},track:G},audio:{...N,track:B}}}}};return qU.create(Q,{version:"1.0",encoding:"utf-8",invalidCharReplacement:""}).end({pretty:!0})},{getExportOptions:snt,getEncodeClipsFromExportRange:xT,getTargetClipsFromExportRange:YH}=(()=>{let e;(l=>{l.AllowDiscontinuous="allow-discontinuous",l.DisallowDiscontinuous="disallow-discontinuous"})(e||(e={}));let t="allow-discontinuous",o=!1;function r(l){const d=l[0];d==="allow-discontinuous"||d==="disallow-discontinuous"?t=d:d==="0"?t="allow-discontinuous":d==="1"&&(t="disallow-discontinuous")}function n(){if(o)return;o=!0,Mo().on(Xt.EXPORT_BEHAVIOR,r)}const a=(l,d)=>{const u=Ve().getBool(Ie.MULTISOURCE_USED),p=u?[Vo.ALL_CLIPS,Vo.SCENE_CLIPS,Vo.SELECTED_CLIPS]:[Vo.ALL_CLIPS,Vo.SELECTED_CLIPS],f=p.map(T=>T!==Vo.SELECTED_CLIPS?A("choose_export_options.range_"+T.toLowerCase()):A("choose_export_options.range_"+T.toLowerCase(),{selectedClips:d>0?d:A("choose_export_options.no_clips"),clipUnit:d>0?A("choose_export_options.clip_unit"):""})),E=[u&&l?[Vo.SCENE_CLIPS]:[],d===0?[Vo.SELECTED_CLIPS]:[]].flat();return{optionValues:p,optionLabels:f,disabledValues:E}},i=(l,d,u)=>{const p=Ve().getBool(Ie.MULTISOURCE_USED),f=p?[Vo.ALL_CLIPS,Vo.SCENE_CLIPS,Vo.SELECTED_CLIPS]:[Vo.ALL_CLIPS,Vo.SELECTED_CLIPS],E=f.map(O=>O!==Vo.SELECTED_CLIPS?A("choose_export_options.range_"+O.toLowerCase()):A("choose_export_options.range_"+O.toLowerCase(),{selectedClips:d>0?d:A("choose_export_options.no_clips"),clipUnit:d>0?A("choose_export_options.clip_unit"):""})),T=[p&&l?[Vo.SCENE_CLIPS]:[],d===0||!u?[Vo.SELECTED_CLIPS]:[]].flat();return{optionValues:f,optionLabels:E,disabledValues:T}};return{getExportOptions:(l,d,u)=>(!o&&n(),(p=>{switch(p){case"allow-discontinuous":return a;case"disallow-discontinuous":return i}})(t)(l,d,u)),getEncodeClipsFromExportRange:(l,d)=>{!o&&n();const u=Do(l),p=mo(l),f=BL(l)!==null,E=Fxe(l),T=Gv(l);if(E===void 0||T===null)throw new C(_.C_EXPORT_GENERAL_ERROR);const O=ns(E,T);switch(d){case Vo.ALL_CLIPS:return{encodeClips:Nc(p).map((S,R)=>({...S,clipIndex:R}))};case Vo.SCENE_CLIPS:return{encodeClips:u.map((S,R)=>({...S,clipIndex:R}))};case Vo.SELECTED_CLIPS:{const S=Nn(l);return S.size===0?{encodeClips:Nc(p).map((R,y)=>({...R,clipIndex:y}))}:!f&&t==="disallow-discontinuous"?(h("export.ts").error(`Attempted to export discontinuous selection while it is forbidden.
1104For now, all clips are exported instead.`),{encodeClips:Nc(p).map((R,y)=>({...R,clipIndex:y}))}):{encodeClips:Nc(p).map((R,y)=>({...R,clipIndex:y})).filter((R,y)=>S.has(y))}}case Vo.CURRENT_POSITION_WORD:{const S=O===E.words.length-1?E.words[O-1]:E.words[O];return{encodeClips:[E],targetWordId:S.id}}}},getTargetClipsFromExportRange:(l,d)=>{!o&&n();const u=l(),p=Z0(u),f=BL(u)!==null;switch(d){case Vo.ALL_CLIPS:return so.ALL;case Vo.SCENE_CLIPS:return so.SCENE_SCELECTED;case Vo.SELECTED_CLIPS:return p.size===0?so.ALL:!f&&t==="disallow-discontinuous"?so.ALL:so.SELECTED;case Vo.CURRENT_POSITION_WORD:return so.WORD}}}})(),xnt=async(e,t,o,r,n,a,i=Py.WITHOUT_LINE_BREAK,s,x)=>{const l=Nc(e);if(r===gi.PREMIERE){const f=zH(l,t,on(o),i,n,a),{mediaIds:E}=HI(f);return jH(E)}const d=new Li(void 0,void 0,s,x).collectFrom({type:Or.SCENE,model:e}).build().getUsedSourceMediaIds(),u=ca().find(f=>d.has(f.mediaId)&&!ia(f.mediaId));if(!u)return h("export.ts").warn("No active source info found. Using default frame rate."),30;if(u.fileLocation!==D.LOCAL&&u.fileLocation!==D.LOCAL_TMP)return h("export.ts").warn("Active source info is not local. Using default frame rate."),30;const p=await L3(u.path);return p.numerator/p.denominator},BH=(e,t,o,r,n)=>{const i={},s={},x={},c=(p,f)=>{s[p]=f},l=p=>s[p],d=(p,f)=>p!==void 0&&f-p>.1;let u=0;return e.forEach(p=>{const{assetIds:f,id:E}=p,T=vo(p),O=hl(p),S=O-T;let R=u;f.forEach(y=>{const v=L.get(o,y);if(!v)return;if(v.role!=="sub"){h("export.ts").warn("Clip has main asset: "+y);return}const w=v.trackIds.map(ne=>L.get(t,ne)).find(ne=>ne!==void 0&&cd(ne));if(!w)return;const{timelineStart:N,timelineEnd:M}=r[y],k=T-N,F=M-N,G=eo(w.mediaId,{excludeBroken:!0});if(!G){h("export.ts").warn(`
1105          [Error occured in prepare exporting assets (getAdditionalMediaTrackInfo)]
1106          There is audio track, but there is no audioInfo.
1107          trackEntries : `+JSON.stringify(t)+`
1108          assetEntries : `+JSON.stringify(o)+`
1109          assetId : `+y+`
1110        `);const ne=Yg(E);throw new C(_.C_MEDIAINFO_NOT_EXIST,{absoluteClipIndex:ne},"audioInfo is undefined in AudioFileInfoManager.getAudioInfo")}const B=ZR(G,w),W=w.sourceIn,Q=w.volume,j=w.fade?.in===!0,$=w.fade?.out===!0,q=w.loop?Math.ceil(F/B):0,H=T-N,U=w.loop?F-H:B-H;if(U<=0)return;const te=Math.min(U,S);if(i[y]){const ne=x[y],oe=ne?i[ne]:i[y],re=l(y);if(d(re,T)){h("export.ts").info("bgm is not continous: current clip timeline Time:"+T+", last bgm inserted clip's end time:"+re);const fe=qe.v4();i[fe]={resultTimelineTime:R,duration:te,startOffset:W,trimmedDuration:B,mediaStart:k,volume:Q,fadeIn:j,fadeOut:$,mediaId:w.mediaId,numLoop:q},x[y]=fe}else oe&&(oe.duration=ue(oe.duration+te,2))}else i[y]={resultTimelineTime:R,duration:te,startOffset:W,trimmedDuration:B,mediaStart:k,volume:Q,fadeIn:j,fadeOut:$,mediaId:w.mediaId,numLoop:q};c(y,O)}),p.words.forEach(y=>{const v=Rn(y),w=y.timelineStart;for(const N in n){const M=Je(N),{timelineStart:k,timelineEnd:F,mediaId:G}=n[M],B=eo(G,{excludeBroken:!0});if(!B){h("export.ts").warn(`
1111            There is mediaId: `+G+`. but there is no audioInfo.
1112          `);continue}const W=L.get(o,M);if(!W)return;if(W.role!=="sub"){h("export.ts").warn("SoundEffect cannot be main asset: "+M);return}const Q=W.trackIds.map(re=>L.get(t,re)).find(re=>re!==void 0&&cd(re)),j=Q?.sourceIn??0,$=Q?ZR(B,Q):0,q=w-k,H=$7(w,w+v,k,F,!1),U=Q?.volume??1,te=Q?.fade?.in===!0,ne=Q?.fade?.out===!0,oe=1;if(H){const re=H?H[1]-H[0]:S;if(!i[M])i[M]={resultTimelineTime:R,duration:re,startOffset:j,trimmedDuration:$,mediaStart:q,volume:U,fadeIn:te,fadeOut:ne,mediaId:G,numLoop:oe};else{const ge=i[M],{duration:fe,mediaStart:ve}=ge,yt=ve+fe;if(q-yt>.1){const We=qe.v4();i[We]={resultTimelineTime:R,duration:fe,startOffset:j,trimmedDuration:$,mediaStart:q,volume:U,fadeIn:te,fadeOut:ne,mediaId:G,numLoop:oe}}else ge.duration+=re}}}R=ue(R+v,2)}),u=ue(u+cs(p),2)}),h("export.ts").info("additional media track map for bgm and sound effect generated:"+JSON.stringify(i,void 0,4)),i},MM=(e,t,o)=>{const r={};return o.forEach(n=>{const a=L.get(t,n);if(!a||a.role!=="sub")return;const i=a.trackIds.map(c=>L.get(e,c)).filter(Se),s=i.find(c=>mn(c));if(!s)return;const x=i.find(c=>U0(c));x&&L.set(r,n,{video:s,audio:x})}),r},DM=(e,t,o,r)=>r===0||e.endBehavior===Fs.FREEZE?1:Math.ceil((t+o)/r),KH=(e,t,o,r)=>{const a={};let i=0;return e.forEach(s=>{let x=i;const c=Df(s),l=vo(s),d=MM(t,o,s.assetIds);Object.keys(d).forEach(u=>{const p=Je(u),{video:f,audio:E}=d[p],{mediaId:T,sourceIn:O,volume:S}=E,{timelineStart:R,timelineEnd:y}=r[p],v=l-R,w=y-R,N=eo(T);if(!N||Ym(N.videoAudioMetaInfo))return;const M=N.videoAudioMetaInfo.duration,k=DM(f,O,w,M),F=!1,G=!1,B=M-O;if(a[p]){const W=a[p],{duration:Q,mediaStart:j,volume:$}=W,q=j+Q;if(v-q>.1){const U=qe.v4();a[U]={resultTimelineTime:x,duration:c,startOffset:O,trimmedDuration:B,mediaStart:v,volume:$,fadeIn:F,fadeOut:G,mediaId:T,numLoop:k}}else W.duration+=c}else a[p]={resultTimelineTime:x,duration:c,startOffset:O,trimmedDuration:B,mediaStart:v,volume:S,fadeIn:F,fadeOut:G,mediaId:T,numLoop:k}}),s.words.forEach(u=>{const{assetIds:p,timelineStart:f}=u,E=Rn(u),T=MM(t,o,p);Object.keys(T).forEach(O=>{const S=Je(O),{video:R,audio:y}=T[S],{mediaId:v,sourceIn:w,volume:N}=y,{timelineStart:M,timelineEnd:k}=r[S],F=f-M,G=k-M,B=eo(v);if(!B||Ym(B.videoAudioMetaInfo))return;const W=B.videoAudioMetaInfo.duration,Q=W-w,j=DM(R,w,G,W),$=!1,q=!1;if(a[S]){const H=a[S],{duration:U,mediaStart:te,volume:ne}=H,oe=te+U;if(F-oe>.1){const ge=qe.v4();a[ge]={resultTimelineTime:x,duration:E,startOffset:w,trimmedDuration:Q,mediaStart:F,volume:ne,fadeIn:$,fadeOut:q,mediaId:v,numLoop:j}}else H.duration+=E}else a[S]={resultTimelineTime:x,duration:E,startOffset:w,trimmedDuration:Q,mediaStart:F,volume:N,fadeIn:$,fadeOut:q,mediaId:v,numLoop:j}}),x+=E}),i=ue(i+cs(s),2)}),a},oge=(e,t)=>(e.playbackRate===1||Du(e.playbackRate))&&e.exportAssets.some(o=>o.type===Ce.VIDEO||o.type===Ce.SIMPLE_CHARACTER)===!1&&t===!1,cnt=e=>{po(ke.EXPORT_TYPE,e)},rge=e=>e.type===Ce.SIMPLE_CHARACTER&&e.asset.isMouthApplied&&e.isVoiceWord===!0,Ad=()=>{const e=na.local().toFormat("MMdd-HHmm"),t=sl(8);return"export_"+e+"_"+t},nge=e=>{try{const t={exportId:e.exportId,type:e.type,quality:e.quality,captionSetting:e.captionSetting,
1112size:e.size,hwAccel:e.hwAccel,videoFrameRate:e.videoFrameRate,videoRatio:e.videoRatio,audioSampleRate:e.audioSampleRate,filterAppliedClipCount:e.filterAppliedClipCount,exportByClip:e.exportByClip,mediaTrackMap:Object.keys(e.mediaTrackMap??{}).length,assetTimelineRanges:Object.keys(e.assetTimelineRanges??{}).length};return JSON.stringify(t,void 0,2)}catch(t){const o="Error during stringifyEncodingSetting: "+P(t);return h("export.ts").error(o),"{}"}},lnt=(e,t,o,r)=>{const n=t.lastIndexOf("."),a=ZN(o+1,r),i=n===-1?t:t.substr(0,n);return e+"/"+i+"_"+a+"."+Kt.PNG},dnt=e=>{const t=[];return tfe(e)&&t.push(GH.TRANSITION),t},unt=async()=>{const e=Cbe(),t=await Y().popup(e);return t===mt.YES?!0:t===mt.NO?!1:null},pnt=async(e,t,o)=>!await Vn("onExportVideo")||o.length>0&&await $2e(o)!==mt.YES?!1:(s0e()&&await mv(_v()),c_().length===0?(xt.info(A("player.load")),!1):e||t||Qh(Ur.EXPORT)?(Y().warn(A("export.busy")),!1):!0),LO=e=>{const t=ca(),o=t.map(n=>n.videoAudioMetaInfo?.videoInfo?.frameRate??void 0).filter(n=>n).filter((n,a,i)=>i.indexOf(n)===a).sort((n,a)=>n===void 0||a===void 0?0:n-a),r=o[o.length-1];return r===void 0?Wl:e||Math.round(r)===E6||Math.round(r)===m6||Math.round(r)===Wl?r:Math.max(r,Wl)},age=(e,t=!1)=>{switch(e){case e0.DEFAULT:return t?Wl:LO(!1);case e0.CAPTION_VIDEO:return LO(!0);case e0.AUTO:{const o=LO(!1);return t?Math.min(o,sZ):o}case e0.FPS_30:return 30;case e0.FPS_60:return 60}},ige=e=>ca().map(o=>EA(o.name)).includes(e),fnt=()=>48e3,gnt=()=>{const r=ca().filter(a=>a.mediaId!==_o);if(r.length===0)return 2;const n=r.map(a=>a.videoAudioMetaInfo?.audioInfo?.channelCount).filter(Se).reduce((a,i)=>{if(a===void 0||a===i)return i},void 0);return n===void 0||n<2||n>8?2:n},Ff=(e,t,o)=>XH(e,o)+"/"+t,XH=(e,t)=>b7()+"/"+e+"/"+k1+"/"+t,kM=async e=>{const o=[],r=[...e],n=1.2,a=.5;let i=null,s=1,x=50;for(;r.length>0;){const c=r.splice(0,s),l=await Promise.all(c.map(async f=>{const E=performance.now(),T=await f(),O=performance.now()-E;return{result:T,elapsedTime:O}})),d=l.reduce((f,E)=>f+E.elapsedTime,0),u=d/l.length,p=l.map(f=>f.result);if(o.push(...p),i=i===null?u:i*(1-a)+u*a,u<=i*n){const f=Math.ceil(6*(x-s)/x);s=Math.min(x,s+f),x=Math.min(x*1.2,50)}else s=Math.max(1,Math.floor(s/2)),x=Math.max(1,Math.floor(x/1.5))}return o},Bw=e=>{if(e?.aborted)throw new C(_.C_VCLOUD_USER_UPLOAD_CANCELED)},cT=e=>{const t=e.multiparts>1,o=e.type==="copy"&&e.metadataDirective==="COPY",r=o?{}:{origFileName:encodeURIComponent(e.origFileName),...e.type==="upload"?{hash:e.hash}:{}};switch(e.type){case"upload":return t?{methodType:"MULTIPART_UPLOAD",name:e.fileName,multiparts:e.multiparts,metadata:r,cacheControl:H_}:{methodType:"PUT",name:e.fileName,contentType:e.contentType,metadata:r,cacheControl:H_};case"copy":return e.sourceSize>SZ?{methodType:"MULTIPART_COPY",name:e.name,sourceKey:e.sourceKey,metadata:r,cacheControl:H_,sourceSize:e.sourceSize,partSize:jc}:{methodType:"COPY",name:e.name,sourceKey:e.sourceKey,metadataDirective:e.metadataDirective,metadata:r,cacheControl:H_}}},JH=async(e,t,o)=>{let r=0;const n=Array.from({length:t},()=>(async()=>{let a;for(;(a=r++)<e.length;)await o(e[a],a)})());await Promise.all(n)},Hu=async e=>{const t=()=>{const a="[prepareUploadData] empty blob for mediaId: "+e.mediaId;throw h("projectUpload.ts").error(a),bUe(e.mediaId),new C(_.C_VCLOUD_MEDIA_FILE_ERROR,{},a)};e.uploadSourceType==="blob"&&DR(e.blob)&&t();const o=await dge(e);DR(o)&&t();const r=gge(o),n=cT({type:"upload",fileName:e.remotePath,contentType:o.type,hash:await c4(o),origFileName:e.name,multiparts:r.length});return{mediaId:e.mediaId,blob:o,uploadBlobs:r,signedUrlRequest:n,size:o.size,targetType:e.targetType,projectId:e.projectId}},qH=async(e,t,o,r,n)=>{const a=h("projectUpload.ts"),i={},s=[],x=e.files.filter(u=>Zr(u)).filter(u=>!ia(u.mediaId));for(const u of x){const p=u.mediaId,{videoAudioMetaInfo:f}=u;if(!f.audioInfo&&!f.videoInfo)throw a.error("No media Info for fileId: "+p),new C(_.C_VCLOUD_MEDIA_FILE_ERROR);const E=Bc(u)?u.path:gd(p),{uploadData:T,source:O}=await cge({path:E,fileId:p,blob:e.blobs?.[p],name:u.name,projectId:t}),S=await Hu(T);
1112s.push({fileId:p,clientFileInfo:S,proxySourceFileInfo:{mediaInfo:u.videoAudioMetaInfo,source:O}})}const c=new Set(s.map(u=>u.fileId)),l=Yx.extractCacheableCloudMediaIds(e.files),d=l.filter(u=>!c.has(u));for(const u of d){const p=e.files.find(E=>E.mediaId===u);if(!p){const E="No fileInfo for mediaId: "+u;throw h("projectUpload.ts").error(E),new C(_.C_VCLOUD_MEDIA_FILE_ERROR,{},E)}const f=Bc(p)?await sge(p,u,t):await xge(p,u,t,e);s.push({fileId:u,clientFileInfo:f})}return await Kw(s,t,n,o,r,i),i},Cu=async(e,t,o,r)=>{const n=h("projectUpload.ts");try{const a=j2(e),i=fge(a,o,e),s=new Blob([i],{type:"application/json"}),x=s.size,c=e.files.reduce((p,f)=>f.fileLocation!==D.REMOTE?p:p+f.fileSize,0),l=x+c,d={uploadSourceType:"blob",mediaId:t,blob:s,remotePath:lge(t),targetType:"snapshot",projectId:o,name:Mx};await lT({data:d,abortSignal:r?.signal}),n.info("update vcloud project snapshot for projectId="+o+", snapshotId="+t+", totalSize="+l);const u=await VOe(o,t,l);return{totalSize:l,snapshotRegistered:u}}catch(a){const i=Ne(a)?a.errorCode:_.C_VCLOUD_
1112UPLOAD_ERROR;if(r?.signal?.aborted||i===_.C_VCLOUD_USER_UPLOAD_CANCELED){const x="[uploadVrewJsonToCloud] aborted";throw h("projectUpload.ts").error(x),new C(_.C_VCLOUD_USER_UPLOAD_CANCELED,{},x)}const s="Error during snapshot upload for projectId="+o+", snapshotId="+t+": "+P(a);throw n.error(s),new C(i,{},s)}},sge=async(e,t,o)=>{const r=e.path,n=yo(r);return await Hu({uploadSourceType:"path",mediaId:t,localPath:r,remotePath:Ws(t,n),targetType:"media",projectId:o,name:e.name})},xge=async(e,t,o,r)=>{const n=r.blobs[t];if(!n){const i="No blob in snapshotInfo.blobs for mediaId: "+t;throw h("projectUpload.ts").error(i),new C(_.C_VCLOUD_MEDIA_FILE_ERROR,{},i)}const a=X0.getExtension(n.type)??await Bs(n);return await Hu({uploadSourceType:"blob",mediaId:t,blob:n,remotePath:Ws(t,a),targetType:"media",projectId:o,name:e.name})},cge=async e=>{const{path:t,fileId:o,blob:r,name:n,projectId:a}=e;if(t)return{uploadData:{uploadSourceType:"path",mediaId:o,localPath:t,remotePath:Ws(o,yo(t)),targetType:"media",projectId:a,name:n},source:{sourceType:"path",path:t}};if(!r)throw h("projectUpload.ts").error("No path or blob for fileId: "+o),new C(_.C_VCLOUD_MEDIA_FILE_ERROR);const i=X0.getExtension(r.type)??await Bs(r);return{uploadData:{uploadSourceType:"blob",mediaId:o,blob:r,remotePath:Ws(o,i),targetType:"media",projectId:a,name:n},source:{sourceType:"blob",blob:r}}},lge=e=>D1+"/"+e+"/"+Mx,dge=async e=>e.uploadSourceType==="blob"?uge(e):pge(e),uge=async e=>{if(e.uploadSourceType!=="blob")throw new C(_.C_VCLOUD_MEDIA_FILE_ERROR,{},"data.uploadSourceType is not blob");if(e.targetType!=="media"||e.shouldNotCache)return e.blob;const o=yo(e.remotePath),r=ul(e.projectId,e.mediaId,o);return!await Ht(So.CLOUD_CACHE).getFileAsBlob(r)&&Rg(r,e.blob.stream()),e.blob},pge=async e=>{if(e.uploadSourceType!=="path")throw new C(_.C_VCLOUD_MEDIA_FILE_ERROR,{},"data.uploadSourceType is not path");const t=e.targetType!=="media"||e.shouldNotCache,o=an(e.localPath);if(t){const x=await fetch(o);if(!x.ok)throw new C(_.C_VCLOUD_MEDIA_FILE_ERROR,{},"Failed to fetch file: "+o+" (status: "+x.status+")");return x.blob()}const r=yo(e.remotePath),n=ul(e.projectId,e.mediaId,r),a=await Ht(So.CLOUD_CACHE).getFileAsBlob(n);if(a)return h("projectUpload.ts").info("[getBlobFromData] Using OPFS cache mediaOpfsPath: "+n),a;const i=await fetch(o);if(!i.ok||!i.body)throw h("projectUpload.ts").error("Failed to get stream for mediaId="+e.mediaId+", localPath="+e.localPath),new C(_.C_VCLOUD_MEDIA_FILE_ERROR,{},"Failed to read file: "+o);await Rg(n,i.body);const s=await Ht(So.CLOUD_CACHE).getFileAsBlob(n);if(!s)throw h("projectUpload.ts").error("Failed to get blob for mediaId="+e.mediaId+", localPath="+e.localPath),new C(_.C_VCLOUD_MEDIA_FILE_ERROR,{},"Failed to retrieve cached blob for mediaId: "+e.mediaId);return s},fge=(e,t,o)=>{try{return JSON.stringify(e)}catch(r){throw r instanceof RangeError?new C(_.C_VCLOUD_PROJECT_TOO_LARGE,{},"[uploadVrewJsonToCloud] project too large to serialize. projectId="+t+", fileCount="+o.files.length):r}},gge=e=>{const t=e.size,o=[];for(let r=0;r<t;r+=jc){const n=e.slice(r,r+jc,e.type);o.push(n)}return o},Kw=async(e,t,o,r,n,a)=>{const i=h("s3Upload.ts"),s=5;try{for(const c of FT(e,100)){const l=await PT(c.map(u=>u.clientFileInfo.signedUrlRequest),t),d=c.map((u,p)=>({file:u,presign:l[p]}));await JH(d,s,async({file:u,presign:p})=>{const{fileId:f,clientFileInfo:E,proxySourceFileInfo:T}=u,{name:O,methodType:S}=E.signedUrlRequest,R=ha(O);if(n(!1,!1,{mediaId:f,type:R,progressRatio:0}),S==="PUT"&&p.result==="PUT")await ZH(p.url,E.uploadBlobs[0],E.signedUrlRequest.cacheControl,r.signal,(v,w)=>{const N=w>0?v/w*_u:0;n(!1,!1,{mediaId:f,type:R,progressRatio:N})});else if(S==="MULTIPART_UPLOAD"&&p.result==="MULTIPART_UPLOAD")await $H(p.urls,E.uploadBlobs,p.uploadId,t,O,r.signal,(v,w)=>{const N=w>0?v/w*_u:0;n(!1,!1,{mediaId:f,type:R,progressRatio:N})});else throw new C(_.C_VCLOUD_MEDIA_FILE_ERROR,{},"Unexpected presign/result: "+p.result);const y=Ff(o,O,t);if(a[f]={...a[f],path:y},T){const v=await $w({videoAudioMetaInfo:T.mediaInfo,mediaId:f,source:T.source,projectId:t,uploadAbortSignal:r.signal,onProgressUpdate:w=>{n(!1,!1,{mediaId:f,type:R,progressRatio:_u+w*Iy})}});a[f].proxy=v}n(!1,!1,{mediaId:f,type:R,progressRatio:1})})}}
1112catch(x){const c=ye(x)??_.C_VCLOUD_UPLOAD_ERROR;throw r.signal?.aborted||c===_.C_VCLOUD_USER_UPLOAD_CANCELED?(i.info("[processPutUploads] User canceled upload, projectId: "+t),new C(_.C_VCLOUD_USER_UPLOAD_CANCELED)):(i.error("[processPutUploads] failed to upload, projectId: "+t),new C(c))}},lT=async({data:e,abortSignal:t,updateProgress:o})=>{const r=h("s3Upload.ts"),n=be().getUserInfo()?.uid;if(n===void 0)throw h("s3Upload.ts").error("uid is undefined"),new C(_.A_AUTH_GERNAL_ERROR);try{const a=new Jo,{mediaId:i,blob:s,uploadBlobs:x,signedUrlRequest:c,targetType:l,projectId:d}=await Hu(e);if(l==="media"&&await Ege(d,c.name,s)){const O=Ff(n,c.name,d);return r.info("[uploadToCloud] File already uploaded: "+O+", mediaId: "+i+", projectId: "+d+", uid: "+n),O}const u=await Nd(d,c);u.result==="PUT"&&c.methodType==="PUT"&&await ZH(u.url,x[0],c.cacheControl,t,o),u.result==="MULTIPART_UPLOAD"&&c.methodType==="MULTIPART_UPLOAD"&&await $H(u.urls,x,u.uploadId,d,c.name,t,o);const p=l==="media"?Ff(n,c.name,d):mge(n,i,d),f=pe(a.getElapsedSec());if(!(e.uploadSourceType==="path"&&e.shouldNotCache)){const T=yo(e.remotePath);NUe(d,T,f,s.size)}return p}catch(a){const i=ye(a)??_.C_VCLOUD_UPLOAD_ERROR;throw i===_.C_VCLOUD_USER_UPLOAD_CANCELED?(r.info("[uploadToCloud] User canceled upload, projectId: "+e.projectId+", mediaId: "+e.mediaId+", uid: "+n),a):(r.error("Failed to upload asset to cloud: projectId="+e.projectId+", mediaId="+e.mediaId+", uid="+n+", err="+P(a)),new C(i))}},QH=async(e,t,o,r)=>{const n=h("s3Upload.ts");try{const a={methodType:"MULTIPART_COMPLETE",name:e,etags:t,uploadId:o},i=await Nd(r,a);if(i.result!=="MULTIPART_COMPLETE"){const s="Multipart complete failed. ret: "+JSON.stringify(i);throw n.error(s),new C(_.C_VCLOUD_MULTIPART_UPLOAD_ERROR)}n.info("Multipart upload completed successfully for path: "+e)}catch(a){if(Ne(a))throw a;const i="Failed to complete multipart upload for path: "+e+". err : "+P(a);throw n.error(i),new C(_.C_VCLOUD_MULTIPART_UPLOAD_ERROR)}},_ge=async e=>{if(at()&&!await H0(V.TRANSCODING_VIDEO))throw h("s3Upload.ts").info("FFMPEG not found, skipping upload in uploadNewMediaToCloud"),new C(_.C_ENCODING_USER_CANCELED);const{uploadData:o,abortController:r,uploadChunkProgressCallback:n,proxyCreator:a}=e,i=await lT({data:o,abortSignal:r.signal,updateProgress:n});if(a){if(!("videoAudioMetaInfo"in e.fileInfo))throw h("s3Upload.ts").error("Failed to create proxy for "+o.mediaId+", videoAudioMetaInfo is not found"),new C(_.C_VCLOUD_UPLOAD_ERROR);let s;if("path"in e.fileInfo)s={sourceType:"path",path:e.fileInfo.path};else if(o.uploadSourceType==="blob")s={sourceType:"blob",blob:o.blob};else throw h("s3Upload.ts").error("Failed to create proxy for "+o.mediaId+", neither path nor blob is available"),new C(_.C_VCLOUD_UPLOAD_ERROR);const x=await a({videoAudioMetaInfo:e.fileInfo.videoAudioMetaInfo,mediaId:o.mediaId,source:s,projectId:o.projectId,uploadAbortSignal:r.signal});return{url:i,proxyInfo:x}}return{url:i}},Ege=async(e,t,o)=>{const r=h("s3Upload.ts"),n=await Nd(e,{methodType:"HEAD",name:t});if(n.result!=="HEAD")return r.warn("Failed to get head signed url for "+t),!1;try{const a=await fetch(n.url,{method:"HEAD"});if(a.status===404)return r.info("File not found for "+t),!1;if(!a.ok)return r.warn("Failed to check file already uploaded for "+t),!1;const i=a.headers.get(TZ);return i?i===await c4(o):(r.warn("Hash not found for "+t),!1)}catch(a){return r.warn("Failed to check file already uploaded for "+t+": "+P(a)),!1}},ZH=async(e,t,o,r,n)=>{const a=o?{"Cache-Control":o}:void 0,i=MT(x=>{n&&x.total&&n(x.loaded,x.total)},300),s=await G2(()=>r2.put(e,t,{headers:a,signal:r,onUploadProgress:i}),r);if(n&&s&&n(t.size,t.size),s===null&&r?.aborted)throw h("s3Upload.ts").info("[uploadSingleFile] User canceled upload"),new C(_.C_VCLOUD_USER_UPLOAD_CANCELED);if(s?.status!==200)throw h("s3Upload.ts").warn("[uploadSingleFile] Upload failed with status: "+s?.status),new C(_.C_VCLOUD_S3_UPLOAD_ERROR)},$H=async(e,t,o,r,n,a,i)=>{const s=h("s3Upload.ts"),x=t.reduce((l,d)=>l+d.size,0);let c=0;try{const l=[];for(let d=0;d<e.length;d++){const u=e[d],p=t[d],f=c,E=MT(y=>{if(i&&y.total){const v=f+y.loaded;i(Math.min(v,x),x)}},300),T=performance.now(),O=await G2(()=>r2.put(u,p,{signal:a,onUploadProgress:E}),a),S=performance.now();if(O===null)throw s.info("[uploadMultipart] user canceled"),new C(_.C_VCLOUD_
1112USER_UPLOAD_CANCELED);if(O.status!==200)throw s.warn("[uploadMultipart] chunk upload failed: "+O.status),new C(_.C_VCLOUD_S3_UPLOAD_ERROR);i&&i(Math.min(f+p.size,x),x),s.info("[uploadMultipart] chunk "+(d+1)+" speed: "+x4(T,S,p.size)+" Mbps");const R=O.headers.etag||O.headers.ETag;if(!R)throw s.warn("No etag in upload result: "+JSON.stringify(O?.headers)),new C(_.C_VCLOUD_UPLOAD_ETAG_MISSING);if(l.push(R),c+=p.size,i){const y=Math.min(c,x);i(y,x)}}if(l.length!==t.length){const d="etag length mismatch. blobs.length: "+t.length+", etags: "+l.length+"}";throw s.error(d),new C(_.C_VCLOUD_UPLOAD_ETAG_MISSING)}await QH(n,l,o,r)}catch(l){const d=ye(l)??_.C_VCLOUD_MULTIPART_UPLOAD_ERROR;throw a?.aborted||d===_.C_VCLOUD_USER_UPLOAD_CANCELED?(s.info("[Uploading] User canceled multipart upload, projectId: "+r),new C(_.C_VCLOUD_USER_UPLOAD_CANCELED)):(s.error("[Uploading] failed to upload multipart file, projectId: "+r),new C(d))}},mge=(e,t,o)=>XH(e,o)+"/"+D1+"/"+t+"/"+Mx,hge=/\/proxy\/(\d+(?:\.\d+)?)~/,Ige=/\/proxy\/audio_(\d+)/,FM=e=>{const t=e.match(hge);if(t)return parseFloat(t[1]);const o=e.match(Ige);return o?parseInt(o[1],10):0},Tge=e=>e.filter(o=>o.includes(ff)).sort((o,r)=>FM(o)-FM(r));var Sge=(e=>(e.UPLOADING="uploading",e.DONE="done",e.EDITING="editing",e))(Sge||{});const Uf=2,Xw=1,WE=2,qg=(e,t,o)=>vt(e,n=>{n.files.forEach((a,i)=>{if(t[a.mediaId]){if(o&&a.fileLocation!==D.REMOTE)return;const{path:s,proxy:x}=t[a.mediaId],c={...a,url:s,fileLocation:D.REMOTE,proxyInfo:x?sG(x):void 0};n.files[i]=c}})}),Jw=(e,t,o,r,n)=>{const a=[];for(const i of e){const{mediaId:s,name:x}=i;if(s===_o)continue;const c=t[s];if(!c)continue;const l=Ws(s,yo(c.key)),d=cT({type:"copy",name:l,sourceKey:c.key,origFileName:x,multiparts:Math.ceil(c.size/jc),sourceSize:c.size,metadataDirective:n}),u={signedUrlRequest:d,uploadBlobs:[],size:c.size},p=i.fileLocation===D.LOCAL||i.fileLocation===D.LOCAL_TMP?i.path:void 0,f=Zr(i)&&p?{mediaInfo:i.videoAudioMetaInfo,source:{sourceType:"path",path:p}}:void 0;a.push({fileId:s,clientFileInfo:u,needProxy:Zr(i),jobId:o,proxySourceFileInfo:f,version:r})}return a},Oge=async({uid:e,uploadId:t,newProjectId:o,uploadTitle:r,snapshotId:n,currentProjectSize:a,observer:i,mediaFileSizes:s,abortCtrl:x,originalVrewFileData:c,uploadableVrewFileData:l,currProjectId:d})=>{const u=h("s3Copy.ts"),p=u0(a,s,Gs.UPLOAD,i);eI(o);try{if(!d)throw new C(_.C_LOGIC_ERROR);u.info("[uploadCloudProjectByMediaCopy] createCloudProjectUploadSessionV2 for newProjectId: "+o+", sourceProjectId: "+d);const f=await gA({projectId:o,projectTitle:r,snapshotId:n,uploadType:"copy",version:Uf,copyProjectId:d});if(f.uploadType!=="copy"){const S="Unexpected upload type: "+f.uploadType+" for projectId: "+o;throw u.error(S),new C(_.C_VCLOUD_UPLOAD_ERROR,{},S)}await ol();const E=Jw(l.files,f.mediaFileMap,t,Uf,"COPY"),T={};E.length>0&&await qw(E,o,e,x,p,T,{mode:"save-as",sourceProjectId:d});const O=qg(c,T,!0);await Cu(O,n,o,x),await _A({projectId:o,totalSize:a}),await Pae(o,T,x)}catch(f){const E=ye(f)??_.C_VCLOUD_UPLOAD_ERROR;if(x.signal?.aborted||E===_.C_VCLOUD_USER_UPLOAD_CANCELED)throw u.info("[uploadCloudProjectByMediaCopy] User canceled upload"),new C(_.C_VCLOUD_USER_UPLOAD_CANCELED);const T="Fail while uploading cloud project by media copy. projectId: "+o;throw h("s3Copy.ts").error(T),new C(E)}},qw=async(e,t,o,r,n,a,i)=>{const s=h("s3Copy.ts"),x=5,c=100,l=i.mode;try{for(const d of FT(e,c)){const u=await PT(d.map(f=>f.clientFileInfo.signedUrlRequest),t),p=d.map((f,E)=>({task:f,presign:u[E]}));await JH(p,x,async({task:f,presign:E})=>{const{fileId:T,needProxy:O,proxySourceFileInfo:S,jobId:R,version:y}=f,v=ha(f.clientFileInfo.signedUrlRequest.name);await Cge(f,E,t,o,r,n,a),O&&(l==="migration"&&S?await jge(T,S,t,r,n,R,y,a):l==="save-as"&&await Gge(T,i.sourceProjectId,t,o,r,a,f.clientFileInfo.size),n(!1,!1,{mediaId:T,type:v,progressRatio:1}))})}}catch(d){const u=ye(d)??_.C_VCLOUD_UPLOAD_ERROR;if(r.signal?.aborted||u===_.C_VCLOUD_USER_UPLOAD_CANCELED)throw s.info("[processCopyUploads] User canceled copy, projectId: "+t),new C(_.C_VCLOUD_USER_UPLOAD_CANCELED);const p="[processCopyUploads] failed to copy, projectId: "+t+", error: "+P(d)+" ";throw s.error(p),new C(u,{},p)}},Qw=async(e,t,o,r)=>{const n=h("s3Copy.ts"),a=MT(c=>{r&&c.total&&r(c.loaded,c.total)},300),i=await G2(()=>r2.put(e.url,null,{headers:e.headers,signal:t,onUploadProgress:a}),t);if(r&&i&&r(o,o),i===null&&t?.aborted)throw n.info("[copySinglePart] copy canceled by user"),new C(_.C_VCLOUD_
1112USER_UPLOAD_CANCELED);if(i?.status!==200)throw n.warn("[copySinglePart] copy failed with status "+i?.status),new C(_.C_VCLOUD_S3_COPY_ERROR);const s=i.data.match(F1);if(!s)throw n.error("[copySinglePart] ETag missing in CopyPartResult"),new C(_.C_VCLOUD_UPLOAD_ETAG_MISSING);return s[2]},Zw=async({parts:e,uploadId:t,projectId:o,pathName:r,signal:n,totalSize:a,onProgress:i})=>{const s=h("s3Copy.ts"),x=[];let c=0;try{for(let l=0;l<e.length;l++){const{url:d,headers:u}=e[l],p=u["x-amz-copy-source-range"],f=Rge(p),E=c,T=MT(M=>{if(i&&M.total){const k=E+M.loaded;i(Math.min(k,a),a)}},300),O=performance.now(),S=await G2(()=>r2.put(d,null,{headers:u,signal:n,onUploadProgress:T}),n),R=performance.now(),y=x4(O,R,f);if(s.info("[copyMultipartFromS3] Upload speed for chunk "+(l+1)+": "+y+" Mbps"),S===null&&n?.aborted)throw s.info("[copyMultipartFromS3] copy canceled by user"),new C(_.C_VCLOUD_USER_UPLOAD_CANCELED);if(S?.status!==200)throw s.warn("[copyMultipartFromS3] copy part failed with status "+S?.status),new C(_.C_VCLOUD_S3_COPY_ERROR);i&&S&&i(f,a);const v=S.data,w=v.match(F1);if(!w)throw s.error("[copyMultipartFromS3] ETag missing in CopyPartResult"),new C(_.C_VCLOUD_UPLOAD_ETAG_MISSING);const N=w[2];if(x.push(N),c+=f,i){const M=Math.min(c,a);i(M,a)}}if(x.length!==e.length){const l="Expected "+e.length+" parts but got "+x.length;throw s.error("[copyMultipartFromS3] "+l),new C(_.C_VCLOUD_UPLOAD_ETAG_MISSING,{},l)}await QH(r,x,t,o)}catch(l){const d=ye(l)??_.C_VCLOUD_S3_COPY_ERROR;throw n?.aborted||d===_.C_VCLOUD_USER_UPLOAD_CANCELED?(s.info("[copyMultipartFromS3] User canceled copy multipart, projectId: "+o),new C(_.C_VCLOUD_USER_UPLOAD_CANCELED)):(s.error("[copyMultipartFromS3] failed to copy multipart, projectId: "+o),new C(d))}},Cge=async(e,t,o,r,n,a,i)=>{const{fileId:s,clientFileInfo:x,needProxy:c}=e,{name:l}=x.signedUrlRequest,d=ha(l);a(!1,!1,{mediaId:s,type:d,progressRatio:0});const u=c?_u:1;t.result==="COPY"?await Qw({url:t.url,headers:t.headers},n.signal,x.size,(f,E)=>{const T=E>0?f/E*u:0;a(!1,!1,{mediaId:s,type:d,progressRatio:T})}):t.result==="MULTIPART_COPY"&&await Zw({parts:t.parts,uploadId:t.uploadId,projectId:o,pathName:l,signal:n.signal,totalSize:x.size,onProgress:(f,E)=>{const T=E>0?f/E*u:0;a(!1,!1,{mediaId:s,type:d,progressRatio:T})}});const p=Ff(r,l,o);i[s]={...i[s],path:p},a(!1,!1,{mediaId:s,type:d,progressRatio:u})},Rge=e=>{const t=/^bytes=(\d+)-(\d+)$/.exec(e);if(!t)return h("s3Copy.ts").error("[getPartSizeFromRange] Unexpected range format: "+e),0;const o=parseInt(t[1],10);return parseInt(t[2],10)-o+1},$w=async({videoAudioMetaInfo:e,mediaId:t,source:o,projectId:r,uploadAbortSignal:n,onProgressUpdate:a=()=>{}})=>{const i=h("proxy.ts"),{videoInfo:s,audioInfo:x,duration:c}=e;let l,d;const u=o.sourceType==="path"?o.path:"[blob]";try{[l,d]=await Promise.all([Lge(o,x,c,n),Age(o,s,t,c,n)]);const p=UM(l),f=UM(d),E=p+f;let T=0;const O={mediaId:t,projectId:r,uploadAbortSignal:n,onFileUploaded:()=>{T++,a(T/E)}},S=vge(d,O),R=yge(l,O);i.info("[createProxyFiles] videoTasks: "+S.length+", audioTasks: "+R.length);const y=performance.now(),[v,w]=await Promise.all([kM(S),kM(R)]),N=performance.now();return i.info("[createProxyFiles] total time: "+((N-y)/1e3).toFixed(2)+" seconds"),Nge([...v,...w])}catch(p){const f=ye(p)??_.C_VCLOUD_UPLOAD_ERROR;if(f===_.C_VCLOUD_USER_UPLOAD_CANCELED)throw i.info("[createProxyFiles] User canceled upload, mediaId: "+t+", source: "+u),p;const E="Failed to upload proxy to cloud: mediaId="+t+", source="+u+", err="+P(p);throw i.error(E),new C(f)}finally{wge(l,d)}},Age=async(e,t,o,r,n)=>{if(!t)return;Bw(n);const a=h("proxy.ts");if(e.sourceType==="path"){const{tempFolder:s,exportId:x,setting:c}=await Pge();return a.info("[createProxyFiles]",{mediaId:o,source:e.path,duration:r,setting:c,tempFolder:s,videoSize:t.size}),await bge(o,e.path,r,c,x),{sourceType:"path",paths:await kge(s,o),tempDir:s}}return{sourceType:"blob",files:await Dge(e.blob)}},yge=(e,t)=>e?e.sourceType==="path"?e.paths.map((o,r)=>
1112jm(t,{type:"path",path:o,name:"audio_"+r+ff})):e.blobs.map((o,r)=>jm(t,{type:"blob",blob:o,name:"audio_"+r+ff})):[],vge=(e,t)=>e?e.sourceType==="path"?e.paths.map(o=>jm(t,{type:"path",path:o})):e.files.map(o=>jm(t,{type:"blob",blob:o,name:o.name})):[],wge=(e,t)=>{e?.sourceType==="path"&&e.tempFsList.forEach(o=>{qt().clearExtractedAudioTempFile(o)}),t?.sourceType==="path"&&t.tempDir&&Ue().deleteFolder(t.tempDir)},jm=(e,t)=>async()=>{const o=t.type==="path"?t.name??gt(t.path):t.name,r=Wge(o,e.mediaId);Bw(e.uploadAbortSignal),e.onFileUploaded();const n=t.type==="path"?{uploadSourceType:"path",mediaId:e.mediaId,localPath:t.path,remotePath:r,targetType:"media",projectId:e.projectId,shouldNotCache:!0,name:o}:{uploadSourceType:"blob",mediaId:e.mediaId,blob:t.blob,remotePath:r,targetType:"media",projectId:e.projectId,shouldNotCache:!0,name:o};return await lT({data:n,abortSignal:e.uploadAbortSignal})},Nge=e=>{const t=e.find(r=>r?.includes(Ph)),o=e.filter(r=>r?.includes(ff));return{videoProxyUrl:t,audioProxyUrls:o}},UM=e=>e?e.sourceType==="path"?e.paths.length:"blobs"in e?e.blobs.length:e.files.length:0,Pge=async()=>{const e=await Ue().tempFolder(),t=Ad(),o={type:V.STREAM,exportId:t,quality:F0.REGULAR,captionSetting:Eg,size:R3,hwAccel:qt().getAvailableHwAccel(),videoFrameRate:0,option:{streamEncodingOption:{baseFolder:e}}};return{tempFolder:e,exportId:t,setting:o}},bge=async(e,t,o,r,n)=>{const a=Mge(n);await qt().encode([],{[e]:t},[{clipIndex:0,captions:[],exportCaptionModels:[],exportAssets:[],playbackRate:1,pieceTimelineInProject:0,timelineDuration:o,wordIds:[]}],Kt.HLS,a,r)},Lge=async(e,t,o,r)=>{if(!t)return;Bw(r),h("proxy.ts").info("[createProxyFiles] extracting audio fragments");const a=await Vge(e,o);return a.sourceType==="path"?{sourceType:"path",paths:a.resultList,tempFsList:a.tempFsList}:{sourceType:"blob",blobs:a.blobs}},Mge=e=>{const t=h("proxy.ts"),o=new u2(10);let r=0;return{onStart:()=>{o.start(),t.info("[Transcoding] Started encoding, exportId: "+e)},onProgress:(a,i)=>{r=a/i,t.debug("[Transcoding] Progress: "+(r*100).toFixed(2)+"%")},onEnd:(a,i)=>{t.info("[Transcoding] Completed encoding, path: "+i)},onError:a=>{t.error("[Transcoding] Encoding error: "+P(a))},onCancel:()=>{t.warn("[Transcoding] Encoding cancelled by system.")},onResult:()=>{}}},Dge=async e=>{const t=Ht(So.AUDIO_TEMP);return(await ix(t)).convertHLS(e)},kge=async(e,t)=>{const o=await Ue().listDir(e);if(!o||o.length===0)throw h("proxy.ts").error("Failed to get proxy media resources. Path list is empty. mediaId: "+t),new C(_.C_VCLOUD_UPLOAD_ERROR);return o},Fge=async(e,t)=>{const o=qt(),r=[],n=[],a=e4(t);try{const i=await o.getMediaFileStartTimes(e),s=i?.audio;s===void 0&&h("proxy.ts").warn("[extractAudioFragmentsFromPath] cannot resolve audio start time, skip normalization");const x=i?.container,c=s!==void 0&&x!==void 0&&s!==x;let l=e;if(c){const d=s-x;h("proxy.ts").info("[extractAudioFragmentsFromPath] normalize audio start time: "+d+"ms");const u=await o.extractAudio(e,Gt.MP3,!1,!0);l=u.path,u.tempfile&&n.push(u.tempfile)}for(const{startTime:d,duration:u}of a){const{path:p,tempfile:f}=await o.extractAudioFragment(l,Gt.AAC,d,u);r.push(p),n.push(f)}return{resultList:r,tempFsList:n}}catch(i){throw n.forEach(s=>{o.clearExtractedAudioTempFile(s).catch(x=>{h("proxy.ts").warn("[extractAudioFragmentsFromPath] failed to clean temp file: "+P(x))})}),i}},Uge=async(e,t)=>{const o=Ht(So.AUDIO_TEMP),r=await ix(o),n=await r.getMediaFileInfo(e);if(!n.audioInfo)return[];const a=n.audioInfo.codec,i=n.videoInfo===void 0,{blob:s,codec:x}=i?{blob:e,codec:a}:await r.extractAudio(e,a,()=>{}),c=[],l=e4(t);for(const{startTime:d,duration:u}of l){const p=await r.sliceAudio(s,x,d,u);c.push(p)}return c},Vge=async(e,t)=>e.sourceType==="path"?{sourceType:"path",...await Fge(e.path,t)}:{sourceType:"blob",blobs:await Uge(e.blob,t)},Gge=async(e,t,o,r,n,a,i)=>{const s=yo(a[e].path),x=ti(i4(e,s)),c=await B7(t,x);if(c.length===0)return;const l=Math.ceil(i/c.length),d=c.map(y=>{const v=a4(y,r,t);return cT({type:"copy",name:v,sourceKey:y,origFileName:gt(y),multiparts:Math.ceil(l/jc),sourceSize:l,metadataDirective:"COPY"})}),u=500,p=[];for(let y=0;y<d.length;y+=u)p.push(d.slice(y,y+u));const f=An(4),E=(await Promise.all(p.map(y=>f(()=>PT(y,o))))).flat(),T=An(10);await Promise.all(E.map((y,v)=>T(async()=>{n.signal.throwIfAborted(),y.result==="COPY"?await Qw({url:y.url,headers:y.headers},n.signal,0,()=>{}):y.result==="MULTIPART_COPY"&&await Zw({uploadId:y.uploadId,parts:y.parts,projectId:o,pathName:d[v].name,signal:n.signal,totalSize:0,onProgress:()=>{}})}
1112)));const O=d.map(y=>Ff(r,y.name,o)),S=O.find(y=>y.includes(Ph))??"",R=Tge(O);a[e].proxy={videoProxyUrl:S,audioProxyUrls:R}},Wge=(e,t)=>gg+"/"+t+"/proxy/"+e,e4=e=>{const t=Math.ceil(e/US),o=[];for(let r=0;r<t;r++){const n=r===0,a=n?0:r*US-VS,i=US+(n?VS:VS*2);o.push({startTime:a,duration:i})}return o},Hge=async(e,t,o,r,n,a,i)=>{const s=h("migration.ts");try{const x=await av(e,t);if(!x)throw new C(_.C_VCLOUD_INVALID_SNAPSHOT_INFO);const c=await t4(e);eI(e);const l=Object.entries(c).reduce((v,[w,{size:N}])=>(v[w]=N,v),{}),d=u0(a,l,Gs.UPLOAD,n,0,.25),u=await Yge(x,c,e,d,o),p=await H2(x,u),f=p.files.filter(v=>!c[v.mediaId]).map(v=>v.mediaId);s.info("[migrateV1ExternalProjectToV2] needUploadMediaIds "+JSON.stringify(f));const E=await o4(p.files,f,e,p.blobs,o),T=Jw(p.files,c,i,Xw,"REPLACE"),O={},S=u0(a,l,Gs.UPLOAD,n,.25,1);E.length>0&&await Kw(E,e,r,o,d,O),T.length>0&&await qw(T,e,r,o,S,O,{mode:"migration"});const R=qg(p,O,!1),y=Cn(10);await Cu(R,y,e,o),await zf({projectId:e,action:"finish",mediaFileMap:c})}catch(x){const c=ye(x)??_.C_VCLOUD_MIGRATE_PROJECT_ERROR;if(o.signal?.aborted||c===_.C_VCLOUD_USER_UPLOAD_CANCELED)throw s.info("[migrateV1ExternalProjectToV2] User canceled migration"),new C(_.C_VCLOUD_USER_UPLOAD_CANCELED);const l="Fail while migrating external project. projectId: "+e+", snapshotId: "+t;throw h("migration.ts").error(l),new C(c)}},jge=async(e,t,o,r,n,a,i,s)=>{const{mediaInfo:x,source:c}=t,l=c.sourceType==="path"?yo(c.path):await Bs(c.blob),d=ha(Ws(e,l)),u=await Bge({mediaInfo:x,mediaId:e,source:c,projectId:o,uploadAbortSignal:r.signal,onProgressUpdate:p=>n(!1,!1,{mediaId:e,type:d,progressRatio:_u+p*Iy}),jobId:a,version:i});s[e].proxy=sG(u)},zge=async(e,t,o,r,n,a,i)=>{const s=h("migration.ts"),x=Object.fromEntries(t.files.map(l=>[l.mediaId,l.fileSize])),c=u0(a,x,Gs.UPLOAD,n);try{const l=await t4(e);eI(e);const d=t.files,u=d.filter(S=>!l[S.mediaId]).map(S=>S.mediaId);s.info("[migrateV1CurrentProjectToV2] needUploadMediaIds "+JSON.stringify(u));const p=await o4(d,u,e,t.blobs,o),f=Jw(d,l,i,Xw,"REPLACE"),E={};p.length>0&&await Kw(p,e,r,o,c,E),f.length>0&&await qw(f,e,r,o,c,E,{mode:"migration"});const T=qg(t,E,!1),O=Cn(10);await Cu(T,O,e,o),await zf({projectId:e,action:"finish",mediaFileMap:l}),c(!0,!1)}catch(l){c(!1,!0);const d=ye(l)??_.C_VCLOUD_MIGRATE_PROJECT_ERROR;if(o.signal?.aborted||d===_.C_VCLOUD_USER_UPLOAD_CANCELED)throw s.info("[migrateV1CurrentProjectToV2] User canceled migration"),new C(_.C_VCLOUD_USER_UPLOAD_CANCELED);const u="Fail while migrating current project. projectId: "+e;throw h("migration.ts").error(u),new C(d)}},_nt=(e,t)=>({updateProgress:(o,r)=>{r.progressRatio&&t(r.progressRatio),r.isError&&e({type:"SET_UPLOAD_STATE",payload:rv.UPLOAD_ERROR}),e({type:"SET_UPLOAD_TEXT",payload:o})}}),Yge=async(e,t,o,r,n)=>{const a=h("migration.ts"),i={},s=e.files,x=An(10);try{const c=s.map(l=>x(async()=>{const{mediaId:d}=l,u=t[d];if(!u)return;const p=yo(u.key);if(l.fileLocation===D.IN_MEMORY){const f=await Xge(d,p,o,n);i[d]=f}else if(l.fileLocation===D.LOCAL_TMP){const{value:f,type:E}
1112=await Kge(d,p,o),T=E==="url"?{mediaId:d,ext:p,url:f}:{mediaId:d,ext:p,pathInfo:{path:f,preserveOriginal:!0}},{resolvedPath:O}=await Ue().putLocalCache(T);l.path=O}r(!1,!1,{mediaId:d,type:ha(u.key),progressRatio:1})}));return await Promise.all(c),i}catch(c){const l=ye(c)??_.C_VCLOUD_LOAD_MEDIA_BLOBS_FAILED;throw n.signal?.aborted||l===_.C_VCLOUD_USER_UPLOAD_CANCELED?(a.info("[loadV1ProjectMediaBlobs] User canceled get blobs"),new C(_.C_VCLOUD_USER_UPLOAD_CANCELED)):(a.error("[loadV1ProjectMediaBlobs] failed to get blobs"),new C(l))}},t4=async e=>{const t=await zf({projectId:e,action:"start"});if(t.result!=="start"){const o="Fail while migrating v1 cloud project session. result : "+t.result;throw h("migration.ts").error(o),new C(_.C_VCLOUD_GENERAL_ERROR,{},o)}return t.mediaFileMap},Bge=async({mediaInfo:e,mediaId:t,source:o,projectId:r,uploadAbortSignal:n,onProgressUpdate:a,jobId:i,version:s})=>{const x=h("migration.ts");if(o.sourceType!=="path")throw x.error("[migrateSourceFileToCloud] unexpected source type for migration: "+o.sourceType),new C(_.C_VCLOUD_UPLOAD_ERROR);const c=yo(o.path),l=s===Xw?await eN(t,c,r):o.path;x.info("downloadPath: "+l+", version: "+s+", mediaId: "+t+", ext: "+c+", projectId: "+r+", jobId: "+i);try{const d=await(async()=>{const p=new Oi,f=await p.getTempFileName(c);return{sourceType:"path",path:await tI(l,f,i),tempFs:p}})(),u=await $w({videoAudioMetaInfo:e,mediaId:t,source:d,projectId:r,uploadAbortSignal:n,onProgressUpdate:a});return d.tempFs?.clearAll(),u}catch(d){const u=ye(d)??_.C_VCLOUD_MIGRATE_PROJECT_ERROR;if(u===_.C_VCLOUD_USER_UPLOAD_CANCELED||n.aborted)throw x.info("[migrateSourceFileToCloud] User canceled migration"),new C(_.C_VCLOUD_USER_UPLOAD_CANCELED);const p="[migrateSourceFileToCloud] failed: "+P(d);throw x.error(p),new C(u)}},Kge=async(e,t,o)=>{const r=await _G(o,e,t);if(r)return h("migration.ts").info("[getMediaPathOrUrl] get path from opfs, mediaId: "+e),{value:r,type:"path"};const n=await eN(e,t,o);return h("migration.ts").info("[getMediaPathOrUrl] get url from signed url, mediaId: "+e),{value:n,type:"url"}},Xge=async(e,t,o,r)=>{const n=await Cg(o,e,t);if(n)return h("migration.ts").info("[getMediaBlob] get blob from opfs, mediaId: "+e),n;const a=await eN(e,t,o),i=await fetch(a,{method:"GET",signal:r.signal});if(h("migration.ts").info("[getMediaBlob] get blob from signed url, mediaId: "+e),r.signal?.aborted)throw h("migration.ts").info("[getLocalOrRemoteBlob] User canceled download, mediaId: "+e),new C(_.C_VCLOUD_USER_UPLOAD_CANCELED);if(i.status!==200){const c="[getLocalOrRemoteBlob] failed to download, mediaId: "+e;throw h("migration.ts").error(c),new C(_.C_VCLOUD_MEDIA_FILE_ERROR,{},c)}const s=await i.blob(),x=ul(o,e,t);return Rg(x,s.stream()),s},eN=async(e,t,o)=>{const r=Jge(e,t),n=await Nd(o,{methodType:"GET",name:r});if(n.result!=="GET")throw new C(_.C_VCLOUD_DOWNLOAD_ERROR);return n.url},o4=async(e,t,o,r,n)=>{const a=[];try{for(const i of e){const{mediaId:s}=i;if(s!==_o){if(!t.includes(s)){h("migration.ts").info("[generateLocalUploadTasks] mediaId: "+s+" is not in needUploadMediaIds");continue}if(i.fileLocation===D.LOCAL||i.fileLocation===D.LOCAL_TMP){const x=i.path,c=yo(x),l=Ws(s,c),d=Zr(i)&&x?{mediaInfo:i.videoAudioMetaInfo,source:{sourceType:"path",path:x}}:void 0,u=await Hu({uploadSourceType:"path",mediaId:s,localPath:x,remotePath:l,targetType:"media",projectId:o,name:i.name});a.push({fileId:s,clientFileInfo:{signedUrlRequest:u.signedUrlRequest,size:i.fileSize,uploadBlobs:u.uploadBlobs},proxySourceFileInfo:d})}else{const x=L.get(r,s);if(!x)throw h("migration.ts").error("cannot get blob for mediaId : "+s),new C(_.C_VCLOUD_UPLOAD_ERROR);const c=X0.getExtension(x.type)??await Bs(x),l=Ws(s,c),d=await Hu({uploadSourceType:"blob",mediaId:s,blob:x,remotePath:l,targetType:"media",projectId:o,name:i.name});a.push({fileId:s,clientFileInfo:{signedUrlRequest:d.signedUrlRequest,size:i.fileSize,uploadBlobs:d.uploadBlobs}})}}}return a}catch(i){const s=ye(i)??_.C_VCLOUD_MIGRATE_PROJECT_ERROR;if(n.signal.aborted)throw h("migration.ts").error("[generateLocalUploadTasks] aborted"),new C(s);const x="[generateLocalUploadTasks] failed to generate local upload tasks. error: "+i;throw h("migration.ts").error(x),new C(s)}},Jge=(e,t)=>
1112gg+"/"+e+"."+t,qge=50,Qge=5,Zge=jc*Qge,$ge=e=>!Number.isFinite(e)||e<=0?1:Math.min(e,jc),e_e=()=>{let e=0,t=0;const o=[],r=()=>{for(;e<qge;){const n=o[0];if(!n||t+n.byteWeight>Zge)return;o.shift(),n.start()}};return(n,a)=>new Promise((i,s)=>{const x=$ge(n),c=()=>{e++,t+=x,(async()=>{try{i(await a())}catch(l){s(l)}finally{e--,t-=x,r()}})()};o.push({byteWeight:x,start:c}),r()})};var Hr=(e=>(e.IMAGE="image",e.LOTTIE="lottie",e.WEB="web",e.VIDEO="video",e.SHAPE="shape",e.SIMPLE_CHARACTER="simpleCharacter",e.WATERMARK="watermark",e))(Hr||{});class Be{static CURRENT_VREW_JSON_VERSION=17;static CURRENT_AVMEDIA_VERSION=1;static CURRENT_IMAGE_VERSION=1;static CURRENT_SVG_VERSION=1;static CURRENT_HTML_VERSION=1;static CURRENT_WATERMARK_VERSION=2;static fromAssetEffectInfoJson=t=>{if(t)return W0(t.type)?{type:t.type,duration:t.duration}:{type:t.type,duration:t.duration,startDelay:t.startDelay??wh}};static toAssetEffectInfoJson=t=>{if(t)return ax(t)?{type:t.type,duration:t.duration,startDelay:t.startDelay}:{type:t.type,duration:t.duration}};static toWordJson=t=>({id:t.id,text:t.text,pronunciation:t.pronunciation,playbackRate:t.playbackRate,duration:t.duration,aligned:t.aligned,type:t.type,originalDuration:t.originalDuration,originalStartTime:t.originalStartTime,truncatedWords:t.truncatedWords.map(r=>Be.toWordJson(r)),assetIds:t.assetIds,hardcutWordMeta:t.hardcutWordMeta,freeze:t.type===Z.SPACER?t.freeze:void 0});static toClipboardCopiedWordJson=t=>({id:t.id,text:t.text,pronunciation:t.pronunciation,playbackRate:t.playbackRate,duration:t.duration,aligned:t.aligned,type:t.type,originalDuration:t.originalDuration,originalStartTime:t.originalStartTime,truncatedWords:t.truncatedWords.map(o=>Be.toWordJson(o)),assetIds:t.assetIds,hardcutWordMeta:t.hardcutWordMeta,newline:t.newline,freeze:t.type===Z.SPACER?t.freeze:void 0});static toCaptionJson=t=>({text:t.text.ops,style:t.style,height:t.height});static toClipDirtyJson=t=>({blankDeleted:t.blankDeleted,caption:t.caption,video:t.video});static toTranslationModifiedJson=t=>({result:t.result,source:t.source});static toClipJson=(t,o)=>{const r=t.assetIds.filter(i=>o?.[i]),n=ai(t);return{sceneId:t.sceneId,words:t.words.map(i=>Be.toWordJson(i)),captionMode:t.captionMode,captions:t.captions.map(i=>Be.toCaptionJson(i)),markerId:t.markerId,assetIds:r,dirty:Be.toClipDirtyJson(t.dirty),translationModified:Be.toTranslationModifiedJson(t.translationModified),id:n,videoTransform:t.videoTransform,backgroundId:t.backgroundId,transitionModel:t.transitionModel}};static toProjectPropsJson=t=>({tracks:Be.toTracksJson(t.trackEntries),assets:Be.toAssetsJson(t.baseAssetEntries),overdubInfos:t.overdubInfosMap,analyzeDate:t.analyzeDate,captionDisplayMode:t.captionDisplayMode,markerNames:t.markerNames,videoRatio:t.videoRatio,globalVideoTransform:t.globalVideoTransform,videoSize:t.videoSize,backgroundMap:t.backgroundMap,globalCaptionStyle:t.globalCaptionStyle,lastTTSSettings:t.lastTTSSettings?qV(t.lastTTSSettings):void 0,initProjectVideoSize:t.initProjectVideoSize,pronunciationDisplay:t.pronunciationDisplay,projectAudioLanguage:t.projectAudioLanguage,audioLanguagesMap:t.audioLanguagesMap,originalClips:t.originalClips.map(r=>Be.toClipJson(r,t.baseAssetEntries)),ttsClipInfosMap:Object.fromEntries(Object.entries(t.ttsClipInfosMap).map(([r,n])=>[r,{...n,speaker:JV(n.speaker)}])),denoiseMap:t.denoiseMap});static toFileJson=t=>{switch(t.type){case"AVMedia":return Be.toAVMediaFileJson(t);case"Image":return Be.toImageFileJson(t);case"Svg":return Be.toSvgFileJson(t);case"Html":return Be.toHtmlFileJson(t);default:throw new C(_.C_LOGIC_ERROR,{},"Invalid file type: "+JSON.stringify(t))}};static toSourceFileTypeJson=t=>{switch(t){case de.VIDEO_AUDIO:return ie.VIDEO_AUDIO;case de.IMAGE:return ie.IMAGE;case de.FILTER:return ie.FILTER;case de.BGM:return ie.BGM;case de.OVERDUB:return ie.OVERDUB;case de.ASSET_VIDEO:return ie.ASSET_VIDEO;case de.SOUND_EFFECT:return ie.SOUND_EFFECT;case de.TTS:return ie.TTS;case de.TTS_EFFECT:return ie.TTS_EFFECT;case de.TTS_DUBBING:return ie.TTS_DUBBING;case de.SHAPE:return ie.SHAPE;case de.TEXTBOX:return ie.TEXTBOX;default:return ie.INVALID}};static fromSourceFileTypeJson=t=>{switch(t){case ie.VIDEO_AUDIO:return de.VIDEO_AUDIO;case ie.IMAGE:return de.IMAGE;case ie.FILTER:return de.FILTER;case ie.BGM:return de.BGM;case ie.OVERDUB:return de.OVERDUB;case ie.ASSET_VIDEO:return de.ASSET_VIDEO;case ie.SOUND_EFFECT:return de.SOUND_EFFECT;case ie.TTS:return de.TTS;case ie.TTS_EFFECT:return de.TTS_EFFECT;case ie.TTS_DUBBING:return de.TTS_DUBBING;case ie.SHAPE:return de.SHAPE;case ie.TEXTBOX:return de.TEXTBOX;
1112default:return de.INVALID}};static toAVMediaFileJson=t=>{switch(t.fileLocation){case D.LOCAL:return{version:this.CURRENT_AVMEDIA_VERSION,mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,type:"AVMedia",videoAudioMetaInfo:t.videoAudioMetaInfo,visualAIGenerationMeta:t.visualAIGenerationMeta,sourceFileType:this.toSourceFileTypeJson(t.sourceType),fileLocation:D.LOCAL,path:t.path,relativePath:t.relativePath};case D.REMOTE:return{version:this.CURRENT_AVMEDIA_VERSION,mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,type:"AVMedia",videoAudioMetaInfo:t.videoAudioMetaInfo,visualAIGenerationMeta:t.visualAIGenerationMeta,sourceFileType:this.toSourceFileTypeJson(t.sourceType),fileLocation:D.REMOTE,url:t.url,proxyInfo:t.proxyInfo};case D.LOCAL_TMP:return{version:this.CURRENT_AVMEDIA_VERSION,mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,type:"AVMedia",videoAudioMetaInfo:t.videoAudioMetaInfo,visualAIGenerationMeta:t.visualAIGenerationMeta,sourceFileType:this.toSourceFileTypeJson(t.sourceType),fileLocation:D.LOCAL_TMP,path:t.path};case D.PACKAGED:return{version:this.CURRENT_AVMEDIA_VERSION,mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,type:"AVMedia",videoAudioMetaInfo:t.videoAudioMetaInfo,visualAIGenerationMeta:t.visualAIGenerationMeta,sourceFileType:this.toSourceFileTypeJson(t.sourceType),fileLocation:D.PACKAG
1112ED,path:t.path};case D.IN_MEMORY:return{version:this.CURRENT_AVMEDIA_VERSION,mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,type:"AVMedia",videoAudioMetaInfo:t.videoAudioMetaInfo,visualAIGenerationMeta:t.visualAIGenerationMeta,sourceFileType:this.toSourceFileTypeJson(t.sourceType),fileLocation:D.IN_MEMORY}}};static toImageFileJson=t=>{switch(t.fileLocation){case D.LOCAL:return{version:this.CURRENT_IMAGE_VERSION,mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,type:"Image",isTransparent:t.isTransparent,visualAIGenerationMeta:t.visualAIGenerationMeta,fileLocation:D.LOCAL,path:t.path,relativePath:t.relativePath};case D.REMOTE:return{version:this.CURRENT_IMAGE_VERSION,mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,type:"Image",isTransparent:t.isTransparent,visualAIGenerationMeta:t.visualAIGenerationMeta,fileLocation:D.REMOTE,url:t.url,proxyInfo:t.proxyInfo};case D.LOCAL_TMP:return{version:this.CURRENT_IMAGE_VERSION,mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,type:"Image",isTransparent:t.isTransparent,visualAIGenerationMeta:t.visualAIGenerationMeta,fileLocation:D.LOCAL_TMP,path:t.path};case D.PACKAGED:return{version:this.CURRENT_IMAGE_VERSION,mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,type:"Image",isTransparent:t.isTransparent,visualAIGenerationMeta:t.visualAIGenerationMeta,fileLocation:D.PACKAG
1112ED,path:t.path};case D.IN_MEMORY:return{version:this.CURRENT_IMAGE_VERSION,mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,type:"Image",isTransparent:t.isTransparent,visualAIGenerationMeta:t.visualAIGenerationMeta,fileLocation:D.IN_MEMORY}}};static toSvgFileJson=t=>{switch(t.fileLocation){case D.LOCAL:return{version:this.CURRENT_SVG_VERSION,mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,type:"Svg",fileLocation:D.LOCAL,path:t.path,relativePath:t.relativePath};case D.REMOTE:return{version:this.CURRENT_SVG_VERSION,mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,type:"Svg",fileLocation:D.REMOTE,url:t.url,proxyInfo:t.proxyInfo};case D.LOCAL_TMP:return{version:this.CURRENT_SVG_VERSION,mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,type:"Svg",fileLocation:D.LOCAL_TMP,path:t.path};case D.PACKAGED:return{version:this.CURRENT_SVG_VERSION,mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,type:"Svg",fileLocation:D.PACKAG
1112ED,path:t.path};case D.IN_MEMORY:return{version:this.CURRENT_SVG_VERSION,mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,type:"Svg",fileLocation:D.IN_MEMORY}}};static toHtmlFileJson=t=>{switch(t.fileLocation){case D.LOCAL:return{version:this.CURRENT_HTML_VERSION,mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,type:"Html",fileLocation:D.LOCAL,path:t.path,relativePath:t.relativePath};case D.REMOTE:return{version:this.CURRENT_HTML_VERSION,mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,type:"Html",fileLocation:D.REMOTE,url:t.url,proxyInfo:t.proxyInfo};case D.LOCAL_TMP:return{version:this.CURRENT_HTML_VERSION,mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,type:"Html",fileLocation:D.LOCAL_TMP,path:t.path};case D.PACKAGED:return{version:this.CURRENT_HTML_VERSION,mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,type:"Html",fileLocation:D.PACKAGED,path:t.path};case D.IN_MEMORY:return{version:this.CURRENT_HTML_VERSION,mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,type:"Html",fileLocation:D.IN_MEMORY}}};static convertCaptionStyleSetting=t=>({...t,assetEffectInfo:this.fromAssetEffectInfoJson(t.assetEffectInfo)});static fromCaptionJson=t=>t.map(o=>{const{text:r,style:n,height:a}=o;return{text:new Qt(r),style:n&&Be.convertCaptionStyleSetting(n),height:a}});static fromWordJson=t=>({id:t.id,text:t.text,timelineStart:pe(0),duration:pe(t.duration),playbackRate:ur(t.playbackRate),aligned:t.aligned,type:t.type,originalDuration:t.originalDuration,originalStartTime:t.originalStartTime,truncatedWords:t.truncatedWords.map(o=>Be.fromWordJson(o)),assetIds:t.assetIds.map(Je),hardcutWordMeta:t.hardcutWordMeta,pronunciation:t.pronunciation,freeze:t.type===Z.SPACER?t.freeze:void 0});static fromClipboardCopiedWordJson=t=>{const o={id:t.id,text:t.text,timelineStart:pe(0),duration:pe(t.duration),playbackRate:ur(t.playbackRate),aligned:t.aligned,type:t.type,originalDuration:t.originalDuration,originalStartTime:t.originalStartTime,truncatedWords:t.truncatedWords.map(r=>Be.fromWordJson(r)),assetIds:t.assetIds.map(Je),hardcutWordMeta:t.hardcutWordMeta,pronunciation:t.pronunciation,newline:t.newline};return t.type===Z.SPACER?{...o,freeze:t.freeze}:o};static fromClipJsonToGlobalClipModel=t=>({clipId:t.id,sceneId:t.sceneId,startPosition:0,words:t.words.map(o=>Be.fromWordJson(o)),assetIds:t.assetIds.map(Je),captionMode:t.captionMode,captions:Be.fromCaptionJson(t.captions),markerId:t.markerId,dirty:t.dirty,translationModified:t.translationModified,videoTransform:t.videoTransform,backgroundId:t.backgroundId,transitionModel:t.transitionModel});static fromAVMediaFileJson=t=>{const{fileLocation:o}=t;if(o===D.IN_MEMORY)return{type:"AVMedia",mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,fileLocation:D.IN_MEMORY,videoAudioMetaInfo:t.videoAudioMetaInfo,visualAIGenerationMeta:t.visualAIGenerationMeta,sourceType:this.fromSourceFileTypeJson(t.sourceFileType)};if(o===D.LOCAL)return{type:"AVMedia",mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,fileLocation:D.LOCAL,path:t.path,relativePath:t.relativePath,videoAudioMetaInfo:t.videoAudioMetaInfo,visualAIGenerationMeta:t.visualAIGenerationMeta,sourceType:this.fromSourceFileTypeJson(t.sourceFileType)};if(o===D.LOCAL_TMP)return{type:"AVMedia",mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,fileLocation:D.LOCAL_TMP,path:t.path,videoAudioMetaInfo:t.videoAudioMetaInfo,visualAIGenerationMeta:t.visualAIGenerationMeta,sourceType:this.fromSourceFileTypeJson(t.sourceFileType)};if(o===D.PACKAGED)return{type:"AVMedia",mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,fileLocation:D.PACKAG
1112ED,path:t.path,videoAudioMetaInfo:t.videoAudioMetaInfo,visualAIGenerationMeta:t.visualAIGenerationMeta,sourceType:this.fromSourceFileTypeJson(t.sourceFileType)};if(o===D.REMOTE)return{type:"AVMedia",mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,fileLocation:D.REMOTE,url:t.url,proxyInfo:t.proxyInfo,videoAudioMetaInfo:t.videoAudioMetaInfo,visualAIGenerationMeta:t.visualAIGenerationMeta,sourceType:this.fromSourceFileTypeJson(t.sourceFileType)};throw new C(_.C_VREW_FILE_INCOMPATIBLE_VERSION)};static fromImageFileJson=t=>{const{fileLocation:o}=t;if(o===D.IN_MEMORY)return{type:"Image",mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,fileLocation:D.IN_MEMORY,isTransparent:t.isTransparent??!1,visualAIGenerationMeta:t.visualAIGenerationMeta};if(o===D.LOCAL)return{type:"Image",mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,fileLocation:D.LOCAL,path:t.path,relativePath:t.relativePath,isTransparent:t.isTransparent??!1,visualAIGenerationMeta:t.visualAIGenerationMeta};if(o===D.LOCAL_TMP)return{type:"Image",mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,fileLocation:D.LOCAL_TMP,path:t.path,isTransparent:t.isTransparent??!1,visualAIGenerationMeta:t.visualAIGenerationMeta};if(o===D.PACKAGED)return{type:"Image",mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,fileLocation:D.PACKAG
1112ED,path:t.path,isTransparent:t.isTransparent??!1,visualAIGenerationMeta:t.visualAIGenerationMeta};if(o===D.REMOTE)return{type:"Image",mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,fileLocation:D.REMOTE,url:t.url,proxyInfo:t.proxyInfo,isTransparent:t.isTransparent??!1,visualAIGenerationMeta:t.visualAIGenerationMeta};throw new C(_.C_VREW_FILE_INCOMPATIBLE_VERSION)};static fromSvgFileJson=(t,o)=>{const{fileLocation:r}=t;if(r===D.IN_MEMORY)return{type:"Svg",mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,fileLocation:D.IN_MEMORY,rawSvg:o};if(r===D.LOCAL)return{type:"Svg",mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,fileLocation:D.LOCAL,path:t.path,relativePath:t.relativePath,rawSvg:o};if(r===D.LOCAL_TMP)return{type:"Svg",mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,fileLocation:D.LOCAL_TMP,path:t.path,rawSvg:o};if(r===D.PACKAGED)return{type:"Svg",mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,fileLocation:D.PACKAG
1112ED,path:t.path,rawSvg:o};if(r===D.REMOTE)return{type:"Svg",mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,fileLocation:D.REMOTE,url:t.url,proxyInfo:t.proxyInfo,rawSvg:o};throw new C(_.C_VREW_FILE_INCOMPATIBLE_VERSION)};static fromHtmlFileJson=(t,o)=>{const{fileLocation:r}=t;if(r===D.IN_MEMORY)return{type:"Html",mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,fileLocation:D.IN_MEMORY,rawHtml:o};if(r===D.LOCAL)return{type:"Html",mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,fileLocation:D.LOCAL,path:t.path,relativePath:t.relativePath,rawHtml:o};if(r===D.LOCAL_TMP)return{type:"Html",mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,fileLocation:D.LOCAL_TMP,path:t.path,rawHtml:o};if(r===D.PACKAGED)return{type:"Html",mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,fileLocation:D.PACKAGED,path:t.path,rawHtml:o};if(r===D.REMOTE)return{type:"Html",mediaId:t.mediaId,sourceOrigin:t.sourceOrigin,fileSize:t.fileSize,name:t.name,fileLocation:D.REMOTE,url:t.url,proxyInfo:t.proxyInfo,rawHtml:o};throw new C(_.C_VREW_FILE_INCOMPATIBLE_VERSION)};static fromFileJson=(t,o)=>{switch(t.type){case"AVMedia":return this.fromAVMediaFileJson(t);case"Image":return this.fromImageFileJson(t);case"Svg":{const r=o[t.mediaId];if(r===void 0)throw new C(_.C_MEDIA_BLOB_LOST);return this.fromSvgFileJson(t,r)}case"Html":{const r=o[t.mediaId];if(r===void 0)throw new C(_.C_MEDIA_BLOB_LOST);return this.fromHtmlFileJson(t,r)}default:throw new C(_.C_VREW_FILE_INCOMPATIBLE_VERSION)}};static toVrewMarkColorJson=t=>{switch(t){case mi.WHITE:return"WHITE";case mi.MINT:return"MINT";case mi.BLACK:return"BLACK"}};static toVrewMarkPositionJson=t=>{switch(t){case _i.TOP_LEFT:return"TOP_LEFT";case _i.TOP_RIGHT:return"TOP_RIGHT";case _i.BOTTOM_LEFT:return"BOTTOM_LEFT";case _i.BOTTOM_RIGHT:return"BOTTOM_RIGHT"}};static toVrewMarkInfoJson=t=>({version:this.CURRENT_WATERMARK_VERSION,color:Be.toVrewMarkColorJson(t.color),index:t.index,position:Be.toVrewMarkPositionJson(t.position)});static toShapeKeyJson=t=>{switch(t){case Ye.Line:return"line";case Ye.DashedLine:return"dashed-line";case Ye.Arrow:return"arrow";case Ye.DashedArrow:return"dashed-arrow";case Ye.DoubleArrow:return"double-arrow";case Ye.Cross:return"cross";case Ye.Square:return"square";case Ye.Triangle:return"triangle";case Ye.Oval:return"oval";case Ye.Deprecated_RoundedSquare:return"square"}};static fromShapeKeyJson=t=>{switch(t){case"line":return Ye.Line;case"dashed-line":return Ye.DashedLine;case"arrow":return Ye.Arrow;case"dashed-arrow":return Ye.DashedArrow;case"double-arrow":return Ye.DoubleArrow;case"cross":return Ye.Cross;case"square":return Ye.Square;case"triangle":return Ye.Triangle;case"oval":return Ye.Oval}};static fromEndBehaviorJson=t=>t==="freeze"?Fs.FREEZE:Fs.LOOP;static toTracksJson=t=>{const o={};return Object.entries(t).forEach(([r,n])=>{o[r]=Be.toTrackJson(n)}),o};static toTrackJson=t=>{switch(t.type){case z.IMAGE:{const o=t;return{trackId:o.trackId,mediaId:o.mediaId,xPos:o.xPos,yPos:o.yPos,height:o.height,width:o.width,rotation:o.rotation,filterEffect:o.filterEffect,zIndex:o.zIndex,type:Hr.IMAGE,originalWidthHeightRatio:o.originalWidthHeightRatio,importType:o.importType,stockSource:o.stockSource,kenburnsAnimationInfo:o.kenburnsAnimationInfo,assetEffectInfo:this.toAssetEffectInfoJson(o.assetEffectInfo),editInfo:o.editInfo?{crop:o.editInfo?.crop,opacity:o.editInfo?.opacity,flip:o.editInfo?.flip}:void 0,stats:o.stats?{fillType:o.stats.fillType,fillMenu:o.stats.fillMenu,rearrangeCount:o.stats.rearrangeCount,isImportedByNewClipOption:o.stats.isImportedByNewClipOption,isTransparent:o.stats.isTransparent,aiStylizedCaptionAssetId:o.stats.aiStylizedCaptionAssetId,sourceTemplateId:o.stats.sourceFramePackId,sourceTemplateName:o.stats.sourceTemplateName,isRemoveBackground:o.stats.isRemoveBackground}:void 0}}case z.LOTTIE:{const o=t;return{trackId:o.trackId,mediaId:o.mediaId,xPos:o.xPos,yPos:o.yPos,height:o.height,width:o.width,rotation:o.rotation,filterEffect:o.filterEffect,zIndex:o.zIndex,type:Hr.LOTTIE,heightScale:o.heightScale,widthScale:o.widthScale,frameRate:o.frameRate,data:o.data,frameLength:o.frameLength}}case z.WEB:{const o=t;return{trackId:o.trackId,mediaId:o.mediaId,xPos:o.xPos,yPos:o.yPos,height:o.height,width:o.width,rotation:o.rotation,filterEffect:o.filterEffect,zIndex:o.zIndex,type:Hr.WEB,deltas:o.deltas,loop:o.loop,durationSeconds:o.durationSeconds,importType:o.importType,enabledInlineTypes:o.enabledInlineTypes,customAttributes:o.customAttributes,assetEffectInfo:this.toAssetEffectInfoJson(o.assetEffectInfo),stats:o.stats?{styledInFloatingMenu:o.stats.styledInFloatingMenu,styledInPanel:o.stats.styledInPanel,sourceTemplateId:o.stats.sourceFramePackId,sourceTemplateName:o.stats.sourceTemplateName}:void 0,scaleFactor:o.scaleFactor}}case z.VIDEO:{const o=t;return{trackId:o.trackId,mediaId:o.mediaId,xPos:o.xPos,yPos:o.yPos,height:o.height,width:o.width,rotation:o.rotation,filterEffect:o.filterEffect,zIndex:o.zIndex,type:Hr.VIDEO,sourceIn:o.sourceIn,sourceOut:o.sourceOut,originalWidthHeightRatio:o.originalWidthHeightRatio,isTrimmable:o.isTrimmable,hasAlphaChannel:o.hasAlphaChannel,editInfo:o.editInfo?{crop:o.editInfo?.crop,opacity:o.editInfo?.opacity,flip:o.editInfo?.flip}:void 0,fillType:o.fillType,stats:o.stats?{sourceTemplateName:o.stats.sourceTemplateName}:void 0,endBehavior:o.endBehavior}}case z.SHAPE:{const o=t;return o.dimensionType===Tr.ONE?{trackId:o.trackId,mediaId:o.mediaId,xPos:o.xPos,yPos:o.yPos,height:o.height,width:o.width,rotation:o.rotation,filterEffect:o.filterEffect,zIndex:o.zIndex,type:Hr.SHAPE,dimensionType:Tr.ONE,stroke:o.stroke,hasHead:o.hasHead,shapeOfHead:o.shapeOfHead,stats:o.stats?{sourceTemplateId:o.stats.sourceFramePackId,sourceTemplateName:o.stats.sourceTemplateName}:void 0,assetEffectInfo:this.toAssetEffectInfoJson(o.assetEffectInfo)}:{trackId:o.trackId,mediaId:o.mediaId,xPos:o.xPos,yPos:o.yPos,height:o.height,width:o.width,rotation:o.rotation,filterEffect:o.filterEffect,zIndex:o.zIndex,type:Hr.SHAPE,dimensionType:Tr.TWO,shapeType:o.shapeType,shapeSource:Be.toShapeKeyJson(o.shapeSource),stroke:o.stroke,plane:o.plane,cornerRounding:o.cornerRounding,stats:o.stats?{sourceTemplateId:o.stats.sourceFramePackId,sourceTemplateName:o.stats.sourceTemplateName}:void 0,assetEffectInfo:this.toAssetEffectInfoJson(o.assetEffectInfo)}}case z.SIMPLE_CHARACTER:{const o=t,r=o.pose.isPreset?{isPreset:!0,presetType:o.pose.presetType,labelKey:o.pose.labelKey,silentMediaId:o.pose.silentMediaId,speakingMediaId:o.pose.speakingMediaId}:{isPreset:!1,customPoseId:o.pose.poseId,customName:o.pose.label,silentMediaId:o.pose.silentMediaId,speakingMediaId:o.pose.speakingMediaId};return{trackId:o.trackId,mediaId:o.mediaId,xPos:o.xPos,yPos:o.yPos,height:o.height,width:o.width,rotation:o.rotation,filterEffect:o.filterEffect,zIndex:o.zIndex,type:Hr.SIMPLE_CHARACTER,isPreset:o.isPreset,pose:r,isMouthApplied:o.isMouthApplied}}case z.WATERMARK:{const o=t;return{trackId:o.trackId,type:Hr.WATERMARK,mediaId:o.mediaId,xPos:o.xPos,yPos:o.yPos,height:o.height,width:o.width,rotation:o.rotation,filterEffect:o.filterEffect,vrewMarkInfo:Be.toVrewMarkInfoJson(o.vrewMarkInfo)}}case ze.TTSClip:case ze.VideoAudio:{const o=t;return{trackId:o.trackId,mediaId:o.mediaId,volume:o.volume,fade:o.fade,sourceIn:o.sourceIn,sourceOut:o.sourceOut,loop:o.loop,playbackRate:o.playbackRate,type:o.type}}case ze.SoundEffect:case ze.BGM:{const o=t;return{trackId:o.trackId,mediaId:o.mediaId,volume:o.volume,fade:o.fade,sourceIn:o.sourceIn,sourceOut:o.sourceOut,loop:o.loop,playbackRate:o.playbackRate,type:o.type,stats:o.stats?{sourceTemplateName:o.stats.sourceTemplateName}:void 0}}case ze.Overdub:{const o=t;return{trackId:o.trackId,mediaId:o.mediaId,volume:o.volume,fade:o.fade,sourceIn:o.sourceIn,sourceOut:o.sourceOut,loop:o.loop,playbackRate:o.playbackRate,type:o.type,overdubId:o.overdubId}}case ze.TTSEffect:case ze.TTSDubbing:{const o=t,r=Be.toTTSFileInfoJson(o.ttsFileInfo);return{trackId:o.trackId,mediaId:o.mediaId,volume:o.volume,fade:o.fade,sourceIn:o.sourceIn,sourceOut:o.sourceOut,loop:o.loop,playbackRate:o.playbackRate,type:o.type,ttsFileInfo:r}}default:{const o=t;throw new C(_.C_LOGIC_ERROR,{},"[toTrackJson] Unknown track type: "+JSON.stringify(o))}}};static fromAssetsJson=t=>{const o={};return Object.entries(t).forEach(([r,n])=>{o[Je(r)]={trackIds:n.trackIds.map(kr),role:n.role}}),o};static toAssetsJson=t=>{const o={};return Object.entries(t).forEach(([r,n])=>{o[r]={trackIds:n.trackIds,role:n.role}}),o};static fromVrewMarkInfoJson=t=>({color:Be.fromVrewMarkColorJson(t.color),index:t.index,position:Be.fromVrewMarkPositionJson(t.position)});static convStandardAudioType=t=>{switch(t){case"ttsClip":return ze.TTSClip;case"videoAudio":return ze.VideoAudio;case"soundEffect":return ze.SoundEffect;case"bgm":return ze.BGM}};static convOverdubAudioType=t=>{if(t==="overdub")return ze.Overdub};static convTtsAudioType=t=>{switch(t){case"ttsEffect":return ze.TTSEffect;case"ttsDubbing":return ze.TTSDubbing}};static fromTracksJson=t=>{const o=zn({});return Object.entries(t).forEach(([r,n])=>{o[kr(r)]=Be.fromTrackJson(n)}),o};static fromTrackJson=t=>{switch(t.type){case Hr.IMAGE:return{trackId:t.trackId,mediaId:t.mediaId,xPos:t.xPos,yPos:t.yPos,height:t.height,width:t.width,rotation:t.rotation,filterEffect:t.filterEffect?{filterMediaId:t.filterEffect.filterMediaId,alpha:ur(t.filterEffect.alpha)}:void 0,zIndex:t.zIndex,type:z.IMAGE,originalWidthHeightRatio:t.originalWidthHeightRatio,importType:t.importType,stockSource:t.stockSource,kenburnsAnimationInfo:t.kenburnsAnimationInfo,assetEffectInfo:this.fromAssetEffectInfoJson(t.asset
1112EffectInfo),editInfo:t.editInfo?{crop:t.editInfo.crop,opacity:t.editInfo.opacity,flip:t.editInfo.flip}:void 0,stats:t.stats?{fillType:t.stats.fillType,fillMenu:t.stats.fillMenu,rearrangeCount:t.stats.rearrangeCount,isImportedByNewClipOption:t.stats.isImportedByNewClipOption,isTransparent:t.stats.isTransparent,aiStylizedCaptionAssetId:t.stats.aiStylizedCaptionAssetId,sourceFramePackId:t.stats.sourceTemplateId,sourceTemplateName:t.stats.sourceTemplateName,isRemoveBackground:t.stats.isRemoveBackground}:void 0};case Hr.LOTTIE:return{trackId:t.trackId,mediaId:t.mediaId,xPos:t.xPos,yPos:t.yPos,height:t.height,width:t.width,rotation:t.rotation,filterEffect:t.filterEffect?{filterMediaId:t.filterEffect.filterMediaId,alpha:ur(t.filterEffect.alpha)}:void 0,zIndex:t.zIndex,type:z.LOTTIE,heightScale:t.heightScale,widthScale:t.widthScale,frameRate:t.frameRate,data:t.data,frameLength:t.frameLength};case Hr.WEB:return{trackId:t.trackId,mediaId:t.mediaId,xPos:t.xPos,yPos:t.yPos,height:t.height,width:t.width,rotation:t.rotation,filterEffect:t.filterEffect?{filterMediaId:t.filterEffect.filterMediaId,alpha:ur(t.filterEffect.alpha)}:void 0,zIndex:t.zIndex,type:z.WEB,deltas:t.deltas,loop:t.loop,durationSeconds:t.durationSeconds,importType:t.importType,enabledInlineTypes:t.enabledInlineTypes,customAttributes:t.customAttributes,assetEffectInfo:this.fromAssetEffectInfoJson(t.assetEffectInfo),stats:t.stats?{styledInFloatingMenu:t.stats.styledInFloatingMenu,styledInPanel:t.stats.styledInPanel,sourceFramePackId:t.stats.sourceTemplateId,sourceTemplateName:t.stats.sourceTemplateName}:void 0,scaleFactor:t.scaleFactor};case Hr.VIDEO:return{trackId:t.trackId,mediaId:t.mediaId,xPos:t.xPos,yPos:t.yPos,height:t.height,width:t.width,rotation:t.rotation,filterEffect:t.filterEffect?{filterMediaId:t.filterEffect.filterMediaId,alpha:ur(t.filterEffect.alpha)}:void 0,zIndex:t.zIndex,type:z.VIDEO,sourceIn:pe(t.sourceIn),sourceOut:pe(t.sourceOut),originalWidthHeightRatio:t.originalWidthHeightRatio,isTrimmable:t.isTrimmable,hasAlphaChannel:t.hasAlphaChannel,editInfo:t.editInfo?{crop:t.editInfo.crop,opacity:t.editInfo.opacity,flip:t.editInfo.flip}:void 0,fillType:t.fillType,stats:t.stats?{sourceTemplateName:t.stats.sourceTemplateName}:void 0,endBehavior:Be.fromEndBehaviorJson(t.endBehavior)};case Hr.SHAPE:return t.dimensionType===Tr.ONE?{trackId:t.trackId,mediaId:t.mediaId,xPos:t.xPos,yPos:t.yPos,height:t.height,width:t.width,rotation:t.rotation,filterEffect:t.filterEffect?{filterMediaId:t.filterEffect.filterMediaId,alpha:ur(t.filterEffect.alpha)}:void 0,zIndex:t.zIndex,type:z.SHAPE,dimensionType:Tr.ONE,stroke:t.stroke,hasHead:t.hasHead,shapeOfHead:t.shapeOfHead,stats:t.stats?{sourceFramePackId:t.stats.sourceTemplateId,sourceTemplateName:t.stats.sourceTemplateName}:void 0,assetEffectInfo:this.fromAssetEffectInfoJson(t.assetEffectInfo)}:{trackId:t.trackId,mediaId:t.mediaId,xPos:t.xPos,yPos:t.yPos,height:t.height,width:t.width,rotation:t.rotation,filterEffect:t.filterEffect?{filterMediaId:t.filterEffect.filterMediaId,alpha:ur(t.filterEffect.alpha)}:void 0,zIndex:t.zIndex,type:z.SHAPE,dimensionType:Tr.TWO,shapeType:t.shapeType,shapeSource:Be.fromShapeKeyJson(t.shapeSource),stroke:t.stroke,plane:t.plane,cornerRounding:t.cornerRounding,stats:t.stats?{sourceFramePackId:t.stats.sourceTemplateId,sourceTemplateName:t.stats.sourceTemplateName}:void 0,assetEffectInfo:this.fromAssetEffectInfoJson(t.assetEffectInfo)};case Hr.SIMPLE_CHARACTER:{const o=t.pose.isPreset?{isPreset:!0,presetType:t.pose.presetType,labelKey:t.pose.labelKey,silentMediaId:t.pose.silentMediaId,speakingMediaId:t.pose.speakingMediaId}:{isPreset:!1,poseId:t.pose.customPoseId,label:t.pose.customName,silentMediaId:t.pose.silentMediaId,speakingMediaId:t.pose.speakingMediaId};return{trackId:t.trackId,mediaId:t.mediaId,xPos:t.xPos,yPos:t.yPos,height:t.height,width:t.width,rotation:t.rotation,filterEffect:t.filterEffect?{filterMediaId:t.filterEffect.filterMediaId,alpha:ur(t.filterEffect.alpha)}:void 0,zIndex:t.zIndex,type:z.SIMPLE_CHARACTER,isPreset:t.isPreset,isMouthApplied:t.isMouthApplied,pose:o}}case Hr.WATERMARK:return{trackId:t.trackId,mediaId:t.mediaId,xPos:t.xPos,yPos:t.yPos,height:t.height,width:t.width,rotation:t.rotation,filterEffect:t.filterEffect?{filterMediaId:t.filterEffect.filterMediaId,alpha:ur(t.filterEffect.alpha)}:void 0,type:z.WATERMARK,vrewMarkInfo:Be.fromVrewMarkInfoJson(t.vrewMarkInfo)};case"ttsClip":case"videoAudio":return{trackId:t.trackId,mediaId:t.mediaId,volume:t.volume,fade:t.fade,sourceIn:t.sourceIn,sourceOut:t.sourceOut,loop:t.loop,playbackRate:t.playbackRate,type:Be.convStandardAudioType(t.type)};case"soundEffect":case"bgm":return{trackId:t.trackId,mediaId:t.mediaId,volume:t.volume,fade:t.fade,sourceIn:t.sourceIn,sourceOut:t.sourceOut,loop:t.loop,playbackRate:t.playbackRate,type:Be.convStandardAudioType(t.type),stats:t.stats?{sourceTemplateName:t.stats.sourceTemplateName}:void 0};case"overdub":return{trackId:t.trackId,mediaId:t.mediaId,volume:t.volume,fade:t.fade,sourceIn:t.sourceIn,sourceOut:t.sourceOut,loop:t.loop,playbackRate:t.playbackRate,type:Be.convOverdubAudioType(t.type),overdubId:t.overdubId};case"ttsEffect":case"ttsDubbing":return{trackId:t.trackId,mediaId:t.mediaId,volume:t.volume,fade:t.fade,sourceIn:t.sourceIn,sourceOut:t.sourceOut,loop:t.loop,playbackRate:t.playbackRate,type:Be.convTtsAudioType(t.type),ttsFileInfo:Be.fromTTSInfoJson(t.ttsFileInfo)};default:{const o=t;throw new C(_.C_LOGIC_ERROR,{},"Unknown track type: "+JSON.stringify(o))}}};static convTTSLang=t=>{switch(t){case"en-US":return ft.English;case"ko-KR":return ft.Korean;case"ja-JP":return ft.Japanese;case"zh-CN":return ft.Chinese;case"es-ES":return ft.Spanish;case"zh-TW":return ft.Taiwanese}};static convTTSSpeaker=t=>{const o=a=>{switch(a){case"google":return Oe.Google;case"clova":return Oe.Clova;case"kt":return Oe.KT;case"vrewva":case"vrew":return Oe.Vrew;case"usertts":return Oe.UserTTS;case"wemakevoice":return Oe.Wemakevoice_deprecated;case"voicevox":return Oe.Voicevox;case"polly":return Oe.Polly;case"elevenlabs":return Oe.Elevenlabs;case"gemini":return Oe.Gemini;case"typecast":return Oe.Typecast}},r=a=>{switch(a){case"all":return Fd.All;case"male":return Fd.Male;case"female":return Fd.Female}};return{age:(a=>{switch(a){case"all":return gs.All;case"child":return gs.Child;case"elderly":return gs.Elderly;case"middle":return gs.Middle;case"teenage":return gs.Teenage;case"youth":return gs.Youth}})(t.age),gender:r(t.gender),lang:Be.convTTSLang(t.lang),name:t.name,speakerId:t.speakerId,provider:o(t.provider),badge:t.badge,emotions:t.emotions,actingOptions:t.actingOptions,versions:t.versions,free:t.free,tags:t.tags}};static toTTSFileInfoJson=t=>({duration:t.duration,speaker:Be.toTTSSpeakerJson(t.speaker),volume:t.volume,speed:t.speed,pitch:t.pitch,emotion:t.emotion,emotionIntensity:t.emotionIntensity,acting:t.acting,effect:t.effect,version:t.version,text:Be.toTTSTextJson(t.text),errorInfo:t.errorInfo?{msg:t.errorInfo.msg,msgArg:t.errorInfo.msgArg,reason:t.errorInfo.reason}:void 0});static fromTTSInfoJson=t=>({duration:t.duration,pitch:t.pitch,speed:t.speed,volume:t.volume,emotion:t.emotion,emotionIntensity:t.emotionIntensity,acting:t.acting,effect:t.effect,version:t.version,text:Be.fromTTSTextJson(t.text),speaker:Be.convTTSSpeaker(t.speaker),errorInfo:t.errorInfo?Be.fromTTSErrorInfoJson(t.errorInfo):void 0});static toTTSSpeakerJson=t=>{const o=i=>{switch(i){case Oe.Google:return"google";case Oe.Clova:return"clova";case Oe.KT:return"kt";case Oe.Vrew:return"vrew";case Oe.UserTTS:return"usertts";case Oe.Wemakevoice_deprecated:return"wemakevoice";case Oe.Voicevox:return"voicevox";case Oe.Polly:return"polly";case Oe.Elevenlabs:return"elevenlabs";case Oe.Gemini:return"gemini";case Oe.Typecast:return"typecast";default:throw new C(_.C_LOGIC_ERROR,{},"Unknown TTS provider: "+i)}},r={[Fd.All]:"all",[Fd.Male]:"male",[Fd.Female]:"female"},n={[ft.English]:"en-US",[ft.Korean]:"ko-KR",[ft.Japanese]:"ja-JP",[ft.Chinese]:"zh-CN",[ft.Spanish]:"es-ES",[ft.Taiwanese]:"zh-TW"},a={[gs.All]:"all",[gs.Child]:"child",[gs.Elderly]:"elderly",[gs.Middle]:"middle",[gs.Teenage]:"teenage",[gs.Youth]:"youth"};return{name:t.name,speakerId:t.speakerId,provider:o(t.provider),gender:r[t.gender],lang:n[t.lang],age:a[t.age],emotions:t.emotions,actingOptions:t.actingOptions,versions:t.versions,badge:t.badge,tags:t.tags,free:t.free}};static toTTSTextJson=t=>({processed:t.processed,raw:t.raw,textAspectLang:Be.convTTSLang(t.textAspectLang)});static fromTTSTextJson=t=>({processed:t.processed,raw:t.raw,textAspectLang:Be.convTTSLang(t.textAspectLang)});static fromTTSErrorInfoJson=t=>{if(!t)return;const o=t.reason;switch(o){case nr.AUTH:case nr.LOW_VERSION:case nr.SPEAKER_DELET
1112ED:case nr.NETWORK:case nr.API_NETWORK:case nr.NOT_COMPLETED:case nr.DIFFERENT_LANG:case nr.INVALID_INPUT:case nr.TIMEOUT:case nr.PRICING_CHANGED:case nr.UNKNOWN:return{msg:t.msg,msgArg:t.msgArg,reason:o};default:return}};static fromLastTTSSettingJson=t=>{if(t)return{...t,speaker:Be.convTTSSpeaker(t.speaker)}};static fromVrewMarkColorJson=t=>{switch(t){case"WHITE":return mi.WHITE;case"MINT":return mi.MINT;case"BLACK":return mi.BLACK}};static fromVrewMarkPositionJson=t=>{switch(t){case"TOP_LEFT":return _i.TOP_LEFT;case"TOP_RIGHT":return _i.TOP_RIGHT;case"BOTTOM_LEFT":return _i.BOTTOM_LEFT;case"BOTTOM_RIGHT":return _i.BOTTOM_RIGHT;default:return _i.TOP_LEFT}};static fromClipboardJson=t=>{const{copiedWords:o,copiedClips:r,copiedElements:n}=t;return{copiedWords:o.map(a=>Be.fromClipboardCopiedWordJson(a)),copiedGlobalClips:r.map(a=>Be.fromClipJsonToGlobalClipModel(a)),copiedElements:Be.fromCopiedMediaElementsJson(n)}};static toClipboardJson=(t,o)=>{const{copiedWords:r,copiedGlobalClips:n,copiedElements:a}=t;return{copiedWords:r.map(i=>Be.toClipboardCopiedWordJson(i)),copiedClips:n.map(i=>Be.toClipJson(i,o)),copiedElements:Be.toCopiedMediaElementsJson(a)}};static fromCopiedMediaElementsJson=t=>t.map(o=>Be.fromCopiedMediaElementJson(o));static fromCopiedMediaElementJson=t=>({elementId:Je(t.elementId),mediaId:t.mediaId,type:t.type});static toCopiedMediaElementsJson=t=>t.map(o=>Be.toCopiedMediaElementJson(o));static toCopiedMediaElementJson=t=>({elementId:t.elementId,mediaId:t.mediaId,type:t.type});static fromGlobalCaptionStyleSettingJson=t=>({...t,captionStyleSetting:{...t.captionStyleSetting,assetEffectInfo:Be.fromAssetEffectInfoJson(t.captionStyleSetting.assetEffectInfo)}});static fromOverdubInfosJson=t=>Object.fromEntries(Object.entries(t).map(([o,r])=>[Je(o),{originWords:r.originWords.map(n=>({...n,duration:pe(n.duration)}))}]));static fromTtsClipInfosJson=t=>Object.fromEntries(Object.entries(t).map(([o,r])=>[o,Be.fromTTSInfoJson(r)]))}const $R=async(e,t)=>{if(!await Vn("onClickDownloadBackUpProject"))return;await yr(_.C_LOGIN_REQUIRED_ERROR,"Login is required to download project.",h("downloadModal.ts"));const o=Lt().getUserPlanStatusForVcloud();if(o==="FREE"){Y().openModal(st.NEED_PLAN_UPGRADE,{premiumFeatureType:Ut.VCLOUD});return}e.type==="DIRECT_DOWNLOAD"&&r4(e.projectId)||(Y().openModal(st.CLOUD_BACKUP_DOWNLOAD,{userPlanStatusForVcloud:o,info:e,returnTo:t}),k7(),F7())},eA=async e=>{const t=Y(),r=Lt().getCloudProjects().find(u=>u.scheduledDeletionDate!==void 0)?.scheduledDeletionDate,a=Fe()!==ce.English,{type:i}=e,s=u=>{if(u.name==="span"&&u.attribs?.class==="vcloud-download")return b.jsx("span",{className:"vcloud-download",onClick:async()=>{t.closeLastShownMessage(),i==="open"&&e.callback?.(),await $R({type:"SELECT_PROJECT"},"OPEN_PROJECT")},style:{cursor:"pointer"},children:u.children?.[0]?.data})},x=b.jsxs(Xe,{direction:"column",gap:16,css:{userSelect:"none"},children:[b.jsx(Nt,{css:{color:ee.gray[850],fontWeight:400,fontSize:16,lineHeight:"24px"},children:i==="save"?Wc(A("vcloud.save_project_restricted_refund_desc")):A("vcloud.open_project_restricted_refund_desc")}),r&&b.jsxs(Xe,{gap:8,align:"center",color:ee.gray[650],bg:ee.gray[50],p:16,radius:16,css:{fontWeight:400,fontSize:14,lineHeight:"20px"},children:[b.jsx(fn,{src:Oy,w:20,h:20,maskColor:ee.gray[300]}),b.jsx(Nt,{css:{whiteSpace:"break-spaces"},children:Wc(A("vcloud.popup_refund_expired_at",{date:vx(r,!1,a?{dateStyle:"long"}:void 0)}),{transform:s})})]})]}),c={bodyClassName:"general-modal",headerClassName:"premium",title:A("vcloud.refund_warning_popup_title"),content:x,confirmTextFrontIconClassName:"upgrade-plan",yesStr:A("vcloud.alert_upgrade"),noStr:i==="save"?A("popup.cancel"):A("vcloud.download_project")},l=u=>{const p=be().getUserInfo()?.paidPlanInfo;wUe(p?.planType??"FREE");const f=be().getUserInfo()?.uid;if(f===void 0){h("modal.tsx").error("uid is undefined");return}u?.(),AT(f,{source:g.LIMIT_POPUP,origin:{type:"premium_feature",premiumFeatureType:Ut.VCLOUD}})},d=await t.popup(c);switch(i){case"open":d===mt.YES?l(e.callback):d===mt.NO&&await $R({type:"DIRECT_DOWNLOAD",projectId:e.projectId},"OPEN_PROJECT");break;
1112case"save":d===mt.YES&&l();break}},Ent=async()=>{const e=Y(),t={bodyClassName:"general-modal",title:A("vcloud.open_project_restricted_downgrade_title"),content:A("vcloud.open_project_restricted_downgrade_desc"),yesStr:A("vcloud.clean_up_space"),noStr:A("vcloud.download_project")};return await e.popup(t)},mnt=async e=>{const t=Y(),o={bodyClassName:"general-modal",title:A(e),content:`${A("vcloud.warn_abort")}`,yesStr:A("popup.confirm"),noStr:A("popup.cancel")};return await t.popup(o)},t_e=async()=>{const e=Y(),t={bodyClassName:"general-modal",title:A("vcloud.warn_project_delete_title"),content:`${A("vcloud.warn_project_delete_desc")}`,yesStr:A("popup.delete_project"),noStr:A("popup.cancel"),confirmButtonColor:"red-button"};return await e.popup(t)},o_e=async e=>{const t=Y(),o={bodyClassName:"general-modal",title:A("vcloud.warn_bulk_project_delete_title",{count:e}),content:A("vcloud.warn_bulk_project_delete_desc",{count:e}),yesStr:A("popup.delete_project"),noStr:A("popup.cancel"),confirmButtonColor:"red-button"};return await t.popup(o)},hnt=e=>e===1?t_e():o_e(e),r_e=async()=>{const e={bodyClassName:"general-modal",title:A("vcloud.project_save_failed_title"),content:A("vcloud.project_save_failed_desc"),yesStr:A("popup.confirm")};return await Y().popup(e)},n_e=async()=>{const e={bodyClassName:"general-modal",title:A("vcloud.project_already_opened_title"),content:A("vcloud.project_already_opened_de
1112sc"),yesStr:A("vcloud.force_acquire_editing_session"),extraStr:A("popup.cancel")};return await Y().popup(e)},Int=async()=>{const e={bodyClassName:"general-modal",title:A("vcloud.project_already_opened_title"),content:A("error.vcloud_session_conflict"),yesStr:A("popup.confirm")};return await Y().popup(e)},r4=e=>!Oo()&&Lt().isV1CloudProject(e)?(Y().popup(nz(A("vcloud.migrate_cloud_project_warning_desc"))),!0):!1;class gc extends ad.EventEmitter{static instance;cloudProjects=[];initializingProjects=new Map;initAttempts=new Map;static MAX_INIT_ATTEMPTS=3;eventEmitter=new ad.EventEmitter;_uploads=new Map;backgroundUploadCloseHandler=null;withUploadLimit=e_e();withProxyUploadLimit=tf(5);withMediaCacheWriteLimit=tf(10);pendingMediaCacheWrites=0;accessContexts=new Map;temporalProjectId=null;sharedToken=null;constructor(){super()}initialize=()=>{se().getEventEmitter().on(co.VREW_FILE_OPENED,t=>{t!==this.temporalProjectId&&this.resetSharedProject()}).on(co.NEWFILE,(t,o,r)=>{r&&this.resetSharedProject()}).on(co.TMP_PROJECT_OPENED,()=>{this.resetSharedProject()}).on(co.MEDIA_READY_FOR_CLOUD_UPLOAD,t=>{this.handleCloudUploadEvent(t)})};handleCloudUploadEvent=async t=>{const{mediaId:o,blob:r,fileInfo:n,projectId:a,onComplete:i,onError:s}=t,x=this._uploads.get(o);if(x){try{const u=await x.future.promise();await i(u)}catch{s(!0)}return}const c=new Ns;c.promise().catch(u=>{h("VcloudManager.ts").info("[handleCloudUploadEvent] Future rejected for mediaId: "+o+", error: "+P(u))});const l={mediaId:o,fileSize:r.size,fileName:n.name,abortController:new AbortController,future:c},d=this.shouldShowUploadProgress(n);Mo().getDebugVal(Xt.CONTROL_VCLOUD_STATUS);try{const u=await this.executeMediaUpload(l,r,n,a,d);await i(u)}catch(u){const p=Ne(u)&&u.errorCode===_.C_VCLOUD_USER_UPLOAD_CANCELED;s(p),!p&&h("VcloudManager.ts").error("[handleCloudUploadEvent] Upload failed for mediaId: "+o+", error: "+P(u))}finally{this.maybeRemoveBackgroundUploadCloseHandler()}};static getInstance=()=>(!gc.instance&&(gc.instance=new gc),gc.instance);setTemporalProjectId=t=>{this.temporalProjectId=t};getTemporalProjectId=()=>this.temporalProjectId;resetSharedProject=()=>{this.setSharedToken(null),this.setTemporalProjectId(null),this.initializingProjects.clear(),this.initAttempts.clear()};setSharedToken=t=>{this.sharedToken=t};getSharedToken=()=>this.sharedToken;getCloudProjects=()=>this.cloudProjects;getEventEmitter=()=>this.eventEmitter;isEditableCloudProject=t=>t?Lt().getCloudProjects().some(r=>r.projectId===t&&r.version>=WE):!1;isV1CloudProject=t=>Lt().getCloudProjects().some(r=>r.projectId===t&&r.version<WE);redeemProject=async t=>{await W7(t);const{projectInfo:o,accessContext:r}=await MOe(t);this.setAccessContext(t,r),this.cloudProjects.push(o),this.temporalProjectId=t};syncCloudProjects=async()=>{const t=h("VcloudManager.ts");try{if(!be().getUserInfo()){t.info("No idToken or uid at syncCloudProjects. Skip"),this.cloudProjects=[],this.getEventEmitter().emit(mm.SYNC_PROJECTS);return}const{projectInfos:r,usedSpace:n}=await DOe();t.info("Total "+r.length+" projects found on cloud."),r.length>0&&t.info("Total "+r.length+" projects found on cloud. usedSpace : "+jr(n));const a=r.map(i=>{const{projectInfo:s}=i,{projectId:x,projectTitle:c,created:l,lastModified:d,totalSize:u,uploadCount:p,downloadCount:f,deletionAlertStatus:E,lastDeletionAlertSentAt:T,scheduledDeletionDate:O,snapshotId:S,version:R,sessionId:y,deleted:v,deletionScheduledDate:w}=s;return{projectId:x,projectTitle:c,created:l,lastModified:d,totalSize:u,uploadCount:p,downloadCount:f,deletionAlertStatus:E,lastDeletionAlertSentAt:T,scheduledDeletionDate:O,snapshotId:S,version:R,sessionId:y,deleted:v,deletionScheduledDate:w}});this.cloudProjects=a,r.forEach(i=>{const{projectInfo:s,accessContext:x}=i;this.setAccessContext(s.projectId,{role:x.role,accessMethod:x.accessMethod})}),this.getEventEmitter().emit(mm.SYNC_PROJECTS)}catch(o){h("VcloudManager.ts").error("error while loading cloudProjectList:"+P(o));return}};deleteCloudProject=async t=>{const o=Lt().getVCloudProjectInfo(t);if(!o)throw new C(_.C_VCLOUD_PROJECT_INFO_NOT_FOUND);const r=se().getProjectId();if(r===t)throw h("VcloudManager.ts").error("Cannot delete current project. currentProjectId: "+r+", projectId: "+t),new C(_.C_VCLOUD_DELETE_ERROR);await _D(t),vUe(o),await this.syncCloudProjects(),Ht(So.CLOUD_CACHE).removeDir(X_(t))};deleteCloudProjects=async t=>{const o=h("VcloudManager.ts"),r=se().getProjectId(),n=t.filter(c=>c!==r);if(n.length===0)return{succeeded:[],failed:[]};const a=tf(5),i=await Promise.allSettled(n.map(c=>a(()=>_D(c)))),s=[],x=[];
1112i.forEach((c,l)=>{c.status==="fulfilled"?s.push(n[l]):(x.push(n[l]),o.error("failed to delete cloud project "+n[l]+": "+P(c.reason)))}),await this.syncCloudProjects();for(const c of s)Ht(So.CLOUD_CACHE).removeDir(X_(c));return{succeeded:s,failed:x}};renameCloudProject=async(t,o)=>{const r=Lt().getVCloudProjectInfo(t);if(!r)throw h("VcloudManager.ts").error("[renameCloudProject] Project not found in local cache: "+t),new C(_.C_VCLOUD_PROJECT_INFO_NOT_FOUND);await GOe(t,o),AUe(r),await this.syncCloudProjects()};getVCloudProjectInfo=t=>this.cloudProjects.find(o=>o.projectId===t);isCloudProjectInitializedOrInitializing=t=>!!this.getVCloudProjectInfo(t)||this.initializingProjects.has(t);downloadCloudProject=async(t,o,r,n,a,i,s=!1)=>{const x=h("VcloudManager.ts"),c=async()=>{const l=ql(zr("vcloud.download_user_cancel"));return await Y().popup(l)===mt.YES?(i&&(i.abort(),await $h(n)),Ts.OK):Ts.CANCEL};pt().addCloseHandler(c);try{const l=this.getVCloudProjectInfo(o);if(!l){const p="cannot get cloud project info for projectId : "+o+", projectName : "+r;return x.error(p),{result:"error",errorCode:_.C_VCLOUD_PROJECT_INFO_NOT_FOUND,msg:p}}if(RUe(l),l.version<WE){const p=await UOe(o);return p.result==="error"?(x.error("cannot get download info for projectId : "+o+", projectName : "+r),p):await uie(t,p.downloadInfo,o,r,n,l.totalSize,a,i)}const d=await av(o,l.snapshotId);if(!d)throw x.error("[Downloading] : snapshotJson is null. projectId:"+o+", snapshotId:"+l.snapshotId),new C(_.C_VCLOUD_DOWNLOAD_ERROR);if(d.version>Be.CURRENT_VREW_JSON_VERSION)throw new C(_.C_VREW_FILE_INCOMPATIBLE_VERSION);return await cie(t,d,o,r,n,l.totalSize,a,i,s)}finally{pt().removeCloseHandler(c)}};migrateV1CloudProject=async t=>{const o=h("VcloudManager.ts"),{projectId:r,target:n}=t;o.info("[migrateCloudProjectV1] start. projectId: "+t.projectId);const a=be().getUserInfo()?.uid;if(a===void 0)throw h("VcloudManager.ts").error("uid is undefined"),new C(_.A_AUTH_GERNAL_ERROR);const i=async()=>{const x=ql(zr("vcloud.upload_user_cancel"));return await Y().popup(x)===mt.YES?(t.abortCtrl&&(t.abortCtrl.abort(),await zf({projectId:r,action:"error"})),Ts.OK):Ts.CANCEL};pt().addCloseHandler(i);const s=new Jo;try{if(Oo()&&!await H0(V.TRANSCODING_VIDEO))throw h("VcloudManager.ts").info("FFMPEG not found, skipping upload"),new C(_.C_ENCODING_USER_CANCELED);OUe(t.cloudProjectInfo,n),n==="current"?await zge(r,t.vrewFileData,t.abortCtrl,a,t.observer,t.currentProjectSize,t.migrateId):await Hge(r,t.cloudProjectInfo.snapshotId,t.abortCtrl,a,t.observer,t.currentProjectSize,t.migrateId),await this.syncCloudProjects(),se().notifySaved();const c=pe(s.getElapsedSec());fk(t.cloudProjectInfo,n,c,"success")}catch(x){const c=ye(x)??_.C_VCLOUD_UPLOAD_ERROR;if(c===_.C_ENCODING_USER_CANCELED)throw h("VcloudManager.ts").info("vcloud upload canceled. errCode: ",c),new C(c);const l=pe(s.getElapsedSec());if(fk(t.cloudProjectInfo,n,l,"error"),await zf({projectId:r,action:"error"}),h("VcloudManager.ts").info("[migrateV1CloudProject] remove dir for projectId in opfs: "+r),Ht(So.CLOUD_CACHE).removeDir(X_(r)),t.abortCtrl.signal.aborted||c===_.C_VCLOUD_USER_UPLOAD_CANCELED)throw h("VcloudManager.ts").info("User canceled uploading."),new C(c);const d="Upload failed for projectId: "+r+" error: "+P(x);throw h("VcloudManager.ts").error(d),new C(c)}finally{pt().removeCloseHandler(i)}};uploadCloudProject=async(t,o,r,n,a,i,s,x)=>{const c=h("VcloudManager.ts"),l=Cn(10),d=be().getUserInfo()?.uid,u={...a,files:await j5(a)};if(d===void 0)throw h("VcloudManager.ts").error("uid is undefined"),new C(_.A_AUTH_GERNAL_ERROR);const p=Object.fromEntries(u.files.map(S=>[S.mediaId,S.fileSize])),f=c_e(u),E=se().getProjectId(),T=async()=>{const S=ql(zr("vcloud.upload_user_cancel"));return await Y().popup(S)===mt.YES?(s&&(s.abort(),await JO({projectId:o,uploadType:r})),Ts.OK):Ts.CANCEL};pt().addCloseHandler(T),c.info("start to upload cloud project. uploadId:"+t+", projectId:"+o+", uploadType:"+r+", uploadTitle:"+n+", currProjectId:"+E),CUe({projectId:o,uploadType:r,filemetrics:f,sourceProjectId:E});const O=new Jo;try{if(Oo()&&!await H0(V.TRANSCODING_VIDEO))throw h("VcloudManager.ts").info("FFMPEG not found, skipping upload"),new C(_.C_ENCODING_USER_CANCELED);if(r==="copy"){await Oge({uploadId:t,newProjectId:o,uploadTitle:n,snapshotId:l,currentProjectSize:x,observer:i,mediaFileSizes:p,abortCtrl:s,originalVrewFileData:a,uploadableVrewFileData:u,uid:d,currProjectId:E});const N=pe(O.getElapsedSec());c.info("upload cloud project success. elapsedTimeSec: "+N),fC({projectId:o,uploadType:r,filemetrics:f,elapsedTimeSec:N,result:"success",sourceProjectId:E}),await this.syncCloudProjects(),se().notifySaved(),hx({status:"saved"});return}await gA({projectId:o,projectTitle:n,snapshotId:l,uploadType:"new",ver
1112sion:Uf});const R=u0(x,p,Gs.UPLOAD,i);eI(o);const y=await qH(u,o,s,R,d),v=qg(a,y,!1);await Cu(v,l,o,s),R(!0,!1),await _A({projectId:o,totalSize:x});const w=pe(O.getElapsedSec());c.info("upload cloud project success. elapsedTime: "+w),fC({projectId:o,uploadType:r,filemetrics:f,elapsedTimeSec:w,result:"success",sourceProjectId:E}),await this.syncCloudProjects(),se().notifySaved(),hx({status:"saved"});return}catch(S){const R=ye(S)??_.C_VCLOUD_UPLOAD_ERROR;if(R===_.C_ENCODING_USER_CANCELED)throw h("VcloudManager.ts").info("vcloud upload canceled. errCode: ",R),new C(R);const y=pe(O.getElapsedSec());if(fC({projectId:o,uploadType:r,filemetrics:f,elapsedTimeSec:y,result:"error",sourceProjectId:E}),await JO({projectId:o,uploadType:r}),h("VcloudManager.ts").info("[uploadCloudProject] remove dir for projectId in opfs: "+o),Ht(So.CLOUD_CACHE).removeDir(X_(o)),s.signal.aborted||R===_.C_VCLOUD_USER_UPLOAD_CANCELED)throw c.info("User canceled uploading."),new C(R);const v="Upload failed for projectId: "+o+", uploadType: "+r+", error: "+P(S);throw c.error(v),new C(R)}finally{pt().removeCloseHandler(T)}};getUserPlanStatusForVcloud=()=>{const t=this.cloudProjects.reduce((o,r)=>o+r.totalSize,0);try{const o=be().getUserInfo()?.paidPlanInfo;return o?t>o.cloudStorageLimit?"DOWNGRADE":"UPGRADE":t>0?"REFUND":"FREE"}catch(o){return h("VcloudManager.ts").error("getUserPlanStatusForVcloud failed: "+P(o)),"FREE"}};initializeNewCloudProject=async(t,o,r)=>{const n=h("VcloudManager.ts");n.info("[initializeNewCloudProject] Starting for: "+t);try{const a=Cn(10);await gA({projectId:t,projectTitle:o,snapshotId:a,uploadType:"new",version:Uf});const{totalSize:i}=await Cu(r,a,t);await _A({projectId:t,totalSize:i}),await this.syncCloudProjects(),n.info("[initializeNewCloudProject] Project created: "+t),await ol(t);const s=sessionStorage.getItem(Wt.VCLOUD_SESSION_ID),x=s??Cn();!s&&sessionStorage.setItem(Wt.VCLOUD_SESSION_ID,x),await M7(t,x)}catch(a){throw n.error("[initializeNewCloudProject] Failed: "+t,P(a)),await JO({projectId:t,uploadType:"new"}),a}};lazyInitializeCloudProject=async(t,o)=>{const r=h("VcloudManager.ts");if(this.getVCloudProjectInfo(t))return!1;const n=this.initAttempts.get(t)??0;if(n>=gc.MAX_INIT_ATTEMPTS)return r.info("[lazyInit] Skipping init after "+n+" failed attempts: "+t),!1;const a=this.initializingProjects.get(t);if(a){r.info("[lazyInit] Waiting for pending init: "+t);try{await a}catch(s){r.warn("[lazyInit] Pending init failed: "+t,P(s))}return!1}const i=this.executeCloudProjectInit(t,o);this.initializingProjects.set(t,i);try{return await i,!0}catch(s){return r.warn("[lazyInit] Init failed for project: "+t,P(s)),!1}};executeCloudProjectInit=async(t,o)=>{const r=h("VcloudManager.ts");try{const n=Q1(),a=Qwe(n||hy);await this.initializeNewCloudProject(t,a,o),this.initAttempts.delete(t)}catch(n){const a=(this.initAttempts.get(t)??0)+1;throw this.initAttempts.set(t,a),r.warn("[lazyInit] Failed (attempt "+a+"/"+gc.MAX_INIT_ATTEMPTS+"): "+t,P(n)),n}finally{this.initializingProjects.delete(t)}};ensureCloudProjectInitialized=async(t,o)=>{const r=h("VcloudManager.ts"),n=await this.lazyInitializeCloudProject(t,o),a=this.getVCloudProjectInfo(t);if(!a)return r.info("[ensureCloudProjectInitialized] failed: "+t),{status:"failed"};const i=n?"new":"existing";return r.info("[ensureCloudProjectInitialized] "+i+": "+t),{status:i,projectTitle:a.projectTitle}};ensureEditingSessionAndSync=async t=>{if(!await wo())throw h("VcloudManager.ts").error("[ensureSession] missing idToken"),new C(_.A_AUTH_GERNAL_ERROR);const o=sessionStorage.getItem(Wt.VCLOUD_SESSION_ID);if(!o)throw h("VcloudManager.ts").error("[ensureSession] missing clientSessionId"),new C(_.C_VCLOUD_SESSION_ERROR);try{await D7(t,o),h("VcloudManager.ts").info("[ensureSession] session renewed")}catch(r){if(Ne(r)&&r.errorCode===_.C_VCLOUD_SESSION_CONFLICT){h("VcloudManager.ts").info("[ensureSession] session conflict"),qz(t,"save"),await r_e();const n="[ensureSession] error occurred while renewing editing session. projectId: "+t+", error: "+P(r);throw h("VcloudManager.ts").error(n),new C(_.C_VCLOUD_SESSION_ERROR,{},n)}}};saveVrewJsonToCloud=async(t,o)=>{const r=Cn(10);try{hx({status:"saving"});const{snapshotRegistered:n}=await Cu(t,r,o);return se().notifySaved(),n?r:void 0}catch(n){if(Ne(n)&&n.errorCode===_.C_VCLOUD_PROJECT_TOO_LARGE)throw n;const a="error occurred while uploading vrew json to cloud. projectId: "+o+", error: "+P(n);
1112throw h("VcloudManager.ts").error(a),new C(_.C_VCLOUD_UPLOAD_ERROR,{},a)}finally{hx({status:"saved"})}};getInProgressMediaIds=()=>Array.from(this._uploads.keys());hasOngoingCloudOperations=()=>this._uploads.size>0||this.initializingProjects.size>0||this.pendingMediaCacheWrites>0;isMediaInProgress=t=>this._uploads.has(t);resolveFuture=(t,o)=>{const r=this._uploads.get(t);r&&(r.future.resolve(o),this._uploads.delete(t)),this.emit(fc.REMOVE,t)};rejectFuture=(t,o,r=!1)=>{const a=this._uploads.get(t);if(a&&(a.future.reject(o),this._uploads.delete(t)),r){this.emit(fc.REMOVE,t);return}this.emit(fc.UPLOAD_FAIL,t),setTimeout(()=>{!this._uploads.has(t)&&this.emit(fc.REMOVE,t)},1e4)};removeUpload=t=>{this._uploads.delete(t)};abortRequest=t=>{const o=this._uploads.get(t);o&&o.abortController.abort(),this.rejectFuture(t,new C(_.C_VCLOUD_USER_UPLOAD_CANCELED),!0)};abortAllUploads=()=>{this.getInProgressMediaIds().forEach(t=>{this.abortRequest(t)})};cancelUploadsForDeletedAssets=(t,o,r)=>{l4(t,o,r).filter(n=>this.isMediaInProgress(n)).forEach(n=>this.abortRequest(n))};createProgressHandler=(t,o)=>{const r={updateProgress:(n,a)=>{this.emit(fc.UPDATE_PROGRESS,t,a.progressRatio)}};return u0(o,{[t]:o},Gs.UPLOAD,r)};shouldCreateProxy(t){return Zr(t)}shouldShowUploadProgress(t){return t.fileSize>OZ}createUploadProgressCallback(t,o,r,n){return(a,i)=>{const s=i>0?a/i*n:0;r(!1,!1,{mediaId:t,type:ha(o),progressRatio:s})}}createProxyCreator(t,o,r,n){return async a=>await $w({...a,onProgressUpdate:r?i=>{r(!1,!1,{mediaId:t,type:ha(o),progressRatio:n+i*Iy})}:void 0})}prepareUploadCallbacks(t){const{mediaId:o,ext:r,fileInfo:n,needProxy:a,shouldShowProgress:i}=t;if(!a)return{uploadChunkProgressCallback:i?this.createUploadProgressCallback(o,r,this.createProgressHandler(o,n.fileSize),1):void 0,proxyCreator:void 0};const s=_u;if(i){const x=this.createProgressHandler(o,n.fileSize);return{uploadChunkProgressCallback:this.createUploadProgressCallback(o,r,x,s),proxyCreator:this.createProxyCreator(o,r,x,s)}}return{uploadChunkProgressCallback:void 0,proxyCreator:this.createProxyCreator(o,r)}}async executeMediaUpload(t,o,r,n,a){const{mediaId:i,abortController:s}=t;if(this._uploads.set(i,t),a&&(this.emit(fc.ADD,i),!Qh(Ur.VCLOUD)&&Qy(Ur.VCLOUD,void 0)),this.ensureBackgroundUploadCloseHandler(),s.signal.aborted)throw new C(_.C_VCLOUD_USER_UPLOAD_CANCELED);const x=yo(r.name),c=Ws(i,x),l=DR(o)?void 0:this.cacheMediaLocally(ul(n,i,x),o),d={mediaId:i,remotePath:c,targetType:"media",projectId:n,name:r.name,uploadSourceType:"blob",blob:o,shouldNotCache:!0},u=this.shouldCreateProxy(r),{uploadChunkProgressCallback:p,proxyCreator:f}=this.prepareUploadCallbacks({mediaId:i,ext:x,fileInfo:r,needProxy:u,shouldShowProgress:a}),E=new Jo;s1e(o.size);try{const T=()=>this.withUploadLimit(o.size,()=>{if(s.signal.aborted)throw new C(_.C_VCLOUD_USER_UPLOAD_CANCELED);return _ge({uploadData:d,fileInfo:r,abortController:s,uploadChunkProgressCallback:p,proxyCreator:f})}),O=u?await this.withProxyUploadLimit(T):await T();mk({fileSize:o.size,elapsedTimeSec:pe(E.getElapsedSec()),result:"success"});const S={...O,cacheWriteFailed:await l===!1};return this.resolveFuture(i,S),S}catch(T){throw mk({fileSize:o.size,elapsedTimeSec:pe(E.getElapsedSec()),result:"error"}),!s.signal.aborted&&this.rejectFuture(i,T),T}finally{this.maybeRemoveBackgroundUploadCloseHandler()}}async cacheMediaLocally(t,o){this.pendingMediaCacheWrites++;try{return await this.withMediaCacheWriteLimit(async()=>await Ht(So.CLOUD_CACHE).getFileAsBlob(t)?!0:Nae(t,o.stream()))}catch(r){return h("VcloudManager.ts").warn("[cacheMediaLocally] Failed to read blob: "+t,P(r)),!1}finally{this.pendingMediaCacheWrites--,this.maybeRemoveBackgroundUploadCloseHandler()}}ensureBackgroundUploadCloseHandler(){this.backgroundUploadCloseHandler===null&&(this.backgroundUploadCloseHandler=Iie,pt().addCloseHandler(this.backgroundUploadCloseHandler))}maybeRemoveBackgroundUploadCloseHandler(){this.backgroundUploadCloseHandler!==null&&!this.hasOngoingCloudOperations()&&(pt().removeCloseHandler(this.backgroundUploadCloseHandler),this.backgroundUploadCloseHandler=null)}setAccessContext=(t,o)=>{this.accessContexts.set(t,o)};getAccessContext=t=>this.accessContexts.get(t)}const Lt=gc.getInstance;var Gs=(e=>(e.UPLOAD="UPLOAD",e.DOWNLOAD="DOWNLOAD",e))(Gs||{});const Ws=(e,t)=>gg+"/"+e+"/"+e+"."+t,n4=(e,t)=>
1112e+"/"+k1+"/"+t,a_e=(e,t,o,r)=>n4(e,t)+"/"+Ws(o,r),a4=(e,t,o)=>{const r=n4(t,o)+"/";return e.startsWith(r)?e.substring(r.length):e},i4=(e,t)=>gg+"/"+e+"/"+IZ+"/"+e+"."+t,Tnt=(e,t)=>e+"/"+t+"/"+t+".vrew",i_e=e=>{const t={progress:[A("vcloud.download_progress_1"),A("vcloud.download_progress_2")],almostDone:A("vcloud.backup_download_long_almost_done")},o={progress:[A("vcloud.upload_progress_1"),A("vcloud.upload_progress_2")],almostDone:A("vcloud.backup_upload_long_almost_done")};let r=Date.now(),n=0;const a=3e3,i=(s,x)=>{const c=Date.now(),l=c-r,d=x.progress;if(s)return x.almostDone;if(l>a){n+=1;const u=n%d.length;return r=c,d[u]}return d[0]};return e==="UPLOAD"?s=>i(s,o):s=>i(s,t)},s_e=(e,t,o,r,n)=>{const a=!!(r&&r<5),i=o(a);return e?n==="UPLOAD"?A("vcloud.upload_error"):A("vcloud.backup_download_error"):t?n==="UPLOAD"?A("vcloud.upload_done"):A("vcloud.backup_download_done"):i},s4=(e,t,o,r,n)=>{let a=0,i=0;if(e){const{mediaId:s,progressRatio:x}=e,c=t[s]??0,l=c/(o||c||1);r[s]=x*l;for(const u of Object.keys(r))a+=r[u];i=n.supply(a)}else for(const s of Object.keys(r))a+=r[s];return{progressSum:a,remainSec:i}},dT=(e,t,o)=>(e.totalFileCounts++,t<1e6?e.fileCountsUnder1MB++:t<1e7?e.fileCountsUnder10MB++:t<1e8?e.fileCountsUnder100MB++:t<1e9?e.fileCountsUnder1GB++:t<1e10?e.fileCountsUnder10GB++:e.fileCountsOver10GB++,o==="media"?e.totalMediaFileSize+=t:o==="source"?e.totalSourceFileSize+=t:o==="snapshot"&&(e.snapshotSize+=t),e),tN=()=>({totalFileCounts:0,fileCountsUnder1MB:0,fileCountsUnder10MB:0,fileCountsUnder100MB:0,fileCountsUnder1GB:0,fileCountsUnder10GB:0,fileCountsOver10GB:0,snapshotSize:0,totalMediaFileSize:0,totalSourceFileSize:0}),u0=(e,t,o,r,n,a)=>{const i=new u2(10),s=i_e(o);i.start();const x={};return(c,l,d)=>{const u=n??0,p=a??1,{progressSum:f,remainSec:E}=s4(d,t,e,x,i),T=u+(p-u)*f,O={progressRatio:T,isDone:c,isError:!!l,remainSec:E>0?E:void 0},S=s_e(!!l,c,s,E,o);r?.updateProgress(S,O)}},x4=(e,t,o)=>{const r=(t-e)/1e3,n=o/r,a=n*8,i=a/1e6;return Math.floor(i)},Snt=e=>e.replace(/[\s.]+$/,""),x_e=e=>e.reduce((t,o)=>t+o.totalSize,0),ha=e=>{const t=yo(e);return Lh.includes(t)?"video":h6.includes(t)?"audio":sg.includes(t)?"image":I6.test(e)?"json":"etc"},Ont=async()=>{if(!await be().fetchUserInfo())return{vcloudProjectsCount:0,usedStorage:0,totalStorage:0};await Lt().syncCloudProjects();const t=Lt().getCloudProjects().length,o=x_e(Lt().getCloudProjects()),r=be().getUserInfo()?.paidPlanInfo?.cloudStorageLimit??0;return{vcloudProjectsCount:t,usedStorage:o,totalStorage:r}},c4=async e=>{const o=e.slice(0,131072),r=e.slice(e.size>131072?e.size-131072:0,e.size),n=new Uint8Array(await o.arrayBuffer()),a=new Uint8Array(await r.arrayBuffer()),i=new Uint8Array(8);new DataView(i.buffer).setBigUint64(0,BigInt(e.size),!0);const x=new Uint8Array(n.byteLength+a.byteLength+i.byteLength);x.set(n,0),x.set(a,n.byteLength),x.set(i,n.byteLength+a.byteLength);const c=await crypto.subtle.digest("SHA-256",x);return Array.from(new Uint8Array(c)).map(d=>d.toString(16).padStart(2,"0")).join("")},uT=e=>{const t=/\/projects\/([^/]+)\/media\/([^/]+)\/\2\.(\w+)$/,o=e.match(t);if(!o)return null;const[,r,n,a]=o;return{projectId:r,mediaId:n,ext:a}},oN=async(e,t,o,r)=>{const n=uT(e);if(n===null)return null;const a=Ws(n.mediaId,n.ext),i=await Nd(o??n.projectId,{methodType:t,name:a},r);return i.result!==t||!("url"in i)?null:i.url},rN=async(e,t)=>{const o=h("util.ts"),r=t??se().getProjectId();if(!r)return o.warn("Project id not found for "+e),null;const n=uT(e);if(!n)return o.warn("Failed to extract media id and ext from "+e),null;const{mediaId:a,ext:i}=n,s=Ws(a,i),x=await oN(e,"HEAD",r);if(x===null)return o.warn("Failed to get head signed url for "+s),null;try{const c=await fetch(x,{method:"HEAD"});if(c.status===404)return o.info("File not found for "+s+". cloudProjectId: "+r+", mediaId: "+a+", ext: "+i),null;if(!c.ok)return o.warn("Failed to check file already uploaded for "+s),null;const l=decodeURIComponent(c.headers.get(iL)??"");return l||(o.warn("Orig filename not found for "+s+" "+c.headers.get(iL)),Vr()?a+"."+i:null)}catch(c){return o.warn("Failed to get cloud source file orig name for "+s+": "+P(c)),null}},Cnt=(e,t)=>
1112{const o=t>0?e/t:0;return A("vcloud.usage_info",{used:jr(e),total:jr(t),ratio:Math.round(o*100)})},c_e=e=>{const t={totalFileCounts:0,fileCountsUnder1MB:0,fileCountsUnder10MB:0,fileCountsUnder100MB:0,fileCountsUnder1GB:0,fileCountsUnder10GB:0,fileCountsOver10GB:0,snapshotSize:0,totalMediaFileSize:0,totalSourceFileSize:0};e.files.forEach(n=>{const a=n.fileSize;t.totalFileCounts++,a<1e6?t.fileCountsUnder1MB++:a<1e7?t.fileCountsUnder10MB++:a<1e8?t.fileCountsUnder100MB++:a<1e9?t.fileCountsUnder1GB++:a<1e10?t.fileCountsUnder10GB++:t.fileCountsOver10GB++,Zr(n)?t.totalSourceFileSize+=a:t.totalMediaFileSize+=a});const o=JSON.stringify(j2(e)),r=BU.byteLength(o,"utf-8");return t.snapshotSize=r,t},tA=e=>Lt().getAccessContext(e.projectId)?.accessMethod==="PERSISTENT",Rnt=e=>e.reduce((t,o)=>o.broken?t:t+(o.fileSize||0),0),l4=(e,t,o)=>{const r=new Set(o),n=Object.entries(t),a=new Set(n.flatMap(([s,x])=>r.has(Je(s))?x.trackIds.map(c=>L.get(e,c)?.mediaId).filter(Se):[])),i=new Set(n.flatMap(([s,x])=>r.has(Je(s))?[]:x.trackIds.map(c=>L.get(e,c)?.mediaId).filter(Se)));return[...a].filter(s=>!i.has(s))},nN=100*1024*1024;class Oi{tempFiles=new Set;tempFolders=[];basePath;setBasePath=t=>this.basePath=t;getBasePath=()=>this.basePath;getTempFileName=async(t,o,r,n)=>{const a=await(await ae())("fs.tempfile",{extension:t,filenamePrefix:o,basePath:this.basePath,noUuid:r});return!n&&this.tempFiles.add(a),a};createTempFolder=async t=>{const o=await(await ae())("fs.tempfolder",{basePath:this.basePath});return this.tempFolders.push({tempFolder:o,exts:t}),o};clear=async t=>{for(const o of t)this.tempFiles.delete(o);try{await(await ae())("fs.delete",{names:t})}catch(o){for(const r of t)this.tempFiles.add(r);throw o}};clearAll=async()=>{await(await ae())("fs.delete",{names:Array.from(this.tempFiles)}),this.tempFiles.clear();for(const t of this.tempFolders)await(await ae())("fs.deleteFolder",{path:t.tempFolder})}}class l_e{cachedAllowGa=null;autosavePath;addFile=async(t,o,r)=>{const n={name:t,data:o,encoding:r};return(await ae())("fs.put",n,void 0,void 0,{silentArg:!0})};listDir=async t=>(await ae())("fs.listDir",{path:t});links=async t=>(await ae())("fs.links",t);putMediaCache=async(t,o,r)=>{const n={mediaId:t,mediaCacheEntry:{blobData:await o.arrayBuffer(),ext:r}};return(await ae())("fs.putMediaCache",n,void 0,void 0,{silentArg:!0})};putLocalCache=async t=>{const o=await ae(),r=h("local.ts"),{blob:n,url:a,pathInfo:i,ext:s,mediaId:x,overWrite:c}=t;if(n===void 0&&a===void 0&&i===void 0)throw new C(_.C_LOGIC_ERROR,void 0,"data and url and path are undefined in local cache.");let l,d;if(n)if(n.size<nN)d=await n.arrayBuffer();else try{const f=x+"_"+Cn()+"."+s,E=await o("fs.createFileForStream",{fileName:f});r.info("path created for writeStream : "+E);let T=0;const O=n.stream();for await(const S of vb(O))await o("fs.writeChunkToFile",{path:E,chunk:S.buffer,offset:T}),T+=S.byteLength;await o("fs.finalizeStream",{path:E}),r.info("finalizeStream for "+E),l=E}catch(f){throw r.error("putLocalCache stream write error for "+x+" ("+n.size+"): "+P(f)),h("local.ts").error("Failed to create file for stream: "+P(f)),f}const u=i?{path:i.path,method:i.preserveOriginal?"copy":"move"}:l?{path:l,method:"move"}:void 0;return o("fs.putLocalCache",{mediaId:x,ext:s,url:a,data:d,pathInfo:u,overWrite:c},void 0,void 0,{silentArg:!0})};clearOldLocalCache=async()=>{(await ae())("fs.clearOldLocalCache")};loadProjectFile=async t=>{const o=await ae(),{mainJson:r,fileSize:n,mediaEntries:a}=await o("fs.loadProjectMeta",{path:t}),i={},s={};let x=a.map(c=>c.mediaId);for(;x.length>0;){const{buffers:c,exts:l,remainingIds:d,pathUpdates:u}=await o("fs.loadProjectBuffers",{path:t,mediaIds:x});Object.entries(c).forEach(([p,f])=>{i[p]=new Blob([f],{type:X0.getType(l[p])??pf})}),Object.assign(s,l),r.files.forEach(p=>{p.mediaId in u&&(p.path=u[p.mediaId])}),x=d}return{mainJson:r,exts:s,blobs:i,fileSize:n}};putProjectFile=async t=>(await(await ae())("fs.putProject",t,void 0,void 0,{silentArg:!0})).size;cancelPutProjectFile=async t=>{await(await ae())("fs.cancelPutProject",t)};saveFramePackFile=async t=>{await(await ae())("fs.saveFramePack",t)};loadFramePackFile=async t=>{const o=await(await ae())("fs.loadFramePackFile",{path:t}),{mainJson:r,buffers:n}=o,a={};
1112return Object.entries(n).forEach(([i,s])=>{const{buffer:x,mimeType:c}=s,l=new Blob([x],{type:c});a[i]={blob:l,mimeType:c}}),{mainJson:r,blobs:a}};deleteFramePackFile=async t=>{await(await ae())("fs.deleteFramePack",t)};loadLocalFramePackFiles=async()=>{const{framePacks:t}=await(await ae())("fs.loadLocalFramePack");return t.map(({mainJson:o,buffers:r})=>{const n={};return Object.entries(r).forEach(([a,i])=>{const{buffer:s,mimeType:x}=i,c=new Blob([s],{type:x});n[a]={blob:c,mimeType:x}}),{mainJson:o,blobs:n}})};createVrewFileForVCloudProject=async t=>{await(await ae())("fs.createVrewFileFromCloudDownload",t,void 0,void 0,{silentArg:!0})};deleteFiles=async t=>(await ae())("fs.delete",{names:t});downloadFile=async(t,o,r,n,a)=>(await ae())("fs.download",{url:t,path:o,downloadId:n,logLabel:a},r);abortDownload=async t=>(await ae())("fs.abortDownload",{downloadId:t});showOpenDialog=async(t,o,r,n,a,i)=>{const s=await(await ae())("fs.showopen",{mediaTypes:t,mediaDesc:o,title:r,defaultPath:n,openDirectory:a});return s&&s[0]&&!i&&QO(a?s[0].name:ti(s[0].name)),s?s[0]:null};async writeStreamFileToLocal(t,o,r,n){const a=await ae(),i=h("local.ts"),s=await t.getFile(),x=s.name,c=o?o.endsWith(jx.sep)?jx.join(o,x):o:void 0;let l;try{l=await a("fs.createFileForStream",{fileName:x,destPath:c,periodicSync:n}),i.info("path created for writeStream : "+l);let d=0;const u=s.size;let p=-1;const f=s.stream();for await(const E of vb(f))if(await a("fs.writeChunkToFile",{path:l,chunk:E.buffer,offset:d}),d+=E.byteLength,r&&u>0){const T=Math.floor(d*100/u);T>p&&(p=T,r(T))}return await a("fs.finalizeStream",{path:l}),i.info("finalizeStream for "+l),r&&u>0&&p<100&&r(100),{name:l}}catch(d){throw i.error("writeStreamFileToLocal error : "+d),l&&await a("fs.finalizeStream",{path:l,cancel:!0}),d}}showOpenDialogImportMultipleFiles=async(t,o,r,n,a)=>{const i=await(await ae())("fs.showopen",{mediaTypes:t,mediaDesc:o,title:r,defaultPath:n,openDirectory:a,multiSelections:!0});return i&&QO(a?i[0].name:ti(i[0].name)),i??[]};showOpenDialogWithMultiFiles=async(t,o,r,n,a)=>{const i=await this.showOpenDialogImportMultipleFiles(t,o,r,n,a);return i?i.map(({name:s})=>({path:s})):null};showSaveDialog=async(t,o,r)=>{const n=await(await ae())("fs.showsave",{mediaType:t,title:o,recommandPath:r});return n.name&&QO(ti(n.name)),n};getAvailableDiskSpace=async()=>await(await ae())("fs.getAvailableDiskSpace");checkAllowGa=async()=>{if(this.cachedAllowGa!==null)return this.cachedAllowGa;const t=await(await ae())("fs.check_allow_ga");return this.cachedAllowGa=t,t};setAllowGa=async t=>(this.cachedAllowGa={kind:t?"allow":"deny"},(await ae())("fs.updateGaAllow",{allow:t}));getInitFile=async()=>{const t=await(await ae())("fs.getInitFile");return this.autosavePath=t.autosaveFilePath,t};getExclusiveName=async t=>(await ae())("fs.getExclusiveName",{filePath:t});openFolder=async t=>(await ae())("fs.openFolder",{path:t});createFolder=async(t,o)=>(await ae())("fs.createFolder",{basePath:t,folderName:o});existsFile=async t=>(await ae())("fs.existsFile",{path:t});existsFolder=async t=>(await ae())("fs.existsFolder",{path:t});setOpenVrewFile=async t=>(await ae())("fs.setOpenVrewFile",{path:t});getExistingFiles=async t=>(await ae())("fs.getExistingFiles",{paths:t});updateAutosaveTargetPath=async t=>(await ae())("fs.updateAutosaveTargetPath",{path:t});cleanupRestoreFile=async t=>(await ae())("fs.cleanupRestoreFile",{usedFiles:t});cleanupBackupFiles=async()=>(await ae())("fs.cleanupBackupFiles");getTotalBackupSize=async()=>(await ae())("fs.getTotalBackupSize");getTotalProxySize=async()=>(await ae())("fs.getTotalProxySize");getTempStorageConfig=async()=>(await ae())("fs.getTempStorageConfig");setTempStoragePath=async t=>(await ae())("fs.setTempStoragePath",{absolutePath:t});prepareImageFiles=async(t,o)=>{const r={},n=/image\/([-\w.]+)/;for(const a of o){const i=a.blob,s=i.type.match(n),x=s?s[1]:await Bs(i),c=await t.getTempFileName(x||void 0);await this.addFile(c,await i.arrayBuffer(),"binary"),r[a.mediaId]=c}return r};prepareMainAudioFiles=async(t,o)=>{const r={};for(const n of o){const a=n.blob,i=n.videoAudioMetaInfo.audioInfo?.codec,s=await t.getTempFileName(i);await this.addFile(s,await a.arrayBuffer(),"binary"),r[n.mediaId]=s}return r};prepareFilterFileByEffect=async(t,o,r)=>{const n=r.find(c=>c.mediaId===o.filterMediaId)?.blob;if(!n)throw new C(_.C_LOGIC_ERROR,{},"Failed to prepare lut, mediaId "+o.filterMediaId);const a=await V2(n),i=await t.getTempFileName("cube"),s=o.alpha,x=o.filterMediaId+"_"+s;return(await ae())("fs.createCubeFile",{lutImageData:a,filterPath:i,title:x,alpha:s})};cubeToPng=async t=>(await ae())("fs.cubeToPng",{cubePath:t});lockFile=async t=>(await ae())("fs.lockFile",{path:t},void 0,void 0,{silent:!0});releaseFile=async t=>(await ae())("fs.releaseFile",{path:t},void 0,void 0,{silent:!0});getProcessArgv=async()=>(await ae())("fs.getProcessArgv");getSameSizeFile=async(t,o)=>(await ae())("fs.getSameSizeFile",{dirPath:t,fileSize:o});getFileInfo=async t=>(await ae())("fs.getFileInfo",{filePath:t});getFileInfos=async t=>(await ae())("fs.getFileInfos",{filePaths:t});getFileCrc32=async t=>(await ae())("fs.getFileCrc32",{filePath:t});copyFile=async(t,o)=>(await ae())("fs.copyFile",{from:t,to:o});
1112tempFolder=async t=>(await ae())("fs.tempfolder",{basePath:t});deleteFolder=async t=>(await ae())("fs.deleteFolder",{path:t});countFiles=async t=>(await ae())("fs.countFiles",{path:t});saveFile=async(t,o,r)=>{if(r==="")throw new C(_.C_LOGIC_ERROR,void 0,"format is empty for saveFile");const n=typeof t=="function"?await t():t,a=await n.arrayBuffer(),i=zu(o+"."+r,!0),s=await fb(i,r,o);if(s==="")return h("local.ts").info("User canceled saving blob"),{result:!1};try{return await this.addFile(s,a,"binary"),{result:!0,path:mu(s)}}catch(x){throw h("local.ts").error("Error during saving blob "+s+": "+P(x)),Ne(x)?x:new C(_.C_SAVE_FILE_FAILED)}};readFile=async t=>(await ae())("fs.readFile",{path:t});deleteLocalStorage=async()=>(localStorage.clear(),(await ae())("fsTypes.deleteLocalStorage"));printFsSummary=async()=>(await ae())("fs.printFsSummary");selectMultipleTypesOfFiles=async t=>{try{return await this.showOpenDialogImportMultipleFiles(t,void 0,A("filetype.video"),U2())}catch(o){if(no(o))return[];throw Ne(o)?o:(h("local.ts").warn("selectMultipleTypesOfFilesError",P(o)),new C(_.C_SELECT_IMAGE_OR_VIDEO_FILES_ERROR,{},Jx(o)))}};checkUserVideoValidPath=async t=>!!await(await ae())("fs.existsFile",{path:t});getDownLoadsPath=async()=>{const t=Mt(ke.DOWNLOADS_DIR);if(t)return t;const o=await(await ae())("fs.getDownloadsPath");return po(ke.DOWNLOADS_DIR,o),o};getAutosavePath=()=>this.autosavePath;getCurrentProjectFileInfo=()=>{const t=se(),o=t.getCurrentProjectFileType(),r=o===Ee.CLOUD,n=o===Ee.PROJECT||o===Ee.CLOUD,a=t.getCurrentProjectPath(),i=t.getProjectId(),s=r&&i?Lt().getVCloudProjectInfo(i)?.projectTitle||"-":gt(a),x=r?"-":wb(a)||"-";return{isSaved:n,path:a,fileName:s,dir:x}};getSourceFileInfoForDiagnostic=async t=>{const o=h("local.ts"),r=t.videoAudioMetaInfo?.videoInfo;if(!r)return o.error("MediaVideoInfo could not be found. MediaId: : "+t.mediaId),null;const n=I0(r.size),a=cRe(n.width,n.height),i=Math.floor(t.fileSize*8/t.videoAudioMetaInfo.duration/1e3),s=t.videoAudioMetaInfo.videoInfo?.colorSpace,x=t.name,c=t.fileLocation===D.LOCAL?t.path:t.fileLocation===D.REMOTE?await rN(t.url,void 0)??"_":"_",l=t.fileLocation===D.LOCAL?wb(c):"-";return{mediaId:t.mediaId,path:c,fileName:x,duration:os(t.videoAudioMetaInfo.duration),size:jr(t.fileSize),videoSize:a,dir:l,frame:r.frameRate,bitrate:i??0,colorSpace:s??""}};getCacheExtInfos=async()=>(await ae())("fs.getCacheExtInfos");filterLocalTmpMediaIds=t=>{const o=W2().filter(n=>n.fileLocation===D.LOCAL_TMP).map(n=>n.mediaId),r=new Set(o);return t.filter(n=>r.has(n))};restoreLocalCache=async t=>{const o=this.filterLocalTmpMediaIds(t);return await(await ae())("fs.restoreLocalCache",{mediaIds:o})};getAlreadyExistMediaId=async t=>await(await ae())("fs.getAlreadyExistMediaid",t);async getFilePath(t){if(!window.api)throw new C(_.C_LOGIC_ERROR,{},"electron api is not available");return Array.isArray(t)?window.api.fs.getFilePath(t):(await window.api.fs.getFilePath([t]))[0]}initializeProxy=async()=>(await ae())("fs.initializeProxy");cleanupProxyFiles=async()=>(await ae())("fs.cleanupProxyFiles")}let MO;const yn=()=>(MO===void 0&&(MO=new l_e),MO),Ant=()=>at()||typeof ImageDecoder<"u"&&typeof VideoEncoder<"u",aN=async e=>{if(!await H0(V.CONVERTING_GIF))return;const o={onCancel:async()=>{qt().abort()},cancelTitle:A("gif.user_cancel?")},r=m0(Sa(A("gif.prepare")));let n=0,a=0,i,s="";const x=setInterval(()=>{if(n===0)return;n=n-1;const p=A("gif.progress");r.message(Sa(p,{...o,remainTime:A("export.remain_time",{remainTime:QN(Math.max(n,0))}),progressRatio:a}))},1e3),c=new u2(10),l={onStart:()=>c.start(),onProgress:(p,f,E)=>{const T=p/f;n=c.supply(T),a=T},onEnd:(p,f)=>{clearInterval(x),s=f},onError:p=>{clearInterval(x),h("gif.ts").error("GifConversionInternalError",p),i=new C(p.errorCode,p.errorArgs)},onCancel:()=>{clearInterval(x)},onResult:(p,f)=>{}},d={type:V.CONVERTING_GIF,exportId:Ad(),quality:F0.SUPER_HIGH,size:lg,captionSetting:Eg,hwAccel:gr.NONE,videoFrameRate:Wl,option:{}},u=qe.v4();if(await qt().encode([],{[u]:e},[],Kt.WEBM,l,d),r.dismiss(),i)throw i;return s},d_e=async e=>
1112{if(!at())throw new C(_.C_GIF_IMPORT_GENERAL_ERROR,{},"Cannot import gif in web");if(!await H0(V.CONVERTING_GIF))throw new C(_.C_GIF_IMPORT_GENERAL_ERROR,{},"FFMPEG not found, cannot convert gif to webm");const o=await aN(e);if(o===void 0)throw new C(_.C_GIF_IMPORT_GENERAL_ERROR,{},"Failed to convert gif to webm");const r=await A4(o);if(r===void 0)throw new C(_.C_GIF_IMPORT_GENERAL_ERROR,{},"Registering converted gif failed");return r},u_e=async e=>{const t=await aN(e);if(t===void 0)throw new C(_.C_GIF_IMPORT_GENERAL_ERROR,{},"Failed to convert gif to webm");const o=await A4(t);if(o===void 0)throw new C(_.C_GIF_IMPORT_GENERAL_ERROR,{},"Registering converted gif failed");return o},p_e=async(e,t)=>{const o=await t.arrayBuffer(),r=new Oi,n=e.replace(/\.gif$/g,""),a=await r.getTempFileName("gif",n,!0);return await Ue().addFile(a,o,"utf8"),a},ynt=e=>{const t=e.is_sticker,o=t?e.images.original.url:e.images.original.mp4,{width:r,height:n}=e.images.original,a=r/n;return{isGif:t,srcUrl:o,aspectRatio:a}},f_e=async e=>{const t=await aN(e);if(t===void 0)throw new C(_.C_GIF_IMPORT_GENERAL_ERROR,{},"Failed to convert gif to webm");return t},d4=async e=>{const t=Ht(ug.AUDIO_TEMP);return(await ix(t)).convertGifToWebm(e)},vnt=async(e,t)=>{if(at()){const d=await p_e(t,e),u=await d_e(d);if(!u){const p="no videoInfo when converted gif files";throw h("gif.ts").error(p),new C(_.C_GIF_IMPORT_GENERAL_ERROR,{},p)}return u.asset}const o=await d4(e),r=t.replace(/\.gif$/i,"")+".webm",n=await fd({type:"blob",blob:o,name:r});if(!n){const d="assetVideoInfo is null after web GIF conversion";throw h("gif.ts").error(d),new C(_.C_GIF_IMPORT_GENERAL_ERROR,{},d)}const{mediaId:a}=n,{duration:i,videoInfo:s}=n.videoAudioMetaInfo;if(!s){const d="videoInfo missing from converted GIF metadata";throw h("gif.ts").error(d),new C(_.C_GIF_IMPORT_GENERAL_ERROR,{},d)}const{width:x,height:c}=I0(s.size),l=x/Math.max(1,c);return{mediaId:a,aspectRatio:l,duration:i}},g_e={uploading:null,transcoding:!1,encoding:!1,translating:!1,imageGenerating:!1,linebreaking:!1,
1112captionCorrecting:!1},u4=In({name:"processing",initialState:g_e,reducers:{startUpload:(e,t)=>{const{jobId:o,analysisJobList:r,message:n,sttAnalyzeOption:a,analysisType:i}=t.payload;e.uploading={jobId:o,analysisJobList:r,analysisType:i,message:n,progress:0,sttAnalyzeOption:a}},updateUploadProgress:(e,t)=>{const{progress:o,message:r}=t.payload;e.uploading!==null&&(r!==void 0&&(e.uploading.message=r),o!==void 0&&(e.uploading.progress=o))},updateTotalMediaDuration:(e,t)=>{e.uploading?.sttAnalyzeOption&&(e.uploading.sttAnalyzeOption.totalMediaDuration=t.payload)},endUpload:e=>{e.uploading=null},setTranscoding:(e,t)=>{e.transcoding=t.payload},setEncoding:(e,t)=>{e.encoding=t.payload},setTranslating:(e,t)=>{e.translating=t.payload},setImageGenerating:(e,t)=>{e.imageGenerating=t.payload},setLinebreaking:(e,t)=>{e.linebreaking=t.payload},setCaptionCorrecting:(e,t)=>{e.captionCorrecting=t.payload}}}),wnt=u4.reducer,{startUpload:Nnt,updateUploadProgress:Pnt,updateTotalMediaDuration:bnt,endUpload:Lnt,setTranscoding:VM,setEncoding:GM,setTranslating:Gd,setImageGenerating:Mnt,setLinebreaking:Dnt,setCaptionCorrecting:knt}=u4.actions,yd=e=>e.processing,__e=e=>yd(e).uploading,Fnt=e=>__e(e)!==null,Unt=e=>yd(e).transcoding,E_e=e=>yd(e).encoding,m_e=e=>yd(e).translating,Vnt=e=>yd(e).imageGenerating,Gnt=e=>yd(e).linebreaking,Wnt=e=>yd(e).captionCorrecting,p4=1e3*60*60*3,WM="Notification"in window;class h_e{notified;constructor(){if(this.notified=[],!WM){h("browser.ts").info("Notification isn't supported in this browser system.");return}window.addEventListener("beforeunload",()=>{[...this.notified].forEach(t=>this.disable(t))})}requestGrant(){Notification.requestPermission().then(t=>{switch(t){case"denied":h("browser.ts").info(["Permission for browser notification denied.","Make sure you are doing this in HTTPS,","or you allowed notification from this server."].join(" "));break;case"default":h("browser.ts").info("Permission request for browser notification dismissed.");break;case"granted":h("browser.ts").info("Permission for browser notification granted.");break}}).catch(t=>{h("browser.ts").warn("request rejected : "+t)})}notify(t){if(!WM||document.hasFocus())return;const o=new Notification("Vrew",{body:t});this.notified.push(o),o.onclick=()=>{window.focus(),this.notified=this.notified.filter(r=>r!==o)},setTimeout(()=>this.disable(o),p4)}disable=t=>{t.close(),this.notified=this.notified.filter(o=>o!==t)}}class I_e{requestGrant(){}async notify(t){(await ae())("notification.notify",{message:t,title:"Vrew",maxDuration:p4})}}let DO;const $p=()=>(!DO&&(DO=new(at()?I_e:h_e)),DO),Wd={main:"hvc1.1.6.L93.B0",main10:"hvc1.2.4.L93.B0",rext422:"hvc1.4.10.L93.9d.8",rext444:"hvc1.4.10.L93.9c.8",rextHighDepth:"hvc1.4.10.L93.99.88"},T_e=e=>e===void 0?Wd.main:e.includes("p12")||e.includes("p16")?Wd.rextHighDepth:e.includes("444")?Wd.rext444:e.includes("422")?Wd.rext422:e.includes("p10")?Wd.main10:Wd.main,S_e=3600,Hnt=async e=>{const{width:t,height:o}=await f4(e);return t/o},f4=async e=>{const t=await g4(e);return t===void 0||!t.videoHeight?{width:100,height:100,duration:t?.duration??1}:{width:t.videoWidth,height:t.videoHeight,duration:t.duration}},g4=async e=>new Promise(t=>{const o=document.createElement("video");o.onloadedmetadata=()=>{t(o)},o.onerror=r=>{const n=o.error,a=n?.code??"unknown",i=n?.message??"unknown";h("video.ts").error("Loading "+e+" failed: "+P(r)+" error code: "+a+", error message: "+i),t(void 0)},o.src=an(e),o.crossOrigin="anonymous"}),jnt=(e,t)=>t&&(t===90||t===270)?e.height+" x "+e.width:e.width+" x "+e.height,znt=(e,t)=>{const o={size:{width:e.width,height:e.height},name:""},r=_x.map(a=>{const{width:i,height:s}=_4(a.name,t);return{size:{width:i,height:s},name:""+a.name}});return r.splice(0,0,o),{resolutionList:r,defaultIndex:0}},_4=(e,t)=>{const o=_x.find(i=>i.name===e);if(o===void 0)throw new C(_.C_LOGIC_ERROR,{},"No targetResolution for export");const r=o.size,{width:n,height:a}=L4(r,t);return{width:n,height:a}},Ynt=(e,t)=>{const o=e.find(r=>r.name===t);return o?o.size:_x[0].size},HE=e=>{switch(e){case Gt.AAC:return"m4a";case Gt.MP3:return"mp3";case Gt.PCM:return"wav";case Gt.FLAC:return"flac";case Gt.OPUS:case Gt.VORBIS:return"webm";default:return"m4a"}},Bnt=e=>{if(e===0)throw new C(_.C_MEDIA_NO_DURATION)},Knt=async e=>{const t=qt();await t.checkFfmpegExist(!0)===!1&&await t.downloadFfmpeg(!0);const r=e.mediaContainer?Ed.includes(e.mediaContainer):!1;
1112if(e.audioInfo&&Eo(Gt).getKeyOrDefault(e.audioInfo.codec,void 0)===void 0)throw FUe({codec:e.audioInfo.codec}),h("video.ts").error("Incompatible audio codec: "+e.audioInfo.codec),new C(_.C_MEDIA_INCOMPATIBLE_AUDIO_CODEC,{audioCodec:e.audioInfo.codec});if(e.videoInfo&&!rA(e.videoInfo.codec,e.videoInfo.pixFmt))throw Qz({codec:e.videoInfo.codec}),h("video.ts").error("Incompatible video codec: "+e.videoInfo.codec),new C(_.C_MEDIA_INCOMPATIBLE_VIDEO_CODEC,{videoCodec:e.videoInfo.codec});if(!r)throw UUe({container:e.mediaContainer??"unknown"}),h("video.ts").error("Incompatible container: "+e.mediaContainer),new C(_.C_MEDIA_INCOMPATIBLE_VIDEO_TYPE,{videoType:e.mediaContainer});if(e.audioInfo===void 0&&e.videoInfo===void 0)throw new C(_.C_MEDIA_NO_AUDIO_VIDEO_TRACK);return e},E4=async(e,t,o,r)=>m4(e,t,o,Kt.MP4,r),O_e=(e,t)=>e*8/t,C_e=async(e,t,o,r)=>m4(e,t,o,Kt.MP3,r),m4=async(e,t,o,r,n)=>{if(!await R_e(e))return;const a={onCancel:async()=>{qt().abort()},cancelTitle:t===Lu.TRANSCODE?A("transcode.user_cancel?"):A("recovery.user_cancel_recovery_video")},i=m0(Sa(A("transcode.prepare")));let s=0,x=0,c=0,l=[],d;const u=setInterval(()=>{if(o&&o()){qt().abort();return}if(s===0)return;s=s-1;const R=n?A("bulk_transcode.progress_video",{TOTAL_VIDEO_CNT:e.length,CURRENT_VIDEO_INDEX:c+1}):t===Lu.TRANSCODE?A("transcode.progress_video"):A("recovery.progress_video_recovery");i.message(Sa(R,{...a,remainTime:A("export.remain_time",{remainTime:QN(Math.max(s,0))}),progressRatio:x}))},1e3),p=new u2(10),f={onStart:()=>p.start(),onProgress:(R,y)=>{const v=R/y;s=p.supply(v),x=v},onEnd:(R,y)=>{clearInterval(u),l=[y],ck()},onError:R=>{clearInterval(u),h("video.ts").error("EncodeInternalError",R),d=new C(R.errorCode,R.errorArgs)},onCancel:()=>{clearInterval(u),xk()},onResult:()=>{}},E={onStart:()=>p.start(),onProgress:(R,y,v)=>{const w=R/y;s=p.supply(w),x=w,c=v},onEnd:(R,y)=>{clearInterval(u),l=y,ck()},onError:R=>{clearInterval(u),h("video.ts").error("EncodeInternalError",R),d=new C(R.errorCode,R.errorArgs)},onCancel:()=>{clearInterval(u),xk()},onResult:()=>{}},{encodingSetting:T,mediaPieces:O}=h4(e,r),S=n?await qt().encodeUserVideos(O,r,E,T):await qt().encode([],O[0].path,O[0].pieces,r,f,T);if(i.dismiss(),S.type===Dr.SUCCESS)return await rs(l,async y=>{const v=await qt().getMediaFileInfo(y);return{path:y,mediaFileInfo:v}});if(d)throw d},R_e=async e=>!(e.length===0||(e.forEach(({totalSeconds:o})=>{if(o===null)throw new C(_.C_MEDIA_NO_DURATION)}),!await H0(V.TRANSCODING_VIDEO))),h4=(e,t)=>{const o={type:t===Kt.MP4?V.TRANSCODING_VIDEO:V.TRANSCODING_AUDIO,exportId:Ad(),quality:F0.REGULAR,size:e[0].videoSize?e[0].videoSize:lg,captionSetting:Eg,hwAccel:e[0].videoSize?qt().getAvailableHwAccel():gr.NONE,videoFrameRate:Wl,option:{}},r=e.map(({totalSeconds:n,origFile:a,mediaId:i})=>{const s="legacy_media_id";return{path:{[i??s]:a},pieces:[{start:0,end:n,captions:[],exportAssets:[],mediaId:i??s,clipIndex:0,playbackRate:1,pieceTimelineInProject:0,timelineDuration:n,exportCaptionModels:[],wordIds:[]}]}});return{encodingSetting:o,mediaPieces:r}},A_e=e=>{const o=e.videoSize,r=o?nde(o):lg,{encodingSetting:n,mediaPieces:a}=h4([e],Kt.MP4);return{proxySetting:{...n,type:V.PROXY_VIDEO,size:r,videoBitRate:2e3},mediaPieces:a}},I4=async(e,t)=>{if(e.length<=0)return[];e.forEach(r=>{if(dg.test(r))throw h("video.ts").error("trying to load shared folder path "+r),new C(_.C_IMPORT_SHARED_FOLDER_READ)});const o=await Qg(e.map(r=>({path:r})),void 0,!0,t,!0);return o===void 0?[]:o.map(r=>r.path)},Xnt=async e=>{const t=Ht(ug.AUDIO_TEMP);return(await ix(t)).getMediaFileInfo(e)},Qg=async(e,t,o,r,n)=>{const i=qt(),s=Y(),x=Og();try{x?.(VM(!0)),$p().requestGrant(),await i.checkFfmpegExist(!0)===!1&&await i.downloadFfmpeg(!0);const l=[],d=[],u=[],p=(await rs(e,async({path:R})=>{const y=bi(Ed).test(R),v=await i.getMediaFileInfo(R),{audioInfo:w,videoInfo:N}=v,M=N!==void 0?await i.getVideoKeyFrameInterval(R):0,k=await i.getColorSpace(R)??[],F=k.length>=3?k[2]:void 0,G=P2(F),B=(await qt().getUnknownCodecAudioStream(R)).length>0;if(w===void 0&&N===void 0)throw y?new C(_.C_MEDIA_NO_AUDIO_VIDEO_TRACK):new C(_.C_MEDIA_INCOMPATIBLE_CONTAINER);const W=N===void 0?!0:y&&(r?.insertionTarget===Ds.ASSET?xN(N.codec,N.pixFmt):rA(N.codec,N.pixFmt)),Q=w===void 0?!0:y&&Eo(Gt).getKeyOrDefault(w.codec,void 0)&&!bi(T6).test(R)&&!B,j=M<9;if(N!==void 0&&r?.insertionTarget!==Ds.ASSET&&!rA(N.codec,N.pixFmt)&&Qz({codec:N.co
1112dec}),VUe(k,N,r,M),W&&Q){const $=r?.insertionTarget===Ds.ASSET&&G;if(!o||j&&!$)return{path:R,mediaFileInfo:v};d.push({origFile:R,totalSeconds:v.duration,videoSize:N?.size,mediaFileInfo:v}),h("video.ts").info("Add transcoding recommend list, Target Path: "+R+", Reason","isKeyFrameIntervalCompatible:"+j);return}h("video.ts").info("Add transcoding list, Target Path: "+R+", Reason","isVideoCompatible:"+(W?"true":"false")+",","isAudioCompatible:"+(Q?"true":"false")+",","isKeyFrameIntervalCompatible:"+j),v.videoInfo!==void 0?(l.push({origFile:R,totalSeconds:v.duration,videoSize:N?.size,mediaFileInfo:v}),iE(void 0,N?.codec,r)):(u.push({origFile:R,totalSeconds:v.duration}),iE(void 0,w?.codec,r)),$p().notify(A("osinfo.ok"))})).filter(Se);if(d.length!==0){const R=wbe(d[0].origFile,d.length);await s.popup(R)===mt.YES?l.push(...d):p.push(...d.map(v=>({path:v.origFile,mediaFileInfo:v.mediaFileInfo})))}const f=l.length+u.length;if(f===0)return p;const E=n?vbe(l[0]?.origFile??u[0].origFile,e.length,f,l.length?"_vrew.mp4":"_vrew.mp3"):iz();if(await s.popup(E)!==mt.YES)return iE(!1,void 0,r),p;iE(!0,void 0,r);const O=await E4(l,Lu.TRANSCODE,t,n)||[];l.length&&!O.length&&h("video.ts").error("Failed to convert video: "+l[0].origFile);const S=await C_e(u,Lu.TRANSCODE,t,n)||[];return u.length&&!S.length&&h("video.ts").error("Failed to convert audio: "+u[0].origFile),n&&UFe(l.length),[...p,...O,...S]}catch(c){$p().notify(A("osinfo.failed"));const l=ye(c),d=Ho(c),u=l===_.D_ERR_SOURCE_FILE_LOST?"error.source_file_lost_info":void 0;return s.error(l,Ot(l,{errorArg:d,defaultKey:"transcode.transcode_error",errorDescKey:u})),FDe(l,r),[]}finally{x?.(VM(!1))}},oA=(e,t)=>{const o=e.width/e.height,r=t.width/t.height;if(o===r)return e;if(o>
1112r){const i=t.width*e.height/t.height;return{width:Math.min(e.width,On(Math.round(i))),height:e.height}}const n=t.height*e.width/t.width,a=Math.min(e.height,On(Math.round(n)));return{width:e.width,height:a}},y_e=(e,t,o,r)=>{if(r){if(!aA(r,il))return{scaledSize:t?oA(e,t):e,videoTransformInfo:{zoomX:1,zoomY:1,xPos:0,yPos:0}};const a=e,i=b4(r,o,t);return{scaledSize:a,videoTransformInfo:i}}else return{scaledSize:t?oA(e,t):e,videoTransformInfo:{zoomX:1,zoomY:1,xPos:0,yPos:0}}},_c={},v_e=()=>{const e={...Lx.DefaultConfig};return e.xhrSetup=t=>{t.withCredentials=!0},e.enableWorker=!0,e.lowLatencyMode=!1,e.maxBufferLength=10,e.maxMaxBufferLength=30,e.enableWebVTT=!1,e.startFragPrefetch=!1,e.testBandwidth=!1,e},Jnt=e=>{const t=_c[e];t&&(t.destroy(),delete _c[e])},qnt=(e,t,o)=>{if(_c[e])return _c[e].detachMedia(),_c[e].attachMedia(t),_c[e];if(Lx.isSupported()){const r=new Lx(v_e());r.attachMedia(t),r.loadSource(o),r.on(Lx.Events.ERROR,async(n,a)=>{await S4(a)}),_c[e]=r}else t.canPlayType("application/vnd.apple.mpegurl")&&(t.src=o);return _c[e]},w_e=async(e,t)=>{const o=Nu(e)+"_parts",r=gt(e),n=QN(Math.max(t,0)),a=Math.ceil(t/S_e),i={bodyClassName:"general-modal",title:A("split_media.too_long_title"),content:jt.createElement(Qr,void 0,A("split_media.too_long_info",{fileName:KS(r),fileDuration:n,count:a})),yesStr:A("popup.split"),noStr:A("popup.close")};if(await Y().popup(i)!==mt.YES){pC(0);return}if(!await H0(V.SPLIT_MEDIA)){pC(0);return}const c=[],l=jt.createElement(Qr,void 0,A("split_media.progress_desc")),d=m0(Sa(l)),u=1e3;let p=0,f=1,E="";const T=()=>{f=f+1,p=Math.min(1,f/a),E=A("split_media.completed_segments",{count:a,current:f})},O=setInterval(()=>{d.message(Sa(l,{progressRatio:p,remainTime:E}))},u);try{const y=await qt().splitMedia(e,o,T);c.push(...y.paths),pC(a)}catch(y){const v=ye(y)??_.C_SPLIT_ERROR,w=Ot(v,{defaultKey:""});Y().error(v,w);return}finally{d.dismiss(),clearInterval(O)}const S={bodyClassName:["general-modal","split-result-popup"].join(" "),title:A("split_media.split_done_title"),content:jt.createElement(Qr,void 0,A("split_media.split_done_desc",{fileName:KS(r),count:a})+c.map(y=>`
1113
1114 * `+KS(gt(y))).join("")),yesStr:A("popup.open_folder"),noStr:A("popup.close")};await Y().popup(S)===mt.YES&&Ue().openFolder(c[0])},ia=e=>e===_o,iN=(e,t)=>!e.assetIds.some(o=>L.get(t,o)?.role==="main"),zm=(e,t=16e3)=>{const o=Jg(new Float32Array(e*t),{isFloat:!0,numChannels:1,sampleRate:t,numFrames:t});return new Blob([o],{type:"audio/wav"})},Ym=e=>e.audioInfo===void 0,N_e=e=>e?e.videoAudioMetaInfo.videoInfo!==void 0:!1,P_e=e=>{switch(e.type){case"url":return!1;case"path":return!0;case"blob":return e.blob.size<nN}},fd=async e=>{try{const t=P_e(e)?await Ue().getAlreadyExistMediaId({path:e.type!=="blob"?e.value:void 0,data:e.type==="blob"?await e.blob.arrayBuffer():void 0}):null,o=t??qe.v4();await yi(e,o,tt.USER);const r=eo(o);if(!r){const n="[createUserVideoInfo] Video not found for mediaId: "+o;throw h("video.ts").error(n),new C(_.C_MEDIAINFO_NOT_EXIST,{},n)}return r}catch(t){if(Ne(t)&&t.errorCode===_.C_VCLOUD_USER_UPLOAD_CANCELED){h("video.ts").info("User canceled upload in createUserVideoInfo. name: "+(e.type==="blob"?e.name:e.value));return}throw h("video.ts").error("Error occurred while createUserVideoInfo: "+P(t)),Ne(t)?t:new C(_.C_ASSET_VIDEO_PARSE_ERROR)}},Qnt=async e=>{const{type:t}=e;if(t==="path"&&Oo()&&!await Vf(e.path))throw new C(_.C_ASSET_VIDEO_TOO_BIG_ERROR,{},"Asset video size is too big");const o=qe.v4(),r=t==="url"?dN(e.url):lN(t==="path"?e.path:e.fileName),n=t==="blob"?{mediaId:o,ext:r,blob:e.blob}:t==="url"?{mediaId:o,ext:r,url:e.url}:{mediaId:o,ext:r,pathInfo:{path:e.path,preserveOriginal:!0}},a=await Ue().putLocalCache(n),i=await qt().getMediaFileInfo(a.resolvedPath);return{mediaId:o,info:i,path:a.resolvedPath}},T4=async(e,t,o)=>{try{const r=qe.v4();await yi({type:"url",value:e},r,tt.VREW_RESOURCE,o);const n=eo(r);if(!n){const a="[createStockVideoInfo] Video not found for mediaId: "+r;throw h("video.ts").error(a),new C(_.C_MEDIAINFO_NOT_EXIST,{},a)}return n}catch(r){throw h("video.ts").error("Error occurred while createStockVideoInfo: "+P(r)),Ne(r)?(r.errorCode===_.C_MEDIA_INCOMPATIBLE_VIDEO_CODEC&&kUe({codec:r.errorArgs.codec,stockSite:t??ws.UNKNOWN}),r):new C(_.C_ASSET_VIDEO_PARSE_ERROR)}},Znt=async(e,t)=>{try{const o=typeof e=="string"?{type:Oo()?"path":"url",value:e}:{type:"blob",blob:e.blob,name:e.name??"generated_"+t+".mp4"};await yi(o,t,tt.AI_GENERATED);const r=eo(t);if(!r){const n="[createGenVideoInfo] Video not found for mediaId: "+t;throw h("video.ts").error(n),new C(_.C_MEDIAINFO_NOT_EXIST,{},n)}return r}catch(o){throw h("video.ts").error("Error occurred while createGenVideoInfo: "+P(o)),Ne(o)?o:new C(_.C_ASSET_VIDEO_PARSE_ERROR)}};let kO;const FO=()=>(kO===void 0&&(kO=new Qv(3)),kO),b_e=async(e,t)=>{const o=await sN(e,t);return o?{screenShotUrl:o.toDataURL(),width:o.width,height:o.height}:void 0},sN=async(e,t)=>{const o=FO().get(e)??await g4(e);if(!o)return;FO().has(e)===void 0&&FO().set(e,o);const r=document.createElement("canvas"),n=o.videoWidth,a=o.videoHeight;
1114r.width=n,r.height=a;const i=r.getContext("2d");if(i)return new Promise(s=>{o.onseeked=()=>{i.drawImage(o,0,0,n,a),s(r)};const x=o.duration;o.currentTime=Math.min(x,t)})},L_e=async(e,t)=>{const o=await sN(e,t);if(o)return new Promise(r=>{o.toBlob(n=>{if(!n){r(void 0);return}r(n)})})},M_e=e=>e.id==="dummy-video",HM=e=>{const{mediaId:t,videoAudioMetaInfo:o}=e,{videoInfo:r}=o;if(!r)return;const{width:n,height:a}=I0(r.size),i=n/(a??1);return{mediaId:t,aspectRatio:i,assetVideoInfo:e}},D_e=async(e,t)=>{const o=Hs(e);if(!o)return;const r=t?eo(t):void 0;if(r)return HM(r);h("video.ts").info("convert source file to asset video for sourceMediaId : "+e+".");const n=Bc(o)?await fd({type:"path",value:o.path}):await(async()=>{const a=await En(e);if(a)return await fd({type:"blob",blob:a,name:gt(e)})})();if(n?.videoAudioMetaInfo?.videoInfo)return HM(n)},jM=e=>{const t=e?Yu(e):void 0;return t?.broken===!0?S6:t?.videoAudioMetaInfo?.videoInfo?I0(t?.videoAudioMetaInfo?.videoInfo?.size):se().getInitProjectVideoSize()},H0=async e=>{const t=qt();if(await t.checkFfmpegExist(!0)===!1&&await t.downloadFfmpeg(!0),await t.checkFfmpegExist(!1))return Promise.resolve(!0);if(!Ta(It.FFMPEG_DOWNLOADED)){o1e(e);const s=A("name.ffmpeg"),x={bodyClassName:"general-modal",title:A("popup.title_confirm"),content:A("popup.download_module",{module:s}),yesStr:A("popup.continue")};if(await Y().popup(x)!==mt.YES)return r1e(e),Promise.resolve(!1);n1e(e)}Ta(It.FFMPEG_DOWNLOADED)===!1&&wn(It.FFMPEG_DOWNLOADED),GMe(e);const a=m0(Sa(A("export.prepare")));return await t.downloadFfmpeg(!1,s=>a.message(Sa(A("export.download_progress",{module:A("name.ffmpeg"),progress:s}))))===!1?(a.dismiss(),await Y().warn(A("error.download_module_failed",{module:A("name.ffmpeg")})),Promise.resolve(!1)):(a.dismiss(),WMe(e),Promise.resolve(!0))},S4=async e=>{const t=se().isCloudProject();e.type===Lx.ErrorTypes.NETWORK_ERROR&&e.fatal===!1&&t&&(h("video.ts").info("hls network error, try to re-issue cloud cookie"),await ol())},$nt=async(e,t,o)=>{if(Oo()){if(!await Vf(e))throw new C(_.C_ASSET_VIDEO_TOO_BIG_ERROR,{},"Asset video size is too big");const n=dN(e),a=new Oi,i=await a.getTempFileName(n);await Ue().downloadFile(e,i);const s=await f_e(i);await yi({type:"path",value:s},t,o)}else{const r=await fetch(e);if(!r.ok)throw new C(_.C_GIF_IMPORT_GENERAL_ERROR,{},"Failed to fetch GIF: "+r.status);const n=await r.blob();if(!await Vf(n))throw new C(_.C_ASSET_VIDEO_TOO_BIG_ERROR,{},"Asset video size is too big");const i=await d4(n);await yi({type:"blob",blob:i,name:(e.split("/").pop()?.replace(/\.gif$/i,"")??"gif")+".webm"},t,o)}},O4=e=>{const t=T_e(e);return document.createElement("video").canPlayType('video/mp4 ; codecs="'+t+'"')!==""},C4=e=>Eo(cg).asValueOrDefault(e,void 0)!==void 0,xN=(e,t)=>e===cg.HEVC?Oo()?!1:O4(t):C4(e),rA=(e,t)=>e===cg.HEVC?O4(t):C4(e),k_e=async(e,t)=>{switch(e.type){case"url":return(await Ue().downloadFile(e.value,void 0,void 0,void 0,t)).name;case"path":return e.value}},R4=async(e,t,o,r)=>{if(e.type==="blob"){const d=Ht(ug.AUDIO_TEMP),u=await ix(d),p=await u.getMediaFileInfo(e.blob),{resolvedPath:f}=await Ue().putLocalCache({mediaId:t,ext:lN(e.name),blob:e.blob});return{type:"AVMedia",mediaId:t,videoAudioMetaInfo:p,sourceOrigin:o,fileLocation:D.LOCAL_TMP,fileSize:e.blob.size,name:e.name,sourceType:de.ASSET_VIDEO,path:f,skipPrepare:!0}}const n=await k_e(e,r);if(!await Vf(n))throw new C(_.C_ASSET_VIDEO_TOO_BIG_ERROR,{},"Asset video size is too big");const i=await qt().getMediaFileInfo(n);if(i.videoInfo===void 0)throw new C(_.C_SELECT_ASSET_VIDEO_FILE_ERROR,{},"AssetVideo is incompatible and conversion to h264 has no result.");const s=await U_e(i,n);if(!s)throw new C(_.C_SELECT_ASSET_VIDEO_FILE_ERROR,{},"AssetVideo is incompatible and conversion to h264 has no result.");const x=(await Ue().getFileInfo(s.path)).size,c=s.info,l=gt(s.path);return{type:"AVMedia",mediaId:t,path:s.path,videoAudioMetaInfo:c,sourceOrigin:o,fileLocation:D.LOCAL_TMP,fileSize:x,name:l,sourceType:de.ASSET_VIDEO,skipPrepare:!1}},F_e=async(e,t,o)=>{const r=e.type==="url"?e.value.includes(z7()):!1,n=e.type!=="blob"?await fetch(e.value,r?{credentials:"include"}:void 0).then(x=>x.blob()):e.blob,a=Ht(ug.AUDIO_TEMP),i=await ix(a),s=await i.getMediaFileInfo(n);return{type:"AVMedia",mediaId:t,videoAudioMetaInfo:s,sourceOrigin:o,fileLocation:D.IN_MEMORY,fileSize:n.size,name:e.type==="blob"?e.name:gt(e.value),sourceType:de.ASSET_VIDEO,blob:n,skipPrepare:!1}},P2=e=>e!==void 0&&(e.includes(Ji.BT2020)||e.includes(Ji.BT2100)),zM=(e,t)=>!t||e.size===void 0||t.size===void 0||e.size!==t.size?!1:Math.round(e.duration??0)===Math.round(t.duration??0),cN=(e,t,o,r,n,a)=>{const i=pT(e,t,o,r,n,{...a,role:"sub"});if(!i)return null;const s=eo(t)?.videoAudioMetaInfo.audioInfo?{trackId:Rt(),mediaId:t,volume:a?.volume??RU,type:ze.VideoAudio,sourceIn:i.sourceIn,sourceOut:i.sourceOut,loop:!0,playbackRate:Un}:void 0;return{...i,audio:s}},pT=(e,t,o,r,n,a,i)=>{const s=eo(t);if(!s&&i!==!0)return;const x=Eae(a?.role??"sub"),c=a?.longAxisRatio??1,l=.5,d=a?.isTrimmable??!0,u=a?.hasAlphaChannel??s?.videoAudioMetaInfo.videoInfo?.hasAlphaChannel??!1,p=a?.sourceIn??pe(0),f=a?.sourceOut??a?.sourceIn??pe(s?.videoAudioMetaInfo.duration??0),E=cr(r),T=o>1?c:c*o/E,O=o>1?c*E/o:c,S=a?.xPos??l-T/2,R=a?.yPos??l-O/2,y=a?.rotation??0,v=a?.fillType;return{trackId:e,mediaId:t,type:z.VIDEO,xPos:S,yPos:R,height:O,width:T,rotation:y,sourceIn:p,sourceOut:f,zIndex:n,originalWidthHeightRatio:o,isTrimmable:d,hasAlphaChannel:u,editInfo:{crop:a?.crop},fillType:v!=="cover"?v:void 0,endBehavior:x}},A4=async e=>
1114{if(await y4())return;const t=await fd({type:"path",value:e});if(!t)return;const{videoAudioMetaInfo:o,mediaId:r}=t,{duration:n,videoInfo:a}=o;if(!a){const c="no videoInfo when selectVideoFiles";throw h("assetVideo.ts").error(c),new C(_.C_SELECT_ASSET_VIDEO_FILE_ERROR,{},c)}const{width:i,height:s}=I0(a.size),x=i/(s??1);return{asset:{type:Pu.Video,mediaId:r,aspectRatio:x,duration:n},info:t}},eat=async(e,t,o,r,n,a)=>{if(o===0||r===0)return[];const i=[];for(let x=0;x<o;x++)i.push(ue(x*r,3));return await Promise.all(i.map(x=>e({time:pe(x),mediaId:t,isCanceled:n}).then(c=>(a(c),c))))},tat=(e,t)=>{const o=e<=1;switch(t){case"contain":{const r=o?e:1,n=o?1:1/e;return{xPos:o?.5-r/2:0,yPos:o?0:.5-n/2,width:r,height:n}}case"cut":{const r=e<=1,n=r?1:e,a=r?1/e:1;return{xPos:r?0:.5-n/2,yPos:r?.5-a/2:0,width:n,height:a}}}},lN=e=>{const r=e.lastIndexOf(".");return r>0?e.slice(r+1):"mp4"},dN=e=>{const t=e.split("?")[0]||"",o=".",r=t.lastIndexOf(o),n="mp4",a=r>0?t.slice(r+1):n;return/[/\\?%*:|"<>]/.test(a)?n:a},y4=async()=>at()?await H0("assetVideo")===!1:!1,U_e=async(e,t)=>{if(e.videoInfo&&xN(e.videoInfo.codec,e.videoInfo.pixFmt))return{path:t,info:e};const r=iz();if(await Y().popup(r)===mt.YES){const a=await E4([{origFile:t,totalSeconds:e.duration,videoSize:e.videoInfo?.size}],Lu.TRANSCODE,void 0);if(a!==void 0){const i=a[0].mediaFileInfo;return{path:a[0].path,info:i}}}},Vf=async e=>{if(typeof e=="string"&&/^https:\/\//.test(e))return!0;const t=typeof e=="string"?(await Ue().getFileInfo(e)).size??0:e.size;return t<pZ?!0:(YUe(t),!1)},v4=()=>Lt().getUserPlanStatusForVcloud()==="UPGRADE",uN=()=>{if(!v4())return"local";const e=Ve().get(Ie.NEW_PROJECT_SAVE_LOCATION);return e==="cloud"||e==="local"?e:Ve().get(Ie.LAST_PROJECT_TYPE)===Ee.CLOUD?"cloud":"local"},V_e=async e=>{await Y().popup({bodyClassName:"general-modal",title:A("vcloud.media_upload_failed_title"),content:A("vcloud.media_upload_failed_desc"),yesStr:A("vcloud.retry"),noStr:A("popup.cancel")})===mt.YES&&await e()},YM={type:Ee.EMPTY,path:"",initProjectVideoSize:{width:1920,height:1080}};class G_e{fileManager;needSave=!1;savedPastSnapshot;projectFileInfo={...YM,id:qe.v4()};events=new ad.EventEmitter;lastOpenedFilePath;projectSaved=!1;projectNamedExplicitly=!1;sampleProjectType=void 0;sampleProjectSourceDir;withAddFileLimit=tf(5);_pendingPromotions=new Map;_failedUploads=new Map;_batchModalTimer=null;BATCH_DEBOUNCE_MS=1e3;blankVideoInfo;createBlankVideoInfo(){const t=zm(1,zx);return{blankAudioBlob:t,blankInfo:{sourceType:de.VIDEO_AUDIO,type:"AVMedia",sourceOrigin:tt.VREW_RESOURCE,fileLocation:D.IN_MEMORY,mediaId:_o,fileSize:t.size,videoAudioMetaInfo:{duration:1,audioInfo:{sampleRate:AU,codec:Gt.PCM,channelCount:O6},videoInfo:void 0},name:_o+".mp4"}}}dummyBlob=new Blob;constructor(){this.fileManager=new iO(this.getOpfsStorageConfig()),this.blankVideoInfo=this.createBlankVideoInfo()}getOpfsStorageConfig(t=this.projectFileInfo.type,o=this.projectFileInfo.id){switch(t){case Ee.CLOUD:return{namespace:Nb.CLOUD_CACHE,pathPrefix:o+"/media"};case Ee.BROWSER:return{namespace:C6.BROWSER_PROJECT,pathPrefix:this.getUserId()+"/"+o+"/media"};case Ee.PROJECT:case Ee.MEDIA:default:return{namespace:Nb.LOCAL_CACHE,pathPrefix:o+"/media"}}}async processFileInput(t,o,r=this.projectFileInfo.type,n=this.projectFileInfo.id,a={}){const i=r===Ee.CLOUD&&tae(t)?s=>this.uploadMediaToCloud(s,n):void 0;o==="update"?await this.fileManager.update(t,{onBlobReady:i}):await this.fileManager.add(t,{onBlobReady:i,skipPrepare:a.skipPrepare}),sO()}uploadPendingMediaFiles(t,o){h("ProjectInfoManager.ts").info("[uploadPendingMediaFiles] Uploading "+o.length+" files"),this.executeBatchUpload(t,o)}async executeBatchUpload(t,o){const r=An(5);try{await Promise.all(o.map(n=>r(()=>this.uploadMediaToCloud(n.mediaId,t))))}catch(n){const a="[executeBatchUpload] Batch upload failed for project: "+t+", error: "+P(n);h("ProjectInfoManager.ts").error(a)}}async uploadMediaToCloud(t,o){if(this.projectFileInfo.id!==o){h("ProjectInfoManager.ts").info("[uploadMediaToCloud] Skipping - project context changed (mediaId: "+t+")");return}if(this._pendingPromotions.get(t)===o){h("ProjectInfoManager.ts").info("[uploadMediaToCloud] Already uploading mediaId: "+t);return}const r=this.fileManager.getFileInfo(t);if(!r){h("ProjectInfoManager.ts").warn("[uploadMediaToCloud] fileInfo not found for mediaId: "+t);return}const n=await this.getFileBlob(t);if(!n){h("ProjectInfoManager.ts").warn("[uploadMediaToCloud] blob not found for mediaId: "+t);return}
1114this._pendingPromotions.set(t,o);const a={mediaId:t,blob:n,fileInfo:r,projectId:o,onComplete:async i=>{if(this.projectFileInfo.id!==o||!this.fileManager.getFileInfo(t)){this._pendingPromotions.get(t)===o&&this._pendingPromotions.delete(t),h("ProjectInfoManager.ts").info("[uploadMediaToCloud] Skipping promoteToRemote - context changed (mediaId: "+t+")");return}const s=yo(i.url);await this.fileManager.promoteToRemote(t,{url:i.url,proxy:i.proxyInfo},async()=>{await this.fileManager.saveBlobToCache(t,n,s,i.cacheWriteFailed)}),sO(),this._pendingPromotions.get(t)===o&&this._pendingPromotions.delete(t),this._pendingPromotions.size===0&&(h("ProjectInfoManager.ts").info("[uploadMediaToCloud] All uploads complete for project: "+o),this.events.emit(co.BACKGROUND_UPLOAD_COMPLETE,o))},onError:i=>{if(this._pendingPromotions.get(t)===o&&this._pendingPromotions.delete(t),!i){if(this.projectFileInfo.id!==o)return;this._failedUploads.set(t,o),this._scheduleBatchModal()}}};this.events.emit(co.MEDIA_READY_FOR_CLOUD_UPLOAD,a)}_scheduleBatchModal(){this._batchModalTimer!==null&&clearTimeout(this._batchModalTimer),this._batchModalTimer=setTimeout(()=>{this._batchModalTimer=null,this._showBatchFailureModal().catch(t=>{h("ProjectInfoManager.ts").error("[_showBatchFailureModal] error",t)})},this.BATCH_DEBOUNCE_MS)}async _showBatchFailureModal(){const t=new Map(this._failedUploads);this._failedUploads.clear(),await V_e(async()=>{for(const[o,r]of t)this.uploadMediaToCloud(o,r).catch(n=>{h("ProjectInfoManager.ts").error("[_showBatchFailureModal] Retry upload failed (mediaId: "+o+")",n)})})}async addMultiple(t,o=this.projectFileInfo.type,r=this.projectFileInfo.id,n={}){h("ProjectInfoManager.ts").info("[ProjectInfoManager.addMultiple] Processing "+t.length+" files");const a=t.map(i=>this.withAddFileLimit(async()=>this.addFile(i,n,o,r)));await Promise.all(a)}createDummyAudioInfo=()=>{const t=zm(1);return{dummyAudioInfo:{mediaId:gf,type:"AVMedia",fileLocation:D.IN_MEMORY,videoAudioMetaInfo:{videoInfo:void 0,audioInfo:{codec:Gt.PCM,sampleRate:zx},duration:1},sourceOrigin:tt.VREW_RESOURCE,fileSize:t.size,name:gf+"."+Hh,sourceType:de.TTS},dummyAudioBlob:t}};async addFile(t,o={},r=this.projectFileInfo.type,n=this.projectFileInfo.id){await this.processFileInput(t,"add",r,n,o)}getProxyInfo(t){return this.fileManager.getProxyInfo(t)}async getFileBlob(t,o){const r=this.getFileInfo(t,{excludeBroken:o?.excludeBroken||!1});if(!r||o&&o.excludeBroken&&r.broken&&!yf(r))return null;const n=await this.fileManager.getBlob(t,o?.onProgress);return n||null}async hasCached(t){return this.getFileInfo(t)?this.fileManager.hasCached(t):!1}getFileInfo(t,o){const r=this.fileManager.getFileInfo(t);if(!(o&&o.excludeBroken&&r?.broken&&!yf(r)))return r}getAllFileInfos(){return this.fileManager.getAllFiles()}getAVMediaFiles(){return this.fileManager.getAVMediaFiles()}getImageFiles(){return this.fileManager.getImageFiles()}getInMemoryBlobUrl(t){return this.fileManager.getInMemoryBlobUrl(t)}getInMemoryFileBlob(t){return this.fileManager.getInMemoryFileBlob(t)}getMediaUrl(t){return this.fileManager.getMediaUrl(t)}getFileSrcUrl(t){return this.fileManager.getFileSrcUrl(t)}async updateFile(t){await this.processFileInput(t,"update")}removeFile(t){const o=this.fileManager.remove(t);return o&&sO(),o}getBlankVideoInfo(){return this.blankVideoInfo}getBlankAVMediaInput(){const{blankInfo:t,blankAudioBlob:o}=this.blankVideoInfo;return{...t,fileLocation:D.IN_MEMORY,blob:o}}getDummyBlob(){return this.dummyBlob}getEventEmitter(){return this.events}getCurrentProjectPath(){return this.projectFileInfo.path}getCurrentProjectFileType(){return this.projectFileInfo.type}getSaveProjectType(){const t=this.getCurrentProjectFileType();return t===Ee.PROJECT||t===Ee.CLOUD||t===Ee.BROWSER?t:uN()==="cloud"?Ee.CLOUD:t}getProjectId(){return this.projectFileInfo.id}getFileNeedSave(){return this.needSave}markDirty(){!this.needSave&&(this.needSave=!0,this.events.emit(co.NEEDSAVE,this.needSave))}getAnalyzeDate=()=>this.projectFileInfo.analyzeDate;async convertCloudToLocalInputs(t,o){return!rae(t)||o!==Ee.MEDIA||!this.isCloudProject()?t:(h("ProjectInfoManager.ts").info("convertCloudToLocalInputs(type: "+o+", inputs: "+t.length+")"),Promise.all(t.map(async r=>{if(Jy(r))switch(r.type){case"AVMedia":{if(!oae(r))return r;if(r.sourceType===de.ASSET_VIDEO&&at()){h("ProjectInfoManager.ts").info("[convertCloudToLocalInputs] convert asset video to local_tmp for mediaId: "+r.mediaId+", info : "+JSON.stringify(r));const{resolvedPath:n}=await Ue().putLocalCache({url:r.url,mediaId:r.mediaId,ext:dN(r.url)});return aae(r,n)}else{const n=await this.getFileBlob(r.mediaId);if(!n){const a="[convertCloudToLocalInputs] Media blob lost for mediaId: "+r.mediaId+", info : "+JSON.stringify(r);throw h("ProjectInfoManager.ts").error(a),new C(_.C_MEDIA_BLOB_LOST,{},a)}return iae(r,n)}}default:return h("ProjectInfoManager.ts").warn("Cannot convert REMOTE "+r.type+" to local: "+r.mediaId),r}return r})))}async notifyFileOpen(t,o,r,n){const a=ZO(ks()),i=h("ProjectInfoManager.ts");if(i.info("ProjectInfoMgr.notifyFileOpen(type: "+t+", newProject: "+(r!==void 0)+")"),r===void 0)await this.addMultiple(o,this.projectFileInfo.type),await this.addFile(this.getBlankAVMediaInput(),{},this.projectFileInfo.type),nae(o)&&this.events.emit(co.ADD_NEW_SCENE_WITH_SOURCE);else{const x=AL(o);this.releaseLockedFiles(this.projectFileInfo.type,x),this.sampleProjectType=r.sampleProjectType;const{currentPath:c,projectId:l,fromAutosave:d,props:{videoSize:u,initProjectVideoSize:p}}=r;await this._initializeDataManagers(t,o,l),i.info("total media len : "+o.length),t===Ee.PROJECT||t===Ee.CLOUD?(this.events.emit(co.VREW_FILE_OPENED,l,c,t),Ue().setOpenVrewFile(c)):t===Ee.MEDIA&&(this.events.emit(co.TMP_PROJECT_OPENED),Ue().setOpenVrewFile(void 0));const f=t===Ee.MEDIA||d;if(this.savedPastSnapshot=this.sampleProjectType===void 0&&f?"FROMAUTOSAVE":a,this._setCurrentFile(t,c,l,d,!1,u,n,p),t===Ee.CLOUD){const E=this.fileManager.getAllFiles().filter(T=>!T.broken&&aG(T));E.length>0&&this.uploadPendingMediaFiles(l,E)}}const s=AL(o);this.lockFiles(s)}notifyMediaChanged=(t,o)=>{const r=this.fileManager.getAVMediaFiles().filter(a=>Zr(a));r.length>
11140&&r[0]&&o&&(this.projectFileInfo.projectVideoSize=o),this.needSave=!0,this.events.emit(co.NEEDSAVE,this.needSave),this.events.emit(co.REPLACE_MEDIA,this.needSave,t),this.events.emit(co.PROJECT_INFO_UPDATED,this.projectFileInfo)};notifySaved(){this.needSave=!1,this.events.emit(co.NEEDSAVE,this.needSave)}notifyFileSaved(t,o,r,n={fromAutosave:!1}){const{fromAutosave:a,thumbnailCandidate:i}=n;if(this.savedPastSnapshot=ZO(ks()),this.projectFileInfo.type!==t||this.projectFileInfo.path!==o||this.projectFileInfo.id!==r){const s=this.projectFileInfo.analyzeDate;this._setCurrentFile(t,o,r,a,!0,this.projectFileInfo.projectVideoSize,s,this.projectFileInfo.initProjectVideoSize)}else this.needSave&&this.notifySaved();this.getEventEmitter().emit(co.VREW_FILE_SAVED,this.getProjectId(),o,this.projectFileInfo.type,i)}notifyEdit(){const t=ZO(ks());t&&t!==this.savedPastSnapshot&&!this.needSave?(this.needSave=!0,this.events.emit(co.NEEDSAVE,this.needSave)):t===this.savedPastSnapshot&&this.needSave&&(this.needSave=!1,this.events.emit(co.NEEDSAVE,this.needSave))}isProjectSaved=()=>this.projectSaved;markProjectAsNamed(){this.projectNamedExplicitly=!0,h("ProjectInfoManager.ts").info("[markProjectAsNamed] Project marked as explicitly named")}needsNaming(t){const o=t??this.getCurrentProjectFileType();return(o===Ee.CLOUD||o===Ee.BROWSER)&&!this.projectNamedExplicitly}updateCurrentProjectFileType(t){this.projectFileInfo.type=t,this.projectSaved=t===Ee.PROJECT||t===Ee.CLOUD||t===Ee.BROWSER;const o=this.getOpfsStorageConfig(t);this.fileManager.updateOpfsConfig(o),this.events.emit(co.PROJECT_INFO_UPDATED,this.projectFileInfo),h("ProjectInfoManager.ts").info("[updateCurrentProjectFileType] Type updated to: "+t)}notifyVideoSizeEstimated=(t,o)=>{this.projectFileInfo={...this.projectFileInfo,estimatedVideoSize:{width:t,height:o}},this.events.emit(co.PROJECT_INFO_UPDATED,this.projectFileInfo)};getProjectVideoSizeToSave=()=>this.projectFileInfo.projectVideoSize;getInitProjectVideoSize=()=>this.projectFileInfo.initProjectVideoSize;releaseLockedFiles=(t,o)=>{this.sampleProjectType===void 0&&o.forEach(r=>Ue().releaseFile(r))};lockFiles=t=>{this.sampleProjectType===void 0&&t.forEach(o=>Ue().lockFile(o))};_setCurrentFile(t,o,r,n,a,i,s,x){const c=this.needSave;switch(this.projectSaved=t===Ee.PROJECT||t===Ee.CLOUD||t===Ee.BROWSER,this.projectFileInfo.type=t,this.projectFileInfo.path=o,this.projectFileInfo.id=r,this.projectFileInfo.projectVideoSize=i,this.projectFileInfo.analyzeDate=s,this.projectFileInfo.initProjectVideoSize=x,!a&&(this.projectFileInfo.estimatedVideoSize=void 0,this.projectNamedExplicitly=(t===Ee.BROWSER||t===Ee.CLOUD)&&!n),this.events.emit(co.NEWFILE,t,o,!a,r),this.events.emit(co.PROJECT_INFO_UPDATED,this.projectFileInfo),t){case Ee.MEDIA:this.needSave=this.sampleProjectType===void 0;break;case Ee.PROJECT:case Ee.BROWSER:case Ee.CLOUD:this.needSave=n===!0;break;default:this.needSave=!0}if(c!==this.needSave&&this.events.emit(co.NEEDSAVE,this.needSave),t===Ee.PROJECT||t===Ee.BROWSER){const l=Ve();this.lastOpenedFilePath===void 0&&(this.lastOpenedFilePath=l.get(Ie.LAST_FILEPATH)),this.lastOpenedFilePath!==o&&this.sampleProjectType===void 0&&(l.set(Ie.LAST_FILEPATH,o),this.lastOpenedFilePath=o)}}async reset(){this.projectFileInfo={...YM,id:qe.v4()},this.needSave=!1,this.savedPastSnapshot=void 0,this._batchModalTimer!==null&&(clearTimeout(this._batchModalTimer),this._batchModalTimer=null),this._failedUploads.clear(),this._pendingPromotions.clear(),this.fileManager.clear(),this.fileManager=new iO(this.getOpfsStorageConfig()),this.sampleProjectType=void 0,await this.addFile(this.getBlankAVMediaInput()),this.events.emit(co.NEWFILE,Ee.EMPTY,"",!0,this.projectFileInfo.id),this.events.emit(co.RESET),this.events.emit(co.PROJECT_INFO_UPDATED,this.projectFileInfo)}isDemo=()=>this.sampleProjectType==="demo";isSampleProject=()=>this.sampleProjectType!==void 0;clearSampleProject=()=>{this.sampleProjectSourceDir=void 0,this.sampleProjectType=void 0};setSampleProjectSourceDir=t=>{this.sampleProjectSourceDir=t};getSampleProjectSourceDir=()=>this.sampleProjectSourceDir;isEmpty=()=>this.getCurrentProjectFileType()===Ee.EMPTY;isMedia=()=>this.getCurrentProjectFileType()===Ee.MEDIA;isLocalProject=()=>this.getCurrentProjectFileType()===Ee.PROJECT;isCloudProject=()=>this.getCurrentProjectFileType()===Ee.CLOUD;getUserId=()=>be().getUserInfo()?.uid??tn;async _initializeDataManagers(t,o,r=this.projectFileInfo.id){const n=await this.convertCloudToLocalInputs(o,t);this._batchModalTimer!==null&&(clearTimeout(this._batchModalTimer),this._batchModalTimer=null),this._failedUploads.clear(),this._pendingPromotions.clear(),this.fileManager.clear(),this.fileManager=new iO(this.getOpfsStorageConfig(t,r)),await this.addMultiple(n,t,r),await this.addFile(this.getBlankAVMediaInput(),{},t,r)}}let bl;const W_e=()=>{!bl&&(bl=new G_e,bl.getEventEmitter().on(co.NEEDSAVE,e=>{hx({needSave:e})}).on(co.NEWFILE,async(e,t,o,r)=>{let n="",a="none";switch(e){case Ee.PROJECT:n=gt(t),a="device";break;case Ee.CLOUD:n=gt(t),a="saved";break;case Ee.MEDIA:!bl.isProjectSaved()&&(n=gt(t),a="none");break;case Ee.BROWSER:n=await Kf(t)??t,a="device";break;case Ee.EMPTY:break}hx({needSave:bl.getFileNeedSave(),status:a,title:n})}
1114))},se=()=>(!bl&&W_e(),bl),j0=e=>{const t=[{ratio:1,type:he.SQUARE},{ratio:1.7777777777777777,type:he.WIDE_SCREEN},{ratio:.5625,type:he.VERTICAL},{ratio:.8,type:he.INSTAGRAM},{ratio:1.3333333333333333,type:he.CLASSIC}];for(const{ratio:o,type:r}of t)if(Math.abs(e-o)<=.01)return r;return he.INIT},pN=()=>{const e=se().getInitProjectVideoSize(),t=j0(e.width/e.height);return t===he.INIT?e.width/e.height:cr(t)},w4=()=>{const e=se().getInitProjectVideoSize();return j0(e.width/e.height)},cr=e=>{switch(e){case he.VERTICAL:return 9/16;case he.WIDE_SCREEN:return 16/9;case he.CLASSIC:return 4/3;case he.INSTAGRAM:return 4/5;case he.SQUARE:return 1;case he.INIT:case he.ORIGINAL:default:return pN()}},oat=e=>{switch(e){case he.VERTICAL:return 16/9;case he.WIDE_SCREEN:return 9/16;case he.CLASSIC:return 3/4;case he.INSTAGRAM:return 5/4;case he.SQUARE:return 1;case he.INIT:case he.ORIGINAL:default:return 9/16}},N4=(e,t,o,r)=>{const n=cr(r),a=o?t*n:e,i=a/n;return{width:Math.floor(a),height:Math.floor(i)}},P4=e=>{switch(e){case he.VERTICAL:return"9:16";case he.WIDE_SCREEN:return"16:9";case he.CLASSIC:return"4:3";case he.INSTAGRAM:return"4:5";case he.SQUARE:return"1:1";case he.INIT:case he.ORIGINAL:return"original"}},b4=(e,t,o)=>{const r=cr(he.INIT),n=o?o.width/o.height:r,a=cr(t),i=e.xPos,s=e.yPos,x=e.zoom;if(n>a){const c=i,l=x,d=(1-a*(1/n))*.5+s,u=x*a*(1/n);return{zoomX:l,zoomY:u,xPos:c,yPos:d}}else{const c=s,l=x,d=(1-1/a*n)*.5+i;return{zoomX:x*(1/a)*n,zoomY:l,xPos:d,yPos:c}}},H_e=(e,t,o)=>{const r=N4(e,t,!1,o);return{width:On(r.width),height:On(r.height)}},L4=(e,t)=>{const{width:o,height:r}=e,n=cr(t),a=o/r;if(a<=n){const x=o,c=Math.ceil(o*(1/n));return{width:On(x),height:On(c)}}if(1<n){const x=Math.ceil(r*n),c=r;return{width:On(x),height:On(c)}}if(1/n<a){const x=r,c=Math.ceil(r*(1/n));return{width:On(x),height:On(c)}}const i=Math.ceil(o*n),s=o;return{width:On(i),height:On(s)}},fN=(e,t,o,r)=>{const n=nA(e,o,t);return M4(n,r,t)},M4=(e,t,o)=>{const{xPos:r,width:n,yPos:a,height:i}=e;if(t>o){const c=(1-o/t)*.5+o/t*r,l=o/t*n;return{xPos:c,width:l,yPos:a,height:i}}const s=(1-t/o)*.5+t/o*a,x=t/o*i;return{xPos:r,width:n,yPos:s,height:x}},nA=(e,t,o)=>{const{xPos:r,width:n,yPos:a,height:i}=e;if(t>o){const c=(r-(1-o/t)*.5)*(t/o),l=t/o*n;return{xPos:c,width:l,yPos:a,height:i}}const s=(a-(1-t/o)*.5)*(o/t),x=o/t*i;return{xPos:r,width:n,yPos:s,height:x}},BM=(e,t,o,r)=>{if(e)return e.type===Ir.CUSTOM?{...e,...lle(e.from,e.to,r)}:{...e,...wI(e.type,t,o)}},Gf=(e,t,o)=>{switch(t){case ro.CONTAIN:return il;case ro.CUT:{const r=cr(he.INIT),n=o?o.width/o.height:r,a=cr(e),i=n<a,s=-Math.abs(1-n/a)*.5,x=-Math.abs(1-a/n)*.5;return{zoom:i?a/n:n/a,xPos:s,yPos:x,rotation:0}}}},KM=(e,t)=>Math.abs(e.zoom-t.zoom)<.001&&Math.abs(e.xPos-t.xPos)<.001&&Math.abs(e.yPos-t.yPos)<.001&&Math.abs(e.rotation-t.rotation)<.001,rat=(e,t)=>({zoom:t.zoom-e.zoom,xPos:t.xPos-e.xPos,yPos:t.yPos-e.yPos,rotation:t.rotation-e.rotation}),aA=(e,t)=>e.zoom!==t.zoom||e.xPos!==t.xPos||e.yPos!==t.yPos||e.rotation!==t.rotation,j_e=(e,t)=>{const o=!aA(t,il),r=Gf(e,ro.CUT,void 0),n=!aA(r,t);return o?"fit":n?"fill":"etc"},z_e=(e,t,o,r)=>{const{xPos:n,width:a,yPos:i,height:s}=fN({xPos:e.xPos,yPos:e.yPos,width:e.width,height:e.height},t,o,r),{originalWidthHeightRatio:x}=e,c=e.stats?.fillType;if(!c){const f=$t(n,.05-a,.95),E=$t(i,.05-s,1-.05),T={xPos:f,yPos:E,width:a,height:s},O=e.kenburnsAnimationInfo;return{...e,...T,kenburnsAnimationInfo:O?.type===Ir.CUSTOM?BM(O,x,r,T):O}}const l=_b(x,r,c),d=e.kenburnsAnimationInfo,u=BM(d,x,r,l);return{...e,...l,kenburnsAnimationInfo:u}},Y_e=(e,t,o,r)=>{const n=zn({});return Object.entries(e).forEach(([a,i])=>{const s=Wa(i)?i:B_e(i,t,o,r);L.set(n,kr(a),s)}),n},B_e=(e,t,o,r)=>{const{xPos:n,width:a,yPos:i,height:s}=fN({xPos:e.xPos,yPos:e.yPos,width:e.width,height:e.height},t,o,r);switch(e.type){case z.IMAGE:return z_e(e,t,o,r);case z.WEB:{const c=$t(n,.050000000000000044-a,.95),l=$t(i,1-.95-s,.95);return{...e,xPos:c,yPos:l,width:a,height:s}}case z.VIDEO:{const c=$t(n,.050000000000000044-a,.95),l=$t(i,1-.95-s,.95);return{...e,xPos:c,yPos:l,width:a,height:s,fillType:void 0}}case z.SHAPE:{const c=$t(n,.09999999999999998-a,.9),l=$t(i,1-.9-s,.9);return{...e,xPos:c,yPos:l,width:a,height:s}}case z.SIMPLE_CHARACTER:{const c=$t(n,.050000000000000044-a,.95),l=$t(i,1-.95-s,.95);return{...e,xPos:c,yPos:l,width:a,height:s}}case z.WATERMARK:return K_e(e,t,o,r);case z.LOTTIE:default:return e}},K_e=(e,t,o,r)=>{const{xPos:n,width:a,yPos:i,height:s}=fN({xPos:e.xPos,yPos:e.yPos,width:e.width,height:e.height},t,o,r);return{...e,xPos:n,yPos:i,width:a,height:s}},nat=(e,t,o,r)=>{const n=L.get(yU,r);if(n===void 0)return e;const{X_RATIO:a,Y_RATIO:i}=n,{xPos:s,yPos:x,width:c,height:l}=e,{width:d,height:u}=nA({xPos:s,yPos:x,width:c,height:l},o,t),p=r===_i.TOP_RIGHT||r===_i.BOTTOM_RIGHT?d:0,f=r===_i.BOTTOM_LEFT||r===_i.BOTTOM_RIGHT?u:0,E=a-p,T=i-f,O=nA({xPos:E,yPos:T,width:d,height:u},t,t),S=M4(O,o,t);return{...e,xPos:S.xPos,yPos:S.yPos,width:S.width,height:S.height,vrewMarkInfo:{...e.vrewMarkInfo,position:r}}},aat=e=>D4(e,he.VERTICAL),D4=(e,t)=>
1114{const o=cr(e),r=cr(t);return Math.abs(o-r)<.01},X_e=e=>{if(e!==w4())return e;const t=[he.WIDE_SCREEN,he.VERTICAL,he.SQUARE,he.INSTAGRAM,he.CLASSIC];for(const o of t)if(D4(o,e))return o},gN=(e,t)=>[...t.sort((r,n)=>r-n).reduce((r,n,a)=>{const i=n-a,s=r.get(i);return s?r.set(i,{...s,to:n+1}):r.set(i,{from:n,to:n+1,type:e})},new Map).values()],k4=e=>gN("SCENE",e),iat=e=>gN("CLIP",e),is=e=>gN("GLOBAL_CLIP",e),J_e=(e,t)=>{for(let o=e.from;o<e.to;o++)if(!t(o))return!1;return!0},sat=(e,t)=>e.every(o=>J_e(o,t)),q_e=(e,t)=>e.from<=t&&t<e.to,xat=(e,t)=>e.some(o=>q_e(o,t)),Q_e=e=>e.to-e.from,Z_e=e=>e.reduce((t,o)=>t+Q_e(o),0),cat=e=>{const t=[];for(let o=e.from;o<e.to;o++)t.push(o);return t},lat=(e,t)=>{const o=new Set;if(t.forEach(n=>{for(let a=n.from;a<n.to;a++)o.add(a)}),o.size===0)return e;const r=e.filter((n,a)=>!o.has(a));return r.length===e.length?e:r},dat=(e,t,o)=>{let r,n=0;for(let a=0;a<e.length;a++){if(n<t.length&&a>=t[n].from&&a<t[n].to){const i=o(e[a]);r?r.push(i):i!==e[a]&&(r=e.slice(0,a),r.push(i))}else r&&r.push(e[a]);n<t.length&&a===t[n].to-1&&n++}return r??e},uat=(e,t,o,r)=>{let n,a=0,i=0;for(let s=0;s<e.length;s++){if(a<t.length&&s>=t[a].from&&s<t[a].to){if(i>=o.length)throw new C(_.C_LOGIC_ERROR,void 0,`[applyOperationToSortedChunksWithPayloads] Out of Range For Payloads. 
1115          payloadIndex: `+i+" Payloads: "+o.length+", Chunks: "+t.length);const x=r(e[s],o[i++]);n?n.push(x):x!==e[s]&&(n=e.slice(0,s),n.push(x))}else n&&n.push(e[s]);a<t.length&&s===t[a].to-1&&a++}return n??e},$_e=(e,t)=>e.type===t&&e.from<e.to,pat=(e,t)=>e.every(o=>$_e(o,t)),F4=(e,t)=>{const o=(n,a,i)=>(a.assetIds.includes(e)&&n.push(i),n),r=t.reduce(o,[]);if(r.length>0)return{from:r[0],to:(r.at(-1)??0)+1,type:"GLOBAL_CLIP"};for(const[n,a]of t.entries()){const i=a.words.reduce(o,[]);if(i.length>0)return{from:i[0],to:(i.at(-1)??0)+1,type:"WORD",globalClipIndex:n}}return null},eEe=e=>{if(!e.transitionModel)return null;const t=vo(e),{timelineStartOffset:o}=e.transitionModel,{words:r}=e,n=t+o,a=r.reduce((x,c)=>{if(x.length===r.length)return x;const l=x[x.length-1];return x.push(pe(l+c.duration)),x},[t]),i=r.findIndex((x,c)=>a[c]<=n&&a[c]+x.duration>=n);if(i===-1)return null;const s=r.length-1;return{from:i,to:s+1,type:"WORD"}},tEe=(e,t)=>{const o=F4(e,t);if(!o)return null;if(o.type==="GLOBAL_CLIP"){const{from:a,to:i}=o;return{clipCount:i-a,wordCount:0}}const{from:r,to:n}=o;return{clipCount:0,wordCount:n-r}},fat=e=>e.splice(1).reduce((t,o)=>({from:o.from,to:o.to,next:t}),{from:e[0].from,to:e[0].to}),Zg=(e,t)=>{const o=ii({}),r={mainAssetIdsInClip:[]};if(Object.entries(e).forEach(([n,{trackIds:a,role:i}])=>{const s=Je(n);if(i==="main"){if(t.includes(s)){h("transcript.ts").error("Main asset "+s+" is included in clip asset ids"),r.mainAssetIdsInClip.push(s);return}L.set(o,s,{trackIds:a,role:i,rangeType:tr.WORD});return}L.set(o,s,{trackIds:a,role:i,rangeType:t.includes(s)?tr.CLIP:tr.WORD})}),r.mainAssetIdsInClip.length>0&&(wi()||fr.level===Xr.Hotfix)){const n="Main asset "+r.mainAssetIdsInClip.join(", ")+" is included in clip asset ids";h("transcript.ts").warn(n),Y().popup({title:"Errors at convertToAssetEntries()",content:n})}return o},oEe=(e,t,o,r)=>{const n=mH(e,5),a=b2({width:1920,height:1080},void 0,r),i={props:a,projectId:qe.v4(),currentPath:A("startmode.untitled")};return{clipDispatchRange:gn.NEW_PROJECT,clips:n,newSourceOption:fT(i,t),projectProperty:a,audioLanguage:pn.None,sceneId:o}},rEe=(e,t,o,r)=>{const n=mH(e,5),a=b2({width:1920,height:1080},void 0,r);return{clipDispatchRange:gn.NEW_SCENE,clips:n,newSourceOption:fT(void 0,t),projectProperty:a,sceneId:ct(),sceneIndex:o,audioLanguage:pn.None}},b2=(e,t,o,r,n)=>{const a=e.width/e.height,i=Mt(ke.DEFAULT_CAPTION_DISPLAY_MODE);return{globalCaptionStyle:x2e(a),captionDisplayMode:i,trackEntries:t?.tracks??zn({}),baseAssetEntries:t?.assets??{},overdubInfosMap:{},backgroundMap:sy,videoRatio:o?cr(o):a,videoSize:e,markerNames:iy,globalVideoTransform:il,lastTTSSettings:void 0,initProjectVideoSize:e,pronunciationDisplay:p1,projectAudioLanguage:pn.None,audioLanguagesMap:n??{},originalClips:[],ttsClipInfosMap:r??{},denoiseMap:{}}},_N=e=>e.map(t=>t.clips).flatMap(EN),EN=e=>e.flatMap(t=>t.assetIds),mN=()=>{const e=se().getBlankVideoInfo(),{blankAudioBlob:t,blankInfo:o}=e;return{blankInfo:o,blankAudioBlob:t}},fT=(e,t)=>
1115{const{blankAudioBlob:o,blankInfo:r}=mN();return vd({files:[r],blobs:{[r.mediaId]:o},dispatchType:Ee.MEDIA,projectOption:e,startMedia:t})},xx=(e,t)=>{const o=pI(e),r=xI(e),n=dI(e),a=za(e),i=_l(e),s=Ng(e),x=vv(e),c=Nv(e),l=wv(e),d=r[l],{position:u}=i,{globalPosition:p}=s;if(o===void 0)throw h("transcript.ts").error("currentClip is undefined in getElementChunk"),new C(_.C_LOGIC_ERROR);switch(t.type){case"IMPORT_RANGE":switch(t.importRange){case nt.SELECTED_CLIPS:return is(Array.from(x));case nt.SELECTED_WORDS:return XM(o,c);case nt.ALL_CLIPS:return lEe(r);case nt.SCENE_CLIPS:return cEe(d);case nt.CURRENT_CLIP:{if(u===null){const E="position is null in getElementChunk with ImportRange.CURRENT_CLIP";throw h("transcript.ts").error(E),new C(_.C_LOGIC_ERROR,void 0,E)}const f=Er(a,p);return[{from:f,to:f+1,type:"GLOBAL_CLIP"}]}case nt.CURRENT_WORD:if(u===null){const f="position is null in getElementChunk with ImportRange.CURRENT_WORD";throw h("transcript.ts").error(f),new C(_.C_LOGIC_ERROR,void 0,f)}return xEe(i,n,u);case nt.FOLLOW_SELECTED_ELEMENT:{if(p===null||u===null){const S="position is null in getElementChunk with ImportRange.FOLLOW_SELECTED_ELEMENT";throw h("transcript.ts").error(S),new C(_.C_LOGIC_ERROR,void 0,S)}const{selectedElements:f}=i;if(f.length===0)return[];const{id:E}=f[f.length-1],T=a.map((S,R)=>S.assetIds.indexOf(E)!==-1?R:void 0).filter(Se);return T.length!==0?is(T):sEe(n,u,E)}default:throw h("transcript.ts").error("Invalid targetImportRange in getElementChunk"),new C(_.C_LOGIC_ERROR)}case"CUSTOM_GLOBAL_CLIP":return is(t.globalClipIndices);case"CUSTOM_WORD":return XM(o,t.wordPositions);default:throw h("transcript.ts").error("Invalid importOption in getElementChunk"),new C(_.C_LOGIC_ERROR)}},nEe=(e,t)=>{const o=za(e),r=vW(e),n=o.findIndex(s=>s.sceneId===r.id),a=bW(e),i=n+a;if(n===-1)throw h("transcript.ts").error("sceneStartIdx is -1 in getRearrangeElementGlobalChunks"),new C(_.C_LOGIC_ERROR);switch(t.type){case Dn.ALL_SCENES:return[{from:0,to:o.length,type:"GLOBAL_CLIP"}];case Dn.ALL_CLIPS_IN_CURRENT_SCENE:return[{from:n,to:n+r.clips.length,type:"GLOBAL_CLIP"}];case Dn.PROJECT_START_TO_CURRENT:return[{from:0,to:i+1,type:"GLOBAL_CLIP"}];case Dn.START_TO_CURRENT:return[{from:n,to:i+1,type:"GLOBAL_CLIP"}];case Dn.CURRENT_TO_END:return[{from:i,to:n+r.clips.length,type:"GLOBAL_CLIP"}];case Dn.CURRENT_TO_PROJECT_END:return[{from:i,to:o.length,type:"GLOBAL_CLIP"}];case Dn.CURRENT_CLIP:return[{from:i,to:i+1,type:"GLOBAL_CLIP"}];case Dn.TO_CURRENT_CLIP_START_WORD:return[{from:o[i].startPosition,to:o[i].startPosition+1,type:"WORD"}];case Dn.CUSTOM:return t.chunks.map(s=>{if(s.type==="CLIP")return{...s,type:"GLOBAL_CLIP"};if(s.type!=="SCENE")return s}).filter(Se)}},aEe=(e,t)=>{const o=pI(e),r=za(e),n=_l(e),a=Nv(e),{position:i}=n;if(i===null||o===void 0)return;const s=Ys(o),x=t.type==="IMPORT_RANGE"&&t.importRange===nt.SELECTED_WORDS&&s===a.length,c=x?{type:"IMPORT_RANGE",importRange:nt.CURRENT_CLIP}:t,l=xx(e,c);if(l===void 0)return;let d=null;if(l.length>0&&l[0].type==="GLOBAL_CLIP"){const{from:u}=l[0],p=r[u];!p&&h("transcript.ts").warn("on getPasteElementsChunkData(), No clip for chunks: "+JSON.stringify(l)),d=p?.startPosition??null}return{chunks:l,cursorGlobalPosition:d}},U4=(e,t,o,r)=>{const n=pI(e),a=za(e),i=Nv(e);if(n===void 0)return;const s=Ys(n),x=t.type==="IMPORT_RANGE"&&t.importRange===nt.SELECTED_WORDS&&s===i.length,c=x?{type:"IMPORT_RANGE",importRange:nt.CURRENT_CLIP}:t,l=xx(e,c),d=Je(qe.v4()),u=l.map((f,E)=>({chunk:f,assetInfos:[{type:Hx.NEW,assetId:l.length>1?E===0?d:Je(qe.v4()):d,assetType:o,mediaId:r}],audioInfos:[]}));let p=null;if(l.length>0&&l[0].type==="GLOBAL_CLIP"){const{from:f}=l[0],E=a[f];!E&&h("transcript.ts").warn("on getNewElementsChunkData(), No clip for chunks: "+JSON.stringify(l)),p=E?.startPosition??null}return{chunkData:u,cursorAssetId:d,cursorGlobalPosition:p}},gat=(e,t)=>e.map(r=>{const n=Object.entries(t).sort(([a],[i])=>a.localeCompare(i)).map(([,a])=>{const{track:i}=a;return{type:Hx.NEW,assetId:Je(qe.v4()),assetType:i.type,mediaId:i.mediaId}});return{chunk:r,assetInfos:n,audioInfos:[]}}),iEe=(e,t,o,r)=>
1115{const n=_I(e),a=Cxe(e),i=o.map(l=>{const d=L.get(n,l);return d===void 0?void 0:{type:Hx.EXISTING,assetId:l,srcAsset:d.track}}).filter(Se),s=r.map(l=>{const d=L.get(a,l);if(d===void 0)return;const{track:u}=d;return{type:Hx.EXISTING,audioTransformId:l,srcAudioTransform:u,isSoundEffect:Id(u)}}).filter(Se);if(o.length!==i.length||r.length!==s.length)throw h("transcript.ts").error("Invalid assetIds or audioTransformIds in getExistingElementGlobalChunkData"),new C(_.C_LOGIC_ERROR);const x=l=>{if(J0(l)){const{audio:d,...u}=l,p=d?{...d,trackId:Rt()}:void 0;return{...u,trackId:Rt(),...p?{audio:p}:{}}}return{...l,trackId:Rt()}};return t.map((l,d)=>{const u=d>0;return{chunk:l,assetInfos:i.map(p=>u?{...p,assetId:ho(),srcAsset:x(p.srcAsset)}:p),audioInfos:s.map(p=>u?{...p,audioTransformId:ho(),srcAudioTransform:{...p.srcAudioTransform,trackId:Rt()}}:p)}})},sEe=(e,t,o)=>{const r=Co(e,t),n=e[r],{words:a}=n,i=a.map((x,c)=>x.assetIds.indexOf(o)!==-1?c:void 0).filter(Se);return[{from:i[0],to:i[i.length-1]+1,type:"WORD"}]},xEe=(e,t,o)=>{const{globalWordRange:r}=e,n=Co(t,o),a=ns(t[n],o);return[r!==null&&Bv(r)===1?{from:G0(r).from,to:G0(r).to,type:"WORD"}:{from:a,to:a+1,type:"WORD"}]},cEe=e=>[{from:e.globalClipRange.from,to:e.globalClipRange.to,type:"GLOBAL_CLIP"}],XM=(e,t)=>[{from:ns(e,t[0]),to:ns(e,t[t.length-1])+1,type:"WORD"}],lEe=e=>[{from:0,to:e.length,type:"SCENE"}],dEe=(e,t,o,r)=>{for(let n=o;n<e.length;n++){const a=e[n],i=n===o?r:0;for(let s=i;s<a.words.length;s++)if(a.words[s].type===Z.NORMAL&&a.words[s].text===t)return{clipIndex:n,wordIndex:s}}},uEe=(e,t,o,r)=>{let n=t,a=o,i=r;for(;n>0&&a<e.length&&(i++,i>=e[a].words.length&&(a++,i=0),!(a>=e.length));)e[a].words[i].type===Z.NORMAL&&n--;return{nextClipIdx:a,nextWordIdx:i}},pEe=(e,t)=>{const o=[];let r=0,n=0;for(const a of t){const i=a[0],s=dEe(e,i,r,n);if(s===void 0){const p="Cannot find word: "+i+" from clipIdx: "+r+", wordIdx: "+n;return h("transcript.ts").error(p),[]}const{clipIndex:x,wordIndex:c}=s,l=e[x].words[c];o.push(l.id);const{nextClipIdx:d,nextWordIdx:u}=uEe(e,a.length,x,c);r=d,n=u}return o},_at=e=>(e.type==="color-hex"||e.type==="color-rgb")&&e.attributeName!=="--textbox-color",fEe=e=>{const t=[];return Object.entries(e).forEach(([o,r])=>{Gn(r)&&r.editInfo?.removeBackgroundInfo?.isRemoveBackgroundDone===!1&&t.push(kr(o))}),t},V4=e=>e.every(t=>t instanceof Object?typeof t.fileName=="string"&&typeof t.globalPosition=="number":!1),Eat=e=>{const t=se();if(t.getCurrentProjectFileType()===Ee.EMPTY)return;const o=t.getCurrentProjectPath();if(e===null){h("transcript.ts").error("Invalid globalPosition at saveEditPosition()");return}let r=Ve().getArray(Ie.LAST_OPEN_FILE_NAMES,V4);r.some(a=>a.fileName===o)?r=r.filter(a=>a.fileName!==o):r.length>=5&&r.shift(),r.push({fileName:o,globalPosition:e}),Ve().set(Ie.LAST_OPEN_FILE_NAMES,r)},gEe=e=>Ve().getArray(Ie.LAST_OPEN_FILE_NAMES,V4).find(r=>r.fileName===e)?.globalPosition??null,mat=e=>{const t=se();if(t.getCurrentProjectFileType()===Ee.EMPTY)return;const o=t.getCurrentProjectPath(),r=Ve().getObject(Ie.LAST_SCENE_FOLD_INFO);r[o]=e,Ve().set(Ie.LAST_SCENE_FOLD_INFO,r)},_Ee=e=>Ve().getObject(Ie.LAST_SCENE_FOLD_INFO)[e]??{},G4=(e,t)=>{const o={},r={};for(const[a,i]of Object.entries(t)){const{trackIds:s,role:x,rangeType:c}=i,l=s.map(f=>L.get(e,f)).filter(Se);if(l.length===0){h("transcript.ts").warn("No valid tracks are contained in asset with assetId: "+a);continue}if(l.length===1){const f=l[0];Rr(f)?h("transcript.ts").warn("Watermark track is contained in asset with assetId: "+a):Wa(f)?L.set(r,Je(a),{track:f,role:x}):L.set(o,Je(a),{track:f,role:x,rangeType:c});continue}const d=l.find(f=>mn(f));if(!d){h("transcript.ts").warn("Multiple tracks are contained in non-video asset with assetId: "+a);continue}const u=l.find(f=>U0(f)||By(f)),p={...d,audio:u};L.set(o,Je(a),{track:p,role:x,rangeType:c})}const n=Object.values(e).find(Rr);return{assetInfos:o,audioTransformsMap:r,watermark:n}},EEe=e=>{if(J0(e)){const{audio:t,...o}=e;return t?[o,t]:[o]}return[e]},W4=(e,t,o)=>{const r=zn({}),n={};for(const[a,i]of Object.entries(e)){const{track:s,role:x}=i,c=EEe(s),l=c.map(u=>(L.set(r,u.trackId,u),u.trackId)),d={trackIds:l,role:x};L.set(n,Je(a),d)}for(const[a,i]of Object.entries(t)){if(a in r){h("transcript.ts").warn("audioTransformId: "+a+" already exists in trackEntries, skipping...");continue}const{track:s,role:x}=i;L.set(r,kr(s.trackId),s);const c={trackIds:[s.trackId],role:x};L.set(n,Je(a),c)}
1115return o&&L.set(r,o.trackId,o),{trackEntries:r,assetEntries:n}},vd=e=>{const{files:t,blobs:o,dispatchType:r,projectOption:n,startMedia:a,analyzeDate:i=YCe(new Date)}=e;return{dispatchType:r,files:t,blobs:o,newProjectOption:n,analyzeDate:i,startMedia:a}},Rt=()=>kr(ct()),H4=()=>kr("dummyTrackId"),ho=()=>Je(qe.v4()),$g=()=>({version:Ha(),date:na.local().toFormat("yyyy-MM-dd'T'HH:mm:ssZZ"),stage:fr.level}),iA=()=>({created:void 0,updated:void 0,loadCount:0,saveCount:0}),gT=(e,t)=>{const o=$g();return t?{created:o,updated:o,loadCount:0,saveCount:1}:{...e,updated:o,saveCount:e.saveCount+1}},j4=["Pretendard-Vrew","Noto Sans JP-Vrew","Noto Sans TC-Vrew"],z4="-Vrew",Y4="2.8.0";var mEe=(e=>(e.SYSTEM="system",e.WEB="free",e.BOOKMARK="bookmark",e))(mEe||{}),B4=(e=>(e.EMPTY="empty",e.RAW_VIDEO="raw_video",e.PROJECT="project",e.SOURCE_VIDEO="source_video",e.COLORED="colored",e))(B4||{});const hat=(e,t,o)=>vt(e,r=>{const{fullRangeAssets:n}=r,a=n.findIndex(i=>i.track.mediaId===t.track.mediaId);if(a===-1){if(r.fullRangeAssets.push(t),o){const{ext:i,mimeType:s}=o;L.set(r.assetLocationMap,t.track.mediaId,{assetLocation:D.IN_MEMORY,pathInFile:t.track.mediaId+"."+i,mimeType:s})}return}r.fullRangeAssets[a]=t}),Iat=(e,t)=>vt(e,o=>{const r=o.fullRangeAssets,n=r.findIndex(a=>a.track.mediaId===t);return n>=0&&r.splice(n,1),L.remove(o.assetLocationMap,t),o}),K4=e=>R6.includes(e.type),hEe=e=>e.assetLocation===D.REMOTE,Tat=e=>e.getType()===B4.COLORED,IEe=async(e,t)=>{const{track:o}=e;switch(t.assetLocation){case D.IN_MEMORY:{const r=ei().getImageFileInfo(o.mediaId);if(r===void 0)throw new C(_.C_FRAMEPACK_GENERAL_ERROR,{},"Attempted to import meida id "+o.mediaId+" but image file info doesn't exist");const{blob:n,imageInfo:a}=r;return{blob:n,isTransparent:a.isTransparent}}case D.REMOTE:{const r=t.src;return{blob:await(await fetch(r)).blob(),isTransparent:!0}}}},TEe=async e=>{if(Qx(e))return e.mediaId;const t=ei().getShapeInfo(e.mediaId);if(t===void 0)throw new C(_.C_FRAMEPACK_GENERAL_ERROR,{},"Attempted to import media id "+e.mediaId+" but shapeInfo doesn't exist");const o=se(),r=x_(e.mediaId),n=o.getCurrentProjectFileType(),a=n===Ee.CLOUD&&r?.fileLocation===D.REMOTE||n!==Ee.CLOUD&&r?.fileLocation===D.IN_MEMORY;return r&&a?r.mediaId:r?(await n5(t.shapeInfo.rawSvg,e.mediaId),e.mediaId):(await o5(t.shapeInfo.rawSvg,e.mediaId),e.mediaId)},SEe=async e=>{const t=ei().getTextboxInfo(e.mediaId);if(t===void 0)throw new C(_.C_FRAMEPACK_GENERAL_ERROR,{},"Attempted to import media id "+e.mediaId+" but textboxInfo doesn't exist");const o=se(),r=UT(e.mediaId,{excludeBroken:!0}),n=o.getCurrentProjectFileType(),a=n===Ee.CLOUD&&r?.fileLocation===D.REMOTE||n!==Ee.CLOUD&&r?.fileLocation===D.IN_MEMORY;return r&&a?r.mediaId:r?(await r5(t.textboxInfo.rawHtml,e.mediaId),e.mediaId):(await eP(t.textboxInfo.rawHtml,e.mediaId),e.mediaId)},OEe=async e=>{const{fullRangeAssets:t,assetLocationMap:o}=e,r={};for(const n of t){const a={...n.track,trackId:Rt()};switch(a.type){case z.IMAGE:{const i=L.get(o,a.mediaId);if(i===void 0)throw new C(_.C_FRAMEPACK_GENERAL_ERROR,{},"Asset location for "+a.mediaId+" cannot be found");const{blob:s,isTransparent:x}=await IEe(n,i),c=qe.v4();await vi(s,x,void 0,c),r[Je(c)]={track:{...a,mediaId:c,stats:{sourceFramePackId:e.id}},role:"sub",rangeType:tr.CLIP};break}case z.SHAPE:{await TEe(a);const i=ho();r[i]={track:{...a,stats:{sourceFramePackId:e.id}},role:"sub",rangeType:tr.CLIP};break}case z.WEB:{await SEe(a);const i=ho();r[i]={track:{...a,stats:{sourceFramePackId:e.id}},role:"sub",rangeType:tr.CLIP};break}}}return r},CEe=async(e,t)=>{if(K4(e))switch(e.type){case z.IMAGE:{const o=oa(e.mediaId);if(o===void 0)return;const r=await En(e.mediaId);if(!r)return;const n=o.isTransparent,a=ei().registerImageBlob({blob:r,isTransparent:n}),i=a.mediaId;return L.set(t,i,{assetLocation:D.IN_MEMORY,pathInFile:i+".png",mimeType:"image/png"}),{editable:!1,track:{...e,mediaId:a.mediaId}}}case z.WEB:{const o=UT(e.mediaId,{excludeBroken:!0});if(o===void 0)return;const r=o.mediaId,n=await En(e.mediaId);return n?(ei().registerTextboxInfo(o,n),L.set(t,r,{assetLocation:D.IN_MEMORY,pathInFile:r+".html",mimeType:"text/html"}),{editable:!1,track:{...e,mediaId:r}}):void 0}case z.SHAPE:if(i2(e)){const o=x_(e.mediaId);if(o===void 0)return;const r=await En(e.mediaId);if(!r)return;ei().registerShapeInfo(o,r),L.set(t,o.mediaId,{assetLocation:D.IN_MEMORY,pathInFile:o.mediaId+".xml",mimeType:"application/xml"})}return{editable:!1,track:{...e}}}},REe=async e=>{const t={};return{fullRangeAssets:(await Promise.all(Object.values(e).map(n=>CEe(n.track,t)))).filter(Se),assetLocationMap:t}},Sat=async(e,t,o,r)=>{const n=Gf(o,ro.CONTAIN),a=Gf(o,ro.CUT),i=KM(r,n)?ro.CONTAIN:KM(r,a)?ro.CUT:ro.CONTAIN,s=qe.v4(),x={videoRatio:o,videoTransformFillType:i},{fullRangeAssets:c,assetLocationMap:l}=await REe(e),d=$g();return{id:s,videoTransform:x,globalCaptionStyle:t,fullRangeAssets:c,assetLocationMap:l,createdInfo:d}},Oat=e=>e.videoTransform.videoRatio===he.WIDE_SCREEN||e.videoTransform.videoRatio===he.CLASSIC,Cat=e=>e.videoTransform.videoRatio===he.VERTICAL||e.videoTransform.videoRatio===he.SQUARE||e.videoTransform.videoRatio===he.INSTAGRAM,Rat=(e,t,o)=>{if(!Oo())return bSe("create_template"),!1;const r=X_e(j0(e));return r===void 0?Y().warn(A("template.warn_ratio_not_supported")):(t===kn.FRAMEPACK&&o(),Y().openModal(st.CREATE_FRAMEPACK,{currentProjectRatio:r})),!0};var Zn=(e=>(e.IMAGE="image",e.LOTTIE="lottie",e.WEB="web",e.VIDEO="video",e.SHAPE="shape",e.SIMPLE_CHARACTER="simpleCharacter",e.WATERMARK="watermark",e))(Zn||{}),Tx=(e=>(e[e.NONE=0]="NONE",e[e.VERTICAL=1]="VERTICAL",e[e.HORIZONTAL=2]="HORIZONTAL",e[e.VERTICAL_HORIZONTAL=3]="VERTICAL_HORIZONTAL",e))(Tx||{});const X4=async(e,t)=>({vrewJson:{...e,version:17,props:AEe(e.props)},blobs:t}),AEe=e=>{const{mediaEffectMap:t,flipSetting:o,tracks:r,denoiseMap:n,...a}=e,i=new Map;Object.entries(t??{}
1115).forEach(([c,l])=>{const{filter:d}=l;d===void 0||d.filterMediaId===Gl||i.set(c,{filterMediaId:d.filterMediaId,alpha:ur(d.filterAlphas[d.filterMediaId]??vh)})});const s=yEe(e.assets),x={};for(const[c,l]of Object.entries(r))L.set(x,kr(c),J4(l,i,o,s.has(l.trackId)));return{...a,tracks:x,denoiseMap:n??{}}},yEe=e=>{const t=new Set;return Object.values(e).forEach(o=>{o.role==="main"&&o.trackIds.forEach(r=>{t.add(r)})}),t},JM=e=>{if(!(e===void 0||e===Tx.NONE))switch(e){case Tx.VERTICAL:return{vertical:!0,horizontal:!1};case Tx.HORIZONTAL:return{vertical:!1,horizontal:!0};case Tx.VERTICAL_HORIZONTAL:return{vertical:!0,horizontal:!0}}},J4=(e,t,o,r=!1)=>{switch(e.type){case Zn.IMAGE:{const n=r?o?.[e.mediaId]:e.editInfo?.flip;return{...e,type:Hr.IMAGE,filterEffect:t.get(e.mediaId),editInfo:e.editInfo||n?{crop:e.editInfo?.crop,...e.editInfo,flip:JM(n)}:void 0}}case Zn.LOTTIE:return{...e,type:Hr.LOTTIE,filterEffect:t.get(e.mediaId)};case Zn.WEB:return{...e,type:Hr.WEB,filterEffect:t.get(e.mediaId)};case Zn.VIDEO:{const n=r?o?.[e.mediaId]:e.editInfo?.flip;return{...e,type:Hr.VIDEO,filterEffect:t.get(e.mediaId),editInfo:e.editInfo||n?{crop:e.editInfo?.crop,...e.editInfo,flip:JM(n)}:void 0}}case Zn.SHAPE:return{...e,type:Hr.SHAPE,filterEffect:t.get(e.mediaId)};case Zn.SIMPLE_CHARACTER:return{...e,type:Hr.SIMPLE_CHARACTER,filterEffect:t.get(e.mediaId)};case Zn.WATERMARK:return{...e,type:Hr.WATERMARK,filterEffect:t.get(e.mediaId)};case"ttsClip":case"videoAudio":case"soundEffect":case"bgm":case"overdub":case"ttsEffect":case"ttsDubbing":return e}},q4=e=>({...e,fullRangeAssets:e.fullRangeAssets.map(t=>({...t,trackModel:J4(t.trackModel,new Map,{})}))});var hi=(e=>(e.IMAGE="image",e.LOTTIE="lottie",e.WEB="web",e.VIDEO="video",e.SHAPE="shape",e.SIMPLE_CHARACTER="simpleCharacter",e.WATERMARK="watermark",e))(hi||{}),Sx=(e=>(e[e.NONE=0]="NONE",e[e.VERTICAL=1]="VERTICAL",e[e.HORIZONTAL=2]="HORIZONTAL",e[e.VERTICAL_HORIZONTAL=3]="VERTICAL_HORIZONTAL",e))(Sx||{});const Bm=(e,t,o,r)=>e.filter(n=>L.get(t,n)!==void 0?!0:(h("vrewJsonUpgraderV15.ts").warn("[VrewJsonUpgraderV15] Excluding orphan "+r+"Id "+n+" ("+o+")"),!1)),Q4=async(e,t)=>{const{props:o,transcript:r,files:n}=e,{props:a,transcript:i}=vEe(o,r,n),s={...e,version:16,props:a,transcript:i};return await X4(s,t)},vEe=(e,t,o)=>{const{audios:r,waterMark:n,...a}=e,i=wEe(o),s=NEe(e.overdubInfos),x={},c={},{tracks:l,assets:d}=PEe(e.assets,e.audios,e.waterMark,i,s),{overdubInfos:u,tracks:p,assets:f}=MEe(t,e.overdubInfos,i),{originalClips:E,tracks:T,assets:O}=DEe(e.originalClipsMap,e.ttsClipInfosMap,i),{transcript:S,tracks:R,assets:y}=kEe(t,e.assets,e.audios,e.overdubInfos,e.ttsClipInfosMap,i);Object.assign(x,l,p,T,R),Object.assign(c,d,f,O,y);const v=HEe(e.flipSetting);return{props:{...a,tracks:x,assets:c,overdubInfos:u,originalClips:E,flipSetting:v},transcript:S}},wEe=e=>{const t=new Map;for(const o of e){if(o.type!=="AVMedia")continue;const{duration:r,videoInfo:n,audioInfo:a}=o.videoAudioMetaInfo;t.set(o.mediaId,{videoInfo:n,hasAudio:a!==void 0,duration:r})}return t},NEe=e=>{const t=new Map;for(const[o,r]of Object.entries(e))t.set(Je(r.audioTransformId),Yy(o));return t},PEe=(e,t,o,r,n)=>{const a={},i={};for(const[s,x]of Object.entries(e)){const c=Z4(x,r);for(const l of c)L.set(a,l.trackId,l);L.set(i,Je(s),{trackIds:c.map(l=>l.trackId),role:"sub"})}for(const[s,x]of Object.entries(t)){const c=n.get(Je(s)),l=bEe(x,r,c);L.set(a,l.trackId,l),L.set(i,Je(s),{trackIds:[l.trackId],role:"sub"})}if(o){const s=LEe(o);L.set(a,s.trackId,s)}return{tracks:a,assets:i}},Z4=(e,t)=>{switch(e.type){case hi.IMAGE:return[{...e,type:Zn.IMAGE,trackId:Rt()}];case hi.LOTTIE:return[{...e,type:Zn.LOTTIE,trackId:Rt()}];case hi.VIDEO:{const{volume:o,...r}=e,n={...r,type:Zn.VIDEO,sourceIn:e.sourceIn,sourceOut:e.sourceIn,trackId:Rt()},a=t.get(e.mediaId)?.hasAudio?{trackId:Rt(),mediaId:e.mediaId,volume:o,type:"videoAudio",sourceIn:e.sourceIn,sourceOut:e.sourceIn,loop:!0,playbackRate:Un}:void 0;return a?[n,a]:[n]}case hi.SIMPLE_CHARACTER:return[{...e,type:Zn.SIMPLE_CHARACTER,trackId:Rt()}];case hi.SHAPE:return[{...e,type:Zn.SHAPE,trackId:Rt()}];case hi.WEB:return[{...e,type:Zn.WEB,trackId:Rt()}]}},bEe=(e,t,o)=>{const r=t.get(e.mediaId)?.duration,n=pe(r!==void 0?$t(e.sourceIn,0,r):Math.max(e.sourceIn,0)),a=e.sourceOut,i=r!==void 0?pe(r-$t(a,0,r)):n,s=pe(Math.max(i,n));switch(e.type){case"soundEffect":case"bgm":return{...e,trackId:Rt(),type:e.type,sourceIn:n,sourceOut:s};case"overdub":{if(!o)throw new C(_.C_LOGIC_ERROR,{}
1115,"OverdubId not found for overdub audio");return{...e,trackId:Rt(),type:e.type,sourceIn:n,sourceOut:s,overdubId:o}}case"ttsEffect":case"ttsDubbing":return{...e,trackId:Rt(),type:e.type,sourceIn:n,sourceOut:s}}},LEe=e=>({...e,trackId:Rt(),type:Zn.WATERMARK,vrewMarkInfo:e.vrewMark}),MEe=(e,t,o)=>{const r={},n={},a={},i={};for(const s of e.scenes)for(const x of s.clips)for(const c of x.words)c.overdubId&&L.set(i,c.overdubId,c.mediaId);return Object.entries(t).forEach(([s,x])=>{const c=L.get(i,s),l=[];for(const d of x.originWords){const u=[];if(c){const{mainVisualTrack:p,mainAudioTrack:f}=WEe(d,c,o);p&&L.set(n,p.trackId,p),f&&L.set(n,f.trackId,f);const E=p||f?{trackIds:[p?.trackId,f?.trackId].filter(Se),role:"main"}:void 0,T=E?ho():void 0;E&&T&&(L.set(a,T,E),u.push(T))}l.push({text:d.text,duration:d.duration,aligned:d.aligned,wordType:d.wordType,originalDuration:d.originalDuration,originalStartTime:d.originalStartTime,assetIds:u,hardcutWordMeta:d.hardcutWordMeta,pronunciation:d.pronunciation})}L.set(r,Yy(s),{originWords:l})}),{overdubInfos:r,tracks:n,assets:a}},DEe=(e,t,o)=>{const r={},n={},a=[];for(const[i,s]of Object.entries(e)){const{clips:x,tracks:c,assets:l}=$4(s,i,{},{},{},t,o);Object.assign(r,c),Object.assign(n,l),a.push(...x)}return{tracks:r,assets:n,originalClips:a}},kEe=(e,t,o,r,n,a)=>{const i={},s={},x={};return{transcript:{clips:e.scenes.flatMap(l=>{const{clips:d,tracks:u,assets:p}=$4(l.clips,l.id,t,o,r,n,a);return Object.assign(i,u),Object.assign(s,p),l.name&&(x[l.id]=l.name),d.map(f=>({...f,sceneId:l.id}))}),sceneNames:x,translateInfo:e.scenes[0]?.translateInfo??null},tracks:i,assets:s}},$4=(e,t,o,r,n,a,i)=>{const s={},x={};return{clips:e.map(l=>{const{clip:d,tracks:u,assets:p}=FEe(l,t,o,r,n,a,i);return Object.assign(s,u),Object.assign(x,p),d}),tracks:s,assets:x}},FEe=(e,t,o,r,n,a,i)=>{const{words:s,tracks:x,assets:c}=ej(e.words,o,r,n,a,i),l="clipId: "+e.id+", sceneId: "+t,d=Bm(e.assetIds,o,l,"asset"),u=Bm(e.audioIds,r,l,"audio");return{clip:{sceneId:t,words:s,captionMode:e.captionMode,captions:e.captions,markerId:e.markerId,assetIds:[...d,...u],dirty:e.dirty,translationModified:e.translationModified,id:e.id,videoTransform:e.videoTransform,backgroundId:e.backgroundId,transitionModel:e.transitionModel},tracks:x,assets:c}},ej=(e,t,o,r,n,a)=>{const i={},s={};return{words:e.map(c=>{const{word:l,tracks:d,assets:u}=UEe(c,t,o,r,n,a);return Object.assign(i,d),Object.assign(s,u),l}),tracks:i,assets:s}},UEe=(e,t,o,r,n,a)=>{const i={},s={},x=e.sourceAudioTransformId?L.get(o,e.sourceAudioTransformId):void 0,c=VEe(e.overdubId,r),l=c?L.get(o,c):void 0,{mainVisualTrack:d,mainAudioTrack:u}=GEe(e,x,l,n,a);d&&L.set(i,d.trackId,d),u&&L.set(i,u.trackId,u);const p=d||u?{trackIds:[d?.trackId,u?.trackId].filter(Se),role:"main"}:void 0,f=p?c??ho():void 0;p&&f&&L.set(s,f,p);const E=e.truncatedWords.length>0?e.truncatedWords:e.autoControl?[{...e,autoControl:!1,id:ct(),duration:pe(Math.max(0,e.originalStartTime+e.originalDuration-e.startTime))}]:[],{words:T,tracks:O,assets:S}=ej(E,t,o,r,n,a);Object.assign(i,O),Object.assign(s,S);const R="wordId: "+e.id,y=Bm(e.assetIds,t,R,"asset"),v=Bm(e.audioIds,o,R,"audio");return{word:{id:e.id,text:e.text,pronunciation:e.pronunciation,playbackRate:e.playbackRate,duration:e.duration,aligned:e.aligned,type:e.type,originalDuration:e.originalDuration,originalStartTime:e.originalStartTime,truncatedWords:T,assetIds:[...f?[f]:[],...y,...v],hardcutWordMeta:e.hardcutWordMeta,freeze:e.type===Z.SPACER?e.freeze:void 0},tracks:i,assets:s}},VEe=(e,t)=>{if(!e)return;const o=L.get(t,e)?.audioTransformId;return o?Je(o):void 0},jE={videoInfo:{size:{width:1,height:1}},hasAudio:!0,duration:0},GEe=(e,t,o,r,n)=>{if(e.mediaId===_o||e.type===Z.ENTER||e.type===Z.SPACER)return{mainVisualTrack:void 0,mainAudioTrack:void 0};if(e.overdubId&&o){const{mediaId:d}=o,{hasAudio:u,duration:p}=n.get(d)??jE,f=u?{trackId:Rt(),mediaId:d,volume:t?.volume??ma,type:"overdub",sourceIn:pe(0),sourceOut:pe(p),loop:!1,playbackRate:Un,overdubId:Yy(e.overdubId)}:void 0,{videoInfo:E}=n.get(e.mediaId)??jE;return{mainVisualTrack:E!==void 0?{trackId:Rt(),mediaId:e.mediaId,xPos:0,yPos:0,height:0,width:0,rotation:0,zIndex:0,type:Zn.VIDEO,sourceIn:pe(e.startTime),sourceOut:pe(e.startTime+e.duration),originalWidthHeightRatio:E.size.width/E.size.height,isTrimmable:!0,hasAlphaChannel:!1,editInfo:void 0,fillType:void 0}:void 0,mainAudioTrack:f}}const{videoInfo:a,hasAudio:i}=n.get(e.mediaId)??jE,s=a!==void 0,x=i&&!s&&L.get(r,e.mediaId)!==void 0,c=s?{trackId:Rt(),mediaId:e.mediaId,xPos:0,yPos:0,height:0,width:0,rotation:0,zIndex:0,type:Zn.VIDEO,sourceIn:pe(e.startTime),sourceOut:pe(e.startTime+e.duration),originalWidthHeightRatio:a.size.width/a.size.height,isTrimmable:!0,hasAlphaChannel:!1,editInfo:void 0,fillType:void 0}:void 0,l=i?{trackId:Rt(),mediaId:e.mediaId,volume:t?.volume??ma,type:x?"ttsClip":"videoAudio",sourceIn:pe(e.startTime),sourceOut:pe(e.startTime+e.duration),loop:!1,playbackRate:Un}:void 0;return{mainVisualTrack:c,mainAudioTrack:l}},WEe=(e,t,o)=>{if(t===_o||e.wordType===Z.ENTER||e.wordType===Z.SPACER)return{mainVisualTrack:void 0,mainAudioTrack:void 0};const{videoInfo:r,hasAudio:n}=o.get(t)??jE,a=r!==void 0,i=a?{trackId:Rt(),mediaId:t,xPos:0,yPos:0,height:0,width:0,rotation:0,zIndex:0,type:Zn.VIDEO,sourceIn:pe(e.startTime),sourceOut:pe(e.startTime+e.duration),originalWidthHeightRatio:r.size.width/r.size.height,isTrimmable:!0,hasAlphaChannel:!1,editInfo:void 0,fillType:void 0}:void 0,s=n?{trackId:Rt(),mediaId:t,volume:ma,type:"videoAudio",sourceIn:pe(e.startTime),sourceOut:pe(e.startTime+e.duration),loop:!1,playbackRate:Un}:void 0;return{mainVisualTrack:i,mainAudioTrack:s}},HEe=e=>{if(e===void 0)return{};const t=o=>{switch(o){case Sx.NONE:return Tx.NONE;case Sx.VERTICAL:return Tx.VERTICAL;case Sx.HORIZONTAL:return Tx.HORIZONTAL;case Sx.VERTICAL_HORIZONTAL:return Tx.VERTICAL_HORIZONTAL}};return Object.fromEntries(Object.entries(e).map(([o,r])=>[o,t(r)]))},tj=e=>q4({...e,fullRangeAssets:e.fullRangeAssets.map(t=>({...t,trackModel:Z4(t.assetModel,new Map)[0]}))}),jEe=100;class zEe{audioCtx;audioCache;playEntries;constructor(){this.audioCtx=new(window.AudioContext||window.webkitAudioContext),this.audioCache=new Qv(jEe,({requestProp:t},{requestProp:o})=>this.isSameTTSRequestProps(t,o)),this.playEntries={}}toTTSCacheEntry=(t,o,r,n,a,i)=>({blob:t,mediaId:o,requestProp:r,timestamps:n,errorInfo:a,options:i});_toCacheKey=t=>({requestProp:{...t,volume:Vm(t)?t.volume:0,speed:Vu(t)?t.speed:0}});getEntry=t=>{const o=this.audioCache.get(this._toCacheKey(t));return o===void 0?null:{...o,requestProp:{...o.requestProp,volume:Vm(t)?o.requestProp.volume:t.volume,speed:Vu(t)?o.requestProp.speed:t.speed,effect:t.effect}}};setEntry=t=>{this.audioCache.set(this._toCacheKey(t.requestProp),t)};doesExist=t=>this.audioCache.has(this._toCacheKey(t));play=async(t,o,r,n,a)=>{const i=t.mediaId;try{a?.throwIfAborted();const s=this.audioCtx,x=await Rd(await t.blob.arrayBuffer());a?.throwIfAborted();const c=s.createBufferSource(),l=x.getChannelData(0),d=Math.min(x.duration/5,1),u=zw(l,x.sampleRate,0,d),p=s.createBuffer(x.numberOfChannels,x.length,x.sampleRate);
1115p.copyToChannel(u,0),c.buffer=p,o&&o(i);const f=()=>{delete this.playEntries[i],r&&r(i)};r&&c.addEventListener("ended",f),c.connect(s.destination),c.start(),this.playEntries[i]={audioId:i,node:c,playing:!0,onEnd:f}}catch(s){if(a?.aborted)return;n&&n(i),h("ttsBlobManager.ts").error("Error playing audio in ttsBlobManager "+P(s)),delete this.playEntries[i]}};stop=(t,o,r)=>{o&&o();const n=this.playEntries[t];n?.onEnd&&(r!=="leave"&&n?.node.removeEventListener("ended",n?.onEnd),r==="invoke"&&n?.onEnd()),n?.node.stop(),delete this.playEntries[t]};stopAll=t=>{Object.values(this.playEntries).forEach(o=>{o.onEnd&&(t!=="leave"&&o.node.removeEventListener("ended",o.onEnd),t==="invoke"&&o?.onEnd()),o.node.stop()}),this.playEntries={}};isSameTTSRequestProps=(t,o)=>$I(t.speaker,o.speaker)&&t.pitch===o.pitch&&t.speed===o.speed&&t.volume===o.volume&&t.text.processed===o.text.processed&&vw(t.emotion,o.emotion)&&Lw(t,o)&&dv(t,o)&&t.version===o.version}let UO=null;const Wf=()=>(UO===null&&(UO=new zEe),UO);class Yr extends Error{constructor(t,o,r,n){super(o),this.errorType=t,this.httpStatus=r,this.transport=n}errorType;httpStatus;transport}const YEe=new Set([408,429]),BEe=e=>!(e instanceof Yr)||e.errorType!=="network"?!1:e.transport===!0?!0:e.httpStatus===void 0?!1:e.httpStatus>=500||YEe.has(e.httpStatus),KEe=new Map(Object.entries({invalid_input:"invalid_input",different_lang:"different_lang",low_version:"low_version",quota_exceeded:"quota_exceeded",authorization:"authorization",timeout:"timeout",speaker_deleted:"speaker_deleted",db:"db",aws:"aws",network:"network",api_network:"api_network",device_too_many_free_account:"device_too_many_free_account",pricing_changed:"pricing_changed",unknown:"unknown"})),Km=e=>e instanceof Yr?KEe.get(e.errorType):void 0;class hN{entry;constructor(t){this.entry=t}}class Bi extends hN{static TTSTimestampProcessingError={FA_BAD_RESPONSE:"FA_BAD_RESPONSE"};async process(){const t=Tt(this.entry).pipe(St(o=>{const r=o.timestamps===void 0;return L9(()=>r,n2(()=>zt(Bi._getTimestampsFromFA(o))),Tt(o.timestamps)).pipe(At(Bi._validateTimestamp),At(n=>r||Vu(this.entry.requestProp)?n:Ka.adjustTimestamps(n,this.entry.requestProp.speed)))}),At(o=>({...this.entry,timestamps:o})),a2(2),c0(o=>(h("ttsPostProcessor.ts").error("error during fa request: "+P(o)),Tt({...this.entry,timestamps:void 0}))));return Bt(t)}static doesNeedFaRequest(t,o){return t.errorInfo===void 0&&t.timestamps===void 0&&o===Sc.CLIP}static _convertTTSTimestamps(t){return t.map(o=>[o.word,ue(o.startTime,2),ue(o.startTime+o.duration,2)])}static _getTimestampsFromFA(t){return Bt(Tt(t).pipe(Ma(Bi._preprocessFa),St(({faText:o,faLang:r,alignText:n})=>Bi._requestFa(t,o,r,n))))}static async _preprocessFa(t){const o=h("ttsPostProcessor.ts"),{text:r}=t.requestProp,n=t.requestProp.text.textAspectLang,a=UE(r.processed),{faText:i,alignText:s}=await Bi._getTextForFA(a,n),x=n.split("-")[0];if(i===null)throw o.error("error while tokenizing text, lang: "+n+", text: "+r),new C(_.C_TTS_TOKENIZE_ERROR);return{faText:Bi.getSpecialCharacterConcatedText(i),alignText:s?Bi.getSpecialCharacterConcatedText(s):void 0,faLang:x}}static getSpecialCharacterConcatedText(t){const o=/^[-\uff01\uff1f\uff0e\uff0c\u2010-\u2014\u2018-\u201d\u2024-\u2026\u3000-\u3002\u30fb\u30fd-\u30ff\uff61\uff64\uff65\uff9e\uff9f]+$/g,r=/^[-=+,#/?^$.@*"※~&%ㆍ・!』\\|()[\]<>`'…》°÷%¿¡㎏㎐㎞㎝㎛㎡㈜。、]+$/g;return t.split(" ").reduce((i,s)=>{if(i.length===0)return[s];if(s.match(o)||s.match(r)){const x=i.pop();return i.push(x+s),i}return i.push(s),i},[]).join(" ")}static async _getTextForFA(t,o){switch(o){case ft.English:case ft.Korean:case ft.Spanish:return Promise.resolve({faText:t,dict:null});case ft.Chinese:case ft.Taiwanese:return{faText:await hse(t,o),dict:null};case ft.Japanese:{const r=await mse(t,"spacedFurigana");return{faText:UE(r.text),dict:r.furiganaMap,alignText:UE(r.spacedKanjiText)}}}}static async _requestFa(t,o,r,n){const a=h("ttsPostProcessor.ts"),i=await Rd(await t.blob.arrayBuffer()),s=Jg(i.getChannelData(0).buffer,{isFloat:!0,numChannels:1,sampleRate:i.sampleRate,numFrames:Math.floor(i.sampleRate*i.duration)}),x=(await V2(new Blob([s],{type:"audio/wav"}))).replace("data:audio/wav;base64,",""),c=await vOe("/fa/"+r,{method:"POST",body:JSON.stringify({wav:x,lang:r,text:o,speaker:t.requestProp.speaker.name})});if(!c.ok)throw a.error("failed to fetch fa result: status is not ok. "+c.status+":"+c.statusText),new Error(Bi.TTSTimestampProcessingError.FA_BAD_RESPONSE);const l=await c.json();if(n){const d=n.split(" ");l.forEach((u,p)=>u[0]=d[p]??"")}return l}static _validateTimestamp(t){if(t===void 0)throw new Error("timestamp is undefined");const o=h("ttsPostProcessor.ts");if(t.length===0)throw o.error("empty response from FA"),new Error(Bi.TTSTimestampProcessingError.FA_BAD_RESPONSE);for(const[r,n,a]of t)if(n>a)throw o.error("fa word minus duration from fa: "+JSON.stringify(t)+", Text : "+r),new Error(Bi.TTSTimestampProcessingError.FA_BAD_RESPONSE);return t}}class Ka extends hN{static TTS_AUDIO_SETTING={volume:{min:.2,max:1.3},speed:{min:.5,max:1.5}};async process(){const t=!Vm(this.entry.requestProp),o=!Vu(this.entry.requestProp);return!t&&!o?this.entry:{...this.entry,mediaId:ct(),blob:await Ka._adjust(this.entry,this.entry.requestProp,t,o)}}static async _adjust(t,o,r,n){const a=r?Ka._scaleUIValue(Ka.TTS_AUDIO_SETTING.volume.min,Ka.TTS_AUDIO_SETTING.volume.max,o.volume):1,i=n?Ka._scaleUIValue(Ka.TTS_AUDIO_SETTING.speed.min,Ka.TTS_AUDIO_SETTING.speed.max,o.speed):1;return hfe(t.blob,a,i)}static adjustTimestamps(t,o){const r=Ka._scaleUIValue(Ka.TTS_AUDIO_SETTING.speed.min,Ka.TTS_AUDIO_SETTING.speed.max,o);return r===1?t:t.map(([a,i,s])=>{const x=i/r,c=s/r;return[a,x,c]})}static _scaleUIValue(t,o,r){return r>
11150?vD(1,o,yD(r,0,EZ)):r<0?vD(t,1,yD(r,_Z,0)):1}}class _T extends hN{async process(){return{...this.entry,mediaId:ct(),blob:await _T._modulate(this.entry.blob,this.entry.requestProp)}}static async _modulate(t,o){return o.effect===void 0?t:await Ofe(t,o.effect)}}const oj=5,XEe=4,rj=async(e,t,o)=>{const r=new Array(e.length);let n=0;const a=async()=>{for(;;){const s=n;if(n+=1,s>=e.length)return;r[s]=await o(e[s],s)}},i=Math.max(1,Math.min(t,e.length));return await Promise.all(Array.from({length:i},()=>a())),r},ET=(e,t,o={})=>rj(JEe(e,o.batchSize??oj),o.concurrency??XEe,r=>t(r)),JEe=(e,t=oj)=>{const o=[];for(let r=0;r<e;r+=t){const n=Math.min(r+t,e),a=[];for(let i=r;i<n;i+=1)a.push(i);o.push(a)}return o},qEe=e=>({requestType:e.requestType,clientInfo:e.clientInfo,planReqId:e.planReqId,chunkIdxs:e.chunkIdxs,debugChunkFailRate:e.debugChunkFailRate}),nj=h("ttsChunkClient.ts"),aj=e=>{XV(e)&&$e().refetchStockTTSSpeakerList().catch(t=>{nj.error("Failed to refresh stale TTS pricing: "+P(t))})},IN=1e3,qM=900*1e3,QM=5,mT=e=>new Yr("cancelled",e+" cancelled"),ij=e=>ta(()=>mT(e)),sj=(e,t,o)=>n2(e).pipe(a2({count:QM-1,delay:(r,n)=>o?.aborted||!BEe(r)?ta(()=>r):(nj.warn(t+" poll attempt "+n+"/"+(QM-1)+" failed, retrying: "+P(r)),md(IN))})),QEe=(e,t)=>new Yr("network",e+" transport failed: "+P(t),void 0,!0),ZEe=(e,t)=>{throw no(t)?mT(e):t instanceof TypeError?QEe(e,t):t},$Ee=(e,t)=>{throw no(t)?mT(e):t instanceof TypeError||t instanceof SyntaxError?new Yr("network",e+" body parse failed: "+P(t)):t},hT=async(e,t,o)=>{if(o?.aborted)throw mT(e);const r=await Pn(e,{method:"POST",body:JSON.stringify(t),signal:o}).catch(n=>ZEe(e,n));if(!r.ok){const n=r.status===401||r.status===403;throw new Yr(n?"authorization":"network","HTTP "+r.status+" from "+e,r.status)}return await r.json().catch(n=>$Ee(e,n))},xj=async(e,t)=>{const o=await hT("/request-tts-chunk",e,t);if(o.result==="enqueued"&&o.appliedPricing===void 0)throw new Yr("unknown","TTS pricing is missing from an enqueued response");if(aj(o.appliedPricing),o.result==="error")throw new Yr(o.errorType,o.msg??"unknown");return o.reqId},eme=async(e,t)=>{const o={reqId:e,timezoneMin:-new Date().getTimezoneOffset()};return hT("/get-tts-chunk",o,t)},cj=(e,t)=>{const o=Date.now(),r="getTTSChunk (reqId="+e+")",n=()=>zt(eme(e,t)),a=sj(n,r,t);return a.pipe($U(i=>{if(i.result==="success"||i.result==="error")return Tt();if(t?.aborted)return ij(r);if(Date.now()-o>qM){const s=i.result==="pending"?i.progress.stage:"unknown";return ta(()=>new Yr("timeout","getTTSChunk polling timed out after "+qM+"ms (reqId="+e+", lastStage="+s+")"))}return md(IN).pipe(St(()=>a))}))},ZM=360*1e3,lj=async(e,t)=>{const o=await hT("/plan-script",e,t);if(o.result==="enqueued"&&o.appliedPricing===void 0)throw new Yr("unknown","TTS pricing is missing from an enqueued plan response");if(aj(o.appliedPricing),o.result==="error")throw o.errorType==="pricing_changed"&&Yl().refresh({force:!0}),new Yr(o.errorType,o.msg??"unknown");return{planReqId:o.planReqId,appliedPricing:o.appliedPricing}},tme=async(e,t)=>hT("/get-script-plan",{planReqId:e},t),dj=(e,t)=>{const o=Date.now(),r="getScriptPlan (planReqId="+e+")",n=()=>zt(tme(e,t)),a=sj(n,r,t);return a.pipe($U(i=>i.result==="success"||i.result==="error"?Tt():t?.aborted?ij(r):Date.now()-o>ZM?ta(()=>new Yr("timeout","getScriptPlan polling timed out after "+ZM+"ms")):md(IN).pipe(St(()=>a))))},TN=async()=>{const[e,t]=await Promise.all([zo(),Ia()]);return{cid:e,deviceId:t.deviceId,deviceName:t.deviceName,machineId:t.machineId,clientType:Oo()?rd.DESKTOP_APP:rd.TRY}},ome=e=>{const t=BV(e.requestProp.speaker);return t===e.requestProp.speaker?e:{...e,requestProp:{...e.requestProp,speaker:t}}},uj=async e=>{const t=await new _T(e).process(),o=await new Ka(t).process(),r=o.timestamps!==void 0&&!Vu(o.requestProp)?{...o,timestamps:Ka.adjustTimestamps(o.timestamps,o.requestProp.speed)}:o;return ome(r)},pj=async(e,t)=>{const{audioInfo:o}=e.result,r=o.videoAudioMetaInfo.audioInfo;if(!r)throw new C(_.C_MEDIA_NO_AUDIO_TRACK,{},t+": "+o.mediaId);return await i_({mediaId:o.mediaId,audioBlob:e.result.ttsBlob,sampleRate:r.sampleRate,codec:r.codec??Gt.MP3,duration:o.videoAudioMetaInfo.duration,sourceOrigin:o.sourceOrigin,name:o.name,sourceType:o.sourceType}),o},rme=6e4,fj=async(e,t)=>{if(e.kind==="inline"){const a=Uint8Array.from(atob(e.mp3Base64),i=>i.charCodeAt(0));return new Blob([a],{type:"audio/mpeg"})}const o=AbortSignal.timeout(rme),r=t?AbortSignal.any([t,o]):o,n=await fetch(e.url,{signal:r});if(!n.ok)throw new Error("Failed to fetch clip presigned URL: "+n.status);return n.blob()},gj=e=>e.replace(/\u00A0/g," ").normalize("NFC").replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g,""),nme=`
1116`,ame=`
1117
1118`,ime=e=>{let t=0;const o=[],r=new Map,n=[];for(let i=0;i<e.length;i+=1){const s=gj(e[i].text);if(o.push(s),r.set(e[i].clipId,[t,t+s.length]),i<e.length-1){const x=e[i+1].continuesFromPrev?nme:ame;n.push(x),t+=s.length+x.length}else t+=s.length}return{script:o.reduce((i,s,x)=>x===0?s:i+n[x-1]+s,""),offsetsByClipId:r}},sme=200,xme=async e=>{if(e.length===1)return e[0];const t=await Promise.all(e.map(async s=>Rd(await s.arrayBuffer()))),o=t[0].sampleRate,r=Math.max(...t.map(s=>s.numberOfChannels)),n=t.reduce((s,x)=>s+x.length,0),a=new Float32Array(n*r);let i=0;for(const s of t){if(s.sampleRate!==o)throw new Error("Preview audio sample rates differ");for(let x=0;x<r;x++){const c=s.getChannelData(Math.min(x,s.numberOfChannels-1));for(let l=0;l<s.length;l++)a[(i+l)*r+x]=c[l]}i+=s.length}return new Blob([Jg(a.buffer,{isFloat:!0,numChannels:r,sampleRate:o,numFrames:n}
1118)],{type:"audio/wav"})},cme=async(e,t)=>{t?.throwIfAborted();const o=gj(e.text.slice(0,sme));if(!o.trim())throw new Yr("invalid_input","Empty preview script");const{voiceSetting:r,replaceRulesMap:n}=e,a=ww(r),{planReqId:i}=await lj({requestType:pu.PREVIEW,idempotencyKey:sl(),script:o,speakerInfo:a,linebreakMode:"audio",replaceRulesMap:n},t),s=await Bt(dj(i,t).pipe(um()));if(s.result!=="success")throw new Yr(s.result==="error"?s.errorType:"unknown","Preview planning failed");if(s.chunks.length===0)throw new Yr("invalid_input","No voiceable preview text");const x=await TN(),c=await ET(s.chunks.length,async p=>{const f=await xj({requestType:pu.PREVIEW,planReqId:i,chunkIdxs:p,clientInfo:x},t),E=await Bt(cj(f,t).pipe(um()));if(E.result!=="success")throw new Yr(E.result==="error"?E.errorType:"unknown","Preview synthesis failed");const T=E.failedChunks[0];if(E.requestType!==pu.PREVIEW)throw new Yr("unknown","Expected a PREVIEW response");if(T)throw new Yr(T.errorType??"unknown",T.errorMsg);const O=[...E.chunkAudios].sort((S,R)=>S.chunkIdx-R.chunkIdx);if(O.length!==p.length||O.some((S,R)=>S.chunkIdx!==p[R]))throw new Yr("unknown","Incomplete preview audio");return O}),l=await Promise.all(c.flat().map(async p=>{const f=await fj(p.audio,t);return t?.throwIfAborted(),uj({mediaId:ct(),blob:f,requestProp:{...r,text:{raw:p.scriptText,processed:p.scriptText,textAspectLang:p.textAspectLang}}})}));t?.throwIfAborted();const d=await xme(l.map(p=>p.blob));return t?.throwIfAborted(),{entry:{mediaId:ct(),blob:d,requestProp:{...l[0].requestProp,text:{raw:o,processed:o,textAspectLang:l[0].requestProp.text.textAspectLang}}},processedLength:s.chunks.reduce((p,f)=>p+f.processedLength,0)}},lme=async(e,t)=>{const o=new AbortController,r=t?AbortSignal.any([t,o.signal]):o.signal;try{return await cme(e,r)}finally{o.abort()}},e_=24e3,dme=e=>{if(e.length===0)return;if(e.length===1)return e[0];const t=new AbortController;for(const o of e){if(o.aborted)return t.abort(o.reason),t.signal;o.addEventListener("abort",()=>t.abort(o.reason),{once:!0})}return t.signal},ume=e=>Tt(e).pipe(pme(),_me(),hme(e.length),Fa(),e1(zt(e)),St(([t,o])=>Tt(t).pipe(Ime(o),Ome(o.type)))),pme=()=>e=>e.pipe(St(t=>{const o=dm([zt(zo()),zt(Ia())]).pipe(At(([n,a])=>({cid:n,deviceInfo:a}))),r=dm([o,Tt(t)]).pipe(At(([n,a])=>{const i={[Sc.PREVIEW]:$d.PREVIEW,[Sc.CLIP]:$d.CLIP,[Sc.DUBBING]:$d.DUBBING,[Sc.EFFECT]:$d.EFFECT},s=a[0],x=s.type,c=s.userReqId,l=JR(s.voiceSetting).speaker,d=a.map(S=>({text:S.ttsString.processed,textAspectLang:S.ttsString.textAspectLang,voice:JR(S.voiceSetting)})),{lang:u,name:p,provider:f,speakerId:E}=l,T={requestType:i[x],speakerInfo:{provider:f,lang:u,name:p,speakerId:E},userInfo:{cid:n.cid,uid:s.uid,clientType:Oo()?rd.DESKTOP_APP:rd.TRY,deviceId:n.deviceInfo.deviceId,deviceName:n.deviceInfo.deviceName,machineId:n.deviceInfo.machineId},infos:d.map(S=>({text:S.text,textAspectLang:S.textAspectLang,volume:S.voice.volume,speed:S.voice.speed,pitch:S.voice.pitch,emotion:S.voice.emotion,emotionIntensity:S.voice.emotionIntensity,acting:S.voice.acting,version:S.voice.version??N1}))},O=dme(a.map(S=>S.signal).filter(S=>S!==void 0));return{request:T,userReqId:c,signal:O}}));return Bt(r)})),fme=(e,t,o)=>{if(o?.aborted)return h("tts.ts").info("TTS cancelled — skip make-tts for reqId "+t),ta(()=>new DOMException("make-tts aborted","AbortError"));const r=Yl(),n=e.requestType===$d.PREVIEW?void 0:r.getExpectedPricing({provider:e.speakerInfo.provider,speakerId:e.speakerInfo.speakerId??e.speakerInfo.name,uid:e.userInfo.uid});return n2(async()=>{if(o?.aborted)throw new DOMException("make-tts aborted","AbortError");return await $m("/make-tts",{method:"POST",body:JSON.stringify({...e,...n===void 0?{}:{expectedPricing:n}}),signal:o})}).pipe(St(s=>me(s,_.C_TTS_NETWORK_ERROR)),St(s=>(s.result==="error"&&s.errorType==="pricing_changed"&&r.refresh({force:!0}),s.result==="success"&&e.requestType!==$d.PREVIEW&&n!==void 0&&r.shouldRefreshForAppliedPricing(s.appliedPricing,n,e.userInfo.uid)&&r.refresh({force:!0}),XV(s.appliedPricing)&&$e().refetchStockTTSSpeakerList().catch(x=>{h("tts.ts").error("Failed to refresh stale TTS pricing: "+P(x))}),s.result==="error"?(h("tts.ts").error("makeTTS error on server: "+JSON.stringify(s)),ta(()=>{throw s})):Tt(s.reqId)))).pipe(St(s=>{const x={reqId:s,timezoneMin:-new Date().getTimezoneOffset()};return Tt(x).pipe(St(c=>$m("/get-tts",{method:"POST",body:JSON.stringify(c),signal:o})),St(c=>
1118me(c,_.C_TTS_NETWORK_ERROR)),St(c=>{if(c.result==="pending")return ta(()=>{throw Error(Ef.TIMEOUT)});const l={name:e.speakerInfo.name,provider:e.speakerInfo.provider};return Tt({response:c,userReqId:t,speakerInfo:l})}),a2({count:10,delay:c=>Jx(c)===Ef.TIMEOUT?md(1e3):ta(()=>{throw c}),resetOnSuccess:!0}))}))},gme=(e,t)=>{const o=a=>{if(Object.values(_).includes(a)){const i=a;throw new C(i,{},"mock error")}return{type:"error",errorType:a}},r={name:e.speakerInfo.name,provider:e.speakerInfo.provider};Mo().getDebugVal(Xt.TTS_MOCK_RESPONSE);const n=parseFloat(Mo().getDebugVal(Xt.TTS_RANDOMLY_FAIL)??"");if(!isNaN(n)&&Math.random()<n){const a=Math.random();return a>.9?{response:{result:"error",errorType:"timeout"},userReqId:t,speakerInfo:r}:a>.8?{response:{result:"error",errorType:"authorization"},userReqId:t,speakerInfo:r}:a>.7?{response:{result:"error",errorType:"low_version"},userReqId:t,speakerInfo:r}:{response:{result:"success",ttsDatas:Array(e.infos.length).fill(null).map(()=>{const i=Math.random();return i<.1?o("invalid_input"):i<.2?o(_.C_TTS_GENERAL_ERROR):i<.3?o("different_lang"):i<.4?o(_.C_TTS_NETWORK_ERROR):i<.5?o("db"):i<.6?o("aws"):i<.7?o("speaker_deleted"):i<.8?o("api_network"):o("unknown")})},userReqId:t,speakerInfo:r}}return null},_me=()=>e=>e.pipe(St(({request:t,userReqId:o,signal:r})=>Tt({request:t,userReqId:o,signal:r}).pipe(St(({request:n,userReqId:a,signal:i})=>{const s=gme(n,a);return s?Tt(s):fme(n,a,i)}),c0(n=>{const a={name:t.speakerInfo.name,provider:t.speakerInfo.provider};return r?.aborted||no(n)?(h("tts.ts").info("tts request cancelled by user (reqId "+o+")"),Tt({response:{result:"error",errorType:"unknown"},userReqId:o,speakerInfo:a,cancelled:!0})):(h("tts.ts").error("error during requesting tts: "+P(n)),(n.type==="error"||n.result==="error")&&"errorType"in n?Tt({response:{result:"error",errorType:n.errorType},userReqId:o,speakerInfo:a}):Jx(n)===Ef.TIMEOUT?Tt({response:{result:"error",errorType:"timeout"},userReqId:o,speakerInfo:a}):Ne(n)?(eS(n.errorCode),Tt({response:{result:"error",errorType:n.errorCode===_.C_TTS_NETWORK_ERROR?"network":"unknown"},userReqId:o,speakerInfo:a})):Tt({response:{result:"error",errorType:"unknown"},userReqId:o,speakerInfo:a}))}))));let $_;const SN=(e,t,o,r)=>{if(h("tts.ts").warn("tts request failed: "+JSON.stringify(e)),e.errorType==="device_too_many_free_account"){const a=_.C_DEVICE_TOO_MANY_FREE_ACCOUNT,i=Ot(a,{defaultKey:"error.tts_general_error"});Y().error(a,i)}let n;if(e.errorType==="api_network"){const a=o.provider===Oe.UserTTS?_.C_USER_TTS_API_SERVER_ERROR:_.C_TTS_API_SERVER_ERROR,i=sx(o.name,o.provider),s=eT(o.provider);if(n={aivoice_name:i,aivoice_provider:s,error_code:a},$_||($_=new Set),!$_.has(t)){$_.add(t);const x=Ot(a,{defaultKey:"error.tts_general_error",errorArg:{aivoice_name:i,aivoice_provider:s}});Y().error(a,x)}}return Array(r).fill(null).map(()=>({type:"failed",errorInfo:ju(e.errorType,n)}))},Eme=(e,t,o)=>e.ttsDatas.map(r=>r.type==="error"?SN({result:"error",errorType:r.errorType,inputText:r.inputText,msg:r.msg},t,o,1)[0]:{type:"success",audioData:r.audioData,timestamps:r.timestamps}),mme=e=>Array(e).fill(null).map(()=>({type:"failed",errorInfo:{reason:nr.CANCELLED,msg:"tts.unknown_error"}})),hme=e=>t=>t.pipe(At(({response:o,userReqId:r,speakerInfo:n,cancelled:a})=>a?mme(e):o.result==="error"?SN(o,r,n,e):Eme(o,r,n))),Ime=e=>t=>{const o=Nw(e.ttsString,e.voiceSetting);return t.pipe(At(r=>r.type==="success"?Tme(o,r,e.options):Sme(o,r)))},Tme=(e,t,o)=>Wf().toTTSCacheEntry(new Blob([Uint8Array.from(t.audioData).buffer],{type:yfe(Gt.MP3)}),ct(),e,t.timestamps?Bi._convertTTSTimestamps(t.timestamps):void 0,void 0,o),Sme=(e,t)=>Wf().toTTSCacheEntry(zm(1),ct(),e,void 0,t.errorInfo),Ome=e=>t=>t.pipe(_j()),_j=e=>t=>t.pipe(er(o=>{o.errorInfo===void 0&&!Wf().doesExist(o.requestProp)&&Wf().setEntry(o)}),St(o=>new _T(o).process()),St(o=>new Ka(o).process())),Cme=()=>e=>e.pipe(St(t=>{const o=BV(t.requestProp.speaker),r={...t,requestProp:{...t.requestProp,speaker:o}};return Tt(r)})),ON=new Set(["api_network","device_too_many_free_account"]),Rme=e=>{const t=new Set,o=[];for(const r of e){const n=r.errorType;n===void 0||!ON.has(n)||t.has(n)||(t.add(n),o.push(n))}return o},ju=(e,t)=>{switch(e){case"authorization":return{msg:"tts.error_auth",reason:nr.AUTH};case"different_lang":return{msg:"tts.diff_lang",reason:nr.DIFFERENT_LANG};
1118case"invalid_input":return{msg:"tts.invalid_input",reason:nr.INVALID_INPUT};case"low_version":return{msg:"tts.error_low_version",reason:nr.LOW_VERSION};case"speaker_deleted":return{msg:"tts.error_speaker_deleted",reason:nr.SPEAKER_DELETED};case"timeout":return{msg:"tts.error_timeout",reason:nr.TIMEOUT};case"network":return{msg:"tts.error_network",reason:nr.NETWORK};case"api_network":return{msg:"tts.error_api_network_clip",msgArg:t,reason:nr.API_NETWORK};case"quota_exceeded":return{msg:"error.request_quota_exceeded_error",reason:nr.UNKNOWN};case"pricing_changed":return{msg:"tts.error_pricing_changed",reason:nr.PRICING_CHANGED};default:return{msg:"tts.unknown_error",reason:nr.UNKNOWN}}},CN=(e,t)=>{switch(e){case"device_too_many_free_account":return _.C_DEVICE_TOO_MANY_FREE_ACCOUNT;case"low_version":return _.C_APP_VERSION_IS_LOW;case"api_network":return t===Oe.UserTTS?_.C_USER_TTS_API_SERVER_ERROR:_.C_TTS_API_SERVER_ERROR;case"quota_exceeded":return _.C_REQUEST_QUOTA_EXCEEDED_ERROR;case"network":return _.C_TTS_NETWORK_ERROR;default:return _.C_TTS_GENERAL_ERROR}},Ame=(e,t)=>
1118{if(e===void 0||!ON.has(e))return;const o=CN(e,t.provider);Y().error(o,Ot(o,{defaultKey:"error.tts_general_error",errorArg:{aivoice_name:sx(t.name,t.provider),aivoice_provider:eT(t.provider)},errorDescKey:"common.no_usage_deduction"}))},RN=e=>{if(e==="network")try{eS(_.C_TTS_NETWORK_ERROR)}catch(t){h("tts.ts").warn("TTS error analytics failed: "+P(t))}},Hf=(e,t)=>{e.some(o=>o.errorType==="network")&&RN("network");for(const o of Rme(e))Ame(o,t)};class yme{NUM_ENTRY_PER_REQUEST=5;REQUEST_CONCURRENCY=4;BUFFER_TIME_MS=1e3;_subj$;_subscription;constructor(){this._subj$=new id,this._subscription=this._startPipeline()}reset(){this._subj$.complete(),this._subscription.unsubscribe(),this._subj$=new id,this._subscription=this._startPipeline()}request(t){this._subj$.next(t)}_groupEntries(){return t=>t.pipe(M9(this.BUFFER_TIME_MS),St(o=>zt(o).pipe(ZU(r=>r.requestPayload.type+"_"+r.requestPayload.voiceSetting.speaker.speakerId))),Ma(o=>o.pipe(D9(this.NUM_ENTRY_PER_REQUEST))),jl(o=>o.length>0))}_startPipeline(){return this._subj$.pipe(this._groupEntries(),Ma(t=>{const o=t.map(({requestPayload:n})=>n);return ume(o).pipe(e1(zt(t)),er(([n,{future:a}])=>a.resolve(n)),At(k9))},this.REQUEST_CONCURRENCY)).subscribe({complete:()=>h("tts.ts").info("TTSRequestQueue completed"),error:t=>h("tts.ts").error("TTSRequestQueue error: "+P(t))})}}class Vl{static _instance;_queue;constructor(){this._queue=new yme}static getInstance(){return!Vl._instance&&(Vl._instance=new Vl),Vl._instance}getTTSEntry=async t=>await this._getEntryFromCache(t)??this._getEntryFromRequest(t);_getEntryFromRequest=async t=>{const o=new Ns;return this._queue.request({future:o,requestPayload:t}),o.promise()};_getEntryFromCache=async t=>{Mo().getDebugVal(Xt.TTS_DISABLE_CACHE);const o=Nw(t.ttsString,t.voiceSetting),r=Wf().getEntry(o);if(r===null)return null;const n=Tt(r).pipe(_j(t.type),Cme());return Bt(n)}}const $M=(e,t)=>{const o=HG.match(e,t,n=>uv(e,...n));return o.sort((n,a)=>a.from.length-n.from.length),o},Aat=async(e,t,o)=>{try{if(t.onRequestStart?.(),!e.text.length)return i0(A("tts.error_text_input_none")),t.onError?.(),null;const{entry:r,processedLength:n}=await lme(e,o);return o?.throwIfAborted(),vme(r,n),t.onSuccess?.(),r}catch(r){if(o?.aborted||no(r))return t.onCancel?.(),null;h("tts.ts").error("error during requesting tts preview: "+P(r)),t.onError?.();const n=Km(r);if(RN(n),n==="invalid_input")i0(A("tts.error_text_invalid"));else if(n){const a=SN({result:"error",errorType:n},sl(),{name:e.voiceSetting.speaker.name,provider:e.voiceSetting.speaker.provider},1)[0];!ON.has(n)&&i0(A(a.errorInfo.msg))}else{const a=Ne(r)?r.errorCode:_.C_TTS_GENERAL_ERROR;await Y().error(a,Ot(a,{defaultKey:"error.tts_general_error"}))}return null}finally{t.onRequestEnd?.()}},yat=async(e,t)=>{const o="/request-tts-sample",r={name:e,type:t},n={method:"POST",body:JSON.stringify(r)},a=await qo(o,n);return me(a,_.C_TTS_NETWORK_ERROR)},vme=(e,t)=>{const{speaker:o,text:r,emotion:n,effect:a,speed:i,pitch:s,volume:x}=e.requestProp,c=u=>{switch(u.requestProp.speaker.provider){case Oe.Clova:return"clova";case Oe.Google:return"google";case Oe.KT:return"kt";case Oe.Vrew:return"vrew";case Oe.UserTTS:return"userTTS";case Oe.Wemakevoice_deprecated:return"wemakevoice";case Oe.Voicevox:return"voicevox";case Oe.Polly:return"polly";case Oe.Elevenlabs:return"elevenlabs";case Oe.Gemini:return"gemini";case Oe.Typecast:return"typecast"}return"unknown"},l=e.options?.preprocess?.replaceRules?.length,d={type:"preview",insertOfModify:"preview",isPreview:1,numRequestedTTS:1,numGeneratedTTS:1,originalTextLength:r.raw.length,generatedTextLength:t,speakerName:bw(o.name,o.provider),speakerId:o.speakerId,speakerLang:o.lang,speakerProvider:c(e),isFreeSpeaker:o.free?1:0,isRecommendedSpeaker:o.badge==="Recommended"?1:0,emotion:n??"",acting:UG(o)?Vs(o,e.requestProp.acting)??"":"",effect:a??"",speed:i,pitch:s,volume:x,duration:0,numInputReplacedTTS:l?1:0};Xz(d)},vat=e=>{const{provider:t,speakerId:o,name:r,lang:n,versions:a}=e;J3(t,o,r,n,a?.at(-1)??"v1")};var qi=(e=>(e.IMAGE="image",e.LOTTIE="lottie",e.WEB="web",e.VIDEO="video",e.SHAPE="shape",e.SIMPLE_CHARACTER="simpleCharacter",e))(qi||{}),Ox=(e=>(e[e.NONE=0]="NONE",e[e.VERTICAL=1]="VERTICAL",e[e.HORIZONTAL=2]="HORIZONTAL",e[e.VERTICAL_HORIZONTAL=3]="VERTICAL_HORIZONTAL",e))(Ox||{});const Ej=async(e,t)=>{const o=e.projectId??"",r={...e,files:await Promise.all(e.files.map(n=>Bme(n,t,o))),props:{...e.props,assets:Wme(e.props.assets),audios:Hme(e.props.audios,e.files),ttsClipInfosMap:jme(e.files),waterMark:e.props.waterMarkMap?Nme(e.props.waterMarkMap):void 0,projectAudioLanguage:wme(e.files),originalClipsMap:Pme(e.files),audioLanguagesMap:Mme(e.files),flipSetting:rhe(e.props.flipSetting)},transcript:{...e.transcript,scenes:e.transcript.scenes.map(n=>({...n,clips:n.clips.map(a=>bme(a))}
1118))}};return Q4(r,t)},wme=e=>{const t=e.find(r=>r.type===ie.VIDEO_AUDIO);if(t)return t.audioLanguage;const o=e.find(r=>r.type===ie.TTS);return o?on(D0(o.ttsInfo.speaker.lang)):_f},Nme=e=>{const t=Object.values(e);if(t.length===0)return;const o=t[0];if(o.waterMarkInfo.vrewMark)return{mediaId:o.mediaId,type:hi.WATERMARK,vrewMark:o.waterMarkInfo.vrewMark,xPos:o.xPos,yPos:o.yPos,height:o.height,width:o.width,rotation:o.rotation}},Pme=e=>e.filter(t=>t.type===ie.VIDEO_AUDIO).reduce((t,o)=>(t[o.mediaId]=o.originalClips.map(r=>Lme(r)),t),{}),bme=e=>{const{playbackRate:t,...o}=e;return{...o,words:e.words.map(r=>mj(r,t))}},mj=(e,t)=>({...e,duration:pe(e.duration),playbackRate:ur(t),truncatedWords:e.truncatedWords.map(o=>mj(o,t))}),Lme=e=>({...e,words:e.words.map(hj)}),hj=e=>({...e,duration:pe(e.duration),playbackRate:ur(1),truncatedWords:e.truncatedWords.map(t=>hj(t))}),Mme=e=>e.filter(t=>t.type===ie.VIDEO_AUDIO).reduce((t,o)=>(t[o.mediaId]=o.audioLanguage,t),{}),Ij=e=>{switch(e.type){case qi.IMAGE:return Dme(e);case qi.VIDEO:return kme(e);case qi.LOTTIE:return Fme(e);case qi.WEB:return Ume(e);case qi.SHAPE:return Vme(e);case qi.SIMPLE_CHARACTER:return Gme(e);default:{const t=e;throw new C(_.C_LOGIC_ERROR,{},"Unknown asset type: "+JSON.stringify(t))}}},Dme=e=>({...e,type:hi.IMAGE}),kme=e=>{const{frontOffset:t,stats:o,...r}=e;return{...r,type:hi.VIDEO,sourceIn:pe(t),fillType:o?.fillType}},Fme=e=>({...e,type:hi.LOTTIE}),Ume=e=>({...e,type:hi.WEB}),Vme=e=>({...e,type:hi.SHAPE}),Gme=e=>({xPos:e.xPos,yPos:e.yPos,height:e.height,width:e.width,rotation:e.rotation,mediaId:e.mediaId,zIndex:e.zIndex,type:hi.SIMPLE_CHARACTER,isPreset:!e.mediaId.startsWith("user_char_"),isMouthApplied:e.isMouthApplied,pose:{isPreset:!0,presetType:"static",labelKey:"character_pose.static",silentMediaId:e.mediaId,speakingMediaId:e.webmMediaId}}),Wme=e=>{const t={};return Object.entries(e).forEach(([o,r])=>{t[o]=Ij(r)}),t},Hme=(e,t)=>{const o={};return Object.entries(e).forEach(([r,n])=>{const a=Yme(n,t);a!==null&&(o[r]=a)}),o},jme=e=>e.reduce((t,o)=>{if(o.type===ie.TTS){const r={duration:o.ttsInfo.duration,speaker:o.ttsInfo.speaker,volume:o.ttsInfo.volume,speed:o.ttsInfo.speed,pitch:o.ttsInfo.pitch,text:o.ttsInfo.text,version:o.ttsInfo.version,effect:o.ttsInfo.effect,emotion:o.ttsInfo.emotion,errorInfo:o.ttsInfo.errorInfo};t[o.mediaId]=r}return t},{}),zme=e=>{switch(e.type){case"ttsEffect":return"ttsEffect";case"ttsDubbing":return"ttsDubbing";default:throw new C(_.C_LOGIC_ERROR,{},"Unknown audio type: "+e.type+" for mediaId: "+e.mediaId)}},Yme=(e,t)=>{if(e.type==="ttsEffect"||e.type==="ttsDubbing"){const n=t.find(x=>x.mediaId===e.mediaId);if(!n||!(n.type===ie.TTS_EFFECT||n.type===ie.TTS_DUBBING))return h("vrewJsonUpgraderV14.ts").warn("Skipping TTS audio migration: file not found for mediaId "+e.mediaId),null;const a={duration:n.ttsInfo.duration,speaker:n.ttsInfo.speaker,volume:n.ttsInfo.volume,speed:n.ttsInfo.speed,pitch:n.ttsInfo.pitch,emotion:n.ttsInfo.emotion,version:n.ttsInfo.version,text:n.ttsInfo.text,effect:n.ttsInfo.effect,errorInfo:n.ttsInfo.errorInfo},i=zme(e);return{mediaId:e.mediaId,volume:e.volume,fade:{in:e.isFadeInApplied,out:e.isFadeOutApplied},sourceIn:e.frontOffset,sourceOut:e.rearOffset,loop:e.loop,playbackRate:Un,type:i,ttsFileInfo:a}}if(e.type!=="soundEffect"&&e.type!=="bgm"&&e.type!=="overdub"){const n="Unknown audio type: "+e.type+" for mediaId: "+e.mediaId;throw h("vrewJsonUpgraderV14.ts").error(n),new C(_.C_LOGIC_ERROR,{},n)}return{mediaId:e.mediaId,volume:e.volume,fade:{in:e.isFadeInApplied,out:e.isFadeOutApplied},sourceIn:pe(e.frontOffset),sourceOut:pe(e.rearOffset),loop:e.loop,playbackRate:Un,type:e.type}},Bme=async(e,t,o)=>{switch(e.type){case ie.VIDEO_AUDIO:return ohe(e,t,o);case ie.ASSET_VIDEO:return the(e,t,o);case ie.SOUND_EFFECT:case ie.BGM:case ie.OVERDUB:return Qme(e,t,o);case ie.TTS:return Zme(e,t,o);case ie.TTS_EFFECT:return $me(e,t,o);case ie.TTS_DUBBING:return ehe(e,t,o);case ie.SHAPE:return Jme(e,t,o);case ie.TEXTBOX:return qme(e,t,o);case ie.IMAGE:return eD(e,t,e.isTransparent,o);case ie.FILTER:case ie.WATERMARK:return eD(e,t,!0,o);default:throw new C(_.C_LOGIC_ERROR,{},"Unsupported file type: "+e.type)}},Kme=async(e,t,o)=>{if(e.mediaId===_o)return _o+".mp4";if([ie.BGM,ie.SOUND_EFFECT,ie.OVERDUB,ie.TTS_EFFECT,ie.TTS_DUBBING].includes(e.type)&&"audioMetaInfo"in e&&e.audioMetaInfo?.name)return e.audioMetaInfo.name;if(e.type===ie.VIDEO_AUDIO&&o&&e.fileLocation===D.REMOTE){const a=await rN(e.path,o);if(a)return a}if(e.fileLocation===D.REMOTE)return gt(e.path);switch(e.type){case ie.BGM:case ie.SOUND_EFFECT:case ie.OVERDUB:return e.mediaId+".mp3";case ie.TTS_EFFECT:case ie.TTS_DUBBING:case ie.TTS:return e.ttsInfo.text.processed.slice(0,20)+".mp3";case ie.IMAGE:{const a=t[e.mediaId]?X0.getExtension(t[e.mediaId].type)||await Bs(t[e.mediaId]):"png";return e.mediaId+"."+a}case ie.SHAPE:return e.mediaId+".xml";case ie.TEXTBOX:return e.mediaId+".html";case ie.WATERMARK:return e.mediaId+".png";case ie.VIDEO_AUDIO:case ie.ASSET_VIDEO:return e.path?gt(e.path):e.mediaId+"."+ZE;default:return e.path&&e.path!==""?gt(e.path):e.mediaId+"."+ZE}},Xme=e=>{if(e.type!==ie.VIDEO_AUDIO)return;const t=!!e.proxyUrl,o=e.videoMetaInfo.audioInfo?.audioCloudPaths,r=!!o?.length;if(t&&r)return{videoProxyUrl:e.proxyUrl,audioProxyUrls:o};if(t)return{videoProxyUrl:e.proxyUrl};if(r)return{audioProxyUrls:o}},ic=async(e,t,o)=>
1118{if(e.type===ie.INVALID)throw new C(_.C_LOGIC_ERROR,{},"Unsupported file type: "+e.type);const r=await Kme(e,t,o);switch(e.fileLocation){case D.LOCAL:return{version:1,mediaId:e.mediaId,sourceOrigin:e.sourceOrigin,fileSize:e.fileSize,name:r,fileLocation:D.LOCAL,path:e.path,relativePath:e.relativePath};case D.REMOTE:return{version:1,mediaId:e.mediaId,sourceOrigin:e.sourceOrigin,fileSize:e.fileSize,name:r,fileLocation:D.REMOTE,url:e.path,proxyInfo:Xme(e)};case D.LOCAL_TMP:return{version:1,mediaId:e.mediaId,sourceOrigin:e.sourceOrigin,fileSize:e.fileSize,name:r,fileLocation:D.LOCAL_TMP,path:e.path};case D.PACKAGED:return{version:1,mediaId:e.mediaId,sourceOrigin:e.sourceOrigin,fileSize:e.fileSize,name:r,fileLocation:D.PACKAGED,path:e.path};case D.IN_MEMORY:return{version:1,mediaId:e.mediaId,sourceOrigin:e.sourceOrigin,fileSize:e.fileSize,name:r,fileLocation:D.IN_MEMORY};default:throw new C(_.C_LOGIC_ERROR,{},"Unsupported file location: "+e.fileLocation)}},eD=async(e,t,o,r)=>{const n=await ic(e,t,r);switch(n.fileLocation){case D.IN_MEMORY:return{version:1,mediaId:n.mediaId,sourceOrigin:n.sourceOrigin,fileSize:n.fileSize,name:n.name,fileLocation:D.IN_MEMORY,type:"Image",isTransparent:o??!1};case D.LOCAL:return{version:1,mediaId:n.mediaId,sourceOrigin:n.sourceOrigin,fileSize:n.fileSize,name:n.name,fileLocation:D.LOCAL,path:n.path,relativePath:n.relativePath,type:"Image",isTransparent:o??!1};case D.LOCAL_TMP:return{version:1,mediaId:n.mediaId,sourceOrigin:n.sourceOrigin,fileSize:n.fileSize,name:n.name,fileLocation:D.LOCAL_TMP,path:n.path,type:"Image",isTransparent:o??!1};case D.PACKAGED:return{version:1,mediaId:n.mediaId,sourceOrigin:n.sourceOrigin,fileSize:n.fileSize,name:n.name,fileLocation:D.PACKAG
1118ED,path:n.path,type:"Image",isTransparent:o??!1};case D.REMOTE:return{version:1,mediaId:n.mediaId,sourceOrigin:n.sourceOrigin,fileSize:n.fileSize,name:n.name,fileLocation:D.REMOTE,url:n.url,proxyInfo:n.proxyInfo,type:"Image",isTransparent:o??!1}}},Jme=async(e,t,o)=>{const r=await ic(e,t,o);switch(r.fileLocation){case D.IN_MEMORY:return{version:1,mediaId:r.mediaId,sourceOrigin:r.sourceOrigin,fileSize:r.fileSize,name:r.name,fileLocation:D.IN_MEMORY,type:"Svg"};case D.LOCAL:return{version:1,mediaId:r.mediaId,sourceOrigin:r.sourceOrigin,fileSize:r.fileSize,name:r.name,fileLocation:D.LOCAL,path:r.path,relativePath:r.relativePath,type:"Svg"};case D.LOCAL_TMP:return{version:1,mediaId:r.mediaId,sourceOrigin:r.sourceOrigin,fileSize:r.fileSize,name:r.name,fileLocation:D.LOCAL_TMP,path:r.path,type:"Svg"};case D.PACKAGED:return{version:1,mediaId:r.mediaId,sourceOrigin:r.sourceOrigin,fileSize:r.fileSize,name:r.name,fileLocation:D.PACKAGED,path:r.path,type:"Svg"};case D.REMOTE:return{version:1,mediaId:r.mediaId,sourceOrigin:r.sourceOrigin,fileSize:r.fileSize,name:r.name,fileLocation:D.REMOTE,url:r.url,proxyInfo:r.proxyInfo,type:"Svg"}}},qme=async(e,t,o)=>{const r=await ic(e,t,o);switch(r.fileLocation){case D.IN_MEMORY:return{version:1,mediaId:r.mediaId,sourceOrigin:r.sourceOrigin,fileSize:r.fileSize,name:r.name,fileLocation:D.IN_MEMORY,type:"Html"};case D.LOCAL:return{version:1,mediaId:r.mediaId,sourceOrigin:r.sourceOrigin,fileSize:r.fileSize,name:r.name,fileLocation:D.LOCAL,path:r.path,relativePath:r.relativePath,type:"Html"};case D.LOCAL_TMP:return{version:1,mediaId:r.mediaId,sourceOrigin:r.sourceOrigin,fileSize:r.fileSize,name:r.name,fileLocation:D.LOCAL_TMP,path:r.path,type:"Html"};case D.PACKAGED:return{version:1,mediaId:r.mediaId,sourceOrigin:r.sourceOrigin,fileSize:r.fileSize,name:r.name,fileLocation:D.PACKAG
1118ED,path:r.path,type:"Html"};case D.REMOTE:return{version:1,mediaId:r.mediaId,sourceOrigin:r.sourceOrigin,fileSize:r.fileSize,name:r.name,fileLocation:D.REMOTE,url:r.url,proxyInfo:r.proxyInfo,type:"Html"}}},Qme=async(e,t,o)=>{const r=e.audioMetaInfo,n={audioInfo:{codec:r.codec??Gt.MP3,sampleRate:r.sampleRate},duration:r.duration},a=await ic(e,t,o);switch(a.fileLocation){case D.IN_MEMORY:return{version:1,mediaId:a.mediaId,sourceOrigin:a.sourceOrigin,fileSize:a.fileSize,name:a.name,fileLocation:D.IN_MEMORY,type:"AVMedia",videoAudioMetaInfo:n,sourceFileType:e.type};case D.LOCAL:return{version:1,mediaId:a.mediaId,sourceOrigin:a.sourceOrigin,fileSize:a.fileSize,name:a.name,fileLocation:D.LOCAL,path:a.path,relativePath:a.relativePath,type:"AVMedia",videoAudioMetaInfo:n,sourceFileType:e.type};case D.LOCAL_TMP:return{version:1,mediaId:a.mediaId,sourceOrigin:a.sourceOrigin,fileSize:a.fileSize,name:a.name,fileLocation:D.LOCAL_TMP,path:a.path,type:"AVMedia",videoAudioMetaInfo:n,sourceFileType:e.type};case D.PACKAGED:return{version:1,mediaId:a.mediaId,sourceOrigin:a.sourceOrigin,fileSize:a.fileSize,name:a.name,fileLocation:D.PACKAG
1118ED,path:a.path,type:"AVMedia",videoAudioMetaInfo:n,sourceFileType:e.type};case D.REMOTE:return{version:1,mediaId:a.mediaId,sourceOrigin:a.sourceOrigin,fileSize:a.fileSize,name:a.name,fileLocation:D.REMOTE,url:a.url,proxyInfo:a.proxyInfo,type:"AVMedia",videoAudioMetaInfo:n,sourceFileType:e.type}}},t_=(e,t,o)=>{switch(e.fileLocation){case D.IN_MEMORY:return{version:1,mediaId:e.mediaId,sourceOrigin:e.sourceOrigin,fileSize:e.fileSize,name:e.name,fileLocation:D.IN_MEMORY,type:"AVMedia",videoAudioMetaInfo:t,sourceFileType:o};case D.LOCAL:return{version:1,mediaId:e.mediaId,sourceOrigin:e.sourceOrigin,fileSize:e.fileSize,name:e.name,fileLocation:D.LOCAL,path:e.path,relativePath:e.relativePath,type:"AVMedia",videoAudioMetaInfo:t,sourceFileType:o};case D.LOCAL_TMP:return{version:1,mediaId:e.mediaId,sourceOrigin:e.sourceOrigin,fileSize:e.fileSize,name:e.name,fileLocation:D.LOCAL_TMP,path:e.path,type:"AVMedia",videoAudioMetaInfo:t,sourceFileType:o};case D.PACKAGED:return{version:1,mediaId:e.mediaId,sourceOrigin:e.sourceOrigin,fileSize:e.fileSize,name:e.name,fileLocation:D.PACKAG
1118ED,path:e.path,type:"AVMedia",videoAudioMetaInfo:t,sourceFileType:o};case D.REMOTE:return{version:1,mediaId:e.mediaId,sourceOrigin:e.sourceOrigin,fileSize:e.fileSize,name:e.name,fileLocation:D.REMOTE,url:e.url,proxyInfo:e.proxyInfo,type:"AVMedia",videoAudioMetaInfo:t,sourceFileType:o}}},Zme=async(e,t,o)=>{const r={audioInfo:{codec:Gt.MP3,sampleRate:e_},duration:e.ttsInfo.duration},n=await ic(e,t,o);return t_(n,r,e.type)},$me=async(e,t,o)=>{const r={audioInfo:{codec:e.audioMetaInfo?.codec??Gt.MP3,sampleRate:e.audioMetaInfo?.sampleRate??e_},duration:e.ttsInfo.duration},n=await ic(e,t,o);return t_(n,r,e.type)},ehe=async(e,t,o)=>{const r={audioInfo:{codec:e.audioMetaInfo.codec??Gt.MP3,sampleRate:e.audioMetaInfo.sampleRate},duration:e.ttsInfo.duration},n=await ic(e,t,o);return t_(n,r,e.type)},the=async(e,t,o)=>{const r={audioInfo:e.videoMetaInfo.audioInfo?{codec:e.videoMetaInfo.audioInfo.codec,sampleRate:e.videoMetaInfo.audioInfo.sampleRate}:void 0,videoInfo:{size:e.videoMetaInfo.videoInfo.size,frameRate:e.videoMetaInfo.videoInfo.frameRate,codec:e.videoMetaInfo.videoInfo.codec},duration:e.videoMetaInfo.duration},n=await ic(e,t,o);return t_(n,r,e.type)},ohe=async(e,t,o)=>{if(!e.videoMetaInfo.audioInfo&&!e.videoMetaInfo.videoInfo)throw new C(_.C_LOGIC_ERROR,{},"Invalid video meta info: neither audio nor video info found. file: "+JSON.stringify(e));let r;if(e.videoMetaInfo.audioInfo&&e.videoMetaInfo.videoInfo)r={audioInfo:{codec:e.videoMetaInfo.audioInfo.codec,sampleRate:e.videoMetaInfo.audioInfo.sampleRate},videoInfo:{size:e.videoMetaInfo.videoInfo.size,frameRate:e.videoMetaInfo.videoInfo.frameRate,codec:e.videoMetaInfo.videoInfo.codec},duration:e.videoMetaInfo.duration};else if(e.videoMetaInfo.audioInfo)r={audioInfo:{codec:e.videoMetaInfo.audioInfo.codec,sampleRate:e.videoMetaInfo.audioInfo.sampleRate},videoInfo:void 0,duration:e.videoMetaInfo.duration};else if(e.videoMetaInfo.videoInfo)r={audioInfo:void 0,videoInfo:{size:e.videoMetaInfo.videoInfo.size,frameRate:e.videoMetaInfo.videoInfo.frameRate,codec:e.videoMetaInfo.videoInfo.codec},duration:e.videoMetaInfo.duration};else throw new C(_.C_LOGIC_ERROR,{},"Invalid video meta info: neither audio nor video info found. file: "+JSON.stringify(e));const n=await ic(e,t,o);return t_(n,r,e.type)},rhe=e=>{if(e===void 0)return{};const t=o=>{switch(o){case Ox.NONE:return Sx.NONE;case Ox.VERTICAL:return Sx.VERTICAL;case Ox.HORIZONTAL:return Sx.HORIZONTAL;case Ox.VERTICAL_HORIZONTAL:return Sx.VERTICAL_HORIZONTAL}};return Object.fromEntries(Object.entries(e).map(([o,r])=>[o,t(r)]))},Tj=e=>tj({...e,fullRangeAssets:e.fullRangeAssets.map((t,o)=>{try{return{...t,assetModel:Ij(t.assetModel)}}catch(r){throw h("upgradeFramePackJsonV5.ts").error("[upgradeFramePackJsonV5] Failed to convert asset in framepack. framepackId: "+e.id+", assetIndex: "+o+", assetMediaId: "+t.assetModel?.mediaId+", asset: "+JSON.stringify(t.assetModel)),r}})});var Br=(e=>(e.IMAGE="image",e.LOTTIE="lottie",e.WEB="web",e.VIDEO="video",e.SHAPE="shape",e.CHARACTER="character",e.SIMPLE_CHARACTER="simpleCharacter",e))(Br||{}),sA=(e=>(e.FILTER="filter",e))(sA||{}),Cx=(e=>(e[e.NONE=0]="NONE",e[e.VERTICAL=1]="VERTICAL",e[e.HORIZONTAL=2]="HORIZONTAL",e[e.VERTICAL_HORIZONTAL=3]="VERTICAL_HORIZONTAL",e))(Cx||{});const Sj=async(e,t)=>{const{migratedAssets:o,removedAssetIdSet:r}=ahe(e.props.assets),n={...e,files:she(e.files),props:{...e.props,assets:o},transcript:{...e.transcript,scenes:nhe(e.transcript.scenes,r)}},a={...n,version:14,files:n.files.map(che),props:{...n.props,assets:lhe(n.props.assets),overdubInfos:{},flipSetting:dhe(n.props.flipSetting)}};return Ej(a,t)},nhe=(e,t)=>vt(e,o=>{o.forEach(r=>{r.clips.forEach(n=>{n.assetIds=tD(n.assetIds,t),n.words.forEach(a=>{a.assetIds=tD(a.assetIds,t)})})})}),tD=(e,t)=>e.filter(o=>!t.has(o)),ahe=e=>{const t={},o=new Set;return Object.entries(e).forEach(([r,n])=>{n.type===Br.CHARACTER?o.add(r):t[r]=ihe(n)}),{migratedAssets:t,removedAssetIdSet:o}},ihe=e=>{switch(e.type){case Br.IMAGE:return e;case Br.LOTTIE:return e;case Br.VIDEO:return e;case Br.CHARACTER:throw new C(_.C_LOGIC_ERROR,{},"Character asset is deprecated");case Br.SIMPLE_CHARACTER:return e;case Br.SHAPE:return xhe(e);case Br.WEB:return e}},she=e=>e.filter(t=>t.type!==ie.CHARACTER),xhe=e=>{switch(e.dimensionType){case Tr.ONE:{const t=$t(e.stroke.width,.001,.06);return vt(e,o=>{o.stroke.width=t})}case Tr.TWO:{const t=$t(e.stroke.width,0,.06),o=e.cornerRounding===void 0?void 0:$t(e.cornerRounding,0,1);return vt(e,r=>{r.stroke.width=t,r.cornerRounding=o})}}},che=e=>{switch(e.type){case ie.SOUND_EFFECT:case ie.BGM:return{...e,version:3};case ie.CHARACTER:throw new C(_.C_LOGIC_ERROR,{},"Character asset is deprecated");default:return e}},lhe=e=>Object.fromEntries(Object.entries(e).map(([t,o])=>[t,Oj(o)])),Oj=e=>{switch(e.type){case Br.IMAGE:return{...e,type:qi.IMAGE};case Br.LOTTIE:return{...e,type:qi.LOTTIE};case Br.VIDEO:return{...e,type:qi.VIDEO};case Br.SIMPLE_CHARACTER:return{...e,type:qi.SIMPLE_CHARACTER};case Br.SHAPE:return{...e,type:qi.SHAPE};case Br.WEB:return{...e,type:qi.WEB};case Br.CHARACTER:throw new C(_.C_LOGIC_ERROR,{},"Character asset is deprecated")}},dhe=e=>{if(e===void 0)return{};const t=o=>{switch(o){case Cx.NONE:return Ox.NONE;case Cx.VERTICAL:return Ox.VERTICAL;case Cx.HORIZONTAL:return Ox.HORIZONTAL;case Cx.VERTICAL_HORIZONTAL:return Ox.VERTICAL_HORIZONTAL}};return Object.fromEntries(Object.entries(e).map(([o,r])=>[o,t(r)]))},Cj=e=>Tj({...e,fullRangeAssets:e.fullRangeAssets.map(t=>({...t,assetModel:Oj(t.assetModel)}))}),uhe=()=>{const e=$e().getCharacterInfo();return e===null?[]:[...e.stockCharacters,...e.userCharacters]},wat=()=>{const e=$e().getCharacterInfo();if(e===null)return;const t={};for(const o of e.stockCharacters)t[o.name]={static:o.static.thumbnailUrl,dynamic:o.static.movingUrl||void 0};for(const o of e.userCharacters)t[o.characterId]={static:o.static.thumbnailUrl,dynamic:o.static.movingUrl||void 0};return t},Nat=()=>{const e=$e().getCharacterInfo();return e===null?[]:e.characterOrder},Pat=()=>{const e=$e().getCharacterInfo();return e===null?[]:e.userCharacters.map(t=>t.characterId)},bat=()=>{const e=$e().getCharacterInfo(),t=e?.userCharacters??[];t.length>0&&h("character.ts").info("userCharacters: "+JSON.stringify(t,void 0,2))},Lat=async e=>{const t={characterId:e};try{const o=await Ui("/delete-generated-character",{method:"POST",body:JSON.stringify(t)}
1118),r=await me(o,_.C_CHARACTER_NETWORK_ERROR);if(r.result==="success")return;const n="Error during deleting user character "+e+": "+r;throw new C(_.C_CHARACTER_STUDIO_DELETE_ERROR,{},n)}catch(o){const r=ye(o)??_.C_CHARACTER_STUDIO_DELETE_ERROR,n=Ot(r,{defaultKey:"character_studio.delete_character_error",errorArg:Ho(o)});h("character.ts").error(P(o)),Y().error(r,n)}},Mat=e=>uhe().find(o=>"name"in o&&o.name===e||"characterId"in o&&o.characterId===e),AN=e=>e+"-webm",Dat=async(e,t,o)=>{if(Vi(t))return;const r="characterId"in e?tt.USER:tt.VREW_RESOURCE,n=await rh(e.static.thumbnailUrl);if(!n)throw new C(_.C_CHARACTER_NETWORK_ERROR,{},"Error during download character thumbnail");const a="characterId"in e?e.characterId:e.name;await vi(n,!0,r,a);const i=e.static.closedUrl;if(i){const x=await rh(i);if(!x)throw new C(_.C_CHARACTER_NETWORK_ERROR,{},"Error during download character assets");const c=await Bs(x);if(Lh.includes(c))await yi({type:"blob",blob:x,name:t+"."+c},t,r);else if(sg.includes(c))await vi(x,!0,r,t);else throw new C(_.C_CHARACTER_NETWORK_ERROR,{},"Unsupported file type for character assets")}else await vi(n,!0,r,t);const s=e.static.movingUrl;s&&o&&await yi({type:"url",value:s},o,r)},kat=async(e,t,o,r)=>{const n=r?tt.USER:tt.VREW_RESOURCE;if(oa(t)===void 0&&eo(t)===void 0){const{closedUrl:a}=e,i=await rh(a);if(!i)throw new C(_.C_CHARACTER_NETWORK_ERROR,{},"Error during download pose base asset");const s=await Bs(i);if(Lh.includes(s))await yi({type:"blob",blob:i,name:t+"."+s},t,n);else if(sg.includes(s))await vi(i,!0,n,t);else throw new C(_.C_CHARACTER_NETWORK_ERROR,{},"Error during download pose base asset")}o&&e.movingUrl&&eo(o)===void 0&&await yi({type:"url",value:e.movingUrl},o,n)};let VO=null;const Fat=async()=>(VO===null&&(VO=await phe()),VO),phe=async()=>{try{const e=await Ui("/character-poses",{method:"GET"}),t=await me(e,_.C_CHARACTER_NETWORK_ERROR);return t.result==="success"?t.poses:(h("character.ts").error("Failed to get system poses: "+t.errorMsg),[])}catch(e){return h("character.ts").error("Error getting system poses: "+P(e)),[]}},Uat=async(e,t,o)=>{await yr(_.A_AUTH_GERNAL_ERROR,"No credential at addCharacterPose",h("character.ts"));const r=be().getUserInfo()?.uid;if(!r)throw new C(_.A_AUTH_GERNAL_ERROR,{},"uid is required");const n=await zo(),{deviceId:a,deviceName:i,machineId:s}=await Ia(),x=Xo(),c=-new Date().getTimezoneOffset(),l={characterId:e,poseId:t,cid:n,deviceId:a,machineId:s,uid:r,clientType:x,isRegeneration:o,deviceName:i,timezoneMin:c};try{const d=await bn("/add-character-pose",{method:"POST",body:JSON.stringify(l)});return await me(d,_.C_CHARACTER_NETWORK_ERROR)}catch(d){return h("character.ts").error("Error adding character pose: "+P(d)),{result:"error",errorType:"unknown",errorMsg:P(d)}}},Vat=async e=>{try{await yr(_.A_AUTH_GERNAL_ERROR,"No credential at getCharacterPoseStatus",h("character.ts"));const t=await bn("/get-character-pose-progress?requestId="+e,{method:"GET"}).then(o=>me(o,_.C_CHARACTER_NETWORK_ERROR));switch(t.status){case"pending":return{status:"pending",progress:t.progress};case"success":return{status:"success"};case"error":throw new C(_.C_CHARACTER_NETWORK_ERROR,{},t.errorMsg);default:throw new C(_.C_CHARACTER_NETWORK_ERROR,{},"Unexpected polling result: "+JSON.stringify(t))}}catch(t){return h("character.ts").error("Error getting pose status: "+P(t)),{status:"error",errorType:"unknown",errorMsg:P(t)}}},Gat=async(e,t)=>{await yr(_.A_AUTH_GERNAL_ERROR,"No credential at getCharacterPoseGenerationStatus",h("character.ts"));const o={characterId:e,poseId:t};try{const r=await bn("/get-character-pose-status",{method:"POST",body:JSON.stringify(o)}),n=await me(r,_.C_CHARACTER_NETWORK_ERROR);if(n.result!=="success")throw new C(_.C_CHARACTER_NETWORK_ERROR,{},n.errorMsg);return n}catch(r){throw h("character.ts").error("Error getting character pose status: "+P(r)),r}},Wat=async e=>{await yr(_.A_AUTH_GERNAL_ERROR,"No credential at cancelCharacterPose",h("character.ts"));const t={requestId:e};try{const o=await bn("/cancel-character-pose",{method:"POST",body:JSON.stringify(t)}
1118),r=await me(o,_.C_CHARACTER_NETWORK_ERROR);if(r.result!=="success")throw new C(_.C_CHARACTER_NETWORK_ERROR,{},r.errorMsg);return r}catch(o){throw h("character.ts").error("Error cancelling character pose: "+P(o)),o}},Hat=e=>{switch(e){case"image":return"image";case"text":return"prompt";case"n/a":return"none";default:return e}},Rj=e=>e.replace(new RegExp(z4+"$"),""),fhe=(e,t)=>wR(""+e+z4,t),ghe=()=>$e().getWebFontFamilies().map(e=>({...e,fontName:Rj(e.fontName)})),jat=(e,t)=>e.map(r=>({...r,font:r.font?IT(r.font,t):void 0})),IT=(e,t)=>{const o=t??ghe(),r=o.map(i=>({...i,fontName:Rj(i.fontName)})),{fontName:n,weight:a}=zc(e);return r.find(i=>i.fontName===n&&i.weight===a)!==void 0?fhe(n,a):e};var _he=(e=>(e.POSE_JSON="POSE_JSON",e.SVG="SVG",e))(_he||{}),Xm=(e=>(e.PNG="PNG",e.WEBM="WEBM",e))(Xm||{}),Qs=(e=>(e.METHOD_SELECT="method_select",e.TEXT_REQUEST="text_request",e.TEXT_DRAFT_LOADING="text_draft_loading",e.TEXT_DRAFT_RESULT="text_draft_result",e.TEXT_LIP_SYNC_LOADING="text_lip_sync_loading",e.TEXT_FINAL_RESULT="text_final_result",e.IMAGE_REQUEST="image_request",e.IMAGE_DRAFT_LOADING="image_draft_loading",e.IMAGE_DRAFT_RESULT="image_draft_result",e.IMAGE_LIP_SYNC_LOADING="image_lip_sync_loading",e.IMAGE_FINAL_RESULT="image_final_result",e))(Qs||{}),pa=(e=>(e.IMAGE="image",e.LOTTIE="lottie",e.WEB="web",e.VIDEO="video",e.SHAPE="shape",e.CHARACTER="character",e.SIMPLE_CHARACTER="simpleCharacter",e))(pa||{}),Rx=(e=>(e[e.NONE=0]="NONE",e[e.VERTICAL=1]="VERTICAL",e[e.HORIZONTAL=2]="HORIZONTAL",e[e.VERTICAL_HORIZONTAL=3]="VERTICAL_HORIZONTAL",e))(Rx||{});const Aj=async(e,t)=>{for(const o of Object.keys(e))await Ue().putMediaCache(o,e[o],t[o])},Jm={captionStyleSetting:{webAssetId:Ao,yAlign:eV,yOffset:0,xOffset:Bh,rotation:0,width:.96,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:Ri},{attributeName:"--textbox-align",type:"textbox-align",value:Ny}],scaleFactor:sU},quillStyle:{size:"100",color:go.DEFAULT_TEXT_COLOR,font:"Pretendard-Vrew_700","outline-color":go.DEFAULT_STYLE_COLOR,"outline-width":"4","outline-on":"true"}},Ehe=e=>({...e,style:e.style?{...e.style,assetEffectInfo:e.style.assetEffectInfo?{type:e.style.assetEffectInfo.type,duration:900}:void 0}:void 0}),mhe=e=>"transitionModel"in e,hhe=e=>({...e,captions:e.captions.map(Ehe),transitionModel:void 0}),Ihe=e=>e.map(t=>mhe(t)?t:hhe(t)),The=e=>{const{version:t}=e;switch(t){case 3:return{...e,type:ie.VIDEO_AUDIO,version:4,originalClips:Ihe(e.originalClips)};case 4:return e}},She=e=>e.type===ie.VIDEO_AUDIO?The(e):e,Ohe=e=>{const t=e.statistics?.saveInfo?.updated?.version;return t&&F9.lt(t,Y4)?{...e,files:e.files.map(n=>n.type!==ie.VIDEO_AUDIO?n:{...n,originalClips:rD(n.originalClips)}),transcript:{...e.transcript,scenes:e.transcript.scenes.map(n=>({...n,clips:rD(n.clips)}))},props:{...e.props,globalCaptionStyle:Lj(e.props.globalCaptionStyle),assets:Hhe(e.props.assets)}}:e},TT=e=>({...e,duration:e.duration??Wx}),Che=e=>({...e,type:Br.IMAGE,assetEffectInfo:e.assetEffectInfo?TT(e.assetEffectInfo):void 0}),Rhe=e=>{const{webAssetId:t,html:o,defaultAttribute:r,assetEffectInfo:n,...a}=e;return{...a,type:Br.WEB,mediaId:t,assetEffectInfo:n?TT(n):void 0}},Ahe=e=>({...e,type:Br.SHAPE,assetEffectInfo:e.assetEffectInfo?TT(e.assetEffectInfo):void 0});let yN;const yhe=async()=>{const e=h("vrewJsonUpgraderV12.ts"),t=await Ui("/search-characters-v3",{method:"post",credentials:"include"}).then(o=>me(o,_.C_CHARACTER_NETWORK_ERROR));if(t.status==="error"){const o="error occured while getting characterInfo, "+JSON.stringify(t);throw e.error(o),new C(_.C_CHARACTER_NETWORK_ERROR,{},o)}return t.result},vhe=e=>{const t=yN?.simpleCharacterInfos.find(r=>r.name===e.appearance),o=t?.speakingUrl?AN(e.appearance):void 0;return{...e,type:Br.SIMPLE_CHARACTER,mediaId:e.appearance,webmMediaId:o}},yj=e=>{switch(e.type){case pa.IMAGE:return Che(e);case pa.LOTTIE:return{...e,type:Br.LOTTIE};case pa.VIDEO:return{...e,type:Br.VIDEO};case pa.CHARACTER:return{...e,type:Br.CHARACTER};case pa.SIMPLE_CHARACTER:return vhe(e);case pa.SHAPE:return Ahe(e);case pa.WEB:return Rhe(e)}},whe=e=>{const t=Object.entries(e).map(([o,r])=>[o,yj(r)]);return Object.fromEntries(t)},Nhe=async e=>{const t=[],o={},r={},n=await $e().getWebAssets(),a=n?.content??[],i={[Ao]:Qc(),...Object.fromEntries(a.map(s=>[s.mediaId,s.html]))};return Object.values(e).filter(s=>
1118s.type===pa.WEB).forEach(s=>{const x=i[s.webAssetId];if(!x){const c="Error occured while fetching textbox for legacy textbox data before v13. webAssetId:"+s.webAssetId;throw new C(_.C_VREW_FILE_INVALID_FORMAT,{},c)}o[s.webAssetId]=new Blob([x]),r[s.webAssetId]="html",t.push({version:1,type:ie.TEXTBOX,mediaId:s.webAssetId,sourceOrigin:tt.VREW_RESOURCE,fileLocation:D.IN_MEMORY,path:"",fileSize:o[s.webAssetId].size})}),await Aj(o,r),{textboxFiles:t,textboxBlobs:o}},Phe=async(e,t)=>{const o={},r={};return await Promise.all(e.map(async n=>{const a=n.characterInfo;if(a.type===Xm.PNG){const i=t[n.mediaId];if(i){const s=a.appearance;o[s]=i,r[s]="png"}}else if(a.type===Xm.WEBM){const i=AN(a.appearance),s={mediaId:i,ext:"webm",pathInfo:{path:n.path,preserveOriginal:!1}};await Ue().putLocalCache(s)}})),await Aj(o,r),o},vj=e=>({...e,mediaId:e.webAssetId,assetEffectInfo:e.assetEffectInfo?TT(e.assetEffectInfo):void 0}),bhe=e=>e.style?{...e,style:vj(e.style)}:{...e,style:void 0},wj=e=>{const{audioTransformIds:t,...o}=e;return{...o,audioIds:t,truncatedWords:o.truncatedWords.map(wj)}},Nj=e=>{const{audioTransformIds:t,...o}=e;return{...o,captions:e.captions.map(bhe),audioIds:t,words:e.words.map(wj)}},Pj=e=>({...e,captionStyleSetting:vj(e.captionStyleSetting)}),Lhe=e=>{const t=Object.entries(e).map(([o,r])=>[o,Mhe(r)]);return Object.fromEntries(t)},Mhe=e=>({...e,waterMarkInfo:{...e.waterMarkInfo,version:2,vrewMark:e.waterMarkInfo.vrewMark?{...e.waterMarkInfo.vrewMark,version:2}:void 0}}),oD=(e,t)=>({...e,version:4,fileSize:t[e.mediaId].size}),Dhe=async e=>{const t=(await $e().getStockMusicInfo())?.musics??[],o=(await $e().getStockSoundEffectInfo())?.sounds??[],r=t.find(a=>a.id===e.mediaId)?.url||o.find(a=>a.id===e.mediaId)?.url;if(h("vrewJsonUpgraderV12.ts").info("[vrew file load] fetching stock audio blob from cloud storage.. audio url:"+r+". mediaId:"+e.mediaId),r===void 0)throw h("vrewJsonUpgraderV12.ts").error("Vrew file load error: No BGM or SoundEffect Blob is detected in vrewFile or fetching failed. mediaId:"+e.mediaId+"."),new C(_.C_MEDIA_BLOB_LOST);const n=await rh(r);if(!n)throw h("vrewJsonUpgraderV12.ts").error("Vrew file load error: No BGM or SoundEffect Blob is detected in vrewFile or fetching failed. mediaId:"+e.mediaId+"."),new C(_.C_MEDIA_BLOB_LOST);return n},khe=async(e,t,o)=>{switch(o.type){case ie.INVALID:return o;case ie.FILTER:return{...o,version:2,fileSize:e[o.mediaId].size};case ie.IMAGE:return{...o,version:2,fileSize:e[o.mediaId].size};case ie.BGM:case ie.SOUND_EFFECT:if(o.fileLocation!==D.IN_MEMORY){const r=await Dhe(o);return{...o,version:2,fileSize:r.size}}return{...o,version:2,fileSize:e[o.mediaId].size};case ie.ASSET_VIDEO:{if(o.fileLocation!==D.LOCAL_TMP)throw new C(_.C_MEDIA_LOST,{},"invalid fileLocation for asset video file. mediaId: "+o.mediaId);const r=t.get(o.path);if(!r||r.size===0){const n="Asset video file info not found for file : "+JSON.stringify(o);throw h("vrewJsonUpgraderV12.ts").error(n),new C(_.C_MEDIA_LOST,{},n)}return{...o,version:2,fileSize:r.size}}case ie.CHARACTER:return{...o,version:2,fileSize:e[o.mediaId].size};case ie.SIMPLE_CHARACTER:{const r=o.characterInfo,n=yN?.simpleCharacterInfos.find(x=>x.name===r.appearance),a=n?.makerUid?tt.USER:tt.VREW_RESOURCE;if(r.type===Xm.PNG)return{...o,version:2,mediaId:r.appearance,type:ie.IMAGE,isTransparent:!0,sourceOrigin:a,fileSize:e[o.mediaId].size};const i=await qt().getMediaFileInfo(o.path),s=(await Ue().getFileInfo(o.path)).size;if(!i.videoInfo){const x="Error occured while fetching video info for simple character file before v13. path:"+o.path;throw new C(_.C_VREW_FILE_INVALID_FORMAT,{},x)}return{...o,version:2,mediaId:AN(r.appearance),type:ie.ASSET_VIDEO,videoMetaInfo:{videoInfo:{size:i.videoInfo.size,frameRate:i.videoInfo.frameRate,codec:i.videoInfo.codec},duration:i.duration},isTransparent:!0,sourceOrigin:a,fileSize:s}}case ie.WATERMARK:return{...o,version:2,waterMarkInfo:{...o.waterMarkInfo,version:2,vrewMark:o.waterMarkInfo.vrewMark?{...o.waterMarkInfo.vrewMark,version:2}:void 0},fileSize:e[o.mediaId].size};case ie.SHAPE:return{...o,version:2,fileSize:e[o.mediaId].size};case ie.VIDEO_AUDIO:return{...o,version:5,originalClips:o.originalClips.map(Nj)};case ie.TTS:return oD(o,e);case ie.TTS_EFFECT:case ie.TTS_DUBBING:if(o.fileLocation!==D.IN_MEMORY)throw new C(_.C_MEDIA_LOST,{},"invalid fileLocation for tts file. file: "+JSON.stringify(o));return oD(o,e)}},Fhe=(e,t)=>{const{filterSetting:o}=e,r=t.filter(a=>a.type===ie.VIDEO_AUDIO),n=t.filter(a=>a.type===ie.FILTER);return Object.fromEntries(r.map(a=>[a.mediaId,{[sA.FILTER]:{effectType:sA.FILTER,filterMediaId:o?td[o.index].mediaId:Gl,filterAlphas:o?.alphas?Uhe(o.alph
1118as,n):Vhe()}}]))},Uhe=(e,t)=>{const o=e.default,r=Object.fromEntries(o.map((a,i)=>[td[i].mediaId,a])),n=Object.fromEntries(t.map(a=>[a.mediaId,.5]));return{...r,...n}},Vhe=()=>Object.fromEntries(fU.map(e=>{const t=Object.keys(e)[0];return[t,e[t]]})),Ghe=e=>Object.entries(e).reduce((t,[o,r])=>(L.set(t,o,{...r,loop:r.loop??r.type===ze.BGM}),t),{}),Whe=e=>{if(e===void 0)return{};const t=o=>{switch(o){case Rx.NONE:return Cx.NONE;case Rx.VERTICAL:return Cx.VERTICAL;case Rx.HORIZONTAL:return Cx.HORIZONTAL;case Rx.VERTICAL_HORIZONTAL:return Cx.VERTICAL_HORIZONTAL}};return Object.fromEntries(Object.entries(e).map(([o,r])=>[o,t(r)]))},bj=async(e,t)=>{const o={...e,files:e.files.map(She)},r=Ohe(o),{textboxFiles:n,textboxBlobs:a}=await Nhe(r.props.assets);yN=await yhe();const i=await Phe(r.files.filter(f=>f.type===ie.SIMPLE_CHARACTER),t),s={...t,...a,...i},{filterSetting:x,...c}=r.props,l=r.files.filter(f=>f.type===ie.ASSET_VIDEO).map(f=>f.path),d=await Ue().getFileInfos(l),u=new Map;for(let f=0;f<l.length;f++)u.set(l[f],d[f]);const p={...r,transcript:{scenes:r.transcript.scenes.map(f=>({...f,clips:f.clips.map(Nj)}))},files:[...await rs(r.files,async f=>khe(s,u,f)),...n],props:{...c,mediaEffectMap:Fhe(r.props,e.files),globalCaptionStyle:Pj(r.props.globalCaptionStyle),waterMarkMap:r.props.waterMarkMap?Lhe(r.props.waterMarkMap):void 0,assets:whe(r.props.assets),videoRatio:jhe(r.props.videoRatio,r.props.initProjectVideoSize),audios:Ghe(r.props.audioTransformsMap),pronunciationDisplay:p1,flipSetting:Whe(r.props.flipSetting)}};return Sj(p,s)},rD=e=>vt(e,t=>{t.forEach(o=>{o.captions.forEach(r=>{r.text.forEach(n=>{if(n.attributes){const a=n.attributes.font;if(!a)return;n.attributes.font=IT(a)}})})})}),Lj=e=>vt(e,t=>{t.quillStyle.font&&(t.quillStyle.font=IT(t.quillStyle.font))}),Hhe=e=>{const t={};return Object.entries(e).forEach(([o,r])=>{t[o]=Mj(r)}),t},Mj=e=>e.type!==pa.WEB?e:vt(e,t=>{Object.values(t.deltas).forEach(({ops:o})=>{o.forEach(r=>{if(r.attributes){const n=r.attributes.font;if(!n)return;r.attributes.font=IT(n)}})})}),jhe=(e,t)=>{switch(e){case he.VERTICAL:return 9/16;case he.WIDE_SCREEN:return 16/9;case he.CLASSIC:return 4/3;case he.INSTAGRAM:return 4/5;case he.SQUARE:return 1;case he.INIT:case he.ORIGINAL:default:return t.width/t.height}},Dj=e=>{const t=zhe(e);return Cj({...t,globalCaptionStyle:Pj(t.globalCaptionStyle),fullRangeAssets:t.fullRangeAssets.map(o=>({...o,assetModel:yj(o.assetModel)}))})},zhe=e=>{const t=e.createdInfo;return!t||U9.lt(t.version,Y4)?{...e,globalCaptionStyle:Lj(e.globalCaptionStyle),fullRangeAssets:e.fullRangeAssets.map(n=>({...n,assetModel:Mj(n.assetModel)}))}:e};var Pa=(e=>(e.IMAGE="image",e.LOTTIE="lottie",e.WEB="web",e.VIDEO="video",e.SHAPE="shape",e.CHARACTER="character",e.SIMPLE_CHARACTER="simpleCharacter",e))(Pa||{}),Ax=(e=>(e[e.NONE=0]="NONE",e[e.VERTICAL=1]="VERTICAL",e[e.HORIZONTAL=2]="HORIZONTAL",e[e.VERTICAL_HORIZONTAL=3]="VERTICAL_HORIZONTAL",e))(Ax||{});const Yhe=200,nD=100;var Bhe=(e=>(e[e.ORIGINAL=0]="ORIGINAL",e[e.TRANSLATE=1]="TRANSLATE",e))(Bhe||{});const kj=.075,xA="textarea";var Khe=(e=>(e.TRANSCRIPT="TRANSCRIPT",e.MANUAL="MANUAL",e))(Khe||{}),Xhe=(e=>(e.Korean="ko",e.English="en",e.Japanese="ja",e.Spanish="es",e.Taiwanese="zh",e))(Xhe||{}),Jhe=(e=>(e.None="None",e))(Jhe||{});const qhe=(e,t)=>({top:.1,middle:(1-t)/2,bottom:.97-t,custom:0})[e],cA=e=>["ja","zh",Jc.LAO,Jc.CHINESE_SIMPLIFIED].includes(e)===!1,lA=(e,t,o,r=!0,n=!0)=>{if(e===void 0)return"";const{captionMode:a,captions:i}=e;return o===0&&a==="TRANSCRIPT"?Qhe(e.words,r,n,t):i[o]?wt().toText(new Qt(i[o].text)):""},Qhe=(e,t=!0,o=!0,r=!0)=>{const n=r?" ":"";let a="";e.forEach(s=>{const x=s.hardcutWordMeta?"":n;s.text&&(a=a.concat(x,s.text))});const i=o?LT(a):a;return t?i.trim():i},Zhe=(e,t,o)=>e==="custom"||t===0&&(e==="top"||e==="middle")||t===1&&e==="bottom"?0:t===0&&e==="bottom"?-(o+.01):t===1&&(e==="top"||e==="middle")?o+.01:0,$he=(e,t)=>{const r=kj*e/nD,n=Math.round(42*nD/e),a=Math.floor(t/n)+1;return r*a},dA=(e,t)=>t.split(`
1119`).map(a=>$he(e,a.length)).reduce((a,i)=>a+i,0),uA=e=>{let t=0;for(const o of Object.keys(e)){const r=e[o];for(const n of r.ops)typeof n.insert!="string"||n.attributes===void 0||n.attributes.size===void 0||(t=Math.max(t,parseInt(n.attributes.size)))}return t||Yhe},eIe=(e,t,o,r)=>{if(t===0){const{height:n,style:a,text:i}=e.captions[1];if(n!==void 0)return n;const s=lA(e,cA(on(o)),1),x=a?new Qt(i):wt().fromText(s,r),c={[xA]:x},l=uA(c);return dA(l,s.trim())}if(t===1){const{height:n,text:a,style:i}=e.captions[0];if(n!==void 0)return n;
1119const s=lA(e,cA(on(o)),0),x=i?new Qt(a):wt().fromText(s,r),c={[xA]:x},l=uA(c);return dA(l,s.trim())}return kj},tIe=(e,t,o)=>r=>{const{captions:n}=e,{targetCaption:a,otherCaption:i}=r===0?{targetCaption:n.at(0),otherCaption:n.at(1)}:{targetCaption:n.at(1),otherCaption:n.at(0)};if(a===void 0||i===void 0)throw h("vrewJsonUpgraderV11.ts").error("caption is undefined during converting to custom caption in upgraderV11"),new C(_.C_LOGIC_ERROR);const{style:s,text:x,height:c}=a,l=a.style??t.captionStyleSetting,{yAlign:d,yOffset:u}=l,p=lA(e,cA(on(o)),r),f=s?new Qt(x):wt().fromText(p,t.quillStyle),E=uA({[xA]:f}),T=c??dA(E,p.trim()),O=Zhe(d,r,eIe(e,r,o,t.quillStyle)),S=qhe(d,T)+u+O;return{...a,text:f.ops,style:{...l,yAlign:"custom",yOffset:S}}},oIe=e=>({...e,captionStyleSetting:vN(e.captionStyleSetting)}),Fj=e=>({...e,speakerId:e.name}),Uj=e=>e?{...e,speaker:Fj(e.speaker)}:void 0,rIe=e=>{if(e===void 0)return{};const t=o=>{switch(o){case Ax.NONE:return Rx.NONE;case Ax.VERTICAL:return Rx.VERTICAL;case Ax.HORIZONTAL:return Rx.HORIZONTAL;case Ax.VERTICAL_HORIZONTAL:return Rx.VERTICAL_HORIZONTAL}};return Object.fromEntries(Object.entries(e).map(([o,r])=>[o,t(r)]))},nIe=e=>({...e,globalCaptionStyle:oIe(e.globalCaptionStyle),lastTTSSettings:Uj(e.lastTTSSettings),audioTransformsMap:EIe(e.audioTransformsMap),assets:sIe(e.assets),flipSetting:rIe(e.flipSetting)}),Vj=e=>{switch(e.type){case Pa.WEB:return aIe(e);case Pa.IMAGE:return iIe(e);case Pa.SHAPE:return{...e,type:pa.SHAPE};case Pa.LOTTIE:return{...e,type:pa.LOTTIE};case Pa.VIDEO:return{...e,type:pa.VIDEO};case Pa.CHARACTER:return{...e,type:pa.CHARACTER};case Pa.SIMPLE_CHARACTER:return{...e,type:pa.SIMPLE_CHARACTER}}},aIe=e=>({...e,type:pa.WEB,assetEffectInfo:e.assetEffectInfo?{type:e.assetEffectInfo.type,duration:Wx}:void 0}),iIe=e=>({...e,type:pa.IMAGE,assetEffectInfo:e.assetEffectInfo?{type:e.assetEffectInfo.type,duration:Wx}:void 0}),sIe=e=>{const t=Object.entries(e).map(([o,r])=>[o,Vj(r)]);return Object.fromEntries(t)},xIe=(e,t,o)=>{switch(e){case"custom":return o;case"top":case"middle":case"bottom":{const r=(1-t)*.5;return ue(o-r,6)}}},vN=e=>({...e,xOffset:xIe(e.yAlign,e.width,e.xOffset),assetEffectInfo:e.assetEffectInfo?{type:e.assetEffectInfo.type,duration:Wx}:void 0}),cIe=e=>({...e,style:e.style!==void 0?vN(e.style):void 0}),lIe=(e,t,o)=>{const{captions:r}=e,n=r.at(1);return n!==void 0&&wt().isEmpty(new Qt(n.text))?r:[0,1].map(tIe(e,t,o))},Gj=(e,t)=>o=>({...o,captions:lIe(o,e,t).map(cIe)}),dIe=(e,t,o)=>({...e,version:4,originalClips:e.originalClips.map(Gj(t,o))}),uIe=e=>({...e,speaker:Fj(e.speaker)}),pIe=e=>({...e,version:3,ttsInfo:uIe(e.ttsInfo)}),fIe=(e,t)=>o=>{switch(o.type){case ie.INVALID:case ie.FILTER:case ie.IMAGE:case ie.SOUND_EFFECT:case ie.BGM:case ie.ASSET_VIDEO:case ie.CHARACTER:case ie.SIMPLE_CHARACTER:case ie.WATERMARK:case ie.SHAPE:return o;case ie.VIDEO_AUDIO:return dIe(o,e,t);case ie.TTS:case ie.TTS_EFFECT:case ie.TTS_DUBBING:return pIe(o)}},gIe=(e,t)=>o=>({...o,clips:o.clips.map(Gj(e,t))}),_Ie=e=>e.find(o=>o.type===ie.VIDEO_AUDIO)?.audioLanguage??A6(),EIe=e=>Object.entries(e).reduce((t,[o,r])=>(L.set(t,o,{...r,loop:r.type===ze.BGM}),t),{}),Wj=async(e,t)=>
1119{const o=_Ie(e.files),r=e.props.globalCaptionStyle,n={...e,files:e.files.map(fIe(r,o)),props:nIe(e.props),transcript:{scenes:e.transcript.scenes.map(gIe(r,o))},lastTTSSettings:Uj(e.lastTTSSettings)};return bj(n,t)},Hj=async e=>{const t={...e,globalCaptionStyle:mIe(e.globalCaptionStyle),fullRangeAssets:e.fullRangeAssets.map(o=>({editable:o.editable,isUserInsertedAsset:o.isUserInsertedAsset,assetModel:Vj(o.assetModel)})),createdInfo:void 0};return Dj(t)},mIe=e=>({quillStyle:e.quillStyle,captionStyleSetting:vN(e.captionStyleSetting)});var Ja=(e=>(e.IMAGE="image",e.LOTTIE="lottie",e.WEB="web",e.VIDEO="video",e.SHAPE="shape",e.CHARACTER="character",e.SIMPLE_CHARACTER="simpleCharacter",e))(Ja||{});const aD={line:Ye.Line,"dashed-line":Ye.DashedLine,arrow:Ye.Arrow,"dashed-arrow":Ye.DashedArrow,"double-arrow":Ye.DoubleArrow,cross:Ye.Cross,square:Ye.Square,"rounded-square":Ye.Deprecated_RoundedSquare,triangle:Ye.Triangle,oval:Ye.Oval};var yx=(e=>(e[e.NONE=0]="NONE",e[e.VERTICAL=1]="VERTICAL",e[e.HORIZONTAL=2]="HORIZONTAL",e[e.VERTICAL_HORIZONTAL=3]="VERTICAL_HORIZONTAL",e))(yx||{});const hIe=e=>{const{shapeSource:t}=e;switch(t){case"line":case"dashed-line":case"arrow":case"dashed-arrow":case"double-arrow":case"cross":case"oval":return;case"square":case"triangle":return e.stroke.width>0&&e.stroke.isRounded?.1:0;case"rounded-square":return .1}},IIe=e=>{for(const t of e)if(t.type===ie.VIDEO_AUDIO&&t.mediaId!==_o&&t.videoMetaInfo.videoInfo!==void 0)return t.videoMetaInfo.videoInfo.size;return{width:1920,height:1080}},TIe=(e,t)=>({version:3,path:e.path,relativePath:e.relativePath,mediaId:e.mediaId,sourceOrigin:e.sourceOrigin,fileLocation:e.fileLocation,type:ie.VIDEO_AUDIO,audioLanguage:e.audioLanguage,fileSize:e.fileSize,importMethod:e.importMethod,videoMetaInfo:e.videoMetaInfo,originalClips:e.originalClips.map(jj(t))}),SIe=e=>{const t=e.at(-1);if(!t||typeof t.insert!="string")return e;const o={...t,insert:t.insert.replace(/\n*$/,`
1120`)};return[...e.slice(0,-1),o]},OIe=e=>t=>{const{trailingNewlinesFixed:o,text:r}=t;return{text:o?r:SIe(r),height:t.height,style:t.style!==void 0?zj(t.style,e):void 0}},jj=e=>t=>({words:t.words,captionMode:t.captionMode,captions:t.captions.map(OIe(e)),markerId:t.markerId,assetIds:t.assetIds,dirty:t.dirty,translationModified:t.translationModified,id:t.id,playbackRate:t.playbackRate,videoTransform:t.videoTransform,audioTransformIds:t.audioTransformIds,backgroundId:t.backgroundId}),wN=e=>({mediaId:e.mediaId,duration:e.duration,speaker:e.speaker,volume:e.volume,speed:e.speed,pitch:e.pitch,emotion:e.emotion,text:{processed:e.text,raw:e.text,textAspectLang:e.speaker.lang}}),CIe=e=>{switch(e.version){case 2:return e;case 1:return{...e,version:2,ttsInfo:wN(e.ttsInfo)};default:throw new C(_.C_VREW_FILE_INCOMPATIBLE_VERSION)}},RIe=e=>{switch(e.version){case 2:return e;case 1:return{...e,version:2,ttsInfo:wN(e.ttsInfo)};default:throw new C(_.C_VREW_FILE_INCOMPATIBLE_VERSION)}},AIe=e=>{switch(e.version){case 2:return e;case 1:return{...e,version:2,ttsInfo:wN(e.ttsInfo)};default:throw new C(_.C_VREW_FILE_INCOMPATIBLE_VERSION)}},yIe=e=>t=>{switch(t.type){case ie.INVALID:return t;case ie.FILTER:return t;case ie.IMAGE:return t;case ie.SOUND_EFFECT:case ie.BGM:return t;case ie.ASSET_VIDEO:return t;case ie.CHARACTER:return t;case ie.SIMPLE_CHARACTER:return t;case ie.TTS:return CIe(t);case ie.TTS_EFFECT:return RIe(t);case ie.TTS_DUBBING:return AIe(t);case ie.WATERMARK:return t;case ie.VIDEO_AUDIO:return TIe(t,e)}},zj=(e,t)=>({webAssetId:e.webAssetId,yAlign:e.yAlign,yOffset:e.yOffset,xOffset:e.xOffset,rotation:e.rotation,width:e.width,customAttributes:e.customAttributes,assetEffectInfo:e.assetEffectInfo,scaleFactor:t}),Yj=(e,t)=>({captionStyleSetting:zj(e.captionStyleSetting,t),quillStyle:e.quillStyle}),vIe=e=>e.dimensionType===Tr.ONE?{...e,type:Pa.SHAPE}:{...e,type:Pa.SHAPE,dimensionType:Tr.TWO,shapeType:e.shapeType,shapeSource:wIe(e.shapeSource),stroke:e.stroke,plane:e.plane,cornerRounding:hIe(e)},wIe=e=>{switch(e){case"line":case"dashed-line":case"arrow":case"dashed-arrow":case"double-arrow":case"cross":case"square":case"triangle":case"oval":return e;case"rounded-square":return"square"}},NIe=(e,t)=>({...e,type:Pa.WEB,scaleFactor:t}),Bj=(e,t)=>{switch(e.type){case Ja.IMAGE:return{...e,type:Pa.IMAGE};case Ja.LOTTIE:return{...e,type:Pa.LOTTIE};case Ja.VIDEO:return{...e,type:Pa.VIDEO};case Ja.CHARACTER:return{...e,type:Pa.CHARACTER};case Ja.SIMPLE_CHARACTER:return{...e,type:Pa.SIMPLE_CHARACTER};case Ja.SHAPE:return vIe(e);case Ja.WEB:return NIe(e,t)}},PIe=(e,t)=>{const o=Object.entries(e).map(([r,n])=>[r,Bj(n,t)]);return Object.fromEntries(o)},bIe=e=>{if(e===void 0)return{};const t=o=>{switch(o){case yx.NONE:return Ax.NONE;case yx.VERTICAL:return Ax.VERTICAL;case yx.HORIZONTAL:return Ax.HORIZONTAL;case yx.VERTICAL_HORIZONTAL:return Ax.VERTICAL_HORIZONTAL}};return Object.fromEntries(Object.entries(e).map(([o,r])=>[o,t(r)]))},LIe=(e,t,o)=>({globalCaptionStyle:Yj(e.globalCaptionStyle,o),captionDisplayMode:e.captionDisplayMode,videoSize:e.videoSize,filterSetting:e.filterSetting,flipSetting:bIe(e.flipSetting),assets:PIe(e.assets,o),analyzeDate:e.anal
1120yzeDate,audioTransformsMap:e.audioTransformsMap,markerNames:e.markerNames,videoRatio:e.videoRatio===he.ORIGINAL?he.INIT:e.videoRatio,globalVideoTransform:e.globalVideoTransform,backgroundMap:e.backgroundMap,lastTTSSettings:e.lastTTSSettings,waterMarkMap:e.waterMarkMap,initProjectVideoSize:t}),MIe=e=>e.type===Ja.SHAPE&&e.dimensionType===Tr.TWO,DIe=async e=>{const t=[],o={},r={},n=$e().getStockShapeInfo()?.templates;Object.values(e).filter(MIe).forEach(a=>{const i=aD[a.shapeSource]===Ye.Deprecated_RoundedSquare?Ye.Square:aD[a.shapeSource],s=n?.find(x=>x.shapeKey===i)?.template;if(!s){const x="Error occured while fetching shape for legacy shape data before v11. shapeType:"+i;throw new C(_.C_VREW_FILE_INVALID_FORMAT,{},x)}o[a.mediaId]=new Blob([s]),r[a.mediaId]="xml",t.push({version:1,type:ie.SHAPE,mediaId:a.mediaId,sourceOrigin:tt.VREW_RESOURCE,fileLocation:D.IN_MEMORY,path:""})});for(const a of Object.keys(o))await Ue().putMediaCache(a,o[a],r[a]);return{shapeFiles:t,shapeBlobs:o}},kIe=(e,t)=>e.map(o=>({clips:o.clips.map(jj(t)),name:o.name,dirty:o.dirty,translateInfo:o.translateInfo,id:o.id})),Kj=async(e,t)=>
1120{const o=IIe(e.files),r=o.width/o.height,{shapeFiles:n,shapeBlobs:a}=await DIe(e.props.assets),i={...t,...a},s={version:11,files:e.files.map(yIe(r)).concat(n),props:LIe(e.props,o,r),transcript:{scenes:kIe(e.transcript.scenes,r)},comment:e.comment,projectId:e.projectId,makerCid:e.makerCid,makerUid:e.makerUid,statistics:e.statistics,lastTTSSettings:e.lastTTSSettings};return Wj(s,i)},FIe=async e=>{const t=cr(he.INIT),o={...e,globalCaptionStyle:Yj(e.globalCaptionStyle,t),fullRangeAssets:e.fullRangeAssets.map(r=>({editable:r.editable,isUserInsertedAsset:r.isUserInsertedAsset,assetModel:Bj(r.assetModel,t)}))};return await Hj(o)},UIe=async e=>{switch(e.version){case 1:return await FIe(e);case 2:return await Hj(e);case 3:return Dj(e);case 4:return Cj(e);case 5:return Tj(e);case 6:return tj(e);case 7:return q4(e);case 8:return e;default:throw new C(_.C_FRAMEPACK_FILE_INCOMPATIBLE_VERSION)}};class y0{static CURRENT_FRAME_PACK_JSON_VERSION=8;static toVideoTransformJson=t=>({videoRatio:t.videoRatio,videoTransformFillType:t.videoTransformFillType});static toFramePackAssetJson=t=>{const o={...t.track,trackId:H4()};return{editable:t.editable,isUserInsertedAsset:t.isUserInsertedAsset,trackModel:Be.toTrackJson(o)}};static toFramePackAssetLocationsJson=t=>{const o={};return Object.entries(t).forEach(([r,n])=>{L.set(o,r,y0.toFramePackAssetLocationJson(n))}),o};static toFramePackAssetLocationJson=t=>{switch(t.assetLocation){case D.IN_MEMORY:return{assetLocation:D.IN_MEMORY,pathInFile:t.pathInFile,mimeType:t.mimeType};case D.REMOTE:return{assetLocation:D.REMOTE,src:t.src}}};static fromVideoTransformJson=t=>({videoRatio:t.videoRatio,videoTransformFillType:t.videoTransformFillType});static fromFramePackAssetJson=t=>{const o=Be.fromTrackJson(t.trackModel);return Rr(o)||Wa(o)?(h("FramePackJsonConverter.ts").warn("Watermark or audio track is not supported in template asset"),null):{editable:t.editable,isUserInsertedAsset:t.isUserInsertedAsset,track:o}};static fromFramePackAssetLocationsJson=t=>{const o={};return Object.entries(t).forEach(([r,n])=>{L.set(o,r,y0.fromFramePackAssetLocationJson(n))}),o};static fromFramePackAssetLocationJson=t=>{switch(t.assetLocation){case D.IN_MEMORY:return{assetLocation:D.IN_MEMORY,pathInFile:t.pathInFile,mimeType:t.mimeType};case D.REMOTE:return{assetLocation:D.REMOTE,src:t.src}}}}const VIe=(e,t)=>{const o=ei();let r;switch(t){case"image/png":r=o.getImageFileInfo(e);break;case"application/xml":r=o.getShapeInfo(e);break;case"text/html":r=o.getTextboxInfo(e);break;default:return}return r===void 0?(h("framePackFile.ts").warn("File info for "+e+" ("+t+") should exist in framePack resource manager"),void 0):r.blob},GIe=async(e,t)=>{const o=await Promise.all(Object.entries(e.assetLocationMap).map(([i,s])=>{if(s.assetLocation===D.IN_MEMORY)return{mediaId:i,mimeType:s.mimeType,pathInFile:s.pathInFile}}).filter(Se).map(async({mediaId:i,mimeType:s,pathInFile:x})=>{const c=VIe(i,s);if(c!==void 0)return{blob:c,pathInFile:x}}).filter(Se)),r={};await Promise.all(o.map(async({blob:i,pathInFile:s})=>{const x=await i.arrayBuffer();r[s]=x}));const n=JSON.stringify(WIe(e)),a={rawJson:n,buffers:r,path:t};await Ue().saveFramePackFile(a)},WIe=e=>({version:y0.CURRENT_FRAME_PACK_JSON_VERSION,id:e.id,videoTransform:y0.toVideoTransformJson(e.videoTransform),globalCaptionStyle:e.globalCaptionStyle,fullRangeAssets:e.fullRangeAssets.map(y0.toFramePackAssetJson),assetLocationMap:y0.toFramePackAssetLocationsJson(e.assetLocationMap),backgroundColor:e.backgroundColor,createdInfo:$g()}),Xj=async e=>{if(e.version<=0)throw new C(_.C_FRAMEPACK_FILE_INVALID_FORMAT);const t=await UIe(e),{id:o,videoTransform:r,globalCaptionStyle:n,fullRangeAssets:a,assetLocationMap:i,backgroundColor:s,createdInfo:x}=t;return{id:o,videoTransform:y0.fromVideoTransformJson(r),globalCaptionStyle:Be.fromGlobalCaptionStyleSettingJson(n),fullRangeAssets:a.map(c=>y0.fromFramePackAssetJson(c)).filter(ri),assetLocationMap:y0.fromFramePackAssetLocationsJson(i),backgroundColor:s,createdInfo:x??$g()}},HIe=async e=>{const t=Ue(),o=await t.loadFramePackFile(e);if(o===void 0)return;const{mainJson:r,blobs:n}=o,a=await Xj(r),i=await Jj({framePack:a,blobs:n});return{framePack:a,blobs:{...n,...i}}},jIe=async()=>
1120{try{const e=Ue(),t=await e.loadLocalFramePackFiles();return(await Promise.all(t.map(async({mainJson:r,blobs:n})=>{try{const a=await Xj(r),i=await Jj({framePack:a,blobs:n});return{framePack:a,blobs:{...n,...i}}}catch(a){return h("framePackFile.ts").error("Failed to load framePack "+r.id+": "+P(a)),null}}))).filter(yy)}catch(e){const t="error in loadLocalFramePackFiles: "+P(e);return h("framePackFile.ts").error(t),[]}},Jj=async({framePack:e,blobs:t})=>{const o={};return e.fullRangeAssets.forEach(r=>{const n={...r.track};if(f0(n)&&i2(n)&&!t[n.mediaId]){const a=$e().getStockShapeInfo()?.templates,i=a?.find(s=>s.shapeKey===n.shapeSource)?.template;if(!i){h("framePackFile.ts").error("Error occured while fetching shape for framePack. shapeType:"+n.shapeSource);return}o[n.mediaId]={blob:new Blob([i],{type:"application/xml"}),mimeType:"application/xml"}}}),o},zat=async()=>{await Promise.all([ei().ensureFontMapInitialized(),ei().ensureStockVideoInitialized(),ei().ensureImageInfoInitialized()]),ei().registerStockFramePackShapeInfo(),ei().registerStockTextboxInfo(),Y().openModal(st.SHORTS)},Yat=async e=>{if(!at()){const s=e,{name:x,blob:c}=s,l=URL.createObjectURL(c),{videoThumbnailPath:d,videoDimension:u}=await pA(l),p={path:x,blob:c,addSceneIndex:null,mediaFileInfo:void 0};return{type:bs.USER_VIDEO,uploadedMediaInfo:p,videoUrl:l,videoThumbnailPath:d,thumbnailImageMediaId:qe.v4(),videoDimension:u}}const t=e,{name:o}=t,r=(await Qg([{path:o}],void 0,!0))[0],{videoThumbnailPath:n,videoDimension:a}=await pA(o),i={path:o,blob:null,addSceneIndex:null,mediaFileInfo:r.mediaFileInfo};return{type:bs.USER_VIDEO,uploadedMediaInfo:i,videoUrl:o,videoThumbnailPath:n,thumbnailImageMediaId:qe.v4(),videoDimension:a}},zIe=async({remotePath:e,stockVideoLabel:t})=>{const o=await fetch(e),r=await o.blob(),n=URL.createObjectURL(r),{videoThumbnailPath:a,videoDimension:i}=await pA(n),s={path:e,blob:r,addSceneIndex:null,mediaFileInfo:void 0};return{type:bs.STOCK_VIDEO,stockVideoLabel:t,uploadedMediaInfo:s,videoUrl:n,videoThumbnailPath:a,thumbnailImageMediaId:qe.v4(),videoDimension:i}},pA=async e=>{const t=await b_e(e,2);if(t===void 0)throw new C(_.C_FRAMEPACK_GENERAL_ERROR);const{screenShotUrl:o,width:r,height:n}=t,a=r/n;return{videoThumbnailPath:o,videoDimension:a}},Bat=(e,t,o)=>{const r=cr(t.videoRatio),n=t.videoTransformFillType===ro.CONTAIN?"contain":"cut";return{..._b(e,r,n),trackId:Rt(),type:z.IMAGE,originalWidthHeightRatio:e,importType:_e.UNKNOWN,mediaId:o,rotation:0,zIndex:0}},Kat=()=>ei().getStockVideos()[0],Xat=(e,t)=>{const o=e?y6[e]:v6,r=o.indexOf(t);if(r===-1)return{prevStage:void 0,nextStage:void 0,currentStageString:""};const n=r>0?o[r-1]:void 0,a=r<o.length-1?o[r+1]:void 0,i=r+1+" / "+o.length;return{prevStage:n,nextStage:a,currentStageString:i}},Jat=(e,t)=>vt(e,o=>{t&&(o.id=t)}),qat=(e,t)=>
1120{const{captionStyleSetting:o,quillStyle:r}=e.globalCaptionStyle,{captionStyleSetting:n,quillStyle:a}=t,i={captionStyleSetting:{...o,customAttributes:n.customAttributes},quillStyle:{...a,size:r.size}};return{...e,globalCaptionStyle:i}},Qat=(e,t)=>({...e,backgroundColor:t}),Zat=(e,t,o)=>vt(e,r=>{const n=r.fullRangeAssets.map(a=>a.track);t.forEach(a=>{const i=n.findIndex(s=>s.mediaId===a.mediaId);if(i===-1){const s={editable:!0,track:a,isUserInsertedAsset:o};r.fullRangeAssets.push(s),L.set(r.assetLocationMap,a.mediaId,{assetLocation:D.IN_MEMORY,pathInFile:a.mediaId+".png",mimeType:"image/png"});return}r.fullRangeAssets[i].track=a})}),qj=e=>e===pn.None?{maxLineLength:0,mode:l0.FORCE_ALIGN_LENGTH,isDefaultOption:!0,mostRecentLineLengthEdit:"none"}:Mt(ke.SHORTS_LINEBREAK_SETTING)[e],$at=(e,t)=>e===bs.USER_VIDEO?t:Fe(),eit=(e,t)=>{const o=e===bs.USER_VIDEO?t:Fe();return Jue(o,qj(o),Boe)},tit=e=>{if(e===pn.None)return{lineLengthMax:0,lineLengthMin:0,lineLengthDefault:0,lastUsedMaxLineLength:0,mode:l0.ALIGN_SENTENCE};const t=Mt(ke.SHORTS_LINEBREAK_SETTING)[e];return{lineLengthMax:Woe[e],lineLengthMin:Jd[e],lineLengthDefault:Goe[e],lastUsedMaxLineLength:t.maxLineLength,mode:t.mode}},oit=e=>({...e,height:e.height*(oR*oR)}),rit=(e,t,o)=>{const r=Math.min(1,oR/o),n=_U/r,a=Math.round(t*n);if(e===void 0||Math.abs(e-a)<2)return;const i=IU(e/n,2);if(i!==t)return i},nit=e=>{const t=zn({}),o=ii({});return e.fullRangeAssets.forEach(r=>{const{track:n}=r;if(n.type===z.VIDEO){const{audio:i,...s}=n,x={...s,trackId:Rt()};L.set(t,x.trackId,x);const c=i?{...i,trackId:Rt()}:void 0;c&&L.set(t,c.trackId,c),L.set(o,ho(),{trackIds:c?[x.trackId,c.trackId]:[x.trackId],role:"sub",rangeType:tr.CLIP});return}const a={...r.track,trackId:Rt()};L.set(t,a.trackId,a),L.set(o,ho(),{trackIds:[a.trackId],role:"sub",rangeType:tr.CLIP})}),{trackEntries:t,assetEntries:o}},Qj=(e,t,o)=>{const r=t===pn.None?Fe():t,n=e,a=o[n];return a?a[r]:e},Zj=(e,t,o)=>vt(e,r=>{const n=e.quillStyle.font;n!==void 0&&(r.quillStyle.font=Qj(n,t,o))}),YIe=(e,t,o)=>vt(e,r=>{r.globalCaptionStyle=Zj(r.globalCaptionStyle,t,o)}),BIe=(e,t)=>{const o=Fe();return vt(e,r=>{r.fullRangeAssets.forEach(n=>{if(n.track.type===z.WEB)for(const a in n.track.deltas)n.track.deltas[a].ops.forEach(s=>{s.insert!==void 0&&typeof s.insert=="string"&&s.insert!==`
1121`&&(s.insert=A(s.insert)),t&&s.attributes?.font&&(s.attributes.font=Qj(s.attributes.font,o,t))})})})},KIe=async(e,t)=>{const o=h("shorts.ts"),r="";if(!t)return r;try{const n=await VK(t);if(!n)return o.error("file fetch failed: "+t.name),r;const a=n.type,i=gt(t.name).replace(RZ,".vrew"),s={cid:e,type:a,name:i},x=await si("/requestUploadImage",{method:"POST",body:JSON.stringify(s)},iZ).then(u=>u.json());if(x.result!=="single")throw new Error("Unexpected upload result: "+x.result);const{url:c,fileKey:l}=x;o.debug("logUploadUrl",c),o.info("Uploading "+l+" (size: "+n.size+")");const d=await fetch(c,{method:"PUT",body:n});return o.info("Uploaded result : "+d.statusText),l}catch(n){o.error("Feedback send images error : "+P(n))}return r},ait=async(e,t)=>{try{const o=await zo(),r=await ZT(),n=new Date().getTime(),a=new Date(r).getTime(),i=Math.floor((n-a)/(1e3*60*60*24)),s=[];for(const u of t){const p=await KIe(o,u);s.push(p)}const x=""+(await pt().getSystemSummary()).os,c=pt().isM1Arch(),l=toe(x,c),d={featureType:"shorts_template",clientType:at()?0:1,cid:o,content:e,uiLanguage:Fe(),osInfo:l,imageFiles:s,elapsedDays:i,buildTimestamp:QA};await si("/request-feature-specific-request",{method:"POST",body:JSON.stringify(d)})}catch(o){h("shorts.ts").error("Uploading framePack request failed "+P(o))}},iit=e=>{if(e!==null)return e.type===bs.BLANK_VIDEO?"blank_video":e.thumbnailImageMediaId},sit=e=>e.type===bs.BLANK_VIDEO?"":e.videoThumbnailPath,XIe=e=>{if(e===null)return"unknown";switch(e.type){case bs.USER_VIDEO:return"user_video";case bs.BLANK_VIDEO:return"blank_video";case bs.STOCK_VIDEO:return e.stockVideoLabel}},xit=e=>e?.type===bs.USER_VIDEO?e.videoDimension:cr(he.WIDE_SCREEN),JIe=[{id:"style_1",globalCaptionStyleSetting:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:0,xOffset:0,rotation:0,width:.9,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{size:"237",color:"#ffffff",font:"VITRO_CORE_LIGHT","outline-on":"true","outline-color":"#3cba6a","outline-width":"4","shadow-on":"true","shadow-color":"#9cf0b7","shadow-color-alpha":"1","shadow-position-x":"0","shadow-position-y":"0","shadow-blur-radius":"29","background-on":"false",background:"#000000","background-radius":"0px","background-alpha":"1","background-padding-side":"3px"}}},{id:"style_2",globalCaptionStyleSetting:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:0,xOffset:.05,rotation:0,width:.9,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"CAFE24_SSURROUND",size:"237",color:"#ff6a00","outline-color":"#ffffff","outline-width":"4","outline-on":"true","shadow-on":"true","shadow-color":"#9cf0b7","shadow-color-alpha":"1","shadow-position-x":"0","shadow-position-y":"0","shadow-blur-radius":"29","background-on":"false",background:"#000000","background-radius":"0px","background-alpha":"1","background-padding-side":"3px","secondary-outline-on":"true","secondary-outline-width":"4","secondary-outline-color":"#d85a00"}}},{id:"style_3",globalCaptionStyleSetting:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:0,xOffset:.05,rotation:0,width:.9,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{size:"237",color:"#f6fadb",font:"COOKIE_RUN_BLACK","outline-on":"true","outline-color":"#539ce2","outline-width":"4","shadow-on":"true","shadow-color":"#000000","shadow-color-alpha":"1","shadow-position-x":"2","shadow-position-y":"2","shadow-blur-radius":"10","background-on":"false",background:"#000000","background-radius":"0px","background-alpha":"1","background-padding-side":"3px"}}},{id:"style_4",globalCaptionStyleSetting:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:0,xOffset:.05,rotation:0,width:.9,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{size:"237",color:"#ffb4b4",font:"CAFE24_SSURROUND","outline-on":"true","outline-color":"#4b4b4b","outline-width":"4","shadow-on":"true","shadow-color":"#000000","shadow-color-alpha":"0.5","shadow-position-x":"2","shadow-position-y":"2","shadow-blur-radius":"10","background-on":"false",background:"#000000","background-radius":"0px","background-alpha":"1","background-padding-side":"3px"}}},{id:"style_5",globalCaptionStyleSetting:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:0,xOffset:.05,rotation:0,width:.9,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{size:"237",color:"#ff45cf",font:"BLACK_HAN_SANS","outline-on":"true","outline-color":"#2c2c2c","outline-width":"4","shadow-on":"true","shadow-color":"#000000","shadow-color-alpha":"0.38","shadow-position-x":"4","shadow-position-y":"4","shadow-blur-radius":"0","background-on":"false",background:"#000000","background-radius":"0px","background-alpha":"1","background-padding-side":"3px"}}},{id:"style_6",globalCaptionStyleSetting:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:0,xOffset:.05,rotation:0,width:.9,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{size:"237",color:"#ffffff",font:"JUA","outline-on":"true","outline-color":"#6F760A","outline-width":"4","shadow-on":"false","shadow-color":"#000000","shadow-color-alpha":"0.29","shadow-position-x":"4","shadow-position-y":"4","shadow-blur-radius":"59","background-on":"true",background:"#d9ec37","background-radius":"10px","background-alpha":"1","background-padding-side":"10px","background-padding-top":"3px","background-padding-bottom":"6px"}}},{id:"style_7",globalCaptionStyleSetting:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:0,xOffset:.05,rotation:0,width:.9,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{size:"237",color:"#ffffff",font:"S_CORE_DREAM_BLACK","outline-on":"true","outline-color":"#982ABC","outline-width":"5","shadow-on":"true","shadow-color":"#450d59","shadow-color-alpha":"1","shadow-position-x":"0","shadow-position-y":"6","shadow-blur-radius":"8","background-on":"false",background:"#0061fd","background-radius":"0px","background-alpha":"1","background-padding-side":"3px"}}},{id:"style_8",globalCaptionStyleSetting:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:0,xOffset:.05,rotation:0,width:.9,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{size:"237",color:"#fcc700",font:"CAFE24_SSURROUND","outline-on":"true","outline-color":"#ffffff","outline-width":"5","shadow-on":"true","shadow-color":"#00a1d8","shadow-color-alpha":"1","shadow-position-x":"0","shadow-position-y":"8","shadow-blur-radius":"0","background-on":"false",background:"#0061fd","background-radius":"0px","background-alpha":"1","background-padding-side":"3px"}}},{id:"style_9",globalCaptionStyleSetting:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:0,xOffset:.05,rotation:0,width:.9,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{size:"237",color:"#fed977",font:"CAFE24_SSURROUND","outline-on":"false","outline-color":"#ffffff","outline-width":"5","shadow-on":"false","shadow-color":"#00a1d8","shadow-color-alpha":"1","shadow-position-x":"0","shadow-position-y":"8","shadow-blur-radius":"0","background-on":"true",background:"#ff4015","background-radius":"20px","background-alpha":"1","background-padding-side":"16px","background-padding-top":"8px","background-padding-bottom":"6px"}}},{id:"style_10",globalCaptionStyleSetting:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:0,xOffset:.05,rotation:0,width:.9,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777}
1121,quillStyle:{size:"237",color:"#fcc700",font:"SEBANG_BOLD","outline-on":"false","outline-color":"#ffffff","outline-width":"5","shadow-on":"false","shadow-color":"#00a1d8","shadow-color-alpha":"1","shadow-position-x":"0","shadow-position-y":"8","shadow-blur-radius":"0","background-on":"true",background:"#373737","background-radius":"4px","background-alpha":"1","background-padding-side":"16px","background-padding-top":"8px","background-padding-bottom":"6px",italic:"true"}}},{id:"style_11",globalCaptionStyleSetting:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.1,xOffset:.02,rotation:0,width:.96,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"NANUM_SQUARE_ROUND",size:"237",color:"#ffffff","outline-on":"true","outline-color":"#000000","outline-width":"6"}}},{id:"style_12",globalCaptionStyleSetting:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.1,xOffset:.02,rotation:0,width:.96,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"GMARKET_SANS_MEDIUM",size:"237",color:"#ffffff","outline-on":"false","background-on":"true",background:"#000000","background-alpha":"0.56","background-radius":"4px","background-padding-side":"8px","background-padding-top":"4px","background-padding-bottom":"4px"}}},{id:"style_13",globalCaptionStyleSetting:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.1,xOffset:.02,rotation:0,width:.96,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"SB_AGGRO_MEDIUM",size:"237",color:"#ffffff","outline-on":"true","outline-color":"#000000","outline-width":"6","secondary-outline-on":"true","secondary-outline-width":"4","secondary-outline-color":"#ffffff"}}},{id:"style_14",globalCaptionStyleSetting:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.1,xOffset:.02,rotation:0,width:.96,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"BAZZI",size:"237",color:"#000000","outline-on":"false","outline-color":"#000000","outline-width":"6","secondary-outline-on":"false","secondary-outline-width":"4","secondary-outline-color":"#ffffff","background-on":"true",background:"#ffffff","background-radius":"20px","background-alpha":"0.7","background-padding-side":"20px","background-padding-top":"4px","background-padding-bottom":"4px"}}},{id:"style_15",globalCaptionStyleSetting:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.1,xOffset:.02,rotation:0,width:.96,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"MARUBURI_SERIF",size:"237",color:"#ffffff","outline-on":"false","outline-color":"#000000","outline-width":"6","shadow-on":"true","shadow-color":"#00a1d8","shadow-color-alpha":"1","shadow-position-x":"0","shadow-position-y":"0","shadow-blur-radius":"69"}}},{id:"style_16",globalCaptionStyleSetting:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.1,xOffset:.02,rotation:0,width:.96,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"NANUM_SQUARE_ROUND_REGULAR",size:"237",color:"#ffffff","outline-on":"false","outline-color":"#000000","outline-width":"6","background-on":"true",background:"#000000","background-radius":"0px","background-alpha":"0.7","background-padding-side":"3px"}}},{id:"style_17",globalCaptionStyleSetting:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.1,xOffset:.02,rotation:0,width:.96,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"NANUM_SQUARE_ROUND_REGULAR",size:"237",color:"#ffffff","outline-on":"false","outline-color":"#000000","outline-width":"6","background-on":"false",background:"#000000","background-radius":"0px","background-alpha":"0.7","background-padding-side":"3px","shadow-on":"true","shadow-color":"#000000","shadow-color-alpha":"1","shadow-position-x":"2","shadow-position-y":"2","shadow-blur-radius":"20"}}}],qIe=e=>({id:"template_28",videoTransform:{videoRatio:he.VERTICAL,videoTransformFillType:ro.CONTAIN},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"middle",yOffset:0,xOffset:0,rotation:0,width:.96,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{"outline-on":"false","background-on":"true","shadow-on":"false",font:"IBM_PLEX_SANS_SEMI_BOLD",size:"200",color:"#ffffff","outline-color":"#000000","outline-width":"7",background:"#00a1d8","background-alpha":"1","background-radius":"8px","background-padding-side":"9px","background-padding-top":"4px","background-padding-bottom":"4px","shadow-color":"#000000","shadow-color-alpha":"1","shadow-position-x":"4","shadow-position-y":"6","shadow-blur-radius":"0"}},assetLocationMap:{},fullRangeAssets:[],createdInfo:e}),QIe=e=>({id:"template_18",videoTransform:{videoRatio:he.WIDE_SCREEN,videoTransformFillType:ro.CONTAIN},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.025,xOffset:0,rotation:0,width:.96,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#18191a"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"NANUM_SQUARE_NEO_EXTRA_BOLD",size:"125",color:"#eaf28f"}},assetLocationMap:{template_18_image_1:{assetLocation:D.REMOTE,src:"https://stock-resources.vrew.ai/template-resources/images/template_18_image_1.png"}},fullRangeAssets:[{editable:!1,track:{mediaId:"template_18_image_1",type:z.IMAGE,xPos:0,yPos:0,width:1,height:1,rotation:0,zIndex:1,originalWidthHeightRatio:1.7777777777777777,importType:_e.UNKNOWN,stats:{}}},{editable:!1,track:{mediaId:"uc-0010-simple-textbox",type:z.WEB,xPos:.42176308539944923,yPos:.010686274509803955,width:.15564738292011018,height:.09,rotation:0,zIndex:2,importType:Yt.UNKNOWN,deltas:{textarea:new Qt().insert("shorts.channel_name",{font:"NANUM_SQUARE_NEO_EXTRA_BOLD",size:"100",color:"#eaf28f"}).insert(`
1122`)},customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],enabledInlineTypes:["bold","italic","font","size","color","background","outline-color","shadow-color"],durationSeconds:0,loop:!0,stats:{},scaleFactor:1.7777777777777777}}],createdInfo:e}),ZIe=e=>({id:"template_21",videoTransform:{videoRatio:he.WIDE_SCREEN,videoTransformFillType:ro.CONTAIN},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.0375,xOffset:0,rotation:0,width:.96,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"GMARKET_SANS_MEDIUM",size:"125",color:"#ffffff","background-on":"true",background:"#324482","background-radius":"0","background-alpha":"1","background-padding-side":"5px","background-padding-top":"2px","background-padding-bottom":"2px"}},assetLocationMap:{template_21_image_1:{assetLocation:D.REMOTE,src:"https://stock-resources.vrew.ai/template-resources/images/template_21_image_1.png"}},fullRangeAssets:[{editable:!1,track:{mediaId:"template_21_image_1",type:z.IMAGE,xPos:0,yPos:0,width:1,height:1,rotation:0,zIndex:1,originalWidthHeightRatio:1.7777777777777777,importType:_e.UNKNOWN,stats:{}}}],createdInfo:e}),$Ie=e=>({id:"template_1",videoTransform:{videoRatio:he.VERTICAL,videoTransformFillType:ro.CUT},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.126775,xOffset:0,rotation:0,width:.9,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000099"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"VITRO PRIDE TTF-Vrew_400",size:"240",color:"#ffffff",italic:"true"}},assetLocationMap:{template_1_image_1:{assetLocation:D.REMOTE,src:"https://stock-resources.vrew.ai/template-resources/images/template_1_image_1.png"}},fullRangeAssets:[{editable:!1,track:{mediaId:"template_1_image_1",type:z.IMAGE,xPos:.06806918874911365,yPos:.03481894150417823,width:.8638613861386139,height:.9303621169916435,rotation:0,zIndex:2,originalWidthHeightRatio:.5233485193621867,importType:_e.UNKNOWN,stats:{}}}],createdInfo:e}),eTe=e=>({id:"template_14",videoTransform:{videoRatio:he.VERTICAL,videoTransformFillType:ro.CONTAIN},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.225,xOffset:0,rotation:0,width:.9,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"BM_HANNA_11YRS",size:"200",color:"#ffffff","outline-color":"#000000","outline-width":"4","outline-on":"false","background-on":"true",background:"#ffffff","background-radius":"0px","background-alpha":"0","background-padding-side":"30px","background-padding-top":"6px","background-padding-bottom":"4px"}},assetLocationMap:{template_14_image_1:{assetLocation:D.REMOTE,src:"https://stock-resources.vrew.ai/template-resources/images/template_14_image_1.png"}},fullRangeAssets:[{editable:!0,track:{mediaId:"template_14_image_1",type:z.IMAGE,xPos:.09051117232935665,yPos:.14416011093387474,width:.022727272727272728,height:.07888631090487239,rotation:0,zIndex:1,originalWidthHeightRatio:.16666666666666666,importType:_e.UNKNOWN,stats:{}}},{editable:!0,track:{mediaId:"uc-0010-simple-textbox",type:z.WEB,xPos:.12570247933884304,yPos:.1701031395011601,width:.6,height:.05,rotation:0,zIndex:2,importType:Yt.UNKNOWN,deltas:{textarea:new Qt().insert("shorts.insert_title",{size:"200",color:"#b9eaff",font:"BM_HANNA_11YRS",italic:"true","shadow-on":"true","shadow-color":"#000000","shadow-color-alpha":"0.53","shadow-position-x":"0","shadow-position-y":"3","shadow-blur-radius":"8"}).insert(`
1123`)},customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"start"}],enabledInlineTypes:["bold","italic","font","size","color","background","outline-color","shadow-color"],durationSeconds:0,loop:!0,stats:{},scaleFactor:1.7777777777777777}},{editable:!0,track:{mediaId:"uc-0010-simple-textbox",type:z.WEB,xPos:.13190082644628107,yPos:.14458109773781902,width:.2066115702479339,height:.03,rotation:0,zIndex:3,importType:Yt.UNKNOWN,deltas:{textarea:new Qt().insert("CHAPTER 1",{size:"100",color:"#ffffff",font:"BM_HANNA_11YRS",italic:"true","shadow-on":"true","shadow-color":"#000000","shadow-color-alpha":"0.53","shadow-position-x":"0","shadow-position-y":"3","shadow-blur-radius":"8"}).insert(`
1124`)},customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],enabledInlineTypes:["bold","italic","font","size","color","background","outline-color","shadow-color"],durationSeconds:0,loop:!0,stats:{},scaleFactor:1.7777777777777777}}],createdInfo:e}),tTe=e=>({id:"template_20",videoTransform:{videoRatio:he.WIDE_SCREEN,videoTransformFillType:ro.CONTAIN},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.0584,xOffset:0,rotation:0,width:.96,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"KCC_EUNYOUNG",size:"150",color:"#ffffff","outline-on":"true","outline-color":"#4b3700","outline-width":"4","secondary-outline-on":"true","secondary-outline-width":"4","secondary-outline-color":"#ffffff"}},assetLocationMap:{template_20_image_1:{assetLocation:D.REMOTE,src:"https://stock-resources.vrew.ai/template-resources/images/template_20_image_1.png"}},fullRangeAssets:[{editable:!1,track:{mediaId:"template_20_image_1",type:z.IMAGE,xPos:0,yPos:0,width:1,height:1,rotation:0,zIndex:1,originalWidthHeightRatio:1.7777777777777777,importType:_e.UNKNOWN,stats:{}}},{editable:!1,track:{mediaId:"uc-0010-simple-textbox",type:z.WEB,xPos:.8370798898071624,yPos:0,width:.13911845730027547,height:.11,rotation:0,zIndex:8,importType:Yt.UNKNOWN,deltas:{textarea:new Qt().insert("shorts.channel_name",{size:"125",color:"#ffffff",font:"KCC_EUNYOUNG",bold:"true"}).insert(`
1125`)},customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],enabledInlineTypes:["bold","italic","font","size","color","background","outline-color","shadow-color"],durationSeconds:0,loop:!0,stats:{},scaleFactor:1.7777777777777777}}],createdInfo:e}),oTe=e=>({id:"template_0",videoTransform:{videoRatio:he.VERTICAL,videoTransformFillType:ro.CONTAIN},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.126775,xOffset:0,rotation:0,width:.96,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{size:"237",color:"#ffffff",font:"PRETENDARD","outline-color":"#000000","outline-width":"4","outline-on":"true"}},assetLocationMap:{},fullRangeAssets:[],createdInfo:e}),rTe=e=>({id:"template_17",videoTransform:{videoRatio:he.WIDE_SCREEN,videoTransformFillType:ro.CONTAIN},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.025,xOffset:0,rotation:0,width:.96,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"MARUBURI_SERIF",size:"100",color:"#ffffff"}},assetLocationMap:{template_17_image_1:{assetLocation:D.REMOTE,src:"https://stock-resources.vrew.ai/template-resources/images/template_17_image_1.png"}},fullRangeAssets:[{editable:!1,track:{mediaId:"template_17_image_1",type:z.IMAGE,xPos:-.0009641873278235975,yPos:.5906862745098039,width:1,height:.40833333333333327,rotation:0,zIndex:1,originalWidthHeightRatio:4.35374149659864,importType:_e.UNKNOWN,stats:{}}},{editable:!1,track:{mediaId:"uc-0050-branding-box",type:z.WEB,xPos:.7855371900826448,yPos:.035196078431372575,width:.21349862258953167,height:.1,rotation:0,zIndex:1,importType:Yt.UNKNOWN,deltas:{textarea:new Qt().insert("shorts.channel_name",{size:"100",font:"MARUBURI_SERIF"}).insert(`
1126`)},customAttributes:[{attributeName:"--outline-color",type:"color-hex",value:"#ffffff"}],enabledInlineTypes:["font","size"],durationSeconds:0,loop:!1,stats:{},scaleFactor:1.7777777777777777}}],createdInfo:e}),nTe=e=>({id:"template_11",videoTransform:{videoRatio:he.VERTICAL,videoTransformFillType:ro.CONTAIN},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"middle",yOffset:0,xOffset:0,rotation:0,width:.9,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000099"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"SB_AGGRO_BOLD",size:"250",color:"#000000","outline-color":"#000000","outline-width":"10","outline-on":"false",
1126"background-on":"true",background:"#ffffff","background-radius":"0px","background-alpha":"0.65","background-padding-side":"16px",italic:"true","background-padding-top":"6px","background-padding-bottom":"4px"}},assetLocationMap:{},fullRangeAssets:[{editable:!0,track:{mediaId:"uc-0010-simple-textbox",type:z.WEB,xPos:.20041322314049587,yPos:.03921113689095129,width:.6,height:.05,rotation:0,zIndex:1,importType:Yt.UNKNOWN,deltas:{textarea:new Qt().insert("shorts.channel_name",{size:"200",color:"#ffffff",font:"SB_AGGRO_MEDIUM","shadow-on":"true","shadow-color":"#000000","shadow-color-alpha":"1","shadow-position-x":"0","shadow-position-y":"3","shadow-blur-radius":"41"}).insert(`
1127`)},customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],enabledInlineTypes:["bold","italic","font","size","color","background","outline-color","shadow-color"],durationSeconds:0,loop:!0,stats:{},scaleFactor:1.7777777777777777}}],createdInfo:e}),aTe=e=>({id:"template_4",videoTransform:{videoRatio:he.VERTICAL,videoTransformFillType:ro.CUT},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.132525,xOffset:0,rotation:0,width:.9,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"PRETENDARD",size:"253",color:"#ffffff","background-on":"false",background:"#9ec888","background-radius":"1px","background-alpha":"0.63","background-padding-side":"3px","background-padding-top":"2px","background-padding-bottom":"2px","shadow-on":"true","shadow-color":"#2EE58D","shadow-color-alpha":"1","shadow-position-x":"4","shadow-position-y":"4","shadow-blur-radius":"0","outline-on":"true","outline-color":"#000000","outline-width":"4"}},assetLocationMap:{template_4_image_1:{assetLocation:D.REMOTE,src:"https://stock-resources.vrew.ai/template-resources/images/template_4_image_1.png"}},fullRangeAssets:[{editable:!0,track:{mediaId:"template_4_image_1",type:z.IMAGE,xPos:14070186810693563e-32,yPos:11606313837090609e-23,width:.9975247524752475,height:.10167130919220056,rotation:0,zIndex:1,originalWidthHeightRatio:3.857142857142857,importType:_e.UNKNOWN,stats:{}}},{editable:!0,track:{mediaId:"uc-0010-simple-textbox",type:z.WEB,xPos:.13118811881188197,yPos:.01242339832869082,width:.7376237623762376,height:.07,rotation:0,zIndex:1,importType:Yt.UNKNOWN,deltas:{textarea:new Qt().insert("shorts.insert_title",{size:"237",color:"#000000",font:"PRETENDARD","shadow-on":"false","shadow-color":"#000000","shadow-color-alpha":"1","shadow-position-x":"0","shadow-position-y":"3","shadow-blur-radius":"30"}).insert(`
1128`)},customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],enabledInlineTypes:["bold","italic","font","size","color","background","outline-color","shadow-color"],durationSeconds:0,loop:!0,stats:{},scaleFactor:1.7777777777777777}}],createdInfo:e}),iTe=e=>({id:"template_15",videoTransform:{videoRatio:he.VERTICAL,videoTransformFillType:ro.CONTAIN},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.225,xOffset:0,rotation:0,width:.9,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"CAFE24_SSURROUND_AIR",size:"200",color:"#ffffff","outline-color":"#FF7B7B","outline-width":"2","outline-on":"true","background-on":"true",background:"#FFE9E9","background-radius":"10px","background-alpha":"0.8","background-padding-side":"30px","background-padding-top":"6px","background-padding-bottom":"4px"}},assetLocationMap:{template_15_image_1:{assetLocation:D.REMOTE,src:"https://stock-resources.vrew.ai/template-resources/images/template_15_image_1.png"}},fullRangeAssets:[{editable:!1,track:{mediaId:"template_15_image_1",type:z.IMAGE,xPos:0,yPos:0,width:1,height:1,rotation:0,zIndex:1,originalWidthHeightRatio:.5625,importType:_e.UNKNOWN,stats:{}}}],createdInfo:e}),sTe=e=>({id:"template_16",videoTransform:{videoRatio:he.WIDE_SCREEN,videoTransformFillType:ro.CONTAIN},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"custom",yOffset:.42034357674104117,xOffset:0,rotation:0,width:.96,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777,assetEffectInfo:{type:Me.FADE_IN,duration:Wx,startDelay:wh}},quillStyle:{font:"NANUM_SQUARE_NEO_EXTRA_BOLD",size:"200",color:"#ffffff"}},assetLocationMap:{},fullRangeAssets:[{editable:!1,track:{type:z.SHAPE,dimensionType:2,mediaId:"template_16_shpae_1",zIndex:1,shapeType:0,shapeSource:Ye.Square,stroke:{color:"#00000000",width:0,isDashed:!1,isRounded:!0},plane:{color:"#00000080"}
1128,width:1,height:1,xPos:0,yPos:0,rotation:0,cornerRounding:0}},{editable:!0,track:{mediaId:"uc-0010-simple-textbox",type:z.WEB,xPos:.8095316804407713,yPos:.03764705882352944,width:.18044077134986225,height:.09,rotation:0,zIndex:2,importType:Yt.UNKNOWN,deltas:{textarea:new Qt().insert("shorts.channel_name",{size:"100",color:"#ffffff",font:"NANUM_SQUARE_NEO_EXTRA_BOLD"}).insert(`
1129`)},customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],enabledInlineTypes:["bold","italic","font","size","color","background","outline-color","shadow-color"],durationSeconds:0,loop:!0,stats:{},scaleFactor:1.7777777777777777}}],createdInfo:e}),xTe=e=>({id:"template_10",videoTransform:{videoRatio:he.VERTICAL,videoTransformFillType:ro.CUT},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.132525,xOffset:0,rotation:0,width:.9,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"GMARKET_SANS_MEDIUM",size:"221",color:"#ffffff","background-on":"true",background:"#000000","background-radius":"0px","background-alpha":"0.6","background-padding-side":"3px","background-padding-top":"2px","background-padding-bottom":"3px","shadow-on":"false","shadow-color":"#000000","shadow-color-alpha":"0.6","shadow-position-x":"0","shadow-position-y":"0","shadow-blur-radius":"87","outline-on":"false","outline-color":"#000000","outline-width":"4",italic:"true"}},assetLocationMap:{template_10_image_1:{assetLocation:D.REMOTE,src:"https://stock-resources.vrew.ai/template-resources/images/template_10_image_1.png"}},fullRangeAssets:[{editable:!1,track:{mediaId:"template_10_image_1",type:z.IMAGE,xPos:0,yPos:0,width:1,height:1,rotation:0,zIndex:1,originalWidthHeightRatio:.5625,importType:_e.UNKNOWN,stats:{}}},{editable:!0,track:{mediaId:"uc-0010-simple-textbox",type:z.WEB,xPos:.06559405940594108,yPos:.025153203342619893,width:.8688118811881188,height:.09,rotation:0,zIndex:1,importType:Yt.UNKNOWN,deltas:{textarea:new Qt().insert("shorts.channel_name",{size:"316",color:"#ffffff",font:"GMARKET_SANS",italic:"true","shadow-on":"false","shadow-color":"#5756ff","shadow-color-alpha":"1","shadow-position-x":"3","shadow-position-y":"3","shadow-blur-radius":"0"}).insert(`
1130`)},customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],enabledInlineTypes:["bold","italic","font","size","color","background","outline-color","shadow-color"],durationSeconds:0,loop:!0,stats:{},scaleFactor:1.7777777777777777}}],createdInfo:e}),cTe=e=>({id:"template_24",videoTransform:{videoRatio:he.VERTICAL,videoTransformFillType:ro.CONTAIN},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"middle",yOffset:0,xOffset:0,rotation:0,width:.96,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"MONTSERRAT_ALTERNATES_EXTRA_BOLD",size:"200",color:"#d9ec37","outline-on":"true","outline-color":"#000000","outline-width":"7","shadow-on":"true","shadow-color":"#000000","shadow-color-alpha":"1","shadow-position-x":"4","shadow-position-y":"6","shadow-blur-radius":"0"}},assetLocationMap:{},fullRangeAssets:[],createdInfo:e}),lTe=e=>({id:"template_22",videoTransform:{videoRatio:he.WIDE_SCREEN,videoTransformFillType:ro.CONTAIN},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.0584,xOffset:0,rotation:0,width:.96,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#000000c4"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"PYEONGCHANG_PEACE_LIGHT",size:"100",color:"#ffffff"}},assetLocationMap:{template_22_image_1:{assetLocation:D.REMOTE,src:"https://stock-resources.vrew.ai/template-resources/images/template_22_image_1.png"}},fullRangeAssets:[{editable:!1,track:{mediaId:"template_22_image_1",type:z.IMAGE,xPos:0,yPos:0,width:1,height:1,rotation:0,zIndex:1,originalWidthHeightRatio:1.7777777777777777,importType:_e.UNKNOWN,stats:{}}}],createdInfo:e}),dTe=e=>({id:"template_2",videoTransform:{videoRatio:he.VERTICAL,videoTransformFillType:ro.CUT},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.10314999999999999,xOffset:0,rotation:0,width:.9,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"NANUM_SQUARE_ROUND",size:"237",color:"#FED977","background-on":"true",background:"#FF4015","background-radius":"7px","background-alpha":"1","background-padding-side":"4px","background-padding-top":"2px","background-padding-bottom":"2px"}},assetLocationMap:{template_2_image_1:{assetLocation:D.REMOTE,src:"https://stock-resources.vrew.ai/template-resources/images/template_2_image_1.png"}},fullRangeAssets:[{editable:!1,track:{mediaId:"template_2_image_1",type:z.IMAGE,xPos:0,yPos:-.006249999999999978,width:1,height:1.0125,rotation:0,zIndex:2,originalWidthHeightRatio:.5555555555555556,importType:_e.UNKNOWN,stats:{}}},{editable:!0,track:{mediaId:"uc-0010-simple-textbox",type:z.WEB,xPos:.20049504950495056,yPos:.030529247910863533,width:.6,height:.07,rotation:0,zIndex:3,importType:Yt.UNKNOWN,deltas:{textarea:new Qt().insert("shorts.channel_name",{size:"237",color:"#ffffff",font:"NANUM_SQUARE_ROUND"}).insert(`
1131`)},customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],enabledInlineTypes:["bold","italic","font","size","color","background","outline-color","shadow-color"],durationSeconds:0,loop:!0,stats:{},scaleFactor:1.7777777777777777}}],createdInfo:e}),uTe=e=>({id:"template_8",videoTransform:{videoRatio:he.VERTICAL,videoTransformFillType:ro.CUT},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"middle",yOffset:.11747500000000001,xOffset:0,rotation:0,width:.9,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"SEBANG",size:"237",color:"#ffffff","background-on":"true",background:"#000000","background-radius":"0px","background-alpha":"0.49","background-padding-side":"3px","background-padding-top":"2px","background-padding-bottom":"3px","shadow-on":"false","shadow-color":"#2EE58D","shadow-color-alpha":"1","shadow-position-x":"4","shadow-position-y":"4","shadow-blur-radius":"0","outline-on":"false","outline-color":"#000000","outline-width":"4"}},assetLocationMap:{template_8_image_1:{assetLocation:D.REMOTE,src:"https://stock-resources.vrew.ai/template-resources/images/template_8_image_1.png"}},fullRangeAssets:[{editable:!1,track:{mediaId:"template_8_image_1",type:z.IMAGE,xPos:0,yPos:0,width:1,height:1,rotation:0,zIndex:1,originalWidthHeightRatio:.5625,importType:_e.UNKNOWN,stats:{}}},{editable:!0,track:{mediaId:"uc-0010-simple-textbox",type:z.WEB,xPos:.10767326732673274,yPos:.02495821727019485,width:.7846534653465347,height:.09,rotation:0,zIndex:1,importType:Yt.UNKNOWN,deltas:{textarea:new Qt().insert("shorts.insert_title",{size:"237",color:"#ffffff",font:"SEBANG_BOL
1131D","background-on":"true",background:"#ff4015","background-radius":"2px","background-alpha":"1","background-padding-side":"3px","background-padding-top":"2px","background-padding-bottom":"2px"}).insert(`
1132`)},customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],enabledInlineTypes:["bold","italic","font","size","color","background","outline-color","shadow-color"],durationSeconds:0,loop:!0,stats:{},scaleFactor:1.7777777777777777}}],createdInfo:e}),pTe=e=>({id:"template_29",videoTransform:{videoRatio:he.VERTICAL,videoTransformFillType:ro.CONTAIN},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"middle",yOffset:0,xOffset:0,rotation:0,width:.96,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"PERMANENT_MARKER_REGULAR",size:"300",color:"#d357fe","outline-on":"true","outline-color":"#000000","outline-width":"7","shadow-on":"true","shadow-color":"#000000","shadow-color-alpha":"1","shadow-position-x":"4","shadow-position-y":"6","shadow-blur-radius":"0"}},assetLocationMap:{},fullRangeAssets:[],createdInfo:e}),fTe=e=>({id:"template_5",videoTransform:{videoRatio:he.VERTICAL,videoTransformFillType:ro.CUT},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.132525,xOffset:0,rotation:0,width:.9,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"JUA",size:"253",color:"#ffffff","background-on":"true",background:"#934BB5","background-radius":"5px","background-alpha":"1","background-padding-side":"3px","background-padding-top":"2px","background-padding-bottom":"3px","shadow-on":"false","shadow-color":"#2EE58D","shadow-color-alpha":"1","shadow-position-x":"4","shadow-position-y":"4","shadow-blur-radius":"0","outline-on":"false","outline-color":"#000000","outline-width":"4"}},assetLocationMap:{template_5_image_1:{assetLocation:D.REMOTE,src:"https://stock-resources.vrew.ai/template-resources/images/template_5_image_1.png"}},fullRangeAssets:[{editable:!1,track:{mediaId:"template_5_image_1",type:z.IMAGE,xPos:0,yPos:0,width:1,height:1,rotation:0,originalWidthHeightRatio:.5625,zIndex:1,importType:_e.UNKNOWN,stats:{}}},{editable:!0,track:{mediaId:"uc-0010-simple-textbox",type:z.WEB,xPos:.08292079207920869,yPos:.02913649025069639,width:.8341584158415841,height:.07,rotation:0,zIndex:1,importType:Yt.UNKNOWN,deltas:{textarea:new Qt().insert("shorts.insert_title",{size:"237",color:"#ffffff",font:"JUA","shadow-on":"true","shadow-color":"#000000","shadow-color-alpha":"0.37","shadow-position-x":"0","shadow-position-y":"3","shadow-blur-radius":"30"}).insert(`
1133`)},customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"end"}],enabledInlineTypes:["bold","italic","font","size","color","background","outline-color","shadow-color"],durationSeconds:0,loop:!0,stats:{},scaleFactor:1.7777777777777777}}],createdInfo:e}),gTe=e=>({id:"template_12",videoTransform:{videoRatio:he.VERTICAL,videoTransformFillType:ro.CONTAIN},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"middle",yOffset:0,xOffset:0,rotation:0,width:.9,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777}
1133,quillStyle:{font:"SEBANG_BOLD",size:"200",color:"#ffffff","outline-color":"#000000","outline-width":"4","outline-on":"true","background-on":"true",background:"#ffffff","background-radius":"0px","background-alpha":"0","background-padding-side":"30px","background-padding-top":"6px","background-padding-bottom":"4px"}},assetLocationMap:{template_12_image_1:{assetLocation:D.REMOTE,src:"https://stock-resources.vrew.ai/template-resources/images/template_12_image_1.png"},template_12_image_2:{assetLocation:D.REMOTE,src:"https://stock-resources.vrew.ai/template-resources/images/template_12_image_2.png"}},fullRangeAssets:[{editable:!0,track:{mediaId:"uc-0010-simple-textbox",type:z.WEB,xPos:.20041322314049587,yPos:.03921113689095129,width:.6,height:.05,rotation:0,zIndex:1,importType:Yt.UNKNOWN,deltas:{textarea:new Qt().insert("shorts.channel_name",{size:"200",color:"#ffffff",font:"SB_AGGRO_MEDIUM","shadow-on":"true","shadow-color":"#000000","shadow-color-alpha":"1","shadow-position-x":"0","shadow-position-y":"3","shadow-blur-radius":"41"}).insert(`
1134`)},customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],enabledInlineTypes:["bold","italic","font","size","color","background","outline-color","shadow-color"],durationSeconds:0,loop:!0,stats:{},scaleFactor:1.7777777777777777}},{editable:!0,track:{mediaId:"template_12_image_1",type:z.IMAGE,xPos:.8223287419651045,yPos:.5664733178654296,width:.08884297520661157,height:.04988399071925754,rotation:0,zIndex:1,originalWidthHeightRatio:.9828571428571429,importType:_e.UNKNOWN,stats:{}}},{editable:!0,track:{mediaId:"template_12_image_2",type:z.IMAGE,xPos:.08884299816345209,yPos:.385498839907193,width:.08471074380165289,height:.048723897911832945,rotation:0,zIndex:2,originalWidthHeightRatio:.9828571428571429,importType:_e.UNKNOWN,stats:{}}}],createdInfo:e}),_Te=e=>({id:"template_19",videoTransform:{videoRatio:he.WIDE_SCREEN,videoTransformFillType:ro.CONTAIN},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.0584,xOffset:0,rotation:0,width:.96,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#000000b3"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"CAFE24_CURSIVE",size:"150",color:"#ffffff"}},assetLocationMap:{template_19_image_1:{assetLocation:D.REMOTE,src:"https://stock-resources.vrew.ai/template-resources/images/template_19_image_1.png"}},fullRangeAssets:[{editable:!1,track:{mediaId:"template_19_image_1",type:z.IMAGE,xPos:0,yPos:0,width:1,height:1,rotation:0,zIndex:1,originalWidthHeightRatio:1.7777777777777777,importType:_e.UNKNOWN,stats:{}}}],createdInfo:e}),ETe=e=>({id:"template_13",videoTransform:{videoRatio:he.VERTICAL,videoTransformFillType:ro.CONTAIN},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.225,xOffset:0,rotation:0,width:.9,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"GMARKET_SANS",size:"200",color:"#000000","outline-color":"#000000","outline-width":"4","outline-on":"false","background-on":"true",background:"#ffffff","background-radius":"0px","background-alpha":"0","background-padding-side":"30px","background-padding-top":"6px","background-padding-bottom":"4px"}},assetLocationMap:{},fullRangeAssets:[{editable:!0,track:{mediaId:"uc-0010-simple-textbox",type:z.WEB,xPos:.20041322314049587,yPos:.05893271461716939,width:.6,height:.12,rotation:0,zIndex:1,importType:Yt.UNKNOWN,deltas:{textarea:new Qt().insert("shorts.insert_title_part1",{size:"250",color:"#000000",font:"GMARKET_SANS","shadow-on":"false","shadow-color":"#000000","shadow-color-alpha":"1","shadow-position-x":"0","shadow-position-y":"3","shadow-blur-radius":"41"}).insert(`
1135`).insert("shorts.insert_title_part2",{size:"250",color:"#000000",font:"GMARKET_SANS","shadow-on":"false","shadow-color":"#000000","shadow-color-alpha":"1","shadow-position-x":"0","shadow-position-y":"3","shadow-blur-radius":"41"}).insert(`
1136`)},customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],enabledInlineTypes:["bold","italic","font","size","color","background","outline-color","shadow-color"],durationSeconds:0,loop:!0,stats:{},scaleFactor:1.7777777777777777}},{editable:!0,track:{mediaId:"uc-0150-search-box",type:z.WEB,xPos:.22004132231404966,yPos:.7853828306264501,width:.5599173553719008,height:.04,rotation:0,zIndex:2,importType:Yt.UNKNOWN,deltas:{textarea:new Qt().insert("shorts.search_channel",{size:"150",font:"GMARKET_SANS_MEDIUM"}).insert(`
1137`)},customAttributes:[{attributeName:"--identity-color",type:"color-hex",value:"#2e2e2e"}],enabledInlineTypes:["font","size"],durationSeconds:0,loop:!1,stats:{},scaleFactor:1.7777777777777777}}],backgroundColor:"#ffffff",createdInfo:e}),mTe=e=>({id:"template_3",videoTransform:{videoRatio:he.VERTICAL,videoTransformFillType:ro.CONTAIN},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.1375,xOffset:0,rotation:0,width:.9,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000099"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"CAFE24_CURSIVE",size:"250",color:"#ffffff","outline-color":"#000000","outline-width":"10","outline-on":"false","background-on":"true",background:"#000000","background-radius":"7px","background-alpha":"0.5","background-padding-side":"5px",italic:"true"}},assetLocationMap:{},fullRangeAssets:[{editable:!0,track:{mediaId:"uc-0010-simple-textbox",type:z.WEB,xPos:.20041322314049587,yPos:.03921113689095129,width:.6,height:.06,rotation:0,zIndex:1,importType:Yt.UNKNOWN,deltas:{textarea:new Qt().insert("shorts.channel_name",{size:"250",color:"#ffffff",font:"CAFE24_CURSIVE","shadow-on":"true","shadow-color":"#000000","shadow-color-alpha":"1","shadow-position-x":"0","shadow-position-y":"3","shadow-blur-radius":"41"}).insert(`
1138`)},customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],enabledInlineTypes:["bold","italic","font","size","color","background","outline-color","shadow-color"],durationSeconds:0,loop:!0,stats:{},scaleFactor:1.7777777777777777}}],createdInfo:e}),hTe=e=>({id:"template_6",videoTransform:{videoRatio:he.VERTICAL,videoTransformFillType:ro.CUT},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.132525,xOffset:0,rotation:0,width:.9,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"BAZZI",size:"253",color:"#373737","background-on":"true",background:"#edeef0","background-radius":"2px","background-alpha":"0.9","background-padding-side":"3px","background-padding-top":"2px","background-padding-bottom":"3px","shadow-on":"false","shadow-color":"#2ee58d","shadow-color-alpha":"1","shadow-position-x":"4","shadow-position-y":"4","shadow-blur-radius":"0","outline-on":"false","outline-color":"#000000","outline-width":"4"}},assetLocationMap:{template_6_image_1:{assetLocation:D.REMOTE,src:"https://stock-resources.vrew.ai/template-resources/images/template_6_image_1.png"},template_6_image_2:{assetLocation:D.REMOTE,src:"https://stock-resources.vrew.ai/template-resources/images/template_6_image_2.png"},template_6_image_3:{assetLocation:D.REMOTE,src:"https://stock-resources.vrew.ai/template-resources/images/template_6_image_3.png"}},fullRangeAssets:[{editable:!1,track:{mediaId:"template_6_image_1",type:z.IMAGE,xPos:0,yPos:0,width:1,height:1,rotation:0,originalWidthHeightRatio:.5625,zIndex:1,importType:_e.UNKNOWN,stats:{}}},{editable:!0,track:{mediaId:"template_6_image_2",type:z.IMAGE,xPos:.6856434406204537,yPos:.7098885793871875,width:.29207920792079206,height:.16991643454038996,rotation:0,zIndex:3,originalWidthHeightRatio:.963531669865643,importType:_e.UNKNOWN,stats:{}}},{editable:!0,track:{mediaId:"template_6_image_3",type:z.IMAGE,xPos:29723198594624037e-31,yPos:.06364902506963943,
1138width:.27722772277227725,height:.1671309192200557,rotation:0,originalWidthHeightRatio:.9312796208530806,zIndex:4,importType:_e.UNKNOWN,stats:{}}},{editable:!0,track:{mediaId:"uc-0010-simple-textbox",type:z.WEB,xPos:.13118811881188197,yPos:.022172701949860735,width:.7376237623762376,height:.08,rotation:0,zIndex:1,importType:Yt.UNKNOWN,deltas:{textarea:new Qt().insert("shorts.insert_title",{size:"237",color:"#ffffff",font:"JUA","shadow-on":"false","shadow-color":"#000000","shadow-color-alpha":"0.58","shadow-position-x":"0","shadow-position-y":"3","shadow-blur-radius":"30","background-on":"true",background:"#85c5d6","background-radius":"5px","background-alpha":"1","background-padding-side":"4px","background-padding-top":"1px","background-padding-bottom":"2px"}).insert(`
1139`)},customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],enabledInlineTypes:["bold","italic","font","size","color","background","outline-color","shadow-color"],durationSeconds:0,loop:!0,stats:{},scaleFactor:1.7777777777777777}}],createdInfo:e}),ITe=e=>({id:"template_7",videoTransform:{videoRatio:he.VERTICAL,videoTransformFillType:ro.CONTAIN},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"top",yOffset:.05,xOffset:0,rotation:0,width:.9,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"BM_DOHYEON",size:"150",color:"#ffffff","background-on":"true",background:"#000000","background-radius":"0px","background-alpha":"0.2","background-padding-side":"3px"}},assetLocationMap:{template_7_image_1:{assetLocation:D.REMOTE,src:"https://stock-resources.vrew.ai/template-resources/images/template_7_image_1.png"}},fullRangeAssets:[{editable:!0,track:{mediaId:"uc-0010-simple-textbox",type:z.WEB,xPos:.1,yPos:.06944444444444445,width:.8,height:.05,rotation:0,zIndex:2,importType:Yt.UNKNOWN,deltas:{textarea:new Qt().insert("shorts.insert_title",{size:"200",color:"#ffffff",font:"BM_DOHYEON"}).insert(`
1140`)},customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],enabledInlineTypes:["bold","italic","font","size","color","background","outline-color","shadow-color"],durationSeconds:0,loop:!0,stats:{},scaleFactor:1.7777777777777777}},{editable:!0,track:{mediaId:"template_7_image_1",type:z.IMAGE,xPos:.2044491525423736,yPos:.0882872233400402,width:.5911016949152542,height:.030952380952380953,rotation:0,zIndex:1,originalWidthHeightRatio:10.441176470588236,importType:_e.UNKNOWN,stats:{}}}],createdInfo:e}),TTe=e=>({id:"template_25",videoTransform:{videoRatio:he.VERTICAL,videoTransformFillType:ro.CONTAIN},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.141725,xOffset:0,rotation:0,width:.96,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{"outline-on":"true","shadow-on":"false",font:"OSWALD_SEMI_BOLD",size:"240",color:"#ffffff","outline-color":"#000000","outline-width":"3","shadow-color":"#000000","shadow-color-alpha":"1","shadow-position-x":"4","shadow-position-y":"6","shadow-blur-radius":"0"}},assetLocationMap:{},fullRangeAssets:[],createdInfo:e}),STe=e=>({id:"template_26",videoTransform:{videoRatio:he.VERTICAL,videoTransformFillType:ro.CONTAIN},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"top",yOffset:0,xOffset:0,rotation:0,width:.96,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"MONTSERRAT_SEMI_BOLD",size:"200",color:"#000000","outline-on":"false","outline-color":"#000000","outline-width":"7","shadow-on":"false","shadow-color":"#000000","shadow-color-alpha":"1","shadow-position-x":"4","shadow-position-y":"6","shadow-blur-radius":"0","background-on":"true",background:"#ffffff","background-radius":"8px","background-alpha":"1","background-padding-side":"9px","background-padding-top":"4px","background-padding-bottom":"4px"}},assetLocationMap:{},fullRangeAssets:[],createdInfo:e}),OTe=e=>({id:"template_27",videoTransform:{videoRatio:he.VERTICAL,videoTransformFillType:ro.CONTAIN},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.1877,xOffset:0,rotation:0,width:.96,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"POPPINS_EXTRA_BOLD",size:"250",color:"#ffffff","outline-on":"true","outline-color":"#000000","outline-width":"6","shadow-on":"false","shadow-color":"#000000","shadow-color-alpha":"1","shadow-position-x":"4","shadow-position-y":"6","shadow-blur-radius":"0",italic:"true"}},assetLocationMap:{},fullRangeAssets:[{editable:!1,track:{mediaId:"uc-0010-simple-textbox",xPos:.19940476190476203,yPos:.0721739130434783,height:.06,width:.6,rotation:0,zIndex:12,type:z.WEB,deltas:{textarea:new Qt().insert("shorts.insert_title",{size:"250",color:"#fcc800",font:"POPPINS_EXTRA_BOLD","outline-on":"true","shadow-on":"false","outline-color":"#000000","outline-width":"6","shadow-color":"#000000","shadow-color-alpha":"1","shadow-position-x":"4","shadow-position-y":"6","shadow-blur-radius":"0"}).insert(`
1141`)},loop:!0,durationSeconds:0,importType:Yt.UNKNOWN,enabledInlineTypes:["bold","italic","font","size","color","background","outline-color","shadow-color"],
1141customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],stats:{},scaleFactor:1.7777777777777777}}],createdInfo:e}),CTe=e=>({id:"template_9",videoTransform:{videoRatio:he.VERTICAL,videoTransformFillType:ro.CUT},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.132525,xOffset:0,rotation:0,width:.9,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"CAFE24_DANGJUNGHAE",size:"253",color:"#FCC700","background-on":"true",background:"#000000","background-radius":"0px","background-alpha":"0.6","background-padding-side":"3px","background-padding-top":"2px","background-padding-bottom":"3px","shadow-on":"false","shadow-color":"#000000","shadow-color-alpha":"0.6","shadow-position-x":"0","shadow-position-y":"0","shadow-blur-radius":"87","outline-on":"false","outline-color":"#000000","outline-width":"4"}},assetLocationMap:{},fullRangeAssets:[],createdInfo:e}),RTe=e=>({id:"template_23",videoTransform:{videoRatio:he.VERTICAL,videoTransformFillType:ro.CONTAIN},globalCaptionStyle:{captionStyleSetting:{mediaId:"uc-0010-simple-textbox",yAlign:"bottom",yOffset:-.1405,xOffset:0,rotation:0,width:.96,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],scaleFactor:1.7777777777777777},quillStyle:{font:"Pretendard-Vrew_700",size:"200",color:"#000000",bold:"",italic:"",strike:"",underline:"","outline-on":"false","background-on":"true","shadow-on":"false","outline-color":"#000000","outline-width":"7","secondary-outline-color":"","secondary-outline-width":"",background:"#FCC700","background-alpha":"1","background-radius":"8px","background-padding-side":"9px","background-padding-top":"4px","background-padding-bottom":"4px","shadow-color":"#000000","shadow-color-alpha":"1","shadow-position-x":"4","shadow-position-y":"6","shadow-blur-radius":"0","secondary-outline-on":"false"}},assetLocationMap:{},fullRangeAssets:[{editable:!1,track:{mediaId:"uc-0010-simple-textbox",type:z.WEB,xPos:.20023148148148154,yPos:.2619791666666667,height:.06,width:.6,rotation:0,zIndex:7,importType:Yt.UNKNOWN,deltas:{textarea:new Qt().insert("shorts.insert_title",{size:"250",color:"#ffffff",font:"Pretendard-Vrew_700"}).insert(`
1142`)},loop:!0,durationSeconds:0,enabledInlineTypes:["bold","italic","font","size","color","background","outline-color","shadow-color"],customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],stats:{},scaleFactor:1.7777777777777777}},{editable:!1,track:{mediaId:"uc-0010-simple-textbox",xPos:.2002314814814816,yPos:.09979166666666672,height:.05,width:.6,rotation:0,zIndex:10,type:z.WEB,deltas:{textarea:new Qt().insert("shorts.insert_title",{size:"200",color:"#fcc800",font:"Pretendard-Vrew_700"}).insert(`
1143`)},loop:!0,durationSeconds:0,importType:Yt.UNKNOWN,enabledInlineTypes:["bold","italic","font","size","color","background","outline-color","shadow-color"],customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:"#00000000"},{attributeName:"--textbox-align",type:"textbox-align",value:"center"}],stats:{},scaleFactor:1.7777777777777777}},{editable:!1,track:{type:z.SHAPE,mediaId:"template_23_shpae_1",xPos:.2983333333333333,yPos:.09468750000000004,height:0,width:.4,rotation:0,zIndex:8,dimensionType:1,stroke:{color:"#fcc800",width:.0075,isRounded:!1,isDashed:!1},hasHead:!1}},{editable:!1,track:{type:z.SHAPE,mediaId:"template_23_shpae_2",xPos:.2983333333333333,yPos:.1558854166666667,height:0,width:.4,rotation:0,zIndex:9,dimensionType:1,stroke:{color:"#fcc800",width:.0075,isRounded:!1,isDashed:!1},hasHead:!1}}],createdInfo:e});class ATe{stockFramePacks=[];localFramePacks=[];captionPresets=[];imageInfos=[];svgInfos=[];htmlInfos=[];mostRecentCaptionPresetId="default";stockVideos=[];fontMap;fontMapPromise;fontMapFuture=new Ns;
1143stockVideoPromise;stockVideoFuture=new Ns;localFramePackPromise;localFramePackFuture=new Ns;imageInfoPromise;imageInfoFuture=new Ns;localFramePackInitialized=!1;localFramePackPreparePromise;stockFramePackShapeInfoRegistered=!1;stockTextboxInfoRegistered=!1;blobMap=new Map;blobUrlMap=new Map;constructor(){this.fontMapPromise=this.fontMapFuture.promise(),this.stockVideoPromise=this.stockVideoFuture.promise(),this.localFramePackPromise=this.localFramePackFuture.promise(),this.imageInfoPromise=this.imageInfoFuture.promise();const t=$g();this.stockFramePacks=[oTe(t),$Ie(t),dTe(t),mTe(t),aTe(t),fTe(t),hTe(t),ITe(t),uTe(t),CTe(t),xTe(t),nTe(t),gTe(t),ETe(t),eTe(t),iTe(t),rTe(t),QIe(t),_Te(t),tTe(t),ZIe(t),lTe(t),sTe(t),RTe(t),cTe(t),TTe(t),STe(t),OTe(t),qIe(t),pTe(t)],this.captionPresets=JIe,this.prepareFontMap(),this.prepareStockVideos(),this.prepareImageInfos()}ensureFontMapInitialized=async()=>{if(!this.fontMapPromise)throw h("FramePackResourceManager.ts").error("FramePackResourceManager does not have font map promise"),new C(_.C_FRAMEPACK_GENERAL_ERROR);await this.fontMapPromise};ensureStockVideoInitialized=async()=>{if(!this.stockVideoPromise)throw h("FramePackResourceManager.ts").error("FramePackResourceManager does not have stock video promise"),new C(_.C_FRAMEPACK_GENERAL_ERROR);await this.stockVideoPromise};ensureImageInfoInitialized=async()=>{if(!this.imageInfoPromise)throw h("FramePackResourceManager.ts").error("FramePackResourceManager does not have image info promise"),new C(_.C_FRAMEPACK_GENERAL_ERROR);await this.imageInfoPromise};ensureLocalFramePackInitialized=async()=>{if(!this.localFramePackPromise)throw h("FramePackResourceManager.ts").error("FramePackResourceManager does not have local framepack promise"),new C(_.C_FRAMEPACK_GENERAL_ERROR)};registerVideoThumbnail=async(t,o)=>{const r=await fetch(t).then(i=>i.blob());this.blobMap.set(o,r);const n={type:"Image",mediaId:o,sourceOrigin:tt.USER,fileLocation:D.IN_MEMORY,isTransparent:!1,fileSize:r.size,name:o+"."+j_},a=this.imageInfos.findIndex(i=>i.mediaId===o);a!==-1&&this.imageInfos.splice(a,1),this.imageInfos.push(n)};getStockFramePacks=t=>this.stockFramePacks.map(o=>BIe(o,this.fontMap)).map(o=>this.fontMap===void 0?o:YIe(o,t,this.fontMap));getLocalFramePacks=()=>[...this.localFramePacks];upsertLocalFramePack=t=>{const o=this.localFramePacks.findIndex(r=>
1143r.id===t.id);if(o!==-1){this.localFramePacks[o]=t;return}this.localFramePacks.push(t)};isStockFramePack=t=>this.stockFramePacks.map(r=>r.id).includes(t);deleteLocalFramePack=async t=>{await Ue().deleteFramePackFile({id:t});const o=this.localFramePacks.findIndex(r=>r.id===t);o!==-1&&this.localFramePacks.splice(o,1)};getCaptionPresets=t=>{const o=this.fontMap;return o?this.captionPresets.map(r=>({...r,globalCaptionStyleSetting:Zj(r.globalCaptionStyleSetting,t,o)})):this.captionPresets};registerImageBlob=({blob:t,isTransparent:o})=>{const r=qe.v4(),n={type:"Image",mediaId:r,sourceOrigin:tt.USER,fileLocation:D.IN_MEMORY,isTransparent:o,fileSize:t.size,name:r+"."+j_};return this.imageInfos.push(n),this.blobMap.set(r,t),n};registerImageFiles=async t=>{const o=await rs(t,M2),r=o.map(this.registerImageBlob);return await rs(r,async a=>{const{mediaId:i}=a,s=this.blobMap.get(i);if(s===void 0){const l="[registerImageFiles] Blob not found for mediaId: "+i;throw h("FramePackResourceManager.ts").error(l),new C(_.C_MEDIA_BLOB_LOST,{},l)}const x=URL.createObjectURL(s),c=await L2(x);return URL.revokeObjectURL(x),{type:Pu.Image,mediaId:i,aspectRatio:c}})};getImageFileInfo=t=>{const o=this.imageInfos.find(n=>n.mediaId===t),r=this.blobMap.get(t);if(o&&r)return{imageInfo:o,blob:r}};getImageFileSrcUrl=t=>{const o=this.blobUrlMap.get(t);if(o)return o;const r=this.blobMap.get(t);if(r){const n=URL.createObjectURL(r);return this.blobUrlMap.set(t,n),n}};registerShapeInfo=(t,o)=>{const r=this.svgInfos.map(n=>n.mediaId);this.svgInfos.forEach(n=>{r.includes(n.mediaId)}),this.svgInfos.push(t),this.blobMap.set(t.mediaId,o)};registerShapeInfos=(t,o)=>{t.forEach(r=>{this.registerShapeInfo(r,o[r.mediaId])})};getShapeInfo=t=>{const o=this.svgInfos.find(n=>n.mediaId===t),r=this.blobMap.get(t);if(o&&r)return{shapeInfo:o,blob:r}};registerTextboxInfo=(t,o)=>{const r=this.htmlInfos.map(n=>n.mediaId);this.htmlInfos.forEach(n=>{r.includes(n.mediaId)}),this.htmlInfos.push(t),this.blobMap.set(t.mediaId,o)};registerTextboxInfos=(t,o)=>{t.forEach(r=>{this.registerTextboxInfo(r,o[r.mediaId])})};getTextboxInfo=t=>{const o=this.htmlInfos.find(n=>n.mediaId===t),r=this.blobMap.get(t);if(o&&r)return{textboxInfo:o,blob:r}};notifyCaptionPresetSelected=t=>{this.mostRecentCaptionPresetId=t};getMostRecentCaptionPresetId=()=>this.mostRecentCaptionPresetId;getStockVideos=()=>this.stockVideos;saveLocalFramePack=async(t,o)=>{await GIe(t,o),this.upsertLocalFramePack(t)};loadLocalFramePackByPath=async t=>{const o=await HIe(t);if(o===void 0)return;const{framePack:r,blobs:n}=o;await this.loadLocalFramePack({framePack:r,blobs:n})};loadLocalFramePack=async({framePack:t,blobs:o})=>{await Promise.all(Object.entries(o).map(async([r,n])=>{const{blob:a,mimeType:i}=n;if(i==="image/png"){const s=await PN(a),x={mediaId:r,type:"Image",sourceOrigin:tt.USER,fileLocation:D.IN_MEMORY,name:r+"."+j_,isTransparent:s,fileSize:a.size};!this.imageInfos.find(c=>c.mediaId===r)&&this.imageInfos.push(x)}else if(i==="application/xml"){const s={type:"Svg",rawSvg:await a.text(),mediaId:r,sourceOrigin:tt.USER,fileLocation:D.IN_MEMORY,name:r+"."+ER,fileSize:a.size};!this.svgInfos.find(x=>x.mediaId===r)&&this.svgInfos.push(s)}else if(i==="text/html"){const s={type:"Html",rawHtml:await a.text(),mediaId:r,sourceOrigin:tt.USER,fileLocation:D.IN_MEMORY,fileSize:a.size,name:r+"."+_R};!this.htmlInfos.find(x=>x.mediaId===r)&&this.htmlInfos.push(s)}h("FramePackResourceManager.ts").info("Loaded local framepack blob for mediaId: "+r+", size: "+a.size),this.blobMap.set(r,a)})),this.upsertLocalFramePack(t)};prepareLocalFramePacks=async()=>{if(!this.localFramePackInitialized){if(this.localFramePackPreparePromise)return this.localFramePackPreparePromise;this.localFramePackPreparePromise=(async()=>{const t=await jIe();await Promise.all(t.map(async o=>{try{await this.loadLocalFramePack(o)}catch(r){h("FramePackResourceManager.ts").error("Failed to load local framepack "+o.framePack.id+": "+P(r))}})),this.localFramePackFuture.resolve(),this.localFramePackInitialized=!0})();try{await this.localFramePackPreparePromise}catch(t){throw this.localFramePackPreparePromise=void 0,t}}};registerCurrentProjectAssets=async t=>{const o=h("FramePackResourceManager.ts");for(const r of Object.values(t)){const{track:n}=r;try{const a=Vi(n.mediaId),i=await En(n.mediaId);if(!a||!i){o.warn("[registerCurrentProjectAssets] FileInfo or blob not found for mediaId: "+n.mediaId);continue}switch(a.type){case"Image":{!this.imageInfos.find(s=>s.mediaId===n.mediaId)&&(this.imageInfos.push(a),this.blobMap.set(n.mediaId,i),o.info("[registerCurrentProjectAssets] Registered image asset: "+n.mediaId));break}case"Html":{!this.htmlInfos.find(s=>s.mediaId===n.mediaId)&&(this.htmlInfos.push(a),this.blobMap.set(n.mediaId,i),o.info("[registerCurrentProjectAssets] Registered web asset: "+n.mediaId));break}case"Svg":{!this.svgInfos.find(s=>s.mediaId===n.mediaId)&&(this.svgInfos.push(a),this.blobMap.set(n.mediaId,i),o.info("[registerCurrentProjectAssets] Registered shape asset: "+n.mediaId));break}default:o.error("[registerCurrentProjectAssets] Unsupported file type: "+a.type+" for mediaId: "+n.mediaId);break}}catch(a){o.error("[registerCurrentProjectAssets] Failed to register asset "+n.mediaId+":",P(a))}}};registerStockFramePackShapeInfo=()=>
1143{if(this.stockFramePackShapeInfoRegistered)return;const t=$e().getStockShapeInfo()?.templates;if(!t)return;const o=[],r=this.stockFramePacks.flatMap(a=>a.fullRangeAssets),n={};for(const a of r){const i={...a.track,trackId:H4()};if(f0(i)&&i2(i))try{const s=i,x=t?.find(d=>d.shapeKey===s.shapeSource)?.template;if(!x){const d="No matching shape framepack found. shapeType:"+s.shapeType;throw h("FramePackResourceManager.ts").error(d),new Error(d)}const c=new Blob([x]);n[s.mediaId]=c;const l={type:"Svg",rawSvg:x,mediaId:s.mediaId,sourceOrigin:tt.VREW_RESOURCE,fileLocation:D.IN_MEMORY,fileSize:c.size,name:s.mediaId+"."+ER};o.push(l)}catch(s){h("FramePackResourceManager.ts").error("Failed to register stock framepack shape. asset:"+i.shapeSource+", mediaId:"+i.mediaId,P(s));return}}this.registerShapeInfos(o,n),this.stockFramePackShapeInfoRegistered=!0};registerStockTextboxInfo=()=>{if(this.stockTextboxInfoRegistered)return;const t=(s,x)=>{const c=new Blob([x]);return{type:"Html",rawHtml:x,mediaId:s,sourceOrigin:tt.VREW_RESOURCE,fileLocation:D.IN_MEMORY,fileSize:c.size,name:s+"."+_R}},o={},r=t(Ao,Qc());o[r.mediaId]=new Blob([Qc()]);const n=$e().getWebAssetsSync()?.content;if(!n)return;const a=n.map(s=>t(s.mediaId,s.html));a.forEach(s=>{o[s.mediaId]=new Blob([s.rawHtml])});const i=[r,...a];this.registerTextboxInfos(i,o),this.stockTextboxInfoRegistered=!0};prepareFontMap=async()=>{this.fontMap=(await $e().getWebAssets())?.textboxFonts,this.fontMapFuture.resolve()};prepareStockVideos=async()=>{const t=fr.level===Xr.Release?[{remotePath:"https://stock-resources.vrew.ai/template-resources/videos/shorts_stock_video_1.mp4",stockVideoLabel:"stock_video_1"},{remotePath:"https://stock-resources.vrew.ai/template-resources/videos/shorts_stock_video_2.mp4",stockVideoLabel:"stock_video_2"},{remotePath:"https://stock-resources.vrew.ai/template-resources/videos/shorts_stock_video_3.mp4",stockVideoLabel:"stock_video_3"},{remotePath:"https://stock-resources.vrew.ai/template-resources/videos/shorts_stock_video_4.mp4",stockVideoLabel:"stock_video_4"}]:[{remotePath:"https://stock-resources-test.vrew.ai/template-resources/videos/shorts_stock_video_1.mp4",stockVideoLabel:"stock_video_1"},{remotePath:"https://stock-resources-test.vrew.ai/template-resources/videos/shorts_stock_video_2.mp4",stockVideoLabel:"stock_video_2"},{remotePath:"https://stock-resources-test.vrew.ai/template-resources/videos/shorts_stock_video_3.mp4",stockVideoLabel:"stock_video_3"},{remotePath:"https://stock-resources-test.vrew.ai/template-resources/videos/shorts_stock_video_4.mp4",stockVideoLabel:"stock_video_4"}],o=await rs(t,zIe);this.stockVideos=o,this.stockVideoFuture.resolve(),Promise.all(o.map(r=>this.registerVideoThumbnail(r.videoThumbnailPath,r.thumbnailImageMediaId))).catch(r=>{h("FramePackResourceManager.ts").error("Failed to register stock video thumbnails in background",r)})};prepareImageInfos=async()=>{const t=this.stockFramePacks.reduce((r,n)=>({...r,...n.assetLocationMap}),{}),o=await Promise.all(Object.entries(t).filter(([,r])=>hEe(r)).map(async([r,n])=>{const a=n,{src:i}=a,s=await fetch(i).then(c=>c.blob());return this.blobMap.set(r,s),{type:"Image",mediaId:r,sourceOrigin:tt.VREW_RESOURCE,fileLocation:D.IN_MEMORY,isTransparent:!1,fileSize:s.size,name:r+"."+j_}}));this.imageInfos=o,this.imageInfoFuture.resolve()}}let qm;const ei=()=>(!qm&&yTe(),qm),yTe=()=>{!qm&&(qm=new ATe)},vTe="left",wTe=Ve().get(Ie.PREVIEW_LOCATION_NAME,vTe),$j=In({name:"previewLocation",initialState:wTe,reducers:{setPreviewLocation:(e,t)=>t.payload}}),cit=$j.reducer,lit=e=>ja(e).previewLocation,dit=e=>t=>{Ve().set(Ie.PREVIEW_LOCATION_NAME,e),t($j.actions.setPreviewLocation(e))};var NTe=(e=>(e[e.DELETE=0]="DELETE",e[e.INSERT=1]="INSERT",e))(NTe||{}),Pt=(e=>(e.IMAGE="image",e.VIDEO="video",e.GIF="gif",e))(Pt||{}),kp=(e=>(e.PROJECT_RANGE="project_range",e.SCENE_RANGE="scene_range",e.SELECTED_CLIP_RANGE="selected_clip_range",e.DIRECT_INPUT="direct_input",e))(kp||{}),zE=(e=>(e.CLIP_THUMBNAIL="clip_thumbnail",e.FRAMEPACK_THUMBNAIL="template_thumbnail",e.GENERATED_THUMBNAIL="generated_thumbnail",e))(zE||{});const iD={pca_components:[[-.0128709077835083,-.12074575573205948,-.015878021717071533,-.007974102161824703,-.050652679055929184,-.0180387943983078,-.013071435503661633,-.13414767384529114,-.03348022326827049,.0017629569629207253,.2668817341327667,.0528225339949131,-.0004937935154885054,.2777540981769562,.08187136799097061,-.022464212030172348,-.1155005469918251,-.013133301399
114364819,-.029579194262623787,-.10006457567214966,-.009745601564645767,-.027226122096180916,-.0789930671453476,.0061121052131056786,-.002508891746401787,-.008385068736970425,.031009405851364136,.004951528739184141,-.005175005178898573,.03476593270897865,-.009014194831252098,-.08908531069755554,-.005912830587476492,-.016932981088757515,-.11566466093063354,-.022059878334403038,-.018211612477898598,-.13165199756622314,-.03056688793003559,-.020749522373080254,.2610805034637451,.08235978335142136,-.008513947017490864,.2543274164199829,.05572299286723137,.0003104457282461226,.1541983187198639,.05750920623540878,-.021136602386832237,.1427338421344757,.07299917191267014,.006650953553617001,.08977392315864563,.0518740676343441,.033780988305807114,-.02260659635066986,-.07036266475915909,-.013316836208105087,.06834469735622406,.05249062180519104,.02120497077703476,-.015759719535708427,.015406305901706219,-.006757515482604504,.21454621851444244,.05627594515681267,-.026583079248666763,.21341784298419952,.08227939158678055,-.018881116062402725,-.050238046795129776,.018934672698378563,-.008889405988156796,-.05288409814238548,.013534986414015293,.00043688048026524484,-.11284169554710388,-.015112859196960926,.012605500407516956,-.09363077580928802,-.01338656060397625,.014618877321481705,-.07138948887586594,.0012965238420292735,.0008894251077435911,.0037390815559774637,.024313298985362053,-.005211997777223587,.006147121079266071,.028875941410660744,-.003939536865800619,-.08159893751144409,-.010206874459981918,-.0011733255814760923,-.11089680343866348,-.025397399440407753,-.003809010609984398,-.12968452274799347,-.03265208750963211,.021603984758257866,.2601274251937866,.079869844019413,.013869907706975937,.2565838694572449,.05337802320718765,.005960467271506786,.16160373389720917,.053097255527973175,.02230386808514595,.14495699107646942,.0683596283197403,-.0025155760813504457,.0998845249414444,.04678293690085411,-.019036656245589256,-.008962038904428482,-.07594752311706543,.01343485713005066,.07615147531032562,.04680456966161728,-.020274505019187927,-.004146712366491556,.010527350008487701,.01288839802145958,.21878616511821747,.052643127739429474,.027821645140647888,.21213920414447784,.0782494843006134,.01264625508338213,-.039987046271562576,.012994782999157906,.0037884158082306385,-.04412011429667473,.008281922899186611],[-.0063798232004
114304644,-.01309877634048462,.05646371841430664,.0018694046884775162,.06839350610971451,.006022223271429539,-.007160169538110495,-.0713622197508812,.06153738871216774,-.005373496096581221,-.018364794552326202,.05846092477440834,-.010223372839391232,-.09170448780059814,.04434839263558388,-.0413905568420887,-.014559827744960785,.05258520320057869,-.07115630060434341,-.04899236559867859,.06435961276292801,-.09562669694423676,-.08778435736894608,.08645286411046982,-.13875435292720795,-.1489492654800415,.12244963645935059,-.1372697949409485,-.13516992330551147,.12353949248790741,-.10744155943393707,-.1047390028834343,.09438451379537582,-.08070283383131027,-.08802595734596252,.07840245217084885,-.046833913773298264,-.07518602907657623,.066166952252388,-.035438213497400284,-.09243343025445938,.052689481526613235,-.04297179728746414,-.022592637687921524,.06400806456804276,-.10216512531042099,-.06248437613248825,.09415832161903381,-.0876268818974495,-.10005063563585281,.09878416359424591,-.11970186233520508,-.08983369916677475,.11392803490161896,-.038970738649368286,-.005089223384857178,.07492146641016006,-.11402525007724762,-.11998716741800308,.12233278155326843,-.01573428325355053,-.003945130854845047,.12411192059516907,-.07515611499547958,-.03852825611829758,.07717148959636688,-.060284458100795746,-.09257648140192032,.07796259224414825,-.11729057133197784,-.12105318903923035,.10941951721906662,-.12699586153030396,-.12030649185180664,.11191880702972412,.030839893966913223,-.013002809137105942,.0513041689991951,.06439222395420074,-.04546451196074486,.062099821865558624,.09213227033615112,-.08323224633932114,.08297370374202728,.14429782330989838,-.14390061795711517,.11726979911327362,.1432133913040161,-.13133293390274048,.11884425580501556,.10452821105718613,-.10253684222698212,.09089861810207367,.07255725562572479,-.0865323543548584,.07587643712759018,.03538687527179718,-.07474975287914276,.06476955115795135,.017168352380394936,-.0916065126657486,.05076519399881363,.0341511145234108,-.020962757989764214,.06205137073993683,.1015084758400917,-.058823294937610626,.09053828567266464,.08222788572311401,-.09701261669397354,.09492914378643036,.12327034771442413,-.08583259582519531,.10961412638425827,.03442173823714256,-.006510809063911438,.06813889741897583,.11522144079208374,-.11489816755056381,.1176142692565918,.009601011872291565,-.0074887387454509735,.11932991445064545,.07004101574420929,-.03547118976712227,.0742993950843811,.04723082482814789,-.0912141501903534,.07483651489019394,.11877620220184326,-.1154792308807373,.10496987402439117,.12988635897636414,-.11743278801441193,.10753386467695236],[-.017140869051218033,-.15928012132644653,-.07686054706573486,.0001370204845443368,-.05529005825519562,-.04593568667769432,-.016591358929872513,-.19512082636356354,-.09485245496034622,-.007154800929129124,-.04282404109835625,-.10202476382255554,-.007002350874245167,-.06747892498970032,-.14140525460243225,-.0370371975004673,-.1524399071931839,-.0746990367770195,-.06247120350599289,-.12727409601211548,-.07763856649398804,-.07781265676021576,-.0907612070441246,-.08035635948181152,-.08006060123443604,-.006405867636203766,-.09361698478460312,-.07189084589481354,-.02255024015903473,-.09279970079660416,-.058932866901159286,-.11861421167850494,-.09051771461963654,-.04699283093214035,-.1593189388513565,-.09123852103948593,-.031789228320121765,-.18571344017982483,-.09333834052085876,-.023055676370859146,-.05833151564002037,-.13872085511684418,-.02323438785970211,-.0375315360724926,-.10020317137241364,-.05288836732506752,-.021381236612796783,-.09583746641874313,-.060575470328330994,-.0132431760430336,-.11968032270669937,-.06268513202667236,-.017388097941875458,-.09436751157045364,-.03580301254987717,.16807645559310913,-.03511933982372284,-.0742882490158081,-.004878602921962738,-.10704779624938965,-.025495022535324097,.10768899321556091,-.1800524890422821,-.03833572566509247,-.02992628701031208,-.09763696789741516,-.041243262588977814,-.036100588738918304,-.1290673166513443,-.08706121146678925,-.05018845573067665,-.08466094732284546,-.07075032591819763,-.0740617960691452,-.09115094691514969,.005518857389688492,-.1524980515241623,-.07495014369487762,.03844849765300751,-.12800201773643494,-.07806773483753204,.06133608892560005,-.09060805290937424,-.08072175085544586,.07781696319580078,-.0019365251064300537,-.09310173988342285,.06951095163822174,-.018494054675102234,-.09303587675094604,.04148832708597183,-.11755026876926422,-.0912545770406723,.022724155336618423,-.15937748551368713,-.09216661751270294,.002041429281234741,-.1859932839870453,-.09406017512083054,.01080130971968174,-.05949237942695618,-.13965854048728943,.010936209000647068,-.036800991743803024,-.1013488844037056,.04667311906814575,-.018100885674357414,-.09681811928749084,.05402223393321037,-.012452010065317154,-.12057790160179138,.058603234589099884,-.013283837586641312,-.09490535408258438,.030791528522968292,.16137279570102692,-.023501697927713394,.0703941285610199,-.002239316701889038,-.10675759613513947,.019686592742800713,.09973877668380737,-.175897479057312,.029210828244686127,-.02825971134006977,-.09885583817958832,.031605783849954605,-.037362225353717804,-.130324125289917,.07805033028125763,-.0485038198530674,-.08420907706022263,.06116529181599617,-.07252287864685059,-.09197830408811569],[-.13287320733070374,.008035201579332352,.00610443577170372,-.009856760501861572,.004494979977607727,.004279162734746933,-.14084219932556152,.02836835
vendor: 5,100 bytes, line 1143
11437568979263,.00733798136934638,-.15445078909397125,-.007554484065622091,-7689273479627445e-20,-.1827513873577118,.008980602957308292,-.0038534977938979864,-.1236744076013565,-.024317024275660515,.0014241047902032733,-.11826108396053314,-.057352058589458466,-.0027867096941918135,-.11315901577472687,-.0785161554813385,-.007080368231981993,-.10126829147338867,-.10386905074119568,-.013388325460255146,-.10295268148183823,-.09427260607481003,-.011606669053435326,-.1158885732293129,-.05145786702632904,-.004018372856080532,-.12412378937005997,-.02558266744017601,-9341669647255912e-20,-.13259536027908325,.0023077114019542933,.0035379210021346807,-.1728459894657135,-.020706648007035255,-.007698887959122658,-.14524438977241516,-.031634118407964706,-.004205795936286449,-.12261802703142166,-.06780707091093063,-.009700736030936241,-.13423387706279755,-.07411406934261322,-.012263990007340908,-.11287291347980499,-.07957670837640762,-.01175994798541069,-.05373792722821236,-.18482498824596405,-.027493765577673912,-.11615151911973953,-.09041432291269302,-.012868847697973251,-.1565992832183838,-.09797531366348267,-.018933214247226715,-.13436689972877502,-.05174730345606804,-.007177789229899645,-.1556517630815506,-.047509223222732544,-.010959025472402573,-.10613109171390533,-.09231157600879669,-.010728640481829643,-.10751505941152573,-.07330384850502014,-.008370630443096161,-.12385179847478867,.03414216265082359,.008830278180539608,-.11754123866558075,.06430083513259888,.012406443245708942,-.11417955160140991,.08013992756605148,.013772080652415752,-.10847894102334976,.09944646060466766,.014735697768628597,-.10859392583370209,.09191413223743439,.012555108405649662,-.11715484410524368,.07944174855947495,.013251335360109806,-.12528112530708313,.06825527548789978,.01288565807044506,-.13364265859127045,.0513412207365036,.010890110395848751,-.1746029555797577,.03921816498041153,22099782654549927e-21,-.1475563794374466,.016880972310900688,.0034046166110783815,-.1249513253569603,.05996455252170563,.007532945834100246,-.139351487159729,.07749121636152267,.006640593986958265,-.11633994430303574,.07498890161514282,.00958514865487814,-.07653062045574188,.17866802215576172,.02500545047223568,-.1231895163655281,.0926218032836914,.010643082670867443,-.16038690507411957,.1133430004119873,.015708453953266144,-.1366836428642273,.039795201271772385,.005911686923354864,-.15882840752601624,.06253866106271744,.0036844443529844284,-.11089225113391876,.09296218305826187,.014602044597268105,-.1116957888007164,.08574946224689484,.013162665069103241],[-.004039741586893797,-.1697598546743393,-.013228880241513252,-.0017532706260681152,-.03381654620170593,-.02260589599609375,.002576887607574463,-.10107731074094772,-.02966020442545414,-.01625511795282364,-.13407914340496063,.056909289211034775,-.012203613296151161,.024783223867416382,.07518505305051804,.013433519750833511,-.16773299872875214,-.008945655077695847,.04107855260372162,-.14608438313007355,-.0038928729481995106,.08147162944078445,-.10869113355875015,.01528849732130766,.16998377442359924,-.06594732403755188,.04468344897031784,.18273459374904633,-.0740576833486557,.04856736585497856,.13468874990940094,-.09129743278026581,.0036043445579707623,.0862647294998169,-.10397283732891083,-.01500540878623724,.04188533127307892,-.1074712872505188,-.025928320363163948,-.004352309741079807,.005323552526533604,.07770825177431107,.02626066468656063,-.13928554952144623,.06134575977921486,.1253843754529953,-.13419723510742188,.06703547388315201,.07313564419746399,-.06269685178995132,.07776293158531189,.16159111261367798,-.11947332322597504,.06348450481891632,-.03205983713269234,.07210239768028259,-.07464296370744705,.12460554391145706,-.08450549840927124,.06316517293453217,.005239034071564674,.14075380563735962,.013362857513129711,.07430047541856766,-.13997091352939606,.06367456167936325,.022124435752630234,-.03233318030834198,.08240026980638504,.12863440811634064,-.08636834472417831,.03128278627991676,.17040978372097015,-.07822854071855545,.02499995194375515,-.019633639603853226,-.15797047317028046,-.011107247322797775,-.04168577119708061,-.12718886137008667,-.009565127082169056,-.07871652394533157,-.08715472370386124,.0078524649143219,-.16952168941497803,-.05449387803673744,.03490747511386871,-.18440084159374237,-.059221360832452774,.0395212322473526,-.12456602603197098,-.07452981173992157,-.0032575884833931923,-.07577699422836304,-.0896182730793953,-.020452531054615974,-.03305691480636597,-.10073928534984589,-.0288825836032629,-.013326659798622131,.00858569797128439,.07371780276298523,-.05194591358304024,-.13557089865207672,.05748501047492027,-.13602124154567719,-.12364205718040466,.06003715842962265,-.08047828823328018,-.056792184710502625,.07002495974302292,-.1646149456501007,-.10573217272758484,.05538297817111015,.06226763874292374,.05088546872138977,-.05844104290008545,-.1283487230539322,-.08451741933822632,.05465147644281387,.0514661930501461,.11454755812883377,.011811397969722748,-.09252794086933136,-.131890207529068,.05772053450345993,-.034842927008867264,-.027172157540917397,.07555194199085236,-.12328361
1143719846725,-.06855282187461853,.02292032167315483,-.16185013949871063,-.06187603250145912,.016703777015209198],[.09756766259670258,-.007347025442868471,.0024322145618498325,.11276386678218842,-.003566920757293701,-.004347525537014008,.06981305778026581,-.01874440908432007,-.0017845346592366695,.07724373042583466,.011318221688270569,.006820685230195522,.07187431305646896,-.01644359529018402,-.0005084183067083359,.08879092335700989,-.002732314169406891,-.03341563791036606,.057861246168613434,.01098494790494442,-.0729035884141922,.02791711315512657,.017413809895515442,-.09770037233829498,-.029922369867563248,.009059712290763855,-.1290828287601471,-.028306376188993454,.009507782757282257,-.10774718225002289,.008363877423107624,.0009433329105377197,-.07887418568134308,.03316263109445572,-.006895590573549271,-.060999639332294464,.05385209992527962,-.014396222308278084,-.036002784967422485,.05959306284785271,-.012879244983196259,-.035001639276742935,.06111368536949158,.015000037848949432,-.027320658788084984,.011716052889823914,.013124017976224422,-.07228706777095795,.014121683314442635,.007787689566612244,-.0837811678647995,-.010039068758487701,.009301548823714256,-.09251805394887924,-.33267003297805786,-.0372813381254673,-.37120121717453003,-.010736273601651192,.006473235785961151,-.1060624048113823,-.18559446930885315,.057316020131111145,-.20855943858623505,.0385047122836113,.015101402997970581,-.053039826452732086,.03995319455862045,-.008501417934894562,-.06472194939851761,-.004053891636431217,.011492785066366196,-.11780865490436554,-.015091466717422009,.00702337920665741,-.09697577357292175,.0838504284620285,-.0071280598640441895,.04060801863670349,.04878411442041397,-.013591781258583069,.07943415641784668,.016856620088219643,-.005789615213871002,.11099575459957123,-.0397147536277771,-.00035525811836123466,.14946457743644714,-.035645075142383575,-.0022200439125299454,.13100019097328186,.0032848333939909935,-.015377060510218143,.0879802405834198,.03041023388504982,-.01864943653345108,.06301257759332657,.053025439381599426,-.01976761966943741,.03342750295996666,.055531784892082214,-.02154659479856491,.03690747171640396,.0618336983025074,.009577922523021698,.042599327862262726,.008168634958565235,.00088471919298172,.09430883824825287,.004186544567346573,-.0027664508670568466,.10241258144378662,-.014756583608686924,-.0015195980668067932,.11697635799646378,-.3432241976261139,.05598350614309311,.3082919120788574,-.020496878772974014,-.00967415887862444,.12857435643672943,-.18870088458061218,.004898101091384888,.17346040904521942,.03786235302686691,.005883030593395233,.07140398025512695,.03187114745378494,-.01956821233034134,.07722634822130203,-.012579236179590225,-.006286803632974625,.13683006167411804,-.01859850063920021,-.010309739969670773,.11289789527654648]],pca_mean:[.00021476468828041106,.02903646230697632,-.012311046943068504,.0004887791583314538,.013599908910691738,-.012745254673063755,.0002943448780570179,.03459400311112404,-.008005731739103794,.00044926611008122563,.03999805077910423,-.006790013052523136,.0006092285038903356,.04990217089653015,-.007279739715158939,-.00519487913697958,.027826178818941116,-.011836952529847622,-.010162796825170517,.029919972643256187,-.009081742726266384,-.013452491723001003,.03200220316648483,-.005433679558336735,-.01719215326011181,.0359281525015831,.002622970612719655,-.015455331653356552,.035933248698711395,.0012650907738134265,-.010677986778318882,.0346568264067173,-.0035023277159780264,-.007717697881162167,.03429150581359863,-.005720977205783129,-.004033007193356752,.034313153475522995,-.007451949175447226,-.005111115053296089,.04923039674758911,-.007021571975201368,-.003954041283577681,.039507895708084106,-.0062467074021697044,-.010615367442369461,.037846241146326065,-.00257647642865777,-.013478301465511322,.04234714061021805,-.002867866540327668,-.012841464951634407,.03711554780602455,-.00024684052914381027,-.04813593626022339,.017877060920000076,.04562690109014511,-.015650881454348564,.0391172394156456,.00021243299124762416,-.027440520003437996,.06335633993148804,.019902942702174187,-.007645012345165014,.03868108242750168,-.004625384230166674,-.009891011752188206,.04655059054493904,-.005139196757227182,-.015695370733737946,.034021493047475815,-.001396322506479919,-.013010247610509396,.035235848277807236,-.0008269206737168133,.005639014299958944,.027524221688508987,-.01173639576882124,.010704065673053265,.0295246709138155,-.008831750601530075,.013964194804430008,.03136230632662773,-.005080748349428177,.017883773893117905,.035053398460149765,.0031051309779286385,.01614135503768921,.035142846405506134,.0016932622529566288,.011330710723996162,.034195609390735626,-.0032168147154152393,.008345038630068302,.0339425653219223,-.0055246190167963505,.00468279467895627,.03413274139165878,-.0073548280633986,.006322581321001053,.0489763543009758,-.006909849122166634,.004877979401499033,.03931109234690666,-.00614460464566946,.011435301043093204,.03735421970486641,-.002290918491780758,.014363421127200127,.0415932759642601,-.0025278287939727306,.013556819409132004,.03646466135978699,.00011688155791489407,.047476381063461304,.015877900645136833,.04677097126841545,.016423193737864494,.03846253082156181,.0006226558471098542,.028500979766249657,.06260653585195541,.020776210352778435,.008505121804773808,.03829759731888771,-.004407508298754692,.011043031699955463,.04601622372865677,-.00490525970235467,.01627497375011444,.033239707350730896,-.000939037068746984,.013677963055670261,.034644078463315964,-.0004540549707598984]};function GO(e,t){return Math.sqrt((e.x-t.x)*(e.x-t.x)+(e.y-t.y)*(e.y-t.y))}class ef{static lerp(t,o,r){return t+(o-t)*r}static random(t,o){return t+Math.random()*(o-t)}static smoothStep(t,o,r){const n=Math.max(0,Math.min(1,(t-o)/(r-o)));return n*n*(3-2*n)}static getTransformFunc(t,o,r){const n=o.subtract(t),a=n.normalize(),i=n.length,s=a.clone();s.angle+=90;const x=r.subtract(t),c=x.dot(a),l=x.dot(s);return(d,u)=>{const p=u.subtract(d);if(p.length===0)return d.clone();const f=p.length/i,E=p.normalize(),T=E.clone();return T.angle+=90,d.add(E.multiply(c*f)).add(T.multiply(l*f))}}static getClosestPointOnSegment(t,o,r){const n=o.subtract(t),a=r.subtract(t).dot(n)/n.dot(n);return a>=1?o.clone():a<=0?t.clone():t.add(n.multiply(a))}static isCollinear(t,o,r=.01){let n=!1;if(t&&o){const a=t.normalize(),i=o.normalize();n=Math.abs(a.dot(i))>1-r}return n}static gaussian(t,o){let r=0,n=0;for(;r===0;)r=Math.random();for(;n===0;)n=Math.random();
1143return Math.sqrt(-2*Math.log(r))*Math.cos(2*Math.PI*n)*o+t}static clamp(t,o,r){return Math.min(Math.max(t,o),r)}static multiplyMatrices(t,o){const r=[];for(let n=0;n<t.length;n++){r[n]=[];for(let a=0;a<o[0].length;a++){let i=0;for(let s=0;s<t[0].length;s++)i+=t[n][s]*o[s][a];r[n][a]=i}}return r}static getRigidTransform(t,o){const r=[[t[0][0],-1*t[0][1],1,0],[t[0][1],t[0][0],0,1],[t[1][0],-1*t[1][1],1,0],[t[1][1],t[1][0],0,1]],n=Gb(o,[4,1]),a=V9(r);return Wb(a,n)}static decodePCA(t){const o=G9(t)[0];t=Wb(t,iD.pca_components);for(let r=0;r<t.length;r++)t[r]=W9(t[r],iD.pca_mean);return Gb(t,[o,45,3])}static selectSegments(t,o,r,n){const a=[];let i=0;for(let c=0;c<o;c++){const l=ef.gaussian(1,n);a.push(l),i+=l}for(let c=0;c<a.length;c++)a[c]=a[c]/i;let s=0;const x=[];for(let c=0;c<o;c++){const l=s,d=s+a[c]*ef.clamp(ef.gaussian(1,r)*t,0,1);x.push([l,d]),s+=a[c]}return x}static isLeft(t,o,r){return(o.x-t.x)*(r.y-t.y)-(o.y-t.y)*(r.x-t.x)>0}static packCircles(t,o,r,n,a,i=10){let s=[],x=0;for(;s.length<r&&x<i;){for(;s.length<r;){const u={x:o*(Math.random()*2-1)+t.x,y:o*(Math.random()*2-1)+t.y};GO(u,t)>o||s.some(p=>GO(p,u)<p.radius)||s.push({c:u,r:0})}const c=20,l=(u,p)=>{const f=GO(u.c,p.c);return f<u.r+p.r&&f>Math.abs(u.r-p.r)},d={c:t,r:o};for(let u=0;u<c;u++){let p=!1;if(s.forEach(f=>{!s.some(T=>f!==T&&(l(f,T)||l(f,d)))&&f.r<n&&(f.r+=n/c,p=!0)}),!p)break}s=s.filter(u=>u.r>=a),x++}return s}}const PTe=/^image\//,sD=["No valid data on clipboard."],L2=async e=>{const t=await NN(e);return t.height?t.width/t.height:1},bTe=async e=>{const t=await NN(e);return t.height?{width:t.width,height:t.height}:{width:100,height:100}},NN=async e=>new Promise(t=>{const o=new Image;o.onload=()=>{t(o)},o.onerror=r=>{h("image.ts").error("Loading "+e+" failed : "+JSON.stringify(r)),t(o)},o.src=e}),e7=async(e,t,o)=>{const{file:r,path:n}=await VTe(e),a=await r.blob();if(a.size===0){const d="Empty blob is loaded from "+e;throw h("image.ts").error(d),new C(_.C_MEDIAINFO_NOT_EXIST,{},d)}const{blob:i,isTransparent:s}=await M2(a),x=o??qe.v4();await vi(i,s,t,x);const c=await L2(n),l=oa(x);if(!l){const d="[loadImageFile] Image info not found for mediaId: "+x;
1143throw h("image.ts").error(d),new C(_.C_MEDIA_IMAGE_FILE_READ_ERROR,{},d)}return{aspectRatio:c,imageInfo:l}},LTe=async e=>{const t=URL.createObjectURL(e);try{const{blob:o,isTransparent:r}=await M2(e),n=qe.v4();await vi(o,r,void 0,n);const a=await L2(t),i=oa(n);if(!i){const s="[loadImageFileByBlob] Image info not found for mediaId: "+n;throw h("image.ts").error(s),new C(_.C_MEDIAINFO_NOT_EXIST,{},s)}return{aspectRatio:a,imageInfo:i}}finally{URL.revokeObjectURL(t)}},MTe=async(e,t,o,r)=>{const n=URL.createObjectURL(e);try{const a=await L2(n),i=await PN(e),s=qe.v4();await vi(e,i,void 0,s);const x=oa(s);if(!x){const l="[binaryToImageModel] Image info not found for mediaId: "+s;return h("image.ts").error(l),null}const c=gb(Rt(),s,a,o,r,{importType:t});return c?{imageModel:c,imageInfo:x}:null}finally{URL.revokeObjectURL(n)}},t7=()=>document.hasFocus()?new Promise(async e=>{try{const t=await navigator.clipboard.read();if(t.length===0){e(null);return}const o=t[0];let r=null;for(const n of o.types)if(n==="text/plain"){e(null);return}else PTe.test(n)&&(r=await o.getType(n));e(r)}catch(t){if(xg(t)){const{name:o,message:r}=t;!sD.includes(r)&&(h("image.ts").warn("Error occurred during access clipboard, "+o+", "+r),sD.push(r))}e(null)}}):Promise.resolve(null),uit=(e,t)=>{const o=e*t;return o<0?-o+w6:0},pit=(e,t,o,r,n)=>{const a=e*o,i=t*o,s=o-i-.5*(n-i);return a<s?-r:a-s-r},fit=(e,t,o,r)=>{const n=e*o,a=t*o,i=.5*(r-a);return n<i?-n+i:0},git=e=>({...{top:6,height:484},...{right:{right:44},left:{left:44}}[e]}),_it=async(e,t)=>{const o=await YOe(e,t);return Object.keys(o).sort((n,a)=>(o[a]??0)-(o[n]??0))||[]},DTe=async(e,t,o)=>e?await cR({id:"select-image-file",mimeTypes:t.map(r=>"image/"+r),extensions:o.map(r=>"."+r),description:A("filetype.image"),multiple:!0}):[await cR({id:"select-image-file",mimeTypes:t.map(r=>"image/"+r),extensions:o.map(r=>"."+r),description:A("filetype.image"),multiple:!1})],Eit=async({supportGif:e,selectMulti:t})=>{try{const o=pt().getSupportedImageMimeTypes().filter(a=>e?!0:a!=="gif"),r=pt().getSupportedImageFiles().filter(a=>e?!0:a!=="gif");return await DTe(t,o,r)}catch(o){if(no(o))return;throw Ne(o)?o:(h("image.ts").warn("SelectImageFileError",P(o)),new C(_.C_SELECT_IMAGE_FILE_ERROR,{},Jx(o)))}},mit=async e=>{if(!vU.test(e.name))throw new C(_.C_MEDIA_INCOMPATIBLE_IMAGE);const{blob:o,isTransparent:r}=await M2(e),n=qe.v4();await vi(o,r,void 0,n);const a=URL.createObjectURL(o),i=await L2(a);return URL.revokeObjectURL(a),{type:Pu.Image,mediaId:n,aspectRatio:i}},o7=async(e,t)=>{const{blob:o,isTransparent:r}=await M2(e),n=t??qe.v4();await vi(o,r,void 0,n);const a=URL.createObjectURL(o),i=await L2(a);return URL.revokeObjectURL(a),{type:Pu.Image,mediaId:n,aspectRatio:i}},kTe=e=>e.filter(Gn),FTe=(e,t)=>{const o=[0,e/3,e*2/3,e],r=[0,t/3,t*2/3,t];return o.map(n=>r.map(a=>({x:n,y:a}))).flat()},hit=e=>new Promise(t=>{if(e.srcUrl.split(".").pop()!=="png")return t(!1);
1143if(e.stockSite===ws.OPENMOJI)return t(!0);try{const o=new Image,r=document.createElement("canvas"),n=r.getContext("2d");o.src=e.srcUrl,o.crossOrigin="anonymous",o.onload=()=>{if(r.width=o.width,r.height=o.height,n===null)return t(!1);n.drawImage(o,0,0);const a=n.getImageData(0,0,o.width,o.height).data,i=FTe(o.width,o.height).some(s=>a[(s.y*o.width+s.x)*4+3]===0);return t(i)},o.onerror=a=>(h("image.ts").error("Loading "+e.srcUrl+" failed : "+JSON.stringify(a)),t(!1))}catch(o){h("image.ts").error("Loading "+e.srcUrl+" failed : "+JSON.stringify(o)),t(!0)}}),PN=async e=>{try{const t=new Image,o=URL.createObjectURL(e);return await new Promise((n,a)=>{t.onload=()=>{const i=document.createElement("canvas"),s=i.getContext("2d");if(!s){a("No context");return}const{width:x,height:c}=t;i.width=x,i.height=c,s.drawImage(t,0,0,x,c);const l=s.getImageData(0,0,x,c);for(let d=0;d<l.data.length;d+=4)if(l.data[d+3]<255){n(!0);return}n(!1)},t.onerror=i=>a(i),t.src=URL.createObjectURL(e)}).finally(()=>{t.src="",URL.revokeObjectURL(o)})}catch(t){h("image.ts").warn("Error during checking image transparency: "+P(t))}return!1},Iit=(e,t,o,r,n)=>{const a=e.xPos*t,i=e.yPos*o,s=e.width*t,x=70,c=r==="right"&&RD(0,180,e.rotation)||r!=="right"&&RD(180,360,e.rotation)?e.height*o+x:e.height*o,l=c*Math.abs(Math.sin(e.rotation*2*Math.PI/360))+s*Math.abs(Math.cos(e.rotation*2*Math.PI/360)),d=r==="right"?a+n+.5*(s-l)-50:a+n+.5*(s+l)+10,u=136,p=i+u;return{left:d,top:p,widthIncrementalByRotation:l}},Tit=(e,t,o)=>{const r=e/t,n=e,a=t,i=ef.clamp(r,GS,WS);return{assetBoxWidth:n,assetBoxHeight:i===GS?Math.floor(e/GS):i===WS?Math.floor(e/WS):a}},UTe=async e=>{const t=_n(),o=await t.getValue(Bo.VREW_FEATURES_DB,Ko.USER_ASSET,e);if(o?.type===Pt.IMAGE)return o},r7=(e,t,o)=>{const r=document.createElement("canvas"),n=r.getContext("2d");return r.width=t,r.height=o,n?.drawImage(e,0,0,t,o),{canvas:r,context:n}},n7=(e,t)=>new Promise((o,r)=>{e.toBlob(n=>{if(n===null)return r(new C(_.C_MEDIA_BLOB_LOST));o(n)},t)}),Sit=async e=>{const t=URL.createObjectURL(e),o=new Image;try{return await new Promise(r=>{o.onload=()=>{const{naturalWidth:n,naturalHeight:a}=o;r(n>0&&a>0?{naturalWidth:n,naturalHeight:a}:null)},o.onerror=()=>r(null),o.src=t})}finally{o.onload=null,o.onerror=null,URL.revokeObjectURL(t)}},M2=async e=>{const t=new Image;return new Promise(function(o,r){t.onload=()=>{const{naturalWidth:a,naturalHeight:i}=t,s=a>3840||i>3840,x=a/i,c=s?a>i?3840:Math.floor(3840*x):a,l=c/x,{canvas:d,context:u}=r7(t,c,l),p=u?.getImageData(0,0,d.width,d.height);let f=!1;if(p){for(let E=0;E<p.data.length;E+=4)if(p.data[E+3]<255){f=!0;break}}n7(d,e.type).then(E=>o({blob:E,isTransparent:f}),r)},t.onerror=a=>{h("image.ts").error("image loading for width & height check failed : "+JSON.stringify(a)),r(new C(_.C_MEDIA_IMAGE_FILE_READ_E
1143RROR))},t.src=URL.createObjectURL(e)}).finally(()=>{t.src&&URL.revokeObjectURL(t.src)})},Oit=(e,t)=>{switch(t.type){case zE.FRAMEPACK_THUMBNAIL:case zE.GENERATED_THUMBNAIL:return ei().getImageFileSrcUrl(e.mediaId)??null;case zE.CLIP_THUMBNAIL:return s_(e.mediaId)}},VTe=async e=>{const t=/^data:/.test(e),o=at()&&!t?an(e):e;return{file:await fetch(o).catch(n=>{throw h("image.ts").error("Failed to fetch image from "+e+", "+n.message),new C(_.C_MEDIA_IMAGE_FILE_READ_ERROR,{},n.message)}),path:o}},GTe=async(e,t)=>{const o=await PN(e),r=qe.v4();await vi(e,o,t,r);const n=oa(r);if(!n){const a="[loadBlobImageFile] Image info not found for mediaId: "+r;throw h("image.ts").error(a),new C(_.C_MEDIAINFO_NOT_EXIST,{},a)}return n},WTe=async(e,t)=>{const o=await i7(e,"image");return GTe(o,t)},a7=e=>{const t=e.indexOf(",");if(t<0)throw new Error("Invalid base64 media data URL");const o=e.slice(0,t),r=o.slice(5).split(";")[0];if(!o.startsWith("data:")||!o.includes(";base64")||!r)throw new Error("Invalid base64 media data URL");const n=window.atob(e.slice(t+1)),a=new Uint8Array(n.length);for(let i=0;i<n.length;i++)a[i]=n.charCodeAt(i);return{bytes:a,mimeType:r}},Cit=e=>{const{bytes:t,mimeType:o}=a7(e);return new Blob([t],{type:o})},i7=async(e,t,o=t==="image"?"png":"mp4")=>{if(!e.startsWith("data:")){const a=await fetch(e);if(!a.ok)throw new Error("Failed to fetch media source: "+a.status+" "+a.statusText);return a.blob()}const{bytes:r}=a7(e),n=t==="image"&&o==="jpg"?"jpeg":o;return new Blob([r],{type:t+"/"+n})},WO=1920,HTe=.8,Rit=e=>new Promise((t,o)=>{const r=new Image,n=URL.createObjectURL(e);r.onload=async()=>{URL.revokeObjectURL(n);try{let{width:a,height:i}=r;if(a<=WO&&i<=WO&&await DT(e)==="image/jpeg"){t(e.slice(0,e.size,"image/jpeg"));return}const s=WO/Math.max(a,i);a=Math.round(a*s),i=Math.round(i*s);const x=document.createElement("canvas");x.width=a,x.height=i,x.getContext("2d").drawImage(r,0,0,a,i),x.toBlob(l=>{l?t(l):o(new Error("Failed to convert image to JPEG"))},"image/jpeg",HTe)}catch(a){o(a)}},r.onerror=()=>{URL.revokeObjectURL(n),o(new Error("Failed to load image for conversion"))},r.src=n}),xD=.7,jTe=4,zTe=640,Ait=async(e,t)=>{if(e.size<=t)return e;const o=URL.createObjectURL(e);try{const r=await NN(o),{naturalWidth:n,naturalHeight:a}=r;
1143if(!n||!a)throw new C(_.C_MEDIA_IMAGE_FILE_READ_ERROR);let i=xD,s=e;for(let x=0;x<jTe;x++){const c=Math.max(1,Math.round(n*i)),l=Math.max(1,Math.round(a*i)),{canvas:d,context:u}=r7(r,c,l);if(!u)throw new C(_.C_MEDIA_IMAGE_FILE_READ_ERROR);if(s=await n7(d,e.type),s.size<=t)return s;if(Math.max(c,l)<=zTe)break;i*=xD}return s}finally{URL.revokeObjectURL(o)}},YTe=30,s7=e=>{const t=na.utc().plus({hours:9}).toISO({includeOffset:!1}),o=Mt(ke.EDIT_VREWMARK_ALTERNATIVE_INFOS).find(l=>l.uid===e),r=o?.startDate??"",n=r===""?0:new Date(r).getTime(),a=new Date(t).getTime(),i=Math.floor((a-n)/(1e3*60)),s=Math.floor((a-n)/(1e3*60*60*24)),x=Mo().getDebugVal(Xt.CHANGE_VREWMARK_PERIOD);return x!==void 0&&!isNaN(parseInt(x))?i<parseInt(x):s<YTe},BTe=async(e,t)=>{const o={style:{paddingBottom:"1em"}};if(!e){const x=jt.createElement("div",void 0,A("vrewmark.delete_unable").split(`
1144`).map(d=>{const u=d===""?o:void 0;return jt.createElement("div",u,d)})),c={bodyClassName:"general-modal",title:A("vrewmark.delete_title"),content:x,yesStr:A("popup.login"),noStr:void 0};return await Y().popup(c)===mt.YES&&(Ike("vrewmark"),uP()),!1}const r=ba(),n=r.isPremiumFeatureAvailable(Ut.DELETE_VREW_MARK);if(!t&&!n)return Y().openModal(st.NEED_PLAN_UPGRADE,{premiumFeatureType:Ut.DELETE_VREW_MARK}),!1;const a=jt.createElement("div",void 0,A("vrewmark.delete_confirm")),i={bodyClassName:"general-modal",title:A("vrewmark.delete_title"),content:a,yesStr:A("popup.delete"),noStr:A("popup.close")};return await Y().popup(i)===mt.YES},KTe=async(e,t)=>{const o=t??0,r=L.get(N6,e),n=r?.at(o);if(n===void 0)throw new C(_.C_LOGIC_ERROR,void 0,"invalid color and index at vrewmark");const{aspectRatio:a,imageInfo:i}=await e7(n.image,tt.VREW_RESOURCE,n.mediaId),s={mediaId:i.mediaId,aspectRatio:a};return{vrewMarkInfo:{color:e,index:o,position:_i.TOP_LEFT},vrewMarkImage:s}},yit=async(e,t)=>{try{const o=na.utc().plus({hours:9}).toISO({includeOffset:!1}),r=Mt(ke.EDIT_VREWMARK_ALTERNATIVE_INFOS);return HUe(t),(await dCe(e,o,t)).result==="error"?!1:(po(ke.EDIT_VREWMARK_ALTERNATIVE_INFOS,r.filter(a=>a.uid!==e).concat([{uid:e,startDate:o}])),!0)}catch(o){return h("vrewmark.ts").error("Error occurred while sendVrewMarkAlternativeInfoToBigquery. "+P(o)),!1}},ST=async(e,t)=>{const o=await KTe(e),{vrewMarkInfo:r,vrewMarkImage:n}=o;return O9e(Rt(),n.mediaId,n.aspectRatio,t,r)},OT=async e=>{if(!await be().isLoginDone())return!1;const o=e();if(!k2(o))return!1;const n=ba().isPremiumFeatureAvailable(Ut.DELETE_VREW_MARK);return n?(po(ke.DISABLE_VREW_MARK,!0),!1):(!n&&Mt(ke.DISABLE_VREW_MARK)&&po(ke.DISABLE_VREW_MARK,!1),!Mt(ke.DISABLE_VREW_MARK))},Ya=e=>e.user,CT=e=>Ya(e).uid,x7=e=>Ya(e).planInfo,bN=e=>x7(e)!==void 0,vit=e=>Ya(e).name,wit=e=>Ya(e).userCloudStorageLimit,Nit=e=>Ya(e).authUpdateCounter,Pit=e=>Ya(e).email,bit=e=>Ya(e).userTrialAccOverdub,Lit=e=>Ya(e).userOverdubLimit,D2=e=>Ya(e).credits,Mit=Te(D2,e=>Ig(e)),Dit=Te(D2,e=>jy(e));Te([D2,bN],(e,t)=>zy(e,t)?.expireAt);const k2=Te(Ya,e=>e.uid?e.emailVerified&&(e.parentEmail?e.parentEmailVerified:!0):!1),kit=e=>{const t=k2(e),o=CT(e),r=s7(o),n=ba(),a=n.isPremiumFeatureAvailable(Ut.DELETE_VREW_MARK);return t&&a||r},LN="/try/assets/ic_check_filled-BQhMMAsw.svg",c7="/try/assets/ic_link-Bs1EZBhs.svg",MN="/try/assets/ic_warning_filled-GMZnBdKy.svg",XTe="/try/assets/img_change_card_fail-rwUlo5ny.svg",JTe="/try/assets/img_change_card_success-BBZ5kQxW.svg",qTe="/try/assets/img_usage_eraser-DGKs1BeR.svg",QTe=xe("div",{display:"inline-block"}),Mi=e=>{const{w:t,h:o,src:r,children:n,tooltip:a,bgSize:i,...s}=e,{css:x,rest:c,className:l}=al(s),{style:d,...u}=c,p={...x,backgroundRepeat:"no-repeat",backgroundPosition:"center center",width:t,height:o,backgroundSize:i},f=r?`url(${r})`:void 0;return b.jsx(M0,{content:a,children:b.jsx(QTe,{css:p,className:l,...u,style:{...f?{backgroundImage:f}:{},...d},children:n})})},ZTe=e=>{const{type:t}=e,r=Cf(x7)?.planType??"FREE",n=t==="CHANGE_CARD",a=t==="UPGRADE",i=!n,s=be().getUserInfo()?.referralInfo?.referralType,x=OSe(r,s),c=a?A("payment_modal.success_title_upgrade",{planType:x}):t==="NORMAL_PAYMENT"?A("payment_modal.success_title_normal_payment",{planType:x}):"",l=n?A("payment_modal.success_description_change_card"):void 0,d={alignSelf:"flex-center",marginTop:"40px",fontWeight:700,fontSize:"16px",lineHeight:"24px",color:ee.gray[850]},u={...d,alignSelf:"flex-start",marginTop:"20px",fontWeight:400,whiteSpace:"pre-line"};return t===void 0?null:b.jsxs(Xe,{direction:"column",align:"center",children:[n?b.jsx(Mi,{src:JTe,w:200,h:200}):b.jsx(Mi,{src:LN,w:120,h:120}),i&&b.jsx(Nt,{css:d,children:c}),l&&b.jsx(Nt,{css:u,children:l})]})},$Te=()=>{const e={alignSelf:"flex-center",marginTop:"40px",fontWeight:700,fontSize:"16px",lineHeight:"24px",color:ee.gray[850]},t={...e,alignSelf:"flex-start",marginTop:"20px",fontWeight:400,whiteSpace:"pre-line"};return b.jsxs(Xe,{direction:"column",align:"center",children:[b.jsx(Mi,{src:LN,w:120,h:120}),b.jsx(Nt,{css:e,children:A("user_refund.refund_success_title")}),b.jsx(Nt,{css:t,children:A("user_refund.refund_success_desc")})]})},eSe=()=>{const e={paddingBottom:"40px"},t={alignSelf:"flex-start",marginTop:"40px",fontWeight:700,fontSize:"16px",lineHeight:"24px",color:ee.gray[850]},o={...t,marginTop:"20px",fontWeight:400,whiteSpace:"pre-line"};return b.jsxs(Xe,{direction:"column",align:"center",css:e,children:[b.jsx(Mi,{src:MN,w:120,h:120}),b.jsx(Nt,{css:t,children:A("user_refund.refund_fail_desc_main")}),b.jsx(Nt,{css:o,children:A("user_refund.refund_fail_desc_sub")})]})},tSe=e=>{const{type:t,isExpired:o}=e,[r,n]=it.useState(!1),a=t==="UPGRADE",i=t==="CHANGE_CARD",s=o||!i,x=o?A("payment_modal.expired_title"):i?"":a?A("payment_modal.fail_title_upgrade"):A("payment_modal.fail_title_normal_payment"),c=o?A("payment_modal.expired_description"):A("payment_modal.fail_description"),l=i?A("payment_modal.link_change_card"):a?A("payment_modal.link_upgrade"):A("payment_modal.link_payment_page"),d=it.useCallback(()=>{n(!0),setTimeout(()=>n(!1),f7)},[]),u=async()=>
1144{if(r)return;if(!await Vn("onClickPaymentButton")){h("PaymentModal.tsx").error("Cannot start payment, upgrade, change card without ensured login in PaymentFailModal");return}d();const O=await be().fetchUserInfo(),S=O?.planInfo;if(a&&S){const{currency:y,planType:v}=S;return u7(v,y)}if(i&&S)return SSe(S.currency);const R=jh(O?.referralInfo?.referralType);return WN(R)},p={paddingBottom:"40px"},f={alignSelf:"flex-start",marginTop:"40px",fontWeight:700,fontSize:"16px",lineHeight:"24px",color:ee.gray[850]},E={...f,marginTop:"20px",fontWeight:400,whiteSpace:"pre-line"},T={padding:"0 36px",marginTop:"40px",height:"40px",backgroundColor:r?ee.mint[550]:ee.mint[500],borderRadius:"8px",fontWeight:500,fontSize:"16px",lineHeight:"24px",color:ee.gray[0],"&:hover":{backgroundColor:ee.mint[550]},filter:r?"brightness(0.9)":void 0};return b.jsxs(Xe,{direction:"column",align:"center",css:p,children:[i?b.jsx(Mi,{src:XTe,w:200,h:200}):b.jsx(Mi,{src:MN,w:120,h:120}),s&&b.jsx(Nt,{css:f,children:x}),b.jsx(Nt,{css:E,children:c}),b.jsxs(Xe,{justify:"center",align:"center",cursor:r?"default":"pointer",gap:4,css:T,onClick:u,children:[b.jsx(fn,{maskColor:ee.mint[100],src:c7,w:20,h:20}),b.jsx(Nt,{children:l})]})]})},HO=e=>{const t={whiteSpace:"pre-line"};return{title:A("payment_modal.upgrade_exception_header"),content:b.jsx(Nt,{css:t,children:e}),yesStr:A("payment_modal.upgrade_exception_confirm")}},oSe=e=>({title:A("payment_modal.success_header"),content:b.jsx(ZTe,{type:e}),yesStr:A("payment_modal.success_confirm")}),rSe=()=>({title:A("user_refund.success_modal_header"),content:b.jsx($Te,{}),yesStr:A("payment_modal.success_confirm")}),nSe=()=>({title:A("user_refund.fail_modal_header"),content:b.jsx(eSe,{}),showFooterButtons:!1}),aSe=(e,t)=>({title:A("payment_modal.fail_header"),content:b.jsx(tSe,{type:e,isExpired:t}),showFooterButtons:!1}),iSe=e=>{const{creditGranted:t}=e;return b.jsxs(Xe,{direction:"column",align:"center",gap:20,children:[b.jsx(Mi,{src:qTe,w:240,h:240,bgSize:"cover"}),b.jsx(Nt,{css:{fontSize:"18px",fontWeight:700,lineHeight:"25.5px",textAlign:"center"},children:A("usage_eraser.success_modal_credit_description",{credits:Wy(t)})})]})},sSe=e=>{const{isExpired:t}=e,[o,r]=it.useState(!1),n=t,a=t?A("payment_modal.expired_title"):A("payment_modal.fail_title_normal_payment"),i=t?A("payment_modal.expired_description"):A("payment_modal.fail_description"),s=A("payment_modal.link_payment_page"),x=it.useCallback(()=>{r(!0),setTimeout(()=>r(!1),f7)},[]),c=async()=>{if(!o){if(!await Vn("onClickPaymentButton")){h("PaymentModal.tsx").error("Cannot start payment, upgrade, change card without ensured login in PaymentFailModal");return}x(),HN(g.PAYMENT_MODAL)}},l={paddingBottom:"40px"},d={alignSelf:"flex-start",marginTop:"40px",fontWeight:700,fontSize:"16px",lineHeight:"24px",color:ee.gray[850]},u={...d,marginTop:"20px",fontWeight:400,whiteSpace:"pre-line"},p={padding:"0 36px",marginTop:"40px",height:"40px",backgroundColor:o?ee.mint[550]:ee.mint[500],borderRadius:"8px",fontWeight:500,fontSize:"16px",lineHeight:"24px",color:ee.gray[0],"&:hover":{backgroundColor:ee.mint[550]},filter:o?"brightness(0.9)":void 0};return b.jsxs(Xe,{direction:"column",align:"center",css:l,children:[b.jsx(Mi,{src:MN,w:120,h:120}),n&&b.jsx(Nt,{css:d,children:a}),b.jsx(Nt,{css:u,children:i}),b.jsxs(Xe,{justify:"center",align:"center",cursor:"pointer",gap:4,css:p,onClick:c,children:[b.jsx(fn,{maskColor:ee.mint[100],src:c7,w:20,h:20}),b.jsx(Nt,{children:s})]})]})},xSe=e=>({title:A("payment_modal.success_header"),yesStr:A("payment_modal.success_confirm"),content:b.jsx(iSe,{creditGranted:e})}),cSe=()=>({title:A("payment_modal.fail_header"),content:b.jsx(sSe,{}),showFooterButtons:!1}),cD=5e3,lD=420*1e3,lSe=60*1e3,dSe=10*1e3,DN=60,kN=e=>Ne(e)&&e.errorCode===_.S_SOCKET_MAX_CONNECTION_TIMEOUT_ERROR,uSe={payment:()=>OOe()},Qm=new Set,pSe=e=>{Qm.add(e)},fSe=e=>{Qm.delete(e)},Fit=()=>{const e=[...Qm];Qm.clear();for(const t of e)t.readyState!==WebSocket.CLOSED&&t.close()},FN=(e,t,o,r,n,a,i=!0)=>new Promise((s,x)=>{const c=h("socket.ts"),l=uSe[e]();let d,u=!1,p=!1,f=!1,E=null,T=null,O=null;const S=()=>{i&&f&&fSe(d),E&&(clearTimeout(E),E=null),T&&(clearTimeout(T),T=null),O&&(clearTimeout(O),O=null),d&&d.readyState!==WebSocket.CLOSED&&d.close()},R=(N,M)=>{!u&&(u=!0,S(),x(M??new Error(N)))},y=N=>{!u&&(u=!0,S(),s(N))},v=(N=lD)=>{T=setTimeout(()=>{if(d&&d.readyState===WebSocket.OPEN)try{c.debug("[connectSocketAndWaitForMessage] Sending heartbeat for subId: "+t),d.send(JSON.stringify({action:"ping"})),v(lD)}catch(M){const k=Math.max(Math.min(lSe,N/2),dSe);c.warn("[connectSocketAndWaitForMessage] Heartbeat failed, retrying in "+k/1e3+"s: "+P(M
1144)),v(k)}},N)},w=()=>{const N=a*60*1e3;O=setTimeout(()=>{const M="Max connection time exceeded: "+a+" minutes";R(M,new C(_.S_SOCKET_MAX_CONNECTION_TIMEOUT_ERROR))},N)};E=setTimeout(()=>{!p&&R("Subscribe confirmation timeout after "+cD+"ms")},cD);try{d=new WebSocket(l)}catch(N){R("Failed to create socket: "+P(N));return}d.onopen=()=>{c.info("[connectSocketAndWaitForMessage] Socket opened for subId: "+t+", subType: "+o+", service: "+r);const N={action:"socket_subscribe",subId:t,subType:o,service:r};d.send(JSON.stringify(N))},d.onmessage=N=>{c.info("[connectSocketAndWaitForMessage] Socket message received for subId: "+t+", data: "+N.data);try{const M=JSON.parse(N.data);if(M.action==="socket_subscribe"){if(M.result==="success"){p=!0,i&&(pSe(d),f=!0),E&&(clearTimeout(E),E=null),v(),w();return}if(M.result==="fail"){R("Server returned socket_subscribe fail");return}}const k=n(M);k.handled&&y(k.result)}catch(M){c.warn("[connectSocketAndWaitForMessage] Failed to parse socket message: "+P(M))}},d.onerror=()=>{c.info("[connectSocketAndWaitForMessage] Socket error for subId: "+t),R("Socket error")},d.onclose=()=>{c.info("[connectSocketAndWaitForMessage] Socket closed for subId: "+t),!u&&R("Socket closed unexpectedly")}}),gSe=e=>FN("payment",e,"guid","plan_payment_result",t=>{const o=t;return o.action!=="plan_payment_result"?{handled:!1}:{handled:!0,result:o.result==="success"?"success":"error"}},DN),_Se=e=>FN("payment",e,"guid","refund_result",t=>{const o=t;return o.action!=="refund_result"?{handled:!1}:{handled:!0,result:o.result==="success"}},DN),ESe=e=>FN("payment",e,"guid","usage_eraser_payment_result",t=>{const o=t;return o.action!=="usage_eraser_payment_result"?{handled:!1}:o.result==="success"?{handled:!0,result:{result:"success",quantity:o.quantity??wU}}:{handled:!0,result:{result:"error"}}},DN),jO=3600*1e3,mSe=5*1e3,RT=(e,t)=>{const o=h("payment.ts"),r=Date.now(),n=r+jO,a=async()=>{const i=await cCe(e,r,t);switch(i){case"COMPLETE":{o.info("Payment has succeeded, guid: "+e+", type: "+t+", status: "+i+"."),UN(t);return}case"EXIT":{o.error("exit polling to get payment progress, guid: "+e+", type: "+t+", status: "+i+".");return}case"EXPIRED":{o.error("Payment has expired due to time limit "+jO+"ms. guid: "+e+", type: "+t+", status: "+i+".");return}case"PENDING":{if(Date.now()>n){o.error("Payment has expired due to time limit "+jO+"ms, guid: "+e+", type: "+t+", status: "+i+".");return}o.info("payment progress is pending. trying to poll again, guid: "+e+", type: "+t+", statys: "+i+"."),setTimeout(a,mSe);return}default:{o.error("An error occered getting payment progress, guid: "+e+", type: "+t+",  status: "+i+"."),VN(t);return}}};a()},zO=3600*1e3,hSe=5*1e3,ISe=e=>{const t=h("payment.ts"),o=Date.now(),r=o+zO,n=async()=>{const a=await lCe(e,o);switch(a?.status){case"COMPLETE":{t.info("Payment usage eraser success. guid: "+e+". status: "+a.status),d7(a.quantity??wU);return}case"EXIT":{t.error("exit polling to get payment progress usage eraser. guid: "+e+". status: "+a.status);return}case"EXPIRED":{t.error("Payment usage eraser has expired due to time limit "+zO+"ms. guid: "+e+". status: "+a.status);return}case"PENDING":{if(Date.now()>r){t.error("Payment usage eraser has expired due to time limit "+zO+"ms. guid: "+e+". status: "+a.status);return}t.info("payment progress usage eraser is pending. guid: "+e+". trying to poll again"),setTimeout(n,hSe);return}default:{t.error("An error occered getting payment progress usage eraser. guid: "+e+". status: "+a?.status),l7();return}}};n()},AT=async(e,t)=>{if(uUe(t.source),!await Vn("openPlanUpgradeUrl")||!e){h("payment.ts").error("Cannot start payment or upgrade without ensured login in QuotaWarningModal");return}const o=await be().fetchUserInfo(),r=o?.planInfo;if(Kz(r===void 0?$E.NEW:$E.UPGRADE,t),r===void 0){const n=jh(o?.referralInfo?.referralType);return WN(n)}return g7(r)},UN=async e=>{const t=await be().fetchUserInfo();if(e==="USER_REFUND"){_Ue(),Y().popup(rSe());return}if(t===void 0||t.planInfo===void 0){h("payment.ts").error("userInfo or planInfo is undefined while payment succeeded");return}e==="CHANGE_CARD"&&EUe(!1),(e==="NORMAL_PAYMENT"||e==="UPGRADE")&&gUe(e,t.planInfo),Y().popup(oSe(e))},VN=e=>
1144{if(e==="USER_REFUND"){Y().popup(nSe());return}Y().popup(aSe(e))},l7=async()=>{Y().popup(cSe())},d7=async e=>{const t=await be().fetchUserInfo();if(t===void 0||t.planInfo===void 0){h("payment.ts").error("userInfo or planInfo is undefined while payment usage eraser success");return}const o=Number(ane)*e,r=t.credits??[],n=Ig(r)??0,a=jy(r)??0;GUe({planType:t.planInfo.planType,usageType:"CREDIT",afterRatio:a>0?n/a:0,beforeRatio:a>0?Math.max(0,n-o)/a:0,quantity:e}),Y().popup(xSe(o))},TSe=e=>e===void 0?!1:e==="MONTHLY"||e==="ANNUAL",Uit=e=>{Y().openModal(st.PAYMENT_PLAN_MANAGEMENT,{planInfo:e})},GN=e=>[Xr.Hotfix,Xr.RC,Xr.Release].includes(e)===!1,WN=async e=>{const t=await V7();if(t===void 0)return;const{guid:o,sessionId:r}=t,n={[Hl.GUID]:o,...r!==void 0?{[Hl.PAYMENT_SESSION_ID]:r}:{}};GN(fr.level)&&(n[Hl.TEST]=1);const a=n_(n),i=r_(),s=Fe(),x=s===ce.Taiwanese?"zh-TW":s,c=e?i+"/"+x+"/payment/order/subscription"+a:i+"/"+x+"/payment/pricepolicy"+a;pt().openUrl(c),gSe(o).then(async l=>{SP(),l==="success"?await UN("NORMAL_PAYMENT"):VN("NORMAL_PAYMENT")}).catch(l=>{kN(l)||(OP(),RT(o,"NORMAL_PAYMENT"))})},Vit=e=>{const t={guid:e},o=n_(t),r=r_(),n=Fe(),a=n===ce.Taiwanese?"zh-TW":n,i=r+"/"+a+"/payment/user-refund"+o;pt().openUrl(i),_Se(e).then(async s=>{SP(),s?await UN("USER_REFUND"):VN("USER_REFUND")}).catch(s=>{kN(s)||(OP(),RT(e,"USER_REFUND"))})},Git=()=>{const e={[ce.Korean]:"66789",[ce.Japanese]:"66790",[ce.English]:"66791"},t=Fe(),o=t===ce.Korean||t===ce.Japanese||t===ce.English?e[t]:e[ce.English];pt().openUrl(wJ+"/"+o)},u7=async(e,t)=>{const o=r_(),r=await ZOe();if(r===void 0){h("payment.ts").error("The startUpgrade failed");return}const{guid:n,sessionId:a}=r,i={guid:n,...a!==void 0?{[Hl.PAYMENT_SESSION_ID]:a}:{}};GN(fr.level)&&(i[Hl.TEST]=1);const s=n_(i),x=p7(t);pt().openUrl(o+"/"+x+"/payment/upgrade/pricepolicy"+s),RT(n,"UPGRADE")},SSe=async e=>{const t=await V7(!0);if(t===void 0){h("payment.ts").error("The startChangeCard failed");return}const{guid:o,sessionId:r}=t,n={guid:o,...r!==void 0?{[Hl.PAYMENT_SESSION_ID]:r}:{}};GN(fr.level)&&(n[Hl.TEST]=1);const a=n_(n),i=r_(),s=p7(e);pt().openUrl(i+"/"+s+"/payment/change-card"+a),RT(o,"CHANGE_CARD")},HN=async e=>{pUe(e);const t=await QOe();if(t===void 0){h("payment.ts").error("The startPurchaseUsageEraser failed");return}const o={guid:t},r=n_(o),n=r_(),a=Fe(),i=a===ce.Taiwanese?"zh-TW":a;pt().openUrl(n+"/"+i+"/payment/eraser/v2/order"+r),ESe(t).then(async s=>{SP(),s.result==="success"?await d7(s.quantity):await l7()}).catch(s=>{kN(s)||(OP(),ISe(t))})},p7=e=>{if(e==="KRW")return"ko";if(e==="JPY")return"ja";const t=Fe();return t===ce.Spanish?"es":t===ce.Taiwanese?"zh-TW":"en"},OSe=(e,t)=>{switch(e){case"FREE":return zr("payment.plantype_free");case"LIGHT":return zr("payment.plantype_light");case"STANDARD":return zr("payment.plantype_standard");case"BUSINESS":return zr("payment.plantype_business");case"CUSTOM":return jh(t)?zr("payment.plantype_business")+" ("+zr("payment.referral_discount_label")+")":zr("payment.plantype_custom")}},CSe=e=>{switch(e){case"AUTH":return _.C_PAYMENT_AUTHORIZATION_ERROR;case"DUP_KEY":return _.C_PAYMENT_DUPLICATE_ERROR;default:return _.C_PAYMENT_GENERAL_ERRROR}},f7=3*1e3,Wit=(e,t)=>{const o=t==="KRW"?"ko-KR":t==="JPY"?"ja-JP":"en-US";return new Intl.NumberFormat(o,{style:"currency",currency:t}).format(e)},g7=e=>{if(e.planType==="CUSTOM"){Y().popup(HO(zr("payment_modal.upgrade_exception_custom")));return}if(!TSe(e.period)){Y().popup(HO(zr("payment_modal.upgrade_exception_term_pass")));return}if(e.planType==="BUSINESS"&&e.period==="ANNUAL"){Y().popup(HO(zr("payment_modal.upgrade_exception_annual_business")));return}return u7(e.planType,e.currency)},wd=e=>{switch(e){case"AUTHORIZATION":return _.C_PAYMENT_AUTHORIZATION_ERROR;case"USER_VERIFICATION_NEEDED":return _.C_PAYMENT_USER_VERIFICATION_NEEDED;case"DUPLICATE_PAYMENT":return _.C_PAYMENT_DUPLICATE_ERROR;case"INCONSISTENCY":return _.C_PAYMENT_INCONSISTENCY_ERROR;case"EXPIRED":return _.C_PAYMENT_EXPIRED_ERROR;case"DB_ERROR":return _.C_PAYMENT_DB_ERROR;default:return _.C_PAYMENT_GENERAL_ERRROR}},Hit=e=>!e||!e.paidPlanInfo||e.paidPlanInfo.subscriptionConsentInfo===void 0||RSe(e.uid)?{isConsentRequired:!1,isConsentDue:!1}:{isConsentRequired:!0,isConsentDue:e.paidPlanInfo.subscriptionConsentInfo.isConsentDue},RSe=e=>Ve().getObject(Ie.SUB_CONSENT_NOTICE_PREFERENCES)[e]?.isDissented===!0,jit=(e,t)=>
1144{if(!e)return;const o=Ve().getObject(Ie.SUB_CONSENT_NOTICE_PREFERENCES),r={...o,[e]:{nextNoticeDays:t}};Ve().set(Ie.SUB_CONSENT_NOTICE_PREFERENCES,r)},zit=e=>{const t=Ve().getObject(Ie.SUB_CONSENT_NOTICE_PREFERENCES),o={...t,[e]:{isDissented:!0}};Ve().set(Ie.SUB_CONSENT_NOTICE_PREFERENCES,o)},Yit=e=>Ve().getObject(Ie.SUB_CONSENT_NOTICE_PREFERENCES)[e],Bit=e=>{const t=Ve().getObject(Ie.SUB_CONSENT_NOTICE_PREFERENCES);delete t[e],Ve().set(Ie.SUB_CONSENT_NOTICE_PREFERENCES,t)},ASe=e=>({draggablePercent:80,...e});class jN{toastId;constructor(t){this.toastId=t}message=(t,o)=>(xt.update(this.toastId,{render:t,...o}),this);asClosable=(t=5e3,o={})=>this.options({autoClose:t,closeOnClick:!0,draggable:!1,closeButton:!0,hideProgressBar:!0,...o});dismiss=(t=1)=>{xt.dismiss(this.toastId);let r=0;const n=setInterval(()=>{++r,xt.isActive(this.toastId)||r>=t&&clearInterval(n),xt.dismiss(this.toastId)},1e3)};options=t=>(xt.update(this.toastId,ASe(t)),this)}const m0=(e,t={})=>{const o=Es.info(e,{autoClose:!1,draggable:!1,closeOnClick:!1,closeButton:!1,draggablePercent:80,containerId:s0.TOP_RIGHT,...t});return new jN(o)},_7=e=>{let t=!1;return async function(){if(!e||t||!e.onCancel)return;if(t=!0,!e.cancelTitle){e.onCancel();return}const o=ql(e.cancelTitle);await Y().popup(o)===mt.YES&&e.onCancel()}},ySe=(e,t,o)=>{const{progressRatio:r,progressStageText:n,progressWarnText:a}=t,i=_7({onCancel:o}),s={paddingTop:"9px"},x=`${Math.round(r*100)}%`,c=b.jsx(uy,{percent:r*100,className:"progress-line",strokeColor:ee.mint[500],trailColor:ee.gray[125]}),l=o?b.jsx("div",{className:"cancel-btn",onClick:i,children:A("popup.cancel")}):void 0;return b.jsxs("div",{className:"progress-translate",style:s,children:[b.jsx("div",{className:"textrow",children:b.jsx("span",{children:e})}),c,b.jsxs("div",{className:"progressrow",children:[b.jsx("div",{className:"progress-text",children:n}),b.jsx("div",{className:"progress-label",children:x})]}),b.jsx("div",{className:"progress-warn",children:a}),l]})},Sa=(e,t)=>{const o=_7(t),r=t?.progressRatio!==void 0?b.jsx(uy,{percent:t.progressRatio*100,className:"progress-line",strokeColor:ee.mint[500],trailColor:ee.gray[125]}):void 0,n=t?.remainTime?b.jsx("div",{className:"remain-time",children:t.remainTime}):void 0,a=t?.onCancel?b.jsx("div",{className:"cancel-btn",onClick:o,children:A("popup.cancel")}):void 0,i=t?.progressRatio===void 0&&t?.onCancel===void 0&&t?.remainTime===void 0;return b.jsxs("div",{className:"progress-normal",children:[b.jsx("div",{className:un({text:!i}),children:e}),r,n,a]})},vSe=e=>b.jsxs(it.Fragment,{children:[b.jsxs("div",{className:"title",children:[b.jsx("div",{className:"warning-icon"}),A("warning.invalid_font_title")]}),b.jsx("div",{className:"desc",children:A("warning.invalid_font_desc")}),b.jsxs("div",{className:"font-list-area",children:[b.jsx("div",{className:"title",children:A("warning.invalid_font_number",{number:e.length})}),b.jsx("div",{className:"scroll-zone",children:b.jsx("ul",{className:"list",children:e.map((t,o)=>b.jsx("li",{children:t},`font-${o}`))})})]})]}),wSe=e=>{const t=NSe(e),o=PSe();Es.info(t,o)},NSe=e=>{const t=jt.createElement("button",{className:"close-all",onClick:()=>{Es.dismiss()}},"close-all"),o=(x,c)=>jt.createElement("button",{className:"ga-copy-button",onClick:()=>{navigator.clipboard&&c!==void 0&&(navigator.clipboard.writeText(c.toString()),To.popup(`Copied: ${c}`))}},x),r=`${e.join(`
1145`)}`,n=`${e.join("_")}`,[a,i,s]=e;return jt.createElement("div",{className:"content"},jt.createElement("div",{className:"desc"},r),o("category",a),o("action",i),o("label",s),o("whole",n),t)},PSe=()=>({position:"top-right",draggable:!1,closeOnClick:!1,closeButton:!0,containerId:s0.TOP_RIGHT,className:"ga-debug",autoClose:!1}),zN=async(e,t,o,r)=>{lUe(e);const n={bodyClassName:"premium-feature-modal",headerIconClassName:"premium",title:A("need_plan_upgrade.header"),confirmTextFrontIconClassName:"upgrade-plan",content:o??b.jsx(Xe,{direction:"column",align:"flex-start",gap:24,children:Wc(A(`need_plan_upgrade.paid_user_feature_${e}`,r))}),yesStr:A("need_plan_upgrade.upgrade_plan"),noStr:A("popup.cancel")};
1145await Y().popup(n)===mt.YES&&(dUe(e),await AT(t,{source:g.LIMIT_POPUP,origin:{type:"premium_feature",premiumFeatureType:e}}))},bSe=e=>{const t=A("edit_on_trial_warning.body_msg");Vke(e),Y().popup(nz(t))},Kit=(e,t)=>{const{progressRatio:o,progressWarnText:r,progressBtnLabel:n,onClickButton:a,isBtnDisabled:i}=t,s={paddingTop:"9px"},x=`${Math.round(o*100)}%`,c=b.jsx(uy,{percent:o*100,className:"progress-line",strokeColor:ee.mint[500],trailColor:ee.gray[125]}),l={fontSize:12,fontWeight:400,color:ee.gray[550]},d={fontSize:14,fontWeight:500,lineHeight:"16px"},u=b.jsxs(Xe,{direction:"row",p:"10px 0px",align:"center",justify:"space-between",children:[b.jsx(Nt,{style:l,children:r}),b.jsx(Nt,{style:d,children:x})]});return b.jsxs("div",{className:"progress-normal",style:s,children:[b.jsx("span",{className:"text",children:e}),c,u,n&&b.jsx(LSe,{disabled:i,onClick:i?void 0:a,children:n})]})};xe(Xe,{flexDirection:"column",gap:16});const LSe=xe(Nt,{cursor:"pointer",w:80,h:38,mb:-4,lineHeight:"36px",border:`1px solid ${ee.gray[125]}`,borderRadius:8,fontSize:14,fontWeight:400,color:ee.gray[550],textAlign:"center",variants:{disabled:{true:{opacity:.5},false:{"&:hover":{bg:ee.gray[25]}}}}}),Xit=e=>b.jsx(nne,{...e}),E7=15,m7=17e4,Jit=E7*m7/1e3,qit={variants:{lang:{[ft.Korean]:{bg:ee.purple[50]},[ft.English]:{c:ee.blue[300],bg:ee.blue[50]},[ft.Japanese]:{c:ee.green[400],bg:ee.green[50]},[ft.Spanish]:{},[ft.Chinese]:{},[ft.Taiwanese]:{}},isDark:{true:{},false:{}}},compoundVariants:[{lang:ft.Korean,isDark:!0,css:{c:Fc.purple[100]}},{lang:ft.Korean,isDark:!1,css:{c:Fc.purple[400]}}],defaultVariants:{lang:ft.Korean,isDark:!1}},h7=e=>{const t=ni.getInstance(Ur.USER_TTS),o=t.getPayload(),r=o?.items??[],n=r.findIndex(({speakerId:i})=>i===e.speakerId),a=n===-1?[...r,e]:r.map((i,s)=>s===n?e:i);if(o===null){t.openProgress({items:a});return}t.setPayload({items:a})},MSe=e=>{const t=ni.getInstance(Ur.USER_TTS),o=t.getPayload();if(o===null)return;const r=o.items.filter(n=>n.speakerId!==e);if(r.length===0){Zy(Ur.USER_TTS);return}t.setPayload({items:r})},DSe=e=>{if(!C7(e)){I7(e.speakerId,e.trainingInfo.status);return}h7({speakerId:e.speakerId,speakerName:e.name,lang:e.lang,progressBaseAt:e.trainingInfo.requestedAt,progress:e.trainingInfo.progress,status:e.trainingInfo.status})},I7=(e,t)=>{const o=ni.getInstance(Ur.USER_TTS),r=o.getPayload(),n=r?.items.find(a=>a.speakerId===e);r===null||n===void 0||o.setPayload({items:r.items.map(a=>a.speakerId===e?{...a,progress:100,status:t}:a)})},fA=Symbol("userTTSPollingCancelled"),T7=new id,YO=new Set,kSe=()=>{T7.next()},FSe=()=>{kSe(),Zy(Ur.USER_TTS)},USe=async e=>{try{const t=await Bt(n2(()=>XSe(e)).pipe(a2({count:E7,delay:o=>o.message==="pending"?md(m7):ta(()=>o)}),wl(T7)),{defaultValue:fA});return typeof t=="symbol"?fA:t.info.trainingInfo.status}catch(t){return h("userTTSTrainingProgress.ts").error("Failed userTTS training: "+P(t)),"failed"}},S7=async(e,t)=>{if(!YO.has(e)){YO.add(e),t!==void 0&&h7({speakerId:e,...t});try{const o=await USe(e);if(o===fA)return;I7(e,o),$e().updateUserTTSSpeakerList().catch(r=>{h("userTTSTrainingProgress.ts").error("Failed to update userTTS speakers after polling: "+P(r))})}finally{YO.delete(e)}}};var VSe=(e=>(e.INTRO="user_tts_intro",e.AGREEMENT="user_tts_agreement",e.INSTRUCTION="user_tts_instruction",e.RECORD_PERMISSION="user_tts_record_permission",e.RECORD_SETTING="user_tts_record_setting",e.RECORDING="user_tts_recording",e.SUBMIT="user_tts_submit",e.LOADING="user_tts_loading",e.FAILURE="user_tts_failure",e.FINISH="user_tts_finish",e))(VSe||{});const Qit=20,Zit=e=>"trainingInfo"in e,GSe=e=>{const t=e.versions?.at(-1);return t===void 0||t==="v1"},WSe=e=>e.versions?.at(-1)==="v2",dD={release:[ft.Korean,ft.Japanese,ft.English],debug:[]},$it=()=>{const e=[...dD.release.map(D0)],t=[...dD.debug.map(D0)];return new Set([...e,...wi()?t:[]]).has(Fe())},est={[ft.Korean]:"v1",[ft.Japanese]:"v1",[ft.English]:"v2"},O7=()=>{if(wi()||Us(Xt.USER_TTS))return 100;const e=be().getUserInfo();return e===void 0?0:e.paidPlanInfo?.userTTSSpeakerLimit??1},tst=async(e,t,o,r)=>{await Bt(n2(()=>YSe(e,t,o,r)).pipe(a2({count:2,delay:n=>no(n)?ta(()=>n):md(1e3),resetOnSuccess:!0})))},ost=async(e,t,o,r)=>Bt(n2(()=>BSe(e,t,o,r)).pipe(a2({count:2,delay:n=>no(n)?ta(()=>n):md(1e3),resetOnSuccess:!0}))),HSe=e=>e.outcomeInfo?.isConfirmed===!1,jSe=async()=>{Ta(It.DONT_SHOW_USER_TTS_GUIDE_AGAIN)||Y().popup(ybe())},zSe=e=>{const{speakerId:t,name:o,trainingInfo:r,outcomeInfo:n}=e,{status:a,requestedAt:i}=r;if(a==="complete"&&n?.modelMetadata){xt.info(A("user_tts.training_success",{speakerName:o}),{autoClose:!1,onClose:jSe});const s=na.fromISO(i),x=na.fromISO(n?.modelMetadata.created).toUTC(),c=Math.floor(x.diff(s,"minutes").as("minutes"));gL(t,!0,c),pD(e)}else a==="failed"&&(xt.error(A("user_tts.training_fail",{speakerName:o}),{autoClose:!1}),gL(t,!1),pD(e))},C7=e=>e.trainingInfo.status!=="complete"&&e.trainingInfo.status!=="failed",rst=async(e,t,o,r)=>{if(!await Vn("openUserTTSModal"))return;const n=$e().getUserTTSSpeakers()?.length??0,a=O7();if(n>
1145=a&&a!==0){await zN(Ut.USER_TTS_SPEAKER,t,void 0,{userTTSSpeakerLimit:a});return}const s=()=>{o?.(),Y().openModal(st.USER_TTS,{initialLang:r}),sre(e)},x=Y(),c=x.getActiveModal();if(c===st.TXT_TO_VIDEO||c===st.IMPORT_DOCS||c===st.IMPORT_IMAGES){const l={bodyClassName:"general-modal",title:A("popup.confirm"),content:A("user_tts.warn_on_open"),yesStr:A("user_tts.exit_yes"),noStr:A("ttv_v2.close_modal_continue")};x.popup(l).then(d=>{d===mt.YES&&s()})}else s()},nst=(e,t)=>{const o=e.some(n=>n===t),r=t==="";return{isValid:!(o||r),reason:{isDuplicate:o,isBlank:r}}},ast=()=>{Y().openModal(st.USER_TTS_SPEAKER_LIST)},ist=async(e,t,o)=>{try{t(!0);const r=e.versions?.at(-1),n=e.speakerId;if(GSe(e))await KSe(e.speakerId,e.name,e.lang),xt.info(A("tts_modal.user_speaker_training_start_toast"));else if(WSe(e))await R7(e.speakerId,e.name,e.lang,e.trainingInput.promptText),xt.info(A("tts_modal.user_speaker_register_success_toast",{speakerName:e.name}));else throw new C(_.C_USER_TTS_GENERAL_ERROR,{},`Unsupported userTTS speaker version. speakerId: ${n}, speakerVersion: ${r}`);await $e().updateUserTTSSpeakerList(),o($e().getUserTTSSpeakers()??[])}catch(r){h("userTTS.tsx").error(`Failed to start userTTS training: ${P(r)}`);const n={bodyClassName:"general-modal",title:A("popup.title_confirm"),content:A("tts_modal.user_speaker_failed_retry_training"),yesStr:A("popup.confirm")};Y().popup(n)}finally{t(!1)}},sst=async(e,t,o)=>{const r=async(n,a)=>{if(!(!n||a!==mt.YES)){xt.info(A("tts_modal.user_speaker_deleting",{speakerName:e.name}));try{o(!0),await JSe(e.speakerId),MSe(e.speakerId);const i=$e();await i.updateUserTTSSpeakerList(),t(i.getUserTTSSpeakers()??[]),xt.info(A("tts_modal.user_speaker_deleted",{speakerName:e.name}))}catch(i){const s=_.C_USER_TTS_NETWORK_ERROR,x=Ot(s,{defaultKey:"error.user_tts_network_error"});Y().error(s,x),o(!1),h("userTTS.tsx").error(`Failed to delete userTTS speaker: ${P(i)}`)}}};Y().popup({title:A("popup.title_confirm"),content:b.jsx(Qr,{children:A("tts_modal.confirm_user_speaker_deletion",{speakerName:e.name})}),noStr:A("popup.cancel"),yesStr:A("popup.delete"),checkBox:{label:A("tts_modal.check_user_speaker_deletion"),defaultChecked:!1,handler:r,ensureCheck:!0}})},xst=(e,t)=>{const o=Fe()===ce.English?vx(e??t):vx(e??t).replace(/\s+/g,"").replace(/\.$/,"");return A("tts_modal.speaker_created_time",{createdAt:o,interpolation:{escapeValue:!1}})},cst=async(e,t,o,r)=>{try{await R7(e,t,o,r)}catch(n){const a=`Failed to register userTTS v2 speaker: ${P(n)}`;throw h("userTTS.tsx").error(a),new C(_.C_USER_TTS_NETWORK_ERROR,{},a)}finally{await $e().updateUserTTSSpeakerList()}},lst=e=>{switch(e){case ft.Korean:return A("user_tts.language_tag_label_ko");case ft.English:return A("user_tts.language_tag_label_en");case ft.Japanese:return A("user_tts.language_tag_label_ja");case ft.Spanish:case ft.Chinese:case ft.Taiwanese:return}},uD=async()=>{const e=h("userTTS.ts");if(!await wo()&&!Us(Xt.USER_TTS))return[];try{const t=O7(),o={userTTSSpeakerLimit:t},r=await $m("/user-tts-voice-list",{method:"POST",body:JSON.stringify(o)}),n=await me(r,_.C_USER_TTS_FETCH_SPEAKER_LIST_ERROR);if(n.result==="error"){const a="/user-tts-voice-result error: "+JSON.stringify(n);throw e.error(a),new C(_.C_USER_TTS_FETCH_SPEAKER_LIST_ERROR,{},a)}return Ere(n.speakers),n.speakers}catch(t){return e.error("Failed to fetch user speaker list: "+t),void 0}},YSe=async(e,t,o,r)=>{try{const n=await t.arrayBuffer(),a=new Uint8Array(n),i={speakerId:e,audioData:Array.from(a),sentenceIndex:o},s=await Pn("/upload-user-tts-audio-file",{method:"POST",body:JSON.stringify(i),signal:r});if((await me(s,_.C_USER_TTS_NETWORK_ERROR)).result!=="success")throw new C(_.C_USER_TTS_NETWORK_ERROR,{})}catch(n){throw no(n)?(h("userTTS.ts").debug("Aborted to upload userTTS audio"),n):(h("userTTS.ts").warn("Failed to upload userTTS audio: "+P(n)),Ne(n)?n:new C(_.C_USER_TTS_NETWORK_ERROR,{}))}},BSe=async(e,t,o,r)=>{try{const n={speakerId:e,targetIndex:t,text:o},a=await Pn("/verify-user-tts-recording",{method:"POST",body:JSON.stringify(n),signal:r}),i=await me(a,_.C_USER_TTS_NETWORK_ERROR);
1145if(i.result!=="success")throw new C(_.C_USER_TTS_NETWORK_ERROR,{});return{isAligned:i.isAligned,similarity:i.similarity}}catch(n){throw no(n)?(h("userTTS.ts").debug("Aborted to verify userTTS recording"),n):(h("userTTS.ts").warn("Failed to verify userTTS recording: "+P(n)),Ne(n)?n:new C(_.C_USER_TTS_NETWORK_ERROR,{}))}},pD=async e=>{try{const t=await Pn("/confirm-user-tts-speaker",{method:"POST",body:JSON.stringify({speaker:e})}),o=await me(t,_.C_USER_TTS_NETWORK_ERROR);if(o.result!=="success")throw new Error(JSON.stringify(o))}catch(t){h("userTTS.ts").error("Failed to confirm userTTS speaker: "+P(t))}},KSe=async(e,t,o)=>{if(e===null)throw h("userTTS.ts").error("speakerId is null"),new C(_.C_USER_TTS_GENERAL_ERROR,{});const r={speakerId:e,speakerName:t,lang:o};xre(e);try{const n=await Pn("/start-user-tts-training",{method:"POST",body:JSON.stringify(r)}),a=await me(n,_.C_USER_TTS_NETWORK_ERROR);if(a.result!=="success")throw h("userTTS.ts").warn("Failed to start userTTS training: "+JSON.stringify(a)),new C(_.C_USER_TTS_NETWORK_ERROR,{});fL(e,"success"),S7(e,{speakerName:t,lang:o,progressBaseAt:new Date().toISOString(),progress:0,status:"requested"})}catch(n){throw fL(e,"failed"),n}},R7=async(e,t,o,r)=>{const n={speakerId:e,speakerName:t,lang:o,promptText:r};cre(e);const a=Date.now();try{const i=await Pn("/register-user-tts-v2-speaker",{method:"POST",body:JSON.stringify(n)}),s=await me(i,_.C_NETWORK_REQUEST_FAILED);if(s.result!=="success")throw h("userTTS.ts").warn("Failed to register userTTS v2 speaker: "+JSON.stringify(s)),new C(_.C_USER_TTS_NETWORK_ERROR,{});_L(e,"success",Math.round((Date.now()-a)/1e3))}catch(i){throw _L(e,"failed",Math.round((Date.now()-a)/1e3)),i}},XSe=async e=>{const t={speakerId:e},o=await Pn("/check-user-tts-training-status",{method:"POST",body:JSON.stringify(t)}),r=await me(o,_.C_USER_TTS_NETWORK_ERROR);if(r.result==="success")return{info:r.info};throw r.result==="pending"?(h("userTTS.ts").info("checkTrainingStatus: Pending training status, "+JSON.stringify(r)),new C(_.C_USER_TTS_GENERAL_ERROR,{},r.result)):(h("userTTS.ts").error("checkTrainingStatus: Training failed, "+JSON.stringify(r)),new C(_.C_USER_TTS_GENERAL_ERROR,{},r.result))},JSe=async e=>{const t={speakerId:e},o=await Pn("/delete-user-tts-speaker",{method:"POST",body:JSON.stringify(t)}),r=await me(o,_.C_USER_TTS_NETWORK_ERROR);if(r.result!=="success")throw h("userTTS.ts").warn("Failed to delete userTTS speaker: "+JSON.stringify(r)),new C(_.C_USER_TTS_NETWORK_ERROR,{})},dst=async(e,t)=>{const o={speakerId:e,newName:t},r=await Pn("/change-user-tts-speaker-name",{method:"POST",body:JSON.stringify(o)}),n=await me(r,_.C_USER_TTS_NETWORK_ERROR);if(n.result!=="success")throw h("userTTS.ts").warn("Failed to change userTTS speaker name: "+JSON.stringify(n)),new C(_.C_USER_TTS_NETWORK_ERROR,{})};class qSe{constructor(t){this.cooldownMs=t}cooldownMs;inFlight;completedAt;run(t){if(this.inFlight!==void 0)return this.inFlight;if(this.completedAt!==void 0&&Date.now()-this.completedAt<this.cooldownMs)return Promise.resolve();const o=Promise.resolve().then(t),r=o.finally(()=>{this.completedAt=Date.now(),this.inFlight===r&&(this.inFlight=void 0)});return this.inFlight=r,r}}const QSe=3e4,ZSe={create:{models:[]},edit:{models:[]},extend:{models:[]}};class A7{invalidFontInfos=[];fontFuture=new Ns;prFontInit=this.fontFuture.promise();webFonts;stockTTSSpeakerList;stockTTSSpeakerListRefetchGate=new qSe(QSe);stockTTSSpeakerImagePrefix;userTTSSpeakers;templateList;stockMusicInfo=null;stockSoundEffectInfo=null;textboxInfo=null;characterInfo=null;stockShapeInfo=null;genImageModels=[];genVideoModels=[];genVideoModelListByMode=ZSe;genAssetModelsListeners=new Set;constructor(){const t=Ly();t.on(Ix.SIGN_IN,this.refreshUserTTSOnAuthChange),t.on(Ix.USER_INFO_UPDATED,this.refreshUserTTSOnAuthChange),t.on(Ix.SIGN_OUT,this.clearUserTTSOnSignOut)}waitFontLoading=async()=>{await this.prFontInit};initWebFonts=async()=>{const t=Fe();if(this.webFonts===void 0)try{this.webFonts=await WOe(t),this.webFonts.forEach(o=>{if(j4.includes(o.fontName)||o.path===void 0)return;const r=new FontFace(o.fontName,"url("+o.path+")",{weight:o.weight.toString()});document.fonts.add(r)}),h("base.ts").info("init web font done"),Ve().set(Ie.WEB_FONT_CACHE,this.webFonts)}catch(o){h("base.ts").error("error occured while init web font list: "+P(o)),this.webFonts=Ve().getArray(Ie.WEB_FONT_CACHE)}};getWebFontFamilies=()=>this.webFonts??[];hasInvalidFonts=()=>this.invalidFontInfos.length>0;getInvalidFontInfos=()=>this.invalidFontInfos;isInvalidFont=t=>{const{fontName:o,weight:r}=t;return!this.invalidFontInfos.find(n=>n.fontName===o&&n.weight===r)};initTTSSpeakerList=async t=>{if(this.stockTTSSpeakerList===void 0&&(this.stockTTSSpeakerList=await ED(),this.stockTTSSpeakerList===void 0&&t!==!0))throw new C(_.C_TTS_FETCH_SPEAKER_LIST_ERROR);if(this.userTTSSpeakers===void 0){if(this.userTTSSpeakers=await uD(),this.userTTSSpeakers===void 0&&t!==!0)throw new C(_.C_USER_TTS_FETCH_SPEAKER_LIST_ERROR);this.applyFetchedUserTTSSpeakers()}};getStockTTSSpeakerList=()=>this.stockTTSSpeakerList;fetchAndApplyStockTTSSpeakerList=async()=>{const t=await ED();t!==void 0&&(this.stockTTSSpeakerList=t)};refetchStockTTSSpeakerList=()=>this.stockTTSSpeakerListRefetchGate.run(this.fetchAndApplyStockTTSSpeakerList);getUserTTSSpeakers=()=>this.userTTSSpeakers??void 0;updateUserTTSSpeakerList=async()=>
1145{if(this.userTTSSpeakers=await uD(),this.userTTSSpeakers===void 0)throw new C(_.C_USER_TTS_FETCH_SPEAKER_LIST_ERROR);this.applyFetchedUserTTSSpeakers()};applyFetchedUserTTSSpeakers=()=>{this.handleNewUserTTSSpeakers(),this.syncUserTTSTrainProgress(this.userTTSSpeakers??[]),this.getUserTTSSpeakersInTraining().forEach(t=>{S7(t.speakerId)})};handleNewUserTTSSpeakers=()=>{this.userTTSSpeakers?.forEach(t=>{HSe(t)&&zSe(t)})};getUserTTSSpeakersInTraining=()=>this.userTTSSpeakers?.filter(C7)??[];syncUserTTSTrainProgress=t=>{t.forEach(DSe)};refreshUserTTSOnAuthChange=()=>{this.updateUserTTSSpeakerList().catch(t=>{h("base.ts").error("Failed to update userTTS speakers on auth change: "+P(t))})};clearUserTTSOnSignOut=()=>{FSe(),this.refreshUserTTSOnAuthChange()};initTTSSpeakerImagePrefix=async()=>{this.stockTTSSpeakerImagePrefix=await XOe()};getTTSSpeakerImagePrefix=()=>this.stockTTSSpeakerImagePrefix;getStockMusicInfo=async()=>(!this.stockMusicInfo&&await this.initializeStockMusics(),this.stockMusicInfo);initializeStockMusics=async()=>{const t=await BOe();if(!t)return;const{musics:o,tagInfo:r,nameInfo:n}=t;this.stockMusicInfo={musics:o,tagInfo:r,nameInfo:n}};getStockSoundEffectInfo=async()=>(this.stockSoundEffectInfo===null&&await this.initializeStockSoundEffects(),this.stockSoundEffectInfo);initializeStockSoundEffects=async()=>{const t=await JOe();t&&(this.stockSoundEffectInfo={sounds:t.soundEffects,tagInfo:t.tagInfo,nameInfo:t.nameInfo,categoryTagInfo:t.categoryTagInfo})};getWebAssets=async()=>(this.textboxInfo===null&&await this.initializeWebAssets(),this.textboxInfo);getWebAssetsSync=()=>this.textboxInfo;getWebTexboxHtml=t=>t===Ao?Qc():this.textboxInfo?.content.find(r=>r.mediaId===t)?.html;getWebTextboxInlineTypes=t=>t===Ao?Dc():this.textboxInfo?.content.find(r=>r.mediaId===t)?.enabledInlineTypes;initializeWebAssets=async()=>{const t=await HOe();if(t.content.length===0||!t.textboxFonts)return;const{textboxFonts:o}=t;this.textboxInfo={...t,textboxFonts:o,content:t.content.map(r=>nxe(r,o))}};getCharacterInfo=()=>(this.characterInfo===null&&this.initializeCharacterInfo(),this.characterInfo);updateCharacterInfo=async()=>{await this.initializeCharacterInfo()};initializeCharacterInfo=async()=>{this.characterInfo=await jOe()};initializeShapeInfo=async()=>{this.stockShapeInfo=await zOe()};getStockShapeInfo=()=>(this.stockShapeInfo===null&&this.initializeShapeInfo(),this.stockShapeInfo);initializeGenerateAssetModelList=async()=>{const t=await Y7();t.result==="success"&&this.setGenAssetModels(t.genImageModels,t.genVideoModels,t.genVideoModelListByMode)};getGenImageModels=()=>$Se(this.genImageModels);getGenVideoModels=()=>eOe(this.genVideoModels);getGenVideoModelListByMode=()=>this.genVideoModelListByMode;subscribeGenAssetModels=t=>(this.genAssetModelsListeners.add(t),t(),()=>{this.genAssetModelsListeners.delete(t)});setGenAssetModels=(t,o,r)=>{this.genImageModels=t,this.genVideoModels=o,this.genVideoModelListByMode=r,this.genAssetModelsListeners.forEach(n=>n())};initializeTemplateList=async()=>{this.templateList=await TCe()};getTemplateList=()=>this.templateList}const $Se=e=>y7(e),eOe=e=>y7(e),y7=(e,t)=>(Us(Xt.GEN_ASSET_MODEL_FORCE_DISABLED),Us(Xt.GEN_ASSET_MODEL_FORCE_DEPRECATED),e);class tOe extends A7{init=async()=>{let o=!1;const r=async()=>{await Promise.all([this.initWebFonts(),this.initializeStockMusics(),this.initializeStockSoundEffects(),this.initTTSSpeakerList(),this.initializeShapeInfo(),this.initializeCharacterInfo(),this.initTTSSpeakerImagePrefix(),this.initializeGenerateAssetModelList(),this.initializeTemplateList()]),o=!0};try{await Promise.race([r(),new Promise((n,a)=>{setTimeout(()=>{if(!o){a();return}n()},3e4)})])}finally{this.fontFuture.resolve()}};getSystemFontFamilies=()=>[];resetInvalidFontInfos=t=>{this.invalidFontInfos=[],t.forEach(o=>{const{fontName:r,weight:n}=zc(o);if(r.length===0)return;const a={fontName:r,weight:n};this.checkFontValid(a)&&this.invalidFontInfos.push(a)})};checkFontValid=t=>{if(this.getWebFontFamilies().find(o=>o.fontName===t.fontName&&o.weight===t.weight))return!1;
1145try{return!document.fonts.check(t.weight+"px "+lV(t.fontName))}catch(o){return h("browser.ts").error(P(o)),!1}}}class oOe extends A7{fontFamilies;init=async()=>{let o=!1;const r=async()=>{await Promise.all([this.initSystemFonts(),this.initWebFonts(),this.initializeStockMusics(),this.initializeStockSoundEffects(),this.initTTSSpeakerList(),this.initializeWebAssets(),this.initializeShapeInfo(),this.initializeCharacterInfo(),this.initTTSSpeakerImagePrefix(),this.initializeGenerateAssetModelList(),this.initializeTemplateList()]),o=!0};try{await Promise.race([r(),new Promise((n,a)=>{setTimeout(()=>{if(!o){a();return}n()},3e4)})])}finally{this.fontFuture.resolve()}};initSystemFonts=async()=>{if(this.fontFamilies===void 0)try{const t=await(await ae())("electron.init_font_list");this.fontFamilies=t.fontFamilies,h("local.ts").info("init system font done")}catch(t){h("local.ts").error("error occured while init font list: "+P(t))}};getSystemFontFamilies=()=>this.fontFamilies??[];resetInvalidFontInfos=t=>{this.invalidFontInfos=[];const o=this.getSystemFontFamilies(),r=this.getWebFontFamilies();t.forEach(n=>{const{fontName:a,weight:i}=zc(n);a.length!==0&&o.find(s=>s.fontName===a&&s.weight===i)===void 0&&r.find(s=>s.fontName===a&&s.weight===i)===void 0&&this.invalidFontInfos.push({fontName:a,weight:i})})}}let BO;const $e=()=>(!BO&&(BO=new(at()?oOe:tOe)),BO),rOe=({userText:e,style:t,engine:o,startFrameImageUrl:r,generationOptions:n})=>({type:"video",userText:e,style:t,engine:o,...r?{startFrameImageUrl:r}:{},...n?{generationOptions:n}:{}}),nOe=({userPrompt:e,style:t,prompt:o,width:r,height:n,engine:a,startFrameImageUrl:i,generationOptions:s,archive:x,pricingRevision:c},l)=>({type:"genvideo",userPrompt:e,style:t,prompt:o,width:r,height:n,engine:a,...l,...i?{startFrameImageUrl:i}:{},...s?{generationOptions:s}:{},...x!==void 0?{archive:x}:{},...c!==void 0?{pricingRevision:c}:{}});let eE=null;const aOe=async()=>{try{const e=await lx("/geoip",{method:"POST",body:JSON.stringify({})}),t=await me(e,_.A_AUTH_USERINFO_ERROR);return t.result==="error"?(h("geoIpService.ts").error("[GeoIpService] fetchUserLocation error: "+t.msg),null):(du.set(Ci.USER_COUNTRY,t.country),{country:t.country})}catch(e){return h("geoIpService.ts").error("[GeoIpService] fetchUserLocation error: "+P(e)),null}},v7=async()=>{const e=du.get(Ci.USER_COUNTRY);return e!==""?(h("geoIpService.ts").info("[GeoIpService] Cached hit: "+e),{country:e}):eE?(h("geoIpService.ts").info("[GeoIpService] Request already in flight or completed. Returning existing promise."),eE):(eE=aOe(),eE)},iOe=14,sOe=e=>{try{const t=new URL(e);return t.protocol==="vrew:"&&t.hostname.toLowerCase()==="openmodal"&&t.searchParams.get("modal")==="feedback"}catch{return!1}};class xOe{initialized=!1;paymentSupportBot=!1;isLoggedIn=!1;lastUserInfo=null;constructor(){this.loadScript()}loadScript=()=>{const t=window;if(t.ChannelIO)return(window.console.error||window.console.log||function(){})("ChannelIO script included twice.");const o=function(...n){o.c(n)};o.q=[],o.c=function(n){o.q.push(n)},t.ChannelIO=o;function r(){if(t.ChannelIOInitialized)return;t.ChannelIOInitialized=!0;const n=document.createElement("script");n.type="text/javascript",n.async=!0,n.src="https://cdn.channel.io/plugin/ch-plugin-web.js",n.charset="UTF-8";const a=document.getElementsByTagName("script")[0];a&&a.parentNode?.insertBefore(n,a)}document.readyState==="complete"?r():"attachEvent"in window?window.attachEvent?.("onload",r):(window.addEventListener("DOMContentLoaded",r,!1),window.addEventListener("load",r,!1))};initialize=async t=>{t?this.isLoggedIn=!0:(this.isLoggedIn=!1,this.forceRemoveChatSession());const o=!this.initialized,{isMU:r,needTag:n}=await fD(t?.lastChat,t?.lastFeedback),a=t&&r?t.uid:null,i=A("channeltok.user_label_error_reported_korean"),s=this.getUserLanguage(),x={pluginKey:TJ.key,hideChannelButtonOnBoot:!0,language:s};a!==null&&(x.memberId=a);const c=h("channelTok.ts");window.ChannelIO("clearCallbacks"),this.alignUserLanguagePage(),window.ChannelIO("shutdown"),po(ke.CHANNELTOK_ACTIVE,!1),window.ChannelIO("boot",x,(l,d)=>{const u=l?", error: "+P(l):"",p=d?{id:d.id,memberId:d.memberId,name:d.name,profileCid:d.profile?.cid,profileUid:d.profile?.uid,profileEmail:d.profile?.email,lastVersion:d.profile?.version,planType:d.profile?.planType,planPeriod:d.profile?.planPeriod,planStatus:d.profile?.planStatus,daysSinceSignUp:d.profile?.daysSinceSignUp,signupDate:d.profile?.signupDate,language:d.language,tags:d.tags}:void 0,f=p?", user: "+JSON.stringify(p,void 0,2):"";c.info("ChannelTok boot done"+u+f);const E=t?{name:t.name,email:t.email,uid:t.uid,planType:t.planType,planPeriod:t.planPeriod,planStatus:t.planStatus,lastChat:t.lastChat,lastFeedback:t.lastFeedback,tags:void 0,daysSinceSignUp:t.daysSinceSignUp,signupDate:t.signupDate}:null;if(n&&E){const T=d?.tags?[...d.tags]:[];T.includes(i)===!1&&T.push(i),E.tags=T}this.updateUser(E,o).then(()=>{this.lastUserInfo=t}),d!==null&&(d.alert>=1&&this.showChannelButton(),window.ChannelIO("onBadgeChanged",(T,O)=>{T>0&&this.showChannelButton()}),window.ChannelIO("onChatCreated",()=>{this.showChannelButton(),RR()}),window.ChannelIO("onHideMessenger",()=>{this.paymentSupportBot&&(c.info("onHideMessenger called from payment session. restart"),this.lastUserInfo&&this.initialize(this.lastUserInfo),this.paymentSupportBot=!1),this.hideChannelButton()}),!at()&&window.ChannelIO("onUrlClicked",T=>(c.info("onUrlClicked: "+T),sOe(T)?(Y().openModal(st.FEEDBACK,{openD
1145ataTransferDirectly:!0}),!0):!1)))}),this.initialized=!0};hideChannelButton=()=>{this.removeCloseButton(),window.ChannelIO("hideChannelButton"),po(ke.CHANNELTOK_ACTIVE,!1)};showChannelButton=()=>{window.ChannelIO("showChannelButton"),this.showCloseButton()};showPaymentSupportBot=()=>{const t={[ce.Korean]:"paymentKo",[ce.Japanese]:"paymentJa",[ce.English]:"paymentEn"},o=Fe(),r=t[o]??t[ce.English];this.paymentSupportBot=!0,window.ChannelIO("setPage",r),window.ChannelIO("openChat")};showCloseButton=()=>{if(document.getElementsByClassName("channeltok-close-button").length>0)return;const o=h("channelTok.ts"),r=document.getElementById("ch-plugin");if(!r){o.info("ChannelTok: Failed to find ch-plugin");return}const n=document.createElement("div");n.setAttribute("class","channeltok-area"),r.appendChild(n);const a=document.createElement("div"),i=document.createTextNode(A("setting.channeltok_hide"));a.appendChild(i),n.appendChild(a),a.setAttribute("class","channeltok-close-button"),a.addEventListener("click",this.hideChannelButton)};removeCloseButton=()=>{const t=document.querySelector(".channeltok-area");t&&t.remove()};alignUserLanguagePage=()=>{window.ChannelIO("resetPage");const t=Fe(),o={[ce.Korean]:"supportKo",[ce.Japanese]:"supportJa",[ce.English]:"supportEn"},r=o[t]??o[ce.English];window.ChannelIO("setPage",r)};showMessenger=()=>{window.ChannelIO("showMessenger"),RR()};GA=(t,o,r,n)=>{if(this.isAvailableEvent(t,o)||this.isLoggedIn&&this.isLoggedInAvailableEvent(t,o,r)){h("channelTok.ts").info("trying to upload event to channel.io...");const a=this.generateEventName(t,o,r);window.ChannelIO("track",a,n)}};sendSurveyResponse=(t,o)=>{if(!this.initialized){h("channelTok.ts").warn("ChannelTok not initialized, skipping survey response");return}o.type==="select"?(o.answers.forEach(r=>{const n=this.generateEventName(t,r,void 0);window.ChannelIO("track",n,{}),h("channelTok.ts").info("Sent survey to ChannelTok: "+n)}),window.ChannelIO("updateUser",{profile:{[t]:o.answers.join(", ")}}),h("channelTok.ts").info("Updated user profile with survey: "+t)):(window.ChannelIO("track",t,{response:o.answer}),h("channelTok.ts").info("Sent survey to ChannelTok: "+t),window.ChannelIO("updateUser",{profile:{[t]:o.answer}}),h("channelTok.ts").info("Updated user profile with survey: "+t))};updateUser=async(t,o=!1)=>{if(!this.initialized)return;this.isLoggedIn=t!==null;const{isMU:r}=await fD(t?.lastChat,t?.lastFeedback),n=na.utc().plus({hours:9}),a="'"+n.minus({minutes:30}).toISO({includeOffset:!1})+"'",i="'"+n.plus({minutes:30}).toISO({includeOffset:!1})+"'",s=await zo(),x=await ZT(),c=Ha(),l="http://es.v6x.team:5601/app/discover#/?_g=(filters:!(),refreshInterval:(pause:!t,value:0),time:(from:"+a+",to:"+i+"))&_a=(columns:!(category,action,label),filters:!(),index:'914004a0-2d78-11ec-9f60-7952b5199357',interval:auto,query:(language:kuery,query:'cid:%20"+s+"'),sort:!(!(timestamp,desc)))",d=at()?"desktop":"web",u=t?{vrewEmail:t.email,name:t.name,uid:t.uid,cid:s,cidTimestamp:x,userExplorerLink:l,...t.uid?{vocLink:"http://vrew-voc.v6x.team:3030/question/40?uid="+t.uid}:{},version:c,clientType:d,planType:t.planType,planPeriod:t.planPeriod,planStatus:t.planStatus,daysSinceSignUp:t.daysSinceSignUp,signupDate:t.signupDate}:{cid:s,cidTimestamp:x,userExplorerLink:l,version:c,clientType:d};t&&r&&(u.email=t.email);const p={profile:u};t?.tags&&(p.tags=t.tags),(o||!t&&this.lastUserInfo||t&&!this.lastUserInfo||t&&this.lastUserInfo&&(u.email!==this.lastUserInfo.email||u.name!==this.lastUserInfo.name||u.uid!==this.lastUserInfo.uid||u.planType!==this.lastUserInfo.planType||u.planPeriod!==this.lastUserInfo.planPeriod||u.planStatus!==this.lastUserInfo.planStatus))&&window.ChannelIO("updateUser",p,(f,E)=>{const T=h("channelTok.ts");if(f){T.error("channelTok Update user failed."+P(f));return}T.info("channelTok updateUser success")})};getUserLanguage=()=>{const t=Fe();return["ko","en","ja"].includes(t)?t:"en"};isAvailableEvent=(t,o)=>Pb[t]&&Pb[t].has(o);isLoggedInAvailableEvent=(t,o,r)=>t===m.AUTH&&o===g.AUTH_TRACK?r==="signIn_success"||r==="oauthSignIn_success":bb[t]&&bb[t].has(o);generateEventName=(t,o,r)=>t===m.AUTH&&o===g.AUTH_TRACK&&r?t+"@"+o+"#"+r:t===m.INIT&&o===g.INIT_INFO&&this.isLoggedIn?t+"@"+o+"#login":t+"@"+o;forceRemoveChatSession=()=>{document.cookie.split(";").forEach(o=>{const r=o.trim();if(r.startsWith("ch-session")){const n=r.split("=")[0];document.cookie=n+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;",h("channelTok.ts").info("Removed ch-session cookie: "+n)}})}}let KO=null;const Zm=()=>(!KO&&(KO=new xOe),KO),fD=async(e,t)=>{const o=cOe(t),r=await lOe();return{isMU:r||e!==void 0||o,needTag:o,uscaUser:r}},cOe=e=>{if(e===void 0)return!1;const t=na.fromISO(e);return t.isValid===!1?(h("channelTok.ts").error("Invalid lastFeedback date of "+e),!1):na.local().diff(t,"days").days<iOe},lOe=async()=>{const e=await v7();return!!(e&&["US","CA"].includes(e.country))},XO=e=>({email:e.email,name:e.name,uid:e.uid,planType:e.paidPlanInfo?.planType??"FREE",planPeriod:e.paidPlanInfo?.period??"",planStatus:e.paidPlanInfo?.planStatus??"",lastChat:e.lastChat,lastFeedback:e.lastFeedback,daysSinceSignUp:Math.floor(na.utc().diff(na.fromISO(e.created),"days").days),signupDate:e.created}),w7=()=>(Mo().getDebugVal(Xt.START_MODAL_VERSION),Mt(ke.START_MODAL_VERSION)==="B"?"B":"A"),dOe=["2","5"],uOe=e=>dOe.includes(e),to=()=>{const e=Mt(ke.TTV_VERSION);return uOe(e)?e:"2"},yT=()=>to()==="5",pOe="2026-08-25T09:00:00.000Z",N7=e=>{if(!e)return!1;const t=new Date(e);return Number.isNaN(t.getTime())?!1:t>=new Date(pOe)},fOe=e=>N7(e)?ls("ttv_version_5"):null,ust=e=>{if(Mo().getDebugVal(Xt.TTV_VERSION),!e){h("temporary.ttv.ts").info("[TTV] version not decided: no user info.");return}if(N7(e)){Rie("ttv_version_5");const t=ls("ttv_version_5"),o=t===cv.ttv_version_5.B?"5":"2";h("temporary.ttv.ts").info("[TTV] version decided by A/B. variant: "+t+", version: "+o),po(ke.TTV_VERSION,o);return}h("temporary.ttv.ts").info("[TTV] version decided: 2 (not an A/B test target)."),po(ke.TTV_VERSION,"2")};var Nr=(e=>(e.STT_ONLY="stt_only",e.HARDCUT_ONLY="hardcut_only",e.STT_AND_HARDCUT="stt_and_hardcut",e.STT_AND_AUTO_SPLIT_SCENE="stt_and_auto_split_scene",e.STT_AND_CAPTION_CORRECTION="stt_and_caption_correction",e.STT_AND_HARDCUT_AND_CAPTION_CORRECTION="stt_and_hardcut_and_caption_correction",e.STT_AND_AUTO_SPLIT_SCENE_AND_CAPTION_CORRECTION="stt_and_auto_split_scene_and_caption_correction",e.STT_AND_HARDCUT_AND_AUTO_SPLIT_SCENE="stt_and_hardcut_and_auto_split_scene",e.STT_AND_HARDCUT_AND_AUTO_SPLIT_SCENE_AND_CAPTION_CORRECTION="stt_and_hardcut_and_auto_split_scene_and_caption_correction",e))(Nr||{}),o_=(e=>(e.ANALYSIS_SUBPROCESS="analysis_subprocess",e.VDROP_SUBPROCESS="vdrop_subprocess",e))(o_||{}),Xi=(e=>(e.ANALYSIS="analysis",e.VDROP="vdrop",e.CLIPBOARD="clipboard",e))(Xi||{}),Ii=(e=>(e.JOB="job",e.PROCESS="process",e))(Ii||{}),Ll=(e=>(e.UPDATE_MESSAGE="update_message",e.UPDATE_AUDIO_ANALYSIS="audio_analysis",e.UPDATE_HARDCUT="hardcut",e.UPDATE_AUTO_SPLIT_SCENE="auto_
1145split_scene",e.UPDATE_CAPTION_CORRECTION="caption_correction",e.UPDATE_AUDIO_EXTRACT="audio_extract",e))(Ll||{}),pi=(e=>(e.TRANSCRIBE_REQUEST="transcribe.request",e.TRANSCRIBE_ANALYZE="transcribe.analyze",e.TRANSCRIBE_ANALYZE_WITH_DURATION="transcribe.analyze_with_duration",e.TRANSCRIBE_ALIGN="transcribe.align",e.TRANCSRIBE_SUCCESS="transcribe.success",e.TRANSCRIBE_UNKNOWN="transcribe.unknown",e.SERVER_ERROR="error.server_error",e))(pi||{}),Lr=(e=>(e[e.ANALYTICS_MANAGER=0]="ANALYTICS_MANAGER",e[e.LOCAL_GA=1]="LOCAL_GA",e[e.BROWSER_GA=2]="BROWSER_GA",e[e.VREW_ANALYTICS=3]="VREW_ANALYTICS",e[e.GA4=4]="GA4",e[e.CHANNELTOK_GA=5]="CHANNELTOK_GA",e[e.AMPLITUDE=6]="AMPLITUDE",e[e.ANONYMOUS=7]="ANONYMOUS",e[e.GTAG=8]="GTAG",e[e.META_PIXEL=9]="META_PIXEL",e[e.REDDIT_PIXEL=10]="REDDIT_PIXEL",e))(Lr||{});const pst={AGENT:"agent"},YN=e=>{try{const t=JSON.parse(e||"{}");if(t!==null&&typeof t=="object"&&!Array.isArray(t))return t}catch{}return e?{customValue:e}:{}},gOe={[m.VA_EXPORT]:new Set([g.VA_ANIMATION_INFO,g.VA_BGM_INFO,g.VA_CHARACTER_INFO,g.VA_CAPTION_EXPORT,g.VA_CURSOR_STATE,g.VA_CUT_EDIT_EXPORT,g.VA_FONT_INFO,g.VA_TTS_INFO,g.VA_IMAGE_INFO,g.VA_MARKER,g.VA_PLAYBACK_RATE,g.VA_RATIO,g.VA_SOUNDFX_INFO,g.VA_FRAMEPACK,g.VA_TEMPLATE,g.VA_TEXT_INFO,g.VA_TRANSLATE,g.VA_ZOOM_ROTATE,g.VA_VCLOUD_INFO,g.VA_VIDEO_REMIX,g.VA_VIDEO_INFO]),[m.RED_DOT]:new Set([g.INIT,g.USE]),[m.CURSOR_STATE]:new Set([g.WORD_DETAIL,g.WORD_SELECT,g.INSERT_CURSOR_A,g.INSERT_CURSOR_B,g.CLIP_SELECT]),[m.TTV_MODAL]:new Set([g.GENERATE_EACH_IMAGE]),[m.MOUSE_EDIT]:new Set([g.DISPLAY_THUMBNAIL,g.HOVER_THUMBNAIL_VIDEO,g.DELETE_WORD,g.WORD_READY_TO_DELETE,g.CLICK_DESIGN_TEXTBOX]),[m.EXPORT]:new Set([g.EXPORT_VIDEO_DONE,g.EXPORT_VIDEO_DONE_2,g.EXPORT_VIDEO_DONE_3,g.EXPORT_CAPTION_VIDEO_DONE,g.EXPORT_CAPTION_VIDEO_DONE_2,g.EXPORT_SRT_DONE,g.EXPORT_TEXT_DONE,g.EXPORT_TEXT_DONE_2,g.EXPORT_PREMIERE_DONE,g.EXPORT_FCPX_DONE,g.EXPORT_DAVINCI_FCPX_DONE,g.EXPORT_AUDIO_DONE,g.EXPORT_AUDIO_DONE_2,g.EXPORT_IMAGE_DONE,g.EXPORT_USED_MARKER_COUNT,g.EXPORT_VIDEO_START,g.EXPORT_VIDEO_START2,g.EXPORT_VIDEO_ENCODING_START,g.EXPORT_VIDEO_ENCODING_DONE,g.EXPORT_FILTER,g.EXPORT_CAPTION_VIDEO_CANCEL,g.EXPORT_CAPTION_VIDEO_DONE,g.EXPORT_CAPTION_VIDEO_DONE_2,g.EXPORT_CAPTION_VIDEO_ENCODING_START,g.EXPORT_CAPTION_VIDEO_ENCODING_DONE,g.EXPORT_CAPTION_VIDEO_FFMPEG_DOWNLOAD_START,g.EXPORT_CAPTION_VIDEO_FFMPEG_DOWNLOAD_DONE]),[m.RESEARCH]:new Set([]),[m.RESEARCH_PLAY]:new Set([]),[m.SELECT_CLIP]:new Set([g.SHIFT_CLICK,g.CLICK_CHECKBOX,g.CLICK_CHECKBOX_SURROUNDING_AREA,g.CTRL_CLICK,g.DRAG]),[m.TEXT_FLOATING_MENU]:new Set([]),[m.TEXT_PANEL_MENU]:new Set([]),[m.TTS]:new Set([g.CHANGE_CONTENT_TEXT]),[m.GUIDE_TOOLTIP]:new Set([]),[m.SUMMARY_IMAGE]:new Set([]),[m.SUMMARY_EXPORT]:new Set([]),[m.INSERT_GEN_ASSET]:new Set([g.TTV_DONE]),[m.ANONYMOUS_EVENT]:new Set([]),[m.INSERT_FREE_SOURCE]:new Set([g.SEARCH_FREE_SOURCE])},_Oe={[m.AUTH]:new Set([g.AUTH_TRACK]),[m.PREMIUM_FEATURE]:new Set([g.GO_TO_UPGRADE,g.DISPLAY,g.CLICK,g.LEARN_MORE]),[m.DEMO]:new Set([g.DEMO_LOADED])},EOe=1e3*60*60*24*7,gD=1800*1e3,mOe=1e3;class P7{type=Lr.AMPLITUDE;SAMPLE_RATIO=.03;SAMPLE_TARGET_COUNTRY=["US","CA"];API_KEY;enabled=!1;cid="";webCid="";uid="";cidTimestamp="";installCode="";osName="";vrewDeviceId="";machineId="";utmParams=void 0;browserName="";browserVersion="";country="";uidTimestamp="";constructor(){this.API_KEY=fr.level===Xr.Release?Qb.prod.apiKey:Qb.dev.apiKey}async amplitudeInitialize(){if(!await this.shouldInitAmplitude(this.uid,this.cid)){await this.pruneBuffered();return}H9(this.API_KEY,this.uid===""?void 0:this.uid,{deviceId:this.cid,instanceName:fr.level===Xr.Release?"prod":"dev",flushIntervalMillis:1e4,appVersion:Ha(),logLevel:Vr()?Hb.Warn:Hb.Error,optOut:!1,autocapture:{sessions:!0,attribution:!0,pageViews:!1,formInteractions:!1,fileDownloads:!1}}),this.enabled=!0,this.initDefaultUserProperties(this.uid,this.uidTimestamp),await this.flushBuffered(),h("amplitude.ts").info(`
1146          [Amplitude] Initialized with done.
1147            uid: `+this.uid+`
1148            cid: `+this.cid+`
1149          `)}async initialize(t,o,r,n,a,i,s,x,c,l,d,u,p){this.cid=o,this.webCid=p??"",this.cidTimestamp=r,this.uid=n,this.uidTimestamp=a,this.installCode=s,this.utmParam
1149s=u,this.osName=bx(),this.vrewDeviceId=x,this.machineId=c,this.browserName=l,this.browserVersion=d,await this.amplitudeInitialize()}async shouldInitAmplitude(t,o){const r=await this.isRandomlySampledUser(t),n=await this.isRandomlySampledUser(o),a=await v7();this.country=a?.country??"";const i=this.SAMPLE_TARGET_COUNTRY.includes(this.country);return r||n||i}initDefaultUserProperties(t,o){const r=[{key:"installCode",value:this.installCode,type:"set"},{key:"osName",value:this.osName,type:"set"},{key:"machineId",value:this.machineId,type:"set"},{key:"cid",value:this.cid,type:"set"},{key:"cidTimestamp",value:this.cidTimestamp,type:"set"},{key:"vrewDeviceId",value:this.vrewDeviceId,type:"set"}];t!==""&&r.push({key:"uid",value:t,type:"set"}),o!==""&&r.push({key:"uidTimestamp",value:o,type:"set"}),this.webCid&&r.push({key:"webCid",value:this.webCid,type:"set"}),$C.forEach(n=>{this.utmParams?.[n]&&r.push({key:n,value:this.utmParams[n],type:"set"})}),this.setUserProperties(r),this.setUserInfoProperties(),this.setPaidPlanProperties(),this.setNewUserProperties(),this.setPromotedUserProperties(),this.setTTVVersionProperties()}async isRandomlySampledUser(t){if(t==="")return!1;const o=new TextEncoder,r=o.encode(t),n=await crypto.subtle.digest("SHA-256",r),a=Array.from(new Uint8Array(n)),i=a.map(x=>x.toString(16).padStart(2,"0")).join("");return parseInt(i.substring(0,8),16)<this.SAMPLE_RATIO*Math.pow(2,32)}setUserInfoProperties(){const t=be().getUserInfo();if(!t)return;const{credits:o}=t,r=o.find(c=>c.creditType==="FREE_MONTHLY"),n=o.find(c=>c.creditType==="PAID_MONTHLY"),a=c=>Math.floor(Hy(c??"0")),i=o.reduce((c,l)=>c+a(l.creditBalance),0),s=o.reduce((c,l)=>c+a(l.givenCredit),0),x=s>0?Math.round(Math.max(0,(1-i/s)*100)):0;this.setUserProperties([{key:"emailVerified",value:t.emailVerified,type:"set"},{key:"parentEmailVerified",value:t.parentEmailVerified,type:"set"},{key:"creditBalanceFreeMonthly",value:a(r?.creditBalance),type:"set"},{key:"creditGivenFreeMonthly",value:a(r?.givenCredit),type:"set"},{key:"creditBalancePaidMonthly",value:a(n?.creditBalance),type:"set"},{key:"creditGivenPaidMonthly",value:a(n?.givenCredit),type:"set"},{key:"creditUsedRatio",value:x,type:"set"}])}setNewUserProperties(){const t=[],o=mA(this.cidTimestamp);o===void 0?h("amplitude.ts").warn("[Amplitude] Failed to calculate passed times, cidTimestamp : "+this.cidTimestamp+"."):t.push({key:"daysPassedAfterCidCreated",value:o.daysPassed,type:"set"},{key:"weeksPassedAfterCidCreated",value:o.weeksPassed,type:"set"},{key:"isNewCid",value:o.daysPassed<1,type:"set"});const r=mA(this.uidTimestamp);r!==void 0&&t.push({key:"uidElapsedDays",value:r.daysPassed,type:"set"}),t.length>0&&this.setUserProperties(t)}setPromotedUserProperties(){const t=Ta(It.TTV_CLICKED_BUTTON);this.setUserProperties([{key:"isPromoted",value:t,type:"once"}])}setPaidPlanProperties(){const t=be().getUserInfo()?.paidPlanInfo;if(t===void 0){this.setUserProperties([{key:"planType",value:"FREE",type:"set"}]);return}this.setUserProperties([{key:"planName",value:t.planName,type:"set"},{key:"planType",value:t.planType,type:"set"},{key:"planPeriod",value:t.period,type:"set"},{key:"paidAt",value:t.paidAt,type:"set"},{key:"expiredAt",value:t.expiredAt,type:"set"},{key:"cloudStorageLimit",value:t.cloudStorageLimit,type:"set"},{key:"price",value:t.price,type:"set"},{key:"payMethod",value:t.payMethod,type:"set"},{key:"currency",value:t.currency,type:"set"},{key:"planStatus",value:t.planStatus,type:"set"},{key:"scheduledPrice",value:t.scheduledPrice??0,type:"set"}])}disable(){j9(!0)}async event(t,o,r,n,a){const i=Date.now(),s=YN(a),x=this.getEventName(t,o,r,s);if(x===null||this.isBlacklistedEvent(t,o))return;if(this.setUserInfoProperties(),this.setNewUserProperties(),this.setPaidPlanProperties(),this.updateUserPropertyBeforeTrack(o,s),this.enabled){XS(x,{action:o,category:t,label:r,value:n,...s,projectId:se().getProjectId()??"no-project-id",projectSavedType:this.getGAProjectType()??"no-project-type",isDemo:se().isDemo(),isElectron:at(),clientType:Xo(),browserName:this.browserName,browserVersion:this.browserVersion,country:this.country,language:Fe(),isBuffered:!1});return}const l={eventName:x,props:{action:o,category:t,label:r,...s,projectId:se().getProjectId()??"no-project-id",projectSavedType:this.getGAProjectType()??"no-project-type",isDemo:se().isDemo(),isElectron:at(),clientType:Xo(),browserName:this.browserName,browserVersion:this.browserVersion,country:this.country,language:Fe(),isBuffered:!0},unixTimestampMs:i,insertId:qe.v4(),createdAt:i,expiresAt:i+EOe};await this.bufferAmplitudeEvent(l)}updateUserPropertyBeforeTrack(t,o){if(t===g.INIT_INFO){const r=new jb;
1149Object.entries(o).forEach(([n,a])=>{n!=="initTriggerType"&&r.set(n,a)}),zb(r)}else return}getEventName(t,o,r,n){return this.isCustomEventType(t,o)?this.generateCustomEventName(t,o,r,n):t+"@"+o}isCustomEventType(t,o){const r=L.get(_Oe,t);return!r||r.size===0?!1:r.has(o)}generateCustomEventName(t,o,r,n){if(t===m.AUTH&&o===g.AUTH_TRACK){const a=n.op;return a===void 0?t+"@"+o:a==="refresh"?null:t+"@"+o+"#"+a}if(t===m.PREMIUM_FEATURE){const a=t+"@"+o,i=r?"#"+r:"#"+n.triggerType;return""+a+i}return t===m.DEMO&&o===g.DEMO_LOADED&&at()?null:t+"@"+o}async updateInfo(t,o,r){const n=[],a=this.uid!==t,i="webCid"in r?r.webCid:void 0,s=i!==void 0&&this.webCid!==i;a&&(this.uid=t,this.uidTimestamp=o),"installCode"in r&&r.installCode!==void 0&&(this.installCode=r.installCode),"utmParams"in r&&(this.utmParams=r.utmParams),"webCid"in r&&r.webCid!==void 0&&(this.webCid=r.webCid),"installCode"in r&&r.installCode!==void 0&&(this.installCode=r.installCode,n.push({key:"installCode",value:this.installCode,type:"set"})),"utmParams"in r&&(this.utmParams=r.utmParams,$C.forEach(c=>{const l=this.utmParams?.[c];l&&n.push({key:c,value:l,type:"set"})})),"webCid"in r&&r.webCid!==void 0&&(this.webCid=r.webCid,n.push({key:"webCid",value:r.webCid,type:"set"})),n.length>0&&this.setUserProperties(n),(a||s)&&await this.amplitudeInitialize()}async flush(){this.enabled&&z9()}reset(){Y9()}setUserProperties(t){if(!this.enabled)return;const o=new jb;t.forEach(({key:r,value:n,type:a})=>{a==="set"&&o.set(r,n),a==="once"&&o.setOnce(r,n),a==="add"&&o.add(r,Number(n)),a==="remove"&&o.remove(r,n),a==="prepend"&&o.prepend(r,n),a==="append"&&o.append(r,n)}),zb(o)}isBlacklistedEvent(t,o){const r=L.get(gOe,t);return r?r.size===0?!0:r.has(o):!1}getGAProjectType(){const t=se();if(!t.isEmpty())return t.isDemo()?"demo":t.isProjectSaved()?"saved":"temp"}static sendVrewSurveyEvent(t,o){const r="vrew_survey@"+t,n=Object.entries(o).reduce((a,[i,s])=>(s.type==="text"||(a[i]=s.answers),a),{});XS(r,{...n,projectId:se().getProjectId()??"no-project-id",isDemo:se().isDemo(),isElectron:at()})}bufferAmplitudeEvent=async t=>{try{await _n().putValue(Bo.VREW_EVENT_DB,Ko.VREW_AMPLITUDE_EVENT,t.insertId,t)}catch(o){h("amplitude.ts").error(`
1150        Failed to buffer event to IndexedDB.
1151        Error: `+P(o)+`
1152      `)}};deleteEventsByKeys=async(t,o)=>{if(o.length!==0)try{await t.deleteValues(Bo.VREW_EVENT_DB,Ko.VREW_AMPLITUDE_EVENT,o)}catch(r){h("amplitude.ts").error(`
1153        Failed to delete events from IndexedDB.
1154        Error: `+P(r)+`
1155      `)}};deleteExpiredBufferedEvents=async(t,o,r)=>{const n=o.filter(a=>a.expiresAt<=r).map(a=>a.insertId);await this.deleteEventsByKeys(t,n)};groupEventsBySessionWindow=t=>t.reduce((o,r)=>{const n=o[o.length-1];if(!n)return o.push([r]),o;const a=n[n.length-1];return r.unixTimestampMs-a.unixTimestampMs<=gD?(n.push(r),o):(o.push([r]),o)},[]);shouldUseCurrentSessionForLatestGroup=(t,o)=>{const r=B9(),n=t[t.length-1];return!!(n&&r&&o-n[n.length-1].unixTimestampMs<=gD)};trackEventGroup=(t,o)=>{const r=t[0]?t[0].unixTimestampMs:void 0;t.forEach(n=>{XS(n.eventName,n.props,o?{time:n.unixTimestampMs,insert_id:n.insertId}:{time:n.unixTimestampMs,insert_id:n.insertId,session_id:r})})};pruneBuffered=async()=>{try{const t=_n(),o=await t.getAllValues(Bo.VREW_EVENT_DB,Ko.VREW_AMPLITUDE_EVENT);if(o.length===0)return;const r=Date.now();await this.deleteExpiredBufferedEvents(t,o,r);const n=o.filter(i=>i.expiresAt>r).sort((i,s)=>i.unixTimestampMs-s.unixTimestampMs),a=n.length-mOe;if(a>0){const i=n.slice(0,a).map(s=>s.insertId);await this.deleteEventsByKeys(t,i)}}catch(t){h("amplitude.ts").error(`
1156        [Amplitude] Unexpected error while pruning buffered events.
1157        Error: `+P(t)+`
1158      `)}};flushBuffered=async()=>{try{const t=_n(),o=await t.getAllValues(Bo.VREW_EVENT_DB,Ko.VREW_AMPLITUDE_EVENT),r=Date.now();await this.deleteExpiredBufferedEvents(t,o,r);const n=o.filter(x=>x.expiresAt>r).sort((x,c)=>x.unixTimestampMs-c.unixTimestampMs),a=this.groupEventsBySessionWindow(n),i=this.shouldUseCurrentSessionForLatestGroup(a,r);a.forEach((x,c)=>{const l=c===a.length-1,d=l&&i;this.trackEventGroup(x,d)});const s=n.map(x=>x.insertId);await this.deleteEventsByKeys(t,s)}catch(t){h("amplitude.ts").error(`
1159        [Amplitude] Unexpected error while flushing buffered events.
1160        Error: `+P(t)+`
1161      `)}};setTTVVersionProperties(){const t=be().getUserInfo();t&&this.setUserProperties([{key:"ttvVersion5ABTest",value:fOe(t.created)??"NONE",type:"set"}])}}const hOe=(e,t)=>
1161({billableDurationSec:t.durationSec??e.durationSec?.defaultValue,resolution:t.resolution??e.resolution?.defaultValue,generateAudio:t.generateAudio??e.generateAudio?.defaultValue??!1}),IOe=(e,t,o)=>{const r=o?e.videoInput:e;if(r===void 0)throw new Error("Missing GenVideo V2 video-input credit rate");if(!t)return r.audioOff;if(r.audioOn===void 0)throw new Error("Missing GenVideo V2 audio-on credit rate"+(o?" for video input":""));return r.audioOn},tE=(e,t,{generationOptions:o,hasVideoInput:r,archive:n})=>{const a=hOe(t,o);if(a.billableDurationSec===void 0)throw new Error("Missing default GenVideo duration");if(a.resolution===void 0)throw new Error("Missing default GenVideo resolution");const i=n?e.archiveRates:e.rates;if(i===void 0)throw new Error("Archive pricing is not supported");const s=i[a.resolution];if(s===void 0)throw new Error('Missing GenVideo V2 credit rate for resolution "'+a.resolution+'"');const x=a.billableDurationSec*IOe(s,a.generateAudio,r);return Math.max(1,x)},TOe={genVideoPricingChanged:!0},fst=e=>e===Ac.REGULAR_V2||e===Ac.PROMO_V2,gst=e=>{const t=e.reduce((o,r)=>{const n=r.pricingRevision===Ac.PROMO_V1||r.pricingRevision===Ac.PROMO_V2?r.promotion.originalCredits:void 0;if(n===void 0||n<=0||r.credits<0||r.credits>=n)return o;const a=(n-r.credits)/n*100;return o===void 0?a:Math.max(o,a)},void 0);return t===void 0?void 0:Math.round(t/10)*10},_st=e=>{if(!Ne(e))return!1;const t=e.errorArgs;return typeof t=="object"&&t!==null&&"genVideoPricingChanged"in t&&t.genVideoPricingChanged===!0},Est=(e,t,{generationOptions:o,hasVideoInput:r})=>{const n=t==="archive",a=n?e.archiveCredits:e.credits;if(a===void 0)throw new Error('Archive pricing is missing for genvideo model "'+e.id+'"');const i={generationOptions:o,hasVideoInput:r,archive:n};switch(e.pricingRevision){case Ac.REGULAR_V1:return n?{credits:a,isDiscounted:!0,originalCredits:e.credits}:{credits:a,isDiscounted:!1};case Ac.PROMO_V1:return{credits:a,isDiscounted:!0,originalCredits:e.promotion.originalCredits};case Ac.REGULAR_V2:{const s=tE(e.creditPricing,e.generationOptions,i);return n?{credits:s,isDiscounted:!0,originalCredits:tE(e.creditPricing,e.generationOptions,{...i,archive:!1})}:{credits:s,isDiscounted:!1}}case Ac.PROMO_V2:return{credits:tE(e.creditPricing,e.generationOptions,i),isDiscounted:!0,originalCredits:tE(e.promotion.originalCreditPricing,e.generationOptions,{...i,archive:!1})}}},mst=(e,t,o)=>({generationOptions:{...e,inputMode:t},hasVideoInput:o}),cx=(e,t)=>async(o,r,...n)=>{const a=be(),i=await a.getIdToken()??t,s=await e(o,r,i,...n);if(s.status!==403||!i||i===t)return s;let x=a.getCurrentIdToken();if(x===i){try{await a.forceRefreshIdToken()}catch(l){return h("authRequest.ts").error("reactive 403 refresh failed on "+o+" : "+P(l)),Ne(l)&&l.errorArgs.firebaseErr===fi.TOKEN_EXPIRED&&await a.signOut(!0),s}x=a.getCurrentIdToken()}if(!x)return s;const c=await e(o,r,x,...n);return c.status===403&&(h("authRequest.ts").error("reactive 403 retry rejected on "+o+", signing out"),await a.signOut(!0)),c},sa=()=>Ha();class SOe{serverConfig;constructor(){mf()?this.serverConfig={useRealServer:!0,baseUrl:"https://api-"+fr.level+".vrew.ai",baseSocketUrl:"wss://api-"+fr.level+".vrew.ai",agentServerBaseUrl:fr.level===Xr.Release?"https://vrew.ai":"https://"+fr.level+".vrew.ai"}:this.serverConfig={useRealServer:!1}}async checkIfFallbackServerNeeded(){mf()||await fetch(this.getFacadeUrl()+"/latest?_=dev").then(t=>t.text()).catch(()=>{this.serverConfig={useRealServer:!0,baseUrl:"https://api-"+Xr.Beta+".vrew.ai",baseSocketUrl:"wss://api-"+Xr.Beta+".vrew.ai",agentServerBaseUrl:"https://"+Xr.Beta+".vrew.ai"}})}getFacadeUrl(){return this.serverConfig.useRealServer?""+this.serverConfig.baseUrl:"http://"+Ba().LOCAL_SERVERS.FACADE_ADDR}getLandingUrl(){return fr.level===Xr.Release?"https://vrew.ai":this.serverConfig.useRealServer?"https://"+fr.level+".vrew.ai":"http://"+Ba().LOCAL_SERVERS.LANDING_ADDR}getLinebreakerUrl(){return this.serverConfig.useRealServer?this.serverConfig.baseUrl+"/linebreaker":"http://"+Ba().LOCAL_SERVERS.LINEBREAKER_ADDR}getOperatorUrl(){return this.serverConfig.useRealServer?this.serverConfig.baseUrl+"/operator":"http://"+Ba().LOCAL_SERVERS.OPERATOR_ADDR}getTranscriberUrl(){return this.serverConfig.useRealServer?this.serverConfig.baseUrl+"/transcriber":"http://"+Ba().LOCAL_SERVERS.TRANSCRIBER_ADDR}getDeeplearningFeaturesUrl(){return this.serverConfig.useRealServer?this.serverConfig.baseUrl+"/deeplearning":"http://"+Ba().LOCAL_SERVERS.DEEPLEARNING_FEATURES_ADDR}getCoworkUrl(){return this.serverConfig.useRealServer?this.serverConfig.baseUrl+"/cowork":"http://"+Ba().LOCAL_SERVERS.COWORK_ADDR}getAuthUrl(){return this.serverConfig.useRealServer?this.serverConfig.baseUrl+"/auth":"http://"+Ba().LOCAL_SERVERS.AUTH_ADDR}getStockUrl(){return this.serverConfig.useRealServer?this.serverConfig.baseUrl+"/stock":"http://"+Ba().LOCAL_SERVERS.STOCK_ADDR}getPaymentUrl(){return this.serverConfig.useRealServer?this.serverConfig.baseUrl+"/payment":"http://"+Ba().LOCAL_SERVERS.PAYMENT_ADDR}getPaymentSocketUrl(){return this.serverConfig.useRealServer?this.serverConfig.baseSocketUrl+"/payment/socket":"ws://"+Ba().LOCAL_SERVERS.PAYMENT_SOCKET_ADDR}getAgentServerUrl(){return this.serverConfig.useRealServer?this.serverConfig.agentServerBaseUrl+"/agent-experimental/":"http://"+Ba().LOCAL_SERVERS.AGENT_ADDR+"/agent-experimental/"}getAgentLlmModelsUrl(){return this.serverConfig.useRealServer?this.serverConfig.agentServerBaseUrl+"/agent/llm-models":"http://"+Ba().LOCAL_SERVERS.AGENT_ADDR+"/agent/llm-models"}}const hn=new SOe;(async()=>await hn.checkIfFallbackServerNeeded())();const b7=()=>{const{flags:{inhouse:e},level:t}=fr,o=e?"http":"https",r=e?"aws.v6x.team:8701":"cloud-"+t+".vrew.ai",n=e?"/"+Ba().LOCAL_SERVERS.
1161VCLOUD_BUCKET:"";return o+"://"+r+n},r_=()=>hn.getLandingUrl(),OOe=()=>hn.getPaymentSocketUrl(),hst=(e,t)=>{const o=Fe(),r=o===ce.Taiwanese?"zh-TW":o,n=sa(),a=Oo()?B1:Y1,i=[NU+"="+encodeURIComponent(n),z1+"="+encodeURIComponent(a),t&&PU+"="+encodeURIComponent(t),e&&L6+"="+window.btoa(unescape(encodeURIComponent(JSON.stringify(e))))].filter(Boolean).join("&");return hn.getLandingUrl()+"/"+r+"/signup?"+i},Ist=(e,t)=>{const o=Fe(),r=o===ce.Taiwanese?"zh-TW":o,n=sa(),a=Oo()?B1:Y1,i=[NU+"="+encodeURIComponent(n),z1+"="+encodeURIComponent(a),t&&PU+"="+encodeURIComponent(t),e&&b6+"="+encodeURIComponent(e)].filter(Boolean).join("&");return hn.getLandingUrl()+"/"+r+"/signin/oauth/google/forward?"+i},COe=(()=>{if(fr.level===Xr.Release)return hn.getLandingUrl()+"/mobile-upload/#";if(mf())return hn.getLandingUrl()+"/mobile-upload/index.html#";if(Vr())return"http://localhost:7003/#";throw new Error("Undefined stage: "+fr.level)})(),ROe=e=>""+hn.getFacadeUrl()+e,AOe=async(e,t,o,r)=>{const n=h("server.ts"),a={method:e,body:JSON.stringify(t)},i=r?r+", ":"",s="/translate-v2",x=o?wT:Pn,c=await x(s,a);if(!c.ok)throw new C(_.C_TRANSLATION_FAILED_ERROR,{},"response status: "+c.status);const l=await c.json();if(l.requestId===void 0)return l;const d=30;for(let u=0;u<d;++u){const p={...t,requestId:l.requestId},f={method:e,body:JSON.stringify(p)},E=await x(s,f),T=await me(E,_.C_TRANSLATION_FAILED_ERROR);if(T.requestId){n.info("translate "+i+"waiting "+(u+1)+"/"+d);continue}return T}throw new C(_.C_TRANSLATION_FAILED_ERROR,{},"Max retry reached. "+i+"body: "+JSON.stringify(t))},yOe=async(e,t,o)=>{const r={method:e,body:JSON.stringify(t)},n="/translate-done",a=o?wT:Pn,i=await a(n,r);return await me(i,_.C_TRANSLATION_FAILED_ERROR)},vOe=(e,t)=>{const o=""+hn.getTranscriberUrl()+e,r={"X-Version":sa()};return fetch(o,{headers:r,...t})},vT=(e,t,o)=>{const r=""+hn.getOperatorUrl()+e,n={"X-Version":sa()};return o&&(n.Authorization=o),t?.headers&&Object.assign(n,t.headers),fetch(r,{...t,headers:n})},Pn=cx(vT),$m=cx(vT,tn),lx=(e,t)=>vT(e,t),wT=(e,t)=>vT(e,t,tn),eh=(e,t)=>{const o=""+hn.getLinebreakerUrl()+e,r={"X-Version":sa()};return fetch(o,{headers:r,...t})},NT=(e,t,o,r)=>{const n={"X-Version":sa()};return o&&(n.Authorization=o),r&&Object.assign(n,r),fetch(ROe(e),{headers:n,...t})},jf=cx(NT),Tst=cx(NT,tn),si=(e,t,o)=>NT(e,t,void 0,o),Sst=(e,t)=>NT(e,t,tn),L7=async e=>await si("/latest",{method:"POST",body:JSON.stringify(e)}).then(t=>t.json()),wOe=async(e,t)=>{const o=Xo(),r=Fe(),n={clientType:o,language:r,osName:bx(),stable:t};if(e){const c=await zo(),l=await ZT();if(c&&l){const u=await fMe();n.cid=c,n.timestamp=l,n.isNewUser=u}const d=Rz();d&&(n.lastUid=d)}const a=await L7(n);let i="";switch(bx()){case HS.WINDOWS:i="windows";break;case HS.MAC:i="macos";break;case HS.Linux:i="linux";break;default:h("server.ts").error("on getLatestInfo(), Unknown platform "+bx())}const s=a[i]?.default?.version||"",x=a[i]?.default?.payload?.url||P6;return{version:s,url:x}},NOe=async()=>{const e={cid:await zo(),excludeFromStats:!0};return(await L7(e)).web?.buildTimestamp},POe=()=>hn.getFacadeUrl(),bOe=e=>{const t=new URLSearchParams;e.channel&&t.set("channel",e.channel),e.os&&t.set("os",e.os);const o=hn.getFacadeUrl()+"/download-installer",r=t.toString();return r?o+"?"+r:o},Ost=async e=>{const t=new Date().getTimezoneOffset(),o=-t,r={audioId:e,timezoneMin:o,type:"stt"};try{const n=await si("/post-transcribe",{method:"PUT",body:JSON.stringify(r)}).then(a=>a.json());n.error&&h("server.ts").error("post-transcribe internal error : "+n.error)}catch(n){h("server.ts").error("Cannot retrieve userInfo "+P(n))}},LOe=async(e,t)=>{const o=h("server.ts");if(!await wo())return o.error("getVCloudUploadProgress failed : no idToken or uid"),"EXIT";try{const r={projectId:e,pollingStartTime:t},n=await Yn("/get-vcloud-upload-progress",{method:"POST",body:JSON.stringify(r)}).then(a=>me(a,_.C_VCLOUD_UPLOAD_ERROR));return n.result==="error"?(o.error("Fail while getting vcloud upload progress projectId: "+e+", errorType: "+n.errorType+", "+n.msg),"ERROR"):n.status}catch(r){const n="getVCloudUploadProgress failed : "+P(r);return o.error(n),"ERROR"}},Cst=async e=>{const t={projectTitle:e};try{await yr(_.A_AUTH_GERNAL_ERROR,"No idToken or uid at checkDuplicateProjectTitle",h("server.ts"));const o=()=>Yn("/check-duplicate-project-title",{method:"POST",body:JSON.stringify(t)}).then(n=>
1161me(n,_.C_VCLOUD_GENERAL_ERROR)),r=await Wr(o,vn,"checkDuplicateProjectTitle");return r.result==="error"?(h("server.ts").error("Fail while checking duplicate project title, errorType: "+r.errorType+", "+r.msg),!1):r.isDuplicate}catch(o){const r="checkDuplicateProjectTitle failed : "+P(o);return h("server.ts").error(r),!1}},Nd=async(e,t,o)=>{try{const r={projectId:e,signedUrlRequest:t},n=()=>bT("/presigned-url/vcloud",{method:"POST",body:JSON.stringify(r),signal:o}).then(i=>me(i,_.C_VCLOUD_GENERAL_ERROR)),a=await Wr(n,vn,"getSignedUrlForCloudProject(projectId="+e+")",o);if(a.result==="error"){const i="Fail while getting presigned url for cloud projectId: "+e+", errorType: "+a.errorType+", "+a.msg;throw h("server.ts").error(i),new C(_.C_VCLOUD_SIGNED_URL_GENERATION_FAILED,{},i)}return a}catch(r){if(o?.throwIfAborted(),Ne(r))throw r;const n="getSignedUrlForCloudProject failed : "+P(r);throw h("server.ts").error(n),new C(_.C_VCLOUD_SIGNED_URL_GENERATION_FAILED,{},n)}},MOe=async e=>{const t=await bT("/get-cloud-project",{method:"POST",body:JSON.stringify({projectId:e})},"none").then(o=>me(o,_.C_VCLOUD_GENERAL_ERROR));if(t.result==="error")throw new C(_.C_VCLOUD_GENERAL_ERROR,{},t.msg);return{projectInfo:t.projectInfo,accessContext:t.accessContext}},DOe=async()=>{const e=Fe(),t=na.local().zoneName,o={language:e,timezone:t};try{const r=()=>Yn("/vcloud-project-list/v2",{method:"POST",body:JSON.stringify(o)}).then(a=>me(a,_.C_VCLOUD_GENERAL_ERROR)),n=await Wr(r,vn,"getCloudProjectList");if(n.result==="error"){const a="Fail while getting cloud project list, errorType : "+n.errorType+", msg: "+n.msg;throw h("server.ts").error(a),new C(_.C_VCLOUD_PROJECT_LIST_ERROR,{},a)}return{usedSpace:n.usedSpace,projectInfos:n.projects}}catch(r){if(Ne(r))throw r;const n="getCloudProjectList failed : "+P(r);throw h("server.ts").error(n),new C(_.C_VCLOUD_PROJECT_LIST_ERROR,{},n)}},ol=async e=>{try{const t=e??se().getProjectId(),o={type:"project",projectId:t},r=()=>bT("/presigned-cookie/vcloud",{method:"POST",body:JSON.stringify(o),credentials:"include",headers:{"X-Api-Version":"v2"}}).then(a=>me(a,_.C_VCLOUD_SIGNED_COOKIE_ERROR)),n=await Wr(r,vn,"getSignedCookieForCloudProject");if(n.result==="error"){const a="Fail while getting presigned cookie for cloud, errorType: "+n.errorType+", "+n.msg;throw h("server.ts").error(a),new C(_.C_VCLOUD_SIGNED_COOKIE_ERROR,{},a)}return n}catch(t){const o="getSignedCookieForCloudProject failed : "+P(t);throw h("server.ts").error(o),new C(_.C_VCLOUD_SIGNED_COOKIE_ERROR,{},o)}},M7=async(e,t)=>{const o={action:"acquire",projectId:e,sessionId:t};h("server.ts").info("[getCloudProjectSession] request: "+JSON.stringify(o)),await yr(_.A_AUTH_GERNAL_ERROR,"No idToken or uid at getCloudProjectSession",h("server.ts"));try{const r=()=>Yn("/manage-cloud-session",{method:"POST",body:JSON.stringify(o)}).then(a=>me(a,_.C_VCLOUD_GENERAL_ERROR)),n=await Wr(r,vn,"getCloudProjectSession(projectId="+e+")");if(n.result==="error"){if(n.errorType==="conflict"){const i="this cloud project is being edited by another session. cloud projectId: "+e+" and sessionId: "+t+", msg: "+n.msg;return h("server.ts").error(i),!1}const a="error while getting cloud project session: "+P(n);throw h("server.ts").error(a),new C(_.C_VCLOUD_GENERAL_ERROR,{},a)}return h("server.ts").info("getCloudProjectSession: projectId: "+e+", client sessionId: "+t),!0}catch(r){if(Ne(r))throw r;const n="error while getting cloud project session: "+P(r);throw h("server.ts").error(n),new C(_.C_VCLOUD_GENERAL_ERROR,{},n)}},kOe=async(e,t)=>{if(!await wo()){h("server.ts").error("No idToken or uid at closeEditingSession");return}const o={action:"done",projectId:e,sessionId:t};try{const r=()=>Yn("/manage-cloud-session",{method:"POST",body:JSON.stringify(o)}).then(a=>me(a,_.C_VCLOUD_GENERAL_ERROR)),n=await Wr(r,vn,"closeEditingSession(projectId="+e+")");if(n.result==="error"){if(n.errorType==="conflict"){const i="this cloud project is being edited by another session. cloud projectId: "+e+" and sessionId: "+t+", msg: "+n.msg;throw h("server.ts").error(i),new C(_.C_VCLOUD_SESSION_CONFLICT,{},i)}const a="Fail while closing editing session. projectId: "+e+", sessionId: "+t+", errorType : "+n.errorType+", msg: "+n.msg;h("server.ts").error(a);return}h("server.ts").info("[closeEditingSession] Success projectId="+e+", sessionId="+t)}catch(r){if((ye(r)===_.C_VCLOUD_SESSION_CONFLICT?_.C_VCLOUD_SESSION_CONFLICT:_.C_VCLOUD_GENERAL_ER
1161ROR)===_.C_VCLOUD_SESSION_CONFLICT){const i="this cloud project is being edited by another session. cloud projectId: "+e+" and sessionId: "+t+", msg: "+P(r);h("server.ts").error(i);return}const a="error while closing editing session: "+P(r);h("server.ts").error(a);return}},FOe=async(e,t)=>{if(!await wo()){h("server.ts").error("No idToken or uid at forceAcquireEditingSession");return}const o={action:"forceAcquire",projectId:e,sessionId:t};try{const r=()=>Yn("/manage-cloud-session",{method:"POST",body:JSON.stringify(o)}).then(a=>me(a,_.C_VCLOUD_GENERAL_ERROR)),n=await Wr(r,vn,"forceAcquireEditingSession(projectId="+e+")");if(n.result==="error"){const a="Fail while force acquiring editing session. errorType : "+n.errorType+", msg: "+n.msg;throw h("server.ts").error(a),new C(_.C_VCLOUD_GENERAL_ERROR,{},a)}return}catch(r){const n="error while force acquiring editing session: "+P(r);throw h("server.ts").error(n),new C(_.C_VCLOUD_GENERAL_ERROR,{},n)}},D7=async(e,t)=>{const o={action:"renew",projectId:e,sessionId:t};try{const r=()=>Yn("/manage-cloud-session",{method:"POST",body:JSON.stringify(o)}).then(a=>me(a,_.C_VCLOUD_GENERAL_ERROR)),n=await Wr(r,vn,"renewEditingSession(projectId="+e+")");if(n.result==="error"){if(n.errorType==="conflict"){const i="this cloud project is being edited by another session. cloud projectId: "+e+" and sessionId: "+t+", msg: "+n.msg;throw h("server.ts").error(i),new C(_.C_VCLOUD_SESSION_CONFLICT,{},i)}const a="Failed to renew editing session. projectId : "+e+", sessionId : "+t+", errorType: "+n.errorType+", msg: "+n.msg;throw h("server.ts").error(a),new C(_.C_VCLOUD_GENERAL_ERROR,{},a)}return h("server.ts").info("[renewEditingSession] Success projectId="+e+", sessionId="+t),n}catch(r){if(Ne(r))throw r;const n="Error while renewing editing session: "+P(r);throw h("server.ts").error(n),new C(_.C_VCLOUD_GENERAL_ERROR,{},n)}},PT=async(e,t)=>{const o=h("server.ts");try{const r={projectId:t,signedUrlRequests:e};await yr(_.A_AUTH_GERNAL_ERROR,"No idToken or uid at requestSignedUrls",h("server.ts"));const n=()=>Yn("/presigned-urls/vcloud",{method:"POST",body:JSON.stringify(r)}).then(i=>me(i,_.C_VCLOUD_GENERAL_ERROR)),a=await Wr(n,vn,"requestSignedUrls(projectId="+t+")");if(a.result==="error"){const i="Fail while getting presigned urls, errorType: "+a.errorType+", "+a.msg;throw h("server.ts").error(i),new C(_.C_VCLOUD_GENERAL_ERROR,{},i)}if(a.signedUrls.length!==e.length){const i="Mismatch between requested files and signed URLs returned, requested files length: "+e.length+", signed URLs length: "+a.signedUrls.length;throw h("server.ts").error(i),new C(_.C_VCLOUD_GENERAL_ERROR,{},i)}return a.signedUrls}catch(r){throw o.error("Failed to request signed URLs: "+P(r)),new C(_.C_VCLOUD_SIGNED_URL_GENERATION_FAILED,{},"Signed URL request failed")}},zf=async e=>{try{await yr(_.A_AUTH_GERNAL_ERROR,"No idToken or uid at migrateV1CloudProjectSession",h("server.ts"));const t=()=>Yn("/migrate-v1-cloud-project-session",{method:"POST",body:JSON.stringify(e)}).then(r=>me(r,_.C_VCLOUD_GENERAL_ERROR)),o=await Wr(t,vn,"migrateV1CloudProjectSession");if(o.result==="error"){const r="Fail while migrating v1 cloud project session. errorType : "+o.errorType+", msg: "+o.msg;if(h("server.ts").error(r),e.action==="error")return{result:"error",errorType:o.errorType,msg:r};throw new C(_.C_VCLOUD_MIGRATE_PROJECT_ERROR)}return o}catch(t){const o=ye(t)??_.C_VCLOUD_MIGRATE_PROJECT_ERROR,r="error while migrating v1 cloud project session: "+P(t);throw h("server.ts").error(r),new C(o)}},gA=async e=>{try{await yr(_.A_AUTH_GERNAL_ERROR,"No idToken or uid at createCloudProjectUploadSession",h("server.ts"));const t=()=>Yn("/vcloud-project-upload-session/create-v2",{method:"POST",body:JSON.stringify(e)}).then(r=>me(r,_.C_VCLOUD_GENERAL_ERROR)),o=await Wr(t,vn,"createCloudProjectUploadSessionV2");if(o.result==="error"){const r="Failed to create upload session due to an error. errorType : "+o.errorType+", msg : "+JSON.stringify(o.msg);throw h("server.ts").error(r),new C(_.C_VCLOUD_UPLOAD_SESSION_CREATION_FAILED,{},r)}return o}catch(t){if(Ne(t))throw t;const o="createCloudProjectUploadSession failed : "+P(t);
1161throw h("server.ts").error(o),new C(_.C_VCLOUD_UPLOAD_SESSION_CREATION_FAILED,{},o)}},_A=async({projectId:e,totalSize:t})=>{try{await yr(_.A_AUTH_GERNAL_ERROR,"No idToken or uid at finishCloudProjectUploadSession",h("server.ts"));const o={projectId:e,totalSize:t,version:Uf},r=()=>Yn("/vcloud-project-upload-session/finish",{method:"POST",body:JSON.stringify(o)}).then(a=>me(a,_.C_VCLOUD_GENERAL_ERROR)),n=await Wr(r,vn,"finishCloudProjectUploadSession(projectId="+e+")");if(n.result==="error"){const a="Fail while finishing upload session. errorType : "+n.errorType+", msg: "+n.msg;throw h("server.ts").error(a),new C(_.C_VCLOUD_UPLOAD_ERROR,{},a)}return n}catch(o){if(Ne(o))throw o;const r="finishCloudProjectInfo failed : "+P(o);throw h("server.ts").error(r),new C(_.C_VCLOUD_UPLOAD_ERROR,{},r)}},UOe=async e=>{try{await yr(_.A_AUTH_GERNAL_ERROR,"No idToken or uid at getCloudProjectDownloadInfo",h("server.ts"));const t={projectId:e},o=()=>Yn("/vcloud-project-download-info",{method:"POST",body:JSON.stringify(t)}).then(n=>me(n,_.C_VCLOUD_GENERAL_ERROR)),r=await Wr(o,vn,"getCloudProjectDownloadInfo(projectId="+e+")");if(r.result==="error"){const n="Fail while getting download info. errorType : "+r.errorType+", msg: "+r.msg;throw h("server.ts").error(n),new C(_.C_VCLOUD_DOWNLOAD_INFO_ERROR,{},n)}return{result:"success",downloadInfo:r.downloadInfo}}catch(t){const o=ye(t)??_.C_VCLOUD_DOWNLOAD_INFO_ERROR,r="getCloudProjectDownloadInfo failed : "+P(t);return h("server.ts").error(r),{result:"error",errorCode:o,msg:r}}},_D=async e=>{try{await yr(_.A_AUTH_GERNAL_ERROR,"No idToken or uid at deleteCloudProject",h("server.ts"));const t={projectId:e},o=()=>Yn("/delete-vcloud",{method:"POST",body:JSON.stringify(t)}).then(n=>me(n,_.C_VCLOUD_GENERAL_ERROR)),r=await Wr(o,vn,"deleteCloudProject(projectId="+e+")");if(r.result==="error"){const n="Fail while deleting cloud project. errorType : "+r.errorType+", msg: "+r.msg;throw h("server.ts").error(n),r.errorType==="conflict"?new C(_.C_VCLOUD_SESSION_CONFLICT):new C(_.C_VCLOUD_DELETE_ERROR)}return}catch(t){if(Ne(t))throw t;const o="deleteCloudProject failed : "+P(t);throw h("server.ts").error(o),new C(_.C_VCLOUD_DELETE_ERROR,{},o)}},BN=async e=>{try{const t={projectId:e},o=()=>bT("/update-vcloud-project-donwload-cnt",{method:"POST",body:JSON.stringify(t)}).then(a=>me(a,_.C_VCLOUD_GENERAL_ERROR)),r=await Wr(o,vn,"updateVCloudProjectDownloadCnt(projectId="+e+")");if(r.result==="success"){h("server.ts").info("updateVCloudProjectDownloadCnt success");return}const n="Fail while updating download count. errorType : "+r.errorType+", msg: "+r.msg;h("server.ts").error(n);return}catch(t){const o=ye(t)??_.C_VCLOUD_DOWNLOAD_ERROR,r="updateVCloudProjectDownloadCnt failed : "+P(t)+", errCode: "+o;h("server.ts").error(r);return}},VOe=async(e,t,o)=>{try{await yr(_.A_AUTH_GERNAL_ERROR,"No idToken or uid at updateVCloudProjectSnapshot",h("server.ts"));const r={projectId:e,snapshotId:t,totalSize:o},n=()=>Yn("/update-vcloud-project-snapshot",{method:"POST",body:JSON.stringify(r)}).then(s=>me(s,_.C_VCLOUD_GENERAL_ERROR)),a=await Wr(n,vn,"updateVCloudProjectSnapshot(projectId="+e+", snapshotId="+t+")");if(a.result==="success")return h("server.ts").info("update vcloud project snapshot for projectId : "+e+", snapshotId : "+t+" success"),!0;const i="Fail while updating snapshot. errorType : "+a.errorType+", msg: "+a.msg+". projectId: "+e+", snapshotId: "+t+", totalSize: "+o;return h("server.ts").error(i),!1}catch(r){const n=ye(r)??_.C_VCLOUD_UPLOAD_ERROR,a="updateVCloudProjectSnapshot failed : "+P(r)+", errCode: "+n;return h("server.ts").error(a),!1}},GOe=async(e,t)=>{try{await yr(_.A_AUTH_GERNAL_ERROR,"No idToken or uid at updateVCloudProjectTitle",h("server.ts"));const o={projectId:e,projectTitle:t},r=()=>Yn("/update-vcloud-project-title",{method:"POST",body:JSON.stringify(o)}).then(i=>me(i,_.C_VCLOUD_GENERAL_ERROR)),n=await Wr(r,vn,"updateVCloudProjectTitle(projectId="+e+")");if(n.result==="success"){h("server.ts").info("update vcloud project title for projectId : "+e+", projectTitle : "+t+" success");return}const a="Fail while updating project title. errorType : "+n.errorType+", msg: "+n.msg+". projectId: "+e+", projectTitle: "+t;throw h("server.ts").error(a),n.errorType==="conflict"?new C(_.C_VCLOUD_SESSION_CONFLICT):new C(_.C_VCLOUD_PROJECT_TITLE_UPDATE_FAILED,{},a)}catch(o){const r=ye(o)??_.C_VCLOUD_PROJECT_TITLE_UPDATE_FAILED,n="updateVCloudProjectTitle failed : "+P(o)+", errCode: "+r;throw h("server.ts").error(n),new C(r,{},n)}},JO=async e=>{try{await yr(_.A_AUTH_GERNAL_ERROR,"No idToken or uid at handleVCloudUploadError",h("server.ts"));const t=()=>Yn("/handle-vcloud-upload-error",{method:"POST",body:JSON.stringify(e)}).then(r=>
1161me(r,_.C_VCLOUD_GENERAL_ERROR)),o=await Wr(t,vn,"handleVCloudUploadError(projectId="+e.projectId+")");if(o.result==="error"){const r="Fail while handling upload error. errorType : "+o.errorType+", msg: "+JSON.stringify(o.msg);h("server.ts").error(r);return}h("server.ts").info("success to handle upload error for projectId : "+e.projectId);return}catch(t){const o=ye(t)??_.C_VCLOUD_UPLOAD_ERROR,r="handleUploadErrorForCloud failed : "+P(t)+", errCode: "+o;h("server.ts").error(r);return}},k7=async()=>{try{if(!Oo())return;await yr(_.A_AUTH_GERNAL_ERROR,"No idToken or uid at recoverVcloudProjects",h("server.ts"));const e=()=>Yn("/recover-vcloud-projects",{method:"POST"}).then(o=>me(o,_.C_VCLOUD_GENERAL_ERROR)),t=await Wr(e,vn,"recoverVcloudProjects");if(t.result==="error"){const o="Fail while recovering vcloud projects. errorType : "+t.errorType+", msg: "+t.msg;h("server.ts").error(o);return}return}catch(e){const t=ye(e)??_.C_VCLOUD_UPLOAD_ERROR,o="recoverVcloudProjects failed : "+P(e)+", errCode: "+t;h("server.ts").error(o);return}},F7=async()=>{try{if(!Oo())return;if(!await wo()){h("server.ts").error("No idToken or uid at cleanUpOldVCloudProjectSnapshots");return}const e=()=>Yn("/clean-up-old-vcloud-project-snapshots",{method:"POST"}).then(o=>me(o,_.C_VCLOUD_CLEAN_UP_OLD_PROJECT_SNAPSHOTS_FAILED)),t=await Wr(e,vn,"cleanUpOldVCloudProjectSnapshots");if(t.result==="error"){const o="Fail while cleaning up old vcloud project snapshots. errorType : "+t.errorType+", msg: "+t.msg;h("server.ts").error(o);return}return}catch(e){const t=ye(e)??_.C_VCLOUD_CLEAN_UP_OLD_PROJECT_SNAPSHOTS_FAILED,o="cleanUpOldVCloudProjectSnapshots failed : "+P(e)+", errCode: "+t;h("server.ts").error(o);return}},Rst=async(e,t,o=1)=>{try{const r=await qo("/stock-images/?query="+e+"&page="+o+"&locale="+t,{method:"GET"}).then(n=>{if(!n.ok)throw h("server.ts").error("Search stock image response not ok. status: "+n.status+", statusText: "+n.statusText),new C(_.C_IMAGE_SEARCH_ERROR);return n.json()});if(r.error||r.errorMessage||!r.images)throw h("server.ts").error("search stock image response is malformed. error: "+r?.error+", result.images:"+r?.images+" result:"+r),new C(_.C_IMAGE_SEARCH_ERROR,{},r.error);return r.images}catch(r){return h("server.ts").error("error occured while getting stock images:"+P(r)),[]}},WOe=async e=>{const t=await qo("/search-web-fonts",{method:"POST",headers:{"X-Version":sa()},body:JSON.stringify({lang:e})}).then(o=>o.ok?o.json():{freeFonts:[]});if(!t||t.errorMessage)throw new C(_.C_GET_WEBFONT_FAIL,{});return t.freeFonts},U7=async e=>{if(!await wo())throw new Error("recommendStockMusics requires authenticated user.");const t=await bn("/stock-music-recommendations",{method:"POST",body:JSON.stringify(e)},{"Content-Type":"application/json"}).then(async o=>o.ok?o.json():{result:"error",recommendations:[],error:"Stock music recommendations status: "+o.status+", statusText: "+o.statusText});if(t.result==="error")throw h("server.ts").error("recommendStockMusics failed: "+t.error),new Error(t.error);return t},Ast=async(e,t)=>(await U7(t!==void 0?{query:e,limit:t}:{query:e})).recommendations,yst=async(e,t)=>{if(!await wo())throw new Error("recommendStockSoundEffects requires authenticated user.");const o=await bn("/stock-sound-effect-recommendations",{method:"POST",body:JSON.stringify(t!==void 0?{query:e,limit:t}:{query:e})},{"Content-Type":"application/json"}).then(async r=>r.ok?r.json():{result:"error",recommendations:[],error:"Stock sound effect recommendations status: "+r.status+", statusText: "+r.statusText});if(o.result==="error")throw h("server.ts").error("recommendStockSoundEffects failed: "+o.error),new Error(o.error);return o.recommendations},vst=async(e,t)=>{const o=Fe(),r=await U7({projectText:e,language:o});return{query:r.query,recommendations:r.recommendations}},HOe=async e=>{const t=await qo("/search-textboxes",{method:"POST",body:JSON.stringify({id:e})}).then(o=>o.ok?o.json():(h("server.ts").error("textbox search result not ok. status: "+o.status+", statusText: "+o.statusText),{content:[]}));if(!t||t.errorMessage)throw new C(_.C_GET_WEBFONT_FAIL,{});return t},jOe=async()=>
1161{const e=h("server.ts"),t=Fe(),o=await Ui("/search-characters-v4?language="+t,{method:"GET",credentials:"include"}).then(r=>me(r,_.C_CHARACTER_NETWORK_ERROR));if(o.status==="error"){const r="error occured while getting characterInfo, "+JSON.stringify(o);throw e.error(r),new C(_.C_CHARACTER_NETWORK_ERROR,{},r)}return o.result},zOe=async()=>{const e=await qo("/stock-shapes-v2",{method:"get"}).then(t=>t.ok?t.json():(h("server.ts").error("shape search result not ok."),{framePack:[],presets:[]}));if(!e||e.errorMessage)throw new C(_.C_SHAPE_SEARCH_ERROR,{});{const t=e.presets.map(Yce);return{templates:e.templates,presets:t}}},YOe=async(e,t)=>{try{if(e.trim().length===0)return{};const o=await fetch(hn.getOperatorUrl()+"/get-noun",{method:"POST",body:JSON.stringify({text:e,locale:t})}).then(r=>{if(!r.ok)throw h("server.ts").error("get noun response not ok. status: "+r.status+", statusText: "+r.statusText),new C(_.C_IMAGE_SEARCH_ERROR);return r.json()});return o.error||!o.wordMap?{}:o.wordMap}catch(o){return h("server.ts").error("error occured while getting noun:"+P(o)),{}}},BOe=async()=>{try{const e=await qo("/stock-musics?version=v4",{method:"GET"}).then(t=>{if(!t.ok)throw h("server.ts").error("Stock bgm list status: "+t.status+", statusText: "+t.statusText),new C(_.C_BGM_ERROR);return t.json()});if(e.error||e.errorMessage)throw new C(_.C_BGM_ERROR,{},e.error);return e}catch(e){return h("server.ts").error("error occured while getting stock musics:"+P(e)),null}},ED=async()=>{try{const e=await lx("/tts-voice-list-v2",{method:"GET"}),t=await me(e,_.C_TTS_FETCH_SPEAKER_LIST_ERROR);if(t.result)return _re(t.result),t.result;if(t.error)throw h("server.ts").error("Error occurred when fetching stock speaker list: "+t.error.msg),new C(_.C_TTS_FETCH_SPEAKER_LIST_ERROR,{},t.error.msg);return h("server.ts").warn("Unexpected response format when fetching speaker list."),void 0}catch(e){return h("server.ts").error("Failed to fetch stock speaker list: "+P(e)),void 0}},KOe=async()=>{try{const e=await Pn("/tts-discounts",{method:"GET"}).then(t=>me(t,_.C_TTS_FETCH_SPEAKER_LIST_ERROR));return e.result==="error"?(h("server.ts").warn("Failed to fetch TTS discounts: "+e.msg),void 0):e}catch(e){return h("server.ts").warn("Failed to fetch TTS discounts: "+P(e)),void 0}},wst=async(e,t)=>{const o=await $m("/search-ai-voices",{method:"POST",body:JSON.stringify(e),signal:t,headers:{"Content-Type":"application/json"}}),r=await me(o,_.C_TTS_AI_VOICE_SEARCH_ERROR);if(r.result==="error"){const n="searchAIVoices failed: "+r.error;throw h("server.ts").error(n),new C(_.C_TTS_AI_VOICE_SEARCH_ERROR,{},n)}return{results:r.results,matchType:r.matchType}},XOe=async()=>{try{return await qo("/tts-speaker-img-prefix",{method:"GET"}).then(async e=>{if(e.ok)return(await e.json()).prefix;throw h("server.ts").error("Network error: Failed to fetch speaker image prefix: "+e.statusText),new C(_.C_TTS_NETWORK_ERROR)})}catch(e){return h("server.ts").error("Failed to fetch speaker image prefix: "+P(e)),""}},JOe=async()=>{try{const e=await qo("/sound-effects",{method:"GET",headers:{"X-Version":sa()}}).then(t=>{if(!t.ok)throw h("server.ts").error("Stock sound effect list status: "+t.status+", statusText: "+t.statusText),new C(_.C_SOUND_EFFECT_ERROR);return t.json()});if(e.error||e.errorMessage)throw new C(_.C_SOUND_EFFECT_ERROR,{},e.error);return e}catch(e){return h("server.ts").error("error occured while getting stock sound effects:"+P(e)),void 0}},Nst=async()=>{const e=h("server.ts");try{const t={clientType:Xo(),osName:bx(),osVersion:iU()},o=await si("/get-support-policy",{method:"POST",body:JSON.stringify(t)});if(!o.ok){e.warn("Error fetching support policy : "+o.status);return}const r=await o.json();if(r.error){e.warn("Error fetching support policy : "+r.error);return}return r.policy}catch(t){e.error("Error during fetch support policy : "+P(t))}},Pst=async e=>{const t=h("server.ts");try{const o={lastChecked:e},r=await si("/get-banner-info",{method:"POST",body:JSON.stringify(o)});if(!r.ok){t.warn("Error fetching banner info : "+r.status);return}const n=await r.json();if(n.error){t.warn("Error fetching Banner Info : "+n.error);return}if(n.info?.banners&&!ZCe(n.info.banners)){t.warn("Incorrect banner format : "+JSON.stringify(n.info.banners));return}return n.info}catch(o){const r="Error during fetch Banner Info : "+P(o);h("server.ts").error(r)}},qOe=async(e,t,o=1,r=!1,n=!1,a,i)=>{const s=h("server.ts");try{const x=a?cr(a):void 0,c=["query="+e,"page="+o,"locale="+t,"cache_only="+(r?1:0),"select_one="+(n?1:0),x?"video_ratio="+x:""].join("&"),l=await qo("/stock-videos/?"+c,{method:"GET",signal:i}).then(d=>{if(!d.ok){const u="/stock-videos response: "+d.status;throw s.error(u),new C(_.C_ASSET_VIDEO_SEARCH_ERROR,{},u)}return d.json()});if(l.error||l.errorMessage||!l.videos)throw h("server.ts").error("search stock video response is malformed. error: "+l?.error+", result.videos:"+l?.videos+" result:"+l),new C(_.C_ASSET_VIDEO_SEARCH_ERROR,{},l.error);return l.videos}catch(x){return no(x)?(h("server.ts").info("stock video search cancelled by user"),[]):(h("server.ts").error("error occured while getting stock videos:"+P(x)),[])}},Yf=(e,t,o,r)=>{switch(e){case"low_version":return new C(_.C_APP_VERSION_IS_LOW,{version:sa()},t);case"device_too_many_free_account":return new C(_.C_DEVICE_TOO_MANY_FREE_ACCOUNT,{},t);case"content_filtered":case"NSFW_content_detected":return r?new C(_.C_VIDEO_CONTENT_FILTERED,{},t):new C(_.C_NSFW_CONTENT_DETECTED,{},t);case"real_person_filtered":return r?new C(_.C_VIDEO_CONTENT_FILTERED_PE
1161RSON,{},t):new C(_.C_NSFW_CONTENT_DETECTED,{},t);case"timeout":return o?new C(_.C_RAY_DIFFUSION_SERVER_WAITING):new C(r?_.C_VIDEO_GENERATION_NETWORK_ERROR:_.C_IMAGE_GENERATION_NETWORK_ERROR,{},t);case"pricing_changed":return new C(r?_.C_VIDEO_GENERATION_ERROR:_.C_IMAGE_GENERATION_ERROR,r?TOe:{},t);default:return new C(r?_.C_VIDEO_GENERATION_ERROR:_.C_IMAGE_GENERATION_ERROR,{},t)}},bst=async()=>{const e=h("server.ts"),t=be(),o=t.getUserInfo()?.uid;if(!await wo()||!o){const r="No idToken or uid at request unsubscribe payment";throw e.error(r),new C(_.C_LOGIC_ERROR,{},r)}try{const r=await dx("/unsubscribe-payment",{method:"POST",body:JSON.stringify({uid:o})}).then(n=>{if(!n.ok){const a="Error handle unsubscribe : "+n.status;throw new C(_.C_PAYMENT_NETWORK_ERROR,{},a)}return n.json()});if(r.error){const n="cannot handle unsubscribe, "+JSON.stringify(r.error);e.error(n);const a=wd(r.error.code);throw new C(a,{},n)}return}catch(r){const n="error occured while unsubscribe payment :"+P(r);e.error(n);const a=ye(r)??_.C_PAYMENT_UNSUBSCRIBE_ERROR,i=Ot(a,{defaultKey:"error.payment_unsubscribe_error",errorArg:Ho(r)});throw Y().error(a,i),r}},Lst=async()=>{const e=h("server.ts"),t=be(),o=t.getUserInfo()?.uid;if(!await wo()||!o){const r="No idToken or uid at request reschedule payment";throw e.error(r),new C(_.C_LOGIC_ERROR,{},r)}try{const r=await dx("/reschedule-payment",{method:"POST",body:JSON.stringify({uid:o,isSubscriptionConsent:!1,requestedBy:"user"})}).then(n=>{if(!n.ok){const a="Error handle reschedule : "+n.status;throw new C(_.C_PAYMENT_NETWORK_ERROR,{},a)}return n.json()});if(r.result==="error"){const n="cannot handle reschedule, errorCode: "+r.errorCode+", errorMsg: "+r.errorMsg;throw e.error(n),new C(_.C_PAYMENT_RESCHEDULE_ERROR,{},n)}return}catch(r){const n="error occured while reschedule payment :"+P(r);e.error(n);const a=ye(r)??_.C_PAYMENT_RESCHEDULE_ERROR,i=Ot(a,{defaultKey:"error.payment_reschedule_error",errorArg:Ho(r)});throw Y().error(a,i),r}},V7=async(e=!1)=>{const t=h("server.ts"),o=await zo(),r=be(),n=r.getUserInfo(),a=n?.uid;if(!await wo()||!a){const s="No idToken or uid at createInitPayment";throw new C(_.C_LOGIC_ERROR,{},s)}const i=Xo();try{const s={uid:a,cid:o,isChangeCard:e,clientType:i},x=await dx("/create-init-payment",{method:"POST",body:JSON.stringify(s)}).then(c=>{if(!c.ok){const l="response status: "+c.status;throw new C(_.C_PAYMENT_NETWORK_ERROR,{},l)}return c.json()});if(x.error){const c="cannot create init payment, "+JSON.stringify(x.error),l=wd(x.error.code);throw new C(l,{},c)}if(!x.guid){const c="No guid from response: "+JSON.stringify(x)+"}";throw t.error(c),new C(_.C_PAYMENT_GENERAL_ERRROR,{},c)}return{guid:x.guid,sessionId:x.sessionId}}catch(s){h("server.ts").error("An error occured at createInitPayment. isChageCard: "+e+". error: "+P(s));const x=ye(s)??_.C_PAYMENT_GENERAL_ERRROR;if(n&&x===_.C_PAYMENT_USER_VERIFICATION_NEEDED){My(n);return}const c=Ot(x,{defaultKey:"error.payment_general_error",errorArg:Ho(s)});Y().error(x,c);return}},Mst=async()=>{const e=await zo(),t=be(),o=t.getUserInfo()?.uid;if(!await wo()||!o){const n="No idToken or uid at createInitPayment";throw new C(_.C_LOGIC_ERROR,{},n)}const r=Xo();try{const n={uid:o,cid:e,clientType:r},a=await dx("/create-init-user-refund",{method:"POST",body:JSON.stringify(n)}).then(i=>{if(!i.ok){const s="response status: "+i.status;throw new C(_.C_PAYMENT_NETWORK_ERROR,{},s)}return i.json()});if(a.error){const i="cannot create init payment, "+JSON.stringify(a.error),s=wd(a.error.code);throw new C(s,{},i)}return a.guid}catch(n){h("server.ts").error("An error occured at createInitUserRefund. error: "+P(n));const a=ye(n)??_.C_PAYMENT_GENERAL_ERRROR,i=Ot(a,{defaultKey:"error.payment_general_error",errorArg:Ho(n)});Y().error(a,i);return}},QOe=async()=>{const e=h("server.ts"),t=await zo(),o=be(),r=o.getUserInfo()?.uid;if(!await wo()||!r){const a="No idToken or uid at createInitUsageEraser";throw new C(_.C_LOGIC_ERROR,{},a)}const n=Xo();try{const a={uid:r,cid:t,clientType:n},i=await dx("/create-init-usage-eraser",{method:"POST",body:JSON.stringify(a)}).then(s=>{if(!s.ok){const x="response status: "+s.status;
1161throw new C(_.C_PAYMENT_NETWORK_ERROR,{},x)}return s.json()});if(i.error){const s="cannot create init usage eraser, "+JSON.stringify(i.error),x=wd(i.error.code);throw new C(x,{},s)}if(!i.guid){const s="No guid from response: "+JSON.stringify(i)+"}";throw e.error(s),new C(_.C_PAYMENT_GENERAL_ERRROR,{},s)}return i.guid}catch(a){h("server.ts").error("An error occured at createInitUsageEraser. error: "+P(a));const i=ye(a)??_.C_PAYMENT_GENERAL_ERRROR,s=Ot(i,{defaultKey:"error.payment_general_error",errorArg:Ho(a)});Y().error(i,s);return}},ZOe=async()=>{const e=h("server.ts"),t=await zo(),o=be(),r=o.getUserInfo(),n=r?.uid;if(!await wo()||!n){e.error("No idToken or uid at getPaymentPreregistrationInfo");return}const a=Xo();try{const i={uid:n,cid:t,clientType:a},s=await dx("/create-init-plan-upgrade",{method:"POST",body:JSON.stringify(i)}).then(x=>{if(!x.ok){const c="Error response at createInitPlanUpgrde. status: "+x.status;throw new C(_.C_PAYMENT_NETWORK_ERROR,{},c)}return x.json()});if(s.error||!s.guid||!s.planUpgradeData){const x="An error occurred at createInitPlanUpgrade , "+JSON.stringify(s.error);e.error(x);const c=wd(s.error?.code);throw new C(c,{},x)}return{guid:s.guid,planUpgradeData:s.planUpgradeData,sessionId:s.sessionId}}catch(i){h("server.ts").error("An error occured at createInitPlanUpgrade. error: "+P(i));const s=ye(i)??_.C_PAYMENT_GENERAL_ERRROR;if(r&&s===_.C_PAYMENT_USER_VERIFICATION_NEEDED){My(r);return}const x=Ot(s,{defaultKey:"error.payment_general_error",errorArg:Ho(i)});Y().error(s,x);return}},Dst=async e=>{const t={guid:e};try{const o=await Zs("/user-refund-info",{method:"post",body:JSON.stringify(t)}),r=await me(o,_.C_PAYMENT_NETWORK_ERROR);if(r.result===void 0){const n="no result from userRefundInfo";throw new C(_.C_PAYMENT_GENERAL_ERRROR,{},n)}return r.result}catch(o){h("server.ts").error("fail to request user refund session info to auth server "+P(o)+", guid: "+e);return}},G7=(e,t,o)=>{const r=""+hn.getCoworkUrl()+e,n={"X-Version":sa()};return o&&(n.Authorization=o),fetch(r,{...t,headers:{...n,...t?.headers}})},$Oe=cx(G7),bT=async(e,t,o="idToken")=>{const r=Lt(),n=r.getSharedToken();if(!n)return o==="none"?G7(e,t):$Oe(e,t);const a=""+hn.getCoworkUrl()+e,i={"X-Version":sa(),Authorization:n},s=await fetch(a,{...t,headers:{...i,...t?.headers}});if(s.status!==403)return s;const x=r.getTemporalProjectId();if(!x)return s;await W7(x);const c={"X-Version":sa()},l=r.getSharedToken();return c.Authorization=l??be().getCurrentIdToken(),fetch(a,{...t,headers:{...c,...t?.headers}})},W7=async e=>{const t=await h0("/issue-share-token",{method:"POST",body:JSON.stringify({projectId:e})}).then(o=>me(o,_.C_VCLOUD_GENERAL_ERROR));if(t.result!=="success"){const o="Failed to issue shared token: "+t.errorType+", "+t.msg;throw new C(_.C_VCLOUD_GENERAL_ERROR,{},o)}return Lt().setSharedToken(t.token)},H7=(e,t,o)=>{const r=""+hn.getCoworkUrl()+e,n={"X-Version":sa()};return o&&(n.Authorization=o),fetch(r,{...t,headers:{...n,...t?.headers}})},Yn=cx(H7),h0=(e,t)=>H7(e,t),KN=(e,t,o)=>{const r=""+hn.getAuthUrl()+e,n={"X-Version":sa()};return o&&(n.Authorization=o),fetch(r,{headers:n,...t})},F2=cx(KN),Zs=(e,t)=>KN(e,t),mD=(e,t,o)=>KN(e,t,o),XN=(e,t,o,r)=>{const n=""+hn.getStockUrl()+e,a={"X-Version":sa()};return r&&Object.assign(a,r),o&&(a.Authorization=o),fetch(n,{headers:a,...t})},bn=cx(XN),Ui=cx(XN,tn),qo=(e,t,o)=>XN(e,t,void 0,o),eCe=(e,t,o)=>{const r=""+hn.getPaymentUrl()+e,n={"X-Version":sa()};return o&&(n.Authorization=o),fetch(r,{headers:n,...t})},dx=cx(eCe),hD=async(e,t)=>{const o=e.engine??Tc.SDXL;try{const r=await Ui("/make-genimage",{method:"POST",body:JSON.stringify(e),signal:t}),n=await me(r,_.C_IMAGE_GENERATION_ERROR);if(n.result==="error")throw h("server.ts").error("One or more "+o+` images were not generated successfully.
1162      requestBody: `+JSON.stringify(e)),Yf(n.errorType,n.errorMsg,"forceVrewServer"in e&&e.forceVrewServer===!0);return n.reqId}catch(r){throw no(r)?(h("server.ts").info("make-genimage cancelled by user"),r):Ne(r)?r:(h("server.ts").error("An unexpected error occured while makeGenimage : "+P(r)),new C(_.C_IMAGE_GENERATION_ERROR,{},P(r)))}},tCe=async(e,t)=>{try{const o=await Ui("/get-genimage?reqId="+e,{method:"GET",signal:t});return await me(o,_.C_IMAGE_GENERATION_ERROR)}catch(o){throw no(o)?(h("server.ts").info("get-genimage cancelled by user"),o):Ne(o)?o:(h("server.ts").error("An unexpected error occured while getGenimage : "+P(o)),new C(_.C_IMAGE_GENERATION_ERROR,{},P(o)))}},kst=async(e,t,o,r,n)=>{try{const a={type:"base_image",numPrompt:t,userText:e,style:o,engine:n,...r&&r.length>0?{referenceImageUrls:r}:{}},i=await qo("/generate-genimage-prompt",{method:"POST",body:JSON.stringify(a)}),s=await me(i,_.C_PROMPT_GENERATION_ERROR);switch(s.result){case"success":{const{prompt:x}=s;return x}case"error":throw h("server.ts").error(`Error occured while generating prompt:
1163          errorType: `+s.errorType+`
1164          errorMsg: `+s.errorMsg),new C(_.C_PROMPT_GENERATION_ERROR)}}catch(a){throw Ne(a)?a:(h("server.ts").error("Network error occured while getChatToGenimageBasePrompt : "+P(a)),new C(_.C_PROMPT_GENERATION_ERROR,{},P(a)))}},oCe=e=>e.startsWith("data:")?e:"data:image/jpeg;base64,"+e,rCe=async e=>{if("b64Image"in e)return{type:"base64",b64Image:oCe(e.b64Image),prompt:e.prompt,provider:e.provider};const t=await fetch(e.imageUrl);if(!t.ok){const o="Failed to fetch generated image from signed URL: "+t.status+" "+t.statusText;throw h("server.ts").error(o),new C(_.C_IMAGE_GENERATION_ERROR,{},o)}return{type:"base64",b64Image:await V2(await t.blob()),prompt:e.prompt,provider:e.provider}},qO={[Yi.AI_IMAGE_MODAL]:"express",[Yi.THUMBNAIL_GENERATOR]:"express",[Yi.CHARACTER_STUDIO]:"express",[Yi.TTV_MODAL]:"default",[Yi.VIDEO_REMIX_MODAL]:"default",[Yi.AI_AUTO_INSERTION_CONTEXT]:"default",[Yi.AI_AUTO_INSERTION_PANEL]:"default",[Yi.AI_AUTO_INSERTION_STT_MODAL]:"default",[Yi.GENERATE_VIDEO_MODAL]:"default",[Yi.AGENT_IMAGE]:"default",[Yi.AGENT_VIDEO]:"default"}
1164,nCe=async(e,t)=>{Us(Xt.GEN_ASSET_FORCE_FAIL);const o=be().getUserInfo()?.uid??tn,r=await zo(),{deviceId:n,deviceName:a,machineId:i}=await Ia(),s=Xo(),x=Mo().getDebugVal(Xt.FORCE_IMAGEGEN_VREWSERVER)!==void 0,c=Vr(),l=new Date().getTime(),d=e.engine,u=$e().getGenImageModels().find(R=>R.id===d)?.capabilities,p=!!e.isHighResolutionOn&&(u?.includes("high_resolution")??!1),f=u?.includes("reference_image")??!1,E=d===Tc.SDXL?await hD({prompts:e.prompts,width:e.width,height:e.height,highResolution:p,uid:o,cid:r,deviceId:n,clientType:s,deviceName:a,machineId:i,provider:e.provider??rR.VREW,forceVrewServer:x,engine:d,returnFilekey:c,returnType:"url",lane:qO[e.trigger]},t):await hD({prompts:e.prompts,engine:d,width:e.width,height:e.height,highResolution:p,uid:o,cid:r,deviceId:n,clientType:s,deviceName:a,machineId:i,returnFilekey:c,returnType:"url",...d===Tc.FLUX_2_KLEIN?{lane:qO[e.trigger],forceVrewServer:x}:{},...f&&"referenceImageUrls"in e&&e.referenceImageUrls?{referenceImageUrls:e.referenceImageUrls}:{}},t);let T=!0,O=0,S=rR.VREW;try{const w=Math.ceil(19),N=Math.ceil(250/10),M=f&&"referenceImageUrls"in e&&Array.isArray(e.referenceImageUrls)&&e.referenceImageUrls.length>0,k=d===Tc.SDXL&&qO[e.trigger]==="express",F=M||p,G=F?N:k?5:w;for(let B=0;B<G;B++){if(t?.aborted)throw new DOMException("generateImages aborted","AbortError");const W=await tCe(E,t);switch(W.status){case"done":{const{images:Q,errors:j,sid:$}=W,q=await Promise.all(Q.map(rCe)),H=[];return j&&j.forEach(U=>{H.push(Yf(U.errorType,U.errorMsg,x))}),Us(Xt.NSFW_IMAGE_FAIL)&&Math.random()<.5,e.postGenimageUsage&&$&&(t?.aborted?h("server.ts").info("generateImages aborted — skip postImagegen for sid="+$):await JN([$],e.trigger).then(()=>{be().fetchUserInfo()})),T=H.length>0,O=q.length,S=q.find(U=>U.provider)?.provider??S,{images:q,errorsOnGeneration:H,sid:$}}case"pending":continue;case"error":throw Yf(W.errorType,W.errorMsg,x)}}throw h("server.ts").error("Max retry count reached while generating image."),new C(_.C_IMAGE_GENERATION_NETWORK_ERROR)}finally{if(!t?.aborted){const R=Math.floor((new Date().getTime()-l)/1e3);sUe(e.prompts.length,O,T,!0,S,R,e.trigger,e.engine,p,e.userReferenceImageCount)}}},aCe=async(e,t,o,r,n="none",a="none",i,s,x)=>{const c=h("server.ts"),l={summary:e,prevCaption:t,caption:o,nextCaption:r,style:a,color:n,userGuidance:i,engine:x};try{const d=await qo("/generate-ttv-genimage-prompt",{method:"POST",body:JSON.stringify(l),signal:s}).then(u=>{if(!u.ok)throw new C(_.C_PROMPT_GENERATION_ERROR,{},"output status is "+u.status);return me(u,_.C_PROMPT_GENERATION_ERROR)});if(d.result!=="success"){const u="Error occurred during generating prompt. "+JSON.stringify(d);throw c.error(u),new C(_.C_PROMPT_GENERATION_ERROR,{},u)}return c.info("Prompt generated: "+JSON.stringify(d.prompt)),d.prompt}catch(d){if(no(d))throw d;const u=P(d);throw c.error("Error occured while generate prompt : "+u),new C(_.C_PROMPT_GENERATION_ERROR,{},u)}},sc=async(e,t,o,r,n,a=r)=>{const i=h("server.ts");i.info("Polling Result For: "+e);for(let x=0;x<o;x++){const c=await qo("/prompt-results?rid="+e,{method:"GET",signal:n}).then(l=>me(l,r));switch(c.result){case"success":return i.info("Polling "+e+" result ready after "+(x+1)+" attempts"),c.text;case"error":throw i.error("Polling result failed: "+c.errorType+" - "+c.msg),new C(r,{},c.msg);case"pending":{await Fo(t);continue}default:{const l="Unexpected polling result: "+JSON.stringify(c);throw i.error(l),new C(r,{},l)}}}const s="Polling timeout after "+o+" attempts";throw i.error(s),new C(a,{},s)},iCe=async(e,t,o,r,n,a,i,s,x)=>{const c=h("server.ts"),l=50,d=FT(e,l);d.length>1&&c.info("Splitted captions into "+d.length+" chunks for generating visual prompts.");const u=3e3,p=20;try{const f=d.map(async(T,O)=>{try{const S=qe.v4();await qo("/generate-visual-prompt",{method:"POST",body:JSON.stringify({apiVersion:"v2",captions:T,summary:t,rid:S,includeVideoPrompt:o,includeGenimagePrompt:r,style:n,color:a,userGuidance:i,engine:x}),signal:s});const y=await sc(S,u,p,_.C_PROMPT_GENERATION_ERROR,s);return JSON.parse(y).map((N,M)=>({ttvPrompts:N,originalCaption:T[M]}))}catch(S){throw c.error("Error occured while generating visual prompt for index "+(O+1)+" chunk"),S}});return await Promise.all(f).then(T=>T.flat())}catch(f){throw c.error("One of the visual prompts generation failed. Error: "+P(f)),f}},sCe=async(e,t)=>{await yr(_.A_AUTH_GERNAL_ERROR,"No idToken at getReferenceImageUploadURL",h("server.ts"));const o={fileType:e},r=await bn("/get-reference-upload-url",{method:"POST",body:JSON.stringify(o),signal:t});return me(r,_.C_REFERENCE_IMAGE_UPLOAD_FAILED)},Fst=async(e,t,o,r,n)=>{await yr(_.A_AUTH_GERNAL_ERROR,"No idToken at getGenVideoInputUploadURL",h("server.ts"));const a={engine:e,inputType:t,fileType:o,fileSize:r},i=await bn("/get-genvideo-input-upload-url",{method:"POST",body:JSON.stringify(a),signal:n});return me(i,_.C_VIDEO_REFERENCE_UPLOAD_FAILED)},xCe=async(e,t,o,r,n,a,i,s)=>
1164{Us(Xt.PREPARE_TTV_PLAN_FAIL),await yr(_.A_AUTH_GERNAL_ERROR,"No idToken at prepareTTVPlanWithConsistency",h("server.ts"));const x=qe.v4();h("server.ts").info(`prepareTTVPlanWithConsistency started. 
1165    rid=`+x);const c={captions:e,summary:t,rid:x,style:o,includeVideoPrompt:r,referenceImages:n,userGuidance:a,engine:i},l=await bn("/prepare-ttv-visual-plan",{method:"POST",body:JSON.stringify(c),signal:s}),d=await me(l,_.C_STOCK_NETWORK_ERROR);if(d.result!=="success")throw h("server.ts").error(`prepareTTVPlanWithConsistency failed.
1166      errorType=`+d.errorType+`
1167      errorMsg=`+d.errorMsg),new C(_.C_TTV_PLAN_GENERATION_ERROR,{},d.errorMsg);h("server.ts").info("prepareTTVPlanWithConsistency polling started");const u=d.polling;await Fo(u.initialDelayMs);const p=await sc(d.rid,u.intervalMs,u.maxAttempts,_.C_TTV_PLAN_GENERATION_ERROR,s,_.C_TTV_PLAN_POLLING_TIMEOUT),f=JSON.parse(p);return h("server.ts").info(`prepareTTVPlanWithConsistency successfully completed.
1168    clipPlansCount=`+f.clipPlans.length+`
1169    allReferencesCount=`+f.allReferences.length),f.clipPlans},Ust=async(e,t)=>{const o=h("server.ts"),r=qe.v4(),n={summary:e,clipsInfo:t,rid:r};try{o.info("generateThumbnailImagePrompt rid: "+r);const a=t.reduce((x,c)=>{const l=new Blob([c.thumbnail],{type:"image/png"}).size,d=c.caption?new Blob([c.caption],{type:"text/plain"}).size:0;return x+l+d},0)/(1024*1024);o.info("generateThumbnailImagePrompt memory usage: "+a.toFixed(2)+"MB"),o.info("clipsInfo length: "+t.length);const i=await qo("/generate-thumbnail-image-prompt",{method:"POST",body:JSON.stringify(n)}).then(x=>me(x,_.C_THUMBNAIL_GENERATOR_NETWORK_ERROR));if(i.result!=="success"){const x="Error occurred from generateThumbnailImagePrompt: "+JSON.stringify(i);throw h("server.ts").error(x),new C(_.C_PROMPT_GENERATION_ERROR,{},x)}const s=i.prompt;return o.info("thumbnailImagePrompt generated: "+JSON.stringify(s,void 0,3)+`
1170      from summary : `+e),s}catch(a){const i="Error occurred from generateThumbnailImagePrompt: "+P(a);throw o.error(i),Ne(a)?a:new C(_.C_PROMPT_GENERATION_ERROR)}},Vst=async e=>{const t=h("server.ts"),o={caption:e,type:"keyword"};try{const r=await qo("/generated-prompt",{method:"POST",body:JSON.stringify(o)}).then(n=>{if(!n.ok)throw new C(_.C_PROMPT_GENERATION_ERROR,{},"output status is "+n.status);return n.json()});if(r.result!=="success"){const n="Error occurred during generating prompt. "+JSON.stringify(r);throw h("server.ts").error(n),new C(_.C_PROMPT_GENERATION_ERROR,{},n)}return t.info("Keyword Prompt generated."+JSON.stringify(r.prompt)),r.prompt.filter(n=>n!=null)}catch(r){return t.info("Erorr occured while generate keyword prompt : "+P(r)),[]}},j7=async(e,t,o,r)=>{const{uid:n,deviceId:a,deviceName:i}=r,s=qe.v4(),x=Xo(),c={type:e,lang:t,script:o,rid:s,maxTokens:4096,uid:n,deviceId:a,deviceName:i,clientType:x};try{qo("/generated-remix-script",{method:"POST",body:JSON.stringify(c)});const l=5e3,d=20;let u=0,p=!1;for(await Fo(l);!p;){u+=1,u>d&&(p=!0);const f=await qo("/prompt-results?rid="+s,{method:"GET"}).then(E=>me(E,_.C_PROMPT_GENERATION_ERROR));if(f.result==="error")throw new C(_.C_PROMPT_GENERATION_ERROR,{},f.msg);if(f.result==="pending"){await Fo(l);continue}if(f.result==="success"&&f.text)return f.text}return}catch(l){return h("server.ts").error("error occured while generating script for video remix. "+P(l)),void 0}},Gst=async()=>{const e=h("server.ts"),t=be(),o=t.getUserInfo()?.uid;if(!await wo()||!o){e.error("No idToken or uid at getPaymentPreregistrationInfo");return}try{const r=await dx("/get-payment-preregistration-info",{method:"POST",body:JSON.stringify({uid:o})}).then(a=>{if(!a.ok){const i="Error response at getPaymentPreregistrationInfo. status: "+a.status;throw new C(_.C_PAYMENT_NETWORK_ERROR,{},i)}return a.json()});if(r.error){const{type:a,msg:i}=r.error,s="Error response at getPaymentPreregistrationInfo. type: "+a+". msg: "+i,x=CSe(a);throw e.error("Error response at getPaymentPreregistrationInfo. type: "+a+". msg: "+i),new C(x,{},s)}if(r.getResult)return r.getResult;const n="Wrong response at getPaymentPreregistrationInfo. res: "+JSON.stringify(r);
1170throw new C(_.C_PAYMENT_GENERAL_ERRROR,{},n)}catch(r){h("server.ts").error("An error occured at getPaymentPreregistrationInfo. error: "+P(r));const n=ye(r)??_.C_PAYMENT_GENERAL_ERRROR,a=Ot(n,{defaultKey:"error.payment_general_error",errorArg:Ho(r)});Y().error(n,a);return}},cCe=async(e,t,o)=>{const r=h("server.ts"),n=be(),a=n.getUserInfo()?.uid;if(!await wo()||!a)return r.error("No idToken or uid at getPaymentProgress"),"EXIT";try{const i={uid:a,guid:e,pollingStartTime:t,type:o},s=()=>dx("/get-payment-progress",{method:"POST",body:JSON.stringify(i)}).then(c=>{if(!c.ok)throw new C(_.C_PAYMENT_NETWORK_ERROR,{},"status: "+c.status);return c.json()}),x=await Wr(s,M1,"getPaymentProgress(type="+o+")");if(x.error){const c="Error response at getPaymentProgress, "+JSON.stringify(x.error),{code:l}=x.error;if(l==="EXPIRED")return"EXPIRED";const d=wd(l);throw new C(d,{},c)}return x.status}catch(i){h("server.ts").error("An error occured at getPaymentProgress. pollingType: "+o+". error: "+P(i));const s=ye(i)??_.C_PAYMENT_GENERAL_ERRROR,x=Ot(s,{defaultKey:"error.payment_general_error",errorArg:Ho(i)});Y().error(s,x);return}},lCe=async(e,t)=>{const o=h("server.ts"),r=be(),n=r.getUserInfo()?.uid;if(!await wo()||!n)return o.error("No idToken or uid at getPaymentProgressUsageEraser"),{status:"EXIT"};try{const a={uid:n,guid:e,pollingStartTime:t},i=()=>dx("/get-payment-progress-usage-eraser",{method:"POST",body:JSON.stringify(a)}).then(x=>{if(!x.ok)throw new C(_.C_PAYMENT_NETWORK_ERROR,{},"status: "+x.status);return x.json()}),s=await Wr(i,M1,"getPaymentProgressUsageEraser");if(s.error){const x="Error response at getPaymentProgressUsageEraser, "+JSON.stringify(s.error),{code:c}=s.error;if(c==="EXPIRED")return{status:"EXPIRED"};const l=wd(c);throw new C(l,{},x)}return{status:s.status,quantity:s.quantity}}catch(a){h("server.ts").error("An error occured at getPaymentProgressUsageEraser. error: "+P(a));const i=ye(a)??_.C_PAYMENT_GENERAL_ERRROR,s=Ot(i,{defaultKey:"error.payment_general_error",errorArg:Ho(a)});Y().error(i,s);return}},me=(e,t)=>{if(!e.ok)throw e.status===401?new C(_.C_API_AUTH_FAILED,{},"Server has returned 401: Unauthorized"):new C(t,{},"response status is not ok: "+e.statusText+"("+e.status+")");return e.json()},JN=async(e,t)=>{const o=await pt().getDeviceInfo(),r={sids:e,timezoneMin:-new Date().getTimezoneOffset(),trigger:t,deviceId:o.deviceId,deviceName:o.deviceName,machineId:o.machineId};h("server.ts").info("postImagegen requested for "+JSON.stringify(e)+", trigger: "+t);const n=await Ui("/post-imagegen",{method:"POST",body:JSON.stringify(r)}).catch(i=>{const s="postImagegen response block error: "+P(i)+" for "+JSON.stringify(e)+", "+t;throw h("server.ts").error(s),new C(_.C_USAGE_COUNT_ERROR,{},s)});!n.ok&&h("server.ts").error("postimageGen is not ok, status: "+n.status+", statusText: "+n.statusText);const a=await me(n,_.C_USAGE_COUNT_ERROR);if(a?.error){const i="postImagegen response error: "+JSON.stringify(a)+" for "+JSON.stringify(e)+", trigger: "+t;throw h("server.ts").error(i),new C(_.C_USAGE_COUNT_ERROR,{},i)}h("server.ts").info("postImagegen completed for "+JSON.stringify(e)+", trigger: "+t)},Wst=async(e,t,o,r,n,a)=>{const i={title:e,description:t,query:o,examples:r,language:n,setting:a};try{const s=await Ui("/video-styles",{method:"POST",body:JSON.stringify(i)}),x=await me(s,_.C_VIDEO_STYLE_ERROR);if(x.error)throw new C(_.C_VIDEO_STYLE_ERROR,{},x.error);return!0}catch(s){h("server.ts").error("error occured while creating TTV video style. title: "+e+". "+P(s));const x=ye(s)??_.C_VIDEO_STYLE_ERROR;return Y().error(x,Ot(x,{defaultKey:yT()?"ttv_v5.my_setting_save_failed":"ttv_v2_style_creation.save_failed"})),!1}},Hst=async(e,t,o,r,n,a,i)=>{const s={title:t,description:o,query:r,examples:n,language:a,setting:i};try{const x=await Ui("/video-styles/"+e,{method:"PUT",body:JSON.stringify(s)}),c=await me(x,_.C_VIDEO_STYLE_ERROR);if(c.error)throw new C(_.C_VIDEO_STYLE_ERROR,{},c.error);return!0}catch(x){h("server.ts").error("error occured while editing video style for ttv. "+P(x));const c=ye(x)??_.C_VIDEO_STYLE_ERROR;return Y().error(c,Ot(c,{defaultKey:yT()?"ttv_v5.my_setting_update_failed":"ttv_v2_style_creation.update_failed"})),!1}},jst=async e=>{try{const t=await Ui("/video-styles",{method:"DELETE",body:JSON.stringify({videoStyleId:e})}),o=await me(t,_.C_VIDEO_STYLE_ERROR);if(o.error)throw new C(_.C_VIDEO_STYLE_ERROR,{},o.error);return!0}catch(t){h("server.ts").error("error occured while deleting TTV video style. "+P(t));const o=ye(t)??_.C_VIDEO_STYLE_ERROR;return Y().error(o,Ot(o,{defaultKey:yT()?"ttv_v5.my_setting_delete_failed":"ttv_v2.delete_style_failed"})),!1}},zst=async e=>{try{Us(Xt.TTV_STYLE_FETCH_FAIL);const t=Fe(),o=e?"&version="+e:"",r=await Ui("/video-styles?language="+t+
1170o,{method:"GET"}),n=await me(r,_.C_VIDEO_STYLE_ERROR);if(n.error)throw new C(_.C_VIDEO_STYLE_ERROR,{},n.error);if(n.result.length===0&&e!=="v5")throw new C(_.C_VIDEO_STYLE_ERROR,{},"getTTVVideoStyle result is empty");return n.result}catch(t){if(h("server.ts").error("error occured while getting video style for ttv. "+P(t)),Y().error(_.C_VIDEO_STYLE_ERROR,Ot(_.C_VIDEO_STYLE_ERROR,{defaultKey:e==="v5"?"ttv_v5.my_setting_fetch_failed":"ttv_v2.fetch_style_failed"})),e==="v5")throw t;return[]}},Yst=async(e,t)=>{const o=Fe(),r={videoStyleId:e,title:t};try{return(await qo("/generated-subject?language="+o,{method:"POST",body:JSON.stringify(r)}).then(a=>me(a,_.C_PROMPT_GENERATION_ERROR))).result.subjects}catch(n){return h("server.ts").error("Error occured while generating subject for ttv. "+P(n)),[]}},dCe=async(e,t,o)=>{if(!await wo()){const O="No idToken at sendVrewMarkAlternativeInfoToBigquery";return h("server.ts").error(O),{result:"error",errorType:"authorization",msg:O}}const r=await zo(),n=sa(),a=Fe(),{knownSource:i,knownSourceOtherDetail:s,uploadOnSocialMedia:x,uploadSocialMedia:c,uploadSocialMediaURL:l,sourceCiteRadioOption:d,videoMakingPurpose:u,sourceCiteDetail:p}=o,f={uid:e,cid:r,version:n,language:a,submitDate:t,inputLink:l,selectedDescriptionType:d,knownSource:i,knownSourceOtherDetail:s,uploadOnSocialMedia:x,uploadSocialMedia:c,videoMakingPurpose:u,sourceCiteDetail:p},E=await lx("/add-vrewmark-bigquery",{method:"POST",body:JSON.stringify(f)});!E.ok&&h("server.ts").error("addVrewmarkBigquery is not ok, status: "+E.status+", statusText: "+E.statusText);const T=await E.json().catch(O=>{h("server.ts").error("addVrewmarkBigquery json() error: "+P(O))});return T.result==="error"&&h("server.ts").error("addVrewmarkBigquery response error: "+JSON.stringify(T)),T},z7=()=>"project-"+fr.level+".vrew.ai",Bst=async e=>{const t=Fe(),o=qe.v4(),r=h("server.ts"),n={fullCaptions:e,rid:o,language:t};try{r.info("generateThumbnailSummary rid: "+o);const a=await qo("/generate-thumbnail-summary",{method:"POST",body:JSON.stringify(n)}).then(i=>me(i,_.C_THUMBNAIL_GENERATOR_NETWORK_ERROR));if(a.result!=="success"){const i="Unable to generate summary: "+JSON.stringify(a)+" from caption: "+e;throw r.error(i),a.errorType==="operation_rejected"?new C(_.C_THUMBNAIL_GENERATOR_SUMMARY_FAILED):new C(_.C_THUMBNAIL_GENERATOR_GENERAL_ERROR)}return r.info("thumbnailSummary: "+JSON.stringify(a.summary)+`
1171        from caption: `+e+`
1172        debugInfo: `+JSON.stringify(a.debugInfo)),a.summary}catch(a){const i="Error occurred from generate-thumbnail-summary: "+P(a);throw r.error(i),Ne(a)?a:new C(_.C_THUMBNAIL_GENERATOR_GENERAL_ERROR)}},Kst=async e=>{const t=Fe(),o=qe.v4(),r=h("server.ts"),n={image:e,rid:o,language:t};try{r.info("generateThumbnailImageDescription rid: "+o);const a=await qo("/generate-thumbnail-image-description",{method:"POST",body:JSON.stringify(n)}).then(i=>me(i,_.C_THUMBNAIL_GENERATOR_NETWORK_ERROR));if(a.result!=="success"){const i="Unable to generate thumbnail image description: "+JSON.stringify(a);throw r.error(i),new C(_.C_THUMBNAIL_GENERATOR_IMAGE_DESCRIPTION_FAILED)}if(a.description.trim()===""){const i="An empty string was returned from generate-thumbnail-image-description: "+JSON.stringify(a);throw r.error(i),new C(_.C_THUMBNAIL_GENERATOR_IMAGE_DESCRIPTION_FAILED)}return r.info("imageDescription: "+JSON.stringify(a.description)),a.description}catch(a){const i="Error occurred from generate-thumbnail-image-description: "+P(a);throw r.error(i),Ne(a)?a:new C(_.C_THUMBNAIL_GENERATOR_GENERAL_ERROR)}},Xst=async(e,t)=>{const o=Fe(),r=qe.v4(),n=h("server.ts"),a={summary:e,rid:r,language:o,numPhrases:t};try{n.info("generateThumbnailPhrases rid: "+r);const i=await qo("/generate-thumbnail-phrases",{method:"POST",body:JSON.stringify(a)}).then(s=>me(s,_.C_THUMBNAIL_GENERATOR_NETWORK_ERROR));if(i.result!=="success"){const s="generateThumbnailPhrases failed: "+JSON.stringify(i)+" from summary: "+e;throw n.error(s),new C(_.C_THUMBNAIL_GENERATOR_PHRASE_FAILED)}if(i.thumbnailPhrases[0].trim()===""){const s="An empty phrase was returned from generate-thumbnail-phrases: "+JSON.stringify(i);throw n.error(s),new C(_.C_THUMBNAIL_GENERATOR_PHRASE_FAILED)}return n.info("thumbnailPhrases: "+JSON.stringify(i.thumbnailPhrases)+`
1173        from summary: `+e+`
1174        debugInfo: `+JSON.stringify(i.debugInfo)),i.thumbnailPhrases}catch(i){const s="Error occurred from generate-thumbnail-phrases: "+P(i);throw n.error(s),Ne(i)?i:new C(_.C_THUMBNAIL_GENERATOR_GENERAL_ER
1174ROR)}},Jst=async e=>{const t={method:"POST",body:JSON.stringify(e)},o=await lx("/upload-rembg-image-file",t);return me(o,_.C_REMOVE_BACKGROUND_ERROR)},qst=async e=>{const t={method:"POST",body:JSON.stringify(e)},o=await lx("/handle-remove-background",t);return me(o,_.C_REMOVE_BACKGROUND_ERROR)},Qst=async({transcriptInfos:e,maxLineLength:t,lineBreakMode:o,onProgress:r,signal:n,language:a})=>{if(n?.aborted)throw new C(_.C_UPLOAD_USER_CANCELED);const i="/client-linebreak-async-start",s={transcriptInfos:e,maxLineLength:t,lineBreakMode:o};a!==void 0&&(s.language=a);const x=await eh(i,{method:"POST",body:JSON.stringify(s),signal:n}).then(d=>me(d,_.C_LINEBREAKER_FAILED_ERROR)).catch(d=>{if(n?.aborted||no(d))throw new C(_.C_UPLOAD_USER_CANCELED);const u="client linebreak fail: error detail: "+d;throw new C(_.C_LINEBREAKER_FAILED_ERROR,{},u)});if(x.result==="error")throw new C(_.C_LINEBREAKER_FAILED_ERROR,{},x.errorMsg);const{reqId:c,polling:l}=x;h("server.ts").info("client linebreak async started: reqId="+c),await Fo(l.initialDelayMs);for(let d=0;d<l.maxAttempts;d++){if(n?.aborted)throw new C(_.C_UPLOAD_USER_CANCELED);const u=await eh("/client-linebreak-async-status?reqId="+encodeURIComponent(c),{method:"GET",signal:n}).then(p=>me(p,_.C_LINEBREAKER_FAILED_ERROR)).catch(p=>{if(n?.aborted||no(p))throw new C(_.C_UPLOAD_USER_CANCELED);const f="client linebreak status fail: error detail: "+p;throw new C(_.C_LINEBREAKER_FAILED_ERROR,{},f)});if(u.status==="done")return h("server.ts").info("client linebreak async done: reqId="+c+", linebreakVersion="+u.linebreakVersion+", detectedLanguage="+JSON.stringify(u.detectedLanguage)),{result:u.result,linebreakVersion:u.linebreakVersion,detectedLanguage:u.detectedLanguage};if(u.status==="error")throw new C(_.C_LINEBREAKER_FAILED_ERROR,{},u.errorMsg);r?.(u.progress),await Fo(l.intervalMs)}throw new C(_.C_LINEBREAKER_FAILED_ERROR,{},"client linebreak polling timed out: reqId="+c+" after "+l.maxAttempts+" attempts")},Zst=async(e,t,o,r)=>{if(o?.()||r?.aborted)throw new C(_.C_UPLOAD_USER_CANCELED);const n={captions:e};if(!await wo())throw new C(_.C_LOGIN_REQUIRED_ERROR);const a=await jf("/start-caption-correction",{method:"POST",body:JSON.stringify(n),signal:r}).then(x=>me(x,_.C_CAPTION_CORRECTION_ERROR)).catch(x=>
1174{if(r?.aborted)throw new C(_.C_UPLOAD_USER_CANCELED);if(Ne(x))throw x;const c="caption correction start fail: error detail: "+x;throw new C(_.C_CAPTION_CORRECTION_ERROR,{},c)});if(a.result==="error"){const x=a.errorType,c=x==="authorization"?_.C_LOGIN_REQUIRED_ERROR:x==="insufficientCredit"?_.C_REQUEST_QUOTA_EXCEEDED_ERROR:_.C_CAPTION_CORRECTION_ERROR;throw h("server.ts").error("caption correction server error: ["+x+"] "+a.errorMsg),new C(c,{captionCorrectionErrorType:x},"["+x+"] "+a.errorMsg)}const{reqId:i,polling:s}=a;h("server.ts").info("caption correction started: reqId="+i),await Fo(s.initialDelayMs);for(let x=0;x<s.maxAttempts;x++){if(o?.()||r?.aborted)throw new C(_.C_UPLOAD_USER_CANCELED);const c={reqId:i},l=await jf("/get-caption-correction-status",{method:"POST",body:JSON.stringify(c),signal:r}).then(d=>me(d,_.C_CAPTION_CORRECTION_ERROR)).catch(d=>{if(r?.aborted)throw new C(_.C_UPLOAD_USER_CANCELED);if(Ne(d))throw d;const u="caption correction status fail: error detail: "+d;throw new C(_.C_CAPTION_CORRECTION_ERROR,{},u)});if(l.status==="done")return l.result;if(l.status==="error"){const d=l.errorType,u=d==="authorization"?_.C_LOGIN_REQUIRED_ERROR:d==="insufficientCredit"?_.C_REQUEST_QUOTA_EXCEEDED_ERROR:_.C_CAPTION_CORRECTION_ERROR;throw h("server.ts").error("caption correction server error: reqId="+i+" ["+d+"] "+l.errorMsg),new C(u,{captionCorrectionErrorType:d},"["+d+"] "+l.errorMsg)}t?.(l.progress),await Fo(s.intervalMs)}throw new C(_.C_CAPTION_CORRECTION_ERROR,{},"caption correction polling timed out: reqId="+i+" after "+s.maxAttempts+" attempts")},uCe=(e,t)=>{try{const o=Zm(),r=new Set(e.surveys.filter(n=>n.sendToChannelTalk).map(n=>n.id));for(const n in t)r.has(n)&&o.sendSurveyResponse(n,t[n])}catch(o){h("server.ts").error("Failed to send survey to ChannelTok: "+P(o))}},$st=async(e,t,o)=>{if(!await wo()){h("server.ts").error("No idToken at submitVrewSurvey");return}P7.sendVrewSurveyEvent(e,t),uCe(o,t);try{await pCe(e,t)}catch(r){h("server.ts").error("An error occured at submitVrewSurvey. error: "+P(r));return}},pCe=async(e,t)=>{const o=be().getUserInfo()?.uid??"anonymous",r=await zo(),n=sa(),a=Fe(),i={uid:o,cid:r,version:n,language:a,surveyType:e,submitDate:new Date().toISOString().replace("Z",""),surveyResponses:t},s=await lx("/send-vrew-survey-to-bigquery",{method:"POST",body:JSON.stringify(i)});!s.ok&&h("server.ts").error("sendVrewSurveyBigquery is not ok, status: "+s.status+", statusText: "+s.statusText);const x=await s.json().catch(c=>{h("server.ts").error("sendVrewSurveyBigquery json() error: "+P(c))});if(x.result==="error")throw h("server.ts").error("sendVrewSurveyBigquery response error: "+JSON.stringify(x)),new Error("error occurred while sending survey form data.");return x},Y7=async()=>{try{Us(Xt.GEN_ASSET_MODELS_FETCH_FAIL);const e=await qo("/get-generate-asset-model-list",{method:"GET"}).then(t=>me(t,_.C_STOCK_NETWORK_ERROR));return h("server.ts").info("request generate asset model list response: "+JSON.stringify(e)),e.result==="error"?e:e.genImageModels.length===0?{result:"error",errorMsg:"No available generate asset model"}:e}catch(e){return h("server.ts").error("Error occurred while get generate asset model list: "+P(e)),{result:"error",errorMsg:P(e)}}},e0t=async({userText:e,style:t,engine:o,startFrameImageUrl:r,generationOptions:n,signal:a})=>{try{await yr(_.A_AUTH_GERNAL_ERROR,"GenVideo prompt generation requires an authenticated user",h("server.ts"));const i=rOe({userText:e,style:t,engine:o,...r?{startFrameImageUrl:r}:{},...n?{generationOptions:n}:{}}),s=await bn("/start-genvideo-prompt-job",{method:"POST",body:JSON.stringify(i),signal:a}),x=await me(s,_.C_PROMPT_GENERATION_ERROR);if(x.result==="error")throw h("server.ts").error(`Error occurred while starting GenVideo prompt generation:
1175        errorType: `+x.errorType+`
1176        errorMsg: `+x.errorMsg),new C(_.C_PROMPT_GENERATION_ERROR);const{rid:c,polling:l}=x;await Fo(l.initialDelayMs);const d=await sc(c,l.intervalMs,l.maxAttempts,_.C_PROMPT_GENERATION_ERROR,a),u=JSON.parse(d);if(u.result==="error")throw h("server.ts").error(`GenVideo prompt generation failed:
1177        errorType: `+u.errorType+`
1178        errorMsg: `+u.errorMsg),new C(_.C_PROMPT_GENERATION_ERROR);return u.prompt}catch(i){throw no(i)||Ne(i)?i:(h("server.ts").error("Network error occured while getGenVideoPrompt : "+P(i)),new C(_.C_PROMPT_GENERATION_ERROR,{},P(i)))}},ID=10*1e3,fCe=5*1e3,TD=35,th=()=>new DOMException("GenVideo request aborted","AbortError"),SD=(e,t)=>t?t.aborted?Promise.reject(th()):new Promise((o,r)=>{const n=()=>{clearTimeout(a),t.removeEventListener("abort",n),r(th())},a=setTimeout(()=>{t.removeEventListener("abort",n),o()},e);t.addEventListener("abort",n,{once:!0}),t.aborted&&n()}):Fo(e),gCe=async(e,t)=>{const o=await fetch(e,{signal:t});
1178if(!o.ok)throw new C(_.C_VIDEO_GENERATION_NETWORK_ERROR,{},"Failed to download generated video: "+o.status+" "+o.statusText);const r=await o.blob();return new Promise((n,a)=>{const i=new FileReader;i.onload=()=>{if(typeof i.result!="string"){a(new C(_.C_VIDEO_GENERATION_NETWORK_ERROR));return}n(i.result.split(",")[1])},i.onerror=()=>{a(new C(_.C_VIDEO_GENERATION_NETWORK_ERROR,{},P(i.error)))},i.readAsDataURL(r)})},t0t=async e=>{const{signal:t}=e;if(t?.aborted)throw th();Us(Xt.GEN_ASSET_FORCE_FAIL);const o=be().getUserInfo()?.uid??tn,r=await zo(),{deviceId:n,machineId:a}=await Ia(),i=Xo(),s=Mo().getDebugVal(Xt.FORCE_IMAGEGEN_VREWSERVER)!==void 0,x=new Date().getTime(),c=nOe(e,{uid:o,cid:r,deviceId:n,clientType:i,machineId:a}),l=cL*1e3,{reqId:d,fileKey:u}=await _Ce(c,t);if(u!==void 0)try{await ECe(u,t)}catch(T){if(no(T))throw T;h("server.ts").info("Triggered processGenVideo but failed. Continuing...")}const p=new AbortController,f=setTimeout(()=>p.abort(),l),E=t?AbortSignal.any([t,p.signal]):p.signal;try{await SD(ID,E),h("server.ts").info("Waited "+ID/1e3+" seconds before polling for reqId: "+d);for(let T=0;T<TD;T++){if(E.aborted)throw th();const O=await mCe(d,E);switch(O.status){case"done":{const{signedUrl:S,sid:R,mediaDurationSec:y}=O;return{videoBase64:await gCe(S,E),prompt:O.prompt,sid:R,mediaDurationSec:y,reqId:d,elapsedTime:Math.floor((new Date().getTime()-x)/1e3)}}case"pending":{await SD(fCe,E);continue}case"error":throw h("server.ts").error("error when generating video: "+JSON.stringify(O)),Yf(O.errorType,O.errorMsg,s,!0)}}throw h("server.ts").error("GenVideo polling timed out after "+TD+" attempts."),new C(_.C_VIDEO_GENERATION_NETWORK_ERROR)}catch(T){throw p.signal.aborted&&!t?.aborted?(h("server.ts").error("GenVideo polling exceeded the "+cL+"s client deadline."),new C(_.C_VIDEO_GENERATION_NETWORK_ERROR)):T}finally{clearTimeout(f);const T=Math.floor((new Date().getTime()-x)/1e3);h("server.ts").info("elapsedSec for genvideo: "+T)}},_Ce=async(e,t)=>{try{const o=await Ui("/make-genvideo",{method:"POST",body:JSON.stringify(e),signal:t}),r=await me(o,_.C_VIDEO_GENERATION_ERROR);if(r.result==="error")throw h("server.ts").error(`One or more genvideo were not generated successfully.
1179        errorType: `+r.errorType+`
1180        errorMsg: `+r.errorMsg),Yf(r.errorType,r.errorMsg,!1,!0);return{reqId:r.reqId,fileKey:r.fileKey}}catch(o){throw no(o)||Ne(o)?o:(h("server.ts").error("An unexpected error occured while makeGenVideo : "+P(o)),new C(_.C_VIDEO_GENERATION_ERROR,{},P(o)))}},ECe=async(e,t)=>{try{await qo("/process-genvideo",{method:"POST",body:JSON.stringify({Key:e}),signal:t})}catch(o){throw no(o)?o:(h("server.ts").error("An unexpected error occured while processGenVideo : "+P(o)),new C(_.C_VIDEO_GENERATION_ERROR,{},P(o)))}},mCe=async(e,t)=>{try{const o=await Ui("/get-genvideo?reqId="+e,{method:"GET",signal:t});return await me(o,_.C_VIDEO_GENERATION_ERROR)}catch(o){throw no(o)||Ne(o)?o:(h("server.ts").error("An unexpected error occured while getGenVideo : "+P(o)),new C(_.C_VIDEO_GENERATION_ERROR,{},P(o)))}},o0t=async(e,t,o,r,n,a)=>{const i=qe.v4(),s=h("server.ts"),x=Fe(),c={topic:o,rid:i,isProOn:t,language:x,styleId:e,useWebSearch:t,userPrompt:r,length:n},l=3e3,d=20;s.info("generateVideoScript request body:",JSON.stringify(c));try{await Ui("/generate-video-script",{method:"POST",body:JSON.stringify(c),signal:a});const u=await sc(i,l,d,_.C_TTV_GENERATE_SCRIPT_ERROR),p=JSON.parse(u);return s.info("generateVideoScript Status:",JSON.stringify(p.status)),{script:p.script,searchSources:p?.searchSources}}catch(u){if(Ne(u)||no(u))throw u;const p="Error occurred from generate-video-script: "+P(u);throw s.error(p),new C(_.C_TTV_GENERATE_SCRIPT_ERROR)}},r0t=async e=>{const t=h("server.ts"),o=Fe(),r={script:e,rid:qe.v4(),language:o};try{const n=await qo("/generate-video-style",{method:"POST",body:JSON.stringify(r)}).then(a=>me(a,_.C_STOCK_NETWORK_ERROR));if(n.result!=="success"){const a="Unable to generate video style: "+JSON.stringify(n);throw t.error(a),new C(_.C_TTV_GENERATE_VIDEO_STYLE_ERROR)}return{prompt:n.style,title:n.title}}catch(n){t.error("Error occurred from generate-video-style: "+P(n));const a=ye(n)??_.C_TTV_GENERATE_VIDEO_STYLE_ERROR;return Y().error(a,Ot(a,{defaultKey:"ttv_v2_style_creation.generate_prompt_failed"})),{prompt:"",title:""}}},n0t=async e=>{const t=h("server.ts"),o=Fe();try{const r=await qo("/ttv-notice?language="+o+"&noticeType="+e,{method:"GET"}).then(n=>
1180me(n,_.C_STOCK_NETWORK_ERROR));if(r.result!=="success"){const n="Failed to get TTV notice: "+JSON.stringify(r);throw t.error(n),new C(_.C_TTV_GENERAL_ERROR)}return{title:r.title,content:r.content}}catch(r){return t.error("Error occurred from getTTVNotice: "+P(r)),{title:"",content:""}}},B7=async(e,t)=>{const o=await Yn("/cloud-list-objects",{method:"POST",body:JSON.stringify({projectId:e,prefix:t})}).then(r=>me(r,_.C_VCLOUD_LIST_OBJECTS_ERROR));if(o.result!=="success")throw new C(_.C_VCLOUD_LIST_OBJECTS_ERROR);return o.objects},a0t=()=>hn.getAgentServerUrl(),OD=async(e,t)=>{const o={imageIds:e,method:t};try{const r=await lx("/presigned-url/slides-img",{method:"POST",body:JSON.stringify(o)}).then(n=>me(n,_.C_GENERATE_SLIDES_SCRIPT_ERROR));if(r.result==="success")return r.urls;throw h("server.ts").error("Failed to get presigned url for image description: "+r.errorType+", "+r.errorMsg),new C(_.C_GENERATE_SLIDES_SCRIPT_ERROR)}catch(r){const n="Error occured while getting presigned url for image description: "+P(r),a=Ne(r)?r.errorCode:_.C_GENERATE_SLIDES_SCRIPT_ERROR;Y().error(a,n);return}},hCe=async(e,t,o)=>{const r=qe.v4(),{deviceId:n,deviceName:a,machineId:i}=await Ia(),s={rid:r,contentItems:o,language:e,userPrompt:t,deviceId:n,deviceName:a,machineId:i},x=5e3,c=1e4,l=30;try{const d=await bn("/generated-slides-script",{method:"POST",body:JSON.stringify(s)}).then(T=>me(T,_.C_GENERATE_SLIDES_SCRIPT_ERROR));if(d.result==="error"){const T="Failed to trigger slides script generation. errorType: "+d.errorType+", errorMsg: "+d.errorMsg;throw h("server.ts").error(T),new C(_.C_GENERATE_SLIDES_SCRIPT_ERROR,{},T)}await Fo(c);const u=await sc(r,x,l,_.C_GENERATE_SLIDES_SCRIPT_ERROR),p=JSON.parse(u);if(!Array.isArray(p))throw new Error("Invalid response format");return[...p].sort((T,O)=>(T.page??0)-(O.page??0)).map(T=>typeof T.page=="number"&&typeof T.script=="string"?T.script.trim():"")}catch(d){const u="Error occured while generating slides script: "+P(d);throw h("server.ts").error(u),new C(_.C_GENERATE_SLIDES_SCRIPT_ERROR)}},i0t=async(e,t,o)=>{try{const r={blobType:e,uploadPartInfo:t},n=await bn("/get-atv-upload-url",{method:"POST",body:JSON.stringify(r),signal:o}).then(a=>me(a,_.C_STOCK_NETWORK_ERROR));if(n.result==="error"){const a="Failed to get signed URL for ATV. response: "+JSON.stringify(n);throw h("server.ts").error(a),new C(_.C_ATV_UPLOAD_ERROR,{},a)}return n}catch(r){if(no(r))throw h("server.ts").info("Abort signal received while getATVUploadURL."),r;const n=ye(r)??_.C_ATV_UPLOAD_ERROR,a="Error occurred while getting signed URL for ATV. atvItemId: "+t.atvItemId+". error: "+P(r);throw h("server.ts").error(a),new C(n,{},a)}},s0t=async(e,t)=>{try{const o=e,r=await bn("/upload-atv-asset",{method:"POST",body:JSON.stringify(o),signal:t}).then(s=>me(s,_.C_STOCK_NETWORK_ERROR));if(r.result==="error"){const s="Failed to upload ATV asset. response: "+JSON.stringify(r)+".";throw h("server.ts").error(s),new C(_.C_ATV_UPLOAD_ERROR,{},s)}const n=r.polling;await Fo(n.initialDelayMs);const a=await sc(e.rid,n.intervalMs,n.maxAttempts,_.C_ATV_UPLOAD_ERROR,t),i=JSON.parse(a);if(i.result==="error"){const s="Failed to upload ATV asset polling. polling response: "+JSON.stringify(i);throw h("server.ts").error(s),new C(_.C_ATV_UPLOAD_ERROR,{},s)}return i}catch(o){if(no(o))throw h("server.ts").info("Abort signal received while uploadATVAssetToGCSFromS3."),o;const r=ye(o)??_.C_ATV_UPLOAD_ERROR,n="Error occurred while uploading ATV asset. Error: "+P(o);throw h("server.ts").error(n),new C(r,{},n)}},x0t=async(e,t,o)=>{const r=qe.v4(),n=Fe();try{const a={userPrompt:e,rid:r,language:n,atvItemIds:t},i=await bn("/generate-asset-to-video",{method:"POST",body:JSON.stringify(a),signal:o}).then(l=>me(l,_.C_STOCK_NETWORK_ERROR));if(i.result==="error"){const l="Failed to generateATV. response: "+JSON.stringify(i);throw h("server.ts").error(l),new C(_.C_ATV_GENERATE_SCRIPT_ERROR,{},l)}const s=i.polling;await Fo(s.initialDelayMs);const x=await sc(r,s.intervalMs,s.maxAttempts,_.C_ATV_GENERATE_SCRIPT_ERROR,o),c=JSON.parse(x);if(c.result==="error"){const l="Failed to generateATV polling. polling response: "+JSON.stringify(c);throw h("server.ts").error(l),new C(_.C_ATV_GENERATE_SCRIPT_ERROR,{},l)}return c.scenes}catch(a){if(no(a))throw h("server.ts").info("Abort signal received while generateATV."),a;const i=ye(a)??_.C_ATV_GENERATE_SCRIPT_ERROR,s="Error occurred while generateATV. error: "+P(a);throw h("server.ts").error(s),new C(i,{},s)}},c0t=async(e,t)=>{try{const o=new Date().getTime(),r=Fe(),n={image:e,language:r},a=await bn("/generate-asset-to-video-prompt",{method:"POST",body:JSON.stringify(n),signal:t}).then(s=>
1180me(s,_.C_STOCK_NETWORK_ERROR)),i=Math.floor((new Date().getTime()-o)/1e3);if(h("server.ts").info("Generate ATV Prompt completed. Duration: "+i+"s. result: "+JSON.stringify(a.result)+"."),a.result==="error")throw new C(_.C_ATV_GENERATE_PROMPT_ERROR,{},a.errorMsg);return a.prompts}catch(o){if(no(o))throw h("server.ts").info("Skip generateATVPrompt because abort signal is received."),o;const r=ye(o)??_.C_ATV_GENERATE_PROMPT_ERROR,n="Error occurred while generating ATV prompt. error: "+P(o);throw h("server.ts").error(n),new C(r,{},n)}},ICe=async e=>{try{const t=Fe(),o={demoType:e,language:t,supportedVrewJsonVersion:Be.CURRENT_VREW_JSON_VERSION},r=await h0("/get-demo-project-id",{method:"POST",body:JSON.stringify(o)}).then(n=>me(n,_.C_NETWORK_REQUEST_FAILED));if(r.result==="error")throw new C(_.C_NETWORK_REQUEST_FAILED,{},r.msg);return r.projectId}catch(t){return h("server.ts").error("Error occurred from getDemoProjectId: "+P(t)),""}},l0t=async()=>{const e=h("server.ts"),t={agreementType:"vrew_agent",version:"1",agreed:!0},o=await jf("/save-user-agreement",{method:"POST",body:JSON.stringify(t)});if(!o.ok)throw e.error("sendVrewAgentConsent failed: "+o.status),new C(_.C_AGENT_GENERAL_ERROR,{});const r=await o.json();if(r.result==="error")throw e.error("sendVrewAgentConsent error: "+r.errorMsg),new C(_.C_AGENT_GENERAL_ERROR,{})},d0t=async()=>{const e=h("server.ts"),t=await jf("/get-user-agreement?agreementType=vrew_agent",{method:"GET"});if(!t.ok)throw e.error("getVrewAgentConsent failed: "+t.status),new C(_.C_AGENT_GENERAL_ERROR,{});const o=await t.json();if(o.result==="error")throw e.error("getVrewAgentConsent error: "+o.errorMsg),new C(_.C_AGENT_GENERAL_ERROR,{});return!!o.agreed},u0t=async()=>{const e=be().getUserInfo()?.uid;if(!await wo()||!e){const o="No idToken or uid at subscriptionConsent";throw new C(_.C_LOGIC_ERROR,{},o)}const t={uid:e,isSubscriptionConsent:!0,requestedBy:"user"};try{const o=await dx("/reschedule-payment",{method:"POST",body:JSON.stringify(t)}),r=await me(o,_.C_PAYMENT_NETWORK_ERROR);if(r.result==="error"){const n="Failed to request subscription consent. response: "+JSON.stringify(r);throw new C(_.C_PAYMENT_NETWORK_ERROR,{},n)}return r}catch(o){throw Ne(o)?o:(h("server.ts").error("Error occurred while requestSubscriptionConsent. error: "+P(o)),new C(_.C_PAYMENT_NETWORK_ERROR,{},P(o)))}},p0t=async(e,t,o,r,n)=>{const a=qe.v4(),i=h("server.ts"),s=Fe(),x={userRequest:o,rid:a,isProOn:t,language:s,styleId:e,useWebSearch:t,length:r},c=3e3,l=20;
1180i.info("generateVideoScriptV2 request body:",JSON.stringify(x));try{await bn("/generate-video-script-v2",{method:"POST",body:JSON.stringify(x),signal:n});const d=await sc(a,c,l,_.C_TTV_GENERATE_SCRIPT_ERROR),u=JSON.parse(d);return i.info("generateVideoScriptV2 Status:",JSON.stringify(u.status)),{script:u.script,searchSources:u?.searchSources}}catch(d){if(Ne(d)||no(d))throw d;const u="Error occurred from generate-video-script-v2: "+P(d);throw i.error(u),new C(_.C_TTV_GENERATE_SCRIPT_ERROR)}},f0t=async e=>{const t=h("server.ts"),o={originalScript:e};try{const r=await bn("/cleaning-script",{method:"POST",body:JSON.stringify(o)}).then(n=>me(n,_.C_STOCK_NETWORK_ERROR));if(r.result==="error")throw new C(_.C_TTV_GENERATE_SCRIPT_ERROR,{},r.errorMsg);return t.info("Cleaning script completed. Removed texts: "+r.removedTexts.join(", ")+"."),{cleanedScript:r.cleanedScript,removedTextCount:r.removedTexts.length,isFailed:!1}}catch(r){return t.error("Error occured while cleaning script. "+P(r)+". So using original script."),{cleanedScript:e,removedTextCount:0,isFailed:!0}}},g0t=async e=>{const t=Fe(),o={videoStyleId:e,language:t};try{const r=await bn("/generate-script-prompt",{method:"POST",body:JSON.stringify(o)}).then(n=>me(n,_.C_STOCK_NETWORK_ERROR));if(r.result==="error")throw h("server.ts").error("Error occured while generating script prompt. "+r.errorMsg),new C(_.C_PROMPT_GENERATION_ERROR,{},r.errorMsg);return r.userRequests}catch(r){return h("server.ts").error("Error occured while generating script prompt. "+P(r)),[]}},_0t=async e=>{try{await qo("/log-script-classification",{method:"POST",body:JSON.stringify({input:e})})}catch(t){h("server.ts").info("logScriptClassification skipped or failed: "+P(t))}},TCe=async()=>{try{const e=await qo("/stock-resource-info",{method:"POST"}).then(r=>me(r,_.C_STOCK_NETWORK_ERROR));if(h("server.ts").info("request template list response: "+JSON.stringify(e)),e.result==="error")throw new C(_.C_STOCK_NETWORK_ERROR);const t=await fetch(e.templateListInfoUrl,{cache:"no-cache"});return(await me(t,_.C_STOCK_NETWORK_ERROR)).projects.map(r=>({...r,previewUrl:r.previewUrl?new URL(r.previewUrl,e.templateListInfoUrl).href:void 0,thumbnailUrl:r.thumbnailUrl?new URL(r.thumbnailUrl,e.templateListInfoUrl).href:void 0})).filter(r=>r.visible).sort((r,n)=>r.order-n.order)}catch(e){return h("server.ts").error("Error occurred while get template list: "+P(e)),[]}},E0t=async(e,t)=>{try{if(!await wo())return[];const o=await F2("/get-credit-history",{method:"POST",body:JSON.stringify({kind:"user",from:e,to:t,timezoneMin:-new Date().getTimezoneOffset()})}),r=await o.json();return r.result!=="success"||r.kind!=="user"?[]:r.data.entries}catch(o){const r="[fetchCreditHistory] failed to fetch credit history: "+P(o);throw h("server.ts").error(r),o}},m0t=async e=>{try{if(e.trim().length===0)throw new C(_.C_TTV_SETTING_SUGGESTION_ERROR,{errorType:"invalid_request"},"originalScript is empty");if(!await wo())throw new C(_.C_TTV_SETTING_SUGGESTION_ERROR,{errorType:"authorization"},"idToken is missing");const t={originalScript:e},o=await bn("/recommend-ttv-settings",{method:"POST",body:JSON.stringify(t)}),r=await me(o,_.C_STOCK_NETWORK_ERROR);if(r.result==="error")throw new C(_.C_TTV_SETTING_SUGGESTION_ERROR,{errorType:r.errorType},r.errorType+": "+r.errorMsg);return r.recommendation}catch(t){throw h("server.ts").error("error occured while recommending TTV settings. "+P(t)),t}},h0t=async e=>{try{if(e.clipText.trim().length===0)throw new C(_.C_IMAGE_VIDEO_PROMPT_RECOMMENDATION_ERROR,{errorType:"invalid_request"},"clipText is empty");if(!await wo())throw new C(_.C_IMAGE_VIDEO_PROMPT_RECOMMENDATION_ERROR,{errorType:"authorization"},"idToken is missing");const t=await bn("/recommend-image-video-prompt",{method:"POST",body:JSON.stringify(e)}),o=await me(t,_.C_STOCK_NETWORK_ERROR);if(o.result==="error")throw new C(_.C_IMAGE_VIDEO_PROMPT_RECOMMENDATION_ERROR,{errorType:o.errorType},o.errorType+": "+o.errorMsg);return o.recommendation}catch(t){throw h("server.ts").error("error occured while recommending image/video prompt. "+P(t)),t}};class SCe{aborted;isFinished;canceled;processId;constructor(t){this.aborted=!1,this.isFinished=!1,this.canceled=!1,this.processId=t}abort=()=>{this.aborted=!0};done=()=>{this.isFinished=!0};cancel=()=>{this.canceled=!0};isAborted=()=>this.aborted;isDone=()=>this.isFinished;isCanceled=()=>this.canceled;getProcessId=()=>this.processId}class qN{aborted;isFinished;canceled;processType;constructor(t){this.aborted=!1,this.isFinished=!1,this.canceled=!1,this.processType=t}spawnChildProcess(t){}abort(){this.aborted=!0}done(){this.isFinished=!0}cancel(){this.canceled=!0}isAborted(){return this.aborted}isDone(){return this.isFinished}isCanceled(){return this.canceled}commit(t){}getProcessId(){return""}getChildProcessIds(){return[]}getType(){return this.processType}getProcesses(){return new Map}}class OCe extends qN{analysisStatus;childProcesses;analysisType;lastProgress;constructor(t){super(Xi.ANALYSIS);const o=new Map,r=new Map,n=new Map,a=new Map,i=new Map;this.analysisStatus={facadeStages:o,hardcutStages:r,autoSplitSceneStages:n,captionCorrectionStages:a,sttAnalyzeOption:t.sttAnalyzeOption,audioExtractStages:i},this.childProcesses=new Map,this.analysisType=t.analysisType,this.lastProgress=0}spawnChildProcess=t=>{const o=new SCe(t);return this.childProcesses.set(t,o),o};getChildProcessIds=()=>Array.from(this.childProcesses.values()).map(t=>t.getProcessId());getProcesses=()=>this.childProcesses;shouldKillFfmpeg=()=>this.analysisType===Nr.HARDCUT_ONLY||this.analysisType===Nr.STT_AND_HARDCUT||this.analysisType===Nr.STT_AND_HARDCUT_AND_AUTO_SPLIT_SCENE||this.analysisType===Nr.STT_AND_HARDCUT_AND_CAPTION_CORRECTION||this.analysisType===Nr.STT_AND_HARDCUT_AND_AUTO_SPLIT_SCENE_AND_CAPTION_CORRECTION;abort=async()=>
1180{super.abort(),this.childProcesses.forEach(t=>t.abort()),this.shouldKillFfmpeg()&&(await ae())("ffmpeg.ffmpegKill")};done=async()=>{super.done(),this.childProcesses.forEach(t=>t.done()),this.shouldKillFfmpeg()&&(await ae())("ffmpeg.ffmpegKill")};cancel=async()=>{super.cancel(),this.childProcesses.forEach(t=>t.cancel()),this.shouldKillFfmpeg()&&(await ae())("ffmpeg.ffmpegKill")};commit=t=>{switch(t.type){case Ll.UPDATE_AUDIO_ANALYSIS:{const{processId:o,stage:r}=t;this.analysisStatus.facadeStages.set(o,r);return}case Ll.UPDATE_HARDCUT:{const{processId:o,progress:r}=t;this.analysisStatus.hardcutStages.set(o,r);return}case Ll.UPDATE_AUTO_SPLIT_SCENE:{const{processId:o,progress:r}=t;this.analysisStatus.autoSplitSceneStages.set(o,r);return}case Ll.UPDATE_CAPTION_CORRECTION:{const{processId:o,progress:r}=t;this.analysisStatus.captionCorrectionStages.set(o,r);return}case Ll.UPDATE_AUDIO_EXTRACT:{const{processId:o,progress:r}=t;this.analysisStatus.audioExtractStages.set(o,r);return}}};getIntegratedProgress=()=>{const s=this.getSttProgress()??0,x=this.getHardcutProgress()??0,c=this.getAutoSplitSceneProgress()??0,l=this.getCaptionCorrectionProgress()??0,d=this.getAudioExtractProgress()??0,u=ue(s*.8+d*.2,0),p=ue((x+u)/2,0),f=ue(u*.8+c*.2,0),E=ue(p*.8+c*.2,0),T=ue(u*.8+l*.2,0),O=ue(p*.8+l*.2,0),S=ue(f*.8+l*.2,0),R=ue(E*.8+l*.2,0);switch(this.analysisType){case Nr.STT_ONLY:return this.lastProgress=Math.max(this.lastProgress,u),this.lastProgress;case Nr.HARDCUT_ONLY:return this.lastProgress=Math.max(this.lastProgress,x),this.lastProgress;case Nr.STT_AND_HARDCUT:return this.lastProgress=Math.max(this.lastProgress,p),this.lastProgress;case Nr.STT_AND_AUTO_SPLIT_SCENE:return this.lastProgress=Math.max(this.lastProgress,f),this.lastProgress;case Nr.STT_AND_CAPTION_CORRECTION:return this.lastProgress=Math.max(this.lastProgress,T),this.lastProgress;case Nr.STT_AND_HARDCUT_AND_CAPTION_CORRECTION:return this.lastProgress=Math.max(this.lastProgress,O),this.lastProgress;case Nr.STT_AND_AUTO_SPLIT_SCENE_AND_CAPTION_CORRECTION:return this.lastProgress=Math.max(this.lastProgress,S),this.lastProgress;case Nr.STT_AND_HARDCUT_AND_AUTO_SPLIT_SCENE:return this.lastProgress=Math.max(this.lastProgress,E),this.lastProgress;case Nr.STT_AND_HARDCUT_AND_AUTO_SPLIT_SCENE_AND_CAPTION_CORRECTION:return this.lastProgress=Math.max(this.lastProgress,R),this.lastProgress;default:return 0}};getAudioExtractProgress=()=>{if(this.analysisStatus.audioExtractStages.size===0)return;const t=Array.from(this.analysisStatus.audioExtractStages.values()).reduce((o,r)=>o+r,0)/this.analysisStatus.audioExtractStages.size;return ue(t*100,2)};getSttProgress=()=>{if(this.getFacadeStageSize()===0)return;const t=this.getFacadeStages();if(t.some(({progress:r})=>!r))return;const o=t.map(({progress:r})=>r).reduce((r,n)=>r+n)/this.getFacadeStageSize();return ue(o*100,2)};getHardcutProgress=()=>{if(this.getHardcutStageSize()===0)return;const t=this.getHardcutStages();if(t.some(r=>!r))return;const o=t.map(r=>r).reduce((r,n)=>r+n)/this.getHardcutStageSize();return ue(o,2)};getAutoSplitSceneProgress=()=>{if(this.getAutoSplitSceneStageSize()===0)return;const t=this.getAutoSplitSceneStages();if(t.some(r=>!r))return;const o=t.map(r=>r).reduce((r,n)=>r+n)/this.getAutoSplitSceneStageSize();return ue(o,2)};getCaptionCorrectionProgress=()=>{if(this.getCaptionCorrectionStageSize()===0)return;const t=this.getCaptionCorrectionStages();if(t.some(r=>!r))return;const o=t.map(r=>r).reduce((r,n)=>r+n)/this.getCaptionCorrectionStageSize();return ue(o,2)};getIntegratedMessage=()=>{const t=this.getSttMessage(),o=this.getSttProgress(),r=this.getHardcutProgress(),n=this.getAutoSplitSceneProgress(),a=this.getCaptionCorrectionProgress(),i=this.analysisType,s=100;switch(i){case Nr.STT_ONLY:return t;case Nr.HARDCUT_ONLY:return A("hardcut.modal_display_msg");case Nr.STT_AND_HARDCUT:return o===s?A("hardcut.modal_display_msg"):t;case Nr.STT_AND_AUTO_SPLIT_SCENE:return o===s&&n!==s?A("auto_split_scenes.progress"):t;case Nr.STT_AND_CAPTION_CORRECTION:return o===s&&a!==s?A("caption_correction.progress"):t;case Nr.STT_AND_HARDCUT_AND_CAPTION_CORRECTION:return o===s&&r===s&&a!==s?A("caption_correction.progress"):o===s?A("hardcut.modal_display_msg"):t;case Nr.STT_AND_AUTO_SPLIT_SCENE_AND_CAPTION_CORRECTION:return o===s&&n===s&&a!==s?A("caption_correction.progress"):o===s&&n!==s?A("auto_split_scenes.progress"):t;case Nr.STT_AND_HARDCUT_AND_AUTO_SPLIT_SCENE:return o===s&&r===s&&n!==s?A("auto_split_scenes.progress"):o===s?A("hardcut.modal_display_msg"):t;case Nr.STT_AND_HARDCUT_AND_AUTO_SPLIT_SCENE_AND_CAPTION_CORRECTION:return o===s&&r===s&&n===s&&a!==s?A("caption_correction.progress"):o===s&&r===s&&n!==s?A("auto_split_scenes.progress"):o===s?A("hardcut.modal_display_msg"):t;default:return t??A("hardcut.modal_display_msg")}};getSttMessage=()=>{if(!this.analysisStatus.sttAnalyzeOption)return;const t=this.getFacadeText(),{sttAnalyzeOption:{totalMediaDuration:o}}=this.analysisStatus;return A(t,{durationMin:Math.ceil((o??0)/60)})};getFacadeText=()=>{if(this.getFacadeStageSize()===0)return pi.TRANSCRIBE_REQUEST;const t=this.getFacadeStages().map(({text:o})=>o);return t.every(o=>o===pi.TRANCSRIBE_SUCCESS)?pi.TRANCSRIBE_SUCCESS:t.some(o=>o===pi.SERVER_ERROR)?pi.SERVER_ERROR:t.some(o=>o===pi.TRANSCRIBE_UNKNOWN)?pi.TRANSCRIBE_UNKNOWN:t.some(o=>o===pi.TRANSCRIBE_ANALYZE)?pi.TRANSCRIBE_ANALYZE_WITH_DURATION:t.some(o=>o===pi.TRANSCRIBE_ALIGN)?pi.TRANSCRIBE_ALIGN:pi.TRANSCRIBE_REQUEST};getFacadeStageSize=()=>this.analysisStatus.facadeStages.size;getFacadeStages=()=>{const t=this.analysisStatus.facadeStages.values();return t?[...t]:[]};getHardcutStageSize=()=>this.analysisStatus.hardcutStages.size;getHardcutStages=()=>{const t=this.analysisStatus.hardcutStages.values();return t?[...t]:[]};getAutoSplitSceneStageSize=()=>this.analysisStatus.autoSplitSceneStages.size;getAutoSplitSceneStages=()=>{const t=this.analysisStatus.autoSplitSceneStages.values();return t?[...t]:[]};getCaptionCorrectionStageSize=()=>this.analysisStatus.captionCorrectionStages.size;getCaptionCorrectionStages=()=>{const t=this.analysisStatus.captionCorrectionStages.values();return t?[...t]:[]};setTotalMediaDuration=t=>{this.analysisStatus.sttAnalyzeOption={...this.analysisStatus.sttAnalyzeOption,totalMediaDuration:t}}}class CCe{aborted;isFinished;canceled;processId;constructor(t){this.aborted=!1,this.isFinished=!1,this.canceled=!1,this.processId=t}abort=()=>{this.aborted=!0};done=()=>{this.isFinished=!0};cancel=()=>{this.canceled=!0};isAborted=()=>this.aborted;isDone=()=>this.isFinished;isCanceled=()=>this.canceled;getProcessId=()=>this.processId}class RCe extends qN{childProcesses;constructor(){super(Xi.CLIPBOARD),this.childProcesses=new Map}abort=()=>
1180{super.abort(),this.childProcesses.forEach(t=>t.abort())};spawnChildProcess=t=>{const o=new CCe(t);return this.childProcesses.set(t,o),o};getProcesses=()=>this.childProcesses}class ACe{aborted;isFinished;canceled;processId;constructor(t){this.aborted=!1,this.isFinished=!1,this.canceled=!1,this.processId=t}abort=()=>{this.aborted=!0};done=()=>{this.isFinished=!0};cancel=()=>{this.canceled=!0};isAborted=()=>this.aborted;isDone=()=>this.isFinished;isCanceled=()=>this.canceled;getProcessId=()=>this.processId}class yCe extends qN{childProcesses;constructor(){super(Xi.VDROP),this.childProcesses=new Map}abort=()=>{super.abort(),this.childProcesses.forEach(t=>t.abort())};spawnChildProcess=t=>{const o=new ACe(t);return this.childProcesses.set(t,o),o};getProcesses=()=>this.childProcesses}class vCe{uploadingLifecycle;jobs;updateUploadingProgressPayload=t=>{const o=ni.getInstance(Ur.UPLOADING),r=o.getPayload();r!==null&&o.setPayload(t(r))};constructor(t){this.uploadingLifecycle=t,this.jobs=new Map}startJob=(t,o)=>{switch(o.type){case Xi.ANALYSIS:{const{analysisJobList:r,sttAnalyzeOption:n,analysisType:a}=o;this.jobs.set(t,new OCe(o));const i={jobId:t,analysisJobList:r,analysisType:a,message:A("transcribe.request_start"),sttAnalyzeOption:n};this.uploadingLifecycle.startToUpload(i),o.shouldDisplayProgress&&ni.getInstance(Ur.UPLOADING).openProgress({...i,progress:0});return}case Xi.VDROP:{this.jobs.set(t,new yCe);return}case Xi.CLIPBOARD:{this.jobs.set(t,new RCe);return}}};updateTotalMediaDuration=t=>{this.uploadingLifecycle.updateTotalMediaDuration(t),this.updateUploadingProgressPayload(o=>({...o,sttAnalyzeOption:o.sttAnalyzeOption?{...o.sttAnalyzeOption,totalMediaDuration:t}:o.sttAnalyzeOption})),this.jobs.forEach(o=>{o.getType()===Xi.ANALYSIS&&o.setTotalMediaDuration(t)})};startProcess=(t,o)=>{const{jobId:r}=o,n=this.jobs.get(r);if(n===void 0){h("IntegratedProgress.ts").warn("Subprocess spawn requested but parent process doesn't exist, parent id: "+r+" child id: "+t);return}if(n.spawnChildProcess(t)===void 0){h("IntegratedProgress.ts").warn("child process spawn failed, parent id: "+r+" child id: "+t);return}};cleanupJob=t=>{pt().updateIconProgressBar(void 0);const o=this.jobs.get(t);if(o===void 0){h("IntegratedProgress.ts").warn("cleanup job is called on "+t+" but process doesn't exist");return}o.getType()===Xi.ANALYSIS&&(this.uploadingLifecycle.endOfUpload(),Zy(Ur.UPLOADING)),this.jobs.delete(t)};cancelJob=t=>{const o=this.jobs.get(t);if(o===void 0){h("IntegratedProgress.ts").warn("cancel job called on "+t+" but it doesn't exist");return}o.cancel()};abortJob=t=>{const o=this.jobs.get(t);if(o===void 0){h("IntegratedProgress.ts").warn("abort job called on "+t+" but it doesn't exist");return}o.abort()};markJobAsDone=t=>{const o=this.jobs.get(t);if(o===void 0){h("IntegratedProgress.ts").warn("mark as done on job "+t+" but it doesn't exist");return}o.done()};markProcessAsDone=(t,o)=>{const r=this.jobs.get(t);if(!r)return;const n=r.getProcesses().get(o);if(n===void 0){h("IntegratedProgress.ts").warn("mark as done on process "+o+" but it doesn't exist");return}n.done()};isCanceled=t=>{switch(t.type){case Ii.JOB:return this.isJobCanceled(t.jobId);case Ii.PROCESS:return this.isProcessCanceled(t.jobId,t.processId)}};isAborted=t=>{switch(t.type){case Ii.JOB:return this.isJobAborted(t.jobId);case Ii.PROCESS:return this.isProcessAborted(t.jobId,t.processId)}};isDone=t=>{switch(t.type){case Ii.JOB:return this.isJobDone(t.jobId);case Ii.PROCESS:return this.isProcessDone(t.jobId,t.processId)}};isJobCanceled=t=>{const o=this.jobs.get(t);if(o===void 0){h("IntegratedProgress.ts").warn("isCanceled on job "+t+" but it doesn't exist");return}return o.isCanceled()};isJobAborted=t=>{const o=this.jobs.get(t);if(o===void 0){h("IntegratedProgress.ts").warn("isAborted on job "+t+" but it doesn't exist");return}return o.isAborted()};isJobDone=t=>{const o=this.jobs.get(t);if(o===void 0){h("IntegratedProgress.ts").warn("isDone on job "+t+" but it doesn't exist");return}return o.isDone()};isProcessCanceled=(t,o)=>{const r=this.jobs.get(t);if(!r)return;const n=r.getProcesses().get(o);if(n===void 0){h("IntegratedProgress.ts").warn("isCanceled on process "+o+" but it doesn't exist");return}return n.isCanceled()};isProcessAborted=(t,o)=>{const r=this.jobs.get(t);if(!r)return;const n=r.getProcesses().get(o);if(n===void 0){h("IntegratedProgress.ts").warn("isaborted on process "+o+" but it doesn't exist");return}return n.isAborted()};isProcessDone=(t,o)=>{const r=this.jobs.get(t);if(!r)return;const n=r.getProcesses().get(o);if(n===void 0){h("IntegratedProgress.ts").warn("isDone on process "+o+" but it doesn't exist");return}return n.isDone()};commitProgress=(t,o)=>{const r=this.jobs.get(t);if(r===void 0){h("IntegratedProgress.ts").warn("commit on job "+t+" but it doesn't exist");return}if(r.commit(o),r.getType()===Xi.ANALYSIS){const n=r,a=n.getIntegratedProgress(),i=o.type===Ll.UPDATE_MESSAGE?o.message:n.getIntegratedMessage();
1180pt().updateIconProgressBar(a/100),this.uploadingLifecycle.updateUploadProgress({progress:a,message:i}),this.updateUploadingProgressPayload(s=>({...s,progress:a,message:i??s.message}));return}else{const a=A(pi.TRANSCRIBE_REQUEST);this.uploadingLifecycle.updateUploadProgress({progress:0,message:a}),this.updateUploadingProgressPayload(i=>({...i,progress:0,message:a}))}};getProgressInfoOnCancel=t=>{const o=this.jobs.get(t);if(o===void 0)return h("IntegratedProgress.ts").warn("getProgressInfoOnCancel on job "+t+" but it doesn't exist"),{sttProgress:void 0,hardcutProgress:void 0,autoSplitSceneProgress:void 0};if(o.getType()!==Xi.ANALYSIS)return h("IntegratedProgress.ts").warn("getProgressInfoOnCancel on job "+t+" but it's not an analysis job"),{sttProgress:void 0,hardcutProgress:void 0,autoSplitSceneProgress:void 0};const r=o,n=r.getSttProgress(),a=r.getHardcutProgress(),i=r.getAutoSplitSceneProgress();return{sttProgress:n,hardcutProgress:a,autoSplitSceneProgress:i}}}let oh;const I0t=e=>{if(oh)throw new C(_.C_LOGIC_ERROR);oh=new vCe(e)},Cr=()=>{if(!oh)throw new C(_.C_LOGIC_ERROR);return oh},wCe=[{regex:OU,lang:rr.JAPANESE},{regex:SU,lang:rr.HANGUL},{regex:M6,lang:rr.CHINESE},{regex:D6,lang:rr.LATIN}],K7=e=>{if(e.length===0)return rr.EMPTY;const t={[rr.HANGUL]:0,[rr.JAPANESE]:0,[rr.CHINESE]:0,[rr.LATIN]:0,[rr.UNKNOWN]:0,[rr.EMPTY]:0};for(const n of e)for(const a of wCe)if(a.regex.test(n)){t[a.lang]++;break}const o=[[rr.HANGUL,t[rr.HANGUL]],[rr.JAPANESE,t[rr.JAPANESE]],[rr.CHINESE,t[rr.CHINESE]],[rr.LATIN,t[rr.LATIN]]];return o.reduce((n,[,a])=>n+a,0)===0?rr.UNKNOWN:t[rr.CHINESE]>0&&t[rr.JAPANESE]>0&&t[rr.HANGUL]===0&&t[rr.LATIN]===0?rr.JAPANESE:(o.sort((n,a)=>a[1]-n[1]),o[0][0])},NCe=2,T0t=async(e,t,o)=>new Promise(async(r,n)=>{let a=!1;(async()=>{for(;!a&&!Cr().isProcessAborted(t,o)&&!Cr().isProcessDone(t,o);)Cr().isProcessCanceled(t,o)&&n(new C(_.C_UPLOAD_USER_CANCELED)),await Fo(1e3)})();try{const i=await e;a=!0,r(i)}catch(i){a=!0,n(i)}}),PCe=e=>e.reduce((t,o)=>{const r=o.toString(),n=t.get(r),a=(n||0)+1;return t.set(r,a)},new Map),S0t=(e,t)=>{const o=PCe(e),r=[];return o.forEach((n,a)=>
1180{if(n>=e.length*t){const i=parseFloat(a);r.push(i)}}),r},bCe=e=>e.replace(Mh,".vrew"),LCe=(e,t="xml")=>e.replace(Mh,"."+t),MCe=(e,t)=>e.replace(Mh,"."+t),EA=e=>e.replace(Mh,""),CD=e=>bh.test(e),DCe=e=>(Oo()?bi(F6):bi(Ed)).test(e.name),O0t=e=>e.filter(t=>!DCe(t)),kCe=(e,t,o)=>{const r=e.dataset[t];if(r!==void 0)return{element:e,data:o(r)};if(e.parentElement)return kCe(e.parentElement,t,o)};class X7{constructor(t=0,o=0,r=0){this.expected=t,this.actual=o,this.lastPieceDeltaInternal=r}expected;actual;lastPieceDeltaInternal;accumulate=(t,o,r)=>{this.expected+=t,this.actual+=o,this.lastPieceDeltaInternal=r};get delta(){return parseFloat((this.expected-this.actual).toFixed(3))}get lastPieceDelta(){return parseFloat(this.lastPieceDeltaInternal.toFixed(3))}}const C0t=e=>e.indexOf(`
1181`)>0?"two-line":"one-line",R0t=(e,t)=>{const o=e.className;if(typeof o!="string")return!1;let r=o.split(" ").includes(t),n=e.parentElement;for(;n&&!r;)r=n.className.split(" ").includes(t),n=n.parentElement;return r},FCe=()=>navigator.userAgent==="ReactSnap",QN=e=>{let t=0,o=0,r=0,n=e;return t=Math.trunc(e/3600),n-=t*3600,o=Math.trunc(n/60),n-=o*60,r=Math.trunc(n),t>0?t+A("remained.hour")+" "+o+A("remained.min")+" "+r+A("remained.sec"):o>0?o+A("remained.min")+" "+r+A("remained.sec"):r+A("remained.sec")},UCe=e=>e%180!==0&&e%90===0,I0=e=>{let t=e.width;e.paspH&&e.paspV&&(t=Math.round(t*e.paspH/e.paspV));const o=On(t),r=On(e.height);return e.rotation!==void 0&&UCe(e.rotation)?{width:r,height:o}:{width:o,height:r}},A0t=e=>e.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&"),LT=e=>e.replace(/\u00a0/g," "),y0t=e=>e.indexOf(" ")<0&&e.indexOf(" ")<0?e:LT(e).replace(/ {2}/g,"  ").replace(/ $/," "),ZN=(e,t,o="0")=>(Array(t+1).join(o)+e).slice(-t),VCe=e=>e===ce.English||e===ce.Spanish,GCe=(e,t)=>Math.abs(e-t)<1e-4,WCe=(e,t)=>{let o="",r=!1,n=!1;const a=[];t===void 0&&(t=NCe);for(let i=0;i<e.length;i++)e[i]>="a"&&e[i]<="z"?!r&&o.length<t?o+=e[i]:(o&&(a.push(o),o=""),a.push(e[i]),r=!0):(r=!!(e[i]>="A"&&e[i]<="Z"),o&&(r?a.push(o):(a.push(o.toUpperCase()),n=!0),o=""),a.push(e[i]));return o&&(a.push(o.toUpperCase()),n=!0),n?a.join(""):e},v0t=(e,t,o)=>vt(e,r=>{const n=r[t];r[t]={...n,...o}}),On=e=>e+(e%2===0?0:1),U2=()=>Ve().get(Ie.LAST_OPEN_FOLDER,void 0),J7=()=>Mt(ke.SAVE_TRAILING_SINGLE_DOT),zu=(e,t)=>{const o=U2(),r=gt(e);if(!o||t===!1){const i=/^http(s):\/\//.test(e),s=nR(e);return i||s?r:e}if(nR(o))return r;const n=o[o.length-1];return(n==="\\"||n==="/"?o:o+JU.sep)+r},QO=e=>Ve().set(Ie.LAST_OPEN_FOLDER,e),HCe=()=>Ha()+"	"+new Date().toISOString(),jCe=(e,t,o,r,n,a,i)=>[jt.createElement(Qr,{key:"left-"+a},e),jt.createElement("a",{key:"link_a_"+a,href:o,target:"_blank",onClick:i},/https:\/\/.*/.test(t)?t:jt.createElement(Qr,null,t),n),jt.createElement(Qr,{key:"right-"+a},r)],w0t=e=>e.replace(/([\\`*_~[\]<])/g,"\\$1"),zCe=(e,t,o)=>{const r=/([\s\S]*)\[(.+)\]\((.*)\)(.*)/,n=e.split(")");return(n.length===1?[jt.createElement(Qr,{},n[0])]:n.map((i,s,x)=>{const c=s===x.length-1,l=c?i:i+")",d=l.match(r);if(!d)return[jt.createElement(Qr,{key:"remain-"+s},l)];const[,u,p,f,E]=d;return jCe(u,p,f,E,o,s,t)})).flat()},p0=(e,t)=>jt.createElement(Qr,{options:{overrides:{a:{component:"a",props:{style:{color:ee.blue[400],textDecoration:"underline"},...t?.withLinkClickHandler&&{onClickCapture:pRe}}}}}},e.replace(/\n/g,"<br/>")),V2=async e=>new Promise((t,o)=>{const r=new FileReader;r.onloadend=()=>{const n=r.result;if(typeof n!="string"){const a=n===null?"null":"ArrayBuffer",i="type mismatch in toBase64: read as "+a+", blob type "+e.type+", blob size "+e.size+", state: "+r.readyState;h("misc.ts").error(i),o(new C(_.C_BLOB_READ_ERROR,{},i))}else t(n)},r.onerror=n=>{const a="Error during toBase64: "+P(r.error)+", evt: "+n?.loaded+" "+n?.total+" "+n?.lengthComputable;h("misc.ts").error(a),o(new C(_.C_BLOB_READ_ERROR,{},a))},r.readAsDataURL(e)}),N0t=e=>{const t=";base64,",o=e.indexOf(t);return e.startsWith("data:")&&o>=0?e.slice(o+t.length):e},YCe=e=>e.getFullYear()+"-"+e.getMonth()+"-"+e.getDate()+" "+e.getHours()+":"+e.getMinutes()+":"+e.getSeconds(),P0t=e=>{const t=e;return{shiftKey:t.shiftKey,ctrlKey:Mr()?t.metaKey:t.ctrlKey}},q7=(e,t=void 0)=>{const o={...e};for(const r in o)o[r]===t&&delete o[r];return o},z0=(e,t,o,r=!1)=>{let n=0,a=e.length-1,i=0;if(e.length!==0){for(;n<=a;){i=Math.floor((n+a)/2);const s=o(e[i],t);s<=0?a=i-1:s>0&&(n=i+1)}return n<e.length&&o(e[n],t)===0||r?n:void 0}},BCe=(e,t)=>
1181{const[o,r]=e,[n,a]=t;return o<=n&&a<=r},ZO=e=>{const t=(e?.snapshots.past.length??0)-1;return e?.snapshots.past[t]},b0t=(e,t)=>{const a=e.getTime()-t.getTime(),i=Math.floor(a/864e5),s=Math.floor((a-864e5*i)/36e5),x=Math.floor((a-864e5*i-36e5*s)/6e4);return{day:i,hour:s,min:x}},KCe=(e,t,o,r)=>{const n=t<=o,a=r<=e;return n===!1&&a===!1},Xo=()=>Oo()?rd.DESKTOP_APP:rd.TRY,Bf=e=>/^(https?|ftp):\/\//.test(e),Q7=async()=>{const e=pt(),t=await e.getDownloadUrl();e.openUrl(t)},L0t=(e,t)=>{let o=null;return(...n)=>{o!==null&&(clearTimeout(o),o=null),o=window.setTimeout(()=>e(...n),t)}};function MT(e,t=100){let o=!1;return function(...r){!o&&(e.apply(this,r),o=!0,setTimeout(()=>{o=!1},t))}}const XCe=e=>{const t=new Date().getTime(),o=Date.parse(e);return isNaN(o)?Math.floor(t/1e3):Math.floor((t-o)/1e3)},G2=async(e,t)=>{const o=h("misc.ts");let r=0;const n=$b;for(let a=1;a<=$b;a++){if(await Fo(r),t?.aborted)return o.info("upload request was cancelled during retry "+a+"."),null;try{return await e()}catch(i){if(no(i))return o.info("upload request was cancelled during retry "+a+", e.name: "+i.name+"."),null;if(navigator.onLine===!1)throw o.info("Network is offline, upload request was cancelled during retry "+a+"."),new C(_.S3_UPLOAD_NETWORK_ERROR,{},"");o.error("Error occured during retry, retryCount: "+a+" error: "+P(i))}r=Math.pow(2,a)*100}throw new C(_.C_RETRIER_ERROR,{},"all "+n+" Retry failed")},Wr=async(e,t,o,r)=>{const n=h("misc.ts"),a="[generalRetrier:"+o+"]";let i=0,s="";for(let x=1;x<=t;x++){await Fo(i),r?.throwIfAborted();try{const c=await e();return x>1&&n.info(a+" succeeded after "+x+"/"+t+" attempts"),c}catch(c){r?.throwIfAborted(),s=P(c),n.error(a+" attempt "+x+"/"+t+" failed. error: "+s)}i=Math.pow(2,x)*100}throw new C(_.C_RETRIER_ERROR,{},a+" all "+t+" retries failed. last error: "+s)},Z7=async(e,t={})=>{const o=h("misc.ts"),{maxRetry:r=3,onRetry:n}=t;let a=0;for(let s=1;s<=r;s++){if(await Fo(a),navigator.onLine===!1){const x="Network is offline, fetch cancelled during retry "+s+".";throw o.info("Network is offline, fetch cancelled during retry "+s+"."),new C(_.C_NETWORK_OFFLINE,{},x)}try{return await e()}catch(x){if(o.error("Fetch error during retry "+s+"/"+r+": "+P(x)),n?.(s,x),s===r){const c="Fetch failed after "+s+" attempts: "+P(x);throw o.error(c),new C(_.C_FILE_DOWNLOAD_FAILED,{totalAttempts:s},c)}}a=Math.pow(2,s)*100}const i="Fetch failed after "+r+" attempts";throw o.error(i),new C(_.C_FILE_DOWNLOAD_FAILED,void 0,i)},tf=e=>{let t=0;const o=[];return r=>new Promise((n,a)=>{const i=async()=>{t++;try{const s=await r();n(s)}catch(s){a(s)}finally{t--,o.length>0&&o.shift()()}};t<e?i():o.push(i)})},M0t=(e,t)=>(e%t+t)%t,RD=(e,t,o)=>e>o&&o>=t||e<=o&&o<t,D0t=e=>{if(e.length===0)return!0;for(let t=1;t<e.length;t++)if(e[t]-t!==e[0])return!1;return!0},k0t=(e,t=(o,r)=>o.includes(r))=>e.reduce((o,r)=>(t(o,r)||o.push(r),o),[]),JCe=e=>{const t=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],o=Math.floor(Math.log(e)/Math.log(1024));return(e/Math.pow(1024,o)).toFixed(1)+" "+t[o]},Bs=async e=>{const t=e.slice(0,8),o=await t.arrayBuffer(),r=new Uint8Array(o),n=s=>[...s].map(x=>x.charCodeAt(0)),a=(s,x=0)=>s.every((c,l)=>c===r[l+x]);return[{ext:"jpg",info:[{sigs:[255,216,255]}]},{ext:"png",info:[{sigs:[137,80,78,71,13,10,26,10]}]},{ext:"gif",info:[{sigs:[71,73,70]}]},{ext:"bmp",info:[{sigs:[66,77]}]},{ext:"tif",info:[{sigs:[73,73,42,0]},{sigs:[73,32,73]}]},{ext:"mp3",info:[{sigs:n("ID3")},{sigs:[255,251]},{sigs:[255,243]},{sigs:[255,242]}]},{ext:"wav",info:[{sigs:[82,73,70,70]},{sigs:[87,65,86,69]}]},{ext:"flac",info:[{sigs:n("fLaC")}]},{ext:"m4a",info:[{sigs:[102,116,121,112],offset:4}]},{ext:"aac",info:[{sigs:[255,241]},{sigs:[255,249]}]},{ext:"ogg",info:[{sigs:[79,103,103,83]}]},{ext:"webm",info:[{sigs:[26,69,223,163]}]}].find(({info:s})=>s.some(({sigs:x,offset:c})=>a(x,c)))?.ext??ZE},DT=async e=>e.type&&e.type!=="application/octet-stream"?e.type:X0.getType(await Bs(e))??e.type,F0t=(e,t)=>{const o=e.normalize("NFC").toLowerCase(),r=t.normalize("NFC").toLowerCase();return o.includes(r)},$7=(e,t,o,r,n)=>{let i=!1,s=0,x=0;return o<=e&&e<=r&&(i=!0),o<=t&&t<=r&&(i=!0),e<=o&&o<=t&&(i=!0),e<=r&&r<=t&&(i=!0),s=n?Math.max(e,o)-e:Math.max(e,o),x=n?Math.min(t,r)-e:Math.min(t,r),i&&x-s>.01?[s,x]:null},U0t=(e,t,o,r)=>{const n=o-e,a=r-t;return Math.sqrt(Math.pow(n,2)+Math.pow(a,2))},V0t=(e,t,o,r)=>{const n=o-e,a=r-t;return qCe(Math.atan2(a,n))},G0t=e=>e*Math.PI/180,qCe=e=>e*180/Math.PI,AD=(e,t,o)=>{let r=e,n=t;if(r>n)throw new C(_.C_LOGIC_ERROR,{},"start must be smaller than end or equal to end.");if(o<0)throw new C(_.C_LOGIC_ERROR,{},"source duration can not be negative.");if(o===0)return{start:0,end:0};for(;r<0||n<0;)r+=o,n+=o;
1181const a=n-r,i=r%o,s=Math.min(o,i+a);return{start:ue(i,3),end:ue(s,3)}},QCe=(e,t,o)=>{let r=e,n=t;if(r>n)throw new C(_.C_LOGIC_ERROR,{},"start must be smaller than end or equal to end.");if(o<0)throw new C(_.C_LOGIC_ERROR,{},"source duration can not be negative.");if(o===0)return[];for(;r<0||n<0;)r+=o,n+=o;const a=[];let i=n-r;const s=.001;let x=r%o,c=Math.min(o,x+i),l=c-x;for(;i>s;)a.push({start:ue(x,3),end:ue(c,3)}),i-=l,x=0,c=Math.min(o,x+i),l=c-x;return a},ZCe=e=>{const t=h("misc.ts"),o=[...Eo(ce).values()],r=Object.keys(e);for(let n=0;n<r.length;++n){const a=r[n];if(!o.includes(a))return t.warn("Key "+a+" is not member of Language}"),!1;const i=e[a];if(!Array.isArray(i))return t.warn("Key "+a+" value type is not array : "+typeof i),!1;for(const s of i){const{title:x,desc:c,link:l,tooltip:d}=s;if(typeof x!="string"||typeof c!="string"||typeof l!="string"||typeof d<"u"&&typeof d!="string")return t.warn("bannerEntry "+JSON.stringify(i)+" is malformed."),!1}}return!0},$Ce=(e,t)=>Math.abs(e-t)<.01,W0t=e=>e.stopPropagation(),H0t=()=>{},eRe=()=>Ps()?8191:Mr()?262144:131071,tRe=e=>e?["signIn","newProject","template"].includes(e):!1,j0t=e=>{const t=window.location.search,o=new URLSearchParams(t),r=o.get(e);return tRe(r)?r:null},n_=e=>{const t=new URLSearchParams;for(const r in q7(e))t.append(r,e[r]);const o=t.toString();return o?"?"+o:""},kT=()=>{switch(Fe()){case ce.Korean:return"ko-KR";case ce.Japanese:return"ja-JP";case ce.Spanish:return"es-ES";case ce.Taiwanese:return"zh-TW";default:return"en-US"}},oRe={image:"Vrew Image",video:"Vrew Video",screenshot:"Vrew Screenshot"},rRe={[ce.English]:"at",[ce.Spanish]:"a las"},nRe=/^\s+$/,of=e=>String(e).padStart(2,"0"),aRe=e=>{try{return new Intl.DateTimeFormat(kT(),{hour:"numeric",minute:"2-digit",second:"2-digit"}).formatToParts(e).map(t=>t.type!=="literal"?t.value:nRe.test(t.value)?" ":".").join("").replace(/^[\s.]+|[\s.]+$/g,"")}catch{return of(e.getHours())+"."+of(e.getMinutes())+"."+of(e.getSeconds())}},z0t=(e,t=new Date)=>{const o=oRe[e],r=t.getFullYear()+"-"+of(t.getMonth()+1)+"-"+of(t.getDate()),n=rRe[Fe()]??"",a=aRe(t);return[o,r,n,a].filter(Boolean).join(" ")},Y0t=e=>{const t=kT();return new Intl.NumberFormat(t,{notation:"compact"}).format(e)},yD=(e,t,o)=>(e-t)/(o-t),vD=(e,t,o)=>e+(t-e)*o,iRe=(e,t)=>{const o=Fe(),r=o===ce.English,n=r?"en-US":kT();return new Intl.DateTimeFormat(n,t??{year:"numeric",month:r?"short":"2-digit",day:"2-digit"}).format(e)},sRe=e=>{const t=kT();return new Intl.DateTimeFormat(t,{hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).format(e)},vx=(e,t=!1,o)=>{if(e===void 0)return"";const r=typeof e=="string"?new Date(e):e,n=iRe(r,o);return t?n+" "+sRe(r):n},wD=e=>{if(e===void 0)return;const t=typeof e=="string"?new Date(e):e;return na.fromJSDate(t).minus({minutes:1}).toJSDate()},mA=e=>{try{const t=new Date(e),o=new Date;if(isNaN(t.getTime()))return;const r=o.getTime()-t.getTime(),n=Math.floor(r/(1e3*60*60*24)),a=Math.floor(n/7);return{daysPassed:n,weeksPassed:a}}catch(t){h("misc.ts").error(`
1182      Failed to calculate time difference.
1183      Error: `+P(t)+`
1184    `);return}},FT=(e,t)=>{const o=[];for(let r=0;r<e.length;r+=t)o.push(e.slice(r,r+t));return o},xRe=e=>(e=e.replace(/[\r\n]/g,"").replace(/\s+/g," "),e=e.replace(/\s*{\s*/g,"{").replace(/\s*:\s*/g,":").replace(/\s*;\s*/g,";"),e=e.replace(/\s*,\s*/g,","),e),ND=(e,t)=>e.map(o=>{const r=L.get(t,o);if(r===void 0){const n=qe();return L.set(t,o,n),n}return r}),cRe=(e,t)=>e+" × "+t,e5=async()=>{const e=h("misc.ts"),t=await pt().getFsInfo();if(!t)return e.error("Failed to get file system information"),null;const o=t.fileSystems.find(r=>Ps()?r.mount==="C:":r.mount==="/");return o||(e.error("Failed to get target mount point filesystem information"),null)},B0t=e=>e.map(t=>({elem:t,sort:Math.random()})).sort((t,o)=>t.sort-o.sort).map(({elem:t})=>t),lRe=e=>Error().stack?.split(`
1185`).slice(2+e).join(`
1186`)??"",K0t=(e,t,o=!0)=>o?Math.round(e/t)*t:Math.floor(e/t)*t,dRe=e=>{if(wi())return;const t=lRe(1);t!==""&&h("misc.ts").info("scrollIntoView() called at "+e+`, stack trace: 
1187`+t)},uRe=e=>{const t=Fe(),o=Dh[e],r=o[t];return r||null},$N=e=>{const t=e.reduce((n,a)=>n+a.length,0),o=new Float32Array(t);let r=0;return e.forEach(n=>{o.set(n,r),r=r+n.length}),o},X0t=(e,t,o,r,n)=>e==="image-fill"&&t!==void 0?un("icon",t,{applied:!0}):e==="remove-background"?un("icon",e,{dark:n}):un("icon",e,{applied:o,loading:r}),J0t=(e,t)=>
1187typeof t=="string"||typeof t=="number"?Eo(e).isValue(t):!1,q0t=e=>Object.keys(e).length===0||Object.keys(e).every(t=>!e[t]),t5=e=>Object.fromEntries(e),a_=async(e,t,o,r,n=1e3)=>{const a=Cr(),i=(e.type===Ii.JOB,e.jobId),s=()=>{const c=a.isCanceled(e),l=a.isAborted(e),d=a.isDone(e);if(c)return"canceled";if(l||d)return"terminal";if(!(c!==void 0&&l!==void 0&&d!==void 0)){if(e.type===Ii.PROCESS){if(a.isJobCanceled(i))return"canceled";if(a.isJobAborted(i)||a.isJobDone(i))return"terminal"}return"missing"}};return k6((async()=>{let c,l=!0;for(;l;){if(c=s(),c!==void 0){l=!1;break}const u=await o();if(c=s(),c==="terminal")return u;if(c!==void 0)break;await Fo(n)}const d=c==="canceled"?_.C_UPLOAD_USER_CANCELED:r;throw new C(d,{progressInfoOnCancel:a.getProgressInfoOnCancel(i)})})(),t,()=>a.abortJob(i))},PD=(e,t=" ",o=!0,r=!1)=>{const n=["remained.hour","remained.min","remained.sec"];return os(e,!1,!1).split(":").map((s,x)=>{if(!(o&&s==="00"&&x!==2))return(r?s:parseInt(s))+A(n[x])}).filter(Se).join(t)},Q0t=(e,t)=>e!=="script"||t,Z0t=async e=>{const t=await NOe();if(t&&QA<t){xt.info(A("common.refresh_suggested"),{autoClose:e});return}},pRe=e=>{e.currentTarget instanceof HTMLAnchorElement&&(e.preventDefault(),pt().openUrl(e.currentTarget.href))},fRe=()=>Ve().get(Ie.GCLID,void 0),gRe=e=>Ve().set(Ie.GCLID,e),_Re=(e,t)=>{if(!e.length)return 0;const o=Math.min(100,Math.max(0,t)),r=o/100*(e.length-1),n=Math.floor(r),a=Math.ceil(r),i=r-n,s=e[n]*(1-i)+e[a]*i;return ue(s,1)},$0t=(e,t)=>{const o=[...e].sort((r,n)=>r-n);return t.map(r=>_Re(o,r))},ERe=e=>na.fromISO(e).isValid,ext=e=>e.reduce((t,o)=>{if(t.length===0)t.push([o]);else{const r=t[t.length-1],n=r[r.length-1];o===n+1?r.push(o):t.push([o])}return t},[]),yi=async(e,t,o,r)=>{const n=at()?await R4(e,t,o,r):await F_e(e,t,o);await se().addFile(n,{skipPrepare:n.skipPrepare})},mRe=async e=>{const t=e.fileLocation===D.LOCAL_TMP;await se().addFile(e,{skipPrepare:t})},eP=async(e,t)=>{const o=new Blob([e]),r={type:"Html",sourceOrigin:tt.USER,mediaId:t,fileLocation:D.IN_MEMORY,name:t+"."+_R,fileSize:o.size,rawHtml:e};await se().addFile({...r,blob:o})},o5=async(e,t)=>{const o=new Blob([e]),r={type:"Svg",sourceOrigin:tt.USER,mediaId:t,fileLocation:D.IN_MEMORY,name:t+"."+ER,fileSize:o.size,rawSvg:e};await se().addFile({...r,blob:o})},vi=async(e,t,o,r)=>{const n=await Bs(e),a={type:"Image",isTransparent:t,sourceOrigin:o??tt.USER,mediaId:r,fileLocation:D.IN_MEMORY,name:r+"."+n,fileSize:e.size};await se().addFile({...a,blob:e})},tP=()=>se().createDummyAudioInfo(),i_=async({mediaId:e,audioBlob:t,sampleRate:o,codec:r,duration:n,sourceOrigin:a,name:i,sourceType:s})=>{const x=Ht(ug.AUDIO_TEMP),c=await ix(x),l=await c.getMediaFileInfo(t);if(!l.audioInfo){const u="[createAssetAudioInfo] Audio info not found for mediaId: "+e;throw h("manager.ts").error(u),new C(_.C_LOGIC_ERROR,{},u)}const d={type:"AVMedia",videoAudioMetaInfo:{duration:n,audioInfo:{sampleRate:o,codec:r,channelCount:l.audioInfo.channelCount},videoInfo:void 0},sourceOrigin:a,fileLocation:D.IN_MEMORY,name:i,mediaId:e,fileSize:t.size,sourceType:s};await se().addFile({...d,blob:t})},hRe=async(e,t,o)=>{const r={type:"Image",isTransparent:!1,sourceOrigin:tt.USER,mediaId:t,fileLocation:D.IN_MEMORY,name:e,fileSize:o.size};await se().addFile({...r,blob:o})},IRe=async(e,t)=>{if(!Vi(e))return;const r=await R4({type:"path",value:t},e,tt.USER);await se().updateFile(r)},r5=async(e,t)=>{const o=Vi(t);if(o?.type!=="Html")return;const r=new Blob([e],{type:"text/html"}),n={...o,fileLocation:D.IN_MEMORY,rawHtml:e,fileSize:r.size};return se().updateFile({...n,blob:r})},n5=async(e,t)=>{const o=Vi(t);if(o?.type!=="Svg")return;const r=new Blob([e],{type:"image/svg+xml"}),n={...o,fileLocation:D.IN_MEMORY,rawSvg:e,fileSize:r.size};return se().updateFile({...n,blob:r})},En=async(e,t)=>await se().getFileBlob(e,t),a5=e=>se().getInMemoryFileBlob(e),TRe=async e=>await se().hasCached(e),Vi=(e,t)=>se().getFileInfo(e,t),i5=async(e,t)=>{const o=Vi(e);if(!o||o.type!=="Image"&&o.type!=="AVMedia")return;if(o.type==="Image"&&t?.mediaType==="video"||o.type==="AVMedia"&&t?.mediaType==="image"){h("manager.ts").warn("[updateVisualAIGenerationMeta] Skip mismatched metadata. fileType: "+o.type+", mediaType: "+t.mediaType);return}const r=async()=>{const a=await En(e);if(!a){const i="[updateVisualAIGenerationMeta] Blob not found for mediaId: "+e;throw h("manager.ts").error(i),new C(_.C_MEDIA_BLOB_LOST,{},i)}return a};if(o.type==="Image"){const a=t?.mediaType==="image"?t:void 0;if(o.fileLocation===D.IN_MEMORY){await se().updateFile({...o,visualAIGenerationMeta:a,blob:await r()});return}await se().updateFile({...o,visualAIGenerationMeta:a});return}const n=t?.mediaType==="video"?t:void 0;if(o.fileLocation===D.IN_MEMORY){await se().updateFile({...o,visualAIGenerationMeta:n,blob:await r()});return}await se().updateFile({...o,visualAIGenerationMeta:n})},gd=e=>{const t=Vi(e);return!t||!Bc(t)?null:t.path},s_=e=>se().getMediaUrl(e),oa=(e,t)=>{const o=Vi(e,t);if(o?.type==="Image")return o},UT=(e,t)=>{const o=Vi(e,t);if(o?.type==="Html")return o},x_=(e,t)=>{const o=Vi(e,t);if(o?.type==="Svg")return o},eo=(e,t)=>{const o=Vi(e,t);if(o?.type==="AVMedia")return o},SRe=e=>se().getProxyInfo(e),W2=()=>se().getAllFileInfos(),Hs=e=>ca().find(t=>t.mediaId===e),ca=()=>se().getAVMediaFiles().filter(Zr),Yu=e=>c_().find(t=>t.mediaId===e),c_=()=>se().getAVMediaFiles().filter(yf),oP=()=>se().getImageFiles(),ORe=e=>{se().removeFile(e)},CRe=Object.freeze(Object.defineProperty({__proto__:null,createAssetAudioInfo:i_,createAssetVideoInfo:yi,createCustomFilterInfo:hRe,createDummyTTSAudioInfo:tP,createImageAssetInfo:vi,createShapeAssetInfo:o5,createTextboxAssetInfo:eP,getAVMediaFileInfo:eo,getFileBlob:En,getHtmlFileInfo:UT,getImageFileInfo:oa,getImageFileInfos:oP,getInMemoryFileBlob:a5,getMainSourceFileInfo:Yu,getMainSourceFileInfos:c_,getMainVideoAudioFileInfo:Hs,getMainVideoAudioFileInfos:ca,getMediaDiskPath:gd,getMediaUrl:s_,getProxyInfo:SRe,getSvgFileInfo:x_,getVrewFileInfo:Vi,getVrewFileInfos:W2,hasCached:TRe,registerPreparedTTVAssetVideo:mRe,removeVrewFile:ORe,updateAssetVideoInfo:IRe,updateShapeAssetInfo:n5,updateTextboxAssetInfo:r5,updateVisualAIGenerationMeta:i5},Symbol.toStringTag,{value:"Module"})),txt=async(e,t,o)=>{const r=an(t),n=await fetch(r).catch(u=>{throw h("bgm.ts").error("Failed to fetch audio from "+r+", "+u.message),new C(_.C_BGM_ERROR,{},u.message)});if(!n.ok)throw new C(_.C_BGM_ERROR,{},"fetching bgm error. path:"+r+" ");const a=await n.blob();!await qt().checkFfmpegExist(!0)&&await qt().downloadFfmpeg(!0);const i=await qt().getAudioMetaInfo(t).catch(u=>{const p=P(u);throw h("bgm.ts").error("Failed to fetch bgm meta info "+t+", "+p),new C(_.C_BGM_ERROR,{},p)});if(i===void 0)throw h("bgm.ts").error("Failed to fetch audio from "+r),new C(_.C_BGM_ERROR,{});const{duration:s,sampleRate:x}=i;if(isNaN(s)||isNaN(x))throw h("bgm.ts").error("Fetched meta info contains NaN values "+JSON.stringify(i)),new C(_.C_BGM_ERROR,{});if(a.size===0){const u="Empty blob is loaded from "+t;throw h("bgm.ts").error(u),new C(_.C_BGM_ERROR,{},u)}const c=gt(t),l=RRe(c);await i_({mediaId:o,audioBlob:a,sampleRate:x,codec:l,duration:s,sourceOrigin:tt.USER,name:c,sourceType:e});const d=eo(o);if(!d){const u="[loadLocalAudioInfo] Audio info not found for mediaId: "+o;throw h("bgm.ts").error(u),new C(_.C_LOGIC_ERROR,{},u)}return d},oxt=e=>{if(e===void 0)return{name:"",extension:""};const t=".",o=e.lastIndexOf(t),r=o>0?e.slice(0,o):e,n=o>0?e.slice(o):"";return{name:r,extension:n}},YE=e=>e<1?0:e<6?.5:2,s5=(e,t,o)=>{const r={};for(let n=0;n<e.length;n++){const a=e[n],i=vo(a),s=hl(a);for(const x of a.assetIds){const c=L.get(o,x);if(c===void 0)continue;const l=c.trackIds.map(u=>L.get(t,u)).find(u=>u!==void 0&&ll(u));if(l===void 0)continue;const d=r[x];d!==void 0?(d.timelineEnd=Math.max(s,d.timelineEnd),d.globalClipRange.to=n+1):r[x]={mediaId:l.mediaId,timelineStart:i,timelineEnd:s,globalClipRange:{type:"GLOBAL_CLIP",from:n,to:n+1}}}}return r},rh=async e=>{const t=h("bgm.ts"),o=3;try{const r=e.includes(z7());return await Wr(()=>fetch(e,r?{credentials:"include"}:void 0).then(a=>{if(!a.ok){h("bgm.ts").error("music fetch response invalid. status: "+a.status+", statusText: "+a.statusText);return}return a.blob()}),o,"fetchingBgmBlob")}catch(r){t.error("Error occured while fetching music. url:"+e+". error: "+P(r));return}},RRe=e=>{switch(e.split(".").at(-1)){case"mp3":return Gt.MP3;case"m4a":return Gt.AAC;case"flac":return Gt.FLAC;case"wav":return Gt.PCM;case"webm":return Gt.OPUS;default:return Gt.MP3}},rxt=async()=>{try{return await cR({id:"select-audio-file",mimeTypes:["audio/*"],extensions:U6.map(t=>"."+t),description:A("filetype.audio"),multiple:!1})}catch(e){h("bgm.ts").error(P(e));return}},nxt=e=>e.id!=="mewpot_bgm_6812"&&!e.site.includes("audionautix"),axt=e=>{const{onPlay:t,onStop:o}=e??{},r=it.useMemo(()=>new window.Audio,[]),n=it.useRef(0),a=it.useCallback(()=>{n.current+=1,r.pause(),r.hasAttribute("src")&&(r.removeAttribute("src"),r.load())},[r]),i=it.useCallback(s=>{n.current+=1,r.pause(),r.src=s,r.load()},[r]);return it.useEffect(()=>{const s=()=>{const l=n.current;r.volume=.5,r.play().then(()=>{l===n.current&&t?.()},d=>{l===n.current&&(h("bgm.ts").error("failed to play bgm preview: "+P(d)),o?.())})},x=()=>o?.(),c=()=>{const{error:l}=r;h("bgm.ts").error("failed to load bgm preview. code: "+l?.code+", message: "+l?.message),n.current+=1,o?.()};return r.addEventListener("loadeddata",s),r.addEventListener("ended",x),r.addEventListener("error",c),()=>{r.removeEventListener("loadeddata",s),r.removeEventListener("ended",x),r.removeEventListener("error",c)}},[r,t,o]),{play:i,stop:a}},ARe=30,bD=3;var yRe=(e=>(e.LOCAL_UPDATED="project_history.local_updated",e.CLOUD_UPDATED="project_history.cloud_updated",e.BROW
1187SER_UPDATED="project_history.browser_updated",e))(yRe||{}),Kn=(e=>(e[e.INIT=0]="INIT",e[e.CUSTOM_LIST=1]="CUSTOM_LIST",e[e.OS_DIALOG_OLD=2]="OS_DIALOG_OLD",e[e.OS_DIALOG_NEW=3]="OS_DIALOG_NEW",e[e.FILE_CLICK=4]="FILE_CLICK",e[e.DRAG_AND_DROP=5]="DRAG_AND_DROP",e[e.UNKNOWN=6]="UNKNOWN",e))(Kn||{});class vRe{eventEmitter=new ad.EventEmitter;localProjects=[];_latestLocalSave=new Map;cloudProjects=[];localInitialized=!1;mostRecentAttemptedOpenMethod=0;constructor(){if(at()){const t=se();this.loadProjects(),t.getEventEmitter().on(co.VREW_FILE_OPENED,(o,r,n)=>{n===Ee.PROJECT&&!t.isSampleProject()?this.localProjectOpened(o,r):n===Ee.CLOUD&&this.cloudProjectOpened(o,r)}).on(co.VREW_FILE_SAVED,(o,r,n,a)=>{n===Ee.PROJECT&&this.localProjectSaved(o,r,a).catch(i=>{h("projectHistoryManager.ts").error("Failed to update local project history: "+P(i))})})}Lt().getEventEmitter().on(mm.SYNC_PROJECTS,()=>{this.updateCloudHistory()})}getLocalProjects=()=>this.localProjects;updateCloudHistory=()=>{const t=Lt().getCloudProjects().filter(tA);this.cloudProjects=t.map(o=>({type:Mn.CLOUD,projectId:o.projectId,filePath:"",projectName:o.projectTitle,lastAccessed:new Date(o.lastModified).getTime(),snapshotId:o.snapshotId,thumbnail:void 0,projectSize:o.totalSize,scheduledDeletionDate:o.scheduledDeletionDate}))};getCloudProjects=()=>this.cloudProjects;cloudProjectOpened=(t,o)=>{this.addSeedToLocalStorage(t)};loadCloudProjects=async()=>{await Lt().syncCloudProjects(),this.updateCloudHistory()};notifyUpdated=t=>{switch(t){case Mn.LOCAL:this.hasListener("project_history.local_updated")&&this.eventEmitter.emit("project_history.local_updated");break;case Mn.CLOUD:this.hasListener("project_history.cloud_updated")&&this.eventEmitter.emit("project_history.cloud_updated");break;case Mn.BROWSER:this.hasListener("project_history.browser_updated")&&this.eventEmitter.emit("project_history.browser_updated");break}};getCloudProjectsForProject=async()=>(await this.loadCloudProjects(),this.cloudProjects);deleteCloudProject=async t=>{await Lt().deleteCloudProject(t),this.notifyUpdated(Mn.CLOUD)};renameCloudProject=async(t,o)=>{await Lt().renameCloudProject(t,o),this.notifyUpdated(Mn.CLOUD)};checkDuplicateBrowserProjectTitle=async(t,o)=>{const r=_n(),n=be().getUserInfo()?.uid??tn;return(await r.getAllValues(Bo.VREW_PROJECT_DB,Ko.VREW_PROJECT)).some(i=>i.uid===n&&i.projectName===t&&i.projectId!==o)};checkDuplicateCloudProjectTitle=async t=>Lt().getCloudProjects().filter(tA).some(r=>r.projectTitle===t);renameBrowserProject=async(t,o)=>{const r=h("projectHistoryManager.ts");if(await this.checkDuplicateBrowserProjectTitle(o,t)){const x='Attempt to rename Browser project failed: The project name "'+o+'" is already in use. Project ID: '+t+".";throw r.error(x),new C(_.C_BROWSER_PROJECT_GENERAL_ERROR,{},x)}const a=_n(),i=await a.getValue(Bo.VREW_PROJECT_DB,Ko.VREW_PROJECT,t);if(!i){r.warn("No projectId "+t+" exist in db");return}const s=be().getUserInfo()?.uid??tn;if(i.uid!==s){const x="While renaming Browser project "+t+", uid "+s+" mismatch with "+i.uid;throw r.error(x),new C(_.C_BROWSER_PROJECT_GENERAL_ERROR,{},x)}i.projectName=o,await a.putValue(Bo.VREW_PROJECT_DB,Ko.VREW_PROJECT,t,i),this.notifyUpdated(Mn.BROWSER),yUe(i)};cleanCloudProjectHistory=async()=>{this.cloudProjects=[],this.notifyUpdated(Mn.CLOUD)};deleteBrowserProject=async t=>{const o=h("projectHistoryManager.ts"),r=se();if(r.getCurrentProjectFileType()===Ee.BROWSER&&t===r.getCurrentProjectPath()){o.error("Refused to delete Browser project "+t+": it is the currently open project");return}const n=_n(),a=await n.getValue(Bo.VREW_PROJECT_DB,Ko.VREW_PROJECT,t);if(!a){o.warn("No projectId "+t+" exist in db"),this.notifyUpdated(Mn.BROWSER);return}const i=be().getUserInfo()?.uid??tn;if(a.uid!==i){const x="While deleting Browser project "+t+", uid "+i+" mismatch with "+a.uid;throw o.error(x),new C(_.C_BROWSER_PROJECT_GENERAL_ERROR,{},x)}await n.deleteValue(Bo.VREW_PROJECT_DB,Ko.VREW_PROJECT,t),await Ht(So.BROWSER_PROJECT).removeDir(Xf(i,t)),this.notifyUpdated(Mn.BROWSER)};deleteBrowserProjects=async t=>{const o=h("projectHistoryManager.ts"),r=se(),n=r.getCurrentProjectFileType()===Ee.BROWSER?r.getCurrentProjectPath():void 0,a=t.filter(d=>d!==n),i=be().getUserInfo()?.uid??tn,s=_n(),x=Ht(So.BROWSER_PROJECT),c=[],l=[];for(const d of a)try{const u=await s.getValue(Bo.VREW_PROJECT_DB,Ko.VREW_PROJECT,d);if(!u){o.warn("No projectId "+d+" exist in db"),l.push(d);continue}if(u.uid!==i){o.error("While deleting Browser project "+d+", uid "+i+" mismatch with "+u.uid),l.push(d);continue}await s.deleteValue(Bo.VREW_PROJECT_DB,Ko.VREW_PROJECT,d),await x.removeDir(Xf(i,d)),c.push(d)}catch(u){l.push(d),o.error("failed to delete browser project "+d+": "+P(u))}return c.length>0&&this.notifyUpdated(Mn.BROWSER),{succeeded:c,failed:l}};removeProjectHistories=async t=>{const o=se(),r=o.getCurrentProjectFileType()===Ee.PROJECT?o.getProjectId():void 0,n=t.filter(a=>a!==r);for(const a of n){const i=this.localProjects.findIndex(s=>s.projectId===a);i!==-1&&this.localProjects.splice(i,1)}await this.mergeAndSyncLocalProjects([])};getEventEmitter=()=>this.eventEmitter;getProjectName=t=>{const o=se().isCloudProject(),r=se().isLocalProject();return o?this.getCloudProjects().find(n=>n.projectId===t)?.projectName??null:r?this.getLocalProjects().find(n=>n.projectId===t)?.projectName??null:null};shouldOpenModal=()=>this.getStoredSeeds().length>=bD||this.localProjects.length>=0;localProjectOpened=(t,o)=>{const r=this.getLocalProjectHistory(t,o);this.addSeedToLocalStorage(t),this.localInitialized?this.mergeAndSyncLocalProjects([r]):this.localProjects.push(r)};addSeedToLocalStorage=t=>{const o=this.getStoredSeeds();o.length>=bD||o.includes(t)||(o.push(t),window.localStorage.setItem(Ci.SHOULD_DISPLAY_MODAL_SEEDS,JSON.stringify(o)))};getStoredSeeds=()=>{const t=window.localStorage.getItem(Ci.SHOULD_DISPLAY_MODAL_SEEDS);return t===null?[]:JSON.parse(t)};localProjectSaved=async(t,o,r)=>{const n=Symbol(t);this._latestLocalSave.set(t,n);const a=this.getLocalProjectHistory(t,o);if(this.localInitialized){const i=await r?.catch(s=>(h("projectHistoryManager.ts").warn("Failed to create local project thumbnail: "+P(s)),void 0));if(this._latestLocalSave.get(t)!==n)return;i!==void 0&&(a.thumbnail=i),await this.mergeAndSyncLocalProjects([a])}};setThumbnail=async(t,o)=>{const r=this.localProjects.find(n=>n.projectId===t);if(!r){h("projectHistoryManager.ts").warn("Cannot set thumbnail: no projectId "+t+" in local history");return}return r.thumbnail=o,this.mergeAndSyncLocalProjects([])};updateProjectId=(t,o)=>{this.localProjects=this.localProjects.map(r=>r.projectId===t?{...r,projectId:o}:r)};removeProjectHistory=async t=>{const o=this.localProjects.findIndex(r=>r.projectId===t);o!==-1&&this.localProjects.splice(o,1),await this.mergeAndSyncLocalProjects([])};cleanLocalProjectHistory=async()=>{this.localProjects=[],await pt().setProjectOpenHistory([]),this.notifyUpdated(Mn.LOCAL)};setMostRecentAttemptedOpenMethod=t=>{this.mostRecentAttemptedOpenMethod=t};getMostRecentAttemptedOpenMethod=()=>this.mostRecentAttemptedOpenMethod;mergeLocalProjectHistories=(t,o)=>{if(o===void 0)return t;const r=t.lastAccessed>o.lastAccessed?t:o,n=t.lastAccessed>o.lastAccessed?o:t;return r.thumbnail===void 0&&(r.thumbnail=n.thumbnail),r};mergeAndSyncLocalProjects=async t=>{const o=[...this.localProjects,...t],r={};o.forEach(s=>{const x=r[s.projectId];r[s.projectId]=this.mergeLocalProjectHistories(s,x)});const n=Object.values(r),a={};
1187n.forEach(s=>{const x=a[s.filePath];a[s.filePath]=this.mergeLocalProjectHistories(s,x)});const i=Object.values(a).sort((s,x)=>x.lastAccessed-s.lastAccessed);this.localProjects=i.slice(0,ARe),await pt().setProjectOpenHistory(this.localProjects),this.notifyUpdated(Mn.LOCAL)};loadProjects=()=>{(async()=>{const t=await pt().getProjectOpenHistory();await this.mergeAndSyncLocalProjects(t),this.localInitialized=!0})()};hasListener=t=>this.eventEmitter.listenerCount(t)>0;getProjectNameFromPath=t=>gt(t).split(".").slice(0,-1).join(".");getLocalProjectHistory=(t,o)=>({type:Mn.LOCAL,projectId:t,filePath:o,projectName:this.getProjectNameFromPath(o),lastAccessed:Date.now()})}let nh;const wRe=()=>{!nh&&(nh=new vRe)},Il=()=>(!nh&&wRe(),nh),ixt=e=>{const t=se();switch(e.type){case Mn.BROWSER:return t.getCurrentProjectFileType()===Ee.BROWSER&&e.projectId===t.getCurrentProjectPath();case Mn.CLOUD:return t.getCurrentProjectFileType()===Ee.CLOUD&&e.projectId===t.getProjectId();case Mn.LOCAL:return t.getCurrentProjectFileType()===Ee.PROJECT&&e.projectId===t.getProjectId()}},sxt=e=>{const t=Array.from(new Intl.Segmenter(void 0,{granularity:"grapheme"}).segment(e)).length;if(t<F_.NAME_MIN_LENGTH||t>F_.NAME_MAX_LENGTH)return A("vcloud.title_policy_invalid_length");if(e.endsWith("."))return A("vcloud.title_policy_end_with_dot");if(F_.VCLOUD_TITLE_INVALID_CHAR_REGEX.test(e)){const o=F_.VCLOUD_TITLE_INVALID_CHAR_REGEX.source.replace(/^\[|\]$/g,"").replace(/\\\\/g,"\\").split("").join(" ");return A("vcloud.title_policy_invalid_char")+` 
1188(`+o+")"}};class n0{static instance;cloudSavePollingInstance=null;pollingInterval=6e4;maxRetries=3;constructor(){this.cloudSavePollingInstance=null}async startPolling(t,o){const r=h("CloudProjectPollingManager.ts");if(r.info("[poll] Start projectId="+t+", sessionId="+o),!Lt().isEditableCloudProject(t)){r.info("[poll] Skipping non-editable cloud project: "+t);return}await this.stopPolling();const n=Date.now()+"-"+t;this.cloudSavePollingInstance={token:n,timeoutId:null,retryCount:0,projectId:t,sessionId:o},this.poll(this.cloudSavePollingInstance)}async stopPolling(){this.cloudSavePollingInstance?.timeoutId&&clearTimeout(this.cloudSavePollingInstance.timeoutId),h("CloudProjectPollingManager.ts").info("[stopPolling] currentPolling: "+JSON.stringify(this.cloudSavePollingInstance)),this.cloudSavePollingInstance?.projectId&&(h("CloudProjectPollingManager.ts").info("[stopPolling] closeEditingSession projectId="+this.cloudSavePollingInstance.projectId+", sessionId="+this.cloudSavePollingInstance.sessionId),await kOe(this.cloudSavePollingInstance.projectId,this.cloudSavePollingInstance.sessionId)),h("CloudProjectPollingManager.ts").info("[stopPolling] projectId="+this.cloudSavePollingInstance?.projectId),this.cloudSavePollingInstance=null}async poll(t){const o=h("CloudProjectPollingManager.ts");if(!this.cloudSavePollingInstance){o.info("[poll] Skip - currentPolling is null (stopped)");return}if(this.cloudSavePollingInstance?.token!==t.token){o.info("[poll] Skipped - Token mismatch | expected="+t.token+", current="+this.cloudSavePollingInstance?.token);return}const r=se().getCurrentProjectFileType(),n=se().getProjectId();if(!n||n!==t.projectId||!Lt().isEditableCloudProject(n)||r!==Ee.CLOUD){o.info("[poll] Current project changed or invalid. Stopping polling. projectId: "+t.projectId+", currProjectId: "+n+", currProjectType: "+r),await this.stopPolling();return}if(!await wo()){o.error("No idToken or uid at getCloudProjectSession. Stopping polling."),await this.stopPolling();return}try{const a=Date.now();o.info("[poll] renewEditingSession projectId="+t.projectId+", sessionId="+t.sessionId),await D7(t.projectId,t.sessionId);const i=Date.now()-a,s=Math.max(0,this.pollingInterval-i);if(this.cloudSavePollingInstance?.token!==t.token)return;this.cloudSavePollingInstance.retryCount=0,this.cloudSavePollingInstance.timeoutId&&clearTimeout(this.cloudSavePollingInstance.timeoutId),this.cloudSavePollingInstance.timeoutId=setTimeout(()=>{this.poll(t)},s)}catch(a){const i=Ne(a)&&a.errorCode===_.C_VCLOUD_SESSION_CONFLICT?"conflict":"unknown";this.handlePollingError(t,i,P(a))}}handlePollingError(t,o,r){const n=h("CloudProjectPollingManager.ts");if(this.cloudSavePollingInstance?.token!==t.token){n.info("[pollError] Error skipped - Token mismatch");return}if(n.error("[pollError] Error | type="+o+", msg="+r),o==="conflict"){n.error("[pollError] Conflict error. Stopping polling."),this.stopPolling();return}this.cloudSavePollingInstance.retryCount++,this.cloudSavePollingInstance.retryCount<=this.maxRetries?(this.cloudSavePollingInstance.timeoutId&&clearTimeout(this.cloudSavePollingInstance.timeoutId),this.cloudSavePollingInstance.timeoutId=setTimeout(()=>{this.poll(t)},this.pollingInterval*2)):(n.error("[pollError] Max retries exceeded. Stopping polling."),this.stopPolling())}static getInstance(){return!n0.instance&&(n0.instance=new n0),n0.instance}}const NRe=(e,t,o,r)=>{if(e===Ee.MEDIA){if(se().getSaveProjectType()!==Ee.CLOUD&&t!==Ee.CLOUD)return null;const a=Lt().isCloudProjectInitializedOrInitializing(r);return t!==Ee.CLOUD?a?"saveLocal":null:v4()?a?"save":"new":null}if(e===t)return o?e===Ee.CLOUD?"saveAs":null:e===Ee.CLOUD?"save":null;if(e===Ee.CLOUD)return"saveLocal";if(t===Ee.CLOUD){const n=Lt().getVCloudProjectInfo(r);return n&&n.version<WE?"migrate":"new"}return null},x5=async(e,t,o)=>new Promise(r=>{Y().openModal(st.WEB_SAVE_PROJECT,{initialName:e,isCopy:t,currentSavePath:o,onSaveToBrowser:n=>r({destination:"browser",projectName:n}),onSaveToCloud:n=>r({destination:"cloud",projectName:n}),onCancel:()=>r(void 0)})}),hA=async(e,t)=>{const o=h("save.ts"),r=await Lt().ensureCloudProjectInitialized(e,t);if(r.status==="failed")return{success:!1};if(se().getProjectId()!==e)return o.info("[ensureCloudProjectReady] Project changed during init, aborting: "+e),{success:!1};if(se().isMedia()&&se().updateCurrentProjectFileType(Ee.CLOUD),r.status==="new"){const a=sessionStorage.getItem(Wt.VCLOUD_SESSION_ID);a&&n0.getInstance().startPolling(e,a);const i=se().getAllFileInfos().filter(aG);i.length>0&&se().uploadPendingMediaFiles(e,i),hx({title:r.projectTitle}),se().getEventEmitter().emit(co.CLOUD_PROJECT_INITIALIZED,e)}return{success:!0,projectTitle:r.projectTitle}},PRe="",c5=async e=>{const t=new TextEncoder().encode(e),o=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(o)).map(r=>r.toString(16).padStart(2,"0")).join("")},l5=e=>({...e,files:e.files.map(({path:t,...o})=>o),integrity:PRe}),bRe=async e=>{const t=l5(e);return await c5(JSON.stringify(t))},LRe=async e=>{const t=l5(e);return{...e,integrity:await c5(JSON.stringify(t))}},MRe=async e=>{const t=e.integrity;if(typeof t!="string"||t.length===0)return{ok:"absent"};const o=await bRe(e);return o===t?{ok:!0}:{ok:!1,expected:t,actual:o}};var rf=(e=>(e.IMAGE="image",e.LOTTIE="lottie",e.WEB="web",e.VIDEO="video",e.SHAPE="shape",e.CHARACTER="character",e.SIMPLE_CHARACTER="simpleCharacter",e))(rf||{}),wx=(e=>(e[e.NONE=0]="NONE",e[e.VERTICAL=1]="VERTICAL",e[e.HORIZONTAL=2]="HORIZONTAL",e[e.VERTICAL_HORIZONTAL=3]="VERTICAL_HORIZONTAL",e))(wx||{}),R0=(e=>(e.IMAGE="image",e.LOTTIE="lottie",e.WEB="web",e.VIDEO="video",e.SHAPE="shape",e.CHARACTER="character",e.SIMPLE_CHARACTER="simpleCharacter",e))(R0||{}),Nx=(e=>(e[e.NONE=0]="NONE",e[e.VERTICAL=1]="VERTICAL",e[e.HORIZONTAL=2]="HORIZONTAL",e[e.VERTICAL_HORIZONTAL=3]="VERTICAL_HORIZONTAL",e))(Nx||{});const d5=e=>({duration:e.duration,mediaId:e.mediaId,pitch:e.pitch,speed:e.speed,volume:e.volume,emotion:e.emotion,effect:void 0,text:{processed:e.text,raw:e.text,textAspectLang:e.speaker.lang},speaker:e.speaker}),DRe=(e,t)=>{if(e.length>0){const o=e[e.length-1];if(o.duration>0||o.text.length>0)return e.push({originalStartTime:o.originalStartTime+o.duration,id:ct(),text:"",startTime:o.startTime+o.duration,duration:0,type:Z.ENTER,aligned:!1,originalDuration:0,autoControl:!1,truncatedWords:[],mediaId:o.mediaId,audioTransformIds:[],assetIds:[]}),!0;o.type!==Z.ENTER&&(e[e.length-1]={...o,type:Z.ENTER})}return!1},u5=e=>e.map(t=>{const o=t.words.length,r=t.words.filter((n,a)=>a===o-1||n.type!==Z.ENTER);return DRe(r),{...t,words:r}}),p5=e=>t=>({words:t.words.map(_5),captionMode:t.captionSetting?ar.MANUAL:t.captionMode,captions:kRe(t,t.captions,t.captionSetting,e),markerId:t.markerId,assetIds:t.assetIds,dirty:t.dirty,translationModified:t.translationModified,faceEffectId:t.faceEffectId,id:t.id,playbackRate:t.playbackRate,videoTransform:t.videoTransform,audioTransformIds:E5(t.mediaTracks)}),kRe=(e,t,o,r)=>{if(o===void 0)return t.length===2?t.map(c=>({text:wt().fromText(c.text).ops,trailingNewlinesFixed:void 0})):[{text:wt().fromText(t[0].text).ops,trailingNewlinesFixed:void 0},{text:wt().fromText("").ops,trailingNewlinesFixed:void 0}];const{captionStyleSetting:n,quillStyle:a}=GRe(o)??{captionStyleSetting:void 0,quillStyle:void 0},i=FRe(on(r));return t.length===2?t.map((x,c)=>{const l=LD(e,i,c);return l.length===0?{text:wt().fromText("").ops,trailingNewlinesFixed:void 0}:{text:wt().fromText(l,a).ops,style:n,trailingNewlinesFixed:void 0}}):[{text:wt().fromText(LD(e,i,0),a).ops,style:n,trailingNewlinesFixed:void 0},{text:wt().fromText("").ops,trailingNewlinesFixed:void 0}]},LD=(e,t,o,r=!0,n=!0)=>
1188{if(e===void 0)return"";const{captionMode:a,captions:i}=e;return o===0&&a===ar.TRANSCRIPT?URe(e.words,t,r,n):i[o]?.text??""},FRe=e=>[ce.Japanese,ce.Taiwanese,Jc.LAO,Jc.CHINESE_SIMPLIFIED].includes(e)===!1,URe=(e,t=!0,o=!0,r=!0)=>{const n=t?" ":"";let a="";e.forEach(s=>{s.text&&(a=a.concat(n,s.text))});const i=r?LT(a):a;return o?i.trim():i},VRe=.02,GRe=e=>{if(e.version===2){const t=e;return t.captionPosInfo.xOffsetCenter=t.captionPosInfo.xOffsetCenter/1680+VRe,t.captionPosInfo.yOffsetBottom=t.captionPosInfo.yOffsetBottom/-960,{captionStyleSetting:g5(t),quillStyle:f5(t)}}else return Jm},f5=e=>{const{captionFontFamily:t,weight:o,captionSize:r,captionStyle:n,textColor:a}=e,i={font:t+"_"+o,size:r.toString(),color:a.toLowerCase()};switch(n){case Nl.STROKE:{const{outlineColor:s,outlineWidth:x}=e;return{...i,"outline-color":s.toLowerCase(),"outline-width":""+x,"outline-on":x!==0?"true":"false"}}case Nl.SHADOW:{const{shadowColor:s}=e;return{...i,"shadow-on":"true","shadow-color":s.toLowerCase()}}case Nl.OPAQUEBOX:case Nl.HIGHLIGHT:case Nl.NORMAL:break}return i},g5=e=>{const{captionPosInfo:t,captionStyle:o,opaqueboxAlpha:r,opaqueboxColor:n}=e,a=o===Nl.OPAQUEBOX?Fn(n).alpha(r).toRgbString():Ri;return{...Jm.captionStyleSetting,yAlign:Iw(t.yAlign),xOffset:t.xOffsetCenter,yOffset:t.yOffsetBottom,customAttributes:[{attributeName:"--textbox-color",type:"color-hex",value:a},{attributeName:"--textbox-align",type:"textbox-align",value:hw(t.xAlign)}]}},_5=e=>({id:e.id??ct(),text:e.text,startTime:e.startTime,duration:e.duration,aligned:e.aligned,type:e.type,originalDuration:e.originalDuration,originalStartTime:e.originalStartTime,truncatedWords:e.truncatedWords.map(_5),autoControl:e.autoControl,mediaId:e.mediaId,sourceAudioTransformId:e.sourceAudioTransformId,assetIds:e.assetIds??[],audioTransformIds:E5(e.mediaTracks)}),E5=e=>e.map(t=>t.audioTransformId),WRe=()=>({duration:1,audioInfo:{codec:Gt.PCM,sampleRate:AU},videoTrackExists:!1}),HRe=e=>({version:2,type:ie.VIDEO_AUDIO,path:e.path,mediaId:e.mediaId,sourceOrigin:e.sourceOrigin,fileLocation:ia(e.mediaId)?D.IN_MEMORY:e.fileLocation,originalClips:u5(e.originalClips?.map(p5(e.lang??pn.None))??[]),audioLanguage:e.lang??pn.None,fileSize:e.fileSize??0,importMethod:e.importMethod??"fileSystem",videoMetaInfo:ia(e.mediaId)?WRe():e.videoMetaInfo??{duration:0}}),jRe=e=>({version:1,type:ie.IMAGE,path:e.path,sourceOrigin:e.sourceOrigin,fileLocation:e.fileLocation,mediaId:e.mediaId,vrewMark:e.vrewMark,isTransparent:!0}),zRe=e=>({version:1,type:ie.FILTER,path:e.path,sourceOrigin:e.sourceOrigin,fileLocation:e.fileLocation,mediaId:e.mediaId}),YRe=e=>{if(e.ttsInfo===void 0){h("vrewJsonUpgraderV9.ts").error("TTS file has no ttsInfo while upgrading vrewjson v9 to v10, "+JSON.stringify(e));return}return{version:2,type:ie.TTS,path:e.path,mediaId:e.mediaId,sourceOrigin:e.sourceOrigin,fileLocation:e.fileLocation,ttsInfo:d5(e.ttsInfo)}},BRe=e=>{if(e.type!==de.SOUND_EFFECT&&e.type!==de.BGM){h("vrewJsonUpgraderV9.ts").error("sound effect or bgm file has invalid type while upgrading vrewjson v9 to v10, "+JSON.stringify(e));return}return{version:1,type:(o=>{switch(o){case de.SOUND_EFFECT:return ie.SOUND_EFFECT;case de.BGM:return ie.BGM;default:throw new C(_.C_VREW_FILE_INCOMPATIBLE_VERSION)}})(e.type),path:e.path,sourceOrigin:e.sourceOrigin,fileLocation:e.fileLocation,mediaId:e.mediaId,audioMetaInfo:{duration:e.audioMetaInfo?.duration??0,name:e.audioMetaInfo?.name??"unknown",sampleRate:e.audioMetaInfo?.sampleRate??0,codec:e.audioMetaInfo?.codec??void 0}}},KRe=e=>{if(e.ttsInfo===void 0){h("vrewJsonUpgraderV9.ts").error("TTS effect file has no ttsInfo while upgrading vrewjson v9 to v10, "+JSON.stringify(e));return}return{version:2,type:ie.TTS_EFFECT,path:e.path,sourceOrigin:e.sourceOrigin,fileLocation:e.fileLocation,mediaId:e.mediaId,audioMetaInfo:{duration:e.audioMetaInfo?.duration??0,name:e.audioMetaInfo?.name??"unknown",sampleRate:e.audioMetaInfo?.sampleRate??0,codec:e.audioMetaInfo?.codec??void 0},ttsInfo:d5(e.ttsInfo)}},XRe=e=>{if(e.videoMetaInfo===void 0){h("vrewJsonUpgraderV9.ts").error("Asset video file has no videoMetaInfo while upgrading vrewjson v9 to v10, "+JSON.stringify(e));return}return{version:1,type:ie.ASSET_VIDEO,path:e.path,sourceOrigin:e.sourceOrigin,fileLocation:e.fileLocation,mediaId:e.mediaId,videoMetaInfo:e.videoMetaInfo,isTransparent:!0}},JRe=e=>{if(e.characterInfo===void 0){h("vrewJsonUpgraderV9.ts").error("Character file has no characterInfo while upgrading vrewjson v9 to v10, "+JSON.stringify(e));return}return{version:1,type:ie.CHARACTER,path:e.path,sourceOrigin:e.sourceOrigin,fileLocation:e.fileLocation,mediaId:e.mediaId,characterInfo:e.characterInfo}},qRe=()=>({version:1,type:ie.INVALID,path:"",sourceOrigin:tt.USER,fileLocation:D.LOCAL,mediaId:""}),QRe=e=>{switch(e.type){case de.VIDEO_AUDIO:return HRe(e);case de.IMAGE:return jRe(e);case de.FILTER:return zRe(e);case de.TTS:return YRe(e);case de.BGM:case de.SOUND_EFFECT:return BRe(e);case de.TTS_EFFECT:return KRe(e);case de.ASSET_VIDEO:return XRe(e);case de.CHARACTER:return JRe(e);default:return h("vrewJsonUpgraderV9.ts").error("Invalid file type on load, "+e.type+", "+JSON.stringify(e)),qRe()}},ZRe=e=>{if(e===void 0)return Jm;if(e.version===2){const t=e;return t.captionPosInfo.xOffsetCenter=t.captionPosInfo.xOffsetCenter/1680+Bh,t.captionPosInfo.yOffsetBottom=t.captionPosInfo.yOffsetBottom/-960,{captionStyleSetting:g5(t),quillStyle:f5(t)}}else return Jm},$Re=e=>({...e,type:Ja.IMAGE,originalWidthHeightRatio:e.originalWidthHeightRatio??1,importType:e.importType??_e.UNKNOWN}),eAe=e=>({...e,type:Ja.VIDEO,isTrimmable:e.isTrimmable===void 0?!0:e.isTrimmable,hasAlphaChannel:!1}),tAe=e=>({...e,type:Ja.WEB,enabledInlineTypes:e.enabledInlineTypes??[...oI],customAttributes:e.customAttributes??[],webAssetId:e.webAssetId??Ao,defaultAttribute:{size:"200"},importType:e.importType??Yt.UNKNOWN}),oAe=e=>{switch(e.type){case R0.IMAGE:return $Re(e);case R0.LOTTIE:return{...e,type:Ja.LOTTIE};case R0.VIDEO:return eAe(e);case R0.SHAPE:return{...e,type:Ja.SHAPE};case R0.CHARACTER:return{...e,type:Ja.CHARACTER};case R0.WEB:return tAe(e)}},rAe=e=>{const t=Object.entries(e).map(([o,r])=>[o,oAe(r)]);return Object.fromEntries(t)},nAe=(e,t)=>
1188{const o={},r={};return t.forEach(n=>{n.clips.forEach(a=>{a.mediaTracks.forEach(i=>{L.set(r,i.audioTransformId,i.mediaId)}),a.words.forEach(i=>{i.mediaTracks.forEach(s=>{L.set(r,s.audioTransformId,s.mediaId)})})})}),Object.keys(e).forEach(n=>{const a=L.get(e,n),i=L.get(r,n);if(!a||!i)return;const s={...a,frontOffset:0,rearOffset:0,mediaId:i};L.get(o,n)===void 0&&L.set(o,n,s)}),o},aAe=e=>{if(e===void 0)return{};const t=o=>{switch(o){case Nx.NONE:return yx.NONE;case Nx.VERTICAL:return yx.VERTICAL;case Nx.HORIZONTAL:return yx.HORIZONTAL;case Nx.VERTICAL_HORIZONTAL:return yx.VERTICAL_HORIZONTAL}};return Object.fromEntries(Object.entries(e).map(([o,r])=>[o,t(r)]))},iAe=(e,t)=>({globalCaptionStyle:ZRe(e.captionSetting),captionDisplayMode:e.captionDisplayMode||Sf.ORIGINAL_ONLY,videoSize:e.videoSize,filterSetting:e.filterSetting,flipSetting:aAe(e.flipSetting),assets:rAe(e.assets),analyzeDate:e.analyzeDate,faceEffectsMap:{},audioTransformsMap:nAe(e.audioTransformsMap,t),markerNames:e.markerNames,videoRatio:e.videoRatio,globalVideoTransform:e.globalVideoTransform??il,backgroundMap:sy,lastTTSSettings:void 0,waterMarkMap:{}}),sAe=e=>e?{engine:e.engine,option:e.options.length>0?{name:e.options[0].name,value:e.options[0].value}:void 0}:{engine:Ea.GOOGLE},xAe=(e,t)=>e.map(o=>({clips:u5(o.clips.map(p5(t))),name:o.name,dirty:o.dirty,translateInfo:o.translationSourceLanguage&&o.translationTargetLanguage?{source:o.translationSourceLanguage,target:o.translationTargetLanguage,engineInfo:sAe(o.translationEngine),numberOfTranslate:o.numberOfTranslate??0}:void 0,id:o.id})),m5=async(e,t)=>{const o=e.files.find(n=>n.type===de.VIDEO_AUDIO)?.lang??pn.None,r={files:e.files.map(QRe).filter(Se),props:iAe(e.props,e.transcript.scenes),transcript:{scenes:xAe(e.transcript.scenes,o)},comment:e.comment,projectId:e.projectId,makerCid:e.makerCid,makerUid:e.makerUid,statistics:e.statistics,lastTTSSettings:void 0};return await Kj(r,t)},cAe=e=>e.length===2?e:[e[0]||{text:""},e[1]||{text:""}],lAe=e=>Object.assign({video:!1,caption:!1,blankDeleted:!1},e),dAe=e=>Object.assign({source:!1,result:!1},e),h5=e=>({words:e.words,captionMode:e.captionMode,captions:cAe(e.captions),markerId:e.markerId,assetIds:e.assetIds,dirty:lAe(e.dirty),translationModified:dAe(e.translationModified),captionSetting:e.captionSetting,faceEffectId:e.faceEffectId,id:e.id??ct(),playbackRate:e.playbackRate,videoTransform:e.videoTransform,mediaTracks:e.mediaTracks}),uAe=e=>({type:de.VIDEO_AUDIO,path:e.path,mediaId:e.mediaId,sourceOrigin:e.sourceOrigin,fileLocation:ia(e.mediaId)?D.PACKAGED:D.LOCAL,originalClips:(e.originalClips??[]).map(h5),lang:e.lang,fileSize:e.fileSize,importMethod:e.importMethod??"fileSystem"}),pAe=e=>({type:de.IMAGE,path:e.path,sourceOrigin:tt.USER,fileLocation:D.IN_MEMORY,mediaId:e.mediaId,vrewMark:e.vrewMark}),fAe=e=>({type:de.FILTER,path:e.path,sourceOrigin:tt.USER,fileLocation:D.IN_MEMORY,mediaId:e.mediaId}),gAe=e=>({type:de.TTS,path:e.path,fileSize:e.fileSize,mediaId:e.mediaId,originalClips:[],sourceOrigin:tt.VREW_RESOURCE,fileLocation:D.IN_MEMORY,lang:e.lang,ttsInfo:e.ttsInfo}),_Ae=e=>({type:e.type,path:e.path,sourceOrigin:e.sourceOrigin,fileLocation:e.sourceOrigin===tt.USER?D.IN_MEMORY:D.REMOTE,mediaId:e.mediaId,audioMetaInfo:{duration:e.bgmMetaInfo?.duration??0,name:e.bgmMetaInfo?.name??"unknown",sampleRate:e.bgmMetaInfo?.sampleRate??0,codec:e.bgmMetaInfo?.codec??void 0}}),EAe=e=>{switch(e.type){case de.VIDEO_AUDIO:return uAe(e);case de.IMAGE:return pAe(e);case de.FILTER:return fAe(e);case de.TTS:return gAe(e);case de.BGM:case de.SOUND_EFFECT:return _Ae(e);default:return h("vrewJsonUpgraderV8.ts").error("Invalid file type on converting SourceFileV8 to SourceFileV9, "+e.type+", "+e+"."),{type:de.INVALID,path:"",sourceOrigin:tt.USER,fileLocation:D.LOCAL,mediaId:""}}},mAe=e=>({...e,type:R0.IMAGE,zIndex:e.zIndex??0}),hAe=e=>({...e,type:R0.LOTTIE,zIndex:e.zIndex??0}),IAe=e=>({...e,type:R0.WEB,zIndex:e.zIndex??0,enabledInlineTypes:[...oI],customAttributes:[],webAssetId:Ao}),TAe=e=>{switch(e.type){case rf.IMAGE:return mAe(e);case rf.LOTTIE:return hAe(e);case rf.WEB:return IAe(e)}},SAe=e=>{const t=Object.entries(e).map(([o,r])=>[o,TAe(r)]);return Object.fromEntries(t)},OAe=e=>Object.entries(e).reduce((t,[o,r])=>(t[o]={...r,type:r.type??ze.BGM},t),{}),CAe=e=>{if(e===void 0)return{};const t=o=>{switch(o){case wx.NONE:return Nx.NONE;case wx.VERTICAL:return Nx.VERTICAL;case wx.HORIZONTAL:return Nx.HORIZONTAL;case wx.VERTICAL_HORIZONTAL:return Nx.VERTICAL_HORIZONTAL}};return Object.fromEntries(Object.entries(e).map(([o,r])=>[o,t(r)]))},RAe=e=>({captionSetting:e.captionSetting,captionDisplayMode:e.captionDisplayMode,videoSize:e.videoSize,filterSetting:e.filterSetting,flipSetting:CAe(e.flipSetting),assets:SAe(e.assets),analyzeDate:e.anal
1188yzeDate,faceEffectsMap:e.faceEffectsMap,audioTransformsMap:OAe(e.audioTransformsMap??{}),markerNames:e.markerNames??iy,videoRatio:e.videoRatio??he.ORIGINAL,globalVideoTransform:il}),AAe=e=>Object.assign({video:!1},e),yAe=e=>e.map(t=>({id:t.id??ct(),clips:t.clips.map(h5),name:t.name,dirty:AAe(t.dirty),translationSourceLanguage:t.translationSourceLanguage,translationTargetLanguage:t.translationTargetLanguage,numberOfTranslate:t.numberOfTranslate})),I5=async(e,t)=>{const o={files:e.files.map(EAe),props:RAe(e.props),transcript:{scenes:yAe(e.transcript.scenes)},comment:e.comment,projectId:e.projectId,makerCid:e.makerCid,makerUid:e.makerUid,statistics:e.statistics};return await m5(o,t)},T5=e=>({...e,truncatedWords:e.truncatedWords.map(T5),mediaTracks:[],assetIds:[]}),S5=e=>({words:e.words.map(T5),captionMode:e.captionMode,captions:e.captions,assetIds:e.images.map(t=>t.imageId),markerId:e.markerId,dirty:e.dirty,translationModified:e.translationModified,captionSetting:e.captionSetting,faceEffectId:e.faceEffectId,id:e.id,playbackRate:e.playbackRate,videoTransform:e.videoTransform,mediaTracks:[]}),vAe=e=>({type:de.VIDEO_AUDIO,path:e.path,sourceOrigin:e.sourceOrigin,mediaId:e.mediaId,lang:e.lang,vrewMark:e.vrewMark,fileSize:e.fileSize,originalClips:e.originalClips?.map(S5)??[]}),wAe=(e,t)=>(e.imageIds?.forEach(o=>{t.set(o,e.mediaId)}),{type:de.IMAGE,path:e.path,sourceOrigin:tt.USER,mediaId:e.mediaId,vrewMark:e.vrewMark}),NAe=e=>({type:de.FILTER,path:e.path,sourceOrigin:tt.USER,mediaId:e.mediaId}),PAe=()=>({type:de.INVALID,path:"",sourceOrigin:tt.USER,mediaId:""}),bAe=e=>t=>{switch(t.type){case de.VIDEO_AUDIO:return vAe(t);case de.IMAGE:return wAe(t,e);case de.FILTER:return NAe(t);default:return h("vrewJsonUpgraderV7.ts").error("Invalid file type on upgrading SourceFileV7 to SourceFileV8. "+t.type+", "+t),PAe()}},LAe=e=>e.map(t=>({id:t.id??ct(),clips:t.clips.map(S5),name:t.name,dirty:t.dirty,translationSourceLanguage:t.translationSourceLanguage,translationTargetLanguage:t.translationTargetLanguage,numberOfTranslate:t.numberOfTranslate})),MAe=e=>t=>e.has(t.imageId)?!0:(h("vrewJsonUpgraderV7.ts").error("Image "+t.imageId+" does not exist!"),!1),DAe=e=>t=>[t.imageId,{...t,type:rf.IMAGE,xPos:t.xRatio,yPos:t.yRatio,width:t.widthRatio,height:t.heightRatio,rotation:t.rotateDeg??0,zIndex:0,mediaId:e.get(t.imageId),originalWidthHeightRatio:"originalWidthHeightRatio"in t?t.originalWidthHeightRatio||1:t.heightRatio?t.widthRatio/t.heightRatio:1,importType:"importType"in t?t.importType:_e.UNKNOWN,stats:"stats"in t?{...t.stats,fillType:t.stats&&"fillType"in t.stats?t.stats.fillType:void 0}:void 0}],kAe=(e,t)=>{const o=e.transcript.scenes.map(a=>a.clips).map(a=>a).flat(),r=o.map(a=>a.images).flat(),n=r.filter(MAe(t)).map(DAe(t));return Object.fromEntries(n)},FAe=e=>{if(e===void 0)return{};const t=o=>{switch(o){case Mp.NONE:return wx.NONE;case Mp.VERTICAL:return wx.VERTICAL;case Mp.HORIZONTAL:return wx.HORIZONTAL;case Mp.VERTICAL_HORIZONTAL:return wx.VERTICAL_HORIZONTAL}};return Object.fromEntries(Object.entries(e).map(([o,r])=>[o,t(r)]))},UAe=(e,t)=>{const{props:o}=e;return{captionSetting:o.captionSetting,captionDisplayMode:o.captionDisplayMode,videoSize:o.videoSize,filterSetting:o.filterSetting,flipSetting:FAe(o.flipSetting),assets:kAe(e,t),audioTransformsMap:{},markerNames:iy,videoRatio:he.ORIGINAL}},VAe=e=>{const t=e.props.assets??{};return e.transcript.scenes.forEach(o=>{const r={};o.clips.forEach((n,a)=>{n.assetIds.forEach(i=>{const s=r[i]?.at(-1);if(!s){r[i]=[{from:a,to:a+1,type:"CLIP"}];return}if(s.to===a){s.to=a+1;return}r[i].push({from:a,to:a+1,type:"CLIP"})})}),Object.entries(r).forEach(([n,a])=>{const i=t[n];i&&a.slice(1).forEach((s,x)=>{const c=qe.v4();t[c]={...i};for(let l=s.from;l<s.to;l++){const{assetIds:d}=o.clips[l],u=d.indexOf(n);u<0||(d[u]=c)}})})}),e},O5=async(e,t)=>{const o=new Map,r={version:8,files:e.files.map(bAe(o)),props:UAe(e,o),transcript:{scenes:LAe(e.transcript.scenes)},comment:e.comment,projectId:e.projectId??qe.v4(),makerCid:e.makerCid,makerUid:e.makerUid,statistics:e.statistics};return await I5(VAe(r),t)},C5=e=>({id:e.id??ct(),words:e.words,captionMode:e.captionMode,captions:e.captions,markerId:e.markerId,images:e.images,dirty:e.dirty,translationModified:e.translationModified,captionSetting:e.captionSetting,faceEffectId:e.faceEffectId,playbackRate:1}),GAe=e=>({type:de.VIDEO_AUDIO,path:e.path,sourceOrigin:e.sourceOrigin,mediaId:e.mediaId,originalClips:e.originalClips?.map(C5)??[],lang:e.lang,vrewMark:e.vrewMark,fileSize:e.fileSize}),WAe=e=>({type:de.IMAGE,path:e.path,sourceOrigin:tt.USER,mediaId:e.mediaId,imageIds:e.imageIds,vrewMark:e.vrewMark}),HAe=e=>({type:de.FILTER,path:e.path,sourceOrigin:tt.USER,mediaId:e.mediaId}),jAe=()=>({type:de.INVALID,path:"",sourceOrigin:tt.USER,mediaId:""}),zAe=e=>{switch(e.type){case de.VIDEO_AUDIO:return GAe(e);case de.IMAGE:return WAe(e);case de.FILTER:return HAe(e);default:return h("vrewJsonUpgraderV6.ts").error("Invalid file type on upgrading SourceFileV6 to SourceFileV7. "+e.type+", "+e+"."),jAe()}},YAe=e=>e.map(t=>({id:t.id??ct(),clips:t.clips.map(C5),name:t.name,dirty:t.dirty,translationSourceLanguage:t.translationSourceLanguage,translationTargetLanguage:t.translationTargetLanguage,numberOfTranslate:t.numberOfTranslate})),R5=async(e,t)=>{const o={files:e.files.map(zAe),props:e.props,transcript:{scenes:YAe(e.transcript.scenes)},comment:e.comment,projectId:e.projectId,makerCid:e.makerCid,makerUid:e.makerUid,statistics:e.statistics};return await O5(o,t)},BAe=e=>({type:de.VIDEO_AUDIO,path:e.path,sourceOrigin:tt.USER,originalClips:e.originalClips??[],mediaId:e.mediaId,lang:e.lang,vrewMark:e.vrewMark,fileSize:e.fileSize}),KAe=e=>({type:de.IMAGE,path:e.path,sourceOrigin:tt.USER,mediaId:e.mediaId,imageIds:e.imageIds,vrewMark:e.vrewMark}),XAe=e=>({type:de.FILTER,path:e.path,sourceOrigin:tt.USER,mediaId:e.mediaId}),JAe=()=>({type:de.INVALID,path:"",sourceOrigin:tt.USER,mediaId:""}),qAe=e=>{switch(e.type){case de.VIDEO_AUDIO:return BAe(e);case de.IMAGE:return KAe(e);case de.FILTER:return XAe(e);default:return h("vrewJsonUpgraderV5.ts").error("Invalid file type on upgrading SourceFileV5 to SourceFileV6. "+e.type+", "+e+"."),JAe()}},QAe=e=>e.map(t=>({id:t.id??ct(),clips:t.clips,dirty:t.dirty,translationSourceLanguage:t.translationSourceLanguage,translationTargetLanguage:t.translationTargetLanguage,numberOfTranslate:t.numberOfTranslate,name:t.name})),A5=async(e,t)=>{const o={files:e.files.map(qAe),props:e.props,transcript:{scenes:QAe(e.transcript.scenes)},comment:e.comment,projectId:e.projectId,makerCid:e.makerCid,makerUid:e.makerUid,statistics:e.statistics};return await R5(o,t)},ZAe=-1,$Ae=e=>({...e,rotateDeg:e.rotateDeg??0}),eye=e=>{const t={version:2,captionStyle:e.captionStyle,captionSize:e.captionSize,captionFontFamily:e.captionFontFamily,weight:e.weight,textColor:e.textColor,outlineColor:e.outlineColor,shadowColor:e.shadowColor,opaqueboxColor:e.opaqueboxColor,opaqueboxAlpha:e.opaqueboxAlpha,captionLineHeightRatio:e.captionLineHeightRatio,outlineWidth:e.outlineWidth,captionPosInfo:e.captionPosInfo};return Object.keys(t).length!==Object.keys(_m).length&&h("vrewJsonUpgraderV4.ts").warn("CaptionSetting key count check failed. Error occurred when saving CaptionJsonV2."),Object.keys(t.captionPosInfo).length!==Object.keys(go.DEFAULT_CAPTION_POS).length&&h("vrewJsonUpgraderV4.ts").warn("CaptionPosInfo key count check failed. Error occurred when saving CaptionJsonV2"),{..._m,...t,captionPosInfo:{...go.DEFAULT_CAPTION_POS,...t.captionPosInfo}}},tye=e=>{const t={version:2,..._m,captionStyle:e.captionStyle,captionSize:e.captionSize,captionFontFamily:e.captionFontFamily,weight:e.weight,textColor:e.textColor,outlineColor:e.outlineColor,shadowColor:e.shadowColor,opaqueboxColor:e.opaqueboxColor,opaqueboxAlpha:e.opaqueboxAlpha,captionLineHeightRatio:e.captionLineHeightRatio?e.captionLineHeightRatio:ZAe,outlineWidth:e.outlineWidth?e.outlineWidth:go.DEFAULT_OUTLINE_THICKNESS_DEPRECATED,captionPosInfo:{...go.DEFAULT_CAPTION_POS}};return Object.keys(t).length<Object.keys(_m).length&&h("vrewJsonUpgraderV4.ts").warn("Creating captionSetting from CaptionJsonV1 failed."),t},oye=e=>{if(e===void 0)return;let t;e.version===2?t=eye(e):t=tye(e);const o=t.captionFontFamily;if(o===go.NOTO_FONT_FAMILY_LEGACY||o===go.NOTO_FONT_FAMILY_JP_LEGACY){const r=o===go.NOTO_FONT_FAMILY_LEGACY?go.NOTO_FONT_FAMILY_LEGACY:go.NOTO_FONT_FAMILY_JP_LEGACY;return{...t,captionFontFamily:r}}return t},y5=e=>({words:e.words,captionMode:e.captionMode,captions:[{text:e.caption},{text:""}],markerId:e.markerId,images:e.images.map($Ae),dirty:e.dirty??{video:!1,caption:!1,blankDeleted:!1},translationModified:{source:!1,result:!1},captionSetting:oye(e.captionSetting),faceEffectId:e.faceEffectId}),rye=e=>({type:de.VIDEO_AUDIO,path:e.path,originalClips:e.originalClips?.map(y5)??[],mediaId:e.mediaId,lang:e.lang,vrewMark:e.vrewMark,fileSize:e.fileSize}),nye=e=>({type:de.IMAGE,path:e.path,mediaId:e.mediaId,imageIds:e.imageIds,vrewMark:e.vrewMark}),aye=e=>({type:de.FILTER,path:e.path,mediaId:e.mediaId}),iye=()=>({type:de.INVALID,path:"",mediaId:""}),sye=e=>{switch(e.type){case de.VIDEO_AUDIO:return rye(e);case de.IMAGE:return nye(e);case de.FILTER:return aye(e);default:return h("vrewJsonUpgraderV4.ts").error("Invalid file type on upgrading SourceFileV4 to SourceFileV5. "+e.type+", "+e+"."),iye()}},xye=e=>e.map(t=>({id:ct(),clips:t.clips.map(y5),name:t.name,dirty:t.dirty??{video:!1},numberOfTranslate:0})),v5=async(e,t)=>{const o={files:e.files.map(sye),props:e.props,transcript:{scenes:xye(e.transcript.scenes)},comment:e.comment,projectId:qe.v4()};return await A5(o,t)},cye=e=>({...e,id:e.id??ct()}),w5=e=>({words:e.words.map(cye),captionMode:e.captionMode,caption:e.caption,markerId:e.markerId,images:[],dirty:{video:!1,caption:!1,blankDeleted:!1},captionSetting:void 0,faceEffectId:void 0}),lye=e=>({type:de.VIDEO_AUDIO,path:e.path,mediaId:e.mediaId,lang:e.lang,originalClips:e.originalClips.map(w5)}),dye=e=>e.map(t=>({clips:t.clips.map(w5),dirty:{video:!1}})),N5=async(e,t)=>{const o={files:e.files.map(lye),props:e.props,transcript:{scenes:dye(e.transcript.scenes)},comment:e.comment};return await v5(o,t)},P5=e=>t=>({...t,originalStartTime:t.originalStartTime??t.startTime,originalDuration:t.originalDuration??t.duration,truncatedWords:t.truncatedWords?.map(P5(e))??[],autoControl:t.autoControl??t.type===Z.SILENT,id:ct(),mediaId:e}),MD=e=>t=>({words:t.words.map(P5(e)),captionMode:t.subtitleMode,caption:t.subtitle}),uye=e=>{for(let t=0;t<e.length&&t<100;t++)for(let o=0;o<e[t].words.length;o++){const r=e[t].words[o].text;if(r){if(V6.test(r))return ce.Korean;if(G6.test(r))return ce.Japanese}}return _f},b5=async(e,t)=>{const o=e.files[0];if(o===void 0)throw h("vrewJsonUpgraderV2.ts").error("no files in vrewJsonV2 while upgrading vrewjson v2 to v3. vrewjson: "+JSON.stringify(e)),new C(_.C_VREW_FILE_BROKEN);const r=qe.v4(),n=o.transcript.clips.map(MD(r)),a=o.original?o.original.originalClips.map(MD(r)):n,i={path:o.path,originalClips:a,lang:o.lang??uye(n),mediaId:r},s={captionDisplayMode:{[Ke.ORIGINAL]:!0,[Ke.TRANSLATE]:!1}}
1188,x={files:[i],props:e.props??s,transcript:{scenes:[{clips:n}]}};return await N5(x,t)},pye=e=>({originalStartTime:e.startTime,originalDuration:e.duration,type:e.isSpace?Z.SILENT:Z.NORMAL,autoControl:!!e.isSpace,...e}),fye=e=>({words:e.words.map(pye),subtitleMode:e.subtitleMode,subtitle:""}),gye=async(e,t)=>{const o=e.files.at(0);if(o===void 0)throw h("vrewJsonUpgraderV1.ts").error("no files in vrewJsonV2 while upgrading vrewjson v1 to v2. vrewjson: "+JSON.stringify(e)),new C(_.C_VREW_FILE_BROKEN);const r=o.transcript.paragraphs.map(fye),n=[{path:o.path,transcript:{clips:r}}];return await b5({version:2,files:n},t)},_ye=async(e,t)=>{const{version:o,files:r}=e;if(o<0||r===void 0||r.length===0)throw new C(_.C_VREW_FILE_INVALID_FORMAT);switch(o){case 1:return await gye(e,t);case 2:return await b5(e,t);case 3:return await N5(e,t);case 4:return await v5(e,t);case 5:return await A5(e,t);case 6:return await R5(e,t);case 7:return await O5(e,t);case 8:return await I5(e,t);case 9:return await m5(e,t);case 10:return await Kj(e,t);case 11:return Wj(e,t);case 12:return await bj(e,t);case 13:return await Sj(e,t);case 14:return await Ej(e,t);case 15:return await Q4(e,t);case 16:return await X4(e,t);case Be.CURRENT_VREW_JSON_VERSION:return{vrewJson:e,blobs:t};default:throw new C(_.C_VREW_FILE_INCOMPATIBLE_VERSION)}};var IA=(e=>(e.SEARCH="SEARCH",e.SEARCH_CURRENT="SEARCH_CURRENT",e.SELECTED="SELECTED",e.CURRENT_SELECTED="CURRENT_SELCETED",e.SPELL_CHECK="SPELL_CHECK",e))(IA||{}),L5=(e=>(e.REPLACE="REPLACE",e.RETRANSLATE="RETRANSLATE",e))(L5||{}),ka=(e=>(e.APPLY_STATIC_DECORATION="APPLY_STATIC_DECORATION",e.APPLY_DYNAMIC_DECORATION="APPLY_DYNAMIC_DECORATION",e.UPDATE_DECORATION="UPDATE_DECORATION",e.CLEAR_DYNAMIC_DECORATION="CLEAR_DYNAMIC_DECORATION",e.CLEAR_STATIC_DECORATION="CLEAR_STATIC_DECORATION",e.GET_IMPORT_SCRIPT_DECORATION_RANGE="GET_IMPORT_SCRIPT_DECORATION_RANGE",e.GET_CAPTION_SETTING_DECORATION_RANGE="GET_CAPTION_SETTING_DECORATION_RANGE",e.SET_MARKER_PANEL_DECORATION="SET_MARKER_PANEL_DECORATION",e.CLEAR_MARKER_PANEL_DECORATION="CLEAR_MARKER_PANEL_DECORATION",e.SET_ONBOARDING_WORD_DELETE_BUTTON_ANIMATION="SET_ONBOARDING_WORD_DELETE_BUTTON_ANIMATION",e.SET_PRONUNCIATION_DISPLAY="SET_PRONUNCIATION_DISPLAY",e))(ka||{});const ps=e=>e.decoration,M5=e=>ps(e).captionStaticDecorations,D5=e=>ps(e).captionDynamicDecorations,k5=e=>ps(e).wordDecorations,xxt=jn(k5,(e,t)=>t,(e,t)=>e.filter(o=>o.wordGlobalPosition===t))((e,t)=>t),cxt=e=>ps(e).dynamicDecorationCount,lxt=e=>ps(e).importScriptDecoration.clipDecorationCounter,Eye=Te(ps,e=>{const{wordDecorations:t}=e;return t.filter(r=>r.type===IA.CURRENT_SELECTED||r.type===IA.SELECTED).map(r=>r.wordGlobalPosition).filter(ri)}),mye=e=>ps(e).captionSettingDecoration,dxt=e=>ps(e).captionSettingDecoration.clipDecorationCounter,hye=e=>mye(e).targetClipIndices,uxt=jn(hye,(e,t)=>t,(e,t)=>e.includes(t))((e,t)=>t),Iye=e=>ps(e).importScriptDecoration.targetClipIndices,pxt=jn(Iye,(e,t)=>t,(e,t,o)=>o,(e,t,o)=>e.includes(t)&&o===Ke.ORIGINAL)((e,t,o)=>t+"."+o),fxt=jn(M5,(e,t)=>t,(e,t,o)=>o,(e,t,o)=>e.length===0?e:e.filter(r=>r.globalClipIndex===t).filter(r=>r.captionIndex===o))((e,t,o)=>t+"."+o),gxt=jn(D5,(e,t)=>t,(e,t,o)=>o,(e,t,o)=>e.length===0?[]:e.filter(r=>r.globalClipIndex===t).filter(r=>r.captionIndex===o))((e,t,o)=>t+"."+o),_xt=e=>ps(e).triggerMarkerClipIndex,Ext=e=>ps(e).triggerMarkerId,mxt=e=>ps(e).onboardingWordDeleteButtonAnimation,F5=e=>ps(e).pronunciationDisplay;var TA=(e=>(e.ALIAS="alias",e.ALL_SCROLL="all-scroll",e.AUTO="auto",e.CELL="cell",e.CONTEXT_MENU="context-menu",e.RESIZE_COLUMN="col-resize",e.COPY="copy",e.CROSSHAIR="crosshair",e.DEFAULT="default",e.RESIZE_E="e-resize",e.RESIZE_HORIZONTAL="ew-resize",e.GRAB="grab",e.GRABBING="grabbing",e.HELP="help",e.MOVE="move",e.RESIZE_N="n-resize",e.RESIZE_NE="ne-resize",e.RESIZE_NESW="nesw-resize",e.RESIZE_VERTICAL="ns-resize",e.RESIZE_NW="nw-resize",e.RESIZE_NWSE="nwse-resize",e.NO_DROP="no-drop",e.NONE="none",e.NOT_ALLOWED="not-allowed",e.POINTER="pointer",e.PROGRESS="progress",e.RESIZE_ROW="row-resize",e.RESIZE_S="s-resize",e.RESIZE_SE="se-resize",e.RESIZE_SW="sw-resize",e.TEXT="text",e.URL="url",e.RESIZE_W="w-resize",e.WAIT="wait",e.ZOOM_IN="zoom-in",e.ZOOM_OUT="zoom
1188-out",e.INHERIT="inherit",e))(TA||{});const DD=(()=>{let e="default";return t=>{e!==t&&(document.getElementById("root")?.setAttribute("global-cursor",t),e=t)}})();var Tye=(e=>(e.Thumbnail="Thumbnail",e.Timeline="Timeline",e.Body="Body",e))(Tye||{}),Sye=(e=>(e.TTVContentSetting="contentSetting",e.Validating="validating",e.Generating="generating",e))(Sye||{}),Oye=(e=>(e[e.None=0]="None",e[e.Start=1]="Start",e[e.GeneratingContents=2]="GeneratingContents",e[e.GeneratingContentsDone=3]="GeneratingContentsDone",e[e.ApplyingPostEffects=4]="ApplyingPostEffects",e[e.AlleffectsApplied=5]="AlleffectsApplied",e))(Oye||{});const hxt={random:[],active:["mewpot_bgm_4132","mewpot_bgm_6254","mewpot_bgm_6467"],intense:["mewpot_bgm_6524","mewpot_bgm_6336","mewpot_bgm_6928"],emotional:["mewpot_bgm_7046","mewpot_bgm_6200","mewpot_bgm_6647"],happy:["mewpot_bgm_7024","mewpot_bgm_7688","mewpot_bgm_7227"],horror:["mewpot_bgm_7472","mewpot_bgm_7401","mewpot_bgm_6590"]},rP={normal:"gpt-3.5",advanced:"gpt-4"};var v0=(e=>(e.FreeVideo="freeVideo",e.GenImage="genImage",e))(v0||{});const Ixt=(e,t,o,r,n,a,i)=>{switch(e){case nt.CURRENT_CLIP:return pc(r,n,a);case nt.SELECTED_CLIPS:{const s=i.filter(c=>BE(c,n,a)!==void 0);if(s.length===0)return ma;const x=pc(s[0],n,a);return s.some(c=>pc(c,n,a)!==x)?void 0:x}case nt.ALL_CLIPS:{const s=t.flatMap(c=>c.clips).filter(c=>BE(c,n,a)!==void 0);if(s.length===0)return ma;const x=pc(s[0],n,a);return s.some(c=>pc(c,n,a)!==x)?void 0:x}case nt.SCENE_CLIPS:{const s=t[o].clips.filter(c=>BE(c,n,a)!==void 0);if(s.length===0)return ma;const x=pc(s[0],n,a);return s.some(c=>pc(c,n,a)!==x)?void 0:x}}return ma},BE=(e,t,o)=>{for(const r of e.words){const n=oi(r,t,o);if(n)return n}},pc=(e,t,o)=>BE(e,t,o)?.volume??ma;var Bu=(e=>(e.ASSET_REARRANGE_MESSAGE="image_rearrange_message",e.TTS_INSERT_AFTER_MULTI_LINE_SUPPORT="tts_insert_after_multi_line_support",e.TTS_LICENSE_NOTIFIED="tts_license_notified",e.WORD_IMAGE="word_image",e.MARKER_PANEL_MESSAGE="marker_panel_message",e.WORD_ASSET="word_image",e.KENBURNS_TRY_MOVE="kenburns_try_move",e.SINGLE_IMAGE_IMPORT_TO_USER_ASSET_PANEL="single_image_import_to_user_asset_panel",e.LEGACY_ASSET_LIST="asset_list",e.MANUAL_PROXY_ACTIVATION="manual_proxy_activation",e.CLICK_WORD_DELETE_BUTTON="click_word_delete_button",e.CLICK_VIDEO_PLAY_BUTTON="click_video_play_button",e))(Bu||{});const nP=(e,t=0)=>{const o=Ve(),r=o.getObject(Ie.FEATURE_USED_COUNT);return!r[e]&&(r[e]=t,o.set(Ie.FEATURE_USED_COUNT,{...r})),r[e]},U5=(e,t=1)=>{const o=Ve(),r=o.getObject(Ie.FEATURE_USED_COUNT);o.set(Ie.FEATURE_USED_COUNT,{...r,[e]:r[e]+t})};let kD=0;const Cye=[10,20,40,80,160,320,640,1280],Rye=()=>(kD++,Cye.includes(kD)),Aye=()=>Ta(It.TABKEY_PLAY_USED),yye=()=>{wn(It.TABKEY_PLAY_USED)},FD=()=>!Aye()&&Rye(),Txt=()=>Ta(It.RETRANSLATION),vye=()=>{wn(It.RETRANSLATION)},wye=(e,t=!1)=>{const o=h("tour.ts"),{tourId:r,tourInfo:{type:n},currStep:a}=e;if(r===Fr.CLICK_WORD_DELETE_BUTTON){const s=ir().get(Wt.LAST_CLICK_WORD_DELETE_BUTTON_CLIP_ID);return s?_O(s):null}if(r===Fr.RETRANSLATE){const s=ir().get(Wt.CAPTION_MODIFIED_CLIP_ID);return s?UR(s):null}if(r===Fr.TABKEY_PLAY){const s=ir().get(Wt.TABKEY_TOOLTIP_CLIP_ID);return s?_O(s):null}if(r===Fr.MARKER_PANEL){const s=ir().get(Wt.MARKER_PANEL_CLIP_ID);return s?UR(s)?.querySelector(".clip-marker")??null:null}if(r===Fr.SILENT_BLOCK_SHORTCUT){const s=ir().get(Wt.SILENT_BLOCK_SHORTCUT_CLIP_ID);return s?_O(s):null}const i=t?document.querySelectorAll("["+W6+'="'+r+'"]['+H6+'="'+n+'"]['+j6+'="'+a+'"]'):document.querySelectorAll("["+z6+'="'+r+'"]['+Y6+'="'+n+'"]['+B6+'="'+a+'"]');return i.length>1?(o.warn("found more than one element for tourId "+r+", tourType "+n+", tourStep "+a),i[i.length-1]):i.length===0?(o.error("found no element for tourId "+r+", tourType "+n+", tourStep "+a),null):i[0]},Nye=e=>{switch(e){case Ct.NONE:return{};case Ct.TTS_NEW_USER:return{};case Ct.NEW_USER_ONBOARDING:return{[et.NEW_USER_ONBOARDING_CAPTION_MODIFY]:t=>Op(1,t),[et.NEW_USER_ONBOARDING_VIDEO_PLAY_BEFORE_DELETE]:t=>Op(2,t),[et.NEW_USER_ONBOARDING_WORD_DELETE]:t=>Op(3,t),[et.NEW_USER_ONBOARDING_VIDEO_PLAY_AFTER_DELETE]:t=>Op(4,t),[et.NEW_USER_ONBOARDING_START_MENU]:t=>Op(5,t)};case Ct.PROXY_GUIDE:return{};case Ct.PREPARE_PROXY_GUIDE:return{};case Ct.FEATURE_ONBOARDING_OVERDUB:return{[et.OVERDUB_ONBOARDING_LISTEN_CLIP]:t=>dE(1,t),[et.OVERDUB_ONBOARDING_WORD_EDIT]:t=>dE(2,t),[et.OVERDUB_ONBOARDING_LISTEN_RESULT]:t=>dE(3,t),[et.OVERDUB_ONBOARDING_START_MENU]:t=>dE(4,t)};
1188case Ct.CLICK_WORD_DELETE_BUTTON:return{};case Ct.CLICK_PREVIEW_START_BUTTON:return{};case Ct.TABKEY_PLAY:return{};case Ct.RETRANSLATE:return{};case Ct.MARKER_PANEL:return{[et.SHOW_MARKER_PANEL_TOOLTIP]:t=>{t||yz("button-click")}};case Ct.SILENT_BLOCK_SHORTCUT:return{}}},Pye=e=>{switch(e){case Ct.NONE:return{};case Ct.TTS_NEW_USER:return{};case Ct.NEW_USER_ONBOARDING:return{[et.NEW_USER_ONBOARDING_CAPTION_MODIFY]:()=>Tp(1),[et.NEW_USER_ONBOARDING_VIDEO_PLAY_BEFORE_DELETE]:()=>Tp(2),[et.NEW_USER_ONBOARDING_WORD_DELETE]:()=>Tp(3),[et.NEW_USER_ONBOARDING_VIDEO_PLAY_AFTER_DELETE]:()=>Tp(4),[et.NEW_USER_ONBOARDING_START_MENU]:()=>Tp(5)};case Ct.PROXY_GUIDE:return{};case Ct.PREPARE_PROXY_GUIDE:return{};case Ct.FEATURE_ONBOARDING_OVERDUB:return{[et.OVERDUB_ONBOARDING_LISTEN_CLIP]:()=>cE(1),[et.OVERDUB_ONBOARDING_WORD_EDIT]:()=>cE(2),[et.OVERDUB_ONBOARDING_LISTEN_RESULT]:()=>cE(3),[et.OVERDUB_ONBOARDING_START_MENU]:()=>cE(4)};case Ct.CLICK_WORD_DELETE_BUTTON:return{};case Ct.CLICK_PREVIEW_START_BUTTON:return{};case Ct.TABKEY_PLAY:return{};case Ct.RETRANSLATE:return{};case Ct.MARKER_PANEL:return{};case Ct.SILENT_BLOCK_SHORTCUT:return{}}},bye=e=>{switch(e){case Ct.NONE:return{};case Ct.TTS_NEW_USER:return{};case Ct.NEW_USER_ONBOARDING:return{[et.NEW_USER_ONBOARDING_CAPTION_MODIFY]:()=>Sp(1),[et.NEW_USER_ONBOARDING_VIDEO_PLAY_BEFORE_DELETE]:()=>Sp(2),[et.NEW_USER_ONBOARDING_WORD_DELETE]:()=>Sp(3),[et.NEW_USER_ONBOARDING_VIDEO_PLAY_AFTER_DELETE]:()=>Sp(4),[et.NEW_USER_ONBOARDING_START_MENU]:()=>Sp(5)};case Ct.PROXY_GUIDE:return{};case Ct.PREPARE_PROXY_GUIDE:return{[et.PREPARE_PROXY_GUIDE]:()=>t1e("on","tour")};case Ct.FEATURE_ONBOARDING_OVERDUB:return{[et.OVERDUB_ONBOARDING_LISTEN_CLIP]:()=>lE(1),[et.OVERDUB_ONBOARDING_WORD_EDIT]:()=>lE(2),[et.OVERDUB_ONBOARDING_LISTEN_RESULT]:()=>lE(3),[et.OVERDUB_ONBOARDING_START_MENU]:()=>lE(4)};case Ct.CLICK_WORD_DELETE_BUTTON:return{};case Ct.CLICK_PREVIEW_START_BUTTON:return{};case Ct.TABKEY_PLAY:return{};case Ct.RETRANSLATE:return{};case Ct.MARKER_PANEL:return{[et.SHOW_MARKER_PANEL_TOOLTIP]:()=>yz("action-try")};case Ct.SILENT_BLOCK_SHORTCUT:return{}}},aP=(e,t,o,r)=>{const n=e===hf.CLOSED?Nye:e===hf.ACTION_DONE?Pye:bye,a=n(t);if(a===void 0)return;const i=a[o];i!==void 0&&i(r)},Sxt=e=>e.currStep===et.OVERDUB_ONBOARDING_WORD_EDIT?(Lye(e),!0):!1,Lye=e=>{const t=wye(e,!0);t&&t.click()},Mye=3,Dye=3,kye=()=>nP(Bu.CLICK_WORD_DELETE_BUTTON,1)>=Mye,Fye=()=>nP(Bu.CLICK_VIDEO_PLAY_BUTTON,1)>=Dye,VT=(e,t)=>{const o=ir();if(o.get(e)){const r=parseInt(o.get(t)||"0",10);o.set(t,String(r+1))}},oE=e=>parseInt(ir().get(e)||"0",10),Oxt=()=>VT(Wt.WORD_DELETE_BUTTON_QUICK_TOOLTIP_SHOWN,Wt.QUICKTIP_WORD_DELETE_BUTTON_COUNT),Uye=()=>VT(Wt.WORD_DELETE_BUTTON_QUICK_TOOLTIP_SHOWN,Wt.QUICKTIP_WORD_DELETE_SHORTCUT_COUNT),Vye=()=>VT(Wt.PREVIEW_START_BUTTON_QUICK_TOOLTIP_SHOWN,Wt.QUICKTIP_PREVIEW_BUTTON_COUNT),Gye=()=>VT(Wt.PREVIEW_START_BUTTON_QUICK_TOOLTIP_SHOWN,Wt.QUICKTIP_PREVIEW_SHORTCUT_COUNT),Wye=()=>({quicktipWordDeleteButtonCount:oE(Wt.QUICKTIP_WORD_DELETE_BUTTON_COUNT),quicktipWordDeleteShortcutCount:oE(Wt.QUICKTIP_WORD_DELETE_SHORTCUT_COUNT),quicktipPreviewButtonCount:oE(Wt.QUICKTIP_PREVIEW_BUTTON_COUNT),quicktipPreviewShortcutCount:oE(Wt.QUICKTIP_PREVIEW_SHORTCUT_COUNT),isNewCid:(()=>{const e=du.get(Ci.CID_TIMESTAMP),t=mA(e);return t?t.daysPassed<1:!1})()}),Cxt=(e,t,o)=>{Vye(),!e&&(U5(Bu.CLICK_VIDEO_PLAY_BUTTON),Fye()&&!Ta(It.PREVIEW_START_BUTTON_QUICK_TOOLTIP)&&t===Ct.NONE&&(o(Ct.CLICK_PREVIEW_START_BUTTON,Fr.CLICK_PREVIEW_START_BUTTON),wn(It.PREVIEW_START_BUTTON_QUICK_TOOLTIP)))},Hye=e=>{const t=e==="script"?g.SCRIPT:g.CLIPS;I().event(m.EDIT_VIEW,t)},V5=e=>{I().event(m.EDIT_VIEW,g.SCRIPT,e)},jye={type:Mt(ke.VIEW_MODE)??"clips",newlineMode:Mt(ke.NEWLINE_MODE)??!1,showAssetsInScript:Mt(ke.SHOW_ASSETS_IN_SCRIPT)??!0},GT=In({name:"viewMode",initialState:jye,reducers:{setViewMode:(e,t)=>{e.type=t.payload},setNewlineMode:(e,t)=>{e.newlineMode=t.payload},setShowAssetsInScript:(e,t)=>{e.showAssetsInScript=t.payload}}}),Rxt=GT.reducer,Axt=e=>t=>{po(ke.VIEW_MODE,e),Hye(e),t(GT.actions.setViewMode(e))},yxt=e=>t=>{po(ke.NEWLINE_MODE,e),V5(e?"newline_on":"newline_off"),t(GT.actions.setNewlineMode(e))},vxt=e=>t=>{po(ke.SHOW_ASSETS_IN_SCRIPT,e),V5(e?"assets_on":"assets_off"),t(GT.actions.setShowAssetsInScript(e))},iP=e=>ja(e).viewMode,G5=e=>iP(e).type,wxt=e=>G5(e)==="script",zye=e=>iP(e).newlineMode,Yye=e=>iP(e).showAssetsInScript,Bye={fontWeight:"font-weight",fontFamily:"font-family",fontStyle:"font-style",textDecoration:"text-decoration",color:"color",fontSize:"font-size",textShadow:"text-shadow",background:"background",padding:"padding",borderRadius:"border-radius",margin:"margin",display:"display",letterSpacing:"letter-spacing",lineHeight:"line-height"},Zo=t2.import("parchment"),Kye={[Ro.bold]:{scope:Zo.Scope.INLINE_ATTRIBUTE,whitelist:void 0},[Ro.italic]:{scope:Zo.Scope.INLINE_ATTRIBUTE,whitelist:void 0},[Ro.strike]:{scope:Zo.Scope.INLINE_ATTRIBUTE,whitelist:void 0},[Ro.underline]:{scope:Zo.Scope.INLINE_ATTRIBUTE,whitelist:void 0},[Ro.font]:{scope:Zo.Scope.INLINE_ATTRIBUTE,whitelist:void 0},[Ro.size]:{scope:Zo.Scope.INLINE_ATTRIBUTE,whitelist:void 0},[Ro.color]:{scope:Zo.Scope.INLINE_ATTRIBUTE,whitelist:void 0},[Ro.outlineOn]:{scope:Zo.Scope.INLINE_ATTRIBUTE,whitelist:void 0},[Ro.secondaryOutlineOn]:{scope:Zo.Scope.INLINE_ATTRIBUTE,whitelist:void 0},[Ro.backgroundOn]:{scope:Zo.Scope.INLINE_ATTRIBUTE,whitelist:void 0},[Ro.shadowOn]:{scope:Zo.Scope.INLINE_ATTRIBUTE,whitelist:void 0},[Ro.outlineColor]:{scope:Zo.Scope.INLINE_ATTRIBUTE,whitelist:void 0},[Ro.outlineWidth]:{scope:Zo.Scope.INLINE_ATTRIBUTE,whitelist:void 0},[Ro.secondaryOutlineColor]:{scope:Zo.Scope.INLINE_ATTRIBUTE,whitelist:void 0},[Ro.secondaryOutlineWidth]:{scope:Zo.Scope.INLINE_ATTRIBUTE,whitelist:void 0},[Ro.background]:{scope:Zo.Scope.INLINE_ATTRIBUTE,whitelist:void 0},[Ro.backgroundAlpha]:{scope:Zo.Scope.INLINE_ATTRIBUTE,whitelist:void 0},[Ro.backgroundRadius]:{scope:Zo.Scope.INLINE_ATTRIBUTE,whitelist:void 0},[Ro.backgroundPaddingSide]:{scope:Zo.Scope.INLINE_ATTRIBUTE,whitelist:void 0},[Ro.backgroundPaddingTop]:{scope:Zo.Scope.INLINE_ATTRIBUTE,whitelist:void 0},[Ro.backgroundPaddingBottom]:{scope:Zo.Scope.INLINE_ATTRIBUTE,whitelist:void 0},[Ro.shadowColor]:{scope:Zo.Scope.INLINE_ATTRIBUTE,whitelist:void 0},[Ro.shadowColorAlpha]:{scope:Zo.Scope.INLINE_ATTRIBUTE,whitelist:void 0},[Ro.shadowPositionX]:{scope:Zo.Scope.INLINE_ATTRIBUTE,whitelist:void 0},[Ro.shadowPositionY]:{scope:Zo.Scope.INLINE_ATTRIBUTE,whitelist:void 0},[Ro.shadowBlurRadius]:{scope:Zo.Scope.INLINE_ATTRIBUTE,whitelist:void 0},[Ro.letterSpacing]:{scope:Zo.Scope.INLINE_ATTRIBUTE,whitelist:void 0},[Ro.lineHeight]:{scope:Zo.Scope.BLOCK_ATTRIBUTE,whitelist:void 0}},Xye=t2.import("parchment");class au extends Xye.Attributor.Attribute{constructor(t,o,r){super(t,au.keyName(t),o),this.callback=r}callback;static keyName=t=>"data-"+t;static build=(t,o,r)=>{const n=a=>{const i=t.map(x=>a.getAttribute(au.keyName(x))||""),s=r(...i);a.style.setProperty(o,s)};return t.reduce((a,i)=>(a[i]=new au(i,Kye[i],n),a),{})};add(t,o){return super.add(t,o)===!1?!1:(this.callback(t),!0)}
1188canAdd(t,o){return this.whitelist==null?!0:typeof o=="string"?this.whitelist.indexOf(o.replace(/["']/g,""))>-1:this.whitelist.indexOf(o)>-1}remove(t){super.remove(t),this.callback(t),!t.getAttribute("style")&&t.removeAttribute("style")}stack=(...t)=>new au(this.attrName,{scope:this.scope,whitelist:this.whitelist},o=>{this.callback(o),t.forEach(r=>r.callback(o))})}const Jye=[25,50,75,90,100,110,125,150,200,250,300,350,400,450,500],Nxt=au.build([Ro.size],Bye.fontSize,e=>e!==""?Number(e)/EU+"px":"");var Jl=(e=>(e.WORD="WORD",e.CLIP="CLIP",e.ELEMENT="ELEMENT",e))(Jl||{}),L0=(e=>(e.COPY_TO_CLIPBOARD="COPY_TO_CLIPBOARD",e.CUT_TO_CLIPBOARD="CUT_TO_CLIPBOARD",e.WORD_PASTE_FROM_CLIPBOARD="WORD_PASTE_FROM_CLIPBOARD",e.CLIP_PASTE_FROM_CLIPBOARD="CLIP_PASTE_FROM_CLIPBOARD",e.ELEMENTS_PASTE_FROM_CLIPBOARD="ELEMENTS_PASTE_FROM_CLIPBOARD",e.APPLY_SHARED_CLIPBOARD="APPLY_SHARED_CLIPBOARD",e))(L0||{});const Oa=()=>Ve().getBool(Ie.VIDEO_LOCK),Pxt=e=>{Ve().set(Ie.VIDEO_LOCK,e)},W5=e=>{if(Oa())switch(e){case ot.REMOVE_SCENES:case L0.CUT_TO_CLIPBOARD:case ot.DELETE_BLANKS:case ot.REVERT_BLANKS:case ot.DRAG_WORDS:case ot.MOVE_CLIPS:case ot.MOVE_SCENES:case L0.WORD_PASTE_FROM_CLIPBOARD:case L0.CLIP_PASTE_FROM_CLIPBOARD:case ot.DELETE_CUTS:case ot.DELETE_SELECTED:return!0}return!1},Ca=()=>{const e="video-lock",t=To.generateToastOption(e,Na.DEFAULT,3e3),o=To.generateToastComponent(A("video_lock.inform"));!To.isActive(e)&&(To.clearWaitingQueue(),To.popup(o,{...t})),Cke()},bxt=e=>{const t="toggle-video",o=To.generateToastOption(t,Na.DEFAULT,1e3),r=To.generateToastComponent(e?A("toolbar.toggle_video_lock"):A("toolbar.toggle_video_unlock"));To.clearWaitingQueue(),To.dismiss(t),To.popup(r,o)},Lxt=()=>{const e="video-lock",t=To.generateToastOption(e,Na.DEFAULT,3e3),o=To.generateToastComponent(A("video_lock.discontinuous_section_warning"));!To.isActive(e)&&(To.clearWaitingQueue(),To.popup(o,{...t}))},qye=5,WT=(e,t)=>{switch(e){case Kt.MP4:return"mp4";case Kt.SRT:return"srt";case Kt.TXT:return"txt";case Kt.XML:switch(t){case gi.PREMIERE:return"premiere";case gi.FCPX:return"finalcut";case gi.DAVINCI:return"davinci"}break;case Kt.FCPXML:return"finalcut";case Kt.MOV:return"mov";case Kt.MP3:return"mp3";case Kt.WAV:return"wav";case Kt.PNG:return"png";case Kt.GIF:return"gif";case Kt.HLS:return"m3u8"}return"not supported"},sP=e=>{if(e){if(e===K6)return"demo"}else return"invalid";return e},Qye=(e,t)=>["mp3","wav"].includes(t)?!1:["srt","txt","premiere","finalcut","davinci"].includes(t)?!0:Mv(e),HT=(e,t,o,r,n,a=!1)=>{const i=tc(e),s=ex(e),x=VW(e),{globalClips:c}=Dg(e),l=I2(e),d=He(e),u=on(i),p=oc(e),f=Qye(e,t),E=Oa(),T=Mv(e),O=Fi(e),S=vg(e),{assetInfos:R,audioTransformsMap:y,watermark:v}=f2(e),w=mo(e),N=lt(e),M=ht(e),k=hxe(e),F=lve(w,u,f),G=qve(d.map(fe=>kf(fe,0)),c.map(fe=>kf(fe,0)),E,p),{exportScenes:B,exportClips:W}=dve(e,o),Q=se().getCurrentProjectFileType(),j=se().getAllFileInfos(),$=new Li(S).collectFrom({type:Or.SCENE,model:w}).build(),q=$.getUsedSourceMediaIds(),H=$.getActiveAssetMediaIds(R),U=$.getActiveAudioMediaIds(y),te=v?.mediaId,ne=new Set([...q,...H,...U,...te?[te]:[]]),oe=j.filter(fe=>ne.has(fe.mediaId)),re=swe(W,B,T,u,s,r,j0(l),x,G.projectId,Q,O,oe,N,M,k),ge=xwe(e);return{exportId:n,language:Fe(),captionDisplayMode:xn(e),mediaLanguage:e.snapshots.present.transcript.projectAudioLanguage,captionLanguage:F,outputType:t,project:G,export:re,etc:ge,doesNewExportUsed:a}},$n=(e,t=1)=>{const o=Math.pow(10,t);return Math.round(e*o)/o},Zye=(e,t,o,r,n)=>{const a=JSON.stringify({exportId:e,totalProjectMediaSize:t,projectDurationMin:$n(r),projectType:o});I().event(m.EXPORT,g.EXPORT_MEDIA_SIZE,n,void 0,a)},jT=(e,t)=>{const o=Ha();tve(e,t,o),eve(e,t,o),$ye(e.exportId,t,o),ove(e,o),nve(e,o),ave(e,t,o),sve(e,o),uwe(e,o),cwe(e,t,o),pwe(e,o),_we(e,o),lwe(e,t,o),Ewe(e,t,o),rve(e,o),mwe(e,o),ive(e,o),xve(e),cve(e),gwe(e,o),fwe(e,o),Zye(e.exportId,e.export.totalProjectMediaSize,e.export.projectType,e.project.duration,o)},zT=(e,t,o,r,n=0)=>{const{projectAudioLanguage:a,translateInfo:i}=rt(e),s=mo(e),x=on(a),c=s.length,l=xn(e);return{exportId:t,language:x,numberOfScenes:c,numberOfTranslationPair:i?1:0,pairDetails:"",sourceCaptionLang:i?.source,targetCaptionLang:i?.target,captionDisplayMode:l,outputType:o,captionExportMode:r,numberOfAutoTranslate:n,numberOfTranslate:i?.numberOfTranslate??0,projectId:sP(se().getProjectId()),isProjectSaved:se().isProjectSaved()?"saved":"not-saved"}},YT=async e=>{const t=JSON.stringify({exportId:e.exportId,numberOfScenes:e.numberOfScenes,numberOfTranslationPair:e.numberOfTranslationPair,pairDetails:e.pairDetails,language:e.language,sourceCaptionLang:e.sourceCaptionLang,targetCaptionLang:e.targetCaptionLang,captionDisplayMode:XI(e.captionDisplayMode),outputType:e.outputType,captionExportMode:e.captionExportMode,numberOfAutoTranslate:e.numberOfAutoTranslate,numberOfTranslate:e.numberOfTranslate,projectId:e.projectId,isProjectSaved:e.isProjectSaved});I().event(m.VA_EXPORT,g.VA_TRANSLATE,Ha(),void 0,t)},da=()=>({[Z.NORMAL]:0,[Z.SILENT]:0,[Z.ENTER]:0,[Z.SOUND]:0,[Z.LAUGHTER]:0,[Z.CLAP]:0,[Z.FILLER]:0,[Z.SPACER]:0,[Z.AU
1188DIO_EVENT]:0}),UD=(e,t=o=>1)=>{const o=e.globalClips,r=da();return o.forEach(n=>{n.words.forEach(a=>{r[a.type]+=t(a)})}),r},Qd=e=>({normal:e[Z.NORMAL],silent:e[Z.SILENT],sound:e[Z.SOUND],laughter:e[Z.LAUGHTER],clap:e[Z.CLAP],filler:e[Z.FILLER],audioEvent:e[Z.AUDIO_EVENT]}),BT=e=>{const t=rt(e),o=Dg(e),r=Lv(e),n=TH(o.globalClips),a=n,i=r,s=Yo(),x=UD(o),c=UD(t),l=da(),d=da(),u=da();for(const p in x){const f=p;l[f]=s.wordCursorCount[f]+s.wordSelectionCount[f]+s.wordCorrectionCount[f],x[f]===0?(d[f]=0,u[f]=0):(d[f]=(x[f]-c[f])/x[f],u[f]=l[f]/x[f])}return{sourceTotalDurationSec:a,currentDurationSec:i,projectId:sP(se().getProjectId()),isProjectSaved:se().isProjectSaved()?"saved":"not-saved",originalWordCounts:x,exportedWordCounts:c,editedWordCounts:l,deletedWordRatios:d,editedWordRatios:u,didEditCuts:a.toFixed(2)===i.toFixed(2),cursorStateCounts:{word:s.sumCountsByWordType(s.wordCursorCount),correction:s.sumCountsByWordType(s.wordCorrectionCount),selection:s.sumCountsByWordType(s.wordSelectionCount),clip:s.clipCursorCount,insert:s.sumCountsByWordType(s.wordInsertCount),insertExceptSide:s.sumCountsByWordType(s.wordInsertCountExceptSide)}}},$ye=(e,t,o)=>{const{cursorStateCounts:r}=t,n=JSON.stringify({exportId:e,word:r.word,correction:r.correction,selection:r.selection,clip:r.clip,insert:r.insert,insertExceptSide:r.insertExceptSide});I().event(m.VA_EXPORT,g.VA_CURSOR_STATE,o,void 0,n)},eve=(e,t,o)=>{const r=JSON.stringify({exportId:e.exportId,outputType:e.outputType,numSources:e.project.numSources,sourceTotalDurationMin:Math.floor(t.sourceTotalDurationSec/60),currentDurationMin:Math.floor(t.currentDurationSec/60),sourceTotalDurationSec:Math.round(t.sourceTotalDurationSec),currentDurationSec:Math.round(t.currentDurationSec),projectId:t.projectId,isProjectSaved:t.isProjectSaved,originalWordCounts:Qd(t.originalWordCounts),exportedWordCounts:Qd(t.exportedWordCounts),editedWordCounts:Qd(t.editedWordCounts),deletedWordRatios:Qd(t.deletedWordRatios),editedWordRatios:Qd(t.editedWordRatios),didEditCuts:t.didEditCuts?"1":"0"});I().event(m.VA_EXPORT,g.VA_CUT_EDIT_EXPORT,o,void 0,r)},tve=(e,t,o)=>{const r=H5(e.export.ttsExportStats),n=JSON.stringify({exportId:e.exportId,language:e.language,doesNewExportUsed:e.doesNewExportUsed,mediaLanguage:e.mediaLanguage,captionLanguage:e.captionLanguage,captionDisplayMode:XI(e.captionDisplayMode),exportType:e.outputType,numSources:e.project.numSources,projectDurationMin:$n(e.project.duration),exportDurationMin:$n(e.export.duration),originalNumClips:e.project.originalNumClips,numExportClips:e.export.numClips,numVideoEditedClips:e.export.numVideoEditedClips,numCaptionEditedClips:e.export.numCaptionEditedClips,captionEditedClipRatio:e.export.captionEditedClipRatio,numScenes:e.export.numScenes,numProjectClips:e.project.numClips,numClipsWithCaption:e.export.numClipsWithCaption,clipsWithCaptionRatio:e.export.clipsWithCaptionRatio,numClipsWithCaptionSetting:e.export.numClipsWithCaptionSetting,numUniqueCaptionSetting:e.export.numUniqueCaptionSetting,clipsWithCaptionSettingRatio:e.export.clipsWithCaptionSettingRatio,videoLock:e.project.videoLock,didTranslationOccurInProject:e.project.didTranslationOccurInProject,projectId:e.project.projectId,totalBlankDuration:e.export.totalBlankDuration,numImageInstances:e.export.numImageInstances,numUserImageInstances:e.export.numUserImageInstances,numGenImageInstances:e.export.numGenImageInstances,numGenEditImageInstances:e.export.numGenEditImageInstances,numMarkers:e.export.numMarkers,numStockImageInstances:e.export.numStockImageInstances,numPlaybackRateClips:e.export.numPlaybackRateClips,playbackRateClipRatio:e.export.playbackRateClipRatio,numVideoTransformClips:e.export.numVideoTransformClips,videoTransformClipRatio:e.export.videoTransformClipRatio,numTTS:e.export.numClipsWithTTS,numClipTTSCount:e.export.numClipTTSCount,numEffectTTSCount:e.export.numEffectTTSCount,numDubbingTTSCount:e.export.numDubbingTTSCount,clipTTSCountRatio:e.export.clipTTSCountRatio,effectTTSCountRatio:e.export.effectTTSCountRatio,dubbingTTSCountRatio:e.export.dubbingTTSCountRatio,numBGM:e.export.numBGM,numBGMClips:e.export.numBGMClips,numUserBGM:e.export.numUserBGM,startMode:e.project.startMode,videoAudioModeDetail
1188:e.project.videoAudioModeDetail,numVolumeChangedClips:e.export.numVolumeChangedClips,volumeChangedClipRatio:e.export.volumeChangedClipRatio,selectedVideoRatio:e.export.videoRatioString,numClipsWithText:e.export.webAssetExportStats.numClipsWithText,numSoundFX:e.export.numSoundFX,soundFXClipRatio:e.export.soundFXClipRatio,numFreeSoundFX:e.export.numFreeSoundFX,numUserSoundFX:e.export.numUserSoundFX,userAssetVideoCount:e.export.userAssetVideoCount,freeAssetVideoCount:e.export.freeAssetVideoCount,imageKenburnsCount:e.export.imageKenburnsCount,numShapes:e.export.numShapes,usedShapeKeys:e.export.usedShapeKeys,imageAnimationsCount:e.export.imageAnimationsCount,numCharacters:e.export.numCharacters,numUserCharacters:e.export.numUserCharacters,numClipColorApplicableClips:e.export.numClipColorApplicableClips,numClipColorAppliedClips:e.export.numClipColorAppliedClips,numClipColorApplicableAndAppliedClips:e.export.numClipColorApplicableAndAppliedClips,uniqueFramePackIdsInAssets:e.export.uniqueFramePackIdsInAssets,usedFramePackType:e.project.usedFramePackType,isAIWritingUsed:e.project.isAIWritingUsed,aiWritingMode:e.project.aiWritingMode,lastUsedWritingModel:e.project.lastUsedWritingModel,videoStyleTag:e.project.videoStyleTag,videoRemixIncluded:e.export.videoRemixExportStats.exportWithRemixScene,numClipWithRoomEffect:e.export.numClipWithRoomEffect,vCloudUploadCounts:e.export.vcloudExportStats.vCloudUploadCounts,useVCloudProject:e.export.vcloudExportStats.useVCloudProject,ttvOptionCaptionLength:e.project.ttvOptionCaptionLength,ttvOptionCaptionPosition:e.project.ttvOptionCaptionPosition,ttvOptionCaptionAutoAnimation:e.project.ttvOptionCaptionAutoAnimation,numSystemFonts:e.export.numSystemFonts,numFreeFonts:e.export.numFreeFonts,numFonts:e.export.numFonts,isFreeFontUsed:e.export.isFreeFontUsed,isSystemFontUsed:e.export.isSystemFontUsed,numCharacterClips:e.export.characterAssetExportStats.numCharacterClips,characterClipRatio:e.export.characterAssetExportStats.characterClipRatio,numUniqueCharacters:e.export.characterAssetExportStats.numUniqueCharacters,basicTextBoxCount:e.export.webAssetExportStats.basicTextBoxCount,designedTextBoxCount:e.export.webAssetExportStats.designedTextBoxCount,textBoxCount:e.export.webAssetExportStats.textBoxCount,animationTextCount:e.export.webAssetExportStats.animationTextCount,editedWordRatios:Qd(t.editedWordRatios),numUserTTSClipCount:e.export.numUserTTSClipCount,numCharacteristicTTSClipCount:e.export.numCharacteristicTTSClipCount,numCharacteristicTTSEffectCount:e.export.numCharacteristicTTSEffectCount,numCharacteristicTTSDubbingCount:e.export.numCharacteristicTTSDubbingCount,userTTSClipCountRatio:e.export.userTTSClipCountRatio,numTotalTTSSpeakers:r.numTotalSpeakers,numTotalTTSSpeakerLangs:r.numTotalSpeakerLangs,mostUsedTTSSpeaker:r.mostUsedSpeaker,mostTTSSpeakerRatio:r.mostSpeakerRatio,numTotalTTS:r.numTotalTTS,numClipMultipleTTSVoicesCount:e.export.numClipsWithMultipleTTSVoices,numTTSDubbingOnSource:r.numDubbingOnEmptyClip,numTTSDubbingOnTTS:r.numDubbingOnTTS,numTTSDubbingOnEmptyClip:r.numDubbingOnEmptyClip,numTTSSpacerCount:e.export.numSpacerCount,numFreezeCount:e.export.numFreezeCount,numTTSClipWithRoomEffectMetal:e.export.ttsVoiceEffectPayload.numClipWithRoomEffectMetal,numTTSClipWithRoomEffectEcho:e.export.ttsVoiceEffectPayload.numClipWithRoomEffectEcho,numTTSClipWithRoomEffectRailway:e.export.ttsVoiceEffectPayload.numClipWithRoomEffectRailway,numTTSClipWithRoomEffectTelephone:e.export.ttsVoiceEffectPayload.numClipWithRoomEffectTelephone,numTTSClipWithRoomEffectRadio:e.export.ttsVoiceEffectPayload.numClipWithRoomEffectRadio,captionCount:e.export.captionCount,captionAnimationsCount:e.export.captionAnimationsCount,clientLinebreakExecuteCount:e.export.clientLinebreakExecuteCount,numTransitionClips:e.export.transitionClipCount,denoisedSourceCount:e.export.denoisedSourceCount,numOverdubWords:e.export.numOverdubWords,projectType:e.export.projectType,totalProjectMediaSize:e.export.totalProjectMediaSize,editView:e.etc.viewMode,scriptViewNewline:e.etc.scriptViewNewline,scriptViewShowAssets:e.etc.scriptViewShowAssets,...Wye()});I().event(m.VA_EXPORT,g.VA_UNIVERSAL_EXPORT,o,void 0,n)},ove=(e,t)=>
1188{const{playbackRateCount:o}=e.export,r=Object.keys(o).sort((c,l)=>o[l]-o[c]),n=r.length>0,a=r.reduce((c,l)=>c+=o[l],0),i=r[0]??"null",s=o[i]??"null",x=JSON.stringify({exportId:e.exportId,usedPlaybackRate:n,outputType:e.outputType,playbackRateAppliedClipCount:a,mostUsedPlaybackRate:i,mostUsedPlaybackRateClipCount:s,numClips:e.export.numClips});I().event(m.VA_EXPORT,g.VA_PLAYBACK_RATE,t,void 0,x)},rve=(e,t)=>{const{videoRatioString:o,globalVideoTransform:r,videoRatio:n}=e.export,a=n!==w4()?"True":"False",i=j_e(n,r),s=JSON.stringify({exportId:e.exportId,useVideoRatio:a,selectedVideoRatio:o,optionName:i});I().event(m.VA_EXPORT,g.VA_RATIO,t,void 0,s)},nve=(e,t)=>{const{zoomCount:o,rotationCount:r}=e.export,n=Object.keys(o).sort((d,u)=>o[u]-o[d]),a=Object.keys(r).sort((d,u)=>o[u]-o[d]),i=n.reduce((d,u)=>d+=o[u],0),s=a.reduce((d,u)=>d+=r[u],0),x=n[0]??"null",c=a[0]??"null",l=JSON.stringify({exportId:e.exportId,isVideoTransform:e.export.numVideoTransformClips>0,outputType:e.outputType,numClips:e.export.numClips,numVideoTransformClips:e.export.numVideoTransformClips,numZoomedClips:i,numRotatedClips:s,numPositionedClips:e.export.numPositionedClips,mostUsedZoom:x,mostUsedRotation:c});I().event(m.VA_EXPORT,g.VA_ZOOM_ROTATE,t,void 0,l)},ave=(e,t,o)=>{const r=e.export.imageInfo,n=JSON.stringify({exportId:e.exportId,outputType:e.outputType,numSources:e.project.numSources,totalBlankDuration:e.export.totalBlankDuration,didEditCuts:t.didEditCuts?"1":"0",isVrewLogoUsed:e.export.isVrewLogoUsed?"1":"0",numClips:e.project.numClips,numClipsWithImage:e.export.numClipsWithImage,numUnknownImage:r[_e.UNKNOWN],numModelUploadImage:r[_e.MODAL_UPLOAD],numPanelImage:r[_e.PANEL_UPLOAD],numStockImage:r[_e.STOCK_IMAGE]+r[_e.STOCK_CONTEXT_FLOATING_MENU],numClipboardImage:r[_e.SYSTEM_CLIPBOARD],imageCount:e.export.imageCount,clipImageCount:e.export.clipImageCount,wordImageCount:e.export.wordImageCount,filledImageCount:e.export.filledImageCount,contain:e.export.imageFillCount.contain,cut:e.export.imageFillCount.cut,cover:e.export.imageFillCount.cover,context:e.export.imageFillMenuCount.context,floating:e.export.imageFillMenuCount.floating,numContextFloatingMenuImage:r[_e.CONTEXT_FLOATING_MENU]+r[_e.STOCK_CONTEXT_FLOATING_MENU],numDragNDropImage:r[_e.DRAG_AND_DROP],numBetweenClipContextMenuImage:r[_e.BETWEEN_CLIP_CONTEXT_MENU],numFromNewClipOptionImage:e.export.numImageFromNewClipOptions,numTransparentImage:e.export.imageTransparentCount,numOpenmojiImage:e.export.imageOpenmojiCount,numCopyPasteImage:r[_e.COPY_AND_PASTE],numInsertedMyassetImage:r[_e.USER_ASSET_PANEL],imageKenburnsCount:e.export.imageKenburnsCount,imageAnimationsCount:e.export.imageAnimationsCount,imageCropCount:e.export.imageCropCount,imageRemoveBackgroundCount:e.export.imageRemoveBackgroundCount,imageRemoveBackgroundWithCropCount:e.export.imageRemoveBackgroundWithCropCount});I().event(m.VA_EXPORT,g.VA_IMAGE_INFO,o,void 0,n)},ive=(e,t)=>{const o=e.export.characterAssetExportStats,r=JSON.stringify({exportId:e.exportId,...o});I().event(m.VA_EXPORT,g.VA_CHARACTER_INFO,t,void 0,r)},Ln=e=>ue(e,3),sve=(e,t)=>{const o=e.export.webAssetExportStats.textBoxCount,r=e.export.webAssetExportStats,n={},a={},i={},s={},x={};Object.keys(r.positionCountStat).forEach(d=>{n[d]=Ln(r.positionCountStat[d]/o)}),Object.keys(r.centerPositionCountStat).forEach(d=>{a[d]=Ln(r.centerPositionCountStat[d]/o)}),Object.keys(r.maxFontSizeCountStat).forEach(d=>{i[d]=Ln(r.maxFontSizeCountStat[d]/o)}),Object.keys(r.textLengthCountStat).forEach(d=>{s[d]=Ln(r.textLengthCountStat[d]/o)}),Object.keys(r.rotationDegreeCountStat).forEach(d=>{x[d]=r.rotationDegreeCountStat[d]/o});const c=ue(e.export.elapsed.webAssetPrepare??0,2),l=JSON.stringify({exportId:e.exportId,outputType:e.outputType,numSources:e.project.numSources,numClips:e.project.numClips,numClipsWithText:r.numClipsWithText,numClipsWithCaptionAndText:r.numClipsWithCaptionAndText,textBoxCount:o,basicTextBoxCount:r.basicTextBoxCount,designedTextBoxCount:r.designedTextBoxCount,blingblingTextBoxCount:r.blingblingTextBoxCount,emojiTextboxCount:r.emojiTextboxCount,positionCountStat:r.positionCountStat,positionRatioStat:n,centerPositionCountStat:r.centerPositionCountStat,centerPositionRatioStat:a,maxFontSizeRatioStat:i,textLanguageCountStat:r.textLanguageCountStat,textLengthCountStat:r.textLengthCountStat,textLengthRatioStat:s,rotationDegreeCountStat:r.rotationDegreeCountStat,rotationDegreeRatioStat:x,boldTextRatio:Ln(r.boldTextCount/o),italicTextRatio:Ln(r.italicTextCount/o),noStyleTextRatio:Ln(r.noStyleTextCount/o),coloredTextRatio:Ln(r.coloredTextCount/o),outlineTextRatio:Ln(r.outlineTextCount/o),backgroundTextRatio:Ln(r.backgroundTextCount/o),shadowTextRatio:Ln(r.shadowTextCount/o),rubyTextRatio:Ln(r.rubyAppliedTextCount/o),letterSpacingAppliedTextRatio:Ln(r.letterSpacingAppliedTextCount/o),lineHeightAppliedTextRatio:Ln(r.lineHeightAppliedTextCount/o),fontSizeMixedTextRatio:Ln(r.fontSizeMixedTextCount/o),prepareElapsed:c,clipTextBoxCount:r.clipTextBoxCount,wordTextBoxCount:r.wordTextBoxCount,wordTextBoxRatio:Ln(r.wordTextBoxCount/o),toolbarImportCount:r.toolbarImportCount,contextMenuImportCount:r.contextMenuImportCount,contextFloatingMenuImportCount:r.contextFloatingMenuImportCount,singleClipRangeTextboxCount:r.singleClipRangeTextboxCount,longRangeTextboxCount:r.longRangeTextboxCount,singleClipRangeTextboxRatio:Ln(r.singleClipRangeTextboxCount/o),longRangeTextboxRatio:Ln(r.longRangeTextboxCount/o),clipsWithCaptionAndTextRatio:Ln(r.numClipsWithCaptionAndText/r.numClipsWithText),designedTextCountStat:r.designedTextCountStat,clipsWithDesignedTextboxes:r.clipsWithDesignedTextboxes,panelModifiedTextboxCount:r.panelModifiedTextboxCount,animationTextCount:r.animationTextCount,savedStylesApplyCount:r.savedStylesApplyCount});I().event(m.VA_EXPORT,g.VA_TEXT_INFO,t,void 0,l)},xve=e=>{const{outputType:t,project:o}
1188=e,{startMode:r,videoAudioModeDetail:n,cumulativeFramePackApplyCount:a,lastAppliedFramePack:i,ratioChangedByFramePack:s,usedFramePackType:x}=o,{videoRatioString:c,uniqueFramePackIdsInAssets:l}=e.export,d=JSON.stringify({exportId:e.exportId,startMode:r,videoAudioModeDetail:n,outputType:t,selectedVideoRatio:c,cumulativeTemplateApplyCount:a,lastAppliedTemplate:i??"none",ratioChangedByTemplate:s,uniqueTemplateIdsInAssets:l,usedTemplateType:x});I().event(m.VA_EXPORT,g.VA_FRAMEPACK,void 0,void 0,d)},cve=e=>{const{outputType:t,project:o}=e,{startMode:r,videoAudioModeDetail:n,cumulativeTemplateApplyCount:a,lastAppliedTemplateName:i}=o,{videoRatioString:s,uniqueTemplateNamesInAssets:x}=e.export,c=JSON.stringify({exportId:e.exportId,startMode:r,videoAudioModeDetail:n,outputType:t,selectedVideoRatio:s,cumulativeTemplateApplyCount:a,lastAppliedTemplateName:i,uniqueTemplateNamesInAssets:x});I().event(m.VA_EXPORT,g.VA_TEMPLATE,void 0,void 0,c)},lve=(e,t,o)=>{if(!o)return rr.EMPTY;const r=[];e.forEach(i=>{const s=qye-r.length;s!==0&&r.push(...i.clips.slice(0,s))});const n=r.map(i=>Hn(i,Ar(t),0,!1,!0)).join("").trim();return K7(n)},dve=(e,t)=>{const{globalClips:o}=rt(e),r=mo(e),n=$x(e);if(t===Vo.SELECTED_CLIPS){const{encodeClips:a}=xT(e,t);return{exportScenes:[n],exportClips:a}}else if(t===Vo.SCENE_CLIPS){const a=n.clips;return{exportScenes:[n],exportClips:a}}else return{exportScenes:r,exportClips:o.map(i=>kf(i,0))}},uve=(e,t)=>e.filter(o=>o.assetIds.some(r=>L.get(t,r)!==void 0)).length,pve=(e,t,o,r)=>e.filter(n=>N2(n.words,t,o,r)).length,fve=e=>{const t=e.length,o=e.filter(S=>S.type==="CLIP").length,r=e.filter(S=>S.type==="EFFECT").length,n=e.filter(S=>S.speaker.provider===Oe.UserTTS&&S.type==="CLIP").length,a=e.filter(S=>S.speaker.provider===Oe.UserTTS&&S.type==="EFFECT").length,i=e.filter(S=>S.speaker.provider===Oe.UserTTS&&S.type==="DUBBING").length,s=e.filter(S=>PO(S.speaker)&&S.type==="CLIP").length,x=e.filter(S=>PO(S.speaker)&&S.type==="EFFECT").length,c=e.filter(S=>PO(S.speaker)&&S.type==="DUBBING").length,l=new Set(e.filter(S=>S.speaker.provider===Oe.UserTTS).map(S=>S.speaker.speakerId)).size,d=e.filter(S=>S.type==="DUBBING").length,u=$n(o/t,3),p=$n(r/t,3),f=$n(n/t,3),E=$n(d/t,3),T=$n(a/t,3),O=$n(i/t,3);return{numClipTTSCount:o,numEffectTTSCount:r,numDubbingTTSCount:d,numUserTTSClipCount:n,numUserTTSEffectCount:a,numUserTTSDubbingCount:i,numUserTTSSpeakerCount:l,numCharacteristicTTSClipCount:s,numCharacteristicTTSEffectCount:x,numCharacteristicTTSDubbingCount:c,clipTTSCountRatio:u,effectTTSCountRatio:p,dubbingTTSCountRatio:E,userTTSClipCountRatio:f,userTTSEffectCountRatio:T,userTTSDubbingCountRatio:O}},gve=(e,t,o,r)=>e.filter(n=>Xg(n.words,t,o).filter(s=>pd(s,r)).length>1).length,_ve=e=>e.reduce((t,o)=>t+o.words.filter(r=>r.type===Z.SPACER&&!r.freeze).length,0),Eve=e=>e.reduce((t,o)=>t+o.words.filter(r=>Q0(r)).length,0),mve=e=>{const t=e.flatMap(o=>o.captions).filter(o=>o.style);return{clipCaptionSettingCount:t.length,clipCaptionSettingUniqueCount:t.length,clipsWithCaptionSettingRatio:ue(t.length/e.length,3)}},hve=(e,t,o)=>aH(e).reduce((a,i)=>{const{visualMediaId:s,audioMediaId:x}=ss(i,t,o);return s===void 0&&x===void 0?a+sr(i):a},0),Ive=(e,t)=>{const o=e.reduce((x,c)=>[...x,...c.assetIds],[]),r=new Set(o.filter(x=>L.get(t,x)?.importType!==void 0)).size,n=new Set(o.filter(x=>{const c=L.get(t,x)?.importType;return c===_e.STOCK_IMAGE||c===_e.STOCK_CONTEXT_FLOATING_MENU||c===_e.IMAGE_GENERATE_MODAL_STOCK||c===_e.IMAGE_REPLACE_MODAL_STOCK})).size,a=new Set(o.filter(x=>{const c=L.get(t,x)?.importType;return c===_e.CONTEXT_FLOATING_MENU||c===_e.DRAG_AND_DROP||c===_e.MODAL_UPLOAD||c===_e.PANEL_UPLOAD||c===_e.USER_ASSET_PANEL||c===_e.USER_ASSET_CONTEXT_MENU})).size,i=new Set(o.filter(x=>{const c=L.get(t,x)?.importType;return c===_e.IMAGE_GENERATE_MODAL||c===_e.AI_IMAGE_AUTO_INSERTION_PANEL||c===_e.AI_IMAGE_AUTO_INSERTION_STT_MODAL||c===_e.CONTEXT_MENU||c===_e.TTV||c===_e.IMAGE_REPLACE_MODAL||c===_e.IMAGE_GENERATE_MODAL_EDIT||c===_e.IMAGE_REPLACE_MODAL_EDIT})).size,s=new Set(o.filter(x=>{const c=L.get(t,x)?.importType;return c===_e.IMAGE_GENERATE_MODAL_EDIT||c===_e.IMAGE_REPLACE_MODAL_EDIT})).size;return{numImageInstances:r,numStockImageInstances:n,numUserImageInstances:a,numGenImageInstances:i,numGenEditImageInstances:s}},Tve=(e,t)=>
1188{const o=Object.values(e.deltas).flatMap(R=>R.ops?.flatMap(y=>y.attributes)).filter(Se),r=Y0e(e),n=K7(r);switch(t.textLanguageCountStat[n]++,!0){case r.length<=5:t.textLengthCountStat[5]++;break;case r.length<=10:t.textLengthCountStat[10]++;break;case r.length<=20:t.textLengthCountStat[20]++;break;case r.length>20:t.textLengthCountStat["20+"]++;break}const{xPos:a,yPos:i,width:s,height:x}=e,c=$t(Math.floor(i*3),0,2),l=$t(Math.floor((i+x)*3),0,2),d=$t(Math.floor(a*3),0,2),u=$t(Math.floor((a+s)*3),0,2);x0(c,l+1).forEach(R=>{x0(d,u+1).forEach(y=>{const v="position"+(3*R+y+1);t.positionCountStat[v]=t.positionCountStat[v]===void 0?1:t.positionCountStat[v]+1})});const p=$t(Math.floor((i+x/2)*3),0,2),f=$t(Math.floor((a+s/2)*3),0,2),E="position"+(3*p+f+1);t.centerPositionCountStat[E]=t.centerPositionCountStat[E]===void 0?1:t.centerPositionCountStat[E]+1;const T=Object.values(e.deltas).flatMap(R=>R.ops?.flatMap(y=>{if(y.insert!==`
1189`)return y.attributes?.size??tR}).filter(Se).map(y=>parseInt(y))),O=o.length===0?tR:Math.max(...T),S="fontSize"+O;return t.maxFontSizeCountStat[S]=t.maxFontSizeCountStat[S]===void 0?1:t.maxFontSizeCountStat[S]+1,o.length===0&&t.noStyleTextCount++,o.some(R=>R.bold===!0)&&t.boldTextCount++,o.some(R=>R.italic===!0)&&t.italicTextCount++,o.some(R=>"color"in R)&&t.coloredTextCount++,o.some(R=>"outline-color"in R)&&t.outlineTextCount++,o.some(R=>"background"in R)&&t.backgroundTextCount++,o.some(R=>"shadow-color"in R)&&t.shadowTextCount++,o.some(R=>"ruby-tag"in R)&&t.rubyAppliedTextCount++,o.some(R=>"letter-spacing"in R)&&t.letterSpacingAppliedTextCount++,o.some(R=>"line-height"in R)&&t.lineHeightAppliedTextCount++,new Set(T).size>=2&&t.fontSizeMixedTextCount++,/(\p{Emoji}|\p{Extended_Pictographic})/u.test(r)&&t.emojiTextboxCount++,t},Sve=(e,t)=>{const o=[1,2,3,4,5,6,7,8,9],r=["5","10","20","20+"],n=["-180","-90","0","90","180"],a=$e().getWebAssetsSync()?.content.filter(d=>d.tags.includes("ANIMATED")).map(d=>d.mediaId),i={fadeCount:0,flipCount:0,flipHighlightCount:0,flyCount:0,rotateCount:0,rollCount:0,focusCount:0,tadaCount:0,swingCount:0,shakeCount:0,rubberBandCount:0,heartBeatCount:0,popInCount:0,blinkCount:0,popCount:0,typingCount:0,movingCount:0};let s={numClipsWithText:0,numClipsWithCaptionAndText:0,textBoxCount:0,basicTextBoxCount:0,designedTextBoxCount:0,blingblingTextBoxCount:0,emojiTextboxCount:0,positionCountStat:Object.fromEntries(o.map(d=>["position"+d,0])),centerPositionCountStat:Object.fromEntries(o.map(d=>["position"+d,0])),maxFontSizeCountStat:Object.fromEntries(Jye.map(d=>["fontSize"+d,0])),textLanguageCountStat:Object.fromEntries(Object.values(rr).map(d=>[d,0])),textLengthCountStat:Object.fromEntries(r.map(d=>[d,0])),rotationDegreeCountStat:Object.fromEntries(n.map(d=>[d,0])),designedTextCountStat:{},boldTextCount:0,italicTextCount:0,noStyleTextCount:0,coloredTextCount:0,outlineTextCount:0,backgroundTextCount:0,shadowTextCount:0,rubyAppliedTextCount:0,letterSpacingAppliedTextCount:0,lineHeightAppliedTextCount:0,fontSizeMixedTextCount:0,clipTextBoxCount:0,wordTextBoxCount:0,toolbarImportCount:0,contextMenuImportCount:0,contextFloatingMenuImportCount:0,copyPasteImportCount:0,singleClipRangeTextboxCount:0,longRangeTextboxCount:0,clipsWithDesignedTextboxes:0,panelModifiedTextboxCount:0,animationTextCount:0,savedStylesApplyCount:0,webAppliedAnimationCounts:i};const x=[],c=[];e.forEach(d=>{const u=d.assetIds.map(S=>L.get(t,S)).filter(Se),p=u.filter(S=>!x.includes(S)),f=new Set(d.words.flatMap(S=>S.assetIds).map(S=>L.get(t,S)).filter(Se)),E=[...p,...f];(u.length>0||f.size>0)&&(s.numClipsWithText++,(Hn(d,!0,0,!0).length>0||Hn(d,!0,1,!0).length>0)&&s.numClipsWithCaptionAndText++),s.textBoxCount+=E.length,s.clipTextBoxCount+=p.length,s.wordTextBoxCount+=f.size,E.forEach(S=>{switch(S.importType){case Yt.TEXTBOX_TOOLBAR:s.toolbarImportCount++;break;case Yt.CONTEXT_FLOATING_MENU:s.contextFloatingMenuImportCount++;break;case Yt.CONTEXT_MENU:s.contextMenuImportCount++;break;case Yt.COPY_AND_PASTE:s.copyPasteImportCount++;break}const R=S.rotation<0?S.rotation%360+360:S.rotation%360;switch(!0){case(180<R&&R<270):s.rotationDegreeCountStat[n[0]]++;break;case(270<=R&&R<360):s.rotationDegreeCountStat[n[1]]++;break;case R===0:s.rotationDegreeCountStat[n[2]]++;break;case(0<R&&R<=90):s.rotationDegreeCountStat[n[3]]++;break;case(90<R&&R<=180):s.rotationDegreeCountStat[n[4]]++;break}S.mediaId===Ao?s.basicTextBoxCount++:S.mediaId!==void 0&&(s.designedTextBoxCount++,a&&a.includes(S.mediaId)&&s.blingblingTextBoxCount++),S.stats?.styledInPanel&&s.panelModifiedTextboxCount++,S.assetEffectInfo!==void 0&&(s.animationTextCount++,s.webAppliedAnimationCounts=qv(S.assetEffectInfo?.type,s.webAppliedAnimationCounts)),s=Tve(S,s)}),x.push(...p),c.push(...d.assetIds),E.filter(S=>
1189S.mediaId!==void 0&&S.mediaId!==Ao).forEach(S=>{s.designedTextCountStat[S.mediaId]=(s.designedTextCountStat[S.mediaId]||0)+1}),[...u,...f].some(S=>S.mediaId!==void 0&&S.mediaId!==Ao)&&s.clipsWithDesignedTextboxes++});const l={};return c.forEach(d=>{l[d]?l[d]+=1:l[d]=1}),Object.values(l).forEach(d=>{d===1?s.singleClipRangeTextboxCount++:d>e.length/2&&s.longRangeTextboxCount++}),s.savedStylesApplyCount=Yo().getSavedStylesApplyCount(),s},Ove=(e,t)=>{const o=e.map(W=>{const Q=W.assetIds,j=W.words.flatMap(q=>q.assetIds);return Hc([...Q,...j]).filter(q=>L.get(t,q)!==void 0)}).filter(W=>W.length>0),r=Hc(o.flat()).length,n=e.length,a=o.length,i=$n(o.length/e.length,3),s={},x={};o.forEach(W=>{W.forEach(Q=>{const j=L.get(t,Q);if(j===void 0)return;const{mediaId:$,pose:q}=j,H=$;s[H]?s[H]++:s[H]=1;const U=q.isPreset?q.presetType:"CUSTOM";x[U]?x[U]++:x[U]=1})});const c=Object.keys(s),l=c.length,d=c.filter(W=>W.startsWith(Lb)).length,u=l-d,p=o.map(W=>W.length);let f=p[0],E=p[0],T=0,O=0,S=0;const R={};p.forEach(W=>{f=Math.max(f,W),E=Math.min(E,W),T+=W,R[W]===void 0&&(R[W]=0),R[W]++,S<R[W]&&(S=R[W],O=W)});const y=parseFloat((T/p.length).toFixed(2)),v=R[1]??0,w=R[2]??0,N=(R[3]??0)+(R[4]??0),M=p.length-v-w-N,k={usermadeRandom2D:0,usermadeRandom3D:0,usermadeRandomRealistic:0,usermade2D:0,usermade3D:0,usermadeRealistic:0,vrew2D:0,vrew3D:0,vrewRealistic:0},F=$e().getCharacterInfo()?.charTagMap??{},G=F?.["2D"]??[],B=F?.["3D"]??[];return c.forEach(W=>{const Q=W.startsWith(Lb),j=G.includes(W)?"2D":B.includes(W)?"3D":"realistic";if(Q){switch(j){case"2D":k.usermade2D++;break;case"3D":k.usermade3D++;break;case"realistic":k.usermadeRealistic++}return}switch(j){case"2D":k.vrew2D++;break;case"3D":k.vrew3D++;break;case"realistic":k.vrewRealistic++}}),{numTotalCharacters:r,numUniqueCharacters:l,numUniqueUsermadeCharacters:d,numUniqueVrewCharacters:u,numExportedClips:n,numCharacterClips:a,characterClipRatio:i,exportedCharacterList:c,numClipsPerCharacter:s,numClipsPerPose:x,numCharacterPerClipMax:f,numCharacterPerClipMin:E,numCharacterPerClipMode:O,numCharacterPerClipMean:y,numClipOneCharacter:v,numClipTwoCharacters:w,numClipThreeFourCharacters:N,numClipManyCharacters:M,numUniqueCharacterDimension:k}},Cve=(e,t)=>{const o=Yo().videoRemixInfos,r=e.reduce((s,x)=>{const c=L.get(o,x.id);return c&&s.push(c),s},[]),n=Bg(t),a=r.length>0,i=e.length===r.length;return{videoRemixInfos:r,exportScenesDuration:n,numExportClips:t.length,exportWithRemixScene:a,hasOnlyRemixScene:i}},Rve=(e,t,o,r)=>{const n=c=>c.type===ze.TTSEffect?"EFFECT":c.type===ze.TTSDubbing?"DUBBING":null,a=(c,l)=>{if(l?Kx(l,r):void 0)return"TTS_CLIP";const u=c?Hs(c):void 0,p=l?Hs(l):void 0;return!u&&!p||ia(u?.mediaId)&&ia(p?.mediaId)?"EMPTY_CLIP":u&&Zr(u)||p&&Zr(p)?"USER_SOURCE":(h("va.ts").warn("Unknown source type on getTTSExportStats: "+c+" or "+l),null)},i=Array.from(Gw(e,t,o)).map(c=>Kx(c,r)).filter(Se).map(c=>({type:"CLIP",speaker:c.speaker,clipType:"TTS_CLIP"})),s=e.flatMap(c=>c.words).flatMap(c=>c.assetIds.map(l=>{const d=L.get(o,l);return!d||d.role!=="sub"?void 0:d.trackIds.map(p=>L.get(t,p)).find(p=>p!==void 0&&(qh(p)||dl(p)))}).filter(Se).map(l=>[c,l])),x=s.filter(([,c])=>s2(c)).map(([c,l])=>[c,l,Wg(l.mediaId,t)]).map(([c,l,d])=>{const u=n(l),{visualMediaId:p,audioMediaId:f}=ss(c,t,o),E=a(p,f);return!d||!E||!u||!d.ttsFileInfo?null:{type:u,speaker:d.ttsFileInfo.speaker,clipType:E}}).filter(ri);return[...i,...x]},Ave=(e,t,o)=>{const r=Array.from(Gw(e,t,o)).map(a=>Wg(a,t)).filter(Se).map(a=>a.ttsFileInfo.effect).reduce((a,i)=>{switch(i){case"metal":a.numClipWithRoomEffectMetal++;break;case"echo":a.numClipWithRoomEffectEcho++;break;case"railway":a.numClipWithRoomEffectRailway++;break;case"telephone":a.numClipWithRoomEffectTelephone++;break;case"radio":a.numClipWithRoomEffectRadio++;break}return a},{numClipWithRoomEffectMetal:0,numClipWithRoomEffectEcho:0,numClipWithRoomEffectRailway:0,numClipWithRoomEffectTelephone:0,numClipWithRoomEffectRadio:0}),n=Object.values(r).reduce((a,i)=>a+i,0);return{ttsVoiceEffectPayload:r,numClipWithRoomEffect:n}},yve=(e,t)=>{const o=e.flatMap(n=>n.assetIds);return new Set(o.filter(n=>
1189L.get(t,n)?.stockSource===ws.OPENMOJI)).size},vve=(e,t)=>{const o=e.flatMap(n=>n.assetIds);return new Set(o.filter(n=>L.get(t,n)?.stats?.isTransparent)).size},VD=e=>eo(e)?.sourceOrigin===tt.USER,wve=(e,t,o)=>{const r=Array.from(e.flatMap(s=>s.assetIds).reduce((s,x)=>s.add(x),new Set)),n=r.flatMap(s=>{const x=L.get(o,s);return!x||x.role!=="sub"?[]:x.trackIds.map(c=>L.get(t,c)).filter(Se)}).filter(ll),a=n.filter(s=>VD(s.mediaId)),i=n.filter(s=>!VD(s.mediaId));return{numBGM:a.length+i.length,numFreeBGM:i.length,numUserBGM:a.length,freeBGMList:Array.from(i).map(s=>s.mediaId)}},Nve=(e,t,o)=>{const r=e.length,n=e.filter(x=>x.assetIds.some(c=>{const l=L.get(o,c);return l?l.trackIds.some(d=>{const u=L.get(t,d);return u&&ll(u)}):!1})),a=n.length,i=e.reduce((x,c)=>x+Df(c),0),s=n.reduce((x,c)=>x+Df(c),0);return{bgmClipRatio:$n(a/(r||1),3),bgmClipDurationRatio:$n(s/(i||1),3),numBGMClips:a}},Pve=(e,t,o)=>{const r=new Set,n=new Set;for(const a of e)for(const i of a.words.flatMap(s=>s.assetIds)){const s=L.get(o,i);if(!s||s.role!=="sub")continue;const x=s.trackIds.map(c=>L.get(t,c)).filter(c=>c!==void 0&&Ky(c));for(const c of x){const{mediaId:l}=c;eo(l)?.sourceOrigin===tt.USER?r.add(l):n.add(l)}}return{numSoundFX:n.size+r.size,numFreeSoundFX:n.size,numUserSoundFX:r.size}},bve=(e,t,o)=>{const r=e.length,n=e.filter(i=>i.words.some(s=>s.assetIds.some(x=>{const c=L.get(o,x);return!c||c.role!=="sub"?!1:c.trackIds.some(l=>{const d=L.get(t,l);return d&&Ky(d)})}))),a=n.length;return{soundFXClipRatio:$n(a/(r||1),3),numSoundFXClips:a}},Lve=e=>e.reduce((t,o)=>o.markerId===void 0?t:t+1,0),Mve=e=>vt({0:0,1:0,2:0,3:0,4:0,5:0},o=>{for(const r of e){const n=r.markerId;if(n===void 0)continue;const a=L.get(o,n);a!==void 0&&L.set(o,n,a+1)}}),Dve=e=>e.reduce((t,o)=>{const r=o.words.findIndex(i=>i.playbackRate!==Un);if(r===-1)return t;const n=o.words.at(r);if(!n)return t;const a=ue(n.playbackRate,2);return{...t,[a]:(t[a]??0)+1}},{}),kve=e=>{const t=e.filter(RH).length;return{numPlaybackRateClips:t,playbackRateClipRatio:$n(t/e.length,3)}},Fve=e=>{const t=e.filter(o=>o.videoTransform).length;return{numVideoTransformClips:t,videoTransformClipRatio:$n(t/e.length,3)}},Uve=(e,t,o)=>{const r=e.filter(n=>pc(n,t,o)!==1).length;return{numVolumeChangedClips:r,volumeChangedClipRatio:$n(r/e.length,3)}},Vve=e=>e.reduce((t,o)=>{if(o.videoTransform===void 0||o.videoTransform.zoom===1)return t;const r=ue(o.videoTransform.zoom,2);return{...t,[r]:(t[r]??0)+1}},{}),Gve=e=>e.reduce((t,o)=>{if(o.videoTransform===void 0||o.videoTransform.rotation===0)return t;const r=Math.floor(o.videoTransform.rotation);return{...t,[r]:(t[r]??0)+1}},{}),Wve=e=>e.filter(t=>t.videoTransform?.xPos||t.videoTransform?.yPos).length,Hve=(e,t,o)=>e.reduce((r,n)=>{const a=L.get(o,n);if(!a||a.role!=="sub")return r;const i=a.trackIds.filter(s=>{const x=L.get(t,s);return x&&f0(x)}).length;return r+i},0),jve=(e,t,o)=>{const r=new Set;return e.forEach(n=>{const a=L.get(o,n);!a||a.role!=="sub"||a.trackIds.forEach(i=>{const s=L.get(t,i);!s||!f0(s)||r.add(yI(s))})}),Array.from(r)},zve=(e,t,o)=>{const r=Hc([...e.flatMap(i=>i.assetIds),...e.flatMap(i=>i.words.flatMap(s=>s.assetIds))]),n=Hve(r,t,o),a=jve(r,t,o);return{numShapes:n,usedShapeKeys:a}},Yve=(e,t,o,r)=>{const n=i=>i.backgroundId!==void 0,a=i=>Hpe(i,o,r)||!jpe(cr(he.INIT),cr(t),i.videoTransform);return e.reduce((i,s)=>{const x=n(s)?1:0,c=a(s)?1:0;return{numClipColorApplicableClips:i.numClipColorApplicableClips+c,numClipColorAppliedClips:i.numClipColorAppliedClips+x,numClipColorApplicableAndAppliedClips:i.numClipColorApplicableAndAppliedClips+c*x}},{numClipColorApplicableClips:0,numClipColorAppliedClips:0,numClipColorApplicableAndAppliedClips:0})},Bve=(e,t,o)=>{const r=Hc([...e.flatMap(i=>i.assetIds),...e.flatMap(i=>i.words.flatMap(s=>s.assetIds))]);let n=0,a=0;return r.forEach(i=>{const s=L.get(o,i);!s||s.role!=="sub"||s.trackIds.map(x=>L.get(t,x)).forEach(x=>{if(!x||!Tg(x))return;oa(x.mediaId)?.sourceOrigin===tt.USER?a++:n++})}),{numCharacters:n,numUserCharacters:a}},Kve=(e,t,o)=>e.reduce((r,n)=>{const a=n.words.flatMap(i=>i.assetIds.flatMap(s=>{const x=L.get(o,s);return!x||x.role!=="sub"?[]:x.trackIds.filter(c=>{const l=L.get(t,c);return l&&qh(l)})}));return r+a.length},0),Xve=(e,t)=>
1189{const o=e.reduce((y,v)=>[...y,...v.assetIds],[]),r=e.flatMap(y=>y.words).reduce((y,v)=>[...y,...v.assetIds],[]),n=[...o,...r],a={contain:0,cut:0,cover:0},i={context:0,floating:0};let s=0,x=0,c=0,l=0,d=0,u=0,p=0,f=0,E={fadeCount:0,flipCount:0,flipHighlightCount:0,flyCount:0,rotateCount:0,rollCount:0,focusCount:0,tadaCount:0,swingCount:0,shakeCount:0,rubberBandCount:0,heartBeatCount:0,popInCount:0,blinkCount:0,popCount:0,typingCount:0,movingCount:0},T=0,O=0;const S={[_e.UNKNOWN]:0,[_e.MODAL_UPLOAD]:0,[_e.PANEL_UPLOAD]:0,[_e.STOCK_IMAGE]:0,[_e.SYSTEM_CLIPBOARD]:0,[_e.CONTEXT_FLOATING_MENU]:0,[_e.STOCK_CONTEXT_FLOATING_MENU]:0,[_e.DRAG_AND_DROP]:0,[_e.DRAG_AND_DROP_MULTIPLE]:0,[_e.BETWEEN_CLIP_CONTEXT_MENU]:0,[_e.COPY_AND_PASTE]:0,[_e.USER_ASSET_PANEL]:0,[_e.USER_ASSET_CONTEXT_MENU]:0,[_e.IMAGE_GENERATE_MODAL]:0,[_e.IMAGE_GENERATE_MODAL_STOCK]:0,[_e.IMAGE_GENERATE_MODAL_EDIT]:0,[_e.IMAGE_REPLACE_MODAL]:0,[_e.IMAGE_REPLACE_MODAL_STOCK]:0,[_e.IMAGE_REPLACE_MODAL_EDIT]:0,[_e.AI_IMAGE_AUTO_INSERTION_PANEL]:0,[_e.AI_IMAGE_AUTO_INSERTION_STT_MODAL]:0,[_e.CONTEXT_MENU]:0,[_e.FRAMEPACK]:0,[_e.TTV]:0,[_e.AGENT]:0,[_e.AI_STYLIZED_CAPTION]:0},R={};return n.forEach(y=>{if(R[y])return;const v=L.get(t,y);v&&(s+=1,R[y]=v,S[v.importType]+=1,o.includes(y)?x+=1:c+=1,(v.width===1||v.height===1)&&(l+=1),v.stats?.fillType&&(a[v.stats.fillType]+=1),v.stats?.fillMenu&&(i[v.stats.fillMenu]+=1),v.kenburnsAnimationInfo!==void 0&&(u+=1),v.assetEffectInfo!==void 0&&(p+=1,E=qv(v.assetEffectInfo?.type,E)),v.stats?.isRemoveBackground&&(f+=1),d+=v.stats?.rearrangeCount??0,fR(v.editInfo?.crop)&&(T+=1),fR(v.editInfo?.crop)&&v.stats?.isRemoveBackground&&(O+=1))}),{imageInfo:S,imageCount:s,clipImageCount:x,wordImageCount:c,filledImageCount:l,imageFillCount:a,imageFillMenuCount:i,imageRearrangeCount:d,imageKenburnsCount:u,imageAnimationsCount:p,imageAppliedAnimationCounts:E,imageCropCount:T,imageRemoveBackgroundCount:f,imageRemoveBackgroundWithCropCount:O}},Jve=e=>Object.values(e).filter(t=>t.stats?.isImportedByNewClipOption).length,qve=(e,t,o,r)=>{const n=Yo().lastAppliedFramePack,a=Yo().isAIWritingUsed,i=Yo().ttvCaptionOptions,s=i?{ttvOptionCaptionLength:i.length,ttvOptionCaptionPosition:i.position,ttvOptionCaptionAutoAnimation:i.autoAnimation}:{},x=Yo().projectStartMode;return{numSources:pse().length,duration:dH(e)/60,originalNumClips:t.length,numClips:e.length,videoLock:o?"lock":"unlock",didTranslationOccurInProject:r?"O":"X",projectId:sP(se().getProjectId()),isProjectSaved:se().isProjectSaved()?"saved":"not-saved",startMode:x===Ei.DRAG_AND_DROP?Ei.VIDEO_AUDIO:x,videoAudioModeDetail:x===Ei.VIDEO_AUDIO||x===Ei.DRAG_AND_DROP?x:"NONE",cumulativeFramePackApplyCount:Yo().cumulativeFramePackApplyCount,lastAppliedFramePack:n,ratioChangedByFramePack:Yo().ratioChangedByFramePack,usedFramePackType:n===void 0?"none":ei().isStockFramePack(n)?"free":"user",cumulativeTemplateApplyCount:Yo().cumulativeTemplateApplyCount,lastAppliedTemplateName:Yo().lastAppliedTemplateName,isAIWritingUsed:a,aiWritingMode:a?Yo().aiWritingMode:"none",lastUsedWritingModel:a?Yo().lastUsedWritingModel:"none",videoStyleTag:Yo().videoStyleTag,...s}},Qve=(e,t)=>{const o=e?t.filter(r=>r.dirty.caption).length:0;return{numCaptionEditedClips:o,captionEditedClipRatio:$n(o/t.length,3)}},Zve=e=>e.filter(t=>t.dirty.video||t.dirty.blankDeleted).length,$ve=(e,t)=>{const o=t.filter(r=>Hn(r,Ar(e),0).trim().length>0).length;return{numClipsWithCaption:o,clipsWithCaptionRatio:$n(o/t.length,3)}},ewe=(e,t)=>{let o=0;const r=gv(e,t);r.forEach(x=>{const{fontName:c,weight:l}=zc(x);hv(c,l)&&o++});const n=r.length-o,a=n+o;return{numSystemFonts:n,numFreeFonts:o,isFreeFontUsed:o===0?"X":"O",numFonts:a,isSystemFontUsed:n===0?"X":"O"}},twe=(e,t,o)=>{const r=new Set,n=new Set,a=new Set,i=new Set,s=new Set,x=new Set;let c=0;const l=u=>{const p=eo(u.mediaId)?.sourceOrigin;if(p)switch(fR(u.editInfo?.crop)&&(c+=1),p){case tt.USER:a.add(u.mediaId);return;case tt.VREW_RESOURCE:i.add(u.mediaId);return;case tt.AI_GENERATED:h("va.ts").warn("AI generated video found: "+u.mediaId.slice(0,8)+", not expected.");return}},d=u=>{const p=L.get(o,u);return p?.role!=="sub"?null:p?.trackIds.map(E=>L.get(t,E)).filter(Se)?.find(E=>mn(E))??null};return e.forEach(u=>
1189{u.assetIds.map(d).filter(ri).forEach(p=>{s.add(u.id),r.add(p.mediaId),l(p)}),u.words.forEach(p=>{p.assetIds.map(d).filter(ri).forEach(f=>{x.add(p.id),n.add(f.mediaId),l(f)})})}),{userAssetVideoCount:a.size,freeAssetVideoCount:i.size,numAssetVideoClip:s.size,numAssetVideoWord:x.size,numClipRangeAssetVideo:r.size,numWordRangeAssetVideo:n.size,videoCropCount:c}},owe=(e,t,o)=>{const r=Hc([...e.flatMap(a=>a.assetIds),...e.flatMap(a=>a.assetIds)]);return Hc(r.flatMap(a=>{const i=L.get(o,a);return i?i?.trackIds.map(s=>{const x=L.get(t,s);if(x&&xr(x)&&K4(x))return x.stats?.sourceFramePackId}).filter(Se):[]})).length},rwe=(e,t,o)=>{const r=Hc([...e.flatMap(a=>a.assetIds),...e.flatMap(a=>a.words.flatMap(i=>i.assetIds))]);return Hc(r.flatMap(a=>{const i=L.get(o,a);return i?i.trackIds.map(s=>{const x=L.get(t,s);if(x&&rG(x))return x.stats?.sourceTemplateName}).filter(Se):[]})).length},nwe=e=>{let t=0,o=0,r={fadeCount:0,flipCount:0,flipHighlightCount:0,flyCount:0,rotateCount:0,rollCount:0,focusCount:0,tadaCount:0,swingCount:0,shakeCount:0,rubberBandCount:0,heartBeatCount:0,popInCount:0,blinkCount:0,popCount:0,typingCount:0,movingCount:0};return e.forEach(n=>{n.captions.forEach(a=>{wt().isEmpty(a.text)||(t++,a.style?.assetEffectInfo&&(o++,r=qv(a.style.assetEffectInfo.type,r)))})}),{captionCount:t,captionAnimationsCount:o,captionAppliedAnimationCounts:r}},awe=()=>Yo().clientLinebreakExecuteCount,iwe=e=>e.reduce((t,o)=>t+o.fileSize,0),swe=(e,t,o,r,n,a,i,s,x,c,l,d,u,p,f)=>{const E={},T={},O={};let S;for(const[AX,yX]of Object.entries(p)){const MS=Je(AX),vX=yX.trackIds.map(Xs=>L.get(u,Xs));for(const Xs of vX)Xs&&(Gn(Xs)?L.set(E,MS,Xs):Wn(Xs)?L.set(T,MS,Xs):Tg(Xs)?L.set(O,MS,Xs):Rr(Xs)&&(S=Xs))}const{captionCount:R,captionAnimationsCount:y,captionAppliedAnimationCounts:v}=nwe(e),w=uve(e,E),N=S!==void 0,{numCaptionEditedClips:M,captionEditedClipRatio:k}=Qve(o,e),{numClipsWithCaption:F,clipsWithCaptionRatio:G}=$ve(r,e),{clipCaptionSettingCount:B,clipCaptionSettingUniqueCount:W,clipsWithCaptionSettingRatio:Q}=mve(e),{numSystemFonts:j,numFreeFonts:$,isFreeFontUsed:q,numFonts:H,isSystemFontUsed:U}=ewe(e,n),te=hve(e,u,p),{numImageInstances:ne,numStockImageInstances:oe,numUserImageInstances:re,numGenImageInstances:ge,numGenEditImageInstances:fe}=Ive(e,E),ve=Sve(e,T),yt=yve(e,E),Le=vve(e,E),{numBGM:We,numFreeBGM:kt,numUserBGM:bt,freeBGMList:Jt}=wve(e,u,p),{bgmClipRatio:Ft,bgmClipDurationRatio:Pe,numBGMClips:_t}=Nve(e,u,p),{numFreeSoundFX:No,numUserSoundFX:ko,numSoundFX:dt}=Pve(e,u,p),{numSoundFXClips:vr,soundFXClipRatio:ln}=bve(e,u,p),Qo=Lve(e),li=Mve(e),Sn=Dve(e),{numPlaybackRateClips:mr,playbackRateClipRatio:Wi}=kve(e),{numVideoTransformClips:dr,videoTransformClipRatio:Hi}=Fve(e),ji=Vve(e),xp=Gve(e),{numVolumeChangedClips:cp,volumeChangedClipRatio:cc}=Uve(e,u,p),Ld=Wve(e),{imageInfo:lp,imageCount:dp,clipImageCount:up,wordImageCount:pp,filledImageCount:RS,imageFillCount:v_,imageFillMenuCount:lc,imageRearrangeCount:Md,imageKenburnsCount:AS,imageAnimationsCount:yS,imageAppliedAnimationCounts:w_,imageCropCount:vS,imageRemoveBackgroundCount:wS,imageRemoveBackgroundWithCropCount:NS}=Xve(e,E),N_=Jve(E),P_=Twe(i),{userAssetVideoCount:fp,freeAssetVideoCount:PS,numAssetVideoClip:b_,numAssetVideoWord:Dd,numClipRangeAssetVideo:bS,numWordRangeAssetVideo:mb,videoCropCount:Rl}=twe(e,u,p),{numShapes:gp,usedShapeKeys:_p}=zve(e,u,p),L_=Kve(e,u,p),{ttsVoiceEffectPayload:M_,numClipWithRoomEffect:D_}=Ave(e,u,p),{numCharacters:LS,numUserCharacters:ZK}=Bve(e,u,p),{numClipColorApplicableClips:$K,numClipColorAppliedClips:eX,numClipColorApplicableAndAppliedClips:tX}=Yve(e,i,u,p),oX=Ove(e,O),hb=Rve(e,u,p,l),{numClipTTSCount:rX,numEffectTTSCount:nX,numDubbingTTSCount:aX,numUserTTSClipCount:iX,numUserTTSEffectCount:sX,numUserTTSDubbingCount:xX,numUserTTSSpeakerCount:cX,numCharacteristicTTSClipCount:lX,numCharacteristicTTSEffectCount:dX,numCharacteristicTTSDubbingCount:uX,clipTTSCountRatio:pX,effectTTSCountRatio:fX,dubbingTTSCountRatio:gX,userTTSClipCountRatio:_X,userTTSEffectCountRatio:EX,userTTSDubbingCountRatio:mX}=fve(hb),hX=owe(e,u,p),IX=rwe(e,u,p),TX=Cve(t,e),SX=hwe(x),OX=Iwe(e),CX=Swe(e,u,p,f),RX=Owe(e,u,p);return{duration:dH(e)/60,numClips:e.length,numClipsWithImage:w,isVrewLogoUsed:N,numVideoEditedClips:Zve(e),numCaptionEditedClips:M,captionEditedClipRatio:k,numScenes:t.length,numClipsWithCaption:F,clipsWithCaptionRatio:G,numClipsWithTTS:pve(e,u,p,l),numClipTTSCount:rX,clipTTSCountRatio:pX,numEffectTTSCount:nX,effectTTSCountRatio:fX,numDubbingTTSCount:aX,dubbingTTSCountRatio:gX,numUserTTSClipCount:iX,userTTSClipCountRatio:_X,numUserTTSEffectCount:sX,userTTSEffectCountRatio:EX,numUserTTSDubbingCount:xX,userTTSDubbingCountRatio:mX,numUserTTSSpeakerCount:cX,numCharacteristicTTSClipCount:lX,numCharacteristicTTSEffectCount:dX,numCharacteristicTTSDubbingCount:uX,numClipsWithMultipleTTSVoices:gve(e,u,p,l),numSpacerCount:_ve(e),numFreezeCount:Eve(e),numClipsWithCaptionSetting:B,numUniqueCaptionSetting:W,clipsWithCaptionSettingRatio:Q,totalBlankDuration:te,numImageInstances:ne,numStockImageInstances:oe,numUserImageInstances:re,numGenImageInstances:ge,numGenEditImageInstances:fe,numMarkers:Qo,numMarkerClipsCount:li,playbackRateCount:Sn,imageInfo:lp,numPlaybackRateClips:mr,playbackRateClipRatio:Wi,numVideoTransformClips:dr,videoTransformClipRatio:Hi,numPositionedClips:Ld,zoomCount:ji,rotationCount:xp,imageCount:dp,clipImageCount:up,wordImageCount:pp,filledImageCount:RS,imageFillCount:v_,imageFillMenuCount:lc,imageRearrangeCount:Md,imageOpenmojiCount:yt,imageTransparentCount:Le,imageKenburnsCount:AS,numBGM:We,numBGMClips:_t,numFreeBGM:kt,numUserBGM:bt,freeBGMList:Jt,bgmClipRatio:Ft,bgmClipDurationRatio:Pe,numSystemFonts:j,numFreeFonts:$,numFonts:H,isFreeFontUsed:q,isSystemFontUsed:U,webAssetExportStats:ve,elapsed:a,numImageFromNewClipOptions:N_,numVolumeChangedCl
1189ips:cp,volumeChangedClipRatio:cc,videoRatioString:P_,numFreeSoundFX:No,numUserSoundFX:ko,numSoundFX:dt,numSoundFXClips:vr,soundFXClipRatio:ln,userAssetVideoCount:fp,freeAssetVideoCount:PS,numAssetVideoClip:b_,numAssetVideoWord:Dd,numClipRangeAssetVideo:bS,numWordRangeAssetVideo:mb,globalVideoTransform:s,videoRatio:i,numShapes:gp,usedShapeKeys:_p,numTTSEffects:L_,imageAnimationsCount:yS,numCharacters:LS,numUserCharacters:ZK,imageAppliedAnimationCounts:w_,imageRemoveBackgroundCount:wS,imageRemoveBackgroundWithCropCount:NS,numClipColorApplicableClips:$K,numClipColorAppliedClips:eX,numClipColorApplicableAndAppliedClips:tX,characterAssetExportStats:oX,ttsExportStats:hb,uniqueFramePackIdsInAssets:hX,uniqueTemplateNamesInAssets:IX,videoRemixExportStats:TX,ttsVoiceEffectPayload:M_,numClipWithRoomEffect:D_,vcloudExportStats:SX,captionCount:R,captionAnimationsCount:y,captionAppliedAnimationCounts:v,clientLinebreakExecuteCount:awe(),imageCropCount:vS,videoCropCount:Rl,transitionClipCount:OX,denoisedSourceCount:CX,numOverdubWords:RX,projectType:c,totalProjectMediaSize:iwe(d)}},xwe=e=>{const t=G5(e),o=zye(e),r=Yye(e);return{viewMode:t,scriptViewNewline:o,scriptViewShowAssets:r}},cwe=(e,t,o)=>{const r=JSON.stringify({exportId:e.exportId,exportType:e.outputType,numSources:e.project.numSources,totalBlankDuration:e.export.totalBlankDuration,didEditCuts:t.didEditCuts?"1":"0",numProjectClips:e.project.numClips,numBGMClips:e.export.numBGMClips,numFreeBGM:e.export.numFreeBGM,numUserBGM:e.export.numUserBGM,numBGM:e.export.numBGM,freeBGMList:e.export.freeBGMList.length>0?JSON.stringify(e.export.freeBGMList):void 0,bgmClipRatio:e.export.bgmClipRatio,bgmClipDurationRatio:e.export.bgmClipDurationRatio});I().event(m.VA_EXPORT,g.VA_BGM_INFO,o,void 0,r)},lwe=(e,t,o)=>{const r=JSON.stringify({exportId:e.exportId,exportType:e.outputType,numSources:e.project.numSources,totalBlankDuration:e.export.totalBlankDuration,didEditCuts:t.didEditCuts?"1":"0",numProjectClips:e.project.numClips,numSoundFXClips:e.export.numSoundFXClips,numFreeSoundFX:e.export.numFreeSoundFX,numUserSoundFX:e.export.numUserSoundFX,numSoundFX:e.export.numSoundFX,soundFXClipRatio:e.export.soundFXClipRatio});I().event(m.VA_EXPORT,g.VA_SOUNDFX_INFO,o,void 0,r)},dwe=e=>e.reduce((t,o)=>{const r=bw(o.speaker.name,o.speaker.provider),n=t.get(r);return t.set(r,{count:n?n.count+1:1,lang:o.speaker.lang,provider:o.speaker.provider}),t},new Map),H5=e=>{const t=e.length,o=dwe(e),r=new Set([...o.values()].map(l=>l.lang)).size,n=[...o.entries()].sort((l,d)=>d[1].count-l[1].count).at(0),a=Object.fromEntries([...o.entries()].map(([l,{count:d}])=>[l,d])),i=Object.fromEntries([...o.entries()].reduce((l,[,{provider:d}])=>{const u=l.get(d);return l.set(d,u?u+1:1),l},new Map)),s=e.filter(l=>l.type==="DUBBING"&&l.clipType==="USER_SOURCE").length,x=e.filter(l=>l.type==="DUBBING"&&l.clipType==="TTS_CLIP").length,c=e.filter(l=>l.type==="DUBBING"&&l.clipType==="EMPTY_CLIP").length;return{numTotalTTS:t,numTotalSpeakers:o.size,numTotalSpeakerLangs:r,mostUsedSpeaker:n?n[0]:null,mostSpeakerRatio:n&&t!==0?ue(n[1].count/t,2):null,countsPerSpeaker:a,countsPerProvider:i,numDubbingOnSource:s,numDubbingOnTTS:x,numDubbingOnEmptyClip:c}},uwe=(e,t)=>{const{ttsExportStats:o,ttsVoiceEffectPayload:r}=e.export,{numTotalTTS:n,numTotalSpeakers:a,numTotalSpeakerLangs:i,mostUsedSpeaker:s,mostSpeakerRatio:x,countsPerSpeaker:c,countsPerProvider:l,numDubbingOnSource:d,numDubbingOnTTS:u,numDubbingOnEmptyClip:p}=H5(o),f=JSON.stringify({exportId:e.exportId,outputType:e.outputType,numTotalSpeakers:a,numTotalSpeakerLangs:i,mostUsedSpeaker:s,mostSpeakerRatio:x,numTotalTTS:n,countsPerSpeaker:c,countsPerProvider:l,numTTSClips:e.export.numClipsWithTTS,numClipTTSCount:e.export.numClipTTSCount,clipTTSCountRatio:e.export.clipTTSCountRatio,numEffectTTSCount:e.export.numEffectTTSCount,effectTTSCountRatio:e.export.effectTTSCountRatio,numDubbingTTSCount:e.export.numDubbingTTSCount,dubbingTTSCountRatio:e.export.dubbingTTSCountRatio,numClipMultipleTTSVoicesCount:e.export.numClipsWithMultipleTTSVoices,numDubbingOnSource:d,numDubbingOnTTS:u,numDubbingOnEmptyClip:p,numSpacerCount:e.export.numSpacerCount,startMode:e.project.startMode,videoAudioModeDetail
1189:e.project.videoAudioModeDetail,numClipsExported:e.export.numClips,numFreeImagesExported:e.export.numStockImageInstances,numUserImagesExported:e.export.numUserImageInstances,numFreeVideosExported:e.export.freeAssetVideoCount,numUserVideosExported:e.export.userAssetVideoCount,...r});I().event(m.VA_EXPORT,g.VA_TTS_INFO,t,void 0,f)},pwe=(e,t)=>{const{numSystemFonts:o,numFreeFonts:r}=e.export,n=JSON.stringify({exportId:e.exportId,isFreeFontUsed:r===0?"0":"1",exportType:e.outputType,numFonts:o+r,numFreeFonts:r,numSystemFonts:o,isSystemFontUsed:o===0?"0":"1"});I().event(m.VA_EXPORT,g.VA_FONT_INFO,t,void 0,n)},fwe=(e,t)=>{const o=e.export.vcloudExportStats,{vCloudUploadCounts:r,useVCloudProject:n}=o,a=JSON.stringify({exportId:e.exportId,exportType:e.outputType,vCloudUploadCounts:r,useVCloudProject:n});I().event(m.VA_EXPORT,g.VA_VCLOUD_INFO,t,void 0,a)},gwe=(e,t)=>{const o=e.export.videoRemixExportStats,{videoRemixInfos:r,exportScenesDuration:n,numExportClips:a,exportWithRemixScene:i,hasOnlyRemixScene:s}=o;let x;const c={exportId:e.exportId,exportWithRemixScene:i,startMode:e.project.startMode,videoAudioModeDetail:e.project.videoAudioModeDetail,lang:e.captionLanguage,exportType:e.outputType,exportScenesDuration:n,numExportClips:a,selectedVideoRatio:e.export.videoRatioString};switch(r.length){case 0:x=JSON.stringify({...c});break;case 1:{const{type:l,sourceType:d,sourceSceneDuration:u,numSourceSceneClips:p,resultSceneDuration:f,numResultSceneClips:E}=r[0];x=JSON.stringify({...c,type:l,sourceType:d,sourceSceneDuration:u,numSourceSceneClips:p,resultSceneDuration:f,numResultSceneClips:E,hasOnlyRemixScene:s});break}default:x=JSON.stringify({...c,type:"mixed",hasOnlyRemixScene:s});break}I().event(m.VA_EXPORT,g.VA_VIDEO_REMIX,t,void 0,x)},Mxt=async(e,t)=>{if(se().isDemo()||!at())return;const{videoAudioMetaInfo:o,fileSize:r}=e[0],{videoInfo:n,presumedDevice:a,duration:i}=o;if(!n)return;const{size:{width:s,height:x,rotation:c},codec:l,frameRate:d}=n,u=JSON.stringify({device:a??Kp.UNKNOWN,resolution:s+"x"+x,duration:i,fileSize:r,rotation:c??0,frameRate:d,codec:l,importMethod:t}),p=Ha();I().event(m.VA_IMPORT,g.VA_UNIVERSAL_IMPORT,p,void 0,u)},_we=(e,t)=>{const{numMarkerClipsCount:o}=e.export;let r=0,n=0;const a=Object.fromEntries(Object.entries(o).map(s=>{const x=s[0],c=s[1];return c>0&&(r++,n+=c),["marker"+x,c]})),i=JSON.stringify({exportId:e.exportId,...a,markerColors:r,markerClips:n});I().event(m.VA_EXPORT,g.VA_MARKER,t,void 0,i)},Ewe=(e,t,o)=>{const r=JSON.stringify({exportId:e.exportId,exportType:e.outputType,numSources:e.project.numSources,totalBlankDuration:e.export.totalBlankDuration,didEditCuts:t.didEditCuts?"1":"0",numProjectClips:e.project.numClips,numAssetVideoClip:e.export.numAssetVideoClip,userAssetVideoCount:e.export.userAssetVideoCount,freeAssetVideoCount:e.export.freeAssetVideoCount,numClipRangeAssetVideo:e.export.numClipRangeAssetVideo,numWordRangeAssetVideo:e.export.numWordRangeAssetVideo,videoCropCount:e.export.videoCropCount});I().event(m.VA_EXPORT,g.VA_VIDEO_INFO,o,void 0,r)},mwe=(e,t)=>{const o=JSON.stringify({exportId:e.exportId,exportType:e.outputType,numSources:e.project.numSources,numProjectClips:e.project.numClips,numClipsWithImage:e.export.numClipsWithImage,imageCount:e.export.imageCount,clipImageCount:e.export.clipImageCount,wordImageCount:e.export.wordImageCount,imageAnimationsCount:e.export.imageAnimationsCount,imageFadeCount:e.export.imageAppliedAnimationCounts.fadeCount,imageFlipCount:e.export.imageAppliedAnimationCounts.flipCount,imageFlipHighlightCount:e.export.imageAppliedAnimationCounts.flipHighlightCount,imageFlyCount:e.export.imageAppliedAnimationCounts.flyCount,imageRotateCount:e.export.imageAppliedAnimationCounts.rotateCount,imageRollCount:e.export.imageAppliedAnimationCounts.rollCount,imageFocusCount:e.export.imageAppliedAnimationCounts.focusCount,imageTadaCount:e.export.imageAppliedAnimationCounts.tadaCount,imageSwingCount:e.export.imageAppliedAnimationCounts.swingCount,imageShakeCount:e.export.imageAppliedAnimationCounts.shakeCount,imageRubberBandCount:e.export.imageAppliedAnimationCounts.rubberBandCount,imageHeartBeatCount:e.export.imageAppliedAnimationCounts.heartBeatCount,imagePopInCount:e.export.imageAppliedAnimationCounts.popInCount,imageBlinkCount:e.export.imageAppliedAnimationCounts.blinkCount,imagePopCount:e.export.imageAppliedAnimationCounts.popCount,numClipsWithText:e.exp
1189ort.webAssetExportStats.numClipsWithText,textCount:e.export.webAssetExportStats.textBoxCount,clipTextBoxCount:e.export.webAssetExportStats.clipTextBoxCount,wordTextBoxCount:e.export.webAssetExportStats.wordTextBoxCount,animationTextCount:e.export.webAssetExportStats.animationTextCount,textTypingCount:e.export.webAssetExportStats.webAppliedAnimationCounts.typingCount,textFadeCount:e.export.webAssetExportStats.webAppliedAnimationCounts.fadeCount,textFlipCount:e.export.webAssetExportStats.webAppliedAnimationCounts.flipCount,textFlipHighlightCount:e.export.webAssetExportStats.webAppliedAnimationCounts.flipHighlightCount,textFlyCount:e.export.webAssetExportStats.webAppliedAnimationCounts.flyCount,textRotateCount:e.export.webAssetExportStats.webAppliedAnimationCounts.rotateCount,textRollCount:e.export.webAssetExportStats.webAppliedAnimationCounts.rollCount,textFocusCount:e.export.webAssetExportStats.webAppliedAnimationCounts.focusCount,textTadaCount:e.export.webAssetExportStats.webAppliedAnimationCounts.tadaCount,textSwingCount:e.export.webAssetExportStats.webAppliedAnimationCounts.swingCount,textShakeCount:e.export.webAssetExportStats.webAppliedAnimationCounts.shakeCount,textRubberBandCount:e.export.webAssetExportStats.webAppliedAnimationCounts.rubberBandCount,textHeartBeatCount:e.export.webAssetExportStats.webAppliedAnimationCounts.heartBeatCount,textPopInCount:e.export.webAssetExportStats.webAppliedAnimationCounts.popInCount,textBlinkCount:e.export.webAssetExportStats.webAppliedAnimationCounts.blinkCount,textPopCount:e.export.webAssetExportStats.webAppliedAnimationCounts.popCount,captionCount:e.export.captionCount,captionAnimationsCount:e.export.captionAnimationsCount,captionTypingCount:e.export.captionAppliedAnimationCounts.typingCount,captionFadeCount:e.export.captionAppliedAnimationCounts.fadeCount,captionFlipCount:e.export.captionAppliedAnimationCounts.flipCount,captionFlipHighlightCount:e.export.captionAppliedAnimationCounts.flipHighlightCount,captionFlyCount:e.export.captionAppliedAnimationCounts.flyCount,captionRotateCount:e.export.captionAppliedAnimationCounts.rotateCount,captionRollCount:e.export.captionAppliedAnimationCounts.rollCount,captionFocusCount:e.export.captionAppliedAnimationCounts.focusCount,captionTadaCount:e.export.captionAppliedAnimationCounts.tadaCount,captionSwingCount:e.export.captionAppliedAnimationCounts.swingCount,captionShakeCount:e.export.captionAppliedAnimationCounts.shakeCount,captionRubberBandCount:e.export.captionAppliedAnimationCounts.rubberBandCount,captionHeartBeatCount:e.export.captionAppliedAnimationCounts.heartBeatCount,captionPopInCount:e.export.captionAppliedAnimationCounts.popInCount,captionBlinkCount:e.export.captionAppliedAnimationCounts.blinkCount,captionPopCount:e.export.captionAppliedAnimationCounts.popCount});I().event(m.VA_EXPORT,g.VA_ANIMATION_INFO,t,void 0,o)},hwe=e=>{const t=Lt().getVCloudProjectInfo(e);return t?{useVCloudProject:!0,vCloudUploadCounts:t.uploadCount}:{useVCloudProject:!1,vCloudUploadCounts:0}},Iwe=e=>e.map(t=>t.transitionModel?t.transitionModel.type:null).filter(ri).length,Twe=e=>{const t=P4(e);if(t==="original"){const n=1.3333333333333333,a=pN(),i=a<=.75+.01?"vertical":a<n-.01?"etc":"horizontal";return t+"_"+i}else return t},Swe=(e,t,o,r)=>{const n=new Set(Object.values(r)),a=Gw(e,t,o);return Array.from(a).filter(i=>n.has(i)).length},Owe=(e,t,o)=>e.reduce((r,n)=>r+n.words.filter(a=>PH(a,t,o)).length,0),ah=()=>({isEdited:!1,requestCount:0,responseCount:0,toolCallCount:0,toolErrorCount:0}),Cwe=e=>{if(!e)return ah();const t=ah();return{isEdited:e.isEdited??t.isEdited,requestCount:e.requestCount??t.requestCount,responseCount:e.responseCount??t.responseCount,toolCallCount:e.toolCallCount??t.toolCallCount,toolErrorCount:e.toolErrorCount??t.toolErrorCount}};class Rwe{wordCursorCount=da();wordSelectionCount=da();wordCorrectionCount=da();wordInsertCount=da();wordInsertCountExceptSide=da();clipCursorCount=0;projectStartMode=Ei.UNKNOWN;projectStartModeCache=void 0;printChange=!1;cumulativeFramePackApplyCount=0;lastAppliedFramePack=void 0;ratioChangedByFramePack=!1;cumulativeTemplateApplyCount=0;lastAppliedTemplateName=void 0;videoRemixInfos={};isAIWritingUsed=!1;aiWritingMode=void 0;lastUsedWritingModel=void 0;videoStyleTag=void 0;ttvCaptionOptions=void 0;sttLinebreakOptions=void 0;clientLinebreakExecuteCount=0;agentStats=ah();prevSelectedWordIds=[];saveInfo;savedStylesApplyCount=0;constructor(){this.saveInfo=iA()}shouldSendGA=t=>t===1||t%10===0;sumCountsByWordType=t=>Object.keys(t).reduce((r,n)=>r+t[n],0);updateWordCorrectionCount=t=>
1189{this.wordCorrectionCount[t]+=1,this.shouldSendGA(this.wordCorrectionCount[t])&&Hke(this.wordCorrectionCount[t],t),this.shouldSendGA(this.sumCountsByWordType(this.wordCorrectionCount))&&jke(this.sumCountsByWordType(this.wordCorrectionCount)),this.printChange&&h("statisticsManager.ts").info("word correct "+ru[t])};updateWordSelectionCount=t=>{this.wordSelectionCount[t]+=1,this.shouldSendGA(this.wordSelectionCount[t])&&Gke(this.wordSelectionCount[t],t),this.shouldSendGA(this.sumCountsByWordType(this.wordSelectionCount))&&Wke(this.sumCountsByWordType(this.wordSelectionCount)),this.printChange&&h("statisticsManager.ts").info("word select "+ru[t])};updateWordInsertCount=t=>{this.wordInsertCount[t]+=1,this.shouldSendGA(this.sumCountsByWordType(this.wordInsertCount))&&zke(this.sumCountsByWordType(this.wordInsertCount)),this.printChange&&h("statisticsManager.ts").info("word insert "+ru[t])};updateWordInsertCountExceptSide=t=>{this.wordInsertCountExceptSide[t]+=1,this.shouldSendGA(this.sumCountsByWordType(this.wordInsertCountExceptSide))&&Yke(this.sumCountsByWordType(this.wordInsertCountExceptSide)),this.printChange&&h("statisticsManager.ts").info("word insert except side "+ru[t])};updateClipCursorCount=()=>{this.clipCursorCount+=1,this.shouldSendGA(this.clipCursorCount)&&Bke(this.clipCursorCount),this.printChange&&h("statisticsManager.ts").info("clip cursor")};didWordSelectionChange=t=>this.prevSelectedWordIds.length!==t.length||this.prevSelectedWordIds.some((o,r)=>o!==t[r].id);updateCountFromMultipleWordSelection=t=>{this.didWordSelectionChange(t)&&t.forEach(o=>{!this.prevSelectedWordIds.includes(o.id)&&this.updateWordSelectionCount(o.type)}),this.prevSelectedWordIds=t.map(o=>o.id)};updateWordCountsWhenCursorChanged=(t,o,r,n)=>{if(t.globalPosition!==null&&o.length!==0){const a=d0(o,t.globalPosition).type;switch(t.cursorMode){case we.CORRECTING:{this.updateWordCorrectionCount(a);break}case we.INSERT_CURSOR:{if(n!==Bx.MOUSE||t.globalWordRange!==null)break;const i=CI(r,t.globalPosition);i!==0&&i!==r.words.length-1&&this.updateWordInsertCountExceptSide(a),this.updateWordInsertCount(a);break}case we.CLIP:{this.updateClipCursorCount();break}}this.updateCountFromMultipleWordSelection(t.globalWordRange!==null&&t.cursorMode===we.INSERT_CURSOR?nT(o,t.globalWordRange):[])}};updateProjectStartModeCache=t=>{this.projectStartModeCache=t};commitProjectStartMode=()=>{this.projectStartModeCache&&(this.projectStartMode=this.projectStartModeCache),this.projectStartModeCache=void 0};getProjectStartMode=()=>this.projectStartMode;updateFramePackApplyInfo=(t,o)=>{this.cumulativeFramePackApplyCount++,this.lastAppliedFramePack=t,o&&(this.ratioChangedByFramePack=!0)};updateTemplateApplyInfo=t=>{this.cumulativeTemplateApplyCount++,this.lastAppliedTemplateName=t};updateVideoRemixInfo=(t,o)=>{this.videoRemixInfos[t]=o};updateVideoStyleInfo=(t,o,r,n)=>{this.videoStyleTag=r,this.isAIWritingUsed=t,this.aiWritingMode=o,this.lastUsedWritingModel=rP[o],this.ttvCaptionOptions=n};toJson=t=>({wordCursorCount:this.wordCursorCount,wordSelectionCount:this.wordSelectionCount,wordCorrectionCount:this.wordCorrectionCount,projectStartMode:this.projectStartMode,saveInfo:Awe(t),savedStyleApplyCount:this.savedStylesApplyCount,cumulativeTemplateApplyCount:this.cumulativeFramePackApplyCount,lastAppliedTemplate:this.lastAppliedFramePack,ratioChangedByTemplate:this.ratioChangedByFramePack,videoRemixInfos:this.videoRemixInfos,isAIWritingUsed:this.isAIWritingUsed,aiWritingMode:this.aiWritingMode,lastUsedWritingModel:this.lastUsedWritingModel,videoStyleTag:this.videoStyleTag,ttvCaptionOptions:this.ttvCaptionOptions,sttLinebreakOptions:this.sttLinebreakOptions,clientLinebreakExecuteCount:this.clientLinebreakExecuteCount,agentStats:this.agentStats,cumulativeNewTemplateApplyCount:this.cumulativeTemplateApplyCount,lastAppliedNewTemplateName:this.lastAppliedTemplateName});resetFromJson=t=>{this.wordCursorCount=t.wordCursorCount??da(),this.wordSelectionCount=t.wordSelectionCount??da(),this.wordCorrectionCount=t.wordCorrectionCount??da(),this.projectStartMode=t.projectStartMode??Ei.UNKNOWN;const o=ywe(t.saveInfo);this.saveInfo={...o,loadCount:o.loadCount+1},this.savedStylesApplyCount=t.savedStyleApplyCount??0,this.cumulativeFramePackApplyCount=t.cumulativeTemplateApplyCount,this.lastAppliedFramePack=t.lastAppliedTemplate,this.ratioChangedByFramePack=t.ratioChangedByTemplate,this.videoRemixInfos=t.videoRemixInfos??{},this.isAIWritingUsed=t.isAIWritingUsed??!1,this.aiWritingMode=t.aiWritingMode,this.lastUsedWritingModel=t.lastUsedWritingModel,this.videoStyleTag=t.videoStyleTag,this.ttvCaptionOptions=t.ttvCaptionOptions?{...t.ttvCaptionOptions,isOn:t.ttvCaptionOptions.isOn??!0}:void 0,this.sttLinebreakOptions=t.sttLinebreakOptions,this.clientLinebreakExecuteCount=t.clientLinebreakExecuteCount??0,this.agentStats=Cwe(t.agentStats),this.cumulativeTemplateApplyCount=t.cumulativeNewTemplateApplyCount??0,this.lastAppliedTemplateName=t.lastAppliedNewTemplateName};reset=()=>{this.wordCursorCount=da(),this.wordSelectionCount=da(),this.wordCorrectionCount=da(),this.wordInsertCount=da(),this.wordInsertCountExceptSide=da(),this.clipCursorCount=0,this.prevSelectedWordIds=[],this.saveInfo=iA(),this.savedStylesApplyCount=0,this.cumulativeFramePackApplyCount=0,this.lastAppliedFramePack=void 0,this.ratioChangedByFramePack=!1,this.cumulativeTemplateApplyCount=0,this.lastAppliedTemplateName=void 0,this.videoRemixInfos={},this.isAIWritingUsed=!1,this.aiWritingMode=void 0,this.lastUsedWritingModel=void 0,this.videoStyleTag=void 0,this.ttvCaptionOptions=void 0,this.sttLinebreakOptions=void 0,this.clientLinebreakExecuteCount=0,this.agentStats=ah()};getLastSaveInfo=()=>this.saveInfo;updateSaveInfo=t=>this.saveInfo=t;getSavedStylesApplyCount=()=>this.savedStylesApplyCount;incSavedStylesApplyCount=()=>{this.savedStylesApplyCount++};incClientLinebreakExecuteCount=()=>{this.clientLinebreakExecuteCount++};setSttLinebreakOptions=(t,o)=>{this.sttLinebreakOptions={mode:t,maxLineLength:o}};markAgentEdited=()=>{this.agentStats.isEdited=!0};incAgentRequestCount=()=>{this.agentStats.requestCount++};incAgentResponseCount=()=>{this.agentStats.responseCount++};incToolCallCount=()=>{this.agentStats.toolCallCount++};incToolErrorCount=()=>{this.agentStats.toolErrorCount++}}let $O;const Yo=()=>(!$O&&($O=new Rwe),$O),Awe=e=>({created:e.created?{version:e.created.version,date:e.created.date,stage:e.created.stage}:void 0,updated:e.updated?{version:e.updated.version,date:e.updated.date,stage:e.updated.stage}:void 0,loadCount:e.loadCount,saveCount:e.saveCount}),ywe=e=>e?{created:e.created?{version:e.created.version,date:e.created.date,stage:e.created.stage}:void 0,updated:e.updated?{version:e.updated.version,date:e.updated.date,stage:e.updated.stage}:void 0,loadCount:e.loadCount,saveCount:e.saveCount}:iA(),vwe=180*1e3,wwe=10*1e3,H2=async(e,t)=>{const{vrewJson:o,blobs:r}=await _ye(e,t),{files:n,props:a,transcript:i}
1189=o,{blobs:s,extractedTexts:x,brokenMediaIds:c}=await lie.enrichFilesAndBlobs(n,r),l=n.map(p=>{const f=Be.fromFileJson(p,x);return c.has(p.mediaId)?{...f,broken:!0}:f}),d=xP(a.denoiseMap??{},l);return h("vrewfile.ts").info("[loadVrewFileData] fileInfos length: "+l.length),{files:l,globalClips:i.clips.map(p=>Be.fromClipJsonToGlobalClipModel(p)),sceneNames:i.sceneNames,translateInfo:i.translateInfo,props:{globalCaptionStyle:Be.fromGlobalCaptionStyleSettingJson(a.globalCaptionStyle),analyzeDate:a.analyzeDate,videoSize:a.videoSize,captionDisplayMode:a.captionDisplayMode||$1,baseAssetEntries:Be.fromAssetsJson(a.assets),trackEntries:mae(Be.fromTracksJson(a.tracks),Be.fromAssetsJson(o.props.assets)),overdubInfosMap:Be.fromOverdubInfosJson(a.overdubInfos),markerNames:a.markerNames,videoRatio:a.videoRatio,globalVideoTransform:a.globalVideoTransform??il,backgroundMap:a.backgroundMap,lastTTSSettings:Be.fromLastTTSSettingJson(a.lastTTSSettings),initProjectVideoSize:a.initProjectVideoSize,pronunciationDisplay:a.pronunciationDisplay,projectAudioLanguage:a.projectAudioLanguage,audioLanguagesMap:a.audioLanguagesMap,originalClips:a.originalClips.map(p=>Be.fromClipJsonToGlobalClipModel(p)),ttsClipInfosMap:Be.fromTtsClipInfosJson(a.ttsClipInfosMap),denoiseMap:d},blobs:s,comment:o.comment,projectId:o.projectId?o.projectId:qe.v4(),makerUid:o.makerUid,makerCid:o.makerCid,statistics:o.statistics}},xP=(e,t,o)=>{const r=new Map(t.map(i=>[i.mediaId,i])),n=o?.logging??!0,a=Object.entries(e).flatMap(([i,s])=>{const x=r.get(i),c=r.get(s);if(!x||!c)return n&&h("vrewfile.ts").warn("[normalizeDenoiseMap] Missing denoise pair media. original="+i+", denoised="+s),[];if(x.type!=="AVMedia"||c.type!=="AVMedia"||c.broken===!0)return n&&h("vrewfile.ts").warn("[normalizeDenoiseMap] Broken or invalid denoise pair media. original="+i+", denoised="+s),[];const l=Math.abs(x.videoAudioMetaInfo.duration-c.videoAudioMetaInfo.duration);return l>=fte?(n&&h("vrewfile.ts").warn("[normalizeDenoiseMap] Duration mismatch in denoise pair. original="+i+", denoised="+s+", diff="+l),[]):[[i,s]]});return Object.fromEntries(a)},GD=(e,t,o)=>{const{duration:r}=e.videoAudioMetaInfo,n=r!==0?r:t.duration??0;return{newFilePath:t.path,mediaFileInfo:{...o,duration:n}}},Nwe=async(e,t,o,r,n)=>{if(t.fileLocation!==D.LOCAL)return;let a=t.path;const i=await Lwe(e,t.path,t.relativePath??"",t.fileSize);a!==i&&i&&(h("vrewfile.ts").info("Recommend new path "+i+" instead of original one "+t.path+" "),a=i);const s=Zr(t)?t.videoAudioMetaInfo.duration:void 0,x={path:t.path,size:t.fileSize,duration:s};let c=i?await qt().getMediaFileInfo(i):void 0;const l=i?{path:i,size:(await Ue().getFileInfo(i)).size,duration:c?.duration}:void 0;if(l&&c&&x.path===l.path&&zM(x,l))return GD(t,l,c);const d=_be(Wt.DONT_ASK_AGAIN_LOST_VIDEO_SAME_SPEC);if(l&&c&&zM(x,l)&&d===mc.YES)return GD(t,l,c);const u=await o(x,l,n);if(u!==zl.CANCEL){if(u===zl.FIND||i===void 0){h("vrewfile.ts").info("Original media "+t.path+" does not exist. Ask new media path.");const p=gt(t.path);r.pause();const f=await Ue().showOpenDialog(Ed,void 0,gt(p),U2());if(r.resume(),f===null)return;a=f.name,c=await qt().getMediaFileInfo(f.name)}return{newFilePath:a,mediaFileInfo:c??t.videoAudioMetaInfo}}},Pwe=async(e,t,o,r,n)=>{const a=Ue(),i=[];for(const u of e.files)Zr(u)&&u.fileLocation===D.LOCAL&&i.push(u.path);const s=await Promise.all(i.map(async u=>!await a.existsFile(u))),x=s.filter(Boolean).length;let c=!1,l=0,d=0;for(const u of e.files){if(u.type!=="AVMedia"||!(Zr(u)&&u.fileLocation===D.LOCAL))continue;const p=s[l]??!1;l++;let f;p&&(d++,f={index:d,total:x});const E=await Nwe(r,u,t,n,f);if(E===void 0)return;const{mediaFileInfo:T,newFilePath:O}=E,S=await bwe(O,T,u);if(S){n.pause();const N=await o(S);if(n.resume(),!N)return}const R=await Qg([{path:O}],void 0,!1,{insertionTarget:Ds.PROJECT,method:c2.TOOLBAR,from:l2.PC});if(R.length===0)return;const{size:y}=await Ue().getFileInfo(R[0].path);u.path!==R[0].path&&(c=!0);const v={...u,path:R[0].path,fileSize:y,videoAudioMetaInfo:R[0].mediaFileInfo,broken:!1},w=e.files.findIndex(N=>N.mediaId===u.mediaId);w>=0&&(e.files[w]=v)}return{vrewFileData:e,pathModified:c}},bwe=async(e,t,o)=>{if(o.fileLocation!==D.LOCAL)return;const r=o.videoAudioMetaInfo.duration;return Math.abs(r-t.duration)<1?void 0:(Gwe(r,t),{originalFilename:gt(o.path),originalFileDuration:r,newFilename:gt(e),newFileDuration:t.duration})},Lwe=async(e,t,o,r)=>
1189{const n=Ue(),a=ML([ti(e),o],Ps()),i=Mt(ke.LAST_OPEN_DIR_LIST),s=await n.getDownLoadsPath(),x=[ti(t),ti(a),ti(e),...i,s].filter(dd).filter(gm);for(const c of x){const l=ML([c,gt(t)],Ps());if(await n.existsFile(l))return l;if(!r||r===0)continue;const u=await n.getSameSizeFile(c,r);if(u)return u}},Mwe=async(e,t)=>{for(const o of Object.keys(e))await Ue().putMediaCache(o,e[o],t[o])},Dwe=async e=>{const t=await $e().getWebAssets(),o=oxe(e.props.trackEntries,t?.content??[]);return{...e,props:{...e.props,trackEntries:o}}},kwe=async e=>{try{const t=Ue(),o="[backup]",r=gt(e),n=ti(e),a=X6(r,o),i=n+a;if(await t.existsFile(i))return;const s=Ibe(),x=Y().popup(s);await t.copyFile(e,i),h("vrewfile.ts").info("Backup vrew file: "+i),await x,NA(g.DISPLAY)}catch(t){xt.error(A("popup.backup_fail")),h("vrewfile.ts").error(P(t)),NA(g.FAIL)}},Fwe=async(e,t,o,r)=>{const n=new Jo,a=h("vrewfile.ts"),i=Ue();if(Vwe(o),!(!r&&!await E9e()))try{const{mainJson:s,blobs:x,exts:c,fileSize:l}=await i.loadProjectFile(o),d=await MRe(s);d.ok===!1&&a.warn("[loadVrewFile] integrity mismatch: file="+o+" version="+s.version+" expected="+d.expected+" actual="+d.actual),s.version<10&&await kwe(o),await Mwe(x,c);const u=await H2(s,x),p=await Pwe(u,e,t,o,n);if(!p){a.info("Failed to find new media path. loading vrewfile canceled.");return}h("vrewfile.ts").info("[loadVrewFile] ensureMediaFilesValid success");const{vrewFileData:f,pathModified:E}=p,T=await Dwe(f),O=n.getElapsedSec();return{vrewFileData:T,pathModified:E,elapsed:O,fileSize:l}}finally{Ebe(Wt.DONT_ASK_AGAIN_LOST_VIDEO_SAME_SPEC,mc.UNDEFINED)}},WD=async e=>{h("vrewfile.ts").info("getting vrew snapshot info..");const t=gT(Yo().getLastSaveInfo(),!0),o=se().getProjectId();return await KT(e,o,t)},KT=async(e,t,o)=>{const r=se(),{captionDisplayMode:n,videoRatio:a,markerNames:i,globalVideoTransform:s,backgroundMap:x,globalCaptionStyle:c,translateInfo:l,overdubInfosMap:d,trackEntries:u,assetEntries:p,sceneNames:f,denoiseMap:E}=rt(e),{assetInfos:T,audioTransformsMap:O,watermark:S}=f2(e),R=tc(e),y=Pv(e),v=Fi(e),w=He(e),N=F5(e),M=Dg(e),k=za(M),F=m2(M),G=h2(M),{assetInfos:B,audioTransformsMap:W}=gI(M),Q={...B,...T},j={...W,...O},$=new Li(d,void 0,u,p,E).collectFrom({type:Or.GLOBAL_CLIP,model:w},{checkDuplicateMainAsset:wi()}),q=$.build(),H=q.getBaseSourceMediaIds(),U=k.filter(dt=>dt.words.some(vr=>{const{visualMediaIds:ln,audioMediaIds:Qo}=gl(vr,F,G);return ln.some(li=>H.has(li))||Qo.some(li=>H.has(li))})),te=new Li(M.overdubInfosMap,void 0,F,G).collectFrom({type:Or.GLOBAL_CLIP,model:U}),ne=Lpe(q,te.build()),oe=new Yx(ne,Q,j,d,x,E,S),{usedAssets:re,usedOverdubInfos:ge,usedAudioTransforms:fe}=oe.getUsedAssets(),{usedBackgroundMap:ve}=oe.getUsedBackground(),{files:yt,blobs:Le}=await oe.getFileDataAndBlobs(),We=xP(E,yt,{logging:!1}),kt=ne.getUsedSourceMediaIds(),bt=Object.fromEntries(Object.entries(v).filter(([dt])=>kt.has(dt)));let Jt;try{Jt=us()}catch(dt){$e().initTTSSpeakerList(!0),h("vrewfile.ts").error("Failed to get lastTTSsettings: "+P(dt))}const Ft=Object.fromEntries(Object.entries(re).map(([dt,vr])=>[dt,{track:vr,role:Q[Je(dt)].role}])),{trackEntries:Pe,assetEntries:_t}=W4(Ft,fe,S),No=aT(w);return{files:yt,globalClips:w,sceneNames:Z9e(f,No),translateInfo:l,props:{globalCaptionStyle:c,captionDisplayMode:n,videoSize:r.getProjectVideoSizeToSave(),analyzeDate:r.getAnalyzeDate(),trackEntries:Pe,baseAssetEntries:_t,overdubInfosMap:ge,videoRatio:a,markerNames:i,globalVideoTransform:s,backgroundMap:ve,lastTTSSettings:Jt,initProjectVideoSize:se().getInitProjectVideoSize(),pronunciationDisplay:N,projectAudioLanguage:R,audioLanguagesMap:y,ttsClipInfosMap:bt,originalClips:U,denoiseMap:We},blobs:Le,projectId:t,statistics:Yo().toJson(o)}},j5=async e=>{const{files:t,blobs:o}=e,r=se().getDummyBlob(),n=Ue(),a=rn.reduce(Object.entries(o),(s,[x,c])=>((c!==r||x===_o)&&(s[x]=c),s),{});await n.restoreLocalCache(t.map(s=>s.mediaId));const i=[];for(const s of t){if(s.mediaId===_o){i.push(s);continue}s.fileLocation===D.LOCAL_TMP||s.fileLocation===D.LOCAL?await n.existsFile(s.path)&&i.push(s):s.fileLocation===D.IN_MEMORY?a[s.mediaId]!==void 0&&i.push(s):i.push(s)}return i},Uwe=async(e,t)=>{const{captionDisplayMode:o,overdubInfosMap:r,trackEntries:n,assetEntries:a,videoRatio:i,markerNames:s,globalVideoTransform:x,backgroundMap:c,globalCaptionStyle:l,denoiseMap:d}=rt(e),{assetInfos:u,audioTransformsMap:p}=f2(e),f=F5(e),E=Dg(e),T=m2(E),O=h2(E),S=za(E),R=tc(e),y=Pv(e),v=Fi(e),{copiedGlobalClips:w,copiedWords:N,copiedElements:M}=t,k=M.map(ge=>ge.elementId),F=new Li(r,k,n,a,d).collectFrom({type:Or.GLOBAL_CLIP,model:w}).collectFrom({type:Or.WORD,model:N}).build(),G=new Yx(F,u,p,r,c,d,void 0),{usedAssets:B,usedOverdubInfos:W,usedAudioTransforms:Q}=G.getUsedAssets(),j=Object.fromEntries(Object.entries(B).map(([ge,fe])=>[ge,{track:fe,role:u[Je(ge)].role}])),{trackEntries:$,assetEntries:q}
1189=W4(j,Q,void 0),H=F.getBaseSourceMediaIds(),{usedBackgroundMap:U}=G.getUsedBackground(),{files:te,blobs:ne}=await G.getFileDataAndBlobs(),oe=xP(d,te,{logging:!1});return{files:te,globalClips:[],sceneNames:{},translateInfo:null,props:{globalCaptionStyle:l,captionDisplayMode:o,baseAssetEntries:{...O,...q},trackEntries:{...T,...$},overdubInfosMap:W,videoRatio:i,markerNames:s,globalVideoTransform:x,backgroundMap:U,lastTTSSettings:void 0,initProjectVideoSize:se().getInitProjectVideoSize(),pronunciationDisplay:f,projectAudioLanguage:R,audioLanguagesMap:y,originalClips:S.filter(ge=>ge.words.some(fe=>{const{visualMediaIds:ve,audioMediaIds:yt}=gl(fe,T,O);return ve.some(Le=>H.has(Le))||yt.some(Le=>H.has(Le))})),ttsClipInfosMap:v,denoiseMap:oe},blobs:ne,projectId:se().getProjectId()}},ct=()=>Cn(10),Vwe=e=>{if(dg.test(e))throw h("vrewfile.ts").error("trying to load shared folder path "+e),new C(_.C_VREW_FILE_IN_SHARED_FOLDER_READ);if(Oo()&&!bh.test(e))throw new C(_.C_INVALID_VREW_EXT_TYPE)},Gwe=(e,t)=>{const o=h("vrewfile.ts");o.warn("The duration of original media file was "+e.toFixed(2)+"s"),o.warn("the duration of a newly chosen file is "+t.duration.toFixed(2)+"s.")},Wwe=(e,t)=>({...t,files:t.files.map(o=>o.fileLocation===D.LOCAL?{...o,relativePath:Vae(e,o.path)}:o)}),cP=async(e,t,o,r,n,a,i)=>{const s=new Jo,x=await jwe(e,t,o,Wwe(t,r),n,i),c=a+s.getElapsedSec();return rn.isNumber(x)?(nFe(x,c),await Ue().setOpenVrewFile(t),P0.SAVED):x==="not_saved"?P0.DONT_SAVE:x==="canceled"?P0.CANCEL:(h("vrewfile.ts").error("Unknown save result "+x),P0.DONT_SAVE)},Hwe=async()=>{const e=ca().filter(n=>n.fileLocation===D.LOCAL).map(n=>n.path),t=e.at(0),o=zu(t?bCe(t):A("startmode.untitled")+".vrew",!0),r=await Ue().showSaveDialog("vrew",A("vrewfile.save_title"),o);if(!(!r||!r.name))return r.name},j2=e=>{const{files:t,props:o}=e;return{version:Be.CURRENT_VREW_JSON_VERSION,files:t.map(a=>Be.toFileJson(a)),transcript:{clips:e.globalClips.map(a=>Be.toClipJson(a,o.baseAssetEntries)),sceneNames:e.sceneNames,translateInfo:e.translateInfo},props:Be.toProjectPropsJson(o),comment:HCe(),projectId:e.projectId,makerCid:e.makerCid,makerUid:e.makerUid,statistics:e.statistics}},jwe=async(e,t,o,r,n,a)=>{if(dg.test(t))throw h("vrewfile.ts").error("trying to save shared folder path "+t),new C(_.C_VREW_FILE_IN_SHARED_FOLDER_WRITE);DD(TA.WAIT);let i=0;const s=Mo().getDebugVal(Xt.SLOW_SAVE)==="1",x=Bwe(!1);let c;try{const l=await LRe(j2(r)),d=await j5(r),u={reqId:x,savePath:t,projectName:o,data:JSON.stringify(l),mediaIds:Yx.putProjectMediaIds(d),autoSave:!1,slowSaveTest:s},p=new Ns,f=p.promise(),E=s?wwe:vwe,T=async()=>{MUe();const R=Kwe(t,n),y=await Y().popup(R),v=h("vrewfile.ts");if(DUe(y),c===void 0){v.info("on askCancelSave, quit flag on. do nothing.");return}if(y===mt.NO||y===mt.CANCEL||y===mt.CLOSE){Ue().cancelPutProjectFile({reqId:x});const w=y===mt.NO?"not_saved":"canceled";p.resolve(w);return}c=setTimeout(T,E)};c=setTimeout(T,E);const O=Ue(),S=O instanceof l_?O.putProjectFile(u,{thumbnailCandidate:a}):O.putProjectFile(u);if(i=await Promise.race([f,S]),rn.isNumber(i)){const R=se().getProjectId();se().notifyFileSaved(e,t,r.projectId,{fromAutosave:!1,thumbnailCandidate:a}),R!==r.projectId&&Il().updateProjectId(R,r.projectId)}}catch(l){throw h("vrewfile.ts").error("error occured while saving vrewFileData:"+P(l)),l}finally{c!==void 0&&(clearTimeout(c),c=void 0),setTimeout(()=>DD(TA.DEFAULT),100)}return i};let zwe=0,Ywe=0;const Bwe=e=>e?"autosave_"+Ywe++:"save_"+zwe++,z5=async(e,t,o,r,n=!1)=>{const a=t===Ee.BROWSER;if(e){const x=qe.v4();if(!Oo()&&a){const d=await Kf(o),u=await x5(d,n,o);return u?{projectId:x,savePath:x,projectName:u.projectName,projectType:Ee.BROWSER,uploadToCloud:u.destination==="cloud"}:void 0}const c=a?x:await Hwe();return c?{projectId:x,savePath:c,projectName:c,projectType:t}:void 0}if(!Oo()&&t===Ee.MEDIA&&uN()==="local")return{projectId:r,savePath:r,projectName:await qwe(""+A("startmode.untitled")),projectType:Ee.BROWSER};const s=await(async()=>a?await Kf(o)??o:o)();return{savePath:o,projectId:r,projectName:s,projectType:t}},Kwe=(e,t)=>{const o=A("save.timeout_cancel_save?",{interpolation:{escapeValue:!1},path:"`"+e+"`"}),r=jt.createElement(Qr,{},o),n=A("popup.save_wait"),a=A("popup.save_cancel"),i=t?A("popup.cancel_progress"):void 0;return{bodyClassName:"general-modal",title:A("save.timeout_cancel_save_title"),content:r,showHeaderCancel:!0,yesStr:n,noStr:a,extraStr:i}},Y5=async(e,t,o,r,n,a,i)=>{const s=[],x=Bg(o),c=n.reduce((d,u)=>d+u.fileSize,0);Tke(a,x,t,c,i),s.push("vrewfile "+e+" loaded, elapsed : "+a+"s, size: "+jr(t));const l={...r,size:jr(t)};s.push(JSON.stringify(l)),h("vrewfile.ts").info(s.join(`
1190`))},Xwe=(e,t,o)=>{const r=Y();return r.getModalProps(st.LOST_VIDEO)?(h("vrewfile.ts").warn("findLostVideo already set"),Promise.resolve(zl.CANCEL)):new Promise(i=>{r.openModal(st.LOST_VIDEO,{resolve:i,originalFileInfo:e,recommendFileInfo:t,progress:o})})},Jwe=e=>{const t=Y();return t.getModalProps(st.WARN_DIFFERENT_MEDIA_DURATION)?(h("vrewfile.ts").warn("warnDifferentMediaDuration already set"),Promise.resolve(!1)):new Promise(r=>{t.openModal(st.WARN_DIFFERENT_MEDIA_DURATION,{resolve:r,mismatchedDurationInfo:e})})},Dxt=async()=>
1190{if(Oo())return[];const e=be().getUserInfo()?.uid??tn;return(await _n().getAllValues(Bo.VREW_PROJECT_DB,Ko.VREW_PROJECT)).filter(r=>r.uid===e).map(r=>({type:Mn.BROWSER,projectSize:r.size,projectId:r.projectId,filePath:"",projectName:r.projectName,lastAccessed:new Date(r.lastModifiedAt).getTime(),thumbnail:r.thumbnail}))},kxt=async e=>(await _n().getAllValues(Bo.VREW_PROJECT_DB,Ko.VREW_PROJECT)).filter(r=>r.uid===e).reduce((r,n)=>r+n.size,0),Kf=async e=>se().isDemo()?vE:(await _n().getValue(Bo.VREW_PROJECT_DB,Ko.VREW_PROJECT,e))?.projectName,qwe=async e=>{const t=_n(),o=await t.getAllValues(Bo.VREW_PROJECT_DB,Ko.VREW_PROJECT),r=new Set(o.map(i=>i.projectName));if(!r.has(e))return e;let n=1,a=e+" ("+n+")";for(;r.has(a);)n+=1,a=e+" ("+n+")";return a},Qwe=e=>{const t=Lt().getCloudProjects().filter(tA),o=new Set(t.map(a=>a.projectTitle));if(!o.has(e))return e;let r=1,n=e+" ("+r+")";for(;o.has(n);)r+=1,n=e+" ("+r+")";return n},SA=(e,t)=>e+"/"+t+"/"+Mx,Xf=(e,t)=>e+"/"+t,B5=(e,t,o,r)=>e+"/"+t+"/"+o+"."+r,Zwe=async(e,t=!1)=>{const o=h("vrewfile.ts"),r=_n(),n=await r.getValue(Bo.VREW_PROJECT_DB,Ko.VREW_PROJECT,e);if(!n)throw new Error("No projectInfo for "+e);const a=Ht(So.BROWSER_PROJECT),i=be().getUserInfo()?.uid??tn,s=Xf(i,e),x=await a.readDir(s+"/","file"),c=await Promise.all(x.map(E=>a.getFileAsBlob(s+"/"+E))),l=c.reduce((E,T)=>E+(T?.size??0),0),d=new TransformStream,{readable:u,writable:p}=d,f=new K9(p,{zip64:!0});return(async()=>{try{for(let E=0;E<x.length;E++){const T=x[E];let O=c[E];if(!O){o.warn("No fileBlob "+T+" exist in opfs");continue}if(t&&T===Mx){const R=await O.text(),y=JSON.parse(R);y.files.forEach(v=>{(v.videoAudioMetaInfo?.videoInfo!==void 0||Sae(v))&&v.fileLocation===D.IN_MEMORY&&!ia(v.mediaId)&&(v.fileLocation=D.LOCAL_TMP)}),O=new Blob([JSON.stringify(y)],{type:"application/json"})}const S=T===Mx?Mx:CZ+"/"+T;await f.add(S,O.stream(),{level:0})}await f.close()}catch(E){if(no(E)){try{await p.abort()}catch{}return}throw o.error("Failed to create browser project stream: "+P(E)),new C(_.C_CREATE_BROWSER_PROJECT_FILE_FAILED,void 0,"Unexpected error during creating browser project stream")}})(),{stream:u,name:n.projectName+"_"+ct()+".vrew",type:"application/zip",size:l}},Fxt=async(e,t=!1)=>{if(await Ch("EXPORT_PROJECT_FILE")===P0.CANCEL)return;const r=await _n().getValue(Bo.VREW_PROJECT_DB,Ko.VREW_PROJECT,e);if(!r)throw new C(_.C_LOGIC_ERROR,void 0,"No projectInfo for "+e);const n=Ue();if(!(n instanceof l_))throw new C(_.C_LOGIC_ERROR,void 0,"BrowserFileSystem is required");const a=new AbortController,i=()=>{a.abort()},s=m0(Sa(A("toast.downloading_browser_project"),{onCancel:i})),x=async()=>await Zwe(e,t),c=r.projectName+"_"+ct();try{const{result:l}=await n.saveFileStream(x,c,"vrew",{onProgress:d=>{s.message(Sa(A("toast.downloading_browser_project"),{progressRatio:d,onCancel:i}))},signal:a.signal});l&&Pbe()}catch(l){h("vrewfile.ts").error("[downloadBrowserProject] Failed to download browser project: "+P(l));const d=Ne(l)?l.errorCode:_.C_BROWSER_PROJECT_DOWNLOAD_FAILED,u=Ot(d,{defaultKey:"error.export_vrew_project_failed"});Y().error(d,u)}finally{s.asClosable(1e3,{closeOnClick:!0})}};class l_{blobs;autosavePath;_latestThumbnailSave=new Map;constructor(){this.blobs=[],wi()&&(window.fs=this)}listDir=t=>Promise.resolve(void 0);listFiles=()=>[];addFile=(t,o)=>Promise.resolve(void 0);putMediaCache=async(t,o,r)=>{this.blobs.push({blob:o,mediaId:t,ext:r})};putLocalCache=async t=>{const{mediaId:o,ext:r,blob:n,url:a,pathInfo:i}=t;if(n===void 0&&a===void 0&&i===void 0)throw new C(_.C_LOGIC_ERROR,void 0,"data and url and path are undefined in local cache.");let s=n;if(!s&&a&&(s=await fetch(a).then(c=>{if(!c.ok){const l="Error during localCache download "+a+": "+c.status;throw new C(_.C_LOCAL_CACHE_DOWNLOAD_FAILED,{},l)}return c.blob()})),!s)throw new C(_.C_LOGIC_ERROR,{},"No blob result for putLocalCache()");return this.blobs.push({blob:s,mediaId:o,ext:r}),{resolvedPath:URL.createObjectURL(s)}};getMediaLocalCacheInfo=()=>Promise.reject();clearOldLocalCache=()=>{};putProjectFile=async(t,o={})=>{const{savePath:r,projectName:n,data:a,mediaIds:i}=t,s=h("browser.ts"),x=Ht(So.BROWSER_PROJECT),c=be().getUserInfo()?.uid??tn,l=5;let d=0;await Bt(zt(i).pipe(Ma(async T=>{const O=this.blobs.find(w=>w.mediaId===T);if(!O){const w="During FS.putProjectFile(), No blob for media "+T;throw s.error(w),new C(_.C_MEDIA_BLOB_LOST,{},w)}const{blob:S,ext:R}=O,y=B5(c,r,T,R);if(await x.existsFile(y)){d+=S.size;return}try{await x.saveFile(y,S.stream(),!0)}catch(w){throw s.error("[putProjectFile] Failed to save blob. mediaId: "+T+", size: "+S.size+", type: "+S.type+", error: "+P(w)),w}d+=S.size},l),X9(void 0)));const u=SA(c,r),p=new TextEncoder,f=p.encode(a),E=new ReadableStream({start(T){T.enqueue(f),T.close()}});try{await x.saveFile(u,E,!0)}catch(T){throw s.error("[putProjectFile] Failed to save project.json. error: "+P(T)),T}return d+=a.length,await this.saveProjectInfoToIndexedDB({savePath:r,uid:c,projectName:n,totalSize:d},o),Promise.resolve(a.length)};createVrewFileForVCloudProject=async()=>Promise.reject();cancelPutProjectFile=async t=>Promise.resolve();saveFramePackFile=async t=>{const{rawJson:o,buffers:r}=t,n=new t1;n.file("template.json",o),Object.entries(r).forEach(([i,s])=>{n.file("media/"+i,s)});const a=await n.generateAsync({type:"blob",compression:"DEFLATE"});this.saveFile(a,"test_template_"+qe.v4(),J6)};loadFramePackFile=async t=>{};loadLocalFramePackFiles=async()=>[];deleteFramePackFile=async t=>{};deleteFiles=t=>Promise.resolve();downloadFile=async(t,o,r,n,a)=>{const i=await fetch(t).then(l=>l.arrayBuffer()),s=o||t.substring(t.lastIndexOf("/")+1),x=new Uint8Array(i),c={name:s,data:x};return Promise.resolve(c)};abortDownload=async t=>{};showOpenDialog=(t,o,r,n)=>{const a=document.createElement("input");a.setAttribute("type","file"),a.setAttribute("accept",t.map(s=>"."+s).reduce((s,x)=>s.length>0?s+","+x:x,"")),a.style.display="none",a.value="",document.body.appendChild(a);const i=new Ns;return a.onchange=async()=>{document.body.removeChild(a);const{files:s}=a;if(!s||s.length===0){i.reject("Not selected");return}const x=s.item(0);if(!x){i.reject("Not selected");return}const c=x.slice(0,x.size,x.type);i.resolve({name:x.name,blob:c})},a.click(),i.promise()};showOpenDialogImportMultipleFiles=(t,o,r,n,a)=>{const i=document.createElement("input");i.setAttribute("type","file"),i.setAttribute("accept",t.map(x=>"."+x).reduce((x,c)=>x.length>0?x+","+c:c,"")),i.style.display="none",i.multiple=!0,i.value="",document.body.appendChild(i);const s=new Ns;return i.addEventListener?.("cancel",()=>{s.resolve([])}),i.onchange=async()=>{document.body.removeChild(i);const{files:x}=i;if(!x||x.length===0){s.reject("Not selected");return}const c=[];for(let l=0;l<x.length;l++){const d=x.item(l);if(!d){s.reject("Not selected");return}
1190c.push({name:d.name,blob:d.slice(0,d.size,d.type)})}s.resolve(c)},i.click(),s.promise()};showSaveDialog=(t,o,r)=>{const n=r?gt(r):"untitled.vrew";return Promise.resolve({name:n})};getAvailableDiskSpace=async()=>{};checkAllowGa=async()=>{const t=Ve(),o=t.get(Ie.ALLOW_GA);return o===""?(this.setAllowGa(!0),{kind:"allow"}):{kind:o==="true"?"allow":"deny"}};setAllowGa=t=>{const o=Ve();return o.set(Ie.ALLOW_GA,t),o.set(Ie.ALLOW_GA_LAST_DATE,new Date().toISOString()),Promise.resolve()};getInitFile=()=>Promise.resolve(null);getExclusiveName=t=>Promise.resolve(t);openFolder=t=>Promise.resolve();createFolder=()=>Promise.reject();existsFile=t=>Promise.resolve(!1);existsFolder=async t=>{const[o,...r]=t.split("/"),n=r.join("/");return await Ht(o).existsDir(n)};updateAutosaveTargetPath=t=>{this.autosavePath=t};cleanupRestoreFile=t=>{};cleanupBackupFiles=()=>Promise.resolve(!0);getTotalBackupSize=()=>Promise.resolve(0);getTotalProxySize=()=>Promise.resolve(0);getTempStorageConfig=()=>Promise.resolve({customPath:null});setTempStoragePath=t=>Promise.resolve({result:"error",reason:"unknown"});createCubeFile=(t,o,r)=>Promise.resolve(null);setOpenVrewFile=t=>Promise.resolve();cubeToPng=t=>Promise.resolve(new Uint8Array);lockFile=t=>Promise.resolve();releaseFile=t=>Promise.resolve();getProcessArgv=()=>Promise.resolve(void 0);getSameSizeFile=t=>Promise.resolve(null);getFileInfo=async t=>{const o=Ht(So.BROWSER_PROJECT),r=await o.readFile(t);if(!r)return{size:0,modifiedTime:new Date(0),birthTime:0};const n=await r.getFile();return{size:n.size,modifiedTime:new Date(n.lastModified),birthTime:0}};getFileInfos=t=>Promise.resolve([]);getFileCrc32=t=>Promise.resolve(void 0);copyFile=()=>Promise.resolve();tempFolder=()=>Promise.reject();deleteFolder=t=>Promise.reject();countFiles=t=>Promise.reject();downloadBlobAsFile=async(t,o)=>{const r=document.createElement("a"),n=window.URL.createObjectURL(t);r.href=n,r.download=o,r.textContent=o,document.body.appendChild(r),r.onclick=()=>document.body.removeChild(r),r.click(),setTimeout(()=>window.URL.revokeObjectURL(n),1e3)};saveFile=async(t,o,r)=>{if(r==="")throw new C(_.C_LOGIC_ERROR,void 0,"format is empty for saveFile");const n={suggestedName:o+"."+r,types:[{accept:{"*/*":["."+r]}}]};try{const a=await showSaveFilePicker(n),i=await a.createWritable(),s=typeof t=="function"?await t():t;try{await s.stream().pipeTo(i)}catch(x){throw x instanceof DOMException&&x.name==="InvalidStateError"?new C(_.C_INVA
1190LID_STATE_ERROR):x}return{result:!0,path:mu(o+"."+r)}}catch(a){if(a instanceof DOMException&&a.name==="AbortError")return h("browser.ts").info("User cancelled save file"),{result:!1};throw h("browser.ts").error("Error during saveFile: "+P(a)),Ne(a)?a:new C(_.C_SAVE_FILE_FAILED)}};saveFileStream=async(t,o,r,n)=>{if(r==="")throw new C(_.C_LOGIC_ERROR,void 0,"format is empty for saveFileStream");const a={suggestedName:o+"."+r,types:[{accept:{"*/*":["."+r]}}]},{onProgress:i,signal:s}=n??{};try{const x=await showSaveFilePicker(a),c=await x.createWritable();let l=0,d=0;try{const{stream:u,size:p}=await t(),f=p??0,E=100,T=new TransformStream({transform(O,S){l+=O.byteLength;const R=performance.now();i&&(R-d>E||l===f)&&(d=R,i(f>0?Math.min(l/f,1):0)),S.enqueue(O)}});await u.pipeThrough(T).pipeTo(c,{signal:s}),i&&f>0&&i(1)}catch(u){throw await c.abort(),u instanceof DOMException&&u.name==="InvalidStateError"?new C(_.C_INVALID_STATE_ERROR):u}return{result:!0,path:mu(o+"."+r)}}catch(x){if(x instanceof DOMException&&x.name==="AbortError")return h("browser.ts").info("User cancelled save file"),{result:!1};throw h("browser.ts").error("Error during saveFileStream: "+P(x)),Ne(x)?x:new C(_.C_SAVE_FILE_STREAM_FAILED)}};deleteLocalStorage=()=>{localStorage.clear()};printFsSummary=()=>Promise.resolve();selectMultipleTypesOfFiles=async t=>{try{return await this.showOpenDialogImportMultipleFiles(t,void 0,A("filetype.video"),U2())}catch(o){if(no(o))return[];throw Ne(o)?o:(h("browser.ts").warn("selectMultipleTypesOfFilesError",P(o)),new C(_.C_SELECT_IMAGE_OR_VIDEO_FILES_ERROR,{},Jx(o)??P(o)))}};checkUserVideoValidPath=t=>!0;getDownLoadsPath=()=>"";getAutosavePath=()=>this.autosavePath;getCurrentProjectFileInfo=()=>({isSaved:!1,path:"",fileName:"",dir:""});getSourceFileInfoForDiagnostic=t=>Promise.resolve(null);getCacheExtInfos=()=>Promise.resolve({});restoreLocalCache=async t=>{};getAlreadyExistMediaId=async()=>null;async getFilePath(t){return Array.isArray(t)?t.map(o=>o.name):t.name}loadProjectFile=async t=>{const o=Ht(So.BROWSER_PROJECT),r=be().getUserInfo()?.uid??tn,n=await o.getFileAsBlob(SA(r,t));if(!n)throw new Error("No projectFile.json for "+t+" folder");const a=JSON.parse(await n.text()),i=Xf(r,t),s=await o.readDir(i+"/","file"),x={},c={};let l=0;for await(const d of s){if(d===Mx)continue;const u=i+"/"+d,p=await o.getFileAsBlob(u);if(!p){const O="No media blob for "+d;h("browser.ts").warn(O);continue}const f=d.lastIndexOf(".");if(f===-1)throw new C(_.C_MEDIA_BLOB_LOST,{},"No ext for "+d);const E=d.substring(0,f),T=d.substring(f+1);x[E]=new Blob([p],{type:X0.getType(T)||pf}),c[E]=T,l+=p.size}return{mainJson:a,blobs:x,exts:c,fileSize:n.size+l}};initializeProxy=async()=>({proxyDir:"",mediaIds:[]});cleanupProxyFiles=async()=>Promise.resolve();saveProjectInfoToIndexedDB=async(t,o={})=>{const{savePath:r,uid:n,projectName:a,totalSize:i}=t,s=Symbol(r);this._latestThumbnailSave.set(r,s);const x=_n(),c=await x.getValue(Bo.VREW_PROJECT_DB,Ko.VREW_PROJECT,r),l=new Date,d={createdAt:c?.createdAt??l.toISOString(),projectId:r,uid:n,projectName:a,lastModifiedAt:l.toISOString(),size:i,thumbnail:c?.thumbnail};await x.putValue(Bo.VREW_PROJECT_DB,Ko.VREW_PROJECT,r,d);const u=o.thumbnailCandidate;u&&u.then(async p=>{if(p===void 0||this._latestThumbnailSave.get(r)!==s)return;const f=await x.getValue(Bo.VREW_PROJECT_DB,Ko.VREW_PROJECT,r);!f||this._latestThumbnailSave.get(r)!==s||await x.putValue(Bo.VREW_PROJECT_DB,Ko.VREW_PROJECT,r,{...f,thumbnail:p})}).catch(p=>{h("browser.ts").warn("Failed to save browser project thumbnail: "+P(p))})};updateProjectThumbnail=async(t,o)=>{const r=_n(),n=await r.getValue(Bo.VREW_PROJECT_DB,Ko.VREW_PROJECT,t);if(!n){h("browser.ts").warn("Cannot save thumbnail: no project "+t+" in IndexedDB");return}await r.putValue(Bo.VREW_PROJECT_DB,Ko.VREW_PROJECT,t,{...n,thumbnail:o})};hasThumbnail=async t=>(await _n().getValue(Bo.VREW_PROJECT_DB,Ko.VREW_PROJECT,t))?.thumbnail!==void 0}let eC;const XT=()=>(eC===void 0&&(eC=new l_),eC);let tC;const Ue=()=>(!tC&&(tC=at()?yn():XT()),tC);var lP=(e=>(e.PROJECT="PROJECT",e.IMAGE_PROJECT="IMAGE_PROJECT",e.SCENE="SCENE",e.ASSET="ASSET",e.ASSET_CLIP="ASSET_CLIP",e.CONTEXT_FLOATING_MENU="CONTEXT_FLOATING_MENU",e.TRANSFER="TRANSFER",e))(lP||{});const $we=5,JT=1e3,d_=3600*1e3,qT=50,eNe="vdrop-asset_";var tNe=(e=>(e.AUDIO="audio",e.VIDEO="video",e.IMAGE="image",e))(tNe||{}),oNe=(e=>
1190(e.SESSION_CREATED="SESSION_CREATED",e.LINK_OPENED="LINK_OPENED",e.METADATA_UPLOAD_DONE="METADATA_UPLOAD_DONE",e.FILE_UPLOAD_DONE="FILE_UPLOAD_DONE",e.FILE_DOWNLOAD_DONE="FILE_DOWNLOAD_DONE",e.SESSION_EXPIRED="SESSION_EXPIRED",e.PENDING="PENDING",e.CANCELED="CANCELED",e))(oNe||{});const K5=4*Math.pow(2,30),rNe=async e=>{h("vdrop.ts").info("Initialize vdrop session");const o=await h0("/vdrop/new",{method:"GET"}),r=await me(o,_.C_VDROP_NETWORK_ERROR);if(!("sessionId"in r))throw new C(_.C_VDROP_GENERAL_ERROR);const n=await zo(),a=r.sessionId,i=COe+"/"+a,s=new URLSearchParams;n&&s.append("cid",n),e&&s.append("importType",e);const x=s.toString(),c=x?i+"?"+x:i;return Cr().startJob(a,{type:Xi.VDROP}),{sessionId:a,url:c}},nNe=async(e,t,o)=>{const r="vdrop_metadata_"+Cn(10),n=h("vdrop.ts");return Cr().startProcess(r,{type:o_.VDROP_SUBPROCESS,jobId:e}),a_({processId:r,jobId:e,type:Ii.PROCESS},d_,async()=>{try{const a=await u_(e),{status:i}=p_(a);switch(i){case void 0:throw n.error("vdrop session not created"),new C(_.C_VDROP_GENERAL_ERROR);case"SESSION_EXPIRED":throw n.error("vdrop session expired"),new C(_.C_VDROP_SESSION_EXPIRED);case"CANCELED":n.warn("vdrop session canceled"),Cr().markProcessAsDone(e,r);return;case"PENDING":case"SESSION_CREATED":return;case"LINK_OPENED":t(!0),Cr().markProcessAsDone(e,r);return;default:return}}catch(a){n.error("Get vdrop metadata during polling failed "+P(a)),Cr().abortJob(e),Ku(e,a,"upload"),o();return}},_.C_VDROP_UPLOAD_TIMEOUT,JT)},aNe=async(e,t,o,r)=>{const n="vdrop_metadata_"+Cn(10),a=h("vdrop.ts");Cr().startProcess(n,{type:o_.VDROP_SUBPROCESS,jobId:e});const i=async x=>{const c=await h0("/vdrop/"+x+"/metadata-v2",{method:"GET"}),l=await me(c,_.C_VDROP_NETWORK_ERROR);if(l.status==="error")throw new C(_.C_VDROP_GENERAL_ERROR);return l.body.metadataArray},s=x=>{if(x.length===0)throw a.error("Failed to get vdrop metadata"),new C(_.C_VDROP_GENERAL_ERROR);a.info("Get vdrop metadata success"),aFe(r,x[0].fileType,x.reduce((c,l)=>c+l.fileSize,0),x.length),t(x),Cr().markProcessAsDone(e,n)};return a_({processId:n,jobId:e,type:Ii.PROCESS},d_,async()=>{try{const x=await u_(e),{status:c}=p_(x);switch(c){case void 0:throw a.error("vdrop session not created"),new C(_.C_VDROP_GENERAL_ERROR);case"SESSION_EXPIRED":throw a.error("vdrop session expired"),new C(_.C_VDROP_SESSION_EXPIRED);case"CANCELED":a.error("vdrop session canceled"),Cr().markProcessAsDone(e,n);return;case"PENDING":case"SESSION_CREATED":case"LINK_OPENED":return;default:{const l=await i(e);s(l)}}}catch(x){a.error("Get vdrop metadata during polling failed "+P(x)),Cr().abortJob(e),Ku(e,x,"download"),o();return}},_.C_VDROP_UPLOAD_TIMEOUT,JT)},X5=async(e,t,o)=>{try{const r=await h0("/vdrop/"+e+"/progress",{method:"PUT",body:JSON.stringify({progress:t,fileName:o})});!r.ok&&h("vdrop.ts").error("Update vdrop progress status not ok. status: "+r.status+", statusText: "+r.statusText)}catch(r){h("vdrop.ts").error("Failed to update vdrop progress: "+P(r))}},iNe=async(e,t,o,r,n,a)=>{const i="vdrop_download_"+Cn(10);t.current=i;const s=h("vdrop.ts");return Cr().startProcess(i,{type:o_.VDROP_SUBPROCESS,jobId:e}),a_({processId:i,jobId:e,type:Ii.PROCESS},d_,async()=>{try{const x=await u_(e),c=x.body.sessionStatusArray.map(u=>u.downloadUrl),{status:l}=p_(x),d=J5(x);switch(r(u=>d>u?d:u),l){case"SESSION_EXPIRED":throw s.error("Vdrop session expired"),new C(_.C_VDROP_SESSION_EXPIRED);case void 0:case"SESSION_CREATED":case"LINK_OPENED":case"FILE_DOWNLOAD_DONE":throw s.error("Vdrop invalid status on downloadData"),new C(_.C_VDROP_GENERAL_ERROR);case"CANCELED":s.error("Vdrop session canceled"),Cr().markProcessAsDone(e,i);return;case"PENDING":case"METADATA_UPLOAD_DONE":return;case"FILE_UPLOAD_DONE":if(c.length===0)throw s.error("Vdrop invalid status on downloadData: downloadUrls is empty"),new C(_.C_VDROP_GENERAL_ERROR);r(qT),await lNe(e,c,o,r,a),Cr().markProcessAsDone(e,i)}}catch(x){s.error("Vdrop download during polling failed: "+P(x)),Cr().abortJob(e),Ku(e,x,"download",o),n();return}},_.C_VDROP_UPLOAD_TIMEOUT,JT)},sNe=async(e,t)=>(await r2.get(e,{responseType:"blob",onDownloadProgress:r=>{if(r.total){const n=Math.round(r.loaded*100/r.total);t(n)}}})).data,xNe=async(e,t,o,r,n,a)=>{const i=o.map(async(s,x)=>{const c=s.fileName,l=t[x];if(!l)throw h("vdrop.ts").error("Vdrop invalid status on downloadData"),new C(_.C_VDROP_GENERAL_ER
1190ROR);const d=async u=>{if(Oo()){const p=Ue(),f=await fNe(),E=eNe.concat(c),T=jx.join(f,E),O=await p.getExclusiveName(T);return await p.downloadFile(l,O,S=>u(parseInt(S))),{name:O}}else{const p=await sNe(l,u);return{name:c,blob:p}}};return Wr(()=>d(u=>{const p=qT+Math.floor(u/2);a(e,p,c),r[x]=p,n(r.reduce((f,E)=>f+E,0)/r.length)}),$we,"vdropDownload("+c+")")});return await Promise.all(i)},cNe=e=>e[0]?.fileType.includes("video")?"video":e[0]?.fileType.includes("audio")?"audio":"image",lNe=async(e,t,o,r,n)=>{const a=new Jo;a.reset();const i=Array(o.length).fill(qT),s=rn.throttle((E,T,O)=>{X5(E,T,O).catch(S=>{h("vdrop.ts").error("Failed to update session progress: "+P(S))})},1e3),x=await xNe(e,t,o,i,r,s),c=a.lap(),l=cNe(o),d=o.reduce((E,T)=>E+T.fileSize,0),u=o.length;iFe(n.importType,l,d,u,c),dNe(e);const p=n.type==="source"?n.addSceneIndex===null?Ds.PROJECT:Ds.SCENE:Ds.ASSET,f=await uNe(l,p,x);await pNe(n,l,f)},dNe=async e=>{try{const t=await h0("/vdrop/"+e+"/download-done",{method:"PUT"});!t.ok&&h("vdrop.ts").error("Update vdrop download-done status not ok. status: "+t.status+", statusText: "+t.statusText)}catch(t){h("vdrop.ts").error("Failed to notify download done: "+P(t))}},uNe=async(e,t,o)=>{if(e==="image")return rs(o,async s=>{if(A0(s))return s;const x=await fetch(an(s.name)).then(l=>l.blob());return{name:gt(s.name),blob:x}});const r=await rs(o.filter(A0),async s=>{const x=Ht(So.AUDIO_TEMP),c=await ix(x),l=await c.getMediaFileInfo(s.blob);if(!(l.videoInfo?xN(l.videoInfo.codec,l.videoInfo.pixFmt):!0)){const u="Vdrop codec "+l.videoInfo?.codec+" is not compatible with this browser: "+s.name;throw h("vdrop.ts").error(u),new C(_.C_MEDIA_INCOMPATIBLE_VIDEO_CODEC,{videoCodec:l.videoInfo?.codec},u)}return{...s,mediaFileInfo:l}}),n={insertionTarget:t,method:c2.VDROP_MODAL,from:l2.VDROP},a=(await Qg(o.filter(s=>!A0(s)).map(({name:s})=>({path:s})),void 0,!0,n,!0)).map(s=>({name:s.path,mediaFileInfo:s.mediaFileInfo})),i=[...r,...a];return rs(i,async s=>{const x=lN(s.name),c=qe.v4(),l=await Ue().putLocalCache({mediaId:c,pathInfo:A0(s)?void 0:{path:s.name,preserveOriginal:!1},blob:A0(s)?s.blob:void 0,ext:x});return{...s,name:A0(s)?s.name:l.resolvedPath,mediaId:c}})},pNe=async(e,t,o)=>{if(e.type==="source"){const{importMethod:r,addSceneIndex:n}=e,a=e.importType===lP.PROJECT?gn.NEW_PROJECT:gn.NEW_SCENE;if(t==="image"){const x=o.map(c=>{if(!A0(c)){const l="Vdrop image filetype always should be blob type";throw new C(_.C_VDROP_GENERAL_ERROR,void 0,l)}return c});Y().openModal(st.IMPORT_IMAGES,{clipDispatchRange:a,blobFiles:x}),Y().closeLastShownMessage();return}const i=n===null?Ds.PROJECT:Ds.SCENE,s=o.map(x=>({path:x.name,blob:A0(x)?x.blob:void 0,mediaFileInfo:x.mediaFileInfo,mediaId:x.mediaId}));if(s.length===1){FG(s,n,r,t==="video"?Ls.VIDEO:Ls.AUDIO,!1),Y().closeLastShownMessage();return}Y().openModal(st.MULTI_FILE_UPLOAD,{uploadList:s,addSceneIndex:n,startMedia:Ls.VIDEO,importMethod:r,execContext:{insertionTarget:i,method:c2.VDROP_MODAL,from:l2.VDROP}}),Y().closeLastShownMessage();return}else if(e.type==="asset"){const{uploadAsset:r}=e;r(o),Y().closeLastShownMessage()}},u_=async e=>await h0("/vdrop/"+e+"/status-v2",{method:"GET"}).then(t=>me(t,_.C_VDROP_NETWORK_ERROR)),p_=e=>{const t=e.body.sessionStatusArray;if(t.length<=0)return{status:void 0};const o=t[0].status;return t.every(n=>n.status===o)?{status:o}:{status:"PENDING"}},J5=e=>{const t=e.body.sessionStatusArray;return t.length===0?0:t.reduce((r,n)=>r+n.progress,0)/t.length},fNe=async()=>await Ue().tempFolder(),dP=async e=>{try{const t=await h0("/vdrop/"+e+"/expire",{method:"PUT"});if(!t.ok){h("vdrop.ts").error("Failed to expire vdrop session: "+t.status);return}h("vdrop.ts").info("Succeeded to expire vdrop session: "+t.status);return}catch(t){h("vdrop.ts").error("Failed to expire vdrop session: "+P(t));return}finally{Y().closeLastShownMessage()}},HD=async e=>{try{const t=await h0("/vdrop/"+e+"/cancel",{method:"PUT"});if(!t.ok){h("vdrop.ts").error("Failed to cancel vdrop session: "+t.status);return}h("vdrop.ts").info("Succeeded to cancel vdrop session: "+t.status);return}catch(t){h("vdrop.ts").error("Failed to cancel vdrop session: "+P(t));return}},Ku=async(e,t,o,r)=>{e&&await dP(e);
1190const n=Ne(t)?t.errorCode:_.C_VDROP_GENERAL_ERROR,a=Ho(t);if(n===_.C_UPLOAD_USER_CANCELED){Gz(o);return}if(!r||r.length===0)pk(void 0,void 0,void 0,n);else{const s=r[0]?.fileType.includes("video")?"video":r[0]?.fileType.includes("audio")?"audio":"image",x=r.reduce((l,d)=>l+d.fileSize,0),c=r.length;pk(s,x,c,n)}const i=Ot(n,{defaultKey:"error.vdrop_download_failed",errorArg:a});Y().error(n,i)},gNe=async e=>{if(e)try{const t=await u_(e),{status:o}=p_(t);if(o&&["FILE_UPLOAD_DONE","FILE_DOWNLOAD_DONE"].includes(o))return;await HD(e)}catch(t){h("vdrop.ts").error("Failed to check status before cancel: "+P(t)),await HD(e)}},_Ne=async(e,t,o)=>{const r={metadataArray:[t],cid:o},n=await h0("/vdrop/"+e+"/metadata-v2",{method:"POST",body:JSON.stringify(r)});if(!n.ok)throw h("vdrop.ts").error("Failed to upload vdrop metadata: "+n.status),new C(_.C_VDROP_NETWORK_ERROR);const a=await me(n,_.C_VDROP_GENERAL_ERROR);if(a.status==="error")throw new C(_.C_VDROP_NETWORK_ERROR);return a.body.uploadUrls[0]},ENe=async(e,t,o,r)=>{const n=rn.throttle(r,1e3);return G2(()=>r2.put(e,t,{headers:{"Content-Type":t.type},signal:o,onUploadProgress:a=>{const i=a.loaded/(a.total??a.loaded);n(Math.floor(i*50))}}))},mNe=async e=>{try{const t=await h0("/vdrop/"+e+"/upload-done",{method:"PUT"});!t.ok&&h("vdrop.ts").error("Failed to notify upload done: "+t.status)}catch(t){h("vdrop.ts").error("Failed to notify upload done: "+P(t))}},hNe=async(e,t,o,r,n)=>{await ENe(e,t,r,i=>{n(i),X5(o,i,t.name).catch(s=>{h("vdrop.ts").error("Failed to update progress during upload: "+P(s))})}).then(i=>{if(i===null){h("vdrop.ts").info("Vdrop upload canceled by user.");return}if(i?.status!==200)throw new C(_.C_VDROP_NETWORK_ERROR);return i})&&await mNe(o)},INe=async e=>{await dP(e)},TNe=e=>{const t=/\p{Extended_Pictographic}/gu,o=e.name.replace(t,"");return new File([e],o,{type:e.type})},SNe=async(e,t,o,r,n)=>{try{const a=TNe(t),i=CNe(a,"video");r([i]);const s=await _Ne(e,i,await zo());await hNe(s,a,e,o,n)}catch(a){throw h("vdrop.ts").error("Error occurred during upload: "+P(a)),await INe(e),a}},ONe=(e,t,o,r,n,a)=>{const i="vdrop_download_"+Cn(10);return t.current=i,Cr().startProcess(i,{type:o_.VDROP_SUBPROCESS,jobId:e}),a_({processId:i,jobId:e,type:Ii.PROCESS},d_,async()=>{try{const s=await u_(e),{status:x}=p_(s),c=J5(s);if(o(l=>c>l?c:l),x==="CANCELED"){Cr().markProcessAsDone(e,i);return}if(x==="FILE_DOWNLOAD_DONE"){Cr().markProcessAsDone(e,i),r(),lFe(n,(performance.now()-a)/1e3);return}}catch(s){h("vdrop.ts").error("Error occurred during download: "+P(s)),Cr().markProcessAsDone(e,i),Ku(e,s,"upload")}},_.C_VDROP_UPLOAD_TIMEOUT,JT)},CNe=(e,t)=>{h("vdrop.ts").info("readFile start",e);const r="video/mp4",n="audio/mp3",a="image/jpeg",i={audio:n,video:r,image:a},s=i[t]||a;return{fileName:e.name,fileSize:e.size,fileType:e.type||s,thumbnail:void 0}},q5=e=>{uFe("file_size_limit_exceeded",e),h("vdrop.ts").info("Vdrop file size limit exceeded, fileSize: "+e)},RNe="/try/assets/ic_phone-mkBz5zWm.svg",ANe=xe("div",{display:"flex",alignItems:"center",justifyContent:"center"}),Gi=it.forwardRef((e,t)=>{const{gap:o,...r}=e,{css:n,className:a,rest:i,children:s}=al(r),x=aU(n,{gap:o});return b.jsx(ANe,{ref:t,css:x,className:a,...i,children:s})}),yNe=xe("div",{position:"absolute",variants:{axis:{horizontal:{left:"50%",transform:"translateX(-50%)"},vertical:{top:"50%",transform:"translateY(-50%)"},both:{left:"50%",top:"50%",transform:"translate(-50%, -50%)"}}}}),Uxt=it.forwardRef((e,t)=>{const{axis:o="both",...r}=e,{css:n,rest:a,children:i,className:s}=al(r);return b.jsx(yNe,{axis:o,ref:t,className:s,css:n,...a,children:i})}),vNe=({outputFile:e})=>{const t=typeof e=="string";return{fileName:t?gt(e):e.name,shouldShowPrimaryButton:t,onClickOpenFolder:()=>{!t||!Oo()||(Ue().openFolder(e),Y().closeLastShownMessage())},onClickShareToMobile:async()=>{Y().closeLastShownMessage();try{const s=t?await m9e(e):e;if(s.size>K5){q5(s.size),xt.error(A("error.vdrop_file_size_limit_exceeded"));return}hbe("export",s)}catch(s){h("VideoExportDonePopup.tsx").error(`Failed to open share to mobile in export : ${P(s)}`),xt.error(A("vdrop.failed_to_get_exported_video"))}},onClickClose:()=>{Y().closeLastShownMessage()}}},wNe=({outputFile:e})=>{const{fileName:t,shouldShowPrimaryButton:o,onClickOpenFolder:r,onClickShareToMobile:n,onClickClose:a}=vNe({outputFile:e});return b.jsxs(NNe,{children:[b.jsxs(PNe,{children:[b.jsxs(bNe,{children:[b.jsx(o1,{loop:!1,play:!0,animationData:SJ,style:{width:128,height:128}}),b.jsx(LNe,{children:A("export.video_desc")})]}),b.jsx(MNe,{children:b.jsx(DNe,{children:A("export.file_name",{fileName:t})})})]}),b.jsxs(kNe,{children:[b.jsxs(FNe,{onClick:n,children:[b.jsx(UNe,{src:RNe}),b.jsx(VNe,{children:A("export.send_to_mobile")})]}
1190),b.jsxs(GNe,{children:[b.jsx(jD,{type:o?"close":"primary",onClick:a,children:b.jsx(zD,{children:A("popup.close")})}),o&&b.jsx(jD,{type:"primary",onClick:r,children:b.jsx(zD,{children:A("export.open_folder")})})]})]})]})},NNe=xe(Xe,{flexDirection:"column",gap:48,w:"100%",p:"0px 28px 32px 28px"}),PNe=xe(Xe,{flexDirection:"column",gap:32,w:"100%"}),bNe=xe(Gi,{flexDirection:"column",gap:8,w:"100%"}),LNe=xe("div",{fontSize:20,fontWeight:700,lineHeight:"28px",c:ee.gray[850]}),MNe=xe(Gi,{flexDirection:"column",gap:12,h:60,p:20,radius:8,bg:ee.gray[50]}),DNe=xe("div",{fontSize:14,fontWeight:400,lineHeight:"20px",c:ee.gray[750]}),kNe=xe(Xe,{justifyContent:"space-between",w:"100%"}),FNe=xe(Gi,{gap:4,p:"8px 12px 8px 8px",radius:8,cursor:"pointer","&:hover":{bg:ee.mint[25]}}),UNe=xe(Mi,{w:20,h:20}),VNe=xe("div",{fontSize:14,fontWeight:500,lineHeight:"20px",c:ee.mint[500]}),GNe=xe(Xe,{gap:8}),jD=xe(Gi,{h:40,p:"0px 12px",radius:8,cursor:"pointer",variants:{type:{close:{bg:ee.gray[100],c:ee.gray[750],"&:hover":{bg:ee.gray[150]}},primary:{bg:ee.mint[500],c:ee.gray[0],"&:hover":{bg:ee.mint[600]}}}}}),zD=xe("div",{minW:76,fontSize:14,fontWeight:500,lineHeight:"20px",textAlign:"center"}),WNe="/try/assets/ic_success-CHC-4_gA.svg",HNe=xe("img"),Q5=it.forwardRef((e,t)=>{const{children:o,...r}=e,{css:n,rest:a,className:i}=al(r);return b.jsx(HNe,{ref:t,css:n,className:i,onContextMenu:s=>{s.currentTarget.closest(`.${Vx.VIDEO_WRAPPER}`)||s.preventDefault()},...a})}),jNe=()=>{const e=()=>{Y().closeLastShownMessage()};return b.jsxs(zNe,{children:[b.jsxs(YNe,{children:[b.jsx(BNe,{children:b.jsx(Q5,{w:100,h:100,src:WNe})}),b.jsxs(KNe,{children:[b.jsx(XNe,{children:A("vdrop.transfer_success")}),b.jsx(JNe,{children:A("vdrop.send_to_mobile_after")})]})]}),b.jsx(qNe,{onClick:e,children:b.jsx(QNe,{children:A("vdrop.ok")})})]})},zNe=xe(Gi,{w:"100%",flexDirection:"column",gap:40}),YNe=xe(Xe,{w:"100%",flexDirection:"column",gap:28}),BNe=xe(Gi,{w:"100%",gap:10,p:"20px 0px"}),KNe=xe(Xe,{w:"100%",flexDirection:"column",gap:4}),XNe=xe("div",{fontSize:16,fontWeight:700,lineHeight:"24px",color:ee.gray[850]}),JNe=xe("div",{fontSize:14,fontWeight:400,lineHeight:"20px",color:ee.gray[550]}),qNe=xe(Gi,{w:160,h:40,bg:ee.mint[500],p:"0px 12px",radius:8,gap:8,cursor:"pointer","&:hover":{backgroundColor:ee.mint[600]}}),QNe=xe("div",{fontSize:14,fontWeight:500,lineHeight:"24px",color:ee.gray[0]}),ZNe="/try/assets/ic_file-C072wm7v.svg",$Ne="/try/assets/ic_upload-24CUxZq5.svg",ePe=({onClickSend:e,deviceConnected:t,initialFile:o})=>{const r=it.useRef(null),[n,a]=it.useState(o||null),i=()=>{n!==null&&(cFe(o?"export":"toolbar"),e(n))},[s,x]=it.useState(!1),c=l=>{const d=l.target.files;if(d&&d.length>0){if(d[0].size>K5){a(null),x(!0),q5(d[0].size);return}x(!1),a(d[0]),dFe(d[0].size,d[0].type)}};return b.jsxs(b.Fragment,{children:[b.jsxs(tPe,{children:[b.jsxs(oPe,{children:[b.jsx(rPe,{children:A("vdrop.file_name")}),b.jsxs(nPe,{onClick:()=>r.current?.click(),children:[b.jsx(aPe,{src:$Ne}),b.jsx("input",{type:"file",accept:"video/*",onChange:c,id:"file-upload",ref:r,hidden:!0}),b.jsx(iPe,{children:A("vdrop.select_file")})]})]}),b.jsxs(sPe,{children:[b.jsx(cPe,{children:n===null?b.jsx(gPe,{children:A("vdrop.empty_file_desc")}):b.jsx(lPe,{children:b.jsxs(dPe,{children:[b.jsx(uPe,{src:ZNe}),b.jsx(pPe,{children:n.name}),b.jsx(fPe,{children:jr(n.size)})]})})}),s&&b.jsx(xPe,{children:A("error.vdrop_file_size_limit_exceeded")})]})]}),t&&b.jsx(_Pe,{disabled:n===null,onClick:i,children:t?A("vdrop.send"):A("vdrop.waiting_device")})]})},tPe=xe(Xe,{flexDirection:"column",w:"100%",gap:4}),oPe=xe(Gi,{w:"100%",justifyContent:"space-between"}),rPe=xe("div",{fontSize:16,fontWeight:700,lineHeight:"24px",color:ee.gray[750]}),nPe=xe(Gi,{flexDirection:"row",radius:8,p:"8px 12px 8px 8px",gap:4,cursor:"pointer","&:hover":{backgroundColor:ee.mint[25]}}),aPe=xe(Mi,{w:20,h:20}),iPe=xe("div",{fontSize:14,fontWeight:500,lineHeight:"20px",color:ee.mint[500]}),sPe=xe(Xe,{w:"100%",flexDirection:"column",gap:8}),xPe=xe("div",{fontSize:12,fontWeight:400,lineHeight:"16px",color:ee.tangerine[700],pl:4}),cPe=xe(Xe,{flexDirection:"column",maxH:156,overflowY:"auto",overflowX:"hidden",radius:8,p:"16px 12px",gap:4,backgroundColor:ee.gray[25]}),lPe=xe(Gi,{w:360,radius:4,justifyContent:"center",p:"4px 8px",gap:8}),dPe=xe(Xe,{flexDirection:"row",w:"100%",gap:4,overflow:"hidden"}),uPe=xe(Mi,{w:20,h:20,flexShrink:0}),pPe=xe("div",{fontSize:14,fontWeight:400,lineHeight:"20px",color:ee.gray[750],textOverflow:"ellipsis",whiteSpace:"nowrap",wordBreak:"break-all",overflow:"hidden",userSelect:"none",flex:1}),fPe=xe("div",{fontSize:14,fontWeight:400,lineHeight:"20px",color:ee.gray[400]}),gPe=xe("div",{fontSize:14,fontWeight:400,lineHeight:"20.5px",color:ee.gray[400]}),_Pe=xe(Gi,{minW:100,h:40,p:"0px 12px",gap:8,backgroundColor:ee.mint[500],color:"white",radius:8,fontSize:16,fontWeight:700,lineHeight:"24px",cursor:"pointer","&:hover":{backgroundColor:ee.mint[600]},variants:{disabled:{true:{backgroundColor:ee.gray[150],pointerEvents:"none",cursor:"not-allowed"}}}}),EPe="/try/assets/ic_circle_info-DPUVIuQk.svg",mPe="/try/assets/vdrop_img_hand-CRxhLTlR.svg",hPe="/try/assets/vdrop_spinner-o1lVX9LP.svg",IPe="/try/assets/vdrop_uploading_caution-eEojW1gA.svg",TPe=({className:e,ratio:t,indeterminate:o})=>b.jsx("progress",{className:un(e,"vrew--progress",{indeterminate:o}),value:t,max:"100"}),SPe=e=>{const t=it.useRef(""),o=it.useRef(""),r=it.useRef(!1),n=it.useRef(void 0),a=it.useRef(new AbortController),[i,s]=it.useState(""),[x,c]=it.useState([]),[l,d]=it.useState(0),[u,p]=it.useState(!1),[f,E]=it.useState(!1),[T,O]=it.useState(!1),S=it.useRef(!1),R=e.type==="upload"?"upload":"download",y=it.useRef(null),v=it.useCallback(async()=>{t.current&&(await dP(t.current),p(!0),h("VdropPopup.tsx").error("Vdrop link o
1190pen timer expired"),Y().closeLastShownMessage(),Y().info(A("error.vdrop_session_expired")))},[]),w=it.useCallback(async()=>{if(!r.current)try{const{sessionId:M,url:k}=await rNe(e.importType);t.current=M,s(k),r.current=!0,n.current=setTimeout(v,d_),await nNe(M,E,()=>p(!0)),clearTimeout(n.current),e.type!=="upload"&&await aNe(M,c,()=>p(!0),e.importType)}catch(M){if(Ne(M)&&M.errorCode===_.C_VDROP_USER_CANCELED)return;h("VdropPopup.tsx").error(`Failed to init vdrop: ${P(M)}`),Ku(t.current,M,R)}},[e.importType,e.type,v,R]);it.useEffect(()=>{e.type!=="upload"&&x.length>0&&!S.current&&(S.current=!0,iNe(t.current,o,x,d,()=>p(!0),e))},[x,e,S]);const N=it.useCallback(async M=>{if(!(e.type!=="upload"||M===null))try{y.current=performance.now(),await SNe(t.current,M,a.current.signal,c,d),await ONe(t.current,o,d,()=>O(!0),e.calledFrom,y.current)}catch(k){Ku(t.current,k,R)}},[e,R]);return it.useEffect(()=>{w()},[w]),it.useEffect(()=>{if(e.type==="upload"){sFe(e.calledFrom);return}xFe(e.calledFrom)},[e.calledFrom,e.type]),it.useEffect(()=>{const M=a.current;return()=>{t.current&&(Gz(R),Cr().cancelJob(t.current)),gNe(t.current),M.abort(),n.current&&(clearTimeout(n.current),n.current=void 0)}},[R]),{url:i,metadataArray:x,totalProgress:l,sessionExpired:u,deviceConnected:f,onClickSend:N,transferDone:T}},OPe=e=>{const{url:t,metadataArray:o,totalProgress:r,sessionExpired:n,deviceConnected:a,onClickSend:i,transferDone:s}=SPe(e),x=o.reduce((d,u)=>d+u.fileSize,0),c=o.length,l=e.type==="upload";return n?null:b.jsx(CPe,{children:s?b.jsx(jNe,{}):o.length>0?b.jsxs(b.Fragment,{children:[b.jsxs(RPe,{children:[b.jsx(APe,{animationData:OJ,direction:l?-1:1,play:!0,loop:!0}),b.jsxs(yPe,{children:[b.jsxs(vPe,{children:[b.jsx(wPe,{children:`${A("vdrop.transferring_files",{fileCount:c})}`}),b.jsx(NPe,{children:JCe(x)})]}),b.jsxs(PPe,{className:"qr-progress",children:[b.jsx(TPe,{ratio:r}),b.jsxs(bPe,{children:[Math.floor(r),"%"]})]})]})]}),b.jsx(LPe,{children:r<=qT?b.jsxs(b.Fragment,{children:[b.jsx(YD,{}),b.jsx(oC,{children:l?A("vdrop.send_warning"):A("vdrop.caution_loading")})]}):b.jsx(b.Fragment,{children:l?b.jsxs(b.Fragment,{children:[b.jsx(MPe,{}),b.jsx(oC,{children:A("vdrop.send_info")})]}):b.jsxs(b.Fragment,{children:[b.jsx(YD,{}),b.jsxs(oC,{children:[A("vdrop.caution_sending1"),b.jsx("br",{}),A("vdrop.caution_sending2")]})]})})})]}):b.jsxs(b.Fragment,{children:[b.jsxs(DPe,{children:[b.jsx(kPe,{children:A("vdrop.qrcode_camera_guide")}),b.jsxs(FPe,{children:[b.jsx(Qr,{children:l?A("vdrop.send_desc_1"):A("vdrop.qrcode_desc1")}),b.jsx("br",{}),l?A("vdrop.send_desc_2"):A("vdrop.qrcode_desc2")]})]}),b.jsxs(UPe,{children:[t?b.jsx(VPe,{value:t,size:180,level:"L",bgColor:xd,fgColor:u1}):b.jsx(WPe,{}),b.jsx(HPe,{})]}),l&&b.jsx(ePe,{onClickSend:i,deviceConnected:a,initialFile:e.exportedFile})]})})},CPe=xe(Xe,{w:"100%",flexDirection:"column",justifyContent:"flex-start",alignSelf:"stretch",radius:12,fontStyle:"normal",fontWeight:400,fontSize:16,gap:16}),RPe=xe(Xe,{flexDirection:"column",w:360,h:270,mb:40,gap:16,order:0}),APe=xe(o1,{w:360,h:202,radius:8,objectFit:"contain"}),yPe=xe(Xe,{flexDirection:"column",alignItems:"flex-start",p:0}),vPe=xe(Xe,{flexDirection:"row",alignItems:"center",justifyContent:"flex-start",maxW:"100%",gap:8,mb:4,p:0}),wPe=xe("div",{color:ee.gray[900],textOverflow:"ellipsis",overflow:"hidden",whiteSpace:"pre",lineHeight:"24px"}),NPe=xe(Xe,{alignItems:"center",textAlign:"right",color:ee.gray[900],fontSize:13,lineHeight:"20px"}),PPe=xe(Xe,{justifyContent:"space-between",alignItems:"center",w:360,h:24}),bPe=xe("div",{alignItems:"center",textAlign:"right",color:ee.mint[500],lineHeight:"24px"}),LPe=xe(Xe,{flexDirection:"row",w:360,gap:8,mb:40}),YD=xe("div",{pos:"relative",w:22,h:16,t:4,backgroundImage:`url(${IPe})`,backgroundRepeat:"no-repeat",backgroundPosition:"center"}),MPe=xe("div",{pos:"relative",w:22,h:16,t:4,backgroundImage:`url(${EPe})`,backgroundRepeat:"no-repeat",backgroundPosition:"center"}),oC=xe("div",{color:ee.gray[900],lineHeight:"24px"}),DPe=xe(Xe,{flexDirection:"column",alignItems:"flex-start",w:360,gap:4}),kPe=xe("div",{alignItems:"center",color:ee.gray[850],fontWeight:700,lineHeight:"24px"}),FPe=xe("div",{alignSelf:"stretch",color:ee.gray[550],fontSize:14,lineHeight:"20px"}),UPe=xe(Gi,{justifyContent:"space-between",p:20}),VPe=xe(J9,{w:196,h:196,radius:8,p:8,bg:xd}),GPe=q9({"0%":{transform:"rotate(0deg)"},"100%":{transform:"rotate(360deg)"}}),WPe=xe("div",{h:195,w:195,backgroundImage:`url(${hPe})`,backgroundRepeat:"no-repeat",backgroundPosition:"center",animation:`${GPe} 1.5s infinite linear`}),HPe=xe("div",{w:128,h:128,backgroundImage:`url(${mPe})`,backgroundRepeat:"no-repeat",backgroundPosition:"center"}
1190),jPe={activeModal:st.NULL,openModalCount:0},Z5=In({name:"modal",initialState:jPe,reducers:{openModal:(e,t)=>{e.activeModal=t.payload},closeModal:(e,t)=>{t.payload===e.activeModal&&(e.activeModal=st.NULL)},pushOpenModal:e=>{e.openModalCount+=1},popOpenModal:e=>{e.openModalCount=Math.max(0,e.openModalCount-1)}}}),Vxt=Z5.reducer,{openModal:zPe,closeModal:YPe,pushOpenModal:Gxt,popOpenModal:Wxt}=Z5.actions,$5=e=>ja(e).modal,QT=e=>$5(e).activeModal,Hxt=e=>QT(e)!==st.NULL||$5(e).openModalCount>0,BPe={ids:[]},ez=In({name:"msgBox",initialState:BPe,reducers:{openMsgBox:(e,t)=>{e.ids.push(t.payload)},closeMsgBox:(e,t)=>{e.ids=e.ids.filter(o=>o!==t.payload)}}}),jxt=ez.reducer,{openMsgBox:KPe,closeMsgBox:BD}=ez.actions,XPe=e=>ja(e).msgBox,JPe=e=>XPe(e).ids,qPe=e=>JPe(e).length>0,QPe="/try/assets/notify_image_close-dBa-mAf8.svg",ZPe=({title:e,scrollTarget:t})=>{const o=()=>{t?.scrollTo({top:t?.scrollHeight,left:0,behavior:"smooth"})};return b.jsxs($Pe,{onClick:o,children:[b.jsx("div",{className:"animated-arrow"}),b.jsx(Qr,{children:e})]})},$Pe=xe(Xe,{gap:8,w:"max-content",h:48,radius:12,padding:"12px 16px",alignItems:"center",userSelect:"none",position:"absolute",left:0,right:0,marginLeft:"auto",marginRight:"auto",bottom:10,fontWeight:500,fontSize:14,lineHeight:20,color:ee.purple[400],backgroundColor:ee.purple[50]}),ebe=(e,t)=>{const{isModalMsgBox:o,visibleWhenMsgBoxExist:r}=t,n=qPe(e);return{hidden:!o&&n&&!r}};class tbe extends jt.Component{bodyRef=jt.createRef();constructor(t){super(t),this.state={showScrollShadow:!1,isOpen:!0,isChecked:this.props.checkBox?.defaultChecked||!1}}componentDidMount=()=>{window.addEventListener("resize",this.updateScrollShadow),setTimeout(this.updateScrollShadow,0)};componentWillUnmount=()=>{window.removeEventListener("resize",this.updateScrollShadow),this.setState({isOpen:!1})};render(){const{className:t,headerClassName:o,contentLabel:r,children:n,showHeaderCancel:a,headerText:i,headerIconClassName:s,headerButtonName:x,onClickHeaderButton:c,showFooterButtons:l,alignCenterFooterButtons:d=!0,onExtra:u,confirmText:p,confirmTextFrontIconClassName:f,confirmTextBackIconClassName:E,cancelText:T,extraText:O,shouldCloseOnOverlayClick:S=!1,shouldCloseOnEsc:R=!0,transparentBackground:y=!1,overlayClassName:v,large:w,headerWider:N=!1,disableConfirm:M=!1,enableScrollShadow:k=!0,forceScrollText:F,extraFooter:G,extraHeader:B,hidden:W,loadingMsg:Q,loading:j,portalClassName:$,closeDelayMs:q,checkBox:H,mayExceedViewport:U,footerBanner:te,confirmDisabledTooltip:ne,confirmButtonColor:oe="blue-button"}=this.props,re=Fe(),ge=a===void 0||a,fe=M||H?.ensureCheck&&!this.state.isChecked;return b.jsxs(Q9,{className:un(Pte,`locale-${re}`,{hidden:W,transparent:y},o||""),overlayClassName:un(v?`${v} modal-overlay`:"modal-overlay",{hidden:W}),portalClassName:un($),isOpen:this.state.isOpen,contentLabel:r,ariaHideApp:!1,onRequestClose:this.onCloseModal,shouldCloseOnOverlayClick:S,shouldCloseOnEsc:R,closeTimeoutMS:q,children:[j&&b.jsxs("div",{className:"modal-dim",children:[b.jsx("div",{className:"loader"}),b.jsx("div",{className:"modal-dim-desc",children:Q})]}),i!==void 0?b.jsxs("div",{className:"modal-header",children:[x&&b.jsx("div",{className:un("header-button",x),onClick:c}),s&&b.jsx("div",{className:un("header-icon",s)}),typeof i=="string"?b.jsx("span",{className:un({large:w,headerWider:N}),children:i}):b.jsx("div",{className:"header-title-wrapper",children:i}),ge?b.jsx("button",{className:"header-cancel","aria-label":A("popup.close"),onClick:this.onCloseModal}):void 0]}):void 0,B&&b.jsx("div",{className:un("extraHeader",{large:w}),children:B}),b.jsxs("div",{className:un(`body ${t}`,{large:w,showFooterButtons:l,mayExceedViewport:U}),ref:this.bodyRef,onScroll:this.updateScrollShadow,onClick:this.updateScrollShadow,children:[n,H&&b.jsx(Nt,{mt:20,children:b.jsx(pU,{checked:this.state.isChecked,onCheckedChange:()=>this.setState(ve=>({...ve,isChecked:!ve.isChecked})),label:H.label,labelTypography:{fontSize:15}})})]}),(l||G||te)&&b.jsx("div",{className:un("not-fully-scrolled",{show:k&&this.state.showScrollShadow}),children:F&&this.state.showScrollShadow&&b.jsx(ZPe,{title:F,scrollTarget:this.bodyRef.current})}),G&&b.jsx("div",{className:un("extraFooter",{large:w}),children:G}),l&&b.jsxs("div",{className:un("footer-buttons",{"align-center":d,"align-end":!d,reverse:Mr()}),children:[p&&b.jsx(M0,{content:fe?ne:"",children:b.jsxs("button",{onClick:this.onConfirmModal,className:un(oe,{one:!T,three:O!==void 0}),disabled:fe,children:[f&&b.jsx("div",{className:f}),b.jsx("span",{children:p}),E&&b.jsx("div",{className:E})]})}),T&&b.jsx("button",{onClick:this.onCancelModal,className:un("white-button",{three:O!==void 0}),children:b.jsx("span",{children:T})}),O&&b.jsx("button",{onClick:u,className:un("white-button",{three:!0}),children:b.jsx("span",{children:O})})]}),te&&b.jsx("div",{className:un("footer-banner",{"remove-padding-top":l}),children:te})]})}updateScrollShadow=()=>
1190{if(this.bodyRef.current===null)return;const t=this.bodyRef.current.scrollHeight,o=this.bodyRef.current.clientHeight,r=this.bodyRef.current.scrollTop;this.setState({showScrollShadow:t!==o&&t-o-r>1})};handleCustomCheckBoxResult=t=>{const{checkBox:o}=this.props,{isChecked:r}=this.state;o&&o.handler(r,t)};onConfirmModal=()=>{this.handleCustomCheckBoxResult(mt.YES),this.props.onConfirm?.()};onCloseModal=async()=>{const{closeDelayMs:t,onClickHeaderCancelButton:o,onClose:r,onCancel:n}=this.props;if(o!==void 0&&await Promise.resolve(o())===K1.YES)return;this.setState({isOpen:!1}),this.handleCustomCheckBoxResult(mt.CLOSE);const a=r||n;if(a!==void 0){if(t===void 0){a();return}setTimeout(()=>{a()},t)}};onCancelModal=()=>{this.handleCustomCheckBoxResult(mt.NO),this.props.onCancel?.()}}const obe=Z9(ebe)(tbe),zxt=it.memo(({id:e,size:t,additionalHidden:o})=>{const r=it.useRef(null),n=be().getUserInfo(),a=()=>{Zz(e),Y().closeModal(st.TYPEFORM)},i=()=>{$z(e),Y().closeModal(st.TYPEFORM)},s=()=>{WUe(e),r.current?.animate([{opacity:0},{opacity:1}],{duration:500,easing:"ease-in-out",fill:"both"})};return b.jsxs(obe,{headerClassName:abe().className,className:`typeform-${t??"lg"}`,showFooterButtons:!1,transparentBackground:!0,children:[b.jsx(r1.Widget,{id:e,style:{width:"100%",height:"98%"},onReady:s,onSubmit:i,hideHeaders:!0,disableScroll:!0,autoFocus:!0,hidden:{uid:n?.uid??"NO_USER_ID",...o}}),b.jsx(M0,{content:A("popup.close"),children:b.jsx(nbe,{ref:r,onClick:a,children:b.jsx(fn,{src:QPe,w:22,h:22,maskColor:ee.gray[0]})})})]})}),rbe=({id:e,additionalHidden:t})=>{const o=be().getUserInfo(),r=it.useRef(!1),n=()=>{r.current=!0,$z(e)};return it.useEffect(()=>()=>{r.current||Zz(e)},[e]),b.jsx(r1.Widget,{id:e,style:{width:"100%",height:"98%"},onSubmit:n,hideHeaders:!0,disableScroll:!0,autoFocus:!0,hidden:{uid:o?.uid??"NO_USER_ID",...t}})},nbe=xe("button",{position:"absolute",opacity:"0",bottom:"-12%",left:"50%",transform:"translateX(-50%)",padding:"12px 12px",cursor:"pointer",borderRadius:"20px",background:zi.gray[900](.5),border:"none",display:"flex",justifyContent:"center",alignItems:"center","&:hover":{background:zi.gray[900](.7)}}),abe=n1("div",{"&.modal-content":{border:"none",borderRadius:"11px"},"&.modal-content .typeform-lg":{padding:"0",border:"none",width:"70vw",height:"70vh",display:"flex",justifyContent:"center",alignItems:"center"},"&.modal-content .typeform-sm":{width:480,height:600}}),KD=({imageSrc:e,header:t,headerIcon:o,description:r})=>b.jsxs(ibe,{children:[b.jsx(Q5,{src:e,w:322,h:176}),b.jsxs(sbe,{children:[b.jsxs(Xe,{align:"center",gap:8,children:[o&&b.jsx(Mi,{src:o,w:20,h:20}),b.jsx(xbe,{children:t})]}),b.jsx(cbe,{children:b.jsx(Qr,{children:r})})]})]}),ibe=xe(Xe,{flexDirection:"column",justifyContent:"center",w:322,h:283,border:`solid 1px ${ee.gray[125]}`,overflow:"hidden"}),sbe=xe(Xe,{flexDirection:"column",gap:12,p:"14px 12px"}),xbe=xe("span",{c:ee.gray[900],fontSize:16,fontWeight:700,lineHeight:"24px"}),cbe=xe(Nt,{c:ee.gray[650],fontSize:14,fontWeight:400,lineHeight:"20px","& > p":{m:0}}),Yxt=xe(Xe,{alignSelf:"stretch",flexDirection:"column",flexShrink:0,alignItems:"center",w:"100%",p:0,variants:{fullHeight:{true:{h:"540px"},false:{h:"420px"}},version:{v2:{justifyContent:"center"}}},compoundVariants:[{version:"v2",fullHeight:!1,css:{h:394}},{version:"v2",fullHeight:!0,css:{h:478}}],defaultVariants:{fullHeight:!1,version:"v1"}}),Bxt=20,lbe=()=>{const e=Fe(),t=q6[e];return b.jsxs(b.Fragment,{children:[b.jsx(KD,{imageSrc:t.setting,header:A("user_tts.finish_setting_title"),description:A("user_tts.finish_setting_description")}),b.jsx(KD,{imageSrc:t.tab,header:A("user_tts.finish_tab_title"),description:A("user_tts.finish_tab_description")})]})},Kxt=it.createContext({handleCloseModal:()=>{}}),Xxt=(e,t,o,r,n=-5,a=5)=>{const i=r??11;return new Array(i).fill(0).map((s,x)=>({label:x===0?e:x===i-1?t:x===Math.floor(i/2)?o:void 0,value:n+x*(a-n)/(i-1)}))},dbe=xe(Nt,{display:"flex",flexDirection:"column",alignItems:"flex-end",fontSize:"15px",lineHeight:"22.5px",span:{w:"100%",strong:{whiteSpace:"nowrap"},a:{c:ee.mint[600],textUnderlinePosition:"under"}},button:{display:"flex",alignItems:"center",h:"36px",p:"0px 12px",m:"8px 0 40px",border:"none",radiu
1190s:"8px",bg:ee.gray[100],c:ee.gray[750],fontSize:"15px",fontWeight:500,"&:hover":{bg:ee.gray[125]}}}),ube=xe(Nt,{".free-tag":{display:"inline-flex",alignItems:"center",verticalAlign:"text-bottom",height:20,mr:3,p:"0 4px",radius:4,bg:ee.green[50],c:ee.green[400],fontWeight:700,fontSize:10,userSelect:"none"}}),Jxt=e=>Math.round(e*100)+"%",pbe=(e,t)=>bU("div",{"&":t.entire,"&.modal-content .modal-header":t.header,["&.modal-content ."+e]:t.content,"&.modal-content .footer-buttons":t.footer,"&.modal-content .extraFooter":t.extraFooter,"&.modal-content .not-fully-scrolled":t.scrollZone,"&.modal-content .footer-banner":t.footerBanner});var f_=(e=>(e.SUMMARY="summary",e.HIGHLIGHT="highlight",e))(f_||{}),Jf=(e=>(e.SOURCE_VIDEO="source_video",e.GEN_ASSETS="gen_assets",e))(Jf||{}),fbe=(e=>(e.SELECT_TYPE="select_type",e.SELECT_SOURCE="select_source",e.SELECT_VOICE="select_voice",e.GENERATE="generate",e))(fbe||{});class gbe{msgBoxList;msgBoxId=0;modalProps;constructor(){this.msgBoxList=[],this.modalProps={}}getModalProps=t=>this.modalProps[t];setModalProps=(t,o)=>{this.modalProps[t]=o};dispatch=Og();openModal=(t,o)=>{this.setModalProps(t,o),this.dispatch(zPe(t))};closeModal=t=>{this.setModalProps(t,void 0),this.dispatch(YPe(t))};info(t){return this.message(A("popup.title_guide"),t)}warn(t){return this.message(A("popup.title_warning"),t)}async error(t=_.C_INVALID_ERRORCODE,o,r="general-modal",n){const a=h("modal.tsx");await Ue().printFsSummary();const i=T=>this.msgBoxList.some(O=>O.setting.errorInfo?.errorCode===T);if(t!==_.C_INVALID_ERRORCODE&&i(t))return a.info(`Duplicate error modal prevented for errorCode ${t}`),mt.CLOSE;a.info(`showing popup of errorCode ${t}`);const s=n?.subErrorCode,x=n!==void 0?JSON.stringify(Dte(n)):void 0;eS(t,x);const c=`external_link.error_${t.toLowerCase()}`,l=A(c);let d=gU.test(l)?l:void 0;if(!d){const T=Fe(),O=await si(`/get-error-url/${T}/${t.toLowerCase()}`).then(S=>{if(!S.ok)throw new Error(`status code: ${S.status}`);return S.json()}).catch(S=>a.error(`Failed to fetch error url for language ${T}/${t}: ${JSON.stringify(S)}`));O&&(O.error?a.info(`Failed getting error url for language ${T}/${t}: ${O.error}`):O.result&&(d=O.result))}d&&/^https:\/\/vreww*.imweb.me/.test(d)&&pFe(m.ERROR_MESSAGE,d);const u=d?A("popup.error_link"):Mb.includes(t)||Db.includes(t)?A("popup.send_error"):A("popup.confirm"),p=d||Db.includes(t)||Mb.includes(t)?A("popup.close"):void 0,f=typeof o=="string"?p0(o,{withLinkClickHandler:!0}):o,E=await this.show({bodyClassName:r,title:A("popup.title_error"),content:f,yesStr:u,noStr:p,errorInfo:{errorCode:t,subErrorCode:s,containExternalLink:d!==void 0}});return d&&(E===mt.YES?(pt().openUrl(d),dk(t,"open")):dk(t,"close")),E}async popup(t,o){return this.show(t,o)}getMsgBoxSetting(t){const o=this.find(t);if(o>=0)return this.msgBoxList[o]}message(t,o,r){return this.show({bodyClassName:"general-modal",title:t,content:o,yesStr:A("popup.confirm")},r)}getActiveModal=()=>{const t=ks();return t?QT(t):st.NULL};show(t,o){return new Promise(r=>{const n=s=>{this.dispatch(BD(i)),this.unregister(i)},a=o?s=>{n(),o(s,r)}:s=>{n(),r(s)},i=this.newRegister(t,a);this.dispatch(KPe(i))})}register(t,o,r){const n=this.find(t);n<0?this.msgBoxList.push({id:t,setting:o,callback:r}):this.msgBoxList[n].setting=o}newRegister(t,o){const r=this.msgBoxId;return this.msgBoxId++,this.register(r,t,o),r}unregister(t){const o=this.find(t);o>=0&&this.msgBoxList.splice(o,1)}find(t){return this.msgBoxList.findIndex(r=>
1190r.id===t)}isLastShownMessage(t){return this.msgBoxList[this.msgBoxList.length-1]?.setting===t}closeLastShownMessage(){if(this.msgBoxList.length>0){const t=this.msgBoxList[this.msgBoxList.length-1];this.dispatch(BD(t.id)),this.unregister(t.id),t.callback&&t.callback(mt.CLOSE)}}}let rC;const Y=()=>(rC||(rC=new gbe),rC),_be=e=>{const t=ir().get(e);return t===mc.YES?mc.YES:t===mc.NO?mc.NO:mc.UNDEFINED},Ebe=(e,t)=>ir().set(e,t),tz="vdrop-popup",mbe=pbe(tz,{content:{width:440,pb:32}}),oz=(e,t)=>{Y().popup({bodyClassName:`${tz} above-modal-overlay`,headerClassName:mbe().className,title:t,content:b.jsx(OPe,{...e}),showHeaderCancel:!0,showFooterButtons:!1,mayExceedViewport:!0})},qxt=async e=>{await Vn("openImportFromMobile")&&(wn(It.VDROP_USED),oz(e,A("startmode.start_with_video_and_audio_from_mobile")))},hbe=async(e,t)=>{if(!await Vn("openShareToMobile"))return;const o={type:"upload",importType:lP.TRANSFER,calledFrom:e,exportedFile:t};oz(o,A("vdrop.send_to_mobile"))},Qxt=e=>{Y().openModal(st.RECORDER,{addSceneIndex:e})},g_=e=>{Y().openModal(st.TTS,e)},Zxt=e=>{Y().openModal(st.VIDEO_REMIX,e)},$xt=()=>{Y().openModal(st.ASSET_TO_VIDEO)},uP=(e,t)=>{const o=Y();return o.getActiveModal()===st.LOGIN?(h("modal.tsx").warn("askLogin already set"),Promise.resolve("canceled")):new Promise(n=>{o.openModal(st.LOGIN,{resolve:n,isForUserDeletion:!1,desc:e,sendBootBeacon:t})})},rz=e=>{const t=e.filter(i=>i.dirty.caption).length,o=e.length,r=o-t,n=(r/o*100).toFixed(2);bke(o,r,n);const a=b.jsxs(b.Fragment,{children:[b.jsx("div",{className:"sub-title",children:A("translation.retranslation_guide_title")}),b.jsx("div",{className:"content",children:A("translation.retranslation_guide_content")})]});Y().popup({bodyClassName:"general-modal preserve-white-space retranslation-popup",title:A("popup.title_guide"),content:a,noStr:A("translation.retranslation_guide_editcaption"),yesStr:A("translation.retranslation_guide_translate")}).then(i=>{i===mt.YES&&Y().openModal(st.TRANSLATE)})},ql=e=>({bodyClassName:"general-modal",title:A("popup.title_confirm"),content:e,yesStr:A("popup.yes"),noStr:A("popup.no")}),Ibe=()=>({headerClassName:"backup-modal-header",bodyClassName:"backup-modal",title:A("popup.project_backup_title"),content:A("popup.project_backup_desc").split(`
1191`).flatMap(e=>e?b.jsx("p",{children:zCe(e,t=>{t.preventDefault(),pt().openUrl(t.currentTarget.href),NA(g.LINK)})}):b.jsx(b.Fragment,{})),yesStr:A("popup.backup_yes"),noStr:void 0}),Tbe=(e,t)=>{const o=t?e===Ke.ORIGINAL?A("caption.original_caption"):A("caption.translated_caption"):A("caption.caption"),r=(t?e===Ke.ORIGINAL?A("toolbar.original_caption_on"):A("toolbar.translated_caption_on"):A("toolbar.caption_on")).replace(`
1192`," ");return{bodyClassName:"description-modal remove-caption",title:A("caption.remove_all_caption_header",{caption:o}),content:b.jsxs("div",{className:"content",children:[b.jsx("div",{className:"msg",children:b.jsx(Qr,{children:A("caption.remove_all_caption_msg",{caption:o})})}),b.jsx("div",{className:"desc",children:b.jsx(Qr,{children:A("caption.remove_all_caption_desc",{caption:o,captionSwitchName:r})})})]}),yesStr:A("caption.remove_all_caption_confirm"),noStr:A("caption.cancel")}},nz=e=>{const t=Ps()?"app-download-modal-icon-win":Mr()?"app-download-modal-icon-mac":"app-download-modal-icon-linux",o=async()=>{await Q7(),Fke()},r=b.jsx(Qr,{className:"promote-download-body",children:e}),n=b.jsxs("div",{className:"blue-button one app-download-modal",onClick:o,children:[b.jsx("button",{className:t}),b.jsx("span",{className:"app-download-modal-text",children:A("toolbar.app_download_label")})]});return{headerClassName:"promote-download-header",title:A("popup.title_guide"),yesStr:void 0,noStr:void 0,bodyClassName:"promote-download",content:r,extraFooter:n,showFooterButtons:!1}},Sbe=(e,t=!1)=>({label:A("popup.do_not_show_again"),defaultChecked:t,handler:(o,r)=>{if(o)switch(r){case mt.YES:wn(e);break;case mt.NO:case mt.CLOSE:break}}}),Obe=e=>{const t=e.slice(e.indexOf("**")+2,e.lastIndexOf("**")),o=n=>{const i=n.target.href;i&&window.open(i),n.preventDefault()},r=b.jsxs(dbe,{onClickCapture:o,children:[p0(e.split(`
1193
1194`)[0]??""),b.jsx(Rbe,{licenseText:t}),p0(e.split(`
1195
1196`)[1]??"")]});return{title:A("tts.voicevox_license_announce_title"),content:r,yesStr:A("popup.confirm")}},Cbe=()=>({title:A("popup.title_guide"),content:b.jsx(Qr,{children:A("export.beta_export_popup_content")}),yesStr:A("popup.confirm"),noStr:A("popup.cancel")}),Rbe=({licenseText:e})=>
1196{const[t,o]=it.useState(!1),r=it.useRef(null),n=()=>{r.current&&clearTimeout(r.current),r.current=setTimeout(()=>{o(!1)},2e3),navigator.clipboard.writeText(e),o(!0)};return it.useEffect(()=>()=>{r.current&&clearTimeout(r.current)},[]),b.jsxs("button",{onClick:n,children:[b.jsx(Mi,{src:t?xL.copy.copyComplete:xL.copy.copy,w:24,h:24,color:ee.gray[400]}),t?A("tts.voicevox_license_copy_complete"):A("tts.voicevox_license_copy")]})},ect=()=>{const e={position:"relative",width:"100%",fontWeight:400,fontSize:"15px",lineHeight:"22.5px",color:ee.gray[850]},t=b.jsx(Nt,{css:e,children:p0(A("need_plan_upgrade.alternative_done_content"))}),o=b.jsxs(Xe,{direction:"column",align:"center",gap:40,children:[b.jsx(Mi,{w:120,h:120,src:LN}),t]});return{title:A("need_plan_upgrade.alternative_done_title"),content:o,yesStr:A("popup.confirm")}},Abe=(e,t,o)=>{const r=i=>{const s=i===Jf.GEN_ASSETS?o:0,x=t+s;return x===0?"":A("video_remix.show_usage",{credits:LU(Math.ceil(x))})},n=xe(Nt,{fontSize:16,fontWeight:400,".video-remix-usage-tag":{fontWeight:700,lineHeight:"20px",color:ee.mint[500]}}),a=b.jsx(n,{children:Wc(r(e))});return{title:A("popup.title_guide"),content:a,yesStr:A("popup.confirm"),noStr:A("popup.cancel")}},tct=()=>{const e=b.jsx(ube,{css:{whiteSpace:"pre-line"},children:Wc(A("quota.recommend_using_free_voice"))});return{title:A("popup.title_guide"),content:e,yesStr:A("popup.confirm")}},ybe=()=>({bodyClassName:"user-tts-guide",headerClassName:"user-tts-guide",title:A("user_tts.finish_title"),content:b.jsx(Xe,{gap:15,children:b.jsx(lbe,{})}),yesStr:A("popup.confirm"),checkBox:Sbe(It.DONT_SHOW_USER_TTS_GUIDE_AGAIN,!1)}),az=(e,t)=>({bodyClassName:"typeform",title:A("survey.popup_title"),content:b.jsx(rbe,{id:e,additionalHidden:t}),showFooterButtons:!1}),vbe=(e,t,o,r)=>{const n=gt(e);return{bodyClassName:"general-modal",title:A("bulk_transcode.ask_title"),content:A("bulk_transcode.ask_content",{TOTAL_FILE_CNT:t,UNAVAILABLE_FILE_NAME:n,UNAVAILABLE_FILE_CNT:o,TRANSCODED_FILE_NAME:Nu(n)+r}),yesStr:A("popup.transcode"),noStr:A("popup.close")}},iz=()=>({bodyClassName:"general-modal",title:A("transcode.ask_title"),content:A("transcode.ask_content"),yesStr:A("popup.transcode"),noStr:A("popup.close")}),oct=(e,t)=>
1196{const o=xe(Xe,{alignItems:"center",gap:8}),r=xe(Gi,{w:28,h:28,bg:ee.orange[50],radius:8}),n=b.jsxs(o,{children:[b.jsx(r,{children:b.jsx(qee,{size:20})}),A("need_plan_upgrade.header")]}),a=Wc(A(`need_plan_upgrade.paid_user_feature_${e}`,t));return{bodyClassName:"general-modal",title:n,content:a,yesStr:A("plan.upgrade"),noStr:A("popup.cancel")}},wbe=(e,t)=>{const o=gt(e);return{bodyClassName:"general-modal",title:A("transcode.ask_recommend_title"),content:A("transcode.ask_recommend_content",{RECOMMEND_FILE_NAME:o,RECOMMEND_FILE_CNT:t}),yesStr:A("popup.yes"),noStr:A("popup.no")}},rct=(e,t)=>({bodyClassName:"caution",title:A("export_sync_caution.header"),content:b.jsxs("div",{className:"desc-with-time",children:[b.jsx(Qr,{children:A("export_sync_caution.desc_1")}),b.jsx(Qr,{children:A("export_sync_caution.desc_2",{originalTime:os(e,!0),editedTime:os(t,!0)})}),b.jsx(Qr,{children:A("export_sync_caution.desc_3")})]}),yesStr:A("choose_export_options.confirm"),noStr:A("choose_export_options.cancel")}),sz=(e,t)=>{h("modal.tsx").error(`Failed to open url: ${t}`),Y().error(ye(e),cte(t))},Nbe=e=>{const t="export-popup",o=bU("div",{[`&.modal-content .${t}`]:{w:570,p:0},"&.modal-content .modal-header":{pb:8}}),r={title:"",content:b.jsx(wNe,{outputFile:e}),showHeaderCancel:!0,showFooterButtons:!1,headerClassName:o().className,bodyClassName:t};Y().popup(r)},OA=async e=>{const{status:t,reason:o}=await Q6();if(t==="SUPPORTED")return!1;h("modal.tsx").info(`Show browser compatibility warning in ${e}, browser support status: ${t}${o?`, reason: ${o}`:""}`),i1e("modal",t,e);const n=Y(),a=n1("div",{"&.modal-content":{display:"flex",flexDirection:"column",alignItems:"center"},"&.modal-content .modal-header":{justifyContent:"flex-start",alignSelf:"stretch",padding:"24px 28px 20px"},"&.modal-content .modal-header span":{width:"fit-content"},"&.modal-content .modal-header .header-cancel":{marginLeft:"auto"},"&.modal-content .body":{padding:"28px",width:"fit-content",minWidth:"360px"},"&.modal-content .footer-buttons":{padding:"16px 0px 28px"}}),i=b.jsx(Xe,{css:{fontWeight:400,fontSize:16,lineHeight:"24px",color:ee.gray[800],whiteSpace:"pre-wrap"},children:t==="UPDATE_RECOMMENDED"?A("browser_compatibility_warning_modal.content_need_update"):t==="HW_ACCEL_DISABLED"?A("browser_compatibility_warning_modal.content_hw_accel_disabled"):t==="OPFS_QUOTA_LOW"?A("browser_compatibility_warning_modal.content_opfs_quota_low"):A("browser_compatibility_warning_modal.content")}),s={bodyClassName:"general-modal",headerClassName:a().className,title:t==="UPDATE_RECOMMENDED"?A("browser_compatibility_warning_modal.title_need_update"):t==="HW_ACCEL_DISABLED"?A("browser_compatibility_warning_modal.title_hw_accel_disabled"):t==="OPFS_QUOTA_LOW"?A("browser_compatibility_warning_modal.title_opfs_quota_low"):A("browser_compatibility_warning_modal.title"),content:i,yesStr:A("popup.confirm")};return await n.popup(s),!0},Pbe=()=>{const e={title:A("toolbar.export_vrew_project_success"),content:b.jsx(Xe,{color:ee.gray[850],css:{fontSize:16,fontWeight:400,lineHeight:"28px",whiteSpace:"pre-wrap",paddingBottom:28},children:A("toolbar.export_vrew_project_success_description")}),yesStr:A("popup.ok"),extraFooter:b.jsxs(Xe,{justify:"space-between",align:"center",p:"16px 28px 28px",gap:8,children:[b.jsx(Zee,{onClick:Q7,ga:()=>TMe("export")}),b.jsx(Gi,{onClick:()=>Y().closeLastShownMessage(),cursor:"pointer",css:{width:176,height:40,padding:"0px 12px",color:ee.gray[0],backgroundColor:ee.mint[500],borderRadius:8,fontSize:14,lineHeight:"20px",fontWeight:500,"&:hover":{backgroundColor:ee.mint[600]}},children:A("popup.ok")})]}),showFooterButtons:!1};Y().popup(e)},nct=async()=>{const e=Y(),t={bodyClassName:"general-modal",title:A("browser_project.warn_project_delete_title"),content:A("browser_project.warn_project_delete_desc"),yesStr:A("popup.delete_project"),noStr:A("popup.cancel"),confirmButtonColor:"red-button"};return await e.popup(t)},act=async e=>{const t=Y(),o={bodyClassName:"general-modal",title:A("browser_project.warn_bulk_project_delete_title",{count:e}),content:A("browser_project.warn_bulk_project_delete_desc",{count:e}),yesStr:A("popup.delete_project"),noStr:A("popup.cancel"),confirmButtonColor:"red-button"};return await t.popup(o)},bbe=()=>{const e=vy();if(Oo()||e?.utm_campaign===void 0)return null;if(e.utm_campaign==="Vrew_Overdub_PMax_US_2508"){const o=Fe();return fm.includes(o)?rm.OVERDUB:null}else return null},Lbe=()=>bbe()!==null,ict=e=>{if(e===rm.OVERDUB)return j1.overdub},Mbe=()=>
1196!(!Dbe()||Y().getActiveModal()===st.VREW_SURVEY),Dbe=()=>{const e=Fe();return e!==ce.Spanish&&e!==ce.Taiwanese},kbe=(e,t)=>se().getEventEmitter().on(co.NEWFILE,()=>{const o=e();(o.tourInfo.type===Ct.NEW_USER_ONBOARDING&&o.currStep!==et.NEW_USER_ONBOARDING_START_MENU||o.tourInfo.type===Ct.FEATURE_ONBOARDING_OVERDUB&&o.currStep!==et.OVERDUB_ONBOARDING_START_MENU)&&t()}),Fbe=bo.HOME,xz=In({name:"activeTab",initialState:Fbe,reducers:{changeActiveTab:(e,t)=>t.payload}}),sct=xz.reducer,Ube=e=>ja(e).toolbar.activeTab,xct=e=>Ube(e)===bo.MYVREW,{changeActiveTab:cz}=xz.actions,nC=async(e,t)=>{if(t){const o=aV(t);await Y().popup(o);return}},aC=e=>e?{planName:e.planName,planType:e.planType,period:e.period,paidAt:e.paidAt,expiredAt:e.expiredAt,currentCycleStart:e.currentCycleStart,cloudStorageLimit:e.cloudStorageLimit,userTTSSpeakerLimit:e.userTTSSpeakerLimit,overdubLimit:e.overdubLimit,price:e.price,payMethod:e.payMethod,currency:e.currency,planStatus:e.planStatus,subscriptionConsentInfo:e.subscriptionConsentInfo,scheduledPrice:e.scheduledPrice}:void 0,rE={email:"",uid:"",name:"",emailVerified:!1,parentEmail:"",parentEmailVerified:!1,userAccOverdubMonthly:Wh,credits:[],planInfo:void 0},cct=async(e,t)=>{const o=h("AuthManager.ts");try{const r=await F2("/update-username",{method:"POST",body:JSON.stringify({uid:e,name:t,clientType:Xo()})}).then(n=>n.json());if(r.error)throw o.error("/update-username api failed for "+e+" : "+JSON.stringify(r)),r.error;return t}catch(r){throw o.error("/update-username api call failed for "+e+" : "+P(r)),r}},Vbe=async(e,t,o)=>{const r=h("AuthManager.ts");try{const n={deviceId:e,deviceName:t,machineId:o},a=await si("/register-device-info",{method:"POST",body:JSON.stringify(n)}).then(i=>i.json());if(a.error){r.error("registerDeviceInfo failed: "+a.error);return}return a.deviceInfo}catch(n){r.error("Cannot retrieve deviceInfo for "+e+" : "+n)}},Gbe=async(e,t,o)=>{const r=new Date().getTimezoneOffset(),n=-r,a=h("AuthManager.ts");try{const i={deviceId:e,timezoneMin:n,deviceName:t,machineId:o},s=await si("/get-device-info",{method:"POST",body:JSON.stringify(i)}).then(x=>x.json());if(s.error){a.error("getDeviceInfo failed: "+s.error);return}return a.info("deviceInfo result : "+JSON.stringify(s)),s.deviceInfo}catch(i){if(a.error("Cannot retrieve deviceInfo for "+e+" : "+P(i)),MU(i)){const s=_.C_API_GATEWAY_NETWORK_REQUEST_FAILED,x=Ot(s,{defaultKey:"error.download_failed"});Y().error(s,x)}}},Wbe=rn.throttle(async()=>{const e=h("AuthManager.ts");let t="";try{t=xt.info(A("user.deleting_user"),{autoClose:!1});const o={clientType:Xo()},r=await F2("/delete-user",{method:"POST",body:JSON.stringify(o)}).then(a=>{if(!a.ok){const i="deleteUser got status "+a.status+". statusText: "+a.statusText;throw e.error(i),br("deleteUser","error",{error:i}),new C(_.A_AUTH_DELETE_USER_ERROR,{},i)}return a.json()});if(r.error){if(r.error.errorCode===_.A_AUTH_DELETE_USER_NOT_READY)throw r.error;const a="/delete-user api failed: "+P(r.error);throw e.error(a),br("deleteUser","error",{error:a}),new C(_.A_AUTH_DELETE_USER_ERROR,{},r.error.msg)}br("deleteUser","success");const n={bodyClassName:["general-modal","text-align-center"].join(" "),headerClassName:"without-header-bar",title:A("myvrew.user_info_unregister_completed_title"),content:A("myvrew.user_info_unregister_completed_content"),yesStr:A("popup.confirm"),showHeaderCancel:!1,large:!0};await Y().popup(n),await be().signOut(!0)}catch(o){const r=ye(o)??_.A_AUTH_DELETE_USER_ERROR,n="/delete-user api call failed: "+P(o);throw e.error(n),br("deleteUser","error",{error:n}),new C(r,{},n)}finally{xt.dismiss(t)}},2e3,{trailing:!1}),lct=async(e,t)=>{const o=h("AuthManager.ts"),r={language:e,timezoneMin:t};try{const n=await F2("/send-verifying-email",{method:"POST",body:JSON.stringify(r)}).then(a=>a.json());if(n.error)throw o.error("/send-verifying-email : "+JSON.stringify(n)),new C(_.C_EMAIL_RESEND_ERROR);return{emailSent:n.emailSent,parentEmailSent:n.parentEmailSent}}catch(n){throw o.error("Cannot retrieve sendVerifyingMail. : "+P(n)),new C(_.C_EMAIL_RESEND_ERROR)}};class Hbe{prInitialized;setUserAction=()=>{};userInfo=void 0;initFuture=new Ns;hasShownHoldToast=!1;
1196versionTooLow=!1;eventEmitter=Ly();idToken=void 0;signOutRevision=0;inflightRefresh=null;constructor(){this.prInitialized=this.initFuture.promise()}getUserInfo=()=>this.userInfo;waitUntilInitialized=async()=>{await this.prInitialized};initialize=async t=>{h("AuthManager.ts").info("AuthManager.initialize() called."),this.setUserAction=t;try{return await this.autoLogin(),this.userInfo?.email}finally{this.initFuture.resolve()}};isVersionTooLow=()=>this.versionTooLow;isLoginDone=async()=>(await this.prInitialized,this.userInfo!==void 0&&this.userInfo.uid!=="");handleChannelTok=t=>{const o=Vy()||!at();if(!(Mt(ke.CHANNELTOK_ACTIVE)!==null)){const n=o;po(ke.CHANNELTOK_ACTIVE,n),n&&YFe(!0)}Zm().initialize(t)};autoLogin=async()=>{h("AuthManager.ts").info("[autoLogin] start."),await this.refreshToken("auto_sign_in").catch(r=>{Ne(r)&&r.errorCode===_.C_APP_VERSION_IS_LOW&&(this.versionTooLow=!0),h("AuthManager.ts").info("[autoLogin] no refresh token found. "+P(r))});const t=await this.fetchUserInfo(this.idToken);if(!t){h("AuthManager.ts").info("[autoLogin] no userInfo."),await this.initWithoutSignIn();return}const o={user:t,session:{idToken:this.idToken??""}};await this.signInInternal(o,{}),h("AuthManager.ts").info("[autoLogin] done.")};setIdToken=t=>{this.idToken=t};getIdToken=async()=>(await this.prInitialized,this.idToken??null);getCurrentIdToken=()=>this.idToken;signIn=async(t,o,r,n)=>{const a=Xo(),{deviceId:i,deviceName:s,machineId:x}=await Ia(),c=Fe();try{const l={email:t,password:o,clientType:a,deviceId:i,deviceName:s,machineId:x,language:c,persistSession:r},d=await Zs("/v2/sign-in",{method:"POST",body:JSON.stringify(l),credentials:"include"}).then(F=>F.json());if(d.error){const F="/sign-in api failed: "+JSON.stringify(d);h("AuthManager.ts").error(F);const G=d.error.errorCode;nC(void 0,d.maintenance),br("signIn","error",{error:F});const B=G===_.A_AUTH_LOGIN_DELETED_USER?{email:t}:void 0;throw new C(G,B,d.error.firebaseCode)}if(!d.user||!d.session){const F="/sign-in api failed. no error but user & session do not exist: "+JSON.stringify(d);throw h("AuthManager.ts").error(F),nC(void 0,d.maintenance),br("signIn","error",{error:F}),new C(_.A_AUTH_SIGNIN_ERROR)}const{email:u,uid:p,emailVerified:f,name:E,parentEmail:T,parentEmailVerified:O=!1,created:S,planInfo:R,referralInfo:y,utmParams:v,featureUsage:w,lastChat:N,lastFeedback:M}=d.user;this.setIdToken(d.session.idToken);const k=aC(R);return this.userInfo={email:u,uid:p,emailVerified:f,name:E,parentEmail:T??"",parentEmailVerified:O,created:S,credits:[],paidPlanInfo:k,referralInfo:y,utmParams:v,featureUsage:w,lastChat:N,lastFeedback:M},this.setUserAction(this.getUserActionPayload(this.userInfo)),this.handleChannelTok(XO(this.userInfo)),ba().updateCurrentUserPlan(R?.planType??"FREE"),cC(p,S,{installCode:n,utmParams:v}),this.setLastUid(p),this.setLastUidTimestamp(S),hR(!0),pt().sendSignInEvent(),br("signIn","success"),this.eventEmitter.emit(Ix.SIGN_IN),u}catch(l){const d="signIn failed "+P(l);throw h("AuthManager.ts").error(d),!Ne(l)&&br("signIn","error",{error:d}),l}};getEmailFromGoogleAccessToken=async t=>{const o={accessToken:t};try{const r=await Zs("/get-email-from-google-access-token",{method:"POST",body:JSON.stringify(o)}).then(n=>me(n,_.A_AUTH_JSONIFY_ERROR));return vl(r,"/get-email-from-google-access-token"),r.email}catch(r){return await DE("getEmail",r),void 0}};oauthSignIn=async(t,o,r,n,a,i,s,x,c)=>{let l="";try{l=xt.info(A("sign_in.signing_in"),{autoClose:!1});const d={credential:t,credentialType:o,providerId:r,clientType:Xo(),language:Fe(),referralInfo:c,throwIfNotExists:!1,persistSession:n};h("AuthManager.ts").info("/oauth-sign-in request: "+JSON.stringify(d));const u=await Zs("/v2/oauth-sign-in",{method:"POST",body:JSON.stringify(d),credentials:"include"});h("AuthManager.ts").info("/oauth-sign-in ret: "+JSON.stringify(u));const p=await me(u,_.A_AUTH_JSONIFY_ERROR);h("AuthManager.ts").info("/oauth-sign-in response: "+JSON.stringify(p)),vl(p,"/oauth-sign-in"),await this.signInInternal(p,{installCode:a,webCid:i}),br("oauthSignIn","success"),xt.dismiss(l),xt.success(A("sign_in.sign_in_success")),vR("login_success");const f=p.isSignUp;(s||f)&&await this.postProcessForSignUp(p.user?.uid??"",a,r,x)}catch(d){xt.dismiss(l),await DE("oauthSignIn",d)}};sessionSignIn=async(t,o,r,n)=>{let a="";try{a=xt.info(A("sign_in.signing_in"),{autoClose:!1});const i={sessionId:t,clientType:Xo()},s=await Zs("/get-auth-token",{method:"POST",body:JSON.stringify(i),credentials:"include"}).then(l=>me(l,_.A_AUTH_AUTH_TOKEN_ERROR));if(s.result==="error")throw new C(s.errorCode??_.A_AUTH_AUTH_TOKEN_ERROR,void 0,"Failed to get auth token: "+s.message);if(!s.idToken)throw new C(_.A_AUTH_AUTH_TOKEN_ERROR,void 0,"No idToken in response");be().setIdToken(s.idToken);const x=await be().fetchUserInfo();if(!x)throw new C(_.A_AUTH_SIGNUP_ERROR,void 0,"Failed to get user info from auth token");const c={user:x,session:{idToken:s.idToken}};await be().signInInternal(c,{installCode:o,webCid:r}),pt().sendSignInEvent(),sV().updateLoginHint(x.email),this.postProcessForSignUp(x.uid,o,"password",n),xt.dismiss(a),xt.success(A("sign_in.sign_in_success")),vR("login_success")}catch(i){xt.dismiss(a),await DE("signUp",i)}};signInInternal=async(t,o)=>{AR(t),xV(t),yR(t);const{email:r,uid:n,emailVerified:a,name:i,parentEmail:s,parentEmailVerified:x=!1,created:c,planInfo:l,referralInfo:d,utmParam
1196s:u,featureUsage:p,lastChat:f,lastFeedback:E,credits:T}=t.user;this.setIdToken(t.session?.idToken),this.userInfo={email:r,uid:n,emailVerified:a,name:i,parentEmail:s??"",parentEmailVerified:x,created:c,credits:T??[],paidPlanInfo:aC(l),referralInfo:d,utmParams:u,featureUsage:p,lastChat:f,lastFeedback:E},this.setUserAction(this.getUserActionPayload(this.userInfo)),this.handleChannelTok(XO(this.userInfo)),ba().updateCurrentUserPlan(l?.planType??"FREE");const O=await _g();O&&!O.webCid&&o.webCid&&await SR(Ps(),O.cid,O.timestamp??new Date().toISOString(),o.webCid),cC(n,c,{...o,utmParams:u}),this.setLastUid(n),this.setLastUidTimestamp(c),hR(!0),this.eventEmitter.emit(Ix.SIGN_IN)};forceRefreshIdToken=async()=>(!this.inflightRefresh&&(this.inflightRefresh=this.refreshToken("refresh_token").finally(()=>{this.inflightRefresh=null})),this.inflightRefresh);getEventEmitter=()=>this.eventEmitter;refreshToken=async(t,o)=>{const{deviceId:r,deviceName:n,machineId:a}=await Ia(),i=Fe(),s=pt(),x=s.getWindowId(),c=s.getWindowCount(),l={clientType:Xo(),deviceId:r,deviceName:n,machineId:a,language:i,overwriteToken:o,refreshFor:t,windowId:x,windowCount:c,clientRequestedAt:new Date().toISOString()},d=await Zs("/v2/refresh-token",{method:"POST",body:JSON.stringify(l),credentials:"include"}).then(u=>me(u,_.A_AUTH_JSONIFY_ERROR));if(vl(d,"/v2/refresh-token"),yR(d),!d.session?.idToken)throw new C(_.A_AUTH_REFRESH_TOKEN_ERROR,void 0,"/v2/refresh-token api failed: no idToken in response");this.setIdToken(d.session.idToken),br("refresh","success")};refreshTokenDebugCommand=()=>{this.forceRefreshIdToken()};sendPasswordResetEmail=async t=>{const o=Fe(),r=await Zs("/reset-password",{method:"POST",body:JSON.stringify({email:t,lang:o})}).then(n=>n.json());vl(r,"/reset-password"),r.email&&h("AuthManager.ts").info("Email: "+r.email+" reset"),br("resetPassword","success")};signOut=async t=>{if(this.userInfo){if(this.signOutRevision+=1,t){const o={clientType:Xo()};mD("/sign-out",{method:"POST",body:JSON.stringify(o),credentials:"include"},this.getCurrentIdToken()).then(r=>me(r,_.A_AUTH_JSONIFY_ERROR)).then(r=>{if(r.result==="error")throw new C(_.A_AUTH_SIGN_OUT_ERROR,void 0,r.error.msg);h("AuthManager.ts").info("[signOut] Removed VREW_RTK cookie"),br("signOut","success")}).catch(r=>{h("AuthManager.ts").error(r.message),br("signOut","error",{error:r.message})})}this.setIdToken(void 0),this.userInfo=void 0,this.setUserAction(rE),this.setLastUid(""),this.setLastUidTimestamp(""),cC(rE.uid??"",""),this.handleChannelTok(null),ba().updateCurrentUserPlan("FREE"),this.eventEmitter.emit(Ix.SIGN_OUT),pt().sendSignOutEvent()}};updatePassword=async(t,o,r)=>{const n=h("AuthManager.ts"),a=await this.reauth(t,o),i=await this.getIdToken();if(a===void 0){const s="reauth api calling failed during updatePassword()";throw n.error(s),br("updatePassword","error",{error:s}),new C(_.A_AUTH_PASSWORD_UPDATE_ERROR)}if(a.error){const s="reauth api failed during updatePassword(): "+P(a.error);throw n.error(s),br("updatePassword","error",{error:s}),new C(_.A_AUTH_PASSWORD_UPDATE_ERROR,void 0,a.error.firebaseCode)}if(!i){n.warn("No valid idToken during updatePassword()");return}try{const s={idToken:i,newPassword:r,clientType:Xo()},x=await Zs("/v2/update-password",{method:"POST",body:JSON.stringify(s),credentials:"include"}).then(c=>c.json());if(x.error){const c="/update-password api failed: "+JSON.stringify(x);n.error(c);const l=x.error.errorCode;throw br("updatePassword","error",{error:c}),nC(void 0,x.maintenance),new C(l)}n.info("/update-password api result: "+JSON.stringify(x)),x.session&&this.setIdToken(x.session.idToken),br("updatePassword","success")}catch(s){const x="update password failed "+P(s);h("AuthManager.ts").error(x),!Ne(s)&&br("updatePassword","error",{error:x});const c=ye(s)??_.A_AUTH_PASSWORD_UPDATE_ERROR;throw new C(c)}};reauth=async(t,o)=>{const r=h("AuthManager.ts");try{const n=await Zs("/reauth",{method:"POST",body:JSON.stringify({email:t,password:o})}).then(a=>{if(!a.ok){const i="reauth got status "+a.status+". statusText: "+a.statusText;throw r.error(i),br("reauth","error",{error:i}),new C(_.A_AUTH_REAUTH_ERROR,{},i)}return a.json()});return n.success&&n.session&&this.setIdToken(n.session.idToken),r.info("/reauth api result: "+JSON.stringify(n)),br("reauth","success"),n}catch(n){const a="/reauth api failed "+P(n);r.error(a),!Ne(n)&&br("reauth","error",{error:a});return}};fetchSignUpProviderIdFromDatabase=async t=>{const o=h("AuthManager.ts");if(!t)return o.warn("email is not provided"),void 0;const r=await Zs("/fetch-sign-up-provider-id-from-database",{method:"POST",body:JSON.stringify({email:t})}).then(n=>me(n,_.A_AUTH_JSONIFY_ERROR));return vl(r,"/fetch-sign-up-provider-id-from-database"),o.info("/fetch-sign-up-provider-id-from-database api result: "+JSON.stringify(r)),br("fetchSignUpProviderIdFromDatabase","success",{providerId:r.providerId}),r.providerId};initWithoutSignIn=async()=>{h("AuthManager.ts").info("[initWithoutSignIn] start."),this.setLastUid(""),this.setLastUidTimestamp("");const t=await Ia();let o=await Gbe(t.deviceId,t.deviceName,t.machineId);!o&&(o=await Vbe(t.deviceId,t.deviceName,t.machineId));const r={...rE};this.setUserAction(q7(r)),this.handleChannelTok(null),ba().initialize("FREE")};setLastUid=t=>{Ve().set(Ie.LAST_UID,t)};setLastUidTimestamp=t=>{Ve().set(Ie.LAST_UID_TIMESTAMP,t)};fetchUserInfo=async t=>{const o=h("AuthManager.ts"),r=this.signOutRevision,n=t??this.idToken;if(!n)return o.info("No valid idToken: "+n),void 0;try{const a={clientType:Xo()},i={method:"POST",body:JSON.stringify(a)},s=await(t?mD("/get-user-info",i,t):F2("/get-user-info",i)).then(x=>me(x,_.A_AUTH_JSONIFY_ERROR));if(o.info("userInfo result : "+JSON.stringify(s)),AR(s),vl(s,"/get-user-info"),s.user){const{email:x,uid:c,emailVerified:l,name:d,parentEmail:u,parentEmailVerified:p=!1,created:f,planInfo:E,referralInfo:T,lastChat:O,lastFeedback:S,utmParam
1196s:R,featureUsage:y,credits:v}=s.user;if(r!==this.signOutRevision)return o.info("[fetchUserInfo] Skip stale response"),void 0;const w=aC(E);E?.planStatus==="HOLD"&&!this.hasShownHoldToast&&(xt.warn(A("payment.plan_hold_warning",{expiredAt:na.fromISO(E.expiredAt).setLocale(Fe()).toLocaleString(na.DATE_SHORT)})),this.hasShownHoldToast=!0),Kne(v??[],E!==void 0),this.userInfo={email:x,uid:c,emailVerified:l,name:d,parentEmail:u??"",parentEmailVerified:p,created:f,credits:v??[],paidPlanInfo:w,referralInfo:T?{referralType:T.referralType,referralCode:T.referralCode}:void 0,lastChat:O,lastFeedback:S,utmParams:R,featureUsage:y},Zm().updateUser(XO(this.userInfo)),ba().updateCurrentUserPlan(this.userInfo.paidPlanInfo?.planType??"FREE"),this.setUserAction(this.getUserActionPayload(this.userInfo)),this.eventEmitter.emit(Ix.USER_INFO_UPDATED)}return s.user}catch(a){if(ye(a)===_.C_UPLOAD_SERVER_MAINTENANCE)throw a;if(o.error("Cannot retrieve userInfo : "+P(a)),MU(a))throw new C(_.C_API_GATEWAY_NETWORK_REQUEST_FAILED)}};getUserActionPayload=t=>{const{paidPlanInfo:o}=t;return{...rE,uid:t.uid,name:t.name,email:t.email,parentEmail:t.parentEmail,emailVerified:t.emailVerified,parentEmailVerified:t.parentEmailVerified,userAccOverdubMonthly:t.featureUsage.accOverdubMonthly,userTrialAccOverdub:t.featureUsage.trialAccOverdub,userCloudStorageLimit:o?.cloudStorageLimit??y1,userTTSSpeakerLimit:o?.userTTSSpeakerLimit??v1,userOverdubLimit:o?.overdubLimit??Wh,credits:t.credits??[],planInfo:o?{planName:o.planName,planType:o.planType,period:o.period,paidAt:o.paidAt,expiredAt:o.expiredAt,currentCycleStart:o.currentCycleStart,price:o.price,payMethod:o.payMethod,currency:o.currency,planStatus:o.planStatus,scheduledPrice:o.scheduledPrice,subscriptionConsentInfo:o.subscriptionConsentInfo}:void 0}};postProcessForSignUp=async(t,o,r,n)=>{const a=Ve().getArray(Ie.SIGNED_UP_UIDS),i=this.getUserInfo(),s=i&&(!i.emailVerified||i.parentEmail&&!i.parentEmailVerified);!a.includes(t)&&(Ve().set(Ie.SIGNED_UP_UIDS,[...a,t]),!Lbe()&&Y().openModal(st.VREW_SURVEY,{type:"onboarding"})),wn(It.MEMBER_REGISTER),n!==void 0&&gRe(n);const x=be().getUserInfo()?.referralInfo?.referralType;Rte(x),s&&Og()?.(cz(bo.MYVREW)),I().event(m.AUTH,g.SIGNUP,void 0,void 0,JSON.stringify({uid:t,installCode:o,providerId:r}))}}let nf,iC;const jbe=()=>(!nf&&(nf=new Hbe),nf),dct=e=>(h("AuthManager.ts").info("initAuthManager called."),!iC&&(iC=jbe().initialize(e)),iC),be=()=>{if(!nf)throw h("AuthManager.ts").error("No authmanager detected."),new C(_.C_LOGIC_ERROR,{},"No auth manager");return nf},wo=async()=>!!await be().getIdToken(),yr=async(e,t,o)=>{if(!await wo())throw o.error(t),new C(e,{},t)};class zbe{type=Lr.ANONYMOUS;cid="redacted";uid="redacted";enabled=!1;osName="";eventQueue=[];eventTimer=void 0;initialize=(t,o,r,n,a,i,s,x,c,l,d,u,p)=>{this.enabled=!0,this.osName=bx(),this.eventQueue=[],this.eventTimer=void 0};disable=()=>{this.enabled=!1};updateInfo=async(t,o,r)=>{};getGAProjectType=()=>{const t=se();if(!t.isEmpty())return t.isDemo()?"demo":t.isProjectSaved()?"saved":"temp"};event=async(t,o,r,n,a)=>{if(!this.enabled)return;const i=be().getUserInfo()?.paidPlanInfo?.planType,s=i??"FREE",x=this.uid,c=Fe(),l=this.getGAProjectType(),d={cid:this.cid,clientTimestamp:new Date().toISOString(),category:t,action:o,label:r,value:n,customValue:a,uid:x,osName:this.osName,projectSavedType:l,language:c,planType:s};this.eventQueue.push(d),this.eventQueue.length>=DU?(this.eventTimer!==void 0&&(clearTimeout(this.eventTimer),this.eventTimer=void 0),this.flush()):this.eventTimer===void 0&&(this.eventTimer=setTimeout(this.flush,kU*1e3))};flush=async()=>{if(this.eventTimer=void 0,this.eventQueue.length>0){const t=[...this.eventQueue],o=Xo();this.eventQueue=[];const r={events:t,clientType:o};try{await si("/analytics-v2",{method:"POST",body:JSON.stringify(r)})}catch(n){const a="failed to send anonymous analytics: "+P(n);h("anonymous.ts").warn(a)}}}}class Ybe{type=Lr.CHANNELTOK_GA;initialized;resolveInitialize=null;constructor(){this.initialized=new Promise(t=>{this.resolveInitialize=t})}initialize=(t,o,r,n,a,i,s,x,c,l,d,u,p)=>{this.resolveInitialize(!0)};disable=()=>{this.resolveInitialize(!1)};event=async(t,o,r,n,a)=>{await this.initialized!==!1&&Zm().GA(t,o,r,Bbe(t,o,r,n,a))};updateInfo=(t,o,r)=>{};flush=async()=>{}}const Bbe=(e,t,o,r,n)=>{let a;if(n===void 0)a=void 0;else try{a=JSON.parse(n)}catch{a=void 0}switch(e){case m.VA_EXPORT:{if(t!==g.VA_UNIVERSAL_EXPORT||a===void 0)return{};const i=a.exportDuration;return{startMode:a.startMode,exportType:a.exportType,exportDuration_sec:i*60,exportDuration_min:i,numExportClips:a.numExportClips,numScenes:a.numScenes,projectSavedType:a.projectSavedType,freeAssetVideoCount:a.freeAssetVideoCount,userAssetVideoCount:a.userAssetVideoCount,selectedVideoRatio:a.selectedVideoRatio,numUniqueCaptionSetting:a.numUniqueCaptionSetting,numTTS:a.numTTS,numSoundFX:a.numSoundFX,numBGM:a.numBGM,numCharacters:a.numCharacters,numUserCharacters:a.numUserCharacters,numRecords:a.numRecords}}case m.ERROR:{const i={errorType:t,errorCode:o};switch(t){case g.ERROR_IMPORT:case g.ERROR_EXPORT:case g.ERROR_AUDIO_ANALYSIS:case g.ERROR_LOGIN:return i;case g.ERROR_CODE:return{errorCode:o,errorMsg:n};default:return{errorType:t}}}case m.INIT:return t!==g.INIT_INFO?{}:a;case m.AUDIO_ANALYSIS:return{action:t,selectedSttTier:a.selectedSttTier,requestedSttEngine:a.requestedSttEngine,countsOfAppliedSttEngines:a.countsOfAppliedSttEngines};case m.TOOLBAR_COMMON:case m.TOOLBAR_HELP:return{action:t};case m.AUTH:return t===g.SIGNUP?{providerId:a.providerId}:{};case m.START_NEW_PROJECT:return t!==g.NEW_PROJECT_STARTED||a===void 0?{}:{startMode:a.startMode};default:return{}}},lz=1e3,ih="KRW",dz=new Map([[m.AUTH+"@"+g.SIGNUP,1e3],[m.EXPORT+"@"+g.NEW_EXPORT_START,2e4],[m.KEY_EDIT+"@"+g.UNDO,1e3],[m.SEEKBAR+"@"+g.SEEKBAR_HOVER,1e3],[m.SELECT_CLIP+"@"+g.CLICK_CHECKBOX,1e3],[m.START_NEW_PROJECT+"@"+g.NEW_PROJECT_STARTED,1e3],[m.TOOLBAR_COMMON+"@"+g.CLICK_DOWNLOAD_APP,5e3],[m.TOOLBAR_COMMON+"@"+g.MENU_EDIT,1e3],[m.TOOLBAR_COMMON+"@"+g.MENU_HELP,1e3]]);var Kbe=(e=>(e.PAGE_VIEW="PageView",e.ADD_PAYMENT_INFO="AddPaymentInfo",e.ADD_TO_CART="AddToCart",e.ADD_TO_WISHLIST="AddToWishlist",e.COMPLETE_REGISTRATION="CompleteRegistration",e.CONTACT="Contact",e.CUSTOMIZE_PRODUCT="CustomizeProduct",e.DONATE="Donate",e.FIND_LOCATION="FindLocation",e.INITIATE_CHECKOUT="InitiateCheckout",e.LEAD="Lead",e.PURCHASE="Purchase",e.SCHEDULE="Schedule",e.SEARCH="Search",e.START_TRIAL="StartTrial",e.SUBMIT_APPLICATION="SubmitApplication",e.SUBSCRIBE="Subscribe",e.VIEW_CONTENT="ViewContent",e))(Kbe||{});const Xbe={[m.AUTH]:{[g.SIGNUP]:"CompleteRegistration"},[m.PREMIUM_FEATURE]:{[g.GO_TO_UPGRADE]:"InitiateCheckout"}};class Jbe{type=Lr.META_PIXEL;enabled=!1;uid="";
1196transformStandardEventParams=(t,o)=>{switch(t){case"CompleteRegistration":return{value:lz,currency:ih,...o};case"InitiateCheckout":return{...o};default:return h("metaPixel.ts").warn("[MetaPixel] Unhandled standard event type: "+t),o}};initialize=(t,o,r,n,a,i,s,x,c,l,d,u,p)=>{if(this.enabled)return;this.uid=n;const f=fr.level===Xr.Release?pR.meta.prod.pixelId:pR.meta.dev.pixelId,E=document.createElement("script");E.innerHTML=`
1197      !function(f,b,e,v,n,t,s)
1198      {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
1199      n.callMethod.apply(n,arguments):n.queue.push(arguments)};
1200      if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
1201      n.queue=[];t=b.createElement(e);t.async=!0;
1202      t.src=v;s=b.getElementsByTagName(e)[0];
1203      s.parentNode.insertBefore(t,s)}(window, document,'script',
1204      'https://connect.facebook.net/en_US/fbevents.js');
1205      fbq('init', '`+f+"', "+JSON.stringify({external_id:this.uid})+`);
1206      fbq('track', 'PageView');
1207    `,E.onerror=()=>{h("metaPixel.ts").info("[MetaPixel] Failed to load Meta Pixel script"),this.disable()},document.head.appendChild(E);const T=document.createElement("noscript"),O=document.createElement("img");O.height=1,O.width=1,O.style.display="none",O.src="https://www.facebook.com/tr?id="+f+"&ev=PageView&noscript=1",T.appendChild(O),document.head.appendChild(T),this.enabled=!0};disable=()=>{this.enabled=!1};getEventName=(t,o)=>t+"@"+o;event=async(t,o,r,n,a)=>{if(!this.enabled||!window.fbq)return;const i=Xbe[t]?.[o],s=YN(a);if(i){const x=this.transformStandardEventParams(i,s);window.fbq("track",i,x)}else{r!==void 0&&(s.label=r),n!==void 0&&(s.eventValue=n);const x=this.getEventName(t,o),c=dz.get(x);c&&(s.value=c,s.currency=ih),window.fbq("trackCustom",x,s)}};updateInfo=(t,o,r)=>{this.uid=t};flush=async()=>{}}var qbe=(e=>(e.PAGE_VISIT="PageVisit",e.VIEW_CONTENT="ViewContent",e.SEARCH="Search",e.ADD_TO_CART="AddToCart",e.ADD_TO_WISHLIST="AddToWishlist",e.PURCHASE="Purchase",e.LEAD="Lead",e.SIGN_UP="SignUp",e.CUSTOM="Custom",e))(qbe||{});const Qbe={[m.AUTH]:{[g.SIGNUP]:"SignUp"}};class Zbe{type=Lr.REDDIT_PIXEL;enabled=!1;uid="";transformStandardEventParams=(t,o)=>{switch(t){case"Purchase":{const{currency:r,amount:n}=o;return{value:n,currency:r}}case"SignUp":return{value:lz,currency:ih};default:return h("redditPixel.ts").warn("[RedditPixel] Unhandled standard event type: "+t),o}};initialize=(t,o,r,n,a,i,s,x,c,l,d,u,p)=>{if(this.enabled)return;this.uid=n;const f=pR.reddit.prod.pixelId,E=document.createElement("script");E.innerHTML=`
1208      !function(w,d)
1209      {if(!w.rdt){var p=w.rdt=function(){p.sendEvent?p.sendEvent.apply(p,arguments):p.callQueue.push(arguments)};
1210      p.callQueue=[];var t=d.createElement("script");
1211      t.src="https://www.redditstatic.com/ads/pixel.js",
1212      t.async=!0;var s=d.getElementsByTagName("script")[0];
1213      s.parentNode.insertBefore(t,s)}}(window,document);
1214      rdt('init','`+f+`');
1215      rdt('track', 'PageVisit');
1216    `,E.onerror=()=>{h("redditPixel.ts").info("[RedditPixel] Failed to load Reddit Pixel script"),this.disable()},document.head.appendChild(E),this.enabled=!0};disable=()=>{this.enabled=!1};getEventName=(t,o)=>t+"@"+o;event=async(t,o,r,n,a)=>{if(!this.enabled||!window.rdt)return;const i=Qbe[t]?.[o],s=YN(a);if(i){const x=this.transformStandardEventParams(i,s);window.rdt("track",i,{...x,externalId:this.uid})}else{const x=this.getEventName(t,o),c=dz.get(x);c&&(s.value=c,s.currency=ih),window.rdt("track","Custom",{customEventName:x,...s,externalId:this.uid})}};updateInfo=(t,o,r)=>{this.uid=t};flush=async()=>{}}class $be{type=Lr.BROWSER_GA;initialized;resolveInitialize=null;constructor(){this.initialized=new Promise(t=>{this.resolveInitialize=t})}initialize=(t,o,r,n,a,i,s,x,c,l,d,u,p)=>{const f=kh[t].uaTagId;JS.initialize(f,{gaOptions:{clientId:o,userId:n||void 0}}),JS.pageview(i),this.resolveInitialize(!0)};updateInfo=(t,o,r)=>{};disable=()=>{this.resolveInitialize(!1)};event=async(t,o,r,n)=>{await this.initialized!==!1&&JS.event({action:o,category:t,label:r,value:n})};flush=async()=>{}}const eLe="https://www.google-analytics.com/mp/collect",tLe=25,oLe=5;class rLe{type=Lr.GA4;uid;enabled=!0;cid;endPoint="";eventTimer=void 0;eventQueue=[];initialize=(t,o,r,n,a,i,s,x,c,l,d,u,p)=>{this.cid=o,this.uid=n;const{measurementId:f,secretKey:E}=kh[t];this.endPoint=eLe+"?measurement_id="+f+"&api_secret="+E};updateInfo=async(t,o,r)=>{this.uid=t};getEventName(t,o){return t+"__"+o}disable=()=>{this.enabled=!1};event=async(t,o,r,n)=>{if(!this.enabled)return;const a=this.getEventName(t,o),i={name:a,params:{engagement_time_msec:1}};r!==void 0&&(i.params.label=r),n!==void 0&&(i.params.value=n);const s=fRe();if(s&&(i.params.gclid=s),this.eventQueue.push(i),this.eventQueue.length===tLe){await this.flush();return}this.eventTimer===void 0&&(this.eventTimer=setTimeout(this.flush,oLe*1e3))};flush=async()=>{this.eventTimer!==void 0&&(clearTimeout(this.eventTimer),this.eventTimer=void 0);const t=this.eventQueue;this.eventQueue=[];const o=this.endPoint,r={client_id:this.cid,events:t};this.uid&&(r.user_id=this.uid);const n=JSON.stringify(r);try{await fetch(o,{method:"POST",body:n})}catch(a){h("ga4.ts").warn("sending ga4 event failed:"+P(a))}}}class nLe{type=Lr.GTAG;enabled=!0;initStatus="PENDING";eventQueue=[];initialize=(t,o,r,n,a,i,s,x,c,l,d,u,p)=>
1216{if(this.initStatus==="INITIALIZED")return;this.eventQueue=[];const{measurementId:f}=kh[t],{measurementId:E}=Z6[t];if(!f)return;const T=document.createElement("script");T.async=!0,T.src="https://www.googletagmanager.com/gtag/js?id="+f,T.onload=()=>{const O=document.createElement("script");O.innerHTML=`
1217        window.dataLayer = window.dataLayer || [];
1218        function gtag(){dataLayer.push(arguments);}
1219        gtag('js', new Date());
1220        gtag('config', '`+f+`', {
1221          'uid': '`+n+`',
1222          'cid': '`+o+`',
1223        });
1224        gtag('config', '`+E+`', {
1225          'uid': '`+n+`',
1226          'cid': '`+o+`',
1227        });
1228      `,document.head.appendChild(O),this.initStatus="INITIALIZED",this.eventQueue.forEach(S=>{this.event(S.category,S.action,S.label,S.value)}),this.eventQueue=[]},T.onerror=O=>{h("gtag.ts").info(`
1229        [GTag] Failed to load gtag.ts script.
1230          error: `+O+`
1231        `),this.initStatus="INITIALIZED",this.disable(),this.eventQueue=[]},document.head.appendChild(T)};updateInfo=async(t,o,r)=>{!this.enabled||this.initStatus!=="INITIALIZED"||window.gtag("set",{user_id:t})};getEventName(t,o){return t+"__"+o}disable=()=>{this.enabled=!1};event=async(t,o,r,n)=>{if(!this.enabled)return;if(this.initStatus==="PENDING"){this.eventQueue.push({category:t,action:o,label:r,value:n});return}const a={};r!==void 0&&(a.label=r),n!==void 0&&(a.value=n);const i=this.getEventName(t,o);window.gtag("event",i,a)};flush=async()=>{}}class aLe{type=Lr.LOCAL_GA;visitor=null;initialized;resolveInitialize=null;isFilteredCid=!1;filterStartDate=new Date("2020/05/31 15:00:00Z");campaignMedium;constructor(){this.initialized=new Promise(t=>{this.resolveInitialize=t})}initialize=(t,o,r,n,a,i,s,x,c,l,d,u,p)=>{this.campaignMedium=s||void 0;const f=kh[t].uaTagId;try{this.visitor=n?Yb(f,o,{uid:n}):Yb(f,o),this.visitor.pageview({dp:i,cm:this.campaignMedium}).send(),this.resolveInitialize(!0),this.isFilteredCid=this.getSampleFiltered(o)}catch(E){h("local.ts").error("ga initialize failed, "+P(E)),this.resolveInitialize(!1)}};updateInfo=async(t,o,r)=>{};disable=()=>{this.resolveInitialize(!1)};event=async(t,o,r,n)=>{if(await this.initialized===!1)return;if(!this.visitor){h("local.ts").error("ga initialize but no visitor");return}let i=!0;if(this.isFilteredCid&&this.isFilterActivateDate()){const s=$6[t];i=s&&s.has(o)}i&&this.visitor.event({ec:t,ea:o,el:r,ev:n,cm:this.campaignMedium}).send()};getSampleFiltered=t=>{if(fr.level!==Xr.Release)return h("local.ts").info("cid "+t+" is not filtered for ga: "+fr.level+"."),!1;const o=t.substr(0,2)>"4c";return h("local.ts").info("cid "+t+" is "+(o?"":"not ")+"filtered for GA."),o};isFilterActivateDate=()=>!(new Date<this.filterStartDate);flush=async()=>{}}const iLe=1800*1e3;var sLe=(e=>(e.NEW_SESSION="new_session",e))(sLe||{}),xLe=(e=>(e.EDIT_ACTIVITY="EDIT_ACTIVITY",e.GA_ACTIVITY="GA_ACTIVITY",e))(xLe||{});class cLe{sessionId=void 0;enabled=!1;mostRecentInteraction=Date.now();eventEmitter=new ad.EventEmitter;constructor(){this.sessionId=ir().get(Wt.SESSION_ID)||qe.v4(),this.enabled=!0,this.mostRecentInteraction=Date.now()}createNewSession=()=>{this.enabled&&(this.sessionId=qe.v4(),ir().set(Wt.SESSION_ID,this.sessionId),this.eventEmitter.emit("new_session"))};notifyInteraction=()=>{const t=Date.now();t-this.mostRecentInteraction>=iLe&&this.createNewSession(),this.mostRecentInteraction=t};getSessionId=()=>this.enabled?this.sessionId:void 0;getEventEmitter=()=>this.eventEmitter;disable=()=>{this.enabled=!1};getMostRecentInteraction=()=>this.mostRecentInteraction}let sC;const xC=()=>(!sC&&(sC=new cLe),sC);class lLe{type=Lr.VREW_ANALYTICS;enabled=!1;cid="";uid="";cidTimestamp="";uidTimestamp="";installCode="";osName="";deviceId="";machineId="";utmParams=void 0;webCid=void 0;browserName="";browserVersion="";eventQueue=[];eventTimer=void 0;initialize=(t,o,r,n,a,i,s,x,c,l,d,u,p)=>{this.enabled=!0,this.cid=o,this.cidTimestamp=r,this.uid=n,this.uidTimestamp=a,this.installCode=s,this.osName=bx(),this.deviceId=x,this.machineId=c,this.browserName=l,this.browserVersion=d,this.eventQueue=[],this.eventTimer=void 0,this.utmParam
1231s=u,this.webCid=p};disable=()=>{this.enabled=!1,xC().disable()};updateInfo=async(t,o,r)=>{this.enabled&&(this.uid=t,this.uidTimestamp=o,"installCode"in r&&r.installCode!==void 0&&(this.installCode=r.installCode),"utmParams"in r&&(this.utmParams=r.utmParams),"webCid"in r&&(this.webCid=r.webCid))};getGAProjectType=()=>{const t=se();if(!t.isEmpty())return t.isDemo()?"demo":t.isProjectSaved()?"saved":"temp"};event=async(t,o,r,n,a)=>{if(!this.enabled)return;xC().notifyInteraction();const i=be().getUserInfo()?.paidPlanInfo?.planType,s=i??"FREE",x=this.uid,c=ERe(this.uidTimestamp)?this.uidTimestamp:void 0,l=se().getProjectId(),d=Fe(),u=this.getGAProjectType(),p={cid:this.cid,cidTimestamp:this.cidTimestamp,clientTimestamp:new Date().toISOString(),category:t,action:o,label:r,value:n,customValue:a,uid:x,uidTimestamp:c,projectId:l,sessionId:xC().getSessionId(),installCode:this.installCode,osName:this.osName,deviceId:this.deviceId,machineId:this.machineId,projectSavedType:u,language:d,planType:s,...this.utmParams,webCid:this.webCid};at()===!1&&(p.browserName=this.browserName,p.browserVersion=this.browserVersion),this.eventQueue.push(p),this.eventQueue.length>=DU?(this.eventTimer!==void 0&&clearTimeout(this.eventTimer),this.flush()):this.eventTimer===void 0&&(this.eventTimer=setTimeout(this.flush,kU*1e3))};flush=async()=>{if(this.eventTimer=void 0,this.eventQueue.length>0){const t=[...this.eventQueue],o=Xo();this.eventQueue=[];const r={events:t,clientType:o};try{await si("/analytics-v2",{method:"POST",body:JSON.stringify(r)})}catch(n){h("va.ts").warn("post failed, "+P(n))}}}}class dLe{prtLog=!1;init(){Mo().on(Xt.GA,()=>{this.prtLog=!this.prtLog})}log(t,o,r,n,a){if(this.prtLog){window.console.log("[GA]",t,o,r,n,a);const i=[t,o,r,n,a].filter(s=>s);wSe(i)}}}class hc{type=Lr.ANALYTICS_MANAGER;providers;gaLogger;initialized;resolveInitialize=null;static _instance=null;static get instance(){return hc._instance===null&&(hc._instance=new hc([at()?new aLe:new $be,at()?new rLe:new nLe,new lLe,new Ybe,new P7,new zbe,new Jbe,new Zbe],new dLe)),hc._instance}constructor(t,o){if(hc._instance!==null)throw new Error("Cannot use multiple instances of AnalyticsManager.");o.init(),this.gaLogger=o,this.providers=t,this.initialized=new Promise(r=>{this.resolveInitialize=r})}initialize=(t,o,r,n,a,i,s,x,c,l,d,u,p)=>{this.providers.forEach(f=>{try{f.initialize(t,o,r,n,a,i,s,x,c,l,d,u,p)}catch(E){h("analyticsManager.ts").error("ga type "+f.type+" initialization failed: "+P(E))}}),this.resolveInitialize(!0)};updateInfo=(t,o,r)=>{this.providers.forEach(n=>{try{n.updateInfo(t,o,r)}catch(a){h("analyticsManager.ts").error("ga type "+n.type+" update failed: "+P(a))}})};disable=()=>{this.providers.forEach(t=>t.disable()),this.resolveInitialize(!1)};event=async(t,o,r,n,a)=>{this.gaLogger.log(t,o,r,n,a),await this.initialized!==!1&&this.providers.forEach(s=>{try{switch(s.type){case Lr.BROWSER_GA:case Lr.LOCAL_GA:case Lr.GA4:case Lr.GTAG:{const x=r9[t];if(x===!0||x&&x[o]===!0)return;s.event(t,o,r,n);break}case Lr.VREW_ANALYTICS:{const x=o9[t];if(x===!0||x&&x[o]===!0)return;s.event(t,o,r,n,a);break}case Lr.CHANNELTOK_GA:{s.event(t,o,r,n,a);break}case Lr.AMPLITUDE:s.event(t,o,r,n,a);break;case Lr.ANONYMOUS:{const x=t9[t];(x===!0||x&&x[o]===!0)&&s.event(t,o,r,n,a);break}case Lr.ANALYTICS_MANAGER:throw Error("Something has gone wrong here...");case Lr.META_PIXEL:case Lr.REDDIT_PIXEL:{const x=e9[t];if(x===!0||x&&x[o]===!0)return;s.event(t,o,r,n,a);break}}}catch(x){h("analyticsManager.ts").error("ga type "+s.type+" event failed: "+P(x))}})};flush=async()=>{for(const t of this.providers)await t.flush().catch(o=>{h("analyticsManager.ts").error("ga type "+t.type+" flush failed: "+P(o))})};getAmplitude=()=>this.providers.find(t=>t.type===Lr.AMPLITUDE)}const I=()=>hc.instance,uct=()=>hc.instance.getAmplitude(),Hd=vy(),XD=e=>{try{const t=ir().get(e);if(!t)return;const o=new Date().getTime(),r=Date.parse(t);if(isNaN(r))return;const n=(o-r)/1e3;return ue(n,2)}catch{return}},uLe=()=>ir().get(Wt.SESSION_ID),pLe=()=>{try{return(ir().get(Wt.INTERVAL_TIMESTAMP)??null)!==null}catch{return window.console.warn("Failed to get intervalTimestamp in sessionStorage"),!1}},JD=()=>{try{ir().set(Wt.INTERVAL_TIMESTAMP,new Date().toISOString())}catch{window.console.warn("Failed to set intervalTimestamp in sessionStorage")}},pP=(e,t={})=>
1231{if(at()||!Hd?.utm_source)return;pLe()===!1&&JD();const o="00000000-0000-0000-0000-000000000000",r=parseInt(Ve().get(Ie.VREW_SESSION_COUNT,"1"))||1,n=XD(Wt.PREBOOT_TIMESTAMP),a=XD(Wt.INTERVAL_TIMESTAMP),i={cid:o,clientTimestamp:new Date().toISOString(),category:m.BOOT,action:e,utm_source:Hd?.utm_source,utm_medium:Hd?.utm_medium,utm_campaign:Hd?.utm_campaign,utm_term:Hd?.utm_term,utm_content:Hd?.utm_content,sessionId:uLe(),customValue:JSON.stringify({...t,elapsedTimeSincePreboot:n,intervalElapsedTime:a,sessionCount:r})},s={clientType:rd.TRY,events:[i]},x=JSON.stringify(s),c=POe()+"/analytics-v2";try{navigator.sendBeacon(c,x)}catch(l){h("ga.ts").error("Failed to send beacon: "+P(l))}JD()},fLe=10;let KE;const gLe=e=>e.every(t=>typeof t=="object"&&t!==null&&"projectId"in t&&typeof t.projectId=="string"&&"flags"in t&&t.flags!==null&&typeof t.flags=="object"),_Le=()=>(KE===void 0&&(KE=Ve().getArray(Ie.ASSET_INCONSISTENCY_DETECTED_PROJECT_INFO,gLe)),KE),ELe=e=>{KE=e,Ve().set(Ie.ASSET_INCONSISTENCY_DETECTED_PROJECT_INFO,e)},pct=e=>{const t=se().getProjectId();if(!t)return;const o=_Le(),r=o.find(c=>c.projectId===t),n=Object.fromEntries([...e].map(c=>[c,!0])),a=new Set(Object.keys(r?.flags??{})),i=new Set(Object.keys(n));if(!(a.size!==i.size||[...i].some(c=>!a.has(c))))return;const x=o.filter(c=>c.projectId!==t);for(x.push({projectId:t,flags:n});x.length>fLe;)x.shift();ELe(x),I().event(m.ERROR,g.ASSET_INCONSISTENCY_DETECTED,void 0,void 0,JSON.stringify(n))};var Za=(e=>(e.FREE_SOURCE="free_source",e.USER_ASSET="user_asset",e.GEN_ASSET="gen_asset",e))(Za||{});const fct=3,gct={v1:22050,v2:24e3};var qf=(e=>(e.NOT_SELECTED="not-selected",e.VIDEO="video",e.AUDIO="audio",e.SCREEN="screen",e))(qf||{});const mLe=e=>{switch(e){case"health":case"selfGrowth":case"finance":case"lifestyle":case"businessTech":case"entertainment":case"education":case"society":case"knowledge":case"spirituality":case"animals":case"etc":case"none":return!0;default:return!1}},hLe=e=>e==="general"||e==="narrative"||e==="uncertain",ILe=e=>e!==null&&typeof e=="object",TLe=e=>{const t=JSON.parse(e);if(!ILe(t))throw new Error("Invalid summary with category response.");const{summary:o,category:r,contentFormat:n}=t;if(typeof o!="string")throw new Error("Invalid summary in summary with category response.");if(typeof r!="string")throw new Error("Invalid category in summary with category response.");return{summary:o,category:mLe(r)?r:"etc",contentFormat:hLe(n)?n:"uncertain"}},SLe=async(e,t)=>{const o=new Date().getTime(),r=qe.v4(),n={script:e,rid:r,maxTokens:200,includeCategory:!0},a=2e3,i=20;try{await qo("/generate-summary",{method:"POST",body:JSON.stringify(n),signal:t});const s=await sc(r,a,i,_.C_TTV_GENERATE_SUMMARY_ERROR,t);return TLe(s)}catch(s){return h("ttv.ts").error("Error occured while generating summary with category for TTV. "+P(s)),void 0}finally{const s=Math.floor((new Date().getTime()-o)/1e3);h("ttv.ts").info("Generate Summary with category completed. Duration: "+s+"s.")}},OLe=e=>e.assetVideoInfo.fileLocation===D.IN_MEMORY;var Xn=(e=>(e.AUTO="AUTO",e.R16_9="16:9",e.R4_3="4:3",e.R1_1="1:1",e.R3_4="3:4",e.R9_16="9:16",e))(Xn||{});const uz=(e,t)=>{const o=e/t;return Math.abs(o-1)<.05?Xn.R1_1:o>1.45?Xn.R16_9:o>1?Xn.R4_3:o<.65?Xn.R9_16:Xn.R3_4},qD=e=>{if(typeof e!="string")return;const t=e.trim().toUpperCase();if(t===Xn.AUTO)return Xn.AUTO;if(t===Xn.R16_9)return Xn.R16_9;if(t===Xn.R4_3)return Xn.R4_3;if(t===Xn.R1_1)return Xn.R1_1;if(t===Xn.R3_4)return Xn.R3_4;if(t===Xn.R9_16)return Xn.R9_16},sh=1920,CLe=.9,_ct=async e=>e.size>0&&(await DT(e)).startsWith("image/"),RLe=async e=>{const t=await DT(e);return t==="image/jpeg"||t==="image/jpg"},ALe=e=>new Promise((t,o)=>{const r=new Image;r.onload=()=>t(r),r.onerror=()=>o(new C(_.C_REFERENCE_IMAGE_IMPORT_FAILED)),r.src=e}),yLe=(e,t)=>{const o=Math.max(e,t);if(o<=sh)return{width:e,height:t};const r=sh/o;return{width:Math.round(e*r),height:Math.round(t*r)}},vLe=(e,t,o)=>{const r=document.createElement("canvas"),n=r.getContext("2d");if(!n)throw new C(_.C_REFERENCE_IMAGE_IMPORT_FAILED);return r.width=t,r.height=o,n.drawImage(e,0,0,t,o),new Promise((a,i)=>{r.toBlob(s=>{if(!s)return i(new C(_.C_REFERENCE_IMAGE_IMPORT_FAILED));a(s)},"image/jpeg",CLe)})},wLe=async e=>{const t=URL.createObjectURL(e);
1231try{const o=await ALe(t),{naturalWidth:r,naturalHeight:n}=o;if(!(r>sh||n>sh)&&await RLe(e))return{blob:e.slice(0,e.size,"image/jpeg"),widthPx:r,heightPx:n};const{width:i,height:s}=yLe(r,n);return{blob:await vLe(o,i,s),widthPx:i,heightPx:s}}finally{URL.revokeObjectURL(t)}},Ect=async e=>(await wLe(e)).blob,NLe=e=>{const t=e.match(/^data:(image\/(?:png|jpe?g|webp));base64,(.+)$/s);if(!t)throw new C(_.C_REFERENCE_IMAGE_UPLOAD_FAILED,{},`Failed to parse reference image: not a valid data URL (prefix: ${e.slice(0,30)}...)`);const o=t[1],r=o==="image/jpg"?"image/jpeg":o,n=t[2],a=atob(n),i=Uint8Array.from(a,s=>s.charCodeAt(0));return{fileType:r,binary:i}},PLe=async(e,t)=>Promise.all(e.map(async(o,r)=>{const n=`reference-${r+1}`,{fileType:a,binary:i}=NLe(o),s=h("referenceImage.tsx");s.info(`Uploading reference image (label: ${n}, type: ${a})`);const{uploadUrl:x,imageUrl:c}=await sCe(a,t).catch(d=>{throw s.error(`Failed to get reference image upload URL (label: ${n}, type: ${a}): ${P(d)}`),d});if(await G2(()=>fetch(x,{method:"PUT",body:i,headers:{"Content-Type":a},signal:t}).then(d=>{if(!d.ok)throw new C(_.C_REFERENCE_IMAGE_UPLOAD_FAILED,{},`Failed to upload reference image: server responded with error (label: ${n}, status: ${d.status} ${d.statusText}, url: ${c})`);return d}),t)===null||t?.aborted)throw new DOMException("Reference image upload aborted","AbortError");return s.info(`reference image uploaded (label: ${n})`),{type:"unknown",imageUrl:c,label:n}})),bLe=async()=>await Y().popup({bodyClassName:"general-modal above-modal-overlay",title:A("genimage_setting.change_model_title"),content:A("genimage_engine.reference_images_change_model_warning"),yesStr:A("genimage_setting.change_model_confirm"),noStr:A("popup.cancel")})===mt.YES,LLe=e=>{switch(e.kind){case"start_frame":return A("genimage_setting.start_frame_change_required_title");case"reference_image":return A("genimage_setting.reference_change_required_title")}},MLe=({params:e})=>{const t=A(e.kind==="start_frame"?"genimage_setting.start_frame_change_required_desc":"genimage_setting.reference_change_required_desc",{model:e.target.name});return b.jsxs(kLe,{children:[b.jsx(FLe,{children:Wc(t)}),b.jsx(ULe,{children:e.kind==="start_frame"?b.jsx(CA,{label:A("genimage_setting.model_change_required_per_video_label"),from:e.current.credits,to:e.target.credits}):b.jsx(DLe,{params:e})})]})},DLe=({params:e})=>{const{current:t,target:o,isHighResolutionOn:r,numImages:n}=e,a=r?kb(t):0,i=r?kb(o):0,s=a>0||i>0;return b.jsxs(b.Fragment,{children:[b.jsx(CA,{label:A("genimage_setting.model_change_required_per_image_label"),from:t.credits,to:o.credits}),typeof n=="number"&&b.jsxs(b.Fragment,{children:[b.jsx(YLe,{}),b.jsx(CA,{label:A("genimage_setting.model_change_required_total_label",{count:n})+(s?` ${A("genimage_setting.model_change_required_upscale_suffix")}`:""),from:(t.credits+a)*n,to:(o.credits+i)*n})]})]})},CA=({label:e,from:t,to:o})=>b.jsxs(VLe,{children:[b.jsx(GLe,{children:e}),b.jsxs(WLe,{children:[b.jsx(QD,{value:t}),b.jsx(zLe,{children:"→"}),b.jsx(QD,{value:o,highlight:!0})]})]}),QD=({value:e,highlight:t})=>b.jsxs(HLe,{children:[b.jsx(Ux,{name:"credit",size:14,color:t?ee.mint[600]:ee.gray[650]}),b.jsx(jLe,{highlight:t,children:A("credit_rate.credit_count",{count:e})})]}),mct=async e=>await Y().popup({bodyClassName:"general-modal wide above-modal-overlay",title:LLe(e),content:b.jsx(MLe,{params:e}),yesStr:A("genimage_setting.model_change_required_confirm"),noStr:A("popup.cancel")})===mt.YES,kLe=xe(Xe,{flexDirection:"column",alignItems:"center",gap:16,w:"100%"}),FLe=xe(Nt,{w:"100%",fontSize:15,fontWeight:500,lineHeight:"22px",c:ee.gray[850]}),ULe=xe(Xe,{flexDirection:"column",gap:16,w:"100%",p:16,radius:16,border:`1px solid ${ee.gray[125]}`}),VLe=xe(Xe,{alignItems:"center",justifyContent:"space-between",gap:12,w:"100%"}),GLe=xe(Nt,{fontSize:14,fontWeight:500,lineHeight:"20px",c:ee.gray[850],whiteSpace:"nowrap"}),WLe=xe(Xe,{alignItems:"center",gap:6}),HLe=xe(Xe,{alignItems:"center",gap:4}),jLe=xe(Nt,{fontSize:14,fontWeight:500,lineHeight:"20px",c:ee.gray[650],whiteSpace:"nowrap",variants:{highlight:{true:{fontWeight:700,c:ee.mint[600]}}}}),zLe=xe(Nt,{fontSize:14,fontWeight:500,lineHeight:"20px",c:ee.gray[650]}),YLe=xe(Nt,{w:"100%",h:1,bg:ee.gray[100]}),ZD=new WeakMap,BLe=async(e,t)=>{if(!t)return $D(e);const o=t.get(e);if(o)return o;let r=ZD.get(t);!r&&(r=new Map,ZD.set(t,r));const n=r.get(e);if(n)return n;const a=$D(e).then(i=>(t.set(e,i),r.delete(e),i)).catch(i=>{throw r.delete(e),i});return r.set(e,a),a},RA=e=>({mediaType:"image",description:e.description,userGuidance:e.userGuidance,style:e.style,selectedRatioOption:e.selectedRatioOption,referenceMediaIds:e.referenceMediaIds,userReferenceMediaIds:e.userReferenceMediaIds,genImageEngine:e.genImageEngine,isHighResolutionOn:e.isHighResolutionOn}),hct=e=>
1231({mediaType:"video",description:e.description,userGuidance:e.userGuidance,style:e.style,selectedRatioOption:e.selectedRatioOption,referenceMediaIds:e.referenceMediaIds,userReferenceMediaIds:e.userReferenceMediaIds,genVideoEngine:e.genVideoEngine,archive:e.archive}),$D=async e=>{const t=await i7(e,"image"),o=qe.v4();return await vi(t,!1,tt.USER,o),o},ek=e=>oa(e)!==void 0,KLe=async e=>{const{visualAIGenerationMeta:t,pendingUserReferenceImages:o,referenceImageCache:r}=e;if(!t)return;if(!o?.length)return{...t,selectedRatioOption:qD(t.selectedRatioOption)??t.selectedRatioOption,referenceMediaIds:t.referenceMediaIds?Array.from(new Set(t.referenceMediaIds)):void 0,userReferenceMediaIds:t.userReferenceMediaIds?Array.from(new Set(t.userReferenceMediaIds)):void 0};const n=await Promise.all(o.map(async s=>{if(s.mediaId&&ek(s.mediaId))return{mediaId:s.mediaId,includeInUserReferenceMediaIds:s.includeInUserReferenceMediaIds!==!1};const x=r?.get(s.dataUrl);return x&&ek(x)?{mediaId:x,includeInUserReferenceMediaIds:s.includeInUserReferenceMediaIds!==!1}:(x&&r?.delete(s.dataUrl),{mediaId:await BLe(s.dataUrl,r),includeInUserReferenceMediaIds:s.includeInUserReferenceMediaIds!==!1})})),a=Array.from(new Set(n.map(({mediaId:s})=>s))),i=Array.from(new Set([...t.userReferenceMediaIds??[],...n.filter(({includeInUserReferenceMediaIds:s})=>s).map(({mediaId:s})=>s)]));return{...t,selectedRatioOption:qD(t.selectedRatioOption)??t.selectedRatioOption,referenceMediaIds:Array.from(new Set([...t.referenceMediaIds??[],...a])),userReferenceMediaIds:i}},pz=async e=>{const{mediaId:t,visualAIGenerationMeta:o,pendingUserReferenceImages:r,referenceImageCache:n}=e;try{const a=await KLe({visualAIGenerationMeta:o,pendingUserReferenceImages:r,referenceImageCache:n});return a&&await i5(t,a),a}catch(a){return h("visualAIGeneration.ts").error("Failed to finalize visual AI generation metadata: "+P(a)),o}},XLe=async e=>{const t=await WTe(e.src,e.sourceOrigin??tt.AI_GENERATED);return await pz({mediaId:t.mediaId,visualAIGenerationMeta:e.visualAIGenerationMeta,pendingUserReferenceImages:e.pendingUserReferenceImages,referenceImageCache:e.referenceImageCache}),t},Ict=e=>e.startsWith("data:")?e:"data:image/png;base64,"+e,fz=.7,Qf=20,gz=1e3,_z=()=>({sids:[],numVrewImage:0,numStabilityImage:0,numNSFWImage:0,nsfwClipIndices:new Set,errorsInResults:new Map}),Tct=["none","picture","vintage","watercolor","illustration","flat_vector","oil_painting","pencil_drawing","anime","pixel_art","low_poly","origami","comic_book","neon_punk","3d_model","craft_clay"],Sct=e=>e==="random"?"none":e,Ez=e=>e===_.C_NSFW_CONTENT_DETECTED||e===_.C_VIDEO_CONTENT_FILTERED||e===_.C_VIDEO_CONTENT_FILTERED_PERSON,Oct=async e=>{const t=ba().isPremiumFeatureAvailable(Ut.GENERATE_IMAGE_DOWNLOAD);return!t&&await zN(Ut.GENERATE_IMAGE_DOWNLOAD,e),t},Cct=async e=>{const t=ba().isPremiumFeatureAvailable(Ut.GENERATE_VIDEO_DOWNLOAD);return!t&&await zN(Ut.GENERATE_VIDEO_DOWNLOAD,e),t},mz=e=>{Us(Xt.TTV_EMPTY_ASSET_CLIP);const t=[];let o=[],r,n="empty";return e.forEach((a,i)=>{o.push(i);const s=e[i+1],x=i===e.length-1,c=a?.src!==void 0?"image":a?"video":n,l=a??r;if(s||x){switch(c){case"image":{t.push({type:"image",data:l,applyClipIndices:o});break}case"video":{t.push({type:"video",data:l,applyClipIndices:o});break}case"empty":{t.push({type:c,data:void 0,applyClipIndices:o});break}}o=[]}else l!==void 0&&(r=l,n=c)}),t},tk=async(e,t,o,r,n,a)=>{const i=h("generateAssets.ts"),s=performance.now(),x=await qOe(e,Fe(),1,t,o,n,a);if(i.info(r+" searchStockVideo finished in "+((performance.now()-s)/1e3).toFixed(1)+"s"),i.debug(r+" "+x.length+" videos for query "+e),x.length!==0)for(let c=0;c<x.length;c++){const l=x[c],{thumbnailUrl:d,width:u,height:p,srcUrl:f}=l,E=performance.now(),T=await T4(l.srcUrl,l.stockSite,r).catch(S=>{const R=c===x.length-1,y=R?"":", trying next video ("+(c+1)+"/"+x.length+").";return i.error(r+" Error during createStockVideoInfo in makeStockVideoAsset: "+P(S)+y+`
1232        elapsed time: `+((performance.now()-E)/1e3).toFixed(1)+"s"),void 0});if(!T)continue;if(i.info(r+" createStockVideoInfo finished in "+((performance.now()-E)/1e3).toFixed(1)+"s"),T.fileLocation===D.IN_MEMORY){const S=await En(T.mediaId);if(!S){i.error(r+" Failed to get blob for mediaId: "+T.mediaId);continue}return{videoSrc:f,width:u,height:p,thumbnailUrl:d,assetVideoInfo:T,provider:l.stockSite??ws.UNKNOWN,blob:S}}return{videoSrc:f,width:u,height:p,thumbnailUrl:d,assetVideoInfo:T,provider:l.stockSite??ws.UNKNOWN}}},JLe=async(e,t,o,r,n,a,i,s,x,c,l,d,u)=>{const[p,f]=[i[s-1],i[s+1]];let E;try{E=await hz(e,p,t,f,o,r,d,u,c)}catch(T){if(u?.aborted||no(T))throw T;E=void 0}
1232return E?xh(E,n,a,x,c,0,l,d,void 0,u):{result:"error",errorCode:_.C_PROMPT_GENERATION_ERROR,errorMsg:"[generateImagePromptForTTVWithRetry] Failed to generate prompt for genImage."}},hz=async(e,t,o,r,n,a,i,s,x)=>{let d;for(let u=0;u<2;u++)try{return await aCe(e,t,o,r,n,a,i,s,x)}catch(p){if(s?.aborted||no(p))throw p;d=p,u!==1&&await Fo(1e3)}throw new C(Ne(d)?d.errorCode:_.C_PROMPT_GENERATION_ERROR,{},"[generateImagePromptForTTVWithRetry] Failed to generate prompt for genImage. error: "+P(d))},qLe=async(e,t,o,r,n,a,i,s,x)=>{const c=zt(e).pipe(V0(async({ttvPrompts:l,originalCaption:d},u)=>{if(t[u]!==v0.GenImage)return{ttvPrompts:l,originalCaption:d};if(l.imagePrompt!==void 0&&l.imagePrompt.positive!=="")return{ttvPrompts:l,originalCaption:d};let p;try{p=await hz(r,o[u-1],d,o[u+1],n,a,i,s,x)}catch(f){throw s?.aborted||no(f)?f:new C(Ne(f)?f.errorCode:_.C_PROMPT_GENERATION_ERROR,{},"[ensureImagePromptsForGenImageClips] Failed to prepare fallback image prompt for clip "+u+". error: "+P(f))}return{ttvPrompts:{...l,imagePrompt:p},originalCaption:d}},Qf));return Bt(c)},xh=async(e,t,o,r,n,a,i,s,x,c)=>{try{const l=await nCe({engine:n,prompts:[e],width:t,height:o,trigger:r,postGenimageUsage:!1,provider:rR.VREW,isHighResolutionOn:i,userGuidance:s,...x?{referenceImageUrls:x}:{},userReferenceImageCount:a},c),d=l.images[0];if(!d){const u="imageResult is empty. imageResult: "+JSON.stringify(l);h("generateAssets.ts").error(u);const[p]=l.errorsOnGeneration;throw p??new C(_.C_IMAGE_GENERATION_ERROR,void 0,u)}return{result:"success",sid:l.sid,base64Img:d.b64Image,provider:d.provider}}catch(l){if(no(l))throw l;return{result:"error",errorCode:Ne(l)?l.errorCode:_.C_IMAGE_GENERATION_ERROR,errorArgs:Ne(l)?l.errorArgs:void 0,errorMsg:"Error during generateImageWithPolling: "+P(l)}}},QLe=async(e,t,o,r,n,a,i,s,x={})=>{const c=Date.now(),l=h("generateAssets.ts");if(Us(Xt.REQUEST_VISUAL_ASSETS_FAIL),s?.aborted)throw new DOMException("TTV visual prompt preparation aborted","AbortError");const d=await Sz(t,e,s),{summary:u,category:p,contentFormat:f}=d;if(s?.aborted)throw new DOMException("TTV visual prompt preparation aborted","AbortError");x.onProgress?.(.25);const E=await iCe(t,u,o,!0,a,n,i,s,x.genimageEngine);if(s?.aborted)throw new DOMException("TTV visual prompt preparation aborted","AbortError");x.onProgress?.(.75);const T=E.map(()=>Iz(o,r,fz)),O=x.requireImagePromptsForGenImageClips===!0&&r,S=O?await qLe(E,T,t,u,n,a,i,s,x.genimageEngine):E;if(s?.aborted)throw new DOMException("TTV visual prompt preparation aborted","AbortError");return x.onProgress?.(1),l.info("GenImage prompts: "+JSON.stringify(S)+", elapsed: "+((Date.now()-c)/1e3).toFixed(1)+"s"),{summary:u,category:p,contentFormat:f,prompts:S,clipTypes:T,promptForClip:t,isVideoOn:o,isImageOn:r,color:n,style:a,allowImagePromptFallbackDuringGeneration:!O||o}},ZLe=async(e,t,o,r,n,a,i,s,x,c,l)=>{const d=Date.now(),u=[],p=h("generateAssets.ts"),f=_z(),{prompts:E,clipTypes:T,isImageOn:O,isVideoOn:S,promptForClip:R,summary:y,color:v,style:w,allowImagePromptFallbackDuringGeneration:N}=e;try{let M=0;const k=B=>{++M;const W=M/E.length;h("generateAssets.ts").info("Visual assets progress: "+Math.floor(W*100)+"% (Done/Total: "+M+"/"+E.length+")"),t(W),u.push(B)},F=zt(E).pipe(V0(async({ttvPrompts:B,originalCaption:W},Q)=>{if(l?.aborted)return;Q<Qf&&await Fo(Q*gz);const j=Date.now(),$="GenImage["+(Q+1)+"/"+E.length+"]",q=T[Q];p.info($+" started. Clip type: "+q);let H;return q===v0.FreeVideo?H=await ch(B,$,i,j,l):H=await rk(B,W,y,w,v,o,r,n,s,R,Q,$,f,j,x,c,N,l),!H&&O&&S&&!l?.aborted&&(p.info($+" First attempt failed, trying alternative clip"),q===v0.GenImage?H=await ch(B,$,i,j,l):H=await rk(B,W,y,w,v,o,r,n,s,R,Q,$,f,j,x,c,N,l)),k(ue((Date.now()-j)/1e3,1)),H},Qf)),G=await Bt(F);if(Tz(f),a&&!l?.aborted)for(const[B,{errorArgs:W}]of f.errorsInResults.entries())Ez(B)||await Y().error(B,Ot(B,{defaultKey:"error.image_generation_error",errorArg:W,errorDescKey:"common.no_usage_deduction"}));return l?.aborted?p.info("TTV cancelled — skip postImagegen for "+f.sids.length+" sids"):await JN(f.sids,n),h("generateAssets.ts").info("generateTTVVisualAssetsFromPlanWithoutConsistency elapsedSecondsByClip: "+JSON.stringify(u)),{data:mz(G),numVrewImage:f.numVrewImage,numStabilityImage:f.numStabilityImage,numNSFWImage:f.numNSFWImage,nsfwClipIndices:f.nsfwClipIndices,elapsedSecondsByClip:u}}
1232catch(M){if(l?.aborted||no(M))return p.info("generateTTVVisualAssetsFromPlanWithoutConsistency aborted. elapsed: "+((Date.now()-d)/1e3).toFixed(1)+"s"),{data:[],numVrewImage:f.numVrewImage,numStabilityImage:f.numStabilityImage,numNSFWImage:f.numNSFWImage,nsfwClipIndices:f.nsfwClipIndices,elapsedSecondsByClip:u};throw p.error("Error during generateTTVVisualAssetsFromPlanWithoutConsistency. trigger: "+n+". error: "+P(M)),new C(Ne(M)?M.errorCode:_.C_TTV_GENERAL_ERROR)}finally{p.info("generateTTVVisualAssetsFromPlanWithoutConsistency finished. elapsed: "+((Date.now()-d)/1e3).toFixed(1)+"s")}},$Le=async(e,t,o,r,n,a,i,s,x,c,l,d,u,p,f,E)=>{const T=Date.now(),O=h("generateAssets.ts");O.info("requestVisualAssets started. trigger: "+c);try{const S=await QLe(e,t,r,n,a,i,f,E,{genimageEngine:u});return{...await ZLe(S,o,s,x,c,l,d,u,p,f,E),summary:S.summary,category:S.category,contentFormat:S.contentFormat}}catch(S){throw no(S)?(O.info("requestVisualAssets aborted. elapsed: "+((Date.now()-T)/1e3).toFixed(1)+"s"),S):Ne(S)?S:new C(_.C_TTV_GENERAL_ERROR)}finally{O.info("requestVisualAssets finished. elapsed: "+((Date.now()-T)/1e3).toFixed(1)+"s")}},eMe=async(e,t,o,r,n,a,i,s,x={})=>{const c=Date.now(),l=h("generateAssets.ts");if(!lh(a,"consistency"))throw new C(_.C_IMAGE_GENERATION_PREPARE_ERROR,{},`prepareTTVVisualPlanWithConsistency requires a model with 'consistency' capability. Got "`+a+'".');if(l.info(`prepareTTVVisualPlanWithConsistency started.
1233    promptForClipCount: `+t.length+`, 
1234    referenceImagesCount: `+n.length+`, 
1235    style: `+r+`, 
1236    isVideoOn: `+o+`, 
1237    userGuidance: `+!!i),wn(It.IMAGE_CONSISTENCY_MODE,!0),s?.aborted)throw new DOMException("TTV visual plan preparation aborted","AbortError");const d=await Sz(t,e,s),{summary:u,category:p,contentFormat:f}=d;if(s?.aborted)throw new DOMException("TTV visual plan preparation aborted","AbortError");x.onProgress?.(.2),l.info("Upload reference images started");const E=await PLe(n,s);if(l.info("Upload reference images successfully finished in "+((Date.now()-c)/1e3).toFixed(1)+"s"),s?.aborted)throw new DOMException("TTV visual plan preparation aborted","AbortError");x.onProgress?.(.5),l.info("Prepare TTV plan with consistency started");const T=await xCe(t,u,r,o,E,i,a,s);if(l.info("Prepare TTV plan with consistency successfully finished in "+((Date.now()-c)/1e3).toFixed(1)+"s"),s?.aborted)throw new DOMException("TTV visual plan preparation aborted","AbortError");return x.onProgress?.(1),{summary:u,clipPlans:T,category:p,contentFormat:f,isVideoOn:o,referenceImageCount:n.length,referenceImages:n,uploadedReferenceImages:E,promptForClip:t,style:r}},tMe=async(e,t,o,r,n,a,i,s,x,c)=>{const l=Date.now(),d=[],u=h("generateAssets.ts"),p=_z(),{clipPlans:f,isVideoOn:E,referenceImageCount:T,referenceImages:O,uploadedReferenceImages:S,promptForClip:R,style:y}=e;try{const v=uz(o,r);let w=0;const N=F=>{++w;const G=w/f.length;u.info("Visual assets progress: "+Math.floor(G*100)+"%"),t(G),d.push(F)};u.info("Generate visual assets with consistency started");const M=zt(f).pipe(V0(async(F,G)=>{if(c?.aborted)return;G<Qf&&await Fo(G*gz);const B=Date.now(),W=Iz(E,!0,fz),Q="clip "+(G+1)+"/"+f.length+" ("+W+")";try{const j={description:F.videoPrompt.description||F.imagePrompt,keyword:F.videoPrompt.keyword||F.imagePrompt,imagePrompt:{positive:F.imagePrompt}},$={positive:F.imagePrompt};if(W===v0.FreeVideo){const q=await ch(j,Q,a,B,c);if(q)return q;u.error(Q+" Stock video search failed")}else{const q=await xh($,o,r,n,i,T,s,x,F.referenceImageUrls,c);if(q.result==="success"){const{sid:H,base64Img:U,provider:te}=q;return te==="vrew"?p.numVrewImage+=1:p.numStabilityImage+=1,H&&p.sids.push(H),{src:U,provider:te,visualAIGenerationMeta:RA({description:R[F.clipIndex],userGuidance:x||void 0,style:y,selectedRatioOption:v,genImageEngine:i,isHighResolutionOn:!!s}),pendingUserReferenceImages:ok(O,S,F.referenceImageUrls)}}u.error(Q+` Generate image failed.
1238                errorCode: `+q.errorCode+`
1239                errorMsg: `+q.errorMsg),AA(q.errorCode,q.errorArgs,q.errorMsg,p,G)}if(E&&!c?.aborted)if(u.info(Q+" First attempt failed, trying alternative clip type"),W===v0.FreeVideo){const q=await xh($,o,r,n,i,T,s,x,F.referenceImageUrls,c);if(q.result==="success"){const{sid:H,base64Img:U,provider:te}=q;return te==="vrew"?p.numVrewImage+=1:p.numStabilityImage+=1,H&&p.sids.push(H),{src:U,provider:te,visualAIGenerationMeta:RA({description:R[F.clipIndex],userGuidance:x||void 0,style:y,selectedRatioOption:v,genImageEngine:i,isHighResolutionOn:!!s}
1239),pendingUserReferenceImages:ok(O,S,F.referenceImageUrls)}}AA(q.errorCode,q.errorArgs,q.errorMsg,p,G)}else return await ch(j,Q,a,B,c);return u.error(Q+" All attempts failed. returning empty asset"),void 0}catch(j){if(c?.aborted||no(j))throw j;return u.error(Q+" Unexpected error occurred. error: "+P(j)),void 0}finally{N(ue((Date.now()-B)/1e3,1))}},Qf)),k=await Bt(M);return Tz(p),c?.aborted?u.info("TTV cancelled — skip postImagegen for "+p.sids.length+" sids"):await JN(p.sids,n),u.info("Successfully finished generateTTVVisualAssetsFromPlanWithConsistency in "+((Date.now()-l)/1e3).toFixed(1)+`s.
1240      elapsedSecondsByClip=`+d.join(", ")),{data:mz(k),numVrewImage:p.numVrewImage,numStabilityImage:p.numStabilityImage,numNSFWImage:p.numNSFWImage,nsfwClipIndices:p.nsfwClipIndices,elapsedSecondsByClip:d}}catch(v){if(c?.aborted||no(v))return u.info("generateTTVVisualAssetsFromPlanWithConsistency aborted. elapsed: "+((Date.now()-l)/1e3).toFixed(1)+"s"),{data:[],numVrewImage:p.numVrewImage,numStabilityImage:p.numStabilityImage,numNSFWImage:p.numNSFWImage,nsfwClipIndices:p.nsfwClipIndices,elapsedSecondsByClip:d};throw u.error("Error during generateTTVVisualAssetsFromPlanWithConsistency. error: "+P(v)),new C(Ne(v)?v.errorCode:_.C_TTV_GENERAL_ERROR)}finally{u.info("generateTTVVisualAssetsFromPlanWithConsistency finished. elapsed: "+((Date.now()-l)/1e3).toFixed(1)+"s")}},Rct=async(e,t,o,r,n,a,i,s,x,c,l,d,u,p)=>{const f=Date.now(),E=h("generateAssets.ts");E.info("requestVisualAssetsWithConsistency started. trigger: "+s);try{const T=await eMe(e,t,r,n,c,l,u,p);return{...await tMe(T,o,a,i,s,x,l,d,u,p),summary:T.summary,category:T.category,contentFormat:T.contentFormat}}catch(T){throw no(T)?(E.info("requestVisualAssetsWithConsistency aborted. elapsed: "+((Date.now()-f)/1e3).toFixed(1)+"s"),T):Ne(T)?T:new C(_.C_TTV_GENERAL_ERROR)}finally{E.info("requestVisualAssetsWithConsistency finished. elapsed: "+((Date.now()-f)/1e3).toFixed(1)+"s")}},Iz=(e,t,o)=>{if(!e&&!t)throw new Error("Both isVideoOn and isImageOn cannot be off at the same time.");return e&&!t?v0.FreeVideo:!e&&t?v0.GenImage:Math.random()<o?v0.FreeVideo:v0.GenImage},Tz=e=>{const t={...e,nsfwClipIndices:Array.from(e.nsfwClipIndices),errorsInResults:Array.from(e.errorsInResults.entries())};h("generateAssets.ts").info("GenImageAggregateInfo: "+JSON.stringify(t))},ok=(e,t,o)=>{if(o.length===0)return;const r=new Map(t.map((a,i)=>[a.imageUrl,e[i]])),n=o.flatMap(a=>{const i=r.get(a);return i?[{dataUrl:i}]:[]});return n.length>0?n:void 0},ch=async(e,t,o,r,n)=>{const a=h("generateAssets.ts");if(e.description){const i=await tk(e.description,!1,!0,t,o,n);if(i)return a.info(t+" done. (video from description, elapsed: "+((Date.now()-r)/1e3).toFixed(1)+"s)"),i}if(e.keyword){a.info(t+" First attempt with description failed. Trying with keyword");const i=await tk(e.keyword,!0,!1,t,o,n);if(i)return a.info(t+" done. (video from keyword, elapsed: "+((Date.now()-r)/1e3).toFixed(1)+"s)"),i}return a.info(t+" video search failed, returning empty asset, elapsed: "+((Date.now()-r)/1e3).toFixed(1)+"s"),void 0},rk=async(e,t,o,r,n,a,i,s,x,c,l,d,u,p,f,E,T=!0,O)=>{const S=h("generateAssets.ts");let R;const y=x??fP().id;if(e.imagePrompt!==void 0&&e.imagePrompt.positive!=="")R=await xh(e.imagePrompt,a,i,s,y,0,f,E,void 0,O);else if(T)R=await JLe(o,t,n,r,a,i,c,l,s,y,f,E,O);else return S.info(d+" image prompt is missing after preparation, returning empty asset"),void 0;if(R.result==="success"){const{sid:M,base64Img:k,provider:F}=R;return F==="vrew"?u.numVrewImage+=1:u.numStabilityImage+=1,M&&u.sids.push(M),S.info(d+" done. (genimage from prompt, provider: "+F+", elapsed: "+((Date.now()-p)/1e3).toFixed(1)+"s)"),{src:k,provider:F,visualAIGenerationMeta:RA({description:t,userGuidance:E||void 0,style:r,selectedRatioOption:uz(a,i),genImageEngine:y,isHighResolutionOn:!!f})}}const{errorCode:v,errorArgs:w,errorMsg:N}=R;return AA(v,w,N,u,l),S.info(d+" image generation failed, returning empty asset, elapsed: "+((Date.now()-p)/1e3).toFixed(1)+"s"),void 0},Sz=async(e,t,o)=>{if(e.length<=1)return{summary:e[0]??"",category:"none",contentFormat:"uncertain"};const r=5e3,n=oMe(e.join(`
1241`),r);n.length>1&&h("generateAssets.ts").info("Splitted captions into "+n.length+" chunks for generating summary.");const a=n.map((s,x)=>{try{return SLe(s,o)}catch(c){throw h("generateAssets.ts").error("Error occured while generating summary for index "+(x+1)+" chunk."),c}}),i=(await Promise.all(a)).filter(Se);return i.length===0?{summary:t,category:"none",contentFormat:"uncertain"}:{summary:i.map(({summary:s})=>s).join(`
1242`),category:i.find(({category:s})=>s!=="etc"&&s!=="none")?.category??"etc",contentFormat:i.some(({contentFormat:s})=>
1242s==="narrative")?"narrative":i.some(({contentFormat:s})=>s==="uncertain")?"uncertain":"general"}},oMe=(e,t)=>{const o=[];let r="";const n=e.split(`
1243`);for(let a=0;a<n.length;a++){const i=n[a];r.length+i.length>t&&(o.push(r.trim()),r=""),r+=i+`
1244`}return r.length>0&&o.push(r.trim()),o},rMe=(e,t)=>{const o=vI();return wI(o,t,e,{small:.94,middle:.9,big:.7,center:.5,padding:.15})},Act=(e,t)=>{const o=vI(),r=t/(e||1),n=.97,a=r>1?Math.max(0,.5-n/2):.05;return wI(o,t,e,{small:.98,middle:n,big:.9,center:.5,padding:a})},yct=e=>{const t=vI([Ir.LEFT_TO_RIGHT,Ir.RIGHT_TO_LEFT,Ir.MAGIC_HORIZONTAL]);return wI(t,e,cr(W1))},px=e=>{switch(e){case"16:9":return{width:1344,height:768};case"4:3":return{width:1152,height:864};case"3:4":return{width:864,height:1152};case"9:16":return{width:768,height:1344};default:return{width:1024,height:1024}}},Oz=e=>{switch(e){case he.WIDE_SCREEN:return px("16:9");case he.VERTICAL:return px("9:16");case he.CLASSIC:return px("4:3");case he.SQUARE:return px("1:1");case he.INSTAGRAM:return px("3:4");default:{const{width:t,height:o}=se().getInitProjectVideoSize();return t>o?px("4:3"):t<o?px("3:4"):px("1:1")}}},nMe=async(e,t)=>!await Jh(e,t),lh=(e,t)=>aMe(e).capabilities?.includes(t)??!1,aMe=e=>
1244{const t=$e().getGenImageModels(),o=t.find(r=>r.id===e);return o||(h("generateAssets.ts").error('Genimage model not found for engine "'+e+'". Falling back to initial model: '+JSON.stringify(aR)),aR)},fP=()=>{const e=$e().getGenImageModels().filter(r=>r.tier==="BASIC"),t=e.find(r=>r.isDefault===!0&&!r.disabled);if(t)return t;const o=e.find(r=>!r.disabled);return o?(h("generateAssets.ts").warn("Default genimage model in BASIC tier is disabled or absent. Falling back to first enabled model: "+o.id),o):(h("generateAssets.ts").error("No enabled genimage model in BASIC tier. Falling back to FALLBACK_GENIMAGE_MODEL."),aR)},iMe=(e,t)=>{const o=t.filter(n=>n.credits<=e.credits);return o.length>0?{model:o.reduce((a,i)=>i.credits>a.credits?i:a),isCheaperOrEqual:!0}:{model:t.reduce((n,a)=>a.credits<n.credits?a:n),isCheaperOrEqual:!1}},vct=(e,t,o)=>{const r=$e().getGenImageModels().filter(n=>!n.disabled&&(n.capabilities?.includes(t)??!1)&&(!o?.requiredCapability||(n.capabilities?.includes(o.requiredCapability)??!1)));if(r.length===0)throw new C(_.C_IMAGE_GENERATION_PREPARE_ERROR,{},'No enabled genimage model with capability "'+t+'".');return iMe(e,r)},wct=e=>{const t=async o=>{if(!e.hasReferenceImages||lh(o,e.capability))return!0;const r=await bLe();return r&&e.onClearReferenceImages(),r};return{handleChangeModel:async o=>{await t(o.id)&&e.onChangeModel(o)}}},Nct=e=>px(e);let nk=0;const Pct=async()=>{const e=++nk,t=await Y7();return t.result==="success"?(e===nk&&$e().setGenAssetModels(t.genImageModels,t.genVideoModels,t.genVideoModelListByMode),!0):(h("generateAssets.ts").warn("Failed to fetch gen asset model list: "+t.errorMsg+". Existing cache is retained until next retry."),!1)},AA=(e,t,o,r,n)=>{Ez(e)&&(r.numNSFWImage+=1,r.nsfwClipIndices.add(n)),r.errorsInResults.set(e,{errorArgs:t,msg:o})},sMe=async(e,t)=>{t<=0||(h("generateAssets.ts").info("showNsfwImagePopup. trigger: "+e+", nsfwImageCount: "+t),l1e(e,t),await Y().message(A("image_video_generate_modal.content_filtered_title"),p0(A("image_video_generate_modal.content_filtered_batch_description",{count:t}))))},bct=e=>e?.sunsetDate?A("genimage_engine.deprecated_desc",{date:vx(e.sunsetDate,!1,{year:"2-digit",month:"numeric",day:"numeric"}),interpolation:{escapeValue:!1}}):void 0,Lct=(e,t,o)=>[{value:e,label:A("video_analysis.short_line_length")},{value:t,label:A("video_analysis.normal_line_length")},{value:o,label:A("video_analysis.long_line_length")}],Mct=()=>[l0.ALIGN_SENTENCE,l0.FORCE_ALIGN_LENGTH],xMe=2,cMe=(e,t)=>Mt(t===by.STT?ke.STT_LINEBREAK_SETTING:ke.CLIENT_LINEBREAK_SETTING)[e],lMe=(e,t)=>{const o=gP(e);return t.maxLineLength<o.min||t.maxLineLength>o.max},dMe=(e,t)=>{const o=gP(e);return t===void 0?{type:"default",maxLineLength:o.default,linebreakMode:l0.ALIGN_SENTENCE}:lMe(e,t)?{type:"default",maxLineLength:o.default,linebreakMode:l0.ALIGN_SENTENCE}:{type:"last_used",maxLineLength:t.maxLineLength,linebreakMode:t.mode}},gP=(e,t=xMe)=>Yoe[t][e],Dct=(e,t,o,r)=>{const n=t===by.STT?ke.STT_LINEBREAK_SETTING:ke.CLIENT_LINEBREAK_SETTING,a=Mt(n),i={...a,[e]:{maxLineLength:o,mode:r}};po(n,i)},kct=(e,t)=>{const o=cMe(e,t);return dMe(e,o)},uMe=e=>gP(e).default,pMe=(e,t)=>(...o)=>(t(),e?e(...o):null);let nE;const zo=async()=>(await _g()).cid,ZT=async()=>(await _g()).timestamp,fMe=async()=>(await _g()).isNewUser,gMe=async()=>(await _g()).webCid,Ia=async()=>nE||(nE=await pt().getDeviceInfo(),nE),Cz=async(e,t,o)=>{const r=Xo(),n={agreed:t?1:0,cid:await zo(),clientType:r,installCode:o,licenseAgreed:e?1:0,version:Ha(),os:bx(),lang:Fe()};await si("/ga-agree-result",{method:"POST",body:JSON.stringify(n)}).catch(a=>{throw h("ga.ts").error("Error: requestToFacade gaAgreeResult failed: "+P(a)),new C(_.C_SYSTEM_API_ERROR,{},a)})},Fct=async(e,t)=>{if(FCe())return;const o=Ue(),r=await o.checkAllowGa();EMe(r.kind==="allow",e,t),pP(g.BOOT_GA_INIT)},Uct=async e=>{await Ue().setAllowGa(!1),I().disable(),Cz(Cy(),!1,e).catch(o=>h("ga.ts").error("reportAgreementAllow failed : "+P(o)))},Vct=async e=>{await Ue().setAllowGa(!0),Cz(Cy(),!0,e).catch(o=>h("ga.ts").error("reportAgreementAllow failed : "+P(o)))},Rz=()=>Ve().get(Ie.LAST_UID,""),_Me=()=>Ve().get(Ie.LAST_UID_TIMESTAMP,""),EMe=async(e,t,o)=>{const r=await zo(),n=await ZT(),a=be().getUserInfo()?.uid??Rz(),i=be().getUserInfo()?.created??_Me(),s=await gMe();if(e){const x=await Ia();IMe(r,n,a,i,t,x.deviceId,x.machineId,o,s);return}else{I().disable();return}},Ks=e=>e??"undefined",$T=e=>{if(e===void 0){if(mf())return h("ga.ts").error("unknown tab value from tabToCategory"),void 0;throw new C(_.C_LOGIC_ERROR,void 0,"unknown tab value from tabToCategory")}let t;
1244switch(e){case bo.HOME:{t=m.TOOLBAR_HOME;break}case bo.FILE:{t=m.TOOLBAR_FILE;break}case bo.EDIT:{t=m.TOOLBAR_EDIT;break}case bo.CAPTION:{t=m.TOOLBAR_CAPTION_A;break}case bo.FORMAT:{t=m.TOOLBAR_FORMAT;break}case bo.SETTING:{t=m.TOOLBAR_SETTING;break}case bo.HELP:{t=m.TOOLBAR_HELP;break}case bo.INSERT:{t=m.TOOLBAR_INSERT;break}case bo.EFFECT:{t=m.TOOLBAR_EFFECT;break}case bo.MYVREW:{t=m.TOOLBAR_COMMON;break}default:{if(mf())return h("ga.ts").error("unconfigured Tab enum value from tabToCategory"),void 0;throw new C(_.C_LOGIC_ERROR,void 0,"unconfigured Tab enum value from tabToCategory")}}return t},mMe=()=>{const e=fr.level===Xr.Release;return at()?e?U_.ELECTRON:U_.ELECTRON_DEV:e?U_.TRY:U_.TRY_DEV},hMe=()=>at()?n9:a9,IMe=(e,t,o,r,n,a,i,s,x)=>{const c=mMe(),l=hMe();I().initialize(c,e,t,o,r,l,n,a,i,Bb.browserName,Bb.fullBrowserVersion,s,x)},cC=(e,t,o)=>{h("ga.ts").info("[updateGAInfo]",e,t,o),I().updateInfo(e,t,o??{})},Gct=({lang:e,location:t,videoLock:o,showThumbnail:r,showThumbnailVideo:n,disableVrewMark:a,vrewMarkLastPermissionDate:i,screenWidth:s,screenHeight:x,windowWidth:c,windowHeight:l,loggedIn:d,spellcheckStatus:u,theme:p,isGridEditGuideActive:f,isShortsEditGuideActive:E,userInfo:T,systemInfo:O,updatePolicy:S,count:R,isInitAutomatic:y,userSpeakerCount:v,backupList:w,macAppLocation:N,startupOption:M,editView:k,scriptViewShowAssets:F,scriptViewNewline:G,zoomLevel:B,customPanelWidth:W},Q)=>{const j=qt().getAvailableHwAccel(),$=j!==gr.NONE,q={lang:e,location:t,isLock:o?"lock":"unlock",isShowingThumbnail:r?"show":"hide",isShowingThumbnailVideo:n?"show":"hide",isShowingVrewMark:a?"hide":"show",vrewMarkLastPermissionDate:i,screenWidth:s,screenHeight:x,windowWidth:c,windowHeight:l,loggedIn:d?"member":"not_member",isSpellcheckOn:u?"on":"off",theme:p,isGridEditGuideActive:f?"on":"off",isShortsEditGuideActive:E?"on":"off",planType:T?.paidPlanInfo?.planType??"FREE",planPeriod:T?.paidPlanInfo?.period??"",planStatus:T?.paidPlanInfo?.planStatus??"",systemInfo:O,updatePolicy:S,useHwAccel:$?"on":"off",useDecodeHwAccel:"on",hwAccel:j,initTriggerType:y?"automaticDaily":"manual",userSpeakerCount:v,backupList:w,count:R,macAppLocation:N,startupOption:M,editView:k,scriptViewShowAssets:F,scriptViewNewline:G,zoomLevel:B,customPanelWidth:W};I().event(m.INIT,Q?g.FIRST_INIT:g.INIT_INFO,void 0,void 0,JSON.stringify(q))},Wct=e=>{I().event(m.LOGIN_LAYER,g.DISPLAY,e)},Hct=e=>{const t=Ks(e);I().event(t,g.DISPLAY)},jct=e=>{I().event(m.LOGIN_LAYER,g.LOGIN,e?"on":"off")},zct=()=>{I().event(m.LOGIN_LAYER,g.SIGNUP)},Yct=()=>{I().event(m.LOGIN_LAYER,g.RESET_PW)},Bct=()=>{I().event(m.LOGIN_LAYER,g.LATER)},Kct=()=>{I().event(m.LOGIN_LAYER,g.CLOSE)},Xct=()=>{I().event(m.RESETPW_LAYER,g.SEND)},Jct=()=>{I().event(m.MYMENU_LOGIN_USERINFO,g.CHANGE_NAME)},qct=()=>{I().event(m.MYMENU_LOGIN_USERINFO,g.CHANGE_PASSWORD_BUTTON)},Qct=()=>{I().event(m.MYLAYER_LOGIN,g.USERINFO)},Zct=()=>{I().event(m.MYLAYER_LOGIN,g.CLICK_LOGOUT)},$ct=()=>{I().event(m.MYMENU_LOGIN_USERINFO,g.WITHDRAW_BUTTON)},elt=()=>{I().event(m.MYVREW,g.CLICK_LOGOUT)},tlt=()=>{I().event(m.MYVREW,g.PAGE_REGISTER)},olt=()=>{I().event(m.LOGIN_LAYER,g.LOGIN_SUCCESS)},rlt=()=>{I().event(m.LOGIN_LAYER,g.LOGIN_FAIL)},nlt=e=>{I().event(m.TOOLBAR_COMMON,g.TOGGLE_SUBBAR,e?"fold":"unfold")},alt=()=>{I().event(m.TOOLBAR_COMMON,g.CLICK_SEND_FEEDBACK)},TMe=e=>{I().event(m.TOOLBAR_COMMON,g.CLICK_DOWNLOAD_APP,void 0,void 0,JSON.stringify({from:e})),pt().getInstallCode()!==""&&I().event(m.TOOLBAR_COMMON,g.CLICK_DOWNLOAD_APP_AD,void 0,void 0,JSON.stringify({from:e}))},ilt=()=>{I().event(m.TOOLBAR_COMMON,g.CLICK_MYVREW)},slt=()=>{I().event(m.TOOLBAR_HELP,g.CLICK_MYVREW)},xlt=()=>{const e=g.HOVER_MYVREW,t=Ra(e);t!==void 0&&I().event(m.TOOLBAR_COMMON,e,t)},clt=()=>{I().event(m.TOOLBAR_COMMON,g.MENU_HOME)},llt=()=>{I().event(m.TOOLBAR_COMMON,g.MENU_FILE)},dlt=()=>{I().event(m.TOOLBAR_COMMON,g.MENU_EDIT)},ult=()=>{I().event(m.TOOLBAR_COMMON,g.MENU_CAPTION)},plt=()=>{I().event(m.TOOLBAR_COMMON,g.MENU_FORMAT)},flt=()=>{I().event(m.TOOLBAR_COMMON,g.MENU_INSERT)},glt=()=>{I().event(m.TOOLBAR_COMMON,g.MENU_AI_VOICE)},_lt=()=>{I().event(m.TOOLBAR_COMMON,g.MENU_FRAMEPACK)},Elt=()=>{I().event(m.TOOLBAR_COMMON,g.MENU_EFFECT)},mlt=()=>{I().event(m.TOOLBAR_COMMON,g.MENU_HELP)},hlt=()=>{I().event(m.WARNING,g.WARN_INSUFFICIENT_DISK_SPACE)},SMe=()=>{I().event(m.KEY_FILE,g.OPEN_PROJECT)},Ilt=()=>{const e=se().getSaveProjectType(),t=e===Ee.CLOUD?"cloud":at()?"local":"browser";I().event(m.TOOLBAR_FILE,g.CLICK_SAVE,t)},Tlt=()=>{const e=se().getSaveProjectType(),t=e===Ee.CLOUD?"cloud":at()?"local":"browser";I().event(m.TOOLBAR_FILE,g.CLICK_SAVE_AS,t)},Slt=()=>{const e=se().getSaveProjectType()===Ee.CLOUD?"cloud":"local",t="cloud",o={currSaveType:e,targetSaveType:t};I().event(m.TOOLBAR_FILE,g.CLICK_SAVE_AS_TO_CLOUD,void 0,void 0,JSON.stringify(o))},Olt=()=>{const e=se().getSaveProjectType()===Ee.CLOUD?"cloud":at()?"local":"browser",t="local",o={currSaveType:e,targetSaveType:t};I().event(m.TOOLBAR_FILE,g.CLICK_SAVE_AS_TO_LOCAL,void 0,void 0,JSON.stringify(o))},Clt=()=>{const e=se().getSaveProjectType()===Ee.CLOUD?"cloud":at()?"local":"browser",t="browser",o={currSaveType:e,targetSaveType:t};I().event(m.TOOLBAR_FILE,g.CLICK_SAVE_IN_BROWSER,void 0,void 0,JSON.stringify(o))},Rlt=()=>{I().event(m.TOOLBAR_FILE,g.CLICK_EXPORT_TO_VIDEO)},Alt=()=>{I().event(m.TOOLBAR_FILE,g.CLICK_RATIO)},ylt=e=>{I().event(e==="scene_panel"?m.SCENE_PANEL:m.TOOLBAR_FILE,g.CLICK_VIDEO_REMIX)},vlt=e=>{I().event(m.VIDEO_REMIX,g.CLOSE_DOCS,void 0,void 0,JSON.stringify({phase:e}))},wlt=e=>{I().event(m.VIDEO_REMIX,g.DONE,void 0,void 0,JSON.stringify(e))},Nlt=e=>{I().event(m.VIDEO_REMIX,g.CHECK_USAGE,e)},Plt=()=>{I().event(m.VIDEO_REMIX,g.NO_SUBTITLE)},blt=e=>{const t=P4(e);I().event(m.RATIO_SETTING,g.SELECT_RATIO,t)},Llt=()=>{I().event(m.RATIO_SETTING,g.CLICK_RATIO_FIT)},Mlt=()=>{I().event(m.RATIO_SETTING,g.CLICK_RATIO_FILL)},Dlt=()=>{I().event(m.TOOLBAR_FILE,g.CLICK_EXPORT_TO)},klt=()=>{I().event(m.TOOLBAR_FILE,g.CLICK_EXPORT_TO_SRT)},Flt=()=>{I().event(m.TOOLBAR_FILE,g.CLICK_EXPORT_TO_TXT)},Ult=()=>{I().event(m.TOOLBAR_FILE,g.CLICK_EXPORT_TO_XML)},Vlt=()=>{I().event(m.TOOLBAR_FILE,g.CLICK_EXPORT_TO_FCPXML)},Glt=()=>{I().event(m.TOOLBAR_FILE,g.CLICK_EXPORT_TO_DAVINCI_XML)},Wlt=()=>{I().event(m.TOOLBAR_FILE,g.CLICK_EXPORT_TO_CAPTION_VIDEO)},Hlt=()=>{I().event(m.TOOLBAR_FILE,g.CLICK_EXPORT_TO_AUDIO)},jlt=()=>{I().event(m.TOOLBAR_FILE,g.CLICK_EXPORT_TO_IMAGE)},OMe=()=>{I().event(m.TOOLBAR_HOME,g.DEMO_PLAY)},CMe=()=>{I().event(m.TOOLBAR_HOME,g.DEMO_PAUSE)},zlt=e=>{const t=Ks(e);I().event(t,g.CLICK_UNDO)},Ylt=e=>{const t=Ks(e);I().event(t,g.CLICK_REDO)},RMe=(e,t,o,r)=>{const n=Ks(o),a=r.length>0?g.COPY_ASSET:g.COPY,i=r.length===1?"single":"multi",s=i==="single"?{assetType:Dt(r[0].assetType)}:cn(r.map(c=>Dt(c.assetType))),x={behaviorType:t,...r.length>0&&{selectType:i,...s}};I().event(n,a,e,void 0,JSON.stringify(x))},AMe=(e,t)=>{const o={gaBehaviorType:t};I().event(m.TOOLBAR_EDIT,g.CLICK_COPY_IN_ORIGINAL_VIEW,e,void 0,JSON.stringify(o))},yMe=(e,t,o,r)=>{const n=Ks(o),a=r.length>0?g.CUT_ASSET:g.CUT,i=r.length===1?"single":"multi",s=i==="single"?{assetType:Dt(r[0].assetType)}:cn(r.map(c=>Dt(c.assetType))),x={behaviorType:t,...r.length>0&&{selectType:i,...s}};I().event(n,a,e,void 0,JSON.stringify(x))},vMe=(e,t,o,r)=>{const n=Ks(o),a={behaviorType:t,pasteOrigin:r};I().event(n,g.CLICK_PASTE,e,void 0,JSON.stringify(a))},Blt=(e,t)=>{const o=Ks(e),r={gaBehaviorType:t};I().event(o,g.CLICK_MERGE_CLIPS,void 0,void 0,JSON.stringify(r))},wMe=(e,t)=>{const o=Ks(t),r={gaBehaviorType:e};I().event(o,g.CLICK_DIVIDE_CLIP,void 0,void 0,JSON.stringify(r))},Az=(e,t)=>{const o=t||m.TOOLBAR_EDIT;I().event(o,g.CLICK_TRUNCATE_SILENT_SECTIONS,e?"on":"off")},Klt=(e,t)=>{const o=Ks(t);Az(e,o)},Xlt=e=>{Az(e,m.TOOLBAR_EDIT)},Jlt=e=>{I().event(m.TOOLBAR_FILTER,g.CLICK_FILTER_PANEL,e?"on":"off")},qlt=e=>{I().event(m.TOOLBAR_EDIT,g.CLICK_ORIGINAL_VIEW,e?"on":"off")},Qlt=e=>{I().event(m.TOOLBAR_EDIT,g.CLICK_SEARCH,e?"on":"off")},Zlt=()=>{I().event(m.TOOLBAR_EDIT,g.CLICK_MARKER_MENU)},NMe=(e,t,o)=>{const r=JSON.stringify({markerId:e,clipsNum:t});I().event(o,g.INSERT_MARKER,void 0,void 0,r)},PMe=e=>{const t=""+e;I().event(m.KEY_EDIT,g.INSERT_MARKER,t)},$lt=()=>{I().event(m.TOOLBAR_EDIT,g.OPEN_MARKER_PANEL)},bMe=()=>{I().event(m.MARKER_ICON,g.OPEN_MARKER_PANEL)},edt=()=>{I().event(m.MOUSECLICK_EDIT,g.OPEN_MARKER_PANEL)},tdt=()=>{I().event(m.MARKER_ICON,g.CLICK_ICON)},odt=(e,t)=>
1244{const o=JSON.stringify({markerId:e,clipsNum:t});I().event(m.MARKER_PANEL,g.SELECT_COLOR,void 0,void 0,o)},rdt=(e,t)=>{const o=JSON.stringify({clipIndex:e,clipsNum:t});I().event(m.MARKER_PANEL,g.CLICK_ITEM,void 0,void 0,o)},ndt=(e,t,o)=>{const r=JSON.stringify({x:e,y:t,z:o});I().event(m.MARKER_PANEL,g.CLICK_CHECKBOX,void 0,void 0,r)},adt=e=>{const t=e?"on":"off";I().event(m.MARKER_PANEL,g.CLICK_CHECKBOX_ALL,t)},idt=()=>{I().event(m.MARKER_PANEL,g.CLICK_TOP)},sdt=()=>{I().event(m.MARKER_PANEL,g.CLICK_X)},xdt=e=>{const t=e?"X":"O";I().event(m.MARKER_PANEL,g.WRITE_NAME,t)},LMe=()=>{I().event(m.SMART_TOOLTIP_MARKER_PANEL,g.DISPLAY)},yz=e=>{I().event(m.SMART_TOOLTIP_MARKER_PANEL,g.CLOSE,e)},cdt=e=>{const t=e?m.TOOLBAR_CAPTION_B:m.TOOLBAR_CAPTION_A;I().event(t,g.CLICK_IMPORT_TEXT)},ldt=e=>{const t=e?m.TOOLBAR_CAPTION_B:m.TOOLBAR_CAPTION_A;I().event(t,g.CLICK_IMPORT_SCRIPT)},ddt=e=>{const t=e?m.TOOLBAR_CAPTION_B:m.TOOLBAR_CAPTION_A;I().event(t,g.CLICK_IMPORT_SUBTITLE)},udt=(e,t)=>{const o=Ks(t);I().event(o,g.CLICK_SIZE,e.toString())},pdt=(e,t,o)=>{const r={[Ai.LEFT]:g.UPDATE_CAPTION_ALIGN_LEFT,[Ai.CENTER]:g.UPDATE_CAPTION_ALIGN_CENTER,[Ai.RIGHT]:g.UPDATE_CAPTION_ALIGN_RIGHT,[oo.TOP]:g.UPDATE_CAPTION_ALIGN_TOP,[oo.MIDDLE]:g.UPDATE_CAPTION_ALIGN_MIDDLE,[oo.BOTTOM]:g.UPDATE_CAPTION_ALIGN_BOTTOM,[oo.CUSTOM]:g.UPDATE_CAPTION_ALIGN_CUSTOM},n=mw(o,t).toString();I().event(m.TOOLBAR_FORMAT,r[e],n,void 0,o.toString())},fdt=(e,t)=>{const o={[Ai.LEFT]:g.UPDATE_CAPTION_POS_LEFT,[Ai.CENTER]:g.UPDATE_CAPTION_POS_CENTER,[Ai.RIGHT]:g.UPDATE_CAPTION_POS_RIGHT},r=mw(t,Yh.HORIZONTAL);I().event(m.TOOLBAR_FORMAT,o[e],r.toString(),void 0,t.toString())},gdt=(e,t)=>{const o={[oo.TOP]:g.UPDATE_CAPTION_POS_TOP,[oo.MIDDLE]:g.UPDATE_CAPTION_POS_MIDDLE,[oo.BOTTOM]:g.UPDATE_CAPTION_POS_BOTTOM,[oo.CUSTOM]:g.UPDATE_CAPTION_ALIGN_CUSTOM},r=mw(t,Yh.VERTICAL);I().event(m.TOOLBAR_FORMAT,o[e],r.toString(),void 0,t.toString())},_dt=e=>{I().event(m.TOOLBAR_FORMAT,g.LETTER_SPACING,e)},Edt=e=>{I().event(m.TOOLBAR_FORMAT,g.LINE_HEIGHT,e)},ak=(e,t)=>{const o=t?m.TOOLBAR_FORMAT:m.CAPTION_FORMAT;I().event(o,g.DELETE_FORMAT,""+e)},mdt=e=>{I().event(m.TOOLBAR_SETTING,g.CLICK_LANGUAGE,e)},hdt=e=>{I().event(m.TOOLBAR_SETTING,g.CLICK_PREVIEW_LOCATION,e)},Idt=e=>{I().event(m.TOOLBAR_SETTING,g.CLICK_WORD_DELETE_BUTTON,e?"lock":"unlock")},Tdt=e=>{I().event(m.TOOLBAR_SETTING,g.CLICK_MINI_PREVIEW,e?"lock":"unlock")},Sdt=()=>{I().event(m.TOOLBAR_HELP,g.CLICK_KEYBOARD_SHORTCUTS),Dz(io.BUTTON)},Odt=()=>{I().event(m.TOOLBAR_HELP,g.CLICK_SETTING)},Cdt=()=>{I().event(m.TOOLBAR_HELP,g.CLICK_SEND_FEEDBACK)},Rdt=()=>{I().event(m.TOOLBAR_HELP,g.CLICK_INFORMATION)},Adt=e=>{I().event(m.UPLOAD,g.UPLOAD_VIDEO_WITH_DRAG_AND_DROP,e)},ydt=e=>{I().event(m.UPLOAD,g.ADD_VIDEO_WITH_DRAG_AND_DROP,e)},vdt=(e,t,o,r,n,a,i,s,x,c,l,d,u,p,f,E)=>{const T=R=>R.linebreak?"linebreak":R.punctuation?"punctuation":"slash",O=s===uMe(e)&&i===l0.ALIGN_SENTENCE,S={language:e,region:t,isUsingSTT:o,selectedSttTier:r,isUsingScript:!!n,attachedScriptType:a.importScriptMethod,scriptLineBreak:T(a.splitOptions),isLineBreakerOptionToggled:!O,lineBreakerMaxLineLength:s,lineBreakerOptionEditedWith:i===l0.ALIGN_SENTENCE?"auto":"manual",splitClipAtHardcut:x,displayHardcutIcon:c,addedSourceCount:l.length,addedVideoSourceCount:l.filter(R=>R.mediaFileInfo?.videoInfo).length,addedAudioSourceCount:l.filter(R=>R.mediaFileInfo?.audioInfo&&!R.mediaFileInfo?.videoInfo).length,addedSceneCount:d?1:l.length,insertionFrom:f?.from,insertionOrigin:f?.method,insertionTargetType:f?.insertionTarget,isAutoSplitSceneEnabled:u,isCaptionCorrectionEnabled:p,insertAIImage:E??!1};I().event(m.STT,g.START,void 0,void 0,JSON.stringify(S))},wdt=(e,t,o,r)=>{const n=t+"-"+o+"-"+r,a=n+"-"+e;I().event(m.UPLOAD,g.UPLOAD_AUDIO_INFO,void 0,void 0,JSON.stringify({audioFileId:n,audioUploadRequestId:a}))},Ndt=e=>{const t=e.mediaFileInfo?.duration??0,o=_P(e.importMethod,e.path),r=o??"unknown",n=t.toFixed(2)+"_"+r;I().event(m.UPLOAD,g.UPLOAD_VIDEO_SEND_AUDIO_START,n)},Pdt=e=>{I().event(m.UPLOAD,g.UPLOAD_VIDEO_SEND_AUDIO_DONE,e)},_P=(e,t)=>{if(e==="video_record")return"record-webcam";if(e==="audio_record")return"record-voice";if(bi(Fh).test(t))return"video";if(bi(xy).test(t))return"audio"},MMe=(e,t,o)=>{const r=e.importTarget.range===gn.NEW_PROJECT,n=r?1:t+1,a=r?1:o+1,i=e.files[0].mediaFileInfo?.videoInfo?.size,s=_P(e.files[0].importMethod,e.files[0].path),x=e.type===Sm.TRANSCRIBE?e.importScript!==null:void 0,c=e.f
1244iles[0].type===kG.TRANSCRIBE?e.files[0].linebreakerOptions:void 0;return{videoNum:n,sceneNum:a,videoInfoSize:i,type:s,script:x,lineBreakerOptions:c}},yA=e=>e===void 0?"none":e===l0.ALIGN_SENTENCE?"meaning":"length",bdt=(e,t,o,r,n)=>{const{videoNum:a,sceneNum:i,type:s,script:x,lineBreakerOptions:c}=MMe(e,t,o),l=s??"unknown",d=x?"O":"X",u=c===void 0||c.isDefaultOption?"X":"O",p=c===void 0?0:c.maxLineLength,f=yA(c?.mode),E=c===void 0?"none":c.mostRecentLineLengthEdit,T=i>1?"True":"False",O=!!e.files[0].hardcutSetting.divideWordOnHardcut,S=!!e.files[0].hardcutSetting.divideClipOnHardcut,R=ue((Date.now()-n.startTime)/1e3,2),y=n.bitRate??0,v=n.videoDurationInSeconds??0,w=ue(v===0?0:y/8*v,2),N=ue(w/R,2),M=ue(v/R,2),k=n.systemInfo?.cpu??null,F=a+"_"+i+"_"+l;I().event(m.UPLOAD,g.UPLOAD_VIDEO_DONE,F,void 0,JSON.stringify({videoNum:a,sceneNum:i,fileType:l,isUsingScript:d,lineBreakerMaxLineLength:p,lineBreakerMode:f,lineBreakerOptionEditedWith:E,isLineBreakerOptionToggled:u,isMultiScenes:T,displayHardcutIcon:O,splitClipAtHardcut:S,sourceBitRate:y,sourceBytesPerExportElapsedSeconds:N,sourceFileSizeInBytes:w,sourceSecondsPerExportElapsedSeconds:M,sourceVideoDurationSec:v,elapsedSec:R,hardcutTimestamps:r,cpuInfo:k}))},Ldt=(e,t,o)=>{const r=ue((Date.now()-t.startTime)/1e3,2),n=!!e.files[0].hardcutSetting.divideWordOnHardcut,a=!!e.files[0].hardcutSetting.divideClipOnHardcut,i=t.bitRate??0,s=t.videoDurationInSeconds??0,x=ue(s===0?0:i/8*s,2),c=t.systemInfo?.cpu??null,l=o?.sttProgress??null,d=o?.hardcutProgress??null,u=o?.autoSplitSceneProgress??null;I().event(m.UPLOAD,g.UPLOAD_VIDEO_CANCEL,void 0,void 0,JSON.stringify({displayHardcutIcon:n,splitClipAtHardcut:a,sourceBitRate:i,sourceFileSizeInBytes:x,sourceVideoDurationSec:s,elapsedSec:r,sttProgress:l,hardcutProgress:d,autoSplitSceneProgress:u,cpuInfo:c}))},vz=e=>{const t=e/60;let o;return t<=5?o="0to5":t<=10?o="5to10":t<=20?o="10to20":t<=30?o="20to30":t<=40?o="30to40":t<=50?o="40to50":t<=60?o="50to60":t<=120?o="60to120":o="120to",o},Mdt=e=>{const t=e.files[0].mediaFileInfo?.duration??0,o=_P(e.files[0].importMethod,e.files[0].path),r=o||"unknown",n=vz(t)+"_"+r;I().event(m.UPLOAD,g.UPLOADED_VIDEO_DURATION,n)},Ddt=e=>{const t=e.type===Sm.TRANSCRIBE?bi(Fh).test(e.files[0].path)?"video":bi(xy).test(e.files[0].path)?"audio":"unknown":e.type===Sm.NO_AUDIO_TRACK?"video_only":"skip_stt",o=Ha();I().event(m.UPLOAD,g.UPLOAD_VIDEO_LOAD_RESULT,t,void 0,o)},kdt=e=>{const t=e.files[0].mediaFileInfo;if(t?.audioInfo===void 0){const r=t?.duration??0,n=vz(r);I().event(m.UPLOAD,g.UPLOAD_VIDEO_WITHOUT_AUDIO,n)}},Fdt=e=>{I().event(m.VIDEO,g.LOADED_VIDEO_RATIO,e)},DMe=(e,t,o,r)=>{const n={[V.VIDEO]:g.EXPORT_VIDEO_START,[V.CAPTION_VIDEO]:g.EXPORT_CAPTION_VIDEO_START,[V.TRANSCODING_VIDEO]:void 0,[V.TRANSCODING_AUDIO]:void 0,[V.CONVERTING_GIF]:void 0,[V.STREAM]:void 0,[V.IMAGE]:g.EXPORT_IMAGE_START,[V.ANIMATED_IMAGE]:g.EXPORT_IMAGE_START,[V.AUDIO_MP3]:g.EXPORT_AUDIO_START,[V.AUDIO_WAV]:g.EXPORT_AUDIO_START,[V.AUDIO_AAC]:void 0,[V.SPLIT_MEDIA]:void 0,[V.STATIC_FRAME]:void 0,[V.PROXY_VIDEO]:void 0},a=JSON.stringify({exportId:o,exportByClip:r}),i=n[e];i&&I().event(m.EXPORT,i,t,void 0,a)},kMe=(e,t,o)=>{const r={[V.VIDEO]:g.EXPORT_VIDEO_START2,[V.CAPTION_VIDEO]:void 0,[V.TRANSCODING_VIDEO]:void 0,[V.TRANSCODING_AUDIO]:void 0,[V.CONVERTING_GIF]:void 0,[V.STREAM]:void 0,[V.IMAGE]:void 0,[V.ANIMATED_IMAGE]:void 0,[V.AUDIO_MP3]:void 0,[V.AUDIO_WAV]:void 0,[V.AUDIO_AAC]:void 0,[V.SPLIT_MEDIA]:void 0,[V.STATIC_FRAME]:void 0,[V.PROXY_VIDEO]:void 0},n=r[e];if(n){const a=e===V.VIDEO?t?Vc.ON:Vc.OFF:void 0,i=JSON.stringify({exportId:o});I().event(m.EXPORT,n,a,void 0,i)}},FMe=(e,t,o,r)=>{const n=[30,60,90,120,180,240,300],a=[];return n.forEach(i=>{const s=setTimeout(()=>UMe(e,t,o,r,i),i*60*1e3);a.push(s)}),a},UMe=(e,t,o,r,n)=>{const a=JSON.stringify({encodingType:e,outputType:t,videoDuration:o,exportId:r,min:n});I().event(m.EXPORT,g.EXPORT_PERFORMANCE_PROGRESS,void 0,void 0,a)},VMe=(e,t)=>{const o=JSON.stringify({exportId:t});I().event(m.EXPORT,g.EXPORT_VIDEO_WITHOUT_CAPTION_START,e,void 0,o)},GMe=e=>{const t={[V.VIDEO]:g.EXPORT_VIDEO_FFMPEG_DOWNLOAD_START,[V.IMAGE]:void 0,[V.ANIMATED_IMAGE]:void 0,[V.CAPTION_VIDEO]:g.EXPORT_CAPTION_VIDEO_FFMPEG_DOWNLOAD_START,[V.AUDIO_MP3]:g.EXPORT_AUDIO_FFMPEG_DOWNLOAD_START,[V.AUDIO_WAV]:g.EXPORT_AUDIO_FFMPEG_DOWNLOAD_START,[V.AUDIO_AAC]:void 0,[V.TRANSCODING_VIDEO]:g.TRANSCODE_VIDEO_FFMPEG_DOWNLOAD_START,[V.TRANSCODING_AUDIO]:g.TRANSCODE_VIDEO_FFMPEG_DOWNLOAD_START,[V.
1244CONVERTING_GIF]:void 0,[V.STREAM]:void 0,[V.SPLIT_MEDIA]:void 0,assetVideo:void 0,[V.STATIC_FRAME]:void 0,[V.PROXY_VIDEO]:g.TRANSCODE_VIDEO_FFMPEG_DOWNLOAD_START},o=e===V.TRANSCODING_VIDEO?m.TRANSCODE:m.EXPORT,r=t[e];r&&I().event(o,r)},WMe=e=>{const t={[V.VIDEO]:g.EXPORT_VIDEO_FFMPEG_DOWNLOAD_DONE,[V.IMAGE]:void 0,[V.ANIMATED_IMAGE]:void 0,[V.CAPTION_VIDEO]:g.EXPORT_CAPTION_VIDEO_FFMPEG_DOWNLOAD_DONE,[V.AUDIO_MP3]:g.EXPORT_AUDIO_FFMPEG_DOWNLOAD_DONE,[V.AUDIO_WAV]:g.EXPORT_AUDIO_FFMPEG_DOWNLOAD_DONE,[V.AUDIO_AAC]:void 0,[V.TRANSCODING_VIDEO]:g.TRANSCODE_VIDEO_FFMPEG_DOWNLOAD_DONE,[V.TRANSCODING_AUDIO]:g.TRANSCODE_VIDEO_FFMPEG_DOWNLOAD_DONE,[V.CONVERTING_GIF]:void 0,[V.STREAM]:void 0,[V.SPLIT_MEDIA]:void 0,assetVideo:void 0,[V.STATIC_FRAME]:void 0,[V.PROXY_VIDEO]:g.TRANSCODE_VIDEO_FFMPEG_DOWNLOAD_DONE},o=e===V.TRANSCODING_VIDEO?m.TRANSCODE:m.EXPORT,r=t[e];r&&I().event(o,r)},HMe=(e,t,o)=>{const r={[V.VIDEO]:g.EXPORT_VIDEO_ENCODING_START,[V.CAPTION_VIDEO]:g.EXPORT_CAPTION_VIDEO_ENCODING_START,[V.AUDIO_MP3]:g.EXPORT_AUDIO_ENCODING_START,[V.AUDIO_WAV]:g.EXPORT_AUDIO_ENCODING_START,[V.AUDIO_AAC]:void 0,[V.IMAGE]:void 0,[V.ANIMATED_IMAGE]:void 0,[V.TRANSCODING_VIDEO]:void 0,[V.TRANSCODING_AUDIO]:void 0,[V.CONVERTING_GIF]:void 0,[V.STREAM]:void 0,[V.SPLIT_MEDIA]:void 0,[V.STATIC_FRAME]:void 0,[V.PROXY_VIDEO]:void 0},n=r[e];if(n){const a=e===V.VIDEO?t?Vc.ON:Vc.OFF:void 0,i=JSON.stringify({exportId:o});I().event(m.EXPORT,n,a,void 0,i)}},jMe=(e,t,o)=>{const r={[V.VIDEO]:g.EXPORT_VIDEO_ENCODING_DONE,[V.CAPTION_VIDEO]:g.EXPORT_CAPTION_VIDEO_ENCODING_DONE,[V.AUDIO_MP3]:g.EXPORT_AUDIO_ENCODING_DONE,[V.AUDIO_WAV]:g.EXPORT_AUDIO_ENCODING_DONE,[V.AUDIO_AAC]:void 0,[V.IMAGE]:void 0,[V.ANIMATED_IMAGE]:void 0,[V.TRANSCODING_VIDEO]:void 0,[V.TRANSCODING_AUDIO]:void 0,[V.CONVERTING_GIF]:void 0,[V.STREAM]:void 0,[V.SPLIT_MEDIA]:void 0,[V.STATIC_FRAME]:void 0,[V.PROXY_VIDEO]:void 0},n=r[e];if(n){const a=e===V.VIDEO?t?Vc.ON:Vc.OFF:void 0,i=JSON.stringify({exportId:o});I().event(m.EXPORT,n,a,void 0,i)}},vA={[mi.BLACK]:"black",[mi.MINT]:"mint",[mi.WHITE]:"white"},zMe=(e,t,o,r,n,a,i)=>{const s={[V.VIDEO]:g.EXPORT_VIDEO_DONE,[V.CAPTION_VIDEO]:g.EXPORT_CAPTION_VIDEO_DONE,[V.AUDIO_MP3]:g.EXPORT_AUDIO_DONE,[V.AUDIO_WAV]:g.EXPORT_AUDIO_DONE,[V.AUDIO_AAC]:void 0,[V.IMAGE]:g.EXPORT_IMAGE_DONE,[V.ANIMATED_IMAGE]:g.EXPORT_IMAGE_DONE,[V.TRANSCODING_VIDEO]:void 0,[V.TRANSCODING_AUDIO]:void 0,[V.CONVERTING_GIF]:void 0,[V.STREAM]:void 0,[V.SPLIT_MEDIA]:void 0,[V.STATIC_FRAME]:void 0,[V.PROXY_VIDEO]:void 0},x=s[e];if(x){let d="",u={exportId:i};if(e===V.VIDEO){const p=n?""+vA[n.color]+(n.index+1):"";d=n?"none":"1_"+p,u=n?{vrewMarkLength:1,vrewMarkDesc:p,exportId:i}:{exportId:i}}else e===V.IMAGE&&a!==void 0&&(d=t+"_"+a.toString(),u={outputType:t,imageEncodingClipNum:a,exportId:i});I().event(m.EXPORT,x,d,void 0,u===void 0?void 0:JSON.stringify(u))}const c={[V.VIDEO]:g.EXPORT_VIDEO_DONE_2,[V.CAPTION_VIDEO]:g.EXPORT_CAPTION_VIDEO_DONE_2,[V.AUDIO_MP3]:g.EXPORT_AUDIO_DONE_2,[V.AUDIO_WAV]:g.EXPORT_AUDIO_DONE_2,[V.AUDIO_AAC]:void 0,[V.IMAGE]:void 0,[V.ANIMATED_IMAGE]:void 0,[V.TRANSCODING_VIDEO]:void 0,[V.TRANSCODING_AUDIO]:void 0,[V.CONVERTING_GIF]:void 0,[V.STREAM]:void 0,[V.SPLIT_MEDIA]:void 0,[V.STATIC_FRAME]:void 0,[V.PROXY_VIDEO]:void 0},l=c[e];if(l){const d=o+"_"+r,u={allMediaNum:o,currentSceneNum:r,exportId:i};I().event(m.EXPORT,l,d,void 0,JSON.stringify(u))}},YMe=(e,t,o)=>{const r={[V.VIDEO]:g.EXPORT_VIDEO_CANCEL,[V.CAPTION_VIDEO]:g.EXPORT_CAPTION_VIDEO_CANCEL,[V.AUDIO_MP3]:g.EXPORT_AUDIO_CANCEL,[V.AUDIO_WAV]:g.EXPORT_AUDIO_CANCEL,[V.AUDIO_AAC]:void 0,[V.IMAGE]:g.EXPORT_IMAGE_CANCEL,[V.ANIMATED_IMAGE]:void 0,[V.TRANSCODING_VIDEO]:void 0,[V.TRANSCODING_AUDIO]:void 0,[V.CONVERTING_GIF]:void 0,[V.STREAM]:void 0,[V.SPLIT_MEDIA]:void 0,[V.STATIC_FRAME]:void 0,[V.PROXY_VIDEO]:void 0},n=r[e];if(n){const a=e===V.VIDEO?t?Vc.ON:Vc.OFF:void 0,i=JSON.stringify({exportId:o});I().event(m.EXPORT,n,a,void 0,i)}},BMe=(e,t,o)=>{const r=e+"_"+t,n={exportId:o,mediaNum:e,sceneNum:t};I().event(m.EXPORT,g.EXPORT_SRT_DONE,r,void 0,JSON.stringify(n))},KMe=(e,t,o,r)=>{I().event(m.EXPORT,g.EXPORT_TEXT_DONE,e,void 0,JSON.stringify({exportId:r}));const n=t+"_"+o,a={allMediaNum:t,sceneNum:o,exportId:r};I().event(m.EXPORT,g.EXPORT_TEXT_DONE_2,n,void 0,JSON.stringify(a))},XMe=(e,t,o)=>{const r=e+"_"+t,n={mediaNum:e,sceneNum:t,exportId:o};I().event(m.EXPORT,g.EXPORT_PREMIERE_DONE,r,void 0,JSON.stringify(n))},JMe=(e,t,o)=>{const r=e+"_"+t,n={mediaNum:e,sceneNum:t,exportId:o};I().event(m.EXPORT,g.EXPORT_FCPX_DONE,r,void 0,JSON.stringify(n))},qMe=(e,t,o)=>{const r=e+"_"+t,n={mediaNum:e,sceneNum:t,exportId:o};I().event(m.EXPORT,g.EXPORT_DAVINCI_FCPX_DONE,r,void 0,JSON.stringify(n))},EP=(e,t,o)=>{const r=e+"_"+t,n={markerNum:e,clipsNum:t,exportId:o};I().event(m.EXPORT,g.EXPORT_USED_MARKER_COUNT,r,void 0,JSON.stringify(n))},Udt=e=>{I().event(m.OPEN,g.OPEN_PROJECT_WITH_DRAG_AND_DROP,e)}
1244,Vdt=e=>{I().event(m.INSERT,g.INSERT_IMAGE_ERROR,e?"typeError":"zoneError")},QMe=e=>e===Kn.INIT,ZMe=(e,t)=>{const o={[Kn.INIT]:"init",[Kn.CUSTOM_LIST]:"customList",[Kn.OS_DIALOG_OLD]:"osDialogOld",[Kn.OS_DIALOG_NEW]:"osDialogNew",[Kn.FILE_CLICK]:"fileClick",[Kn.DRAG_AND_DROP]:"dragAndDrop",[Kn.UNKNOWN]:"unknown"},r={[Kn.INIT]:"outside",[Kn.CUSTOM_LIST]:"inside",[Kn.OS_DIALOG_OLD]:"inside",[Kn.OS_DIALOG_NEW]:"inside",[Kn.FILE_CLICK]:"outside",[Kn.DRAG_AND_DROP]:"outside",[Kn.UNKNOWN]:"unknown"},n=e?"ios":"desktop",{created:a,updated:i}=Yo().getLastSaveInfo();I().event(m.OPEN_PROJECT,g.OPEN_PROJECT_DONE,QMe(t)?"auto":"user",void 0,JSON.stringify({projectOpenedFrom:r[t],projectOpenMethod:o[t],projectGenLocation:n,projectCreatedVersion:a?.version,projectCreatedStage:a?.stage,projectUpdatedVersion:i?.version,projectUpdatedStage:i?.stage,currentClientVersion:Ha(),currentVrewJsonVersion:Be.CURRENT_VREW_JSON_VERSION}))},$Me=()=>{I().event(m.AUTO_RECOVER,g.OPEN_PROJECT_DONE)},eDe=e=>{const t=e==="video"?g.OPEN_VIDEO_DONE:g.OPEN_AUDIO_DONE;I().event(m.AUTO_RECOVER,t)},Gdt=()=>{I().event(m.IMPORT_TEXT,g.ATTACH_TEXT)},tDe=e=>{I().event(m.IMPORT_TEXT,g.IMPORT_TEXT_DONE,e?"fromScript":"fromTimetext")},Wdt=e=>{I().event(m.UPLOAD,g.POPUP_SETTING_IMPORT_SCRIPT,e)},Hdt=(e,t)=>{I().event(m.IMPORT_SCRIPT,g.CLICK_TAB_IMPORT_SCRIPT_OPTION,e,void 0,JSON.stringify({importScriptMethod:t.toString()}))},jdt=(e,t,o)=>{I().event(m.IMPORT_SCRIPT,g.CLICK_DIVIDE_OPTION,e,void 0,JSON.stringify({option:t,isChecked:o}))},zdt=(e,t)=>{I().event(m.IMPORT_SCRIPT,g.ATTACH_SCRIPT,e,void 0,JSON.stringify({loadingMethod:t}))},Ydt=e=>{I().event(m.IMPORT_SCRIPT,g.DELETE_SCRIPT,e)},oDe=(e,t,o,r,n)=>{const a=t.to-t.from===e?jS.MULTI_ALL:t.to-t.from===1?jS.SINGLE:jS.MULTI_CURRENT,{label:i,splitOptions:s,importScriptMethod:x,attachFileMethod:c,enteredTextLength:l}=n,d={targetSceneLabel:a,prevClipCount:o,nextClipCount:r,splitOptions:s,importScriptMethod:x.toString(),attachFileMethod:c,enteredTextLength:l};I().event(m.IMPORT_SCRIPT,g.IMPORT_SCRIPT_DONE,i,void 0,JSON.stringify(d))},wz=e=>{I().event(m.IMPORT_SCRIPT,g.IMPORT_SCRIPT_UNDO,e)},rDe=(e,t)=>{I().event(m.NOTICE_WEMAKEVOICE,g.SELECT,void 0,void 0,JSON.stringify({...e,triggerSource:t}))},nDe=e=>{I().event(m.NOTICE_WEMAKEVOICE,g.DONE,void 0,void 0,JSON.stringify(e))},Bdt=()=>{I().event(m.FEEDBACK,g.SEND_FEEDBACK_DONE)},Kdt=e=>{I().event(m.FEEDBACK,g.FEEDBACK_IMAGE_UPLOAD,void 0,void 0,JSON.stringify({uploadType:e}))},Xdt=(e,t,o,r,n,a)=>{let i;o?i="clip":r?i="word":i="all";const s={incSound:t?1:0,filterTime:a,numBlankSections:n,targetRange:i};I().event(m.SILENT_SECTIONS,g.TRUNCATE_SILENT_SECTIONS_DONE,e!==void 0?e.toString():"reset",void 0,JSON.stringify(s))},Jdt=()=>{I().event(m.EDIT_CUT_DETAIL,g.EDIT_CUT_DETAIL_PLAY)},qdt=()=>{I().event(m.EDIT_CUT_DETAIL,g.EDIT_CUT_DETAIL_PAUSE)},Qdt=()=>{I().event(m.EDIT_CUT_DETAIL,g.EDIT_CUT_DETAIL_RESET)},Zdt=()=>{I().event(m.EDIT_CUT_DETAIL,g.EDIT_CUT_DETAIL_SPLIT_WORD)},$dt=()=>{I().event(m.EDIT_CUT_DETAIL,g.EDIT_CUT_DETAIL_CHANGE_WORD_TEXT)},eut=e=>{I().event(m.EDIT_CUT_DETAIL,g.EDIT_CUT_DETAIL_CHANGE_WORD_INTERVAL,e)},tut=()=>{I().event(m.EDIT_CUT_DETAIL,g.EDIT_CUT_DETAIL_TOOLTIP_DISCONTINUOUS_SECTION)},aDe=e=>{switch(e){case pr.CTRL_P:return g.PLAY_PREVIEW_CTRLP;case pr.SPACE:return g.PLAY_PREVIEW_SPACE;case pr.TAB:return g.PLAY_PREVIEW_TAB;case pr.SHIFT_TAB:return g.PLAY_PREVIEW_SHIFT_TAB;case pr.F4:return g.PLAY_PREVIEW_F4;case pr.F5:return g.PLAY_PREVIEW_F5;default:return}},iDe=e=>{const t=aDe(e);if(t===void 0)return;const o=Ra(t);o!==void 0&&I().event(m.KEY_PLAYER,t,o)},sDe=e=>{const t=e===Ee.CLOUD?"cloud":"local";I().event(m.KEY_FILE,g.SAVE,t)},xDe=e=>{const t=e===Ee.CLOUD?"cloud":"local";I().event(m.KEY_FILE,g.SAVE_AS,t)},cDe=()=>{I().event(m.KEY_SELECT,g.SELECT_ALL)},lDe=e=>{I().event(m.KEY_SELECT,g.SELECT_ALL,"asset",void 0,JSON.stringify({selectedFrom:e}))},out=(e,t,o)=>{I().event(e,g.SELECT_CLIP,t,o)},rut=(e,t)=>{I().event(m.TOOLBAR_EDIT,g.SELECT_ASSET,e,t)},lC=e=>{const t={[so.WORD]:g.DELETE_WORD,[so.CLIP]:g.DELETE_CLIP},o=t[e],r=Ra(o);o&&r&&I().event(m.KEY_EDIT,o,r)},dDe=()=>
1244{I().event(m.IMAGE_EDIT,g.DELETE_VREW_MARK)},dC=e=>{const t={[so.WORD]:g.BACKSPACE_WORD,[so.CLIP]:g.BACKSPACE_CLIP},o=t[e],r=Ra(o);o&&r&&I().event(m.KEY_EDIT,o,r)},ik=()=>{I().event(m.KEY_EDIT,g.UNDO)},uDe=(e,t)=>{switch(t){case _r.IMPORT_MATCHED_SCRIPT:wz(e?tu.SHORTCUTKEY:tu.TOOLBAR);break;case _r.IMPORT_SUBTITLE:Pz(e?tu.SHORTCUTKEY:tu.TOOLBAR);break}},pDe=()=>{I().event(m.KEY_EDIT,g.REDO)},fDe=e=>{I().event(m.KEY_EDIT,g.COPY_IN_ORIGINAL_VIEW,e)},gDe=(e,t)=>{if(e===so.WORD||e===so.CLIP||e===so.CLIPBOARD_TEXT)I().event(m.KEY_EDIT,g.CUT,e);else{if(t.length===0){h("ga.ts").info("assetInfos is undefined");return}const o=t.length===1?"single":"multi",r=o==="single"||t.slice(1).every(i=>i.rangeType===t[0].rangeType)?t[0].rangeType:"combi",n=o==="single"?{assetType:Dt(t[0].assetType)}:cn(t.map(i=>Dt(i.assetType))),a={selectType:o,...n};I().event(m.KEY_EDIT,g.CUT_ASSET,r,void 0,JSON.stringify(a))}},_De=(e,t)=>{const o={pasteOrigin:t};I().event(m.KEY_EDIT,g.PASTE,e,void 0,JSON.stringify(o))},jd=(e,t)=>{const o={[Is.BACKSPACE]:g.MERGE_CLIPS_BACKSPACE,[Is.DELETE]:g.MERGE_CLIPS_DELETE,[Is.CTRL_E]:g.MERGE_CLIPS_CTRL_E,[Is.CTRL_SHIFT_E]:g.MERGE_CLIPS_CTRL_SHIFT_E,[Is.CTRL_M]:g.MERGE_CLIPS_CTRL_M,[Is.CTRL_SHIFT_M]:g.MERGE_CLIPS_CTRL_SHIFT_M},r=o[e],n=Ra(r,t);r&&n&&I().event(m.KEY_EDIT,r,n,void 0,t)},sk=(e,t,o,r,n)=>{e?mDe():t===io.KEY?EDe(n):t===io.CONTEXTMENU?KDe(o):t===io.FLOATING_MENU?tFe():wMe(o,r)},EDe=e=>{const t=g.DIVIDE_CLIP,o=Ra(t);o!==void 0&&I().event(m.KEY_EDIT,t,o),e!==void 0&&I().event(m.RESEARCH,g.RESEARCH_ENTERCORRECTING_KEYBOARD,"divide_clip_"+e)},mDe=()=>{I().event(m.KEY_EDIT,g.PASTE_INTO_NEXT_CLIP)},hDe=(e,t)=>{const o=e?t?g.MOVE_TO_PREVIOUS_CLIP_CAPTION:g.MOVE_TO_PREVIOUS_CLIP_CAPTION_CTRL:t?g.MOVE_TO_PREVIOUS_CLIP_WORD:g.MOVE_TO_PREVIOUS_CLIP_WORD_CTRL,r=Ra(o);r!==void 0&&I().event(m.KEY_MOVE,o,r)},IDe=(e,t)=>{const o=e?t?g.MOVE_TO_NEXT_CLIP_CAPTION:g.MOVE_TO_NEXT_CLIP_CAPTION_CTRL:t?g.MOVE_TO_NEXT_CLIP_WORD:g.MOVE_TO_NEXT_CLIP_WORD_CTRL,r=Ra(o);r!==void 0&&I().event(m.KEY_MOVE,o,r)},TDe=()=>{const e=g.MOVE_TO_PREVIOUS_EDIT_FIELD,t=Ra(e);t!==void 0&&I().event(m.KEY_MOVE,e,t)},SDe=()=>{const e=g.MOVE_TO_NEXT_EDIT_FIELD,t=Ra(e);t!==void 0&&I().event(m.KEY_MOVE,e,t)},ODe=e=>{I().event(m.KEY_MOVE,g.MOVE_TO_THE_BEGINNING_OF_LINE,e)},CDe=e=>{I().event(m.KEY_MOVE,g.MOVE_TO_THE_END_OF_LINE,e)},RDe=e=>{I().event(m.KEY_MOVE,g.MOVE_TO_THE_BEGINNING_OF_CLIP,e)},ADe=e=>{I().event(m.KEY_MOVE,g.MOVE_TO_THE_END_OF_CLIP,e)},yDe=()=>{I().event(m.KEY_MOVE,g.MOVE_TO_THE_BEGINNING_OF_THE_VIDEO)},vDe=()=>{I().event(m.KEY_MOVE,g.MOVE_TO_THE_END_OF_THE_VIDEO)},Nz=(e,t,o)=>{const r=t||o?{...t?{pasteOrigin:t}:{},triggerSource:o}:void 0;I().event(m.EDIT_CUT_WITH_MOUSE,g.DRAG_MOVE,e,void 0,r?JSON.stringify(r):void 0)},nut=()=>{const e=Ra(g.CHANGE_CAPTION);e!==void 0&&I().event(m.EDIT_CAPTION,g.CHANGE_CAPTION,e)},wDe=()=>{const e=Ra(g.CLICK_TO_PLAY_PREVIEW);e!==void 0&&I().event(m.PREVIEW,g.CLICK_TO_PLAY_PREVIEW,e)},NDe=()=>{const e=Ra(g.CLICK_PREVIEW_TO_STOP);e!==void 0&&I().event(m.PREVIEW,g.CLICK_PREVIEW_TO_STOP,e)},aut=()=>{I().event(m.PREVIEW,g.EXPAND_PREVIEW)},iut=e=>{I().event(m.PREVIEW,g.SLIDE_PREVIEW,e?"O":"X")},mP=e=>{I().event(m.ERROR,g.ERROR_IMPORT,e)},PDe=e=>{let t;e?.clipCount?t="mismatch_"+e.clipCount:e?.empty&&(t="empty"),I().event(m.ERROR,g.ERROR_IMPORT,_.C_TIMECODE_TEXT_TIMECODE_MISMATCH,void 0,t)},bDe=e=>{I().event(m.IMPORT_SUBTITLE,g.ERROR_IMPORT,e)},sut=()=>{I().event(m.IMPORT_SUBTITLE,g.ATTACH_SUBTITLE)},xut=()=>{I().event(m.IMPORT_SUBTITLE,g.DELETE_SUBTITLE)},LDe=()=>{I().event(m.IMPORT_SUBTITLE,g.IMPORT_SUBTITLE_START)},MDe=(e,t,o,r,n,a)=>{const i=e+"_"+(t?"O":"X")+"_"+o+"_"+r+"_"+n.toFixed(0)+"_"+a.toFixed(0);h("ga.ts").info("custom value of gaImportSubtitleDone:"+i),I().event(m.IMPORT_SUBTITLE,g.IMPORT_SUBTITLE_DONE,void 0,void 0,i)},Pz=e=>{I().event(m.IMPORT_SUBTITLE,g.IMPORT_SUBTITLE_UNDO,e)},cut=e=>{I().event(m.ERROR,g.ERROR_AUDIO_ANALYSIS,e)},aE=(e,t)=>{const o=JSON.stringify({exportId:t});I().event(m.ERROR,g.ERROR_EXPORT,e,void 0,o)},eS=(e,t)=>{I().event(m.ERROR,g.ERROR_CODE,e,void 0,t)},lut=e=>{I().event(m.ERROR,g.ERROR_LOGIN,e)},dut=()=>{I().event(m.AUTO_RECOVER,g.AUTO_RECOVER_DISPLAY_POPUP)},uut=()=>{I().event(m.AUTO_RECOVER,g.AUTO_RECOVER_CONFIRM)},put=()=>
1244{I().event(m.AUTO_RECOVER,g.AUTO_RECOVER_DELETE)},fut=()=>{I().event(m.AUTO_RECOVER,g.AUTO_RECOVER_CLOSE)},gut=e=>{I().event(m.KEY_EDIT,g.SEARCH,e)},_ut=e=>{I().event(m.SEARCH,g.CLOSE,e)},DDe=new Set([g.PLAY_PREVIEW_CTRLP,g.PLAY_PREVIEW_SPACE,g.PLAY_PREVIEW_TAB,g.PLAY_PREVIEW_SHIFT_TAB,g.PLAY_PREVIEW_F4,g.PLAY_PREVIEW_F5,g.CHANGE_CAPTION,g.CLICK_TO_PLAY_PREVIEW,g.CLICK_PREVIEW_TO_STOP,g.MOVE_TO_PREVIOUS_CLIP_WORD,g.MOVE_TO_PREVIOUS_CLIP_CAPTION,g.MOVE_TO_NEXT_CLIP_WORD,g.MOVE_TO_NEXT_CLIP_CAPTION,g.MOVE_TO_PREVIOUS_CLIP_WORD_CTRL,g.MOVE_TO_PREVIOUS_CLIP_CAPTION_CTRL,g.MOVE_TO_NEXT_CLIP_WORD_CTRL,g.MOVE_TO_NEXT_CLIP_CAPTION_CTRL,g.MOVE_TO_PREVIOUS_EDIT_FIELD,g.MOVE_TO_NEXT_EDIT_FIELD,g.CONTEXTMENU_DISPLAY,g.DIVIDE_CLIP,g.DELETE_WORD,g.DELETE_CLIP,g.BACKSPACE_CLIP,g.BACKSPACE_WORD,g.BACKSPACE_IMAGE,g.MERGE_CLIPS_BACKSPACE,g.MERGE_CLIPS_DELETE,g.MERGE_CLIPS_CTRL_E,g.MERGE_CLIPS_CTRL_SHIFT_E,g.MERGE_CLIPS_CTRL_M,g.MERGE_CLIPS_CTRL_SHIFT_M,g.CREATE_FORMAT,g.HOVER_MYVREW,g.ERROR_TOAST_LOCK,g.CLICK_CAPTION_SETTING_TARGET_SWITCH_AUTO,g.DISPLAY_BOOKMARK,g.DOWNLOAD_TTI_DONE,g.DOWNLOAD_GEN_VIDEO_DONE]),kDe=e=>{if(e===1)return!0;let t=10;for(;;){if(e===t)return!0;if(e<t)break;t=t*2}return!1},iu={},Ra=(e,t)=>{if(!DDe.has(e))return;const o=e+(t||"");iu[o]===void 0&&(iu[o]=0);let r=iu[o];if(r++,iu[o]=r,kDe(r))return""+r},iE=(e,t,o)=>{const r=e===void 0?g.TRANSCODE_DISPLAY_POPUP:e?g.TRANSCODE_DISPLAY_POPUP_CONFIRM:g.TRANSCODE_DISPLAY_POPUP_CLOSE,n=o;I().event(m.TRANSCODE,r,t,void 0,JSON.stringify(n))},xk=()=>{I().event(m.TRANSCODE,g.TRANSCODE_CANCEL)},FDe=(e,t)=>{const o=t;I().event(m.TRANSCODE,g.TRANSCODE_ERROR,e,void 0,JSON.stringify(o))},ck=()=>{I().event(m.TRANSCODE,g.TRANSCODE_DONE)},UDe=(e,t,o)=>{const r=e?"open":"close";I().event(m.SCENE_PANEL,g.SCENE_PANEL_HANDLE,r,void 0,JSON.stringify({behaviorType:t,numberOfOrigSource:o}))},Eut=(e,t)=>{const o=""+e;I().event(m.SCENE_PANEL,g.SCENE_ADD_MEDIA,o,void 0,JSON.stringify({addedLocation:e,numberOfOrigSource:t}))},mut=(e,t,o)=>{I().event(m.SCENE_PANEL,g.SCENE_ADD_VIDEO_DONE,void 0,void 0,JSON.stringify({addedLocation:e,numberOfAddedScenes:t,numberOfOrigSource:o}))},VDe=(e,t,o,r,n)=>{const a=e+"_"+t+"_"+o+"_"+r,i={total:e,laughter:t,clap:o,filler:r};I().event(m.UPLOAD,g.UPLOADED_VIDEO_AUDIOLABEL,a,void 0,JSON.stringify(i)),I().event(m.UPLOAD,g.UPLOAD_LOADED_WORD,""+n)},GDe=e=>{I().event(m.RED_DOT,g.USE,e)},WDe=e=>{const t=e===Tu.CLICK?"click":e===Tu.ENTER_KEY?"enter":e===Tu.FLOATING_MENU?"floating_menu":"f2";I().event(m.EDIT_CUT_DETAIL,g.EDIT_CUT_DETAIL_OPEN,t)},hut=e=>{const t=g.CONTEXTMENU_DISPLAY,o=Ra(t),r={positionLabel:e};(o!==void 0||e)&&I().event(m.MOUSECLICK_EDIT,t,o,void 0,JSON.stringify(r))},HDe=(e,t)=>{if(e===so.WORD||e===so.CLIP||e===so.CLIPBOARD_TEXT)I().event(m.KEY_EDIT,g.COPY,e);else{if(t.length===0){h("ga.ts").info("assetInfos is undefined");return}const o=t.length===1?"single":"multi",r=o==="single"||t.slice(1).every(i=>i.rangeType===t[0].rangeType)?t[0].rangeType:"combi",n=o==="single"?{assetType:Dt(t[0].assetType)}:cn(t.map(i=>Dt(i.assetType))),a={selectType:o,...n};I().event(m.KEY_EDIT,g.COPY_ASSET,r,void 0,JSON.stringify(a))}},jDe=(e,t,o)=>{if(e===so.WORD||e===so.CLIP)I().event(m.MOUSECLICK_EDIT,g.CLICK_COPY,e,void 0,t);else{if(o.length===0){h("ga.ts").info("assetInfos is undefined");return}const r=o.length===1?"single":"multi",n=r==="single"||o.slice(1).every(s=>s.rangeType===o[0].rangeType)?o[0].rangeType:"combi",a=r==="single"?{assetType:Dt(o[0].assetType)}:cn(o.map(s=>Dt(s.assetType))),i={gaBehaviorType:t,selectType:r,...a};I().event(m.MOUSECLICK_EDIT,g.CLICK_COPY_ASSET,n,void 0,JSON.stringify(i))}},zDe=(e,t)=>{I().event(m.MOUSECLICK_EDIT,g.CLICK_COPY_IN_ORIGINAL_VIEW,e,void 0,t)},YDe=(e,t,o)=>{const r={gaBehaviorType:t};if(e===so.WORD||e===so.CLIP)I().event(m.MOUSECLICK_EDIT,g.CLICK_CUT,e,void 0,JSON.stringify(r));else{if(o.length===0){h("ga.ts").info("assetInfos is undefined");return}const n=o.length===1?"single":"multi",a=n==="single"||o.slice(1).every(x=>x.rangeType===o[0].rangeType)?o[0].rangeType:"combi",i=n==="single"?{assetType:Dt(o[0].assetType)}:cn(o.map(x=>Dt(x.assetType))),s={gaBehaviorType:t,selectType:n,...i};I().event(m.MOUSECLICK_EDIT,g.CLICK_CUT_ASSET,a,void 0,JSON.stringify(s))}},BDe=(e,t,o)=>{const r={behaviorType:t,pasteOrigin:o};I().event(m.MOUSECLICK_EDIT,g.CLICK_PASTE,e,void 0,JSON.stringify(r))},Iut=e=>{const t={gaBehaviorType:e};I().event(m.MOUSECLICK_EDIT,g.CLICK_MERGE_CLIPS,void 0,void 0,JSON.stringify(t))},KDe=e=>{const t={gaBehaviorType:e};I().event(m.MOUSECLICK_EDIT,g.CLICK_DIVIDE_CLIP,void 0,void 0,JSON.stringify(t))},bz=(e,t,o,r)=>{I().event(m.MOUSECLICK_EDIT,g.CLICK_DIVIDE_SCENE,void 0,void 0,JSON.stringify({numberOfSelectedClips:e,numberOfOrigSource:t,sceneDivideType:o,triggerSource:r}))};var wA=(e=>(e.DEFAULT="default",e.ORIGINAL="original",e.TRANSLATE="translate",e))(wA||{});const Tut=(e,t,o)=>{const r=e?m.TOOLBAR_CAPTION_B:m.TOOLBAR_CAPTION_A,n=t?g.CLICK_TRANSLATE_AGAIN:g.CLICK_TRANSLATE_NEW,a=o?"
1244icon":"menu";I().event(r,n,a)},XDe=(e,t,o)=>{const r=t?m.TOOLBAR_CAPTION_B:m.TOOLBAR_CAPTION_A,n=o==="original"?g.CLICK_USE_CAPTION:g.CLICK_USE_TRANSLATED_CAPTION,a=e?"on":"off";I().event(r,n,a)},JDe=(e,t,o)=>{const r=e===Ke.ORIGINAL?o?"original":"default":"translate",n={default:t===0?g.CLICK_COPY_ALL_CAPTION:g.CLICK_COPY_SELECTED_CAPTION,original:t===0?g.CLICK_COPY_ALL_ORIGINAL_CAPTION:g.CLICK_COPY_SELECTED_ORIGINAL_CAPTION,translate:t===0?g.CLICK_COPY_ALL_TRANSLATION_CAPTION:g.CLICK_COPY_SELECTED_TRANSLATION_CAPTION},a=n[r],i=t===0?void 0:t.toString(),s=o?m.TOOLBAR_CAPTION_B:m.TOOLBAR_CAPTION_A;I().event(s,a,i)},Sut=(e,t,o)=>{const r={default:t===void 0?g.CLICK_DELETE_ALL_CAPTION:g.CLICK_DELETE_SELECTED_CAPTION,original:t===void 0?g.CLICK_DELETE_ALL_ORIGINAL_CAPTION:g.CLICK_DELETE_SELECTED_ORIGINAL_CAPTION,translate:t===void 0?g.CLICK_DELETE_ALL_TRANSLATION_CAPTION:g.CLICK_DELETE_SELECTED_TRANSLATION_CAPTION},n=r[e],a=t===void 0?void 0:t.toString(),i=o?m.TOOLBAR_CAPTION_B:m.TOOLBAR_CAPTION_A;I().event(i,n,a)},qDe=(e,t,o)=>{const r=e===Ke.TRANSLATE?"translate":o?"original":"default",n={default:t===0?g.CLICK_COPY_ALL_CAPTION:g.CLICK_COPY_SELECTED_CAPTION,original:t===0?g.CLICK_COPY_ALL_ORIGINAL_CAPTION:g.CLICK_COPY_SELECTED_ORIGINAL_CAPTION,translate:t===0?g.CLICK_COPY_ALL_TRANSLATION_CAPTION:g.CLICK_COPY_SELECTED_TRANSLATION_CAPTION},a=n[r],i=t===0?void 0:t.toString();I().event(m.MOUSECLICK_EDIT,a,i)},Out=(e,t)=>{const o={default:t===void 0?g.CLICK_DELETE_ALL_CAPTION:g.CLICK_DELETE_SELECTED_CAPTION,original:t===void 0?g.CLICK_DELETE_ALL_ORIGINAL_CAPTION:g.CLICK_DELETE_SELECTED_ORIGINAL_CAPTION,translate:t===void 0?g.CLICK_DELETE_ALL_TRANSLATION_CAPTION:g.CLICK_DELETE_SELECTED_TRANSLATION_CAPTION},r=o[e],n=t===void 0?void 0:t.toString();I().event(m.MOUSECLICK_EDIT,r,n)},Cut=e=>{const t=e?g.CLICK_TRANSLATE_AGAIN:g.CLICK_TRANSLATE_NEW;I().event(m.MOUSECLICK_EDIT,t)},Rut=()=>{I().event(m.TOOLBAR_INSERT,g.CLICK_INSERT_IMAGE)},Aut=()=>{I().event(m.TOOLBAR_FILTER,g.CLICK_FILTER)},yut=()=>{I().event(m.TOOLBAR_EFFECT,g.CLICK_DENOISE)},vut=()=>{I().event(m.TOOLBAR_EFFECT,g.CLICK_TRANSITION)},wut=e=>{I().event(m.TOOLBAR_EFFECT,g.TOGGLE_PLAYBACK_PANEL,e?"open":"close")},Nut=e=>{I().event(m.TOOLBAR_EFFECT,g.CLICK_ZOOM_ROTATE,e?"open":"close")},QDe=(e,t)=>{I().event(e===z.IMAGE?m.IMAGE_EDIT:m.TEXT_EDIT,g.RESIZE_IMAGE,void 0,void 0,t?JSON.stringify({triggerSource:t}):void 0)},ZDe=e=>{I().event(m.IMAGE_EDIT,g.MOVE_IMAGE,void 0,void 0,e?JSON.stringify({triggerSource:e}):void 0)},$De=e=>{I().event(m.IMAGE_EDIT,g.ROTATE_IMAGE,void 0,void 0,e?JSON.stringify({triggerSource:e}):void 0)},Put=(e,t)=>{I().event(m.IMAGE_EDIT,g.CROP_ENTER,void 0,void 0,JSON.stringify({isAlreadyCropped:e,cropEnterReason:t}))},but=(e,t,o)=>{I().event(m.IMAGE_EDIT,g.CROP_CONFIRM,void 0,void 0,JSON.stringify({modified:e,cropConfirmReason:t,cropEnterInfo:o}))},Lut=(e,t)=>{I().event(m.VIDEO_EDIT,g.CROP_ENTER,void 0,void 0,JSON.stringify({isAlreadyCropped:e,cropEnterReason:t}))},Mut=(e,t,o)=>{I().event(m.VIDEO_EDIT,g.CROP_CONFIRM,void 0,void 0,JSON.stringify({modified:e,cropConfirmReason:t,cropEnterInfo:o}))},Dut=()=>{I().event(m.IMAGE_EDIT,g.STRETCH_IMAGE)},eke=()=>{I().event(m.IMAGE_CLICK_MENU,g.MOVE_TO_FRONT)},tke=()=>{I().event(m.IMAGE_CLICK_MENU,g.MOVE_FORWARD)},oke=()=>{I().event(m.IMAGE_CLICK_MENU,g.MOVE_BACKWARD)},rke=()=>{I().event(m.IMAGE_CLICK_MENU,g.MOVE_TO_BACK)},nke=["image","video","bgm","soundfx","text","character","gif","ai_voice_clip","ai_voice_over_clip","ai_voice_dubbing","shape","lottie","vrewmark","overdub","video_audio"],cn=e=>{const t=new Map;nke.forEach(n=>{n!=="lottie"&&t.set(n,0)}),e.forEach(n=>{t.set(n,t.get(n)+1)});const o=Array.from(t.entries()).filter(n=>{const[,a]=n;return a>0}).map(n=>{const[a,i]=n;return a+"_"+i}).join("/"),r=Array.from(t.values()).reduce((n,a)=>n+a,0);return{assetType:o,totalCount:r}},kut=(e,t)=>{const o=e.length===1?"single":"multi",r=g.SELECT,n=e[0].rangeType,a=o==="single"||e.slice(1).every(x=>x.rangeType===n)?n:"combi",i=o==="single"?{assetType:Dt(e[0].assetType)}:cn(e.map(x=>Dt(x.assetType))),s={selectType:o,...i};I().event(m.ASSET_CURSOR,r,a,void 0,JSON.stringify(s))},ake=(e,t)=>{const o=t.length===1?"single":"multi",r=o==="single"?{assetType:Dt(t[0])}:cn(t.map(a=>Dt(a))),n={selectType:o,...r};I().event(m.ASSET_CURSOR,g.DELETE,e,void 0,JSON.stringify(n))},Fut=(e,t)=>{const o=Dt(e);t?I().event(m.LIST_EDIT,g.CHANGE_NEW_CLIP,void 0,void 0,JSON.stringify({selectType:"single",assetType:o})):I().event(m.ASSET_CURSOR,g.CHANGE_NEW_CLIP,o)},Uut=(e,t)=>{const o=t.length===1?"single":"multi";t.length>1&&h("ga.ts").info("gaAudioChangeVolume: "+t.length+" assets");const r=o==="single"?{assetType:Dt(t[0])}:cn(t.map(a=>Dt(a))),n={...r};I().event(m.ASSET_CURSOR,g.VOLUME_SLIDER,r.assetType==="soundfx"?e.toFixed(2):e.toString(),void 0,JSON.stringify(n))},Vut=e=>{const t=e.length===1?"single":"multi",o=t==="single"||e.slice(1).every(a=>a.rangeType===e[0].rangeType)?e[0].rangeType:"combi",r=t==="single"?{assetType:Dt(e[0].assetType)}:cn(e.map(a=>Dt(a.assetType))),n={...r};I().event(m.ASSET_CURSOR,g.CLICK_VOLUME_EDIT,o,void 0,JSON.stringify(n))},Gut=e=>{const t=Dt(z.VIDEO),o={assetType:t};I().event(m.ASSET_CURSOR,g.CLICK_EDIT_VIDEO_START,e,void 0,JSON.stringify(o))},Wut=e=>{const t=e.length===1?"single":"multi",o=t==="single"?{assetType:Dt(e[0])}:cn(e.map(n=>Dt(n))),r={selectedType:t,...o};I().event(m.ASSET_CURSOR,g.CLICK_EDIT_RANGE,void 0,void 0,JSON.stringify(r))}
1244,ike=e=>{switch(e.type){case Dn.ALL_SCENES:return"all-clips";case Dn.ALL_CLIPS_IN_CURRENT_SCENE:return"all-clips-in-scene";case Dn.PROJECT_START_TO_CURRENT:return"scenes-first-now-clips";case Dn.START_TO_CURRENT:return"first-now-clips";case Dn.CURRENT_TO_END:return"now-final-clips";case Dn.CURRENT_TO_PROJECT_END:return"now-scenes-final-clips";case Dn.CURRENT_CLIP:return"word-to-current-clip";case Dn.TO_CURRENT_CLIP_START_WORD:return"clip-to-word";case Dn.CUSTOM:return"custom-clips"}},ske=e=>{if(e.type!==Dn.CUSTOM)return;const{chunks:t}=e,{clipCount:o,clipGroupCount:r}=t.reduce((n,a)=>(n.clipCount=n.clipCount+a.to-a.from,n.clipGroupCount=n.clipGroupCount+1,n),{clipCount:0,clipGroupCount:0});return{clipCount:o,clipGroupCount:r}},Hut=(e,t,o)=>{const r=e.length===1?"single":"multi",n=r==="single"?{assetType:Dt(e[0])}:cn(e.map(c=>Dt(c))),a=o?"asset_list":"asset_cursor",i=ske(t),s={...n,selectedFrom:a,selectedType:r,...i},x=ike(t);I().event(m.EDIT_RANGE,g.CONTEXT_MENU_EDIT_RANGE,x,void 0,JSON.stringify(s))},jut=(e,t)=>{const o=e.length===1?"single":"multi",r=o==="single"?{assetType:Dt(e[0])}:{assetType:cn(e.map(a=>Dt(a))).assetType},n={selectedType:o,...r};I().event(m.ASSET_CURSOR,g.FILL,t,void 0,JSON.stringify(n))},zut=e=>{const t=e.length===1?"single":"multi",o=t==="single"?{assetType:Dt(e[0])}:{assetType:cn(e.map(n=>Dt(n))).assetType},r={selectedType:t,...o};I().event(m.ASSET_CURSOR,g.ANIMATION,void 0,void 0,JSON.stringify(r))},Yut=e=>{const t=e.length===1?"single":"multi",o=t==="single"?{assetType:Dt(e[0])}:{assetType:cn(e.map(n=>Dt(n))).assetType},r={selectedType:t,...o};I().event(m.ASSET_CURSOR,g.REPLACE,void 0,void 0,JSON.stringify(r))},xke=(e,t,o)=>{if(t>0){const r=e+"_"+t,n={vrewMarkNum:e,userImageNum:t,exportId:o};I().event(m.SUMMARY_IMAGE,g.SUMMARY_IMAGE_COUNT,r,void 0,JSON.stringify(n))}},cke=(e,t)=>{const o=JSON.stringify({exportId:t});for(let r=0;r<e.length;++r)I().event(m.SUMMARY_IMAGE,""+g.SUMMARY_IMAGE_USAGE_PREFIX+(r+1),e[r],void 0,o)},lke=(e,t,o,r)=>{const n=o===0?0:Math.floor(e/o*100)/100,a=o===0?0:Math.floor(t/o*100)/100;if(e>0||t>0){const i=n+"_"+a,s={vrewMarkRatio:n,userImageRatio:a,exportId:r};I().event(m.SUMMARY_IMAGE,g.SUMMARY_IMAGE_CLIP_RATIO,i,void 0,JSON.stringify(s))}},But=e=>{I().event(m.FEATURE_POPUP,g.DISPLAY,e)},Kut=(e,t)=>I().event(m.FEATURE_POPUP,g.CLOSE,e,void 0,JSON.stringify({closedAfter:t})),Lz=(e,t,o,r,n,a,i,s)=>{const x=z2(r,e),c=tS(n),l=Math.max(e,t),d=x+"_"+l+"_"+c,u={importRangeString:x,maxCount:l,imageImportString:c,imageType:a?"free-image":"pc-image",myassetInsertMethod:i===void 0?nm.NONE:i.insertMethod,myassetSection:i===void 0?UU.NONE:i.sectionType,imageOrderNum:i===void 0?null:i.index+1,myassetImageId:i===void 0?"none":i.hash,isFavoriteAsset:i===void 0?"none":i.isFavoriteAsset?"favorite":"not-favorite",isReplace:!!s,replaceOrigAspectRatio:s?ue(s.originalAspectRatio,2):void 0,replaceNewAspectRatio:s?ue(s.newAspectRatio,2):void 0};I().event(m.INSERT,g.INSERT_IMAGE_DONE_MENU,d,void 0,JSON.stringify(u))},Mz=(e,t,o,r)=>{const n=t>0?"selected-words":e>0?"selected-clips":"current-clip",a=Math.max(e||1,t),i=n+"_"+a,s=o.length===1?"single":"multi",x=s==="single"?{assetType:Dt(o[0].assetType)}
1244:cn(o.map(l=>Dt(l.assetType))),c={selectType:s,pasteOrigin:r,...x};I().event(m.INSERT,g.INSERT_ASSET_DONE_PASTE,i,void 0,JSON.stringify(c))},Dt=e=>{switch(e){case z.SIMPLE_CHARACTER:return"character";case z.WEB:return"text";case ze.SoundEffect:return"soundfx";case ze.TTSDubbing:return"ai_voice_dubbing";case ze.TTSEffect:return"ai_voice_over_clip";case ze.VideoAudio:return"video_audio";case z.WATERMARK:return"vrewmark";case ze.Overdub:return"overdub";case z.LOTTIE:return"lottie";case z.SHAPE:return"shape";case z.IMAGE:return"image";case z.VIDEO:return"video";case ze.BGM:return"bgm";case ze.TTSClip:return"ai_voice_clip"}},Xut=(e,t,o,r)=>{const n=GK(o,r,t);if(n===void 0)return;const a=Dt(n);I().event(m.EDIT_RANGE,g.CLICK_DOT,e,void 0,JSON.stringify({assetType:a}))},Jut=(e,t,o,r,n,a,i)=>{const s=GK(e,t,o);if(s===void 0)return;const x=Dt(s),c=Math.abs(n-a),l=i==="TOP"&&n>a||i==="BOTTOM"&&n<a,d=r+"_"+c+"_"+(l?"o":"x"),u={assetType:x,preselected:r,newselected:c,isFlipped:l?"o":"x"};I().event(m.EDIT_RANGE,g.DRAG_DOT,d,void 0,JSON.stringify(u))},qut=e=>{const t=Dt(e),o={assetType:t};I().event(m.ASSET_CURSOR,g.AI_VOICE_DETAIL,void 0,void 0,JSON.stringify(o))},dke=(e,t,o,r)=>{const n=xi(t,o),a=Vz(e),i=Math.max(o,r),s=n+"_"+i+"_"+a,x={importRangeString:n,maxCount:i,textboxImportString:a};e===Yt.TEXTBOX_TOOLBAR?I().event(m.TOOLBAR_INSERT,g.CLICK_TEXTBOX,s,void 0,JSON.stringify(x)):e===Yt.CONTEXT_FLOATING_MENU?I().event(m.CONTEXT_FLOATING_MENU,g.CLICK_TEXTBOX,s,void 0,JSON.stringify(x)):e===Yt.CONTEXT_MENU?I().event(m.MOUSECLICK_EDIT,g.CLICK_TEXTBOX,s):e===Yt.ANNOUNCEMENT_IMAGE&&I().event(m.ANNOUNCEMENT_IMAGE,g.CLICK_TEXTBOX,s,void 0,JSON.stringify(x))},Qut=()=>{I().event(m.FILTER,g.RETURN_TO_ORIGINAL)},Zut=e=>{I().event(m.FILTER,g.SELECT_FILTER,e)},$ut=(e,t)=>{const o=e+"_"+Math.floor(t*100),r={filterName:e,alpha:Math.floor(t*100)};I().event(m.FILTER,g.ADJUST,o,void 0,JSON.stringify(r))},e2t=()=>{I().event(m.FILTER,g.CLICK_ICON)},t2t=()=>{I().event(m.FILTER,g.CLICK_DELETE_EFFECT)},o2t=()=>{I().event(m.FILTER,g.LOAD_LUT,Uh.BUTTON_CLICK)},r2t=()=>{I().event(m.TOOLBAR_HOME,g.CLICK_ANNOUNCEMENT)},n2t=e=>{I().event(m.ANNOUNCEMENT_IMAGE,g.TRY_NOW,e)},a2t=()=>{I().event(m.FILTER,g.LOAD_LUT,Uh.LOAD)},i2t=()=>{I().event(m.FILTER,g.LOAD_LUT,Uh.COMPLETED)},s2t=()=>{I().event(m.FILTER,g.LOAD_LUT,Uh.FAILED)},uke=(e,t)=>{e!==0&&I().event(m.EXPORT,g.EXPORT_FILTER,void 0,void 0,JSON.stringify({filterAppliedClipCount:e,exportId:t}))},pke=(e,t,o,r)=>{const n=e?g.MP4_FILTER:g.MP4_ORIGINAL,a=t+"_"+o,i={exportId:r,srcTotalMin:t,elapsedTotalMin:o};I().event(m.SUMMARY_EXPORT,n,a,void 0,JSON.stringify(i))},fke=(e,t,o)=>{const r=t+"_"+(e?"o":"x"),n={hwAccel:t,useHwAccel:e?"o":"x",exportId:o};I().event(m.INIT,g.INIT_HWACCEL,r,void 0,JSON.stringify(n))},gke=(e,t,o)=>{const r=t+"_"+(e?"o":"x"),n={hwAccel:t,useHwAccel:e?"o":"x",exportId:o};I().event(m.EXPORT,g.EXPORT_VIDEO_DONE_3,r,void 0,JSON.stringify(n))},x2t=e=>{const t=vA[e.color]+"_"+(e.index+1),o={vrewMarkColor:vA[e.color],vrewMarkIndex:e.index+1};I().event(m.VREWMARK,g.VREWMARK_SELECT,t,void 0,JSON.stringify(o))},_ke=()=>{I().event(m.STT,g.DISPLAY_POPUP)};let lk=!1;const Eke=()=>{lk||(lk=!0,I().event(m.PREVIEW,g.PLAY_NOT_READY))},mke=e=>{I().event(m.DEMO,g.DEMO_LOADED,e.toFixed(2))},hke=()=>{I().event(m.DEMO,g.FAILED)},Ike=e=>{I().event(m.POPUP,g.LOGIN,e)},Tke=(e,t,o,r,n)=>{const a=e.toFixed(3)+"_"+Math.ceil(t)+"_"+o+"}",i={elapsed:e,projectDuration:t,fileSize:o,totalMediaSize:r,projectType:n};I().event(m.INIT,g.LOADING,a,void 0,JSON.stringify(i))},Ske=(e,t,o,r,n)=>{if(e){if(t===Ee.PROJECT)$Me();else{const a=bi(Fh).test(o)?"video":bi(xy).test(o)?"audio":void 0;a?eDe(a):h("ga.ts").warn("unknown media type "+o)}return}(t===Ee.PROJECT||t===Ee.BROWSER||t===Ee.CLOUD)&&ZMe(r,n)},Oke=e=>{const t=ks();if(!t)return;const o=Yo().projectStartMode,r=He(t).length,n=Lv(t),a=I2(t),i=j0(a),s={projectTriggerType:e,startMode:o===Ei.DRAG_AND_DROP||o===Ei.VDROP?Ei.VIDEO_AUDIO:o,numClip:r,totalDurationSec:ue(n,3),videoAudioModeDetail:o===Ei.VIDEO_AUDIO||o===Ei.DRAG_AND_DROP||o===Ei.VDROP?o:"NONE",videoRatio:o===Ei.SHORTS?he.VERTICAL:i};I().event(m.START_NEW_PROJECT,g.NEW_PROJECT_STARTED,void 0,void 0,JSON.stringify(s))},c2t=()=>{I().event(m.TOOLBAR_FILE,g.CLICK_FILEINFO)},l2t=(e,t)=>{I().event(m.FILEINFO,g.DISPLAY,e?"project_"+t.toString():"file")},d2t=()=>{I().event(m.FILEINFO,g.SAVE_PROJECT,"save_project")},u2t=()=>{I().event(m.FILEINFO,g.SAVE_PROJECT,"open_dialog")},p2t=()=>{I().event(m.FILEINFO,g.CHANGE_VIDEO,"change_video")},f2t=()=>{I().event(m.FILEINFO,g.CHANGE_VIDEO,"open_dialog")},g2t=()=>{I().event(m.FILEINFO,g.OPEN_FOLDER)},_2t=e=>{I().event(m.FILEINFO,g.CANCEL,e.toString())},E2t=e=>{I().event(m.FILEINFO,g.CONFIRM,e.toString())},m2t=e=>{const t=e?"with_rec":"without_rec";I().event(m.FIND_SOURCE,g.FINDSOURCE_DISPLAY,t)},h2t=(e,t)=>{const o={[zl.CONFIRM]:g.FINDSOURCE_BTN_CONFIRM,[zl.CANCEL]:g.FINDSOURCE_BTN_CANCEL,[zl.FIND]:g.FINDSOURCE_BTN_FIND},r=o[e],n=t?"with_rec":"without_rec";I().event(m.FIND_SOURCE,r,n)},I2t=()=>{I().event(m.FIND_SOURCE,g.FINDSOURCE_DONT_ASK_AGAIN,"checked")},T2t=e=>{I().event(m.TOOLBAR_CAPTION_A,g.CLICK_VIDEO_LOCK,e?"lock":"unlock")},S2t=e=>{I().event(m.TOOLBAR_SETTING,g.CLICK_VIDEO_LOCK,e?"lock":"unlock")},Cke=()=>{const e=g.ERROR_TOAST_LOCK,t=Ra(e);t!==void 0&&I().event(m.KEY_EDIT,e,t)},O2t=(e,t,o,r,n)=>{const a={numSearchResult:e,numResultVideoCut:t,numResultCaption:o,isMatchCase:r?"matchcase-on":"matchcase-off",isMatchWord:n?"bywords-on":"bywords-off"};I().event(m.SEARCH,g.SEARCH_SEARCH,e.toString(),void 0,JSON.stringify(a))},C2t=(e,t,o)=>{const r=e?g.SEARCH_PREVIOUS:g.SEARCH_NEXT,n=t+"_"+o,a={numCurrentResult:t,numSearchResult:o};I().event(m.SEARCH,r,n,void 0,JSON.stringify(a))},R2t=e=>{I().event(m.SEARCH,g.CLICK_TAB,e)},A2t=e=>{I().event(m.SEARCH,g.CLICK_CHECKBOX_FROM_LIST,void 0,void 0,JSON.stringify({isChecked:e}))},y2t=()=>{I().event(m.SEARCH,g.CLICK_CLIP_AREA_FROM_LIST)},v2t=(e,t)=>{I().event(m.SEARCH,g.CLICK_RECOMMENDED_WORD,e,void 0,JSON.stringify({wordOrder:t}))},w2t=e=>{I().event(m.SEARCH,g.CLICK_CHECK_ALL,e)},N2t=e=>{const t=e?"on":"off";I().event(m.REPLACE,g.REPLACE_MATCH_CASE,t)},P2t=e=>{const t=e?"on":"off";I().event(m.REPLACE,g.REPLACE_WHOLE_WORDS,t)},b2t=()=>{I().event(m.REPLACE,g.REPLACE_ASK_REPLACE)},L2t=()=>{I().event(m.REPLACE,g.REPLACE_ASK_DELETE)},M2t=()=>{I().event(m.REPLACE,g.CLOSE_REPLACE)},D2t=()=>{I().event(m.REPLACE,g.CLOSE_DELETE)},k2t=(e,t)=>{I().event(m.REPLACE,g.REPLACE_DELETE,void 0,void 0,JSON.stringify({isDeleteAll:e,cnt:t}))},F2t=(e,t,o,r)=>{const n=e==="selected"?"multi":e,a=n+"_"+t+"_matchcase-"+(o?"on":"off")+"_bywords-"+(r?"on":"off"),i={isReplaceAll:e,cnt:t,isMatchCase:o?"matchcase-on":"matchcase-off",isMatchWord:r?"bywords-on":"bywords-off"};I().event(m.REPLACE,g.REPLACE_REPLACE,a,void 0,JSON.stringify(i))},U2t=()=>{I().event(m.REPLACE,g.CLICK_FILTER)},dh=(e,t)=>{let o;
1244typeof t=="object"&&"engine"in t&&(o=JSON.stringify(t)),I().event(m.TRANSLATE,g.FAIL_BY_SYSTEM,e,void 0,o)},Rke=e=>{I().event(m.TRANSLATE,g.FAIL_BY_USER,void 0,void 0,e)},Ake=()=>{I().event(m.TRANSLATE,g.CANCEL)},yke=(e,t,o,r,n,a)=>{const i={numSentence:e,numChar:t,sourceLanguage:o,targetLanguage:r,type:a,engineType:n.engine};I().event(m.TRANSLATE,g.SEND,void 0,void 0,JSON.stringify(i))},vke=(e,t,o,r,n,a)=>{const i=t!==0?(o/t).toFixed(2):"0",s=a===io.BUTTON?"toolbar":a===io.CONTEXTMENU?"mouseclickcontext":a===io.KEY?"ctrl+R":"undefined",x={method:s,numClips:e,numSentences:t,numInconsistentSentences:o,ratioOfinconsistent:i,engine:n.engine};I().event(m.TRANSLATE,g.TRANSLATE_DONE,r,void 0,JSON.stringify(x))},wke=(e,t,o,r,n)=>{const a=t!==0?(o/t).toFixed(2):"0",i=n===io.BUTTON?"toolbar":n===io.CONTEXTMENU?"mouseclickcontext":n===io.KEY?"ctrl+R":"undefined",s=i+"_"+e+"_"+t+"_"+o+"_"+a;I().event(m.TRANSLATE,g.TRANSLATE_AGAIN_DONE,r.toString(),void 0,s)},Nke=(e,t,o,r,n)=>{const a=t!==0?(o/t).toFixed(2):"0",i=n===io.BUTTON?"toolbar":n===io.CONTEXTMENU?"mouseclickcontext":n===io.KEY?"ctrl+R":"undefined",s=i+"_"+e+"_"+t+"_"+o+"_"+a;I().event(m.TRANSLATE,g.TRANSLATE_SELECTED_AGAIN_DONE,r.toString(),void 0,s)},Pke=e=>{const t=e.join("_"),o=e.length+"_"+t;I().event(m.TRANSLATE,g.MULTIPLE_TRANSLATE_DONE_SRT,void 0,void 0,o)},bke=(e,t,o)=>{const r=e+"_"+t+"_"+o+"%",n=JSON.stringify({totalLen:e,nonEditedClipsLen:t,nonEditedClipsRatio:o});I().event(m.TRANSLATE,g.GUIDE_EDIT_FIRST,r,void 0,n)},V2t=()=>{I().event(m.KEY_HELP,g.SHOW_KEYBOARD_SHORTCUTS),Dz(io.KEY)},Dz=e=>{I().event(m.SHORTCUTS_POPUP,g.DISPLAY,e)},Lke=(e,t)=>{const o=t.length,r=t.filter(l=>l).length,n=o===0?0:Math.floor(r/o*100),a=Math.floor(n/20)*20;let i=0,s=0;for(let l=0;l<t.length-1;l++){const d=t[l],u=t[l+1];d&&!u&&(i===0&&(s=l),i=i+1)}const x=t[t.length-1]?1:0,c=o+"_"+r+"_"+n+"_"+a+"_"+i+"_"+s+"_"+x;I().event(e,e===m.EXPORT?g.EXPORT_ACTIVE_COUNT:g.UPLOAD_ACTIVE_COUNT,void 0,void 0,c)},Mke=(e,t,o,r,n,a,i,s)=>{const{elapsedSec:x,outputBitRate:c,encodingPerformance:l}=e,d=ue(r/x,2),u=c===void 0?0:c/8*r,p=ue(u/x,2),f=t===gr.NONE?"cpu":t,E=i?{cpu:i.summary.cpu,cpuSpeedInGhz:i.cpu.speedInGHz,memoryTotalInBytes:i.mem.totalInBytes,memoryUsedInBytes:i.mem.usedInBytes,memoryUsagePercentage:i.mem.totalInBytes===0?0:ue(i.mem.usedInBytes*100/i.mem.totalInBytes,2),gpu:i.gpu.gpus.length===0?{model:"none",vramInMb:0}:i.gpu.gpus[0]}:void 0,T=JSON.stringify({videoExportElapsedSeconds:x,hwAccelLabel:f,outputVideoDurationSeconds:r,videoResolution:o.width+"x"+o.height,fps:a,encodingQuality:n,sys:E,encodingPerformance:l,outputBitRate:c,outputFileSizeInBytes:u,outputSecondsPerExportElapsedSeconds:d,outputBytesPerExportElapsedSeconds:p,exportId:s});I().event(m.EXPORT,g.EXPORT_PERFORMANCE_RESULT,void 0,void 0,T)},Dke=(e,t)=>{I().event(m.SMART_SURVEY,g.DISPLAY,e,void 0,""+t)},kz=e=>{I().event(m.SMART_SURVEY,g.CLOSE,e)},Fz=e=>{I().event(m.SMART_SURVEY,g.JOIN,e)},kke=()=>{I().event(m.INVALID_FONT,g.INCLUDED)},G2t=(e,t)=>{I().event(m.GUIDE_TOOLTIP,e,t)},W2t=e=>{I().event(m.PERFORMANCE_METRIC,g.CAPTION_INPUT,""+e,void 0,JSON.stringify({elapsedTime:e}))},H2t=e=>{I().event(m.ERROR,g.ERROR_EDIT,"invisible_modal",void 0,JSON.stringify({modalState:e}))},Fke=()=>{I().event(m.MODAL,g.CLICK_DOWNLOAD_APP,void 0,void 0,JSON.stringify({installCode:pt().getInstallCode()})),pt().getInstallCode()!==""&&I().event(m.MODAL,g.CLICK_DOWNLOAD_APP_AD)},Uke=(e,t,o)=>{const r=Co(t,e,!0),n=r-o,a=e-t[r].startPosition+1,i=Ys(t[r]),s=a+"_"+i+"_"+Math.floor(a/i*10)*10,x={wordPositionInClip:a,clipWordLength:i,ratio:Math.floor(a/i*10)*10};I().event(m.RESEARCH_PLAY,""+n,s,void 0,JSON.stringify(x))},Vke=e=>{I().event(m.MODAL,g.SHOW_DOWNLOAD_MODAL,void 0,void 0,JSON.stringify({origin:e}))},dk=(e,t)=>{I().event(m.ERROR_LINK_MODAL,e,t)},j2t=e=>{I().event(m.SPELLCHECK,g.SPELLCHECK_TOGGLE,e?"o":"x")},z2t=e=>{I().event(m.SPELLCHECK,g.SPELLCHECK_REPLACE_WORD,"index-"+e)},Y2t=()=>{I().event(m.SPELLCHECK,g.SPELLCHECK_SHOW_CTX_MENU)},B2t=()=>{I().event(m.SPELLCHECK,g.SPELLCHECK_ADD_IGNORE)},K2t=(e,t,o,r)=>{const n={cumulativeClipCnt:t,draggedPosition:r??""};I().event(m.SELECT_CLIP,e,o?""+o:void 0,void 0,JSON.stringify(n))},Gke=(e,t)=>{let o;switch(t){case Z.NORMAL:o=g.NORMAL_WORD_SELECT;break;case Z.SOUND:o=g.SOUND_WORD_SELECT;break;case Z.LAUGHTER:o=g.LAUGHTER_WORD_SELECT;break;case Z.CLAP:o=g.CLAP_WORD_SELECT;break;case Z.FILLER:o=g.FILLER_WORD_SELECT;break}o!==void 0&&I().event(m.WORD_EDIT,o,e.toString(),void 0,ru[t])},Wke=e=>{I().event(m.CURSOR_STATE,g.WORD_SELECT,""+e)},Hke=(e,t)=>{let o;switch(t){case Z.NORMAL:o=g.NORMAL_WORD_DETAIL;break;case Z.SOUND:o=g.SOUND_WORD_DETAIL;break;case Z.LAUGHTER:o=g.LAUGHTER_WORD_DETAIL;break;case Z.CLAP:o=g.CLAP_WORD_DETAIL;break;case Z.FILLER:o=g.FILLER_WORD_DETAIL;break}o!==void 0&&I().event(m.WORD_EDIT,o,e.toString(),void 0,ru[t])},jke=e=>{I().event(m.CURSOR_STATE,g.WORD_DETAIL,""+e)},zke=e=>{I().event(m.CURSOR_STATE,g.INSERT_CURSOR_A,""+e)},Yke=e=>{I().event(m.CURSOR_STATE,g.INSERT_CURSOR_B,""+e)},Bke=e=>{I().event(m.CURSOR_STATE,g.CLIP_SELECT,""+e)},X2t=e=>{I().event(m.EYE_DROPPER,g.CLICK_EYE_DROPPER,e)},J2t=e=>{I().event(m.MOUSE_EDIT,g.DISPLAY_THUMBNAIL,e.toString())},uk=(e,t,o)=>
1244{I().event(m.MOUSE_EDIT,g.DELETE_WORD,e?"selected":"normal",void 0,o?JSON.stringify({numWord:t,triggerSource:o}):t.toString())},q2t=()=>{I().event(m.MOUSE_EDIT,g.WORD_READY_TO_DELETE)},Q2t=(e,t)=>{const o=e===nt.ALL_CLIPS?"all":e===nt.CURRENT_CLIP?"current":"selected_"+t;I().event(m.PLAYBACK_RATE_EFFECT,g.CLICK_RANGE,o)},Z2t=(e,t,o)=>{const r=xi(t,o);I().event(m.PLAYBACK_RATE_EFFECT,g.CLICK_SETTING_SLDIER,ue(e,2)+"_"+r+"_"+o)},$2t=(e,t,o)=>{const r=xi(t,o);I().event(m.PLAYBACK_RATE_EFFECT,g.SETTING_RATE_CUSTOM,ue(e,2)+"_"+r+"_"+o)},ept=(e,t,o)=>{const r=e/t===o;I().event(m.PLAYBACK_RATE_EFFECT,g.SETTING_DURATION_CUSTOM,e+"_"+t+"_"+ue(o,2)+"_"+r)},tpt=(e,t,o)=>{I().event(m.INSERT,e==="clip"?g.BLANK_CLIP:g.BLANK_WORD,void 0,void 0,JSON.stringify({method:t,freeze:o}))},opt=e=>{I().event(m.TOOLBAR_INSERT,g.CLICK_AI_IMAGE_AUTO_INSERTION,e?"on":"off")},rpt=(e,t)=>{const o=new Map([[kn.FREE_SOURCE_LIBRARY,g.CLICK_FREE_ASSETS],[kn.IMAGE_LIBRARY,g.CLICK_INSERT_IMAGE_FREE],[kn.VIDEO_LIBRARY,g.CLICK_INSERT_VIDEO_FREE],[kn.SHAPE_INSERT,g.CLICK_SHAPE],[kn.GIPHY,g.CLICK_GIPHY]]),r=o.get(e);r&&I().event(m.TOOLBAR_INSERT,r,t?"on":"off")},npt=()=>{I().event(m.MOUSECLICK_EDIT,g.CLICK_INSERT_IMAGE_FREE)},Kke=(e,t,o,r,n)=>{const{provider:a,assetType:i}=n,s=xi(e,o),x=tS(t),c=Math.max(o,r),l={assetType:i,importRangeString:s,maxCount:c,imageImportString:x,provider:a};I().event(m.INSERT_GEN_ASSET,g.INSERT_GEN_ASSET_DONE,void 0,void 0,JSON.stringify(l))},apt=(e,t=!1)=>{const o=e.filter(i=>i.type==="image").length,r=e.filter(i=>i.type==="video").length,n=e.map(i=>i.data?.provider).filter(Se).filter(gm),a={numImage:o,numVideo:r,videoMute:t,providers:n,ttvVersion:to()};I().event(m.INSERT_GEN_ASSET,g.TTV_DONE,void 0,void 0,JSON.stringify(a))},Uz=(e,t,o,r,n,a,i,s)=>{const{stockSite:x,keywordType:c,assetType:l,freeAssetSection:d}=a??{stockSite:"unknown",keywordType:FU.VREW,assetType:"image",freeAssetSection:void 0},u=z2(e,o),p=tS(t),f=Math.max(o,r,n),E=l+"_"+u+"_"+f+"_"+p+"_"+x+"_"+c,T={assetType:l,importRangeString:u,maxCount:f,stockSite:x,keywordType:c,imageImportString:p,freeAssetSection:d,isReplace:!!i,replaceOrigAspectRatio:i?ue(i.originalAspectRatio,2):void 0,replaceNewAspectRatio:i?ue(i.newAspectRatio,2):void 0};I().event(m.INSERT_FREE_SOURCE,g.INSERT_FREE_SOURCE_DONE,E,void 0,JSON.stringify({...T,triggerSource:s}))},ipt=(e,t)=>{I().event(m.INSERT_FREE_SOURCE,g.INSERT_GIPHY,void 0,void 0,JSON.stringify({isChecked:e?"check":"uncheck",type:t}))},spt=(e,t)=>{I().event(m.FREE_SOURCE_PANEL,g.SHOW_ONLY_TRANSPARENT,void 0,void 0,JSON.stringify({resourceType:Eo(Kr).getKeyOrDefault(e),isChecked:t?"check":"uncheck"}))},Xke=(e,t,o,r,n)=>{const a=z2(e,o),i=tS(t),s=e==="REPLACE_SELECTED_ELEMENTS",x=Math.max(o,r,n),c=a+"_"+x+"_"+i,l={importRangeString:a,maxCount:x,imageImportString:i,isReplace:s};I().event(m.INSERT_FREE_SOURCE,g.INSERT_IMAGE_DONE_MENU,c,void 0,JSON.stringify(l))},xpt=(e,t)=>{I().event(m.INSERT_FREE_SOURCE,g.SEARCH_FREE_SOURCE,e+"_"+t.replace(" ","+"),void 0,JSON.stringify({imageSearchType:e,searchKeyword:t.replace(" ","+")}))},cpt=e=>{I().event(m.INSERT_FREE_SOURCE,g.CLICK_FREE_SOURCE_INFO,e)},lpt=e=>{I().event(m.INSERT_FREE_SOURCE,g.CLICK_FREE_SOURCE_INFO_LICENSE,void 0,void 0,JSON.stringify({type:e}))},dpt=e=>{I().event(m.INSERT_FREE_SOURCE,g.PNG_FILTER,e?"check":"uncheck")},upt=()=>{I().event(m.IMAGE_FLOATING_MENU,g.DISPLAY_IMAGE_FLOATING_MENU)},ppt=()=>{I().event(m.VIDEO_FLOATING_MENU,g.DISPLAY_VIDEO_FLOATING_MENU)},fpt=()=>{I().event(m.IMAGE_FLOATING_MENU,g.REMOVE_BACKGROUND)},gpt=()=>{I().event(m.IMAGE_FLOATING_MENU,g.REORDER)},_pt=()=>{I().event(m.IMAGE_FLOATING_MENU,g.REPLACE)},Ept=()=>{I().event(m.IMAGE_FLOATING_MENU,g.FILL_CONTAIN)},mpt=()=>{I().event(m.IMAGE_FLOATING_MENU,g.FILL_CUT)},hpt=()=>{I().event(m.IMAGE_FLOATING_MENU,g.FILL_COVER)},Ipt=()=>{I().event(m.IMAGE_FLOATING_MENU,g.MOVE_TO_FRONT)},Tpt=()=>{I().event(m.IMAGE_FLOATING_MENU,g.MOVE_FORWARD)},Spt=()=>{I().event(m.IMAGE_FLOATING_MENU,g.MOVE_TO_BACK)},Opt=()=>{I().event(m.IMAGE_FLOATING_MENU,g.MOVE_BACKWARD)},Cpt=()=>{I().event(m.IMAGE_FLOATING_MENU,g.FLIP_HORIZONTAL)},Rpt=()=>{I().event(m.IMAGE_FLOATING_MENU,g.FLIP_VERTICAL)},Apt=()=>{I().event(m.IMAGE_CLICK_MENU,g.FLIP_HORIZONTAL)},ypt=()=>{I().event(m.IMAGE_CLICK_MENU,g.FLIP_VERTICAL)},vpt=()=>{I().event(m.IMAGE_CLICK_MENU,g.FILL_CONTAIN)},wpt=()=>{I().event(m.IMAGE_CLICK_MENU,g.FILL_CUT)},Npt=()=>{I().event(m.IMAGE_CLICK_MENU,g.FILL_COVER)},Ppt=()=>{I().event(m.IMAGE_CLICK_MENU,g.REMOVE_BACKGROUND_ABORT)},bpt=()=>{I().event(m.IMAGE_CLICK_MENU,g.REMOVE_BACKGROUND_CONFIRM)},Lpt=()=>{I().event(m.ZOOM_ROATE_EFFECT,g.CLICK_ICON)},Mpt=()=>{I().event(m.TRANSITION_EFFECT,g.CLICK_ICON)},Dpt=()=>
1244{I().event(m.TRANSITION_EFFECT,g.DELETE_TRANSITION)},kpt=(e,t,o)=>{I().event(m.TRANSITION_EFFECT,g.INSERT_TRANSITION,void 0,void 0,JSON.stringify({transitionType:e,duration:t,numVideoAsset:o}))},Fpt=(e,t)=>{I().event(m.TRANSITION_EFFECT,g.CHANGE_DURATION,void 0,void 0,JSON.stringify({transitionType:e,duration:t}))},Upt=e=>{const t=""+ue(e,2),o={zoomValue:ue(e,2)};I().event(m.RATIO_SETTING,g.ZOOM,t,void 0,JSON.stringify(o))},Vpt=e=>{const t=""+ue(e,2),o={xPosValue:ue(e,2)};I().event(m.RATIO_SETTING,g.POSITION_HORIZONTAL,t,void 0,JSON.stringify(o))},Gpt=e=>{const t=""+ue(e,2),o={yPosValue:ue(e,2)};I().event(m.RATIO_SETTING,g.POSITION_VERTICAL,t,void 0,JSON.stringify(o))},Wpt=(e,t,o,r)=>{const n=xi(e,t),a=n+"_"+t+"_"+(o?"minimap":"custom")+"_"+ue(r,2),i={importRangeString:n,clipCount:t,fromMinimap:o?"minimap":"custom",zoomValue:ue(r,2)};I().event(m.ZOOM_ROATE_EFFECT,g.ZOOM,a,void 0,JSON.stringify(i))},Hpt=(e,t,o,r)=>{const n=xi(e,t),a=n+"_"+t+"_"+(o?"minimap":"custom")+"_"+ue(r,2),i={importRangeString:n,clipCount:t,fromMinimap:o?"minimap":"custom",zoomValue:ue(r,2)};I().event(m.ZOOM_ROATE_EFFECT,g.POSITION_HORIZONTAL,a,void 0,JSON.stringify(i))},jpt=(e,t,o,r)=>{const n=xi(e,t),a=n+"_"+t+"_"+(o?"minimap":"custom")+"_"+ue(r,2),i={importRangeString:n,clipCount:t,fromMinimap:o?"minimap":"custom",zoomValue:ue(r,2)};I().event(m.ZOOM_ROATE_EFFECT,g.POSITION_VERTICAL,a,void 0,JSON.stringify(i))},zpt=(e,t,o,r)=>{const n=xi(e,t),a=n+"_"+t+"_"+(o?"minimap":"custom")+"_"+ue(r,2),i={importRangeString:n,clipCount:t,fromMinimap:o?"minimap":"custom",zoomValue:ue(r,2)};I().event(m.ZOOM_ROATE_EFFECT,g.ROTATION,a,void 0,JSON.stringify(i))},Ypt=(e,t)=>{const o=xi(e,t);I().event(m.ZOOM_ROATE_EFFECT,g.RESET,o+"_"+t,void 0,JSON.stringify({importRangeString:o,clipCount:t}))},Jke=e=>{I().event(m.SMART_GUIDE,g.VALUE_SETTING,"arrow_key_keyboard",void 0,e)},qke=e=>{I().event(m.SMART_GUIDE,g.VALUE_SETTING,"arrow_key_click",void 0,e)},Qke=e=>{I().event(m.SMART_GUIDE,g.VALUE_SETTING,"manual_input",void 0,e)},Bpt=(e,t)=>{switch(t){case"input":return Qke(e);case"keyboard":return Jke(e);case"stepper":return qke(e)}},Zke=(e,t)=>{const o=t.length>0?g.CUT_ASSET:g.CUT,r=t.length===1?"single":"multi",n=r==="single"?{assetType:Dt(t[0].assetType)}:cn(t.map(i=>Dt(i.assetType))),a=t.length>0?JSON.stringify({selectType:r,...n}):void 0;I().event(m.CONTEXT_FLOATING_MENU,o,e,void 0,a)},$ke=(e,t)=>{const o=t.length>0?g.COPY_ASSET:g.COPY,r=t.length===1?"single":"multi",n=r==="single"?{assetType:Dt(t[0].assetType)}:cn(t.map(i=>Dt(i.assetType))),a=t.length>0?JSON.stringify({selectType:r,...n}):void 0;I().event(m.CONTEXT_FLOATING_MENU,o,e,void 0,a)},eFe=(e,t)=>{const o={pasteOrigin:t};I().event(m.CONTEXT_FLOATING_MENU,g.PASTE,e,void 0,JSON.stringify(o))},Kpt=()=>{I().event(m.CONTEXT_FLOATING_MENU,g.CLICK_MERGE_CLIPS)},tFe=()=>{I().event(m.CONTEXT_FLOATING_MENU,g.CLICK_DIVIDE_CLIP)},Xpt=()=>{I().event(m.CONTEXT_FLOATING_MENU,g.EDIT_CUT_DETAIL)},Jpt=e=>{I().event(m.CONTEXT_FLOATING_MENU,g.ADJUST_SPACER,e.toString())},qpt=()=>{I().event(m.UPLOAD,g.DRAG_AND_DROP_POPUP)},uC=e=>{I().event(m.AUDIOTRACK_CHECK,g.RESULT,e)},Qpt=e=>I().event(m.TOOLBAR_INSERT,g.CLICK_AI_VOICE,e),Zpt=(e,t)=>{switch(t){case"toolbar":I().event(m.TOOLBAR_INSERT,g.CLICK_AI_VOICE_MODIFY,void 0,void 0,JSON.stringify({target:e}));break;case"clip":I().event(m.EDIT_CLIP,g.CLICK_AI_VOICE_MODIFY,void 0,void 0,JSON.stringify({target:e}));break;case"shortcut":I().event(m.KEY_EDIT,g.CLICK_AI_VOICE_MODIFY,void 0,void 0,JSON.stringify({target:e}));break;case"context_menu":I().event(m.MOUSECLICK_EDIT,g.CLICK_AI_VOICE_MODIFY,void 0,void 0,JSON.stringify({target:e}));break}},$pt=(e,t)=>{const o={clickOrigin:e,textLength:t};I().event(m.TTS,g.CLICK_AI_VOICE_PREVIEW,void 0,void 0,JSON.stringify(o))},xi=(e,t)=>{let o="current-clip";switch(e){case nt.ALL_CLIPS:o="all-clips";break;case nt.SCENE_CLIPS:o="scene-clips";break;case nt.SELECTED_CLIPS:o="selected-clips";break;case nt.SELECTED_WORDS:o="selected-words";break;case nt.CURRENT_WORD:o="current-word";break;case nt.FOLLOW_SELECTED_ELEMENT:o=t>0?"selected-clips":"selected-words";break}return o},z2=(e,t)=>{let o="new-clip";switch(e){case"NEW_CLIP":o="new-clip";break;case"REPLACE_SELECTED_ELEMENTS":o="replace-selected-elements";break;default:o=xi(e,t);break}return o},tS=e=>{switch(e){case _e.MODAL_UPLOAD:return"modal_pc-image";case _e.CONTEXT_FLOATING_MENU:return"context-floating-menu_pc-image";case _e.DRAG_AND_DROP:case _e.DRAG_AND_DROP_MULTIPLE:return"drag-and-drop_pc-image";case _e.PANEL_UPLOAD:return"free-panel_pc-image";case _e.STOCK_CONTEXT_FLOATING_MENU:return"context-floating-menu_free-image";case _e.STOCK_IMAGE:return"free-panel_free-image";case _e.BETWEEN_CLIP_CONTEXT_MENU:return"between-clip-context-menu";case _e.USER_ASSET_PANEL:return"myasset-panel_pc-image";case _e.USER_ASSET_CONTEXT_MENU:return"context-menu_pc-image";case _e.IMAGE_GENERATE_MODAL:return"image-generate-modal";case _e.IMAGE_GENERATE_MODAL_STOCK:return"image-generate-modal-stock";case _e.IMAGE_REPLACE_MODAL:return"image-replace-modal";case _e.IMAGE_REPLACE_MODAL_STOCK:return"image-replace-modal-stock";case _e.SYSTEM_CLIPBOARD:case _e.COPY_AND_PASTE:case _e.UNKNOWN:default:return""}},Vz=e=>{switch(e){case Yt.CONTEXT_FLOATING_MENU:return"context-floating-menu_text-box";case Yt.CONTEXT_MENU:return"context-menu_text-box";case Yt.TEXTBOX_TOOLBAR:return"toolbar_text-box";case Yt.ANNOUNCEMENT_IMAGE:return"announcement-image_text-box";case Yt.COPY_AND_PASTE:case Yt.FRAMEPACK:case Yt.THUMBNAIL_GENERATOR:case Yt.UNKNOWN:return""}},hP=(e,t,o,r,n,a,i)=>{if(e===nt.ALL_CLIPS)return{clipCount:o,wordCount:0};if(e===nt.SCENE_CLIPS)return{clipCount:t.length,wordCount:0};if(e===nt.SELECTED_CLIPS)return{clipCount:r,wordCount:0};if(e===nt.SELECTED_WORDS)return{clipCount:0,wordCount:n};if(e===nt.FOLLOW_SELECTED_ELEMENT&&a.length>0){const s=tEe(a[a.length-1],i);if(s)return s}return{clipCount:1,wordCount:0}},oFe=e=>{I().event(m.IMPORT,g.LONG_AUDIO_DURATION,Math.round(e/60).toString())},pC=e=>{I().event(m.IMPORT,g.LONG_AUDIO_CONVERT,e.toString())},eft=e=>{I().event(m.TOOLBAR_INSERT,g.CLICK_INSERT_BGM,e?"on":"off")},tft=e=>{I().event(m.INSERT_BGM,g.IMPORT_BGM_PC,e.toFixed(2))},oft=(e,t)=>{I().event(m.INSERT_BGM,g.SELECT_BGM_PC,e+"_"+t.toFixed(2))},rft=(e,t,o)=>{const r={musicId:t,aiAudioSearch:o};I().event(m.INSERT_BGM,g.SELECT_BGM_FREE,e,void 0,JSON.stringify(r))},nft=e=>{I().event(m.INSERT_BGM,g.CLICK_KEYWORD,e)},aft=e=>{I().event(m.INSERT_BGM,g.CLICK_PLAY_FREE,e)},ift=e=>{const t=a1(e).toString(16);I().event(m.INSERT_BGM,g.CLICK_PLAY_USER,t)},sft=e=>{I().event(m.INSERT_BGM,g.CLICK_PAUSE_FREE,e)},xft=e=>{const t=a1(e).toString(16);I().event(m.INSERT_BGM,g.CLICK_PAUSE_USER,t)},cft=e=>{I().event(m.INSERT_BGM,g.CLICK_TAB,e.toString())},lft=e=>{I().event(m.INSERT_BGM,g.SEARCH,e)},dft=e=>{I().event(m.INSERT_BGM,g.AI_SEARCH_BGM_SUBMIT,e)},uft=e=>{I().event(m.INSERT_BGM,g.AI_SEARCH_BGM_FAILED,e)},pft=e=>{I().event(m.INSERT_BGM,g.AI_SEARCH_BGM_CLICK_INSPIRATION,e)},fft=e=>{I().event(m.INSERT_BGM,g.AI_AUTO_RECOMMEND_BGM_CLICK,void 0,e)},gft=e=>{I().event(m.INSERT_BGM,g.CLICK_BOOKMARK,e)},_ft=(e,t,o,r,n,a,i,s)=>{const x={numBGMPlay:t+o,numUserBGMPlay:o,numFreeBGMPlay:t,bgmName:r,bgmId:n,tab:a,site:i,entryPoint:s};I().event(m.INSERT_BGM,g.INSERT_DONE_MENU,(e?"user":r)+"_"+(e?"userBgmId":n)+"_"+(e?"pc":"free"),void 0,JSON.stringify(x))},Eft=e=>{const t={assetType:ze.BGM};I().event(m.EDIT_RANGE,g.CLICK_DOT,e?"top":"bottom",void 0,JSON.stringify(t))},mft=(e,t,o,r)=>{const n=Math.abs(t-o),a=r==="TOP"&&t>o||r==="BOTTOM"&&t<o,i=e+"_"+n+"_"+(a?"o":"x"),s={assetType:ze.BGM,previousRange:e,nextRange:n,isRangeFlipped:a?"o":"x"};I().event(m.EDIT_RANGE,g.DRAG_DOT,i,void 0,JSON.stringify(s))},hft=e=>{I().event(m.TEXT_FLOATING_MENU,g.DISPLAY,e)},Ift=()=>{I().event(m.TEXT_FLOATING_MENU,g.MOVE)},Tft=e=>{I().event(m.TEXT_FLOATING_MENU,g.FIX,e)},Sft=()=>{I().event(m.TEXT_FLOATING_MENU,g.RETURN_TO_ORIGINAL)},Oft=(e,t)=>{const o=e?g.UNBOLD:g.BOLD;I().event(m.TEXT_FLOATING_MENU,o,t)},Cft=(e,t)=>{const o=e?g.UNITALIC:g.ITALIC;I().event(m.TEXT_FLOATING_MENU,o,t)},Rft=(e,t)=>{I().event(m.TEXT_FLOATING_MENU,e,t)},Aft=(e,t)=>{const o=g.SIZE+"-"+e;I().event(m.TEXT_FLOATING_MENU,o,t)},yft=e=>{I().event(m.TEXT_FLOATING_MENU,g.FONT_COLOR,e)}
1244,vft=e=>{I().event(m.TEXT_FLOATING_MENU,g.OUTLINE_COLOR,e)},wft=e=>{I().event(m.TEXT_FLOATING_MENU,g.BACKGROUND,e)},Nft=e=>{I().event(m.TEXT_FLOATING_MENU,g.HIGHLIGHT_COLOR,e)},Pft=e=>{I().event(m.TEXT_FLOATING_MENU,g.SHADOW_COLOR,e)},bft=e=>{const t=e?"off":"on-all";I().event(m.TEXT_FLOATING_MENU,g.RUBY,t)},Lft=()=>{I().event(m.TEXT_FLOATING_MENU,g.RUBY,"on-part")},Mft=e=>{I().event(m.TEXT_FLOATING_MENU,g.LETTER_SPACING,e)},Dft=e=>{I().event(m.TEXT_FLOATING_MENU,g.LINE_HEIGHT,e)},rFe=e=>{I().event(m.TEXT_EDIT,g.MOVE_TEXT,void 0,void 0,e?JSON.stringify({triggerSource:e}):void 0)},kft=(e,t)=>{const o=e?g.UNBOLD:g.BOLD;I().event(m.TEXT_PANEL_MENU,o,t)},Fft=(e,t)=>{const o=e?g.UNITALIC:g.ITALIC;I().event(m.TEXT_PANEL_MENU,o,t)},Uft=(e,t)=>{const o=e?g.UNSTRIKE:g.STRIKE;I().event(m.TEXT_PANEL_MENU,o,t)},Vft=(e,t)=>{const o=e?g.UNUNDERLINE:g.UNDERLINE;I().event(m.TEXT_PANEL_MENU,o,t)},Gft=(e,t)=>{I().event(m.TEXT_PANEL_MENU,e,t)},Wft=(e,t)=>{const o=g.SIZE+"-"+e;I().event(m.TEXT_PANEL_MENU,o,t)},Hft=e=>{I().event(m.TEXT_PANEL_MENU,g.FONT_COLOR,e)},jft=e=>{I().event(m.TEXT_PANEL_MENU,g.OUTLINE_ON,e)},zft=e=>{I().event(m.TEXT_PANEL_MENU,g.OUTLINE_OFF,e)},Yft=e=>{I().event(m.TEXT_PANEL_MENU,g.OUTLINE_COLOR,e)},Bft=e=>{I().event(m.TEXT_PANEL_MENU,g.OUTLINE_WIDTH,e)},Kft=e=>{I().event(m.TEXT_PANEL_MENU,g.SECONDARY_OUTLINE_ON,e)},Xft=e=>{I().event(m.TEXT_PANEL_MENU,g.SECONDARY_OUTLINE_OFF,e)},Jft=e=>{I().event(m.TEXT_PANEL_MENU,g.SECONDARY_OUTLINE_COLOR,e)},qft=e=>{I().event(m.TEXT_PANEL_MENU,g.SECONDARY_OUTLINE_WIDTH,e)},Qft=e=>{I().event(m.TEXT_PANEL_MENU,g.BACKGROUND_ON,e)},Zft=e=>{I().event(m.TEXT_PANEL_MENU,g.BACKGROUND_OFF,e)},$ft=e=>{I().event(m.TEXT_PANEL_MENU,g.BACKGROUND,e)},egt=e=>{I().event(m.TEXT_PANEL_MENU,g.BACKGROUND_OPACITY,e)},tgt=e=>{I().event(m.TEXT_PANEL_MENU,g.BACKGROUND_RADIUS,e)},ogt=e=>{I().event(m.TEXT_PANEL_MENU,g.BACKGROUND_SIDE_PADDING,e)},rgt=e=>{I().event(m.TEXT_PANEL_MENU,g.BACKGROUND_TOP_PADDING,e)},ngt=e=>{I().event(m.TEXT_PANEL_MENU,g.BACKGROUND_BOTTOM_PADDING,e)},agt=e=>{I().event(m.TEXT_PANEL_MENU,g.SHADOW_ON,e)},igt=e=>{I().event(m.TEXT_PANEL_MENU,g.SHADOW_OFF,e)},sgt=e=>{I().event(m.TEXT_PANEL_MENU,g.SHADOW_COLOR,e)},xgt=e=>{I().event(m.TEXT_PANEL_MENU,g.SHADOW_OPACITY,e)},cgt=e=>{I().event(m.TEXT_PANEL_MENU,g.SHADOW_BLUR,e)},lgt=e=>{I().event(m.TEXT_PANEL_MENU,g.SHADOW_X,e)},dgt=e=>{I().event(m.TEXT_PANEL_MENU,g.SHADOW_Y,e)},ugt=e=>{I().event(m.TEXT_PANEL_MENU,g.LETTER_SPACING,e)},pgt=e=>{I().event(m.TEXT_PANEL_MENU,g.LINE_HEIGHT,e)},fgt=e=>{I().event(m.TEXT_PANEL_MENU,g.DISPLAY_BOOKMARK,e.toString())},ggt=(e,t)=>{I().event(m.TEXT_PANEL_MENU,g.ADD_TO_BOOKMARK,e.toString(),void 0,t)},_gt=e=>{I().event(m.TEXT_PANEL_MENU,g.REMOVE_FROM_BOOKMARK,e.toString())},Egt=()=>{I().event(m.TEXT_PANEL_MENU,g.ADJUST)},mgt=e=>{const t=Ks(e),o=w7();I().event(t,g.CLICK_START_NEW_PROJECT,void 0,void 0,JSON.stringify({startModalVersion:o}))},hgt=e=>{const t=Ks(e);I().event(t,g.CLICK_OPEN_PROJECT)},Igt=e=>{I().event(m.OPEN_PROJECT,e)},Tgt=(e,t)=>{const o={projectType:e,projectId:t};I().event(m.OPEN_PROJECT,g.CLICK_PROJECT,void 0,void 0,JSON.stringify(o))},Sgt=()=>{const e=w7();I().event(m.START_PAGE,g.CLICK_START_NEW_PROJECT,void 0,void 0,JSON.stringify({startModalVersion:e}))},Ogt=()=>{I().event(m.START_PAGE,g.CLICK_OPEN_PROJECT)},Cgt=()=>{I().event(m.START_PAGE,g.CLICK_OPEN_DEMO_PROJECT)},Rgt=()=>{I().event(m.START_NEW_PROJECT,g.CLICK_OPEN_VIDEO_FILE)},Agt=()=>{I().event(m.START_NEW_PROJECT,g.CLICK_AI_VOICE)},ygt=()=>{I().event(m.START_NEW_PROJECT,g.CLICK_SHORTS)},vgt=()=>{I().event(m.START_NEW_PROJECT,g.CLICK_DOCS)},wgt=()=>{I().event(m.START_NEW_PROJECT,g.CLICK_IMAGES)},Ngt=()=>{I().event(m.START_NEW_PROJECT,g.CLICK_TEMPLATE)},Pgt=()=>{I().event(m.TOOLBAR_INSERT,g.OPEN_TEMPLATE_PANEL)},bgt=(e,t)=>{I().event(m.TEMPLATE,g.SELECT_TEMPLATE,void 0,void 0,JSON.stringify({templateName:e,...t}))},Lgt=e=>{I().event(m.START_NEW_PROJECT,g.TEXT_TO_VIDEO,void 0,void 0,JSON.stringify({isPromoted:e,ttvVersion:to()}))},Mgt=e=>{e===bo.HOME?I().event(m.TOOLBAR_HOME,g.CLICK_FONT):e===bo.FORMAT&&I().event(m.TOOLBAR_FORMAT,g.CLICK_FONT)},Dgt=e=>{I().event(m.FONT_SETTING,g.CLICK_TAB,e)},kgt=e=>{I().event(m.FONT_SETTING,g.CLICK_KEYWORD,e)},Fgt=e=>{I().event(m.FONT_SETTING,g.CLICK_BOOKMARK,e,void 0,"on")},Ugt=e=>{I().event(m.FONT_SETTING,g.CLICK_BOOKMARK,e,void 0,"off")},Vgt=e=>{I().event(m.TEXT_PANEL_MENU,g.CLICK_BOOKMARK,e,void 0,"on")},Ggt=e=>{I().event(m.TEXT_PANEL_MENU,g.CLICK_BOOKMARK,e,void 0,"off")},Wgt=(e,t,o,r)=>{const n={name:e.vrewDisplayName,from:t?"search":o?"bookmark":"none",category:e.type==="web"&&!t&&!o?r:void 0},a=e.type==="web"&&j4.includes(e.fontName)?"default":e.type;I().event(m.FONT_SETTING,g.SELECT_FONT,a,void 0,JSON.stringify(n))},nFe=(e,t)=>{const o={saveFileSizeInBytes:e,saveElapsedSec:ue(t,2),saveBPS:ue(e/t,2)};I().event(m.PROJECT_SAVE,g.PROJECT_SAVE_STAT,void 0,void 0,JSON.stringify(o))},Hgt=()=>{I().event(m.BETWEEN_CLIP_CONTEXT_MENU,g.CLICK_INSERT_BUTTON)},jgt=()=>{I().event(m.BETWEEN_CLIP_CONTEXT_MENU,g.CLICK_BLANK_CLIP)},zgt=()=>{I().event(m.BETWEEN_CLIP_CONTEXT_MENU,g.CLICK_INSERT_IMAGE)},Ygt=()=>{I().event(m.BETWEEN_CLIP_CONTEXT_MENU,g.CLICK_AI_VOICE)},Bgt=(e,t,o)=>{const r=e+"_"+"NEW_CLIP".toLowerCase()+"_1_"+_e.BETWEEN_CLIP_CONTEXT_MENU+"_"+t+"_"+o,n={assetType:e,importRange:"NEW_CLIP".toLowerCase(),imageNumber:1,stockSite:t,searchKeyword:o,importType:_e.BETWEEN_CLIP_CONTEXT_MENU};I().event(m.INSERT_SOURCE_CLIP,g.INSERT_FREE_SOURCE_DONE,r,void 0,JSON.stringify(n))},Kgt=e=>{const t=Dt(e),o={assetType:t};I().event(m.EDIT_RANGE,g.CLICK_PARENS,void 0,void 0,JSON.stringify(o))},Xgt=(e,t,o,r,n)=>{const a=Dt(e),i=[t,o,r,n].join("_"),s={assetType:a,prevWordCount:t,nextWordCount:o,inverted:r,convertedToClip:n};I().event(m.EDIT_RANGE,g.DRAG_PARENS,i,void 0,JSON.stringify(s))},Jgt=(e,t,o)=>{const r=e.length===1?"single":"multi",n=r==="single"?{assetType:Dt(e[0].assetType)}:cn(e.map(i=>Dt(i.assetType))),a={selectedType:r,...n,prevRange:t,nextRange:o};
1244I().event(m.EDIT_RANGE,g.DRAG_THUMB,[t,o].join("_"),void 0,JSON.stringify(a))},qgt=()=>{I().event(m.OPEN_PROJECT,g.DESKTOP_SEARCH)},Qgt=e=>{I().event(m.OPEN_PROJECT,e)},Zgt=()=>{I().event(m.OPEN_PROJECT,g.SEARCH)},$gt=()=>{I().event(m.OPEN_PROJECT,g.DELETE)},e_t=e=>I().event(m.TOOLBAR_EFFECT,g.CLICK_VOLUME,e),t_t=()=>I().event(m.VOLUME_EFFECT,g.CLICK_ICON),IP=e=>{switch(e){case nt.ALL_CLIPS:return"all";case nt.SCENE_CLIPS:return"scene_clips";case nt.SELECTED_CLIPS:return"selected";case nt.CURRENT_CLIP:default:return"current"}},o_t=e=>(t,o,r)=>{const n=IP(t),a=n+"_"+o+"_"+e+"_"+(r??"mixed"),i={range:n,numAppliedClips:o,method:e,valuePercentage:r?.toString()??"mixed"};I().event(m.VOLUME_EFFECT,g.VOLUME,a,void 0,JSON.stringify(i))},r_t=(e,t)=>{const o=IP(e),r=o+"_"+t,n={range:o,numAppliedClips:t};I().event(m.VOLUME_EFFECT,g.RESET,r,void 0,JSON.stringify(n))};let Fp=0;const n_t=()=>{Fp=0},a_t=()=>{Fp=Fp+1,[20,80,150].includes(Fp)&&I().event(m.SEEKBAR,g.SEEKBAR_HOVER,Fp.toString())},i_t=()=>{const e=Fe();I().event(m.TOOLBAR_HELP,g.CLICK_COMMUNITY,e)},Gz=e=>{I().event(m.VDROP,g.CANCEL,e)},aFe=(e,t,o,r)=>{const n=es(o);I().event(m.VDROP,g.DOWNLOAD_START,void 0,void 0,JSON.stringify({entryPoint:e,fileType:t,fileSize:n,fileCount:r}))},iFe=(e,t,o,r,n)=>{const a=es(o);I().event(m.VDROP,g.DOWNLOAD_DONE,void 0,void 0,JSON.stringify({entryPoint:e,fileType:t,fileSize:a,fileCount:r,downloadDuration:Math.floor(n)}))},pk=(e,t,o,r)=>{const n=t===void 0?"null":es(t);I().event(m.ERROR,g.ERROR_CODE,r,void 0,JSON.stringify({fileType:e,fileSize:n,fileCount:o,type:"download"}))},s_t=e=>{const t=e?g.ADD_VDROP_TOOLTIP:g.CLOSE_VDROP_TOOLTIP;I().event(m.VDROP,t)},sFe=e=>{I().event(m.VDROP,g.CLICK_UPLOAD,e)},xFe=e=>{I().event(m.VDROP,g.CLICK_DOWNLOAD,e)},cFe=e=>{I().event(m.VDROP,g.UPLOAD_START,e)},lFe=(e,t)=>{I().event(m.VDROP,g.UPLOAD_SUCCESS,e,void 0,JSON.stringify({elapsedTime:t}))},dFe=(e,t)=>{I().event(m.VDROP,g.FILE_SELECTED,void 0,void 0,JSON.stringify({fileSize:e,fileType:t}))},uFe=(e,t)=>{I().event(m.VDROP,g.UPLOAD_FAILED,void 0,void 0,JSON.stringify({fileSize:t,reason:e}))},x_t=()=>{I().event(m.TOOLBAR_HOME,g.CLICK_SHOW_FORMAT_TAB)},c_t=()=>{I().event(m.TOOLBAR_INSERT,g.CLICK_INSERT_SOUNDFX)},l_t=e=>{I().event(m.INSERT_SOUNDFX,g.IMPORT_SOUNDFX_PC,""+e,void 0,JSON.stringify({duration:e}))},d_t=(e,t)=>{I().event(m.INSERT_SOUNDFX,g.SELECT_SOUNDFX_PC,e+"_"+t)},u_t=(e,t)=>{I().event(m.INSERT_SOUNDFX,g.SELECT_SOUNDFX_FREE,e,void 0,JSON.stringify({soundFXId:e,aiAudioSearch:t}))},p_t=e=>{I().event(m.INSERT_SOUNDFX,g.AI_SEARCH_SOUNDFX_SUBMIT,e)},f_t=e=>{I().event(m.INSERT_SOUNDFX,g.AI_SEARCH_SOUNDFX_FAILED,e)},g_t=e=>{I().event(m.INSERT_SOUNDFX,g.AI_SEARCH_SOUNDFX_CLICK_INSPIRATION,e)},__t=e=>{I().event(m.INSERT_SOUNDFX,g.CLICK_TAB,e.toString())},E_t=e=>{I().event(m.INSERT_SOUNDFX,g.CLICK_KEYWORD,e)},m_t=()=>{I().event(m.INSERT_SOUNDFX,g.CLICK_PLAY_PC)},h_t=e=>{I().event(m.INSERT_SOUNDFX,g.CLICK_PLAY_FREE,e)},I_t=()=>{I().event(m.INSERT_SOUNDFX,g.CLICK_PAUSE_PC)},T_t=e=>{I().event(m.INSERT_SOUNDFX,g.CLICK_PAUSE_FREE,e)},S_t=e=>{I().event(m.INSERT_SOUNDFX,g.SEARCH,e)},O_t=(e,t,o,r,n,a,i)=>{const s=e===tt.USER?"pc":t;I().event(m.INSERT_SOUNDFX,g.INSERT_SOUNDFX_DONE,void 0,void 0,JSON.stringify({soundFXId:s,wordOrder:o+1,numWordsInClip:r,numPlay:n+a,numFreePlay:n,numPCPlay:a,tab:i.toString()}))},C_t=e=>{I().event(m.INSERT_SOUNDFX,g.CLICK_BOOKMARK,e)},R_t=()=>{I().event(m.INSERT_SOUNDFX,g.CLICK_FILTER)},A_t=e=>{I().event(m.INSERT_SOUNDFX,g.SELECT_FILTER_CATEGORY,e.toString())},y_t=e=>{I().event(m.INSERT_SOUNDFX,g.SELECT_FILTER_TAG,e)},v_t=e=>{I().event(m.INSERT_SOUNDFX,g.DESELECT_FILTER_TAG,e)},w_t=(e,t)=>{const o=t?"hover":"normal";I().event(m.PANEL_STATUS,e,o)},pFe=(e,t)=>I().event(e,g.VISIT_COMMUNITY,t),N_t=()=>{I().event(m.TOOLBAR_INSERT,g.CLICK_DESIGN_TEXTBOX)},P_t=()=>{I().event(m.MOUSE_EDIT,g.CLICK_DESIGN_TEXTBOX)},b_t=()=>{I().event(m.CONTEXT_FLOATING_MENU,g.CLICK_DESIGN_TEXTBOX)},L_t=e=>{I().event(m.CONTEXT_FLOATING_MENU,g.OPEN_MENU,e)},M_t=(e,t)=>{const o=e==="context_menu"?m.MOUSECLICK_EDIT:m.CONTEXT_FLOATING_MENU;I().event(o,g.INSERT_MY_ASSET,void 0,void 0,JSON.stringify({entry:e,target:t}))},D_t=(e="context_floating_menu",t="insert")=>{I().event(m.CONTEXT_FLOATING_MENU,g.OPEN_FREE_ASSET_PANEL,void 0,void 0,JSON.stringify({source:e,mode:t}))},k_t=(e="context_floating_menu",t="insert")=>{I().event(m.CONTEXT_FLOATING_MENU,g.OPEN_USER_ASSET_PANEL,void 0,void 0,JSON.stringify({source:e,mode:t}))},F_t=()=>{I().event(m.CONTEXT_FLOATING_MENU,g.OPEN_ZOOM_ROTATE_PANEL)},U_t=()=>{I().event(m.CONTEXT_FLOATING_MENU,g.OPEN_VOLUME_PANEL)},V_t=()=>{I().event(m.CONTEXT_FLOATING_MENU,g.OPEN_TRANSITION_PANEL)},G_t=()=>{I().event(m.CONTEXT_FLOATING_MENU,g.OPEN_PLAYBACK_RATE_PANEL)},W_t=()=>{I().event(m.CONTEXT_FLOATING_MENU,g.OPEN_CLIP_BG_COLOR_PANEL)},H_t=()=>{I().event(m.CONTEXT_FLOATING_MENU,g.CLICK_FILL_CONTAIN)},j_t=()=>{I().event(m.CONTEXT_FLOATING_MENU,g.CLICK_FILL_CUT)},z_t=(e,t)=>{I().event(m.CONTEXT_FLOATING_MENU,e==="assetInsert"?g.CLICK_INSERT_SHORTCUT:g.CLICK_EFFECT_SHORTCUT,t)},Y_t=()=>{I().event(m.CONTEXT_FLOATING_MENU,g.CLICK_FILTER)},fFe=e=>{switch(e){case en.TOOLBAR:return Yt.TEXTBOX_TOOLBAR;case en.ANNOUNCEMENT_IMAGE:return Yt.ANNOUNCEMENT_IMAGE;case en.CONTEXT_MENU:return Yt.CONTEXT_MENU;case en.CONTEXT_FLOATING_MENU:return Yt.CONTEXT_FLOATING_MENU;default:return Yt.UNKNOWN}},B_t=(e,t,o,r,n,a,i)=>{const s=xi(o,r),x=fFe(t),c=Vz(x),l=Math.max(r,n),d=s+"_"+l+"_"+c+"_"+a+"_"+i,u={importRangeString:s,maxCount:l,textboxImportString:c,animated:a,textboxId:i};I().event(m.INSERT_DESIGN_TEXTBOX,e,d,void 0,JSON.stringify(u))},K_t=e=>{I().event(m.DESIGN_TEXTBOX,g.FILTER_BLINGBLING,e?"on":"off")},Tp=e=>I().event(m.ONBOARDING_TOUR_GUIDE,g.ACTION_DONE,e.toString(),void 0,JSON.stringify({step:e})),Sp=e=>{I().event(m.ONBOARDING_TOUR_GUIDE,g.CLICK_NEXT_BUTTON,e.toString(),void 0,JSON.stringify({step:e}))},Op=(e,t)=>{I().event(m.ONBOARDING_TOUR_GUIDE,g.END_RUN,e.toString(),void 0,JSON.stringify({step:e,auto:t}))},X_t=()=>{I().event(m.MOUSECLICK_EDIT,g.CLICK_INSERT_VIDEO)},J_t=()=>{I().event(m.BETWEEN_CLIP_CONTEXT_MENU,g.CLICK_INSERT_VIDEO)},gFe=(e,t,o,r,n)=>{const a=z2(e,0),i=r===_e.MODAL_UPLOAD?"modal":r===_e.CONTEXT_FLOATING_MENU?"context_floating_menu":r===_e.USER_ASSET_CONTEXT_MENU?"context_menu":r===_e.DRAG_AND_DROP||r===_e.DRAG_AND_DROP_MULTIPLE?"drag_and_drop":"between_clip_context_menu",s={importRange:a,numClipOrWord:t>0?t:void 0,numAsset:o>0?o:void 0,importType:i,isReplace:!!n,replaceOrigAspectRatio:n?ue(n.originalAspectRatio,2):void 0,replaceNewAspectRatio:n?ue(n.newAspectRatio,2):void 0};return JSON.stringify(s)},Wz=(e,t,o,r,n,a,i)=>{const s=z2(e,n),x={importRangeString:s,numClipOrWord:t>0?t:void 0,numAsset:void 0,importType:r,myassetInsertMethod:a===void 0?nm.NONE:a.insertMethod,myassetSection:a===void 0?UU.NONE:a.sectionType,videoOrderNum:a===void 0?null:a.index+1,myassetVideoId:a===void 0?"none":a.hash,isFavoriteAsset:a===void 0?"none":a.isFavoriteAsset?"favorite":"not-favorite",isReplace:!!i,replaceOrigAspectRatio:i?ue(i.originalAspectRatio,2):void 0,replaceNewAspectRatio:i?ue(i.newAspectRatio,2):void 0};I().event(m.INSERT_VIDEO,g.INSERT_VIDEO_DONE,void 0,void 0,JSON.stringify(x))},q_t=()=>{I().event(m.VIDEO_FLOATING_MENU,g.FILL_CONTAIN)},Q_t=()=>{I().event(m.VIDEO_FLOATING_MENU,g.REORDER)},Z_t=()=>{I().event(m.VIDEO_FLOATING_MENU,g.REPLACE)},$_t=()=>{I().event(m.VIDEO_FLOATING_MENU,g.FILL_CUT)},eEt=()=>{I().event(m.VIDEO_FLOATING_MENU,g.MOVE_TO_FRONT)},tEt=()=>{I().event(m.VIDEO_FLOATING_MENU,g.MOVE_FORWARD)},oEt=()=>{I().event(m.VIDEO_FLOATING_MENU,g.MOVE_TO_BACK)},rEt=()=>{I().event(m.VIDEO_FLOATING_MENU,g.MOVE_BACKWARD)},nEt=()=>{I().event(m.VIDEO_FLOATING_MENU,g.FLIP_HORIZONTAL)},aEt=()=>{I().event(m.VIDEO_FLOATING_MENU,g.FLIP_VERTICAL)},iEt=()=>{I().event(m.VIDEO_CLICK_MENU,g.FLIP_HORIZONTAL)},sEt=()=>{I().event(m.VIDEO_CLICK_MENU,g.FLIP_VERTICAL)},xEt=()=>{I().event(m.VIDEO_FLOATING_MENU,g.FILL_CONTAIN)},cEt=()=>{I().event(m.VIDEO_FLOATING_MENU,g.FILL_CUT)},_Fe=()=>{I().event(m.VIDEO_CLICK_MENU,g.MOVE_TO_FRONT)},EFe=()=>{I().event(m.VIDEO_CLICK_MENU,g.MOVE_FORWARD)},mFe=()=>{I().event(m.VIDEO_CLICK_MENU,g.MOVE_BACKWARD)},hFe=()=>{I().event(m.VIDEO_CLICK_MENU,g.MOVE_TO_BACK)},lEt=e=>{I().event(m.EDIT_VIDEO_START_MODAL,g.EDIT_VIDEO_START_DONE,e.toString())},dEt=e=>{I().event(m.EDIT_VIDEO_START_MODAL,g.PLAY,e)},uEt=()=>{I().event(m.IMAGE_FLOATING_MENU,g.CLICK_ANIMATION)},pEt=e=>{I().event(m.TEXT_FLOATING_MENU,g.CLICK_ANIMATION,void 0,void 0,JSON.stringify({animationImportType:e}))},IFe=e=>{const t=e.replaceAll("-","_");I().event(m.KENBURNS,g.KENBURNS_DONE,t)},fEt=e=>{const t=e.replaceAll("-","_");I().event(m.KENBURNS,g.KENBURNS_EDIT_DONE,t.replaceAll("-","_"))},TFe=(e,t,o)=>{const r=e.replaceAll("-","_"),n=JSON.stringify({type:r,duration:t,startDelay:o});I().event(m.ANIMATION_IMAGE,g.SELECT_ANIMATION,r,void 0,n)},SFe=()=>{I().event(m.ANIMATION_IMAGE,g.RESET_ANIMATION)},OFe=(e,t,o,r)=>{const n=e.replaceAll("-","_"),a=JSON.stringify({type:n,duration:t,startDelay:o,shapeKey:r});
1244I().event(m.ANIMATION_SHAPE,g.SELECT_ANIMATION,n,void 0,a)},CFe=e=>{I().event(m.ANIMATION_SHAPE,g.RESET_ANIMATION,void 0,void 0,e!==void 0?JSON.stringify({shapeKey:e}):void 0)},RFe=()=>{I().event(m.KENBURNS,g.REMOVE_KENBURNS)},AFe=(e,t,o)=>{const r=e.replaceAll("-","_"),n=JSON.stringify({type:r,duration:t,startDelay:o});I().event(m.ANIMATION_TEXT,g.SELECT_ANIMATION,r,void 0,n)},yFe=()=>{I().event(m.ANIMATION_TEXT,g.RESET_ANIMATION)},vFe=()=>{I().event(m.ANIMATION_MIXED,g.RESET_ANIMATION)},gEt=()=>{I().event(m.KENBURNS,g.CLICK_PREVIEW)},Y2=e=>e===qf.VIDEO?"webcam":e===qf.AUDIO?"voice":"screen",_Et=e=>I().event(e==="start_modal"?m.START_NEW_PROJECT:e==="scene_panel"?m.SCENE_PANEL:e==="toolbar_file"?m.TOOLBAR_FILE:e==="toolbar_insert"?m.TOOLBAR_INSERT:m.TOOLBAR_HOME,g.CLICK_RECORD),EEt=e=>I().event(m.RECORD,e===qf.VIDEO?g.CLICK_RECORD_WEBCAM:e===qf.AUDIO?g.CLICK_RECORD_VOICE:g.CLICK_RECORD_SCREEN),mEt=e=>I().event(m.RECORD,g.START_RECORD,Y2(e)),hEt=(e,t,o,r,n,a,i,s,x,c)=>I().event(m.RECORD,g.DONE_RECORD,Y2(e),void 0,JSON.stringify({env:t+"-"+(o?"web":"app"),video:r,audio:n,screenAudio:a,duration:i,width:s??null,height:x??null,reason:c})),IEt=e=>I().event(m.RECORD,g.CANCEL_RECORD,Y2(e),void 0),TEt=e=>I().event(m.RECORD,g.RESET_RECORD,Y2(e)),SEt=e=>I().event(m.RECORD,g.DOWNLOAD_RECORD,Y2(e)),OEt=e=>I().event(m.RECORD,g.ADD_TO_PROJECT,Y2(e)),CEt=e=>I().event(m.RECORD,g.VIEW_GUIDE,e),REt=(e,t,o)=>I().event(m.RECORD,g.RECORD_SETTING,void 0,void 0,JSON.stringify({type:e,stage:t,direction:o})),wFe=new Map([["textFloatingMenu",m.TEXT_FLOATING_MENU],["toolbarFormat",m.TOOLBAR_FORMAT]]),AEt=(e,t)=>{const o=wFe.get(e);o&&I().event(o,t==="open"?g.PANEL_ON:g.PANEL_OFF)},yEt=()=>I().event(m.TEXT_FLOATING_MENU,g.FOCUS_ON),vEt=()=>I().event(m.TEXT_FLOATING_MENU,g.FOCUS_OFF),wEt=()=>I().event(m.TEXT_FLOATING_MENU,g.FOCUS_ERROR),NEt=e=>{const t=new Map([[Kr.ALL,g.CLICK_ALL_TAB],[Kr.Image,g.CLICK_IMAGE_TAB],[Kr.Video,g.CLICK_VIDEO_TAB],[Kr.Shape,g.CLICK_SHAPE_TAB],[Kr.GIPHY,g.CLICK_GIPHY_TAB]]),o=t.get(e);if(o)if(e===Kr.GIPHY){const r={tabOpenTrigger:am.CLICK_TAB};I().event(m.INSERT_FREE_SOURCE,o,am.CLICK_TAB,void 0,JSON.stringify(r))}else I().event(m.INSERT_FREE_SOURCE,o)},PEt=()=>{const e={tabOpenTrigger:am.CLICK_VIEW_ALL};I().event(m.INSERT_FREE_SOURCE,g.CLICK_GIPHY_TAB,am.CLICK_VIEW_ALL,void 0,JSON.stringify(e))},bEt=e=>{I().event(m.EDIT_SHAPE,g.OPEN_EDIT_SHAPE_PANEL,"insert",void 0,JSON.stringify({shapeKey:e}))},LEt=e=>{I().event(m.EDIT_SHAPE,g.OPEN_EDIT_SHAPE_PANEL,"click_button",void 0,JSON.stringify({shapeKey:e}))},MEt=(e,t,o,r,n)=>{const a=t==="line"?g.EDIT_LINE_COLOR:g.EDIT_FILL_COLOR,i=JSON.stringify({method:r,value:o,shapeKey:n});I().event(m.EDIT_SHAPE,a,i,e)},DEt=(e,t,o,r,n)=>{const a=t==="line"?g.EDIT_LINE_TRANSPARENCY:g.EDIT_FILL_TRANSPARENCY,i=JSON.stringify({method:r,value:o,shapeKey:n});I().event(m.EDIT_SHAPE,a,i,e)},kEt=(e,t,o,r)=>{const n=JSON.stringify({method:o,value:t,shapeKey:r});I().event(m.EDIT_SHAPE,g.EDIT_LINE_WEIGHT,n,e)},FEt=(e,t,o)=>{const r=JSON.stringify({method:t,value:e,shapeKey:o});I().event(m.EDIT_SHAPE,g.EDIT_CORNER_ROUNDING,void 0,void 0,r)},UEt=(e,t,o)=>{const r=JSON.stringify({value:t?"on":"off",shapeKey:o});I().event(m.EDIT_SHAPE,g.EDIT_LINE_ROUND,r,e)},VEt=(e,t,o)=>{const r=JSON.stringify({value:t?"on":"off",shapeKey:o});I().event(m.EDIT_SHAPE,g.EDIT_LINE_DOTTED,r,e)},TP=e=>{const t={[Po.BACK]:g.MOVE_TO_BACK,[Po.BACKWARD]:g.MOVE_BACKWARD,[Po.FORWARD]:g.MOVE_FORWARD,[Po.FRONT]:g.MOVE_TO_FRONT};return L.get(t,e)},GEt=(e,t)=>{const o=TP(e);o&&I().event(m.SHAPE_FLOATING_MENU,o,void 0,void 0,JSON.stringify({shapeKey:t}))},sE=(e,t)=>{const o=TP(e);o&&I().event(m.SHAPE_CLICK_MENU,o,void 0,void 0,t!==void 0?JSON.stringify({shapeKey:t}):void 0)},WEt=(e,t,o)=>new Map([[z.IMAGE,{[Po.FORWARD]:tke,[Po.FRONT]:eke,[Po.BACK]:rke,[Po.BACKWARD]:oke}],[z.VIDEO,{[Po.FORWARD]:EFe,[Po.FRONT]:_Fe,[Po.BACK]:hFe,[Po.BACKWARD]:mFe}],[z.SHAPE,{[Po.FORWARD]:()=>sE(Po.FORWARD,o),[Po.FRONT]:()=>sE(Po.FRONT,o),[Po.BACK]:()=>sE(Po.BACK,o),[Po.BACKWARD]:()=>sE(Po.BACKWARD,o)}],[z.SIMPLE_CHARACTER,{[Po.FORWARD]:()=>xE(Po.FORWARD),[Po.FRONT]:()=>xE(Po.FRONT),[Po.BACK]:()=>xE(Po.BACK),[Po.BACKWARD]:()=>xE(Po.BACKWARD)}]]).get(e)?.[t]??(()=>{}),HEt=e=>{I().event(m.SHAPE_CLICK_MENU,g.PASTE,void 0,void 0,e!==void 0?JSON.stringify({shapeKey:e}):void 0)},jEt=()=>{I().event(m.TOOLBAR_COMMON,g.CLICK_EXPORT_TO)},zEt=()=>{I().event(m.TOOLBAR_COMMON,g.CLICK_EXPORT_TO_VIDEO)},YEt=()=>{I().event(m.TOOLBAR_COMMON,g.CLICK_EXPORT_TO_SRT)},BEt=()=>{I().event(m.TOOLBAR_COMMON,g.CLICK_EXPORT_TO_TXT)},KEt=()=>{I().event(m.TOOLBAR_COMMON,g.CLICK_EXPORT_TO_XML)},XEt=()=>{I().event(m.TOOLBAR_COMMON,g.CLICK_EXPORT_TO_FCPXML)},JEt=()=>{I().event(m.TOOLBAR_COMMON,g.CLICK_EXPORT_TO_DAVINCI_XML)},qEt=()=>{I().event(m.TOOLBAR_COMMON,g.CLICK_EXPORT_TO_CAPTION_VIDEO)},QEt=()=>{I().event(m.TOOLBAR_COMMON,g.CLICK_EXPORT_TO_AUDIO)},ZEt=()=>{I().event(m.TOOLBAR_COMMON,g.CLICK_EXPORT_TO_IMAGE)},$Et=()=>{I().event(m.TOOLBAR_COMMON,g.CLICK_EXPORT_TO_VREW_PROJECT)},emt=(e,t)=>{const o=z2(e,0),r={type:"gif",importRange:o,numClipOrWord:t,importType:"between_clip_context_menu",stockSite:"giphy"};I().event(m.INSERT_SOURCE_CLIP,g.INSERT_FREE_SOURCE_DONE,void 0,void 0,JSON.stringify(r))},tmt=()=>I().event(m.AI_VOICE_OVER_CLIP,g.AI_VOICE_CANCEL),omt=e=>I().event(m.TOOLBAR_INSERT,g.CLICK_CAPTION_DUBBING,e),rmt=e=>I().event(m.TOOLBAR_INSERT,g.CLICK_CAPTION_DUBBING_OPTION,void 0,void 0,JSON.stringify({dubbingOption:e})),NFe=e=>I().event(m.CAPTION_DUBBING,g.ASK_DELETE_ALL_DUBBING,void 0,void 0,JSON.stringify({deleteOrNot:e})),nmt=e=>I().event(m.CAPTION_DUBBING_ALERT,g.NO_CAPTION_DUBBING_TO_EDIT,void 0,void 0,JSON.stringify({dubbingOption:e})),PFe=()=>I().event(m.CAPTION_DUBBING_ALERT,g.NO_CAPTION_TO_DUBBING),bFe=e=>I().event(m.CAPTION_DUBBING_ALERT,g.CREATE_ONLY_WHEN_NO_DUBBING,void 0,void 0,JSON.stringify({createOrNot:e})),LFe=()=>I().event(m.CAPTION_DUBBING_ALERT,g.ALL_CAPTIONS_ALREADY_HAVE_DUBBING),amt=e=>I().event(m.CAPTION_DUBBING,g.TOGGLE_TTS_DUBBING_AUTO_MUTE,e?"on":"off"),imt=e=>I().event(m.CAPTION_DUBBING,g.TOGGLE_TTS_DUBBING_AUTO_FREEZE_WORD,e?"on":"off"),MFe=(e,t)=>
1244I().event(m.CAPTION_DUBBING,g.SUBMIT,void 0,void 0,JSON.stringify({autoMute:e,autoFreezeWord:t})),smt=(e,t,o,r)=>{if(e&&t===en.DRAG_AND_DROP_TO_MYASSET)return;let n=0,a=0,i=0;r.forEach(({type:x})=>{switch(x){case Pt.IMAGE:n++;break;case Pt.VIDEO:a++;break;case Pt.GIF:i++;break}});const s={panelOpenTrigger:e?t===en.TOOLBAR?"toolbar-insert":t===en.CONTEXT_FLOATING_MENU?"context-floating-menu":t===en.CLIP_GAP_FLOATING_BUTTON?"between-clip-context-menu":t===en.CLIPBOARD?"paste":t===en.CONTEXT_MENU?"mouseclick-edit":t===en.DRAG_AND_DROP?"drag-and-drop":"none":"none",currentTab:xc(o),imageCnt:n,videoCnt:a,gifCnt:i,totalAssetCnt:n+a+i};I().event(m.INSERT_MYASSET,g.SHOW_MYASSET_PANEL,e?"on":"off",void 0,JSON.stringify(s))},xmt=(e,t)=>{const o={imageUploadMethod:e?"click-import-from-pc-button":"click-empty-drop-region",currentTab:xc(t)};I().event(m.INSERT_MYASSET,g.IMPORT_MYASSET_PC_START,void 0,void 0,JSON.stringify(o))},cmt=e=>{const t={imageUploadMethod:"click-import-from-mobile-button",currentTab:xc(e)};I().event(m.INSERT_MYASSET,g.IMPORT_MYASSET_MOBILE_START,void 0,void 0,JSON.stringify(t))},DFe=(e,t)=>{const{uploadImgCnt:o,uploadVideoCnt:r}=t,n=o>0,a=r>0,i=e===Kr.ALL||n&&a?"all":n?"image":"video",s=xc(e),x=[eu.AUTOMATIC_BETWEEN_CLIP_CONTEXT_MENU_FROM_MOBILE,eu.AUTOMATIC_CONTEXT_MENU_FROM_MOBILE,eu.CLICK_IMPORT_FROM_MOBILE_BUTTON,eu.IMAGE_VIDEO_REPLACE_MODAL_FROM_MOBILE].includes(t.myAssetUploadMethod)?g.IMPORT_MYASSET_MOBILE_DONE:g.IMPORT_MYASSET_PC_DONE;I().event(m.INSERT_MYASSET,x,void 0,void 0,JSON.stringify({...t,prevTab:s,currentTab:i}))},kFe=(e,t,o,r,n,a,i,s)=>{const x=a.filter(R=>R.type===Pt.IMAGE),c=a.filter(R=>R.type===Pt.VIDEO),l=i.filter(R=>R.type===Pt.IMAGE),d=i.filter(R=>R.type===Pt.VIDEO),u=s.filter(R=>R.type===Pt.IMAGE),p=s.filter(R=>R.type===Pt.VIDEO),f=x.length,E=c.length,T=e!==kn.USER_ASSET_LIBRARY?void 0:t,O=f+l.length,S=E+d.length;DFe(T,{myAssetUploadMethod:o,uploadImgCnt:r,prevTotalImgCnt:f,totalImgCnt:O>Si?Si:O,overlappedImgCnt:u.length,uploadVideoCnt:n,prevTotalVideoCnt:E,totalVideoCnt:S>Si?Si:S,overlappedVideoCnt:p.length})},FFe=(e,t,o,r)=>{const n=e.filter(x=>x.type===Pt.IMAGE),a=t.filter(x=>x.type===Pt.IMAGE),i=e.filter(x=>x.type===Pt.IMAGE&&x.isFavorite).length;return{totalImgCnt:n.length,favoriteImgCnt:i,uploadImgCnt:o,overlappedImgCnt:a.length,uploadVideoCnt:r}},lmt=(e,t)=>{const o={myassetType:e,currentTab:xc(t)};I().event(m.INSERT_MYASSET,g.CLICK_INSERT_RANGE,void 0,void 0,JSON.stringify(o))},dmt=(e,t)=>{const o={myassetType:e,currentTab:xc(t)};I().event(m.INSERT,g.CLICK_MORE,void 0,void 0,JSON.stringify(o))},umt=(e,t,o,r,n)=>{let a=0,i=0,s=0;e.forEach(({type:c})=>{switch(c){case Pt.IMAGE:a++;break;case Pt.VIDEO:i++;break;case Pt.GIF:s++;break}});const x={totalImgCnt:a,isFavoriteAsset:t?"favorite":"not-favorite",myassetSection:o,totalVideoCnt:i,totalGifCnt:s,myassetType:r,currentTab:xc(n)};I().event(m.INSERT_MYASSET,g.CLICK_DELETE_MYASSET,void 0,void 0,JSON.stringify(x))},pmt=(e,t,o,r,n)=>{let a=0,i=0,s=0,x=0;e.forEach(({type:l,isFavorite:d})=>{switch(l){case Pt.IMAGE:a++,d&&i++;break;case Pt.VIDEO:s++,d&&x++;break}});const c={totalImgCnt:a,favoriteImgCnt:i,totalVideoCnt:s,favoriteVideoCnt:x,myassetType:r,currentTab:xc(n)};t?I().event(m.INSERT_MYASSET,g.CLICK_REMOVE_FAVORITE,void 0,void 0,JSON.stringify({...c,myassetSection:o})):I().event(m.INSERT_MYASSET,g.CLICK_ADD_FAVORITE,void 0,void 0,JSON.stringify(c))},fmt=(e,t)=>{const o={myassetPanelState:t?"favorite-panel":"myasset-panel"};I().event(m.INSERT_MYASSET,e===Kr.Image?g.CLICK_IMAGE_TAB:e===Kr.Video?g.CLICK_VIDEO_TAB:g.CLICK_ALL_TAB,void 0,void 0,JSON.stringify(o))},UFe=e=>{I().event(m.TRANSCODE,g.MYASSET_IMPORT_VIDEO,void 0,void 0,JSON.stringify({transcodedVideoCnt:e}))},VFe=e=>{I().event(m.MYASSET_IMPORT_WARNING,g.MYASSET_TRANSCODE_DESKTOP_ONLY,void 0,void 0,JSON.stringify({transcodeFailedVideoCnt:e}))},GFe=(e,t,o,r,n)=>{const a={totalImgCnt:e,favoriteImgCnt:t,uploadImgCnt:o,overlappedImgCnt:r,uploadVideoCnt:n};I().event(m.MYASSET_IMPORT_WARNING,g.MYASSET_STORAGE_FULL,void 0,void 0,JSON.stringify(a))},gmt=()=>{I().event(m.INSERT_MYASSET,g.CLICK_DELETE_ALL_MORE)},_mt=()=>{I().event(m.INSERT_MYASSET,g.CLICK_DELETE_ALL_ENTER)},Emt=(e,t,o)=>{let r=0,n=0,a=0;e.forEach(({type:s})=>{switch(s){case Pt.IMAGE:r++;break;case Pt.VIDEO:n++;break;case Pt.GIF:a++;break}});const i={totalImgCnt:r,totalVideoCnt:n,totalGifCnt:a,currentTab:xc(t),includeFavorites:o};I().event(m.INSERT_MYASSET,g.CLICK_DELETE_ALL_CONFIRM,void 0,void 0,JSON.stringify(i))},mmt=()=>{I().event(m.INSERT_MYASSET,g.CLICK_DELETE_ALL_CANCEL)},hmt=()=>{I().event(m.INSERT_SOURCE_CLIP,g.CLICK_GIPHY_BANNER)},WFe=(e,t,o,r)=>{const n=e>Si,a=t+o>Si,i=r.filter(S=>S.type===Pt.IMAGE),s=r.filter(S=>S.type===Pt.VIDEO),x=r.filter(S=>S.type===Pt.GIF),c=i.length,l=s.length,d=x.length,u=i.filter(S=>S.isFavorite).length,p=s.filter(S=>S.isFavorite).length,f=x.filter(S=>S.isFavorite).length,E={totalImgCnt:c,favoriteImgCnt:u,uploadImgCnt:e},T={totalVideoCnt:l,favoriteVideoCnt:p,uploadVideoCnt:t}
1244,O={totalGifCnt:d,favoriteGifCnt:f,uploadGifCnt:o};n&&a?I().event(m.MYASSET_IMPORT_WARNING,g.MYASSET_MAX_IMG_AND_VIDEO_CNT_EXCEED,void 0,void 0,JSON.stringify({...E,...T,...O})):n?I().event(m.MYASSET_IMPORT_WARNING,g.MYASSET_MAX_IMG_CNT_EXCEED,void 0,void 0,JSON.stringify(E)):a&&I().event(m.MYASSET_IMPORT_WARNING,g.MYASSET_MAX_VIDEO_CNT_EXCEED,void 0,void 0,JSON.stringify(T))},HFe=e=>{const t={mimeType:e.split("/")[0],mimeSubtype:e.split("/")[1]};I().event(m.MYASSET_IMPORT_WARNING,g.MYASSET_WRONG_FILE_FORMAT,void 0,void 0,JSON.stringify(t))},jFe=e=>{I().event(m.MYASSET_IMPORT_WARNING,g.VIDEO_PATH_CHANGED,void 0,void 0,JSON.stringify({pathChangedVideoCnt:e}))},Imt=e=>{I().event(m.CHARACTER_FLOATING_MENU,e)},xE=e=>{const t=TP(e);t&&I().event(m.CHARACTER_CLICK_MENU,t)},Tmt=e=>{I().event(m.TOOLBAR_INSERT,g.CLICK_CHARACTER,e?"on":"off")},Smt=e=>{const t={panelOpenTrigger:e===en.CHARACTER_INSERT?"insert-character":"character-floating-menu"};I().event(m.EDIT_CHARACTER,g.OPEN_EDIT_CHARACTER_PANEL,void 0,void 0,JSON.stringify(t))},zFe=(e,t,o,r,n,a,i,s,x)=>{const c=xi(e,t),l=Math.max(t,o),d={importRangeString:c,maxCount:l,characterName:r.replace("_","-"),currentActiveTag:n,characterType:a,characterDimension:i,isFavoriteCharacter:s,characterPanelState:x};I().event(m.INSERT_CHARACTER,g.INSERT_CHARACTER_DONE,void 0,void 0,JSON.stringify(d))},Omt=(e,t)=>{I().event(m.INSERT_CHARACTER,g.DELETE_CHARACTER,void 0,void 0,JSON.stringify({characterGenSource:e,poseCnt:t}))},Cmt=(e,t)=>{I().event(m.CHARACTER_SETTING,g.CLICK_APPLY_POSE,void 0,void 0,JSON.stringify({poseType:e,characterGenSource:t}))},Rmt=(e,t)=>{I().event(m.CHARACTER_SETTING,g.CLICK_GEN_POSE,void 0,void 0,JSON.stringify({poseType:e,characterGenSource:t}))},Amt=(e,t,o)=>{I().event(m.CHARACTER_SETTING,g.CLICK_REGEN_POSE,void 0,void 0,JSON.stringify({poseType:e,characterGenSource:t,regenCnt:o}))},ymt=e=>{I().event(m.CHARACTER_SETTING,g.CANCEL_GEN_POSE,void 0,void 0,JSON.stringify({poseType:e}))},vmt=e=>{I().event(m.CHARACTER_SETTING,g.CLICK_EXPECT,void 0,void 0,JSON.stringify({poseType:e}))},wmt=e=>{I().event(m.CHARACTER_SETTING,g.GEN_POSE_DONE,void 0,void 0,JSON.stringify({poseType:e}))},Nmt=e=>{I().event(m.GEN_IMAGE_CHARACTER,g.CLICK_UPLOAD_IMAGE,e)},Pmt=()=>{I().event(m.GEN_IMAGE_CHARACTER,g.HOVER_COPYRIGHT_GUIDE)},bmt=e=>{I().event(m.GEN_IMAGE_CHARACTER,g.DETECT_REALISTIC_IMAGE,void 0,void 0,JSON.stringify({isRealistic:e}))},Lmt=e=>{I().event(m.GEN_IMAGE_CHARACTER,g.SELECT_CHARACTER_STYLE,e)},Mmt=()=>{I().event(m.GEN_IMAGE_CHARACTER,g.DISPLAY_POPUP,"size_guide")},Dmt=e=>{I().event(m.GEN_IMAGE_CHARACTER,g.CLICK_NEXT,e)},kmt=e=>{I().event(m.GEN_PROMPT_CHARACTER,g.CLICK_NEXT,e)},Fmt=e=>{I().event(m.GEN_IMAGE_CHARACTER,g.CLICK_PREV,e)},Umt=e=>{I().event(m.GEN_PROMPT_CHARACTER,g.CLICK_PREV,e)},Vmt=()=>{I().event(m.GEN_IMAGE_CHARACTER,g.DISPLAY_POPUP,"final_credit_low")},Gmt=()=>{I().event(m.GEN_PROMPT_CHARACTER,g.DISPLAY_POPUP,"final_credit_low")},Wmt=e=>{I().event(m.CHARACTER_SETTING,g.LIPSYNC_TOGGLE,void 0,void 0,JSON.stringify({isOn:e}))},Hz=(e,t,o,r,n)=>{const a=gFe(e,t,o,r,n);I().event(m.INSERT_GIF,g.INSERT_GIF_DONE,void 0,void 0,a)},Hmt=e=>{I().event(m.DESIGN_TEXTBOX,g.FILTER,e.toLowerCase())},jz=(e,t)=>{I().event(t,g.CLICK_THEME,e)},jmt=e=>{jz(e,m.TOOLBAR_SETTING)},zmt=e=>{jz(e,m.THEME_SELECT)},Ymt=()=>{I().event(m.THEME_SELECT,g.DISPLAY)},Bmt=e=>{I().event(m.THEME_SELECT,e)},Kmt=e=>I().event(m.TEXT_FLOATING_MENU,g.EMOJI_INSERT,e),YFe=e=>{I().event(m.ABTEST,g.INIT_CHANNEL_TOK,e?"A":"B")},BFe=(e,t)=>{I().event(m.ABTEST,g.INIT,void 0,void 0,JSON.stringify({[e]:t}))},Xmt=e=>{I().event(m.UPLOAD,g.POPUP_SETTING_HARDCUT,e)},Jmt=e=>{I().event(m.UPLOAD,g.POPUP_SETTING_HARDCUT_MARK,e)},qmt=e=>{I().event(m.UPLOAD,g.POPUP_SETTING_HARDCUT_DIVIDE_CLIP,e)},Qmt=()=>{I().event(m.CONTEXT_FLOATING_MENU,g.REMOVE_HARDCUT_ICON)},Zmt=e=>{const t=e?"on":"off";I().event(m.RATIO_SETTING,g.CLICK_CLIP_COLOR_EFFECT,t)},$mt=e=>{const t=Eo(kn).getKeyOrDefault(e);I().event(m.CONTEXT_MENU,g.OPEN_PANEL,t)},KFe=(e,t,o,r,n)=>{const a=f=>f.words.every(E=>iN(E,r)),i=f=>Pw(f.words,o,r,n)!=="none",s=f=>{const E=oi(f.words[0],o,r)?.mediaId;return E&&!a(f)&&!i(f)&&!pl(E)},x=f=>{const E=GR(f.words[0],o,r)?.mediaId;return f.videoTransform!==void 0&&E};let c=0,l=0,d=0,u=0;e.forEach(f=>
1244{a(f)&&(l+=1),i(f)&&(u+=1),s(f)&&(d+=1),x(f)&&(c+=1)});const p=t?0:e.length-(c+l+d+u);return{zoomRotatedClips:c,blankClips:l,audioClips:d,aiVoiceClips:u,fullScreenClips:p}},eht=(e,t,o,r,n,a,i,s,x,c)=>{const l=t===nt.ALL_CLIPS?n:t===nt.SELECTED_CLIPS?a:[n[i]],d=l.length,u=KFe(l,r,s,x,c),p=xi(t,d),f=JSON.stringify({colorCode:e,importRangeString:p,maxCount:d,imageImportString:o,ratioEdited:r,...u});I().event(m.CLIP_COLOR_EFFECT,g.SELECT_CLIP_COLOR,void 0,void 0,f)},tht=()=>{I().event(m.CLIP_COLOR_EFFECT,g.CLICK_CLIP_COLOR_EFFECT)},oht=()=>{I().event(m.CLIP_COLOR_EFFECT,g.CLICK_DELETE_EFFECT)},XFe=(e,t)=>{I().event(e,g.BOLD,void 0,void 0,t)},JFe=(e,t)=>{I().event(e,g.ITALIC,void 0,void 0,t)},qFe=(e,t,o)=>{I().event(e,g.INPUT_SIZE,t,void 0,o)},QFe=(e,t)=>{I().event(e,g.TEXT_COLOR,void 0,void 0,t)},ZFe=(e,t)=>{I().event(e,g.OUTLINE_COLOR,void 0,void 0,t)},$Fe=(e,t,o)=>{I().event(e,g.OUTLINE_WIDTH,t,void 0,o)},eUe=(e,t)=>{I().event(e,g.BACKGROUND_COLOR,void 0,void 0,t)},tUe=(e,t)=>{I().event(e,g.SHADOW_COLOR,void 0,void 0,t)},oUe=(e,t)=>{I().event(e,g.HIGHLIGHT_COLOR,void 0,void 0,t)},NA=e=>{I().event(m.BACKUP_NOTICE,e)},xc=e=>e===Kr.ALL?"all":e===Kr.Image?"image":e===Kr.Video?"video":"none",rht=(e,t,o)=>{I().event(m.INSERT_CHARACTER,g.CLICK_ADD_FAVORITE,void 0,void 0,JSON.stringify({characterName:e,characterType:t,charDimension:o}))},nht=(e,t,o)=>{I().event(m.INSERT_CHARACTER,g.CLICK_REMOVE_FAVORITE,void 0,void 0,JSON.stringify({characterName:e,characterType:t,charDimension:o}))},aht=e=>{I().event(m.INSERT_CHARACTER,g.CLICK_FAVORITE_ALL,void 0,void 0,JSON.stringify({favoriteCharacterCnt:e}))},iht=(e,t)=>{I().event(m.INSERT_CHARACTER,g.CLICK_GO_CHARACTER_PANEL,void 0,void 0,JSON.stringify({favoriteCharacterCnt:e,myCharacterCnt:t}))},sht=()=>{I().event(m.MAKE_MY_CHARACTER,g.CLICK_MAKE_CHARACTER,void 0,void 0)},xht=e=>{I().event(m.MAKE_MY_CHARACTER,g.CLICK_GEN_METHOD,e)},cht=e=>{const t={characterRegenCnt:e.characterRegenCnt,lipsyncRegenCnt:e.lipsyncRegenCnt};I().event(m.MAKE_MY_CHARACTER,g.MAKE_CHARACTER_CANCEL,e.stage,void 0,JSON.stringify(t))},lht=e=>{I().event(m.GEN_IMAGE_CHARACTER,g.MAKE_CHARACTER_DONE,void 0,void 0,JSON.stringify(e))},dht=e=>{I().event(m.GEN_PROMPT_CHARACTER,g.MAKE_CHARACTER_DONE,void 0,void 0,JSON.stringify(e))},uht=()=>{I().event(m.SHORTS_MODE,g.UPLOAD_VIDEO)},pht=e=>{I().event(m.SHORTS_MODE,g.SELECT_VIDEO,void 0,void 0,JSON.stringify({videoLabel:e}))},fht=()=>{I().event(m.SHORTS_MODE,g.DELETE_VIDEO)},ght=e=>{I().event(m.SHORTS_MODE,g.SELECT_LANGUAGE,e)},_ht=e=>{I().event(m.SHORTS_MODE,g.SELECT_FRAMEPACK,e)},Eht=e=>{I().event(m.SHORTS_MODE,g.CLICK_LAYOUT,e)},mht=e=>{I().event(m.SHORTS_MODE,g.CLICK_BACKGROUND_COLOR,void 0,void 0,JSON.stringify({colorCode:e}))},hht=e=>{I().event(m.SHORTS_MODE,g.SELECT_MAX_LINE_LENGTH,e.toFixed(0))},Iht=e=>{I().event(m.SHORTS_MODE,g.CLICK_CAPTION_FORMAT,e)},Tht=()=>{I().event(m.SHORTS_MODE,g.INSERT_IMAGE_DONE)},Sht=e=>{I().event(m.SHORTS_MODE,g.INSERT_TEXT_DONE,e)},Oht=()=>{I().event(m.SHORTS_MODE,g.DELETE_IMAGE)},Cht=()=>{I().event(m.SHORTS_MODE,g.DELETE_TEXT)},Rht=e=>{I().event(m.SHORTS_MODE,g.TOGGLE_PREVIEW,e)},Aht=()=>{I().event(m.SHORTS_MODE,g.CLICK_NEXT)},yht=()=>{I().event(m.SHORTS_MODE,g.CLICK_PREVIOUS)},vht=(e,t,o,r,n)=>{const a=n.type===bs.USER_VIDEO?r:pn.None,i=qj(a).maxLineLength,s=Mt(ke.SHORTS_OVERLAY_GUIDE)?"on":"off",x=e.fullRangeAssets.filter(p=>p.isUserInsertedAsset),c=x.filter(p=>p.track.type===z.IMAGE).length,l=x.filter(p=>p.track.type===z.WEB).length,d=XIe(n),u={language:a,templateId:t,videoTransform:e.videoTransform.videoTransformFillType===ro.CONTAIN?"fit":"fill",backgroundColor:e.backgroundColor??"default",lineBreakerMaxLineLength:i,captionStyle:o,userImageNum:c,userTextboxNum:l,uiGuideToggled:s,videoLabel:d};I().event(m.SHORTS_MODE,g.START_REAL_EDIT,void 0,void 0,JSON.stringify(u))},wht=(e,t,o,r)=>{I().event(m.DOCS_TO_VIDEO,g.CLOSE_DOCS,void 0,void 0,JSON.stringify({stage:e,generateCount:t,maxTextLength:o,workingTime:r}))},Nht=()=>{I().event(m.DOCS_TO_VIDEO,g.SHOW_GUIDE)},Pht=(e,t,o)=>{I().event(m.DOCS_TO_VIDEO,g.UPLOAD_FORMAT,void 0,void 0,JSON.stringify({format:e,method:t,replace:o}))},bht=()=>{I().event(m.DOCS_TO_VIDEO,g.CLICK_HOW_TO_CONVERT)},Lht=()=>{I().event(m.DOCS_TO_VIDEO,g.UPLOAD_DONE)},Mht=()=>{I().event(m.DOCS_TO_VIDEO,g.CLICK_SETTING)},Dht=e=>{I().event(m.DOCS_TO_VIDEO,g.IMG_QUALITY,e)},kht=()=>{I().event(m.DOCS_TO_VIDEO,g.REPLACE_FILE)},Fht=()=>{I().event(m.DOCS_TO_VIDEO,g.REPLACE_DONE)},Uht=()=>{I().event(m.DOCS_TO_VIDEO,g.METHOD_AI_SCRIPT)},Vht=()=>{I().event(m.DOCS_TO_VIDEO,g.METHOD_IMPORT_FROM_FILE)},Ght=()=>{I().event(m.DOCS_TO_VIDEO,g.METHOD_MANUAL)},Wht=e=>{I().event(m.DOCS_TO_VIDEO,g.TRY_UPLOAD,void 0,void 0,JSON.stringify({method:e}))},Hht=(e,t,o,r,n)=>{const a={importMethod:e,usedPrompt:t,promptLength:o,numSlides:r,initialTextLength:n};I().event(m.DOCS_TO_VIDEO,g.IMPORT_DONE,void 0,void 0,JSON.stringify(a))},jht=e=>{I().event(m.DOCS_TO_VIDEO,g.CLICK_VIEW,e)},zht=e=>{I().event(m.DOCS_TO_VIDEO,g.CLICK_SLIDE,(e+1).toString())},Yht=()=>{I().event(m.DOCS_TO_VIDEO,g.HOVER_CLIP_GUIDE)},Bht=e=>{I().event(m.DOCS_TO_VIDEO,g.CLICK_NEXT,e)},Kht=e=>{I().event(m.DOCS_TO_VIDEO,g.CLICK_PREVIOUS,e)},rUe=()=>{I().event(m.DOCS_TO_VIDEO,g.GENERATE_SCRIPT_START)},nUe=()=>{I().event(m.DOCS_TO_VIDEO,g.GENERATE_SCRIPT_DONE)},aUe=()=>{I().event(m.DOCS_TO_VIDEO,g.GENERATE_SCRIPT_FAILED)},Xht=()=>{I().event(m.DOCS_TO_VIDEO,g.HOVER_LENGTH_GUIDE)},Jht=(e,t)=>
1244{I().event(m.DOCS_TO_VIDEO,g.DONE_SCRIPT,void 0,void 0,JSON.stringify({editedTextLength:e,editingTime:t}))},qht=e=>{I().event(m.DOCS_TO_VIDEO,g.TOGGLE_AI_VOICE,e?"on":"off")},iUe=(e,t,o,r,n,a,i,s,x,c)=>{const l={slides:e,workingTime:t,inputTextLength:o,maxTextLength:r,isDirty:n,voiceOn:a,enterCount:i,imgQuality:s,scriptMethod:x,generateCount:c};I().event(m.DOCS_TO_VIDEO,g.START_REAL_EDIT,void 0,void 0,JSON.stringify(l))},Qht=()=>{I().event(m.IMAGES_TO_VIDEO,g.DISPLAY)},Zht=(e,t)=>{I().event(m.IMAGES_TO_VIDEO,g.CLOSE,JSON.stringify({stage:e,workingTime:t}))},$ht=(e,t,o="pc")=>{I().event(m.IMAGES_TO_VIDEO,g.ADD_IMAGES,JSON.stringify({numberOfAddedImages:e,numberOfImages:t,importFrom:o}))},eIt=e=>{I().event(m.IMAGES_TO_VIDEO,g.REORDER_IMAGES,JSON.stringify({numberOfReordered:e}))},tIt=(e,t)=>{I().event(m.IMAGES_TO_VIDEO,g.DELETE_IMAGES,JSON.stringify({numberOfDeleted:e,numberOfImages:t}))},oIt=e=>{I().event(m.IMAGES_TO_VIDEO,g.IMAGES_FINALIZED,JSON.stringify({numberOfImages:e}))},rIt=(e,t,o)=>{I().event(m.IMAGES_TO_VIDEO,g.CAPTION_FINALIZED,JSON.stringify({numberOfImages:e,numberOfScriptedImages:t,totalTextLength:o}))},nIt=(e,t,o,r,n)=>{I().event(m.IMAGES_TO_VIDEO,g.SETTING_FINALIZED,JSON.stringify({videoRatio:e,fillType:t,useAiVoice:o,useAutoAnimation:r,numberOfImages:n}))},aIt=(e,t,o,r,n,a,i,s,x,c,l)=>{I().event(m.IMAGES_TO_VIDEO,g.CREATED_IMAGES,JSON.stringify({videoRatio:e,fillType:t,useAiVoice:o,useAutoAnimation:r,numberOfImages:n,numberOfScriptedImages:a,totalScriptLength:i,areAllAspectRatiosEqual:s,totalScriptInputDuration:x,creatingTime:c,workingTime:l}))},iIt=()=>{I().event(m.PAYMENT,g.OPEN_EVENT)},sIt=e=>{I().event(m.ASSET_LIST,g.CLICK_ICON,e)},xIt=e=>{I().event(m.ASSET_LIST,g.DRAG_LIST,e)},cIt=(e,t,o,r)=>{const n=e.length===1?"single":"multi",a=!t&&!o?g.SELECT:t?g.CTRL_SELECT:g.SHIFT_SELECT,i=n==="single"?{assetType:Dt(e[0].assetType)}:cn(e.map(x=>Dt(x.assetType))),s={selectType:n,...i,listType:r};I().event(m.ASSET_LIST,a,void 0,void 0,JSON.stringify(s))},lIt=(e,t,o)=>{const r=e==="click_menu"?g.CLICK_MENU:g.RIGHT_CLICK;I().event(m.ASSET_LIST,r,t,void 0,JSON.stringify({listType:o}))},dIt=e=>{const t=e==="expand"?g.DRAG_EXPAND:g.DRAG_CONTRACT;I().event(m.ASSET_LIST,t)},uIt=(e,t,o)=>{const r=t.length===1?"single":"multi",n=r==="single"||t.slice(1).every(x=>x.rangeType===t[0].rangeType)?t[0].rangeType:"combi",a=r==="single"?{assetType:Dt(t[0].assetType)}:cn(t.map(x=>Dt(x.assetType))),i=[g.DELETE,g.CLICK_EDIT_RANGE],s={selectType:i.includes(e)?r:void 0,...a,listType:o};I().event(m.LIST_EDIT,e,n,void 0,JSON.stringify(s))},br=(e,t,o)=>{const r=JSON.stringify({op:e,message:t,...o});I().event(m.AUTH,g.AUTH_TRACK,e+"_"+t,void 0,r)},pIt=()=>{I().event(m.FEEDBACK,g.CHATTING)},fIt=()=>{I().event(m.FEEDBACK,g.ERROR_REPORT)},gIt=e=>{I().event(m.FEEDBACK,g.FEEDBACK_SEND_PROJECT,e)},_It=(e,t,o,r)=>{I().event(m.TTV_MODAL,g.CLICK_VIDEO_STYLE,void 0,void 0,JSON.stringify({type:e,styleId:t,tag:o,trigger:r,ttvVersion:to()}))},EIt=e=>{I().event(m.TTV_MODAL,g.CHANGE_AI_WRITING_MODE,void 0,void 0,JSON.stringify({writingMode:e,ttvVersion:to()}))},mIt=()=>{I().event(m.TTV_MODAL,g.CLICK_VOICE_CHANGE_BUTTON,void 0,void 0,JSON.stringify({ttvVersion:to()}))},hIt=e=>{I().event(m.TTV_MODAL,g.CHANGE_BGM_TYPE,void 0,void 0,JSON.stringify({bgmType:e,ttvVersion:to()}))},IIt=e=>{I().event(m.TTV_MODAL,g.CLICK_BGM_PREVIEW,void 0,void 0,JSON.stringify({trigger:e,ttvVersion:to()}))},TIt=e=>{I().event(m.TTV_MODAL,g.CLICK_TTS_PREVIEW,void 0,void 0,JSON.stringify({trigger:e,ttvVersion:to()}))},SIt=(e="none")=>{I().event(m.TTV_MODAL,g.CLICK_SUBJECT_REFRESH,void 0,void 0,JSON.stringify({videoStyleTag:e,ttvVersion:to()}))},OIt=(e="none")=>{I().event(m.TTV_MODAL,g.CLICK_SUBJECT,void 0,void 0,JSON.stringify({videoStyleTag:e,ttvVersion:to()}))},CIt=()=>{I().event(m.VIDEO_STYLE_MAKER,g.INIT,void 0,void 0,JSON.stringify({ttvVersion:to()}))},RIt=e=>{I().event(m.VIDEO_STYLE_MAKER,g.VIDEO_STYLE_MAKE_DONE,void 0,void 0,JSON.stringify({isWithoutScriptMode:e,ttvVersion:to()}))},AIt=(e,t)=>{I().event(m.VIDEO_STYLE_MAKER,g.CLOSE,void 0,void 0,JSON.stringify({stage:e,isEditMode:t,ttvVersion:to()}))},yIt=()=>{I().event(m.VIDEO_STYLE_MAKER,g.GENERATE_PROMPT,void 0,void 0,JSON.stringify({ttvVersion:to()}))},vIt=e=>{I().event(m.VIDEO_STYLE_MAKER,g.PROMOTE,void 0,void 0,JSON.stringify({buttonType:e,ttvVersion:to()}))},wIt=e=>{I().event(m.TTV_MODAL,g.TOGGLE_AI_WRITING_TOOLTIP,void 0,void 0,JSON.stringify({show:"on",ttvVersion:to()}))},NIt=(e,t,o="none",r="none")=>{I().event(m.TTV_MODAL,g.CLICK_AI_WRITING_BUTTON,void 0,void 0,JSON.stringify({type:e,videoStyleId:o,tag:r,writingMode:t,ttvVersion:to()}))},PIt=e=>{I().event(m.TTV_MODAL,g.AI_WRITING_FAILED,void 0,void 0,JSON.stringify({writingMode:e,model:rP[e],ttvVersion:to()}))},bIt=(e,t,o,r,n,a)=>{I().event(m.TTV_MODAL,g.AI_WRITING_DONE,void 0,void 0,JSON.stringify({numChar:e,resolvedTimeSec:Math.floor(t/1e3),writingMode:o,model:rP[o],scriptLengthSetting:r,useScriptPrompt:n,videoStyleTag:a,ttvVersion:to()}))},LIt=(e,t,o)=>{I().event(m.IMAGE_GENERATE,g.CHANGE_GENIMAGE_OPTION,void 0,void 0,JSON.stringify({trigger:e,type:t,value:o}))},zz=(e,t,o,r,n,a,i,s,x,c,l,d,u,p)=>{const{imageInfo:{style:f,videoMute:E,videoOn:T,isHighResolutionOn:O,fillType:S,referenceImages:R,shortsImageRatio:y},isImageOn:v,isBgmOn:w,isTTSOn:N}=e,M=a?{ttvOptionCaptionOn:a.isOn??!0,ttvOptionCaptionLength:a.length,ttvOptionCaptionPosition:a.position,ttvOptionCaptionAutoAnimation:a.autoAnimation}:{},k=v&&lh(i,"consistency"),F=k?R?.length??0:0,G=yT()?{usesSavedMediaSetting:d,numMediaSetting:u}:{};
1244return{isImageOn:v?"O":"X",isBgmOn:w?"O":"X",isTTSOn:N?"O":"X",isVideoOn:T?"O":"X",isAutoMuteOn:E?"O":"X",style:f,numText:t,isChatGPTTextUsed:o?"O":"X",writingMode:o?r:"none",videoRatio:n,...M,genimageEngine:i,useHighResolution:O&&lh(i,"high_resolution"),videoFillType:S,useScriptPrompt:x,useImagePrompt:s,scriptLengthSetting:c,musicType:l??"off",useConsistencyMode:k,referenceImageCount:F,useReferenceImage:F>0,shortsImageRatio:y,assetInsertionFrequency:p,...G,ttvVersion:to()}},MIt=(e,t,o,r,n,a,i,s,x,c,l,d,u,p,f,E,T,O,S,R,y,v,w,N,M,k,F,G,B,W)=>{const Q=zz(e,t,o,d,p,E,T,O,S,R,y,G,B,W),j=s/(r||1);I().event(m.TTV_MODAL,g.TTV_DONE,void 0,void 0,JSON.stringify({...Q,numClip:r,numImage:n,numVideo:a,numEmptyClip:i,totalTimeSec:s,numVrewImage:x,numStabilityImage:c,videoStyleTag:l,numNSFWImage:u,totalDurationSec:f,elapsedSecPerClip:ue(j,2),imageProvider:v,ttsElapsedSec:w,visualAssetsElapsedSec:N,elapsedSecByClipP50:M,elapsedSecByClipP95:k,elapsedSecByClipP100:F,userGuidanceLength:e.imageInfo.userGuidance?.length??0})),Q.useConsistencyMode&&I().event(m.IMAGE_GENERATE,g.CONSISTENCY_TTV,void 0,void 0,JSON.stringify({referenceImageCount:Q.referenceImageCount,isVideoOn:e.imageInfo.videoOn?"O":"X"}))},DIt=(e,t,o,r,n,a,i)=>{I().event(m.TTV_MODAL,g.TTV_CLOSE,void 0,void 0,JSON.stringify({watingTime:e,stage:t,isAIWritingUsed:o,ttvVersion:to(),elapsedSecByClipP50:r,elapsedSecByClipP95:n,elapsedSecByClipP100:a,elapsedSecPerClip:i}))},Yz={[en.TOOLBAR]:"toolbar",[en.CONTEXT_MENU]:"context_menu",[en.CONTEXT_FLOATING_MENU]:"context_floating_menu",[en.ASSET_MENU]:"asset_menu",[en.IMAGE_VIDEO_GENERATE]:"result_tile",[en.ANNOUNCEMENT_IMAGE]:"announcement",[en.PROGRESS_DOCK]:"progress_dock"},kIt=(e,t="generate")=>{const o=Yz[e];o&&I().event(m.TOOLBAR_INSERT,g.OPEN_IMAGE_GENERATE_PANEL,void 0,void 0,JSON.stringify({trigger:o,mode:t}))},FIt=(e,t="generate",o)=>{const r=Yz[e];if(!r)return;const n=(()=>{if(o)switch(o.kind){case"video":return{seedKind:o.kind,videoMode:o.mode};case"frame":return{seedKind:o.kind,imageDestination:o.destination};case"references":return{seedKind:o.kind,videoMode:o.mode}}})();I().event(m.TOOLBAR_INSERT,g.OPEN_VIDEO_GENERATE_PANEL,void 0,void 0,JSON.stringify({trigger:r,mode:t,...n}))},UIt=(e,t,o,r,n,a,i,s,x,c,l,d,u,p,f,E,T)=>{I().event(m.IMAGE_GENERATE,g.REQUEST_AI_IMAGE_AUTO_INSERTION,void 0,void 0,JSON.stringify({trigger:e,clipCount:t,applyRange:o,style:r,color:n,fillType:a,includeVideo:i,muteVideo:s,engine:x,useHighResolution:c,userGuidance:l,userGuidanceLength:d,includeImage:u,useConsistencyMode:p,referenceImageCount:f,useReferenceImage:E,shortsImageRatio:T}))},VIt=(e,t,o,r,n,a,i,s,x,c,l,d,u,p,f,E,T)=>{if(I().event(m.IMAGE_GENERATE,g.AI_IMAGE_AUTO_INSERTION_DONE,void 0,void 0,JSON.stringify({trigger:e,clipCount:t,applyRange:o,style:r,color:n,fillType:a,includeVideo:i,muteVideo:s,engine:x,useHighResolution:c,userGuidance:l,includeImage:d,imageProvider:u,useConsistencyMode:p,referenceImageCount:f,useReferenceImage:E,shortsImageRatio:T})),p){const O=e==="stt-modal"?g.CONSISTENCY_STT:g.CONSISTENCY_EDIT;I().event(m.IMAGE_GENERATE,O,void 0,void 0,JSON.stringify({referenceImageCount:f,isVideoOn:i?"O":"X"}))}},sUe=(e,t,o,r,n,a,i,s,x,c)=>{I().event(m.IMAGE_GENERATE,g.GENERATE_EACH_IMAGE,void 0,void 0,JSON.stringify({isFailled:o?"O":"X",doesPromptUsed:r?"O":"X",numRequestedImage:e,numGeneratedImage:t,provider:n,elapsedSec:a,trigger:i??"unknown",engine:s,useHighResolution:x,referenceImageCount:c}))},GIt=e=>{I().event(e,g.DOWNLOAD_TTI)},WIt=e=>{const t=se().getProjectId();if(t===void 0)return;Ra(g.DOWNLOAD_TTI_DONE,t);const o=iu[g.DOWNLOAD_TTI_DONE+t];I().event(e,g.DOWNLOAD_TTI_DONE,void 0,void 0,JSON.stringify({downloadGenImgCnt:o}))},HIt=(e,t,o,r,n,a)=>{const i=_e.IMAGE_REPLACE_MODAL,s="REPLACE_SELECTED_ELEMENTS";a?.type===Za.FREE_SOURCE?Uz(s,i,0,0,e,a,{originalAspectRatio:o,newAspectRatio:r}):t===z.VIDEO?n?.videoOrigin===If.TRANSCODE_GIF?Hz(s,0,e,i,{originalAspectRatio:o,newAspectRatio:r}):Wz(s,0,0,i,0,a?.type===Za.USER_ASSET?a:void 0,{originalAspectRatio:o,newAspectRatio:r}):Lz(0,0,0,s,i,!1,a?.type===Za.USER_ASSET?a:void 0,{originalAspectRatio:o,newAspectRatio:r})},jIt=(e,t,o,r,n,a,i)=>{I().event(m.IMAGE_GENERATE_MODAL,g.CHATGENIMAGE_GENERATE_BASE_IMAGE,void 0,void 0,JSON.stringify({style:e,imageRatio:t,numRequestedImage:o,engine:r,useHighResolution:n,referenceImageCount:a,promptLength:i}))},zIt=(e,t,o,r,n,a,i,s)=>{I().event(m.IMAGE_GENERATE_MODAL,g.CHATGENIMAGE_INSERT_BASE_IMAGE,void 0,void 0,JSON.stringify({style:e,imageRatio:t,numRequestedImage:o,imageIndex:r,insertCountFromGenerateBaseImage:n,engine:a,useHighResolution:i,referenceImageCount:s}))},YIt=()=>{I().event(m.ASSET_CURSOR,g.REPLACE_WITH_GEN_VIDEO)},BIt=()=>{I().event(m.ASSET_CURSOR,g.REPLACE_WITH_GEN_IMAGE)},KIt=e=>{I().event(m.ASSET_CURSOR,g.REPLACE_WITH_STOCK,void 0,void 0,JSON.stringify({assetType:e}))},XIt=(e,t)=>
1244{I().event(m.ASSET_CURSOR,g.REPLACE_WITH_USER_ASSET,void 0,void 0,JSON.stringify({assetType:e,source:t}))},JIt=(e,t)=>{I().event(m.ASSET_CURSOR,g.CLICK_REPLACE_OPTION,void 0,void 0,JSON.stringify({entry:e,target:t}))},xUe=(e,t,o,r)=>{const{type:n,duration:a}=e??{},i=n===void 0?"reset":"adjust",s=n===void 0?"reset":n,x=o?"selected":t!==Xa.ALL?"clip":"default";I().event(m.TOOLBAR_FORMAT,g.ANIMATION,i,void 0,JSON.stringify({type:s,duration:a,target:x,clipCount:r}))},cUe=(e,t)=>{I().event(m.USAGE_LIMIT,g.CREDIT_WARNING,e+"%",void 0,JSON.stringify({usedPercentage:e,creditTrigger:t}))},Bz=(e,t,o)=>{I().event(m.USAGE_LIMIT,g.CREDIT_NOT_ENOUGH,o,void 0,JSON.stringify({balance:Math.floor(e),required:Math.ceil(t),creditTrigger:o}))},qIt=e=>{const t=$t(parseFloat((e*100).toFixed(2)),0,100);I().event(m.USAGE_LIMIT,g.GENCHARACTER,void 0,void 0,JSON.stringify({usedPercentage:t}))},lUe=e=>{const t=Kh(e);I().event(m.PREMIUM_FEATURE,g.DISPLAY,t)},dUe=e=>{const t=Kh(e);I().event(m.PREMIUM_FEATURE,g.CLICK,t)},QIt=e=>{const t=Kh(e);I().event(m.PREMIUM_FEATURE,g.LEARN_MORE,t)},uUe=e=>{I().event(m.UPGRADE_CLICK,e)},pUe=e=>{I().event(m.USAGE_ERASER_CLICK,e)},fUe=e=>{switch(e.type){case"manual":return{label:void 0,triggerType:"manual"};case"premium_feature":{const t=Kh(e.premiumFeatureType);return{label:t,triggerType:t}}case"usage_limit":return{label:e.creditTrigger,triggerType:e.creditTrigger}}},Kz=(e,{source:t,origin:o})=>{const{label:r,triggerType:n}=fUe(o),a={paymentType:e,source:t,triggerType:n};I().event(m.PREMIUM_FEATURE,g.GO_TO_UPGRADE,r,void 0,JSON.stringify(a))},gUe=(e,t)=>{const o=e==="UPGRADE",r={isUpgrade:o,planType:t.planType,planPeriod:t.period,currency:t.currency,amount:t.price};I().event(m.PAYMENT,g.COMPLETED,void 0,void 0,JSON.stringify(r))},_Ue=()=>{I().event(m.PAYMENT,g.USER_REFUND,void 0,void 0,void 0)},SP=()=>{I().event(m.PAYMENT_SOCKET,g.SOCKET_COMPLETE)},OP=()=>{I().event(m.PAYMENT_SOCKET,g.SOCKET_FALLBACK)},EUe=e=>{const t=e?g.START:g.COMPLETED;I().event(m.PAYMENT,t)},ZIt=()=>{I().event(m.PAYMENT,g.UNSUBSCRIBE)},$It=()=>{I().event(m.PAYMENT,g.RESCHEDULE)},yl=(e,t)=>I().event(m.TTS,g.CHANGE_VOICE_SETTING,e.type,void 0,JSON.stringify({prevValue:e.prevValue,nextValue:e.nextValue,triggerSource:t})),eTt=(e,t,o,r)=>I().event(m.TTS,g.TTS_RECOMMENDED_SAMPLE,void 0,void 0,JSON.stringify({speakerName:e,speakerId:t,isFreeSpeaker:o?1:0,numTries:r})),mUe=(e,t)=>I().event(m.TTS,"tts_speaker_request",void 0,void 0,JSON.stringify({...e,triggerSource:t,usageStage:"prepared_audio"})),Xz=(e,t)=>I().event(m.TTS,g.TTS_REQUEST,void 0,void 0,JSON.stringify({...e,triggerSource:t})),Jz=(e,t,o)=>{e!==t&&I().event(m.TTS,g.CHANGE_CONTENT_TEXT,void 0,void 0,JSON.stringify({prevTextLength:e.length,nextTextLength:t.length,diff:t.length-e.length,triggerSource:o}))},hUe=(e,t)=>{const o=e===bu.GRID?g.CLICK_GRID_GUIDE:g.CLICK_SHORTS_GUIDE,r=t?"on":"off";I().event(m.EDIT_GUIDE,o,r)},tTt=()=>{I().event(m.TOOLBAR_FRAMEPACK,g.CLICK_FRAMEPACK)},oTt=e=>{const t=IP(e);I().event(m.PANEL_FRAMEPACK,g.CLICK_RANGE,t)},rTt=e=>{const t=e===he.WIDE_SCREEN?"youtube":"shorts";I().event(m.PANEL_FRAMEPACK,g.CLICK_RATIO,t)},nTt=()=>{I().event(m.PANEL_FRAMEPACK,g.CLICK_APPLY)},aTt=()=>{I().event(m.PANEL_FRAMEPACK,g.CLICK_UNDO)},iTt=(e,t,o,r)=>{const n=e.videoTransform.videoRatio===he.WIDE_SCREEN?"youtube":"shorts",a=e.id,i=t?o?"both":"styleOnly":o?"ratioOnly":"none",s=r?"free":"user";I().event(m.PANEL_FRAMEPACK,g.INFO_CONFIRM,void 0,void 0,JSON.stringify({templateRatio:n,templateId:a,overrideInfo:i,templateType:s}))},sTt=(e,t)=>{const o=t==="video_audio"?g.VIDEO_AUDIO:g.SHORTS_MODE;I().event(m.CLICK_STT_TIER,o,e)},xTt=(e,t,o,r)=>{const n=t==="video_audio"?g.VIDEO_AUDIO:g.SHORTS_MODE,a=r?.reduce((s,x)=>{const c=Eo(Fb).getKeyOrDefault(x.sttType,void 0);return c===void 0||(s[c]=(s[c]??0)+(x.count??1)),s},{}),i={selectedSttTier:e,requestedSttEngine:Eo(Fb).getKeyOrDefault(o,void 0),countsOfAppliedSttEngines:a};I().event(m.AUDIO_ANALYSIS,n,i.requestedSttEngine,void 0,JSON.stringify(i)),n===g.VIDEO_AUDIO&&e===Em.PLUS&&I().event(m.AUDIO_ANALYSIS,g.STT_PLUS_VIDEO_AUDIO,i.requestedSttEngine,void 0,JSON.stringify(i))},cTt=e=>{I().event(m.CREATE_FRAMEPACK,g.CHECK_PREVIEW,e)},lTt=()=>{I().event(m.CREATE_FRAMEPACK,g.EXCLUDE_ASSET)},dTt=()=>{I().event(m.CREATE_FRAMEPACK,g.RE_ADD_ASSET)},uTt=()=>{I().event(m.CREATE_FRAMEPACK,g.CLICK_UPGRADE)},pTt=()=>{I().event(m.TOOLBAR_FRAMEPACK,g.FIND_VRT)},fTt=()=>{I().event(m.TOOLBAR_FRAMEPACK,g.IMPORT_VRT)},gTt=()=>{I().event(m.TOOLBAR_FRAMEPACK,g.CLICK_UPGRADE)},_Tt=()=>{I().event(m.TOOLBAR_FRAMEPACK,g.DELETE_FRAMEPACK)},ETt=(e,t,o,r,n)=>{const a={includedAssets:e,excludedAssets:t,templateRatio:o,numUserTemplates:r};I().event(m.CREATE_FRAMEPACK,n?g.SAVED:g.SAVE,void 0,void 0,JSON.stringify(a))},mTt=()=>{I().event(m.TOOLBAR_FRAMEPACK,g.CHECK_MY_FRAMEPACK)},hTt=(e,t)=>{I().event(m.TOOLBAR_FRAMEPACK,g.CLICK_USER_FRAMEPACK,e,void 0,JSON.stringify({numTemplates:t}))},ITt=()=>{I().event(m.SETTING,g.CHATTING)},TTt=e=>{const t={screenWidth:window.screen.width,clientWidht:document.documentElement.clientWidth};I().event("toolbar_"+e,g.CLICK_LEFT_SCROLL_BUTTON,void 0,void 0,JSON.stringify(t))},STt=e=>{const t={screenWidth:window.screen.width,clientWidht:document.documentElement.clientWidth};I().event("toolbar_"+e,g.CLICK_RIGHT_SCROLL_BUTTON,void 0,void 0,JSON.stringify(t))},OTt=e=>{const t={screenWidth:window.screen.width,clientWidht:document.documentElement.clientWidth};I().event("toolbar_"+e,g.SHOW_SCROLL_BUTTON,void 0,void 0,JSON.stringify(t))},CTt=()=>{I().event(m.TOOLBAR_SETTING,g.CLICK_CLEANUP_BACKUP_BUTTON)},RTt=()=>{I().event(m.TOOLBAR_SETTING,g.CLICK_CLEANUP_CACHE_BUTTON)},ATt=async e=>{const t={totalStorage:0,availableStorage:0,currentBackupSize:e!==null?es(e):null};try{const o=await e5();if(o===null)h("ga.ts").error("gaCleanupBackupStart error: failed to get main disk usage");else{const{sizeInBytes:r,usedInBytes:n}=o;t.totalStorage=es(r),t.availableStorage=es(r-n)}I().event(m.TOOLBAR_SETTING,g.CLEANUP_BACKUP_START,void 0,void 0,JSON.stringify(t))}catch(o){h("ga.ts").error("gaCleanupBackupStart error: "+P(o))}},yTt=async(e,t,o)=>{const r={totalStorage:0,availableStorage:0,currentBackupSize:t!==null?es(t):null,deletedBackupSize:o!==null?es(o):null};try{const n=await e5();if(n===null)h("ga.ts").error("gaCleanupBackupResult error: failed to get main disk usage");else{const{sizeInBytes:a,usedInBytes:i}=n;r.totalStorage=es(a),r.availableStorage=es(a-i)}I().event(m.TOOLBAR_SETTING,e?g.CLEANUP_BACKUP_SUCCESS:g.CLEANUP_BACKUP_FAIL,void 0,void 0,JSON.stringify(r))}catch(n){h("ga.ts").error("gaCleanupBackupResult error: "+P(n))}},IUe=e=>{I().event(m.KEY_EDIT,g.ENTER_TEXTBOX_EDIT_MODE,void 0,void 0,JSON.stringify({numSelectedElements:e}))},vTt=async e=>{const t={currentCacheSize:e!==null?es(e):null};try{I().event(m.TOOLBAR_SETTING,g.CLEANUP_CACHE_START,void 0,void 0,JSON.stringify(t))}catch(o){h("ga.ts").error("gaCleanupCacheStart error: "+P(o))}},wTt=async(e,t,o)=>{const r={currentCacheSize:t!==null?es(t):null,deletedCacheSize:o!==null?es(o):null};try{I().event(m.TOOLBAR_SETTING,e?g.CLEANUP_CACHE_SUCCESS:g.CLEANUP_CACHE_FAIL,void 0,void 0,JSON.stringify(r))}catch(n){h("ga.ts").error("gaCleanupCacheResult error: "+P(n))}},NTt=e=>{I().event(m.TOOLBAR_SETTING,g.CLICK_UPDATEPOLICY,e)},PTt=e=>{const{payload:t}=e;I().event(m.SCREENSHOT,e.action,void 0,void 0,JSON.stringify(t))},bTt=()=>{I().event(m.GEN_PROMPT_CHARACTER,g.CLICK_SUGGEST_PROMPT)},LTt=e=>{I().event(m.GEN_IMAGE_CHARACTER,g.CLICK_REGEN_CHARACTER,void 0,void 0,JSON.stringify({regenCnt:e}))},MTt=e=>{I().event(m.GEN_PROMPT_CHARACTER,g.CLICK_REGEN_CHARACTER,void 0,void 0,JSON.stringify({regenCnt:e}))},DTt=e=>{I().event(m.GEN_IMAGE_CHARACTER,g.REGEN_LIPSYNC,void 0,void 0,JSON.stringify({regenCnt:e}))},kTt=e=>{const t={pageName:ZUe(e)};I().event(m.MAKE_MY_CHARACTER,g.CLICK_PREV,void 0,void 0,JSON.stringify(t))},TUe=()=>{I().event(m.CLIP_SHORTCUT,g.DISPLAY)},FTt=e=>{I().event(m.CLIP_SHORTCUT,g.MOVE,e.toString())},SUe=()=>{I().event(m.KEY_FILE,g.CLOSE_WINDOW)},UTt=(e,t)=>{const o=e==="click"?g.CLICK:g.DISPLAY,r={os:t};I().event(m.BANNER,o,"legacyos",void 0,JSON.stringify(r))},qz=(e,t)=>{const o={projectId:e,type:t};I().event(m.VCLOUD,g.SESSION_ACQUIRE_REQUEST,void 0,void 0,JSON.stringify(o))},VTt=(e,t,o)=>{const r={totalCloudStorage:e,usedCloudStorage:t,currentProjectSize:o};I().event(m.VCLOUD,g.CLICK_VCLOUD_CAPACITY,void 0,void 0,JSON.stringify(r))},GTt=e=>{const t=Lt().getCloudProjects().length,o={vcloudProjectsCount:t,clickOrigin:e};I().event(m.VCLOUD,g.CLICK_VCLOUD_LIST,void 0,void 0,JSON.stringify(o))},WTt=e=>{const t={projectId:e};I().event(m.VCLOUD,g.CLICK_VCLOUD_MIGRATE,void 0,void 0,JSON.stringify(t))},OUe=(e,t)=>{const o={projectId:e.projectId,target:t};I().event(m.VCLOUD,g.MIGRATE_START,void 0,void 0,JSON.stringify(o))},fk=(e,t,o,r)=>{const n={projectId:e.projectId,version:e.version,created:e.created,lastModified:e.lastModified,totalSize:e.totalSize,uploadCount:e.uploadCount,downloadCount:e.downloadCount,snapshotId:e.snapshotId,sessionId:e.sessionId,target:t,elapsedTimeSec:ue(o,2)};I().event(m.VCLOUD,r==="success"?g.MIGRATE_SUCCESS:g.MIGRATE_FAILED,void 0,void 0,JSON.stringify(n))},CUe=({projectId:e,uploadType:t,filemetrics:o,sourceProjectId:r})=>{const n={projectId:e,uploadType:t,totalSnapshotSize:o.snapshotSize,totalSourceSize:o.totalSourceFileSize,totalMediaSize:o.totalMediaFileSize,totalFileCounts:o.totalFileCounts,fileCountsUnder1MB:o.fileCountsUnder1MB,fileCountsUnder10MB:o.fileCountsUnder10MB,fileCountsUnder100MB:o.fileCountsUnder100MB,fileCountsUnder1GB:o.fileCountsUnder1GB,fileCountsUnder10GB:o.fileCountsUnder10GB,fileCountsOver10GB:o.fileCountsOver10GB,sourceProjectId:r};I().event(m.VCLOUD,g.UPLOAD_START,void 0,void 0,JSON.stringify(n))},HTt=e=>{const t={isChanged:e?"true":"false"};I().event(m.VCLOUD,g.UPLOAD_TITLE,void 0,void 0,JSON.stringify(t))},jTt=e=>{const t={type:e};I().event(m.VCLOUD,g.CANCEL_CONFIRM,void 0,void 0,JSON.stringify(t))},gk=(e,t)=>{const o={type:e,inProgressFileCount:t};I().event(m.VCLOUD,g.BACKGROUND_UPLOAD_CONFIRM,void 0,void 0,JSON.stringify(o))},fC=({projectId:e,uploadType:t,filemetrics:o,elapsedTimeSec:r,result:n,sourceProjectId:a})=>{const i={projectId:e,uploadType:t,totalSnapshotSize:o.snapshotSize,totalSourceSize:o.totalSourceFileSize,totalMediaSize:o.totalMediaFileSize,totalFileCounts:o.totalFileCounts,fileCountsUnder1MB:o.fileCountsUnder1MB,fileCountsUnder10MB:o.fileCountsUnder10MB,fileCountsUnder100MB:o.fileCountsUnder100MB,fileCountsUnder1GB:o.fileCountsUnder1GB,fileCountsUnder10GB:o.fileCountsUnder10GB,fileCountsOver10GB:o.fileCountsOver10GB,elapsedTimeSec:ue(r,2),sourceProjectId:a},s=n==="success"?g.UPLOAD_SUCCESS:g.UPLOAD_FAILED;I().event(m.VCLOUD,s,void 0,void 0,JSON.stringify(i))},zTt=()=>{I().event(m.VCLOUD,g.CLICK_VCLOUD_DOWNLOAD,void 0,void 0,void 0)},RUe=e=>{const t={projectId:e.projectId,created:e.created,lastModified:e.lastModified,totalSize:e.totalSize,uploadCount:e.uploadCount,downloadCount:e.downloadCount,version:e.version};I().event(m.VCLOUD,g.DOWNLOAD_START,void 0,void 0,JSON.stringify(t))},_k=(e,t,o)=>{const r={elapsedTimeSec:ue(e,2),ext:t,location:o};I().event(m.VCLOUD,g.DOWNLOAD_CLOUD_FILE,void 0,void 0,JSON.stringify(r))},AUe=e=>{const t={projectId:e.projectId,created:e.created,lastModified:e.lastModified,totalSize:e.totalSize,uploadCount:e.uploadCount,downloadCount:e.downloadCount};I().event(m.VCLOUD,g.RENAME_PROJECT,void 0,void 0,JSON.stringify(t))},yUe=e=>{const t={projectId:e.projectId,createdAt:e.createdAt,lastModified:e.lastModifiedAt,size:e.size};I().event(m.BROWSER_PROJECT,g.RENAME_PROJECT,void 0,void 0,JSON.stringify(t))},vUe=e=>{const t={projectId:e.projectId,created:e.created,lastModified:e.lastModified,totalSize:e.totalSize,uploadCount:e.uploadCount,downloadCount:e.downloadCount};I().event(m.VCLOUD,g.DELETE_PROJECT_DONE,void 0,void 0,JSON.stringify(t))},YTt=(e,t)=>{const o=t==="confirm"?g.CLICK_DELETE_CONFIRM:g.CLICK_DELETE,r={projectId:e};I().event(m.VCLOUD,o,void 0,void 0,JSON.stringify(r))},BTt=e=>{const t={projectId:e};I().event(m.VCLOUD,g.CLICK_DELETE_CANCEL,void 0,void 0,JSON.stringify(t))},KTt=(e,t)=>{const o=t==="confirm"?g.CLICK_BULK_DELETE_CONFIRM:g.CLICK_BULK_DELETE;I().event(m.VCLOUD,o,void 0,void 0,JSON.stringify({count:e}))}
1244,XTt=e=>{I().event(m.VCLOUD,g.CLICK_BULK_DELETE_CANCEL,void 0,void 0,JSON.stringify({count:e}))},JTt=(e,t)=>{I().event(m.VCLOUD,g.BULK_DELETE_PROJECT_DONE,void 0,void 0,JSON.stringify({succeededCount:e,failedCount:t}))},qTt=e=>{const t={type:e};I().event(m.VCLOUD,g.CANCEL,void 0,void 0,JSON.stringify(t))},QTt=(e,t,o)=>{const r={totalCloudStorage:e,usedCloudStorage:t,planStatus:o};I().event(m.VCLOUD,g.DISPLAY_ALERT_DELETE_SCHEDULED,void 0,void 0,JSON.stringify(r))},ZTt=e=>{const t={projectId:e};I().event(m.VCLOUD,g.CLICK_OPEN_DOWNLOADED_PROJECT,void 0,void 0,JSON.stringify(t))},$Tt=e=>{const t={projectId:e};I().event(m.VCLOUD,g.CLICK_GOTO_DOWNLOAD_FOLDER,void 0,void 0,JSON.stringify(t))},CP=(e,t,o)=>{const r={projectId:e,snapshotSize:t.snapshotSize,totalSourceSize:t.totalSourceFileSize,totalMediaSize:t.totalMediaFileSize,totalFileCounts:t.totalFileCounts,fileCountsUnder1MB:t.fileCountsUnder1MB,fileCountsUnder10MB:t.fileCountsUnder10MB,fileCountsUnder100MB:t.fileCountsUnder100MB,fileCountsUnder1GB:t.fileCountsUnder1GB,fileCountsUnder10GB:t.fileCountsUnder10GB,fileCountsOver10GB:t.fileCountsOver10GB,elapsedTimeSec:ue(o,2)};I().event(m.VCLOUD,g.DOWNLOAD_SUCCESS,void 0,void 0,JSON.stringify(r))},RP=(e,t)=>
1244{const o={projectId:e,elapsedTimeSec:ue(t,2)};I().event(m.VCLOUD,g.DOWNLOAD_FAILED,void 0,void 0,JSON.stringify(o))},wUe=e=>{const t={planType:e};I().event(m.VCLOUD,g.CLICK_UPGRADE,void 0,void 0,JSON.stringify(t))},NUe=(e,t,o,r)=>{const n={projectId:e,ext:t,elapsedTimeSec:ue(o,2),size:r};I().event(m.VCLOUD,g.UPLOAD_CLOUD_FILE,void 0,void 0,JSON.stringify(n))},PUe=(e,t,o)=>{const r={size:e,ext:t,elapsedTimeSec:ue(o,2)};I().event(m.VCLOUD,g.FETCH_CLOUD_FILE,void 0,void 0,JSON.stringify(r))},bUe=e=>{I().event(m.VCLOUD,g.CLOUD_EMPTY_UPLOAD_BLOCKED,void 0,void 0,JSON.stringify({mediaId:e}))},LUe=(e,t,o)=>{I().event(m.VCLOUD,g.CLOUD_EMPTY_BLOB_HANDLED,void 0,void 0,JSON.stringify({mediaId:e,type:t,recovered:o}))},eSt=(e,t)=>{I().event(m.EXPORT,g.NEW_EXPORT_RESULT,void 0,void 0,JSON.stringify({newExportResult:e,exportType:t}))},tSt=(e,t,o,r)=>{I().event(m.EXPORT,g.NEW_EXPORT_START,void 0,void 0,JSON.stringify({exportEnv:e,exportType:t,range:o,audioEncodeMode:r}))},oSt=async(e,t,o,r,n,a,i)=>{const s=await pt().getSystemInfo(),x=s?{cpu:s.summary.cpu,cpuSpeedInGhz:s.cpu.speedInGHz,memTotal:ue(WL(s.mem.totalInBytes),2),memUsed:ue(WL(s.mem.usedInBytes),2),memUsage:s.mem.totalInBytes===0?0:ue(s.mem.usedInBytes*100/s.mem.totalInBytes,2),gpu:s.gpu.gpus.length===0?{model:"none",vramInMb:0}:s.gpu.gpus[0]}:void 0,c={exportId:e,videoResolution:t.width+"x"+t.height,quality:o,outputSizeMB:ue(r,2),totalDurationSec:ue(n,2),elapsedTimeSec:ue(a,2),finishedPercentage:i,sys:x};I().event(m.EXPORT,i===100?g.NEW_EXPORT_PERFORMANCE:g.NEW_EXPORT_PERFORMANCE_PROGRESS,void 0,void 0,JSON.stringify(c))},MUe=()=>{I().event(m.PROJECT_SAVE,g.PROJECT_SAVE_TIMEOUT_POPUP_SHOW)},DUe=e=>{const t={result:e};I().event(m.PROJECT_SAVE,g.PROJECT_SAVE_TIMEOUT_POPUP_RESULT,void 0,void 0,JSON.stringify(t))},rSt=e=>{I().event(m.EXPORT,g.MINIMIZE,void 0,void 0,JSON.stringify({minimizeCnt:e}))},nSt=e=>{I().event(m.EXPORT,g.EXPAND,void 0,void 0,JSON.stringify({expandCnt:e}))},aSt=e=>{I().event(m.EXPORT,g.EXPORT_DISK_WRITE,void 0,void 0,JSON.stringify(e))},iSt=e=>{I().event(m.EXPORT,g.NEW_EXPORT_ERROR,void 0,void 0,JSON.stringify({errorType:e.type}))},sSt=e=>{const t=e.length===1?"single":"multi",o={selectType:t};I().event(m.ASSET_CURSOR,g.CLICK_TOGGLE_BGM_FADE_IN_OUT,void 0,void 0,JSON.stringify(o))},xSt=(e,t,o)=>{const r=o.length===1?"single":"multi",n=eY(r,o),a=AP(r,o),i={selectType:r,toggled:t,fadeType:e,...a};I().event(m.ASSET_CURSOR,g.TOGGLE_BGM_FADE_IN_OUT,n,void 0,JSON.stringify(i))},kUe=e=>{I().event(m.INSERT_FREE_SOURCE,g.INCOMPATIBLE_VIDEO_CODEC,void 0,void 0,JSON.stringify(e))},FUe=e=>{I().event(m.IMPORT,g.INCOMPATIBLE_AUDIO_CODEC,void 0,void 0,JSON.stringify(e))},Qz=e=>{I().event(m.IMPORT,g.INCOMPATIBLE_VIDEO_CODEC,void 0,void 0,JSON.stringify(e))},UUe=e=>{I().event(m.IMPORT,g.INCOMPATIBLE_CONTAINER,void 0,void 0,JSON.stringify(e))},VUe=async(e,t,o,r)=>{try{const n=e[0]??"unknown",a=e[1]??"unknown",i=e[2]??"unknown",s=i==="unknown",x=r??"unknown",{width:c,height:l}=t?.size??{width:0,height:0},d=(()=>{const S=[{width:7680,height:4320,name:"8K"},{width:5120,height:2880,name:"5K"},{width:4096,height:2160,name:"DCI 4K"},{width:3840,height:2160,name:"4K"},{width:3440,height:1440,name:"UWQHD"},{width:3200,height:1800,name:"WQHD+"},{width:2560,height:1440,name:"QHD"},{width:2560,height:1080,name:"UWHD"},{width:1920,height:1080,name:"FHD"},{width:1280,height:720,name:"HD"},{width:960,height:540,name:"qHD"}],R=100,y=Math.max(c,l),v=Math.min(c,l);for(const w of S)if(Math.abs(y-w.width)<=R&&Math.abs(v-w.height)<=R)return w.name;return"unknown"})(),u=t?.codec??"unknown",p=t?.frameRate??0,f=P2(i),E=o?.insertionTarget,T=o?.method,O=o?.from;I().event(m.UPLOAD,g.VIDEO_META,e.join(","),void 0,JSON.stringify({chromaSubsampling:n,colorRange:a,colorSpace:i,isHDR:f,isEmptyColorSpace:s,width:c,height:l,approximatedResolution:d,codec:u,frameRate:p,keyFrameInterval:x,insertionTargetType:E,insertionOrigin:T,insertionFrom:O}))}catch(n){h("ga.ts").error("gaVideoMeta error: "+P(n))}},GUe=async e=>{const t={planType:e.planType,usageType:e.usageType,afterRatio:e.afterRatio,beforeRatio:e.beforeRatio,quantity:e.quantity};I().event(m.PAYMENT,g.USAGE_ERASER,void 0,void 0,JSON.stringify(t))},WUe=e=>{const t=Object.entries(Dh).find(([,o])=>Object.values(o).includes(e))?.[0];if(!t){h("ga.ts").error("gaTypeformDisplay error: invalid typeformId "+e);return}I().event(m.TYPEFORM,g.DISPLAY,void 0,void 0,JSON.stringify({surveyType:t}))},Zz=e=>{const t=Object.entries(Dh).find(([,o])=>Object.values(o).includes(e))?.[0];if(!t){h("ga.ts").error("gaTypeformClose error: invalid typeformId "+e);return}I().event(m.TYPEFORM,g.CLOSE,void 0,void 0,JSON.stringify({surveyType:t}))},$z=e=>{const t=Object.entries(Dh).find(([,o])=>Object.values(o).includes(e))?.[0];if(!t){h("ga.ts").error("gaTypeformSubmit error: invalid typeformId "+e);return}I().event(m.TYPEFORM,g.SUBMIT,void 0,void 0,JSON.stringify({surveyType:t}))},HUe=e=>{const t={knownSource:e.knownSource,uploadOnSocialMedia:e.uploadOnSocialMedia,uploadSocialMedia:e.uploadSocialMedia||"NULL",sourceCiteRadioOption:e.sourceCiteRadioOption||"NULL"};I().event(m.VREWMARK,g.SUBMIT,void 0,void 0,JSON.stringify(t))},jUe=()=>{I().event(m.ONBOARDING_TOUR_GUIDE,g.START,void 0,void 0,JSON.stringify({onboardingType:"tour",onboardingVersion:2}))},zUe=()=>{I().event(m.ONBOARDING_TOUR_GUIDE,g.DONE,void 0,void 0,JSON.stringify({onboardingType:"tour",onboardingVersion:2}))},cSt=(e,t)=>
1244{const o=t.length===1?"single":"multi",r=eY(o,t),n=AP(o,t),a={selectType:o,toggled:e,...n};I().event(m.ASSET_CURSOR,g.TOGGLE_BGM_LOOP,r,void 0,JSON.stringify(a))},lSt=(e,t)=>{const o=t.length===1?"single":"multi",r=AP(o,t),n={selectType:o,endBehavior:e,...r};I().event(m.ASSET_CURSOR,g.CHANGE_ASSET_END_BEHAVIOR,e,void 0,JSON.stringify(n))},eY=(e,t)=>e==="single"||t.slice(1).every(({toggled:o})=>o===t[0].toggled)?t[0].toggled.toString():"combi",AP=(e,t)=>{if(e==="single"){const a=t.at(0);return{assetType:a?Dt(a.assetType):"unknown",assetSource:a?.source??"unknown"}}const o=cn(t.map(a=>Dt(a.assetType))),r=t.reduce((a,i)=>{const s=i.source??"unknown",x=a.get(s);return x===void 0?a.set(s,1):a.set(s,x+1),a},new Map),n=Array.from(r.entries()).map(([a,i])=>a+"("+i+")").join("/");return{...o,assetSource:n}},dSt=e=>eo(e.mediaId)?.sourceOrigin,YUe=e=>{I().event(m.INSERT_VIDEO,g.ASSET_SIZE_EXCEEDED,void 0,void 0,JSON.stringify({fileSize:e}))},uSt=e=>{I().event(m.VREW_SURVEY,g.DISPLAY,void 0,void 0,JSON.stringify({surveyType:e}))},pSt=(e,t,o)=>{I().event(m.VREW_SURVEY,g.CLOSE,void 0,void 0,JSON.stringify({surveyType:e,leaveQuestionId:t,reason:o}))},fSt=e=>{I().event(m.VREW_SURVEY,g.SUBMIT,void 0,void 0,JSON.stringify({surveyType:e}))},gSt=()=>{I().event(m.TOOLBAR_EDIT,g.CLICK_OPEN_LINEBREAK_PANEL,void 0,void 0,void 0)},Ek=(e,t)=>{const o={isOverdubAvailable:t};I().event(e,g.CLICK_OVERDUB,void 0,void 0,JSON.stringify(o))},_St=()=>{I().event(m.OVERDUB,g.TRY_EDIT,void 0,void 0)},BUe=(e,t,o,r,n)=>{const a={numPreviousWords:e,numPreviousCharacters:t,numChangedCharacters:o,isOverdubbed:r,audioLanguage:n};I().event(m.OVERDUB,g.EDIT,void 0,void 0,JSON.stringify(a))},ESt=()=>{I().event(m.OVERDUB,g.EDIT_CANCEL,void 0,void 0)},KUe=(e,t,o,r,n,a)=>{const i={numPreviousWords:e,numPreviousCharacters:t,numChangedCharacters:o,isOverdubbed:r,elapsedSec:n,overdubTrialRemaining:a};I().event(m.OVERDUB,g.EDIT_SUCCESS,void 0,void 0,JSON.stringify(i))},XUe=(e,t,o,r,n)=>{const a={numPreviousWords:e,numPreviousCharacters:t,numChangedCharacters:o,isOverdubbed:r,audioLanguage:n};I().event(m.OVERDUB,g.EDIT_FAILED,void 0,void 0,JSON.stringify(a))},mSt=()=>{I().event(m.OVERDUB,g.ROLLBACK,void 0,void 0)},gC=(e,t)=>{const o={isSTTWords:e,numSources:t};I().event(m.OVERDUB,g.TOAST_OPEN,void 0,void 0,JSON.stringify(o))},hSt=(e,t,o,r,n,a)=>{const i=Yo().sttLinebreakOptions;I().event(m.EDIT_CLIP,g.CLIENT_LINEBREAK_DONE,void 0,void 0,JSON.stringify({lineBreakerMaxLineLength:e.maxLineLength,lineBreakerMode:yA(e.mode),language:e.language,importRange:e.importRange,videoRatio:t,avgClipLineLength:o,numUsedAssets:r,numAppliedClips:n,sttMaxLineLength:i?.maxLineLength,sttLinebreakMode:yA(i?.mode),projectId:se().getProjectId(),triggerSource:a}))},ISt=(e,t)=>{I().event(m.EDIT_CLIP,g.CLIENT_LINEBREAK_INVALID,void 0,void 0,JSON.stringify({error:e,triggerSource:t}))},TSt=()=>{I().event(m.EDIT_CLIP,g.CLICK_CONFIRM_LINEBREAK,void 0,void 0,void 0)},SSt=e=>{I().event(m.TOOLBAR_FILE,g.CLICK_THUMBNAIL_GENERATOR,void 0,void 0,JSON.stringify({videoRatio:e}))},OSt=(e,t)=>{I().event(m.THUMBNAIL_GENERATOR,g.GENERATE_DRAFT_CLICK,void 0,void 0,JSON.stringify({entry:e,thumbnailGenRatio:t}))},CSt=()=>{I().event(m.THUMBNAIL_GENERATOR,g.GENERATE_DRAFT_CANCEL)},RSt=e=>{I().event(m.THUMBNAIL_GENERATOR,g.GENERATE_DRAFT_CONFIRM,void 0,void 0,JSON.stringify({thumbnailGenRatio:e}))},ASt=()=>{I().event(m.THUMBNAIL_GENERATOR,g.GENERATE_DRAFT_NO)},ySt=(e,t)=>{I().event(m.THUMBNAIL_GENERATOR,g.GENERATE_DRAFT_DONE,void 0,void 0,JSON.stringify({elapsedSec:e,thumbnailGenRatio:t}))},vSt=()=>{I().event(m.THUMBNAIL_GENERATOR,g.GENERATE_PHARASE_CLICK)},wSt=()=>{I().event(m.THUMBNAIL_GENERATOR,g.GENERATE_MORE_PHRASE_CLICK)},NSt=e=>{I().event(m.THUMBNAIL_GENERATOR,g.GENERATE_IMAGE,void 0,void 0,JSON.stringify({style:e}))},PSt=()=>{I().event(m.THUMBNAIL_GENERATOR,g.UPLOAD_USER_BACKGROUND_IMAGE)},bSt=()=>{I().event(m.THUMBNAIL_GENERATOR,g.SEARCH_STOCK_BACKGROUND_IMAGE)},LSt=e=>{I().event(m.THUMBNAIL_GENERATOR,g.SET_BACKGROUND_IMAGE,void 0,void 0,JSON.stringify({imageType:e}))},MSt=()=>{I().event(m.THUMBNAIL_GENERATOR,g.INSERT_TEXT_BOX)},DSt=()=>{I().event(m.THUMBNAIL_GENERATOR,g.UPLOAD_USER_STICKER)},kSt=()=>{I().event(m.THUMBNAIL_GENERATOR,g.SEARCH_STICKER)},FSt=e=>{I().event(m.THUMBNAIL_GENERATOR,g.INSERT_STICKER,void 0,void 0,JSON.stringify({imageType:e}))},USt=(e,t)=>
1244{I().event(m.THUMBNAIL_GENERATOR,g.THUMBNAIL_DOWNLOAD,void 0,void 0,JSON.stringify({backgroundImageType:e,thumbnailGenRatio:t}))},VSt=(e,t,o,r)=>{I().event(m.THUMBNAIL_GENERATOR,g.CLOSE,void 0,void 0,JSON.stringify({downloadCount:e,generateDraftCount:t,phraseCount:o,generateImageCount:r}))},GSt=e=>{I().event(m.THUMBNAIL_GENERATOR,g.SUMMARY_FAILED,void 0,void 0,JSON.stringify({captionLength:e}))},WSt=e=>{const t=window.innerHeight,o=window.innerHeight,r={trigger:e,windowWidth:t,windowHeight:o};I().event(m.FEATURE_SEARCH,g.OPEN_EVENT,void 0,void 0,JSON.stringify(r))},HSt=(e,t,o,r,n,a,i,s)=>{const x={type:e,trigger:t,featureKey:o,featureName:r,featurePath:n,confirmedItemIdx:a,elapsedTime:i};I().event(m.FEATURE_SEARCH,g.CONFIRM,void 0,void 0,JSON.stringify(x)),I().event(m.ANONYMOUS_EVENT,g.LOG_FEATURE_SEARCH_INPUT,void 0,void 0,JSON.stringify({keyword:s,type:"confirmed",featureKey:o,confirmedItemIdx:a,elapsedTime:i}))},jSt=(e,t)=>{const o={trigger:e};I().event(m.FEATURE_SEARCH,g.CANCEL,void 0,void 0,JSON.stringify(o)),t&&I().event(m.ANONYMOUS_EVENT,g.LOG_FEATURE_SEARCH_INPUT,void 0,void 0,JSON.stringify({keyword:t,type:"cancelled"}))},zSt=e=>{const t={keyword:e,type:"searching"};I().event(m.ANONYMOUS_EVENT,g.LOG_FEATURE_SEARCH_INPUT,void 0,void 0,JSON.stringify(t))},YSt=e=>{I().event(m.FEATURE_SEARCH,g.CLICK_SEARCH,void 0,void 0,void 0),I().event(m.ANONYMOUS_EVENT,g.LOG_FEATURE_SEARCH_INPUT,void 0,void 0,JSON.stringify({keyword:e,type:"open_search_panel"}))},BSt=(e,t)=>{I().event(m.STARTUP_OPTION,g.CHANGE_STARTUP_OPTION,void 0,void 0,JSON.stringify({option:e,trigger:t}))},KSt=()=>{I().event(m.STARTUP_OPTION,g.DISPLAY)},XSt=(e,t)=>{I().event(m.PROJECT_SAVE_LOCATION,g.CHANGE_PROJECT_SAVE_LOCATION,void 0,void 0,JSON.stringify({option:e,trigger:t}))},JUe=(e,t)=>{const o=e===e0.AUTO||e===e0.DEFAULT?e+"("+Math.round(t)+")":Math.round(t).toString(),r=JSON.stringify({frameRateOption:o});I().event(m.EXPORT,g.EXPORT_FRAME_RATE,void 0,void 0,r)},JSt=e=>{I().event(m.EXPERIMENT,g.OPEN_EXPERIMENT_MODAL,void 0,void 0,JSON.stringify({info:e}))},qSt=e=>{I().event(m.EXPERIMENT,g.GO_TO_EXPERIMENT,void 0,void 0,JSON.stringify({key:e}))},QSt=e=>{I().event(m.VOCAL_DICTIONARY,e?g.OPEN_PANEL:g.CLOSE_PANEL,void 0,void 0,void 0)},qUe=e=>{I().event(m.AI_VOICE,g.TOGGLE_WORD_PRONUNCIATION,void 0,void 0,JSON.stringify({type:e?"on":"off"}))},QUe=e=>{I().event(m.VOCAL_DICTIONARY,g.CLICK_TOGGLE_VOCAL_DICTIONARY_USE,void 0,void 0,JSON.stringify({isOn:e}))},ZUe=e=>{switch(e){case Qs.TEXT_REQUEST:return"textRequest";case Qs.IMAGE_REQUEST:return"setCharacter";case Qs.TEXT_DRAFT_LOADING:case Qs.IMAGE_DRAFT_LOADING:return"genCharacter";case Qs.TEXT_DRAFT_RESULT:case Qs.IMAGE_DRAFT_RESULT:return"draftResult";case Qs.TEXT_LIP_SYNC_LOADING:case Qs.IMAGE_LIP_SYNC_LOADING:return"genLipSync";case Qs.TEXT_FINAL_RESULT:case Qs.IMAGE_FINAL_RESULT:return"finalResult";default:return"methodSelect"}},ZSt=()=>{I().event(m.TTV_MODAL,g.SHOW_TTV_VIDEO_STYLE_TOOLTIP)},$St=e=>{I().event(m.TTV_MODAL,g.TTV_SCRIPT_PROMPT_EXAMPLE,void 0,void 0,JSON.stringify({index:e,ttvVersion:to()}))},eOt=e=>{const t={};for(const n of e.paragraphs)for(const[a,,,,,i]of n)i===Z.AUDIO_EVENT&&(t[a]=(t[a]||0)+1);const o=Object.keys(t);if(o.length===0)return;const r=Object.values(t).reduce((n,a)=>n+a,0);I().event(m.AUDIO_EVENT_DETECTED,g.DONE,void 0,void 0,JSON.stringify({totalCount:r,audioEventCounts:JSON.stringify(o)}))},tOt=()=>{I().event(m.TTV_MODAL,g.TTV_PREV_VERSION_STYLE_GUIDE)},oOt=e=>{Array.from(e.entries()).map(([o,r])=>({type:o,total:r.hit+r.miss,hit:r.hit,miss:r.miss})).forEach(o=>{I().event(m.VCLOUD,g.EXPORT_CACHE,void 0,void 0,JSON.stringify({type:o.type,total:o.total,hit:o.hit,miss:o.miss}))})},$Ue=e=>{Array.from(e.entries()).map(([o,r])=>({type:o,total:r.hit+r.miss,hit:r.hit,miss:r.miss})).forEach(o=>{I().event(m.VCLOUD,g.LOAD_CACHE,void 0,void 0,JSON.stringify({type:o.type,total:o.total,hit:o.hit,miss:o.miss}))})},e1e=e=>{I().event(m.PROXY_VIDEO,g.TOGGLE_ON,void 0,void 0,JSON.stringify({method:e}))},t1e=(e,t)=>{I().event(m.PROXY_VIDEO,g.CLICK,void 0,void 0,JSON.stringify({status:e,location:t}))},rOt=(e,t)=>{I().event(m.PROXY_VIDEO,g.CONVERT_START,void 0,void 0,JSON.stringify({width:e.width,height:e.height,bitrate:Math.round(t)}))},nOt=()=>{I().event(m.PROXY_VIDEO,g.CONVERT_CANCEL,void 0,void 0)},aOt=e=>{I().event(m.PROXY_VIDEO,g.CLEAR,void 0,void 0,JSON.stringify({deletedBytes:e}))},iOt=e=>{I().event(m.VIDEO_GENERATE,g.GEN_VIDEO_START,void 0,void 0,JSON.stringify(e))},sOt=(e,t)=>{I().event(m.VIDEO_GENERATE,"error"in t?g.GEN_VIDEO_ERROR:g.GEN_VIDEO_DONE,void 0,void 0,JSON.stringify({...e,...t}))},xOt=()=>{I().event(m.VIDEO_GENERATE,g.GEN_VIDEO_CANCEL,void 0,void 0)},cOt=(e,t,o,r,n)=>
1244{I().event(m.VIDEO_GENERATE,g.INSERT_GEN_VIDEO,void 0,void 0,JSON.stringify({style:e,videoRatio:t,engine:o,useStartFrame:r,isArchiveOn:n}))},lOt=e=>{I().event(e,g.DOWNLOAD_GEN_VIDEO)},dOt=e=>{const t=se().getProjectId();if(t===void 0)return;Ra(g.DOWNLOAD_GEN_VIDEO_DONE,t);const o=iu[g.DOWNLOAD_GEN_VIDEO_DONE+t];I().event(e,g.DOWNLOAD_GEN_VIDEO_DONE,void 0,void 0,JSON.stringify({downloadGenVideoCnt:o}))},uOt=(e,t,o)=>{I().event(m.VIDEO_GENERATE,g.ADD_GENVIDEO_TO_MY_ASSET,void 0,void 0,JSON.stringify({style:e,videoRatio:t,engine:o}))},pOt=(e,t,o,r)=>{I().event(m.IMAGE_GENERATE_MODAL,r?g.ADD_CHAT_IMAGE_TO_MY_ASSET:g.ADD_GENIMAGE_TO_MY_ASSET,void 0,void 0,JSON.stringify({style:e,imageRatio:t,engine:o}))},fOt=(e,t)=>{I().event(m.VIDEO_GENERATE,g.CHANGE_GENVIDEO_ENGINE,void 0,void 0,JSON.stringify({trigger:e,engine:t}))},oS=e=>e==="image"?m.IMAGE_GENERATE_MODAL:m.VIDEO_GENERATE,gOt=e=>{I().event(oS(e),g.DELETE_RESULT)},_Ot=e=>{I().event(oS(e),g.OPEN_GENERATED_RESULT_PREVIEW)},EOt=e=>{I().event(m.IMAGE_GENERATE_MODAL,g.ATTACH_REFERENCE_IMAGE,void 0,void 0,JSON.stringify(e))},mOt=e=>{I().event(m.VIDEO_GENERATE,g.ATTACH_START_IMAGE,void 0,void 0,JSON.stringify(e))},hOt=()=>{I().event(m.IMAGE_GENERATE_MODAL,g.REMOVE_REFERENCE_IMAGE)},IOt=()=>{I().event(m.VIDEO_GENERATE,g.REMOVE_START_IMAGE)},TOt=(e,t,o,r)=>{I().event(oS(e),g.MODEL_AUTO_SWITCHED,void 0,void 0,JSON.stringify({fromModel:t,toModel:o,capability:r}))},SOt=(e,t,o)=>{I().event(oS(e),g.CLICK_CANCEL_MODEL_AUTO_SWITCHED,void 0,void 0,JSON.stringify({fromModel:t,toModel:o}))},OOt=(e,t)=>{I().event(m.IMAGE_GENERATE_MODAL,g.CLICK_CHANGE_TO_CONSISTENCY_MODEL,void 0,void 0,JSON.stringify({fromModel:e,toModel:t}))},COt=e=>{I().event(m.VIDEO_GENERATE,g.CHANGE_GENVIDEO_OPTION,void 0,void 0,JSON.stringify(e))},ROt=e=>{I().event(m.TTV_MODAL,g.CLICK_NEXT,void 0,void 0,JSON.stringify({currentStage:e,ttvVersion:to()}))},AOt=e=>{I().event(m.TTV_MODAL,g.PROCEED_NEXT,void 0,void 0,JSON.stringify({currentStage:e,ttvVersion:to()}))},yOt=(e,t,o,r,n,a,i,s,x,c,l,d,u,p)=>{I().event(m.TTV_MODAL,g.START_GENERATION,void 0,void 0,JSON.stringify(zz(e,t,o,r,n,a,i,s,x,c,l,d,u,p)))},vOt=()=>{I().event(m.TTV_MODAL,g.DISPLAY,void 0,void 0,JSON.stringify({ttvVersion:to()}))},o1e=e=>{I().event(m.FFMPEG_DOWNLOAD_MODAL,g.DISPLAY,void 0,void 0,JSON.stringify({ffmpegDownloadType:e}))},r1e=e=>{I().event(m.FFMPEG_DOWNLOAD_MODAL,g.CLOSE,void 0,void 0,JSON.stringify({ffmpegDownloadType:e}))},n1e=e=>{I().event(m.FFMPEG_DOWNLOAD_MODAL,g.CONFIRM,void 0,void 0,JSON.stringify({ffmpegDownloadType:e}))},wOt=(e,t)=>{I().event(m.START_MODAL,g.CLICK,void 0,void 0,JSON.stringify({buttonType:e,location:t}))},NOt=()=>{I().event(m.START_NEW_PROJECT,g.CLICK_ASSET_TO_VIDEO)},POt=()=>{I().event(m.ATV,g.RELOAD_SESSION)},bOt=(e,t)=>{I().event(m.ATV,g.FILE_IMPORT_CLICK,void 0,void 0,JSON.stringify({stage:e,type:t}))},LOt=(e,t)=>{I().event(m.ATV,g.FILE_IMPORT_DONE,void 0,void 0,JSON.stringify({imageCount:e,videoCount:t}))},MOt=e=>{let t=0,o=0,r=0,n=0,a=0;for(const i of e)t++,i.reason===vp.TOO_LONG_VIDEO?o++:i.reason===vp.TOO_LARGE_VIDEO?r++:i.reason===vp.UNSUPPORTED_FORMAT?n++:i.reason===vp.LOAD_FAILED&&a++;I().event(m.ATV,g.FILE_IMPORT_FAILED,void 0,void 0,JSON.stringify({totalCount:t,tooLongVideoCount:o,tooLargeVideoCount:r,unsupportedFormatCount:n,loadFailedCount:a}))},DOt=(e,t,o)=>{I().event(m.ATV,g.FILE_UPLOAD_INFO,void 0,void 0,JSON.stringify({totalCount:e,singleCount:t,multipartCount:o}))},kOt=e=>{I().event(m.ATV,g.IMAGE_RESIZE_RESULT,void 0,void 0,JSON.stringify(e))},FOt=e=>{I().event(m.ATV,g.MOVE_TO_NEXT,void 0,void 0,JSON.stringify({nextStage:e}))},UOt=e=>{I().event(m.ATV,g.CLOSE,void 0,void 0,JSON.stringify({stage:e}))},VOt=()=>{I().event(m.ATV,g.OPEN_PROMPT_SUGGEST)},GOt=()=>{I().event(m.ATV,g.USE_PROMPT_SUGGEST)},WOt=()=>{I().event(m.ATV,g.REGENERATE_PROMPT)},HOt=(e,t,o,r,n,a,i,s)=>{I().event(m.ATV,g.START_GENERATION,void 0,void 0,JSON.stringify({imageCount:e,videoCount:t,totalCount:e+t,isPromptUsed:o,promptLength:r,isBGMOn:n?"O":"X",isTTSOn:a?"O":"X",isVideoSoundOn:i,captionPosition:s}))},jOt=(e,t,o,r)=>{const n=Object.fromEntries(Object.entries(e).filter(([,a])=>a!==void 0).map(([a,i])=>[a+"_duration",i]));I().event(m.ATV,g.DONE,void 0,void 0,JSON.stringify({...n,elapsedSec:t,assetCount:o,elapsedSecPerAsset:t/o,isTTSSuccess:r}))},zOt=(e,t,o)=>{I().event(m.ATV,g.FAILED,void 0,void 0,JSON.stringify({errorCode:e,imageCount:t,videoCount:o}))},YOt=e=>{I().event(m.NEW_WINDOW,g.CLICK,e)},cE=e=>{const t=be().getUserInfo()!==void 0,o=ls("overdub_onboarding_start_menu"),r=e===4?{isLoggedIn:t,abTestVariant:t?o:void 0,step:e}:{step:e};I().event(m.OVERDUB_ONBOARDING_TOUR_GUIDE,g.ACTION_DONE,void 0,void 0,JSON.stringify(r))},lE=e=>{const t={step:e};I().event(m.OVERDUB_ONBOARDING_TOUR_GUIDE,g.CLICK_NEXT_BUTTON,void 0,void 0,JSON.stringify(t))},dE=(e,t)=>{const o={step:e,auto:t};I().event(m.OVERDUB_ONBOARDING_TOUR_GUIDE,g.END_RUN,void 0,void 0,JSON.stringify(o))},BOt=()=>{I().event(m.OVERDUB_ONBOARDING_TOUR_GUIDE,g.START,void 0,void 0)},KOt=()=>{const e=ls("overdub_onboarding_start_menu"),t={abTestVariant:e};I().event(m.OVERDUB_ONBOARDING_TOUR_GUIDE,g.AB_TEST_SET,void 0,void 0,JSON.stringify(t))},a1e=e=>{I().event(m.OVERDUB_ONBOARDING_TOUR_GUIDE,e),e===g.FEATURE_ONBOARDING_MODAL_OPEN&&pP(g.BOOT_ENTER_OVERDUB_ONBOARDING_MODAL)},XOt=e=>{I().event(m.OVERDUB_ONBOARDING_TOUR_GUIDE,e)},JOt=(e,t)=>{const o={onboardingType:e,onboardingViews:t};I().event(m.ONBOARDING_TOUR_GUIDE,g.FEATURE_ONBOARDING_TRIGGERED,void 0,void 0,JSON.stringify(o))},qOt=e=>{I().event(m.ATV,g.CANCEL,void 0,void 0,JSON.stringify({elapsedSec:e}))},i1e=(e,t,o)=>{I().event(m.WARNING,g.SHOW_BROWSER_COMPATIBILITY_WARNING,void 0,void 0,JSON.stringify({type:e,status:t,from:o}))},QOt=(e,t)=>{I().event(m.ATV,g.TTS,void 0,void 0,JSON.stringify({textLength:e,speakerProvider:t.speaker.provider,speakerId:t.speaker.speakerId}))},s1e=e=>{I().event(m.VCLOUD,g.MEDIA_UPLOAD_START,void 0,void 0,JSON.stringify({fileSize:e}))},mk=({fileSize:e,elapsedTimeSec:t,result:o})=>{const r={fileSize:e,elapsedTimeSec:ue(t,2)},n=o==="success"?g.MEDIA_UPLOAD_SUCCESS:g.MEDIA_UPLOAD_FAILED;I().event(m.VCLOUD,n,void 0,void 0,JSON.stringify(r))},x1e=e=>{I().event(m.VCLOUD,g.MEDIA_UPLOAD_CANCEL,void 0,void 0,e?JSON.stringify({triggerSource:e}):void 0)},ZOt=e=>{I().event(m.DEFAULT_CAPTION_DISPLAY_MODE,g.TOGGLE,e?"on":"off")},c1e=e=>{I().event(m.IMPORT,g.NORMALIZE_AUDIO_START_TIME,void 0,void 0,JSON.stringify(e))},$Ot=e=>{const{planName:t,leftDays:o}=e,r=ls("monthly_subscription_consent_banner_due"),n={planName:t,leftDays:o,abTestVariant:r??void 0};I().event(m.SUBSCRIPTION_CONSENT,g.DISPLAY,void 0,void 0,JSON.stringify(n))},eCt=e=>{const{planName:t,leftDays:o}=e,r=ls("monthly_subscription_consent_banner_due"),n={planName:t,leftDays:o,abTestVariant:r??void 0};I().event(m.SUBSCRIPTION_CONSENT,g.CLOSE,void 0,void 0,JSON.stringify(n))},tCt=e=>{const{planName:t,leftDays:o}=e,r=ls("monthly_subscription_consent_banner_due"),n={planName:t,leftDays:o,abTestVariant:r??void 0};I().event(m.SUBSCRIPTION_CONSENT,g.CONFIRM,void 0,void 0,JSON.stringify(n))},oCt=e=>{const{planName:t,leftDays:o}=e,r=ls("monthly_subscription_consent_banner_due"),n={planName:t,leftDays:o,abTestVariant:r??void 0};I().event(m.SUBSCRIPTION_CONSENT,g.CANCEL,void 0,void 0,JSON.stringify(n))},rCt=e=>{const{planName:t,leftDays:o,isConsent:r}=e,n=ls("monthly_subscription_consent_banner_due"),a={planName:t,leftDays:o,isConsent:r,abTestVariant:n??void 0};I().event(m.SUBSCRIPTION_CONSENT,g.OPEN_MODAL,void 0,void 0,JSON.stringify(a))},nCt=e=>{const{planName:t,leftDays:o,isConsent:r}=e,n=ls("monthly_subscription_consent_banner_due"),a={planName:t,leftDays:o,isConsent:r,abTestVariant:n??void 0};I().event(m.SUBSCRIPTION_CONSENT,g.CLOSE_MODAL,void 0,void 0,JSON.stringify(a))},aCt=(e,t)=>
1244{I().event(m.WEB_SAVE_MODAL,g.DISPLAY,void 0,void 0,JSON.stringify({planType:e,saveType:t}))},iCt=(e,t,o,r)=>{I().event(m.WEB_SAVE_MODAL,g.CLICK,void 0,void 0,JSON.stringify({planType:e,saveType:t,destination:o,button:r}))},sCt=(e,t,o)=>{I().event(m.WEB_SAVE_MODAL,g.COMPLETED,void 0,void 0,JSON.stringify({planType:e,saveType:t,destination:o}))},xCt=e=>{I().event(m.MOUSE_EDIT,g.HOVER_THUMBNAIL_VIDEO,void 0,void 0,JSON.stringify(e))},cCt=e=>{I().event(m.ASSET_CURSOR,g.CLICK_GENERATE_WITH_MEDIA,e.target,void 0,JSON.stringify(e))},lCt=e=>{I().event(m.AI_IMAGE_AUTO_INSERTION,g.ATTACH_REFERENCE_IMAGE,void 0,void 0,JSON.stringify(e))},dCt=(e,t,o)=>{I().event(m.TTV_MODAL,g.SCRIPT_WARNING,void 0,void 0,JSON.stringify({issues:e,details:t,userChoice:o,ttvVersion:to()}))},uCt=()=>{I().event(m.TTV_MODAL,g.OPEN_MY_MEDIA_SETTINGS,void 0,void 0,JSON.stringify({ttvVersion:to()}))},pCt=e=>{I().event(m.TTV_MODAL,g.SAVE_MY_MEDIA_SETTINGS,void 0,void 0,JSON.stringify({result:e,ttvVersion:to()}))},fCt=e=>{I().event(m.TTV_MODAL,g.APPLY_MY_MEDIA_SETTINGS,void 0,void 0,JSON.stringify({numMediaSetting:e,ttvVersion:to()}))},gCt=e=>{I().event(m.TTV_MODAL,g.RENAME_MY_MEDIA_SETTINGS,void 0,void 0,JSON.stringify({result:e,ttvVersion:to()}))},_Ct=e=>{I().event(m.TTV_MODAL,g.DELETE_MY_MEDIA_SETTINGS,void 0,void 0,JSON.stringify({result:e,ttvVersion:to()}))},ECt=e=>{I().event(m.TTV_MODAL,g.FETCH_MY_MEDIA_SETTINGS_FAILED,void 0,void 0,JSON.stringify({trigger:e,ttvVersion:to()}))},mCt=()=>{I().event(m.TTV_MODAL,g.RETRY_FETCH_MY_MEDIA_SETTINGS,void 0,void 0,JSON.stringify({ttvVersion:to()}))},hCt=e=>{I().event(m.TTV_MODAL,g.SETTING_SUGGESTION,void 0,void 0,JSON.stringify({...e,ttvVersion:to()}))},ICt=e=>{I().event(m.TTV_MODAL,g.APPLY_SETTING_SUGGESTION,void 0,void 0,JSON.stringify({...e,ttvVersion:to()}))},TCt=({numMediaSetting:e,numUsedVrewStyle:t,numCustomStyle:o})=>{I().event(m.TTV_MODAL,g.SAVED_SETTING,void 0,void 0,JSON.stringify({numMediaSetting:e,numUsedVrewStyle:t,numCustomStyle:o,ttvVersion:to()}))},rS=(e,t)=>{I().event(m.TTV_MODAL,g.CHANGE_CAPTION_OPTION,void 0,void 0,JSON.stringify({...e,videoRatio:t,ttvVersion:to()}))},SCt=(e,t)=>rS({captionOptionType:"on",captionOptionOn:e},t),OCt=(e,t)=>rS({captionOptionType:"position",captionOptionPosition:e},t),CCt=(e,t)=>rS({captionOptionType:"length",captionOptionLength:e},t),RCt=(e,t)=>rS({captionOptionType:"animation",captionOptionAnimation:e},t),ACt=e=>{I().event(m.TTV_MODAL,g.OPEN_CAPTION_OPTION,void 0,void 0,JSON.stringify({videoRatio:e,ttvVersion:to()}))},yCt=(e,t)=>{I().event(m.TTV_MODAL,g.CHANGE_VIDEO_RATIO,void 0,void 0,JSON.stringify({fromRatio:e,toRatio:t,ttvVersion:to()}))},vCt=({fromRatio:e,toRatio:t,from:o,to:r})=>{I().event(m.TTV_MODAL,g.RESET_CAPTION_BY_RATIO,void 0,void 0,JSON.stringify({fromRatio:e,toRatio:t,fromCaptionPosition:o.position,toCaptionPosition:r.position,fromCaptionLength:o.length,toCaptionLength:r.length,fromCaptionAutoAnimation:o.autoAnimation,toCaptionAutoAnimation:r.autoAnimation,ttvVersion:to()}))},wCt=({result:e,removedTextCount:t,originalLength:o,cleanedLength:r})=>{I().event(m.TTV_MODAL,g.CLEAN_SCRIPT,void 0,void 0,JSON.stringify({result:e,removedTextCount:t,originalLength:o,cleanedLength:r,ttvVersion:to()}))},NCt=(e,t)=>{I().event(m.VIDEO_GENERATE,g.ATTACH_GENVIDEO_INPUT,void 0,void 0,JSON.stringify({inputType:e,...t}))},PCt=(e,t)=>{I().event(m.VIDEO_GENERATE,g.SELECT_GENVIDEO_IMAGE_DESTINATION,void 0,void 0,JSON.stringify({destination:e,trigger:t}))},l1e=(e,t)=>{I().event(m.IMAGE_GENERATE,g.NSFW_IMAGE_BLOCKED,void 0,t,JSON.stringify({trigger:e,nsfwImageCount:t}))},nS=e=>e==="video_panel"?m.VIDEO_GENERATE:m.IMAGE_GENERATE,bCt=e=>{I().event(nS(e),g.OPEN_PROMPT_SUGGEST,void 0,void 0,JSON.stringify({trigger:e}))},LCt=(e,t)=>{I().event(nS(e),g.USE_PROMPT_SUGGEST,void 0,void 0,JSON.stringify({trigger:e,scope:t}))},MCt=e=>{I().event(nS(e),g.REGENERATE_PROMPT,void 0,void 0,JSON.stringify({trigger:e}))},DCt=(e,t,o)=>{I().event(nS(e),g.PROMPT_SUGGEST_RESULT,void 0,void 0,JSON.stringify({trigger:e,result:t,...o?{errorCode:o}:{}}))},kCt=()=>{I().event(m.AI_IMAGE_AUTO_INSERTION,g.OPEN_PROMPT_SUGGEST)},FCt=()=>{I().event(m.AI_IMAGE_AUTO_INSERTION,g.USE_PROMPT_SUGGEST)},UCt=()=>{I().event(m.AI_IMAGE_AUTO_INSERTION,g.REGENERATE_PROMPT)},VCt=(e,t)=>
1244{I().event(m.AI_IMAGE_AUTO_INSERTION,g.PROMPT_SUGGEST_RESULT,void 0,void 0,JSON.stringify({result:e,...t?{errorCode:t}:{}}))},GCt=(e,t)=>(o,r)=>{const n=r(),a=k5(n),i=M5(n),s=bc(e,a),x=bc(t,i);if(s&&x)return;const c=s?a:e,l=x?i:t;return o({type:ka.APPLY_STATIC_DECORATION,payload:{wordDecorations:c,captionStaticDecorations:l}})},d1e=e=>(t,o)=>{const r=o(),n=D5(r),a=bc(e,n);if(a){t(u1e());return}const i=a?n:e;return t({type:ka.APPLY_DYNAMIC_DECORATION,payload:{captionDynamicDecorations:i}})},u1e=()=>({type:ka.UPDATE_DECORATION}),p1e=()=>({type:ka.CLEAR_DYNAMIC_DECORATION}),f1e=()=>({type:ka.CLEAR_STATIC_DECORATION}),g1e=()=>(e,t)=>{const o=t(),{globalClipRange:r}=$x(o);return e({type:ka.GET_IMPORT_SCRIPT_DECORATION_RANGE,payload:{targetClipIndices:bG(r)}})},_1e=e=>(t,o)=>{if(e)return t({type:ka.GET_CAPTION_SETTING_DECORATION_RANGE,payload:{targetClipIndices:e}});const r=o(),n=He(r),a=n.map((i,s)=>i.captions.some(x=>x.style!==void 0)?null:s).filter(ri);return t({type:ka.GET_CAPTION_SETTING_DECORATION_RANGE,payload:{targetClipIndices:a}})},WCt=()=>({type:ka.CLEAR_MARKER_PANEL_DECORATION}),HCt=e=>t=>{t({type:ka.SET_PRONUNCIATION_DISPLAY,payload:{display:e}}),qUe(e)};class E1e{_factory;_opts;_state="idle";_promise=null;_controller=null;constructor(t,o={}){this._factory=t,this._opts={persistOnResolve:o.persistOnResolve??!0,resetOnReject:o.resetOnReject??!0}}get state(){return this._state}get inFlight(){return this._state==="pending"}get(){return this._promise}abort(t){if(this._controller&&!this._controller.signal.aborted)try{const o=new DOMException(t?"AbortError: "+t:"AbortError","AbortError");this._controller.abort(o)}catch{this._controller.abort()}}reset(){this._state!=="pending"&&(this._promise=null,this._controller=null,this._state="idle")}async run(t,...o){if(this._promise)return this._promise;const r=new AbortController;this._controller=r;let n=null;if(t)if(t.aborted)try{r.abort(t.reason??new DOMException("Aborted","AbortError"))}catch{r.abort()}else{const s=()=>{try{r.abort(t.reason??new DOMException("Aborted","AbortError"))}catch{r.abort()}};t.addEventListener("abort",s,{once:!0}),n=()=>t.removeEventListener("abort",s)}this._state="pending";const a=()=>this._factory(r.signal,...o),i=(async()=>{try{const s=await a();return this._state="resolved",!this._opts.persistOnResolve&&this.reset(),s}catch(s){throw this._state="rejected",this._opts.resetOnReject&&this.reset(),s}finally{n&&n(),this._controller===r&&this._state!=="pending"&&(this._controller=null)}})();return this._promise=i,i}}function m1e(e,t){return new E1e(e,t)}function af(e,t){const o=m1e(e,t),r=(...n)=>o.run(void 0,...n);return r.abort=n=>o.abort(n),r.reset=()=>o.reset(),r.promise=()=>o.get(),r}class h1e{_window;_bufferSliceIndex=-1;constructor(t=60){this._window=X.fromSec(t)}set bufferWindowSec(t){this._window=X.fromSec(t)}reset(t=0){this._bufferSliceIndex=t-1}peek(t,o){if(t.length===0)return[];this._bufferSliceIndex<o&&(this._bufferSliceIndex=o-1);const r=[];let n=X.zero(),a=this._bufferSliceIndex;for(;a<t.length-1&&n.lt(this._window);){++a;const i=t[a];r.push([i.startInProject,i.startInProject.add(i.durationInProject),i.startInVideo.add(i.durationInVideo)]),n=n.add(i.durationInVideo)}return r}commit(t){this._bufferSliceIndex+=t}}class I1e{_requested=X.zero();_filled=X.zero();reset(){this._requested=X.zero(),this._filled=X.zero()}setBufferTime(t){this._requested=t,this._filled=X.zero()}updateFilledTime(t){this._filled=X.max(this._filled,t)}updateRequestedTime(t){this._requested=t}isBufferSufficient(t){return this._filled.gt(t)}getStatus(){return{requested:this._requested,filled:this._filled}}}class T1e{_backgroundBuffering=null;_syncBufferingActive=!1;_realigning=!1;_progressWaiters=new Set;_interruptWaiters=new Set;get occupied(){return this._backgroundBuffering!==null||this._syncBufferingActive||this._realigning}get parkedCount(){return this._progressWaiters.size+this._interruptWaiters.size}beginSyncBuffering(){this._syncBufferingActive=!0}endSyncBuffering(){this._syncBufferingActive=!1}beginRealign(){this._realigning=!0}endRealign(){this._realigning=!1}
1244setBackgroundBuffering(t){this._backgroundBuffering=t}clearBackgroundBuffering(t){this._backgroundBuffering===t&&(this._backgroundBuffering=null)}notifyProgress(){this._wake(this._progressWaiters)}notifyInterrupt(){this._wake(this._interruptWaiters)}parkProgress(t){return this._park(this._progressWaiters,t)}parkInterrupt(t){return this._park(this._interruptWaiters,t)}_wake(t){const o=[...t];t.clear();for(const r of o)r()}_park(t,o){let r,n;return{waited:new Promise(i=>{n=()=>{t.delete(r),i()},r=()=>{o.removeEventListener("abort",n),i()},t.add(r),o.addEventListener("abort",n,{once:!0})}),cancel:()=>{o.removeEventListener("abort",n),n()}}}}class tY{_timeline;_bufferPlanner;_bufferManager;_state="idle";_stopTimeoutMs;_stopRequested=!1;_bufferingToken=0;_bufferingGate=new T1e;_inFlightFetches=new Set;_alignmentGeneration=0;get _timelineGeneration(){return this._alignmentGeneration}_invalidateBuffering(){const t=++this._bufferingToken;return this._bufferingGate.notifyInterrupt(),t}_fetchTracked(t,o){const r=this._onFetchData(t,o).finally(()=>{this._inFlightFetches.delete(r)});return this._inFlightFetches.add(r),r}async _settleInFlightFetches(){let t=this._invalidateBuffering();for(;this._inFlightFetches.size>0;)t=this._invalidateBuffering(),await Promise.allSettled([...this._inFlightFetches]);return t}constructor(t){this._timeline=new GJ(t?.fps??30),this._bufferPlanner=new h1e(60),this._bufferManager=new I1e,this._stopTimeoutMs=t?.stopTimeoutMs}_pendingInitArgs=null;init=(t,o)=>(this._pendingInitArgs={slices:t,initialTime:o},this._invalidateBuffering(),this._initOneFlight());_initOneFlight=af(async()=>{if(this._state!=="idle"&&this._state!=="running")return this._logger.warn(null,"init: cannot init from state '"+this._state+"'"),this;this._bufferingGate.beginRealign();try{let t=this._state==="running";for(;;){if(this._invalidateBuffering(),this._inFlightFetches.size>0&&(await this._settleInFlightFetches(),this._isDestroyed()))return this;const o=this._pendingInitArgs;if(!o)return this;const{slices:r,initialTime:n}=o;if(this._timeline.init(r,n),this._alignmentGeneration++,this._bufferManager.reset(),this._bufferPlanner.reset(n?this._timeline.currentSliceIndex:void 0),n&&this._bufferManager.setBufferTime(n),(t||n)&&this.clearCache(),!t&&await this._onInit(r,n),this._isDestroyed())return this;if(this._bufferingGate.notifyProgress(),o!==this._pendingInitArgs){t=!0;continue}break}return this._stopRequested?(await this._onStop(),this._stopRequested=!1,!this._isDestroyed()&&(this._state="stopped"),this):(this._state="running",this)}catch(t){throw!this._isDestroyed()&&(this._state="idle"),t}finally{this._bufferingGate.endRealign(),this._bufferingGate.notifyProgress()}},{persistOnResolve:!1});stop=af(async()=>{const t=this._initOneFlight.promise();if(t){this._stopRequested=!0;try{await t}finally{this._stopRequested=!1}return}this._state==="running"&&(await this._onStop(),this._state="stopped")},{persistOnResolve:!1});destroy=af(async()=>{if(this._state!=="destroyed")try{this._state==="running"&&(this._stopTimeoutMs!==void 0?await Promise.race([this.stop(),gu(this._stopTimeoutMs)]):await this.stop()),await this._onDestroy()}finally{this._invalidateBuffering(),this._timeline.clear(),this._alignmentGeneration++,this._bufferManager.reset(),this._bufferPlanner.reset(),this.clearCache(),this._state="destroyed",this._bufferingGate.notifyProgress()}},{persistOnResolve:!1});async seek(t,o="time-move"){let r=this._invalidateBuffering();if(this._bufferingGate.beginRealign(),this._inFlightFetches.size>0&&(r=await this._settleInFlightFetches(),r!==this._bufferingToken)){this._bufferingGate.endRealign(),o==="content-change"&&this.clearCache();return}if(this._timeline.seek(t),this._alignmentGeneration++,this._bufferPlanner.reset(this._timeline.currentSliceIndex),this._bufferManager.setBufferTime(t),o==="content-change")this.clearCache();else{this._resetTimeDependentRenderState();const n=this._timeline.current()?.[0];n&&this._dataProvider.seekCursor(n)}this._bufferingGate.endRealign(),this._bufferingGate.notifyProgress(),await this._ensureBuffered(t,r)}
1244_releaseConsumedWindow(){const t=this._timeline.timeslices,o=this._timeline.currentSliceIndex-1;o<=0||this._dataProvider.releaseBefore(t[o].startInProject)}async _ensureBuffered(t,o){const r=this._bufferPlanner.peek(this._timeline.timeslices,this._timeline.currentSliceIndex);if(r.length===0)return"empty";this._releaseConsumedWindow(),this._bufferManager.updateRequestedTime(r[r.length-1][2]),this._bufferingGate.beginSyncBuffering();try{let n=0;for(;n<r.length&&!this._bufferManager.isBufferSufficient(t);){if(o!==this._bufferingToken)return"superseded";const[a,i,s]=r[n];try{if(await this._fetchTracked(a,i),o!==this._bufferingToken)return"superseded";this._bufferManager.updateFilledTime(s),this._bufferingGate.notifyProgress()}catch(x){if(o!==this._bufferingToken)return"superseded";throw x}if(o!==this._bufferingToken)return"superseded";this._bufferPlanner.commit(1),this._bufferingGate.notifyProgress(),n++}if(n<r.length){const a=this._bufferRanges(r,n,o).finally(()=>{this._bufferingGate.clearBackgroundBuffering(a),this._bufferingGate.notifyProgress()});this._bufferingGate.setBackgroundBuffering(a)}return"planned"}finally{this._bufferingGate.endSyncBuffering(),this._bufferingGate.notifyProgress()}}async _bufferRanges(t,o,r){for(let n=o;n<t.length;n++){if(r!==this._bufferingToken||this._abortSignal.aborted)return;const[a,i,s]=t[n];try{if(await this._fetchTracked(a,i),r!==this._bufferingToken)return;this._bufferManager.updateFilledTime(s),this._bufferingGate.notifyProgress()}catch(x){r===this._bufferingToken&&this._logger.warn(null,"background buffer fill error: "+x);return}if(r!==this._bufferingToken)return;this._bufferPlanner.commit(1),this._bufferingGate.notifyProgress()}}async _nextPrepared(){if(this._state!=="running")return this._logger.warn(null,"next: previewer not running (state="+this._state+")"),null;const t=this._timelineGeneration,o=this._timeline.next();if(!o)return null;const[,r]=o;return!await this._waitForBuffer(r,t)||t!==this._timelineGeneration?null:o}_isDestroyed(){return this._state==="destroyed"}get currentTime(){return this._timeline.currentTime}get duration(){return this._timeline.duration}get ended(){return this._timeline.ended}async _waitForBuffer(t,o){for(;!this._bufferManager.isBufferSufficient(t);){if(this._abortSignal.aborted||this._isDestroyed()||o!==this._timelineGeneration||t.as.ms()>=this._timeline.duration.as.ms())return!1;if(this._bufferingGate.occupied){await this._bufferingGate.parkProgress(this._abortSignal).waited;continue}const r=this._ensureBuffered(t,this._bufferingToken),n=this._bufferingGate.parkInterrupt(this._abortSignal),a=await Promise.race([r.then(i=>(n.cancel(),{settled:!0,planned:i==="planned",empty:i==="empty"}),i=>{throw n.cancel(),i}),n.waited.then(()=>({settled:!1,planned:!1,empty:!1}))]);if(!a.settled){r.catch(()=>{}),!this._abortSignal.aborted&&!this._isDestroyed()&&o===this._timelineGeneration&&!this._bufferManager.isBufferSufficient(t)&&await gu(0);continue}if(a.empty)return!1;a.planned||await gu(0)}return!this._abortSignal.aborted&&!this._isDestroyed()}}const S1e=100;class O1e{_logger;_meta;_pool;_strand=new Mu;_params=[];_renderTimeline;_worker={state:"idle"};_release=null;_lastParam=null;constructor(t,o,r){this._meta=t,this._logger=o,this._pool=r,this._renderTimeline=new R1e(S1e)}isEmpty(){return this._params.length===0&&this._lastParam===null}clear(){this._renderTimeline.clear(),this._params.splice(0,this._params.length),this._lastParam=null,this._strand.next(()=>this._clearWorker())}push(...t){this._params.push(...t)}async render(t){return this._strand.next(async()=>{if(this._params.length===0&&this._lastParam===null)return[[],!1];try{if(this._worker.state==="idle"){const{worker:a,release:i}=this._pool.acquire();this._release=i,this._worker=await this._initWorker(this._params[0],a)}else this._worker.state==="cleared"&&(this._worker=await this._initWorker(this._params[0],this._worker.worker));const[o,r]=this._renderTimeline.next(t.timelineStart);return this._isParamsReady({from:o,to:r})?[await this._render(o,r),!0]:[await this._flush(),!1]}catch(o){throw Ae(void 0,o,void 0,{errorAt:t.timelineStart,erroredFrom:"Audio"})}})}async destroy(){return this._strand.next(async()=>{try{this._logger.verbose(null,"destroying renderer"),await this._clearWorker()}finally{this._params.splice(0,this._params.length),this._lastParam=null,this._renderTimeline.clear(),this._release?.(),this._release=null,this._logger.verbose(null,"destroyed renderer")}})}async _initWorker(t,o){return await Ey(o.init(this._meta,hk(t),vf(this._logger),Qa("isVerbose"),Qa("isDev")),3e3,()=>{this._logger.warn(null,"renderer not initialized after 3 seconds")}),{state:"initialized",worker:o}}
1244async _clearWorker(){if(this._worker.state==="initialized")try{const t=this._worker.worker;this._worker={state:"cleared",worker:t},await t.clear()}catch(t){const o=Ae(void 0,t,"Error while clearing audio renderer");this._logger.warn(null,o.message)}}async _render(t,o){const r=[];for(;this._params.length;){const n=this._params[0];try{const a=n.timelineStart.add(n.timelineDuration);if(a.lte(t)){this._params.shift();continue}if(n.timelineStart.gte(o)||(this._throwIfWorkerIdle(),this._worker.state!=="initialized"))break;this._lastParam&&!C1e(this._lastParam,n)&&r.push(...await this._flush());const i=this._worker.worker;await i.update(hk(n));const s=await i.render(t.as.us(),o.as.us());if(r.push(...s),this._lastParam={id:n.id,timelineEnd:n.timelineStart.add(n.timelineDuration),sourceId:n.sourceId,playbackRate:n.playbackRate},a.lt(o))this._params.shift();else break}catch(a){throw Ae(void 0,a,void 0,{errorAt:n.timelineStart,erroredFrom:"Audio"})}}return(this._params.length===0||this._params[0].timelineStart.gte(o))&&r.push(...await this._flush()),r}async _flush(){return this._lastParam===null||this._worker.state!=="initialized"?[]:(this._lastParam=null,this._worker.worker.flush())}_isParamsReady(t){for(;this._params.length;){const o=this._params[0];if(o.timelineStart.add(o.timelineDuration).lte(t.from)){this._params.shift();continue}return!o.timelineStart.gte(t.to)}return!1}_throwIfWorkerIdle(){if(this._worker.state==="idle")throw Ae(je.AUDIO_LOGIC_ERR,"AudioRenderer is not initialized")}}const C1e=(e,t)=>{const o=e.id===t.id,r=e.sourceId===t.sourceId&&e.playbackRate===t.playbackRate,n=e.timelineEnd.eq(t.timelineStart);return r&&(o||n)};class R1e{_interval;_tick=null;constructor(t){this._interval=X.fromMS(t)}next(t){this._tick=!this._tick||this._tick.lt(t)?t:this._tick;const o=this._tick,r=o.add(this._interval);return this._tick=r,[o,r]}clear(){this._tick=null}}const hk=e=>({...e,timelineStart:e.timelineStart.as.us(),timelineDuration:e.timelineDuration.as.us(),sourceIn:e.sourceIn.as.us(),loop:e.loop?{in:e.loop.in.as.us(),out:e.loop.out.as.us()}:void 0});class A1e{constructor(t){this._sampleRate=t}_sampleRate;_buffer=[];_endTimelineIndex=0;push(...t){if(t.length===0)return;for(const r of t){if(r.sampleRate!==this._sampleRate)throw Ae(je.AUDIO_LOGIC_ERR,"AudioSink: sampleRate mismatch. Expected "+this._sampleRate+", but got "+r.sampleRate);this._buffer.push({timelineIndex:r.timelineIndex,data:r.data})}const o=this._buffer.at(-1);this._endTimelineIndex=o.timelineIndex+o.data[0].length}isEmpty(){return this._buffer.length===0}isSufficient(t){return qS(t,this._sampleRate)<=this._endTimelineIndex}get(t){if(this._buffer.length===0)return[];const o=this._sampleRate,r=qS(t.timelineStart,o),n=qS(t.timelineEnd,o),a=[];for(;this._buffer.length>0;){const i=this._buffer.at(0);if(i.data.length===0){this._buffer.shift();continue}const s=i.timelineIndex,x=s+i.data[0].length;if(r>=x){this._buffer.shift();continue}if(n<=s)break;const c=Math.max(s,r)-s,l=Math.min(x,n)-s,d=i.data.map(u=>u.subarray(c,l));if(d[0].length>0){const u=s+c;a.push({timelineIndex:u,data:d,sampleRate:this._sampleRate})}if(x<=n)this._buffer.shift();else break}return a}clear(){this._buffer.length=0,this._endTimelineIndex=0}}const y1e=3e3;class v1e{maxIdleSize=1;entries=new Map;_logger=nn("AudioRendererWorkerPool");countIdle(){let t=0;return this.entries.forEach(o=>{o.state==="idle"&&(t+=1)}),t}acquire(){const t=Array.from(this.entries).find(([,a])=>a.state==="idle"),[o,r]=t??this.createWorker();r.state="busy";const n=()=>{const a=this.entries.get(o);if(!(!a||a.state!=="busy")){if(this.countIdle()>=this.maxIdleSize){this.entries.delete(o),this._destroyWorkerWithTimeout(o,a.native);return}a.state="idle"}};return{worker:r.guarded,release:n}}createWorker(){const t=new Worker(new URL("/try/assets/renderer.audio.worker-BnoF42Qc.js",import.meta.url),{type:"module"}),o=i1(t),r=TG({native:t,remote:o,logger:this._logger,workerLabel:"audio renderer worker",onDeath:()=>this.entries.delete(o)}),n={native:t,state:"idle",guarded:r};return this.entries.set(o,n),[o,n]}_destroyWorkerWithTimeout(t,o){Ey(t.destroy(),y1e,()=>{this._logger.warn(null,"audio renderer worker killed"),o.terminate()}).catch(r=>{this._logger.warn(null,"worker close failed: "+qr(r)),o.terminate()})}
1244destroy(){this.entries.forEach((t,o)=>{this._destroyWorkerWithTimeout(o,t.native)}),this.entries.clear()}}const w1e=1,N1e=30;class P1e{_meta;_provider;_tracks=new Map;_sinks=new Map;_pool;_mixer;_state="idle";_generation=0;constructor(t,o){this._meta=t,this._provider=o,this._pool=new v1e,this._mixer=Vh(new Worker(new URL("/try/assets/mixer.audio-DdQ9z92e.js",import.meta.url),{type:"module"}))}async init(){this._state!=="destroyed"&&await this._mixer.init(this._meta)}async render(t){if(this._state==="destroyed")return this._createEmptyResult(t);const o=this._generation;this._state="running";try{return await this._render(t,o)}catch(r){const n=this._staleResult(o,t);if(n)return n;throw r}finally{this._state==="running"&&(this._state="idle")}}clear(){if(this._state!=="destroyed"){this._generation++;for(const t of this._tracks.values())t.clear();for(const t of this._sinks.values())t.clear()}}destroy=af(async()=>{if(this._state!=="destroyed"){this._state="destroyed",this._generation++;try{for(const[,t]of this._tracks.entries())await t.destroy();await this._mixer.destroy()}finally{this._pool.destroy(),this._tracks.clear();for(const t of this._sinks.values())t.clear();this._sinks.clear()}}},{persistOnResolve:!1});async _render(t,o){this._fetchTracks(t);const r=[];for(const[s,x]of this._tracks.entries()){this._throwIfNoSinkExists(s);const c=this._sinks.get(s);for(;!c.isSufficient(t.timelineEnd);){const[l,d]=await x.render(t),u=this._staleResult(o,t);if(u)return u;if(c.push(...l),!d)break}this._shouldDestroyTrack(s,t.timelineEnd)&&r.push(s)}for(const s of r){await this._tracks.get(s)?.destroy();const x=this._staleResult(o,t);if(x)return x;this._tracks.delete(s)}const n=[];for(const[s,x]of this._sinks.entries()){const c=x.get(t);n.push(...c),x.isEmpty()&&!this._tracks.has(s)&&(x.clear(),this._sinks.delete(s))}let a;try{a=await this._mixer.render(b1e(t),n)}catch(s){const x=this._staleResult(o,t);if(x)return x;throw s}const i=this._staleResult(o,t);return i||{data:a,numberOfChannels:this._meta.numberOfChannels,timelineTime:t.videoTimelineTime}}_addTrack(t,o){if(o.length===0)return;const r=o[0],n=nn("AudioRenderer#"+r.sourceId.slice(0,8)),a=new O1e(this._meta,n,this._pool);if(a.push(...o),this._tracks.set(t,a),!this._sinks.has(t)){const i=new A1e(this._meta.sampleRate);this._sinks.set(t,i)}}_fetchTracks(t){const o=t.timelineStart,r=t.timelineEnd.add(X.fromSec(w1e)),n=this._provider.get(o,r).mainLayer.tracks.target;for(const[a,i]of Object.entries(n)){const s=this._tracks.get(a);s?s.push(...i):this._addTrack(a,i)}}_throwIfNoSinkExists(t){if(!this._sinks.has(t))throw Ae(je.AUDIO_LOGIC_ERR,"Sink not found for track "+t)}_shouldDestroyTrack(t,o){const r=this._tracks.get(t);if(!r)return!0;const n=this._provider.getNextParamTimelineStart(t),a=!n||n.gt(o.add(X.fromSec(N1e)));return r.isEmpty()&&a}_staleResult(t,o){return this._state==="destroyed"||t!==this._generation?this._createEmptyResult(o):null}_createEmptyResult(t){const o=t.timelineEnd.sub(t.timelineStart).as.sec(),r=Math.max(0,Math.ceil(o*this._meta.sampleRate));return{data:new Float32Array(r*this._meta.numberOfChannels),numberOfChannels:this._meta.numberOfChannels,timelineTime:t.videoTimelineTime}}}const b1e=e=>({timelineStart:e.timelineStart.as.us(),timelineEnd:e.timelineEnd.as.us()});class L1e extends tY{_logger=nn("AudioPreviewer");_dataProvider;_abortSignal;_manager;_render$=new id;_end$=new id;constructor(t,o,r){super(),this._dataProvider=o,this._abortSignal=r,this._manager=new P1e(t,o),this._abortSignal.addEventListener("abort",()=>this._end$.next(),{once:!0})}next=async()=>{const t=await this._nextPrepared();if(!t)return!1;const[o,r,n]=t,a=o.add(n);return this._render$.next({timelineStart:o,timelineEnd:a,videoTimelineTime:r}),!0};stream=()=>this._render$.asObservable().pipe(wl(this._end$),s1(St(async t=>({type:"Audio",...await this._manager.render(t),projectTimelineTime:t.timelineStart}))),c0(t=>(this.destroy(),ta(()=>Ae(je.AUDIO_LOGIC_ERR,t,"Failed to render audio.")))),x1(()=>{this._end$.next()}));complete(){this._render$.complete()}clearCache(){this._dataProvider.clear(),this._manager.clear()}_resetTimeDependentRenderState(){this._manager.clear()}async _onInit(){await this._manager.init(),this._logger.verbose(null,"Audio Previewer initialized")}async _onStop(){this._end$.next()}async _onDestroy(){this._logger.debug(null,"destroying");try{await this._manager.destroy()}finally{this._render$.complete(),this._end$.complete(),this._logger.debug(null,"destroyed")}}_onFetchData(t,o){return this._dataProvider.fetch(t,o)}}const M1e=3e3;class D1e{maxIdleSize=2;entries=new Map;_logger=nn("VideoDecoderWorkerPool");countIdle(){let t=0;
1244return this.entries.forEach(o=>{o.state==="idle"&&(t+=1)}),t}acquire(){const t=Array.from(this.entries).find(([,a])=>a.state==="idle"),[o,r]=t??this._createWorker();r.state="busy";const n=()=>{const a=this.entries.get(o);if(!(!a||a.state!=="busy")){if(this.countIdle()>=this.maxIdleSize){this.entries.delete(o),this._destroyWorkerWithTimeout(o,a.native);return}a.state="idle"}};return{worker:r.guarded,release:n}}_createWorker(){this._logger.verbose(null,"creating new worker");const t=new Worker(new URL("/try/assets/decoder.worker-BdB5LWGp.js",import.meta.url),{type:"module"});this._logger.verbose(null,"worker created");const o=i1(t),r=TG({native:t,remote:o,logger:this._logger,workerLabel:"video decoder worker",onDeath:()=>this.entries.delete(o)}),n={native:t,state:"idle",guarded:r};return this.entries.set(o,n),[o,n]}_destroyWorkerWithTimeout(t,o){Ey(t.destroy(),M1e,()=>{this._logger.warn(null,"video decoder worker killed"),o.terminate()}).catch(r=>{this._logger.warn(null,"worker destroy failed: "+qr(r)),o.terminate()})}destroy(){this.entries.forEach((t,o)=>{this._destroyWorkerWithTimeout(o,t.native)}),this.entries.clear()}}const Bn=(e,t,o,r)=>{const n=3*e,a=3*(o-e)-n,i=1-n-a,s=3*t,x=3*(r-t)-s,c=1-s-x,l=f=>((i*f+a)*f+n)*f,d=f=>((c*f+x)*f+s)*f,u=f=>(3*i*f+2*a)*f+n,p=f=>{let E=f;for(let T=0;T<5;T++){const O=u(E);if(O===0)break;const S=l(E)-f;if(E-=S/O,Math.abs(S)<1e-6)break}return Math.max(0,Math.min(1,E))};return f=>f<=0?0:f>=1?1:d(p(f))},k1e=Bn(.25,.1,.25,1),F1e=["focus-in-","focus-out-","flip-in-","flip-out-","popping-","moving-","slide-"],U1e=new Set(["focus-in","focus-out","flip","flip-once","popping","popping-once","fade-in-out","blink","blink-once","tada","tada-once","swing","swing-once","rubber-band","rubber-band-once","shake-x","shake-x-once","shake-y","shake-y-once","heart-beat","heart-beat-once","pop-in","pop-in-once"]),aS=e=>U1e.has(e)||F1e.some(t=>e.startsWith(t))?ts:k1e,V1e=(e,t,o,r,n)=>{if(G1e(e))return H1e(e,t,r,n);if(K1e(e))return j1e(e,t,o,r);if(X1e(e))return z1e(e,t,r,n);if(J1e(e))return Y1e(e,t,o,r,n);throw new Error("Invalid animation variant: "+e)},Zf=(e,t)=>js(e.as.ms("raw")/t.as.ms("raw"),0,1),G1e=e=>B1e(e)||q1e(e),W1e=(e,t,o,r)=>{const n=X.max(X.zero(),t.sub(r)),a=X.min(n,o);return aS(e)(Zf(a,o))},H1e=(e,t,o,r)=>({progress:W1e(e,t,o,r),phase:"start"}),j1e=(e,t,o,r)=>{const n=X.max(X.zero(),o.sub(r));if(t.lt(n))return{progress:0,phase:"end"};const a=X.min(t.sub(n),r);return{progress:aS(e)(Zf(a,r)),phase:"end"}},z1e=(e,t,o,r)=>{if(o.eq(X.zero()))return{progress:0,phase:"loop"};const n=X.max(X.zero(),t.sub(r)),a=n.mod(o);return{progress:aS(e)(Zf(a,o)),phase:"loop"}},Y1e=(e,t,o,r,n)=>{const a=r.div(2),i=aS(e);if(t.lt(n))return{progress:0,phase:"in"};const s=X.max(X.zero(),o.sub(a)),x=n.add(a),c=X.max(x,s);if(t.lt(x)){const d=X.min(t.sub(n),a);return{progress:i(Zf(d,a)),phase:"in"}}if(t.lte(c))return{progress:1,phase:"in"};const l=X.min(t.sub(c),a);return{progress:i(Zf(l,a)),phase:"out"}},B1e=e=>Eo(xo).isValue(e),K1e=e=>Eo($o).isValue(e),X1e=e=>Eo(Js).isValue(e),J1e=e=>Eo(VU).isValue(e),q1e=e=>Eo(Qn).isValue(e),Ti=(e,t)=>{if(t.length===0)return 0;if(e<=t[0][0])return t[0][1];for(let o=1;o<t.length;o++){const[r,n]=t[o],[a,i]=t[o-1];if(e<=r){const s=(e-a)/Math.max(1e-6,r-a);return n*s+i*(1-s)}}return t[t.length-1][1]},Et=(e,t,o)=>{if(t.length===0)return 0;if(e<=t[0][0])return t[0][1];for(let r=1;r<t.length;r++){const[n,a]=t[r],[i,s]=t[r-1];if(e<=n){const x=(e-i)/Math.max(1e-6,n-i),c=o(x);return a*c+s*(1-c)}}return t[t.length-1][1]},ts=e=>Math.max(0,Math.min(1,e)),Zi=(e,t,o)=>e+(t-e)*o,ga=e=>e*Math.PI/180,_C=e=>{const t=(e%360+360)%360;return t>=180?t-360:t},Cp=(e,t,o)=>{const r=_C(e),n=_C(t),a=_C(n-r);return r+a*o};let uE=null;const Lo=Bn(.25,.1,.25,1),$a=Bn(.42,0,1,1),Ec=Bn(0,0,.58,1),Q1e=Bn(.42,0,.58,1),pE=Bn(0,.4,.15,1),fE=Bn(.4,0,1,.15),oY=Bn(.55,.055,.675,.19),Z1e=Bn(.175,.885,.32,1),$1e=[[0,0],[.4,1],[1,1]],eVe=[[0,1],[.6,1],[1,0]],Ik=[[0,1],[.5,0],[1,1]],tVe=[[0,-1],[.6,-.5],[.8,-.2],[1,0]],oVe=[[0,30],[.6,-20],[.8,5],[1,0]],rVe=[[0,0],[.6,.6],[.8,.9],[1,1]],nVe=[[0,1],[.6,.5],[.8,.2],[1,0]],aVe=[[0,-30],[.6,20],[.8,-5],[1,0]],iVe=[[0,0],[.6,.5],[.8,.8],[1,1]],sVe=[[0,0],[.2,-.2],[.4,-.5],[1,-1]],xVe=[[0,0],[.2,5],[.4,-20],[1,30]],Tk=[[0,1],[.2,.9],[.4,.6],[1,0]],cVe=[[0,0],[.2,.2],[.4,.5],[1,1]],lVe=[[0,0],[.2,-5],[.4,20],[1,-30]],Sk=[[0,.3],[1,1]],dVe=[[0,0],[.5,1],[1,1]],Ok=[[0,1],[.5,.3],[1,.3]],uVe=[[0,1],[.5,0],[1,0]],Uo={popping:{scale:[[0,.3],[.2,1.1],[1,1]],alph
1244a:[[0,0],[.2,1],[1,1]]},"popping-in":{scale:[[0,.3],[.2,1.1],[.4,.9],[.6,1.03],[.8,.97],[1,1]],alpha:[[0,0],[.6,1],[1,1]]},"popping-in-down":{scale:[[0,3],[.4,.9],[.65,.95],[.8,.985],[1,1]],motion:[[0,-3e3],[.4,25],[.65,-10],[.8,5],[1,0]],alpha:[[0,0],[.4,1],[1,1]]},"popping-in-up":{scale:[[0,5],[.6,.9],[.75,.95],[.9,.985],[1,1]],motion:[[0,3e3],[.6,-20],[.75,10],[.9,-5],[1,0]],alpha:[[0,0],[.6,1],[1,1]]},"popping-in-right":{scale:[[0,3],[.6,1],[.75,.98],[.9,.995],[1,1]],motion:[[0,-3e3],[.6,25],[.75,-10],[.9,5],[1,0]],alpha:[[0,0],[.6,1],[1,1]]},"popping-in-left":{scale:[[0,3],[.6,1],[.75,.98],[.9,.995],[1,1]],motion:[[0,3e3],[.6,-25],[.75,10],[.9,-5],[1,0]],alpha:[[0,0],[.6,1],[1,1]]},"popping-out":{scale:[[0,1],[.2,.9],[.5,1.1],[.55,1.1],[1,.3]],alpha:[[0,1],[.5,1],[.55,1],[1,0]]},"popping-out-down":{scale:[[0,1],[.2,.985],[.4,.9],[.45,.9],[1,3]],motion:[[0,0],[.2,10],[.4,-20],[.45,-20],[1,2e3]],alpha:[[0,1],[.4,1],[.45,1],[1,0]]},"popping-out-up":{scale:[[0,1],[.2,.985],[.4,.9],[.45,.9],[1,3]],motion:[[0,0],[.2,-10],[.4,20],[.45,20],[1,-2e3]],alpha:[[0,1],[.4,1],[.45,1],[1,0]]},"popping-out-left":{scale:[[0,1],[.2,.9],[1,2]],motion:[[0,0],[.2,20],[1,-2e3]],alpha:[[0,1],[.2,1],[1,0]]},"popping-out-right":{scale:[[0,1],[.2,.9],[1,2]],motion:[[0,0],[.2,-20],[1,2e3]],alpha:[[0,1],[.2,1],[1,0]]}},pVe=[[0,1],[.1,.9],[.2,.9],[.3,1.1],[.4,1.1],[.5,1.1],[.6,1.1],[.7,1.1],[.8,1.1],[.9,1.1],[1,1]],fVe=[[0,0],[.1,-3],[.2,-3],[.3,3],[.4,-3],[.5,3],[.6,-3],[.7,3],[.8,-3],[.9,3],[1,0]],Ck=[[0,0],[.1,-10],[.2,10],[.3,-10],[.4,10],[.5,-10],[.6,10],[.7,-10],[.8,10],[.9,-10],[1,0]],gVe=[[0,0],[.2,15],[.4,-10],[.6,5],[.8,-5],[1,0]],_Ve=[[0,1],[.14,1.5],[.28,1],[.42,1.5],[.7,1],[1,1]],EVe=[[0,.1],[.5,1],[1,1]],mVe=[[0,30],[.5,-10],[.7,3],[1,0]],hVe=[[0,1],[.3,1.25],[.4,.75],[.5,1.15],[.65,.95],[.75,1.05],[1,1]],IVe=[[0,1],[.3,.75],[.4,1.25],[.5,.85],[.65,1.05],[.75,.95],[1,1]],TVe=[[0,$a],[.4,Ec],[.5,$a],[.8,$a],[1,$a]],SVe=[[.4,$a],[.5,Ec],[.8,$a],[1,$a]],Rk=[[.4,$a],[.6,$a],[.8,Lo],[1,Lo]],rY=[[0,0],[.4,-190],[.5,-170],[.8,0],[1,0]],nY=[[0,1],[.4,1.6],[.5,1.6],[.8,.95],[1,1]],Ak=[[0,90],[.4,-20],[.6,10],[.8,-5],[1,0]],yk=[[0,0],[.6,1],[1,1]],OVe=[[0,0],[.3,-20],[1,90]],CVe=[[0,0],[.3,-15],[1,90]],vk=[[0,1],[.3,1],[1,0]],RVe={"fade-in":({progress:e})=>({alpha:e}),"fade-out":({progress:e})=>({alpha:1-e}),"fade-in-out":({progress:e,phase:t})=>t==="in"?{alpha:Et(e,$1e,Lo)}:{alpha:Et(e,eVe,Lo)},"fade-in-down":({progress:e,elh:t})=>({alpha:e,motion:{system:"relative",value:[0,(e-1)*t]}}),"fade-in-up":({progress:e,elh:t})=>({alpha:e,motion:{system:"relative",value:[0,(1-e)*t]}}),"fade-in-left":({progress:e,elw:t})=>({alpha:e,motion:{system:"relative",value:[(1-e)*t,0]}}),"fade-in-right":({progress:e,elw:t})=>({alpha:e,motion:{system:"relative",value:[(e-1)*t,0]}}),"fade-out-down":({progress:e,elh:t})=>({alpha:1-e,motion:{system:"relative",value:[0,e*t]}}),"fade-out-up":({progress:e,elh:t})=>({alpha:1-e,motion:{system:"relative",value:[0,-e*t]}}),"fade-out-left":({progress:e,elw:t})=>({alpha:1-e,motion:{system:"relative",value:[-e*t,0]}}),"fade-out-right":({progress:e,elw:t})=>({alpha:1-e,motion:{system:"relative",value:[e*t,0]}})},AVe={"slide-in-right":({progress:e,elw:t})=>{const o=gE("slide-in-right",e,t);return{motion:{system:"relative",value:o.motion},skew:o.skew,alpha:o.alpha}},"slide-in-left":({progress:e,elw:t})=>{const o=gE("slide-in-left",e,t);return{motion:{system:"relative",value:o.motion},skew:o.skew,alpha:o.alpha}},"slide-out-left":({progress:e,elw:t})=>{const o=gE("slide-out-left",e,t);return{motion:{system:"relative",value:o.motion},skew:o.skew,alpha:o.alpha}},"slide-out-right":({progress:e,elw:t})=>{const o=gE("slide-out-right",e,t);return{motion:{system:"relative",value:o.motion},skew:o.skew,alpha:o.alpha}}},yVe={"moving-in-up":({progress:e,cw:t,ch:o})=>{const r=pE(e),n=Math.hypot(t,o)*2;return{motion:{system:"absolute",value:[0,(1-r)*n],absoluteMotionScaleWithAnim:!1}}},"moving-in-down":({progress:e,cw:t,ch:o})=>{const r=pE(e),n=Math.hypot(t,o)*2;return{motion:{system:"absolute",value:[0,-(1-r)*n],absoluteMotionScaleWithAnim:!1}}},"moving-in-left":({progress:e,cw:t,ch:o})=>{const r=pE(e),n=Math.hypot(t,o)*2;return{motion:{system:"absolute",value:[(1-r)*n,0],absoluteMotionScaleWithAnim:!1}}},"moving-in-right":({progress:e,cw:t,ch:o})=>{const r=pE(e),n=Math.hypot(t,o)*2;return{motion:{system:"absolute",value:[-(1-r)*n,0],absoluteMotionScaleWithAnim:!1}}},"moving-out-up":({progress:e,cw:t,ch:o})=>{const r=fE(e),n=Math.hypot(t,o)*2;return{motion:{system:"absolute",value:[0,-r*n],absoluteMotionScaleWithAnim:!1}}},"moving-out-down":({progress:e,cw:t,ch:o})=>{const r=fE(e),n=Math.hypot(t,o)*2;return{motion:{system:"absolute",value:[0,r*n],absoluteMotionScaleWithAnim:!1}}},"moving-out-left":({progress:e,cw:t,ch:o})=>{const r=fE(e),n=Math.hypot(t,o)*2;return{motion:{system:"absolute",value:[-r*n,0],absoluteMotionScaleWithAnim:!1}}},"moving-out-right":({progress:e,cw:t,ch:o})=>{const r=fE(e),n=Math.hypot(t,o)*2;return{motion:{system:"absolute",value:[r*n,0],absoluteMotionScaleWithAnim:!1}}}},vVe={"rotate-in":({progress:e})=>{const t=zd("rotate-in",e);return{rotate:t.angle,alpha:t.alpha}},"rotate-in-down-left":({progress:e})=>{const t=zd("rotate-in-down-left",e);return{rotate:t.angle,alpha:t.alpha,origin:[0,1]}},"rotate-in-down-right":({progress:e})=>{const t=zd("rotate-in-down-right",e);return{rotate:t.angle,alpha:t.alpha,origin:[1,1]}},"rotate-out":({progress:e})=>{const t=zd("rotate-out",e);return{rotate:t.angle,alpha:t.alpha}},"rotate-out-down-left":({progress:e})=>{const t=zd("rotate-out-down-left",e);return{rotate:t.angle,alpha:t.alpha,origin:[0,1]}},"rotate-out-down-right":({progress:e})=>{const t=zd("rotate-out-down-right",e);return{rotate:t.angle,alpha:t.alpha,origin:[1,1]}}},wVe={"roll-in":({progress:e,elw:t})=>{const o=wk("roll-in",e,t);return{motion:{system:"relative",value:o.motion},rotate:o.angle,alpha:o.alpha}},"roll-out":({progress:e,elw:t})=>{const o=wk("roll-out",e,t);return{motion:{system:"relative",value:o.motion},rotate:o.angle,alpha:o.alpha}}},NVe={"focus-in":({progress:e})=>{const t=S0("focus-in",e);return{scale:t.scale,motion:{system:"relative",value:t.motion},alpha:t.alpha}},"focus-in-down":({progress:e})=>{const t=S0("focus-in-down",e);return{scale:t.scale,motion:{system:"absolute",value:t.motion},alpha:t.alpha}},"focus-in-left":({progress:e})=>{const t=S0("focus-in-left",e);return{scale:t.scale,motion:{system:"absolute",value:t.motion},alpha:t.alpha}},"focus-in-right":({progress:e})=>{const t=S0("focus-in-right",e);return{scale:t.scale,motion:{system:"absolute",value:t.motion},alpha:t.alpha}},"focus-in-up":({progress:e})=>{const t=S0("focus-in-up",e);return{scale:t.scale,motion:{system:"absolute",value:t.motion},alpha:t.alpha}},"focus-out":({progress:e})=>{const t=S0("focus-out",e);return{scale:t.scale,motion:{system:"relative",value:t.motion},alpha:t.alpha}},"focus-out-down":({progress:e})=>{const t=S0("focus-out-down",e);return{scale:t.scale,motion:{system:"absolute",value:t.motion},alpha:t.alpha,origin:[.5,1]}},"focus-out-left":({progress:e})=>{const t=S0("focus-out-left",e);return{scale:t.scale,motion:{system:"absolute",value:t.motion},alpha:t.alpha,origin:[0,.5]}},"focus-out-right":({progress:e})=>{const t=S0("focus-out-right",e);return{scale:t.scale,motion:{system:"absolute",value:t.motion},alpha:t.alpha,origin:[1,.5]}},"focus-out-up":({progress:e})=>{const t=S0("focus-out-up",e);return{scale:t.scale,motion:{system:"absolute",value:t.motion},alpha:t.alpha,origin:[.5,1]}}},aY={flip:({progress:e,elw:t,elh:o})=>{const r=Bd("flip",e),n=Yd(t,o,r.angle,r.axis);return{scale:r.scale,alpha:r.alpha,perspectiveCorners:n}},"flip-once":({progress:e,elw:t,elh:o})=>{const r=Bd("flip",e),n=Yd(t,o,r.angle,r.axis);return{scale:r.scale,alpha:r.alpha,perspectiveCorners:n}},"flip-in-x":({progress:e,elw:t,elh:o})=>{const r=Bd("flip-in-x",e),n=Yd(t,o,r.angle,r.axis);return{scale:r.scale,alpha:r.alpha,perspectiveCorners:n}},"flip-in-y":({progress:e,elw:t,elh:o})=>{const r=Bd("flip-in-y",e),n=Yd(t,o,r.angle,r.axis);return{scale:r.scale,alpha:r.alpha,perspectiveCorners:n}},"flip-out-x":({progress:e,elw:t,elh:o})=>{const r=Bd("flip-out-x",e),n=Yd(t,o,r.angle,r.axis);return{scale:r.scale,alpha:r.alpha,perspectiveCorners:n}},"flip-out-y":({progress:e,elw:t,elh:o})=>{const r=Bd("flip-out-y",e),n=Yd(t,o,r.angle,r.axis);return{scale:r.scale,alpha:r.alpha,perspectiveCorners:n}}},PVe=e=>typeof e=="string"&&Object.hasOwn(aY,e),bVe={popping:({progress:e})=>_s("popping",e),"popping-once":({progress:e})=>_s("popping-once",e),"popping-in":({progress:e})=>_s("popping-in",e),"popping-in-down":({progress:e})=>_s("popping-in-down",e),"popping-in-left":({progress:e})=>_s("popping-in-left",e),"popping-in-right":({progress:e})=>_s("popping-in-right",e),"popping-in-up":({progress:e})=>_s("popping-in-up",e),"popping-out":({progress:e})=>_s("popping-out",e),"popping-out-down":({progress:e})=>_s("popping-out-down",e),"popping-out-left":({progress:e})=>_s("popping-out-left",e),"popping-out-right":({progress:e})=>_s("popping-out-right",e),"popping-out-up":({progress:e})=>_s("popping-out-up",e)},LVe={tada:({progress:e})=>{const t=ui("tada",e);return{scale:t.scale,rotate:t.rotate,motion:{system:"relative",value:t.motion}}},"tada-once":({progress:e})=>{const t=ui("tada",e);return{scale:t.scale,rotate:t.rotate,motion:{system:"relative",value:t.motion}}},"shake-x":({progress:e})=>{const t=ui("shake-x",e);return{scale:t.scale,rotate:t.rotate,motion:{system:"absolute",value:t.motion}}},"shake-x-once":({progress:e})=>{const t=ui("shake-x",e);return{scale:t.scale,rotate:t.rotate,motion:{system:"absolute",value:t.motion}}},"shake-y":({progress:e})=>{const t=ui("shake-y",e);return{scale:t.scale,rotate:t.rotate,motion:{system:"absolute",value:t.motion}}},"shake-y-once":({progress:e})=>{const t=ui("shake-y",e);return{scale:t.scale,rotate:t.rotate,motion:{system:"absolute",value:t.motion}}},swing:({progress:e})=>{const t=ui("swing",e);return{scale:t.scale,rotate:t.rotate,motion:{system:"relative",value:t.motion},origin:[.5,0]}},"swing-once":({progress:e})=>{const t=ui("swing",e);return{scale:t.scale,rotate:t.rotate,motion:{system:"relative",value:t.motion},origin:[.5,0]}},"heart-beat":({progress:e})=>{const t=ui("heart-beat",e);return{scale:t.scale,rotate:t.rotate,motion:{system:"relative",value:t.motion}}},"heart-beat-once":({progress:e})=>{const t=ui("heart-beat",e);return{scale:t.scale,rotate:t.rotate,motion:{system:"relative",value:t.motion}}},"rubber-band":({progress:e})=>{const t=ui("rubber-band",e);return{scale:t.scale,rotate:t.rotate,motion:{system:"relative",value:t.motion}}},"rubber-band-once":({progress:e})=>{const t=ui("rubber-band",e);return{scale:t.scale,rotate:t.rotate,motion:{system:"relative",value:t.motion}}},"pop-in":({progress:e})=>{const t=ui("pop-in",e);return{alpha:t.alpha??1,scale:t.scale,rotate:t.rotate,motion:{system:"relative",value:t.motion},origin:[.5,1]}},"pop-in-once":({progress:e})=>{const t=ui("pop-in",e);return{alpha:t.alpha??1,scale:t.scale,rotate:t.rotate,motion:{system:"relative",value:t.motion},origin:[.5,1]}},blink:({progress:e})=>({alpha:Et(e,Ik,Lo)}),"blink-once":({progress:e})=>({alpha:Et(e,Ik,Lo)})},MVe={typing:()=>({}),typing_up:()=>({}),typing_down:()=>({})},DVe=()=>uE||(uE={...RVe,...AVe,...yVe,...vVe,...wVe,...NVe,...aY,...bVe,...LVe,...MVe},uE),kVe=(e,t,o,r,n,a,i,s=1)=>{const x=Math.max(1,Math.floor(o)),c=Math.max(1,Math.floor(r)),l=Math.max(1,Math.floor(a)),d=Math.max(1,Math.floor(i)),u=DVe()[e],p=u?.({variant:e,progress:t,phase:n,elw:x,elh:c,cw:l,ch:d})??{};return iY(p,s)},iY=(e,t)=>{const{motion:o}=e;if(!(o?.system==="absolute"&&o.absoluteMotionScaleWithAnim!==!1)||!o||t===1)return e;const[n,a]=o.value;return{...e,motion:{...o,value:[n*t,a*t]}}},gE=(e,t,o)=>{const r=Math.max(0,Math.min(1,t)),n=a=>a*Math.PI/180;switch(e){case"slide-in-right":{const a=Et(r,tVe,Ec)*o,i=Et(r,oVe,Ec),s=Et(r,rVe,Ec);return{motion:[a,0],skew:[n(i),0],alpha:s}}case"slide-in-left":{const a=Et(r,nVe,Ec)*o,i=Et(r,aVe,Ec),s=Et(r,iVe,Ec);return{motion:[a,0],skew:[n(i),0],alpha:s}}case"slide-out-left":{const a=Et(r,sVe,$a)*o,i=Et(r,xVe,$a),s=Et(r,Tk,$a);return{motion:[a,0],skew:[n(i),0],alpha:s}}case"slide-out-right":{const a=Et(r,cVe,$a)*o,i=Et(r,lVe,$a),s=Et(r,Tk,$a);return{motion:[a,0],skew:[n(i),0],alpha:s}}}return{motion:[0,0],skew:[0,0],alpha:1}},zd=(e,t)=>{const o=Math.max(0,Math.min(1,t));switch(e){case"rotate-in":{const r=Cp(-200,0,o);return{angle:ga(r),alpha:o}}case"rotate-in-down-left":{const r=Cp(45,0,o);return{angle:ga(r),alpha:o}}case"rotate-in-down-right":{const r=Cp(-45,0,o);return{angle:ga(r),alpha:o}}case"rotate-out":return{angle:ga(Zi(0,200,o)),alpha:1-o};case"rotate-out-down-left":{const r=Cp(0,-45,o);return{angle:ga(r),alpha:1-o}}case"rotate-out-down-right":{const r=Cp(0,45,o);return{angle:ga(r),alpha:1-o}}}return{angle:0,alpha:1}},XE=(e,t)=>{const o=Math.max(0,Math.min(1,e));let r=0;for(let n=0;n<t.length;n++){const a=t[n][0],i=t[n][1],s=Math.max(1e-6,a-r);if(o<=a){const x=(o-r)/s,c=i(x);return r+c*s}r=a}return 1},wk=(e,t,o)=>{const r=Math.max(0,Math.min(1,t));switch(e){case"roll-in":return{motion:[-(1-r)*o,0],angle:ga(Zi(-120,0,r)),alph
1244a:r};case"roll-out":return{motion:[r*o,0],angle:ga(Zi(0,120,r)),alpha:1-r}}return{motion:[0,0],angle:0,alpha:1}},S0=(e,t)=>{const o=Math.max(0,Math.min(1,t));switch(e){case"focus-in":return{scale:[Et(o,Sk,Lo),Et(o,Sk,Lo)],motion:[0,0],alpha:ts(Et(o,dVe,Lo))};case"focus-in-down":return _E({p:o,axis:"y",direction:-1});case"focus-in-left":return _E({p:o,axis:"x",direction:1});case"focus-in-right":return _E({p:o,axis:"x",direction:-1});case"focus-in-up":return _E({p:o,axis:"y",direction:1});case"focus-out":return{scale:[Et(o,Ok,Lo),Et(o,Ok,Lo)],motion:[0,0],alpha:ts(Et(o,uVe,Lo))};case"focus-out-down":return EE({p:o,axis:"y",overshoot:-60,exit:2e3,useDownUpTiming:!0});case"focus-out-left":return EE({p:o,axis:"x",overshoot:42,exit:-2e3,useDownUpTiming:!1});case"focus-out-right":return EE({p:o,axis:"x",overshoot:-42,exit:2e3,useDownUpTiming:!1});case"focus-out-up":return EE({p:o,axis:"y",overshoot:60,exit:-2e3,useDownUpTiming:!0})}return{scale:[1,1],motion:[0,0],alpha:1}},_E=({p:e,axis:t,direction:o})=>{let r,n,a;const i=t==="x"?10:60;if(e<=.6){const x=e/.6,c=oY(x);r=Zi(.1,.475,c),n=Zi(o*1e3,o===1?-i:i,c),a=ts(Zi(0,1,c))}else{const x=(e-.6)/.4,c=Z1e(x);r=Zi(.475,1,c),n=Zi(o===1?-i:i,0,c),a=1}return{scale:[r,r],motion:t==="x"?[n,0]:[0,n],alpha:a}},EE=({p:e,axis:t,overshoot:o,exit:r,useDownUpTiming:n})=>{let a,i,s;if(e<=.4){const c=e/.4,l=Lo(c);a=Zi(1,.475,l),i=Zi(0,o,l),s=1}else{const c=(e-.4)/.6,l=n?oY(c):Lo(c);a=Zi(.475,.1,l),i=Zi(o,r,l),s=ts(Zi(1,0,l))}return{scale:[a,a],motion:t==="x"?[i,0]:[0,i],alpha:s}},_s=(e,t)=>{const o=Math.max(0,Math.min(1,t)),r=s=>ts(Et(o,s,Lo)),n=s=>Et(o,s,Lo),a=s=>Et(o,s,Lo),i=s=>Et(o,s,Lo);switch(e){case"popping":case"popping-once":{const s=n(Uo.popping.scale);return{scale:[s,s],alpha:r(Uo.popping.alpha)}}case"popping-in":{const s=n(Uo["popping-in"].scale);return{scale:[s,s],alpha:r(Uo["popping-in"].alpha)}}case"popping-in-down":{const s=n(Uo["popping-in-down"].scale),x=i(Uo["popping-in-down"].motion);return{scale:[1,s],motion:{system:"absolute",value:[0,x],absoluteMotionScaleWithAnim:!1},alpha:r(Uo["popping-in-down"].alpha)}}case"popping-in-up":{const s=n(Uo["popping-in-up"].scale),x=i(Uo["popping-in-up"].motion);return{scale:[1,s],motion:{system:"absolute",value:[0,x],absoluteMotionScaleWithAnim:!1},alpha:r(Uo["popping-in-up"].alpha)}}case"popping-in-right":{const s=n(Uo["popping-in-right"].scale),x=a(Uo["popping-in-right"].motion);return{scale:[s,1],motion:{system:"absolute",value:[x,0],absoluteMotionScaleWithAnim:!1},alpha:r(Uo["popping-in-right"].alpha)}}case"popping-in-left":{const s=n(Uo["popping-in-left"].scale),x=a(Uo["popping-in-left"].motion);return{scale:[s,1],motion:{system:"absolute",value:[x,0],absoluteMotionScaleWithAnim:!1},alpha:r(Uo["popping-in-left"].alpha)}}case"popping-out":{const s=n(Uo["popping-out"].scale);return{scale:[s,s],alpha:r(Uo["popping-out"].alpha)}}case"popping-out-down":{const s=n(Uo["popping-out-down"].scale),x=i(Uo["popping-out-down"].motion);return{scale:[1,s],motion:{system:"absolute",value:[0,x],absoluteMotionScaleWithAnim:!1},alpha:r(Uo["popping-out-down"].alpha)}}case"popping-out-up":{const s=n(Uo["popping-out-up"].scale),x=i(Uo["popping-out-up"].motion);return{scale:[1,s],motion:{system:"absolute",value:[0,x],absoluteMotionScaleWithAnim:!1},alpha:r(Uo["popping-out-up"].alpha)}}case"popping-out-left":{const s=n(Uo["popping-out-left"].scale),x=a(Uo["popping-out-left"].motion);return{scale:[s,1],motion:{system:"absolute",value:[x,0],absoluteMotionScaleWithAnim:!1},alpha:r(Uo["popping-out-left"].alpha)}}case"popping-out-right":{const s=n(Uo["popping-out-right"].scale),x=a(Uo["popping-out-right"].motion);return{scale:[s,1],motion:{system:"absolute",value:[x,0],absoluteMotionScaleWithAnim:!1},alpha:r(Uo["popping-out-right"].alpha)}}}return{scale:[1,1],alpha:1}},ui=(e,t)=>{const o=Math.max(0,Math.min(1,t));switch(e){case"tada":{const r=Et(o,pVe,Lo),n=ga(Et(o,fVe,Lo));return{scale:[r,r],rotate:n,motion:[0,0]}}case"shake-x":{const r=Et(o,Ck,Lo);return{scale:[1,1],rotate:0,motion:[r,0]}}case"shake-y":{const r=Et(o,Ck,Lo);return{scale:[1,1],rotate:0,motion:[0,r]}}case"swing":{const r=Et(o,gVe,Lo);return{scale:[1,1],rotate:ga(r),motion:[0,0]}}case"heart-beat":{const r=Et(o,_Ve,Q1e);return{scale:[r,r],rotate:0,motion:[0,0]}}case"rubber-band":return{scale:[FVe(o),UVe(o)],rotate:0,motion:[0,0]};case"pop-in":{const r=Et(o,EVe,Lo),n=Et(o,mVe,Lo),a=Lo(o);return{scale:[r,r],rotate:ga(n),motion:[0,0],alpha:a}}case"blink":return{scale:[1,1],rotate:0,motion:[0,0]};case"flip":{const r=XE(o,TVe),n=Ti(r,rY),a=ga(n),i=Math.cos(a),s=Ti(r,nY);return{scale:[i*s,s],rotate:0,motion:[0,0]}}}return{scale:[1,1],rotate:0,motion:[0,0]}},FVe=e=>Et(e,hVe,Lo),UVe=e=>Et(e,IVe,Lo),sY=400,VVe=(e,t,o,r,n=sY)=>{const a=o*Math.PI/180,i=Math.sin(a),s=Math.cos(a),x=e/2,c=t/2,l=(f,E)=>{const T=r==="y"?[f*s,E,-f*i]:[f,E*s,E*i],O=1-T[2]/n;return[x*O+T[0],c*O+T[1],O]},d=l(-x,-c),u=l(x,-c),p=l(-x,c);return[u[0]-d[0],u[1]-d[1],u[2]-d[2],p[0]-d[0],p[1]-d[1],p[2]-d[2],d[0],d[1],d[2]]},Yd=(e,t,o,r,n=sY)=>{const a=o*Math.PI/180,i=Math.sin(a),s=Math.cos(a),x=e/2,c=t/2,l=d=>{const u=Math.min(d,n*.95);return n/(n-u)};if(r==="y"){const d=x*i,u=-x*i,p=l(d),f=l(u),E=-x*s*p,T=x*s*f,O=-c*p,S=c*p,R=-c*f,y=c*f;return{topLeft:[x+E,c+O],topRight:[x+T,c+R],bottomRight:[x+T,c+y],bottomLeft:[x+E,c+S]}}else{const d=-c*i,u=c*i,p=l(d),f=l(u),E=-c*s*p,T=c*s*f,O=-x*p,S=x*p,R=-x*f,y=x*f;return{topLeft:[x+O,c+E],topRight:[x+S,c+E],bottomRight:[x+y,c+T],bottomLeft:[x+R,c+T]}}},Bd=(e,t)=>{const o=Math.max(0,Math.min(1,t));switch(e){case"flip":{const r=XE(o,SVe),n=Ti(r,rY),a=Ti(r,nY);return{scale:[a,a],alpha:1,angle:n,axis:"y"}}case"flip-in-x":{const r=XE(o,Rk),n=Ti(r,Ak),a=ga(n),i=Math.max(.001,Math.abs(Math.cos(a))),s=ts(Ti(r,yk));
1244return{scale:[1,i],alpha:s,angle:n,axis:"x"}}case"flip-in-y":{const r=XE(o,Rk),n=Ti(r,Ak),a=ga(n),i=Math.max(.001,Math.abs(Math.cos(a))),s=ts(Ti(r,yk));return{scale:[i,1],alpha:s,angle:n,axis:"y"}}case"flip-out-x":{const r=Et(o,OVe,Lo),n=ga(r),a=Math.max(.001,Math.abs(Math.cos(n))),i=ts(Et(o,vk,Lo));return{scale:[1,a],alpha:i,angle:r,axis:"x"}}case"flip-out-y":{const r=Et(o,CVe,Lo),n=ga(r),a=Math.max(.001,Math.abs(Math.cos(n))),i=ts(Et(o,vk,Lo));return{scale:[a,1],alpha:i,angle:r,axis:"y"}}}return{scale:[1,1],alpha:1,angle:0,axis:"y"}},GVe=(e,t,o)=>{if(t.eq(X.zero()))return 0;const r=e.sub(o);if(r.as.ms("raw")<=0)return 0;const n=t.as.ms("raw");return ts(r.as.ms("raw")/n)},WVe=[[0,0],[.8,360],[1,360]],HVe=[[0,.6],[.8,1],[1,1]],Nk=Bn(.25,.1,.25,1),jVe=e=>{const t=ts(e),o=Et(t,WVe,Nk);return{alpha:Et(t,HVe,Nk),rotateXDeg:o}},zVe={webAssetId:"a-0190-flip-x",animationDuration:X.fromSec(1),getProgress:GVe,getUniforms:jVe,perspective:{axis:"x",em:20}},xY=43758.5453123,cY=127.1,lY=311.7,dY=269.5,uY=183.3,pY=6.283185307179586,fY=8,iS=8,gY=.4155,_Y=.8,YVe=()=>`
1245float dfract(float x) { return x - floor(x); }
1246
1247float hash21(vec2 p, float seed) {
1248  vec2 ps = p + vec2(seed * 0.137);
1249  float d = ps.x * `+cY.toFixed(1)+" + ps.y * "+lY.toFixed(1)+`;
1250  return dfract(sin(d) * `+xY+`);
1251}
1252
1253float dfade(float t) { return t * t * t * (t * (t * 6.0 - 15.0) + 10.0); }
1254
1255float valueNoise2D(vec2 p, float seed) {
1256  vec2 ip = floor(p);
1257  vec2 fp = p - ip;
1258  float a = hash21(ip, seed);
1259  float b = hash21(ip + vec2(1.0, 0.0), seed);
1260  float c = hash21(ip + vec2(0.0, 1.0), seed);
1261  float d = hash21(ip + vec2(1.0, 1.0), seed);
1262  float ux = dfade(fp.x);
1263  float uy = dfade(fp.y);
1264  return mix(mix(a, b, ux), mix(c, d, ux), uy);
1265}
1266
1267float turbulence2D(vec2 p, float freq, int octaves, float seed) {
1268  float sum = 0.0;
1269  float amp = 1.0;
1270  float ampSum = 0.0;
1271  float f = freq;
1272  for (int i = 0; i < `+iS+`; i++) {
1273    if (i >= octaves) break;
1274    float signedN = abs(2.0 * valueNoise2D(p * f, seed) - 1.0);
1275    sum += signedN * amp;
1276    ampSum += amp;
1277    amp *= 0.5;
1278    f *= 2.0;
1279  }
1280  float channel = 0.5 + `+_Y+" * (sum - "+gY+` * ampSum);
1281  return clamp(channel, 0.0, 1.0);
1282}
1283
1284vec2 displacementVector(vec2 p, float freq, int octaves, float seed, float phase, bool decorrelate) {
1285  float angle = `+pY+` * phase;
1286  vec2 o = vec2(cos(angle), sin(angle)) * `+fY.toFixed(1)+`;
1287  float nx = turbulence2D(vec2(p.x + o.x, p.y + o.y), freq, octaves, seed);
1288  if (!decorrelate) {
1289    return vec2(nx - 0.5, nx - 0.5);
1290  }
1291  float ny = turbulence2D(
1292    vec2(p.x + o.x + `+dY.toFixed(1)+", p.y + o.y + "+uY.toFixed(1)+`),
1293    freq, octaves, seed);
1294  return vec2(nx - 0.5, ny - 0.5);
1295}
1296`,BVe=()=>`
1297fn dfract(x: f32) -> f32 { return x - floor(x); }
1298
1299fn hash21(p: vec2<f32>, seed: f32) -> f32 {
1300  let ps = p + vec2<f32>(seed * 0.137);
1301  let d = ps.x * `+cY.toFixed(1)+" + ps.y * "+lY.toFixed(1)+`;
1302  return dfract(sin(d) * `+xY+`);
1303}
1304
1305fn dfade(t: f32) -> f32 { return t * t * t * (t * (t * 6.0 - 15.0) + 10.0); }
1306
1307fn valueNoise2D(p: vec2<f32>, seed: f32) -> f32 {
1308  let ip = floor(p);
1309  let fp = p - ip;
1310  let a = hash21(ip, seed);
1311  let b = hash21(ip + vec2<f32>(1.0, 0.0), seed);
1312  let c = hash21(ip + vec2<f32>(0.0, 1.0), seed);
1313  let d = hash21(ip + vec2<f32>(1.0, 1.0), seed);
1314  let ux = dfade(fp.x);
1315  let uy = dfade(fp.y);
1316  return mix(mix(a, b, ux), mix(c, d, ux), uy);
1317}
1318
1319fn turbulence2D(p: vec2<f32>, freq: f32, octaves: i32, seed: f32) -> f32 {
1320  var sum = 0.0;
1321  var amp = 1.0;
1322  var ampSum = 0.0;
1323  var f = freq;
1324  for (var i = 0; i < `+iS+`; i = i + 1) {
1325    if (i >= octaves) { break; }
1326    let signedN = abs(2.0 * valueNoise2D(p * f, seed) - 1.0);
1327    sum = sum + signedN * amp;
1328    ampSum = ampSum + amp;
1329    amp = amp * 0.5;
1330    f = f * 2.0;
1331  }
1332  let channel = 0.5 + `+_Y+" * (sum - "+gY+` * ampSum);
1333  return clamp(channel, 0.0, 1.0);
1334}
1335
1336fn displacementVector(p: vec2<f32>, freq: f32, octaves: i32, seed: f32, phase: f32, decorrelate: bool) -> vec2<f32> {
1337  let angle = `+pY+` * phase;
1338  let o = vec2<f32>(cos(angle), sin(angle)) * `+fY.toFixed(1)+`;
1339  let nx = turbulence2D(vec2<f32>(p.x + o.x, p.y + o.y), freq, octaves, seed);
1340  if (!decorrelate) {
1341    return vec2<f32>(nx - 0.5, nx - 0.5);
1342  }
1343  let ny = turbulence2D(
1344    vec2<f32>(p.x + o.x + `+dY.toFixed(1)+", p.y + o.y + "+uY.toFixed(1)+`),
1345    freq, octaves, seed);
1346  return vec2<f32>(nx - 0.5, ny - 0.5);
1347}
1348`,Os="uDispParams",Ql="uDispOctaves",Zl="uDispDecorrelate",EY=e=>({baseFrequency:e.baseFrequency,numOctaves:Math.max(1,Math.min(iS,Math.floor(e.numOctaves))),scale:e.scale,seed:e.seed,phase:e.progressPhase??0,decorrelate:e.decorrelate??!1}),KVe=(e,t)=>e/t,XVe=(e,t)=>e*t,JVe=2,uh=4,qVe=e=>!Number.isFinite(e)||e===0?uh:Math.max(uh,Math.ceil(Math.abs(e)/2)+JVe);class mY extends hd{_uniforms;constructor(){const t=new sd({[Os]:{value:new Float32Array(4),type:"vec4<f32>"},[Ql]:{value:5,type:"i32"},[Zl]:{value:0,type:"i32"}});super({glProgram:new cl({vertex:QVe(),fragment:ZVe(),name:"Displacement_GL"}),gpuProgram:new xl({name:"Displacement_GPU",vertex:{source:Pk(),entryPoint:"mainVertex"},fragment:{source:Pk(),entryPoint:"mainFragment"}}),resources:{filterUniforms:t},padding:uh}),this._uniforms=t}update(t,o,r,n){const a=t.displacementMap,i=this._uniforms.uniforms[Os];if(!a||a.scale===0){i[0]=0,i[1]=0,i[2]=0,i[3]=0,this._uniforms.uniforms[Ql]=1,this._uniforms.uniforms[Zl]=0,this.padding=uh;return}const s=Math.abs(n.layout.scale?.x??1)||1,x=XVe(a.baseFrequency,s),c=KVe(a.scale,s);i[0]=x,i[1]=c,i[2]=a.seed,i[3]=a.phase,this._uniforms.uniforms[Ql]=Math.max(1,Math.min(iS,Math.floor(a.numOctaves))),this._uniforms.uniforms[Zl]=a.decorrelate?1:0,this.padding=qVe(c)}}const QVe=()=>`
1349#version 300 es
1350precision highp float;
1351
1352layout(location = 0) in vec2 aPosition;
1353
1354out vec2 vTextureCoord;
1355
1356uniform vec4 uInputSize;
1357uniform vec4 uOutputFrame;
1358uniform vec4 uOutputTexture;
1359
1360vec4 filterVertexPosition(void) {
1361    vec2 position = aPosition * uOutputFrame.zw + uOutputFrame.xy;
1362    position.x = position.x * (2.0 / uOutputTexture.x) - 1.0;
1363    position.y = position.y * (2.0*uOutputTexture.z / uOutputTexture.y) - uOutputTexture.z;
1364    return vec4(position, 0.0, 1.0);
1365}
1366
1367vec2 filterTextureCoord(void) {
1368    return aPosition * (uOutputFrame.zw * uInputSize.zw);
1369}
1370
1371void main(void) {
1372    gl_Position = filterVertexPosition();
1373    vTextureCoord = filterTextureCoord();
1374}
1375`,ZVe=()=>`
1376#version 300 es
1377precision highp float;
1378
1379in vec2 vTextureCoord;
1380out vec4 fragColor;
1381
1382uniform sampler2D uTexture;
1383// (w, h, 1/w, 1/h) of the padded filter-input RT. The displacement is computed
1384// in RT texel space (vTextureCoord × uInputSize.xy) then converted back to the
1385// normalised uv via uInputSize.zw, so the remap is decoupled from padding/Po2.
1386uniform vec4 uInputSize;
1387// (minX, minY, maxX, maxY) clamp of the input frame in normalised uv. The
1388// displaced uv is clamped to this so the remap never bleeds outside the sprite.
1389uniform vec4 uInputClamp;
1390uniform vec4 `+Os+`; // (freq, scalePx, seed, phase)
1391uniform int `+Ql+`;
1392uniform int `+Zl+`; // 0 = same-channel (SVG A/A); 1 = decorrelated R/G
1393
1394`+YVe()+`
1395
1396void main() {
1397    float freq = `+Os+`.x;
1398    float scalePx = `+Os+`.y;
1399    float seed = `+Os+`.z;
1400    float phase = `+Os+`.w;
1401
1402    if (scalePx == 0.0) {
1403        fragColor = texture(uTexture, vTextureCoord);
1404        return;
1405    }
1406
1407    // Noise sampled in RT texel space so baseFrequency reads as cycles/px.
1408    vec2 texel = vTextureCoord * uInputSize.xy;
1409    vec2 disp = displacementVector(texel, freq, `+Ql+", seed, phase, "+Zl+` != 0);
1410    // feDisplacementMap: displacement = scale * (channel - 0.5); disp already
1411    // carries the (channel - 0.5) term, so multiply by scalePx then back to uv.
1412    vec2 offsetUv = disp * scalePx * uInputSize.zw;
1413    vec2 sampleUv = clamp(vTextureCoord + offsetUv, uInputClamp.xy, uInputClamp.zw);
1414    // Premultiplied passthrough: a UV remap re-samples premultiplied texels and
1415    // emits them unchanged, so no un/re-premultiply is needed.
1416    fragColor = texture(uTexture, sampleUv);
1417}
1418`,Pk=()=>`
1419struct GlobalFilterUniforms {
1420  uInputSize:vec4<f32>,
1421  uInputPixel:vec4<f32>,
1422  uInputClamp:vec4<f32>,
1423  uOutputFrame:vec4<f32>,
1424  uGlobalFrame:vec4<f32>,
1425  uOutputTexture:vec4<f32>,
1426};
1427
1428struct DisplacementUniforms {
1429  `+Os+`: vec4<f32>,
1430  `+Ql+`: i32,
1431  `+Zl+`: i32,
1432};
1433
1434@group(0) @binding(0) var<uniform> gfu: GlobalFilterUniforms;
1435@group(0) @binding(1) var uTexture: texture_2d<f32>;
1436@group(0) @binding(2) var uSampler: sampler;
1437
1438@group(1) @binding(0) var<uniform> disp: DisplacementUniforms;
1439
1440struct VSOutput {
1441    @builtin(position) position: vec4<f32>,
1442    @location(0) uv : vec2<f32>,
1443};
1444
1445fn filterVertexPosition(aPosition:vec2<f32>) -> vec4<f32> {
1446    var position = aPosition * gfu.uOutputFrame.zw + gfu.uOutputFrame.xy;
1447    position.x = position.x * (2.0 / gfu.uOutputTexture.x) - 1.0;
1448    position.y = position.y * (2.0*gfu.uOutputTexture.z / gfu.uOutputTexture.y) - gfu.uOutputTexture.z;
1449    return vec4(position, 0.0, 1.0);
1450}
1451
1452fn filterTextureCoord(aPosition:vec2<f32>) -> vec2<f32> {
1453    return aPosition * (gfu.uOutputFrame.zw * gfu.uInputSize.zw);
1454}
1455
1456@vertex
1457fn mainVertex(@location(0) aPosition: vec2<f32>) -> VSOutput {
1458  return VSOutput(filterVertexPosition(aPosition), filterTextureCoord(aPosition));
1459}
1460
1461`+BVe()+`
1462
1463@fragment
1464fn mainFragment(
1465  @builtin(position) position: vec4<f32>,
1466  @location(0) uv: vec2<f32>,
1467) -> @location(0) vec4<f32> {
1468  let freq = disp.`+Os+`.x;
1469  let scalePx = disp.`+Os+`.y;
1470  let seed = disp.`+Os+`.z;
1471  let phase = disp.`+Os+`.w;
1472
1473  if (scalePx == 0.0) {
1474    return textureSample(uTexture, uSampler, uv);
1475  }
1476
1477  let texel = uv * gfu.uInputSize.xy;
1478  let d = displacementVector(texel, freq, disp.`+Ql+", seed, phase, disp."+Zl+` != 0);
1479  let offsetUv = d * scalePx * gfu.uInputSize.zw;
1480  let sampleUv = clamp(uv + offsetUv, gfu.uInputClamp.xy, gfu.uInputClamp.zw);
1481  // Premultiplied passthrough (see GL counterpart): a UV remap re-samples
1482  // premultiplied texels and emits them unchanged.
1483  return textureSample(uTexture, uSampler, sampleUv);
1484}
1485`,$Ve=(e,t,o)=>{if(t.eq(X.zero()))return 0;const r=e.sub(o);if(r.as.ms("raw")<=0)return 0;const n=t.as.ms("raw");return r.as.ms("raw")%n/n},eGe=.02,tGe=5,bk=2,oGe=18.75,ph=e=>e/oGe,rGe=[103/255,243/255,218/255,1],nGe=[241/255,111/255,111/255,1],aGe=[ph(2.5),ph(1)],iGe=[ph(-1),ph(-2)],Lk=0,sGe=.25,xGe=.4,cGe=.5,lGe=.55,hY=1,dGe=2,EC={baseFrequency:eGe,numOctaves:tGe,scale:0,seed:hY},Mk=(e,t,o)=>e>=t&&e<o,uGe=e=>{const t=Mk(e,sGe,xGe),o=Mk(e,cGe,lGe),r=t?{...EC,scale:bk,seed:hY}:o?{...EC,scale:bk,seed:dGe}:EC;return{displacementMap:EY(r),shadowLayers:[{offset:aGe,blur:Lk,color:rGe,strength:t?1:0},{offset:iGe,blur:Lk,color:nGe,strength:o?1:0}]}},pGe={webAssetId:"a-0110-glitch",animationDuration:X.fromSec(.5),getProgress:$Ve,getUniforms:uGe},IY=(e,t,o)=>{if(t.eq(X.zero()))return 0;const r=X.max(X.zero(),e.sub(o)),n=X.min(r,t);return js(n.as.ms("raw")/t.as.ms("raw"),0,1)},fGe=(e,t,o)=>{if(t.eq(X.zero()))return 0;const r=X.max(X.zero(),e.sub(o)),n=r.mod(t);return js(n.as.ms("raw")/t.as.ms("raw"),0,1)},gGe=Bn(.25,.1,.25,1),_Ge=e=>{const t=js(e,0,1);return{motion:{system:"layer-relative",value:[Et(t,[[0,-.75],[.6,0],[1,0]],gGe),0]}}},EGe={webAssetId:"a-0230-gradient-expand#bg",animationDuration:X.fromSec(1),getProgress:IY,getUniforms:_Ge},mGe=Bn(.25,.1,.25,1),hGe=e=>{const t=js(e,0,1);return{alpha:Et(t,[[0,0],[.3,0],[.6,1],[1,1]],mGe)}},IGe={webAssetId:"a-0230-gradient-expand#text",animationDuration:X.fromSec(1),getProgress:IY,getUniforms:hGe},Rp=Bn(.25,.1,.25,1),TGe=(e,t,o)=>{if(t.eq(X.zero()))return 0;const r=e.sub(o);if(r.as.ms("raw")<=0)return 0;const n=t.as.ms("raw");return r.as.ms("raw")%n/n},SGe=[[0,0],[.15,-.1],[.3,-.2],[.7,-.2],[.85,-.1],[1,0]],OGe=[[0,0],[.15,1],[.3,1],[.7,
14851],[.85,1],[1,0]],CGe=[[0,0],[.15,0],[.3,1],[.7,1],[.85,0],[1,0]],RGe=[[0,0],[.15,.1],[.3,.1],[.7,.1],[.85,.1],[1,0]],AGe=[[0,0],[.15,0],[.3,.2],[.7,.2],[.85,0],[1,0]],Dk=[0,0,0,0],yGe=(e,t)=>{const o=Et(e,OGe,Rp),r=Et(e,CGe,Rp),n=Et(e,RGe,Rp),a=Et(e,AGe,Rp),i=[{offset:[a,a],blur:0,color:Dk,strength:r,colorRole:"shadow2"},{offset:[n,n],blur:0,color:Dk,strength:o,colorRole:"shadow1"}];if(t===void 0)return{shadowLayers:i};const s=Et(e,SGe,Rp),x=s*t;return{shadowLayers:i,motion:{system:"absolute",value:[x,x]}}},vGe={webAssetId:"a-0160-grow",animationDuration:X.fromSec(.5),getProgress:TGe,getUniforms:yGe,graphicColorRoles:{shadow1:"--text-color-2",shadow2:"--text-color-3"}},wGe=(e,t,o)=>{if(t.eq(X.zero()))return 0;const r=e.sub(o);if(r.as.ms("raw")<=0)return 0;const n=t.as.ms("raw");return r.as.ms("raw")%n/n},kk=[.04,.1,.1,.14],mC=kk.map((e,t)=>Math.sqrt(kk.slice(0,t+1).reduce((o,r)=>o+r*r,0))),NGe=["core","core","glow","glow"],PGe=[0,0,0,0],bGe=[[.8,1],[.84,.7048],[.88,.3175],[.92,.1148],[.96,.0244],[1,0]],mE=(e,t,o)=>{if(e<=.8)return Ti(e,[[0,t],[.8,o]]);const r=Ti(e,bGe);return t+(o-t)*r},LGe=e=>{const t=mE(e,1,1),o=mE(e,0,1),r=mE(e,.8,1.2),n=mE(e,0,1.2),a=[t,o,r,n],i=mC.length;return{shadowLayers:mC.map((s,x)=>{const c=i-1-x;return{offset:[0,0],blur:mC[c],color:PGe,strength:a[c],colorRole:NGe[c]}})}},MGe={webAssetId:"a-0150-neon",animationDuration:X.fromSec(.8),getProgress:wGe,getUniforms:LGe,graphicColorRoles:{core:"#FFFFFF",glow:"--shadow-color"}},DGe=(e,t,o)=>{if(t.eq(X.zero()))return 0;const r=e.sub(o);if(r.as.ms("raw")<=0)return 0;const n=t.as.ms("raw");return r.as.ms("raw")%n/n},kGe=e=>{const t=Ti(e,[[0,1],[.1,-1],[.2,-3],[.3,3],[.4,1],[.5,-1],[.6,-3],[.7,3],[.8,-1],[.9,1],[1,1]]),o=Ti(e,[[0,1],[.1,-2],[.2,0],[.3,2],[.4,-1],[.5,2],[.6,1],[.7,1],[.8,-1],[.9,2],[1,-2]]);return{motion:{system:"absolute",value:[t,o]}}},FGe={webAssetId:"a-0130-rage",animationDuration:X.fromSec(.5),getProgress:DGe,getUniforms:kGe},UGe=Bn(.25,.1,.25,1),VGe=(e,t,o)=>{if(t.eq(X.zero()))return 0;const r=X.max(X.zero(),e.sub(o)),n=X.min(r,t);return js(n.as.ms("raw")/t.as.ms("raw"),0,1)},GGe=e=>{const t=js(e,0,1),o=Et(t,[[0,.66],[.6,1],[1,1]],UGe);return{scale:[o,o]}},WGe={webAssetId:"a-0180-scale-cartoon",animationDuration:X.fromSec(1.6),getProgress:VGe,getUniforms:GGe},HGe=Bn(.25,.1,.25,1),jGe=(e,t,o)=>{if(t.eq(X.zero()))return 0;const r=X.max(X.zero(),e.sub(o)),n=r.mod(t);return js(n.as.ms("raw")/t.as.ms("raw"),0,1)},zGe=e=>{const t=js(e,0,1),o=Et(t,[[0,.66],[.35,1],[.5,.94],[.65,1],[1,.66]],HGe);return{scale:[o,o]}},YGe={webAssetId:"a-0181-scale-cartoon-loop",animationDuration:X.fromSec(.8),getProgress:jGe,getUniforms:zGe},hC=Bn(.25,.1,.25,1),BGe=(e,t,o)=>{if(t.eq(X.zero()))return 0;const r=e.sub(o);if(r.as.ms("raw")<=0)return 0;const n=t.as.ms("raw");return r.as.ms("raw")%n/n},KGe=[[0,.8],[.4,.96],[.45,1],[.75,1],[.8,.97],[1,.8]],XGe=[[0,.08],[.4,.04],[.45,0],[.75,0],[.8,.04],[1,.08]],JGe=.01,qGe=[[0,.01],[.8,.01],[1,.02]],Fk=[0,0,0,0],QGe=e=>{const t=Et(e,KGe,hC),o=Et(e,XGe,hC),r=Et(e,qGe,hC),n=[{offset:[o,0],blur:JGe,color:Fk,strength:1},{offset:[-o,0],blur:r,color:Fk,strength:1}];return{scale:[t,1],shadowLayers:n}},ZGe={webAssetId:"a-0170-scale-x",animationDuration:X.fromSec(.5),getProgress:BGe,getUniforms:QGe,graphicColorRoles:{shadow:"--text-color"}},$Ge=(e,t)=>js(e.as.ms("raw")/t.as.ms("raw"),0,1),eWe=(e,t,o)=>{if(t.eq(X.zero()))return 0;const r=X.max(X.zero(),e.sub(o)),n=X.min(r,t);return $Ge(n,t)},tWe=e=>{const t=js(e,0,1),o=Ti(t,[[0,1],[.7,.5],[.9,0],[1,0]]),r=Ti(t,[[0,.5],[.7,1.2],[.9,1.5],[1,1.5]]);return{alpha:o,scale:[r,r]}},oWe={webAssetId:"a-0140-shout",animationDuration:X.fromSec(.7),getProgress:eWe,getUniforms:tWe},IC=Bn(.25,.1,.25,1),rWe=(e,t,o)=>{const r=t.as.ms("raw");if(r<=0)return 0;const n=Math.max(0,e.as.ms("raw")-o.as.ms("raw"));return Math.min(n,r)/r},nWe=e=>{const t=ts(e),o=Et(t,[[0,.6],[.8,1],[1,1]],IC),r=Et(t,[[0,0],[.8,ga(-15)],[1,0]],IC),n=Et(t,[[0,0],[.8,-.3],[1,0]],IC);return{alpha:o,skew:[r,0],scale:[1,1/Math.cos(r)],origin:[.5,1],motion:{system:"em",value:[n,0]}}},aWe={webAssetId:"a-0200-skew-x",contentSelector:".textarea",animationDuration:X.fromSec(1),getProgress:rWe,getUniforms:nWe},iWe=Bn(.25,.1,.25,1),sWe=(e,t,o)=>{if(t.eq(X.zero()))return 0;const r=e.sub(o);if(r.as.ms("raw")<=0)return 0;const n=t.as.ms("raw");return r.as.ms("raw")%n/n},xWe=60,cWe=2.5,lWe=[[0,1],[1,0]],TC=[0,0,0,0],dWe=e=>{const t=Et(e,lWe,iWe);
1485return{gradientSweep:{angle:xWe,stops:[{pos:.42,color:TC,colorRole:"backdrop"},{pos:.5,color:TC,colorRole:"spotlight"},{pos:.58,color:TC,colorRole:"backdrop"}],phase:t,scale:cWe}}},uWe={webAssetId:"a-0210-spotlight",animationDuration:X.fromSec(2),getProgress:sWe,getUniforms:dWe,bakeNeutralizeFill:"#fff",graphicColorRoles:{backdrop:"--backdrop-color",spotlight:"--spotlight-color"}},pWe=(e,t,o)=>{if(t.eq(X.zero()))return 0;const r=e.sub(o);if(r.as.ms("raw")<=0)return 0;const n=t.as.ms("raw");return r.as.ms("raw")%n/n},fWe=.01,gWe=5,_We=2,SC=[1,2,3,4,5],EWe=e=>{const t=Math.max(0,Math.min(1,e)),o=Math.min(SC.length-1,Math.floor(t*SC.length));return SC[o]},mWe=e=>{const t={baseFrequency:fWe,numOctaves:gWe,scale:_We,seed:EWe(e)};return{displacementMap:EY(t)}},hWe={webAssetId:"a-0100-squiggly",animationDuration:X.fromSec(.5),getProgress:pWe,getUniforms:mWe},OC=Bn(.25,.1,.25,1),IWe=e=>{const t=js(e,0,1),o=Et(t,[[0,.5],[.6,1],[.8,1],[1,.9]],OC),r=Et(t,[[0,.94],[.6,1],[.8,1],[1,1]],OC),n=Et(t,[[0,0],[.6,.3],[.8,.4],[1,.4]],OC);return{alpha:o,scale:[r,r],motion:{system:"em",value:[n,-n]}}},TWe={webAssetId:"a-0220-sweat#droplet",animationDuration:X.fromSec(.3),getProgress:fGe,getUniforms:IWe};var dn=(e=>(e.SHOUT="shout",e.SCALE_CARTOON="scale-cartoon",e.SCALE_CARTOON_LOOP="scale-cartoon-loop",e.SKEW_X="skew-x",e.RAGE="rage",e.NEON="neon",e.GROW="grow",e.SCALE_X="scale-x",e.SPOTLIGHT="spotlight",e.SQUIGGLY="squiggly",e.GLITCH="glitch",e.WAVY_BACKGROUND="wavy-background",e.FLIP_X="flip-x",e.SWEAT_DROPLET="sweat-droplet",e.GRADIENT_EXPAND_TEXT="gradient-expand-text",e.GRADIENT_EXPAND_BG="gradient-expand-bg",e))(dn||{}),su=(e=>(e.SWEAT="sweat",e.GRADIENT_EXPAND="gradient-expand",e))(su||{});const Cs="uBgScroll",Xu="uBgColors",$i=4,SWe=.75,OWe=.5,yP=.75,CWe="#000",TY=[135,225,315,45],SY=[0,0,1,1],OY=[-.5,-.5,0,0],RWe=(e,t)=>{const o="bg"+(e+1),r=t?.[o];return r?[r[0],r[1],r[2]]:[0,0,0]};class CY extends hd{_uniforms;constructor(){const t=new sd({[Cs]:{value:new Float32Array(4),type:"vec4<f32>"},[Xu]:{value:new Float32Array($i*4),type:"vec4<f32>",size:$i}});super({glProgram:new cl({vertex:bWe(),fragment:LWe(),name:"BackgroundScroll_GL"}),gpuProgram:new xl({name:"BackgroundScroll_GPU",vertex:{source:Uk(),entryPoint:"mainVertex"},fragment:{source:Uk(),entryPoint:"mainFragment"}}),resources:{filterUniforms:t}}),this._uniforms=t}update(t,o,r,n){const a=t.backgroundScroll,i=this._uniforms.uniforms[Cs],s=this._uniforms.uniforms[Xu],x=Math.abs(n.layout.scale?.x??1)||1,c=yP*o*x,l=OWe*o*x;i[0]=a?.offsetGroupA??0,i[1]=a?.offsetGroupB??0,i[2]=c,i[3]=l;for(let d=0;d<$i;d++){const u=RWe(d,r),p=d*4;s[p+0]=u[0],s[p+1]=u[1],s[p+2]=u[2],s[p+3]=SWe}}}const RY=e=>(e*Math.PI/180).toFixed(6),AWe=()=>TY.map((e,t)=>"    layerAngle["+t+"] = "+RY(e)+";").join(`
1486`),yWe=()=>SY.map((e,t)=>"    layerGroup["+t+"] = "+e+";").join(`
1487`),vWe=()=>OY.map((e,t)=>"    layerInitialEm["+t+"] = "+e.toFixed(6)+";").join(`
1488`),wWe=()=>"array<f32, "+$i+">("+TY.map(RY).join(", ")+")",NWe=()=>"array<i32, "+$i+">("+SY.join(", ")+")",PWe=()=>"array<f32, "+$i+">("+OY.map(e=>e.toFixed(6)).join(", ")+")",bWe=()=>`
1489#version 300 es
1490precision highp float;
1491
1492layout(location = 0) in vec2 aPosition;
1493
1494out vec2 vTextureCoord;
1495out vec2 vNormCoord;
1496out vec2 vBoxSize;
1497
1498uniform vec4 uInputSize;
1499uniform vec4 uOutputFrame;
1500uniform vec4 uOutputTexture;
1501
1502vec4 filterVertexPosition(void) {
1503    vec2 position = aPosition * uOutputFrame.zw + uOutputFrame.xy;
1504    position.x = position.x * (2.0 / uOutputTexture.x) - 1.0;
1505    position.y = position.y * (2.0*uOutputTexture.z / uOutputTexture.y) - uOutputTexture.z;
1506    return vec4(position, 0.0, 1.0);
1507}
1508
1509vec2 filterTextureCoord(void) {
1510    return aPosition * (uOutputFrame.zw * uInputSize.zw);
1511}
1512
1513void main(void) {
1514    gl_Position = filterVertexPosition();
1515    vTextureCoord = filterTextureCoord();
1516    vNormCoord = aPosition;
1517    // Filter-frame pixel size of the glyph texture. The per-layer diagonal axis
1518    // is projected in this pixel space so the tile period (px) reads as a true
1519    // length and the stripe angle is aspect-invariant.
1520    vBoxSize = uOutputFrame.zw;
1521}
1522`,LWe=()=>`
1523#version 300 es
1524precision highp float;
1525
1526in vec2 vTextureCoord;
1527in vec2 vNormCoord;
1528in vec2 vBoxSize;
1529out vec4 fragColor;
1530
1531uniform sampler2D uTexture;
1532uniform vec4 `+Cs+`; // (offsetGroupA, offsetGroupB, tilePx, solidPx)
1533uniform vec4 `+Xu+"["+$i+`]; // rgb + 0.75 stripe alpha
1534
1535// One diagonal-mosaic layer's color contribution. background-size:0.75em + repeat
1536// tiles the gradient into 0.75em square cells, each resetting the gradient — so
1537// the pixel is folded into ONE cell first, then the cell-local diagonal gradient
1538// is evaluated (NOT a continuous dot(boxPx,dir) projection, which would paint a
1539// band straight across the box). background-position-x slides the cell grid along
1540// SCREEN x by offsetTiles tile-widths, so boxPx.x shifts by offsetTiles*tilePx
1541// before the fold. Cell axis dir = (sin a, -cos a) (CSS up = -y); the gradient
1542// line runs through the cell centre with length L = tilePx*(|sin|+|cos|); a
1543// pixel's along-line coordinate s = dot(cell-centre, dir) + L/2 lands in [0, L],
1544// and the solid band is s < solidPx (the 0.5em hard stop).
1545vec4 wavyLayer(vec2 boxPx, float angle, float offsetTiles, float tilePx, float solidPx, vec4 color) {
1546    float s = sin(angle);
1547    vec2 dir = vec2(s, -cos(angle));
1548    // background-position-x scrolls the cell grid: shift screen x, fold into cell.
1549    vec2 shifted = vec2(boxPx.x - offsetTiles * tilePx, boxPx.y);
1550    vec2 cell = shifted - floor(shifted / tilePx) * tilePx; // posmod into [0, tilePx)
1551    vec2 centred = cell - vec2(tilePx * 0.5);
1552    float lineLen = tilePx * (abs(s) + abs(cos(angle)));
1553    float along = dot(centred, dir) + lineLen * 0.5; // 0..lineLen along the gradient
1554    float stripe = step(along, solidPx); // 1 in the solid 0.5em band, else 0
1555    return vec4(color.rgb, color.a * stripe);
1556}
1557
1558vec4 over(vec4 dst, vec4 src) {
1559    float outA = src.a + dst.a * (1.0 - src.a);
1560    vec3 outRgb = src.rgb * src.a + dst.rgb * dst.a * (1.0 - src.a);
1561    return vec4(outA > 0.0 ? outRgb / outA : vec3(0.0), outA);
1562}
1563
1564void main() {
1565    float offsetA = `+Cs+`.x;
1566    float offsetB = `+Cs+`.y;
1567    float tilePx = `+Cs+`.z;
1568    float solidPx = `+Cs+`.w;
1569
1570    // Box-pixel position from the box TOP-LEFT, the absolute-length tile-fold
1571    // space. CSS background-position is top-left origin, and vNormCoord shares
1572    // vTextureCoord's y-down texture axis (vNormCoord(0,0) is the on-screen
1573    // top-left — see GradientSweepFilter's same nc convention), so a bare
1574    // vNormCoord*vBoxSize anchors the tile mosaic at the box top-left to match
1575    // the CSS background-position origin; a centre offset would phase-shift it.
1576    vec2 boxPx = vNormCoord * vBoxSize;
1577
1578    float layerAngle[`+$i+`];
1579`+AWe()+`
1580    int layerGroup[`+$i+`];
1581`+yWe()+`
1582    float layerInitialEm[`+$i+`];
1583`+vWe()+`
1584
1585    // The four CSS background layers composite top-most-first (background: g1,
1586    // g2, …). Fold bottom-up so layer 0 (g1) ends on top: start at layer 3 and
1587    // over() each layer above the accumulator.
1588    vec4 acc = vec4(0.0);
1589    for (int i = `+$i+` - 1; i >= 0; i--) {
1590        float groupOffset = layerGroup[i] == 0 ? offsetA : offsetB;
1591        // Initial bg-position-x (em) + animated group slide, both in tile-width
1592        // units (initial em / 0.75em tile = initial em / WAVY_TILE_EM).
1593        float offsetTiles = groupOffset + layerInitialEm[i] / `+yP.toFixed(6)+`;
1594        vec4 layer = wavyLayer(boxPx, layerAngle[i], offsetTiles, tilePx, solidPx, `+Xu+`[i]);
1595        acc = over(acc, layer);
1596    }
1597
1598    // -webkit-background-clip: text — mask the composited gradient by the baked
1599    // glyph alpha, then lay the source's static white outline (-webkit-text-stroke)
1600    // back on top. The bake encodes two regions in one texture: interior fill is
1601    // an opaque BLACK sentinel (alpha=1, the mosaic mask; rgb 0) and the outline
1602    // stroke keeps its own color (rgb ≠ 0). Pixi v8 filter textures are
1603    // premultiplied, so un-premultiply before reading rgb (mirrors
1604    // MultiShadowFilter). strokeMask = max(glyph.rgb): ~1 on the bright outline,
1605    // ~0 on the black interior. The mosaic fills the whole glyph footprint, and
1606    // the outline is composited over() it so the white border survives at the edge
1607    // (matching the CSS stroke-over-fill order) instead of the mosaic overrunning
1608    // the ring and thickening the glyph. Emit premultiplied to match the pipeline.
1609    vec4 glyphPremult = texture(uTexture, vTextureCoord);
1610    float glyphAlpha = glyphPremult.a;
1611    vec3 glyphRgb = glyphAlpha > 0.0 ? glyphPremult.rgb / glyphAlpha : vec3(0.0);
1612    float strokeMask = max(glyphRgb.r, max(glyphRgb.g, glyphRgb.b));
1613
1614    vec4 mosaicLayer = vec4(acc.rgb, acc.a * glyphAlpha);
1615    vec4 strokeLayer = vec4(glyphRgb, glyphAlpha * strokeMask);
1616    vec4 result = over(mosaicLayer, strokeLayer);
1617    fragColor = vec4(result.rgb * result.a, result.a);
1618}
1619`,Uk=()=>`
1620struct GlobalFilterUniforms {
1621  uInputSize:vec4<f32>,
1622  uInputPixel:vec4<f32>,
1623  uInputClamp:vec4<f32>,
1624  uOutputFrame:vec4<f32>,
1625  uGlobalFrame:vec4<f32>,
1626  uOutputTexture:vec4<f32>,
1627};
1628
1629struct BackgroundScrollUniforms {
1630  `+Cs+`: vec4<f32>,
1631  `+Xu+": array<vec4<f32>, "+$i+`>,
1632};
1633
1634@group(0) @binding(0) var<uniform> gfu: GlobalFilterUniforms;
1635@group(0) @binding(1) var uTexture: texture_2d<f32>;
1636@group(0) @binding(2) var uSampler: sampler;
1637
1638@group(1) @binding(0) var<uniform> bg: BackgroundScrollUniforms;
1639
1640struct VSOutput {
1641    @builtin(position) position: vec4<f32>,
1642    @location(0) uv : vec2<f32>,
1643    @location(1) normCoord : vec2<f32>,
1644    @location(2) boxSize : vec2<f32>,
1645};
1646
1647fn filterVertexPosition(aPosition:vec2<f32>) -> vec4<f32> {
1648    var position = aPosition * gfu.uOutputFrame.zw + gfu.uOutputFrame.xy;
1649    position.x = position.x * (2.0 / gfu.uOutputTexture.x) - 1.0;
1650    position.y = position.y * (2.0*gfu.uOutputTexture.z / gfu.uOutputTexture.y) - gfu.uOutputTexture.z;
1651    return vec4(position, 0.0, 1.0);
1652}
1653
1654fn filterTextureCoord(aPosition:vec2<f32>) -> vec2<f32> {
1655    return aPosition * (gfu.uOutputFrame.zw * gfu.uInputSize.zw);
1656}
1657
1658@vertex
1659fn mainVertex(@location(0) aPosition: vec2<f32>) -> VSOutput {
1660  return VSOutput(
1661    filterVertexPosition(aPosition),
1662    filterTextureCoord(aPosition),
1663    aPosition,
1664    // Filter-frame pixel size; the diagonal axis is projected in this pixel
1665    // space so the tile period is a true length and the angle aspect-invariant.
1666    gfu.uOutputFrame.zw,
1667  );
1668}
1669
1670// See the GL counterpart: background-size:0.75em + repeat tiles the gradient into
1671// 0.75em cells, so the pixel is folded into one cell (posmod — WGSL has no mod
1672// builtin, so floor-based manual mod) then the cell-local diagonal gradient is
1673// evaluated. Cell axis dir = (sin a, -cos a); line through the cell centre with
1674// length lineLen = tilePx*(|sin|+|cos|); along = dot(cell-centre, dir) + lineLen/2
1675// in [0, lineLen]; solid band where along < solidPx. background-position-x shifts
1676// screen x by offsetTiles*tilePx before the fold.
1677fn wavyLayer(boxPx: vec2<f32>, angle: f32, offsetTiles: f32, tilePx: f32, solidPx: f32, color: vec4<f32>) -> vec4<f32> {
1678  let s = sin(angle);
1679  let dir = vec2<f32>(s, -cos(angle));
1680  let shifted = vec2<f32>(boxPx.x - offsetTiles * tilePx, boxPx.y);
1681  let cell = shifted - floor(shifted / tilePx) * tilePx;
1682  let centred = cell - vec2<f32>(tilePx * 0.5);
1683  let lineLen = tilePx * (abs(s) + abs(cos(angle)));
1684  let along = dot(centred, dir) + lineLen * 0.5;
1685  let stripe = step(along, solidPx);
1686  return vec4<f32>(color.rgb, color.a * stripe);
1687}
1688
1689fn over(dst: vec4<f32>, src: vec4<f32>) -> vec4<f32> {
1690  let outA = src.a + dst.a * (1.0 - src.a);
1691  let outRgb = src.rgb * src.a + dst.rgb * dst.a * (1.0 - src.a);
1692  if (outA > 0.0) {
1693    return vec4<f32>(outRgb / outA, outA);
1694  }
1695  return vec4<f32>(0.0, 0.0, 0.0, outA);
1696}
1697
1698@fragment
1699fn mainFragment(
1700  @builtin(position) position: vec4<f32>,
1701  @location(0) uv: vec2<f32>,
1702  @location(1) normCoord: vec2<f32>,
1703  @location(2) boxSize: vec2<f32>,
1704) -> @location(0) vec4<f32> {
1705  let offsetA = bg.`+Cs+`.x;
1706  let offsetB = bg.`+Cs+`.y;
1707  let tilePx = bg.`+Cs+`.z;
1708  let solidPx = bg.`+Cs+`.w;
1709
1710  // Top-left origin tile-fold space, mirroring the GL counterpart: normCoord is
1711  // the y-down texture axis (normCoord(0,0) = on-screen top-left), so
1712  // normCoord*boxSize anchors the mosaic at the box top-left to match the CSS
1713  // background-position origin.
1714  let boxPx = normCoord * boxSize;
1715
1716  var layerAngle = `+wWe()+`;
1717  var layerGroup = `+NWe()+`;
1718  var layerInitialEm = `+PWe()+`;
1719
1720  // Top-most-first CSS layers; fold bottom-up so layer 0 (g1) ends on top.
1721  var acc = vec4<f32>(0.0);
1722  for (var i = `+$i+` - 1; i >= 0; i = i - 1) {
1723    var groupOffset = offsetA;
1724    if (layerGroup[i] != 0) { groupOffset = offsetB; }
1725    let offsetTiles = groupOffset + layerInitialEm[i] / `+yP.toFixed(6)+`;
1726    let layer = wavyLayer(boxPx, layerAngle[i], offsetTiles, tilePx, solidPx, bg.`+Xu+`[i]);
1727    acc = over(acc, layer);
1728  }
1729
1730  // -webkit-background-clip: text — mask by the baked glyph alpha, then lay the
1731  // source's static white outline back on top (see GL counterpart for the
1732  // two-region bake encoding and the un-premultiply rationale). Emit premultiplied.
1733  let glyphPremult = textureSample(uTexture, uSampler, uv);
1734  let glyphAlpha = glyphPremult.a;
1735  var glyphRgb = vec3<f32>(0.0);
1736  if (glyphAlpha > 0.0) { glyphRgb = glyphPremult.rgb / glyphAlpha; }
1737  let strokeMask = max(glyphRgb.r, max(glyphRgb.g, glyphRgb.b));
1738
1739  let mosaicLayer = vec4<f32>(acc.rgb, acc.a * glyphAlpha);
1740  let strokeLayer = vec4<f32>(glyphRgb, glyphAlpha * strokeMask);
1741  let result = over(mosaicLayer, strokeLayer);
1742  return vec4<f32>(result.rgb * result.a, result.a);
1743}
1744`,MWe=(e,t,o)=>{if(t.eq(X.zero()))return 0;const r=e.sub(o);if(r.as.ms("raw")<=0)return 0;const n=t.as.ms("raw");return r.as.ms("raw")%n/n},DWe=2,kWe=-1,FWe=e=>({backgroundScroll:{offsetGroupA:e*DWe,offsetGroupB:e*kWe}}),UWe={webAssetId:"a-0120-wavy-background",animationDuration:X.fromSec(1),getProgress:MWe,getUniforms:FWe,bakeNeutralizeFill:CWe,graphicColorRoles:{bg1:"--background-color-1",bg2:"--background-color-2",bg3:"--background-color-3",bg4:"--background-color-4"}},vP={[dn.SHOUT]:oWe,[dn.SCALE_CARTOON]:WGe,[dn.SCALE_CARTOON_LOOP]:YGe,[dn.SKEW_X]:aWe,[dn.RAGE]:FGe,[dn.NEON]:MGe,[dn.GROW]:vGe,[dn.SCALE_X]:ZGe,[dn.SPOTLIGHT]:uWe,[dn.SQUIGGLY]:hWe,[dn.GLITCH]:pGe,[dn.WAVY_BACKGROUND]:UWe,[dn.FLIP_X]:zVe,[dn.SWEAT_DROPLET]:TWe,[dn.GRADIENT_EXPAND_TEXT]:IGe,[dn.GRADIENT_EXPAND_BG]:EGe},VWe=new Set(Object.values(dn)),rl=e=>typeof e=="string"&&VWe.has(e),nl=e=>vP[e],AY={[su.SWEAT]:{webAssetId:"a-0220-sweat",variant:su.SWEAT,layers:[{layerId:"text",order:0,selector:".container",variant:void 0},{layerId:"droplet",order:1,selector:".sweat",variant:dn.SWEAT_DROPLET}]},[su.GRADIENT_EXPAND]:{webAssetId:"a-0230-gradient-expand",variant:su.GRADIENT_EXPAND,layers:[{layerId:"bg",order:0,selector:".background",variant:dn.GRADIENT_EXPAND_BG},{layerId:"text",order:1,selector:".textarea",variant:dn.GRADIENT_EXPAND_TEXT}]}},GWe=new Set(Object.values(su)),wP=e=>typeof e=="string"&&GWe.has(e),WWe=e=>rl(e)||wP(e),HWe=e=>AY[e],jWe=e=>({variant:e.variant,animationDuration:e.layers.reduce((t,o)=>o.variant?X.max(t,vP[o.variant].animationDuration):t,X.zero())}),zWe=e=>
1744{for(const[t,o]of Object.entries(vP))if(o.webAssetId===e)return{variant:t,animationDuration:o.animationDuration};for(const t of Object.values(AY))if(t.webAssetId===e)return jWe(t)};class yY{_canvas;_ctx;constructor(t,o){this._canvas=new OffscreenCanvas(t,o);const r=this._canvas.getContext("2d");if(!r)throw Ae(je.CANVAS_CTX_ERR,new Error("Failed to get 2d context from canvas"));this._ctx=r}get width(){return this._canvas.width}get height(){return this._canvas.height}save(){this._ctx.save()}restore(){this._ctx.restore()}translatePixel(t,o){this._ctx.translate(t,o)}translateRatio(t,o){this.translatePixel(t*this._canvas.width,o*this._canvas.height)}rotateRad(t){this._ctx.rotate(t)}rotateDeg(t){this.rotateRad(t*Math.PI/180)}scale(t,o){this._ctx.scale(t,o)}fillRectPixel(t,o,r,n,a){const i=this._ctx.fillStyle;this._ctx.fillStyle=t,this._ctx.fillRect(o,r,n,a),this._ctx.fillStyle=i}fillRectRatio(t,o,r,n,a){this.fillRectPixel(t,o*this._canvas.width,r*this._canvas.height,n*this._canvas.width,a*this._canvas.height)}drawImagePixel(t,o,r,n,a){this._ctx.drawImage(t,o,r,n,a)}drawImageRatio(t,o,r,n,a){this.drawImagePixel(t,o*this._canvas.width,r*this._canvas.height,n*this._canvas.width,a*this._canvas.height)}async toImageBitmap(){return O1(this._canvas)}toImageData(){return this._ctx.getImageData(0,0,this._canvas.width,this._canvas.height)}clear(){this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height)}}class vY{dataArray=[];maxSize;eqFn;constructor(t,o=(r,n)=>r===n){this.maxSize=t,this.eqFn=o}set(t,o){const r=this.dataArray.findIndex(n=>this.eqFn(n.key,t));r>-1&&this.dataArray.splice(r,1),this.dataArray.length===this.maxSize-1&&this.dataArray.shift(),this.dataArray.push({key:t,value:o})}get(t){const o=this.dataArray.findIndex(r=>this.eqFn(r.key,t));if(o>-1){const r=this.dataArray.splice(o,1)[0];return this.dataArray.push(r),r.value}}getAll(){return this.dataArray}has(t){return this.dataArray.some(o=>this.eqFn(o.key,t))}clear(t){t&&this.dataArray.forEach(o=>t(o.value)),this.dataArray=[]}}class wY{constructor(t){this._abortSignal=t,this._abortSignal.addEventListener("abort",()=>{this.clear()},{once:!0})}_abortSignal;_prefetchCache=new vY(20);_activeMap=new Map;_pendingFetches=new Map;async prefetch(t){await Promise.allSettled(t.filter(o=>o.kind==="uri"&&!(this._prefetchCache.has(o.uri)||this._activeMap.has(o.uri)||this._pendingFetches.has(o.uri))).map(o=>this._fetchOnce(o.uri,this._abortSignal)))}async get(t){if(t.kind==="blob")return{blob:t.blob,release:()=>{}};const o=t.uri,r=this._activeMap.get(o);if(r)return r.refCount++,this._createHandle(o,r.blob);const n=this._prefetchCache.get(o);if(n)return this._moveToActive(o,n);const a=await this._fetchOnce(o,this._abortSignal);return this._moveToActive(o,a)}clear(){this._prefetchCache.clear(),this._activeMap.clear(),this._pendingFetches.clear()}_fetchOnce(t,o){const r=this._pendingFetches.get(t);if(r)return r;const n=$f(t,o).then(a=>(this._prefetchCache.set(t,a),a));return this._pendingFetches.set(t,n),n.then(()=>{this._pendingFetches.get(t)===n&&this._pendingFetches.delete(t)},()=>{this._pendingFetches.get(t)===n&&this._pendingFetches.delete(t)}),n}_moveToActive(t,o){return this._activeMap.set(t,{blob:o,refCount:1}),this._createHandle(t,o)}_createHandle(t,o){return{blob:o,release:()=>this._release(t)}}_release(t){const o=this._activeMap.get(t);o&&(o.refCount--,o.refCount<=0&&this._activeMap.delete(t))}}const YWe=async(e,t)=>{const o=performance.now(),r=KWe(e);return T1(async()=>{try{const a=await fetch(r,{signal:t});if(!a.ok)throw Ae(je.NETWORK_FAILED_ERR,"fetch response is not ok",`Details:
1745            network: `+navigator.onLine+`
1746            response: `+a.status+" "+a.statusText+`
1747            time: `+(performance.now()-o)+`ms
1748            url: `+e+`
1749            status: `+a.status+`
1750            statusText: `+a.statusText+`
1751            headers: `+JSON.stringify(Object.fromEntries(a.headers.entries()))+`
1752            disk: `+await PA()+`
1753          `);return a}catch(a){throw a instanceof DOMException&&a.name==="AbortError"?a:Ae(je.NETWORK_FAILED_ERR,`fetch failed
1754         Details:
1755          time: `+(performance.now()-o)+`ms
1756          url: `+e+`
1757          err: `+qr(a)+`
1758          network: `+navigator.onLine+`
1759          disk: `+await PA()+`
1760        `)}},1,()=>100+Math.random()*1e3)},BWe=async e=>{switch(e.kind){case"blob":return e.blob;case"uri":return $f(e.uri)}},PA=async()=>{try{const e=await navigator.storage.estimate();return"storage estimation: "+e.usage+" / "+e.quota}catch{return"storage estimation: failed to get storage estimation"}},$f=async(e,t)=>T1(async()=>{const r=await YWe(e,t);try{return await r.blob()}catch(n){if(n instanceof Error&&n.name==="TypeError"){const a=await PA();throw Ae(je.DISK_NO_SPACE,`blob() failed
1761         Details:
1762          url: `+e+`
1763          err: `+qr(n)+`
1764          disk: `+a+`
1765        `)}throw Ae(je.NETWORK_FAILED_ERR,n)}},1,()=>100+Math.random()*1e3),KWe=e=>{if(!e)return e;const t=e.toLowerCase(),o=/^\/(assets|worklet|libav|locales|src|@fs)\//,r=o.test(e)||e.startsWith("/try/")&&o.test("/"+e.slice(5));if(t.startsWith("http://")||t.startsWith("https://")||t.startsWith("blob:")||t.startsWith("data:")||t.startsWith("vrew-file:")||r)return e;throw Ae(je.LOGIC_ERR,"[assertLoadableUrl] Unconverted path reached core: "+e)},NY=async e=>{try{const t=new Image;return t.crossOrigin="anonymous",t.src=e,await t.decode(),t}
1765catch(t){throw Ae(je.FILE_READ_ERROR,t,"Failed to load image element (src="+e+")")}},XWe="position:fixed;left:0;top:0;visibility:hidden;contain:layout style size;",Up=()=>{const e=document.createElement("div");return e.style.cssText=XWe,document.body.appendChild(e),e},JWe=()=>{const e="vrew-measure-sandbox",t=document.getElementById(e);if(t instanceof HTMLDivElement)return t;const o=Up();return o.id=e,o},Vk=e=>{const t=JWe(),o=e.cloneNode(!0);t.appendChild(o);let r=0,n=0;if(o instanceof Element){const a=o.getBoundingClientRect();r=a.width,n=a.height}return t.removeChild(o),{width:r,height:n}};class JE{_dpr=window.devicePixelRatio||1;_lang;_img=null;_canvas=null;constructor(t,o){this._lang=o,this.init(t)}init(t){if(this._canvas&&Math.round(this._canvas.width/this._dpr)===Math.round(t.width)&&Math.round(this._canvas.height/this._dpr)===Math.round(t.height)){this._canvas.clear();return}const o=Math.round(t.width*this._dpr),r=Math.round(t.height*this._dpr);this._canvas=new yY(o,r)}async rasterize(t,o){if(!this._canvas)throw Ae(je.LOGIC_ERR,"Canvas not initialized while rasterizing");const r=Math.round(this._canvas.width/this._dpr),n=Math.round(this._canvas.height/this._dpr),a=this._createSVG(t,r,n,o?.globalCSS);this._img&&(this._img.src="",this._img=null);const i=this._serialize(a);return this._img=await NY(i),await this._getImageBitmap(this._img)}destroy(){this._img&&(this._img.src="",this._img=null)}_createSVG(t,o,r,n){const a="http://www.w3.org/2000/svg",i=document.createElementNS(a,"svg"),s=document.createElementNS(a,"foreignObject");if(i.setAttribute("width",""+o),i.setAttribute("height",""+r),i.setAttribute("viewBox","0 0 "+o+" "+r),i.style.zoom=""+window.devicePixelRatio,n){const x=document.createElementNS(a,"style");x.textContent=n,i.appendChild(x)}return s.setAttribute("width","100%"),s.setAttribute("height","100%"),s.setAttribute("x","0"),s.setAttribute("y","0"),s.setAttribute("lang",this._lang),t.style.setProperty("forced-color-adjust","none"),s.appendChild(t),i.appendChild(s),i}_serialize(t){const o=new XMLSerializer,r=o.serializeToString(t);return"data:image/svg+xml;charset=utf-8,"+encodeURIComponent(r)}async _getImageBitmap(t){if(!this._canvas)throw Ae(je.LOGIC_ERR,"Canvas not initialized while getting image bitmap");return this._canvas.clear(),this._canvas.drawImageRatio(t,0,0,1,1),await this._canvas.toImageBitmap()}}const NP=2e3,PP=8,PY=200,qWe=PY/PP,Rs="vrew-textbox-root",QWe=["uc-0180-center-gradient-outline","uc-0190-shiny-corner","uc-0230-gradient-white-outline","uc-0270-striped-text-fill","uc-0290-double-outline-with-fill"],ZWe=e=>QWe.some(t=>e.querySelector("."+t)),$We=/[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f-\x9f]/.source,e3e=/(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.source,t3e=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])/.source,bY=new RegExp("(?:"+$We+"|"+e3e+"|"+t3e+")+","g"),o3e=e=>{const t=new DOMParser().parseFromString(C1(e.html),"text/html"),o=document.createElement("div"),r=new Set([Rs]);e.tbClassName&&e.tbClassName.split(" ").forEach(i=>i&&r.add(i)),o.className=Array.from(r).join(" "),e.tbId&&o.setAttribute("id",e.tbId);const n=document.createElement("div"),a=new t2(n);for(const i in e.deltas){if(a.setContents(e.deltas[i]),e.effect?.info&&sS(e.effect.info.variant)){const{info:l,time:d,timelineDuration:u}=e.effect;DY({quill:a,text:a.getText(),currTime:d,animationName:e.effect.info.variant,animDuration:l.animationDuration,animStartDelay:l.startDelay,timelineDuration:u})}if(a.getText().replace(`
1766`,"").length===0)continue;const x=n.getElementsByClassName("ql-editor")[0]?.innerHTML.replace(bY,"").trim(),c=t.getElementById(i);c&&(c.innerHTML=x)}return o.innerHTML=t.documentElement.innerHTML,o},LY="data-textbox-padding-wrapper",r3e=(e,t,o,r,n,a,i)=>{const s=document.createElement("div");Object.assign(s.style,{position:"absolute",overflow:"visible",transformOrigin:.5*100+"% "+.5*100+"%"});const x=document.createElement("div");x.setAttribute(LY,""),Object.assign(x.style,{overflow:"visible"});const c=a3e(r,n),l=document.createElement("div"),d=o3e({deltas:t,html:e}),u=i3e(o,t,Rs);return s.append(x,u),x.append(c),c.append(l),l.append(d),s},Gk=(e,t)=>{const o=ZWe(e),r=typeof globalThis.CSS?.escape=="function"?globalThis.CSS.escape:d=>d.replace(/[^a-zA-Z0-9_-]/g,"\\$&"),n=t.filter(Boolean).map(d=>"#"+r(d)),a=n.length>0?n.join(", "):"."+Rs,i=n.length>0?n.map(d=>d+", "+d+" *").join(", "):"."+Rs+", ."+Rs+" *",s=e.cloneNode(!0),x=document.createElement("style");x.textContent=`
1767    `+i+` {
1768      color: transparent !important;
1769      -webkit-text-fill-color: transparent !important;
1770      text-shadow: none !important;
1771      -webkit-text-stroke: 0 transparent !important;
1772      background-image: none !important;
1773      `+(o?`
1774      /* For background-clip:text templates, background-color can still paint the glyph even
1775         after background-image removal. Remove the entire background shorthand. */
1776      background: none !important;
1777      background-color: transparent !important;
1778      -webkit-background-clip: initial !important;
1779      background-clip: initial !important;
1780      `:"")+`
1781      filter: none !important;
1782      -webkit-filter: none !important;
1783    }
1784  `,s.appendChild(x);const c=e.cloneNode(!0),l=document.createElement("style");return l.textContent=`
1785    .`+Rs+`,
1786    .`+Rs+` * {
1787      visibility: hidden !important;
1788    }
1789
1790    /* Show only text target areas (and their descendants) */
1791    `+i+` {
1792      visibility: visible !important;
1793    }
1794
1795    /* Remove non-text paints inside text targets, keeping geometry intact */
1796    `+i+` {
1797      `+(o?"/* keep background paints for background-clip:text templates */":"background-color: transparent !important;")+`
1798      box-shadow: none !important;
1799      border-color: transparent !important;
1800      outline-color: transparent !important;
1801    }
1802
1803    `+a+`::before,
1804    `+a+`::after,
1805    `+a+` *::before,
1806    `+a+` *::after {
1807      visibility: hidden !important;
1808    }
1809  `,c.appendChild(l),{background:s,text:c}},n3e=(e,t,o,r,n,a,i)=>{const s=e.cloneNode(!0),x=s.children[0],c=x.children[0],l=c.querySelector("."+Rs);l&&(l.id=n,l.classList.add(a)),S3e(t.variant,c);const d=document.createElement("div"),u=new t2(d);for(const p in i){const f=s.querySelector("#"+p);if(!f)continue;u.setContents(i[p]),DY({quill:u,text:u.getText(),currTime:o.as.us("round"),animationName:t.variant,animDuration:t.animationDuration,animStartDelay:t.startDelay,timelineDuration:r.as.us("round")});const E=d.getElementsByClassName("ql-editor")[0]?.innerHTML.replace(bY,"").trim();E&&(f.innerHTML=E)}return s},a3e=(e,t)=>
1809{const o=document.createElement("div");return Object.assign(o.style,{position:"relative",transformOrigin:"top left",width:e/t+"px",zoom:t}),o},i3e=(e,t,o)=>{const r=document.createElement("style"),n=s3e(o),a=x3e(o,e,t);return r.textContent=n+`
1810`+a,r},s3e=e=>"."+e+" { font-size: "+qWe+"px; } ."+e+" * { font-kerning: normal }",x3e=(e,t,o)=>{const r=c3e(o),n={attributeName:"--textbox-lineheight",type:"textbox-lineheight",value:r+"px"},a=i=>"."+i+` {
1811    <% attrs.forEach((attr) => { %><%- attr.attributeName %>: <%- attr.value %>;<% }) %>
1812  }
1813`;return rn.template(a(e))({attrs:[...t,n]})},c3e=e=>{const t=MY(e),o=t/PP*1.2;return d3e(e)?o*1.5:o},MY=e=>{let t=0;for(const o of Object.keys(e)){const r=e[o];for(const n of r.ops)typeof n.insert!="string"||n.attributes===void 0||n.attributes.size===void 0||(t=Math.max(t,parseInt(n.attributes.size)))}return t||PY},l3e=(e,t)=>{const r=MY(e);return Math.max(50,Math.round(r/PP*t))},d3e=e=>{for(const t of Object.keys(e)){const o=e[t];for(const r of o.ops)if(!(typeof r.insert!="string"||r.attributes===void 0)&&r.attributes.ruby)return!0}return!1},DY=({quill:e,text:t,currTime:o,animationName:r,animDuration:n,animStartDelay:a,timelineDuration:i})=>{const s=new Qt,x=u3e(t,NP);if(x.length===0)return;const c=X.min(X.fromUS(n),X.max(X.fromUS(i-a),X.zero())),l=c.div(x.length);x.forEach((d,u)=>{const p=X.fromUS(a).add(l.mul(u).sub(X.fromUS(o))),f=VJ(p.as.sec(),2),E=f===0?.001:f,T=T3e({charIdx:u,animationName:r,textDuration:l.as.sec(),animationDelay:E});s.retain(d.length,{"text-animation":T})}),e.updateContents(s)},u3e=(e,t)=>{const o=e??"";if(typeof Intl<"u"&&typeof Intl.Segmenter=="function"){const r=new Intl.Segmenter(void 0,{granularity:"grapheme"}),n=[];for(const a of r.segment(o))if(n.push(a.segment),n.length>=t)break;return n}return Array.from(o).slice(0,t)},p3e=e=>{e.style.setProperty("visibility","visible","important"),e.style.setProperty("opacity","1","important"),e.style.setProperty("animation-name","none","important"),e.style.setProperty("animation-duration","0s","important"),e.style.setProperty("animation-delay","0s","important"),e.style.setProperty("animation-fill-mode","none","important"),e.style.setProperty("animation-play-state","paused","important"),e.style.setProperty("filter","none","important"),e.style.setProperty("-webkit-filter","none","important")},f3e=(e,t)=>e.classList.contains("textarea")||t.has(e.id),g3e=e=>{Object.assign(e.style,{display:"block",padding:"0",margin:"0",border:"0",backgroundColor:"transparent",boxShadow:"none",outline:"none"})},_3e=e=>{Object.assign(e.style,{display:"contents",padding:"0",margin:"0",border:"0",backgroundColor:"transparent",boxShadow:"none",outline:"none"})},E3e=e=>{e.style.display==="inline-block"&&(e.style.display="inline"),Object.assign(e.style,{padding:"0",margin:"0",border:"0",backgroundColor:"transparent",boxShadow:"none",outline:"none",borderRadius:"0",verticalAlign:"baseline"})},m3e=(e,t,o)=>{const r=e.cloneNode(!0);p3e(r);let n=r,a=e.parentElement,i=!1;for(;a&&a!==t;){const s=a.cloneNode(!1);f3e(a,o)?(i=!0,g3e(s)):i?_3e(s):E3e(s),s.appendChild(n),n=s,a=a.parentElement}return n},xu=e=>Math.round(e*1e3)/1e3,sf="data-vrew-strip-glyph-idx",Wk=e=>{const t=document.createElement("div");Object.assign(t.style,{position:"absolute",left:"-100000px",top:"0px",overflow:"hidden",visibility:"hidden",contain:"layout style size"}),t.appendChild(e),document.body.appendChild(t);try{const o=new Map,r=Array.from(e.querySelectorAll("["+sf+"]"));for(const n of r){const a=n.getAttribute(sf),i=a?parseInt(a,10):NaN;if(!Number.isFinite(i))continue;const s=n.querySelector(".text-animation-wrapper");if(!s)continue;const x=n.getBoundingClientRect(),c=s.getBoundingClientRect();o.set(i,{x:xu(c.left-x.left),y:xu(c.top-x.top)})}return o}finally{t.removeChild(e),document.body.removeChild(t)}},h3e=(e,t)=>{const o=document.createElement("div");Object.assign(o.style,{position:"absolute",left:"-100000px",top:"0px",width:t.width+"px",height:t.height+"px",overflow:"hidden"});const r=e.cloneNode(!0);o.appendChild(r),document.body.appendChild(o);try{const n=o.querySelector("."+Rs)??r.querySelector("."+Rs);if(!n)return[];const a=Array.from(n?.getElementsByClassName("text-animation-wrapper")??[]).slice(0,NP),i=o.getBoundingClientRect(),s=[];for(const x of a){const c=x.getBoundingClientRect(),l=xu(c.left-i.left),d=xu(c.top-i.top),u=xu(c.width),p=xu(c.height);s.push({x:l,y:d,width:u,height:p})}return s}finally{document.body.removeChild(o)}},I3e=async(e,t,o)=>{const r=o.maxSheetHeight,n=o.globalCSS,a=o.scale,i=new Set(o.textTargetIds.filter(
1813Boolean)),s=window.devicePixelRatio||1,x=h3e(e,t),{x:c,y:l}=R3e(x),d=e.cloneNode(!0),u=Array.from(d.querySelectorAll("style")).map(w=>w.cloneNode(!0)),p=Array.from(d.querySelectorAll("svg > defs")).map(w=>{const N=document.createElementNS("http://www.w3.org/2000/svg","svg");return N.style.position="absolute",N.style.width="0",N.style.height="0",N.style.overflow="hidden",N.appendChild(w.cloneNode(!0)),N}),f=d.querySelector("."+Rs),E=f?.className??Rs,T=f?Array.from(f.getElementsByClassName("text-animation-wrapper")).slice(0,NP):[],O=x.length,S=[],R=[],y=[];let v=0;for(;v<O;){let w=0,N=1,M=v;for(;M<O;){const U=x[M],te=Math.ceil(U.width+c*2),ne=Math.ceil(U.height+l*2);if(M>v&&w+ne>r)break;w+=ne,N=Math.max(N,te),M+=1}const k=S.length,F=document.createElement("div");Object.assign(F.style,{position:"relative",width:N+"px",height:w+"px",overflow:"hidden"});for(const U of u)F.appendChild(U.cloneNode(!0));for(const U of p)F.appendChild(U.cloneNode(!0));const G=document.createElement("div");Object.assign(G.style,{transformOrigin:"top left",width:N/a+"px",height:w/a+"px",zoom:a}),F.appendChild(G);const B=document.createElement("div");B.className=E,Object.assign(B.style,{position:"relative",width:N/a+"px",height:w/a+"px",overflow:"hidden"}),G.appendChild(B);const W=document.createElement("div");Object.assign(W.style,{position:"absolute",left:"0px",top:"0px",display:"flex",flexDirection:"column",alignItems:"flex-start",width:N/a+"px",height:w/a+"px"}),B.appendChild(W);let Q=[],j=0;for(let U=v;U<M;U++){const te=x[U],ne=Math.ceil(te.width+c*2),oe=Math.ceil(te.height+l*2),re=document.createElement("div");re.setAttribute(sf,""+U),Object.assign(re.style,{position:"relative",width:ne/a+"px",height:oe/a+"px",overflow:"hidden",flex:"0 0 auto"});const ge=document.createElement("div");Object.assign(ge.style,{position:"absolute",left:Math.floor(c/a)+"px",top:Math.floor(l/a)+"px",width:Math.ceil(te.width/a)+"px",height:Math.ceil(te.height/a)+"px",overflow:"visible"});const fe=T[U];fe&&f&&ge.appendChild(m3e(fe,f,i)),re.appendChild(ge),W.appendChild(re),Q.push({idx:U,dest:te,cellW:ne,cellH:oe,y:j}),j+=oe}let $=Wk(F);const q=new Map;for(const U of Q){const te=$.get(U.idx);if(!te)continue;const ne=x[U.idx],oe=Math.ceil(te.y+ne.height+l);oe>U.cellH&&q.set(U.idx,oe)}if(q.size>0){let U=0;const te=[];for(const ne of Q){const oe=q.get(ne.idx)??ne.cellH;te.push({...ne,cellH:oe,y:U}),U+=oe}Q=te,w=U,F.style.height=w+"px",G.style.height=w/a+"px",B.style.height=w/a+"px",W.style.height=w/a+"px";for(const ne of W.querySelectorAll("["+sf+"]")){const oe=parseInt(ne.getAttribute(sf),10),re=q.get(oe);re!==void 0&&(ne.style.height=re/a+"px")}$=Wk(F)}for(const U of Q)y.push({dest:U.dest,origin:$.get(U.idx)??{x:c,y:l},src:{sheet:k,x:0,y:Math.floor(U.y*s),width:Math.ceil(U.cellW*s),height:Math.ceil(U.cellH*s)}});const H=new JE({width:N,height:w},o.lang);try{const U=await H.rasterize(F,n?{globalCSS:n}:void 0);S.push(U),R.push({width:N,height:w,glyphStart:v,glyphCount:M-v})}finally{H.destroy()}v=M}return{layout:{dpr:s,sheets:R,glyphs:y},sheetBitmaps:S}},T3e=({charIdx:e,animationName:t,textDuration:o,animationDelay:r})=>({charIdx:""+e,animationName:t,animationDuration:o+"s",animationDelay:r+"s",animationFillMode:"forwards",animationTimingFunction:"ease-in-out",animationPlayState:"running",opacity:"0",position:"relative"}),S3e=(e,t)=>{(!t.id||t.id.match(/^\d/))&&(t.id="ha-"+h1());const o=O3e(e);return t.appendChild(o),t},O3e=e=>{const t=document.createElement("style");return t.textContent=`
1814    `+C3e[e]+`
1815  `,t},sS=e=>Eo(Qn).isValue(e),C3e={[Qn.TYPING]:`@keyframes asset-effect-typing {
1816    0% {
1817      opacity: 1;
1818    }
1819    100% {
1820      opacity: 1;
1821    }
1822  }`,[Qn.TYPING_UP]:`@keyframes asset-effect-typing-up {
1823    0% {
1824      opacity: 1;
1825    }
1826    100% {
1827      opacity: 1;
1828    }
1829  }`,[Qn.TYPING_DOWN]:`@keyframes asset-effect-typing-down {
1830    0% {
1831      opacity: 1;
1832    }
1833    100% {
1834      opacity: 1;
1835    }
1836  }`},R3e=e=>{if(e.length===0)return{x:0,y:0};const t=e.reduce((i,s)=>Math.max(i,s.height),0),o=.6,r=16,n=8,a=Math.max(r,Math.ceil(t*o)+n);return{x:a,y:a}},Ru=(e,t)=>e.filters?.find(o=>o instanceof t),bP=(e,t)=>{e.filters?e.filters=[...e.filters,t]:e.filters=[t]},Au=(e,t,o)=>{if(!e.filters)return;const r=e.filters.find(a=>a instanceof t);
1836if(!r)return;r.destroy(o);const n=e.filters.filter(a=>a!==r);e.filters=n.length>0?n:null},A3e=(e,t)=>{e.filters?.forEach(o=>o.destroy(t)),e.filters=null},w0=4,As="uGradSweep",N0="uGradStopPos",ys="uGradStopColor",y3e=(e,t)=>t?e.colorRole!==void 0?t[e.colorRole]??e.color:Object.values(t)[0]??e.color:e.color;class kY extends hd{_uniforms;constructor(){const t=new sd({[As]:{value:new Float32Array(4),type:"vec4<f32>"},[N0]:{value:new Float32Array(4),type:"vec4<f32>"},[ys]:{value:new Float32Array(w0*4),type:"vec4<f32>",size:w0}});super({glProgram:new cl({vertex:v3e(),fragment:w3e(),name:"GradientSweep_GL"}),gpuProgram:new xl({name:"GradientSweep_GPU",vertex:{source:Hk(),entryPoint:"mainVertex"},fragment:{source:Hk(),entryPoint:"mainFragment"}}),resources:{filterUniforms:t}}),this._uniforms=t}update(t,o,r,n){const a=t.gradientSweep,i=this._uniforms.uniforms[As],s=this._uniforms.uniforms[N0],x=this._uniforms.uniforms[ys],c=a?.stops??[],l=Math.min(c.length,w0),d=a?a.angle*Math.PI/180:0,u=Math.max(1,n.sprite.texture?.width??1),p=Math.max(1,n.sprite.texture?.height??1),f=Math.abs(Math.sin(d)),E=Math.abs(Math.cos(d)),T=a?.scale??1,O=u*f+p*E,S=T*u*f+p*E,R=O/Math.max(1e-4,S);i[0]=d,i[1]=R,i[2]=a?.phase??0,i[3]=l;for(let y=0;y<w0;y++){const v=c[y],w=y*4;if(v&&y<l){s[y]=v.pos;const N=y3e(v,r);x[w+0]=N[0],x[w+1]=N[1],x[w+2]=N[2],x[w+3]=N[3]}else s[y]=0,x[w+0]=0,x[w+1]=0,x[w+2]=0,x[w+3]=0}}}const v3e=()=>`
1837#version 300 es
1838precision mediump float;
1839
1840layout(location = 0) in vec2 aPosition;
1841
1842out vec2 vTextureCoord;
1843out vec2 vNormCoord;
1844out vec2 vBoxSize;
1845
1846uniform vec4 uInputSize;
1847uniform vec4 uOutputFrame;
1848uniform vec4 uOutputTexture;
1849
1850vec4 filterVertexPosition(void) {
1851    vec2 position = aPosition * uOutputFrame.zw + uOutputFrame.xy;
1852    position.x = position.x * (2.0 / uOutputTexture.x) - 1.0;
1853    position.y = position.y * (2.0*uOutputTexture.z / uOutputTexture.y) - uOutputTexture.z;
1854    return vec4(position, 0.0, 1.0);
1855}
1856
1857vec2 filterTextureCoord(void) {
1858    return aPosition * (uOutputFrame.zw * uInputSize.zw);
1859}
1860
1861void main(void) {
1862    gl_Position = filterVertexPosition();
1863    vTextureCoord = filterTextureCoord();
1864    vNormCoord = aPosition;
1865    // Filter-frame pixel size (width, height) of the glyph texture. The gradient
1866    // axis is computed in this pixel space so its on-screen angle matches the CSS
1867    // nominal angle regardless of the box aspect ratio.
1868    vBoxSize = uOutputFrame.zw;
1869}
1870`,w3e=()=>`
1871#version 300 es
1872precision mediump float;
1873
1874in vec2 vTextureCoord;
1875in vec2 vNormCoord;
1876in vec2 vBoxSize;
1877out vec4 fragColor;
1878
1879uniform sampler2D uTexture;
1880uniform vec4 `+As+`;
1881uniform vec4 `+N0+`;
1882uniform vec4 `+ys+"["+w0+`];
1883
1884// CSS linear-gradient coordinate. The CSS gradient line passes through the box
1885// centre at the given angle (0deg = up, clockwise) and its length is the
1886// projection of the box onto that line: abs(W*sin) + abs(H*cos). The fragment is
1887// projected in pixel space (nc * boxSize) so the on-screen angle equals the
1888// nominal angle for any aspect ratio, then normalised by the line length to a
1889// [0,1] box coordinate gRaw. nc shares vTextureCoord's y-down axis (texture
1890// space), so the CSS y-up direction (sin, -cos) keeps its -cos.y here.
1891//
1892// The affine phase model maps gRaw to the 250%-tile coordinate: t = gRaw*comp +
1893// phase*(1 - comp). comp (= boxLine/tileLine, computed CPU-side from the texture
1894// aspect) compresses the box gradient to the tile's width; (1 - comp) is the
1895// per-loop slide Δt that the phase drives. This reproduces the source's
1896// background-position-x sweep exactly — same pixels, same timing — for any box
1897// aspect ratio.
1898float gradientCoord(vec2 nc, vec2 boxSize, float angleRad, float comp, float phase) {
1899    vec2 dir = vec2(sin(angleRad), -cos(angleRad));
1900    vec2 p = (nc - vec2(0.5)) * boxSize;
1901    float lineLen = abs(boxSize.x * dir.x) + abs(boxSize.y * dir.y);
1902    float gRaw = dot(p, dir) / max(1e-4, lineLen) + 0.5;
1903    return gRaw * comp + phase * (1.0 - comp);
1904}
1905
1906vec4 sampleGradient(float t) {
1907    int count = int(`+As+`.w);
1908    if (count <= 0) return vec4(0.0);
1909    vec4 first = `+ys+`[0];
1910    if (t <= `+N0+`[0]) return first;
1911    for (int i = 1; i < `+w0+`; i++) {
1912        if (i >= count) break;
1913        float p0 = `+N0+`[i - 1];
1914        float p1 = `+N0+`[i];
1915        if (t <= p1) {
1916            float k = (t - p0) / max(1e-4, p1 - p0);
1917            return mix(`+ys+"[i - 1], "+ys+`[i], k);
1918        }
1919    }
1920    // Past the last active stop: clamp to it (background-repeat: no-repeat).
1921    for (int i = `+w0+` - 1; i >= 0; i--) {
1922        if (i < count) return `+ys+`[i];
1923    }
1924    return first;
1925}
1926
1927void main() {
1928    float alpha = texture(uTexture, vTextureCoord).a;
1929    // clamp (not fract): background-repeat is no-repeat, so coords outside the
1930    // gradient tile clamp to the edge stop instead of tiling a ph
1930antom band.
1931    float t = clamp(gradientCoord(vNormCoord, vBoxSize, `+As+".x, "+As+".y, "+As+`.z), 0.0, 1.0);
1932    vec4 grad = sampleGradient(t);
1933    fragColor = vec4(grad.rgb * grad.a * alpha, grad.a * alpha);
1934}
1935`,Hk=()=>`
1936struct GlobalFilterUniforms {
1937  uInputSize:vec4<f32>,
1938  uInputPixel:vec4<f32>,
1939  uInputClamp:vec4<f32>,
1940  uOutputFrame:vec4<f32>,
1941  uGlobalFrame:vec4<f32>,
1942  uOutputTexture:vec4<f32>,
1943};
1944
1945struct GradientUniforms {
1946  `+As+`: vec4<f32>,
1947  `+N0+`: vec4<f32>,
1948  `+ys+": array<vec4<f32>, "+w0+`>,
1949};
1950
1951@group(0) @binding(0) var<uniform> gfu: GlobalFilterUniforms;
1952@group(0) @binding(1) var uTexture: texture_2d<f32>;
1953@group(0) @binding(2) var uSampler: sampler;
1954
1955@group(1) @binding(0) var<uniform> grad: GradientUniforms;
1956
1957struct VSOutput {
1958    @builtin(position) position: vec4<f32>,
1959    @location(0) uv : vec2<f32>,
1960    @location(1) normCoord : vec2<f32>,
1961    @location(2) boxSize : vec2<f32>,
1962};
1963
1964fn filterVertexPosition(aPosition:vec2<f32>) -> vec4<f32> {
1965    var position = aPosition * gfu.uOutputFrame.zw + gfu.uOutputFrame.xy;
1966    position.x = position.x * (2.0 / gfu.uOutputTexture.x) - 1.0;
1967    position.y = position.y * (2.0*gfu.uOutputTexture.z / gfu.uOutputTexture.y) - gfu.uOutputTexture.z;
1968    return vec4(position, 0.0, 1.0);
1969}
1970
1971fn filterTextureCoord(aPosition:vec2<f32>) -> vec2<f32> {
1972    return aPosition * (gfu.uOutputFrame.zw * gfu.uInputSize.zw);
1973}
1974
1975@vertex
1976fn mainVertex(@location(0) aPosition: vec2<f32>) -> VSOutput {
1977  return VSOutput(
1978    filterVertexPosition(aPosition),
1979    filterTextureCoord(aPosition),
1980    aPosition,
1981    // Filter-frame pixel size of the glyph texture; the gradient axis is
1982    // computed in this pixel space so the on-screen angle is aspect-invariant.
1983    gfu.uOutputFrame.zw,
1984  );
1985}
1986
1987// See the GL gradientCoord comment: CSS gradient-line projection in pixel space
1988// (aspect-correct), normalised by line length to gRaw, then the affine phase
1989// model t = gRaw*comp + phase*(1 - comp). nc is y-down (texture space), so the
1990// CSS up vector keeps its -cos in .y.
1991fn gradientCoord(nc: vec2<f32>, boxSize: vec2<f32>, angleRad: f32, comp: f32, phase: f32) -> f32 {
1992  let dir = vec2<f32>(sin(angleRad), -cos(angleRad));
1993  let p = (nc - vec2<f32>(0.5)) * boxSize;
1994  let lineLen = abs(boxSize.x * dir.x) + abs(boxSize.y * dir.y);
1995  let gRaw = dot(p, dir) / max(1e-4, lineLen) + 0.5;
1996  return gRaw * comp + phase * (1.0 - comp);
1997}
1998
1999fn sampleGradient(t: f32) -> vec4<f32> {
2000  let count = i32(grad.`+As+`.w);
2001  if (count <= 0) { return vec4<f32>(0.0); }
2002  let first = grad.`+ys+`[0];
2003  if (t <= grad.`+N0+`[0]) { return first; }
2004  for (var i = 1; i < `+w0+`; i = i + 1) {
2005    if (i >= count) { break; }
2006    let p0 = grad.`+N0+`[i - 1];
2007    let p1 = grad.`+N0+`[i];
2008    if (t <= p1) {
2009      let k = (t - p0) / max(1e-4, p1 - p0);
2010      return mix(grad.`+ys+"[i - 1], grad."+ys+`[i], k);
2011    }
2012  }
2013  for (var i = `+w0+` - 1; i >= 0; i = i - 1) {
2014    if (i < count) { return grad.`+ys+`[i]; }
2015  }
2016  return first;
2017}
2018
2019@fragment
2020fn mainFragment(
2021  @builtin(position) position: vec4<f32>,
2022  @location(0) uv: vec2<f32>,
2023  @location(1) normCoord: vec2<f32>,
2024  @location(2) boxSize: vec2<f32>,
2025) -> @location(0) vec4<f32> {
2026  let alpha = textureSample(uTexture, uSampler, uv).a;
2027  // clamp (not fract): background-repeat is no-repeat (see GL counterpart).
2028  let t = clamp(gradientCoord(normCoord, boxSize, grad.`+As+".x, grad."+As+".y, grad."+As+`.z), 0.0, 1.0);
2029  let g = sampleGradient(t);
2030  return vec4<f32>(g.rgb * g.a * alpha, g.a * alpha);
2031}
2032`,t0=4,Ju="uShadowParams",qu="uShadowColor",jk=(e,t,o)=>e*t*Math.abs(o),_d=[.25,.5,.75,1,1.25,1.5,1.75,2,2.25,2.5,2.75,3],bA=_d.map(e=>e<1?2:1),Qu=[0,11.25,5.625,16.875,2.8125,14.0625,8.4375,19.6875,1.40625,12.65625,7.03125,18.28125],N3e=_d[_d.length-1],FY=e=>Number.isInteger(e)?e.toFixed(1):String(e),UY=e=>Math.cos(e*Math.PI/180).toFixed(6),VY=e=>Math.sin(e*Math.PI/180).toFixed(6),P3e=()=>_d.map((e,t)=>"    ringScales["+t+"] = "+FY(e)+";").join(`
2033`),b3e=()=>bA.map((e,t)=>"    ringStride["+t+"] = "+e+";").join(`
2034`),L3e=()=>Qu.map((e,t)=>"    ringCos["+t+"] = "+UY(e)+";").join(`
2035`),M3e=()=>Qu.map((e,t)=>"    ringSin["+t+"] = "+VY(e)+";").join(`
2036`),D3e=()=>"array<f32, "+_d.length+">("+_d.map(FY).join(", ")+")",k3e=()=>"array<i32, "+bA.length+">("+bA.join(", ")+")",F3e=()=>"array<f32, "+Qu.length+">("+Qu.map(UY).join(", ")+")",U3e=()=>"array<f32, "+Qu.length+">("+Qu.map(VY).join(", ")+")",Zd=_d.length,V3e=2,GY=32,G3e=(e,t)=>
2036{const o=e.shadowLayers??[];let r=0;for(const n of o){if(n.strength<=0)continue;const a=Math.max(Math.abs(n.offset[0]),Math.abs(n.offset[1]))*t,i=n.blur*t,s=a+N3e*i;r=Math.max(r,s)}return Math.max(GY,Math.ceil(r)+V3e)},W3e=(e,t)=>t?e.colorRole!==void 0?t[e.colorRole]??e.color:Object.values(t)[0]??e.color:e.color;class WY extends hd{_uniforms;constructor(){const t=new sd({[Ju]:{value:new Float32Array(t0*4),type:"vec4<f32>",size:t0},[qu]:{value:new Float32Array(t0*4),type:"vec4<f32>",size:t0}});super({glProgram:new cl({vertex:H3e(),fragment:j3e(),name:"MultiShadow_GL"}),gpuProgram:new xl({name:"MultiShadow_GPU",vertex:{source:zk(),entryPoint:"mainVertex"},fragment:{source:zk(),entryPoint:"mainFragment"}}),resources:{filterUniforms:t},padding:GY}),this._uniforms=t}update(t,o,r,n){const a=t.shadowLayers??[],i=this._uniforms.uniforms[Ju],s=this._uniforms.uniforms[qu],x=n.layout.scale?.x??1;for(let c=0;c<t0;c++){const l=a[c],d=c*4;if(l){i[d+0]=jk(l.offset[0],o,x),i[d+1]=jk(l.offset[1],o,x),i[d+2]=l.blur*o,i[d+3]=l.strength;const u=W3e(l,r);s[d+0]=u[0],s[d+1]=u[1],s[d+2]=u[2],s[d+3]=u[3]}else i[d+0]=0,i[d+1]=0,i[d+2]=0,i[d+3]=0,s[d+0]=0,s[d+1]=0,s[d+2]=0,s[d+3]=0}this.padding=G3e(t,o)}}const H3e=()=>`
2037#version 300 es
2038precision mediump float;
2039
2040layout(location = 0) in vec2 aPosition;
2041
2042out vec2 vTextureCoord;
2043
2044uniform vec4 uInputSize;
2045uniform vec4 uOutputFrame;
2046uniform vec4 uOutputTexture;
2047
2048vec4 filterVertexPosition(void) {
2049    vec2 position = aPosition * uOutputFrame.zw + uOutputFrame.xy;
2050    position.x = position.x * (2.0 / uOutputTexture.x) - 1.0;
2051    position.y = position.y * (2.0*uOutputTexture.z / uOutputTexture.y) - uOutputTexture.z;
2052    return vec4(position, 0.0, 1.0);
2053}
2054
2055vec2 filterTextureCoord(void) {
2056    return aPosition * (uOutputFrame.zw * uInputSize.zw);
2057}
2058
2059void main(void) {
2060    gl_Position = filterVertexPosition();
2061    vTextureCoord = filterTextureCoord();
2062}
2063`,j3e=()=>`
2064#version 300 es
2065precision mediump float;
2066
2067in vec2 vTextureCoord;
2068out vec4 fragColor;
2069
2070uniform sampler2D uTexture;
2071uniform vec4 `+Ju+"["+t0+`];
2072uniform vec4 `+qu+"["+t0+`];
2073// Pixi global filter uniform: (w, h, 1/w, 1/h) of the padded filter-input RT.
2074// vTextureCoord is normalised by uInputSize.zw (the self-vertex below), so glow
2075// blur/offset displacements MUST use the same denominator — using the original
2076// glyph texel (1/textureDim) inflates the physical displacement by RT/texture
2077// and re-couples the glow reach to padding/Po2/resolution.
2078uniform vec4 uInputSize;
2079
2080// Multi-concentric-ring Gaussian-weighted glow blur covering the full visible
2081// Gaussian tail out to 3 sigma (the outermost ring sits at 3.0x blurPx). An
2082// earlier kernel only reached 1.5x blurPx, clipping ~half the spread of a CSS
2083// drop-shadow() (whose soft tail reaches ~3 sigma) and leaving ~blurPx-wide
2084// radial gaps that read as discrete satellite blobs ("graininess") at large
2085// radii; extending the reach to 3.0x fixed that. This samples 12 rings at a
2086// uniform 0.25x blurPx step (0.25x..3.0x) plus center, each ring weighted by a
2087// Gaussian (w = exp(-(d/sigma)^2/2) with d = blurPx*s, so w = exp(-(s*s)/2)) and
2088// normalised by the accumulated weight sum (not a fixed divisor). The current
2089// change keeps that 3.0x reach and instead tightens the ring step from 0.5x to
2090// 0.25x (6->12 rings) to shrink the radial gap between rings, so the glow contour
2091// no longer steps in concentric bands ("staircase").
2092//
2093// sigma = blurPx (NOT coupled to any spread factor): the descriptor already
2094// emits the cumulative-sigma chain (neon) or raw blur (others), so sigma stays
2095// the physical blurPx.
2096//
2097// Tap budget: inner rings (s < 1.0) keep 8 angular taps (45deg spacing); outer
2098// rings (s >= 1.0) densify to 16 taps (22.5deg spacing) to halve the angular gap
2099// where the radial reach is largest. 1 center + 3*8 + 9*16 = 169 taps, single
2100// pass. The 16-dir table is sampled with a per-ring stride (2 for inner, 1 for
2101// outer).
2102//
2103// Stagger: each ring is rotated by a distinct azimuth offset so the rings'
2104// spokes interleave instead of co-aligning into 16-direction radial streaks.
2105float sampleGlowAlpha(vec2 uv, float blurPx) {
2106    if (blurPx <= 0.0) {
2107        return texture(uTexture, uv).a;
2108    }
2109    vec2 r = blurPx * uInputSize.zw;
2110
2111    float weightSum = 1.0; // center tap, exp(0) = 1
2112    float a = texture(uTexture, uv).a;
2113
2114    // Sixteen unit directions (22.5deg apart). Inner rings stride by 2 (8 taps,
2115    // 45deg); outer rings stride by 1 (16 taps, 22.5deg).
2116    vec2 dirs[16];
2117    dirs[0]  = vec2( 1.000000,  0.000000);
2118    dirs[1]  = vec2( 0.923880,  0.382683);
2119    dirs[2]  = vec2( 0.707107,  0.707107);
2120    dirs[3]  = vec2( 0.382683,  0.923880);
2121    dirs[4]  = vec2( 0.000000,  1.000000);
2122    dirs[5]  = vec2(-0.382683,  0.923880);
2123    dirs[6]  = vec2(-0.707107,  0.707107);
2124    dirs[7]  = vec2(-0.923880,  0.382683);
2125    dirs[8]  = vec2(-1.000000,  0.000000);
2126    dirs[9]  = vec2(-0.923880, -0.382683);
2127    dirs[10] = vec2(-0.707107, -0.707107);
2128    dirs[11] = vec2(-0.382683, -0.923880);
2129    dirs[12] = vec2( 0.000000, -1.000000);
2130    dirs[13] = vec2( 0.382683, -0.923880);
2131    dirs[14] = vec2( 0.707107, -0.707107);
2132    dirs[15] = vec2( 0.923880, -0.382683);
2133
2134    float ringScales[`+Zd+`];
2135`+P3e()+`
2136
2137    // Stride 2 (8 taps) for inner rings, 1 (16 taps) for outer rings (s >= 1.0).
2138    int ringStride[`+Zd+`];
2139`+b3e()+`
2140
2141    // Per-ring azimuth rotation (cos/sin of the staggered ring bearings, deg in
2142    // GLOW_RING_AZIMUTH_DEG) so the rings' spokes interleave rather than co-align.
2143    float ringCos[`+Zd+`];
2144`+L3e()+`
2145    float ringSin[`+Zd+`];
2146`+M3e()+`
2147
2148    for (int ring = 0; ring < `+Zd+`; ring++) {
2149        float s = ringScales[ring];
2150        float w = exp(-(s * s) * 0.5);
2151        float rc = ringCos[ring];
2152        float rs = ringSin[ring];
2153        int stride = ringStride[ring];
2154        for (int t = 0; t < 16; t += stride) {
2155            vec2 base = dirs[t];
2156            vec2 dir = vec2(base.x * rc - base.y * rs, base.x * rs + base.y * rc);
2157            a += texture(uTexture, uv + dir * (s * r)).a * w;
2158            weightSum += w;
2159        }
2160    }
2161    return a / weightSum;
2162}
2163
2164vec4 over(vec4 dst, vec4 src) {
2165    float outA = src.a + dst.a * (1.0 - src.a);
2166    vec3 outRgb = src.rgb * src.a + dst.rgb * dst.a * (1.0 - src.a);
2167    return vec4(outA > 0.0 ? outRgb / outA : vec3(0.0), outA);
2168}
2169
2170void main() {
2171    vec4 acc = vec4(0.0);
2172    for (int i = 0; i < `+t0+`; i++) {
2173        vec4 p = `+Ju+`[i];
2174        float strength = p.w;
2175        if (strength <= 0.0) continue;
2176        vec2 offsetUv = p.xy * uInputSize.zw;
2177        float a = sampleGlowAlpha(vTextureCoord - offsetUv, p.z) * strength;
2178        vec4 c = `+qu+`[i];
2179        // Saturate the glow-loop effective alpha: over() is unclamped, so a
2180        // src.a > 1 (e.g. a high-strength white core) would propagate acc.a > 1
2181        // and turn the next layer's (1 - src.a) factor negative. Clamping here
2182        // keeps acc.a in [0,1]. Body composite below is left untouched.
2183        acc = over(acc, vec4(c.rgb, clamp(c.a * a, 0.0, 1.0)));
2184    }
2185    // Pixi v8 filter input/output textures are premultiplied (see pixi.js
2186    // ColorMatrixFilter, which un-premultiplies on read and re-premultiplies on
2187    // write). The sampled glyph is therefore premultiplied — un-premultiply its
2188    // rgb before over() (which re-applies src.a internally) so the glyph alpha
2189    // is not squared and anti-aliased edges keep their color. The composited
2190    // result is straight alpha; re-premultiply the emitted fragment to match the
2191    // sibling filters (AlphaMask/GradientSweep) and the pipeline's blend.
2192    vec4 glyphPremult = texture(uTexture, vTextureCoord);
2193    vec4 glyph = vec4(
2194        glyphPremult.a > 0.0 ? glyphPremult.rgb / glyphPremult.a : vec3(0.0),
2195        glyphPremult.a);
2196    vec4 result = over(acc, glyph);
2197    fragColor = vec4(result.rgb * result.a, result.a);
2198}
2199`,zk=()=>`
2200struct GlobalFilterUniforms {
2201  uInputSize:vec4<f32>,
2202  uInputPixel:vec4<f32>,
2203  uInputClamp:vec4<f32>,
2204  uOutputFrame:vec4<f32>,
2205  uGlobalFrame:vec4<f32>,
2206  uOutputTexture:vec4<f32>,
2207};
2208
2209struct ShadowUniforms {
2210  `+Ju+": array<vec4<f32>, "+t0+`>,
2211  `+qu+": array<vec4<f32>, "+t0+`>,
2212};
2213
2214@group(0) @binding(0) var<uniform> gfu: GlobalFilterUniforms;
2215@group(0) @binding(1) var uTexture: texture_2d<f32>;
2216@group(0) @binding(2) var uSampler: sampler;
2217
2218@group(1) @binding(0) var<uniform> shadow: ShadowUniforms;
2219
2220struct VSOutput {
2221    @builtin(position) position: vec4<f32>,
2222    @location(0) uv : vec2<f32>,
2223};
2224
2225fn filterVertexPosition(aPosition:vec2<f32>) -> vec4<f32> {
2226    var position = aPosition * gfu.uOutputFrame.zw + gfu.uOutputFrame.xy;
2227    position.x = position.x * (2.0 / gfu.uOutputTexture.x) - 1.0;
2228    position.y = position.y * (2.0*gfu.uOutputTexture.z / gfu.uOutputTexture.y) - gfu.uOutputTexture.z;
2229    return vec4(position, 0.0, 1.0);
2230}
2231
2232fn filterTextureCoord(aPosition:vec2<f32>) -> vec2<f32> {
2233    return aPosition * (gfu.uOutputFrame.zw * gfu.uInputSize.zw);
2234}
2235
2236@vertex
2237fn mainVertex(@location(0) aPosition: vec2<f32>) -> VSOutput {
2238  return VSOutput(filterVertexPosition(aPosition), filterTextureCoord(aPosition));
2239}
2240
2241// Multi-concentric-ring Gaussian-weighted glow blur covering the full visible
2242// Gaussian tail out to 3 sigma (mirror of the GL counterpart — same math, same
2243// shared GLOW_RING_SCALES source; only the array syntax differs per backend).
2244// 12 rings at a uniform 0.25x blurPx step (0.25x..3.0x) plus center, Gaussian
2245// weighted (w = exp(-(s*s)/2), sigma = blurPx) and normalised by the weight sum.
2246// Inner rings (s < 1.0) sample 8 taps (stride 2), outer rings (s >= 1.0) sample
2247// 16 taps (stride 1) from the shared 16-dir table. 169 taps, single pass.
2248// Stagger: each ring uses a distinct azimuth offset so the rings' spokes
2249// interleave instead of co-aligning into 16-direction streaks.
2250fn sampleGlowAlpha(uv: vec2<f32>, blurPx: f32) -> f32 {
2251  if (blurPx <= 0.0) {
2252    return textureSample(uTexture, uSampler, uv).a;
2253  }
2254  let r = blurPx * gfu.uInputSize.zw;
2255
2256  var weightSum = 1.0; // center tap, exp(0) = 1
2257  var a = textureSample(uTexture, uSampler, uv).a;
2258
2259  // Sixteen unit directions (22.5deg apart). Inner rings stride by 2 (8 taps),
2260  // outer rings stride by 1 (16 taps).
2261  var dirs = array<vec2<f32>, 16>(
2262    vec2<f32>( 1.000000,  0.000000),
2263    vec2<f32>( 0.923880,  0.382683),
2264    vec2<f32>( 0.707107,  0.707107),
2265    vec2<f32>( 0.382683,  0.923880),
2266    vec2<f32>( 0.000000,  1.000000),
2267    vec2<f32>(-0.382683,  0.923880),
2268    vec2<f32>(-0.707107,  0.707107),
2269    vec2<f32>(-0.923880,  0.382683),
2270    vec2<f32>(-1.000000,  0.000000),
2271    vec2<f32>(-0.923880, -0.382683),
2272    vec2<f32>(-0.707107, -0.707107),
2273    vec2<f32>(-0.382683, -0.923880),
2274    vec2<f32>( 0.000000, -1.000000),
2275    vec2<f32>( 0.382683, -0.923880),
2276    vec2<f32>( 0.707107, -0.707107),
2277    vec2<f32>( 0.923880, -0.382683)
2278  );
2279
2280  var ringScales = `+D3e()+`;
2281
2282  // Stride 2 (8 taps) for inner rings, 1 (16 taps) for outer rings (s >= 1.0).
2283  var ringStride = `+k3e()+`;
2284
2285  // Per-ring azimuth rotation (cos/sin of the staggered ring bearings, deg in
2286  // GLOW_RING_AZIMUTH_DEG) so the rings' spokes interleave rather than co-align.
2287  var ringCos = `+F3e()+`;
2288  var ringSin = `+U3e()+`;
2289
2290  for (var ring = 0; ring < `+Zd+`; ring = ring + 1) {
2291    let s = ringScales[ring];
2292    let w = exp(-(s * s) * 0.5);
2293    let rc = ringCos[ring];
2294    let rs = ringSin[ring];
2295    let stride = ringStride[ring];
2296    for (var t = 0; t < 16; t = t + stride) {
2297      let base = dirs[t];
2298      let dir = vec2<f32>(base.x * rc - base.y * rs, base.x * rs + base.y * rc);
2299      a = a + textureSample(uTexture, uSampler, uv + dir * (s * r)).a * w;
2300      weightSum = weightSum + w;
2301    }
2302  }
2303  return a / weightSum;
2304}
2305
2306fn over(dst: vec4<f32>, src: vec4<f32>) -> vec4<f32> {
2307  let outA = src.a + dst.a * (1.0 - src.a);
2308  let outRgb = src.rgb * src.a + dst.rgb * dst.a * (1.0 - src.a);
2309  if (outA > 0.0) {
2310    return vec4<f32>(outRgb / outA, outA);
2311  }
2312  return vec4<f32>(0.0, 0.0, 0.0, outA);
2313}
2314
2315@fragment
2316fn mainFragment(
2317  @builtin(position) position: vec4<f32>,
2318  @location(0) uv: vec2<f32>,
2319) -> @location(0) vec4<f32> {
2320  var acc = vec4<f32>(0.0);
2321  for (var i = 0; i < `+t0+`; i = i + 1) {
2322    let p = shadow.`+Ju+`[i];
2323    let strength = p.w;
2324    if (strength <= 0.0) { continue; }
2325    let offsetUv = p.xy * gfu.uInputSize.zw;
2326    let a = sampleGlowAlpha(uv - offsetUv, p.z) * strength;
2327    let c = shadow.`+qu+`[i];
2328    // Saturate the glow-loop effective alpha (see GL counterpart): over() is
2329    // unclamped, so a src.a > 1 would propagate acc.a > 1 and break the next
2330    // layer's (1 - src.a) factor. Body composite below is left untouched.
2331    acc = over(acc, vec4<f32>(c.rgb, clamp(c.a * a, 0.0, 1.0)));
2332  }
2333  // See the GL counterpart: Pixi v8 filter textures are premultiplied, so
2334  // un-premultiply the sampled glyph before over() (avoids squaring its alpha)
2335  // and re-premultiply the emitted fragment to match the pipeline blend.
2336  let glyphPremult = textureSample(uTexture, uSampler, uv);
2337  var glyphRgb = vec3<f32>(0.0);
2338  if (glyphPremult.a > 0.0) {
2339    glyphRgb = glyphPremult.rgb / glyphPremult.a;
2340  }
2341  let glyph = vec4<f32>(glyphRgb, glyphPremult.a);
2342  let result = over(acc, glyph);
2343  return vec4<f32>(result.rgb * result.a, result.a);
2344}
2345`;class z3e{params;sprite;descriptor;graphicVariant;filterCtors=[];apply(t,o){this.sprite=o.sprite;const r=t.effects?.Animation,n=this.params?.variant;if(this.params=r,!r||!rl(r.variant)){this.descriptor=void 0,this.graphicVariant=void 0,this.filterCtors=[],this._removeFilters(o);return}const{descriptor:a,filterCtors:i}=HY(r.variant);if(i.length===0){this.descriptor=void 0,this.graphicVariant=void 0,this.filterCtors=[],this._removeFilters(o);return}if(this.descriptor=a,this.graphicVariant=r.variant,this.filterCtors=i,!(r.variant===n&&i.every(s=>Ru(o.sprite,s)))){this._removeFilters(o);for(const s of i)bP(o.sprite,new s)}}updateProgress(t,o){const r=this.params,n=this.descriptor,a=this.graphicVariant;if(!r||!n||!a)return;const i=BY(t,r,a),s=n.getUniforms(i),x=K3e(r.layerMetrics,r.bakedFontSizePx,r.elementZoom,o);for(const c of this.filterCtors){const l=Ru(o.sprite,c);l&&l.update(s,x,r.graphicFxColors,o)}}destroy(){if(this.sprite)for(const t of Bk())Au(this.sprite,t,!0);this.params=void 0,this.sprite=void 0,this.descriptor=void 0,this.graphicVariant=void 0,this.filterCtors=[]}_removeFilters(t){for(const o of Bk())Ru(t.sprite,o)&&Au(t.sprite,o,!0)}}const Yk=new Map,HY=e=>{const t=Yk.get(e);if(t)return t;const o=nl(e),r=o.getUniforms(0),n=[];r.displacementMap!==void 0&&n.push(mY),r.gradientSweep!==void 0&&n.push(kY),r.shadowLayers!==void 0&&n.push(WY),r.backgroundScroll!==void 0&&n.push(CY);const a=Object.freeze({descriptor:o,filterCtors:Object.freeze(n)});return Yk.set(e,a),a},Bk=()=>[mY,kY,WY,CY],Y3e=e=>rl(e)?HY(e).filterCtors.length>0:!1,B3e=e=>{const t=e.sprite.texture?.height??0;return t>0?t:1},jY=(e,t,o)=>e?.fontSizePx??t??B3e(o),K3e=(e,t,o,r)=>{const n=o??1,a=t!==void 0?t*n:void 0;return jY(e,a,r)},Kk=new WeakMap,zY=e=>e!==void 0&&(PVe(e.variant)||rl(e.variant)&&nl(e.variant).perspective!==void 0),YY=e=>{const t=Kk.get(e);if(t)return t;const o=Object.freeze({animationDuration:X.fromSec(Math.max(1e-4,e.animationDuration/1e6)),assetTimelineDuration:X.fromUS(Math.max(e.assetTimelineDuration,e.animationDuration)),startDelay:X.fromUS(e.startDelay)});return Kk.set(e,o),o};class X3e{geometry=new J3e;textReveal=new q3e;graphic=new z3e;apply(t,o){this.textReveal.apply(t,o),this.geometry.apply(t,o),this.graphic.apply(t,o)}updateProgress(t,o){this.geometry.updateProgress(t,o),this.textReveal.updateProgress(t,o),this.graphic.updateProgress(t,o)}destroy(){this.geometry.destroy(),this.textReveal.destroy(),this.graphic.destroy()}}class J3e{context;params;clipMask;clipMaskWidth;clipMaskHeight;clipMaskMatrixA;clipMaskMatrixB;clipMaskMatrixC;clipMaskMatrixD;clipMaskMatrixTx;
2345clipMaskMatrixTy;apply(t,o){this.context=o;const r=t.effects?.Animation;if(!r){this.params=void 0,this.releaseClipMask(o),o.releasePerspectiveMesh(),o.releaseAnimationLayer();return}const n=this.params;if(this.params=r,!(r.effectId===n?.effectId&&r.variant===n.variant))if(sS(r.variant)){const a=o.ensureAnimationLayer();a.alpha=1,oHe(a),a.pivot.set(0,0),this.params=void 0}else o.ensureAnimationLayer()}updateProgress(t,o){const r=this.params;if(!r)return;this.context=o;const n=this.computeUniforms(t,o,r);this.applyUniforms(o,n,r),this.syncClipMask(o,r)}syncClipMask(t,o){const r=t.sprite.texture;if(!o.clipToBox||!r){this.releaseClipMask(t);return}const n=t.getAnimationLayer();let a=this.clipMask;!a&&(a=new $9,t.root.addChild(a),this.clipMask=a),n.mask!==a&&(n.mask=a),(this.clipMaskWidth!==r.width||this.clipMaskHeight!==r.height)&&(a.clear(),a.rect(0,0,r.width,r.height).fill(16777215),this.clipMaskWidth=r.width,this.clipMaskHeight=r.height),t.layout.updateLocalTransform();const i=t.layout.localTransform;(this.clipMaskMatrixA!==i.a||this.clipMaskMatrixB!==i.b||this.clipMaskMatrixC!==i.c||this.clipMaskMatrixD!==i.d||this.clipMaskMatrixTx!==i.tx||this.clipMaskMatrixTy!==i.ty)&&(a.setFromMatrix(i),this.clipMaskMatrixA=i.a,this.clipMaskMatrixB=i.b,this.clipMaskMatrixC=i.c,this.clipMaskMatrixD=i.d,this.clipMaskMatrixTx=i.tx,this.clipMaskMatrixTy=i.ty)}releaseClipMask(t){const o=this.clipMask;if(this.clipMaskWidth=void 0,this.clipMaskHeight=void 0,this.clipMaskMatrixA=void 0,this.clipMaskMatrixB=void 0,this.clipMaskMatrixC=void 0,this.clipMaskMatrixD=void 0,this.clipMaskMatrixTx=void 0,this.clipMaskMatrixTy=void 0,!o)return;this.clipMask=void 0;const r=t.getAnimationLayer();r.mask===o&&(r.mask=null);try{o.removeFromParent()}catch{}try{o.destroy()}catch{}}computeUniforms(t,o,r){return wP(r.variant)?{}:rl(r.variant)?this.computeCustomUniforms(t,o,r,r.variant):this.computeStandardUniforms(t,o,r,r.variant)}computeCustomUniforms(t,o,r,n){const a=nl(n),i=BY(t,r,n),s=jY(r.layerMetrics,r.bakedFontSizePx,o),x=r.bakedFontSizePx!==void 0?s*(r.elementZoom??1):s,c=Q3e(s,o.layout.scale?.x),l=a.getUniforms(i,c),d=a.perspective,u=l.rotateXDeg,p=d!==void 0&&u!==void 0?(()=>{const T=o.sprite.texture?.width??1,O=o.sprite.texture?.height??1,S=d.em*x;return{...l,perspectiveHomography:VVe(T,O,u,d.axis,S)}})():l,f=Z3e(p,r.layerMetrics),E=iY(f,r.elementZoom??1);return $3e(E,o.layout.scale?.x??1,o.layout.scale?.y??1)}computeStandardUniforms(t,o,r,n){const{progress:a,phase:i}=this.computeProgress(t,r,n);return kVe(n,a,o.sprite.texture?.width??1,o.sprite.texture?.height??1,i,o.canvasSize.width,o.canvasSize.height,r.elementZoom??1)}destroy(){this.context&&(this.releaseClipMask(this.context),this.context.releasePerspectiveMesh(),this.context.releaseAnimationLayer()),this.params=void 0,this.context=void 0}computeProgress(t,o,r){const n=YY(o);return V1e(r,X.fromUS(Math.max(0,t-o.timelineStart)),n.assetTimelineDuration,n.animationDuration,n.startDelay)}applyUniforms(t,o,r){const n=t.ensureAnimationLayer(),a=o.origin??[.5,.5],i=[r.flipH?1-a[0]:a[0],r.flipV?1-a[1]:a[1]],s=this.projectOriginToParent(i,t),x=o.scale?.[0]??1,c=o.scale?.[1]??1,l=o.skew?.[0]??0,d=o.skew?.[1]??0,{dx:u,dy:p}=this.computeMotionOffset(o,t,r,x,c);if(o.perspectiveHomography||o.perspectiveCorners){const f=t.ensurePerspectiveMesh(),E=t.sprite.texture?.width??1,T=t.sprite.texture?.height??1;if(o.perspectiveHomography)f.setHomography(eHe(o.perspectiveHomography,r.flipH,r.flipV,E,T));else if(o.perspectiveCorners){const O=tHe(o.perspectiveCorners,r.flipH,r.flipV,E,T);f.setCorners(O.topLeft[0],O.topLeft[1],O.topRight[0],O.topRight[1],O.bottomRight[0],O.bottomRight[1],O.bottomLeft[0],O.bottomLeft[1])}}else t.releasePerspectiveMesh();
2345n.alpha=o.alpha??1,n.scale.set(x,c),n.skew.set(l,d),n.rotation=o.rotate??0,n.pivot.set(s.x,s.y),n.position.set(s.x+u,s.y+p)}computeMotionOffset(t,o,r,n,a){const i=o.layout.scale?.x??1,s=o.layout.scale?.y??1,x=r.assetRotation??0,c=t.motion?.system??"relative";let l,d;if(c==="relative")l=i*n,d=s*a;else{const T=t.motion,O=T&&"absoluteMotionScaleWithAnim"in T?T.absoluteMotionScaleWithAnim??!0:!0;l=O?i*n:1,d=O?s*a:1}const u=(t.motion?.value?.[0]??0)*l,p=(t.motion?.value?.[1]??0)*d,f=Math.cos(x),E=Math.sin(x);return{dx:u*f-p*E,dy:u*E+p*f}}projectOriginToParent(t,o){const r=o.sprite.texture;if(!r)return{x:0,y:0};const n=t[0]*r.width,a=t[1]*r.height;o.layout.updateLocalTransform();const i=o.layout.localTransform;return{x:i.a*n+i.c*a+i.tx,y:i.b*n+i.d*a+i.ty}}}class q3e{params;atlasState;_spriteAlpha=1;apply(t,o){const r=t.effects?.Animation,n=this.params?.effectId;if(this.params=r,!r||!sS(r.variant)){this._cleanup();return}this._spriteAlpha=o.sprite.alpha;const a=r.textRevealStripAtlas;if(!a?.layout||!a.sheetBitmaps?.length){this._cleanup();return}const i=this.atlasState,s=!!i&&a.layout===i.layout&&a.sheetBitmaps===i.sheetBitmaps;i&&r.effectId===n&&s||(this._cleanup(),this._initAtlasState(o,a.layout,a.sheetBitmaps))}updateProgress(t,o){const r=this.params;if(!r)return;const n=this.atlasState;if(n){this._updateStripAtlas(t,o,r,n);return}}destroy(){const t=this.atlasState;if(t)try{this._disposeStripAtlasState(t)}catch{}this.atlasState=void 0,this.params=void 0}_cleanup(){const t=this.atlasState;if(t)try{this._disposeStripAtlasState(t)}catch{}this.atlasState=void 0}_disposeStripAtlasState(t){this._destroyStripAtlasOverlay(t);for(const o of t.glyphSprites)try{o.removeFromParent(),o.destroy({children:!0,texture:!0,textureSource:!1})}catch{}for(const o of t.sheetSources)try{o.destroy()}catch{}for(const o of t.sheetBitmaps)try{o.close()}catch{}try{t.container.removeFromParent()}catch{}try{t.container.destroy({children:!0})}catch{}}_destroyStripAtlasOverlay(t){if(t.overlay){try{t.overlay.removeFromParent(),t.overlay.destroy({children:!0,texture:!0,textureSource:!1})}catch{}t.overlay=void 0,t.overlayGlyphIdx=void 0}}_initAtlasState(t,o,r){const n=new jp;n.zIndex=(t.sprite.zIndex??0)+.01,t.layout.addChild(n);const a=r.map(i=>py.from(i));this.atlasState={layout:o,sheetBitmaps:r,sheetSources:a,container:n,glyphSprites:[],lastStep:-1}}_updateStripAtlas(t,o,r,n){const a=n.layout.glyphs.length;if(!(a<=0)){if(o.layout.alpha=this._spriteAlpha,o.sprite.alpha=0,r.variant===Qn.TYPING){const i=this._computeCharIndex(t,r,a);this._revealStripAtlas(o,r,n,i,0),this._destroyStripAtlasOverlay(n);return}if(r.variant===Qn.TYPING_UP||r.variant===Qn.TYPING_DOWN){const{charIndex:i,charFraction:s}=this.computeTypingProgress(t,r,a);this._revealStripAtlas(o,r,n,i,s)}}}_revealStripAtlas(t,o,r,n,a){const i=1/(t.layout.scale?.x??1),s=1/(t.layout.scale?.y??1),x=r.layout.glyphs.length,c=Math.max(0,Math.min(n,x));if(r.lastStep!==c){r.lastStep=c;for(let l=0;l<c;l++){let d=r.glyphSprites[l];d?this._positionStripGlyphSprite(d,r,l,i,s):(d=this._createStripGlyphSprite(r,l,i,s),d.zIndex=(t.sprite.zIndex??0)+.01,r.container.addChild(d),r.glyphSprites[l]=d),d.visible=!0}for(let l=c;l<r.glyphSprites.length;l++){const d=r.glyphSprites[l];d&&(d.visible=!1)}}if(a>0&&c<x&&(o.variant===Qn.TYPING_UP||o.variant===Qn.TYPING_DOWN)){const l=r.layout.glyphs[c];if(!l)return;const d=(l.dest.x-l.origin.x)*i,u=(l.dest.y-l.origin.y)*s,p=o.variant===Qn.TYPING_UP?10:o.variant===Qn.TYPING_DOWN?-10:0,f=o.elementZoom??1,E=p*f*(1-a),T=E/(t.layout.scale?.y||1);let O=r.overlay;if(!O)O=new lR(this._createStripGlyphTexture(r,c)),O.zIndex=(t.sprite.zIndex??0)+.02,r.container.addChild(O),r.overlay=O,r.overlayGlyphIdx=c;else if(r.overlayGlyphIdx!==c){const S=O.texture;O.texture=this._createStripGlyphTexture(r,c),r.overlayGlyphIdx=c,t.handleDispose(()=>{try{S.destroy(!1)}catch{}})}O.visible=!0,O.position.set(d,u+T)}else this._destroyStripAtlasOverlay(r)}_createStripGlyphTexture(t,o){const r=t.layout.glyphs[o];if(!r)return mx.EMPTY;const n=r.src,a=t.sheetSources[n.sheet];return a?new mx({source:a,frame:new dR(n.x,n.y,n.width,n.height)}):mx.EMPTY}_positionStripGlyphSprite(t,o,r,n,a){const i=o.layout.glyphs[r];i&&t.position.set((i.dest.x-i.origin.x)*n,(i.dest.y-i.origin.y)*
2345a)}_createStripGlyphSprite(t,o,r,n){const a=new lR(this._createStripGlyphTexture(t,o));return this._positionStripGlyphSprite(a,t,o,r,n),a}_computeCharIndex(t,o,r){const n=this._computeProgress(t,o);return Math.min(r,Math.ceil(r*n))}computeTypingProgress(t,o,r){const n=this._computeProgress(t,o),a=r*n,i=Math.min(r,Math.floor(a)),s=Xk(a-i);return{charIndex:i,charFraction:s}}_computeProgress(t,o){const r=Math.min(o.animationDuration,Math.max(0,o.assetTimelineDuration-o.startDelay)),n=Math.max(1e-4,r/1e6),a=Math.max(0,t-o.timelineStart-o.startDelay)/1e6;return Xk(a/n)}}const Xk=e=>Math.max(0,Math.min(1,e)),Q3e=(e,t)=>e*Math.abs(t??1),BY=(e,t,o)=>{if(!rl(o))return 0;const r=nl(o),n=YY(t);return r.getProgress(X.fromUS(Math.max(0,e-t.timelineStart)),n.animationDuration,n.startDelay)},Z3e=(e,t)=>{const{motion:o}=e,r=o?.system==="em"||o?.system==="layer-relative";if(!t){if(!r)return e;const{motion:s,...x}=e;return x}const n=r?{system:"absolute",value:o.system==="em"?[o.value[0]*t.fontSizePx,o.value[1]*t.fontSizePx]:[o.value[0]*t.contentRect.width,o.value[1]*t.contentRect.height]}:o,a=e.origin??[.5,.5],i=[(t.contentRect.x+a[0]*t.contentRect.width)/t.boxSize.width,(t.contentRect.y+a[1]*t.contentRect.height)/t.boxSize.height];return{...e,motion:n,origin:i}},$3e=(e,t,o=t)=>{const{motion:r}=e;if(!(r?.system==="absolute"&&r.absoluteMotionScaleWithAnim!==!1)||!r)return e;const a=t===0||t===1?1:1/t,i=o===0||o===1?1:1/o;if(a===1&&i===1)return e;const[s,x]=r.value;return{...e,motion:{...r,value:[s*a,x*i]}}},hE=(e,t)=>{const o=Array(9).fill(0);for(let r=0;r<3;r+=1)for(let n=0;n<3;n+=1)for(let a=0;a<3;a+=1)o[r*3+n]+=e[a*3+n]*t[r*3+a];return o},eHe=(e,t,o,r,n)=>{let a=e;return t&&(a=hE([-1,0,0,0,1,0,r,0,1],hE(a,[-1,0,0,0,1,0,1,0,1]))),o&&(a=hE([1,0,0,0,-1,0,0,n,1],hE(a,[1,0,0,0,-1,0,0,1,1]))),a},tHe=(e,t,o,r,n)=>{if(!t&&!o)return e;let a=e;t&&(a={topLeft:a.topRight,topRight:a.topLeft,bottomRight:a.bottomLeft,bottomLeft:a.bottomRight}),o&&(a={topLeft:a.bottomLeft,topRight:a.bottomRight,bottomRight:a.topRight,bottomLeft:a.topLeft});const i=c=>t?r-c:c,s=c=>o?n-c:c,x=c=>[i(c[0]),s(c[1])];return{topLeft:x(a.topLeft),topRight:x(a.topRight),bottomRight:x(a.bottomRight),bottomLeft:x(a.bottomLeft)}},oHe=e=>{e.position.set(0,0),e.scale.set(1,1),e.rotation=0,e.skew.set(0,0)},xS=e=>e==="webgl2"?`
2346#version 300 es
2347precision mediump float;
2348
2349layout(location = 0) in vec2 aPosition;
2350
2351out vec2 vTextureCoord;
2352
2353uniform vec4 uInputSize; // Size of input texture (w, h, 1/w, 1/h)
2354uniform vec4 uOutputFrame; // Rectangle of the filter inside the render target (dst x, dst y, dst w, dst h)
2355uniform vec4 uOutputTexture; // Size of render target (w, h, flipY, 1)
2356
2357vec4 filterVertexPosition(void) {
2358    vec2 position = aPosition * uOutputFrame.zw + uOutputFrame.xy; // convert to dst space
2359    position.x = position.x * (2.0 / uOutputTexture.x) - 1.0; // convert to ndc
2360    position.y = position.y * (2.0*uOutputTexture.z / uOutputTexture.y) - uOutputTexture.z; // convert to ndc
2361
2362    return vec4(position, 0.0, 1.0);
2363}
2364
2365vec2 filterTextureCoord(void) {
2366    return aPosition * (uOutputFrame.zw * uInputSize.zw); // convert to src space
2367}
2368
2369void main(void) {
2370    gl_Position = filterVertexPosition();
2371    vTextureCoord = filterTextureCoord();
2372}
2373  `:`
2374    struct GlobalFilterUniforms {
2375      uInputSize:vec4<f32>,
2376      uInputPixel:vec4<f32>,
2377      uInputClamp:vec4<f32>,
2378      uOutputFrame:vec4<f32>,
2379      uGlobalFrame:vec4<f32>,
2380      uOutputTexture:vec4<f32>,
2381    };
2382    
2383    @group(0) @binding(0) var<uniform> gfu: GlobalFilterUniforms;
2384    
2385    struct VSOutput {
2386        @builtin(position) position: vec4<f32>,
2387        @location(0) uv : vec2<f32>
2388      };
2389    
2390    fn filterVertexPosition(aPosition:vec2<f32>) -> vec4<f32>
2391    {
2392        var position = aPosition * gfu.uOutputFrame.zw + gfu.uOutputFrame.xy;
2393    
2394        position.x = position.x * (2.0 / gfu.uOutputTexture.x) - 1.0;
2395        position.y = position.y * (2.0*gfu.uOutputTexture.z / gfu.uOutputTexture.y) - gfu.uOutputTexture.z;
2396    
2397        return vec4(position, 0.0, 1.0);
2398    }
2399    
2400    fn filterTextureCoord( aPosition:vec2<f32> ) -> vec2<f32>
2401    {
2402        return aPosition * (gfu.uOutputFrame.zw * gfu.uInputSize.zw);
2403    }
2404    
2405    fn globalTextureCoord( aPosition:vec2<f32> ) -> vec2<f32>
2406    {
2407      return  (aPosition.xy / gfu.uGlobalFrame.zw) + (gfu.uGlobalFrame.xy / gfu.uGlobalFrame.zw);  
2408    }
2409    
2410    fn getSize() -> vec2<f32>
2411    {
2412      return gfu.uGlobalFrame.zw;
2413    }
2414      
2415    @vertex
2416    fn main(
2417      @location(0) aPosition : vec2<f32>, 
2418    ) -> VSOutput {
2419      return VSOutput(
2420       filterVertexPosition(aPosition),
2421       filterTextureCoord(aPosition)
2422      );
2423    }
2424    `;class ya extends hd{static U_BLEND_TEXTURE="uBlendTexture";static U_BLEND_TEXTURE_SAMPLER=ya.U_BLEND_TEXTURE+"Sampler";static U_PROGRESS="progress";id;_timelineStart;_timelineEnd;constructor(t){const{vertex:o,fragment:r}=rHe(t.type,ya.U_BLEND_TEXTURE,ya.U_PROGRESS),{vertex:n,fragment:a}=nHe(t.type,ya.U_BLEND_TEXTURE,ya.U_BLEND_TEXTURE_SAMPLER,ya.U_PROGRESS);super({glProgram:new cl({vertex:o,fragment:r,name:"BlendFilter_GL"}),gpuProgram:new xl({name:"BlendFilter_GPU",vertex:{source:n,entryPoint:"main"},fragment:{source:a,entryPoint:"main"}}),resources:{filterUniforms:{[ya.U_PROGRESS]:{value:0,type:"f32"}}}}),this.id=t.id,this._timelineStart=t.timelineStart,this._timelineEnd=t.t
2424imelineEnd}destroy(t){try{this.resources[ya.U_BLEND_TEXTURE]?.destroy&&this.resources[ya.U_BLEND_TEXTURE].destroy(!0)}catch(o){nn("BlendFilter").warn(null,Ae(void 0,o,"Error while destroying blend texture"))}super.destroy(t)}set source(t){this.resources[ya.U_BLEND_TEXTURE]?.destroy&&this.resources[ya.U_BLEND_TEXTURE].destroy(!0),this.resources[ya.U_BLEND_TEXTURE]=t,this.resources[ya.U_BLEND_TEXTURE_SAMPLER]=t.style}updateTime(t){this.resources.filterUniforms.uniforms[ya.U_PROGRESS]=rn.clamp((t-this._timelineStart)/(this._timelineEnd-this._timelineStart),0,1)}}const rHe=(e,t,o)=>{const r="uTexture",n="vTextureCoord",{functionName:a,functionImpl:i}=aHe(e,r,t,n,o),s=xS("webgl2"),x=`
2425#version 300 es
2426precision mediump float;
2427
2428in vec2 `+n+`;
2429out vec4 fragColor;
2430
2431uniform vec4 uInputSize;    // (width, height, 1/width, 1/height)
2432uniform vec4 uOutputFrame;  // (x, y, width, height)
2433uniform vec4 uOutputTexture;
2434uniform sampler2D `+r+`;
2435uniform sampler2D `+t+`;
2436
2437uniform float `+o+`;
2438
2439vec2 normUV(vec2 uv) {
2440  vec2 normalized = (uv * uInputSize.xy - uOutputFrame.xy) / uOutputFrame.zw;
2441  normalized.y = 1.0 - normalized.y;
2442  return normalized;
2443}
2444
2445`+i+`
2446
2447void main() {
2448  vec4 blendAppliedResult = `+a+`();
2449  fragColor = blendAppliedResult;
2450}
2451  `;return{vertex:s,fragment:x}},nHe=(e,t,o,r)=>{const n="uTexture",a="uSampler",i="position",{functionName:x,functionImpl:c}=iHe(e,n,t,a,o),l=xS("webgpu"),d=`
2452struct GlobalFilterUniforms {
2453  uInputSize:vec4<f32>,
2454  uInputPixel:vec4<f32>,
2455  uInputClamp:vec4<f32>,
2456  uOutputFrame:vec4<f32>,
2457  uGlobalFrame:vec4<f32>,
2458  uOutputTexture:vec4<f32>,
2459};
2460
2461struct FilterUniforms {
2462  `+r+`: f32,
2463};
2464
2465@group(0) @binding(0) var<uniform> gfu: GlobalFilterUniforms;
2466@group(0) @binding(1) var `+n+`: texture_2d<f32>;
2467@group(0) @binding(2) var `+a+`: sampler;
2468@group(1) @binding(0) var<uniform> filterUniforms : FilterUniforms;
2469@group(1) @binding(1) var `+t+`: texture_2d<f32>;
2470@group(1) @binding(2) var `+o+`: sampler;
2471
2472fn normUV(uv: vec2<f32>) -> vec2<f32> {
2473  var normalized = (uv * gfu.uInputSize.xy - gfu.uOutputFrame.xy) / gfu.uOutputFrame.zw;
2474  normalized.y = 1.0 - normalized.y;
2475  return normalized;
2476}
2477
2478`+c+`
2479
2480@fragment
2481fn main(
2482  @builtin(position) `+i+`: vec4<f32>,
2483  @location(0) uv : vec2<f32>
2484) -> @location(0) vec4<f32> {
2485  return `+x+"(uv, filterUniforms."+r+`);
2486}
2487  `;return{vertex:l,fragment:d}},aHe=(e,t,o,r,n)=>{const a=`
2488  vec4 getFromColor(sampler2D uTexture, vec2 textureCoordinate) {
2489    return texture(uTexture, textureCoordinate);
2490  }
2491  `,i=`
2492  vec4 getToColor(sampler2D uBlendTexture, vec2 textureCoordinate) {
2493    // Transform local texture coordinates to global output texture coordinates.
2494    // - textureCoordinate: normalized coordinates in the input frame [0,1].
2495    // - uInputSize.xy: size of the input frame in pixels.
2496    // - uOutputFrame.xy: position of the input frame within the output texture, in pixels.
2497    // - uOutputTexture.xy: size of the output texture in pixels.
2498    // The formula maps the input frame's local coordinates to the corresponding position in the output texture:
2499    //   global = (textureCoordinate * uInputSize.xy + uOutputFrame.xy) / uOutputTexture.xy
2500    // This ensures sampling from the correct region of the output texture.
2501    vec2 global = (textureCoordinate * uInputSize.xy + uOutputFrame.xy) / uOutputTexture.xy;
2502    return texture(uBlendTexture, global);
2503  }
2504  `;switch(e){case Ze.NONE:return{functionName:"noneTransition",functionImpl:`
2505`+a+`
2506`+i+`
2507vec4 noneTransition() {
2508  return getFromColor(`+t+", "+r+`);
2509}
2510      `};case Ze.CROSS_FADE:return{functionName:"crossFadeTransition",functionImpl:`
2511`+a+`
2512`+i+`
2513vec4 crossFadeTransition() {
2514  return mix(getFromColor(`+t+", "+r+"), getToColor("+o+", "+r+"), "+n+`);
2515}
2516      `};case Ze.LINEAR_BLUR:return{functionName:"linearBlurTransition",functionImpl:`
2517`+a+`
2518`+i+`
2519vec4 linearBlurTransition() {
2520  vec2 uv = `+r+`;
2521  float progress = `+n+`;
2522  const int samples = 6;
2523  const float intensity = 0.1;
2524  vec4 fromColor = vec4(0.0);
2525  vec4 toColor = vec4(0.0);
2526
2527  float displacement = intensity * (0.5 - distance(0.5, progress));
2528  for (int xi = 0; xi < samples; xi++)
2529  {
2530      float offsetX = float(xi) / float(samples) - 0.5;
2531      for (int yi = 0; yi < samples; yi++)
2532      {
2533          float offsetY = float(yi) / float(samples) - 0.5;
2534          vec2 offset = vec2(offsetX, offsetY);
2535          fromColor += getFromColor(`+t+`, uv + displacement * offset);
2536          toColor += getToColor(`+o+`, uv + displacement * offset);
2537      }
2538  }
2539  fromColor /= float(samples * samples);
2540  toColor /= float(samples * samples);
2541  return mix(fromColor, toColor, progress);
2542}
2543      `};case Ze.DIRECTIONAL_WARP:return{functionName:"directionalWarpTransition",functionImpl:`
2544`+a+`
2545`+i+`
2546vec4 directionalWarpTransition() {
2547  vec2 uv = `+r+`;
2548  float progress = `+n+`;
2549
2550  float smoothness = 0.5;
2551  vec2 center = vec2(0.5, 0.5);
2552  vec2 direction = vec2(-1.0, 1.0); 
2553  direction /= abs(direction.x) + abs(direction.y);
2554
2555  float directionalDot = direction.x * center.x + direction.y * center.y;
2556  float transitionFactor = 1.0 - smoothstep(-smoothness, 0.0,
2557     direction.x * uv.x + direction.y * uv.y 
2558     - (directionalDot - 0.5 + progress * ( 1.0 + smoothness)));
2559
2560  return mix(
2561    getFromColor(`+t+`, (uv - 0.5) * (1.0 - transitionFactor) + 0.5),
2562    getToColor(`+o+`, (uv - 0.5) * transitionFactor + 0.5),
2563    transitionFactor);
2564}
2565      `};case Ze.GLITCH_MEMORIES:return{functionName:"glitchMemoriesTransition",functionImpl:`
2566`+a+`
2567`+i+`
2568vec4 glitchMemoriesTransition() {
2569  vec2 uv = `+r+`;
2570  float progress = `+n+`;
2571
2572  vec2 noiseTextureCoord = vec2(0.0, 0.0);
2573  noiseTextureCoord += floor(vec2(progress) * vec2(1200.0, 3500.0)) / vec2(64);
2574  vec2 noiseDistortion = progress > 0.0 ? (fract(noiseTextureCoord) - 0.5) * 0.3 *(1.0 - progress) : vec2(0.0);
2575  vec2 redCoord = uv + noiseDistortion * 0.2;
2576  vec2 greenCoord = uv + noiseDistortion * 0.3;
2577  vec2 blueCoord = uv + noiseDistortion * 0.5;
2578
2579  return vec4(
2580    mix(getFromColor(`+t+", redCoord), getToColor("+o+`, redCoord), progress).r,
2581    mix(getFromColor(`+t+", greenCoord), getToColor("+o+`, greenCoord), progress).g,
2582    mix(getFromColor(`+t+", blueCoord), getToColor("+o+`, blueCoord), progress).b,
2583    1.0);
2584}
2585      `};case Ze.PIXELIZE:return{functionName:"pixelizeTransition",functionImpl:`
2586`+a+`
2587`+i+`
2588vec4 pixelizeTransition() {
2589  ivec2 squaresMin = ivec2(20, 20);
2590  int pixelizeSteps = 50;
2591  vec2 uv = `+r+`;
2592  float progress = `+n+`;
2593  int steps = pixelizeSteps;
2594
2595  float pixelizationLevel = min(progress, 1.0 - progress);
2596  float dist = steps > 0 ? ceil(pixelizationLevel * float(steps)) / float(steps) : pixelizationLevel;
2597  vec2 squareSize = 2.0 * dist / vec2(squaresMin);
2598
2599  vec2 pixelizedCoord = dist > 0.0 ? (floor(uv / squareSize) + 0.5) * squareSize : uv;
2600  return mix(getFromColor(`+t+", pixelizedCoord), getToColor("+o+`, pixelizedCoord), progress);
2601}
2602      `};case Ze.WIND:return{functionName:"windTransition",functionImpl:`
2603`+a+`
2604`+i+`
2605float windRand (vec2 coord) {
2606  return fract(sin(dot(coord.xy ,vec2(12.9898,78.233))) * 43758.5453);
2607}
2608
2609vec4 windTransition () {
2610  vec2 uv = `+r+`;
2611  float progress = `+n+`;
2612  float windSize = 0.3;
2613
2614  float random = windRand(vec2(0, uv.y));
2615  float windEffectIntensity = smoothstep(
2616    0.0, 
2617    -windSize, 
2618    uv.x * (1.0 - windSize) + windSize * random - (progress * (1.0 + windSize))
2619  );
2620
2621  return mix(
2622    getFromColor(`+t+`, uv),
2623    getToColor(`+o+`, uv),
2624    windEffectIntensity
2625  );
2626}
2627      `};case Ze.VERTICAL_WIPE:return{functionName:"verticalWipeTransition",functionImpl:`
2628`+a+`
2629`+i+`
2630vec4 verticalWipeTransition() {
2631  vec2 uv = `+r+`;
2632  float progress = `+n+`;
2633
2634  vec2 uvNorm = (uv * uInputSize.xy - uOutputFrame.xy) / uOutputFrame.zw;
2635  vec2 adjustedUV = uvNorm + vec2(0.0, progress);
2636  vec2 fractUV = fract(adjustedUV);
2637
2638  float inside =
2639    step(0.0, adjustedUV.x) * step(adjustedUV.x, 1.0) *
2640    step(0.0, adjustedUV.y) * step(adjustedUV.y, 1.0);
2641
2642  vec2 finalUV = fractUV * uOutputFrame.zw / uInputSize.xy + uOutputFrame.xy / uInputSize.xy;
2643
2644  return mix(
2645    getToColor(`+o+`, finalUV),
2646    getFromColor(`+t+`, finalUV),
2647    inside
2648  );
2649}
2650      `};case Ze.SIMPLE_ZOOM:return{functionName:"simpleZoomTransition",functionImpl:`
2651`+a+`
2652`+i+`
2653vec2 zoomEffect(vec2 uv, float zoomIntensity) {
2654  return 0.5 + ((uv - 0.5) * (1.0 - zoomIntensity));
2655}
2656
2657vec4 simpleZoomTransition() {
2658  vec2 uv = `+r+`;
2659  float progress = `+n+`;
2660  float zoomIntensity = 0.8;
2661  float normalizedIntensity = clamp(zoomIntensity, 0.2, 1.0);
2662
2663  vec2 normalizedUV = (uv * uInputSize.xy - uOutputFrame.xy) / uOutputFrame.zw;
2664  vec2 zoomedUV = zoomEffect(normalizedUV, smoothstep(0.0, normalizedIntensity, progress));
2665  vec2 finalUV = zoomedUV * uOutputFrame.zw / uInputSize.xy + uOutputFrame.xy / uInputSize.xy;
2666
2667  return mix(
2668    getFromColor(`+t+`, finalUV),
2669    getToColor(`+o+`, uv),
2670    smoothstep(normalizedIntensity - 0.2, 1.0, progress)
2671  );
2672}
2673      `};case Ze.WIPE_LEFT:return{functionName:"wipeLeftTransition",functionImpl:`
2674`+a+`
2675`+i+`
2676vec4 wipeLeftTransition() {
2677  vec2 uv = `+r+`;
2678  float progress = `+n+`;
2679
2680  vec4 fromColor = getFromColor(`+t+`, uv);
2681  vec4 toColor = getToColor(`+o+`, uv);
2682  
2683  float fade = step(1.0 - uv.x, progress);
2684  return mix(fromColor, toColor, fade);
2685}
2686      `};case Ze.WIPE_RIGHT:return{functionName:"wipeRightTransition",functionImpl:`
2687`+a+`
2688`+i+`
2689vec4 wipeRightTransition() {
2690  vec2 uv = `+r+`;
2691  float progress = `+n+`;
2692
2693  vec4 fromColor = getFromColor(`+t+`, uv);
2694  vec4 toColor = getToColor(`+o+`, uv);
2695  
2696  float fade = step(uv.x, progress);
2697  return mix(fromColor, toColor, fade);
2698}
2699      `};case Ze.WIPE_UP:return{functionName:"wipeUpTransition",functionImpl:`
2700`+a+`
2701`+i+`
2702vec4 wipeUpTransition() {
2703  vec2 uv = `+r+`;
2704  float progress = `+n+`;
2705
2706  vec4 fromColor = getFromColor(`+t+`, uv);
2707  vec4 toColor = getToColor(`+o+`, uv);
2708  
2709  float fade = step(1.0 - uv.y, progress);
2710  return mix(fromColor, toColor, fade);
2711}
2712      `};case Ze.WIPE_DOWN:return{functionName:"wipeDownTransition",functionImpl:`
2713`+a+`
2714`+i+`
2715vec4 wipeDownTransition() {
2716  vec2 uv = `+r+`;
2717  float progress = `+n+`;
2718
2719  vec4 fromColor = getFromColor(`+t+`, uv);
2720  vec4 toColor = getToColor(`+o+`, uv);
2721  
2722  float fade = step(uv.y, progress);
2723  return mix(fromColor, toColor, fade);
2724}
2725      `};case Ze.IRIS:return{functionName:"irisTransition",functionImpl:`
2726`+a+`
2727`+i+`
2728vec4 irisTransition() {
2729  vec2 uv = `+r+`;
2730  float progress = `+n+`;
2731
2732  vec2 ellipseScale = vec2(1.0, 0.5);
2733  float circleSize = pow(2.0 * abs(progress - 0.5), 3.0);
2734  vec4 backgroundColor = vec4(0.0, 0.0, 0.0, 1.0);
2735
2736  float distFromCenter = length((normUV(uv) - 0.5) * ellipseScale);
2737  return mix(
2738    progress < 0.5 ? getFromColor(`+t+", uv) : getToColor("+o+`, uv),
2739    backgroundColor,
2740    step(circleSize, distFromCenter)
2741  );
2742}
2743      `};case Ze.DREAMY:return{functionName:"dreamyTransition",functionImpl:`
2744`+a+`
2745`+i+`
2746vec2 calculateOffset(float progress, float horizontalPosition, float phaseOffset) {
2747  float phase = progress * progress + progress + phaseOffset;
2748  float verticalOffset = 0.03 * progress * cos(10.0 * (progress + horizontalPosition));
2749  return vec2(0, verticalOffset);
2750}
2751vec4 dreamyTransition() {
2752  vec2 uv = `+r+`;
2753  float progress = `+n+`;
2754  
2755  vec2 offsetStart = calculateOffset(progress, uv.x, 0.0);
2756  vec2 offsetEnd = calculateOffset(1.0 - progress, uv.x, 3.14);
2757
2758  return mix(
2759    getFromColor(`+t+`, uv + offsetStart),
2760    getToColor(`+o+`, uv + offsetEnd),
2761    progress
2762  );
2763}
2764      `};case Ze.RADIAL:return{functionName:"radialTransition",functionImpl:`
2765`+a+`
2766`+i+`
2767vec4 radialTransition() {
2768  const float PI = 3.141592653589;
2769  float smoothness = 1.0;
2770  vec2 uv = `+r+`;
2771  float progress = `+n+`;
2772  vec2 normalizedUV = normUV(uv) * 2.0 - 1.0;
2773  
2774  float angleOffset = atan(normalizedUV.y, normalizedUV.x) + (progress - 0.5) * PI * 2.5;
2775
2776  return mix(
2777    getFromColor(`+t+`, uv),
2778    getToColor(`+o+`, uv),
2779    smoothstep(0.0, smoothness, angleOffset)
2780  );
2781}
2782      `};case Ze.WINDOW_BLIND:return{functionName:"windowBlindTransition",functionImpl:`
2783`+a+`
2784`+i+`
2785vec4 windowBlindTransition () {
2786  vec2 uv = `+r+`;
2787  float progress = `+n+`;
2788  float adjustedProgress = progress;
2789
2790  if (mod(floor(uv.y * 100.0 * progress), 2.0) == 0.0)
2791    adjustedProgress *= 1.5;
2792
2793  return mix(
2794    getFromColor(`+t+`, uv),
2795    getToColor(`+o+`, uv),
2796    mix(adjustedProgress, progress, smoothstep(0.8, 1.0, progress))
2797  );
2798}
2799      `};case Ze.CIRCLE_OPEN:return{functionName:"circleOpenTransition",functionImpl:`
2800`+a+`
2801`+i+`
2802vec4 circleOpenTransition () {
2803  vec2 uv = `+r+`;
2804  const vec2 center = vec2(0.5, 0.5);
2805  const float SQRT_2 = 1.414213562373;
2806  const float smoothness = 0.5;
2807  float progress = `+n+`;
2808
2809  float mask = smoothstep(
2810    -smoothness,
2811    0.0,
2812    SQRT_2 * distance(center, normUV(uv)) - progress * (1.0 + smoothness)
2813  );
2814
2815  return mix(getFromColor(`+t+", uv), getToColor("+o+`, uv), 1.0 - mask);
2816}
2817      `};case Ze.DIRECTIONAL_WIPE:return{functionName:"directionalWipeTransition",functionImpl:`
2818`+a+`
2819`+i+`
2820vec4 directionalWipeTransition () {
2821  vec2 uv = `+r+`;
2822  const vec2 center = vec2(0.5, 0.5);
2823  const float smoothness = 0.5;
2824  float progress = `+n+`;
2825
2826  vec2 wipeDirection = vec2(1.0, -1.0); 
2827  vec2 normalizedDirection = normalize(wipeDirection);
2828  normalizedDirection /= abs(normalizedDirection.x) + abs(normalizedDirection.y);
2829  float lineOffset = normalizedDirection.x * center.x + normalizedDirection.y * center.y;
2830  float mask =
2831    (1.0 - step(progress, 0.0)) *
2832    (1.0 - smoothstep(-smoothness, 0.0, normalizedDirection.x * uv.x +
2833       normalizedDirection.y * uv.y - (lineOffset - 0.5 + progress * (1.0 + smoothness))));
2834  return mix(getFromColor(`+t+", uv), getToColor("+o+`, uv), mask);
2835}
2836      `};case Ze.MORPH:return{functionName:"morphTransition",functionImpl:`
2837`+a+`
2838`+i+`
2839vec4 morphTransition() {
2840  vec2 uv = `+r+`;
2841  float progress = `+n+`;
2842  float intensity = 0.1;
2843
2844  vec4 fromColor = getFromColor(`+t+`, uv);
2845  vec4 toColor = getToColor(`+o+`, uv);
2846
2847  vec2 offsetStart = (((fromColor.rg + fromColor.b) * 0.5) * 2.0 - 1.0);
2848  vec2 offsetEnd = (((toColor.rg + toColor.b) * 0.5) * 2.0 - 1.0);
2849  vec2 offsetMorph = mix(offsetStart, offsetEnd, 0.5) * intensity;
2850
2851  float startWeight = progress;
2852  float endWeight = 1.0 - startWeight;
2853
2854  return mix(
2855    getFromColor(`+t+`, uv + offsetMorph * startWeight),
2856    getToColor(`+o+`, uv - offsetMorph * endWeight),
2857    progress);
2858}
2859      `};case Ze.BLACK_FADE_OUT:return{functionName:"blackFadeOutTransition",functionImpl:`
2860`+a+`
2861`+i+`
2862vec4 blackFadeOutTransition() {
2863  vec2 uv = `+r+`;
2864  float progress = `+n+`;
2865  vec4 blackVec = vec4(0.0, 0.0, 0.0, 1.0);
2866
2867  return mix(
2868    getFromColor(`+t+`, uv),
2869    blackVec,
2870    smoothstep(0.0, 1.0, progress)
2871  );
2872}
2873      `};case Ze.WHITE_FADE_OUT:return{functionName:"whiteFadeOutTransition",functionImpl:`
2874`+a+`
2875`+i+`
2876vec4 whiteFadeOutTransition() {
2877  vec2 uv = `+r+`;
2878  float progress = `+n+`;
2879  vec4 whiteVec = vec4(1.0, 1.0, 1.0, 1.0);
2880
2881  return mix(
2882    getFromColor(`+t+`, uv),
2883    whiteVec,
2884    smoothstep(0.0, 1.0, progress)
2885  );
2886}
2887      `};case Ze.COLOR_DISTANCE:return{functionName:"colorDistanceTransition",functionImpl:`
2888`+a+`
2889`+i+`
2890vec4 colorDistanceTransition() {
2891  float power = 5.0;
2892  vec2 uv = `+r+`;
2893  float progress = `+n+`;
2894
2895  vec4 fromColor = getFromColor(`+t+`, uv);
2896  vec4 toColor = getToColor(`+o+`, uv);
2897  float transitionMask = step(distance(fromColor, toColor), progress);
2898  
2899  vec4 mixedColor = mix(fromColor, toColor, transitionMask);
2900
2901  return mix(
2902    mixedColor,
2903    toColor,
2904    pow(progress, power)
2905  );
2906}
2907      `};case Ze.GRAY_SCALE_FADE:return{functionName:"grayScaleFadeTransition",functionImpl:`
2908`+a+`
2909`+i+`
2910vec3 toGrayScale(vec3 color) {
2911      float gray = dot(color, vec3(0.2126, 0.7152, 0.0722));
2912      return vec3(gray);
2913    }
2914
2915vec4 grayScaleFadeTransition () {
2916  float intensity = 0.3;
2917  vec2 uv = `+r+`;
2918  float progress = `+n+`;
2919
2920  vec4 fromColor = getFromColor(`+t+`, uv);
2921  vec4 toColor = getToColor(`+o+`, uv);
2922
2923  vec4 fromGrayScale = vec4(toGrayScale(fromColor.rgb), 1.0);
2924  vec4 toGrayScale = vec4(toGrayScale(toColor.rgb), 1.0);
2925
2926  vec4 fromMixed = mix(fromGrayScale, fromColor, smoothstep(1.0 - intensity, 0.0, progress));
2927  vec4 toMixed = mix(toGrayScale, toColor, smoothstep(intensity, 1.0, progress));
2928
2929  return mix(fromMixed, toMixed, progress);
2930}
2931      `}}},iHe=(e,t,o,r,n)=>{const a=`
2932fn mix4(a: vec4<f32>, b: vec4<f32>, t: f32) -> vec4<f32> {
2933  return a * (1.0 - t) + b * t;
2934}
2935
2936fn getFromColor(tc: vec2<f32>) -> vec4<f32> {
2937  return textureSample(`+t+", "+r+`, tc);
2938}
2939
2940fn getToColor(c: vec2<f32>) -> vec4<f32> {
2941  let global = (c * gfu.uInputSize.xy + gfu.uOutputFrame.xy) / gfu.uOutputTexture.xy;
2942  return textureSample(`+o+", "+n+`, global);
2943}
2944
2945  `,i={[Ze.NONE]:{functionName:"noneTransition",functionImpl:`
2946  fn noneTransition(uv: vec2<f32>, progress: f32) -> vec4<f32> {
2947    return getFromColor(uv);
2948  }
2949  `},[Ze.CROSS_FADE]:{functionName:"crossFadeTransition",functionImpl:`
2950  fn crossFadeTransition(uv: vec2<f32>, progress: f32) -> vec4<f32> {
2951    return mix4(getFromColor(uv), getToColor(uv), progress);
2952  }
2953  `},[Ze.LINEAR_BLUR]:{functionName:"linearBlurTransition",functionImpl:`
2954  fn linearBlurTransition(uv: vec2<f32>, progress: f32) -> vec4<f32> {
2955    let intensity: f32 = 0.1;
2956    let samples : i32 = 6;
2957    var fromColor : vec4<f32> = vec4<f32>(0.0);
2958    var toColor   : vec4<f32> = vec4<f32>(0.0);
2959  
2960    let displacement = intensity * (0.5 - abs(0.5 - progress));
2961    for (var xi: i32 = 0; xi < samples; xi = xi + 1) {
2962      let offsetX: f32 = f32(xi) / f32(samples) - 0.5;
2963      for (var yi: i32 = 0; yi < samples; yi = yi + 1) {
2964        let offsetY: f32 = f32(yi) / f32(samples) - 0.5;
2965        let offset : vec2<f32> = vec2<f32>(offsetX, offsetY);
2966        fromColor += getFromColor(uv + displacement * offset);
2967        toColor   += getToColor  (uv + displacement * offset);
2968      }
2969    }
2970    fromColor = fromColor / f32(samples * samples);
2971    toColor   = toColor   / f32(samples * samples);
2972    return mix4(fromColor, toColor, progress);
2973  }
2974  `},[Ze.DIRECTIONAL_WARP]:{functionName:"directionalWarpTransition",functionImpl:`
2975  fn directionalWarpTransition(uv: vec2<f32>, progress: f32) -> vec4<f32> {
2976    let smoothness : f32 = 0.5;
2977    let center     : vec2<f32> = vec2<f32>(0.5, 0.5);
2978    var direction  : vec2<f32> = vec2<f32>(-1.0, 1.0);
2979    direction = direction / (abs(direction.x) + abs(direction.y));
2980  
2981    let directionalDot = direction.x * center.x + direction.y * center.y;
2982    let tFactor = 1.0 - smoothstep(
2983      -smoothness, 0.0,
2984      direction.x * uv.x + direction.y * uv.y -
2985        (directionalDot - 0.5 + progress * (1.0 + smoothness))
2986    );
2987  
2988    return mix4(
2989      getFromColor( (uv - 0.5) * (1.0 - tFactor) + 0.5 ),
2990      getToColor  ( (uv - 0.5) * tFactor           + 0.5 ),
2991      tFactor
2992    );
2993  }
2994  `},[Ze.GLITCH_MEMORIES]:{functionName:"glitchMemoriesTransition",functionImpl:`
2995  fn glitchMemoriesTransition(uv: vec2<f32>, progress: f32) -> vec4<f32> {
2996    var noiseTc = vec2<f32>(0.0, 0.0);
2997    noiseTc = noiseTc + floor(vec2<f32>(progress, progress) * vec2<f32>(1200.0, 3500.0)) / vec2<f32>(64.0, 64.0);
2998    let noiseDist = select(
2999        vec2<f32>(0.0, 0.0),
3000        (fract(noiseTc) - 0.5) * 0.3 * (1.0 - progress),
3001        progress > 0.0
3002    );
3003  
3004    let redCoord   = uv + noiseDist * 0.2;
3005    let greenCoord = uv + noiseDist * 0.3;
3006    let blueCoord  = uv + noiseDist * 0.5;
3007  
3008    return vec4<f32>(
3009      mix4(getFromColor(redCoord),   getToColor(redCoord),   progress).r,
3010      mix4(getFromColor(greenCoord), getToColor(greenCoord), progress).g,
3011      mix4(getFromColor(blueCoord),  getToColor(blueCoord),  progress).b,
3012      1.0
3013    );
3014  }
3015  `},[Ze.PIXELIZE]:{functionName:"pixelizeTransition",functionImpl:`
3016  fn pixelizeTransition(uv: vec2<f32>, progress: f32) -> vec4<f32> {
3017    let steps : i32 = 50;
3018    let squaresMin : vec2<f32> = vec2<f32>(20.0, 20.0);
3019  
3020    let level = min(progress, 1.0 - progress);
3021    let dist  = select(
3022        level,
3023        ceil(level * f32(steps)) / f32(steps),
3024        steps > 0
3025    );
3026  
3027    let squareSize = 2.0 * dist / squaresMin;
3028    let pixUV = select(
3029        uv,
3030        (floor(uv / squareSize) + 0.5) * squareSize,
3031        dist > 0.0
3032    );
3033  
3034    return mix4(getFromColor(pixUV), getToColor(pixUV), progress);
3035  }
3036  `},[Ze.WIND]:{functionName:"windTransition",functionImpl:`
3037  fn rand2(coord: vec2<f32>) -> f32 {
3038    return fract(sin(dot(coord, vec2<f32>(12.9898, 78.233))) * 43758.5453);
3039  }
3040  
3041  fn windTransition(uv: vec2<f32>, progress: f32) -> vec4<f32> {
3042    let windSize : f32 = 0.3;
3043    let r = rand2(vec2<f32>(0.0, uv.y));
3044  
3045    let intensity = smoothstep(
3046        0.0, -windSize,
3047        uv.x * (1.0 - windSize) + windSize * r - progress * (1.0 + windSize)
3048    );
3049  
3050    return mix4(
3051        getFromColor(uv),
3052        getToColor(uv),
3053        intensity
3054    );
3055  }
3056  `},[Ze.VERTICAL_WIPE]:{functionName:"verticalWipeTransition",functionImpl:`
3057  fn verticalWipeTransition(uv: vec2<f32>, progress: f32) -> vec4<f32> {
3058    let uvNorm = (uv * gfu.uInputSize.xy - gfu.uOutputFrame.xy) / gfu.uOutputFrame.zw;
3059    let adjusted = uvNorm + vec2<f32>(0.0, progress);
3060    let fractUv  = fract(adjusted);
3061
3062    let inside =
3063      step(0.0, adjusted.x) * step(adjusted.x, 1.0) *
3064      step(0.0, adjusted.y) * step(adjusted.y, 1.0);
3065
3066    let finalUV =
3067      fractUv * gfu.uOutputFrame.zw / gfu.uInputSize.xy + gfu.uOutputFrame.xy / gfu.uInputSize.xy;
3068
3069    return mix4(
3070      getToColor(finalUV),
3071      getFromColor(finalUV),
3072      inside
3073    );
3074  }
3075  `},[Ze.SIMPLE_ZOOM]:{functionName:"simpleZoomTransition",functionImpl:`
3076  fn zoom(uv: vec2<f32>, z: f32) -> vec2<f32> {
3077    return vec2<f32>(0.5, 0.5) + (uv - vec2<f32>(0.5, 0.5)) * (1.0 - z);
3078  }
3079  
3080  fn simpleZoomTransition(uv: vec2<f32>, progress: f32) -> vec4<f32> {
3081    let zoomIntensity = 0.8;
3082    let normInt       = clamp(zoomIntensity, 0.2, 1.0);
3083
3084    let normalizedUV = (uv * gfu.uInputSize.xy - gfu.uOutputFrame.xy) / gfu.uOutputFrame.zw;
3085    let zoomedUV = zoom(normalizedUV, smoothstep(0.0, normInt, progress));
3086    let finalUV = zoomedUV * gfu.uOutputFrame.zw / gfu.uInputSize.xy + gfu.uOutputFrame.xy / gfu.uInputSize.xy;
3087  
3088    return mix4(
3089      getFromColor(finalUV),
3090      getToColor(uv),
3091      smoothstep(normInt - 0.2, 1.0, progress)
3092    );
3093  }
3094  `},[Ze.WIPE_LEFT]:{functionName:"wipeLeftTransition",functionImpl:`
3095  fn wipeLeftTransition(uv: vec2<f32>, progress: f32) -> vec4<f32> {
3096    let fade = step(1.0 - uv.x, progress);
3097    return mix4(getFromColor(uv), getToColor(uv), fade);
3098  }
3099  `},[Ze.WIPE_RIGHT]:{functionName:"wipeRightTransition",functionImpl:`
3100  fn wipeRightTransition(uv: vec2<f32>, progress: f32) -> vec4<f32> {
3101    let fade = step(uv.x, progress);
3102    return mix4(getFromColor(uv), getToColor(uv), fade);
3103  }
3104  `},[Ze.WIPE_UP]:{functionName:"wipeUpTransition",functionImpl:`
3105  fn wipeUpTransition(uv: vec2<f32>, progress: f32) -> vec4<f32> {
3106    let fade = step(1.0 - uv.y, progress);
3107    return mix4(getFromColor(uv), getToColor(uv), fade);
3108  }
3109  `},[Ze.WIPE_DOWN]:{functionName:"wipeDownTransition",functionImpl:`
3110  fn wipeDownTransition(uv: vec2<f32>, progress: f32) -> vec4<f32> {
3111    let fade = step(uv.y, progress);
3112    return mix4(getFromColor(uv), getToColor(uv), fade);
3113  }
3114  `}
3114,[Ze.IRIS]:{functionName:"circleCropTransition",functionImpl:`
3115  fn circleCropTransition(uv: vec2<f32>, progress: f32) -> vec4<f32> {
3116    let ellipseScale = vec2<f32>(1.0, 0.5);
3117    let circleSize   = pow(2.0 * abs(progress - 0.5), 3.0);
3118    let bg           = vec4<f32>(0.0, 0.0, 0.0, 1.0);
3119  
3120    let d = length((normUV(uv) - vec2<f32>(0.5, 0.5)) * ellipseScale);
3121    return mix4(
3122      select(getFromColor(uv), getToColor(uv), progress >= 0.5),
3123      bg,
3124      step(circleSize, d)
3125    );
3126  }
3127  `},[Ze.DREAMY]:{functionName:"dreamyTransition",functionImpl:`
3128  fn offset(progress: f32, x: f32, phase: f32) -> vec2<f32> {
3129    let v = 0.03 * progress * cos(10.0 * (progress + x));
3130    return vec2<f32>(0.0, v);
3131  }
3132  
3133  fn dreamyTransition(uv: vec2<f32>, progress: f32) -> vec4<f32> {
3134    let offStart = offset(progress,           uv.x, 0.0);
3135    let offEnd   = offset(1.0 - progress, uv.x, 3.14159265);
3136  
3137    return mix4(
3138      getFromColor(uv + offStart),
3139      getToColor  (uv + offEnd),
3140      progress
3141    );
3142  }
3143  `},[Ze.RADIAL]:{functionName:"radialTransition",functionImpl:`
3144  fn radialTransition(uv: vec2<f32>, progress: f32) -> vec4<f32> {
3145    let PI = 3.141592653589;
3146    let smoothness: f32 = 1.0;
3147  
3148    let norm = normUV(uv) * 2.0 - vec2<f32>(1.0, 1.0);
3149    let angle = atan2(norm.y, norm.x) + (progress - 0.5) * PI * 2.5;
3150    return mix4(getFromColor(uv), getToColor(uv), smoothstep(0.0, smoothness, angle));
3151  }
3152  `},[Ze.WINDOW_BLIND]:{functionName:"windowBlindTransition",functionImpl:`
3153  fn windowBlindTransition(uv: vec2<f32>, progress: f32) -> vec4<f32> {
3154    var adj = progress;
3155    if ((i32(floor(uv.y * 100.0 * progress)) % 2) == 0) {
3156      adj = adj * 1.5;
3157    }
3158    return mix4(
3159      getFromColor(uv),
3160      getToColor(uv),
3161      mix(adj, progress, smoothstep(0.8, 1.0, progress))
3162    );
3163  }
3164  `},[Ze.CIRCLE_OPEN]:{functionName:"circleOpenTransition",functionImpl:`
3165  fn circleOpenTransition(uv: vec2<f32>, progress: f32) -> vec4<f32> {
3166    let SQRT_2     : f32 = 1.414213562373;
3167    let smoothness : f32 = 0.5;
3168  
3169    let mask = smoothstep(
3170      -smoothness, 0.0,
3171      SQRT_2 * distance(vec2<f32>(0.5,0.5), normUV(uv)) - progress * (1.0 + smoothness)
3172    );
3173    return mix4(getFromColor(uv), getToColor(uv), 1.0 - mask);
3174  }
3175  `},[Ze.DIRECTIONAL_WIPE]:{functionName:"directionalWipeTransition",functionImpl:`
3176  fn directionalWipeTransition(uv: vec2<f32>, progress: f32) -> vec4<f32> {
3177    let smoothness : f32 = 0.5;
3178    let dir        : vec2<f32> = vec2<f32>(1.0, -1.0);
3179    let normDir    : vec2<f32> = dir / (abs(dir.x) + abs(dir.y));
3180    let lineOffset : f32 = dot(normDir, vec2<f32>(0.5,0.5));
3181  
3182    let mask = (1.0 - step(progress, 0.0)) *
3183               (1.0 - smoothstep(
3184                 -smoothness, 0.0,
3185                 dot(normDir, uv) - (lineOffset - 0.5 + progress * (1.0 + smoothness))
3186               ));
3187    return mix4(getFromColor(uv), getToColor(uv), mask);
3188  }
3189  `},[Ze.MORPH]:{functionName:"morphTransition",functionImpl:`
3190  fn morphTransition(uv: vec2<f32>, progress: f32) -> vec4<f32> {
3191    let intensity = 0.1;
3192    let fromC = getFromColor(uv);
3193    let toC   = getToColor(uv);
3194  
3195    let offStart = ((fromC.rg + fromC.b) * 0.5) * 2.0 - 1.0;
3196    let offEnd   = ((toC.rg   + toC.b)   * 0.5) * 2.0 - 1.0;
3197    let morphOff = mix(offStart, offEnd, 0.5) * intensity;
3198  
3199    return mix4(
3200      getFromColor(uv + morphOff * progress),
3201      getToColor  (uv - morphOff * (1.0 - progress)),
3202      progress
3203    );
3204  }
3205  `},[Ze.BLACK_FADE_OUT]:{functionName:"blackFadeOutTransition",functionImpl:`
3206  fn blackFadeOutTransition(uv: vec2<f32>, progress: f32) -> vec4<f32> {
3207    return mix4(
3208      getFromColor(uv),
3209      vec4<f32>(0.0, 0.0, 0.0, 1.0),
3210      smoothstep(0.0, 1.0, progress)
3211    );
3212  }
3213  `},[Ze.WHITE_FADE_OUT]:{functionName:"whiteFadeOutTransition",functionImpl:`
3214  fn whiteFadeOutTransition(uv: vec2<f32>, progress: f32) -> vec4<f32> {
3215    return mix4(
3216      getFromColor(uv),
3217      vec4<f32>(1.0, 1.0, 1.0, 1.0),
3218      smoothstep(0.0, 1.0, progress)
3219    );
3220  }
3221  `},[Ze.COLOR_DISTANCE]:{functionName:"colorDistanceTransition",functionImpl:`
3222  fn colorDistanceTransition(uv: vec2<f32>, progress: f32) -> vec4<f32> {
3223    let power: f32 = 5.0;
3224    let fromC = getFromColor(uv);
3225    let toC   = getToColor(uv);
3226    let mask  = step(distance(fromC, toC), progress);
3227    let mixed = mix4(fromC, toC, mask);
3228    return mix4(mixed, toC, pow(progress, power));
3229  }
3230  `},[Ze.GRAY_SCALE_FADE]:{functionName:"grayScaleFadeTransition",functionImpl:`
3231  fn toGray(c: vec3<f32>) -> vec3<f32> {
3232    let g = dot(c, vec3<f32>(0.2126, 0.7152, 0.0722));
3233    return vec3<f32>(g, g, g);
3234  }
3235  
3236  fn grayScaleFadeTransition(uv: vec2<f32>, progress: f32) -> vec4<f32> {
3237    let intensity = 0.3;
3238    let fromC = getFromColor(uv);
3239    let toC   = getToColor(uv);
3240  
3241    let fromGray = vec4<f32>(toGray(fromC.rgb), 1.0);
3242    let toGray   = vec4<f32>(toGray(toC.rgb),   1.0);
3243  
3244    let fromMix = mix4(fromGray, fromC, smoothstep(1.0 - intensity, 0.0, progress));
3245    let toMix   = mix4(toGray,   toC,   smoothstep(intensity,       1.0, progress));
3246  
3247    return mix4(fromMix, toMix, progress);
3248  }
3249  `}};return{functionName:i[e].functionName,functionImpl:a+i[e].functionImpl}};class sHe{currentEffectId;sprite;async apply(t,o){this.sprite=o.sprite;const r=t.effects?.Filter;if(!r){this.currentEffectId!==void 0&&(Au(o.sprite,wa,!0),this.currentEffectId=void 0);return}const n=Ru(o.sprite,wa);if(n?.id===r.effectId){this.currentEffectId=r.effectId;return}n&&Au(o.sprite,wa,!0),await this.applyLutFilter(o,r),this.currentEffectId=r.effectId}destroy(){this.sprite&&Au(this.sprite,wa,!0),this.currentEffectId=void 0,this.sprite=void 0}async applyLutFilter(t,o){const{blob:r,release:n}=await t.assetFetcher.get(o.source),a=mx.from(await Lc(r));a.source.style.scaleMode="nearest",a.source.style.addressMode="clamp-to-edge",a.source.autoGenerateMipmaps=!1;const i=new wa({id:o.effectId,alpha:o.alpha,lut:a.source});bP(t.sprite,i),a.destroy(!1),a.source.once("destroy",()=>{n()})}}class wa extends hd{static U_LUT="uLUT";static U_ALPHA="uAlpha";static U_LUT_SAMPLER=wa.U_LUT+"Sampler";id;constructor(t){const{vertex:o,fragment:r}=xHe(wa.U_LUT,wa.U_ALPHA),{vertex:n,fragment:a}=cHe(wa.U_LUT,wa.U_LUT_SAMPLER,wa.U_ALPHA);super({glProgram:new cl({vertex:o,fragment:r,name:"LUTFilter_GL"}),gpuProgram:new xl({name:"LUTFilter_GPU",vertex:{source:n,entryPoint:"main"},fragment:{source:a,entryPoint:"main"}}),resources:{[wa.U_LUT]:t.lut,[wa.U_LUT_SAMPLER]:t.lut.style,filterUniforms:{[wa.U_ALPHA]:{value:t.alpha,type:"f32"}}}}),this.id=t.id}destroy(t){try{const o=this.resources[wa.U_LUT];o&&"destroy"in o&&o.destroy()}catch(o){nn("LUTFilter").warn(null,"Error while destroying LUT filter, "+qr(o))}super.destroy(t)}}const xHe=(e,t)=>{const o=xS("webgl2"),r=`
3250#version 300 es
3251precision mediump float;
3252
3253in vec2 vTextureCoord;
3254out vec4 fragColor;
3255
3256uniform sampler2D uTexture;   
3257uniform sampler2D `+e+`;    
3258uniform float     `+t+`;    
3259
3260vec2 calcLookupPos(vec3 color, vec2 quad) {
3261    float x = (quad.x * 0.125) + 63.0/512.0 * color.r + 0.5/512.0;
3262    float y = (quad.y * 0.125) + 63.0/512.0 * color.g + 0.5/512.0;
3263
3264    return vec2(x, y);
3265}
3266
3267vec4 applyLUT(vec4 col) {
3268    float blue  = col.b * 63.0;
3269
3270    vec2 quad1;
3271    quad1.y = floor(floor(blue) / 8.0);
3272    quad1.x = floor(blue) - (quad1.y * 8.0);
3273
3274    vec2 quad2;
3275    quad2.y = floor(ceil(blue) / 8.0);
3276    quad2.x = ceil(blue)  - (quad2.y * 8.0);
3277
3278    vec4 col1 = texture(`+e+`, calcLookupPos(col.rgb, quad1));
3279    vec4 col2 = texture(`+e+`, calcLookupPos(col.rgb, quad2));
3280    vec4 lut  = mix(col1, col2, fract(blue));
3281    
3282    vec3 mixed = mix(col.rgb, lut.rgb, `+t+`);
3283
3284    return vec4(mixed, col.a);
3285}
3286
3287void main() {
3288    vec4 base = texture(uTexture, vTextureCoord);
3289    fragColor = applyLUT(base); 
3290}
3291    `;return{vertex:o,fragment:r}},cHe=(e,t,o)=>{const r=xS("webgpu"),n=`
3292struct FilterUniforms {
3293  `+o+`: f32,
3294};
3295
3296@group(0) @binding(1) var uTexture: texture_2d<f32>;
3297@group(0) @binding(2) var uSampler: sampler;
3298@group(1) @binding(0) var<uniform> filterUniforms : FilterUniforms;
3299@group(1) @binding(1) var `+e+`: texture_2d<f32>;
3300@group(1) @binding(2) var `+t+`: sampler;
3301
3302fn calcLookupPos(color: vec3<f32>, quad: vec2<f32>) -> vec2<f32> {
3303  let x = (quad.x * 0.125) + 63.0 / 512.0 * color.r + 0.5 / 512.0;
3304  let y = (quad.y * 0.125) + 63.0 / 512.0 * color.g + 0.5 / 512.0;
3305  return vec2<f32>(x, y);
3306}
3307
3308fn applyLUT(col: vec4<f32>) -> vec4<f32> {
3309  let blue = col.b * 63.0;
3310
3311  var quad1 = vec2<f32>(floor(blue) - floor(floor(blue) / 8.0) * 8.0, floor(floor(blue) / 8.0));
3312  var quad2 = vec2<f32>(ceil(blue) - floor(ceil(blue) / 8.0) * 8.0, floor(ceil(blue) / 8.0));
3313
3314  let col1 = textureSample(`+e+", "+t+`, calcLookupPos(col.rgb, quad1));
3315  let col2 = textureSample(`+e+", "+t+`, calcLookupPos(col.rgb, quad2));
3316  let lut = mix(col1, col2, fract(blue));
3317
3318  let mixed = mix(col.rgb, lut.rgb, filterUniforms.`+o+`);
3319
3320  return vec4<f32>(mixed, col.a);
3321}
3322
3323@fragment
3324fn main(
3325  @builtin(position) position: vec4<f32>,
3326  @location(0) uv : vec2<f32>
3327) -> @location(0) vec4<f32> {
3328  let base = textureSample(uTexture, uSampler, uv);
3329  return applyLUT(base);
3330}
3331`;return{vertex:r,fragment:n}},Jk={0:"NO_ERROR",1280:"INVALID_ENUM",1281:"INVALID_VALUE",1282:"INVALID_OPERATION",1285:"OUT_OF_MEMORY",1286:"INVALID_FRAMEBUFFER_OPERATION",37442:"CONTEXT_LOST_WEBGL"};class lHe{constructor(t,o){this._ctx=t,this._logger=o}_ctx;_logger;_cachedGLCapabilities=null;_cachedWebGLVendor=null;_cachedWebGLRenderer=null;_lastGLErrorBeforeLost=null;cacheGLInfo(){const t=this._ctx.getGL();if(t)try{this._cachedGLCapabilities={maxTextureSize:t.getParameter(t.MAX_TEXTURE_SIZE),maxRenderbufferSize:t.getParameter(t.MAX_RENDERBUFFER_SIZE),maxViewportDims:t.getParameter(t.MAX_VIEWPORT_DIMS),maxCombinedTextureImageUnits:t.getParameter(t.MAX_COMBINED_TEXTURE_IMAGE_UNITS)};const o=t.getExtension("WEBGL_debug_renderer_info");this._cachedWebGLVendor=o?t.getParameter(o.UNMASKED_VENDOR_WEBGL):t.getParameter(t.VENDOR),this._cachedWebGLRenderer=o?t.getParameter(o.UNMASKED_RENDERER_WEBGL):t.getParameter(t.RENDERER)}catch{}}registerContextLostListener(t){const o=t.gl,r=o.canvas,n=()=>{try{this._lastGLErrorBeforeLost=o.getError();const a=Jk[this._lastGLErrorBeforeLost]??"UNKNOWN("+this._lastGLErrorBeforeLost+")";this._logger.warn(null,"WebGL context lost! Last GL error: "+a+" (0x"+this._lastGLErrorBeforeLost.toString(16)+")")}catch{}};return r.addEventListener("webglcontextlost",n),()=>r.removeEventListener("webglcontextlost",n)}collect(){const t=this._ctx.getSprites(),o=[];for(const[a,i]of t){const s=i.getTextureInfo();s&&o.push({id:a,...s})}const r=this._cachedWebGLVendor||this._lastGLErrorBeforeLost!==null?{vendor:this._cachedWebGLVendor??void 0,renderer:this._cachedWebGLRenderer??void 0,lastGLError:this._lastGLErrorBeforeLost??void 0,lastGLErrorName:this._lastGLErrorBeforeLost!==null?Jk[this._lastGLErrorBeforeLost]??"UNKNOWN("+this._lastGLErrorBeforeLost+")":void 0}:void 0,n=this._ctx.getCanvasSize();return{canvasSize:{width:n.width,height:n.height},spritesCount:t.size,disposersCount:this._ctx.getDisposersCount(),glCapabilities:this._cachedGLCapabilities??void 0,webglInfo:r,textures:o}}}const kc="uAlphaMap",xf=kc+"Sampler",Zu="uAlphaMapMatrix",vs="uAlphaClamp";class IE extends hd{_hostSprite;_alphaTexture;_textureMatrix;_filterUniforms;constructor(t){const{hostSprite:o,alphaTexture:r}=t,n=new eJ(r),a=new sd({[Zu]:{value:new c1,type:"mat3x3<f32>"},[vs]:{value:n.uClampFrame,type:"vec4<f32>"}});super({glProgram:new cl({vertex:dHe(),fragment:uHe(),name:"AlphaMask_GL"}),gpuProgram:new xl({name:"AlphaMask_GPU",vertex:{source:qk(),entryPoint:"mainVertex"},fragment:{source:qk(),entryPoint:"mainFragment"}}),resources:{filterUniforms:a,[kc]:r.source,[xf]:r.source.style}}),this._hostSprite=o,this._alphaTexture=r,this._textureMatrix=n,this._filterUniforms=a}get alphaTexture(){return this._alphaTexture}set alphaTexture(t){this._alphaTexture=t,this._textureMatrix.texture=t,this.resources[kc]=t.source,this.resources[xf]=t.source.style}apply(...t){const[o,r,n,a]=t;this._textureMatrix.texture=this._alphaTexture;const i=this._filterUniforms.uniforms[Zu];o.calculateSpriteMatrix(i,this._hostSprite).prepend(this._textureMatrix.mapCoord),this._filterUniforms.uniforms[vs]=this._textureMatrix.uClampFrame,this.resources[kc]=this._alphaTexture.source,this.resources[xf]=this._alphaTexture.source.style,o.applyFilter(this,r,n,a)}destroy(t){try{this._alphaTexture.destroy(!0)}catch(o){nn("AlphaMaskFilter").warn(null,"Error while destroying alpha mask texture, "+qr(o))}super.destroy(t)}}const dHe=()=>`
3332#version 300 es
3333precision mediump float;
3334
3335layout(location = 0) in vec2 aPosition;
3336
3337out vec2 vTextureCoord;
3338out vec2 vAlphaCoord;
3339
3340uniform vec4 uInputSize;
3341uniform vec4 uOutputFrame;
3342uniform vec4 uOutputTexture;
3343uniform mat3 `+Zu+`;
3344
3345vec4 filterVertexPosition(void) {
3346    vec2 position = aPosition * uOutputFrame.zw + uOutputFrame.xy;
3347    position.x = position.x * (2.0 / uOutputTexture.x) - 1.0;
3348    position.y = position.y * (2.0*uOutputTexture.z / uOutputTexture.y) - uOutputTexture.z;
3349    return vec4(position, 0.0, 1.0);
3350}
3351
3352vec2 filterTextureCoord(void) {
3353    return aPosition * (uOutputFrame.zw * uInputSize.zw);
3354}
3355
3356void main(void) {
3357    gl_Position = filterVertexPosition();
3358    vTextureCoord = filterTextureCoord();
3359    vAlphaCoord = (`+Zu+` * vec3(vTextureCoord, 1.0)).xy;
3360}
3361`,uHe=()=>`
3362#version 300 es
3363precision mediump float;
3364
3365in vec2 vTextureCoord;
3366in vec2 vAlphaCoord;
3367out vec4 fragColor;
3368
3369uniform sampler2D uTexture;
3370uniform sampler2D `+kc+`;
3371uniform vec4 `+vs+`;
3372
3373void main() {
3374  vec4 color = texture(uTexture, vTextureCoord);
3375  float clip = step(3.5,
3376    step(`+vs+`.x, vAlphaCoord.x) +
3377    step(`+vs+`.y, vAlphaCoord.y) +
3378    step(vAlphaCoord.x, `+vs+`.z) +
3379    step(vAlphaCoord.y, `+vs+`.w));
3380  float alpha = texture(`+kc+`, vAlphaCoord).r * clip;
3381  fragColor = vec4(color.rgb * alpha, alpha);
3382}
3383`,qk=()=>`
3384struct GlobalFilterUniforms {
3385  uInputSize:vec4<f32>,
3386  uInputPixel:vec4<f32>,
3387  uInputClamp:vec4<f32>,
3388  uOutputFrame:vec4<f32>,
3389  uGlobalFrame:vec4<f32>,
3390  uOutputTexture:vec4<f32>,
3391};
3392
3393struct AlphaMaskUniforms {
3394  `+Zu+`:mat3x3<f32>,
3395  `+vs+`:vec4<f32>,
3396};
3397
3398@group(0) @binding(0) var<uniform> gfu: GlobalFilterUniforms;
3399@group(0) @binding(1) var uTexture: texture_2d<f32>;
3400@group(0) @binding(2) var uSampler: sampler;
3401
3402@group(1) @binding(0) var<uniform> filterUniforms: AlphaMaskUniforms;
3403@group(1) @binding(1) var `+kc+`: texture_2d<f32>;
3404@group(1) @binding(2) var `+xf+`: sampler;
3405
3406struct VSOutput {
3407    @builtin(position) position: vec4<f32>,
3408    @location(0) uv : vec2<f32>,
3409    @location(1) alphaUv : vec2<f32>,
3410};
3411
3412fn filterVertexPosition(aPosition:vec2<f32>) -> vec4<f32> {
3413    var position = aPosition * gfu.uOutputFrame.zw + gfu.uOutputFrame.xy;
3414    position.x = position.x * (2.0 / gfu.uOutputTexture.x) - 1.0;
3415    position.y = position.y * (2.0*gfu.uOutputTexture.z / gfu.uOutputTexture.y) - gfu.uOutputTexture.z;
3416    return vec4(position, 0.0, 1.0);
3417}
3418
3419fn filterTextureCoord(aPosition:vec2<f32>) -> vec2<f32> {
3420    return aPosition * (gfu.uOutputFrame.zw * gfu.uInputSize.zw);
3421}
3422
3423fn getAlphaCoord(aPosition:vec2<f32>) -> vec2<f32> {
3424    return (filterUniforms.`+Zu+` * vec3<f32>(filterTextureCoord(aPosition), 1.0)).xy;
3425}
3426
3427@vertex
3428fn mainVertex(
3429  @location(0) aPosition: vec2<f32>,
3430) -> VSOutput {
3431  return VSOutput(
3432    filterVertexPosition(aPosition),
3433    filterTextureCoord(aPosition),
3434    getAlphaCoord(aPosition),
3435  );
3436}
3437
3438@fragment
3439fn mainFragment(
3440  @builtin(position) position: vec4<f32>,
3441  @location(0) uv: vec2<f32>,
3442  @location(1) alphaUv: vec2<f32>,
3443) -> @location(0) vec4<f32> {
3444  let color = textureSample(uTexture, uSampler, uv);
3445  let clip = step(3.5,
3446    step(filterUniforms.`+vs+`.x, alphaUv.x) +
3447    step(filterUniforms.`+vs+`.y, alphaUv.y) +
3448    step(alphaUv.x, filterUniforms.`+vs+`.z) +
3449    step(alphaUv.y, filterUniforms.`+vs+`.w));
3450  let alpha = textureSample(`+kc+", "+xf+`, alphaUv).r * clip;
3451  return vec4<f32>(color.rgb * alpha, alpha);
3452}
3453`,pHe=cl.from({name:"ProjectiveMesh_GL",vertex:`
3454    #version 300 es
3455    precision highp float;
3456
3457    layout(location = 0) in vec2 aPosition;
3458    layout(location = 1) in vec2 aUV;
3459
3460    uniform mat3 uProjectionMatrix;
3461    uniform mat3 uWorldTransformMatrix;
3462    uniform vec4 uWorldColorAlpha;
3463    uniform mat3 uTransformMatrix;
3464    uniform vec4 uColor;
3465    uniform mat3 uTextureMatrix;
3466    uniform mat3 uHomography;
3467
3468    out vec2 vUV;
3469    out vec4 vColor;
3470
3471    void main(void) {
3472      vec3 projectivePosition = uHomography * vec3(aUV, 1.0);
3473      mat3 modelViewProjectionMatrix = uProjectionMatrix * uWorldTransformMatrix * uTransformMatrix;
3474      vec3 clipPosition = modelViewProjectionMatrix * projectivePosition;
3475
3476      gl_Position = vec4(clipPosition.xy, 0.0, clipPosition.z);
3477      vUV = (uTextureMatrix * vec3(aUV, 1.0)).xy;
3478      vColor = uColor * uWorldColorAlpha;
3479    }
3480  `,fragment:`
3481    #version 300 es
3482    precision highp float;
3483
3484    uniform sampler2D uTexture;
3485
3486    in vec2 vUV;
3487    in vec4 vColor;
3488
3489    out vec4 finalColor;
3490
3491    void main(void) {
3492      finalColor = texture(uTexture, vUV) * vColor;
3493    }
3494  `}),Qk=`
3495  struct GlobalUniforms {
3496    uProjectionMatrix: mat3x3<f32>,
3497    uWorldTransformMatrix: mat3x3<f32>,
3498    uWorldColorAlpha: vec4<f32>,
3499    uResolution: vec2<f32>,
3500  };
3501
3502  struct LocalUniforms {
3503    uTransformMatrix: mat3x3<f32>,
3504    uColor: vec4<f32>,
3505    uRound: f32,
3506  };
3507
3508  struct TextureUniforms {
3509    uTextureMatrix: mat3x3<f32>,
3510  };
3511
3512  struct ProjectiveUniforms {
3513    uHomography: mat3x3<f32>,
3514  };
3515
3516  @group(0) @binding(0) var<uniform> globalUniforms: GlobalUniforms;
3517  @group(1) @binding(0) var<uniform> localUniforms: LocalUniforms;
3518  @group(2) @binding(0) var uTexture: texture_2d<f32>;
3519  @group(2) @binding(1) var uSampler: sampler;
3520  @group(2) @binding(2) var<uniform> textureUniforms: TextureUniforms;
3521  @group(3) @binding(0) var<uniform> projectiveUniforms: ProjectiveUniforms;
3522
3523  struct VertexOutput {
3524    @builtin(position) position: vec4<f32>,
3525    @location(0) uv: vec2<f32>,
3526    @location(1) color: vec4<f32>,
3527  };
3528
3529  @vertex
3530  fn mainVertex(
3531    @location(0) aPosition: vec2<f32>,
3532    @location(1) aUV: vec2<f32>,
3533  ) -> VertexOutput {
3534    let projectivePosition = projectiveUniforms.uHomography * vec3<f32>(aUV, 1.0);
3535    let modelViewProjectionMatrix = globalUniforms.uProjectionMatrix
3536      * globalUniforms.uWorldTransformMatrix
3537      * localUniforms.uTransformMatrix;
3538    let clipPosition = modelViewProjectionMatrix * projectivePosition;
3539
3540    return VertexOutput(
3541      vec4<f32>(clipPosition.xy, aPosition.x * 0.0, clipPosition.z),
3542      (textureUniforms.uTextureMatrix * vec3<f32>(aUV, 1.0)).xy,
3543      localUniforms.uColor * globalUniforms.uWorldColorAlpha,
3544    );
3545  }
3546
3547  @fragment
3548  fn mainFragment(input: VertexOutput) -> @location(0) vec4<f32> {
3549    return textureSample(uTexture, uSampler, input.uv) * input.color;
3550  }
3551`,fHe=xl.from({name:"ProjectiveMesh_GPU",vertex:{source:Qk,entryPoint:"mainVertex"},fragment:{source:Qk,entryPoint:"mainFragment"}}),Zk=(e,t)=>new Float32Array([0,0,e,0,e,t,0,t]),gHe=new Float32Array([1,0,0,0,1,0,0,0,1]),_He=(e,t,o,r)=>{const[n,a]=e,[i,s]=t,[x,c]=o,[l,d]=r,u=i-x,p=l-x,f=n-i+x-l,E=s-c,T=d-c,O=a-s+c-d,S=u*T-p*E;if(Math.abs(S)<1e-7)return;const R=(f*T-p*O)/S,y=(u*O-f*E)/S,v=i-n+R*i,w=l-n+y*l,N=s-a+R*s,M=d-a+y*d;return new Float32Array([v,N,R,w,M,y,n,a,1])};class EHe extends tJ{_projectiveUniforms;_textureUniforms;_width;_height;constructor(t){const o=new oJ({positions:Zk(t.width,t.height),uvs:new Float32Array([0,0,1,0,1,1,0,1]),indices:new Uint32Array([0,1,2,0,2,3])}),r=new sd({uHomography:{value:gHe.slice(),type:"mat3x3<f32>"}}),n=new sd({uTextureMatrix:{value:t.textureMatrix.mapCoord,type:"mat3x3<f32>"}}),a=new rJ({glProgram:pHe,gpuProgram:fHe,resources:{uTexture:t.source,uSampler:t.source.style,textureUniforms:n,projectiveUniforms:r}});a.texture=t,super({geometry:o,shader:a,texture:t}),this._projectiveUniforms=r,this._textureUniforms=n,this._width=t.width,this._height=t.height,this.setCorners(0,0,t.width,0,t.width,t.height,0,t.height)}syncTexture(t){this.texture!==t&&(this.texture=t);const o=this.shader;if(!o||(o.resources.uTexture=t.source,o.resources.uSampler=t.source.style,this._textureUniforms.uniforms.uTextureMatrix=t.textureMatrix.mapCoord,this._textureUniforms.update(),this._width===t.width&&this._height===t.height))return;this._width=t.width,this._height=t.height,this.geometry.positions.set(Zk(t.width,t.height)),this.geometry.getBuffer("aPosition").update()}setCorners(t,o,r,n,a,i,s,x){const c=_He([t,o],[r,n],[a,i],[s,x]);if(!c){this.visible=!1;return}this.geometry.positions.set([t,o,r,n,a,i,s,x]),this.geometry.getBuffer("aPosition").update(),this.setHomography(c)}setHomography(t){let o=t.length!==9;for(let n=0;n<t.length;n+=1)if(!Number.isFinite(t[n])){o=!0;break}const r=t[0]*(t[4]*t[8]-t[7]*t[5])-t[3]*(t[1]*t[8]-t[7]*t[2])+t[6]*(t[1]*t[5]-t[4]*t[2]);if(o||Math.abs(r)<1e-7){this.visible=!1;return}this._projectiveUniforms.uniforms.uHomography.set(t),this._projectiveUniforms.update(),this.visible=!0}destroy(t){const o=this.shader,r=this.geometry;super.destroy(t),o?.destroy(),r.destroy(!0)}}const KY=8,$k=e=>py.from({resource:e.texture,...zY(e.effects?.Animation)?{autoGenerateMipmaps:!0,maxAnisotropy:KY}:{}});class LP{constructor(t,o){this.options=t,this._sprite=new lR(new mx({source:$k(o),rotate:CC(o.transform.intrinsicRotation)})),this._layout=new jp,this._layout.sortableChildren=!0,this._layout.addChild(this._sprite),this._root=new jp,this._root.sortableChildren=!1,this._root.addChild(this._layout),this.options.parent.addChild(this._root),this._effectNodeMap={lut:null,animation:null}}options;_logger=nn("PixiSprite");_root;_anim;_layout;_sprite;_perspectiveMesh;_effectNodeMap;_createContext(){return{sprite:this._sprite,layout:this._layout,root:this._root,canvasSize:this.options.canvasSize,handleDispose:this.options.handleDispose,assetFetcher:this.options.assetFetcher,ensureAnimationLayer:()=>this._ensureAnimationLayer(),releaseAnimationLayer:()=>this._releaseAnimationLayer(),getAnimationLayer:()=>this._anim??this._root,ensurePerspectiveMesh:()=>this._ensurePerspectiveMesh(),releasePerspectiveMesh:()=>this._releasePerspectiveMesh()}}static async create(t,o){const r=new LP(o,t);return await r.update(t),r}async update(t){this._root.zIndex=t.zIndex,this._anim&&(this._anim.zIndex=t.zIndex),this._layout.zIndex=t.zIndex,await this._updateTexture(t),this._updateAlphaFilter(t),this._applyTransform(t.transform),await this._applyEffects(t)}async _applyEffects(t){const o=this._createContext();t.effects?.Filter?(this._effectNodeMap.lut??=new sHe,await this._effectNodeMap.lut.apply(t,o)):this._effectNodeMap.lut&&(this._effectNodeMap.lut.destroy(),this._effectNodeMap.lut=null),t.effects?.Animation?(this._effectNodeMap.animation??=new X3e,this._effectNodeMap.animation.apply(t,o)):this._effectNodeMap.animation&&(this._effectNodeMap.animation.destroy(),this._effectNodeMap.animation=null)}updateAnimationProgress(t){const o=this._effectNodeMap.animation;if(!o)return;const r=this._createContext();o.updateProgress(t,r)}getTextureInfo(){try{const t=this._sprite.texture;if(!t||t.destroyed)return null;const o=t.source;if(!o)return null;const r=o.resource;let n="unknown";return r instanceof ImageBitmap?n="ImageBitmap":typeof VideoFrame<"u"&&r instanceof VideoFrame?n="VideoFrame":r instanceof OffscreenCanvas&&(n="OffscreenCanvas"),{width:o.width,height:o.height,resourceType:n}}catch{return null}}destroy(){for(const t of Object.values(this._effectNodeMap))t&&t.destroy();this._releasePerspectiveMesh(),this._releaseAnimationLayer(),this._root.removeFromParent(),this.options.handleDispose(()=>{try{A3e(this._sprite,!0)}catch(t){this._logger.warn(null,Ae(void 0,t,"Error while destroying sprite filters"))}try{this._sprite.destroy({children:!0,texture:!0,textureSource:!0})}catch(t){this._logger.warn(null,Ae(void 0,t,"Error while destroying sprite"))}try{this._layout.destroy({children:!0})}catch{}try{this._root.destroy({children:!0})}catch{}})}async _updateTexture(t){const o=this._sprite.texture?.source,r=zY(t.effects?.Animation);if(!this._sprite.texture||this._sprite.texture.destroyed||o?.resource!==t.texture||o.autoGenerateMipmaps!==r||o.maxAnisotropy!==(r?KY:1)){const n=this._sprite.texture?.frame,a=new mx({source:$k(t),rotate:CC(t.transform.intrinsicRotation),frame:n}),i=this._sprite.texture;this._sprite.texture=a,i&&this.options.handleDispose(()=>{try{i.destroy(!0)}catch(s){this._logger.warn(null,Ae(void 0,s,"Error while destroying previous texture"))}})}}_updateAlphaFilter(t){if(!t.alphaTexture){Ru(this._sprite,IE)&&Au(this._sprite,IE);return}const o=py.from(t.alphaTexture),r=CC(t.transform.intrinsicRotation),n=eF(t.transform.crop,r??0),a=new mx({source:o,rotate:r,frame:new dR((n?.x??0)*o.width,(n?.y??0)*o.height,(n?.width??1)*
3551o.width,(n?.height??1)*o.height)}),i=Ru(this._sprite,IE);if(i){const s=i.alphaTexture;i.alphaTexture=a,s&&s!==a&&this.options.handleDispose(()=>{try{s.destroy(!0)}catch(x){this._logger.warn(null,Ae(void 0,x,"Error while destroying previous alpha texture"))}})}else bP(this._sprite,new IE({hostSprite:this._sprite,alphaTexture:a}))}_applyTransform(t){if(!this._sprite.texture)return;this._applyCrop(t.crop);const{x:o,y:r,anchor:n,flips:a,rotation:i,size:s,opacity:x}=t,c=this._sprite.texture.frame?.width??this._sprite.texture.width,l=this._sprite.texture.frame?.height??this._sprite.texture.height,d=s.width/c,u=s.height/l,p=new c1().scale(d*(a?.h?-1:1),u*(a?.v?-1:1)).translate(o+n.x*c,r+n.y*l).rotate(i??0).translate(a?.h?-c:0,a?.v?-l:0);this._sprite.setFromMatrix(p),this._sprite.anchor.set(n.x,n.y),this._sprite.position.set(o+n.x*c*d,r+n.y*l*u),this._syncLayoutFromSprite(n.x,n.y),this._sprite.alpha=x??1}_applyCrop(t){if(!this._sprite.texture)return;const o=this._sprite.texture.source.width,r=this._sprite.texture.source.height,n=eF(t,this._sprite.texture.rotate),a=(n?.x??0)*o,i=(n?.y??0)*r,s=(n?.width??1)*o,x=(n?.height??1)*r;if(a===this._sprite.texture.frame.x&&i===this._sprite.texture.frame.y&&s===this._sprite.texture.frame.width&&x===this._sprite.texture.frame.height)return;const c=new mx({source:this._sprite.texture.source,rotate:this._sprite.texture.rotate,frame:new dR(a,i,s,x)}),l=this._sprite.texture;this._sprite.texture=c,this.options.handleDispose(()=>{try{l.destroy()}catch(d){this._logger.warn(null,Ae(void 0,d,"Error while destroying cropped texture"))}})}_syncLayoutFromSprite(t,o){this._sprite.texture&&(this._layout.position.copyFrom(this._sprite.position),this._layout.scale.copyFrom(this._sprite.scale),this._layout.skew.copyFrom(this._sprite.skew),this._layout.rotation=this._sprite.rotation,this._layout.pivot.set(t*this._sprite.texture.width,o*this._sprite.texture.height),this._sprite.position.set(0,0),this._sprite.scale.set(1,1),this._sprite.skew.set(0,0),this._sprite.rotation=0,this._sprite.anchor.set(0,0))}_ensureAnimationLayer(){if(this._anim)return this._anim;const t=new jp;return t.sortableChildren=!1,t.zIndex=this._root.zIndex,this._root.removeChild(this._layout),t.addChild(this._layout),this._root.addChild(t),this._anim=t,t}_releaseAnimationLayer(){if(this._anim){try{this._anim.removeChild(this._layout)}catch{}this._root.addChild(this._layout),this._root.removeChild(this._anim);try{this._anim.destroy({children:!0})}catch{}this._anim=void 0}}_ensurePerspectiveMesh(){const t=this._sprite.texture;if(!t||t.destroyed)throw Ae(je.LOGIC_ERR,void 0,"Cannot create PerspectiveMesh without valid texture");if(this._perspectiveMesh)return this._perspectiveMesh.syncTexture(t),this._perspectiveMesh;const o=new EHe(t);return o.zIndex=this._sprite.zIndex,this._layout.addChild(o),this._sprite.visible=!1,this._perspectiveMesh=o,o}_releasePerspectiveMesh(){const t=this._perspectiveMesh;if(t){this._perspectiveMesh=void 0,this._sprite.visible=!0;try{t.removeFromParent()}catch{}this.options.handleDispose(()=>{try{t.destroy({children:!0})}catch(o){this._logger.warn(null,Ae(void 0,o,"Error while destroying PerspectiveMesh"))}})}}}const CC=e=>{if(e===void 0)return;const t=Math.round(e*180/Math.PI),o=(t%360+360)%360;if(o===90)return fu.S;if(o===180)return fu.W;if(o===270)return fu.N},eF=(e,t)=>!e||t===0?e:t===fu.S?{x:1-e.y-e.height,y:e.x,width:e.height,height:e.width}:t===fu.N?{x:e.y,y:1-e.x-e.width,width:e.height,height:e.width}:t===fu.W?{x:1-e.x-e.width,y:1-e.y-e.height,width:e.width,height:e.height}:e;class mHe{constructor(t,o,r){this._canvasSize=t,this._forceWebGPU=o,this._abortSignal=r,this._canvas=new OffscreenCanvas(this._canvasSize.width,this._canvasSize.height),this._assetFetcher=new wY(this._abortSignal),this._diagnostics=new lHe({getGL:()=>this._renderer instanceof G_?this._renderer.gl:null,getSprites:()=>this._sprites,getDisposersCount:()=>this._deferredDisposers.length,getCanvasSize:()=>this._canvasSize},this._logger)}_canvasSize;_forceWebGPU;_abortSignal;_logger=nn("PixiScene");_renderer;_canvas;_stage=new jp;_sprites=new Map;_deferredDisposers=[];_assetFetcher;_blendFilter=null;_diagnostics;_unregisterContextLostListener=null;
3551async init(){try{if(this._logger.verbose(null,"Initializing renderer"),this._renderer=await nJ({canvas:this._canvas,width:this._canvas.width,height:this._canvas.height,preference:this._forceWebGPU?"webgpu":"webgl",webgpu:{powerPreference:"high-performance"},webgl:{powerPreference:"high-performance",multiView:!0}}),this._stage.sortableChildren=!0,this._stage.filterArea=this._renderer.screen,this._renderer instanceof G_){const t=this._renderer.gl,o=t?.getParameter(t.VERSION);this._logger.info(null,"Using WebGL renderer, version: "+o),this._diagnostics.cacheGLInfo(),this._unregisterContextLostListener=this._diagnostics.registerContextLostListener(this._renderer)}else this._logger.info(null,"Using WebGPU renderer")}catch(t){throw Ae(je.RENDERER_INIT_HWACCEL_UNAVAILABLE,t)}}collectDiagnostics(){return this._diagnostics.collect()}get hasContext(){return this._renderer instanceof G_?!this._renderer.gl.isContextLost():!0}get errorMessage(){return this._renderer instanceof G_?this._renderer.gl.getError().toString():null}destroy(t){this._destroySpritesSafe(),this._flushDeferredDisposals(),this._destroyFiltersSafe(),this._destroyStageSafe(),this._unregisterContextLostListener?.(),this._unregisterContextLostListener=null,this._destroyRendererSafe(t),this._sprites.clear()}async draw(t){if(!this._abortSignal.aborted){this._updateBlendProgress(t);for(const o of this._sprites.values())o.updateAnimationProgress(t);this._renderer.render(this._stage)}return this._flushDeferredDisposals(),this._canvas.transferToImageBitmap()}setBlendSource(t){if(this._abortSignal.aborted){t.close();return}const o=this._blendFilter;if(!o){t.close();return}const r=mx.from(t);o.source=r.source,this._deferDispose(()=>{t.close();try{r.destroy()}catch(n){this._logger.warn(null,Ae(void 0,n,"Error while destroying temporary blend texture wrapper"))}})}async upsert(t,o=this._stage){if(!this._abortSignal.aborted)for(const[r,n]of t){const a=this._sprites.get(r);a?await a.update(n):await this._addSprite(r,n,o)}}remove(t){if(!this._abortSignal.aborted)for(const o of t)this._removeSprite(o)}upsertGlobalEffects(t){if(!this._abortSignal.aborted)for(const o of t)this._upsertGlobalEffect(o)}removeGlobalEffects(t){if(!this._abortSignal.aborted)for(const o of t)this._removeGlobalEffect(o)}async _addSprite(t,o,r){const n=await LP.create(o,{parent:r,assetFetcher:this._assetFetcher,handleDispose:this._deferDispose.bind(this),canvasSize:this._canvasSize});this._sprites.set(t,n)}_removeSprite(t){const o=this._sprites.get(t);o&&(o.destroy(),this._sprites.delete(t))}_updateBlendProgress(t){this._blendFilter?.updateTime(t)}_ensureBlendFilter(t){t.type==="Blend"&&this._blendFilter?.id!==t.effectId&&(this._disposeBlendFilter(),this._stage.filterArea=this._renderer.screen,this._blendFilter=new ya({type:t.blendType,id:t.effectId,timelineStart:t.timelineStart,timelineEnd:t.timelineEnd}),this._stage.filters=this._blendFilter)}_disposeBlendFilter(t=!1){this._blendFilter&&(this._blendFilter.destroy(t),this._blendFilter=null,this._stage.filters=[],this._stage.filterArea=void 0)}_upsertGlobalEffect(t){switch(t.type){case"Background":{this._renderer.background.color=t.color;break}case"Blend":this._ensureBlendFilter(t)}}_removeGlobalEffect(t){switch(t){case"Background":{this._renderer.background.color="0x000000";break}case"Blend":{this._disposeBlendFilter();break}}}_destroySpritesSafe(){for(const t of this._sprites.values())t.destroy()}_destroyFiltersSafe(){try{this._disposeBlendFilter(!0)}catch(t){this._logger.warn(null,Ae(void 0,t,"Error while destroying filters"))}finally{this._blendFilter=null,this._stage.filterArea=void 0}}_destroyStageSafe(){try{this._stage.destroy({context:!0,style:!0,children:!0,texture:!0,textureSource:!0})}catch(t){this._logger.warn(null,Ae(void 0,t,"Error while destroying stage"))}}_destroyRendererSafe(t){try{this._renderer?.destroy({releaseGlobalResources:t})}catch(o){this._logger.warn(null,Ae(void 0,o,"Error while destroying pixi.js renderer"))}}_deferDispose(t){this._deferredDisposers.push(t)}_flushDeferredDisposals(){const t=this._deferredDisposers.splice(0);for(const o of t)try{o()}catch(r){this._logger.warn(null,Ae(void 0,r,"Error while deferred dispose"))}}}
3551class hHe{_effectMap={Background:{params:null,dirty:!1},Blend:{params:null,dirty:!1}};_renderers=new Map;_cachedElements=new Map;async destroy(){await Promise.all([...this._renderers.keys()].map(async t=>this.removeRenderer(t))),Object.values(this._effectMap).forEach(({params:t})=>{t&&this.removeEffect(t?.type)})}setRenderer(t,o){this._renderers.set(t,o)}removeRenderer(t){this._renderers.delete(t),this._cachedElements.delete(t)}upsertEffect(t){this._effectMap[t.type]?.params?.effectId!==t.effectId&&(this._effectMap[t.type].params=t,this._effectMap[t.type].dirty=!0)}removeEffect(t){this._effectMap[t].params=null,this._effectMap[t].dirty=!1}async render(t){const o=await Promise.all(Array.from(this._renderers.entries()).map(([a,i])=>i.build(t).then(s=>{if(s){const x=this._buildElementMetas(i,s);x.length>0&&this._cachedElements.set(a,x)}return[a,s]}))),r=this._getDirtyEffects();this._resetEffectsDirty();const n=Array.from(this._cachedElements.values()).flat();return[o,r,n]}_getDirtyEffects(){return Object.fromEntries(Object.entries(this._effectMap).filter(([,t])=>t.params).map(([t,o])=>[t,o.dirty?o.params:null]))}_resetEffectsDirty(){for(const[,t]of Object.entries(this._effectMap))t.dirty=!1}_buildElementMetas(t,o){if(o.length===0)return[];const r=t.params,n={modelId:r.modelId,renderType:r.type,opacity:r.transform?.opacity??1,zIndex:r.position.zIndex},a=r.transform?.rotation??0;return t.getOverlayEntries(o).map(i=>({...n,paramId:i.paramId,rect:i.rect,rotation:i.rotation??a,captionRole:i.captionRole}))}}class XY{constructor(t){this.opts=t}opts;_imageBitmap=null;_releaseHandle=null;async init(){const{blob:t,release:o}=await this.opts.assetFetcher.get(this.opts.source);return this._releaseHandle=o,this._imageBitmap=await Lc(t),this}async render(){if(!this._imageBitmap)throw Ae(je.LOGIC_ERR,"Image bitmap is not initialized");return{id:this.opts.id,source:this._imageBitmap,size:this.opts.imageSize,position:this.opts.position,crop:this.opts.crop,transform:this.opts.transform,effects:this.opts.effects}}destroy(){this._imageBitmap=null,this._releaseHandle?.(),this._releaseHandle=null}shouldReRender(){return!1}}class MP{future=null;current=null;_isResolved=!1;promise(t=!1){return t&&this.reset(),this.current?this.current:this.current=new Promise((o,r)=>{this.future={resolve:o,reject:r}})}resolve(t,o=!0,r=!1){if(!this.future){if(r)return;throw new Error("No promise")}this._isResolved||(this.future.resolve(t),this._isResolved=!0,o&&this.reset())}reject(t,o=!0,r=!1){if(!this.future){if(r)return;throw new Error("No promise")}this._isResolved||(this.future.reject(t),this._isResolved=!0,o&&this.reset())}reset(){return this.current=null,this.future=null,this._isResolved=!1,this}}const tF=e=>"sourceIn"in e,IHe=e=>e.type!=="Audio",jCt=e=>e.type==="Audio",THe=e=>{let t=1/0,o=1/0,r=-1/0,n=-1/0;for(const a of e){const i=a.transform;i.x<t&&(t=i.x),i.y<o&&(o=i.y),i.x+i.size.width>r&&(r=i.x+i.size.width),i.y+i.size.height>n&&(n=i.y+i.size.height)}return{x:t,y:o,width:r-t,height:n-o}};class B2{constructor(t,o,r=new MP,n="idle",a=null,i=new Set){this.params=t,this.context=o,this._initFuture=r,this._state=n,this._lastRenderTime=a,this._currentBitmaps=i,this.logger=nn(t.type+"#"+t.id.slice(0,8))}params;context;_initFuture;_state;_lastRenderTime;_currentBitmaps;logger;get id(){return this.params.id}
3551async init(){if(this._state==="initializing")return this.logger.debug(null,"Already initializing"),this._initFuture.promise();if(this._state==="initialized")return this.logger.debug(null,"Already initialized"),this;this._state="initializing";try{this.logger.debug(null,"Initializing"),this._initFuture.promise().catch(()=>{});const t=await this._initImpl();return this._initFuture.resolve(t),this._state="initialized",this.logger.debug(null,"Initialized"),t}catch(t){throw this._initFuture.reject(t),this._state="idle",Ae(void 0,t,void 0,{errorAt:this.params.timelineStart,erroredFrom:this.params.type})}finally{this._lastRenderTime=null}}async destroy(){this.logger.debug(null,"Destroying"),this._state="idle",this._lastRenderTime=null,this._initFuture.reset(),await this._destroyImpl(),this._releaseCurrentBitmaps(),this.logger.debug(null,"Destroyed")}getOverlayRect(){return null}getOverlayEntries(t){const o=this.getOverlayRect()??THe(t);return[{paramId:this.params.id,rect:o,rotation:this.params.transform?.rotation}]}async build(t){const o=t.sub(this.params.timelineStart).mul(tF(this.params)?this.params.playbackRate:1),r=tF(this.params)?o.add(this.params.sourceIn):o;try{if(this._state!=="initialized"&&await this.init(),this._lastRenderTime&&!this._shouldReRenderImpl(r,this._lastRenderTime))return null;const n=await this._buildImpl(r);if(this._lastRenderTime=r,!n)return null;const a=Array.isArray(n)?n:[n];return this._updateBitmapOwnership(a),a.map(SHe)}catch(n){throw Ae(void 0,n,void 0,{errorAt:this.params.timelineStart,erroredFrom:this.params.type})}}async update(t){if(t===this.params)return!1;try{this.logger.debug(null,"Updating");const o=await this._updateImpl(t);return this._state=o?"idle":this._state,this._lastRenderTime=null,this.logger.debug(null,"Updated"),o}catch(o){throw Ae(void 0,o,void 0,{errorAt:this.params.timelineStart,erroredFrom:this.params.type})}}_releaseCurrentBitmaps(){for(const t of this._currentBitmaps)$s(t);this._currentBitmaps.clear()}_updateBitmapOwnership(t){const o=new Set;for(const r of t)o.add(r.source),r.alphaSource&&o.add(r.alphaSource);for(const r of this._currentBitmaps)!o.has(r)&&$s(r);this._currentBitmaps=o}}const SHe=e=>({id:e.id,transform:OHe(e),zIndex:e.position.zIndex,texture:e.source,alphaTexture:e.alphaSource,effects:e.effects}),OHe=e=>{const{size:t,position:o,transform:r,crop:n}=e,{width:a,height:i}=t,s=o.adjustment?o.adjustment.x*a:0,x=o.adjustment?o.adjustment.y*i:0,c=r?.transformOrigin?.x??.5,l=r?.transformOrigin?.y??.5;return{x:o.x+s,y:o.y+x,rotation:r?.rotation?r.rotation*(Math.PI/180):void 0,intrinsicRotation:r?.intrinsicRotation?r.intrinsicRotation*(Math.PI/180):void 0,anchor:{x:c,y:l},crop:n,size:t,flips:r?.flipH||r?.flipV?{h:r?.flipH??!1,v:r?.flipV??!1}:void 0,opacity:r?.opacity}};class CHe{_resolve=null;wait(t){if(this._resolve!==null)throw new Error("Signal: concurrent wait() is not supported");return new Promise(o=>{if(this._resolve=o,t){const r=()=>this.fire();t.addEventListener("abort",r,{once:!0})}})}fire(){const t=this._resolve;this._resolve=null,t?.()}get pending(){return this._resolve!==null}}class RHe{constructor(t,o){this._low=t,this._high=o}_low;_high;_buffer=[];_readySignal=new CHe;push(t,o){this._buffer.push({frame:t,mediaTime:o}),this._buffer.length>=this._low&&this._readySignal.fire()}shift(){return this._buffer.shift()}peek(){return this._buffer[0]}peekAt(t){return this._buffer[t]}get length(){return this._buffer.length}get isAtHighWatermark(){return this._buffer.length>=this._high}get isBelowLowWatermark(){return this._buffer.length<this._low}clear(){for(const t of this._buffer)t.frame.close();this._buffer.length=0,this._readySignal.fire()}waitUntilReady(t){return this._buffer.length>=this._low||t.aborted?Promise.resolve():this._readySignal.wait(t)}}const TE=1e3,oF=4,AHe=8,rF=1e-6,yHe=1,vHe=4,wHe=.08,NHe=.08;class PHe{constructor(t,o,r,n,a){this._mediaSource=t,this._frameRate=o,this._mediaId=r,this._hwAccel=n,this._getPlaybackRate=a,this._logger=nn("LiveVideoRenderer#"+r.slice(0,6))}_mediaSource;_frameRate;_mediaId;_hwAccel;_getPlaybackRate;_logger;_state="uninitialized";_video=null;_objectUrl=null;_generation=0;_extractQueue=new RHe(oF,AHe);_extractState={extracting:!1,watermarkPaused:!1,lastExtractedMediaSec:-1/0,lastFrameDurationSec:null};_lastServedFrameIdx=null;_extractCallback={handle:null,token:0};_prefillController=null;get state(){return this._state}async init(t){try{return await this._load(this._mediaSource,t)&&(this._state="initialized",await this._waitForPrefill()),this}catch(o){throw this._state="error",this._teardown(),o}}async destroy(){this._generation++;try{this._teardown()}finally{this._state="destroyed"}}
3551async reset(t,o,r,n){this._logger.verbose(null,"Resetting LiveVideoRenderer to new source"),this._generation++,this._mediaSource=t,this._mediaId=o,this._hwAccel=r;try{this._teardown(),await this._load(t,n)&&(this._state="initialized",await this._waitForPrefill()),this._logger.verbose(null,"LiveVideoRenderer reset completed")}catch(a){throw this._state="error",this._logger.error(null,"LiveVideoRenderer reset failed: "+qr(a)),this._teardown(),a}}async render(t,o){const r=this._video;if(!r)throw Ae(je.VIDEO_RENDER_ERR,new Error("render() called before init()"),this._mediaId);const n=this._generation;this._applyPlaybackRate(r);try{const a=this._resolveTargetSec(t,r,o),i=Rc(X.fromSec(a),this._frameRate),s=await this._consumeExtractCache(r,a);if(s)return this._isStale(n,r)?(s.close(),null):(!this._extractState.watermarkPaused&&(r.paused&&this._safePlay(r),this._reviveExtract(n,r)),{frame:s,rotation:0});if(r.paused&&this._safePlay(r),this._shouldSeek(r,a))try{await this._seek(r,a)}catch(c){if(this._isStale(n,r))return null;throw c}else await this._awaitPresentedFrameNear(r,a);if(this._isStale(n,r))return null;try{const c=await Lc(r);return this._isStale(n,r)?(c.close(),null):(this._reviveExtract(n,r),this._lastServedFrameIdx=i,{frame:c,rotation:0})}catch(c){if(this._isStale(n,r))return null;throw c}}catch(a){throw Ae(je.VIDEO_RENDER_ERR,a,this._mediaId+" error occurred while rendering video frame")}}shouldReRender(t,o){return o?Rc(t,this._frameRate)!==Rc(o,this._frameRate):!0}async _load(t,o){const r=this._generation,{video:n,objectUrl:a}=await this._loadVideoElement(t);if(r!==this._generation||this._state==="destroyed"||this._state==="error")return this._disposeElement(n,a),!1;if(this._video=n,this._objectUrl=a,o!==void 0&&o>0){try{await this._seek(n,o)}catch{}if(this._isStale(r,n))return!1}return this._startExtract(n),!0}_loadVideoElement(t){const r=["loadstart","progress","loadedmetadata","durationchange","canplay","suspend"],{src:n,objectUrl:a}=this._resolveUrl(t),i=document.createElement("video");return i.crossOrigin="anonymous",i.muted=!0,new Promise((s,x)=>{let c;const l=()=>{clearTimeout(c),c=setTimeout(()=>{p(this._classifyLoadError(null,t),new Error("video load timeout"),this._mediaId+" timed out loading live video element (hwAccel="+this._hwAccel+")")},3e3)},d=()=>{i.removeEventListener("loadeddata",u),i.removeEventListener("error",f),r.forEach(T=>i.removeEventListener(T,E)),clearTimeout(c)},u=()=>{d(),s({video:i,objectUrl:a})},p=(T,O,S)=>{d(),this._disposeElement(i,a),x(Ae(T,O,S))},f=T=>{const O=T.target,S=O?.error?.code??null;p(this._classifyLoadError(S,t),T,this._mediaId+" failed to load live video element (code="+(S??"unknown")+", hwAccel="+this._hwAccel+")")},E=()=>l();l(),i.addEventListener("loadeddata",u),i.addEventListener("error",f),r.forEach(T=>i.addEventListener(T,E)),i.src=n})}_classifyLoadError(t,o){if(o.kind==="blob")return je.VIDEO_FORMAT_ERR;
3551if(t===null)return je.FILE_READ_ERROR;switch(t){case 3:case 4:return je.VIDEO_FORMAT_ERR;default:return je.FILE_READ_ERROR}}_resolveUrl(t){if(t.kind==="blob"){const o=URL.createObjectURL(t.blob);return{src:o,objectUrl:o}}return{src:t.uri,objectUrl:null}}_resolveTargetSec(t,o,r){const n=o.duration,a=t.as.us("round");if(!Number.isFinite(n)||n<=0)return t.as.sec();const i=X.fromSec(n).as.us("round");if(r==="loop"&&a>i)return X.fromUS(a%i).as.sec();const s=Math.max(0,i-Math.round(1e6/this._frameRate)),x=Math.min(Math.max(a,0),s);return X.fromUS(x).as.sec()}_shouldSeek(t,o){const r=o-t.currentTime,n=yHe/this._frameRate;if(r<-n)return!0;const a=Math.min(vHe/this._frameRate,wHe);return r>a}_applyPlaybackRate(t){const o=this._getPlaybackRate?.()??1;t.playbackRate=Number.isFinite(o)?Math.min(Math.max(o,.0625),16):o>0?16:.0625}_cancelExtractCallback(t){this._extractCallback.token++;const o=this._extractCallback.handle;this._extractCallback.handle=null,o!==null&&typeof t.cancelVideoFrameCallback=="function"&&t.cancelVideoFrameCallback(o)}_safePlay(t){this._applyPlaybackRate(t),Promise.resolve(t.play()).catch(o=>{this._logger.warn(null,"video.play() rejected: "+qr(o))})}_seek(t,o){return new Promise((r,n)=>{const a=()=>{t.removeEventListener("seeked",i),t.removeEventListener("error",s),clearTimeout(x)},i=()=>{a(),r()},s=c=>{a(),n(Ae(je.VIDEO_DECODE_ERR,c))},x=setTimeout(()=>{a(),r()},TE);t.addEventListener("seeked",i),t.addEventListener("error",s),this._cancelExtractCallback(t),this._extractQueue.clear(),this._extractState.extracting=!1,this._extractState.watermarkPaused=!1,this._lastServedFrameIdx=null,t.currentTime=o})}async _awaitPresentedFrameNear(t,o){if(typeof t.requestVideoFrameCallback!="function")return;
3551const r=performance.now()+TE,n=1/this._frameRate;do await this._awaitNextPresentedFrame(t,r);while(o-t.currentTime>n&&performance.now()<r)}_awaitNextPresentedFrame(t,o=performance.now()+TE){return typeof t.requestVideoFrameCallback!="function"?Promise.resolve():new Promise(r=>{let n=!1,a=null;const i=()=>{n||(n=!0,clearTimeout(x),a!==null&&t.cancelVideoFrameCallback(a),r())},s=Math.max(0,o-performance.now()),x=setTimeout(i,s);a=t.requestVideoFrameCallback(()=>i())})}_isStale(t,o){return t!==this._generation||this._video!==o||this._state==="destroyed"||this._state==="error"}_teardown(){this._prefillController?.abort(),this._prefillController=null;const t=this._video;t?this._cancelExtractCallback(t):(this._extractCallback.token++,this._extractCallback.handle=null),this._extractQueue.clear(),this._extractState.extracting=!1,this._extractState.watermarkPaused=!1,this._extractState.lastExtractedMediaSec=-1/0,this._extractState.lastFrameDurationSec=null,this._lastServedFrameIdx=null;const o=this._objectUrl;this._video=null,this._objectUrl=null,t&&this._disposeElement(t,o)}_disposeElement(t,o){o&&URL.revokeObjectURL(o);try{t.pause(),t.removeAttribute("src"),t.load(),t.remove()}catch(r){this._logger.warn(null,"Failed to tear down video element: "+qr(r))}}_waitForPrefill(){const t=this._video;if(!t||typeof t.requestVideoFrameCallback!="function"||this._extractQueue.length>=oF||!this._extractState.extracting)return Promise.resolve();this._prefillController?.abort();const o=new AbortController;this._prefillController=o;const r=setTimeout(()=>o.abort(),TE);return this._extractQueue.waitUntilReady(o.signal).finally(()=>{clearTimeout(r),this._prefillController===o&&(this._prefillController=null)})}_startExtract(t){this._extractState.extracting||(this._extractState.extracting=!0,this._extractState.watermarkPaused=!1,this._extractState.lastExtractedMediaSec=t.currentTime,t.paused&&this._safePlay(t),this._scheduleExtractCallback(t))}_scheduleExtractCallback(t){if(typeof t.requestVideoFrameCallback!="function"){this._extractState.extracting=!1,this._extractCallback.token++,this._extractCallback.handle=null;return}const o=this._generation,r=++this._extractCallback.token;let n=null;n=t.requestVideoFrameCallback((a,i)=>{this._extractCallback.handle===n&&(this._extractCallback.handle=null),this._onExtractedFrame(o,r,t,i)}),this._extractCallback.handle=n}async _onExtractedFrame(t,o,r,n){if(o!==this._extractCallback.token||!this._extractState.extracting)return;if(this._isStale(t,r)){this._extractState.extracting=!1;return}const a=n.mediaTime;if(a<=this._extractState.lastExtractedMediaSec){this._cancelExtractCallback(r),this._extractState.extracting=!1,r.pause(),this._prefillController?.abort();return}let i;try{i=await Lc(r)}catch(x){this._cancelExtractCallback(r),this._extractState.extracting=!1,!this._isStale(t,r)&&(this._logger.warn(null,"extract capture failed: "+qr(x)),this._extractState.extracting=!0,this._scheduleExtractCallback(r));return}if(this._isStale(t,r)){i.close(),this._cancelExtractCallback(r),this._extractState.extracting=!1;return}const s=this._extractState.lastExtractedMediaSec;if(this._extractState.lastExtractedMediaSec=a,Number.isFinite(s)&&a>s&&(this._extractState.lastFrameDurationSec=a-s),this._extractQueue.push(i,a),this._extractQueue.isAtHighWatermark){this._cancelExtractCallback(r),this._extractState.extracting=!1,this._extractState.watermarkPaused=!0,r.pause();return}this._scheduleExtractCallback(r)}_reviveExtract(t,o){this._isStale(t,o)||this._extractState.extracting&&!o.paused||(this._extractState.extracting=!1,this._extractState.watermarkPaused=!1,this._startExtract(o))}_cacheMatchToleranceSec(){return Math.min(Math.max(1/this._frameRate,this._extractState.lastFrameDurationSec??0),NHe)}async _consumeExtractCache(t,o){let r=this._extractQueue.peek();const n=Rc(X.fromSec(o),this._frameRate);if(n===this._lastServedFrameIdx)return null;for(;this._extractQueue.length>1;){const c=this._extractQueue.peekAt(1);if(!c||c.mediaTime-o>rF)break;this._extractQueue.shift()?.frame.close(),r=this._extractQueue.peek()}const a=r!==void 0?r.mediaTime-o:null,i=a!==null&&Math.abs(a)<=this._cacheMatchToleranceSec();if(r===void 0)return this._extractState.watermarkPaused=!1,null;if(!i)return r.mediaTime<o&&(this._extractQueue.clear(),this._extractState.watermarkPaused=!1),null;this._lastServedFrameIdx=n;const s=r.mediaTime-o>rF,x=s?{frame:await Lc(r.frame),mediaTime:r.mediaTime}:this._extractQueue.shift();return this._extractState.watermarkPaused&&this._extractQueue.isBelowLowWatermark&&(this._extractState.watermarkPaused=!1,this._safePlay(t),this._startExtract(t)),x.frame}}const bHe=()=>{if(!WebAssembly||typeof WebAssembly!="object"||typeof WebAssembly.instantiate!="function")return!1;const e=[0,97,115,109,1,0,0,0];try{const t=new WebAssembly.Module(new Uint8Array(e));if(t instanceof WebAssembly.Module)return new WebAssembly.Instance(t)instanceof WebAssembly.Instance}catch{return!1}return!1};let SE=null,OE=null,uc=null;const nF=CJ,aF=async()=>
3551{if(SE&&OE)return{mjsUrl:SE,wasmUrl:OE};if(uc)return uc.promise();uc=new MP,uc.promise();try{const e="/try/",t=new URL(e+"libav/libav-vrew-"+nF+".mjs",import.meta.url).href,o=new URL(e+"libav/libav-vrew-"+nF+".wasm",import.meta.url).href,[r,n]=await Promise.all([$f(t),$f(o)]);SE=URL.createObjectURL(r),OE=URL.createObjectURL(n);const a={mjsUrl:SE,wasmUrl:OE};return uc.resolve(a),a}catch(e){throw uc&&uc.reject(e),e}finally{uc=null}};class JY{constructor(t,o,r,n,a){this._mediaSource=t,this._decoder=o,this._frameRate=r,this._mediaId=n,this._hwAccel=a,this._logger=nn("WebCodecsVideoRenderer#"+n.slice(0,6))}_mediaSource;_decoder;_frameRate;_mediaId;_hwAccel;_logger;_state="uninitialized";_releaseHandle=null;get state(){return this._state}async init(){this._logger.verbose(null,"initializing libAV");const{mjsUrl:t,wasmUrl:o}=await aF();this._logger.verbose(null,"libAV initialized");try{let r=!1;const n=this._decoder.init(this._mediaSource,this._hwAccel,vf(this._logger),t,o,{forceLibAV:Qa("forceLibAV"),verbose:Qa("isVerbose"),debug:Qa("isDev")}).then(()=>{this._logger.info(null,"Decoder initialization finished"),this._state="initialized",r&&this._logger.warn(null,"Decoder initialization resolved after timeout")}).catch(i=>{if(r)this._logger.warn(null,"Decoder initialization failed after timeout: "+qr(i));else throw i}),a=new Promise((i,s)=>{setTimeout(()=>{r=!0,s(Ae(je.DECODER_WORKER_SPAWN_ERR,"Decoder initialization timeout"))},12e4)});return await Promise.race([n,a]),this}
3551catch(r){throw Ae(navigator.onLine?je.FILE_READ_ERROR:je.NETWORK_FAILED_ERR,r,"isWebAssemblySupported: "+bHe()+`
3552         navigator.onLine: `+navigator.onLine+`
3553        `)}}async destroy(){try{await this._decoder.clear()}finally{this._state="destroyed",this._releaseHandle?.(),this._releaseHandle=null}}async reset(t,o,r){this._logger.verbose(null,"Resetting WebCodecsRenderer to new source"),this._mediaId=o,this._mediaSource=t,this._hwAccel=r;try{const{mjsUrl:n,wasmUrl:a}=await aF();await this._decoder.clear(),await this._decoder.init(t,this._hwAccel,vf(this._logger),n,a,{forceLibAV:Qa("forceLibAV"),verbose:Qa("isVerbose"),debug:Qa("isDev")}),this._logger.verbose(null,"WebCodecsRenderer reset completed")}catch(n){throw this._logger.error(null,"WebCodecsRenderer reset failed: "+qr(n)),n}}async render(t,o){try{return await this._decoder.decode(t.as.us(),o)}catch(r){throw Ae(je.VIDEO_DECODE_ERR,r,this._mediaId+" error occurred while rendering video frame")}}shouldReRender(t,o){return o?Rc(t,this._frameRate)!==Rc(o,this._frameRate):!0}}class LHe extends B2{_renderer;_releaseWorker=null;constructor(t,o){super(t,o),this._renderer=this._getRenderer(this.context.useHWAccel)}async _updateImpl(t){if(this.params.sourceId!==t.sourceId){this.logger.debug(null,"Media source changed, resetting renderer, id="+this.params.id);try{await this._renderer.reset(t.source,this.params.id,this.context.useHWAccel,t.sourceIn.as.sec())}catch(o){const r=Ae(void 0,o,"Reset failed, falling back to destroy/reinit, id="+this.params.id);this.logger.warn(null,r.message),await this.destroy()}this.params=t}else this.logger.debug(null,"Source unchanged, updating params only, id="+this.params.id),this.params=t;return!1}async _initImpl(){return await this._renderer.init(this.params.sourceIn.as.sec()),this}async _destroyImpl(){await this._renderer.destroy(),this._releaseWorker?.(),this._releaseWorker=null}async _buildImpl(t){const o=await this._renderer.render(this._applyLoop(t),this.params.loop?"loop":"clamp");return o?qY(this.id,o,this.params):null}_shouldReRenderImpl(t,o){return this._renderer.shouldReRender(t,o)}_applyLoop(t){if(!this.params.loop)return t;const{in:o,out:r}=this.params.loop,n=r.sub(o);return n.gt(X.zero())&&t.gte(r)?o.add(t.sub(o).mod(n)):t}_getRenderer(t){if(this.context.mode==="live")return new PHe(this.params.source,this.context.frameRate,this.params.id,t,()=>(this.context.getPreviewRate?.()??1)*this.params.playbackRate);const{worker:o,release:r}=this.context.videoDecoderPool.acquire();return this._releaseWorker=r,new JY(this.params.source,o,this.context.frameRate,this.params.id,t)}}const qY=(e,t,o)=>({id:e,source:t.frame,alphaSource:t.alphaFrame,size:o.size,position:o.position,effects:o.effects,crop:o.crop,transform:t.rotation===0?o.transform:{...o.transform,intrinsicRotation:t.rotation}});class MHe extends B2{_speakingVideoRenderer=null;_silentVideoRenderer=null;_silentImageRenderer=null;_releaseWorkers=[];_paramsDirty=!1;async _updateImpl(t){this._paramsDirty=!0;const o=this.params.silentAsset,r=t.silentAsset,n=o.type===r.type&&o.sourceId===r.sourceId,a=this.params.speakingAsset,i=t.speakingAsset,s=!a&&!i||a&&i&&a.sourceId===i.sourceId;return n&&s?(this.params=t,!1):(this.params=t,await this.destroy(),!0)}async _initImpl(){this._releaseWorkers=[],this.params.speakingAsset?this._speakingVideoRenderer=this._createVideoRenderer(this.params.speakingAsset):this._speakingVideoRenderer=null;const t=this.params.silentAsset;return t.type==="Video"?(this._silentVideoRenderer=this._createVideoRenderer(t),this._silentImageRenderer=null):(this._silentImageRenderer=new XY({id:this.id,imageSize:t.size,position:t.position,assetFetcher:this.context.assetFetcher,source:t.source,crop:t.crop,transform:t.transform}),this._silentVideoRenderer=null),await Promise.all([this._speakingVideoRenderer?.init(),this._silentVideoRenderer?.init(),this._silentImageRenderer?.init()]),this}async _destroyImpl(){const t=[this._speakingVideoRenderer,this._silentVideoRenderer,this._silentImageRenderer];await Promise.allSettled(t.map(o=>o?.destroy())),this._speakingVideoRenderer=null,this._silentVideoRenderer=null,this._silentImageRenderer=null;for(const o of this._releaseWorkers)o();this._releaseWorkers=[],this._paramsDirty=!0}async _buildImpl(t){const o=this._shouldRenderSpeakingVideo()?await this._renderSpeakingVideo(t):await this._renderSilentAsset(t);return this._paramsDirty=!1,o}async _renderSilentImage(t){if(!this._silentImageRenderer)throw Ae(je.LOGIC_ERR,"silent image renderer is not initialized");const o=await this._silentImageRenderer.render(t);return{...o,source:await Lc(o.source)}}async _renderVideoAsset(t,o,r){if(!t)throw Ae(je.LOGIC_ERR,"video renderer is not initialized");const n=await t.render(r,o.loop?"loop":"clamp");return n?qY(this.id+":video",n,o):null}async _renderSpeakingVideo(t){if(!this.params.speakingAsset)throw Ae(je.LOGIC_ERR,"speaking asset is not defined");return this._renderVideoAsset(this._speakingVideoRenderer,this.params.speakingAsset,t)}async _renderSilentAsset(t){return this.params.silentAsset.type==="Video"?this._renderVideoAsset(this._silentVideoRenderer,this.params.silentAsset,t):this._renderSilentImage(t)}_shouldReRenderImpl(t,o){return this._paramsDirty?!0:this._shouldRenderSpeakingVideo()?this._speakingVideoRenderer?.shouldReRender(t,o)??!0:this.params.silentAsset.type==="Video"?this._silentVideoRenderer?.shouldReRender(t,o)??!0:this._silentImageRenderer?this._silentImageRenderer.shouldReRender(t,o):!0}_shouldRenderSpeakingVideo(){return!!(this._speakingVideoRenderer&&this.params.shouldAnimate&&this.params.speakingAsset)}_createVideoRenderer(t){const{worker:o,release:r}=this.context.videoDecoderPool.acquire();return this._releaseWorkers.push(r),new JY(t.source,o,this.context.frameRate,t.id,this.context.useHWAccel)}}const DHe=(e,t,o)=>({x:e.x/t,y:e.y/o,width:e.width/t,height:e.height/o}),kHe=(e,t)=>t?{x:e.x+t.x*e.width,y:e.y+t.y*e.height,width:e.width*t.width,height:e.height*t.height}:e;class FHe{constructor(t){this._opts=t}_opts;_imageBitmap=null;_releaseHandle=null;destroy(){this._imageBitmap=null,this._releaseHandle?.(),this._releaseHandle=null}
3553async init(){const{blob:t,release:o}=await this._opts.assetFetcher.get(this._opts.source);return this._releaseHandle=o,this._imageBitmap=await Lc(t),this}async render(t){if(!this._imageBitmap)throw Ae(je.LOGIC_ERR,"image bitmap is not initialized");const o=this._getKenburnsRect(t),r=DHe(o,this._imageBitmap.width,this._imageBitmap.height),n=kHe(r,this._opts.crop);return{id:this._opts.id,source:this._imageBitmap,size:this._opts.imageSize,crop:n,position:this._opts.position,transform:this._opts.transform,effects:this._opts.effects}}_getKenburnsRect(t){if(!this._imageBitmap)throw Ae(je.LOGIC_ERR,"image bitmap is not initialized");const o=this._opts.kenburnsInfo,{width:r,height:n}=this._imageBitmap,{scale:a,centerX:i,centerY:s}=UHe(this._opts.timelineDuration,t,o),x=r*a,c=n*a;return{x:r*i-x/2,y:n*s-c/2,width:x,height:c}}shouldReRender(){return!0}}const UHe=(e,t,o)=>{const{from:r,to:n}=o;if(e.eq(X.zero()))return{scale:.5,centerX:.5,centerY:.5};const a=t.as.sec()/e.as.sec(),i=r.scale+(n.scale-r.scale)*a,s=r.centerX+(n.centerX-r.centerX)*a,x=r.centerY+(n.centerY-r.centerY)*a;return{scale:i,centerX:s,centerY:x}};class VHe extends B2{_renderer;constructor(t,o){super(t,o),this._renderer=this._makeRenderer(t)}_makeRenderer(t){const o={id:this.id,source:t.source,frameRate:this.context.frameRate,canvasSize:this.context.canvasSize,imageSize:t.size,position:t.position,transform:t.transform,timelineDuration:t.timelineDuration,crop:t.crop,assetFetcher:this.context.assetFetcher,effects:t.effects};return t.effects?.Kenburns?new FHe({...o,kenburnsInfo:t.effects?.Kenburns}):new XY(o)}async _updateImpl(t){return this._renderer?.destroy(),this.params=t,this._renderer=this._makeRenderer(t),!0}async _initImpl(){return await this._renderer.init(),this}async _destroyImpl(){this._renderer.destroy()}_shouldReRenderImpl(t,o){return this._renderer.shouldReRender(t,o)}async _buildImpl(t){if(!this._renderer)throw Ae(je.LOGIC_ERR,"image renderer is not initialized");return this._renderer.render(t)}}class GHe{constructor(t){this._opts=t}_opts;_bitmap=null;async init(){const t=new yY(this._opts.shapeSize.width,this._opts.shapeSize.height),{blob:o,release:r}=await this._opts.fetcher.get(this._opts.source);try{const n=await o.text(),a=await NY("data:image/svg+xml;charset=utf-8,"+encodeURIComponent(n));return t.drawImagePixel(a,0,0,this._opts.shapeSize.width,this._opts.shapeSize.height),this._bitmap=await t.toImageBitmap(),t.clear(),this}finally{r()}}destroy(){this._bitmap=null}async render(){if(this._bitmap===null)throw Ae(je.LOGIC_ERR,"Shape bitmap is not initialized");return{id:this._opts.id,source:this._bitmap,size:this._opts.shapeSize,effects:this._opts.effects,position:this._opts.position,crop:this._opts.crop,transform:this._opts.transform}}shouldReRender(){return!1}}class WHe extends B2{_renderer;constructor(t,o){super(t,o),this._renderer=this._makeRenderer(t)}_makeRenderer(t){const o={id:this.id,source:t.source,timelineDuration:t.timelineDuration,fetcher:this.context.assetFetcher,frameRate:this.context.frameRate,canvasSize:this.context.canvasSize,shapeSize:t.size,position:t.position,transform:t.transform,effects:t.effects,crop:t.crop};return new GHe(o)}async _updateImpl(t){return this._renderer.destroy(),this.params=t,!0}async _initImpl(){return this._renderer=this._makeRenderer(this.params),await this._renderer.init(),this}async _destroyImpl(){this._renderer.destroy()}async _buildImpl(t){return this._renderer.render(t)}_shouldReRenderImpl(t,o){return this._renderer.shouldReRender(t,o)}}const HHe=e=>{if(!Y3e(e))return`
3554    * {
3555      animation: none !important;
3556    }
3557  `;const t=nl(e).bakeNeutralizeFill;return t!==void 0?`
3558    * {
3559      animation: none !important;
3560      background-image: none !important;
3561      color: `+t+` !important;
3562      -webkit-text-fill-color: `+t+` !important;
3563    }
3564  `:`
3565    * {
3566      animation: none !important;
3567      filter: none !important;
3568      -webkit-filter: none !important;
3569      text-shadow: none !important;
3570    }
3571  `},jHe=e=>{const t=e.trim();if(!t)return;if(t.toLowerCase()==="transparent")return[0,0,0,0];if(t.startsWith("#")){const a=t.slice(1),i=a.length===3||a.length===4?[...a].map(x=>x+x).join(""):a;if(i.length!==6&&i.length!==8)return;const s=[parseInt(i.slice(0,2),16)/255,parseInt(i.slice(2,4),16)/255,parseInt(i.slice(4,6),16)/255,i.length===8?parseInt(i.slice(6,8),16)/255:1];return s.some(Number.isNaN)?void 0:s}const o=t.replace(/^rgba?\(/i,"").replace(/\)$/,""),r=o.split(/[,/\s]+/).filter(
3571Boolean);if(r.length<3||r.length>4)return;const n=r.map(a=>/^[+-]?(\d+\.?\d*|\.\d+)$/.test(a)?Number(a):void 0);if(!n.some(a=>a===void 0))return[n[0]/255,n[1]/255,n[2]/255,n[3]??1]},zHe=(e,t,o)=>{if(!Number.isFinite(t)||t<=0||!Number.isFinite(o)||o<=0)return;const r=e.querySelector(".textarea")??e,n=parseFloat(getComputedStyle(r).fontSize);if(!(!Number.isFinite(n)||n<=0))return n*o},LA="data-anim-layer",YHe=(e,t)=>{const o=[];for(const r of t){const n=e.querySelector(r.selector);if(!n)return!1;o.push([n,r.layerId])}for(const[r,n]of o)r.setAttribute(LA,n);return!0},Kd=e=>Number.isFinite(e)&&e>0,iF=(e,t,o)=>{const r=new Map;if(!Kd(o))return r;const n=e.getBoundingClientRect();if(!Kd(n.width)||!Kd(n.height))return r;for(const a of t){const i=e.querySelector(a.selector);if(!i)continue;const s=i.getBoundingClientRect(),x=parseFloat(getComputedStyle(i).fontSize);!Kd(s.width)||!Kd(s.height)||!Kd(x)||r.set(a.layerId,{contentRect:{x:(s.left-n.left)/o,y:(s.top-n.top)/o,width:s.width/o,height:s.height/o},boxSize:{width:n.width/o,height:n.height/o},fontSizePx:x})}return r},BHe=(e,t)=>{const o=e.querySelectorAll("["+LA+"]");for(const r of o)r.getAttribute(LA)!==t&&r.style.setProperty("visibility","hidden","important")},KHe=e=>{const t=e.effects?.Animation;return[...e.layers].sort((r,n)=>r.binding.order-n.binding.order).map(({binding:r,bitmap:n,metrics:a})=>{const i=r.variant,s=t&&i?{...t,variant:i,animationDuration:nl(i).animationDuration.as.us("round"),effectId:t.effectId+":"+r.layerId,layerMetrics:a,clipToBox:r.clip,textRevealStripAtlas:void 0}:void 0;return{id:e.id+":"+r.layerId,source:n,size:e.size,position:{...e.position,zIndex:e.position.zIndex+r.order*.01},transform:e.transform,crop:e.crop,effects:{...e.effects,Animation:s}}})};class MA{_bitmaps=[];_layerBakes=null;_actualTextboxSize=null;_adjustedTextboxSize=null;_baseElement=null;_padding={horizontal:0,vertical:0};opts;constructor(t,o,r,n){this.opts={id:t.id,textboxInfo:{base:o,deltas:t.deltas,attributes:t.attributes,webFontCSS:t.fonts,scale:t.scale},loop:t.loop,textboxSize:t.size,position:t.position,transform:t.transform,assetDuration:t.duration,timelineDuration:t.timelineDuration,frameRate:r,canvasSize:n,effects:t.effects,crop:t.crop,lang:t.lang}}get actualTextboxSize(){if(!this._actualTextboxSize)throw Ae(je.LOGIC_ERR,"actualTextboxSize accessed before init()");return this._actualTextboxSize}async init(){this._baseElement=r3e(this.opts.textboxInfo.base,this.opts.textboxInfo.deltas,this.opts.textboxInfo.attributes,this.opts.textboxSize.width,this.opts.textboxInfo.scale),this._baseElement.lang=this.opts.lang,this.opts.effects?.Animation&&(this.opts.effects.Animation.elementZoom=this.opts.textboxInfo.scale);const t=this.opts.effects?.Animation?.variant;WWe(t)&&(this._neutralizeBakeAnimation(t),this._extractGraphicFxColors(t)),this._measureAndAdjustForOverflow(),rl(t)&&this._injectSingleTextureMetrics(t);const o=wP(t)?HWe(t):void 0;return o?await this._initMultiLayer(o):this._isTypewriterEffect()?await this._initTypewriter():await this._initStandard(),this}async _initMultiLayer(t){if(!this._baseElement)throw Ae(je.LOGIC_ERR,"Base element is not initialized");if(t.layers.length===0){await this._initStandard();return}if(!YHe(this._baseElement,t.layers)){await this._initStandard();return}const o=Up();o.appendChild(this._baseElement);const r=iF(this._baseElement,t.layers,this.opts.textboxInfo.scale);o.removeChild(this._baseElement),document.body.removeChild(o);const n=new JE(this._adjustedTextboxSize??this.actualTextboxSize,this.opts.lang),a=this.opts.textboxInfo.webFontCSS,i=[];try{const s=[...t.layers].sort((x,c)=>x.order-c.order);for(const x of s){const c=this._baseElement.cloneNode(!0);BHe(c,x.layerId);const l=await n.rasterize(c,{globalCSS:a});i.push({binding:x,bitmap:l,metrics:r.get(x.layerId)})}this._layerBakes=i}finally{n.destroy()}}_neutralizeBakeAnimation(t){if(!this._baseElement)throw Ae(je.LOGIC_ERR,"Base element is not initialized");const o=document.createElement("style");o.textContent=HHe(t),this._baseElement.appendChild(o)}_extractGraphicFxColors(t){const o=rl(t)?nl(t).graphicColorRoles:void 0;if(!o||!this._baseElement||!this.opts.effects?.Animation)return;const r=Up();r.appendChild(this._baseElement);try{const n=this._baseElement.querySelector(".textarea")??this._baseElement,a={};for(const[i,s]of Object.entries(o)){const x=s.startsWith("--")?getComputedStyle(n).getPropertyValue(s).trim():s,c=jHe(x);c&&(a[i]=c)}Object.keys(a).length>0&&(this.opts.effects.Animation.graphicFxColors=a)}finally{r.removeChild(this._baseElement),document.body.removeChild(r)}}_injectSingleTextureMetrics(t){if(!this._baseElement||!this.opts.effects?.Animation)return;const o=Up();o.appendChild(this._baseElement);try{const r=window.devicePixelRatio||1,n=zHe(this._baseElement,this.opts.textboxInfo.scale,r);n!==void 0&&(this.opts.effects.Animation.bakedFontSizePx=n);const a=nl(t);if(a.contentSelector){const i=a.webAssetId,s=iF(this._baseElement,[{layerId:i,selector:a.contentSelector,order:0}],this.opts.textboxInfo.scale).get(i);s&&(this.opts.effects.Animation.layerMetrics=s)}}finally{o.removeChild(this._baseElement),document.body.removeChild(o)}}_isTypewriterEffect(){const t=this.opts.effects?.Animation;if(!t)return!1;const o=t.variant;return!(!(o==="typing"||o==="typing_up"||o==="typing_down")||t.animationDuration===0)}async _initTypewriter(){const t=this.opts.effects.Animation;if(!this._baseElement)throw Ae(je.LOGIC_ERR,"Base element is not initialized");if(t.variant!==Qn.TYPING&&t.variant!==Qn.TYPING_UP&&t.variant!==Qn.TYPING_DOWN)throw Ae(je.LOGIC_ERR,"Animation is not a typewriter effect: "+t.variant);const o=this._baseElement.cloneNode(!0),r=Object.keys(this.opts.textboxInfo.deltas),{background:n}=Gk(this._baseElement.cloneNode(!0),r),{text:a}=Gk(o,r),i=new JE(this._adjustedTextboxSize??this.actualTextboxSize,this.opts.lang);try{const s=this.opts.textboxInfo.webFontCSS,x=await i.rasterize(n,{globalCSS:s}),c=n3e(a,t,X.zero(),this.opts.timelineDuration,"tb-id-"+Date.now(),"tb-class-"+Date.now(),this.opts.textboxInfo.deltas),{layout:l,sheetBitmaps:d}=await I3e(c,this._adjustedTextboxSize??this.actualTextboxSize,{globalCSS:s,maxSheetHeight:4096,scale:this.opts.textboxInfo.scale,textTargetIds:r,lang:this.opts.lang});d.length>0?(t.textRevealStripAtlas={layout:l,sheetBitmaps:d},this._bitmaps.push(x,x)):this._bitmaps.push(x)}finally{i.destroy()}}async _initStandard(){if(!this._baseElement)throw Ae(je.LOGIC_ERR,"Base element is not initialized");const t=new JE(this._adjustedTextboxSize??this.actualTextboxSize,this.opts.lang),o=this.opts.textboxInfo.webFontCSS;try{const r=await t.rasterize(this._baseElement,{globalCSS:o});this._bitmaps.push(r)}finally{t.destroy()}}
3571destroy(){this._bitmaps.length=0,this._layerBakes=null,this._baseElement=null,this._actualTextboxSize=null,this._padding.horizontal=0,this._padding.vertical=0}async render(){if(this._layerBakes){const s=this._adjustedTextboxSize??this.actualTextboxSize;return KHe({id:this.opts.id,layers:this._layerBakes,size:s,position:this._adjustPosition(s),transform:this._adjustTransformOrigin(),crop:this.opts.crop,effects:this.opts.effects})}if(this._bitmaps.length===0)throw Ae(je.LOGIC_ERR,"Bitmap is not initialized");const t=this._adjustedTextboxSize??this.actualTextboxSize,o=this._adjustPosition(t),r=this._adjustTransformOrigin();if(this._bitmaps.length===1)return{id:this.opts.id,source:this._bitmaps[0],size:t,position:o,transform:r,crop:this.opts.crop,effects:this.opts.effects};const n=this._bitmaps[0],a=this._bitmaps[1];return[{id:this.opts.id+":bg",source:n,size:t,position:o,transform:r,crop:this.opts.crop,effects:this.opts.effects?.Animation?{...this.opts.effects,Animation:void 0}:this.opts.effects},{id:this.opts.id+":text",source:a,size:t,position:o,transform:r,crop:this.opts.crop,effects:this.opts.effects}]}shouldReRender(){return!1}_adjustTransformOrigin(){const t=this.opts.transform,o=t?.transformOrigin?.x??.5,r=t?.transformOrigin?.y??.5,n=o*this.actualTextboxSize.width,a=r*this.actualTextboxSize.height,i=(this._padding.horizontal+n)/(this._adjustedTextboxSize??this.actualTextboxSize).width,s=(this._padding.vertical+a)/(this._adjustedTextboxSize??this.actualTextboxSize).height;return{...t,transformOrigin:{x:i,y:s}}}_adjustPosition(t){const o=this.opts.position.adjustment,r=o?{x:o.x*this.actualTextboxSize.width/t.width,y:o.y*this.actualTextboxSize.height/t.height}:void 0;return{...this.opts.position,x:this.opts.position.x-this._padding.horizontal,y:this.opts.position.y-this._padding.vertical,adjustment:r}}_measureAndAdjustForOverflow(){if(!this._baseElement)throw Ae(je.LOGIC_ERR,"Base element is not initialized");const t=this._baseElement.querySelector("["+LY+"]");if(!t){const p=Vk(this._baseElement);this._adjustedTextboxSize=p,this._actualTextboxSize=p;return}const o=Up();o.appendChild(this._baseElement);const r=Vk(this._baseElement),n=XHe(this._baseElement,this.opts.textboxInfo.scale),a=JHe(this._baseElement,this.opts.textboxInfo.scale);o.removeChild(this._baseElement),document.body.removeChild(o);const i=this.opts.textboxInfo.scale,s=4096,x=l3e(this.opts.textboxInfo.deltas,i),c=Math.max(0,Math.floor((s-r.width)/2)),l=Math.max(0,Math.floor((s-r.height)/2)),d=Math.min(x+n,c),u=Math.min(x+a,l);this._padding.horizontal=d,this._padding.vertical=u,t.style.padding=u+"px "+d+"px",this._actualTextboxSize={width:r.width,height:r.height},this._adjustedTextboxSize={width:r.width+d*2,height:r.height+u*2}}}const XHe=(e,t)=>{const o=t*(e.scrollWidth-e.clientWidth);return Math.max(0,o)},JHe=(e,t)=>{const o=t*(e.scrollHeight-e.clientHeight);return Math.max(0,o)};class qHe extends B2{_originalRenderer=null;_originalHtml=null;_translatedRenderer=null;_translatedHtml=null;get _isDual(){return!!this.params.original&&!!this.params.translated}getOverlayRect(){return!this._originalRenderer&&!this._translatedRenderer?null:this._isDual&&this._originalRenderer&&this._translatedRenderer?this._getDualOverlayRect():this._getActiveOverlayRect()}getOverlayEntries(t){const o=this._getIndividualOverlayEntries();return o.length>0?o:super.getOverlayEntries(t)}_getIndividualOverlayEntries(){const t=[],o=this.params.id;if(this._originalRenderer&&this.params.original){const r=this._isDual?this._getOriginalYOffset():0,n=this._getRendererOverlayRect(this._originalRenderer,this.params.original.position,r);n&&t.push({paramId:"orig-"+o,rect:n,rotation:this.params.original.transform?.rotation??0,captionRole:"original"})}if(this._translatedRenderer&&this.params.translated){const r=this._isDual?this._getTranslatedYOffset():0,n=this._getRendererOverlayRect(this._translatedRenderer,this.params.translated.position,r);n&&t.push({paramId:"trans-"+o,rect:n,rotation:this.params.translated.transform?.rotation??0,captionRole:"translated"})}return t}_getRendererOverlayRect(t,o,r){const n=t.actualTextboxSize,a=o.adjustment?o.adjustment.x*n.width:0,i=o.adju
3571stment?o.adjustment.y*n.height:0;return{x:o.x+a,y:o.y+i+r,width:n.width,height:n.height}}_getActiveOverlayRect(){return this._originalRenderer&&this.params.original?this._getRendererOverlayRect(this._originalRenderer,this.params.original.position,0):this._translatedRenderer&&this.params.translated?this._getRendererOverlayRect(this._translatedRenderer,this.params.translated.position,0):null}_getDualOverlayRect(){if(!this._originalRenderer||!this._translatedRenderer)return null;const t=this._originalRenderer.actualTextboxSize,o=this._translatedRenderer.actualTextboxSize,r=this.params.original.position,n=this.params.translated.position,a=this._getOriginalYOffset(),i=this._getTranslatedYOffset(),s=r.adjustment?r.adjustment.x*t.width:0,x=r.adjustment?r.adjustment.y*t.height:0,c=n.adjustment?n.adjustment.x*o.width:0,l=n.adjustment?n.adjustment.y*o.height:0,d=r.x+s,u=r.y+x+a,p=n.x+c,f=n.y+l+i,E=Math.min(d,p),T=Math.min(u,f),O=Math.max(d+t.width,p+o.width),S=Math.max(u+t.height,f+o.height);return{x:E,y:T,width:O-E,height:S-T}}async _updateImpl(t){try{this._originalRenderer?.destroy(),this._translatedRenderer?.destroy()}finally{this._originalRenderer=null,this._translatedRenderer=null}return this.params.original&&t.original&&this.params.original.sourceId!==t.original.sourceId&&(this._originalHtml=null),t.original||(this._originalHtml=null),this.params.translated&&t.translated&&this.params.translated.sourceId!==t.translated.sourceId&&(this._translatedHtml=null),t.translated||(this._translatedHtml=null),this.params=t,!0}async _initImpl(){return this.params.original&&(this._originalRenderer=new MA(this.params.original,await this._getHTML("original"),this.context.frameRate,this.context.canvasSize)),this.params.translated&&(this._translatedRenderer=new MA(this.params.translated,await this._getHTML("translated"),this.context.frameRate,this.context.canvasSize)),await Promise.all([this._originalRenderer?.init(),this._translatedRenderer?.init()]),this}async _getHTML(t){if(t==="original"&&this._originalHtml)return this._originalHtml;if(t==="translated"&&this._translatedHtml)return this._translatedHtml;const o=t==="original"?this.params.original:this.params.translated;if(!o)throw Ae(je.LOGIC_ERR,"caption renderer: "+t+" params not available");const{blob:r,release:n}=await this.context.assetFetcher.get(o.source);try{const a=await r.text();return t==="original"?this._originalHtml=a:this._translatedHtml=a,a}finally{n()}}async _destroyImpl(){try{this._originalRenderer?.destroy()}finally{this._originalRenderer=null}try{this._translatedRenderer?.destroy()}finally{this._translatedRenderer=null}this._originalHtml=null,this._translatedHtml=null}async _buildImpl(t){if(!this._originalRenderer&&!this._translatedRenderer)throw Ae(je.LOGIC_ERR,"caption renderer is not initialized");return this._isDual&&this._originalRenderer&&this._translatedRenderer?this._buildDualImpl(t):this._buildSingleImpl(t)}async _buildSingleImpl(t){const o=this._originalRenderer??this._translatedRenderer;if(!o)throw Ae(je.LOGIC_ERR,"caption renderer is not initialized");const r=await o.render(t);return Array.isArray(r)?r:[r]}async _buildDualImpl(t){const[o,r]=await Promise.all([this._originalRenderer.render(t),this._translatedRenderer.render(t)]),n=Array.isArray(o)?o:[o],a=Array.isArray(r)?r:[r],i=this._getOriginalYOffset(),s=this._getTranslatedYOffset(),x=this.params.position.zIndex,c=n.map((d,u)=>this._adjustResult(d,i,x+1e-4*u)),l=a.map((d,u)=>this._adjustResult(d,s,x+.001+1e-4*u));return[...c,...l]}_adjustResult(t,o,r){return{...t,position:{x:t.position.x,y:t.position.y+o,zIndex:r,adjustment:t.position.adjustment}}}_getOriginalYOffset(){if(!this._translatedRenderer)throw Ae(je.LOGIC_ERR,"caption renderer is not initialized");const t=this._translatedRenderer.actualTextboxSize.height,o=this._getCaptionGap();switch(this.params.yAlign){case"top":case"custom":return 0;case"middle":return-(t/2+o/2);case"bottom":return-(t+o);default:return 0}}_getTranslatedYOffset(){if(!this._originalRenderer)throw Ae(je.LOGIC_ERR,"caption renderer is not initialized");const t=this._originalRenderer.actualTextboxSize.height,o=this._getCaptionGap();
3571switch(this.params.yAlign){case"custom":return 0;case"top":return t+o;case"middle":return t/2+o/2;case"bottom":return 0;default:return t+o}}_getCaptionGap(){return .01*this.context.canvasSize.height}_shouldReRenderImpl(t,o){if(!this._originalRenderer&&!this._translatedRenderer)throw Ae(je.LOGIC_ERR,"caption renderer is not initialized");return(this._originalRenderer?.shouldReRender(t,o)??!1)||(this._translatedRenderer?.shouldReRender(t,o)??!1)}}class QHe extends B2{_logger=nn("renderer.textbox.ts");_renderer=null;_html=null;getOverlayRect(){if(!this._renderer)return null;const t=this._renderer.actualTextboxSize,o=this.params.position,r=o.adjustment?o.adjustment.x*t.width:0,n=o.adjustment?o.adjustment.y*t.height:0;return{x:o.x+r,y:o.y+n,width:t.width,height:t.height}}async _updateImpl(t){return this._renderer?.destroy(),this._renderer=null,this.params.sourceId!==t.sourceId&&(this._html=null),this.params=t,!0}async _initImpl(){return this._renderer=new MA(this.params,await this._getHtml(),this.context.frameRate,this.context.canvasSize),await this._renderer.init(),this}async _getHtml(){if(this._html)return this._html;const{blob:t,release:o}=await this.context.assetFetcher.get(this.params.source);try{return this._html=await t.text(),this._html}catch(r){const n="Failed to get html. kind: "+this.params.source.kind+", uri: "+(this.params.source.kind==="uri"?this.params.source.uri:"")+" blob size: "+(this.params.source.kind==="blob"?""+this.params.source.blob.size:"N/A");
3571throw this._logger.error(null,n,r),Ae(je.FILE_READ_ERROR,r)}finally{o()}}async _destroyImpl(){this._renderer?.destroy(),this._renderer=null,this._html=null}async _buildImpl(t){if(!this._renderer)throw Ae(je.LOGIC_ERR,"textbox renderer is not initialized");return await this._renderer.render(t)}_shouldReRenderImpl(t,o){if(!this._renderer)throw Ae(je.LOGIC_ERR,"textbox renderer is not initialized");return this._renderer.shouldReRender(t,o)}}class ZHe{constructor(t){this._rendererContext=t}_rendererContext;_activeEntries=new Map;_initializingEntries=new Map;_logger=nn("RendererPool");_isDestroyed=!1;async prepare(t,o){if(this._assertNotDestroyed(),this._activeEntries.has(t))return;const r=this._initializingEntries.get(t)??this._startInitializing(t,o);await this._awaitInitializing(r)}async acquire(t,o){this._assertNotDestroyed();const r=this._activeEntries.get(t);if(r)return this._update(r.renderer,o);const n=this._initializingEntries.get(t);if(n){const a=await this._awaitInitializing(n);return await this._update(a,o),a}return this._awaitInitializing(this._startInitializing(t,o))}async release(t){const o=this._activeEntries.get(t);if(o)try{await o.renderer.destroy()}catch(r){const n=Ae(void 0,r,"Error while destroying renderer for trackId: "+t);this._logger.warn(null,n.message)}finally{this._activeEntries.delete(t)}}async destroy(){this._isDestroyed=!0;const t=[...this._activeEntries.values()],o=[...this._initializingEntries.entries()];this._activeEntries.clear(),this._initializingEntries.clear(),await Promise.all([...t.map(({renderer:r})=>this._destroyRenderer(r)),...o.map(async([r,n])=>{try{const a=await n.renderer;await this._destroyRenderer(a)}catch(a){const i=Ae(void 0,a,"Error while initializing renderer for trackId: "+r);this._logger.warn(null,i.message)}})])}_assertNotDestroyed(){if(this._isDestroyed)throw Ae(je.LOGIC_ERR,"RendererPool is destroyed")}async _awaitInitializing(t){const o=await t.renderer;return this._assertNotDestroyed(),o}_startInitializing(t,o){const r=this._createRenderer(o),n=Symbol(),a=this._initializeRenderer(t,r,n),i={token:n,renderer:a};return this._initializingEntries.set(t,i),i}async _initializeRenderer(t,o,r){try{const n=await o.init();return!this._isDestroyed&&this._activeEntries.set(t,{renderer:n}),n}catch(n){const a=Ae(void 0,n,"Failed to initialize renderer for trackId: "+t);throw await this._destroyRenderer(o),a}finally{this._initializingEntries.get(t)?.token===r&&this._initializingEntries.delete(t)}}async _destroyRenderer(t){try{await t.destroy()}catch(o){const r=Ae(void 0,o,"Error while destroying renderer");this._logger.warn(null,r.message)}}async _update(t,o){return t.params===o?t:await t.update(o)?(this._logger.debug(null,"Reinitializing renderer for "+t.i
3571d),t.init()):t}_createRenderer(t){switch(t.type){case"Video":return new LHe(t,this._rendererContext);case"Image":return new VHe(t,this._rendererContext);case"Textbox":return new QHe(t,this._rendererContext);case"Shape":return new WHe(t,this._rendererContext);case"Caption":return new qHe(t,this._rendererContext);case"Character":return new MHe(t,this._rendererContext)}}}class DP{constructor(t){this._rendererContext=t,this._scene=new mHe(this._rendererContext.canvasSize,Qa("forceWebGPU"),this._rendererContext.abortSignal),this._mainRendererPool=new ZHe(this._rendererContext)}_rendererContext;_scene;_mainLayer=new hHe;_mainRendererPool;_activeTrackIds=new Set;_trackChildIds=new Map;_activeGlobalEffects=new Set;_logger=nn("RenderEngine");_lastHasContext=null;_currentBlendEffect=null;_blendSourceEngine=null;_blendSourceTrackIds=[];get hasContext(){return this._scene.hasContext}get errorMessage(){return this._scene.errorMessage}async init(){this._throwIfAborted(),await this._scene.init(),this._logger.verbose(null,"init: scene initialized")}async updateMainLayer({globalEffects:t,tracks:o}){this._throwIfAborted(),this._logger.debug(null,"updateMainLayer: target="+Object.keys(o.target).length+" removed="+o.removed.length+" effects="+JSON.stringify(t)),await Promise.all(o.removed.map(n=>(this._mainLayer.removeRenderer(n),this._mainRendererPool.release(n)))),await Promise.all(Object.entries(o.target).map(async([n,a])=>{const i=await this._mainRendererPool.acquire(n,a);this._mainLayer.setRenderer(n,i)}));const r=["Background","Blend"];for(const n of r)t[n]?this._mainLayer.upsertEffect(t[n]):(this._mainLayer.removeEffect(n),n==="Blend"&&(this._currentBlendEffect=null,await this._clearBlendSourceLayer()))}resetGlobalEffects(){this._mainLayer.removeEffect("Background"),this._mainLayer.removeEffect("Blend")}updateBlendEffect(t,o,r){this._throwIfAborted(),this._currentBlendEffect?.params.effectId!==t.effectId&&(this._logger.debug(null,"updateBlendEffect: id="+t.effectId),this._currentBlendEffect={params:t,tracks:o,effects:r,dirty:!0})}async prepare(t){this._throwIfAborted(),this._logger.debug(null,"prepare: tracks="+Object.keys(t).length),await Promise.all(Object.entries(t).map(([o,r])=>this._mainRendererPool.prepare(o,r)))}async destroy(t=!0){this._logger.debug(null,"destroy: begin"),await this._destroyBlendSourceEngine(),this._scene.destroy(t),await this._mainLayer.destroy(),await this._mainRendererPool.destroy(),this._currentBlendEffect=null,this._activeTrackIds.clear(),this._activeGlobalEffects.clear(),this._logger.debug(null,"destroy: done")}async _destroyBlendSourceEngine(){const t=this._blendSourceEngine;t&&(this._blendSourceEngine=null,this._blendSourceTrackIds=[],await t.destroy(!1))}async _clearBlendSourceLayer(){const t=this._blendSourceEngine;if(!t)return;const o=this._blendSourceTrackIds;o.length!==0&&(this._blendSourceTrackIds=[],await t.updateMainLayer({globalEffects:{},tracks:{target:{},removed:o}}))}async render(t){try{this._logContextTransitionIfNeeded(t),this._throwIfAborted();const[o,r,n]=await this._mainLayer.render(t);await this._sync(o,r);const a=await this._scene.draw(t.as.us("round"));return this._logContextTransitionIfNeeded(t),{bitmap:a,elements:n,canvasSize:this._rendererContext.canvasSize}}catch(o){throw Ae(je.VIDEO_RENDER_ERR,o,"Error while rendering video")}finally{this._logContextTransitionIfNeeded(t)}}_logContextTransitionIfNeeded(t){const o=this._lastHasContext,r=this._scene.hasContext;this._lastHasContext=r,o!==null&&o===!0&&r===!1&&(this._logger.warn(null,"RenderEngine context lost (hasContext: true -> false)","t="+t.as.ms("floor")+"ms","fps="+this._rendererContext.frameRate,"size="+this._rendererContext.canvasSize.width+"x"+this._rendererContext.canvasSize.height,"useHWAccel="+this._rendererContext.useHWAccel,"tracks="+this._activeTrackIds.size,"globalEffects="+this._activeGlobalEffects.size,"blendEffect="+(this._currentBlendEffect?.params.effectId??"none")),this._logContextLostDiagnostics())}_logContextLostDiagnostics(){try{const t=this._scene.collectDiagnostics();this._logger.error(null,"[ContextLostDiagnostics]",JSON.stringify(t,null,2))}catch(t){this._logger.warn(null,"Failed to collect context lost diagnostics",t)}}collectDiagnostics(){return this._scene.collectDiagnostics()}async _sync(t,o){await Promise.all([this._syncNodes(t),this._syncGlobalEffects(o)])}_handleRemovedTracks(t){[...this._activeTrackIds].filter(r=>
3571!t.has(r)).forEach(r=>{const n=[...this._trackChildIds.get(r)??[]];this._scene.remove(n),this._trackChildIds.delete(r)})}async _handleUpsertedTracks(t){this._activeTrackIds.clear();for(const[o,r]of t.entries()){if(this._activeTrackIds.add(o),!r)continue;const n=new Map(r.map(s=>[s.id,s])),a=this._trackChildIds.get(o)??new Set,i=[];for(const s of a)!n.has(s)&&i.push(s);this._scene.remove(i),await this._scene.upsert([...n.entries()]),this._trackChildIds.set(o,new Set(n.keys()))}}async _syncNodes(t){const o=new Map(t);this._handleRemovedTracks(o),await this._handleUpsertedTracks(o)}async _syncGlobalEffects(t){const o=[];for(const n of this._activeGlobalEffects)!(n in t)&&o.push(n);o.length>0&&this._scene.removeGlobalEffects(o),this._activeGlobalEffects.clear();const r=[];for(const[n,a]of Object.entries(t))this._activeGlobalEffects.add(n),a&&r.push(a);if(r.length>0&&this._scene.upsertGlobalEffects(r),this._currentBlendEffect?.dirty){const{params:n,tracks:a,effects:i}=this._currentBlendEffect;this._logger.debug(null,"blend: rendering source id="+n.effectId+" tracks="+Object.keys(a).length);try{!this._blendSourceEngine&&(this._blendSourceEngine=new DP(this._rendererContext),await this._blendSourceEngine.init());const s=this._blendSourceEngine,x=this._blendSourceTrackIds.filter(l=>!(l in a));s.resetGlobalEffects(),this._logger.debug(null,"blend: updating main layer"),await s.updateMainLayer({globalEffects:i,tracks:{target:a,removed:x}}),this._blendSourceTrackIds=Object.keys(a),this._logger.debug(null,"blend: updating main layer done");const c=await s.render(X.fromUS(n.targetTimeline));this._scene.setBlendSource(await my(c.bitmap)),this._logger.debug(null,"blend: source updated"),this._currentBlendEffect.dirty=!1}catch(s){throw await this._destroyBlendSourceEngine().catch(()=>{}),s}}}_throwIfAborted(){if(this._rendererContext.abortSignal.aborted)throw Ae(je.LOGIC_ERR,"RenderEngine aborted")}}class $He extends tY{constructor(t,o,r,n){super({fps:t.fps,stopTimeoutMs:3e3}),this._abortSignal=r,this._meta=t,this._dataProvider=o,this._assetFetcher=new wY(r),this._renderEngine=new DP({frameRate:this._meta.fps,canvasSize:this._meta.size,useHWAccel:this._meta.useHwAccel,assetFetcher:this._assetFetcher,videoDecoderPool:this._videoDecoderPool,abortSignal:r,mode:this._meta.mode,getPreviewRate:n}),r.addEventListener("abort",()=>this._end$.next(),{once:!0})}_abortSignal;_meta;_logger=nn("VideoPreviewer");_assetFetcher;_renderEngine;_dataProvider;_videoDecoderPool=new D1e;_render$=new aJ(void 0);_end$=new id;_warmupEnd$=new id;get hasContext(){return this._renderEngine.hasContext}get errorMessage(){return this._renderEngine.errorMessage}collectDiagnostics(){return this._renderEngine.collectDiagnostics()}next=async()=>{const t=await this._nextPrepared();if(!t)return!1;const[o,r,n]=t;return this._render$.next({...this._dataProvider.get(o),projectTimelineTime:o,videoTimelineTime:r,duration:n,advancesPlayback:!0}),!0};stream=()=>{const t=this._render$.asObservable().pipe(wl(this._end$),jl(n=>n!==void 0),iJ((n,a)=>{const i=a.mainLayer.tracks.target,s=this._diffRemoved(n.prevTargets,i),x=a.projectTimelineTime.add(X.fromSec(this._meta.mode==="live"?10:3));return{prevTargets:i,job:{payload:a,removed:s,warmupTo:x}}},{}),At(n=>n.job),jl(n=>n!==void 0)),o=t.pipe(wl(this._end$),St(({payload:n,removed:a})=>zt(this._renderEngine.updateMainLayer({globalEffects:n.mainLayer.globalEffects,tracks:{target:n.mainLayer.tracks.target,removed:a}})).pipe(er(()=>{const i=n.blendLayer;i&&this._renderEngine.updateBlendEffect(i.blendEffect,i.tracks,i.effectParams)}),St(()=>new sJ(i=>{this._renderEngine.render(n.projectTimelineTime).then(s=>{if(i.closed){$s(s.bitmap);return}i.next({type:"Video",bitmap:s.bitmap,timelineTime:n.videoTimelineTime,projectTimelineTime:n.projectTimelineTime,duration:n.duration,elements:s.elements,canvasSize:s.canvasSize}),i.complete()},s=>i.error(s))})))),wl(this._end$)),r=t.pipe(jl(({payload:n})=>n.advancesPlayback),Ma(({payload:n,warmupTo:a})=>zt(this._warmup(n.projectTimelineTime,a).catch(()=>{}))),wl(this._end$),wl(this._warmupEnd$),xJ());return uR(o,r).pipe(er({error:()=>{this.stop()}}),x1(()=>{this._logger.verbose(null,"video previewer ended"),this._end$.next()}))};async renderCurrent(){const t=this._timelineGeneration,o=this._timeline.current();if(!o)return!1;const[r,n,a]=o;return!await this._waitForBuffer(n,t)||t!==this._timelineGeneration?!1:(this._render$.next({...this._dataProvider.get(r),projectTimelineTime:r,videoTimelineTime:n,duration:a,advancesPlayback:!1}),!0)}complete(){this._warmupEnd$.next(),this._render$.complete()}clearCache(){this._dataProvider.clear()}_resetTimeDependentRenderState(){}async _onInit(){this._logger.verbose(null,"Initializing render engine"),await this._renderEngine.init(),this._logger.verbose(null,"Render engine initialized")}async _onStop(){this._end$.next()}async _onDestroy(){this._logger.verbose(null,"video previewer destroy begin");try{try{await this._renderEngine.destroy()}catch(t){this._logger.warn(null,"render engine destroy error: "+qr(t))}this._videoDecoderPool.destroy()}finally{this._render$.complete(),this._end$.complete(),this._warmupEnd$.complete(),this._assetFetcher.clear(),this._logger.verbose(null,"video previewer destroy done")}}_diffRemoved(t,o){return t?Object.keys(t).filter(r=>!(r in o)).map(r=>r):[]}async _warmup(t,o){try{const r=this._dataProvider.getUpcomingParams(t,o),n=Object.values(r).map(a=>a.type==="Video"?null:"source"in a?a.source:null).filter(_y);await Promise.all([this._assetFetcher.prefetch(n),this._renderEngine.prepare(r)])}catch(r){throw this._logger.warn(null,"warmup error: "+qr(r)),Ae(je.UNKNOWN_ERR,r)}}_onFetchData(t,o){return this._dataProvider.fetch(t,o,this._meta.size)}}class QY{constructor(t,o,r,n,a){if(this._abortSignal=n,!o&&!r)throw Ae(je.LOGIC_ERR,"Video or audio data provider is required");if(this._meta=t,t.video&&!o)throw Ae(je.LOGIC_ERR,"Video data provider is required");if(this._video=t.video?new $He(t.video,o,this._abortSignal,a):null,t.audio&&!r)throw Ae(je.LOGIC_ERR,"Audio data provider is required");this._audio=t.audio?new L1e(t.audio,r,this._abortSignal):null,this._abortSignal.addEventListener("abort",()=>this.stop(),{once:!0})}_abortSignal;_meta;_video;_audio;_videoStrand=new Mu;_audioStrand=new Mu;_logger=nn("Previewer");get fps(){if(!this._meta.video)throw Ae(je.LOGIC_ERR,"Video meta is not available");return this._meta.video.fps}get sampleRate(){if(!this._meta.audio)throw Ae(je.LOGIC_ERR,"Audio meta is not available");return this._meta.audio.sampleRate}get numberOfChannels(){if(!this._meta.audio)throw Ae(je.LOGIC_ERR,"Audio meta is not available");return this._meta.audio.numberOfChannels}get videoSize(){if(!this._meta.video)throw Ae(je.LOGIC_ERR,"Video meta is not available");return this._meta.video.size}get duration(){const t=this._video?.duration??X.zero(),o=this._audio?.duration??X.zero();return X.max(t,o)}get channels(){if(!this._meta.audio)throw Ae(je.LOGIC_ERR,"Audio meta is not available");return this._meta.audio.numberOfChannels}get currentTime(){const t=this._video?.currentTime,o=this._audio?.currentTime,r=[t,o].filter(_y);return r.length?X.min(...r):null}isAlignedTo(t){const o=r=>r!=null&&r.eq(t);return(!this._video||o(this._video.currentTime))&&(!this._audio||o(this._audio.currentTime))}get ended(){return this._video&&this._audio?this._video.ended&&this._audio.ended:this._video?this._video.ended:this._audio?this._audio.ended:!1}get videoEnded(){return this._video?.ended??!0}hasContext(){return this._video?.hasContext??!0}get errorMessage(){return this._video?.errorMessage??null}collectDiagnostics(){return this._video?.collectDiagnostics?.()??null}async init(t,o){if(gy(t).length===0)throw Ae(je.LOGIC_ERR,"No slices to preview");this._logger.verbose(null,"Initializing previewer");const r=[];this._video&&r.push(this._video.init(t,o)),this._audio&&r.push(this._audio.init(t,o));try{await Promise.all(r)}catch(n){throw await Promise.allSettled(r),await this._handleInitError(n),n}this._logger.verbose(null,"Previewer initialized")}async destroy(){try{this._logger.verbose(null,"stopping previewer"),await this.stop()}catch(t){this._logger.warn(null,"stop error: "+qr(t))}try{this._logger.verbose(null,"destroying previewer"),await Promise.all([this._video?.destroy(),this._audio?.destroy()])}catch(t){this._logger.warn(null,"destroy error: "+qr(t))}}stream(){const t=[];return this._video&&t.push(this._video.stream()),this._audio&&t.push(this._audio.stream()),t.length>0?uR(...t):uR()}async seek(t,o){await Promise.all([this._video?.seek(t,o),this._audio?.seek(t,o)])}async renderCurrent(){return this._videoStrand.next(async()=>await this._video?.renderCurrent()??!1)}
3571async next(){const[t,o]=await Promise.all([this._video?this._videoStrand.next(()=>this._video.next()):Promise.resolve(!0),this._audio?this._audioStrand.next(()=>this._audio.next()):Promise.resolve(!0)]);return t&&o}async nextVideo(){return this._video?this._videoStrand.next(()=>this._video.next()):!0}async nextAudio(){return this._audio?this._audioStrand.next(()=>this._audio.next()):!0}complete(){this._video?.complete(),this._audio?.complete()}stop=af(async()=>{await Promise.all([this._video?.stop(),this._audio?.stop()])},{persistOnResolve:!1});_handleInitError=async t=>{const o=Ae(void 0,t).message;this._logger.error(null,"Failed to initialize "+o);const r=await Promise.allSettled([this._video?.destroy(),this._audio?.destroy()]);for(const n of r)n.status==="rejected"&&this._logger.warn(null,"destroy during init cleanup failed: "+qr(n.reason))}}class e4e{_strand=new Mu;_supplier;constructor(t){this._supplier=t}async fetch(t,o,r){return this._strand.next(()=>this._fetch(t,o,r))}async _fetch(t,o,r){return this._supplier.getSlice({timeStart:t,timeEnd:o,canvasSize:r})}}class t4e{_intervals=[];uncovered(t,o){const r=[];let n=t;for(const[a,i]of this._intervals){if(n.gte(o))break;if(!i.lte(n)){if(a.gte(o))break;a.gt(n)&&r.push([n,a]),n=i}}return n.lt(o)&&r.push([n,o]),r}add(t,o){if(t.gte(o))return;let r=t,n=o;const a=[];let i=!1;for(const[s,x]of this._intervals){if(x.lt(r)){a.push([s,x]);continue}if(s.gt(n)){!i&&(a.push([r,n]),i=!0),a.push([s,x]);continue}s.lt(r)&&(r=s),x.gt(n)&&(n=x)}i||a.push([r,n]),this._intervals=a}trimBefore(t){const o=[];for(const[r,n]of this._intervals)n.lte(t)||o.push([r.gte(t)?r:t,n]);this._intervals=o}clear(){this._intervals=[]}}const o4e=(e,t)=>{let o=-1,r=0;for(const n of t){const a=r4e(e,n.timelineStart);a<e.length&&e[a].timelineStart.eq(n.timelineStart)||(e.splice(a,0,n),o<0&&(o=a),r++)}return r===0?null:{firstIndex:o,count:r}},r4e=(e,t)=>{let o=0,r=e.length;for(;o<r;){const n=o+r>>1;e[n].timelineStart.lt(t)?o=n+1:r=n}return o};function n4e(e,t){const o=e.map((n,a)=>Math.max(n.length,...t.map(i=>(i[a]??"").length))),r=n=>n.map((a,i)=>a.padEnd(o[i]," ")).join(" | ");return[r(e),...t.map(r)].join(`
3572`)}class ZY{_fetcher;_store;_coverage=new t4e;_logger=nn("VideoPreviewData");constructor(t){this._fetcher=new e4e(t),this._store=new a4e}async fetch(t,o,r){const n=this._coverage.uncovered(t,o);for(const[a,i]of n){const s=await this._fetcher.fetch(a,i,r);if(this._logger.debug(a.as.ms("round"),"fetch: from="+a.as.ms("round")+" to="+i.as.ms("round")+" mainTracks="+s.mainLayer.tracks.size+" mainEffects="+s.mainLayer.globalEffectParams.size+" blendLayers="+(s.blendLayers?.size??0)),this._store.addMainLayer(s.mainLayer),s.blendLayers)for(const[x,c]of s.blendLayers.entries())this._store.addBlendLayer(x,c);this._coverage.add(a,i)}}clear(){this._store.clear(),this._coverage.clear()}get(t){return this._store.get(t)}seekCursor(t){this._store.seekCursor(t)}releaseBefore(t){this._store.releaseBefore(t),this._coverage.trimBefore(t)}getUpcomingParams(t,o){return this._store.getUpcomingParamsInRange(t,o)}}class a4e{_mainLayer={tracks:new Map,globalEffectParams:new Map};_blendLayers=new Map;_cursor=new Map;_logger=nn("VideoPreviewData.Cache");addMainLayer(t){this._addToLayer(this._mainLayer,t)}addBlendLayer(t,o){this._blendLayers.set(t,o)}_addToLayer(t,o){this._addToTracks(t.tracks,o.tracks),this._addToGlobalEffectParams(t.globalEffectParams,o.globalEffectParams)}_addToTracks(t,o){for(const r of o.values()){const n=t.get(r.id);n?o4e(n.params,r.params):t.set(r.id,r)}}_addToGlobalEffectParams(t,o){for(const r of o.values())t.set(r.effectId,r)}get(t){const o=this._getTargetLayerSlice(this._mainLayer,t),r=o.globalEffects.Blend,n=r?this._getBlendLayerResult(r):void 0;return{mainLayer:o,blendLayer:n}}_getBlendLayerResult(t){const o=this._blendLayers.get(t.effectId);if(!o)return;const r=X.fromUS(t.targetTimeline),n=this._getTargetTracks(o,r).target,a=this._getGlobalEffectParams(o,r);return delete a.Blend,{blendEffect:t,tracks:n,effectParams:a}}_getTargetLayerSlice(t,o){return{tracks:this._getTargetTracks(t,o),globalEffects:this._getGlobalEffectParams(t,o)}}_getTargetTracks(t,o){const r={};for(const n of t.tracks.values()){const a=this._findActiveParam(n,o);a&&(r[n.id]=a)}return{target:r}}_findActiveParam(t,o){const r=t.params;if(r.length===0)return;let n=Math.min(this._cursor.get(t.id)??0,r.length-1);for(;n>
35720&&r[n].timelineStart.gt(o);)n--;for(;n<r.length;n++){const a=r[n];if(!IHe(a))continue;const i=a.timelineStart;if(!a.timelineDuration.add(i).lte(o)){if(i.lte(o))return this._cursor.set(t.id,n),a;break}}}_getGlobalEffectParams(t,o){const r={};for(const n of t.globalEffectParams.values())if(X.fromUS(n.timelineEnd).lte(o))!(n.type in r)&&(r[n.type]=void 0);else if(X.fromUS(n.timelineStart).lte(o))switch(n.type){case"Background":r.Background=n;break;case"Blend":r.Blend=n;break;default:{const a=n;throw new Error("Unhandled effect type: "+a)}}return r}seekCursor(t){for(const o of this._mainLayer.tracks.values())this._findActiveParam(o,t)}releaseBefore(t){this._releaseLayerBefore(this._mainLayer,t);for(const o of this._blendLayers.keys())!this._mainLayer.globalEffectParams.has(o)&&this._blendLayers.delete(o);this._cursor.clear()}_releaseLayerBefore(t,o){for(const r of t.tracks.values()){const n=r.params.filter(a=>!a.timelineDuration.add(a.timelineStart).lte(o));if(n.length===0){t.tracks.delete(r.id);continue}r.params.length=0,r.params.push(...n)}for(const[r,n]of t.globalEffectParams.entries())X.fromUS(n.timelineEnd).lte(o)&&t.globalEffectParams.delete(r)}clear(){this._mainLayer.tracks.clear(),this._mainLayer.globalEffectParams.clear(),this._blendLayers.clear(),this._cursor.clear()}getUpcomingParamsInRange(t,o){const r={},n=Qa("isDev"),a=[];for(const i of this._mainLayer.tracks.values()){let s=!1;for(let x=0;x<i.params.length;x++){const c=i.params[x];if(c.type==="Audio")continue;const l=c.timelineStart,d=c.timelineDuration.add(l);if(!d.lte(t)){if(!s&&E1(l,d,t,o)){r[i.id]=c,s=!0;continue}if(l.gt(t))break}}}if(n&&a.length>0){const i=["trackId","removed","target","nextStart"],s="cache:upcomingRange from="+t.as.ms("round")+" to="+o.as.ms("round")+" tracks="+Object.keys(r).length,x=n4e(i,a);this._logger.debug(t.as.ms("round"),s+`
3573`+x)}return r}}const i4e=5e3,s4e=e=>e.type==="Video",x4e=async(e,t,o,r)=>{const n=nn("renderFirstFrame"),a=new QY({video:{fps:30,size:t,useHwAccel:!1,mode:"standard"}},new ZY(e),null,o);try{await a.init([{startInProject:X.zero().as.ms(),durationInProject:X.fromMS(1).as.ms()}]);const i=cJ(a.stream().pipe(jl(s4e)));a.next();const s=await HJ(i,i4e),x=await my(s.bitmap);try{return await zJ(x,r)}finally{$s(x)}}catch(i){return n.warn(null,"renderFirstFrameBlob failed: "+qr(i)),void 0}finally{await a.destroy()}},c4e=e=>I1(e),K2=e=>e,l4e=(e,t,o,r,n,a,i)=>{const s=n!==void 0?n*Math.PI/180:void 0,x={type:"Animation",effectId:K2(e.effectId),animationDuration:e.duration.as.us("round"),assetTimelineDuration:o.as.us("round"),timelineStart:r.as.us("round"),startDelay:e.startDelay.as.us("round"),canvasSize:t,elementZoom:1,assetRotation:s,flipH:a,flipV:i};return sS(e.variant)?{...x,variant:e.variant}:{...x,variant:e.variant}},d4e=(e,t)=>({type:"Background",effectId:K2(e.effectId),timelineStart:e.timelineStart.as.us("round"),timelineEnd:e.timelineEnd.as.us("round"),color:e.color,canvasSize:t}),u4e=(e,t)=>({type:"Blend",effectId:K2(e.effectId),timelineStart:e.timelineStart.as.us("round"),timelineEnd:e.timelineEnd.as.us("round"),targetTimeline:e.targetTimeline.as.us("round"),blendType:e.blendType,canvasSize:t}),p4e=(e,t,o)=>{if(!o)return null;if(o.type!=="Image")throw new C(_.C_EXPORT_PREPARE_ERROR,void 0,"Filter info not found for effect, effectId: "+e.effectId+", infoId: "+e.filterInfoId+", filterInfo: "+JSON.stringify(o));return{type:"Filter",effectId:K2(e.effectId),alpha:e.alpha,canvasSize:t,source:o.source}},f4e=(e,t,o,r)=>{const n=i=>({scale:i.scale,centerX:o?1-i.centerX:i.centerX,centerY:r?1-i.centerY:i.centerY});return{type:"Kenburns",effectId:K2(e.effectId),variant:e.variant,from:n(e.from),to:n(e.to),canvasSize:t}},g4e=(e,t,o,r)=>{switch(t.type){case"Filter":return p4e(t,o,r.get(t.filterInfoId)??null);case"Animation":{const n="transform"in e?e.transform:void 0;return l4e(t,o,e.timeline.duration,e.timeline.start,n?.rotation,n?.flipH,n?.flipV)}case"Kenburns":{const n="transform"in e?e.transform:void 0;return f4e(t,o,n?.flipH,n?.flipV)}}},_4e=(e,t)=>{switch(e.type){case"Background":return d4e(e,t);case"Blend":return u4e(e,t)}},sF=[],E4e=(e,t,o,r)=>{const n=new Map;for(const a of e){const i=[];Vp(a,t,o,i),n.set(a.modelId,{effectDependencies:i,infos:r(a)})}return n},Vp=(e,t,o,r)=>{if("effectIds"in e&&e.effectIds?.length)for(const n of e.effectIds){const a=t.get(n);
3573r.push(a),a?.type==="Filter"&&r.push(o(a.filterInfoId))}switch(e.type){case"Caption":e.original&&Vp(e.original,t,o,r),e.translated&&Vp(e.translated,t,o,r);break;case"Character":Vp(e.silentAsset,t,o,r),e.speakingAsset&&Vp(e.speakingAsset,t,o,r);break}},m4e=e=>e.type==="Textbox"||e.type==="Caption",h4e=(e,t,o)=>{const r=m4e(e),n=r?o:null,a=r?$e().getWebFontFamilies():null,i=a?.length===0?sF:a,s=r?$e().getSystemFontFamilies():null,x=s?.length===0?sF:s;return{model:e,effectDependencies:t.effectDependencies,infos:t.infos,lang:n,webFonts:i,systemFonts:x}},xF=(e,t)=>{if(e.length!==t.length)return!1;for(let o=0;o<e.length;o++)if(e[o]!==t[o])return!1;return!0},I4e=(e,t)=>e.model===t.model&&e.lang===t.lang&&e.webFonts===t.webFonts&&e.systemFonts===t.systemFonts&&xF(e.effectDependencies,t.effectDependencies)&&xF(e.infos,t.infos),RC=e=>e.width<=0||e.height<=0;class T4e{_visualByModel=new WeakMap;_visualCanvasSize=null;_audioByModel=new WeakMap;getOrCreate(t,o,r,n,a){const i=h4e(t,r,a),s=this.peek(t,o);if(s&&I4e(s.key,i))return s.value;const x=n(),c={key:i,value:x};return this.store(t,o,c),x.catch(()=>this.deleteIfCurrent(t,o,c)),x}peek(t,o){if(t.type==="Audio")return this._audioByModel.get(t);if(!(!RC(o)&&o!==this._visualCanvasSize))return this._visualByModel.get(t)}store(t,o,r){if(t.type==="Audio"){this._audioByModel.set(t,r);return}RC(o)||(o!==this._visualCanvasSize&&(this._visualByModel=new WeakMap,this._visualCanvasSize=o),this._visualByModel.set(t,r))}deleteIfCurrent(t,o,r){if(t.type==="Audio"){this._audioByModel.get(t)===r&&this._audioByModel.delete(t);return}!RC(o)&&o===this._visualCanvasSize&&this._visualByModel.get(t)===r&&this._visualByModel.delete(t)}}const Pd=e=>e.modelId,__=e=>e.infoId,E_=(e,t)=>e.infosById.get(t)??null,m_=(e,t)=>({x:Math.round(e.x*t.width),y:Math.round(e.y*t.height),zIndex:e.zIndex,adjustment:e.adjustment}),kP=(e,t)=>({width:Math.round(e.width*t.width),height:Math.round(e.height*t.height)}),S4e=(e,t)=>({width:Math.round(e.width*t.width),height:"auto"}),O4e=(e,t)=>{const o=E_(t,e.infoId);if(!o)return null;if(o.type!=="AVMedia")throw new C(_.C_EXPORT_PREPARE_ERROR,void 0,"Audio info not found for model, modelId: "+e.modelId+", infoId: "+e.infoId);return!o.hasAudioTrack||e.volume===0?null:{type:"Audio",sourceId:__(e),id:Pd(e),modelId:e.modelId,timelineStart:e.timeline.start,timelineDuration:e.timeline.duration,sourceIn:e.src.in,source:o.source,loop:e.src.loop,playbackRate:e.src.playbackRate,gain:C4e(e)}},C4e=e=>{const{volume:t,fadeIn:o,fadeOut:r}=e,n=e.timeline.start,a=e.timeline.start.add(e.timeline.duration),i=R4e(e),s=A4e(e),x=[];return i?(x.push([n.as.us(),0,"step"]),x.push([o.as.us(),t,"linear"])):x.push([n.as.us(),t,"step"]),s&&(x.push([r.as.us(),t,"step"]),x.push([a.as.us(),0,"linear"])),x},R4e=e=>{const t=e.timeline.start.add(e.timeline.duration);return e.fadeIn.gt(e.timeline.start)&&e.fadeIn.lte(t)},A4e=e=>{const t=e.timeline.start.add(e.timeline.duration);return e.fadeOut.gte(e.timeline.start)&&e.fadeOut.lt(t)},$Y=(e,t)=>{const o=E_(t,e.infoId);if(!o)return null;if(o.type!=="Image")throw new C(_.C_EXPORT_PREPARE_ERROR,void 0,"Image info not found for model, modelId: "+e.modelId+", infoId: "+e.infoId);return{type:"Image",timelineStart:e.timeline.start,timelineDuration:e.timeline.duration,id:Pd(e),modelId:e.modelId,sourceId:__(e),source:o.source,crop:e.crop,size:kP(e.size,t.canvasSize),position:m_(e.position,t.canvasSize),transform:e.transform,effects:t.effects.get(e.modelId)}},FP=(e,t)=>{const o=E_(t,e.infoId);if(!o)return null;if(o.type!=="AVMedia")throw new C(_.C_EXPORT_PREPARE_ERROR,void 0,"Video info not found for model, modelId: "+e.modelId+", infoId: "+e.infoId);return o.hasVideoTrack?{id:Pd(e),modelId:e.modelId,sourceId:__(e),loop:e.src.loop,timelineStart:e.timeline.start,timelineDuration:e.timeline.duration,sourceIn:e.src.in,type:"Video",position:m_(e.position,t.canvasSize),size:kP(e.size,t.canvasSize),crop:e.crop,source:o.source,transform:e.transform,effects:t.effects.get(e.modelId),playbackRate:e.src.playbackRate}:null},y4e=(e,t)=>
3573{const o=v4e(e,t);if(!o)return null;const r=e.speakingAsset?FP(e.speakingAsset,t):null,n=Pd(e);return e.timelines.map((a,i)=>{const s=a.isAudible&&!!r;return{type:"Character",id:n+"-"+i,modelId:e.modelId,timelineStart:a.timelineStart,timelineDuration:a.timelineDuration,position:o.position,silentAsset:o,speakingAsset:r,shouldAnimate:s}})},v4e=(e,t)=>{const o=e.silentAsset;switch(o.type){case"Image":return $Y(o,t);case"Video":return FP(o,t);default:{const r=o;throw new C(_.C_EXPORT_PREPARE_ERROR,void 0,"Unsupported base asset type: "+r)}}},w4e=async(e,t)=>{const o=await N4e(e,t.canvasSize,E_(t,e.infoId));return o?{type:"Shape",id:Pd(e),modelId:e.modelId,sourceId:__(e),timelineStart:e.timeline.start,timelineDuration:e.timeline.duration,effects:t.effects.get(e.modelId),size:kP(e.size,t.canvasSize),position:m_(e.position,t.canvasSize),crop:e.crop,transform:e.transform,source:o}:null},N4e=async(e,t,o)=>{const r=await(e.variant==="1d"?b4e(e,t):P4e(e,t,o));return r?{kind:"blob",blob:new Blob([r],{type:"image/svg+xml"})}:null},P4e=async(e,t,o)=>{if(!o)return null;if(o.type!=="Shape")throw new C(_.C_EXPORT_PREPARE_ERROR,void 0,"Shape info not found for model, modelId: "+e.modelId+", infoId: "+e.infoId);const{width:r,height:n}=t,a=await BWe(o.source);return rn.template(await a.text())({strokeWidth:e.stroke.width*r,strokeColor:e.stroke.color,planeColor:e.plane?.color,width:r*e.size.width,height:n*e.size.height,isDashed:e.stroke.isDashed,isRounded:e.stroke.isRounded,cornerRounding:e.cornerRounding,randomId:h1()})},b4e=(e,t)=>{const o=t.width*e.size.width,r=e.size.height*(e.head?t.height/8:t.height),n=!e.head,a=e.head==="double",i=e.stroke.isRounded,s=e.stroke.isDashed;if(n)return`<svg
3574      viewBox="0 0 `+o+" "+r+`"
3575      xmlns="http://www.w3.org/2000/svg"
3576      style="width: `+o+"px;height: "+r+`px; overflow: visible"
3577    >
3578      <line
3579        x1="`+r/2+`"
3580        y1="`+r/2+`"
3581        x2="`+(o-r/2)+`"
3582        y2="`+r/2+`"
3583        stroke="`+e.stroke.color+`"
3584        stroke-width="`+r+`"
3585        stroke-linecap="`+(i?"round":"square")+`"
3586        stroke-dasharray="`+(s?2.2*r+" "+2.2*r:"0")+`"
3587      />
3588    </svg>`;if(a){const p=r*4,f=r*4,E=r*8,T=Fn(e.stroke.color).alpha(1).toHex(),O=Fn(e.stroke.color).alpha();return`<svg
3589      viewBox="0 0 `+o+" "+E+`"
3590      xmlns="http://www.w3.org/2000/svg"
3591      style="width: `+o+"px;height: "+E+"px;opacity:"+O+`; overflow: hidden"
3592    >
3593      <line
3594        x1="`+r*Math.sqrt(2)+`"
3595        y1="`+E/2+`"
3596        x2="`+(o-r*Math.sqrt(2))+`"
3597        y2="`+E/2+`"
3598        stroke="`+T+`"
3599        stroke-width="`+r+`"
3600        stroke-linecap="`+(i?"round":"square")+`"
3601        stroke-dasharray="`+(s?2.2*r+" "+2.2*r:"0")+`"
3602      />
3603      <polyline
3604        points="`+f+","+(E-p)/2+" "+(i?r/2:r)+","+E/2+" "+f+","+(E+p)/2+`"
3605        fill="none"
3606        stroke="`+T+`"
3607        stroke-width="`+r+`"
3608        stroke-linecap="`+(i?"round":"square")+`"
3609        stroke-linejoin="`+(i?"round":"inherit")+`"
3610      />
3611      <polyline
3612            points="`+(o-f)+","+(E-p)/2+" "+(i?o-r/2:o-r)+","+E/2+" "+(o-f)+","+(E+p)/2+`"
3613            fill="none"
3614            stroke="`+T+`"
3615            stroke-width="`+r+`"
3616            stroke-linecap="`+(i?"round":"square")+`"
3617            stroke-linejoin="`+(i?"round":"inherit")+`"
3618          />
3619    </svg>`}const x=r*4,c=r*4,l=r*8,d=Fn(e.stroke.color).alpha(1).toHex(),u=Fn(e.stroke.color).alpha();return`<svg
3620      viewBox="0 0 `+o+" "+l+`"
3621      xmlns="http://www.w3.org/2000/svg"
3622      style="width: `+o+"px;height: "+l+"px;opacity:"+u+`; overflow: hidden"
3623    >
3624      <line
3625        x1="`+r*Math.sqrt(2)+`"
3626        y1="`+l/2+`"
3627        x2="`+(o-r/2)+`"
3628        y2="`+l/2+`"
3629        stroke="`+d+`"
3630        stroke-width="`+r+`"
3631        stroke-linecap="`+(i?"round":"square")+`"
3632        stroke-dasharray="`+(s?2.2*r+" "+2.2*r:"0")+`"
3633      />
3634      <polyline
3635        points="`+c+","+(l-x)/2+" "+(i?r/2:r)+","+l/2+" "+c+","+(l+x)/2+`"
3636        fill="none"
3637        stroke="`+d+`"
3638        stroke-width="`+r+`"
3639        stroke-linecap="`+(i?"round":"square")+`"
3640        stroke-linejoin="`+(i?"round":"inherit")+`"
3641      />
3642    </svg>`};class cu{cache=new vY(30);inFlight=new Map;queue=[];maxConcurrency=5;activeCount=0;static _instance;constructor(){}static getInstance(){return cu._instance===void 0&&(cu._instance=new cu),cu._instance}async get(t){const o=this.cache.get(t);if(o!==void 0)return o;const r=this.inFlight.get(t);if(r)return r;const n=new MP,a=n.promise();return this.inFlight.set(t,a),this.queue.push({path:t,future:n}),this._drain(),a}clear(){this.cache.clear(),this.inFlight.clear(),this.queue.length=0,this.activeCount=0}_drain(){queueMicrotask(()=>this._processQueue())}async _processQueue(){for(;this.activeCount<this.maxConcurrency&&this.queue.length>0;){const t=this.queue.shift();
3642this.activeCount+=1,this._run(t).catch(()=>{}).finally(()=>{this.activeCount=Math.max(0,this.activeCount-1),this._drain()})}}async _run(t){try{const o=await $f(t.path),r=await I1(o);this.cache.set(t.path,r),t.future.resolve(r)}catch(o){t.future.reject(o)}finally{this.inFlight.delete(t.path)}}}const L4e=async e=>{if(e.length===0)return[];const t=cu.getInstance(),o=await Promise.all(e.map(r=>t.get(r.path)));return e.map((r,n)=>({...r,path:o[n]}))},DA=async(e,t)=>{const o=k4e(e,E_(t,e.infoId));if(!o)return null;const r=Object.values(e.deltas);return{type:"Textbox",id:Pd(e),modelId:e.modelId,sourceId:__(e),timelineStart:e.timeline.start,timelineDuration:e.timeline.duration,loop:e.loop,duration:e.duration,attributes:e.attributes,deltas:e.deltas,source:o,scale:D4e(e.scaleFactor,t.canvasSize),fonts:await V4e(r),size:S4e(e.size,t.canvasSize),position:m_(e.position,t.canvasSize),crop:e.crop,transform:e.transform,effects:F4e(e,t),lang:t.textRenderLanguage}},M4e=async(e,t)=>{const{canvasSize:o}=t,r=e.original?await DA(e.original,t):null,n=e.translated?await DA(e.translated,t):null;return!r&&!n?null:{type:"Caption",id:Pd(e),modelId:e.modelId,timelineStart:e.timeline.start,timelineDuration:e.timeline.duration,position:m_(e.position,o),yAlign:e.yAlign,original:r??null,translated:n??null}},D4e=(e,{width:t,height:o},{lines:r=9,defaultFontSize:n=200,emToPx:a=8}={})=>{const i=n/a*r,s=Math.min(1,t/o/e);return o*s/i},k4e=(e,t)=>{if(e.infoId===Ao)return{kind:"blob",blob:new Blob([AZ],{type:"text/html"})};if(!t)return null;if(t.type!=="Textbox")throw new C(_.C_EXPORT_PREPARE_ERROR,void 0,"Textbox info not found for model, modelId: "+e.modelId+", infoId: "+e.infoId);return t.source},F4e=(e,t)=>{const o=t.effects.get(e.modelId),r=U4e(e,t);return!r||o?.Animation?.variant===r.variant?o:{...o,Animation:r}},U4e=(e,t)=>{const o=zWe(e.infoId);if(!o)return;const r=e.transform?.rotation,n=r!==void 0?r*Math.PI/180:void 0;return{type:"Animation",effectId:e.modelId+":"+o.variant,variant:o.variant,animationDuration:o.animationDuration.as.us("round"),assetTimelineDuration:e.duration.as.us("round"),timelineStart:e.timeline.start.as.us("round"),startDelay:X.zero().as.us("round"),canvasSize:t.canvasSize,elementZoom:1,assetRotation:n,flipH:e.transform?.flipH,flipV:e.transform?.flipV}},V4e=async e=>{const t=G4e(e),o=await L4e(t);return dV(o)},G4e=e=>{const t=W4e(),o=e.flatMap(r=>r.ops.map(n=>{const a=n.attributes?.font;if(!a||n.attributes?.bold!=="true")return a;const{fontName:i}=zc(a),s=t.filter(c=>c.fontName.toUpperCase()===i.toUpperCase()&&c.path),x=s.filter(c=>c.weight>=700).sort((c,l)=>c.weight-l.weight)[0]??s.filter(c=>c.weight<700).sort((c,l)=>l.weight-c.weight)[0];return x?i+"_"+x.weight:a})).filter(_y);return[...new Set(o)].flatMap(r=>{const{fontName:n,weight:a}=zc(r),i=t.find(s=>s.fontName.toUpperCase()===n.toUpperCase()&&s.weight===a&&s.path);return i?.path?[{fontName:i.fontName,path:i.path,weight:i.weight}]:[]})},W4e=()=>$e().getWebFontFamilies(),H4e=async(e,t,o,r)=>(await Promise.all(e.filter(a=>a.timeline.duration.gt(X.zero())).map(async a=>{const i=r.get(a.modelId);if(!i)throw new Error("Missing render-param cache dependencies for model "+a.modelId);const s=await j4e(a,t,o,i);return s||null}))).flat().filter(gR),j4e=(e,t,o,r)=>o(e,r,()=>z4e(e,t)),z4e=async(e,t)=>{switch(e.type){case"Audio":return O4e(e,t);case"Video":return FP(e,t);case"Image":return $Y(e,t);case"Caption":return M4e(e,t);case"Shape":return w4e(e,t);case"Textbox":return DA(e,t);case"Character":return y4e(e,t)}},Y4e=e=>e.__bound==="global",B4e=e=>e.__bound==="model",e8=(e,t,o)=>Object.values(e.effects).filter(Y4e).filter(r=>r.timelineStart.lt(r.timelineEnd)&&E1(r.timelineStart,r.timelineEnd,t,o??t)),K4e=(e,t)=>{const o=new Map;for(const r of t.values()){const n=L.get(e.effects,r);n&&B4e(n)&&o.set(n.effectId,n)}return o},X4e=(e,t)=>{const o=J4e(e)[t];return o||(h("selectors.info.ts").warn("Info "+t+" is broken or not found"),null)},J4e=e=>e.infos,cF=new WeakMap,q4e=(e,t)=>e.start.lt(t)?1:e.start.gt(t)?-1:0,Q4e=e=>{const t=X.zero(),o=[];let r=0;for(const i of Object.values(e)){const s=i.timeline.start,x=i.timeline.duration;x.gt(t)&&o.push({model:i,start:s,end:s.add(x),ord:r}),r+=1}o.sort((i,s)=>i.start.lt(s.start)?-1:i.start.gt(s.start)?1:0);const n=new Array(o.length);let a;for(let i=0;i<o.length;i++){const s=o[i].end;a=a===void 0||s.gt(a)?s:a,n[i]=a}return{entries:o,prefixMaxEnd:n}},Z4e=e=>{let t=cF.get(e);return t===void 0&&(t=Q4e(e),cF.set(e,t)),t},$4e=(e,t,o)=>{const{entries:r,prefixMaxEnd:n}=Z4e(e.models),a=o??t,i=z0(r,a,q4e,!0)??0,s=[];for(let x=i-1;x>=0&&!n[x].lte(t);x--){const c=r[x];t.lt(c.end)&&s.push(c)}
3642return s.sort((x,c)=>x.ord-c.ord),s.map(x=>x.model)},t8=e=>{switch(e.type){case"Audio":case"Image":case"Textbox":case"Shape":case"Video":return[e.infoId];case"Caption":return[e.original?.infoId,e.translated?.infoId].filter(gR);case"Character":return[e.silentAsset.infoId,e.speakingAsset?.infoId].filter(gR)}const t=e;throw new Error("Unhandled model type: "+t)},eje=e=>{const t=e.flatMap(o=>{switch(o.type){case"Audio":case"Image":case"Textbox":case"Shape":case"Video":return o.effectIds;case"Caption":return(o.original?.effectIds??[]).concat(o.translated?.effectIds??[]);case"Character":return o.silentAsset.effectIds.concat(o.speakingAsset?.effectIds??[])}const r=o;throw new Error("Unhandled model type: "+r)}).flat();return new Set(t)},tje=e=>{const t=new T4e;return o=>oje(o,t,e())},oje=async({timeStart:e,timeEnd:t,canvasSize:o,mediaStore:r},n,a)=>{const i=(l,d,u)=>n.getOrCreate(l,o,d,u,a),s={canvasSize:o,mediaStore:r,selectCachedRenderParams:i,textRenderLanguage:a},x=await o8(e,t,s),c=await aje(e,t,s);return{mainLayer:x,blendLayers:c}},o8=async(e,t,o)=>{const r=await rje(e,t,o),n=nje(e,t,o);return{tracks:r,globalEffectParams:n}},rje=async(e,t,o)=>{const r=await ije(e,t,o);return dje(r)},nje=(e,t,{canvasSize:o,mediaStore:r})=>new Map(e8(r,e,t).map(n=>{const a=_4e(n,o);return[a.effectId,a]})),aje=async(e,t,o)=>{const r=e8(o.mediaStore,e,t).filter(a=>a.type==="Blend");if(r.length===0)return;const n=await Promise.all(r.map(async a=>{const i=await o8(a.targetTimeline,a.targetTimeline.add(X.fromUS(1)),o);for(const[s,x]of i.globalEffectParams)x.type==="Blend"&&i.globalEffectParams.delete(s);return[K2(a.effectId),i]}));return new Map(n)},ije=async(e,t,{canvasSize:o,mediaStore:r,selectCachedRenderParams:n,textRenderLanguage:a})=>{const i=$4e(r,e,t),s=sje(i,r),x=cje(r,xje(i,s)),c=lje(i,o,s,x),l=E4e(i,s,u=>x.get(u)??null,u=>t8(u).map(p=>x.get(p)??null));return await H4e(i,{effects:c,canvasSize:o,infosById:x,textRenderLanguage:a},n,l)},sje=(e,t)=>K4e(t,eje(e)),xje=(e,t)=>{const o=new Set;for(const r of e)for(const n of t8(r))n!==Ao&&o.add(n);for(const r of t.values())r.type==="Filter"&&o.add(r.filterInfoId);return o},cje=(e,t)=>new Map([...t].map(o=>[o,X4e(e,o)])),lje=(e,t,o,r)=>{const n=(x,c)=>{switch(c.type){case"Filter":x.Filter=c;return;case"Animation":x.Animation=c;return;case"Kenburns":x.Kenburns=c;return}},a=new Map,i=new Set,s=x=>{if(i.has(x.modelId))return;i.add(x.modelId);const c={};if("effectIds"in x&&x.effectIds?.length)for(const l of x.effectIds){const d=o.get(l);if(!d)continue;const u=g4e(x,d,t,r);u&&n(c,u)}switch(Object.keys(c).length>0&&a.set(x.modelId,c),x.type){case"Caption":x.original&&s(x.original),x.translated&&s(x.translated);break;case"Character":s(x.silentAsset),x.speakingAsset&&s(x.speakingAsset);break}};for(const x of e)s(x);return a},dje=e=>{const t=[...e].sort((n,a)=>X.compare(n.timelineStart,a.timelineStart)),o=new Map;for(const n of t){const a=n.type==="Video"||n.type==="Audio"?n.type+":"+n.sourceId.slice(0,8):n.type+":"+n.id.slice(0,8),i=o.get(a)??[];let s=!1;for(const x of i){const c=x.params[x.params.length-1];if(c.timelineDuration.add(c.timelineStart).lte(n.timelineStart)){x.params.push(n),s=!0;break}}if(!s){const x=i.length,c=a+"#"+x;i.push({trackId:c,params:[n]}),o.set(a,i)}}const r=new Map;for(const n of o.values())for(const a of n){const i=r.get(a.trackId);i?i.params.push(...a.params):r.set(a.trackId,{id:a.trackId,params:a.params})}return r},kA=e=>{Object.isFrozen(e)||(Object.freeze(e),e.type==="Character"&&(kA(e.silentAsset),e.speakingAsset&&kA(e.speakingAsset)))},lF=e=>{for(const t of e.tracks.values())for(const o of t.params)kA(o)},uje=e=>{if(lF(e.mainLayer),e.blendLayers)for(const t of e.blendLayers.values())lF(t);return e};class fh{_store;_selectTimelineSlice;constructor(t,o){this._store=t,this._selectTimelineSlice=tje(()=>o)}async getSlice(t){const o=await this._selectTimelineSlice({timeStart:t.timeStart,timeEnd:t.timeEnd,canvasSize:t.canvasSize,mediaStore:this._store});return uje(o)}}const Ic={video:"-video",audio:"-audio",caption:"-caption",silentCharacter:"-silent",speakingCharacter:"-speaking"},pje=[Ic.video,Ic.audio,Ic.caption],Di=(e,t)=>t?.isVideo?""+e+Ic.video:t?.isAudio?""+e+Ic.audio:t?.isCaption?""+e+Ic.caption:t?.isSilentCharacter?""+e+Ic.silentCharacter:t?.isSpeakingCharacter?""+e+Ic.speakingCharacter:e,fje=e=>"orig-"+e,gje=e=>"trans-"+e,_je=e=>{const t=e;for(const o of pje)if(t.endsWith(o))return t.slice(0,-o.length);return t},zCt=(e,t,o)=>{const r=_je(e),n=L.get(t,r);
3642if(n){const a=n.trackIds.find(i=>{const s=L.get(o,i);return s&&xr(s)});if(a)return a}return r},Eje=({effectId:e,filterMediaId:t,alpha:o})=>({type:"Filter",__bound:"model",effectId:e,alpha:o,filterInfoId:t}),mje=({effectId:e,color:t,timelineStart:o,timelineEnd:r})=>({type:"Background",__bound:"global",effectId:e,color:t,timelineStart:o instanceof X?o:X.fromSec(o),timelineEnd:r instanceof X?r:X.fromSec(r)}),hje=({effectId:e,blendType:t,timelineStart:o,timelineEnd:r,targetTimeline:n})=>({type:"Blend",__bound:"global",effectId:e,blendType:t,timelineEnd:r,timelineStart:o,targetTimeline:n}),Ije=(e,t,o,r)=>{const n={[Me.BLINK_ONCE]:xo.BLINK_ONCE,[Me.FADE_IN]:xo.FADE_IN,[Me.FADE_IN_DOWN]:xo.FADE_IN_DOWN,[Me.FADE_IN_UP]:xo.FADE_IN_UP,[Me.FADE_IN_LEFT]:xo.FADE_IN_LEFT,[Me.FADE_IN_RIGHT]:xo.FADE_IN_RIGHT,[Me.RUBBER_BAND_ONCE]:xo.RUBBER_BAND_ONCE,[Me.TADA_ONCE]:xo.TADA_ONCE,[Me.SHAKE_X_ONCE]:xo.SHAKE_X_ONCE,[Me.SHAKE_Y_ONCE]:xo.SHAKE_Y_ONCE,[Me.SWING_ONCE]:xo.SWING_ONCE,[Me.HEART_BEAT_ONCE]:xo.HEART_BEAT_ONCE,[Me.POP_IN_ONCE]:xo.POP_IN_ONCE,[Me.FLIP_ONCE]:xo.FLIP_ONCE,[Me.FLIP_IN_X]:xo.FLIP_IN_X,[Me.FLIP_IN_Y]:xo.FLIP_IN_Y,[Me.SLIDE_IN_RIGHT]:xo.SLIDE_IN_RIGHT,[Me.SLIDE_IN_LEFT]:xo.SLIDE_IN_LEFT,[Me.ROTATE_IN]:xo.ROTATE_IN,[Me.ROTATE_IN_DOWN_LEFT]:xo.ROTATE_IN_DOWN_LEFT,[Me.ROTATE_IN_DOWN_RIGHT]:xo.ROTATE_IN_DOWN_RIGHT,[Me.ROLL_IN]:xo.ROLL_IN,[Me.FOCUS_IN]:xo.FOCUS_IN,[Me.FOCUS_IN_DOWN]:xo.FOCUS_IN_DOWN,[Me.FOCUS_IN_LEFT]:xo.FOCUS_IN_LEFT,[Me.FOCUS_IN_RIGHT]:xo.FOCUS_IN_RIGHT,[Me.FOCUS_IN_UP]:xo.FOCUS_IN_UP,[Me.POPPING_IN]:xo.POPPING_IN,[Me.POPPING_IN_DOWN]:xo.POPPING_IN_DOWN,[Me.POPPING_IN_LEFT]:xo.POPPING_IN_LEFT,[Me.POPPING_IN_RIGHT]:xo.POPPING_IN_RIGHT,[Me.POPPING_IN_UP]:xo.POPPING_IN_UP,[Me.POPPING_ONCE]:xo.POPPING_ONCE,[Me.MOVING_IN_UP]:xo.MOVING_IN_UP,[Me.MOVING_IN_DOWN]:xo.MOVING_IN_DOWN,[Me.MOVING_IN_LEFT]:xo.MOVING_IN_LEFT,[Me.MOVING_IN_RIGHT]:xo.MOVING_IN_RIGHT,[Qe.FADE_OUT]:$o.FADE_OUT,[Qe.FADE_OUT_DOWN]:$o.FADE_OUT_DOWN,[Qe.FADE_OUT_UP]:$o.FADE_OUT_UP,[Qe.FADE_OUT_LEFT]:$o.FADE_OUT_LEFT,[Qe.FADE_OUT_RIGHT]:$o.FADE_OUT_RIGHT,[Qe.FLIP_OUT_X]:$o.FLIP_OUT_X,[Qe.FLIP_OUT_Y]:$o.FLIP_OUT_Y,[Qe.SLIDE_OUT_RIGHT]:$o.SLIDE_OUT_RIGHT,[Qe.SLIDE_OUT_LEFT]:$o.SLIDE_OUT_LEFT,[Qe.ROTATE_OUT]:$o.ROTATE_OUT,[Qe.ROTATE_OUT_DOWN_LEFT]:$o.ROTATE_OUT_DOWN_LEFT,[Qe.ROTATE_OUT_DOWN_RIGHT]:$o.ROTATE_OUT_DOWN_RIGHT,[Qe.ROLL_OUT]:$o.ROLL_OUT,[Qe.FOCUS_OUT]:$o.FOCUS_OUT,[Qe.FOCUS_OUT_DOWN]:$o.FOCUS_OUT_DOWN,[Qe.FOCUS_OUT_LEFT]:$o.FOCUS_OUT_LEFT,[Qe.FOCUS_OUT_RIGHT]:$o.FOCUS_OUT_RIGHT,[Qe.FOCUS_OUT_UP]:$o.FOCUS_OUT_UP,[Qe.POPPING_OUT]:$o.POPPING_OUT,[Qe.POPPING_OUT_DOWN]:$o.POPPING_OUT_DOWN,[Qe.POPPING_OUT_LEFT]:$o.POPPING_OUT_LEFT,[Qe.POPPING_OUT_RIGHT]:$o.POPPING_OUT_RIGHT,[Qe.POPPING_OUT_UP]:$o.POPPING_OUT_UP,[Qe.MOVING_OUT_UP]:$o.MOVING_OUT_UP,[Qe.MOVING_OUT_DOWN]:$o.MOVING_OUT_DOWN,[Qe.MOVING_OUT_LEFT]:$o.MOVING_OUT_LEFT,[Qe.MOVING_OUT_RIGHT]:$o.MOVING_OUT_RIGHT,[rI.FADE_IN_OUT]:VU.FADE_IN_OUT,[hr.BLINK]:Js.BLINK,[hr.TADA]:Js.TADA,[hr.SHAKE_X]:Js.SHAKE_X,[hr.SHAKE_Y]:Js.SHAKE_Y,[hr.SWING]:Js.SWING,[hr.HEART_BEAT]:Js.HEART_BEAT,[hr.POP_IN]:Js.POP_IN,[hr.RUBBER_BAND]:Js.RUBBER_BAND,[hr.FLIP]:Js.FLIP,[hr.POPPING]:Js.POPPING,[Mc.TYPING]:Qn.TYPING,[Mc.TYPING_UP]:Qn.TYPING_UP,[Mc.TYPING_DOWN]:Qn.TYPING_DOWN};return{type:"Animation",__bound:"model",effectId:e,duration:t,variant:n[o],startDelay:r}},Tje=(e,t,o,r)=>({type:"Kenburns",__bound:"model",effectId:e,variant:t,from:{scale:o.scale,centerX:o.centerX,centerY:o.centerY},to:{scale:r.scale,centerX:r.centerX,centerY:r.centerY}}),UP=(e,t)=>{const o=X.fromSec(vo(e)),r=Sje(e,t);return[o,r]},Sje=(e,t)=>{const o=vo(e);if(t){const r=vo(t);return X.fromSec(r-o)}return X.fromSec(Df(e))},X2=e=>e.globalClips,Oje=(e,t)=>{const o=n8(e);return t.assetIds.reduce((r,n)=>{const a=L.get(o,n);return a&&(r[n]=a),r},{})},Cje=(e,t)=>{const o=n8(e);return t.assetIds.reduce((r,n)=>{const a=L.get(o,n);return a&&(r[n]=a),r},{})},r8=Te(e=>e,e=>X2(e).reduce((t,o)=>{const r=Cje(e,o),n=i8(o).reduce((a,i)=>{const s=Oje(e,i);return Object.assign(a,s),a},{});return Object.assign(t,r,n),t},{})),n8=Te(e=>e.trackEntries,e=>e.assetEntries,(e,t)=>{const o={};for(const[r,n]of Object.entries(t)){if(n.role==="main")continue;const a=n.trackIds.at(0);if(!a)continue;const i=L.get(e,a);!i||!Wa(i)||(o[r]=i)}return o}
3642),Rje=(e,t)=>{const o=m2(e),r=h2(e),n=Aje(e),a=yje(t,o,r);if(!a)return null;const{overdubId:i,overdubTrack:s}=a;if(!n[i]||!s)return null;const c=eo(s.mediaId);if(!c)return null;const l=X.fromSec(c.videoAudioMetaInfo.duration),d=X.fromSec(sr(t)),u=l.as.us()/d.as.us();return{mediaId:s.mediaId,playbackRate:u,audioDuration:l}},Aje=e=>e.overdubInfosMap,yje=(e,t,o)=>{for(const r of e.assetIds){const n=o[r];if(!(!n||n.role!=="main"))for(const a of n.trackIds){const i=L.get(t,a);if(i&&i.type===ze.Overdub)return{overdubId:i.overdubId,overdubTrack:i}}}},vje=e=>e.globalVideoTransform;function wje(e,t){const o=[];e.filter(({start:i,end:s})=>i<s).forEach(({start:i,end:s})=>{o.push({time:i,type:"tts_start"}),o.push({time:s,type:"tts_end"})}),t.forEach(({id:i,start:s,end:x})=>{o.push({time:s,type:"word_start",wordId:i}),o.push({time:x,type:"word_end",wordId:i})}),o.sort((i,s)=>{if(i.time!==s.time)return i.time-s.time;const x={word_end:0,tts_end:1,tts_start:2,word_start:3};return x[i.type]-x[s.type]});const r=new Map,n=new Set;let a=0;return o.forEach(i=>{switch(i.type){case"tts_start":a++,n.forEach(s=>{r.set(s,!0)});break;case"tts_end":a--;break;case"word_start":n.add(i.wordId),a>0&&r.set(i.wordId,!0);break;case"word_end":n.delete(i.wordId),!r.has(i.wordId)&&r.set(i.wordId,!1);break}}),r}const a8=e=>e.globalClips.flatMap(t=>i8(t)),i8=e=>e.words,Nje=Te(e=>e,e=>{const t=r8(e),o=Object.entries(t).filter(([,a])=>a.type===ze.TTSDubbing||a.type===ze.TTSEffect).map(([a])=>{const i=cS(e,Je(a));if(!i)return null;const[s,x]=i;return{start:s.as.us(),end:s.add(x).as.us()}}).filter(ri),r=a8(e),n=r.map(a=>{const i=X.fromSec(a.timelineStart),s=X.fromSec(Rn(a)),x=i.add(s);return{id:a.id,start:i.as.us(),end:x.as.us()}});return wje(o,n)}),Pje=(e,t,o)=>{const r=Nje(e);return s8(e).filter(({word:n})=>{const a=X.fromSec(n.timelineStart),i=X.fromSec(Rn(n));return X.doOverlap(t,o,a,a.add(i).roundTo(4))}).reduce((n,{word:a})=>{const i=n.at(-1),s=i?.timelineStart.add(i?.timelineDuration??X.zero())??X.fromSec(a.timelineStart),x=X.fromSec(Rn(a)),c=bje(a,r);return!i||i.isAudible!==c?(n.push({timelineStart:s,timelineDuration:x,isAudible:c}),n):(i.timelineStart.add(i.timelineDuration).eq(s,1)?n[n.length-1]={...i,timelineDuration:i.timelineDuration.add(x)}:n.push({timelineStart:s,timelineDuration:x,isAudible:c}),n)},[])},bje=(e,t)=>e.type===Z.NORMAL?!0:t.get(e.id)??!1,Lje=e=>s8(e).reduce((t,{word:o,videoTransform:r})=>{const n=t.at(-1),a=n?n.timelineStart.add(n.timelineDuration):X.zero(),i=Rje(e,o),s=X.fromSec(Rn(o)),x=Q0(o)?Sy:o.playbackRate,c=m2(e),l=h2(e),d=Sv(o,c,l),u=d?{mediaId:d.mediaId,sourceIn:X.fromSec(d.sourceIn),filterEffect:d.filterEffect,flip:Im(d.editInfo)}:void 0,p=oi(o,c,l),f=p?{mediaId:p.mediaId,sourceIn:i?X.zero():X.fromSec(p.sourceIn),volume:ur(p.volume??ma)}:void 0;return t.push({wordId:o.id,timelineStart:a,timelineDuration:s,playbackRate:(i?.playbackRate??Un)*x,video:u,audio:f,videoTransform:r}),t},[]),s8=e=>{const t=vje(e);return X2(e).map(o=>({words:o.words.filter(r=>Rn(r)>0),videoTransform:o.videoTransform??t})).reduce((o,{words:r,videoTransform:n})=>{for(const a of r)o.push({word:a,videoTransform:n});return o},[])},cS=(e,t)=>{const o=L.get(e.assetTimelineRanges,t);if(o)return[X.fromSec(o.timelineStart),X.fromSec(o.timelineEnd-o.timelineStart)];const r=L.get(e.soundEffectTimelineRanges,t);if(r)return[X.fromSec(r.timelineStart),X.fromSec(r.timelineEnd-r.timelineStart)];const n=LW(e),a=L.get(n,t);return a?[X.fromSec(a.timelineStart),X.fromSec(a.timelineEnd-a.timelineStart)]:(h("selector.asset.ts").error("Asset timeline not found for "+t),null)},Mje=(e,t)=>{const o=kje(e),{trackEntries:r,assetEntries:n}=e,a=[];for(const i of o){const s=L.get(n,i);if(!s){h("selector.asset.ts").error("Asset entry not found for "+i);continue}if(s.role!==t)continue;const x=s.trackIds.flatMap(l=>{const d=L.get(r,l);return d?[d]:[]});if(x.length===0){h("selector.asset.ts").error("No tracks found for asset "+i);continue}const c=Dje(x);c&&a.push({id:i,asset:c})}return a},Dje=e=>{if(e.length===1){const n=e[0];return!xr(n)||Rr(n)?null:n}const t=e.find(mn);if(!t)return null;const o=e.find(U0);return{...t,audio:o}},kje=e=>{const t=X2(e),o=a8(e);return new Set(t.flatMap(r=>r.assetIds).concat(o.flatMap(r=>r.assetIds)))},Fje=e=>{const t=X2(e),o=Uje(e),r=new Map;for(let n=0;n<t.length;n++){const a=t[n];if(!a.backgroundId)continue;const i=L.get(o,a.backgroundId);if(!i)continue;const s=t.at(n+1),[x,c]=UP(a,s),l=r.get(a.backgroundId)??r.set(a.backgroundId,{backgroundId:a.backgroundId,background:i,timelines:[]}).get(a.backgroundId),d=l.timelines.at(-1);d&&d.timelineStart.add(d.timelineDuration).eq(x,1)?d.timelineDuration=d.timelineDuration.add(c):l.timelines.push({timelineStart:x,timelineDuration:c})}return r},Uje=e=>e.backgroundMap,J2=e=>e.videoRatio,Vje=e=>e.projectAudioLanguage,Gje=e=>
3642{const t=X2(e),o=Vje(e),r=jje(e),n=Wje(e),a=Hje(e);return!n&&!a?[]:t.map(i=>{const s=n?Dm(i,Ke.ORIGINAL,o,r):void 0,x=a?Dm(i,Ke.TRANSLATE,o,r):void 0;return{clipId:i.clipId,original:s,translated:x}})},x8=e=>e.captionDisplayMode,Wje=e=>x8(e)[Ke.ORIGINAL],Hje=e=>x8(e)[Ke.TRANSLATE],jje=e=>e.globalCaptionStyle,zje=e=>X2(e).map(o=>{const r=Yje(o);if(!r||r.type===Re.NONE)return null;const[n]=UP(o),a=n.add(X.fromSec(r.timelineStartOffset)),i=a.add(X.fromSec(r.duration));return{transitionId:r.id,transitionType:r.type,timelineStart:a,timelineEnd:i}}).filter(yy),Yje=e=>e.transitionModel,c8=e=>Rxe(e)??null,Bje=e=>{const t=Kje(e),o=Xje(e);return[...t,...o]},Kje=e=>{const t=Fje(e);return Array.from(t.values()).flatMap(({backgroundId:o,background:r,timelines:n})=>{if(r.type!==k0.SOLID)throw new C(_.C_LOGIC_ERROR,void 0,"Unsupported background type: "+r.type);return n.map((a,i)=>mje({effectId:o+"-"+i,color:r.color,timelineStart:a.timelineStart,timelineEnd:a.timelineStart.add(a.timelineDuration)}))})},Xje=e=>zje(e).map(({transitionId:o,transitionType:r,timelineStart:n,timelineEnd:a})=>hje({effectId:o,blendType:Jje(r),timelineStart:n,timelineEnd:a,targetTimeline:a})),Jje=e=>{switch(e){case Re.NONE:return Ze.NONE;case Re.CROSS_FADE:return Ze.CROSS_FADE;case Re.LINEAR_BLUR:return Ze.LINEAR_BLUR;case Re.DIRECTIONAL_WARP:return Ze.DIRECTIONAL_WARP;case Re.GLITCH_MEMORIES:return Ze.GLITCH_MEMORIES;case Re.PIXELIZE:return Ze.PIXELIZE;case Re.WIND:return Ze.WIND;case Re.VERTICAL_WIPE:return Ze.VERTICAL_WIPE;case Re.SIMPLE_ZOOM:return Ze.SIMPLE_ZOOM;case Re.WIPE_LEFT:return Ze.WIPE_LEFT;case Re.WIPE_RIGHT:return Ze.WIPE_RIGHT;case Re.WIPE_UP:return Ze.WIPE_UP;case Re.WIPE_DOWN:return Ze.WIPE_DOWN;case Re.IRIS:return Ze.IRIS;case Re.DREAMY:return Ze.DREAMY;case Re.RADIAL:return Ze.RADIAL;case Re.WINDOW_BLIND:return Ze.WINDOW_BLIND;case Re.CIRCLE_OPEN:return Ze.CIRCLE_OPEN;case Re.DIRECTIONAL_WIPE:return Ze.DIRECTIONAL_WIPE;case Re.MORPH:return Ze.MORPH;case Re.BLACK_FADE_OUT:return Ze.BLACK_FADE_OUT;case Re.WHITE_FADE_OUT:return Ze.WHITE_FADE_OUT;case Re.COLOR_DISTANCE:return Ze.COLOR_DISTANCE;case Re.GRAY_SCALE_FADE:return Ze.GRAY_SCALE_FADE}},qje=e=>({projectRatio:J2(e)}),Qje=(e,t)=>{switch(e.fileLocation){case D.LOCAL:case D.LOCAL_TMP:return{kind:"uri",uri:an(e.path)};case D.PACKAGED:return{kind:"uri",uri:e.path};case D.REMOTE:return{kind:"uri",uri:t??e.url};case D.IN_MEMORY:{const o=s_(e.mediaId);if(o)return{kind:"uri",uri:o};break}}throw new C(_.C_MEDIA_BLOB_LOST,{},"[resolveMediaSourceFromFileInfo] Source not found. mediaId : "+JSON.stringify(e))},Zje=(e,t,o,r)=>({type:"AVMedia",source:e,infoId:t,hasVideoTrack:o,hasAudioTrack:r}),$je=(e,t)=>({type:"Image",source:e,infoId:t}),e7e=(e,t)=>({type:"Textbox",infoId:t,source:e}),t7e=(e,t)=>({type:"Shape",source:e,infoId:t}),l8=(e,t)=>u8(e,o7e(e,t)),d8=(e,t)=>u8(e,t),u8=(e,t)=>{switch(e.type){case"AVMedia":{const o=e.videoAudioMetaInfo.videoInfo!==void 0,r=e.videoAudioMetaInfo.audioInfo!==void 0,n=CE(e);return Zje(t,n,o,r)}case"Image":{const o=CE(e);return $je(t,o)}case"Svg":{const o=CE(e);return t7e(t,o)}case"Html":{const o=CE(e);return e7e(t,o)}}},CE=e=>e.mediaId,o7e=(e,t)=>{try{return Qje(e,t)}catch(o){throw h("info.adapter.ts").error("[getMediaSource] Failed to resolve media source for "+e.mediaId+": "+P(o)),Ne(o)?o:new C(_.C_EXPORT_PREPARE_ERROR,{},"[getMediaSource] Failed to resolve media source: "+e.mediaId)}};var eg=(e=>(e[e.BACKGROUND=-2]="BACKGROUND",e[e.SOURCE=-1]="SOURCE",e[e.CAPTION=Number.MAX_SAFE_INTEGER-1]="CAPTION",e[e.OVERLAY=Number.MAX_SAFE_INTEGER]="OVERLAY",e))(eg||{});const q2=e=>e.mediaId,p8=(e,t)=>{switch(t){case"silent":return e.pose.silentMediaId;case"speaking":return e.pose.speakingMediaId}},Q2=e=>f0(e)&&Qx(e)?{x:e.xPos,y:e.yPos,zIndex:e.zIndex,adjustment:{x:0,y:-.5}}:{x:e.xPos,y:e.yPos,zIndex:Rr(e)?eg.OVERLAY:e.zIndex},Z2=(e,t)=>f0(e)&&Qx(e)?e.hasHead?{width:Math.max(e.width,4*Math.sqrt(2)*e.height/t),height:8*e.stroke.width*t}:{width:e.width,height:e.stroke.width*t}:{width:e.width,height:e.height},$2=e=>{const t=r7e(e),o=n7e(e);return f0(e)&&Qx(e)?{rotation:e.rotation,transformOrigin:{x:0,y:.5},opacity:t}:{rotation:e.rotation,opacity:t,flipH:o?.flipH,flipV:o?.flipV}}
3642,ep=e=>{if(!(J0(e)||Gn(e))||e.editInfo?.crop===void 0)return;const{top:t,left:o,right:r,bottom:n}=pg(e.editInfo?.crop);return{x:o,y:t,width:1-o-r,height:1-t-n}},r7e=e=>{if(!(!J0(e)&&!Gn(e)))return e.editInfo?.opacity},n7e=e=>{if(!(J0(e)||Gn(e)))return;const t=e.editInfo?.flip?.horizontal===!0,o=e.editInfo?.flip?.vertical===!0;if(!(!t&&!o))return{flipH:t,flipV:o}},VP=(e,t,o)=>{if(!e.assetEffectInfo)return null;const r="animation-"+o,n=ax(e.assetEffectInfo)?e.assetEffectInfo.startDelay:wh,a=X.min(t,X.fromMS(n)),i=a7e(t,e.assetEffectInfo,a);return Ije(r,i,e.assetEffectInfo.type,a)},a7e=(e,t,o)=>{const r=X.max(X.zero(),e.sub(o)),n=X.fromMS(t.duration*(Jr(t.type)?2:1));return X.min(r,n)},i7e=(e,t)=>e.kenburnsAnimationInfo===void 0?null:Tje("kenburns-"+t,e.kenburnsAnimationInfo.type,{scale:e.kenburnsAnimationInfo.from.scale,centerX:e.kenburnsAnimationInfo.from.centerX,centerY:e.kenburnsAnimationInfo.from.centerY},{scale:e.kenburnsAnimationInfo.to.scale,centerX:e.kenburnsAnimationInfo.to.centerX,centerY:e.kenburnsAnimationInfo.to.centerY}),h_=(e,t)=>!e.filterEffect||Xp(e.filterEffect.filterMediaId)?null:Eje({effectId:"filter-"+t,filterMediaId:e.filterEffect.filterMediaId,alpha:e.filterEffect.alpha}),lS=e=>({type:"Video",infoId:e.infoId,modelId:e.modelId,effectIds:e.effectIds,position:e.position,timeline:{start:e.timelineStart,duration:e.timelineDuration},src:{in:e.sourceIn,playbackRate:e.playbackRate,loop:e.loop},crop:e.crop,size:e.size,transform:e.transform}),GP=e=>({type:"Audio",infoId:e.infoId,modelId:e.modelId,effectIds:e.effectIds,timeline:{start:e.timelineStart,duration:e.timelineDuration},src:{in:e.sourceIn,playbackRate:e.playbackRate,loop:e.loop},volume:e.volume,fadeIn:e.fadeIn,fadeOut:e.fadeOut}),WP=e=>({type:"Image",infoId:e.infoId,modelId:e.modelId,effectIds:e.effectIds,position:e.position,size:e.size,timeline:{start:e.timelineStart,duration:e.timelineDuration},crop:e.crop,transform:e.transform}),s7e=e=>({type:"Textbox",infoId:e.infoId,modelId:e.modelId,effectIds:e.effectIds,position:e.position,size:e.size,timeline:{start:e.timelineStart,duration:e.timelineDuration},transform:e.transform,loop:e.loop,duration:e.duration,scaleFactor:e.scaleFactor,deltas:e.deltas,attributes:e.attributes,crop:e.crop}),x7e=e=>({type:"Caption",modelId:e.modelId,position:e.position,timeline:{start:e.timelineStart,duration:e.timelineDuration},yAlign:e.yAlign,original:e.original,translated:e.translated}),c7e=e=>({type:"Shape",infoId:e.infoId,modelId:e.modelId,effectIds:e.effectIds,position:e.position,size:e.size,timeline:{start:e.timelineStart,duration:e.timelineDuration},transform:e.transform,variant:"1d",stroke:{color:e.color,width:e.width,isRounded:e.isRounded,isDashed:e.isDashed},head:e.head,crop:e.crop}),l7e=e=>({type:"Shape",infoId:e.infoId,modelId:e.modelId,effectIds:e.effectIds,position:e.position,size:e.size,timeline:{start:e.timelineStart,duration:e.timelineDuration},transform:e.transform,variant:"2d",shapeType:e.shapeType,stroke:{color:e.color,width:e.width,isRounded:e.isRounded,isDashed:e.isDashed},plane:e.plane,cornerRounding:e.cornerRounding,crop:e.crop}),d7e=e=>({type:"Character",modelId:e.modelId,timeline:{start:e.timelineStart,duration:e.timelineDuration},timelines:e.timelines,silentAsset:e.silentAsset,speakingAsset:e.speakingAsset,position:e.position}),u7e=(e,t,o,r,n)=>{const a=q2(e),i=n.get(e.mediaId),s=i?.type==="AVMedia"?i:void 0;if(!s)return h("model.adapter.audio.ts").error("Audio Info "+a+" not found, asset: "+JSON.stringify(e)),[[],[]];const x=X.max(X.zero(),X.fromSec(e.sourceIn)),c=p7e(s,e),l=e.loop?o.add(r):X.min(o.add(r),c.sub(x).add(o)),d=l.sub(o),u=e.fade?.in?dF(d):X.zero(),p=e.fade?.out?dF(d):X.zero();return[[GP({infoId:a,modelId:Di(t,{isAudio:!0}),effectIds:[],timelineStart:o,timelineDuration:d,playbackRate:1,...e.loop?{loop:{in:x,out:c}}:{},volume:e.volume,sourceIn:x,fadeIn:o.add(u),fadeOut:l.sub(p)})],[]]},p7e=(e,t)=>{const o=X.fromSec(e.videoAudioMetaInfo.duration),r=X.max(X.zero(),X.fromSec(t.sourceOut));return X.min(r,o)},dF=e=>{const t=e.as.sec();return t<1?X.zero():t<6?X.fromSec(.5):X.fromSec(2)},f7e=(e,t,o,r)=>{const n=Di(t),a=Q2(e),i=Z2(e,o.projectRatio),s=$2(e),x=ep(e);return[d7e({modelId:n,timelineStart:o.timelineStart,timelineDuration:o.timelineDuration,silentAsset:g7e(e,o,n,a,i,s,x),speakingAsset:_7e(e,o,n,a,i,s,x),timelines:r,position:a}),[]]},g7e=(e,t,o,r,n,a,i)=>{const s=p8(e,"silent"),x=t.fileInfoByMediaId.get(s);if(x?.type==="AVMedia"){const{videoAudioMetaInfo:c}=x;return lS({infoId:s,modelId:Di(o,{isSilentCharacter:!0}),effectIds:[],timelineStart:t.timelineStart,timelineDuration:t.timelineDuration,loop:{in:X.zero(),out:X.max(X.zero(),X.fromSec(c.duration))},playbackRate:1,sourceIn:X.zero(),position:r,size:n,transform:a,crop:i})}return WP({infoId:s,modelId:Di(o,{isSilentCharacter:!0}),effectIds:[],timelineStart:t.timelineStart,timelineDuration:t.timelineDuration,position:r,size:n,transform:a,crop:i})},_7e=(e,t,o,r,n,a,i)=>{const s=p8(e,"speaking");if(!e.isMouthApplied)return;const x=t.fileInfoByMediaId.get(s),c=x?.type==="AVMedia"?x.videoAudioMetaInfo:void 0;if(c)return lS({infoId:s,modelId:Di(o,{isSpeakingCharacter:!0}),effectIds:[],timelineStart:t.timelineStart,timelineDuration:t.timelineDuration,loop:{in:X.zero(),out:X.max(X.zero(),X.fromSec(c.duration))},playbackRate:1,sourceIn:X.zero(),position:r,size:n,transform:a,crop:i})},E7e=(e,t,o)=>{const r=q2(e),n=Di(t),a=Q2(e),i=Z2(e,o.projectRatio),s=$2(e),x=ep(e),c=VP(e,o.timelineDuration,n),l=i7e(e,n),d=h_(e,n),u=[c,l,d].filter(E=>!!E),p=u.map(E=>
3642E.effectId);return[WP({infoId:r,modelId:n,effectIds:p,timelineStart:o.timelineStart,timelineDuration:o.timelineDuration,position:a,size:i,transform:s,crop:x}),u]},m7e=(e,t,o)=>{const r=q2(e),n=Di(t),a=Q2(e),i=Z2(e,o.projectRatio),s=$2(e),x=ep(e),c=VP(e,o.timelineDuration,n),l=h_(e,n),d=[c,l].filter(p=>!!p);return[e.dimensionType===Tr.ONE?c7e({infoId:r,modelId:n,effectIds:d.map(p=>p.effectId),timelineStart:o.timelineStart,timelineDuration:o.timelineDuration,color:e.stroke.color,width:e.stroke.width,isRounded:e.stroke.isRounded,isDashed:e.stroke.isDashed,head:e.shapeOfHead,position:a,size:i,transform:s,crop:x}):l7e({infoId:r,modelId:n,effectIds:d.map(p=>p.effectId),timelineStart:o.timelineStart,timelineDuration:o.timelineDuration,shapeType:e.shapeType===od.DEFAULT?"default":e.shapeType===od.HEADED?"headed":"tailed",color:e.stroke.color,width:e.stroke.width,isRounded:e.stroke.isRounded,isDashed:e.stroke.isDashed,plane:e.plane,cornerRounding:e.cornerRounding,position:a,size:i,transform:s,crop:x}),d]},h7e=(e,t,o)=>{const r=q2(e),n=Q2(e),a=Z2(e,o.projectRatio),i=$2(e),s=ep(e),x=e.endBehavior===Fs.FREEZE,c=Di(t,{isVideo:!0}),l=h_(e,c),d=o.fileInfoByMediaId.get(e.mediaId),u=d?.type==="AVMedia"?d:void 0,p=pe(u?.videoAudioMetaInfo.duration??e.sourceOut),f=lS({infoId:r,modelId:c,effectIds:l?[l.effectId]:[],timelineStart:o.timelineStart,timelineDuration:o.timelineDuration,playbackRate:1,sourceIn:X.max(X.zero(),X.fromSec(e.sourceIn)),loop:x?void 0:vL(p),position:n,size:a,transform:i,crop:s});if(!u?.videoAudioMetaInfo.audioInfo)return[[f],l?[l]:[]];const E=GP({infoId:r,modelId:Di(t,{isAudio:!0}),effectIds:[],timelineStart:o.timelineStart,timelineDuration:o.timelineDuration,playbackRate:1,loop:x?void 0:vL(p),volume:X9e(e),sourceIn:X.max(X.zero(),X.fromSec(e.sourceIn)),fadeIn:o.timelineStart,fadeOut:o.timelineStart.add(o.timelineDuration)});return[[f,E],l?[l]:[]]},I7e=(e,t)=>{const o=cS(e,t);if(!o)return[];const[r,n]=o;return Pje(e,r,r.add(n))},f8=(e,t,o)=>{const r=q2(e),n=Di(t),a=Q2(e),i=Z2(e,o.projectRatio),s=$2(e),x=ep(e),c=VP(e,o.timelineDuration,n),l=h_(e,n),d=[c,l].filter(f=>!!f),u=d.map(f=>f.effectId);return[s7e({infoId:r,modelId:n,effectIds:u,timelineStart:o.timelineStart,timelineDuration:o.timelineDuration,duration:X.fromSec(e.durationSeconds),scaleFactor:e.scaleFactor,loop:e.loop,deltas:e.deltas,attributes:e.customAttributes,position:a,size:{width:i.width,height:"auto"},transform:s,crop:x}),d]},T7e=({clipId:e,original:t,translated:o},r,n)=>{const a=t??o;if(!a)return null;const i={projectRatio:n,timelineStart:r[0],timelineDuration:r[1]},s=t&&o&&t.yAlign!==oo.CUSTOM&&o.yAlign!==oo.CUSTOM&&t.yAlign===o.yAlign?t.yAlign:oo.CUSTOM;return S7e(t??null,o??null,e,a.webModel.xPos,a.webModel.yPos,s,i)},uF=(e,t,o,r)=>{const[n,a]=f8(e,Je(t),r),i=g8(e.xPos,e.yPos,o);return[{...n,position:i},a]},S7e=(e,t,o,r,n,a,i)=>{const[s,x]=e?uF(e.webModel,fje(o),e.yAlign,i):[null,[]],[c,l]=t?uF(t.webModel,gje(o),t.yAlign,i):[null,[]],d=x.concat(l);return[x7e({modelId:Di(o,{isCaption:!0}),original:s,translated:c,timelineStart:i.timelineStart,timelineDuration:i.timelineDuration,yAlign:a,position:g8(r,n,a)}),d]},g8=(e,t,o)=>{if(o===oo.CUSTOM)return{x:e,y:t,zIndex:eg.CAPTION};const r={[oo.TOP]:.1,[oo.MIDDLE]:.5,[oo.BOTTOM]:.97},n={[oo.TOP]:0,[oo.MIDDLE]:-.5,[oo.BOTTOM]:-1};return{x:.5+e,y:r[o]+t,adjustment:{x:-.5,y:n[o]},zIndex:eg.CAPTION}},O7e=["assets","audios","captions","sources","watermarks"],HP=()=>({assets:new Set,audios:new Set,captions:new Set,sources:new Set,watermarks:new Set}),C7e=HP();let FA=HP();const _8=(e,t)=>Array.isArray(e)&&Array.isArray(t)?R7e(e,t):typeof e=="function"&&typeof t=="function"?!0:e===t,R7e=(e,t)=>e.length===t.length&&e.every((o,r)=>_8(o,t[r])),A7e=KU({memoize:xR,memoizeOptions:{equalityCheck:_8,maxSize:1}}),y7e=()=>jn(e=>e.dependencies,e=>e.convert,(e,t)=>t())({keySelector:e=>e.key,selectorCreator:A7e}),Ap=e=>{const t=y7e(),o=r=>(FA[e].add(r.key),t(r));return Object.defineProperty(o,"cache",{value:t.cache}),o},tp={assets:Ap("assets"),audios:Ap("audios"),captions:Ap("captions"),sources:Ap("sources"),watermarks:Ap("watermarks")},pF=e=>{e&&v7e(FA),FA=HP()}
3642,v7e=e=>{O7e.forEach(t=>{const o=C7e[t];o.forEach(r=>{e[t].has(r)||(tp[t].cache.remove(r),o.delete(r))}),e[t].forEach(r=>o.add(r))})},w7e=(e,t,o,r)=>[e,t,o.captionDisplayMode,o.globalCaptionStyle,o.projectAudioLanguage,r],N7e=(e,t,o,r,n)=>{const a=[o.type,r.projectRatio,Y0(r.timelineStart),Y0(r.timelineDuration),...V7e(e,t)];switch(o.type){case z.SIMPLE_CHARACTER:return[...a,AC(r,o.pose.silentMediaId),o.pose.speakingMediaId!==void 0?AC(r,o.pose.speakingMediaId):void 0,M7e(n)];case z.VIDEO:return[...a,o.audio,AC(r,o.mediaId)];case z.IMAGE:case z.SHAPE:case z.WEB:return a;case z.LOTTIE:throw new Error("Lottie asset is not implemented")}},P7e=(e,t,o)=>[...gh(e,U7e),t,e.video?o.get(e.video.mediaId):void 0],b7e=(e,t)=>[e,t],L7e=(e,t,o,r)=>[e,Y0(t),Y0(o),r.get(e.mediaId)],M7e=e=>e.map(t=>gh(t,D7e)),gh=(e,t)=>Object.values(t).map(o=>o(e)),D7e={timelineStart:e=>Y0(e.timelineStart),timelineDuration:e=>Y0(e.timelineDuration),isAudible:e=>e.isAudible},k7e={mediaId:e=>e.mediaId,sourceIn:e=>Y0(e.sourceIn),filterEffect:e=>e.filterEffect,flip:e=>e.flip},F7e={mediaId:e=>e.mediaId,sourceIn:e=>Y0(e.sourceIn),volume:e=>e.volume},U7e={wordId:e=>e.wordId,timelineStart:e=>Y0(e.timelineStart),timelineDuration:e=>Y0(e.timelineDuration),playbackRate:e=>e.playbackRate,video:e=>e.video?gh(e.video,k7e):void 0,audio:e=>e.audio?gh(e.audio,F7e):void 0,videoTransform:e=>e.videoTransform},V7e=(e,t)=>{const o=e.assetEntries[t];return o?o.trackIds.map(r=>e.trackEntries[r]):[]},AC=(e,t)=>e.fileInfoByMediaId.get(t),Y0=e=>e.as.us(),G7e=(e,t,o,r)=>{const n=I0(e),a=n.width/n.height,{wRatio:i,hRatio:s}=W7e(t,a);return{size:H7e(i,s,o?.zoom??1,o?.zoom??1),position:j7e(o?.xPos??0,o?.yPos??0,i,s),transform:z7e(o,r)}},W7e=(e,t)=>{if(Math.abs(e-t)<1e-6)return{wRatio:1,hRatio:1};if(e>t)return{wRatio:t/e,hRatio:1};const o=1,r=e/t;return{wRatio:o,hRatio:r}},H7e=(e,t,o,r)=>({width:e*o,height:t*r}),j7e=(e,t,o,r)=>{const n=(1-o)/2,a=(1-r)/2;return{x:n+e,y:a+t,zIndex:eg.SOURCE}},z7e=(e,t)=>{const o=e?.rotation??0,r=t===Go.HORIZONTAL||t===Go.VERTICAL_HORIZONTAL,n=t===Go.VERTICAL||t===Go.VERTICAL_HORIZONTAL;if(!(!o&&!r&&!n))return{rotation:o,flipH:r,flipV:n}},Y7e=({wordId:e,timelineStart:t,timelineDuration:o,playbackRate:r,video:n,audio:a,videoTransform:i},s,x)=>{const c=[],l=[];if(n){const d=B7e(n.mediaId,x)?.videoAudioMetaInfo.videoInfo,u=d?G7e(d.size,s,i??null,n.flip??null):null;if(u){const{size:p,position:f,transform:E,crop:T}=u,O=Di(e,{isVideo:!0}),S=n.mediaId,R=h_(n,O),y=lS({infoId:S,modelId:O,effectIds:R?[R.effectId]:[],position:f,timelineStart:t,timelineDuration:o,playbackRate:r,sourceIn:X.max(X.zero(),n.sourceIn),size:p,crop:T,transform:E});c.push(y),R&&l.push(R)}}if(a){const d=X.max(X.zero(),a.sourceIn),u=GP({infoId:a.mediaId,modelId:Di(e,{isAudio:!0}),effectIds:[],timelineStart:t,timelineDuration:o,playbackRate:r,sourceIn:d,volume:a.volume,fadeIn:t,fadeOut:t.add(o)});c.push(u)}return[c,l]},B7e=(e,t)=>{const o=t.get(e);return o&&Zr(o)?o:void 0},K7e=e=>{const t=c8(e);if(!t)return[[],[]];const o=J2(e),r=Q2(t),n=Z2(t,o),a=X.fromSec(Uc.TIMELINE_START),i=X.fromSec(Uc.TIMELINE_END).sub(a),s=[];return[[WP({infoId:q2(t),modelId:Di(t.mediaId),effectIds:s.map(c=>c.effectId),timelineStart:a,timelineDuration:i,position:r,size:n,transform:$2(t),crop:ep(t)})],s]},X7e=(e,t)=>{try{const o=Bje(e),[r,n]=q7e(e),[a,i]=Q7e(e,t),[s,x]=$7e(e),[c,l]=Z7e(e,t),[d,u]=e5e(e,t),p={effects:[...o,...n,...i,...x,...l,...u],models:[...r,...a,...s,...c,...d]};return pF(!0),p}catch(o){throw pF(!1),o}},J7e=(e,t,o,r,n,a)=>{const i={projectRatio:n,timelineStart:X.fromSec(Math.max(0,o)),timelineDuration:X.fromSec(Math.max(0,r)),fileInfoByMediaId:a};return E8(e,t,i,[{timelineStart:i.timelineStart,timelineDuration:i.timelineDuration,isAudible:!1}])},E8=(e,t,o,r)=>{switch(e.type){case z.VIDEO:{const[n,a]=h7e(e,t,o);return[n,a]}case z.SHAPE:{const[n,a]=m7e(e,t,o);return[[n],a]}case z.IMAGE:{const[n,a]=E7e(e,t,o);return[[n],a]}case z.SIMPLE_CHARACTER:{const[n,a]=f7e(e,t,o,r);return[[n],a]}case z.WEB:{const[n,a]=f8(e,t,o);return[[n],a]}case z.LOTTIE:throw new Error("Lottie asset is not implemented")}},q7e=e=>{const t=Gje(e);if(t.length===0)return[[],[]];const o=J2(e),r=new Map(e.globalClips.map((n,a)=>[n.clipId,a]));return t.reduce((n,a)=>{const i=r.get(a.clipId);if(i===void 0)return n;const s=e.globalClips[i],x=e.globalClips.at(i+1),c=w7e(s,x,e,o),[l,d]=tp.captions({key:"caption:"+a.clipId,dependencies:c,convert:()=>{const u=UP(s,x),p=T7e(a,u,o);return p?[[p[0]],p[1]]:[[],[]]}});return n[0].push(...l),n[1].push(...d),n},[[],[]])},Q7e=(e,t)=>{const o=Mje(e,"sub"),r=J2(e);return o.reduce((n,{id:a,asset:i})=>{const s=cS(e,a);if(!s)return n;const[x,c]=s,l={projectRatio:r,timelineStart:x,timelineDuration:c,fileInfoByMediaId:t},d=i.type===z.SIMPLE_CHARACTER?I7e(e,a):[],u=N7e(e,a,i,l,d),[p,f]=tp.assets({ke
3642y:"asset:"+a,dependencies:u,convert:()=>E8(i,a,l,d)});return n[0].push(...p),n[1].push(...f),n},[[],[]])},Z7e=(e,t)=>{const o=J2(e);return Lje(e).reduce((r,n)=>{const a=P7e(n,o,t),[i,s]=tp.sources({key:"source:"+n.wordId,dependencies:a,convert:()=>Y7e(n,o,t)});return r[0].push(...i),r[1].push(...s),r},[[],[]])},$7e=e=>{const t=c8(e);if(!t)return[[],[]];const o=J2(e);return tp.watermarks({key:"watermark:"+t.mediaId,dependencies:b7e(t,o),convert:()=>K7e(e)})},e5e=(e,t)=>{const o=r8(e);return Object.entries(o).reduce((r,[n,a])=>{const i=Je(n),s=cS(e,i);if(!s)return r;const[x,c]=s,l=L7e(a,x,c,t),[d,u]=tp.audios({key:"audio:"+n,dependencies:l,convert:()=>u7e(a,i,x,c,t)});return r[0].push(...d),r[1].push(...u),r},[[],[]])},m8=(e,t)=>({global:{initProjectSize:e??{width:1920,height:1080},projectRatio:t??16/9},infos:{},models:{},effects:{}}),fF={assetEntries:!1,assetTimelineRanges:!1,backgroundMap:!1,captionDisplayMode:!1,denoiseMap:!1,globalCaptionStyle:!1,globalClips:!1,globalVideoTransform:!1,overdubInfosMap:!1,projectAudioLanguage:!1,soundEffectTimelineRanges:!1,trackEntries:!1,videoRatio:!1,audioLanguagesMap:!0,autoScrollingWhilePlaying:!0,globalCursor:!0,markerNames:!0,overdubStates:!0,sceneNames:!0,showOriginal:!0,translateInfo:!0,ttsClipInfosMap:!0,ttsStates:!0},t5e=(e,t)=>Object.keys(fF).filter(r=>!fF[r]).every(r=>e[r]===t[r]),o5e=(e,t)=>t5e(e.transcript,t.transcript)&&n5e(e.fileInfos,t.fileInfos)&&e.mediaSourceBlobSnapshotByMediaId===t.mediaSourceBlobSnapshotByMediaId&&r5e(e.mediaSourceSignedUrlByMediaId,t.mediaSourceSignedUrlByMediaId),r5e=(e,t)=>{if(e===void 0||t===void 0)return e===t;if(e.size!==t.size)return!1;for(const[o,r]of e)if(t.get(o)!==r)return!1;return!0},h8=e=>({transcript:e.transcript,fileInfos:[...e.fileInfos],...e.mediaSourceBlobSnapshotByMediaId!==void 0?{mediaSourceBlobSnapshotByMediaId:e.mediaSourceBlobSnapshotByMediaId}:{},...e.mediaSourceSignedUrlByMediaId!==void 0?{mediaSourceSignedUrlByMediaId:new Map(e.mediaSourceSignedUrlByMediaId)}:{}}),I8=e=>{const t=m8(),o={...e.transcript},r=a5e(o),{models:n,effects:a}=i5e(o,e.fileInfos),i=s5e(e);return t.global={...t.global,...r},t.models=Object.fromEntries(n.map(s=>[s.modelId,s])),t.effects=Object.fromEntries(a.map(s=>[s.effectId,s])),t.infos=Object.fromEntries(i.map(s=>[s.infoId,s])),t},n5e=(e,t)=>e.length===t.length&&e.every((o,r)=>o===t[r]),a5e=e=>qje(e),i5e=(e,t)=>{const o=new Map(t.map(r=>[r.mediaId,r]));return X7e(e,o)},s5e=e=>{const t=[];for(const o of e.fileInfos)if(o.broken!==!0)try{const r=e.mediaSourceBlobSnapshotByMediaId?.get(o.mediaId),n=r!==void 0?d8(o,{kind:"blob",blob:r}):l8(o,e.mediaSourceSignedUrlByMediaId?.get(o.mediaId));t.push(n)}catch(r){h("store.updater.ts").warn("[buildMediaStore] Failed to convert media info "+o.mediaId+": "+P(r))}return t},T8=10,x5e=3300*1e3,c5e=3600*1e3,cf=()=>new DOMException("Remote media signing canceled","AbortError"),gF=(e,t)=>t?t.aborted?Promise.reject(t.reason??cf()):new Promise((o,r)=>{const n=()=>t.removeEventListener("abort",a),a=()=>{n(),r(t.reason??cf())};t.addEventListener("abort",a,{once:!0}),e.then(i=>{n(),o(i)},i=>{n(),r(i)})}):e,l5e=async(e,t)=>{const o=An(T8);return Promise.all(e.map(r=>o(async()=>{if(r.fileLocation!==D.REMOTE)return null;try{const n=await oN(r.url,"GET");return n===null?null:[r.mediaId,n]}catch(n){return t(r,n)}})))},d5e=e=>new Map(e.filter(t=>t!==null)),S8=async e=>{const t=h("remoteMediaSignedUrl.ts"),o=await l5e(e,(r,n)=>(t.warn("[collectRemoteSignedUrlsByMediaId] Failed to presign "+r.mediaId+", falling back to stored url: "+P(n)),null));return d5e(o)},_F=e=>e.fileLocation===D.REMOTE,u5e=()=>new DOMException("Remote media source changed while signing","AbortError"),p5e=()=>new DOMException("Remote media signing timed out","TimeoutError"),YCt=e=>{const t=h("remoteMediaSignedUrl.ts"),o=new Map,r=new Map,n=An(T8);let a=0;const i=e/2,s=(u,p,f)=>{r.get(u)===p&&(f===null?o.delete(u):o.set(u,f))},x=(u,p)=>{const f=Date.now(),E=new AbortController,T=n(async()=>{if(E.signal.aborted)throw E.signal.reason;let S;try{return S=setTimeout(()=>E.abort(p5e()),i),await gF(oN(u.url,"GET",void 0,E.signal),E.signal)}finally{clearTimeout(S)}}).then(S=>{r.get(u.mediaId)===p&&(p.signedAt=f,s(u.mediaId,p,S))},S=>{r.get(u.mediaId)===p&&(t.warn("[createRemoteSignedUrlsByMediaIdProvider] Failed to presign "+u.mediaId+", falling back to stored url: "+P(S)),!(p.signedAt!==void 0&&Date.now()-p.signedAt<c5e)&&o.delete(u.mediaId))}).finally(()=>{p.refresh?.controller===E&&(p.refresh=void 0)}),O={settled:T,controller:E,waiterCount:0};return p.refresh=O,O},c=(u,p)=>{const f=p.refresh,E=f&&!f.controller.signal.aborted?f:x(u,p);return E.waiterCount+=1,E},l=(u,p)=>{p.waiterCount-=1,!(p.waiterCount>
36420||u.refresh!==p)&&p.controller.abort(cf())},d=u=>{const p=r.get(u.mediaId);if(p?.sourceUrl===u.url)return p;a+=1;const f={sourceUrl:u.url,generation:a};return r.set(u.mediaId,f),o.delete(u.mediaId),f};return async(u,p)=>{if(p?.aborted)throw p.reason??cf();for(const O of u)_F(O)||r.delete(O.mediaId)&&o.delete(O.mediaId);const f=u.filter(_F).map(O=>{const S=d(O),R=S.signedAt!==void 0&&Date.now()-S.signedAt<x5e;return{fileInfo:O,entry:S,task:R?void 0:c(O,S)}});let E;const T=new Promise(O=>{E=setTimeout(O,e)});try{await Promise.race([Promise.allSettled(f.map(({task:O})=>O?gF(O.settled,p):Promise.resolve())),T])}finally{clearTimeout(E);for(const{entry:O,task:S}of f)S&&l(O,S)}if(p?.aborted)throw p.reason??cf();if(f.some(({fileInfo:O,entry:S})=>r.get(O.mediaId)?.generation!==S.generation))throw u5e();return o}},f5e=async(e,t=W2(),o=new Map,r=g5e(t))=>{const n={transcript:rt(e()),fileInfos:[...t]},a=Fe(),i=h8({...n,mediaSourceBlobSnapshotByMediaId:new Map([...r,...o])}),s=await S8(i.fileInfos);return new fh(I8({...i,mediaSourceSignedUrlByMediaId:s}),a)},g5e=e=>new Map(e.flatMap(t=>{if(t.fileLocation!==D.IN_MEMORY||t.mediaId===_o)return[];const o=a5(t.mediaId);return o===null?[]:[[t.mediaId,o]]})),BCt=async(e,t,o,r,n=new Map)=>{const a=m8(o,r),i=await S8(Object.values(t)),s=new Map(Object.values(t).map(l=>[l.mediaId,l])),x=[],c=[];for(const[l,d]of Object.entries(e)){const[u,p]=J7e(d,Je(l),0,1,r,s);x.push(u[0]),c.push(...p)}
3642return a.models=Object.fromEntries(x.map(l=>[l.modelId,l])),a.effects=Object.fromEntries(c.map(l=>[l.effectId,l])),a.infos=Object.fromEntries(Object.values(t).map(l=>{const d=n.get(l.mediaId),u=d===void 0?l8(l,i.get(l.mediaId)):d8(l,{kind:"blob",blob:d});return[u.infoId,u]})),new fh(a,Fe())},UA="thumbnail.jpg",O8="thumbnail",I_=(e,t)=>e+"/"+O8+"/"+t+".jpg",_h=new Set,yC=new Map,_5e=An(5),C8=async(e,t,o)=>{try{const r=Ht(So.CLOUD_CACHE);await r.removeDir(e+"/"+O8).catch(()=>{}),await r.saveFile(I_(e,t),o.stream())}catch(r){h("thumbnail.ts").warn("[cacheThumbnailLocally] failed to cache thumbnail for projectId="+e+", snapshotId="+t+": "+P(r))}},E5e=async(e,t,o)=>{try{await lT({data:{uploadSourceType:"blob",targetType:"snapshot",mediaId:t,blob:o,remotePath:UA,projectId:e,name:UA}}),_h.delete(I_(e,t)),await C8(e,t,o)}catch(r){h("thumbnail.ts").warn("[uploadCloudProjectThumbnail] failed for projectId="+e+", snapshotId="+t+": "+P(r))}},m5e=async(e,t)=>{const o=I_(e,t);try{const r=await Nd(e,{methodType:"GET",name:UA});if(r.result!=="GET")return _h.add(o),null;const n=await fetch(r.url);if(!n.ok)return _h.add(o),null;const a=await n.blob();return await C8(e,t,a),a}catch(r){return h("thumbnail.ts").warn("[loadCloudProjectThumbnail] failed for projectId="+e+", snapshotId="+t+": "+P(r)),null}},h5e=async(e,t)=>{try{const o=await Ht(So.CLOUD_CACHE).getFileAsBlob(I_(e,t));if(o)return o}catch(o){h("thumbnail.ts").warn("[loadCloudProjectThumbnail] OPFS read failed for projectId="+e+": "+P(o))}return _5e(()=>m5e(e,t))},KCt=(e,t)=>{const o=I_(e,t);if(_h.has(o))return Promise.resolve(null);const r=yC.get(o);if(r)return r;const n=h5e(e,t).finally(()=>yC.delete(o));return yC.set(o,n),n},I5e=158,T5e=110,R8=2,VA=I5e*R8,GA=T5e*R8,EF=VA/GA,S5e=e=>{const t=e>=EF?VA:GA*e,o=e>=EF?VA/e:GA;return{width:Math.floor(t),height:Math.floor(o)}},A8=async(e,t)=>{const o=h("projectThumbnail.ts");let r;try{const n=ks();if(!n)return;const a=await f5e(()=>n),i=S5e(I2(n)),s=new AbortController;r=await x4e(a,i,s.signal,t)}catch(n){return o.warn("thumbnail render failed for project "+e+": "+P(n)),void 0}if(!r)return o.warn("thumbnail render produced no image for project "+e),void 0;if(se().getProjectId()===e)return r},y8=async(e,t)=>{const o=await A8(e);if(!o)return;const r=await c4e(o);try{await t(r)}catch(n){h("projectThumbnail.ts").warn("thumbnail persistence failed for project "+e+": "+P(n))}},v8=e=>y8(e,t=>Il().setThumbnail(e,t)),w8=(e,t)=>y8(e,o=>XT().updateProjectThumbnail(t,o)),O5e=.8,C5e=async(e,t)=>{const o=await A8(e,{type:"image/jpeg",quality:O5e});o&&await E5e(e,t,o)},N8=async e=>{const t=Lt().getVCloudProjectInfo(e)?.snapshotId;t&&await C5e(e,t)},R5e=e=>Il().getLocalProjects().find(t=>t.projectId===e)?.thumbnail!==void 0,A5e=async(e,t)=>{try{if(await XT().hasThumbnail(t))return}catch(o){h("projectThumbnail.ts").warn("browser thumbnail check failed for project "+t+": "+P(o))}await w8(e,t)},y5e=({type:e,projectId:t,savePath:o})=>{if(e===Ee.PROJECT){if(R5e(t))return;v8(t)}else e===Ee.BROWSER?A5e(t,o):e===Ee.CLOUD&&N8(t)};let mF=!1;const XCt=()=>{if(mF)return;mF=!0;const e=se().getEventEmitter();e.on(co.VREW_FILE_SAVED,(t,o,r)=>{r===Ee.PROJECT?v8(t):r===Ee.BROWSER&&w8(t,o)}),e.on(co.CLOUD_PROJECT_INITIALIZED,t=>{N8(t)})},hF=Symbol("LegacyAdapter"),jP=e=>e==null||!(hF in e)||e[hF]!==!0?null:e,JCt=e=>{const t=jP(e);if(t===null)throw new Error("assertLegacyAdapter: expected a LegacyPlayerAdapter instance for legacy facade access");return t},v5e=5,w5e=1500,N5e=1e3;class P5e{playQueue;lastAlertTime;constructor(){this.playQueue=[],this.lastAlertTime=0}checkPlayAvailability=()=>{const t=Date.now();return this.playQueue.length<v5e?(this.playQueue.push({enqueueTime:t}),!0):t-this.playQueue[0].enqueueTime>w5e?(this.playQueue.shift(),this.playQueue.push({enqueueTime:t}),!0):!1};alertBlockNoti=()=>{const t=Date.now();t-this.lastAlertTime>N5e&&(xt.info(A("player.block")),this.lastAlertTime=t)}}let vC;const IF=()=>(!vC&&(vC=new P5e),vC);class b5e{imgs=new Map;blobUrls=new Map;loadingPromises=new Map;async get(t){const o=this.imgs.get(t);if(o)return o;const r=this.loadingPromises.get(t);if(r)return r;const n=this.loadImage(t);this.loadingPromises.set(t,n);try{return await n}finally{this.loadingPromises.delete(t)}}async loadImage(t){const o=await En(t);if(!o)throw new C(_.C_MEDIA_BLOB_LOST,{},"File not found");const r=URL.createObjectURL(o);this.blobUrls.set(t,r);try{const n=await this.createImageElement(r);return this.imgs.set(t,n),n}catch(n){throw this.cleanupBlobUrl(t),n}}createImageElement(t){return new Promise((o,r)=>{const n=new Image,a=()=>{n.onload=null,n.onerror=null};n.onload=()=>{a(),o(n)},n.onerror=i=>{a(),r(new Error("Failed to load image: "+i))},n.src=t})}cleanupBlobUrl(t){const o=this.blobUrls.get(t);o&&(URL.revokeObjectURL(o),this.blobUrls.delete(t))}}const wC=new b5e;class P8{_promise;constructor(){this._promise=Promise.resolve()}next(t){const o={run:()=>{}},r=new Promise((n,a)=>{o.run=()=>{try{const i=t();return i&&i instanceof Promise?i.then(n).catch(a):(n(i),i)}catch(i){return a(i),i}}});return this._promise=this._promise.then(o.run),r}}var Ml=(e=>(e.VIDEO_PLAYER="VideoPlayer",e.EXPORTER="Exporter",e.FILTER_PANEL="FilterPanel",e.THUMBNAIL="Thumbnail",e.TRANSITION="Transition",e))(Ml||{}),fo=(e=>(e.Float="float",e.Vec2="vec2",e.Vec3="vec3",e.Vec4="vec4",e.Int="int",e.Ivec2="ivec2",e.Ivec3="ivec3",e.Ivec4="ivec4",e.Bool="bool",e.Bvec2="bvec2",e.Bvec3="bvec3",e.Bvec4="bvec4",e.Mat2="mat2",e.Mat3="mat3",e.Mat4="mat4",e.S
3642ampler2D="sampler2D",e.SamplerCube="samplerCube",e.Sampler2DArray="sampler2DArray",e.Sampler3D="sampler3D",e))(fo||{}),la=(e=>(e[e.MAIN=0]="MAIN",e[e.FILTER=1]="FILTER",e[e.EFFECT=2]="EFFECT",e[e.OVERLAY_BASE=3]="OVERLAY_BASE",e[e.OVERLAY_EFFECT=4]="OVERLAY_EFFECT",e))(la||{});class L5e{static toRadian=t=>t*Math.PI/180}const M5e=()=>Object.values(b8).map(({functionBody:e})=>e).join(`
3643`),D5e=()=>Object.values(b8).map(({index:e,functionName:t})=>`
3644  if (transitionIndex == `+e+`) {
3645      return `+t+`();
3646  }
3647  `).join(`
3648`),b8={[Re.NONE]:{index:or.NONE,thumbnail:Vt.thumbnail.NONE,effectGif:Vt.gif.NONE,type:Re.NONE,functionName:"noneTransition",functionBody:`
3649vec4 noneTransition() {
3650  return getFromColor(textureCoordinate);
3651}
3652    `},[Re.CROSS_FADE]:{index:or.CROSS_FADE,thumbnail:Vt.thumbnail.CROSS_FADE,effectGif:Vt.gif.CROSS_FADE,type:Re.CROSS_FADE,functionName:"dissolveTransition",functionBody:`
3653vec4 dissolveTransition() {
3654  return mix(getFromColor(textureCoordinate), getToColor(textureCoordinate), transitionProgress);
3655}
3656    `},[Re.LINEAR_BLUR]:{index:or.LINEAR_BLUR,thumbnail:Vt.thumbnail.LINEAR_BLUR,effectGif:Vt.gif.LINEAR_BLUR,type:Re.LINEAR_BLUR,uniforms:[{name:"intensity",type:fo.Float,initValue:.1}],functionName:"linearBlurTransition",functionBody:`
3657uniform float intensity;
3658
3659vec4 linearBlurTransition() {
3660  vec2 uv = textureCoordinate;
3661  float progress = transitionProgress;
3662  const int samples = 6;
3663  vec4 fromColor = vec4(0.0);
3664  vec4 toColor = vec4(0.0);
3665
3666  float displacement = intensity * (0.5 - distance(0.5, progress));
3667  for (int xi = 0; xi < samples; xi++)
3668  {
3669      float offsetX = float(xi) / float(samples) - 0.5;
3670      for (int yi = 0; yi < samples; yi++)
3671      {
3672          float offsetY = float(yi) / float(samples) - 0.5;
3673          vec2 offset = vec2(offsetX, offsetY);
3674          fromColor += getFromColor(uv + displacement * offset);
3675          toColor += getToColor(uv + displacement * offset);
3676      }
3677  }
3678  fromColor /= float(samples * samples);
3679  toColor /= float(samples * samples);
3680  return mix(fromColor, toColor, progress);
3681}
3682    `},[Re.DIRECTIONAL_WARP]:{index:or.DIRECTIONAL_WARP,thumbnail:Vt.thumbnail.DIRECTIONAL_WARP,effectGif:Vt.gif.DIRECTIONAL_WARP,type:Re.DIRECTIONAL_WARP,functionName:"directionalWarpTransition",functionBody:`
3683vec4 directionalWarpTransition() {
3684  vec2 uv = textureCoordinate;
3685  float progress = transitionProgress;
3686
3687  float smoothness = 0.5;
3688  vec2 center = vec2(0.5, 0.5);
3689  vec2 direction = vec2(-1.0, 1.0); 
3690  direction /= abs(direction.x) + abs(direction.y);
3691
3692  float directionalDot = direction.x * center.x + direction.y * center.y;
3693  float transitionFactor = 1.0 - smoothstep(-smoothness, 0.0,
3694     direction.x * uv.x + direction.y * uv.y 
3695     - (directionalDot - 0.5 + progress * ( 1.0 + smoothness)));
3696
3697  return mix(
3698    getFromColor((uv - 0.5) * (1.0 - transitionFactor) + 0.5),
3699    getToColor((uv - 0.5) * transitionFactor + 0.5),
3700    transitionFactor);
3701}
3702`},[Re.GLITCH_MEMORIES]:{index:or.GLITCH_MEMORIES,thumbnail:Vt.thumbnail.GLITCH_MEMORIES,effectGif:Vt.gif.GLITCH_MEMORIES,type:Re.GLITCH_MEMORIES,functionName:"glitchMemoriesTransition",functionBody:`
3703vec4 glitchMemoriesTransition() {
3704  vec2 uv = textureCoordinate;
3705  float progress = transitionProgress;
3706
3707  vec2 noiseTextureCoord = vec2(0.0, 0.0);
3708  noiseTextureCoord += floor(vec2(progress) * vec2(1200.0, 3500.0)) / vec2(64);
3709  vec2 noiseDistortion = progress > 0.0 ? (fract(noiseTextureCoord) - 0.5) * 0.3 *(1.0 - progress) : vec2(0.0);
3710  vec2 redCoord = uv + noiseDistortion * 0.2;
3711  vec2 greenCoord = uv + noiseDistortion * 0.3;
3712  vec2 blueCoord = uv + noiseDistortion * 0.5;
3713
3714  return vec4(
3715    mix(getFromColor(redCoord), getToColor(redCoord), progress).r,
3716    mix(getFromColor(greenCoord), getToColor(greenCoord), progress).g,
3717    mix(getFromColor(blueCoord), getToColor(blueCoord), progress).b,
3718    1.0);
3719}
3720`},[Re.PIXELIZE]:{index:or.PIXELIZE,thumbnail:Vt.thumbnail.PIXELIZE,effectGif:Vt.gif.PIXELIZE,type:Re.PIXELIZE,uniforms:[{name:"pixelizeSteps",type:fo.Int,initValue:50},{name:"squaresMin",type:fo.Ivec2,initValue:[20,20]}],functionName:"pixelizeTransition",functionBody:`
3721uniform ivec2 squaresMin; 
3722uniform int pixelizeSteps; 
3723
3724vec4 pixelizeTransition() {
3725  vec2 uv = textureCoordinate;
3726  float progress = transitionProgress;
3727  int steps = pixelizeSteps;
3728
3729  float pixelizationLevel = min(progress, 1.0 - progress);
3730  float dist = steps > 0 ? ceil(pixelizationLevel * float(steps)) / float(steps) : pixelizationLevel;
3731  vec2 squareSize = 2.0 * dist / vec2(squaresMin);
3732
3733  vec2 pixelizedCoord = dist > 0.0 ? (floor(uv / squareSize) + 0.5) * squareSize : uv;
3734  return mix(getFromColor(pixelizedCoord), getToColor(pixelizedCoord), progress);
3735}
3736    `},[Re.WIND]:{index:or.WIND,thumbnail:Vt.thumbnail.WIND,effectGif:Vt.gif.WIND,type:Re.WIND,uniforms:[{name:"windSize",type:fo.Float,initValue:.3}],functionName:"windTransition",functionBody:`
3737uniform float windSize; 
3738
3739float windRand (vec2 coord) {
3740  return fract(sin(dot(coord.xy ,vec2(12.9898,78.233))) * 43758.5453);
3741}
3742
3743vec4 windTransition () {
3744  vec2 uv = textureCoordinate;
3745  float progress = transitionProgress;
3746
3747  float random = windRand(vec2(0, uv.y));
3748  float windEffectIntensity = smoothstep(
3749    0.0, 
3750    -windSize, 
3751    uv.x * (1.0 - windSize) + windSize * random - (progress * (1.0 + windSize))
3752  );
3753
3754  return mix(
3755    getFromColor(uv),
3756    getToColor(uv),
3757    windEffectIntensity
3758  );
3759}
3760    `},[Re.VERTICAL_WIPE]:{index:or.VERTICAL_WIPE,thumbnail:Vt.thumbnail.VERTICAL_WIPE,effectGif:Vt.gif.VERTICAL_WIPE,type:Re.VERTICAL_WIPE,functionName:"verticalWipeTransition",functionBody:`
3761vec4 verticalWipeTransition() {
3762  vec2 uv = textureCoordinate;
3763  float progress = transitionProgress;
3764  vec2 direction = vec2(0.0, 1.0);
3765
3766  vec2 adjustedUV = uv + progress * sign(direction);
3767  vec2 fractUV = fract(adjustedUV);
3768
3769  return mix(
3770    getToColor(fractUV),
3771    getFromColor(fractUV),
3772    step(0.0, adjustedUV.y) * step(adjustedUV.y, 1.0) * step(0.0, adjustedUV.x) * step(adjustedUV.x, 1.0)
3773  );
3774}
3775    `},[Re.SIMPLE_ZOOM]:{index:or.SIMPLE_ZOOM,thumbnail:Vt.thumbnail.SIMPLE_ZOOM,effectGif:Vt.gif.SIMPLE_ZOOM,type:Re.SIMPLE_ZOOM,functionName:"simpleZoomTransition",functionBody:`
3776vec2 zoomEffect(vec2 uv, float zoomIntensity) {
3777  return 0.5 + ((uv - 0.5) * (1.0 - zoomIntensity));
3778}
3779
3780vec4 simpleZoomTransition() {
3781  vec2 uv = textureCoordinate;
3782  float progress = transitionProgress;
3783  float zoomIntensity = 0.8;
3784  float normalizedIntensity = clamp(zoomIntensity, 0.2, 1.0);
3785
3786  return mix(
3787    getFromColor(zoomEffect(uv, smoothstep(0.0, normalizedIntensity, progress))),
3788    getToColor(uv),
3789    smoothstep(normalizedIntensity - 0.2, 1.0, progress)
3790  );
3791}
3792`},[Re.WIPE_LEFT]:{index:or.WIPE_LEFT,thumbnail:Vt.thumbnail.WIPE_LEFT,effectGif:Vt.gif.WIPE_LEFT,type:Re.WIPE_LEFT,functionName:"wipeLeftTransition",functionBody:`
3793vec4 wipeLeftTransition() {
3794  vec2 uv = textureCoordinate;
3795  float progress = transitionProgress;
3796
3797  vec4 fromColor = getFromColor(uv);
3798  vec4 toColor = getToColor(uv);
3799  
3800  float fade = step(1.0 - uv.x, progress);
3801  return mix(fromColor, toColor, fade);
3802}
3803    `},[Re.WIPE_RIGHT]:{index:or.WIPE_RIGHT,thumbnail:Vt.thumbnail.WIPE_RIGHT,effectGif:Vt.gif.WIPE_RIGHT,type:Re.WIPE_RIGHT,functionName:"wipeRightTransition",functionBody:`
3804vec4 wipeRightTransition() {
3805  vec2 uv = textureCoordinate;
3806  float progress = transitionProgress;
3807
3808  vec4 fromColor = getFromColor(uv);
3809  vec4 toColor = getToColor(uv);
3810  
3811  float fade = step(uv.x, progress);
3812  return mix(fromColor, toColor, fade);
3813}
3814    `},[Re.WIPE_UP]:{index:or.WIPE_UP,thumbnail:Vt.thumbnail.WIPE_UP,effectGif:Vt.gif.WIPE_UP,type:Re.WIPE_UP,functionName:"wipeUpTransition",functionBody:`
3815vec4 wipeUpTransition() {
3816  vec2 uv = textureCoordinate;
3817  float progress = transitionProgress;
3818
3819  vec4 fromColor = getFromColor(uv);
3820  vec4 toColor = getToColor(uv);
3821  
3822  float fade = step(1.0 - uv.y, progress);
3823  return mix(fromColor, toColor, fade);
3824}
3825    `},[Re.WIPE_DOWN]:{index:or.WIPE_DOWN,thumbnail:Vt.thumbnail.WIPE_DOWN,effectGif:Vt.gif.WIPE_DOWN,type:Re.WIPE_DOWN,functionName:"wipeDownTransition",functionBody:`
3826vec4 wipeDownTransition() {
3827  vec2 uv = textureCoordinate;
3828  float progress = transitionProgress;
3829
3830  vec4 fromColor = getFromColor(uv);
3831  vec4 toColor = getToColor(uv);
3832  
3833  float fade = step(uv.y, progress);
3834  return mix(fromColor, toColor, fade);
3835}
3836    `},[Re.IRIS]:{index:or.IRIS,thumbnail:Vt.thumbnail.IRIS,effectGif:Vt.gif.IRIS,type:Re.IRIS,functionName:"
3836circleCropTransition",functionBody:`
3837vec4 circleCropTransition() {
3838  vec2 uv = textureCoordinate;
3839  float progress = transitionProgress;
3840
3841  vec2 ellipseScale = vec2(1.0, 0.5);
3842  float circleSize = pow(2.0 * abs(progress - 0.5), 3.0);
3843  vec4 backgroundColor = vec4(0.0, 0.0, 0.0, 1.0);
3844
3845  float distFromCenter = length((vec2(uv) - 0.5) * ellipseScale);
3846  return mix(
3847    progress < 0.5 ? getFromColor(uv) : getToColor(uv),
3848    backgroundColor,
3849    step(circleSize, distFromCenter)
3850  );
3851}
3852    `},[Re.DREAMY]:{index:or.DREAMY,thumbnail:Vt.thumbnail.DREAMY,effectGif:Vt.gif.DREAMY,type:Re.DREAMY,functionName:"dreamyTransition",functionBody:`
3853vec2 calculateOffset(float progress, float horizontalPosition, float phaseOffset) {
3854  float phase = progress * progress + progress + phaseOffset;
3855  float verticalOffset = 0.03 * progress * cos(10.0 * (progress + horizontalPosition));
3856  return vec2(0, verticalOffset);
3857}
3858vec4 dreamyTransition() {
3859  vec2 uv = textureCoordinate;
3860  float progress = transitionProgress;
3861  
3862  vec2 offsetStart = calculateOffset(progress, uv.x, 0.0);
3863  vec2 offsetEnd = calculateOffset(1.0 - progress, uv.x, 3.14);
3864
3865  return mix(
3866    getFromColor(uv + offsetStart),
3867    getToColor(uv + offsetEnd),
3868    progress
3869  );
3870}
3871    `},[Re.RADIAL]:{index:or.RADIAL,thumbnail:Vt.thumbnail.RADIAL,effectGif:Vt.gif.RADIAL,type:Re.RADIAL,functionName:"radialTransition",functionBody:`
3872vec4 radialTransition() {
3873  const float PI = 3.141592653589;
3874  float smoothness = 1.0;
3875  vec2 uv = textureCoordinate;
3876  float progress = transitionProgress;
3877  vec2 normalizedUV = uv * 2.0 - 1.0;
3878  
3879  float angleOffset = atan(normalizedUV.y, normalizedUV.x) - (progress - 0.5) * PI * 2.5;
3880
3881  return mix(
3882    getToColor(uv),
3883    getFromColor(uv),
3884    smoothstep(0.0, smoothness, angleOffset)
3885  );
3886}
3887    `},[Re.WINDOW_BLIND]:{index:or.WINDOW_BLIND,thumbnail:Vt.thumbnail.WINDOW_BLIND,effectGif:Vt.gif.WINDOW_BLIND,type:Re.WINDOW_BLIND,functionName:"windowBlindTransition",functionBody:`
3888vec4 windowBlindTransition () {
3889  vec2 uv = textureCoordinate;
3890  float progress = transitionProgress;
3891  float adjustedProgress = progress;
3892
3893  if (mod(floor(uv.y * 100.0 * progress), 2.0) == 0.0)
3894    adjustedProgress *= 1.5;
3895
3896  return mix(
3897    getFromColor(uv),
3898    getToColor(uv),
3899    mix(adjustedProgress, progress, smoothstep(0.8, 1.0, progress))
3900  );
3901}
3902  `},[Re.CIRCLE_OPEN]:{index:or.CIRCLE_OPEN,thumbnail:Vt.thumbnail.CIRCLE_OPEN,effectGif:Vt.gif.CIRCLE_OPEN,type:Re.CIRCLE_OPEN,functionName:"circleOpenTransition",functionBody:`
3903vec4 circleOpenTransition () {
3904  vec2 uv = textureCoordinate;
3905  const vec2 center = vec2(0.5, 0.5);
3906  const float SQRT_2 = 1.414213562373;
3907  const float smoothness = 0.5;
3908  float progress = transitionProgress;
3909
3910  float mask = smoothstep(
3911    -smoothness,
3912    0.0,
3913    SQRT_2 * distance(center, uv) - progress * (1.0 + smoothness)
3914  );
3915
3916  return mix(getFromColor(uv), getToColor(uv), 1.0 - mask);
3917}
3918    `},[Re.DIRECTIONAL_WIPE]:{index:or.DIRECTIONAL_WIPE,thumbnail:Vt.thumbnail.DIRECTIONAL_WIPE,effectGif:Vt.gif.DIRECTIONAL_WIPE,type:Re.DIRECTIONAL_WIPE,functionName:"directionalWipeTransition",functionBody:`
3919vec4 directionalWipeTransition () {
3920  vec2 uv = textureCoordinate;
3921  const vec2 center = vec2(0.5, 0.5);
3922  const float smoothness = 0.5;
3923  float progress = transitionProgress;
3924
3925  vec2 wipeDirection = vec2(1.0, -1.0); 
3926  vec2 normalizedDirection = normalize(wipeDirection);
3927  normalizedDirection /= abs(normalizedDirection.x) + abs(normalizedDirection.y);
3928  float lineOffset = normalizedDirection.x * center.x + normalizedDirection.y * center.y;
3929  float mask =
3930    (1.0 - step(progress, 0.0)) *
3931    (1.0 - smoothstep(-smoothness, 0.0, normalizedDirection.x * uv.x +
3932       normalizedDirection.y * uv.y - (lineOffset - 0.5 + progress * (1.0 + smoothness))));
3933  return mix(getFromColor(uv), getToColor(uv), mask);
3934}
3935`},[Re.MORPH]:{index:or.MORPH,thumbnail:Vt.thumbnail.MORPH,effectGif:Vt.gif.MORPH,type:Re.MORPH,uniforms:[{name:"morphIntensity",type:fo.Float,initValue:.1}],functionName:"morphTransition",functionBody:`
3936uniform float morphIntensity;
3937
3938vec4 morphTransition() {
3939  vec2 uv = textureCoordinate;
3940  float progress = transitionProgress;
3941  float intensity = morphIntensity;
3942
3943  vec4 fromColor = getFromColor(uv);
3944  vec4 toColor = getToColor(uv);
3945
3946  vec2 offsetStart = (((fromColor.rg + fromColor.b) * 0.5) * 2.0 - 1.0);
3947  vec2 offsetEnd = (((toColor.rg + toColor.b) * 0.5) * 2.0 - 1.0);
3948  vec2 offsetMorph = mix(offsetStart, offsetEnd, 0.5) * intensity;
3949
3950  float startWeight = progress;
3951  float endWeight = 1.0 - startWeight;
3952
3953  return mix(
3954    getFromColor(uv + offsetMorph * startWeight),
3955    getToColor(uv - offsetMorph * endWeight),
3956    progress);
3957}
3958    `},[Re.BLACK_FADE_OUT]:{index:or.BLACK_FADE_OUT,thumbnail:Vt.thumbnail.BLACK_FADE_OUT,effectGif:Vt.gif.BLACK_FADE_OUT,type:Re.BLACK_FADE_OUT,functionName:"blackFadeOutTransition",functionBody:`
3959vec4 blackFadeOutTransition() {
3960  vec2 uv = textureCoordinate;
3961  float progress = transitionProgress;
3962  vec4 blackVec = vec4(0.0, 0.0, 0.0, 1.0);
3963
3964  return mix(
3965    getFromColor(uv),
3966    blackVec,
3967    smoothstep(0.0, 1.0, progress)
3968  );
3969}
3970    `},[Re.WHITE_FADE_OUT]:{index:or.WHITE_FADE_OUT,thumbnail:Vt.thumbnail.WHITE_FADE_OUT,effectGif:Vt.gif.WHITE_FADE_OUT,type:Re.WHITE_FADE_OUT,functionName:"whiteFadeOutTransition",functionBody:`
3971vec4 whiteFadeOutTransition() {
3972  vec2 uv = textureCoordinate;
3973  float progress = transitionProgress;
3974  vec4 whiteVec = vec4(1.0, 1.0, 1.0, 1.0);
3975
3976  return mix(
3977    getFromColor(uv),
3978    whiteVec,
3979    smoothstep(0.0, 1.0, progress)
3980  );
3981}
3982    `},[Re.COLOR_DISTANCE]:{index:or.COLOR_DISTANCE,thumbnail:Vt.thumbnail.COLOR_DISTANCE,effectGif:Vt.gif.COLOR_DISTANCE,type:Re.COLOR_DISTANCE,functionName:"
3982colorDistanceTransition",functionBody:`
3983vec4 colorDistanceTransition() {
3984  float power = 5.0;
3985  vec2 uv = textureCoordinate;
3986  float progress = transitionProgress;
3987
3988  vec4 fromColor = getFromColor(uv);
3989  vec4 toColor = getToColor(uv);
3990  float transitionMask = step(distance(fromColor, toColor), progress);
3991  
3992  vec4 mixedColor = mix(fromColor, toColor, transitionMask);
3993
3994  return mix(
3995    mixedColor,
3996    toColor,
3997    pow(progress, power)
3998  );
3999}
4000    `},[Re.GRAY_SCALE_FADE]:{index:or.GRAY_SCALE_FADE,thumbnail:Vt.thumbnail.GRAY_SCALE,effectGif:Vt.gif.GRAY_SCALE,type:Re.GRAY_SCALE_FADE,functionName:"grayScaleFadeTransition",functionBody:`
4001    vec3 toGrayScale(vec3 color) {
4002      float gray = dot(color, vec3(0.2126, 0.7152, 0.0722));
4003      return vec3(gray);
4004    }
4005
4006    vec4 grayScaleFadeTransition () {
4007      float intensity = 0.3;
4008      vec2 uv = textureCoordinate;
4009      float progress = transitionProgress;
4010
4011      vec4 fromColor = getFromColor(uv);
4012      vec4 toColor = getToColor(uv);
4013
4014      vec4 fromGrayScale = vec4(toGrayScale(fromColor.rgb), 1.0);
4015      vec4 toGrayScale = vec4(toGrayScale(toColor.rgb), 1.0);
4016
4017      vec4 fromMixed = mix(fromGrayScale, fromColor, smoothstep(1.0 - intensity, 0.0, progress));
4018      vec4 toMixed = mix(toGrayScale, toColor, smoothstep(intensity, 1.0, progress));
4019
4020      return mix(fromMixed, toMixed, progress);
4021    }
4022    `}},TF=`#version 300 es
4023precision mediump float;
4024
4025uniform int flip;
4026uniform float aspectRatio;
4027uniform float transformZoomX;
4028uniform float transformZoomY;
4029uniform float transformXPos;
4030uniform float transformYPos;
4031uniform float transformRotation;
4032
4033in vec2 position;
4034out vec2 textureCoordinate;
4035
4036mat4 createPreRotateMatrix(float aspectRatio) {
4037  return mat4(aspectRatio, 0, 0, 0,
4038              0, 1, 0, 0,
4039              0, 0, 1, 0,
4040              0, 0, 0, 1);
4041}
4042
4043mat4 createPostRotateMatrix(float aspectRatio) {
4044  return mat4(1.0 / aspectRatio, 0, 0, 0,
4045              0, 1, 0, 0,
4046              0, 0, 1, 0,
4047              0, 0, 0, 1);
4048}
4049
4050mat4 createTransformRotateMatrix(float rotation) {
4051  return mat4(cos(rotation), -sin(rotation), 0, 0,
4052              sin(rotation), cos(rotation), 0, 0,
4053              0, 0, 1, 0,
4054              0, 0, 0, 1);
4055}
4056
4057mat4 createPreScaleMatrix() {
4058  return mat4(1, 0, 0, 1,
4059              0, 1, 0, -1,
4060              0, 0, 1, 0,
4061              0, 0, 0, 1);
4062}
4063
4064mat4 createPostScaleMatrix() {
4065  return mat4(1, 0, 0, -1,
4066              0, 1, 0, 1,
4067              0, 0, 1, 0,
4068              0, 0, 0, 1);
4069}
4070
4071mat4 createTransformScaleMatrix(float scaleX, float scaleY) {
4072  return mat4(scaleX, 0, 0, 0,
4073              0, scaleY, 0, 0,
4074              0, 0, 1, 0,
4075              0, 0, 0, 1);
4076}
4077
4078mat4 createTransformTranslateMatrix(float posX, float posY) {
4079  return mat4(1, 0, 0, 2.0 * posX,
4080              0, 1, 0, -2.0 * posY,
4081              0, 0, 1, 0,
4082              0, 0, 0, 1);
4083}
4084
4085mat4 calculateRotateMatrix() {
4086  return createPreRotateMatrix(aspectRatio) * createTransformRotateMatrix(transformRotation) * createPostRotateMatrix(aspectRatio);
4087}
4088
4089mat4 calculateScaleMatrix() {
4090  return createPreScaleMatrix() * createTransformScaleMatrix(transformZoomX, transformZoomY) * createPostScaleMatrix();
4091}
4092
4093mat4 calculateTranslateMatrix() {
4094  return createTransformTranslateMatrix(transformXPos, transformYPos);
4095}
4096
4097// The order is important, as it will affect the final result.
4098// this is not a ordinary Transform Matrix Calculation order. This is a special order for this shader. ( Rotate -> Scale -> Translate )(transpose)
4099mat4 calculateTransformMatrix() {
4100  return calculateRotateMatrix() * calculateScaleMatrix() * calculateTranslateMatrix();
4101}
4102
4103void main() {
4104  textureCoordinate = (position + vec2(1.0)) / 2.0;
4105  textureCoordinate.y = 1.0 - textureCoordinate.y;
4106
4107  vec4 position4D = vec4(position, 1.0, 1.0);
4108
4109  position4D.y = (flip == `+Go.VERTICAL+" || flip == "+Go.VERTICAL_HORIZONTAL+` ? -1.0 : 1.0) * position4D.y;
4110  position4D.x = (flip == `+Go.HORIZONTAL+" || flip == "+Go.VERTICAL_HORIZONTAL+` ? -1.0 : 1.0) * position4D.x;
4111
4112  if(transformZoomX != 0.0 && transformZoomY != 0.0) {
4113    position4D = position4D * calculateTransformMatrix();
4114  }
4115
4116  gl_Position = position4D;
4117}`,SF=`#version 300 es
4118precision highp float;
4119
4120uniform sampler2D uTexture; // base video texture
4121uniform sampler2D uLookup;
4122uniform float filterAlpha;
4123
4124/* Transition uniforms */
4125uniform bool isTransitioning;
4126
4127uniform sampler2D baseOverlayTexture; // for asset transition
4128
4129uniform sampler2D effectTexture; // transition effect texture
4130uniform sampler2D effectOverlayTexture;
4131
4132
4133uniform int transitionIndex;
4134uniform float transitionProgress;
4135
4136in vec2 textureCoordinate;
4137out vec4 FragColor;
4138
4139vec4 getFromColor(vec2 textureCoordinate) {
4140  vec4 baseOverlayColor = texture(baseOverlayTexture, textureCoordinate);
4141  if (isTransitioning) {
4142    vec4 fromColor = texture(uTexture, textureCoordinate);
4143    return mix(fromColor, baseOverlayColor, baseOverlayColor.a);
4144  }
4145  return texture(uTexture, textureCoordinate);
4146}
4147
4148vec4 getToColor(vec2 textureCoordinate) {
4149  vec4 effectOverlayColor = texture(effectOverlayTexture, textureCoordinate);
4150  vec4 toColor = texture(effectTexture, textureCoordinate);
4151  if (isTransitioning) {
4152    return mix(toColor, effectOverlayColor, effectOverlayColor.a);
4153  }
4154
4155  return toColor;
4156}
4157
4158// Transition Effect Functions.
4159// If you want to add new transition effect, you can add to this list.
4160// Func must have declare own uniform variables. be careful for same name.
4161`+M5e()+`
4162
4163vec4 applyTransitionFactory() {
4164  `+D5e()+`
4165
4166  // default case. (no transition effect)
4167  return texture(uTexture, textureCoordinate);
4168}
4169
4170vec2 calculateLookupTexturePosition(vec4 textureColor, vec2 quad) {
4171    return vec2((quad.x * 0.125) + 63.0/512.0 * textureColor.r + 0.5/512.0,
4172                (quad.y * 0.125) + 63.0/512.0 * textureColor.g + 0.5/512.0);
4173}
4174
4175vec4 lookup(vec4 textureColor, sampler2D lookupTable) {
4176    mediump float blueColor = textureColor.b * 63.0;
4177
4178    mediump vec2 quad1;
4179    quad1.y = floor(floor(blueColor) / 8.0);
4180    quad1.x = floor(blueColor) - (quad1.y * 8.0);
4181
4182    mediump vec2 quad2;
4183    quad2.y = floor(ceil(blueColor) / 8.0);
4184    quad2.x = ceil(blueColor) - (quad2.y * 8.0);
4185
4186    highp vec2 texPos1 = calculateLookupTexturePosition(textureColor, quad1);
4187    highp vec2 texPos2 = calculateLookupTexturePosition(textureColor, quad2);
4188
4189    lowp vec4 newColor1 = texture(lookupTable, texPos1);
4190    lowp vec4 newColor2 = texture(lookupTable, texPos2);
4191
4192    lowp vec4 newColor = mix(newColor1, newColor2, fract(blueColor));
4193    return mix(textureColor, newColor, filterAlpha);
4194}
4195
4196bool isOutOfBounds(vec2 textureCoordinate) {
4197    return textureCoordinate.x <= 0.0 || textureCoordinate.x > 1.0 || textureCoordinate.y <= 0.0 || textureCoordinate.y > 1.0;
4198}
4199
4200void main() {
4201    vec4 mainTexture = texture(uTexture, textureCoordinate);
4202
4203    if (isOutOfBounds(textureCoordinate)) {
4204        FragColor = vec4(0.0, 0.0, 0.0, 0.0);
4205        return;
4206    }
4207
4208    vec4 transitionAppliedResult = applyTransitionFactory();
4209
4210    vec4 filterAppliedResult = lookup(transitionAppliedResult, uLookup);
4211    // Keep the premultiplied-alpha invariant: a color filter (LUT) can lift a
4212    // fully transparent pixel's premultiplied-black rgb to a non-zero color,
4213    // which would composite as an additive halo over transparent areas. Force
4214    // rgb to 0 where alpha is 0.
4215    float outAlpha = transitionAppliedResult.a;
4216    FragColor = vec4(outAlpha > 0.0 ? filterAppliedResult.rgb : vec3(0.0), outAlpha);
4217}`,Eh={[Ml.VIDEO_PLAYER]:null,[Ml.EXPORTER]:null,[Ml.FILTER_PANEL]:null,[Ml.THUMBNAIL]:null,[Ml.TRANSITION]:null};class k5e{ctx;name;canvasVideoRatio;backgroundColor="#000000";DEFAULT_CANVAS_ELEMENT=document.createElement("canvas");hdrCanvas;hdrCanvasContext;sourceSize;lastUniformMap=new Map;constructor(t){this.name=t,this.canvasVideoRatio=he.INIT,this.sourceSize={width:0,height:0},Eh[t]===null&&(Eh[t]=this)}init=t=>{const o=h("glRenderer.ts");try{const r=t.getContext("webgl2",{preserveDrawingBuffer:!0,alpha:!0});if(!r)return o.error("getContext('webgl2') failed."),!1;r.enable(r.BLEND);const n=r.getParameter(r.MAX_TEXTURE_IMAGE_UNITS),a=r.getParameter(r.MAX_VERTEX_ATTRIBS);o.debug("glsl: MAX_TEXTURE_IMAGE_UNITS:"+n+", MAX_VERTEX_ATTRIBS: "+a+"}");const i=Kb(r,TF,SF);return this.initTexture(r,la.MAIN),this.initTexture(r,la.FILTER),this.initTexture(r,la.EFFECT),this.initTexture(r,la.OVERLAY_BASE),this.initTexture(r,la.OVERLAY_EFFECT),r.useProgram(i.program),this.setUniformVariable(fo.Int,"transitionIndex",or.NONE),this.ctx={gl:r,shader:i,canvas:t,alpha:0,flip:void 0,videoTransform:il},t.addEventListener("webglcontextlost",this.handleContextLost),t.addEventListener("webglcontextrestored",this.handleRestoreContext),!0}catch(r){const n="Initialization failed during glRenderer.init() : "+P(r);return h("glRenderer.ts").error(n),!1}};restore=()=>{if(!this.ctx)return;this.clearHDRCanvas();const{gl:t}=this.ctx,o=Kb(t,TF,SF);this.initTexture(t,la.MAIN),this.initTexture(t,la.FILTER),this.initTexture(t,la.EFFECT),this.initTexture(t,la.OVERLAY_BASE),this.initTexture(t,la.OVERLAY_EFFECT),this.ctx.shader=o,t.useProgram(o.program),this.setUniformVariable(fo.Int,"transitionIndex",or.NONE),this.lastUniformMap.forEach(({value:r,type:n},a)=>{this.setUniformVariable(n,a,r)})};handleContextLost=t=>{t.preventDefault(),h("glRenderer.ts").warn("[GLRenderer."+this.name+"] WebGL context lost.")};handleRestoreContext=()=>{if(!this.ctx){h("glRenderer.ts").warn(this.name+" context  doesn't exist");return}this.restore(),h("glRenderer.ts").info("[GLRenderer."+this.name+"] WebGL context restored done.")};
4217updateBackgroundColor=t=>{this.backgroundColor=t};render=async(t,o,r=!1)=>{if(!this.ctx){h("glRenderer.ts").warn(this.name+" context  doesn't exist");const n="[GLRenderer."+this.name+"] "+this.name+" context doesn't exist";throw new C(_.C_GLSL_INIT_ERROR,void 0,n)}try{const{gl:n,shader:a,alpha:i,flip:s,videoTransform:x}=this.ctx;if(n.isContextLost())return h("glRenderer.ts").info("[GLRenderer."+this.name+"] "+this.name+" context is lost. skip rendering"),!1;a.bind(),this.DEFAULT_CANVAS_ELEMENT.width=t.width,this.DEFAULT_CANVAS_ELEMENT.height=t.height;const c=this.DEFAULT_CANVAS_ELEMENT.getContext("2d");c&&(c.fillStyle=this.backgroundColor,c.fillRect(0,0,t.width,t.height));const l=o?o instanceof HTMLVideoElement&&(o===void 0||M_e(o))?this.DEFAULT_CANVAS_ELEMENT:o:this.DEFAULT_CANVAS_ELEMENT,d=r&&l instanceof HTMLVideoElement;!d&&this.clearHDRCanvas();const u=l instanceof HTMLVideoElement?l.videoWidth:l.width,p=l instanceof HTMLVideoElement?l.videoHeight:l.height;if(u===0||p===0||l instanceof HTMLVideoElement&&l.readyState<2)return!1;const f=d?this.getHDRCanvas(l,u,p):l,E=await createImageBitmap(f);n.activeTexture(n.TEXTURE0+la.MAIN),this.updateTexture(n,E),E.close(),this.updateFilterUniforms(i),this.updateFlipUniforms(s),this.updateVideoSize(t),this.updateVideoTransformUniforms(x);const T=n.canvas.getContext("2d");return T&&(T.fillStyle=this.backgroundColor,T.fillRect(0,0,t.width,t.height)),lJ(this.ctx.gl),!0}catch(n){return h("glRenderer.ts").error("[GLRenderer."+this.name+"] Error Occur while rendering : "+P(n)),!1}};getHDRCanvas=(t,o,r)=>{if(this.hdrCanvas===void 0||this.hdrCanvas.width!==o||this.hdrCanvas.height!==r||this.hdrCanvasContext===void 0){const n=new OffscreenCanvas(o,r),a=n.getContext("2d",{colorSpace:"srgb"})??void 0;if(!a)return h("glRenderer.ts").warn("[GLRenderer."+this.name+"] sRGB canvas creation failed; skipping HDR conversion."),this.hdrCanvas=void 0,this.hdrCanvasContext=void 0,t;this.hdrCanvas=n,this.hdrCanvasContext=a}return this.hdrCanvasContext?(this.hdrCanvasContext.clearRect(0,0,o,r),this.hdrCanvasContext.drawImage(t,0,0,o,r),this.hdrCanvas):t};clearHDRCanvas=()=>{this.hdrCanvas=void 0,this.hdrCanvasContext=void 0};initTexture=(t,o)=>{const r=t.createTexture();if(r===null)throw h("glRenderer.ts").error("Cannot create texture"),new Error("Cannot create texture, unit: "+o);return t.activeTexture(t.TEXTURE0+o),t.bindTexture(t.TEXTURE_2D,r),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),o===la.MAIN?(t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_BASE_LEVEL,0),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAX_LEVEL,0)):(t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,t.LINEAR)),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0),r};updateTexture=(t,o)=>{try{if(o instanceof OffscreenCanvas){t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,o.transferToImageBitmap());return}t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,o)}catch(r){h("glRenderer.ts").error("Cannot update texture : "+P(r))}};getCanvas=()=>this.ctx?.canvas;setVideoRatio=t=>{this.canvasVideoRatio=t};setFlip=t=>{this.ctx&&(this.ctx.flip=t)};setVideoTransform=t=>{this.ctx&&(this.ctx.videoTransform=t)};updateViewport=(t,o)=>{this.ctx&&this.ctx.gl.viewport(0,0,t,o)};updateCanvasSize=(t,o)=>{this.ctx&&(this.ctx.canvas.width=t,this.ctx.canvas.height=o)};setFilterImage=(t,o)=>{if(!this.ctx)return;if(t===void 0){this.ctx.alpha=0;return}const{filterImage:r,filterAlpha:n}=t;this.ctx.gl.activeTexture(this.ctx.gl.TEXTURE0+la.FILTER),this.updateTexture(this.ctx.gl,r),this.ctx.gl.activeTexture(this.ctx.gl.TEXTURE0+la.MAIN),this.ctx.alpha=o?0:n};updateFilterUniforms=t=>{this.ctx&&(this.setUniformVariable(fo.Sampler2D,"uTexture",la.MAIN),this.setUniformVariable(fo.Sampler2D,"uLookup",la.FILTER),this.setUniformVariable(fo.Float,"filterAlpha",t))};updateFlipUniforms=t=>{if(!this.ctx)return;const{shader:o}=this.ctx;o.uniforms.flip=t||Go.NONE};updateVideoSize=t=>{this.sourceSize=t};updateVideoTransformUniforms=t=>{if(!this.ctx)return;const{gl:o}=this.ctx;o.clearColor(0,0,0,0),o.clear(o.COLOR_BUFFER_BIT);const{zoomX:r,zoomY:n,xPos:a,yPos:i}=this._getGlRatioTransformZoomInfo(t);this.setUniformVariable(fo.Float,"transformZoomX",r),this.setUniformVariable(fo.Float,"transformZoomY",n),this.setUniformVariable(fo.Float,"transformXPos",a),this.setUniformVariable(fo.Float,"transformYPos",i),this.setUniformVariable(fo.Float,"transformRotation",-L5e.toRadian(t.rotation)),this.setUniformVariable(fo.Float,"aspectRatio",this.sourceSize.width/this.sourceSize.height)};_getGlRatioTransformZoomInfo=t=>{const{zoomX:o,zoomY:r,xPos:n,yPos:a}=b4(t,this.canvasVideoRatio,this.sourceSize);return{zoomX:o,zoomY:r,xPos:n,yPos:a}};setUniformVariable=(t,o,r)=>{if(!this.ctx)return;const{gl:n,shader:a}=this.ctx;try{const i=n.getUniformLocation(a.program,o);switch(i===null&&h("glRenderer.ts").warn("Cannot find uniform location: "+o),this.lastUniformMap.set(o,{type:t,value:r}),t){case fo.Float:n.uniform1f(i,r);break;case fo.Int:n.uniform1i(i,r);break;case fo.Vec2:n.uniform2fv(i,r);break;case fo.Vec3:n.uniform3fv(i,r);break;case fo.Vec4:n.uniform4fv(i,r);break;case fo.Ivec2:n.uniform2iv(i,r);break;case fo.Ivec3:n.uniform3iv(i,r);break;case fo.Ivec4:n.uniform4iv(i,r);break;case fo.Bvec2:n.uniform2iv(i,r);break;case fo.Bvec3:n.uniform3iv(i,r);break;case fo.Bvec4:n.uniform4iv(i,r);break;case fo.Mat2:n.uniformMatrix2fv(i,!1,r);break;case fo.Mat3:n.uniformMatrix3fv(i,!1,r);break;case fo.Mat4:n.uniformMatrix4fv(i,!1,r);break;case fo.Bool:n.uniform1i(i,r);break;case fo.Sampler2D:n.uniform1i(i,r);break;case fo.SamplerCube:n.uniform1i(i,r);break;case fo.Sampler2DArray:n.uniform1i(i,r);break;case fo.Sampler3D:n.uniform1i(i,r);break}}catch(i){h("glRenderer.ts").error("Error Occur while setUniformVariable : "+P(i));return}}}const qCt=e=>Eh[e]?Eh[e]:null,L8=960,M8=(e,t=L8)=>e>=1?{width:On(t),height:On(Math.ceil(t/e))}:{width:On(Math.ceil(t*e)),height:On(t)},F5e=(e,t)=>Math.max(e,t)<=L8?{width:On(e),height:On(t)}:M8(e/t),WA=(e,t)=>
4217{let o,r;return e/t<wE/NE?(o=NE*e/t,r=NE):(o=wE,r=wE*t/e),{width:Math.floor(o),height:Math.floor(r)}},QCt=(e,t,o)=>{const r=WA(e.width,e.height),n=N4(r.width,r.height,!1,o),a=WA(n.width,n.height);return{width:a.width*t,height:a.height*t}},U5e=2,OF=5,CF=3,RF=256,V5e=3e4;class G5e{sources={};tokens={};pendingRequests={};idleTimers={};pendingTimers={};videos={};hlsInstances={};canvases={};mediaThumbnailSizes={};lastRenderedMediaId;worker;filterMediaId=Gl;filterAlpha;canvas;glRenderer;errorRetryCount=0;assetErrorRetryCount=0;flip;assetVideo;assetCanvas;elementId="assetVideoThumbExtracter";currentAssetMediaId=null;currentAssetBlobUrl=null;currentAssetResolve=null;constructor(){this.worker=new P8,this.flip=Go.NONE,this.canvas=document.createElement("canvas"),this.canvas.width=RF,this.canvas.height=RF,this.assetVideo=document.createElement("video"),this.assetCanvas=document.createElement("canvas"),this.assetVideo.crossOrigin="anonymous",this.assetVideo.id=this.elementId,this.assetVideo.onseeked=this.assetSeekListener,this.assetVideo.onerror=this.assetErrorListener;const t=new k5e(Ml.THUMBNAIL);t.init(this.canvas)?this.glRenderer=t:h("thumbnail.ts").warn("Cannot init glRenderer for thumbnail."),this.lastRenderedMediaId="",se().getEventEmitter().on(co.NEWFILE,(r,n,a)=>{a&&this.resetFilterState()}).on(co.RESET,()=>{this.resetFilterState()})}resetFilterState=async()=>{if(this.filterMediaId=Gl,this.filterAlpha=void 0,this.flip=Go.NONE,this.glRenderer){const t=await wC.get(Gl);this.glRenderer.setFilterImage({filterImage:t,filterAlpha:vh},!0),this.glRenderer.setFlip(Go.NONE)}h("thumbnail.ts").info("[ThumbnailQueue] Filter state reset for new project")};getAssetThumbnail=async(t,o)=>{if(this.currentAssetMediaId===t&&this.currentAssetBlobUrl)return this.setAssetVideoSrc(this.currentAssetBlobUrl),this.setAssetVideoTime(o),!0;const r=await this.createNewAssetBlobUrl(t);return r?(this.setAssetVideoSrc(r),this.setAssetVideoTime(o),!0):!1};async createNewAssetBlobUrl(t){this.revokeCurrentAssetBlobUrl();const o=gd(t);if(o)return this.currentAssetMediaId=t,this.currentAssetBlobUrl=null,an(o);const r=await En(t);if(!r)return this.currentAssetMediaId=null,null;const n=URL.createObjectURL(r);return this.currentAssetMediaId=t,this.currentAssetBlobUrl=n,n}revokeCurrentAssetBlobUrl(){this.currentAssetBlobUrl&&(URL.revokeObjectURL(this.currentAssetBlobUrl),this.currentAssetBlobUrl=null)}setAssetVideoSrc(t){this.assetVideo.src!==t&&(this.assetVideo.src=t)}setAssetVideoTime(t){this.assetVideo.currentTime===t?this.assetVideo.currentTime=t+.01:this.assetVideo.currentTime=t}assetSeekListener=()=>{this.assetErrorRetryCount=0;const t=80,o=this.assetVideo.videoWidth,r=this.assetVideo.videoHeight,n=o/r;this.assetCanvas.width=t*n,this.assetCanvas.height=t,this.assetCanvas.getContext("2d").drawImage(this.assetVideo,0,0,t*n,t);const a=this.assetCanvas.toDataURL();this.currentAssetResolve?.(a),this.currentAssetResolve=null};assetErrorListener=async t=>{const o=this.assetVideo.error;if(h("thumbnail.ts").warn("Asset video error. error code: "+o?.code+", message: "+o?.message),this.assetErrorRetryCount+=1,this.assetErrorRetryCount>CF){h("thumbnail.ts").error("Asset thumbnail loading failed after "+CF+" retries"),this.currentAssetResolve?.($r),this.currentAssetResolve=null,this.assetErrorRetryCount=0;return}if(Bf(this.assetVideo.src)&&this.assetVideo.error?.code===Ub.MEDIA_ERR_NETWORK){await ol(),this.assetVideo.load();return}this.currentAssetResolve?.($r),this.currentAssetResolve=null};registerSource=(t,o,r)=>{r?this.sources[t]&&this.disposeSourceVideo(t):this.clearAllSourceVideos();const n=an(o);this.sources[t]={src:n,isHls:this.isHlsStream(n)},this.tokens[t]??=0};extract=async(t,o,r,n,a,i)=>{if(t<0)return $r;this.glRenderer&&this.glRenderer.setVideoRatio(he.INIT);const s=this.glRenderer&&(this.filterMediaId!==n||this.filterAlpha!==a)?wC.get(n):void 0;return this.worker.next(async()=>{if(this.glRenderer&&(this.filterMediaId!==n||this.filterAlpha!==a)){const l=s!==void 0?await s:await wC.get(n),d=Xp(n);this.filterMediaId=n,this.filterAlpha=a,this.glRenderer.setFilterImage({filterImage:l,filterAlpha:a},d)}if(this.glRenderer&&this.flip!==i&&(this.flip=i),r())return $r;if(this.sources[o]){this.idleTimers[o]!==void 0&&(clearTimeout(this.idleTimers[o]),delete this.idleTimers[o]),this.videos[o]&&this.videos[o].readyState<HTMLMediaElement.HAVE_CURRENT_DATA&&this.disposeSourceVideo(o);const l=this.tokens[o]??0;return await new Promise(u=>{if(this.pendingRequests[o]={resolve:u,time:t,token:l},this.videos[o]){const p=this.videos[o];p.currentTime=t===p.currentTime?t+.01:t}else this.createSourceVideoForExtract(o)}).finally(()=>{this.videos[o]&&this.sources[o]?this.scheduleIdleDispose(o):delete this.pendingRequests[o]})}const x=new Promise(l=>{this.currentAssetResolve=l});return!await this.getAssetThumbnail(o,t)&&(this.currentAssetResolve?.($r),this.currentAssetResolve=null),x})};onSeeked=async(t,o,r)=>{this.errorRetryCount=0;
4217try{const n=this.canvases[t];if(!n){r($r);return}const a=n.getContext("2d");if(!a){h("thumbnail.ts").error("On ThumbnailQueue, No 2d context from canvas."),r($r);return}const i=this.flip;if(this.glRenderer&&this.lastRenderedMediaId!==t){this.lastRenderedMediaId=t;const s=this.mediaThumbnailSizes[t];this.canvas.width=s.width,this.canvas.height=s.height,this.glRenderer.updateViewport(this.canvas.width,this.canvas.height)}if(this.glRenderer&&t!==_o&&(!Xp(this.filterMediaId)||i!==void 0)){this.glRenderer.setFlip(i);const s=se().getInitProjectVideoSize(),x=Yu(t),c=P2(x?.videoAudioMetaInfo.videoInfo?.colorSpace);if(await this.glRenderer.render(s,this.videos[t],c),this.tokens[t]!==o){r($r);return}}this.captureOrRetry(a,t,o,r)}catch{r($r)}};isHlsStream=t=>t.includes(Ph)&&Lx.isSupported();setupHlsPlayback=(t,o,r,n)=>{const a=H5e();a.loadSource(o),a.attachMedia(t),a.on(Lx.Events.MANIFEST_PARSED,()=>{this.tokens[r]===n&&t.play()}),a.on(Lx.Events.ERROR,(i,s)=>{this.tokens[r]===n&&S4(s)}),this.hlsInstances[r]=a};createSourceVideoForExtract=t=>{const o=document.createElement("video");o.crossOrigin="anonymous",o.oncanplaythrough=()=>{const a=this.pendingRequests[t];a&&(this.initializeThumbnailSize(t),o.currentTime=a.time===o.currentTime?a.time+.01:a.time)},o.onseeked=()=>{const a=this.pendingRequests[t];a&&this.onSeeked(t,a.token,a.resolve)},o.onerror=()=>{const a=this.pendingRequests[t];a&&this.onError(t,a.token,a.resolve)};const{src:r,isHls:n}=this.sources[t];n?this.setupHlsPlayback(o,r,t,this.tokens[t]??0):o.src=r,this.videos[t]=o};scheduleIdleDispose=t=>{delete this.pendingRequests[t],this.idleTimers[t]!==void 0&&clearTimeout(this.idleTimers[t]),this.idleTimers[t]=setTimeout(()=>{delete this.idleTimers[t],this.disposeSourceVideo(t)},V5e)};disposeSourceVideo=t=>{this.pendingRequests[t]?.resolve($r),delete this.pendingRequests[t],this.idleTimers[t]!==void 0&&(clearTimeout(this.idleTimers[t]),delete this.idleTimers[t]);const o=this.hlsInstances[t];o&&(o.detachMedia(),o.destroy(),delete this.hlsInstances[t]);const r=this.videos[t];r&&(r.pause(),r.removeAttribute("src"),r.load(),r.oncanplaythrough=null,r.onseeked=null,r.onerror=null,delete this.videos[t]),delete this.canvases[t],this.pendingTimers[t]!==void 0&&(clearTimeout(this.pendingTimers[t]),delete this.pendingTimers[t]),this.lastRenderedMediaId===t&&(this.lastRenderedMediaId=""),this.tokens[t]=(this.tokens[t]??0)+1,this.errorRetryCount=0};clearAllSourceVideos=()=>{new Set([...Object.keys(this.videos),...Object.keys(this.sources)]).forEach(o=>this.disposeSourceVideo(o)),this.sources={},this.revokeCurrentAssetBlobUrl(),this.currentAssetMediaId=null,this.currentAssetResolve?.($r),this.currentAssetResolve=null};initializeThumbnailSize=t=>{if(this.mediaThumbnailSizes[t]!==void 0){if(!this.canvases[t]){const i=this.mediaThumbnailSizes[t],s=document.createElement("canvas");s.width=i.width,s.height=i.height,this.canvases[t]=s}return}let{videoWidth:o,videoHeight:r}=this.videos[t];if(o===0||r===0){const i=Yu(t);if(i!==void 0&&i.videoAudioMetaInfo.videoInfo===void 0)o=1920,r=1080;else return}const n=F5e(o,r);this.mediaThumbnailSizes[t]=n;const a=document.createElement("canvas");a.width=n.width,a.height=n.height,this.canvases[t]=a};captureOrRetry=(t,o,r,n,a=0)=>{if(a>10){delete this.pendingTimers[o],n($r);return}const i=this.mediaThumbnailSizes[o];if(!i){h("thumbnail.ts").error("Cannot find thumbnail size of mediaId "+o),delete this.pendingTimers[o],n($r);return}if(!this.videos[o]){h("thumbnail.ts").error("Cannot find thumbnail video of mediaId "+o),delete this.pendingTimers[o],n($r);return}const x=i.width,c=i.height;try{let l;const d=this.flip;this.glRenderer&&(!Xp(this.filterMediaId)||d!==void 0)?l=this.canvas.toDataURL(im,sm):(t.drawImage(this.videos[o],0,0,x,c),l=this.canvases[o].toDataURL(im,sm)),l.length<128?(this.pendingTimers[o]&&clearTimeout(this.pendingTimers[o]),this.pendingTimers[o]=setTimeout(()=>{this.tokens[o]===r&&this.captureOrRetry(t,o,r,n,a+1)},200)):(delete this.pendingTimers[o],n(l))}catch(l){h("thumbnail.ts").warn(l),delete this.pendingTimers[o],n($r)}};onError=async(t,o,r)=>{const n=this.videos[t];if(!n){r($r);return}const a=gd(t);if(Oo()&&a){const c=Vi(t);try{const l=await Ue().existsFile(a);if(this.tokens[t]!==o){r($r);return}if(!l){const d=_.D_ERR_SOURCE_FILE_LOST;h("thumbnail.ts").error(d+" Thumbnail loading error: Local file not found - "+a+" (location: "+c?.fileLocation+") for mediaId: "+t),Y().error(d,Ot(d,{defaultKey:""})),r($r);return}}catch(l){if(h("thumbnail.ts").error("Failed to check local file existence for thumbnail: "+a,l),this.tokens[t]!==o){r($r);return}const d=_.D_ERR_SOURCE_FILE_LOST;Y().error(d,Ot(d,{defaultKey:""})),r($r);return}}if(this.errorRetryCount+=1,this.errorRetryCount>OF){const{readyState:c,error:l}=n;
4217h("thumbnail.ts").error("Thumbnail loading failed after "+OF+" retries for "+t+", readyState: "+c+(l?", mediaError: "+l.message:"")),r($r),this.errorRetryCount=0;return}const{readyState:i,error:s}=n;if(Bf(n.src)&&s?.code===Ub.MEDIA_ERR_NETWORK&&(await ol(),this.tokens[t]!==o)){r($r);return}const x=Math.pow(U5e,this.errorRetryCount)*1e3;h("thumbnail.ts").error("Thumbnail loading error : for "+t+", readyState : "+i+", "+(s?", mediaError : "+s.message:"")+", retryInterval : "+x),this.pendingTimers[t]&&clearTimeout(this.pendingTimers[t]),this.pendingTimers[t]=setTimeout(()=>{this.tokens[t]===o&&n.load()},x)}}let qE;const D8=()=>(qE===void 0&&(qE=new G5e),qE),W5e=()=>{qE?.clearAllSourceVideos()},H5e=()=>new Lx({enableWorker:!0,lowLatencyMode:!1,maxBufferLength:2,maxMaxBufferLength:5,maxBufferSize:5*1024*1024,enableWebVTT:!1,startFragPrefetch:!1,testBandwidth:!1,xhrSetup:e=>{e.withCredentials=!0}}),k8=(e,t,o,r,n,a)=>{const i=[];for(const s of e){const x=[],c=vo(s),l=c+ac(s),{bgmTimelineRanges:d,soundEffectTimelineRanges:u}=a(c,l);if(xs(s)<o)continue;const{words:p}=s;for(let f=0;f<p.length-1;f++){if(Nm(s,f)<o||p[f].type===Z.ENTER)continue;const E=p[f],T=HA(s,E,d,u,r,n);x.push({word:E,sceneIndex:t,position:Nm(s,f),playTargetSubMediaTracks:T,assetIds:[...s.assetIds,...E.assetIds]})}i.push(...x)}return i},j5e=(e,t,o,r,n)=>k8(e,t,0,o,r,n),HA=(e,t,o,r,n,a)=>{const i=[],x=Rn(t),c=t.timelineStart;e.assetIds.forEach(l=>{const d=L.get(a,l);if(!d)return;if(d.role!=="sub"){h("videoPlay.ts").warn("Clip has main asset: "+l);return}const u=d.trackIds.map(W=>L.get(n,W)).find(W=>W!==void 0&&ll(W));if(!u)return;const p=L.get(o,l);if(p===void 0)return;const{timelineStart:f,mediaId:E}=p,T=eo(E);if(T===void 0){h("videoPlay.ts").warn(`
4218        [Error occured in getPlayTargetMediaTracks.]
4219        This is logic error.
4220        There is audioTrack. but there is no audioInfo.
4221        trackEntries : `+JSON.stringify(n)+`
4222        assetEntries : `+JSON.stringify(a)+`
4223        assetId : `+l+`
4224      `);return}const O=parseFloat((c-f).toFixed(2));if(O<0)return;const S=u.loop?p.timelineEnd-f:Math.min(ZR(T,u),p.timelineEnd-f),R=f+S,y=Math.min(x,R-c),v=Math.abs(f-c)<1e-6,w=Math.abs(R-(c+y))<1e-6,N=v&&u.fade?.in===!0,M=w&&u.fade?.out===!0,k=N||M?YE(S):0,F=N?k:0,G=M?k:0,B=O+y;O<B&&i.push({startTime:O,duration:y,assetId:l,mediaId:E,fadeInDuration:F,fadeOutDuration:G})});for(const l in r){const d=Je(l),{timelineStart:u,timelineEnd:p,mediaId:f}=r[d];if(!$7(u,p,c,c+x,!1))continue;const T=parseFloat((c-u).toFixed(2));if(T<0)continue;const O=Math.min(Rn(t),p-c),S=T+O;T<S&&i.push({startTime:T,duration:O,assetId:d,mediaId:f,fadeInDuration:0,fadeOutDuration:0})}return i},z5e=(e,t)=>{let o=Object.entries(e).sort((n,a)=>a[1].timelineStart-n[1].timelineStart),r=Object.entries(t).sort((n,a)=>a[1].timelineStart-n[1].timelineStart);return(n,a)=>{const i={bgmTimelineRanges:{},soundEffectTimelineRanges:{}};o=o.filter(s=>s[1].timelineEnd>=n),r=r.filter(s=>s[1].timelineEnd>=n);for(let s=o.length-1;s>=0;s--){const x=o[s];if(x[1].timelineStart>=a)break;i.bgmTimelineRanges[Je(x[0])]=x[1]}for(let s=r.length-1;s>=0;s--){const x=r[s];if(x[1].timelineStart>=a)break;i.soundEffectTimelineRanges[Je(x[0])]=x[1]}return i}},Y5e=(e,t,o,r,n,a,i,s,x,c)=>{const l=t[o],{clips:d}=l;if(d===void 0||d.length===0)throw new C(_.C_LOGIC_ERROR,{},"No clips or empty clips");const u=s5(c,s,x),p=z5e(u,i);switch(e){case uo.PLAY_ALL:{const f=[];for(let E=0;E<t.length;E++)if(!(E<o))if(E===o){const{clips:T}=t[E];f.push(...k8(T,E,r,s,x,p))}else{const{clips:T}=t[E];f.push(...j5e(T,E,s,x,p))}return NC(f)}case uo.PLAY_CLIP:{const f=[],E=t.flatMap(S=>S.clips),T=t[o],O=n.includes(Co(T.clips,r,!0)+T.globalClipRange.from);return n.forEach(S=>{const R=Hm(S,c),y=E[S],v=y.words,w=[];v.forEach((N,M)=>{w.push({word:N,sceneIndex:R,position:Nm(y,M),playTargetSubMediaTracks:HA(y,N,u,i,s,x),assetIds:[...y.assetIds,...N.assetIds]})}
4224),w.forEach(N=>{N.word.type!==Z.ENTER&&(O&&N.position+c[t[N.sceneIndex].globalClipRange.from].startPosition<r+c[T.globalClipRange.from].startPosition||f.push(N))})}),NC(f)}case uo.PLAY_WORDS:if(a){const{from:f,to:E}=G0(a),T=c[a.globalClipIndex],O=Hm(a.globalClipIndex,c),S=c[t[O].globalClipRange.from],R=S.startPosition,y=T.words.slice(f,E).map((v,w)=>({word:v,sceneIndex:O,position:T.startPosition-R+f+w,playTargetSubMediaTracks:HA(T,v,u,i,s,x),assetIds:[...T.assetIds,...v.assetIds]})).filter(({position:v,word:w})=>v>=r&&w.type!==Z.ENTER);return NC(y)}break}return h("videoPlay.ts").error("no play target words error [getPlayTargetWords()]"),[]},ms=(e,t,o,r,n,a,i,s,x,c,l,d,u)=>{const p=Y5e(e,t,a,n,o,r,c,l,d,u);return{playType:e,playTargetWords:p,playPosition:n,playSceneIndex:a,playStartClipIndex:i,playMethod:s,preservePlayCursor:x}},NC=e=>{const t=[];let o=0;return e.forEach(r=>{t.push({...r,accStartDuration:o}),o+=Rn(r.word)}),t},ZCt=e=>{const t=Mt(ke.EDIT_OVERLAY),o=L.get(t,e),r={...t,[e]:!o};po(ke.EDIT_OVERLAY,r),hUe(e,!o)},B5e=(e,t)=>({type:lo.MOVE_CURSOR_TO_LEFT,payload:{shiftKey:e,captionDisplayMode:t}}),K5e=(e,t)=>({type:lo.MOVE_CURSOR_TO_RIGHT,payload:{shiftKey:e,captionDisplayMode:t}}),X5e=(e,t,o,r,n,a,i,s,x,c,l)=>({type:lo.MOVE_CURSOR_TO_POSITION,payload:{sceneIndex:e,position:t,shiftKey:o,method:r,fromClip:n,clickedPos:i,currentClipIndex:s,onWord:x,draggingWord:c,preservePreviousRange:l,captionDisplayMode:a}}),ux=(e,t,o)=>({type:o,payload:{shiftKey:e,captionDisplayMode:t}}),jA=(e,t=!1)=>ux(t,e,lo.MOVE_CURSOR_TO_WORD_IN_NEXT_CLIP),F8=(e,t=!1)=>ux(t,e,lo.MOVE_CURSOR_TO_WORD_IN_PREV_CLIP),J5e=(e,t)=>({type:lo.MOVE_CURSOR_TO_CAPTIONFIELD,payload:{editCaption:e,globalClipIndex:t}}),q5e=(e,t)=>({type:lo.MOVE_CURSOR_TO_CAPTIONFIELD_AND_PAUSE,payload:{editCaption:e,globalClipIndex:t}}),B0=(e,t)=>o=>{const r=ld()?.sessionState.snapshot.playingContext?.playMethod??null;if(e===null)return;const n=r===pr.BUTTON||r===pr.PREVIEW_CLICK||r===pr.SPACE?q5e(e,t):J5e(e,t);o(n)},Q5e=e=>(t,o)=>{const r=o(),{cursorMode:n,editCaption:a,globalPosition:i}=jo(r),s=xn(r),x=He(r),c=Er(x,i);if(tl(x,c))return t;switch(n){case we.INSERT_CURSOR:case we.CLIP:return t(jA(s,e));case we.CAPTION:{if(!a)break;const l=c+1,d=vt(a,u=>{u.globalClipIndex=l,u.initCaretPosition=void 0});return t(B0(d,l))}}return t},Z5e=e=>(t,o)=>{const r=o(),{cursorMode:n,editCaption:a,globalPosition:i}=jo(r),s=xn(r),x=He(r),c=Er(x,i);if(Kg(x,c))return t;switch(n){case we.INSERT_CURSOR:case we.CLIP:return t(F8(s,e));case we.CAPTION:{if(!a)break;const l=c-1,d=vt(a,u=>{u.globalClipIndex=l,u.initCaretPosition=void 0});return t(B0(d,l))}}return t},$5e=e=>(t,o)=>{const r=o(),{cursorMode:n,editCaption:a,globalPosition:i}=jo(r),s=xn(r),x=He(r),c=Er(x,i);switch(n){case we.INSERT_CURSOR:{const l=pH(s);return l===null?tl(x,c)?t:t(jA(s,e)):t(B0({globalClipIndex:c,captionIndex:l},c))}case we.CAPTION:{if(!a)break;const l=gH(a.captionIndex,s);if(l===null)return tl(x,c)?t:t(jA(s,e));const d=vt(a,u=>{u.captionIndex=l});return B0(d,c)(t)}}return t},eze=e=>(t,o)=>{const r=o(),{cursorMode:n,editCaption:a,globalPosition:i}=jo(r),s=xn(r),x=He(r),c=Er(x,i);switch(n){case we.INSERT_CURSOR:{if(Kg(x,c))return t;const l=fH(s);if(l===null)return t(F8(s,e));const d=c-1;return t(B0({globalClipIndex:d,captionIndex:l},d))}case we.CAPTION:{if(!a)break;const l=_H(a.captionIndex,s);if(l===null)return t(yu());const d=vt(a,u=>{u.captionIndex=l});return t(B0(d,c))}}return t},tze=e=>(t,o)=>{const r=o(),{cursorMode:n,editCaption:a,globalPosition:i,globalWordRange:s}=jo(r),x=xn(r),c=He(r),l=Er(c,i);switch(n){case we.INSERT_CURSOR:{if(s)return t(yu());const d=e?fH(x):pH(x);return d===null?t:t(B0({globalClipIndex:l,captionIndex:d},l))}case we.CAPTION:{if(!a)break;const d=e?_H(a.captionIndex,x):gH(a.captionIndex,x);if(d===null)return t(yu());const u=vt(a,p=>{p.captionIndex=d});return t(B0(u,l))}}return t(yu())},zP=(e,t,o,r)=>({type:lo.MOVE_CURSOR_TO_SELECTED_ELEMENT,payload:{elementId:e,elementType:t,globalPosition:o,selectedFromAssetList:r??!1}}),oze=e=>({type:lo.CURSOR_TEXT_SELECT,payload:{textSelection:e}}),$Ct=(e,t)=>
4224({type:lo.SELECT_CAPTION_OVERLAY,payload:{globalClipIndex:e,captionIndex:t}}),rze=(e,t,o,r)=>({type:lo.MOVE_CURSOR_TO_SELECTED_ELEMENTS,payload:{elements:e,globalPosition:t,shouldFlush:o,selectedFromAssetList:r??!1}}),eRt=(e,t,o)=>({type:lo.DESELECT_GLOBAL_MULTI_ELEMENTS,payload:{deselectElements:e,globalPosition:t,selectedFromAssetList:o??!1}}),tRt=(e,t)=>({type:lo.MOVE_CURSOR_TO_SELECTED_WATERMARK,payload:{watermarkId:e,position:t}}),nze=e=>({type:lo.SET_SELECTED_FROM_ASSET_LIST,payload:{selectedFromAssetList:e}}),aze=e=>({type:lo.USE_DISABLED_CURSOR,payload:{preserveWordRange:e}}),ize=(e=!0)=>(t,o)=>{const r=o();return Zx(r)===we.DISABLED?t:t(aze(e))},U8=(e=!1)=>(t,o)=>{const r=xn(o());return t(B5e(e,r))},sze=(e=!1)=>(t,o)=>{const r=xn(o());return t(K5e(e,r))},AF=(e,t=0,o=!1,r=Bx.MOUSE,n=!1,a,i,s,x,c)=>(l,d)=>{const u=xn(d());l(X5e(e,t,o,r,n,u,a,i,s,x,c))},yF=(e,t=void 0,o=!1)=>(r,n)=>{const a=n();Zx(a)!==we.CORRECTING&&WDe(e),r({type:lo.TOGGLE_WORD_CORRECTOR,payload:{shiftKey:o,globalPosition:t}})},xze=()=>e=>e({type:lo.SELECT_ALL}),cze=e=>(t,o)=>{const r=xn(o());t(ux(e,r,lo.MOVE_CURSOR_TO_THE_FIRST_OF_PARAGRAPH))},lze=e=>(t,o)=>{const r=xn(o());t(ux(e,r,lo.MOVE_CURSOR_TO_THE_LAST_OF_PARAGRAPH))},dze=e=>(t,o)=>{const r=xn(o());t(ux(e,r,lo.MOVE_CURSOR_TO_THE_FIRST_OF_LINE))},uze=e=>(t,o)=>{const r=xn(o());t(ux(e,r,lo.MOVE_CURSOR_TO_THE_LAST_OF_LINE))},pze=e=>(t,o)=>{const r=xn(o());t(ux(e,r,lo.MOVE_CURSOR_TO_THE_TOP))},fze=e=>(t,o)=>{const r=xn(o());t(ux(e,r,lo.MOVE_CURSOR_TO_THE_BOTTOM))},oRt=e=>t=>t({type:lo.SET_CORRECTING_FOCUS,payload:{inputFocus:e}}),gze=e=>t=>t({type:lo.SET_WORD_CORRECTOR_RANGE,payload:{positionRange:e}}),_ze=e=>(t,o)=>{const r=xn(o());t(ux(e,r,lo.MOVE_CURSOR_TO_NEXT_WORD))},Eze=e=>(t,o)=>{const r=xn(o());t(ux(e,r,lo.MOVE_CURSOR_TO_PREV_WORD))},yu=()=>({type:lo.DESELECT_CURSOR}),V8=(e,t,o)=>{const{startPosition:r,words:n}=t;let a=t.startPosition;return o&&Sce(o,t)&&(a=r+n.length-1),{type:lo.MOVE_CURSOR_TO_SPECIFIC_POSITION,payload:{sceneIndex:e,position:a}}},G8=(e,t)=>({type:lo.MOVE_CURSOR_TO_SPECIFIC_POSITION,payload:{sceneIndex:e,position:t}}),T_=(e,t=!1)=>({type:lo.INSERT_CURSOR_TO_POSITION,payload:{globalPosition:e,selectWord:t}}),W8=(e,t)=>({type:lo.UPDATE_CURSOR_POSITION,payload:{globalPosition:e},...t?{meta:t}:{}}),rRt=e=>(t,o)=>{const r=o(),n=mo(r),a=n.find(x=>x.id===e);if(!a)return;const i=He(r),s=i[a.globalClipRange.from];if(s!==void 0)return t({type:lo.INSERT_CURSOR_TO_POSITION,payload:{globalPosition:s.startPosition}})},nRt=()=>(e,t)=>{const o=t(),r=He(o),n={type:lo.SELECT_GLOBAL_CLIPS_BY_RANGE,payload:{start:0,end:r.length}};return e(n)},mze=e=>(t,o)=>{const r=o(),n=He(r),a=ci(n).at(e);if(a===void 0)return;const i={type:lo.SELECT_GLOBAL_CLIPS_BY_RANGE,payload:{start:a.globalClipRange.from,end:a.globalClipRange.to}};return t(i)},hze=e=>({type:lo.MOVE_CURSOR_TO_SPECIFIC_GLOBAL_POSITION,payload:{globalPosition:e}}),aRt=(e,t)=>({type:lo.MOVE_GLOBAL_DISABLED_CURSOR_TO_SPECIFIC_POSITION,payload:{globalPosition:e,forceScroll:t}}),Ize=e=>(t,o)=>{const r=o(),n=He(r),a=n.at(e);a!==void 0&&t(T_(a.startPosition))},H8=(e,t)=>(o,r)=>{Mg(r())&&o(IK(!1));const a=e.map(x=>x.mediaId),i={type:Ga.ADD_MEDIA_ID,payload:{mediaIds:a}};o(i),e.forEach((x,c)=>{const{mediaId:l,src:d}=x,u=t||c>0;D8().registerSource(l,d,u)});const s={type:Ga.RECEIVE_VIDEO,payload:{payloads:e,appendMedia:t}};o(s)},YP=(e,t)=>(o,r)=>{Mg(r())&&o(IK(!1));const a=e.map(i=>i.mediaId);o({type:Ga.ADD_AUDIO_ID,payload:{audioIds:a}}),o({type:Ga.RECEIVE_AUDIO,payload:{payloads:e,appendMedia:t}})},Tze=()=>({type:Ga.CLEAR_MEDIA}),Sze=(e,t=uo.PLAY_DEFAULT)=>(o,r)=>{const n=r(),a=fI(n),i=ld()?.sessionState.snapshot,s=E2(n),x=ec(n),{mediaIds:c,audioIds:l}=a,d=i?.playCursor===null||i?.playCursor===void 0?null:{sceneIndex:i.playCursor.sceneIndex,position:i.playCursor.sceneLocalPosition},u=i?.playingContext??null,p=Pg(n),f=Zx(n),E=_0(n),T=OW(n),O=lt(n),S=ht(n),R=Nn(n),y=Do(n),v=He(n),w=PW(n);if(p===null)return null;const N=wc(p,v);if(N===null)return null;const M=u?.playStartClipIndex??null,k=u?.lastPlayType??null,F=!w||k===uo.PLAY_CLIP&&d!==null&&Ice(y,N,d.position);if(!c.every(te=>l.includes(te)))return Eke(),xt.info(A("player.load")),{kind:"audio_not_ready"};if(!u&&!IF().checkPlayAvailability())return IF().alertBlockNoti(),{kind:"play_not_available"};if(f===we.CORRECTING&&jP(ld())?.resetTimelinePlayback(),(f===we.ELEMENT&&t!==uo.PLAY_ASSET_ANIMATION||f===we.WATERMARK||f===we.CORRECTING||w&&(e===pr.BUTTON||e===pr.PREVIEW_CLICK))&&o(yu()),Aze(e,u!==null,d?.position,f,M,y),u===null&&o(B6e(!0)),u!==null)return{kind:"stop_active",payload:{preservePlayCursor:F}};const G=t!==uo.PLAY_DEFAULT?t:Rze(n),B=rt(n),{soundEffectTimelineRanges:W,overdubInfosMap:Q}=B,j=xa(n),$=mo(n),q=ds(n),H=d?.sceneIndex===j,U=te=>
4224({command:te,visiblePosition:N,clips:y,trackEntries:O,assetEntries:S,overdubInfosMap:Q});switch(G){case uo.PLAY_ALL:{if(tJe($,j,N)&&f===we.INSERT_CURSOR&&!q){const re=PC(0,v);if(re===null)return null;o(G8(re.sceneIndex,re.playPosition));const ge=ms(G,$,[],null,re.playPosition,re.sceneIndex,re.clipIndex,e,F,W,O,S,v);return{kind:"restarted_from_first",payload:U({...ge,startFromBeginning:!0})}}if(R.size===0){const re=d!==null&&H?d.position:N,ge=ms(uo.PLAY_ALL,$,[],null,re,j,s,e,F,W,O,S,v);return{kind:"ready",payload:U(ge)}}const te=[...R].sort((re,ge)=>re-ge),ne=d!==null&&H?d.position:v[te[0]].startPosition,oe=ms(uo.PLAY_ALL,$,[],null,ne,j,s,e,F,W,O,S,v);return{kind:"ready",payload:U(oe)}}case uo.PLAY_CLIP:{if(R.size===0){const re=Cze(N,y[s],d?.position,w),ge=ms(uo.PLAY_CLIP,$,[T],null,re,j,s,e,F,W,O,S,v);return{kind:"ready",payload:U(ge)}}const te=[...R].sort((re,ge)=>re-ge),ne=d!==null&&H?d.position:wc(v[te[0]].startPosition,v)??0,oe=ms(uo.PLAY_CLIP,$,te,null,ne,j,s,e,F,W,O,S,v);return{kind:"ready",payload:U(oe)}}case uo.PLAY_WORDS:{if(q===null)return null;const{globalClipIndex:te}=q,{from:ne}=G0(q),oe=v[te].startPosition+ne,re=d!==null&&H?d.position:wc(oe,v)??0,ge=ms(uo.PLAY_WORDS,$,[],q,re,j,s,e,F,W,O,S,v);return{kind:"ready",payload:U(ge)}}case uo.PLAY_ASSET_ANIMATION:{const te=RI(E);if(f!==we.ELEMENT||!te)return null;const ne=F4(te,v);if(ne===null)return null;if(ne.type==="GLOBAL_CLIP"){const yt=x0(ne.from,ne.to),Le=PC(ne.from,v);if(Le===null)return null;const We=ms(uo.PLAY_CLIP,$,yt,null,Le.playPosition,Le.sceneIndex,Le.clipIndex,e,F,W,O,S,v);return{kind:"ready",payload:U(We)}}const oe=G0({globalClipIndex:ne.globalClipIndex,from:ne.from,to:ne.to}),re=PC(oe.globalClipIndex,v);if(re===null)return null;const ge=v[oe.globalClipIndex].startPosition+oe.from,fe=wc(ge,v)??0,ve=ms(uo.PLAY_WORDS,$,[],oe,fe,re.sceneIndex,re.clipIndex,e,F,W,O,S,v);return{kind:"ready",payload:U(ve)}}case uo.PLAY_TRANSITION:{const te=v[x],ne=eEe(te);if(!ne)return null;const oe={from:ne.from,to:ne.to,globalClipIndex:x},re=v[$[j].globalClipRange.from],ge=re.startPosition,fe=ms(uo.PLAY_WORDS,$,[],oe,te.startPosition+oe.from-ge,j,x,e,F,W,O,S,v);return{kind:"ready",payload:U(fe)}}default:return null}},Oze=e=>{if(e===null||e.kind==="audio_not_ready"||e.kind==="play_not_available")return;const t=ld();if(e.kind==="stop_active"){if(t===null||t.disposed)return;t.pause({preservePlayCursor:e.payload.preservePlayCursor});return}if(t===null||t.disposed)return;const{command:o,visiblePosition:r}=e.payload;t.play({...o,legacyContext:{visiblePosition:r,clips:e.payload.clips,trackEntries:e.payload.trackEntries,assetEntries:e.payload.assetEntries,overdubInfosMap:e.payload.overdubInfosMap}})},mh=(e,t=uo.PLAY_DEFAULT)=>(o,r)=>{const n=Sze(e,t)(o,r);return Oze(n)},iRt=e=>t=>{const o=ld();if(o===null)return;const r=o.playing&&jP(o)!==null;r&&t(mh(pr.BUTTON)),o.setPlaybackRate(e),r&&t(mh(pr.BUTTON))},Cze=(e,t,o,r)=>{if(o!==void 0)return o;if(r)return t.startPosition;const n=xs(t);return e>=n?t.startPosition:e},PC=(e,t)=>{const o=t[e];if(!o)return null;const r=Hm(e,t);if(r<0)return null;const n=SH(e,t,r);if(n===void 0)return null;const a=wc(o.startPosition,t);return a===null?null:{sceneIndex:r,clipIndex:n,playPosition:a}},Rze=e=>{const t=Z0(e),o=PW(e),r=ds(e);return t.size>0||o?uo.PLAY_CLIP:r?uo.PLAY_WORDS:uo.PLAY_ALL},sRt=e=>t=>{const o={type:Ga.CLEAR_EVENT_QUEUE,payload:{handledEventNum:e}};return t(o)},xRt=()=>e=>{const t={type:Ga.UPDATE_THUMBNAIL};return e(t)},cRt=()=>({type:Ga.PLAYBACK_SESSION_CHANGED}),Aze=(e,t,o,r,n,a)=>{e===pr.PREVIEW_CLICK?NDe():e===pr.BUTTON?wDe():iDe(e),se().isSampleProject()&&(t?CMe():OMe()),t&&o!==void 0&&r===we.CAPTION&&n&&Uke(o,a,n)},j8=e=>(t,o)=>{const r=tc(o()),n=e.map(({mediaId:s,path:x,duration:c})=>({mediaId:s,src:x,projectAudioLanguage:r,duration:c}));t(H8(n,!0));const a={type:Ga.UPDATE_THUMBNAIL};t(a);const i=e.map(({mediaId:s,path:x,duration:c})=>({mediaId:s,audioBlob:null,path:x,duration:c}));t(YP(i,!0))},z8=e=>async t=>{const o=await nc.getInstance(),r=ca(),n=new Set(o.getInactivatedProxies()),a=r.filter(s=>n.has(s.mediaId));a.forEach(s=>o.setProxyActivation(s.mediaId,!0));const i=a.map(s=>({mediaId:s.mediaId,path:o.getProxyFilePath(s.mediaId),duration:s.videoAudioMetaInfo.duration}));t(j8(i)),h("videoplay.ts").info("Activate proxy and update sources, length: "+a.length),e1e(e)},lRt=()=>async e=>{const t=await nc.getInstance(),o=ca(),r=o.filter(s=>Bc(s)),n=new Set(t.getActivatedProxies()),a=r.filter(s=>n.has(s.mediaId));a.forEach(s=>t.setProxyActivation(s.mediaId,!1));const i=a.map(s=>({mediaId:s.mediaId,path:s.path,duration:s.videoAudioMetaInfo.duration}));e(j8(i)),h("videoplay.ts").info("Deactivate proxy and update sources, length: "+a.length)},dRt=(e,t)=>
4224(o,r)=>{const n=r(),a=mo(n),i=Zx(n),s=ku(t,e,a);s!==null&&i!==we.CORRECTING&&o(W8(s,{origin:"playback"}))},uRt=()=>(e,t)=>{const o=t(),r=Zx(o);if(r===we.CORRECTING||r===we.CAPTION)return;const n=Pg(o);if(n===null)return;const a=He(o),i=y_(a,n),s=mo(o),x=s?.[i]?.clips;if(!x)return;const c=wc(n,a);if(c===null)return;const l=lW(x,c,!0);if(l===c)return;const d=ku(l,i,s);d!==null&&e(W8(d,{origin:"playback"}))};var yze=(e=>(e.CLICK_VIDEO_FIT_RATE="click_video_fit_rate",e.APPLY_VIDEO_FIT_RATE_DONE="apply_video_fit_rate_done",e.TOGGLE_AUTO_FIT_SPACER="toggle_auto_fit_spacer",e.BLANK_WORD_AUTO_FIT="blank_word_auto_fit",e))(yze||{});const vze=(e,t,o)=>{I().event(m.PLAYBACK_RATE_EFFECT,"click_video_fit_rate",xi(e,t)+"_"+t,void 0,JSON.stringify({videoFitRateSource:o}))},wze=e=>{const{videoFitRateApplicableCount:t,videoFitRateSkippedCount:o,videoFitRateAvgRate:r,videoFitRateMinRate:n,videoFitRateMaxRate:a,videoFitRateRange:i}=e;I().event(m.PLAYBACK_RATE_EFFECT,"apply_video_fit_rate_done",void 0,void 0,JSON.stringify({videoFitRateApplicableCount:t,videoFitRateSkippedCount:o,videoFitRateAvgRate:r,videoFitRateMinRate:n,videoFitRateMaxRate:a,videoFitRateRange:xi(i,t+o)}))},pRt=e=>{I().event(m.TOOLBAR_SETTING,"toggle_auto_fit_spacer",e?"on":"off")},Nze=e=>{I().event(m.INSERT,"blank_word_auto_fit",void 0,void 0,JSON.stringify(e))},Pze=(e,t,o)=>Gp("new",e,t,o),Gp=async(e,t,o,r)=>{const n=Mo().getDebugVal(Xt.CONTROL_VCLOUD_STATUS);if(!await Vn("onClickBackUpProject"))return!1;if(!await wo())throw h("uploadModal.ts").error("[Uploading] idToken or projectId is not valid"),new C(_.C_VCLOUD_GENERAL_ERROR);if(e==="saveAs"&&await sv()===iv.STAY_IN_PROJECT)return!1;const a=Lt().getUserPlanStatusForVcloud();if(a==="FREE"||n==="free")return Y().openModal(st.NEED_PLAN_UPGRADE,{premiumFeatureType:Ut.VCLOUD}),!1;if(a==="REFUND")return await eA({type:"save"}),!1;if(e==="migrate"){if(r4(t))return!1;const s=Lt().getVCloudProjectInfo(t);if(!s)throw h("uploadModal.ts").error("[Uploading] cloud project info is not found for projectId: "+t),new C(_.C_VCLOUD_GENERAL_ERROR);const x=s.totalSize;return Y().openModal(st.MIGRATE_CLOUD_PROJECT,{projectId:t,modalAction:e,userPlanStatusForVcloud:a,currentProjectSize:x,target:"current"}),!1}k7(),F7();const i=o||Il().getProjectName(t)||Q1()||hy;return new Promise(s=>{Y().openModal(st.CHOOSE_CLOUD_UPLOAD_OPTIONS,{projectId:t,projectName:i,modalAction:e,userPlanStatusForVcloud:a,onComplete:s,skipTitleInput:r})})},bze={isFloating:!1,isMenuOpen:!1,showType:"normal"},Y8=In({name:"assetList",initialState:bze,reducers:{toggleAssetListFloating:e=>{e.isFloating=!e.isFloating},setAssetListMenuOpen:(e,t)=>{e.isMenuOpen=t.payload},setAssetListShowType:(e,t)=>{e.showType=t.payload}}}),fRt=Y8.reducer,{toggleAssetListFloating:gRt,setAssetListMenuOpen:Lze,setAssetListShowType:Mze}=Y8.actions,BP=e=>ja(e).assetList,_Rt=e=>BP(e).isFloating,ERt=e=>BP(e).isMenuOpen,mRt=e=>BP(e).showType,Dze=!1,B8=In({name:"cursorMoverMenu",initialState:Dze,reducers:{toggle:e=>!e}}),hRt=B8.reducer,{toggle:kze}=B8.actions,Fze=()=>(e,t)=>(!Uze(t())&&TUe(),e(kze())),Uze=e=>ja(e).cursorMoverMenu,Vze={overlaidElementId:void 0,overlayClassName:void 0,overlayCenterClickAllowed:!1},dS=In({name:"overlay",initialState:Vze,reducers:{setOverlaidElement:(e,t)=>{e.overlaidElementId=t.payload.overlaidElementId,e.overlayClassName=t.payload.overlayClassName,e.overlayCenterClickAllowed=t.payload.overlayCenterClickAllowed??!1}}}),IRt=dS.reducer,KP=e=>ja(e).overlay,XP=e=>KP(e).overlaidElementId,TRt=e=>KP(e).overlayClassName,SRt=e=>KP(e).overlayCenterClickAllowed,K8=(e,t=!1)=>(o,r)=>{const n=r();XP(n)!==void 0&&o(Va()),o(dS.actions.setOverlaidElement({overlaidElementId:t?Gc.GLOBAL_TRANSPARENT_OVERLAY:Gc.GLOBAL_OVERLAY,overlayClassName:e}))},op=(e,t,o,r)=>(n,a)=>{const i=a();XP(i)!==void 0&&n(Va()),e.setAttribute(iR,t),n(dS.actions.setOverlaidElement({overlaidElementId:t,overlayClassName:o,overlayCenterClickAllowed:r}))},Va=()=>(e,t)=>{const o=t(),r=XP(o),n=document.querySelector("["+iR+'="'+r+'"]');n instanceof HTMLElement&&n.removeAttribute(iR),e(dS.actions.setOverlaidElement({overlaidElementId:void 0,overlayClassName:void 0,overlayCenterClickAllowed:void 0}))},Gze={isConnected:!1,isOpen:!1,hasConsented:null,isSuggestedPromptsModalOpen:!1,chatSessionId:0,agentLastTraceId:null},rp=In({name:"vrewAgent",initialState:Gze,reducers:{openVrewAgent:e=>{e.isOpen=!0,e.isConnected=!0},closeVrewAgent:e=>{e.isOpen=!1},disconnectVrewAgent:e=>{e.isOpen=!1,e.isConnected=!1},toggleVrewAgent:e=>{e.isOpen=!e.isOpen,e.isConnected=!0},setConsent:(e,t)=>
4224{e.hasConsented=t.payload},openSuggestedPromptsModal:e=>{e.isSuggestedPromptsModalOpen=!0},closeSuggestedPromptsModal:e=>{e.isSuggestedPromptsModalOpen=!1},setAgentLastTraceId:(e,t)=>{e.agentLastTraceId=t.payload}},extraReducers:e=>{e.addCase(ot.APPLY_TRANSCRIPT,(t,o)=>{o.payload.addSceneIndex===null&&(t.chatSessionId+=1)})}}),ORt=rp.reducer,{closeVrewAgent:CRt,disconnectVrewAgent:RRt,setConsent:ARt,openSuggestedPromptsModal:yRt,closeSuggestedPromptsModal:vRt,setAgentLastTraceId:wRt}=rp.actions,X8=(e,t)=>{Wze(t())&&e(q8())},NRt=()=>(e,t)=>{X8(e,t),e(rp.actions.openVrewAgent())},PRt=()=>(e,t)=>{!JP(t())&&X8(e,t),e(rp.actions.toggleVrewAgent())},np=e=>ja(e).vrewAgent,JP=e=>np(e).isOpen,bRt=e=>np(e).isConnected,LRt=e=>np(e).hasConsented,MRt=e=>np(e).isSuggestedPromptsModalOpen,DRt=e=>np(e).chatSessionId,kRt=e=>np(e).agentLastTraceId,Tl=e=>ja(e).panel,Sl=e=>Tl(e).panelState,Wze=e=>Sl(e)!==kn.NULL,FRt=e=>Tl(e).panelOpenTrigger,URt=e=>Tl(e).panelBlinkCount,Hze=e=>Tl(e).userAssetPanelResourceType,VRt=e=>Tl(e).userAssetCounter,jze=e=>Tl(e).panelInReplaceMode,GRt=e=>Tl(e).replaceModeEnterCount,WRt=e=>Tl(e).sidePanelWidth,J8=340,zze=J8,Yze={panelState:kn.NULL,panelOpenTrigger:null,panelBl
4224inkCount:0,userAssetPanelResourceType:Kr.ALL,userAssetCounter:0,panelInReplaceMode:null,replaceModeEnterCount:0,sidePanelWidth:J8},K0=In({name:"panel",initialState:Yze,reducers:{openPanel:(e,t)=>{const{panelState:o,trigger:r}=t.payload;e.panelState=o,e.panelOpenTrigger=r},closePanel:e=>{e.panelState=kn.NULL,e.panelOpenTrigger=null},blinkPanel:e=>{e.panelBlinkCount+=1},changeUserAssetPanelResourceType:(e,t)=>{e.userAssetPanelResourceType=t.payload},incrementUserAssetCounter:e=>{e.userAssetCounter+=1},enterReplaceMode:(e,t)=>{e.panelInReplaceMode=t.payload,e.replaceModeEnterCount+=1},clearReplaceMode:e=>{e.panelInReplaceMode=null},setSidePanelWidth:(e,t)=>{e.sidePanelWidth=Math.round(Math.min(i9,Math.max(zze,t.payload)))}}}),HRt=K0.reducer,{closePanel:q8,changeUserAssetPanelResourceType:Bze,enterReplaceMode:jRt,clearReplaceMode:zRt,setSidePanelWidth:YRt}=K0.actions,qP=(e,t)=>(o,r)=>{const n=r();if(He(n).length===0)return;const i=Sl(n);if(e===i){o(K0.actions.blinkPanel());return}JP(n)&&o(rp.actions.closeVrewAgent()),o(K0.actions.openPanel({panelState:e,trigger:t}))},BRt=(e,t)=>(o,r)=>{const n=r(),a=Sl(n);if(e===a){o(K0.actions.closePanel());return}JP(n)&&o(rp.actions.closeVrewAgent()),o(K0.actions.openPanel({panelState:e,trigger:t}))},Q8=(e,t,o)=>(r,n)=>{window.indexedDB&&(r(Bze(o)),Sl(n())!==e&&r(qP(e,t)),r(K0.actions.incrementUserAssetCounter()))},Kze=(e,t)=>o=>{o(qP(kn.MARKER,en.CLIP_MARKER));const r={type:ka.SET_MARKER_PANEL_DECORATION,payload:{globalClipIndex:e,markerId:t}};o(r)},KRt=e=>(t,o)=>{t(qP(kn.FREE_SOURCE_LIBRARY,e)),Sl(o())===kn.FREE_SOURCE_LIBRARY&&t(K0.actions.enterReplaceMode("freeSource"))},XRt=e=>(t,o)=>{t(Q8(kn.USER_ASSET_LIBRARY,e,Kr.ALL)),Sl(o())===kn.USER_ASSET_LIBRARY&&t(K0.actions.enterReplaceMode("userAsset"))},JRt=e=>(t,o)=>{jze(o())===e&&t(K0.actions.clearReplaceMode())},Xze={},Z8=In({name:"sceneFold",initialState:Xze,reducers:{foldScene:(e,t)=>{e[t.payload.sceneId]=t.payload.shouldFold},applySceneFoldInfos:(e,t)=>t.payload}}),qRt=Z8.reducer,{foldScene:QRt,applySceneFoldInfos:Jze}=Z8.actions,qze=e=>ja(e).sceneFold,ZRt=(e,t)=>qze(e)[t]??!1,Qze={isOpen:!1},$8=In({name:"scenePanel",initialState:Qze,reducers:{openScenePanel:()=>({isOpen:!0}),closeScenePanel:()=>({isOpen:!1}),toggleScenePanel:e=>({isOpen:!e.isOpen})}}),$Rt=$8.reducer,{openScenePanel:eAt,closeScenePanel:Zze,toggleScenePanel:tAt}=$8.actions,$ze=e=>ja(e).scenePanel,oAt=e=>$ze(e).isOpen,eYe={isSurveyTriggered:!1,surveyInfo:null},eB=In({name:"smartSurvey",initialState:eYe,reducers:{setSmartSurvey:(e,t)=>t.payload}}),rAt=eB.reducer,{setSmartSurvey:vF}=eB.actions,uS=e=>async(t,o)=>{const{isSurveyTriggered:r,surveyInfo:n}=tYe(o());try{const a=n??await jie(Fe());if(r||!a||!a.timingTypes.includes(e)){t(vF({isSurveyTriggered:r,surveyInfo:a}));return}t(vF({isSurveyTriggered:!0,surveyInfo:a})),Jie(a)}catch(a){h("smartSurvey.ts").warn("Failed to active survey. Skip : "+P(a));return}},tYe=e=>ja(e).smartSurvey,tB=()=>({tourId:"",currStepIdx:0,currStep:et.NONE,show:!1,resolving:!1,tourInfo:{steps:[],type:Ct.NONE}}),oYe=tB(),oB=In({name:"tour",initialState:oYe,reducers:{startTour:(e,t)=>{const{tourInfo:o,tourId:r}=t.payload;e.currStep=o.steps[0].step,e.resolving=!1,e.currStepIdx=0,e.show=!1,e.tourInfo=o,e.tourId=r},clearTour:()=>tB(),increaseTourStep:(e,t)=>{const o=e.currStepIdx+t.payload.step;e.currStepIdx=o,e.currStep=e.tourInfo.steps[o].step,e.show=!1},decreaseTourStep:(e,t)=>{const o=e.currStepIdx-t.payload.step;e.currStepIdx=o,e.currStep=e.tourInfo.steps[o].step,e.show=!1},setTourVisibility:(e,t)=>{e.show=t.payload.show},setTourResolveStatus:(e,t)=>{e.resolving=t.payload.resolving}}}),nAt=oB.reducer,{startTour:rYe,clearTour:nYe,increaseTourStep:aYe,decreaseTourStep:iYe,setTourVisibility:rB,setTourResolveStatus:nB}=oB.actions,pS=e=>ja(e).tour,fs=e=>pS(e),sYe=e=>pS(e).tourInfo.type,aAt=e=>pS(e).currStep,iAt=e=>pS(e).resolving,sAt=e=>sYe(e)!==Ct.NONE;var aB=(e=>(e.RESET_STATE="RESET_STATE",e))(aB||{});const xAt=e=>e.type==="RESET_STATE",xYe=(e,t)=>{let o=e,r=t,n=new fh(e,t);return{bindStore:(a,i)=>{a===o&&i===r||(o=a,r=i,n=new fh(a,i))},getSlice:a=>n.getSlice(a)}},cYe=3e4,lYe=[{startInProject:0,durationInProject:1}],dYe=({profile:e,supplier:t,abortSignal:o})=>new QY({video:e.video},new ZY(t),null,o),Wp=()=>new DOMException("Thumbnail capture canceled","AbortError"),uYe=e=>new DOMException("Thumbnail capture timed out after "+e+"ms","TimeoutError"),fx=e=>e.reason??Wp(),pYe=(e,t)=>
4224{const o=new AbortController;let r,n=!1;const a=()=>{r!==void 0&&(window.clearTimeout(r),r=void 0),n&&(e.removeEventListener("abort",s),n=!1)},i=x=>{o.signal.aborted||(o.abort(x),a())},s=()=>i(fx(e));return e.aborted?i(fx(e)):(e.addEventListener("abort",s,{once:!0}),n=!0,r=window.setTimeout(()=>i(uYe(t)),t)),{signal:o.signal,dispose:a}};class fYe{constructor(t){this._options=t}_options;_session;_projectId;_profileKey;_initializedTimeSlices;_initializedTimeline;_appliedComposition;_idleTimerId;_pendingCapture;_captureStrand=new Mu;captureThumbnailFrame(t){const o=this._captureStrand.next(async()=>{if(t.abortSignal.aborted)throw fx(t.abortSignal);const r=pYe(t.abortSignal,this._options.captureDeadlineMs);try{return await this._captureExclusive({...t,abortSignal:r.signal})}finally{r.dispose()}});return new Promise((r,n)=>{let a=!1;const i=x=>{a||(a=!0,t.abortSignal.removeEventListener("abort",s),x())},s=()=>i(()=>n(fx(t.abortSignal)));t.abortSignal.addEventListener("abort",s,{once:!0}),t.abortSignal.aborted&&s(),o.then(x=>i(()=>r(x)),x=>i(()=>n(x)))})}async _captureExclusive(t){this._clearIdleTimer();try{this._throwIfCanceled(t);let o;const r=new Promise((n,a)=>{o=()=>{const i=fx(t.abortSignal);this._invalidateSessionIfCurrent(this._session,i),a(i)},t.abortSignal.addEventListener("abort",o,{once:!0})});if(t.abortSignal.aborted&&o(),t.abortSignal.aborted)return await r;try{return await Promise.race([this._capture(t),r])}finally{t.abortSignal.removeEventListener("abort",o)}}finally{this._session&&this._resetIdleTimer()}}async _capture(t){this._throwIfCanceled(t);const o=await this._prepareCapture(t);this._throwIfCanceled(t);let r;try{r=await this._renderFrame(o.session,t)}catch(a){throw!(a instanceof DOMException&&a.name==="AbortError"&&!t.abortSignal.aborted&&t.isCanceled?.()===!0)&&this._invalidateSessionIfCurrent(o.session,a),a}if(!this._isCurrentSession(o.session))throw $s(r),this._sessionAbortReason(o.session,t.abortSignal);let n;try{n=await my(r)}catch(a){throw $s(r),a}if(!this._isCurrentSession(o.session))throw $s(n),this._sessionAbortReason(o.session,t.abortSignal);return o.commitComposition&&(this._appliedComposition=t.composition),n}async _prepareCapture(t){const o=t.composition.timeSlices.length>0?t.composition.timeSlices:lYe,r=this._session;if(!r||this._projectId!==t.composition.projectId||this._profileKey!==t.composition.profile.key){const c=await this._replacePreviewer(t);return await this._initializeAtRequestedTime(c,o,t.timelineMs),{session:c,commitComposition:!0}}r.supplier.bindStore(t.composition.store,t.composition.textRenderLanguage);const n=this._initializedTimeSlices,a=this._initializedTimeline;if(!n||!a||!m1(n,o))return await this._initializeAtRequestedTime(r,o,t.timelineMs),{session:r,commitComposition:!0};const i=t.composition.revision,s=this._appliedComposition?.revision,x=s!==i;try{await Promise.race([r.previewer.seek(this._videoTimeAt(a,t.timelineMs),x?"content-change":"time-move"),r.failure]),this._throwIfSessionStale(r,t.abortSignal)}catch(c){throw this._invalidateSessionIfCurrent(r,c),c}return{session:r,commitComposition:x}}async _initializeAtRequestedTime(t,o,r){const n=gy(o);try{await Promise.race([t.previewer.init(o,this._videoTimeAt(n,r)),t.failure]),this._throwIfSessionStale(t)}catch(a){throw this._invalidateSessionIfCurrent(t,a),a}this._initializedTimeSlices=o,this._initializedTimeline=n}_videoTimeAt(t,o){return WJ(t,X.fromMS(o))}async _renderFrame(t,o){let r;const n=new Promise((x,c)=>{this._pendingCapture={session:t,resolve:l=>{r=l,x(l)},reject:c,isCanceled:()=>o.abortSignal.aborted||o.isCanceled?.()===!0}}),a=Promise.resolve().then(()=>t.previewer.renderCurrent());let i;const s=new Promise((x,c)=>{i=()=>c(fx(o.abortSignal)),o.abortSignal.addEventListener("abort",i,{once:!0})});o.abortSignal.aborted&&i();try{const x=Promise.all([n,a.then(l=>
4224{if(!l)throw new Error("Thumbnail capture produced no frame")})]).then(([l])=>l),c=await Promise.race([x,s,t.failure]);return r=void 0,c}catch(x){throw r&&($s(r),r=void 0),x}finally{o.abortSignal.removeEventListener("abort",i)}}_resolvePending(t,o){if(!this._isCurrentSession(t)){$s(o);return}const r=this._takePending(t);if(!r){$s(o);return}if(r.isCanceled()){$s(o),r.reject(Wp());return}r.resolve(o)}_rejectPending(t,o){this._takePending(o)?.reject(t)}_takePending(t){const o=this._pendingCapture;if(o&&!(t&&o.session!==t))return this._pendingCapture=void 0,o}_throwIfCanceled(t){if(t.abortSignal.aborted)throw fx(t.abortSignal);if(t.isCanceled?.())throw Wp()}async _replacePreviewer(t){await this._destroyPreviewer(),this._throwIfCanceled(t);const o=new AbortController,r=xYe(t.composition.store,t.composition.textRenderLanguage),n=this._options.createPreviewer({profile:t.composition.profile,supplier:r,abortSignal:o.signal});let a;const i=new Promise((x,c)=>{a=c});i.catch(()=>{});const s={previewer:n,supplier:r,abortController:o,failure:i,rejectFailure:a};this._session=s;try{s.subscription=n.stream().subscribe({next:x=>{x.type==="Audio"||!x.bitmap||this._resolvePending(s,x.bitmap)},error:x=>{this._invalidateSessionIfCurrent(s,x)}}),this._throwIfSessionStale(s)}catch(x){throw this._invalidateSessionIfCurrent(s,x),x}return this._projectId=t.composition.projectId,this._profileKey=t.composition.profile.key,s}_clearIdleTimer(){this._idleTimerId!==void 0&&(window.clearTimeout(this._idleTimerId),this._idleTimerId=void 0)}_resetIdleTimer(){this._clearIdleTimer(),this._idleTimerId=window.setTimeout(()=>{this._destroyPreviewer().catch(()=>{})},cYe)}_isCurrentSession(t){return this._session===t}_sessionAbortReason(t,o){return t.abortController.signal.aborted?fx(t.abortController.signal):o?.aborted?fx(o):Wp()}_throwIfSessionStale(t,o){if(!this._isCurrentSession(t))throw this._sessionAbortReason(t,o)}_invalidateSessionIfCurrent(t,o){!t||!this._isCurrentSession(t)||this._detachSession(t,o)&&this._destroySession(t).catch(()=>{})}async _destroyPreviewer(){const t=this._session;t&&this._detachSession(t,Wp())&&await this._destroySession(t)}async _destroySession(t){try{await t.previewer.destroy()}finally{t.subscription?.unsubscribe()}}_detachSession(t,o){return this._isCurrentSession(t)?(this._clearIdleTimer(),this._session=void 0,this._rejectPending(o,t),this._projectId=void 0,this._profileKey=void 0,this._initializedTimeSlices=void 0,this._initializedTimeline=void 0,this._appliedComposition=void 0,t.rejectFailure(o),t.abortController.abort(o),!0):!1}}const gYe=({captureDeadlineMs:e,createPreviewer:t=dYe})=>{const o=new fYe({createPreviewer:t,captureDeadlineMs:e});return{captureThumbnailFrame:r=>o.captureThumbnailFrame(r)}},_Ye=5e3,wF=15e3,EYe=5e3,mYe=()=>{const e=gYe({captureDeadlineMs:EYe});return t=>e.captureThumbnailFrame({timelineMs:t.timelineMs,composition:t.composition,abortSignal:t.abortSignal??new AbortController().signal,isCanceled:t.isCanceled??(()=>!1)})},iB=()=>({abortSignal:new AbortController().signal,releaseCaptureLane:()=>{}}),hh=()=>new DOMException("Thumbnail serialization canceled","AbortError"),hYe=(e,t)=>t.aborted?Promise.reject(t.reason??hh()):new Promise((o,r)=>{const n=new FileReader;let a=!1;const i=()=>{t.removeEventListener("abort",x),n.onloadend=null,n.onerror=null},s=c=>{a||(a=!0,i(),r(c))},x=()=>{a||(a=!0,i(),n.readyState===FileReader.LOADING&&typeof n.abort=="function"&&n.abort(),r(t.reason??hh()))};n.onloadend=()=>{if(!a){if(typeof n.result!="string"){s(new Error("Failed to read serialized thumbnail as data URL"));return}a=!0,i(),o(n.result)}},n.onerror=()=>s(n.error??new Error("Failed to read serialized thumbnail")),t.addEventListener("abort",x,{once:!0});try{n.readAsDataURL(e)}catch(c){s(c)}}),sB=(e,t)=>t.aborted?Promise.reject(t.reason??hh()):new Promise((o,r)=>{let n=!1;const a=()=>t.removeEventListener("abort",s),i=x=>{n||(n=!0,a(),r(x))},s=()=>i(t.reason??hh());t.addEventListener("abort",s,{once:!0});try{e.toBlob(x=>{if(!n){if(!x){i(new Error("Failed to serialize canvas as JPEG"));return}n=!0,a(),o(x)}},im,sm)}catch(x){i(x)}}).then(o=>hYe(o,t)),xB=async(e,t=iB())=>{const o=document.createElement("canvas");o.width=e.width,o.height=e.height;let r=!1;try{const n=o.getContext("bitmaprenderer");if(!n)throw new Error("Failed to get bitmap renderer context");n.transferFromImageBitmap(e),r=!0}finally{r||e.close(),t.releaseCaptureLane()}return sB(o,t.abortSignal)},IYe=(e,t,o,r)=>{const n=Math.min(o/e,r/t);return{width:Math.max(1,Math.round(e*n)),height:Math.max(1,Math.round(t*n))}},TYe=async(e,t,o,r=iB())=>{const{width:n,height:a}=IYe(e.width,e.height,t,o),i=document.createElement("canvas");i.width=n,i.height=a;try{const s=i.getContext("2d");if(!s)throw new Error("Failed to get 2D canvas context");s.drawImage(e,0,0,n,a)}finally{e.close(),r.releaseCaptureLane()}return sB(i,r.abortSignal)},SYe=e=>typeof e=="object"&&e!==null&&"__internal"in e&&e.__internal==="MediaProcessingError"&&"type"in e&&typeof e.type=="string"&&"message"in e&&typeof e.message=="string",bC={maxAttempts:2,retryDelayMs:100,maxConsecutiveDurable:1},O0=()=>new DOMException("Thumbnail capture canceled","AbortError"),OYe=()=>new DOMException("Thumbnail capture superseded","AbortError"),CYe=e=>{const t=o=>o.split(`
4225`,1)[0].trim();
4225return SYe(e)?e.type+": "+t(e.message):xg(e)||s9(e)?e.name+": "+t(e.message):t(String(e))},NF=e=>new DOMException(e===void 0?"Thumbnail capture timed out":"Thumbnail capture timed out after "+CYe(e),"TimeoutError");class RYe{_works=new Map;_durableQueue=[];_interactiveQueue=[];_callerGroups=new Map;_draining=!1;_consecutiveDurable=0;request(t){if(t.abortSignal?.aborted||t.isCanceled?.())return Promise.resolve({status:"canceled",reason:"aborted"});let o;if(t.coalescingIdentity){const a=this._callerGroups.get(t.coalescingIdentity);a&&a.renderIdentity!==t.renderIdentity&&this.supersedeCaller(t.coalescingIdentity),o=this._callerGroups.get(t.coalescingIdentity),!o&&(o={identity:t.coalescingIdentity,renderIdentity:t.renderIdentity,subscribers:new Set},this._callerGroups.set(t.coalescingIdentity,o))}let r=this._works.get(t.renderIdentity);r?t.intent==="durable"&&r.intent==="interactive"&&this._promote(r):(r={renderIdentity:t.renderIdentity,run:t.run,abortController:new AbortController,subscribers:new Set,intent:t.intent,state:"pending",attempts:0},this._works.set(t.renderIdentity,r),this._queue(r));const n=new Promise(a=>{const i={work:r,callerGroup:o,abortSignal:t.abortSignal,isCanceled:t.isCanceled,resolve:a,settled:!1};r.subscribers.add(i),o?.subscribers.add(i);const s=t.queueDeadlineMs===void 0?_Ye:t.queueDeadlineMs;if(r.state==="pending"&&s!==null&&(i.queueDeadlineTimer=window.setTimeout(()=>{const x=NF();this._settleSubscriber(i,{status:"failed",error:x},x)},s)),i.abortSignal){const x=()=>{this._settleSubscriber(i,{status:"canceled",reason:"aborted"},i.abortSignal?.reason??O0())};i.abortSignal.addEventListener("abort",x,{once:!0}),i.removeAbortListener=()=>i.abortSignal?.removeEventListener("abort",x)}});return this._startDrain(),n}supersedeCaller(t){const o=this._callerGroups.get(t);if(o)for(const r of[...o.subscribers])this._settleSubscriber(r,{status:"canceled",reason:"superseded"},OYe())}_queue(t){(t.intent==="durable"?this._durableQueue:this._interactiveQueue).push(t)}_promote(t){if(t.intent="durable",t.state!=="pending")return;const o=this._interactiveQueue.indexOf(t);o!==-1&&this._interactiveQueue.splice(o,1),this._durableQueue.push(t)}_startDrain(){this._draining||(this._draining=!0,this._drain().finally(()=>{this._draining=!1,this._hasPendingWork()&&this._startDrain()}))}async _drain(){let t=this._nextWork();for(;t;)this._pruneCanceledSubscribers(t),t.subscribers.size===0?this._detachWork(t,O0()):await this._startAttempt(t),t=this._nextWork()}_nextWork(){this._discardStaleQueueEntries(this._durableQueue),this._discardStaleQueueEntries(this._interactiveQueue);const t=this._durableQueue.length>0,o=this._interactiveQueue.length>0;if(!(!t&&!o))return o&&(!t||this._consecutiveDurable>=bC.maxConsecutiveDurable)?(this._consecutiveDurable=0,this._interactiveQueue.shift()):(this._consecutiveDurable=o?this._consecutiveDurable+1:0,this._durableQueue.shift())}_discardStaleQueueEntries(t){for(;t.length>0;){const o=t[0];if(o.state==="pending"&&this._works.get(o.renderIdentity)===o){if(this._isExpired(o)){t.shift(),this._timeoutWork(o);continue}return}t.shift()}}_hasPendingWork(){return this._durableQueue.length>0||this._interactiveQueue.length>0}_startAttempt(t){if(this._isExpired(t))return this._timeoutWork(t),Promise.resolve();this._clearQueueDeadlines(t),t.attempts===0&&(t.startedAt=Date.now(),t.deadlineTimer=window.setTimeout(()=>this._timeoutWork(t),wF)),t.state="running",t.attempts+=1;const o=new AbortController;let r;const n=new Promise(x=>{r=x}),a=()=>{!o.signal.aborted&&o.abort(t.abortController.signal.reason??O0())};t.abortController.signal.addEventListener("abort",a,{once:!0});const i={work:t,abortController:o,laneReleased:n,laneHeld:!0,releaseCaptureLane:()=>{i.laneHeld&&(i.laneHeld=!1,t.state==="running"&&(t.state="finalizing"),r())},removeWorkAbortListener:()=>t.abortController.signal.removeEventListener("abort",a),settled:!1};t.attempt=i;let s;try{s=t.run({abortSignal:o.signal,isCanceled:()=>!this._hasActiveSubscriber(t),releaseCaptureLane:i.releaseCaptureLane})}catch(x){s=Promise.reject(x)}return s.then(x=>this._settleAttempt(i,{value:x}),x=>this._settleAttempt(i,{error:x}
4225)),i.laneReleased}_settleAttempt(t,o){if(t.settled)return;t.settled=!0,t.releaseCaptureLane(),t.removeWorkAbortListener();const r=t.work;if(r.attempt!==t)return;if(r.attempt=void 0,this._pruneCanceledSubscribers(r),r.state==="finished"||r.subscribers.size===0||r.abortController.signal.aborted){this._detachWork(r,r.abortController.signal.reason??O0());return}if("value"in o){this._finishWork(r,{status:"completed",value:o.value});return}if(no(o.error)){this._finishWork(r,{status:"canceled",reason:"aborted"});return}r.lastError=o.error;const n=this._isTimeoutError(o.error);if(!n&&!this._isExpired(r)&&r.attempts<bC.maxAttempts){this._scheduleRetry(r);return}this._isExpired(r)||n?this._timeoutWork(r,o.error):this._finishWork(r,{status:"failed",error:o.error})}_scheduleRetry(t){t.state="waiting-retry",this._delay(t.abortController.signal).then(()=>{if(this._pruneCanceledSubscribers(t),this._isExpired(t)){this._timeoutWork(t);return}if(t.state==="finished"||t.subscribers.size===0||t.abortController.signal.aborted){this._detachWork(t,t.abortController.signal.reason??O0());return}t.state="pending",this._queue(t),this._startDrain()},()=>{this._detachWork(t,t.abortController.signal.reason??O0())})}_delay(t){return t.aborted?Promise.reject(t.reason??O0()):new Promise((o,r)=>{const n=window.setTimeout(()=>{t.removeEventListener("abort",a),o()},bC.retryDelayMs),a=()=>{window.clearTimeout(n),t.removeEventListener("abort",a),r(t.reason??O0())};t.addEventListener("abort",a,{once:!0})})}_hasActiveSubscriber(t){for(const o of t.subscribers)if(!o.settled&&!o.abortSignal?.aborted&&!o.isCanceled?.())return!0;return!1}_pruneCanceledSubscribers(t){const o=this._hasActiveSubscriber(t);for(const r of[...t.subscribers]){const n=r.isCanceled?.()===!0;(r.abortSignal?.aborted||n&&(r.callerGroup!==void 0||r.abortSignal!==void 0||!o))&&this._settleSubscriber(r,{status:"canceled",reason:"aborted"},r.abortSignal?.reason??O0())}}_settleSubscriber(t,o,r){if(t.settled)return;t.settled=!0,t.removeAbortListener?.(),t.queueDeadlineTimer!==void 0&&(window.clearTimeout(t.queueDeadlineTimer),t.queueDeadlineTimer=void 0),t.work.subscribers.delete(t);const n=t.callerGroup;n&&(n.subscribers.delete(t),n.subscribers.size===0&&this._callerGroups.get(n.identity)===n&&this._callerGroups.delete(n.identity)),t.resolve(o);const a=t.work;a.subscribers.size===0&&a.state!=="finished"&&this._detachWork(a,r??O0())}_detachWork(t,o){t.state="finished",t.attempt?.laneHeld||this._clearDeadline(t),this._works.get(t.renderIdentity)===t&&this._works.delete(t.renderIdentity),!t.abortController.signal.aborted&&t.abortController.abort(o)}_finishWork(t,o){t.state="finished",this._clearDeadline(t),this._works.get(t.renderIdentity)===t&&this._works.delete(t.renderIdentity);for(const r of[...t.subscribers])this._settleSubscriber(r,o)}_timeoutWork(t,o=NF(t.lastError)){if(t.state==="finished"){this._clearDeadline(t),this._reclaimHeldLane(t);return}t.state="finished",this._clearDeadline(t),this._works.get(t.renderIdentity)===t&&this._works.delete(t.renderIdentity);for(const r of[...t.subscribers])this._settleSubscriber(r,{status:"failed",error:o});!t.abortController.signal.aborted&&t.abortController.abort(o),this._reclaimHeldLane(t)}_reclaimHeldLane(t){const o=t.attempt;o?.laneHeld&&(h("thumbnailCaptureScheduler.ts").warn("thumbnail capture run did not settle before deadline; reclaiming capture lane: "+String(t.renderIdentity)),o.releaseCaptureLane())}_clearDeadline(t){t.deadlineTimer!==void 0&&(window.clearTimeout(t.deadlineTimer),t.deadlineTimer=void 0)}_clearQueueDeadlines(t){for(const o of t.subscribers)o.queueDeadlineTimer!==void 0&&(window.clearTimeout(o.queueDeadlineTimer),o.queueDeadlineTimer=void 0)}_isExpired(t){return t.startedAt!==void 0&&Date.now()-t.startedAt>=wF}_isTimeoutError(t){return t instanceof Error&&t.name==="TimeoutError"}}const AYe=()=>new RYe,fS=AYe(),cB=()=>new DOMException("Thumbnail capture canceled","AbortError"),cAt=e=>fS.supersedeCaller(e),QP=async(e,t)=>{const o=await e.run({timelineMs:e.timelineMs,abortSignal:t.abortSignal,isCanceled:t.isCanceled});if(t.abortSignal.aborted||t.isCanceled())throw o.close(),t.abortSignal.reason??cB();return o},lAt=e=>fS.request({intent:"interactive",renderIdentity:"interactive-data-url|"+e.renderIdentity,coalescingIdentity:e.coalescingIdentity,abortSignal:e.abortSignal,isCanceled:e.isCanceled,run:async t=>xB(await QP(e,t),t)}),yYe=e=>fS.request({intent:"durable",renderIdentity:"project-data-url|"+e.renderIdentity,coalescingIdentity:e.coalescingIdentity,abortSignal:e.abortSignal,isCanceled:e.isCanceled,run:async t=>{const o=await QP(e,t),r=GU*(window.devicePixelRatio||1);return TYe(o,wE*r,NE*r,t)}}),vYe=async e=>{const t=await fS.request({intent:"interactive",renderIdentity:"interactive-data-url|"+e.renderIdentity,abortSignal:e.abortSignal,isCanceled:e.isCanceled,queueDeadlineMs:e.queueDeadlineMs,run:async o=>xB(await QP(e,o),o)});switch(t.status){case"completed":return t.value;case"failed":throw t.error;case"canceled":throw e.abortSignal?.reason??cB()}},wYe=e=>e.map(t=>({startInProject:vo(t)*1e3,durationInProject:cs(t)*1e3})).reduce((t,o)=>t.length===0?[o]:(Math.abs(t[t.length-1].startInProject+t[t.length-1].durationInProject-o.startInProject)<10?t[t.length-1].durationInProject=t[t.length-1].durationInProject+o.durationInProject:t.push(o),t),[]),NYe=e=>e.map(o=>({startInProject:Math.round(vo(o)*1e3),durationInProject:1})),dAt=(e,t,o,r,n)=>{if(!r&&!n)throw new C(_.C_LOGIC_ERROR,void 0,"videoOptions or audioOptions is required");return{timeSlices:e,video:r?{fps:r.fps,size:r.size}:void 0,audio:n?{sampleRate:n.sampleRate,channels:n.channels}:void 0,hwAccel:o,supplier:t}},PYe=(e,t)=>
4225(t?.firstFrameOnly?NYe:wYe)(e),uAt=e=>{if(e.length===0)return pe(0);const t=e[e.length-1];return pe((t.startInProject+t.durationInProject)/1e3)},bYe=dJ(e=>Nc(mo(e)),e=>PYe(e).map(t=>({startInProject:t.startInProject,durationInProject:t.durationInProject})),{memoizeOptions:{resultEqualityCheck:m1}}),LYe=e=>{let t=null;return(...o)=>{const r=e(...o);if(t!==null&&o5e(t.source,r))return t.store;const n=h8(r),a=I8(n);return t={source:n,store:a},a}},MYe=({getFileInfos:e})=>LYe((t,o,r=e())=>({transcript:rt(t),fileInfos:r,...o?{mediaSourceSignedUrlByMediaId:o}:{}})),DYe=e=>{if(Number.isFinite(e)&&e>0)return e;const t=pN();return h("thumbnailRenderProfile.ts").warn("thumbnail render profile: invalid ratio "+e+", falling back to project ratio "+t),t},kYe=e=>{const t=DYe(e),o=M8(t),r={fps:30,size:{width:RL(o.width),height:RL(o.height)},useHwAccel:!0,mode:"standard"};return{key:JSON.stringify(r),video:r}},FYe=({getProjectId:e,getState:t,getFileInfos:o})=>{const r=t();if(!r)throw new Error("thumbnail composition requires an initialized app state");return Object.freeze({projectId:e(),state:r,fileInfos:o(),textRenderLanguage:Fe()})},UYe=({getProjectId:e,getState:t,getFileInfos:o,revisionNamespace:r})=>{const n=MYe({getFileInfos:o});let a,i,s=0;return(x,c)=>{const{projectId:l,state:d,fileInfos:u,textRenderLanguage:p}=c??FYe({getProjectId:e,getState:t,getFileInfos:o}),f=n(d,x,u);return a&&(a!==f||i!==p)&&(s+=1),a=f,i=p,Object.freeze({projectId:l,store:f,timeSlices:bYe(d),profile:kYe(f.global.projectRatio),revision:r?r+":"+s:String(s),textRenderLanguage:p})}},VYe=(e,t)=>JSON.stringify([t,e.projectId,e.revision,e.profile.key]),lB=(e,t)=>o=>e({...o,composition:t}),pAt=({timelineSec:e,abortSignal:t,composition:o,captureRaw:r})=>{const n=X.fromSec(e).as.ms("round");return vYe({timelineMs:n,abortSignal:t,queueDeadlineMs:null,renderIdentity:VYe(o,n),run:lB(r,o)})},GYe=new Set(["Audio","Overdub"]);let dB=0;const WYe=mYe(),HYe=async({timelineMs:e,composition:t})=>{try{const o=await yYe({timelineMs:e,renderIdentity:"project-thumbnail-capture-"+dB++,coalescingIdentity:{},run:lB(WYe,t)});if(o.status==="failed")throw o.error;return o.status==="completed"?o.value:void 0}catch(o){return h("projectThumbnailCapture.ts").warn("project thumbnail capture failed: "+P(o)),void 0}},jYe=({state:e,projectId:t,fileInfos:o})=>{let r;try{const n=UYe({getProjectId:()=>t,getState:()=>e,getFileInfos:()=>o})();if(!Object.values(n.store.models).some(s=>!GYe.has(s.type)))return;const i="project-save-"+dB++;r=Object.freeze({...n,revision:i})}catch(n){return h("projectThumbnailCapture.ts").warn("project thumbnail capture failed: "+P(n)),void 0}return HYe({timelineMs:X.zero().as.ms(),composition:r})},zYe=2e3,YYe=e=>new Promise(t=>{const o=new Image,r=setTimeout(()=>t(e),zYe),n=a=>{clearTimeout(r),t(a)};o.onload=()=>{try{const a=GU*(window.devicePixelRatio||1),i=WA(o.width,o.height),s=document.createElement("canvas");s.width=i.width*a,s.height=i.height*a;const x=s.getContext("2d");if(!x){n(e);return}x.drawImage(o,0,0,s.width,s.height),n(s.toDataURL(im,sm))}catch(a){h("projectSaveThumbnail.ts").warn("project thumbnail downscale failed: "+P(a)),n(e)}},o.onerror=()=>n(e),o.src=e}),ZP=(e,t)=>{const o=W2();if(SG())return jYe({state:e,projectId:t,fileInfos:o});try{const r=o.find(yf)?.mediaId;return r===void 0||!pl(r)?void 0:D8().extract(pe(0),r,()=>!1,Gl,vh,Go.NONE).then(YYe).catch(n=>(h("projectSaveThumbnail.ts").warn("legacy project thumbnail capture failed: "+P(n)),void 0))}catch(r){return h("projectSaveThumbnail.ts").warn("legacy project thumbnail capture failed: "+P(r)),void 0}},fAt=async(e,t,o,r,n)=>{const{deviceId:a,deviceName:i}=await Ia(),s=5e3,x=uB(e,s),c=zt(x).pipe(V0((l,d)=>zt(j7(f_.HIGHLIGHT,Y3(on(t)),l,{uid:o,deviceId:a,deviceName:i})).pipe(er(u=>h("videoRemix.ts").info("highlight #"+(d+1),u)),At(u=>{if(!u)return null;try{const p=JSON.parse(u);return p.title&&p.highlightClipIndices&&p.highlightClipIndices.length>0?{title:p.title,highlightClipIndices:p.highlightClipIndices,lang:t,sceneId:r}:null}catch(p){return h("videoRemix.ts").error("Failed to parse highlight scene info: "+P(p)+", res: "+JSON.stringify(u)),null}}))),Fa(),jl(ri),aa(),er(l=>{if(l.length===0)throw new C(_.C_EXTRACT_HIGHLIGHT_FALIED);n(1)}),c0(l=>{h("videoRemix.ts").error("No valid highlight scene infos exist: "+P(l));const d=ye(l)??_.C_EXTRACT_HIGHLIGHT_FALIED,u=Ot(d,{defaultKey:"error.create_highlight_failed",errorDescKey:"common.no_usage_deduction"});return Y().error(d,u),Tt(void 0)}));return Bt(c)},uB=(e,t)=>{const o=[];let r="";
4225const n=e.split(`
4226`);for(let a=0;a<n.length;a++){const i=n[a];(r.length+i.length>t||(a+1)%100===0)&&(o.push(r.trim()),r=""),r+=i+`
4227`}return r.length>0&&o.push(r.trim()),o},BYe=async(e,t,o,r)=>{const{deviceId:n,deviceName:a}=await Ia(),i=t===ft.English||t===ft.Spanish?15e3:5e3,s=uB(e,i),x=(()=>{let l=0;return{inc:()=>++l}})(),c=zt(s).pipe(V0((l,d)=>zt(j7(f_.SUMMARY,t,l,{uid:o,deviceId:n,deviceName:a})).pipe(At(u=>{if(h("videoRemix.ts").info("summary #"+(d+1),u),!u)throw new C(_.C_VIDEO_REMIX_GENERATE_SUMMARY_FAILED);const p=JSON.parse(u);return p.forEach(f=>{if(!f.summary||!f.sources||f.sources.length===0)throw h("videoRemix.ts").info("Generate remix script invalid result: "+JSON.stringify(f)),new C(_.C_GENERATE_SUMMARY_INVALID_RESULT)}),r(x.inc()/s.length),p}))),At(l=>l.flat()),c0(l=>{h("videoRemix.ts").error("Failed to get summary scene infos: "+P(l));const d=ye(l)??_.C_VIDEO_REMIX_GENERATE_SUMMARY_FAILED,u=Ot(d,{defaultKey:"error.generate_summary_failed",errorDescKey:"common.no_usage_deduction"});return Y().error(d,u),Tt(void 0)}));return Bt(c)},gAt=async(e,t,o,r)=>{const n=await BYe(e,t,o,r);if(!n){r(0);return}const a=n.map(async i=>{const{summary:s,sources:x}=i,c=new Um({maxLineMode:"middle"}),l=await c.processInput(s,t);return{text:l.map(d=>d.raw).join(`
4228`),sourceClipIdx:x.at(0)??0,numClips:l.length}});return Promise.all(a)},KYe=e=>{const t=ho(),{title:o,highlightClipIndices:r,lang:n,sceneId:a}=e,i={from:0,to:r.length-1,type:"CLIP"},s=[{chunk:i,assetInfos:[{type:Hx.NEW,assetId:t,assetType:z.WEB,mediaId:Ao}],audioInfos:[]}],x=exe(o,n);return{...e,chunkData:s,assetOptions:{webAssetData:x,yPos:.08},sceneId:a}},XYe=async(e,t,o)=>await Y().popup(Abe(e,t,o))===mt.YES,_At=async(e,t,o,r)=>{let n;try{n=LR(r.length,e.voiceSetting.speaker.provider,e.voiceSetting.speaker.speakerId)}catch(x){h("videoRemix.ts").error("Failed to resolve Video Remix TTS pricing: "+P(x));const c=ye(x)??_.C_TTS_FETCH_SPEAKER_LIST_ERROR;return Y().error(c,Ot(c,{defaultKey:"error.tts_general_error",errorDescKey:"common.no_usage_deduction"})),{result:"error"}}return n===0&&t===Jf.SOURCE_VIDEO?{result:"confirm",ttsCredits:n}:await XYe(t,n,o)===!1?{result:"cancel",ttsCredits:n}:await epe(n)?t===Jf.SOURCE_VIDEO?{result:"confirm",ttsCredits:n}:await nMe(o*fP().credits,hg.VIDEO_REMIX)?{result:"confirm",ttsCredits:n}:{result:"quota_exceeded",ttsCredits:n}:{result:"quota_exceeded",ttsCredits:n}},JYe=(e,t)=>{const o=t.clips.filter((n,a)=>e.includes(a)),r=Bg(o);return{type:f_.HIGHLIGHT,sourceSceneDuration:JK(t),numSourceSceneClips:t.clips.length,resultSceneDuration:r,numResultSceneClips:o.length,sourceSceneTextLength:I2e(t.clips).length}},qYe=(e,t,o)=>{const{sourceSceneDuration:r,numSourceSceneClips:n,sourceSceneTextLength:a}=o,i=Bg(e);return{type:f_.SUMMARY,sourceType:t,sourceSceneDuration:r,numSourceSceneClips:n,resultSceneDuration:i,numResultSceneClips:e.length,sourceSceneTextLength:a}};var $P=(e=>(e.CUT="CUT",e.COPY="COPY",e))($P||{});let LC=null;const QYe=()=>{if(LC)return LC;const e=Mr();return LC={IS_LEFT:{verifyFunc:De("left"),returnKeycode:J.LEFT},IS_RIGHT:{verifyFunc:De("right"),returnKeycode:J.RIGHT},IS_UP:{verifyFunc:De("up"),returnKeycode:J.UP},IS_DOWN:{verifyFunc:De("down"),returnKeycode:J.DOWN},IS_SHIFT_LEFT:{verifyFunc:De("shift+left"),returnKeycode:J.SHIFT_LEFT},IS_SHIFT_RIGHT:{verifyFunc:De("shift+right"),returnKeycode:J.SHIFT_RIGHT},IS_SHIFT_UP:{verifyFunc:De("shift+up"),returnKeycode:J.SHIFT_UP},IS_SHIFT_DOWN:{verifyFunc:De("shift+down"),returnKeycode:J.SHIFT_DOWN},IS_MOD_LEFT:{verifyFunc:De("mod+left"),returnKeycode:J.MOD_LEFT},IS_MOD_RIGHT:{verifyFunc:De("mod+right"),returnKeycode:J.MOD_RIGHT},IS_MOD_UP:{verifyFunc:De("mod+up"),returnKeycode:J.MOD_UP},IS_MOD_DOWN:{verifyFunc:De("mod+down"),returnKeycode:J.MOD_DOWN},IS_SHIFT_MOD_LEFT:{verifyFunc:De("shift+mod+left"),returnKeycode:J.SHIFT_MOD_LEFT},IS_SHIFT_MOD_RIGHT:{verifyFunc:De("shift+mod+right"),returnKeycode:J.SHIFT_MOD_RIGHT},IS_SHIFT_MOD_UP:{verifyFunc:De("shift+mod+up"),returnKeycode:J.SHIFT_MOD_UP},IS_SHIFT_MOD_DOWN:{verifyFunc:De("shift+mod+down"),returnKeycode:J.SHIFT_MOD_DOWN},IS_ALT_UP:{verifyFunc:De("alt+up"),returnKeycode:J.ALT_UP},IS_ALT_DOWN:{verifyFunc:De("alt+down"),returnKeycode:J.ALT_DOWN},IS_ALT_LEFT:{verifyFunc:De("alt+left"),returnKeycode:J.ALT_LEFT},IS_ALT_RIGHT:{verifyFunc:De("alt+right"),returnKeycode:J.ALT_RIGHT},IS_SHIFT_ALT_UP:{verifyFunc:De("shift+alt+up"),returnKeycode:J.SHIFT_ALT_UP},IS_SHIFT_ALT_DOWN:{verifyFunc:De("shift+alt+down"),returnKeycode:J.SHIFT_ALT_DOWN},IS_SHIFT_ALT_LEFT:{verifyFunc:De("shift+alt+left"),returnKeycode:J.SHIFT_ALT_LEFT},IS_SHIFT_ALT_RIGHT:{verifyFunc:De("shift+alt+right"),returnKeycode:J.SHIFT_ALT_RIGHT},IS_ALT_DELETE:{verifyFunc:De("alt+del"),returnKeycode:J.DELETE_CAPTION},IS_OPTION_BACKSPACE:{verifyFunc:De("opt+backspace"),returnKeycode:e?J.DELETE_CAPTION:"NOTHING"},IS_HOME:{verifyFunc:De("home"),returnKeycode:J.HOME},IS_END:{verifyFunc:De("end"),returnKeycode:J.END},IS_SHIFT_HOME:{verifyFunc:De("shift+home"),returnKeycode:J.SHIFT_HOME},IS_SHIFT_END:{verifyFunc:De("shift+end"),returnKeycode:J.SHIFT_END},IS_MOD_HOME:{verifyFunc:De("mod+home"),returnKeycode:J.MOVE_TO_BEGINNING_VIDEO},IS_MOD_END:{verifyFunc:De("mod+end"),returnKeycode:J.MOVE_TO_END_VIDEO},IS_SHIFT_MOD_HOME:{verifyFunc:De("shift+mod+home"),returnKeycode:J.MOVE_TO_BEGINNING_VIDEO},IS_SHIFT_MOD_END:{verifyFunc:De("shift+mod+end"),returnKeycode:J.MOVE_TO_END_VIDEO},IS_MOD_P:{verifyFunc:De("mod+p"),returnKeycode:J.PLAY_P},IS_MOD_C:{verifyFunc:De("mod+c"),returnKeycode:J.COPY},IS_MOD_X:{verifyFunc:De("mod+x"),returnKeycode:J.CUT},IS_MOD_V:{verifyFunc:De("mod+v"),returnKeycode:J.PASTE},IS_MOD_Z:{verifyFunc:De("mod+z"),returnKeycode:J.UNDO},IS_MOD_Y:{verifyFunc:De("mod+y"),returnKeycode:J.REDO},IS_MOD_M:{verifyFunc:De("mod+m"),returnKeycode:J.MERGE_CLIPS},IS_MOD_E:{verifyFunc:De("mod+e"),returnKeycode:J.MERGE_CLIPS_2},IS_SHIFT_MOD_Z:{verifyFunc:De("shift+mod+z"),returnKeycode:J.REDO},IS_SHIFT_MOD_M:{verifyFunc:De("shift+mod+m"),returnKeycode:J.MERGE_PREVIOUS_CLIP},IS_SHIFT_MOD_E:{verifyFunc:De("shift+mod+e"),returnKeycode:J.MERGE_PREVIOUS_CLIP_2},IS_MOD_A:{verifyFunc:De("mod+a"),returnKeycode:J.SELECT_ALL},IS_MOD_S:{verifyFunc:De("mod+s"),returnKeycode:J.SAVE},IS_SHIFT_MOD_S:{verifyFunc:De("shift+mod+s"),returnKeycode:J.SAVE_AS},IS_ENTER:{verifyFunc:De("return"),returnKeycode:J.ENTER},IS_SHIFT_ENTER:{verifyFunc:De("shift+return"),returnKeycode:J.SHIFT_ENTER},IS_MOD_ENTER:{verifyFunc:De("mod+return"),returnKeycode:J.CTRL_ENTER},IS_F2:{verifyFunc:De("f2"),returnKeycode:J.F2},IS_F3:{verifyFunc:De("f3"),returnKeycode:J.F3},IS_F4:{verifyFunc:De("f4"),returnKeycode:J.PLAY_F4},IS_F5:{verifyFunc:De("f5"),returnKeycode:J.PLAY_F5},IS_F7:{verifyFunc:De("f7"),returnKeycode:J.F7},IS_SHIFT_F7:{verifyFunc:De("shift+f7"),returnKeycode:J.SHIFT_F7},IS_MOD_F7:{verifyFunc:De("mod+f7"),returnKeycode:J.MOD_F7},IS_SHIFT_MOD_F7:{verifyFunc:De("shift+mod+f7"),returnKeycode:J.SHIFT_MOD_F7},IS_F8:{verifyFunc:De("f8"),returnKeycode:J.F8},IS_MOD_F8:{verifyFunc:De("mod+f8"),returnKeycode:J.MOD_F8},IS_ESCAPE:{verifyFunc:De("escape"),returnKeycode:J.ESCAPE},IS_SHIFT_ESCAPE:{verifyFunc:De("shift+escape"),returnKeycode:J.SHIFT_ESCAPE},IS_BACKSPACE:{verifyFunc:De("backspace"),returnKeycode:J.BACKSPACE},IS_SPACE:{verifyFunc:De("space"),returnKeycode:J.PLAY_SPACE},IS_DELETE:{verifyFunc:De("del"),returnKeycode:J.DELETE},IS_TAB:{verifyFunc:De("tab"),returnKeycode:J.PLAY_TAB},IS_SHIFT_TAB:{verifyFunc:De("shift+tab"),returnKeycode:J.PLAY_SHIFT_TAB},IS_TOGGLE_SEARCH:{verifyFunc:De("mod+f"),returnKeycode:J.TOGGLE_SEARCH},IS_TOGGLE_DEBUG:{verifyFunc:De("mod+d"),returnKeycode:J.TOGGLE_DEBUG},IS_GT:{verifyFunc:De("mod+."),returnKeycode:J.PLAY_FASTER},IS_LT:{verifyFunc:De("mod+,"),returnKeycode:J.PLAY_SLOWER},IS_TRANSLATE:{verifyFunc:De("mod+r"),returnKeycode:J.TRANSLATE},IS_SHORTCUTS:{verifyFunc:De("mod+/"),returnKeycode:J.TOGGLE_SHORTCUTS},IS_MOD_B:{verifyFunc:De("mod+b"),returnKeycode:J.CTRL_B},IS_SHIFT_MOD_B:{verifyFunc:De("shift+mod+b"),returnKeycode:J.SHIFT_MOD_B},IS_MOD_SEMICOLON:{verifyFunc:De("mod+;"),returnKeycode:J.CTRL_SEMICOLON},IS_MOD_I:{verifyFunc:De("mod+i"),returnKeycode:J.CTRL_I},IS_MOD_K:{verifyFunc:De("mod+k"),returnKeycode:J.INSERT_MARKER_RECENT},IS_MOD_J:{verifyFunc:De("mod+j"),returnKeycode:J.TOGGLE_CURSOR_MOVER_MENU},IS_MOD_O:{verifyFunc:De("mod+o"),returnKeycode:J.OPEN_PROJECT},IS_MOD_W:{verifyFunc:De("mod+w"),returnKeycode:J.CLOSE},IS_FEATURE_SEARCH:{verifyFunc:t=>De("mod+u")(t)&&Mr()||De("mod+q")(t)&&!Mr(),returnKeycode:J.FEATURE_SEARCH},IS_ALT_A:{verifyFunc:De("alt+a"),returnKeycode:J.ALT_A},IS_ALT_S:{verifyFunc:De("alt+s"),returnKeycode:J.ALT_S},IS_ALT_D:{verifyFunc:De("alt+d"),returnKeycode:J.ALT_D},IS_ALT_F:{verifyFunc:De("alt+f"),returnKeycode:J.ALT_F},IS_NEW_WINDOW:{verifyFunc:Oo()?De("mod+n"):De("alt+n"),returnKeycode:J.NEW_WINDOW}}};function ZYe(e){const t=QYe();for(const o in t)if(t[o].verifyFunc(e))return t[o].returnKeycode;return"NOTHING"}const pB=.1,S_=e=>parseFloat(e.toFixed(2)),fB=(e,t)=>S_(e-t),lf=(e,t)=>S_(e+t),$Ye=(e,t)=>
4228{const o=[],r=[],n=t[t.length-1].endTime;return e.forEach(a=>{const i=Tw();vo(a)<=n?o.push(a):r.push({...a,captions:i,captionMode:ar.MANUAL})}),[o,r]},MC=(e,t,o)=>({sceneId:e,clipId:ct(),captions:[{text:wt().fromText(t)},{text:wt().fromText("")}],words:o,startPosition:-1,assetIds:[],captionMode:ar.MANUAL,dirty:{video:!1,caption:!1,blankDeleted:!1},translationModified:{source:!1,result:!1}}),PF=e=>S_(fl(e)),e8e=e=>e.map(t=>t.words).flat().filter(t=>t.type!==Z.ENTER),t8e=e=>e.map(t=>({...t,duration:pe(S_(t.duration))})),bF=(e,t,o,r,n)=>{const{startTime:a,endTime:i}=o,s=[];let x=t,c=e;const l={...n},d={...r};for(;x.length;){const u=x[0];if(!u)break;const p=sr(u),f=lf(c,p),E=KCe(c,f,a,i);if(BCe([a,i],[c,f])){s.push(u),c=lf(c,p),x.shift();continue}else if(E){const O=c<a?a:i,S=fB(O,c),R=pe(S*u.playbackRate),y=dW(R,u,r,n);if(!y){s.push(u),c=lf(c,p),x.shift();continue}const{splitWords:v,newAssetEntries:w,newTrackEntries:N}=y,[M,k]=v;x.shift(),x=[M,{...k,text:"",type:Z.SOUND},...x],Object.entries(w).forEach(([F,G])=>{L.set(l,Je(F),G)}
4228),Object.entries(N).forEach(([F,G])=>{L.set(d,kr(F),G)});continue}else break}return{words:[s,x],newAssetEntries:l,newTrackEntries:d}},EAt=(e,t,o,r,n,a)=>{if(o.length===0)return{clips:t,newAssetEntries:a,newTrackEntries:n};const i=[],s="";let x={...a},c={...n};const[l,d]=$Ye(t,o);let u=t8e(e8e(l));if(o[0]?.startTime>0){const E={startTime:0,endTime:o[0].startTime,text:s};o.unshift(E)}let p=S_(r);if(o.forEach((E,T)=>{const O=o[T+1];let S=[],R=[],y=!1;const{words:[v,w],newAssetEntries:N,newTrackEntries:M}=bF(p,u,E,c,x);if(x={...x,...N},c={...c,...M},p=lf(p,PF(v)),u=w,S=v,O&&fB(O.startTime,E.endTime)>0){const k=O?.startTime||0,F=E.endTime,G=k||E.endTime,B={startTime:F,endTime:G},{words:[W,Q],newAssetEntries:j,newTrackEntries:$}=bF(p,u,B,c,x);x={...x,...j},c={...c,...$};const q=PF(W);p=lf(p,q),u=Q,R=W,q>pB&&(y=!0)}if(!y&&(S=[...S,...R],R=[]),S.length){Dx(S);const k=MC(e,E.text,S);i.push(k)}if(R.length){Dx(R);const k=MC(e,s,R);i.push(k)}}),u.length>0){Dx(u);const E=MC(e,s,u);i.push(E)}return{clips:[...i,...d],newAssetEntries:x,newTrackEntries:c}},mAt=(e,t)=>e.filter(o=>o.endTime>t).map(o=>({...o,startTime:Math.max(o.startTime,t)})),o8e=e=>e.map(t=>({...t,startTime:parseFloat((t.startTime/1e3).toFixed(2)),endTime:parseFloat((t.endTime/1e3).toFixed(2))})),r8e=e=>e.map((t,o)=>{const r=e[o+1]?.startTime;return{...t,endTime:r?Math.min(t.endTime,r):t.endTime}}),n8e=e=>{const t=o8e(e);return r8e(t)},a8e=async(e,t)=>{const o=os(e),r=os(t),n=jt.createElement("div",{className:"two-line"},A("import.subtitle_useless_srt_line_exist",{projectTime:o,srtTime:r}).split(`
4229`).map((i,s)=>jt.createElement("div",s===0?{className:"first-line"}:void 0,jt.createElement(Qr,void 0,i)))),a={bodyClassName:"general-modal",title:A("import.subtitle_caution_for_useless_srt_line"),content:n,yesStr:A("import.confirm_srt_import")};await Y().popup(a)},i8e=(e,t)=>{const o=KK(e),r=gB(t,o),n=_B(t),a=t.length&&t[0].startTime>0?1:0,i=t.filter((c,l)=>{const d=t[l+1];return!!(d&&d.startTime<o&&d.startTime-c.endTime>pB)}).length,s=e.map(c=>c.clips).flat().filter(c=>vo(c)>n).length;return r?t.filter(c=>c.startTime<o).length+i+a:t.length+s+i+a},gB=(e,t)=>e.filter(o=>o.startTime>t).length>0,_B=e=>e.length?e[e.length-1].endTime:0,s8e=e=>{const t=/(\d+)\n((?:\d{1,2}:)?\d{2}:\d{2}[,.]\d{1,6})\s*-->\s*((?:\d{1,2}:)?\d{2}:\d{2}[,.]\d{1,6})\n?([\s\S]*?(?=\n\d+\n(?:\d{1,2}:)?\d{2}:\d{2}[,.]\d{1,6}|$|\n\n))/g;return Array.from(e.replace(/\r\n/g,`
4230`).matchAll(t),o=>{const[r,n,a]=o.slice(2),i=LF(r.trim()),s=LF(n.trim());return{startTime:i,endTime:s,text:a.trim()}})},x8e=e=>e.length===3?[0,...e]:e,c8e=([e,t,o,r])=>e*36e5+t*6e4+o*1e3+r,LF=s1(e=>e.replace(",",".").split(/[:.]/).map(t=>t.slice(0,3)).map(Number),x8e,c8e),l8e=e=>{const t=e.filter(r=>r.captionIndex===Ke.ORIGINAL).length!==0,o=e.filter(r=>r.captionIndex===Ke.TRANSLATE).length!==0;return t&&o?"both":t&&!o?"original":!t&&o?"translate":"none"},d8e=async(e,t,o,r,n)=>{try{const a=await Uu(e,{engine:Ea.GPT},t,o,r,n);return{translatedCaptions:a.flatMap(s=>s.translations.map(x=>({text:x}))),sids:a.map(s=>s.sid)}}catch(a){h("caption.ts").error(a);const i=Ne(a)?a:new C(_.C_TRANSLATION_FAILED_ERROR,Ho(a));if(dh(i.errorCode,i.errorArgs),i.errorCode===_.C_REQUEST_QUOTA_EXCEEDED_ERROR)throw i;const s=await Uu(e,{engine:Ea.GOOGLE},t,o,r,n);return{translatedCaptions:s.flatMap(c=>c.translations.map(l=>({text:l}))),sids:s.map(c=>c.sid)}}},u8e=async(e,t,o,r,n)=>{const a=await U3(e,t);try{const i=await Uu(a.map(l=>l.text),{engine:Ea.GPT},t,o,r,n),s=i.flatMap(l=>l.translations),x=s.map((l,d)=>({text:l,numClause:a[d].numClause}));return{translatedCaptions:await km(x,o),sids:i.map(l=>l.sid)}}catch(i){h("caption.ts").error(i);const s=Ne(i)?i:new C(_.C_TRANSLATION_FAILED_ERROR,Ho(i));if(dh(s.errorCode,s.errorArgs),s.errorCode===_.C_REQUEST_QUOTA_EXCEEDED_ERROR)throw s;const x=await Uu(a.map(u=>u.text),{engine:Ea.GOOGLE},t,o,r,n),c=x.flatMap(u=>u.translations),l=c.map((u,p)=>({text:u,numClause:a[p].numClause}));return{translatedCaptions:await km(l,o),sids:x.map(u=>u.sid)}}},DC=async(e,t)=>{const o=e.split(`
4231`).join(vu);return await UK(t,o)},p8e=async(e,t,o)=>{if(e.length===1&&e[0].caption)return await DC(e[0].caption,t);const r=ti(t),n=gt(t),a=e.map(x=>{const{lang:c}=x,l=r+Nu(n)+"-"+A("translation_language."+c,{defaultValue:c})+("."+o);return{...x,path:l}}),i=Ue();if(i instanceof l_){const x=a.filter(u=>u.caption!==null);if(x.length===0)return;if(x.length===1){const{path:u,caption:p}=x[0];return await DC(p,u)}const c=new t1;x.forEach(({path:u,caption:p})=>{c.file(gt(u),kK+p.split(`
4232`).join(vu))});const l=await c.generateAsync({type:"blob"}),d=Nu(n)+".zip";return i.downloadBlobAsFile(l,d),d}if(at()){const x=await yn().getExistingFiles(a.map(c=>c.path));if(x.length!==0){const c=gt(x[0]),l={bodyClassName:"general-modal",title:A("popup.title_confirm"),content:A("export.overwrite_file?",{number:x.length,filename:c}),yesStr:A("popup.confirm"),noStr:A("popup.cancel")};if(await Y().popup(l)!==mt.YES)return}}let s;for(const x of a){const{path:c,caption:l}=x;if(l===null)continue;s=await DC(l,c)}return s},f8e=async(e,t)=>{const o=se(),r=o.getCurrentProjectFileType(),n=r===Ee.BROWSER?(await Kf(o.getCurrentProjectPath())??o.getCurrentProjectPath())+"."+e:r===Ee.CLOUD?(Lt().getVCloudProjectInfo(o.getProjectId())?.projectTitle??o.getCurrentProjectPath())+"."+e:MCe(o.getCurrentProjectPath(),e),a=zu(n,!0),i={srt:A("toolbar.export_caption_title"),txt:t?.withTimecode?A("export.timeco
4232de_text_title"):A("export.text_title")},s=await fb(a,e,i[e]);if(s!=="")return s},EB=(e,t)=>{switch(e){case Yp.NONE:return Ar(t)?" ":"";case Yp.BY_NEW_LINE:return`
4233`;case Yp.BY_SKIP_LINE:return`
4234
4235`}},g8e=(e,t,o,r,n,a)=>{switch(e){case"srt":return e2e(t,o,r);case"txt":{if(a===void 0)return"";const{withTimecode:i,enableClipJoinOptions:s}=a,x=Ar(o);return i?t.map(d=>{const u=os(vo(d)),p=Hn(d,x,n);return u+"	"+p}).join(`
4236`):t.map(l=>Hn(l,x,n)).join(EB(s,o))}}},_8e=(e,t,o,r,n)=>{switch(e){case"srt":return $ue(t,o);case"txt":{if(n===void 0)return"";const{withTimecode:a,enableClipJoinOptions:i}=n;return o.map(c=>c.text||"").map((c,l)=>{const d=os(vo(t[l]));return a?d+"	"+c:c}).join(a?`
4237`:EB(i,r))}}},hAt=(e,t,o,r)=>async(n,a)=>{const i=await f8e(t,r);if(!i)return;const s=Ad(),x=e.map(R=>({...R,caption:null})),c=m0(A("export.prepare")),l=a(),d=tc(l),u=mo(l),p=oc(l),{encodeClips:f}=xT(l,o),E=lt(l),T=ht(l),O=k2(l)?CT(l):"",S={srt:Kt.SRT,txt:Kt.TXT};Tt({results:x,scenes:u,encodeClips:f,projectAudioLanguage:d,fileType:t,savePath:i,options:r,progressPopup:c,dispatch:n,ga:{didTranslationOccurInProject:p,trackEntries:E,assetEntries:T,exp
4237ortPayload:HT(l,WT(S[t]),o,{},s),cutEditPayload:BT(l),translatePayload:zT(l,s,S[t],l8e(x),e.filter(R=>R.captionIndex===null).length)},uid:O}).pipe(er(R=>{const y={srt:Kc.EXPORT_CAPTION,txt:Kc.EXPORT_TEXT};R.dispatch(uS(y[R.fileType]))}),Ma(async R=>{const{results:y,encodeClips:v,options:w}=R,N=[Sf.ORIGINAL_ONLY,Sf.TRANSLATED_ONLY],M=zt(y).pipe(At(F=>{const{lang:G,captionIndex:B}=F;if(B===null)return F;const W=g8e(R.fileType,v,G,N[B],B,w);return{...F,caption:W}}),aa()),k=await Bt(M);return{...R,results:k}}),er(R=>{R.progressPopup.message(A("export.translating_to_lang"))}),Ma(async R=>{const{results:y,projectAudioLanguage:v,scenes:w,fileType:N,encodeClips:M,options:k,uid:F}=R,G=on(v),B=w.map(H=>Xue(H.clips,G)).flat(),W=B.flat().join("").length,Q=y.filter(H=>H.caption===null).length,j=W*Q;if(await H3(j))return;const $=zt(y).pipe(Ma(async H=>{const{lang:U,caption:te}=H;if(te!==null)return{...H,sids:[]};const ne=Fm(G)&&Fm(U),{translatedCaptions:oe,sids:re}=ne?await u8e(B,G,U,N,F):await d8e(B,G,U,N,F),ge=_8e(N,M,oe,U,k);return{...H,caption:ge,sids:re}}),aa()),q=await Bt($);return{...R,results:q}}),uJ(R=>R!==void 0),er(R=>{const{results:y}=R;y.forEach(v=>{const{lang:w,captionIndex:N}=v;N===null&&R2e(w)})}),Ma(async R=>{const{results:y,fileType:v,savePath:w}=R,N=await p8e(y,w,v),M=y.flatMap(k=>k.sids).filter(Se);return M.length>0&&(await G3(O,M),await be().fetchUserInfo()),{...R,resultPath:N}}),er(R=>{const{resultPath:y,fileType:v}=R;y&&FK(v,y)}),er(R=>{const{scenes:y,results:v,fileType:w,options:N,ga:{exportPayload:M,cutEditPayload:k,translatePayload:F,didTranslationOccurInProject:G,trackEntries:B,assetEntries:W}}=R,Q=sp(y,B,W).length,j=y.length;switch(w){case"srt":{BMe(Q,j,s);break}case"txt":{KMe((o===Vo.ALL_CLIPS?so.ALL:so.SELECTED)+"-"+(N?.withTimecode?"with":"without")+"_timecode",Q,j,s);break}}const{markerNum:$,clipsNum:q}=Eb(y,B,W);EP($,q,s),jT(M,k);const H=v.filter(U=>U.captionIndex===null).map(U=>U.lang);H.length>0&&Pke(H),G&&YT(F)})).subscribe({next:()=>{},error:R=>{c.dismiss(),h("caption.ts").error(t+" Export failed");const y=ye(R)??_.C_TRANSLATION_FAILED_ERROR,v=Ho(R);h("caption.ts").error(P(R)),W3(y,"error.translation_failed",v)},complete:()=>{c.dismiss()}})},IAt=(e,t)=>({type:_r.IMPORT_CAPTION,payload:{captions:e,captionIndex:t}}),E8e=(e,t,o,r,n,a)=>i=>{const s=is([e]),x={type:_r.UPDATE_CAPTION,payload:{globalClipChunks:s,caption:r,editCaption:n,captionIndex:t,captionLanguage:o,updateReason:a}};return i(x)},m8e=e=>async(t,o)=>{const r=o(),n=He(r),a=Od(r),i=oc(r),s=a.length>0?a:n.map((x,c)=>c);if(a.length===0){const x=Tbe(e,i);if(await Y().popup(x)!==mt.YES)return}t({type:_r.REMOVE_CAPTION_ON_CLIPS,payload:{globalClipChunks:is(s),captionIndex:e}})},TAt=(e,t,o,r,n,a={})=>async(i,s)=>{const{showSuccessToast:x=!0}=a;po(ke.IMPORT_SCRIPT_SETTING,{...n.splitOptions});const c=m0(Sa(A("import.script_start"))),l=R=>{const y=A("import.script_progress",{progress:R});c.message(Sa(y))},d=on(r),u=t.slice(o.from,o.to),p=u.reduce((R,y)=>R+y.clips.length,0),f=s(),{captionDisplayMode:E}=rt(f),T=n.splitOptions,O=0;let S=0;try{const{allClips:R,allClipWords:y,matchResult:v,mergedCaptions:w}=await _pe(e,u,d,l,T);i(I8e(R,y,v,d,w,O,o)),S=v.length}catch(R){i($u(E)),c.dismiss(),h("caption.ts").error(P(R));const y=ye(R)??_.C_SCRIPT_IMPORT_ERROR,v=Ot(y,{defaultKey:"import.load_script_error"});return Y().error(y,v),mP(y),!1}try{if(c.dismiss(),i(g1e()),x){const R=Ta(It.SCRIPT_IMPORT);setTimeout(()=>{const y="import_script",v=To.generateToastOption(y,Na.WITH_BUTTON,R?xm:!1,()=>{wn(It.SCRIPT_IMPORT)}),w=To.generateToastComponentWithButton(A("import.script_success"),A("import.script_cancel"),()=>{i(qx.ActionCreators.undo()),wz(tu.TOAST),i($u(E)),To.dismiss(y)}),N=To.popup(w,{...v});new jN(N).asClosable(R?xm:!1)},WU)}oDe(u.length,o,p,S,{...n})}catch(R){h("caption.ts").error(P(R))}return!0},SAt=(e,t)=>async(o,r)=>{const n=r(),{captionDisplayMode:a}=rt(n);if(Object.values(Ke).includes(e)===!1)return;const i={...a,[e]:!a[e]},s=e===Ke.ORIGINAL?wA.ORIGINAL:wA.TRANSLATE;XDe(i[e],t,s),o($u(i))},OAt=(e,t)=>async(o,r)=>{const n=r(),{captionDisplayMode:a}=rt(n);if(Object.values(Ke).includes(e)===!1||a[e]===t)return;const i={...a,[e]:t};o($u(i))},h8e=e=>t=>{const o=Ta(It.SUBTITLE_IMPORT);setTimeout(()=>{const r="import_subtitle",n=To.generateToastOption(r,Na.WITH_BUTTON,o?xm:!1,()=>{wn(It.SUBTITLE_IMPORT)}),a=To.generateToastComponentWithButton(A("import.subtitle_success"),A("import.subtitle_cancel"),()=>{t(qx.ActionCreators.undo()),Pz(tu.TOAST),t($u(e)),To.dismiss(r)}),i=To.popup(a,{...n});new jN(i).asClosable(o?xm:!1)},WU)},CAt=(e,t)=>async(o,r)=>
4237{const n=Y(),a=h("caption.ts");try{LDe(),a.info("Loading subtitle file "+e.name);const i=await n2e(e,t);if(i===null)return;const s=s8e(i);if(s.length===0){const T=`
4238      Subtitle length is 0.
4239      first 5 lines of rawFile : 
4240        `+i.split(`
4241`).slice(0,5).join(`
4242`)+`
4243      `;throw new C(_.C_SUBTITLE_IMPORT_NO_LINE_ERROR,{},T)}const x=mo(r()),c=xn(r()),l=n8e(s);a.info("target srt line length: "+s.length);const d=KK(x),u=gB(l,d),p=_B(l),f=x.reduce((T,O)=>T+O.clips.length,0),E=i8e(x,l);a.info("project total duration: "+d+", subtitle's last end timestamp: "+p+", subtitle line number: "+l.length),u&&await a8e(d,p),o({type:_r.IMPORT_SUBTITLE,payload:{subtitles:l}}),o(h8e(c)),MDe(x.length,u,f,E,d,p)}catch(i){const s="Error occured while generating clips from srt lines.."+P(i),x=ye(i)??_.C_SUBTITLE_IMPORT_ERROR;a.error(s);const c=Ot(x,{defaultKey:"import.load_subtitle_error"});n.error(x,c),bDe(x)}},I8e=(e,t,o,r,n,a,i)=>({type:_r.IMPORT_MATCHED_SCRIPT,payload:{clips:e,words:t,startWordIndices:o,lang:r,captions:n,captionIndex:a,targetSceneRange:i}}),$u=(e,t)=>o=>{t!==!0&&o(yu()),o({type:_r.CHANGE_CAPTION_DISPLAY_MODE,payload:{captionDisplayMode:e}})},T8e=(e,t,o,r)=>({type:_r.CHANGE_CAPTION_SETTING,payload:{captionStyleValues:e,targetClipChunks:t,captionIndex:o,updateReason:r}}),S8e=(e,t,o,r)=>({type:_r.CHANGE_CAPTION_SETTING_COLLAPSED,payload:{captionStyleValues:e,targetClipChunks:t,captionIndex:o,updateReason:r}}),mB=(e,t,o,r)=>(n,a)=>{const i=a(),s=Nn(i),x=He(i),c=ec(i),l=Tn(i),{captionDisplayMode:d}=rt(i),{webModelTextSelection:u,editCaption:p}=l,f=w2(x,c,s,d,u,p);n(_1e(f?.targetGlobalClipIndices));const E=t?S8e:T8e,T=e.quillStyle?.size!==void 0,O=e.quillStyle?.font!==void 0;if(r&&C8e(e,f,r),f){const S=is(f.targetGlobalClipIndices);n(E(e,S,f.captionIndex,o)),(T||O)&&n(DF(f.targetGlobalClipIndices));return}n(E(e,null,void 0,o)),(T||O)&&n(DF(null))},hB=(e,t)=>({type:_r.DELETE_CAPTION_SETTING,payload:{globalClipChunks:e,captionIndex:t}}),RAt=(e,t)=>o=>{const r=is([e]);o(hB(r,t))},O8e=(e,t)=>{if((e===null||e.captionIndex===void 0)&&t===null)return;const o=e&&e.captionIndex!==void 0?e.globalClipIndex:t.globalClipIndex,r=e&&e.captionIndex!==void 0?e.captionIndex:t.captionIndex;return{globalClipIndex:o,captionIndex:r}},AAt=()=>(e,t)=>{const o=t(),r=Od(o),n=Tn(o);if(r.length>0){const s=is(r);return ak(r.length,!0),e(MF(s))}if(ak(1,!0),n.cursorMode===we.CAPTION){const{webModelTextSelection:s,editCaption:x}=n,c=O8e(s,x);if(c===void 0)return;const l=c.globalClipIndex,d=is([l]);return e(hB(d,c.captionIndex))}const a=ec(o),i=is([a]);return e(MF(i))},MF=e=>({type:_r.DELETE_CAPTION_SETTING_CLIPS,payload:{globalClipChunks:e}}),yAt=(e,t)=>({type:_r.DISASSEMBLE_CAPTION_GROUP,payload:{clipIndex:e,...t}}),vAt=(e,t,o,r)=>(n,a)=>{const i=a(),s=Do(i),x=s[e].captions[t];return x.style&&x.style.yAlign==="custom"&&x.style.xOffset===o&&x.style.yOffset===r?n:n({type:_r.MOVE_CAPTION_TEXTBOX,payload:{clipIndex:e,captionIndex:t,xPos:o,yPos:r}})},wAt=(e,t,o,r,n,a)=>(i,s)=>{const x=s(),c=Do(x),l=c[e].captions[t];return l.style&&l.style.yAlign==="custom"&&l.style.xOffset===o&&l.style.yOffset===r&&l.style.width===n&&l.height===a?i:i({type:_r.RESIZE_CAPTION_TEXTBOX,payload:{clipIndex:e,captionIndex:t,xPos:o,yPos:r,width:n,height:a}})},NAt=(e,t,o)=>(r,n)=>{const a=n(),i=Do(a),s=i[e].captions[t];return s.style&&s.style.rotation===o?r:r({type:_r.ROTATE_CAPTION_TEXTBOX,payload:{clipIndex:e,captionIndex:t,rotation:o}})},PAt=(e,t,o,r,n,a)=>({type:_r.TRANSFORM_CAPTION_TEXTBOX,payload:{clipIndex:e,captionIndex:t,xPos:o,yPos:r,width:n,rotation:a}}),bAt=(e,t,o,r)=>({type:_r.UPDATE_CAPTION_DELTA,payload:{globalClipIndex:e,captionIndex:t,delta:o,updateReason:r}}),LAt=(e,t,o,r)=>({type:_r.UPDATE_CAPTION_ATTRIBUTE,payload:{globalClipIndex:e,captionIndex:t,attribute:o,updateReason:r}}),DF=e=>(t,o)=>{const r=o(),n=He(r),a=e??n.map((c,l)=>l),i=is(a),s=e===null,x={type:_r.RESET_CAPTION_HEIGHT,payload:{globalClipChunks:i,preserveCaptionStyle:s}};return t(x)},C8e=(e,t,o)=>{const{quillStyle:r,captionStyleSetting:n}=e,{tab:a,target:i,hasSelectedClips:s}=o,x=t?.targetGlobalClipIndices.length.toString()??"default",c=JSON.stringify({target:i.valueOf(),clip_count:x});if(n&&(n.customAttributes?.find(u=>u.attributeName==="--textbox-color")&&eUe(a,c),"assetEffectInfo"in n)){const u=t?.targetGlobalClipIndices.length;xUe(n.assetEffectInfo,i,s??!1,u)}if(r)switch(!0){case"bold"in r:XFe(a,c);break;case"italic"in r:JFe(a,c);break;case"size"in r:qFe(a,r.size??"",c);break;case"color"in r:QFe(a,c);break;case"outline-color"in r:ZFe(a,c);break;case"outline-weight"in r:$Fe(a,r["outline-width"]??"",c);break;case"shadow-color"in r:tUe(a,c);break;case"background"in r:oUe(a,c);break}},R8e=(e,t)=>
4243{switch(e.type){case"letter-spacing":return{quillStyle:{"letter-spacing":e.value.toString()}};case"line-height":return{quillStyle:{"line-height":e.value.toString()}};case"color":return{quillStyle:{color:e.color.toLowerCase()}};case"outline":return e.color===void 0?{quillStyle:{"outline-on":e.stroke?"true":"false","outline-width":(e.stroke??0).toString()}}:e.color===Ri?{quillStyle:{"outline-on":"false","outline-color":void 0,"outline-width":void 0}}:{quillStyle:{"outline-on":"true","outline-color":e.color?.toLowerCase(),"outline-width":(e.stroke===0||e.stroke===void 0?go.OUTLINE_WIDTH:e.stroke).toString()}};case"shadow":return e.color===Ri?{quillStyle:{"shadow-on":"false","shadow-color-alpha":"0","shadow-blur-radius":"0"}}:{quillStyle:{"shadow-on":"true","shadow-color":e.color.toLowerCase(),"shadow-blur-radius":"4","shadow-color-alpha":"0.5"}};case"highlight":return e.color===Ri?{quillStyle:{"background-on":"false"}}:{quillStyle:{"background-on":"true",background:e.color.toLowerCase(),"background-alpha":"1","background-radius":"0"}};case"size":return{quillStyle:{size:e.size.toString()}};case"font_family":return{quillStyle:{font:e.font}};case"position":return e.direction==="x"?{captionStyleSetting:{xOffset:e.position}}:{captionStyleSetting:{yOffset:e.position}};case"align":if(e.direction==="x"){const o=hw(e.align),r={attributeName:"--textbox-align",value:o},n=rn.cloneDeep(t);return M3(n,r),{captionStyleSetting:{customAttributes:n.customAttributes}}}else return{captionStyleSetting:{yAlign:Iw(e.align),yOffset:0}};case"bold":return{quillStyle:{bold:e.on?"true":void 0}};case"italic":return{quillStyle:{italic:e.on?"true":void 0}}}},MAt=e=>(t,o)=>{const r=o(),n=Vv(r),a=R8e(e,n),i=Uv(r),s=gxe(r);t(mB(a,e.collapse,cm.TOOLBAR,{tab:e.tab===bo.HOME?m.TOOLBAR_HOME:m.TOOLBAR_FORMAT,hasSelectedClips:s,target:i.target})),i.target===Xa.ALL&&A8e(e)},A8e=e=>{switch(e.type){case"color":return po(ke.LAST_USED_CAPTION_TEXT_COLOR,e.color);case"outline":{const t=e.color===Ri?0:e.stroke;po(ke.LAST_USED_CAPTION_OUTLINE_COLOR,e.color),po(ke.LAST_USED_CAPTION_OUTLINE_WIDTH,t);break}case"shadow":return po(ke.LAST_USED_CAPTION_SHADOW_COLOR,e.color);case"highlight":return po(ke.LAST_USED_CAPTION_HIGHLIGHT_COLOR,e.color);case"position":{const t=e.direction==="x"?Ie.LAST_CAPTION_POS_INFO_X:Ie.LAST_CAPTION_POS_INFO_Y;return Ve().set(t,e.position)}case"align":{const t=e.direction==="x"?Ie.LAST_CAPTION_POS_INFO_X_ALIGN:Ie.LAST_CAPTION_POS_INFO_Y_ALIGN;return e.direction==="y"&&Ve().set(Ie.LAST_CAPTION_POS_INFO_Y,0),Ve().set(t,e.align)}default:return}},DAt=e=>(t,o)=>{const r=o(),n=Tn(r).cursorMode,a=ht(r),i=lt(r),s=_0(r),x=RI(s),c=Uv(r).target;if(n===we.ELEMENT&&x!==null){const p=L.get(a,x);if(!p){kC(e,c);return}const f=p.trackIds.map(E=>L.get(i,E)).find(E=>E!==void 0&&Wn(E));if(f){t(p9e(f.trackId,e,cm.TOOLBAR)),kC(e,c);return}}const l=Gxe(r),d=rn.cloneDeep(l);M3(d,e);const u={captionStyleSetting:{customAttributes:d.customAttributes}};t(mB(u,!1,cm.TOOLBAR,{tab:m.TOOLBAR_FORMAT,target:c})),kC(e,c)},kC=(e,t)=>{t===Xa.ALL&&e.attributeName==="--textbox-color"&&po(ke.LAST_USED_CAPTION_BACKGROUND_COLOR,e.value)},y8e=async(e,t)=>{const o=e.files.filter(i=>!ia(i.mediaId)).filter(i=>i.fileLocation===D.REMOTE),r=An(10),n=t.signal;if(o.length===0)return e;const a=Object.fromEntries(await Promise.all(o.map(i=>r(async()=>{try{if(Zr(i)){n.throwIfAborted();const x=await hm(i.url,n),{resolvedPath:c}=await Ue().putLocalCache({mediaId:i.mediaId,blob:x,ext:yo(i.url)});return[i.mediaId,c]}const s=await hm(i.url,n);return MR(i)?(await yi({type:"blob",blob:s,name:i.name},i.mediaId,i.sourceOrigin),[i.mediaId,""]):[i.mediaId,s]}catch(s){throw h("clipboard.ts").error("Failed to download or process file for clipboard "+i.mediaId+": "+s),s}}))));return{...e,blobs:{...e.blobs,...Object.fromEntries(Object.entries(a).filter(([,i])=>i instanceof Blob).map(([i,s])=>[i,s]))},files:e.files.map(i=>{if(ia(i.mediaId)||!Zr(i)&&!MR(i))return{...i,fileLocation:D.IN_MEMORY};const s={mediaId:i.mediaId,sourceOrigin:i.sourceOrigin,fileSize:i.fileSize,name:i.name,type:i.type,videoAudioMetaInfo:i.videoAudioMetaInfo,sourceType:i.sourceType};switch(i.sourceType){case de.VIDEO_AUDIO:return{...s,fileLocation:D.LOCAL_TMP,path:a[i.mediaId]};case de.ASSET_VIDEO:return{...s,fileLocation:D.LOCAL_TMP,path:a[i.mediaId]};default:return i}})}},v8e=async(e,t)=>{const o=h("clipboard.ts"),r=se(),n=r.getProjectId();if(!n)throw o.error("No project id in getVrewfileDataFromLocal"),new C(_.C_LOGIC_ERROR,{},"Project ID not found for uploading files.");const a=be(),i=a.getUserInfo()?.uid;if(!i)throw o.error("No uid in getVrewfileDataFromLocal"),new C(_.A_AUTH_GERNAL_ERROR,{},"User ID not found for uploading files.");const s=()=>{},x=await qH(e,n,t,s,i);return qg(e,x,!1)},w8e=async(e,t)=>{const o=h("clipboard.ts"),r=se(),n=r.getProjectId(),a=e.projectId,i=be(),s=i.getUserInfo()?.uid;if(!s)throw new C(_.A_AUTH_GERNAL_ERROR,{},"User ID not found for uploading files.");const x=[];
4243for(const f of e.files){if(t.signal.throwIfAborted(),f.fileLocation!==D.REMOTE||ia(f.mediaId))continue;if(f.proxyInfo){const O=yo(f.url),S=i4(f.mediaId,O),R=ti(S),y=await B7(a,R);t.signal.throwIfAborted(),y.length>0&&x.push(...y.map(v=>kF(s,a,v,f.fileSize/y.length)))}const E=yo(f.url),T=a_e(s,a,f.mediaId,E);x.push(kF(s,a,T,f.fileSize))}if(x.length===0)return e;const c=500,l=[];for(let f=0;f<x.length;f+=c)l.push(x.slice(f,f+c));const d=An(4),u=(await Promise.all(l.map(f=>d(()=>PT(f,n))))).flat();if(u.length!==x.length)throw new Error("Signed URLs length mismatch");const p=An(100);return await Promise.all(u.map((f,E)=>p(async()=>{if(t.signal.throwIfAborted(),f.result==="COPY"){const{url:T,headers:O}=f;await Qw({url:T,headers:O},t.signal,0,()=>{})}else if(f.result==="MULTIPART_COPY"){const{uploadId:T,parts:O}=f;await Zw({uploadId:T,parts:O,projectId:n,pathName:x[E].name,signal:t.signal,totalSize:0,onProgress:()=>{}})}}))),o.info("Copied all "+u.length+" files. sourceProjectId: "+a+", targetProjectId: "+n),vt(e,f=>{f.files.forEach(E=>{E.fileLocation===D.REMOTE&&(E.url=E.url.replaceAll(a,n),E.proxyInfo&&(E.proxyInfo.videoProxyUrl&&(E.proxyInfo.videoProxyUrl=E.proxyInfo.videoProxyUrl.replaceAll(a,n)),E.proxyInfo.audioProxyUrls&&(E.proxyInfo.audioProxyUrls=E.proxyInfo.audioProxyUrls.map(T=>T.replaceAll(a,n)))))})})},kF=(e,t,o,r)=>{const n=gt(o),a=a4(o,e,t);return cT({type:"copy",name:a,sourceKey:o,origFileName:n,multiparts:Math.ceil(r/jc),sourceSize:r,metadataDirective:"COPY"})},N8e=async(e,t,o)=>{const r=e.filter(a=>(a.type==="Html"||a.type==="Svg")&&a.fileLocation===D.REMOTE);if(r.length===0)return;const n=An(10);await Promise.all(r.map(a=>n(async()=>{o.throwIfAborted(),t[a.mediaId]=await hm(a.url,o)})))},P8e=({trackEntries:e,assetEntries:t,clipboard:o,originalClips:r,overdubInfosMap:n})=>{const a=new Map,i=new Map;Object.keys(e).forEach(T=>{a.set(kr(T),Rt())}),Object.keys(t).forEach(T=>{i.set(Je(T),ho())});const s=T=>a.get(T)??T,x=T=>i.get(T)??T,c=T=>T.map(x),l=zn({});Object.entries(e).forEach(([T,O])=>{if(!O)return;const S=s(kr(T));L.set(l,S,{...O,trackId:S})});const d=ii({});Object.entries(t).forEach(([T,O])=>{if(!O)return;const S=x(Je(T));L.set(d,S,{...O,trackIds:O.trackIds.map(s)})});const u=T=>({...T,assetIds:c(T.assetIds),truncatedWords:T.truncatedWords.map(u)}),p={...o,copiedWords:o.copiedWords.map(T=>({...u(T),newline:T.newline})),copiedGlobalClips:o.copiedGlobalClips.map(T=>({...T,assetIds:c(T.assetIds),words:T.words.map(u)})),copiedElements:o.copiedElements.map(T=>({...T,elementId:x(T.elementId)}))},f=r.map(T=>({...T,assetIds:c(T.assetIds),words:T.words.map(u)})),E=Object.fromEntries(Object.entries(n).map(([T,O])=>[T,{...O,originWords:O.originWords.map(S=>({...S,assetIds:c(S.assetIds)}))}]));return{trackEntries:l,assetEntries:d,clipboard:p,originalClips:f,overdubInfosMap:E}},ap=e=>e.clipboard,b8e=e=>ap(e).copiedWords,L8e=e=>ap(e).copiedGlobalClips,M8e=e=>ap(e).copiedElements,IB=e=>ap(e).sourceAssetEntries,TB=e=>ap(e).sourceTrackEntries;class D8e{registerPutClipboard=async()=>Promise.reject();isRegisteredClipboardDone=async()=>Promise.resolve(!1);putClipboard=async(t,o,r,n)=>Promise.reject();getClipboard=async()=>Promise.resolve(null);clearClipboard=async()=>Promise.resolve()}const k8e=500,F8e=5e3;class U8e{clipboardHash;registerId;constructor(){this.clipboardHash=void 0,this.registerId=void 0}registerPutClipboard=async()=>{const t=qe.v4();this.registerId=t,await(await ae())("electron.registerPutClipboard",{registerId:t})};isRegisteredClipboardDone=async()=>{const t="clipboard_register_"+Cn(10);return Cr().startJob(t,{type:Xi.CLIPBOARD}),await a_({type:Ii.JOB,jobId:t},F8e,async()=>{try{return await(await ae())("electron.checkUpdateRegistered")?!1:(Cr().markJobAsDone(t),!0)}catch{return Cr().abortJob(t),!1}},_.C_LOCAL_FILE_FETCH_FAILED,k8e)};putClipboard=async(t,o,r,n)=>{this.registerId&&await(await ae())("electron.putClipboard",{registerId:this.registerId,vrewJsonData:t,clipboardData:o,cachedMediaIds:r,projectType:n})};getClipboard=async()=>{const t=await(await ae())("electron.getClipboard",{senderHash:this.clipboardHash});return t&&(this.clipboardHash=t.clipboardHash),t};clearClipboard=async()=>(await ae())("electron.clearClipboard")}let FC;const df=()=>(!FC&&(FC=new(at()?U8e:D8e)),FC),V8e=5,G8e=async e=>{const t=document.createElement("video");t.src=e,t.crossOrigin="anonymous",t.muted=!0,t.preload="metadata";try{await t.play().catch(()=>{}),t.currentTime=.1,await new Promise((a,i)=>{function s(){window.clearTimeout(l),t.removeEventListener("seeked",x),t.removeEventListener("error",c)}function x(){s(),a()}function c(){s(),i(new Error("Failed to load user video thumbnail source"))}t.addEventListener("seeked",x,{once:!0}),t.addEventListener("error",c,{once:!0});const l=window.setTimeout(()=>{s(),i(new Error("Timed out while creating user video thumbnail"))},1e4)});const o=document.createElement("canvas"),r=300*Math.min(window.devicePixelRatio||1,2),n=Math.min(t.videoWidth,r);return o.width=n,o.height=t.videoHeight*(n/t.videoWidth),o.getContext("2d").drawImage(t,0,0,o.width,o.height),o.toDataURL("image/jpeg",.92)}finally{t.remove()}};class W8e{constructor(t=G8e){this.generate=t}generate;caches=new Map;pendingHashes=new Set;queue=[];activeCount=0;listeners=new Set;notifyListeners=()=>{for(const t of this.listeners.values())t()};subscribe=t=>(this.listeners.add(t),()=>{this.listeners.delete(t)});get=t=>this.caches.get(t);request=(t,o)=>{this.caches.has(t)||this.pendingHashes.has(t)||(this.pendingHashes.add(t),this.queue.push({hash:t,blobUrl:o}),this.pump())};pump=()=>{for(;this.activeCount<V8e&&this.queue.length>0;){const t=this.queue.shift();this.pendingHashes.has(t.hash)&&this.runGenerate(t.hash,t.blobUrl)}};runGenerate=(t,o)=>{this.activeCount++,this.generate(o).then(r=>{this.pendingHashes.has(t)&&this.set(t,r)}).catch(r=>{h("userVideoThumbnailCache.ts").warn("Error during creating user video "+t+" thumbnail: "+P(r))}).finally(()=>{this.activeCount--,this.pendingHashes.delete(t),this.pump()})};delete=t=>{const o=new Set(t);let r=!1;for(const n of t)this.caches.delete(n)&&(r=!0),this.pendingHashes.delete(n);this.queue=this.queue.filter(n=>!o.has(n.hash)),r&&this.notifyListeners()};set=(t,o)=>{this.caches.set(t,o),this.notifyListeners()}}let UC;const H8e=()=>(UC===void 0&&(UC=new W8e),UC),SB=async()=>await _n().getAllValues(Bo.VREW_FEATURES_DB,Ko.USER_ASSET),zA=async(e,t)=>{try{const o=e.map(n=>n.hash);return await _n().putValues(Bo.VREW_FEATURES_DB,Ko.USER_ASSET,o,e),!0}catch(o){return h("userAsset.ts").error("Failed to put assets in Indexed DB "+o),o==="QuotaExceededError"&&Y().message(A("user_asset.storage_full_warning_title"),A("user_asset.storage_full_warning_desc")),t&&GFe(t.totalImgCnt,t.favoriteImgCnt,t.uploadImgCnt,t.overlappedImgCnt,t.uploadVideoCnt),!1}},OB=async e=>{await _n().deleteValues(Bo.VREW_FEATURES_DB,Ko.USER_ASSET,e),H8e().delete(e)},VC=1024*1024*10,j8e=async e=>await rs(e,async o=>{if(o.type===Pt.IMAGE){const i=await Xb("sha1",o.blob);return{...o,hash:i}}const r=typeof o.pathOrBlob=="string"?await fetch(an(o.pathOrBlob)).then(i=>i.blob()):o.pathOrBlob,n=r.size<VC?r:new Blob([r.slice(0,VC/2),r.slice(-VC/2)]),a=await Xb("sha1",n);return{...o,pathOrBlob:r,hash:a}}),z8e=e=>e.reduce((t,o)=>{switch(o.type){case Pt.IMAGE:t.imageCnt++;break;case Pt.VIDEO:t.videoCnt++;break;case Pt.GIF:t.gifCnt++}return t},{imageCnt:0,videoCnt:0,gifCnt:0}),Y8e=async(e,t,o,r)=>(await rs(e,async(a,i)=>{const s=t+o[i];switch(a.type){case Pt.IMAGE:return await B8e(a,s);case Pt.VIDEO:case Pt.GIF:return await K8e(a,s);default:return}})).filter(Se),B8e=async(e,t,o)=>{const{blob:r,hash:n}=e,a=window.URL.createObjectURL(r),{width:i,height:s}=await bTe(a);return window.URL.revokeObjectURL(a),{type:Pt.IMAGE,blob:r,hash:n,width:i,height:s,isFavorite:!1,favoriteTimestamp:t,insertTimestamp:t}},K8e=async(e,t,o)=>{const{pathOrBlob:r,hash:n,filename:a}=e;if(typeof r=="string")throw new C(_.C_LOGIC_ERROR,{},"UserVideoGifSource.pathOrBlob should be blob");const i=r,s=URL.createObjectURL(i),{width:x,height:c,duration:l}=await f4(s);return URL.revokeObjectURL(s),{type:e.type,blob:i,src:a,width:x,height:c,duration:l,hash:n,isFavorite:!1,favoriteTimestamp:t,insertTimestamp:t}},X8e=(e,t)=>
4243{const o=r=>{let n=0,a=0;const i=[];e.forEach(({type:c})=>{c===r&&a++}),t.forEach(c=>{const{type:l}=c;l===r&&(n++,i.push(c))});const s=n+a-Si;return s>0?i.sort((c,l)=>c.insertTimestamp>l.insertTimestamp?-1:1).sort((c,l)=>c.isFavorite&&!l.isFavorite?-1:!c.isFavorite&&l.isFavorite?1:0).map(c=>c.hash).slice(-s):[]};return{deleteRequiredImages:o(Pt.IMAGE),deleteRequiredVideos:o(Pt.VIDEO),deleteRequiredGifs:o(Pt.GIF)}},J8e=async(e,t,o)=>{const r=[],n=[],a=new Set,i=[],s=t.map(({hash:l})=>l),x=Date.now();return e.forEach((l,d)=>{const{hash:u}=l,p=s.indexOf(u);if(p>-1)i.push({...t[p],isFavorite:!1,favoriteTimestamp:x+d,insertTimestamp:x+d});else{if(a.has(u))return;a.add(u),r.push(l),n.push(d)}}),{uploadRequiredAssets:await Y8e(r,x,n),updateRequiredAssets:i}},Ih=async(e,t,o,r,n)=>{if(!window.indexedDB||e.length===0)return;const a=await SB(),i=await j8e(e),{imageCnt:s,videoCnt:x,gifCnt:c}=z8e(e);await W9e(s,x,c,a);const{uploadRequiredAssets:l,updateRequiredAssets:d}=await J8e(i,a),{deleteRequiredImages:u,deleteRequiredVideos:p,deleteRequiredGifs:f}=X8e(l,a),E=FFe(a,d,s,x);d.length>0&&await zA(d,E),l.length>0&&await zA(l,E),await OB([...u,...p,...f]),kFe(r,o,t,s,x,a,l,d)},q8e=async e=>{const{type:t,hash:o,width:r,height:n,isFavorite:a,favoriteTimestamp:i,insertTimestamp:s}=e;if(t===Pt.IMAGE){const x=e.blob,c=URL.createObjectURL(x);return{type:t,blob:x,width:r,height:n,hash:o,isFavorite:a,favoriteTimestamp:i,insertTimestamp:s,blobUrl:c}}else if(e.type===Pt.VIDEO||e.type===Pt.GIF){const{src:x,duration:c}=e;let l=e.blob;if(l===void 0){if(!await Ue().checkUserVideoValidPath(x))return h("userAsset.ts").error('UserVideo "'+x+'" is invalid path'),void 0;if(l=await fetch(an(x)).then(f=>f.blob()).catch(f=>{const E="Error during fetching "+x+": "+P(f);return h("userAsset.ts").error(E),void 0}),l===void 0)return h("userAsset.ts").error('Failed to get video path for user asset "'+x+'"'),void 0}const d=URL.createObjectURL(l);return{type:t,width:r,height:n,hash:o,isFavorite:a,favoriteTimestamp:i,insertTimestamp:s,duration:c,blob:l,name:gt(x),blobUrl:d}}},Q8e=e=>{switch(e.type){case Pt.IMAGE:return{type:Pt.IMAGE,width:e.width,height:e.height,hash:e.hash,isFavorite:e.isFavorite,favoriteTimestamp:e.favoriteTimestamp,insertTimestamp:e.insertTimestamp,blob:e.blob};case Pt.VIDEO:case Pt.GIF:return{type:e.type,width:e.width,height:e.height,hash:e.hash,isFavorite:e.isFavorite,favoriteTimestamp:e.favoriteTimestamp,insertTimestamp:e.insertTimestamp,duration:e.duration,blob:e.blob,src:e.name}}},kAt=async(e,t)=>{const o={...e,favoriteTimestamp:Date.now(),isFavorite:!e.isFavorite},{totalImgCnt:r,favoriteImgCnt:n}=t;return await zA([Q8e(o)],{totalImgCnt:r,favoriteImgCnt:n,uploadImgCnt:0,overlappedImgCnt:0,uploadVideoCnt:0}),o},CB=(e,t,o)=>[e,t,o].filter(r=>r>0).length>=2?Kr.ALL:e>0?Kr.Image:t>0?Kr.Video:o>0?Kr.GIF:Kr.ALL,Z8e=async e=>{const t=_n(),o=await t.getValue(Bo.VREW_FEATURES_DB,Ko.USER_ASSET,e);if(o?.type===Pt.VIDEO)return o},FAt=async e=>{const t=await SB(),o=[],r=[],n=new Set,a=new Map(e.map(i=>[i.hash,i]));for(const i of t){const s=a.get(i.hash);if(s){r.push({...s,isFavorite:i.isFavorite,favoriteTimestamp:i.favoriteTimestamp,insertTimestamp:i.insertTimestamp}),n.add(i.hash);continue}const x=await q8e(i);if(x===void 0){o.push({path:i.type===Pt.VIDEO?i.src:"",hash:i.hash});continue}r.push(x)}return e.forEach(({hash:i,blobUrl:s})=>{!n.has(i)&&URL.revokeObjectURL(s)}),o.length>0&&(OB(o.map(({hash:i})=>i)),Y().message(A("user_asset.video_path_changed_title"),A("user_asset.video_path_changed_desc",{PATH_CHANGED_FILE_NAME:o[0].path,PATH_CHANGED_FILE_CNT:o.length})),jFe(o.length)),r.sort((i,s)=>s.insertTimestamp-i.insertTimestamp),r},UAt=e=>e>=nN,$8e=e=>e.copiedElements.length>0?Jl.ELEMENT:e.copiedGlobalClips.length>0?Jl.CLIP:Jl.WORD,eBe=3e3,RB=(e,t,o)=>{const r=new Set;o.copiedGlobalClips.forEach(s=>{s.assetIds.forEach(x=>r.add(x)),s.words.forEach(x=>{x.assetIds.forEach(c=>r.add(c)),x.truncatedWords.forEach(c=>{c.assetIds.forEach(l=>r.add(l))})})}),o.copiedWords.forEach(s=>{s.assetIds.forEach(x=>r.add(x)),s.truncatedWords.forEach(x=>{x.assetIds.forEach(c=>r.add(c))})}
4243),o.copiedElements.forEach(s=>r.add(s.elementId));const n={},a=new Set;r.forEach(s=>{const x=L.get(t,s);x&&(n[s]=x,x.trackIds.forEach(c=>a.add(c)))});const i={};return a.forEach(s=>{const x=L.get(e,s);x&&(i[s]=x)}),{sourceAssetEntries:ii(n),sourceTrackEntries:zn(i)}},tBe=(e,t,o)=>r=>r({type:L0.WORD_PASTE_FROM_CLIPBOARD,payload:{copiedWords:e,sourceAssetEntries:t,sourceTrackEntries:o}}),AB=e=>({type:L0.ELEMENTS_PASTE_FROM_CLIPBOARD,payload:{chunkDatas:e}}),yB=e=>{const t=e(),o=lt(t),r=ht(t),n=Tn(t),{cursorMode:a,selectedElements:i,globalWordRange:s,globalClipRange:x}=n,c=i.map(p=>p.id),l=c.map(p=>{const f=L.get(r,p);if(!f||f.role!=="sub")return;const E=f.trackIds.map(O=>L.get(o,O)).filter(Se);if(E.length===0)return;const T=E.find(O=>xr(O)&&!Rr(O));return{rangeType:f.rangeType,assetType:T?T.type:E[0].type}}).filter(Se),d=wce(a)?so.SELECTED:a===we.CLIP?so.CLIP:so.WORD,u=s!==null||x!==null?o0.USER_REQ:o0.SYS_AUTO;return{target:d,behaviorType:u,selectedGAAssetInfo:l}},oBe=(e,t,o,r)=>{const{target:n,behaviorType:a,selectedGAAssetInfo:i}=yB(e);iBe(t,n,a,o,i,r)},vB=(e,t,o)=>e.map(r=>{const n=L.get(o,r.id);if(!n||n.role!=="sub")return;const a=n.trackIds.map(i=>L.get(t,i)).filter(Se);if(a.length!==0){if(r.type===ra.ASSET){const i=a.find(s=>xr(s)&&!Rr(s));return i?{type:r.type,mediaId:i.mediaId,elementId:r.id}:void 0}return{type:r.type,mediaId:a[0].mediaId,elementId:r.id}}}).filter(Se),rBe=(e,t,o)=>async(r,n)=>{const a=n(),{projectAudioLanguage:i}=rt(a),s=jo(a),{cursorMode:x,globalPosition:c,selectedElements:l}=s,d=He(a),u=ec(a),p=q0(),f=lt(a),E=ht(a),T=zs(a);if(c===null)return r;const O=d[u];if(!XW(O,s,!1,p))return r;if(oBe(n,e,t,o),x===we.CAPTION)return document.execCommand("copy"),r;const S=CI(O,c),R=ds(a)??{from:S,to:S+1,globalClipIndex:u},y=R?nT(d,R):[],v=_2(a),w=v.filter(G=>L.get(T,G.clipId)?.shouldRenderAsTTSClip!==!0);if(navigator.clipboard){const G=xH(d,R,w,i);navigator.clipboard.writeText(G).catch(B=>{h("clipboard.ts").warn("Error occurred during writing clipboard, "+P(B))})}const N={copiedWords:y,copiedGlobalClips:w,copiedElements:vB(l,f,E)},{sourceAssetEntries:M,sourceTrackEntries:k}=RB(f,E,N),F={...N,sourceAssetEntries:M,sourceTrackEntries:k};return pt().getWindowCount()>1&&r(NB(F)),r({type:L0.COPY_TO_CLIPBOARD,payload:{targetClipboard:F}})},VAt=(e,t)=>(o,r)=>{const n=r(),a=tc(n),i=T2(n),s=oc(n),x=Do(n),c=bg(n),l=c.length>0?c:x,d=t===Ke.ORIGINAL?on(a)||i?.source:i?.target||on(a),u=s?t===Ke.ORIGINAL?A("caption.copy_original_caption_toast_desc"):A("caption.copy_translated_caption_toast_desc"):A("caption.copy_caption_toast_desc"),p=l.map(f=>Hn(f,Ar(d),t));return navigator.clipboard&&navigator.clipboard.writeText(p.filter(f=>f.trim()!=="").join(`
4244`)).then(()=>{To.popup(u),e===io.BUTTON?JDe(t,c.length,s):e===io.CONTEXTMENU&&qDe(t,c.length,s)}).catch(f=>{h("clipboard.ts").warn("Error occurred during writing clipboard, "+P(f))}),o},nBe=(e,t,o)=>{const{target:r,behaviorType:n,selectedGAAssetInfo:a}=yB(e);aBe(t,r,n,a,o)},wB=(e,t)=>(o,r)=>{const n=r(),{projectAudioLanguage:a}=rt(n),i=jo(n),{cursorMode:s,globalPosition:x,selectedElements:c}=i,l=He(n),d=ec(n),u=q0(),p=lt(n),f=ht(n);if(x===null)return o;if(Oa()&&s!==we.CAPTION)return Ca(),o;const E=l[d];if(!XW(E,i,!0,u))return o;if(nBe(r,e,t),s===we.CAPTION)return document.execCommand("cut"),o;const T=CI(E,x),O=ds(n)??{from:T,to:T+1,globalClipIndex:d},S=O?nT(l,O):[],R=_2(n),y=zs(n),v=R.filter(F=>L.get(y,F.clipId)?.shouldRenderAsTTSClip!==!0);if(navigator.clipboard){const F=xH(l,O,v,a);navigator.clipboard.writeText(F).catch(G=>{h("clipboard.ts").warn("Error occurred during writing clipboard, "+P(G))})}const w={copiedWords:S,copiedGlobalClips:v,copiedElements:vB(c,p,f)},{sourceAssetEntries:N,sourceTrackEntries:M}=RB(p,f,w),k={...w,sourceAssetEntries:N,sourceTrackEntries:M};return pt().getWindowCount()>1&&o(NB(k)),o({type:L0.CUT_TO_CLIPBOARD,payload:{targetClipboard:k}})},aBe=(e,t,o,r,n)=>{switch(e){case io.BUTTON:yMe(t,o,$T(n),r);break;case io.CONTEXTMENU:YDe(t,o,r);break;case io.KEY:gDe(t,r);break;case io.FLOATING_MENU:Zke(t,r);break}},iBe=(e,t,o,r,n,a)=>{if(r)switch(e){case io.BUTTON:AMe(t,o);break;case io.CONTEXTMENU:zDe(t,o);break;case io.KEY:fDe(t);break}else switch(e){case io.BUTTON:RMe(t,o,$T(a),n);break;case io.CONTEXTMENU:jDe(t,o,n);break;case io.KEY:HDe(t,n);break;case io.FLOATING_MENU:$ke(t,n);break}},sBe=(e,t,o)=>async(r,n)=>{const a=n(),i=ap(a),s=Zx(a);if(q0()&&s!==we.CAPTION)return r;const c=await t7();let l=i,d=nd.ORIGINAL_CLIPBOARD;if(pt().getWindowCount()>1){await df().isRegisteredClipboardDone();const p=new AbortController,f=setTimeout(()=>{Y().openModal(st.WAITING_CLIPBOARD,{onCancel:()=>{p.abort(),Y().closeModal(st.WAITING_CLIPBOARD)}})},eBe),E=await df().getClipboard(),T=ba().isPremiumFeatureAvailable(Ut.SHARED_CLIPBOARD);if(E!==null&&!T)return clearTimeout(f),Y().closeModal(st.WAITING_CLIPBOARD),Y().openModal(st.NEED_PLAN_UPGRADE,{premiumFeatureType:Ut.SHARED_CLIPBOARD}
4244),df().clearClipboard(),r;const O=await r(gBe(E,p));O!==void 0&&(l=O,d=nd.SHARED_CLIPBOARD),clearTimeout(f),Y().closeModal(st.WAITING_CLIPBOARD)}const u=$8e(l);return o?o!==u?r:r(FF(o,d,e,t)):s===we.CORRECTING?r:(s===we.CAPTION||s===we.DISABLED)&&c===null?(await xBe(e,t),r):r(c?pBe():FF(u,d,e,t))},FF=(e,t,o,r)=>n=>{switch(e){case Jl.ELEMENT:return n(fBe(t,o,r));case Jl.CLIP:return n(lBe(t,o,r));case Jl.WORD:return n(cBe(t,o,r));default:return n}},xBe=async(e,t)=>{await navigator.clipboard.readText().then(o=>{o&&(document.execCommand("insertText",!1,o.replace(/\n+$/,"")),e!==io.KEY&&gS(nd.ORIGINAL_CLIPBOARD,e,so.CLIPBOARD_TEXT,t))}).catch(o=>h("clipboard.ts").warn("error on accessing clipboard: "+P(o)))},cBe=(e,t,o)=>(r,n)=>{const a=n(),i=b8e(a),s=Tn(a),{cursorMode:x,position:c}=s;if(Oa()){Ca();return}if(c===null||i.length===0||x!==we.INSERT_CURSOR&&x!==we.CAPTION&&x!==we.CLIP)return;gS(e,t,so.WORD,o),e===nd.SHARED_CLIPBOARD&&Xh("sharedClipboard");const l=IB(a),d=TB(a);return r(tBe(i,l,d))},lBe=(e,t,o)=>(r,n)=>{if(Oa())return Ca(),r;const a=n(),i=L8e(a),s=IB(a),x=TB(a);return gS(e,t,so.CLIP,o),e===nd.SHARED_CLIPBOARD&&Xh("sharedClipboard"),r({type:L0.CLIP_PASTE_FROM_CLIPBOARD,payload:{copiedGlobalClips:i,sourceAssetEntries:s,sourceTrackEntries:x}})},dBe=async(e,t)=>{try{const o=await t7();return o===null?null:MTe(o,_e.SYSTEM_CLIPBOARD,e,t)}catch(o){return h("clipboard.ts").error(o),null}},uBe=(e,t)=>{if(!t)return null;const o=L.get(e,t);if(!o)return null;const{track:r}=o;return Gn(r)?{...r,importType:_e.COPY_AND_PASTE,stats:r.stats?{...r.stats}:void 0}:Wn(r)?{...r,importType:Yt.COPY_AND_PASTE}:{...r}},pBe=()=>async(e,t)=>{const o=t(),r=rt(o),n=cI(o),a=I2(o),i=Lg(o),s=Tn(o),x=Array.from(Z0(o)),c=$0(o),l=P9e(n),d=Sl(o),u=Hze(o),p=await dBe(j0(a),l);if(p){if(window.indexedDB){const N=await En(p.imageInfo.mediaId);if(!N)return;Ih([{type:Pt.IMAGE,blob:N}],eu.AUTOMATIC_COPY_PASTE,u,d).then(()=>{U9e(d)&&e(Q8(kn.USER_ASSET_LIBRARY,en.CLIPBOARD,CB(1,0,0)))})}const f=p.imageModel;if(!f||!i)return;const E=bB(i,[f],n)[0],T=PB(s.cursorMode,x,c),O={type:"IMPORT_RANGE",importRange:T},S=U4(r,O,E.type,E.mediaId);if(S===void 0)return;const{chunkData:R,cursorAssetId:y,cursorGlobalPosition:v}=S;Mz(x.length,c.length,[{assetType:E.type,rangeType:R[0].chunk.type==="WORD"?tr.WORD:tr.CLIP}],nd.ORIGINAL_CLIPBOARD);const w=R.map(N=>{const{chunk:M}=N;return{chunk:M,assetInfos:[{type:Hx.EXISTING,assetId:y,srcAsset:E}],audioInfos:[]}});e(AB(w)),e(zP(y,ra.ASSET,v))}},fBe=(e,t,o)=>async(r,n)=>{const a=n(),i=rt(a),s=cI(a),x=Av(a),c=M8e(a),l=Lg(a),d=Tn(a),u=Array.from(Z0(a)),p=$0(a),f=c.filter(j=>Nce(j.type)).map(j=>j.elementId),E=c.filter(j=>Pce(j.type)).map(j=>j.elementId),T=f.map(j=>uBe(s,j)).filter(ri);if(T.length!==f.length||!l)return;const O=bB(l,T,s),S=PB(d.cursorMode,u,p),R={type:"IMPORT_RANGE",importRange:S},y=aEe(i,R);if(y===void 0)return;const{chunks:v,cursorGlobalPosition:w}=y;Mz(u.length,p.length,O.map(j=>({assetType:j.type,rangeType:y.chunks[0].type==="WORD"?tr.WORD:tr.CLIP})),e),gS(e,t,so.ELEMENT,o),e===nd.SHARED_CLIPBOARD&&Xh("sharedClipboard");const N=E.map(j=>L.get(x,j)?.track).filter(Se);if(E.length!==N.length)return;const M=j=>{if(J0(j)){const{audio:$,...q}=j,H=$?{...$,trackId:Rt()}:void 0;return{...q,trackId:Rt(),...H?{audio:H}:{}}}return{...j,trackId:Rt()}},k=j=>({...j,trackId:Rt()}),F=j=>({type:Hx.EXISTING,assetId:ho(),srcAsset:M(j)}),G=j=>({type:Hx.EXISTING,audioTransformId:ho(),isSoundEffect:Id(j),srcAudioTransform:k(j)}),B=j=>"assetId"in j?{id:j.assetId,type:ra.ASSET}:{id:j.audioTransformId,type:ra.AUDIO},{chunkDatas:W,pasteElements:Q}=v.reduce((j,$)=>{const{chunkDatas:q,pasteElements:H}=j,U=O.map(F),te=N.map(G),ne={chunk:$,assetInfos:U,audioInfos:te},oe=[...U.map(B),...te.map(B)];return{chunkDatas:[...q,ne],pasteElements:[...H,...oe]}},{chunkDatas:[],pasteElements:[]});r(AB(W)),r(rze(Q,w,!0,d.selectedFromAssetList))},NB=e=>async(t,o)=>{if(!at())return t;await df().registerPutClipboard();const r=o(),n=await Uwe(r,e);if(!n)return t;const a=j2(n),i=JSON.stringify(a),{props:s}=n,{baseAssetEntries:x}=s,c=se().isCloudProject(),l=c?Yx.extractCacheableCloudMediaIds(n.files):Yx.putProjectMediaIds(n.files),d=Be.toClipboardJson(e,x),u=JSON.stringify(d),p=se().getCurrentProjectFileType();return await df().putClipboard(i,u,l,p===Ee.CLOUD?"cloud":"local"),t},gBe=(e,t)=>async(o,r)=>{const n=h("clipboard.ts");if(!e)return;const{videoRatio:a}=rt(r()),{vrewJsonData:i,clipboardData:s,buffers:x,exts:c,projectType:l}=e;try{const d=Object.entries(x).reduce((fe,[ve,yt])=>{const Le=new Blob([yt],{type:X0.getType(c[ve])??pf});return{...fe,[ve]:Le}},{}),u=JSON.parse(i);await N8e(u.files??[],d,t.signal);let p=await H2(u,d);const f=se(),E=f.getCurrentProjectFileType(),T=E===Ee.MEDIA||E===Ee.PROJECT,O=E===Ee.CLOUD;l==="cloud"&&T?p=await y8e(p,t):l==="local"&&O?p=await v8e(p,t):l==="cloud"&&O&&(p=await w8e(p,t)),t.signal.throwIfAborted();const{props:S,files:R,blobs:y}=p,{trackEntries:v,baseAssetEntries:w,videoRatio:N,initProjectVideoSize:M}=S,k=N,F=a,G=M.width/M.height,B=JSON.parse(s),W=Be.fromClipboardJson(B),Q=EN(W.copiedGlobalClips),j=Zg(w,Q),$=k!==F,q=$?Y_e(v,G,k,F):v,{trackEntries:H,assetEntries:U,clipboard:te,originalClips:ne,overdubInfosMap:oe}=P8e({trackEntries:q,assetEntries:j,clipboard:W,originalClips:S.originalClips,overdubInfosMap:S.overdubInfosMap}),re={...S,trackEntries:H,assetEntries:U,overdubInfosMap:oe},ge=vd({files:R,blobs:y,dispatchType:Ee.MEDIA});return await o(T0(ge)),o(_Be(re,te,ne)),te}catch(d){if(t.signal.aborted){n.info("Clipboard paste aborted");return}n.error("Failed to parse clipboard data: "+d);return}},_Be=(e,t,o)=>r=>{const n={type:L0.APPLY_SHARED_CLIPBOARD,payload:{appliedProps:e,originalClips:o,targetClipboard:t}};r(n)},PB=(e,t,o)=>e===we.ELEMENT?nt.FOLLOW_SELECTED_ELEMENT:t.length!==0?nt.SELECTED_CLIPS:o.length!==0?nt.SELECTED_WORDS:nt.CURRENT_CLIP,gS=(e,t,o,r)=>{switch(t){case io.MOUSE:o===so.WORD&&Nz(so.WORD,e);break;case io.BUTTON:vMe(o,o0.USER_REQ,$T(r),e);break;case io.CONTEXTMENU:BDe(o,o0.USER_REQ,e);break;case io.KEY:_De(o,e);break;case io.FLOATING_MENU:eFe(o,e);break}},EBe=(e,t)=>e.mediaId===t.mediaId&&Math.abs(e.xPos-t.xPos)<1e-5&&Math.abs(e.yPos-t.yPos)<1e-5&&Math.abs(e.width-t.width)<1e-5&&Math.abs(e.height-t.height)<1e-5,bB=(e,t,o)=>{const r=e.assetIds.map(a=>{const i=L.get(o,a);if(i)return i.track}).filter(Se).sort((a,i)=>a.xPos<i.yPos?-1:a.xPos>i.xPos?1:a.yPos<=i.yPos?-1:1);return t.map(a=>r.reduce((i,s)=>EBe(i,s)?{...i,xRatio:i.xPos+.02,yRatio:i.yPos+.02}:i,a)).map(a=>({...a,xPos:a.xPos,yPos:a.yPos}))},GAt=async e=>{const t=await DT(e);if(document.hasFocus())await navigator.clipboard.write([new ClipboardItem({[t]:e})]);else{const o=new AbortController;document.addEventListener("mousemove",async()=>{document.hasFocus()&&(await navigator.clipboard.write([new ClipboardItem({[t]:e})]),o.abort())},{signal:o.signal})}},WAt=e=>(t,o)=>{const r=o();return v0e(r)!==e?t({type:g0.UPDATE_CAPTION_SELECTION_CHANGED,payload:{isCaptionSelected:e}}):t},HAt=e=>t=>t({type:g0.SET_CAPTION_LENGTH_LIMIT,payload:{limit:e}}),mBe=()=>async e=>{await Vn("openProject")&&(Il().shouldOpenModal()||!Oo()?Y().openModal(st.OPEN_PROJECT):e(hBe()))},hBe=()=>async e=>{const t=await Ue().showOpenDialog(["vrew"],zr("vrewfile.load_vrew_file"),zr("toolbar.open_project_title"),U2());t&&(Il().setMostRecentAttemptedOpenMethod(Kn.OS_DIALOG_OLD),e(ag({loadingType:"userProject",filePath:t.name})))},jAt=e=>({type:g0.SET_ASSET_DRAGGING_RANGE,payload:{assetDraggingRange:e}}),zAt=e=>t=>{const o={type:g0.CHANGE_LAST_USED_BLANK_OPTION,payload:{option:e}};t(o)},IBe=()=>e=>{const t={type:g0.SET_IS_READY_TO_OPEN_PROJECT,payload:{isReadyToOpenProject:!0}};return e(t)},YAt=e=>({type:g0.SET_RENDER_RANGE,payload:{renderRange:e}}),BAt=e=>({type:g0.SET_PENDING_SCROLL_STATE,payload:{pendingScrollState:e}}),TBe=e=>(e.importType===_e.AI_STYLIZED_CAPTION||e.importType===_e.COPY_AND_PASTE)&&typeof e.stats?.aiStylizedCaptionAssetId=="string",SBe=(e,t,o)=>{const r=new Set(e.flatMap(a=>[...a.assetIds,...a.words.flatMap(i=>i.assetIds)])),n=new Set;return r.forEach(a=>{L.get(o,a)?.trackIds.forEach(s=>{const x=L.get(t,s);if(!x||!Gn(x)||!TBe(x))return;const c=x.stats?.aiStylizedCaptionAssetId;c!==void 0&&n.add(c)})}),n.size},LB=e=>!!e&&e.type==="Image",Pc=e=>!!e&&e.type==="AVMedia",OBe=e=>!!e&&e.type==="Html",YA=async e=>{if(e.mediaId===_o)return URL.createObjectURL(se().getBlankVideoInfo().blankAudioBlob);
4244if(e.fileLocation===D.IN_MEMORY){const o=await En(e.mediaId);if(!o){const r="[_getURI] Blob not found for mediaId: "+e.mediaId;throw h("exportLocal.ts").error(r),new C(_.C_MEDIA_BLOB_LOST,{},r)}return URL.createObjectURL(o)}if(Bc(e))return e.path;const t=s_(e.mediaId);return t||""},eb=async e=>{const t=await En(e);if(!t){const o="[_requireBlob] Blob not found for mediaId: "+e;throw h("exportLocal.ts").error(o),new C(_.C_MEDIA_BLOB_LOST,{},o)}return t},GC=async(e,t,o)=>{const r=e.get(t);if(!LB(r)){const n="[_makeImageInfo] Image not found for mediaId: "+t;throw h("exportLocal.ts").error(n),new C(_.C_MEDIA_LOST,{},n)}return{mediaId:t,sourceType:o,blob:await eb(t),isTransparent:r.isTransparent}},RE=async(e,t)=>{const o=e.get(t);if(!Pc(o)){const n="[_makeAssetVideoInfo] Asset video not found for mediaId: "+t;throw h("exportLocal.ts").error(n),new C(_.C_MEDIA_LOST,{},n)}const r=await YA(o);if(!r){const n="[_makeAssetVideoInfo] Path not found for mediaId: "+t;throw h("exportLocal.ts").error(n),new C(_.C_MEDIA_LOST,{},n)}return{mediaId:t,sourceType:de.ASSET_VIDEO,videoAudioMetaInfo:o.videoAudioMetaInfo,originalPath:r}},WC=async(e,t,o)=>{if(o?.broken){const{blankInfo:a,blankAudioBlob:i}=se().getBlankVideoInfo();return{mediaId:t,sourceType:de.VIDEO_AUDIO,videoAudioMetaInfo:a.videoAudioMetaInfo,originalPath:await YA(a),fileLocation:a.fileLocation,blob:i}}const r=e.get(t);if(!Pc(r)){const a="[_makeMainMediaInfo] Main media not found for mediaId: "+t;throw h("exportLocal.ts").error(a),new C(_.C_MEDIA_LOST,{},a)}const n=await YA(r);if(!n){const a="[_makeMainMediaInfo] Path not found for mediaId: "+t;throw h("exportLocal.ts").error(a),new C(_.C_MEDIA_LOST,{},a)}return{mediaId:t,sourceType:de.VIDEO_AUDIO,videoAudioMetaInfo:r.videoAudioMetaInfo,originalPath:n,fileLocation:r.fileLocation}},UF=async(e,t,o)=>{const r=e.get(t);if(!Pc(r)){const n="[_makeMainAudioInfo] Main audio not found for mediaId: "+t;throw h("exportLocal.ts").error(n),new C(_.C_MEDIA_LOST,{},n)}return{mediaId:t,sourceType:o,blob:await eb(t),videoAudioMetaInfo:r.videoAudioMetaInfo}},AE=async(e,t,o)=>{const r=e.get(t);if(!Pc(r)){const n="[_makeAssetAudioInfo] Asset audio not found for mediaId: "+t;throw h("exportLocal.ts").error(n),new C(_.C_MEDIA_LOST,{},n)}return{mediaId:t,sourceType:o,blob:await eb(t),videoAudioMetaInfo:r.videoAudioMetaInfo}},MB=async(e,t,o)=>{const r=W2(),n=p=>p.mediaId+":"+p.sourceType,a=new Map(r.map(p=>[p.mediaId,p])),i=new Set,s=[],x=p=>{const f=n(p);!i.has(f)&&(s.push(p),i.add(f))},c=[];Zie(e).forEach(p=>{c.push(()=>GC(a,p,de.FILTER))});const l=Object.keys(t).filter(p=>!o.has(Je(p)));for(const p of l){const f=L.get(t,p);if(!f)continue;const E=f.trackIds.map(T=>L.get(e,T)).filter(Se);for(const T of E){const{mediaId:O}=T;switch(T.type){case z.IMAGE:case z.WATERMARK:c.push(()=>GC(a,O,de.IMAGE));break;case z.WEB:{const S=a.get(O);OBe(S)&&x({mediaId:O,sourceType:de.TEXTBOX,rawHtml:S.rawHtml});break}case z.VIDEO:{if(f.role==="main"){const S=a.get(O),R=Pc(S)&&S.broken;c.push(()=>WC(a,O,{broken:R}))}else c.push(()=>RE(a,O));break}case z.SIMPLE_CHARACTER:{const S=T.pose.silentMediaId,R=a.get(S);if(LB(R)?c.push(()=>GC(a,S,de.IMAGE)):Pc(R)?c.push(()=>RE(a,S)):h("exportLocal.ts").error("[convertFileInfosToExportLocalMediaInfos] Unhandled silent media type: "+R?.type+" for mediaId: "+S),T.pose.speakingMediaId){const y=T.pose.speakingMediaId;c.push(()=>RE(a,y))}break}case ze.Overdub:c.push(()=>UF(a,O,de.OVERDUB));break;case ze.TTSClip:c.push(()=>UF(a,O,de.TTS));break;case ze.TTSEffect:c.push(()=>AE(a,O,de.TTS_EFFECT));break;case ze.TTSDubbing:c.push(()=>AE(a,O,de.TTS_DUBBING));break;case ze.SoundEffect:c.push(()=>AE(a,O,de.SOUND_EFFECT));break;case ze.BGM:c.push(()=>AE(a,O,de.BGM));break;case ze.VideoAudio:{if(f.role==="main"){const S=a.get(O),R=Pc(S)&&S.broken;c.push(()=>WC(a,O,{broken:R}))}else c.push(()=>RE(a,O));break}}}}const d=a.get(_o);return d&&Pc(d)&&c.push(()=>WC(a,_o,{broken:!1})),(await Promise.all(c.map(async(p,f)=>{try{return await p()}catch(E){return h("exportLocal.ts").warn("[convertFileInfosToExportLocalMediaInfos] Task failed for mediaId: "+f+": "+P(E)),null}}
4244))).forEach(p=>{p&&x(p)}),s};var CBe=(e=>(e.OPEN_PANEL="open_panel",e.CLICK_CREATE="click_create",e.CLICK_REGENERATE="click_regenerate",e.POLLING_DONE="polling_done",e.GENERATE_DONE="generate_done",e.GENERATE_FAILED="generate_failed",e.REGENERATE_DONE="regenerate_done",e.CANCEL_FAILED="cancel_failed",e.INSERT_DONE="insert_done",e.EXPORT_DONE="export_done",e.VIEW_RESULT_MODAL="view_result_modal",e.CLOSE_RESULT_MODAL="close_result_modal",e.CLICK_ADVANCED="click_advanced",e.CLICK_RESET_CHROMA_KEY="click_reset_chroma_key",e.CLICK_INSERT="click_insert",e.CLICK_RECENT_ASSET="click_recent_asset",e.CLICK_RECENT_ADVANCED_OPTIONS="click_recent_advanced_options",e.CLICK_MODIFY_ASSET_MENU="click_modify_asset_menu",e.CLICK_MODIFY_FLOATING_MENU="click_modify_floating_menu",e.CLICK_MODIFY_RESULT_MODAL="click_modify_result_modal",e.CLICK_RECENT_MORE="click_recent_more",e.CLICK_RECENT_MODIFY="click_recent_modify",e.CLICK_RECENT_RESTORE="click_recent_restore",e.CLICK_RECENT_CANCEL="click_recent_cancel",e.CLICK_MODIFY_CONTEXT_MENU="click_modify_context_menu",e.CLICK_RECENT_FAVORITE="click_recent_favorite",e.CLICK_RECENT_DELETE="click_recent_delete",e))(CBe||{});const lr=(e,t={})=>{I().event(m.AI_STYLIZED_CAPTION,e,void 0,void 0,JSON.stringify(t))},KAt=e=>{const{openTrigger:t}=e;lr("open_panel",{openTrigger:t===null?"UNKNOWN":en[t]})},XAt=()=>{lr("click_create")},JAt=e=>{lr("polling_done",e)},qAt=e=>{lr("generate_done",e)},QAt=e=>{lr("insert_done",e)},RBe=e=>{lr("export_done",e)},ZAt=e=>{lr("generate_failed",e)},$At=e=>{lr("regenerate_done",e)},eyt=()=>{lr("view_result_modal")},tyt=()=>{lr("close_result_modal")},oyt=e=>{lr("click_advanced",{is_open:e})},ryt=()=>{lr("click_reset_chroma_key")},nyt=e=>{lr("click_insert",{...e})},ayt=()=>{lr("click_recent_asset")},iyt=()=>{lr("click_recent_advanced_options")},syt=()=>{lr("click_modify_asset_menu")},xyt=()=>{lr("click_modify_floating_menu")},cyt=()=>{lr("click_modify_result_modal")},lyt=e=>{lr("click_recent_more",e)},dyt=()=>{lr("click_recent_modify")},uyt=e=>{lr("click_recent_restore",e)},pyt=()=>{lr("click_recent_cancel")},fyt=()=>{lr("cancel_failed")},gyt=()=>{lr("click_modify_context_menu")},_yt=()=>{lr("click_recent_favorite")},Eyt=()=>{lr("click_recent_delete")},myt=e=>{lr("click_regenerate",e)},ABe=(e,t)=>{const o=qt(),r=A("export.user_cancel?"),n={onCancel:async()=>{o.abort()},cancelTitle:r},a=async()=>{const w=ql(r);return await Y().popup(w)===mt.YES?(o.abort(),Ts.OK):Ts.CANCEL};pt().addCloseHandler(a);const i=m0(Sa(A("export.prepare")));let s,x=0,c=0,l=0,d=0,u=e.type===V.AUDIO_MP3||e.type===V.AUDIO_WAV?A("export.progress_audio"):e.type===V.IMAGE?A("export.progress_image"):e.type===V.STATIC_FRAME?A("export.progress_static_frame"):A("export.progress_video");const p=e.type===V.IMAGE;let f=u,E="",T=c;const O=setInterval(()=>{if(c>1||(x=x-1,document.hasFocus()===!1))return;const w=s===Jn.AUDIO_CONCAT_WATCH?`
4245`:p?A("export.completed_images",{numerator:l,denominator:d}):A("export.remain_time",{remainTime:os(Math.max(x,0))});if(f!==u||E!==w||T!==c){const N=c,M={...n,remainTime:w,progressRatio:N};i.message(Sa(u,M)),f=u,E=w,T=c}},1e3),S=new u2(10),R=()=>{clearInterval(O),pt().removeCloseHandler(a)};let y;return{onStart:()=>S.start(),onProgress:(w,N,M)=>{if(M===Jn.AUDIO_CONCAT_WATCH&&(y===void 0&&(y=new Jo),y.getElapsedSec()*1e3<3e3))return;c=w/N,p?(l=w,d=N):x=S.supply(w/N),s!==M&&(s=M,u=M===Jn.VIDEO_EXPORT_WATCH?A("export.progress_video"):M===Jn.WEBASSET_EXPORT_WATCH?A("export.progress_video_export_webassets"):M===Jn.STATIC_FRAME_EXPORT_WATCH?A("export.progress_static_frame"):A("export.progress_video_concat_audio"),S.reset());const k=parseFloat((Math.ceil(c*100)/100).toFixed(2));pt().updateIconProgressBar(k)},onEnd:async(w,N)=>{if(h("exporter.ts").info("Export end, path: "+N),pt().updateIconProgressBar(void 0),R(),jMe(e.type,(e.filterAppliedClipCount??0)>0,t),i.dismiss(3),e.type!==V.STATIC_FRAME)if(e.type===V.VIDEO)Nbe(N);else{const M={bodyClassName:"general-modal",title:A("popup.title_confirm"),content:w,yesStr:A("export.open_folder"),noStr:A("popup.close")};await Y().popup(M)===mt.YES&&yn().openFolder(N)}},onError:w=>{R(),h("exporter.ts").error("EncodeInternalError : "+P(w)),i.dismiss(),pt().updateIconProgressBar(void 0);const N=w.errorCode===_.D_ERR_SOURCE_FILE_LOST?"error.source_file_lost_info":void 0,M=w.errorCode??_.C_EXPORT_GENERAL_ER
4245ROR,k=Ot(M,{defaultKey:"export.export_error",errorArg:w.errorArgs,errorDescKey:N}),F=p0(k);Y().error(M,F)},onCancel:()=>{h("exporter.ts").debug("Exporting video cancelled by user. during VIDEO_EXPORT_WATCH"),pt().updateIconProgressBar(void 0),R(),i.dismiss()},onResult:(w,N)=>{}}},tg=e=>({[V.VIDEO]:Kt.MP4,[V.TRANSCODING_VIDEO]:Kt.MP4,[V.TRANSCODING_AUDIO]:Kt.MP3,[V.CONVERTING_GIF]:Kt.WEBM,[V.STREAM]:Kt.HLS,[V.CAPTION_VIDEO]:Kt.MOV,[V.IMAGE]:Kt.PNG,[V.ANIMATED_IMAGE]:Kt.GIF,[V.AUDIO_MP3]:Kt.MP3,[V.AUDIO_WAV]:Kt.WAV,[V.AUDIO_AAC]:Kt.M4A,[V.SPLIT_MEDIA]:Kt.MP4,[V.STATIC_FRAME]:Kt.MP4,[V.PROXY_VIDEO]:Kt.MP4})[e],yBe=async(e,t,o,r)=>{const n=[],a=s=>{const{videoInfo:x,audioInfo:c,duration:l}=s.videoAudioMetaInfo;return JSON.stringify({type:s.sourceType,path:s.originalPath,videoCodec:x?.codec??void 0,videoSize:x?x.size.width+"x"+x.size.height:void 0,frameRate:x?.frameRate,audioCodec:c?.codec,audioSampleRate:c?.sampleRate,duration:PD(l)})};n.push(...e.map(a)),n.push(...t.map(a)),h("exporter.ts").info("Exporting start, duration: "+PD(o)+", encodingSetting : "+nge(r)+`
4246`+n.join(`
4247`))},vBe=async(e,t,o,r,n,a)=>{HMe(n.type,(n.filterAppliedClipCount??0)>0,r);const i=ABe(n,r),s={},{mediaIds:x,assetMediaIds:c}=HI(t),l=[],d=[];return x.forEach(u=>{const p=FI(e).find(f=>f.mediaId===u&&f.sourceType===de.VIDEO_AUDIO);p&&(s[u]=p.originalPath,l.push(p))}),c.forEach(u=>{const p=UI(e).find(f=>f.mediaId===u);p&&d.push(p)}),yBe(l,d,o,n).catch(u=>{h("exporter.ts").error("Error during logExportFiles: "+P(u))}),qt().encode(e,s,t,a,i,n)},wBe=e=>{const t=ca(),o=Object.keys(e).length>0,r=t.map(s=>s.videoAudioMetaInfo.audioInfo?.sampleRate??zx),n=new Set(r);o&&n.add(e_);const a=(s,x)=>x-s;return[...n].sort(a)[0]},DB=(e,t,o,r,n,a,i,s,x,c,l,d,u,p,f,E,T)=>async(O,S)=>{const R=qt();if(!R.ready)return xt.error(A("export.not_ready")),{type:Dr.NOT_STARTED,elapsedSec:0};const y=c!==gr.NONE,v=a===V.IMAGE||a===V.ANIMATED_IMAGE,w=a===V.CAPTION_VIDEO,N=S();if(E_e(N)||Qh(Ur.EXPORT))return Y().warn(A("export.busy")),{type:Dr.NOT_STARTED,elapsedSec:0};let k={type:Dr.FAILED,elapsedSec:0};const F=[];try{O(GM(!0));const G=d+"-"+n.width+"x"+n.height+"-"+Uoe(i),B=se().isDemo()?"demo":w?d:G,W=age(s);if(DMe(a,B,e,f),kMe(a,l>0,e),JUe(s,W),a===V.VIDEO&&(fke(y,R.getAvailableHwAccel(),e),o===!1&&VMe(G,e)),!await H0(a))throw new C(_.C_ENCODING_USER_CANCELED);const j=Lp(t),$=Fi(N),q=E0(N),H=wg(N),U=vg(N),te={type:a,exportId:e,captionSetting:r,size:n,quality:i,hwAccel:c,videoFrameRate:W,videoRatio:u,audioSampleRate:v?void 0:wBe($),filterAppliedClipCount:l,exportByClip:f,option:x,triggerSurveyToast:E,mediaTrackMap:T,assetTimelineRanges:q,overdubInfosMap:U,watermark:H},ne=tg(a);switch(F.push(...FMe(a,ne,j,e)),k=await vBe(p,t,j,e,te,ne),k.type){case Dr.SUCCESS:{const oe=mo(N),re=lt(N),ge=ht(N),{markerNum:fe,clipsNum:ve,userImageClipsNum:yt,imageIds:Le,vrewMark:We,vrewMarkClipsNum:kt}=Eb(oe,re,ge),bt=sp(oe,re,ge).length;let Jt;if((a===V.IMAGE||a===V.ANIMATED_IMAGE)&&(Jt=t.length),zMe(a,ne,bt,oe.length,We,Jt,e),a===V.VIDEO){l>0&&uke(l,e),gke(y,R.getAvailableHwAccel(),e);const Ft=await pt().getSystemInfo();Mke(k,y?c:gr.NONE,n,j,te.quality,te.videoFrameRate,Ft,e)}d===so.ALL&&(bBe(Le,re,ge,e),lke(kt,yt,ve,e),LBe(kTe(t.flatMap(Ft=>Ft.exportAssets.map(Pe=>Pe.asset))),e)),a!==V.STATIC_FRAME&&EP(fe,ve,e);break}case Dr.USER_CANCELED:YMe(a,(te.filterAppliedClipCount??0)>0,e);break;default:break}}catch(G){h("exporter.ts").error("Error during encodeMedia : "+P(G));const B=ye(G)??_.C_EXPORT_GENERAL_ERROR;if(B===_.C_ENCODING_USER_CANCELED)return xt.info(A("export.cancel")),{type:Dr.USER_CANCELED,elapsedSec:0};const W=Ot(B,{defaultKey:"export.export_error",errorArg:Ho(G)});Y().error(B,W)}finally{O(GM(!1)),F.forEach(clearTimeout)}return k},hyt=(e,t,o,r,n,a,i)=>async s=>{const x=se().getInitProjectVideoSize(),c=use()===!1?_4("FHD",r):x9<Math.max(x.width,x.height)?L4(x,r):H_e(x.width,x.height,r),l=e.words.at(t),d=l?pW(l,a,i):[],u=NG(d)?1:0,p=qt().getAvailableHwAccel(),f=F0.HIGH,E=await Ue().tempFolder(),T=E+"/"+ct(),O={staticFrameEncodingOption:{outputPathName:T}};try{const S=await s(PBe(o,c,V.STATIC_FRAME,f,e0.DEFAULT,O,p,u,Vo.CURRENT_POSITION_WORD,n,!1));if(S===void 0)throw new Error("export is undefined. export failed.");const[R,y]=S;if(R.type===Dr.USER_CANCELED)throw new C(_.C_ENCODING_USER_CANCELED);const v=await NBe(y,e,t);if(v===void 0)throw new Error(`timestamp is undefined. timestamp calculation failed. 
4248        pieces: `+JSON.stringify(y)+`,
4249        visibleClip: `+JSON.stringify(e)+`,
4250        visiblePosition: `+t+`,
4251      `);const w=await yn().readFile(T+".mp4"),N=new Blob([w],{type:"video/mp4"}),M=URL.createObjectURL(N),k=await L_e(M,v).finally(()=>URL.revokeObjectURL(M));if(k===void 0)throw new Error("pngBlob is undefined. screenshot failed.");return[R,k]}finally{await yn().deleteFiles([T+".mp4"])}},NBe=async(e,t,o)=>{const r=ns(t,o),n=r===t.words.length-1,a=n?t.words.at(r-1):t.words.at(r);
4251if(a===void 0){h("exporter.ts").warn("[exportStaticFrame] visibleWord is undefined.");return}const i=new Map(t.words.map(c=>[c.id,c])),s=(c,l)=>{let d=0;for(const u of c){const p=i.get(u);if(!p)continue;const f=Rn(p);if(u===a.id){l&&(d+=f);break}d+=f}return d};return e.filter(c=>c.wordIds.includes(a.id)).map(c=>c.wordIds).reduce((c,l)=>c+s(l,n),0)},PBe=(e,t,o,r,n,a,i,s,x,c,l)=>async(d,u)=>{kB();const p=u();try{const f=Ya(p),E=Ad(),T=lt(p),O=ht(p),S=wg(p),R=YH(u,x),y=xn(p),v=oc(p),w=I2(p),N=VW(p),M=ex(p),{encodeClips:k,targetWordId:F}=xT(p,x),{exportAssets:G,exportOverdubInfos:B,assetOverdubIdMap:W,missingAssetIds:Q}=tb(p),j=yH(k,Q),$=SBe(j,T,O),q=j.map(_t=>({..._t,videoTransform:_t.videoTransform??N})),H=await MB(T,O,Q),U=Mv(p),te=o===V.CAPTION_VIDEO?Kl.CAPTION_TRANSPARENT_VIDEO:U?Kl.WITH_CAPTION:Kl.WITHOUT_CAPTION,ne=Dxe(p),oe=Fg(p),re=Ede(T,O,oe),ge=o===V.STATIC_FRAME&&F!==void 0,fe=WI(q,G,W,B,ne,te,c,y,M,re),ve=ge?fe.filter(_t=>_t.wordIds.some(No=>No===F)):fe;if(at()){const{assetMediaIds:_t}=HI(ve);await Ue().restoreLocalCache(_t)}const yt=DW(p),Le=E0(p),We=BH(j,T,O,yt,oe),kt=KH(j,T,O,Le),bt={...We,...kt},Jt=[],Ft=setInterval(()=>{Jt.push(document.hasFocus())},1e3),Pe=()=>{d(uS(Kc.EXPORT_VIDEO))};if(ve.length>0){const _t=await d(DB(E,ve,U,e,t,o,r,n,a,i,s,R,j0(w),H,l,Pe,bt));if(clearInterval(Ft),_t.type===Dr.SUCCESS){if(o===V.VIDEO&&$>0&&RBe({assetCount:$}),o===V.STATIC_FRAME)return[_t,ve];jT(HT(p,WT(tg(o)),x,{webAssetPrepare:_t.encodingPerformance?.elapsedWebassetPrepareSec},E),BT(p)),v&&YT(zT(p,E,tg(o),XI(y))),!(f.planInfo===void 0)&&S===void 0&&Xh("deleteVrewMark"),Lke(m.EXPORT,Jt)}return FB(_t),[_t,ve]}else{Y().warn(A("export.empty"));return}}catch(f){const E=ye(f)??_.C_EXPORT_GENERAL_ERROR,T=Ot(E,{defaultKey:"export.export_error",errorArg:Ho(f)});h("exporter.ts").error("Error during getExportAssetInfo: "+P(f)),Y().error(E,T);return}},Iyt=(e,t,o)=>async(r,n)=>{try{const a=n(),i=Ad();kB();const{encodeClips:s}=xT(a,e),x=YH(n,e),c=xn(a),l=oc(a),d=lt(a),u=ht(a),p=ex(a),f=E0(a),E=DW(a),T=Fg(a),{exportAssets:O,exportOverdubInfos:S,assetOverdubIdMap:R,missingAssetIds:y}=tb(a),v=yH(s,y),w=await MB(d,u,y),N=BH(v,d,u,E,T),M=KH(v,d,u,f),k={...N,...M},F=WI(v,O,R,S,sy,Kl.WITHOUT_CAPTION,_f,c,p);if(F.length<=0)return Y().warn(A("export.empty")),r;const G=()=>{r(uS(Kc.EXPORT_AUDIO))},B=await r(DB(i,F,!1,Eg,{width:0,height:0},t,F0.REGULAR,e0.DEFAULT,{},gr.NONE,0,x,he.INIT,w,o,G,k));return B.type===Dr.SUCCESS&&(jT(HT(a,WT(tg(t)),e,{},i),BT(a)),l&&YT(zT(a,i,tg(t),"none",0))),FB(B),r}catch(a){const i=ye(a)??_.C_EXPORT_GENERAL_ERROR,s=Ho(a),x=Ot(i,{defaultKey:"export.export_error",errorArg:s});h("exporter.ts").error("Error during getExportAssetInfo: "+P(a)),Y().error(i,x);return}},kB=()=>$p().requestGrant(),FB=e=>{let t;switch(e.type){case Dr.SUCCESS:t=A("osinfo.ok");break;case Dr.FAILED:t=A("osinfo.failed");break}t&&$p().notify(t)},bBe=(e,t,o,r)=>{let n=0;e.forEach(i=>{const s=L.get(o,i);if(!s)return;s.trackIds.map(c=>L.get(t,c)).filter(c=>c!==void 0&&Gn(c)).forEach(c=>{const l=c.mediaId;!l||!oa(l)||++n})}),xke(0,n,r)},LBe=async(e,t)=>{const o=[14,24,34,44,13,23,33,43,12,22,32,42,11,21,31,41],r=[{sizeRatio:.05,code:"a"},{sizeRatio:.1,code:"b"},{sizeRatio:.25,code:"c"},{sizeRatio:.5,code:"d"},{sizeRatio:.75,code:"e"},{sizeRatio:1/0,code:"f"}],n=(x,c)=>{const l=Math.floor($t(x,0,1)*100),d=Math.floor($t(c,0,1)*100),u=Math.floor(d/25),p=Math.floor(l/25),f=u*4+p;return o[f]},a=(x,c)=>{const l=x*c;for(const{sizeRatio:d,code:u}of r)if(l<d)return u;return r[r.length-1].code},i=se().getInitProjectVideoSize(),s=e.map(x=>{if(!oa(x.mediaId))return h("exporter.ts").error("Cannot find media for mediaId "+x.mediaId),"";const l=x.xPos+x.width/2,d=x.yPos+x.height/2,u=n(l,d),p=a(x.width,x.height),f=i.width*x.width,E=i.height*x.height,T=Math.floor(E===0?0:f/E*100)/100;return x.mediaId+","+u+"_"+p+"_"+T}).filter(x=>x).filter((x,c,l)=>l.indexOf(x)===c).map(x=>{const c=x.match(/.*,(.*)/);return c?c[1]:(h("exporter.ts").error("Parsing failed of ga label "+x),"")}).filter(x=>x);cke(s,t)},MBe=(e,t,o)=>{const r=L.get(E0(o),t);if(!r)return;const n=r.timelineStart,a=r.timelineEnd-r.timelineStart,i=MI(e.assetEffectInfo,a),s={assetId:t,startTimelineTime:n,duration:a,animationInfo:i};return{type:Ce.WEB,asset:e,animationExportInfo:s}},DBe=e=>({type:Ce.LOTTIE,asset:e}),kBe=(e,t,o,r)=>{const{isTransparent:n}=r;
4251if(e.kenburnsAnimationInfo===void 0&&e.assetEffectInfo===void 0)return{type:Ce.IMAGE,asset:e,isTransparent:n};const a=L.get(E0(o),t);if(!a)return;const i=a.timelineStart,s=a.timelineEnd-a.timelineStart,x=MI(e.assetEffectInfo,s),c={assetId:t,startTimelineTime:i,duration:s,animationInfo:x};return{type:Ce.IMAGE,asset:e,animationExportInfo:c,isTransparent:n}},FBe=(e,t,o)=>{const r=E0(o),n=r[t];if(n)return{type:Ce.VIDEO,asset:e,videoExportInfo:{timelineStart:n.timelineStart,timelineEnd:n.timelineEnd,revisedStart:n.timelineStart,revisedEnd:n.timelineEnd,startOffsetInPiece:0,videoLoopMode:qn.NO_LOOP},isTransparent:!1}},UBe=(e,t,o)=>{const r=E0(o),n=r[t];if(!n)return;const a=e.pose.speakingMediaId?eo(e.pose.speakingMediaId):void 0;return{type:Ce.SIMPLE_CHARACTER,asset:e,assetId:t,isVoiceWord:void 0,webmDuration:a?.videoAudioMetaInfo?.duration,videoExportInfo:{timelineStart:n.timelineStart,timelineEnd:n.timelineEnd,revisedStart:n.timelineStart,revisedEnd:n.timelineEnd,startOffsetInPiece:0,videoLoopMode:qn.MANUAL_LOOP}}},VBe=(e,t,o)=>{if(e.assetEffectInfo===void 0)return{type:Ce.SHAPE,asset:e};const r=L.get(E0(o),t);if(!r)return;const n=r.timelineStart,a=r.timelineEnd-r.timelineStart,i=MI(e.assetEffectInfo,a),s={assetId:t,startTimelineTime:n,duration:a,animationInfo:i};return{type:Ce.SHAPE,asset:e,animationExportInfo:s}},GBe=e=>{const t={trackId:e.trackId,mediaId:e.mediaId,type:ze.VideoAudio,sourceIn:e.sourceIn,sourceOut:e.sourceOut,volume:e.volume,loop:e.loop,playbackRate:e.playbackRate},o={trackId:e.trackId,mediaId:_o,type:z.VIDEO,sourceIn:e.sourceIn,sourceOut:e.sourceOut,audio:t,originalWidthHeightRatio:16/9,isTrimmable:!1,hasAlphaChannel:!1,xPos:0,yPos:0,width:1,height:1,rotation:0,zIndex:0,endBehavior:Fs.FREEZE};return{type:Ce.VIDEO,asset:o,videoExportInfo:{timelineStart:0,timelineEnd:0,revisedStart:0,revisedEnd:0,startOffsetInPiece:0,videoLoopMode:qn.NO_LOOP},isTransparent:!1}},tb=e=>{const t=oG,o=lt(e),r=ht(e),n={},a={},i={},s=new Set;return Object.entries(r).forEach(([x,{trackIds:c,role:l}])=>{const d=Je(x);let u;const p=c.map(f=>L.get(o,f)).filter(Se);for(const f of p){if(K9e(f)){s.add(d);return}if(x2(f)){i[d]=f.overdubId;const{duration:E}=NH(f);n[f.overdubId]={mediaId:f.mediaId,audioDuration:E}}switch(f.type){case z.WEB:{u=MBe(f,d,e);break}case z.LOTTIE:{u=DBe(f);break}case z.IMAGE:{const E=oa(f.mediaId);if(E===void 0)break;u=kBe(f,d,e,E);break}case z.VIDEO:{if(eo(f.mediaId)===void 0)break;const T=p.find(S=>S.type===ze.VideoAudio),O={...f,audio:T};u=FBe(O,d,e);break}case z.SHAPE:{u=VBe(f,d,e);break}case z.SIMPLE_CHARACTER:{u=UBe(f,d,e);break}}u!==void 0&&(t(f)&&(u.asset={...u.asset,mediaId:qe.v4()}),L.set(a,d,{asset:u,role:l}))}if(u===void 0&&l==="main"){const f=p.find(E=>By(E)||U0(E));if(f){const E=GBe(f);L.set(a,d,{asset:E,role:l})}}}),{exportAssets:a,exportOverdubInfos:n,assetOverdubIdMap:i,missingAssetIds:s}},WBe=e=>{const t=e.map(r=>r.id),o=e.map(r=>r.text).join(" ");return{type:ot.REGISTER_OVERDUB_STATE,payload:{wordIds:t,wordText:o}}},Tyt=e=>({type:ot.REMOVE_OVERDUB_STATE,payload:{wordId:e}}),VF=(e,t,o)=>({type:ot.CHANGE_OVERDUB_STATE,payload:{headWordId:e,status:t,targetText:o}}),Syt=(e,t,o,r,n,a)=>async(i,s)=>{const x=e[0],c=be().getUserInfo()?.uid??tn,l=s(),d=vg(l),u=lt(l),p=ht(l),f=Fi(l);if(i(VF(x,"processing",t)),n){const S=KA(et.OVERDUB_ONBOARDING_WORD_EDIT);S?await i(GF(Fr.ONBOARDING_TOUR,S)):i(Xx(Fr.ONBOARDING_TOUR,!1))}const E=await ofe(c,d,o,e,t,r,n,a,u,p,f);if(!L.get(fW(s()),x))return;
4251if(E.result==="error"){const S=h("overdub.ts");E.noContext?(S.warn("Context exceeded"),xt.warn(A("overdub.context_exceeded_toast"))):(S.error("Overdub request failed: "+E.errorMsg),xt.error(A("overdub.overdub_request_failed_toast"))),n&&i(qBe(Fr.ONBOARDING_TOUR)),i(VF(x,"error"));return}const T=44100,O=qe.v4();if(await i_({mediaId:O,audioBlob:E.blob,sampleRate:T,codec:Gt.MP3,duration:E.audioDuration,sourceOrigin:tt.AI_GENERATED,name:t+"."+Hh,sourceType:de.OVERDUB}),i(YP([{mediaId:O,audioBlob:E.blob,path:URL.createObjectURL(E.blob),duration:E.audioDuration}],!0)),i({type:Zt.APPLY_OVERDUB,payload:{wordIds:e,text:t,mediaId:O}}),se().markDirty(),n){const S=KA(et.OVERDUB_ONBOARDING_WORD_EDIT);S?await i(GF(Fr.ONBOARDING_TOUR,S)):i(Xx(Fr.ONBOARDING_TOUR,!1));return}po(ke.OVERDUB_USAGE_TOOLTIP_SUPPRESSED,!1),wn(It.OVERDUB_TOOLTIP),cfe(r)},Oyt=e=>({type:Zt.RESET_OVERDUB,payload:{wordId:e}}),Cyt=async(e,t,o,r,n,a,i,s,x,c,l)=>{if(!await lfe(i))return;const d=o.length>0?o:r!==null?[r]:void 0;if(t&&d&&d[0]<=Mce(n)){const u=d.map(f=>t.words.at(f-t.startPosition)).filter(Se),p=kw(t.words);if(u.length<=0||!xfe(u,p,a,x,c,l)){Ek(s,!1);return}e(u),Ek(s,!0)}},ob={[It.START_NEW_PROJECT]:{badge:{color:"red"},tooltip:{title:"toolbar.new_feature_newproject",desc:"toolbar.new_feature_newproject_desc",type:"notice",closedKey:It.START_NEW_PROJECT_TOOLTIP_CLOSED},showOnFirstUse:!0,tabMenu:bo.HOME},[It.VIDEO_REMIX_TOOLBAR_CLICKED]:{badge:{color:"red"},tooltip:{title:"toolbar.new_feature_video_remix",desc:"toolbar.new_feature_video_remix_desc",type:"notice",closedKey:It.VIDEO_REMIX_TOOLTIP_CLOSED},tabMenu:bo.FILE},[It.CREATE_FRAMEPACK]:{badge:{color:"red"},tooltip:{title:"toolbar.new_feature_frame",desc:"toolbar.new_feature_frame_desc",type:"notice",closedKey:It.CREATE_FRAMEPACK_TOOLTIP_CLOSED},tabMenu:bo.TEMPLATE},[It.CHARACTER_STUDIO_V4]:{badge:{color:"red"},tabMenu:bo.INSERT},[It.ASSET_SELECT_MENU]:{badge:{color:"red"},tabMenu:bo.EDIT},[It.VCLOUD]:{badge:{color:"red"},tooltip:{title:"toolbar.new_feature_cloud",desc:"toolbar.new_feature_cloud_desc",type:"notice",closedKey:It.VCLOUD_TOOLTIP_CLOSED},tabMenu:bo.FILE},[It.CLIENT_LINEBREAK]:{badge:{color:"red"},tooltip:{title:"toolbar.new_feature_client_linebreak",desc:"toolbar.new_feature_client_linebreak_desc",type:"notice",closedKey:It.CLIENT_LINEBREAK_TOOLTIP_CLOSED},tabMenu:bo.EDIT},[It.THUMBNAIL_GENERATOR]:{badge:{color:"red"},tabMenu:bo.FILE},[It.TRANSITION]:{badge:{color:"red"},tabMenu:bo.EFFECT},[It.VOCAL_DICTIONARY]:{badge:{color:"red"},tooltip:{title:"toolbar.new_feature_vocal_dictionary",desc:"toolbar.new_feature_vocal_dictionary_desc",type:"notice",closedKey:It.VOCAL_DICTIONARY_TOOLTIP_CLOSED},tabMenu:bo.AI_VOICE},[It.DENOISE]:{badge:{color:"red"},tooltip:{title:"toolbar.new_feature_denoise",desc:Oo()?"toolbar.new_feature_denoise_desc_electron":"toolbar.new_feature_denoise_desc_web",type:"new",closedKey:It.DENOISE_TOOLTIP_CLOSED},tabMenu:bo.EFFECT},[It.OVERDUB]:{badge:{color:"red"},tabMenu:bo.EDIT},[It.NOTICE_CLOUD_AUTO_SAVE]:{badge:{color:"red"},tooltip:{title:"vcloud.notice_cloud_auto_save_title",desc:"vcloud.notice_cloud_auto_save_desc",type:"notice",closedKey:It.NOTICE_CLOUD_AUTO_SAVE_TOOLTIP_CLOSED},tabMenu:bo.FILE},[It.FREEZE_WORD]:{badge:{color:"red"},tooltip:{title:"toolbar.new_feature_freeze_word",desc:"toolbar.new_feature_freeze_word_desc",type:"new",closedKey:It.FREEZE_WORD_TOOLTIP_CLOSED},tabMenu:bo.INSERT}},HBe=()=>ob,UB=e=>ob[e],Ryt=e=>{const t=Object.values(ob).filter(o=>o.tabMenu===e);return t.length===0?null:t[0].badge?.color??null},jBe=null,O_=In({name:"newFeature",initialState:jBe,reducers:{setActiveNewFeature:(e,t)=>t.payload,closeNewFeatureTooltip:e=>{e&&(e.isTooltipClosed=!0)}}}),Ayt=O_.reducer,rb=e=>ja(e).toolbar.newFeature,nb=e=>rb(e)?.key??null,yyt=e=>rb(e)?.isTooltipClosed??!1,zBe=e=>(t,o)=>{if(rb(o()))return;const r=UB(e);if(!gV([e,r]))return;const n=r.tooltip?.closedKey,a=n!==void 0&&Ta(n);t(O_.actions.setActiveNewFeature({key:e,isTooltipClosed:a})),_V()!==e&&(Cre(e),Ore(e))},vyt=e=>(t,o)=>{nb(o())===e&&t(O_.actions.setActiveNewFeature(null))},wyt=()=>async e=>{const t=HBe(),o=await Tre(t),r=YBe(o);r&&e(zBe(r))},Nyt=(e,t=!1)=>(o,r)=>{wn(e,t),nb(r())===e&&o(O_.actions.setActiveNewFeature(null))},VB=e=>(t,o)=>{const r=UB(e)?.tooltip?.closedKey;r&&wn(r),nb(o())===e&&t(O_.actions.closeNewFeatureTooltip())},YBe=e=>e.length===0?null:e[Math.floor(Math.random()*e.length)],BBe=3,ab=(e,t)=>
4251{const o=ld();o===null||o.disposed||o.play({...e,legacyContext:{visiblePosition:e.playPosition,clips:Do(t),trackEntries:lt(t),assetEntries:ht(t),overdubInfosMap:vg(t)}})},Ol=(e,t)=>e===t.tourId,Cl=(e,t,o)=>(r,n)=>{const a=n(),i=fs(a),s=c9[e];!s||i.tourInfo.type!==Ct.NONE||(o?.(),r(rYe({tourId:t,tourInfo:s})))},Xx=(e,t)=>(o,r)=>{const n=r(),a=fs(n);Ol(e,a)&&o(GB(a.tourInfo.type,a.currStep,t))},GB=(e,t,o)=>r=>{aP(hf.CLOSED,e,t,o),r(Va()),r(nYe())},KBe=e=>(t,o)=>{const r=o(),n=fs(r);Ol(e,n)&&t(nB({resolving:!0}))},XBe=e=>(t,o)=>{const r=o(),n=fs(r);Ol(e,n)&&t(nB({resolving:!1}))},JBe=(e,t)=>(o,r)=>{const n=r(),a=fs(n),{currStepIdx:i,tourInfo:{steps:s}}=a;Ol(e,a)&&(aP(hf.ACTION_DONE,a.tourInfo.type,a.currStep,!1),i===s.length-1?o(Xx(e,!1)):(o(aYe({step:1})),t?.()))},qBe=e=>(t,o)=>{const r=o(),n=fs(r),{currStepIdx:a}=n;Ol(e,n)&&t(a===0?Xx(e,!1):iYe({step:1}))},GF=(e,t)=>async(o,r)=>{const n=r(),a=fs(n);if(!Ol(e,a))return;aP(hf.RESOLVED,a.tourInfo.type,a.currStep,!1),o(WB(e)),o(KBe(e));const i=await t(e,o,r);o(XBe(e)),i&&o(JBe(e))},WB=e=>(t,o)=>{const r=o(),n=fs(r);Ol(e,n)&&t(rB({show:!1}))},Pyt=e=>(t,o)=>{const r=o(),n=fs(r);Ol(e,n)&&t(rB({show:!0}))},BA=async(e,t,o,r)=>{await Fo(t);const n=r(),a=fs(n),i=a.tourId===e;return!i&&o(GB(a.tourInfo.type,a.currStep,!0)),i},QBe=(e,t,o)=>{const r=Fe(),n=o(),a=He(n),i=a.findIndex(c=>c.clipId===lm[r]),s=a[i],x=cy[r]?.at(0);!x||i===-1||(wn(It.LEGACY_ONBOARDING_2_TOUR_SHOWN),t(B0({captionIndex:0,globalClipIndex:i,initCaretPosition:{childIndices:[0],offset:s.captionMode===ar.MANUAL?wt().toText(s.captions[0].text).length:x.offset}},i)))},ZBe=async(e,t,o)=>{const r=o(),n=Fe(),a=Do(r),i=a.find(x=>x.id===lm[n]),s=cy[n]?.at(-1)?.caption;return i?.captions.at(0)?.text===s},$Be=async(e,t,o)=>{const r=Fe(),n=lm[r];if(!n)return!1;const a=o(),i=He(a),s=i.findIndex(u=>u.clipId===lm[r]),x=i[s];if(!x)return!1;const c=cy[r];if(!c)return!1;const l=(u,p)=>t(E8e(s,0,r,u,{captionIndex:0,globalClipIndex:s,initCaretPosition:{childIndices:[0],offset:p}},cm.SYSTEM));t(B0({captionIndex:0,globalClipIndex:s,initCaretPosition:{childIndices:[0],offset:c.at(0)?.offset??0}},s));const d=document.getElementById(Td(x.clipId));if(d&&t(op(d,Gc.ONBOARDING_TOUR,"clip-overlay")),await BA(e,1e3,t,o)===!1)return t(Va()),!1;t({type:_r.RESET_CAPTION,payload:{clipId:n}});for(const{caption:u,offset:p}of c)if(l(u,p),await BA(e,300,t,o)===!1)return t(Va()),!1;return t(Va()),!0},eKe=(e,t,o)=>{const r=Fe(),n=o(),a=xa(n),i=ly[r];if(!i)return;const s=Do(n),x=Dw(s,i),c=s.at(x);c&&t(V8(a,c))},tKe=async(e,t,o)=>{const r=q0(),n=Fe(),a=HU[n];return a===void 0||!r?!1:(t(WB(e)),await Fo(a),!0)},oKe=async(e,t,o)=>{const r=Fe(),n=o(),a=Fg(n),i=lt(n),s=ht(n),x=xa(n),c=mo(n),l=ly[r];if(!l)return!0;const d=Do(n),u=He(n),p=Dw(d,l),f=d.at(p),E=HU[r];return p===-1||!f||E===void 0||(t(V8(x,f)),ab(ms(uo.PLAY_CLIP,c,[p],null,f.startPosition,x,p,pr.AUTO,!1,a,i,s,u),n),await Fo(E)),!0},rKe=async(e,t,o)=>{const r=o(),n=Fe();return Do(r).flatMap(s=>s.words).find(s=>s.id===jU[n])===void 0},nKe=async(e,t,o)=>{const r=o(),n=Fe(),a=xa(r),i=Do(r),s=ly[n],x=jU[n];if(!s||!x)return!0;const c=i.at(Dw(i,s));if(!c)return!0;const l=document.getElementById(Td(c.id));l&&t(op(l,Gc.ONBOARDING_TOUR,"clip-overlay"));const d=Fpe(c,x);return t(G8(a,c.startPosition+d)),t({type:ka.SET_ONBOARDING_WORD_DELETE_BUTTON_ANIMATION,payload:{type:"circle-button"}}),await Fo(2e3),t({type:ka.SET_ONBOARDING_WORD_DELETE_BUTTON_ANIMATION,payload:{type:"focused"}}),await Fo(500),t({type:ka.SET_ONBOARDING_WORD_DELETE_BUTTON_ANIMATION,payload:{type:"large-button"}}),await Fo(1e3),await BA(e,500,t,o)===!1?(t(Va()),!1):(t(hK(x)),t({type:ka.SET_ONBOARDING_WORD_DELETE_BUTTON_ANIMATION,payload:{type:void 0}}),await Fo(1e3),t(Va()),!0)},aKe=()=>{at()&&(wn(It.ONBOARDING_TOUR_FINISHED),zUe())},iKe=async(e,t)=>(t(Xx(Fr.ONBOARDING_TOUR,!1)),!0),sKe=async(e,t,o)=>{const r=zs(o());return Object.keys(r).length===0&&Ta(It.TTS_INSERTED)},xKe=()=>e=>{e(Cl(Ct.NEW_USER_ONBOARDING,Fr.ONBOARDING_TOUR))},WF=(e,t)=>(o,r)=>{const n=r(),a=He(n)[ec(n)]?.clipId;a!==void 0&&(ir().set(Wt.TABKEY_TOOLTIP_CLIP_ID,a),o(Cl(e,t)))},cKe=e=>(t,o)=>{Ta(It.MARKER_PANEL)||nP(Bu.MARKER_PANEL_MESSAGE)>=BBe||fs(o()).tourInfo.type!==Ct.NONE||(ir().set(Wt.MARKER_PANEL_CLIP_ID,e),t(Cl(Ct.MARKER_PANEL,Fr.MARKER_PANEL)),U5(Bu.MARKER_PANEL_MESSAGE),LMe())},byt=()=>e=>{e(Cl(Ct.PROXY_GUIDE,Fr.PROXY_GUIDE)),wn(It.SHOW_PROXY_GUIDE_TOOLTIP)},Lyt=()=>e=>{e(Cl(Ct.PREPARE_PROXY_GUIDE,Fr.PREPARE_PROXY_GUIDE)),wn(It.SHOW_PREPARE_PROXY_GUIDE_TOOLTIP)},HB=e=>t=>{t(Xx(Fr.PROXY_GUIDE,e)),t(Xx(Fr.PREPARE_PROXY_GUIDE,e))},lKe=async()=>(po(ke.PREPARE_PROXY,!0),wn(It.PREPARE_PROXY),!0),dKe=async(e,t,o)=>{const r=o(),n=Fe(),a=Fg(r),i=lt(r),s=ht(r),x=xa(r),c=mo(r),l=e2[n];if(!l)return!0;const d=He(r),u=ml(d,l),p=d.at(u);return u===-1||!p?!0:(t(T_(p.startPosition)),ab(ms(uo.PLAY_CLIP,c,[u],null,p.startPosition,x,u,pr.AUTO,!1,a,i,s,d),r),await Fo(3e3),t(Va()),!0)},uKe=async(e,t)=>(t(Va()),!0),pKe=async(e,t)=>(t(Va()),!0),fKe=async(e,t)=>!0,gKe=async(e,t,o)=>{const r=o(),n=Fe(),a=Fg(r),i=lt(r),s=ht(r),x=xa(r),c=mo(r),l=e2[n];if(!l)return!0;const d=He(r),u=ml(d,l),p=d.at(u);if(u===-1||!p)return!0;const f=document.getElementById(Td(p.clipId));return f&&t(op(f,Gc.ONBOARDING_TOUR,"clip-overlay",!1)),ab(ms(uo.PLAY_CLIP,c,[u],null,p.startPosition,x,u,pr.AUTO,!1,a,i,s,d),r),await Fo(4e3),t(Va()),!0},_Ke=async(e,t)=>(t(Va()),t(VB(It.START_NEW_PROJECT)),!(be().getUserInfo()!==void 0)||ls("overdub_onboarding_start_menu")===cv.overdub_onboarding_start_menu.B||xse(),!0),EKe=(e,t)=>{t(VB(It.START_NEW_PROJECT)),t(Va())},mKe=async(e,t)=>{t(Va())},hKe=async()=>Mt(ke.PREPARE_PROXY),IKe=(e,t,o)=>{const r=o(),n=Fe(),a=e2[n];if(!a)return!1;const i=He(r),s=ml(i,a),x=i.at(s);if(s===-1||!x)return!1;const c=document.getElementById(Td(x.clipId));return c&&t(op(c,Gc.ONBOARDING_TOUR,"clip-overlay",!1)),!0},TKe=(e,t,o)=>{const r=Fe(),n=o();t(K8(void 0,!0));const a=e2[r];if(!a)return;
4251const i=He(n),s=ml(i,a),x=i.at(s);if(!x)return!1;const c=x.startPosition+x.words.findIndex(l=>l.id===zU[r]);return t(T_(c,!0)),!0},SKe=(e,t,o)=>{const r=Fe(),n=o(),a=e2[r];if(!a)return;const i=He(n),s=ml(i,a),x=i.at(s);if(!x)return;const c=x.words.find(l=>l.id===zU[r]);if(!c){t(Va());return}return t(WBe([c])),!0},OKe=async(e,t,o)=>{const r=o(),n=Fe(),a=e2[n];if(!a)return!1;const i=He(r),s=ml(i,a),x=i.at(s);if(s===-1||!x)return!1;const c=document.getElementById(Td(x.clipId));return c&&t(op(c,Gc.ONBOARDING_TOUR,"clip-overlay",!1)),t(ize()),!0},CKe=async(e,t)=>{const o=document.querySelectorAll(".start-modal-wrapper");if(o.length>0){const r=o[o.length-1];t(op(r,Gc.ONBOARDING_TOUR,"toolbar-overlay",!0))}return!0},Myt=e=>{switch(e){case et.NEW_USER_ONBOARDING_CAPTION_MODIFY:return QBe;case et.NEW_USER_ONBOARDING_VIDEO_PLAY_BEFORE_DELETE:return eKe;case et.NEW_USER_ONBOARDING_START_MENU:return aKe;case et.OVERDUB_ONBOARDING_LISTEN_CLIP:return IKe;case et.OVERDUB_ONBOARDING_SELECT_WORD:return TKe;case et.OVERDUB_ONBOARDING_WORD_EDIT:return SKe;case et.OVERDUB_ONBOARDING_LISTEN_RESULT:return OKe;case et.OVERDUB_ONBOARDING_START_MENU:return CKe;default:return}},KA=e=>{switch(e){case et.NEW_USER_ONBOARDING_CAPTION_MODIFY:return $Be;case et.NEW_USER_ONBOARDING_VIDEO_PLAY_BEFORE_DELETE:case et.NEW_USER_ONBOARDING_VIDEO_PLAY_AFTER_DELETE:return oKe;case et.NEW_USER_ONBOARDING_WORD_DELETE:return nKe;case et.NEW_USER_ONBOARDING_START_MENU:return iKe;case et.PREPARE_PROXY_GUIDE:return lKe;case et.OVERDUB_ONBOARDING_LISTEN_CLIP:return dKe;case et.OVERDUB_ONBOARDING_SELECT_WORD:return uKe;case et.OVERDUB_ONBOARDING_WORD_EDIT:return pKe;case et.OVERDUB_ONBOARDING_GENERATING:return fKe;case et.OVERDUB_ONBOARDING_LISTEN_RESULT:return gKe;case et.OVERDUB_ONBOARDING_START_MENU:return _Ke;case et.SHOW_MARKER_PANEL_TOOLTIP:return RKe;default:return}},RKe=async(e,t,o)=>{const r=ir().get(Wt.MARKER_PANEL_CLIP_ID),n=He(o()),a=r?ml(n,r,!0):-1,i=n[a]?.markerId;return i===void 0?(t(Xx(e,!0)),!1):(t(Ize(a)),t(Kze(a,i)),bMe(),!0)},Dyt=e=>{switch(e){case et.OVERDUB_ONBOARDING_START_MENU:return EKe;case et.OVERDUB_ONBOARDING_LISTEN_CLIP:case et.OVERDUB_ONBOARDING_LISTEN_RESULT:return mKe;default:return}},kyt=e=>{const t=KA(e);if(t&&e===et.OVERDUB_ONBOARDING_SELECT_WORD)return{waitMs:3e3,action:t}},Fyt=e=>{switch(e){case et.NEW_USER_ONBOARDING_CAPTION_MODIFY:return ZBe;case et.NEW_USER_ONBOARDING_VIDEO_PLAY_BEFORE_DELETE:case et.NEW_USER_ONBOARDING_VIDEO_PLAY_AFTER_DELETE:return tKe;case et.NEW_USER_ONBOARDING_WORD_DELETE:return rKe;case et.TTS_NEW_USER_SUBMIT:return sKe;case et.PREPARE_PROXY_GUIDE:return hKe;case et.SHOW_CLICK_WORD_DELETE_BUTTON_TOOLTIP:return AKe;case et.SHOW_CLICK_PREVIEW_START_BUTTON_TOOLTIP:return yKe;case et.SHOW_TABKEY_PLAY_TOOLTIP:return vKe;case et.SHOW_RETRANSLATE_TOOLTIP:return wKe;default:return}},AKe=async(e,t,o)=>ir().get(Wt.WORD_DELETE_BUTTON_QUICK_TOOLTIP_SHOWN)==="true",yKe=async()=>ir().get(Wt.PREVIEW_START_BUTTON_QUICK_TOOLTIP_SHOWN)==="true",vKe=async()=>Ta(It.TABKEY_PLAY_USED),wKe=async()=>ir().get(Wt.RETRANSLATION_SHORTCUT_USED)==="true",NKe=e=>({engine:e.engine===Ea.XL8||e.engine===Ea.PAPAGO?Ea.GPT:e.engine}),Uyt=(e,t)=>(o,r)=>{const n=r(),a=xa(n),i=mo(n),s=Od(n),x=T2(n),c=He(n),{clips:l}=i[a];if(x&&e===zG.RE_TRANSLATE){const d=s.length?s:V3(c);o(jB(a,d,x.source,x.target,t,x.engineInfo,s.length?void 0:2,x.target));return}F2e(l)?rz(l):Y().openModal(st.TRANSLATE)},jB=(e,t,o,r,n,a,i,s)=>async(x,c)=>{const l=NKe(a),d=h("translate.ts"),u=c();if(m_e(u)){xt.info(A("translation.already_doing"));return}const f=s&&s===r;if(!t.length){const R=f?A("translation.no_clips_for_retranslate"):A("translation.no_clips_for_translate");xt.info(R);return}if(s&&s!==r){const R=D2e(s,r);if(await Y().popup(R)!==mt.YES)return}const T=(R,y,v)=>{d.error(y),dh(R,v),W3(R,"error.translation_failed",v)};let O;const S=He(u);try{await x(HF(u,S,e,t,o,r,n,l,i,s));return}catch(R){const y="Error occurred during translate with "+JSON.stringify(O)+" : "+P(R);if(ye(R)===_.C_TRANSLATION_FAILED_ERROR&&l.engine!==Ea.GOOGLE){const v=k2e(l.engine);await Y().popup(v)===mt.YES&&(d.warn(y),d.info("retry with google translate."),O=Ea.GOOGLE)}if(!O){const v=ye(R)??_.C_TRANSLATION_FAILED_ERROR,w=Ho(R);
4251T(v,y,w);return}}try{return dh(_.C_TRANSLATION_FAILED_ERROR,{engine:l.engine}),await x(HF(u,S,e,t,o,r,n,{engine:O},i,s))}catch(R){const y=ye(R)??_.C_TRANSLATION_FAILED_ERROR,v="Error occurred during fallback translate : "+P(R),w=Ho(R);T(y,v,w)}},HF=(e,t,o,r,n,a,i,s,x,c)=>async l=>{let d=!1;const u=c===void 0||c!==a,p=x===void 0&&!u,f=k2(e),E=f?CT(e):"",T=u?"initial":p?"selected":"auto",O=rt(e),{globalCaptionStyle:S}=O;l(Gd(!0));const R=h("translate.ts"),y=0,v=t.map(oe=>Hn(oe,Ar(n),y)),w=[];t.forEach((oe,re)=>{oe.translationModified.result===!0&&w.push(re)}),R.info("translationModified index:"+JSON.stringify(w));const N=Fm(n)&&Fm(a);let M=w2e(r);if(x!==void 0&&N){const oe=Math.min(Math.max(...r)+x,t.length-1),re=b2e(M,x,oe).map((ge,fe)=>{const ve=M[fe];return Cw(ge,w).length>0?(R.info("Intersection "+JSON.stringify(ge)+" between "+JSON.stringify(w)+" so original."),ve):ge});re.length===M.length&&(R.info("apply padded group indices.."),M=re)}const k=M.map(oe=>oe.map(re=>v[re])),F=k.flat().join("").length;if(await H3(F)){l(Gd(!1));return}const G=A("translation.merge_clause_stage"),B=A("translation.translate_stage"),W=A("translation.split_sentence_stage"),Q=k.reduce((oe,re)=>oe+re.length,0),j=3,$=j*Q;let q=0;const H=m0(NO(0,0,"")),U=()=>{l(Gd(!1)),d=!0,Ake(),H.asClosable(3e3,{type:"info",render:A("translation.translate_cancel")})};c!==void 0&&c===a&&vye();const ne=oe=>{if(d)return;q+=oe;const re=q/$,ge=x!==void 0,fe=NO(re,r.length,re<.33?G:re<.66?B:W,U,ge);H.message(fe)};try{const oe=Y(),re=x!==void 0,ge=NO(0,r.length,G,U,re);H.message(ge);let fe=0,ve=0,yt=[],Le=r;const We=[];if(N){const bt=[];h("translate.ts").info("Translation target groups: "+k.length);const Jt=[];for(let Ft=0;Ft<k.length&&!d;Ft++){const Pe=k[Ft],_t=await U3(Pe,n);bt.push(_t),ve+=_t.length,ne(Pe.length);const No=await Uu(_t.map(ln=>ln.text),s,n,a,T,E,Ft);No.forEach(ln=>{ln.sid!==void 0&&We.push(ln.sid)}),fe+=No.reduce((ln,Qo)=>ln+Qo.numInconsistentLangSentence,0);const ko=No.map(ln=>ln.translations).flat(),dt=ko.map((ln,Qo)=>({text:ln,numClause:_t[Qo].numClause})),vr=await km(dt,a);ne(Pe.length),h("translate.ts").info("group "+Ft+" translation done."),Jt[Ft]=vr}if(l(Gd(!1)),x!==void 0){const{paddedTargetIndices:Ft,paddedTranslatedCaptions:Pe}=U2e(r,M,Jt,bt);yt=Pe,Le=Ft}else yt=Jt.flat()}else{const bt=k.flat(),Jt=await Uu(bt,s,n,a,T,E);Jt.forEach(Ft=>{Ft.sid!==void 0&&We.push(Ft.sid)}),ve=Jt.reduce((Ft,Pe)=>Ft+Pe.translations.length,0),fe=Jt.reduce((Ft,Pe)=>Ft+Pe.numInconsistentLangSentence,0),yt=Jt.map(Ft=>Ft.translations.map(Pe=>({text:Pe}))).flat(),l(Gd(!1))}if(d)return;if(await G3(E,We),await be().fetchUserInfo(),He(e).length!==t.length){Rke("clips_count_changed"),H.dismiss(),oe.warn(A("error.translation_clips_count_changed"));return}H.asClosable(3e3,{type:"success",render:A("translation.done")}),R.info("result target clip Indices: "+JSON.stringify(Le)),u?vke(r.length,ve,fe,n+"_"+a,s,i):p?Nke(r.length,ve,fe,Le.length,i):wke(r.length,ve,fe,Le.length,i);const kt=is(Le);if(l({type:jG.TRANSLATE,payload:{selectedClipChunks:kt,sourceLanguage:n,targetLanguage:a,translatedCaptions:yt.map(bt=>({text:wt().fromText(bt.text,S.quillStyle)})),translateEngineInfo:s,captionIndex:Ke.TRANSLATE,sceneIndex:o,firstTranslation:u}}),l($u(Sf.SHOW_ALL)),c===a){const bt=[];for(let Jt=0;Jt<Le.length;Jt++)bt.push({globalClipIndex:Le[Jt],start:0,end:yt[Jt].text.length,type:L5.RETRANSLATE,captionIndex:Ke.TRANSLATE});l(d1e(bt))}}finally{l(Gd(!1)),H.dismiss()}},zB=e=>{const t=ZI(e);return t===void 0||t.badge==="Deprecated"||t.badge==="Disabled"},PKe=(e,t)=>A(e,{speaker:sx(t.name,t.provider)}),bKe=e=>{const t=e===Oe.KT?"tts.deprecated_speaker_notice_link_kt":"tts.deprecated_speaker_notice_link_default",o=A(t);return o!==t?o:""},LKe=(e,t)=>{const o=PKe(e,t),r=bKe(t.provider);return""+o+r},MKe=(e,t)=>{if(h("ttsDeprecateUtil.ts").warn("Last used speaker is deprecated. "+JSON.stringify(e)+" on "+t),e.provider===Oe.UserTTS){Y().message(A("tts.deprecated_user_speaker_title"),$e().getUserTTSSpeakers()===void 0?A("tts.deprecated_user_speaker_modal_error"):p0(A("tts.deprecated_user_speaker_modal",{speaker:sx(e.name,e.provider)})));return}if(t==="create"){if(nDe(e),ir().get(Wt.WEMAKEVOICE_WARNING_SHOWN))return;ir().set(Wt.WEMAKEVOICE_WARNING_SHOWN,{warningShown:!0})}const o=ZI(e)===void 0;
4251Y().message(A("tts.deprecated_title"),jt.createElement("div",{onClickCapture:r=>{const n=r.target,a=n.href;a&&window.open(a),r.preventDefault()}},p0(LKe(o?"tts.disabled_speaker_modal":"tts.deprecated_speaker_modal",e)))),t==="init"&&o&&po(ke.LAST_TTS_SETTING,{})};var La=(e=>(e.DOCS="DOCS",e.IMAGES="IMAGES",e.TTV="TTV",e.SUMMARY="SUMMARY",e.ATV="ATV",e))(La||{});const yE=(e,t)=>{const o={success:t.onSuccess,error:t.onError,cancel:t.onCancel}[e];o?.()},YB=(e,t,o)=>{if(o.length===0)return{words:e,scriptCharStartByWordId:t};const r=new Map(o.map((s,x)=>[s.charRange.start,{token:s,idx:x}]));let n=0;const a=new Map;return{words:e.map(s=>{if(s.type!==Z.NORMAL)return s;const x=t.get(s.id);if(x!==void 0){a.set(s.id,x);const l=r.get(x);return l!==void 0&&(n=l.idx+1),l?.token.pronunciation!==void 0?{...s,pronunciation:l.token.pronunciation}:s}if(n>=o.length)return s;const c=o[n];return n+=1,a.set(s.id,c.charRange.start),{...s,pronunciation:c.pronunciation??s.pronunciation}}),scriptCharStartByWordId:a}},DKe=(e,t,o)=>YB(e,t,o.flatMap(r=>r.tokens)),BB=(e,t,o)=>{const r=o.map(()=>[]);let n=0;return e.forEach(a=>{const i=t.get(a.id);if(a.type===Z.NORMAL&&i!==void 0){const s=o.findIndex(x=>i>=x.charRange.start&&i<x.charRange.end);s>=0&&(n=s)}r[n].push(a)}),r.map((a,i)=>{const s=i===o.length-1,x=s?a:[...a];return s||Dx(x,{preserveEmptyWords:!0}),x})},kKe=(e,t,o,r,n)=>{if(r.length===0||n.length===0)return[{...e,words:[...t]}];if(r.length===1){const[i]=r;return[{...e,clipId:n[0],words:[...t],captions:Xl(i.text)}]}return BB(t,o,r).map((i,s)=>({...e,clipId:n[s],words:i,captions:Xl(r[s].text)}))},FKe=(e,t,o)=>{const r=x=>{for(const[c,l]of o)if(l.some(d=>x>=d.start&&x<d.end))return c},n=new Map;let a,i=Number.POSITIVE_INFINITY;for(const[x,c]of o){n.set(x,[]);const l=Math.min(...c.map(d=>d.start));l<i&&(a=x,i=l)}let s=a;return e.forEach(x=>{if(x.type===Z.NORMAL){const l=t.get(x.id);if(l===void 0){s=void 0;return}const d=r(l);if(d===void 0){s=void 0;return}s=d}else if(x.type===Z.ENTER||x.type===Z.SPACER)return;if(s===void 0)return;const c=n.get(s);c!==void 0&&c.push({...x,assetIds:[]})}),n};class KB{}class ib extends KB{_entry;static async _toTTSAssetResult(t,o){const r=ue(await Yw(t.blob),2),n={trackId:Rt(),type:o===Ge.EFFECT?ze.TTSEffect:ze.TTSDubbing,mediaId:t.mediaId,volume:1,fade:{in:!1,out:!1},loop:!1,playbackRate:ur(1),ttsFileInfo:{duration:r,errorInfo:t.errorInfo,text:t.requestProp.text,speaker:t.requestProp.speaker,volume:t.requestProp.volume,speed:t.requestProp.speed,pitch:t.requestProp.pitch,emotion:t.requestProp.emotion,emotionIntensity:t.requestProp.emotionIntensity,acting:t.requestProp.acting,effect:t.requestProp.effect,version:t.requestProp.version},sourceIn:pe(0),sourceOut:pe(r)},a={type:"AVMedia",mediaId:t.mediaId,sourceOrigin:tt.VREW_RESOURCE,videoAudioMetaInfo:{duration:r,audioInfo:{sampleRate:e_,codec:Gt.MP3},videoInfo:void 0},fileLocation:D.IN_MEMORY,name:t.requestProp.text.processed.slice(0,20)+"."+Hh,fileSize:t.blob.size,sourceType:o===Ge.EFFECT?de.TTS_EFFECT:de.TTS_DUBBING};return{ttsBlob:t.blob,ttsModel:n,audioInfo:a}}constructor(t){super(),this._entry=t}async process(t){return await ib._toTTSAssetResult(this._entry,t)}}class ua extends KB{data;constructor(t){super(),this.data=t}static async _toGeneratedTTSAudio(t){const o=ue(await Yw(t.blob),2),r={duration:o,errorInfo:t.errorInfo,text:t.requestProp.text,speaker:t.requestProp.speaker,volume:t.requestProp.volume,speed:t.requestProp.speed,pitch:t.requestProp.pitch,emotion:t.requestProp.emotion,emotionIntensity:t.requestProp.emotionIntensity,acting:t.requestProp.acting,effect:t.requestProp.effect,version:t.requestProp.version},n={type:"AVMedia",mediaId:t.mediaId,sourceOrigin:tt.VREW_RESOURCE,videoAudioMetaInfo:{duration:o,audioInfo:{sampleRate:e_,codec:Gt.MP3},videoInfo:void 0},fileLocation:D.IN_MEMORY,name:t.requestProp.text.processed.slice(0,20)+"."+Hh,fileSize:t.blob.size,sourceType:de.TTS};return{ttsBlob:t.blob,ttsFileInfo:r,audioInfo:n}}async process(){const t=await ua._toGeneratedTTSAudio(this.data.entry),o=ua._toWord(t,this.data.entry.options),{words:r,scriptCharStartByWordId:n}=ua._getDividedWords({word:o,entry:this.data.entry}),a=ua._toGlobalClipWithoutSceneId(t,this.data.clipId,[...r]),i=ua._remapScriptCharStartsToClipWords(r,a.words,n);return{globalClip:a,result:t,scriptCharStartByWordId:i}}static _remapScriptCharStartsToClipWords(t,o,r){const n=new Map;return t.forEach((a,i)=>{const s=o[i],x=r.get(a.id);s!==void 0&&x!==void 0&&n.set(s.id,x)}),n}static _getDividedWords(t){const{entry:o,word:r}=t;try{if(o.timestamps===void 0)throw new Error("timestamps is undefined");return o.timestamps.length===0?{words:[r],scriptCharStartByWordId:new Map}:ua._applyTimestamp(o.timestamps,r,o.requestProp.text.textAspectLang,o.options,o.timestampCharStarts,o.timestampPronunciations)}catch(n){return h("ttsProcessor.ts").error("error during applying Fa Result: "+P
4251(n)),{words:[r],scriptCharStartByWordId:new Map}}}static _toWord(t,o){const r=t.ttsFileInfo.text.processed,n=this._getWordText(t.ttsFileInfo.text.raw,o);return{...ym(t.ttsFileInfo.duration),text:n,type:Z.NORMAL,pronunciation:n===r?void 0:r}}static _applyTimestamp(t,o,r,n,a,i){const s=h("ttsProcessor.ts"),x=.5,c=t.flatMap((S,R,y)=>{const v=[S[0],R===0?0:S[1],S[2]],w=a?.[R],N=i?.[R],M=v[2],k=y[R+1]?y[R+1][1]:o.timelineStart+sr(o);return k-M>=x?[{ts:v,charStart:w,pronunciation:N},{ts:["",M,k],charStart:void 0,pronunciation:void 0}]:[{ts:[v[0],v[1],k],charStart:w,pronunciation:N}]}),l=c.map(S=>S.ts),d=c.map(S=>S.charStart),u=c.map(S=>S.pronunciation),p=n?.preprocess?.replaceRules,f=p?.length&&o.pronunciation&&o.text!==o.pronunciation&&ua._getReplacedText(o.text,n)===o.pronunciation,E=f?ua._alignFaWordsToOriginalText(o.text,o.pronunciation,p,l,r,d).map(([S,R,y])=>[S,R,y,void 0]):l.map((S,R)=>[S,S[0],d[R],u[R]]),T=[],O=new Map;return E.forEach(([S,R,y,v])=>{const w=ue(S[1],2),N=ue(S[2],2);let M=ue(N-w,2);M<0&&(s.error("duration is minus. faResult: "+JSON.stringify(t)+", targetWord: "+JSON.stringify(o)),M=0);const k=!!R?.length,F={...ym(M),assetIds:o.assetIds,text:R,type:k?Z.NORMAL:Z.SILENT,originalStartTime:w,pronunciation:v??(S[0]===R?void 0:S[0])};T.push(F),k&&y!==void 0&&O.set(F.id,y)}),{words:T,scriptCharStartByWordId:O}}static _getWordText(t,o){return new Um({...o?.preprocess,replaceRules:void 0}).preprocessInputText(t)}static _getReplacedText(t,o){return new Um({...o?.preprocess}).applyInputReplaceRules(t)}static _toGlobalClipWithoutSceneId=(t,o,r)=>{const n={...yg(r),id:o,captions:Xl(t.ttsFileInfo.text.raw),captionMode:ar.MANUAL},{sceneId:a,...i}=Ww(n,"");return i};static _alignFaWordsToOriginalText(t,o,r,n,a,i){const s=ua._createAlignedFaWordMappings(t,o,r,n.map(d=>d[0])),x=D0(a),c=Ar(x)?" ":"";return s.map(({originalTextRange:d,faWordsRange:u})=>{const[p,f]=u,E=[n.slice(p,f).map(([R])=>R).join(c),n[p][1],n[f-1][2]];if(d==="silent")return[E,"",void 0];if(d==="unmatched")return[E,E[0],void 0];const[T,O]=d,S=t.substring(T,O);return[E,S,i?.[p]]})}static _createAlignedFaWordMappings(t,o,r,n){const a=ua._buildFaWordToReplacedMap(n,o),i=ua._buildReplacedToOriginalMap(t,r),s=(x,c,l)=>{if(typeof c=="string")return x.push({originalTextRange:c,faWordsRange:[l,l+1]}),x;const d=x.at(-1),[u,p]=c,f=d?.originalTextRange;return d&&Array.isArray(f)&&u<f[1]?(f[1]=p,d.faWordsRange[1]=l+1):x.push({originalTextRange:[u,p],faWordsRange:[l,l+1]}),x};return n.map((x,c)=>{const l=a[c];if(!Array.isArray(l))return l==="silent"?"silent":"unmatched";const[d,u]=l,p=i.slice(d,u),f=p[0],E=p[p.length-1];return!f||!E?"unmatched":[f[0],E[1]]}).reduce(s,[])}static _removeSpaces(t){return t.split("").reduce((o,r,n)=>(/\s/.test(r)||(o.compacted+=r,o.indices.push(n)),o),{compacted:"",indices:[]})}static _buildFaWordToReplacedMap(t,o){const{compacted:r,indices:n}=ua._removeSpaces(o);return t.reduce(([a,i],s,x)=>{const c=ua._removeSpaces(s).compacted;if(c.length===0)return i[x]="silent",[a,i];const d=r.indexOf(c,a);if(d<0)return i[x]="unmatched",h("ttsProcessor.ts").warn("TTSClipProcessor.getFaWordInputTextInfos: faWord not found. "+JSON.stringify({word:s,offset:a,replaced:o})),[a,i];const u=d+c.length;return i[x]=[n[d],n[u-1]+1],[u,i]},[0,[]])[1]}static _buildReplacedToOriginalMap(t,o){let r=0;const n=[];for(;r<t.length;){const a=r,i=o.findIndex(({from:x})=>{const c=a,l=a+x.length;return t.substring(c,l)===x&&!uv(t,c,l)}),s=i<0?null:o[i];s?(rn.times(s.to.length,()=>{n.push([a,a+s.from.length])}),r+=s.from.length):(n.push([r,r+1]),r++)}return n}}const XB=e=>{const[t,...o]=e.captionLinePlans;return t===void 0?[e.text.trim()||e.text]:[t.text.trim(),...o.map(r=>r.text.trim())]},Vyt=(e,t)=>t==="occasional"?e.map(o=>o.text):e.flatMap(XB);var UKe=(e=>(e.UPLOAD="upload",e.SELECT_METHOD="select_method",e.LOADING="loading",e.INPUT_SCRIPT="input_script",e.BLANK_OR_TTS="blank_or_tts",e.CREATE_PROJECT="create_project",e))(UKe||{}),VKe=(e=>(e.SLIDE_VIEW="slide_view",e.LIST_VIEW="list_view",e))(VKe||{}),og=(e=>(e.NORMAL="normal",e.HIGH="high",e))(og||{});const GKe="3.4.120",WKe=3e4,HKe=/(?<!\.[a-zA-Z])[.!?。.。!?…][)\]}>"'’”»›》〉⟩〕〛〙〗)]}】」』]*\s*$/,jKe=e=>{const t=e.split(`
4252`),o=[];let r=[];const n=()=>{r.length&&(o.push(r.join(" ")),r=[])};for(const a of t){const i=a.trim();if(!i){n();continue}r.push(i),HKe.test(i)&&n()}return n(),o.join(`
4253`)},Gyt=3e4,Wyt=async(e,t,o={})=>{try{const r=document.createElement("canvas"),n=r.getContext("2d",{willReadFrequently:!0});if(!n)return;Jb.GlobalWorkerOptions.workerSrc=new URL("/try/assets/pdf.worker.min-DFOQrV6Q.js",import.meta.url).toString();const a=URL.createObjectURL(t.blob);let i;try{i=await Jb.getDocument({url:a,fontExtraProperties:!0,cMapUrl:"https://cdn.jsdelivr.net/npm/pdfjs-dist@"+GKe+"/cmaps/",cMapPacked:!0}).promise}catch(c){const l=l9(c)??"";if(l==="PasswordException"){ite(Na.DECRYPT_DOCS_PW,A("docs_import.decrypt_docs_pw"));return}else throw l==="InvalidPDFException"?(h("docsImport.ts").error("Import "+t.name+" failed : "+P(c)),new C(_.C_INVA
4253LID_PDF_ERROR)):(h("docsImport.ts").error("Import "+t.name+" failed : "+P(c)),new C(_.C_PDF_IMPORT_ERROR))}const s=Array(i.numPages).fill(0).map((c,l)=>l+1),x=[];for(const c of s){const l=await i.getPage(c),d=l.getViewport({scale:YKe(e)});r.height=d.height,r.width=d.width;const u={canvasContext:n,viewport:d};await Promise.race([l.render(u).promise,zKe(WKe,_.C_PDF_RENDER_TIMEOUT)]);const p=await l.getTextContent(),f=await new Promise((y,v)=>{r.toBlob(w=>{w?y(w):v()},"image/jpeg",.92)}),E=r.toDataURL("image/jpeg",.92).replace(/^data:image\/[a-z]+;base64,/,""),T=t.name+"_"+c+"_"+Cn(6)+".jpeg",O=p.items.map(y=>{const v=y;return v.hasEOL?v.str?v.str+`
4254`:`
4255
4256`:v.str||" "}).join("").trim(),S=jKe(O);x.push({imgBlob:f,imageId:T,dataURL:E,text:BKe([S])[0],width:r.width,height:r.height});const R=Math.round(c/s.length*100)/100;o.onProgress?.(R)}return URL.revokeObjectURL(a),x}catch(r){throw h("docsImport.ts").error(P(r)),Ne(r)?r:new C(_.C_PDF_IMPORT_ERROR)}},zKe=(e,t)=>new Promise((o,r)=>setTimeout(()=>r(new C(t)),e)),YKe=e=>{switch(e){case og.NORMAL:return 3;case og.HIGH:return 5}},BKe=e=>e.map(t=>GG(t).flatMap(tv).join(`
4257`)),Hyt=e=>e.split("/").pop(),jyt=async(e,t,o,r={})=>{try{rUe();const n=await OD(t.map(c=>c.imageId),"PUT");if(!n)throw h("docsImport.ts").error("Failed to get image urls"),new Error("Failed to get upload urls");await Promise.all(t.map(async(c,l)=>{const d=c.imgBlob,u=n[l];return fetch(u,{method:"PUT",body:d}).then(p=>{if(!p.ok)throw h("docsImport.ts").error("Failed to upload image "+c.imageId+" : "+p.statusText),new Error("Failed to upload image");return p})})),h("docsImport.ts").info("Successfully uploaded pdf images");const a=await OD(t.map(c=>c.imageId),"GET");if(!a)throw h("docsImport.ts").error("Failed to get download urls"),new Error("Failed to get download urls");const i=(c,l)=>{let d=c;const u=setInterval(()=>{d<l?(d+=1,r.onProgress?.(d/l)):clearInterval(u)},1500);return u},s=i(0,100),x=await hCe(o,e,a.map((c,l)=>({imageUrl:c,idx:l+1,numTotal:a.length})));return clearInterval(s),h("docsImport.ts").info("Successfully generated descriptions: "+x.reduce((c,l)=>c+l.length,0)+" characters"),nUe(),x}catch(n){throw h("docsImport.ts").error("Failed loading proccess in pdfLoader : "+P(n)),aUe(),Ne(n)?n:new C(_.C_GENERATE_SLIDES_SCRIPT_ERROR)}};class KKe{numSlide=0;startTimeStamp=0;editingTimeStamp=0;numTextLength=0;maxTextLength=0;editedTextLength=0;enterCount=0;isAIVoiceUsed=Mt(ke.DOCS_TTS_TOGGLE);originalTexts=[];isDirty=!1;imgQuality=og.NORMAL;generateCount=0;scriptMethod="ai_script";initialize(){this.numSlide=0,this.startTimeStamp=0,this.editingTimeStamp=0,this.numTextLength=0,this.maxTextLength=0,this.editedTextLength=0,this.enterCount=0,this.isAIVoiceUsed=Mt(ke.DOCS_TTS_TOGGLE),this.originalTexts=[],this.isDirty=!1,this.imgQuality=og.NORMAL,this.generateCount=0,this.scriptMethod="ai_script"}}let HC=null;const XKe=()=>(!HC&&(HC=new KKe),HC),JB=(e,t,o)=>({chunkIdx:t,scriptCharRange:e.scriptCharRange,scriptText:e.text,errorMsg:"",errorType:o}),sb=(e,t,o)=>t.flatMap(r=>{const n=e[r];return n===void 0?[]:[JB(n,r,o)]}),JKe=(e,t,o,r)=>{const n=new Set(t.map(i=>i.chunkIdx)),a=new Map(o.map(i=>[i.chunkIdx,i]));return e.map((i,s)=>{if(n.has(s))return null;const x=a.get(s);return x!==void 0?x:JB(i,s,r)}).filter(i=>i!==null)},qKe=async(e,t,o)=>{try{return await e()}catch(r){if(!t(r))throw r;return o?.(r),e()}},lu=h("ttsChunkTrigger.ts"),QKe=()=>{Mo().getDebugVal(Xt.TTS_RANDOMLY_FAIL);const e=parseFloat("");return isNaN(e)?void 0:e},ZKe=async e=>{const t=qEe({planReqId:e.planReqId,chunkIdxs:e.chunkIdxs,requestType:e.requestType,clientInfo:e.clientInfo,debugChunkFailRate:QKe()}),o=await xj(t,e.signal);lu.info("[TTS batch] make reqId="+o+" planReqId="+e.planReqId+" chunkIdxs="+e.chunkIdxs.join(","));const r=await Bt(cj(o,e.signal).pipe(um(n=>n.result==="success"||n.result==="error")));return r.result==="error"&&lu.error("[TTS batch] error reqId="+o+" planReqId="+e.planReqId+" errorType="+r.errorType+" msg="+(r.msg??"(none)")),{reqId:o,finalResponse:r}},qB=async e=>{const t=e.script,o=Yl().getExpectedPricing({provider:e.speakerInfo.provider,speakerId:e.speakerInfo.speakerId,uid:e.uid}),r=Cn(10);return qKe(async()=>{const a=await lj({requestType:pu.CLIP,idempotencyKey:r,expectedPricing:o,speakerInfo:e.speakerInfo,script:t,linebreakMode:e.linebreakMode,splitAtPunctuation:e.splitAtPunctuation,captionLengthMode:e.captionLengthMode,replaceRulesMap:e.replaceRulesMap},e.signal),i=a.planReqId,{appliedPricing:s}=a;if(s.provider!==e.speakerInfo.provider||s.speakerId!==e.speakerInfo.speakerId)throw new Yr("unknown","TTS plan applied pricing speaker mismatch: requested="+e.speakerInfo.provider+"/"+e.speakerInfo.speakerId+", applied="+s.provider+"/"+s.speakerId);Yl().shouldRefreshForAppliedPricing(s,o,e.uid)&&Yl().refresh({force:!0}),lu.info("[TTS plan] request start: planReqId="+i+" speaker="+e.speakerInfo.speakerId+" lang="+e.speakerInfo.lang+" chars="+t.length+" linebreakMode="+(e.linebreakMode??"default"));
4257const x=await Bt(dj(i,e.signal).pipe(er(c=>{e.onProgress&&"progress"in c&&c.progress&&e.onProgress(c.progress)}),um(c=>c.result==="success"||c.result==="error")));if(x.result==="error")throw lu.error("[TTS plan] error: planReqId="+i+" errorType="+x.errorType+" msg="+(x.msg??"(none)")),new Yr(x.errorType,x.msg??"unknown");return lu.info("[TTS plan] success: planReqId="+i+" chunks="+x.chunkCount+" sentences="+x.sentenceCount+" model="+x.modelUsed+" latencyMs="+x.latencyMs),{planReqId:x.planReqId,chunks:x.chunks,appliedPricing:s}},a=>a instanceof Yr&&a.errorType==="timeout",a=>{lu.warn("[TTS plan] attempt 1/2 timed out, retrying: "+P(a))})},$Ke=e=>!e||typeof e!="object"?!1:"result"in e&&e.result==="not_deducted"?"reason"in e&&(e.reason==="free"||e.reason==="anonymous"||e.reason==="billing_error"):"result"in e&&e.result==="deducted"?"deductedCreditUnits"in e&&typeof e.deductedCreditUnits=="number"&&Number.isSafeInteger(e.deductedCreditUnits)&&e.deductedCreditUnits>=0:!1,jC=h("fetchChunkBatch.ts"),xb=async(e,t)=>{try{const{reqId:o,finalResponse:r}=await ZKe({planReqId:t.planReqId,chunkIdxs:e,uid:t.uid,clientInfo:t.clientInfo,requestType:pu.CLIP,signal:t.signal});if(r.result==="success"){if(r.requestType!==pu.CLIP)throw new Yr("unknown","Expected a CLIP response");const n=r,a=r.creditDeduction;return $Ke(a)?{kind:"success",reqId:o,response:n,creditDeduction:a}:(jC.error(t.warnLabel+" ["+e.join(",")+"] returned malformed TTS credit deduction"),{kind:"success",reqId:o,response:n})}return r.result==="error"?{kind:"error",errorType:r.errorType}:{kind:"unresolved"}}catch(o){const r=t.warnLabel+" ["+e.join(",")+"] threw: "+P(o);t.signal?.aborted?jC.info(r):jC.warn(r);const n=Km(o);return n===void 0?{kind:"unresolved"}:{kind:"error",errorType:n}}},eXe=e=>{const t=[],o=[],r=[];return e.forEach(n=>n.tokens.forEach(a=>{t.push([a.text,a.startSec,a.startSec+a.durationSec]),o.push(a.charRange.start),r.push(a.pronunciation)})),{timestamps:t,charStarts:o,pronunciations:r}},tXe=(e,t,o)=>{const r={...o.voiceSetting,text:o.ttsString},{timestamps:n,charStarts:a,pronunciations:i}=eXe(e.captionLines);return{mediaId:dy.v4(),blob:t,requestProp:r,timestamps:n,timestampCharStarts:a,timestampPronunciations:i,options:o.options}},QB=async(e,t,o,r,n)=>{const a=l=>(n?.throwIfAborted(),l()),i=await a(()=>fj(e.audio,n)),s=await a(()=>uj(tXe(e,i,t))),x=await a(()=>new ua({entry:s,clipId:o}).process()),c=await a(()=>pj(x,r));return n?.throwIfAborted(),{pair:x,audioInfo:c}},_S={CLICK_SHOW_TYPE:"click_show_type",VIEW_SHOW_TYPE:"view_show_type",AI_SEARCH_VOICE_SUBMIT:"ai_search_voice_submit",AI_SEARCH_VOICE_FAILED:"ai_search_voice_failed"},oXe=e=>{I().event(m.TTS_MODAL,g.TTS_OPEN,void 0,void 0,JSON.stringify({entryPoint:e}))},zyt=()=>{I().event(m.TTS_MODAL,g.CLICK_SEARCH)},Yyt=()=>{I().event(m.TTS_MODAL,_S.AI_SEARCH_VOICE_SUBMIT)},Byt=()=>{I().event(m.TTS_MODAL,_S.AI_SEARCH_VOICE_FAILED)},Kyt=e=>{I().event(m.ANONYMOUS_EVENT,g.AI_SEARCH_VOICE_PICK,void 0,void 0,JSON.stringify(e))},Xyt=e=>{I().event(m.TTS_MODAL,_S.CLICK_SHOW_TYPE,e)},Jyt=(e,t)=>{I().event(m.TTS_MODAL,_S.VIEW_SHOW_TYPE,e,void 0,JSON.stringify({showTypeEntrySource:t}))},qyt=(e,t,o)=>I().event(m.AI_VOICE,g.SELECT,void 0,void 0,JSON.stringify({from:e,selectedType:t,selectedFilterName:o}));var Hp=(e=>(e.EMPTY_INPUT="EMPTY_INPUT",e.SAME_INPUT="SAME_INPUT",e.ALREADY_PROCESSING="ALREADY_PROCESSING",e.TOO_LONG_WORD="TOO_LONG_WORD",e.TOO_LONG_PRONUNCIATION="TOO_LONG_PRONUNCIATION",e.CREATE_DUPLICATED_WORD="CREATE_DUPLICATED_WORD",e.GENERAL_ERROR="GENERAL_ERROR",e))(Hp||{});class kx extends Error{_type;constructor(t){switch(super(),t){case"authorization":case"bad-request":case"not-found":case"unknown":this._type="GENERAL_ERROR";return;case"duplicated":this._type="CREATE_DUPLICATED_WORD";return}this._type=t}get type(){return this._type}}const rXe=async()=>{if(!await wo())return h("vocalDictionary.ts").warn("Failed to init vocal dictionary list. idToken is null."),[];const e=await Pn("/get-vocal-dictionary-list",{method:"POST",body:JSON.stringify({})}).then(t=>me(t,_.C_TTS_NETWORK_ERROR));if(e.result!=="success")throw new kx(e.errorType);if(e.list===void 0)throw new kx("unknown");return e.list},nXe=async e=>{if(!await wo())throw new kx("authorization");const t=await Pn("/create-vocal-dictionary-item",{method:"POST",body:JSON.stringify(e)}).then(o=>
4257me(o,_.C_TTS_NETWORK_ERROR));if(t.result!=="success")throw new kx(t.errorType);if(t.itemId===void 0)throw new kx("unknown");return t.itemId},aXe=async e=>{if(!await wo())throw new kx("authorization");const t=await Pn("/update-vocal-dictionary-item",{method:"POST",body:JSON.stringify(e)}).then(o=>me(o,_.C_TTS_NETWORK_ERROR));if(t.result!=="success")throw new kx(t.errorType)},iXe=async e=>{if(!await wo())throw new kx("authorization");const t=await Pn("/delete-vocal-dictionary-item",{method:"POST",body:JSON.stringify({itemId:e})}).then(o=>me(o,_.C_TTS_NETWORK_ERROR));if(t.result!=="success")throw new kx(t.errorType)};class Th{static _inst=new Th;_dictionary;_promise;constructor(){this._dictionary={[ft.Korean]:{},[ft.English]:{},[ft.Japanese]:{},[ft.Spanish]:{},[ft.Taiwanese]:{},[ft.Chinese]:{}},this._promise=null}static get inst(){return Th._inst}async init(){!this._promise&&(this._promise=new Promise(t=>{this._resetDictionary(),rXe().then(o=>{o.forEach(r=>{this._dictionary[r.lang][r.itemId]=r}),t()}).catch(o=>{const r="Failed to fetch vocal dictionary list. "+P(o);h("vocalDictionary.ts").error(r);const n=_.C_TTS_VOCAL_DICTIONARY_FETCH_ERROR,a=Ot(n,{defaultKey:"error.tts_vocal_dictionary_fetch_error"});Y().error(n,a),t()})})),await this._promise,this._promise=null}async getFetchedList(){return this._promise?(await this._promise,this._toAllList()):this._toAllList()}_resetDictionary(){this._dictionary[ft.Korean]={},this._dictionary[ft.English]={},this._dictionary[ft.Japanese]={},this._dictionary[ft.Spanish]={},this._dictionary[ft.Taiwanese]={},this._dictionary[ft.Chinese]={}}get(t){for(const o of Eo(ft).values())if(this._dictionary[o][t])return this._dictionary[o][t]}async add(t){try{const o=await nXe(t),r={...t,itemId:o};return this._dictionary[t.lang][o]=r,r}catch(o){const r="Failed to add item with word: "+t.word+". "+P(o);return h("vocalDictionary.ts").error(r),void 0}}async update(t){try{return await aXe(t),this._dictionary[t.lang][t.itemId]=t,t}catch{const r="Failed to update item with itemId: "+t.itemId;return h("vocalDictionary.ts").error(r),void 0}}async remove({itemId:t}){try{const o=this.get(t);return o===void 0?void 0:(delete this._dictionary[o?.lang][t],await iXe(t),o)}catch{const r="Failed to remove item with itemId: "+t;return h("vocalDictionary.ts").error(r),void 0}}get replaceRulesMap(){return t5(Eo(ft).getValues().map(t=>[t,this._toLangFilteredList(t).map(o=>this._toReplaceRules(o)).flat()]))}_toAllList(){return Object.values(this._dictionary).flatMap(t=>Object.values(t))}_toLangFilteredList(t){return Object.values(this._dictionary[t])}_toReplaceRules(t){const o={from:t.word,to:t.pronunciation},r=[o],n=XA(o.from);n!==o.from&&r.push({from:n,to:o.to});const a=sXe(o.from);return a!==o.from&&r.push({from:a,to:o.to}),r}}const ZB=()=>Th.inst,XA=e=>Cc.codeToString(Cc.toHankakuSpace(Cc.toHankanaCase(Cc.stringToCode(e)))),sXe=e=>Cc.codeToString(Cc.toZenkakuSpace(Cc.toZenkanaCase(Cc.stringToCode(e)))),$B=(e,t,o,r)=>o.items.filter(n=>{if(t!==n.lang)return!1;const a=XA(n.word),i=XA(e),s=i.includes(a);switch(o.variant){case"create":return s;case"read":case"delete":case"update":return s&&r;default:return!1}}),xXe=(e,t,o)=>{const r=e.globalClips,n=e.trackEntries,a=e.assetEntries,{from:i,to:s}=o,x=r.slice(i,s);return Array.from(new Li(void 0,void 0,n,a).collectFrom({type:Or.GLOBAL_CLIP,model:x}).build().getUsedSubAssetIds()).map(l=>{const d=L.get(a,l);if(!d)return null;const u=d.trackIds.map(S=>L.get(n,S)).find(S=>S!==void 0&&s2(S));if(!u)return null;const{text:p,speaker:f}=u.ttsFileInfo,E=p.processed!==oT(p.raw),T=$B(p.raw,f.lang,t,E);return{item:[l,u.type],appliedItems:T}}).filter(ri).filter(({appliedItems:l})=>l.length>0)},cXe=(e,t,o)=>{const{from:r,to:n}=o;return e.globalClips.slice(r,n).map(i=>{const s=jg(i,e.trackEntries,e.assetEntries,e.ttsClipInfosMap),x=s?L.get(e.ttsClipInfosMap,s):null;if(!x)return;const c=Mw(i),l=i.words.some(u=>u.pronunciation!==void 0),d=$B(c,x.speaker.lang,t,l);return d.length>0?{item:i,appliedItems:d}:void 0}).filter(Se)},Qyt=(e,t,o)=>{const r=cXe(e,t,o),n=xXe(e,t,o);return{ttsClipsToUpdate:r.map(({item:a})=>a),ttsAssetsToUpdate:n.map(({item:a})=>a),appliedItems:rn.uniqBy([...r,...n].flatMap(({appliedItems:a})=>a),"itemId")}},jF=32,Zyt=(e,t)=>
4257!e||!t?Hp.EMPTY_INPUT:e.length>jF?Hp.TOO_LONG_WORD:t.length>jF?Hp.TOO_LONG_PRONUNCIATION:e===t?Hp.SAME_INPUT:null,$yt=(e,t)=>{Y().openModal(st.VOCAL_DICT_EDIT,e),I().event(m.VOCAL_DICTIONARY,g.OPEN_MODAL,void 0,void 0,JSON.stringify(t))},evt=e=>{Y().closeModal(st.VOCAL_DICT_EDIT),I().event(m.VOCAL_DICTIONARY,g.CLOSE_MODAL,void 0,void 0,JSON.stringify({trigger:e}))},lXe={enable:Mt(ke.VOCAL_DICTIONARY_ENABLED)},eK=In({name:"vocalDictionary",initialState:lXe,reducers:{setEnable:(e,t)=>{e.enable=t.payload}}}),tvt=eK.reducer,dXe=e=>Ov(e).vocalDictionary,cb=e=>dXe(e).enable,ovt=e=>(t,o)=>{e!==cb(o())&&(t(eK.actions.setEnable(e)),QUe(e))};var $l=(e=>(e.NO_TEXT="NO_TEXT",e.INVALID_TEXT="INVALID_TEXT",e.NO_CLIPS_DELIVERED="NO_CLIPS_DELIVERED",e))($l||{});const uXe=()=>e=>e.pipe(St(t=>t.contents.length!==0?Tt(t):ta(()=>{throw t.silent||i0(A("tts.error_text_input_none")),new Error("NO_TEXT")}))),pXe=e=>{const t=new Um(e.options?.preprocess),o=e.voiceSetting.speaker.lang,r=zt(t.processInput(e.contents,o)).pipe(St(n=>n.length!==0?Tt(n):ta(()=>
4257{throw e.silent||i0(A("tts.error_text_invalid")),new Error("INVALID_TEXT")})));return Bt(r)},rg=(e,t,o,r)=>({shouldRenderAsTTSClip:e.shouldRenderAsTTSClip,status:e.status,type:e.type,voiceSetting:e.voiceSetting,options:e.options,silent:e.silent,clipId:o,ttsString:t,variant:r,errorInfo:e.errorInfo}),fXe=e=>{const t=Tt(e).pipe(uXe(),St(o=>pXe(o)),Fa(),At((o,r)=>rg(e,o,r===0?e.clipId:ct(),r!==0||Gm(e)?"INSERT":"MODIFY")),aa());return Bt(t)},gXe=(e,t,o,r,n)=>{const a=Tt({state:e,handlers:t,user:o}),i=a.pipe(St(({state:s,handlers:x,user:c})=>{const l={type:Sc.CLIP,ttsString:s.ttsString,handlers:x,voiceSetting:s.voiceSetting,options:s.options,uid:c.uid,userReqId:r,signal:n};return zt(Vl.getInstance().getTTSEntry(l)).pipe(Ma(d=>d.errorInfo?Tt(d):new Bi(d).process()),At(d=>({entry:d,clipId:s.clipId})),St(d=>new ua(d).process()))}),pJ(()=>{throw h("ttsClip.ts").error("requestTTSClip: empty result. contents: "+JSON.stringify(e)),new C(_.C_TTS_GENERAL_ERROR)}));return Bt(i)},tK=(e,t)=>async o=>{const r=t.find(i=>i.clipId===e.clipId);if(!r)throw h("ttsClip.ts").error("extendTTSClips: originalSplittedState is not found. originalState: "+JSON.stringify(e)+", spilttedState: "+JSON.stringify(t)),new C(_.C_LOGIC_ERROR,{},"extendTTSClips: originalSplittedState is not found.");o(_Xe(r.ttsString.processed,e.clipId));const n=t.filter(i=>i.clipId!==e.clipId).map(i=>({...e,clipId:i.clipId,contents:i.ttsString.processed,status:"processing"}));if(!eo(gf)){const i=tP();await o(T0(zg([i.dummyAudioInfo],{[i.dummyAudioInfo.mediaId]:i.dummyAudioBlob})))}o({type:Wo.EXTEND_TTS_CLIP,payload:{targetClipId:e.clipId,appendingTTSStates:n,duration:1}})},oK=e=>t=>{const o={type:Ge.CLIP,variant:"INSERT",status:"idle",contents:"",voiceSetting:us(),options:{preprocess:{maxLineMode:"long",ski
4257pSplitAtPunc:!QI()}},clipId:e,shouldRenderAsTTSClip:!0,errorInfo:void 0};t({type:Wo.SET_TTS_STATE,payload:{type:o.type,states:{[o.clipId]:o}}}),!Ta(It.TTS_INSERTED)&&t(Cl(Ct.TTS_NEW_USER,Fr.TTS_NEW_USER))},rvt=e=>async t=>{try{await $e().initTTSSpeakerList();const o=ct(),r=se().createDummyAudioInfo();await t(T0(zg([r.dummyAudioInfo],{[r.dummyAudioInfo.mediaId]:r.dummyAudioBlob}))),t({type:ot.INSERT_TTS_DUMMY_CLIP,payload:{clipIndex:e+1,duration:r.dummyAudioInfo.videoAudioMetaInfo.duration,newClipIds:[o]}}),t(oK(o))}catch(o){h("ttsClip.ts").error("error in createTTSDummyClip: "+P(o));const r=ye(o)??_.C_TTS_NETWORK_ERROR;Y().error(r,Ot(r,{defaultKey:"error.tts_network_error"}))}},nvt=e=>(t,o)=>{const r=o(),n=zs(r),a=lt(r),i=ht(r),s=Fi(r);if(!(N2(e.words,a,i,s)&&!qd(n,e)))return;const c=wxe(r,e);if(!c)return;const l=Kx(c,s);if(!l)return;const{ttsString:d,voiceSetting:u}=tT(l),p=d.raw?.trim(),f=p&&p.length>0?p:Mw(e),E={type:Ge.CLIP,variant:"INSERT",status:"idle",contents:f,options:{preprocess:{maxLineMode:"long",skipSplitAtPunc:!QI()}},voiceSetting:us(u),clipId:e.id,shouldRenderAsTTSClip:!0,errorInfo:l.errorInfo};t({type:Wo.SET_TTS_STATE,payload:{type:Ge.CLIP,states:{[e.id]:E}}})},avt=e=>(t,o)=>{const r=o(),n=lt(r),a=ht(r),i=Fi(r);N2(e.words,n,a,i)&&(t(rK([e],!0)),t(hze(e.startPosition)))},ivt=(e,t)=>(o,r)=>{const n=r(),a=zs(n),i=lt(n),s=ht(n),x=Fi(n),c=e.filter(l=>N2(l.words,i,s,x)&&L.get(a,l.clipId)===void 0);c.length!==0&&(o(rK(c,!1)),oXe("tts_clip_edit_voice"),g_({type:Ge.CLIP,clipIds:c.map(l=>l.clipId),shouldAbortOnClose:t,preserveOriginalClips:c.length>1}))},rK=(e,t)=>(o,r)=>{const n=r(),a=lt(n),i=ht(n),s=Fi(n),x=z2e(e,a,i,s);if(e.length!==x.length)throw h("ttsClip.ts").error("modifyTTSClips: targetGlobalClips.length !== ttsInfos.length, "+e.length+", "+x.length),new C(_.C_LOGIC_ERROR,{},"modify lengths mismatch");const c=x.map((d,u)=>({info:d,globalClip:e[u]})),l=Object.fromEntries(c.map(d=>{const{voiceSetting:u}=tT(d.info),p={type:Ge.CLIP,variant:"MODIFY",status:"idle",contents:Mw(d.globalClip),options:{preprocess:{maxLineMode:"long",ski
4257pSplitAtPunc:!QI()}},voiceSetting:us(u),clipId:d.globalClip.clipId,shouldRenderAsTTSClip:t,errorInfo:d.info.errorInfo};return[d.globalClip.clipId,p]}));o({type:Wo.SET_TTS_STATE,payload:{type:Ge.CLIP,states:l}})},nK=e=>(t,o)=>{const r=o();if(He(r).length===1){Y().warn(A("transcript.empty_scene_not_allowed"));return}return t({type:Wo.ABORT_TTS_CLIP_INSERT,payload:{clipIds:e}})},svt=e=>t=>t(C_(e)),_Xe=(e,t,o)=>(r,n)=>{const a=n();if(!zs(a))return;const s=mI(a,t);if(!s)return;Jz(s.contents,e,o);const x=vt(s,c=>{c.contents=e});r({type:Wo.SET_TTS_CONTENT,payload:{type:Ge.CLIP,clipId:t,contents:x.contents}})},xvt=(e,t)=>(o,r)=>{const n=r(),a=e.filter(i=>mI(n,i)!==void 0);if(a.length===0){h("ttsClip.ts").error("openTTSClipModal: targetClipIds.length === 0");return}g_({type:Ge.CLIP,clipIds:a,shouldAbortOnClose:t})},C_=(e,t)=>o=>o({type:Wo.SET_TTS_STATE,payload:{type:Ge.CLIP,states:Object.fromEntries(e.map(r=>[r,null])),groupKey:t}}),cvt=()=>(e,t)=>{const o=t(),r=UW(o);if(r.length===0)return;e(yp(r,"processing"));const n={onCancel:()=>{e(yp(r,"error"))},onError:()=>{e(yp(r,"error"))},onRequestStart:()=>{e(yp(r,"processing"))},onSuccess:()=>{e(yp(r,"success"))}},a=cb(o);return e(S6e({type:Ge.CLIP,clipIds:r.map(i=>i.clipId)},n,a?ZB().replaceRulesMap:null,void 0,{preserveOriginalClips:!0}))},lvt=()=>(e,t)=>{const o=t(),r=UW(o),n=He(o).length;if(r.length===n){Y().warn(A("transcript.empty_scene_not_allowed"));return}const i=r.map(s=>s.clipId);if(i.length!==0)return e(nK(i))},ng=Je("tts-batch-dummy-asset-id"),aK=e=>"result"in e,EXe=(e,t,o,r)=>{if(o.length===0)return[{...e,clip:{...e.clip,captions:Xl(r)}}];if(o.length===1){const[a]=o;return[{...e,clip:{...e.clip,captions:Xl(a.text)}}]}return BB(e.clip.words,t,o).map((a,i)=>{const s=o[i];return{clip:{...e.clip,clipId:i===0?e.clip.clipId:ct(),words:a,captions:Xl(s.text)},trackEntries:i===0?e.trackEntries:zn({}),assetEntries:i===0?e.assetEntries:ii({})}})},ES=e=>{const t=e.flat(),o=[],r=zn({}),n=ii({});for(const a of t)o.push(a.clip),Object.assign(r,a.trackEntries),Object.assign(n,a.assetEntries);return{globalClips:o,tracks:r,assets:n}},mS=(e,t=e.globalClip)=>aK(e)?q3(t,e.result.audioInfo.mediaId):{clip:t,trackEntries:zn({}),assetEntries:ii({})},zF=(e,t,o)=>q3({...e,words:[...t]},o),iK=e=>e.contents.map(({text:t})=>({type:Ge.CLIP,status:"idle",variant:"INSERT",contents:t,voiceSetting:e.voiceSetting,options:e.options,silent:!0,clipId:ct(),shouldRenderAsTTSClip:!1,errorInfo:void 0})),mXe=async(e,t,o,r)=>{const n={raw:e.scriptText,processed:e.scriptText,textAspectLang:r},a=rg(t,n,ct(),"INSERT"),i={...a.voiceSetting,text:a.ttsString},s={mediaId:qe.v4(),blob:zm(1),requestProp:i,errorInfo:e.errorType?ju(e.errorType,{aivoice_name:sx(t.voiceSetting.speaker.name,t.voiceSetting.speaker.provider),aivoice_provider:eT(t.voiceSetting.speaker.provider),error_code:CN(e.errorType,t.voiceSetting.speaker.provider)}):{reason:nr.UNKNOWN,msg:"tts.unknown_error"},options:a.options},x=new ua({entry:s,clipId:a.clipId}),c=await x.process();await pj(c,"[ttvPipeline] No audio track for failed-chunk placeholder");const{words:l,...d}=c.globalClip;return{globalClip:{...d,sceneId:o},result:c.result,timestampedWords:{words:l,scriptCharStartByWordId:c.scriptCharStartByWordId}}},YF=(e,t)=>Array(e).fill(0).map(()=>[{globalClip:Ww(Uw(void 0,void 0,5,ct()),t)}]),hXe=(e,t,o,r,n)=>{const a=(()=>{let c=0;return{inc:()=>++c}})(),i=e.contents.filter(c=>c.text.trim().length>0).length;return Tt(e).pipe(er(()=>o.onRequestStart?.()),At(c=>iK(c)),Fa(),St((c,l)=>zt(fXe(c)).pipe(c0(d=>{if(Ne(d))throw d;return pm}),At(d=>({states:d,idx:l})))),V0(({states:c,idx:l})=>zt(c).pipe(V0(d=>gXe(d,o,r,t,n).then(u=>({...u,globalClip:{...u.globalClip,sceneId:e.sceneId}}))),c0(d=>{if(Ne(d))throw d;return pm}),At(d=>({group:d,idx:l})),er(()=>o.onProgress?.(a.inc()/i))))).pipe(At(c=>c.sort((l,d)=>l.idx-d.idx)),Fa(),gJ({idx:-1}),_J(),St(([c,l])=>{const d=YF(l.idx-c.idx-1,e.sceneId);return"group"in l?Tt(...d,l.group):Tt(...d)}),aa(),At(c=>c.concat(YF(e.contents.length-c.length,e.sceneId))))},IXe=e=>e.filter(o=>o.every(aK)).map(o=>o.map(r=>r.result)).flat(),TXe=(e,t="contain",o)=>WK(e.map(({imgBlob:r})=>r),e.map(({width:r})=>r),e.map(({height:r})=>r),o,t),zC=e=>({outcome:"complete",results:e,hasFailures:e.some(t=>t.ttsFileInfo.errorInfo!==void 0)}),SXe=(e,t,o,r={})=>async n=>{switch(e.variant){case La.DOCS:case La.IMAGES:return zC(await n(OXe(e.variant,e,t)));case La.TTV:{const{scriptPlan:a,onClipCountsPerPlanChunk:i}=r;if(!a||!i)throw new C(_.C_LOGIC_ERROR,{},"[ttsBatchPipeline] TTV requires scriptPlan and onClipCountsPerPlanChunk");return n(RXe(e,a,i,t,o))}case La.SUMMARY:return zC(await n(bXe(e,t)));case La.ATV:return zC(await n(yXe(e,t)))}},OXe=(e,t,o)=>async(r,n)=>
4257{const a=e===La.IMAGES,{contents:i,clipDispatchRange:s,videoRatio:x,currentPath:c,fillType:l,useAnimation:d,sceneId:u}=t,{numSlide:p,startTimeStamp:f,numTextLength:E,maxTextLength:T,isDirty:O,isAIVoiceUsed:S,enterCount:R,imgQuality:y,scriptMethod:v,generateCount:w}=XKe(),N=(new Date().getTime()-f)/1e3;!a&&iUe(p,N,E,T,O,S,R,y,v,w);const M=sl(),{clipAndInfos$:k,results$:F,audioLanguage$:G}=TS(t,M,o,n),B=zt(TXe(i,l,cr(x))).pipe(Gh()),W=Tf(k.pipe(Fa()),B.pipe(At(({assetIds:We})=>We),Fa())).pipe(At(([We,kt])=>We.map(bt=>mS(bt,{...bt.globalClip,assetIds:[...bt.globalClip.assetIds,kt]}))),aa()),[Q,j,$,q]=await Bt(fy([B,W,F,G])),H=a?Ls.IMAGES:Ls.DOCS,U=1920,te={width:U,height:U/cr(x)},{globalClips:ne,tracks:oe,assets:re}=ES(j);for(const[We,kt]of Object.entries(Q.assets))L.set(oe,kt.trackId,kt),L.set(re,Je(We),{trackIds:[kt.trackId],role:"sub"});const{files:ge,blobs:fe}=IS($,Q),ve=hS($),yt={dispatchInterface:lb(s,xa(n()),u),globalClips:ne,files:ge,blobs:fe,tracks:oe,assets:re,ttsClipInfosMap:ve,projectProps:{startMedia:H,audioLanguage:q,videoRatio:x,videoSize:te,currentPath:c}},Le=Tt(SS(yt)).pipe(St(We=>zt(r(ip(We))).pipe(At(()=>$),er(()=>{switch(e){case La.DOCS:Y().closeModal(st.IMPORT_DOCS);break;case La.IMAGES:if(d){const kt=We.clips.flatMap(bt=>bt.assetIds);r(PK(kt))}break}}))));return Bt(Le)},CXe=(e,t,o,r,n)=>async(a,i)=>{const{clipDispatchRange:s,videoRatio:x,sceneId:c}=e,l=sl(),{clipAndInfos$:d,results$:u,audioLanguage$:p}=TS(e,l,t,i,n),f=d.pipe(Fa(),At(F=>F.map(G=>mS(G))),aa()),[E,T,O]=await Bt(fy([f,u,p])),{globalClips:S,tracks:R,assets:y}=ES(E),{files:v,blobs:w}=IS(T),N=hS(T),M={dispatchInterface:lb(s,xa(i()),c),globalClips:S,files:v,blobs:w,assets:y,tracks:R,ttsClipInfosMap:N,projectProps:{startMedia:o,audioLanguage:O,videoRatio:x,videoSize:r}},k=Tt(SS(M)).pipe(St(F=>zt(a(ip(F))).pipe(At(()=>T))));return Bt(k)},YC=async(e,t,o)=>{const{clipDispatchRange:r,videoRatio:n,sceneId:a}=e,i=e.contents.map(x=>x.text??""),s=r===gn.NEW_PROJECT?oEe(i,Ls.TTV,a,n):rEe(i,Ls.TTV,xa(o())+1,n);await t(ip(s))},RXe=(e,t,o,r,n)=>async(a,i)=>{const{clipDispatchRange:s,videoRatio:x,sceneId:c}=e,l=e.contents.map(Le=>Le.text??"").join(`
4258`);if(!l.trim())return h("ttsBatch.ts").info("[ttvPipeline] empty script — falling back to blank scene (V1 parity)"),r.onRequestStart?.(),await YC(e,a,i),r.onRequestEnd?.(),{outcome:"complete",results:[],hasFailures:!1};r.onRequestStart?.(),Hg(e.voiceSetting);const d=Ya(i());await yr(_.C_TTS_GENERAL_ERROR,"[ttvPipeline] not signed in — aborting generation",h("ttsBatch.ts"));const u=await TN();h("ttsBatch.ts").info("[ttvPipeline] using planReqId="+t.planReqId+" (chunks="+t.chunks.length+")");const p=t.chunks,f=t.planReqId;if(p.length===0)return h("ttsBatch.ts").info("[ttvPipeline] no voiceable chunks in plan — blank scene (V1 parity)"),await YC(e,a,i),r.onRequestEnd?.(),{outcome:"complete",results:[],hasFailures:!1};const E=[],T=[],O={type:null};try{if(await ET(p.length,async Le=>{if(n?.aborted)return;const We=await xb(Le,{planReqId:f,uid:d.uid,clientInfo:u,signal:n,warnLabel:"[ttvPipeline] batch"});if(We.kind!=="unresolved"){if(We.kind==="error"){O.type===null&&(O.type=We.errorType),T.push(...sb(p,Le,We.errorType));return}E.push(...We.response.chunkAudios),T.push(...We.response.failedChunks)}}),n?.aborted)return h("ttsBatch.ts").info("[ttvPipeline] aborted during TTS — skipping side effects"),{outcome:"cancelled",results:[]}}catch(Le){if(n?.aborted)return h("ttsBatch.ts").info("[ttvPipeline] aborted during TTS — skipping side effects"),{outcome:"cancelled",results:[]};h("ttsBatch.ts").error("[ttvPipeline] batch synth threw: "+P(Le))}const S=E.length===0,R=O.type??void 0,y=new Set(T.map(Le=>Le.chunkIdx)),v=p.every((Le,We)=>y.has(We));if(S&&v&&T.every(Le=>Le.errorType==="invalid_input"))return h("ttsBatch.ts").info("[ttvPipeline] invalid_input total failure — falling back to blank scene (V1 parity, no modal)"),await YC(e,a,i),r.onRequestEnd?.(),{outcome:"complete",results:[],hasFailures:!1};const N=E,M=JKe(p,E,T,void 0);if(M.length>0&&(S&&h("ttsBatch.ts").error("[ttvPipeline] total TTS failure (errorType="+(R??"unknown")+") — building "+M.length+" errored clip(s)"),Hf(M,e.voiceSetting.speaker)),N.length===0&&M.length===0)throw new C(_.C_TTS_GENERAL_ER
4258ROR,{},"[ttvPipeline] nothing to build (no clips, no lines)");const k=iK(e),F=k[0];if(!F)throw new C(_.C_TTS_GENERAL_ERROR,{},"[ttvPipeline] failed to build origin TTSClipState");const G=AXe(F,N,l),B=[],W=[];for(let Le=0;Le<N.length;Le+=1){const We=N[Le],kt=G[Le],{pair:bt}=await QB(We,kt,kt.clipId,"[ttvPipeline] No audio track for mediaId",n),Jt=YB(bt.globalClip.words,bt.scriptCharStartByWordId,We.captionLines.flatMap(_t=>_t.tokens)),{words:Ft,...Pe}=bt.globalClip;B.push({globalClip:{...Pe,sceneId:c},result:bt.result,timestampedWords:Jt}),W.push(bt.result),r.onProgress?.((Le+1)/(N.length+M.length))}const Q=[],j=new Map;for(let Le=0;Le<M.length;Le+=1){const We=M[Le],kt=p[We.chunkIdx],bt=kt?XB(kt):[We.scriptText],Jt=[];for(const Ft of bt){const Pe=await mXe({...We,scriptText:Ft},F,c,kt?.textAspectLang??F.voiceSetting.speaker.lang);W.push(Pe.result),Jt.push(zF(Pe.globalClip,Pe.timestampedWords.words,Pe.result.audioInfo.mediaId)),Q.push({clipId:Pe.globalClip.clipId,errorInfo:Pe.result.ttsFileInfo.errorInfo})}j.set(We.chunkIdx,Jt),r.onProgress?.((N.length+Le+1)/(N.length+M.length))}const $=N.length+M.length,q=new Array($);B.forEach((Le,We)=>{const kt=N[We];kt!==void 0&&(q[kt.chunkIdx]=EXe(zF(Le.globalClip,Le.timestampedWords.words,Le.result.audioInfo.mediaId),Le.timestampedWords.scriptCharStartByWordId,kt.captionLines,kt.scriptText))}),M.forEach(Le=>{q[Le.chunkIdx]=j.get(Le.chunkIdx)??[]});const H=q.map((Le,We)=>Le!==void 0?Le:(h("ttsBatch.ts").warn("[ttvPipeline] chunkIdx "+We+" missing from both chunkAudios and failedChunks (totalChunkCount="+$+")"),[]));M.length>0&&h("ttsBatch.ts").warn("[ttvPipeline] partial success: "+M.length+"/"+$+" chunks failed — inserted errorInfo placeholders (retry via clip)."),o(H.map(Le=>Le.length));const U=H.flat(),{globalClips:te,tracks:ne,assets:oe}=ES([U]),{files:re,blobs:ge}=IS(W),fe=hS(W),ve=D0(await z3(W)??e.voiceSetting.speaker.lang),yt={dispatchInterface:lb(s,xa(i()),c),globalClips:te,files:re,blobs:ge,assets:oe,tracks:ne,ttsClipInfosMap:fe,projectProps:{startMedia:Ls.TTV,audioLanguage:ve,videoRatio:x,videoSize:{width:1920,height:1080}}};if(n?.aborted)return h("ttsBatch.ts").info("[ttvPipeline] aborted before scene dispatch — skipping"),{outcome:"cancelled",results:[]};await a(ip(SS(yt)));for(const{clipId:Le,errorInfo:We}of Q)We&&a({type:Wo.SET_TTS_CLIP_ERROR_INFO,payload:{clipId:Le,errorInfo:We}});return r.onRequestEnd?.(),{outcome:"complete",results:W,hasFailures:M.length>0}},AXe=(e,t,o)=>t.map(r=>{const n=r.scriptText&&r.scriptText.length>0?r.scriptText:(()=>{const i=Math.max(0,r.scriptCharRange.start),s=Math.min(o.length,r.scriptCharRange.end);return s>i?o.slice(i,s):""})(),a={raw:n,processed:n,textAspectLang:r.textAspectLang};return rg(e,a,ct(),"INSERT")}),yXe=(e,t)=>async o=>
4258o(CXe(e,t,Ls.ATV,Xee)),vXe=async(e,t)=>{const o=[],r=[],n={},a=An(10);return await Promise.all(e.map(i=>a(async()=>{if(!i){r.push(ng);return}const{mediaId:s,aspectRatio:x,sourceIn:c,assetVideoInfo:l}=i,d=Rt(),u=ho(),p=cN(d,s,x,t,0,{sourceIn:c,volume:0});if(p){n[u]=p,r.push(u);const f=await En(s);if(!f){const E="[getSourceVideoAssetMap] Cannot find blob for mediaId: "+s;throw new C(_.C_MEDIA_BLOB_LOST,{},E)}o.push({info:l,blob:f})}else r.push(ng)}))),{assetFileInfos:{assetVideoInfos:o},assets:n,assetIds:r}},wXe=(e,t,o,r)=>{const{contents:n,videoRatio:a}=e,i=n.map(S=>S.sourceClipIdx),s=r(),x=Do(s),c=lt(s),l=ht(s),d={},{clipAndInfos$:u,results$:p,audioLanguage$:f}=TS(e,t,o,r),E=zt(i).pipe(St(S=>{const R=x.at(S);if(!R)return Tt(null);const y=R.words[0],v=Sv(y,c,l);if(!v)return Tt(null);const{mediaId:w,sourceIn:N}=v,M=L.get(d,w);return D_e(w,M).then(k=>k?(L.set(d,w,k.mediaId),{...k,sourceIn:N}):null)}),aa()),T=E.pipe(Ma(S=>vXe(S,a)),Gh()),O=Tf([u.pipe(Fa(),Fa()),T.pipe(At(({assetIds:S})=>S),Fa())]).pipe(At(([S,R])=>mS(S,R===ng?S.globalClip:{...S.globalClip,assetIds:[...S.globalClip.assetIds,R]})),aa());return{assetMap$:T,clipsWithTracks$:O,results$:p,audioLanguage$:f}},NXe=async(e,t)=>{const o=new Map,r=[],n=[],a=[],i={};for(const s of e){const{applyClipIndices:x}=s,c=Rt(),l=ho();switch(s.type){case"image":{const d=s.data.src,u=await XLe({src:d,sourceOrigin:tt.AI_GENERATED,visualAIGenerationMeta:s.data.visualAIGenerationMeta,pendingUserReferenceImages:s.data.pendingUserReferenceImages,referenceImageCache:o}),p=await En(u.mediaId);if(!p)throw new C(_.C_MEDIA_BLOB_LOST,{},"[getGenImageAssetMap] Cannot find blob for mediaId: "+u.mediaId);const{width:f,height:E}=Oz(t),T=rU(f,E);r.push({info:u,blob:p}),a.push(...Array.from({length:x.length},()=>l)),i[l]=gb(c,u.mediaId,T,t,0,{imageKenburnsInfo:{...rMe(cr(t),T),type:Ir.CUSTOM}});break}case"video":{const d=s.data,{width:u,height:p,assetVideoInfo:f,videoSrc:E}=d,{mediaId:T,fileLocation:O}=f;OLe(d)?await yi({type:"blob",blob:d.blob,name:f.name},T,f.sourceOrigin):O===D.LOCAL_TMP?await yi({type:"path",value:f.path},T,f.sourceOrigin):await yi({type:"url",value:E},T,f.sourceOrigin),await pz({mediaId:T,visualAIGenerationMeta:s.data.visualAIGenerationMeta,pendingUserReferenceImages:s.data.pendingUserReferenceImages,referenceImageCache:o});const S=eo(T);if(!S){const y="[getGenImageAssetMap] Cannot find videoInfo for mediaId: "+T;throw new C(_.C_MEDIAINFO_NOT_EXIST,{},y)}const R=cN(c,T,rU(u,p),t,0,void 0);if(R){i[l]=R,a.push(...Array.from({length:x.length},()=>l));const y=await En(T);if(!y)throw new C(_.C_MEDIA_BLOB_LOST,{},"[getGenImageAssetMap] Cannot find blob for mediaId: "+T);n.push({info:S,blob:y})}else a.push(ng);break}}}return{assetFileInfos:{imageMediaInfos:r,assetVideoInfos:n},assets:i,assetIds:a}},PXe=(e,t,o,r)=>{const{contents:n,videoRatio:a,genImageOption:i}=e,{clipAndInfos$:s,results$:x,audioLanguage$:c}=TS(e,t,o,r),l=Tf(Tt(n.flatMap(p=>p.text.split(`
4259`))),Tt(Oz(a))).pipe(St(([p,{width:f,height:E}])=>zt($Le(i?.title??"",p,()=>{},!0,!0,i?.color??"none",i?.style??"picture",f,E,Yi.VIDEO_REMIX_MODAL,!0,a,fP().id)).pipe(er(({numNSFWImage:T})=>{sMe(Yi.VIDEO_REMIX_MODAL,T)})))),d=l.pipe(St(({data:p})=>zt(NXe(p,a))),Gh()),u=Tf([s.pipe(Fa(),Fa()),d.pipe(At(({assetIds:p})=>p),Fa())]).pipe(At(([p,f])=>mS(p,f===ng?p.globalClip:{...p.globalClip,assetIds:[...p.globalClip.assetIds,f]})),aa());return{assetMap$:d,clipsWithTracks$:u,results$:x,audioLanguage$:c}},hS=e=>e.reduce((t,o)=>(t[o.audioInfo.mediaId]=o.ttsFileInfo,t),{}),IS=(e,t)=>{const o=[],r={},{blankInfo:n,blankAudioBlob:a}=mN();return o.push(n),r[n.mediaId]=a,e.forEach(i=>{o.push(i.audioInfo),r[i.audioInfo.mediaId]=i.ttsBlob}),t&&(t.assetFileInfos.imageMediaInfos?.forEach(i=>{o.push(i.info),r[i.info.mediaId]=i.blob}),t.assetFileInfos.assetVideoInfos?.forEach(i=>{o.push(i.info),r[i.info.mediaId]=i.blob})),{files:o,blobs:r}},bXe=(e,t)=>async(o,r)=>{const{videoRatio:n,sourceType:a,sourceSceneInfo:i}=e,s=sl(),{assetMap$:x,clipsWithTracks$:c,results$:l,audioLanguage$:d}=a===Jf.SOURCE_VIDEO?wXe(e,s,t,r):PXe(e,s,t,r),[u,p,f,E]=await Bt(fy([x,c,l,d])),{files:T,blobs:O}=IS(f,u),S=hS(f),{globalClips:R,tracks:y,assets:v}=ES(p);for(const[M,k]of Object.entries(u.assets))L.set(y,k.trackId,k),L.set(v,Je(M),{trackIds:[k.trackId],role:"sub"});const w={dispatchInterface:{type:gn.NEW_SCENE,sceneId:e.sceneId,sceneIndex:xa(r())+1,sceneName:A("video_remix.summary_scene_name")},globalClips:R,files:T,blobs:O,tracks:y,assets:v,ttsClipInfosMap:S,projectProps:{startMedia:Ls.SUMMARY,audioLanguage:E,videoRatio:n,videoSize:se().getInitProjectVideoSize()}},N=Tt(SS(w)).pipe(St(M=>zt(o(ip(M))).pipe(At(()=>f),er(()=>
4259{if(M.clipDispatchRange===gn.NEW_SCENE){const k=qYe(M.clips,a,i);Yo().updateVideoRemixInfo(M.sceneId,k)}}))));return Bt(N)},TS=(e,t,o,r,n)=>{const a=Ya(r()),i=hXe(e,t,o,a,n).pipe(Gh()),s=i.pipe(At(c=>IXe(c))),x=s.pipe(At(c=>zt(z3(c))),fJ(),At(c=>D0(c??e.voiceSetting.speaker.lang)));return{clipAndInfos$:i,results$:s,audioLanguage$:x}},SS=e=>{const{dispatchInterface:t,globalClips:o,files:r,blobs:n,tracks:a,assets:i,projectProps:s,ttsClipInfosMap:x}=e,c=b2(s.videoSize,{tracks:a,assets:i},s.videoRatio,x),l={props:c,projectId:qe.v4(),currentPath:s.currentPath??A("startmode.untitled")},d=zg(r,n,t.type===gn.NEW_PROJECT?l:void 0,s.startMedia);switch(t.type){case gn.NEW_PROJECT:return{clipDispatchRange:t.type,audioLanguage:s.audioLanguage,sceneId:t.sceneId,projectProperty:c,clips:o,newSourceOption:d};case gn.NEW_SCENE:return{clipDispatchRange:t.type,clips:o,newSourceOption:d,projectProperty:c,audioLanguage:s.audioLanguage,sceneId:t.sceneId,sceneIndex:t.sceneIndex,sceneName:t.sceneName}}},dvt=(e,t,o,r,n,a="contain",i=!1,s)=>async x=>{await $e().initTTSSpeakerList();const c={type:Ge.BATCH,status:"idle",sceneId:s,voiceSetting:us(),variant:e,contents:t,clipDispatchRange:o,videoRatio:r,currentPath:n,fillType:a,useAnimation:i};x({type:Wo.SET_TTS_STATE,payload:{type:Ge.BATCH,state:c}})},uvt=(e,t,o,r,n,a)=>async i=>{await $e().initTTSSpeakerList();const s={type:Ge.BATCH,status:"idle",sceneId:n,voiceSetting:us(a),variant:e,contents:t,clipDispatchRange:o,videoRatio:r,options:{preprocess:{skipSplitAtPunc:!0},quota:{skipQuotaCheck:!0}}};i({type:Wo.SET_TTS_STATE,payload:{type:Ge.BATCH,state:s}})},pvt=e=>async t=>{await $e().initTTSSpeakerList();const o={type:Ge.BATCH,status:"idle",sceneId:e,voiceSetting:us(),variant:La.ATV,contents:[{text:""}],clipDispatchRange:gn.NEW_PROJECT,videoRatio:W1,options:{preprocess:{skipSplitAtPunc:!0},quota:{skipQuotaCheck:!0}}};t({type:Wo.SET_TTS_STATE,payload:{type:Ge.BATCH,state:o}})},fvt=(e,t,o,r,n,a,i,s)=>async x=>{await $e().initTTSSpeakerList();const c={type:Ge.BATCH,status:"idle",sceneId:a,voiceSetting:us(i),variant:La.SUMMARY,contents:e,sourceType:t,clipDispatchRange:o,videoRatio:r,sourceSceneInfo:n,genImageOption:s,options:{preprocess:{skipSplitAtPunc:!0},quota:{skipQuotaCheck:!0}}};x({type:Wo.SET_TTS_STATE,payload:{type:Ge.BATCH,state:c}})},gvt=e=>(t,o)=>{const r=o();Wv(r)&&t({type:Wo.SET_TTS_CONTENT,payload:{type:Ge.BATCH,contents:e}})},lb=(e,t,o)=>{switch(e){case gn.NEW_PROJECT:return{type:gn.NEW_PROJECT,sceneId:o};case gn.NEW_SCENE:return{type:gn.NEW_SCENE,sceneId:o,sceneIndex:t+1}}},LXe=(e,t,o,r)=>e<r&&t>o,R_=e=>[...e].map(([t,[o,r]])=>({clipId:t,start:o,end:r})).sort((t,o)=>t.start-o.start),db=(e,t,o)=>{let r=0,n=o.length;for(;r<n;){const i=Math.floor((r+n)/2);o[i].end<=e?r=i+1:n=i}const a=[];for(let i=r;i<o.length;i+=1){const s=o[i];if(s.start>=t)break;LXe(e,t,s.start,s.end)&&a.push(s)}return a},BF=(e,t,o,r,n,a,i=R_(o))=>{const s=db(e,t,i)[0];return s!==void 0?s.clipId:(n.warn(a+" abs range ["+e+".."+t+"] does not overlap any original clip — falling back to "+r),r)},BC=h("attributeCaptionLines.ts"),Sh=e=>{const t=new Map,o=new Map;for(const r of e){const n=t.get(r.ownerClipId)??[];n.push(r),t.set(r.ownerClipId,n);const a=o.get(r.chunkIdx)??[];a.push(r),o.set(r.chunkIdx,a)}return{byOwnerClipId:t,byChunkIdx:o}},OS=(e,t,o,r=R_(t))=>{const n=o[0],a=[];for(let i=0;i<e.length;i+=1){const s=e[i];if(s.captionLines.length===0){BC.warn("chunk "+i+" has no captionLines — attributing whole chunk range to owner");const x=s.scriptCharRange.start,c=s.scriptCharRange.end,l=BF(x,c,t,n,BC,"captionLine",r);a.push({chunkIdx:s.chunkIdx,chunk:s,lineIdx:0,captionLine:{text:s.scriptText,charRange:{start:0,end:s.scriptCharRange.end-s.scriptCharRange.start},tokens:[]},ownerClipId:l,absCharRange:{start:x,end:c}});continue}for(let x=0;x<s.captionLines.length;x+=1){const c=s.captionLines[x],l=s.scriptCharRange.start+c.charRange.start,d=s.scriptCharRange.start+c.charRange.end,u=db(l,d,r);if(u.length<=1){const p=u[0]?.clipId??BF(l,d,t,n,BC,"captionLine",r);a.push({chunkIdx:s.chunkIdx,chunk:s,lineIdx:x,captionLine:c,ownerClipId:p,absCharRange:{start:l,end:d}});continue}for(const p of u){const f=Math.max(l,p.start),E=Math.min(d,p.end);if(E<=f)continue;const T=f-s.scriptCharRange.start,O=E-s.scriptCharRange.start;a.push({chunkIdx:s.chunkIdx,chunk:s,lineIdx:x,captionLine:{...c,text:c.text.slice(T-c.charRange.start,O-c.charRange.start),charRange:{start:T,end:O}},ownerClipId:p.clipId,absCharRange:{start:f,end:E}})}}}return a},KC=h("chunkSubClipMap.ts"),KF=(e,t)=>{const o=[];let r=0;for(let n=0;n<t;n+=1)o.push(r),r+=e[n];return o},_vt=(e,t,o)=>{t.length!==o.length&&KC.warn("[TTV] plan/clip chunk count differs: plan="+t.length+" clips="+o.length);const r=Math.min(t.length,o.length),n=KF(t,r),a=KF(o,r),i=[];for(let x=0;x<r;x+=1)for(let c=0;c<t[x];c+=1)i.push(x);if(i.length===0)return[];const s=new Set;for(const x of e){const c=Math.min(Math.max(x,0),i.length-1);c!==x&&KC.warn("[TTV] plan index out of range, clamped: "+x+" -> "+c+" (planLines="+i.length+")");const l=i[c],d=t[l],u=o[l];if(u<=0)continue;u<d&&KC.warn("[TTV] chunk "+l+" has fewer clips than planned lines: clips="+u+" planned="+d+" — assets will share clips");const p=c-n[l],f=Math.floor(p*u/d),E=Math.min(u,Math.max(f+1,Math.floor((p+1)*u/d)));for(let T=f;T<E;T+=1)s.add(a[l]+T)}
4259return[...s].sort((x,c)=>x-c)},MXe=(e,t)=>{const o=Math.min(e.length,t.length);return{lines:e.slice(0,o),ids:t.slice(0,o)}},DXe=/[\p{L}\p{N}]/u,sK=e=>DXe.test(e),kXe=e=>e.trim().length===0?"empty":sK(e)?"ok":"nonVoiceable",FXe={empty:"tts.error_text_input_none",nonVoiceable:"tts.error_text_invalid"},XF=h("attributeFailedChunks.ts"),JF=(e,t,o)=>e.length===0?[]:o===void 0?(XF.warn("fallbackClipId is undefined; no attribution possible"),[]):[...e].sort((r,n)=>r.chunkIdx-n.chunkIdx).flatMap(r=>{const n=t.get(r.chunkIdx);return!n?.length&&XF.warn("failed chunk "+r.chunkIdx+" has no owner mapping — falling back to "+o),(n?.length?n:[o]).map(i=>({chunkIdx:r.chunkIdx,failedChunk:r,ownerClipId:i}))}),UXe=(e,t,o,r)=>{const n=db(e,t,o).map(a=>a.clipId);return n.length>0?n:[r]},VXe=(e,t,o,r=R_(t))=>{const n=o[0],a=new Map,i=new Map;for(const s of o)a.set(s,new Set);for(const s of e){const x=UXe(s.scriptCharRange.start,s.scriptCharRange.end,r,n);i.set(s.chunkIdx,x);for(const c of x){const l=a.get(c)??new Set;l.add(s.chunkIdx),a.set(c,l)}}return{ownerChunks:a,chunkOwners:i}},GXe=(e,t,o)=>{const r=new Set,n=new Set;for(const[a,i]of e){let s=!1,x=!1;for(const c of i)t.has(c)?s=!0:o.has(c)&&(x=!0);s?r.add(a):x&&n.add(a)}return{succeeded:r,failed:n}},WXe=(e,t)=>{const o=[];for(const[r,n]of e)n.size>0||sK(t.get(r)??"")&&o.push(r);return o},JA=e=>e.contents,qF=e=>{const{speed:t,volume:o,...r}=ww(e);return JSON.stringify(r)},HXe=(e,t)=>qF(e)===qF(t)&&e.speed===t.speed&&e.volume===t.volume&&e.effect===t.effect,jXe=e=>{const t=[];for(const o of e){const r=t.at(-1),n=r?.at(-1);r===void 0||n===void 0||!HXe(n.voiceSetting,o.voiceSetting)?t.push([o]):r.push(o)}return t},QF=(e,t)=>({raw:e,processed:e,textAspectLang:t}),xK=(e,t,o)=>{const r=[...t].sort((n,a)=>n.chunkIdx-a.chunkIdx||n.lineIdx-a.lineIdx);if(o&&r.length>0){const n=JA(e).replace(/\n+$/,""),a=r[0],i=QF(n,a.chunk.textAspectLang),s=e.clipId,x=Gm(e)?"INSERT":"MODIFY",c=rg(e,i,s,x);return r.map(l=>({attr:l,clipId:s,subState:c}))}return r.map((n,a)=>{const i=(n.captionLine.text??"").replace(/^\n+|\n+$/g,""),s=(n.chunk.scriptText??"").replace(/^\n+|\n+$/g,""),x=i.length>0?i:s,c=QF(x,n.chunk.textAspectLang),l=a===0?e.clipId:dy.v4(),d=a!==0||Gm(e)?"INSERT":"MODIFY",u=rg(e,c,l,d);return{attr:n,clipId:l,subState:u}})},zXe=(e,t,o)=>{const r=[...t].sort((u,p)=>u.chunkIdx-p.chunkIdx),n=r.map(u=>({chunkIdx:u.chunkIdx,scriptCharRange:u.scriptCharRange,scriptText:u.text,textAspectLang:u.textAspectLang,captionLines:u.captionLinePlans.map(p=>({text:p.text,charRange:p.charRange,tokens:[]}))})),a=OS(n,o,e.map(u=>u.clipId)),{byOwnerClipId:i}=Sh(a),s=new Map,x=new Map,c=new Map;for(const u of e){const p=i.get(u.clipId)??[];if(p.length===0)continue;const f=xK(u,p,!1),E=[];for(const{attr:T,clipId:O,subState:S}of f)s.set(T,O),c.set(O,S),E.push(S);x.set(u.clipId,E)}const l=new Map;for(const u of a){const p=s.get(u);if(p===void 0)continue;const f=l.get(u.chunkIdx)??[];f.push(p),l.set(u.chunkIdx,f)}return{orderedOwners:e.filter(u=>
4259x.has(u.clipId)).map(u=>({state:u,subs:x.get(u.clipId)})),subClipIdsByChunkIdx:l,subStateByClipId:c}},YXe=e=>{if(!cb(e))return;const t=ZB().replaceRulesMap,o=Object.entries(t).filter(([,r])=>r.length>0);if(o.length!==0)return Object.fromEntries(o)},ea=h("ttsChunkToClipPipeline.ts"),BXe=4,Fx={reason:nr.NOT_COMPLETED,msg:"tts.not_completed"},cK=(e,t,o,r)=>{if(e.resultChunkIdxs.has(o))return;e.resultChunkIdxs.add(o);const n=r.get(o);e.results.push(n===void 0?t:{...t,chunkTextLength:n})},ZF=async(e,t,o,r,n=e.offsetsByClipId,a,i)=>{const{signal:s,settledRef:x,preserveOriginal:c,emptyOwnerClipIds:l,trackInserted:d,dispatch:u,materializeChunkAudio:p,applyPerLineClips:f,deliveredClipIds:E,userReqId:T,ownedClipIds:O,runOwnedClipIds:S,materialized:R}=e;if(t.length===0||x.settled||s?.aborted)return;const y=n===e.offsetsByClipId?e.ownerRanges:R_(n),v=a??OS(o,n,t.map(H=>H.clipId),y),w=i??v,{byOwnerClipId:N,byChunkIdx:M}=Sh(v),{byChunkIdx:k}=Sh(w),F=new Map,G=new Map,B=new Map;for(const H of t){const U=N.get(H.clipId)??[],te=xK(H,U,c),ne=new Set,oe=[];for(const{attr:re,clipId:ge,subState:fe}of te)F.set(re,ge),G.set(re,fe),!ne.has(fe.clipId)&&(ne.add(fe.clipId),oe.push(fe));B.set(H.clipId,oe)}for(const H of t){const U=B.get(H.clipId)??[];if(U.length===0){ea.warn("ttsChunkToClipPipeline: no captionLines attributed to original clipId "+H.clipId),l.add(H.clipId);continue}d(U),await u(tK(H,U))}const W=[...o].sort((H,U)=>H.chunkIdx-U.chunkIdx),Q=new Map;for(const H of W){if(x.settled||s?.aborted)return;const U=(M.get(H.chunkIdx)??[]).filter(ve=>G.has(ve));if(U.length===0)continue;const te=U[0],ne=F.get(te),oe=G.get(te),{pair:re,annotated:ge,audioInfo:fe}=await p(H,oe,ne);if(x.settled||s?.aborted)return;if(c){const ve=new Map;for(const We of U){const kt=ve.get(We.ownerClipId)??[];kt.push(We),ve.set(We.ownerClipId,kt)}const yt=new Map;for(const We of k.get(H.chunkIdx)??[]){const kt=We.ownerClipId,bt=yt.get(kt)??[];bt.push(We.captionLine.charRange),yt.set(kt,bt)}const Le=FKe(ge.words,ge.scriptCharStartByWordId,yt);for(const[We,kt]of ve){const bt=Le.get(We)??[];if(!bt.some(_t=>_t.type===Z.NORMAL)){ea.warn("preserve: owner "+We+" has no NORMAL words in chunk "+H.chunkIdx);continue}const Ft=G.get(kt[0]),Pe=Q.get(We)??{words:[],segments:[],subState:Ft,globalClipTemplate:re.globalClip,fullText:Ft.ttsString.raw};Pe.words.push(...bt),Pe.segments.push({mediaId:fe.mediaId,wordCount:bt.length,ttsFileInfo:re.result.ttsFileInfo}),Q.set(We,Pe)}}else f({pair:re,annotated:ge,audioInfo:fe},U.map(ve=>ve.captionLine),U.map(ve=>F.get(ve)),U.map(ve=>G.get(ve)));cK(e,re.result,H.chunkIdx,r)}if(c){if(x.settled||s?.aborted)return;for(const H of t){const U=Q.get(H.clipId);if(U===void 0||U.words.length===0){ea.warn("preserve: owner "+H.clipId+" has no NORMAL words across all chunks"),u({type:Wo.SET_TTS_CLIP_ERROR_INFO,payload:{clipId:H.clipId,errorInfo:{reason:nr.NOT_COMPLETED,msg:"tts.error_text_invalid"}}});continue}const te=[...U.words],ne=te[te.length-1];(ne===void 0||ne.type!==Z.ENTER)&&Dx(te,{preserveEmptyWords:!0});const oe={...U.globalClipTemplate,clipId:U.subState.clipId,words:te,captions:Xl(U.fullText),captionMode:ar.MANUAL},[re,...ge]=U.segments;if(re===void 0){ea.error("preserve: owner "+H.clipId+" accumulated words without any audio segment"),u({type:Wo.SET_TTS_CLIP_ERROR_INFO,payload:{clipId:H.clipId,errorInfo:Fx}});continue}E.add(U.subState.clipId),u({type:Wo.APPLY_CLIPS_FROM_TTS,payload:{globalClip:oe,isModifying:U.subState.variant==="MODIFY",mediaId:re.mediaId,mediaSegments:[re,...ge],ttsFileInfo:re.ttsFileInfo,groupKey:T}})}}const j=Array.from(B.values()).flatMap(H=>H.map(U=>U.clipId));j.forEach(H=>{O.add(H),S.add(H)}),u(C_(j,T));for(const H of t)R.add(H.clipId);const $=ni.getInstance(Ur.TTS),q=$.getPayload();q&&$.setPayload({numSuccess:q.numSuccess+t.length})},KXe=async(e,t,o)=>{const{script:r,speakerInfo:n,replaceRulesMap:a,throwIfAborted:i,offsetsByClipId:s,ownerRanges:x,okClipIds:c,settledRef:l,signal:d,user:u,clientInfo:p,stateByClipId:f,orderedStates:E,markClipsError:T,errorSpeaker:O,ttsErrorMsgArg:S,materialized:R,emptyOwnerClipIds:y,errorInfoFromFailed:v,results:w,markFailure:N,reportCreditDeduction:M,dispatch:k,userReqId:F}=e,G=new Set;let B=Promise.resolve();const W=await qB({script:r,speakerInfo:n,uid:u.uid,linebreakMode:"audio",splitAtPunctuation:e.splitAtPunctuation,captionLengthMode:"long",replaceRulesMap:a,signal:d});i();const Q=W.chunks,j=new Map(W.chunks.map(Pe=>[Pe.chunkIdx,Pe.processedLength])),{ownerChunks:$,chunkOwners:q}=VXe(Q,s,c,x),H=new Map(c.map((Pe,_t)=>[Pe,_t])),U=new Map([...$].map(([Pe,_t])=>[Pe,_t.size])),te=[],ne=new Map,oe=new Map,re=[],ge=new Set,fe=new Set,ve=new Set,yt={type:null},Le=Pe=>{const _t=f.get(Pe),No=$.get(Pe);if(!_t||!No||No.size===0)return;const ko=[...No].map(dt=>ne.get(dt)).filter(dt=>dt!==void 0);G.add(Pe),ve.delete(Pe),B=B.then(()=>
4259ZF(e,[_t],ko,j,s,oe.get(Pe)??[],[...oe.values()].flat())).catch(dt=>{G.delete(Pe),ve.add(Pe),ea.warn("ttsChunkToClipPipeline: streamed materialize failed for "+Pe+": "+P(dt))})};if(await ET(W.chunks.length,async Pe=>{if(l.settled||d?.aborted)return;const _t=await xb(Pe,{planReqId:W.planReqId,uid:u.uid,clientInfo:p,signal:d,warnLabel:"ttsChunkToClipPipeline: owner batch"});if(l.settled||d?.aborted)return;if(_t.kind==="unresolved"){for(const Qo of Pe)ge.add(Qo);N();return}if(_t.kind==="error"){yt.type===null&&(yt.type=_t.errorType);for(const Qo of Pe)ge.add(Qo);re.push(...sb(W.chunks,Pe,_t.errorType)),N();return}const No=_t.response;_t.creditDeduction&&M({batchId:_t.reqId,deduction:_t.creditDeduction}),te.push(...No.chunkAudios),re.push(...No.failedChunks);const ko=[];for(const Qo of No.chunkAudios)ne.set(Qo.chunkIdx,Qo),!fe.has(Qo.chunkIdx)&&(fe.add(Qo.chunkIdx),ko.push(Qo));const dt=Sh(OS(ko,s,c,x));for(const[Qo,li]of dt.byOwnerClipId){const Sn=oe.get(Qo)??[];Sn.push(...li),oe.set(Qo,Sn)}const vr=new Set(ve);for(const Qo of ko)for(const li of q.get(Qo.chunkIdx)??[]){const Sn=U.get(li);if(Sn===void 0||Sn<=0)continue;const mr=Sn-1;U.set(li,mr),mr===0&&vr.add(li)}const ln=[...vr].sort((Qo,li)=>(H.get(Qo)??Number.MAX_SAFE_INTEGER)-(H.get(li)??Number.MAX_SAFE_INTEGER));for(const Qo of ln)G.has(Qo)||Le(Qo)}),await B,i(),(re.length>0||ge.size>0)&&N(),te.length===0){const Pe=yt.type!==null?ju(yt.type,S(yt.type)):Fx,_t=JF(re,q,E[0]?.clipId),No=new Map;for(const ko of _t)!No.has(ko.ownerClipId)&&No.set(ko.ownerClipId,ko.failedChunk);for(const ko of E){const dt=No.get(ko.clipId);T([ko.clipId],dt?v(dt):Pe)}throw ea.error("ttsChunkToClipPipeline owner-stream failed: no successful clips (planReqId="+W.planReqId+")"),Hf(re,O),new Error($l.NO_CLIPS_DELIVERED)}const We=GXe($,new Set(te.map(Pe=>Pe.chunkIdx)),new Set([...re.map(Pe=>Pe.chunkIdx),...ge]));for(const Pe of WXe($,new Map(E.map(_t=>[_t.clipId,_t.contents]))))ea.warn("[tts] owner clip has voiceable text but produced no chunk — left unchanged with no audio (possible mapping bug): clipId="+Pe);const kt=JF(re,q,E[0]?.clipId),bt=new Map;for(const Pe of kt)!bt.has(Pe.ownerClipId)&&bt.set(Pe.ownerClipId,Pe.failedChunk);for(const Pe of We.failed){const _t=bt.get(Pe);ea.warn("[owner fail] clipId="+Pe+" errorType="+(_t?.errorType??"(none)")+" serverMsg="+(_t?.errorMsg??"(none)")),T([Pe],_t?v(_t):Fx)}const Jt=E.filter(Pe=>We.succeeded.has(Pe.clipId)),Ft=Jt.filter(Pe=>!R.has(Pe.clipId));if(Ft.length>0){const Pe=new Set(Ft.map(dt=>dt.clipId)),_t=new Set;for(const dt of Pe){const vr=$.get(dt);if(vr)for(const ln of vr)_t.add(ln)}const No=[..._t].map(dt=>ne.get(dt)).filter(dt=>dt!==void 0),ko=Ft.flatMap(dt=>oe.get(dt.clipId)??[]);try{await ZF(e,Ft,No,j,s,ko,[...oe.values()].flat())}catch(dt){ea.error("ttsChunkToClipPipeline: final materialize of remaining owners failed: "+P(dt));for(const vr of Ft)R.has(vr.clipId)||y.add(vr.clipId)}}for(const Pe of y)We.failed.has(Pe)||(ea.warn("ttsChunkToClipPipeline: owner "+Pe+" received no caption lines (attribution starved) — marking as not-completed"),T([Pe],Fx));return k(C_(Jt.map(Pe=>Pe.clipId).filter(Pe=>!y.has(Pe)),F)),Hf(re,O),l.settled=!0,w},XXe=async e=>{const{orderedStates:t,settledRef:o,signal:r,materializeChunkAudio:n,offsetsByClipId:a,ownerRanges:i,dispatch:s,userReqId:x,applyPerLineClips:c,results:l,ownedClipIds:d,runOwnedClipIds:u,trackInserted:p,markClipsError:f,errorInfoFromFailed:E,script:T,speakerInfo:O,replaceRulesMap:S,throwIfAborted:R,user:y,clientInfo:v,errorSpeaker:w,ttsErrorMsgArg:N,markFailure:M,reportCreditDeduction:k}=e,F=new Set;let G=Promise.resolve();const B=()=>{let oe=new Map,re=new Map;return{layPlaceholders:fe=>{const ve=zXe(t,fe,a);oe=ve.subClipIdsByChunkIdx,re=ve.subStateByClipId,ve.subStateByClipId.forEach((yt,Le)=>{d.add(Le),u.add(Le)});for(const{state:yt,subs:Le}of ve.orderedOwners)p(Le),G=G.then(()=>s(tK(yt,Le)))},hasKey:fe=>oe.has(fe),keys:()=>oe.keys(),fill:async fe=>{if(o.settled||r?.aborted)return;const ve=oe.get(fe.chunkIdx);if(ve===void 0||ve.length===0){ea.warn("ttsChunkToClipPipeline: chunk "+fe.chunkIdx+" has no sub-clip placeholders — dropping its audio");return}const yt=re.get(ve[0]),{pair:Le,annotated:We,audioInfo:kt}=await n(fe,yt,ve[0]);if(o.settled||r?.aborted)return;const bt=OS([fe],a,t.map(ko=>ko.clipId),i),Jt=bt.map(ko=>ko.captionLine),{lines:Ft,ids:Pe}=MXe(Jt,ve);Jt.length!==ve.length&&ea.warn("ttsChunkToClipPipeline: sub-clip count mismatch on chunk "+fe.chunkIdx+": attributedLine
4259s="+Jt.length+" placeholders="+ve.length+"; filling "+Pe.length),Pe.length>0&&(c({pair:Le,annotated:We,audioInfo:kt},Ft,Pe,Pe.map(ko=>re.get(ko))),s(C_(Pe,x))),cK(e,Le.result,fe.chunkIdx,j);const _t=ni.getInstance(Ur.TTS),No=_t.getPayload();No&&_t.setPayload({numSuccess:No.numSuccess+Pe.length})},markFailed:(fe,ve)=>{f(oe.get(fe)??[],ve)},finalize:()=>{},streamWarnMsg:(fe,ve)=>"ttsChunkToClipPipeline: streamed sub-clip chunk "+fe+" fill failed: "+P(ve),finalErrorMsg:(fe,ve)=>"ttsChunkToClipPipeline: final sub-clip fill of chunk "+fe+" failed: "+P(ve)}},W=await qB({script:T,speakerInfo:O,uid:y.uid,linebreakMode:"audio",splitAtPunctuation:e.splitAtPunctuation,captionLengthMode:"long",replaceRulesMap:S,signal:r});R();const Q=W.chunks,j=new Map(W.chunks.map(oe=>[oe.chunkIdx,oe.processedLength])),$=B();$.layPlaceholders(Q);const q=[],H=[],U={type:null};if(await ET(W.chunks.length,async oe=>{if(o.settled||r?.aborted)return;const re=await xb(oe,{planReqId:W.planReqId,uid:y.uid,clientInfo:v,signal:r,warnLabel:"ttsChunkToClipPipeline: batch"});if(o.settled||r?.aborted)return;if(re.kind==="unresolved"){M();return}if(re.kind==="error"){U.type===null&&(U.type=re.errorType),H.push(...sb(W.chunks,oe,re.errorType)),M();return}const ge=re.response;re.creditDeduction&&k({batchId:re.reqId,deduction:re.creditDeduction}),q.push(...ge.chunkAudios),H.push(...ge.failedChunks);for(const fe of ge.chunkAudios)F.has(fe.chunkIdx)||$.hasKey(fe.chunkIdx)&&(F.add(fe.chunkIdx),G=G.then(()=>$.fill(fe)).catch(ve=>{F.delete(fe.chunkIdx),ea.warn($.streamWarnMsg(fe.chunkIdx,ve))}))}),await G,R(),H.length>0&&M(),q.length===0){const oe=U.type!==null?ju(U.type,N(U.type)):Fx,re=new Map(H.map(ge=>[ge.chunkIdx,ge]));for(const ge of $.keys()){const fe=re.get(ge);$.markFailed(ge,fe?E(fe):oe)}throw ea.error("ttsChunkToClipPipeline chunk-stream failed: no successful clips (planReqId="+W.planReqId+")"),Hf(H,w),new Error($l.NO_CLIPS_DELIVERED)}const te=new Map(H.map(oe=>[oe.chunkIdx,oe])),ne=new Map(q.map(oe=>[oe.chunkIdx,oe]));for(const oe of $.keys()){if(F.has(oe))continue;const re=ne.get(oe);if(re!==void 0){try{await $.fill(re)}catch(fe){ea.error($.finalErrorMsg(oe,fe)),M(),$.markFailed(oe,Fx)}continue}const ge=te.get(oe);ge!==void 0?$.markFailed(oe,E(ge)):(M(),$.markFailed(oe,Fx))}return Hf(H,w),o.settled=!0,l},JXe=(e,t,o,r={},n)=>async(a,i)=>{if(e.length===0)throw new C(_.C_LOGIC_ERROR,{},"ttsChunkToClipPipeline: empty states");const s=QI(),x=new Map;He(i()).forEach((S,R)=>x.set(S.clipId,R));const c=[...e].sort((S,R)=>{const y=x.get(S.clipId)??Number.MAX_SAFE_INTEGER,v=x.get(R.clipId)??Number.MAX_SAFE_INTEGER;return y-v}),l=c.filter(S=>{const R=kXe(JA(S));return R!=="ok"&&!S.silent&&i0(A(FXe[R])),R==="ok"});if(l.length===0)throw new Error($l.INVALID_TEXT);const d=S=>S===void 0?void 0:x.get(S.clipId),u=S=>{const R=S.map((y,v)=>{const w=v===0?void 0:d(S[v-1]),N=d(y);return{clipId:y.clipId,text:JA(y),continuesFromPrev:w!==void 0&&N!==void 0&&N-w===1}});return ime(R)},p=jXe(l);o.onRequestStart?.(),Hg(l[0].voiceSetting),!y0e(i()).some(S=>S.type===Ur.TTS)&&Qy(Ur.TTS,{numSuccess:0});const E=new Set,T=new Set,O=new Set;try{const S=Ya(i());await yr(_.C_TTS_GENERAL_ERROR,"[ttsChunkToClipPipeline] not signed in — aborting generation",ea);const R=YXe(i()),y=await TN();let v=!1;const w=()=>{v=!0},N=(q,H)=>{q.length>0&&w();for(const U of q)a({type:Wo.SET_TTS_CLIP_ERROR_INFO,payload:{clipId:U,errorInfo:H}})},M=r.preserveOriginalClips===!0,k=!M,F=()=>{if(n?.aborted)throw new Error("ttsChunkToClipPipeline: aborted")},G=q=>{for(const H of q)H.variant==="INSERT"&&T.add(H.clipId)},B=async(q,H,U)=>{const{pair:te,audioInfo:ne}=await QB(q,H,U,"[ttsChunkToClipPipeline] No audio track for mediaId",n);await a(T0(zg([ne],{[ne.mediaId]:te.result.ttsBlob})));const oe=DKe(te.globalClip.words,te.scriptCharStartByWordId,q.captionLines),{words:re,...ge}=te.globalClip;return{pair:{...te,globalClip:ge},annotated:oe,audioInfo:ne}},W=(q,H,U,te)=>{const ne=kKe(q.pair.globalClip,q.annotated.words,q.annotated.scriptCharStartByWordId,H,U);for(let oe=0;oe<ne.length;oe+=1){const re=ne[oe];O.add(re.clipId),a({type:Wo.APPLY_CLIPS_FROM_TTS,payload:{globalClip:re,isModifying:te[oe].variant==="MODIFY",mediaId:q.audio
4259Info.mediaId,ttsFileInfo:q.pair.result.ttsFileInfo,groupKey:t}})}};l.forEach(q=>E.add(q.clipId));const Q=[],j=async q=>{const H={settled:!1},U=new Set,{script:te,offsetsByClipId:ne}=u(q),oe=R_(ne),re=q[0].voiceSetting,ge=ww(re),fe=re.speaker,ve={aivoice_name:sx(fe.name,fe.provider),aivoice_provider:eT(fe.provider)},yt=dt=>({...ve,error_code:CN(dt,fe.provider)}),Le=dt=>dt.errorType?ju(dt.errorType,yt(dt.errorType)):Fx;let We=!1;const kt=(dt,vr)=>{dt.length>0&&(We=!0),N(dt,vr)},bt=new Map(q.map(dt=>[dt.clipId,dt])),Jt=q.map(dt=>dt.clipId),Ft=[],Pe=new Set,_t=new Set,No=new Set;Jt.forEach(dt=>U.add(dt));const ko={dispatch:a,getState:i,handlers:o,signal:n,userReqId:t,orderedStates:q,script:te,splitAtPunctuation:s,offsetsByClipId:ne,ownerRanges:oe,speakerInfo:ge,replaceRulesMap:R,clientInfo:y,user:S,errorSpeaker:fe,stateByClipId:bt,okClipIds:Jt,results:Ft,resultChunkIdxs:Pe,markFailure:w,reportCreditDeduction:dt=>r.onCreditDeduction?.(dt),materialized:_t,emptyOwnerClipIds:No,ownedClipIds:E,runOwnedClipIds:U,deliveredClipIds:O,preserveOriginal:M,settledRef:H,trackInserted:G,markClipsError:kt,errorInfoFromFailed:Le,throwIfAborted:F,ttsErrorMsgArg:yt,materializeChunkAudio:B,applyPerLineClips:W};try{return k?await XXe(ko):await KXe(ko)}catch(dt){if(n?.aborted===!0)throw dt;if(RN(Km(dt)),Q.push(dt),H.settled=!0,ea.error("ttsChunkToClipPipeline: voice setting run failed for speaker "+ge.speakerId+": "+P(dt)),!We){const vr=Km(dt);kt(Jt.filter(ln=>!O.has(ln)),vr?ju(vr,yt(vr)):Fx)}return Ft}finally{try{r.onRunEnd?.({states:q,audios:Ft})}catch(dt){ea.warn("TTS analytics failed: "+P(dt))}}},$=await rj(p,BXe,q=>j(q));if(o.onRequestEnd?.(),Q.length===p.length)throw Q[0];return{outcome:"complete",results:$.flat(),hasFailures:v}}catch(S){if(n?.aborted===!0){const y=[...T].filter(N=>!O.has(N)),v=new Set(y),w=[...E].filter(N=>!v.has(N));return y.length>0&&a(nK(y)),w.length>0&&a(C_(w,t)),{outcome:"cancelled",results:[]}}throw S}};var QE=(e=>(e.END_OF_SCENES="END_OF_SCENES",e.NO_TEXT="NO_TEXT",e.INVALID_TEXT="INVALID_TEXT",e))(QE||{});const qXe=e=>t=>t.pipe(St(o=>o.contents.length===0?(e||i0(A("tts.error_text_input_none")),ta(()=>new Error("NO_TEXT"))):Tt(o))),QXe=e=>t=>t.pipe(St(o=>o===null?(e||i0(A("tts.error_text_invalid")),ta(()=>new Error("INVALID_TEXT"))):Tt(o))),ZXe=async e=>Bt(Tt(e).pipe(qXe(e.silent),St(async t=>{const o=new V2e(t.variant,t.options?.preprocess);return o.processInput(t.contents,t.voiceSetting.speaker.lang).then(o.getFirstOrNull)}),QXe(e.silent))),$Xe=async(e,t,o)=>{const r=zt(ZXe(e)),n=dm([r,Tt({payload:e,user:o})]),a=sl(),i=n.pipe(St(([s,{payload:x,user:c}])=>{const l={handlers:t,ttsString:s,type:x.variant===Ge.EFFECT?Sc.EFFECT:Sc.DUBBING,voiceSetting:x.voiceSetting,options:x.options,uid:c.uid,userReqId:a};return zt(Vl.getInstance().getTTSEntry(l)).pipe(St(d=>{const u=new ib(d);return zt(u.process(x.variant))}))}));return Bt(i)},e6e=()=>e=>t=>t.pipe(er(({infoModelPair:o,payload:r})=>{const n=[{audioTrack:o.ttsModel,assetId:r.audioId,globalPosition:r.globalPosition,isSynchronous:!1}];e(Z6e(n))}),At(({infoModelPair:o})=>({audioInfo:o.audioInfo,ttsFileInfo:o.ttsModel.ttsFileInfo,ttsBlob:o.ttsBlob}))),t6e=()=>e=>t=>t.pipe(er(({infoModelPair:o,payload:r})=>{const n=[{newTrack:o.ttsModel,newAudioId:r.audioId,prevAudioId:r.modifyingAudioId}];e({type:Ga.MODIFY_SOUND_EFFECTS,payload:{pairs:n}})}),At(({infoModelPair:o})=>({audioInfo:o.audioInfo,ttsFileInfo:o.ttsModel.ttsFileInfo,ttsBlob:o.ttsBlob}))),ub=(e,t)=>o=>{const r=Tt(e).pipe(er(()=>t.onRequestStart?.()),er(()=>Hg(e[0].voiceSetting)),St(n=>zt(n).pipe(V0(a=>zt(o(o6e(a,t))).pipe(er(()=>t.onProgress?.(1)),c0(i=>i instanceof EJ?(t.onProgress?.(0),pm):(t.onProgress?.(0),ta(()=>{throw i}))))))),aa(),Fa(),er(()=>t.onRequestEnd?.()),St(n=>n.length===0?ta(()=>{throw new C(_.C_TTS_GENERAL_ERROR)}):Tt(n)));return Bt(r)},o6e=(e,t)=>async(o,r)=>{const n=await $Xe(e,t,Ya(r())),a=Tt({infoModelPair:n,payload:e,handlers:t}).pipe(St(i=>i.infoModelPair.ttsModel.ttsFileInfo.errorInfo!==void 0?pm:Tt(i)),St(async({infoModelPair:i})=>{if(!i.audioInfo.videoAudioMetaInfo.audioInfo){const s="[handleTTSEffect] Audio track not found in TTS result for mediaId: "+i.ttsModel.mediaId;throw new C(_.C_MEDIA_NO_AUDIO_TRACK,{},s)}return await i_({mediaId:i.ttsModel.mediaId,audioBlob:i.ttsBlob,sampleRate:i.audioInfo.videoAudioMetaInfo.audioInfo.sampleRate,codec:i.audioInfo.videoAudioMetaInfo.audioInfo.codec,duration:i.audioInfo.videoAudioMetaInfo.duration,sourceOrigin:i.audioInfo.sourceOrigin,name:i.audioInfo.name,sourceType:i.audioInfo.sourceType}),{infoModelPair:i,payload:e}}),St(({infoModelPair:i,payload:s})=>rT(s)?Tt({infoModelPair:i,payload:s}).pipe(o(e6e())):Tt({infoModelPair:i,payload:s}).pipe(o(t6e()),St(async x=>(s.variant===Ge.DUBBING&&await o(n6e(s.audioId,x.audioInfo.videoAudioMetaInfo.duration)),x)))),er(()=>
4259o(r6e(e.audioId))));return Bt(a)},Evt=()=>async(e,t)=>{await $e().initTTSSpeakerList();const o=t(),r=uI(o),n=jo(o),a=n.globalPosition??xs(r),i=j3(r,Ke.ORIGINAL),s=ho(),x={type:Ge.EFFECT,status:"idle",variant:Ge.EFFECT,audioId:s,globalPosition:a,contents:i,voiceSetting:us()};e({type:Wo.SET_TTS_STATE,payload:{type:Ge.EFFECT,states:{[s]:x}}})},r6e=e=>t=>{t({type:Wo.SET_TTS_STATE,payload:{type:Ge.EFFECT,states:{[e]:null}}})},mvt=(e,t)=>(o,r)=>{const n=Fv(r(),e);!n||!rT(n)||o({type:Wo.SET_TTS_STATE,payload:{type:Ge.EFFECT,states:{[e]:vt(n,a=>{a.globalPosition=t})}}})},hvt=(e,t)=>(o,r)=>{const n=r(),a=lt(n),i=ht(n),s=L.get(i,t),x=s?s.trackIds.map(l=>L.get(a,l)).find(l=>l!==void 0&&s2(l)):void 0,c=x?Wg(x.mediaId,a):void 0;if(c){const l=c.ttsFileInfo.text.raw;Jz(l,e)}o({type:Wo.SET_TTS_CONTENT,payload:{type:Ge.EFFECT,audioId:t,contents:e}})},Ivt=(e,t=!0)=>(o,r)=>{const n=r(),a=lt(n),i=ht(n),s=L.get(i,e),x=s?s.trackIds.map(f=>L.get(a,f)).find(f=>f!==void 0&&s2(f)):void 0,c=x?Wg(x.mediaId,a):void 0;if(!c){h("ttsEffect.ts").error("[setTTSEffectModify] TTS model not found for audioId: "+e+", mediaId: "+x?.mediaId);return}const l=ho(),d=c.type===ze.TTSEffect?Ge.EFFECT:Ge.DUBBING,u=oT(c.ttsFileInfo.text.raw),p={type:Ge.EFFECT,status:"idle",variant:d,audioId:l,contents:u,modifyingAudioId:e,voiceSetting:us(tT(c.ttsFileInfo).voiceSetting)};return o({type:Wo.SET_TTS_STATE,payload:{type:Ge.EFFECT,states:{[l]:p}}}),t===!0&&g_({type:Ge.EFFECT,audioId:l,shouldAbortOnClose:!0}),l},n6e=(e,t)=>async(o,r)=>{if(!Mt(ke.SMART_AI_DUBBING_AUTO_FREEZE_WORD))return;const a=r(),i=He(a),s=lt(a),x=ht(a),c=cpe(i,s,x,e);c&&await o(DK(c.globalClip,c.clipIndex,t))},qA=e=>e.range!==Dl.EXISTING_DUBBINGS;var a6e=(e=>(e.ALREADY_DUBBED="ALREADY_DUBBED",e.USER_CANCEL="USER_CANCEL",e.NO_SUBTITLES_TO_DUB="NO_SUBTITLES_TO_DUB",e))(a6e||{});const lK=(e,t,o)=>e.words.flatMap(r=>r.assetIds).find(r=>{const n=L.get(o,r);return!n||n.role!=="sub"?!1:n.trackIds.find(a=>{const i=L.get(t,a);return i&&dl(i)})}),dK=(e,t,o)=>Object.fromEntries(e.map(r=>[r.clipId,{globalClip:r,ttsDubbingId:lK(r,t,o)}])),Tvt=()=>e=>e({type:Wo.SET_TTS_STATE,payload:{type:Ge.DUBBING,state:null}}),i6e=(e,t)=>{switch(e){case Dl.ALL_CLIPS:return He(t);case Dl.SCENE_CLIPS:{const o=fxe(t),r=Do(t);return Ype(r,o)}case Dl.SELECTED_CLIPS:return _2(t);case Dl.CURRENT_CLIP:return[uI(t)]}},Svt=(e,t)=>async(o,r)=>{try{await $e().initTTSSpeakerList();const n=r(),a=i6e(e,n),i=lt(n),s=ht(n),x=dK(a,i,s),c=Object.values(x).filter(({ttsDubbingId:u})=>u!==void 0).length;if(c===a.length)throw new Error("ALREADY_DUBBED");if(c!==0&&await Y().popup({bodyClassName:"general-modal",title:A("popup.title_confirm"),yesStr:A("popup.confirm"),noStr:A("popup.cancel"),content:A("tts_dubbing.modal_partial_create")})!==mt.YES)throw new Error("USER_CANCEL");const l=Object.entries(x).filter(([,{ttsDubbingId:u}])=>u===void 0).map(([u,{globalClip:p}])=>({clipId:u,text:j3(p,t)})).filter(({text:u})=>u!==void 0&&u.trim().length!==0);if(l.length===0)throw new Error("NO_SUBTITLES_TO_DUB");const d={type:Ge.DUBBING,status:"idle",contents:l,range:e,voiceSetting:us()};o({type:Wo.SET_TTS_STATE,payload:{type:Ge.DUBBING,state:d}}),g_({type:Ge.DUBBING,shouldAbortOnClose:!0})}catch(n){if(!xg(n))throw n;const a=n.message;if(a==="USER_CANCEL")return;if(a==="NO_SUBTITLES_TO_DUB")PFe(),Y().warn(A("tts_dubbing.modal_no_subtitles_to_dub"));else if(a==="ALREADY_DUBBED"){LFe();const i=await Y().warn(A(e===Dl.SCENE_CLIPS?"tts_dubbing.modal_already_dubbed":"tts_dubbing.modal_already_dubbed_selected_range"));bFe(i===mt.YES?"create":"cancel")}else h("ttsDubbing.ts").error("error during setTTSDubbingModal: "+P(a))}},s6e=(e,t)=>(o,r)=>Tt({payload:e,handlers:t,globalClips:He(r())}).pipe(At(({payload:s,handlers:x,globalClips:c})=>{const l=s.contents.map(d=>{const u=hH(c,d.clipId);if(!u)throw h("ttsDubbing.ts").error(`
4260            clipId `+d.clipId+" not found in globalClips. globalClips length: "+c.length+` 
4261          `),new C(_.C_TTS_GENERAL_ERROR);return{text:d.text,globalPosition:wf(u)}});return{payload:s,handlers:x,textGlobalPosPairs:l}})).pipe(St(({handlers:s,payload:x,textGlobalPosPairs:c})=>{const l=c.map(d=>({type:Ge.EFFECT,status:"idle",silent:!0,variant:Ge.DUBBING,voiceSetting:x.voiceSetting,options:x.options,contents:d.text,globalPosition:d.globalPosition,audioId:ho()}));return o(ub(l,s))})),Ovt=()=>async(e,t)=>{const o=t(),r=await Y().popup(ql(A("tts_dubbing.modal_delete_all_dubbing")));if(NFe(r===mt.YES?"delete":"cancel"),r!==mt.YES)return;const n=lt(o),a=ht(o),i=Object.entries(a).filter(([,s])=>s.role!=="sub"?!1:s.trackIds.find(x=>{const c=L.get(n,x);return c&&dl(c)})).map(([s])=>Je(s));e(vK(i.map(s=>({elementId:s,elementType:ze.SoundEffect}))))},Cvt=()=>async(e,t)=>{const o=t(),r=He(o),n=lt(o),a=ht(o),i=dK(r,n,a),s=Object.values(i).filter(d=>d.ttsDubbingId!==void 0).map(({ttsDubbingId:d})=>{const u=L.get(a,d);if(!u||u.role!=="sub")throw new C(_.C_LOGIC_ERROR,void 0,"Sub asset not found for ttsDubbingId "+d);const p=u.trackIds.map(f=>L.get(n,f)).find(f=>f!==void 0&&dl(f));if(!p)throw new C(_.C_LOGIC_ERROR,void 0,"TTS dubbing track not found for ttsDubbingId "+d);return{ttsModel:p,ttsDubbingId:d}}),{...x}=s[0].ttsModel.ttsFileInfo,c=us(x),l={type:Ge.DUBBING,status:"idle",range:Dl.EXISTING_DUBBINGS,contents:s.map(({ttsDubbingId:d,ttsModel:u})=>({prevAudioId:d,text:oT(u.ttsFileInfo.text.raw)})),voiceSetting:c};e({type:Wo.SET_TTS_STATE,payload:{type:Ge.DUBBING,state:l}}),g_({type:Ge.DUBBING,shouldAbortOnClose:!0})},x6e=(e,t)=>o=>Tt({payload:e,handlers:t}).pipe(St(({handlers:a,payload:i})=>
4261{const s=i.contents.map(x=>({type:Ge.EFFECT,status:"idle",silent:!0,variant:Ge.DUBBING,voiceSetting:i.voiceSetting,options:i.options,contents:x.text,audioId:ho(),modifyingAudioId:x.prevAudioId}));return o(ub(s,a))})),c6e=e=>{const t=ni.getInstance(Ur.DUBBING).getPayload();t&&ni.getInstance(Ur.DUBBING).setPayload({numSuccess:t.numSuccess+(e?1:0),numFailed:t.numFailed+(e?0:1),numTotal:t.numTotal})},l6e=()=>{const e=ni.getInstance(Ur.DUBBING).getPayload();if(!e)return;const t=e.numTotal-e.numSuccess-e.numFailed;t>0&&ni.getInstance(Ur.DUBBING).setPayload({...e,numFailed:e.numFailed+t})},d6e=(e,t)=>async(o,r)=>{MFe(Mt(ke.SMART_AI_DUBBING_AUTO_MUTE),Mt(ke.SMART_AI_DUBBING_AUTO_FREEZE_WORD));const n=e.contents.length;Qy(Ur.DUBBING,{numSuccess:0,numFailed:0,numTotal:n});const a={...t,onProgress:i=>{t.onProgress?.(i),c6e(i===1)}};try{const i=qA(e)?o(s6e(e,a)):o(x6e(e,a)),s=await Bt(i);if(qA(e)){const x=r(),c=lt(x),l=ht(x),d=He(x),u=e.contents.filter(T=>{const O=hH(d,T.clipId);return O&&lK(O,c,l)!==void 0});await o(p6e({...e,contents:u},s));const p=ca(),f=Fi(x);if(Object.values(f).length===0&&p.every(({videoAudioMetaInfo:T})=>T.audioInfo===void 0))return s;const E=u.map(T=>T.clipId);await o(u6e(E))}return s}catch(i){throw l6e(),i}},u6e=e=>async(t,o)=>{if(!Mt(ke.SMART_AI_DUBBING_AUTO_MUTE))return;const n=o(),a=He(n),i=lt(n),s=ht(n),x=new Set,c=new Set(e),l=a.filter(d=>c.has(d.clipId));for(const d of l)for(const u of d.words)for(const p of u.assetIds){if(x.has(p))continue;const f=L.get(s,p);if(!f||f.role!=="main")continue;f.trackIds.some(T=>{const O=L.get(i,T);return O&&Wa(O)})&&x.add(p)}x.size!==0&&t(CK([...x],0))},p6e=(e,t)=>async(o,r)=>{if(!Mt(ke.SMART_AI_DUBBING_AUTO_FREEZE_WORD))return;const a=r(),i=He(a),s=e.contents.reduce((c,l,d)=>{const u=t[d];return!u||u.ttsFileInfo.errorInfo||(c[l.clipId]=u.audioInfo.videoAudioMetaInfo.duration),c},{}),x=i.map((c,l)=>{const d=s[c.clipId];return d===void 0?null:{globalClip:c,clipIndex:l,ttsDuration:d}}).filter(ri).sort((c,l)=>l.clipIndex-c.clipIndex);for(const{globalClip:c,clipIndex:l,ttsDuration:d}of x)await o(DK(c,l,d))},f6e=(e,t,o)=>{t.speaker!==void 0&&$I(e.speaker,t.speaker)===!1&&yl({type:"speaker",prevValue:e.speaker.speakerId,nextValue:t.speaker.speakerId},o),t.volume!==void 0&&e.volume!==t.volume&&yl({type:"volume",prevValue:e.volume,nextValue:t.volume},o),t.speed!==void 0&&e.speed!==t.speed&&yl({type:"speed",prevValue:e.speed,nextValue:t.speed},o),t.pitch!==void 0&&e.pitch!==t.pitch&&yl({type:"pitch",prevValue:e.pitch,nextValue:t.pitch},o),t.emotion!==void 0&&e.emotion!==t.emotion&&yl({type:"emotion",prevValue:e.emotion??"",nextValue:t.emotion},o);const r=Vs(e.speaker,e.acting),n=Vs(t.speaker??e.speaker,t.acting);t.acting!==void 0&&n!==void 0&&r!==n&&yl({type:"acting",prevValue:r??"",nextValue:n},o),t.effect!==void 0&&e.effect!==t.effect&&yl({type:"effect",prevValue:e.effect??"none",nextValue:t.effect},o)},Rvt=e=>Da(e)?{type:Ge.CLIP,clipIds:e.map(({clipId:t})=>t)}:e,Avt=(e,t,o)=>r=>
4261{switch(e.type){case Ge.CLIP:r(XC({type:e.type,clipIds:e.clipIds,partialVoiceSetting:t},o));return;case Ge.EFFECT:r(XC({type:e.type,audioId:e.audioId,partialVoiceSetting:t},o));return;case Ge.BATCH:case Ge.DUBBING:r(XC({type:e.type,partialVoiceSetting:t},o));return}},XC=(e,t)=>(o,r)=>{const n=r(),{partialVoiceSetting:a}=e,i=e.type===Ge.CLIP?e.clipIds.map(x=>mI(n,x)).filter(Se):e.type===Ge.EFFECT?Fv(n,e.audioId):e.type===Ge.DUBBING?kW(n):Wv(n);if(!Array.isArray(i)&&!i||Array.isArray(i)&&i.length===0)return;const s=Array.isArray(i)?i[0].voiceSetting:i.voiceSetting;f6e(s,a,t),(a?.speaker?.badge==="Deprecated"||a?.speaker?.badge==="Disabled")&&rDe(a.speaker,t),o({type:Wo.SET_TTS_VOICE_SETTING,payload:e})},g6e=(e,t)=>{if(t===null)return e;const o=t5(Object.entries(t).map(([r,n])=>[r,HG.build(n)]));return Da(e)?vt(e,r=>{r.forEach(n=>{const a=n.voiceSetting.speaker.lang,i=o[a];if(i===null)return;const s=$M(n.contents,i);n.options=n.options??{},n.options.preprocess=n.options.preprocess??{},n.options.preprocess.replaceRules=s})}):vt(e,r=>{const n=r.voiceSetting.speaker.lang,a=Array.isArray(r.contents)?r.contents.map(({text:x})=>x).join(""):r.contents,i=o[n];if(i===null)return;const s=$M(a,i);r.options=r.options??{},r.options.preprocess=r.options.preprocess??{},r.options.preprocess.replaceRules=s})},$F=e=>({outcome:"complete",results:e,hasFailures:e.some(t=>t.ttsFileInfo.errorInfo!==void 0)}),_6e=(e,t,o,r,n={},a)=>async i=>{if(Da(e))return i(JXe(e,t,o,{preserveOriginalClips:n.preserveOriginalClips,onCreditDeduction:n.onCreditDeduction,onRunEnd:({states:s,audios:x})=>_K(s,x,a,{requestId:t},"speaker")},r));{const s=Tt(e).pipe(er(x=>Hg(x.voiceSetting)),St(x=>{switch(x.type){case Ge.EFFECT:return i(ub([x],o)).then($F);case Ge.DUBBING:return i(d6e(x,o)).then($F);case Ge.BATCH:return i(SXe(x,o,r,n))}}));return Bt(s)}},E6e=(e,t,o)=>{const r=e.planInfo===void 0,n=t>w1;return Da(o)&&r&&n?(Y().openModal(st.NEED_PLAN_UPGRADE,{premiumFeatureType:Ut.TTS_CLIP_MAX_INPUT,descArg:{requestTTSTextLength:LU(t)}}),!1):!0},m6e=e=>{for(const t of fK(e))if(t.provider===Oe.UserTTS&&zB(t))return Y().message(A("tts.deprecated_user_speaker_title"),p0(A("tts.deprecated_user_speaker_modal",{speaker:sx(t.name,t.provider)}))),!1;return!0},JC=e=>Da(e)?e.reduce((t,o)=>t+LR(Gu(o),o.voiceSetting.speaker.provider,o.voiceSetting.speaker.speakerId),0):LR(Gu(e),e.voiceSetting.speaker.provider,e.voiceSetting.speaker.speakerId),h6e=e=>Da(e)?e.every(({options:t})=>t?.quota?.skipQuotaCheck):e.options?.quota?.skipQuotaCheck,I6e=async(e,t,o)=>{const r=h6e(t),n={requestedLength:Da(t)?t.reduce((c,l)=>c+Gu(l),0):Gu(t)};if(!E6e(e,n.requestedLength,t))return!1;if(r)return!0;if(!m6e(t))return!1;let a=JC(t);if(a===0)return!0;Uy(e.uid);const i=Yl(),s=be().getUserInfo()?.uid===e.uid;if(s&&!await i.ensurePricingLoaded(e.uid))return h("common.ts").warn("TTS pricing could not be loaded before quota check; deferring the authoritative decision to the server"),!0;if(a=JC(t),a===0)return!0;const x=Ig(o);if(x!==void 0&&a>
4261x)try{if(await $e().refetchStockTTSSpeakerList(),s&&!await i.ensurePricingLoaded(e.uid))return h("common.ts").warn("TTS pricing could not be reconciled after refreshing the voice list; deferring the authoritative decision to the server"),!0;a=JC(t)}catch(c){h("common.ts").error("Failed to refresh TTS pricing before quota check: "+P(c))}return!await Jh(a,hg.TTS)},T6e=(e,t)=>{switch(e.type){case Ge.CLIP:return e.clipIds.map(o=>mI(t,o)).filter(Se);case Ge.EFFECT:return Fv(t,e.audioId);case Ge.DUBBING:return kW(t);case Ge.BATCH:return Wv(t)}},S6e=(e,t,o,r,n={},a)=>async(i,s)=>{const x=s(),c=Ya(x),l=T6e(e,x);if(!l)return[];const d=g6e(l,o),u=sl();let p;try{await I6e(c,d,D2(x))?p=await i(_6e(d,u,t,r,n,a)):p={outcome:"cancelled",results:[]}}catch(E){try{await C6e(d,E)}catch(T){h("common.ts").error("handleTTSError failed: "+P(T))}return yE("error",t),[]}if(p.outcome==="cancelled")return yE("cancel",t),p.results;const f=p.results;_K(d,f,a,{requestId:u}),f.some(E=>E.ttsFileInfo.errorInfo===void 0)&&A6e(d);try{await be().fetchUserInfo()}catch(E){h("common.ts").error("handleTTS credit refresh failed: "+P(E))}for(const E of fK(d))zB(E)&&MKe(E,"create"),E.provider===Oe.Voicevox&&Z2e(E);return p.hasFailures?yE("error",t):yE("success",t),f},O6e=e=>{const t=Oh(e),o=gK(e),r=Y2e(e).type;h("common.ts").warn("Type: "+r+", Voice Setting: "+JSON.stringify(t)+", Text Length: "+o)},C6e=async(e,t)=>{O6e(e),Ne(t)?await uK(t):xg(t)?await R6e(t):await pK(t)},R6e=async e=>{switch(h("common.ts").error("ttsPipelineError: "+P(e)),e.message){case $l.NO_TEXT:case $l.INVALID_TEXT:case $l.NO_CLIPS_DELIVERED:case QE.NO_TEXT:case QE.INVALID_TEXT:case QE.END_OF_SCENES:return;case Ef.LOW_VERSION:{const t=Ot(_.C_APP_VERSION_IS_LOW,{defaultKey:"",errorDescKey:"common.no_usage_deduction"});Y().error(_.C_APP_VERSION_IS_LOW,t);return}
4261case Ef.SPEAKER_DELETED:Y().warn(A("tts.deleted_speaker_toast"));return;default:pK(e)}},uK=async e=>(h("common.ts").error("vrewError: "+P(e)),await Y().error(e.errorCode,Ot(e.errorCode,{defaultKey:"error.tts_general_error",errorArg:e.errorArgs,errorDescKey:"common.no_usage_deduction"}))),pK=async e=>{h("common.ts").error("unknown error: "+P(e)),uK(new C(_.C_TTS_GENERAL_ERROR))},yp=(e,t)=>o=>{if(Da(e))return o({type:Wo.SET_TTS_STATUS,payload:{type:Ge.CLIP,status:Object.fromEntries(e.map(({clipId:r})=>[r,t]))}});switch(e.type){case Ge.EFFECT:return o({type:Wo.SET_TTS_STATUS,payload:{type:Ge.EFFECT,audioId:e.audioId,status:t}});case Ge.BATCH:case Ge.DUBBING:return o({type:Wo.SET_TTS_STATUS,payload:{type:e.type,status:t}})}},yvt=()=>{const e=Y().getActiveModal();e===st.TTS&&Y().closeModal(e)},Oh=e=>Da(e)?e[0]?.voiceSetting:e.voiceSetting,fK=e=>{if(!Da(e))return[e.voiceSetting.speaker];const t=new Set,o=[];for(const r of e){const n=r.voiceSetting.speaker.speakerId;!t.has(n)&&(t.add(n),o.push(r.voiceSetting.speaker))}return o},gK=e=>Da(e)?e.reduce((t,o)=>t+Gu(o),0):Gu(e),_K=(e,t,o,r,n="request")=>{const a=t.map(T=>T.ttsFileInfo),i=T=>{if(Da(T))return"clip";switch(T.type){case Ge.EFFECT:return"effect";case Ge.DUBBING:return"dubbing";case Ge.BATCH:switch(T.variant){case La.DOCS:return"pdf";case La.IMAGES:return"image";case La.TTV:return"ttv";case La.SUMMARY:return"summary";case La.ATV:return"atv"}}},s=T=>{switch(Oh(T).speaker.provider){case Oe.Clova:return"clova";case Oe.Google:return"google";case Oe.KT:return"kt";case Oe.VrewVA_deprecated:case Oe.Vrew:return"vrew";case Oe.UserTTS:return"userTTS";case Oe.Wemakevoice_deprecated:return"wemakevoice";case Oe.Voicevox:return"voicevox";case Oe.Polly:return"polly";case Oe.Elevenlabs:return"elevenlabs";case Oe.Gemini:return"gemini";case Oe.Typecast:return"typecast";default:return"unknown"}},x=T=>{if(Da(T))return Gm(T[0]);switch(T.type){case Ge.EFFECT:return rT(T);case Ge.BATCH:return!1;case Ge.DUBBING:return qA(T)}},c=T=>{if(Da(T))return T.length;switch(T.type){case Ge.EFFECT:return 1;case Ge.BATCH:return T.contents.length;case Ge.DUBBING:return T.contents.length}},l=T=>Da(T)?T.filter(O=>O.options?.preprocess?.replaceRules?.length).length:T.options?.preprocess?.replaceRules?.length??0,d=Oh(e),u=gK(e),p=t.reduce((T,O)=>T+(O.chunkTextLength??O.ttsFileInfo.text.processed.length),0),f=ue(a.reduce((T,{duration:O,errorInfo:S})=>T+(S===void 0?O:0),0),2),E={...r,type:i(e),insertOfModify:x(e)?"insert":"modify",isPreview:0,numRequestedTTS:c(e),numGeneratedTTS:a.length,originalTextLength:u,generatedTextLength:p,speakerName:bw(d.speaker.name,d.speaker.provider),speakerId:d.speaker.speakerId,speakerLang:d.speaker.lang,speakerProvider:s(e),isFreeSpeaker:d.speaker.free?1:0,isRecommendedSpeaker:d.speaker.badge==="Recommended"?1:0,emotion:d.emotion??"",acting:UG(d.speaker)?Vs(d.speaker,d.acting)??"":"",effect:d.effect??"",speed:d.speed,pitch:d.pitch,volume:d.volume,duration:f,numInputReplacedTTS:l(e)};if(n==="speaker"){mUe(E,o);return}Xz(E,o),E.speakerProvider==="userTTS"&&ire(E,o)},A6e=e=>{const t=Oh(e),{provider:o,speakerId:r,name:n,lang:a,versions:i}=t.speaker;J3(o,r,n,a,i?.at(-1)??"v1")};let qC;const y6e=()=>(!qC&&(qC=new P8),qC),v6e=(e,t,o)=>{let n=e[t][o+1];if(n===void 0){const i=e[t+1];if(i===void 0)return;n=i[0]}if(n===void 0)return;const[,a,,,]=n;return a},uf=e=>(Dx(e),{id:ct(),captionMode:ar.TRANSCRIPT,captions:Tw(),words:e,startPosition:0,assetIds:[],dirty:{video:!1,caption:!1,blankDeleted:!1},translationModified:{source:!1,result:!1}}),vvt=async(e,t,o,r,n=!0)=>{const{paragraphs:a,language:i,totalDuration:s}=e,x=Math.max(s,o),c=[],l=zn({}),d=ii({}),u=Tt({clips:c,clipsJson:a,totalDuration:x,language:i,audioTotalDuration:s,addClip:!1,splitFirstBlank:!1,trackEntries:l,assetEntries:d}).pipe(At(O=>{const{clipsJson:S}=O;let R=O.addClip;const y=S[0];if(y!==void 0&&y.length>0){let[,,,,,v]=y[0],w=0;for(;v!==Z.NORMAL&&(w++,!(w>=y.length));)[,,,,,v]=y[w];if(w>0&&(R=!0,w<y.length)){const N=y.splice(0,w);S.unshift(N)}}return{...O,addClip:R}}),At(O=>{const{clips:S,clipsJson:R,addClip:y,totalDuration:v}=O;let w=O.splitFirstBlank;return R.forEach((N,M)=>
4261{if(M===0&&!y){const[,B,,,W]=N[0];if(B>=1){const Q=B,{words:j,assetEntries:$,trackEntries:q}=Px(0,Q,W,Z.SILENT,t,void 0,r,n);S.push(uf(j)),Object.entries($).forEach(([H,U])=>{L.set(d,Je(H),U)}),Object.entries(q).forEach(([H,U])=>{L.set(l,kr(H),U)}),w=!0}}const{words:k,assetEntries:F,trackEntries:G}=L6e(R,M,0,N.length,w,i,t,v,r,n);k.length!==0&&(S.push(uf(k)),Object.entries(F).forEach(([B,W])=>{L.set(d,Je(B),W)}),Object.entries(G).forEach(([B,W])=>{L.set(l,kr(B),W)}))}),O}),At(O=>{const{clips:S}=O;if(S.length===0){const{words:R,assetEntries:y,trackEntries:v}=Px(0,x,!1,Z.SILENT,t,void 0,r,n);R&&(S.push(uf(R)),Object.entries(y).forEach(([w,N])=>{L.set(d,Je(w),N)}),Object.entries(v).forEach(([w,N])=>{L.set(l,kr(w),N)}))}return O}),At(O=>{const{clips:S}=O,R=N6e(S);return{...O,stat:R}}),er(O=>{w6e(O.stat)})),{clips:p,stat:f,trackEntries:E,assetEntries:T}=await Bt(u);return{clips:p,stat:f,trackEntries:E,assetEntries:T}},w6e=e=>{const{totalNum:t,mobileTotalNum:o,normalNum:r,silentNum:n,soundNum:a,laughterNum:i,clapNum:s,fillerNum:x,audioEventNum:c}=e,l=o===0?0:r/o;VDe(t,i,s,x,l),t===n?uC(YS.ONLY_SILENT):t===a+c?uC(YS.ONLY_SOUND):uC(YS.SOUND_AND_SILENT)},N6e=e=>{const o={totalNum:0,mobileTotalNum:0,normalNum:0,silentNum:0,soundNum:0,laughterNum:0,clapNum:0,fillerNum:0,audioEventNum:0};return e.forEach(r=>r.words.forEach(n=>{switch(n.type){case Z.ENTER:return;case Z.SILENT:++o.totalNum,o.mobileTotalNum+=Math.ceil(n.duration/1);break;case Z.LAUGHTER:++o.laughterNum;break;case Z.CLAP:++o.clapNum;break;case Z.NORMAL:++o.normalNum;break;case Z.FILLER:++o.fillerNum;break;case Z.AUDIO_EVENT:++o.audioEventNum;break;case Z.SOUND:++o.soundNum;break}n.type!==Z.SILENT&&++o.mobileTotalNum,++o.totalNum})),o},wvt=e=>{const[t,...o]=e;return o.reduce((n,a)=>{const{totalDuration:i,paragraphs:s}=n,x=a.paragraphs.map(u=>u.map(([p,f,E,T,O,S])=>[p,f+i,E+i,T+s.length,O,S])),c=a.sttEngineInfos?a.sttEngineInfos.map(u=>({...u,start:u.start+i,end:u.end+i})):void 0,l=n.timeAligned&&a.timeAligned,d=a.language;return{paragraphs:[...n.paragraphs,...x],timeAligned:l,language:d,totalDuration:n.totalDuration+a.totalDuration,sttEngineInfos:n.sttEngineInfos&&c?[...n.sttEngineInfos,...c].sort((u,p)=>u.start-p.start):n.sttEngineInfos??c,sttType:n.sttType??a.sttType,lineBreakVersion:n.lineBreakVersion??a.lineBreakVersion}},t)},Nvt=(e,t,o,r,n=!0)=>{const{words:a,assetEntries:i,trackEntries:s}=Px(0,e,!0,Z.SOUND,t,o,r,n);return{clip:uf(a),assetEntries:i,trackEntries:s}},Pvt=(e,t,o,r,n,a=!0)=>{const i=[],{words:s,assetEntries:x,trackEntries:c}=Px(0,e,!0,Z.SOUND,t,o,n,a);for(;s.length!==0;){const l=s.splice(0,r);i.push(uf(l))}return{clips:i,assetEntries:x,trackEntries:c}},EK=(e,t)=>{if(!e&&!t)return;const o={trackIds:[e,t].filter(Se),role:"main",rangeType:tr.WORD},r=ho();return{asset:o,assetId:r}},Px=(e,t,o,r,n,a=5,i,s=!0)=>{const x=Math.max(1,Math.ceil(t/a)),c=[],l=zn({}),d=ii({});for(let u=0;u<x;u++){const p=ue(e+a*u,2),f=ue(u===x-1?t-a*u:a,2),E=i!==void 0?pT(Rt(),n,i,he.INIT,0,{role:"main",sourceIn:pe(p),sourceOut:yh(pe(p),pe(f))},!0):void 0;E&&L.set(l,E.trackId,E);const T=s?zK(Rt(),n,ze.VideoAudio,{volume:ma,sourceIn:pe(p),sourceOut:yh(pe(p),pe(f)),loop:!1,playbackRate:ur(1)},!0):void 0;T&&L.set(l,T.trackId,T);const O=EK(E?.trackId,T?.trackId);O&&L.set(d,O.assetId,O.asset),c.push({id:ct(),text:"",timelineStart:pe(p),duration:pe(f),playbackRate:Un,type:r,aligned:o,originalStartTime:p,originalDuration:f,truncatedWords:[],assetIds:O?[O.assetId]:[]})}return{words:c,assetEntries:d,trackEntries:l}},P6e=(e,t,o,r,n,a,i=!0)=>{const s=Px(t,o,r,Z.AUDIO_EVENT,n,o>0?o:void 0,a,i);return{...s,words:s.words.map(x=>({...x,text:e}))}},b6e=(e,t,o,r,n,a,i=!0)=>{const s=zn({}),x=ii({}),c=a!==void 0?pT(Rt(),t,a,he.INIT,0,{role:"main",sourceIn:pe(o),sourceOut:yh(pe(o),pe(r))},!0):void 0;c&&L.set(s,c.trackId,c);const l=i?zK(Rt(),t,ze.VideoAudio,{volume:ma,sourceIn:pe(o),sourceOut:yh(pe(o),pe(r)),loop:!1,playbackRate:ur(1)},!0):void 0;l&&L.set(s,l.trackId,l);const d=EK(c?.trackId,l?.trackId);return d&&L.set(x,d.assetId,d.asset),{wordModel:{id:ct(),text:e,timelineStart:pe(o),duration:pe(r),playbackRate:Un,type:Z.NORMAL,aligned:n,originalStartTime:o,originalDuration:r,truncatedWords:[],assetIds:d?[d.assetId]:[]},assetEntries:x,trackEntries:s}},L6e=(e,t,o,r,n,a,i,s,x,c=!0)=>{const l=[],d=ii({}),u=zn({}),p=e[t];for(let f=o*r;f<Math.min((o+1)*r,p.length);f++){const[E,T,O,,S,R]=p[f],y=Math.max(0,ue(O-T,2));if(t===0&&f===0&&T>0&&!n){const F=T,{words:G,assetEntries:B,trackEntries:W}=Px(0,F,S,Z.SILENT,i,void 0,x,c);
4261l.push(...G),Object.entries(B).forEach(([Q,j])=>{L.set(d,Je(Q),j)}),Object.entries(W).forEach(([Q,j])=>{L.set(u,kr(Q),j)})}const w=v6e(e,t,f),N=w!==void 0?Math.max(0,w-O):Math.max(0,s-(T+y)),M=T0e(N),k=M?y+N:y;switch(R){case Z.NORMAL:{const F=E&&!VCe(a)?WCe(E):E,{wordModel:G,assetEntries:B,trackEntries:W}=b6e(F,i,T,k,S,x,c);l.push(G),Object.entries(B).forEach(([Q,j])=>{L.set(d,Je(Q),j)}),Object.entries(W).forEach(([Q,j])=>{L.set(u,kr(Q),j)});break}case Z.AUDIO_EVENT:{const{words:F,assetEntries:G,trackEntries:B}=P6e(E,T,k,S,i,x,c);l.push(...F),Object.entries(G).forEach(([W,Q])=>{L.set(d,Je(W),Q)}),Object.entries(B).forEach(([W,Q])=>{L.set(u,kr(W),Q)});break}case Z.LAUGHTER:case Z.CLAP:case Z.FILLER:{const{words:F,assetEntries:G,trackEntries:B}=Px(T,k,S,R,i,void 0,x,c);l.push(...F),Object.entries(G).forEach(([W,Q])=>{L.set(d,Je(W),Q)}),Object.entries(B).forEach(([W,Q])=>{L.set(u,kr(W),Q)});break}default:{const{words:F,assetEntries:G,trackEntries:B}=Px(T,k,S,Z.SOUND,i,1,x,c);l.push(...F),Object.entries(G).forEach(([W,Q])=>{L.set(d,Je(W),Q)}),Object.entries(B).forEach(([W,Q])=>{L.set(u,kr(W),Q)})}}if(M===!1){const{words:F,assetEntries:G,trackEntries:B}=Px(O,N,S,Z.SILENT,i,void 0,x,c);l.push(...F),Object.entries(G).forEach(([W,Q])=>{L.set(d,Je(W),Q)}),Object.entries(B).forEach(([W,Q])=>{L.set(u,kr(W),Q)})}}return{words:l,assetEntries:d,trackEntries:u}},bvt=e=>{const t=e===rm.OVERDUB?Dp.EXAMPLE:Mbe()?Dp.ONBOARDING:Dp.EXAMPLE;return async(o,r)=>{try{const n=new Jo,a=Lt(),i={updateProgress:()=>{}},s=await ICe(t);await a.redeemProject(s);const x=at()?await new Oi().createTempFolder(["vrew"]):"",c=await a.downloadCloudProject(s,s,vE,x,i,new AbortController,!0);if(c.result!=="success")throw new Error("Failed to download demo project");if(at()){const d=a0(x,vE),u=a0(d,fg),p=a0(d,vE+".vrew");se().setSampleProjectSourceDir(u),await o(ag({loadingType:"demo",filePath:p}))}else await o(ag({loadingType:"demo",filePath:c.projectId}));o(qx.ActionCreators.clearHistory());const l=n.getElapsedSec();if(mke(l),pP(g.BOOT_ENTER_AFTER_LOAD_DEMO),h("transcript.ts").info("Demo for "+t+" loaded in "+l+"s"),e===rm.OVERDUB){o(K8()),a1e(g.FEATURE_ONBOARDING_MODAL_OPEN),Y().openModal(st.OVERDUB_ONBOARDING);return}t===Dp.ONBOARDING&&(jUe(),kbe(()=>fs(r()),()=>o(Xx(Fr.ONBOARDING_TOUR,!0))),o(xKe()))}catch(n){h("transcript.ts").error("DemoLoadFailed: "+P(n)),xt.error(A("error.demo_load_failed")),hke(),Lt().resetSharedProject()}}},M6e=(e,t)=>Object.fromEntries(Object.entries(e).map(([o,r])=>rG(r)?[o,{...r,stats:{...r.stats,sourceTemplateName:t}}]:[o,r])),mK=(e,t,o,r,n)=>async a=>{const{files:i,globalClips:s,props:x,comment:c,projectId:l}=e,d=oJe(s,e.sceneNames),{loadingType:u}=n,p=n.loadingType==="template"?n.addSceneIndex:null,f=u==="demo"?"demo":u==="template"?"template":void 0,E=p!==null,T=E?{dispatchType:o,files:i,blobs:t,analyzeDate:x.analyzeDate}:vd({files:i,blobs:t,dispatchType:o,projectOption:{fromIOS:/iOS/.test(c||""),props:x,fromAutosave:n.loadingType==="userProject"?n.fromAutosave:!1,projectId:l,currentPath:r,sampleProjectType:f},analyzeDate:x.analyzeDate});await a(T0(T));const O=_N(d),S=Zg(x.baseAssetEntries,O);let R=[],y;if(u==="userProject"||u==="cloud")try{const{messages:M,issueFlags:k}=D6e(x,s,S);R=M,y=k}catch(M){h("transcript.ts").error("[loadProject] Asset structure check failed: "+P(M)),R=[],y=void 0}const v={...x,assetEntries:S};let w=d,N=v;if(E){const{remappedSceneInfos:M,remappedProps:k}=J9e(d,v);w=M,N=k}if(n.loadingType==="template"&&(N={...N,trackEntries:M6e(N.trackEntries,n.templateName)}),a(ig(w,p,N,e.translateInfo,x.projectAudioLanguage,x.originalClips)),(n.loadingType==="userProject"||n.loadingType==="cloud")&&y5e({type:o,projectId:l,savePath:r}),R.length>0){h("transcript.ts").error("[loadProject] Asset structure issues detected: "+R.join(" | "));const M=_.C_VREW_FILE_ASSET_INCONSISTENT,k=Ot(M,{defaultKey:"  "});Y().error(M,k,void 0,{assetStructureIssueFlags:y})}},D6e=(e,t,o)=>{const r=[],n={mainAssetInClip:!1,duplicateMainAsset:!1,mainAssetRangeTypeClip:!1,missingAssetEntry:!1,trackReferencedByMultipleAssets:!1,assetWithoutTrack:!1,missingTrackEntry:!1},a=Object.entries(o).map(([T,{role:O,rangeType:S}])=>{const R=Je(T);if(O==="main"&&S!==tr.WORD)return R}).filter(Se);a.length>0&&(n.mainAssetRangeTypeClip=!0,r.push("Main asset rangeType is not word: "+a.join(", ")));const i=new Set,s=T=>{if(!L.get(o,T)){i.add(T);return}},x=T=>{T.assetIds.forEach(O=>s(O)),T.truncatedWords.forEach(O=>{O.assetIds.forEach(S=>s(S))})},c=T=>{T.forEach(O=>{O.assetIds.forEach(S=>s(S)),O.words.forEach(S=>x(S))})};c(t),c(e.originalClips);for(const T of Object.values(e.overdubInfosMap))for(const O of T.originWords)for(const S of O.assetIds)s(S);i.size>0&&(n.missingAssetEntry=!0,r.push("Missing asset referenced in word/clip: "+[...i].join(", ")));const l=new Map,d=[],u=new Set;
4261Object.entries(o).forEach(([T,O])=>{if(O.trackIds.length===0){d.push(Je(T));return}O.trackIds.forEach(S=>{const R=kr(S);!L.get(e.trackEntries,R)&&u.add(R);const y=l.get(R)??new Set;y.add(Je(T)),l.set(R,y)})});const p=[...l.entries()].filter(([,T])=>T.size>1).map(([T])=>T);p.length>0&&(n.trackReferencedByMultipleAssets=!0,r.push("Track referenced by multiple assets: "+p.join(", "))),d.length>0&&(n.assetWithoutTrack=!0,r.push("Asset has no tracks: "+d.join(", "))),u.size>0&&(n.missingTrackEntry=!0,r.push("Missing track referenced in assets: "+[...u].join(", ")));const f=new Li(e.overdubInfosMap,void 0,e.trackEntries,o).collectFrom({type:Or.GLOBAL_CLIP,model:t},{checkDuplicateMainAsset:!0}).collectFrom({type:Or.GLOBAL_CLIP,model:e.originalClips}),E=f.getIntegrityIssueFlags();return n.duplicateMainAsset=E.duplicateMainAsset,n.mainAssetInClip=E.mainAssetInClip,r.push(...f.getIntegrityErrorMessages()),{messages:r,issueFlags:n}},k6e=async(e,t=!1)=>{const o=h("transcript.ts"),r=sessionStorage.getItem(Wt.VCLOUD_SESSION_ID),n=r??Cn();return await M7(e,n)?(r!==n&&sessionStorage.setItem(Wt.VCLOUD_SESSION_ID,n),n):(o.info("this project is being edited by another session. projectId: "+e+"."),t?(o.info("init is true. return null. projectId: "+e+"."),null):(qz(e,"load"),await n_e()!==mt.YES?(o.info("vCloudProjectAlreadyOpenedWarning is not YES. return null. projectId: "+e+"."),null):(o.info("force acquiring editing session. projectId: "+e+". newSessionId: "+n),await FOe(e,n),sessionStorage.setItem(Wt.VCLOUD_SESSION_ID,n),Y().closeModal(st.OPEN_PROJECT),n)))},Lvt=(e,t=!1)=>async o=>{const r=h("transcript.ts"),n=new Jo,a=new AbortController,i=m0(Sa(A("vcloud.project_loading",{progress:0}),{onCancel:()=>{a.abort(),r.info("cloud project loading is aborted by user")}}));try{await Lt().syncCloudProjects();const s=Lt().getVCloudProjectInfo(e);if(!s)throw r.info("projectInfo is null. invalid project id: "+e),new C(_.C_LOGIC_ERROR);if(!Lt().isEditableCloudProject(e))throw r.error("this project is not editable. projectId: "+e),new C(_.C_LOGIC_ERROR);const c=await k6e(e,t);if(!c)return r.info("sessionId is null. invalid project id: "+e+" return false"),!1;const l=s.snapshotId;if(!l)throw r.info("snapshotId is null. invalid project id: "+e),new C(_.C_LOGIC_ERROR);const d=await av(e,l);if(!d)throw r.info("cloudVrewJson is null. invalid project id: "+e),new C(_.C_LOGIC_ERROR);if(d.version>Be.CURRENT_VREW_JSON_VERSION)throw new C(_.C_VREW_FILE_INCOMPATIBLE_VERSION);const u=y=>{i.message(Sa(A("vcloud.project_loading",{progress:Math.round(y.progressRatio*100)}),{onCancel:()=>{a.abort(),r.info("cloud project loading is aborted by user")}}))};await ol(e);const p=await Xae(e,d,u,a),f=await H2(d,p),{files:E,globalClips:T,blobs:O}=f;if(a.signal.aborted)return i.dismiss(),!1;if(E.length<=0||T.length<=0)throw new C(_.C_LOGIC_ERROR);const S=n.getElapsedSec();return Y5(s.projectTitle,s.totalSize,T,f.statistics?.saveInfo,E,S,Ee.CLOUD).catch(y=>{h("transcript.ts").error("Error during getting fileInfo: "+P(y))}),await o(mK(f,O,Ee.CLOUD,""+s.projectTitle,{loadingType:"cloud"})),o(wK()),n0.getInstance().startPolling(e,c),Ev(f)&&await mv(_v()),await Lt().syncCloudProjects(),Ve().set(Ie.LAST_PROJECT_ID,e),Ve().set(Ie.LAST_PROJECT_TYPE,Ee.CLOUD),!0}catch(s){const x=ye(s)??_.C_VREW_FILE_READ_ERROR;if(a.signal.aborted||x===_.C_VCLOUD_USER_DOWNLOAD_CANCELED)return r.info("Cloud project loading was canceled by user"),!1;r.error("Error occured while loading vcloud project. error: "+P(s)),eS(x,"[loadCloud "+e+"] "+P(s));const c=Ot(x,{defaultKey:"cloud_project_err"});return xt.error(c),!1}
4261finally{i.dismiss()}},ag=e=>async(t,o)=>{const{loadingType:r,filePath:n}=e,a=at()?Nu(gt(n)):await Kf(n)??"";r==="userProject"&&a===""&&h("transcript.ts").error("can't find project name with projectId: "+n);const i=new AbortController,s=new Promise(l=>{i.signal.onabort=()=>l()}),x=r==="userProject"?"vrewfile.loading":void 0,c=x===void 0?null:m0(Sa(A(x,{projectName:a}),{onCancel:()=>{i.abort(),h("transcript.ts").info("project loading is aborted by user")}}));try{if(await qt().checkFfmpegExist(!0)===!1&&await qt().downloadFfmpeg(!0),await j6e(n))throw new C(_.C_CUSTOM_PROJECT_LIST_OPEN_ERROR);const d=await Promise.race([Fwe((e.loadingType==="userProject"?e.askFindLostVideoParam:void 0)??Xwe,(e.loadingType==="userProject"?e.warnDifferentMediaDurationParam:void 0)??Jwe,n,e.loadingType==="template"&&e.addSceneIndex!==null),s.then(()=>{})]);if(!d)return c?.dismiss(),!1;const{vrewFileData:u,pathModified:p,elapsed:f,fileSize:E}=d,{files:T,globalClips:O,props:S,blobs:R,projectId:y,statistics:v}=u;if(T.length<=0||O.length<=0)throw new C(_.C_LOGIC_ERROR);if(i.signal.aborted)return c?.dismiss(),!1;const w=e.loadingType==="userProject"?e.autosaveTargetPath:void 0,N=w||n,M=w!==void 0,k=r!=="userProject"||M&&!CD(N)?Ee.MEDIA:at()?Ee.PROJECT:Ee.BROWSER;Y5(n,E,O,u.statistics?.saveInfo,T,f,k).catch(j=>{h("transcript.ts").error("Error during getting fileInfo: "+P(j))});const F=e.loadingType==="template"?{loadingType:"template",addSceneIndex:e.addSceneIndex,templateName:e.templateName}:e.loadingType==="userProject"?{loadingType:"userProject",fromAutosave:M}:{loadingType:"demo"};if(await t(mK(u,R,k,N,F)),S.lastTTSSettings&&Hg(S.lastTTSSettings),p&&CD(N)){const j=o(),$=ZP(j,u.projectId);await cP(Ee.PROJECT,N,N,u,!1,0,$)}t(s9e(S.videoRatio,mi.MINT));const G=_Ee(N);t(Jze(G));const B=gEe(N);B!==null&&t(T_(B)),Ev(u)&&await mv(_v()),r==="userProject"&&v&&Yo().resetFromJson(v),r==="userProject"&&(Ve().set(Ie.LAST_PROJECT_ID,y),Ve().set(Ie.LAST_PROJECT_TYPE,k)),Mt(ke.PREPARE_PROXY)&&await _3(()=>t(HB(!0)),()=>t(z8("auto")))}catch(l){c?.dismiss();const d=ye(l)??_.C_VREW_FILE_READ_ERROR;d!==_.C_VREW_FILE_BROKEN&&d!==_.D_ERR_VREW_FILE_BROKEN&&h("transcript.ts").error(P(l)),mP(d);const u=Ot(d,{errorArg:{...Ho(l),filePath:n,interpolation:{escapeValue:!1}},defaultKey:"vrewfile.load_failed"});return Y().error(d,u),!1}return c?.asClosable(1e3),!0},Mvt=()=>async e=>{await $e().initTTSSpeakerList();const t=ct(),o=tP(),{clips:[r],trackEntries:n,assetEntries:a}=Qpe(o.dummyAudioInfo.videoAudioMetaInfo.duration,[t],void 0,void 0),i=us(),s=spe(i,o.dummyAudioInfo.videoAudioMetaInfo.duration),x={[o.dummyAudioInfo.mediaId]:s},c=b2({width:1920,height:1080},{tracks:n,assets:a},he.WIDE_SCREEN,x),l=qe.v4(),d={props:c,currentPath:A("startmode.untitled"),projectId:l},u=ct(),p={clipDispatchRange:gn.NEW_PROJECT,audioLanguage:pn.None,clips:[r],projectProperty:c,newSourceOption:zg([o.dummyAudioInfo],{[o.dummyAudioInfo.mediaId]:o.dummyAudioBlob},d,Ls.TTS),sceneId:u};await e(ip(p)),e(oK(t)),!Ta(It.TTS_INSERTED)&&e(Cl(Ct.TTS_NEW_USER,Fr.TTS_NEW_USER))},Dvt=()=>async(e,t)=>{const o=Uw(void 0,void 0,5,ct()),r=b2({width:1920,height:1080},void 0,he.WIDE_SCREEN),n=fT(),a={...n,newProjectOption:{props:r,projectId:qe.v4(),currentPath:A("startmode.untitled")}},i=[{id:ct(),clips:[o]}];await e(T0(a));const{trackEntries:s,baseAssetEntries:x,videoRatio:c}=r,l=await OT(t),d=Object.values(s).find(Rr),u=l&&!d?await ST(mi.BLACK,c):void 0,p=u?{...s,[u.trackId]:u}:s,f=_N(i),E=Zg(x,f),T={...r,assetEntries:E,trackEntries:p};e(ig(i,null,T,null,pn.None))},kvt=e=>(t,o)=>{if(Oa())return Ca(),{removed:!1,reason:"videoLocked"};const r=o(),n=mo(r);if(n.length===e.length)return xt.warn(A("scene.delete_warning")),{removed:!1,reason:"projectWouldBeEmpty"};const a=e.map(l=>n.findIndex(d=>d.id===l)),i=k4(a),s={type:ot.REMOVE_SCENES,payload:{selectedSceneChunks:i}};t(s);const x=mo(o());return{removed:!0,removedSceneCount:n.length-x.length}},Fvt=e=>(t,o)=>{if(Oa()){Ca();return}const r=o(),n=mo(r),a=e.map(x=>n.findIndex(c=>c.id===x)),i=k4(a),s={type:ot.MERGE_SCENES,payload:{selectedSceneChunks:i}};return t(s)},Uvt=e=>(t,o)=>{if(Oa()){Ca();return}const r=o(),n=mo(r),a=He(r),i=zs(r),s=Nn(r),x=lt(r),c=ht(r),l=new Set(Array.from(s).filter(d=>{const u=a[d];return L.get(i,u.clipId)?.shouldRenderAsTTSClip!==!0}));return bz(l.size,sp(n,x,c).length,$P.CUT),t({type:ot.CUT_SELECTED_CLIPS_TO_NEW_SCENE,payload:{sceneId:e,targetGlobalClipIndicesSet:l}})},Vvt=(e,t)=>(o,r)=>{if(Oa()){Ca();return}const n=r(),a=mo(n),i=He(n),s=zs(n),x=Nn(n),c=lt(n),l=ht(n),d=new Set(Array.from(x).filter(u=>{const p=i[u];return L.get(s,p.clipId)?.shouldRenderAsTTSClip!==!0}));return bz(d.size,sp(a,c,l).length,$P.COPY,t),o({type:ot.COPY_SELECTED_CLIPS_TO_NEW_SCENE,payload:{sceneId:e,targetGlobalClipIndicesSet:d}})},Gvt=(e,t)=>{const o=e.map(KYe);return o.forEach(r=>{const n=JYe(r.highlightClipIndices,t);Yo().updateVideoRemixInfo(r.sceneId,n)}),{type:ot.MAKE_HIGHLIGHT_SCENE,payload:{highlightScenePayloads:o}}},hK=(e,t,o="selection")=>(r,n)=>{if(Oa())return Ca(),{deleted:!1,reason:"videoLocked"};const a=n(),i=He(a);if(o==="selection"){const x=ds(a);if(x!==null){const c=Yv(x);return uk(!0,c.to-c.from,t),r({type:ot.DELETE_CUTS,payload:{backSpace:!1}}),{deleted:!0}
4261}}const s=iH(i,e,!0);return s<0?{deleted:!1,reason:"wordNotFound"}:(uk(!1,1,t),r(T_(s)),r({type:ot.DELETE_CUTS,payload:{backSpace:!1}}),{deleted:!0})},Wvt=(e,t,o)=>(r,n)=>{r(hK(e)),!(!kye()||Ta(It.WORD_DELETE_BUTTON_QUICK_TOOLTIP)||o!==Ct.NONE||!He(n()).some(i=>i.clipId===t))&&(ir().set(Wt.LAST_CLICK_WORD_DELETE_BUTTON_CLIP_ID,t),r(Cl(Ct.CLICK_WORD_DELETE_BUTTON,Fr.CLICK_WORD_DELETE_BUTTON)),wn(It.WORD_DELETE_BUTTON_QUICK_TOOLTIP))},QC=e=>(t,o)=>{if(Oa())return Ca(),{deleted:!1,reason:"videoLocked"};const r=o(),n=He(r);return Vxe(r).length===n.length?(Y().warn(A("transcript.empty_scene_not_allowed")),{deleted:!1,reason:"projectWouldBeEmpty"}):(Uye(),t({type:ot.DELETE_CUTS,payload:{backSpace:e}}),{deleted:!0,deletedClipCount:n.length-He(o()).length})},Hvt=e=>t=>Oa()?(Ca(),t):t({type:ot.DELETE_SELECTED,payload:{selectedWords:e}}),jvt=(e,t,o)=>({type:ot.UPDATE_WORD_TEXT_PRONUNCIATION,payload:{wordId:e,text:t,pronunciation:o}}),zvt=(e,t,o)=>({type:ot.ADJUST_WORD_EDGE,payload:{position:e,side:t,sourceDeltaTime:o}}),Yvt=(e,t,o)=>({type:ot.ADJUST_SHARED_WORD_BOUNDARY,payload:{prevPosition:e,nextPosition:t,sourceDeltaTime:o}}),Bvt=(e,t)=>({type:ot.SPLIT_WORD,payload:{position:e,splitTime:t}}),Kvt=(e,t,o)=>(r,n)=>{const a=n(),i=Do(a),s=Lg(a),x=CW(a);if(x===void 0||s===void 0)return;const c=x.wordPositionRange,l=Ar(on(tc(a))),d=sn(i,e),u=sn(i,t),p=O0e(d,u,l);r({type:ot.MERGE_WORDS,payload:{prevPosition:e,nextPosition:t,direction:o,...p}});const f=Ece(c,s,i,o,e,t);r(gze(f)),o==="left"&&r(U8())},Xvt=(e,t=!1,o=[])=>({type:ot.DELETE_BLANKS,payload:{isIncludeSound:t,truncateSec:e,targetBlankInfos:o}}),Jvt=()=>({type:ot.REVERT_BLANKS}),qvt=e=>async(t,o)=>{if(Oa()){Ca();return}const r=o(),n=Od(r),a=Eye(r),i=jo(r),s=He(r),x=AW(r),c=Sl(r);!eo(_o)&&await t(bd());const d=Mt(e?ke.FREEZE_WORD_TIME:ke.SPACER_TIME);let u=!1,p;if(n.length>0)p=n.map(O=>{const S=s[O],R=S.words.length-1;return{globalClipIndex:O,insertionWordIndices:[R]}});else if(a.length>0&&x===null){const O=new Map;a.forEach(S=>{const R=Er(s,S),y=s[R],v=S+1-y.startPosition;!O.has(R)&&O.set(R,[]),O.get(R).push(v)}),p=Array.from(O.entries()).map(([S,R])=>({globalClipIndex:S,insertionWordIndices:R})),c===kn.SEARCH_REPLACE&&(u=!0)}else if(i.cursorMode===we.INSERT_CURSOR&&x===null&&i.globalPosition!==null){const O=Er(s,i.globalPosition),S=s[O],R=i.globalPosition-S.startPosition;p=[{globalClipIndex:O,insertionWordIndices:[R]}]}else return;const f=Mt(ke.AUTO_FIT_SPACER_TO_VIDEO);let E;if(f){const{spacerTargets:O,autoFitApplied:S}=gde(p,s,ht(r),lt(r),d);E=O,Nze({blankWordFreeze:e??!1,blankWordTotalTargets:p.length,blankWordAutoFitApplied:S})}else E=p.map(O=>({...O,playDuration:d}));const T={type:ot.ADD_SPACER,payload:{freeze:e,targets:E}};t(T),u&&(t(f1e()),t(p1e()),t(q8()))},Qvt=e=>(t,o)=>t({type:ot.CHANGE_SPACER_TIME,payload:{targetGlobalPositions:$0(o()),duration:e}}),Zvt=()=>(e,t)=>{const o=t(),r=Dg(o),n=rt(o),a=Mg(o),i=Tn(o),{position:s}=i;if(s===null)return h("transcript.ts").warn("Position is null in showOriginalView"),e;if(a)return h("transcript.ts").warn("Tried to trigger originalView when showOriginal is already true."),e;const x={type:ot.SHOW_ORIGINAL_TRANSCRIPT,payload:{originalTranscript:r,workingTranscript:n}};return e(x)},IK=e=>(t,o)=>{const r=o(),n=Ixe(r),a=Mg(r),i=bg(r),s=i.length;if(!a)return h("transcript.ts").warn("Tried to revert original view when showOriginal is already false"),t;if(e){const c=s===0?"original_view.close_message_words_copied":s===1?"original_view.close_message_clips_copied":"original_view.close_message_clips_copied_plural";xt.info(A(c,{count:s}))}const x={type:ot.SHOW_WORKING_TRANSCRIPT,payload:{workingTranscript:n}};return t(x)},eU=e=>(t,o)=>{const r=o(),n=yxe(r),a=q0(),i=Zx(r);if(QT(r)===st.NULL){if(W5(n)){Ca();return}else if(a){if(i!==we.CAPTION)return;if(n!==_r.UPDATE_CAPTION)return}uDe(e,n),t(qx.ActionCreators.undo()),setTimeout(()=>jW(o),0)}},F6e=()=>(e,t)=>{const o=t(),r=o.snapshots.future.length>0,n=q0(),a=Zx(o);if(r){const i=o.snapshots.future[0].action.lastUndoableActionType;if(W5(i)){Ca();return}else if(n){if(a!==we.CAPTION)return;if(i!==_r.UPDATE_CAPTION)return}}e(qx.ActionCreators.redo()),jW(t)},$vt=()=>(e,t)=>{const o=t(),r=yv(o),n=r===null||Zc(r)?qa.DEFAULT:qa.CLIPS;if(JW(o,n)!==!1)return e({type:ot.MERGE_CLIPS,payload:{mergeTarget:n}})},TK=(e,t=!1,o)=>(r,n)=>{const a=n(),i=rt(a),s=Do(a),x=lI(a),c=ds(a),l=yv(a),d=pI(i),u=Zc(l);if(x===null)return;const p=Co(s,x);if(uH(d)&&tl(s,p))return;const f=Kv(x,d),E=Xv(x,d),T=!c&&(f||E||u),O=T?o0.SYS_AUTO:o0.USER_REQ;return o?sk(t,e,O,$T(o)):sk(t,e,O,void 0,f?"front":E?"end":void 0),r({type:ot.DIVIDE_CLIP,payload:{shift:t}})},ewt=e=>({type:ot.DIVIDE_CLIPS_BY_WORD_IDS,payload:{startWordIds:e}}),twt=e=>(t,o)=>{const r=Do(o()).length,n={from:0,to:r,type:"CLIP"};return t({type:ot.DIVIDE_CLIPS_BY_WORD_LENGTH,payload:{chunks:[n],wordThreshold:e}})},Xd=e=>(t,o)=>{const r=o();if(JW(r,e)!==!1)return t({type:ot.MERGE_CLIPS,payload:{mergeTarget:e}})},owt=(e,t)=>
4261(o,r)=>{const n=r(),a=Tn(n),i=q0();qW(a,i)!==!1&&o(TK(e,!1,t))},U6e=(e,t)=>o=>(t.preventDefault(),e(o)),V6e=e=>async t=>{if(e.length===0)return;ake("keyboard",e.map(B9e));const o=e.map(r=>({elementId:r.elementId,elementType:r.element.type}));t(vK(o))},G6e=e=>async t=>{t(wB(e))},rwt=e=>async(t,o)=>{const r=o(),n=fs(r),a=U6e(t,e),i=lt(r),s=ht(r),x=Tn(r),c=Do(r),l=Mg(r),{position:d,globalClipRange:u,cursorMode:p,selectedElements:f,selectedWatermarkId:E}=x,T=q0(),O=QT(r),S=ZYe(e),R=h("transcript.ts");if(d===null)return R.error("transcript redux have invalid position during keyDownAction "+S+"."),t;if(c.length===0)return t;const y=Co(c,x.position),v=c[y];if(c===void 0||c.length===0)return S===J.UNDO?(ik(),eU(!0)(a,o)):t;const w=(U,te)=>(RDe(U),cze(te)(a,o)),N=(U,te)=>(ADe(U),lze(te)(a,o)),M=(U,te)=>(e.preventDefault(),hDe(U===we.CAPTION,!1),Z5e(te)(a,o)),k=(U,te)=>(e.preventDefault(),IDe(U===we.CAPTION,!1),Q5e(te)(a,o)),F=(U,te)=>(ODe(U),dze(te)(a,o)),G=(U,te)=>(CDe(U),uze(te)(a,o)),B=U=>Eze(U)(a,o),W=U=>_ze(U)(a,o),Q=U=>(TDe(),eze(U)(a,o)),j=U=>(SDe(),$5e(U)(a,o)),$=()=>{e.preventDefault()},q=(U,te=uo.PLAY_DEFAULT)=>(e.preventDefault(),mh(U,te)(t,o)),H=[J.ENTER,J.SHIFT_ENTER,J.F2,J.BACKSPACE,J.DELETE,J.CUT,J.PASTE,J.UNDO,J.REDO,J.MERGE_CLIPS,J.MERGE_CLIPS_2,J.MERGE_PREVIOUS_CLIP,J.MERGE_PREVIOUS_CLIP_2,J.SAVE,J.SAVE_AS,J.TRANSLATE,J.INSERT_MARKER_RECENT,J.F7,J.SHIFT_F7,J.MOD_F7,J.SHIFT_MOD_F7,J.F8,J.MOD_F8,J.CTRL_B,J.SHIFT_MOD_B,J.OPEN_PROJECT,J.CLOSE,J.FEATURE_SEARCH];if(l&&S!=="NOTHING"&&H.includes(S)){e.preventDefault();return}switch(S){case J.ENTER:case J.SHIFT_ENTER:{const U=S===J.SHIFT_ENTER;return p===we.ELEMENT&&!U&&(IUe(f.length),a(bK))?t:(p===we.INSERT_CURSOR||p===we.CLIP)&&qW(x,T)===!0?TK(io.KEY,U)(a,o):p===we.CORRECTING?yF(Tu.ENTER_KEY,void 0,U)(a,o):void 0}case J.ESCAPE:case J.SHIFT_ESCAPE:{e.preventDefault();const U=S===J.SHIFT_ESCAPE;return T?mh(pr.ESCAPE)(t,o):tze(U)(a,o)}case J.F2:return yF(Tu.F2_KEY)(a,o);case J.PLAY_SPACE:return FD()&&n.tourInfo.type===Ct.NONE&&WF(Ct.TABKEY_PLAY,Fr.TABKEY_PLAY)(a,o),Gye(),q(pr.SPACE);case J.PLAY_P:{FD()&&n.tourInfo.type===Ct.NONE&&WF(Ct.TABKEY_PLAY,Fr.TABKEY_PLAY)(a,o);const{globalWordRange:U}=x,te=U?uo.PLAY_DEFAULT:uo.PLAY_CLIP;return q(pr.CTRL_P,te)}case J.LEFT:case J.SHIFT_LEFT:return U8(e.shiftKey)(a,o);case J.RIGHT:case J.SHIFT_RIGHT:return sze(e.shiftKey)(a,o);case J.UP:case J.SHIFT_UP:return AF(-1,-1,e.shiftKey,Bx.KEYBOARD_UP,void 0)(a,o);case J.DOWN:case J.SHIFT_DOWN:return AF(-1,-1,e.shiftKey,Bx.KEYBOARD_DOWN,void 0)(a,o);case J.DELETE:case J.BACKSPACE:{if(T)return null;const U=S===J.BACKSPACE;if(p===we.ELEMENT){const te=f.map(ne=>{const oe=L.get(s,ne.id);if(!oe)return;const re=oe.trackIds.map(ge=>L.get(i,ge)).filter(ge=>ge!==void 0&&(xr(ge)||cd(ge))&&!Rr(ge));if(re.length!==0)return{elementId:ne.id,element:re[0],rangeType:oe.rangeType}}).filter(Se);V6e(te)(a);break}else if(p===we.WATERMARK){if(E===null){h("transcript.ts").warn("cursorMode is "+we.WATERMARK+" but no watermarkId");break}return x9e()(a,o)}else{if(x.globalClipRange!==null)return U?dC(so.CLIP):lC(so.CLIP),a(QC(U));if(x.globalWordRange!==null)return U?dC(so.WORD):lC(so.WORD),a(QC(U));if(U){if(Kv(d,v))return jd(Is.BACKSPACE,o0.USER_REQ),Xd(qa.PREV)(a,o)}else if(Xv(d,v))return jd(Is.DELETE,o0.USER_REQ),Xd(qa.NEXT)(a,o);return U?dC(so.WORD):lC(so.WORD),a(QC(U))}}case J.SELECT_ALL:if(xze()(a),p===we.ELEMENT){const U=x.selectedFromAssetList?"asset_list":"asset_cursor";lDe(U),a(nze(!0)),a(Mze("asset")),a(Lze(!0))}else cDe();break;case J.SAVE:{if(await OA("save"),O!==st.NULL||!at()&&!await Vn("keyCommandSave"))return;const U=se().getSaveProjectType();return sDe(U),a(tU(!1,U))}case J.SAVE_AS:{if(await OA("save"),O!==st.NULL||!at()&&!await Vn("keyCommandSaveAs"))return;const U=se().getSaveProjectType();return xDe(U),a(tU(!0,U))}case J.COPY:return rBe(io.KEY,l)(a,o);case J.CUT:{p===we.ELEMENT?G6e(io.KEY)(a):xxe(r)||wB(io.KEY)(a,o);break}case J.PASTE:return sBe(io.KEY)(a,o);case J.UNDO:return ik(),eU(!0)(a,o);case J.REDO:return pDe(),F6e()(a,o);case J.MERGE_CLIPS:case J.MERGE_CLIPS_2:{e.preventDefault();const U=S===J.MERGE_CLIPS?Is.CTRL_M:Is.CTRL_E;return u!==null&&!Zc(u)?(jd(U,o0.USER_REQ),Xd(qa.CLIPS)(a,o)):(jd(U,o0.SYS_AUTO),Xd(qa.NEXT)(a,o))}case J.MERGE_PREVIOUS_CLIP:case J.MERGE_PREVIOUS_CLIP_2:{e.preventDefault();const U=S===J.MERGE_PREVIOUS_CLIP?Is.CTRL_SHIFT_M:Is.CTRL_SHIFT_E;return u!==null&&!Zc(u)?(jd(U),Xd(qa.CLIPS)(a,o)):(jd(U),Xd(qa.PREV)(a,o))}case J.MOD_LEFT:return Mr()?F(J.MOD_LEFT,e.shiftKey):w(J.MOD_LEFT,e.shiftKey);case J.MOD_RIGHT:return Mr()?G(J.MOD_RIGHT,e.shiftKey):N(J.MOD_RIGHT,e.shiftKey);case J.SHIFT_MOD_UP:return Mr()?w(J.SHIFT_MOD_UP,e.shiftKey):F(J.SHIFT_MOD_UP,e.shiftKey);case J.SHIFT_MOD_DOWN:return Mr()?N(J.SHIFT_MOD_DOWN,e.shiftKey):G(J.SHIFT_MOD_DOWN,e.shiftKey);
4261case J.SHIFT_ALT_UP:return Mr()?w(J.SHIFT_ALT_UP,e.shiftKey):B(e.shiftKey);case J.SHIFT_ALT_DOWN:return Mr()?N(J.SHIFT_ALT_DOWN,e.shiftKey):W(e.shiftKey);case J.SHIFT_MOD_LEFT:return Mr()?F(p,e.shiftKey):B(e.shiftKey);case J.SHIFT_MOD_RIGHT:return Mr()?G(p,e.shiftKey):W(e.shiftKey);case J.HOME:case J.SHIFT_HOME:return Mr()?w(J.HOME,e.shiftKey):F(J.HOME,e.shiftKey);case J.END:case J.SHIFT_END:return Mr()?N(J.END,e.shiftKey):G(J.END,e.shiftKey);case J.MOVE_TO_BEGINNING_VIDEO:return yDe(),pze(e.shiftKey)(a,o);case J.MOVE_TO_END_VIDEO:return vDe(),fze(e.shiftKey)(a,o);case J.PLAY_TAB:case J.PLAY_SHIFT_TAB:{const{globalWordRange:U}=x;yye();const te=U?uo.PLAY_DEFAULT:S===J.PLAY_SHIFT_TAB&&u===null?uo.PLAY_ALL:uo.PLAY_CLIP,ne=S===J.PLAY_TAB?pr.TAB:pr.SHIFT_TAB;return q(ne,te)}case J.PLAY_F4:case J.PLAY_F5:{const{globalWordRange:U}=x,te=U?uo.PLAY_DEFAULT:S===J.PLAY_F5&&u===null?uo.PLAY_ALL:uo.PLAY_CLIP,ne=S===J.PLAY_F4?pr.F4:pr.F5;return q(ne,te)}case J.MOD_UP:return M(p,e.shiftKey);case J.MOD_DOWN:return k(p,e.shiftKey);case J.ALT_LEFT:case J.SHIFT_ALT_LEFT:return Mr()?B(e.shiftKey):$();case J.ALT_RIGHT:case J.SHIFT_ALT_RIGHT:return Mr()?W(e.shiftKey):$();case J.ALT_UP:return Q(e.shiftKey);case J.ALT_DOWN:return j(e.shiftKey);case J.DELETE_CAPTION:return a(m8e(Ke.ORIGINAL));case J.INSERT_MARKER_RECENT:{const U=Mt(ke.RECENT_MARKER_ID)??0;return a(K6e(U,m.KEY_EDIT))}case J.TRANSLATE:{e.preventDefault();const U=xa(r),te=T2(r),ne=oc(r);if(te){const oe=Od(r),re=He(r),ge=oe.length?oe:V3(re);R.info("translation target indices: "+JSON.stringify(ge)),jB(U,ge,te.source,te.target,io.KEY,te.engineInfo,oe.length?void 0:2,te.target)(a,o),ne&&ir().set(Wt.RETRANSLATION_SHORTCUT_USED,"true")}else rz(c);break}case J.TOGGLE_CURSOR_MOVER_MENU:return e.preventDefault(),Fze()(a,o);case J.OPEN_PROJECT:return e.preventDefault(),SMe(),mBe()(a);case J.CLOSE:return e.preventDefault(),SUe(),await pt().closeWindowByUser()}return t},nwt=()=>e=>e({type:ot.PREPARE_DRAG_WORDS}),awt=()=>e=>{if(Oa()){Ca();return}return Nz(so.WORD),e({type:ot.DRAG_WORDS})},tU=(e,t)=>async(o,r)=>{const n=h("transcript.ts"),a=new Jo,i=se(),s=i.getCurrentProjectFileType();n.info("saveEdit, currType: "+s+", saveType: "+t+", toSaveAs: "+e);const x=i.getProjectId(),c=x?NRe(s,t,e,x):null;if(c){n.info("[Cloud Save] status: "+c),o(W6e(c));return}const l=at()?Ee.PROJECT:Ee.BROWSER,d=r();let u;const p=e||!i.isProjectSaved();let f=await z5(p,l,i.getCurrentProjectPath(),i.getProjectId(),e);if(f===void 0){h("transcript.ts").info("user cancelled new project save.");return}const E=!p&&i.needsNaming();if(E){const y=await x5(f.projectName,!1,f.savePath);if(!y)return;f={...f,projectName:y.projectName,uploadToCloud:y.destination==="cloud"}}const T=!at()&&p,O=T||E,S=gT(Yo().getLastSaveInfo(),p);try{if(await o(MK(f.savePath)),u=await KT(d,f.projectId,S),u===void 0)return;Ev(u),Ve().set(Ie.LAST_PROJECT_ID,u.projectId)}catch(y){const v=P(y);n.error("Error during getting save content  : "+v);const w=ye(y)??_.C_VREW_FILE_SAVE_GENERAL_ERROR,N=Ot(w,{defaultKey:"error.vrew_save_failed",errorArg:Ho(y)});Y().error(w,N);return}const R=async()=>{try{const y=a.getElapsedSec(),v=!1,w=ZP(d,u.projectId);await cP(l,f.savePath,f.projectName,u,v,y,w)===P0.SAVED&&(O&&(i.markProjectAsNamed(),hx({title:f.projectName})),Yo().updateSaveInfo(S),i.clearSampleProject(),e&&Oke(tH.SAVE_AS),f.uploadToCloud&&Pze(f.projectId,f.projectName,!0))}catch(y){n.error("Error during saving : "+P(y));const v=ye(y)??_.C_VREW_FILE_SAVE_GENERAL_ERROR;v===_.D_ERR_MEDIA_CACHE_NOT_FOUND&&u?.files.forEach(N=>{n.info("save target media data, file:"+JSON.stringify(N))});const w=Ot(v,{errorArg:Ho(y),defaultKey:"error.vrew_save_failed"});Y().error(v,w)}};y6e().next(R)},W6e=(()=>{let e=null,t=null,o=!1,r=null;const n=a=>async(i,s)=>{const x=h("transcript.ts");if(o){r={saveStatus:a};return}o=!0;try{const c=se(),l=c.getProjectId();if(!l){x.error("[saveCloudEdit] invalid projectId: "+l);return}const d=!c.isProjectSaved(),u=c.needsNaming(Ee.CLOUD),p=d||u,f=gT(Yo().getLastSaveInfo(),d),E=s(),{globalClips:T}=E.snapshots.present.transcript,O=await KT(s(),l,f),S=Lt().getUserPlanStatusForVcloud();switch(a){case"saveLocal":{if(!(await hA(l,O)).success)return;await $R({type:"DIRECT_DOWNLOAD",projectId:l});return}case"new":case"migrate":if(S==="FREE"){Y().openModal(st.NEED_PLAN_UPGRADE,{premiumFeatureType:Ut.VCLOUD});return}else if(S==="REFUND"){await eA({type:"save"});return}await Gp(a,l);return;case"saveAs":if(S==="FREE"){Y().openModal(st.NEED_PLAN_UPGRADE,{premiumFeatureType:Ut.VCLOUD});return}else if(S==="REFUND"){await eA({type:"save"});return}l&&(T!==e||!bL(O.files,t??[]))&&(await Lt().ensureEditingSessionAndSync(l),await Lt().saveVrewJsonToCloud(O,l),e=T,t
4261=O.files),await Gp(a,l);return;case"save":{const R=Lt();if(!(await hA(l,O)).success){x.info("[saveCloudEdit] Cloud project not initialized, falling back to upload modal: "+l),await Gp("new",l);return}if(p){if(x.info("[CloudFirst] Showing rename modal for project naming: "+l),!await Gp("rename",l))return;c.markProjectAsNamed();const N=R.getVCloudProjectInfo(l)?.projectTitle;N&&hx({title:N})}const v=T!==e||!bL(O.files,t??[]);if(v&&(await R.ensureEditingSessionAndSync(l),await R.saveVrewJsonToCloud(O,l),e=T,t=O.files),v){const w=R.getVCloudProjectInfo(l)?.projectTitle??hy;c.notifyFileSaved(Ee.CLOUD,w,l)}Ve().set(Ie.LAST_PROJECT_ID,l),Ve().set(Ie.LAST_PROJECT_TYPE,Ee.CLOUD);return}}}catch(c){const l="cannot save cloud project, "+P(c);if(x.error(l),Ne(c)&&c.errorCode===_.C_VCLOUD_SESSION_ERROR){h("transcript.ts").info("[saveCloudEdit] cloud session error: close cloud project"),i(SK());return}const d=ye(c)??_.C_VREW_FILE_SAVE_GENERAL_ERROR,u=Ot(d,{defaultKey:"error.vrew_save_failed",errorArg:Ho(c)});Y().error(d,u);return}finally{if(o=!1,r){const{saveStatus:c}=r;r=null,i(n(c))}}};return a=>i=>{i(n(a))}})(),SK=()=>e=>{se().reset(),e({type:aB.RESET_STATE,payload:{exclude:["user"]}}),e(IBe()),e(cz(bo.FILE)),e(qx.ActionCreators.clearHistory())},H6e=(e,t,o,r)=>n=>n({type:ot.INSERT_CLIPS,payload:{clips:e,sceneIndex:t,clipIndex:o,projectProps:r}}),ig=(e,t,o,r,n,a)=>(i,s)=>{const x=s(),c=T2(x),l=lt(x),d=ht(x),u={type:ot.APPLY_TRANSCRIPT,payload:{sceneInfos:e,addSceneIndex:t,props:o,originalClips:a??[],translateInfo:t===null?r:c,audioLanguage:n}};i(u),t===null&&(i(qx.ActionCreators.clearHistory()),e.length===1&&(i(Zze()),UDe(!1,o0.SYS_AUTO,sp(e,l,d).length)))},T0=e=>async t=>{const o=Tt({dispatch:t,option:e}).pipe(At(r=>{const{dispatchType:n,newProjectOption:a}=r.option;if(n===Ee.PROJECT&&!a)throw new C(_.C_LOGIC_ERROR,{},"Inconsistent type "+n);return r}),mJ(async r=>{const{option:n}=r,{dispatchType:a,files:i,blobs:s,newProjectOption:x,analyzeDate:c}=n,l=i.map(d=>hae(d,s[d.mediaId]));return await se().notifyFileOpen(a,l,x,c),r}),er(r=>{const{dispatchType:n,newProjectOption:a}=r.option;Ske(a?.fromAutosave??!1,n,a?.currentPath??"",a?.fromIOS??!1,Il().getMostRecentAttemptedOpenMethod())}),Ma(async r=>{const{dispatch:n,option:a}=r,{newProjectOption:i}=a;return i&&(W5e(),n(Tze()),Yo().reset(),(await nc.getInstance()).resetProxyActivation()),r}),Ma(async r=>{const{dispatch:n,option:a}=r,{files:i,blobs:s,newProjectOption:x}=a,c=!x,l=i.filter(u=>Zr(u)&&u.videoAudioMetaInfo.videoInfo!==void 0),d=l.map(u=>{const{mediaId:p}=u,{duration:f}=u.videoAudioMetaInfo,E=PL(u,s[p],!0);if(E===void 0){const T="[receiveVideoPayloads] Cannot find uri for source "+p+", "+JSON.stringify(u);throw h("transcript.ts").error(T),new C(_.C_LOGIC_ERROR,{},T)}return{mediaId:p,src:E,duration:f}});return n(H8(d,c)),r}),At(r=>{const{dispatch:n,option:a}=r,{files:i}=a,s=i.filter(x=>Tae(x)).map(x=>x.mediaId);return n(Q6e(s)),r}),At(r=>{const{dispatch:n,option:a}=r,{files:i,blobs:s,newProjectOption:x}=a,c=x===void 0,l=i.filter(u=>yf(u)),d=l.map(u=>{const{mediaId:p}=u,f=PL(u,s[p],!1);if(f===void 0){const O="[receiveAudioPayloads] Cannot find uri for source "+p+", "+JSON.stringify(u);throw h("transcript.ts").error(O),new C(_.C_LOGIC_ERROR,{},O)}const E=s[p]||null,T=u.videoAudioMetaInfo.audioInfo!==void 0;return{mediaId:p,audioBlob:T?E:null,path:f,duration:u.videoAudioMetaInfo.duration}});return n(YP(d,c)),r})).pipe(At(r=>{const{dispatch:n,option:a}=r;return a.newProjectOption&&n(qx.ActionCreators.clearHistory()),r}));await Bt(o)},j6e=async e=>!at()||Il().getMostRecentAttemptedOpenMethod()!==Kn.CUSTOM_LIST?!1:!await Ue().existsFile(e),iwt=(e,t,o,r)=>(n,a)=>{const i=rt(a()),s=nEe(i,e);if(s===void 0)return n;const x=iEe(i,s,t,o);return x===void 0?n:(r&&r(),n(z6e(x)))},z6e=e=>({type:ot.REARRANGE_ELEMENTS,payload:{chunkDatas:e}}),swt=(e,t,o,r)=>async(n,a)=>{const i=se(),s=a(),x=tc(s),c=ex(s),l=mo(s),d=Nc(l),u=Lv(s),p=oc(s),f=lt(s),E=ht(s),T=Ad();let O,S;const{yAlign:R,yOffset:y}=c.captionStyleSetting,v=Math.round(go.VIRTUAL_YRES*(KR(R,0)+y)),{fontName:w,weight:N}=el(c),{exportAssets:M}=tb(s);if(e===gi.PREMIERE)O=tge(d,M,u,Mr(),on(x),v,w,N,r,t,o,c),S=A("toolbar.export_premiere_title");else if(e===gi.FCPX||e===gi.DAVINCI){const W=new Li(void 0,void 0,f,E).collectFrom({type:Or.SCENE,model:l}).build().getUsedSourceMediaIds(),Q=c_().filter(j=>W.has(j.mediaId)).filter(j=>Bc(j));O=await Yue(d,M,Q,Mr(),c,e,on(x),t,o),S=e===gi.FCPX?A("toolbar.export_fcpx_title"):A("toolbar.export_davinci_title")}if(!O)return;const k=e===gi.PREMIERE?"xml":"fcpxml",F=zu(LCe(i.getCurrentProjectPath(),k),e!==gi.FCPX),G=await fb(F,k,S);if(!G)return;if(n(uS(Kc.EXPORT_XML)),await UK(G,O)){FK("xml",G);const Q=sp(l,f,E).length,j=l.length;e===gi.PREMIERE?XMe(Q,j,T):e===gi.FCPX?JMe(Q,j,T):e===gi.DAVINCI&&qMe(Q,j,T);const{markerNum:$,clipsNum:q}=Eb(l,f,E);EP($,q,T),jT(HT(s,WT(Kt.XML,e),Vo.ALL_CLIPS,{},T),BT(s)),p&&YT(zT(s,T,Kt.XML,XI(o)))}},Y6e=e=>({type:ot.SET_AUTOSCROLLING,payload:{setAutoScroll:e}}),B6e=e=>(t,o)=>{const r=o(),{autoScrollingWhilePlaying:n}=rt(r);n!==e&&t(Y6e(e))},K6e=(e,t,o)=>(r,n)=>{e!==void 0&&po(ke.RECENT_MARKER_ID,e);const a=n(),i=He(a),s=Od(a),x=ec(a),c=o?[o]:s,l=c.length>0?c:x===-1?[]:[x],d=l.filter(f=>i.at(f)?.markerId!==e);if(d.length===0)return;const u=e!==void 0&&d.includes(x)?i.at(x)?.clipId:void 0;u!==void 0&&r(cKe(u));const p=is(d);return X6e(e,t,Z_e(p)),r({type:ot.UPDATE_MARKER,payload:{markerId:e,globalClipChunks:p}})},X6e=(e,t,o)=>{t===m.KEY_EDIT?PMe(o):NMe(e===void 0?-1:e,o,t)},OK=e=>async t=>{const o=await nc.getInstance();o.hasProxyFile(e)&&o.setProxyActivation(e,!1),(Mt(ke.PREPARE_PROXY)||o.isProxyEnabled())&&_3(()=>t(HB(!0)),()=>t(z8("auto")))},xwt=(e,t,o,r,n,a=void 0)=>async i=>{const s=qe.v4(),x=o.type==="path"?NL({mediaId:s,fileLocation:D.LOCAL,fileSize:r,name:t,videoAudioMetaInfo:wL(n),path:o.value}):NL({mediaId:s,fileLocation:D.IN_MEMORY,fileSize:r,name:t,videoAudioMetaInfo:wL(n)}),c=vd({files:[x],blobs:o.type==="blob"?{[s]:o.value}:{},dispatchType:Ee.MEDIA});await i(T0(c));const l={type:ot.CHANGE_MAIN_VIDEO_AUDIO_MEDIA,payload:{currentMediaId:e,newMediaId:s,replacementOption:a}};i(l),i(OK(e)),se().notifyMediaChanged(e,n.videoInfo?.size),h("transcript.ts").info("source "+e+" is changed to "+s)},cwt=(e,t)=>
4261({type:ot.REPLACE_CAPTION,payload:{target:e,replaceText:t}}),lwt=(e,t)=>async o=>{if(Oa()){Ca();return}await o(bd());const r=ct(),n={type:ot.INSERT_BLANK_CLIP,payload:{newClipId:r,duration:e,clipIndex:t}};o(n)},dwt=(e,t,o,r,n)=>async a=>{if(Oa()){Ca();return}await a(bd());const i=ho(),s=ct(),x={type:ot.INSERT_BLANK_CLIP_WITH_IMAGE,payload:{duration:e,clipIndex:t,newClipId:s,mediaId:o,assetId:i,aspectRatio:r,isFromClipGapFloatingButton:!0,options:n}};a(x)},uwt=(e,t,o,r,n)=>async a=>{if(Oa()){Ca();return}const i=ho(),s=ct();if(e===0){h("transcript.ts").error("video duration is 0. So no blank clip generated");return}await a(bd());const x={type:ot.INSERT_BLANK_CLIP_WITH_ASSET_VIDEO,payload:{duration:e,mediaId:o,assetId:i,newClipId:s,aspectRatio:r,clipIndex:t,options:n}};a(x)},pwt=(e,t,o,r)=>async n=>{await n(bd());const a=ho(),i=ct(),s={type:ot.INSERT_BLANK_CLIP_WITH_CHARACTER,payload:{duration:e,clipIndex:t,newClipId:i,mediaId:o,assetId:a,selectedAssetId:r}};n(s)},fwt=(e,t,o,r)=>async n=>{await n(bd());const a=ho(),i=ct(),s={type:ot.INSERT_BLANK_CLIP_WITH_SHAPE,payload:{duration:e,clipIndex:t,newClipId:i,mediaId:o,assetId:a,newShapeData:{type:"new",...r}}};n(s)},gwt=(e,t,o,r)=>async n=>{await n(bd());const a=ho(),i=ct(),s={type:ot.INSERT_BLANK_CLIP_WITH_SHAPE,payload:{duration:e,clipIndex:t,newClipId:i,mediaId:o,assetId:a,newShapeData:{type:"copy",copyAssetId:r}}};n(s)},_wt=(e,t)=>(o,r)=>{const n=r(),a=rt(n),i={type:"IMPORT_RANGE",importRange:t},s=xx(a,i),x=s.flatMap(c=>c.type==="GLOBAL_CLIP"?a.globalClips.slice(c.from,c.to).map(l=>({clipId:l.clipId,rate:e})):c.type==="SCENE"?mo(n).slice(c.from,c.to).flatMap(l=>l.clips.map(d=>({clipId:d.id,rate:e}))):[]);x.length!==0&&o({type:ot.CHANGE_PLAYBACK_RATE_EFFECT,payload:{clipRates:x,chunks:s}})},J6e=(e,t)=>{const o=new Map(t.map(({clipId:i,rate:s})=>[i,s])),r=i=>o.get(ai(i))??AH(i),n=e[0];if(!n)return;const a=r(n);return e.every(i=>r(i)===a)?a:void 0},q6e=({range:e,totalClipCount:t,appliedRates:o})=>{if(o.length===0)return;const{sum:r,min:n,max:a}=o.reduce((i,s)=>({sum:i.sum+s,min:s<i.min?s:i.min,max:s>i.max?s:i.max}),{sum:0,min:1/0,max:-1/0});wze({videoFitRateApplicableCount:o.length,videoFitRateSkippedCount:t-o.length,videoFitRateAvgRate:r/o.length,videoFitRateMinRate:n,videoFitRateMaxRate:a,videoFitRateRange:e})},Ewt=({range:e,source:t})=>(o,r)=>{const n=r(),a=rt(n),i={type:"IMPORT_RANGE",importRange:e},s=xx(a,i),x=SI(n,e);if(vze(e,x.length,t),x.length===0)return;const c=lt(n),l=ht(n),d=x.flatMap(u=>{const p=ai(u),f=VI(u,l,c);if(!f)return[];const E=Xy(f);if(E===void 0)return[];if(!ude(u,l,c,E))return[];const T=xw(Gg(f.sourceIn,E),ac(u),pe(cs(u)));return T===null?[]:[{clipId:p,rate:T}]});if(d.length!==0)return q6e({range:e,totalClipCount:x.length,appliedRates:d.map(({rate:u})=>u)}),o({type:ot.CHANGE_PLAYBACK_RATE_EFFECT,payload:{clipRates:d,chunks:s}}),J6e(x,d)},mwt=(e,t)=>(o,r)=>{const n=r(),a=SI(n,t);if(a.length===0)return;const i=lt(n),s=ht(n),x=new Set;for(const c of a)for(const l of c.words)for(const d of l.assetIds){if(x.has(d))continue;const u=L.get(s,d);if(!u||u.role!=="main")continue;if(u.trackIds.some(f=>{const E=L.get(i,f);return E&&Wa(E)})){x.add(d);break}}x.size!==0&&o(CK([...x],e))},CK=(e,t)=>{const o=t/100;return{type:Ga.CHANGE_ASSET_VOLUMES,payload:{targetAssetIds:e,volume:o}}},hwt=(e,t,o)=>({type:Ga.CHANGE_AUDIO_OFFSET,payload:{assetId:e,sourceIn:t,sourceOut:o}}),Iwt=(e,t)=>(o,r)=>{const n=r(),a=rt(n),i=ho(),s={type:"IMPORT_RANGE",importRange:e},x=xx(a,s),c={type:Ga.ADD_BGM,payload:{chunks:x,audioTrack:t,assetId:i}};o(c),o(zP(i,ra.AUDIO,null))},Q6e=e=>({type:Ga.LOAD_ASSET_AUDIO,payload:{mediaIds:e}}),Z6e=e=>(t,o)=>{const r=e.map(n=>{const a=$6e(o,n.globalPosition,n.isSynchronous);if(a!==null)return{audioTrack:n.audioTrack,assetId:n.assetId,insertGlobalPosition:a}}).filter(Se);t({type:Ga.ADD_SOUND_EFFECTS,payload:r})},$6e=(e,t,o=!0)=>{const r=e(),n=mo(r),a=He(r);if(n.some(c=>{const l=c.globalClipRange.to-1,d=a[l];return XL(t,d)}))return t-1;if(o){const c=Od(r);if(c.length>0)return a[c[0]].startPosition;const l=$0(r);if(l.length>0)return l[0]}const s=Er(a,t,!0);if(s===-1)return 0;const x=a[s];return XL(t,x)?$xe(a,t):t},e9e=(e,t,o,r,n,a,i)=>{const s=e(),x=$x(s),{clips:c}=x,l=He(s),d=Z0(s),u=$0(s),p=Dv(s),f=O2(s),E=hP(t,c,p,d.size,u.length,f?[f]:[],l),T=(o===_e.IMAGE_GENERATE_MODAL||o===_e.IMAGE_REPLACE_MODAL)&&a?.type===Za.FREE_SOURCE;o===_e.STOCK_CONTEXT_FLOATING_MENU||o===_e.STOCK_IMAGE||o===_e.IMAGE_GENERATE_MODAL_STOCK||T?Uz(t,o,E.clipCount,E.wordCount,0,a?.type===Za.FREE_SOURCE?a:void 0,void 0,i):a?.type===Za.GEN_ASSET&&o!==_e.TTV?Kke(t,o,E.clipCount,E.wordCount,a):o===_e.PANEL_UPLOAD&&n?.videoOrigin!==If.TRANSCODE_GIF?Xke(t,o,E.clipCount,E.wordCount,0):r===z.VIDEO?n?.videoOrigin===If.TRANSCODE_GIF?Hz(t,Math.max(E.clipCount,E.wordCount),0,o,void 0):Wz(t,Math.max(E.clipCount,E.wordCount),0,o,E.clipCount,a?.type===Za.USER_ASSET?a:void 0,void 0):Lz(E.clipCount,E.wordCount,0,t,o,a?.type===Za.FREE_SOURCE,a?.type===Za.USER_ASSET?a:void 0,void 0)},t9e=(e,t,o)=>{const r=e(),n=$x(r),{clips:a}=n,i=He(r),s=Z0(r),x=$0(r),c=Dv(r),l=O2(r),d=hP(t,a,c,s.size,x.length,l?[l]:[],i);dke(o,t,d.clipCount,d.wordCount)},o9e=(e,t,o,r)=>{if(o===void 0)return;const n=e(),a=$x(n),{clips:i}=a,s=He(n),x=Z0(n),c=$0(n),l=Dv(n),d=O2(n),u=hP(t,i,l,x.size,c.length,d?[d]:[],s);r?.charValue&&zFe(t,u.clipCount,u.wordCount,o,r.charValue.activeTag,r.charValue.characterType,r.charValue.characterDimension,r.charValue.isFavoriteCharacter,r.charValue.characterPanelState)},RK=(e,t,o,r,n,a,i,s)=>async(x,c)=>{const l=c(),d=rt(l),u=Lg(l),p=n?.importType??_e.UNKNOWN,f=p===_e.STOCK_IMAGE||p===_e.STOCK_CONTEXT_FLOATING_MENU||p===_e.IMAGE_GENERATE_MODAL_STOCK,E=t===z.WEB,T=t===z.SIMPLE_CHARACTER;let O=0;if((f||E)&&u){const M=u.assetIds.length;M<20?O=M*.02:M<40&&(O=-.4+(M-20)*.02)}const S=U4(d,e,t,o),R=lI(l);i&&await i().catch(M=>{throw h("transcript.ts").error("Error occurred during prepareAsset() of putAsset(): "+P(M
4261)),M});const y=e.type==="IMPORT_RANGE"?e.importRange:nt.SELECTED_CLIPS;if(t===z.IMAGE||t===z.VIDEO||t===z.SHAPE?e9e(c,y,p,t,n,a,s):E?t9e(c,y,p):T&&a?.type===Za.FREE_SOURCE&&o9e(c,y,n?.selectedCharacter,a),S===void 0)return;const{chunkData:v,cursorAssetId:w,cursorGlobalPosition:N}=S;hJ(()=>{x(AK(v,r,O,R,n)),p!==_e.DRAG_AND_DROP_MULTIPLE&&x(zP(w,ra.ASSET,N))})},AK=(e,t,o,r,n)=>({type:Zt.PUT_ASSET,payload:{chunkData:e,aspectRatio:t,imageOffset:o,options:n,position:r}}),Twt=(e,t,o,r,n,a)=>(i,s)=>{const x=s(),c=TI(x,e);return!c||c.xPos===t&&c.yPos===o&&c.width===r&&c.height===n?i:(A_(c.type)&&QDe(c.type,a),i(yK(e,t,o,r,n)))},yK=(e,t,o,r,n)=>({type:Zt.RESIZE_DISPLAY_MODEL,payload:{displayModelId:e,newXPos:t,newYPos:o,newWidth:r,newHeight:n}}),Swt=(e,t,o,r)=>(n,a)=>{const i=a(),s=TI(i,e);return!s||s.xPos===t&&s.yPos===o?n:(A_(s.type)&&(s.type===z.IMAGE&&ZDe(r),s.type===z.WEB&&rFe(r)),n(n9e(e,t,o)))},Owt=e=>(t,o)=>{const r=o();if(wg(r))return t(r9e(e))},r9e=e=>({type:Zt.SET_VREW_MARK_FIXED_POSITION,payload:{newPosition:e}}),n9e=(e,t,o)=>({type:Zt.MOVE_DISPLAY_MODEL,payload:{displayModelId:e,newXPos:t,newYPos:o}}),Cwt=(e,t,o)=>(r,n)=>{const a=n(),i=TI(a,e);return!i||i.rotation===t?r:(A_(i.type)&&$De(o),r(a9e(e,t)))},a9e=(e,t)=>{const o=t<0?t%360+360:t%360;return{type:Zt.ROTATE_DISPLAY_MODEL,payload:{displayModelId:e,newRotation:o}}},Rwt=(e,t,o,r,n,a)=>{const i=a<0?a%360+360:a%360;return{type:Zt.TRANSFORM_DISPLAY_MODEL,payload:{displayModelId:e,newXPos:t,newYPos:o,newWidth:r,newHeight:n,newRotation:i}}},Awt=(e,t,o,r,n,a,i)=>(s,x)=>{const c=x(),l=TI(c,e);return l===null||Rr(l)||!yJ(l)||l.xPos===t&&l.yPos===o&&l.width===r&&l.height===n&&l.editInfo?.crop===a?s:[s(yK(e,t,o,r,n)),s(i9e(e,a,i))]},i9e=(e,t,o)=>({type:Zt.CROP_DISPLAY_MODEL,payload:{displayModelId:e,clipPath:t,isEditCropping:o}}),ywt=(e,t)=>(o,r)=>{const n=lt(r()),a=L.get(n,e);if(!a||!(Gn(a)||mn(a))||a.editInfo?.opacity===t)return;const i={type:Zt.SET_TRACK_OPACITY,payload:{trackId:e,opacity:t}};o(i)},vwt=e=>(t,o)=>{const r=o(),n=O2(r);if(!n)return;const a=Mxe(r,n),i=cI(r),s=[...a].sort((u,p)=>(L.get(i,u)?.track.zIndex??0)-(L.get(i,p)?.track.zIndex??0)),x=s.indexOf(n),c=s.length-1,l=0;let d=L.get(i,n)?.track.zIndex??0;switch(e){case Po.FRONT:{const u=c;if(u===x)return;const p=s[u];d=(L.get(i,p)?.track.zIndex??0)+.5;break}case Po.FORWARD:{const u=s.lastIndexOf(n);if(u===c)return;const p=u+1,f=s[p];d=(L.get(i,f)?.track.zIndex??0)+.5;break}case Po.BACKWARD:{if(x===l)return;const u=x-1,p=s[u];d=(L.get(i,p)?.track.zIndex??0)-.5;break}case Po.BACK:{const u=l;if(u===x)return;const p=s[u];d=(L.get(i,p)?.track.zIndex??0)-.5;break}default:return}t({type:Zt.REORDER_ASSET,payload:{assetId:n,newZIndex:d}})},vK=(e,t)=>(o,r)=>{const n=r(),a=lt(n),i=ht(n);if(se().isCloudProject()){const s=e.filter(({elementType:x})=>A_(x)).map(({elementId:x})=>x);Yae(a,i,s,t)}return o({type:Zt.DELETE_ELEMENTS,payload:{targetElements:e}})},s9e=(e,t)=>async(o,r)=>{if(!await OT(r))return o(wK());if(wg(r()))return;const i=await ST(t,e);return o(c9e(i))},wK=()=>(e,t)=>{if(!ba().isPremiumFeatureAvailable(Ut.DELETE_VREW_MARK))return;const r=t(),n=Object.values(lt(r)).find(Rr);if(!(!n||!k2(r)))return h("transcript.ts").info("Removing watermark "+n.mediaId+" because current plan already allows it"),e(NK(!0))},x9e=()=>async(e,t)=>{const o=t(),r=wg(o),n=k2(o),a=CT(o),i=s7(a);return r?await BTe(n,i)?(dDe(),h("transcript.ts").info("Deleting watermark "+r.mediaId),e(NK(!1))):e:void 0},c9e=e=>({type:Zt.INSERT_WATERMARK,payload:{watermark:e}}),NK=e=>({type:Zt.DELETE_WATERMARK,payload:{skipHistory:e}}),wwt=(e,t)=>({type:Zt.SHIFT_TRACK,payload:{trackId:e,values:t}}),Nwt=(e,t)=>({type:Zt.SET_SHAPE_PLANE,payload:{trackId:e,values:t}}),Pwt=(e,t)=>({type:Zt.SET_SHAPE_CORNER_ROUNDING,payload:{trackId:e,cornerRounding:t}}),bwt=(e,t)=>({type:Zt.SET_SHAPE_STROKE,payload:{trackId:e,values:t}}),Lwt=(e,t,o)=>({type:Zt.FILL_TRACKS,payload:{targetTrackIds:e,menu:t,fillType:o}}),Mwt=(e,t)=>({type:Zt.CHANGE_WATERMARK,payload:{newMediaId:e,newVrewMarkInfo:t}}),Dwt=(e,t)=>({type:Zt.REPLACE_IMAGE_VIDEO,payload:{targetAssets:e,newAssetInfo:t}}),kwt=(e,t)=>
4261({type:Zt.SET_REMOVE_BACKGROUND_LOADING_STATE,payload:{targetTrackId:e,removeBackgroundInfo:t}}),Fwt=(e,t,o)=>(r,n)=>{const a=n(),i=lt(a),s=fEe(i);r({type:Zt.UPDATE_IMAGE_TRACKS_LOADING_STATE,payload:{loadingTrackIds:s,isRemoveBackgroundDone:void 0}}),r({type:Zt.REPLACE_TRACK_MEDIA_ID,payload:{targetTrackId:e,newMediaId:t,imageType:o}}),r({type:Zt.UPDATE_IMAGE_TRACKS_LOADING_STATE,payload:{loadingTrackIds:s,isRemoveBackgroundDone:!1}})},pb=(e,t)=>{const o=SI(e,t),r=lt(e),n=ht(e),a=new Set;return o.forEach(i=>{iT(i,r,n).forEach(s=>{a.add(s.trackId)})}),Array.from(a)},Uwt=(e,t,o)=>(r,n)=>{if(Xp(t))return r(l9e(e));const a=pb(n(),e);if(a.length===0)return;const i={type:Zt.CHANGE_FILTER,payload:{targetTrackIds:a,filterMediaId:t,alpha:o}};return r(i)},l9e=e=>(t,o)=>{const r=pb(o(),e);if(r.length===0)return;const n={type:Zt.REMOVE_FILTER,payload:{targetTrackIds:r}};return t(n)},ZC=(e,t,o)=>({type:Zt.FLIP,payload:{trackIds:e,flipVertical:t,flipHorizontal:o}}),Vwt=(e,t)=>(o,r)=>{const n=r(),a=pb(n,e);if(a.length===0)return;if(t===null)return o(ZC(a,!1,!1));const{direction:i,flipped:s}=t;return o(i==="vertical"?ZC(a,s,void 0):ZC(a,void 0,s))},Gwt=e=>({type:Zt.SET_GLOBAL_VIDEO_TRANSFORM,payload:e}),d9e=e=>({type:Zt.SET_VIDEO_TRANSFORM,payload:e}),u9e=e=>({type:Zt.RESET_VIDEO_TRANSFORM,payload:{clipChunks:e}}),oU=e=>(t,o)=>{const r=o(),n=rt(r),a=xx(n,e.importOption),i={chunks:a,...e};return t(d9e(i))},Wwt=(e,t)=>(o,r)=>{const n=r(),{videoRatio:a}=rt(n),i=He(n),s=$x(n),x=_2(n),c=Lg(n),l=lt(n),d=ht(n),u=p=>{if(p===nt.ALL_CLIPS)return i;if(p===nt.SCENE_CLIPS){const f=s.globalClipRange;return i.slice(f.from,f.to)}return p===nt.SELECTED_CLIPS?x:[]};switch(e){case nt.ALL_CLIPS:case nt.SCENE_CLIPS:case nt.SELECTED_CLIPS:{const p=u(e),f=p.reduce((E,T)=>{const{visualMediaId:O}=ss(T.words[0],l,d);if(!O)return E;const S=ml(i,T.clipId);return!E[O]&&(E[O]=[]),E[O].push(S),E},{});Object.entries(f).forEach(([E,T])=>{const O=jM(E),S=Gf(j0(a),t,O);o(oU({importOption:{type:"CUSTOM_GLOBAL_CLIP",globalClipIndices:T},...S}))});break}case nt.CURRENT_CLIP:default:{if(c){const{visualMediaId:p}=ss(c.words[0],l,d),f=jM(p),E=Gf(j0(a),t,f),T={type:"IMPORT_RANGE",importRange:nt.CURRENT_CLIP};o(oU({importOption:T,...E}))}break}}},Hwt=e=>(t,o)=>{const r=o(),n=rt(r),a={type:"IMPORT_RANGE",importRange:e},i=xx(n,a);t(u9e(i))},jwt=(e,t)=>async(o,r)=>{const n=r(),a=rt(n),i=await OEe(t),s={type:"IMPORT_RANGE",importRange:e},x=xx(a,s);return o({type:ot.APPLY_FRAMEPACK,payload:{framePack:t,realAssetRecords:i,chunks:x,isProjectRange:e===nt.ALL_CLIPS}})},zwt=e=>async t=>{const{uploadedMediaInfo:o,videoDimension:r}=e;try{const n=await T4(o.path);if(!n)return;const a=ho(),i={from:0,to:1,type:"GLOBAL_CLIP"},s=[{chunk:i,assetInfos:[{type:Hx.NEW,assetId:a,assetType:z.VIDEO,mediaId:n.mediaId}],audioInfos:[]}];t(AK(s,r,0,null)),t({type:Zt.REORDER_ASSET,payload:{assetId:a,newZIndex:-.5}})}catch(n){h("transcript.ts").error("Error occurred while applyFramePackStockVideo: "+P(n));const a=ye(n)??_.C_ASSET_VIDEO_PARSE_ERROR;Y().error(a,Ot(a,{defaultKey:"error.asset_video_error"}))}},Ywt=(e,t,o,r)=>({type:Zt.UPDATE_WEB_CAPTION,payload:{webTrackId:e,editedContent:t,textboxStyleMethod:o,updateReason:r}}),Bwt=e=>(t,o)=>{const r=o(),n=lt(r),a=ht(r),i=_0(r),{selectedAssetIds:s}=rc(i),x=s.flatMap(c=>{const l=L.get(a,c);return l?l.trackIds.map(u=>{const p=L.get(n,u);if(!(!p||!xr(p)||!PI(p))&&!(Wn(p)&&!Fl(p)))return p.trackId}).filter(Se):[]});return x.length===0?t:t({type:Zt.SET_ASSET_EFFECT,payload:{trackIds:x,assetEffectInfo:e}})},Kwt=e=>(t,o)=>{const r=o(),n=Tn(r),{webModelTextSelection:a}=n;if(a===null||a.captionIndex===void 0)return t;const{globalClipIndex:i,captionIndex:s}=a;return t({type:_r.SET_CAPTION_EFFECT,payload:{globalClipIndex:i,captionIndex:s,assetEffectInfo:e}})},Xwt=()=>(e,t)=>{const o=t(),r=lt(o),n=ht(o),a=Tn(o),{selectedElements:i,webModelTextSelection:s}=a,{selectedAssetIds:x}=rc(i);if(x.length>0){const c=x.flatMap(l=>{const d=L.get(n,l);return d?d.trackIds.map(p=>{const f=L.get(r,p);if(!(!f||!xr(f)||!PI(f)))return f.trackId}).filter(Se):[]});return e({type:Zt.REMOVE_ASSET_ANIMATION,payload:{trackIds:c}})}return s&&s.captionIndex!==void 0?e({type:_r.SET_CAPTION_EFFECT,payload:{globalClipIndex:s.globalClipIndex,captionIndex:s.captionIndex,assetEffectInfo:void 0}}):e},Jwt=(e,t)=>
4261(o,r)=>{const n=r(),a=lt(n),i=ht(n),s=_0(n),{selectedAssetIds:x}=rc(s);if(!t&&x.length===0)return;const c=(t??x).flatMap(l=>{const d=L.get(i,l);return d?d.trackIds.map(p=>{const f=L.get(a,p);if(!(!f||!Gn(f)))return f.trackId}).filter(Se):[]});c.length!==0&&o({type:Zt.ADD_KENBURNS_PRESET,payload:[{targetTrackIds:c,animationType:e}]})},PK=e=>(t,o)=>{const r=o(),n=lt(r),a=ht(r),i=e.flatMap(x=>{const c=L.get(a,x);return c?c.trackIds.map(d=>{const u=L.get(n,d);if(!(!u||!Gn(u)))return u.trackId}).filter(Se):[]}),s=Array.from(i.reduce((x,c)=>{const l=vI(),d=x.get(l)??[];return d.push(c),x.set(l,d),x},new Map),([x,c])=>({animationType:x,targetTrackIds:c}));t({type:Zt.ADD_KENBURNS_PRESET,payload:s})},qwt=(e,t,o)=>(r,n)=>{const a=n(),i=lt(a),s=ht(a),x=_0(a),{selectedAssetIds:c}=rc(x);if(!o&&c.length===0)return;const l=(o??c).flatMap(d=>{const u=L.get(s,d);return u?u.trackIds.map(f=>{const E=L.get(i,f);if(!(!E||!Gn(E)))return E.trackId}).filter(Se):[]});l.length!==0&&r({type:Zt.ADD_KENBURNS_CUSTOM,payload:{targetTrackIds:l,from:e,to:t}})},p9e=(e,t,o)=>({type:Zt.UPDATE_WEB_TRACK_ATTRIBUTE,payload:{webTrackId:e,attribute:t,updateReason:o}}),Qwt=e=>({type:Zt.CHANGE_MARKER_NAMES,payload:{markerNames:e}}),Zwt=e=>({type:Zt.SET_VIDEO_RATIO,payload:{videoRatio:e}}),$wt=(e,t)=>({type:Zt.TRIM_SUB_ASSET_VIDEO,payload:{sourceIn:e,assetId:t}}),eNt=(e,t)=>({type:Zt.TOGGLE_CHARACTER_APPLYING_MOUTH,payload:{trackId:e,isMouthApplied:t}}),tNt=(e,t)=>({type:Zt.CHANGE_CHARACTER_POSE,payload:{trackId:e,pose:t}}),oNt=(e,t)=>(o,r)=>{const n=r(),a=rt(n),i={type:"IMPORT_RANGE",importRange:e},s=xx(a,i),x=ct();return o({type:ot.SET_BACKGROUND,payload:{chunks:s,backgroundId:x,background:{type:k0.SOLID,color:t}}})},rNt=e=>(t,o)=>{const r=o(),n=rt(r),a={type:"IMPORT_RANGE",importRange:e},i=xx(n,a);return t({type:ot.SET_BACKGROUND_ID,payload:{chunks:i}})},nNt=e=>({type:ot.HIDE_HARDCUT_ICON,payload:{wordPosition:e}}),ip=e=>async(t,o)=>{const{clipDispatchRange:r,clips:n,newSourceOption:a,projectProperty:i}=e;await t(T0(a));const{trackEntries:s,baseAssetEntries:x,videoRatio:c}=i,l=EN(n),d=Zg(x,l),u=Object.values(s).find(Rr),p=a.startMedia===Ls.DOCS?mi.BLACK:mi.WHITE,f=await OT(o),E=r===gn.NEW_PROJECT&&f&&!u?await ST(p,c):void 0,T=E?{...s,[E.trackId]:E}:s,O={...i,assetEntries:d,trackEntries:T},S=n.map(R=>Hw(R)?kf(R,0):R);switch(e.clipDispatchRange){case gn.NEW_PROJECT:return t(ig([{clips:S,id:e.sceneId}],null,O,null,e.audioLanguage));case gn.NEW_SCENE:return t(ig([{clips:S,id:e.sceneId,name:e.sceneName}],e.sceneIndex,O,null,e.audioLanguage));case gn.EXISTING_SCENE:return t(H6e(S,e.sceneIndex,e.clipIndex,O))}},bd=()=>async e=>e(T0(fT())),aNt=e=>t=>t({type:ot.UPDATE_AUDIO_LANGUAGE,payload:{audioLang:e}}),iNt=(e,t)=>o=>{o({type:ot.TOGGLE_BGM_LOOP,payload:{trackIds:e,isActive:t}})},sNt=(e,t)=>o=>{o({type:ot.CHANGE_END_BEHAVIOR,payload:{assetIds:e,endBehavior:t}})},xNt=e=>t=>{t({type:ot.APPLY_LINEBREAKS,payload:{chunkSentenceInfos:e}})},cNt=(e,t)=>({type:ot.APPLY_CAPTION_CORRECTIONS,payload:{corrections:e,captionLanguage:t}}),bK=(e,t)=>{const o=t(),r=O2(o);if(!r||q0())return!1;const a=lt(o),i=ht(o);if(!(L.get(i,r)?.trackIds.find(d=>{const u=L.get(a,d);return u!==void 0&&Wn(u)})!==void 0))return!1;const c=E0(o),l=L.get(c,r)?.globalClipRange.from;return l===void 0?(h("transcript.ts").warn("invalid globalClipIndex for assetId "+r,{globalClipIndex:l}),!1):(e(oze({deltaId:wy,globalClipIndex:l,captionIndex:void 0,fromEditTrigger:!0})),!0)},lNt=e=>async(t,o)=>{const r=o(),n=Z0(r),a=$0(r),i=_0(r),s=tc(r),x=i.length>0?nt.FOLLOW_SELECTED_ELEMENT:a.length>0?nt.SELECTED_WORDS:n.size>0?nt.SELECTED_CLIPS:nt.CURRENT_CLIP,c={type:"IMPORT_RANGE",importRange:x},l=YL(s).html;await eP(l,Ao),await t(RK(c,z.WEB,Ao,1,{webAssetData:YL(s),importType:e})),t(bK)},f9e=(e,t,o,r)=>({type:"AVMedia",mediaId:t,fileLocation:D.LOCAL,path:r,fileSize:e.fileSize,name:o,sourceOrigin:e.sourceOrigin,sourceType:e.sourceType,videoAudioMetaInfo:e.videoAudioMetaInfo}),LK=(e,t,o)=>async r=>{const n=qe.v4(),a=f9e(e,n,t,o);await r(T0(vd({files:[a],blobs:{},dispatchType:Ee.MEDIA})));const i={type:ot.REBIND_LOCAL_MEDIA,payload:{currentMediaId:e.mediaId,newMediaId:n}};r(i),r(OK(e.mediaId)),se().notifyMediaChanged(e.mediaId,e.videoAudioMetaInfo.videoInfo?.size),h("transcript.ts").info("local media "+e.mediaId+" is rebinded to "+n)},g9e=e=>async t=>{const o=h("transcript.ts"),r=se(),n=r.getSampleProjectSourceDir();if(!n){o.warn("Demo source directory is not set");return}o.info("Copying demo sources from "+n+" to "+e);const a=[...c_()];for(const i of a){const s=gd(i.mediaId);if(s){const x=gt(s),c=n+"/"+x,l=""+e+x;await Ue().copyFile(c,l),o.info("Copied demo source: "+x+" (mediaId: "+i.mediaId+")"),await t(LK(i,x,l))}}},MK=e=>async t=>{if(!at())return;const r=h("transcript.ts");if(se().isDemo()){const i=ti(e);await t(g9e(i));return}const a=ca();for(const i of a){let s;const x=gd(i.mediaId);x&&nR(x)&&(r.info(x+" is from mobile device. moving into main fs."),s=""+ti(e)+gt(x),await Ue().copyFile(x,s)),s&&await t(LK(i,gt(s),s))}},dNt=(e,t,o=void 0,r="contain",n=!1,a=()=>{})=>async(i,s)=>{const x=e.map(fe=>fe.blob),c=e.map(fe=>fe.text??""),l=e.map(fe=>fe.width??0),d=e.map(fe=>fe.height??0),u=e[0].name??"",p=o?cr(o):t.width/t.height;a(ur(1/6));const f=await WK(x,l,d,p,r);a(ur(2/6));const{assetIds:E}=f,T=4,O=c.flatMap((fe,ve)=>{const yt=E[ve];return fe.split(`
4262`).map(We=>({...yg(aI(Math.max(T,Math.ceil(We.length/10)))),assetIds:[yt],captionMode:ar.MANUAL,captions:[{text:wt().fromText(We)},{text:wt().fromText("")}]}))});a(ur(3/6));const{assetFileInfos:S,assets:R}=f,y=zn({}),v={};for(const[fe,ve]of Object.entries(R))L.set(y,ve.trackId,ve),L.set(v,Je(fe),{trackIds:[ve.trackId],role:"sub"});const w=b2(t,{tracks:y,assets:v},o),N=S.imageMediaInfos?.map(fe=>fe.info)??[],M=S.imageMediaInfos?.reduce((fe,ve)=>(fe[ve.info.mediaId]=ve.blob,fe),{})??{},{blankInfo:k,blankAudioBlob:F}=mN(),G=[...N,k],B={...M,[k.mediaId]:F},W=vd({files:G,blobs:B,dispatchType:Ee.MEDIA,projectOption:{currentPath:u,projectId:qe.v4(),props:w,fromAutosave:!1,fromIOS:!1}});await i(T0(W)),a(ur(4/6));const{trackEntries:Q,baseAssetEntries:j,videoRatio:$}=w,q=await OT(s),H=Object.values(Q).find(Rr),U=q&&!H?await ST(mi.BLACK,$):void 0,te=U?{...Q,[U.trackId]:U}:Q,ne=[{clips:O,id:ct()}],oe=_N(ne),re=Zg(j,oe),ge={...w,assetEntries:re,trackEntries:te};
4262if(i(ig(ne,null,ge,null,pn.None)),a(ur(5/6)),n){const fe=O.flatMap(ve=>ve.assetIds);i(PK(fe))}a(ur(6/6))},uNt=(e,t,o,r,n)=>async a=>{const i=n?n.stockSite===ws.STABILITY||n.stockSite===ws.RAY_DIFFUSION?{type:Za.GEN_ASSET,provider:n.stockSite,assetType:"image"}:{type:Za.FREE_SOURCE,keywordType:FU.USER,stockSite:n.stockSite??ws.UNKNOWN,assetType:n.assetType,freeAssetSection:d9.ALL_TAB}:void 0,{aspectRatio:s,longAxisRatio:x,xPos:c,yPos:l,rotation:d,fillType:u}=o;try{const p=n?.imageImportType??_e.UNKNOWN;a(RK(t,z.IMAGE,e,s,{importType:p,imageKenburnsInfo:r,xPos:c,yPos:l,rotation:d,longAxisRatio:x,fillType:u??(r?"cut":void 0)},i))}catch(p){const f=P(p);h("transcript.ts").error(f),Y().error(_.C_MEDIA_IMAGE_FILE_READ_ERROR,A("error.stock_image_error"))}},pNt=(e,t,o,r,n=null)=>async a=>{let i=!1;const s=()=>{i=!0};o.signal.addEventListener("abort",s);try{const x=new Jo,c=Lt(),l={updateProgress:(E,T)=>{if(T.progressRatio!==void 0){const O=Math.round(T.progressRatio*100);r.onProgress(O)}}};await c.redeemProject(e);const d=at()?await new Oi().createTempFolder(["vrew"]):"",u=!0,p=await c.downloadCloudProject(e,e,zS,d,l,o,u);if(p.result!=="success")throw new Error("Failed to download template project");if(c.resetSharedProject(),at()){const E=a0(d,zS),T=a0(E,fg),O=a0(E,zS+".vrew");se().setSampleProjectSourceDir(T),await a(ag({loadingType:"template",filePath:O,addSceneIndex:n,templateName:t}))}else await a(ag({loadingType:"template",filePath:p.projectId,addSceneIndex:n,templateName:t}));n!==null&&a(mze(n));const f=x.getElapsedSec();h("transcript.ts").info("Template "+e+" loaded in "+f+"s (addSceneIndex: "+n+")"),Yo().updateTemplateApplyInfo(t),r.onSuccess()}catch(x){if(i){h("transcript.ts").info("Template loading cancelled by user"),r.onCancel();return}h("transcript.ts").error("TemplateLoadFailed: "+P(x)),Lt().resetSharedProject(),r.onError()}finally{o.signal.removeEventListener("abort",s)}},DK=(e,t,o)=>async r=>{const n=iI(e.words),a=n&&Q0(n),i=a?cs(e)-n.duration:cs(e);if(o>i){const s=o-i,x=Math.max(U1,Math.min(Math.ceil(s*1e3)/1e3,V1));if(a){const c=xs(e)-1;r({type:ot.CHANGE_SPACER_TIME,payload:{targetGlobalPositions:[c],duration:x}})}else{const c=e.words.length-1;r({type:ot.ADD_SPACER,payload:{targets:[{globalClipIndex:t,insertionWordIndices:[c],playDuration:x}],freeze:!0}})}}else if(a){const s=xs(e)-1;r({type:ot.REMOVE_SPACER,payload:{targetGlobalPositions:[s]}})}},fNt=e=>t=>{t({type:ot.AGENT_RESTORE_SNAPSHOT,payload:{transcript:e}}),t(qx.ActionCreators.clearHistory())},kK="\uFEFF";var P0=(e=>(e[e.NOT_SUPPORT=0]="NOT_SUPPORT",e[e.NO_NEED_SAVE=1]="NO_NEED_SAVE",e[e.SAVED=2]="SAVED",e[e.DONT_SAVE=3]="DONT_SAVE",e[e.CANCEL=4]="CANCEL",e))(P0||{});const FK=async(e,t)=>{const o=A("filetype."+e);if(at()){const r={bodyClassName:"description-modal",title:A("popup.title_confirm"),content:jt.createElement("div",{className:"content"},jt.createElement("div",{className:"msg"},A("export.filetype_done",{filetype:o})),jt.createElement("div",{className:"desc"},Wc(A("video_lock.guide")))),yesStr:A("export.open_folder"),noStr:A("popup.close")};return await Y().popup(r)===mt.YES&&Ue().openFolder(t),!0}else return xt.success(A("export.filetype_done",{filetype:o})),!0},fb=async(e,t,o)=>at()?(await Ue().showSaveDialog(t,o,e))?.name:e,UK=async(e,t)=>{const o=kK+t,r=Ue();if(r instanceof l_){const n=gt(e);return r.downloadBlobAsFile(new Blob([o],{type:"text/plain"}),n),n}return await r.addFile(e,o,"utf8"),e},_9e=()=>async e=>{const t=se(),o=Yo();if(ks()===void 0)return 1;const n=h("fs.ts");try{const a=!t.isProjectSaved(),i=at()?Ee.PROJECT:Ee.BROWSER,s=await z5(a,i,t.getCurrentProjectPath(),t.getProjectId());if(s===void 0)return n.info("save dialog cancelled."),4;const x=new Jo,c=o.getLastSaveInfo(),l=gT(c,a);await e(MK(s.savePath));const d=ks();if(d===void 0)return h("fs.ts").error("stateForSave is undefined"),4;const u=await KT(d,s.projectId,l);if(!u)return h("fs.ts").error("invalid redux state"),4;const p=x.getElapsedSec(),f=!0,E=ZP(d,u.projectId),T=await cP(i,s.savePath,s.projectName,u,f,p,E);return T===2&&(a&&t.markProjectAsNamed(),o.updateSaveInfo(l)),T}catch(a){const i=Ne(a)?Ot(a.errorCode,{errorArg:a.errorArgs,defaultKey:"error.vrew_save_failed"}):P(a);return h("fs.ts").error("Error during saving : "+i),3}},Ch=async e=>{const t=se();if(!t.getFileNeedSave())return await n0.getInstance().stopPolling(),1;const o=Y(),r={OPEN_NEW:"transcribe.close_remind_description",CONFIG_
4262CHANGED:"popup.config_change_close_remind_description",UPDATE:"popup.update_save_remind_description",USER_CLOSE:"popup.user_close_save_remind_description",EXPORT_PROJECT_FILE:"popup.export_project_file_save_remind_description"},n={bodyClassName:"general-modal",title:A("popup.title_save_project"),content:A(r[e]),yesStr:A("popup.yes_save"),noStr:A("popup.no_save"),extraStr:A("popup.cancel_progress")},a=Og();for(;;)switch(await o.popup(n)){case mt.CLOSE:case mt.CANCEL:return 4;case mt.NO:return await n0.getInstance().stopPolling(),3;default:try{if(t.isCloudProject()){const x=t.getProjectId();if(!x)throw h("fs.ts").error("projectId is undefined in trySave"),new C(_.C_LOGIC_ERROR,void 0,"projectId is undefined in trySave");return await Lt().ensureEditingSessionAndSync(x),await Lt().saveVrewJsonToCloud(await WD(ks()),x),await n0.getInstance().stopPolling(),2}if(t.isMedia()&&uN()==="cloud"){const x=t.getProjectId(),c=await WD(ks());return(await hA(x,c)).success?(await Lt().ensureEditingSessionAndSync(x),await Lt().saveVrewJsonToCloud(c,x),await n0.getInstance().stopPolling(),2):4}return await a(_9e())}catch(s){if(ye(s)===_.C_VREW_FILE_IN_SHARED_FOLDER_WRITE){await o.warn(A("error.project_file_no_shared_folder_write"));continue}if(Ne(s)&&s.errorCode===_.C_VCLOUD_SESSION_ERROR)return h("fs.ts").info("[trySave] cloud session error: close cloud project"),a(SK()),4;throw s}}},E9e=async()=>!(await sv()===iv.STAY_IN_PROJECT||await Ch("OPEN_NEW")===4),A0=e=>"blob"in e&&e.blob instanceof Blob,VK=async e=>{const t=A0(e)?e.blob:void 0;if(t)return t;const o=an(e.name);return await fetch(o).then(r=>r.blob())},gNt=async e=>X0.getExtension(e.type)??await Bs(e),m9e=async e=>{const t=await(await fetch(an(e))).blob();return new File([t],gt(e),{type:t.type})},h9e=e=>
4262e.type.split("/")[0]===z.VIDEO&&Lh.indexOf(e.type.split("/")[1])!==-1,I9e=e=>!!vU.test(e),T9e=e=>!!oy.test(e),S9e=e=>!!bi(Fh).test(e.toLowerCase()),GK=(e,t,o)=>{if(!o)return;const r=L.get(t,o);return!r||r.role!=="sub"?void 0:r.trackIds.map(a=>L.get(e,a)).find(a=>a!==void 0&&xr(a)&&!Rr(a))?.type},O9e=(e,t,o,r,n)=>{const a=Uc.WIDTH_RATIO,i=o>1?a:a*o/r,s=o>1?a*r/o:a,x=L.get(yU,Uc.VREWMARK_DEFAULT_POS);if(x===void 0)throw new C(_.C_LOGIC_ERROR,void 0,"invalid default position of vrewmark");const{X_RATIO:c,Y_RATIO:l}=x;return{trackId:e,type:z.WATERMARK,mediaId:t,xPos:c,yPos:l,width:i,height:s,rotation:0,vrewMarkInfo:n}},_Nt=(e,t,o,r,n,a,i)=>{switch(e){case z.IMAGE:case z.LOTTIE:case z.WEB:case z.SHAPE:case z.SIMPLE_CHARACTER:{const s=C9e(e,t,o,r,n,a,i);return s&&!Rr(s)?s:null}case z.VIDEO:return cN(t,o,r,n,a,i);default:return null}},C9e=(e,t,o,r,n,a,i)=>{switch(e){case z.IMAGE:return gb(t,o,r,n,a,i);case z.VIDEO:{if(i?.role===void 0)throw new C(_.C_LOGIC_ERROR,{},"role is required for video asset");return pT(t,o,r,n,a,i)??null}case z.LOTTIE:return y9e(t,o,r,a,i);case z.WEB:return A9e(t,o,a,i);case z.SHAPE:return i?.shapeData===void 0?null:R9e(t,o,a,i.shapeData.key,i.shapeData.option,cr(n));case z.SIMPLE_CHARACTER:{if(i?.selectedCharacter===void 0)throw new C(_.C_INVA
4262LID_ASSET_FORMAT,{},"No selected character");const x=i?.simpleCharInfo;if(!x)throw new C(_.C_INVALID_ASSET_FORMAT,{},"No simpleCharInfo");return w9e(t,o,a,r,x.hasAnimation,x.isPreset,n,x.silentMediaId,x.speakingMediaId)}default:return null}},R9e=(e,t,o,r,n,a,i="part")=>ile[r](e,t,o,a,n,i),A9e=(e,t,o,r)=>{const n=r?.importType??Yt.UNKNOWN;if(r?.webAssetData===void 0)throw new C(_.C_INVALID_ASSET_FORMAT);const a=r.webAssetData,i=.6,s=.2,x=.5-i/2,c=.5-s/2;return{trackId:e,mediaId:t,type:z.WEB,xPos:r.xPos??x,yPos:r.yPos??c,width:i,height:ay,rotation:0,zIndex:o,importType:n,deltas:a.deltas,customAttributes:a.customAttributes,enabledInlineTypes:a.enabledInlineTypes,durationSeconds:a.durationSeconds??0,loop:a.loop??!0,scaleFactor:cr(he.INIT)}},y9e=(e,t,o,r,n)=>{const a=n?.frameRate??0,i=n?.lottieData??"",s=se().getInitProjectVideoSize(),x=s.width/s.height,c=.7,l=o>1?c:c*o/x,d=o>1?c*x/o:c,u=.5-l/2,p=.5-d/2;try{const f=JSON.parse(i);return{trackId:e,mediaId:t,type:z.LOTTIE,xPos:u,yPos:p,width:l,height:d,frameRate:a,data:i,rotation:0,zIndex:r,heightScale:1,widthScale:1,frameLength:Math.round(f.op-f.ip)}}
4262catch{throw new C(_.C_INVALID_ASSET_FORMAT)}},gb=(e,t,o,r,n,a)=>{const s=cr(r),x=a?.longAxisRatio,c=a?.xPos,l=a?.yPos,d=a?.rotation,u=c!==void 0&&l!==void 0,p=a?.imageKenburnsInfo,f=a?.importType??_e.UNKNOWN,E=x!==void 0?x:.7,T=o>1?E:E*o/s,O=o>1?E*s/o:E,[S,R]=u?[c,l]:[.5-T/2,.5-O/2],y=d??0;return{trackId:e,mediaId:t,type:z.IMAGE,xPos:S,yPos:R,width:T,height:O,rotation:y,zIndex:n,originalWidthHeightRatio:o,importType:f,stockSource:a?.stockSource,stats:{isTransparent:a?.isTransparent,fillType:a?.fillType,aiStylizedCaptionAssetId:a?.aiStylizedCaptionAssetId},assetEffectInfo:a?.assetEffectInfo,kenburnsAnimationInfo:p,editInfo:{crop:a?.crop}}},v9e=(e,t,o)=>{if(!t)return e;const r=ce.English;return(t[o]&&Object.keys(t[o]).length>0?t[o]:t[r])?.[e]??e},ENt=(e,t,o)=>{if(!t)return null;const r=ce.English;return(t[o]&&Object.keys(t[o]).length>0?t[o]:t[r])?.[e]},mNt=(e,t)=>{const o={};return e.filter(r=>{const n=v9e(r,t,ce.English);return o[n]?!1:(o[n]=!0,!0)})},hNt=(e,t,o)=>{const r=[],n={};return e.forEach(i=>{i.tags.forEach(s=>{n[s]!==void 0?n[s]+=1:n[s]=0}),r.push(...i.tags)}),Array.from(new Set(r)).sort((i,s)=>{const x=o?.[i]||0,c=o?.[s]||0;return x||c?c-x:(n[s]??0)-(n[i]??0)}).slice(0,t)},w9e=(e,t,o,r,n,a,i,s,x)=>{const c=cr(i),l=.5,d=l*Math.min(1,r/c),u=l*Math.min(1,c/r),p=.5-d/2,f=.5-u/2;return{trackId:e,mediaId:t,type:z.SIMPLE_CHARACTER,xPos:p,yPos:f,width:d,height:u,rotation:0,zIndex:o,isPreset:a,isMouthApplied:n,pose:{isPreset:!0,presetType:"static",labelKey:"character.pose.static",silentMediaId:s,speakingMediaId:x}}},INt=e=>{const t=e.filter(c=>c.type==="video"),o=e.filter(c=>c.type==="image"),r=e.filter(c=>c.type==="shape"),n=o.filter(c=>
4262c.stockSite===ws.OPENMOJI),a=o.filter(c=>c.stockSite===ws.VREW),i=o.filter(c=>c.stockSite===ws.PEXEL||c.stockSite===ws.PIXABAY),s=Math.max(n.length,a.length,i.length,t.length,r.length);return x0(0,Math.ceil(s/2)).reduce(c=>(c.push(...t.splice(0,2)),c.push(...i.splice(0,2)),c.push(...r.splice(0,2)),c.push(...n.splice(0,2)),c.push(...a.splice(0,2)),c),[])},TNt=(e,t,o,r)=>{let n=[];switch(e){case Kr.ALL:n=[...o,...t,...r];break;case Kr.Image:n=[...o];break;case Kr.Video:n=[...t];break}return n},N9e=e=>e===null?Oc.UNKNOWN:bi(Ed).test(e.name)?Oc.VIDEO:oy.test(e.name)?Oc.GIF:Oc.IMAGE,SNt=async(e,t,o,r)=>{try{switch(N9e(e)){case Oc.VIDEO:{if(await y4())return null;const a=async()=>{if(!at()){const O=e.blob,S=await fd({type:"blob",blob:O,name:e.name});return S?{pathOrBlob:O,assetVideoInfo:S}:null}const E=await I4([e.name],{insertionTarget:Ds.ASSET,method:c2.TOOLBAR,from:l2.PC});if(E.length===0)return null;const T=await fd({type:"path",value:E[0]});return T?{pathOrBlob:E[0],assetVideoInfo:T}:null},i=await a();if(i===null)return null;const s={pathOrBlob:i.pathOrBlob,filename:gt(e.name),type:Pt.VIDEO};await Ih([s],t,o,r);const{mediaId:x,videoAudioMetaInfo:c}=i.assetVideoInfo,{videoInfo:l,duration:d}=c;if(!l){const E="no videoInfo when selectImageOrVideoFiles";throw h("asset.ts").error(E),new C(_.C_SELECT_ASSET_VIDEO_FILE_ERROR,{},E)}const{width:u,height:p}=I0(l.size),f=u/(p??1);return{type:"video",asset:{type:Pu.Video,mediaId:x,aspectRatio:f,duration:d,videoOrigin:If.ORIGINAL},info:i.assetVideoInfo}}case Oc.GIF:{const a=await u_e(e.name);return a===void 0?null:{type:"gif",asset:{...a.asset,videoOrigin:If.TRANSCODE_GIF},info:a.info}}case Oc.IMAGE:{const a=async()=>{if(!at()){const u=e.blob,p=await o7(u);return{blob:u,result:{asset:p}}}const x=A0(e),{imageInfo:c,aspectRatio:l}=x?await LTe(e.blob):await e7(e.name),d=await En(c.mediaId);if(!d){const u="[handleImportImage] Image not found for mediaId: "+c.mediaId;throw h("asset.ts").error(u),new C(_.C_MEDIA_BLOB_LOST,{},u)}return{blob:d,result:{asset:{type:Pu.Image,mediaId:c.mediaId,aspectRatio:l}}}},{blob:i,result:s}=await a();return await Ih([{blob:i,type:Pt.IMAGE}],t,o,r),s.asset?{type:"image",asset:s.asset}:null}case Oc.UNKNOWN:return null}}catch(n){h("asset.ts").warn("putImageOrVideoFile",P(n));const a=ye(n)??_.C_SELECT_IMAGE_FILE_ERROR,i=Ot(a,{defaultKey:"error.asset_video_error"});return Y().error(a,i),null}},_b=(e,t,o)=>{const r=e/(t||1),n=r<=1;switch(o){case"contain":{const a=n?r:1,i=n?1:1/r;return{xPos:n?.5-a/2:0,yPos:n?0:.5-i/2,width:a,height:i}}case"cut":{const a=n?1:r,i=n?1/r:1;return{xPos:n?0:.5-a/2,yPos:n?.5-i/2:0,width:a,height:i}}case"cover":return{xPos:0,yPos:0,width:1,height:1}}},WK=async(e,t,o,r,n,a)=>{const i=await Promise.all(e.map(async c=>{const l=await M2(c),d=l.blob,u=l.isTransparent,p=qe.v4();await vi(d,u,void 0,p);const f=oa(p);if(!f){const E="[generateImageAssetMap] Image not found for mediaId: "+p;throw h("asset.ts").error(E),new C(_.C_MEDIAINFO_NOT_EXIST,{},E)}return{info:f,blob:d}})),s=i.map(()=>ho()),x=e.reduce((c,l,d)=>{const u=t[d]/o[d],{xPos:p,yPos:f,width:E,height:T}=_b(u,r,n),O={trackId:Rt(),importType:_e.MODAL_UPLOAD,mediaId:i[d].info.mediaId,originalWidthHeightRatio:u,type:z.IMAGE,width:E,height:T,xPos:p,yPos:f,rotation:0,zIndex:0,kenburnsAnimationInfo:a,stats:{fillType:n}};return c[s[d]]=O,c},{});return{assetFileInfos:{imageMediaInfos:i},assets:x,assetIds:s}},P9e=e=>Math.max(...[...Object.values(e)].filter(t=>t.role==="sub").map(t=>t.track.zIndex),0)+1,ONt=(e,t)=>{const o=Object.values(t).filter(r=>r.role==="sub").flatMap(r=>r.trackIds.map(n=>L.get(e,n))).filter(r=>r!==void 0&&xr(r)&&!Rr(r)).map(r=>r.zIndex);return Math.max(...o,0)+1},HK=(e,t)=>{const o=new Map;return Object.entries(t).forEach(([r,n])=>{if(n.role!=="sub"){o.set(Je(r),0);return}const a=n.trackIds.map(i=>L.get(e,i)).filter(i=>i!==void 0&&xr(i)&&!Rr(i));o.set(Je(r),Math.max(...a.map(i=>i.zIndex),0))}),o},CNt=(e,t)=>{const o=new Set(Object.values(t).filter(a=>a.role==="sub").flatMap(a=>a.trackIds)),r=Object.values(e).filter(a=>o.has(a.trackId)&&xr(a)&&!Rr(a)).sort((a,i)=>a.zIndex-i.zIndex),n={...e};return r.forEach((a,i)=>{L.set(n,a.trackId,{...a,zIndex:i})}),n},Rh=(e,t,o)=>{const r=e.words[0].assetIds.filter(i=>{const s=L.get(o,i);return!s||s.role!=="sub"?!1:s.trackIds.map(c=>L.get(t,c)).filter(Se).some(c=>!Wa(c)||!Id(c))}),n=new Set(r.filter(i=>e.words.slice(1).every(s=>s.type===Z.ENTER||s.assetIds.includes(i))));return{...e,assetIds:[...e.assetIds,...n],words:e.words.map(i=>({...i,assetIds:i.assetIds.filter(s=>!n.has(s))}))}},jK=(e,t)=>{const o=Object.keys(e),r=Object.keys(t).filter(n=>!o.includes(n));return o.filter(n=>{const a=L.get(e,n),i=L.get(t,n);return a===void 0?!1:i===void 0||a.words.length!==i.words.length}).concat(r)},RNt=(e,t,o,r)=>{const n=Object.fromEntries(e.map(s=>[ai(s),s])),a=Object.fromEntries(t.map(s=>[ai(s),s])),i=jK(n,a);return vt(r,s=>{for(const x of i){const c=L.get(a,x);if(!c)return;for(const l of c.assetIds){const d=L.get(s,l);if(!d||d.role!=="sub"||d.rangeType!==tr.WORD)continue;const u=d.trackIds.map(p=>L.get(o,p)).filter(Se);u.length===0||u.every(p=>Wa(p)&&Id(p))||L.set(s,l,{trackIds:d.trackIds,role:d.role,rangeType:tr.CLIP})}}})},ANt=(e,t,o)=>vt(o,n=>{for(const a of e)for(const i of a.assetIds){const s=L.get(n,i);if(!s||s.role!=="sub"||s.rangeType!==tr.WORD)continue;const x=s.trackIds.map(c=>L.get(t,c)).filter(Se);x.length===0||x.every(c=>Wa(c)&&Id(c))||L.set(n,i,{trackIds:s.trackIds,role:s.role,rangeType:tr.CLIP})}}),yNt=(e,t,o,r)=>{const n=Object.fromEntries(e.map(x=>[ai(x),x])),a=Object.fromEntries(t.map(x=>[ai(x),x])),i=jK(n,a);return vt(r,x=>{for(const c of i){const l=L.get(a,c);if(!l)continue;const d=l.words.flatMap(u=>u.assetIds);for(const u of d){const p=L.get(x,u);if(!p||p.role!=="sub"||p.rangeType!==tr.CLIP)continue;const f=p.trackIds.map(E=>L.get(o,E)).filter(Se);f.length===0||f.every(ll)||L.set(x,u,{...p,rangeType:tr.WORD})}}})},b9e=e=>{if(D9e(e))try{return JSON.parse(e)}catch(t){h("asset.ts").error("Error occured while parsing AssetIconDnDPayload. error:"+P(t))}},L9e=e=>{if(k9e(e))try{return JSON.parse(e)}catch(t){h("asset.ts").error("Error occured while parsing UserImageDnDPayload. error:"+P(t))}},M9e=e=>{if(F9e(e))try{return JSON.parse(e)}catch(t){h("asset.ts").error("Error occured while parsing UserVideoDnDPayload. error:"+P(t))}},D9e=e=>e.includes("assetId")&&e.includes("from")&&e.includes("assetType"),k9e=e=>e.includes("imageHash")&&e.includes("index")&&e.includes("sectionType"),F9e=e=>e.includes("videoHash"),U9e=e=>e===kn.USER_ASSET_LIBRARY,vNt=async(e,t,o,r)=>{if(!window.indexedDB)return;const n=Y(),a=[],i=[],s=[],x=[];for(let E=0;E<e.length;E++){const T=e[E];I9e(T.name)?a.push(T):T9e(T.name)?s.push(T):S9e(T.name)?i.push(T):(x.push(gt(T.name)),HFe(T.type))}x.length>
42620&&n.warn(zr("user_asset.files_with_invalid_type",{INVALID_FILE_NAMES:x.join(", ")}));const c=[],l=[];i.forEach(E=>{h9e(E)?c.push(E):l.push(gt(E.name))}),!at()&&l.length>0&&(n.warn(zr("transcode.unavailable_in_trial",{UNAVAILABLE_FILE_NAMES:l.join(", ")})),VFe(l.length));const d=await Ue().getFilePath(i);if(at()){for(const E of d)if(!await Vf(E)){h("asset.ts").error("Asset video file is too big : "+E),n.error(_.C_ASSET_VIDEO_TOO_BIG_ERROR,Ot(_.C_ASSET_VIDEO_TOO_BIG_ERROR,{defaultKey:""}));return}}const u=at()?(await I4(d,{insertionTarget:Ds.ASSET,method:c2.DRAG_AND_DROP,from:l2.PC})).map(E=>({pathOrBlob:E,filename:gt(E),type:Pt.VIDEO})):c.map(E=>({pathOrBlob:E,filename:gt(E.name),type:Pt.VIDEO})),p=(await Ue().getFilePath(s)).map(E=>({pathOrBlob:E,filename:gt(E),type:Pt.GIF})),f=a.map(E=>({blob:E,type:Pt.IMAGE}));await Ih([...u,...f,...p],eu.DRAG_AND_DROP_TO_MYASSET,t,o),r(CB(f.length,u.length,p.length))},V9e=async e=>e>Si?(Y().message(zr("user_asset.max_imported_img_cnt_exceed_warning_title"),zr("user_asset.max_imported_img_cnt_exceed_warning_desc",{MAX_IMPORTED_ASSET_CNT:Si,IMPORTED_IMG_CNT:e})),!0):!1,G9e=async e=>e>Si?(Y().message(zr("user_asset.max_imported_video_cnt_exceed_warning_title"),zr("user_asset.max_imported_video_cnt_exceed_warning_desc",{MAX_IMPORTED_ASSET_CNT:Si,IMPORTED_VIDEO_CNT:e})),!0):!1,W9e=async(e,t,o,r)=>{const n=e>Si,a=t+o>Si;!n&&!a||(n&&a?Y().message(zr("user_asset.max_imported_img_and_video_cnt_exceed_warning_title"),zr("user_asset.max_imported_img_and_video_cnt_exceed_warning_desc",{MAX_IMPORTED_ASSET_CNT:Si,IMPORTED_VIDEO_CNT:t,IMPORTED_IMG_CNT:e})):n?await V9e(e):a&&await G9e(t),WFe(e,t,o,r))},wNt=async(e,t,o)=>{const r=L9e(e),n=M9e(e),a=b9e(e);try{if(r){const{imageHash:i,index:s,sectionType:x}=r,c=await UTe(i);if(!c)return;const{blob:l,isFavorite:d}=c,{mediaId:u,aspectRatio:p}=await o7(l),f={type:Za.USER_ASSET,index:s,sectionType:x,insertMethod:nm.DRAG_AND_DROP,hash:i,isFavoriteAsset:d};t(z.IMAGE,u,p,f)}else if(n){const{videoHash:i,index:s,sectionType:x}=n,c=await Z8e(i);if(!c)return;const{src:l,blob:d,isFavorite:u}=c;let p=d;if(p===void 0){if(!await Ue().checkUserVideoValidPath(l)){h("asset.ts").error("Invalid video path: "+l);return}const w=an(l);p=await fetch(w).then(N=>N.blob())}if(p===void 0){h("asset.ts").error("No blob: "+l);return}const f=await fd({type:"blob",blob:p,name:gt(l)});if(!f)return;const{mediaId:E}=f;if(!f.videoAudioMetaInfo.videoInfo){const y="[handleImportImage] Video not found for mediaId: "+E;throw h("asset.ts").error(y),new C(_.C_SELECT_ASSET_VIDEO_FILE_ERROR,{},y)}const{width:T,height:O}=I0(f.videoAudioMetaInfo.videoInfo.size),S=T/O,R={type:Za.USER_ASSET,index:s,sectionType:x,insertMethod:nm.DRAG_AND_DROP,hash:i,isFavoriteAsset:u};t(z.VIDEO,E,S,R)}else o&&a&&o(a)}catch(i){const s=ye(i)??_.C_DND_ASSET_IMPORT_ERROR,x=Ot(s,{defaultKey:""});h("asset.ts").error("Error while handleDndAssets : "+P(i)+" "),Y().error(s,x)}},NNt=e=>A_(e.type),A_=e=>e===z.SIMPLE_CHARACTER||e===z.IMAGE||e===z.VIDEO||e===z.LOTTIE||e===z.SHAPE||e===z.WEB,rU=(e,t)=>t===0?1:e/t,PNt=(e,t,o,r,n)=>{const a=o?t/o:1,i=cr(r),{width:s,height:x,xPos:c,yPos:l,rotation:d}=e,u=a>1?s:x,p=n===z.VIDEO?Math.min(1,u):u,f=c+s/2,E=l+x/2,T=a>1?p:p*a/i,O=a<=1?p:p*i/a,[S,R]=[f-T/2,E-O/2];return{longAxisRatio:p,xPos:S,yPos:R,rotation:d}},bNt=(e,t)=>vt(e,o=>{Object.entries(o).forEach(([r,n])=>{Wn(n)&&(o[kr(r)]={...n,updateReason:t})})}),H9e=e=>oa(e.mediaId)?.sourceOrigin===tt.AI_GENERATED,LNt=e=>eo(e.mediaId)?.sourceOrigin===tt.AI_GENERATED,j9e=e=>eo(e.mediaId)?.sourceOrigin===tt.AI_GENERATED,MNt=e=>e.map(z9e).filter(Se),z9e=e=>{switch(e.type){case z.IMAGE:return e.stats?.fillType;case z.VIDEO:return e.fillType;default:return}},nU=(e,t)=>{const{assetType:o,isAIGenerated:r,isDesignTextbox:n}=t;switch(o){case z.IMAGE:return e.type===z.IMAGE&&(r?H9e(e):!0);case z.VIDEO:return J0(e)&&(r?j9e(e):!0);case z.WEB:return e.type===z.WEB&&(n?e.mediaId!==Ao:!0);case z.LOTTIE:return e.type===z.LOTTIE;case z.SIMPLE_CHARACTER:return e.type===z.SIMPLE_CHARACTER;case z.SHAPE:return e.type===z.SHAPE;case ze.BGM:case ze.SoundEffect:case ze.TTSEffect:case ze.TTSDubbing:return e.type===o;default:return!1}},Y9e=(e,t,o,r)=>{switch(e.type){case kp.PROJECT_RANGE:return{type:Or.SCENE,model:t};case kp.SCENE_RANGE:{const n=t.at(o);return n?{type:Or.SCENE,model:[n]}:void 0}case kp.SELECTED_CLIP_RANGE:{const n=Array.from(r).map(a=>t.at(o)?.clips.at(a)).filter(Se);return r.size!==n.length?void 0:{type:Or.CLIP,model:n}}case kp.DIRECT_INPUT:{const n=e.clipIndices,a=n.map(i=>t.at(o)?.clips.at(i)).filter(Se);return n.length!==a.length?void 0:{type:Or.CLIP,model:a}}default:return{type:Or.SCENE,model:t}}},DNt=(e,t,o,r,n,a)=>{const i=Y9e(e,t,o,r);if(!i)return;const s=new Li(void 0,void 0,n,a).collectFrom(i).build(),x=s.getUsedSubAssetIds();return Array.from(x)},kNt=(e,t,o,r)=>e.map(a=>{const i=L.get(r,a);if(!i)return;const s=i.trackIds.map(l=>L.get(o,l)).filter(Se);if(s.length===0)return;const x=s.find(l=>
4262xr(l)&&!Rr(l));if(x)return nU(x,t)?{id:a,type:ra.ASSET}:void 0;const c=s.find(cd);if(c)return nU(c,t)?{id:a,type:ra.AUDIO}:void 0}).filter(Se),FNt=(e,t)=>{const o=HK(e,t);return(r,n)=>{const a=o.get(r)??0;return(o.get(n)??0)-a}},UNt=(e,t)=>{const o=HK(e,t);return(r,n)=>{const a=o.get(r)??0,i=o.get(n)??0;return a-i}},Ah=(e,t)=>Object.keys(t).reduce((o,r)=>{const n=L.get(o,r);if(n!==void 0){let a=n;for(;L.get(o,a)!==void 0;)a=L.get(o,a);L.set(o,a,t[r])}else L.set(o,r,t[r]);return o},{...e}),VNt=e=>{const{xPos:t,yPos:o,width:r,height:n}=e,a=u9,i=qb(t,a-r,1-a),s=qb(o,a-n,1-a);return[i,s]},B9e=e=>e.element.type,K9e=e=>{switch(e.type){case z.IMAGE:{const t=oa(e.mediaId,{excludeBroken:!0});return!!(!t||t.broken)}case z.SIMPLE_CHARACTER:{const t=oa(e.pose.silentMediaId,{excludeBroken:!0}),o=eo(e.pose.silentMediaId,{excludeBroken:!0});if(!(t&&!t.broken||o&&!o.broken))return!0;if(e.pose.speakingMediaId){const n=eo(e.pose.speakingMediaId,{excludeBroken:!0});if(!n||n.broken)return!0}return!1}case z.WEB:{if(e.mediaId===Ao)return!1;const t=UT(e.mediaId,{excludeBroken:!0});return!!(!t||t.broken)}case z.VIDEO:{const t=eo(e.mediaId,{excludeBroken:!0});if(!t||t.broken)return!0;const o=e.audio?.mediaId;if(o){const r=eo(o,{excludeBroken:!0});if(!r||r.broken)return!(t&&!t.broken)}return!1}case z.SHAPE:{if(e.dimensionType===Tr.ONE)return!1;const t=x_(e.mediaId,{excludeBroken:!0});return!!(!t||t.broken)}case ze.SoundEffect:case ze.BGM:{const t=eo(e.mediaId,{excludeBroken:!0});return!!(!t||t.broken)}case ze.TTSEffect:case ze.TTSDubbing:{const t=eo(e.mediaId,{excludeBroken:!0});return!!(!t||t.broken)}case z.WATERMARK:{const t=oa(e.mediaId);return!!(!t||t.broken)}}return!1},GNt=e=>e.xPos>0||e.yPos>0||e.xPos+e.width<1||e.yPos+e.height<1,X9e=e=>J0(e)?e.audio?.volume??RU:e.volume,CS=(e,t,o)=>{const r=[],{activeVisualSubAssetIds:n,activeAudioSubAssetIds:a}=Array.from(e).reduce((i,s)=>{const x=L.get(o,s);if(!x||x.role!=="sub")return i;const c=x.trackIds.map(d=>L.get(t,d)).filter(Se);return c.length===0||(c.some(d=>xr(d)&&!Rr(d))?i.activeVisualSubAssetIds.push(s):i.activeAudioSubAssetIds.push(s)),i},{activeVisualSubAssetIds:[],activeAudioSubAssetIds:[]});return r.push(...n.map(i=>({id:i,type:ra.ASSET}))),r.push(...a.map(i=>({id:i,type:ra.AUDIO}))),r},zK=(e,t,o,r,n)=>{const a=eo(t);if(!(!a&&n!==!0))switch(o){case ze.TTSClip:case ze.VideoAudio:case ze.SoundEffect:case ze.BGM:{const i=r.sourceOut??(a?pe(a.videoAudioMetaInfo.duration):r.sourceIn);return{trackId:e,mediaId:t,type:o,volume:r.volume,fade:r?.fade,sourceIn:r.sourceIn,sourceOut:i,loop:r.loop,playbackRate:r.playbackRate}}case ze.Overdub:{if(!r.overdubId)return;const i=r.sourceOut??(a?pe(a.videoAudioMetaInfo.duration):r.sourceIn);return{trackId:e,mediaId:t,type:o,volume:r.volume,fade:r?.fade,sourceIn:r.sourceIn,sourceOut:i,loop:r.loop,playbackRate:r.playbackRate,overdubId:r.overdubId}}case ze.TTSEffect:case ze.TTSDubbing:{if(!r?.ttsFileInfo)return;const i=r.sourceOut??pe(a?a.videoAudioMetaInfo.duration:r.ttsFileInfo.duration);return{trackId:e,mediaId:t,type:o,volume:r.volume,fade:r?.fade,sourceIn:r.sourceIn,sourceOut:i,loop:r.loop,playbackRate:r.playbackRate,ttsFileInfo:r.ttsFileInfo}}default:return}},yh=(e,t)=>pe(ue(Math.max(e+t,0),2)),J9e=(e,t)=>{const o=q9e(e,t);return Q9e(e,t,o)},q9e=(e,t)=>{const o={asset:{},track:{},clip:{},word:{},overdub:{}};return Object.keys(t.assetEntries).forEach(r=>{o.asset[r]=ho()}),Object.keys(t.trackEntries).forEach(r=>{o.track[r]=Rt()}),Object.keys(t.overdubInfosMap).forEach(r=>{o.overdub[r]=qe.v4()}),e.forEach(r=>{r.clips.forEach(n=>{o.clip[n.id]=qe.v4(),YK(n.words,o)})}),o},YK=(e,t)=>{e.forEach(o=>{t.word[o.id]=qe.v4(),o.truncatedWords.length>0&&YK(o.truncatedWords,t)})},Q9e=(e,t,o)=>{const r=e.map(x=>({...x,id:ct(),clips:x.clips.map(c=>({...c,id:o.clip[c.id]??c.id,assetIds:c.assetIds.map(l=>Je(o.asset[l]??l)),words:c.words.map(l=>BK(l,o))}))})),n=Object.fromEntries(Object.entries(t.assetEntries).map(([x,c])=>[o.asset[x]??x,{...c,trackIds:c.trackIds.map(l=>kr(o.track[l]??l))}])),a=Object.fromEntries(Object.entries(t.trackEntries).map(([x,c])=>{const l={...c,trackId:kr(o.track[x]??x)};return nG(l)?[o.track[x]??x,{...l,overdubId:o.overdub[l.overdubId]??l.overdubId}]:[o.track[x]??x,l]})),i=Object.fromEntries(Object.entries(t.overdubInfosMap).map(([x,c])=>
4262[o.overdub[x]??x,c])),s={...t,assetEntries:n,trackEntries:a,overdubInfosMap:i};return{remappedSceneInfos:r,remappedProps:s}},BK=(e,t)=>({...e,id:t.word[e.id]??e.id,assetIds:e.assetIds.map(o=>Je(t.asset[o]??o)),truncatedWords:e.truncatedWords.map(o=>BK(o,t))}),ed=e=>{let t=0,o=0;return vt(e,n=>{n.forEach(a=>{a.startPosition=t,a.words.forEach(i=>{i.timelineStart=pe(ue(o,2)),o+=Rn(i)}),t+=a.words.length})})},WNt=e=>XK(e)-e.sceneTime,KK=e=>e.length>0?XK(e[e.length-1]):0,XK=e=>{if(e.clips.length===0)return 0;const t=e.clips[e.clips.length-1];return hl(t)},JK=e=>Bg(e.clips),HNt=e=>e.reduce((t,o)=>t+JK(o),0),sp=Gr((e,t,o)=>{const r=new Set;return e.forEach(n=>n.clips.forEach(a=>a.words.forEach(i=>{const{visualMediaIds:s,audioMediaIds:x}=gl(i,t,o);s.forEach(c=>r.add(c)),x.forEach(c=>r.add(c))}))),Array.from(r.values()).filter(n=>n.length>0)}),jNt=(e,t,o)=>{if(e.clips.length===0||e.clips[0].words.length===0)return{visualMediaId:void 0,startTime:0};const r=e.clips[0].words[0],n=Sv(r,t,o);return{visualMediaId:n?.mediaId,startTime:n?.sourceIn??0}},Eb=(e,t,o)=>{let r=0,n=0,a=0,i=0;const s=new Set,x=Object.values(t).find(Rr);for(let c=0,l=e.length;c<l;++c){const d=e[c].clips,u=d.length;n+=u;for(let p=0;p<u;++p){const f=d[p];f.markerId!==void 0&&++r;let E=!1;if(x!==void 0){const T=vo(f);Uc.TIMELINE_START<=T&&T<=Uc.TIMELINE_END&&++i}f.assetIds.forEach(T=>{const O=L.get(o,T);if(!O)return;const S=O.trackIds.map(R=>L.get(t,R)).filter(R=>R!==void 0&&xr(R)&&!oG(R)&&!Wn(R)&&!Rr(R));S.length>
42620&&s.add(T),!E&&S.forEach(R=>{Vi(R.mediaId)&&(E=!0)})}),E&&++a}}return{markerNum:r,clipsNum:n,userImageClipsNum:a,imageIds:Array.from(s.values()),vrewMark:x?.vrewMarkInfo,vrewMarkClipsNum:i}},Z9e=(e,t)=>t.reduce((o,r)=>(e[r]!==void 0&&(o[r]=e[r]),o),{}),zNt=(e,t)=>t.reduce((r,n)=>(e[n]!==void 0&&(r[n]=e[n]),r),{}),$9e=(e,t)=>t===0,eJe=(e,t)=>t===e.length-1,tJe=(e,t,o)=>{const r=e.length-1;if(r===t){const{clips:n}=e[r];return Qxe(n,o)}return!1},YNt=(e,t,o)=>{const r={},n=new Set;return e.forEach((a,i)=>{const s=vo(a),x=hl(a);a.assetIds.forEach(c=>{L.get(t,c)?.role==="main"&&(o?.add("mainAssetInClip"),h("scene.ts").warn("[getAssetTimelineRanges] Main asset in clip.assetIds: "+c));const d=L.get(r,c);d!==void 0?(d.timelineEnd=Math.max(x,d.timelineEnd),d.globalClipRange.to=i+1,d.wordInClipRange.to=a.words.length):L.set(r,c,{timelineStart:s,timelineEnd:x,wordInClipRange:Tm(0,a.words.length,"WORD_IN_CLIP"),globalClipRange:Tm(i,i+1,"GLOBAL_CLIP")})}),a.words.forEach((c,l)=>{const d=c.timelineStart,u=Sd(c);c.assetIds.forEach(p=>{L.get(t,p)?.role==="main"&&(n.has(p)&&(o?.add("duplicateMainAsset"),h("scene.ts").warn("[getAssetTimelineRanges] Duplicate main asset: "+p)),n.add(p));const E=L.get(r,p);E!==void 0?(E.timelineEnd=Math.max(u,E.timelineEnd),E.wordInClipRange.to=l+1,E.globalClipRange.to=i+1):L.set(r,p,{timelineStart:d,timelineEnd:u,globalClipRange:{type:"GLOBAL_CLIP",from:i,to:i+1},wordInClipRange:{type:"WORD_IN_CLIP",from:l,to:l+1}})})})}),r},BNt=(e,t,o,r)=>{let n;const a=new Map;for(const i of Object.keys(e)){const s=L.get(o,i);if(!s){r?.add("missingAssetEntry"),h("scene.ts").warn("[filterAudioFromAssetTimelineRanges] Missing asset entry: "+i),n===void 0&&(n={...e}),L.remove(n,Je(i));continue}const{role:x,rangeType:c}=s;x==="main"&&c!==tr.WORD&&(r?.add("mainAssetRangeTypeClip"),h("scene.ts").warn("[filterAudioFromAssetTimelineRanges] Main asset rangeType is not word: "+i+" (rangeType: "+c+")")),s.trackIds.length===0&&(r?.add("assetWithoutTrack"),h("scene.ts").warn("[filterAudioFromAssetTimelineRanges] Asset has no tracks: "+i));const l=[],d=s.trackIds.reduce((p,f)=>{const E=a.get(f);E?(r?.add("trackReferencedByMultipleAssets"),h("scene.ts").warn("[filterAudioFromAssetTimelineRanges] Track referenced by multiple assets: "+f+" -> ["+E+", "+i+"]")):a.set(f,Je(i));const T=L.get(t,f);return T?p.push(T):l.push(f),p},[]);l.length>0&&(r?.add("missingTrackEntry"),h("scene.ts").warn("[filterAudioFromAssetTimelineRanges] Missing track entries for asset "+i+": "+l.join(", "))),!d.some(p=>xr(p)&&!Rr(p))&&(n===void 0&&(n={...e}),L.remove(n,Je(i)))}return n??e},KNt=(e,t,o)=>{const r=new Li(void 0,void 0,t,o).collectFrom({type:Or.SCENE,model:[e]}).build(),n=r.getUsedSubAssetIds();return CS(n,t,o)},XNt=(e,t,o)=>{const r=new Li(void 0,void 0,t,o).collectFrom({type:Or.GLOBAL_CLIP,model:e}).build(),n=r.getUsedSubAssetIds();return CS(n,t,o)},JNt=(e,t,o)=>{const r=e.clips.flatMap(a=>a.words);return EH(kw(r),t,o).some(a=>pl(a))},oJe=(e,t)=>ci(e).map(r=>({clips:r.clips,id:r.id,name:t[r.id]})),ci=Gr(e=>{if(e.length===0)return[{id:ct(),sceneTime:0,clips:[],globalClipRange:{type:"GLOBAL_CLIP",from:-1,to:-1}}];Mo().getDebugVal(Xt.SCENE_PERF_LOG);const t=[];let o=0;for(;o<e.length;){const r=e[o].sceneId;let n=o+1;for(;n<e.length&&e[n].sceneId===r;)n++;const a=e[o].startPosition,i=e.slice(o,n).map(c=>kf(c,a)),s=i.at(0),x={id:r,sceneTime:s?vo(s):0,clips:i,globalClipRange:{type:"GLOBAL_CLIP",from:o,to:n}};t.push(x),o=n}return t}),qK=Gr((e,t)=>e.map(o=>({...o,name:t[o.id]??""}))),QK=Gr((e,t)=>{const o=e.findIndex(n=>n===t);if(o!==-1)return o;const r="Invalid sceneId: "+t+", globalSceneIds: "+JSON.stringify(e);if(h("scene.ts").error(r),wi())throw new C(_.C_LOGIC_ERROR,void 0,r);return 0}),y_=Gr((e,t)=>{if(t===null||e.length===0)return 0;const o=Er(e,t),r=e[o];if(!r){const a="Invalid globalPosition: "+t+", globalClips len: "+e.length;if(h("scene.ts").error(a),wi())throw new C(_.C_LOGIC_ERROR,void 0,a);return 0}const n=aT(e);return QK(n,r.sceneId)}),qNt=(e,t,o)=>{const r=e.slice(t).findIndex(n=>n.sceneId!==o);return r===-1?e.length-1:t+r-1},QNt=e=>e.map(t=>({sceneId:t.id,title:t.name,clips:t.clips.map(o=>({caption:T2e(o),timelineStart:o.words[0].timelineStart,timelineEnd:o.words[0].timelineStart+ac(o)}))})),ZNt=(e,t)=>
4262e.length!==t.length?e:e.flatMap((o,r)=>t[r].map(a=>({...o,id:ct(),name:a.title,clips:o.clips.slice(a.clipRange.from,a.clipRange.to)})));export{ZZe as $,jQ as A,lmt as A$,Zwe as A0,Yn as A1,Bdt as A2,Zm as A3,XO as A4,RZ as A5,iZ as A6,Kdt as A7,PZe as A8,toe as A9,Gdt as AA,Bmt as AB,zmt as AC,pJe as AD,xc as AE,cpt as AF,lpt as AG,XQe as AH,MQ as AI,INt as AJ,PN as AK,vi as AL,Bgt as AM,Qnt as AN,fwt as AO,ynt as AP,$nt as AQ,emt as AR,kUe as AS,uJe as AT,Rst as AU,qOe as AV,jtt as AW,xpt as AX,hmt as AY,TNt as AZ,NTe as A_,ZT as Aa,Bte as Ab,dqe as Ac,pIt as Ad,fIt as Ae,kRt as Af,NN as Ag,XT as Ah,rV as Ai,Voe as Aj,eIt as Ak,nIt as Al,rIt as Am,oIt as An,$ht as Ao,tIt as Ap,$Q as Aq,ZQ as Ar,QQ as As,JQ as At,XQ as Au,aIt as Av,Zht as Aw,xut as Ax,sut as Ay,CAt as Az,jo as B,r4 as B$,dmt as B0,ize as B1,H8e as B2,Tit as B3,cmt as B4,xmt as B5,vNt as B6,SB as B7,lle as B8,o3 as B9,Hct as BA,Uqe as BB,m2t as BC,zl as BD,zM as BE,Ebe as BF,mc as BG,I2t as BH,h2t as BI,gIt as BJ,zet as BK,f4 as BL,lUe as BM,Mn as BN,KCt as BO,$R as BP,$gt as BQ,Kn as BR,YTt as BS,t_e as BT,BTt as BU,Int as BV,Cst as BW,ag as BX,Tgt as BY,Ent as BZ,eA as B_,gEt as Ba,qwt as Bb,IFe as Bc,fEt as Bd,t3 as Be,cle as Bf,xle as Bg,sV as Bh,pP as Bi,Wct as Bj,dct as Bk,br as Bl,Ist as Bm,Bct as Bn,Kct as Bo,olt as Bp,rlt as Bq,jct as Br,lut as Bs,TR as Bt,xqe as Bu,iqe as Bv,Xct as Bw,Dy as Bx,zct as By,Yct as Bz,Ke as C,Aot as C$,GTt as C0,k7 as C1,F7 as C2,Zgt as C3,tA as C4,Dq as C5,aq as C6,pMe as C7,Cnt as C8,GJe as C9,uUe as CA,Kz as CB,g7 as CC,wD as CD,Pit as CE,vit as CF,Jct as CG,cct as CH,qct as CI,$ct as CJ,Wbe as CK,zx as CL,IEt as CM,mEt as CN,hEt as CO,SEt as CP,OEt as CQ,TEt as CR,REt as CS,EEt as CT,QN as CU,WNt as CV,fbe as CW,Jf as CX,f_ as CY,JNt as CZ,I2e as C_,Igt as Ca,Qgt as Cb,act as Cc,KTt as Cd,hnt as Ce,XTt as Cf,JTt as Cg,wUe as Ch,wit as Ci,qgt as Cj,dre as Ck,Hit as Cl,TSe as Cm,f7 as Cn,EUe as Co,SSe as Cp,Mst as Cq,Git as Cr,Dst as Cs,Vit as Ct,bV as Cu,bst as Cv,ZIt as Cw,Lst as Cx,$It as Cy,HN as Cz,He as D,$at as D$,fvt as D0,vlt as D1,gAt as D2,_At as D3,Nlt as D4,tct as D5,JK as D6,wlt as D7,Plt as D8,fAt as D9,Pxt as DA,bxt as DB,Vct as DC,Uct as DD,Xit as DE,mdt as DF,bvt as DG,v4 as DH,uN as DI,XSt as DJ,dit as DK,hdt as DL,jmt as DM,NTt as DN,aOt as DO,t1e as DP,MZ as DQ,Eot as DR,OZe as DS,got as DT,oNt as DU,eht as DV,w4 as DW,rNt as DX,Eht as DY,mht as DZ,Qat as D_,Gvt as Da,dut as Db,fut as Dc,put as Dd,uut as De,CTt as Df,ATt as Dg,yTt as Dh,ITt as Di,RTt as Dj,vTt as Dk,wTt as Dl,Oot as Dm,Sot as Dn,HAt as Do,QI as Dp,j2t as Dq,ZOt as Dr,cs as Ds,amt as Dt,imt as Du,pRt as Dv,ovt as Dw,Tdt as Dx,Idt as Dy,S2t as Dz,ld as E,Nct as E$,E2e as E0,Iht as E1,qat as E2,tit as E3,hht as E4,eit as E5,l$e as E6,B_t as E7,bK as E8,eP as E9,pht as EA,ght as EB,Aht as EC,Fnt as ED,w7 as EE,wOt as EF,Ngt as EG,zat as EH,ygt as EI,$xt as EJ,NOt as EK,Qxt as EL,_Et as EM,wgt as EN,Qht as EO,vgt as EP,DG as EQ,Mvt as ER,Agt as ES,ust as ET,uct as EU,Lgt as EV,Rgt as EW,i7 as EX,hit as EY,nCe as EZ,Xn as E_,Hmt as Ea,K_t as Eb,A9e as Ec,oit as Ed,nit as Ee,Sht as Ef,Eit as Eg,gb as Eh,Tht as Ei,Rht as Ej,Jat as Ek,ait as El,iit as Em,Yat as En,uht as Eo,fht as Ep,sit as Eq,qj as Er,Dvt as Es,zwt as Et,vht as Eu,Kat as Ev,Xat as Ew,yht as Ex,XIe as Ey,_ht as Ez,n$e as F,jSe as F$,Vst as F0,dJe as F1,bTe as F2,kst as F3,yot as F4,Bst as F5,GSt as F6,Xst as F7,gm as F8,Kst as F9,Jc as FA,AM as FB,XR as FC,F3 as FD,jB as FE,Bxt as FF,_qe as FG,Yxt as FH,dD as FI,est as FJ,Eqe as FK,gct as FL,lbe as FM,KD as FN,mqe as FO,Rd as FP,kH as FQ,Jg as FR,VSe as FS,Iqe as FT,hqe as FU,tst as FV,ost as FW,Tqe as FX,Uxt as FY,KSe as FZ,cst as F_,ySt as Fa,BCt as Fb,Ust as Fc,eg as Fd,oa as Fe,OSt as Ff,CSt as Fg,RSt as Fh,USt as Fi,VSt as Fj,LSt as Fk,bSt as Fl,oct as Fm,NSt as Fn,PSt as Fo,DSt as Fp,FSt as Fq,kSt as Fr,MSt as Fs,wSt as Ft,vSt as Fu,ASt as Fv,Mot as Fw,NKe as Fx,Dot as Fy,R2e as Fz,_r as G,Xdt as G$,Sqe as G0,QTt as G1,zTt as G2,Snt as G3,Gp as G4,ZTt as G5,Tnt as G6,$Tt as G7,VJe as G8,HTt as G9,Kqe as GA,Rf as GB,Yqe as GC,Ry as GD,Gst as GE,xct as GF,tlt as GG,hst as GH,lct as GI,iIt as GJ,D2 as GK,eG as GL,jqe as GM,Uit as GN,elt as GO,XP as GP,TRt as GQ,SRt as GR,$q as GS,F4 as GT,n
4262Rt as GU,mze as GV,qZe as GW,_0e as GX,p2 as GY,Eet as GZ,Zx as G_,iQe as Ga,VTt as Gb,eat as Gc,dEt as Gd,lEt as Ge,$wt as Gf,yit as Gg,ect as Gh,uSt as Gi,pSt as Gj,fSt as Gk,lx as Gl,$st as Gm,Uxe as Gn,Da as Go,Tvt as Gp,H2t as Gq,OPe as Gr,zxt as Gs,JPe as Gt,BD as Gu,Aqe as Gv,Gqe as Gw,Wqe as Gx,Bqe as Gy,E0t as Gz,L0 as H,xft as H$,Jvt as H0,Xlt as H1,Xvt as H2,Pn as H3,rre as H4,tqe as H5,Bc as H6,Qqe as H7,vqe as H8,Ns as H9,uyt as HA,dyt as HB,_yt as HC,Eyt as HD,pyt as HE,lyt as HF,myt as HG,XAt as HH,KAt as HI,v9e as HJ,hNt as HK,mNt as HL,nxt as HM,w0t as HN,rxt as HO,MG as HP,ise as HQ,tft as HR,oft as HS,bi as HT,txt as HU,_ft as HV,w_t as HW,aft as HX,ift as HY,rft as HZ,sft as H_,nqe as Ha,fte as Hb,oqe as Hc,rqe as Hd,PQe as He,WRt as Hf,YRt as Hg,$yt as Hh,FCt as Hi,VCt as Hj,UCt as Hk,kCt as Hl,Fst as Hm,_ct as Hn,Vnt as Ho,lCt as Hp,Lqe as Hq,_W as Hr,Rre as Hs,fyt as Ht,JAt as Hu,qAt as Hv,$At as Hw,ZAt as Hx,ayt as Hy,iyt as Hz,ec as I,Jlt as I$,R0t as I0,gft as I1,lft as I2,cft as I3,nft as I4,pft as I5,Ast as I6,fft as I7,vst as I8,dft as I9,Hnt as IA,Dat as IB,bat as IC,iht as ID,Smt as IE,aht as IF,Omt as IG,Lat as IH,nht as II,rht as IJ,Kit as IK,Dnt as IL,Qst as IM,Irt as IN,ISt as IO,hSt as IP,Gnt as IQ,TSt as IR,Hpe as IS,jpe as IT,ZO as IU,xC as IV,Qie as IW,dQe as IX,uQe as IY,pW as IZ,cQe as I_,uft as Ia,X$e as Ib,_2 as Ic,Uat as Id,Wat as Ie,Fat as If,Gat as Ig,Vat as Ih,Mat as Ii,Wmt as Ij,eNt as Ik,wmt as Il,Cmt as Im,kat as In,tNt as Io,ymt as Ip,Hat as Iq,Rmt as Ir,Amt as Is,vmt as It,Tmt as Iu,sht as Iv,Pat as Iw,AJe as Ix,Nat as Iy,ha as Iz,Yo as J,YIt as J$,Xp as J0,Qut as J1,Zut as J2,UL as J3,$ut as J4,o2t as J5,a2t as J6,s2t as J7,hRe as J8,i2t as J9,Btt as JA,o5 as JB,bEt as JC,dpt as JD,ipt as JE,ztt as JF,GRt as JG,FRt as JH,T4 as JI,fst as JJ,e0t as JK,t0t as JL,Ez as JM,_st as JN,PLe as JO,Znt as JP,dOt as JQ,Cit as JR,SNt as JS,jze as JT,zRt as JU,JRt as JV,KIt as JW,JN as JX,sOt as JY,_Ot as JZ,BIt as J_,lQe as Ja,wC as Jb,fI as Jc,GW as Jd,Yu as Je,Uwt as Jf,aTt as Jg,oTt as Jh,jN as Ji,nTt as Jj,Rot as Jk,iTt as Jl,hTt as Jm,rTt as Jn,Oat as Jo,Cat as Jp,pTt as Jq,fTt as Jr,Rat as Js,_Tt as Jt,gTt as Ju,_it as Jv,Drt as Jw,NEt as Jx,PEt as Jy,spt as Jz,p1 as K,kZe as K$,zIt as K0,cOt as K1,Oct as K2,lOt as K3,Cct as K4,pOt as K5,uOt as K6,gOt as K7,tL as K8,jIt as K9,fZ as KA,$2t as KB,Q2t as KC,HNt as KD,Qke as KE,ept as KF,wut as KG,Z2t as KH,pot as KI,Ewt as KJ,_wt as KK,IA as KL,L5 as KM,A2t as KN,y0t as KO,FZe as KP,g0e as KQ,y2t as KR,hze as KS,U2t as KT,R2t as KU,v2t as KV,M2t as KW,D2t as KX,O2t as KY,A0t as KZ,DZe as K_,RA as Ka,h0t as Kb,LCt as Kc,DCt as Kd,MCt as Ke,bCt as Kf,EOt as Kg,hOt as Kh,_xt as Ki,Bet as Kj,WCt as Kk,ndt as Kl,rdt as Km,T_ as Kn,ai as Ko,Y$e as Kp,B$e as Kq,Ext as Kr,odt as Ks,sdt as Kt,Qwt as Ku,xdt as Kv,adt as Kw,idt as Kx,wJe as Ky,gZ as Kz,$1 as L,ggt as L$,Iv as L0,_ut as L1,gut as L2,N2t as L3,P2t as L4,C2t as L5,F2t as L6,k2t as L7,w2t as L8,b2t as L9,d_t as LA,T_t as LB,I_t as LC,C_t as LD,__t as LE,E_t as LF,S_t as LG,g_t as LH,yst as LI,p_t as LJ,f_t as LK,J$e as LL,Z6e as LM,bqe as LN,fgt as LO,LZ as LP,_Ze as LQ,mZe as LR,Vgt as LS,Ggt as LT,EZe as LU,Xa as LV,cxe as LW,wEt as LX,yEt as LY,vEt as LZ,_gt as L_,L2t as La,f1e as Lb,p1e as Lc,GCt as Ld,d1e as Le,cwt as Lf,Hvt as Lg,cxt as Lh,VEt as Li,DEt as Lj,UEt as Lk,kEt as Ll,Htt as Lm,yI as Ln,MEt as Lo,FEt as Lp,Pwt as Lq,A_t as Lr,y_t as Ls,v_t as Lt,R_t as Lu,l_t as Lv,O_t as Lw,h_t as Lx,m_t as Ly,u_t as Lz,qq as M,gyt as M$,Egt as M0,kpt as M1,Dpt as M2,Fpt as M3,bSe as M4,smt as M5,Bze as M6,fmt as M7,gmt as M8,UAt as M9,Vpt as MA,Upt as MB,Gwt as MC,Zmt as MD,Llt as ME,Mlt as MF,Vwt as MG,Ypt as MH,Wpt as MI,Hpt as MJ,jpt as MK,zpt as ML,Hwt as MM,Wwt as MN,oU as MO,Nxe as MP,z$e as MQ,Ixt as MR,mwt as MS,r_t as MT,o_t as MU,URt as MV,JP as MW,upt as MX,K0t as MY,VNt as MZ,Wze as M_,Wz as Ma,mmt as Mb,Emt as Mc,_mt as Md,Hz as Me,Lz as Mf,COt as Mg,xOt as Mh,oL as Mi,mst as Mj,Est as Mk,iOt as Ml,hct as Mm,gst as Mn,PCt as Mo,NCt as Mp,mOt as Mq,fOt as Mr,IOt as Ms,Wet as Mt,tse as Mu,M0t as Mv,blt as Mw,VW as Mx,L$e as My,Gpt as Mz,Eg as N,NJe as N$,LNt as N0,Wtt as N1,HEt as N2,GK as N3,xEt as N4,cEt as N5,Dut as N6,vpt as N7,wpt as N8,Npt as N9,Ipt as NA,Opt as NB,Spt as NC,fpt as ND,Cpt as NE,Rpt as NF,git as NG,xyt as NH,Iit as NI,uit as NJ,fit as NK,pit as NL,X0t as NM,q0t as NN,yq as NO,GEt as NP,LEt as NQ,wwt as NR,U0t as NS,V0t as NT,zce as NU,kut as NV,Imt as NW,PTt as NX,hyt as NY,GAt as NZ,iRt as N_,WEt as Na,hut as Nb,tnt as Nc,fo as Nd,M5e as Ne,D5e as Nf,or as Ng,Zpe as Nh,Fxe as Ni,Q_ as Nj,vot as Nk,k$e as Nl,AJ as Nm,GNt as Nn,iJe as No,Put as Np,bpt as Nq,Ppt as Nr,but as Ns,Ept as Nt,mpt as Nu,hpt as Nv,gpt as Nw,uEt as Nx,_pt as Ny,Tpt as Nz,we as O,FD as O$,y0e as O0,ode as O1,lRt as O2,Lyt as O3,WZe as O4,PJe as O5,ont as O6,rnt as O7,PH as O8,yD as O9,zm as OA,BZe as OB,bJe as OC,mrt as OD,aA as OE,Wrt as OF,drt as OG,Crt as OH,jrt as OI,x_ as OJ,Dpe as OK,P2 as OL,qnt as OM,Jnt as ON,EH as OO,Tge as OP,Fdt as OQ,Ice as OR,On as OS,xRt as OT,sRt as OU,vg as OV,kg as OW,D$e as OX,net as OY,aet as OZ,fot as O_,prt as Oa,ide as Ob,Xq as Oc,Jq as Od,Cxt as Oe,a_t as Of,n_t as Og,byt as Oh,ppt as Oi,Bf as Oj,ol as Ok,Lut as Ol,Mut as Om,q_t as On,$_t as Oo,Q_t as Op,Z_t as Oq,t
4262Et as Or,eEt as Os,rEt as Ot,oEt as Ou,nEt as Ov,aEt as Ow,Q$e as Ox,kit as Oy,JCt as Oz,ii as P,jh as P$,aut as P0,wNt as P1,WF as P2,le as P3,Oae as P4,dte as P5,ute as P6,lte as P7,aqe as P8,cvt as P9,ZEt as PA,qEt as PB,KEt as PC,XEt as PD,JEt as PE,$Et as PF,mEe as PG,Mgt as PH,kgt as PI,Dgt as PJ,dZe as PK,uZe as PL,gZe as PM,Wgt as PN,Fgt as PO,Ugt as PP,Qrt as PQ,VQe as PR,$Je as PS,het as PT,Ube as PU,zSt as PV,YSt as PW,HSt as PX,jy as PY,Zct as PZ,Qct as P_,UW as Pa,Jit as Pb,nQe as Pc,fc as Pd,aQe as Pe,rQe as Pf,$J as Pg,NQe as Ph,rSt as Pi,nSt as Pj,uot as Pk,rOt as Pl,O_e as Pm,nOt as Pn,Cgt as Po,Sgt as Pp,xse as Pq,Ogt as Pr,mBe as Ps,$Qe as Pt,jEt as Pu,zEt as Pv,koe as Pw,YEt as Px,BEt as Py,QEt as Pz,zn as Q,Aut as Q$,WN as Q0,OTt as Q1,TTt as Q2,STt as Q3,r_ as Q4,xlt as Q5,Qee as Q6,TMe as Q7,Q7 as Q8,Ryt as Q9,clt as QA,llt as QB,Zlt as QC,Edt as QD,_dt as QE,Lot as QF,alt as QG,KA as QH,zG as QI,j0e as QJ,jlt as QK,Hlt as QL,Wlt as QM,Glt as QN,Vlt as QO,Ult as QP,Flt as QQ,klt as QR,Dlt as QS,Rlt as QT,i_t as QU,r2t as QV,Rdt as QW,Sdt as QX,Cdt as QY,Odt as QZ,slt as Q_,Ai as Qa,Yh as Qb,C0t as Qc,PW as Qd,pI as Qe,Bh as Qf,udt as Qg,$T as Qh,OR as Qi,hlt as Qj,fm as Qk,kp as Ql,DNt as Qm,kNt as Qn,rut as Qo,Kp as Qp,s_t as Qq,ilt as Qr,mlt as Qs,Elt as Qt,_lt as Qu,glt as Qv,flt as Qw,plt as Qx,ult as Qy,dlt as Qz,L as R,cnt as R$,tTt as R0,Cqe as R1,Oqe as R2,c_t as R3,Rut as R4,c2t as R5,Clt as R6,Olt as R7,Slt as R8,Tlt as R9,rpt as RA,opt as RB,eft as RC,tpt as RD,Qpt as RE,Zoe as RF,rmt as RG,Got as RH,nmt as RI,ast as RJ,Pgt as RK,Nut as RL,yut as RM,vut as RN,e_t as RO,pdt as RP,$lt as RQ,x_t as RR,omt as RS,fdt as RT,gdt as RU,mgt as RV,hgt as RW,zlt as RX,Ylt as RY,Blt as RZ,_at as R_,Ilt as Ra,Alt as Rb,oW as Rc,xZe as Rd,$rt as Re,YOt as Rf,ylt as Rg,OA as Rh,pnt as Ri,c_ as Rj,rct as Rk,SSt as Rl,hbe as Rm,T2t as Rn,gSt as Ro,Klt as R
4262p,qlt as Rq,Qlt as Rr,Cyt as Rs,cdt as Rt,ldt as Ru,ddt as Rv,wA as Rw,Sut as Rx,Tut as Ry,N_t as Rz,rL as S,eCt as S$,$2e as S0,cZe as S1,vyt as S2,zBe as S3,wyt as S4,PRt as S5,GF as S6,WBe as S7,HCt as S8,zAt as S9,xxe as SA,F5 as SB,Let as SC,bet as SD,yet as SE,Aet as SF,Pet as SG,Net as SH,wet as SI,vet as SJ,Ret as SK,Cet as SL,Oet as SM,fet as SN,Tet as SO,w0e as SP,kxe as SQ,fxe as SR,__e as SS,q$e as ST,UTt as SU,Tte as SV,Ste as SW,Ote as SX,oq as SY,$Ot as SZ,jit as S_,ivt as Sa,Svt as Sb,Cvt as Sc,Ovt as Sd,Evt as Se,BRt as Sf,VAt as Sg,DAt as Sh,SAt as Si,m8e as Sj,AAt as Sk,MAt as Sl,K6e as Sm,owt as Sn,Zvt as So,IK as Sp,F6e as Sq,$vt as Sr,lNt as Ss,lwt as St,qvt as Su,Nit as Sv,j$e as Sw,Dg as Sx,TH as Sy,Uet as Sz,xt as T,wF as T$,aoe as T0,zh as T1,coe as T2,Myt as T3,wye as T4,Pyt as T5,WB as T6,GB as T7,Fyt as T8,JBe as T9,cI as TA,Pm as TB,E8e as TC,VG as TD,Mw as TE,Vv as TF,R8e as TG,Vxe as TH,QC as TI,ewt as TJ,L_e as TK,Rit as TL,N0t as TM,Av as TN,Xg as TO,kw as TP,K2e as TQ,K$e as TR,ixe as TS,SYe as TT,kvt as TU,eT as TV,hH as TW,jg as TX,fT as TY,hK as TZ,Og as T_,Dyt as Ta,kyt as Tb,Sxt as Tc,Out as Td,Iut as Te,$mt as Tf,npt as Tg,edt as Th,qrt as Ti,met as Tj,Uvt as Tk,Vvt as Tl,P_t as Tm,YL as Tn,Cut as To,X_t as Tp,qPe as Tq,Gxt as Tr,Wxt as Ts,Sit as Tt,RJe as Tu,Ect as Tv,Ict as Tw,Ktt as Tx,Xce as Ty,Jqe as Tz,P8 as U,b_t as U$,a0t as U0,Hy as U1,wRt as U2,eS as U3,fNt as U4,LRt as U5,Hqe as U6,DRt as U7,zqe as U8,Vqe as U9,N$e as UA,VI as UB,pde as UC,Qvt as UD,Jpt as UE,V1 as UF,Xpt as UG,yF as UH,Tu as UI,vZ as UJ,yZ as UK,U1 as UL,Qmt as UM,nNt as UN,D0t as UO,Kpt as UP,P$e as UQ,aAt as UR,lfe as US,xfe as UT,Ek as UU,Get as UV,qse as UW,Td as UX,z_t as UY,k_t as UZ,D_t as U_,Ute as Ua,l0t as Ub,ARt as Uc,yRt as Ud,CRt as Ue,vRt as Uf,MRt as Ug,d0t as Uh,eZe as Ui,$G as Uj,SRe as Uk,H5e as Ul,S4 as Um,hA as Un,bL as Uo,gT as Up,KT as Uq,z5 as Ur,j5 as Us,Yx as Ut,j2 as Uu,ZP as Uv,L8e as Uw,b8e as Ux,W0e as Uy,TK as Uz,Ga as V,xxt as V$,L_t as V0,Det as V1,Y_t as V2,F_t as V3,H_t as V4,j_t as V5,V_t as V6,U_t as V7,G_t as V8,W_t as V9,Fet as VA,P0e as VB,x0e as VC,Cv as VD,MW as VE,YAt as VF,ZRt as VG,QRt as VH,Xse as VI,OW as VJ,Oxe as VK,S$e as VL,$Ze as VM,tZe as VN,g$e as VO,Zse as VP,FNt as VQ,KQe as VR,krt as VS,$ot as VT,VZe as VU,CW as VV,jvt as VW,LZe as VX,f0e as VY,bZe as VZ,oRt as V_,Jrt as Va,_St as Vb,Oyt as Vc,mSt as Vd,I$e as Ve,Z$e as Vf,Hxt as Vg,_et as Vh,xCt as Vi,V2t as Vj,Zxt as Vk,Eut as Vl,jNt as Vm,rRt as Vn,oAt as Vo,UDe as Vp,tAt as Vq,Fvt as Vr,eAt as Vs,Vdt as Vt,G0e as Vu,qQe as Vv,X1 as Vw,Qse as Vx,Jse as Vy,B6e as Vz,Yse as W,zvt as W$,HZe as W0,E$e as W1,zye as W2,BQe as W3,eZ as W4,Pq as W5,ZQe as W6,oZe as W7,e$e as W8,rZe as W9,Y2t as WA,B2t as WB,z2t as WC,fxt as WD,gxt as WE,W2t as WF,kQe as WG,FQe as WH,Wse as WI,JG as WJ,jQe as WK,zQe as WL,Txt as WM,vye as WN,Gse as WO,YQe as WP,Hse as WQ,WAt as WR,pxt as WS,V$e as WT,lxt as WU,Jdt as WV,Att as WW,_ce as WX,eut as WY,tut as WZ,Lxt as W_,t$e as Wa,iZe as Wb,eW as Wc,_$e as Wd,Vtt as We,BAt as Wf,rwt as Wg,QQe as Wh,nZe as Wi,aZe as Wj,KZe as Wk,h$e as Wl,y$e as Wm,tdt as Wn,bMe as Wo,Ize as Wp,Kze as Wq,GQe as Wr,B0 as Ws,UQe as Wt,nut as Wu,bot as Wv,Eu as Ww,ak as Wx,RAt as Wy,G2t as Wz,Oa as X,wxe as X$,U8 as X0,Kvt as X1,Yvt as X2,Qdt as X3,gze as X4,Bvt as X5,Zdt as X6,vH as X7,qdt as X8,NH as X9,g_ as XA,frt as XB,Kgt as XC,Xgt as XD,Pv as XE,Tyt as XF,Syt as XG,ESt as XH,bit as XI,Lit as XJ,Zrt as XK,ret as XL,DQe as XM,sze as XN,mxt as XO,q2t as XP,Wvt as XQ,Oxt as XR,iAt as XS,UZe as XT,zZe as XU,sZe as XV,Jgt as XW,Grt as XX,U$e as XY,M$e as XZ,F$e as X_,o$e as Xa,Met as Xb,e2t as Xc,Mpt as Xd,tht as Xe,t_t as Xf,Lpt as Xg,t2t as Xh,l9e as Xi,oht as Xj,wr as Xk,zrt as Xl,GCe as Xm,Nfe as Xn,get as Xo,Pfe as Xp,XZe as Xq,gQe as Xr,_Qe as Xs,Ygt as Xt,jgt as Xu,zgt as Xv,J_t as Xw,Hgt as Xx,rT as Xy,tmt as Xz,J2t as Y,A4 as Y$,A$e as Y0,fW as Y1,QZe as Y2,jZe as Y3,uH as Y4,$dt as Y5,v$e as Y6,dxt as Y7,uxt as Y8,nvt as Y9,wOe as YA,eot as YB,Ix as YC,Fit as YD,poe as YE,yTe as YF,Fct as YG,Vy as YH,lqe as YI,bbe as YJ,Xf as YK,ict as YL,QJe as YM,JOt as YN,ZJe as YO,Fy as YP,j0t as YQ,uP as YR,XCe as YS,Oke as YT,tH as YU,nlt as YV,iut as YW,CD as YX,Udt as YY,H
4262Fe as YZ,h9e as Y_,HDe as Ya,gDe as Yb,WQe as Yc,btt as Yd,Sce as Ye,vrt as Yf,Xut as Yg,Eft as Yh,Jut as Yi,mft as Yj,fQe as Yk,Ltt as Yl,K2t as Ym,grt as Yn,kCe as Yo,HQe as Yp,jAt as Yq,nwt as Yr,awt as Ys,vxt as Yt,yxt as Yu,Axt as Yv,W_e as Yw,wRe as Yx,XCt as Yy,I0t as Yz,tvt as Z,mit as Z0,d_e as Z1,U9e as Z2,Bit as Z3,ls as Z4,Yit as Z5,G0 as Z6,GZe as Z7,Ymt as Z8,KSt as Z9,G7e as ZA,h_ as ZB,lS as ZC,l8 as ZD,kYe as ZE,m8 as ZF,LYe as ZG,$tt as ZH,Iot as ZI,bYe as ZJ,uAt as ZK,Het as ZL,$qe as ZM,UYe as ZN,YCt as ZO,pAt as ZP,mYe as ZQ,FYe as ZR,Zqe as ZS,FCe as ZT,sqe as ZU,Qje as ZV,Ont as Za,Gct as Zb,zB as Zc,MKe as Zd,bRt as Ze,Uze as Zf,aB as Zg,wK as Zh,RRt as Zi,IBe as Zj,Uyt as Zk,Lnt as Zl,bnt as Zm,Pnt as Zn,Nnt as Zo,SK as Zp,hF as Zq,cRt as Zr,dRt as Zs,uRt as Zt,VYe as Zu,cAt as Zv,lAt as Zw,lB as Zx,D8 as Zy,vYe as Zz,r$e as _,gje as a,I0 as a$,lXe as a0,L0e as a1,N0e as a2,ja as a3,Mt as a4,ke as a5,Nte as a6,qP as a7,jRt as a8,po as a9,fRt as aA,oYe as aB,Vze as aC,Dze as aD,jye as aE,wTe as aF,D0e as aG,Gze as aH,BPe as aI,jPe as aJ,Yze as aK,eYe as aL,Qze as aM,Xze as aN,bze as aO,ine as aP,g_e as aQ,jG as aR,ka as aS,g0 as aT,Je as aU,mn as aV,U0 as aW,Rt as aX,pT as aY,zK as aZ,Un as a_,Ta as aa,wn as ab,K as ac,Xt as ad,bo as ae,Us as af,WSt as ag,cz as ah,jSt as ai,Ayt as aj,sct as ak,jBe as al,Fbe as am,nAt as an,IRt as ao,hRt as ap,Rxt as aq,cit as ar,a$e as as,ORt as at,jxt as au,Vxt as av,HRt as aw,rAt as ax,$Rt as ay,qRt as az,kQ as b,Od as b$,pe as b0,fl as b1,Bg as b2,Sd as b3,cd as b4,Id as b5,eo as b6,ZR as b7,$7 as b8,Hn as b9,h2 as bA,xI as bB,za as bC,ss as bD,ho as bE,qc as bF,xr as bG,lv as bH,pQe as bI,ed as bJ,p0e as bK,Y as bL,CNt as bM,ONt as bN,J0 as bO,cr as bP,Tg as bQ,_Nt as bR,C9e as bS,Gn as bT,ll as bU,R9e as bV,f0 as bW,_b as bX,PNt as bY,rU as bZ,Ca as b_,Ar as ba,wt as bb,I0e as bc,N2 as bd,ar as be,Se as bf,Wa as bg,wf as bh,HR as bi,CI as bj,ci as bk,Co as bl,dat as bm,lat as bn,TZe as bo,YNt as bp,BNt as bq,pct as br,Rn as bs,sT as bt,Q0 as bu,yh as bv,aT as bw,sr as bx,ac as by,m2 as bz,HQ as c,Xv as c$,Nz as c0,pst as c1,$c as c2,qNt as c3,Ttt as c4,I as c5,mo as c6,Yet as c7,ct as c8,cqe as c9,XL as cA,Yv as cB,Dx as cC,Rh as cD,xs as cE,Ah as cF,sn as cG,ns as cH,Fpe as cI,Nm as cJ,Tv as cK,d0 as cL,mtt as cM,nT as cN,iH as cO,Xrt as cP,AI as cQ,Bx as cR,Su as cS,Qxe as cT,Ett as cU,ett as cV,_tt as cW,jxe as cX,Upe as cY,zxe as cZ,qL as c_,AH as ca,LG as cb,YZe as cc,WR as cd,MZe as ce,Df as cf,b8 as cg,$pe as ch,sI as ci,Qx as cj,s3 as ck,vo as cl,gd as cm,En as cn,sN as co,pg as cp,an as cq,Im as cr,Hrt as cs,eM as ct,Pr as cu,G0t as cv,FW as cw,ri as cx,Er as cy,ttt as cz,tje as d,EAt as d$,att as d0,Rtt as d1,jw as d2,ktt as d3,$et as d4,JL as d5,Kv as d6,Ctt as d7,Zet as d8,pH as d9,m0e as dA,lW as dB,ku as dC,Kg as dD,fH as dE,jet as dF,itt as dG,Bse as dH,dtt as dI,Jet as dJ,qxe as dK,Stt as dL,Itt as dM,Ott as dN,Ag as dO,vtt as dP,htt as dQ,utt as dR,ftt as dS,Jv as dT,ptt as dU,OI as dV,Ptt as dW,wv as dX,Iet as dY,is as dZ,k0t as d_,_H as da,gH as db,ytt as dc,Kse as dd,Ket as de,wm as df,gtt as dg,Zc as dh,Xet as di,ctt as dj,ltt as dk,yW as dl,g2 as dm,wtt as dn,xtt as dp,Qet as dq,ntt as dr,Ntt as ds,stt as dt,ott as du,tl as dv,rtt as dw,C2 as dx,_rt as dy,Ert as dz,$r as e,cat as e$,Ype as e0,mAt as e1,ND as e2,Rr as e3,_l as e4,pxe as e5,_xe as e6,xet as e7,oi as e8,$W as e9,Fw as eA,q3 as eB,Y_e as eC,Ir as eD,wI as eE,PI as eF,Wn as eG,Xtt as eH,i2 as eI,iat as eJ,qqe as eK,nat as eL,pat as eM,Gf as eN,KM as eO,gat as eP,D4 as eQ,j0 as eR,K_e as eS,Uw as eT,hrt as eU,Mtt as eV,xrt as eW,RNt as eX,bpe as eY,irt as eZ,yNt as e_,m$e as ea,vv as eb,y_ as ec,hot as ed,Prt as ee,brt as ef,Lrt as eg,Mrt as eh,wc as ei,mae as ej,rc as ek,nt as el,xx as em,uet as en,det as eo,cet as ep,Gm as eq,II as er,QK as es,ml as et,Hm as eu,Dw as ev,Qpe as ew,Dtt as ex,Zxe as ey,eae as ez,Eat as f,oQe as f$,rat as f0,ANt as f1,RI as f2,Nc as f3,uat as f4,wrt as f5,Wm as f6,QR as f7,w$e as f8,Utt as f9,rrt as fA,ort as fB,Srt as fC,qR as fD,yrt as fE,xat as fF,sat as fG,bNt as fH,Trt as fI,Re as fJ,IZe as fK,ym as fL,tat as fM,M3 as fN,ur as fO,cW as fP,Nrt as fQ,Tw as fR,Brt as fS,Yrt as fT,Cot as fU,iI as fV,v0t as fW,Koe as fX,Fqe as fY,wnt as fZ,tQe as f_,fat as fa,Rrt as fb,Art as fc,KNt as fd,XNt as fe,wy as ff,qet as fg,Bv as fh,b$e as fi,Ftt as fj,cH as fk,Mce as fl,Gtt as fm,nrt as fn,bf as fo,uxe as fp,hZe as fq,k4 as fr,dfe as fs,Krt as ft,bH as fu,ent as fv,Yy as fw,art as fx,Ort as fy,srt as fz,fje as g,Pqe as g$,xAt as g0,gP as g1,l0 as g2,z4 as g3,jat as g4,Dct as g5,by as g6,kct as g7,Y4 as g8,gJe as g9,q8 as gA,xv as gB,Lie as gC,Qv as gD,hx as gE,yxe as gF,eU as gG,eQe as gH,fv as gI,MT as gJ,hwt as gK,yu as gL,W0t as gM,SG as gN,ZYe as gO,jP as gP,oG as gQ,vK as gR,ake as gS,ht as gT,Mxe as gU,UNt as gV,vwt as gW,TV as gX,kre as gY,Mqe as gZ,SV as g_,ou as ga,jbe as gb,Nqe as gc,Z0t as gd,Sl as ge,kIt as gf,FIt as gg,st as gh,Vn as gi,NRt as g
4262j,Nst as gk,eqe as gl,Mi as gm,Cf as gn,mRt as go,kqe as gp,mle as gq,uIt as gr,zut as gs,B9e as gt,E2 as gu,gwt as gv,pwt as gw,dwt as gx,uwt as gy,Fut as gz,Pg as h,Hze as h$,Fre as h0,hV as h1,IV as h2,Dre as h3,Bre as h4,EL as h5,p$e as h6,Wut as h7,NNt as h8,E0 as h9,Wg as hA,oT as hB,Y0e as hC,Nn as hD,wW as hE,RK as hF,Q8 as hG,Ue as hH,U2 as hI,Ot as hJ,Ant as hK,Pt as hL,y4 as hM,Ih as hN,I9e as hO,T9e as hP,S9e as hQ,A0 as hR,Vf as hS,VK as hT,I4 as hU,l2 as hV,c2 as hW,Ds as hX,vnt as hY,fd as hZ,o7 as h_,DW as ha,iwt as hb,Hut as hc,Gg as hd,Xy as he,sNt as hf,lSt as hg,dSt as hh,MNt as hi,Lwt as hj,jut as hk,ZC as hl,Apt as hm,iEt as hn,ypt as ho,sEt as hp,Vi as hq,cCt as hr,ore as hs,wo as ht,bn as hu,me as hv,syt as hw,xL as hx,Ivt as hy,qut as hz,Oy as i,gRt as i$,M_t as i0,qxt as i1,lP as i2,Act as i3,Za as i4,HIt as i5,Dwt as i6,XIt as i7,nP as i8,Bu as i9,wxt as iA,Mv as iB,O$e as iC,C$e as iD,K9e as iE,Te as iF,Li as iG,Or as iH,Fg as iI,G1 as iJ,wat as iK,s_ as iL,Kce as iM,d$e as iN,Q5 as iO,JQe as iP,cIt as iQ,P0t as iR,A_ as iS,lIt as iT,xIt as iU,sIt as iV,dIt as iW,oxt as iX,nze as iY,Mze as iZ,Lze as i_,U5 as ia,CB as ib,VRt as ic,FAt as id,OB as ie,umt as ig,kAt as ih,pmt as ii,XRt as ij,KRt as ik,JIt as il,Yut as im,iNt as io,cSt as ip,sSt as iq,xSt as ir,Gut as is,X9e as it,Uut as iu,Vut as iv,CK as iw,int as ix,TBe as iy,s2 as iz,mat as j,Vse as j$,rze as j0,eRt as j1,zP as j2,xn as j3,_Rt as j4,ERt as j5,H$e as j6,G5 as j7,Yye as j8,lit as j9,Bce as jA,iot as jB,NI as jC,aot as jD,Qtt as jE,Kwt as jF,fle as jG,Bwt as jH,Jwt as jI,rI as jJ,Pl as jK,pv as jL,Jp as jM,Iu as jN,Bpt as jO,a3 as jP,xot as jQ,LQe as jR,rot as jS,bQe as jT,MQe as jU,oot as jV,XG as jW,mh as jX,pr as jY,Ua as jZ,Cd as j_,Q0t as ja,Pst as jb,pt as jc,pFe as jd,CJe as je,JJ as jf,OJe as jg,CHe as jh,Mu as ji,$s as jj,gy as jk,WJ as jl,m1 as jm,hJe as jn,nn as jo,qr as jp,qee as jq,T$e as jr,bg as js,Uv as jt,oet as ju,Lg as jv,not as jw,bp as jx,mB as jy,Xwt as jz,zNt as k,Pft as k$,Gi as k0,uo as k1,ao as k2,Ztt as k3,ax as k4,tot as k5,Yc as k6,Jye as k7,go as k8,foe as k9,Dft as kA,Mft as kB,Ri as kC,wg as kD,KTe as kE,Mwt as kF,x2t as kG,TI as kH,au as kI,Ro as kJ,Bye as kK,yse as kL,Ase as kM,vse as kN,Nxt as kO,vQe as kP,wQe as kQ,Nse as kR,bse as kS,Pse as kT,wse as kU,bft as kV,Lft as kW,ose as kX,NZe as kY,mse as kZ,Kye as k_,dRe as ka,Do as kb,Gv as kc,Vet as kd,X2t as ke,jM as kf,vZe as kg,CZe as kh,c$e as ki,x$e as kj,H0e as kk,RZe as kl,EO as km,SZe as kn,pZe as ko,rW as kp,lZe as kq,wR as kr,lV as ks,fZe as kt,ir as ku,zc as kv,tet as kw,tc as kx,yZe as ky,AZe as kz,u$e as l,Not as l$,vft as l0,Nft as l1,yft as l2,Aft as l3,Rft as l4,L0t as l5,Oft as l6,Cft as l7,Vft as l8,Uft as l9,zft as lA,Hft as lB,Wft as lC,Gft as lD,C1 as lE,sot as lF,wZe as lG,oI as lH,Dxe as lI,_ot as lJ,se as lK,N4 as lL,QCt as lM,I2 as lN,cJe as lO,xJe as lP,$e as lQ,Rv as lR,s$e as lS,axe as lT,zE as lU,Oit as lV,Pot as lW,oo as lX,iet as lY,Qc as lZ,Gxe as l_,Fft as la,kft as lb,pgt as lc,ugt as ld,dgt as le,lgt as lf,cgt as lg,xgt as lh,sgt as li,agt as lj,igt as lk,ngt as ll,rgt as lm,ogt as ln,tgt as lo,egt as lp,$ft as lq,Qft as lr,Zft as ls,qft as lt,Jft as lu,Kft as lv,Xft as lw,Bft as lx,Yft as ly,jft as lz,qze as m,oze as m$,Eoe as m0,pl as m1,UT as m2,GR as m3,Mg as m4,W$e as m5,xa as m6,urt as m7,Sv as m8,GIt as m9,Vrt as mA,z0 as mB,PYe as mC,sJe as mD,be as mE,zo as mF,Ia as mG,qst as mH,WTe as mI,Jst as mJ,G2 as mK,yAt as mL,Fwt as mM,kwt as mN,Owt as mO,sBe as mP,Jl as mQ,rBe as mR,wB as mS,LAt as mT,p9e as mU,lJe as mV,RJ as mW,i$e as mX,ZCt as mY,bwt as mZ,Nwt as m_,ba as ma,gNt as mb,z0t as mc,WIt as md,H9e as me,Dqe as mf,t7 as mg,ket as mh,ex as mi,Ao as mj,u0e as mk,AZ as ml,zCt as mm,_je as mn,fR as mo,R$e as mp,$Ct as mq,tRt as mr,k0e as ms,bu as mt,aat as mu,hl as mv,tde as mw,Urt as mx,Xc as my,Frt as mz,NQ as n,bN as n$,bAt as n0,Ywt as n1,x9e as n2,G8 as n3,Awt as n4,ywt as n5,PAt as n6,Rwt as n7,O2 as n8,eet as n9,LOt as nA,bOt as nB,MOt as nC,POt as nD,wqe as nE,XJe as nF,WOt as nG,JJe as nH,GOt as nI,c0t as nJ,VOt as nK,mZ as nL,Wf as nM,ZB as nN,Aat as nO,sYe as nP,yat as nQ,sx as nR,Ya as nS,rst as nT,O7 as nU,Zit as nV,ape as nW,jot as nX,cb as nY,aRt as nZ,_Xe as n_,M8e as na,Nce as nb,ds as nc,RL as 
4262nd,Fze as ne,FTt as nf,V8 as ng,JZe as nh,Lbe as ni,Kee as nj,Bee as nk,qJe as nl,FOt as nm,LV as nn,mt as no,UOt as np,zq as nq,TPe as nr,vp as ns,jJe as nt,YJe as nu,KJe as nv,m9e as nw,HJe as nx,ix as ny,zJe as nz,lt as o,qit as o$,Vot as o0,Zpt as o1,oXe as o2,xvt as o3,$pt as o4,yp as o5,S6e as o6,z3 as o7,aNt as o8,lvt as o9,kJe as oA,Kot as oB,aL as oC,mvt as oD,Avt as oE,hvt as oF,H0t as oG,p0 as oH,LKe as oI,x7 as oJ,Dit as oK,Y0t as oL,OSe as oM,Xqe as oN,To as oO,F0t as oP,Xot as oQ,Bot as oR,Jot as oS,PO as oT,Gy as oU,Hot as oV,yQe as oW,UJe as oX,$I as oY,eTt as oZ,bw as o_,rvt as oa,nK as ob,svt as oc,vat as od,$it as oe,tV as of,ME as og,Y3 as oh,j2e as oi,Xxt as oj,EZ as ok,_Z as ol,AQe as om,Vs as on,fse as oo,kE as op,Jxt as oq,MJe as or,LJe as os,vw as ot,DJe as ou,Wot as ov,rpe as ow,ope as ox,tpe as oy,FJe as oz,yJ as p,jOt as p$,lst as p0,Qit as p1,nst as p2,dst as p3,us as p4,Hg as p5,ist as p6,sst as p7,xst as p8,obe as p9,ENt as pA,rh as pB,i_ as pC,RRe as pD,Iwt as pE,i0t as pF,s0t as pG,DOt as pH,BJe as pI,M2 as pJ,Ait as pK,kOt as pL,WJe as pM,La as pN,pvt as pO,ext as pP,yct as pQ,uNt as pR,nMe as pS,hg as pT,HOt as pU,Jo as pV,x0t as pW,Zwt as pX,AF as pY,qOt as pZ,zOt as p_,dUe as pa,AT as pb,Kxt as pc,npe as pd,Yl as pe,Jyt as pf,zyt as pg,Xyt as ph,qyt as pi,wst as pj,Byt as pk,Uot as pl,Kyt as pm,Yyt as pn,N1 as po,ert as pp,Wv as pq,qot as pr,KV as ps,Sct as pt,_0t as pu,yT as pv,v7 as pw,W1 as px,oat as py,hxt as pz,_0 as q,Jh as q$,yG as q0,Ss as q1,oEe as q2,ip as q3,gvt as q4,QOt as q5,Rvt as q6,xNt as q7,pbe as q8,Gie as q9,V2 as qA,TOt as qB,SOt as qC,vct as qD,mct as qE,OOt as qF,Pct as qG,lh as qH,$Ne as qI,Tct as qJ,uMe as qK,fP as qL,LIt as qM,wct as qN,P4 as qO,qt as qP,aMe as qQ,UIt as qR,Mnt as qS,Oz as qT,Rct as qU,$Le as qV,sMe as qW,VIt as qX,ni as qY,Ur as qZ,yJe as q_,qSt as qa,tre as qb,JSt as qc,b0t as qd,ixt as qe,CT as qf,kxt as qg,Il as qh,yRe as qi,Dxt as qj,nct as qk,Fxt as ql,fs as qm,Va as qn,a1e as qo,XOt as qp,kbe as qq,BOt as qr,Cl as qs,Rie as qt,KOt as qu,Xx as qv,RQ as qw,BSt as qx,bct as qy,wLe as qz,R1 as r,Ll as r$,ud as r0,XLe as r1,L2 as r2,pz as r3,qo as r4,sc as r5,T0t as r6,S0t as r7,lrt as r8,dW as r9,k2 as rA,Mit as rB,ca as rC,Sm as rD,Cr as rE,Xi as rF,Knt as rG,Bnt as rH,kG as rI,Mdt as rJ,Ddt as rK,kdt as rL,bdt as rM,cse as rN,Tm as rO,kr as rP,jwt as rQ,Ost as rR,nc as rS,_3 as rT,z8 as rU,HB as rV,mut as rW,sp as rX,aV as rY,Ldt as rZ,Nr as r_,vpe as ra,Ys as rb,qf as rc,fct as rd,CEt as re,zu as rf,l_ as rg,Zst as rh,zne as ri,$V as rj,Ig as rk,Wnt as rl,knt as rm,Qy as rn,m0 as ro,cNt as rp,Zy as rq,yqe as rr,out as rs,Z_e as rt,uI as ru,Fi as rv,zot as rw,Yot as rx,yv as ry,M0e as rz,Ov as s,E9e as s$,o_ as s0,mot as s1,TQe as s2,Xo as s3,ant as s4,nnt as s5,Ndt as s6,$p as s7,J7 as s8,cut as s9,Ts as sA,mg as sB,wdt as sC,Sst as sD,Tst as sE,pi as sF,si as sG,IQe as sH,hQe as sI,a_ as sJ,J0t as sK,$Ce as sL,lse as sM,mQe as sN,EQe as sO,Poe as sP,QNt as sQ,ZNt as sR,Rqe as sS,gre as sT,uqe as sU,NL as sV,Em as sW,sTt as sX,uS as sY,Kc as sZ,vdt as s_,SQe as sa,_P as sb,Pdt as sc,wvt as sd,eOt as se,xTt as sf,PD as sg,vvt as sh,mP as si,Pvt as sj,Nvt as sk,Ii as sl,vc as sm,Sw as sn,b2 as so,vd as sp,T0 as sq,OT as sr,ST as ss,_N as st,Zg as su,H6e as sv,ig as sw,Mxt as sx,TAt as sy,ql as sz,Di as t,rEe as t$,n2e as t0,Jmt as t1,qmt as t2,Xmt as t3,V0e as t4,zdt as t5,Ydt as t6,ite as t7,jdt as t8,trt as t9,_Ct as tA,Hst as tB,gCt as tC,fCt as tD,Wst as tE,pCt as tF,zst as tG,ECt as tH,uCt as tI,mCt as tJ,$u as tK,twt as tL,Me as tM,B0t as tN,Sf as tO,Lv as tP,Oye as tQ,$0t as tR,MIt as tS,to as tT,YPe as tU,Lte as tV,XB as tW,apt as tX,Sye as tY,eMe as tZ,QLe as t_,Hdt as ta,OAt as tb,IAt as tc,Wdt as td,Jue as te,Lct as tf,Mct as tg,pqe as th,fqe as ti,gqe as tj,rCt as tk,vx as tl,Wit as tm,u0t as tn,tCt as to,nCt as tp,zit as tq,oCt as tr,uRe as ts,az as tt,bgt as tu,pNt as tv,uvt as tw,mIt as tx,vJe as ty,jst as tz,YQ as u,vOt as u$,tMe as u0,ZLe as u1,_vt as u2,ORe as u3,yi as u4,mRe as u5,OLe as u6,f0t as u7,wCt as u8,yr as u9,wIt as uA,EIt as uB,AIt as uC,TCt as uD,_It as uE,RIt as uF,r0t as uG,yIt as uH,IQ as uI,OCt as uJ,CCt as uK,RCt as uL,ACt as uM,SCt as uN,axt as uO,IIt as uP,hIt as uQ,yCt as uR,vCt as uS,TIt as uT,m0t as uU,hCt as uV,ICt as uW,CIt as uX,vIt as uY,tOt as uZ,ZSt as u_,YXe as ua,ww as ub,qB as uc,gj as ud,Vyt as ue,Bne as uf,n0t as ug,NIt as uh,p0t as ui,o0t as uj,bIt as uk,PIt as ul,zN as um,g0t as un,Yst as uo,ROt as up,AOt as uq,yOt as ur,dCt as us,DIt as ut,pQ as uu,Mo as uv,OIt as uw,SIt as ux,$St as uy,QIt as uz,rt as v,Wy as v$,Hae as v0,rv as v1,Lt as v2,ks as v3,WD as v4,x_e as v5,qTt as v6,mnt as v7,jTt as v8,WTt as v9,Zot as vA,Kx as vB,tT as vC,Af as vD,Qot as vE,U0e as vF,F0e as vG,zCe as vH,bOe as vI,POe as vJ,QY as vK,ZY as vL,my as vM,$0 as vN,GTe as vO,cyt as vP,nyt as vQ,QAt as vR,ryt as vS,eyt as vT,oyt as vU,tyt as vV,K1 as vW,f5e as vX,But as vY,Kut as vZ,n2t as v_,_nt as va,Lvt as vb,Rnt as vc,aCt as vd,sCt as ve,sxt as vf,iCt as vg,cq as vh,Qyt as vi,evt as vj,i0 as vk,Fot as vl,QT as vm,Zyt as vn,kx as vo,Hp as vp,avt as vq,zs as vr,kv as vs,mI as vt,Fv as vu,r6e as vv,QSt as vw,C_ as vx,mee as vy,Tee as vz,sO as w,kfe as w$,Qs as w0,kTt as w1,Fmt as w2,Umt as w3,kmt as w4,Dmt as w5,Gmt as w6,Vmt as w7,MTt as w8,LTt as w9,o4e as wA,qS as wB,Mfe as wC,iSt as wD,lRe as wE,xQe as wF,Lc as wG,lnt as wH,ZN as wI,bfe as wJ,Rc as wK,_1 as wL,EJe as wM,mJe as wN,fJe as wO,SJe as wP,TJe as wQ,F0 as wR,Lfe as wS,Kt as wT,EA as wU,ige as wV,eSt as wW,aSt as wX,oSt as wY,_Je as wZ,Nbe as w_,DTt as wa,LN as wb,lht as wc,dht as wd,bmt as we,Nmt as wf,Pmt as wg,Lmt as wh,qIt as wi,Mmt as wj,xht as wk,bTt as wl,cht as wm,Vo as wn,Ae as wo,WL as wp,yn as wq,HJ as wr,vie as ws,Qa as wt,aF as wu,_y as wv,af as ww,t4e as wx,e4e as wy,jCt as wz,lo as x,b_e as x$,TRe as x0,Zr as x1,DR as x2,oOt as x3,Sa as x4,Ad as x5,e0 as x6,SBe as x7,age as x8,W2 as x9,Ynt as xA,PBe as xB,oV as xC,Yp as xD,oc as xE,Z0 as xF,dnt as xG,use as x
4262H,_4 as xI,L4 as xJ,H_e as xK,$x as xL,NG as xM,iT as xN,qCt as xO,Ml as xP,k5e as xQ,sZ as xR,unt as xS,B4 as xT,Bat as xU,lTt as xV,lI as xW,ei as xX,B_e as xY,Hs as xZ,ia as x_,g5e as xa,dAt as xb,gnt as xc,fnt as xd,E_e as xe,Unt as xf,Qh as xg,H0 as xh,V as xi,RBe as xj,jT as xk,BT as xl,HT as xm,tSt as xn,JUe as xo,snt as xp,BL as xq,f$e as xr,Iyt as xs,kot as xt,T2 as xu,hAt as xv,znt as xw,CR as xx,jnt as xy,gr as xz,t5e as y,SA as y$,nb as y0,yyt as y1,sAt as y2,Nyt as y3,VB as y4,UB as y5,DD as y6,TA as y7,nW as y8,AEt as y9,Swt as yA,xit as yB,rit as yC,Cht as yD,Oht as yE,Tot as yF,H4 as yG,Iat as yH,Zat as yI,pet as yJ,$$e as yK,Sat as yL,ETt as yM,hat as yN,dTt as yO,Tat as yP,cTt as yQ,mTt as yR,uTt as yS,Xh as yT,fb as yU,qQ as yV,Ytt as yW,cRe as yX,RQe as yY,crt as yZ,l2t as y_,Jtt as ya,Tft as yb,hft as yc,Ift as yd,GQ as ye,Sft as yf,wft as yg,Fl as yh,xd as yi,pEt as yj,Use as yk,nx as yl,cot as ym,W0 as yn,Jr as yo,qtt as yp,wot as yq,R2 as yr,Tle as ys,Kmt as yt,set as yu,NAt as yv,wAt as yw,vAt as yx,Cwt as yy,Twt as yz,i1e as z,swt as z$,Kf as z0,g2t as z1,f2t as z2,Qg as z3,Xnt as z4,u2t as z5,d2t as z6,p2t as z7,E2t as z8,_2t as z9,Mht as zA,Uht as zB,Vht as zC,Ght as zD,Dht as zE,jht as zF,Yht as zG,Hyt as zH,Hht as zI,zht as zJ,Gyt as zK,Xht as zL,iUe as zM,dNt as zN,wht as zO,qpt as zP,O0t as zQ,Adt as zR,ydt as zS,DCe as zT,Ei as zU,FG as zV,OQe as zW,xnt as zX,Py as zY,tb as zZ,G$e as z_,hxe as za,tU as zb,xwt as zc,CQe as zd,pse as ze,pd as zf,Y2e as zg,yvt as zh,VKe as zi,qht as zj,XKe as zk,UKe as zl,Kht as zm,Jht as zn,Bht as zo,Nht as zp,og as zq,Wyt as zr,jyt as zs,dvt as zt,kht as zu,Wht as zv,Pht as zw,bht as zx,Fht as zy,Lht as zz};
4263//# sourceMappingURL=scene-B7kE8RMp.js.map

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.