@shotstack/shotstack-studio 2.0.0-beta.6 → 2.0.0-beta.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,7 +2,7 @@ import * as X from "pixi.js";
2
2
  import { Filter as h0, deprecation as f0, GpuProgram as p0, GlProgram as g0, Color as m0 } from "pixi.js";
3
3
  import * as y0 from "howler";
4
4
  import * as No from "opentype.js";
5
- const b0 = "2.0.0-beta.6", w0 = {
5
+ const b0 = "2.0.0-beta.7", w0 = {
6
6
  version: b0
7
7
  };
8
8
  class v0 {
@@ -15498,10 +15498,10 @@ class q0 extends Je {
15498
15498
  this.disposeTexture(), await this.loadTexture();
15499
15499
  }
15500
15500
  async loadTexture() {
15501
- const t = this.clipConfiguration.asset, { src: e } = t, i = { src: e, crossorigin: "anonymous", data: {} }, a = await this.edit.assetLoader.load(e, i);
15502
- if (!(a?.source instanceof X.ImageSource))
15503
- throw a && a.destroy(!0), new Error(`Invalid image source '${e}'.`);
15504
- this.texture = this.createCroppedTexture(a), this.sprite = new X.Sprite(this.texture), this.contentContainer.addChild(this.sprite), this.clipConfiguration.width && this.clipConfiguration.height && this.applyFixedDimensions();
15501
+ const t = this.clipConfiguration.asset, { src: e } = t, i = `${e}${e.includes("?") ? "&" : "?"}x-cors=1`, a = { src: i, crossorigin: "anonymous", data: {} }, n = await this.edit.assetLoader.load(i, a);
15502
+ if (!(n?.source instanceof X.ImageSource))
15503
+ throw n && n.destroy(!0), new Error(`Invalid image source '${e}'.`);
15504
+ this.texture = this.createCroppedTexture(n), this.sprite = new X.Sprite(this.texture), this.contentContainer.addChild(this.sprite), this.clipConfiguration.width && this.clipConfiguration.height && this.applyFixedDimensions();
15505
15505
  }
15506
15506
  disposeTexture() {
15507
15507
  this.sprite && (this.contentContainer.removeChild(this.sprite), this.sprite.destroy(), this.sprite = null), this.texture = null;
@@ -37047,16 +37047,16 @@ class KS extends Je {
37047
37047
  const t = this.clipConfiguration.asset, { src: e } = t;
37048
37048
  if (e.endsWith(".mov"))
37049
37049
  throw new Error(`Video source '${e}' is not supported. .mov files cannot be played in the browser. Please convert to .webm or .mp4 first.`);
37050
- const i = { src: e, data: { autoPlay: !1, muted: !1 } }, a = await this.edit.assetLoader.loadVideoUnique(e, i);
37051
- if (!a || !(a.source instanceof X.VideoSource))
37050
+ const i = `${e}${e.includes("?") ? "&" : "?"}x-cors=1`, a = { src: i, data: { autoPlay: !1, muted: !1 } }, n = await this.edit.assetLoader.loadVideoUnique(i, a);
37051
+ if (!n || !(n.source instanceof X.VideoSource))
37052
37052
  throw new Error(`Invalid video source '${e}'.`);
37053
- a.source.alphaMode = "no-premultiply-alpha", this.texture = this.createCroppedTexture(a);
37054
- const n = this.texture.source.resource;
37055
- n instanceof HTMLVideoElement && n.readyState < 2 && await new Promise((r) => {
37056
- const o = () => {
37057
- n.removeEventListener("loadeddata", o), r();
37053
+ n.source.alphaMode = "no-premultiply-alpha", this.texture = this.createCroppedTexture(n);
37054
+ const r = this.texture.source.resource;
37055
+ r instanceof HTMLVideoElement && r.readyState < 2 && await new Promise((o) => {
37056
+ const l = () => {
37057
+ r.removeEventListener("loadeddata", l), o();
37058
37058
  };
37059
- n.addEventListener("loadeddata", o), n.readyState >= 2 && r();
37059
+ r.addEventListener("loadeddata", l), r.readyState >= 2 && o();
37060
37060
  }), this.sprite = new X.Sprite(this.texture), this.contentContainer.addChild(this.sprite);
37061
37061
  }
37062
37062
  disposeVideo() {
@@ -38037,8 +38037,8 @@ class cr {
38037
38037
  this.updateAssetLoadMetadata(t, "loading", n);
38038
38038
  });
38039
38039
  return this.updateAssetLoadMetadata(t, "success", 1), a;
38040
- } catch {
38041
- return this.updateAssetLoadMetadata(t, "failed", 1), this.decrementRef(t), null;
38040
+ } catch (i) {
38041
+ return console.warn(`[AssetLoader] Failed to load asset "${t}":`, i), this.updateAssetLoadMetadata(t, "failed", 1), this.decrementRef(t), null;
38042
38042
  }
38043
38043
  }
38044
38044
  /**
@@ -1,4 +1,4 @@
1
- (function(gt,ts){typeof exports=="object"&&typeof module<"u"?ts(exports,require("pixi.js"),require("howler"),require("opentype.js")):typeof define=="function"&&define.amd?define(["exports","pixi.js","howler","opentype.js"],ts):(gt=typeof globalThis<"u"?globalThis:gt||self,ts(gt.ShotstackStudio={},gt.PIXI,gt.Howler,gt.opentype))})(this,function(gt,ts,N0,T0){"use strict";var vs=typeof document<"u"?document.currentScript:null;function Rr(s){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const e in s)if(e!=="default"){const i=Object.getOwnPropertyDescriptor(s,e);Object.defineProperty(t,e,i.get?i:{enumerable:!0,get:()=>s[e]})}}return t.default=s,Object.freeze(t)}const X=Rr(ts),I0=Rr(N0),zr=Rr(T0),A0={version:"2.0.0-beta.6"};class E0{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(t,e,i,a){const n=this.curves[a??""]??this.curves.ease,[[r,o],[l,c]]=n,d=i+(3*r-3*l+1)*i*(1-i),u=t,f=t+(e-t)*o,p=t+(e-t)*c,y=e,v=d,S=1-v;return S**3*u+3*S**2*v*f+3*S*v**2*p+v**3*y}}class ga{property;length;cubicBuilder;constructor(t,e,i=0){this.property=this.createKeyframes(t,e,i),this.length=e,this.cubicBuilder=new E0}getValue(t){const e=this.property.find(a=>t>=a.start&&t<a.start+a.length);if(!e){if(this.property.length>0){if(t>=this.length)return this.property[this.property.length-1].to;if(t<0)return this.property[0].from}return 1}const i=(t-e.start)/e.length;switch(e.interpolation){case"bezier":return this.cubicBuilder.getValue(e.from,e.to,i,e.easing);case"constant":return e.from;case"linear":default:return e.from+(e.to-e.from)*i}}createKeyframes(t,e,i=0){if(typeof t=="number")return[{start:0,length:e,from:t,to:t}];if(!t.length)throw new Error("Keyframes should have at least one value.");const a=this.createNormalizedKeyframes(t);try{this.validateKeyframes(a)}catch(n){console.warn("Keyframe configuration issues detected:",n)}return this.insertFillerKeyframes(a,e,i)}createNormalizedKeyframes(t){return t.filter(e=>typeof e.start=="number"&&typeof e.length=="number").toSorted((e,i)=>e.start-i.start).map(e=>({start:e.start,length:e.length,from:typeof e.from=="number"?e.from:0,to:typeof e.to=="number"?e.to:0,interpolation:e.interpolation,easing:e.easing}))}validateKeyframes(t){for(let e=0;e<t.length;e+=1){const i=t[e],a=t[e+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(t,e,i=0){const a=[];for(let n=0;n<t.length;n+=1){const r=t[n],o=t[n+1];if(n===0&&r.start!==0){const d={start:0,length:r.start,from:i,to:r.from};a.push(d)}if(a.push(r),!o){if(r.start+r.length<e){const u=r.start+r.length,f={start:u,length:e-u,from:r.to,to:r.to};a.push(f)}break}if(r.start+r.length!==o.start){const d=r.start+r.length,u=o.start-d,f={start:d,length:u,from:r.to,to:o.from};a.push(f)}}return a}}class ma{static Name="AudioLoadParser";id;name;extension;validAudioExtensions;constructor(){this.id=ma.Name,this.name=ma.Name,this.extension={type:[X.ExtensionType.LoadParser],priority:X.LoaderParserPriority.Normal,ref:null},this.validAudioExtensions=["mp3","mpeg","ogg","wav"]}test(t){const e=t.split("?")[0]?.split(".").pop()??"";return this.validAudioExtensions.includes(e)}async load(t,e,i){return new Promise(a=>{const n={src:t},r=new Howl(n);r.on("load",()=>a(r)),r.on("loaderror",()=>a(null))})}unload(t){t?.unload()}}class ni{baseValue;mode;layers=[];length;clampRange;constructor(t,e,i,a){this.baseValue=t,this.length=e,this.mode=i,this.clampRange=a}addLayer(t){if(t.length===0)return;const e=this.mode==="additive"?0:1;this.layers.push(new ga(t,this.length,e))}getValue(t){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(t);return i}let e=this.baseValue;for(const i of this.layers)e*=i.getValue(t);return this.clampRange&&(e=Math.max(this.clampRange.min,Math.min(this.clampRange.max,e))),e}}class P0{clipConfiguration;constructor(t){this.clipConfiguration=t}buildRelative(t,e){const i=[],a=[],n=[],r=[],o=[],{effect:l,length:c}=this.clipConfiguration;if(!l)return{offsetXKeyframes:i,offsetYKeyframes:a,opacityKeyframes:n,scaleKeyframes:r,rotationKeyframes:o};const d=0;switch(this.getPresetName()){case"zoomIn":{const f=this.getZoomSpeed();r.push({from:1,to:f,start:d,length:c,interpolation:"linear"});break}case"zoomOut":{const f=this.getZoomSpeed();r.push({from:f,to:1,start:d,length:c,interpolation:"linear"});break}case"slideLeft":{const f=this.getFittedSize(t,e);let p=this.getSlideStart();const y=t.width+t.width*p*2;if(f.width<y){const v=y/f.width;r.push({from:v,to:v,start:d,length:c,interpolation:"linear"})}else p=(f.width-t.width)/2/t.width;i.push({from:p,to:-p,start:d,length:c});break}case"slideRight":{const f=this.getFittedSize(t,e);let p=this.getSlideStart();const y=t.width+t.width*p*2;if(f.width<y){const v=y/f.width;r.push({from:v,to:v,start:d,length:c,interpolation:"linear"})}else p=(f.width-t.width)/2/t.width;i.push({from:-p,to:p,start:d,length:c});break}case"slideUp":{const f=this.getFittedSize(t,e);let p=this.getSlideStart();const y=t.height+t.height*p*2;if(f.height<y){const v=y/f.height;r.push({from:v,to:v,start:d,length:c,interpolation:"linear"})}else p=(f.height-t.height)/2/t.height;a.push({from:p,to:-p,start:d,length:c});break}case"slideDown":{const f=this.getFittedSize(t,e);let p=this.getSlideStart();const y=t.height+t.height*p*2;if(f.height<y){const v=y/f.height;r.push({from:v,to:v,start:d,length:c,interpolation:"linear"})}else p=(f.height-t.height)/2/t.height;a.push({from:-p,to:p,start:d,length:c});break}}return{offsetXKeyframes:i,offsetYKeyframes:a,opacityKeyframes:n,scaleKeyframes:r,rotationKeyframes:o}}getPresetName(){const[t]=(this.clipConfiguration.effect??"").split(/(Slow|Fast)/);return t}getZoomSpeed(){const[t,e]=(this.clipConfiguration.effect??"").split(/(Slow|Fast)/);if(t.startsWith("zoom"))switch(e){case"Slow":return 1.1;case"Fast":return 1.7;default:return 1.3}return 0}getSlideStart(){const[t,e]=(this.clipConfiguration.effect??"").split(/(Slow|Fast)/);if(t.startsWith("slide"))switch(e){case"Slow":return .03;case"Fast":return .2;default:return .12}return 0}getFittedSize(t,e){switch(this.clipConfiguration.fit??"crop"){case"cover":case"crop":{const a=Math.max(t.width/e.width,t.height/e.height);return{width:e.width*a,height:e.height*a}}case"contain":{const a=Math.min(t.width/e.width,t.height/e.height);return{width:e.width*a,height:e.height*a}}case"none":default:return e}}}class F0{clipConfiguration;constructor(t){this.clipConfiguration=t}buildRelative(){return{in:this.buildInPresetRelative(),out:this.buildOutPresetRelative()}}buildInPresetRelative(){const t=[],e=[],i=[],a=[],n=[],r=[];if(!this.clipConfiguration.transition?.in)return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:a,rotationKeyframes:n,maskXKeyframes:r};const o=0,l=this.getInPresetLength();switch(this.getInPresetName()){case"fade":{i.push({from:0,to:1,start:o,length:l,interpolation:"bezier",easing:"ease"});break}case"zoom":{a.push({from:10,to:1,start:o,length:l,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:o,length:l,interpolation:"bezier",easing:"easeIn"});break}case"slideLeft":{t.push({from:.025,to:0,start:o,length:l,interpolation:"linear"}),i.push({from:0,to:1,start:o,length:l,interpolation:"bezier",easing:"ease"});break}case"slideRight":{t.push({from:-.025,to:0,start:o,length:l,interpolation:"linear"}),i.push({from:0,to:1,start:o,length:l,interpolation:"bezier",easing:"ease"});break}case"slideUp":{e.push({from:.025,to:0,start:o,length:l,interpolation:"linear"}),i.push({from:0,to:1,start:o,length:l,interpolation:"bezier",easing:"ease"});break}case"slideDown":{e.push({from:-.025,to:0,start:o,length:l,interpolation:"linear"}),i.push({from:0,to:1,start:o,length:l,interpolation:"bezier",easing:"ease"});break}case"carouselLeft":{t.push({from:1,to:0,start:o,length:l,interpolation:"linear"});break}case"carouselRight":{t.push({from:-1,to:0,start:o,length:l,interpolation:"linear"});break}case"carouselUp":{e.push({from:-1.05,to:0,start:o,length:l,interpolation:"linear"});break}case"carouselDown":{e.push({from:1.05,to:0,start:o,length:l,interpolation:"linear"});break}case"reveal":case"wipeRight":{r.push({from:0,to:1,start:o,length:l,interpolation:"bezier",easing:"ease"});break}case"wipeLeft":{r.push({from:1,to:0,start:o,length:l,interpolation:"bezier",easing:"ease"});break}}return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:a,rotationKeyframes:n,maskXKeyframes:r}}buildOutPresetRelative(){const t=[],e=[],i=[],a=[],n=[],r=[];if(!this.clipConfiguration.transition?.out)return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:a,rotationKeyframes:n,maskXKeyframes:r};const o=this.getOutPresetLength(),l=this.clipConfiguration.length-o;switch(this.getOutPresetName()){case"fade":{i.push({from:1,to:0,start:l,length:o,interpolation:"bezier",easing:"ease"});break}case"zoom":{a.push({from:1,to:10,start:l,length:o,interpolation:"bezier",easing:"easeOut"}),i.push({from:1,to:0,start:l,length:o,interpolation:"bezier",easing:"easeOut"});break}case"slideLeft":{t.push({from:0,to:-.025,start:l,length:o,interpolation:"bezier",easing:"ease"}),i.push({from:1,to:0,start:l,length:o,interpolation:"bezier",easing:"ease"});break}case"slideRight":{t.push({from:0,to:.025,start:l,length:o,interpolation:"bezier",easing:"ease"}),i.push({from:1,to:0,start:l,length:o,interpolation:"bezier",easing:"ease"});break}case"slideUp":{e.push({from:0,to:-.025,start:l,length:o,interpolation:"bezier",easing:"ease"}),i.push({from:1,to:0,start:l,length:o,interpolation:"bezier",easing:"ease"});break}case"slideDown":{e.push({from:0,to:.025,start:l,length:o,interpolation:"bezier",easing:"ease"}),i.push({from:1,to:0,start:l,length:o,interpolation:"bezier",easing:"ease"});break}case"carouselLeft":{t.push({from:0,to:-1,start:l,length:o,interpolation:"bezier",easing:"ease"});break}case"carouselRight":{t.push({from:0,to:1,start:l,length:o,interpolation:"bezier",easing:"ease"});break}case"carouselUp":{e.push({from:0,to:1.1,start:l,length:o,interpolation:"bezier",easing:"ease"});break}case"carouselDown":{e.push({from:0,to:-1.1,start:l,length:o,interpolation:"bezier",easing:"ease"});break}case"reveal":case"wipeRight":{r.push({from:1,to:0,start:l,length:o,interpolation:"bezier",easing:"ease"});break}case"wipeLeft":{r.push({from:0,to:1,start:l,length:o,interpolation:"bezier",easing:"ease"});break}}return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:a,rotationKeyframes:n,maskXKeyframes:r}}getInPresetName(){const[t]=(this.clipConfiguration.transition?.in??"").split(/(Slow|Fast|VeryFast)/);return t}getOutPresetName(){const[t]=(this.clipConfiguration.transition?.out??"").split(/(Slow|Fast|VeryFast)/);return t}getInPresetLength(){const t=this.clipConfiguration.transition?.in??"",[e,i]=t.split(/(Slow|Fast|VeryFast)/),a=e.startsWith("carousel"),n=e.startsWith("slide");if(e==="zoom")return .4;switch(i){case"Slow":return 2;case"Fast":return a||n?.25:.5;case"VeryFast":return .25;default:return a||n?.5:1}}getOutPresetLength(){const t=this.clipConfiguration.transition?.out??"",[e,i]=t.split(/(Slow|Fast|VeryFast)/),a=e.startsWith("carousel"),n=e.startsWith("slide");if(e==="zoom")return .4;switch(i){case"Slow":return 2;case"Fast":return a||n?.25:.5;case"VeryFast":return .25;default:return a||n?.5:1}}}const j={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",SelectionCleared:"selection:cleared",EditChanged:"edit:changed",EditUndo:"edit:undo",EditRedo:"edit:redo",TrackAdded:"track:added",TrackRemoved:"track:removed",DurationChanged:"duration:changed",OutputResized:"output:resized",OutputFpsChanged:"output:fpsChanged",OutputFormatChanged:"output:formatChanged",OutputDestinationsChanged:"output:destinationsChanged",MergeFieldRegistered:"mergefield:registered",MergeFieldUpdated:"mergefield:updated",MergeFieldRemoved:"mergefield:removed",MergeFieldChanged:"mergefield:changed",MergeFieldApplied:"mergefield:applied",TranscriptionProgress:"transcription:progress",TranscriptionCompleted:"transcription:completed",TranscriptionFailed:"transcription:failed",LumaAttached:"luma:attached",LumaDetached:"luma:detached"},_s={CanvasClipClicked:"canvas:clipClicked",CanvasBackgroundClicked:"canvas:backgroundClicked",FontCapabilitiesChanged:"font:capabilitiesChanged",ToolbarButtonsChanged:"toolbar:buttonsChanged"};function M0(s,t,e){const i=t.width/s.width,a=t.height/s.height;switch(e??"crop"){case"crop":case"cover":return Math.max(i,a);case"contain":return Math.min(i,a);case"none":default:return 1}}function L0(s,t,e,i,a){if(a)return{x:i,y:i};if(s.width===0||s.height===0)return{x:i,y:i};const n=t.width/s.width,r=t.height/s.height;switch(e??"crop"){case"contain":{const o=Math.min(n,r)*i;return{x:o,y:o}}case"crop":{const o=Math.max(n,r)*i;return{x:o,y:o}}case"cover":return{x:n*i,y:r*i};case"none":default:return{x:i,y:i}}}function B0(s,t,e){const i=t.width/2,a=t.height/2;switch(e??"crop"){case"cover":{const n=t.width/s.width,r=t.height/s.height;return{scaleX:n,scaleY:r,positionX:i,positionY:a}}case"crop":{const n=Math.max(t.width/s.width,t.height/s.height);return{scaleX:n,scaleY:n,positionX:i,positionY:a}}case"contain":{const n=Math.min(t.width/s.width,t.height/s.height);return{scaleX:n,scaleY:n,positionX:i,positionY:a}}case"none":default:return{scaleX:1,scaleY:1,positionX:i,positionY:a}}}function on(s){return!!(s&&typeof s=="object"&&!Array.isArray(s))}function Dr(s,t){const e={...s};return on(s)&&on(t)&&Object.keys(t).forEach(i=>{if(i==="__proto__"||i==="constructor"||i==="prototype")return;const a=t[i],n=s[i];on(a)?i in s&&on(n)?e[i]=Dr(n,a):e[i]=Dr({},a):e[i]=a}),e}function Ur(s,t,e){const i=t.split(".");let a=s;for(let n=0;n<i.length-1;n+=1){if(a==null||typeof a!="object")return;a=a[i[n]]}a!=null&&typeof a=="object"&&(a[i[i.length-1]]=e)}function Ei(s,t){const e=t.split(".");let i=s;for(const a of e){if(i==null||typeof i!="object")return;i=i[a]}return i}async function Xl(s){try{new URL(s)}catch{return{valid:!1,error:"Invalid URL format"}}try{const t=await fetch(s,{method:"HEAD",mode:"cors"});return t.ok?{valid:!0}:{valid:!1,error:`URL returned ${t.status} ${t.statusText}`}}catch(t){return{valid:!1,error:t instanceof Error?t.message:"URL not accessible"}}}function O0(s){return s/1e3}function o8(s){return s}function l8(s){return s}let Kl=class{static ButtonLeftClick=0;static ButtonRightClick=3};class Ql{containerSize;constructor(t){this.containerSize=t}relativeToAbsolute(t,e,i){switch(e){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-t.width,y:-i.y*this.containerSize.height};case"bottomLeft":return{x:i.x*this.containerSize.width,y:(-i.y+1)*this.containerSize.height-t.height};case"bottomRight":return{x:(i.x+1)*this.containerSize.width-t.width,y:(-i.y+1)*this.containerSize.height-t.height};case"left":return{x:i.x*this.containerSize.width,y:(-i.y+.5)*this.containerSize.height-t.height/2};case"right":return{x:(i.x+1)*this.containerSize.width-t.width,y:(-i.y+.5)*this.containerSize.height-t.height/2};case"top":return{x:(i.x+.5)*this.containerSize.width-t.width/2,y:-i.y*this.containerSize.height};case"bottom":return{x:(i.x+.5)*this.containerSize.width-t.width/2,y:(-i.y+1)*this.containerSize.height-t.height};case"center":default:return{x:(i.x+.5)*this.containerSize.width-t.width/2,y:(-i.y+.5)*this.containerSize.height-t.height/2}}}absoluteToRelative(t,e,i){switch(e){case"topLeft":return{x:i.x/this.containerSize.width,y:-(i.y/this.containerSize.height)};case"topRight":return{x:(i.x+t.width)/this.containerSize.width-1,y:-(i.y/this.containerSize.height)};case"bottomLeft":return{x:i.x/this.containerSize.width,y:-((i.y+t.height)/this.containerSize.height-1)};case"bottomRight":return{x:(i.x+t.width)/this.containerSize.width-1,y:-((i.y+t.height)/this.containerSize.height-1)};case"left":return{x:i.x/this.containerSize.width,y:-((i.y+t.height/2)/this.containerSize.height-.5)};case"right":return{x:(i.x+t.width)/this.containerSize.width-1,y:-((i.y+t.height/2)/this.containerSize.height-.5)};case"top":return{x:(i.x+t.width/2)/this.containerSize.width-.5,y:-(i.y/this.containerSize.height)};case"bottom":return{x:(i.x+t.width/2)/this.containerSize.width-.5,y:-((i.y+t.height)/this.containerSize.height-1)};case"center":default:return{x:(i.x+t.width/2)/this.containerSize.width-.5,y:-((i.y+t.height/2)/this.containerSize.height-.5)}}}}class ln{container;constructor(){this.container=new X.Container}getContainer(){return this.container}}var qt=(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))(qt||{});class je extends ln{static DiscardedFrameCount=0;layer;shouldDispose;playerType;edit;clipConfiguration;timingIntent;resolvedTiming;positionBuilder;offsetXKeyframeBuilder;offsetYKeyframeBuilder;scaleKeyframeBuilder;opacityKeyframeBuilder;rotationKeyframeBuilder;maskXKeyframeBuilder;wipeMask;contentContainer;mergeFieldBindings=new Map;constructor(t,e,i){super(),this.edit=t,this.layer=0,this.shouldDispose=!1,this.playerType=i,this.clipConfiguration=e,this.positionBuilder=new Ql(t.size),this.timingIntent={start:e.start,length:e.length},this.resolvedTiming={start:e.start,length:e.length},this.wipeMask=null,this.contentContainer=new X.Container,this.getContainer().addChild(this.contentContainer)}reconfigureAfterRestore(){this.configureKeyframes()}async reloadAsset(){}configureKeyframes(){const t=this.getLength(),e=this.clipConfiguration,i=typeof e.offset?.x=="number"?e.offset.x:0,a=typeof e.offset?.y=="number"?e.offset.y:0,n=typeof e.scale=="number"?e.scale:1,r=typeof e.opacity=="number"?e.opacity:1,o=typeof e.transform?.rotate?.angle=="number"?e.transform.rotate.angle:0;if(this.offsetXKeyframeBuilder=new ni(i,t,"additive"),this.offsetYKeyframeBuilder=new ni(a,t,"additive"),this.scaleKeyframeBuilder=new ni(n,t,"multiplicative"),this.opacityKeyframeBuilder=new ni(r,t,"multiplicative",{min:0,max:1}),this.rotationKeyframeBuilder=new ni(o,t,"additive"),this.clipHasKeyframes())return;const l={...e,start:this.getStart(),length:t},c=new P0(l).buildRelative(this.edit.size,this.getSize()),d=new F0(l).buildRelative();this.offsetXKeyframeBuilder.addLayer(c.offsetXKeyframes),this.offsetYKeyframeBuilder.addLayer(c.offsetYKeyframes),this.scaleKeyframeBuilder.addLayer(c.scaleKeyframes),this.opacityKeyframeBuilder.addLayer(c.opacityKeyframes),this.rotationKeyframeBuilder.addLayer(c.rotationKeyframes),this.offsetXKeyframeBuilder.addLayer(d.in.offsetXKeyframes),this.offsetYKeyframeBuilder.addLayer(d.in.offsetYKeyframes),this.scaleKeyframeBuilder.addLayer(d.in.scaleKeyframes),this.opacityKeyframeBuilder.addLayer(d.in.opacityKeyframes),this.rotationKeyframeBuilder.addLayer(d.in.rotationKeyframes),this.offsetXKeyframeBuilder.addLayer(d.out.offsetXKeyframes),this.offsetYKeyframeBuilder.addLayer(d.out.offsetYKeyframes),this.scaleKeyframeBuilder.addLayer(d.out.scaleKeyframes),this.opacityKeyframeBuilder.addLayer(d.out.opacityKeyframes),this.rotationKeyframeBuilder.addLayer(d.out.rotationKeyframes);const u=[...d.in.maskXKeyframes,...d.out.maskXKeyframes];u.length&&(this.maskXKeyframeBuilder=new ga(u,t))}async load(){this.contentContainer?.destroyed&&(this.contentContainer=new X.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(t,e){if(this.getContainer().visible=this.isActive(),this.getContainer().zIndex=1e5-this.layer*100,!this.isActive())return;const i=this.getPivot(),a=this.getPosition(),n=this.getContainerScale();this.getContainer().scale.set(n.x,n.y),this.getContainer().pivot.set(i.x,i.y),this.getContainer().position.set(a.x+i.x,a.y+i.y);const r=this.getRotation();this.contentContainer.alpha=this.getOpacity(),this.getContainer().angle=r,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 t=this.maskXKeyframeBuilder.getValue(this.getPlaybackTime()),e=this.getSize();this.wipeMask||(this.wipeMask=new X.Graphics,this.getContainer().addChild(this.wipeMask),this.getContainer().mask=this.wipeMask),this.wipeMask.clear(),this.wipeMask.rect(0,0,e.width*t,e.height),this.wipeMask.fill(16777215)}draw(){this.clipConfiguration.width&&this.clipConfiguration.height&&this.applyFixedDimensions()}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(){return{...this.timingIntent}}setTimingIntent(t){t.start!==void 0&&(this.timingIntent.start=t.start),t.length!==void 0&&(this.timingIntent.length=t.length)}getResolvedTiming(){return{...this.resolvedTiming}}setResolvedTiming(t){this.resolvedTiming={...t}}convertToFixedTiming(){this.timingIntent={start:this.resolvedTiming.start,length:this.resolvedTiming.length}}setMergeFieldBinding(t,e){this.mergeFieldBindings.set(t,e)}getMergeFieldBinding(t){return this.mergeFieldBindings.get(t)}removeMergeFieldBinding(t){this.mergeFieldBindings.delete(t)}getMergeFieldBindings(){return this.mergeFieldBindings}setInitialBindings(t){this.mergeFieldBindings=new Map(t)}getExportableClip(){const t=structuredClone(this.clipConfiguration);for(const[i,{placeholder:a,resolvedValue:n}]of this.mergeFieldBindings)Ei(t,i)===n&&Ur(t,i,a);const e=this.getTimingIntent();return t.start=e.start,t.length=e.length,t}getPlaybackTime(){const e=this.edit.playbackTime/1e3-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 t={x:this.offsetXKeyframeBuilder?.getValue(this.getPlaybackTime())??0,y:this.offsetYKeyframeBuilder?.getValue(this.getPlaybackTime())??0};return this.positionBuilder.relativeToAbsolute(this.getSize(),this.clipConfiguration.position??"center",t)}getPivot(){const t=this.getSize();return{x:t.width/2,y:t.height/2}}moveBy(t,e){const i=this.getPosition(),a={x:i.x+t,y:i.y+e},n=this.positionBuilder.absoluteToRelative(this.getSize(),this.clipConfiguration.position??"center",a);this.clipConfiguration.offset||(this.clipConfiguration.offset={x:0,y:0}),this.clipConfiguration.offset.x=n.x,this.clipConfiguration.offset.y=n.y,this.offsetXKeyframeBuilder=new ni(n.x,this.getLength(),"additive"),this.offsetYKeyframeBuilder=new ni(n.y,this.getLength(),"additive")}getFitScale(){const t={width:this.clipConfiguration.width??this.edit.size.width,height:this.clipConfiguration.height??this.edit.size.height},e=this.getContentSize(),i=this.clipConfiguration.fit??"crop";return M0(e,t,i)}getScale(){return(this.scaleKeyframeBuilder?.getValue(this.getPlaybackTime())??1)*this.getFitScale()}getContainerScale(){const t=this.scaleKeyframeBuilder?.getValue(this.getPlaybackTime())??1,e=this.getContentSize(),i=this.clipConfiguration.fit??"crop",a=!!(this.clipConfiguration.width&&this.clipConfiguration.height);return L0(e,this.edit.size,i,t,a)}getRotation(){return this.rotationKeyframeBuilder?.getValue(this.getPlaybackTime())??0}isActive(){const t=this.edit.playbackTime/1e3;return t>=this.getStart()&&t<this.getEnd()}shouldDiscardFrame(){return this.getPlaybackTime()<je.DiscardedFrameCount}onPointerDown(t){t.button===Kl.ButtonLeftClick&&this.edit.events.emit(_s.CanvasClipClicked,{player:this})}clipHasKeyframes(){return[this.clipConfiguration.scale,this.clipConfiguration.offset?.x,this.clipConfiguration.offset?.y,this.clipConfiguration.transform?.rotate?.angle].some(t=>t&&typeof t!="number")}applyFixedDimensions(){const t=this.clipConfiguration.width,e=this.clipConfiguration.height;if(!t||!e)return;const i=this.contentContainer.children.find(f=>f instanceof X.Sprite);if(!i?.texture)return;const a=i.texture.width,n=i.texture.height,r=this.clipConfiguration.fit||"crop";let o=this.contentContainer.mask;o||(o=new X.Graphics,this.contentContainer.addChild(o),this.contentContainer.mask=o),o.clear(),o.rect(0,0,t,e),o.fill(16777215);const l=this.scaleKeyframeBuilder?.getValue(this.getPlaybackTime())??1;i.anchor.set(.5,.5);const u=B0({width:a,height:n},{width:t,height:e},r);i.scale.set(u.scaleX,u.scaleY),i.position.set(u.positionX,u.positionY),this.contentContainer.scale.set(l,l),this.contentContainer.position.set(t/2*(1-l),e/2*(1-l))}applyAnchorPositioning(t,e,i,a){const n=a.width,r=a.height;if(!!a.mask){a.position.set(0,0);return}const l=(t??"center").toLowerCase();let c=0,d=0;l.includes("left")||l==="left"?c=0:l.includes("right")||l==="right"?c=e-n:c=(e-n)/2,l.includes("top")||l==="top"?d=0:l.includes("bottom")||l==="bottom"?d=i-r:d=(i-r)/2,a.position.set(c,d)}supportsEdgeResize(){return!1}onDimensionsChanged(){}notifyDimensionsChanged(){this.onDimensionsChanged()}}class Jl extends je{audioResource;isPlaying;volumeKeyframeBuilder;syncTimer;constructor(t,e){super(t,e,qt.Audio),this.audioResource=null,this.isPlaying=!1,this.syncTimer=0}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.src,i={src:e,parser:ma.Name},a=await this.edit.assetLoader.load(e,i);if(!(a instanceof I0.Howl))throw new Error(`Invalid audio source '${t.src}'.`);this.audioResource=a;const r=typeof t.volume=="number"?t.volume:1;this.volumeKeyframeBuilder=new ga(this.createVolumeKeyframes(t,r),this.getLength(),r),this.configureKeyframes()}update(t,e){super.update(t,e);const{trim:i=0}=this.clipConfiguration.asset;if(this.syncTimer+=e,this.getContainer().alpha=0,!this.audioResource)return;const a=this.edit.isPlaying&&this.isActive(),n=this.getPlaybackTime();a&&(this.isPlaying||(this.isPlaying=!0,this.audioResource.seek(n+i),this.audioResource.play()),this.audioResource.volume()!==this.getVolume()&&this.audioResource.volume(this.getVolume()),Math.abs(this.audioResource.seek()-i-n)>.1&&(this.audioResource.seek(n+i),this.edit.recordSyncCorrection())),this.isPlaying&&!a&&(this.isPlaying=!1,this.audioResource.pause());const r=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&r&&(this.syncTimer=0,this.audioResource.seek(n+i))}draw(){super.draw()}dispose(){this.audioResource?.unload(),this.audioResource=null}reconfigureAfterRestore(){super.reconfigureAfterRestore();const t=this.clipConfiguration.asset,e=typeof t.volume=="number"?t.volume:1;this.volumeKeyframeBuilder=new ga(this.createVolumeKeyframes(t,e),this.getLength(),e)}getSize(){return{width:0,height:0}}getVolume(){return this.volumeKeyframeBuilder.getValue(this.getPlaybackTime())}getCurrentDrift(){if(!this.audioResource)return 0;const{trim:t=0}=this.clipConfiguration.asset,e=this.audioResource.seek(),i=this.getPlaybackTime();return Math.abs(e-t-i)}createVolumeKeyframes(t,e){const{effect:i,volume:a}=t;if(!i||i==="none"||Array.isArray(a))return a??1;const n=this.getLength()/1e3,r=Math.min(2,n/2);return i==="fadeIn"?[{from:0,to:e,start:0,length:r}]:i==="fadeOut"?[{from:e,to:0,start:n-r,length:r}]:[{from:0,to:e,start:0,length:r},{from:e,to:0,start:n-r,length:r}]}}function cn(s){const t=s.trim().replace(",","."),e=t.split(":");if(e.length===3){const i=parseInt(e[0],10),a=parseInt(e[1],10),n=parseFloat(e[2]);return i*3600+a*60+n}if(e.length===2){const i=parseInt(e[0],10),a=parseFloat(e[1]);return i*60+a}return parseFloat(t)||0}function _0(s){const t=[],e=s.split(/\r?\n/);let i=0;for(;i<e.length&&!e[i].includes("-->");)i+=1;for(;i<e.length;){const a=e[i].trim();if(a.includes("-->")){const[n,r]=a.split("-->").map(d=>d.trim().split(" ")[0]),o=cn(n),l=cn(r),c=[];for(i+=1;i<e.length&&e[i].trim()!==""&&!e[i].includes("-->");){const d=e[i].trim();d.startsWith("NOTE")||c.push(d),i+=1}c.length>0&&t.push({start:o,end:l,text:c.join(`
1
+ (function(gt,ts){typeof exports=="object"&&typeof module<"u"?ts(exports,require("pixi.js"),require("howler"),require("opentype.js")):typeof define=="function"&&define.amd?define(["exports","pixi.js","howler","opentype.js"],ts):(gt=typeof globalThis<"u"?globalThis:gt||self,ts(gt.ShotstackStudio={},gt.PIXI,gt.Howler,gt.opentype))})(this,function(gt,ts,N0,T0){"use strict";var vs=typeof document<"u"?document.currentScript:null;function Rr(s){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const e in s)if(e!=="default"){const i=Object.getOwnPropertyDescriptor(s,e);Object.defineProperty(t,e,i.get?i:{enumerable:!0,get:()=>s[e]})}}return t.default=s,Object.freeze(t)}const X=Rr(ts),I0=Rr(N0),zr=Rr(T0),A0={version:"2.0.0-beta.7"};class E0{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(t,e,i,a){const n=this.curves[a??""]??this.curves.ease,[[r,o],[l,c]]=n,d=i+(3*r-3*l+1)*i*(1-i),u=t,f=t+(e-t)*o,p=t+(e-t)*c,y=e,v=d,S=1-v;return S**3*u+3*S**2*v*f+3*S*v**2*p+v**3*y}}class ga{property;length;cubicBuilder;constructor(t,e,i=0){this.property=this.createKeyframes(t,e,i),this.length=e,this.cubicBuilder=new E0}getValue(t){const e=this.property.find(a=>t>=a.start&&t<a.start+a.length);if(!e){if(this.property.length>0){if(t>=this.length)return this.property[this.property.length-1].to;if(t<0)return this.property[0].from}return 1}const i=(t-e.start)/e.length;switch(e.interpolation){case"bezier":return this.cubicBuilder.getValue(e.from,e.to,i,e.easing);case"constant":return e.from;case"linear":default:return e.from+(e.to-e.from)*i}}createKeyframes(t,e,i=0){if(typeof t=="number")return[{start:0,length:e,from:t,to:t}];if(!t.length)throw new Error("Keyframes should have at least one value.");const a=this.createNormalizedKeyframes(t);try{this.validateKeyframes(a)}catch(n){console.warn("Keyframe configuration issues detected:",n)}return this.insertFillerKeyframes(a,e,i)}createNormalizedKeyframes(t){return t.filter(e=>typeof e.start=="number"&&typeof e.length=="number").toSorted((e,i)=>e.start-i.start).map(e=>({start:e.start,length:e.length,from:typeof e.from=="number"?e.from:0,to:typeof e.to=="number"?e.to:0,interpolation:e.interpolation,easing:e.easing}))}validateKeyframes(t){for(let e=0;e<t.length;e+=1){const i=t[e],a=t[e+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(t,e,i=0){const a=[];for(let n=0;n<t.length;n+=1){const r=t[n],o=t[n+1];if(n===0&&r.start!==0){const d={start:0,length:r.start,from:i,to:r.from};a.push(d)}if(a.push(r),!o){if(r.start+r.length<e){const u=r.start+r.length,f={start:u,length:e-u,from:r.to,to:r.to};a.push(f)}break}if(r.start+r.length!==o.start){const d=r.start+r.length,u=o.start-d,f={start:d,length:u,from:r.to,to:o.from};a.push(f)}}return a}}class ma{static Name="AudioLoadParser";id;name;extension;validAudioExtensions;constructor(){this.id=ma.Name,this.name=ma.Name,this.extension={type:[X.ExtensionType.LoadParser],priority:X.LoaderParserPriority.Normal,ref:null},this.validAudioExtensions=["mp3","mpeg","ogg","wav"]}test(t){const e=t.split("?")[0]?.split(".").pop()??"";return this.validAudioExtensions.includes(e)}async load(t,e,i){return new Promise(a=>{const n={src:t},r=new Howl(n);r.on("load",()=>a(r)),r.on("loaderror",()=>a(null))})}unload(t){t?.unload()}}class ni{baseValue;mode;layers=[];length;clampRange;constructor(t,e,i,a){this.baseValue=t,this.length=e,this.mode=i,this.clampRange=a}addLayer(t){if(t.length===0)return;const e=this.mode==="additive"?0:1;this.layers.push(new ga(t,this.length,e))}getValue(t){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(t);return i}let e=this.baseValue;for(const i of this.layers)e*=i.getValue(t);return this.clampRange&&(e=Math.max(this.clampRange.min,Math.min(this.clampRange.max,e))),e}}class P0{clipConfiguration;constructor(t){this.clipConfiguration=t}buildRelative(t,e){const i=[],a=[],n=[],r=[],o=[],{effect:l,length:c}=this.clipConfiguration;if(!l)return{offsetXKeyframes:i,offsetYKeyframes:a,opacityKeyframes:n,scaleKeyframes:r,rotationKeyframes:o};const d=0;switch(this.getPresetName()){case"zoomIn":{const f=this.getZoomSpeed();r.push({from:1,to:f,start:d,length:c,interpolation:"linear"});break}case"zoomOut":{const f=this.getZoomSpeed();r.push({from:f,to:1,start:d,length:c,interpolation:"linear"});break}case"slideLeft":{const f=this.getFittedSize(t,e);let p=this.getSlideStart();const y=t.width+t.width*p*2;if(f.width<y){const v=y/f.width;r.push({from:v,to:v,start:d,length:c,interpolation:"linear"})}else p=(f.width-t.width)/2/t.width;i.push({from:p,to:-p,start:d,length:c});break}case"slideRight":{const f=this.getFittedSize(t,e);let p=this.getSlideStart();const y=t.width+t.width*p*2;if(f.width<y){const v=y/f.width;r.push({from:v,to:v,start:d,length:c,interpolation:"linear"})}else p=(f.width-t.width)/2/t.width;i.push({from:-p,to:p,start:d,length:c});break}case"slideUp":{const f=this.getFittedSize(t,e);let p=this.getSlideStart();const y=t.height+t.height*p*2;if(f.height<y){const v=y/f.height;r.push({from:v,to:v,start:d,length:c,interpolation:"linear"})}else p=(f.height-t.height)/2/t.height;a.push({from:p,to:-p,start:d,length:c});break}case"slideDown":{const f=this.getFittedSize(t,e);let p=this.getSlideStart();const y=t.height+t.height*p*2;if(f.height<y){const v=y/f.height;r.push({from:v,to:v,start:d,length:c,interpolation:"linear"})}else p=(f.height-t.height)/2/t.height;a.push({from:-p,to:p,start:d,length:c});break}}return{offsetXKeyframes:i,offsetYKeyframes:a,opacityKeyframes:n,scaleKeyframes:r,rotationKeyframes:o}}getPresetName(){const[t]=(this.clipConfiguration.effect??"").split(/(Slow|Fast)/);return t}getZoomSpeed(){const[t,e]=(this.clipConfiguration.effect??"").split(/(Slow|Fast)/);if(t.startsWith("zoom"))switch(e){case"Slow":return 1.1;case"Fast":return 1.7;default:return 1.3}return 0}getSlideStart(){const[t,e]=(this.clipConfiguration.effect??"").split(/(Slow|Fast)/);if(t.startsWith("slide"))switch(e){case"Slow":return .03;case"Fast":return .2;default:return .12}return 0}getFittedSize(t,e){switch(this.clipConfiguration.fit??"crop"){case"cover":case"crop":{const a=Math.max(t.width/e.width,t.height/e.height);return{width:e.width*a,height:e.height*a}}case"contain":{const a=Math.min(t.width/e.width,t.height/e.height);return{width:e.width*a,height:e.height*a}}case"none":default:return e}}}class F0{clipConfiguration;constructor(t){this.clipConfiguration=t}buildRelative(){return{in:this.buildInPresetRelative(),out:this.buildOutPresetRelative()}}buildInPresetRelative(){const t=[],e=[],i=[],a=[],n=[],r=[];if(!this.clipConfiguration.transition?.in)return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:a,rotationKeyframes:n,maskXKeyframes:r};const o=0,l=this.getInPresetLength();switch(this.getInPresetName()){case"fade":{i.push({from:0,to:1,start:o,length:l,interpolation:"bezier",easing:"ease"});break}case"zoom":{a.push({from:10,to:1,start:o,length:l,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:o,length:l,interpolation:"bezier",easing:"easeIn"});break}case"slideLeft":{t.push({from:.025,to:0,start:o,length:l,interpolation:"linear"}),i.push({from:0,to:1,start:o,length:l,interpolation:"bezier",easing:"ease"});break}case"slideRight":{t.push({from:-.025,to:0,start:o,length:l,interpolation:"linear"}),i.push({from:0,to:1,start:o,length:l,interpolation:"bezier",easing:"ease"});break}case"slideUp":{e.push({from:.025,to:0,start:o,length:l,interpolation:"linear"}),i.push({from:0,to:1,start:o,length:l,interpolation:"bezier",easing:"ease"});break}case"slideDown":{e.push({from:-.025,to:0,start:o,length:l,interpolation:"linear"}),i.push({from:0,to:1,start:o,length:l,interpolation:"bezier",easing:"ease"});break}case"carouselLeft":{t.push({from:1,to:0,start:o,length:l,interpolation:"linear"});break}case"carouselRight":{t.push({from:-1,to:0,start:o,length:l,interpolation:"linear"});break}case"carouselUp":{e.push({from:-1.05,to:0,start:o,length:l,interpolation:"linear"});break}case"carouselDown":{e.push({from:1.05,to:0,start:o,length:l,interpolation:"linear"});break}case"reveal":case"wipeRight":{r.push({from:0,to:1,start:o,length:l,interpolation:"bezier",easing:"ease"});break}case"wipeLeft":{r.push({from:1,to:0,start:o,length:l,interpolation:"bezier",easing:"ease"});break}}return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:a,rotationKeyframes:n,maskXKeyframes:r}}buildOutPresetRelative(){const t=[],e=[],i=[],a=[],n=[],r=[];if(!this.clipConfiguration.transition?.out)return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:a,rotationKeyframes:n,maskXKeyframes:r};const o=this.getOutPresetLength(),l=this.clipConfiguration.length-o;switch(this.getOutPresetName()){case"fade":{i.push({from:1,to:0,start:l,length:o,interpolation:"bezier",easing:"ease"});break}case"zoom":{a.push({from:1,to:10,start:l,length:o,interpolation:"bezier",easing:"easeOut"}),i.push({from:1,to:0,start:l,length:o,interpolation:"bezier",easing:"easeOut"});break}case"slideLeft":{t.push({from:0,to:-.025,start:l,length:o,interpolation:"bezier",easing:"ease"}),i.push({from:1,to:0,start:l,length:o,interpolation:"bezier",easing:"ease"});break}case"slideRight":{t.push({from:0,to:.025,start:l,length:o,interpolation:"bezier",easing:"ease"}),i.push({from:1,to:0,start:l,length:o,interpolation:"bezier",easing:"ease"});break}case"slideUp":{e.push({from:0,to:-.025,start:l,length:o,interpolation:"bezier",easing:"ease"}),i.push({from:1,to:0,start:l,length:o,interpolation:"bezier",easing:"ease"});break}case"slideDown":{e.push({from:0,to:.025,start:l,length:o,interpolation:"bezier",easing:"ease"}),i.push({from:1,to:0,start:l,length:o,interpolation:"bezier",easing:"ease"});break}case"carouselLeft":{t.push({from:0,to:-1,start:l,length:o,interpolation:"bezier",easing:"ease"});break}case"carouselRight":{t.push({from:0,to:1,start:l,length:o,interpolation:"bezier",easing:"ease"});break}case"carouselUp":{e.push({from:0,to:1.1,start:l,length:o,interpolation:"bezier",easing:"ease"});break}case"carouselDown":{e.push({from:0,to:-1.1,start:l,length:o,interpolation:"bezier",easing:"ease"});break}case"reveal":case"wipeRight":{r.push({from:1,to:0,start:l,length:o,interpolation:"bezier",easing:"ease"});break}case"wipeLeft":{r.push({from:0,to:1,start:l,length:o,interpolation:"bezier",easing:"ease"});break}}return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:a,rotationKeyframes:n,maskXKeyframes:r}}getInPresetName(){const[t]=(this.clipConfiguration.transition?.in??"").split(/(Slow|Fast|VeryFast)/);return t}getOutPresetName(){const[t]=(this.clipConfiguration.transition?.out??"").split(/(Slow|Fast|VeryFast)/);return t}getInPresetLength(){const t=this.clipConfiguration.transition?.in??"",[e,i]=t.split(/(Slow|Fast|VeryFast)/),a=e.startsWith("carousel"),n=e.startsWith("slide");if(e==="zoom")return .4;switch(i){case"Slow":return 2;case"Fast":return a||n?.25:.5;case"VeryFast":return .25;default:return a||n?.5:1}}getOutPresetLength(){const t=this.clipConfiguration.transition?.out??"",[e,i]=t.split(/(Slow|Fast|VeryFast)/),a=e.startsWith("carousel"),n=e.startsWith("slide");if(e==="zoom")return .4;switch(i){case"Slow":return 2;case"Fast":return a||n?.25:.5;case"VeryFast":return .25;default:return a||n?.5:1}}}const j={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",SelectionCleared:"selection:cleared",EditChanged:"edit:changed",EditUndo:"edit:undo",EditRedo:"edit:redo",TrackAdded:"track:added",TrackRemoved:"track:removed",DurationChanged:"duration:changed",OutputResized:"output:resized",OutputFpsChanged:"output:fpsChanged",OutputFormatChanged:"output:formatChanged",OutputDestinationsChanged:"output:destinationsChanged",MergeFieldRegistered:"mergefield:registered",MergeFieldUpdated:"mergefield:updated",MergeFieldRemoved:"mergefield:removed",MergeFieldChanged:"mergefield:changed",MergeFieldApplied:"mergefield:applied",TranscriptionProgress:"transcription:progress",TranscriptionCompleted:"transcription:completed",TranscriptionFailed:"transcription:failed",LumaAttached:"luma:attached",LumaDetached:"luma:detached"},_s={CanvasClipClicked:"canvas:clipClicked",CanvasBackgroundClicked:"canvas:backgroundClicked",FontCapabilitiesChanged:"font:capabilitiesChanged",ToolbarButtonsChanged:"toolbar:buttonsChanged"};function M0(s,t,e){const i=t.width/s.width,a=t.height/s.height;switch(e??"crop"){case"crop":case"cover":return Math.max(i,a);case"contain":return Math.min(i,a);case"none":default:return 1}}function L0(s,t,e,i,a){if(a)return{x:i,y:i};if(s.width===0||s.height===0)return{x:i,y:i};const n=t.width/s.width,r=t.height/s.height;switch(e??"crop"){case"contain":{const o=Math.min(n,r)*i;return{x:o,y:o}}case"crop":{const o=Math.max(n,r)*i;return{x:o,y:o}}case"cover":return{x:n*i,y:r*i};case"none":default:return{x:i,y:i}}}function B0(s,t,e){const i=t.width/2,a=t.height/2;switch(e??"crop"){case"cover":{const n=t.width/s.width,r=t.height/s.height;return{scaleX:n,scaleY:r,positionX:i,positionY:a}}case"crop":{const n=Math.max(t.width/s.width,t.height/s.height);return{scaleX:n,scaleY:n,positionX:i,positionY:a}}case"contain":{const n=Math.min(t.width/s.width,t.height/s.height);return{scaleX:n,scaleY:n,positionX:i,positionY:a}}case"none":default:return{scaleX:1,scaleY:1,positionX:i,positionY:a}}}function on(s){return!!(s&&typeof s=="object"&&!Array.isArray(s))}function Dr(s,t){const e={...s};return on(s)&&on(t)&&Object.keys(t).forEach(i=>{if(i==="__proto__"||i==="constructor"||i==="prototype")return;const a=t[i],n=s[i];on(a)?i in s&&on(n)?e[i]=Dr(n,a):e[i]=Dr({},a):e[i]=a}),e}function Ur(s,t,e){const i=t.split(".");let a=s;for(let n=0;n<i.length-1;n+=1){if(a==null||typeof a!="object")return;a=a[i[n]]}a!=null&&typeof a=="object"&&(a[i[i.length-1]]=e)}function Ei(s,t){const e=t.split(".");let i=s;for(const a of e){if(i==null||typeof i!="object")return;i=i[a]}return i}async function Xl(s){try{new URL(s)}catch{return{valid:!1,error:"Invalid URL format"}}try{const t=await fetch(s,{method:"HEAD",mode:"cors"});return t.ok?{valid:!0}:{valid:!1,error:`URL returned ${t.status} ${t.statusText}`}}catch(t){return{valid:!1,error:t instanceof Error?t.message:"URL not accessible"}}}function O0(s){return s/1e3}function o8(s){return s}function l8(s){return s}let Kl=class{static ButtonLeftClick=0;static ButtonRightClick=3};class Ql{containerSize;constructor(t){this.containerSize=t}relativeToAbsolute(t,e,i){switch(e){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-t.width,y:-i.y*this.containerSize.height};case"bottomLeft":return{x:i.x*this.containerSize.width,y:(-i.y+1)*this.containerSize.height-t.height};case"bottomRight":return{x:(i.x+1)*this.containerSize.width-t.width,y:(-i.y+1)*this.containerSize.height-t.height};case"left":return{x:i.x*this.containerSize.width,y:(-i.y+.5)*this.containerSize.height-t.height/2};case"right":return{x:(i.x+1)*this.containerSize.width-t.width,y:(-i.y+.5)*this.containerSize.height-t.height/2};case"top":return{x:(i.x+.5)*this.containerSize.width-t.width/2,y:-i.y*this.containerSize.height};case"bottom":return{x:(i.x+.5)*this.containerSize.width-t.width/2,y:(-i.y+1)*this.containerSize.height-t.height};case"center":default:return{x:(i.x+.5)*this.containerSize.width-t.width/2,y:(-i.y+.5)*this.containerSize.height-t.height/2}}}absoluteToRelative(t,e,i){switch(e){case"topLeft":return{x:i.x/this.containerSize.width,y:-(i.y/this.containerSize.height)};case"topRight":return{x:(i.x+t.width)/this.containerSize.width-1,y:-(i.y/this.containerSize.height)};case"bottomLeft":return{x:i.x/this.containerSize.width,y:-((i.y+t.height)/this.containerSize.height-1)};case"bottomRight":return{x:(i.x+t.width)/this.containerSize.width-1,y:-((i.y+t.height)/this.containerSize.height-1)};case"left":return{x:i.x/this.containerSize.width,y:-((i.y+t.height/2)/this.containerSize.height-.5)};case"right":return{x:(i.x+t.width)/this.containerSize.width-1,y:-((i.y+t.height/2)/this.containerSize.height-.5)};case"top":return{x:(i.x+t.width/2)/this.containerSize.width-.5,y:-(i.y/this.containerSize.height)};case"bottom":return{x:(i.x+t.width/2)/this.containerSize.width-.5,y:-((i.y+t.height)/this.containerSize.height-1)};case"center":default:return{x:(i.x+t.width/2)/this.containerSize.width-.5,y:-((i.y+t.height/2)/this.containerSize.height-.5)}}}}class ln{container;constructor(){this.container=new X.Container}getContainer(){return this.container}}var qt=(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))(qt||{});class je extends ln{static DiscardedFrameCount=0;layer;shouldDispose;playerType;edit;clipConfiguration;timingIntent;resolvedTiming;positionBuilder;offsetXKeyframeBuilder;offsetYKeyframeBuilder;scaleKeyframeBuilder;opacityKeyframeBuilder;rotationKeyframeBuilder;maskXKeyframeBuilder;wipeMask;contentContainer;mergeFieldBindings=new Map;constructor(t,e,i){super(),this.edit=t,this.layer=0,this.shouldDispose=!1,this.playerType=i,this.clipConfiguration=e,this.positionBuilder=new Ql(t.size),this.timingIntent={start:e.start,length:e.length},this.resolvedTiming={start:e.start,length:e.length},this.wipeMask=null,this.contentContainer=new X.Container,this.getContainer().addChild(this.contentContainer)}reconfigureAfterRestore(){this.configureKeyframes()}async reloadAsset(){}configureKeyframes(){const t=this.getLength(),e=this.clipConfiguration,i=typeof e.offset?.x=="number"?e.offset.x:0,a=typeof e.offset?.y=="number"?e.offset.y:0,n=typeof e.scale=="number"?e.scale:1,r=typeof e.opacity=="number"?e.opacity:1,o=typeof e.transform?.rotate?.angle=="number"?e.transform.rotate.angle:0;if(this.offsetXKeyframeBuilder=new ni(i,t,"additive"),this.offsetYKeyframeBuilder=new ni(a,t,"additive"),this.scaleKeyframeBuilder=new ni(n,t,"multiplicative"),this.opacityKeyframeBuilder=new ni(r,t,"multiplicative",{min:0,max:1}),this.rotationKeyframeBuilder=new ni(o,t,"additive"),this.clipHasKeyframes())return;const l={...e,start:this.getStart(),length:t},c=new P0(l).buildRelative(this.edit.size,this.getSize()),d=new F0(l).buildRelative();this.offsetXKeyframeBuilder.addLayer(c.offsetXKeyframes),this.offsetYKeyframeBuilder.addLayer(c.offsetYKeyframes),this.scaleKeyframeBuilder.addLayer(c.scaleKeyframes),this.opacityKeyframeBuilder.addLayer(c.opacityKeyframes),this.rotationKeyframeBuilder.addLayer(c.rotationKeyframes),this.offsetXKeyframeBuilder.addLayer(d.in.offsetXKeyframes),this.offsetYKeyframeBuilder.addLayer(d.in.offsetYKeyframes),this.scaleKeyframeBuilder.addLayer(d.in.scaleKeyframes),this.opacityKeyframeBuilder.addLayer(d.in.opacityKeyframes),this.rotationKeyframeBuilder.addLayer(d.in.rotationKeyframes),this.offsetXKeyframeBuilder.addLayer(d.out.offsetXKeyframes),this.offsetYKeyframeBuilder.addLayer(d.out.offsetYKeyframes),this.scaleKeyframeBuilder.addLayer(d.out.scaleKeyframes),this.opacityKeyframeBuilder.addLayer(d.out.opacityKeyframes),this.rotationKeyframeBuilder.addLayer(d.out.rotationKeyframes);const u=[...d.in.maskXKeyframes,...d.out.maskXKeyframes];u.length&&(this.maskXKeyframeBuilder=new ga(u,t))}async load(){this.contentContainer?.destroyed&&(this.contentContainer=new X.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(t,e){if(this.getContainer().visible=this.isActive(),this.getContainer().zIndex=1e5-this.layer*100,!this.isActive())return;const i=this.getPivot(),a=this.getPosition(),n=this.getContainerScale();this.getContainer().scale.set(n.x,n.y),this.getContainer().pivot.set(i.x,i.y),this.getContainer().position.set(a.x+i.x,a.y+i.y);const r=this.getRotation();this.contentContainer.alpha=this.getOpacity(),this.getContainer().angle=r,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 t=this.maskXKeyframeBuilder.getValue(this.getPlaybackTime()),e=this.getSize();this.wipeMask||(this.wipeMask=new X.Graphics,this.getContainer().addChild(this.wipeMask),this.getContainer().mask=this.wipeMask),this.wipeMask.clear(),this.wipeMask.rect(0,0,e.width*t,e.height),this.wipeMask.fill(16777215)}draw(){this.clipConfiguration.width&&this.clipConfiguration.height&&this.applyFixedDimensions()}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(){return{...this.timingIntent}}setTimingIntent(t){t.start!==void 0&&(this.timingIntent.start=t.start),t.length!==void 0&&(this.timingIntent.length=t.length)}getResolvedTiming(){return{...this.resolvedTiming}}setResolvedTiming(t){this.resolvedTiming={...t}}convertToFixedTiming(){this.timingIntent={start:this.resolvedTiming.start,length:this.resolvedTiming.length}}setMergeFieldBinding(t,e){this.mergeFieldBindings.set(t,e)}getMergeFieldBinding(t){return this.mergeFieldBindings.get(t)}removeMergeFieldBinding(t){this.mergeFieldBindings.delete(t)}getMergeFieldBindings(){return this.mergeFieldBindings}setInitialBindings(t){this.mergeFieldBindings=new Map(t)}getExportableClip(){const t=structuredClone(this.clipConfiguration);for(const[i,{placeholder:a,resolvedValue:n}]of this.mergeFieldBindings)Ei(t,i)===n&&Ur(t,i,a);const e=this.getTimingIntent();return t.start=e.start,t.length=e.length,t}getPlaybackTime(){const e=this.edit.playbackTime/1e3-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 t={x:this.offsetXKeyframeBuilder?.getValue(this.getPlaybackTime())??0,y:this.offsetYKeyframeBuilder?.getValue(this.getPlaybackTime())??0};return this.positionBuilder.relativeToAbsolute(this.getSize(),this.clipConfiguration.position??"center",t)}getPivot(){const t=this.getSize();return{x:t.width/2,y:t.height/2}}moveBy(t,e){const i=this.getPosition(),a={x:i.x+t,y:i.y+e},n=this.positionBuilder.absoluteToRelative(this.getSize(),this.clipConfiguration.position??"center",a);this.clipConfiguration.offset||(this.clipConfiguration.offset={x:0,y:0}),this.clipConfiguration.offset.x=n.x,this.clipConfiguration.offset.y=n.y,this.offsetXKeyframeBuilder=new ni(n.x,this.getLength(),"additive"),this.offsetYKeyframeBuilder=new ni(n.y,this.getLength(),"additive")}getFitScale(){const t={width:this.clipConfiguration.width??this.edit.size.width,height:this.clipConfiguration.height??this.edit.size.height},e=this.getContentSize(),i=this.clipConfiguration.fit??"crop";return M0(e,t,i)}getScale(){return(this.scaleKeyframeBuilder?.getValue(this.getPlaybackTime())??1)*this.getFitScale()}getContainerScale(){const t=this.scaleKeyframeBuilder?.getValue(this.getPlaybackTime())??1,e=this.getContentSize(),i=this.clipConfiguration.fit??"crop",a=!!(this.clipConfiguration.width&&this.clipConfiguration.height);return L0(e,this.edit.size,i,t,a)}getRotation(){return this.rotationKeyframeBuilder?.getValue(this.getPlaybackTime())??0}isActive(){const t=this.edit.playbackTime/1e3;return t>=this.getStart()&&t<this.getEnd()}shouldDiscardFrame(){return this.getPlaybackTime()<je.DiscardedFrameCount}onPointerDown(t){t.button===Kl.ButtonLeftClick&&this.edit.events.emit(_s.CanvasClipClicked,{player:this})}clipHasKeyframes(){return[this.clipConfiguration.scale,this.clipConfiguration.offset?.x,this.clipConfiguration.offset?.y,this.clipConfiguration.transform?.rotate?.angle].some(t=>t&&typeof t!="number")}applyFixedDimensions(){const t=this.clipConfiguration.width,e=this.clipConfiguration.height;if(!t||!e)return;const i=this.contentContainer.children.find(f=>f instanceof X.Sprite);if(!i?.texture)return;const a=i.texture.width,n=i.texture.height,r=this.clipConfiguration.fit||"crop";let o=this.contentContainer.mask;o||(o=new X.Graphics,this.contentContainer.addChild(o),this.contentContainer.mask=o),o.clear(),o.rect(0,0,t,e),o.fill(16777215);const l=this.scaleKeyframeBuilder?.getValue(this.getPlaybackTime())??1;i.anchor.set(.5,.5);const u=B0({width:a,height:n},{width:t,height:e},r);i.scale.set(u.scaleX,u.scaleY),i.position.set(u.positionX,u.positionY),this.contentContainer.scale.set(l,l),this.contentContainer.position.set(t/2*(1-l),e/2*(1-l))}applyAnchorPositioning(t,e,i,a){const n=a.width,r=a.height;if(!!a.mask){a.position.set(0,0);return}const l=(t??"center").toLowerCase();let c=0,d=0;l.includes("left")||l==="left"?c=0:l.includes("right")||l==="right"?c=e-n:c=(e-n)/2,l.includes("top")||l==="top"?d=0:l.includes("bottom")||l==="bottom"?d=i-r:d=(i-r)/2,a.position.set(c,d)}supportsEdgeResize(){return!1}onDimensionsChanged(){}notifyDimensionsChanged(){this.onDimensionsChanged()}}class Jl extends je{audioResource;isPlaying;volumeKeyframeBuilder;syncTimer;constructor(t,e){super(t,e,qt.Audio),this.audioResource=null,this.isPlaying=!1,this.syncTimer=0}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.src,i={src:e,parser:ma.Name},a=await this.edit.assetLoader.load(e,i);if(!(a instanceof I0.Howl))throw new Error(`Invalid audio source '${t.src}'.`);this.audioResource=a;const r=typeof t.volume=="number"?t.volume:1;this.volumeKeyframeBuilder=new ga(this.createVolumeKeyframes(t,r),this.getLength(),r),this.configureKeyframes()}update(t,e){super.update(t,e);const{trim:i=0}=this.clipConfiguration.asset;if(this.syncTimer+=e,this.getContainer().alpha=0,!this.audioResource)return;const a=this.edit.isPlaying&&this.isActive(),n=this.getPlaybackTime();a&&(this.isPlaying||(this.isPlaying=!0,this.audioResource.seek(n+i),this.audioResource.play()),this.audioResource.volume()!==this.getVolume()&&this.audioResource.volume(this.getVolume()),Math.abs(this.audioResource.seek()-i-n)>.1&&(this.audioResource.seek(n+i),this.edit.recordSyncCorrection())),this.isPlaying&&!a&&(this.isPlaying=!1,this.audioResource.pause());const r=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&r&&(this.syncTimer=0,this.audioResource.seek(n+i))}draw(){super.draw()}dispose(){this.audioResource?.unload(),this.audioResource=null}reconfigureAfterRestore(){super.reconfigureAfterRestore();const t=this.clipConfiguration.asset,e=typeof t.volume=="number"?t.volume:1;this.volumeKeyframeBuilder=new ga(this.createVolumeKeyframes(t,e),this.getLength(),e)}getSize(){return{width:0,height:0}}getVolume(){return this.volumeKeyframeBuilder.getValue(this.getPlaybackTime())}getCurrentDrift(){if(!this.audioResource)return 0;const{trim:t=0}=this.clipConfiguration.asset,e=this.audioResource.seek(),i=this.getPlaybackTime();return Math.abs(e-t-i)}createVolumeKeyframes(t,e){const{effect:i,volume:a}=t;if(!i||i==="none"||Array.isArray(a))return a??1;const n=this.getLength()/1e3,r=Math.min(2,n/2);return i==="fadeIn"?[{from:0,to:e,start:0,length:r}]:i==="fadeOut"?[{from:e,to:0,start:n-r,length:r}]:[{from:0,to:e,start:0,length:r},{from:e,to:0,start:n-r,length:r}]}}function cn(s){const t=s.trim().replace(",","."),e=t.split(":");if(e.length===3){const i=parseInt(e[0],10),a=parseInt(e[1],10),n=parseFloat(e[2]);return i*3600+a*60+n}if(e.length===2){const i=parseInt(e[0],10),a=parseFloat(e[1]);return i*60+a}return parseFloat(t)||0}function _0(s){const t=[],e=s.split(/\r?\n/);let i=0;for(;i<e.length&&!e[i].includes("-->");)i+=1;for(;i<e.length;){const a=e[i].trim();if(a.includes("-->")){const[n,r]=a.split("-->").map(d=>d.trim().split(" ")[0]),o=cn(n),l=cn(r),c=[];for(i+=1;i<e.length&&e[i].trim()!==""&&!e[i].includes("-->");){const d=e[i].trim();d.startsWith("NOTE")||c.push(d),i+=1}c.length>0&&t.push({start:o,end:l,text:c.join(`
2
2
  `)})}else i+=1}return t}function R0(s){const t=[],e=s.split(/\r?\n/);let i=0;for(;i<e.length;){const a=e[i].trim();if(/^\d+$/.test(a)||a==="")i+=1;else if(a.includes("-->")){const[n,r]=a.split("-->").map(d=>d.trim()),o=cn(n),l=cn(r),c=[];for(i+=1;i<e.length&&e[i].trim()!=="";)c.push(e[i].trim()),i+=1;c.length>0&&t.push({start:o,end:l,text:c.join(`
3
3
  `)})}else i+=1}return t}function z0(s){return s.trim().startsWith("WEBVTT")?_0(s):R0(s)}function D0(s,t){return s.find(e=>t>=e.start&&t<=e.end)??null}const U0=`
4
4
  let transcriber = null;
@@ -230,7 +230,7 @@ fn outlineMaxAlphaAtPos(uv: vec2<f32>) -> f32 {
230
230
  return maxAlpha;
231
231
  }
232
232
 
233
- const DOUBLE_PI: f32 = 3.14159265358979323846264 * 2.;`,tp=Object.defineProperty,ep=(s,t,e)=>t in s?tp(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,ri=(s,t,e)=>(ep(s,typeof t!="symbol"?t+"":t,e),e);const un=class Ai extends ts.Filter{constructor(...t){let e=t[0]??{};typeof e=="number"&&(ts.deprecation("6.0.0","OutlineFilter constructor params are now options object. See params: { thickness, color, quality, alpha, knockout }"),e={thickness:e},t[1]!==void 0&&(e.color=t[1]),t[2]!==void 0&&(e.quality=t[2]),t[3]!==void 0&&(e.alpha=t[3]),t[4]!==void 0&&(e.knockout=t[4])),e={...Ai.DEFAULT_OPTIONS,...e};const i=e.quality??.1,a=ts.GpuProgram.from({vertex:{source:Q0,entryPoint:"mainVertex"},fragment:{source:$0,entryPoint:"mainFragment"}}),n=ts.GlProgram.from({vertex:K0,fragment:J0.replace(/\$\{ANGLE_STEP\}/,Ai.getAngleStep(i).toFixed(7)),name:"outline-filter"});super({gpuProgram:a,glProgram:n,resources:{outlineUniforms:{uThickness:{value:new Float32Array(2),type:"vec2<f32>"},uColor:{value:new Float32Array(3),type:"vec3<f32>"},uAlpha:{value:e.alpha,type:"f32"},uAngleStep:{value:0,type:"f32"},uKnockout:{value:e.knockout?1:0,type:"f32"}}}}),ri(this,"uniforms"),ri(this,"_thickness"),ri(this,"_quality"),ri(this,"_color"),this.uniforms=this.resources.outlineUniforms.uniforms,this.uniforms.uAngleStep=Ai.getAngleStep(i),this._color=new ts.Color,this.color=e.color??0,Object.assign(this,e)}apply(t,e,i,a){this.uniforms.uThickness[0]=this.thickness/e.source.width,this.uniforms.uThickness[1]=this.thickness/e.source.height,t.applyFilter(this,e,i,a)}static getAngleStep(t){return parseFloat((Math.PI*2/Math.max(t*Ai.MAX_SAMPLES,Ai.MIN_SAMPLES)).toFixed(7))}get thickness(){return this._thickness}set thickness(t){this._thickness=this.padding=t}get color(){return this._color.value}set color(t){this._color.setValue(t);const[e,i,a]=this._color.toArray();this.uniforms.uColor[0]=e,this.uniforms.uColor[1]=i,this.uniforms.uColor[2]=a}get alpha(){return this.uniforms.uAlpha}set alpha(t){this.uniforms.uAlpha=t}get quality(){return this._quality}set quality(t){this._quality=t,this.uniforms.uAngleStep=Ai.getAngleStep(t)}get knockout(){return this.uniforms.uKnockout===1}set knockout(t){this.uniforms.uKnockout=t?1:0}};ri(un,"DEFAULT_OPTIONS",{thickness:1,color:0,alpha:1,quality:.1,knockout:!1}),ri(un,"MIN_SAMPLES",1),ri(un,"MAX_SAMPLES",100);let ba=un;class hn extends je{static loadedFonts=new Set;cues=[];currentCue=null;background=null;text=null;vttBlobUrl=null;pendingTranscription=null;isTranscribing=!1;constructor(t,e){super(t,e,qt.Caption)}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.font?.family??"Open Sans";if(await this.loadFont(e),W0(t.src)?(this.isTranscribing=!0,this.pendingTranscription=this.loadTranscriptionInBackground(t.src)):await this.loadSubtitles(t.src),this.background=new X.Graphics,this.contentContainer.addChild(this.background),this.text=new X.Text({text:"",style:this.createTextStyle(t)}),this.text.visible=!1,t.stroke?.width&&t.stroke.width>0&&t.stroke.color){const i=new ba({thickness:t.stroke.width,color:t.stroke.color});this.text.filters=[i]}this.contentContainer.addChild(this.text),this.configureKeyframes()}async loadTranscriptionInBackground(t){const e=this.clipConfiguration.alias??"";try{const i=this.edit.getOriginalEdit();if(!i)throw new Error("Cannot resolve alias: edit not loaded");const a=await Y0(t,i,o=>{this.edit.events.emit(j.TranscriptionProgress,{clipAlias:e,...o})});this.vttBlobUrl=a.vttUrl;const n={src:a.vttUrl,parser:Pi.Name},r=await this.edit.assetLoader.load(a.vttUrl,n);r&&(this.cues=r.cues),this.isTranscribing=!1,this.edit.events.emit(j.TranscriptionCompleted,{clipAlias:e,cueCount:this.cues.length})}catch(i){this.isTranscribing=!1,console.error("Failed to transcribe:",i),this.edit.events.emit(j.TranscriptionFailed,{clipAlias:e,error:i instanceof Error?i.message:"Transcription failed"})}}isTranscriptionPending(){return this.isTranscribing}async waitForTranscription(){this.pendingTranscription&&await this.pendingTranscription}update(t,e){if(super.update(t,e),!this.text)return;const i=this.clipConfiguration.asset,a=i.trim??0,n=this.getPlaybackTime()+a,r=D0(this.cues,n);r!==this.currentCue&&(this.currentCue=r,this.updateDisplay(r,i))}dispose(){super.dispose(),this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null,this.vttBlobUrl&&(Z0(this.vttBlobUrl),this.vttBlobUrl=null),this.cues=[],this.currentCue=null}getSize(){const t=this.clipConfiguration.asset;return{width:this.clipConfiguration.width??t.width??this.edit.size.width,height:this.clipConfiguration.height??t.height??this.edit.size.height}}getFitScale(){return 1}getContainerScale(){const t=this.getScale();return{x:t,y:t}}async loadSubtitles(t){try{const e={src:t,parser:Pi.Name},i=await this.edit.assetLoader.load(t,e);i?this.cues=i.cues:(console.error("Failed to load subtitles"),this.cues=[])}catch(e){console.error("Failed to load subtitles:",e),this.cues=[]}}createTextStyle(t){const e=t.font?.family??"Open Sans",{baseFontFamily:i,fontWeight:a}=Rs(e),n=t.font?.size??32,{width:r}=this.getSize();return new X.TextStyle({fontFamily:i,fontSize:n,fill:t.font?.color??"#ffffff",fontWeight:a.toString(),wordWrap:!0,wordWrapWidth:r*.9,lineHeight:(t.font?.lineHeight??1.2)*n,align:t.alignment?.horizontal??"center"})}updateDisplay(t,e){if(!(!this.text||!this.background)){if(!t){this.text.visible=!1,this.background.clear();return}this.text.text=t.text,this.text.visible=!0,this.positionText(e),this.drawBackground(e)}}positionText(t){if(!this.text)return;const e=t.alignment?.horizontal??"center",i=t.alignment?.vertical??"bottom",{width:a,height:n}=this.getSize(),r=t.background?.padding??10;let o=a/2-this.text.width/2;e==="left"?o=r:e==="right"&&(o=a-this.text.width-r);let l=n*.9;i==="top"?l=r:i==="center"&&(l=n/2-this.text.height/2),this.text.position.set(o,l)}drawBackground(t){if(!this.background||!this.text||!this.text.visible){this.background?.clear();return}const e=t.background;if(!e?.color){this.background.clear();return}const i=e.padding??10,a=e.borderRadius??4,n=this.text.x-i,r=this.text.y-i,o=this.text.width+i*2,l=this.text.height+i*2;this.background.clear(),this.background.fillStyle={color:e.color,alpha:e.opacity??.8},a>0?this.background.roundRect(n,r,o,l,a):this.background.rect(n,r,o,l),this.background.fill()}async loadFont(t){const{baseFontFamily:e,fontWeight:i}=Rs(t),a=`${e}-${i}`;if(hn.loadedFonts.has(a))return;const n=Wr(t);if(n){const r=new FontFace(e,`url(${n})`,{weight:i.toString()});await r.load(),document.fonts.add(r),hn.loadedFonts.add(a)}}}class sp extends je{background;text;constructor(t,e){super(t,e,qt.Html),this.background=null,this.text=null}async load(){await super.load();const t=this.clipConfiguration.asset,e=await this.parseDocument();if(!e)return;const i=new X.Graphics;e.background.color&&(i.fillStyle={color:e.background.color,alpha:e.background.opacity??1},i.rect(0,0,t.width??this.edit.size.width,t.height??this.edit.size.height),i.fill());const a=new X.Text;a.text=e.text;const{horizontal:n,vertical:r}=e.alignment;a.style={fontFamily:e.font?.family??"Open Sans",fontSize:e.font?.size??32,fill:e.font?.color??"#ffffff",fontWeight:(e.font?.weight??"400").toString(),wordWrap:!0,wordWrapWidth:t.width??this.edit.size.width,lineHeight:(e.font?.lineHeight??1)*(e.font?.size??32),align:n};let o=(t.width??this.edit.size.width)/2-a.width/2,l=(t.height??this.edit.size.height)/2-a.height/2;if(n==="left"&&(o=0),n==="right"&&(o=(t.width??this.edit.size.width)-a.width),r==="top"&&(l=0),r==="bottom"&&(l=(t.height??this.edit.size.height)-a.height),a.position={x:o,y:l},e.stroke.color&&e.stroke.width){const c=new ba({thickness:e.stroke.width,color:e.stroke.color});a.filters=[c]}this.background=i,this.text=a,this.contentContainer.addChild(i),this.contentContainer.addChild(a),this.configureKeyframes()}update(t,e){super.update(t,e)}draw(){super.draw()}dispose(){super.dispose(),this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null}getSize(){const t=this.clipConfiguration.asset;return{width:t.width??this.edit.size.width,height:t.height??this.edit.size.height}}getFitScale(){return 1}async parseDocument(){const t=this.clipConfiguration.asset,{html:e,css:i="",position:a}=t;if(!e.includes('data-html-type="text"'))return console.warn("Unsupported html format."),null;const r=new DOMParser().parseFromString(e,"text/html").body.textContent??"",l=(await new CSSStyleSheet().replace(i)).cssRules[0],c={text:r,font:{},alignment:{},background:{},stroke:{}};if(l?.constructor.name!=="CSSStyleRule"||!("style"in l))return console.warn("Unsupported css format."),c;const d=l.style,u=this.parseAlignment(a??"center");c.font={color:d.color.length?d.color:void 0,family:d.fontFamily.length?d.fontFamily:void 0,size:d.fontSize.length?parseInt(d.fontSize,10):void 0,weight:d.fontWeight.length?parseInt(d.fontWeight,10):void 0,lineHeight:d.lineHeight.length?parseInt(d.lineHeight,10):void 0},c.alignment=u;let f="";return d.background.length&&(f=d.background),d.backgroundColor.length&&(f=d.backgroundColor),c.background={color:f.length?f:void 0,opacity:d.opacity.length?parseInt(d.opacity,10):void 0},c.stroke={width:d.strokeWidth.length?parseInt(d.strokeWidth,10):void 0,color:d.stroke.length?d.stroke:void 0},c}parseAlignment(t){switch(t){case"topLeft":return{horizontal:"left",vertical:"top"};case"top":return{horizontal:"center",vertical:"top"};case"topRight":return{horizontal:"right",vertical:"top"};case"left":return{horizontal:"left",vertical:"center"};case"right":return{horizontal:"right",vertical:"center"};case"bottomLeft":return{horizontal:"left",vertical:"bottom"};case"bottom":return{horizontal:"center",vertical:"bottom"};case"bottomRight":return{horizontal:"right",vertical:"bottom"};case"center":default:return{horizontal:"center",vertical:"center"}}}}class ip extends je{texture;sprite;constructor(t,e){super(t,e,qt.Image),this.texture=null,this.sprite=null}async load(){await super.load(),await this.loadTexture(),this.configureKeyframes()}update(t,e){super.update(t,e)}draw(){super.draw()}dispose(){super.dispose(),this.disposeTexture()}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}}getContentSize(){return{width:this.sprite?.width??0,height:this.sprite?.height??0}}async reloadAsset(){this.disposeTexture(),await this.loadTexture()}async loadTexture(){const t=this.clipConfiguration.asset,{src:e}=t,i={src:e,crossorigin:"anonymous",data:{}},a=await this.edit.assetLoader.load(e,i);if(!(a?.source instanceof X.ImageSource))throw a&&a.destroy(!0),new Error(`Invalid image source '${e}'.`);this.texture=this.createCroppedTexture(a),this.sprite=new X.Sprite(this.texture),this.contentContainer.addChild(this.sprite),this.clipConfiguration.width&&this.clipConfiguration.height&&this.applyFixedDimensions()}disposeTexture(){this.sprite&&(this.contentContainer.removeChild(this.sprite),this.sprite.destroy(),this.sprite=null),this.texture=null}supportsEdgeResize(){return!0}createCroppedTexture(t){const e=this.clipConfiguration.asset;if(!e.crop)return t;const i=t.width,a=t.height,n=Math.floor((e.crop?.left??0)*i),r=Math.floor((e.crop?.right??0)*i),o=Math.floor((e.crop?.top??0)*a),l=Math.floor((e.crop?.bottom??0)*a),c=n,d=o,u=i-n-r,f=a-o-l,p=new X.Rectangle(c,d,u,f);return new X.Texture({source:t.source,frame:p})}}class ap extends je{texture;sprite;isPlaying;constructor(t,e){super(t,e,qt.Luma),this.texture=null,this.sprite=null,this.isPlaying=!1}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.src,i={src:e,data:{autoPlay:!1,muted:!0}},a=await this.edit.assetLoader.load(e,i);if(!(a?.source instanceof X.ImageSource||a?.source instanceof X.VideoSource))throw a&&this.edit.assetLoader.decrementRef(e),new Error(`Invalid luma source '${t.src}'.`);a.source instanceof X.VideoSource&&(a.source.alphaMode="no-premultiply-alpha"),this.texture=a,this.sprite=new X.Sprite(this.texture),this.contentContainer.addChild(this.sprite),this.configureKeyframes()}update(t,e){if(super.update(t,e),!this.texture||!(this.texture.source instanceof X.VideoSource))return;const i=this.getPlaybackTime(),a=this.edit.isPlaying&&this.isActive();a&&(this.isPlaying||(this.isPlaying=!0,this.texture.source.resource.currentTime=i,this.texture.source.resource.play().catch(console.error)),this.texture.source.resource.volume!==this.getVolume()&&(this.texture.source.resource.volume=this.getVolume()),Math.abs(this.texture.source.resource.currentTime-i)>.1&&(this.texture.source.resource.currentTime=i)),!a&&this.isPlaying&&(this.isPlaying=!1,this.texture.source.resource.pause()),!this.edit.isPlaying&&this.isActive()&&(this.texture.source.resource.currentTime=i)}draw(){super.draw()}dispose(){super.dispose(),this.sprite?.destroy(),this.sprite=null,this.texture=null}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}}getVolume(){return 0}getSprite(){return this.sprite}isVideoSource(){return this.texture?.source instanceof X.VideoSource}getVideoCurrentTime(){return this.texture?.source instanceof X.VideoSource?this.texture.source.resource.currentTime:-1}}function z(s,t,e){function i(o,l){if(o._zod||Object.defineProperty(o,"_zod",{value:{def:l,constr:r,traits:new Set},enumerable:!1}),o._zod.traits.has(s))return;o._zod.traits.add(s),t(o,l);const c=r.prototype,d=Object.keys(c);for(let u=0;u<d.length;u++){const f=d[u];f in o||(o[f]=c[f].bind(o))}}const a=e?.Parent??Object;class n extends a{}Object.defineProperty(n,"name",{value:s});function r(o){var l;const c=e?.Parent?new n:this;i(c,o),(l=c._zod).deferred??(l.deferred=[]);for(const d of c._zod.deferred)d();return c}return Object.defineProperty(r,"init",{value:i}),Object.defineProperty(r,Symbol.hasInstance,{value:o=>e?.Parent&&o instanceof e.Parent?!0:o?._zod?.traits?.has(s)}),Object.defineProperty(r,"name",{value:s}),r}class Fi extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class ec extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const sc={};function zs(s){return sc}function ic(s){const t=Object.values(s).filter(i=>typeof i=="number");return Object.entries(s).filter(([i,a])=>t.indexOf(+i)===-1).map(([i,a])=>a)}function Hr(s,t){return typeof t=="bigint"?t.toString():t}function fn(s){return{get value(){{const t=s();return Object.defineProperty(this,"value",{value:t}),t}}}}function Gr(s){return s==null}function jr(s){const t=s.startsWith("^")?1:0,e=s.endsWith("$")?s.length-1:s.length;return s.slice(t,e)}function np(s,t){const e=(s.toString().split(".")[1]||"").length,i=t.toString();let a=(i.split(".")[1]||"").length;if(a===0&&/\d?e-\d?/.test(i)){const l=i.match(/\d?e-(\d?)/);l?.[1]&&(a=Number.parseInt(l[1]))}const n=e>a?e:a,r=Number.parseInt(s.toFixed(n).replace(".","")),o=Number.parseInt(t.toFixed(n).replace(".",""));return r%o/10**n}const ac=Symbol("evaluating");function Xt(s,t,e){let i;Object.defineProperty(s,t,{get(){if(i!==ac)return i===void 0&&(i=ac,i=e()),i},set(a){Object.defineProperty(s,t,{value:a})},configurable:!0})}function oi(s,t,e){Object.defineProperty(s,t,{value:e,writable:!0,enumerable:!0,configurable:!0})}function li(...s){const t={};for(const e of s){const i=Object.getOwnPropertyDescriptors(e);Object.assign(t,i)}return Object.defineProperties({},t)}function nc(s){return JSON.stringify(s)}function rp(s){return s.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const rc="captureStackTrace"in Error?Error.captureStackTrace:(...s)=>{};function wa(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}const op=fn(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const s=Function;return new s(""),!0}catch{return!1}});function Mi(s){if(wa(s)===!1)return!1;const t=s.constructor;if(t===void 0||typeof t!="function")return!0;const e=t.prototype;return!(wa(e)===!1||Object.prototype.hasOwnProperty.call(e,"isPrototypeOf")===!1)}function oc(s){return Mi(s)?{...s}:Array.isArray(s)?[...s]:s}const lp=new Set(["string","number","symbol"]);function Li(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ds(s,t,e){const i=new s._zod.constr(t??s._zod.def);return(!t||e?.parent)&&(i._zod.parent=s),i}function dt(s){const t=s;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function cp(s){return Object.keys(s).filter(t=>s[t]._zod.optin==="optional"&&s[t]._zod.optout==="optional")}const dp={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function up(s,t){const e=s._zod.def,i=li(s._zod.def,{get shape(){const a={};for(const n in t){if(!(n in e.shape))throw new Error(`Unrecognized key: "${n}"`);t[n]&&(a[n]=e.shape[n])}return oi(this,"shape",a),a},checks:[]});return Ds(s,i)}function hp(s,t){const e=s._zod.def,i=li(s._zod.def,{get shape(){const a={...s._zod.def.shape};for(const n in t){if(!(n in e.shape))throw new Error(`Unrecognized key: "${n}"`);t[n]&&delete a[n]}return oi(this,"shape",a),a},checks:[]});return Ds(s,i)}function fp(s,t){if(!Mi(t))throw new Error("Invalid input to extend: expected a plain object");const e=s._zod.def.checks;if(e&&e.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");const a=li(s._zod.def,{get shape(){const n={...s._zod.def.shape,...t};return oi(this,"shape",n),n},checks:[]});return Ds(s,a)}function pp(s,t){if(!Mi(t))throw new Error("Invalid input to safeExtend: expected a plain object");const e={...s._zod.def,get shape(){const i={...s._zod.def.shape,...t};return oi(this,"shape",i),i},checks:s._zod.def.checks};return Ds(s,e)}function gp(s,t){const e=li(s._zod.def,{get shape(){const i={...s._zod.def.shape,...t._zod.def.shape};return oi(this,"shape",i),i},get catchall(){return t._zod.def.catchall},checks:[]});return Ds(s,e)}function mp(s,t,e){const i=li(t._zod.def,{get shape(){const a=t._zod.def.shape,n={...a};if(e)for(const r in e){if(!(r in a))throw new Error(`Unrecognized key: "${r}"`);e[r]&&(n[r]=s?new s({type:"optional",innerType:a[r]}):a[r])}else for(const r in a)n[r]=s?new s({type:"optional",innerType:a[r]}):a[r];return oi(this,"shape",n),n},checks:[]});return Ds(t,i)}function yp(s,t,e){const i=li(t._zod.def,{get shape(){const a=t._zod.def.shape,n={...a};if(e)for(const r in e){if(!(r in n))throw new Error(`Unrecognized key: "${r}"`);e[r]&&(n[r]=new s({type:"nonoptional",innerType:a[r]}))}else for(const r in a)n[r]=new s({type:"nonoptional",innerType:a[r]});return oi(this,"shape",n),n},checks:[]});return Ds(t,i)}function Bi(s,t=0){if(s.aborted===!0)return!0;for(let e=t;e<s.issues.length;e++)if(s.issues[e]?.continue!==!0)return!0;return!1}function Oi(s,t){return t.map(e=>{var i;return(i=e).path??(i.path=[]),e.path.unshift(s),e})}function pn(s){return typeof s=="string"?s:s?.message}function Us(s,t,e){const i={...s,path:s.path??[]};if(!s.message){const a=pn(s.inst?._zod.def?.error?.(s))??pn(t?.error?.(s))??pn(e.customError?.(s))??pn(e.localeError?.(s))??"Invalid input";i.message=a}return delete i.inst,delete i.continue,t?.reportInput||delete i.input,i}function Yr(s){return Array.isArray(s)?"array":typeof s=="string"?"string":"unknown"}function va(...s){const[t,e,i]=s;return typeof t=="string"?{message:t,code:"custom",input:e,inst:i}:{...t}}const lc=(s,t)=>{s.name="$ZodError",Object.defineProperty(s,"_zod",{value:s._zod,enumerable:!1}),Object.defineProperty(s,"issues",{value:t,enumerable:!1}),s.message=JSON.stringify(t,Hr,2),Object.defineProperty(s,"toString",{value:()=>s.message,enumerable:!1})},cc=z("$ZodError",lc),dc=z("$ZodError",lc,{Parent:Error});function bp(s,t=e=>e.message){const e={},i=[];for(const a of s.issues)a.path.length>0?(e[a.path[0]]=e[a.path[0]]||[],e[a.path[0]].push(t(a))):i.push(t(a));return{formErrors:i,fieldErrors:e}}function wp(s,t=e=>e.message){const e={_errors:[]},i=a=>{for(const n of a.issues)if(n.code==="invalid_union"&&n.errors.length)n.errors.map(r=>i({issues:r}));else if(n.code==="invalid_key")i({issues:n.issues});else if(n.code==="invalid_element")i({issues:n.issues});else if(n.path.length===0)e._errors.push(t(n));else{let r=e,o=0;for(;o<n.path.length;){const l=n.path[o];o===n.path.length-1?(r[l]=r[l]||{_errors:[]},r[l]._errors.push(t(n))):r[l]=r[l]||{_errors:[]},r=r[l],o++}}};return i(s),e}const Zr=s=>(t,e,i,a)=>{const n=i?Object.assign(i,{async:!1}):{async:!1},r=t._zod.run({value:e,issues:[]},n);if(r instanceof Promise)throw new Fi;if(r.issues.length){const o=new(a?.Err??s)(r.issues.map(l=>Us(l,n,zs())));throw rc(o,a?.callee),o}return r.value},qr=s=>async(t,e,i,a)=>{const n=i?Object.assign(i,{async:!0}):{async:!0};let r=t._zod.run({value:e,issues:[]},n);if(r instanceof Promise&&(r=await r),r.issues.length){const o=new(a?.Err??s)(r.issues.map(l=>Us(l,n,zs())));throw rc(o,a?.callee),o}return r.value},gn=s=>(t,e,i)=>{const a=i?{...i,async:!1}:{async:!1},n=t._zod.run({value:e,issues:[]},a);if(n instanceof Promise)throw new Fi;return n.issues.length?{success:!1,error:new(s??cc)(n.issues.map(r=>Us(r,a,zs())))}:{success:!0,data:n.value}},vp=gn(dc),mn=s=>async(t,e,i)=>{const a=i?Object.assign(i,{async:!0}):{async:!0};let n=t._zod.run({value:e,issues:[]},a);return n instanceof Promise&&(n=await n),n.issues.length?{success:!1,error:new s(n.issues.map(r=>Us(r,a,zs())))}:{success:!0,data:n.value}},xp=mn(dc),Cp=s=>(t,e,i)=>{const a=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return Zr(s)(t,e,a)},kp=s=>(t,e,i)=>Zr(s)(t,e,i),Sp=s=>async(t,e,i)=>{const a=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return qr(s)(t,e,a)},Np=s=>async(t,e,i)=>qr(s)(t,e,i),Tp=s=>(t,e,i)=>{const a=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return gn(s)(t,e,a)},Ip=s=>(t,e,i)=>gn(s)(t,e,i),Ap=s=>async(t,e,i)=>{const a=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return mn(s)(t,e,a)},Ep=s=>async(t,e,i)=>mn(s)(t,e,i),Pp=/^[cC][^\s-]{8,}$/,Fp=/^[0-9a-z]+$/,Mp=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Lp=/^[0-9a-vA-V]{20}$/,Bp=/^[A-Za-z0-9]{27}$/,Op=/^[a-zA-Z0-9_-]{21}$/,_p=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Rp=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uc=s=>s?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${s}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,zp=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Dp="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Up(){return new RegExp(Dp,"u")}const Vp=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Wp=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Hp=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Gp=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,jp=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,hc=/^[A-Za-z0-9_-]*$/,Yp=/^\+(?:[0-9]){6,14}[0-9]$/,fc="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Zp=new RegExp(`^${fc}$`);function pc(s){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof s.precision=="number"?s.precision===-1?`${t}`:s.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${s.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function qp(s){return new RegExp(`^${pc(s)}$`)}function Xp(s){const t=pc({precision:s.precision}),e=["Z"];s.local&&e.push(""),s.offset&&e.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const i=`${t}(?:${e.join("|")})`;return new RegExp(`^${fc}T(?:${i})$`)}const Kp=s=>{const t=s?`[\\s\\S]{${s?.minimum??0},${s?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Qp=/^-?\d+$/,Jp=/^-?\d+(?:\.\d+)?/,$p=/^(?:true|false)$/i,tg=/^null$/i,eg=/^[^A-Z]*$/,sg=/^[^a-z]*$/,Le=z("$ZodCheck",(s,t)=>{var e;s._zod??(s._zod={}),s._zod.def=t,(e=s._zod).onattach??(e.onattach=[])}),gc={number:"number",bigint:"bigint",object:"date"},mc=z("$ZodCheckLessThan",(s,t)=>{Le.init(s,t);const e=gc[typeof t.value];s._zod.onattach.push(i=>{const a=i._zod.bag,n=(t.inclusive?a.maximum:a.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<n&&(t.inclusive?a.maximum=t.value:a.exclusiveMaximum=t.value)}),s._zod.check=i=>{(t.inclusive?i.value<=t.value:i.value<t.value)||i.issues.push({origin:e,code:"too_big",maximum:t.value,input:i.value,inclusive:t.inclusive,inst:s,continue:!t.abort})}}),yc=z("$ZodCheckGreaterThan",(s,t)=>{Le.init(s,t);const e=gc[typeof t.value];s._zod.onattach.push(i=>{const a=i._zod.bag,n=(t.inclusive?a.minimum:a.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>n&&(t.inclusive?a.minimum=t.value:a.exclusiveMinimum=t.value)}),s._zod.check=i=>{(t.inclusive?i.value>=t.value:i.value>t.value)||i.issues.push({origin:e,code:"too_small",minimum:t.value,input:i.value,inclusive:t.inclusive,inst:s,continue:!t.abort})}}),ig=z("$ZodCheckMultipleOf",(s,t)=>{Le.init(s,t),s._zod.onattach.push(e=>{var i;(i=e._zod.bag).multipleOf??(i.multipleOf=t.value)}),s._zod.check=e=>{if(typeof e.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof e.value=="bigint"?e.value%t.value===BigInt(0):np(e.value,t.value)===0)||e.issues.push({origin:typeof e.value,code:"not_multiple_of",divisor:t.value,input:e.value,inst:s,continue:!t.abort})}}),ag=z("$ZodCheckNumberFormat",(s,t)=>{Le.init(s,t),t.format=t.format||"float64";const e=t.format?.includes("int"),i=e?"int":"number",[a,n]=dp[t.format];s._zod.onattach.push(r=>{const o=r._zod.bag;o.format=t.format,o.minimum=a,o.maximum=n,e&&(o.pattern=Qp)}),s._zod.check=r=>{const o=r.value;if(e){if(!Number.isInteger(o)){r.issues.push({expected:i,format:t.format,code:"invalid_type",continue:!1,input:o,inst:s});return}if(!Number.isSafeInteger(o)){o>0?r.issues.push({input:o,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:s,origin:i,continue:!t.abort}):r.issues.push({input:o,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:s,origin:i,continue:!t.abort});return}}o<a&&r.issues.push({origin:"number",input:o,code:"too_small",minimum:a,inclusive:!0,inst:s,continue:!t.abort}),o>n&&r.issues.push({origin:"number",input:o,code:"too_big",maximum:n,inst:s})}}),ng=z("$ZodCheckMaxLength",(s,t)=>{var e;Le.init(s,t),(e=s._zod.def).when??(e.when=i=>{const a=i.value;return!Gr(a)&&a.length!==void 0}),s._zod.onattach.push(i=>{const a=i._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<a&&(i._zod.bag.maximum=t.maximum)}),s._zod.check=i=>{const a=i.value;if(a.length<=t.maximum)return;const r=Yr(a);i.issues.push({origin:r,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),rg=z("$ZodCheckMinLength",(s,t)=>{var e;Le.init(s,t),(e=s._zod.def).when??(e.when=i=>{const a=i.value;return!Gr(a)&&a.length!==void 0}),s._zod.onattach.push(i=>{const a=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>a&&(i._zod.bag.minimum=t.minimum)}),s._zod.check=i=>{const a=i.value;if(a.length>=t.minimum)return;const r=Yr(a);i.issues.push({origin:r,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),og=z("$ZodCheckLengthEquals",(s,t)=>{var e;Le.init(s,t),(e=s._zod.def).when??(e.when=i=>{const a=i.value;return!Gr(a)&&a.length!==void 0}),s._zod.onattach.push(i=>{const a=i._zod.bag;a.minimum=t.length,a.maximum=t.length,a.length=t.length}),s._zod.check=i=>{const a=i.value,n=a.length;if(n===t.length)return;const r=Yr(a),o=n>t.length;i.issues.push({origin:r,...o?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:i.value,inst:s,continue:!t.abort})}}),yn=z("$ZodCheckStringFormat",(s,t)=>{var e,i;Le.init(s,t),s._zod.onattach.push(a=>{const n=a._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=new Set),n.patterns.add(t.pattern))}),t.pattern?(e=s._zod).check??(e.check=a=>{t.pattern.lastIndex=0,!t.pattern.test(a.value)&&a.issues.push({origin:"string",code:"invalid_format",format:t.format,input:a.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:s,continue:!t.abort})}):(i=s._zod).check??(i.check=()=>{})}),lg=z("$ZodCheckRegex",(s,t)=>{yn.init(s,t),s._zod.check=e=>{t.pattern.lastIndex=0,!t.pattern.test(e.value)&&e.issues.push({origin:"string",code:"invalid_format",format:"regex",input:e.value,pattern:t.pattern.toString(),inst:s,continue:!t.abort})}}),cg=z("$ZodCheckLowerCase",(s,t)=>{t.pattern??(t.pattern=eg),yn.init(s,t)}),dg=z("$ZodCheckUpperCase",(s,t)=>{t.pattern??(t.pattern=sg),yn.init(s,t)}),ug=z("$ZodCheckIncludes",(s,t)=>{Le.init(s,t);const e=Li(t.includes),i=new RegExp(typeof t.position=="number"?`^.{${t.position}}${e}`:e);t.pattern=i,s._zod.onattach.push(a=>{const n=a._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(i)}),s._zod.check=a=>{a.value.includes(t.includes,t.position)||a.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:a.value,inst:s,continue:!t.abort})}}),hg=z("$ZodCheckStartsWith",(s,t)=>{Le.init(s,t);const e=new RegExp(`^${Li(t.prefix)}.*`);t.pattern??(t.pattern=e),s._zod.onattach.push(i=>{const a=i._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(e)}),s._zod.check=i=>{i.value.startsWith(t.prefix)||i.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:i.value,inst:s,continue:!t.abort})}}),fg=z("$ZodCheckEndsWith",(s,t)=>{Le.init(s,t);const e=new RegExp(`.*${Li(t.suffix)}$`);t.pattern??(t.pattern=e),s._zod.onattach.push(i=>{const a=i._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(e)}),s._zod.check=i=>{i.value.endsWith(t.suffix)||i.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:i.value,inst:s,continue:!t.abort})}}),pg=z("$ZodCheckOverwrite",(s,t)=>{Le.init(s,t),s._zod.check=e=>{e.value=t.tx(e.value)}});class gg{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const i=t.split(`
233
+ const DOUBLE_PI: f32 = 3.14159265358979323846264 * 2.;`,tp=Object.defineProperty,ep=(s,t,e)=>t in s?tp(s,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):s[t]=e,ri=(s,t,e)=>(ep(s,typeof t!="symbol"?t+"":t,e),e);const un=class Ai extends ts.Filter{constructor(...t){let e=t[0]??{};typeof e=="number"&&(ts.deprecation("6.0.0","OutlineFilter constructor params are now options object. See params: { thickness, color, quality, alpha, knockout }"),e={thickness:e},t[1]!==void 0&&(e.color=t[1]),t[2]!==void 0&&(e.quality=t[2]),t[3]!==void 0&&(e.alpha=t[3]),t[4]!==void 0&&(e.knockout=t[4])),e={...Ai.DEFAULT_OPTIONS,...e};const i=e.quality??.1,a=ts.GpuProgram.from({vertex:{source:Q0,entryPoint:"mainVertex"},fragment:{source:$0,entryPoint:"mainFragment"}}),n=ts.GlProgram.from({vertex:K0,fragment:J0.replace(/\$\{ANGLE_STEP\}/,Ai.getAngleStep(i).toFixed(7)),name:"outline-filter"});super({gpuProgram:a,glProgram:n,resources:{outlineUniforms:{uThickness:{value:new Float32Array(2),type:"vec2<f32>"},uColor:{value:new Float32Array(3),type:"vec3<f32>"},uAlpha:{value:e.alpha,type:"f32"},uAngleStep:{value:0,type:"f32"},uKnockout:{value:e.knockout?1:0,type:"f32"}}}}),ri(this,"uniforms"),ri(this,"_thickness"),ri(this,"_quality"),ri(this,"_color"),this.uniforms=this.resources.outlineUniforms.uniforms,this.uniforms.uAngleStep=Ai.getAngleStep(i),this._color=new ts.Color,this.color=e.color??0,Object.assign(this,e)}apply(t,e,i,a){this.uniforms.uThickness[0]=this.thickness/e.source.width,this.uniforms.uThickness[1]=this.thickness/e.source.height,t.applyFilter(this,e,i,a)}static getAngleStep(t){return parseFloat((Math.PI*2/Math.max(t*Ai.MAX_SAMPLES,Ai.MIN_SAMPLES)).toFixed(7))}get thickness(){return this._thickness}set thickness(t){this._thickness=this.padding=t}get color(){return this._color.value}set color(t){this._color.setValue(t);const[e,i,a]=this._color.toArray();this.uniforms.uColor[0]=e,this.uniforms.uColor[1]=i,this.uniforms.uColor[2]=a}get alpha(){return this.uniforms.uAlpha}set alpha(t){this.uniforms.uAlpha=t}get quality(){return this._quality}set quality(t){this._quality=t,this.uniforms.uAngleStep=Ai.getAngleStep(t)}get knockout(){return this.uniforms.uKnockout===1}set knockout(t){this.uniforms.uKnockout=t?1:0}};ri(un,"DEFAULT_OPTIONS",{thickness:1,color:0,alpha:1,quality:.1,knockout:!1}),ri(un,"MIN_SAMPLES",1),ri(un,"MAX_SAMPLES",100);let ba=un;class hn extends je{static loadedFonts=new Set;cues=[];currentCue=null;background=null;text=null;vttBlobUrl=null;pendingTranscription=null;isTranscribing=!1;constructor(t,e){super(t,e,qt.Caption)}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.font?.family??"Open Sans";if(await this.loadFont(e),W0(t.src)?(this.isTranscribing=!0,this.pendingTranscription=this.loadTranscriptionInBackground(t.src)):await this.loadSubtitles(t.src),this.background=new X.Graphics,this.contentContainer.addChild(this.background),this.text=new X.Text({text:"",style:this.createTextStyle(t)}),this.text.visible=!1,t.stroke?.width&&t.stroke.width>0&&t.stroke.color){const i=new ba({thickness:t.stroke.width,color:t.stroke.color});this.text.filters=[i]}this.contentContainer.addChild(this.text),this.configureKeyframes()}async loadTranscriptionInBackground(t){const e=this.clipConfiguration.alias??"";try{const i=this.edit.getOriginalEdit();if(!i)throw new Error("Cannot resolve alias: edit not loaded");const a=await Y0(t,i,o=>{this.edit.events.emit(j.TranscriptionProgress,{clipAlias:e,...o})});this.vttBlobUrl=a.vttUrl;const n={src:a.vttUrl,parser:Pi.Name},r=await this.edit.assetLoader.load(a.vttUrl,n);r&&(this.cues=r.cues),this.isTranscribing=!1,this.edit.events.emit(j.TranscriptionCompleted,{clipAlias:e,cueCount:this.cues.length})}catch(i){this.isTranscribing=!1,console.error("Failed to transcribe:",i),this.edit.events.emit(j.TranscriptionFailed,{clipAlias:e,error:i instanceof Error?i.message:"Transcription failed"})}}isTranscriptionPending(){return this.isTranscribing}async waitForTranscription(){this.pendingTranscription&&await this.pendingTranscription}update(t,e){if(super.update(t,e),!this.text)return;const i=this.clipConfiguration.asset,a=i.trim??0,n=this.getPlaybackTime()+a,r=D0(this.cues,n);r!==this.currentCue&&(this.currentCue=r,this.updateDisplay(r,i))}dispose(){super.dispose(),this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null,this.vttBlobUrl&&(Z0(this.vttBlobUrl),this.vttBlobUrl=null),this.cues=[],this.currentCue=null}getSize(){const t=this.clipConfiguration.asset;return{width:this.clipConfiguration.width??t.width??this.edit.size.width,height:this.clipConfiguration.height??t.height??this.edit.size.height}}getFitScale(){return 1}getContainerScale(){const t=this.getScale();return{x:t,y:t}}async loadSubtitles(t){try{const e={src:t,parser:Pi.Name},i=await this.edit.assetLoader.load(t,e);i?this.cues=i.cues:(console.error("Failed to load subtitles"),this.cues=[])}catch(e){console.error("Failed to load subtitles:",e),this.cues=[]}}createTextStyle(t){const e=t.font?.family??"Open Sans",{baseFontFamily:i,fontWeight:a}=Rs(e),n=t.font?.size??32,{width:r}=this.getSize();return new X.TextStyle({fontFamily:i,fontSize:n,fill:t.font?.color??"#ffffff",fontWeight:a.toString(),wordWrap:!0,wordWrapWidth:r*.9,lineHeight:(t.font?.lineHeight??1.2)*n,align:t.alignment?.horizontal??"center"})}updateDisplay(t,e){if(!(!this.text||!this.background)){if(!t){this.text.visible=!1,this.background.clear();return}this.text.text=t.text,this.text.visible=!0,this.positionText(e),this.drawBackground(e)}}positionText(t){if(!this.text)return;const e=t.alignment?.horizontal??"center",i=t.alignment?.vertical??"bottom",{width:a,height:n}=this.getSize(),r=t.background?.padding??10;let o=a/2-this.text.width/2;e==="left"?o=r:e==="right"&&(o=a-this.text.width-r);let l=n*.9;i==="top"?l=r:i==="center"&&(l=n/2-this.text.height/2),this.text.position.set(o,l)}drawBackground(t){if(!this.background||!this.text||!this.text.visible){this.background?.clear();return}const e=t.background;if(!e?.color){this.background.clear();return}const i=e.padding??10,a=e.borderRadius??4,n=this.text.x-i,r=this.text.y-i,o=this.text.width+i*2,l=this.text.height+i*2;this.background.clear(),this.background.fillStyle={color:e.color,alpha:e.opacity??.8},a>0?this.background.roundRect(n,r,o,l,a):this.background.rect(n,r,o,l),this.background.fill()}async loadFont(t){const{baseFontFamily:e,fontWeight:i}=Rs(t),a=`${e}-${i}`;if(hn.loadedFonts.has(a))return;const n=Wr(t);if(n){const r=new FontFace(e,`url(${n})`,{weight:i.toString()});await r.load(),document.fonts.add(r),hn.loadedFonts.add(a)}}}class sp extends je{background;text;constructor(t,e){super(t,e,qt.Html),this.background=null,this.text=null}async load(){await super.load();const t=this.clipConfiguration.asset,e=await this.parseDocument();if(!e)return;const i=new X.Graphics;e.background.color&&(i.fillStyle={color:e.background.color,alpha:e.background.opacity??1},i.rect(0,0,t.width??this.edit.size.width,t.height??this.edit.size.height),i.fill());const a=new X.Text;a.text=e.text;const{horizontal:n,vertical:r}=e.alignment;a.style={fontFamily:e.font?.family??"Open Sans",fontSize:e.font?.size??32,fill:e.font?.color??"#ffffff",fontWeight:(e.font?.weight??"400").toString(),wordWrap:!0,wordWrapWidth:t.width??this.edit.size.width,lineHeight:(e.font?.lineHeight??1)*(e.font?.size??32),align:n};let o=(t.width??this.edit.size.width)/2-a.width/2,l=(t.height??this.edit.size.height)/2-a.height/2;if(n==="left"&&(o=0),n==="right"&&(o=(t.width??this.edit.size.width)-a.width),r==="top"&&(l=0),r==="bottom"&&(l=(t.height??this.edit.size.height)-a.height),a.position={x:o,y:l},e.stroke.color&&e.stroke.width){const c=new ba({thickness:e.stroke.width,color:e.stroke.color});a.filters=[c]}this.background=i,this.text=a,this.contentContainer.addChild(i),this.contentContainer.addChild(a),this.configureKeyframes()}update(t,e){super.update(t,e)}draw(){super.draw()}dispose(){super.dispose(),this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null}getSize(){const t=this.clipConfiguration.asset;return{width:t.width??this.edit.size.width,height:t.height??this.edit.size.height}}getFitScale(){return 1}async parseDocument(){const t=this.clipConfiguration.asset,{html:e,css:i="",position:a}=t;if(!e.includes('data-html-type="text"'))return console.warn("Unsupported html format."),null;const r=new DOMParser().parseFromString(e,"text/html").body.textContent??"",l=(await new CSSStyleSheet().replace(i)).cssRules[0],c={text:r,font:{},alignment:{},background:{},stroke:{}};if(l?.constructor.name!=="CSSStyleRule"||!("style"in l))return console.warn("Unsupported css format."),c;const d=l.style,u=this.parseAlignment(a??"center");c.font={color:d.color.length?d.color:void 0,family:d.fontFamily.length?d.fontFamily:void 0,size:d.fontSize.length?parseInt(d.fontSize,10):void 0,weight:d.fontWeight.length?parseInt(d.fontWeight,10):void 0,lineHeight:d.lineHeight.length?parseInt(d.lineHeight,10):void 0},c.alignment=u;let f="";return d.background.length&&(f=d.background),d.backgroundColor.length&&(f=d.backgroundColor),c.background={color:f.length?f:void 0,opacity:d.opacity.length?parseInt(d.opacity,10):void 0},c.stroke={width:d.strokeWidth.length?parseInt(d.strokeWidth,10):void 0,color:d.stroke.length?d.stroke:void 0},c}parseAlignment(t){switch(t){case"topLeft":return{horizontal:"left",vertical:"top"};case"top":return{horizontal:"center",vertical:"top"};case"topRight":return{horizontal:"right",vertical:"top"};case"left":return{horizontal:"left",vertical:"center"};case"right":return{horizontal:"right",vertical:"center"};case"bottomLeft":return{horizontal:"left",vertical:"bottom"};case"bottom":return{horizontal:"center",vertical:"bottom"};case"bottomRight":return{horizontal:"right",vertical:"bottom"};case"center":default:return{horizontal:"center",vertical:"center"}}}}class ip extends je{texture;sprite;constructor(t,e){super(t,e,qt.Image),this.texture=null,this.sprite=null}async load(){await super.load(),await this.loadTexture(),this.configureKeyframes()}update(t,e){super.update(t,e)}draw(){super.draw()}dispose(){super.dispose(),this.disposeTexture()}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}}getContentSize(){return{width:this.sprite?.width??0,height:this.sprite?.height??0}}async reloadAsset(){this.disposeTexture(),await this.loadTexture()}async loadTexture(){const t=this.clipConfiguration.asset,{src:e}=t,i=`${e}${e.includes("?")?"&":"?"}x-cors=1`,a={src:i,crossorigin:"anonymous",data:{}},n=await this.edit.assetLoader.load(i,a);if(!(n?.source instanceof X.ImageSource))throw n&&n.destroy(!0),new Error(`Invalid image source '${e}'.`);this.texture=this.createCroppedTexture(n),this.sprite=new X.Sprite(this.texture),this.contentContainer.addChild(this.sprite),this.clipConfiguration.width&&this.clipConfiguration.height&&this.applyFixedDimensions()}disposeTexture(){this.sprite&&(this.contentContainer.removeChild(this.sprite),this.sprite.destroy(),this.sprite=null),this.texture=null}supportsEdgeResize(){return!0}createCroppedTexture(t){const e=this.clipConfiguration.asset;if(!e.crop)return t;const i=t.width,a=t.height,n=Math.floor((e.crop?.left??0)*i),r=Math.floor((e.crop?.right??0)*i),o=Math.floor((e.crop?.top??0)*a),l=Math.floor((e.crop?.bottom??0)*a),c=n,d=o,u=i-n-r,f=a-o-l,p=new X.Rectangle(c,d,u,f);return new X.Texture({source:t.source,frame:p})}}class ap extends je{texture;sprite;isPlaying;constructor(t,e){super(t,e,qt.Luma),this.texture=null,this.sprite=null,this.isPlaying=!1}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.src,i={src:e,data:{autoPlay:!1,muted:!0}},a=await this.edit.assetLoader.load(e,i);if(!(a?.source instanceof X.ImageSource||a?.source instanceof X.VideoSource))throw a&&this.edit.assetLoader.decrementRef(e),new Error(`Invalid luma source '${t.src}'.`);a.source instanceof X.VideoSource&&(a.source.alphaMode="no-premultiply-alpha"),this.texture=a,this.sprite=new X.Sprite(this.texture),this.contentContainer.addChild(this.sprite),this.configureKeyframes()}update(t,e){if(super.update(t,e),!this.texture||!(this.texture.source instanceof X.VideoSource))return;const i=this.getPlaybackTime(),a=this.edit.isPlaying&&this.isActive();a&&(this.isPlaying||(this.isPlaying=!0,this.texture.source.resource.currentTime=i,this.texture.source.resource.play().catch(console.error)),this.texture.source.resource.volume!==this.getVolume()&&(this.texture.source.resource.volume=this.getVolume()),Math.abs(this.texture.source.resource.currentTime-i)>.1&&(this.texture.source.resource.currentTime=i)),!a&&this.isPlaying&&(this.isPlaying=!1,this.texture.source.resource.pause()),!this.edit.isPlaying&&this.isActive()&&(this.texture.source.resource.currentTime=i)}draw(){super.draw()}dispose(){super.dispose(),this.sprite?.destroy(),this.sprite=null,this.texture=null}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}}getVolume(){return 0}getSprite(){return this.sprite}isVideoSource(){return this.texture?.source instanceof X.VideoSource}getVideoCurrentTime(){return this.texture?.source instanceof X.VideoSource?this.texture.source.resource.currentTime:-1}}function z(s,t,e){function i(o,l){if(o._zod||Object.defineProperty(o,"_zod",{value:{def:l,constr:r,traits:new Set},enumerable:!1}),o._zod.traits.has(s))return;o._zod.traits.add(s),t(o,l);const c=r.prototype,d=Object.keys(c);for(let u=0;u<d.length;u++){const f=d[u];f in o||(o[f]=c[f].bind(o))}}const a=e?.Parent??Object;class n extends a{}Object.defineProperty(n,"name",{value:s});function r(o){var l;const c=e?.Parent?new n:this;i(c,o),(l=c._zod).deferred??(l.deferred=[]);for(const d of c._zod.deferred)d();return c}return Object.defineProperty(r,"init",{value:i}),Object.defineProperty(r,Symbol.hasInstance,{value:o=>e?.Parent&&o instanceof e.Parent?!0:o?._zod?.traits?.has(s)}),Object.defineProperty(r,"name",{value:s}),r}class Fi extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class ec extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}const sc={};function zs(s){return sc}function ic(s){const t=Object.values(s).filter(i=>typeof i=="number");return Object.entries(s).filter(([i,a])=>t.indexOf(+i)===-1).map(([i,a])=>a)}function Hr(s,t){return typeof t=="bigint"?t.toString():t}function fn(s){return{get value(){{const t=s();return Object.defineProperty(this,"value",{value:t}),t}}}}function Gr(s){return s==null}function jr(s){const t=s.startsWith("^")?1:0,e=s.endsWith("$")?s.length-1:s.length;return s.slice(t,e)}function np(s,t){const e=(s.toString().split(".")[1]||"").length,i=t.toString();let a=(i.split(".")[1]||"").length;if(a===0&&/\d?e-\d?/.test(i)){const l=i.match(/\d?e-(\d?)/);l?.[1]&&(a=Number.parseInt(l[1]))}const n=e>a?e:a,r=Number.parseInt(s.toFixed(n).replace(".","")),o=Number.parseInt(t.toFixed(n).replace(".",""));return r%o/10**n}const ac=Symbol("evaluating");function Xt(s,t,e){let i;Object.defineProperty(s,t,{get(){if(i!==ac)return i===void 0&&(i=ac,i=e()),i},set(a){Object.defineProperty(s,t,{value:a})},configurable:!0})}function oi(s,t,e){Object.defineProperty(s,t,{value:e,writable:!0,enumerable:!0,configurable:!0})}function li(...s){const t={};for(const e of s){const i=Object.getOwnPropertyDescriptors(e);Object.assign(t,i)}return Object.defineProperties({},t)}function nc(s){return JSON.stringify(s)}function rp(s){return s.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const rc="captureStackTrace"in Error?Error.captureStackTrace:(...s)=>{};function wa(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}const op=fn(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const s=Function;return new s(""),!0}catch{return!1}});function Mi(s){if(wa(s)===!1)return!1;const t=s.constructor;if(t===void 0||typeof t!="function")return!0;const e=t.prototype;return!(wa(e)===!1||Object.prototype.hasOwnProperty.call(e,"isPrototypeOf")===!1)}function oc(s){return Mi(s)?{...s}:Array.isArray(s)?[...s]:s}const lp=new Set(["string","number","symbol"]);function Li(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ds(s,t,e){const i=new s._zod.constr(t??s._zod.def);return(!t||e?.parent)&&(i._zod.parent=s),i}function dt(s){const t=s;if(!t)return{};if(typeof t=="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function cp(s){return Object.keys(s).filter(t=>s[t]._zod.optin==="optional"&&s[t]._zod.optout==="optional")}const dp={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function up(s,t){const e=s._zod.def,i=li(s._zod.def,{get shape(){const a={};for(const n in t){if(!(n in e.shape))throw new Error(`Unrecognized key: "${n}"`);t[n]&&(a[n]=e.shape[n])}return oi(this,"shape",a),a},checks:[]});return Ds(s,i)}function hp(s,t){const e=s._zod.def,i=li(s._zod.def,{get shape(){const a={...s._zod.def.shape};for(const n in t){if(!(n in e.shape))throw new Error(`Unrecognized key: "${n}"`);t[n]&&delete a[n]}return oi(this,"shape",a),a},checks:[]});return Ds(s,i)}function fp(s,t){if(!Mi(t))throw new Error("Invalid input to extend: expected a plain object");const e=s._zod.def.checks;if(e&&e.length>0)throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");const a=li(s._zod.def,{get shape(){const n={...s._zod.def.shape,...t};return oi(this,"shape",n),n},checks:[]});return Ds(s,a)}function pp(s,t){if(!Mi(t))throw new Error("Invalid input to safeExtend: expected a plain object");const e={...s._zod.def,get shape(){const i={...s._zod.def.shape,...t};return oi(this,"shape",i),i},checks:s._zod.def.checks};return Ds(s,e)}function gp(s,t){const e=li(s._zod.def,{get shape(){const i={...s._zod.def.shape,...t._zod.def.shape};return oi(this,"shape",i),i},get catchall(){return t._zod.def.catchall},checks:[]});return Ds(s,e)}function mp(s,t,e){const i=li(t._zod.def,{get shape(){const a=t._zod.def.shape,n={...a};if(e)for(const r in e){if(!(r in a))throw new Error(`Unrecognized key: "${r}"`);e[r]&&(n[r]=s?new s({type:"optional",innerType:a[r]}):a[r])}else for(const r in a)n[r]=s?new s({type:"optional",innerType:a[r]}):a[r];return oi(this,"shape",n),n},checks:[]});return Ds(t,i)}function yp(s,t,e){const i=li(t._zod.def,{get shape(){const a=t._zod.def.shape,n={...a};if(e)for(const r in e){if(!(r in n))throw new Error(`Unrecognized key: "${r}"`);e[r]&&(n[r]=new s({type:"nonoptional",innerType:a[r]}))}else for(const r in a)n[r]=new s({type:"nonoptional",innerType:a[r]});return oi(this,"shape",n),n},checks:[]});return Ds(t,i)}function Bi(s,t=0){if(s.aborted===!0)return!0;for(let e=t;e<s.issues.length;e++)if(s.issues[e]?.continue!==!0)return!0;return!1}function Oi(s,t){return t.map(e=>{var i;return(i=e).path??(i.path=[]),e.path.unshift(s),e})}function pn(s){return typeof s=="string"?s:s?.message}function Us(s,t,e){const i={...s,path:s.path??[]};if(!s.message){const a=pn(s.inst?._zod.def?.error?.(s))??pn(t?.error?.(s))??pn(e.customError?.(s))??pn(e.localeError?.(s))??"Invalid input";i.message=a}return delete i.inst,delete i.continue,t?.reportInput||delete i.input,i}function Yr(s){return Array.isArray(s)?"array":typeof s=="string"?"string":"unknown"}function va(...s){const[t,e,i]=s;return typeof t=="string"?{message:t,code:"custom",input:e,inst:i}:{...t}}const lc=(s,t)=>{s.name="$ZodError",Object.defineProperty(s,"_zod",{value:s._zod,enumerable:!1}),Object.defineProperty(s,"issues",{value:t,enumerable:!1}),s.message=JSON.stringify(t,Hr,2),Object.defineProperty(s,"toString",{value:()=>s.message,enumerable:!1})},cc=z("$ZodError",lc),dc=z("$ZodError",lc,{Parent:Error});function bp(s,t=e=>e.message){const e={},i=[];for(const a of s.issues)a.path.length>0?(e[a.path[0]]=e[a.path[0]]||[],e[a.path[0]].push(t(a))):i.push(t(a));return{formErrors:i,fieldErrors:e}}function wp(s,t=e=>e.message){const e={_errors:[]},i=a=>{for(const n of a.issues)if(n.code==="invalid_union"&&n.errors.length)n.errors.map(r=>i({issues:r}));else if(n.code==="invalid_key")i({issues:n.issues});else if(n.code==="invalid_element")i({issues:n.issues});else if(n.path.length===0)e._errors.push(t(n));else{let r=e,o=0;for(;o<n.path.length;){const l=n.path[o];o===n.path.length-1?(r[l]=r[l]||{_errors:[]},r[l]._errors.push(t(n))):r[l]=r[l]||{_errors:[]},r=r[l],o++}}};return i(s),e}const Zr=s=>(t,e,i,a)=>{const n=i?Object.assign(i,{async:!1}):{async:!1},r=t._zod.run({value:e,issues:[]},n);if(r instanceof Promise)throw new Fi;if(r.issues.length){const o=new(a?.Err??s)(r.issues.map(l=>Us(l,n,zs())));throw rc(o,a?.callee),o}return r.value},qr=s=>async(t,e,i,a)=>{const n=i?Object.assign(i,{async:!0}):{async:!0};let r=t._zod.run({value:e,issues:[]},n);if(r instanceof Promise&&(r=await r),r.issues.length){const o=new(a?.Err??s)(r.issues.map(l=>Us(l,n,zs())));throw rc(o,a?.callee),o}return r.value},gn=s=>(t,e,i)=>{const a=i?{...i,async:!1}:{async:!1},n=t._zod.run({value:e,issues:[]},a);if(n instanceof Promise)throw new Fi;return n.issues.length?{success:!1,error:new(s??cc)(n.issues.map(r=>Us(r,a,zs())))}:{success:!0,data:n.value}},vp=gn(dc),mn=s=>async(t,e,i)=>{const a=i?Object.assign(i,{async:!0}):{async:!0};let n=t._zod.run({value:e,issues:[]},a);return n instanceof Promise&&(n=await n),n.issues.length?{success:!1,error:new s(n.issues.map(r=>Us(r,a,zs())))}:{success:!0,data:n.value}},xp=mn(dc),Cp=s=>(t,e,i)=>{const a=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return Zr(s)(t,e,a)},kp=s=>(t,e,i)=>Zr(s)(t,e,i),Sp=s=>async(t,e,i)=>{const a=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return qr(s)(t,e,a)},Np=s=>async(t,e,i)=>qr(s)(t,e,i),Tp=s=>(t,e,i)=>{const a=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return gn(s)(t,e,a)},Ip=s=>(t,e,i)=>gn(s)(t,e,i),Ap=s=>async(t,e,i)=>{const a=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return mn(s)(t,e,a)},Ep=s=>async(t,e,i)=>mn(s)(t,e,i),Pp=/^[cC][^\s-]{8,}$/,Fp=/^[0-9a-z]+$/,Mp=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Lp=/^[0-9a-vA-V]{20}$/,Bp=/^[A-Za-z0-9]{27}$/,Op=/^[a-zA-Z0-9_-]{21}$/,_p=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Rp=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uc=s=>s?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${s}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,zp=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Dp="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Up(){return new RegExp(Dp,"u")}const Vp=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Wp=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Hp=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Gp=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,jp=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,hc=/^[A-Za-z0-9_-]*$/,Yp=/^\+(?:[0-9]){6,14}[0-9]$/,fc="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Zp=new RegExp(`^${fc}$`);function pc(s){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof s.precision=="number"?s.precision===-1?`${t}`:s.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${s.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function qp(s){return new RegExp(`^${pc(s)}$`)}function Xp(s){const t=pc({precision:s.precision}),e=["Z"];s.local&&e.push(""),s.offset&&e.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const i=`${t}(?:${e.join("|")})`;return new RegExp(`^${fc}T(?:${i})$`)}const Kp=s=>{const t=s?`[\\s\\S]{${s?.minimum??0},${s?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},Qp=/^-?\d+$/,Jp=/^-?\d+(?:\.\d+)?/,$p=/^(?:true|false)$/i,tg=/^null$/i,eg=/^[^A-Z]*$/,sg=/^[^a-z]*$/,Le=z("$ZodCheck",(s,t)=>{var e;s._zod??(s._zod={}),s._zod.def=t,(e=s._zod).onattach??(e.onattach=[])}),gc={number:"number",bigint:"bigint",object:"date"},mc=z("$ZodCheckLessThan",(s,t)=>{Le.init(s,t);const e=gc[typeof t.value];s._zod.onattach.push(i=>{const a=i._zod.bag,n=(t.inclusive?a.maximum:a.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value<n&&(t.inclusive?a.maximum=t.value:a.exclusiveMaximum=t.value)}),s._zod.check=i=>{(t.inclusive?i.value<=t.value:i.value<t.value)||i.issues.push({origin:e,code:"too_big",maximum:t.value,input:i.value,inclusive:t.inclusive,inst:s,continue:!t.abort})}}),yc=z("$ZodCheckGreaterThan",(s,t)=>{Le.init(s,t);const e=gc[typeof t.value];s._zod.onattach.push(i=>{const a=i._zod.bag,n=(t.inclusive?a.minimum:a.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>n&&(t.inclusive?a.minimum=t.value:a.exclusiveMinimum=t.value)}),s._zod.check=i=>{(t.inclusive?i.value>=t.value:i.value>t.value)||i.issues.push({origin:e,code:"too_small",minimum:t.value,input:i.value,inclusive:t.inclusive,inst:s,continue:!t.abort})}}),ig=z("$ZodCheckMultipleOf",(s,t)=>{Le.init(s,t),s._zod.onattach.push(e=>{var i;(i=e._zod.bag).multipleOf??(i.multipleOf=t.value)}),s._zod.check=e=>{if(typeof e.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof e.value=="bigint"?e.value%t.value===BigInt(0):np(e.value,t.value)===0)||e.issues.push({origin:typeof e.value,code:"not_multiple_of",divisor:t.value,input:e.value,inst:s,continue:!t.abort})}}),ag=z("$ZodCheckNumberFormat",(s,t)=>{Le.init(s,t),t.format=t.format||"float64";const e=t.format?.includes("int"),i=e?"int":"number",[a,n]=dp[t.format];s._zod.onattach.push(r=>{const o=r._zod.bag;o.format=t.format,o.minimum=a,o.maximum=n,e&&(o.pattern=Qp)}),s._zod.check=r=>{const o=r.value;if(e){if(!Number.isInteger(o)){r.issues.push({expected:i,format:t.format,code:"invalid_type",continue:!1,input:o,inst:s});return}if(!Number.isSafeInteger(o)){o>0?r.issues.push({input:o,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:s,origin:i,continue:!t.abort}):r.issues.push({input:o,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:s,origin:i,continue:!t.abort});return}}o<a&&r.issues.push({origin:"number",input:o,code:"too_small",minimum:a,inclusive:!0,inst:s,continue:!t.abort}),o>n&&r.issues.push({origin:"number",input:o,code:"too_big",maximum:n,inst:s})}}),ng=z("$ZodCheckMaxLength",(s,t)=>{var e;Le.init(s,t),(e=s._zod.def).when??(e.when=i=>{const a=i.value;return!Gr(a)&&a.length!==void 0}),s._zod.onattach.push(i=>{const a=i._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum<a&&(i._zod.bag.maximum=t.maximum)}),s._zod.check=i=>{const a=i.value;if(a.length<=t.maximum)return;const r=Yr(a);i.issues.push({origin:r,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),rg=z("$ZodCheckMinLength",(s,t)=>{var e;Le.init(s,t),(e=s._zod.def).when??(e.when=i=>{const a=i.value;return!Gr(a)&&a.length!==void 0}),s._zod.onattach.push(i=>{const a=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>a&&(i._zod.bag.minimum=t.minimum)}),s._zod.check=i=>{const a=i.value;if(a.length>=t.minimum)return;const r=Yr(a);i.issues.push({origin:r,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),og=z("$ZodCheckLengthEquals",(s,t)=>{var e;Le.init(s,t),(e=s._zod.def).when??(e.when=i=>{const a=i.value;return!Gr(a)&&a.length!==void 0}),s._zod.onattach.push(i=>{const a=i._zod.bag;a.minimum=t.length,a.maximum=t.length,a.length=t.length}),s._zod.check=i=>{const a=i.value,n=a.length;if(n===t.length)return;const r=Yr(a),o=n>t.length;i.issues.push({origin:r,...o?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:i.value,inst:s,continue:!t.abort})}}),yn=z("$ZodCheckStringFormat",(s,t)=>{var e,i;Le.init(s,t),s._zod.onattach.push(a=>{const n=a._zod.bag;n.format=t.format,t.pattern&&(n.patterns??(n.patterns=new Set),n.patterns.add(t.pattern))}),t.pattern?(e=s._zod).check??(e.check=a=>{t.pattern.lastIndex=0,!t.pattern.test(a.value)&&a.issues.push({origin:"string",code:"invalid_format",format:t.format,input:a.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:s,continue:!t.abort})}):(i=s._zod).check??(i.check=()=>{})}),lg=z("$ZodCheckRegex",(s,t)=>{yn.init(s,t),s._zod.check=e=>{t.pattern.lastIndex=0,!t.pattern.test(e.value)&&e.issues.push({origin:"string",code:"invalid_format",format:"regex",input:e.value,pattern:t.pattern.toString(),inst:s,continue:!t.abort})}}),cg=z("$ZodCheckLowerCase",(s,t)=>{t.pattern??(t.pattern=eg),yn.init(s,t)}),dg=z("$ZodCheckUpperCase",(s,t)=>{t.pattern??(t.pattern=sg),yn.init(s,t)}),ug=z("$ZodCheckIncludes",(s,t)=>{Le.init(s,t);const e=Li(t.includes),i=new RegExp(typeof t.position=="number"?`^.{${t.position}}${e}`:e);t.pattern=i,s._zod.onattach.push(a=>{const n=a._zod.bag;n.patterns??(n.patterns=new Set),n.patterns.add(i)}),s._zod.check=a=>{a.value.includes(t.includes,t.position)||a.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:a.value,inst:s,continue:!t.abort})}}),hg=z("$ZodCheckStartsWith",(s,t)=>{Le.init(s,t);const e=new RegExp(`^${Li(t.prefix)}.*`);t.pattern??(t.pattern=e),s._zod.onattach.push(i=>{const a=i._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(e)}),s._zod.check=i=>{i.value.startsWith(t.prefix)||i.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:i.value,inst:s,continue:!t.abort})}}),fg=z("$ZodCheckEndsWith",(s,t)=>{Le.init(s,t);const e=new RegExp(`.*${Li(t.suffix)}$`);t.pattern??(t.pattern=e),s._zod.onattach.push(i=>{const a=i._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(e)}),s._zod.check=i=>{i.value.endsWith(t.suffix)||i.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:i.value,inst:s,continue:!t.abort})}}),pg=z("$ZodCheckOverwrite",(s,t)=>{Le.init(s,t),s._zod.check=e=>{e.value=t.tx(e.value)}});class gg{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const i=t.split(`
234
234
  `).filter(r=>r),a=Math.min(...i.map(r=>r.length-r.trimStart().length)),n=i.map(r=>r.slice(a)).map(r=>" ".repeat(this.indent*2)+r);for(const r of n)this.content.push(r)}compile(){const t=Function,e=this?.args,a=[...(this?.content??[""]).map(n=>` ${n}`)];return new t(...e,a.join(`
235
235
  `))}}const mg={major:4,minor:2,patch:1},$t=z("$ZodType",(s,t)=>{var e;s??(s={}),s._zod.def=t,s._zod.bag=s._zod.bag||{},s._zod.version=mg;const i=[...s._zod.def.checks??[]];s._zod.traits.has("$ZodCheck")&&i.unshift(s);for(const a of i)for(const n of a._zod.onattach)n(s);if(i.length===0)(e=s._zod).deferred??(e.deferred=[]),s._zod.deferred?.push(()=>{s._zod.run=s._zod.parse});else{const a=(r,o,l)=>{let c=Bi(r),d;for(const u of o){if(u._zod.def.when){if(!u._zod.def.when(r))continue}else if(c)continue;const f=r.issues.length,p=u._zod.check(r);if(p instanceof Promise&&l?.async===!1)throw new Fi;if(d||p instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await p,r.issues.length!==f&&(c||(c=Bi(r,f)))});else{if(r.issues.length===f)continue;c||(c=Bi(r,f))}}return d?d.then(()=>r):r},n=(r,o,l)=>{if(Bi(r))return r.aborted=!0,r;const c=a(o,i,l);if(c instanceof Promise){if(l.async===!1)throw new Fi;return c.then(d=>s._zod.parse(d,l))}return s._zod.parse(c,l)};s._zod.run=(r,o)=>{if(o.skipChecks)return s._zod.parse(r,o);if(o.direction==="backward"){const c=s._zod.parse({value:r.value,issues:[]},{...o,skipChecks:!0});return c instanceof Promise?c.then(d=>n(d,r,o)):n(c,r,o)}const l=s._zod.parse(r,o);if(l instanceof Promise){if(o.async===!1)throw new Fi;return l.then(c=>a(c,i,o))}return a(l,i,o)}}s["~standard"]={validate:a=>{try{const n=vp(s,a);return n.success?{value:n.data}:{issues:n.error?.issues}}catch{return xp(s,a).then(r=>r.success?{value:r.data}:{issues:r.error?.issues})}},vendor:"zod",version:1}}),Xr=z("$ZodString",(s,t)=>{$t.init(s,t),s._zod.pattern=[...s?._zod.bag?.patterns??[]].pop()??Kp(s._zod.bag),s._zod.parse=(e,i)=>{if(t.coerce)try{e.value=String(e.value)}catch{}return typeof e.value=="string"||e.issues.push({expected:"string",code:"invalid_type",input:e.value,inst:s}),e}}),ee=z("$ZodStringFormat",(s,t)=>{yn.init(s,t),Xr.init(s,t)}),yg=z("$ZodGUID",(s,t)=>{t.pattern??(t.pattern=Rp),ee.init(s,t)}),bg=z("$ZodUUID",(s,t)=>{if(t.version){const i={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(i===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=uc(i))}else t.pattern??(t.pattern=uc());ee.init(s,t)}),wg=z("$ZodEmail",(s,t)=>{t.pattern??(t.pattern=zp),ee.init(s,t)}),vg=z("$ZodURL",(s,t)=>{ee.init(s,t),s._zod.check=e=>{try{const i=e.value.trim(),a=new URL(i);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(a.hostname)||e.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:e.value,inst:s,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(a.protocol.endsWith(":")?a.protocol.slice(0,-1):a.protocol)||e.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:e.value,inst:s,continue:!t.abort})),t.normalize?e.value=a.href:e.value=i;return}catch{e.issues.push({code:"invalid_format",format:"url",input:e.value,inst:s,continue:!t.abort})}}}),xg=z("$ZodEmoji",(s,t)=>{t.pattern??(t.pattern=Up()),ee.init(s,t)}),Cg=z("$ZodNanoID",(s,t)=>{t.pattern??(t.pattern=Op),ee.init(s,t)}),kg=z("$ZodCUID",(s,t)=>{t.pattern??(t.pattern=Pp),ee.init(s,t)}),Sg=z("$ZodCUID2",(s,t)=>{t.pattern??(t.pattern=Fp),ee.init(s,t)}),Ng=z("$ZodULID",(s,t)=>{t.pattern??(t.pattern=Mp),ee.init(s,t)}),Tg=z("$ZodXID",(s,t)=>{t.pattern??(t.pattern=Lp),ee.init(s,t)}),Ig=z("$ZodKSUID",(s,t)=>{t.pattern??(t.pattern=Bp),ee.init(s,t)}),Ag=z("$ZodISODateTime",(s,t)=>{t.pattern??(t.pattern=Xp(t)),ee.init(s,t)}),Eg=z("$ZodISODate",(s,t)=>{t.pattern??(t.pattern=Zp),ee.init(s,t)}),Pg=z("$ZodISOTime",(s,t)=>{t.pattern??(t.pattern=qp(t)),ee.init(s,t)}),Fg=z("$ZodISODuration",(s,t)=>{t.pattern??(t.pattern=_p),ee.init(s,t)}),Mg=z("$ZodIPv4",(s,t)=>{t.pattern??(t.pattern=Vp),ee.init(s,t),s._zod.bag.format="ipv4"}),Lg=z("$ZodIPv6",(s,t)=>{t.pattern??(t.pattern=Wp),ee.init(s,t),s._zod.bag.format="ipv6",s._zod.check=e=>{try{new URL(`http://[${e.value}]`)}catch{e.issues.push({code:"invalid_format",format:"ipv6",input:e.value,inst:s,continue:!t.abort})}}}),Bg=z("$ZodCIDRv4",(s,t)=>{t.pattern??(t.pattern=Hp),ee.init(s,t)}),Og=z("$ZodCIDRv6",(s,t)=>{t.pattern??(t.pattern=Gp),ee.init(s,t),s._zod.check=e=>{const i=e.value.split("/");try{if(i.length!==2)throw new Error;const[a,n]=i;if(!n)throw new Error;const r=Number(n);if(`${r}`!==n)throw new Error;if(r<0||r>128)throw new Error;new URL(`http://[${a}]`)}catch{e.issues.push({code:"invalid_format",format:"cidrv6",input:e.value,inst:s,continue:!t.abort})}}});function bc(s){if(s==="")return!0;if(s.length%4!==0)return!1;try{return atob(s),!0}catch{return!1}}const _g=z("$ZodBase64",(s,t)=>{t.pattern??(t.pattern=jp),ee.init(s,t),s._zod.bag.contentEncoding="base64",s._zod.check=e=>{bc(e.value)||e.issues.push({code:"invalid_format",format:"base64",input:e.value,inst:s,continue:!t.abort})}});function Rg(s){if(!hc.test(s))return!1;const t=s.replace(/[-_]/g,i=>i==="-"?"+":"/"),e=t.padEnd(Math.ceil(t.length/4)*4,"=");return bc(e)}const zg=z("$ZodBase64URL",(s,t)=>{t.pattern??(t.pattern=hc),ee.init(s,t),s._zod.bag.contentEncoding="base64url",s._zod.check=e=>{Rg(e.value)||e.issues.push({code:"invalid_format",format:"base64url",input:e.value,inst:s,continue:!t.abort})}}),Dg=z("$ZodE164",(s,t)=>{t.pattern??(t.pattern=Yp),ee.init(s,t)});function Ug(s,t=null){try{const e=s.split(".");if(e.length!==3)return!1;const[i]=e;if(!i)return!1;const a=JSON.parse(atob(i));return!("typ"in a&&a?.typ!=="JWT"||!a.alg||t&&(!("alg"in a)||a.alg!==t))}catch{return!1}}const Vg=z("$ZodJWT",(s,t)=>{ee.init(s,t),s._zod.check=e=>{Ug(e.value,t.alg)||e.issues.push({code:"invalid_format",format:"jwt",input:e.value,inst:s,continue:!t.abort})}}),wc=z("$ZodNumber",(s,t)=>{$t.init(s,t),s._zod.pattern=s._zod.bag.pattern??Jp,s._zod.parse=(e,i)=>{if(t.coerce)try{e.value=Number(e.value)}catch{}const a=e.value;if(typeof a=="number"&&!Number.isNaN(a)&&Number.isFinite(a))return e;const n=typeof a=="number"?Number.isNaN(a)?"NaN":Number.isFinite(a)?void 0:"Infinity":void 0;return e.issues.push({expected:"number",code:"invalid_type",input:a,inst:s,...n?{received:n}:{}}),e}}),Wg=z("$ZodNumberFormat",(s,t)=>{ag.init(s,t),wc.init(s,t)}),Hg=z("$ZodBoolean",(s,t)=>{$t.init(s,t),s._zod.pattern=$p,s._zod.parse=(e,i)=>{if(t.coerce)try{e.value=!!e.value}catch{}const a=e.value;return typeof a=="boolean"||e.issues.push({expected:"boolean",code:"invalid_type",input:a,inst:s}),e}}),Gg=z("$ZodNull",(s,t)=>{$t.init(s,t),s._zod.pattern=tg,s._zod.values=new Set([null]),s._zod.parse=(e,i)=>{const a=e.value;return a===null||e.issues.push({expected:"null",code:"invalid_type",input:a,inst:s}),e}}),jg=z("$ZodUnknown",(s,t)=>{$t.init(s,t),s._zod.parse=e=>e}),Yg=z("$ZodNever",(s,t)=>{$t.init(s,t),s._zod.parse=(e,i)=>(e.issues.push({expected:"never",code:"invalid_type",input:e.value,inst:s}),e)}),Zg=z("$ZodVoid",(s,t)=>{$t.init(s,t),s._zod.parse=(e,i)=>{const a=e.value;return typeof a>"u"||e.issues.push({expected:"void",code:"invalid_type",input:a,inst:s}),e}});function vc(s,t,e){s.issues.length&&t.issues.push(...Oi(e,s.issues)),t.value[e]=s.value}const qg=z("$ZodArray",(s,t)=>{$t.init(s,t),s._zod.parse=(e,i)=>{const a=e.value;if(!Array.isArray(a))return e.issues.push({expected:"array",code:"invalid_type",input:a,inst:s}),e;e.value=Array(a.length);const n=[];for(let r=0;r<a.length;r++){const o=a[r],l=t.element._zod.run({value:o,issues:[]},i);l instanceof Promise?n.push(l.then(c=>vc(c,e,r))):vc(l,e,r)}return n.length?Promise.all(n).then(()=>e):e}});function bn(s,t,e,i){s.issues.length&&t.issues.push(...Oi(e,s.issues)),s.value===void 0?e in i&&(t.value[e]=void 0):t.value[e]=s.value}function xc(s){const t=Object.keys(s.shape);for(const i of t)if(!s.shape?.[i]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${i}": expected a Zod schema`);const e=cp(s.shape);return{...s,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(e)}}function Cc(s,t,e,i,a,n){const r=[],o=a.keySet,l=a.catchall._zod,c=l.def.type;for(const d in t){if(o.has(d))continue;if(c==="never"){r.push(d);continue}const u=l.run({value:t[d],issues:[]},i);u instanceof Promise?s.push(u.then(f=>bn(f,e,d,t))):bn(u,e,d,t)}return r.length&&e.issues.push({code:"unrecognized_keys",keys:r,input:t,inst:n}),s.length?Promise.all(s).then(()=>e):e}const Xg=z("$ZodObject",(s,t)=>{if($t.init(s,t),!Object.getOwnPropertyDescriptor(t,"shape")?.get){const o=t.shape;Object.defineProperty(t,"shape",{get:()=>{const l={...o};return Object.defineProperty(t,"shape",{value:l}),l}})}const i=fn(()=>xc(t));Xt(s._zod,"propValues",()=>{const o=t.shape,l={};for(const c in o){const d=o[c]._zod;if(d.values){l[c]??(l[c]=new Set);for(const u of d.values)l[c].add(u)}}return l});const a=wa,n=t.catchall;let r;s._zod.parse=(o,l)=>{r??(r=i.value);const c=o.value;if(!a(c))return o.issues.push({expected:"object",code:"invalid_type",input:c,inst:s}),o;o.value={};const d=[],u=r.shape;for(const f of r.keys){const y=u[f]._zod.run({value:c[f],issues:[]},l);y instanceof Promise?d.push(y.then(v=>bn(v,o,f,c))):bn(y,o,f,c)}return n?Cc(d,c,o,l,i.value,s):d.length?Promise.all(d).then(()=>o):o}}),Kg=z("$ZodObjectJIT",(s,t)=>{Xg.init(s,t);const e=s._zod.parse,i=fn(()=>xc(t)),a=f=>{const p=new gg(["shape","payload","ctx"]),y=i.value,v=b=>{const P=nc(b);return`shape[${P}]._zod.run({ value: input[${P}], issues: [] }, ctx)`};p.write("const input = payload.value;");const S=Object.create(null);let x=0;for(const b of y.keys)S[b]=`key_${x++}`;p.write("const newResult = {};");for(const b of y.keys){const P=S[b],m=nc(b);p.write(`const ${P} = ${v(b)};`),p.write(`
236
236
  if (${P}.issues.length) {
@@ -257,7 +257,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
257
257
  `){f.push({glyphs:p,width:y,y:0}),p=[],y=0,S=C;continue}if(y+P>n&&p.length>0){if(S>-1){const m=S-(C-p.length)+1,U=p.splice(m),M=p.reduce((_,K)=>_+K.xAdvance,0);f.push({glyphs:p,width:M,y:0}),p=U,y=U.reduce((_,K)=>_+K.xAdvance,0)}else f.push({glyphs:p,width:y,y:0}),p=[],y=0;S=-1}p.push(b),y+=P,v.has(b.cluster)&&(S=C)}p.length>0&&f.push({glyphs:p,width:y,y:0});const x=s.lineHeight*i;for(let C=0;C<f.length;C++)f[C].y=(C+1)*x;return f}catch(t){throw t instanceof Error?t:new Error(`Layout failed: ${String(t)}`)}}};function ES(s,t){return s.type==="linear"?{kind:"linear",angle:s.angle,stops:s.stops,opacity:t}:{kind:"radial",stops:s.stops,opacity:t}}function PS(s,t){const e=Math.max(1,Math.round(t.fontSize*.05));let i=t.baselineY+Math.round(t.fontSize*.1);return s==="line-through"&&(i=t.baselineY-Math.round(t.fontSize*.3)),{x1:t.xStart,x2:t.xStart+t.lineWidth,y:i,width:e}}function FS(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 MS(s){const t=[],e=FS(s.padding),i=s.border?.width??0;if(t.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 t;const a=Math.max(1,await s.getUnitsPerEm()),n=s.font.size/a,r=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-(r-1)*o;break;case"middle":default:const C=s.font.size*.35;l=(s.textRect.height-(r-1)*o)/2+C;break}l+=i+e.top;const c=s.style.gradient?ES(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,y=1/0,v=-1/0,S=-1/0;for(const x of s.lines){let C;switch(s.align.horizontal){case"left":C=0;break;case"right":C=s.textRect.width-x.width;break;case"center":default:C=(s.textRect.width-x.width)/2;break}C+=i+e.left;let b=C;const P=s.lines.indexOf(x),m=l+P*o;if(s.font.background){const U=s.font.size*.15,M=s.font.size*.12,_=s.font.size*.92+M*2,K=m-s.font.size*.78-M;f.push({op:"Rectangle",x:C-U,y:K,width:x.width+U*2,height:_,fill:{kind:"solid",color:s.font.background,opacity:1}})}for(const U of x.glyphs){const M=b+U.xOffset,_=m+U.yOffset,K=U.fontDesc?.family;if((U.isColorEmoji||K&&s.isColorEmojiFont&&s.isColorEmojiFont(K))&&U.char){u.push({op:"DrawColorEmoji",char:U.char,x:M,y:_,fontSize:s.font.size,fontFamily:K||"NotoColorEmoji"}),b+=U.xAdvance;continue}const H=await s.glyphPathProvider(U.id,U.fontDesc);if(!H||H==="M 0 0"){b+=U.xAdvance;continue}const ut=BS(H),vt=M+n*ut.x,_t=M+n*(ut.x+ut.w),Pt=_-n*(ut.y+ut.h),Ht=_-n*ut.y;vt<p&&(p=vt),Pt<y&&(y=Pt),_t>v&&(v=_t),Ht>S&&(S=Ht),s.shadow&&s.shadow.blur>0&&u.push({isShadow:!0,op:"FillPath",path:H,x:M+s.shadow.offsetX,y:_+s.shadow.offsetY,scale:n,fill:{kind:"solid",color:s.shadow.color,opacity:s.shadow.opacity}}),s.stroke&&s.stroke.width>0&&u.push({op:"StrokePath",path:H,x:M,y:_,scale:n,width:s.stroke.width,color:s.stroke.color,opacity:s.stroke.opacity}),u.push({op:"FillPath",path:H,x:M,y:_,scale:n,fill:c}),b+=U.xAdvance}if(s.style.textDecoration!=="none"){const U=PS(s.style.textDecoration,{baselineY:m,fontSize:s.font.size,lineWidth:x.width,xStart:C});u.push({op:"DecorationLine",from:{x:U.x1,y:U.y},to:{x:U.x2,y:U.y},width:U.width,color:d,opacity:s.font.opacity})}}if(p!==1/0){const x={x:p,y,w:Math.max(1,v-p),h:Math.max(1,S-y)};for(const C of u)C.op==="FillPath"&&!C.isShadow&&(C.gradientBBox=x)}if(s.background||s.border){const x=s.contentRect?.width??s.canvas.width,C=s.contentRect?.height??s.canvas.height,b=s.border?.width??0,P=s.border?.radius??0,m=b/2,U=s.canvas.width/2,M=s.canvas.height/2,_=U-x/2,K=M-C/2,q=Math.min(x-b,C-b)/2,H=Math.min(P,q),ut=Math.max(0,H-m);s.background?.color&&t.push({op:"Rectangle",x:_+b,y:K+b,width:x-b*2,height:C-b*2,fill:{kind:"solid",color:s.background.color,opacity:s.background.opacity},borderRadius:ut}),s.border&&s.border.width>0&&t.push({op:"RectangleStroke",x:_+m,y:K+m,width:x-b,height:C-b,stroke:{width:s.border.width,color:s.border.color,opacity:s.border.opacity},borderRadius:H})}return t.push(...f),t.push(...u),t}function LS(s){return s.match(/[MLCQZ]|-?\d*\.?\d+(?:e[-+]?\d+)?/gi)??[]}function BS(s){const t=LS(s);let e=0,i=1/0,a=1/0,n=-1/0,r=-1/0;const o=(l,c)=>{l<i&&(i=l),c<a&&(a=c),l>n&&(n=l),c>r&&(r=c)};for(;e<t.length;)switch(t[e++]){case"M":case"L":{const c=parseFloat(t[e++]),d=parseFloat(t[e++]);o(c,d);break}case"C":{const c=parseFloat(t[e++]),d=parseFloat(t[e++]),u=parseFloat(t[e++]),f=parseFloat(t[e++]),p=parseFloat(t[e++]),y=parseFloat(t[e++]);o(c,d),o(u,f),o(p,y);break}case"Q":{const c=parseFloat(t[e++]),d=parseFloat(t[e++]),u=parseFloat(t[e++]),f=parseFloat(t[e++]);o(c,d),o(u,f);break}}return i===1/0?{x:0,y:0,w:0,h:0}:{x:i,y:a,w:n-i,h:r-a}}var al=.999;function OS(s,t,e){if(!e.anim||!e.anim.preset)return s;const{preset:i}=e.anim,a=t.reduce((l,c)=>l+c.glyphs.length,0);let n=Math.max(.3,a/(30*e.anim.speed));e.clipDuration&&!e.anim.duration&&(n=Math.min(n,e.clipDuration*.9));const r=e.anim.duration??n,o=Math.max(0,Math.min(1,e.t/r));switch(i){case"typewriter":return RS(s,t,o,e.anim.style,e.fontSize,e.t);case"fadeIn":return US(s,t,o,e.anim.style,e.fontSize,r);case"slideIn":return VS(s,t,o,e.anim.direction??"left",e.fontSize,e.anim.style,r);case"shift":return DS(s,t,o,e.anim.direction??"left",e.fontSize,e.anim.style,r);case"ascend":return zS(s,t,o,e.anim.direction??"up",e.fontSize,r);case"movingLetters":return WS(s,e.t,e.anim.direction??"up",e.fontSize);default:return s}}var lr=s=>s.op==="FillPath"&&s.isShadow===!0,cr=s=>s.op==="FillPath"&&!s.isShadow;function _S(s){for(const t of s)if(t.op==="FillPath"){const e=t.fill;if(e?.kind==="solid")return e.color;if((e?.kind==="linear"||e?.kind==="radial")&&Array.isArray(e.stops)&&e.stops.length)return e.stops[e.stops.length-1].color||"#000000"}return"#000000"}function RS(s,t,e,i,a,n,r){if(i==="word"){const l=Ha(t),c=l.length,d=Math.floor(e*c);if(d===0)return s.filter(y=>y.op==="BeginFrame"||y.op==="Rectangle"||y.op==="RectangleStroke");let u=0;for(let y=0;y<Math.min(d,l.length);y++)u+=l[y].glyphCount;const f=jh(s,u),p=e>=al?f:f.filter(y=>y.op!=="DecorationLine");return e<1&&u>0?Yh(p,u,a):p}else{const l=t.reduce((f,p)=>f+p.glyphs.length,0),c=Math.floor(e*l);if(c===0)return s.filter(f=>f.op==="BeginFrame"||f.op==="Rectangle"||f.op==="RectangleStroke");const d=jh(s,c),u=e>=al?d:d.filter(f=>f.op!=="DecorationLine");return e<1&&c>0?Yh(u,c,a):u}}function zS(s,t,e,i,a,n){const r=Ha(t),o=r.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<r.length;p++){const y=r[p].glyphCount;if(c>=f&&c<f+y){u=p;break}f+=y}if(u>=0){const p=u/Math.max(1,o)*(n/n),y=Math.min(1,p+.3);if(e>=y)l.push(d);else if(e>p){const v=(e-p)/Math.max(1e-6,y-p),S=dr(Math.min(1,v)),x=i==="up"?a*.4:-a*.4,C={...d,y:d.y+x*(1-S)};d.op==="FillPath"?C.fill.kind==="solid"?C.fill={...C.fill,opacity:C.fill.opacity*S}:C.fill={...C.fill,opacity:(C.fill.opacity??1)*S}:C.opacity=C.opacity*S,l.push(C)}}cr(d)&&c++}else d.op==="DecorationLine"&&e>=al&&l.push(d);return l}function DS(s,t,e,i,a,n,r){const o=n==="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?Ha(t):[],u=t.reduce((b,P)=>b+P.glyphs.length,0),f=o?d.length:u;if(f===0)return s;const p=[];for(const b of s)if((b.op==="BeginFrame"||b.op==="Rectangle"||b.op==="RectangleStroke")&&p.push(b),b.op==="FillPath"||b.op==="StrokePath")break;const y=.3,S=r*.7/Math.max(1,f-1),x=b=>{const P=b*S,m=P/r,U=Math.min(1,(P+y)/r);return{startF:m,endF:U}};let C=0;for(const b of s){if(b.op!=="FillPath"&&b.op!=="StrokePath"){b.op==="DecorationLine"&&e>.8&&p.push(b);continue}let P;if(!o)P=C;else{let M=-1,_=0;for(let K=0;K<d.length;K++){const q=d[K].glyphCount;if(C>=_&&C<_+q){M=K;break}_+=q}P=Math.max(0,M)}const{startF:m,endF:U}=x(P);if(e<=m){const M={...b,x:b.x+c.x,y:b.y+c.y};b.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(e>=U)p.push(b);else{const M=(e-m)/Math.max(1e-6,U-m),_=dr(Math.min(1,M)),K=c.x*(1-_),q=c.y*(1-_),H={...b,x:b.x+K,y:b.y+q};if(b.op==="FillPath"){const ut=H.fill.kind==="solid"?H.fill.opacity:H.fill.opacity??1;H.fill.kind==="solid"?H.fill={...H.fill,opacity:ut*_}:H.fill={...H.fill,opacity:ut*_}}else H.opacity=H.opacity*_;p.push(H)}cr(b)&&C++}return p}function US(s,t,e,i,a,n){const r=i==="word";if(!r&&!(i==="character")){const x=nl(e),C=.95+.05*x;return GS(s,x,C)}const l=r?Ha(t):[],c=t.reduce((x,C)=>x+C.glyphs.length,0),d=r?l.length:c;if(d===0)return s;const u=[];for(const x of s)if(x.op==="BeginFrame"){u.push(x);break}const f=.3,y=n*.7/Math.max(1,d-1),v=x=>{const C=x*y,b=C/n,P=Math.min(1,(C+f)/n);return{startF:b,endF:P}};let S=0;for(const x of s){if(x.op!=="FillPath"&&x.op!=="StrokePath"){x.op==="DecorationLine"&&e>.8&&u.push(x);continue}let C;if(!r)C=S;else{let m=-1,U=0;for(let M=0;M<l.length;M++){const _=l[M].glyphCount;if(S>=U&&S<U+_){m=M;break}U+=_}C=Math.max(0,m)}const{startF:b,endF:P}=v(C);if(e<=b){const m={...x};x.op==="FillPath"?m.fill.kind==="solid"?m.fill={...m.fill,opacity:0}:m.fill={...m.fill,opacity:0}:m.opacity=0,u.push(m)}else if(e>=P)u.push(x);else{const m=(e-b)/Math.max(1e-6,P-b),U=nl(Math.min(1,m)),M={...x};if(x.op==="FillPath"){const _=M.fill.kind==="solid"?M.fill.opacity:M.fill.opacity??1;M.fill.kind==="solid"?M.fill={...M.fill,opacity:_*U}:M.fill={...M.fill,opacity:_*U}}else M.opacity=M.opacity*U;u.push(M)}cr(x)&&S++}return u}function VS(s,t,e,i,a,n,r){const o=n==="word";if(!o&&!(n==="character")){const P=dr(e),m=ZS(1-P,i,a*2),U=nl(e);return jS(s,m.dx,m.dy,U)}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?Ha(t):[],f=t.reduce((P,m)=>P+m.glyphs.length,0),p=o?u.length:f;if(p===0)return s;const y=[];for(const P of s)if(P.op==="BeginFrame"){y.push(P);break}const v=.3,x=r*.7/Math.max(1,p-1),C=P=>{const m=P*x,U=m/r,M=Math.min(1,(m+v)/r);return{startF:U,endF:M}};let b=0;for(const P of s){if(P.op!=="FillPath"&&P.op!=="StrokePath"){P.op==="DecorationLine"&&e>.8&&y.push(P);continue}let m;if(!o)m=b;else{let _=-1,K=0;for(let q=0;q<u.length;q++){const H=u[q].glyphCount;if(b>=K&&b<K+H){_=q;break}K+=H}m=Math.max(0,_)}const{startF:U,endF:M}=C(m);if(e<=U){const _={...P,x:P.x+d.x,y:P.y+d.y};P.op==="FillPath"?_.fill.kind==="solid"?_.fill={..._.fill,opacity:0}:_.fill={..._.fill,opacity:0}:_.opacity=0,y.push(_)}else if(e>=M)y.push(P);else{const _=(e-U)/Math.max(1e-6,M-U),K=dr(Math.min(1,_)),q=d.x*(1-K),H=d.y*(1-K),ut={...P,x:P.x+q,y:P.y+H};if(P.op==="FillPath"){const vt=ut.fill.kind==="solid"?ut.fill.opacity:ut.fill.opacity??1;ut.fill.kind==="solid"?ut.fill={...ut.fill,opacity:vt*K}:ut.fill={...ut.fill,opacity:vt*K}}else ut.opacity=ut.opacity*K;y.push(ut)}cr(P)&&b++}return y}function WS(s,t,e,i){const a=i*.3;return YS(s,e,a,t)}function Ha(s){const t=[];let e=0;for(let i=0;i<s.length;i++){const a=s[i],n=HS(a);for(const r of n)r.length>0&&t.push({startGlyph:e,glyphCount:r.length,lineIndex:i}),e+=r.length}return t}function HS(s){const t=[];let e=[];for(const i of s.glyphs)i.char===" "||i.char===" "||i.char===`
258
258
  `?e.length&&(t.push([...e]),e=[]):e.push(i);return e.length&&t.push(e),t}function jh(s,t){const e=[];let i=0,a=!1;for(const n of s){if(n.op==="BeginFrame"||n.op==="Rectangle"||n.op==="RectangleStroke"){e.push(n);continue}if(n.op==="FillPath"&&!lr(n)){i<t&&(e.push(n),a=!0),i++;continue}if(n.op==="StrokePath"){i<t&&e.push(n);continue}if(n.op==="FillPath"&&lr(n)){i<t&&e.push(n);continue}if(n.op==="DecorationLine"&&a){e.push(n);continue}}return e}function Yh(s,t,e,i){if(t===0)return s;let a=null,n=0;for(const r of s)if(r.op==="FillPath"&&!lr(r)&&(n++,n===t)){a=r;break}if(a&&a.op==="FillPath"){const r=_S(s),o=a.x+e*.5,l=a.y,c=Math.max(3,e/15),d={op:"DecorationLine",from:{x:o,y:l-e*.75},to:{x:o,y:l+e*.15},width:c,color:r,opacity:1};return[...s,d]}return s}function GS(s,t,e){let i=0,a=0,n=0;return s.forEach(r=>{r.op==="FillPath"&&(i+=r.x,a+=r.y,n++)}),n>0&&(i/=n,a/=n),s.map(r=>{if(r.op==="FillPath"){const o={...r};if(o.fill.kind==="solid"?o.fill={...o.fill,opacity:o.fill.opacity*t}:o.fill={...o.fill,opacity:(o.fill.opacity??1)*t},e!==1&&n>0){const l=r.x-i,c=r.y-a;o.x=i+l*e,o.y=a+c*e}return o}if(r.op==="StrokePath"){const o={...r,opacity:r.opacity*t};if(e!==1&&n>0){const l=r.x-i,c=r.y-a;o.x=i+l*e,o.y=a+c*e}return o}return r.op==="DecorationLine"?{...r,opacity:r.opacity*t}:r})}function jS(s,t,e,i=1){return s.map(a=>{if(a.op==="FillPath"){const n={...a,x:a.x+t,y:a.y+e};return i<1&&(n.fill.kind==="solid"?n.fill={...n.fill,opacity:n.fill.opacity*i}:n.fill={...n.fill,opacity:(n.fill.opacity??1)*i}),n}return a.op==="StrokePath"?{...a,x:a.x+t,y:a.y+e,opacity:a.opacity*i}:a.op==="DecorationLine"?{...a,from:{x:a.from.x+t,y:a.from.y+e},to:{x:a.to.x+t,y:a.to.y+e},opacity:a.opacity*i}:a})}function YS(s,t,e,i){let a=0;const r=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=t==="left"||t==="right"?l*e*(t==="left"?-1:1):0,d=t==="up"||t==="down"?l*e*(t==="up"?-1:1):0;if(o.op==="FillPath"){lr(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*r}:u.fill={...u.fill,opacity:(u.fill.opacity??1)*r},u}return{...o,x:o.x+c,y:o.y+d,opacity:o.opacity*r}}return o})}function ZS(s,t,e){const i=s*e;switch(t){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 nl(s){return s*(2-s)}function dr(s){return 1-Math.pow(1-s,3)}function Ki(s,t=1){const e=/^#?([a-f0-9]{6})$/i.exec(s);if(!e)throw new Error(`Invalid color ${s}`);const i=parseInt(e[1],16),a=i>>16&255,n=i>>8&255,r=i&255;return{r:a,g:n,b:r,a:t}}function qS(s){const t=s.getContext("2d");if(!t)throw new Error("2D context unavailable");return{async render(e){const i=XS(e),a=new Map;for(const n of e){if(n.op==="BeginFrame"){n.pixelRatio;const r=n.width,o=n.height;if("width"in s&&"height"in s&&(s.width=Math.floor(r),s.height=Math.floor(o)),"style"in s&&(s.style.width=`${r}px`,s.style.height=`${o}px`),t.setTransform(1,0,0,1,0,0),n.clear&&t.clearRect(0,0,r,o),n.bg&&n.bg.color){const{color:l,opacity:c,radius:d}=n.bg;if(l){const u=Ki(l,c);d&&d>0?(t.fillStyle=`rgba(${u.r},${u.g},${u.b},${u.a})`,Zh(t,0,0,r,o,d),t.fill()):(t.fillStyle=`rgba(${u.r},${u.g},${u.b},${u.a})`,t.fillRect(0,0,r,o))}}continue}if(n.op==="FillPath"){const r=n,o=new Path2D(r.path);t.save(),t.translate(r.x,r.y);const l=r.scale??1;t.scale(l,-l);const c=r.gradientBBox??i,d={x:(c.x-r.x)/l,y:-(c.y-r.y)/l,w:c.w/l,h:c.h/l},u=JSON.stringify({fill:r.fill,bbox:d});let f=a.get(u);f||(f=qh(t,r.fill,d),a.set(u,f)),t.fillStyle=f,t.fill(o),t.restore();continue}if(n.op==="StrokePath"){const r=n,o=new Path2D(r.path);t.save(),t.translate(r.x,r.y);const l=r.scale??1;t.scale(l,-l);const c=1/Math.abs(l),d=Ki(r.color,r.opacity);t.strokeStyle=`rgba(${d.r},${d.g},${d.b},${d.a})`,t.lineWidth=r.width*c,t.lineJoin="round",t.lineCap="round",t.stroke(o),t.restore();continue}if(n.op==="DecorationLine"){t.save();const r=Ki(n.color,n.opacity);t.strokeStyle=`rgba(${r.r},${r.g},${r.b},${r.a})`,t.lineWidth=n.width,t.beginPath(),t.moveTo(n.from.x,n.from.y),t.lineTo(n.to.x,n.to.y),t.stroke(),t.restore();continue}if(n.op==="Rectangle"){t.save();const r=qh(t,n.fill,{x:n.x,y:n.y,w:n.width,h:n.height});t.fillStyle=r,n.borderRadius&&n.borderRadius>0?Zh(t,n.x,n.y,n.width,n.height,n.borderRadius):t.fillRect(n.x,n.y,n.width,n.height),t.restore();continue}if(n.op==="RectangleStroke"){t.save();const r=Ki(n.stroke.color,n.stroke.opacity);if(t.strokeStyle=`rgba(${r.r},${r.g},${r.b},${r.a})`,t.lineWidth=n.stroke.width,n.borderRadius&&n.borderRadius>0){const o=new Path2D,l=n.x,c=n.y,d=n.width,u=n.height,f=Math.min(d,u)/2,p=Math.min(n.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(),t.stroke(o)}else t.strokeRect(n.x,n.y,n.width,n.height);t.restore();continue}if(n.op==="DrawColorEmoji"){t.save(),t.font=`${n.fontSize}px "${n.fontFamily}"`,t.textBaseline="alphabetic",t.fillText(n.char,n.x,n.y),t.restore();continue}}}}}function Zh(s,t,e,i,a,n){const r=Math.min(i,a)/2,o=Math.min(n,r),l=new Path2D;l.moveTo(t+o,e),l.arcTo(t+i,e,t+i,e+a,o),l.arcTo(t+i,e+a,t,e+a,o),l.arcTo(t,e+a,t,e,o),l.arcTo(t,e,t+i,e,o),l.closePath(),s.save(),s.fill(l),s.restore()}function qh(s,t,e){if(t.kind==="solid"){const o=Ki(t.color,t.opacity);return`rgba(${o.r},${o.g},${o.b},${o.a})`}const i=e.x+e.w/2,a=e.y+e.h/2,n=Math.max(e.w,e.h)/2,r=o=>{const l=t.kind==="linear"||t.kind==="radial"?t.opacity:1,c=t.kind==="linear"||t.kind==="radial"?t.stops:[];for(const d of c){const u=Ki(d.color,l);o.addColorStop(d.offset,`rgba(${u.r},${u.g},${u.b},${u.a})`)}return o};if(t.kind==="linear"){const o=t.angle*Math.PI/180,l=i+Math.cos(o+Math.PI)*n,c=a+Math.sin(o+Math.PI)*n,d=i+Math.cos(o)*n,u=a+Math.sin(o)*n;return r(s.createLinearGradient(l,c,d,u))}else return r(s.createRadialGradient(i,a,0,i,a,n))}function XS(s){let t=1/0,e=1/0,i=-1/0,a=-1/0;for(const n of s){if(n.op!=="FillPath")continue;const r=n;if(r.isShadow)continue;const o=KS(r.path),l=r.scale??1,c=r.x+l*o.x,d=r.x+l*(o.x+o.w),u=r.y-l*(o.y+o.h),f=r.y-l*o.y;c<t&&(t=c),u<e&&(e=u),d>i&&(i=d),f>a&&(a=f)}return t===1/0?{x:0,y:0,w:1,h:1}:{x:t,y:e,w:Math.max(1,i-t),h:Math.max(1,a-e)}}function KS(s){const t=QS(s);let e=0,i=1/0,a=1/0,n=-1/0,r=-1/0;const o=(l,c)=>{l<i&&(i=l),c<a&&(a=c),l>n&&(n=l),c>r&&(r=c)};for(;e<t.length;)switch(t[e++]){case"M":case"L":{const c=parseFloat(t[e++]),d=parseFloat(t[e++]);o(c,d);break}case"C":{const c=parseFloat(t[e++]),d=parseFloat(t[e++]),u=parseFloat(t[e++]),f=parseFloat(t[e++]),p=parseFloat(t[e++]),y=parseFloat(t[e++]);o(c,d),o(u,f),o(p,y);break}case"Q":{const c=parseFloat(t[e++]),d=parseFloat(t[e++]),u=parseFloat(t[e++]),f=parseFloat(t[e++]);o(c,d),o(u,f);break}}return i===1/0?{x:0,y:0,w:0,h:0}:{x:i,y:a,w:n-i,h:r-a}}function QS(s){return s.match(/[MLCQZ]|-?\d*\.?\d+(?:e[-+]?\d+)?/gi)??[]}async function Ga(s){try{const t=await fetch(s);if(!t.ok)throw new Error(`Failed to fetch ${s}: ${t.status} ${t.statusText}`);try{return await t.arrayBuffer()}catch(e){throw new Error(`Failed to read response body as ArrayBuffer from ${s}: ${e instanceof Error?e.message:String(e)}`)}}catch(t){throw t instanceof Error?t.message.includes("Failed to fetch")||t.message.includes("Failed to read")?t:new Error(`Failed to fetch ${s}: ${t.message}`):new Error(`Failed to fetch ${s}: ${String(t)}`)}}var Xh="https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu4mxP.ttf";async function JS(s={}){const t=s.width??ye.DEFAULTS.width,e=s.height??ye.DEFAULTS.height,i=s.pixelRatio??ye.DEFAULTS.pixelRatio,a="https://shotstack-ingest-api-dev-sources.s3.ap-southeast-2.amazonaws.com/euo5r93oyr/zzz01k9h-yycyx-2x2y6-qx9bj-7n567b/source.wasm";Gh.setFallbackLoader(async l=>{const c=(l.family??"Roboto").toLowerCase(),d=`${l.weight??"400"}`;if(c==="roboto"&&d==="400")return Ga(Xh)});let n;try{n=await Gh.getSharedInstance(a)}catch(l){throw new Error(`Failed to initialize font registry: ${l instanceof Error?l.message:String(l)}`)}const r=new AS(n);async function o(l){try{if(l.customFonts)for(const f of l.customFonts)try{const p=await Ga(f.src);await n.registerFromBytes(p,{family:f.family,weight:f.weight??"400"})}catch(p){throw new Error(`Failed to load custom font "${f.family}" from ${f.src}: ${p instanceof Error?p.message:String(p)}`)}const c=l.font??{family:"Roboto",weight:"400",size:48,color:"#000000",opacity:1},d={family:c.family,weight:`${c.weight}`};return await(async()=>{try{await n.getFace(d)}catch{if((c.family||"Roboto").toLowerCase()==="roboto"&&`${c.weight}`=="400"){const p=await Ga(Xh);await n.registerFromBytes(p,{family:"Roboto",weight:"400"})}else throw new Error(`Font not registered for ${d.family}__${d.weight}`)}})(),c}catch(c){throw c instanceof Error?c:new Error(`Failed to ensure fonts: ${String(c)}`)}}return{validate(l){const c=xS.safeParse(l);if(!c.success){const d=c.error.issues.map(u=>u.message).join(". ");throw new Error(`Validation failed: ${d}`)}return{value:c.data}},async registerFontFromUrl(l,c){try{const d=await Ga(l);await n.registerFromBytes(d,c)}catch(d){throw new Error(`Failed to register font "${c.family}" from URL ${l}: ${d instanceof Error?d.message:String(d)}`)}},async registerFontFromFile(l,c){try{let d;if(typeof l=="string")try{d=await Ga(l)}catch(u){throw new Error(`Failed to fetch font from ${l}: ${u instanceof Error?u.message:String(u)}`)}else try{d=await l.arrayBuffer()}catch(u){throw new Error(`Failed to read Blob as ArrayBuffer: ${u instanceof Error?u.message:String(u)}`)}await n.registerFromBytes(d,c)}catch(d){throw d instanceof Error?d:new Error(`Failed to register font "${c.family}" from ${typeof l=="string"?l:"Blob"}: ${String(d)}`)}},async renderFrame(l,c,d){try{const u=await o(l),f={family:u.family,weight:`${u.weight}`};let p;try{let M;const _=n.getColorEmojiFontFamilies();if(_.length>0)M={family:_[0],weight:"400"};else{const q={family:"NotoEmoji",weight:"400"};try{await n.getFace(q),M=q}catch{}}const K=l.padding?typeof l.padding=="number"?{top:l.padding,right:l.padding,bottom:l.padding,left:l.padding}:l.padding:{top:0,right:0,bottom:0,left:0};p=await r.layout({text:l.text,width:(l.width??t)-K.left-K.right,letterSpacing:l.style?.letterSpacing??0,fontSize:u.size,lineHeight:l.style?.lineHeight??1.2,desc:f,textTransform:l.style?.textTransform??"none",emojiFallback:M})}catch(M){throw new Error(`Failed to layout text: ${M instanceof Error?M.message:String(M)}`)}const y=l.padding?typeof l.padding=="number"?{top:l.padding,right:l.padding,bottom:l.padding,left:l.padding}:l.padding:{top:0,right:0,bottom:0,left:0},v=l.border?.width??0,S=(l.width??t)+v*2,x=(l.height??e)+v*2,C=i,b={x:0,y:0,width:(l.width??t)-y.left-y.right,height:(l.height??e)-y.top-y.bottom},P=S,m=x;let U;try{U=await MS({canvas:{width:S,height:x,pixelRatio:C},textRect:b,lines:p,contentRect:{width:P,height:m},font:{family:u.family,size:u.size,weight:`${u.weight}`,color:u.color,opacity:u.opacity,background:u.background},style:{lineHeight:l.style?.lineHeight??1.2,textDecoration:l.style?.textDecoration??"none",gradient:l.style?.gradient},stroke:l.stroke,shadow:l.shadow,align:{horizontal:l.align?.horizontal??"center",vertical:l.align?.vertical??"middle"},background:l.background,border:l.border,padding:l.padding,glyphPathProvider:(M,_)=>n.glyphPath(_||f,M),getUnitsPerEm:M=>n.getUnitsPerEm(M||f),isColorEmojiFont:M=>n.isColorEmojiFont(M)})}catch(M){throw new Error(`Failed to build draw operations: ${M instanceof Error?M.message:String(M)}`)}try{return OS(U,p,{t:c,fontSize:u.size,clipDuration:d,anim:l.animation?{preset:l.animation.preset,speed:l.animation.speed,duration:l.animation.duration,style:l.animation.style,direction:l.animation.direction}:void 0})}catch(M){throw new Error(`Failed to apply animation: ${M instanceof Error?M.message:String(M)}`)}}catch(u){throw u instanceof Error?u:new Error(`Failed to render frame at time ${c}s: ${String(u)}`)}},createRenderer(l){try{return qS(l)}catch(c){throw new Error(`Failed to create renderer: ${c instanceof Error?c.message:String(c)}`)}},destroy(){try{n.release()}catch(l){console.error(`Error during cleanup: ${l instanceof Error?l.message:String(l)}`)}}}}const Kh=s=>{const e=(s.split("/").pop()||"").replace(/\.(ttf|otf|woff|woff2)$/i,""),i=e.replace(/-(Bold|Light|Regular|Italic|Medium|SemiBold|Black|Thin|ExtraLight|ExtraBold|Heavy)$/i,"");return{full:e,base:i}};class Qi extends je{static PREVIEW_FPS=60;textEngine=null;renderer=null;canvas=null;texture=null;sprite=null;lastRenderedTime=-1;cachedFrames=new Map;isRendering=!1;validatedAsset=null;fontSupportsBold=!1;constructor(t,e){const i=e.fit?e:{...e,fit:"cover"};super(t,i,qt.RichText)}buildCanvasPayload(t,e){const i=this.clipConfiguration.width||this.edit.size.width,a=this.clipConfiguration.height||this.edit.size.height,n=t.font?.family,{baseFontFamily:r,fontWeight:o}=e??(n?Rs(n):{baseFontFamily:n,fontWeight:400}),l=t.font?.weight;let c=o;typeof l=="string"?c=parseInt(l,10)||o:typeof l=="number"&&(c=l);const d=this.edit.getTimelineFonts(),u=n?d.find(p=>{const{full:y,base:v}=Kh(p.src),S=n.toLowerCase();return y.toLowerCase()===S||v.toLowerCase()===S}):void 0,f=u?[{src:u.src,family:r||n,weight:c.toString()}]:void 0;return{...t,width:i,height:a,font:t.font?{...t.font,family:r,weight:c}:void 0,stroke:t.font?.stroke,...f&&{customFonts:f}}}async registerFont(t,e,i){if(!this.textEngine)return!1;try{const a={family:t,weight:e.toString()};return i.type==="url"?await this.textEngine.registerFontFromUrl(i.path,a):await this.textEngine.registerFontFromFile(i.path,a),!0}catch(a){return console.warn(`Failed to load font ${t}:`,a),!1}}async checkFontCapabilities(t){try{const i=await(await fetch(t)).arrayBuffer(),n=zr.parse(i).tables.fvar;if(n?.axes){const r=n.axes.find(o=>o.tag==="wght");this.fontSupportsBold=!!r}else this.fontSupportsBold=!1}catch(e){console.warn("Failed to check font capabilities:",e),this.fontSupportsBold=!1}}supportsBold(){return this.fontSupportsBold}resolveFont(t){const{baseFontFamily:e,fontWeight:i}=Rs(t),r=(this.edit.getEdit()?.timeline?.fonts||[]).find(l=>{const{full:c,base:d}=Kh(l.src),u=t.toLowerCase();return c.toLowerCase()===u||d.toLowerCase()===u});if(r)return{url:r.src,baseFontFamily:e,fontWeight:i};const o=Wr(t);return o?{url:o,baseFontFamily:e,fontWeight:i}:null}reconfigureAfterRestore(){super.reconfigureAfterRestore(),this.reconfigure(this.clipConfiguration.asset)}async reconfigure(t){const e=await this.ensureFontRegistered(t);e&&(await this.checkFontCapabilities(e),this.edit.events.emit(_s.FontCapabilitiesChanged,{supportsBold:this.fontSupportsBold}));for(const i of this.cachedFrames.values())i.destroy();if(this.cachedFrames.clear(),this.lastRenderedTime=-1,this.textEngine){const i=this.buildCanvasPayload(t),{value:a}=this.textEngine.validate(i);this.validatedAsset=a}this.textEngine&&this.renderer&&this.renderFrameSafe(this.getCurrentTime()/1e3)}async ensureFontRegistered(t){if(!this.textEngine)return null;const e=t.font?.family;if(!e)return null;const i=this.resolveFont(e);if(!i)return null;const a=t.font?.weight;let{fontWeight:n}=i;return typeof a=="string"?n=parseInt(a,10)||i.fontWeight:typeof a=="number"&&(n=a),await this.registerFont(i.baseFontFamily,n,{type:"url",path:i.url}),i.url}async load(){await super.load();const t=this.clipConfiguration.asset;try{const e=ao.safeParse(t);if(!e.success){console.error("Rich-text asset validation failed:",e.error),this.createFallbackText(t);return}const i=t.font?.family,a=i?Rs(i):void 0,n=this.buildCanvasPayload(t,a);this.textEngine=await JS({width:n.width,height:n.height,fps:Qi.PREVIEW_FPS});const{value:r}=this.textEngine.validate(n);if(this.validatedAsset=r,this.canvas=document.createElement("canvas"),this.canvas.width=n.width,this.canvas.height=n.height,this.renderer=this.textEngine.createRenderer(this.canvas),i){const o=this.resolveFont(i);if(o){const l=t.font?.weight;let{fontWeight:c}=o;typeof l=="string"?c=parseInt(l,10)||o.fontWeight:typeof l=="number"&&(c=l),await this.registerFont(o.baseFontFamily,c,{type:"url",path:o.url}),await this.checkFontCapabilities(o.url)}else console.warn(`Font ${i} not found. Available:`,Object.keys(ya))}await this.renderFrame(0),this.configureKeyframes()}catch(e){console.error("Failed to initialize rich text player:",e),this.cleanupResources(),this.createFallbackText(t)}}cleanupResources(){if(this.textEngine){try{this.textEngine.destroy()}catch(t){console.warn("Error destroying text engine:",t)}this.textEngine=null}this.renderer=null,this.canvas=null,this.validatedAsset=null}async renderFrame(t){if(!this.textEngine||!this.renderer||!this.canvas||!this.validatedAsset)return;const e=Math.floor(t*Qi.PREVIEW_FPS);if(this.cachedFrames.has(e)){const i=this.cachedFrames.get(e);this.sprite&&this.sprite.texture!==i&&(this.sprite.texture=i),this.lastRenderedTime=t;return}try{const i=await this.textEngine.renderFrame(this.validatedAsset,t),a=this.canvas.getContext("2d");a&&a.clearRect(0,0,this.canvas.width,this.canvas.height),await this.renderer.render(i);const n=X.Texture.from(this.canvas);this.sprite?(this.texture&&!this.cachedFrames.has(e)&&this.texture.destroy(),this.sprite.texture=n):(this.sprite=new X.Sprite(n),this.contentContainer.addChild(this.sprite)),this.texture=n,this.cachedFrames.size<150&&this.cachedFrames.set(e,n),this.lastRenderedTime=t}catch(i){console.error("Failed to render rich text frame:",i)}}createFallbackText(t){const e=this.edit.getEdit(),i=this.clipConfiguration.width||e?.output?.size?.width||this.edit.size.width,a=this.clipConfiguration.height||e?.output?.size?.height||this.edit.size.height,n=new X.TextStyle({fontFamily:t.font?.family||"Arial",fontSize:t.font?.size||48,fill:t.font?.color||"#ffffff",align:t.align?.horizontal||"center",wordWrap:!0,wordWrapWidth:i}),r=new X.Text(t.text,n);switch(t.align?.horizontal){case"left":r.anchor.set(0,.5),r.x=0;break;case"right":r.anchor.set(1,.5),r.x=i;break;default:r.anchor.set(.5,.5),r.x=i/2}switch(t.align?.vertical){case"top":r.anchor.set(r.anchor.x,0),r.y=0;break;case"bottom":r.anchor.set(r.anchor.x,1),r.y=a;break;default:r.anchor.set(r.anchor.x,.5),r.y=a/2}this.contentContainer.addChild(r)}renderFrameSafe(t){if(this.isRendering){const e=Math.floor(t*Qi.PREVIEW_FPS),i=this.cachedFrames.get(e);i&&this.sprite&&this.sprite.texture!==i&&(this.sprite.texture=i);return}this.isRendering=!0,this.renderFrame(t).catch(e=>console.error("Failed to render rich text frame:",e)).finally(()=>{this.isRendering=!1})}update(t,e){if(super.update(t,e),e===101&&(this.isRendering=!1,this.lastRenderedTime=-1),!!this.isActive()&&this.textEngine&&this.renderer&&!this.isRendering){const i=this.getCurrentTime()/1e3,a=1/60;Math.abs(i-this.lastRenderedTime)>a&&this.renderFrameSafe(i)}}dispose(){super.dispose();for(const t of this.cachedFrames.values())t.destroy();this.cachedFrames.clear(),this.texture&&!this.cachedFrames.has(Math.floor(this.lastRenderedTime*Qi.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 t=this.edit.getEdit();return{width:this.clipConfiguration.width||t?.output?.size?.width||this.edit.size.width,height:this.clipConfiguration.height||t?.output?.size?.height||this.edit.size.height}}getFitScale(){return 1}getContainerScale(){const t=this.getScale();return{x:t,y:t}}supportsEdgeResize(){return!0}onDimensionsChanged(){if(!this.textEngine||!this.renderer||!this.canvas)return;const t=this.clipConfiguration.asset,{width:e,height:i}=this.getSize();this.canvas.width=e,this.canvas.height=i;for(const r of this.cachedFrames.values())r.destroy();this.cachedFrames.clear(),this.lastRenderedTime=-1;const a=this.buildCanvasPayload(t),{value:n}=this.textEngine.validate(a);this.validatedAsset=n,this.renderFrameSafe(this.getCurrentTime()/1e3)}updateTextContent(t){const e=this.clipConfiguration.asset;if(e.text=t,this.textEngine){const i=this.buildCanvasPayload(e),{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.getCurrentTime()/1e3)}getCurrentTime(){return this.edit.playbackTime-this.getStart()}getCacheSize(){return this.cachedFrames.size}}class $S extends je{shape;shapeBackground;constructor(t,e){super(t,e,qt.Shape),this.shape=null,this.shapeBackground=null}async load(){await super.load();const t=this.clipConfiguration.asset,e=new X.Graphics,i=t.width??this.edit.size.width,a=t.height??this.edit.size.height;e.fillStyle={color:"transparent"},e.rect(0,0,i,a),e.fill();const n=new X.Graphics;switch(t.shape){case"rectangle":{const r=t.rectangle,o=i/2-r.width/2,l=a/2-r.height/2;n.rect(o,l,r.width,r.height);break}case"circle":{const r=t.circle,o=i/2,l=a/2;n.circle(o,l,r.radius);break}case"line":{const r=t.line,o=i/2-r.length/2,l=a/2-r.thickness/2;n.rect(o,l,r.length,r.thickness);break}default:console.warn("Unsupported shape asset type.");break}if(n.fillStyle={color:t.fill?.color??"#ffffff",alpha:t.fill?.opacity??1},n.fill(),t.stroke){const r=new ba({thickness:t.stroke.width,color:t.stroke.color});n.filters=[r]}this.shapeBackground=e,this.shape=n,this.contentContainer.addChild(e),e.addChild(n),this.configureKeyframes()}update(t,e){super.update(t,e)}draw(){super.draw()}dispose(){super.dispose(),this.shape?.destroy(),this.shape=null,this.shapeBackground?.destroy(),this.shapeBackground=null}getSize(){const t=this.clipConfiguration.asset;return{width:t.width??this.edit.size.width,height:t.height??this.edit.size.height}}getFitScale(){return 1}}class ja{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(t,e,i,a){this.parent=t,this.textElement=e,this.clipConfig=i,this.width=a?.width??ja.DEFAULT_CURSOR_WIDTH_PX,this.color=a?.color??ja.DEFAULT_CURSOR_COLOR,this.blinkIntervalMs=a?.blinkInterval??ja.DEFAULT_BLINK_INTERVAL_MS,this.textPosition=0,this.isBlinking=!1,this.isVisible=!0,this.blinkInterval=null,this.createCursor()}updatePosition(t){if(!this.cursor||!this.textElement){console.warn("TextCursor: Cannot update position, cursor not initialized");return}this.textPosition=this.validateTextPosition(t),this.calculateAndApplyPixelPosition()}setPosition(t,e){if(!this.cursor){console.warn("TextCursor: Cannot set position, cursor not initialized");return}this.pixelX=t,this.pixelY=e,this.updateGraphicsPosition()}show(){this.setVisible(!0)}hide(){this.setVisible(!1)}setVisible(t){this.isVisible=t,this.cursor&&!this.isBlinking&&(this.cursor.visible=t)}startBlinking(){if(!this.cursor){console.warn("TextCursor: Cannot start blinking, cursor not initialized");return}this.isBlinking||this.startBlinkingAnimation()}stopBlinking(){this.stopBlinkingAnimation()}setBlinkInterval(t){this.blinkIntervalMs=t,this.isBlinking&&(this.stopBlinking(),this.startBlinking())}dispose(){if(this.stopBlinkingAnimation(),this.cursor&&this.parent)try{this.parent.removeChild(this.cursor)}catch(t){console.warn("TextCursor: Error removing cursor from parent:",t)}if(this.cursor)try{this.cursor.destroy()}catch(t){console.warn("TextCursor: Error destroying cursor graphics:",t)}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 X.Graphics,this.cursor.fillStyle={color:this.color};const t=this.textElement.style.fontSize;this.cursor.rect(0,0,this.width,t),this.cursor.fill(),this.parent.addChild(this.cursor),this.cursor.visible=this.isVisible}validateTextPosition(t){return this.textElement?Math.max(0,Math.min(t,this.textElement.text.length)):0}calculateAndApplyPixelPosition(){this.calculatePixelPositionFromText(),this.updateGraphicsPosition()}calculatePixelPositionFromText(){if(!this.textElement)return;const{text:t}=this.textElement,e=this.textElement.style,i=t.substring(0,this.textPosition),a=i.match(/\n/g);this.currentLine=a?a.length:0;const n=t.split(`
259
259
  `),r=this.currentLine<n.length?n[this.currentLine]:"",o=i.lastIndexOf(`
260
- `),l=o===-1?this.textPosition:this.textPosition-o-1,c=r.substring(0,l);let d;c.length>0&&c.endsWith(" ")?d=this.measureText(`${c}x`,e)-this.measureText("x",e):d=this.measureText(c,e);const u=e.lineHeight;this.pixelY=this.currentLine*u;const p=this.clipConfig.asset.alignment?.horizontal??"center";let y=d;if(p!=="left"){const v=this.measureText(r,e),S=this.textElement.width;let x=0;p==="center"?x=(S-v)/2:p==="right"&&(x=S-v),y=x+d}this.pixelX=y}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(t,e){const i=new X.Text(t,e),{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 ur{static DEFAULT_FOCUS_DELAY_MS=50;hiddenInput=null;isFocused=!1;focusRetryCount=0;maxFocusRetries=3;focusDelay=ur.DEFAULT_FOCUS_DELAY_MS;eventHandlers={};abortController=null;textChangeCallback=null;lastSyncedText="";isComposing=!1;setupInput(t,e){this.focusDelay=e?.focusDelay??ur.DEFAULT_FOCUS_DELAY_MS,this.createHiddenTextarea(),this.hiddenInput&&(this.hiddenInput.value=t,this.lastSyncedText=t),this.setupEventListeners(),e?.autoFocus!==!1&&this.focusInput()}updateInputValue(t){this.hiddenInput&&(this.hiddenInput.value=t,this.lastSyncedText=t)}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(t,e){if(!this.hiddenInput)return;const i=this.hiddenInput.value.length,a=Math.max(0,Math.min(t,i)),n=Math.max(a,Math.min(e,i));this.hiddenInput.setSelectionRange(a,n)}getCursorPosition(){return this.hiddenInput?.selectionStart||0}getValue(){return this.hiddenInput?.value||""}setTextInputHandler(t){this.textChangeCallback=t}setEventHandlers(t){this.eventHandlers={...this.eventHandlers,...t}}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 t={position:"absolute",opacity:"0.01",pointerEvents:"none",zIndex:"999",left:"0px",top:"0px",width:"1px",height:"1px",border:"none",outline:"none",resize:"none",backgroundColor:"transparent"};Object.assign(this.hiddenInput.style,t),this.hiddenInput.tabIndex=0,document.body.appendChild(this.hiddenInput)}setupEventListeners(){if(!this.hiddenInput)return;this.abortController=new AbortController;const{signal:t}=this.abortController;this.hiddenInput.addEventListener("input",this.handleTextInput,{signal:t}),this.hiddenInput.addEventListener("keydown",this.handleKeyDown,{signal:t}),this.hiddenInput.addEventListener("compositionstart",this.handleCompositionStart,{signal:t}),this.hiddenInput.addEventListener("compositionend",this.handleCompositionEnd,{signal:t}),this.hiddenInput.addEventListener("focus",this.handleFocus,{signal:t}),this.hiddenInput.addEventListener("blur",this.handleBlur,{signal:t}),this.hiddenInput.addEventListener("paste",this.handlePaste,{signal:t})}removeAllEventListeners(){this.abortController?.abort(),this.abortController=null}handleTextInput=t=>{if(!this.hiddenInput||this.isComposing)return;const e=this.hiddenInput.value,i=this.hiddenInput.selectionStart||0;this.lastSyncedText=e,this.textChangeCallback?.(e,i)};handleKeyDown=t=>{if(document.activeElement!==this.hiddenInput)return;let e=!1;if((t.ctrlKey||t.metaKey)&&(e=this.handleKeyboardShortcuts(t),e)){t.preventDefault();return}if(t.key==="Tab"){const i=t.shiftKey?"backward":"forward";this.eventHandlers.onTabNavigation?.(i),t.preventDefault();return}switch(t.key){case"Escape":this.eventHandlers.onEscape?.(t),e=!0;break;case"Enter":e=!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),e=!1;break;case"Backspace":case"Delete":e=!1;break;default:e=this.eventHandlers.onCustomKey?.(t.key,t)||!1;break}e&&t.preventDefault()};handleKeyboardShortcuts(t){const{key:e}=t;switch(e.toLowerCase()){case"a":return this.selectAll(),!0;case"c":case"v":return!1;case"z":return this.eventHandlers.onCustomKey?.("undo",t),!0;case"y":return this.eventHandlers.onCustomKey?.("redo",t),!0;default:return!1}}handleCompositionStart=t=>{this.isComposing=!0};handleCompositionEnd=t=>{if(this.isComposing=!1,this.hiddenInput){const e=this.hiddenInput.value,i=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(e,i)}};handleFocus=t=>{this.isFocused=!0,this.focusRetryCount=0,this.eventHandlers.onFocus?.(t)};handleBlur=t=>{this.isFocused=!1,this.eventHandlers.onBlur?.(t)};handlePaste=t=>{setTimeout(()=>{this.handleTextInput(t)},0)};selectAll(){this.hiddenInput&&this.hiddenInput.select()}}class us{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(t,e,i){this.parent=t,this.targetText=e,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 t=structuredClone(this.clipConfig);this.targetText.visible=!1,this.createEditingEnvironment(),this.setupOutsideClickHandler(t),this.isEditing=!0}stopEditing(t=!1,e){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,t&&e&&i!==""&&this.parent.updateTextContent(i,e),this.isEditing=!1}checkForDoubleClick=t=>{const e=Date.now();e-this.lastClickTime<us.DOUBLE_CLICK_THRESHOLD_MS&&this.startEditing(),this.lastClickTime=e};setupOutsideClickHandler(t){this.outsideClickHandler=e=>{const a=this.parent.getContainer().getBounds(),n=e.clientX,r=e.clientY;(n<a.x||n>a.x+a.width||r<a.y||r>a.y+a.height)&&(this.stopEditing(!0,t),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null))},setTimeout(()=>{this.outsideClickHandler&&window.addEventListener("click",this.outsideClickHandler)},us.CLICK_HANDLER_DELAY_MS)}createEditingEnvironment(){this.setupEditingContainer(),this.editingContainer&&this.editableText&&(this.textCursor=new ja(this.editingContainer,this.editableText,this.clipConfig),this.textCursor.updatePosition(this.targetText.text.length),this.textCursor.startBlinking()),this.setupTextInputHandler(),this.updateTextAlignment()}setupEditingContainer(){this.editingContainer=new X.Container,this.parent.getContainer().addChild(this.editingContainer);const t=new X.Graphics;t.fillStyle={color:0,alpha:us.EDITING_BG_ALPHA},t.rect(-5,-5,this.targetText.width+2*us.EDITING_BG_PADDING_PX,this.targetText.height+2*us.EDITING_BG_PADDING_PX),t.fill(),this.editingContainer.addChild(t),this.editableText=new X.Text(this.targetText.text,this.targetText.style),this.editableText.eventMode="static",this.editableText.cursor="text",this.editingContainer.addChild(this.editableText)}setupTextInputHandler(){this.textInputHandler=new ur,this.textInputHandler.setTextInputHandler((t,e)=>{this.editableText&&(this.editableText.text=t,this.updateTextAlignment()),this.textCursor?.updatePosition(e)}),this.textInputHandler.setEventHandlers({onEscape:t=>this.stopEditing(!1),onTabNavigation:t=>this.stopEditing(!0)}),this.textInputHandler.setupInput(this.targetText.text,{autoFocus:!0})}updateTextAlignment(){if(!this.editableText||!this.editingContainer)return;const t=this.getContainerDimensions(),e=this.getAlignmentSettings(),i=this.calculateHorizontalPosition({width:this.editableText.width},t,e.horizontal),a=this.calculateVerticalPosition({height:this.editableText.height},t,e.vertical);if(this.editingContainer.position.set(i,a),this.editingContainer.children.length>0){const n=this.editingContainer.getChildAt(0);n instanceof X.Graphics&&(n.clear(),n.fillStyle={color:0,alpha:us.EDITING_BG_ALPHA},n.rect(-5,-5,this.editableText.width+2*us.EDITING_BG_PADDING_PX,this.editableText.height+2*us.EDITING_BG_PADDING_PX),n.fill())}}calculateHorizontalPosition(t,e,i="center"){switch(i){case"center":return e.width/2-t.width/2;case"right":return e.width-t.width;case"left":default:return 0}}calculateVerticalPosition(t,e,i="center"){switch(i){case"center":return e.height/2-t.height/2;case"bottom":return e.height-t.height;case"top":default:return 0}}getContainerDimensions(){const t=this.clipConfig.asset;return{width:t.width??this.parent.getSize().width,height:t.height??this.parent.getSize().height}}getAlignmentSettings(){const t=this.clipConfig.asset;return{horizontal:t.alignment?.horizontal??"center",vertical:t.alignment?.vertical??"center"}}}class Ji extends je{static loadedFonts=new Set;background=null;text=null;textEditor=null;constructor(t,e){super(t,e,qt.Text)}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.font?.family??"Open Sans";if(await this.loadFont(e),this.background=new X.Graphics,this.drawBackground(),this.text=new X.Text({text:t.text??"",style:this.createTextStyle(t)}),this.positionText(t),t.stroke?.width&&t.stroke.width>0&&t.stroke.color){const i=new ba({thickness:t.stroke.width,color:t.stroke.color});this.text.filters=[i]}this.contentContainer.addChild(this.background),this.contentContainer.addChild(this.text),this.configureKeyframes(),this.textEditor=new us(this,this.text,this.clipConfiguration)}update(t,e){super.update(t,e)}reconfigureAfterRestore(){super.reconfigureAfterRestore(),this.reconfigure()}async reconfigure(){const t=this.clipConfiguration.asset,e=t.font?.family??"Open Sans";if(await this.loadFont(e),this.drawBackground(),this.text){if(this.text.text=t.text??"",this.text.style=this.createTextStyle(t),t.stroke?.width&&t.stroke.width>0&&t.stroke.color){const i=new ba({thickness:t.stroke.width,color:t.stroke.color});this.text.filters=[i]}else this.text.filters=[];this.positionText(t)}}dispose(){super.dispose(),this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null,this.textEditor?.dispose(),this.textEditor=null}getSize(){const t=this.clipConfiguration.asset;return{width:this.clipConfiguration.width??t.width??this.edit.size.width,height:this.clipConfiguration.height??t.height??this.edit.size.height}}getFitScale(){return 1}getContainerScale(){const t=this.getScale();return{x:t,y:t}}supportsEdgeResize(){return!0}onDimensionsChanged(){if(this.drawBackground(),this.text){const t=this.clipConfiguration.asset;this.text.style.wordWrapWidth=this.getSize().width,this.positionText(t)}}applyFixedDimensions(){}createTextStyle(t){const e=t.font?.family??"Open Sans",{baseFontFamily:i,fontWeight:a}=Rs(e),{width:n}=this.getSize();return new X.TextStyle({fontFamily:i,fontSize:t.font?.size??32,fill:t.font?.color??"#ffffff",fontWeight:a.toString(),wordWrap:!0,wordWrapWidth:n,lineHeight:(t.font?.lineHeight??1)*(t.font?.size??32),align:t.alignment?.horizontal??"center"})}positionText(t){if(!this.text)return;const e=t.alignment?.horizontal??"center",i=t.alignment?.vertical??"center",{width:a,height:n}=this.getSize();let r=a/2-this.text.width/2,o=n/2-this.text.height/2;e==="left"?r=0:e==="right"&&(r=a-this.text.width),i==="top"?o=0:i==="bottom"&&(o=n-this.text.height),this.text.position.set(r,o)}drawBackground(){const t=this.clipConfiguration.asset;if(!this.background||!t.background||!t.background.color)return;const{width:e,height:i}=this.getSize();this.background.clear(),this.background.fillStyle={color:t.background.color,alpha:t.background.opacity??1},this.background.rect(0,0,e,i),this.background.fill()}updateTextContent(t,e){this.edit.updateTextContent(this,t,e)}async loadFont(t){const{baseFontFamily:e,fontWeight:i}=Rs(t),a=`${e}-${i}`;if(Ji.loadedFonts.has(a))return;const n=Wr(t);if(n){const r=new FontFace(e,`url(${n})`,{weight:i.toString()});await r.load(),document.fonts.add(r),Ji.loadedFonts.add(a)}}static resetFontCache(){Ji.loadedFonts.clear()}}class tN extends je{texture;sprite;isPlaying;volumeKeyframeBuilder;syncTimer;activeSyncTimer;skipVideoUpdate;constructor(t,e){super(t,e,qt.Video),this.texture=null,this.sprite=null,this.isPlaying=!1;const i=this.clipConfiguration.asset;this.volumeKeyframeBuilder=new ga(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(t,e){if(super.update(t,e),this.skipVideoUpdate)return;const{trim:i=0}=this.clipConfiguration.asset;if(this.syncTimer+=e,!this.texture)return;const a=this.getPlaybackTime(),n=this.edit.isPlaying&&this.isActive();n&&(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+=e,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()))),!n&&this.isPlaying&&(this.isPlaying=!1,this.texture.source.resource.pause());const r=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&r&&(this.syncTimer=0,this.texture.source.resource.currentTime=a+i)}draw(){super.draw()}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 t=this.clipConfiguration.asset,{src:e}=t;if(e.endsWith(".mov"))throw new Error(`Video source '${e}' is not supported. .mov files cannot be played in the browser. Please convert to .webm or .mp4 first.`);const i={src:e,data:{autoPlay:!1,muted:!1}},a=await this.edit.assetLoader.loadVideoUnique(e,i);if(!a||!(a.source instanceof X.VideoSource))throw new Error(`Invalid video source '${e}'.`);a.source.alphaMode="no-premultiply-alpha",this.texture=this.createCroppedTexture(a);const n=this.texture.source.resource;n instanceof HTMLVideoElement&&n.readyState<2&&await new Promise(r=>{const o=()=>{n.removeEventListener("loadeddata",o),r()};n.addEventListener("loadeddata",o),n.readyState>=2&&r()}),this.sprite=new X.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:t=0}=this.clipConfiguration.asset,e=this.texture.source.resource.currentTime,i=this.getPlaybackTime();return Math.abs(e-t-i)}createCroppedTexture(t){const e=this.clipConfiguration.asset;if(!e.crop)return t;const i=t.width,a=t.height;if(i<=0||a<=0)return t;const n=Math.floor((e.crop?.left??0)*i),r=Math.floor((e.crop?.right??0)*i),o=Math.floor((e.crop?.top??0)*a),l=Math.floor((e.crop?.bottom??0)*a),c=n,d=o,u=i-n-r,f=a-o-l,p=new X.Rectangle(c,d,u,f);return new X.Texture({source:t.source,frame:p})}}const Qh=16711935,Jh=2,rl=6,$h=4;class eN{graphics;canvasWidth;canvasHeight;constructor(t,e,i){this.canvasWidth=e,this.canvasHeight=i,this.graphics=new X.Graphics,this.graphics.zIndex=999999,t.addChild(this.graphics)}clear(){this.graphics.clear()}drawCanvasGuide(t,e){this.graphics.strokeStyle={width:Jh,color:Qh},t==="x"?(this.graphics.moveTo(e,0),this.graphics.lineTo(e,this.canvasHeight)):(this.graphics.moveTo(0,e),this.graphics.lineTo(this.canvasWidth,e)),this.graphics.stroke()}drawClipGuide(t,e,i,a){t==="x"?this.drawDashedLine(e,i,e,a):this.drawDashedLine(i,e,a,e)}drawDashedLine(t,e,i,a){const n=i-t,r=a-e,o=Math.sqrt(n*n+r*r),l=Math.floor(o/(rl+$h)),c=n/o,d=r/o;this.graphics.strokeStyle={width:Jh,color:Qh};for(let u=0;u<l;u+=1){const f=u*(rl+$h),p=f+rl,y=t+c*f,v=e+d*f,S=t+c*Math.min(p,o),x=e+d*Math.min(p,o);this.graphics.moveTo(y,v),this.graphics.lineTo(S,x)}this.graphics.stroke()}dispose(){this.graphics.destroy()}}const sN=/^alias:\/\/([a-zA-Z0-9_-]+)$/;function ol(s,t){for(let e=0;e<s.timeline.tracks.length;e+=1){const i=s.timeline.tracks[e];for(let a=0;a<i.clips.length;a+=1)t(i.clips[a],e,a)}}function hr(s){if(typeof s!="string")return null;const t=s.match(sN);return t?t[1]:null}function iN(s){const t={};return ol(s,(e,i,a)=>{e.alias&&(t[e.alias]&&console.warn(`Duplicate alias "${e.alias}" at track ${i}, clip ${a} - overwriting previous`),t[e.alias]=e)}),t}function aN(s){const t=new Map;return ol(s,(e,i,a)=>{const n=e.alias??`t${i}c${a}`,r=new Set,o=hr(e.start);o&&r.add(o);const l=hr(e.length);l&&r.add(l),r.size>0&&t.set(n,r)}),t}function nN(s){const t=new Set,e=new Set;function i(a,n){t.add(a),e.add(a);const r=s.get(a);if(r)for(const o of r){if(e.has(o))return[...n,o];if(!t.has(o)){const l=i(o,[...n,o]);if(l)return l}}return e.delete(a),null}for(const a of s.keys())if(!t.has(a)){const n=i(a,[a]);if(n)return n}return null}function rN(s,t){const e=[],i=new Set,a=new Set([...s.keys(),...Object.keys(t)]);function n(r){if(i.has(r))return;i.add(r);const o=s.get(r);if(o)for(const l of o)n(l);e.push(r)}for(const r of a)n(r);return e}function oN(s){const t=aN(s);if(t.size===0)return;const e=nN(t);if(e)throw new Error(`Circular alias reference detected: ${e.join(" -> ")}`);const i=iN(s),a=new Map;ol(s,(r,o,l)=>{const c=r.alias??`t${o}c${l}`;a.set(c,r)});const n=rN(t,i);for(const r of n){const o=a.get(r);if(o){const l=hr(o.start);if(l){const d=i[l];if(!d)throw new Error(`Alias "${l}" not found. Available: ${Object.keys(i).join(", ")||"none"}`);if(typeof d.start!="number")throw new Error(`Cannot resolve alias "${l}": target has unresolved start`);o.start=d.start}const c=hr(o.length);if(c){const d=i[c];if(!d)throw new Error(`Alias "${c}" not found. Available: ${Object.keys(i).join(", ")||"none"}`);if(typeof d.length!="number")throw new Error(`Cannot resolve alias "${c}": target has unresolved length`);o.length=d.length}}}}class lN{constructor(t,e){this.trackIdx=t,this.clip=e}name="addClip";addedPlayer;async execute(t){if(t)try{const e=t.createPlayerFromAssetType(this.clip);e.layer=this.trackIdx+1,await t.addPlayer(this.trackIdx,e);const n=t.getClips().filter(r=>r.layer===e.layer).findIndex(r=>r===e);t.updateDuration(),t.emitEvent(j.ClipAdded,{trackIndex:this.trackIdx,clipIndex:n}),this.addedPlayer=e}catch(e){const i=this.clip.asset.type??"unknown";t.emitEvent(j.ClipLoadFailed,{trackIndex:this.trackIdx,clipIndex:-1,error:e instanceof Error?e.message:String(e),assetType:i})}}async undo(t){if(!t||!this.addedPlayer)return;const a=t.getClips().filter(n=>n.layer===this.addedPlayer.layer).findIndex(n=>n===this.addedPlayer);t.queueDisposeClip(this.addedPlayer),t.updateDuration(),t.emitEvent(j.ClipDeleted,{trackIndex:this.trackIdx,clipIndex:a})}}class tf{constructor(t){this.trackIdx=t}name="addTrack";execute(t){if(!t)return;const e=t.getTracks(),i=t.getClips();e.splice(this.trackIdx,0,[]),i.forEach(a=>{if(a.layer>this.trackIdx){const n=1e5-a.layer*100,r=t.getContainer().getChildByLabel(`shotstack-track-${n}`,!1);r&&r.removeChild(a.getContainer()),a.layer+=1;const o=1e5-a.layer*100;let l=t.getContainer().getChildByLabel(`shotstack-track-${o}`,!1);l||(l=new X.Container({label:`shotstack-track-${o}`,zIndex:o}),t.getContainer().addChild(l)),l.addChild(a.getContainer())}}),t.getContainer().sortDirty=!0,t.updateDuration(),t.emitEvent(j.TrackAdded,{trackIndex:this.trackIdx,totalTracks:e.length})}undo(t){if(!t)return;const e=t.getTracks(),i=t.getClips();e.splice(this.trackIdx,1),i.forEach(a=>{if(a.layer>this.trackIdx){const n=1e5-a.layer*100,r=t.getContainer().getChildByLabel(`shotstack-track-${n}`,!1);r&&r.removeChild(a.getContainer()),a.layer-=1;const o=1e5-a.layer*100;let l=t.getContainer().getChildByLabel(`shotstack-track-${o}`,!1);l||(l=new X.Container({label:`shotstack-track-${o}`,zIndex:o}),t.getContainer().addChild(l)),l.addChild(a.getContainer())}}),t.getContainer().sortDirty=!0,t.updateDuration()}}class cN{name="ClearSelection";previousSelection=null;execute(t){const e=t.getSelectedClip();if(e){const i=t.findClipIndices(e);i&&(this.previousSelection={player:e,trackIndex:i.trackIndex,clipIndex:i.clipIndex})}t.setSelectedClip(null),t.emitEvent(j.SelectionCleared)}undo(t){if(this.previousSelection){const e=t.getClipAt(this.previousSelection.trackIndex,this.previousSelection.clipIndex);e&&(t.setSelectedClip(e),t.emitEvent(j.ClipSelected,{clip:e.clipConfiguration,trackIndex:this.previousSelection.trackIndex,clipIndex:this.previousSelection.clipIndex}))}}}class ll{constructor(t){this.trackIdx=t}name="deleteTrack";deletedClips=[];execute(t){if(!t)return;const e=t.getClips(),i=t.getTracks();this.deletedClips=e.filter(r=>r.layer===this.trackIdx+1).map(r=>({config:structuredClone(r.clipConfiguration),bindings:new Map(r.getMergeFieldBindings())})),e.forEach((r,o)=>{r.layer===this.trackIdx+1&&(e[o].shouldDispose=!0)}),t.disposeClips(),i.splice(this.trackIdx,1);const a=t.getClips(),n=t.getContainer();a.forEach((r,o)=>{if(r.layer>this.trackIdx+1){n.getChildByLabel(`shotstack-track-${1e5-r.layer*100}`,!1)?.removeChild(r.getContainer()),a[o].layer-=1;const c=1e5-a[o].layer*100;let d=n.getChildByLabel(`shotstack-track-${c}`,!1);d||(d=new X.Container({label:`shotstack-track-${c}`,zIndex:c}),n.addChild(d)),d.addChild(a[o].getContainer())}}),t.updateDuration(),t.emitEvent(j.TrackRemoved,{trackIndex:this.trackIdx})}async undo(t){if(!t)return;const e=t.getTracks(),i=t.getClips();e.splice(this.trackIdx,0,[]),i.forEach((a,n)=>{a.layer>=this.trackIdx+1&&(i[n].layer+=1)});for(const{config:a,bindings:n}of this.deletedClips){const r=t.createPlayerFromAssetType(a);r.layer=this.trackIdx+1,n.size>0&&r.setInitialBindings(n),await t.addPlayer(this.trackIdx,r)}t.updateDuration()}}class fr{constructor(t,e){this.trackIdx=t,this.clipIdx=e}name="deleteClip";deletedClip;deleteTrackCommand;trackWasDeleted=!1;execute(t){if(!t)return;const e=t.getClips(),i=t.getTracks(),a=e.filter(n=>n.layer===this.trackIdx+1);if(this.deletedClip=a[this.clipIdx],t.clearClipError(this.trackIdx,this.clipIdx),this.deletedClip){t.queueDisposeClip(this.deletedClip),t.disposeClips(),t.updateDuration(),t.propagateTimingChanges(this.trackIdx,this.clipIdx-1);const n=i[this.trackIdx];n&&n.length===0&&(this.deleteTrackCommand=new ll(this.trackIdx),this.deleteTrackCommand.execute(t),this.trackWasDeleted=!0),t.emitEvent(j.ClipDeleted,{trackIndex:this.trackIdx,clipIndex:this.clipIdx}),t.getSelectedClip()===this.deletedClip&&(t.setSelectedClip(null),t.emitEvent(j.SelectionCleared))}}async undo(t){!t||!this.deletedClip||(this.trackWasDeleted&&this.deleteTrackCommand&&(await this.deleteTrackCommand.undo(t),this.trackWasDeleted=!1),t.undeleteClip(this.trackIdx,this.deletedClip),t.propagateTimingChanges(this.trackIdx,this.clipIdx),t.emitEvent(j.ClipRestored,{trackIndex:this.trackIdx,clipIndex:this.clipIdx}))}}class dN{constructor(t,e){this.trackIndex=t,this.clipIndex=e}name="SelectClip";previousSelection=null;execute(t){const e=t.getSelectedClip();if(e){const a=t.findClipIndices(e);a&&(this.previousSelection=a)}const i=t.getClipAt(this.trackIndex,this.clipIndex);i&&(t.setSelectedClip(i),t.emitEvent(j.ClipSelected,{clip:i.clipConfiguration,trackIndex:this.trackIndex,clipIndex:this.clipIndex}))}undo(t){if(t.setSelectedClip(null),this.previousSelection){const e=t.getClipAt(this.previousSelection.trackIndex,this.previousSelection.clipIndex);e&&(t.setSelectedClip(e),t.emitEvent(j.ClipSelected,{clip:e.clipConfiguration,trackIndex:this.previousSelection.trackIndex,clipIndex:this.previousSelection.clipIndex}))}else t.emitEvent(j.SelectionCleared)}}class ef{constructor(t,e,i,a){this.clip=t,this.initialClipConfig=e,this.finalClipConfig=i,this.storedInitialConfig=e?structuredClone(e):null,this.storedFinalConfig=i?structuredClone(i):structuredClone(this.clip.clipConfiguration),this.trackIndex=a?.trackIndex??-1,this.clipIndex=a?.clipIndex??-1}name="setUpdatedClip";storedInitialConfig;storedFinalConfig;storedInitialBindings=new Map;trackIndex;clipIndex;storedInitialTiming=null;async execute(t){if(!t)return;this.storedInitialBindings=new Map(this.clip.getMergeFieldBindings()),this.storedFinalConfig&&t.restoreClipConfiguration(this.clip,this.storedFinalConfig);const e=this.storedFinalConfig.start!==this.storedInitialConfig?.start,i=this.storedFinalConfig.length!==this.storedInitialConfig?.length;(e||i)&&(this.storedInitialTiming={start:this.clip.getStart(),length:this.clip.getLength()},this.clip.setTimingIntent({start:this.storedFinalConfig.start,length:this.storedFinalConfig.length}),this.clip.setResolvedTiming({start:this.storedFinalConfig.start,length:this.storedFinalConfig.length})),t.setUpdatedClip(this.clip);for(const[u,{resolvedValue:f}]of this.storedInitialBindings)Ei(this.clip.clipConfiguration,u)!==f&&this.clip.removeMergeFieldBinding(u);const a=this.trackIndex>=0?this.trackIndex:this.clip.layer-1,r=t.getClips().filter(u=>u.layer===this.clip.layer),o=this.clipIndex>=0?this.clipIndex:r.indexOf(this.clip),l=this.storedInitialConfig?.asset,c=this.storedFinalConfig?.asset;l?.src!==c?.src&&this.clip.getTimingIntent().length==="auto"&&await t.resolveClipAutoLength(this.clip);const d=this.storedInitialConfig??this.initialClipConfig??this.clip.clipConfiguration;t.emitEvent(j.ClipUpdated,{previous:{clip:d,trackIndex:a,clipIndex:o},current:{clip:this.storedFinalConfig,trackIndex:a,clipIndex:o}})}async undo(t){if(!t||!this.storedInitialConfig)return;t.restoreClipConfiguration(this.clip,this.storedInitialConfig),this.storedInitialTiming&&(this.clip.setTimingIntent({start:this.storedInitialTiming.start,length:this.storedInitialTiming.length}),this.clip.setResolvedTiming({start:this.storedInitialTiming.start,length:this.storedInitialTiming.length})),t.setUpdatedClip(this.clip),this.clip.setInitialBindings(this.storedInitialBindings);const e=this.trackIndex>=0?this.trackIndex:this.clip.layer-1,a=t.getClips().filter(l=>l.layer===this.clip.layer),n=this.clipIndex>=0?this.clipIndex:a.indexOf(this.clip),r=this.storedFinalConfig?.asset,o=this.storedInitialConfig?.asset;r?.src!==o?.src&&this.clip.getTimingIntent().length==="auto"&&await t.resolveClipAutoLength(this.clip),t.emitEvent(j.ClipUpdated,{previous:{clip:this.storedFinalConfig,trackIndex:e,clipIndex:n},current:{clip:this.storedInitialConfig,trackIndex:e,clipIndex:n}})}}class uN{constructor(t,e,i){this.trackIndex=t,this.clipIndex=e,this.splitTime=i}name="SplitClip";originalClipConfig=null;rightClipPlayer=null;splitSuccessful=!1;originalBindings=new Map;execute(t){const e=t.getClipAt(this.trackIndex,this.clipIndex);if(!e||!e.clipConfiguration)throw new Error("Cannot split clip: invalid player or clip configuration");const i=e.clipConfiguration,a=i.start,n=i.length,r=.1,o=this.splitTime-a;if(o<=r||o>=n-r)throw new Error("Cannot split clip: split point too close to clip boundaries");this.originalClipConfig={...i},this.originalBindings=new Map(e.getMergeFieldBindings());const l={...i,length:o},c={...i,start:a+o,length:n-o};if(i.asset&&(l.asset={...i.asset},c.asset={...i.asset}),i.asset&&(i.asset.type==="video"||i.asset.type==="audio")){const p=i.asset.trim||0;l.asset&&(l.asset.type==="video"||l.asset.type==="audio")&&(l.asset.trim=p),c.asset&&(c.asset.type==="video"||c.asset.type==="audio")&&(c.asset.trim=p+o)}if(Object.assign(e.clipConfiguration,l),e.reconfigureAfterRestore(),e.draw(),this.rightClipPlayer=t.createPlayerFromAssetType(c),!this.rightClipPlayer)throw Object.assign(e.clipConfiguration,this.originalClipConfig),e.reconfigureAfterRestore(),new Error("Failed to create right clip player");this.rightClipPlayer.layer=this.trackIndex+1,this.originalBindings.size>0&&this.rightClipPlayer.setInitialBindings(this.originalBindings);const d=t.getTrack(this.trackIndex);if(!d)throw new Error("Invalid track index");d.splice(this.clipIndex+1,0,this.rightClipPlayer);const u=t.getClips(),f=u.indexOf(e);f!==-1&&u.splice(f+1,0,this.rightClipPlayer),t.addPlayerToContainer(this.trackIndex,this.rightClipPlayer),this.rightClipPlayer.reconfigureAfterRestore(),this.rightClipPlayer.load().then(()=>{this.splitSuccessful=!0,this.rightClipPlayer&&this.rightClipPlayer.draw(),t.updateDuration(),t.emitEvent(j.ClipSplit,{trackIndex:this.trackIndex,originalClipIndex:this.clipIndex,newClipIndex:this.clipIndex+1})}).catch(p=>{console.error("Failed to load split clip:",p)})}undo(t){if(!this.originalClipConfig)return;const e=t.getClipAt(this.trackIndex,this.clipIndex);if(e){if(Object.assign(e.clipConfiguration,this.originalClipConfig),e.reconfigureAfterRestore(),this.rightClipPlayer){const i=t.getTrack(this.trackIndex);if(i){const r=i.indexOf(this.rightClipPlayer);r!==-1&&i.splice(r,1)}const a=t.getClips(),n=a.indexOf(this.rightClipPlayer);n!==-1&&a.splice(n,1),t.queueDisposeClip(this.rightClipPlayer),this.rightClipPlayer=null}t.updateDuration(),t.emitEvent(j.ClipDeleted,{trackIndex:this.trackIndex,clipIndex:this.clipIndex+1})}}}class sf{constructor(t,e,i){this.trackIndex=t,this.clipIndex=e,this.targetAssetType=i}name="TransformClipAsset";originalPlayer=null;originalConfig=null;originalAssetType=null;originalBindings=new Map;newPlayer=null;loadCompleted=!1;execute(t){const e=t.getClipAt(this.trackIndex,this.clipIndex);if(!e?.clipConfiguration)throw new Error("Cannot transform clip: invalid player");this.originalPlayer=e,this.originalConfig={...e.clipConfiguration},this.originalAssetType=this.originalConfig.asset?.type??null,this.originalBindings=new Map(e.getMergeFieldBindings()),this.loadCompleted=!1;const i=this.originalConfig.asset;if(!i.src)throw new Error("Cannot transform clip: asset has no src property");const a={type:this.targetAssetType,src:i.src},n={...this.originalConfig,asset:a};if(this.newPlayer=t.createPlayerFromAssetType(n),!this.newPlayer)throw new Error("Failed to create transformed player");this.newPlayer.layer=this.trackIndex+1,this.originalBindings.size>0&&this.newPlayer.setInitialBindings(this.originalBindings);const r=t.getTrack(this.trackIndex);if(!r)throw new Error("Invalid track index");r[this.clipIndex]=this.newPlayer;const o=t.getClips(),l=o.indexOf(this.originalPlayer);l!==-1&&(o[l]=this.newPlayer),t.addPlayerToContainer(this.trackIndex,this.newPlayer),this.newPlayer.reconfigureAfterRestore(),this.newPlayer.load().then(()=>{this.loadCompleted=!0,this.newPlayer&&this.newPlayer.draw(),t.emitEvent(j.ClipUpdated,{previous:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:this.originalConfig},current:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:n}}),this.originalPlayer&&t.queueDisposeClip(this.originalPlayer)}).catch(c=>{console.error("Failed to load transformed clip:",c)})}undo(t){if(!this.originalPlayer||!this.originalConfig)return;const e=t.getTrack(this.trackIndex);e&&this.newPlayer&&(e[this.clipIndex]=this.originalPlayer);const i=t.getClips();if(this.newPlayer){const a=i.indexOf(this.newPlayer);a!==-1&&(i[a]=this.originalPlayer)}t.addPlayerToContainer(this.trackIndex,this.originalPlayer),this.originalPlayer.reconfigureAfterRestore(),this.originalPlayer.draw(),this.newPlayer&&t.queueDisposeClip(this.newPlayer),t.emitEvent(j.ClipUpdated,{previous:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:this.newPlayer?.clipConfiguration},current:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:this.originalConfig}}),this.newPlayer=null}getOriginalAssetType(){return this.originalAssetType}isLoadCompleted(){return this.loadCompleted}}const hN=3;function fN(s){return new Promise(t=>{const e=document.createElement("video");e.preload="metadata",e.crossOrigin="anonymous",e.onloadedmetadata=()=>t(e.duration),e.onerror=()=>t(null),e.src=s})}async function af(s){const t=s;if(["video","audio","luma"].includes(t.type)&&t.src){const e=await fN(t.src);if(e!==null&&!Number.isNaN(e)){const i=t.trim??0;return e-i}}return hN}function pr(s,t,e){return t===0?0:e[s][t-1].getEnd()}function nf(s,t){return Math.max(0,t-s)}function cl(s){let t=0;for(const e of s)for(const i of e)i.getTimingIntent().length!=="end"&&(t=Math.max(t,i.getEnd()));return t}class pN{constructor(t,e,i){this.trackIndex=t,this.clipIndex=e,this.params=i}name="UpdateClipTiming";player=null;originalIntent=null;previousConfig=null;execute(t){if(!t)return;const e=t.getTrack(this.trackIndex);if(!e||this.clipIndex<0||this.clipIndex>=e.length){console.warn(`Invalid track/clip index: ${this.trackIndex}/${this.clipIndex}`);return}this.player=e[this.clipIndex],this.originalIntent=this.player.getTimingIntent(),this.previousConfig=JSON.parse(JSON.stringify(this.player.clipConfiguration));const i={start:this.originalIntent.start,length:this.originalIntent.length};this.params.start!==void 0&&(i.start=this.params.start==="auto"?"auto":this.params.start/1e3),this.params.length!==void 0&&(this.params.length==="auto"||this.params.length==="end"?i.length=this.params.length:i.length=this.params.length/1e3),this.player.setTimingIntent(i),this.updateClipConfiguration(this.player,i);const a=i.start==="auto"?pr(this.trackIndex,this.clipIndex,t.getTracks()):i.start;if(i.length==="auto")this.player.setResolvedTiming({start:a,length:this.player.getLength()}),t.resolveClipAutoLength(this.player).then(()=>{this.player?.reconfigureAfterRestore(),this.player?.draw(),t.updateDuration(),t.propagateTimingChanges(this.trackIndex,this.clipIndex)}),this.player.reconfigureAfterRestore(),this.player.draw();else if(i.length==="end"){t.trackEndLengthClip(this.player);const n=cl(t.getTracks()),r=Math.max(n-a,.1);this.player.setResolvedTiming({start:a,length:r}),this.player.reconfigureAfterRestore(),this.player.draw()}else t.untrackEndLengthClip(this.player),this.player.setResolvedTiming({start:a,length:i.length}),this.player.reconfigureAfterRestore(),this.player.draw();t.updateDuration(),t.emitEvent(j.ClipUpdated,{previous:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:this.previousConfig},current:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:this.player.clipConfiguration}}),t.propagateTimingChanges(this.trackIndex,this.clipIndex)}undo(t){!t||!this.player||!this.originalIntent||(this.player.setTimingIntent(this.originalIntent),this.previousConfig&&t.restoreClipConfiguration(this.player,this.previousConfig),this.originalIntent.length==="auto"?t.resolveClipAutoLength(this.player):this.originalIntent.length==="end"?t.trackEndLengthClip(this.player):t.untrackEndLengthClip(this.player),this.player.reconfigureAfterRestore(),this.player.draw(),t.updateDuration(),t.emitEvent(j.ClipUpdated,{previous:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:this.player.clipConfiguration},current:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:this.previousConfig}}),t.propagateTimingChanges(this.trackIndex,this.clipIndex))}updateClipConfiguration(t,e){const i=t.clipConfiguration;e.start!=="auto"&&(i.start=e.start),e.length!=="auto"&&e.length!=="end"&&(i.length=e.length)}}class gN{constructor(t,e,i){this.clip=t,this.newText=e,this.initialConfig=i;const{asset:a}=this.clip.clipConfiguration;this.previousText=a&&"text"in a?a.text??"":""}name="updateTextContent";previousText;execute(t){if(t&&this.clip.clipConfiguration.asset&&"text"in this.clip.clipConfiguration.asset){this.clip.clipConfiguration.asset.text=this.newText;const e=this.clip.text;e&&(e.text=this.newText,this.clip.positionText(this.clip.clipConfiguration.asset)),t.setUpdatedClip(this.clip);const i=this.clip.layer-1,r=t.getClips().filter(o=>o.layer===this.clip.layer).indexOf(this.clip);t.emitEvent(j.ClipUpdated,{previous:{clip:this.initialConfig,trackIndex:i,clipIndex:r},current:{clip:this.clip.clipConfiguration,trackIndex:i,clipIndex:r}})}}undo(t){if(t&&this.clip.clipConfiguration.asset&&"text"in this.clip.clipConfiguration.asset){this.clip.clipConfiguration.asset.text=this.previousText;const e=this.clip.text;e&&(e.text=this.previousText,this.clip.positionText(this.clip.clipConfiguration.asset)),t.setUpdatedClip(this.clip);const i=this.clip.layer-1,r=t.getClips().filter(o=>o.layer===this.clip.layer).indexOf(this.clip);t.emitEvent(j.ClipUpdated,{previous:{clip:this.clip.clipConfiguration,trackIndex:i,clipIndex:r},current:{clip:this.initialConfig,trackIndex:i,clipIndex:r}})}}}class dl{events;constructor(){this.events={}}on(t,e){return this.events[t]||(this.events[t]=new Set),this.events[t].add(e),()=>this.off(t,e)}once(t,e){const i=a=>{this.off(t,i),e(a)};return this.on(t,i)}off(t,e){this.events[t]&&(this.events[t].delete(e),!(this.events[t].size>0)&&delete this.events[t])}clear(t){delete this.events[t]}emit(t,...e){if(!this.events[t])return;const i=e[0];for(const a of this.events[t])a(i)}}class mN{constructor(t,e,i){this.getCanvas=t,this.getTracks=e,this.events=i,this.onClipChangedBound=()=>this.rebuildLumaMasksIfNeeded()}activeLumaMasks=[];pendingMaskCleanup=[];onClipChangedBound;initialize(){this.finalizeLumaMasking(),this.setupEventListeners()}update(){this.updateLumaMasks(),this.processPendingMaskCleanup()}getActiveMaskCount(){return this.activeLumaMasks.length}dispose(){this.removeEventListeners();for(const t of this.activeLumaMasks)t.tempContainer.destroy({children:!0}),t.maskSprite.destroy({texture:!0});this.activeLumaMasks=[];for(const t of this.pendingMaskCleanup)try{t.maskSprite.parent?.removeChild(t.maskSprite),t.maskSprite.destroy({texture:!0})}catch{}this.pendingMaskCleanup=[]}cleanupForPlayer(t){const e=this.activeLumaMasks.findIndex(a=>a.lumaPlayer===t);if(e===-1)return;const i=this.activeLumaMasks[e];i.contentClip&&(i.contentClip.getContentContainer().mask=null),i.maskSprite.parent?.removeChild(i.maskSprite),i.tempContainer.destroy({children:!0}),this.activeLumaMasks.splice(e,1),this.pendingMaskCleanup.push({maskSprite:i.maskSprite,frameCount:0})}finalizeLumaMasking(){if(!this.getCanvas())return;const e=this.getTracks();for(const i of e){const a=i.find(o=>o.playerType===qt.Luma),n=a?.getSprite(),r=i.filter(o=>o.playerType!==qt.Luma);a&&n?.texture&&r.length>0&&(this.setupLumaMask(a,n.texture,r[0]),a.getContainer().parent?.removeChild(a.getContainer()))}}setupLumaMask(t,e,i){const a=this.getCanvas();if(!a)return;const{renderer:n}=a.application,{width:r,height:o}=i.getSize(),l=new X.Container,c=new X.Sprite(e);c.width=r,c.height=o;const d=new X.ColorMatrixFilter;d.negative(!1),c.filters=[d],l.addChild(c);const u=n.generateTexture({target:l,resolution:.5}),f=new X.Sprite(u);i.getContainer().addChild(f),i.getContentContainer().setMask({mask:f}),this.activeLumaMasks.push({lumaPlayer:t,maskSprite:f,tempContainer:l,contentClip:i,lastVideoTime:-1})}updateLumaMasks(){const t=this.getCanvas();if(!t)return;const{renderer:e}=t.application,i=1/30;for(const a of this.activeLumaMasks)if(a.lumaPlayer.isVideoSource()){const n=a.lumaPlayer.getVideoCurrentTime();if(Math.abs(n-a.lastVideoTime)>=i){a.lastVideoTime=n;const o=a.maskSprite.texture;a.maskSprite.texture=e.generateTexture({target:a.tempContainer,resolution:.5}),o.destroy(!0)}}}setupEventListeners(){this.events.on(j.ClipAdded,this.onClipChangedBound),this.events.on(j.ClipSplit,this.onClipChangedBound),this.events.on(j.ClipUpdated,this.onClipChangedBound),this.events.on(j.ClipRestored,this.onClipChangedBound),this.events.on(j.ClipDeleted,this.onClipChangedBound)}removeEventListeners(){this.events.off(j.ClipAdded,this.onClipChangedBound),this.events.off(j.ClipSplit,this.onClipChangedBound),this.events.off(j.ClipUpdated,this.onClipChangedBound),this.events.off(j.ClipRestored,this.onClipChangedBound),this.events.off(j.ClipDeleted,this.onClipChangedBound)}processPendingMaskCleanup(){for(let t=this.pendingMaskCleanup.length-1;t>=0;t-=1){const e=this.pendingMaskCleanup[t];if(e.frameCount+=1,e.frameCount>=3){try{e.maskSprite.parent?.removeChild(e.maskSprite),e.maskSprite.destroy({texture:!0})}catch{}this.pendingMaskCleanup.splice(t,1)}}}async rebuildLumaMasksIfNeeded(){if(!this.getCanvas())return;const e=this.getTracks();for(let i=0;i<e.length;i+=1){const a=e[i],n=a.find(l=>l.playerType===qt.Luma),r=a.filter(l=>l.playerType!==qt.Luma);n&&n.getContainer().parent?.removeChild(n.getContainer());const o=n&&this.activeLumaMasks.find(l=>l.lumaPlayer===n);if(n&&!o&&r.length>0){n.getSprite()||await n.load();const l=n.getSprite();l?.texture&&(this.setupLumaMask(n,l.texture,r[0]),n.getContainer().parent?.removeChild(n.getContainer()))}}}}function yN(s){return{find:s.name,replace:s.defaultValue}}function bN(s){const t=typeof s.replace=="string"?s.replace:JSON.stringify(s.replace);return{name:s.find,defaultValue:t}}const wN=/\{\{\s*([A-Z_0-9]+)\s*\}\}/gi,ul=/\{\{\s*[A-Z_0-9]+\s*\}\}/i;class vN{fields=new Map;events;constructor(t){this.events=t}register(t,e){const i=!this.fields.has(t.name);this.fields.set(t.name,t),e?.silent||(this.events.emit(i?j.MergeFieldRegistered:j.MergeFieldUpdated,{field:t}),this.events.emit(j.MergeFieldChanged,{fields:this.getAll()}))}remove(t,e){const i=this.fields.delete(t);return i&&!e?.silent&&(this.events.emit(j.MergeFieldRemoved,{name:t}),this.events.emit(j.MergeFieldChanged,{fields:this.getAll()})),i}get(t){return this.fields.get(t)}getAll(){return Array.from(this.fields.values())}clear(){this.fields.clear()}resolve(t){return!t||this.fields.size===0?t:t.replace(wN,(e,i)=>this.fields.get(i)?.defaultValue??e)}hasUnresolved(t){if(!t)return!1;const e=this.resolve(t);return ul.test(e)}extractFieldName(t){if(!t)return null;const e=ul.exec(t);if(!e)return null;const i=e[0].match(/\{\{\s*([A-Z_0-9]+)\s*\}\}/i);return i?i[1]:null}isMergeFieldTemplate(t){return ul.test(t)}createTemplate(t){return`{{ ${t} }}`}toSerializedArray(){return this.getAll().map(yN)}loadFromSerialized(t){this.fields.clear();for(const e of t)this.fields.set(e.find,bN(e))}generateUniqueName(t){const e=new Set(this.fields.keys());let i=1;for(;e.has(`${t}_${i}`);)i+=1;return`${t}_${i}`}}function xN(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function hl(s,t){if(typeof s=="string"){let e=s;for(const{find:i,replace:a}of t){const n=typeof a=="string"?a:JSON.stringify(a);e=e.replace(new RegExp(`\\{\\{\\s*${xN(i)}\\s*\\}\\}`,"gi"),n)}return e}if(Array.isArray(s))return s.map(e=>hl(e,t));if(s!==null&&typeof s=="object"){const e=s;for(const i of Object.keys(e))e[i]=hl(e[i],t)}return s}function CN(s,t){return t?.length?hl(structuredClone(s),t):s}class kN extends dl{registry;constructor(){super(),this.registry={}}}class gr{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 kN;refCounts=new Map;incrementRef(t){this.refCounts.set(t,(this.refCounts.get(t)??0)+1)}decrementRef(t){const e=this.refCounts.get(t)??0;return e<=1?(this.refCounts.delete(t),!0):(this.refCounts.set(t,e-1),!1)}constructor(){X.Assets.setPreferences({crossOrigin:"anonymous"})}async load(t,e){this.updateAssetLoadMetadata(t,"pending",0),this.incrementRef(t);try{if(await this.shouldUseSafariVideoLoader(e))return await this.loadVideoForSafari(t,e);const a=await X.Assets.load(e,n=>{this.updateAssetLoadMetadata(t,"loading",n)});return this.updateAssetLoadMetadata(t,"success",1),a}catch{return this.updateAssetLoadMetadata(t,"failed",1),this.decrementRef(t),null}}async loadVideoUnique(t,e){this.updateAssetLoadMetadata(t,"pending",0);try{const i=this.extractUrl(e);if(!i)throw new Error("No URL provided for video loading");const a=typeof e=="object"?e.data??{}:{},n=await new Promise((r,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 X.VideoSource({resource:l,autoPlay:a.autoPlay??!1,...a});r(new X.Texture({source:c}))}catch(c){o(c)}},{once:!0}),l.addEventListener("error",()=>o(new Error("Video loading failed")),{once:!0}),this.updateAssetLoadMetadata(t,"loading",.5),l.src=i});return this.updateAssetLoadMetadata(t,"success",1),n}catch{return this.updateAssetLoadMetadata(t,"failed",1),null}}getProgress(){const t=Object.keys(this.loadTracker.registry);return t.length===0?0:t.reduce((i,a)=>i+this.loadTracker.registry[a].progress,0)/t.length}extractUrl(t){if(typeof t=="string")return t;const e=Array.isArray(t.src)?t.src[0]:t.src;return typeof e=="string"?e:e?.src}hasVideoExtension(t){const e=new URL(t,window.location.origin).pathname.toLowerCase();return gr.VIDEO_EXTENSIONS.some(i=>e.endsWith(i))}async getContentType(t){try{return(await fetch(t,{method:"HEAD"})).headers.get("content-type")}catch{return null}}canPlayVideo(t){const e=new URL(t,window.location.origin).pathname.toLowerCase(),i=e.slice(e.lastIndexOf(".")),a=gr.VIDEO_MIME[i];return a?document.createElement("video").canPlayType(a)!=="":!1}async isPlayableVideo(t){if(this.hasVideoExtension(t))return this.canPlayVideo(t);const e=await this.getContentType(t);return e?.startsWith("video/")?document.createElement("video").canPlayType(e)!=="":!1}async shouldUseSafariVideoLoader(t){const e=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),i=this.extractUrl(t);return e&&i!==void 0&&await this.isPlayableVideo(i)}async loadVideoForSafari(t,e){const i=this.extractUrl(e),a=typeof e=="object"?e.data??{}:{},n=await new Promise((r,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 X.VideoSource({resource:l,autoPlay:a.autoPlay??!1,...a});r(new X.Texture({source:c}))}catch(c){o(c)}},{once:!0}),l.addEventListener("error",()=>o(new Error("Video loading failed")),{once:!0}),this.updateAssetLoadMetadata(t,"loading",.5),l.src=i});return this.updateAssetLoadMetadata(t,"success",1),n}updateAssetLoadMetadata(t,e,i){this.loadTracker.registry[t]?(this.loadTracker.registry[t].progress=i,this.loadTracker.registry[t].status=e):this.loadTracker.registry[t]={progress:i,status:e};const a={...this.loadTracker.registry};this.loadTracker.emit("onAssetLoadInfoUpdated",{registry:a})}}class Ya{static Name="FontLoadParser";id;name;extension;validFontExtensions;woff2Decompressor;constructor(){this.id=Ya.Name,this.name=Ya.Name,this.extension={type:[X.ExtensionType.LoadParser],priority:X.LoaderParserPriority.High,ref:null},this.validFontExtensions=["ttf","otf","woff","woff2"],this.woff2Decompressor=null}test(t){const e=t.split("?")[0]?.split(".").pop()?.toLowerCase()??"";return this.validFontExtensions.includes(e)}async load(t,e,i){const a=t.split("?")[0]?.split(".").pop()?.toLowerCase()??"",n=await fetch(t).then(f=>f.arrayBuffer());if(a!=="woff2"){const f=zr.parse(new Uint8Array(n).buffer),p=f.names.fontFamily.en||f.names.fontFamily[Object.keys(f.names.fontFamily)[0]],y=new FontFace(p,`url(${t})`);return await y.load(),document.fonts.add(y),y}if(await this.loadWoff2Decompressor(),!this.woff2Decompressor)throw new Error("Cannot initialize Woff2 decompressor.");const r=this.woff2Decompressor.decompress(n),o=zr.parse(new Uint8Array(r).buffer),l=o.names.fontFamily.en||o.names.fontFamily[Object.keys(o.names.fontFamily)[0]],c=new Blob([r],{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 e=`${await fetch("https://unpkg.com/wawoff2@2.0.1/build/decompress_binding.js").then(i=>i.text())}; return Module`;this.woff2Decompressor=new Function(e)(),await new Promise(i=>{this.woff2Decompressor.onRuntimeInitialized=i})}unload(t){t&&document.fonts.delete(t)}}class rf{constructor(t,e,i,a,n,r,o,l){this.clip=t,this.propertyPath=e,this.fieldName=i,this.previousFieldName=a,this.previousValue=n,this.newValue=r,this.storedPreviousValue=n,this.storedNewValue=r,this.trackIndex=o,this.clipIndex=l}name="setMergeField";storedPreviousValue;storedNewValue;trackIndex;clipIndex;storedPreviousBinding;async execute(t){if(!t)return;const e=t.getMergeFields();this.storedPreviousBinding=this.clip.getMergeFieldBinding(this.propertyPath),Ur(this.clip.clipConfiguration,this.propertyPath,this.storedNewValue),this.fieldName?this.clip.setMergeFieldBinding(this.propertyPath,{placeholder:e.createTemplate(this.fieldName),resolvedValue:this.storedNewValue}):this.clip.removeMergeFieldBinding(this.propertyPath),this.fieldName?e.register({name:this.fieldName,defaultValue:this.storedNewValue},{silent:!0}):this.previousFieldName&&e.remove(this.previousFieldName,{silent:!0}),(this.propertyPath==="asset.src"||this.propertyPath.endsWith(".src"))&&await this.clip.reloadAsset(),this.clip.reconfigureAfterRestore(),this.clip.draw(),t.emitEvent(j.MergeFieldApplied,{propertyPath:this.propertyPath,fieldName:this.fieldName??"",trackIndex:this.trackIndex,clipIndex:this.clipIndex})}async undo(t){if(!t)return;const e=t.getMergeFields();Ur(this.clip.clipConfiguration,this.propertyPath,this.storedPreviousValue),this.storedPreviousBinding?this.clip.setMergeFieldBinding(this.propertyPath,this.storedPreviousBinding):this.clip.removeMergeFieldBinding(this.propertyPath),this.previousFieldName&&e.register({name:this.previousFieldName,defaultValue:this.storedPreviousValue},{silent:!0}),(this.propertyPath==="asset.src"||this.propertyPath.endsWith(".src"))&&await this.clip.reloadAsset(),this.clip.reconfigureAfterRestore(),this.clip.draw(),t.emitEvent(j.MergeFieldRemoved,{propertyPath:this.propertyPath,fieldName:this.previousFieldName,trackIndex:this.trackIndex,clipIndex:this.clipIndex})}}class $i{data;constructor(t){this.data=structuredClone(t)}getTimeline(){return this.data.timeline}getBackground(){return this.data.timeline.background}getTracks(){return this.data.timeline.tracks}getTrack(t){return this.data.timeline.tracks[t]??null}getTrackCount(){return this.data.timeline.tracks.length}getSoundtrack(){return this.data.timeline.soundtrack}getClip(t,e){const i=this.data.timeline.tracks[t];return i?i.clips[e]??null:null}getClipsInTrack(t){return this.data.timeline.tracks[t]?.clips??[]}getClipCount(){return this.data.timeline.tracks.reduce((t,e)=>t+e.clips.length,0)}getClipCountInTrack(t){return this.data.timeline.tracks[t]?.clips.length??0}getOutput(){return this.data.output}getSize(){const{size:t}=this.data.output;if(!t?.width||!t?.height)throw new Error("Output size is not defined");return{width:t.width,height:t.height}}getFormat(){return this.data.output.format}getFps(){return this.data.output.fps}getMergeFields(){return this.data.merge}addTrack(t,e){const i=e??{clips:[]};return this.data.timeline.tracks.splice(t,0,i),i}removeTrack(t){if(t<0||t>=this.data.timeline.tracks.length)return null;const[e]=this.data.timeline.tracks.splice(t,1);return e??null}addClip(t,e,i){const a=this.data.timeline.tracks[t];if(!a)throw new Error(`Track ${t} does not exist`);const n=i??a.clips.length;return a.clips.splice(n,0,e),e}removeClip(t,e){const i=this.data.timeline.tracks[t];if(!i||e<0||e>=i.clips.length)return null;const[a]=i.clips.splice(e,1);return a??null}updateClip(t,e,i){const a=this.getClip(t,e);if(!a)throw new Error(`Clip at track ${t}, index ${e} does not exist`);Object.assign(a,i)}replaceClip(t,e,i){const a=this.data.timeline.tracks[t];if(!a||e<0||e>=a.clips.length)return null;const n=a.clips[e];return a.clips[e]=i,n}setBackground(t){this.data.timeline.background=t}setSoundtrack(t){this.data.timeline.soundtrack=t}getFonts(){return this.data.timeline.fonts??[]}addFont(t){this.data.timeline.fonts||(this.data.timeline.fonts=[]),this.data.timeline.fonts.some(e=>e.src===t)||this.data.timeline.fonts.push({src:t})}removeFont(t){this.data.timeline.fonts&&(this.data.timeline.fonts=this.data.timeline.fonts.filter(e=>e.src!==t))}setFonts(t){this.data.timeline.fonts=t}setSize(t){this.data.output.size={width:t.width,height:t.height}}setFormat(t){this.data.output.format=t}setFps(t){this.data.output.fps=t}setMergeFields(t){this.data.merge=t}toJSON(){const t=structuredClone(this.data);return t.merge?.length===0&&delete t.merge,t}static fromJSON(t){return new $i(t)}clone(){return new $i(this.data)}}function fl(s){if(s==null)return s;if(Array.isArray(s))return s.map(fl);if(typeof s=="object"){const t={};for(const[e,i]of Object.entries(s))t[e]=fl(i);return t}return typeof s=="string"&&s!==""&&!Number.isNaN(Number(s))?Number(s):s}class ta extends ln{static ZIndexPadding=100;assetLoader;events;document;edit;tracks;clipsToDispose;clips;commandHistory=[];commandIndex=-1;playbackTime;size;backgroundColor;totalDuration;isPlaying;selectedClip;copiedClip=null;updatedClip;viewportMask;background;isExporting=!1;cachedTimelineEnd=0;endLengthClips=new Set;isBatchingEvents=!1;isLoadingEdit=!1;syncCorrectionCount=0;toolbarButtons=[];mergeFields;canvas=null;alignmentGuides=null;lumaMaskController;clipErrors=new Map;constructor(t){super(),this.document=new $i(t),this.size=this.document.getSize(),this.backgroundColor=this.document.getBackground()??"#000000",this.assetLoader=new gr,this.edit=null,this.tracks=[],this.clipsToDispose=[],this.clips=[],this.events=new dl,this.mergeFields=new vN(this.events),this.lumaMaskController=new mN(()=>this.canvas,()=>this.tracks,this.events),this.playbackTime=0,this.totalDuration=0,this.isPlaying=!1,this.selectedClip=null,this.updatedClip=null,this.background=null,this.setupIntentListeners()}async load(){this.getContainer().sortableChildren=!0;const t=new X.Graphics;this.background=t,t.fillStyle={color:this.backgroundColor},t.rect(0,0,this.size.width,this.size.height),t.fill(),this.getContainer().addChild(t),this.viewportMask=new X.Graphics,this.viewportMask.rect(0,0,this.size.width,this.size.height),this.viewportMask.fill(16777215),this.getContainer().addChild(this.viewportMask),this.getContainer().setMask({mask:this.viewportMask}),this.alignmentGuides=new eN(this.getContainer(),this.size.width,this.size.height),await this.initializeFromDocument()}async initializeFromDocument(t="load"){const e=this.document.toJSON(),i=e.merge??[];this.mergeFields.loadFromSerialized(i);const a=this.detectMergeFieldBindings(e,i),n=i.length>0?CN(e,i):e,r=lo.parse(fl(n));oN(r),this.edit=r,await Promise.all((this.edit.timeline.fonts??[]).map(async o=>{const l=o.src,c={src:l,parser:Ya.Name};return this.assetLoader.load(l,c)})),this.isLoadingEdit=!0;for(const[o,l]of this.edit.timeline.tracks.entries())for(const[c,d]of l.clips.entries())try{const u=this.createPlayerFromAssetType(d);u.layer=o+1;const f=a.get(`${o}-${c}`);f&&f.size>0&&u.setInitialBindings(f),await this.addPlayer(o,u)}catch(u){const f=d.asset.type??"unknown",p=u instanceof Error?u.message:String(u);this.clipErrors.set(`${o}-${c}`,{error:p,assetType:f}),this.events.emit(j.ClipLoadFailed,{trackIndex:o,clipIndex:c,error:p,assetType:f})}this.isLoadingEdit=!1,this.lumaMaskController.initialize(),await this.resolveAllTiming(),this.updateTotalDuration(),this.edit.timeline.soundtrack&&await this.loadSoundtrack(this.edit.timeline.soundtrack),this.events.emit(j.TimelineUpdated,{current:this.getResolvedEdit()}),this.emitEditChanged(t)}update(t,e){for(const i of this.clips)i.shouldDispose&&this.queueDisposeClip(i),i.update(t,e);this.disposeClips(),this.lumaMaskController.update(),this.isPlaying&&(this.playbackTime=Math.max(0,Math.min(this.playbackTime+e,this.totalDuration)),this.playbackTime===this.totalDuration&&this.pause())}draw(){for(const t of this.clips)t.draw()}dispose(){if(this.clearClips(),this.lumaMaskController.dispose(),this.viewportMask){try{this.getContainer().setMask(null)}catch{}this.viewportMask.destroy(),this.viewportMask=void 0}Ji.resetFontCache()}updateViewportMask(){this.viewportMask&&(this.viewportMask.clear(),this.viewportMask.rect(0,0,this.size.width,this.size.height),this.viewportMask.fill(16777215))}play(){this.isPlaying=!0,this.events.emit(j.PlaybackPlay)}pause(){this.isPlaying=!1,this.events.emit(j.PlaybackPause)}seek(t){this.playbackTime=Math.max(0,Math.min(t,this.totalDuration)),this.pause(),this.update(0,101),this.draw()}stop(){this.seek(0)}async loadEdit(t){if(this.edit&&!this.hasStructuralChanges(t)){this.document=new $i(t),this.isBatchingEvents=!0,this.applyGranularChanges(t),this.isBatchingEvents=!1,this.emitEditChanged("loadEdit:granular");return}this.document=new $i(t);const e=this.document.getSize();(e.width!==this.size.width||e.height!==this.size.height)&&(this.size=e,this.updateViewportMask(),this.canvas?.zoomToFit()),this.backgroundColor=this.document.getBackground()??"#000000",this.background&&(this.background.clear(),this.background.fillStyle={color:this.backgroundColor},this.background.rect(0,0,this.size.width,this.size.height),this.background.fill()),this.clearClips(),await this.initializeFromDocument("loadEdit")}async loadSoundtrack(t){const e={asset:{type:"audio",src:t.src,effect:t.effect,volume:t.volume??1},fit:"crop",start:0,length:this.totalDuration/1e3},i=new Jl(this,e);i.layer=this.tracks.length+1,await this.addPlayer(this.tracks.length,i)}getEdit(){const t=this.document.toJSON(),e=this.mergeFields.toSerializedArray();return e.length>0&&(t.merge=e),t}validateEdit(t){const e=lo.safeParse(t);return e.success?{valid:!0,errors:[]}:{valid:!1,errors:e.error.issues.map(i=>({path:i.path.join("."),message:i.message}))}}getResolvedEdit(){const t=this.tracks.map(e=>({clips:e.filter(i=>i&&!this.clipsToDispose.includes(i)).map(i=>({...i.clipConfiguration,start:i.getStart(),length:i.getLength()}))}));return{timeline:{background:this.backgroundColor,tracks:t,fonts:this.edit?.timeline.fonts||[]},output:this.edit?.output||{size:this.size,format:"mp4"}}}getOriginalEdit(){return this.edit}getDocument(){return this.document}addClip(t,e){const i=new lN(t,e);return this.executeCommand(i)}getClip(t,e){const i=this.tracks[t];return!i||e<0||e>=i.length?null:i[e].clipConfiguration}getClipError(t,e){return this.clipErrors.get(`${t}-${e}`)??null}clearClipErrorAndShift(t,e){this.clipErrors.delete(`${t}-${e}`);const i=[];for(const[a,n]of this.clipErrors){const[r,o]=a.split("-").map(Number);r===t&&o>e&&i.push({oldKey:a,newKey:`${r}-${o-1}`,value:n})}for(const{oldKey:a,newKey:n,value:r}of i)this.clipErrors.delete(a),this.clipErrors.set(n,r)}getPlayerClip(t,e){const i=this.tracks[t];return!i||e<0||e>=i.length?null:i[e]}getOriginalAsset(t,e){const i=this.getPlayerClip(t,e);if(i)return i.getExportableClip()?.asset}deleteClip(t,e){const i=this.tracks[t];if(!i)return;const a=i[e];if(!a)return;if(a.playerType!==qt.Luma){const o=i.findIndex(l=>l.playerType===qt.Luma);if(o!==-1){const l=o<e?e-1:e,c=new fr(t,o);this.executeCommand(c);const d=new fr(t,l);this.executeCommand(d);return}}const r=new fr(t,e);this.executeCommand(r)}splitClip(t,e,i){const a=new uN(t,e,i);this.executeCommand(a)}async addTrack(t,e){this.document&&!this.isLoadingEdit&&this.document.addTrack(t);const i=new tf(t);await this.executeCommand(i);for(const a of e?.clips??[])await this.addClip(t,a)}getTrack(t){const e=this.clips.filter(i=>i.layer===t+1);return e.length===0?null:{clips:e.map(i=>i.clipConfiguration)}}deleteTrack(t){const e=new ll(t);this.executeCommand(e)}getTotalDuration(){return this.totalDuration}getMemoryStats(){const t={};for(const n of this.clips){const r=n.clipConfiguration.asset?.type||"unknown";t[r]=(t[r]||0)+1}let e=0,i=0,a=0;for(const n of this.clips)n.playerType===qt.RichText&&(e+=1,i+=n.getCacheSize()),n.playerType===qt.Text&&(a+=1);return{clipCounts:t,totalClips:this.clips.length,richTextCacheStats:{clips:e,totalFrames:i},textPlayerCount:a,lumaMaskCount:this.lumaMaskController.getActiveMaskCount(),commandHistorySize:this.commandHistory.length,trackCount:this.tracks.length}}getComprehensiveMemoryStats(){const t=[],e={videos:{count:0,totalMB:0,dimensions:[]},images:{count:0,totalMB:0,dimensions:[]},text:{count:0,totalMB:0},richText:{count:0,totalMB:0},luma:{count:0,totalMB:0},animated:{count:0,frames:0,totalMB:0}};for(const r of this.clips){const{asset:o}=r.clipConfiguration,l=o?.type||"unknown",c=["video","image","text","rich-text","luma","audio","html","shape","caption"].includes(l)?l:"unknown",d=r.getSize(),u=this.estimateTextureMB(d.width,d.height),f=this.getAssetLabel(r);t.push({id:r.clipConfiguration.asset?.type||"unknown",type:c,label:f,width:d.width,height:d.height,estimatedMB:u}),c==="video"?(e.videos.count+=1,e.videos.totalMB+=u,e.videos.dimensions.push({width:d.width,height:d.height})):c==="image"?(e.images.count+=1,e.images.totalMB+=u,e.images.dimensions.push({width:d.width,height:d.height})):c==="text"?(e.text.count+=1,e.text.totalMB+=u):c==="rich-text"?(e.richText.count+=1,e.richText.totalMB+=u):c==="luma"&&(e.luma.count+=1,e.luma.totalMB+=u)}for(const r of this.clips)if(r.playerType===qt.RichText){const o=r.getCacheSize();o>0&&(e.animated.count+=1,e.animated.frames+=o,e.animated.totalMB+=o*this.estimateTextureMB(this.size.width,this.size.height))}const i=r=>{if(r.length===0)return"";if(r.length===1)return`${r[0].width}×${r[0].height}`;const o=Math.round(r.reduce((c,d)=>c+d.width,0)/r.length),l=Math.round(r.reduce((c,d)=>c+d.height,0)/r.length);return`avg ${o}×${l}`},a=e.videos.count+e.images.count+e.text.count+e.richText.count+e.luma.count+e.animated.count,n=e.videos.totalMB+e.images.totalMB+e.text.totalMB+e.richText.totalMB+e.luma.totalMB+e.animated.totalMB;return{textureStats:{videos:{count:e.videos.count,totalMB:e.videos.totalMB,avgDimensions:i(e.videos.dimensions)},images:{count:e.images.count,totalMB:e.images.totalMB,avgDimensions:i(e.images.dimensions)},text:{count:e.text.count,totalMB:e.text.totalMB},richText:{count:e.richText.count,totalMB:e.richText.totalMB},luma:{count:e.luma.count,totalMB:e.luma.totalMB},animated:{count:e.animated.count,frames:e.animated.frames,totalMB:e.animated.totalMB},totalTextures:a,totalMB:n},assetDetails:t,systemStats:{clipCount:this.clips.length,trackCount:this.tracks.length,commandCount:this.commandHistory.length}}}estimateTextureMB(t,e){return t*e*4/(1024*1024)}getAssetLabel(t){const e=t.clipConfiguration.asset;if(!e)return"unknown";const i=e.src;if("src"in e&&typeof i=="string")return(i.split("/").pop()||i).split("?")[0];const a=e.text;return"text"in e&&typeof a=="string"?a.length>20?`${a.substring(0,17)}...`:a:e.type?.toString()||"unknown"}getPlaybackHealth(){let t=0,e=0,i=0;for(const a of this.clips)if(a.isActive()){if(t+=1,a.playerType===qt.Video){const n=a.getCurrentDrift();e=Math.max(e,n)}if(a.playerType===qt.Audio){const n=a.getCurrentDrift();i=Math.max(i,n)}}return{activePlayerCount:t,totalPlayerCount:this.clips.length,videoMaxDrift:e,audioMaxDrift:i,syncCorrections:this.syncCorrectionCount}}recordSyncCorrection(){this.syncCorrectionCount+=1}undo(){if(this.commandIndex>=0){const t=this.commandHistory[this.commandIndex];if(t.undo){const e=this.createCommandContext();t.undo(e),this.commandIndex-=1,this.events.emit(j.EditUndo,{command:t.name}),this.emitEditChanged(`undo:${t.name}`)}}}redo(){if(this.commandIndex<this.commandHistory.length-1){this.commandIndex+=1;const t=this.commandHistory[this.commandIndex],e=this.createCommandContext();t.execute(e),this.events.emit(j.EditRedo,{command:t.name}),this.emitEditChanged(`redo:${t.name}`)}}setUpdatedClip(t,e=null,i=null){const a=t.layer-1,n=this.tracks[a],r=n?n.indexOf(t):-1,o=new ef(t,e,i,{trackIndex:a,clipIndex:r});this.executeCommand(o)}updateClip(t,e,i){const a=this.getPlayerClip(t,e);if(!a){console.warn(`Clip not found at track ${t}, index ${e}`);return}const n=structuredClone(a.clipConfiguration),r=structuredClone(a.clipConfiguration),o=Dr(r,i),l=new ef(a,n,o,{trackIndex:t,clipIndex:e});this.executeCommand(l)}updateClipTiming(t,e,i){if(!this.getPlayerClip(t,e)){console.warn(`Clip not found at track ${t}, index ${e}`);return}const n=new pN(t,e,i);this.executeCommand(n)}updateTextContent(t,e,i){const a=new gN(t,e,i);this.executeCommand(a)}executeEditCommand(t){return this.executeCommand(t)}executeCommand(t){const e=this.createCommandContext(),i=t.execute(e);return this.commandHistory=this.commandHistory.slice(0,this.commandIndex+1),this.commandHistory.push(t),this.commandIndex+=1,i instanceof Promise?i.then(()=>this.emitEditChanged(t.name)):(this.emitEditChanged(t.name),i)}emitEditChanged(t){this.isBatchingEvents||this.events.emit(j.EditChanged,{source:t,timestamp:Date.now()})}detectMergeFieldBindings(t,e){const i=new Map;if(!e.length)return i;const a=new Map;for(const{find:n,replace:r}of e){const o=typeof r=="string"?r:JSON.stringify(r);a.set(n.toUpperCase(),o)}for(const[n,r]of t.timeline.tracks.entries())for(const[o,l]of r.clips.entries()){const c=this.detectBindingsInObject(l,"",a);c.size>0&&i.set(`${n}-${o}`,c)}return i}detectBindingsInObject(t,e,i){const a=new Map;if(typeof t=="string"){if(/\{\{\s*([A-Z_0-9]+)\s*\}\}/gi.test(t)){const o=t.replace(/\{\{\s*([A-Z_0-9]+)\s*\}\}/gi,(l,c)=>i.get(c.toUpperCase())??l);a.set(e,{placeholder:t,resolvedValue:o})}return a}if(Array.isArray(t)){for(let n=0;n<t.length;n+=1){const r=e?`${e}[${n}]`:`[${n}]`,o=this.detectBindingsInObject(t[n],r,i);for(const[l,c]of o)a.set(l,c)}return a}if(t!==null&&typeof t=="object")for(const[n,r]of Object.entries(t)){const o=e?`${e}.${n}`:n,l=this.detectBindingsInObject(r,o,i);for(const[c,d]of l)a.set(c,d)}return a}hasStructuralChanges(t){if(!this.edit)return!0;const e=this.edit.timeline.tracks,i=t.timeline.tracks;if(e.length!==i.length)return!0;for(let a=0;a<e.length;a+=1){if(e[a].clips.length!==i[a].clips.length)return!0;for(let n=0;n<e[a].clips.length;n+=1){const r=e[a].clips[n]?.asset?.type,o=i[a].clips[n]?.asset?.type;if(r!==o)return!0}}return JSON.stringify(this.edit.merge??[])!==JSON.stringify(t.merge??[])||JSON.stringify(this.edit.timeline.fonts??[])!==JSON.stringify(t.timeline.fonts??[])}applyGranularChanges(t){const e=this.edit?.output,i=t.output;if(i?.size&&(e?.size?.width!==i.size.width||e?.size?.height!==i.size.height)){const o=i.size.width??this.size.width,l=i.size.height??this.size.height;this.setOutputSize(o,l)}i?.fps!==void 0&&e?.fps!==i.fps&&this.setOutputFps(i.fps),i?.format!==void 0&&e?.format!==i.format&&this.setOutputFormat(i.format),i?.destinations&&JSON.stringify(e?.destinations)!==JSON.stringify(i.destinations)&&this.setOutputDestinations(i.destinations);const a=t.timeline?.background;a&&this.backgroundColor!==a&&this.setTimelineBackground(a);const n=this.edit.timeline.tracks,r=t.timeline.tracks;for(let o=0;o<r.length;o+=1){const l=n[o].clips,c=r[o].clips;for(let d=0;d<c.length;d+=1){const u=l[d],f=c[d];JSON.stringify(u)!==JSON.stringify(f)&&this.updateClip(o,d,f)}}}createCommandContext(){return{getClips:()=>this.clips,getTracks:()=>this.tracks,getTrack:t=>t>=0&&t<this.tracks.length?this.tracks[t]:null,getContainer:()=>this.getContainer(),addPlayer:(t,e)=>this.addPlayer(t,e),addPlayerToContainer:(t,e)=>{this.addPlayerToContainer(t,e)},createPlayerFromAssetType:t=>this.createPlayerFromAssetType(t),queueDisposeClip:t=>this.queueDisposeClip(t),disposeClips:()=>this.disposeClips(),clearClipError:(t,e)=>this.clearClipErrorAndShift(t,e),undeleteClip:(t,e)=>{this.clips.push(e);let i=0;if(t>=0&&t<this.tracks.length){const a=this.tracks[t];i=a.length;for(let n=0;n<a.length;n+=1)if(a[n].getStart()>e.getStart()){i=n;break}a.splice(i,0,e)}if(this.document){const a=e.getExportableClip();this.document.addClip(t,a,i)}this.addPlayerToContainer(t,e),e.load().catch(a=>{const n=e.clipConfiguration?.asset?.type??"unknown",r=a instanceof Error?a.message:String(a);this.clipErrors.set(`${t}-${i}`,{error:r,assetType:n}),this.events.emit(j.ClipLoadFailed,{trackIndex:t,clipIndex:i,error:r,assetType:n})}),this.updateTotalDuration()},setUpdatedClip:t=>{this.updatedClip=t},restoreClipConfiguration:(t,e)=>{const i=structuredClone(e),a=t.clipConfiguration;for(const n of Object.keys(a))delete a[n];if(Object.assign(a,i),t.reconfigureAfterRestore(),t.draw(),this.document){const n=this.findClipIndices(t);if(n){const r=t.getExportableClip();this.document.replaceClip(n.trackIndex,n.clipIndex,r)}}},updateDuration:()=>this.updateTotalDuration(),emitEvent:(t,...e)=>this.events.emit(t,...e),findClipIndices:t=>this.findClipIndices(t),getClipAt:(t,e)=>this.getClipAt(t,e),getSelectedClip:()=>this.selectedClip,setSelectedClip:t=>{this.selectedClip=t},movePlayerToTrackContainer:(t,e,i)=>this.movePlayerToTrackContainer(t,e,i),getEditState:()=>this.getResolvedEdit(),propagateTimingChanges:(t,e)=>this.propagateTimingChanges(t,e),resolveClipAutoLength:t=>this.resolveClipAutoLength(t),untrackEndLengthClip:t=>this.endLengthClips.delete(t),trackEndLengthClip:t=>this.endLengthClips.add(t),getMergeFields:()=>this.mergeFields}}queueDisposeClip(t){this.clipsToDispose.push(t)}disposeClips(){if(this.clipsToDispose.length!==0){for(const t of this.clipsToDispose)t.playerType===qt.Luma&&this.lumaMaskController.cleanupForPlayer(t);for(const t of this.clipsToDispose)this.disposeClip(t);this.clips=this.clips.filter(t=>!this.clipsToDispose.includes(t));for(const t of this.clipsToDispose){const e=t.layer-1;if(e>=0&&e<this.tracks.length){const i=this.tracks[e].indexOf(t);i!==-1&&(this.tracks[e].splice(i,1),this.document&&this.document.removeClip(e,i))}}this.clipsToDispose=[],this.updateTotalDuration(),this.cleanupUnusedFonts()}}cleanupUnusedFonts(){if(!this.document)return;const t=this.document.getFonts();if(t.length===0)return;const e=new Set;for(const i of this.clips){const{asset:a}=i.clipConfiguration;a&&a.type==="rich-text"&&a.font?.family&&e.add(a.font.family)}for(const i of t){const a=this.extractFilenameFromUrl(i.src);a&&!e.has(a)&&this.document.removeFont(i.src)}}extractFilenameFromUrl(t){try{const{pathname:e}=new URL(t),i=e.split("/").pop();return i?i.replace(/\.[^.]+$/,""):null}catch{return null}}disposeClip(t){try{if(this.getContainer().children.includes(t.getContainer())){const e=this.getContainer().getChildIndex(t.getContainer());this.getContainer().removeChildAt(e)}else for(const e of this.getContainer().children)if(e instanceof X.Container&&e.label?.toString().startsWith("shotstack-track-")&&e.children.includes(t.getContainer())){e.removeChild(t.getContainer());break}}catch(e){console.warn(`Attempting to unmount an unmounted clip: ${e}`)}this.unloadClipAssets(t),this.endLengthClips.delete(t),this.cachedTimelineEnd=0,t.dispose()}unloadClipAssets(t){const{asset:e}=t.clipConfiguration;e&&"src"in e&&typeof e.src=="string"&&this.assetLoader.decrementRef(e.src)&&X.Assets.cache.has(e.src)&&X.Assets.unload(e.src)}clearClips(){for(const t of this.clips)this.disposeClip(t);this.clips=[],this.tracks=[],this.clipsToDispose=[],this.clipErrors.clear(),this.updateTotalDuration()}updateTotalDuration(){let t=0;for(const i of this.tracks)for(const a of i)t=Math.max(t,a.getEnd());const e=this.totalDuration;this.totalDuration=t*1e3,e!==this.totalDuration&&this.events.emit(j.DurationChanged,{duration:this.totalDuration})}async resolveAllTiming(){for(let e=0;e<this.tracks.length;e+=1)for(let i=0;i<this.tracks[e].length;i+=1){const a=this.tracks[e][i],n=a.getTimingIntent();let r;n.start==="auto"?r=pr(e,i,this.tracks):r=n.start;let o;n.length==="auto"?o=await af(a.clipConfiguration.asset):n.length==="end"?o=0:o=n.length,a.setResolvedTiming({start:r,length:o})}const t=cl(this.tracks);this.cachedTimelineEnd=t;for(const e of[...this.endLengthClips]){const i=e.getResolvedTiming();e.setResolvedTiming({start:i.start,length:nf(i.start,t)})}for(const e of this.endLengthClips)e.reconfigureAfterRestore()}propagateTimingChanges(t,e){const i=this.tracks[t];if(!i)return;for(let n=Math.max(0,e);n<i.length;n+=1){const r=i[n];if(r.getTimingIntent().start==="auto"){const o=pr(t,n,this.tracks);r.setResolvedTiming({start:o,length:r.getLength()}),r.reconfigureAfterRestore()}}const a=cl(this.tracks);if(a!==this.cachedTimelineEnd){this.cachedTimelineEnd=a;for(const n of[...this.endLengthClips]){const r=nf(n.getStart(),a),o=n.getLength();Math.abs(r-o)>.001&&(n.setResolvedTiming({start:n.getStart(),length:r}),n.clipConfiguration.length=r,n.reconfigureAfterRestore())}}this.updateTotalDuration(),this.events.emit(j.TimelineUpdated,{current:this.getResolvedEdit()})}async resolveClipAutoLength(t){const e=t.getTimingIntent();if(e.length!=="auto")return;const i=this.findClipIndices(t);let a=t.getStart();e.start==="auto"&&i&&(a=pr(i.trackIndex,i.clipIndex,this.tracks));const n=await af(t.clipConfiguration.asset);t.setResolvedTiming({start:a,length:n}),t.clipConfiguration.length=n,t.reconfigureAfterRestore(),i&&this.propagateTimingChanges(i.trackIndex,i.clipIndex)}addPlayerToContainer(t,e){const i=1e5-(t+1)*ta.ZIndexPadding,a=`shotstack-track-${i}`;let n=this.getContainer().getChildByLabel(a,!1);n||(n=new X.Container({label:a,zIndex:i}),this.getContainer().addChild(n)),n.addChild(e.getContainer())}movePlayerToTrackContainer(t,e,i){if(e===i)return;const a=1e5-(e+1)*ta.ZIndexPadding,n=1e5-(i+1)*ta.ZIndexPadding,r=`shotstack-track-${a}`,o=`shotstack-track-${n}`,l=this.getContainer().getChildByLabel(r,!1);let c=this.getContainer().getChildByLabel(o,!1);c||(c=new X.Container({label:o,zIndex:n}),this.getContainer().addChild(c)),l&&l.removeChild(t.getContainer()),c.addChild(t.getContainer()),this.getContainer().sortDirty=!0}createPlayerFromAssetType(t){if(!t.asset?.type)throw new Error("Invalid clip configuration: missing asset type");let e;switch(t.asset.type){case"text":{e=new Ji(this,t);break}case"rich-text":{e=new Qi(this,t);break}case"shape":{e=new $S(this,t);break}case"html":{e=new sp(this,t);break}case"image":{e=new ip(this,t);break}case"video":{e=new tN(this,t);break}case"audio":{e=new Jl(this,t);break}case"luma":{e=new ap(this,t);break}case"caption":{e=new hn(this,t);break}default:throw new Error(`Unsupported clip type: ${t.asset.type}`)}return e}async addPlayer(t,e){for(;this.tracks.length<=t;)this.tracks.push([]);if(this.tracks[t].push(e),this.clips.push(e),this.document&&!this.isLoadingEdit){for(;this.document.getTrackCount()<=t;)this.document.addTrack(this.document.getTrackCount());const r=this.tracks[t].length-1,o=e.getExportableClip();this.document.addClip(t,o,r)}e.getTimingIntent().length==="end"&&this.endLengthClips.add(e);const i=1e5-(t+1)*ta.ZIndexPadding,a=`shotstack-track-${i}`;let n=this.getContainer().getChildByLabel(a,!1);n||(n=new X.Container({label:a,zIndex:i}),this.getContainer().addChild(n)),n.addChild(e.getContainer()),await e.load(),this.updateTotalDuration()}selectClip(t,e){const i=new dN(t,e);this.executeCommand(i)}clearSelection(){const t=new cN;this.executeCommand(t)}isClipSelected(t,e){if(!this.selectedClip)return!1;const i=this.selectedClip.layer-1,a=this.tracks[i].indexOf(this.selectedClip);return t===i&&e===a}getSelectedClipInfo(){if(!this.selectedClip)return null;const t=this.selectedClip.layer-1,e=this.tracks[t].indexOf(this.selectedClip);return{trackIndex:t,clipIndex:e,player:this.selectedClip}}copyClip(t,e){const i=this.getClipAt(t,e);i&&(this.copiedClip={trackIndex:t,clipConfiguration:structuredClone(i.clipConfiguration)},this.events.emit(j.ClipCopied,{trackIndex:t,clipIndex:e}))}pasteClip(){if(!this.copiedClip)return;const t=structuredClone(this.copiedClip.clipConfiguration);t.start=O0(this.playbackTime),this.addClip(this.copiedClip.trackIndex,t)}hasCopiedClip(){return this.copiedClip!==null}findClipIndices(t){for(let e=0;e<this.tracks.length;e+=1){const i=this.tracks[e].indexOf(t);if(i!==-1)return{trackIndex:e,clipIndex:i}}return null}getClipAt(t,e){return t>=0&&t<this.tracks.length&&e>=0&&e<this.tracks[t].length?this.tracks[t][e]:null}selectPlayer(t){const e=this.findClipIndices(t);e&&this.selectClip(e.trackIndex,e.clipIndex)}isPlayerSelected(t){return this.isExporting?!1:this.selectedClip===t}getActivePlayersExcept(t){const e=[];for(const i of this.tracks)for(const a of i)a!==t&&a.isActive()&&e.push(a);return e}showAlignmentGuide(t,e,i,a){this.alignmentGuides&&(t==="canvas"?this.alignmentGuides.drawCanvasGuide(e,i):a&&this.alignmentGuides.drawClipGuide(e,i,a.start,a.end))}clearAlignmentGuides(){this.alignmentGuides?.clear()}moveSelectedClip(t,e){const i=this.getSelectedClipInfo();if(!i)return;const{player:a}=i,n=structuredClone(a.clipConfiguration);a.moveBy(t,e),this.setUpdatedClip(a,n,structuredClone(a.clipConfiguration))}setExportMode(t){this.isExporting=t}isInExportMode(){return this.isExporting}setCanvas(t){this.canvas=t}getCanvasZoom(){return this.canvas?.getZoom()??1}setOutputSize(t,e){const i=Id.safeParse({width:t,height:e});if(!i.success)throw new Error(`Invalid size: ${i.error.issues[0]?.message}`);const a={width:t,height:e};this.size=a,this.edit&&(this.edit.output={...this.edit.output,size:a}),this.document?.setSize(a),this.updateViewportMask(),this.canvas?.zoomToFit(),this.background&&(this.background.clear(),this.background.fillStyle={color:this.backgroundColor},this.background.rect(0,0,t,e),this.background.fill()),this.events.emit(j.OutputResized,a),this.emitEditChanged("output:size")}setOutputFps(t){const e=Ed.safeParse(t);if(!e.success)throw new Error(`Invalid fps: ${e.error.issues[0]?.message}`);this.edit&&(this.edit.output={...this.edit.output,fps:e.data}),this.document?.setFps(e.data),this.events.emit(j.OutputFpsChanged,{fps:t}),this.emitEditChanged("output:fps")}getOutputFps(){return this.edit?.output?.fps??30}setOutputFormat(t){const e=Ad.safeParse(t);if(!e.success)throw new Error(`Invalid format: ${e.error.issues[0]?.message}`);this.edit&&(this.edit.output={...this.edit.output,format:e.data}),this.document?.setFormat(e.data),this.events.emit(j.OutputFormatChanged,{format:e.data}),this.emitEditChanged("output:format")}getOutputFormat(){return this.edit?.output?.format??"mp4"}setOutputDestinations(t){const e=Td.array().safeParse(t);if(!e.success)throw new Error(`Invalid destinations: ${e.error.message}`);this.edit&&(this.edit.output={...this.edit.output,destinations:e.data}),this.events.emit(j.OutputDestinationsChanged,{destinations:e.data}),this.emitEditChanged("output:destinations")}getOutputDestinations(){return this.edit?.output?.destinations??[]}getTimelineFonts(){return this.edit?.timeline?.fonts??[]}pruneUnusedFonts(){this.cleanupUnusedFonts()}setTimelineBackground(t){const e=Pd.safeParse(t);if(!e.success)throw new Error(`Invalid color: ${e.error.issues[0]?.message}`);this.backgroundColor=e.data,this.edit&&(this.edit.timeline={...this.edit.timeline,background:e.data}),this.document?.setBackground(e.data),this.background&&(this.background.clear(),this.background.fillStyle={color:this.backgroundColor},this.background.rect(0,0,this.size.width,this.size.height),this.background.fill()),this.events.emit(j.TimelineBackgroundChanged,{color:e.data}),this.emitEditChanged("timeline:background")}getTimelineBackground(){return this.backgroundColor}registerToolbarButton(t){console.warn('[Shotstack] edit.registerToolbarButton() is deprecated. Use ui.registerButton() instead for typed events: ui.registerButton({ id: "text", ... }); ui.on("button:text", handler);');const e=this.toolbarButtons.findIndex(i=>i.id===t.id);e>=0?this.toolbarButtons[e]=t:this.toolbarButtons.push(t),this.events.emit(_s.ToolbarButtonsChanged,{buttons:this.toolbarButtons})}unregisterToolbarButton(t){console.warn("[Shotstack] edit.unregisterToolbarButton() is deprecated. Use ui.unregisterButton() instead.");const e=this.toolbarButtons.findIndex(i=>i.id===t);e>=0&&(this.toolbarButtons.splice(e,1),this.events.emit(_s.ToolbarButtonsChanged,{buttons:this.toolbarButtons}))}getToolbarButtons(){return[...this.toolbarButtons]}getTemplateClip(t,e){const i=this.getPlayerClip(t,e);return i?i.getExportableClip():null}getTemplateClipText(t,e){const i=this.getTemplateClip(t,e);return i?i.asset?.text??null:null}applyMergeField(t,e,i,a,n,r){const o=this.getPlayerClip(t,e);if(!o)return;const l=Ei(o.clipConfiguration,i),c=r??(typeof l=="string"?l:""),d=this.getTemplateClip(t,e),u=d?Ei(d,i):null,f=typeof u=="string"?this.mergeFields.extractFieldName(u):null,p=new rf(o,i,a,f,c,n,t,e);this.executeCommand(p)}removeMergeField(t,e,i,a){const n=this.getPlayerClip(t,e);if(!n)return;const r=this.getTemplateClip(t,e),o=r?Ei(r,i):null,l=typeof o=="string"?this.mergeFields.extractFieldName(o):null;if(!l)return;const c=new rf(n,i,null,l,a,a,t,e);this.executeCommand(c)}getMergeFieldForProperty(t,e,i){const a=this.getTemplateClip(t,e);if(!a)return null;const n=Ei(a,i);return typeof n=="string"?this.mergeFields.extractFieldName(n):null}updateMergeFieldValueLive(t,e){const i=this.mergeFields.get(t);if(i){this.mergeFields.register({...i,defaultValue:e},{silent:!0});for(let a=0;a<this.tracks.length;a+=1)for(let n=0;n<this.tracks[a].length;n+=1){const r=this.tracks[a][n],o=this.getTemplateClip(a,n);o&&(this.updateMergeFieldInObject(r.clipConfiguration,o,t,e),this.updateMergeFieldBindings(r,t,e))}}}updateMergeFieldBindings(t,e,i){for(const[a,n]of t.getMergeFieldBindings())if(this.mergeFields.extractFieldName(n.placeholder)===e){const o=this.mergeFields.resolve(n.placeholder);t.setMergeFieldBinding(a,{placeholder:n.placeholder,resolvedValue:o})}}updateMergeFieldInObject(t,e,i,a){if(!(!t||!e||typeof t!="object"||typeof e!="object"))for(const n of Object.keys(e)){const r=e[n],o=t;typeof r=="string"?this.mergeFields.extractFieldName(r)===i&&(o[n]=r.replace(new RegExp(`\\{\\{\\s*${i}\\s*\\}\\}`,"gi"),a)):r&&typeof r=="object"&&this.updateMergeFieldInObject(o[n],r,i,a)}}redrawMergeFieldClips(t){for(const e of this.tracks)for(const i of e){const a=this.findClipIndices(i);if(a){const n=this.getTemplateClip(a.trackIndex,a.clipIndex);if(n){const r=this.getMergeFieldUsage(n,t);r.used&&(r.isSrcField&&i.reloadAsset(),i.reconfigureAfterRestore(),i.draw())}}}}getMergeFieldUsage(t,e,i=""){if(!t||typeof t!="object")return{used:!1,isSrcField:!1};for(const[a,n]of Object.entries(t)){const r=i?`${i}.${a}`:a;if(typeof n=="string"){if(this.mergeFields.extractFieldName(n)===e)return{used:!0,isSrcField:r==="asset.src"||r.endsWith(".src")}}else if(typeof n=="object"&&n!==null){const o=this.getMergeFieldUsage(n,e,r);if(o.used)return o}}return{used:!1,isSrcField:!1}}isSrcMergeField(t){for(const e of this.tracks)for(const i of e){const a=this.findClipIndices(i);if(a){const n=this.getTemplateClip(a.trackIndex,a.clipIndex);if(n){const r=this.getMergeFieldUsage(n,t);if(r.used&&r.isSrcField)return!0}}}return!1}deleteMergeFieldGlobally(t){const e=this.mergeFields.get(t);if(!e)return;const i=this.mergeFields.createTemplate(t),a=e.defaultValue;for(let n=0;n<this.tracks.length;n+=1)for(let r=0;r<this.tracks[n].length;r+=1){const o=this.getTemplateClip(n,r);o&&this.restoreMergeFieldInClip(n,r,o,i,a)}this.mergeFields.remove(t)}restoreMergeFieldInClip(t,e,i,a,n,r=""){if(!(!i||typeof i!="object"))for(const o of Object.keys(i)){const l=i[o],c=r?`${r}.${o}`:o;if(typeof l=="string"){const d=this.mergeFields.extractFieldName(l),u=this.mergeFields.extractFieldName(a);if(d&&u&&d===u){const f=l.replace(new RegExp(`\\{\\{\\s*${d}\\s*\\}\\}`,"gi"),n);this.removeMergeField(t,e,c,f)}}else typeof l=="object"&&l!==null&&this.restoreMergeFieldInClip(t,e,l,a,n,c)}}lumaAttachments=new Map;originalAssetTypes=new Map;async attachLumaToClip(t,e,i){const a=this.getClipAt(t,e);if(!a||a.playerType===qt.Luma)return;this.lumaAttachments.has(a)&&await this.detachLumaFromClip(t,e);const n=a.clipConfiguration,r={asset:{type:"luma",src:i},start:n.start,length:n.length,fit:"crop"};await this.addClip(t,r);const o=this.tracks[t],l=o.find(c=>c.playerType===qt.Luma&&c.clipConfiguration.start===n.start);if(l){this.lumaAttachments.set(a,l);const c=o.indexOf(l);this.events.emit(j.LumaAttached,{trackIndex:t,clipIndex:e,lumaSrc:i,lumaClipIndex:c})}}async detachLumaFromClip(t,e){const i=this.getClipAt(t,e);if(!i)return;const a=this.lumaAttachments.get(i);if(!a)return;const n=this.findClipIndices(a);if(n){this.lumaAttachments.delete(i);const r=new fr(n.trackIndex,n.clipIndex);this.executeCommand(r),this.events.emit(j.LumaDetached,{trackIndex:t,clipIndex:e})}}getClipLuma(t,e){const i=this.getClipAt(t,e);if(!i)return null;const a=this.lumaAttachments.get(i);if(!a)return null;const n=this.findClipIndices(a);if(!n)return null;const r=a.clipConfiguration.asset?.src;return r?{src:r,clipIndex:n.clipIndex}:null}hasLumaMask(t,e){const i=this.getClipAt(t,e);return i?this.lumaAttachments.has(i):!1}registerLumaAttachment(t,e,i,a){const n=this.getClipAt(t,e),r=this.getClipAt(i,a);n&&r&&this.lumaAttachments.set(n,r)}syncAttachedLuma(t,e){const i=this.getClipAt(t,e);if(!i)return;const a=this.lumaAttachments.get(i);if(!a)return;const n=i.clipConfiguration;a.clipConfiguration.start=n.start,a.clipConfiguration.length=n.length,a.setResolvedTiming({start:i.getStart(),length:i.getLength()}),a.reconfigureAfterRestore(),a.draw();const r=this.findClipIndices(a);r&&this.document.updateClip(r.trackIndex,r.clipIndex,{start:n.start,length:n.length})}getAttachedLumaPlayer(t){return this.lumaAttachments.get(t)??null}rebuildLumaAttachments(){this.lumaAttachments.clear();for(const t of this.tracks){const e=t.find(a=>a.playerType===qt.Luma),i=t.filter(a=>a.playerType!==qt.Luma);if(e&&i.length>0){const a=i.find(n=>n.clipConfiguration.start===e.clipConfiguration.start&&n.clipConfiguration.length===e.clipConfiguration.length);a?this.lumaAttachments.set(a,e):i.length===1&&this.lumaAttachments.set(i[0],e)}}}transformToLuma(t,e){const i=this.getClipAt(t,e);if(!i?.clipConfiguration?.asset)return;const a=i.clipConfiguration.asset,n=a.type,{src:r}=a;r&&(n==="image"||n==="video")&&this.originalAssetTypes.set(r,n);const o=new sf(t,e,"luma");this.executeCommand(o)}transformFromLuma(t,e){const i=this.getClipAt(t,e);if(!i?.clipConfiguration?.asset)return;const{src:a}=i.clipConfiguration.asset;if(!a)return;let n=this.originalAssetTypes.get(a);n||(n=this.inferAssetTypeFromUrl(a));const r=new sf(t,e,n);this.executeCommand(r)}inferAssetTypeFromUrl(t){const e=t.toLowerCase().split("?")[0];return[".mp4",".webm",".mov",".m4v",".avi",".mkv",".ogv",".ogg"].some(a=>e.endsWith(a))?"video":"image"}setupIntentListeners(){this.events.on(_s.CanvasClipClicked,t=>{this.selectPlayer(t.player)}),this.events.on(_s.CanvasBackgroundClicked,()=>{this.clearSelection()})}}const SN="Browser Not Supported",NN="Please try a different browser or enable hardware acceleration in your browser settings.";function TN(s,t){const e=SN,i=NN,a=document.createElement("div");a.className="ss-webgl-error-overlay";const n=document.createElement("div");n.className="ss-webgl-error-content";const r=document.createElement("div");r.className="ss-webgl-error-icon",r.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">
260
+ `),l=o===-1?this.textPosition:this.textPosition-o-1,c=r.substring(0,l);let d;c.length>0&&c.endsWith(" ")?d=this.measureText(`${c}x`,e)-this.measureText("x",e):d=this.measureText(c,e);const u=e.lineHeight;this.pixelY=this.currentLine*u;const p=this.clipConfig.asset.alignment?.horizontal??"center";let y=d;if(p!=="left"){const v=this.measureText(r,e),S=this.textElement.width;let x=0;p==="center"?x=(S-v)/2:p==="right"&&(x=S-v),y=x+d}this.pixelX=y}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(t,e){const i=new X.Text(t,e),{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 ur{static DEFAULT_FOCUS_DELAY_MS=50;hiddenInput=null;isFocused=!1;focusRetryCount=0;maxFocusRetries=3;focusDelay=ur.DEFAULT_FOCUS_DELAY_MS;eventHandlers={};abortController=null;textChangeCallback=null;lastSyncedText="";isComposing=!1;setupInput(t,e){this.focusDelay=e?.focusDelay??ur.DEFAULT_FOCUS_DELAY_MS,this.createHiddenTextarea(),this.hiddenInput&&(this.hiddenInput.value=t,this.lastSyncedText=t),this.setupEventListeners(),e?.autoFocus!==!1&&this.focusInput()}updateInputValue(t){this.hiddenInput&&(this.hiddenInput.value=t,this.lastSyncedText=t)}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(t,e){if(!this.hiddenInput)return;const i=this.hiddenInput.value.length,a=Math.max(0,Math.min(t,i)),n=Math.max(a,Math.min(e,i));this.hiddenInput.setSelectionRange(a,n)}getCursorPosition(){return this.hiddenInput?.selectionStart||0}getValue(){return this.hiddenInput?.value||""}setTextInputHandler(t){this.textChangeCallback=t}setEventHandlers(t){this.eventHandlers={...this.eventHandlers,...t}}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 t={position:"absolute",opacity:"0.01",pointerEvents:"none",zIndex:"999",left:"0px",top:"0px",width:"1px",height:"1px",border:"none",outline:"none",resize:"none",backgroundColor:"transparent"};Object.assign(this.hiddenInput.style,t),this.hiddenInput.tabIndex=0,document.body.appendChild(this.hiddenInput)}setupEventListeners(){if(!this.hiddenInput)return;this.abortController=new AbortController;const{signal:t}=this.abortController;this.hiddenInput.addEventListener("input",this.handleTextInput,{signal:t}),this.hiddenInput.addEventListener("keydown",this.handleKeyDown,{signal:t}),this.hiddenInput.addEventListener("compositionstart",this.handleCompositionStart,{signal:t}),this.hiddenInput.addEventListener("compositionend",this.handleCompositionEnd,{signal:t}),this.hiddenInput.addEventListener("focus",this.handleFocus,{signal:t}),this.hiddenInput.addEventListener("blur",this.handleBlur,{signal:t}),this.hiddenInput.addEventListener("paste",this.handlePaste,{signal:t})}removeAllEventListeners(){this.abortController?.abort(),this.abortController=null}handleTextInput=t=>{if(!this.hiddenInput||this.isComposing)return;const e=this.hiddenInput.value,i=this.hiddenInput.selectionStart||0;this.lastSyncedText=e,this.textChangeCallback?.(e,i)};handleKeyDown=t=>{if(document.activeElement!==this.hiddenInput)return;let e=!1;if((t.ctrlKey||t.metaKey)&&(e=this.handleKeyboardShortcuts(t),e)){t.preventDefault();return}if(t.key==="Tab"){const i=t.shiftKey?"backward":"forward";this.eventHandlers.onTabNavigation?.(i),t.preventDefault();return}switch(t.key){case"Escape":this.eventHandlers.onEscape?.(t),e=!0;break;case"Enter":e=!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),e=!1;break;case"Backspace":case"Delete":e=!1;break;default:e=this.eventHandlers.onCustomKey?.(t.key,t)||!1;break}e&&t.preventDefault()};handleKeyboardShortcuts(t){const{key:e}=t;switch(e.toLowerCase()){case"a":return this.selectAll(),!0;case"c":case"v":return!1;case"z":return this.eventHandlers.onCustomKey?.("undo",t),!0;case"y":return this.eventHandlers.onCustomKey?.("redo",t),!0;default:return!1}}handleCompositionStart=t=>{this.isComposing=!0};handleCompositionEnd=t=>{if(this.isComposing=!1,this.hiddenInput){const e=this.hiddenInput.value,i=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(e,i)}};handleFocus=t=>{this.isFocused=!0,this.focusRetryCount=0,this.eventHandlers.onFocus?.(t)};handleBlur=t=>{this.isFocused=!1,this.eventHandlers.onBlur?.(t)};handlePaste=t=>{setTimeout(()=>{this.handleTextInput(t)},0)};selectAll(){this.hiddenInput&&this.hiddenInput.select()}}class us{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(t,e,i){this.parent=t,this.targetText=e,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 t=structuredClone(this.clipConfig);this.targetText.visible=!1,this.createEditingEnvironment(),this.setupOutsideClickHandler(t),this.isEditing=!0}stopEditing(t=!1,e){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,t&&e&&i!==""&&this.parent.updateTextContent(i,e),this.isEditing=!1}checkForDoubleClick=t=>{const e=Date.now();e-this.lastClickTime<us.DOUBLE_CLICK_THRESHOLD_MS&&this.startEditing(),this.lastClickTime=e};setupOutsideClickHandler(t){this.outsideClickHandler=e=>{const a=this.parent.getContainer().getBounds(),n=e.clientX,r=e.clientY;(n<a.x||n>a.x+a.width||r<a.y||r>a.y+a.height)&&(this.stopEditing(!0,t),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null))},setTimeout(()=>{this.outsideClickHandler&&window.addEventListener("click",this.outsideClickHandler)},us.CLICK_HANDLER_DELAY_MS)}createEditingEnvironment(){this.setupEditingContainer(),this.editingContainer&&this.editableText&&(this.textCursor=new ja(this.editingContainer,this.editableText,this.clipConfig),this.textCursor.updatePosition(this.targetText.text.length),this.textCursor.startBlinking()),this.setupTextInputHandler(),this.updateTextAlignment()}setupEditingContainer(){this.editingContainer=new X.Container,this.parent.getContainer().addChild(this.editingContainer);const t=new X.Graphics;t.fillStyle={color:0,alpha:us.EDITING_BG_ALPHA},t.rect(-5,-5,this.targetText.width+2*us.EDITING_BG_PADDING_PX,this.targetText.height+2*us.EDITING_BG_PADDING_PX),t.fill(),this.editingContainer.addChild(t),this.editableText=new X.Text(this.targetText.text,this.targetText.style),this.editableText.eventMode="static",this.editableText.cursor="text",this.editingContainer.addChild(this.editableText)}setupTextInputHandler(){this.textInputHandler=new ur,this.textInputHandler.setTextInputHandler((t,e)=>{this.editableText&&(this.editableText.text=t,this.updateTextAlignment()),this.textCursor?.updatePosition(e)}),this.textInputHandler.setEventHandlers({onEscape:t=>this.stopEditing(!1),onTabNavigation:t=>this.stopEditing(!0)}),this.textInputHandler.setupInput(this.targetText.text,{autoFocus:!0})}updateTextAlignment(){if(!this.editableText||!this.editingContainer)return;const t=this.getContainerDimensions(),e=this.getAlignmentSettings(),i=this.calculateHorizontalPosition({width:this.editableText.width},t,e.horizontal),a=this.calculateVerticalPosition({height:this.editableText.height},t,e.vertical);if(this.editingContainer.position.set(i,a),this.editingContainer.children.length>0){const n=this.editingContainer.getChildAt(0);n instanceof X.Graphics&&(n.clear(),n.fillStyle={color:0,alpha:us.EDITING_BG_ALPHA},n.rect(-5,-5,this.editableText.width+2*us.EDITING_BG_PADDING_PX,this.editableText.height+2*us.EDITING_BG_PADDING_PX),n.fill())}}calculateHorizontalPosition(t,e,i="center"){switch(i){case"center":return e.width/2-t.width/2;case"right":return e.width-t.width;case"left":default:return 0}}calculateVerticalPosition(t,e,i="center"){switch(i){case"center":return e.height/2-t.height/2;case"bottom":return e.height-t.height;case"top":default:return 0}}getContainerDimensions(){const t=this.clipConfig.asset;return{width:t.width??this.parent.getSize().width,height:t.height??this.parent.getSize().height}}getAlignmentSettings(){const t=this.clipConfig.asset;return{horizontal:t.alignment?.horizontal??"center",vertical:t.alignment?.vertical??"center"}}}class Ji extends je{static loadedFonts=new Set;background=null;text=null;textEditor=null;constructor(t,e){super(t,e,qt.Text)}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.font?.family??"Open Sans";if(await this.loadFont(e),this.background=new X.Graphics,this.drawBackground(),this.text=new X.Text({text:t.text??"",style:this.createTextStyle(t)}),this.positionText(t),t.stroke?.width&&t.stroke.width>0&&t.stroke.color){const i=new ba({thickness:t.stroke.width,color:t.stroke.color});this.text.filters=[i]}this.contentContainer.addChild(this.background),this.contentContainer.addChild(this.text),this.configureKeyframes(),this.textEditor=new us(this,this.text,this.clipConfiguration)}update(t,e){super.update(t,e)}reconfigureAfterRestore(){super.reconfigureAfterRestore(),this.reconfigure()}async reconfigure(){const t=this.clipConfiguration.asset,e=t.font?.family??"Open Sans";if(await this.loadFont(e),this.drawBackground(),this.text){if(this.text.text=t.text??"",this.text.style=this.createTextStyle(t),t.stroke?.width&&t.stroke.width>0&&t.stroke.color){const i=new ba({thickness:t.stroke.width,color:t.stroke.color});this.text.filters=[i]}else this.text.filters=[];this.positionText(t)}}dispose(){super.dispose(),this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null,this.textEditor?.dispose(),this.textEditor=null}getSize(){const t=this.clipConfiguration.asset;return{width:this.clipConfiguration.width??t.width??this.edit.size.width,height:this.clipConfiguration.height??t.height??this.edit.size.height}}getFitScale(){return 1}getContainerScale(){const t=this.getScale();return{x:t,y:t}}supportsEdgeResize(){return!0}onDimensionsChanged(){if(this.drawBackground(),this.text){const t=this.clipConfiguration.asset;this.text.style.wordWrapWidth=this.getSize().width,this.positionText(t)}}applyFixedDimensions(){}createTextStyle(t){const e=t.font?.family??"Open Sans",{baseFontFamily:i,fontWeight:a}=Rs(e),{width:n}=this.getSize();return new X.TextStyle({fontFamily:i,fontSize:t.font?.size??32,fill:t.font?.color??"#ffffff",fontWeight:a.toString(),wordWrap:!0,wordWrapWidth:n,lineHeight:(t.font?.lineHeight??1)*(t.font?.size??32),align:t.alignment?.horizontal??"center"})}positionText(t){if(!this.text)return;const e=t.alignment?.horizontal??"center",i=t.alignment?.vertical??"center",{width:a,height:n}=this.getSize();let r=a/2-this.text.width/2,o=n/2-this.text.height/2;e==="left"?r=0:e==="right"&&(r=a-this.text.width),i==="top"?o=0:i==="bottom"&&(o=n-this.text.height),this.text.position.set(r,o)}drawBackground(){const t=this.clipConfiguration.asset;if(!this.background||!t.background||!t.background.color)return;const{width:e,height:i}=this.getSize();this.background.clear(),this.background.fillStyle={color:t.background.color,alpha:t.background.opacity??1},this.background.rect(0,0,e,i),this.background.fill()}updateTextContent(t,e){this.edit.updateTextContent(this,t,e)}async loadFont(t){const{baseFontFamily:e,fontWeight:i}=Rs(t),a=`${e}-${i}`;if(Ji.loadedFonts.has(a))return;const n=Wr(t);if(n){const r=new FontFace(e,`url(${n})`,{weight:i.toString()});await r.load(),document.fonts.add(r),Ji.loadedFonts.add(a)}}static resetFontCache(){Ji.loadedFonts.clear()}}class tN extends je{texture;sprite;isPlaying;volumeKeyframeBuilder;syncTimer;activeSyncTimer;skipVideoUpdate;constructor(t,e){super(t,e,qt.Video),this.texture=null,this.sprite=null,this.isPlaying=!1;const i=this.clipConfiguration.asset;this.volumeKeyframeBuilder=new ga(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(t,e){if(super.update(t,e),this.skipVideoUpdate)return;const{trim:i=0}=this.clipConfiguration.asset;if(this.syncTimer+=e,!this.texture)return;const a=this.getPlaybackTime(),n=this.edit.isPlaying&&this.isActive();n&&(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+=e,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()))),!n&&this.isPlaying&&(this.isPlaying=!1,this.texture.source.resource.pause());const r=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&r&&(this.syncTimer=0,this.texture.source.resource.currentTime=a+i)}draw(){super.draw()}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 t=this.clipConfiguration.asset,{src:e}=t;if(e.endsWith(".mov"))throw new Error(`Video source '${e}' is not supported. .mov files cannot be played in the browser. Please convert to .webm or .mp4 first.`);const i=`${e}${e.includes("?")?"&":"?"}x-cors=1`,a={src:i,data:{autoPlay:!1,muted:!1}},n=await this.edit.assetLoader.loadVideoUnique(i,a);if(!n||!(n.source instanceof X.VideoSource))throw new Error(`Invalid video source '${e}'.`);n.source.alphaMode="no-premultiply-alpha",this.texture=this.createCroppedTexture(n);const r=this.texture.source.resource;r instanceof HTMLVideoElement&&r.readyState<2&&await new Promise(o=>{const l=()=>{r.removeEventListener("loadeddata",l),o()};r.addEventListener("loadeddata",l),r.readyState>=2&&o()}),this.sprite=new X.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:t=0}=this.clipConfiguration.asset,e=this.texture.source.resource.currentTime,i=this.getPlaybackTime();return Math.abs(e-t-i)}createCroppedTexture(t){const e=this.clipConfiguration.asset;if(!e.crop)return t;const i=t.width,a=t.height;if(i<=0||a<=0)return t;const n=Math.floor((e.crop?.left??0)*i),r=Math.floor((e.crop?.right??0)*i),o=Math.floor((e.crop?.top??0)*a),l=Math.floor((e.crop?.bottom??0)*a),c=n,d=o,u=i-n-r,f=a-o-l,p=new X.Rectangle(c,d,u,f);return new X.Texture({source:t.source,frame:p})}}const Qh=16711935,Jh=2,rl=6,$h=4;class eN{graphics;canvasWidth;canvasHeight;constructor(t,e,i){this.canvasWidth=e,this.canvasHeight=i,this.graphics=new X.Graphics,this.graphics.zIndex=999999,t.addChild(this.graphics)}clear(){this.graphics.clear()}drawCanvasGuide(t,e){this.graphics.strokeStyle={width:Jh,color:Qh},t==="x"?(this.graphics.moveTo(e,0),this.graphics.lineTo(e,this.canvasHeight)):(this.graphics.moveTo(0,e),this.graphics.lineTo(this.canvasWidth,e)),this.graphics.stroke()}drawClipGuide(t,e,i,a){t==="x"?this.drawDashedLine(e,i,e,a):this.drawDashedLine(i,e,a,e)}drawDashedLine(t,e,i,a){const n=i-t,r=a-e,o=Math.sqrt(n*n+r*r),l=Math.floor(o/(rl+$h)),c=n/o,d=r/o;this.graphics.strokeStyle={width:Jh,color:Qh};for(let u=0;u<l;u+=1){const f=u*(rl+$h),p=f+rl,y=t+c*f,v=e+d*f,S=t+c*Math.min(p,o),x=e+d*Math.min(p,o);this.graphics.moveTo(y,v),this.graphics.lineTo(S,x)}this.graphics.stroke()}dispose(){this.graphics.destroy()}}const sN=/^alias:\/\/([a-zA-Z0-9_-]+)$/;function ol(s,t){for(let e=0;e<s.timeline.tracks.length;e+=1){const i=s.timeline.tracks[e];for(let a=0;a<i.clips.length;a+=1)t(i.clips[a],e,a)}}function hr(s){if(typeof s!="string")return null;const t=s.match(sN);return t?t[1]:null}function iN(s){const t={};return ol(s,(e,i,a)=>{e.alias&&(t[e.alias]&&console.warn(`Duplicate alias "${e.alias}" at track ${i}, clip ${a} - overwriting previous`),t[e.alias]=e)}),t}function aN(s){const t=new Map;return ol(s,(e,i,a)=>{const n=e.alias??`t${i}c${a}`,r=new Set,o=hr(e.start);o&&r.add(o);const l=hr(e.length);l&&r.add(l),r.size>0&&t.set(n,r)}),t}function nN(s){const t=new Set,e=new Set;function i(a,n){t.add(a),e.add(a);const r=s.get(a);if(r)for(const o of r){if(e.has(o))return[...n,o];if(!t.has(o)){const l=i(o,[...n,o]);if(l)return l}}return e.delete(a),null}for(const a of s.keys())if(!t.has(a)){const n=i(a,[a]);if(n)return n}return null}function rN(s,t){const e=[],i=new Set,a=new Set([...s.keys(),...Object.keys(t)]);function n(r){if(i.has(r))return;i.add(r);const o=s.get(r);if(o)for(const l of o)n(l);e.push(r)}for(const r of a)n(r);return e}function oN(s){const t=aN(s);if(t.size===0)return;const e=nN(t);if(e)throw new Error(`Circular alias reference detected: ${e.join(" -> ")}`);const i=iN(s),a=new Map;ol(s,(r,o,l)=>{const c=r.alias??`t${o}c${l}`;a.set(c,r)});const n=rN(t,i);for(const r of n){const o=a.get(r);if(o){const l=hr(o.start);if(l){const d=i[l];if(!d)throw new Error(`Alias "${l}" not found. Available: ${Object.keys(i).join(", ")||"none"}`);if(typeof d.start!="number")throw new Error(`Cannot resolve alias "${l}": target has unresolved start`);o.start=d.start}const c=hr(o.length);if(c){const d=i[c];if(!d)throw new Error(`Alias "${c}" not found. Available: ${Object.keys(i).join(", ")||"none"}`);if(typeof d.length!="number")throw new Error(`Cannot resolve alias "${c}": target has unresolved length`);o.length=d.length}}}}class lN{constructor(t,e){this.trackIdx=t,this.clip=e}name="addClip";addedPlayer;async execute(t){if(t)try{const e=t.createPlayerFromAssetType(this.clip);e.layer=this.trackIdx+1,await t.addPlayer(this.trackIdx,e);const n=t.getClips().filter(r=>r.layer===e.layer).findIndex(r=>r===e);t.updateDuration(),t.emitEvent(j.ClipAdded,{trackIndex:this.trackIdx,clipIndex:n}),this.addedPlayer=e}catch(e){const i=this.clip.asset.type??"unknown";t.emitEvent(j.ClipLoadFailed,{trackIndex:this.trackIdx,clipIndex:-1,error:e instanceof Error?e.message:String(e),assetType:i})}}async undo(t){if(!t||!this.addedPlayer)return;const a=t.getClips().filter(n=>n.layer===this.addedPlayer.layer).findIndex(n=>n===this.addedPlayer);t.queueDisposeClip(this.addedPlayer),t.updateDuration(),t.emitEvent(j.ClipDeleted,{trackIndex:this.trackIdx,clipIndex:a})}}class tf{constructor(t){this.trackIdx=t}name="addTrack";execute(t){if(!t)return;const e=t.getTracks(),i=t.getClips();e.splice(this.trackIdx,0,[]),i.forEach(a=>{if(a.layer>this.trackIdx){const n=1e5-a.layer*100,r=t.getContainer().getChildByLabel(`shotstack-track-${n}`,!1);r&&r.removeChild(a.getContainer()),a.layer+=1;const o=1e5-a.layer*100;let l=t.getContainer().getChildByLabel(`shotstack-track-${o}`,!1);l||(l=new X.Container({label:`shotstack-track-${o}`,zIndex:o}),t.getContainer().addChild(l)),l.addChild(a.getContainer())}}),t.getContainer().sortDirty=!0,t.updateDuration(),t.emitEvent(j.TrackAdded,{trackIndex:this.trackIdx,totalTracks:e.length})}undo(t){if(!t)return;const e=t.getTracks(),i=t.getClips();e.splice(this.trackIdx,1),i.forEach(a=>{if(a.layer>this.trackIdx){const n=1e5-a.layer*100,r=t.getContainer().getChildByLabel(`shotstack-track-${n}`,!1);r&&r.removeChild(a.getContainer()),a.layer-=1;const o=1e5-a.layer*100;let l=t.getContainer().getChildByLabel(`shotstack-track-${o}`,!1);l||(l=new X.Container({label:`shotstack-track-${o}`,zIndex:o}),t.getContainer().addChild(l)),l.addChild(a.getContainer())}}),t.getContainer().sortDirty=!0,t.updateDuration()}}class cN{name="ClearSelection";previousSelection=null;execute(t){const e=t.getSelectedClip();if(e){const i=t.findClipIndices(e);i&&(this.previousSelection={player:e,trackIndex:i.trackIndex,clipIndex:i.clipIndex})}t.setSelectedClip(null),t.emitEvent(j.SelectionCleared)}undo(t){if(this.previousSelection){const e=t.getClipAt(this.previousSelection.trackIndex,this.previousSelection.clipIndex);e&&(t.setSelectedClip(e),t.emitEvent(j.ClipSelected,{clip:e.clipConfiguration,trackIndex:this.previousSelection.trackIndex,clipIndex:this.previousSelection.clipIndex}))}}}class ll{constructor(t){this.trackIdx=t}name="deleteTrack";deletedClips=[];execute(t){if(!t)return;const e=t.getClips(),i=t.getTracks();this.deletedClips=e.filter(r=>r.layer===this.trackIdx+1).map(r=>({config:structuredClone(r.clipConfiguration),bindings:new Map(r.getMergeFieldBindings())})),e.forEach((r,o)=>{r.layer===this.trackIdx+1&&(e[o].shouldDispose=!0)}),t.disposeClips(),i.splice(this.trackIdx,1);const a=t.getClips(),n=t.getContainer();a.forEach((r,o)=>{if(r.layer>this.trackIdx+1){n.getChildByLabel(`shotstack-track-${1e5-r.layer*100}`,!1)?.removeChild(r.getContainer()),a[o].layer-=1;const c=1e5-a[o].layer*100;let d=n.getChildByLabel(`shotstack-track-${c}`,!1);d||(d=new X.Container({label:`shotstack-track-${c}`,zIndex:c}),n.addChild(d)),d.addChild(a[o].getContainer())}}),t.updateDuration(),t.emitEvent(j.TrackRemoved,{trackIndex:this.trackIdx})}async undo(t){if(!t)return;const e=t.getTracks(),i=t.getClips();e.splice(this.trackIdx,0,[]),i.forEach((a,n)=>{a.layer>=this.trackIdx+1&&(i[n].layer+=1)});for(const{config:a,bindings:n}of this.deletedClips){const r=t.createPlayerFromAssetType(a);r.layer=this.trackIdx+1,n.size>0&&r.setInitialBindings(n),await t.addPlayer(this.trackIdx,r)}t.updateDuration()}}class fr{constructor(t,e){this.trackIdx=t,this.clipIdx=e}name="deleteClip";deletedClip;deleteTrackCommand;trackWasDeleted=!1;execute(t){if(!t)return;const e=t.getClips(),i=t.getTracks(),a=e.filter(n=>n.layer===this.trackIdx+1);if(this.deletedClip=a[this.clipIdx],t.clearClipError(this.trackIdx,this.clipIdx),this.deletedClip){t.queueDisposeClip(this.deletedClip),t.disposeClips(),t.updateDuration(),t.propagateTimingChanges(this.trackIdx,this.clipIdx-1);const n=i[this.trackIdx];n&&n.length===0&&(this.deleteTrackCommand=new ll(this.trackIdx),this.deleteTrackCommand.execute(t),this.trackWasDeleted=!0),t.emitEvent(j.ClipDeleted,{trackIndex:this.trackIdx,clipIndex:this.clipIdx}),t.getSelectedClip()===this.deletedClip&&(t.setSelectedClip(null),t.emitEvent(j.SelectionCleared))}}async undo(t){!t||!this.deletedClip||(this.trackWasDeleted&&this.deleteTrackCommand&&(await this.deleteTrackCommand.undo(t),this.trackWasDeleted=!1),t.undeleteClip(this.trackIdx,this.deletedClip),t.propagateTimingChanges(this.trackIdx,this.clipIdx),t.emitEvent(j.ClipRestored,{trackIndex:this.trackIdx,clipIndex:this.clipIdx}))}}class dN{constructor(t,e){this.trackIndex=t,this.clipIndex=e}name="SelectClip";previousSelection=null;execute(t){const e=t.getSelectedClip();if(e){const a=t.findClipIndices(e);a&&(this.previousSelection=a)}const i=t.getClipAt(this.trackIndex,this.clipIndex);i&&(t.setSelectedClip(i),t.emitEvent(j.ClipSelected,{clip:i.clipConfiguration,trackIndex:this.trackIndex,clipIndex:this.clipIndex}))}undo(t){if(t.setSelectedClip(null),this.previousSelection){const e=t.getClipAt(this.previousSelection.trackIndex,this.previousSelection.clipIndex);e&&(t.setSelectedClip(e),t.emitEvent(j.ClipSelected,{clip:e.clipConfiguration,trackIndex:this.previousSelection.trackIndex,clipIndex:this.previousSelection.clipIndex}))}else t.emitEvent(j.SelectionCleared)}}class ef{constructor(t,e,i,a){this.clip=t,this.initialClipConfig=e,this.finalClipConfig=i,this.storedInitialConfig=e?structuredClone(e):null,this.storedFinalConfig=i?structuredClone(i):structuredClone(this.clip.clipConfiguration),this.trackIndex=a?.trackIndex??-1,this.clipIndex=a?.clipIndex??-1}name="setUpdatedClip";storedInitialConfig;storedFinalConfig;storedInitialBindings=new Map;trackIndex;clipIndex;storedInitialTiming=null;async execute(t){if(!t)return;this.storedInitialBindings=new Map(this.clip.getMergeFieldBindings()),this.storedFinalConfig&&t.restoreClipConfiguration(this.clip,this.storedFinalConfig);const e=this.storedFinalConfig.start!==this.storedInitialConfig?.start,i=this.storedFinalConfig.length!==this.storedInitialConfig?.length;(e||i)&&(this.storedInitialTiming={start:this.clip.getStart(),length:this.clip.getLength()},this.clip.setTimingIntent({start:this.storedFinalConfig.start,length:this.storedFinalConfig.length}),this.clip.setResolvedTiming({start:this.storedFinalConfig.start,length:this.storedFinalConfig.length})),t.setUpdatedClip(this.clip);for(const[u,{resolvedValue:f}]of this.storedInitialBindings)Ei(this.clip.clipConfiguration,u)!==f&&this.clip.removeMergeFieldBinding(u);const a=this.trackIndex>=0?this.trackIndex:this.clip.layer-1,r=t.getClips().filter(u=>u.layer===this.clip.layer),o=this.clipIndex>=0?this.clipIndex:r.indexOf(this.clip),l=this.storedInitialConfig?.asset,c=this.storedFinalConfig?.asset;l?.src!==c?.src&&this.clip.getTimingIntent().length==="auto"&&await t.resolveClipAutoLength(this.clip);const d=this.storedInitialConfig??this.initialClipConfig??this.clip.clipConfiguration;t.emitEvent(j.ClipUpdated,{previous:{clip:d,trackIndex:a,clipIndex:o},current:{clip:this.storedFinalConfig,trackIndex:a,clipIndex:o}})}async undo(t){if(!t||!this.storedInitialConfig)return;t.restoreClipConfiguration(this.clip,this.storedInitialConfig),this.storedInitialTiming&&(this.clip.setTimingIntent({start:this.storedInitialTiming.start,length:this.storedInitialTiming.length}),this.clip.setResolvedTiming({start:this.storedInitialTiming.start,length:this.storedInitialTiming.length})),t.setUpdatedClip(this.clip),this.clip.setInitialBindings(this.storedInitialBindings);const e=this.trackIndex>=0?this.trackIndex:this.clip.layer-1,a=t.getClips().filter(l=>l.layer===this.clip.layer),n=this.clipIndex>=0?this.clipIndex:a.indexOf(this.clip),r=this.storedFinalConfig?.asset,o=this.storedInitialConfig?.asset;r?.src!==o?.src&&this.clip.getTimingIntent().length==="auto"&&await t.resolveClipAutoLength(this.clip),t.emitEvent(j.ClipUpdated,{previous:{clip:this.storedFinalConfig,trackIndex:e,clipIndex:n},current:{clip:this.storedInitialConfig,trackIndex:e,clipIndex:n}})}}class uN{constructor(t,e,i){this.trackIndex=t,this.clipIndex=e,this.splitTime=i}name="SplitClip";originalClipConfig=null;rightClipPlayer=null;splitSuccessful=!1;originalBindings=new Map;execute(t){const e=t.getClipAt(this.trackIndex,this.clipIndex);if(!e||!e.clipConfiguration)throw new Error("Cannot split clip: invalid player or clip configuration");const i=e.clipConfiguration,a=i.start,n=i.length,r=.1,o=this.splitTime-a;if(o<=r||o>=n-r)throw new Error("Cannot split clip: split point too close to clip boundaries");this.originalClipConfig={...i},this.originalBindings=new Map(e.getMergeFieldBindings());const l={...i,length:o},c={...i,start:a+o,length:n-o};if(i.asset&&(l.asset={...i.asset},c.asset={...i.asset}),i.asset&&(i.asset.type==="video"||i.asset.type==="audio")){const p=i.asset.trim||0;l.asset&&(l.asset.type==="video"||l.asset.type==="audio")&&(l.asset.trim=p),c.asset&&(c.asset.type==="video"||c.asset.type==="audio")&&(c.asset.trim=p+o)}if(Object.assign(e.clipConfiguration,l),e.reconfigureAfterRestore(),e.draw(),this.rightClipPlayer=t.createPlayerFromAssetType(c),!this.rightClipPlayer)throw Object.assign(e.clipConfiguration,this.originalClipConfig),e.reconfigureAfterRestore(),new Error("Failed to create right clip player");this.rightClipPlayer.layer=this.trackIndex+1,this.originalBindings.size>0&&this.rightClipPlayer.setInitialBindings(this.originalBindings);const d=t.getTrack(this.trackIndex);if(!d)throw new Error("Invalid track index");d.splice(this.clipIndex+1,0,this.rightClipPlayer);const u=t.getClips(),f=u.indexOf(e);f!==-1&&u.splice(f+1,0,this.rightClipPlayer),t.addPlayerToContainer(this.trackIndex,this.rightClipPlayer),this.rightClipPlayer.reconfigureAfterRestore(),this.rightClipPlayer.load().then(()=>{this.splitSuccessful=!0,this.rightClipPlayer&&this.rightClipPlayer.draw(),t.updateDuration(),t.emitEvent(j.ClipSplit,{trackIndex:this.trackIndex,originalClipIndex:this.clipIndex,newClipIndex:this.clipIndex+1})}).catch(p=>{console.error("Failed to load split clip:",p)})}undo(t){if(!this.originalClipConfig)return;const e=t.getClipAt(this.trackIndex,this.clipIndex);if(e){if(Object.assign(e.clipConfiguration,this.originalClipConfig),e.reconfigureAfterRestore(),this.rightClipPlayer){const i=t.getTrack(this.trackIndex);if(i){const r=i.indexOf(this.rightClipPlayer);r!==-1&&i.splice(r,1)}const a=t.getClips(),n=a.indexOf(this.rightClipPlayer);n!==-1&&a.splice(n,1),t.queueDisposeClip(this.rightClipPlayer),this.rightClipPlayer=null}t.updateDuration(),t.emitEvent(j.ClipDeleted,{trackIndex:this.trackIndex,clipIndex:this.clipIndex+1})}}}class sf{constructor(t,e,i){this.trackIndex=t,this.clipIndex=e,this.targetAssetType=i}name="TransformClipAsset";originalPlayer=null;originalConfig=null;originalAssetType=null;originalBindings=new Map;newPlayer=null;loadCompleted=!1;execute(t){const e=t.getClipAt(this.trackIndex,this.clipIndex);if(!e?.clipConfiguration)throw new Error("Cannot transform clip: invalid player");this.originalPlayer=e,this.originalConfig={...e.clipConfiguration},this.originalAssetType=this.originalConfig.asset?.type??null,this.originalBindings=new Map(e.getMergeFieldBindings()),this.loadCompleted=!1;const i=this.originalConfig.asset;if(!i.src)throw new Error("Cannot transform clip: asset has no src property");const a={type:this.targetAssetType,src:i.src},n={...this.originalConfig,asset:a};if(this.newPlayer=t.createPlayerFromAssetType(n),!this.newPlayer)throw new Error("Failed to create transformed player");this.newPlayer.layer=this.trackIndex+1,this.originalBindings.size>0&&this.newPlayer.setInitialBindings(this.originalBindings);const r=t.getTrack(this.trackIndex);if(!r)throw new Error("Invalid track index");r[this.clipIndex]=this.newPlayer;const o=t.getClips(),l=o.indexOf(this.originalPlayer);l!==-1&&(o[l]=this.newPlayer),t.addPlayerToContainer(this.trackIndex,this.newPlayer),this.newPlayer.reconfigureAfterRestore(),this.newPlayer.load().then(()=>{this.loadCompleted=!0,this.newPlayer&&this.newPlayer.draw(),t.emitEvent(j.ClipUpdated,{previous:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:this.originalConfig},current:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:n}}),this.originalPlayer&&t.queueDisposeClip(this.originalPlayer)}).catch(c=>{console.error("Failed to load transformed clip:",c)})}undo(t){if(!this.originalPlayer||!this.originalConfig)return;const e=t.getTrack(this.trackIndex);e&&this.newPlayer&&(e[this.clipIndex]=this.originalPlayer);const i=t.getClips();if(this.newPlayer){const a=i.indexOf(this.newPlayer);a!==-1&&(i[a]=this.originalPlayer)}t.addPlayerToContainer(this.trackIndex,this.originalPlayer),this.originalPlayer.reconfigureAfterRestore(),this.originalPlayer.draw(),this.newPlayer&&t.queueDisposeClip(this.newPlayer),t.emitEvent(j.ClipUpdated,{previous:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:this.newPlayer?.clipConfiguration},current:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:this.originalConfig}}),this.newPlayer=null}getOriginalAssetType(){return this.originalAssetType}isLoadCompleted(){return this.loadCompleted}}const hN=3;function fN(s){return new Promise(t=>{const e=document.createElement("video");e.preload="metadata",e.crossOrigin="anonymous",e.onloadedmetadata=()=>t(e.duration),e.onerror=()=>t(null),e.src=s})}async function af(s){const t=s;if(["video","audio","luma"].includes(t.type)&&t.src){const e=await fN(t.src);if(e!==null&&!Number.isNaN(e)){const i=t.trim??0;return e-i}}return hN}function pr(s,t,e){return t===0?0:e[s][t-1].getEnd()}function nf(s,t){return Math.max(0,t-s)}function cl(s){let t=0;for(const e of s)for(const i of e)i.getTimingIntent().length!=="end"&&(t=Math.max(t,i.getEnd()));return t}class pN{constructor(t,e,i){this.trackIndex=t,this.clipIndex=e,this.params=i}name="UpdateClipTiming";player=null;originalIntent=null;previousConfig=null;execute(t){if(!t)return;const e=t.getTrack(this.trackIndex);if(!e||this.clipIndex<0||this.clipIndex>=e.length){console.warn(`Invalid track/clip index: ${this.trackIndex}/${this.clipIndex}`);return}this.player=e[this.clipIndex],this.originalIntent=this.player.getTimingIntent(),this.previousConfig=JSON.parse(JSON.stringify(this.player.clipConfiguration));const i={start:this.originalIntent.start,length:this.originalIntent.length};this.params.start!==void 0&&(i.start=this.params.start==="auto"?"auto":this.params.start/1e3),this.params.length!==void 0&&(this.params.length==="auto"||this.params.length==="end"?i.length=this.params.length:i.length=this.params.length/1e3),this.player.setTimingIntent(i),this.updateClipConfiguration(this.player,i);const a=i.start==="auto"?pr(this.trackIndex,this.clipIndex,t.getTracks()):i.start;if(i.length==="auto")this.player.setResolvedTiming({start:a,length:this.player.getLength()}),t.resolveClipAutoLength(this.player).then(()=>{this.player?.reconfigureAfterRestore(),this.player?.draw(),t.updateDuration(),t.propagateTimingChanges(this.trackIndex,this.clipIndex)}),this.player.reconfigureAfterRestore(),this.player.draw();else if(i.length==="end"){t.trackEndLengthClip(this.player);const n=cl(t.getTracks()),r=Math.max(n-a,.1);this.player.setResolvedTiming({start:a,length:r}),this.player.reconfigureAfterRestore(),this.player.draw()}else t.untrackEndLengthClip(this.player),this.player.setResolvedTiming({start:a,length:i.length}),this.player.reconfigureAfterRestore(),this.player.draw();t.updateDuration(),t.emitEvent(j.ClipUpdated,{previous:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:this.previousConfig},current:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:this.player.clipConfiguration}}),t.propagateTimingChanges(this.trackIndex,this.clipIndex)}undo(t){!t||!this.player||!this.originalIntent||(this.player.setTimingIntent(this.originalIntent),this.previousConfig&&t.restoreClipConfiguration(this.player,this.previousConfig),this.originalIntent.length==="auto"?t.resolveClipAutoLength(this.player):this.originalIntent.length==="end"?t.trackEndLengthClip(this.player):t.untrackEndLengthClip(this.player),this.player.reconfigureAfterRestore(),this.player.draw(),t.updateDuration(),t.emitEvent(j.ClipUpdated,{previous:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:this.player.clipConfiguration},current:{trackIndex:this.trackIndex,clipIndex:this.clipIndex,clip:this.previousConfig}}),t.propagateTimingChanges(this.trackIndex,this.clipIndex))}updateClipConfiguration(t,e){const i=t.clipConfiguration;e.start!=="auto"&&(i.start=e.start),e.length!=="auto"&&e.length!=="end"&&(i.length=e.length)}}class gN{constructor(t,e,i){this.clip=t,this.newText=e,this.initialConfig=i;const{asset:a}=this.clip.clipConfiguration;this.previousText=a&&"text"in a?a.text??"":""}name="updateTextContent";previousText;execute(t){if(t&&this.clip.clipConfiguration.asset&&"text"in this.clip.clipConfiguration.asset){this.clip.clipConfiguration.asset.text=this.newText;const e=this.clip.text;e&&(e.text=this.newText,this.clip.positionText(this.clip.clipConfiguration.asset)),t.setUpdatedClip(this.clip);const i=this.clip.layer-1,r=t.getClips().filter(o=>o.layer===this.clip.layer).indexOf(this.clip);t.emitEvent(j.ClipUpdated,{previous:{clip:this.initialConfig,trackIndex:i,clipIndex:r},current:{clip:this.clip.clipConfiguration,trackIndex:i,clipIndex:r}})}}undo(t){if(t&&this.clip.clipConfiguration.asset&&"text"in this.clip.clipConfiguration.asset){this.clip.clipConfiguration.asset.text=this.previousText;const e=this.clip.text;e&&(e.text=this.previousText,this.clip.positionText(this.clip.clipConfiguration.asset)),t.setUpdatedClip(this.clip);const i=this.clip.layer-1,r=t.getClips().filter(o=>o.layer===this.clip.layer).indexOf(this.clip);t.emitEvent(j.ClipUpdated,{previous:{clip:this.clip.clipConfiguration,trackIndex:i,clipIndex:r},current:{clip:this.initialConfig,trackIndex:i,clipIndex:r}})}}}class dl{events;constructor(){this.events={}}on(t,e){return this.events[t]||(this.events[t]=new Set),this.events[t].add(e),()=>this.off(t,e)}once(t,e){const i=a=>{this.off(t,i),e(a)};return this.on(t,i)}off(t,e){this.events[t]&&(this.events[t].delete(e),!(this.events[t].size>0)&&delete this.events[t])}clear(t){delete this.events[t]}emit(t,...e){if(!this.events[t])return;const i=e[0];for(const a of this.events[t])a(i)}}class mN{constructor(t,e,i){this.getCanvas=t,this.getTracks=e,this.events=i,this.onClipChangedBound=()=>this.rebuildLumaMasksIfNeeded()}activeLumaMasks=[];pendingMaskCleanup=[];onClipChangedBound;initialize(){this.finalizeLumaMasking(),this.setupEventListeners()}update(){this.updateLumaMasks(),this.processPendingMaskCleanup()}getActiveMaskCount(){return this.activeLumaMasks.length}dispose(){this.removeEventListeners();for(const t of this.activeLumaMasks)t.tempContainer.destroy({children:!0}),t.maskSprite.destroy({texture:!0});this.activeLumaMasks=[];for(const t of this.pendingMaskCleanup)try{t.maskSprite.parent?.removeChild(t.maskSprite),t.maskSprite.destroy({texture:!0})}catch{}this.pendingMaskCleanup=[]}cleanupForPlayer(t){const e=this.activeLumaMasks.findIndex(a=>a.lumaPlayer===t);if(e===-1)return;const i=this.activeLumaMasks[e];i.contentClip&&(i.contentClip.getContentContainer().mask=null),i.maskSprite.parent?.removeChild(i.maskSprite),i.tempContainer.destroy({children:!0}),this.activeLumaMasks.splice(e,1),this.pendingMaskCleanup.push({maskSprite:i.maskSprite,frameCount:0})}finalizeLumaMasking(){if(!this.getCanvas())return;const e=this.getTracks();for(const i of e){const a=i.find(o=>o.playerType===qt.Luma),n=a?.getSprite(),r=i.filter(o=>o.playerType!==qt.Luma);a&&n?.texture&&r.length>0&&(this.setupLumaMask(a,n.texture,r[0]),a.getContainer().parent?.removeChild(a.getContainer()))}}setupLumaMask(t,e,i){const a=this.getCanvas();if(!a)return;const{renderer:n}=a.application,{width:r,height:o}=i.getSize(),l=new X.Container,c=new X.Sprite(e);c.width=r,c.height=o;const d=new X.ColorMatrixFilter;d.negative(!1),c.filters=[d],l.addChild(c);const u=n.generateTexture({target:l,resolution:.5}),f=new X.Sprite(u);i.getContainer().addChild(f),i.getContentContainer().setMask({mask:f}),this.activeLumaMasks.push({lumaPlayer:t,maskSprite:f,tempContainer:l,contentClip:i,lastVideoTime:-1})}updateLumaMasks(){const t=this.getCanvas();if(!t)return;const{renderer:e}=t.application,i=1/30;for(const a of this.activeLumaMasks)if(a.lumaPlayer.isVideoSource()){const n=a.lumaPlayer.getVideoCurrentTime();if(Math.abs(n-a.lastVideoTime)>=i){a.lastVideoTime=n;const o=a.maskSprite.texture;a.maskSprite.texture=e.generateTexture({target:a.tempContainer,resolution:.5}),o.destroy(!0)}}}setupEventListeners(){this.events.on(j.ClipAdded,this.onClipChangedBound),this.events.on(j.ClipSplit,this.onClipChangedBound),this.events.on(j.ClipUpdated,this.onClipChangedBound),this.events.on(j.ClipRestored,this.onClipChangedBound),this.events.on(j.ClipDeleted,this.onClipChangedBound)}removeEventListeners(){this.events.off(j.ClipAdded,this.onClipChangedBound),this.events.off(j.ClipSplit,this.onClipChangedBound),this.events.off(j.ClipUpdated,this.onClipChangedBound),this.events.off(j.ClipRestored,this.onClipChangedBound),this.events.off(j.ClipDeleted,this.onClipChangedBound)}processPendingMaskCleanup(){for(let t=this.pendingMaskCleanup.length-1;t>=0;t-=1){const e=this.pendingMaskCleanup[t];if(e.frameCount+=1,e.frameCount>=3){try{e.maskSprite.parent?.removeChild(e.maskSprite),e.maskSprite.destroy({texture:!0})}catch{}this.pendingMaskCleanup.splice(t,1)}}}async rebuildLumaMasksIfNeeded(){if(!this.getCanvas())return;const e=this.getTracks();for(let i=0;i<e.length;i+=1){const a=e[i],n=a.find(l=>l.playerType===qt.Luma),r=a.filter(l=>l.playerType!==qt.Luma);n&&n.getContainer().parent?.removeChild(n.getContainer());const o=n&&this.activeLumaMasks.find(l=>l.lumaPlayer===n);if(n&&!o&&r.length>0){n.getSprite()||await n.load();const l=n.getSprite();l?.texture&&(this.setupLumaMask(n,l.texture,r[0]),n.getContainer().parent?.removeChild(n.getContainer()))}}}}function yN(s){return{find:s.name,replace:s.defaultValue}}function bN(s){const t=typeof s.replace=="string"?s.replace:JSON.stringify(s.replace);return{name:s.find,defaultValue:t}}const wN=/\{\{\s*([A-Z_0-9]+)\s*\}\}/gi,ul=/\{\{\s*[A-Z_0-9]+\s*\}\}/i;class vN{fields=new Map;events;constructor(t){this.events=t}register(t,e){const i=!this.fields.has(t.name);this.fields.set(t.name,t),e?.silent||(this.events.emit(i?j.MergeFieldRegistered:j.MergeFieldUpdated,{field:t}),this.events.emit(j.MergeFieldChanged,{fields:this.getAll()}))}remove(t,e){const i=this.fields.delete(t);return i&&!e?.silent&&(this.events.emit(j.MergeFieldRemoved,{name:t}),this.events.emit(j.MergeFieldChanged,{fields:this.getAll()})),i}get(t){return this.fields.get(t)}getAll(){return Array.from(this.fields.values())}clear(){this.fields.clear()}resolve(t){return!t||this.fields.size===0?t:t.replace(wN,(e,i)=>this.fields.get(i)?.defaultValue??e)}hasUnresolved(t){if(!t)return!1;const e=this.resolve(t);return ul.test(e)}extractFieldName(t){if(!t)return null;const e=ul.exec(t);if(!e)return null;const i=e[0].match(/\{\{\s*([A-Z_0-9]+)\s*\}\}/i);return i?i[1]:null}isMergeFieldTemplate(t){return ul.test(t)}createTemplate(t){return`{{ ${t} }}`}toSerializedArray(){return this.getAll().map(yN)}loadFromSerialized(t){this.fields.clear();for(const e of t)this.fields.set(e.find,bN(e))}generateUniqueName(t){const e=new Set(this.fields.keys());let i=1;for(;e.has(`${t}_${i}`);)i+=1;return`${t}_${i}`}}function xN(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function hl(s,t){if(typeof s=="string"){let e=s;for(const{find:i,replace:a}of t){const n=typeof a=="string"?a:JSON.stringify(a);e=e.replace(new RegExp(`\\{\\{\\s*${xN(i)}\\s*\\}\\}`,"gi"),n)}return e}if(Array.isArray(s))return s.map(e=>hl(e,t));if(s!==null&&typeof s=="object"){const e=s;for(const i of Object.keys(e))e[i]=hl(e[i],t)}return s}function CN(s,t){return t?.length?hl(structuredClone(s),t):s}class kN extends dl{registry;constructor(){super(),this.registry={}}}class gr{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 kN;refCounts=new Map;incrementRef(t){this.refCounts.set(t,(this.refCounts.get(t)??0)+1)}decrementRef(t){const e=this.refCounts.get(t)??0;return e<=1?(this.refCounts.delete(t),!0):(this.refCounts.set(t,e-1),!1)}constructor(){X.Assets.setPreferences({crossOrigin:"anonymous"})}async load(t,e){this.updateAssetLoadMetadata(t,"pending",0),this.incrementRef(t);try{if(await this.shouldUseSafariVideoLoader(e))return await this.loadVideoForSafari(t,e);const a=await X.Assets.load(e,n=>{this.updateAssetLoadMetadata(t,"loading",n)});return this.updateAssetLoadMetadata(t,"success",1),a}catch(i){return console.warn(`[AssetLoader] Failed to load asset "${t}":`,i),this.updateAssetLoadMetadata(t,"failed",1),this.decrementRef(t),null}}async loadVideoUnique(t,e){this.updateAssetLoadMetadata(t,"pending",0);try{const i=this.extractUrl(e);if(!i)throw new Error("No URL provided for video loading");const a=typeof e=="object"?e.data??{}:{},n=await new Promise((r,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 X.VideoSource({resource:l,autoPlay:a.autoPlay??!1,...a});r(new X.Texture({source:c}))}catch(c){o(c)}},{once:!0}),l.addEventListener("error",()=>o(new Error("Video loading failed")),{once:!0}),this.updateAssetLoadMetadata(t,"loading",.5),l.src=i});return this.updateAssetLoadMetadata(t,"success",1),n}catch{return this.updateAssetLoadMetadata(t,"failed",1),null}}getProgress(){const t=Object.keys(this.loadTracker.registry);return t.length===0?0:t.reduce((i,a)=>i+this.loadTracker.registry[a].progress,0)/t.length}extractUrl(t){if(typeof t=="string")return t;const e=Array.isArray(t.src)?t.src[0]:t.src;return typeof e=="string"?e:e?.src}hasVideoExtension(t){const e=new URL(t,window.location.origin).pathname.toLowerCase();return gr.VIDEO_EXTENSIONS.some(i=>e.endsWith(i))}async getContentType(t){try{return(await fetch(t,{method:"HEAD"})).headers.get("content-type")}catch{return null}}canPlayVideo(t){const e=new URL(t,window.location.origin).pathname.toLowerCase(),i=e.slice(e.lastIndexOf(".")),a=gr.VIDEO_MIME[i];return a?document.createElement("video").canPlayType(a)!=="":!1}async isPlayableVideo(t){if(this.hasVideoExtension(t))return this.canPlayVideo(t);const e=await this.getContentType(t);return e?.startsWith("video/")?document.createElement("video").canPlayType(e)!=="":!1}async shouldUseSafariVideoLoader(t){const e=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),i=this.extractUrl(t);return e&&i!==void 0&&await this.isPlayableVideo(i)}async loadVideoForSafari(t,e){const i=this.extractUrl(e),a=typeof e=="object"?e.data??{}:{},n=await new Promise((r,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 X.VideoSource({resource:l,autoPlay:a.autoPlay??!1,...a});r(new X.Texture({source:c}))}catch(c){o(c)}},{once:!0}),l.addEventListener("error",()=>o(new Error("Video loading failed")),{once:!0}),this.updateAssetLoadMetadata(t,"loading",.5),l.src=i});return this.updateAssetLoadMetadata(t,"success",1),n}updateAssetLoadMetadata(t,e,i){this.loadTracker.registry[t]?(this.loadTracker.registry[t].progress=i,this.loadTracker.registry[t].status=e):this.loadTracker.registry[t]={progress:i,status:e};const a={...this.loadTracker.registry};this.loadTracker.emit("onAssetLoadInfoUpdated",{registry:a})}}class Ya{static Name="FontLoadParser";id;name;extension;validFontExtensions;woff2Decompressor;constructor(){this.id=Ya.Name,this.name=Ya.Name,this.extension={type:[X.ExtensionType.LoadParser],priority:X.LoaderParserPriority.High,ref:null},this.validFontExtensions=["ttf","otf","woff","woff2"],this.woff2Decompressor=null}test(t){const e=t.split("?")[0]?.split(".").pop()?.toLowerCase()??"";return this.validFontExtensions.includes(e)}async load(t,e,i){const a=t.split("?")[0]?.split(".").pop()?.toLowerCase()??"",n=await fetch(t).then(f=>f.arrayBuffer());if(a!=="woff2"){const f=zr.parse(new Uint8Array(n).buffer),p=f.names.fontFamily.en||f.names.fontFamily[Object.keys(f.names.fontFamily)[0]],y=new FontFace(p,`url(${t})`);return await y.load(),document.fonts.add(y),y}if(await this.loadWoff2Decompressor(),!this.woff2Decompressor)throw new Error("Cannot initialize Woff2 decompressor.");const r=this.woff2Decompressor.decompress(n),o=zr.parse(new Uint8Array(r).buffer),l=o.names.fontFamily.en||o.names.fontFamily[Object.keys(o.names.fontFamily)[0]],c=new Blob([r],{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 e=`${await fetch("https://unpkg.com/wawoff2@2.0.1/build/decompress_binding.js").then(i=>i.text())}; return Module`;this.woff2Decompressor=new Function(e)(),await new Promise(i=>{this.woff2Decompressor.onRuntimeInitialized=i})}unload(t){t&&document.fonts.delete(t)}}class rf{constructor(t,e,i,a,n,r,o,l){this.clip=t,this.propertyPath=e,this.fieldName=i,this.previousFieldName=a,this.previousValue=n,this.newValue=r,this.storedPreviousValue=n,this.storedNewValue=r,this.trackIndex=o,this.clipIndex=l}name="setMergeField";storedPreviousValue;storedNewValue;trackIndex;clipIndex;storedPreviousBinding;async execute(t){if(!t)return;const e=t.getMergeFields();this.storedPreviousBinding=this.clip.getMergeFieldBinding(this.propertyPath),Ur(this.clip.clipConfiguration,this.propertyPath,this.storedNewValue),this.fieldName?this.clip.setMergeFieldBinding(this.propertyPath,{placeholder:e.createTemplate(this.fieldName),resolvedValue:this.storedNewValue}):this.clip.removeMergeFieldBinding(this.propertyPath),this.fieldName?e.register({name:this.fieldName,defaultValue:this.storedNewValue},{silent:!0}):this.previousFieldName&&e.remove(this.previousFieldName,{silent:!0}),(this.propertyPath==="asset.src"||this.propertyPath.endsWith(".src"))&&await this.clip.reloadAsset(),this.clip.reconfigureAfterRestore(),this.clip.draw(),t.emitEvent(j.MergeFieldApplied,{propertyPath:this.propertyPath,fieldName:this.fieldName??"",trackIndex:this.trackIndex,clipIndex:this.clipIndex})}async undo(t){if(!t)return;const e=t.getMergeFields();Ur(this.clip.clipConfiguration,this.propertyPath,this.storedPreviousValue),this.storedPreviousBinding?this.clip.setMergeFieldBinding(this.propertyPath,this.storedPreviousBinding):this.clip.removeMergeFieldBinding(this.propertyPath),this.previousFieldName&&e.register({name:this.previousFieldName,defaultValue:this.storedPreviousValue},{silent:!0}),(this.propertyPath==="asset.src"||this.propertyPath.endsWith(".src"))&&await this.clip.reloadAsset(),this.clip.reconfigureAfterRestore(),this.clip.draw(),t.emitEvent(j.MergeFieldRemoved,{propertyPath:this.propertyPath,fieldName:this.previousFieldName,trackIndex:this.trackIndex,clipIndex:this.clipIndex})}}class $i{data;constructor(t){this.data=structuredClone(t)}getTimeline(){return this.data.timeline}getBackground(){return this.data.timeline.background}getTracks(){return this.data.timeline.tracks}getTrack(t){return this.data.timeline.tracks[t]??null}getTrackCount(){return this.data.timeline.tracks.length}getSoundtrack(){return this.data.timeline.soundtrack}getClip(t,e){const i=this.data.timeline.tracks[t];return i?i.clips[e]??null:null}getClipsInTrack(t){return this.data.timeline.tracks[t]?.clips??[]}getClipCount(){return this.data.timeline.tracks.reduce((t,e)=>t+e.clips.length,0)}getClipCountInTrack(t){return this.data.timeline.tracks[t]?.clips.length??0}getOutput(){return this.data.output}getSize(){const{size:t}=this.data.output;if(!t?.width||!t?.height)throw new Error("Output size is not defined");return{width:t.width,height:t.height}}getFormat(){return this.data.output.format}getFps(){return this.data.output.fps}getMergeFields(){return this.data.merge}addTrack(t,e){const i=e??{clips:[]};return this.data.timeline.tracks.splice(t,0,i),i}removeTrack(t){if(t<0||t>=this.data.timeline.tracks.length)return null;const[e]=this.data.timeline.tracks.splice(t,1);return e??null}addClip(t,e,i){const a=this.data.timeline.tracks[t];if(!a)throw new Error(`Track ${t} does not exist`);const n=i??a.clips.length;return a.clips.splice(n,0,e),e}removeClip(t,e){const i=this.data.timeline.tracks[t];if(!i||e<0||e>=i.clips.length)return null;const[a]=i.clips.splice(e,1);return a??null}updateClip(t,e,i){const a=this.getClip(t,e);if(!a)throw new Error(`Clip at track ${t}, index ${e} does not exist`);Object.assign(a,i)}replaceClip(t,e,i){const a=this.data.timeline.tracks[t];if(!a||e<0||e>=a.clips.length)return null;const n=a.clips[e];return a.clips[e]=i,n}setBackground(t){this.data.timeline.background=t}setSoundtrack(t){this.data.timeline.soundtrack=t}getFonts(){return this.data.timeline.fonts??[]}addFont(t){this.data.timeline.fonts||(this.data.timeline.fonts=[]),this.data.timeline.fonts.some(e=>e.src===t)||this.data.timeline.fonts.push({src:t})}removeFont(t){this.data.timeline.fonts&&(this.data.timeline.fonts=this.data.timeline.fonts.filter(e=>e.src!==t))}setFonts(t){this.data.timeline.fonts=t}setSize(t){this.data.output.size={width:t.width,height:t.height}}setFormat(t){this.data.output.format=t}setFps(t){this.data.output.fps=t}setMergeFields(t){this.data.merge=t}toJSON(){const t=structuredClone(this.data);return t.merge?.length===0&&delete t.merge,t}static fromJSON(t){return new $i(t)}clone(){return new $i(this.data)}}function fl(s){if(s==null)return s;if(Array.isArray(s))return s.map(fl);if(typeof s=="object"){const t={};for(const[e,i]of Object.entries(s))t[e]=fl(i);return t}return typeof s=="string"&&s!==""&&!Number.isNaN(Number(s))?Number(s):s}class ta extends ln{static ZIndexPadding=100;assetLoader;events;document;edit;tracks;clipsToDispose;clips;commandHistory=[];commandIndex=-1;playbackTime;size;backgroundColor;totalDuration;isPlaying;selectedClip;copiedClip=null;updatedClip;viewportMask;background;isExporting=!1;cachedTimelineEnd=0;endLengthClips=new Set;isBatchingEvents=!1;isLoadingEdit=!1;syncCorrectionCount=0;toolbarButtons=[];mergeFields;canvas=null;alignmentGuides=null;lumaMaskController;clipErrors=new Map;constructor(t){super(),this.document=new $i(t),this.size=this.document.getSize(),this.backgroundColor=this.document.getBackground()??"#000000",this.assetLoader=new gr,this.edit=null,this.tracks=[],this.clipsToDispose=[],this.clips=[],this.events=new dl,this.mergeFields=new vN(this.events),this.lumaMaskController=new mN(()=>this.canvas,()=>this.tracks,this.events),this.playbackTime=0,this.totalDuration=0,this.isPlaying=!1,this.selectedClip=null,this.updatedClip=null,this.background=null,this.setupIntentListeners()}async load(){this.getContainer().sortableChildren=!0;const t=new X.Graphics;this.background=t,t.fillStyle={color:this.backgroundColor},t.rect(0,0,this.size.width,this.size.height),t.fill(),this.getContainer().addChild(t),this.viewportMask=new X.Graphics,this.viewportMask.rect(0,0,this.size.width,this.size.height),this.viewportMask.fill(16777215),this.getContainer().addChild(this.viewportMask),this.getContainer().setMask({mask:this.viewportMask}),this.alignmentGuides=new eN(this.getContainer(),this.size.width,this.size.height),await this.initializeFromDocument()}async initializeFromDocument(t="load"){const e=this.document.toJSON(),i=e.merge??[];this.mergeFields.loadFromSerialized(i);const a=this.detectMergeFieldBindings(e,i),n=i.length>0?CN(e,i):e,r=lo.parse(fl(n));oN(r),this.edit=r,await Promise.all((this.edit.timeline.fonts??[]).map(async o=>{const l=o.src,c={src:l,parser:Ya.Name};return this.assetLoader.load(l,c)})),this.isLoadingEdit=!0;for(const[o,l]of this.edit.timeline.tracks.entries())for(const[c,d]of l.clips.entries())try{const u=this.createPlayerFromAssetType(d);u.layer=o+1;const f=a.get(`${o}-${c}`);f&&f.size>0&&u.setInitialBindings(f),await this.addPlayer(o,u)}catch(u){const f=d.asset.type??"unknown",p=u instanceof Error?u.message:String(u);this.clipErrors.set(`${o}-${c}`,{error:p,assetType:f}),this.events.emit(j.ClipLoadFailed,{trackIndex:o,clipIndex:c,error:p,assetType:f})}this.isLoadingEdit=!1,this.lumaMaskController.initialize(),await this.resolveAllTiming(),this.updateTotalDuration(),this.edit.timeline.soundtrack&&await this.loadSoundtrack(this.edit.timeline.soundtrack),this.events.emit(j.TimelineUpdated,{current:this.getResolvedEdit()}),this.emitEditChanged(t)}update(t,e){for(const i of this.clips)i.shouldDispose&&this.queueDisposeClip(i),i.update(t,e);this.disposeClips(),this.lumaMaskController.update(),this.isPlaying&&(this.playbackTime=Math.max(0,Math.min(this.playbackTime+e,this.totalDuration)),this.playbackTime===this.totalDuration&&this.pause())}draw(){for(const t of this.clips)t.draw()}dispose(){if(this.clearClips(),this.lumaMaskController.dispose(),this.viewportMask){try{this.getContainer().setMask(null)}catch{}this.viewportMask.destroy(),this.viewportMask=void 0}Ji.resetFontCache()}updateViewportMask(){this.viewportMask&&(this.viewportMask.clear(),this.viewportMask.rect(0,0,this.size.width,this.size.height),this.viewportMask.fill(16777215))}play(){this.isPlaying=!0,this.events.emit(j.PlaybackPlay)}pause(){this.isPlaying=!1,this.events.emit(j.PlaybackPause)}seek(t){this.playbackTime=Math.max(0,Math.min(t,this.totalDuration)),this.pause(),this.update(0,101),this.draw()}stop(){this.seek(0)}async loadEdit(t){if(this.edit&&!this.hasStructuralChanges(t)){this.document=new $i(t),this.isBatchingEvents=!0,this.applyGranularChanges(t),this.isBatchingEvents=!1,this.emitEditChanged("loadEdit:granular");return}this.document=new $i(t);const e=this.document.getSize();(e.width!==this.size.width||e.height!==this.size.height)&&(this.size=e,this.updateViewportMask(),this.canvas?.zoomToFit()),this.backgroundColor=this.document.getBackground()??"#000000",this.background&&(this.background.clear(),this.background.fillStyle={color:this.backgroundColor},this.background.rect(0,0,this.size.width,this.size.height),this.background.fill()),this.clearClips(),await this.initializeFromDocument("loadEdit")}async loadSoundtrack(t){const e={asset:{type:"audio",src:t.src,effect:t.effect,volume:t.volume??1},fit:"crop",start:0,length:this.totalDuration/1e3},i=new Jl(this,e);i.layer=this.tracks.length+1,await this.addPlayer(this.tracks.length,i)}getEdit(){const t=this.document.toJSON(),e=this.mergeFields.toSerializedArray();return e.length>0&&(t.merge=e),t}validateEdit(t){const e=lo.safeParse(t);return e.success?{valid:!0,errors:[]}:{valid:!1,errors:e.error.issues.map(i=>({path:i.path.join("."),message:i.message}))}}getResolvedEdit(){const t=this.tracks.map(e=>({clips:e.filter(i=>i&&!this.clipsToDispose.includes(i)).map(i=>({...i.clipConfiguration,start:i.getStart(),length:i.getLength()}))}));return{timeline:{background:this.backgroundColor,tracks:t,fonts:this.edit?.timeline.fonts||[]},output:this.edit?.output||{size:this.size,format:"mp4"}}}getOriginalEdit(){return this.edit}getDocument(){return this.document}addClip(t,e){const i=new lN(t,e);return this.executeCommand(i)}getClip(t,e){const i=this.tracks[t];return!i||e<0||e>=i.length?null:i[e].clipConfiguration}getClipError(t,e){return this.clipErrors.get(`${t}-${e}`)??null}clearClipErrorAndShift(t,e){this.clipErrors.delete(`${t}-${e}`);const i=[];for(const[a,n]of this.clipErrors){const[r,o]=a.split("-").map(Number);r===t&&o>e&&i.push({oldKey:a,newKey:`${r}-${o-1}`,value:n})}for(const{oldKey:a,newKey:n,value:r}of i)this.clipErrors.delete(a),this.clipErrors.set(n,r)}getPlayerClip(t,e){const i=this.tracks[t];return!i||e<0||e>=i.length?null:i[e]}getOriginalAsset(t,e){const i=this.getPlayerClip(t,e);if(i)return i.getExportableClip()?.asset}deleteClip(t,e){const i=this.tracks[t];if(!i)return;const a=i[e];if(!a)return;if(a.playerType!==qt.Luma){const o=i.findIndex(l=>l.playerType===qt.Luma);if(o!==-1){const l=o<e?e-1:e,c=new fr(t,o);this.executeCommand(c);const d=new fr(t,l);this.executeCommand(d);return}}const r=new fr(t,e);this.executeCommand(r)}splitClip(t,e,i){const a=new uN(t,e,i);this.executeCommand(a)}async addTrack(t,e){this.document&&!this.isLoadingEdit&&this.document.addTrack(t);const i=new tf(t);await this.executeCommand(i);for(const a of e?.clips??[])await this.addClip(t,a)}getTrack(t){const e=this.clips.filter(i=>i.layer===t+1);return e.length===0?null:{clips:e.map(i=>i.clipConfiguration)}}deleteTrack(t){const e=new ll(t);this.executeCommand(e)}getTotalDuration(){return this.totalDuration}getMemoryStats(){const t={};for(const n of this.clips){const r=n.clipConfiguration.asset?.type||"unknown";t[r]=(t[r]||0)+1}let e=0,i=0,a=0;for(const n of this.clips)n.playerType===qt.RichText&&(e+=1,i+=n.getCacheSize()),n.playerType===qt.Text&&(a+=1);return{clipCounts:t,totalClips:this.clips.length,richTextCacheStats:{clips:e,totalFrames:i},textPlayerCount:a,lumaMaskCount:this.lumaMaskController.getActiveMaskCount(),commandHistorySize:this.commandHistory.length,trackCount:this.tracks.length}}getComprehensiveMemoryStats(){const t=[],e={videos:{count:0,totalMB:0,dimensions:[]},images:{count:0,totalMB:0,dimensions:[]},text:{count:0,totalMB:0},richText:{count:0,totalMB:0},luma:{count:0,totalMB:0},animated:{count:0,frames:0,totalMB:0}};for(const r of this.clips){const{asset:o}=r.clipConfiguration,l=o?.type||"unknown",c=["video","image","text","rich-text","luma","audio","html","shape","caption"].includes(l)?l:"unknown",d=r.getSize(),u=this.estimateTextureMB(d.width,d.height),f=this.getAssetLabel(r);t.push({id:r.clipConfiguration.asset?.type||"unknown",type:c,label:f,width:d.width,height:d.height,estimatedMB:u}),c==="video"?(e.videos.count+=1,e.videos.totalMB+=u,e.videos.dimensions.push({width:d.width,height:d.height})):c==="image"?(e.images.count+=1,e.images.totalMB+=u,e.images.dimensions.push({width:d.width,height:d.height})):c==="text"?(e.text.count+=1,e.text.totalMB+=u):c==="rich-text"?(e.richText.count+=1,e.richText.totalMB+=u):c==="luma"&&(e.luma.count+=1,e.luma.totalMB+=u)}for(const r of this.clips)if(r.playerType===qt.RichText){const o=r.getCacheSize();o>0&&(e.animated.count+=1,e.animated.frames+=o,e.animated.totalMB+=o*this.estimateTextureMB(this.size.width,this.size.height))}const i=r=>{if(r.length===0)return"";if(r.length===1)return`${r[0].width}×${r[0].height}`;const o=Math.round(r.reduce((c,d)=>c+d.width,0)/r.length),l=Math.round(r.reduce((c,d)=>c+d.height,0)/r.length);return`avg ${o}×${l}`},a=e.videos.count+e.images.count+e.text.count+e.richText.count+e.luma.count+e.animated.count,n=e.videos.totalMB+e.images.totalMB+e.text.totalMB+e.richText.totalMB+e.luma.totalMB+e.animated.totalMB;return{textureStats:{videos:{count:e.videos.count,totalMB:e.videos.totalMB,avgDimensions:i(e.videos.dimensions)},images:{count:e.images.count,totalMB:e.images.totalMB,avgDimensions:i(e.images.dimensions)},text:{count:e.text.count,totalMB:e.text.totalMB},richText:{count:e.richText.count,totalMB:e.richText.totalMB},luma:{count:e.luma.count,totalMB:e.luma.totalMB},animated:{count:e.animated.count,frames:e.animated.frames,totalMB:e.animated.totalMB},totalTextures:a,totalMB:n},assetDetails:t,systemStats:{clipCount:this.clips.length,trackCount:this.tracks.length,commandCount:this.commandHistory.length}}}estimateTextureMB(t,e){return t*e*4/(1024*1024)}getAssetLabel(t){const e=t.clipConfiguration.asset;if(!e)return"unknown";const i=e.src;if("src"in e&&typeof i=="string")return(i.split("/").pop()||i).split("?")[0];const a=e.text;return"text"in e&&typeof a=="string"?a.length>20?`${a.substring(0,17)}...`:a:e.type?.toString()||"unknown"}getPlaybackHealth(){let t=0,e=0,i=0;for(const a of this.clips)if(a.isActive()){if(t+=1,a.playerType===qt.Video){const n=a.getCurrentDrift();e=Math.max(e,n)}if(a.playerType===qt.Audio){const n=a.getCurrentDrift();i=Math.max(i,n)}}return{activePlayerCount:t,totalPlayerCount:this.clips.length,videoMaxDrift:e,audioMaxDrift:i,syncCorrections:this.syncCorrectionCount}}recordSyncCorrection(){this.syncCorrectionCount+=1}undo(){if(this.commandIndex>=0){const t=this.commandHistory[this.commandIndex];if(t.undo){const e=this.createCommandContext();t.undo(e),this.commandIndex-=1,this.events.emit(j.EditUndo,{command:t.name}),this.emitEditChanged(`undo:${t.name}`)}}}redo(){if(this.commandIndex<this.commandHistory.length-1){this.commandIndex+=1;const t=this.commandHistory[this.commandIndex],e=this.createCommandContext();t.execute(e),this.events.emit(j.EditRedo,{command:t.name}),this.emitEditChanged(`redo:${t.name}`)}}setUpdatedClip(t,e=null,i=null){const a=t.layer-1,n=this.tracks[a],r=n?n.indexOf(t):-1,o=new ef(t,e,i,{trackIndex:a,clipIndex:r});this.executeCommand(o)}updateClip(t,e,i){const a=this.getPlayerClip(t,e);if(!a){console.warn(`Clip not found at track ${t}, index ${e}`);return}const n=structuredClone(a.clipConfiguration),r=structuredClone(a.clipConfiguration),o=Dr(r,i),l=new ef(a,n,o,{trackIndex:t,clipIndex:e});this.executeCommand(l)}updateClipTiming(t,e,i){if(!this.getPlayerClip(t,e)){console.warn(`Clip not found at track ${t}, index ${e}`);return}const n=new pN(t,e,i);this.executeCommand(n)}updateTextContent(t,e,i){const a=new gN(t,e,i);this.executeCommand(a)}executeEditCommand(t){return this.executeCommand(t)}executeCommand(t){const e=this.createCommandContext(),i=t.execute(e);return this.commandHistory=this.commandHistory.slice(0,this.commandIndex+1),this.commandHistory.push(t),this.commandIndex+=1,i instanceof Promise?i.then(()=>this.emitEditChanged(t.name)):(this.emitEditChanged(t.name),i)}emitEditChanged(t){this.isBatchingEvents||this.events.emit(j.EditChanged,{source:t,timestamp:Date.now()})}detectMergeFieldBindings(t,e){const i=new Map;if(!e.length)return i;const a=new Map;for(const{find:n,replace:r}of e){const o=typeof r=="string"?r:JSON.stringify(r);a.set(n.toUpperCase(),o)}for(const[n,r]of t.timeline.tracks.entries())for(const[o,l]of r.clips.entries()){const c=this.detectBindingsInObject(l,"",a);c.size>0&&i.set(`${n}-${o}`,c)}return i}detectBindingsInObject(t,e,i){const a=new Map;if(typeof t=="string"){if(/\{\{\s*([A-Z_0-9]+)\s*\}\}/gi.test(t)){const o=t.replace(/\{\{\s*([A-Z_0-9]+)\s*\}\}/gi,(l,c)=>i.get(c.toUpperCase())??l);a.set(e,{placeholder:t,resolvedValue:o})}return a}if(Array.isArray(t)){for(let n=0;n<t.length;n+=1){const r=e?`${e}[${n}]`:`[${n}]`,o=this.detectBindingsInObject(t[n],r,i);for(const[l,c]of o)a.set(l,c)}return a}if(t!==null&&typeof t=="object")for(const[n,r]of Object.entries(t)){const o=e?`${e}.${n}`:n,l=this.detectBindingsInObject(r,o,i);for(const[c,d]of l)a.set(c,d)}return a}hasStructuralChanges(t){if(!this.edit)return!0;const e=this.edit.timeline.tracks,i=t.timeline.tracks;if(e.length!==i.length)return!0;for(let a=0;a<e.length;a+=1){if(e[a].clips.length!==i[a].clips.length)return!0;for(let n=0;n<e[a].clips.length;n+=1){const r=e[a].clips[n]?.asset?.type,o=i[a].clips[n]?.asset?.type;if(r!==o)return!0}}return JSON.stringify(this.edit.merge??[])!==JSON.stringify(t.merge??[])||JSON.stringify(this.edit.timeline.fonts??[])!==JSON.stringify(t.timeline.fonts??[])}applyGranularChanges(t){const e=this.edit?.output,i=t.output;if(i?.size&&(e?.size?.width!==i.size.width||e?.size?.height!==i.size.height)){const o=i.size.width??this.size.width,l=i.size.height??this.size.height;this.setOutputSize(o,l)}i?.fps!==void 0&&e?.fps!==i.fps&&this.setOutputFps(i.fps),i?.format!==void 0&&e?.format!==i.format&&this.setOutputFormat(i.format),i?.destinations&&JSON.stringify(e?.destinations)!==JSON.stringify(i.destinations)&&this.setOutputDestinations(i.destinations);const a=t.timeline?.background;a&&this.backgroundColor!==a&&this.setTimelineBackground(a);const n=this.edit.timeline.tracks,r=t.timeline.tracks;for(let o=0;o<r.length;o+=1){const l=n[o].clips,c=r[o].clips;for(let d=0;d<c.length;d+=1){const u=l[d],f=c[d];JSON.stringify(u)!==JSON.stringify(f)&&this.updateClip(o,d,f)}}}createCommandContext(){return{getClips:()=>this.clips,getTracks:()=>this.tracks,getTrack:t=>t>=0&&t<this.tracks.length?this.tracks[t]:null,getContainer:()=>this.getContainer(),addPlayer:(t,e)=>this.addPlayer(t,e),addPlayerToContainer:(t,e)=>{this.addPlayerToContainer(t,e)},createPlayerFromAssetType:t=>this.createPlayerFromAssetType(t),queueDisposeClip:t=>this.queueDisposeClip(t),disposeClips:()=>this.disposeClips(),clearClipError:(t,e)=>this.clearClipErrorAndShift(t,e),undeleteClip:(t,e)=>{this.clips.push(e);let i=0;if(t>=0&&t<this.tracks.length){const a=this.tracks[t];i=a.length;for(let n=0;n<a.length;n+=1)if(a[n].getStart()>e.getStart()){i=n;break}a.splice(i,0,e)}if(this.document){const a=e.getExportableClip();this.document.addClip(t,a,i)}this.addPlayerToContainer(t,e),e.load().catch(a=>{const n=e.clipConfiguration?.asset?.type??"unknown",r=a instanceof Error?a.message:String(a);this.clipErrors.set(`${t}-${i}`,{error:r,assetType:n}),this.events.emit(j.ClipLoadFailed,{trackIndex:t,clipIndex:i,error:r,assetType:n})}),this.updateTotalDuration()},setUpdatedClip:t=>{this.updatedClip=t},restoreClipConfiguration:(t,e)=>{const i=structuredClone(e),a=t.clipConfiguration;for(const n of Object.keys(a))delete a[n];if(Object.assign(a,i),t.reconfigureAfterRestore(),t.draw(),this.document){const n=this.findClipIndices(t);if(n){const r=t.getExportableClip();this.document.replaceClip(n.trackIndex,n.clipIndex,r)}}},updateDuration:()=>this.updateTotalDuration(),emitEvent:(t,...e)=>this.events.emit(t,...e),findClipIndices:t=>this.findClipIndices(t),getClipAt:(t,e)=>this.getClipAt(t,e),getSelectedClip:()=>this.selectedClip,setSelectedClip:t=>{this.selectedClip=t},movePlayerToTrackContainer:(t,e,i)=>this.movePlayerToTrackContainer(t,e,i),getEditState:()=>this.getResolvedEdit(),propagateTimingChanges:(t,e)=>this.propagateTimingChanges(t,e),resolveClipAutoLength:t=>this.resolveClipAutoLength(t),untrackEndLengthClip:t=>this.endLengthClips.delete(t),trackEndLengthClip:t=>this.endLengthClips.add(t),getMergeFields:()=>this.mergeFields}}queueDisposeClip(t){this.clipsToDispose.push(t)}disposeClips(){if(this.clipsToDispose.length!==0){for(const t of this.clipsToDispose)t.playerType===qt.Luma&&this.lumaMaskController.cleanupForPlayer(t);for(const t of this.clipsToDispose)this.disposeClip(t);this.clips=this.clips.filter(t=>!this.clipsToDispose.includes(t));for(const t of this.clipsToDispose){const e=t.layer-1;if(e>=0&&e<this.tracks.length){const i=this.tracks[e].indexOf(t);i!==-1&&(this.tracks[e].splice(i,1),this.document&&this.document.removeClip(e,i))}}this.clipsToDispose=[],this.updateTotalDuration(),this.cleanupUnusedFonts()}}cleanupUnusedFonts(){if(!this.document)return;const t=this.document.getFonts();if(t.length===0)return;const e=new Set;for(const i of this.clips){const{asset:a}=i.clipConfiguration;a&&a.type==="rich-text"&&a.font?.family&&e.add(a.font.family)}for(const i of t){const a=this.extractFilenameFromUrl(i.src);a&&!e.has(a)&&this.document.removeFont(i.src)}}extractFilenameFromUrl(t){try{const{pathname:e}=new URL(t),i=e.split("/").pop();return i?i.replace(/\.[^.]+$/,""):null}catch{return null}}disposeClip(t){try{if(this.getContainer().children.includes(t.getContainer())){const e=this.getContainer().getChildIndex(t.getContainer());this.getContainer().removeChildAt(e)}else for(const e of this.getContainer().children)if(e instanceof X.Container&&e.label?.toString().startsWith("shotstack-track-")&&e.children.includes(t.getContainer())){e.removeChild(t.getContainer());break}}catch(e){console.warn(`Attempting to unmount an unmounted clip: ${e}`)}this.unloadClipAssets(t),this.endLengthClips.delete(t),this.cachedTimelineEnd=0,t.dispose()}unloadClipAssets(t){const{asset:e}=t.clipConfiguration;e&&"src"in e&&typeof e.src=="string"&&this.assetLoader.decrementRef(e.src)&&X.Assets.cache.has(e.src)&&X.Assets.unload(e.src)}clearClips(){for(const t of this.clips)this.disposeClip(t);this.clips=[],this.tracks=[],this.clipsToDispose=[],this.clipErrors.clear(),this.updateTotalDuration()}updateTotalDuration(){let t=0;for(const i of this.tracks)for(const a of i)t=Math.max(t,a.getEnd());const e=this.totalDuration;this.totalDuration=t*1e3,e!==this.totalDuration&&this.events.emit(j.DurationChanged,{duration:this.totalDuration})}async resolveAllTiming(){for(let e=0;e<this.tracks.length;e+=1)for(let i=0;i<this.tracks[e].length;i+=1){const a=this.tracks[e][i],n=a.getTimingIntent();let r;n.start==="auto"?r=pr(e,i,this.tracks):r=n.start;let o;n.length==="auto"?o=await af(a.clipConfiguration.asset):n.length==="end"?o=0:o=n.length,a.setResolvedTiming({start:r,length:o})}const t=cl(this.tracks);this.cachedTimelineEnd=t;for(const e of[...this.endLengthClips]){const i=e.getResolvedTiming();e.setResolvedTiming({start:i.start,length:nf(i.start,t)})}for(const e of this.endLengthClips)e.reconfigureAfterRestore()}propagateTimingChanges(t,e){const i=this.tracks[t];if(!i)return;for(let n=Math.max(0,e);n<i.length;n+=1){const r=i[n];if(r.getTimingIntent().start==="auto"){const o=pr(t,n,this.tracks);r.setResolvedTiming({start:o,length:r.getLength()}),r.reconfigureAfterRestore()}}const a=cl(this.tracks);if(a!==this.cachedTimelineEnd){this.cachedTimelineEnd=a;for(const n of[...this.endLengthClips]){const r=nf(n.getStart(),a),o=n.getLength();Math.abs(r-o)>.001&&(n.setResolvedTiming({start:n.getStart(),length:r}),n.clipConfiguration.length=r,n.reconfigureAfterRestore())}}this.updateTotalDuration(),this.events.emit(j.TimelineUpdated,{current:this.getResolvedEdit()})}async resolveClipAutoLength(t){const e=t.getTimingIntent();if(e.length!=="auto")return;const i=this.findClipIndices(t);let a=t.getStart();e.start==="auto"&&i&&(a=pr(i.trackIndex,i.clipIndex,this.tracks));const n=await af(t.clipConfiguration.asset);t.setResolvedTiming({start:a,length:n}),t.clipConfiguration.length=n,t.reconfigureAfterRestore(),i&&this.propagateTimingChanges(i.trackIndex,i.clipIndex)}addPlayerToContainer(t,e){const i=1e5-(t+1)*ta.ZIndexPadding,a=`shotstack-track-${i}`;let n=this.getContainer().getChildByLabel(a,!1);n||(n=new X.Container({label:a,zIndex:i}),this.getContainer().addChild(n)),n.addChild(e.getContainer())}movePlayerToTrackContainer(t,e,i){if(e===i)return;const a=1e5-(e+1)*ta.ZIndexPadding,n=1e5-(i+1)*ta.ZIndexPadding,r=`shotstack-track-${a}`,o=`shotstack-track-${n}`,l=this.getContainer().getChildByLabel(r,!1);let c=this.getContainer().getChildByLabel(o,!1);c||(c=new X.Container({label:o,zIndex:n}),this.getContainer().addChild(c)),l&&l.removeChild(t.getContainer()),c.addChild(t.getContainer()),this.getContainer().sortDirty=!0}createPlayerFromAssetType(t){if(!t.asset?.type)throw new Error("Invalid clip configuration: missing asset type");let e;switch(t.asset.type){case"text":{e=new Ji(this,t);break}case"rich-text":{e=new Qi(this,t);break}case"shape":{e=new $S(this,t);break}case"html":{e=new sp(this,t);break}case"image":{e=new ip(this,t);break}case"video":{e=new tN(this,t);break}case"audio":{e=new Jl(this,t);break}case"luma":{e=new ap(this,t);break}case"caption":{e=new hn(this,t);break}default:throw new Error(`Unsupported clip type: ${t.asset.type}`)}return e}async addPlayer(t,e){for(;this.tracks.length<=t;)this.tracks.push([]);if(this.tracks[t].push(e),this.clips.push(e),this.document&&!this.isLoadingEdit){for(;this.document.getTrackCount()<=t;)this.document.addTrack(this.document.getTrackCount());const r=this.tracks[t].length-1,o=e.getExportableClip();this.document.addClip(t,o,r)}e.getTimingIntent().length==="end"&&this.endLengthClips.add(e);const i=1e5-(t+1)*ta.ZIndexPadding,a=`shotstack-track-${i}`;let n=this.getContainer().getChildByLabel(a,!1);n||(n=new X.Container({label:a,zIndex:i}),this.getContainer().addChild(n)),n.addChild(e.getContainer()),await e.load(),this.updateTotalDuration()}selectClip(t,e){const i=new dN(t,e);this.executeCommand(i)}clearSelection(){const t=new cN;this.executeCommand(t)}isClipSelected(t,e){if(!this.selectedClip)return!1;const i=this.selectedClip.layer-1,a=this.tracks[i].indexOf(this.selectedClip);return t===i&&e===a}getSelectedClipInfo(){if(!this.selectedClip)return null;const t=this.selectedClip.layer-1,e=this.tracks[t].indexOf(this.selectedClip);return{trackIndex:t,clipIndex:e,player:this.selectedClip}}copyClip(t,e){const i=this.getClipAt(t,e);i&&(this.copiedClip={trackIndex:t,clipConfiguration:structuredClone(i.clipConfiguration)},this.events.emit(j.ClipCopied,{trackIndex:t,clipIndex:e}))}pasteClip(){if(!this.copiedClip)return;const t=structuredClone(this.copiedClip.clipConfiguration);t.start=O0(this.playbackTime),this.addClip(this.copiedClip.trackIndex,t)}hasCopiedClip(){return this.copiedClip!==null}findClipIndices(t){for(let e=0;e<this.tracks.length;e+=1){const i=this.tracks[e].indexOf(t);if(i!==-1)return{trackIndex:e,clipIndex:i}}return null}getClipAt(t,e){return t>=0&&t<this.tracks.length&&e>=0&&e<this.tracks[t].length?this.tracks[t][e]:null}selectPlayer(t){const e=this.findClipIndices(t);e&&this.selectClip(e.trackIndex,e.clipIndex)}isPlayerSelected(t){return this.isExporting?!1:this.selectedClip===t}getActivePlayersExcept(t){const e=[];for(const i of this.tracks)for(const a of i)a!==t&&a.isActive()&&e.push(a);return e}showAlignmentGuide(t,e,i,a){this.alignmentGuides&&(t==="canvas"?this.alignmentGuides.drawCanvasGuide(e,i):a&&this.alignmentGuides.drawClipGuide(e,i,a.start,a.end))}clearAlignmentGuides(){this.alignmentGuides?.clear()}moveSelectedClip(t,e){const i=this.getSelectedClipInfo();if(!i)return;const{player:a}=i,n=structuredClone(a.clipConfiguration);a.moveBy(t,e),this.setUpdatedClip(a,n,structuredClone(a.clipConfiguration))}setExportMode(t){this.isExporting=t}isInExportMode(){return this.isExporting}setCanvas(t){this.canvas=t}getCanvasZoom(){return this.canvas?.getZoom()??1}setOutputSize(t,e){const i=Id.safeParse({width:t,height:e});if(!i.success)throw new Error(`Invalid size: ${i.error.issues[0]?.message}`);const a={width:t,height:e};this.size=a,this.edit&&(this.edit.output={...this.edit.output,size:a}),this.document?.setSize(a),this.updateViewportMask(),this.canvas?.zoomToFit(),this.background&&(this.background.clear(),this.background.fillStyle={color:this.backgroundColor},this.background.rect(0,0,t,e),this.background.fill()),this.events.emit(j.OutputResized,a),this.emitEditChanged("output:size")}setOutputFps(t){const e=Ed.safeParse(t);if(!e.success)throw new Error(`Invalid fps: ${e.error.issues[0]?.message}`);this.edit&&(this.edit.output={...this.edit.output,fps:e.data}),this.document?.setFps(e.data),this.events.emit(j.OutputFpsChanged,{fps:t}),this.emitEditChanged("output:fps")}getOutputFps(){return this.edit?.output?.fps??30}setOutputFormat(t){const e=Ad.safeParse(t);if(!e.success)throw new Error(`Invalid format: ${e.error.issues[0]?.message}`);this.edit&&(this.edit.output={...this.edit.output,format:e.data}),this.document?.setFormat(e.data),this.events.emit(j.OutputFormatChanged,{format:e.data}),this.emitEditChanged("output:format")}getOutputFormat(){return this.edit?.output?.format??"mp4"}setOutputDestinations(t){const e=Td.array().safeParse(t);if(!e.success)throw new Error(`Invalid destinations: ${e.error.message}`);this.edit&&(this.edit.output={...this.edit.output,destinations:e.data}),this.events.emit(j.OutputDestinationsChanged,{destinations:e.data}),this.emitEditChanged("output:destinations")}getOutputDestinations(){return this.edit?.output?.destinations??[]}getTimelineFonts(){return this.edit?.timeline?.fonts??[]}pruneUnusedFonts(){this.cleanupUnusedFonts()}setTimelineBackground(t){const e=Pd.safeParse(t);if(!e.success)throw new Error(`Invalid color: ${e.error.issues[0]?.message}`);this.backgroundColor=e.data,this.edit&&(this.edit.timeline={...this.edit.timeline,background:e.data}),this.document?.setBackground(e.data),this.background&&(this.background.clear(),this.background.fillStyle={color:this.backgroundColor},this.background.rect(0,0,this.size.width,this.size.height),this.background.fill()),this.events.emit(j.TimelineBackgroundChanged,{color:e.data}),this.emitEditChanged("timeline:background")}getTimelineBackground(){return this.backgroundColor}registerToolbarButton(t){console.warn('[Shotstack] edit.registerToolbarButton() is deprecated. Use ui.registerButton() instead for typed events: ui.registerButton({ id: "text", ... }); ui.on("button:text", handler);');const e=this.toolbarButtons.findIndex(i=>i.id===t.id);e>=0?this.toolbarButtons[e]=t:this.toolbarButtons.push(t),this.events.emit(_s.ToolbarButtonsChanged,{buttons:this.toolbarButtons})}unregisterToolbarButton(t){console.warn("[Shotstack] edit.unregisterToolbarButton() is deprecated. Use ui.unregisterButton() instead.");const e=this.toolbarButtons.findIndex(i=>i.id===t);e>=0&&(this.toolbarButtons.splice(e,1),this.events.emit(_s.ToolbarButtonsChanged,{buttons:this.toolbarButtons}))}getToolbarButtons(){return[...this.toolbarButtons]}getTemplateClip(t,e){const i=this.getPlayerClip(t,e);return i?i.getExportableClip():null}getTemplateClipText(t,e){const i=this.getTemplateClip(t,e);return i?i.asset?.text??null:null}applyMergeField(t,e,i,a,n,r){const o=this.getPlayerClip(t,e);if(!o)return;const l=Ei(o.clipConfiguration,i),c=r??(typeof l=="string"?l:""),d=this.getTemplateClip(t,e),u=d?Ei(d,i):null,f=typeof u=="string"?this.mergeFields.extractFieldName(u):null,p=new rf(o,i,a,f,c,n,t,e);this.executeCommand(p)}removeMergeField(t,e,i,a){const n=this.getPlayerClip(t,e);if(!n)return;const r=this.getTemplateClip(t,e),o=r?Ei(r,i):null,l=typeof o=="string"?this.mergeFields.extractFieldName(o):null;if(!l)return;const c=new rf(n,i,null,l,a,a,t,e);this.executeCommand(c)}getMergeFieldForProperty(t,e,i){const a=this.getTemplateClip(t,e);if(!a)return null;const n=Ei(a,i);return typeof n=="string"?this.mergeFields.extractFieldName(n):null}updateMergeFieldValueLive(t,e){const i=this.mergeFields.get(t);if(i){this.mergeFields.register({...i,defaultValue:e},{silent:!0});for(let a=0;a<this.tracks.length;a+=1)for(let n=0;n<this.tracks[a].length;n+=1){const r=this.tracks[a][n],o=this.getTemplateClip(a,n);o&&(this.updateMergeFieldInObject(r.clipConfiguration,o,t,e),this.updateMergeFieldBindings(r,t,e))}}}updateMergeFieldBindings(t,e,i){for(const[a,n]of t.getMergeFieldBindings())if(this.mergeFields.extractFieldName(n.placeholder)===e){const o=this.mergeFields.resolve(n.placeholder);t.setMergeFieldBinding(a,{placeholder:n.placeholder,resolvedValue:o})}}updateMergeFieldInObject(t,e,i,a){if(!(!t||!e||typeof t!="object"||typeof e!="object"))for(const n of Object.keys(e)){const r=e[n],o=t;typeof r=="string"?this.mergeFields.extractFieldName(r)===i&&(o[n]=r.replace(new RegExp(`\\{\\{\\s*${i}\\s*\\}\\}`,"gi"),a)):r&&typeof r=="object"&&this.updateMergeFieldInObject(o[n],r,i,a)}}redrawMergeFieldClips(t){for(const e of this.tracks)for(const i of e){const a=this.findClipIndices(i);if(a){const n=this.getTemplateClip(a.trackIndex,a.clipIndex);if(n){const r=this.getMergeFieldUsage(n,t);r.used&&(r.isSrcField&&i.reloadAsset(),i.reconfigureAfterRestore(),i.draw())}}}}getMergeFieldUsage(t,e,i=""){if(!t||typeof t!="object")return{used:!1,isSrcField:!1};for(const[a,n]of Object.entries(t)){const r=i?`${i}.${a}`:a;if(typeof n=="string"){if(this.mergeFields.extractFieldName(n)===e)return{used:!0,isSrcField:r==="asset.src"||r.endsWith(".src")}}else if(typeof n=="object"&&n!==null){const o=this.getMergeFieldUsage(n,e,r);if(o.used)return o}}return{used:!1,isSrcField:!1}}isSrcMergeField(t){for(const e of this.tracks)for(const i of e){const a=this.findClipIndices(i);if(a){const n=this.getTemplateClip(a.trackIndex,a.clipIndex);if(n){const r=this.getMergeFieldUsage(n,t);if(r.used&&r.isSrcField)return!0}}}return!1}deleteMergeFieldGlobally(t){const e=this.mergeFields.get(t);if(!e)return;const i=this.mergeFields.createTemplate(t),a=e.defaultValue;for(let n=0;n<this.tracks.length;n+=1)for(let r=0;r<this.tracks[n].length;r+=1){const o=this.getTemplateClip(n,r);o&&this.restoreMergeFieldInClip(n,r,o,i,a)}this.mergeFields.remove(t)}restoreMergeFieldInClip(t,e,i,a,n,r=""){if(!(!i||typeof i!="object"))for(const o of Object.keys(i)){const l=i[o],c=r?`${r}.${o}`:o;if(typeof l=="string"){const d=this.mergeFields.extractFieldName(l),u=this.mergeFields.extractFieldName(a);if(d&&u&&d===u){const f=l.replace(new RegExp(`\\{\\{\\s*${d}\\s*\\}\\}`,"gi"),n);this.removeMergeField(t,e,c,f)}}else typeof l=="object"&&l!==null&&this.restoreMergeFieldInClip(t,e,l,a,n,c)}}lumaAttachments=new Map;originalAssetTypes=new Map;async attachLumaToClip(t,e,i){const a=this.getClipAt(t,e);if(!a||a.playerType===qt.Luma)return;this.lumaAttachments.has(a)&&await this.detachLumaFromClip(t,e);const n=a.clipConfiguration,r={asset:{type:"luma",src:i},start:n.start,length:n.length,fit:"crop"};await this.addClip(t,r);const o=this.tracks[t],l=o.find(c=>c.playerType===qt.Luma&&c.clipConfiguration.start===n.start);if(l){this.lumaAttachments.set(a,l);const c=o.indexOf(l);this.events.emit(j.LumaAttached,{trackIndex:t,clipIndex:e,lumaSrc:i,lumaClipIndex:c})}}async detachLumaFromClip(t,e){const i=this.getClipAt(t,e);if(!i)return;const a=this.lumaAttachments.get(i);if(!a)return;const n=this.findClipIndices(a);if(n){this.lumaAttachments.delete(i);const r=new fr(n.trackIndex,n.clipIndex);this.executeCommand(r),this.events.emit(j.LumaDetached,{trackIndex:t,clipIndex:e})}}getClipLuma(t,e){const i=this.getClipAt(t,e);if(!i)return null;const a=this.lumaAttachments.get(i);if(!a)return null;const n=this.findClipIndices(a);if(!n)return null;const r=a.clipConfiguration.asset?.src;return r?{src:r,clipIndex:n.clipIndex}:null}hasLumaMask(t,e){const i=this.getClipAt(t,e);return i?this.lumaAttachments.has(i):!1}registerLumaAttachment(t,e,i,a){const n=this.getClipAt(t,e),r=this.getClipAt(i,a);n&&r&&this.lumaAttachments.set(n,r)}syncAttachedLuma(t,e){const i=this.getClipAt(t,e);if(!i)return;const a=this.lumaAttachments.get(i);if(!a)return;const n=i.clipConfiguration;a.clipConfiguration.start=n.start,a.clipConfiguration.length=n.length,a.setResolvedTiming({start:i.getStart(),length:i.getLength()}),a.reconfigureAfterRestore(),a.draw();const r=this.findClipIndices(a);r&&this.document.updateClip(r.trackIndex,r.clipIndex,{start:n.start,length:n.length})}getAttachedLumaPlayer(t){return this.lumaAttachments.get(t)??null}rebuildLumaAttachments(){this.lumaAttachments.clear();for(const t of this.tracks){const e=t.find(a=>a.playerType===qt.Luma),i=t.filter(a=>a.playerType!==qt.Luma);if(e&&i.length>0){const a=i.find(n=>n.clipConfiguration.start===e.clipConfiguration.start&&n.clipConfiguration.length===e.clipConfiguration.length);a?this.lumaAttachments.set(a,e):i.length===1&&this.lumaAttachments.set(i[0],e)}}}transformToLuma(t,e){const i=this.getClipAt(t,e);if(!i?.clipConfiguration?.asset)return;const a=i.clipConfiguration.asset,n=a.type,{src:r}=a;r&&(n==="image"||n==="video")&&this.originalAssetTypes.set(r,n);const o=new sf(t,e,"luma");this.executeCommand(o)}transformFromLuma(t,e){const i=this.getClipAt(t,e);if(!i?.clipConfiguration?.asset)return;const{src:a}=i.clipConfiguration.asset;if(!a)return;let n=this.originalAssetTypes.get(a);n||(n=this.inferAssetTypeFromUrl(a));const r=new sf(t,e,n);this.executeCommand(r)}inferAssetTypeFromUrl(t){const e=t.toLowerCase().split("?")[0];return[".mp4",".webm",".mov",".m4v",".avi",".mkv",".ogv",".ogg"].some(a=>e.endsWith(a))?"video":"image"}setupIntentListeners(){this.events.on(_s.CanvasClipClicked,t=>{this.selectPlayer(t.player)}),this.events.on(_s.CanvasBackgroundClicked,()=>{this.clearSelection()})}}const SN="Browser Not Supported",NN="Please try a different browser or enable hardware acceleration in your browser settings.";function TN(s,t){const e=SN,i=NN,a=document.createElement("div");a.className="ss-webgl-error-overlay";const n=document.createElement("div");n.className="ss-webgl-error-content";const r=document.createElement("div");r.className="ss-webgl-error-icon",r.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">
261
261
  <rect x="2" y="3" width="20" height="14" rx="2" ry="2"/>
262
262
  <line x1="8" y1="21" x2="16" y2="21"/>
263
263
  <line x1="12" y1="17" x2="12" y2="21"/>
package/package.json CHANGED
@@ -5,7 +5,7 @@
5
5
  "cpuccino",
6
6
  "dazzatron"
7
7
  ],
8
- "version": "2.0.0-beta.6",
8
+ "version": "2.0.0-beta.7",
9
9
  "description": "A video editing library for creating and editing videos with Shotstack",
10
10
  "type": "module",
11
11
  "main": "dist/shotstack-studio.umd.js",