@shotstack/shotstack-studio 2.0.0-beta.38 → 2.0.0-beta.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(Mt,fs){typeof exports=="object"&&typeof module<"u"?fs(exports,require("pixi.js"),require("howler"),require("opentype.js"),require("pixi.js/app"),require("pixi.js/events"),require("pixi.js/graphics"),require("pixi.js/text"),require("pixi.js/text-html"),require("pixi.js/sprite-tiling"),require("pixi.js/filters"),require("pixi.js/mesh")):typeof define=="function"&&define.amd?define(["exports","pixi.js","howler","opentype.js","pixi.js/app","pixi.js/events","pixi.js/graphics","pixi.js/text","pixi.js/text-html","pixi.js/sprite-tiling","pixi.js/filters","pixi.js/mesh"],fs):(Mt=typeof globalThis<"u"?globalThis:Mt||self,fs(Mt.ShotstackStudio={},Mt.PIXI,Mt.Howler,Mt.opentype))})(this,function(Mt,fs,cg,dg){"use strict";var Bs=typeof document<"u"?document.currentScript:null;function Fo(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const i=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const G=Fo(fs),ug=Fo(cg),Vo=Fo(dg),fg={version:"2.0.0-beta.38"};class hg{curves={};constructor(){this.initializeCurves()}initializeCurves(){this.curves={smooth:[[.5,0],[.5,1]],ease:[[.25,.1],[.25,1]],easeIn:[[.42,0],[1,1]],easeOut:[[0,0],[.58,1]],easeInOut:[[.42,0],[.58,1]],easeInQuad:[[.55,.085],[.68,.53]],easeInCubic:[[.55,.055],[.675,.19]],easeInQuart:[[.895,.03],[.685,.22]],easeInQuint:[[.755,.05],[.855,.06]],easeInSine:[[.47,0],[.745,.715]],easeInExpo:[[.95,.05],[.795,.035]],easeInCirc:[[.6,.04],[.98,.335]],easeInBack:[[.6,-.28],[.735,.045]],easeOutQuad:[[.25,.46],[.45,.94]],easeOutCubic:[[.215,.61],[.355,1]],easeOutQuart:[[.165,.84],[.44,1]],easeOutQuint:[[.23,1],[.32,1]],easeOutSine:[[.39,.575],[.565,1]],easeOutExpo:[[.19,1],[.22,1]],easeOutCirc:[[.075,.82],[.165,1]],easeOutBack:[[.175,.885],[.32,1.275]],easeInOutQuad:[[.455,.03],[.515,.955]],easeInOutCubic:[[.645,.045],[.355,1]],easeInOutQuart:[[.77,0],[.175,1]],easeInOutQuint:[[.86,0],[.07,1]],easeInOutSine:[[.445,.05],[.55,.95]],easeInOutExpo:[[1,0],[0,1]],easeInOutCirc:[[.785,.135],[.15,.86]],easeInOutBack:[[.68,-.55],[.265,1.55]]}}getValue(e,t,i,a){const r=this.curves[a??""]??this.curves.ease,[[n,o],[l,c]]=r,d=i+(3*n-3*l+1)*i*(1-i),u=e,f=e+(t-e)*o,p=e+(t-e)*c,g=t,w=d,C=1-w;return C**3*u+3*C**2*w*f+3*C*w**2*p+w**3*g}}class Da{property;length;cubicBuilder;cachedIndex=0;constructor(e,t,i=0){this.property=this.createKeyframes(e,t,i),this.length=t,this.cubicBuilder=new hg}getValue(e){const t=this.findKeyframe(e);if(!t){if(this.property.length>0){if(e>=this.length)return this.property[this.property.length-1].to;if(e<0)return this.property[0].from}return 1}const i=(e-t.start)/t.length;switch(t.interpolation){case"bezier":return this.cubicBuilder.getValue(t.from,t.to,i,t.easing);case"constant":return t.from;case"linear":default:return t.from+(t.to-t.from)*i}}findKeyframe(e){const t=this.property;if(t.length===0)return;const i=t[this.cachedIndex];if(i){const o=i.start+i.length;if(Number.isFinite(o)&&e>=i.start&&e<o)return i}const a=this.cachedIndex+1;if(a<t.length){const o=t[a],l=o.start+o.length;if(Number.isFinite(l)&&e>=o.start&&e<l)return this.cachedIndex=a,o}const r=this.cachedIndex-1;if(r>=0){const o=t[r],l=o.start+o.length;if(Number.isFinite(l)&&e>=o.start&&e<l)return this.cachedIndex=r,o}const n=this.binarySearchKeyframe(e);if(n!==-1)return this.cachedIndex=n,t[n]}binarySearchKeyframe(e){const t=this.property;let i=0,a=t.length-1;for(;i<=a;){const r=Math.floor((i+a)/2),n=t[r],o=n.start+n.length;if(!Number.isFinite(o)||e>=o)i=r+1;else if(e<n.start)a=r-1;else return r}return-1}createKeyframes(e,t,i=0){if(typeof e=="number")return[{start:0,length:t,from:e,to:e}];if(!e.length)throw new Error("Keyframes should have at least one value.");const a=this.createNormalizedKeyframes(e);return this.validateKeyframes(a),this.insertFillerKeyframes(a,t,i)}createNormalizedKeyframes(e){return e.filter(t=>typeof t.start=="number"&&typeof t.length=="number").toSorted((t,i)=>t.start-i.start).map(t=>({start:t.start,length:t.length,from:typeof t.from=="number"?t.from:0,to:typeof t.to=="number"?t.to:0,interpolation:t.interpolation,easing:t.easing}))}validateKeyframes(e){for(let t=0;t<e.length;t+=1){const i=e[t],a=e[t+1];if(!a){if(i.start+i.length>this.length)throw new Error("Last keyframe exceeds the maximum duration.");break}if(i.start+i.length>a.start)throw new Error("Overlapping keyframes detected.")}}insertFillerKeyframes(e,t,i=0){const a=[];for(let r=0;r<e.length;r+=1){const n=e[r],o=e[r+1];if(r===0&&n.start!==0){const d={start:0,length:n.start,from:i,to:n.from};a.push(d)}if(a.push(n),!o){if(n.start+n.length<t){const u=n.start+n.length,f={start:u,length:t-u,from:n.to,to:n.to};a.push(f)}break}if(n.start+n.length!==o.start){const d=n.start+n.length,u=o.start-d,f={start:d,length:u,from:n.to,to:o.from};a.push(f)}}return a}}class Si{baseValue;mode;layers=[];length;clampRange;constructor(e,t,i,a){this.baseValue=e,this.length=t,this.mode=i,this.clampRange=a}addLayer(e){if(e.length===0)return;const t=this.mode==="additive"?0:1;this.layers.push(new Da(e,this.length,t))}getValue(e){if(this.layers.length===0)return this.baseValue;if(this.mode==="additive"){let i=this.baseValue;for(const a of this.layers)i+=a.getValue(e);return i}let t=this.baseValue;for(const i of this.layers)t*=i.getValue(e);return this.clampRange&&(t=Math.max(this.clampRange.min,Math.min(this.clampRange.max,t))),t}}class pg{clipConfiguration;effectPreset;constructor(e){this.clipConfiguration=e;const[t,i]=(e.effect??"").split(/(Slow|Fast)/);this.effectPreset={name:t,speed:i}}buildRelative(e,t){const i=[],a=[],r=[],n=[],o=[],{effect:l,length:c}=this.clipConfiguration;if(!l)return{offsetXKeyframes:i,offsetYKeyframes:a,opacityKeyframes:r,scaleKeyframes:n,rotationKeyframes:o};const d=0,u=this.getPresetName();switch(u){case"zoomIn":{const f=this.getZoomSpeed();n.push({from:1,to:f,start:d,length:c,interpolation:"linear"});break}case"zoomOut":{const f=this.getZoomSpeed();n.push({from:f,to:1,start:d,length:c,interpolation:"linear"});break}case"slideLeft":case"slideRight":case"slideUp":case"slideDown":{const f=u==="slideLeft"||u==="slideRight",p=u==="slideLeft"||u==="slideUp",g=this.getFittedSize(e,t),w=f?e.width:e.height,C=f?g.width:g.height;let v=this.getSlideStart();const k=w+w*v*2;if(C<k){const R=k/C;n.push({from:R,to:R,start:d,length:c,interpolation:"linear"})}else v=(C-w)/2/w;const[x,T]=p?[v,-v]:[-v,v];(f?i:a).push({from:x,to:T,start:d,length:c});break}}return{offsetXKeyframes:i,offsetYKeyframes:a,opacityKeyframes:r,scaleKeyframes:n,rotationKeyframes:o}}getPresetName(){return this.effectPreset.name}getZoomSpeed(){const{name:e,speed:t}=this.effectPreset;if(e.startsWith("zoom"))switch(t){case"Slow":return 1.1;case"Fast":return 1.7;default:return 1.3}return 0}getSlideStart(){const{name:e,speed:t}=this.effectPreset;if(e.startsWith("slide"))switch(t){case"Slow":return .03;case"Fast":return .2;default:return .12}return 0}getFittedSize(e,t){switch(this.clipConfiguration.fit??"crop"){case"cover":case"crop":{const a=Math.max(e.width/t.width,e.height/t.height);return{width:t.width*a,height:t.height*a}}case"contain":{const a=Math.min(e.width/t.width,e.height/t.height);return{width:t.width*a,height:t.height*a}}case"none":default:return t}}}class gg{clipConfiguration;inPreset;outPreset;constructor(e){this.clipConfiguration=e,this.inPreset=this.parseTransition(e.transition?.in),this.outPreset=this.parseTransition(e.transition?.out)}parseTransition(e){const[t,i]=(e??"").split(/(Slow|Fast|VeryFast)/);return{name:t,speed:i}}buildRelative(){return{in:this.buildTransitionKeyframes("in"),out:this.buildTransitionKeyframes("out")}}createEmptyKeyframeSet(){return{offsetXKeyframes:[],offsetYKeyframes:[],opacityKeyframes:[],scaleKeyframes:[],rotationKeyframes:[],maskXKeyframes:[]}}buildTransitionKeyframes(e){const t=this.createEmptyKeyframeSet();if(!(e==="in"?this.clipConfiguration.transition?.in:this.clipConfiguration.transition?.out))return t;const a=this.getPresetLength(e),r=e==="in"?0:this.clipConfiguration.length-a,n=this.getPresetName(e),o=e==="in";switch(n){case"fade":{const[l,c]=o?[0,1]:[1,0];t.opacityKeyframes.push({from:l,to:c,start:r,length:a,interpolation:"bezier",easing:"ease"});break}case"zoom":{const[l,c]=o?[10,1]:[1,10],[d,u]=o?[0,1]:[1,0],f=o?"easeIn":"easeOut";t.scaleKeyframes.push({from:l,to:c,start:r,length:a,interpolation:"bezier",easing:f}),t.opacityKeyframes.push({from:d,to:u,start:r,length:a,interpolation:"bezier",easing:f});break}case"slideLeft":case"slideRight":case"slideUp":case"slideDown":{const l=n==="slideLeft"||n==="slideRight",c=n==="slideLeft"||n==="slideUp",d=.025,[u,f]=o?[c?d:-d,0]:[0,c?-d:d],p=o?"linear":"bezier",[g,w]=o?[0,1]:[1,0];(l?t.offsetXKeyframes:t.offsetYKeyframes).push(o?{from:u,to:f,start:r,length:a,interpolation:p}:{from:u,to:f,start:r,length:a,interpolation:p,easing:"ease"}),t.opacityKeyframes.push({from:g,to:w,start:r,length:a,interpolation:"bezier",easing:"ease"});break}case"carouselLeft":case"carouselRight":case"carouselUp":case"carouselDown":{const l=n==="carouselLeft"||n==="carouselRight",c=n==="carouselLeft"||n==="carouselUp",d=l&&1||(o?1.05:1.1),[u,f]=o?[c?d:-d,0]:[0,c?-d:d];(l?t.offsetXKeyframes:t.offsetYKeyframes).push(o?{from:u,to:f,start:r,length:a,interpolation:"linear"}:{from:u,to:f,start:r,length:a,interpolation:"bezier",easing:"ease"});break}case"reveal":case"wipeRight":{const[l,c]=o?[0,1]:[1,0];t.maskXKeyframes.push({from:l,to:c,start:r,length:a,interpolation:"bezier",easing:"ease"});break}case"wipeLeft":{const[l,c]=o?[1,0]:[0,1];t.maskXKeyframes.push({from:l,to:c,start:r,length:a,interpolation:"bezier",easing:"ease"});break}}return t}getPresetName(e){return e==="in"?this.inPreset.name:this.outPreset.name}getPresetLength(e){const{name:t,speed:i}=e==="in"?this.inPreset:this.outPreset,a=t.startsWith("carousel"),r=t.startsWith("slide");if(t==="zoom")return .4;switch(i){case"Slow":return 2;case"Fast":return a||r?.25:.5;case"VeryFast":return .25;default:return a||r?.5:1}}}const Z={PlaybackPlay:"playback:play",PlaybackPause:"playback:pause",TimelineUpdated:"timeline:updated",TimelineBackgroundChanged:"timeline:backgroundChanged",ClipAdded:"clip:added",ClipSplit:"clip:split",ClipSelected:"clip:selected",ClipUpdated:"clip:updated",ClipDeleted:"clip:deleted",ClipRestored:"clip:restored",ClipCopied:"clip:copied",ClipLoadFailed:"clip:loadFailed",ClipUnresolved:"clip:unresolved",SelectionCleared:"selection:cleared",EditChanged:"edit:changed",EditUndo:"edit:undo",EditRedo:"edit:redo",TrackAdded:"track:added",TrackRemoved:"track:removed",DurationChanged:"duration:changed",OutputResized:"output:resized",OutputResolutionChanged:"output:resolutionChanged",OutputAspectRatioChanged:"output:aspectRatioChanged",OutputFpsChanged:"output:fpsChanged",OutputFormatChanged:"output:formatChanged",OutputDestinationsChanged:"output:destinationsChanged",MergeFieldChanged:"mergefield:changed",TranscriptionProgress:"transcription:progress",TranscriptionCompleted:"transcription:completed",TranscriptionFailed:"transcription:failed",LumaAttached:"luma:attached",LumaDetached:"luma:detached"},Be={CanvasClipClicked:"canvas:clipClicked",CanvasBackgroundClicked:"canvas:backgroundClicked",FontCapabilitiesChanged:"font:capabilitiesChanged",ToolbarButtonsChanged:"toolbar:buttonsChanged",Resolved:"resolved",PlayerAddedToTrack:"player:addedToTrack",PlayerMovedBetweenTracks:"player:movedBetweenTracks",PlayerRemovedFromTrack:"player:removedFromTrack",PlayerLoaded:"player:loaded",TrackContainerRemoved:"track:containerRemoved",ViewportSizeChanged:"viewport:sizeChanged",ViewportNeedsZoomToFit:"viewport:needsZoomToFit"};function mg(s,e,t){const i=e.width/s.width,a=e.height/s.height;switch(t??"crop"){case"crop":case"cover":return Math.max(i,a);case"contain":return Math.min(i,a);case"none":default:return 1}}function yg(s,e,t,i,a){if(a)return{x:i,y:i};if(s.width===0||s.height===0)return{x:i,y:i};const r=e.width/s.width,n=e.height/s.height;switch(t??"crop"){case"contain":{const o=Math.min(r,n)*i;return{x:o,y:o}}case"crop":{const o=Math.max(r,n)*i;return{x:o,y:o}}case"cover":return{x:r*i,y:n*i};case"none":default:return{x:i,y:i}}}function bg(s,e,t){const i=e.width/2,a=e.height/2;switch(t??"crop"){case"cover":{const r=e.width/s.width,n=e.height/s.height;return{scaleX:r,scaleY:n,positionX:i,positionY:a}}case"crop":{const r=Math.max(e.width/s.width,e.height/s.height);return{scaleX:r,scaleY:r,positionX:i,positionY:a}}case"contain":{const r=Math.min(e.width/s.width,e.height/s.height);return{scaleX:r,scaleY:r,positionX:i,positionY:a}}case"none":default:return{scaleX:1,scaleY:1,positionX:i,positionY:a}}}function dd(s){return s*1e3}function _o(s){return s/1e3}function l9(s){return s}function c9(s){return s}function hs(s){return typeof s=="string"&&/^alias:\/\/[a-zA-Z0-9_-]+$/.test(s)}function Rr(s){return s.replace(/^alias:\/\//,"")}let ud=class{static ButtonLeftClick=0;static ButtonRightClick=3};class fd{containerSize;constructor(e){this.containerSize=e}relativeToAbsolute(e,t,i){switch(t){case"topLeft":return{x:i.x*this.containerSize.width,y:-i.y*this.containerSize.height};case"topRight":return{x:(i.x+1)*this.containerSize.width-e.width,y:-i.y*this.containerSize.height};case"bottomLeft":return{x:i.x*this.containerSize.width,y:(-i.y+1)*this.containerSize.height-e.height};case"bottomRight":return{x:(i.x+1)*this.containerSize.width-e.width,y:(-i.y+1)*this.containerSize.height-e.height};case"left":return{x:i.x*this.containerSize.width,y:(-i.y+.5)*this.containerSize.height-e.height/2};case"right":return{x:(i.x+1)*this.containerSize.width-e.width,y:(-i.y+.5)*this.containerSize.height-e.height/2};case"top":return{x:(i.x+.5)*this.containerSize.width-e.width/2,y:-i.y*this.containerSize.height};case"bottom":return{x:(i.x+.5)*this.containerSize.width-e.width/2,y:(-i.y+1)*this.containerSize.height-e.height};case"center":default:return{x:(i.x+.5)*this.containerSize.width-e.width/2,y:(-i.y+.5)*this.containerSize.height-e.height/2}}}absoluteToRelative(e,t,i){switch(t){case"topLeft":return{x:i.x/this.containerSize.width,y:-(i.y/this.containerSize.height)};case"topRight":return{x:(i.x+e.width)/this.containerSize.width-1,y:-(i.y/this.containerSize.height)};case"bottomLeft":return{x:i.x/this.containerSize.width,y:-((i.y+e.height)/this.containerSize.height-1)};case"bottomRight":return{x:(i.x+e.width)/this.containerSize.width-1,y:-((i.y+e.height)/this.containerSize.height-1)};case"left":return{x:i.x/this.containerSize.width,y:-((i.y+e.height/2)/this.containerSize.height-.5)};case"right":return{x:(i.x+e.width)/this.containerSize.width-1,y:-((i.y+e.height/2)/this.containerSize.height-.5)};case"top":return{x:(i.x+e.width/2)/this.containerSize.width-.5,y:-(i.y/this.containerSize.height)};case"bottom":return{x:(i.x+e.width/2)/this.containerSize.width-.5,y:-((i.y+e.height)/this.containerSize.height-1)};case"center":default:return{x:(i.x+e.width/2)/this.containerSize.width-.5,y:-((i.y+e.height/2)/this.containerSize.height-.5)}}}}class wg{container;constructor(){this.container=new G.Container}getContainer(){return this.container}}var it=(s=>(s.Video="video",s.Image="image",s.Audio="audio",s.Text="text",s.RichText="rich-text",s.Luma="luma",s.Html="html",s.Shape="shape",s.Caption="caption",s.Svg="svg",s.TextToImage="text-to-image",s.ImageToVideo="image-to-video",s.TextToSpeech="text-to-speech",s))(it||{});class Lt extends wg{static DiscardedFrameCount=0;layer;shouldDispose;playerType;clipId=null;edit;clipConfiguration;resolvedTiming;positionBuilder;offsetXKeyframeBuilder;offsetYKeyframeBuilder;scaleKeyframeBuilder;opacityKeyframeBuilder;rotationKeyframeBuilder;skewXKeyframeBuilder;skewYKeyframeBuilder;maskXKeyframeBuilder;wipeMask;contentContainer;constructor(e,t,i){super(),this.edit=e,this.layer=0,this.shouldDispose=!1,this.playerType=i,this.clipConfiguration=t,this.positionBuilder=new fd(e.size),this.resolvedTiming={start:t.start,length:t.length},this.wipeMask=null,this.contentContainer=new G.Container,this.getContainer().addChild(this.contentContainer)}reconfigureAfterRestore(){this.configureKeyframes()}async reloadAsset(){}configureKeyframes(){const e=this.getLength(),t=this.clipConfiguration,i=typeof t.offset?.x=="number"?t.offset.x:0,a=typeof t.offset?.y=="number"?t.offset.y:0,r=typeof t.scale=="number"?t.scale:1,n=typeof t.opacity=="number"?t.opacity:1,o=typeof t.transform?.rotate?.angle=="number"?t.transform.rotate.angle:0,l=typeof t.transform?.skew?.x=="number"?t.transform.skew.x:0,c=typeof t.transform?.skew?.y=="number"?t.transform.skew.y:0;if(this.offsetXKeyframeBuilder=new Si(i,e,"additive"),this.offsetYKeyframeBuilder=new Si(a,e,"additive"),this.scaleKeyframeBuilder=new Si(r,e,"multiplicative"),this.opacityKeyframeBuilder=new Si(n,e,"multiplicative",{min:0,max:1}),this.rotationKeyframeBuilder=new Si(o,e,"additive"),this.skewXKeyframeBuilder=new Si(l,e,"additive"),this.skewYKeyframeBuilder=new Si(c,e,"additive"),this.clipHasKeyframes()){Array.isArray(t.scale)&&this.scaleKeyframeBuilder.addLayer(t.scale),Array.isArray(t.opacity)&&this.opacityKeyframeBuilder.addLayer(t.opacity),Array.isArray(t.offset?.x)&&this.offsetXKeyframeBuilder.addLayer(t.offset.x),Array.isArray(t.offset?.y)&&this.offsetYKeyframeBuilder.addLayer(t.offset.y),Array.isArray(t.transform?.rotate?.angle)&&this.rotationKeyframeBuilder.addLayer(t.transform.rotate.angle),Array.isArray(t.transform?.skew?.x)&&this.skewXKeyframeBuilder.addLayer(t.transform.skew.x),Array.isArray(t.transform?.skew?.y)&&this.skewYKeyframeBuilder.addLayer(t.transform.skew.y);return}const d={...t,start:this.getStart(),length:e},u=new pg(d).buildRelative(this.edit.size,this.getSize()),f=new gg(d).buildRelative();this.offsetXKeyframeBuilder.addLayer(u.offsetXKeyframes),this.offsetYKeyframeBuilder.addLayer(u.offsetYKeyframes),this.scaleKeyframeBuilder.addLayer(u.scaleKeyframes),this.opacityKeyframeBuilder.addLayer(u.opacityKeyframes),this.rotationKeyframeBuilder.addLayer(u.rotationKeyframes),this.offsetXKeyframeBuilder.addLayer(f.in.offsetXKeyframes),this.offsetYKeyframeBuilder.addLayer(f.in.offsetYKeyframes),this.scaleKeyframeBuilder.addLayer(f.in.scaleKeyframes),this.opacityKeyframeBuilder.addLayer(f.in.opacityKeyframes),this.rotationKeyframeBuilder.addLayer(f.in.rotationKeyframes),this.offsetXKeyframeBuilder.addLayer(f.out.offsetXKeyframes),this.offsetYKeyframeBuilder.addLayer(f.out.offsetYKeyframes),this.scaleKeyframeBuilder.addLayer(f.out.scaleKeyframes),this.opacityKeyframeBuilder.addLayer(f.out.opacityKeyframes),this.rotationKeyframeBuilder.addLayer(f.out.rotationKeyframes);const p=[...f.in.maskXKeyframes,...f.out.maskXKeyframes];p.length&&(this.maskXKeyframeBuilder=new Da(p,e))}async load(){this.contentContainer?.destroyed&&(this.contentContainer=new G.Container,this.getContainer().addChild(this.contentContainer)),this.getContainer().sortableChildren=!0,this.getContainer().cursor="pointer",this.getContainer().eventMode="static",this.getContainer().on?.("pointerdown",this.onPointerDown.bind(this))}update(e,t){if(this.getContainer().visible=this.isActive(),this.getContainer().zIndex=1e5-this.layer*100,!this.isActive())return;const i=this.getPivot(),a=this.getPosition(),r=this.getContainerScale();this.getContainer().scale.set(r.x,r.y),this.getContainer().pivot.set(i.x,i.y),this.getContainer().position.set(a.x+i.x,a.y+i.y);const n=this.getRotation();this.contentContainer.alpha=this.getOpacity(),this.getContainer().angle=n;const o=this.getSkew();this.getContainer().skew?.set(o.x*(Math.PI/180),o.y*(Math.PI/180)),this.clipConfiguration.width&&this.clipConfiguration.height&&this.applyFixedDimensions(),this.updateWipeMask(),this.shouldDiscardFrame()&&(this.contentContainer.alpha=0)}updateWipeMask(){if(!this.maskXKeyframeBuilder){this.wipeMask&&(this.getContainer().mask=null,this.wipeMask.destroy(),this.wipeMask=null);return}const e=this.maskXKeyframeBuilder.getValue(this.getPlaybackTime()),t=this.getSize();this.wipeMask||(this.wipeMask=new G.Graphics,this.getContainer().addChild(this.wipeMask),this.getContainer().mask=this.wipeMask),this.wipeMask.clear(),this.wipeMask.rect(0,0,t.width*e,t.height),this.wipeMask.fill(16777215)}dispose(){this.wipeMask?.destroy(),this.wipeMask=null,this.contentContainer?.destroy()}getStart(){return this.resolvedTiming.start}getLength(){return this.resolvedTiming.length}getEnd(){return this.resolvedTiming.start+this.resolvedTiming.length}getTimingIntent(){if(this.clipId){const e=this.edit.getDocumentClipById(this.clipId);if(e){let t;e.start==="auto"?t="auto":(hs(e.start),t=e.start);let i;return e.length==="auto"||e.length==="end"||hs(e.length),i=e.length,{start:t,length:i}}}return{start:this.clipConfiguration.start,length:this.clipConfiguration.length}}getResolvedTiming(){return{...this.resolvedTiming}}setResolvedTiming(e){this.resolvedTiming={...e},this.clipConfiguration.start=e.start,this.clipConfiguration.length=e.length}getExportableClip(){const e=structuredClone(this.clipConfiguration),t=this.getTimingIntent();return e.start=t.start,e.length=t.length,e}getPlaybackTime(){const e=this.edit.playbackTime-this.getStart();return e<0?0:e>this.getLength()?this.getLength():e}getContentSize(){return this.getSize()}getContentContainer(){return this.contentContainer}getOpacity(){return this.opacityKeyframeBuilder?.getValue(this.getPlaybackTime())??1}getPosition(){const e={x:this.offsetXKeyframeBuilder?.getValue(this.getPlaybackTime())??0,y:this.offsetYKeyframeBuilder?.getValue(this.getPlaybackTime())??0};return this.positionBuilder.relativeToAbsolute(this.getSize(),this.clipConfiguration.position??"center",e)}getPivot(){const e=this.getSize();return{x:e.width/2,y:e.height/2}}calculateMoveOffset(e,t){const i=this.getPosition(),a={x:i.x+e,y:i.y+t},r=this.positionBuilder.absoluteToRelative(this.getSize(),this.clipConfiguration.position??"center",a);return{x:r.x,y:r.y}}getFitScale(){const e={width:this.clipConfiguration.width??this.edit.size.width,height:this.clipConfiguration.height??this.edit.size.height},t=this.getContentSize(),i=this.clipConfiguration.fit??"crop";return mg(t,e,i)}getScale(){return(this.scaleKeyframeBuilder?.getValue(this.getPlaybackTime())??1)*this.getFitScale()}getContainerScale(){const e=this.scaleKeyframeBuilder?.getValue(this.getPlaybackTime())??1,t=this.getContentSize(),i=this.clipConfiguration.fit??"crop",a=!!(this.clipConfiguration.width&&this.clipConfiguration.height);return yg(t,this.edit.size,i,e,a)}getRotation(){return this.rotationKeyframeBuilder?.getValue(this.getPlaybackTime())??0}getSkew(){return{x:this.skewXKeyframeBuilder?.getValue(this.getPlaybackTime())??0,y:this.skewYKeyframeBuilder?.getValue(this.getPlaybackTime())??0}}isActive(){return this.edit.playbackTime>=this.getStart()&&this.edit.playbackTime<this.getEnd()}shouldDiscardFrame(){return this.getPlaybackTime()<Lt.DiscardedFrameCount}onPointerDown(e){e.button===ud.ButtonLeftClick&&this.edit.getInternalEvents().emit(Be.CanvasClipClicked,{player:this})}clipHasKeyframes(){return[this.clipConfiguration.scale,this.clipConfiguration.opacity,this.clipConfiguration.offset?.x,this.clipConfiguration.offset?.y,this.clipConfiguration.transform?.rotate?.angle,this.clipConfiguration.transform?.skew?.x,this.clipConfiguration.transform?.skew?.y].some(e=>e&&typeof e!="number")}applyFixedDimensions(){const e=this.clipConfiguration.width,t=this.clipConfiguration.height;if(!e||!t)return;const i=this.contentContainer.children.find(p=>p instanceof G.Sprite);if(!i?.texture)return;const a=i.texture.width,r=i.texture.height,n=this.clipConfiguration.fit||"crop",o=this.contentContainer.mask;let l=null;if(o instanceof G.Graphics?l=o:o||(l=new G.Graphics,this.contentContainer.addChild(l),this.contentContainer.mask=l),l){const{asset:p}=this.clipConfiguration,g=p&&"border"in p&&p.border&&typeof p.border=="object"?p.border.width??0:0,w=g/2;l.clear(),l.rect(-w,-w,e+g,t+g),l.fill(16777215)}const c=this.scaleKeyframeBuilder?.getValue(this.getPlaybackTime())??1;i.anchor.set(.5,.5);const f=bg({width:a,height:r},{width:e,height:t},n);i.scale.set(f.scaleX,f.scaleY),i.position.set(f.positionX,f.positionY),this.contentContainer.scale.set(c,c),this.contentContainer.position.set(e/2*(1-c),t/2*(1-c))}applyAnchorPositioning(e,t,i,a){const r=a.width,n=a.height;if(!!a.mask){a.position.set(0,0);return}const l=(e??"center").toLowerCase();let c=0,d=0;l.includes("left")||l==="left"?c=0:l.includes("right")||l==="right"?c=t-r:c=(t-r)/2,l.includes("top")||l==="top"?d=0:l.includes("bottom")||l==="bottom"?d=i-n:d=(i-n)/2,a.position.set(c,d)}supportsEdgeResize(){return!1}onDimensionsChanged(){}notifyDimensionsChanged(){this.onDimensionsChanged()}}class za{static Name="AudioLoadParser";id;name;extension;validAudioExtensions;constructor(){this.id=za.Name,this.name=za.Name,this.extension={type:[G.ExtensionType.LoadParser],priority:G.LoaderParserPriority.Normal,ref:null},this.validAudioExtensions=["mp3","mpeg","ogg","wav"]}test(e){const t=e.split("?")[0]?.split(".").pop()??"";return this.validAudioExtensions.includes(t)}async load(e,t,i){return new Promise(a=>{const r={src:e},n=new Howl(r);n.on("load",()=>a(n)),n.on("loaderror",()=>a(null))})}unload(e){e?.unload()}}class vg extends Lt{audioResource;isPlaying;volumeKeyframeBuilder;syncTimer;constructor(e,t){super(e,t,it.Audio),this.audioResource=null,this.isPlaying=!1,this.syncTimer=0}async load(){await super.load();const e=this.clipConfiguration.asset,t=e.src,i={src:t,parser:za.Name},a=await this.edit.assetLoader.load(t,i);if(!(a instanceof ug.Howl))throw new Error(`Invalid audio source '${e.src}'.`);this.audioResource=a;const n=typeof e.volume=="number"?e.volume:1;this.volumeKeyframeBuilder=new Da(this.createVolumeKeyframes(e,n),this.getLength(),n),this.configureKeyframes()}update(e,t){super.update(e,t);const{trim:i=0}=this.clipConfiguration.asset;if(this.syncTimer+=t,this.getContainer().alpha=0,!this.audioResource)return;const a=this.edit.isPlaying&&this.isActive(),r=this.getPlaybackTime();a&&(this.isPlaying||(this.isPlaying=!0,this.audioResource.seek(r+i),this.audioResource.play()),this.audioResource.volume()!==this.getVolume()&&this.audioResource.volume(this.getVolume()),Math.abs(this.audioResource.seek()-i-r)>.1&&(this.audioResource.seek(r+i),this.edit.recordSyncCorrection())),this.isPlaying&&!a&&(this.isPlaying=!1,this.audioResource.pause());const n=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&n&&(this.syncTimer=0,this.audioResource.seek(r+i))}dispose(){this.audioResource?.unload(),this.audioResource=null}reconfigureAfterRestore(){super.reconfigureAfterRestore();const e=this.clipConfiguration.asset,t=typeof e.volume=="number"?e.volume:1;this.volumeKeyframeBuilder=new Da(this.createVolumeKeyframes(e,t),this.getLength(),t)}getSize(){return{width:0,height:0}}getVolume(){return this.volumeKeyframeBuilder.getValue(this.getPlaybackTime())}getCurrentDrift(){if(!this.audioResource)return 0;const{trim:e=0}=this.clipConfiguration.asset,t=this.audioResource.seek(),i=this.getPlaybackTime();return Math.abs(t-e-i)}createVolumeKeyframes(e,t){const{effect:i,volume:a}=e;if(!i||i==="none"||Array.isArray(a))return a??1;const r=this.getLength()/1e3,n=Math.min(2,r/2);return i==="fadeIn"?[{from:0,to:t,start:0,length:n}]:i==="fadeOut"?[{from:t,to:0,start:r-n,length:n}]:[{from:0,to:t,start:0,length:n},{from:t,to:0,start:r-n,length:n}]}}function Dr(s){const e=s.trim().replace(",","."),t=e.split(":");if(t.length===3){const i=parseInt(t[0],10),a=parseInt(t[1],10),r=parseFloat(t[2]);return i*3600+a*60+r}if(t.length===2){const i=parseInt(t[0],10),a=parseFloat(t[1]);return i*60+a}return parseFloat(e)||0}function xg(s){const e=[],t=s.split(/\r?\n/);let i=0;for(;i<t.length&&!t[i].includes("-->");)i+=1;for(;i<t.length;){const a=t[i].trim();if(a.includes("-->")){const[r,n]=a.split("-->").map(d=>d.trim().split(" ")[0]),o=Dr(r),l=Dr(n),c=[];for(i+=1;i<t.length&&t[i].trim()!==""&&!t[i].includes("-->");){const d=t[i].trim();d.startsWith("NOTE")||c.push(d),i+=1}c.length>0&&e.push({start:o,end:l,text:c.join(`
|
|
1
|
+
(function(Mt,fs){typeof exports=="object"&&typeof module<"u"?fs(exports,require("pixi.js"),require("howler"),require("opentype.js"),require("pixi.js/app"),require("pixi.js/events"),require("pixi.js/graphics"),require("pixi.js/text"),require("pixi.js/text-html"),require("pixi.js/sprite-tiling"),require("pixi.js/filters"),require("pixi.js/mesh")):typeof define=="function"&&define.amd?define(["exports","pixi.js","howler","opentype.js","pixi.js/app","pixi.js/events","pixi.js/graphics","pixi.js/text","pixi.js/text-html","pixi.js/sprite-tiling","pixi.js/filters","pixi.js/mesh"],fs):(Mt=typeof globalThis<"u"?globalThis:Mt||self,fs(Mt.ShotstackStudio={},Mt.PIXI,Mt.Howler,Mt.opentype))})(this,function(Mt,fs,cg,dg){"use strict";var Bs=typeof document<"u"?document.currentScript:null;function Fo(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const i=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const G=Fo(fs),ug=Fo(cg),Vo=Fo(dg),fg={version:"2.0.0-beta.39"};class hg{curves={};constructor(){this.initializeCurves()}initializeCurves(){this.curves={smooth:[[.5,0],[.5,1]],ease:[[.25,.1],[.25,1]],easeIn:[[.42,0],[1,1]],easeOut:[[0,0],[.58,1]],easeInOut:[[.42,0],[.58,1]],easeInQuad:[[.55,.085],[.68,.53]],easeInCubic:[[.55,.055],[.675,.19]],easeInQuart:[[.895,.03],[.685,.22]],easeInQuint:[[.755,.05],[.855,.06]],easeInSine:[[.47,0],[.745,.715]],easeInExpo:[[.95,.05],[.795,.035]],easeInCirc:[[.6,.04],[.98,.335]],easeInBack:[[.6,-.28],[.735,.045]],easeOutQuad:[[.25,.46],[.45,.94]],easeOutCubic:[[.215,.61],[.355,1]],easeOutQuart:[[.165,.84],[.44,1]],easeOutQuint:[[.23,1],[.32,1]],easeOutSine:[[.39,.575],[.565,1]],easeOutExpo:[[.19,1],[.22,1]],easeOutCirc:[[.075,.82],[.165,1]],easeOutBack:[[.175,.885],[.32,1.275]],easeInOutQuad:[[.455,.03],[.515,.955]],easeInOutCubic:[[.645,.045],[.355,1]],easeInOutQuart:[[.77,0],[.175,1]],easeInOutQuint:[[.86,0],[.07,1]],easeInOutSine:[[.445,.05],[.55,.95]],easeInOutExpo:[[1,0],[0,1]],easeInOutCirc:[[.785,.135],[.15,.86]],easeInOutBack:[[.68,-.55],[.265,1.55]]}}getValue(e,t,i,a){const r=this.curves[a??""]??this.curves.ease,[[n,o],[l,c]]=r,d=i+(3*n-3*l+1)*i*(1-i),u=e,f=e+(t-e)*o,p=e+(t-e)*c,g=t,w=d,C=1-w;return C**3*u+3*C**2*w*f+3*C*w**2*p+w**3*g}}class Da{property;length;cubicBuilder;cachedIndex=0;constructor(e,t,i=0){this.property=this.createKeyframes(e,t,i),this.length=t,this.cubicBuilder=new hg}getValue(e){const t=this.findKeyframe(e);if(!t){if(this.property.length>0){if(e>=this.length)return this.property[this.property.length-1].to;if(e<0)return this.property[0].from}return 1}const i=(e-t.start)/t.length;switch(t.interpolation){case"bezier":return this.cubicBuilder.getValue(t.from,t.to,i,t.easing);case"constant":return t.from;case"linear":default:return t.from+(t.to-t.from)*i}}findKeyframe(e){const t=this.property;if(t.length===0)return;const i=t[this.cachedIndex];if(i){const o=i.start+i.length;if(Number.isFinite(o)&&e>=i.start&&e<o)return i}const a=this.cachedIndex+1;if(a<t.length){const o=t[a],l=o.start+o.length;if(Number.isFinite(l)&&e>=o.start&&e<l)return this.cachedIndex=a,o}const r=this.cachedIndex-1;if(r>=0){const o=t[r],l=o.start+o.length;if(Number.isFinite(l)&&e>=o.start&&e<l)return this.cachedIndex=r,o}const n=this.binarySearchKeyframe(e);if(n!==-1)return this.cachedIndex=n,t[n]}binarySearchKeyframe(e){const t=this.property;let i=0,a=t.length-1;for(;i<=a;){const r=Math.floor((i+a)/2),n=t[r],o=n.start+n.length;if(!Number.isFinite(o)||e>=o)i=r+1;else if(e<n.start)a=r-1;else return r}return-1}createKeyframes(e,t,i=0){if(typeof e=="number")return[{start:0,length:t,from:e,to:e}];if(!e.length)throw new Error("Keyframes should have at least one value.");const a=this.createNormalizedKeyframes(e);return this.validateKeyframes(a),this.insertFillerKeyframes(a,t,i)}createNormalizedKeyframes(e){return e.filter(t=>typeof t.start=="number"&&typeof t.length=="number").toSorted((t,i)=>t.start-i.start).map(t=>({start:t.start,length:t.length,from:typeof t.from=="number"?t.from:0,to:typeof t.to=="number"?t.to:0,interpolation:t.interpolation,easing:t.easing}))}validateKeyframes(e){for(let t=0;t<e.length;t+=1){const i=e[t],a=e[t+1];if(!a){if(i.start+i.length>this.length)throw new Error("Last keyframe exceeds the maximum duration.");break}if(i.start+i.length>a.start)throw new Error("Overlapping keyframes detected.")}}insertFillerKeyframes(e,t,i=0){const a=[];for(let r=0;r<e.length;r+=1){const n=e[r],o=e[r+1];if(r===0&&n.start!==0){const d={start:0,length:n.start,from:i,to:n.from};a.push(d)}if(a.push(n),!o){if(n.start+n.length<t){const u=n.start+n.length,f={start:u,length:t-u,from:n.to,to:n.to};a.push(f)}break}if(n.start+n.length!==o.start){const d=n.start+n.length,u=o.start-d,f={start:d,length:u,from:n.to,to:o.from};a.push(f)}}return a}}class Si{baseValue;mode;layers=[];length;clampRange;constructor(e,t,i,a){this.baseValue=e,this.length=t,this.mode=i,this.clampRange=a}addLayer(e){if(e.length===0)return;const t=this.mode==="additive"?0:1;this.layers.push(new Da(e,this.length,t))}getValue(e){if(this.layers.length===0)return this.baseValue;if(this.mode==="additive"){let i=this.baseValue;for(const a of this.layers)i+=a.getValue(e);return i}let t=this.baseValue;for(const i of this.layers)t*=i.getValue(e);return this.clampRange&&(t=Math.max(this.clampRange.min,Math.min(this.clampRange.max,t))),t}}class pg{clipConfiguration;effectPreset;constructor(e){this.clipConfiguration=e;const[t,i]=(e.effect??"").split(/(Slow|Fast)/);this.effectPreset={name:t,speed:i}}buildRelative(e,t){const i=[],a=[],r=[],n=[],o=[],{effect:l,length:c}=this.clipConfiguration;if(!l)return{offsetXKeyframes:i,offsetYKeyframes:a,opacityKeyframes:r,scaleKeyframes:n,rotationKeyframes:o};const d=0,u=this.getPresetName();switch(u){case"zoomIn":{const f=this.getZoomSpeed();n.push({from:1,to:f,start:d,length:c,interpolation:"linear"});break}case"zoomOut":{const f=this.getZoomSpeed();n.push({from:f,to:1,start:d,length:c,interpolation:"linear"});break}case"slideLeft":case"slideRight":case"slideUp":case"slideDown":{const f=u==="slideLeft"||u==="slideRight",p=u==="slideLeft"||u==="slideUp",g=this.getFittedSize(e,t),w=f?e.width:e.height,C=f?g.width:g.height;let v=this.getSlideStart();const k=w+w*v*2;if(C<k){const R=k/C;n.push({from:R,to:R,start:d,length:c,interpolation:"linear"})}else v=(C-w)/2/w;const[x,T]=p?[v,-v]:[-v,v];(f?i:a).push({from:x,to:T,start:d,length:c});break}}return{offsetXKeyframes:i,offsetYKeyframes:a,opacityKeyframes:r,scaleKeyframes:n,rotationKeyframes:o}}getPresetName(){return this.effectPreset.name}getZoomSpeed(){const{name:e,speed:t}=this.effectPreset;if(e.startsWith("zoom"))switch(t){case"Slow":return 1.1;case"Fast":return 1.7;default:return 1.3}return 0}getSlideStart(){const{name:e,speed:t}=this.effectPreset;if(e.startsWith("slide"))switch(t){case"Slow":return .03;case"Fast":return .2;default:return .12}return 0}getFittedSize(e,t){switch(this.clipConfiguration.fit??"crop"){case"cover":case"crop":{const a=Math.max(e.width/t.width,e.height/t.height);return{width:t.width*a,height:t.height*a}}case"contain":{const a=Math.min(e.width/t.width,e.height/t.height);return{width:t.width*a,height:t.height*a}}case"none":default:return t}}}class gg{clipConfiguration;inPreset;outPreset;constructor(e){this.clipConfiguration=e,this.inPreset=this.parseTransition(e.transition?.in),this.outPreset=this.parseTransition(e.transition?.out)}parseTransition(e){const[t,i]=(e??"").split(/(Slow|Fast|VeryFast)/);return{name:t,speed:i}}buildRelative(){return{in:this.buildTransitionKeyframes("in"),out:this.buildTransitionKeyframes("out")}}createEmptyKeyframeSet(){return{offsetXKeyframes:[],offsetYKeyframes:[],opacityKeyframes:[],scaleKeyframes:[],rotationKeyframes:[],maskXKeyframes:[]}}buildTransitionKeyframes(e){const t=this.createEmptyKeyframeSet();if(!(e==="in"?this.clipConfiguration.transition?.in:this.clipConfiguration.transition?.out))return t;const a=this.getPresetLength(e),r=e==="in"?0:this.clipConfiguration.length-a,n=this.getPresetName(e),o=e==="in";switch(n){case"fade":{const[l,c]=o?[0,1]:[1,0];t.opacityKeyframes.push({from:l,to:c,start:r,length:a,interpolation:"bezier",easing:"ease"});break}case"zoom":{const[l,c]=o?[10,1]:[1,10],[d,u]=o?[0,1]:[1,0],f=o?"easeIn":"easeOut";t.scaleKeyframes.push({from:l,to:c,start:r,length:a,interpolation:"bezier",easing:f}),t.opacityKeyframes.push({from:d,to:u,start:r,length:a,interpolation:"bezier",easing:f});break}case"slideLeft":case"slideRight":case"slideUp":case"slideDown":{const l=n==="slideLeft"||n==="slideRight",c=n==="slideLeft"||n==="slideUp",d=.025,[u,f]=o?[c?d:-d,0]:[0,c?-d:d],p=o?"linear":"bezier",[g,w]=o?[0,1]:[1,0];(l?t.offsetXKeyframes:t.offsetYKeyframes).push(o?{from:u,to:f,start:r,length:a,interpolation:p}:{from:u,to:f,start:r,length:a,interpolation:p,easing:"ease"}),t.opacityKeyframes.push({from:g,to:w,start:r,length:a,interpolation:"bezier",easing:"ease"});break}case"carouselLeft":case"carouselRight":case"carouselUp":case"carouselDown":{const l=n==="carouselLeft"||n==="carouselRight",c=n==="carouselLeft"||n==="carouselUp",d=l&&1||(o?1.05:1.1),[u,f]=o?[c?d:-d,0]:[0,c?-d:d];(l?t.offsetXKeyframes:t.offsetYKeyframes).push(o?{from:u,to:f,start:r,length:a,interpolation:"linear"}:{from:u,to:f,start:r,length:a,interpolation:"bezier",easing:"ease"});break}case"reveal":case"wipeRight":{const[l,c]=o?[0,1]:[1,0];t.maskXKeyframes.push({from:l,to:c,start:r,length:a,interpolation:"bezier",easing:"ease"});break}case"wipeLeft":{const[l,c]=o?[1,0]:[0,1];t.maskXKeyframes.push({from:l,to:c,start:r,length:a,interpolation:"bezier",easing:"ease"});break}}return t}getPresetName(e){return e==="in"?this.inPreset.name:this.outPreset.name}getPresetLength(e){const{name:t,speed:i}=e==="in"?this.inPreset:this.outPreset,a=t.startsWith("carousel"),r=t.startsWith("slide");if(t==="zoom")return .4;switch(i){case"Slow":return 2;case"Fast":return a||r?.25:.5;case"VeryFast":return .25;default:return a||r?.5:1}}}const Z={PlaybackPlay:"playback:play",PlaybackPause:"playback:pause",TimelineUpdated:"timeline:updated",TimelineBackgroundChanged:"timeline:backgroundChanged",ClipAdded:"clip:added",ClipSplit:"clip:split",ClipSelected:"clip:selected",ClipUpdated:"clip:updated",ClipDeleted:"clip:deleted",ClipRestored:"clip:restored",ClipCopied:"clip:copied",ClipLoadFailed:"clip:loadFailed",ClipUnresolved:"clip:unresolved",SelectionCleared:"selection:cleared",EditChanged:"edit:changed",EditUndo:"edit:undo",EditRedo:"edit:redo",TrackAdded:"track:added",TrackRemoved:"track:removed",DurationChanged:"duration:changed",OutputResized:"output:resized",OutputResolutionChanged:"output:resolutionChanged",OutputAspectRatioChanged:"output:aspectRatioChanged",OutputFpsChanged:"output:fpsChanged",OutputFormatChanged:"output:formatChanged",OutputDestinationsChanged:"output:destinationsChanged",MergeFieldChanged:"mergefield:changed",TranscriptionProgress:"transcription:progress",TranscriptionCompleted:"transcription:completed",TranscriptionFailed:"transcription:failed",LumaAttached:"luma:attached",LumaDetached:"luma:detached"},Be={CanvasClipClicked:"canvas:clipClicked",CanvasBackgroundClicked:"canvas:backgroundClicked",FontCapabilitiesChanged:"font:capabilitiesChanged",ToolbarButtonsChanged:"toolbar:buttonsChanged",Resolved:"resolved",PlayerAddedToTrack:"player:addedToTrack",PlayerMovedBetweenTracks:"player:movedBetweenTracks",PlayerRemovedFromTrack:"player:removedFromTrack",PlayerLoaded:"player:loaded",TrackContainerRemoved:"track:containerRemoved",ViewportSizeChanged:"viewport:sizeChanged",ViewportNeedsZoomToFit:"viewport:needsZoomToFit"};function mg(s,e,t){const i=e.width/s.width,a=e.height/s.height;switch(t??"crop"){case"crop":case"cover":return Math.max(i,a);case"contain":return Math.min(i,a);case"none":default:return 1}}function yg(s,e,t,i,a){if(a)return{x:i,y:i};if(s.width===0||s.height===0)return{x:i,y:i};const r=e.width/s.width,n=e.height/s.height;switch(t??"crop"){case"contain":{const o=Math.min(r,n)*i;return{x:o,y:o}}case"crop":{const o=Math.max(r,n)*i;return{x:o,y:o}}case"cover":return{x:r*i,y:n*i};case"none":default:return{x:i,y:i}}}function bg(s,e,t){const i=e.width/2,a=e.height/2;switch(t??"crop"){case"cover":{const r=e.width/s.width,n=e.height/s.height;return{scaleX:r,scaleY:n,positionX:i,positionY:a}}case"crop":{const r=Math.max(e.width/s.width,e.height/s.height);return{scaleX:r,scaleY:r,positionX:i,positionY:a}}case"contain":{const r=Math.min(e.width/s.width,e.height/s.height);return{scaleX:r,scaleY:r,positionX:i,positionY:a}}case"none":default:return{scaleX:1,scaleY:1,positionX:i,positionY:a}}}function dd(s){return s*1e3}function _o(s){return s/1e3}function l9(s){return s}function c9(s){return s}function hs(s){return typeof s=="string"&&/^alias:\/\/[a-zA-Z0-9_-]+$/.test(s)}function Rr(s){return s.replace(/^alias:\/\//,"")}let ud=class{static ButtonLeftClick=0;static ButtonRightClick=3};class fd{containerSize;constructor(e){this.containerSize=e}relativeToAbsolute(e,t,i){switch(t){case"topLeft":return{x:i.x*this.containerSize.width,y:-i.y*this.containerSize.height};case"topRight":return{x:(i.x+1)*this.containerSize.width-e.width,y:-i.y*this.containerSize.height};case"bottomLeft":return{x:i.x*this.containerSize.width,y:(-i.y+1)*this.containerSize.height-e.height};case"bottomRight":return{x:(i.x+1)*this.containerSize.width-e.width,y:(-i.y+1)*this.containerSize.height-e.height};case"left":return{x:i.x*this.containerSize.width,y:(-i.y+.5)*this.containerSize.height-e.height/2};case"right":return{x:(i.x+1)*this.containerSize.width-e.width,y:(-i.y+.5)*this.containerSize.height-e.height/2};case"top":return{x:(i.x+.5)*this.containerSize.width-e.width/2,y:-i.y*this.containerSize.height};case"bottom":return{x:(i.x+.5)*this.containerSize.width-e.width/2,y:(-i.y+1)*this.containerSize.height-e.height};case"center":default:return{x:(i.x+.5)*this.containerSize.width-e.width/2,y:(-i.y+.5)*this.containerSize.height-e.height/2}}}absoluteToRelative(e,t,i){switch(t){case"topLeft":return{x:i.x/this.containerSize.width,y:-(i.y/this.containerSize.height)};case"topRight":return{x:(i.x+e.width)/this.containerSize.width-1,y:-(i.y/this.containerSize.height)};case"bottomLeft":return{x:i.x/this.containerSize.width,y:-((i.y+e.height)/this.containerSize.height-1)};case"bottomRight":return{x:(i.x+e.width)/this.containerSize.width-1,y:-((i.y+e.height)/this.containerSize.height-1)};case"left":return{x:i.x/this.containerSize.width,y:-((i.y+e.height/2)/this.containerSize.height-.5)};case"right":return{x:(i.x+e.width)/this.containerSize.width-1,y:-((i.y+e.height/2)/this.containerSize.height-.5)};case"top":return{x:(i.x+e.width/2)/this.containerSize.width-.5,y:-(i.y/this.containerSize.height)};case"bottom":return{x:(i.x+e.width/2)/this.containerSize.width-.5,y:-((i.y+e.height)/this.containerSize.height-1)};case"center":default:return{x:(i.x+e.width/2)/this.containerSize.width-.5,y:-((i.y+e.height/2)/this.containerSize.height-.5)}}}}class wg{container;constructor(){this.container=new G.Container}getContainer(){return this.container}}var it=(s=>(s.Video="video",s.Image="image",s.Audio="audio",s.Text="text",s.RichText="rich-text",s.Luma="luma",s.Html="html",s.Shape="shape",s.Caption="caption",s.Svg="svg",s.TextToImage="text-to-image",s.ImageToVideo="image-to-video",s.TextToSpeech="text-to-speech",s))(it||{});class Lt extends wg{static DiscardedFrameCount=0;layer;shouldDispose;playerType;clipId=null;edit;clipConfiguration;resolvedTiming;positionBuilder;offsetXKeyframeBuilder;offsetYKeyframeBuilder;scaleKeyframeBuilder;opacityKeyframeBuilder;rotationKeyframeBuilder;skewXKeyframeBuilder;skewYKeyframeBuilder;maskXKeyframeBuilder;wipeMask;contentContainer;constructor(e,t,i){super(),this.edit=e,this.layer=0,this.shouldDispose=!1,this.playerType=i,this.clipConfiguration=t,this.positionBuilder=new fd(e.size),this.resolvedTiming={start:t.start,length:t.length},this.wipeMask=null,this.contentContainer=new G.Container,this.getContainer().addChild(this.contentContainer)}reconfigureAfterRestore(){this.configureKeyframes()}async reloadAsset(){}configureKeyframes(){const e=this.getLength(),t=this.clipConfiguration,i=typeof t.offset?.x=="number"?t.offset.x:0,a=typeof t.offset?.y=="number"?t.offset.y:0,r=typeof t.scale=="number"?t.scale:1,n=typeof t.opacity=="number"?t.opacity:1,o=typeof t.transform?.rotate?.angle=="number"?t.transform.rotate.angle:0,l=typeof t.transform?.skew?.x=="number"?t.transform.skew.x:0,c=typeof t.transform?.skew?.y=="number"?t.transform.skew.y:0;if(this.offsetXKeyframeBuilder=new Si(i,e,"additive"),this.offsetYKeyframeBuilder=new Si(a,e,"additive"),this.scaleKeyframeBuilder=new Si(r,e,"multiplicative"),this.opacityKeyframeBuilder=new Si(n,e,"multiplicative",{min:0,max:1}),this.rotationKeyframeBuilder=new Si(o,e,"additive"),this.skewXKeyframeBuilder=new Si(l,e,"additive"),this.skewYKeyframeBuilder=new Si(c,e,"additive"),this.clipHasKeyframes()){Array.isArray(t.scale)&&this.scaleKeyframeBuilder.addLayer(t.scale),Array.isArray(t.opacity)&&this.opacityKeyframeBuilder.addLayer(t.opacity),Array.isArray(t.offset?.x)&&this.offsetXKeyframeBuilder.addLayer(t.offset.x),Array.isArray(t.offset?.y)&&this.offsetYKeyframeBuilder.addLayer(t.offset.y),Array.isArray(t.transform?.rotate?.angle)&&this.rotationKeyframeBuilder.addLayer(t.transform.rotate.angle),Array.isArray(t.transform?.skew?.x)&&this.skewXKeyframeBuilder.addLayer(t.transform.skew.x),Array.isArray(t.transform?.skew?.y)&&this.skewYKeyframeBuilder.addLayer(t.transform.skew.y);return}const d={...t,start:this.getStart(),length:e},u=new pg(d).buildRelative(this.edit.size,this.getSize()),f=new gg(d).buildRelative();this.offsetXKeyframeBuilder.addLayer(u.offsetXKeyframes),this.offsetYKeyframeBuilder.addLayer(u.offsetYKeyframes),this.scaleKeyframeBuilder.addLayer(u.scaleKeyframes),this.opacityKeyframeBuilder.addLayer(u.opacityKeyframes),this.rotationKeyframeBuilder.addLayer(u.rotationKeyframes),this.offsetXKeyframeBuilder.addLayer(f.in.offsetXKeyframes),this.offsetYKeyframeBuilder.addLayer(f.in.offsetYKeyframes),this.scaleKeyframeBuilder.addLayer(f.in.scaleKeyframes),this.opacityKeyframeBuilder.addLayer(f.in.opacityKeyframes),this.rotationKeyframeBuilder.addLayer(f.in.rotationKeyframes),this.offsetXKeyframeBuilder.addLayer(f.out.offsetXKeyframes),this.offsetYKeyframeBuilder.addLayer(f.out.offsetYKeyframes),this.scaleKeyframeBuilder.addLayer(f.out.scaleKeyframes),this.opacityKeyframeBuilder.addLayer(f.out.opacityKeyframes),this.rotationKeyframeBuilder.addLayer(f.out.rotationKeyframes);const p=[...f.in.maskXKeyframes,...f.out.maskXKeyframes];p.length&&(this.maskXKeyframeBuilder=new Da(p,e))}async load(){this.contentContainer?.destroyed&&(this.contentContainer=new G.Container,this.getContainer().addChild(this.contentContainer)),this.getContainer().sortableChildren=!0,this.getContainer().cursor="pointer",this.getContainer().eventMode="static",this.getContainer().on?.("pointerdown",this.onPointerDown.bind(this))}update(e,t){if(this.getContainer().visible=this.isActive(),this.getContainer().zIndex=1e5-this.layer*100,!this.isActive())return;const i=this.getPivot(),a=this.getPosition(),r=this.getContainerScale();this.getContainer().scale.set(r.x,r.y),this.getContainer().pivot.set(i.x,i.y),this.getContainer().position.set(a.x+i.x,a.y+i.y);const n=this.getRotation();this.contentContainer.alpha=this.getOpacity(),this.getContainer().angle=n;const o=this.getSkew();this.getContainer().skew?.set(o.x*(Math.PI/180),o.y*(Math.PI/180)),this.clipConfiguration.width&&this.clipConfiguration.height&&this.applyFixedDimensions(),this.updateWipeMask(),this.shouldDiscardFrame()&&(this.contentContainer.alpha=0)}updateWipeMask(){if(!this.maskXKeyframeBuilder){this.wipeMask&&(this.getContainer().mask=null,this.wipeMask.destroy(),this.wipeMask=null);return}const e=this.maskXKeyframeBuilder.getValue(this.getPlaybackTime()),t=this.getSize();this.wipeMask||(this.wipeMask=new G.Graphics,this.getContainer().addChild(this.wipeMask),this.getContainer().mask=this.wipeMask),this.wipeMask.clear(),this.wipeMask.rect(0,0,t.width*e,t.height),this.wipeMask.fill(16777215)}dispose(){this.wipeMask?.destroy(),this.wipeMask=null,this.contentContainer?.destroy()}getStart(){return this.resolvedTiming.start}getLength(){return this.resolvedTiming.length}getEnd(){return this.resolvedTiming.start+this.resolvedTiming.length}getTimingIntent(){if(this.clipId){const e=this.edit.getDocumentClipById(this.clipId);if(e){let t;e.start==="auto"?t="auto":(hs(e.start),t=e.start);let i;return e.length==="auto"||e.length==="end"||hs(e.length),i=e.length,{start:t,length:i}}}return{start:this.clipConfiguration.start,length:this.clipConfiguration.length}}getResolvedTiming(){return{...this.resolvedTiming}}setResolvedTiming(e){this.resolvedTiming={...e},this.clipConfiguration.start=e.start,this.clipConfiguration.length=e.length}getExportableClip(){const e=structuredClone(this.clipConfiguration),t=this.getTimingIntent();return e.start=t.start,e.length=t.length,e}getPlaybackTime(){const e=this.edit.playbackTime-this.getStart();return e<0?0:e>this.getLength()?this.getLength():e}getContentSize(){return this.getSize()}getContentContainer(){return this.contentContainer}getOpacity(){return this.opacityKeyframeBuilder?.getValue(this.getPlaybackTime())??1}getPosition(){const e={x:this.offsetXKeyframeBuilder?.getValue(this.getPlaybackTime())??0,y:this.offsetYKeyframeBuilder?.getValue(this.getPlaybackTime())??0};return this.positionBuilder.relativeToAbsolute(this.getSize(),this.clipConfiguration.position??"center",e)}getPivot(){const e=this.getSize();return{x:e.width/2,y:e.height/2}}calculateMoveOffset(e,t){const i=this.getPosition(),a={x:i.x+e,y:i.y+t},r=this.positionBuilder.absoluteToRelative(this.getSize(),this.clipConfiguration.position??"center",a);return{x:r.x,y:r.y}}getFitScale(){const e={width:this.clipConfiguration.width??this.edit.size.width,height:this.clipConfiguration.height??this.edit.size.height},t=this.getContentSize(),i=this.clipConfiguration.fit??"crop";return mg(t,e,i)}getScale(){return(this.scaleKeyframeBuilder?.getValue(this.getPlaybackTime())??1)*this.getFitScale()}getContainerScale(){const e=this.scaleKeyframeBuilder?.getValue(this.getPlaybackTime())??1,t=this.getContentSize(),i=this.clipConfiguration.fit??"crop",a=!!(this.clipConfiguration.width&&this.clipConfiguration.height);return yg(t,this.edit.size,i,e,a)}getRotation(){return this.rotationKeyframeBuilder?.getValue(this.getPlaybackTime())??0}getSkew(){return{x:this.skewXKeyframeBuilder?.getValue(this.getPlaybackTime())??0,y:this.skewYKeyframeBuilder?.getValue(this.getPlaybackTime())??0}}isActive(){return this.edit.playbackTime>=this.getStart()&&this.edit.playbackTime<this.getEnd()}shouldDiscardFrame(){return this.getPlaybackTime()<Lt.DiscardedFrameCount}onPointerDown(e){e.button===ud.ButtonLeftClick&&this.edit.getInternalEvents().emit(Be.CanvasClipClicked,{player:this})}clipHasKeyframes(){return[this.clipConfiguration.scale,this.clipConfiguration.opacity,this.clipConfiguration.offset?.x,this.clipConfiguration.offset?.y,this.clipConfiguration.transform?.rotate?.angle,this.clipConfiguration.transform?.skew?.x,this.clipConfiguration.transform?.skew?.y].some(e=>e&&typeof e!="number")}applyFixedDimensions(){const e=this.clipConfiguration.width,t=this.clipConfiguration.height;if(!e||!t)return;const i=this.contentContainer.children.find(p=>p instanceof G.Sprite);if(!i?.texture)return;const a=i.texture.width,r=i.texture.height,n=this.clipConfiguration.fit||"crop",o=this.contentContainer.mask;let l=null;if(o instanceof G.Graphics?l=o:o||(l=new G.Graphics,this.contentContainer.addChild(l),this.contentContainer.mask=l),l){const{asset:p}=this.clipConfiguration,g=p&&"border"in p&&p.border&&typeof p.border=="object"?p.border.width??0:0,w=g/2;l.clear(),l.rect(-w,-w,e+g,t+g),l.fill(16777215)}const c=this.scaleKeyframeBuilder?.getValue(this.getPlaybackTime())??1;i.anchor.set(.5,.5);const f=bg({width:a,height:r},{width:e,height:t},n);i.scale.set(f.scaleX,f.scaleY),i.position.set(f.positionX,f.positionY),this.contentContainer.scale.set(c,c),this.contentContainer.position.set(e/2*(1-c),t/2*(1-c))}applyAnchorPositioning(e,t,i,a){const r=a.width,n=a.height;if(!!a.mask){a.position.set(0,0);return}const l=(e??"center").toLowerCase();let c=0,d=0;l.includes("left")||l==="left"?c=0:l.includes("right")||l==="right"?c=t-r:c=(t-r)/2,l.includes("top")||l==="top"?d=0:l.includes("bottom")||l==="bottom"?d=i-n:d=(i-n)/2,a.position.set(c,d)}supportsEdgeResize(){return!1}onDimensionsChanged(){}notifyDimensionsChanged(){this.onDimensionsChanged()}}class za{static Name="AudioLoadParser";id;name;extension;validAudioExtensions;constructor(){this.id=za.Name,this.name=za.Name,this.extension={type:[G.ExtensionType.LoadParser],priority:G.LoaderParserPriority.Normal,ref:null},this.validAudioExtensions=["mp3","mpeg","ogg","wav"]}test(e){const t=e.split("?")[0]?.split(".").pop()??"";return this.validAudioExtensions.includes(t)}async load(e,t,i){return new Promise(a=>{const r={src:e},n=new Howl(r);n.on("load",()=>a(n)),n.on("loaderror",()=>a(null))})}unload(e){e?.unload()}}class vg extends Lt{audioResource;isPlaying;volumeKeyframeBuilder;syncTimer;constructor(e,t){super(e,t,it.Audio),this.audioResource=null,this.isPlaying=!1,this.syncTimer=0}async load(){await super.load();const e=this.clipConfiguration.asset,t=e.src,i={src:t,parser:za.Name},a=await this.edit.assetLoader.load(t,i);if(!(a instanceof ug.Howl))throw new Error(`Invalid audio source '${e.src}'.`);this.audioResource=a;const n=typeof e.volume=="number"?e.volume:1;this.volumeKeyframeBuilder=new Da(this.createVolumeKeyframes(e,n),this.getLength(),n),this.configureKeyframes()}update(e,t){super.update(e,t);const{trim:i=0}=this.clipConfiguration.asset;if(this.syncTimer+=t,this.getContainer().alpha=0,!this.audioResource)return;const a=this.edit.isPlaying&&this.isActive(),r=this.getPlaybackTime();a&&(this.isPlaying||(this.isPlaying=!0,this.audioResource.seek(r+i),this.audioResource.play()),this.audioResource.volume()!==this.getVolume()&&this.audioResource.volume(this.getVolume()),Math.abs(this.audioResource.seek()-i-r)>.1&&(this.audioResource.seek(r+i),this.edit.recordSyncCorrection())),this.isPlaying&&!a&&(this.isPlaying=!1,this.audioResource.pause());const n=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&n&&(this.syncTimer=0,this.audioResource.seek(r+i))}dispose(){this.audioResource?.unload(),this.audioResource=null}reconfigureAfterRestore(){super.reconfigureAfterRestore();const e=this.clipConfiguration.asset,t=typeof e.volume=="number"?e.volume:1;this.volumeKeyframeBuilder=new Da(this.createVolumeKeyframes(e,t),this.getLength(),t)}getSize(){return{width:0,height:0}}getVolume(){return this.volumeKeyframeBuilder.getValue(this.getPlaybackTime())}getCurrentDrift(){if(!this.audioResource)return 0;const{trim:e=0}=this.clipConfiguration.asset,t=this.audioResource.seek(),i=this.getPlaybackTime();return Math.abs(t-e-i)}createVolumeKeyframes(e,t){const{effect:i,volume:a}=e;if(!i||i==="none"||Array.isArray(a))return a??1;const r=this.getLength()/1e3,n=Math.min(2,r/2);return i==="fadeIn"?[{from:0,to:t,start:0,length:n}]:i==="fadeOut"?[{from:t,to:0,start:r-n,length:n}]:[{from:0,to:t,start:0,length:n},{from:t,to:0,start:r-n,length:n}]}}function Dr(s){const e=s.trim().replace(",","."),t=e.split(":");if(t.length===3){const i=parseInt(t[0],10),a=parseInt(t[1],10),r=parseFloat(t[2]);return i*3600+a*60+r}if(t.length===2){const i=parseInt(t[0],10),a=parseFloat(t[1]);return i*60+a}return parseFloat(e)||0}function xg(s){const e=[],t=s.split(/\r?\n/);let i=0;for(;i<t.length&&!t[i].includes("-->");)i+=1;for(;i<t.length;){const a=t[i].trim();if(a.includes("-->")){const[r,n]=a.split("-->").map(d=>d.trim().split(" ")[0]),o=Dr(r),l=Dr(n),c=[];for(i+=1;i<t.length&&t[i].trim()!==""&&!t[i].includes("-->");){const d=t[i].trim();d.startsWith("NOTE")||c.push(d),i+=1}c.length>0&&e.push({start:o,end:l,text:c.join(`
|
|
2
2
|
`)})}else i+=1}return e}function Cg(s){const e=[],t=s.split(/\r?\n/);let i=0;for(;i<t.length;){const a=t[i].trim();if(/^\d+$/.test(a)||a==="")i+=1;else if(a.includes("-->")){const[r,n]=a.split("-->").map(d=>d.trim()),o=Dr(r),l=Dr(n),c=[];for(i+=1;i<t.length&&t[i].trim()!=="";)c.push(t[i].trim()),i+=1;c.length>0&&e.push({start:o,end:l,text:c.join(`
|
|
3
3
|
`)})}else i+=1}return e}function kg(s){return s.trim().startsWith("WEBVTT")?xg(s):Cg(s)}function Sg(s,e){return s.find(t=>e>=t.start&&e<=t.end)??null}const Ag=`
|
|
4
4
|
let transcriber = null;
|
|
@@ -274,7 +274,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
|
|
|
274
274
|
`){f.push({glyphs:p,width:g,y:0}),p=[],g=0,C=k;continue}if(g+T>r&&p.length>0){if(C>-1){const b=C-(k-p.length)+1,R=p.splice(b),M=p.reduce((L,Q)=>L+Q.xAdvance,0);f.push({glyphs:p,width:M,y:0}),p=R,g=R.reduce((L,Q)=>L+Q.xAdvance,0)}else f.push({glyphs:p,width:g,y:0}),p=[],g=0;C=-1}p.push(x),g+=T,w.has(x.cluster)&&(C=k)}p.length>0&&f.push({glyphs:p,width:g,y:0});const v=s.lineHeight*i;for(let k=0;k<f.length;k++)f[k].y=(k+1)*v;return f}catch(e){throw e instanceof Error?e:new Error(`Layout failed: ${String(e)}`)}}};function EA(s,e){return s.type==="linear"?{kind:"linear",angle:s.angle,stops:s.stops,opacity:e}:{kind:"radial",stops:s.stops,opacity:e}}function NA(s,e){const t=Math.max(1,Math.round(e.fontSize*.05));let i=e.baselineY+Math.round(e.fontSize*.1);return s==="line-through"&&(i=e.baselineY-Math.round(e.fontSize*.3)),{x1:e.xStart,x2:e.xStart+e.lineWidth,y:i,width:t}}function PA(s){return s==null?{top:0,right:0,bottom:0,left:0}:typeof s=="number"?{top:s,right:s,bottom:s,left:s}:s}async function FA(s){const e=[],t=PA(s.padding),i=s.border?.width??0;if(e.push({op:"BeginFrame",width:s.canvas.width,height:s.canvas.height,pixelRatio:s.canvas.pixelRatio,clear:!0,bg:void 0}),s.lines.length===0)return e;const a=Math.max(1,await s.getUnitsPerEm()),r=s.font.size/a,n=s.lines.length,o=s.font.size*s.style.lineHeight;let l;switch(s.align.vertical){case"top":l=s.font.size;break;case"bottom":l=s.textRect.height-(n-1)*o;break;case"middle":default:const k=s.font.size*.35;l=(s.textRect.height-(n-1)*o)/2+k;break}l+=i+t.top;const c=s.style.gradient?EA(s.style.gradient,1):{kind:"solid",color:s.font.color,opacity:s.font.opacity},d=s.style.gradient?s.style.gradient.stops[s.style.gradient.stops.length-1]?.color??s.font.color:s.font.color,u=[],f=[];let p=1/0,g=1/0,w=-1/0,C=-1/0;for(const v of s.lines){let k;switch(s.align.horizontal){case"left":k=0;break;case"right":k=s.textRect.width-v.width;break;case"center":default:k=(s.textRect.width-v.width)/2;break}k+=i+t.left;let x=k;const T=s.lines.indexOf(v),b=l+T*o;if(s.font.background){const R=s.font.size*.15,M=s.font.size*.12,L=s.font.size*.92+M*2,Q=b-s.font.size*.78-M;f.push({op:"Rectangle",x:k-R,y:Q,width:v.width+R*2,height:L,fill:{kind:"solid",color:s.font.background,opacity:1}})}for(const R of v.glyphs){const M=x+R.xOffset,L=b+R.yOffset,Q=R.fontDesc?.family;if((R.isColorEmoji||Q&&s.isColorEmojiFont&&s.isColorEmojiFont(Q))&&R.char){u.push({op:"DrawColorEmoji",char:R.char,x:M,y:L,fontSize:s.font.size,fontFamily:Q||"NotoColorEmoji"}),x+=R.xAdvance;continue}const q=await s.glyphPathProvider(R.id,R.fontDesc);if(!q||q==="M 0 0"){x+=R.xAdvance;continue}const ce=_A(q),re=M+r*ce.x,xe=M+r*(ce.x+ce.w),pe=L-r*(ce.y+ce.h),Se=L-r*ce.y;re<p&&(p=re),pe<g&&(g=pe),xe>w&&(w=xe),Se>C&&(C=Se),s.shadow&&s.shadow.blur>0&&u.push({isShadow:!0,op:"FillPath",path:q,x:M+s.shadow.offsetX,y:L+s.shadow.offsetY,scale:r,fill:{kind:"solid",color:s.shadow.color,opacity:s.shadow.opacity}}),s.stroke&&s.stroke.width>0&&u.push({op:"StrokePath",path:q,x:M,y:L,scale:r,width:s.stroke.width,color:s.stroke.color,opacity:s.stroke.opacity}),u.push({op:"FillPath",path:q,x:M,y:L,scale:r,fill:c}),x+=R.xAdvance}if(s.style.textDecoration!=="none"){const R=NA(s.style.textDecoration,{baselineY:b,fontSize:s.font.size,lineWidth:v.width,xStart:k});u.push({op:"DecorationLine",from:{x:R.x1,y:R.y},to:{x:R.x2,y:R.y},width:R.width,color:d,opacity:s.font.opacity})}}if(p!==1/0){const v={x:p,y:g,w:Math.max(1,w-p),h:Math.max(1,C-g)};for(const k of u)k.op==="FillPath"&&!k.isShadow&&(k.gradientBBox=v)}if(s.background||s.border){const v=s.contentRect?.width??s.canvas.width,k=s.contentRect?.height??s.canvas.height,x=s.border?.width??0,T=s.border?.radius??0,b=x/2,R=s.canvas.width/2,M=s.canvas.height/2,L=R-v/2,Q=M-k/2,K=Math.min(v-x,k-x)/2,q=Math.min(T,K),ce=Math.max(0,q-b);s.background?.color&&e.push({op:"Rectangle",x:L+x,y:Q+x,width:v-x*2,height:k-x*2,fill:{kind:"solid",color:s.background.color,opacity:s.background.opacity},borderRadius:ce}),s.border&&s.border.width>0&&e.push({op:"RectangleStroke",x:L+b,y:Q+b,width:v-x,height:k-x,stroke:{width:s.border.width,color:s.border.color,opacity:s.border.opacity},borderRadius:q})}return e.push(...f),e.push(...u),e}function VA(s){return s.match(/[MLCQZ]|-?\d*\.?\d+(?:e[-+]?\d+)?/gi)??[]}function _A(s){const e=VA(s);let t=0,i=1/0,a=1/0,r=-1/0,n=-1/0;const o=(l,c)=>{l<i&&(i=l),c<a&&(a=c),l>r&&(r=l),c>n&&(n=c)};for(;t<e.length;)switch(e[t++]){case"M":case"L":{const c=parseFloat(e[t++]),d=parseFloat(e[t++]);o(c,d);break}case"C":{const c=parseFloat(e[t++]),d=parseFloat(e[t++]),u=parseFloat(e[t++]),f=parseFloat(e[t++]),p=parseFloat(e[t++]),g=parseFloat(e[t++]);o(c,d),o(u,f),o(p,g);break}case"Q":{const c=parseFloat(e[t++]),d=parseFloat(e[t++]),u=parseFloat(e[t++]),f=parseFloat(e[t++]);o(c,d),o(u,f);break}}return i===1/0?{x:0,y:0,w:0,h:0}:{x:i,y:a,w:r-i,h:n-a}}var ec=.999;function MA(s,e,t){if(!t.anim||!t.anim.preset)return s;const{preset:i}=t.anim,a=e.reduce((l,c)=>l+c.glyphs.length,0);let r=Math.max(.3,a/(30*t.anim.speed));t.clipDuration&&!t.anim.duration&&(r=Math.min(r,t.clipDuration*.9));const n=t.anim.duration??r,o=Math.max(0,Math.min(1,t.t/n));switch(i){case"typewriter":return BA(s,e,o,t.anim.style,t.fontSize,t.t);case"fadeIn":return DA(s,e,o,t.anim.style,t.fontSize,n);case"slideIn":return zA(s,e,o,t.anim.direction??"left",t.fontSize,t.anim.style,n);case"shift":return RA(s,e,o,t.anim.direction??"left",t.fontSize,t.anim.style,n);case"ascend":return OA(s,e,o,t.anim.direction??"up",t.fontSize,n);case"movingLetters":return UA(s,t.t,t.anim.direction??"up",t.fontSize);default:return s}}var Gn=s=>s.op==="FillPath"&&s.isShadow===!0,qn=s=>s.op==="FillPath"&&!s.isShadow;function LA(s){for(const e of s)if(e.op==="FillPath"){const t=e.fill;if(t?.kind==="solid")return t.color;if((t?.kind==="linear"||t?.kind==="radial")&&Array.isArray(t.stops)&&t.stops.length)return t.stops[t.stops.length-1].color||"#000000"}return"#000000"}function BA(s,e,t,i,a,r,n){if(i==="word"){const l=pr(e),c=l.length,d=Math.floor(t*c);if(d===0)return s.filter(g=>g.op==="BeginFrame"||g.op==="Rectangle"||g.op==="RectangleStroke");let u=0;for(let g=0;g<Math.min(d,l.length);g++)u+=l[g].glyphCount;const f=Kh(s,u),p=t>=ec?f:f.filter(g=>g.op!=="DecorationLine");return t<1&&u>0?Qh(p,u,a):p}else{const l=e.reduce((f,p)=>f+p.glyphs.length,0),c=Math.floor(t*l);if(c===0)return s.filter(f=>f.op==="BeginFrame"||f.op==="Rectangle"||f.op==="RectangleStroke");const d=Kh(s,c),u=t>=ec?d:d.filter(f=>f.op!=="DecorationLine");return t<1&&c>0?Qh(u,c,a):u}}function OA(s,e,t,i,a,r){const n=pr(e),o=n.length;if(o===0)return s;const l=[];let c=0;for(const d of s)if((d.op==="BeginFrame"||d.op==="Rectangle"||d.op==="RectangleStroke")&&l.push(d),d.op==="FillPath"||d.op==="StrokePath")break;for(const d of s)if(d.op==="FillPath"||d.op==="StrokePath"){let u=-1,f=0;for(let p=0;p<n.length;p++){const g=n[p].glyphCount;if(c>=f&&c<f+g){u=p;break}f+=g}if(u>=0){const p=u/Math.max(1,o)*(r/r),g=Math.min(1,p+.3);if(t>=g)l.push(d);else if(t>p){const w=(t-p)/Math.max(1e-6,g-p),C=Yn(Math.min(1,w)),v=i==="up"?a*.4:-a*.4,k={...d,y:d.y+v*(1-C)};d.op==="FillPath"?k.fill.kind==="solid"?k.fill={...k.fill,opacity:k.fill.opacity*C}:k.fill={...k.fill,opacity:(k.fill.opacity??1)*C}:k.opacity=k.opacity*C,l.push(k)}}qn(d)&&c++}else d.op==="DecorationLine"&&t>=ec&&l.push(d);return l}function RA(s,e,t,i,a,r,n){const o=r==="word",c={left:{x:a*.6,y:0},right:{x:-a*.6,y:0},up:{x:0,y:a*.6},down:{x:0,y:-a*.6}}[i],d=o?pr(e):[],u=e.reduce((x,T)=>x+T.glyphs.length,0),f=o?d.length:u;if(f===0)return s;const p=[];for(const x of s)if((x.op==="BeginFrame"||x.op==="Rectangle"||x.op==="RectangleStroke")&&p.push(x),x.op==="FillPath"||x.op==="StrokePath")break;const g=.3,C=n*.7/Math.max(1,f-1),v=x=>{const T=x*C,b=T/n,R=Math.min(1,(T+g)/n);return{startF:b,endF:R}};let k=0;for(const x of s){if(x.op!=="FillPath"&&x.op!=="StrokePath"){x.op==="DecorationLine"&&t>.8&&p.push(x);continue}let T;if(!o)T=k;else{let M=-1,L=0;for(let Q=0;Q<d.length;Q++){const K=d[Q].glyphCount;if(k>=L&&k<L+K){M=Q;break}L+=K}T=Math.max(0,M)}const{startF:b,endF:R}=v(T);if(t<=b){const M={...x,x:x.x+c.x,y:x.y+c.y};x.op==="FillPath"?M.fill.kind==="solid"?M.fill={...M.fill,opacity:0}:M.fill={...M.fill,opacity:0}:M.opacity=0,p.push(M)}else if(t>=R)p.push(x);else{const M=(t-b)/Math.max(1e-6,R-b),L=Yn(Math.min(1,M)),Q=c.x*(1-L),K=c.y*(1-L),q={...x,x:x.x+Q,y:x.y+K};if(x.op==="FillPath"){const ce=q.fill.kind==="solid"?q.fill.opacity:q.fill.opacity??1;q.fill.kind==="solid"?q.fill={...q.fill,opacity:ce*L}:q.fill={...q.fill,opacity:ce*L}}else q.opacity=q.opacity*L;p.push(q)}qn(x)&&k++}return p}function DA(s,e,t,i,a,r){const n=i==="word";if(!n&&!(i==="character")){const v=tc(t),k=.95+.05*v;return WA(s,v,k)}const l=n?pr(e):[],c=e.reduce((v,k)=>v+k.glyphs.length,0),d=n?l.length:c;if(d===0)return s;const u=[];for(const v of s)if(v.op==="BeginFrame"){u.push(v);break}const f=.3,g=r*.7/Math.max(1,d-1),w=v=>{const k=v*g,x=k/r,T=Math.min(1,(k+f)/r);return{startF:x,endF:T}};let C=0;for(const v of s){if(v.op!=="FillPath"&&v.op!=="StrokePath"){v.op==="DecorationLine"&&t>.8&&u.push(v);continue}let k;if(!n)k=C;else{let b=-1,R=0;for(let M=0;M<l.length;M++){const L=l[M].glyphCount;if(C>=R&&C<R+L){b=M;break}R+=L}k=Math.max(0,b)}const{startF:x,endF:T}=w(k);if(t<=x){const b={...v};v.op==="FillPath"?b.fill.kind==="solid"?b.fill={...b.fill,opacity:0}:b.fill={...b.fill,opacity:0}:b.opacity=0,u.push(b)}else if(t>=T)u.push(v);else{const b=(t-x)/Math.max(1e-6,T-x),R=tc(Math.min(1,b)),M={...v};if(v.op==="FillPath"){const L=M.fill.kind==="solid"?M.fill.opacity:M.fill.opacity??1;M.fill.kind==="solid"?M.fill={...M.fill,opacity:L*R}:M.fill={...M.fill,opacity:L*R}}else M.opacity=M.opacity*R;u.push(M)}qn(v)&&C++}return u}function zA(s,e,t,i,a,r,n){const o=r==="word";if(!o&&!(r==="character")){const T=Yn(t),b=qA(1-T,i,a*2),R=tc(t);return HA(s,b.dx,b.dy,R)}const d={left:{x:a*2,y:0},right:{x:-a*2,y:0},up:{x:0,y:a*2},down:{x:0,y:-a*2}}[i],u=o?pr(e):[],f=e.reduce((T,b)=>T+b.glyphs.length,0),p=o?u.length:f;if(p===0)return s;const g=[];for(const T of s)if(T.op==="BeginFrame"){g.push(T);break}const w=.3,v=n*.7/Math.max(1,p-1),k=T=>{const b=T*v,R=b/n,M=Math.min(1,(b+w)/n);return{startF:R,endF:M}};let x=0;for(const T of s){if(T.op!=="FillPath"&&T.op!=="StrokePath"){T.op==="DecorationLine"&&t>.8&&g.push(T);continue}let b;if(!o)b=x;else{let L=-1,Q=0;for(let K=0;K<u.length;K++){const q=u[K].glyphCount;if(x>=Q&&x<Q+q){L=K;break}Q+=q}b=Math.max(0,L)}const{startF:R,endF:M}=k(b);if(t<=R){const L={...T,x:T.x+d.x,y:T.y+d.y};T.op==="FillPath"?L.fill.kind==="solid"?L.fill={...L.fill,opacity:0}:L.fill={...L.fill,opacity:0}:L.opacity=0,g.push(L)}else if(t>=M)g.push(T);else{const L=(t-R)/Math.max(1e-6,M-R),Q=Yn(Math.min(1,L)),K=d.x*(1-Q),q=d.y*(1-Q),ce={...T,x:T.x+K,y:T.y+q};if(T.op==="FillPath"){const re=ce.fill.kind==="solid"?ce.fill.opacity:ce.fill.opacity??1;ce.fill.kind==="solid"?ce.fill={...ce.fill,opacity:re*Q}:ce.fill={...ce.fill,opacity:re*Q}}else ce.opacity=ce.opacity*Q;g.push(ce)}qn(T)&&x++}return g}function UA(s,e,t,i){const a=i*.3;return GA(s,t,a,e)}function pr(s){const e=[];let t=0;for(let i=0;i<s.length;i++){const a=s[i],r=ZA(a);for(const n of r)n.length>0&&e.push({startGlyph:t,glyphCount:n.length,lineIndex:i}),t+=n.length}return e}function ZA(s){const e=[];let t=[];for(const i of s.glyphs)i.char===" "||i.char===" "||i.char===`
|
|
275
275
|
`?t.length&&(e.push([...t]),t=[]):t.push(i);return t.length&&e.push(t),e}function Kh(s,e){const t=[];let i=0,a=!1;for(const r of s){if(r.op==="BeginFrame"||r.op==="Rectangle"||r.op==="RectangleStroke"){t.push(r);continue}if(r.op==="FillPath"&&!Gn(r)){i<e&&(t.push(r),a=!0),i++;continue}if(r.op==="StrokePath"){i<e&&t.push(r);continue}if(r.op==="FillPath"&&Gn(r)){i<e&&t.push(r);continue}if(r.op==="DecorationLine"&&a){t.push(r);continue}}return t}function Qh(s,e,t,i){if(e===0)return s;let a=null,r=0;for(const n of s)if(n.op==="FillPath"&&!Gn(n)&&(r++,r===e)){a=n;break}if(a&&a.op==="FillPath"){const n=LA(s),o=a.x+t*.5,l=a.y,c=Math.max(3,t/15),d={op:"DecorationLine",from:{x:o,y:l-t*.75},to:{x:o,y:l+t*.15},width:c,color:n,opacity:1};return[...s,d]}return s}function WA(s,e,t){let i=0,a=0,r=0;return s.forEach(n=>{n.op==="FillPath"&&(i+=n.x,a+=n.y,r++)}),r>0&&(i/=r,a/=r),s.map(n=>{if(n.op==="FillPath"){const o={...n};if(o.fill.kind==="solid"?o.fill={...o.fill,opacity:o.fill.opacity*e}:o.fill={...o.fill,opacity:(o.fill.opacity??1)*e},t!==1&&r>0){const l=n.x-i,c=n.y-a;o.x=i+l*t,o.y=a+c*t}return o}if(n.op==="StrokePath"){const o={...n,opacity:n.opacity*e};if(t!==1&&r>0){const l=n.x-i,c=n.y-a;o.x=i+l*t,o.y=a+c*t}return o}return n.op==="DecorationLine"?{...n,opacity:n.opacity*e}:n})}function HA(s,e,t,i=1){return s.map(a=>{if(a.op==="FillPath"){const r={...a,x:a.x+e,y:a.y+t};return i<1&&(r.fill.kind==="solid"?r.fill={...r.fill,opacity:r.fill.opacity*i}:r.fill={...r.fill,opacity:(r.fill.opacity??1)*i}),r}return a.op==="StrokePath"?{...a,x:a.x+e,y:a.y+t,opacity:a.opacity*i}:a.op==="DecorationLine"?{...a,from:{x:a.from.x+e,y:a.from.y+t},to:{x:a.to.x+e,y:a.to.y+t},opacity:a.opacity*i}:a})}function GA(s,e,t,i){let a=0;const n=Math.min(1,i/.5);return s.map(o=>{if(o.op==="FillPath"||o.op==="StrokePath"){const l=Math.sin(a/5*Math.PI+i*Math.PI*2),c=e==="left"||e==="right"?l*t*(e==="left"?-1:1):0,d=e==="up"||e==="down"?l*t*(e==="up"?-1:1):0;if(o.op==="FillPath"){Gn(o)||a++;const u={...o,x:o.x+c,y:o.y+d};return u.fill.kind==="solid"?u.fill={...u.fill,opacity:u.fill.opacity*n}:u.fill={...u.fill,opacity:(u.fill.opacity??1)*n},u}return{...o,x:o.x+c,y:o.y+d,opacity:o.opacity*n}}return o})}function qA(s,e,t){const i=s*t;switch(e){case"left":return{dx:-i,dy:0};case"right":return{dx:i,dy:0};case"up":return{dx:0,dy:-i};case"down":return{dx:0,dy:i}}}function tc(s){return s*(2-s)}function Yn(s){return 1-Math.pow(1-s,3)}function Di(s,e=1){const t=/^#?([a-f0-9]{6})$/i.exec(s);if(!t)throw new Error(`Invalid color ${s}`);const i=parseInt(t[1],16),a=i>>16&255,r=i>>8&255,n=i&255;return{r:a,g:r,b:n,a:e}}function YA(s){const e=s.getContext("2d");if(!e)throw new Error("2D context unavailable");return{async render(t){const i=jA(t),a=new Map;for(const r of t){if(r.op==="BeginFrame"){r.pixelRatio;const n=r.width,o=r.height;if("width"in s&&"height"in s&&(s.width=Math.floor(n),s.height=Math.floor(o)),"style"in s&&(s.style.width=`${n}px`,s.style.height=`${o}px`),e.setTransform(1,0,0,1,0,0),r.clear&&e.clearRect(0,0,n,o),r.bg&&r.bg.color){const{color:l,opacity:c,radius:d}=r.bg;if(l){const u=Di(l,c);d&&d>0?(e.fillStyle=`rgba(${u.r},${u.g},${u.b},${u.a})`,Jh(e,0,0,n,o,d),e.fill()):(e.fillStyle=`rgba(${u.r},${u.g},${u.b},${u.a})`,e.fillRect(0,0,n,o))}}continue}if(r.op==="FillPath"){const n=r,o=new Path2D(n.path);e.save(),e.translate(n.x,n.y);const l=n.scale??1;e.scale(l,-l);const c=n.gradientBBox??i,d={x:(c.x-n.x)/l,y:-(c.y-n.y)/l,w:c.w/l,h:c.h/l},u=JSON.stringify({fill:n.fill,bbox:d});let f=a.get(u);f||(f=gr(e,n.fill,d),a.set(u,f)),e.fillStyle=f,e.fill(o),e.restore();continue}if(r.op==="StrokePath"){const n=r,o=new Path2D(n.path);e.save(),e.translate(n.x,n.y);const l=n.scale??1;e.scale(l,-l);const c=1/Math.abs(l),d=Di(n.color,n.opacity);e.strokeStyle=`rgba(${d.r},${d.g},${d.b},${d.a})`,e.lineWidth=n.width*c,e.lineJoin="round",e.lineCap="round",e.stroke(o),e.restore();continue}if(r.op==="DecorationLine"){e.save();const n=Di(r.color,r.opacity);e.strokeStyle=`rgba(${n.r},${n.g},${n.b},${n.a})`,e.lineWidth=r.width,e.beginPath(),e.moveTo(r.from.x,r.from.y),e.lineTo(r.to.x,r.to.y),e.stroke(),e.restore();continue}if(r.op==="Rectangle"){e.save();const n=gr(e,r.fill,{x:r.x,y:r.y,w:r.width,h:r.height});e.fillStyle=n,r.borderRadius&&r.borderRadius>0?Jh(e,r.x,r.y,r.width,r.height,r.borderRadius):e.fillRect(r.x,r.y,r.width,r.height),e.restore();continue}if(r.op==="RectangleStroke"){e.save();const n=Di(r.stroke.color,r.stroke.opacity);if(e.strokeStyle=`rgba(${n.r},${n.g},${n.b},${n.a})`,e.lineWidth=r.stroke.width,r.borderRadius&&r.borderRadius>0){const o=new Path2D,l=r.x,c=r.y,d=r.width,u=r.height,f=Math.min(d,u)/2,p=Math.min(r.borderRadius,f);o.moveTo(l+p,c),o.arcTo(l+d,c,l+d,c+u,p),o.arcTo(l+d,c+u,l,c+u,p),o.arcTo(l,c+u,l,c,p),o.arcTo(l,c,l+d,c,p),o.closePath(),e.stroke(o)}else e.strokeRect(r.x,r.y,r.width,r.height);e.restore();continue}if(r.op==="DrawColorEmoji"){e.save(),e.font=`${r.fontSize}px "${r.fontFamily}"`,e.textBaseline="alphabetic",e.fillText(r.char,r.x,r.y),e.restore();continue}if(r.op==="Ellipse"){e.save();const n=r.gradientBBox??{x:r.cx-r.rx,y:r.cy-r.ry,w:r.rx*2,h:r.ry*2},o=gr(e,r.fill,n);e.fillStyle=o,e.beginPath();const l=(r.rotation??0)*Math.PI/180;e.ellipse(r.cx,r.cy,r.rx,r.ry,l,0,Math.PI*2),e.fill(),e.restore();continue}if(r.op==="EllipseStroke"){e.save(),sc(e,r.stroke),e.beginPath();const n=(r.rotation??0)*Math.PI/180;e.ellipse(r.cx,r.cy,r.rx,r.ry,n,0,Math.PI*2),e.stroke(),e.restore();continue}if(r.op==="Polygon"){e.save();const n=r.gradientBBox??KA(r.points),o=gr(e,r.fill,n);e.fillStyle=o,e.beginPath(),ep(e,r.points,r.closed??!0),e.fill(),e.restore();continue}if(r.op==="PolygonStroke"){e.save(),sc(e,r.stroke),e.beginPath(),ep(e,r.points,r.closed??!0),e.stroke(),e.restore();continue}if(r.op==="ShapePath"){e.save(),e.translate(r.x,r.y);const n=r.gradientBBox??$h(r.path),o=gr(e,r.fill,n);e.fillStyle=o;const l=new Path2D(r.path);e.fill(l),e.restore();continue}if(r.op==="ShapePathStroke"){e.save(),e.translate(r.x,r.y),sc(e,r.stroke);const n=new Path2D(r.path);e.stroke(n),e.restore();continue}}}}}function Jh(s,e,t,i,a,r){const n=Math.min(i,a)/2,o=Math.min(r,n),l=new Path2D;l.moveTo(e+o,t),l.arcTo(e+i,t,e+i,t+a,o),l.arcTo(e+i,t+a,e,t+a,o),l.arcTo(e,t+a,e,t,o),l.arcTo(e,t,e+i,t,o),l.closePath(),s.save(),s.fill(l),s.restore()}function gr(s,e,t){if(e.kind==="solid"){const o=Di(e.color,e.opacity);return`rgba(${o.r},${o.g},${o.b},${o.a})`}const i=t.x+t.w/2,a=t.y+t.h/2,r=Math.max(t.w,t.h)/2,n=o=>{const l=e.kind==="linear"||e.kind==="radial"?e.opacity:1,c=e.kind==="linear"||e.kind==="radial"?e.stops:[];for(const d of c){const u=Di(d.color,l);o.addColorStop(d.offset,`rgba(${u.r},${u.g},${u.b},${u.a})`)}return o};if(e.kind==="linear"){const o=e.angle*Math.PI/180,l=i+Math.cos(o+Math.PI)*r,c=a+Math.sin(o+Math.PI)*r,d=i+Math.cos(o)*r,u=a+Math.sin(o)*r;return n(s.createLinearGradient(l,c,d,u))}else return n(s.createRadialGradient(i,a,0,i,a,r))}function jA(s){let e=1/0,t=1/0,i=-1/0,a=-1/0;for(const r of s){if(r.op!=="FillPath")continue;const n=r;if(n.isShadow)continue;const o=$h(n.path),l=n.scale??1,c=n.x+l*o.x,d=n.x+l*(o.x+o.w),u=n.y-l*(o.y+o.h),f=n.y-l*o.y;c<e&&(e=c),u<t&&(t=u),d>i&&(i=d),f>a&&(a=f)}return e===1/0?{x:0,y:0,w:1,h:1}:{x:e,y:t,w:Math.max(1,i-e),h:Math.max(1,a-t)}}function $h(s){const e=XA(s);let t=0,i=1/0,a=1/0,r=-1/0,n=-1/0;const o=(l,c)=>{l<i&&(i=l),c<a&&(a=c),l>r&&(r=l),c>n&&(n=c)};for(;t<e.length;)switch(e[t++]){case"M":case"L":{const c=parseFloat(e[t++]),d=parseFloat(e[t++]);o(c,d);break}case"C":{const c=parseFloat(e[t++]),d=parseFloat(e[t++]),u=parseFloat(e[t++]),f=parseFloat(e[t++]),p=parseFloat(e[t++]),g=parseFloat(e[t++]);o(c,d),o(u,f),o(p,g);break}case"Q":{const c=parseFloat(e[t++]),d=parseFloat(e[t++]),u=parseFloat(e[t++]),f=parseFloat(e[t++]);o(c,d),o(u,f);break}}return i===1/0?{x:0,y:0,w:0,h:0}:{x:i,y:a,w:r-i,h:n-a}}function XA(s){return s.match(/[MLCQZ]|-?\d*\.?\d+(?:e[-+]?\d+)?/gi)??[]}function sc(s,e){const t=Di(e.color,e.opacity);s.strokeStyle=`rgba(${t.r},${t.g},${t.b},${t.a})`,s.lineWidth=e.width,s.lineCap=e.lineCap??"butt",s.lineJoin=e.lineJoin??"miter",e.dashArray&&e.dashArray.length>0&&s.setLineDash(e.dashArray)}function KA(s){if(s.length===0)return{x:0,y:0,w:0,h:0};let e=s[0].x,t=s[0].y,i=s[0].x,a=s[0].y;for(let r=1;r<s.length;r++){const n=s[r];n.x<e&&(e=n.x),n.y<t&&(t=n.y),n.x>i&&(i=n.x),n.y>a&&(a=n.y)}return{x:e,y:t,w:i-e,h:a-t}}function ep(s,e,t){if(e.length!==0){s.moveTo(e[0].x,e[0].y);for(let i=1;i<e.length;i++)s.lineTo(e[i].x,e[i].y);t&&s.closePath()}}async function jn(s){try{const e=await fetch(s);if(!e.ok)throw new Error(`Failed to fetch ${s}: ${e.status} ${e.statusText}`);try{return await e.arrayBuffer()}catch(t){throw new Error(`Failed to read response body as ArrayBuffer from ${s}: ${t instanceof Error?t.message:String(t)}`)}}catch(e){throw e instanceof Error?e.message.includes("Failed to fetch")||e.message.includes("Failed to read")?e:new Error(`Failed to fetch ${s}: ${e.message}`):new Error(`Failed to fetch ${s}: ${String(e)}`)}}function qt(s,e){return s===void 0?e:typeof s=="string"?parseFloat(s):s}var zi=null,mr=!1,tp="https://unpkg.com/@resvg/resvg-wasm@2.6.2/index_bg.wasm";async function ic(s){try{const e=await fetch(s);if(e.ok){const t=await e.arrayBuffer(),i=new Uint8Array(t);if(i.length>=4&&i[0]===0&&i[1]===97&&i[2]===115&&i[3]===109)return t;console.error(`Invalid WASM magic number from URL: ${s}`)}else console.error(`Failed to fetch resvg WASM from URL: ${s}, status: ${e.status}`);return}catch(e){console.error(`Error fetching resvg WASM from ${s}:`,e);return}}async function sp(s){try{if(s){const e=s.endsWith(".wasm")?s:s.endsWith("/")?`${s}resvg.wasm`:`${s}/resvg.wasm`,t=await ic(e);if(t)return t}return}catch(e){console.error("Error in loadResvgWasmWeb:",e);return}}async function QA(s){if(zi&&mr)return zi;if(zi=await Promise.resolve().then(()=>sg),!mr){let t=await sp(s);if(t||(t=await ic(tp)),!t)throw new Error("Failed to load resvg WASM from any source");const i=await WebAssembly.compile(t);await zi.initWasm(i),mr=!0}return zi}async function JA(s){if(mr)return;zi=await Promise.resolve().then(()=>sg);let t;if(s instanceof ArrayBuffer?t=s:(t=await sp(s),t||(t=await ic(tp))),!t)throw new Error("Failed to load resvg WASM from any source");const i=await WebAssembly.compile(t);await zi.initWasm(i),mr=!0}async function $A(s,e={}){const{Resvg:t}=await QA(),i={};e.background&&(i.background=e.background),e.fitTo?i.fitTo=e.fitTo:e.width?i.fitTo={mode:"width",value:e.width}:e.height&&(i.fitTo={mode:"height",value:e.height});const a=new t(s,i);try{const r=a.render();try{return{png:r.asPng(),width:r.width,height:r.height}}finally{r.free()}}finally{a.free()}}function eI(s,e,t){if(!s.shape)throw new Error("Shape is required for shape mode");const i=qt(s.width,e),a=qt(s.height,t),r=sI(s.shape),n=hI(r),o=i/2,l=a/2,c=n.x+n.w/2,d=n.y+n.h/2;let u=o-c,f=l-d;s.transform&&(u+=qt(s.transform.x,0),f+=qt(s.transform.y,0));const p=[];if(s.shadow){const w=qt(s.shadow.offsetX,4),C=qt(s.shadow.offsetY,4),v=s.shadow.color??"#000000",k=qt(s.shadow.opacity,.5);p.push(`<path d="${r}" transform="translate(${u+w}, ${f+C})" fill="${v}" fill-opacity="${k}"/>`)}const g=[`d="${r}"`,`transform="translate(${u}, ${f})"`];if(s.fill){const w=`fill-${Date.now()}`,C=tI(s.fill,w);C.defs&&p.unshift(C.defs),g.push(`fill="${C.fill}"`),s.fill.opacity!==void 0&&s.fill.opacity!==1&&g.push(`fill-opacity="${s.fill.opacity}"`)}else g.push('fill="none"');return s.stroke&&s.stroke.width&&qt(s.stroke.width,0)>0&&(g.push(`stroke="${s.stroke.color??"#000000"}"`),g.push(`stroke-width="${s.stroke.width}"`),s.stroke.opacity!==void 0&&s.stroke.opacity!==1&&g.push(`stroke-opacity="${s.stroke.opacity}"`),s.stroke.dashArray&&s.stroke.dashArray.length>0&&g.push(`stroke-dasharray="${s.stroke.dashArray.join(" ")}"`),s.stroke.lineCap&&g.push(`stroke-linecap="${s.stroke.lineCap}"`),s.stroke.lineJoin&&g.push(`stroke-linejoin="${s.stroke.lineJoin}"`)),s.opacity!==void 0&&s.opacity!==1&&g.push(`opacity="${s.opacity}"`),p.push(`<path ${g.join(" ")}/>`),`<svg xmlns="http://www.w3.org/2000/svg" width="${i}" height="${a}" viewBox="0 0 ${i} ${a}">${p.join("")}</svg>`}function tI(s,e,t){if(s.type==="solid")return{fill:s.color};if(s.type==="linear"){const a=qt(s.angle,0)*Math.PI/180,r=50-Math.cos(a)*50,n=50-Math.sin(a)*50,o=50+Math.cos(a)*50,l=50+Math.sin(a)*50,c=s.stops.map(u=>`<stop offset="${qt(u.offset,0)*100}%" stop-color="${u.color}"/>`).join(""),d=`<defs><linearGradient id="${e}" x1="${r}%" y1="${n}%" x2="${o}%" y2="${l}%">${c}</linearGradient></defs>`;return{fill:`url(#${e})`,defs:d}}if(s.type==="radial"){const i=s.stops.map(r=>`<stop offset="${qt(r.offset,0)*100}%" stop-color="${r.color}"/>`).join(""),a=`<defs><radialGradient id="${e}" cx="50%" cy="50%" r="50%">${i}</radialGradient></defs>`;return{fill:`url(#${e})`,defs:a}}return{fill:"#000000"}}function sI(s){const e=s.type;switch(e){case"rectangle":{const t=s;return iI(t.width,t.height,t.cornerRadius??0)}case"circle":return ip(s.radius);case"ellipse":{const t=s;return rI(t.radiusX,t.radiusY)}case"line":{const t=s;return nI(t.length,t.thickness??2)}case"polygon":{const t=s;return oI(t.sides,t.radius)}case"star":{const t=s;return lI(t.points,t.outerRadius,t.innerRadius)}case"arrow":{const t=s;return cI(t.length,t.headWidth??30,t.headLength??25,t.shaftWidth??10)}case"heart":return dI(s.size);case"cross":{const t=s;return uI(t.width,t.height,t.thickness)}case"ring":{const t=s;return fI(t.outerRadius,t.innerRadius)}case"path":return s.d;default:throw new Error(`Unknown shape type: ${e}`)}}var Xn=.5522847498307936;function iI(s,e,t){const i=-s/2,a=-e/2,r=Math.min(t,s/2,e/2);return r===0?`M ${i} ${a} L ${i+s} ${a} L ${i+s} ${a+e} L ${i} ${a+e} Z`:[`M ${i+r} ${a}`,`L ${i+s-r} ${a}`,`Q ${i+s} ${a} ${i+s} ${a+r}`,`L ${i+s} ${a+e-r}`,`Q ${i+s} ${a+e} ${i+s-r} ${a+e}`,`L ${i+r} ${a+e}`,`Q ${i} ${a+e} ${i} ${a+e-r}`,`L ${i} ${a+r}`,`Q ${i} ${a} ${i+r} ${a}`,"Z"].join(" ")}function ip(s){const e=s*Xn;return[`M ${s} 0`,`C ${s} ${e} ${e} ${s} 0 ${s}`,`C ${-e} ${s} ${-s} ${e} ${-s} 0`,`C ${-s} ${-e} ${-e} ${-s} 0 ${-s}`,`C ${e} ${-s} ${s} ${-e} ${s} 0`,"Z"].join(" ")}function aI(s){const e=s*Xn;return[`M ${s} 0`,`C ${s} ${-e} ${e} ${-s} 0 ${-s}`,`C ${-e} ${-s} ${-s} ${-e} ${-s} 0`,`C ${-s} ${e} ${-e} ${s} 0 ${s}`,`C ${e} ${s} ${s} ${e} ${s} 0`,"Z"].join(" ")}function rI(s,e){const t=s*Xn,i=e*Xn;return[`M ${s} 0`,`C ${s} ${i} ${t} ${e} 0 ${e}`,`C ${-t} ${e} ${-s} ${i} ${-s} 0`,`C ${-s} ${-i} ${-t} ${-e} 0 ${-e}`,`C ${t} ${-e} ${s} ${-i} ${s} 0`,"Z"].join(" ")}function nI(s,e){const t=s/2,i=e/2;return`M ${-t} ${-i} L ${t} ${-i} L ${t} ${i} L ${-t} ${i} Z`}function oI(s,e){const t=2*Math.PI/s,i=-Math.PI/2,a=[];for(let r=0;r<s;r++){const n=i+r*t,o=Math.cos(n)*e,l=Math.sin(n)*e;a.push(r===0?`M ${o} ${l}`:`L ${o} ${l}`)}return a.push("Z"),a.join(" ")}function lI(s,e,t){const i=Math.PI/s,a=-Math.PI/2,r=[];for(let n=0;n<s*2;n++){const o=a+n*i,l=n%2===0?e:t,c=Math.cos(o)*l,d=Math.sin(o)*l;r.push(n===0?`M ${c} ${d}`:`L ${c} ${d}`)}return r.push("Z"),r.join(" ")}function cI(s,e,t,i){const a=i/2,r=e/2,n=s-t,o=-s/2;return[`M ${o} ${-a}`,`L ${o+n} ${-a}`,`L ${o+n} ${-r}`,`L ${o+s} 0`,`L ${o+n} ${r}`,`L ${o+n} ${a}`,`L ${o} ${a}`,"Z"].join(" ")}function dI(s){const e=s/32;return["M 0 6","C -0.5 -3 -12 -3 -12 6","C -12 12 0 18 0 24","C 0 18 12 12 12 6","C 12 -3 0.5 -3 0 6","Z"].map(i=>i.replace(/-?\d+(\.\d+)?/g,a=>String(parseFloat(a)*e))).join(" ")}function uI(s,e,t){const i=s/2,a=e/2,r=t/2;return[`M ${-r} ${-a}`,`L ${r} ${-a}`,`L ${r} ${-r}`,`L ${i} ${-r}`,`L ${i} ${r}`,`L ${r} ${r}`,`L ${r} ${a}`,`L ${-r} ${a}`,`L ${-r} ${r}`,`L ${-i} ${r}`,`L ${-i} ${-r}`,`L ${-r} ${-r}`,"Z"].join(" ")}function fI(s,e){const t=ip(s),i=aI(e);return`${t} ${i}`}function hI(s){const e=/-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?/g,t=[];let i;for(;(i=e.exec(s))!==null;){const p=parseFloat(i[0]);!isNaN(p)&&isFinite(p)&&t.push(p)}if(t.length<2)return{x:0,y:0,w:0,h:0};let a=1/0,r=1/0,n=-1/0,o=-1/0,l=0,c=0;const d=s.match(/[MmLlHhVvCcSsQqTtAaZz]/g)||[];let u=0,f=0;for(;u<d.length;){switch(d[u]){case"M":case"L":case"T":f+1<t.length&&(l=t[f++],c=t[f++],a=Math.min(a,l),n=Math.max(n,l),r=Math.min(r,c),o=Math.max(o,c));break;case"m":case"l":case"t":f+1<t.length&&(l+=t[f++],c+=t[f++],a=Math.min(a,l),n=Math.max(n,l),r=Math.min(r,c),o=Math.max(o,c));break;case"H":f<t.length&&(l=t[f++],a=Math.min(a,l),n=Math.max(n,l));break;case"h":f<t.length&&(l+=t[f++],a=Math.min(a,l),n=Math.max(n,l));break;case"V":f<t.length&&(c=t[f++],r=Math.min(r,c),o=Math.max(o,c));break;case"v":f<t.length&&(c+=t[f++],r=Math.min(r,c),o=Math.max(o,c));break;case"C":if(f+5<t.length)for(let g=0;g<3;g++){const w=t[f++],C=t[f++];a=Math.min(a,w),n=Math.max(n,w),r=Math.min(r,C),o=Math.max(o,C),g===2&&(l=w,c=C)}break;case"c":if(f+5<t.length)for(let g=0;g<3;g++){const w=l+t[f++],C=c+t[f++];a=Math.min(a,w),n=Math.max(n,w),r=Math.min(r,C),o=Math.max(o,C),g===2&&(l=w,c=C)}break;case"S":case"Q":if(f+3<t.length)for(let g=0;g<2;g++){const w=t[f++],C=t[f++];a=Math.min(a,w),n=Math.max(n,w),r=Math.min(r,C),o=Math.max(o,C),g===1&&(l=w,c=C)}break;case"s":case"q":if(f+3<t.length)for(let g=0;g<2;g++){const w=l+t[f++],C=c+t[f++];a=Math.min(a,w),n=Math.max(n,w),r=Math.min(r,C),o=Math.max(o,C),g===1&&(l=w,c=C)}break;case"A":f+6<t.length&&(f+=5,l=t[f++],c=t[f++],a=Math.min(a,l),n=Math.max(n,l),r=Math.min(r,c),o=Math.max(o,c));break;case"a":f+6<t.length&&(f+=5,l+=t[f++],c+=t[f++],a=Math.min(a,l),n=Math.max(n,l),r=Math.min(r,c),o=Math.max(o,c));break}u++}return a===1/0?{x:0,y:0,w:0,h:0}:{x:a,y:r,w:n-a,h:o-r}}async function pI(s,e={}){const t=e.defaultWidth??1920,i=e.defaultHeight??1080;let a,r,n;if(s.src){a=s.src;const o=gI(a);r=o.width||t,n=o.height||i}else if(s.shape)r=qt(s.width,t),n=qt(s.height,i),a=eI(s,r,n);else throw new Error("Either 'src' or 'shape' must be provided");return $A(a,{width:r,height:n,background:e.background})}function gI(s){const e=s.match(/width\s*=\s*["']?(\d+(?:\.\d+)?)/i),t=s.match(/height\s*=\s*["']?(\d+(?:\.\d+)?)/i);let i=e?parseFloat(e[1]):0,a=t?parseFloat(t[1]):0;if(!i||!a){const r=s.match(/viewBox\s*=\s*["']([^"']+)["']/i);if(r){const n=r[1].trim().split(/[\s,]+/).map(parseFloat);n.length===4&&(i=i||n[2],a=a||n[3])}}return{width:i,height:a}}var ap="https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu4mxP.ttf";async function mI(s={}){const e=s.width??wt.DEFAULTS.width,t=s.height??wt.DEFAULTS.height,i=s.pixelRatio??wt.DEFAULTS.pixelRatio,a="https://shotstack-ingest-api-dev-sources.s3.ap-southeast-2.amazonaws.com/euo5r93oyr/zzz01k9h-yycyx-2x2y6-qx9bj-7n567b/source.wasm";Xh.setFallbackLoader(async g=>{const w=(g.family??"Roboto").toLowerCase(),C=`${g.weight??"400"}`;if(w==="roboto"&&C==="400")return jn(ap)});let r;try{r=await Xh.getSharedInstance(a)}catch(g){throw new Error(`Failed to initialize font registry: ${g instanceof Error?g.message:String(g)}`)}const n=new TA(r),o=new Map,l=new Map,c=g=>`${g??"400"}`,d=(g,w)=>`${g}__${c(w)}`,u=async(g,w)=>{const C={family:w.family,weight:c(w.weight)},v=`${g}|${d(C.family,C.weight)}`,k=l.get(v);if(k)return k;const x=(async()=>{if(r.hasRegisteredFace(C))return;const T=await jn(g);await r.registerFromBytes(T,C)})();return l.set(v,x),x},f=async g=>{const w={family:g.family,weight:c(g.weight)},C=`${g.src}|${d(w.family,w.weight)}`,v=o.get(C);if(v)return v;const k=(async()=>{if(r.hasRegisteredFace(w))return;const x=await jn(g.src);await r.registerFromBytes(x,w)})();return o.set(C,k),k};async function p(g){try{if(g.customFonts)for(const k of g.customFonts)try{await f(k)}catch(x){throw new Error(`Failed to load custom font "${k.family}" from ${k.src}: ${x instanceof Error?x.message:String(x)}`)}const w=g.font??{family:"Roboto",weight:"400",size:48,color:"#000000",opacity:1},C={family:w.family,weight:`${w.weight}`};return await(async()=>{try{await r.getFace(C)}catch{if((w.family||"Roboto").toLowerCase()==="roboto"&&`${w.weight}`=="400"){if(!r.hasRegisteredFace({family:"Roboto",weight:"400"})){const x=await jn(ap);await r.registerFromBytes(x,{family:"Roboto",weight:"400"})}}else throw new Error(`Font not registered for ${C.family}__${C.weight}`)}})(),w}catch(w){throw w instanceof Error?w:new Error(`Failed to ensure fonts: ${String(w)}`)}}return{validate(g){const w=vA.safeParse(g);if(!w.success){const C=w.error.issues.map(v=>v.message).join(". ");throw new Error(`Validation failed: ${C}`)}return{value:w.data}},async registerFontFromUrl(g,w){try{await u(g,w)}catch(C){throw new Error(`Failed to register font "${w.family}" from URL ${g}: ${C instanceof Error?C.message:String(C)}`)}},async registerFontFromFile(g,w){try{let C;if(typeof g=="string"){await u(g,w);return}else try{C=await g.arrayBuffer()}catch(k){throw new Error(`Failed to read Blob as ArrayBuffer: ${k instanceof Error?k.message:String(k)}`)}const v={family:w.family,weight:c(w.weight)};if(r.hasRegisteredFace(v))return;await r.registerFromBytes(C,v)}catch(C){throw C instanceof Error?C:new Error(`Failed to register font "${w.family}" from ${typeof g=="string"?g:"Blob"}: ${String(C)}`)}},async renderFrame(g,w,C){try{const v=await p(g),k={family:v.family,weight:`${v.weight}`};let x;try{let re;const xe=r.getColorEmojiFontFamilies();if(xe.length>0)re={family:xe[0],weight:"400"};else{const Se={family:"NotoEmoji",weight:"400"};try{await r.getFace(Se),re=Se}catch{}}const pe=g.padding?typeof g.padding=="number"?{top:g.padding,right:g.padding,bottom:g.padding,left:g.padding}:g.padding:{top:0,right:0,bottom:0,left:0};x=await n.layout({text:g.text,width:(g.width??e)-pe.left-pe.right,letterSpacing:g.style?.letterSpacing??0,fontSize:v.size,lineHeight:g.style?.lineHeight??1.2,desc:k,textTransform:g.style?.textTransform??"none",emojiFallback:re})}catch(re){throw new Error(`Failed to layout text: ${re instanceof Error?re.message:String(re)}`)}const T=g.padding?typeof g.padding=="number"?{top:g.padding,right:g.padding,bottom:g.padding,left:g.padding}:g.padding:{top:0,right:0,bottom:0,left:0},b=g.border?.width??0,R=(g.width??e)+b*2,M=(g.height??t)+b*2,L=i,Q={x:0,y:0,width:(g.width??e)-T.left-T.right,height:(g.height??t)-T.top-T.bottom},K=g.width??e,q=g.height??t;let ce;try{ce=await FA({canvas:{width:R,height:M,pixelRatio:L},textRect:Q,lines:x,contentRect:{width:K,height:q},font:{family:v.family,size:v.size,weight:`${v.weight}`,color:v.color,opacity:v.opacity,background:v.background},style:{lineHeight:g.style?.lineHeight??1.2,textDecoration:g.style?.textDecoration??"none",gradient:g.style?.gradient},stroke:g.stroke,shadow:g.shadow,align:{horizontal:g.align?.horizontal??"center",vertical:g.align?.vertical??"middle"},background:g.background,border:g.border,padding:g.padding,glyphPathProvider:(re,xe)=>r.glyphPath(xe||k,re),getUnitsPerEm:re=>r.getUnitsPerEm(re||k),isColorEmojiFont:re=>r.isColorEmojiFont(re)})}catch(re){throw new Error(`Failed to build draw operations: ${re instanceof Error?re.message:String(re)}`)}try{return MA(ce,x,{t:w,fontSize:v.size,clipDuration:C,anim:g.animation?{preset:g.animation.preset,speed:g.animation.speed,duration:g.animation.duration,style:g.animation.style,direction:g.animation.direction}:void 0})}catch(re){throw new Error(`Failed to apply animation: ${re instanceof Error?re.message:String(re)}`)}}catch(v){throw v instanceof Error?v:new Error(`Failed to render frame at time ${w}s: ${String(v)}`)}},createRenderer(g){try{return YA(g)}catch(w){throw new Error(`Failed to create renderer: ${w instanceof Error?w.message:String(w)}`)}},destroy(){try{r.release()}catch(g){console.error(`Error during cleanup: ${g instanceof Error?g.message:String(g)}`)}}}}const rp=s=>{const t=(s.split("/").pop()||"").replace(/\.(ttf|otf|woff|woff2)$/i,""),i=t.replace(/-(Bold|Light|Regular|Italic|Medium|SemiBold|Black|Thin|ExtraLight|ExtraBold|Heavy)$/i,"");return{full:t,base:i}},yI=s=>s.includes("fonts.gstatic.com");class Is extends Lt{static PREVIEW_FPS=60;static fontCapabilityCache=new Map;textEngine=null;renderer=null;canvas=null;texture=null;sprite=null;lastRenderedTime=-1;cachedFrames=new Map;isRendering=!1;pendingRenderTime=null;validatedAsset=null;fontSupportsBold=!1;loadComplete=!1;fontRegistrationCache=new Map;static getFontSourceCacheKey(e){return e.split("#",1)[0].split("?",1)[0]}constructor(e,t){const{fit:i,...a}=t;super(e,a,it.RichText)}resolveFontWeight(e,t){const i=e.font?.weight;return typeof i=="string"?parseInt(i,10)||t:typeof i=="number"?i:t}buildCanvasPayload(e,t){const i=this.clipConfiguration.width||this.edit.size.width,a=this.clipConfiguration.height||this.edit.size.height,r=e.font?.family,{baseFontFamily:n,fontWeight:o}=t??(r?ts(r):{baseFontFamily:r,fontWeight:400}),l=this.resolveFontWeight(e,o),c=this.edit.getTimelineFonts(),d=r?c.find(g=>{const{full:w,base:C}=rp(g.src),v=r.toLowerCase();return w.toLowerCase()===v||C.toLowerCase()===v}):void 0;let u;if(d&&r)u=[{src:d.src,family:n||r,weight:l.toString()}];else if(r){const g=this.edit.getFontMetadata(),w=(n||r).toLowerCase(),v=c.filter(k=>!yI(k.src)).find(k=>g.get(k.src)?.baseFamilyName.toLowerCase()===w);v&&(u=[{src:v.src,family:n||r,weight:l.toString()}])}const p=u||r&&Zr(r)?n||r:void 0;return{...e,width:i,height:a,font:e.font?{...e.font,family:p||"Roboto",weight:l}:void 0,stroke:e.font?.stroke,...u&&{customFonts:u}}}async registerFont(e,t,i){if(!this.textEngine)return!1;const a=Is.getFontSourceCacheKey(i.path),r=`${i.type}:${a}|${e}|${t}`,n=this.fontRegistrationCache.get(r);if(n)return n;const o=(async()=>{try{const l={family:e,weight:t.toString()};return i.type==="url"?await this.textEngine.registerFontFromUrl(i.path,l):await this.textEngine.registerFontFromFile(i.path,l),!0}catch{return!1}})();return this.fontRegistrationCache.set(r,o),o}createFontCapabilityCheckPromise(e){return(async()=>{try{const t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch font: ${t.status}`);const i=await t.arrayBuffer();return!!Vo.parse(i).tables.fvar?.axes?.find(n=>n.tag==="wght")}catch(t){return console.warn("Failed to check font capabilities:",t),!1}})()}async prepareFontForAsset(e,t){const i=await this.ensureFontRegistered(e);if(!i)return;const a=Is.getFontSourceCacheKey(i),r=Is.fontCapabilityCache.get(a),n=r??this.createFontCapabilityCheckPromise(i);r||Is.fontCapabilityCache.set(a,n),this.fontSupportsBold=await n,t&&this.edit.getInternalEvents().emit(Be.FontCapabilitiesChanged,{supportsBold:this.fontSupportsBold})}supportsBold(){return this.fontSupportsBold}resolveFont(e){const{baseFontFamily:t,fontWeight:i}=ts(e),a=this.edit.getFontUrlByFamilyAndWeight(t,i);if(a)return{url:a,baseFontFamily:t,fontWeight:i};const o=(this.edit.getEdit()?.timeline?.fonts||[]).find(c=>{const{full:d,base:u}=rp(c.src),f=e.toLowerCase();return d.toLowerCase()===f||u.toLowerCase()===f});if(o)return{url:o.src,baseFontFamily:t,fontWeight:i};const l=Zr(e);return l?{url:l,baseFontFamily:t,fontWeight:i}:null}reconfigureAfterRestore(){super.reconfigureAfterRestore(),this.reconfigure(this.clipConfiguration.asset)}async reconfigure(e){try{await this.prepareFontForAsset(e,!0);for(const t of this.cachedFrames.values())t.destroy();if(this.cachedFrames.clear(),this.lastRenderedTime=-1,this.textEngine){const t=this.buildCanvasPayload(e),{value:i}=this.textEngine.validate(t);this.validatedAsset=i}this.textEngine&&this.renderer&&this.renderFrameSafe(this.getPlaybackTime())}catch{}}async ensureFontRegistered(e){if(!this.textEngine)return null;const t=e.font?.family;if(!t)return null;const i=this.resolveFont(t);if(!i)return null;const a=this.resolveFontWeight(e,i.fontWeight);return await this.registerFont(i.baseFontFamily,a,{type:"url",path:i.url}),i.url}async load(){await super.load();const e=this.clipConfiguration.asset;try{if(!ku.safeParse(e).success){this.createFallbackText(e);return}const i=e.font?.family,a=i?ts(i):void 0,r=this.buildCanvasPayload(e,a);this.textEngine=await mI({width:r.width,height:r.height,fps:Is.PREVIEW_FPS});const{value:n}=this.textEngine.validate(r);this.validatedAsset=n,this.canvas=document.createElement("canvas"),this.canvas.width=r.width,this.canvas.height=r.height,this.renderer=this.textEngine.createRenderer(this.canvas),await this.prepareFontForAsset(e,!1),await this.renderFrame(0),this.configureKeyframes(),this.loadComplete=!0}catch{this.cleanupResources(),this.createFallbackText(e)}}cleanupResources(){if(this.textEngine){try{this.textEngine.destroy()}catch(e){console.warn("Error destroying text engine:",e)}this.textEngine=null}this.renderer=null,this.canvas=null,this.validatedAsset=null}async renderFrame(e){if(!this.textEngine||!this.renderer||!this.canvas||!this.validatedAsset)return;const t=Math.floor(e*Is.PREVIEW_FPS);if(this.cachedFrames.has(t)){const i=this.cachedFrames.get(t);this.sprite&&this.sprite.texture!==i&&(this.sprite.texture=i),this.lastRenderedTime=e;return}try{const i=this.getLength(),a=await this.textEngine.renderFrame(this.validatedAsset,e,i),r=this.canvas.getContext("2d");r&&r.clearRect(0,0,this.canvas.width,this.canvas.height),await this.renderer.render(a);const n=G.Texture.from(this.canvas);this.sprite?(this.texture&&!this.cachedFrames.has(t)&&this.texture.destroy(),this.sprite.texture=n):(this.sprite=new G.Sprite(n),this.contentContainer.addChild(this.sprite)),this.texture=n,this.cachedFrames.size<150&&this.cachedFrames.set(t,n),this.lastRenderedTime=e}catch(i){console.error("Failed to render rich text frame:",i)}}createFallbackText(e){const t=this.edit.getEdit(),i=this.clipConfiguration.width||t?.output?.size?.width||this.edit.size.width,a=this.clipConfiguration.height||t?.output?.size?.height||this.edit.size.height,r=new G.TextStyle({fontFamily:e.font?.family||"Arial",fontSize:e.font?.size||48,fill:e.font?.color||"#ffffff",align:e.align?.horizontal||"center",wordWrap:!0,wordWrapWidth:i}),n=new G.Text(e.text,r);switch(e.align?.horizontal){case"left":n.anchor.set(0,.5),n.x=0;break;case"right":n.anchor.set(1,.5),n.x=i;break;default:n.anchor.set(.5,.5),n.x=i/2}switch(e.align?.vertical){case"top":n.anchor.set(n.anchor.x,0),n.y=0;break;case"bottom":n.anchor.set(n.anchor.x,1),n.y=a;break;default:n.anchor.set(n.anchor.x,.5),n.y=a/2}this.contentContainer.addChild(n)}renderFrameSafe(e){if(this.isRendering){this.pendingRenderTime=e;const t=Math.floor(e*Is.PREVIEW_FPS),i=this.cachedFrames.get(t);i&&this.sprite&&this.sprite.texture!==i&&(this.sprite.texture=i);return}this.isRendering=!0,this.pendingRenderTime=null,this.renderFrame(e).catch(t=>console.error("Failed to render rich text frame:",t)).finally(()=>{if(this.isRendering=!1,this.pendingRenderTime!==null&&this.pendingRenderTime!==e){const t=this.pendingRenderTime;this.pendingRenderTime=null,this.renderFrameSafe(t)}})}update(e,t){if(super.update(e,t),t===Ca.SEEK_ELAPSED_MARKER&&(this.isRendering=!1,this.pendingRenderTime=null,this.lastRenderedTime=-1),!!this.isActive()&&this.loadComplete&&this.textEngine&&this.renderer&&!this.isRendering){const i=this.getPlaybackTime(),a=1/60;Math.abs(i-this.lastRenderedTime)>a&&this.renderFrameSafe(i)}}dispose(){super.dispose(),this.loadComplete=!1;for(const e of this.cachedFrames.values())e.destroy();this.cachedFrames.clear(),this.texture&&!this.cachedFrames.has(Math.floor(this.lastRenderedTime*Is.PREVIEW_FPS))&&this.texture.destroy(),this.texture=null,this.sprite&&(this.sprite.destroy(),this.sprite=null),this.canvas&&(this.canvas=null),this.textEngine&&(this.textEngine.destroy(),this.textEngine=null),this.renderer=null,this.validatedAsset=null}getSize(){const e=this.edit.getEdit();return{width:this.clipConfiguration.width||e?.output?.size?.width||this.edit.size.width,height:this.clipConfiguration.height||e?.output?.size?.height||this.edit.size.height}}getContentSize(){return{width:this.clipConfiguration.width||this.canvas?.width||this.edit.size.width,height:this.clipConfiguration.height||this.canvas?.height||this.edit.size.height}}getFitScale(){return 1}getContainerScale(){const e=this.getScale();return{x:e,y:e}}supportsEdgeResize(){return!0}onDimensionsChanged(){if(!this.textEngine||!this.renderer||!this.canvas)return;const e=this.clipConfiguration.asset,{width:t,height:i}=this.getSize();this.canvas.width=t,this.canvas.height=i;for(const n of this.cachedFrames.values())n.destroy();this.cachedFrames.clear(),this.lastRenderedTime=-1;const a=this.buildCanvasPayload(e),{value:r}=this.textEngine.validate(a);this.validatedAsset=r,this.renderFrameSafe(this.getPlaybackTime())}updateTextContent(e){const t=this.clipConfiguration.asset;if(t.text=e,this.textEngine){const i=this.buildCanvasPayload(t),{value:a}=this.textEngine.validate(i);this.validatedAsset=a}for(const i of this.cachedFrames.values())i.destroy();this.cachedFrames.clear(),this.lastRenderedTime=-1,this.textEngine&&this.renderer&&this.renderFrameSafe(this.getPlaybackTime())}getCacheSize(){return this.cachedFrames.size}}class bI extends Lt{shape;shapeBackground;constructor(e,t){super(e,t,it.Shape),this.shape=null,this.shapeBackground=null}async load(){await super.load();const e=this.clipConfiguration.asset,t=new G.Graphics,i=e.width??this.edit.size.width,a=e.height??this.edit.size.height;t.fillStyle={color:"transparent"},t.rect(0,0,i,a),t.fill();const r=new G.Graphics;switch(e.shape){case"rectangle":{const n=e.rectangle,o=i/2-n.width/2,l=a/2-n.height/2;r.rect(o,l,n.width,n.height);break}case"circle":{const n=e.circle,o=i/2,l=a/2;r.circle(o,l,n.radius);break}case"line":{const n=e.line,o=i/2-n.length/2,l=a/2-n.thickness/2;r.rect(o,l,n.length,n.thickness);break}default:console.warn("Unsupported shape asset type.");break}if(r.fillStyle={color:e.fill?.color??"#ffffff",alpha:e.fill?.opacity??1},r.fill(),e.stroke){const n=new Ua({thickness:e.stroke.width,color:e.stroke.color});r.filters=[n]}this.shapeBackground=t,this.shape=r,this.contentContainer.addChild(t),t.addChild(r),this.configureKeyframes()}update(e,t){super.update(e,t)}dispose(){super.dispose(),this.shape?.destroy(),this.shape=null,this.shapeBackground?.destroy(),this.shapeBackground=null}getSize(){const e=this.clipConfiguration.asset;return{width:e.width??this.edit.size.width,height:e.height??this.edit.size.height}}getFitScale(){return 1}}const wI="https://unpkg.com/@resvg/resvg-wasm@2.6.2/index_bg.wasm";class Us extends Lt{static resvgInitialized=!1;static resvgInitPromise=null;texture=null;sprite=null;renderedWidth=0;renderedHeight=0;pendingRender=null;constructor(e,t){super(e,t,it.Svg)}static async initializeResvg(){if(!Us.resvgInitialized){if(Us.resvgInitPromise){await Us.resvgInitPromise;return}Us.resvgInitPromise=(async()=>{const t=await(await fetch(wI)).arrayBuffer();await JA(t),Us.resvgInitialized=!0})(),await Us.resvgInitPromise}}async load(){await super.load();let e=this.clipConfiguration.asset;if(e.src){const t=this.edit.resolveMergeFields(e.src);t!==e.src&&(e={...e,src:t})}try{if(!z2.safeParse(e).success){this.createFallbackGraphic();return}await Us.initializeResvg(),await this.doRender(),this.configureKeyframes()}catch(t){console.error("Failed to render SVG asset:",t),this.createFallbackGraphic()}}async reloadAsset(){await this.rerenderAtCurrentDimensions()}createFallbackGraphic(){const e=this.clipConfiguration.width||this.edit.size.width,t=this.clipConfiguration.height||this.edit.size.height,i=bd(e,t);this.renderedWidth=e,this.renderedHeight=t,this.contentContainer.addChild(i),this.configureKeyframes()}update(e,t){super.update(e,t)}dispose(){super.dispose(),this.pendingRender=null,this.sprite&&(this.sprite.destroy(),this.sprite=null),this.texture&&(this.texture.destroy(!0),this.texture=null)}getSize(){return this.clipConfiguration.width&&this.clipConfiguration.height?{width:this.clipConfiguration.width,height:this.clipConfiguration.height}:{width:this.renderedWidth||this.edit.size.width,height:this.renderedHeight||this.edit.size.height}}getContentSize(){return{width:this.renderedWidth||this.edit.size.width,height:this.renderedHeight||this.edit.size.height}}getFitScale(){return 1}supportsEdgeResize(){return!0}onDimensionsChanged(){this.rerenderAtCurrentDimensions()}async rerenderAtCurrentDimensions(){this.pendingRender&&await this.pendingRender,this.sprite&&(this.contentContainer.removeChild(this.sprite),this.sprite.destroy(),this.sprite=null),this.texture&&(this.texture.destroy(!0),this.texture=null),this.pendingRender=this.doRender(),await this.pendingRender,this.pendingRender=null}async doRender(){const e=this.clipConfiguration.asset,t=this.clipConfiguration.width||this.edit.size.width,i=this.clipConfiguration.height||this.edit.size.height,a=await pI(e,{defaultWidth:t,defaultHeight:i});this.renderedWidth=a.width,this.renderedHeight=a.height;const r=new Blob([a.png],{type:"image/png"}),n=URL.createObjectURL(r),o=new Image;o.src=n,await new Promise((l,c)=>{o.onload=()=>l(),o.onerror=()=>c(new Error("Failed to load SVG image"))}),URL.revokeObjectURL(n),this.texture=G.Texture.from(o),this.sprite=new G.Sprite(this.texture),this.contentContainer.addChild(this.sprite),this.clipConfiguration.width&&this.clipConfiguration.height&&this.applyFixedDimensions()}}class yr{static DEFAULT_BLINK_INTERVAL_MS=500;static DEFAULT_CURSOR_WIDTH_PX=2;static DEFAULT_CURSOR_COLOR=16777215;cursor=null;parent;textElement;clipConfig;textPosition=0;pixelX=0;pixelY=0;currentLine=0;isBlinking=!1;blinkInterval=null;blinkIntervalMs=500;width=2;color=16777215;isVisible=!0;constructor(e,t,i,a){this.parent=e,this.textElement=t,this.clipConfig=i,this.width=a?.width??yr.DEFAULT_CURSOR_WIDTH_PX,this.color=a?.color??yr.DEFAULT_CURSOR_COLOR,this.blinkIntervalMs=a?.blinkInterval??yr.DEFAULT_BLINK_INTERVAL_MS,this.textPosition=0,this.isBlinking=!1,this.isVisible=!0,this.blinkInterval=null,this.createCursor()}updatePosition(e){if(!this.cursor||!this.textElement){console.warn("TextCursor: Cannot update position, cursor not initialized");return}this.textPosition=this.validateTextPosition(e),this.calculateAndApplyPixelPosition()}setPosition(e,t){if(!this.cursor){console.warn("TextCursor: Cannot set position, cursor not initialized");return}this.pixelX=e,this.pixelY=t,this.updateGraphicsPosition()}show(){this.setVisible(!0)}hide(){this.setVisible(!1)}setVisible(e){this.isVisible=e,this.cursor&&!this.isBlinking&&(this.cursor.visible=e)}startBlinking(){if(!this.cursor){console.warn("TextCursor: Cannot start blinking, cursor not initialized");return}this.isBlinking||this.startBlinkingAnimation()}stopBlinking(){this.stopBlinkingAnimation()}setBlinkInterval(e){this.blinkIntervalMs=e,this.isBlinking&&(this.stopBlinking(),this.startBlinking())}dispose(){if(this.stopBlinkingAnimation(),this.cursor&&this.parent)try{this.parent.removeChild(this.cursor)}catch(e){console.warn("TextCursor: Error removing cursor from parent:",e)}if(this.cursor)try{this.cursor.destroy()}catch(e){console.warn("TextCursor: Error destroying cursor graphics:",e)}finally{this.cursor=null}this.textPosition=0,this.pixelX=0,this.pixelY=0,this.currentLine=0,this.isVisible=!0}createCursor(){if(!this.textElement)return;this.cursor=new G.Graphics,this.cursor.fillStyle={color:this.color};const e=this.textElement.style.fontSize;this.cursor.rect(0,0,this.width,e),this.cursor.fill(),this.parent.addChild(this.cursor),this.cursor.visible=this.isVisible}validateTextPosition(e){return this.textElement?Math.max(0,Math.min(e,this.textElement.text.length)):0}calculateAndApplyPixelPosition(){this.calculatePixelPositionFromText(),this.updateGraphicsPosition()}calculatePixelPositionFromText(){if(!this.textElement)return;const{text:e}=this.textElement,t=this.textElement.style,i=e.substring(0,this.textPosition),a=i.match(/\n/g);this.currentLine=a?a.length:0;const r=e.split(`
|
|
276
276
|
`),n=this.currentLine<r.length?r[this.currentLine]:"",o=i.lastIndexOf(`
|
|
277
|
-
`),l=o===-1?this.textPosition:this.textPosition-o-1,c=n.substring(0,l);let d;c.length>0&&c.endsWith(" ")?d=this.measureText(`${c}x`,t)-this.measureText("x",t):d=this.measureText(c,t);const u=t.lineHeight;this.pixelY=this.currentLine*u;const p=this.clipConfig.asset.alignment?.horizontal??"center";let g=d;if(p!=="left"){const w=this.measureText(n,t),C=this.textElement.width;let v=0;p==="center"?v=(C-w)/2:p==="right"&&(v=C-w),g=v+d}this.pixelX=g}updateGraphicsPosition(){this.cursor&&this.cursor.position.set(this.pixelX,this.pixelY)}startBlinkingAnimation(){!this.cursor||this.isBlinking||(this.isBlinking=!0,this.blinkInterval=window.setInterval(()=>{this.cursor&&this.isBlinking&&(this.cursor.visible=!this.cursor.visible)},this.blinkIntervalMs))}stopBlinkingAnimation(){this.blinkInterval!==null&&(window.clearInterval(this.blinkInterval),this.blinkInterval=null),this.isBlinking=!1,this.cursor&&(this.cursor.visible=this.isVisible)}measureText(e,t){const i=new G.Text(e,t),{width:a}=i;return i.destroy(),a}isInitialized(){return this.cursor!==null}getState(){return{isInitialized:this.isInitialized(),isBlinking:this.isBlinking,isVisible:this.isVisible,textPosition:this.textPosition,pixelPosition:{x:this.pixelX,y:this.pixelY},currentLine:this.currentLine}}}class Kn{static DEFAULT_FOCUS_DELAY_MS=50;hiddenInput=null;isFocused=!1;focusRetryCount=0;maxFocusRetries=3;focusDelay=Kn.DEFAULT_FOCUS_DELAY_MS;eventHandlers={};abortController=null;textChangeCallback=null;lastSyncedText="";isComposing=!1;setupInput(e,t){this.focusDelay=t?.focusDelay??Kn.DEFAULT_FOCUS_DELAY_MS,this.createHiddenTextarea(),this.hiddenInput&&(this.hiddenInput.value=e,this.lastSyncedText=e),this.setupEventListeners(),t?.autoFocus!==!1&&this.focusInput()}updateInputValue(e){this.hiddenInput&&(this.hiddenInput.value=e,this.lastSyncedText=e)}focusInput(){this.hiddenInput&&setTimeout(()=>{this.hiddenInput&&!this.isFocused&&(this.hiddenInput.focus(),setTimeout(()=>{!this.isFocused&&this.focusRetryCount<this.maxFocusRetries&&(this.focusRetryCount+=1,this.focusInput())},10))},this.focusDelay)}blurInput(){this.hiddenInput&&this.hiddenInput.blur()}setSelectionRange(e,t){if(!this.hiddenInput)return;const i=this.hiddenInput.value.length,a=Math.max(0,Math.min(e,i)),r=Math.max(a,Math.min(t,i));this.hiddenInput.setSelectionRange(a,r)}getCursorPosition(){return this.hiddenInput?.selectionStart||0}getValue(){return this.hiddenInput?.value||""}setTextInputHandler(e){this.textChangeCallback=e}setEventHandlers(e){this.eventHandlers={...this.eventHandlers,...e}}isFocusedInput(){return this.isFocused}dispose(){this.removeAllEventListeners(),this.hiddenInput&&this.hiddenInput.parentNode&&this.hiddenInput.parentNode.removeChild(this.hiddenInput),this.hiddenInput=null,this.isFocused=!1,this.focusRetryCount=0,this.textChangeCallback=null,this.eventHandlers={}}createHiddenTextarea(){this.hiddenInput=document.createElement("textarea");const e={position:"absolute",opacity:"0.01",pointerEvents:"none",zIndex:"18",left:"0px",top:"0px",width:"1px",height:"1px",border:"none",outline:"none",resize:"none",backgroundColor:"transparent"};Object.assign(this.hiddenInput.style,e),this.hiddenInput.tabIndex=0,document.body.appendChild(this.hiddenInput)}setupEventListeners(){if(!this.hiddenInput)return;this.abortController=new AbortController;const{signal:e}=this.abortController;this.hiddenInput.addEventListener("input",this.handleTextInput,{signal:e}),this.hiddenInput.addEventListener("keydown",this.handleKeyDown,{signal:e}),this.hiddenInput.addEventListener("compositionstart",this.handleCompositionStart,{signal:e}),this.hiddenInput.addEventListener("compositionend",this.handleCompositionEnd,{signal:e}),this.hiddenInput.addEventListener("focus",this.handleFocus,{signal:e}),this.hiddenInput.addEventListener("blur",this.handleBlur,{signal:e}),this.hiddenInput.addEventListener("paste",this.handlePaste,{signal:e})}removeAllEventListeners(){this.abortController?.abort(),this.abortController=null}handleTextInput=e=>{if(!this.hiddenInput||this.isComposing)return;const t=this.hiddenInput.value,i=this.hiddenInput.selectionStart||0;this.lastSyncedText=t,this.textChangeCallback?.(t,i)};handleKeyDown=e=>{if(document.activeElement!==this.hiddenInput)return;let t=!1;if((e.ctrlKey||e.metaKey)&&(t=this.handleKeyboardShortcuts(e),t)){e.preventDefault();return}if(e.key==="Tab"){const i=e.shiftKey?"backward":"forward";this.eventHandlers.onTabNavigation?.(i),e.preventDefault();return}switch(e.key){case"Escape":this.eventHandlers.onEscape?.(e),t=!0;break;case"Enter":t=!1;break;case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"ArrowDown":setTimeout(()=>{if(this.hiddenInput){const i=this.hiddenInput.value,a=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(i,a)}},0),t=!1;break;case"Backspace":case"Delete":t=!1;break;default:t=this.eventHandlers.onCustomKey?.(e.key,e)||!1;break}t&&e.preventDefault()};handleKeyboardShortcuts(e){const{key:t}=e;switch(t.toLowerCase()){case"a":return this.selectAll(),!0;case"c":case"v":return!1;case"z":return this.eventHandlers.onCustomKey?.("undo",e),!0;case"y":return this.eventHandlers.onCustomKey?.("redo",e),!0;default:return!1}}handleCompositionStart=e=>{this.isComposing=!0};handleCompositionEnd=e=>{if(this.isComposing=!1,this.hiddenInput){const t=this.hiddenInput.value,i=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(t,i)}};handleFocus=e=>{this.isFocused=!0,this.focusRetryCount=0,this.eventHandlers.onFocus?.(e)};handleBlur=e=>{this.isFocused=!1,this.eventHandlers.onBlur?.(e)};handlePaste=e=>{setTimeout(()=>{this.handleTextInput(e)},0)};selectAll(){this.hiddenInput&&this.hiddenInput.select()}}class Ts{static DOUBLE_CLICK_THRESHOLD_MS=300;static EDITING_BG_PADDING_PX=5;static EDITING_BG_ALPHA=.2;static CLICK_HANDLER_DELAY_MS=100;parent;targetText;clipConfig;isEditing=!1;lastClickTime=0;editingContainer=null;editableText=null;textCursor=null;textInputHandler=null;outsideClickHandler=null;constructor(e,t,i){this.parent=e,this.targetText=t,this.clipConfig=i,this.parent.getContainer().eventMode="static",this.parent.getContainer().on("click",this.checkForDoubleClick)}dispose(){this.parent.getContainer().off("click",this.checkForDoubleClick),this.stopEditing(),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null)}startEditing(){if(this.isEditing||!this.targetText)return;const e=structuredClone(this.clipConfig);this.targetText.visible=!1,this.createEditingEnvironment(),this.setupOutsideClickHandler(e),this.isEditing=!0}stopEditing(e=!1,t){if(!this.isEditing)return;let i="";this.editableText&&(i=this.editableText.text),this.editingContainer&&(this.parent.getContainer().removeChild(this.editingContainer),this.editingContainer.destroy(),this.editingContainer=null),this.editableText=null,this.textCursor&&(this.textCursor.dispose(),this.textCursor=null),this.textInputHandler&&(this.textInputHandler.dispose(),this.textInputHandler=null),this.targetText.visible=!0,e&&t&&i!==""&&this.parent.updateTextContent(i,t),this.isEditing=!1}checkForDoubleClick=e=>{const t=Date.now();t-this.lastClickTime<Ts.DOUBLE_CLICK_THRESHOLD_MS&&this.startEditing(),this.lastClickTime=t};setupOutsideClickHandler(e){this.outsideClickHandler=t=>{const a=this.parent.getContainer().getBounds(),r=t.clientX,n=t.clientY;(r<a.x||r>a.x+a.width||n<a.y||n>a.y+a.height)&&(this.stopEditing(!0,e),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null))},setTimeout(()=>{this.outsideClickHandler&&window.addEventListener("click",this.outsideClickHandler)},Ts.CLICK_HANDLER_DELAY_MS)}createEditingEnvironment(){this.setupEditingContainer(),this.editingContainer&&this.editableText&&(this.textCursor=new yr(this.editingContainer,this.editableText,this.clipConfig),this.textCursor.updatePosition(this.targetText.text.length),this.textCursor.startBlinking()),this.setupTextInputHandler(),this.updateTextAlignment()}setupEditingContainer(){this.editingContainer=new G.Container,this.parent.getContainer().addChild(this.editingContainer);const e=new G.Graphics;e.fillStyle={color:0,alpha:Ts.EDITING_BG_ALPHA},e.rect(-5,-5,this.targetText.width+2*Ts.EDITING_BG_PADDING_PX,this.targetText.height+2*Ts.EDITING_BG_PADDING_PX),e.fill(),this.editingContainer.addChild(e),this.editableText=new G.Text(this.targetText.text,this.targetText.style),this.editableText.eventMode="static",this.editableText.cursor="text",this.editingContainer.addChild(this.editableText)}setupTextInputHandler(){this.textInputHandler=new Kn,this.textInputHandler.setTextInputHandler((e,t)=>{this.editableText&&(this.editableText.text=e,this.updateTextAlignment()),this.textCursor?.updatePosition(t)}),this.textInputHandler.setEventHandlers({onEscape:e=>this.stopEditing(!1),onTabNavigation:e=>this.stopEditing(!0)}),this.textInputHandler.setupInput(this.targetText.text,{autoFocus:!0})}updateTextAlignment(){if(!this.editableText||!this.editingContainer)return;const e=this.getContainerDimensions(),t=this.getAlignmentSettings(),i=this.calculateHorizontalPosition({width:this.editableText.width},e,t.horizontal),a=this.calculateVerticalPosition({height:this.editableText.height},e,t.vertical);if(this.editingContainer.position.set(i,a),this.editingContainer.children.length>0){const r=this.editingContainer.getChildAt(0);r instanceof G.Graphics&&(r.clear(),r.fillStyle={color:0,alpha:Ts.EDITING_BG_ALPHA},r.rect(-5,-5,this.editableText.width+2*Ts.EDITING_BG_PADDING_PX,this.editableText.height+2*Ts.EDITING_BG_PADDING_PX),r.fill())}}calculateHorizontalPosition(e,t,i="center"){switch(i){case"center":return t.width/2-e.width/2;case"right":return t.width-e.width;case"left":default:return 0}}calculateVerticalPosition(e,t,i="center"){switch(i){case"center":return t.height/2-e.height/2;case"bottom":return t.height-e.height;case"top":default:return 0}}getContainerDimensions(){const e=this.clipConfig.asset;return{width:e.width??this.parent.getSize().width,height:e.height??this.parent.getSize().height}}getAlignmentSettings(){const e=this.clipConfig.asset;return{horizontal:e.alignment?.horizontal??"center",vertical:e.alignment?.vertical??"center"}}}class ba extends Lt{static loadedFonts=new Set;background=null;text=null;textEditor=null;constructor(e,t){super(e,t,it.Text)}async load(){await super.load();const e=this.clipConfiguration.asset,t=e.font?.family??"Open Sans";if(await this.loadFont(t),this.background=new G.Graphics,this.drawBackground(),this.text=new G.Text({text:e.text??"",style:this.createTextStyle(e)}),this.positionText(e),e.stroke?.width&&e.stroke.width>0&&e.stroke.color){const i=new Ua({thickness:e.stroke.width,color:e.stroke.color});this.text.filters=[i]}this.contentContainer.addChild(this.background),this.contentContainer.addChild(this.text),this.configureKeyframes(),this.textEditor=new Ts(this,this.text,this.clipConfiguration)}update(e,t){super.update(e,t)}reconfigureAfterRestore(){super.reconfigureAfterRestore(),this.reconfigure()}async reconfigure(){const e=this.clipConfiguration.asset,t=e.font?.family??"Open Sans";if(await this.loadFont(t),this.drawBackground(),this.text){if(this.text.text=e.text??"",this.text.style=this.createTextStyle(e),e.stroke?.width&&e.stroke.width>0&&e.stroke.color){const i=new Ua({thickness:e.stroke.width,color:e.stroke.color});this.text.filters=[i]}else this.text.filters=[];this.positionText(e)}}dispose(){super.dispose(),this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null,this.textEditor?.dispose(),this.textEditor=null}getSize(){const e=this.clipConfiguration.asset;return{width:this.clipConfiguration.width??e.width??this.edit.size.width,height:this.clipConfiguration.height??e.height??this.edit.size.height}}getFitScale(){return 1}getContainerScale(){const e=this.getScale();return{x:e,y:e}}supportsEdgeResize(){return!0}onDimensionsChanged(){if(this.drawBackground(),this.text){const e=this.clipConfiguration.asset;this.text.style.wordWrapWidth=this.getSize().width,this.positionText(e)}}applyFixedDimensions(){}createTextStyle(e){const t=e.font?.family??"Open Sans",{baseFontFamily:i,fontWeight:a}=ts(t),{width:r}=this.getSize();return new G.TextStyle({fontFamily:i,fontSize:e.font?.size??32,fill:e.font?.color??"#ffffff",fontWeight:a.toString(),wordWrap:!0,wordWrapWidth:r,lineHeight:(e.font?.lineHeight??1)*(e.font?.size??32),align:e.alignment?.horizontal??"center"})}positionText(e){if(!this.text)return;const t=e.alignment?.horizontal??"center",i=e.alignment?.vertical??"center",{width:a,height:r}=this.getSize();let n=a/2-this.text.width/2,o=r/2-this.text.height/2;t==="left"?n=0:t==="right"&&(n=a-this.text.width),i==="top"?o=0:i==="bottom"&&(o=r-this.text.height),this.text.position.set(n,o)}drawBackground(){const e=this.clipConfiguration.asset;if(!this.background||!e.background||!e.background.color)return;const{width:t,height:i}=this.getSize();this.background.clear(),this.background.fillStyle={color:e.background.color,alpha:e.background.opacity??1},this.background.rect(0,0,t,i),this.background.fill()}updateTextContent(e,t){this.edit.updateTextContent(this,e,t)}async loadFont(e){const{baseFontFamily:t,fontWeight:i}=ts(e),a=`${t}-${i}`;if(ba.loadedFonts.has(a))return;const r=Zr(e);if(r){const n=new FontFace(t,`url(${r})`,{weight:i.toString()});await n.load(),document.fonts.add(n),ba.loadedFonts.add(a)}}static resetFontCache(){ba.loadedFonts.clear()}}class vI extends Lt{aiOverlay=null;lastPrompt="";constructor(e,t){super(e,t,it.TextToImage)}async load(){await super.load();const{width:e,height:t}=this.getSize(),i=this.edit.getResolvedEdit()?.timeline.tracks.flatMap(l=>l.clips)??[],a=Oo(i,this.clipId??""),{asset:r}=this.clipConfiguration,n=Qs(r)&&r.prompt||"",o=Qs(r)?r.type:"text-to-image";this.aiOverlay=new Do({mode:"panel",icon:"image",width:e,height:t,assetNumber:a??void 0,prompt:n,assetType:o}),this.contentContainer.addChild(this.aiOverlay.getContainer()),this.configureKeyframes()}update(e,t){super.update(e,t);const{width:i,height:a}=this.getSize();this.aiOverlay?.resize(i,a);const{asset:r}=this.clipConfiguration,n=Qs(r)&&r.prompt||"";n!==this.lastPrompt&&(this.aiOverlay?.updatePrompt(n),this.lastPrompt=n)}getSize(){const e=this.clipConfiguration.asset;return{width:this.clipConfiguration.width??e.width??this.edit.size.width,height:this.clipConfiguration.height??e.height??this.edit.size.height}}dispose(){this.aiOverlay?.dispose(),this.aiOverlay=null,super.dispose()}}class xI extends Lt{constructor(e,t){super(e,t,it.TextToSpeech)}async load(){await super.load(),this.configureKeyframes()}update(e,t){super.update(e,t),this.getContainer().alpha=0}getSize(){return{width:0,height:0}}}class CI extends Lt{texture;sprite;isPlaying;volumeKeyframeBuilder;syncTimer;activeSyncTimer;skipVideoUpdate;constructor(e,t){super(e,t,it.Video),this.texture=null,this.sprite=null,this.isPlaying=!1;const i=this.clipConfiguration.asset;this.volumeKeyframeBuilder=new Da(i.volume??1,this.getLength()),this.syncTimer=0,this.activeSyncTimer=0,this.skipVideoUpdate=!1}async load(){await super.load(),await this.loadVideo(),this.configureKeyframes()}update(e,t){if(super.update(e,t),this.skipVideoUpdate)return;const{trim:i=0}=this.clipConfiguration.asset;if(this.syncTimer+=t,!this.texture)return;const a=this.getPlaybackTime(),r=this.edit.isPlaying&&this.isActive();r&&(this.isPlaying||(this.isPlaying=!0,this.activeSyncTimer=0,this.texture.source.resource.currentTime=a+i,this.texture.source.resource.play().catch(console.error)),this.texture.source.resource.volume!==this.getVolume()&&(this.texture.source.resource.volume=this.getVolume()),this.activeSyncTimer+=t,this.activeSyncTimer>1e3&&(this.activeSyncTimer=0,Math.abs(this.texture.source.resource.currentTime-i-a)>.3&&(this.texture.source.resource.currentTime=a+i,this.edit.recordSyncCorrection()))),!r&&this.isPlaying&&(this.isPlaying=!1,this.texture.source.resource.pause());const n=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&n&&(this.syncTimer=0,this.texture.source.resource.currentTime=a+i)}dispose(){super.dispose(),this.disposeVideo()}getSize(){return this.clipConfiguration.width&&this.clipConfiguration.height?{width:this.clipConfiguration.width,height:this.clipConfiguration.height}:{width:this.sprite?.width??0,height:this.sprite?.height??0}}supportsEdgeResize(){return!0}async reloadAsset(){this.skipVideoUpdate=!0,this.disposeVideo(),await this.loadVideo(),this.isPlaying=!1,this.syncTimer=0,this.activeSyncTimer=0,this.skipVideoUpdate=!1}async loadVideo(){const e=this.clipConfiguration.asset,{src:t}=e;if(t.endsWith(".mov"))throw new Error(`Video source '${t}' is not supported. .mov files cannot be played in the browser. Please convert to .webm or .mp4 first.`);const i=`${t}${t.includes("?")?"&":"?"}x-cors=1`,a={src:i,data:{autoPlay:!1,muted:!1}},r=await this.edit.assetLoader.loadVideoUnique(i,a);if(!r||!(r.source instanceof G.VideoSource))throw new Error(`Invalid video source '${t}'.`);r.source.alphaMode="no-premultiply-alpha",this.texture=this.createCroppedTexture(r);const n=this.texture.source.resource;n instanceof HTMLVideoElement&&n.readyState<2&&await new Promise(o=>{const l=()=>{n.removeEventListener("loadeddata",l),o()};n.addEventListener("loadeddata",l),n.readyState>=2&&o()}),this.sprite=new G.Sprite(this.texture),this.contentContainer.addChild(this.sprite)}disposeVideo(){this.texture?.source?.resource&&(this.texture.source.resource.pause(),this.texture.source.resource.src="",this.texture.source.resource.load()),this.sprite&&(this.contentContainer.removeChild(this.sprite),this.sprite.destroy(),this.sprite=null),this.texture&&(this.texture.destroy(!0),this.texture=null)}getVolume(){return this.volumeKeyframeBuilder.getValue(this.getPlaybackTime())}getCurrentDrift(){if(!this.texture?.source?.resource)return 0;const{trim:e=0}=this.clipConfiguration.asset,t=this.texture.source.resource.currentTime,i=this.getPlaybackTime();return Math.abs(t-e-i)}createCroppedTexture(e){const t=this.clipConfiguration.asset;if(!t.crop)return e;const i=e.width,a=e.height;if(i<=0||a<=0)return e;const r=Math.floor((t.crop?.left??0)*i),n=Math.floor((t.crop?.right??0)*i),o=Math.floor((t.crop?.top??0)*a),l=Math.floor((t.crop?.bottom??0)*a),c=r,d=o,u=i-r-n,f=a-o-l,p=new G.Rectangle(c,d,u,f);return new G.Texture({source:e.source,frame:p})}}class np{static create(e,t){if(!t.asset?.type)throw new Error("Invalid clip configuration: missing asset type");switch(t.asset.type){case"text":return new ba(e,t);case"rich-text":return new Is(e,t);case"shape":return new bI(e,t);case"html":return new Ug(e,t);case"image":return new Zg(e,t);case"video":return new CI(e,t);case"audio":return new vg(e,t);case"luma":return new Jg(e,t);case"caption":return new Hr(e,t);case"svg":return new Us(e,t);case"text-to-image":return new vI(e,t);case"image-to-video":return new Qg(e,t);case"text-to-speech":return new xI(e,t);default:throw new Error(`Unsupported asset type: ${t.asset.type}`)}}static cleanup(){ba.resetFontCache()}}function ac(s,e,t,i){const a=new Map,r=`alias://${t}`;for(let n=0;n<s.getTrackCount();n+=1){const o=s.getClipsInTrack(n);for(let l=0;l<o.length;l+=1)if(!i?.has(`${n}:${l}`)){const c=o[l],d=c.id,u=e.timeline.tracks[n]?.clips[l];let f=!1;const p={};if(c.start===r&&(p.start=c.start,f=!0),c.length===r&&(p.length=c.length,f=!0),f&&d&&u){a.set(d,p);const g={};p.start&&(g.start=u.start),p.length&&(g.length=u.length),s.updateClip(n,l,g)}}}return a}function kI(s,e,t,i){const a=new Map;for(const r of t){const n=ac(s,e,r,i);for(const[o,l]of n){const c=a.get(o);c?a.set(o,{...c,...l}):a.set(o,l)}}return a}function rc(s,e){for(const[t,i]of e){const a=s.getClipById(t);if(a){const r={};i.start&&(r.start=i.start),i.length&&(r.length=i.length),s.updateClip(a.trackIndex,a.clipIndex,r)}}}function SI(s){const e=[];for(const t of s){const{alias:i}=t;i&&e.push(i)}return e}const we=()=>({status:"success"}),Ne=s=>({status:"noop",message:s});class AI{constructor(e,t){this.trackIdx=e,this.clip=t}name="addClip";addedClipId;convertedReferences;execute(e){if(!e)throw new Error("AddClipCommand.execute: context is required");const t=e.getDocument();if(!t)throw new Error("AddClipCommand.execute: no document");const i=e.documentAddClip(this.trackIdx,this.clip);this.addedClipId=i.id,this.convertedReferences&&this.convertedReferences.size>0&&rc(t,this.convertedReferences),e.resolve(),e.updateDuration();const n=e.getDocumentTrack(this.trackIdx)?.clips?.findIndex(o=>o.id===this.addedClipId)??-1;return e.emitEvent(Z.ClipAdded,{trackIndex:this.trackIdx,clipIndex:n}),we()}undo(e){if(!e)throw new Error("AddClipCommand.undo: context is required");if(!this.addedClipId)return Ne("No clip ID stored");const t=e.getDocument();if(!t)throw new Error("AddClipCommand.undo: no document");const a=e.getDocumentTrack(this.trackIdx)?.clips,r=a?.findIndex(o=>o.id===this.addedClipId)??-1;if(r===-1)return Ne(`Clip ${this.addedClipId} not found in track ${this.trackIdx}`);const n=a?.[r]?.alias;if(n){const o=new Set([`${this.trackIdx}:${r}`]);this.convertedReferences=ac(t,e.getEditState(),n,o)}return e.documentRemoveClip(this.trackIdx,r),e.resolve(),e.updateDuration(),e.emitEvent(Z.ClipDeleted,{trackIndex:this.trackIdx,clipIndex:r}),we()}dispose(){this.addedClipId=void 0,this.convertedReferences=void 0}}class op{constructor(e){this.trackIdx=e}name="addTrack";execute(e){if(!e)throw new Error("AddTrackCommand.execute: context is required");const t=e.getDocument();if(!t)throw new Error("AddTrackCommand.execute: document is required");return t.addTrack(this.trackIdx),e.resolve(),e.updateDuration(),e.emitEvent(Z.TrackAdded,{trackIndex:this.trackIdx,totalTracks:t.getTrackCount()}),we()}undo(e){if(!e)throw new Error("AddTrackCommand.undo: context is required");const t=e.getDocument();if(!t)throw new Error("AddTrackCommand.undo: document is required");return t.removeTrack(this.trackIdx),e.resolve(),e.updateDuration(),we()}dispose(){}}class nc{constructor(e){this.trackIdx=e}name="deleteTrack";deletedClips=[];convertedReferences;execute(e){if(!e)throw new Error("DeleteTrackCommand.execute: context is required");const t=e.getDocument();if(!t)throw new Error("DeleteTrackCommand: no document");if(t.getTrackCount()<=1)return Ne("Cannot delete the last track");const i=t.getTrack(this.trackIdx);i&&(this.deletedClips=i.clips.map(r=>structuredClone(r)));const a=SI(this.deletedClips);if(a.length>0){const r=new Set;for(let n=0;n<this.deletedClips.length;n+=1)r.add(`${this.trackIdx}:${n}`);this.convertedReferences=kI(t,e.getEditState(),a,r)}return t.removeTrack(this.trackIdx),e.resolve(),e.updateDuration(),e.emitEvent(Z.TrackRemoved,{trackIndex:this.trackIdx}),we()}undo(e){if(!e)throw new Error("DeleteTrackCommand.undo: context is required");const t=e.getDocument();if(!t)throw new Error("DeleteTrackCommand.undo: no document");t.addTrack(this.trackIdx);for(let i=0;i<this.deletedClips.length;i+=1)t.addClip(this.trackIdx,this.deletedClips[i],i);return this.convertedReferences&&this.convertedReferences.size>0&&rc(t,this.convertedReferences),e.resolve(),e.updateDuration(),e.emitEvent(Z.TrackAdded,{trackIndex:this.trackIdx,totalTracks:t.getTrackCount()}),we()}dispose(){this.deletedClips=[],this.convertedReferences=void 0}}class oc{constructor(e,t){this.trackIdx=e,this.clipIdx=t}name="deleteClip";deletedClipConfig;deletedClipId;deleteTrackCommand;trackWasDeleted=!1;storedBindings;convertedReferences;execute(e){if(!e)throw new Error("DeleteClipCommand.execute: context is required");const t=e.getDocument();if(!t)throw new Error("DeleteClipCommand: no document");const i=t.getClip(this.trackIdx,this.clipIdx);if(!i)return Ne(`No clip at track ${this.trackIdx}, index ${this.clipIdx}`);if(this.deletedClipConfig=structuredClone(i),this.deletedClipId=i.id,this.deletedClipId){const o=e.getClipBindings(this.deletedClipId);this.storedBindings=o?new Map(o):void 0,t.clearClipBindings(this.deletedClipId)}const a=i.alias;if(a){const o=new Set([`${this.trackIdx}:${this.clipIdx}`]);this.convertedReferences=ac(t,e.getEditState(),a,o)}e.clearClipError(this.trackIdx,this.clipIdx);const r=e.getSelectedClip();r&&this.deletedClipId&&r.clipId===this.deletedClipId&&(e.setSelectedClip(null),e.emitEvent(Z.SelectionCleared)),e.documentRemoveClip(this.trackIdx,this.clipIdx);const n=t.getTrack(this.trackIdx);return n&&n.clips.length===0&&(this.deleteTrackCommand=new nc(this.trackIdx),this.deleteTrackCommand.execute(e).status==="success"&&(this.trackWasDeleted=!0)),e.resolve(),e.updateDuration(),e.emitEvent(Z.ClipDeleted,{trackIndex:this.trackIdx,clipIndex:this.clipIdx}),we()}undo(e){if(!e)throw new Error("DeleteClipCommand.undo: context is required");if(!this.deletedClipConfig)return Ne("No deleted clip config");const t=e.getDocument();if(!t)throw new Error("DeleteClipCommand.undo: no document");this.trackWasDeleted&&t.addTrack(this.trackIdx);const a=e.documentAddClip(this.trackIdx,this.deletedClipConfig,this.clipIdx).id;return a&&this.storedBindings&&this.storedBindings.size>0&&t.setClipBindingsForClip(a,this.storedBindings),this.convertedReferences&&this.convertedReferences.size>0&&rc(t,this.convertedReferences),e.resolve(),e.updateDuration(),this.trackWasDeleted&&(e.emitEvent(Z.TrackAdded,{trackIndex:this.trackIdx,totalTracks:t.getTrackCount()}),this.trackWasDeleted=!1),e.emitEvent(Z.ClipRestored,{trackIndex:this.trackIdx,clipIndex:this.clipIdx}),we()}dispose(){this.deletedClipConfig=void 0,this.deletedClipId=void 0,this.deleteTrackCommand=void 0,this.storedBindings=void 0,this.convertedReferences=void 0}}class II{constructor(e){this.aspectRatio=e}name="setOutputAspectRatio";previousAspectRatio;execute(e){if(!e)throw new Error("SetOutputAspectRatioCommand requires context");return this.previousAspectRatio=e.getOutputAspectRatio(),e.setOutputAspectRatio(this.aspectRatio),we()}undo(e){if(!e)throw new Error("SetOutputAspectRatioCommand requires context");return this.previousAspectRatio===void 0?Ne("No previous aspect ratio stored"):(e.setOutputAspectRatio(this.previousAspectRatio),we())}dispose(){this.previousAspectRatio=void 0}}class TI{constructor(e){this.destinations=e}name="setOutputDestinations";previousDestinations;execute(e){if(!e)throw new Error("SetOutputDestinationsCommand requires context");return this.previousDestinations=e.getOutputDestinations(),e.setOutputDestinations(this.destinations),we()}undo(e){if(!e)throw new Error("SetOutputDestinationsCommand requires context");return this.previousDestinations===void 0?Ne("No previous destinations stored"):(e.setOutputDestinations(this.previousDestinations),we())}dispose(){this.previousDestinations=void 0}}class EI{constructor(e){this.format=e}name="setOutputFormat";previousFormat;execute(e){if(!e)throw new Error("SetOutputFormatCommand requires context");return this.previousFormat=e.getOutputFormat(),e.setOutputFormat(this.format),we()}undo(e){if(!e)throw new Error("SetOutputFormatCommand requires context");return this.previousFormat===void 0?Ne("No previous format stored"):(e.setOutputFormat(this.previousFormat),we())}dispose(){this.previousFormat=void 0}}class NI{constructor(e){this.fps=e}name="setOutputFps";previousFps;execute(e){if(!e)throw new Error("SetOutputFpsCommand requires context");return this.previousFps=e.getOutputFps(),e.setOutputFps(this.fps),we()}undo(e){if(!e)throw new Error("SetOutputFpsCommand requires context");return this.previousFps===void 0?Ne("No previous FPS stored"):(e.setOutputFps(this.previousFps),we())}dispose(){this.previousFps=void 0}}class PI{constructor(e){this.resolution=e}name="setOutputResolution";previousResolution;execute(e){if(!e)throw new Error("SetOutputResolutionCommand requires context");return this.previousResolution=e.getOutputResolution(),e.setOutputResolution(this.resolution),we()}undo(e){if(!e)throw new Error("SetOutputResolutionCommand requires context");return this.previousResolution===void 0?Ne("No previous resolution stored"):(e.setOutputResolution(this.previousResolution),we())}dispose(){this.previousResolution=void 0}}class FI{constructor(e,t){this.width=e,this.height=t}name="setOutputSize";previousSize;execute(e){if(!e)throw new Error("SetOutputSizeCommand requires context");return this.previousSize=e.getOutputSize(),e.setOutputSize(this.width,this.height),we()}undo(e){if(!e)throw new Error("SetOutputSizeCommand requires context");return this.previousSize?(e.setOutputSize(this.previousSize.width,this.previousSize.height),we()):Ne("No previous size stored")}dispose(){this.previousSize=void 0}}class VI{constructor(e){this.color=e}name="setTimelineBackground";previousColor;execute(e){if(!e)throw new Error("SetTimelineBackgroundCommand requires context");return this.previousColor=e.getTimelineBackground(),e.setTimelineBackground(this.color),we()}undo(e){if(!e)throw new Error("SetTimelineBackgroundCommand requires context");return this.previousColor===void 0?Ne("No previous color stored"):(e.setTimelineBackground(this.previousColor),we())}dispose(){this.previousColor=void 0}}function Re(s){const{id:e,...t}=s;return t}function Qn(s){return!!(s&&typeof s=="object"&&!Array.isArray(s))}function lc(s,e){const t={...s};return Qn(s)&&Qn(e)&&Object.keys(e).forEach(i=>{if(i==="__proto__"||i==="constructor"||i==="prototype")return;const a=e[i],r=s[i];Qn(a)?i in s&&Qn(r)?t[i]=lc(r,a):t[i]=lc({},a):t[i]=a}),t}function Zs(s,e,t){const i=e.split(".");let a=s;for(let r=0;r<i.length-1;r+=1){if(a==null||typeof a!="object")return;a=a[i[r]]}a!=null&&typeof a=="object"&&(a[i[i.length-1]]=t)}function wa(s,e){const t=e.split(".");let i=s;for(const a of t){if(i==null||typeof i!="object")return;i=i[a]}return i}function lp(s,e=50){let t=null,i=null,a=0;return{call:(...l)=>{const c=Date.now(),d=c-a;i=l,d>=e?(a=c,s(...l)):t||(t=setTimeout(()=>{t=null,a=Date.now(),i&&(s(...i),i=null)},e-d))},flush:()=>{t&&(clearTimeout(t),t=null),i&&(a=Date.now(),s(...i),i=null)},cancel:()=>{t&&(clearTimeout(t),t=null),i=null}}}async function cp(s){try{new URL(s)}catch{return{valid:!1,error:"Invalid URL format"}}try{const e=await fetch(s,{method:"HEAD",mode:"cors"});return e.ok?{valid:!0}:{valid:!1,error:`URL returned ${e.status} ${e.statusText}`}}catch(e){return{valid:!1,error:e instanceof Error?e.message:"URL not accessible"}}}class cc{constructor(e,t,i){this.initialClipConfig=e,this.finalClipConfig=t,this.trackIndex=i?.trackIndex??-1,this.clipIndex=i?.clipIndex??-1}name="setUpdatedClip";clipId=null;storedInitialConfig=null;storedFinalConfig=null;storedInitialBindings=new Map;previousDocClip=null;trackIndex;clipIndex;async execute(e){if(!e)throw new Error("SetUpdatedClipCommand.execute: context is required");const t=e.getDocument();if(!t)throw new Error("SetUpdatedClipCommand.execute: document is required");const i=e.getClipAt(this.trackIndex,this.clipIndex);if(!i)return Ne(`Invalid clip at ${this.trackIndex}/${this.clipIndex}`);this.clipId=i.clipId,this.storedInitialConfig||(this.storedInitialConfig=this.initialClipConfig?structuredClone(this.initialClipConfig):structuredClone(i.clipConfiguration)),this.storedFinalConfig||(this.storedFinalConfig=this.finalClipConfig?structuredClone(this.finalClipConfig):structuredClone(i.clipConfiguration));const a=e.getDocumentClip(this.trackIndex>=0?this.trackIndex:i.layer-1,this.clipIndex>=0?this.clipIndex:e.getTracks()[i.layer-1]?.indexOf(i)??-1);this.previousDocClip=a?structuredClone(a):null;const r=this.clipId?e.getClipBindings(this.clipId):void 0;this.storedInitialBindings=r?new Map(r):new Map;const n=this.trackIndex>=0?this.trackIndex:i.layer-1,o=this.clipIndex>=0?this.clipIndex:e.getTracks()[n]?.indexOf(i)??-1,l=this.storedFinalConfig??this.finalClipConfig;l&&t.replaceClipProperties(n,o,l),e.resolve();const c=e.getClipAt(n,o);for(const[w,{resolvedValue:C}]of this.storedInitialBindings)(c?wa(c.clipConfiguration,w):void 0)!==C&&this.clipId&&e.removeClipBinding(this.clipId,w);const d=this.storedInitialConfig??this.initialClipConfig,u=this.storedFinalConfig??this.finalClipConfig,f=d?.asset,p=u?.asset;if(f?.src!==p?.src){const w=e.getClipAt(n,o);w&&w.getTimingIntent().length==="auto"&&await e.resolveClipAutoLength(w)}const g=e.getDocumentClip(n,o);if(!this.previousDocClip||!g)throw new Error(`SetUpdatedClipCommand: document clip not found after mutation at ${n}/${o}`);return e.emitEvent(Z.ClipUpdated,{previous:{clip:Re(this.previousDocClip),trackIndex:n,clipIndex:o},current:{clip:Re(g),trackIndex:n,clipIndex:o}}),we()}async undo(e){if(!e)throw new Error("SetUpdatedClipCommand.undo: context is required");const t=this.storedInitialConfig??this.initialClipConfig;if(!t)return Ne("No stored initial config");const i=e.getDocument();if(!i)throw new Error("SetUpdatedClipCommand.undo: document is required");const a=this.clipId?e.getPlayerByClipId(this.clipId):e.getClipAt(this.trackIndex,this.clipIndex);if(!a)return Ne("Clip not found for undo");const r=this.trackIndex>=0?this.trackIndex:a.layer-1,n=this.clipIndex>=0?this.clipIndex:e.getTracks()[r]?.indexOf(a)??-1,o=structuredClone(e.getDocumentClip(r,n));if(i.replaceClipProperties(r,n,t),e.resolve(),this.clipId){const f=new Map(this.storedInitialBindings);f.size>0?e.getDocument()?.setClipBindingsForClip(this.clipId,f):e.getDocument()?.clearClipBindings(this.clipId)}const c=(this.storedFinalConfig??this.finalClipConfig)?.asset,d=t?.asset;if(c?.src!==d?.src){const f=e.getClipAt(r,n);f&&f.getTimingIntent().length==="auto"&&await e.resolveClipAutoLength(f)}const u=e.getDocumentClip(r,n);if(!o||!u)throw new Error(`SetUpdatedClipCommand: document clip not found after undo at ${r}/${n}`);return e.emitEvent(Z.ClipUpdated,{previous:{clip:Re(o),trackIndex:r,clipIndex:n},current:{clip:Re(u),trackIndex:r,clipIndex:n}}),we()}dispose(){this.clipId=null,this.storedInitialConfig=null,this.storedFinalConfig=null,this.storedInitialBindings.clear(),this.previousDocClip=null}}class _I{constructor(e,t,i){this.trackIndex=e,this.clipIndex=t,this.splitTime=i}name="SplitClip";originalClipConfig=null;rightClipId=null;execute(e){const t=e.getDocument();if(!t)throw new Error("Cannot split clip: no document");const i=t.getClip(this.trackIndex,this.clipIndex);if(!i)return Ne(`No clip at ${this.trackIndex}/${this.clipIndex}`);const a=e.getClipAt(this.trackIndex,this.clipIndex),r=a?.clipConfiguration.start??0,n=a?.clipConfiguration.length??0,o=.1,l=this.splitTime-r;if(l<=o||l>=n-o)return Ne("Split point too close to clip boundaries");this.originalClipConfig=structuredClone(i);const c=l,d=structuredClone(i);if(i.start==="auto"?d.start="auto":d.start=r+l,d.length=n-l,i.asset&&(i.asset.type==="video"||i.asset.type==="audio")){const f=i.asset.trim||0;d.asset&&(d.asset.type==="video"||d.asset.type==="audio")&&(d.asset.trim=f+l)}e.documentUpdateClip(this.trackIndex,this.clipIndex,{length:c});const u=e.documentAddClip(this.trackIndex,d,this.clipIndex+1);return this.rightClipId=u.id??null,e.resolve(),e.updateDuration(),e.emitEvent(Z.ClipSplit,{trackIndex:this.trackIndex,originalClipIndex:this.clipIndex,newClipIndex:this.clipIndex+1}),we()}undo(e){return this.originalClipConfig?(e.documentRemoveClip(this.trackIndex,this.clipIndex+1),e.documentUpdateClip(this.trackIndex,this.clipIndex,this.originalClipConfig),e.resolve(),e.updateDuration(),e.emitEvent(Z.ClipDeleted,{trackIndex:this.trackIndex,clipIndex:this.clipIndex+1}),we()):Ne("No original clip config stored")}dispose(){this.originalClipConfig=null,this.rightClipId=null}}class MI{constructor(e,t,i){this.trackIndex=e,this.clipIndex=t,this.params=i}name="UpdateClipTiming";originalStart;originalLength;clipId;execute(e){if(!e)throw new Error("UpdateClipTimingCommand.execute: context is required");const t=e.getDocument();if(!t)throw new Error("UpdateClipTimingCommand.execute: document is required");const a=e.getDocumentTrack(this.trackIndex)?.clips[this.clipIndex];if(!a)return Ne(`Invalid clip at ${this.trackIndex}/${this.clipIndex}`);const r=e.getClipAt(this.trackIndex,this.clipIndex);if(!r)return Ne(`Player not found at ${this.trackIndex}/${this.clipIndex}`);this.originalStart=a.start,this.originalLength=a.length,this.clipId=r.clipId??void 0;const n=structuredClone(a),o={};this.params.start!==void 0&&(o.start=this.params.start),this.params.length!==void 0&&(o.length=this.params.length),t.updateClip(this.trackIndex,this.clipIndex,o),this.clipId?e.resolveClip(this.clipId):e.resolve(),o.length==="auto"&&e.resolveClipAutoLength(r).then(()=>{e.updateDuration(),e.propagateTimingChanges(this.trackIndex,this.clipIndex)}),e.updateDuration();const l=e.getDocumentClip(this.trackIndex,this.clipIndex);if(!l)throw new Error(`UpdateClipTimingCommand: document clip not found after mutation at ${this.trackIndex}/${this.clipIndex}`);return e.emitEvent(Z.ClipUpdated,{previous:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:Re(n)},current:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:Re(l)}}),e.propagateTimingChanges(this.trackIndex,this.clipIndex),we()}undo(e){if(!e)throw new Error("UpdateClipTimingCommand.undo: context is required");if(this.originalStart===void 0&&this.originalLength===void 0)throw new Error("UpdateClipTimingCommand.undo: no original values");const t=e.getDocument();if(!t)throw new Error("UpdateClipTimingCommand.undo: document is required");const i=e.getClipAt(this.trackIndex,this.clipIndex);if(!i)throw new Error("UpdateClipTimingCommand.undo: player not found");const a=structuredClone(e.getDocumentClip(this.trackIndex,this.clipIndex)),r={};this.originalStart!==void 0&&(r.start=this.originalStart),this.originalLength!==void 0&&(r.length=this.originalLength),t.updateClip(this.trackIndex,this.clipIndex,r),this.clipId?e.resolveClip(this.clipId):e.resolve(),this.originalLength==="auto"&&e.resolveClipAutoLength(i).then(()=>{e.updateDuration(),e.propagateTimingChanges(this.trackIndex,this.clipIndex)}),e.updateDuration();const n=e.getDocumentClip(this.trackIndex,this.clipIndex);if(!a||!n)throw new Error(`UpdateClipTimingCommand: document clip not found after undo at ${this.trackIndex}/${this.clipIndex}`);return e.emitEvent(Z.ClipUpdated,{previous:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:Re(a)},current:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:Re(n)}}),e.propagateTimingChanges(this.trackIndex,this.clipIndex),we()}}class LI{constructor(e,t,i){this.trackIndex=e,this.clipIndex=t,this.newText=i}name="updateTextContent";clipId=null;previousText="";previousDocClip;execute(e){if(!e)throw new Error("UpdateTextContentCommand.execute: context is required");const t=e.getDocument();if(!t)throw new Error("UpdateTextContentCommand.execute: document is required");const i=e.getClipAt(this.trackIndex,this.clipIndex);if(!i)return Ne(`Invalid clip at ${this.trackIndex}/${this.clipIndex}`);const a=t.getClip(this.trackIndex,this.clipIndex);if(!a)return Ne("Clip not found in document");this.clipId=i.clipId,this.previousDocClip=structuredClone(a);const r=a.asset;this.previousText=r&&"text"in r?r.text??"":"";const o={...a.asset,text:this.newText};t.updateClip(this.trackIndex,this.clipIndex,{asset:o}),this.clipId?e.resolveClip(this.clipId):e.resolve();const l=e.getDocumentClip(this.trackIndex,this.clipIndex);if(!this.previousDocClip||!l)throw new Error(`UpdateTextContentCommand: document clip not found after mutation at ${this.trackIndex}/${this.clipIndex}`);return e.emitEvent(Z.ClipUpdated,{previous:{clip:Re(this.previousDocClip),trackIndex:this.trackIndex,clipIndex:this.clipIndex},current:{clip:Re(l),trackIndex:this.trackIndex,clipIndex:this.clipIndex}}),we()}undo(e){if(!e)throw new Error("UpdateTextContentCommand.undo: context is required");const t=e.getDocument();if(!t)throw new Error("UpdateTextContentCommand.undo: document is required");const i=structuredClone(e.getDocumentClip(this.trackIndex,this.clipIndex)),a=t.getClip(this.trackIndex,this.clipIndex);if(!a)return Ne("Clip not found for undo");const n={...a.asset,text:this.previousText};t.updateClip(this.trackIndex,this.clipIndex,{asset:n}),this.clipId?e.resolveClip(this.clipId):e.resolve();const o=e.getDocumentClip(this.trackIndex,this.clipIndex);if(this.previousDocClip){if(!i||!o)throw new Error(`UpdateTextContentCommand: document clip not found after undo at ${this.trackIndex}/${this.clipIndex}`);e.emitEvent(Z.ClipUpdated,{previous:{clip:Re(i),trackIndex:this.trackIndex,clipIndex:this.clipIndex},current:{clip:Re(o),trackIndex:this.trackIndex,clipIndex:this.clipIndex}})}return we()}dispose(){this.clipId=null,this.previousDocClip=void 0}}class dc{events;constructor(){this.events={}}on(e,t){return this.events[e]||(this.events[e]=new Set),this.events[e].add(t),()=>this.off(e,t)}once(e,t){const i=a=>{this.off(e,i),t(a)};return this.on(e,i)}off(e,t){this.events[e]&&(this.events[e].delete(t),!(this.events[e].size>0)&&delete this.events[e])}clear(e){delete this.events[e]}emit(e,...t){if(!this.events[e])return;const i=t[0];for(const a of this.events[e])a(i)}}const dp=.5,BI=1/30;class OI{constructor(e,t,i){this.getCanvas=e,this.getTracks=t,this.events=i,this.onClipChangedBound=()=>this.rebuildLumaMasksIfNeeded(),this.onPlayerLoadedBound=a=>this.onPlayerLoaded(a)}activeLumaMasks=[];pendingMaskCleanup=[];onClipChangedBound;onPlayerLoadedBound;initialize(){this.setupEventListeners()}update(){this.updateLumaMasks(),this.processPendingMaskCleanup()}getActiveMaskCount(){return this.activeLumaMasks.length}dispose(){this.removeEventListeners();for(const e of this.activeLumaMasks)e.tempContainer.destroy({children:!0}),e.maskSprite.destroy({texture:!0});this.activeLumaMasks=[];for(const e of this.pendingMaskCleanup)try{e.maskSprite.parent?.removeChild(e.maskSprite),e.maskSprite.destroy({texture:!0})}catch{}this.pendingMaskCleanup=[]}cleanupForPlayer(e){const t=this.activeLumaMasks.findIndex(a=>a.lumaPlayer===e);if(t===-1)return;const i=this.activeLumaMasks[t];i.contentClip&&(i.contentClip.getContentContainer().mask=null),i.maskSprite.parent?.removeChild(i.maskSprite),i.tempContainer.destroy({children:!0}),this.activeLumaMasks.splice(t,1),this.pendingMaskCleanup.push({maskSprite:i.maskSprite,frameCount:0})}onPlayerLoaded(e){const{player:t,trackIndex:i}=e;if(t.playerType!==it.Luma)return;const a=t,r=a.getSprite();if(!r?.texture){console.warn("PlayerLoaded fired for luma player before texture ready");return}const n=this.getTracks();if(i>=n.length)return;const l=n[i].filter(d=>d.playerType!==it.Luma);l.length===0||this.activeLumaMasks.find(d=>d.lumaPlayer===a)||(this.setupLumaMask(a,r.texture,l[0]),a.getContainer().parent?.removeChild(a.getContainer()))}setupLumaMask(e,t,i){const a=this.getCanvas();if(!a)return;const{renderer:r}=a.application,{width:n,height:o}=i.getSize(),l=new G.Container,c=new G.Sprite(t);c.width=n,c.height=o;const d=new G.ColorMatrixFilter;d.negative(!1),c.filters=[d],l.addChild(c);const u=r.generateTexture({target:l,resolution:dp}),f=new G.Sprite(u);i.getContainer().addChild(f);const p=i.getContentContainer();p.mask=f,this.activeLumaMasks.push({lumaPlayer:e,maskSprite:f,tempContainer:l,contentClip:i,lastVideoTime:-1})}updateLumaMasks(){const e=this.getCanvas();if(!e)return;const{renderer:t}=e.application;for(const i of this.activeLumaMasks)if(i.lumaPlayer.isVideoSource()){const a=i.lumaPlayer.getVideoCurrentTime();if(Math.abs(a-i.lastVideoTime)>=BI){i.lastVideoTime=a;const n=i.maskSprite.texture;i.maskSprite.texture=t.generateTexture({target:i.tempContainer,resolution:dp}),n.destroy(!0)}}}setupEventListeners(){this.events.on(Be.PlayerLoaded,this.onPlayerLoadedBound),this.events.on(Z.ClipUpdated,this.onClipChangedBound)}removeEventListeners(){this.events.off(Be.PlayerLoaded,this.onPlayerLoadedBound),this.events.off(Z.ClipUpdated,this.onClipChangedBound)}processPendingMaskCleanup(){for(let e=this.pendingMaskCleanup.length-1;e>=0;e-=1){const t=this.pendingMaskCleanup[e];if(t.frameCount+=1,t.frameCount>=3){try{t.maskSprite.parent?.removeChild(t.maskSprite),t.maskSprite.destroy({texture:!0})}catch{}this.pendingMaskCleanup.splice(e,1)}}}rebuildLumaMasksIfNeeded(){if(!this.getCanvas())return;const t=this.getTracks();for(let i=0;i<t.length;i+=1){const a=t[i],r=a.find(l=>l.playerType===it.Luma),n=a.filter(l=>l.playerType!==it.Luma);r&&r.getContainer().parent?.removeChild(r.getContainer());const o=r&&this.activeLumaMasks.find(l=>l.lumaPlayer===r);if(r&&!o&&n.length>0){const l=r.getSprite();l?.texture&&this.setupLumaMask(r,l.texture,n[0])}}}}function RI(s){return{find:s.name,replace:s.defaultValue}}function DI(s){const e=typeof s.replace=="string"?s.replace:JSON.stringify(s.replace);return{name:s.find,defaultValue:e}}const zI=/\{\{\s*([A-Z_0-9]+)\s*\}\}/gi,uc=/\{\{\s*[A-Z_0-9]+\s*\}\}/i;class UI{fields=new Map;events;constructor(e){this.events=e}register(e,t){this.fields.set(e.name,e),t?.silent||this.events.emit(Z.MergeFieldChanged,{fields:this.getAll()})}remove(e,t){const i=this.fields.delete(e);return i&&!t?.silent&&this.events.emit(Z.MergeFieldChanged,{fields:this.getAll()}),i}get(e){return this.fields.get(e)}getAll(){return Array.from(this.fields.values())}clear(){this.fields.clear()}resolve(e){return!e||this.fields.size===0?e:e.replace(zI,(t,i)=>this.fields.get(i)?.defaultValue??t)}resolveToNumber(e){if(!this.isMergeFieldTemplate(e))return null;const t=this.resolve(e),i=parseFloat(t);return Number.isFinite(i)?i:null}hasUnresolved(e){if(!e)return!1;const t=this.resolve(e);return uc.test(t)}extractFieldName(e){if(!e)return null;const t=uc.exec(e);if(!t)return null;const i=t[0].match(/\{\{\s*([A-Z_0-9]+)\s*\}\}/i);return i?i[1]:null}isMergeFieldTemplate(e){return uc.test(e)}createTemplate(e){return`{{ ${e} }}`}toSerializedArray(){return this.getAll().map(RI)}loadFromSerialized(e){this.fields.clear();for(const t of e){const i=DI(t);this.fields.set(t.find,i)}}generateUniqueName(e){const t=new Set(this.fields.keys());let i=1;for(;t.has(`${e}_${i}`);)i+=1;return`${e}_${i}`}}const ZI={preview:{width:512,height:288},mobile:{width:640,height:360},sd:{width:1024,height:576},hd:{width:1280,height:720},1080:{width:1920,height:1080},"4k":{width:3840,height:2160}};function Jn(s,e="16:9"){const t=ZI[s];if(!t)throw new Error(`Unknown resolution: ${s}`);switch(e){case"16:9":return{width:t.width,height:t.height};case"9:16":return{width:t.height,height:t.width};case"1:1":return{width:t.height,height:t.height};case"4:5":return{width:Math.round(t.height*4/5),height:t.height};case"4:3":return{width:Math.round(t.height*4/3),height:t.height};default:throw new Error(`Unknown aspectRatio: ${e}`)}}class WI{constructor(e){this.edit=e}setSize(e,t){dx.parse({width:e,height:t});const i={width:e,height:t};this.edit.size=i;const a=this.edit.getResolvedEdit();a&&(a.output={...a.output,size:i},delete a.output.resolution,delete a.output.aspectRatio);const r=this.edit.getDocument();r?.setSize(i),r?.clearResolution(),r?.clearAspectRatio(),this.edit.updateCanvasForSize(),this.edit.getInternalEvents().emit(Z.OutputResized,i)}getSize(){return this.edit.size}setFps(e){const t=fx.parse(e),i=this.edit.getResolvedEdit();i&&(i.output={...i.output,fps:t}),this.edit.getDocument()?.setFps(t),this.edit.getInternalEvents().emit(Z.OutputFpsChanged,{fps:e})}getFps(){return this.edit.getResolvedEdit()?.output?.fps??30}setFormat(e){const t=ux.parse(e),i=this.edit.getResolvedEdit();i&&(i.output={...i.output,format:t}),this.edit.getDocument()?.setFormat(t),this.edit.getInternalEvents().emit(Z.OutputFormatChanged,{format:t})}getFormat(){return this.edit.getResolvedEdit()?.output?.format??"mp4"}setDestinations(e){const t=cx.array().parse(e),i=this.edit.getResolvedEdit();i&&(i.output={...i.output,destinations:t}),this.edit.getInternalEvents().emit(Z.OutputDestinationsChanged,{destinations:t})}getDestinations(){return this.edit.getResolvedEdit()?.output?.destinations??[]}setResolution(e){const t=hx.parse(e),i=this.edit.getResolvedEdit(),a=i?.output?.aspectRatio??"16:9",r=Jn(t,a);this.edit.size=r,i&&(i.output={...i.output,resolution:t},delete i.output.size);const n=this.edit.getDocument();n?.setResolution(t),n?.clearSize(),this.edit.updateCanvasForSize(),this.edit.getInternalEvents().emit(Z.OutputResolutionChanged,{resolution:t}),this.edit.getInternalEvents().emit(Z.OutputResized,{width:r.width,height:r.height})}getResolution(){return this.edit.getResolvedEdit()?.output?.resolution}setAspectRatio(e){const t=px.parse(e),i=this.edit.getResolvedEdit(),a=i?.output?.resolution;if(!a){i&&(i.output={...i.output,aspectRatio:t}),this.edit.getDocument()?.setAspectRatio(t),this.edit.getInternalEvents().emit(Z.OutputAspectRatioChanged,{aspectRatio:t});return}const r=Jn(a,t);this.edit.size=r,i&&(i.output={...i.output,aspectRatio:t},delete i.output.size);const n=this.edit.getDocument();n?.setAspectRatio(t),n?.clearSize(),this.edit.updateCanvasForSize(),this.edit.getInternalEvents().emit(Z.OutputAspectRatioChanged,{aspectRatio:t}),this.edit.getInternalEvents().emit(Z.OutputResized,{width:r.width,height:r.height})}getAspectRatio(){return this.edit.getResolvedEdit()?.output?.aspectRatio}}class HI{constructor(e){this.edit=e}selectedClip=null;copiedClip=null;selectClip(e,t){const i=this.edit.getPlayerClip(e,t);if(i){this.selectedClip=i;const a=this.edit.getDocumentClip(e,t);a&&this.edit.getInternalEvents().emit(Z.ClipSelected,{clip:Re(a),trackIndex:e,clipIndex:t})}}selectPlayer(e){const t=this.findClipIndices(e);t&&this.selectClip(t.trackIndex,t.clipIndex)}clearSelection(){this.selectedClip=null,this.edit.getInternalEvents().emit(Z.SelectionCleared)}isClipSelected(e,t){if(!this.selectedClip)return!1;const i=this.selectedClip.layer-1,r=this.edit.getTracks()[i];if(!r)return!1;const n=r.indexOf(this.selectedClip);return e===i&&t===n}isPlayerSelected(e){return this.edit.isInExportMode()?!1:this.selectedClip===e}getSelectedClipInfo(){if(!this.selectedClip)return null;const e=this.selectedClip.layer-1,i=this.edit.getTracks()[e];if(!i)return null;const a=i.indexOf(this.selectedClip);return{trackIndex:e,clipIndex:a,player:this.selectedClip}}getSelectedClip(){return this.selectedClip}setSelectedClip(e){this.selectedClip=e}copyClip(e,t){const i=this.edit.getResolvedClip(e,t);i&&(this.copiedClip={trackIndex:e,clipConfiguration:structuredClone(i)},this.edit.getInternalEvents().emit(Z.ClipCopied,{trackIndex:e,clipIndex:t}))}pasteClip(){if(!this.copiedClip)return;const e=structuredClone(this.copiedClip.clipConfiguration);e.start=this.edit.playbackTime,delete e.id,this.edit.addClip(this.copiedClip.trackIndex,e)}hasCopiedClip(){return this.copiedClip!==null}findClipIndices(e){const t=this.edit.getTracks();for(let i=0;i<t.length;i+=1){const a=t[i].indexOf(e);if(a!==-1)return{trackIndex:i,clipIndex:a}}return null}}const GI=3;function qI(s){return new Promise(e=>{const t=document.createElement("video");t.preload="metadata",t.crossOrigin="anonymous",t.onloadedmetadata=()=>e(t.duration),t.onerror=()=>e(null),t.src=s})}async function up(s){const e=s;if(["video","audio","luma"].includes(e.type)&&e.src){const t=await qI(e.src);if(t!==null&&!Number.isNaN(t)){const i=e.trim??0;return t-i}}return GI}function fp(s,e,t){return e===0?0:t[s][e-1].getEnd()}function hp(s,e){return Math.max(0,e-s)}function fc(s){let e=0;for(const t of s)for(const i of t)i.getTimingIntent().length!=="end"&&(e=Math.max(e,i.getEnd()));return e}class YI{constructor(e){this.edit=e}cachedTimelineEnd=0;getTimelineEnd(){return this.cachedTimelineEnd}invalidateTimelineEndCache(){this.cachedTimelineEnd=0}async resolveAllTiming(){const e=this.edit.getTracks(),t=this.edit.getResolvedEdit();for(let r=0;r<e.length;r+=1){const n=e[r],o=t.timeline.tracks[r];for(let l=0;l<n.length;l+=1){const c=n[l],d=o?.clips[l];if(d){const u=c.getTimingIntent(),f=d.start;let p=d.length;u.length==="auto"&&(p=await up(c.clipConfiguration.asset)),c.setResolvedTiming({start:f,length:p})}}}const i=fc(e);this.cachedTimelineEnd=i;const a=this.getEndLengthClips();for(const r of a){const n=r.getResolvedTiming();r.setResolvedTiming({start:n.start,length:hp(n.start,i)})}for(const r of a)r.reconfigureAfterRestore()}propagateTimingChanges(e,t){const i=this.edit.getTracks(),a=i[e];if(!a)return;for(let n=Math.max(0,t);n<a.length;n+=1){const o=a[n];if(o.getTimingIntent().start==="auto"){const l=fp(e,n,i);o.setResolvedTiming({start:l,length:o.getLength()}),o.reconfigureAfterRestore()}}this.propagateAliasChanges();const r=fc(i);if(r!==this.cachedTimelineEnd){this.cachedTimelineEnd=r;const n=this.getEndLengthClips();for(const o of n){const l=hp(o.getStart(),r),c=o.getLength();Math.abs(l-c)>.001&&(o.setResolvedTiming({start:o.getStart(),length:l}),o.reconfigureAfterRestore())}}this.edit.updateTotalDuration(),this.edit.getInternalEvents().emit(Z.TimelineUpdated,{current:this.edit.getEdit()})}propagateAliasChanges(){const e=this.edit.getTracks(),t=this.edit.getResolvedEdit();for(let i=0;i<e.length;i+=1){const a=e[i],r=t.timeline.tracks[i];for(let n=0;n<a.length;n+=1){const o=a[n],l=r?.clips[n],c=o.getTimingIntent(),d=hs(c.start),u=hs(c.length);if((d||u)&&l){const f=o.getStart(),p=o.getLength(),g=Math.abs(l.start-f)>.001,w=Math.abs(l.length-p)>.001;(g||w)&&(o.setResolvedTiming({start:l.start,length:l.length}),o.reconfigureAfterRestore())}}}}getEndLengthClips(){const e=this.edit.getTracks(),t=[];for(const i of e)for(const a of i)a.getTimingIntent().length==="end"&&t.push(a);return t}}class jI extends dc{registry;constructor(){super(),this.registry={}}}class $n{static VIDEO_EXTENSIONS=[".mp4",".m4v",".webm",".ogg",".ogv"];static VIDEO_MIME={".mp4":"video/mp4",".m4v":"video/mp4",".webm":"video/webm",".ogg":"video/ogg",".ogv":"video/ogg"};loadTracker=new jI;refCounts=new Map;incrementRef(e){this.refCounts.set(e,(this.refCounts.get(e)??0)+1)}decrementRef(e){const t=this.refCounts.get(e)??0;return t<=1?(this.refCounts.delete(e),!0):(this.refCounts.set(e,t-1),!1)}constructor(){G.Assets.setPreferences({crossOrigin:"anonymous"})}async load(e,t){this.updateAssetLoadMetadata(e,"pending",0),this.incrementRef(e);try{if(await this.shouldUseSafariVideoLoader(t))return await this.loadVideoForSafari(e,t);const a=await G.Assets.load(t,r=>{this.updateAssetLoadMetadata(e,"loading",r)});return this.updateAssetLoadMetadata(e,"success",1),a}catch(i){return console.warn(`[AssetLoader] Failed to load asset "${e}":`,i),this.updateAssetLoadMetadata(e,"failed",1),this.decrementRef(e),null}}async loadVideoUnique(e,t){this.updateAssetLoadMetadata(e,"pending",0);try{const i=this.extractUrl(t);if(!i)throw new Error("No URL provided for video loading");const a=typeof t=="object"?t.data??{}:{},r=await new Promise((n,o)=>{const l=document.createElement("video");l.crossOrigin="anonymous",l.playsInline=!0,l.muted=a.muted??!1,l.preload="auto",l.addEventListener("loadedmetadata",()=>{try{const c=new G.VideoSource({resource:l,autoPlay:a.autoPlay??!1,...a});n(new G.Texture({source:c}))}catch(c){o(c)}},{once:!0}),l.addEventListener("error",()=>o(new Error("Video loading failed")),{once:!0}),this.updateAssetLoadMetadata(e,"loading",.5),l.src=i});return this.updateAssetLoadMetadata(e,"success",1),r}catch{return this.updateAssetLoadMetadata(e,"failed",1),null}}getProgress(){const e=Object.keys(this.loadTracker.registry);return e.length===0?0:e.reduce((i,a)=>i+this.loadTracker.registry[a].progress,0)/e.length}extractUrl(e){if(typeof e=="string")return e;const t=Array.isArray(e.src)?e.src[0]:e.src;return typeof t=="string"?t:t?.src}hasVideoExtension(e){const t=new URL(e,window.location.origin).pathname.toLowerCase();return $n.VIDEO_EXTENSIONS.some(i=>t.endsWith(i))}async getContentType(e){try{return(await fetch(e,{method:"HEAD"})).headers.get("content-type")}catch{return null}}canPlayVideo(e){const t=new URL(e,window.location.origin).pathname.toLowerCase(),i=t.slice(t.lastIndexOf(".")),a=$n.VIDEO_MIME[i];return a?document.createElement("video").canPlayType(a)!=="":!1}async isPlayableVideo(e){if(this.hasVideoExtension(e))return this.canPlayVideo(e);const t=await this.getContentType(e);return t?.startsWith("video/")?document.createElement("video").canPlayType(t)!=="":!1}async shouldUseSafariVideoLoader(e){const t=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),i=this.extractUrl(e);return t&&i!==void 0&&await this.isPlayableVideo(i)}async loadVideoForSafari(e,t){const i=this.extractUrl(t),a=typeof t=="object"?t.data??{}:{},r=await new Promise((n,o)=>{const l=document.createElement("video");l.crossOrigin="anonymous",l.playsInline=!0,l.muted=!0,l.preload="metadata",l.addEventListener("loadedmetadata",()=>{try{const c=new G.VideoSource({resource:l,autoPlay:a.autoPlay??!1,...a});n(new G.Texture({source:c}))}catch(c){o(c)}},{once:!0}),l.addEventListener("error",()=>o(new Error("Video loading failed")),{once:!0}),this.updateAssetLoadMetadata(e,"loading",.5),l.src=i});return this.updateAssetLoadMetadata(e,"success",1),r}updateAssetLoadMetadata(e,t,i){this.loadTracker.registry[e]?(this.loadTracker.registry[e].progress=i,this.loadTracker.registry[e].status=t):this.loadTracker.registry[e]={progress:i,status:t};const a={...this.loadTracker.registry};this.loadTracker.emit("onAssetLoadInfoUpdated",{registry:a})}}class br{static Name="FontLoadParser";id;name;extension;validFontExtensions;woff2Decompressor;constructor(){this.id=br.Name,this.name=br.Name,this.extension={type:[G.ExtensionType.LoadParser],priority:G.LoaderParserPriority.High,ref:null},this.validFontExtensions=["ttf","otf","woff","woff2"],this.woff2Decompressor=null}test(e){const t=e.split("?")[0]?.split(".").pop()?.toLowerCase()??"";return this.validFontExtensions.includes(t)}async load(e,t,i){const a=e.split("?")[0]?.split(".").pop()?.toLowerCase()??"",r=await fetch(e).then(f=>f.arrayBuffer());if(a!=="woff2"){const f=Vo.parse(new Uint8Array(r).buffer),p=f.names.fontFamily.en||f.names.fontFamily[Object.keys(f.names.fontFamily)[0]],g=new FontFace(p,`url(${e})`);return await g.load(),document.fonts.add(g),g}if(await this.loadWoff2Decompressor(),!this.woff2Decompressor)throw new Error("Cannot initialize Woff2 decompressor.");const n=this.woff2Decompressor.decompress(r),o=Vo.parse(new Uint8Array(n).buffer),l=o.names.fontFamily.en||o.names.fontFamily[Object.keys(o.names.fontFamily)[0]],c=new Blob([n],{type:"font/ttf"}),d=URL.createObjectURL(c),u=new FontFace(l,`url(${d})`);return await u.load(),document.fonts.add(u),u}async loadWoff2Decompressor(){if(this.woff2Decompressor)return;const t=`${await fetch("https://unpkg.com/wawoff2@2.0.1/build/decompress_binding.js").then(i=>i.text())}; return Module`;this.woff2Decompressor=new Function(t)(),await new Promise(i=>{this.woff2Decompressor.onRuntimeInitialized=i})}unload(e){e&&document.fonts.delete(e)}}const XI=50,pp={video:72,image:72,audio:48,text:36,"rich-text":36,shape:36,caption:36,html:48,luma:72,svg:72,default:48};function Ws(s){return pp[s]??pp.default}function KI(s){const{dragTarget:e,draggedAssetType:t,altKeyHeld:i,targetClip:a,existingLumaRef:r,draggedClipRef:n}=s;if(e.type==="insert")return{type:"track-insert"};if(!(t==="luma"||t==="image"||t==="video"))return{type:"normal-collision"};if(!i||!a)return t==="luma"?{type:"luma-overlay"}:{type:"normal-collision"};const l=r&&r.clipIndex===n.clipIndex&&r.trackIndex===n.trackIndex;return r&&!l?{type:"luma-blocked",reason:"Target already has a different luma"}:{type:"luma-attach",targetClip:a}}function hc(s,e){return s*e}function QI(s){const e=Math.floor(s/60),t=Math.floor(s%60),i=Math.floor(s%1*10);return`${e.toString().padStart(2,"0")}:${t.toString().padStart(2,"0")}.${i}`}function JI(s){const e=[];let t=0;for(const i of s)e.push(t),t+=Ws(i.primaryAssetType);return e}function $I(s,e){return e[s]??0}const va=12;function e6(s,e){if(s<va/2)return{type:"insert",insertionIndex:0};let t=0;for(let i=0;i<e.length;i+=1){const a=Ws(e[i].primaryAssetType);if(i>0&&s>=t-va/2&&s<t+va/2)return{type:"insert",insertionIndex:i};if(s>=t+va/2&&s<t+a-va/2)return{type:"track",trackIndex:i};t+=a}return s>=t-va/2?{type:"insert",insertionIndex:e.length}:{type:"track",trackIndex:Math.max(0,e.length-1)}}function t6(s){const{tracks:e,playheadTime:t,excludeClip:i}=s,a=[];a.push({time:t,type:"playhead"});for(const r of e)for(const n of r.clips)n.trackIndex===i.trackIndex&&n.clipIndex===i.clipIndex||(a.push({time:n.config.start,type:"clip-start"}),a.push({time:n.config.start+n.config.length,type:"clip-end"}));return a}function s6(s){const{time:e,snapPoints:t,snapThresholdPx:i,pixelsPerSecond:a}=s,r=i/a;for(const n of t)if(Math.abs(e-n.time)<=r)return n.time;return null}function i6(s,e){return s.clips.filter(t=>!(t.trackIndex===e.trackIndex&&t.clipIndex===e.clipIndex)).sort((t,i)=>t.config.start-i.config.start)}function a6(s,e,t){const i=e+t;for(let a=0;a<s.length;a+=1){const r=s[a],n=r.config.start,o=n+r.config.length;if(e<o&&i>n)return{clip:r,index:a}}return null}function r6(s,e,t,i,a){const r=s.config.start,n=r+s.config.length,o=t+i/2,l=r+s.config.length/2;if(o>=l){const p=n,g=p+i,w=a[e+1];return w&&g>w.config.start?{newStartTime:p,pushOffset:g-w.config.start}:{newStartTime:p,pushOffset:0}}const d=e>0?a[e-1].config.start+a[e-1].config.length:0;if(r-d>=i)return{newStartTime:r-i,pushOffset:0};const f=d;return{newStartTime:f,pushOffset:f+i-r}}const n6={newStartTime:0,pushOffset:0};function o6(s){const{track:e,desiredStart:t,clipLength:i,excludeClip:a}=s,r=i6(e,a);if(r.length===0)return{...n6,newStartTime:t};const n=a6(r,t,i);return n?n.clip.config.asset?.type==="luma"?{newStartTime:t,pushOffset:0}:r6(n.clip,n.index,t,i,r):{newStartTime:t,pushOffset:0}}function l6(s){const{track:e,time:t,excludeClip:i}=s;for(const a of e.clips)if(!(i&&a.trackIndex===i.trackIndex&&a.clipIndex===i.clipIndex)&&a.config.asset?.type!=="luma"){const n=a.config.start,o=n+a.config.length;if(t>=n&&t<o)return a}return null}function c6(s,e){return Math.sqrt(s*s+e*e)}function d6(s,e,t){return c6(s,e)>=t}function gp(s,e,t,i,a){return a>0?{type:"move-with-push",pushOffset:a}:e!==s||i!==t?{type:"simple-move"}:{type:"no-change"}}function u6(s){const{dragTarget:e,draggedAssetType:t,altKeyHeld:i,targetClip:a,existingLumaRef:r,draggedClipRef:n,startTime:o,newTime:l,originalTrack:c,pushOffset:d}=s;if(e.type==="insert")return{type:"insert-track",insertionIndex:e.insertionIndex};const u=i&&a;if((t==="image"||t==="video")&&u)return r!==null?gp(o,l,c,e.trackIndex,d):{type:"transform-and-attach",targetClip:a};if(t==="luma"){if(u){const f=r?.clipIndex===n.clipIndex&&r?.trackIndex===n.trackIndex;return r&&!f?{type:"detach-luma"}:{type:"reattach-luma",targetClip:a}}return{type:"detach-luma"}}return gp(o,l,c,e.trackIndex,d)}function f6(s,e,t,i){const a=Math.max(s,t),r=Math.min(e,i);return Math.max(0,r-a)}class h6{queue=[];isProcessing=!1;async enqueue(e){return new Promise((t,i)=>{this.queue.push(async()=>{try{const a=await e();t(a)}catch(a){i(a)}}),this.processQueue()})}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;){const e=this.queue.shift();if(e)try{await e()}catch{}}this.isProcessing=!1}}}class xa{data;clipBindings=new Map;constructor(e){this.data=structuredClone(e),this.hydrateIds()}hydrateIds(){const e=new Set;for(const t of this.data.timeline.tracks)for(let i=0;i<t.clips.length;i+=1){const a=t.clips[i];if(e.has(a)){const r=structuredClone(a);r.id=crypto.randomUUID(),t.clips[i]=r}else e.add(a),a.id||(a.id=crypto.randomUUID())}}getTimeline(){return this.data.timeline}getBackground(){return this.data.timeline.background}getTracks(){return this.data.timeline.tracks}getTrack(e){return this.data.timeline.tracks[e]??null}getTrackCount(){return this.data.timeline.tracks.length}getSoundtrack(){return this.data.timeline.soundtrack}getClip(e,t){const i=this.data.timeline.tracks[e];return i?i.clips[t]??null:null}getClipsInTrack(e){return this.data.timeline.tracks[e]?.clips??[]}getClipCount(){return this.data.timeline.tracks.reduce((e,t)=>e+t.clips.length,0)}getClipCountInTrack(e){return this.data.timeline.tracks[e]?.clips.length??0}getClipById(e){for(let t=0;t<this.data.timeline.tracks.length;t+=1){const i=this.data.timeline.tracks[t].clips;for(let a=0;a<i.length;a+=1)if(i[a].id===e)return{clip:i[a],trackIndex:t,clipIndex:a}}return null}updateClipById(e,t){const i=this.getClipById(e);i&&Object.assign(i.clip,t)}removeClipById(e){const t=this.getClipById(e);return t?this.removeClip(t.trackIndex,t.clipIndex):null}getClipId(e,t){return this.getClip(e,t)?.id??null}getOutput(){return this.data.output}getSize(){const{size:e}=this.data.output;if(!e?.width||!e?.height)throw new Error("Output size is not defined");return{width:e.width,height:e.height}}getFormat(){return this.data.output.format}getFps(){return this.data.output.fps}getResolution(){return this.data.output.resolution}getAspectRatio(){return this.data.output.aspectRatio}getMergeFields(){return this.data.merge}addTrack(e,t){const i=t??{clips:[]};return this.data.timeline.tracks.splice(e,0,i),i}removeTrack(e){if(e<0||e>=this.data.timeline.tracks.length)return null;if(this.data.timeline.tracks.length<=1)return console.warn("Cannot remove the last track"),null;const[t]=this.data.timeline.tracks.splice(e,1);return t??null}addClip(e,t,i){const a=this.data.timeline.tracks[e];if(!a)throw new Error(`Track ${e} does not exist`);const r=t;r.id||(r.id=crypto.randomUUID());const n=i??a.clips.length;return a.clips.splice(n,0,t),t}removeClip(e,t){const i=this.data.timeline.tracks[e];if(!i||t<0||t>=i.clips.length)return null;const[a]=i.clips.splice(t,1);return a??null}updateClip(e,t,i){const a=this.getClip(e,t);if(!a)throw new Error(`Clip at track ${e}, index ${t} does not exist`);Object.assign(a,i)}replaceClipProperties(e,t,i){const a=this.getClip(e,t);if(!a)throw new Error(`Clip at track ${e}, index ${t} does not exist`);const{id:r}=a;for(const n of Object.keys(a))n!=="id"&&delete a[n];Object.assign(a,i),r&&(a.id=r)}replaceClip(e,t,i){const a=this.data.timeline.tracks[e];if(!a||t<0||t>=a.clips.length)return null;const r=a.clips[t];return a.clips[t]=i,r}moveClip(e,t,i,a){const r=this.data.timeline.tracks[e];if(!r||t<0||t>=r.clips.length)return null;const n=this.data.timeline.tracks[i];if(!n)return null;const[o]=r.clips.splice(t,1);if(!o)return null;a&&Object.assign(o,a);const l=typeof o.start=="number"?o.start:0;let c=0;for(let d=0;d<n.clips.length;d+=1){const u=n.clips[d].start;if(l<(typeof u=="number"?u:0))break;c+=1}return n.clips.splice(c,0,o),o}setBackground(e){this.data.timeline.background=e}setSoundtrack(e){this.data.timeline.soundtrack=e}getFonts(){return this.data.timeline.fonts??[]}addFont(e){this.data.timeline.fonts||(this.data.timeline.fonts=[]),this.data.timeline.fonts.some(t=>t.src===e)||this.data.timeline.fonts.push({src:e})}removeFont(e){this.data.timeline.fonts&&(this.data.timeline.fonts=this.data.timeline.fonts.filter(t=>t.src!==e))}setFonts(e){this.data.timeline.fonts=e}setSize(e){this.data.output.size={width:e.width,height:e.height}}setFormat(e){this.data.output.format=e}setFps(e){this.data.output.fps=e}setResolution(e){this.data.output.resolution=e}clearResolution(){delete this.data.output.resolution}setAspectRatio(e){this.data.output.aspectRatio=e}clearAspectRatio(){delete this.data.output.aspectRatio}clearSize(){delete this.data.output.size}setMergeFields(e){this.data.merge=e}setClipBinding(e,t,i){let a=this.clipBindings.get(e);a||(a=new Map,this.clipBindings.set(e,a)),a.set(t,i)}getClipBinding(e,t){return this.clipBindings.get(e)?.get(t)}removeClipBinding(e,t){const i=this.clipBindings.get(e);i&&(i.delete(t),i.size===0&&this.clipBindings.delete(e))}getClipBindings(e){return this.clipBindings.get(e)}setClipBindingsForClip(e,t){t.size===0?this.clipBindings.delete(e):this.clipBindings.set(e,new Map(t))}clearClipBindings(e){this.clipBindings.delete(e)}getClipIdsWithBindings(){return Array.from(this.clipBindings.keys())}toJSON(){const e=structuredClone(this.data);for(const t of e.timeline.tracks)for(const i of t.clips){const a=i.id;if(a){const r=this.clipBindings.get(a);if(r)for(const[n,{placeholder:o}]of r)Zs(i,n,o)}delete i.id}return e.merge?.length===0&&delete e.merge,e}static fromJSON(e){return new xa(e)}clone(){return new xa(this.data)}}const mp=new Set(["asset","start","length","id"]),p6=new Set(["text-to-image","image-to-video","text-to-speech"]);class g6{constructor(e){this.edit=e,this.edit.getInternalEvents().on(Be.Resolved,this.onResolved)}isReconciling=!1;enableCreation=!0;onResolved=({edit:e})=>{this.reconcile(e)};async reconcileInitial(e){const t=this.reconcile(e);return await Promise.all(t.pendingLoads),t}reconcile(e){if(this.isReconciling)return{created:[],updated:[],disposed:[],pendingLoads:[]};this.isReconciling=!0;try{const t=[],i={created:[],updated:[],disposed:[],pendingLoads:t},a=new Set;for(let n=0;n<e.timeline.tracks.length;n+=1){const o=e.timeline.tracks[n];for(let l=0;l<o.clips.length;l+=1){const c=o.clips[l],d=c.id;if(d){a.add(d);const u=this.edit.getPlayerByClipId(d);if(u){const f=this.updatePlayer(u,c,n);f==="recreate"?(this.disposePlayer(d),t.push(this.createPlayer(c,d,n,l)),i.disposed.push(d),i.created.push(d)):f&&i.updated.push(d)}else this.enableCreation&&(this.createPlayer(c,d,n,l),i.created.push(d))}}}const r=this.findOrphanedPlayers(a);for(const n of r)this.disposePlayer(n),i.disposed.push(n);return(i.created.length>0||i.disposed.length>0||i.updated.length>0)&&this.rebuildTracksOrdering(e),this.syncTrackContainers(e.timeline.tracks.length),i}finally{this.isReconciling=!1}}updateSinglePlayer(e,t,i,a=0){const r=this.updatePlayer(e,t,i);if(r==="recreate"){const{clipId:n}=e;return n&&(this.disposePlayer(n),this.createPlayer(t,n,i,a)),"recreate"}return r}createPlayer(e,t,i,a){const r=this.edit.createPlayerFromAssetType(e);r.layer=i+1,r.clipId=t,this.edit.registerPlayerByClipId(t,r),this.edit.addPlayerToTracksArray(i,r),this.edit.addPlayerToContainer(i,r);const n=e.asset?.type??"unknown";return r.load().then(()=>{this.edit.getInternalEvents().emit(Be.PlayerLoaded,{player:r,trackIndex:i,clipIndex:a}),p6.has(n)&&this.edit.getInternalEvents().emit(Z.ClipUnresolved,{trackIndex:i,clipIndex:a,assetType:n,clipId:t})}).catch(l=>{const c=l instanceof Error?l.message:String(l);this.edit.getInternalEvents().emit(Z.ClipLoadFailed,{trackIndex:i,clipIndex:a,error:c,assetType:n})})}updatePlayer(e,t,i){const a=e.clipConfiguration.asset?.type,r=t.asset?.type;if(a!==r)return"recreate";let n=!1;const o=e.layer-1,l=e.clipConfiguration.start,c=e.clipConfiguration.length;return(l!==t.start||c!==t.length)&&(e.setResolvedTiming({start:t.start,length:t.length}),e.reconfigureAfterRestore(),n=!0),o!==i&&(e.layer=i+1,this.edit.movePlayerBetweenTracks(e,o,i),n=!0),this.assetChanged(e.clipConfiguration.asset,t.asset)&&(this.updateAsset(e,t.asset),n=!0),this.clipPropertiesChanged(e.clipConfiguration,t)&&(this.updateClipProperties(e,t),n=!0),n}clipPropertiesChanged(e,t){const i=e,a=t,r=new Set([...Object.keys(i),...Object.keys(a)]);for(const n of r)if(!mp.has(n)&&JSON.stringify(i[n])!==JSON.stringify(a[n]))return!0;return!1}updateClipProperties(e,t){const i=e.clipConfiguration,a=t,r=new Set([...Object.keys(i),...Object.keys(a)]);for(const n of r)mp.has(n)||(a[n]!==void 0?i[n]=a[n]:delete i[n]);e.reconfigureAfterRestore()}assetChanged(e,t){return JSON.stringify(e)!==JSON.stringify(t)}updateAsset(e,t){const i=e.clipConfiguration.asset?.src,a=t?.src;e.clipConfiguration.asset=t,i!==a&&e.reloadAsset?e.reloadAsset().then(()=>{e.reconfigureAfterRestore()}).catch(r=>{console.error("Failed to reload asset:",r)}):e.reconfigureAfterRestore()}syncTrackContainers(e){const t=this.edit.getTracks().length;if(e>t)for(let i=t;i<e;i+=1)this.edit.ensureTrackExists(i);else if(e<t)for(let i=t-1;i>=e;i-=1)this.edit.removeEmptyTrack(i)}findOrphanedPlayers(e){const t=[];for(const[i]of this.edit.getPlayerMap())e.has(i)||t.push(i);return t}disposePlayer(e){const t=this.edit.getPlayerByClipId(e);t&&(this.edit.unregisterPlayerByClipId(e),this.edit.queuePlayerForDisposal(t))}rebuildTracksOrdering(e){const t=this.edit.getTracks();for(let i=0;i<t.length;i+=1)t[i]=[];for(let i=0;i<e.timeline.tracks.length;i+=1){for(;t.length<=i;)t.push([]);for(const a of e.timeline.tracks[i].clips){const r=a.id;if(r){const n=this.edit.getPlayerByClipId(r);n&&t[i].push(n)}}}}dispose(){this.edit.getInternalEvents().off(Be.Resolved,this.onResolved)}}function yp(s,e){function t(i){if(typeof i=="string"&&e.isMergeFieldTemplate(i)){const a=e.resolveToNumber(i);return a!==null?a:e.resolve(i)}if(Array.isArray(i))return i.map(t);if(i!==null&&typeof i=="object"){const a={};for(const[r,n]of Object.entries(i))a[r]=t(n);return a}return i}return t(structuredClone(s))}function m6(s){const e=new Map,t=new Map,i=[];for(let a=0;a<s.getTrackCount();a+=1){const r=s.getClipsInTrack(a);for(let n=0;n<r.length;n+=1){const o=r[n];if(!o.id)throw new Error(`Clip at track ${a}, index ${n} is missing an ID. EditDocument hydration may have been skipped.`);const l=o.alias??o.id,c={clip:o,trackIndex:a,clipIndex:n};if(i.push({...c,id:l}),o.alias){if(t.has(o.alias))throw new Error(`Duplicate alias "${o.alias}" found. Each alias must be unique.`);t.set(o.alias,c)}}}for(let a=0;a<s.getTrackCount();a+=1){const r=s.getClipsInTrack(a);for(let n=0;n<r.length;n+=1){const o=r[n],l=o.alias??o.id,c=new Set;if(hs(o.start)){const d=Rr(o.start);if(!t.has(d))throw new Error(`Alias reference "alias://${d}" not found. No clip defines alias "${d}".`);c.add(d)}if(hs(o.length)){const d=Rr(o.length);if(!t.has(d))throw new Error(`Alias reference "alias://${d}" not found. No clip defines alias "${d}".`);c.add(d)}if(o.start==="auto"&&n>0){const d=r[n-1],u=d.alias??d.id;c.add(u)}c.size>0&&e.set(l,c)}}return{dependencies:e,clipsByAlias:t,allClips:i}}function y6(s){const e=new Set,t=new Set;function i(a,r){e.add(a),t.add(a);const n=s.get(a);if(n)for(const o of n){if(t.has(o))return[...r,o];if(!e.has(o)){const l=i(o,[...r,o]);if(l)return l}}return t.delete(a),null}for(const a of s.keys())if(!e.has(a)){const r=i(a,[a]);if(r)return r}return null}function b6(s,e){const t=[],i=new Set;function a(r){if(i.has(r))return;i.add(r);const n=s.get(r);if(n)for(const o of n)a(o);t.push(r)}for(const r of s.keys())a(r);for(const r of e)a(r);return t}function bp(s,e,t){let i;if(s.start==="auto")i=e;else if(hs(s.start)){const n=Rr(s.start),o=t.get(n);if(!o)throw new Error(`Internal error: Alias "${n}" not resolved.`);i=o.start}else i=s.start;let a,r=!1;if(s.length==="end")a=1,r=!0;else if(s.length==="auto")a=3;else if(hs(s.length)){const n=Rr(s.length),o=t.get(n);if(!o)throw new Error(`Internal error: Alias "${n}" not resolved.`);a=o.length}else a=s.length;return{...s,id:s.id??crypto.randomUUID(),start:i,length:a,pendingEndLength:r||void 0}}function w6(s){let e=0;for(const t of s)for(const i of t.clips)if(!i.pendingEndLength){const a=i.start+i.length;a>e&&(e=a)}return e}function pc(s){const{pendingEndLength:e,...t}=s;return t}function v6(s,e,t){const i=s.getClipById(e);if(!i)return null;const{clip:a,trackIndex:r,clipIndex:n}=i,l=yp(a,t.mergeFields),c=t.resolvedAliases??new Map,d=bp(l,t.previousClipEnd,c);return d.pendingEndLength&&t.cachedTimelineEnd!==void 0&&(d.length=Math.max(t.cachedTimelineEnd-d.start,.1)),{resolved:pc(d),trackIndex:r,clipIndex:n}}function wp(s,e){const{dependencies:t,allClips:i}=m6(s);if(t.size>0){const p=y6(t);if(p)throw new Error(`Circular alias reference detected: ${p.join(" -> ")}`)}const a=i.map(p=>p.id),r=b6(t,a),n=new Map;for(const p of i)n.set(p.id,p);const o=new Map,l=new Map,c=new Map;for(const p of r){const g=n.get(p);if(g){const{clip:w,trackIndex:C,clipIndex:v}=g,k=yp(w,e.mergeFields),x=c.get(C)??0,T=bp(k,x,l);o.set(`${C}-${v}`,T);const b=T.start+T.length,R=c.get(C)??0;b>R&&c.set(C,b),w.alias&&l.set(w.alias,{start:T.start,length:T.length})}}const d=[];for(let p=0;p<s.getTrackCount();p+=1){const g=s.getClipsInTrack(p).length,w=[];for(let C=0;C<g;C+=1){const v=o.get(`${p}-${C}`);if(!v)throw new Error(`Internal error: Clip at track ${p}, index ${C} was not resolved.`);w.push(v)}d.push({clips:w})}const u=w6(d),f=d.map(p=>({clips:p.clips.map(g=>{if(g.pendingEndLength){const w=Math.max(u-g.start,.1);return pc({...g,length:w})}return pc(g)})}));return{timeline:{background:s.getBackground(),tracks:f,fonts:s.getFonts()},output:s.getOutput()}}class Ca{static MAX_HISTORY_SIZE=100;static SEEK_ELAPSED_MARKER=101;document;size;backgroundColor;tracks;playbackTime;totalDuration;isPlaying;get clips(){return this.tracks.flat()}assetLoader;internalEvents;events;canvas=null;timingManager;lumaMaskController;playerReconciler;outputSettings;selectionManager;mergeFieldService;commandHistory=[];commandIndex=-1;commandQueue=new h6;clipsToDispose=new Set;clipErrors=new Map;playerByClipId=new Map;lumaContentRelations=new Map;fontMetadata=new Map;isBatchingEvents=!1;syncCorrectionCount=0;isExporting=!1;lastResolved=null;constructor(e){ja.parse(e),this.tracks=[],this.playbackTime=0,this.totalDuration=0,this.isPlaying=!1,this.document=new xa(e);const t=this.document.getResolution(),i=this.document.getAspectRatio();this.backgroundColor=this.document.getBackground()??"#000000",this.size=t?Jn(t,i):this.document.getSize(),this.assetLoader=new $n,this.internalEvents=new dc,this.events=this.internalEvents,this.lumaMaskController=new OI(()=>this.canvas,()=>this.tracks,this.internalEvents),this.playerReconciler=new g6(this),this.mergeFieldService=new UI(this.internalEvents),this.outputSettings=new WI(this),this.selectionManager=new HI(this),this.timingManager=new YI(this),this.setupIntentListeners()}async load(){await this.initializeFromDocument()}async initializeFromDocument(e="load"){const t=this.document.toJSON(),i=t.merge??[];this.mergeFieldService.loadFromSerialized(i),this.lastResolved=null;const a=this.detectMergeFieldBindings(i),r=ja.parse(t);await Promise.all((r.timeline.fonts??[]).map(async o=>{const l=o.src,c={src:l,parser:br.Name},d=await this.assetLoader.load(l,c);if(d?.family){const u=d.family.replace(/^["']|["']$/g,""),{baseFontFamily:f,fontWeight:p}=ts(u);this.fontMetadata.set(l,{baseFamilyName:f,weight:p})}return d}));const n=this.getResolvedEdit();this.lumaMaskController.initialize(),await this.playerReconciler.reconcileInitial(n),this.normalizeLumaAttachments();for(const[o,l]of a)l.size>0&&this.document.setClipBindingsForClip(o,l);await this.timingManager.resolveAllTiming(),this.updateTotalDuration(),r.timeline.soundtrack&&await this.loadSoundtrack(r.timeline.soundtrack),this.internalEvents.emit(Z.TimelineUpdated,{current:this.getEdit()}),this.emitEditChanged(e)}getInternalEvents(){return this.internalEvents}update(e,t){for(const i of this.clips)i.shouldDispose&&this.queueDisposeClip(i),i.update(e,t);this.disposeClips(),this.lumaMaskController.update(),this.isPlaying&&(this.playbackTime=Math.max(0,Math.min(this.playbackTime+_o(t),this.totalDuration)),this.playbackTime===this.totalDuration&&this.pause())}dispose(){this.clearClips(),this.lumaMaskController.dispose(),this.playerReconciler.dispose();for(const e of this.commandHistory)e.dispose?.();this.commandHistory=[],this.commandIndex=-1,this.lumaContentRelations.clear(),np.cleanup()}updateCanvasForSize(){this.internalEvents.emit(Be.ViewportSizeChanged,{width:this.size.width,height:this.size.height,backgroundColor:this.backgroundColor}),this.internalEvents.emit(Be.ViewportNeedsZoomToFit)}play(){this.isPlaying=!0,this.internalEvents.emit(Z.PlaybackPlay)}pause(){this.isPlaying=!1,this.internalEvents.emit(Z.PlaybackPause)}seek(e){this.playbackTime=Math.max(0,Math.min(e,this.totalDuration)),this.pause(),this.update(0,Ca.SEEK_ELAPSED_MARKER)}stop(){this.seek(0)}async loadEdit(e){if(ja.parse(e),this.tracks.length>0&&!this.hasStructuralChanges(e)){this.lastResolved=null;const n=structuredClone(e);this.preserveClipIdsForGranularUpdate(n);const o=this.document.getTracks(),l=this.document.getOutput();this.document=new xa(n),this.isBatchingEvents=!0,await this.applyGranularChanges(n,o,l),this.isBatchingEvents=!1,this.emitEditChanged("loadEdit:granular");return}const t=this.document,i=this.lastResolved,a=this.size,r=this.backgroundColor;try{this.lastResolved=null,this.document=new xa(e);const n=this.document.getResolution(),o=this.document.getAspectRatio();this.size=n?Jn(n,o):this.document.getSize(),this.backgroundColor=this.document.getBackground()??"#000000",this.internalEvents.emit(Be.ViewportSizeChanged,{width:this.size.width,height:this.size.height,backgroundColor:this.backgroundColor}),this.internalEvents.emit(Be.ViewportNeedsZoomToFit),this.clearClips(),await this.initializeFromDocument("loadEdit")}catch(n){throw this.document=t,this.lastResolved=i,this.size=a,this.backgroundColor=r,n}}async loadSoundtrack(e){const t={id:crypto.randomUUID(),asset:{type:"audio",src:e.src,effect:e.effect,volume:e.volume??1},fit:"crop",start:0,length:this.totalDuration},i=this.createPlayerFromAssetType(t);i.layer=this.tracks.length+1,await this.addPlayer(this.tracks.length,i)}getEdit(){const e=this.document.toJSON(),t=this.mergeFieldService.toSerializedArray();return t.length>0&&(e.merge=t),e}validateEdit(e){const t=ja.safeParse(e);return t.success?{valid:!0,errors:[]}:{valid:!1,errors:t.error.issues.map(i=>({path:i.path.join("."),message:i.message}))}}getResolvedEdit(){return this.lastResolved||(this.lastResolved=wp(this.document,{mergeFields:this.mergeFieldService})),this.lastResolved}getResolvedClip(e,t){return this.getResolvedEdit()?.timeline?.tracks?.[e]?.clips?.[t]??null}getResolvedClipById(e){const t=this.getResolvedEdit();for(const i of t.timeline.tracks)for(const a of i.clips)if(a.id===e)return a;return null}getClipId(e,t){return this.document?.getClipId(e,t)??null}getDocumentClip(e,t){return this.document?.getClip(e,t)??null}getDocument(){return this.document}resolve(){return this.lastResolved=wp(this.document,{mergeFields:this.mergeFieldService}),this.internalEvents.emit(Be.Resolved,{edit:this.lastResolved}),this.lastResolved}resolveClip(e){const t=this.getPlayerByClipId(e);if(!t)return!1;const i=this.document.getClipById(e);if(i?.clip.alias)return this.resolve(),!0;const a=i?.clip;if(a&&(hs(a.start)||hs(a.length)))return this.resolve(),!0;const r=t.layer-1,n=this.tracks[r],o=n?n.indexOf(t):-1;if(o<0)return!1;const l=o>0?n[o-1]:null,c=l?l.getEnd():0,d={mergeFields:this.mergeFieldService,previousClipEnd:c,cachedTimelineEnd:this.timingManager.getTimelineEnd()},u=v6(this.document,e,d);if(!u)return!1;if(this.lastResolved){const p=this.lastResolved.timeline.tracks[u.trackIndex];p&&p.clips[u.clipIndex]&&(p.clips[u.clipIndex]=u.resolved)}return this.playerReconciler.updateSinglePlayer(t,u.resolved,u.trackIndex,u.clipIndex)!==!1}addClip(e,t){nn.parse(t);const i=new AI(e,t);return this.executeCommand(i)}getClip(e,t){const i=this.tracks[e];return!i||t<0||t>=i.length?null:i[t].clipConfiguration}getClipError(e,t){return this.clipErrors.get(`${e}-${t}`)??null}clearClipErrorAndShift(e,t){this.clipErrors.delete(`${e}-${t}`);const i=[];for(const[a,r]of this.clipErrors){const[n,o]=a.split("-").map(Number);n===e&&o>t&&i.push({oldKey:a,newKey:`${n}-${o-1}`,value:r})}for(const{oldKey:a,newKey:r,value:n}of i)this.clipErrors.delete(a),this.clipErrors.set(r,n)}getPlayerClip(e,t){const i=this.tracks[e];return!i||t<0||t>=i.length?null:i[t]}getPlayerByClipId(e){return this.playerByClipId.get(e)??null}getDocumentClipById(e){return this.document?.getClipById(e)?.clip??null}registerPlayerByClipId(e,t){this.playerByClipId.set(e,t)}unregisterPlayerByClipId(e){this.playerByClipId.delete(e)}getPlayerMap(){return this.playerByClipId}addPlayerToTracksArray(e,t){for(;this.tracks.length<=e;)this.tracks.push([]);this.tracks[e].push(t)}movePlayerBetweenTracks(e,t,i){const a=this.tracks[t];if(a){const r=a.indexOf(e);r!==-1&&a.splice(r,1)}for(;this.tracks.length<=i;)this.tracks.push([]);this.tracks[i].push(e),this.movePlayerToTrackContainer(e,t,i)}queuePlayerForDisposal(e){this.queueDisposeClip(e),this.disposeClips()}ensureTrackExists(e){for(;this.tracks.length<=e;)this.tracks.push([])}removeEmptyTrack(e){if(e<0||e>=this.tracks.length)return;const t=this.tracks[e];if(t&&t.length>0){console.warn(`Cannot remove non-empty track ${e}`);return}this.tracks.splice(e,1),this.internalEvents.emit(Be.TrackContainerRemoved,{trackIndex:e});for(let i=e;i<this.tracks.length;i+=1)for(const a of this.tracks[i])a.layer=i+1}getOriginalAsset(e,t){const i=this.getPlayerClip(e,t);if(!i)return;const a=i.getExportableClip();if(!a)return;const{clipId:r}=i;if(r&&this.document){const n=this.document.getClipBindings(r);if(n){for(const[o,{placeholder:l}]of n)if(o.startsWith("asset.")){const c=o.slice(6);Zs(a.asset,c,l)}}}return a.asset}async deleteClip(e,t){const i=this.tracks[e];if(!i)return;const a=i[t];if(!a)return;if(a.playerType!==it.Luma){const o=i.findIndex(l=>l.playerType===it.Luma);if(o!==-1){const l=o<t?t-1:t,c=new oc(e,o);await this.executeCommand(c);const d=new oc(e,l);await this.executeCommand(d);return}}const n=new oc(e,t);await this.executeCommand(n)}splitClip(e,t,i){const a=new _I(e,t,i);return this.executeCommand(a)}async addTrack(e,t){Vu.parse(t);const i=new op(e);await this.executeCommand(i);for(const a of t.clips)await this.addClip(e,a)}getTrack(e){const t=this.clips.filter(i=>i.layer===e+1);return t.length===0?null:{clips:t.map(i=>i.clipConfiguration)}}deleteTrack(e){const t=new nc(e);this.executeCommand(t)}recordSyncCorrection(){this.syncCorrectionCount+=1}undo(){return this.commandQueue.enqueue(async()=>{if(this.commandIndex>=0){const e=this.commandHistory[this.commandIndex];if(e.undo){const t=this.createCommandContext();await Promise.resolve(e.undo(t)),this.commandIndex-=1,this.internalEvents.emit(Z.EditUndo,{command:e.name}),this.emitEditChanged(`undo:${e.name}`)}}})}redo(){return this.commandQueue.enqueue(async()=>{if(this.commandIndex<this.commandHistory.length-1){const e=this.commandIndex+1,t=this.commandHistory[e],i=this.createCommandContext();await Promise.resolve(t.execute(i)),this.commandIndex=e,this.internalEvents.emit(Z.EditRedo,{command:t.name}),this.emitEditChanged(`redo:${t.name}`)}})}setUpdatedClip(e,t=null,i=null){const a=e.layer-1,r=this.tracks[a],n=r?r.indexOf(e):-1,o=new cc(t,i,{trackIndex:a,clipIndex:n});this.executeCommand(o)}updateClipInDocument(e,t){const i=this.document.getClipById(e);i&&this.document.updateClip(i.trackIndex,i.clipIndex,t)}commitClipUpdate(e,t,i){const a=this.document.getClipById(e);if(!a){console.warn(`commitClipUpdate: clip ${e} not found in document`);return}rl.parse(i);const r=new cc(t,structuredClone(i),{trackIndex:a.trackIndex,clipIndex:a.clipIndex});this.addCommandToHistory(r)}pushCommandToHistory(e){const t=this.commandHistory.slice(this.commandIndex+1);for(const i of t)i.dispose?.();for(this.commandHistory=this.commandHistory.slice(0,this.commandIndex+1),this.commandHistory.push(e),this.commandIndex+=1;this.commandHistory.length>Ca.MAX_HISTORY_SIZE;)this.commandHistory.shift()?.dispose?.(),this.commandIndex-=1}addCommandToHistory(e){this.pushCommandToHistory(e),this.emitEditChanged(`commit:${e.name}`)}updateClip(e,t,i){const a=this.getPlayerClip(e,t);if(!a)return console.warn(`Clip not found at track ${e}, index ${t}`),Promise.resolve();const r=this.document?.getClip(e,t),n=structuredClone(r??a.clipConfiguration),o=structuredClone(r??a.clipConfiguration),l=lc(o,i);rl.parse(l);const c=new cc(n,l,{trackIndex:e,clipIndex:t});return this.executeCommand(c)}updateClipTiming(e,t,i){if(!this.getPlayerClip(e,t)){console.warn(`Clip not found at track ${e}, index ${t}`);return}const r=new MI(e,t,i);this.executeCommand(r)}updateTextContent(e,t,i){const a=e.layer-1,r=this.tracks[a]?.indexOf(e)??-1;if(r<0){console.warn("UpdateTextContent: clip not found in track");return}const n=new LI(a,r,t);this.executeCommand(n)}executeEditCommand(e){return this.executeCommand(e)}executeCommand(e){return this.commandQueue.enqueue(async()=>{const t=this.createCommandContext(),i=await Promise.resolve(e.execute(t));this.handleCommandResult(e,i)})}handleCommandResult(e,t){t.status==="success"&&(this.pushCommandToHistory(e),this.emitEditChanged(e.name))}emitEditChanged(e){this.isBatchingEvents||this.internalEvents.emit(Z.EditChanged,{source:e,timestamp:Date.now()})}detectMergeFieldBindings(e){const t=new Map;if(!e.length)return t;const i=new Map;for(const{find:a,replace:r}of e){const n=typeof r=="string"?r:JSON.stringify(r);i.set(a.toUpperCase(),n)}for(let a=0;a<this.document.getTrackCount();a+=1){const r=this.document.getClipsInTrack(a);for(let n=0;n<r.length;n+=1){const o=this.document.getClipId(a,n);if(o){const l=this.detectBindingsInObject(r[n],"",i);l.size>0&&t.set(o,l)}}}return t}detectBindingsInObject(e,t,i){const a=new Map;if(typeof e=="string"){if(/\{\{\s*([A-Z_0-9]+)\s*\}\}/gi.test(e)){const o=e.replace(/\{\{\s*([A-Z_0-9]+)\s*\}\}/gi,(l,c)=>i.get(c.toUpperCase())??l);a.set(t,{placeholder:e,resolvedValue:o})}return a}if(Array.isArray(e)){for(let r=0;r<e.length;r+=1){const n=t?`${t}[${r}]`:`[${r}]`,o=this.detectBindingsInObject(e[r],n,i);for(const[l,c]of o)a.set(l,c)}return a}if(e!==null&&typeof e=="object")for(const[r,n]of Object.entries(e)){const o=t?`${t}.${r}`:r,l=this.detectBindingsInObject(n,o,i);for(const[c,d]of l)a.set(c,d)}return a}hasStructuralChanges(e){if(!this.document)return!0;const t=this.document.getTracks(),i=e.timeline.tracks;if(t.length!==i.length)return!0;for(let a=0;a<t.length;a+=1){if(t[a].clips.length!==i[a].clips.length)return!0;for(let r=0;r<t[a].clips.length;r+=1){const n=t[a].clips[r]?.asset?.type,o=i[a].clips[r]?.asset?.type;if(n!==o)return!0}}return JSON.stringify(this.document.getMergeFields()??[])!==JSON.stringify(e.merge??[])||JSON.stringify(this.document.getFonts())!==JSON.stringify(e.timeline.fonts??[])||JSON.stringify(this.document.getSoundtrack())!==JSON.stringify(e.timeline.soundtrack)}preserveClipIdsForGranularUpdate(e){if(!this.document)return;const t=this.document.getTracks();for(let i=0;i<e.timeline.tracks.length;i+=1){const a=t[i],r=e.timeline.tracks[i];if(a&&r)for(let n=0;n<r.clips.length;n+=1){const o=this.document.getClipId(i,n);o&&(r.clips[n].id=o)}}}async applyGranularChanges(e,t,i){const a=e.output;if(a?.size&&(i?.size?.width!==a.size.width||i?.size?.height!==a.size.height)){const o=a.size.width??this.size.width,l=a.size.height??this.size.height;await this.setOutputSize(o,l)}a?.fps!==void 0&&i?.fps!==a.fps&&await this.setOutputFps(a.fps),a?.format!==void 0&&i?.format!==a.format&&await this.setOutputFormat(a.format),a?.destinations&&JSON.stringify(i?.destinations)!==JSON.stringify(a.destinations)&&await this.setOutputDestinations(a.destinations),a?.resolution!==void 0&&i?.resolution!==a.resolution&&await this.setOutputResolution(a.resolution),a?.aspectRatio!==void 0&&i?.aspectRatio!==a.aspectRatio&&await this.setOutputAspectRatio(a.aspectRatio);const r=e.timeline?.background;r&&this.backgroundColor!==r&&await this.setTimelineBackground(r);const n=e.timeline.tracks;for(let o=0;o<n.length;o+=1){const l=t[o].clips,c=n[o].clips;for(let d=0;d<c.length;d+=1){const u=l[d],f=c[d];JSON.stringify(u)!==JSON.stringify(f)&&await this.updateClip(o,d,f)}}}createCommandContext(){return{getClips:()=>this.clips,getTracks:()=>this.tracks,getTrack:e=>e>=0&&e<this.tracks.length?this.tracks[e]:null,getContainer:()=>this.getViewportContainer(),addPlayer:(e,t)=>this.addPlayer(e,t),addPlayerToContainer:(e,t)=>{this.addPlayerToContainer(e,t)},createPlayerFromAssetType:e=>this.createPlayerFromAssetType(e),queueDisposeClip:e=>this.queueDisposeClip(e),disposeClips:()=>this.disposeClips(),clearClipError:(e,t)=>this.clearClipErrorAndShift(e,t),undeleteClip:(e,t)=>{let i=0;if(e>=0&&e<this.tracks.length){const a=this.tracks[e];i=a.length;for(let r=0;r<a.length;r+=1)if(a[r].getStart()>t.getStart()){i=r;break}a.splice(i,0,t)}if(this.document){const a=t.getExportableClip();this.document.addClip(e,a,i);const r=this.document.getClipId(e,i);r&&(t.clipId=r,this.playerByClipId.set(r,t))}this.addPlayerToContainer(e,t),t.load().catch(a=>{const r=t.clipConfiguration?.asset?.type??"unknown",n=a instanceof Error?a.message:String(a);this.clipErrors.set(`${e}-${i}`,{error:n,assetType:r}),this.internalEvents.emit(Z.ClipLoadFailed,{trackIndex:e,clipIndex:i,error:n,assetType:r})}),this.updateTotalDuration()},setUpdatedClip:()=>{},restoreClipConfiguration:(e,t)=>{const i=structuredClone(t),a=e.clipConfiguration;for(const r of Object.keys(a))delete a[r];if(Object.assign(a,i),e.reconfigureAfterRestore(),this.document){const r=this.findClipIndices(e);if(r){const n=e.getExportableClip();this.document.replaceClip(r.trackIndex,r.clipIndex,n)}}},updateDuration:()=>this.updateTotalDuration(),emitEvent:(e,...t)=>this.internalEvents.emit(e,...t),findClipIndices:e=>this.selectionManager.findClipIndices(e),getClipAt:(e,t)=>this.getClipAt(e,t),getSelectedClip:()=>this.selectionManager.getSelectedClip(),setSelectedClip:e=>{this.selectionManager.setSelectedClip(e)},movePlayerToTrackContainer:(e,t,i)=>this.movePlayerToTrackContainer(e,t,i),getEditState:()=>this.getResolvedEdit(),propagateTimingChanges:(e,t)=>this.propagateTimingChanges(e,t),resolveClipAutoLength:e=>this.resolveClipAutoLength(e),getMergeFields:()=>this.mergeFieldService,getOutputSize:()=>this.outputSettings.getSize(),setOutputSize:(e,t)=>this.outputSettings.setSize(e,t),getOutputFps:()=>this.outputSettings.getFps(),setOutputFps:e=>this.outputSettings.setFps(e),getOutputFormat:()=>this.outputSettings.getFormat(),setOutputFormat:e=>this.outputSettings.setFormat(e),getOutputResolution:()=>this.outputSettings.getResolution(),setOutputResolution:e=>this.outputSettings.setResolution(e),getOutputAspectRatio:()=>this.outputSettings.getAspectRatio(),setOutputAspectRatio:e=>this.outputSettings.setAspectRatio(e),getOutputDestinations:()=>this.outputSettings.getDestinations(),setOutputDestinations:e=>this.outputSettings.setDestinations(e),getTimelineBackground:()=>this.getTimelineBackground(),setTimelineBackground:e=>this.setTimelineBackgroundInternal(e),getDocument:()=>this.document,getDocumentTrack:e=>this.document?.getTrack(e)??null,getDocumentClip:(e,t)=>this.document?.getClip(e,t)??null,documentUpdateClip:(e,t,i)=>{if(!this.document)throw new Error("Document not initialized - cannot update clip");this.document.updateClip(e,t,i)},documentAddClip:(e,t,i)=>{if(!this.document)throw new Error("Document not initialized - cannot add clip");for(;this.document.getTrackCount()<=e;)this.document.addTrack(this.document.getTrackCount());return this.document.addClip(e,t,i)},documentRemoveClip:(e,t)=>{if(!this.document)throw new Error("Document not initialized - cannot remove clip");return this.document.removeClip(e,t)},derivePlayerFromDocument:(e,t)=>{const i=this.document?.getClip(e,t);if(!i)throw new Error(`derivePlayerFromDocument: No document clip at ${e}/${t} - state desync`);const a=this.getClipAt(e,t);if(!a)throw new Error(`derivePlayerFromDocument: No player at ${e}/${t} - state desync`);const{asset:r,...n}=i;Object.assign(a.clipConfiguration,n),a.reconfigureAfterRestore()},buildResolutionContext:(e,t)=>{let i=0;if(t>0){const o=this.tracks[e];o&&o[t-1]&&(i=o[t-1].getEnd())}const a=fc(this.tracks);let r=null;const n=this.getClipAt(e,t);return n&&n.getTimingIntent().length==="auto"&&(r=n.getLength()),{previousClipEnd:i,timelineEnd:a,intrinsicDuration:r}},resolve:()=>this.resolve(),resolveClip:e=>this.resolveClip(e),getPlayerByClipId:e=>this.playerByClipId.get(e)??null,registerPlayerByClipId:(e,t)=>{this.playerByClipId.set(e,t)},unregisterPlayerByClipId:e=>{this.playerByClipId.delete(e)},setClipBinding:(e,t,i)=>{this.document?.setClipBinding(e,t,i)},getClipBinding:(e,t)=>this.document?.getClipBinding(e,t),removeClipBinding:(e,t)=>{this.document?.removeClipBinding(e,t)},getClipBindings:e=>this.document?.getClipBindings(e),getEditSession:()=>this}}queueDisposeClip(e){this.clipsToDispose.add(e)}disposeClips(){if(this.clipsToDispose.size!==0){for(const e of this.clipsToDispose)e.playerType===it.Luma&&(this.lumaMaskController.cleanupForPlayer(e),e.clipId&&this.lumaContentRelations.delete(e.clipId));for(const e of this.clipsToDispose)e.clipId&&this.playerByClipId.delete(e.clipId);for(const e of this.clipsToDispose)this.disposeClip(e);for(const e of this.clipsToDispose){const t=e.layer-1;if(t>=0&&t<this.tracks.length){const i=this.tracks[t].indexOf(e);i!==-1&&this.tracks[t].splice(i,1)}}this.clipsToDispose.clear(),this.updateTotalDuration(),this.cleanupUnusedFonts()}}cleanupUnusedFonts(){if(!this.document)return;const e=this.document.getFonts();if(e.length===0)return;const t=new Set;for(const i of this.clips){const{asset:a}=i.clipConfiguration;a&&a.type==="rich-text"&&a.font?.family&&t.add(a.font.family)}for(const i of e)if(i.src.includes("fonts.gstatic.com")){const r=this.extractFilenameFromUrl(i.src);r&&!t.has(r)&&this.document.removeFont(i.src)}}extractFilenameFromUrl(e){try{const{pathname:t}=new URL(e),i=t.split("/").pop();return i?i.replace(/\.[^.]+$/,""):null}catch{return null}}disposeClip(e){try{const t=this.canvas?.getViewportContainer();if(t){for(const i of t.children)if(i instanceof G.Container&&i.label?.toString().startsWith("shotstack-track-")&&i.children.includes(e.getContainer())){i.removeChild(e.getContainer());break}}}catch(t){console.warn(`Attempting to unmount an unmounted clip: ${t}`)}this.unloadClipAssets(e),this.timingManager.invalidateTimelineEndCache(),e.dispose()}unloadClipAssets(e){const{asset:t}=e.clipConfiguration;t&&"src"in t&&typeof t.src=="string"&&this.assetLoader.decrementRef(t.src)&&G.Assets.cache.has(t.src)&&G.Assets.unload(t.src)}clearClips(){for(const e of this.clips)this.disposeClip(e);this.tracks=[],this.clipsToDispose.clear(),this.clipErrors.clear(),this.lumaContentRelations.clear(),this.updateTotalDuration()}updateTotalDuration(){let e=0;for(const i of this.tracks)for(const a of i)e=Math.max(e,a.getEnd());const t=this.totalDuration;this.totalDuration=e,t!==this.totalDuration&&this.internalEvents.emit(Z.DurationChanged,{duration:this.totalDuration})}propagateTimingChanges(e,t){this.timingManager.propagateTimingChanges(e,t)}async resolveClipAutoLength(e){const t=e.getTimingIntent();if(t.length!=="auto")return;const i=this.findClipIndices(e);let a=e.getStart();t.start==="auto"&&i&&(a=fp(i.trackIndex,i.clipIndex,this.tracks));const r=await up(e.clipConfiguration.asset);e.setResolvedTiming({start:a,length:r}),e.reconfigureAfterRestore(),i&&this.propagateTimingChanges(i.trackIndex,i.clipIndex)}addPlayerToContainer(e,t){this.internalEvents.emit(Be.PlayerAddedToTrack,{player:t,trackIndex:e})}movePlayerToTrackContainer(e,t,i){this.internalEvents.emit(Be.PlayerMovedBetweenTracks,{player:e,fromTrackIndex:t,toTrackIndex:i})}createPlayerFromAssetType(e){return np.create(this,e)}async addPlayer(e,t){for(;this.tracks.length<=e;)this.tracks.push([]);this.tracks[e].push(t),this.internalEvents.emit(Be.PlayerAddedToTrack,{player:t,trackIndex:e}),await t.load(),this.updateTotalDuration()}selectClip(e,t){this.selectionManager.selectClip(e,t)}clearSelection(){this.selectionManager.clearSelection()}isClipSelected(e,t){return this.selectionManager.isClipSelected(e,t)}getSelectedClipInfo(){return this.selectionManager.getSelectedClipInfo()}copyClip(e,t){this.selectionManager.copyClip(e,t)}pasteClip(){this.selectionManager.pasteClip()}hasCopiedClip(){return this.selectionManager.hasCopiedClip()}findClipIndices(e){return this.selectionManager.findClipIndices(e)}getClipAt(e,t){return e>=0&&e<this.tracks.length&&t>=0&&t<this.tracks[e].length?this.tracks[e][t]:null}selectPlayer(e){this.selectionManager.selectPlayer(e)}isPlayerSelected(e){return this.selectionManager.isPlayerSelected(e)}getActivePlayersExcept(e){const t=[];for(const i of this.tracks)for(const a of i)a!==e&&a.isActive()&&t.push(a);return t}showAlignmentGuide(e,t,i,a){this.canvas?.showAlignmentGuide(e,t,i,a)}clearAlignmentGuides(){this.canvas?.clearAlignmentGuides()}moveSelectedClip(e,t){const i=this.getSelectedClipInfo();if(!i)return;const{player:a,trackIndex:r,clipIndex:n}=i,o=this.getResolvedClip(r,n);if(!o)return;const l=structuredClone(o),c=a.calculateMoveOffset(e,t),d=structuredClone(l);d.offset=c,this.setUpdatedClip(a,l,d)}setExportMode(e){this.isExporting=e}isInExportMode(){return this.isExporting}setCanvas(e){this.canvas=e}getCanvas(){return this.canvas}getCanvasZoom(){return this.canvas?.getZoom()??1}getViewportContainer(){if(!this.canvas)throw new Error("Canvas not attached. Viewport container requires Canvas.");return this.canvas.getViewportContainer()}setOutputSize(e,t){const i=new FI(e,t);return this.executeCommand(i)}setOutputFps(e){const t=new NI(e);return this.executeCommand(t)}getOutputFps(){return this.outputSettings.getFps()}setOutputFormat(e){const t=new EI(e);return this.executeCommand(t)}getOutputFormat(){return this.outputSettings.getFormat()}setOutputDestinations(e){const t=new TI(e);return this.executeCommand(t)}getOutputDestinations(){return this.outputSettings.getDestinations()}setOutputResolution(e){const t=new PI(e);return this.executeCommand(t)}getOutputResolution(){return this.outputSettings.getResolution()}setOutputAspectRatio(e){const t=new II(e);return this.executeCommand(t)}getOutputAspectRatio(){return this.outputSettings.getAspectRatio()}getTimelineFonts(){return this.document.getFonts()}getFontMetadata(){return this.fontMetadata}getFontUrlByFamilyAndWeight(e,t){const{baseFontFamily:i}=ts(e),a=i.toLowerCase();for(const[r,n]of this.fontMetadata)if(n.baseFamilyName.toLowerCase()===a&&n.weight===t)return r;for(const[r,n]of this.fontMetadata)if(n.baseFamilyName.toLowerCase()===a)return r;return null}pruneUnusedFonts(){this.cleanupUnusedFonts()}setTimelineBackground(e){const t=new VI(e);return this.executeCommand(t)}setTimelineBackgroundInternal(e){gx.parse(e),this.backgroundColor=e,this.document.setBackground(e),this.internalEvents.emit(Be.ViewportSizeChanged,{width:this.size.width,height:this.size.height,backgroundColor:this.backgroundColor}),this.internalEvents.emit(Z.TimelineBackgroundChanged,{color:e})}getTimelineBackground(){return this.backgroundColor}resolveMergeFields(e){return this.mergeFieldService.resolve(e)}getTemplateClip(e,t){const i=this.getPlayerClip(e,t);if(!i)return null;const a=i.getExportableClip();if(!a)return null;const{clipId:r}=i;if(r&&this.document){const n=this.document.getClipBindings(r);if(n)for(const[o,{placeholder:l}]of n)Zs(a,o,l)}return a}getTemplateClipById(e){const t=this.getPlayerByClipId(e);if(!t)return null;const i=t.getExportableClip();if(!i||!this.document)return null;const a=this.document.getClipBindings(e);if(a)for(const[r,{placeholder:n}]of a)Zs(i,r,n);return i}getTemplateClipText(e,t){const i=this.getTemplateClip(e,t);return i?i.asset?.text??null:null}getLumaClipIdForContent(e){for(const[t,i]of this.lumaContentRelations)if(i===e)return t;return null}getContentClipIdForLuma(e){return this.lumaContentRelations.get(e)??null}setLumaContentRelationship(e,t){this.lumaContentRelations.set(e,t)}clearLumaContentRelationship(e){this.lumaContentRelations.delete(e)}getLumaContentRelationship(e){return this.lumaContentRelations.get(e)}normalizeLumaAttachments(){let e=!1;for(let t=0;t<this.tracks.length;t+=1){const i=this.tracks[t];for(const a of i)if(a.playerType===it.Luma){const r=this.findBestContentMatch(t,a);if(r){a.clipId&&r.clipId&&this.lumaContentRelations.set(a.clipId,r.clipId);const n=i.indexOf(a);this.document.updateClip(t,n,{start:r.getStart(),length:r.getLength()}),e=!0}}}e&&this.resolve()}findBestContentMatch(e,t){const i=this.tracks[e],a=t.getStart(),r=a+t.getLength();let n=null,o=0;for(const l of i)if(l.playerType!==it.Luma){const c=l.getStart(),d=c+l.getLength(),u=f6(a,r,c,d);u>o&&(o=u,n=l)}return n}setupIntentListeners(){this.internalEvents.on(Be.CanvasClipClicked,e=>{this.selectPlayer(e.player)}),this.internalEvents.on(Be.CanvasBackgroundClicked,()=>{this.clearSelection()})}getTracks(){return this.tracks}getTrackCount(){return this.document.getTrackCount()}getClipCountInTrack(e){return this.document.getClipCountInTrack(e)}}const vp=16711935,xp=2,gc=6,Cp=4;class x6{graphics;canvasWidth;canvasHeight;constructor(e,t,i){this.canvasWidth=t,this.canvasHeight=i,this.graphics=new G.Graphics,this.graphics.zIndex=999999,e.addChild(this.graphics)}clear(){this.graphics.clear()}drawCanvasGuide(e,t){this.graphics.strokeStyle={width:xp,color:vp},e==="x"?(this.graphics.moveTo(t,0),this.graphics.lineTo(t,this.canvasHeight)):(this.graphics.moveTo(0,t),this.graphics.lineTo(this.canvasWidth,t)),this.graphics.stroke()}drawClipGuide(e,t,i,a){e==="x"?this.drawDashedLine(t,i,t,a):this.drawDashedLine(i,t,a,t)}drawDashedLine(e,t,i,a){const r=i-e,n=a-t,o=Math.sqrt(r*r+n*n),l=Math.floor(o/(gc+Cp)),c=r/o,d=n/o;this.graphics.strokeStyle={width:xp,color:vp};for(let u=0;u<l;u+=1){const f=u*(gc+Cp),p=f+gc,g=e+c*f,w=t+d*f,C=e+c*Math.min(p,o),v=t+d*Math.min(p,o);this.graphics.moveTo(g,w),this.graphics.lineTo(C,v)}this.graphics.stroke()}updateSize(e,t){this.canvasWidth=e,this.canvasHeight=t}dispose(){this.graphics.destroy()}}const C6="Browser Not Supported",k6="Please try a different browser or enable hardware acceleration in your browser settings.";function S6(s,e){const t=C6,i=k6,a=document.createElement("div");a.className="ss-webgl-error-overlay";const r=document.createElement("div");r.className="ss-webgl-error-content";const n=document.createElement("div");n.className="ss-webgl-error-icon",n.innerHTML=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
|
|
277
|
+
`),l=o===-1?this.textPosition:this.textPosition-o-1,c=n.substring(0,l);let d;c.length>0&&c.endsWith(" ")?d=this.measureText(`${c}x`,t)-this.measureText("x",t):d=this.measureText(c,t);const u=t.lineHeight;this.pixelY=this.currentLine*u;const p=this.clipConfig.asset.alignment?.horizontal??"center";let g=d;if(p!=="left"){const w=this.measureText(n,t),C=this.textElement.width;let v=0;p==="center"?v=(C-w)/2:p==="right"&&(v=C-w),g=v+d}this.pixelX=g}updateGraphicsPosition(){this.cursor&&this.cursor.position.set(this.pixelX,this.pixelY)}startBlinkingAnimation(){!this.cursor||this.isBlinking||(this.isBlinking=!0,this.blinkInterval=window.setInterval(()=>{this.cursor&&this.isBlinking&&(this.cursor.visible=!this.cursor.visible)},this.blinkIntervalMs))}stopBlinkingAnimation(){this.blinkInterval!==null&&(window.clearInterval(this.blinkInterval),this.blinkInterval=null),this.isBlinking=!1,this.cursor&&(this.cursor.visible=this.isVisible)}measureText(e,t){const i=new G.Text(e,t),{width:a}=i;return i.destroy(),a}isInitialized(){return this.cursor!==null}getState(){return{isInitialized:this.isInitialized(),isBlinking:this.isBlinking,isVisible:this.isVisible,textPosition:this.textPosition,pixelPosition:{x:this.pixelX,y:this.pixelY},currentLine:this.currentLine}}}class Kn{static DEFAULT_FOCUS_DELAY_MS=50;hiddenInput=null;isFocused=!1;focusRetryCount=0;maxFocusRetries=3;focusDelay=Kn.DEFAULT_FOCUS_DELAY_MS;eventHandlers={};abortController=null;textChangeCallback=null;lastSyncedText="";isComposing=!1;setupInput(e,t){this.focusDelay=t?.focusDelay??Kn.DEFAULT_FOCUS_DELAY_MS,this.createHiddenTextarea(),this.hiddenInput&&(this.hiddenInput.value=e,this.lastSyncedText=e),this.setupEventListeners(),t?.autoFocus!==!1&&this.focusInput()}updateInputValue(e){this.hiddenInput&&(this.hiddenInput.value=e,this.lastSyncedText=e)}focusInput(){this.hiddenInput&&setTimeout(()=>{this.hiddenInput&&!this.isFocused&&(this.hiddenInput.focus(),setTimeout(()=>{!this.isFocused&&this.focusRetryCount<this.maxFocusRetries&&(this.focusRetryCount+=1,this.focusInput())},10))},this.focusDelay)}blurInput(){this.hiddenInput&&this.hiddenInput.blur()}setSelectionRange(e,t){if(!this.hiddenInput)return;const i=this.hiddenInput.value.length,a=Math.max(0,Math.min(e,i)),r=Math.max(a,Math.min(t,i));this.hiddenInput.setSelectionRange(a,r)}getCursorPosition(){return this.hiddenInput?.selectionStart||0}getValue(){return this.hiddenInput?.value||""}setTextInputHandler(e){this.textChangeCallback=e}setEventHandlers(e){this.eventHandlers={...this.eventHandlers,...e}}isFocusedInput(){return this.isFocused}dispose(){this.removeAllEventListeners(),this.hiddenInput&&this.hiddenInput.parentNode&&this.hiddenInput.parentNode.removeChild(this.hiddenInput),this.hiddenInput=null,this.isFocused=!1,this.focusRetryCount=0,this.textChangeCallback=null,this.eventHandlers={}}createHiddenTextarea(){this.hiddenInput=document.createElement("textarea");const e={position:"absolute",opacity:"0.01",pointerEvents:"none",zIndex:"18",left:"0px",top:"0px",width:"1px",height:"1px",border:"none",outline:"none",resize:"none",backgroundColor:"transparent"};Object.assign(this.hiddenInput.style,e),this.hiddenInput.tabIndex=0,document.body.appendChild(this.hiddenInput)}setupEventListeners(){if(!this.hiddenInput)return;this.abortController=new AbortController;const{signal:e}=this.abortController;this.hiddenInput.addEventListener("input",this.handleTextInput,{signal:e}),this.hiddenInput.addEventListener("keydown",this.handleKeyDown,{signal:e}),this.hiddenInput.addEventListener("compositionstart",this.handleCompositionStart,{signal:e}),this.hiddenInput.addEventListener("compositionend",this.handleCompositionEnd,{signal:e}),this.hiddenInput.addEventListener("focus",this.handleFocus,{signal:e}),this.hiddenInput.addEventListener("blur",this.handleBlur,{signal:e}),this.hiddenInput.addEventListener("paste",this.handlePaste,{signal:e})}removeAllEventListeners(){this.abortController?.abort(),this.abortController=null}handleTextInput=e=>{if(!this.hiddenInput||this.isComposing)return;const t=this.hiddenInput.value,i=this.hiddenInput.selectionStart||0;this.lastSyncedText=t,this.textChangeCallback?.(t,i)};handleKeyDown=e=>{if(document.activeElement!==this.hiddenInput)return;let t=!1;if((e.ctrlKey||e.metaKey)&&(t=this.handleKeyboardShortcuts(e),t)){e.preventDefault();return}if(e.key==="Tab"){const i=e.shiftKey?"backward":"forward";this.eventHandlers.onTabNavigation?.(i),e.preventDefault();return}switch(e.key){case"Escape":this.eventHandlers.onEscape?.(e),t=!0;break;case"Enter":t=!1;break;case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"ArrowDown":setTimeout(()=>{if(this.hiddenInput){const i=this.hiddenInput.value,a=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(i,a)}},0),t=!1;break;case"Backspace":case"Delete":t=!1;break;default:t=this.eventHandlers.onCustomKey?.(e.key,e)||!1;break}t&&e.preventDefault()};handleKeyboardShortcuts(e){const{key:t}=e;switch(t.toLowerCase()){case"a":return this.selectAll(),!0;case"c":case"v":return!1;case"z":return this.eventHandlers.onCustomKey?.("undo",e),!0;case"y":return this.eventHandlers.onCustomKey?.("redo",e),!0;default:return!1}}handleCompositionStart=e=>{this.isComposing=!0};handleCompositionEnd=e=>{if(this.isComposing=!1,this.hiddenInput){const t=this.hiddenInput.value,i=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(t,i)}};handleFocus=e=>{this.isFocused=!0,this.focusRetryCount=0,this.eventHandlers.onFocus?.(e)};handleBlur=e=>{this.isFocused=!1,this.eventHandlers.onBlur?.(e)};handlePaste=e=>{setTimeout(()=>{this.handleTextInput(e)},0)};selectAll(){this.hiddenInput&&this.hiddenInput.select()}}class Ts{static DOUBLE_CLICK_THRESHOLD_MS=300;static EDITING_BG_PADDING_PX=5;static EDITING_BG_ALPHA=.2;static CLICK_HANDLER_DELAY_MS=100;parent;targetText;clipConfig;isEditing=!1;lastClickTime=0;editingContainer=null;editableText=null;textCursor=null;textInputHandler=null;outsideClickHandler=null;constructor(e,t,i){this.parent=e,this.targetText=t,this.clipConfig=i,this.parent.getContainer().eventMode="static",this.parent.getContainer().on("click",this.checkForDoubleClick)}dispose(){this.parent.getContainer().off("click",this.checkForDoubleClick),this.stopEditing(),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null)}startEditing(){if(this.isEditing||!this.targetText)return;const e=structuredClone(this.clipConfig);this.targetText.visible=!1,this.createEditingEnvironment(),this.setupOutsideClickHandler(e),this.isEditing=!0}stopEditing(e=!1,t){if(!this.isEditing)return;let i="";this.editableText&&(i=this.editableText.text),this.editingContainer&&(this.parent.getContainer().removeChild(this.editingContainer),this.editingContainer.destroy(),this.editingContainer=null),this.editableText=null,this.textCursor&&(this.textCursor.dispose(),this.textCursor=null),this.textInputHandler&&(this.textInputHandler.dispose(),this.textInputHandler=null),this.targetText.visible=!0,e&&t&&i!==""&&this.parent.updateTextContent(i,t),this.isEditing=!1}checkForDoubleClick=e=>{const t=Date.now();t-this.lastClickTime<Ts.DOUBLE_CLICK_THRESHOLD_MS&&this.startEditing(),this.lastClickTime=t};setupOutsideClickHandler(e){this.outsideClickHandler=t=>{const a=this.parent.getContainer().getBounds(),r=t.clientX,n=t.clientY;(r<a.x||r>a.x+a.width||n<a.y||n>a.y+a.height)&&(this.stopEditing(!0,e),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null))},setTimeout(()=>{this.outsideClickHandler&&window.addEventListener("click",this.outsideClickHandler)},Ts.CLICK_HANDLER_DELAY_MS)}createEditingEnvironment(){this.setupEditingContainer(),this.editingContainer&&this.editableText&&(this.textCursor=new yr(this.editingContainer,this.editableText,this.clipConfig),this.textCursor.updatePosition(this.targetText.text.length),this.textCursor.startBlinking()),this.setupTextInputHandler(),this.updateTextAlignment()}setupEditingContainer(){this.editingContainer=new G.Container,this.parent.getContainer().addChild(this.editingContainer);const e=new G.Graphics;e.fillStyle={color:0,alpha:Ts.EDITING_BG_ALPHA},e.rect(-5,-5,this.targetText.width+2*Ts.EDITING_BG_PADDING_PX,this.targetText.height+2*Ts.EDITING_BG_PADDING_PX),e.fill(),this.editingContainer.addChild(e),this.editableText=new G.Text(this.targetText.text,this.targetText.style),this.editableText.eventMode="static",this.editableText.cursor="text",this.editingContainer.addChild(this.editableText)}setupTextInputHandler(){this.textInputHandler=new Kn,this.textInputHandler.setTextInputHandler((e,t)=>{this.editableText&&(this.editableText.text=e,this.updateTextAlignment()),this.textCursor?.updatePosition(t)}),this.textInputHandler.setEventHandlers({onEscape:e=>this.stopEditing(!1),onTabNavigation:e=>this.stopEditing(!0)}),this.textInputHandler.setupInput(this.targetText.text,{autoFocus:!0})}updateTextAlignment(){if(!this.editableText||!this.editingContainer)return;const e=this.getContainerDimensions(),t=this.getAlignmentSettings(),i=this.calculateHorizontalPosition({width:this.editableText.width},e,t.horizontal),a=this.calculateVerticalPosition({height:this.editableText.height},e,t.vertical);if(this.editingContainer.position.set(i,a),this.editingContainer.children.length>0){const r=this.editingContainer.getChildAt(0);r instanceof G.Graphics&&(r.clear(),r.fillStyle={color:0,alpha:Ts.EDITING_BG_ALPHA},r.rect(-5,-5,this.editableText.width+2*Ts.EDITING_BG_PADDING_PX,this.editableText.height+2*Ts.EDITING_BG_PADDING_PX),r.fill())}}calculateHorizontalPosition(e,t,i="center"){switch(i){case"center":return t.width/2-e.width/2;case"right":return t.width-e.width;case"left":default:return 0}}calculateVerticalPosition(e,t,i="center"){switch(i){case"center":return t.height/2-e.height/2;case"bottom":return t.height-e.height;case"top":default:return 0}}getContainerDimensions(){const e=this.clipConfig.asset;return{width:e.width??this.parent.getSize().width,height:e.height??this.parent.getSize().height}}getAlignmentSettings(){const e=this.clipConfig.asset;return{horizontal:e.alignment?.horizontal??"center",vertical:e.alignment?.vertical??"center"}}}class ba extends Lt{static loadedFonts=new Set;background=null;text=null;textEditor=null;constructor(e,t){super(e,t,it.Text)}async load(){await super.load();const e=this.clipConfiguration.asset,t=e.font?.family??"Open Sans";if(await this.loadFont(t),this.background=new G.Graphics,this.drawBackground(),this.text=new G.Text({text:e.text??"",style:this.createTextStyle(e)}),this.positionText(e),e.stroke?.width&&e.stroke.width>0&&e.stroke.color){const i=new Ua({thickness:e.stroke.width,color:e.stroke.color});this.text.filters=[i]}this.contentContainer.addChild(this.background),this.contentContainer.addChild(this.text),this.configureKeyframes(),this.textEditor=new Ts(this,this.text,this.clipConfiguration)}update(e,t){super.update(e,t)}reconfigureAfterRestore(){super.reconfigureAfterRestore(),this.reconfigure()}async reconfigure(){const e=this.clipConfiguration.asset,t=e.font?.family??"Open Sans";if(await this.loadFont(t),this.drawBackground(),this.text){if(this.text.text=e.text??"",this.text.style=this.createTextStyle(e),e.stroke?.width&&e.stroke.width>0&&e.stroke.color){const i=new Ua({thickness:e.stroke.width,color:e.stroke.color});this.text.filters=[i]}else this.text.filters=[];this.positionText(e)}}dispose(){super.dispose(),this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null,this.textEditor?.dispose(),this.textEditor=null}getSize(){const e=this.clipConfiguration.asset;return{width:this.clipConfiguration.width??e.width??this.edit.size.width,height:this.clipConfiguration.height??e.height??this.edit.size.height}}getFitScale(){return 1}getContainerScale(){const e=this.getScale();return{x:e,y:e}}supportsEdgeResize(){return!0}onDimensionsChanged(){if(this.drawBackground(),this.text){const e=this.clipConfiguration.asset;this.text.style.wordWrapWidth=this.getSize().width,this.positionText(e)}}applyFixedDimensions(){}createTextStyle(e){const t=e.font?.family??"Open Sans",{baseFontFamily:i,fontWeight:a}=ts(t),{width:r}=this.getSize();return new G.TextStyle({fontFamily:i,fontSize:e.font?.size??32,fill:e.font?.color??"#ffffff",fontWeight:a.toString(),wordWrap:!0,wordWrapWidth:r,lineHeight:(e.font?.lineHeight??1)*(e.font?.size??32),align:e.alignment?.horizontal??"center"})}positionText(e){if(!this.text)return;const t=e.alignment?.horizontal??"center",i=e.alignment?.vertical??"center",{width:a,height:r}=this.getSize();let n=a/2-this.text.width/2,o=r/2-this.text.height/2;t==="left"?n=0:t==="right"&&(n=a-this.text.width),i==="top"?o=0:i==="bottom"&&(o=r-this.text.height),this.text.position.set(n,o)}drawBackground(){const e=this.clipConfiguration.asset;if(!this.background||!e.background||!e.background.color)return;const{width:t,height:i}=this.getSize();this.background.clear(),this.background.fillStyle={color:e.background.color,alpha:e.background.opacity??1},this.background.rect(0,0,t,i),this.background.fill()}updateTextContent(e,t){this.edit.updateTextContent(this,e,t)}async loadFont(e){const{baseFontFamily:t,fontWeight:i}=ts(e),a=`${t}-${i}`;if(ba.loadedFonts.has(a))return;const r=Zr(e);if(r){const n=new FontFace(t,`url(${r})`,{weight:i.toString()});await n.load(),document.fonts.add(n),ba.loadedFonts.add(a)}}static resetFontCache(){ba.loadedFonts.clear()}}class vI extends Lt{aiOverlay=null;lastPrompt="";constructor(e,t){super(e,t,it.TextToImage)}async load(){await super.load();const{width:e,height:t}=this.getSize(),i=this.edit.getResolvedEdit()?.timeline.tracks.flatMap(l=>l.clips)??[],a=Oo(i,this.clipId??""),{asset:r}=this.clipConfiguration,n=Qs(r)&&r.prompt||"",o=Qs(r)?r.type:"text-to-image";this.aiOverlay=new Do({mode:"panel",icon:"image",width:e,height:t,assetNumber:a??void 0,prompt:n,assetType:o}),this.contentContainer.addChild(this.aiOverlay.getContainer()),this.configureKeyframes()}update(e,t){super.update(e,t);const{width:i,height:a}=this.getSize();this.aiOverlay?.resize(i,a);const{asset:r}=this.clipConfiguration,n=Qs(r)&&r.prompt||"";n!==this.lastPrompt&&(this.aiOverlay?.updatePrompt(n),this.lastPrompt=n)}getSize(){const e=this.clipConfiguration.asset;return{width:this.clipConfiguration.width??e.width??this.edit.size.width,height:this.clipConfiguration.height??e.height??this.edit.size.height}}dispose(){this.aiOverlay?.dispose(),this.aiOverlay=null,super.dispose()}}class xI extends Lt{constructor(e,t){super(e,t,it.TextToSpeech)}async load(){await super.load(),this.configureKeyframes()}update(e,t){super.update(e,t),this.getContainer().alpha=0}getSize(){return{width:0,height:0}}}class CI extends Lt{texture;sprite;isPlaying;volumeKeyframeBuilder;syncTimer;activeSyncTimer;skipVideoUpdate;constructor(e,t){super(e,t,it.Video),this.texture=null,this.sprite=null,this.isPlaying=!1;const i=this.clipConfiguration.asset;this.volumeKeyframeBuilder=new Da(i.volume??1,this.getLength()),this.syncTimer=0,this.activeSyncTimer=0,this.skipVideoUpdate=!1}async load(){await super.load(),await this.loadVideo(),this.configureKeyframes()}update(e,t){if(super.update(e,t),this.skipVideoUpdate)return;const{trim:i=0}=this.clipConfiguration.asset;if(this.syncTimer+=t,!this.texture)return;const a=this.getPlaybackTime(),r=this.edit.isPlaying&&this.isActive();r&&(this.isPlaying||(this.isPlaying=!0,this.activeSyncTimer=0,this.texture.source.resource.currentTime=a+i,this.texture.source.resource.play().catch(console.error)),this.texture.source.resource.volume!==this.getVolume()&&(this.texture.source.resource.volume=this.getVolume()),this.activeSyncTimer+=t,this.activeSyncTimer>1e3&&(this.activeSyncTimer=0,Math.abs(this.texture.source.resource.currentTime-i-a)>.3&&(this.texture.source.resource.currentTime=a+i,this.edit.recordSyncCorrection()))),!r&&this.isPlaying&&(this.isPlaying=!1,this.texture.source.resource.pause());const n=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&n&&(this.syncTimer=0,this.texture.source.resource.currentTime=a+i)}dispose(){super.dispose(),this.disposeVideo()}getSize(){return this.clipConfiguration.width&&this.clipConfiguration.height?{width:this.clipConfiguration.width,height:this.clipConfiguration.height}:{width:this.sprite?.width??0,height:this.sprite?.height??0}}supportsEdgeResize(){return!0}async reloadAsset(){this.skipVideoUpdate=!0,this.disposeVideo(),await this.loadVideo(),this.isPlaying=!1,this.syncTimer=0,this.activeSyncTimer=0,this.skipVideoUpdate=!1}async loadVideo(){const e=this.clipConfiguration.asset,{src:t}=e;if(t.endsWith(".mov"))throw new Error(`Video source '${t}' is not supported. .mov files cannot be played in the browser. Please convert to .webm or .mp4 first.`);const i=`${t}${t.includes("?")?"&":"?"}x-cors=1`,a={src:i,data:{autoPlay:!1,muted:!1}},r=await this.edit.assetLoader.loadVideoUnique(i,a);if(!r||!(r.source instanceof G.VideoSource))throw new Error(`Invalid video source '${t}'.`);r.source.alphaMode="no-premultiply-alpha",this.texture=this.createCroppedTexture(r);const n=this.texture.source.resource;n instanceof HTMLVideoElement&&n.readyState<2&&await new Promise(o=>{const l=()=>{n.removeEventListener("loadeddata",l),o()};n.addEventListener("loadeddata",l),n.readyState>=2&&o()}),this.sprite=new G.Sprite(this.texture),this.contentContainer.addChild(this.sprite)}disposeVideo(){this.texture?.source?.resource&&(this.texture.source.resource.pause(),this.texture.source.resource.src="",this.texture.source.resource.load()),this.sprite&&(this.contentContainer.removeChild(this.sprite),this.sprite.destroy(),this.sprite=null),this.texture&&(this.texture.destroy(!0),this.texture=null)}getVolume(){return this.volumeKeyframeBuilder.getValue(this.getPlaybackTime())}getCurrentDrift(){if(!this.texture?.source?.resource)return 0;const{trim:e=0}=this.clipConfiguration.asset,t=this.texture.source.resource.currentTime,i=this.getPlaybackTime();return Math.abs(t-e-i)}createCroppedTexture(e){const t=this.clipConfiguration.asset;if(!t.crop)return e;const i=e.width,a=e.height;if(i<=0||a<=0)return e;const r=Math.floor((t.crop?.left??0)*i),n=Math.floor((t.crop?.right??0)*i),o=Math.floor((t.crop?.top??0)*a),l=Math.floor((t.crop?.bottom??0)*a),c=r,d=o,u=i-r-n,f=a-o-l,p=new G.Rectangle(c,d,u,f);return new G.Texture({source:e.source,frame:p})}}class np{static create(e,t){if(!t.asset?.type)throw new Error("Invalid clip configuration: missing asset type");switch(t.asset.type){case"text":return new ba(e,t);case"rich-text":return new Is(e,t);case"shape":return new bI(e,t);case"html":return new Ug(e,t);case"image":return new Zg(e,t);case"video":return new CI(e,t);case"audio":return new vg(e,t);case"luma":return new Jg(e,t);case"caption":return new Hr(e,t);case"svg":return new Us(e,t);case"text-to-image":return new vI(e,t);case"image-to-video":return new Qg(e,t);case"text-to-speech":return new xI(e,t);default:throw new Error(`Unsupported asset type: ${t.asset.type}`)}}static cleanup(){ba.resetFontCache()}}function ac(s,e,t,i){const a=new Map,r=`alias://${t}`;for(let n=0;n<s.getTrackCount();n+=1){const o=s.getClipsInTrack(n);for(let l=0;l<o.length;l+=1)if(!i?.has(`${n}:${l}`)){const c=o[l],d=c.id,u=e.timeline.tracks[n]?.clips[l];let f=!1;const p={};if(c.start===r&&(p.start=c.start,f=!0),c.length===r&&(p.length=c.length,f=!0),f&&d&&u){a.set(d,p);const g={};p.start&&(g.start=u.start),p.length&&(g.length=u.length),s.updateClip(n,l,g)}}}return a}function kI(s,e,t,i){const a=new Map;for(const r of t){const n=ac(s,e,r,i);for(const[o,l]of n){const c=a.get(o);c?a.set(o,{...c,...l}):a.set(o,l)}}return a}function rc(s,e){for(const[t,i]of e){const a=s.getClipById(t);if(a){const r={};i.start&&(r.start=i.start),i.length&&(r.length=i.length),s.updateClip(a.trackIndex,a.clipIndex,r)}}}function SI(s){const e=[];for(const t of s){const{alias:i}=t;i&&e.push(i)}return e}const we=()=>({status:"success"}),Ne=s=>({status:"noop",message:s});class AI{constructor(e,t){this.trackIdx=e,this.clip=t}name="addClip";addedClipId;convertedReferences;execute(e){if(!e)throw new Error("AddClipCommand.execute: context is required");const t=e.getDocument();if(!t)throw new Error("AddClipCommand.execute: no document");const i=e.documentAddClip(this.trackIdx,this.clip);this.addedClipId=i.id,this.convertedReferences&&this.convertedReferences.size>0&&rc(t,this.convertedReferences),e.resolve(),e.updateDuration();const n=e.getDocumentTrack(this.trackIdx)?.clips?.findIndex(o=>o.id===this.addedClipId)??-1;return e.emitEvent(Z.ClipAdded,{trackIndex:this.trackIdx,clipIndex:n}),we()}undo(e){if(!e)throw new Error("AddClipCommand.undo: context is required");if(!this.addedClipId)return Ne("No clip ID stored");const t=e.getDocument();if(!t)throw new Error("AddClipCommand.undo: no document");const a=e.getDocumentTrack(this.trackIdx)?.clips,r=a?.findIndex(o=>o.id===this.addedClipId)??-1;if(r===-1)return Ne(`Clip ${this.addedClipId} not found in track ${this.trackIdx}`);const n=a?.[r]?.alias;if(n){const o=new Set([`${this.trackIdx}:${r}`]);this.convertedReferences=ac(t,e.getEditState(),n,o)}return e.documentRemoveClip(this.trackIdx,r),e.resolve(),e.updateDuration(),e.emitEvent(Z.ClipDeleted,{trackIndex:this.trackIdx,clipIndex:r}),we()}dispose(){this.addedClipId=void 0,this.convertedReferences=void 0}}class op{constructor(e){this.trackIdx=e}name="addTrack";execute(e){if(!e)throw new Error("AddTrackCommand.execute: context is required");const t=e.getDocument();if(!t)throw new Error("AddTrackCommand.execute: document is required");return t.addTrack(this.trackIdx),e.resolve(),e.updateDuration(),e.emitEvent(Z.TrackAdded,{trackIndex:this.trackIdx,totalTracks:t.getTrackCount()}),we()}undo(e){if(!e)throw new Error("AddTrackCommand.undo: context is required");const t=e.getDocument();if(!t)throw new Error("AddTrackCommand.undo: document is required");return t.removeTrack(this.trackIdx),e.resolve(),e.updateDuration(),we()}dispose(){}}class nc{constructor(e){this.trackIdx=e}name="deleteTrack";deletedClips=[];convertedReferences;execute(e){if(!e)throw new Error("DeleteTrackCommand.execute: context is required");const t=e.getDocument();if(!t)throw new Error("DeleteTrackCommand: no document");if(t.getTrackCount()<=1)return Ne("Cannot delete the last track");const i=t.getTrack(this.trackIdx);i&&(this.deletedClips=i.clips.map(r=>structuredClone(r)));const a=SI(this.deletedClips);if(a.length>0){const r=new Set;for(let n=0;n<this.deletedClips.length;n+=1)r.add(`${this.trackIdx}:${n}`);this.convertedReferences=kI(t,e.getEditState(),a,r)}return t.removeTrack(this.trackIdx),e.resolve(),e.updateDuration(),e.emitEvent(Z.TrackRemoved,{trackIndex:this.trackIdx}),we()}undo(e){if(!e)throw new Error("DeleteTrackCommand.undo: context is required");const t=e.getDocument();if(!t)throw new Error("DeleteTrackCommand.undo: no document");t.addTrack(this.trackIdx);for(let i=0;i<this.deletedClips.length;i+=1)t.addClip(this.trackIdx,this.deletedClips[i],i);return this.convertedReferences&&this.convertedReferences.size>0&&rc(t,this.convertedReferences),e.resolve(),e.updateDuration(),e.emitEvent(Z.TrackAdded,{trackIndex:this.trackIdx,totalTracks:t.getTrackCount()}),we()}dispose(){this.deletedClips=[],this.convertedReferences=void 0}}class oc{constructor(e,t){this.trackIdx=e,this.clipIdx=t}name="deleteClip";deletedClipConfig;deletedClipId;deleteTrackCommand;trackWasDeleted=!1;storedBindings;convertedReferences;execute(e){if(!e)throw new Error("DeleteClipCommand.execute: context is required");const t=e.getDocument();if(!t)throw new Error("DeleteClipCommand: no document");const i=t.getClip(this.trackIdx,this.clipIdx);if(!i)return Ne(`No clip at track ${this.trackIdx}, index ${this.clipIdx}`);if(this.deletedClipConfig=structuredClone(i),this.deletedClipId=i.id,this.deletedClipId){const o=e.getClipBindings(this.deletedClipId);this.storedBindings=o?new Map(o):void 0,t.clearClipBindings(this.deletedClipId)}const a=i.alias;if(a){const o=new Set([`${this.trackIdx}:${this.clipIdx}`]);this.convertedReferences=ac(t,e.getEditState(),a,o)}e.clearClipError(this.trackIdx,this.clipIdx);const r=e.getSelectedClip();r&&this.deletedClipId&&r.clipId===this.deletedClipId&&(e.setSelectedClip(null),e.emitEvent(Z.SelectionCleared)),e.documentRemoveClip(this.trackIdx,this.clipIdx);const n=t.getTrack(this.trackIdx);return n&&n.clips.length===0&&(this.deleteTrackCommand=new nc(this.trackIdx),this.deleteTrackCommand.execute(e).status==="success"&&(this.trackWasDeleted=!0)),e.resolve(),e.updateDuration(),e.emitEvent(Z.ClipDeleted,{trackIndex:this.trackIdx,clipIndex:this.clipIdx}),we()}undo(e){if(!e)throw new Error("DeleteClipCommand.undo: context is required");if(!this.deletedClipConfig)return Ne("No deleted clip config");const t=e.getDocument();if(!t)throw new Error("DeleteClipCommand.undo: no document");this.trackWasDeleted&&t.addTrack(this.trackIdx);const a=e.documentAddClip(this.trackIdx,this.deletedClipConfig,this.clipIdx).id;return a&&this.storedBindings&&this.storedBindings.size>0&&t.setClipBindingsForClip(a,this.storedBindings),this.convertedReferences&&this.convertedReferences.size>0&&rc(t,this.convertedReferences),e.resolve(),e.updateDuration(),this.trackWasDeleted&&(e.emitEvent(Z.TrackAdded,{trackIndex:this.trackIdx,totalTracks:t.getTrackCount()}),this.trackWasDeleted=!1),e.emitEvent(Z.ClipRestored,{trackIndex:this.trackIdx,clipIndex:this.clipIdx}),we()}dispose(){this.deletedClipConfig=void 0,this.deletedClipId=void 0,this.deleteTrackCommand=void 0,this.storedBindings=void 0,this.convertedReferences=void 0}}class II{constructor(e){this.aspectRatio=e}name="setOutputAspectRatio";previousAspectRatio;execute(e){if(!e)throw new Error("SetOutputAspectRatioCommand requires context");return this.previousAspectRatio=e.getOutputAspectRatio(),e.setOutputAspectRatio(this.aspectRatio),we()}undo(e){if(!e)throw new Error("SetOutputAspectRatioCommand requires context");return this.previousAspectRatio===void 0?Ne("No previous aspect ratio stored"):(e.setOutputAspectRatio(this.previousAspectRatio),we())}dispose(){this.previousAspectRatio=void 0}}class TI{constructor(e){this.destinations=e}name="setOutputDestinations";previousDestinations;execute(e){if(!e)throw new Error("SetOutputDestinationsCommand requires context");return this.previousDestinations=e.getOutputDestinations(),e.setOutputDestinations(this.destinations),we()}undo(e){if(!e)throw new Error("SetOutputDestinationsCommand requires context");return this.previousDestinations===void 0?Ne("No previous destinations stored"):(e.setOutputDestinations(this.previousDestinations),we())}dispose(){this.previousDestinations=void 0}}class EI{constructor(e){this.format=e}name="setOutputFormat";previousFormat;execute(e){if(!e)throw new Error("SetOutputFormatCommand requires context");return this.previousFormat=e.getOutputFormat(),e.setOutputFormat(this.format),we()}undo(e){if(!e)throw new Error("SetOutputFormatCommand requires context");return this.previousFormat===void 0?Ne("No previous format stored"):(e.setOutputFormat(this.previousFormat),we())}dispose(){this.previousFormat=void 0}}class NI{constructor(e){this.fps=e}name="setOutputFps";previousFps;execute(e){if(!e)throw new Error("SetOutputFpsCommand requires context");return this.previousFps=e.getOutputFps(),e.setOutputFps(this.fps),we()}undo(e){if(!e)throw new Error("SetOutputFpsCommand requires context");return this.previousFps===void 0?Ne("No previous FPS stored"):(e.setOutputFps(this.previousFps),we())}dispose(){this.previousFps=void 0}}class PI{constructor(e){this.resolution=e}name="setOutputResolution";previousResolution;execute(e){if(!e)throw new Error("SetOutputResolutionCommand requires context");return this.previousResolution=e.getOutputResolution(),e.setOutputResolution(this.resolution),we()}undo(e){if(!e)throw new Error("SetOutputResolutionCommand requires context");return this.previousResolution===void 0?Ne("No previous resolution stored"):(e.setOutputResolution(this.previousResolution),we())}dispose(){this.previousResolution=void 0}}class FI{constructor(e,t){this.width=e,this.height=t}name="setOutputSize";previousSize;execute(e){if(!e)throw new Error("SetOutputSizeCommand requires context");return this.previousSize=e.getOutputSize(),e.setOutputSize(this.width,this.height),we()}undo(e){if(!e)throw new Error("SetOutputSizeCommand requires context");return this.previousSize?(e.setOutputSize(this.previousSize.width,this.previousSize.height),we()):Ne("No previous size stored")}dispose(){this.previousSize=void 0}}class VI{constructor(e){this.color=e}name="setTimelineBackground";previousColor;execute(e){if(!e)throw new Error("SetTimelineBackgroundCommand requires context");return this.previousColor=e.getTimelineBackground(),e.setTimelineBackground(this.color),we()}undo(e){if(!e)throw new Error("SetTimelineBackgroundCommand requires context");return this.previousColor===void 0?Ne("No previous color stored"):(e.setTimelineBackground(this.previousColor),we())}dispose(){this.previousColor=void 0}}function Re(s){const{id:e,...t}=s;return t}function Qn(s){return!!(s&&typeof s=="object"&&!Array.isArray(s))}function lc(s,e){const t={...s};return Qn(s)&&Qn(e)&&Object.keys(e).forEach(i=>{if(i==="__proto__"||i==="constructor"||i==="prototype")return;const a=e[i],r=s[i];Qn(a)?i in s&&Qn(r)?t[i]=lc(r,a):t[i]=lc({},a):t[i]=a}),t}function Zs(s,e,t){const i=e.split(".");let a=s;for(let r=0;r<i.length-1;r+=1){if(a==null||typeof a!="object")return;const n=i[r],o=a[n];(o==null||typeof o!="object")&&(a[n]={}),a=a[n]}a!=null&&typeof a=="object"&&(a[i[i.length-1]]=t)}function wa(s,e){const t=e.split(".");let i=s;for(const a of t){if(i==null||typeof i!="object")return;i=i[a]}return i}function lp(s,e=50){let t=null,i=null,a=0;return{call:(...l)=>{const c=Date.now(),d=c-a;i=l,d>=e?(a=c,s(...l)):t||(t=setTimeout(()=>{t=null,a=Date.now(),i&&(s(...i),i=null)},e-d))},flush:()=>{t&&(clearTimeout(t),t=null),i&&(a=Date.now(),s(...i),i=null)},cancel:()=>{t&&(clearTimeout(t),t=null),i=null}}}async function cp(s){try{new URL(s)}catch{return{valid:!1,error:"Invalid URL format"}}try{const e=await fetch(s,{method:"HEAD",mode:"cors"});return e.ok?{valid:!0}:{valid:!1,error:`URL returned ${e.status} ${e.statusText}`}}catch(e){return{valid:!1,error:e instanceof Error?e.message:"URL not accessible"}}}class cc{constructor(e,t,i){this.initialClipConfig=e,this.finalClipConfig=t,this.trackIndex=i?.trackIndex??-1,this.clipIndex=i?.clipIndex??-1}name="setUpdatedClip";clipId=null;storedInitialConfig=null;storedFinalConfig=null;storedInitialBindings=new Map;previousDocClip=null;trackIndex;clipIndex;async execute(e){if(!e)throw new Error("SetUpdatedClipCommand.execute: context is required");const t=e.getDocument();if(!t)throw new Error("SetUpdatedClipCommand.execute: document is required");const i=e.getClipAt(this.trackIndex,this.clipIndex);if(!i)return Ne(`Invalid clip at ${this.trackIndex}/${this.clipIndex}`);this.clipId=i.clipId,this.storedInitialConfig||(this.storedInitialConfig=this.initialClipConfig?structuredClone(this.initialClipConfig):structuredClone(i.clipConfiguration)),this.storedFinalConfig||(this.storedFinalConfig=this.finalClipConfig?structuredClone(this.finalClipConfig):structuredClone(i.clipConfiguration));const a=e.getDocumentClip(this.trackIndex>=0?this.trackIndex:i.layer-1,this.clipIndex>=0?this.clipIndex:e.getTracks()[i.layer-1]?.indexOf(i)??-1);this.previousDocClip=a?structuredClone(a):null;const r=this.clipId?e.getClipBindings(this.clipId):void 0;this.storedInitialBindings=r?new Map(r):new Map;const n=this.trackIndex>=0?this.trackIndex:i.layer-1,o=this.clipIndex>=0?this.clipIndex:e.getTracks()[n]?.indexOf(i)??-1,l=this.storedFinalConfig??this.finalClipConfig;l&&t.replaceClipProperties(n,o,l),e.resolve();const c=e.getClipAt(n,o);for(const[w,{resolvedValue:C}]of this.storedInitialBindings)(c?wa(c.clipConfiguration,w):void 0)!==C&&this.clipId&&e.removeClipBinding(this.clipId,w);const d=this.storedInitialConfig??this.initialClipConfig,u=this.storedFinalConfig??this.finalClipConfig,f=d?.asset,p=u?.asset;if(f?.src!==p?.src){const w=e.getClipAt(n,o);w&&w.getTimingIntent().length==="auto"&&await e.resolveClipAutoLength(w)}const g=e.getDocumentClip(n,o);if(!this.previousDocClip||!g)throw new Error(`SetUpdatedClipCommand: document clip not found after mutation at ${n}/${o}`);return e.emitEvent(Z.ClipUpdated,{previous:{clip:Re(this.previousDocClip),trackIndex:n,clipIndex:o},current:{clip:Re(g),trackIndex:n,clipIndex:o}}),we()}async undo(e){if(!e)throw new Error("SetUpdatedClipCommand.undo: context is required");const t=this.storedInitialConfig??this.initialClipConfig;if(!t)return Ne("No stored initial config");const i=e.getDocument();if(!i)throw new Error("SetUpdatedClipCommand.undo: document is required");const a=this.clipId?e.getPlayerByClipId(this.clipId):e.getClipAt(this.trackIndex,this.clipIndex);if(!a)return Ne("Clip not found for undo");const r=this.trackIndex>=0?this.trackIndex:a.layer-1,n=this.clipIndex>=0?this.clipIndex:e.getTracks()[r]?.indexOf(a)??-1,o=structuredClone(e.getDocumentClip(r,n));if(i.replaceClipProperties(r,n,t),e.resolve(),this.clipId){const f=new Map(this.storedInitialBindings);f.size>0?e.getDocument()?.setClipBindingsForClip(this.clipId,f):e.getDocument()?.clearClipBindings(this.clipId)}const c=(this.storedFinalConfig??this.finalClipConfig)?.asset,d=t?.asset;if(c?.src!==d?.src){const f=e.getClipAt(r,n);f&&f.getTimingIntent().length==="auto"&&await e.resolveClipAutoLength(f)}const u=e.getDocumentClip(r,n);if(!o||!u)throw new Error(`SetUpdatedClipCommand: document clip not found after undo at ${r}/${n}`);return e.emitEvent(Z.ClipUpdated,{previous:{clip:Re(o),trackIndex:r,clipIndex:n},current:{clip:Re(u),trackIndex:r,clipIndex:n}}),we()}dispose(){this.clipId=null,this.storedInitialConfig=null,this.storedFinalConfig=null,this.storedInitialBindings.clear(),this.previousDocClip=null}}class _I{constructor(e,t,i){this.trackIndex=e,this.clipIndex=t,this.splitTime=i}name="SplitClip";originalClipConfig=null;rightClipId=null;execute(e){const t=e.getDocument();if(!t)throw new Error("Cannot split clip: no document");const i=t.getClip(this.trackIndex,this.clipIndex);if(!i)return Ne(`No clip at ${this.trackIndex}/${this.clipIndex}`);const a=e.getClipAt(this.trackIndex,this.clipIndex),r=a?.clipConfiguration.start??0,n=a?.clipConfiguration.length??0,o=.1,l=this.splitTime-r;if(l<=o||l>=n-o)return Ne("Split point too close to clip boundaries");this.originalClipConfig=structuredClone(i);const c=l,d=structuredClone(i);if(i.start==="auto"?d.start="auto":d.start=r+l,d.length=n-l,i.asset&&(i.asset.type==="video"||i.asset.type==="audio")){const f=i.asset.trim||0;d.asset&&(d.asset.type==="video"||d.asset.type==="audio")&&(d.asset.trim=f+l)}e.documentUpdateClip(this.trackIndex,this.clipIndex,{length:c});const u=e.documentAddClip(this.trackIndex,d,this.clipIndex+1);return this.rightClipId=u.id??null,e.resolve(),e.updateDuration(),e.emitEvent(Z.ClipSplit,{trackIndex:this.trackIndex,originalClipIndex:this.clipIndex,newClipIndex:this.clipIndex+1}),we()}undo(e){return this.originalClipConfig?(e.documentRemoveClip(this.trackIndex,this.clipIndex+1),e.documentUpdateClip(this.trackIndex,this.clipIndex,this.originalClipConfig),e.resolve(),e.updateDuration(),e.emitEvent(Z.ClipDeleted,{trackIndex:this.trackIndex,clipIndex:this.clipIndex+1}),we()):Ne("No original clip config stored")}dispose(){this.originalClipConfig=null,this.rightClipId=null}}class MI{constructor(e,t,i){this.trackIndex=e,this.clipIndex=t,this.params=i}name="UpdateClipTiming";originalStart;originalLength;clipId;execute(e){if(!e)throw new Error("UpdateClipTimingCommand.execute: context is required");const t=e.getDocument();if(!t)throw new Error("UpdateClipTimingCommand.execute: document is required");const a=e.getDocumentTrack(this.trackIndex)?.clips[this.clipIndex];if(!a)return Ne(`Invalid clip at ${this.trackIndex}/${this.clipIndex}`);const r=e.getClipAt(this.trackIndex,this.clipIndex);if(!r)return Ne(`Player not found at ${this.trackIndex}/${this.clipIndex}`);this.originalStart=a.start,this.originalLength=a.length,this.clipId=r.clipId??void 0;const n=structuredClone(a),o={};this.params.start!==void 0&&(o.start=this.params.start),this.params.length!==void 0&&(o.length=this.params.length),t.updateClip(this.trackIndex,this.clipIndex,o),this.clipId?e.resolveClip(this.clipId):e.resolve(),o.length==="auto"&&e.resolveClipAutoLength(r).then(()=>{e.updateDuration(),e.propagateTimingChanges(this.trackIndex,this.clipIndex)}),e.updateDuration();const l=e.getDocumentClip(this.trackIndex,this.clipIndex);if(!l)throw new Error(`UpdateClipTimingCommand: document clip not found after mutation at ${this.trackIndex}/${this.clipIndex}`);return e.emitEvent(Z.ClipUpdated,{previous:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:Re(n)},current:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:Re(l)}}),e.propagateTimingChanges(this.trackIndex,this.clipIndex),we()}undo(e){if(!e)throw new Error("UpdateClipTimingCommand.undo: context is required");if(this.originalStart===void 0&&this.originalLength===void 0)throw new Error("UpdateClipTimingCommand.undo: no original values");const t=e.getDocument();if(!t)throw new Error("UpdateClipTimingCommand.undo: document is required");const i=e.getClipAt(this.trackIndex,this.clipIndex);if(!i)throw new Error("UpdateClipTimingCommand.undo: player not found");const a=structuredClone(e.getDocumentClip(this.trackIndex,this.clipIndex)),r={};this.originalStart!==void 0&&(r.start=this.originalStart),this.originalLength!==void 0&&(r.length=this.originalLength),t.updateClip(this.trackIndex,this.clipIndex,r),this.clipId?e.resolveClip(this.clipId):e.resolve(),this.originalLength==="auto"&&e.resolveClipAutoLength(i).then(()=>{e.updateDuration(),e.propagateTimingChanges(this.trackIndex,this.clipIndex)}),e.updateDuration();const n=e.getDocumentClip(this.trackIndex,this.clipIndex);if(!a||!n)throw new Error(`UpdateClipTimingCommand: document clip not found after undo at ${this.trackIndex}/${this.clipIndex}`);return e.emitEvent(Z.ClipUpdated,{previous:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:Re(a)},current:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:Re(n)}}),e.propagateTimingChanges(this.trackIndex,this.clipIndex),we()}}class LI{constructor(e,t,i){this.trackIndex=e,this.clipIndex=t,this.newText=i}name="updateTextContent";clipId=null;previousText="";previousDocClip;execute(e){if(!e)throw new Error("UpdateTextContentCommand.execute: context is required");const t=e.getDocument();if(!t)throw new Error("UpdateTextContentCommand.execute: document is required");const i=e.getClipAt(this.trackIndex,this.clipIndex);if(!i)return Ne(`Invalid clip at ${this.trackIndex}/${this.clipIndex}`);const a=t.getClip(this.trackIndex,this.clipIndex);if(!a)return Ne("Clip not found in document");this.clipId=i.clipId,this.previousDocClip=structuredClone(a);const r=a.asset;this.previousText=r&&"text"in r?r.text??"":"";const o={...a.asset,text:this.newText};t.updateClip(this.trackIndex,this.clipIndex,{asset:o}),this.clipId?e.resolveClip(this.clipId):e.resolve();const l=e.getDocumentClip(this.trackIndex,this.clipIndex);if(!this.previousDocClip||!l)throw new Error(`UpdateTextContentCommand: document clip not found after mutation at ${this.trackIndex}/${this.clipIndex}`);return e.emitEvent(Z.ClipUpdated,{previous:{clip:Re(this.previousDocClip),trackIndex:this.trackIndex,clipIndex:this.clipIndex},current:{clip:Re(l),trackIndex:this.trackIndex,clipIndex:this.clipIndex}}),we()}undo(e){if(!e)throw new Error("UpdateTextContentCommand.undo: context is required");const t=e.getDocument();if(!t)throw new Error("UpdateTextContentCommand.undo: document is required");const i=structuredClone(e.getDocumentClip(this.trackIndex,this.clipIndex)),a=t.getClip(this.trackIndex,this.clipIndex);if(!a)return Ne("Clip not found for undo");const n={...a.asset,text:this.previousText};t.updateClip(this.trackIndex,this.clipIndex,{asset:n}),this.clipId?e.resolveClip(this.clipId):e.resolve();const o=e.getDocumentClip(this.trackIndex,this.clipIndex);if(this.previousDocClip){if(!i||!o)throw new Error(`UpdateTextContentCommand: document clip not found after undo at ${this.trackIndex}/${this.clipIndex}`);e.emitEvent(Z.ClipUpdated,{previous:{clip:Re(i),trackIndex:this.trackIndex,clipIndex:this.clipIndex},current:{clip:Re(o),trackIndex:this.trackIndex,clipIndex:this.clipIndex}})}return we()}dispose(){this.clipId=null,this.previousDocClip=void 0}}class dc{events;constructor(){this.events={}}on(e,t){return this.events[e]||(this.events[e]=new Set),this.events[e].add(t),()=>this.off(e,t)}once(e,t){const i=a=>{this.off(e,i),t(a)};return this.on(e,i)}off(e,t){this.events[e]&&(this.events[e].delete(t),!(this.events[e].size>0)&&delete this.events[e])}clear(e){delete this.events[e]}emit(e,...t){if(!this.events[e])return;const i=t[0];for(const a of this.events[e])a(i)}}const dp=.5,BI=1/30;class OI{constructor(e,t,i){this.getCanvas=e,this.getTracks=t,this.events=i,this.onClipChangedBound=()=>this.rebuildLumaMasksIfNeeded(),this.onPlayerLoadedBound=a=>this.onPlayerLoaded(a)}activeLumaMasks=[];pendingMaskCleanup=[];onClipChangedBound;onPlayerLoadedBound;initialize(){this.setupEventListeners()}update(){this.updateLumaMasks(),this.processPendingMaskCleanup()}getActiveMaskCount(){return this.activeLumaMasks.length}dispose(){this.removeEventListeners();for(const e of this.activeLumaMasks)e.tempContainer.destroy({children:!0}),e.maskSprite.destroy({texture:!0});this.activeLumaMasks=[];for(const e of this.pendingMaskCleanup)try{e.maskSprite.parent?.removeChild(e.maskSprite),e.maskSprite.destroy({texture:!0})}catch{}this.pendingMaskCleanup=[]}cleanupForPlayer(e){const t=this.activeLumaMasks.findIndex(a=>a.lumaPlayer===e);if(t===-1)return;const i=this.activeLumaMasks[t];i.contentClip&&(i.contentClip.getContentContainer().mask=null),i.maskSprite.parent?.removeChild(i.maskSprite),i.tempContainer.destroy({children:!0}),this.activeLumaMasks.splice(t,1),this.pendingMaskCleanup.push({maskSprite:i.maskSprite,frameCount:0})}onPlayerLoaded(e){const{player:t,trackIndex:i}=e;if(t.playerType!==it.Luma)return;const a=t,r=a.getSprite();if(!r?.texture){console.warn("PlayerLoaded fired for luma player before texture ready");return}const n=this.getTracks();if(i>=n.length)return;const l=n[i].filter(d=>d.playerType!==it.Luma);l.length===0||this.activeLumaMasks.find(d=>d.lumaPlayer===a)||(this.setupLumaMask(a,r.texture,l[0]),a.getContainer().parent?.removeChild(a.getContainer()))}setupLumaMask(e,t,i){const a=this.getCanvas();if(!a)return;const{renderer:r}=a.application,{width:n,height:o}=i.getSize(),l=new G.Container,c=new G.Sprite(t);c.width=n,c.height=o;const d=new G.ColorMatrixFilter;d.negative(!1),c.filters=[d],l.addChild(c);const u=r.generateTexture({target:l,resolution:dp}),f=new G.Sprite(u);i.getContainer().addChild(f);const p=i.getContentContainer();p.mask=f,this.activeLumaMasks.push({lumaPlayer:e,maskSprite:f,tempContainer:l,contentClip:i,lastVideoTime:-1})}updateLumaMasks(){const e=this.getCanvas();if(!e)return;const{renderer:t}=e.application;for(const i of this.activeLumaMasks)if(i.lumaPlayer.isVideoSource()){const a=i.lumaPlayer.getVideoCurrentTime();if(Math.abs(a-i.lastVideoTime)>=BI){i.lastVideoTime=a;const n=i.maskSprite.texture;i.maskSprite.texture=t.generateTexture({target:i.tempContainer,resolution:dp}),n.destroy(!0)}}}setupEventListeners(){this.events.on(Be.PlayerLoaded,this.onPlayerLoadedBound),this.events.on(Z.ClipUpdated,this.onClipChangedBound)}removeEventListeners(){this.events.off(Be.PlayerLoaded,this.onPlayerLoadedBound),this.events.off(Z.ClipUpdated,this.onClipChangedBound)}processPendingMaskCleanup(){for(let e=this.pendingMaskCleanup.length-1;e>=0;e-=1){const t=this.pendingMaskCleanup[e];if(t.frameCount+=1,t.frameCount>=3){try{t.maskSprite.parent?.removeChild(t.maskSprite),t.maskSprite.destroy({texture:!0})}catch{}this.pendingMaskCleanup.splice(e,1)}}}rebuildLumaMasksIfNeeded(){if(!this.getCanvas())return;const t=this.getTracks();for(let i=0;i<t.length;i+=1){const a=t[i],r=a.find(l=>l.playerType===it.Luma),n=a.filter(l=>l.playerType!==it.Luma);r&&r.getContainer().parent?.removeChild(r.getContainer());const o=r&&this.activeLumaMasks.find(l=>l.lumaPlayer===r);if(r&&!o&&n.length>0){const l=r.getSprite();l?.texture&&this.setupLumaMask(r,l.texture,n[0])}}}}function RI(s){return{find:s.name,replace:s.defaultValue}}function DI(s){const e=typeof s.replace=="string"?s.replace:JSON.stringify(s.replace);return{name:s.find,defaultValue:e}}const zI=/\{\{\s*([A-Z_0-9]+)\s*\}\}/gi,uc=/\{\{\s*[A-Z_0-9]+\s*\}\}/i;class UI{fields=new Map;events;constructor(e){this.events=e}register(e,t){this.fields.set(e.name,e),t?.silent||this.events.emit(Z.MergeFieldChanged,{fields:this.getAll()})}remove(e,t){const i=this.fields.delete(e);return i&&!t?.silent&&this.events.emit(Z.MergeFieldChanged,{fields:this.getAll()}),i}get(e){return this.fields.get(e)}getAll(){return Array.from(this.fields.values())}clear(){this.fields.clear()}resolve(e){return!e||this.fields.size===0?e:e.replace(zI,(t,i)=>this.fields.get(i)?.defaultValue??t)}resolveToNumber(e){if(!this.isMergeFieldTemplate(e))return null;const t=this.resolve(e),i=parseFloat(t);return Number.isFinite(i)?i:null}hasUnresolved(e){if(!e)return!1;const t=this.resolve(e);return uc.test(t)}extractFieldName(e){if(!e)return null;const t=uc.exec(e);if(!t)return null;const i=t[0].match(/\{\{\s*([A-Z_0-9]+)\s*\}\}/i);return i?i[1]:null}isMergeFieldTemplate(e){return uc.test(e)}createTemplate(e){return`{{ ${e} }}`}toSerializedArray(){return this.getAll().map(RI)}loadFromSerialized(e){this.fields.clear();for(const t of e){const i=DI(t);this.fields.set(t.find,i)}}generateUniqueName(e){const t=new Set(this.fields.keys());let i=1;for(;t.has(`${e}_${i}`);)i+=1;return`${e}_${i}`}}const ZI={preview:{width:512,height:288},mobile:{width:640,height:360},sd:{width:1024,height:576},hd:{width:1280,height:720},1080:{width:1920,height:1080},"4k":{width:3840,height:2160}};function Jn(s,e="16:9"){const t=ZI[s];if(!t)throw new Error(`Unknown resolution: ${s}`);switch(e){case"16:9":return{width:t.width,height:t.height};case"9:16":return{width:t.height,height:t.width};case"1:1":return{width:t.height,height:t.height};case"4:5":return{width:Math.round(t.height*4/5),height:t.height};case"4:3":return{width:Math.round(t.height*4/3),height:t.height};default:throw new Error(`Unknown aspectRatio: ${e}`)}}class WI{constructor(e){this.edit=e}setSize(e,t){dx.parse({width:e,height:t});const i={width:e,height:t};this.edit.size=i;const a=this.edit.getResolvedEdit();a&&(a.output={...a.output,size:i},delete a.output.resolution,delete a.output.aspectRatio);const r=this.edit.getDocument();r?.setSize(i),r?.clearResolution(),r?.clearAspectRatio(),this.edit.updateCanvasForSize(),this.edit.getInternalEvents().emit(Z.OutputResized,i)}getSize(){return this.edit.size}setFps(e){const t=fx.parse(e),i=this.edit.getResolvedEdit();i&&(i.output={...i.output,fps:t}),this.edit.getDocument()?.setFps(t),this.edit.getInternalEvents().emit(Z.OutputFpsChanged,{fps:e})}getFps(){return this.edit.getResolvedEdit()?.output?.fps??30}setFormat(e){const t=ux.parse(e),i=this.edit.getResolvedEdit();i&&(i.output={...i.output,format:t}),this.edit.getDocument()?.setFormat(t),this.edit.getInternalEvents().emit(Z.OutputFormatChanged,{format:t})}getFormat(){return this.edit.getResolvedEdit()?.output?.format??"mp4"}setDestinations(e){const t=cx.array().parse(e),i=this.edit.getResolvedEdit();i&&(i.output={...i.output,destinations:t}),this.edit.getInternalEvents().emit(Z.OutputDestinationsChanged,{destinations:t})}getDestinations(){return this.edit.getResolvedEdit()?.output?.destinations??[]}setResolution(e){const t=hx.parse(e),i=this.edit.getResolvedEdit(),a=i?.output?.aspectRatio??"16:9",r=Jn(t,a);this.edit.size=r,i&&(i.output={...i.output,resolution:t},delete i.output.size);const n=this.edit.getDocument();n?.setResolution(t),n?.clearSize(),this.edit.updateCanvasForSize(),this.edit.getInternalEvents().emit(Z.OutputResolutionChanged,{resolution:t}),this.edit.getInternalEvents().emit(Z.OutputResized,{width:r.width,height:r.height})}getResolution(){return this.edit.getResolvedEdit()?.output?.resolution}setAspectRatio(e){const t=px.parse(e),i=this.edit.getResolvedEdit(),a=i?.output?.resolution;if(!a){i&&(i.output={...i.output,aspectRatio:t}),this.edit.getDocument()?.setAspectRatio(t),this.edit.getInternalEvents().emit(Z.OutputAspectRatioChanged,{aspectRatio:t});return}const r=Jn(a,t);this.edit.size=r,i&&(i.output={...i.output,aspectRatio:t},delete i.output.size);const n=this.edit.getDocument();n?.setAspectRatio(t),n?.clearSize(),this.edit.updateCanvasForSize(),this.edit.getInternalEvents().emit(Z.OutputAspectRatioChanged,{aspectRatio:t}),this.edit.getInternalEvents().emit(Z.OutputResized,{width:r.width,height:r.height})}getAspectRatio(){return this.edit.getResolvedEdit()?.output?.aspectRatio}}class HI{constructor(e){this.edit=e}selectedClip=null;copiedClip=null;selectClip(e,t){const i=this.edit.getPlayerClip(e,t);if(i){this.selectedClip=i;const a=this.edit.getDocumentClip(e,t);a&&this.edit.getInternalEvents().emit(Z.ClipSelected,{clip:Re(a),trackIndex:e,clipIndex:t})}}selectPlayer(e){const t=this.findClipIndices(e);t&&this.selectClip(t.trackIndex,t.clipIndex)}clearSelection(){this.selectedClip=null,this.edit.getInternalEvents().emit(Z.SelectionCleared)}isClipSelected(e,t){if(!this.selectedClip)return!1;const i=this.selectedClip.layer-1,r=this.edit.getTracks()[i];if(!r)return!1;const n=r.indexOf(this.selectedClip);return e===i&&t===n}isPlayerSelected(e){return this.edit.isInExportMode()?!1:this.selectedClip===e}getSelectedClipInfo(){if(!this.selectedClip)return null;const e=this.selectedClip.layer-1,i=this.edit.getTracks()[e];if(!i)return null;const a=i.indexOf(this.selectedClip);return{trackIndex:e,clipIndex:a,player:this.selectedClip}}getSelectedClip(){return this.selectedClip}setSelectedClip(e){this.selectedClip=e}copyClip(e,t){const i=this.edit.getResolvedClip(e,t);i&&(this.copiedClip={trackIndex:e,clipConfiguration:structuredClone(i)},this.edit.getInternalEvents().emit(Z.ClipCopied,{trackIndex:e,clipIndex:t}))}pasteClip(){if(!this.copiedClip)return;const e=structuredClone(this.copiedClip.clipConfiguration);e.start=this.edit.playbackTime,delete e.id,this.edit.addClip(this.copiedClip.trackIndex,e)}hasCopiedClip(){return this.copiedClip!==null}findClipIndices(e){const t=this.edit.getTracks();for(let i=0;i<t.length;i+=1){const a=t[i].indexOf(e);if(a!==-1)return{trackIndex:i,clipIndex:a}}return null}}const GI=3;function qI(s){return new Promise(e=>{const t=document.createElement("video");t.preload="metadata",t.crossOrigin="anonymous",t.onloadedmetadata=()=>e(t.duration),t.onerror=()=>e(null),t.src=s})}async function up(s){const e=s;if(["video","audio","luma"].includes(e.type)&&e.src){const t=await qI(e.src);if(t!==null&&!Number.isNaN(t)){const i=e.trim??0;return t-i}}return GI}function fp(s,e,t){return e===0?0:t[s][e-1].getEnd()}function hp(s,e){return Math.max(0,e-s)}function fc(s){let e=0;for(const t of s)for(const i of t)i.getTimingIntent().length!=="end"&&(e=Math.max(e,i.getEnd()));return e}class YI{constructor(e){this.edit=e}cachedTimelineEnd=0;getTimelineEnd(){return this.cachedTimelineEnd}invalidateTimelineEndCache(){this.cachedTimelineEnd=0}async resolveAllTiming(){const e=this.edit.getTracks(),t=this.edit.getResolvedEdit();for(let r=0;r<e.length;r+=1){const n=e[r],o=t.timeline.tracks[r];for(let l=0;l<n.length;l+=1){const c=n[l],d=o?.clips[l];if(d){const u=c.getTimingIntent(),f=d.start;let p=d.length;u.length==="auto"&&(p=await up(c.clipConfiguration.asset)),c.setResolvedTiming({start:f,length:p})}}}const i=fc(e);this.cachedTimelineEnd=i;const a=this.getEndLengthClips();for(const r of a){const n=r.getResolvedTiming();r.setResolvedTiming({start:n.start,length:hp(n.start,i)})}for(const r of a)r.reconfigureAfterRestore()}propagateTimingChanges(e,t){const i=this.edit.getTracks(),a=i[e];if(!a)return;for(let n=Math.max(0,t);n<a.length;n+=1){const o=a[n];if(o.getTimingIntent().start==="auto"){const l=fp(e,n,i);o.setResolvedTiming({start:l,length:o.getLength()}),o.reconfigureAfterRestore()}}this.propagateAliasChanges();const r=fc(i);if(r!==this.cachedTimelineEnd){this.cachedTimelineEnd=r;const n=this.getEndLengthClips();for(const o of n){const l=hp(o.getStart(),r),c=o.getLength();Math.abs(l-c)>.001&&(o.setResolvedTiming({start:o.getStart(),length:l}),o.reconfigureAfterRestore())}}this.edit.updateTotalDuration(),this.edit.getInternalEvents().emit(Z.TimelineUpdated,{current:this.edit.getEdit()})}propagateAliasChanges(){const e=this.edit.getTracks(),t=this.edit.getResolvedEdit();for(let i=0;i<e.length;i+=1){const a=e[i],r=t.timeline.tracks[i];for(let n=0;n<a.length;n+=1){const o=a[n],l=r?.clips[n],c=o.getTimingIntent(),d=hs(c.start),u=hs(c.length);if((d||u)&&l){const f=o.getStart(),p=o.getLength(),g=Math.abs(l.start-f)>.001,w=Math.abs(l.length-p)>.001;(g||w)&&(o.setResolvedTiming({start:l.start,length:l.length}),o.reconfigureAfterRestore())}}}}getEndLengthClips(){const e=this.edit.getTracks(),t=[];for(const i of e)for(const a of i)a.getTimingIntent().length==="end"&&t.push(a);return t}}class jI extends dc{registry;constructor(){super(),this.registry={}}}class $n{static VIDEO_EXTENSIONS=[".mp4",".m4v",".webm",".ogg",".ogv"];static VIDEO_MIME={".mp4":"video/mp4",".m4v":"video/mp4",".webm":"video/webm",".ogg":"video/ogg",".ogv":"video/ogg"};loadTracker=new jI;refCounts=new Map;incrementRef(e){this.refCounts.set(e,(this.refCounts.get(e)??0)+1)}decrementRef(e){const t=this.refCounts.get(e)??0;return t<=1?(this.refCounts.delete(e),!0):(this.refCounts.set(e,t-1),!1)}constructor(){G.Assets.setPreferences({crossOrigin:"anonymous"})}async load(e,t){this.updateAssetLoadMetadata(e,"pending",0),this.incrementRef(e);try{if(await this.shouldUseSafariVideoLoader(t))return await this.loadVideoForSafari(e,t);const a=await G.Assets.load(t,r=>{this.updateAssetLoadMetadata(e,"loading",r)});return this.updateAssetLoadMetadata(e,"success",1),a}catch(i){return console.warn(`[AssetLoader] Failed to load asset "${e}":`,i),this.updateAssetLoadMetadata(e,"failed",1),this.decrementRef(e),null}}async loadVideoUnique(e,t){this.updateAssetLoadMetadata(e,"pending",0);try{const i=this.extractUrl(t);if(!i)throw new Error("No URL provided for video loading");const a=typeof t=="object"?t.data??{}:{},r=await new Promise((n,o)=>{const l=document.createElement("video");l.crossOrigin="anonymous",l.playsInline=!0,l.muted=a.muted??!1,l.preload="auto",l.addEventListener("loadedmetadata",()=>{try{const c=new G.VideoSource({resource:l,autoPlay:a.autoPlay??!1,...a});n(new G.Texture({source:c}))}catch(c){o(c)}},{once:!0}),l.addEventListener("error",()=>o(new Error("Video loading failed")),{once:!0}),this.updateAssetLoadMetadata(e,"loading",.5),l.src=i});return this.updateAssetLoadMetadata(e,"success",1),r}catch{return this.updateAssetLoadMetadata(e,"failed",1),null}}getProgress(){const e=Object.keys(this.loadTracker.registry);return e.length===0?0:e.reduce((i,a)=>i+this.loadTracker.registry[a].progress,0)/e.length}extractUrl(e){if(typeof e=="string")return e;const t=Array.isArray(e.src)?e.src[0]:e.src;return typeof t=="string"?t:t?.src}hasVideoExtension(e){const t=new URL(e,window.location.origin).pathname.toLowerCase();return $n.VIDEO_EXTENSIONS.some(i=>t.endsWith(i))}async getContentType(e){try{return(await fetch(e,{method:"HEAD"})).headers.get("content-type")}catch{return null}}canPlayVideo(e){const t=new URL(e,window.location.origin).pathname.toLowerCase(),i=t.slice(t.lastIndexOf(".")),a=$n.VIDEO_MIME[i];return a?document.createElement("video").canPlayType(a)!=="":!1}async isPlayableVideo(e){if(this.hasVideoExtension(e))return this.canPlayVideo(e);const t=await this.getContentType(e);return t?.startsWith("video/")?document.createElement("video").canPlayType(t)!=="":!1}async shouldUseSafariVideoLoader(e){const t=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),i=this.extractUrl(e);return t&&i!==void 0&&await this.isPlayableVideo(i)}async loadVideoForSafari(e,t){const i=this.extractUrl(t),a=typeof t=="object"?t.data??{}:{},r=await new Promise((n,o)=>{const l=document.createElement("video");l.crossOrigin="anonymous",l.playsInline=!0,l.muted=!0,l.preload="metadata",l.addEventListener("loadedmetadata",()=>{try{const c=new G.VideoSource({resource:l,autoPlay:a.autoPlay??!1,...a});n(new G.Texture({source:c}))}catch(c){o(c)}},{once:!0}),l.addEventListener("error",()=>o(new Error("Video loading failed")),{once:!0}),this.updateAssetLoadMetadata(e,"loading",.5),l.src=i});return this.updateAssetLoadMetadata(e,"success",1),r}updateAssetLoadMetadata(e,t,i){this.loadTracker.registry[e]?(this.loadTracker.registry[e].progress=i,this.loadTracker.registry[e].status=t):this.loadTracker.registry[e]={progress:i,status:t};const a={...this.loadTracker.registry};this.loadTracker.emit("onAssetLoadInfoUpdated",{registry:a})}}class br{static Name="FontLoadParser";id;name;extension;validFontExtensions;woff2Decompressor;constructor(){this.id=br.Name,this.name=br.Name,this.extension={type:[G.ExtensionType.LoadParser],priority:G.LoaderParserPriority.High,ref:null},this.validFontExtensions=["ttf","otf","woff","woff2"],this.woff2Decompressor=null}test(e){const t=e.split("?")[0]?.split(".").pop()?.toLowerCase()??"";return this.validFontExtensions.includes(t)}async load(e,t,i){const a=e.split("?")[0]?.split(".").pop()?.toLowerCase()??"",r=await fetch(e).then(f=>f.arrayBuffer());if(a!=="woff2"){const f=Vo.parse(new Uint8Array(r).buffer),p=f.names.fontFamily.en||f.names.fontFamily[Object.keys(f.names.fontFamily)[0]],g=new FontFace(p,`url(${e})`);return await g.load(),document.fonts.add(g),g}if(await this.loadWoff2Decompressor(),!this.woff2Decompressor)throw new Error("Cannot initialize Woff2 decompressor.");const n=this.woff2Decompressor.decompress(r),o=Vo.parse(new Uint8Array(n).buffer),l=o.names.fontFamily.en||o.names.fontFamily[Object.keys(o.names.fontFamily)[0]],c=new Blob([n],{type:"font/ttf"}),d=URL.createObjectURL(c),u=new FontFace(l,`url(${d})`);return await u.load(),document.fonts.add(u),u}async loadWoff2Decompressor(){if(this.woff2Decompressor)return;const t=`${await fetch("https://unpkg.com/wawoff2@2.0.1/build/decompress_binding.js").then(i=>i.text())}; return Module`;this.woff2Decompressor=new Function(t)(),await new Promise(i=>{this.woff2Decompressor.onRuntimeInitialized=i})}unload(e){e&&document.fonts.delete(e)}}const XI=50,pp={video:72,image:72,audio:48,text:36,"rich-text":36,shape:36,caption:36,html:48,luma:72,svg:72,default:48};function Ws(s){return pp[s]??pp.default}function KI(s){const{dragTarget:e,draggedAssetType:t,altKeyHeld:i,targetClip:a,existingLumaRef:r,draggedClipRef:n}=s;if(e.type==="insert")return{type:"track-insert"};if(!(t==="luma"||t==="image"||t==="video"))return{type:"normal-collision"};if(!i||!a)return t==="luma"?{type:"luma-overlay"}:{type:"normal-collision"};const l=r&&r.clipIndex===n.clipIndex&&r.trackIndex===n.trackIndex;return r&&!l?{type:"luma-blocked",reason:"Target already has a different luma"}:{type:"luma-attach",targetClip:a}}function hc(s,e){return s*e}function QI(s){const e=Math.floor(s/60),t=Math.floor(s%60),i=Math.floor(s%1*10);return`${e.toString().padStart(2,"0")}:${t.toString().padStart(2,"0")}.${i}`}function JI(s){const e=[];let t=0;for(const i of s)e.push(t),t+=Ws(i.primaryAssetType);return e}function $I(s,e){return e[s]??0}const va=12;function e6(s,e){if(s<va/2)return{type:"insert",insertionIndex:0};let t=0;for(let i=0;i<e.length;i+=1){const a=Ws(e[i].primaryAssetType);if(i>0&&s>=t-va/2&&s<t+va/2)return{type:"insert",insertionIndex:i};if(s>=t+va/2&&s<t+a-va/2)return{type:"track",trackIndex:i};t+=a}return s>=t-va/2?{type:"insert",insertionIndex:e.length}:{type:"track",trackIndex:Math.max(0,e.length-1)}}function t6(s){const{tracks:e,playheadTime:t,excludeClip:i}=s,a=[];a.push({time:t,type:"playhead"});for(const r of e)for(const n of r.clips)n.trackIndex===i.trackIndex&&n.clipIndex===i.clipIndex||(a.push({time:n.config.start,type:"clip-start"}),a.push({time:n.config.start+n.config.length,type:"clip-end"}));return a}function s6(s){const{time:e,snapPoints:t,snapThresholdPx:i,pixelsPerSecond:a}=s,r=i/a;for(const n of t)if(Math.abs(e-n.time)<=r)return n.time;return null}function i6(s,e){return s.clips.filter(t=>!(t.trackIndex===e.trackIndex&&t.clipIndex===e.clipIndex)).sort((t,i)=>t.config.start-i.config.start)}function a6(s,e,t){const i=e+t;for(let a=0;a<s.length;a+=1){const r=s[a],n=r.config.start,o=n+r.config.length;if(e<o&&i>n)return{clip:r,index:a}}return null}function r6(s,e,t,i,a){const r=s.config.start,n=r+s.config.length,o=t+i/2,l=r+s.config.length/2;if(o>=l){const p=n,g=p+i,w=a[e+1];return w&&g>w.config.start?{newStartTime:p,pushOffset:g-w.config.start}:{newStartTime:p,pushOffset:0}}const d=e>0?a[e-1].config.start+a[e-1].config.length:0;if(r-d>=i)return{newStartTime:r-i,pushOffset:0};const f=d;return{newStartTime:f,pushOffset:f+i-r}}const n6={newStartTime:0,pushOffset:0};function o6(s){const{track:e,desiredStart:t,clipLength:i,excludeClip:a}=s,r=i6(e,a);if(r.length===0)return{...n6,newStartTime:t};const n=a6(r,t,i);return n?n.clip.config.asset?.type==="luma"?{newStartTime:t,pushOffset:0}:r6(n.clip,n.index,t,i,r):{newStartTime:t,pushOffset:0}}function l6(s){const{track:e,time:t,excludeClip:i}=s;for(const a of e.clips)if(!(i&&a.trackIndex===i.trackIndex&&a.clipIndex===i.clipIndex)&&a.config.asset?.type!=="luma"){const n=a.config.start,o=n+a.config.length;if(t>=n&&t<o)return a}return null}function c6(s,e){return Math.sqrt(s*s+e*e)}function d6(s,e,t){return c6(s,e)>=t}function gp(s,e,t,i,a){return a>0?{type:"move-with-push",pushOffset:a}:e!==s||i!==t?{type:"simple-move"}:{type:"no-change"}}function u6(s){const{dragTarget:e,draggedAssetType:t,altKeyHeld:i,targetClip:a,existingLumaRef:r,draggedClipRef:n,startTime:o,newTime:l,originalTrack:c,pushOffset:d}=s;if(e.type==="insert")return{type:"insert-track",insertionIndex:e.insertionIndex};const u=i&&a;if((t==="image"||t==="video")&&u)return r!==null?gp(o,l,c,e.trackIndex,d):{type:"transform-and-attach",targetClip:a};if(t==="luma"){if(u){const f=r?.clipIndex===n.clipIndex&&r?.trackIndex===n.trackIndex;return r&&!f?{type:"detach-luma"}:{type:"reattach-luma",targetClip:a}}return{type:"detach-luma"}}return gp(o,l,c,e.trackIndex,d)}function f6(s,e,t,i){const a=Math.max(s,t),r=Math.min(e,i);return Math.max(0,r-a)}class h6{queue=[];isProcessing=!1;async enqueue(e){return new Promise((t,i)=>{this.queue.push(async()=>{try{const a=await e();t(a)}catch(a){i(a)}}),this.processQueue()})}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;){const e=this.queue.shift();if(e)try{await e()}catch{}}this.isProcessing=!1}}}class xa{data;clipBindings=new Map;constructor(e){this.data=structuredClone(e),this.hydrateIds()}hydrateIds(){const e=new Set;for(const t of this.data.timeline.tracks)for(let i=0;i<t.clips.length;i+=1){const a=t.clips[i];if(e.has(a)){const r=structuredClone(a);r.id=crypto.randomUUID(),t.clips[i]=r}else e.add(a),a.id||(a.id=crypto.randomUUID())}}getTimeline(){return this.data.timeline}getBackground(){return this.data.timeline.background}getTracks(){return this.data.timeline.tracks}getTrack(e){return this.data.timeline.tracks[e]??null}getTrackCount(){return this.data.timeline.tracks.length}getSoundtrack(){return this.data.timeline.soundtrack}getClip(e,t){const i=this.data.timeline.tracks[e];return i?i.clips[t]??null:null}getClipsInTrack(e){return this.data.timeline.tracks[e]?.clips??[]}getClipCount(){return this.data.timeline.tracks.reduce((e,t)=>e+t.clips.length,0)}getClipCountInTrack(e){return this.data.timeline.tracks[e]?.clips.length??0}getClipById(e){for(let t=0;t<this.data.timeline.tracks.length;t+=1){const i=this.data.timeline.tracks[t].clips;for(let a=0;a<i.length;a+=1)if(i[a].id===e)return{clip:i[a],trackIndex:t,clipIndex:a}}return null}updateClipById(e,t){const i=this.getClipById(e);i&&Object.assign(i.clip,t)}removeClipById(e){const t=this.getClipById(e);return t?this.removeClip(t.trackIndex,t.clipIndex):null}getClipId(e,t){return this.getClip(e,t)?.id??null}getOutput(){return this.data.output}getSize(){const{size:e}=this.data.output;if(!e?.width||!e?.height)throw new Error("Output size is not defined");return{width:e.width,height:e.height}}getFormat(){return this.data.output.format}getFps(){return this.data.output.fps}getResolution(){return this.data.output.resolution}getAspectRatio(){return this.data.output.aspectRatio}getMergeFields(){return this.data.merge}addTrack(e,t){const i=t??{clips:[]};return this.data.timeline.tracks.splice(e,0,i),i}removeTrack(e){if(e<0||e>=this.data.timeline.tracks.length)return null;if(this.data.timeline.tracks.length<=1)return console.warn("Cannot remove the last track"),null;const[t]=this.data.timeline.tracks.splice(e,1);return t??null}addClip(e,t,i){const a=this.data.timeline.tracks[e];if(!a)throw new Error(`Track ${e} does not exist`);const r=t;r.id||(r.id=crypto.randomUUID());const n=i??a.clips.length;return a.clips.splice(n,0,t),t}removeClip(e,t){const i=this.data.timeline.tracks[e];if(!i||t<0||t>=i.clips.length)return null;const[a]=i.clips.splice(t,1);return a??null}updateClip(e,t,i){const a=this.getClip(e,t);if(!a)throw new Error(`Clip at track ${e}, index ${t} does not exist`);Object.assign(a,i)}replaceClipProperties(e,t,i){const a=this.getClip(e,t);if(!a)throw new Error(`Clip at track ${e}, index ${t} does not exist`);const{id:r}=a;for(const n of Object.keys(a))n!=="id"&&delete a[n];Object.assign(a,i),r&&(a.id=r)}replaceClip(e,t,i){const a=this.data.timeline.tracks[e];if(!a||t<0||t>=a.clips.length)return null;const r=a.clips[t];return a.clips[t]=i,r}moveClip(e,t,i,a){const r=this.data.timeline.tracks[e];if(!r||t<0||t>=r.clips.length)return null;const n=this.data.timeline.tracks[i];if(!n)return null;const[o]=r.clips.splice(t,1);if(!o)return null;a&&Object.assign(o,a);const l=typeof o.start=="number"?o.start:0;let c=0;for(let d=0;d<n.clips.length;d+=1){const u=n.clips[d].start;if(l<(typeof u=="number"?u:0))break;c+=1}return n.clips.splice(c,0,o),o}setBackground(e){this.data.timeline.background=e}setSoundtrack(e){this.data.timeline.soundtrack=e}getFonts(){return this.data.timeline.fonts??[]}addFont(e){this.data.timeline.fonts||(this.data.timeline.fonts=[]),this.data.timeline.fonts.some(t=>t.src===e)||this.data.timeline.fonts.push({src:e})}removeFont(e){this.data.timeline.fonts&&(this.data.timeline.fonts=this.data.timeline.fonts.filter(t=>t.src!==e))}setFonts(e){this.data.timeline.fonts=e}setSize(e){this.data.output.size={width:e.width,height:e.height}}setFormat(e){this.data.output.format=e}setFps(e){this.data.output.fps=e}setResolution(e){this.data.output.resolution=e}clearResolution(){delete this.data.output.resolution}setAspectRatio(e){this.data.output.aspectRatio=e}clearAspectRatio(){delete this.data.output.aspectRatio}clearSize(){delete this.data.output.size}setMergeFields(e){this.data.merge=e}setClipBinding(e,t,i){let a=this.clipBindings.get(e);a||(a=new Map,this.clipBindings.set(e,a)),a.set(t,i)}getClipBinding(e,t){return this.clipBindings.get(e)?.get(t)}removeClipBinding(e,t){const i=this.clipBindings.get(e);i&&(i.delete(t),i.size===0&&this.clipBindings.delete(e))}getClipBindings(e){return this.clipBindings.get(e)}setClipBindingsForClip(e,t){t.size===0?this.clipBindings.delete(e):this.clipBindings.set(e,new Map(t))}clearClipBindings(e){this.clipBindings.delete(e)}getClipIdsWithBindings(){return Array.from(this.clipBindings.keys())}toJSON(){const e=structuredClone(this.data);for(const t of e.timeline.tracks)for(const i of t.clips){const a=i.id;if(a){const r=this.clipBindings.get(a);if(r)for(const[n,{placeholder:o}]of r)Zs(i,n,o)}delete i.id}return e.merge?.length===0&&delete e.merge,e}static fromJSON(e){return new xa(e)}clone(){return new xa(this.data)}}const mp=new Set(["asset","start","length","id"]),p6=new Set(["text-to-image","image-to-video","text-to-speech"]);class g6{constructor(e){this.edit=e,this.edit.getInternalEvents().on(Be.Resolved,this.onResolved)}isReconciling=!1;enableCreation=!0;onResolved=({edit:e})=>{this.reconcile(e)};async reconcileInitial(e){const t=this.reconcile(e);return await Promise.all(t.pendingLoads),t}reconcile(e){if(this.isReconciling)return{created:[],updated:[],disposed:[],pendingLoads:[]};this.isReconciling=!0;try{const t=[],i={created:[],updated:[],disposed:[],pendingLoads:t},a=new Set;for(let n=0;n<e.timeline.tracks.length;n+=1){const o=e.timeline.tracks[n];for(let l=0;l<o.clips.length;l+=1){const c=o.clips[l],d=c.id;if(d){a.add(d);const u=this.edit.getPlayerByClipId(d);if(u){const f=this.updatePlayer(u,c,n);f==="recreate"?(this.disposePlayer(d),t.push(this.createPlayer(c,d,n,l)),i.disposed.push(d),i.created.push(d)):f&&i.updated.push(d)}else this.enableCreation&&(this.createPlayer(c,d,n,l),i.created.push(d))}}}const r=this.findOrphanedPlayers(a);for(const n of r)this.disposePlayer(n),i.disposed.push(n);return(i.created.length>0||i.disposed.length>0||i.updated.length>0)&&this.rebuildTracksOrdering(e),this.syncTrackContainers(e.timeline.tracks.length),i}finally{this.isReconciling=!1}}updateSinglePlayer(e,t,i,a=0){const r=this.updatePlayer(e,t,i);if(r==="recreate"){const{clipId:n}=e;return n&&(this.disposePlayer(n),this.createPlayer(t,n,i,a)),"recreate"}return r}createPlayer(e,t,i,a){const r=this.edit.createPlayerFromAssetType(e);r.layer=i+1,r.clipId=t,this.edit.registerPlayerByClipId(t,r),this.edit.addPlayerToTracksArray(i,r),this.edit.addPlayerToContainer(i,r);const n=e.asset?.type??"unknown";return r.load().then(()=>{this.edit.getInternalEvents().emit(Be.PlayerLoaded,{player:r,trackIndex:i,clipIndex:a}),p6.has(n)&&this.edit.getInternalEvents().emit(Z.ClipUnresolved,{trackIndex:i,clipIndex:a,assetType:n,clipId:t})}).catch(l=>{const c=l instanceof Error?l.message:String(l);this.edit.getInternalEvents().emit(Z.ClipLoadFailed,{trackIndex:i,clipIndex:a,error:c,assetType:n})})}updatePlayer(e,t,i){const a=e.clipConfiguration.asset?.type,r=t.asset?.type;if(a!==r)return"recreate";let n=!1;const o=e.layer-1,l=e.clipConfiguration.start,c=e.clipConfiguration.length;return(l!==t.start||c!==t.length)&&(e.setResolvedTiming({start:t.start,length:t.length}),e.reconfigureAfterRestore(),n=!0),o!==i&&(e.layer=i+1,this.edit.movePlayerBetweenTracks(e,o,i),n=!0),this.assetChanged(e.clipConfiguration.asset,t.asset)&&(this.updateAsset(e,t.asset),n=!0),this.clipPropertiesChanged(e.clipConfiguration,t)&&(this.updateClipProperties(e,t),n=!0),n}clipPropertiesChanged(e,t){const i=e,a=t,r=new Set([...Object.keys(i),...Object.keys(a)]);for(const n of r)if(!mp.has(n)&&JSON.stringify(i[n])!==JSON.stringify(a[n]))return!0;return!1}updateClipProperties(e,t){const i=e.clipConfiguration,a=t,r=new Set([...Object.keys(i),...Object.keys(a)]);for(const n of r)mp.has(n)||(a[n]!==void 0?i[n]=a[n]:delete i[n]);e.reconfigureAfterRestore()}assetChanged(e,t){return JSON.stringify(e)!==JSON.stringify(t)}updateAsset(e,t){const i=e.clipConfiguration.asset?.src,a=t?.src;e.clipConfiguration.asset=t,i!==a&&e.reloadAsset?e.reloadAsset().then(()=>{e.reconfigureAfterRestore()}).catch(r=>{console.error("Failed to reload asset:",r)}):e.reconfigureAfterRestore()}syncTrackContainers(e){const t=this.edit.getTracks().length;if(e>t)for(let i=t;i<e;i+=1)this.edit.ensureTrackExists(i);else if(e<t)for(let i=t-1;i>=e;i-=1)this.edit.removeEmptyTrack(i)}findOrphanedPlayers(e){const t=[];for(const[i]of this.edit.getPlayerMap())e.has(i)||t.push(i);return t}disposePlayer(e){const t=this.edit.getPlayerByClipId(e);t&&(this.edit.unregisterPlayerByClipId(e),this.edit.queuePlayerForDisposal(t))}rebuildTracksOrdering(e){const t=this.edit.getTracks();for(let i=0;i<t.length;i+=1)t[i]=[];for(let i=0;i<e.timeline.tracks.length;i+=1){for(;t.length<=i;)t.push([]);for(const a of e.timeline.tracks[i].clips){const r=a.id;if(r){const n=this.edit.getPlayerByClipId(r);n&&t[i].push(n)}}}}dispose(){this.edit.getInternalEvents().off(Be.Resolved,this.onResolved)}}function yp(s,e){function t(i){if(typeof i=="string"&&e.isMergeFieldTemplate(i)){const a=e.resolveToNumber(i);return a!==null?a:e.resolve(i)}if(Array.isArray(i))return i.map(t);if(i!==null&&typeof i=="object"){const a={};for(const[r,n]of Object.entries(i))a[r]=t(n);return a}return i}return t(structuredClone(s))}function m6(s){const e=new Map,t=new Map,i=[];for(let a=0;a<s.getTrackCount();a+=1){const r=s.getClipsInTrack(a);for(let n=0;n<r.length;n+=1){const o=r[n];if(!o.id)throw new Error(`Clip at track ${a}, index ${n} is missing an ID. EditDocument hydration may have been skipped.`);const l=o.alias??o.id,c={clip:o,trackIndex:a,clipIndex:n};if(i.push({...c,id:l}),o.alias){if(t.has(o.alias))throw new Error(`Duplicate alias "${o.alias}" found. Each alias must be unique.`);t.set(o.alias,c)}}}for(let a=0;a<s.getTrackCount();a+=1){const r=s.getClipsInTrack(a);for(let n=0;n<r.length;n+=1){const o=r[n],l=o.alias??o.id,c=new Set;if(hs(o.start)){const d=Rr(o.start);if(!t.has(d))throw new Error(`Alias reference "alias://${d}" not found. No clip defines alias "${d}".`);c.add(d)}if(hs(o.length)){const d=Rr(o.length);if(!t.has(d))throw new Error(`Alias reference "alias://${d}" not found. No clip defines alias "${d}".`);c.add(d)}if(o.start==="auto"&&n>0){const d=r[n-1],u=d.alias??d.id;c.add(u)}c.size>0&&e.set(l,c)}}return{dependencies:e,clipsByAlias:t,allClips:i}}function y6(s){const e=new Set,t=new Set;function i(a,r){e.add(a),t.add(a);const n=s.get(a);if(n)for(const o of n){if(t.has(o))return[...r,o];if(!e.has(o)){const l=i(o,[...r,o]);if(l)return l}}return t.delete(a),null}for(const a of s.keys())if(!e.has(a)){const r=i(a,[a]);if(r)return r}return null}function b6(s,e){const t=[],i=new Set;function a(r){if(i.has(r))return;i.add(r);const n=s.get(r);if(n)for(const o of n)a(o);t.push(r)}for(const r of s.keys())a(r);for(const r of e)a(r);return t}function bp(s,e,t){let i;if(s.start==="auto")i=e;else if(hs(s.start)){const n=Rr(s.start),o=t.get(n);if(!o)throw new Error(`Internal error: Alias "${n}" not resolved.`);i=o.start}else i=s.start;let a,r=!1;if(s.length==="end")a=1,r=!0;else if(s.length==="auto")a=3;else if(hs(s.length)){const n=Rr(s.length),o=t.get(n);if(!o)throw new Error(`Internal error: Alias "${n}" not resolved.`);a=o.length}else a=s.length;return{...s,id:s.id??crypto.randomUUID(),start:i,length:a,pendingEndLength:r||void 0}}function w6(s){let e=0;for(const t of s)for(const i of t.clips)if(!i.pendingEndLength){const a=i.start+i.length;a>e&&(e=a)}return e}function pc(s){const{pendingEndLength:e,...t}=s;return t}function v6(s,e,t){const i=s.getClipById(e);if(!i)return null;const{clip:a,trackIndex:r,clipIndex:n}=i,l=yp(a,t.mergeFields),c=t.resolvedAliases??new Map,d=bp(l,t.previousClipEnd,c);return d.pendingEndLength&&t.cachedTimelineEnd!==void 0&&(d.length=Math.max(t.cachedTimelineEnd-d.start,.1)),{resolved:pc(d),trackIndex:r,clipIndex:n}}function wp(s,e){const{dependencies:t,allClips:i}=m6(s);if(t.size>0){const p=y6(t);if(p)throw new Error(`Circular alias reference detected: ${p.join(" -> ")}`)}const a=i.map(p=>p.id),r=b6(t,a),n=new Map;for(const p of i)n.set(p.id,p);const o=new Map,l=new Map,c=new Map;for(const p of r){const g=n.get(p);if(g){const{clip:w,trackIndex:C,clipIndex:v}=g,k=yp(w,e.mergeFields),x=c.get(C)??0,T=bp(k,x,l);o.set(`${C}-${v}`,T);const b=T.start+T.length,R=c.get(C)??0;b>R&&c.set(C,b),w.alias&&l.set(w.alias,{start:T.start,length:T.length})}}const d=[];for(let p=0;p<s.getTrackCount();p+=1){const g=s.getClipsInTrack(p).length,w=[];for(let C=0;C<g;C+=1){const v=o.get(`${p}-${C}`);if(!v)throw new Error(`Internal error: Clip at track ${p}, index ${C} was not resolved.`);w.push(v)}d.push({clips:w})}const u=w6(d),f=d.map(p=>({clips:p.clips.map(g=>{if(g.pendingEndLength){const w=Math.max(u-g.start,.1);return pc({...g,length:w})}return pc(g)})}));return{timeline:{background:s.getBackground(),tracks:f,fonts:s.getFonts()},output:s.getOutput()}}class Ca{static MAX_HISTORY_SIZE=100;static SEEK_ELAPSED_MARKER=101;document;size;backgroundColor;tracks;playbackTime;totalDuration;isPlaying;get clips(){return this.tracks.flat()}assetLoader;internalEvents;events;canvas=null;timingManager;lumaMaskController;playerReconciler;outputSettings;selectionManager;mergeFieldService;commandHistory=[];commandIndex=-1;commandQueue=new h6;clipsToDispose=new Set;clipErrors=new Map;playerByClipId=new Map;lumaContentRelations=new Map;fontMetadata=new Map;isBatchingEvents=!1;syncCorrectionCount=0;isExporting=!1;lastResolved=null;constructor(e){ja.parse(e),this.tracks=[],this.playbackTime=0,this.totalDuration=0,this.isPlaying=!1,this.document=new xa(e);const t=this.document.getResolution(),i=this.document.getAspectRatio();this.backgroundColor=this.document.getBackground()??"#000000",this.size=t?Jn(t,i):this.document.getSize(),this.assetLoader=new $n,this.internalEvents=new dc,this.events=this.internalEvents,this.lumaMaskController=new OI(()=>this.canvas,()=>this.tracks,this.internalEvents),this.playerReconciler=new g6(this),this.mergeFieldService=new UI(this.internalEvents),this.outputSettings=new WI(this),this.selectionManager=new HI(this),this.timingManager=new YI(this),this.setupIntentListeners()}async load(){await this.initializeFromDocument()}async initializeFromDocument(e="load"){const t=this.document.toJSON(),i=t.merge??[];this.mergeFieldService.loadFromSerialized(i),this.lastResolved=null;const a=this.detectMergeFieldBindings(i),r=ja.parse(t);await Promise.all((r.timeline.fonts??[]).map(async o=>{const l=o.src,c={src:l,parser:br.Name},d=await this.assetLoader.load(l,c);if(d?.family){const u=d.family.replace(/^["']|["']$/g,""),{baseFontFamily:f,fontWeight:p}=ts(u);this.fontMetadata.set(l,{baseFamilyName:f,weight:p})}return d}));const n=this.getResolvedEdit();this.lumaMaskController.initialize(),await this.playerReconciler.reconcileInitial(n),this.normalizeLumaAttachments();for(const[o,l]of a)l.size>0&&this.document.setClipBindingsForClip(o,l);await this.timingManager.resolveAllTiming(),this.updateTotalDuration(),r.timeline.soundtrack&&await this.loadSoundtrack(r.timeline.soundtrack),this.internalEvents.emit(Z.TimelineUpdated,{current:this.getEdit()}),this.emitEditChanged(e)}getInternalEvents(){return this.internalEvents}update(e,t){for(const i of this.clips)i.shouldDispose&&this.queueDisposeClip(i),i.update(e,t);this.disposeClips(),this.lumaMaskController.update(),this.isPlaying&&(this.playbackTime=Math.max(0,Math.min(this.playbackTime+_o(t),this.totalDuration)),this.playbackTime===this.totalDuration&&this.pause())}dispose(){this.clearClips(),this.lumaMaskController.dispose(),this.playerReconciler.dispose();for(const e of this.commandHistory)e.dispose?.();this.commandHistory=[],this.commandIndex=-1,this.lumaContentRelations.clear(),np.cleanup()}updateCanvasForSize(){this.internalEvents.emit(Be.ViewportSizeChanged,{width:this.size.width,height:this.size.height,backgroundColor:this.backgroundColor}),this.internalEvents.emit(Be.ViewportNeedsZoomToFit)}play(){this.isPlaying=!0,this.internalEvents.emit(Z.PlaybackPlay)}pause(){this.isPlaying=!1,this.internalEvents.emit(Z.PlaybackPause)}seek(e){this.playbackTime=Math.max(0,Math.min(e,this.totalDuration)),this.pause(),this.update(0,Ca.SEEK_ELAPSED_MARKER)}stop(){this.seek(0)}async loadEdit(e){if(ja.parse(e),this.tracks.length>0&&!this.hasStructuralChanges(e)){this.lastResolved=null;const n=structuredClone(e);this.preserveClipIdsForGranularUpdate(n);const o=this.document.getTracks(),l=this.document.getOutput();this.document=new xa(n),this.isBatchingEvents=!0,await this.applyGranularChanges(n,o,l),this.isBatchingEvents=!1,this.emitEditChanged("loadEdit:granular");return}const t=this.document,i=this.lastResolved,a=this.size,r=this.backgroundColor;try{this.lastResolved=null,this.document=new xa(e);const n=this.document.getResolution(),o=this.document.getAspectRatio();this.size=n?Jn(n,o):this.document.getSize(),this.backgroundColor=this.document.getBackground()??"#000000",this.internalEvents.emit(Be.ViewportSizeChanged,{width:this.size.width,height:this.size.height,backgroundColor:this.backgroundColor}),this.internalEvents.emit(Be.ViewportNeedsZoomToFit),this.clearClips(),await this.initializeFromDocument("loadEdit")}catch(n){throw this.document=t,this.lastResolved=i,this.size=a,this.backgroundColor=r,n}}async loadSoundtrack(e){const t={id:crypto.randomUUID(),asset:{type:"audio",src:e.src,effect:e.effect,volume:e.volume??1},fit:"crop",start:0,length:this.totalDuration},i=this.createPlayerFromAssetType(t);i.layer=this.tracks.length+1,await this.addPlayer(this.tracks.length,i)}getEdit(){const e=this.document.toJSON(),t=this.mergeFieldService.toSerializedArray();return t.length>0&&(e.merge=t),e}validateEdit(e){const t=ja.safeParse(e);return t.success?{valid:!0,errors:[]}:{valid:!1,errors:t.error.issues.map(i=>({path:i.path.join("."),message:i.message}))}}getResolvedEdit(){return this.lastResolved||(this.lastResolved=wp(this.document,{mergeFields:this.mergeFieldService})),this.lastResolved}getResolvedClip(e,t){return this.getResolvedEdit()?.timeline?.tracks?.[e]?.clips?.[t]??null}getResolvedClipById(e){const t=this.getResolvedEdit();for(const i of t.timeline.tracks)for(const a of i.clips)if(a.id===e)return a;return null}getClipId(e,t){return this.document?.getClipId(e,t)??null}getDocumentClip(e,t){return this.document?.getClip(e,t)??null}getDocument(){return this.document}resolve(){return this.lastResolved=wp(this.document,{mergeFields:this.mergeFieldService}),this.internalEvents.emit(Be.Resolved,{edit:this.lastResolved}),this.lastResolved}resolveClip(e){const t=this.getPlayerByClipId(e);if(!t)return!1;const i=this.document.getClipById(e);if(i?.clip.alias)return this.resolve(),!0;const a=i?.clip;if(a&&(hs(a.start)||hs(a.length)))return this.resolve(),!0;const r=t.layer-1,n=this.tracks[r],o=n?n.indexOf(t):-1;if(o<0)return!1;const l=o>0?n[o-1]:null,c=l?l.getEnd():0,d={mergeFields:this.mergeFieldService,previousClipEnd:c,cachedTimelineEnd:this.timingManager.getTimelineEnd()},u=v6(this.document,e,d);if(!u)return!1;if(this.lastResolved){const p=this.lastResolved.timeline.tracks[u.trackIndex];p&&p.clips[u.clipIndex]&&(p.clips[u.clipIndex]=u.resolved)}return this.playerReconciler.updateSinglePlayer(t,u.resolved,u.trackIndex,u.clipIndex)!==!1}addClip(e,t){nn.parse(t);const i=new AI(e,t);return this.executeCommand(i)}getClip(e,t){const i=this.tracks[e];return!i||t<0||t>=i.length?null:i[t].clipConfiguration}getClipError(e,t){return this.clipErrors.get(`${e}-${t}`)??null}clearClipErrorAndShift(e,t){this.clipErrors.delete(`${e}-${t}`);const i=[];for(const[a,r]of this.clipErrors){const[n,o]=a.split("-").map(Number);n===e&&o>t&&i.push({oldKey:a,newKey:`${n}-${o-1}`,value:r})}for(const{oldKey:a,newKey:r,value:n}of i)this.clipErrors.delete(a),this.clipErrors.set(r,n)}getPlayerClip(e,t){const i=this.tracks[e];return!i||t<0||t>=i.length?null:i[t]}getPlayerByClipId(e){return this.playerByClipId.get(e)??null}getDocumentClipById(e){return this.document?.getClipById(e)?.clip??null}registerPlayerByClipId(e,t){this.playerByClipId.set(e,t)}unregisterPlayerByClipId(e){this.playerByClipId.delete(e)}getPlayerMap(){return this.playerByClipId}addPlayerToTracksArray(e,t){for(;this.tracks.length<=e;)this.tracks.push([]);this.tracks[e].push(t)}movePlayerBetweenTracks(e,t,i){const a=this.tracks[t];if(a){const r=a.indexOf(e);r!==-1&&a.splice(r,1)}for(;this.tracks.length<=i;)this.tracks.push([]);this.tracks[i].push(e),this.movePlayerToTrackContainer(e,t,i)}queuePlayerForDisposal(e){this.queueDisposeClip(e),this.disposeClips()}ensureTrackExists(e){for(;this.tracks.length<=e;)this.tracks.push([])}removeEmptyTrack(e){if(e<0||e>=this.tracks.length)return;const t=this.tracks[e];if(t&&t.length>0){console.warn(`Cannot remove non-empty track ${e}`);return}this.tracks.splice(e,1),this.internalEvents.emit(Be.TrackContainerRemoved,{trackIndex:e});for(let i=e;i<this.tracks.length;i+=1)for(const a of this.tracks[i])a.layer=i+1}getOriginalAsset(e,t){const i=this.getPlayerClip(e,t);if(!i)return;const a=i.getExportableClip();if(!a)return;const{clipId:r}=i;if(r&&this.document){const n=this.document.getClipBindings(r);if(n){for(const[o,{placeholder:l}]of n)if(o.startsWith("asset.")){const c=o.slice(6);Zs(a.asset,c,l)}}}return a.asset}async deleteClip(e,t){const i=this.tracks[e];if(!i)return;const a=i[t];if(!a)return;if(a.playerType!==it.Luma){const o=i.findIndex(l=>l.playerType===it.Luma);if(o!==-1){const l=o<t?t-1:t,c=new oc(e,o);await this.executeCommand(c);const d=new oc(e,l);await this.executeCommand(d);return}}const n=new oc(e,t);await this.executeCommand(n)}splitClip(e,t,i){const a=new _I(e,t,i);return this.executeCommand(a)}async addTrack(e,t){Vu.parse(t);const i=new op(e);await this.executeCommand(i);for(const a of t.clips)await this.addClip(e,a)}getTrack(e){const t=this.clips.filter(i=>i.layer===e+1);return t.length===0?null:{clips:t.map(i=>i.clipConfiguration)}}deleteTrack(e){const t=new nc(e);this.executeCommand(t)}recordSyncCorrection(){this.syncCorrectionCount+=1}undo(){return this.commandQueue.enqueue(async()=>{if(this.commandIndex>=0){const e=this.commandHistory[this.commandIndex];if(e.undo){const t=this.createCommandContext();await Promise.resolve(e.undo(t)),this.commandIndex-=1,this.internalEvents.emit(Z.EditUndo,{command:e.name}),this.emitEditChanged(`undo:${e.name}`)}}})}redo(){return this.commandQueue.enqueue(async()=>{if(this.commandIndex<this.commandHistory.length-1){const e=this.commandIndex+1,t=this.commandHistory[e],i=this.createCommandContext();await Promise.resolve(t.execute(i)),this.commandIndex=e,this.internalEvents.emit(Z.EditRedo,{command:t.name}),this.emitEditChanged(`redo:${t.name}`)}})}setUpdatedClip(e,t=null,i=null){const a=e.layer-1,r=this.tracks[a],n=r?r.indexOf(e):-1,o=new cc(t,i,{trackIndex:a,clipIndex:n});this.executeCommand(o)}updateClipInDocument(e,t){const i=this.document.getClipById(e);i&&this.document.updateClip(i.trackIndex,i.clipIndex,t)}commitClipUpdate(e,t,i){const a=this.document.getClipById(e);if(!a){console.warn(`commitClipUpdate: clip ${e} not found in document`);return}rl.parse(i);const r=new cc(t,structuredClone(i),{trackIndex:a.trackIndex,clipIndex:a.clipIndex});this.addCommandToHistory(r)}pushCommandToHistory(e){const t=this.commandHistory.slice(this.commandIndex+1);for(const i of t)i.dispose?.();for(this.commandHistory=this.commandHistory.slice(0,this.commandIndex+1),this.commandHistory.push(e),this.commandIndex+=1;this.commandHistory.length>Ca.MAX_HISTORY_SIZE;)this.commandHistory.shift()?.dispose?.(),this.commandIndex-=1}addCommandToHistory(e){this.pushCommandToHistory(e),this.emitEditChanged(`commit:${e.name}`)}updateClip(e,t,i){const a=this.getPlayerClip(e,t);if(!a)return console.warn(`Clip not found at track ${e}, index ${t}`),Promise.resolve();const r=this.document?.getClip(e,t),n=structuredClone(r??a.clipConfiguration),o=structuredClone(r??a.clipConfiguration),l=lc(o,i);rl.parse(l);const c=new cc(n,l,{trackIndex:e,clipIndex:t});return this.executeCommand(c)}updateClipTiming(e,t,i){if(!this.getPlayerClip(e,t)){console.warn(`Clip not found at track ${e}, index ${t}`);return}const r=new MI(e,t,i);this.executeCommand(r)}updateTextContent(e,t,i){const a=e.layer-1,r=this.tracks[a]?.indexOf(e)??-1;if(r<0){console.warn("UpdateTextContent: clip not found in track");return}const n=new LI(a,r,t);this.executeCommand(n)}executeEditCommand(e){return this.executeCommand(e)}executeCommand(e){return this.commandQueue.enqueue(async()=>{const t=this.createCommandContext(),i=await Promise.resolve(e.execute(t));this.handleCommandResult(e,i)})}handleCommandResult(e,t){t.status==="success"&&(this.pushCommandToHistory(e),this.emitEditChanged(e.name))}emitEditChanged(e){this.isBatchingEvents||this.internalEvents.emit(Z.EditChanged,{source:e,timestamp:Date.now()})}detectMergeFieldBindings(e){const t=new Map;if(!e.length)return t;const i=new Map;for(const{find:a,replace:r}of e){const n=typeof r=="string"?r:JSON.stringify(r);i.set(a.toUpperCase(),n)}for(let a=0;a<this.document.getTrackCount();a+=1){const r=this.document.getClipsInTrack(a);for(let n=0;n<r.length;n+=1){const o=this.document.getClipId(a,n);if(o){const l=this.detectBindingsInObject(r[n],"",i);l.size>0&&t.set(o,l)}}}return t}detectBindingsInObject(e,t,i){const a=new Map;if(typeof e=="string"){if(/\{\{\s*([A-Z_0-9]+)\s*\}\}/gi.test(e)){const o=e.replace(/\{\{\s*([A-Z_0-9]+)\s*\}\}/gi,(l,c)=>i.get(c.toUpperCase())??l);a.set(t,{placeholder:e,resolvedValue:o})}return a}if(Array.isArray(e)){for(let r=0;r<e.length;r+=1){const n=t?`${t}[${r}]`:`[${r}]`,o=this.detectBindingsInObject(e[r],n,i);for(const[l,c]of o)a.set(l,c)}return a}if(e!==null&&typeof e=="object")for(const[r,n]of Object.entries(e)){const o=t?`${t}.${r}`:r,l=this.detectBindingsInObject(n,o,i);for(const[c,d]of l)a.set(c,d)}return a}hasStructuralChanges(e){if(!this.document)return!0;const t=this.document.getTracks(),i=e.timeline.tracks;if(t.length!==i.length)return!0;for(let a=0;a<t.length;a+=1){if(t[a].clips.length!==i[a].clips.length)return!0;for(let r=0;r<t[a].clips.length;r+=1){const n=t[a].clips[r]?.asset?.type,o=i[a].clips[r]?.asset?.type;if(n!==o)return!0}}return JSON.stringify(this.document.getMergeFields()??[])!==JSON.stringify(e.merge??[])||JSON.stringify(this.document.getFonts())!==JSON.stringify(e.timeline.fonts??[])||JSON.stringify(this.document.getSoundtrack())!==JSON.stringify(e.timeline.soundtrack)}preserveClipIdsForGranularUpdate(e){if(!this.document)return;const t=this.document.getTracks();for(let i=0;i<e.timeline.tracks.length;i+=1){const a=t[i],r=e.timeline.tracks[i];if(a&&r)for(let n=0;n<r.clips.length;n+=1){const o=this.document.getClipId(i,n);o&&(r.clips[n].id=o)}}}async applyGranularChanges(e,t,i){const a=e.output;if(a?.size&&(i?.size?.width!==a.size.width||i?.size?.height!==a.size.height)){const o=a.size.width??this.size.width,l=a.size.height??this.size.height;await this.setOutputSize(o,l)}a?.fps!==void 0&&i?.fps!==a.fps&&await this.setOutputFps(a.fps),a?.format!==void 0&&i?.format!==a.format&&await this.setOutputFormat(a.format),a?.destinations&&JSON.stringify(i?.destinations)!==JSON.stringify(a.destinations)&&await this.setOutputDestinations(a.destinations),a?.resolution!==void 0&&i?.resolution!==a.resolution&&await this.setOutputResolution(a.resolution),a?.aspectRatio!==void 0&&i?.aspectRatio!==a.aspectRatio&&await this.setOutputAspectRatio(a.aspectRatio);const r=e.timeline?.background;r&&this.backgroundColor!==r&&await this.setTimelineBackground(r);const n=e.timeline.tracks;for(let o=0;o<n.length;o+=1){const l=t[o].clips,c=n[o].clips;for(let d=0;d<c.length;d+=1){const u=l[d],f=c[d];JSON.stringify(u)!==JSON.stringify(f)&&await this.updateClip(o,d,f)}}}createCommandContext(){return{getClips:()=>this.clips,getTracks:()=>this.tracks,getTrack:e=>e>=0&&e<this.tracks.length?this.tracks[e]:null,getContainer:()=>this.getViewportContainer(),addPlayer:(e,t)=>this.addPlayer(e,t),addPlayerToContainer:(e,t)=>{this.addPlayerToContainer(e,t)},createPlayerFromAssetType:e=>this.createPlayerFromAssetType(e),queueDisposeClip:e=>this.queueDisposeClip(e),disposeClips:()=>this.disposeClips(),clearClipError:(e,t)=>this.clearClipErrorAndShift(e,t),undeleteClip:(e,t)=>{let i=0;if(e>=0&&e<this.tracks.length){const a=this.tracks[e];i=a.length;for(let r=0;r<a.length;r+=1)if(a[r].getStart()>t.getStart()){i=r;break}a.splice(i,0,t)}if(this.document){const a=t.getExportableClip();this.document.addClip(e,a,i);const r=this.document.getClipId(e,i);r&&(t.clipId=r,this.playerByClipId.set(r,t))}this.addPlayerToContainer(e,t),t.load().catch(a=>{const r=t.clipConfiguration?.asset?.type??"unknown",n=a instanceof Error?a.message:String(a);this.clipErrors.set(`${e}-${i}`,{error:n,assetType:r}),this.internalEvents.emit(Z.ClipLoadFailed,{trackIndex:e,clipIndex:i,error:n,assetType:r})}),this.updateTotalDuration()},setUpdatedClip:()=>{},restoreClipConfiguration:(e,t)=>{const i=structuredClone(t),a=e.clipConfiguration;for(const r of Object.keys(a))delete a[r];if(Object.assign(a,i),e.reconfigureAfterRestore(),this.document){const r=this.findClipIndices(e);if(r){const n=e.getExportableClip();this.document.replaceClip(r.trackIndex,r.clipIndex,n)}}},updateDuration:()=>this.updateTotalDuration(),emitEvent:(e,...t)=>this.internalEvents.emit(e,...t),findClipIndices:e=>this.selectionManager.findClipIndices(e),getClipAt:(e,t)=>this.getClipAt(e,t),getSelectedClip:()=>this.selectionManager.getSelectedClip(),setSelectedClip:e=>{this.selectionManager.setSelectedClip(e)},movePlayerToTrackContainer:(e,t,i)=>this.movePlayerToTrackContainer(e,t,i),getEditState:()=>this.getResolvedEdit(),propagateTimingChanges:(e,t)=>this.propagateTimingChanges(e,t),resolveClipAutoLength:e=>this.resolveClipAutoLength(e),getMergeFields:()=>this.mergeFieldService,getOutputSize:()=>this.outputSettings.getSize(),setOutputSize:(e,t)=>this.outputSettings.setSize(e,t),getOutputFps:()=>this.outputSettings.getFps(),setOutputFps:e=>this.outputSettings.setFps(e),getOutputFormat:()=>this.outputSettings.getFormat(),setOutputFormat:e=>this.outputSettings.setFormat(e),getOutputResolution:()=>this.outputSettings.getResolution(),setOutputResolution:e=>this.outputSettings.setResolution(e),getOutputAspectRatio:()=>this.outputSettings.getAspectRatio(),setOutputAspectRatio:e=>this.outputSettings.setAspectRatio(e),getOutputDestinations:()=>this.outputSettings.getDestinations(),setOutputDestinations:e=>this.outputSettings.setDestinations(e),getTimelineBackground:()=>this.getTimelineBackground(),setTimelineBackground:e=>this.setTimelineBackgroundInternal(e),getDocument:()=>this.document,getDocumentTrack:e=>this.document?.getTrack(e)??null,getDocumentClip:(e,t)=>this.document?.getClip(e,t)??null,documentUpdateClip:(e,t,i)=>{if(!this.document)throw new Error("Document not initialized - cannot update clip");this.document.updateClip(e,t,i)},documentAddClip:(e,t,i)=>{if(!this.document)throw new Error("Document not initialized - cannot add clip");for(;this.document.getTrackCount()<=e;)this.document.addTrack(this.document.getTrackCount());return this.document.addClip(e,t,i)},documentRemoveClip:(e,t)=>{if(!this.document)throw new Error("Document not initialized - cannot remove clip");return this.document.removeClip(e,t)},derivePlayerFromDocument:(e,t)=>{const i=this.document?.getClip(e,t);if(!i)throw new Error(`derivePlayerFromDocument: No document clip at ${e}/${t} - state desync`);const a=this.getClipAt(e,t);if(!a)throw new Error(`derivePlayerFromDocument: No player at ${e}/${t} - state desync`);const{asset:r,...n}=i;Object.assign(a.clipConfiguration,n),a.reconfigureAfterRestore()},buildResolutionContext:(e,t)=>{let i=0;if(t>0){const o=this.tracks[e];o&&o[t-1]&&(i=o[t-1].getEnd())}const a=fc(this.tracks);let r=null;const n=this.getClipAt(e,t);return n&&n.getTimingIntent().length==="auto"&&(r=n.getLength()),{previousClipEnd:i,timelineEnd:a,intrinsicDuration:r}},resolve:()=>this.resolve(),resolveClip:e=>this.resolveClip(e),getPlayerByClipId:e=>this.playerByClipId.get(e)??null,registerPlayerByClipId:(e,t)=>{this.playerByClipId.set(e,t)},unregisterPlayerByClipId:e=>{this.playerByClipId.delete(e)},setClipBinding:(e,t,i)=>{this.document?.setClipBinding(e,t,i)},getClipBinding:(e,t)=>this.document?.getClipBinding(e,t),removeClipBinding:(e,t)=>{this.document?.removeClipBinding(e,t)},getClipBindings:e=>this.document?.getClipBindings(e),getEditSession:()=>this}}queueDisposeClip(e){this.clipsToDispose.add(e)}disposeClips(){if(this.clipsToDispose.size!==0){for(const e of this.clipsToDispose)e.playerType===it.Luma&&(this.lumaMaskController.cleanupForPlayer(e),e.clipId&&this.lumaContentRelations.delete(e.clipId));for(const e of this.clipsToDispose)e.clipId&&this.playerByClipId.delete(e.clipId);for(const e of this.clipsToDispose)this.disposeClip(e);for(const e of this.clipsToDispose){const t=e.layer-1;if(t>=0&&t<this.tracks.length){const i=this.tracks[t].indexOf(e);i!==-1&&this.tracks[t].splice(i,1)}}this.clipsToDispose.clear(),this.updateTotalDuration(),this.cleanupUnusedFonts()}}cleanupUnusedFonts(){if(!this.document)return;const e=this.document.getFonts();if(e.length===0)return;const t=new Set;for(const i of this.clips){const{asset:a}=i.clipConfiguration;a&&a.type==="rich-text"&&a.font?.family&&t.add(a.font.family)}for(const i of e)if(i.src.includes("fonts.gstatic.com")){const r=this.extractFilenameFromUrl(i.src);r&&!t.has(r)&&this.document.removeFont(i.src)}}extractFilenameFromUrl(e){try{const{pathname:t}=new URL(e),i=t.split("/").pop();return i?i.replace(/\.[^.]+$/,""):null}catch{return null}}disposeClip(e){try{const t=this.canvas?.getViewportContainer();if(t){for(const i of t.children)if(i instanceof G.Container&&i.label?.toString().startsWith("shotstack-track-")&&i.children.includes(e.getContainer())){i.removeChild(e.getContainer());break}}}catch(t){console.warn(`Attempting to unmount an unmounted clip: ${t}`)}this.unloadClipAssets(e),this.timingManager.invalidateTimelineEndCache(),e.dispose()}unloadClipAssets(e){const{asset:t}=e.clipConfiguration;t&&"src"in t&&typeof t.src=="string"&&this.assetLoader.decrementRef(t.src)&&G.Assets.cache.has(t.src)&&G.Assets.unload(t.src)}clearClips(){for(const e of this.clips)this.disposeClip(e);this.tracks=[],this.clipsToDispose.clear(),this.clipErrors.clear(),this.lumaContentRelations.clear(),this.updateTotalDuration()}updateTotalDuration(){let e=0;for(const i of this.tracks)for(const a of i)e=Math.max(e,a.getEnd());const t=this.totalDuration;this.totalDuration=e,t!==this.totalDuration&&this.internalEvents.emit(Z.DurationChanged,{duration:this.totalDuration})}propagateTimingChanges(e,t){this.timingManager.propagateTimingChanges(e,t)}async resolveClipAutoLength(e){const t=e.getTimingIntent();if(t.length!=="auto")return;const i=this.findClipIndices(e);let a=e.getStart();t.start==="auto"&&i&&(a=fp(i.trackIndex,i.clipIndex,this.tracks));const r=await up(e.clipConfiguration.asset);e.setResolvedTiming({start:a,length:r}),e.reconfigureAfterRestore(),i&&this.propagateTimingChanges(i.trackIndex,i.clipIndex)}addPlayerToContainer(e,t){this.internalEvents.emit(Be.PlayerAddedToTrack,{player:t,trackIndex:e})}movePlayerToTrackContainer(e,t,i){this.internalEvents.emit(Be.PlayerMovedBetweenTracks,{player:e,fromTrackIndex:t,toTrackIndex:i})}createPlayerFromAssetType(e){return np.create(this,e)}async addPlayer(e,t){for(;this.tracks.length<=e;)this.tracks.push([]);this.tracks[e].push(t),this.internalEvents.emit(Be.PlayerAddedToTrack,{player:t,trackIndex:e}),await t.load(),this.updateTotalDuration()}selectClip(e,t){this.selectionManager.selectClip(e,t)}clearSelection(){this.selectionManager.clearSelection()}isClipSelected(e,t){return this.selectionManager.isClipSelected(e,t)}getSelectedClipInfo(){return this.selectionManager.getSelectedClipInfo()}copyClip(e,t){this.selectionManager.copyClip(e,t)}pasteClip(){this.selectionManager.pasteClip()}hasCopiedClip(){return this.selectionManager.hasCopiedClip()}findClipIndices(e){return this.selectionManager.findClipIndices(e)}getClipAt(e,t){return e>=0&&e<this.tracks.length&&t>=0&&t<this.tracks[e].length?this.tracks[e][t]:null}selectPlayer(e){this.selectionManager.selectPlayer(e)}isPlayerSelected(e){return this.selectionManager.isPlayerSelected(e)}getActivePlayersExcept(e){const t=[];for(const i of this.tracks)for(const a of i)a!==e&&a.isActive()&&t.push(a);return t}showAlignmentGuide(e,t,i,a){this.canvas?.showAlignmentGuide(e,t,i,a)}clearAlignmentGuides(){this.canvas?.clearAlignmentGuides()}moveSelectedClip(e,t){const i=this.getSelectedClipInfo();if(!i)return;const{player:a,trackIndex:r,clipIndex:n}=i,o=this.getResolvedClip(r,n);if(!o)return;const l=structuredClone(o),c=a.calculateMoveOffset(e,t),d=structuredClone(l);d.offset=c,this.setUpdatedClip(a,l,d)}setExportMode(e){this.isExporting=e}isInExportMode(){return this.isExporting}setCanvas(e){this.canvas=e}getCanvas(){return this.canvas}getCanvasZoom(){return this.canvas?.getZoom()??1}getViewportContainer(){if(!this.canvas)throw new Error("Canvas not attached. Viewport container requires Canvas.");return this.canvas.getViewportContainer()}setOutputSize(e,t){const i=new FI(e,t);return this.executeCommand(i)}setOutputFps(e){const t=new NI(e);return this.executeCommand(t)}getOutputFps(){return this.outputSettings.getFps()}setOutputFormat(e){const t=new EI(e);return this.executeCommand(t)}getOutputFormat(){return this.outputSettings.getFormat()}setOutputDestinations(e){const t=new TI(e);return this.executeCommand(t)}getOutputDestinations(){return this.outputSettings.getDestinations()}setOutputResolution(e){const t=new PI(e);return this.executeCommand(t)}getOutputResolution(){return this.outputSettings.getResolution()}setOutputAspectRatio(e){const t=new II(e);return this.executeCommand(t)}getOutputAspectRatio(){return this.outputSettings.getAspectRatio()}getTimelineFonts(){return this.document.getFonts()}getFontMetadata(){return this.fontMetadata}getFontUrlByFamilyAndWeight(e,t){const{baseFontFamily:i}=ts(e),a=i.toLowerCase();for(const[r,n]of this.fontMetadata)if(n.baseFamilyName.toLowerCase()===a&&n.weight===t)return r;for(const[r,n]of this.fontMetadata)if(n.baseFamilyName.toLowerCase()===a)return r;return null}pruneUnusedFonts(){this.cleanupUnusedFonts()}setTimelineBackground(e){const t=new VI(e);return this.executeCommand(t)}setTimelineBackgroundInternal(e){gx.parse(e),this.backgroundColor=e,this.document.setBackground(e),this.internalEvents.emit(Be.ViewportSizeChanged,{width:this.size.width,height:this.size.height,backgroundColor:this.backgroundColor}),this.internalEvents.emit(Z.TimelineBackgroundChanged,{color:e})}getTimelineBackground(){return this.backgroundColor}resolveMergeFields(e){return this.mergeFieldService.resolve(e)}getTemplateClip(e,t){const i=this.getPlayerClip(e,t);if(!i)return null;const a=i.getExportableClip();if(!a)return null;const{clipId:r}=i;if(r&&this.document){const n=this.document.getClipBindings(r);if(n)for(const[o,{placeholder:l}]of n)Zs(a,o,l)}return a}getTemplateClipById(e){const t=this.getPlayerByClipId(e);if(!t)return null;const i=t.getExportableClip();if(!i||!this.document)return null;const a=this.document.getClipBindings(e);if(a)for(const[r,{placeholder:n}]of a)Zs(i,r,n);return i}getTemplateClipText(e,t){const i=this.getTemplateClip(e,t);return i?i.asset?.text??null:null}getLumaClipIdForContent(e){for(const[t,i]of this.lumaContentRelations)if(i===e)return t;return null}getContentClipIdForLuma(e){return this.lumaContentRelations.get(e)??null}setLumaContentRelationship(e,t){this.lumaContentRelations.set(e,t)}clearLumaContentRelationship(e){this.lumaContentRelations.delete(e)}getLumaContentRelationship(e){return this.lumaContentRelations.get(e)}normalizeLumaAttachments(){let e=!1;for(let t=0;t<this.tracks.length;t+=1){const i=this.tracks[t];for(const a of i)if(a.playerType===it.Luma){const r=this.findBestContentMatch(t,a);if(r){a.clipId&&r.clipId&&this.lumaContentRelations.set(a.clipId,r.clipId);const n=i.indexOf(a);this.document.updateClip(t,n,{start:r.getStart(),length:r.getLength()}),e=!0}}}e&&this.resolve()}findBestContentMatch(e,t){const i=this.tracks[e],a=t.getStart(),r=a+t.getLength();let n=null,o=0;for(const l of i)if(l.playerType!==it.Luma){const c=l.getStart(),d=c+l.getLength(),u=f6(a,r,c,d);u>o&&(o=u,n=l)}return n}setupIntentListeners(){this.internalEvents.on(Be.CanvasClipClicked,e=>{this.selectPlayer(e.player)}),this.internalEvents.on(Be.CanvasBackgroundClicked,()=>{this.clearSelection()})}getTracks(){return this.tracks}getTrackCount(){return this.document.getTrackCount()}getClipCountInTrack(e){return this.document.getClipCountInTrack(e)}}const vp=16711935,xp=2,gc=6,Cp=4;class x6{graphics;canvasWidth;canvasHeight;constructor(e,t,i){this.canvasWidth=t,this.canvasHeight=i,this.graphics=new G.Graphics,this.graphics.zIndex=999999,e.addChild(this.graphics)}clear(){this.graphics.clear()}drawCanvasGuide(e,t){this.graphics.strokeStyle={width:xp,color:vp},e==="x"?(this.graphics.moveTo(t,0),this.graphics.lineTo(t,this.canvasHeight)):(this.graphics.moveTo(0,t),this.graphics.lineTo(this.canvasWidth,t)),this.graphics.stroke()}drawClipGuide(e,t,i,a){e==="x"?this.drawDashedLine(t,i,t,a):this.drawDashedLine(i,t,a,t)}drawDashedLine(e,t,i,a){const r=i-e,n=a-t,o=Math.sqrt(r*r+n*n),l=Math.floor(o/(gc+Cp)),c=r/o,d=n/o;this.graphics.strokeStyle={width:xp,color:vp};for(let u=0;u<l;u+=1){const f=u*(gc+Cp),p=f+gc,g=e+c*f,w=t+d*f,C=e+c*Math.min(p,o),v=t+d*Math.min(p,o);this.graphics.moveTo(g,w),this.graphics.lineTo(C,v)}this.graphics.stroke()}updateSize(e,t){this.canvasWidth=e,this.canvasHeight=t}dispose(){this.graphics.destroy()}}const C6="Browser Not Supported",k6="Please try a different browser or enable hardware acceleration in your browser settings.";function S6(s,e){const t=C6,i=k6,a=document.createElement("div");a.className="ss-webgl-error-overlay";const r=document.createElement("div");r.className="ss-webgl-error-content";const n=document.createElement("div");n.className="ss-webgl-error-icon",n.innerHTML=`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
|
|
278
278
|
<rect x="2" y="3" width="20" height="14" rx="2" ry="2"/>
|
|
279
279
|
<line x1="8" y1="21" x2="16" y2="21"/>
|
|
280
280
|
<line x1="12" y1="17" x2="12" y2="21"/>
|