@shotstack/shotstack-studio 1.5.1 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- (function(H,Z){typeof exports=="object"&&typeof module<"u"?Z(exports,require("pixi.js"),require("howler"),require("opentype.js"),require("@ffmpeg/ffmpeg")):typeof define=="function"&&define.amd?define(["exports","pixi.js","howler","opentype.js","@ffmpeg/ffmpeg"],Z):(H=typeof globalThis<"u"?globalThis:H||self,Z(H.ShotstackStudio={},H.PIXI,H.Howler,H.opentype,H.FFmpeg))})(this,function(H,Z,ci,hi,di){"use strict";function ae(r){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(r){for(const e in r)if(e!=="default"){const i=Object.getOwnPropertyDescriptor(r,e);Object.defineProperty(t,e,i.get?i:{enumerable:!0,get:()=>r[e]})}}return t.default=r,Object.freeze(t)}const d=ae(Z),ui=ae(ci),Ie=ae(hi);class pi{curves={};constructor(){this.initializeCurves()}initializeCurves(){this.curves={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,s){const n=this.curves[s??""]??this.curves.ease,[[a,o],[l,c]]=n,h=i+(3*a-3*l+1)*i*(1-i),p=t,f=t+(e-t)*o,v=t+(e-t)*c,I=e,b=h,O=1-b;return O**3*p+3*O**2*b*f+3*O*b**2*v+b**3*I}}class R{property;length;cubicBuilder;constructor(t,e,i=0){this.property=this.createKeyframes(t,e,i),this.length=e,this.cubicBuilder=new pi}getValue(t){const e=this.property.find(s=>t>=s.start&&t<s.start+s.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 s=this.createNormalizedKeyframes(t);try{this.validateKeyframes(s)}catch(n){console.warn("Keyframe configuration issues detected:",n)}return this.insertFillerKeyframes(s,e,i)}createNormalizedKeyframes(t){return t.toSorted((e,i)=>e.start-i.start).map(e=>({...e,start:e.start*1e3,length:e.length*1e3}))}validateKeyframes(t){for(let e=0;e<t.length;e+=1){const i=t[e],s=t[e+1];if(!s){if(i.start+i.length>this.length)throw new Error("Last keyframe exceeds the maximum duration.");break}if(i.start+i.length>s.start)throw new Error("Overlapping keyframes detected.")}}insertFillerKeyframes(t,e,i=0){const s=[];for(let n=0;n<t.length;n+=1){const a=t[n],o=t[n+1];if(n===0&&a.start!==0){const h={start:0,length:a.start,from:i,to:a.from};s.push(h)}if(s.push(a),!o){if(a.start+a.length<e){const p=a.start+a.length,f={start:p,length:e-p,from:a.to,to:a.to};s.push(f)}break}if(a.start+a.length!==o.start){const h={start:a.start+a.length,length:o.start,from:a.to,to:o.from};s.push(h)}}return s}}class Bt{static Name="AudioLoadParser";name;extension;validAudioExtensions;constructor(){this.name=Bt.Name,this.extension={type:[d.ExtensionType.LoadParser],priority:d.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(s=>{const n={src:t},a=new Howl(n);a.on("load",()=>s(a)),a.on("loaderror",()=>s(null))})}unload(t){t?.unload()}}class fi{clipConfiguration;constructor(t){this.clipConfiguration=t}build(t,e){const i=[],s=[],n=[],a=[],o=[],{effect:l,length:c}=this.clipConfiguration;if(!l)return{offsetXKeyframes:i,offsetYKeyframes:s,opacityKeyframes:n,scaleKeyframes:a,rotationKeyframes:o};const h=0;switch(this.getPresetName()){case"zoomIn":{const f=this.getZoomSpeed(),v=1*this.clipConfiguration.scale,I=f*this.clipConfiguration.scale;a.push({from:v,to:I,start:h,length:c,interpolation:"linear"});break}case"zoomOut":{const v=this.getZoomSpeed()*this.clipConfiguration.scale,I=1*this.clipConfiguration.scale;a.push({from:v,to:I,start:h,length:c,interpolation:"linear"});break}case"slideLeft":{let f=this.getSlideStart();const v=t.width+t.width*f*2,I=e.height/e.width*t.height;if(I<v){const b=Math.abs(v/t.width);a.push({from:b,to:b,start:h,length:c,interpolation:"linear"})}else f=(I-t.width)/2/t.width;i.push({from:f,to:-f,start:h,length:c});break}case"slideRight":{let f=this.getSlideStart();const v=t.width+t.width*f*2,I=e.height/e.width*t.height;if(I<v){const b=Math.abs(v/t.width);a.push({from:b,to:b,start:h,length:c,interpolation:"linear"})}else f=(I-t.width)/2/t.width;i.push({from:-f,to:f,start:h,length:c});break}case"slideUp":{let f=this.getSlideStart();const v=t.height+t.height*f*2,I=e.height/e.width*t.width;if(I<v){const b=Math.abs(v/t.height);a.push({from:b,to:b,start:h,length:c,interpolation:"linear"})}else f=(I-t.height)/2/t.height;s.push({from:f,to:-f,start:h,length:c});break}case"slideDown":{let f=this.getSlideStart();const v=t.height+t.height*f*2,I=e.height/e.width*t.width;if(I<v){const b=Math.abs(v/t.height);a.push({from:b,to:b,start:h,length:c,interpolation:"linear"})}else f=(I-t.height)/2/t.height;s.push({from:-f,to:f,start:h,length:c});break}}return{offsetXKeyframes:i,offsetYKeyframes:s,opacityKeyframes:n,scaleKeyframes:a,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 1.7;default:return .12}return 0}}class gi{clipConfiguration;constructor(t){this.clipConfiguration=t}build(){const t=[],e=[],i=[],s=[],n=[],a=this.buildInPreset();t.push(...a.offsetXKeyframes),e.push(...a.offsetYKeyframes),i.push(...a.opacityKeyframes),s.push(...a.scaleKeyframes),n.push(...a.rotationKeyframes);const o=this.buildOutPreset();return t.push(...o.offsetXKeyframes),e.push(...o.offsetYKeyframes),i.push(...o.opacityKeyframes),s.push(...o.scaleKeyframes),n.push(...o.rotationKeyframes),{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n}}buildInPreset(){const t=[],e=[],i=[],s=[],n=[];if(!this.clipConfiguration.transition?.in)return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n};const a=0,o=this.getInPresetLength();switch(this.getInPresetName()){case"fade":{const h=Math.max(0,Math.min(this.clipConfiguration.opacity??1,1));i.push({from:0,to:h,start:a,length:o,interpolation:"linear"});break}case"zoom":{const h=this.clipConfiguration.scale+9,p=this.clipConfiguration.scale;s.push({from:h,to:p,start:a,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:a,length:o,interpolation:"bezier",easing:"easeIn"});break}case"slideLeft":{const c=this.clipConfiguration.offset?.x+.025,h=this.clipConfiguration.offset?.x;t.push({from:c,to:h,start:a,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:a,length:o,interpolation:"bezier",easing:"easeIn"});break}case"slideRight":{const c=this.clipConfiguration.offset?.x-.025,h=this.clipConfiguration.offset?.x;t.push({from:c,to:h,start:a,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:a,length:o,interpolation:"bezier",easing:"easeIn"});break}case"slideUp":{const c=this.clipConfiguration.offset?.y+.025,h=this.clipConfiguration.offset?.y;e.push({from:c,to:h,start:a,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:a,length:o,interpolation:"bezier",easing:"easeIn"});break}case"slideDown":{const c=this.clipConfiguration.offset?.y-.025,h=this.clipConfiguration.offset?.y;e.push({from:c,to:h,start:a,length:o,interpolation:"bezier",easing:"easeOut"}),i.push({from:0,to:1,start:a,length:o,interpolation:"bezier",easing:"easeOut"});break}case"carouselLeft":case"carouselRight":case"carouselUp":case"carouselDown":case"shuffleTopRight":case"shuffleRightTop":case"shuffleRightBottom":case"shuffleBottomRight":case"shuffleBottomLeft":case"shuffleLeftBottom":case"shuffleLeftTop":case"shuffleTopLeft":default:console.warn(`Unimplemented transition:in preset "${this.clipConfiguration.transition.in}"`);break}return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n}}buildOutPreset(){const t=[],e=[],i=[],s=[],n=[];if(!this.clipConfiguration.transition?.out)return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n};const a=this.getOutPresetLength(),o=this.clipConfiguration.length-a;switch(this.getOutPresetName()){case"fade":{const c=Math.max(0,Math.min(this.clipConfiguration.opacity??1,1));i.push({from:c,to:0,start:o,length:a,interpolation:"linear"});break}case"zoom":{const h=this.clipConfiguration.scale,p=h+9;s.push({from:h,to:p,start:o,length:a,interpolation:"bezier",easing:"easeOut"}),i.push({from:1,to:0,start:o,length:a,interpolation:"bezier",easing:"easeOut"});break}case"slideLeft":{const c=this.clipConfiguration.offset?.x,h=c-.025;t.push({from:c,to:h,start:o,length:a,interpolation:"bezier",easing:"easeOut"}),i.push({from:1,to:0,start:o,length:a,interpolation:"bezier",easing:"easeOut"});break}case"slideRight":{const c=this.clipConfiguration.offset?.x,h=c+.025;t.push({from:c,to:h,start:o,length:a,interpolation:"bezier",easing:"easeOut"}),i.push({from:1,to:0,start:o,length:a,interpolation:"bezier",easing:"easeOut"});break}case"slideUp":{const c=this.clipConfiguration.offset?.y,h=c-.025;e.push({from:c,to:h,start:o,length:a,interpolation:"bezier",easing:"easeIn"}),i.push({from:1,to:0,start:o,length:a,interpolation:"bezier",easing:"easeIn"});break}case"slideDown":{const c=this.clipConfiguration.offset?.y,h=c+.025;e.push({from:c,to:h,start:o,length:a,interpolation:"bezier",easing:"easeIn"}),i.push({from:1,to:0,start:o,length:a,interpolation:"bezier",easing:"easeIn"});break}case"carouselLeft":case"carouselRight":case"carouselUp":case"carouselDown":case"shuffleTopRight":case"shuffleRightTop":case"shuffleRightBottom":case"shuffleBottomRight":case"shuffleBottomLeft":case"shuffleLeftBottom":case"shuffleLeftTop":case"shuffleTopLeft":default:console.warn(`Unimplemented transition:out preset "${this.clipConfiguration.transition.out}"`);break}return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n}}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??"").split(/(Slow|Fast|VeryFast)/);switch(t){case"Slow":return 2;case"Fast":return .5;case"VeryFast":return .25;default:return 1}}getOutPresetLength(){const[,t]=(this.clipConfiguration.transition?.out??"").split(/(Slow|Fast|VeryFast)/);switch(t){case"Slow":return 2;case"Fast":return .5;case"VeryFast":return .25;default:return 1}}}class mi{static ButtonLeftClick=0;static ButtonRightClick=3}class yi{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 nt{container;constructor(){this.container=new d.Container}getContainer(){return this.container}}class D extends nt{static SnapThreshold=20;static DiscardedFrameCount=Math.ceil(1/30*1e3);static ScaleHandleRadius=10;static RotationHandleRadius=10;static RotationHandleOffset=50;static OutlineWidth=5;static MinScale=.1;static MaxScale=5;layer;shouldDispose;edit;clipConfiguration;positionBuilder;offsetXKeyframeBuilder;offsetYKeyframeBuilder;scaleKeyframeBuilder;opacityKeyframeBuilder;rotationKeyframeBuilder;outline;topLeftScaleHandle;topRightScaleHandle;bottomLeftScaleHandle;bottomRightScaleHandle;rotationHandle;isHovering;isDragging;dragOffset;scaleDirection;scaleStart;scaleOffset;isRotating;rotationStart;rotationOffset;initialClipConfiguration;contentContainer;constructor(t,e){super(),this.edit=t,this.layer=0,this.shouldDispose=!1,this.clipConfiguration=e,this.positionBuilder=new yi(t.size),this.outline=null,this.topLeftScaleHandle=null,this.topRightScaleHandle=null,this.bottomRightScaleHandle=null,this.bottomLeftScaleHandle=null,this.rotationHandle=null,this.isHovering=!1,this.isDragging=!1,this.dragOffset={x:0,y:0},this.scaleDirection=null,this.scaleStart=null,this.scaleOffset={x:0,y:0},this.isRotating=!1,this.rotationStart=null,this.rotationOffset={x:0,y:0},this.initialClipConfiguration=null,this.contentContainer=new d.Container,this.getContainer().addChild(this.contentContainer)}reconfigureAfterRestore(){this.configureKeyframes()}configureKeyframes(){if(this.offsetXKeyframeBuilder=new R(this.clipConfiguration.offset?.x??0,this.getLength()),this.offsetYKeyframeBuilder=new R(this.clipConfiguration.offset?.y??0,this.getLength()),this.scaleKeyframeBuilder=new R(this.clipConfiguration.scale??1,this.getLength(),1),this.opacityKeyframeBuilder=new R(this.clipConfiguration.opacity??1,this.getLength(),1),this.rotationKeyframeBuilder=new R(this.clipConfiguration.transform?.rotate?.angle??0,this.getLength()),this.clipHasKeyframes())return;const t=[],e=[],i=[],s=[],n=[],a=new fi(this.clipConfiguration).build(this.edit.size,this.getSize());t.push(...a.offsetXKeyframes),e.push(...a.offsetYKeyframes),i.push(...a.opacityKeyframes),s.push(...a.scaleKeyframes),n.push(...a.rotationKeyframes);const o=new gi(this.clipConfiguration).build();t.push(...o.offsetXKeyframes),e.push(...o.offsetYKeyframes),i.push(...o.opacityKeyframes),s.push(...o.scaleKeyframes),n.push(...o.rotationKeyframes),t.length&&(this.offsetXKeyframeBuilder=new R(t,this.getLength())),e.length&&(this.offsetYKeyframeBuilder=new R(e,this.getLength())),i.length&&(this.opacityKeyframeBuilder=new R(i,this.getLength(),1)),s.length&&(this.scaleKeyframeBuilder=new R(s,this.getLength(),1)),n.length&&(this.rotationKeyframeBuilder=new R(n,this.getLength()))}async load(){this.outline=new d.Graphics,this.getContainer().addChild(this.outline),this.topLeftScaleHandle=new d.Graphics,this.topRightScaleHandle=new d.Graphics,this.bottomRightScaleHandle=new d.Graphics,this.bottomLeftScaleHandle=new d.Graphics,this.rotationHandle=new d.Graphics,this.topLeftScaleHandle.zIndex=1e3,this.topRightScaleHandle.zIndex=1e3,this.bottomRightScaleHandle.zIndex=1e3,this.bottomLeftScaleHandle.zIndex=1e3,this.rotationHandle.zIndex=1e3,this.getContainer().addChild(this.topLeftScaleHandle),this.getContainer().addChild(this.topRightScaleHandle),this.getContainer().addChild(this.bottomRightScaleHandle),this.getContainer().addChild(this.bottomLeftScaleHandle),this.getContainer().addChild(this.rotationHandle),this.getContainer().sortableChildren=!0,this.getContainer().cursor="pointer",this.getContainer().eventMode="static",this.getContainer().on("pointerdown",this.onPointerStart.bind(this)),this.getContainer().on("pointermove",this.onPointerMove.bind(this)),this.getContainer().on("globalpointermove",this.onPointerMove.bind(this)),this.getContainer().on("pointerup",this.onPointerUp.bind(this)),this.getContainer().on("pointerupoutside",this.onPointerUp.bind(this)),this.getContainer().on("pointerover",this.onPointerOver.bind(this)),this.getContainer().on("pointerout",this.onPointerOut.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(),s=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(s.x+i.x,s.y+i.y);const a=this.getRotation();this.contentContainer.alpha=this.getOpacity(),this.getContainer().angle=a,this.shouldDiscardFrame()&&(this.contentContainer.alpha=0)}draw(){if(!this.outline)return;const t=this.edit.isPlayerSelected(this);if((!this.isActive()||!t)&&!this.isHovering){this.outline.clear(),this.topLeftScaleHandle?.clear(),this.topRightScaleHandle?.clear(),this.bottomRightScaleHandle?.clear(),this.bottomLeftScaleHandle?.clear(),this.rotationHandle?.clear();return}const e=this.isHovering||this.isDragging?65535:16777215,i=this.getSize(),s=this.getScale();if(this.outline.clear(),this.outline.strokeStyle={width:D.OutlineWidth/s,color:e},this.outline.rect(0,0,i.width,i.height),this.outline.stroke(),!this.topLeftScaleHandle||!this.topRightScaleHandle||!this.bottomRightScaleHandle||!this.bottomLeftScaleHandle||!this.isActive()||!t)return;this.topLeftScaleHandle.fillStyle={color:e},this.topLeftScaleHandle.clear();const n=D.ScaleHandleRadius*2/s;if(this.topLeftScaleHandle.rect(-n/2,-n/2,n,n),this.topLeftScaleHandle.fill(),this.topRightScaleHandle.fillStyle={color:e},this.topRightScaleHandle.clear(),this.topRightScaleHandle.rect(i.width-n/2,-n/2,n,n),this.topRightScaleHandle.fill(),this.bottomRightScaleHandle.fillStyle={color:e},this.bottomRightScaleHandle.clear(),this.bottomRightScaleHandle.rect(i.width-n/2,i.height-n/2,n,n),this.bottomRightScaleHandle.fill(),this.bottomLeftScaleHandle.fillStyle={color:e},this.bottomLeftScaleHandle.clear(),this.bottomLeftScaleHandle.rect(-n/2,i.height-n/2,n,n),this.bottomLeftScaleHandle.fill(),!this.rotationHandle)return;const a=i.width/2,o=-50/s;this.rotationHandle.clear(),this.rotationHandle.fillStyle={color:e},this.rotationHandle.circle(a,o,D.RotationHandleRadius/s),this.rotationHandle.fill(),this.outline.strokeStyle={width:D.OutlineWidth/s,color:e},this.outline.moveTo(a,0),this.outline.lineTo(a,o),this.outline.stroke()}dispose(){this.outline?.destroy(),this.outline=null,this.topLeftScaleHandle?.destroy(),this.topLeftScaleHandle=null,this.topRightScaleHandle?.destroy(),this.topRightScaleHandle=null,this.bottomLeftScaleHandle?.destroy(),this.bottomLeftScaleHandle=null,this.bottomRightScaleHandle?.destroy(),this.bottomRightScaleHandle=null,this.rotationHandle?.destroy(),this.rotationHandle=null,this.contentContainer?.destroy()}getStart(){return this.clipConfiguration.start*1e3}getLength(){return this.clipConfiguration.length*1e3}getEnd(){return this.getStart()+this.getLength()}getPlaybackTime(){const t=this.edit.playbackTime-this.getStart();return t<0?0:t>this.getLength()?this.getLength():t}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}}getFitScale(){switch(this.clipConfiguration.fit??"crop"){case"crop":{const t=this.edit.size.width/this.getSize().width,e=this.edit.size.height/this.getSize().height;return this.edit.size.height>=this.edit.size.width?e:t}case"cover":return Math.max(this.edit.size.width/this.getSize().width,this.edit.size.height/this.getSize().height);case"contain":return Math.min(this.edit.size.width/this.getSize().width,this.edit.size.height/this.getSize().height);case"none":default:return 1}}getScale(){return(this.scaleKeyframeBuilder?.getValue(this.getPlaybackTime())??1)*this.getFitScale()}getContainerScale(){const t=this.scaleKeyframeBuilder?.getValue(this.getPlaybackTime())??1,e=this.getSize(),i=this.clipConfiguration.fit??"crop";if(e.width===0||e.height===0)return{x:t,y:t};const s=this.edit.size.width/e.width,n=this.edit.size.height/e.height;switch(i){case"contain":{const a=Math.min(s,n)*t;return{x:a,y:a}}case"crop":{const o=(this.edit.size.height>=this.edit.size.width?n:s)*t;return{x:o,y:o}}case"cover":return{x:s*t,y:n*t};case"none":default:return{x:t,y:t}}}getRotation(){return this.rotationKeyframeBuilder?.getValue(this.getPlaybackTime())??0}isActive(){return this.edit.playbackTime>=this.getStart()&&this.edit.playbackTime<this.getEnd()}shouldDiscardFrame(){return this.getPlaybackTime()<D.DiscardedFrameCount}onPointerStart(t){if(t.button!==mi.ButtonLeftClick||(this.edit.events.emit("canvas:clip:clicked",{player:this}),this.initialClipConfiguration=structuredClone(this.clipConfiguration),this.clipHasKeyframes()))return;if(this.scaleDirection=null,this.topLeftScaleHandle?.getBounds().containsPoint(t.globalX,t.globalY)&&(this.scaleDirection="topLeft"),this.topRightScaleHandle?.getBounds().containsPoint(t.globalX,t.globalY)&&(this.scaleDirection="topRight"),this.bottomRightScaleHandle?.getBounds().containsPoint(t.globalX,t.globalY)&&(this.scaleDirection="bottomRight"),this.bottomLeftScaleHandle?.getBounds().containsPoint(t.globalX,t.globalY)&&(this.scaleDirection="bottomLeft"),this.scaleDirection!==null){this.scaleStart=this.getScale()/this.getFitScale();const l=t.getLocalPosition(this.edit.getContainer());this.scaleOffset=l;return}if(this.rotationHandle?.getBounds().containsPoint(t.globalX,t.globalY)){this.isRotating=!0,this.rotationStart=this.getRotation();const l=t.getLocalPosition(this.edit.getContainer());this.rotationOffset=l;return}this.isDragging=!0;const o=t.getLocalPosition(this.edit.getContainer());this.dragOffset={x:o.x-this.getContainer().position.x,y:o.y-this.getContainer().position.y}}onPointerMove(t){if(this.scaleDirection!==null&&this.scaleStart!==null){const e=t.getLocalPosition(this.edit.getContainer()),i=this.getPosition(),s=this.getPivot(),n={x:i.x+s.x,y:i.y+s.y},a=Math.sqrt((this.scaleOffset.x-n.x)**2+(this.scaleOffset.y-n.y)**2),l=Math.sqrt((e.x-n.x)**2+(e.y-n.y)**2)/a,c=this.scaleStart*l;this.clipConfiguration.scale=Math.max(D.MinScale,Math.min(c,D.MaxScale)),this.scaleKeyframeBuilder=new R(this.clipConfiguration.scale,this.getLength(),1);return}if(this.isRotating&&this.rotationStart!==null){const e=t.getLocalPosition(this.edit.getContainer()),i=this.getPosition(),s=this.getPivot(),n={x:i.x+s.x,y:i.y+s.y},a=Math.atan2(this.rotationOffset.y-n.y,this.rotationOffset.x-n.x),l=(Math.atan2(e.y-n.y,e.x-n.x)-a)*(180/Math.PI);let c=this.rotationStart+l;const h=45,p=c%h,f=2;Math.abs(p)<f?c=Math.floor(c/h)*h:Math.abs(p-h)<f&&(c=Math.ceil(c/h)*h),this.clipConfiguration.transform||(this.clipConfiguration.transform={rotate:{angle:0}}),this.clipConfiguration.transform.rotate||(this.clipConfiguration.transform.rotate={angle:0}),this.clipConfiguration.transform.rotate.angle=c,this.rotationKeyframeBuilder=new R(this.clipConfiguration.transform.rotate.angle,this.getLength());return}if(this.isDragging){const e=t.getLocalPosition(this.edit.getContainer()),i=this.getPivot(),s={x:e.x-this.dragOffset.x,y:e.y-this.dragOffset.y},n={x:s.x-i.x,y:s.y-i.y},a=[{x:0,y:0},{x:this.edit.size.width,y:0},{x:0,y:this.edit.size.height},{x:this.edit.size.width,y:this.edit.size.height}],o={x:this.edit.size.width/2,y:this.edit.size.height/2},l=[...a,o],c=[{x:n.x,y:n.y},{x:n.x+this.getSize().width,y:n.y},{x:n.x,y:n.y+this.getSize().height},{x:n.x+this.getSize().width,y:n.y+this.getSize().height}],h={x:n.x+this.getSize().width/2,y:n.y+this.getSize().height/2},p=[...c,h];let f=D.SnapThreshold,v=D.SnapThreshold,I=null,b=null;for(const N of p)for(const lt of l){const et=Math.abs(N.x-lt.x);et<f&&(f=et,I=n.x+(lt.x-N.x));const It=Math.abs(N.y-lt.y);It<v&&(v=It,b=n.y+(lt.y-N.y))}I!==null&&(n.x=I),b!==null&&(n.y=b);const O=this.positionBuilder.absoluteToRelative(this.getSize(),this.clipConfiguration.position??"center",n);this.clipConfiguration.offset||(this.clipConfiguration.offset={x:0,y:0}),this.clipConfiguration.offset.x=O.x,this.clipConfiguration.offset.y=O.y,this.offsetXKeyframeBuilder=new R(this.clipConfiguration.offset.x,this.getLength()),this.offsetYKeyframeBuilder=new R(this.clipConfiguration.offset.y,this.getLength())}}onPointerUp(){(this.isDragging||this.scaleDirection!==null||this.isRotating)&&this.hasStateChanged()&&this.edit.setUpdatedClip(this,this.initialClipConfiguration,structuredClone(this.clipConfiguration)),this.isDragging=!1,this.dragOffset={x:0,y:0},this.scaleDirection=null,this.scaleStart=null,this.scaleOffset={x:0,y:0},this.isRotating=!1,this.rotationStart=null,this.rotationOffset={x:0,y:0},this.initialClipConfiguration=null}onPointerOver(){this.isHovering=!0}onPointerOut(){this.isHovering=!1}clipHasPresets(){return!!this.clipConfiguration.effect||!!this.clipConfiguration.transition?.in||!!this.clipConfiguration.transition?.out}clipHasKeyframes(){return[this.clipConfiguration.scale,this.clipConfiguration.offset?.x,this.clipConfiguration.offset?.y,this.clipConfiguration.transform?.rotate?.angle].some(t=>t&&typeof t!="number")}hasStateChanged(){if(!this.initialClipConfiguration)return!1;const t=this.clipConfiguration.offset?.x,e=this.clipConfiguration.offset?.y,i=this.clipConfiguration.scale,s=Number(this.clipConfiguration.transform?.rotate?.angle??0),n=this.initialClipConfiguration.offset?.x,a=this.initialClipConfiguration.offset?.y,o=this.initialClipConfiguration.scale,l=Number(this.initialClipConfiguration.transform?.rotate?.angle??0);return n!==void 0&&t!==n||a!==void 0&&e!==a||o!==void 0&&i!==o||s!==l}}class oe extends D{audioResource;isPlaying;volumeKeyframeBuilder;syncTimer;constructor(t,e){super(t,e),this.audioResource=null,this.isPlaying=!1;const i=e.asset;this.volumeKeyframeBuilder=new R(i.volume??1,this.getLength()),this.syncTimer=0}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.src,i={src:e,loadParser:Bt.Name},s=await this.edit.assetLoader.load(e,i);if(!(s instanceof ui.Howl))throw new Error(`Invalid audio source '${t.src}'.`);this.audioResource=s,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 s=this.edit.isPlaying&&this.isActive(),n=this.getPlaybackTime();s&&(this.isPlaying||(this.isPlaying=!0,this.audioResource.seek(n/1e3+i),this.audioResource.play()),this.audioResource.volume()!==this.getVolume()&&this.audioResource.volume(this.getVolume()),Math.abs((this.audioResource.seek()-i)*1e3-n)>100&&this.audioResource.seek(n/1e3+i)),this.isPlaying&&!s&&(this.isPlaying=!1,this.audioResource.pause());const a=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&a&&(this.syncTimer=0,this.audioResource.seek(n/1e3+i))}draw(){super.draw()}dispose(){this.audioResource?.unload(),this.audioResource=null}getSize(){return{width:0,height:0}}getVolume(){return this.volumeKeyframeBuilder.getValue(this.getPlaybackTime())}}var vi=`in vec2 aPosition;
1
+ (function(q,Be){typeof exports=="object"&&typeof module<"u"?Be(exports,require("pixi.js"),require("howler"),require("opentype.js")):typeof define=="function"&&define.amd?define(["exports","pixi.js","howler","opentype.js"],Be):(q=typeof globalThis<"u"?globalThis:q||self,Be(q.ShotstackStudio={},q.PIXI,q.Howler,q.opentype))})(this,function(q,Be,zn,Hn){"use strict";function Oi(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const i=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}function Nn(s,e){for(var t=0;t<e.length;t++){const i=e[t];if(typeof i!="string"&&!Array.isArray(i)){for(const r in i)if(r!=="default"&&!(r in s)){const n=Object.getOwnPropertyDescriptor(i,r);n&&Object.defineProperty(s,r,n.get?n:{enumerable:!0,get:()=>i[r]})}}}return Object.freeze(Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}))}const R=Oi(Be),Un=Oi(zn),Rs=Oi(Hn);class jn{curves={};constructor(){this.initializeCurves()}initializeCurves(){this.curves={ease:[[.25,.1],[.25,1]],easeIn:[[.42,0],[1,1]],easeOut:[[0,0],[.58,1]],easeInOut:[[.42,0],[.58,1]],easeInQuad:[[.55,.085],[.68,.53]],easeInCubic:[[.55,.055],[.675,.19]],easeInQuart:[[.895,.03],[.685,.22]],easeInQuint:[[.755,.05],[.855,.06]],easeInSine:[[.47,0],[.745,.715]],easeInExpo:[[.95,.05],[.795,.035]],easeInCirc:[[.6,.04],[.98,.335]],easeInBack:[[.6,-.28],[.735,.045]],easeOutQuad:[[.25,.46],[.45,.94]],easeOutCubic:[[.215,.61],[.355,1]],easeOutQuart:[[.165,.84],[.44,1]],easeOutQuint:[[.23,1],[.32,1]],easeOutSine:[[.39,.575],[.565,1]],easeOutExpo:[[.19,1],[.22,1]],easeOutCirc:[[.075,.82],[.165,1]],easeOutBack:[[.175,.885],[.32,1.275]],easeInOutQuad:[[.455,.03],[.515,.955]],easeInOutCubic:[[.645,.045],[.355,1]],easeInOutQuart:[[.77,0],[.175,1]],easeInOutQuint:[[.86,0],[.07,1]],easeInOutSine:[[.445,.05],[.55,.95]],easeInOutExpo:[[1,0],[0,1]],easeInOutCirc:[[.785,.135],[.15,.86]],easeInOutBack:[[.68,-.55],[.265,1.55]]}}getValue(e,t,i,r){const n=this.curves[r??""]??this.curves.ease,[[o,a],[p,m]]=n,d=i+(3*o-3*p+1)*i*(1-i),l=e,c=e+(t-e)*a,u=e+(t-e)*m,h=t,f=d,b=1-f;return b**3*l+3*b**2*f*c+3*b*f**2*u+f**3*h}}class ke{property;length;cubicBuilder;constructor(e,t,i=0){this.property=this.createKeyframes(e,t,i),this.length=t,this.cubicBuilder=new jn}getValue(e){const t=this.property.find(r=>e>=r.start&&e<r.start+r.length);if(!t){if(this.property.length>0){if(e>=this.length)return this.property[this.property.length-1].to;if(e<0)return this.property[0].from}return 1}const i=(e-t.start)/t.length;switch(t.interpolation){case"bezier":return this.cubicBuilder.getValue(t.from,t.to,i,t.easing);case"constant":return t.from;case"linear":default:return t.from+(t.to-t.from)*i}}createKeyframes(e,t,i=0){if(typeof e=="number")return[{start:0,length:t,from:e,to:e}];if(!e.length)throw new Error("Keyframes should have at least one value.");const r=this.createNormalizedKeyframes(e);try{this.validateKeyframes(r)}catch(n){console.warn("Keyframe configuration issues detected:",n)}return this.insertFillerKeyframes(r,t,i)}createNormalizedKeyframes(e){return e.toSorted((t,i)=>t.start-i.start).map(t=>({...t,start:t.start*1e3,length:t.length*1e3}))}validateKeyframes(e){for(let t=0;t<e.length;t+=1){const i=e[t],r=e[t+1];if(!r){if(i.start+i.length>this.length)throw new Error("Last keyframe exceeds the maximum duration.");break}if(i.start+i.length>r.start)throw new Error("Overlapping keyframes detected.")}}insertFillerKeyframes(e,t,i=0){const r=[];for(let n=0;n<e.length;n+=1){const o=e[n],a=e[n+1];if(n===0&&o.start!==0){const d={start:0,length:o.start,from:i,to:o.from};r.push(d)}if(r.push(o),!a){if(o.start+o.length<t){const l=o.start+o.length,c={start:l,length:t-l,from:o.to,to:o.to};r.push(c)}break}if(o.start+o.length!==a.start){const d={start:o.start+o.length,length:a.start,from:o.to,to:a.from};r.push(d)}}return r}}class zt{static Name="AudioLoadParser";id;name;extension;validAudioExtensions;constructor(){this.id=zt.Name,this.name=zt.Name,this.extension={type:[R.ExtensionType.LoadParser],priority:R.LoaderParserPriority.Normal,ref:null},this.validAudioExtensions=["mp3","mpeg","ogg","wav"]}test(e){const t=e.split("?")[0]?.split(".").pop()??"";return this.validAudioExtensions.includes(t)}async load(e,t,i){return new Promise(r=>{const n={src:e},o=new Howl(n);o.on("load",()=>r(o)),o.on("loaderror",()=>r(null))})}unload(e){e?.unload()}}class Vn{clipConfiguration;constructor(e){this.clipConfiguration=e}build(e,t){const i=[],r=[],n=[],o=[],a=[],{effect:p,length:m}=this.clipConfiguration;if(!p)return{offsetXKeyframes:i,offsetYKeyframes:r,opacityKeyframes:n,scaleKeyframes:o,rotationKeyframes:a};const d=0;switch(this.getPresetName()){case"zoomIn":{const c=this.getZoomSpeed(),u=1*this.clipConfiguration.scale,h=c*this.clipConfiguration.scale;o.push({from:u,to:h,start:d,length:m,interpolation:"linear"});break}case"zoomOut":{const u=this.getZoomSpeed()*this.clipConfiguration.scale,h=1*this.clipConfiguration.scale;o.push({from:u,to:h,start:d,length:m,interpolation:"linear"});break}case"slideLeft":{let c=this.getSlideStart();const u=e.width+e.width*c*2,h=t.height/t.width*e.height;if(h<u){const f=Math.abs(u/e.width);o.push({from:f,to:f,start:d,length:m,interpolation:"linear"})}else c=(h-e.width)/2/e.width;i.push({from:c,to:-c,start:d,length:m});break}case"slideRight":{let c=this.getSlideStart();const u=e.width+e.width*c*2,h=t.height/t.width*e.height;if(h<u){const f=Math.abs(u/e.width);o.push({from:f,to:f,start:d,length:m,interpolation:"linear"})}else c=(h-e.width)/2/e.width;i.push({from:-c,to:c,start:d,length:m});break}case"slideUp":{let c=this.getSlideStart();const u=e.height+e.height*c*2,h=t.height/t.width*e.width;if(h<u){const f=Math.abs(u/e.height);o.push({from:f,to:f,start:d,length:m,interpolation:"linear"})}else c=(h-e.height)/2/e.height;r.push({from:c,to:-c,start:d,length:m});break}case"slideDown":{let c=this.getSlideStart();const u=e.height+e.height*c*2,h=t.height/t.width*e.width;if(h<u){const f=Math.abs(u/e.height);o.push({from:f,to:f,start:d,length:m,interpolation:"linear"})}else c=(h-e.height)/2/e.height;r.push({from:-c,to:c,start:d,length:m});break}}return{offsetXKeyframes:i,offsetYKeyframes:r,opacityKeyframes:n,scaleKeyframes:o,rotationKeyframes:a}}getPresetName(){const[e]=(this.clipConfiguration.effect??"").split(/(Slow|Fast)/);return e}getZoomSpeed(){const[e,t]=(this.clipConfiguration.effect??"").split(/(Slow|Fast)/);if(e.startsWith("zoom"))switch(t){case"Slow":return 1.1;case"Fast":return 1.7;default:return 1.3}return 0}getSlideStart(){const[e,t]=(this.clipConfiguration.effect??"").split(/(Slow|Fast)/);if(e.startsWith("slide"))switch(t){case"Slow":return .03;case"Fast":return 1.7;default:return .12}return 0}}class Wn{clipConfiguration;constructor(e){this.clipConfiguration=e}build(){const e=[],t=[],i=[],r=[],n=[],o=this.buildInPreset();e.push(...o.offsetXKeyframes),t.push(...o.offsetYKeyframes),i.push(...o.opacityKeyframes),r.push(...o.scaleKeyframes),n.push(...o.rotationKeyframes);const a=this.buildOutPreset();return e.push(...a.offsetXKeyframes),t.push(...a.offsetYKeyframes),i.push(...a.opacityKeyframes),r.push(...a.scaleKeyframes),n.push(...a.rotationKeyframes),{offsetXKeyframes:e,offsetYKeyframes:t,opacityKeyframes:i,scaleKeyframes:r,rotationKeyframes:n}}buildInPreset(){const e=[],t=[],i=[],r=[],n=[];if(!this.clipConfiguration.transition?.in)return{offsetXKeyframes:e,offsetYKeyframes:t,opacityKeyframes:i,scaleKeyframes:r,rotationKeyframes:n};const o=0,a=this.getInPresetLength();switch(this.getInPresetName()){case"fade":{const d=Math.max(0,Math.min(this.clipConfiguration.opacity??1,1));i.push({from:0,to:d,start:o,length:a,interpolation:"linear"});break}case"zoom":{const d=this.clipConfiguration.scale+9,l=this.clipConfiguration.scale;r.push({from:d,to:l,start:o,length:a,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:o,length:a,interpolation:"bezier",easing:"easeIn"});break}case"slideLeft":{const m=this.clipConfiguration.offset?.x+.025,d=this.clipConfiguration.offset?.x;e.push({from:m,to:d,start:o,length:a,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:o,length:a,interpolation:"bezier",easing:"easeIn"});break}case"slideRight":{const m=this.clipConfiguration.offset?.x-.025,d=this.clipConfiguration.offset?.x;e.push({from:m,to:d,start:o,length:a,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:o,length:a,interpolation:"bezier",easing:"easeIn"});break}case"slideUp":{const m=this.clipConfiguration.offset?.y+.025,d=this.clipConfiguration.offset?.y;t.push({from:m,to:d,start:o,length:a,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:o,length:a,interpolation:"bezier",easing:"easeIn"});break}case"slideDown":{const m=this.clipConfiguration.offset?.y-.025,d=this.clipConfiguration.offset?.y;t.push({from:m,to:d,start:o,length:a,interpolation:"bezier",easing:"easeOut"}),i.push({from:0,to:1,start:o,length:a,interpolation:"bezier",easing:"easeOut"});break}case"carouselLeft":case"carouselRight":case"carouselUp":case"carouselDown":case"shuffleTopRight":case"shuffleRightTop":case"shuffleRightBottom":case"shuffleBottomRight":case"shuffleBottomLeft":case"shuffleLeftBottom":case"shuffleLeftTop":case"shuffleTopLeft":default:console.warn(`Unimplemented transition:in preset "${this.clipConfiguration.transition.in}"`);break}return{offsetXKeyframes:e,offsetYKeyframes:t,opacityKeyframes:i,scaleKeyframes:r,rotationKeyframes:n}}buildOutPreset(){const e=[],t=[],i=[],r=[],n=[];if(!this.clipConfiguration.transition?.out)return{offsetXKeyframes:e,offsetYKeyframes:t,opacityKeyframes:i,scaleKeyframes:r,rotationKeyframes:n};const o=this.getOutPresetLength(),a=this.clipConfiguration.length-o;switch(this.getOutPresetName()){case"fade":{const m=Math.max(0,Math.min(this.clipConfiguration.opacity??1,1));i.push({from:m,to:0,start:a,length:o,interpolation:"linear"});break}case"zoom":{const d=this.clipConfiguration.scale,l=d+9;r.push({from:d,to:l,start:a,length:o,interpolation:"bezier",easing:"easeOut"}),i.push({from:1,to:0,start:a,length:o,interpolation:"bezier",easing:"easeOut"});break}case"slideLeft":{const m=this.clipConfiguration.offset?.x,d=m-.025;e.push({from:m,to:d,start:a,length:o,interpolation:"bezier",easing:"easeOut"}),i.push({from:1,to:0,start:a,length:o,interpolation:"bezier",easing:"easeOut"});break}case"slideRight":{const m=this.clipConfiguration.offset?.x,d=m+.025;e.push({from:m,to:d,start:a,length:o,interpolation:"bezier",easing:"easeOut"}),i.push({from:1,to:0,start:a,length:o,interpolation:"bezier",easing:"easeOut"});break}case"slideUp":{const m=this.clipConfiguration.offset?.y,d=m-.025;t.push({from:m,to:d,start:a,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:1,to:0,start:a,length:o,interpolation:"bezier",easing:"easeIn"});break}case"slideDown":{const m=this.clipConfiguration.offset?.y,d=m+.025;t.push({from:m,to:d,start:a,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:1,to:0,start:a,length:o,interpolation:"bezier",easing:"easeIn"});break}case"carouselLeft":case"carouselRight":case"carouselUp":case"carouselDown":case"shuffleTopRight":case"shuffleRightTop":case"shuffleRightBottom":case"shuffleBottomRight":case"shuffleBottomLeft":case"shuffleLeftBottom":case"shuffleLeftTop":case"shuffleTopLeft":default:console.warn(`Unimplemented transition:out preset "${this.clipConfiguration.transition.out}"`);break}return{offsetXKeyframes:e,offsetYKeyframes:t,opacityKeyframes:i,scaleKeyframes:r,rotationKeyframes:n}}getInPresetName(){const[e]=(this.clipConfiguration.transition?.in??"").split(/(Slow|Fast|VeryFast)/);return e}getOutPresetName(){const[e]=(this.clipConfiguration.transition?.out??"").split(/(Slow|Fast|VeryFast)/);return e}getInPresetLength(){const[,e]=(this.clipConfiguration.transition?.in??"").split(/(Slow|Fast|VeryFast)/);switch(e){case"Slow":return 2;case"Fast":return .5;case"VeryFast":return .25;default:return 1}}getOutPresetLength(){const[,e]=(this.clipConfiguration.transition?.out??"").split(/(Slow|Fast|VeryFast)/);switch(e){case"Slow":return 2;case"Fast":return .5;case"VeryFast":return .25;default:return 1}}}class Gn{static ButtonLeftClick=0;static ButtonRightClick=3}class Zn{containerSize;constructor(e){this.containerSize=e}relativeToAbsolute(e,t,i){switch(t){case"topLeft":return{x:i.x*this.containerSize.width,y:-i.y*this.containerSize.height};case"topRight":return{x:(i.x+1)*this.containerSize.width-e.width,y:-i.y*this.containerSize.height};case"bottomLeft":return{x:i.x*this.containerSize.width,y:(-i.y+1)*this.containerSize.height-e.height};case"bottomRight":return{x:(i.x+1)*this.containerSize.width-e.width,y:(-i.y+1)*this.containerSize.height-e.height};case"left":return{x:i.x*this.containerSize.width,y:(-i.y+.5)*this.containerSize.height-e.height/2};case"right":return{x:(i.x+1)*this.containerSize.width-e.width,y:(-i.y+.5)*this.containerSize.height-e.height/2};case"top":return{x:(i.x+.5)*this.containerSize.width-e.width/2,y:-i.y*this.containerSize.height};case"bottom":return{x:(i.x+.5)*this.containerSize.width-e.width/2,y:(-i.y+1)*this.containerSize.height-e.height};case"center":default:return{x:(i.x+.5)*this.containerSize.width-e.width/2,y:(-i.y+.5)*this.containerSize.height-e.height/2}}}absoluteToRelative(e,t,i){switch(t){case"topLeft":return{x:i.x/this.containerSize.width,y:-(i.y/this.containerSize.height)};case"topRight":return{x:(i.x+e.width)/this.containerSize.width-1,y:-(i.y/this.containerSize.height)};case"bottomLeft":return{x:i.x/this.containerSize.width,y:-((i.y+e.height)/this.containerSize.height-1)};case"bottomRight":return{x:(i.x+e.width)/this.containerSize.width-1,y:-((i.y+e.height)/this.containerSize.height-1)};case"left":return{x:i.x/this.containerSize.width,y:-((i.y+e.height/2)/this.containerSize.height-.5)};case"right":return{x:(i.x+e.width)/this.containerSize.width-1,y:-((i.y+e.height/2)/this.containerSize.height-.5)};case"top":return{x:(i.x+e.width/2)/this.containerSize.width-.5,y:-(i.y/this.containerSize.height)};case"bottom":return{x:(i.x+e.width/2)/this.containerSize.width-.5,y:-((i.y+e.height)/this.containerSize.height-1)};case"center":default:return{x:(i.x+e.width/2)/this.containerSize.width-.5,y:-((i.y+e.height/2)/this.containerSize.height-.5)}}}}class Je{container;constructor(){this.container=new R.Container}getContainer(){return this.container}}class we extends Je{static SnapThreshold=20;static DiscardedFrameCount=Math.ceil(1/30*1e3);static ScaleHandleRadius=10;static RotationHandleRadius=10;static RotationHandleOffset=50;static OutlineWidth=5;static MinScale=.1;static MaxScale=5;layer;shouldDispose;edit;clipConfiguration;positionBuilder;offsetXKeyframeBuilder;offsetYKeyframeBuilder;scaleKeyframeBuilder;opacityKeyframeBuilder;rotationKeyframeBuilder;outline;topLeftScaleHandle;topRightScaleHandle;bottomLeftScaleHandle;bottomRightScaleHandle;rotationHandle;isHovering;isDragging;dragOffset;scaleDirection;scaleStart;scaleOffset;isRotating;rotationStart;rotationOffset;initialClipConfiguration;contentContainer;constructor(e,t){super(),this.edit=e,this.layer=0,this.shouldDispose=!1,this.clipConfiguration=t,this.positionBuilder=new Zn(e.size),this.outline=null,this.topLeftScaleHandle=null,this.topRightScaleHandle=null,this.bottomRightScaleHandle=null,this.bottomLeftScaleHandle=null,this.rotationHandle=null,this.isHovering=!1,this.isDragging=!1,this.dragOffset={x:0,y:0},this.scaleDirection=null,this.scaleStart=null,this.scaleOffset={x:0,y:0},this.isRotating=!1,this.rotationStart=null,this.rotationOffset={x:0,y:0},this.initialClipConfiguration=null,this.contentContainer=new R.Container,this.getContainer().addChild(this.contentContainer)}reconfigureAfterRestore(){this.configureKeyframes()}configureKeyframes(){if(this.offsetXKeyframeBuilder=new ke(this.clipConfiguration.offset?.x??0,this.getLength()),this.offsetYKeyframeBuilder=new ke(this.clipConfiguration.offset?.y??0,this.getLength()),this.scaleKeyframeBuilder=new ke(this.clipConfiguration.scale??1,this.getLength(),1),this.opacityKeyframeBuilder=new ke(this.clipConfiguration.opacity??1,this.getLength(),1),this.rotationKeyframeBuilder=new ke(this.clipConfiguration.transform?.rotate?.angle??0,this.getLength()),this.clipHasKeyframes())return;const e=[],t=[],i=[],r=[],n=[],o=new Vn(this.clipConfiguration).build(this.edit.size,this.getSize());e.push(...o.offsetXKeyframes),t.push(...o.offsetYKeyframes),i.push(...o.opacityKeyframes),r.push(...o.scaleKeyframes),n.push(...o.rotationKeyframes);const a=new Wn(this.clipConfiguration).build();e.push(...a.offsetXKeyframes),t.push(...a.offsetYKeyframes),i.push(...a.opacityKeyframes),r.push(...a.scaleKeyframes),n.push(...a.rotationKeyframes),e.length&&(this.offsetXKeyframeBuilder=new ke(e,this.getLength())),t.length&&(this.offsetYKeyframeBuilder=new ke(t,this.getLength())),i.length&&(this.opacityKeyframeBuilder=new ke(i,this.getLength(),1)),r.length&&(this.scaleKeyframeBuilder=new ke(r,this.getLength(),1)),n.length&&(this.rotationKeyframeBuilder=new ke(n,this.getLength()))}async load(){this.outline=new R.Graphics,this.getContainer().addChild(this.outline),this.topLeftScaleHandle=new R.Graphics,this.topRightScaleHandle=new R.Graphics,this.bottomRightScaleHandle=new R.Graphics,this.bottomLeftScaleHandle=new R.Graphics,this.rotationHandle=new R.Graphics,this.topLeftScaleHandle.zIndex=1e3,this.topRightScaleHandle.zIndex=1e3,this.bottomRightScaleHandle.zIndex=1e3,this.bottomLeftScaleHandle.zIndex=1e3,this.rotationHandle.zIndex=1e3,this.getContainer().addChild(this.topLeftScaleHandle),this.getContainer().addChild(this.topRightScaleHandle),this.getContainer().addChild(this.bottomRightScaleHandle),this.getContainer().addChild(this.bottomLeftScaleHandle),this.getContainer().addChild(this.rotationHandle),this.getContainer().sortableChildren=!0,this.getContainer().cursor="pointer",this.getContainer().eventMode="static",this.getContainer().on("pointerdown",this.onPointerStart.bind(this)),this.getContainer().on("pointermove",this.onPointerMove.bind(this)),this.getContainer().on("globalpointermove",this.onPointerMove.bind(this)),this.getContainer().on("pointerup",this.onPointerUp.bind(this)),this.getContainer().on("pointerupoutside",this.onPointerUp.bind(this)),this.getContainer().on("pointerover",this.onPointerOver.bind(this)),this.getContainer().on("pointerout",this.onPointerOut.bind(this))}update(e,t){if(this.getContainer().visible=this.isActive(),this.getContainer().zIndex=1e5-this.layer*100,!this.isActive())return;const i=this.getPivot(),r=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(r.x+i.x,r.y+i.y);const o=this.getRotation();this.contentContainer.alpha=this.getOpacity(),this.getContainer().angle=o,this.clipConfiguration.width&&this.clipConfiguration.height&&this.applyFixedDimensions(),this.shouldDiscardFrame()&&(this.contentContainer.alpha=0)}draw(){if(!this.outline)return;const e=this.edit.isPlayerSelected(this),t=this.edit.isInExportMode();if((!this.isActive()||!e)&&!this.isHovering||t){this.outline.clear(),this.topLeftScaleHandle?.clear(),this.topRightScaleHandle?.clear(),this.bottomRightScaleHandle?.clear(),this.bottomLeftScaleHandle?.clear(),this.rotationHandle?.clear();return}const i=this.isHovering||this.isDragging?65535:16777215,r=this.getSize(),n=this.getScale();if(this.outline.clear(),this.outline.strokeStyle={width:we.OutlineWidth/n,color:i},this.outline.rect(0,0,r.width,r.height),this.outline.stroke(),!this.topLeftScaleHandle||!this.topRightScaleHandle||!this.bottomRightScaleHandle||!this.bottomLeftScaleHandle||!this.isActive()||!e)return;this.topLeftScaleHandle.fillStyle={color:i},this.topLeftScaleHandle.clear();const o=we.ScaleHandleRadius*2/n;if(this.topLeftScaleHandle.rect(-o/2,-o/2,o,o),this.topLeftScaleHandle.fill(),this.topRightScaleHandle.fillStyle={color:i},this.topRightScaleHandle.clear(),this.topRightScaleHandle.rect(r.width-o/2,-o/2,o,o),this.topRightScaleHandle.fill(),this.bottomRightScaleHandle.fillStyle={color:i},this.bottomRightScaleHandle.clear(),this.bottomRightScaleHandle.rect(r.width-o/2,r.height-o/2,o,o),this.bottomRightScaleHandle.fill(),this.bottomLeftScaleHandle.fillStyle={color:i},this.bottomLeftScaleHandle.clear(),this.bottomLeftScaleHandle.rect(-o/2,r.height-o/2,o,o),this.bottomLeftScaleHandle.fill(),!this.rotationHandle)return;const a=r.width/2,p=-50/n;this.rotationHandle.clear(),this.rotationHandle.fillStyle={color:i},this.rotationHandle.circle(a,p,we.RotationHandleRadius/n),this.rotationHandle.fill(),this.outline.strokeStyle={width:we.OutlineWidth/n,color:i},this.outline.moveTo(a,0),this.outline.lineTo(a,p),this.outline.stroke()}dispose(){this.outline?.destroy(),this.outline=null,this.topLeftScaleHandle?.destroy(),this.topLeftScaleHandle=null,this.topRightScaleHandle?.destroy(),this.topRightScaleHandle=null,this.bottomLeftScaleHandle?.destroy(),this.bottomLeftScaleHandle=null,this.bottomRightScaleHandle?.destroy(),this.bottomRightScaleHandle=null,this.rotationHandle?.destroy(),this.rotationHandle=null,this.contentContainer?.destroy()}getStart(){return this.clipConfiguration.start*1e3}getLength(){return this.clipConfiguration.length*1e3}getEnd(){return this.getStart()+this.getLength()}getPlaybackTime(){const e=this.edit.playbackTime-this.getStart();return e<0?0:e>this.getLength()?this.getLength():e}getOpacity(){return this.opacityKeyframeBuilder?.getValue(this.getPlaybackTime())??1}getPosition(){const e={x:this.offsetXKeyframeBuilder?.getValue(this.getPlaybackTime())??0,y:this.offsetYKeyframeBuilder?.getValue(this.getPlaybackTime())??0};return this.positionBuilder.relativeToAbsolute(this.getSize(),this.clipConfiguration.position??"center",e)}getPivot(){const e=this.getSize();return{x:e.width/2,y:e.height/2}}getFitScale(){if(this.clipConfiguration.width&&this.clipConfiguration.height)return 1;switch(this.clipConfiguration.fit??"crop"){case"crop":{const e=this.edit.size.width/this.getSize().width,t=this.edit.size.height/this.getSize().height;return this.edit.size.height>=this.edit.size.width?t:e}case"cover":return Math.max(this.edit.size.width/this.getSize().width,this.edit.size.height/this.getSize().height);case"contain":return Math.min(this.edit.size.width/this.getSize().width,this.edit.size.height/this.getSize().height);case"none":default:return 1}}getScale(){return(this.scaleKeyframeBuilder?.getValue(this.getPlaybackTime())??1)*this.getFitScale()}getContainerScale(){if(this.clipConfiguration.width&&this.clipConfiguration.height)return{x:1,y:1};const e=this.scaleKeyframeBuilder?.getValue(this.getPlaybackTime())??1,t=this.getSize(),i=this.clipConfiguration.fit??"crop";if(t.width===0||t.height===0)return{x:e,y:e};const r=this.edit.size.width/t.width,n=this.edit.size.height/t.height;switch(i){case"contain":{const o=Math.min(r,n)*e;return{x:o,y:o}}case"crop":{const a=(this.edit.size.height>=this.edit.size.width?n:r)*e;return{x:a,y:a}}case"cover":return{x:r*e,y:n*e};case"none":default:return{x:e,y:e}}}getRotation(){return this.rotationKeyframeBuilder?.getValue(this.getPlaybackTime())??0}isActive(){return this.edit.playbackTime>=this.getStart()&&this.edit.playbackTime<this.getEnd()}shouldDiscardFrame(){return this.getPlaybackTime()<we.DiscardedFrameCount}onPointerStart(e){if(e.button!==Gn.ButtonLeftClick||(this.edit.events.emit("canvas:clip:clicked",{player:this}),this.initialClipConfiguration=structuredClone(this.clipConfiguration),this.clipHasKeyframes()))return;if(this.scaleDirection=null,this.topLeftScaleHandle?.getBounds().containsPoint(e.globalX,e.globalY)&&(this.scaleDirection="topLeft"),this.topRightScaleHandle?.getBounds().containsPoint(e.globalX,e.globalY)&&(this.scaleDirection="topRight"),this.bottomRightScaleHandle?.getBounds().containsPoint(e.globalX,e.globalY)&&(this.scaleDirection="bottomRight"),this.bottomLeftScaleHandle?.getBounds().containsPoint(e.globalX,e.globalY)&&(this.scaleDirection="bottomLeft"),this.scaleDirection!==null){this.scaleStart=this.getScale()/this.getFitScale();const p=e.getLocalPosition(this.edit.getContainer());this.scaleOffset=p;return}if(this.rotationHandle?.getBounds().containsPoint(e.globalX,e.globalY)){this.isRotating=!0,this.rotationStart=this.getRotation();const p=e.getLocalPosition(this.edit.getContainer());this.rotationOffset=p;return}this.isDragging=!0;const a=e.getLocalPosition(this.edit.getContainer());this.dragOffset={x:a.x-this.getContainer().position.x,y:a.y-this.getContainer().position.y}}onPointerMove(e){if(this.scaleDirection!==null&&this.scaleStart!==null){const t=e.getLocalPosition(this.edit.getContainer()),i=this.getPosition(),r=this.getPivot(),n={x:i.x+r.x,y:i.y+r.y},o=Math.sqrt((this.scaleOffset.x-n.x)**2+(this.scaleOffset.y-n.y)**2),p=Math.sqrt((t.x-n.x)**2+(t.y-n.y)**2)/o,m=this.scaleStart*p;this.clipConfiguration.scale=Math.max(we.MinScale,Math.min(m,we.MaxScale)),this.scaleKeyframeBuilder=new ke(this.clipConfiguration.scale,this.getLength(),1);return}if(this.isRotating&&this.rotationStart!==null){const t=e.getLocalPosition(this.edit.getContainer()),i=this.getPosition(),r=this.getPivot(),n={x:i.x+r.x,y:i.y+r.y},o=Math.atan2(this.rotationOffset.y-n.y,this.rotationOffset.x-n.x),p=(Math.atan2(t.y-n.y,t.x-n.x)-o)*(180/Math.PI);let m=this.rotationStart+p;const d=45,l=m%d,c=2;Math.abs(l)<c?m=Math.floor(m/d)*d:Math.abs(l-d)<c&&(m=Math.ceil(m/d)*d),this.clipConfiguration.transform||(this.clipConfiguration.transform={rotate:{angle:0}}),this.clipConfiguration.transform.rotate||(this.clipConfiguration.transform.rotate={angle:0}),this.clipConfiguration.transform.rotate.angle=m,this.rotationKeyframeBuilder=new ke(this.clipConfiguration.transform.rotate.angle,this.getLength());return}if(this.isDragging){const t=e.getLocalPosition(this.edit.getContainer()),i=this.getPivot(),r={x:t.x-this.dragOffset.x,y:t.y-this.dragOffset.y},n={x:r.x-i.x,y:r.y-i.y},o=[{x:0,y:0},{x:this.edit.size.width,y:0},{x:0,y:this.edit.size.height},{x:this.edit.size.width,y:this.edit.size.height}],a={x:this.edit.size.width/2,y:this.edit.size.height/2},p=[...o,a],m=[{x:n.x,y:n.y},{x:n.x+this.getSize().width,y:n.y},{x:n.x,y:n.y+this.getSize().height},{x:n.x+this.getSize().width,y:n.y+this.getSize().height}],d={x:n.x+this.getSize().width/2,y:n.y+this.getSize().height/2},l=[...m,d];let c=we.SnapThreshold,u=we.SnapThreshold,h=null,f=null;for(const g of l)for(const y of p){const v=Math.abs(g.x-y.x);v<c&&(c=v,h=n.x+(y.x-g.x));const _=Math.abs(g.y-y.y);_<u&&(u=_,f=n.y+(y.y-g.y))}h!==null&&(n.x=h),f!==null&&(n.y=f);const b=this.positionBuilder.absoluteToRelative(this.getSize(),this.clipConfiguration.position??"center",n);this.clipConfiguration.offset||(this.clipConfiguration.offset={x:0,y:0}),this.clipConfiguration.offset.x=b.x,this.clipConfiguration.offset.y=b.y,this.offsetXKeyframeBuilder=new ke(this.clipConfiguration.offset.x,this.getLength()),this.offsetYKeyframeBuilder=new ke(this.clipConfiguration.offset.y,this.getLength())}}onPointerUp(){(this.isDragging||this.scaleDirection!==null||this.isRotating)&&this.hasStateChanged()&&this.edit.setUpdatedClip(this,this.initialClipConfiguration,structuredClone(this.clipConfiguration)),this.isDragging=!1,this.dragOffset={x:0,y:0},this.scaleDirection=null,this.scaleStart=null,this.scaleOffset={x:0,y:0},this.isRotating=!1,this.rotationStart=null,this.rotationOffset={x:0,y:0},this.initialClipConfiguration=null}onPointerOver(){this.isHovering=!0}onPointerOut(){this.isHovering=!1}clipHasPresets(){return!!this.clipConfiguration.effect||!!this.clipConfiguration.transition?.in||!!this.clipConfiguration.transition?.out}clipHasKeyframes(){return[this.clipConfiguration.scale,this.clipConfiguration.offset?.x,this.clipConfiguration.offset?.y,this.clipConfiguration.transform?.rotate?.angle].some(e=>e&&typeof e!="number")}hasStateChanged(){if(!this.initialClipConfiguration)return!1;const e=this.clipConfiguration.offset?.x,t=this.clipConfiguration.offset?.y,i=this.clipConfiguration.scale,r=Number(this.clipConfiguration.transform?.rotate?.angle??0),n=this.initialClipConfiguration.offset?.x,o=this.initialClipConfiguration.offset?.y,a=this.initialClipConfiguration.scale,p=Number(this.initialClipConfiguration.transform?.rotate?.angle??0);return n!==void 0&&e!==n||o!==void 0&&t!==o||a!==void 0&&i!==a||r!==p}applyFixedDimensions(){const e=this.clipConfiguration.width,t=this.clipConfiguration.height;if(!e||!t)return;const i=this.contentContainer.children[0];if(!i||!i.texture)return;const r=i.texture.width,n=i.texture.height,o=this.clipConfiguration.fit||"crop";if(!this.contentContainer.mask){const p=new R.Graphics;p.rect(0,0,e,t),p.fill(16777215),this.contentContainer.addChild(p),this.contentContainer.mask=p}const a=this.scaleKeyframeBuilder?.getValue(this.getPlaybackTime())??1;switch(i.anchor.set(.5,.5),o){case"cover":{const p=e/r,m=t/n;i.scale.set(p,m),i.position.set(e/2,t/2);break}case"crop":{const p=this.edit.size.width,m=this.edit.size.height;let d=1;(r>p||n>m)&&(d=Math.min(p/r,m/n));const l=r*d,c=n*d,u=Math.max(e/l,t/c),h=d<1?d*u:Math.max(1,u);i.scale.set(h,h),i.anchor.set(.5,.5),i.position.set(e/2,t/2);break}case"contain":{const p=e/r,m=t/n,d=Math.min(p,m);i.scale.set(d,d),i.position.set(e/2,t/2);break}case"none":default:{i.scale.set(1,1),i.position.set(e/2,t/2);break}}this.contentContainer.scale.set(a,a),this.contentContainer.position.set(e/2*(1-a),t/2*(1-a))}applyAnchorPositioning(e,t,i,r){const n=r.width,o=r.height;if(!!r.mask){r.position.set(0,0);return}const p=(e??"center").toLowerCase();let m=0,d=0;p.includes("left")||p==="left"?m=0:p.includes("right")||p==="right"?m=t-n:m=(t-n)/2,p.includes("top")||p==="top"?d=0:p.includes("bottom")||p==="bottom"?d=i-o:d=(i-o)/2,r.position.set(m,d)}}class Os extends we{audioResource;isPlaying;volumeKeyframeBuilder;syncTimer;constructor(e,t){super(e,t),this.audioResource=null,this.isPlaying=!1;const i=t.asset;this.volumeKeyframeBuilder=new ke(i.volume??1,this.getLength()),this.syncTimer=0}async load(){await super.load();const e=this.clipConfiguration.asset,t=e.src,i={src:t,loadParser:zt.Name},r=await this.edit.assetLoader.load(t,i);if(!(r instanceof Un.Howl))throw new Error(`Invalid audio source '${e.src}'.`);this.audioResource=r,this.configureKeyframes()}update(e,t){super.update(e,t);const{trim:i=0}=this.clipConfiguration.asset;if(this.syncTimer+=t,this.getContainer().alpha=0,!this.audioResource)return;const r=this.edit.isPlaying&&this.isActive(),n=this.getPlaybackTime();r&&(this.isPlaying||(this.isPlaying=!0,this.audioResource.seek(n/1e3+i),this.audioResource.play()),this.audioResource.volume()!==this.getVolume()&&this.audioResource.volume(this.getVolume()),Math.abs((this.audioResource.seek()-i)*1e3-n)>100&&this.audioResource.seek(n/1e3+i)),this.isPlaying&&!r&&(this.isPlaying=!1,this.audioResource.pause());const o=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&o&&(this.syncTimer=0,this.audioResource.seek(n/1e3+i))}draw(){super.draw()}dispose(){this.audioResource?.unload(),this.audioResource=null}getSize(){return{width:0,height:0}}getVolume(){return this.volumeKeyframeBuilder.getValue(this.getPlaybackTime())}}var Kn=`in vec2 aPosition;
2
2
  out vec2 vTextureCoord;
3
3
 
4
4
  uniform vec4 uInputSize;
@@ -25,7 +25,7 @@ void main(void)
25
25
  gl_Position = filterVertexPosition();
26
26
  vTextureCoord = filterTextureCoord();
27
27
  }
28
- `,Ci=`struct GlobalFilterUniforms {
28
+ `,qn=`struct GlobalFilterUniforms {
29
29
  uInputSize:vec4<f32>,
30
30
  uInputPixel:vec4<f32>,
31
31
  uInputClamp:vec4<f32>,
@@ -74,7 +74,7 @@ fn mainVertex(
74
74
  filterVertexPosition(aPosition),
75
75
  filterTextureCoord(aPosition)
76
76
  );
77
- }`,xi=`precision highp float;
77
+ }`,Xn=`precision highp float;
78
78
  in vec2 vTextureCoord;
79
79
  out vec4 finalColor;
80
80
 
@@ -115,7 +115,7 @@ void main(void) {
115
115
  vec4 outlineColor = vec4(vec3(uColor) * outlineAlpha, outlineAlpha);
116
116
  finalColor = contentColor + outlineColor;
117
117
  }
118
- `,ki=`struct OutlineUniforms {
118
+ `,Yn=`struct OutlineUniforms {
119
119
  uThickness:vec2<f32>,
120
120
  uColor:vec3<f32>,
121
121
  uAlpha:f32,
@@ -179,7 +179,193 @@ fn outlineMaxAlphaAtPos(uv: vec2<f32>) -> f32 {
179
179
  return maxAlpha;
180
180
  }
181
181
 
182
- const DOUBLE_PI: f32 = 3.14159265358979323846264 * 2.;`,Ti=Object.defineProperty,wi=(r,t,e)=>t in r?Ti(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e,ht=(r,t,e)=>(wi(r,typeof t!="symbol"?t+"":t,e),e);const Ft=class mt extends Z.Filter{constructor(...t){let e=t[0]??{};typeof e=="number"&&(Z.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={...mt.DEFAULT_OPTIONS,...e};const i=e.quality??.1,s=Z.GpuProgram.from({vertex:{source:Ci,entryPoint:"mainVertex"},fragment:{source:ki,entryPoint:"mainFragment"}}),n=Z.GlProgram.from({vertex:vi,fragment:xi.replace(/\$\{ANGLE_STEP\}/,mt.getAngleStep(i).toFixed(7)),name:"outline-filter"});super({gpuProgram:s,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"}}}}),ht(this,"uniforms"),ht(this,"_thickness"),ht(this,"_quality"),ht(this,"_color"),this.uniforms=this.resources.outlineUniforms.uniforms,this.uniforms.uAngleStep=mt.getAngleStep(i),this._color=new Z.Color,this.color=e.color??0,Object.assign(this,e)}apply(t,e,i,s){this.uniforms.uThickness[0]=this.thickness/e.source.width,this.uniforms.uThickness[1]=this.thickness/e.source.height,t.applyFilter(this,e,i,s)}static getAngleStep(t){return parseFloat((Math.PI*2/Math.max(t*mt.MAX_SAMPLES,mt.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,s]=this._color.toArray();this.uniforms.uColor[0]=e,this.uniforms.uColor[1]=i,this.uniforms.uColor[2]=s}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=mt.getAngleStep(t)}get knockout(){return this.uniforms.uKnockout===1}set knockout(t){this.uniforms.uKnockout=t?1:0}};ht(Ft,"DEFAULT_OPTIONS",{thickness:1,color:0,alpha:1,quality:.1,knockout:!1}),ht(Ft,"MIN_SAMPLES",1),ht(Ft,"MAX_SAMPLES",100);let le=Ft;class bi extends D{background;text;constructor(t,e){super(t,e),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 d.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 s=new d.Text;s.text=e.text;const{horizontal:n,vertical:a}=e.alignment;s.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-s.width/2,l=(t.height??this.edit.size.height)/2-s.height/2;if(n==="left"&&(o=0),n==="right"&&(o=(t.width??this.edit.size.width)-s.width),a==="top"&&(l=0),a==="bottom"&&(l=(t.height??this.edit.size.height)-s.height),s.position={x:o,y:l},e.stroke.color&&e.stroke.width){const c=new le({thickness:e.stroke.width,color:e.stroke.color});s.filters=[c]}this.background=i,this.text=s,this.contentContainer.addChild(i),this.contentContainer.addChild(s),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:s}=t;if(!e.includes('data-html-type="text"'))return console.warn("Unsupported html format."),null;const a=new DOMParser().parseFromString(e,"text/html").body.textContent??"",l=(await new CSSStyleSheet().replace(i)).cssRules[0],c={text:a,font:{},alignment:{},background:{},stroke:{}};if(l?.constructor.name!=="CSSStyleRule"||!("style"in l))return console.warn("Unsupported css format."),c;const h=l.style,p=this.parseAlignment(s??"center");c.font={color:h.color.length?h.color:void 0,family:h.fontFamily.length?h.fontFamily:void 0,size:h.fontSize.length?parseInt(h.fontSize,10):void 0,weight:h.fontWeight.length?parseInt(h.fontWeight,10):void 0,lineHeight:h.lineHeight.length?parseInt(h.lineHeight,10):void 0},c.alignment=p;let f="";return h.background.length&&(f=h.background),h.backgroundColor.length&&(f=h.backgroundColor),c.background={color:f.length?f:void 0,opacity:h.opacity.length?parseInt(h.opacity,10):void 0},c.stroke={width:h.strokeWidth.length?parseInt(h.strokeWidth,10):void 0,color:h.stroke.length?h.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 Si extends D{texture;sprite;constructor(t,e){super(t,e),this.texture=null,this.sprite=null}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.src,i={src:e,crossovern:"anonymous",data:{}},s=await this.edit.assetLoader.load(e,i);if(!(s?.source instanceof d.ImageSource))throw new Error(`Invalid image source '${t.src}'.`);this.texture=this.createCroppedTexture(s),this.sprite=new d.Sprite(this.texture),this.contentContainer.addChild(this.sprite),this.configureKeyframes()}update(t,e){super.update(t,e)}draw(){super.draw()}dispose(){super.dispose(),this.sprite?.destroy(),this.sprite=null,this.texture?.destroy(),this.texture=null}getSize(){return{width:this.sprite?.width??0,height:this.sprite?.height??0}}createCroppedTexture(t){const e=this.clipConfiguration.asset;if(!e.crop)return t;const i=t.width,s=t.height,n=Math.floor((e.crop?.left??0)*i),a=Math.floor((e.crop?.right??0)*i),o=Math.floor((e.crop?.top??0)*s),l=Math.floor((e.crop?.bottom??0)*s),c=n,h=o,p=i-n-a,f=s-o-l,v=new d.Rectangle(c,h,p,f);return new d.Texture({source:t.source,frame:v})}}class _e extends D{texture;sprite;isPlaying;constructor(t,e){super(t,e),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}},s=await this.edit.assetLoader.load(e,i);if(!(s?.source instanceof d.ImageSource||s?.source instanceof d.VideoSource))throw new Error(`Invalid luma source '${t.src}'.`);this.texture=s,this.sprite=new d.Sprite(this.texture),this.contentContainer.addChild(this.sprite),this.configureKeyframes()}update(t,e){if(super.update(t,e),!this.texture||!(this.texture.source instanceof d.VideoSource))return;const i=this.getPlaybackTime(),s=this.edit.isPlaying&&this.isActive();s&&(this.isPlaying||(this.isPlaying=!0,this.texture.source.resource.currentTime=i/1e3,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*1e3-i)>100&&(this.texture.source.resource.currentTime=i/1e3)),!s&&this.isPlaying&&(this.isPlaying=!1,this.texture.source.resource.pause()),!this.edit.isPlaying&&this.isActive()&&(this.texture.source.resource.currentTime=i/1e3)}draw(){super.draw()}dispose(){super.dispose(),this.sprite?.destroy(),this.sprite=null,this.texture?.destroy(),this.texture=null}getSize(){return{width:this.sprite?.width??0,height:this.sprite?.height??0}}getVolume(){return 0}getMask(){return this.sprite}}class Ii extends D{shape;shapeBackground;constructor(t,e){super(t,e),this.shape=null,this.shapeBackground=null}async load(){await super.load();const t=this.clipConfiguration.asset,e=new d.Graphics,i=t.width??this.edit.size.width,s=t.height??this.edit.size.height;e.fillStyle={color:"transparent"},e.rect(0,0,i,s),e.fill();const n=new d.Graphics;switch(t.shape){case"rectangle":{const a=t.rectangle,o=i/2-a.width/2,l=s/2-a.height/2;n.rect(o,l,a.width,a.height);break}case"circle":{const a=t.circle,o=i/2,l=s/2;n.circle(o,l,a.radius);break}case"line":{const a=t.line,o=i/2-a.length/2,l=s/2-a.thickness/2;n.rect(o,l,a.length,a.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 a=new le({thickness:t.stroke.width,color:t.stroke.color});n.filters=[a]}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 _t{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,s){this.parent=t,this.textElement=e,this.clipConfig=i,this.width=s?.width??_t.DEFAULT_CURSOR_WIDTH_PX,this.color=s?.color??_t.DEFAULT_CURSOR_COLOR,this.blinkIntervalMs=s?.blinkInterval??_t.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 d.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),s=i.match(/\n/g);this.currentLine=s?s.length:0;const n=t.split(`
183
- `),a=this.currentLine<n.length?n[this.currentLine]:"",o=i.lastIndexOf(`
184
- `),l=o===-1?this.textPosition:this.textPosition-o-1,c=a.substring(0,l);let h;c.length>0&&c.endsWith(" ")?h=this.measureText(`${c}x`,e)-this.measureText("x",e):h=this.measureText(c,e);const p=e.lineHeight;this.pixelY=this.currentLine*p;const v=this.clipConfig.asset.alignment?.horizontal??"center";let I=h;if(v!=="left"){const b=this.measureText(a,e),O=this.textElement.width;let N=0;v==="center"?N=(O-b)/2:v==="right"&&(N=O-b),I=N+h}this.pixelX=I}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 d.Text(t,e),{width:s}=i;return i.destroy(),s}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 Nt{static DEFAULT_FOCUS_DELAY_MS=50;hiddenInput=null;isFocused=!1;focusRetryCount=0;maxFocusRetries=3;focusDelay=Nt.DEFAULT_FOCUS_DELAY_MS;eventHandlers={};abortController=null;textChangeCallback=null;lastSyncedText="";isComposing=!1;setupInput(t,e){this.focusDelay=e?.focusDelay??Nt.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,s=Math.max(0,Math.min(t,i)),n=Math.max(s,Math.min(e,i));this.hiddenInput.setSelectionRange(s,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,s=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(i,s)}},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 W{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<W.DOUBLE_CLICK_THRESHOLD_MS&&this.startEditing(),this.lastClickTime=e};setupOutsideClickHandler(t){this.outsideClickHandler=e=>{const s=this.parent.getContainer().getBounds(),n=e.clientX,a=e.clientY;(n<s.x||n>s.x+s.width||a<s.y||a>s.y+s.height)&&(this.stopEditing(!0,t),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null))},setTimeout(()=>{this.outsideClickHandler&&window.addEventListener("click",this.outsideClickHandler)},W.CLICK_HANDLER_DELAY_MS)}createEditingEnvironment(){this.setupEditingContainer(),this.editingContainer&&this.editableText&&(this.textCursor=new _t(this.editingContainer,this.editableText,this.clipConfig),this.textCursor.updatePosition(this.targetText.text.length),this.textCursor.startBlinking()),this.setupTextInputHandler(),this.updateTextAlignment()}setupEditingContainer(){this.editingContainer=new d.Container,this.parent.getContainer().addChild(this.editingContainer);const t=new d.Graphics;t.fillStyle={color:0,alpha:W.EDITING_BG_ALPHA},t.rect(-5,-5,this.targetText.width+2*W.EDITING_BG_PADDING_PX,this.targetText.height+2*W.EDITING_BG_PADDING_PX),t.fill(),this.editingContainer.addChild(t),this.editableText=new d.Text(this.targetText.text,this.targetText.style),this.editableText.eventMode="static",this.editableText.cursor="text",this.editingContainer.addChild(this.editableText)}setupTextInputHandler(){this.textInputHandler=new Nt,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),s=this.calculateVerticalPosition({height:this.editableText.height},t,e.vertical);if(this.editingContainer.position.set(i,s),this.editingContainer.children.length>0){const n=this.editingContainer.getChildAt(0);n instanceof d.Graphics&&(n.clear(),n.fillStyle={color:0,alpha:W.EDITING_BG_ALPHA},n.rect(-5,-5,this.editableText.width+2*W.EDITING_BG_PADDING_PX,this.editableText.height+2*W.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 _i extends D{background=null;text=null;textEditor=null;async load(){await super.load();const t=this.clipConfiguration.asset;if(this.background=new d.Graphics,t.background&&(this.background.fillStyle={color:t.background.color,alpha:t.background.opacity},this.background.rect(0,0,t.width??this.edit.size.width,t.height??this.edit.size.height),this.background.fill()),this.text=new d.Text(t.text,this.createTextStyle(t)),this.positionText(t),t.stroke){const e=new le({thickness:t.stroke.width,color:t.stroke.color});this.text.filters=[e]}this.contentContainer.addChild(this.background),this.contentContainer.addChild(this.text),this.configureKeyframes(),this.textEditor=new W(this,this.text,this.clipConfiguration)}update(t,e){super.update(t,e)}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:t.width??this.edit.size.width,height:t.height??this.edit.size.height}}getFitScale(){return 1}createTextStyle(t){return new d.TextStyle({fontFamily:t.font?.family??"Open Sans",fontSize:t.font?.size??32,fill:t.font?.color??"#ffffff",fontWeight:(t.font?.weight??"400").toString(),wordWrap:!0,wordWrapWidth:t.width??this.edit.size.width,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",s=t.width??this.edit.size.width,n=t.height??this.edit.size.height;let a=s/2-this.text.width/2,o=n/2-this.text.height/2;e==="left"?a=0:e==="right"&&(a=s-this.text.width),i==="top"?o=0:i==="bottom"&&(o=n-this.text.height),this.text.position.set(a,o)}updateTextContent(t,e){this.edit.updateTextContent(this,t,e)}}class Pi extends D{texture;sprite;isPlaying;volumeKeyframeBuilder;syncTimer;constructor(t,e){super(t,e),this.texture=null,this.sprite=null,this.isPlaying=!1;const i=this.clipConfiguration.asset;this.volumeKeyframeBuilder=new R(i.volume??1,this.getLength()),this.syncTimer=0}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.src;if(e.endsWith(".mov")||e.endsWith(".webm"))throw new Error(`Video source '${t.src}' is not supported. .mov and .webm files are currently not supported.`);const i={src:e,data:{autoPlay:!1,muted:!1}},s=await this.edit.assetLoader.load(e,i);if(!(s?.source instanceof d.VideoSource))throw new Error(`Invalid video source '${t.src}'.`);this.texture=this.createCroppedTexture(s),this.sprite=new d.Sprite(this.texture),this.contentContainer.addChild(this.sprite),this.configureKeyframes()}update(t,e){super.update(t,e);const{trim:i=0}=this.clipConfiguration.asset;if(this.syncTimer+=e,!this.texture)return;const s=this.getPlaybackTime(),n=this.edit.isPlaying&&this.isActive();n&&(this.isPlaying||(this.isPlaying=!0,this.texture.source.resource.currentTime=s/1e3+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)*1e3-s)>100&&(this.texture.source.resource.currentTime=s/1e3+i)),!n&&this.isPlaying&&(this.isPlaying=!1,this.texture.source.resource.pause());const a=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&a&&(this.syncTimer=0,this.texture.source.resource.currentTime=s/1e3+i)}draw(){super.draw()}dispose(){super.dispose(),this.sprite?.destroy(),this.sprite=null,this.texture?.destroy(),this.texture=null}getSize(){return{width:this.sprite?.width??0,height:this.sprite?.height??0}}getVolume(){return this.volumeKeyframeBuilder.getValue(this.getPlaybackTime())}createCroppedTexture(t){const e=this.clipConfiguration.asset;if(!e.crop)return t;const i=t.width,s=t.height,n=Math.floor((e.crop?.left??0)*i),a=Math.floor((e.crop?.right??0)*i),o=Math.floor((e.crop?.top??0)*s),l=Math.floor((e.crop?.bottom??0)*s),c=n,h=o,p=i-n-a,f=s-o-l,v=new d.Rectangle(c,h,p,f);return new d.Texture({source:t.source,frame:v})}}var S;(function(r){r.assertEqual=s=>s;function t(s){}r.assertIs=t;function e(s){throw new Error}r.assertNever=e,r.arrayToEnum=s=>{const n={};for(const a of s)n[a]=a;return n},r.getValidEnumValues=s=>{const n=r.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),a={};for(const o of n)a[o]=s[o];return r.objectValues(a)},r.objectValues=s=>r.objectKeys(s).map(function(n){return s[n]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const n=[];for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&n.push(a);return n},r.find=(s,n)=>{for(const a of s)if(n(a))return a},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function i(s,n=" | "){return s.map(a=>typeof a=="string"?`'${a}'`:a).join(n)}r.joinValues=i,r.jsonStringifyReplacer=(s,n)=>typeof n=="bigint"?n.toString():n})(S||(S={}));var Pe;(function(r){r.mergeShapes=(t,e)=>({...t,...e})})(Pe||(Pe={}));const m=S.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),rt=r=>{switch(typeof r){case"undefined":return m.undefined;case"string":return m.string;case"number":return isNaN(r)?m.nan:m.number;case"boolean":return m.boolean;case"function":return m.function;case"bigint":return m.bigint;case"symbol":return m.symbol;case"object":return Array.isArray(r)?m.array:r===null?m.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?m.promise:typeof Map<"u"&&r instanceof Map?m.map:typeof Set<"u"&&r instanceof Set?m.set:typeof Date<"u"&&r instanceof Date?m.date:m.object;default:return m.unknown}},u=S.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class V extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};const e=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,e):this.__proto__=e,this.name="ZodError",this.issues=t}format(t){const e=t||function(n){return n.message},i={_errors:[]},s=n=>{for(const a of n.issues)if(a.code==="invalid_union")a.unionErrors.map(s);else if(a.code==="invalid_return_type")s(a.returnTypeError);else if(a.code==="invalid_arguments")s(a.argumentsError);else if(a.path.length===0)i._errors.push(e(a));else{let o=i,l=0;for(;l<a.path.length;){const c=a.path[l];l===a.path.length-1?(o[c]=o[c]||{_errors:[]},o[c]._errors.push(e(a))):o[c]=o[c]||{_errors:[]},o=o[c],l++}}};return s(this),i}static assert(t){if(!(t instanceof V))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,S.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=e=>e.message){const e={},i=[];for(const s of this.issues)s.path.length>0?(e[s.path[0]]=e[s.path[0]]||[],e[s.path[0]].push(t(s))):i.push(t(s));return{formErrors:i,fieldErrors:e}}get formErrors(){return this.flatten()}}V.create=r=>new V(r);const Pt=(r,t)=>{let e;switch(r.code){case u.invalid_type:r.received===m.undefined?e="Required":e=`Expected ${r.expected}, received ${r.received}`;break;case u.invalid_literal:e=`Invalid literal value, expected ${JSON.stringify(r.expected,S.jsonStringifyReplacer)}`;break;case u.unrecognized_keys:e=`Unrecognized key(s) in object: ${S.joinValues(r.keys,", ")}`;break;case u.invalid_union:e="Invalid input";break;case u.invalid_union_discriminator:e=`Invalid discriminator value. Expected ${S.joinValues(r.options)}`;break;case u.invalid_enum_value:e=`Invalid enum value. Expected ${S.joinValues(r.options)}, received '${r.received}'`;break;case u.invalid_arguments:e="Invalid function arguments";break;case u.invalid_return_type:e="Invalid function return type";break;case u.invalid_date:e="Invalid date";break;case u.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(e=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(e=`${e} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?e=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?e=`Invalid input: must end with "${r.validation.endsWith}"`:S.assertNever(r.validation):r.validation!=="regex"?e=`Invalid ${r.validation}`:e="Invalid";break;case u.too_small:r.type==="array"?e=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?e=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?e=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?e=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:e="Invalid input";break;case u.too_big:r.type==="array"?e=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?e=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?e=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?e=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?e=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:e="Invalid input";break;case u.custom:e="Invalid input";break;case u.invalid_intersection_types:e="Intersection results could not be merged";break;case u.not_multiple_of:e=`Number must be a multiple of ${r.multipleOf}`;break;case u.not_finite:e="Number must be finite";break;default:e=t.defaultError,S.assertNever(r)}return{message:e}};let Ei=Pt;function ce(){return Ei}const he=r=>{const{data:t,path:e,errorMaps:i,issueData:s}=r,n=[...e,...s.path||[]],a={...s,path:n};if(s.message!==void 0)return{...s,path:n,message:s.message};let o="";const l=i.filter(c=>!!c).slice().reverse();for(const c of l)o=c(a,{data:t,defaultError:o}).message;return{...s,path:n,message:o}};function g(r,t){const e=ce(),i=he({issueData:t,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,e,e===Pt?void 0:Pt].filter(s=>!!s)});r.common.issues.push(i)}class L{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,e){const i=[];for(const s of e){if(s.status==="aborted")return k;s.status==="dirty"&&t.dirty(),i.push(s.value)}return{status:t.value,value:i}}static async mergeObjectAsync(t,e){const i=[];for(const s of e){const n=await s.key,a=await s.value;i.push({key:n,value:a})}return L.mergeObjectSync(t,i)}static mergeObjectSync(t,e){const i={};for(const s of e){const{key:n,value:a}=s;if(n.status==="aborted"||a.status==="aborted")return k;n.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),n.value!=="__proto__"&&(typeof a.value<"u"||s.alwaysSet)&&(i[n.value]=a.value)}return{status:t.value,value:i}}}const k=Object.freeze({status:"aborted"}),Et=r=>({status:"dirty",value:r}),z=r=>({status:"valid",value:r}),Ee=r=>r.status==="aborted",Ae=r=>r.status==="dirty",yt=r=>r.status==="valid",Vt=r=>typeof Promise<"u"&&r instanceof Promise;function Gt(r,t,e,i){if(typeof t=="function"?r!==t||!0:!t.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(r)}function Oe(r,t,e,i,s){if(typeof t=="function"?r!==t||!0:!t.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(r,e),e}typeof SuppressedError=="function"&&SuppressedError;var y;(function(r){r.errToObj=t=>typeof t=="string"?{message:t}:t||{},r.toString=t=>typeof t=="string"?t:t?.message})(y||(y={}));var At,Ot;class K{constructor(t,e,i,s){this._cachedPath=[],this.parent=t,this.data=e,this._path=i,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const De=(r,t)=>{if(yt(t))return{success:!0,data:t.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const e=new V(r.common.issues);return this._error=e,this._error}}};function T(r){if(!r)return{};const{errorMap:t,invalid_type_error:e,required_error:i,description:s}=r;if(t&&(e||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(a,o)=>{var l,c;const{message:h}=r;return a.code==="invalid_enum_value"?{message:h??o.defaultError}:typeof o.data>"u"?{message:(l=h??i)!==null&&l!==void 0?l:o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:(c=h??e)!==null&&c!==void 0?c:o.defaultError}},description:s}}class w{get description(){return this._def.description}_getType(t){return rt(t.data)}_getOrReturnCtx(t,e){return e||{common:t.parent.common,data:t.data,parsedType:rt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new L,ctx:{common:t.parent.common,data:t.data,parsedType:rt(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const e=this._parse(t);if(Vt(e))throw new Error("Synchronous parse encountered promise.");return e}_parseAsync(t){const e=this._parse(t);return Promise.resolve(e)}parse(t,e){const i=this.safeParse(t,e);if(i.success)return i.data;throw i.error}safeParse(t,e){var i;const s={common:{issues:[],async:(i=e?.async)!==null&&i!==void 0?i:!1,contextualErrorMap:e?.errorMap},path:e?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:rt(t)},n=this._parseSync({data:t,path:s.path,parent:s});return De(s,n)}"~validate"(t){var e,i;const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:rt(t)};if(!this["~standard"].async)try{const n=this._parseSync({data:t,path:[],parent:s});return yt(n)?{value:n.value}:{issues:s.common.issues}}catch(n){!((i=(e=n?.message)===null||e===void 0?void 0:e.toLowerCase())===null||i===void 0)&&i.includes("encountered")&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:s}).then(n=>yt(n)?{value:n.value}:{issues:s.common.issues})}async parseAsync(t,e){const i=await this.safeParseAsync(t,e);if(i.success)return i.data;throw i.error}async safeParseAsync(t,e){const i={common:{issues:[],contextualErrorMap:e?.errorMap,async:!0},path:e?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:rt(t)},s=this._parse({data:t,path:i.path,parent:i}),n=await(Vt(s)?s:Promise.resolve(s));return De(i,n)}refine(t,e){const i=s=>typeof e=="string"||typeof e>"u"?{message:e}:typeof e=="function"?e(s):e;return this._refinement((s,n)=>{const a=t(s),o=()=>n.addIssue({code:u.custom,...i(s)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(t,e){return this._refinement((i,s)=>t(i)?!0:(s.addIssue(typeof e=="function"?e(i,s):e),!1))}_refinement(t){return new Q({schema:this,typeName:x.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return J.create(this,this._def)}nullable(){return ut.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return $.create(this)}promise(){return Lt.create(this,this._def)}or(t){return Wt.create([this,t],this._def)}and(t){return Kt.create(this,t,this._def)}transform(t){return new Q({...T(this._def),schema:this,typeName:x.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const e=typeof t=="function"?t:()=>t;return new qt({...T(this._def),innerType:this,defaultValue:e,typeName:x.ZodDefault})}brand(){return new He({typeName:x.ZodBranded,type:this,...T(this._def)})}catch(t){const e=typeof t=="function"?t:()=>t;return new Qt({...T(this._def),innerType:this,catchValue:e,typeName:x.ZodCatch})}describe(t){const e=this.constructor;return new e({...this._def,description:t})}pipe(t){return Jt.create(this,t)}readonly(){return te.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Ai=/^c[^\s-]{8,}$/i,Oi=/^[0-9a-z]+$/,Di=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ri=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Li=/^[a-z0-9_-]{21}$/i,Mi=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Hi=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,zi=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Bi="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let de;const Fi=/^(?:(?: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])$/,Ni=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,Vi=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Gi=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ui=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Zi=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Re="((\\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])))",Wi=new RegExp(`^${Re}$`);function Le(r){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return r.precision?t=`${t}\\.\\d{${r.precision}}`:r.precision==null&&(t=`${t}(\\.\\d+)?`),t}function Ki(r){return new RegExp(`^${Le(r)}$`)}function $i(r){let t=`${Re}T${Le(r)}`;const e=[];return e.push(r.local?"Z?":"Z"),r.offset&&e.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${e.join("|")})`,new RegExp(`^${t}$`)}function Yi(r,t){return!!((t==="v4"||!t)&&Fi.test(r)||(t==="v6"||!t)&&Vi.test(r))}function Xi(r,t){if(!Mi.test(r))return!1;try{const[e]=r.split("."),i=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(e.length+(4-e.length%4)%4,"="),s=JSON.parse(atob(i));return!(typeof s!="object"||s===null||!s.typ||!s.alg||t&&s.alg!==t)}catch{return!1}}function ji(r,t){return!!((t==="v4"||!t)&&Ni.test(r)||(t==="v6"||!t)&&Gi.test(r))}class X extends w{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==m.string){const n=this._getOrReturnCtx(t);return g(n,{code:u.invalid_type,expected:m.string,received:n.parsedType}),k}const i=new L;let s;for(const n of this._def.checks)if(n.kind==="min")t.data.length<n.value&&(s=this._getOrReturnCtx(t,s),g(s,{code:u.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),i.dirty());else if(n.kind==="max")t.data.length>n.value&&(s=this._getOrReturnCtx(t,s),g(s,{code:u.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),i.dirty());else if(n.kind==="length"){const a=t.data.length>n.value,o=t.data.length<n.value;(a||o)&&(s=this._getOrReturnCtx(t,s),a?g(s,{code:u.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):o&&g(s,{code:u.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),i.dirty())}else if(n.kind==="email")zi.test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"email",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="emoji")de||(de=new RegExp(Bi,"u")),de.test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"emoji",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="uuid")Ri.test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"uuid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="nanoid")Li.test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"nanoid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="cuid")Ai.test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"cuid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="cuid2")Oi.test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"cuid2",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="ulid")Di.test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"ulid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),g(s,{validation:"url",code:u.invalid_string,message:n.message}),i.dirty()}else n.kind==="regex"?(n.regex.lastIndex=0,n.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"regex",code:u.invalid_string,message:n.message}),i.dirty())):n.kind==="trim"?t.data=t.data.trim():n.kind==="includes"?t.data.includes(n.value,n.position)||(s=this._getOrReturnCtx(t,s),g(s,{code:u.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),i.dirty()):n.kind==="toLowerCase"?t.data=t.data.toLowerCase():n.kind==="toUpperCase"?t.data=t.data.toUpperCase():n.kind==="startsWith"?t.data.startsWith(n.value)||(s=this._getOrReturnCtx(t,s),g(s,{code:u.invalid_string,validation:{startsWith:n.value},message:n.message}),i.dirty()):n.kind==="endsWith"?t.data.endsWith(n.value)||(s=this._getOrReturnCtx(t,s),g(s,{code:u.invalid_string,validation:{endsWith:n.value},message:n.message}),i.dirty()):n.kind==="datetime"?$i(n).test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{code:u.invalid_string,validation:"datetime",message:n.message}),i.dirty()):n.kind==="date"?Wi.test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{code:u.invalid_string,validation:"date",message:n.message}),i.dirty()):n.kind==="time"?Ki(n).test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{code:u.invalid_string,validation:"time",message:n.message}),i.dirty()):n.kind==="duration"?Hi.test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"duration",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="ip"?Yi(t.data,n.version)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"ip",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="jwt"?Xi(t.data,n.alg)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"jwt",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="cidr"?ji(t.data,n.version)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"cidr",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="base64"?Ui.test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"base64",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="base64url"?Zi.test(t.data)||(s=this._getOrReturnCtx(t,s),g(s,{validation:"base64url",code:u.invalid_string,message:n.message}),i.dirty()):S.assertNever(n);return{status:i.value,value:t.data}}_regex(t,e,i){return this.refinement(s=>t.test(s),{validation:e,code:u.invalid_string,...y.errToObj(i)})}_addCheck(t){return new X({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...y.errToObj(t)})}url(t){return this._addCheck({kind:"url",...y.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...y.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...y.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...y.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...y.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...y.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...y.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...y.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...y.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...y.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...y.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...y.errToObj(t)})}datetime(t){var e,i;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:(e=t?.offset)!==null&&e!==void 0?e:!1,local:(i=t?.local)!==null&&i!==void 0?i:!1,...y.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...y.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...y.errToObj(t)})}regex(t,e){return this._addCheck({kind:"regex",regex:t,...y.errToObj(e)})}includes(t,e){return this._addCheck({kind:"includes",value:t,position:e?.position,...y.errToObj(e?.message)})}startsWith(t,e){return this._addCheck({kind:"startsWith",value:t,...y.errToObj(e)})}endsWith(t,e){return this._addCheck({kind:"endsWith",value:t,...y.errToObj(e)})}min(t,e){return this._addCheck({kind:"min",value:t,...y.errToObj(e)})}max(t,e){return this._addCheck({kind:"max",value:t,...y.errToObj(e)})}length(t,e){return this._addCheck({kind:"length",value:t,...y.errToObj(e)})}nonempty(t){return this.min(1,y.errToObj(t))}trim(){return new X({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new X({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new X({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const e of this._def.checks)e.kind==="min"&&(t===null||e.value>t)&&(t=e.value);return t}get maxLength(){let t=null;for(const e of this._def.checks)e.kind==="max"&&(t===null||e.value<t)&&(t=e.value);return t}}X.create=r=>{var t;return new X({checks:[],typeName:x.ZodString,coerce:(t=r?.coerce)!==null&&t!==void 0?t:!1,...T(r)})};function qi(r,t){const e=(r.toString().split(".")[1]||"").length,i=(t.toString().split(".")[1]||"").length,s=e>i?e:i,n=parseInt(r.toFixed(s).replace(".","")),a=parseInt(t.toFixed(s).replace(".",""));return n%a/Math.pow(10,s)}class vt extends w{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==m.number){const n=this._getOrReturnCtx(t);return g(n,{code:u.invalid_type,expected:m.number,received:n.parsedType}),k}let i;const s=new L;for(const n of this._def.checks)n.kind==="int"?S.isInteger(t.data)||(i=this._getOrReturnCtx(t,i),g(i,{code:u.invalid_type,expected:"integer",received:"float",message:n.message}),s.dirty()):n.kind==="min"?(n.inclusive?t.data<n.value:t.data<=n.value)&&(i=this._getOrReturnCtx(t,i),g(i,{code:u.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),s.dirty()):n.kind==="max"?(n.inclusive?t.data>n.value:t.data>=n.value)&&(i=this._getOrReturnCtx(t,i),g(i,{code:u.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),s.dirty()):n.kind==="multipleOf"?qi(t.data,n.value)!==0&&(i=this._getOrReturnCtx(t,i),g(i,{code:u.not_multiple_of,multipleOf:n.value,message:n.message}),s.dirty()):n.kind==="finite"?Number.isFinite(t.data)||(i=this._getOrReturnCtx(t,i),g(i,{code:u.not_finite,message:n.message}),s.dirty()):S.assertNever(n);return{status:s.value,value:t.data}}gte(t,e){return this.setLimit("min",t,!0,y.toString(e))}gt(t,e){return this.setLimit("min",t,!1,y.toString(e))}lte(t,e){return this.setLimit("max",t,!0,y.toString(e))}lt(t,e){return this.setLimit("max",t,!1,y.toString(e))}setLimit(t,e,i,s){return new vt({...this._def,checks:[...this._def.checks,{kind:t,value:e,inclusive:i,message:y.toString(s)}]})}_addCheck(t){return new vt({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:y.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:y.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:y.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:y.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:y.toString(t)})}multipleOf(t,e){return this._addCheck({kind:"multipleOf",value:t,message:y.toString(e)})}finite(t){return this._addCheck({kind:"finite",message:y.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:y.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:y.toString(t)})}get minValue(){let t=null;for(const e of this._def.checks)e.kind==="min"&&(t===null||e.value>t)&&(t=e.value);return t}get maxValue(){let t=null;for(const e of this._def.checks)e.kind==="max"&&(t===null||e.value<t)&&(t=e.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&S.isInteger(t.value))}get isFinite(){let t=null,e=null;for(const i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(e===null||i.value>e)&&(e=i.value):i.kind==="max"&&(t===null||i.value<t)&&(t=i.value)}return Number.isFinite(e)&&Number.isFinite(t)}}vt.create=r=>new vt({checks:[],typeName:x.ZodNumber,coerce:r?.coerce||!1,...T(r)});class Ct extends w{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==m.bigint)return this._getInvalidInput(t);let i;const s=new L;for(const n of this._def.checks)n.kind==="min"?(n.inclusive?t.data<n.value:t.data<=n.value)&&(i=this._getOrReturnCtx(t,i),g(i,{code:u.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),s.dirty()):n.kind==="max"?(n.inclusive?t.data>n.value:t.data>=n.value)&&(i=this._getOrReturnCtx(t,i),g(i,{code:u.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),s.dirty()):n.kind==="multipleOf"?t.data%n.value!==BigInt(0)&&(i=this._getOrReturnCtx(t,i),g(i,{code:u.not_multiple_of,multipleOf:n.value,message:n.message}),s.dirty()):S.assertNever(n);return{status:s.value,value:t.data}}_getInvalidInput(t){const e=this._getOrReturnCtx(t);return g(e,{code:u.invalid_type,expected:m.bigint,received:e.parsedType}),k}gte(t,e){return this.setLimit("min",t,!0,y.toString(e))}gt(t,e){return this.setLimit("min",t,!1,y.toString(e))}lte(t,e){return this.setLimit("max",t,!0,y.toString(e))}lt(t,e){return this.setLimit("max",t,!1,y.toString(e))}setLimit(t,e,i,s){return new Ct({...this._def,checks:[...this._def.checks,{kind:t,value:e,inclusive:i,message:y.toString(s)}]})}_addCheck(t){return new Ct({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:y.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:y.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:y.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:y.toString(t)})}multipleOf(t,e){return this._addCheck({kind:"multipleOf",value:t,message:y.toString(e)})}get minValue(){let t=null;for(const e of this._def.checks)e.kind==="min"&&(t===null||e.value>t)&&(t=e.value);return t}get maxValue(){let t=null;for(const e of this._def.checks)e.kind==="max"&&(t===null||e.value<t)&&(t=e.value);return t}}Ct.create=r=>{var t;return new Ct({checks:[],typeName:x.ZodBigInt,coerce:(t=r?.coerce)!==null&&t!==void 0?t:!1,...T(r)})};class ue extends w{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==m.boolean){const i=this._getOrReturnCtx(t);return g(i,{code:u.invalid_type,expected:m.boolean,received:i.parsedType}),k}return z(t.data)}}ue.create=r=>new ue({typeName:x.ZodBoolean,coerce:r?.coerce||!1,...T(r)});class Dt extends w{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==m.date){const n=this._getOrReturnCtx(t);return g(n,{code:u.invalid_type,expected:m.date,received:n.parsedType}),k}if(isNaN(t.data.getTime())){const n=this._getOrReturnCtx(t);return g(n,{code:u.invalid_date}),k}const i=new L;let s;for(const n of this._def.checks)n.kind==="min"?t.data.getTime()<n.value&&(s=this._getOrReturnCtx(t,s),g(s,{code:u.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),i.dirty()):n.kind==="max"?t.data.getTime()>n.value&&(s=this._getOrReturnCtx(t,s),g(s,{code:u.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),i.dirty()):S.assertNever(n);return{status:i.value,value:new Date(t.data.getTime())}}_addCheck(t){return new Dt({...this._def,checks:[...this._def.checks,t]})}min(t,e){return this._addCheck({kind:"min",value:t.getTime(),message:y.toString(e)})}max(t,e){return this._addCheck({kind:"max",value:t.getTime(),message:y.toString(e)})}get minDate(){let t=null;for(const e of this._def.checks)e.kind==="min"&&(t===null||e.value>t)&&(t=e.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const e of this._def.checks)e.kind==="max"&&(t===null||e.value<t)&&(t=e.value);return t!=null?new Date(t):null}}Dt.create=r=>new Dt({checks:[],coerce:r?.coerce||!1,typeName:x.ZodDate,...T(r)});class pe extends w{_parse(t){if(this._getType(t)!==m.symbol){const i=this._getOrReturnCtx(t);return g(i,{code:u.invalid_type,expected:m.symbol,received:i.parsedType}),k}return z(t.data)}}pe.create=r=>new pe({typeName:x.ZodSymbol,...T(r)});class Ut extends w{_parse(t){if(this._getType(t)!==m.undefined){const i=this._getOrReturnCtx(t);return g(i,{code:u.invalid_type,expected:m.undefined,received:i.parsedType}),k}return z(t.data)}}Ut.create=r=>new Ut({typeName:x.ZodUndefined,...T(r)});class Zt extends w{_parse(t){if(this._getType(t)!==m.null){const i=this._getOrReturnCtx(t);return g(i,{code:u.invalid_type,expected:m.null,received:i.parsedType}),k}return z(t.data)}}Zt.create=r=>new Zt({typeName:x.ZodNull,...T(r)});class fe extends w{constructor(){super(...arguments),this._any=!0}_parse(t){return z(t.data)}}fe.create=r=>new fe({typeName:x.ZodAny,...T(r)});class xt extends w{constructor(){super(...arguments),this._unknown=!0}_parse(t){return z(t.data)}}xt.create=r=>new xt({typeName:x.ZodUnknown,...T(r)});class at extends w{_parse(t){const e=this._getOrReturnCtx(t);return g(e,{code:u.invalid_type,expected:m.never,received:e.parsedType}),k}}at.create=r=>new at({typeName:x.ZodNever,...T(r)});class ge extends w{_parse(t){if(this._getType(t)!==m.undefined){const i=this._getOrReturnCtx(t);return g(i,{code:u.invalid_type,expected:m.void,received:i.parsedType}),k}return z(t.data)}}ge.create=r=>new ge({typeName:x.ZodVoid,...T(r)});class $ extends w{_parse(t){const{ctx:e,status:i}=this._processInputParams(t),s=this._def;if(e.parsedType!==m.array)return g(e,{code:u.invalid_type,expected:m.array,received:e.parsedType}),k;if(s.exactLength!==null){const a=e.data.length>s.exactLength.value,o=e.data.length<s.exactLength.value;(a||o)&&(g(e,{code:a?u.too_big:u.too_small,minimum:o?s.exactLength.value:void 0,maximum:a?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),i.dirty())}if(s.minLength!==null&&e.data.length<s.minLength.value&&(g(e,{code:u.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),i.dirty()),s.maxLength!==null&&e.data.length>s.maxLength.value&&(g(e,{code:u.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),i.dirty()),e.common.async)return Promise.all([...e.data].map((a,o)=>s.type._parseAsync(new K(e,a,e.path,o)))).then(a=>L.mergeArray(i,a));const n=[...e.data].map((a,o)=>s.type._parseSync(new K(e,a,e.path,o)));return L.mergeArray(i,n)}get element(){return this._def.type}min(t,e){return new $({...this._def,minLength:{value:t,message:y.toString(e)}})}max(t,e){return new $({...this._def,maxLength:{value:t,message:y.toString(e)}})}length(t,e){return new $({...this._def,exactLength:{value:t,message:y.toString(e)}})}nonempty(t){return this.min(1,t)}}$.create=(r,t)=>new $({type:r,minLength:null,maxLength:null,exactLength:null,typeName:x.ZodArray,...T(t)});function kt(r){if(r instanceof A){const t={};for(const e in r.shape){const i=r.shape[e];t[e]=J.create(kt(i))}return new A({...r._def,shape:()=>t})}else return r instanceof $?new $({...r._def,type:kt(r.element)}):r instanceof J?J.create(kt(r.unwrap())):r instanceof ut?ut.create(kt(r.unwrap())):r instanceof q?q.create(r.items.map(t=>kt(t))):r}class A extends w{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),e=S.objectKeys(t);return this._cached={shape:t,keys:e}}_parse(t){if(this._getType(t)!==m.object){const c=this._getOrReturnCtx(t);return g(c,{code:u.invalid_type,expected:m.object,received:c.parsedType}),k}const{status:i,ctx:s}=this._processInputParams(t),{shape:n,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof at&&this._def.unknownKeys==="strip"))for(const c in s.data)a.includes(c)||o.push(c);const l=[];for(const c of a){const h=n[c],p=s.data[c];l.push({key:{status:"valid",value:c},value:h._parse(new K(s,p,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof at){const c=this._def.unknownKeys;if(c==="passthrough")for(const h of o)l.push({key:{status:"valid",value:h},value:{status:"valid",value:s.data[h]}});else if(c==="strict")o.length>0&&(g(s,{code:u.unrecognized_keys,keys:o}),i.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const h of o){const p=s.data[h];l.push({key:{status:"valid",value:h},value:c._parse(new K(s,p,s.path,h)),alwaysSet:h in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const c=[];for(const h of l){const p=await h.key,f=await h.value;c.push({key:p,value:f,alwaysSet:h.alwaysSet})}return c}).then(c=>L.mergeObjectSync(i,c)):L.mergeObjectSync(i,l)}get shape(){return this._def.shape()}strict(t){return y.errToObj,new A({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(e,i)=>{var s,n,a,o;const l=(a=(n=(s=this._def).errorMap)===null||n===void 0?void 0:n.call(s,e,i).message)!==null&&a!==void 0?a:i.defaultError;return e.code==="unrecognized_keys"?{message:(o=y.errToObj(t).message)!==null&&o!==void 0?o:l}:{message:l}}}:{}})}strip(){return new A({...this._def,unknownKeys:"strip"})}passthrough(){return new A({...this._def,unknownKeys:"passthrough"})}extend(t){return new A({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new A({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:x.ZodObject})}setKey(t,e){return this.augment({[t]:e})}catchall(t){return new A({...this._def,catchall:t})}pick(t){const e={};return S.objectKeys(t).forEach(i=>{t[i]&&this.shape[i]&&(e[i]=this.shape[i])}),new A({...this._def,shape:()=>e})}omit(t){const e={};return S.objectKeys(this.shape).forEach(i=>{t[i]||(e[i]=this.shape[i])}),new A({...this._def,shape:()=>e})}deepPartial(){return kt(this)}partial(t){const e={};return S.objectKeys(this.shape).forEach(i=>{const s=this.shape[i];t&&!t[i]?e[i]=s:e[i]=s.optional()}),new A({...this._def,shape:()=>e})}required(t){const e={};return S.objectKeys(this.shape).forEach(i=>{if(t&&!t[i])e[i]=this.shape[i];else{let n=this.shape[i];for(;n instanceof J;)n=n._def.innerType;e[i]=n}}),new A({...this._def,shape:()=>e})}keyof(){return Me(S.objectKeys(this.shape))}}A.create=(r,t)=>new A({shape:()=>r,unknownKeys:"strip",catchall:at.create(),typeName:x.ZodObject,...T(t)}),A.strictCreate=(r,t)=>new A({shape:()=>r,unknownKeys:"strict",catchall:at.create(),typeName:x.ZodObject,...T(t)}),A.lazycreate=(r,t)=>new A({shape:r,unknownKeys:"strip",catchall:at.create(),typeName:x.ZodObject,...T(t)});class Wt extends w{_parse(t){const{ctx:e}=this._processInputParams(t),i=this._def.options;function s(n){for(const o of n)if(o.result.status==="valid")return o.result;for(const o of n)if(o.result.status==="dirty")return e.common.issues.push(...o.ctx.common.issues),o.result;const a=n.map(o=>new V(o.ctx.common.issues));return g(e,{code:u.invalid_union,unionErrors:a}),k}if(e.common.async)return Promise.all(i.map(async n=>{const a={...e,common:{...e.common,issues:[]},parent:null};return{result:await n._parseAsync({data:e.data,path:e.path,parent:a}),ctx:a}})).then(s);{let n;const a=[];for(const l of i){const c={...e,common:{...e.common,issues:[]},parent:null},h=l._parseSync({data:e.data,path:e.path,parent:c});if(h.status==="valid")return h;h.status==="dirty"&&!n&&(n={result:h,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(n)return e.common.issues.push(...n.ctx.common.issues),n.result;const o=a.map(l=>new V(l));return g(e,{code:u.invalid_union,unionErrors:o}),k}}get options(){return this._def.options}}Wt.create=(r,t)=>new Wt({options:r,typeName:x.ZodUnion,...T(t)});const j=r=>r instanceof Yt?j(r.schema):r instanceof Q?j(r.innerType()):r instanceof Xt?[r.value]:r instanceof dt?r.options:r instanceof jt?S.objectValues(r.enum):r instanceof qt?j(r._def.innerType):r instanceof Ut?[void 0]:r instanceof Zt?[null]:r instanceof J?[void 0,...j(r.unwrap())]:r instanceof ut?[null,...j(r.unwrap())]:r instanceof He||r instanceof te?j(r.unwrap()):r instanceof Qt?j(r._def.innerType):[];class me extends w{_parse(t){const{ctx:e}=this._processInputParams(t);if(e.parsedType!==m.object)return g(e,{code:u.invalid_type,expected:m.object,received:e.parsedType}),k;const i=this.discriminator,s=e.data[i],n=this.optionsMap.get(s);return n?e.common.async?n._parseAsync({data:e.data,path:e.path,parent:e}):n._parseSync({data:e.data,path:e.path,parent:e}):(g(e,{code:u.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),k)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,e,i){const s=new Map;for(const n of e){const a=j(n.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const o of a){if(s.has(o))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(o)}`);s.set(o,n)}}return new me({typeName:x.ZodDiscriminatedUnion,discriminator:t,options:e,optionsMap:s,...T(i)})}}function ye(r,t){const e=rt(r),i=rt(t);if(r===t)return{valid:!0,data:r};if(e===m.object&&i===m.object){const s=S.objectKeys(t),n=S.objectKeys(r).filter(o=>s.indexOf(o)!==-1),a={...r,...t};for(const o of n){const l=ye(r[o],t[o]);if(!l.valid)return{valid:!1};a[o]=l.data}return{valid:!0,data:a}}else if(e===m.array&&i===m.array){if(r.length!==t.length)return{valid:!1};const s=[];for(let n=0;n<r.length;n++){const a=r[n],o=t[n],l=ye(a,o);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return e===m.date&&i===m.date&&+r==+t?{valid:!0,data:r}:{valid:!1}}class Kt extends w{_parse(t){const{status:e,ctx:i}=this._processInputParams(t),s=(n,a)=>{if(Ee(n)||Ee(a))return k;const o=ye(n.value,a.value);return o.valid?((Ae(n)||Ae(a))&&e.dirty(),{status:e.value,value:o.data}):(g(i,{code:u.invalid_intersection_types}),k)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([n,a])=>s(n,a)):s(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}Kt.create=(r,t,e)=>new Kt({left:r,right:t,typeName:x.ZodIntersection,...T(e)});class q extends w{_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.parsedType!==m.array)return g(i,{code:u.invalid_type,expected:m.array,received:i.parsedType}),k;if(i.data.length<this._def.items.length)return g(i,{code:u.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),k;!this._def.rest&&i.data.length>this._def.items.length&&(g(i,{code:u.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),e.dirty());const n=[...i.data].map((a,o)=>{const l=this._def.items[o]||this._def.rest;return l?l._parse(new K(i,a,i.path,o)):null}).filter(a=>!!a);return i.common.async?Promise.all(n).then(a=>L.mergeArray(e,a)):L.mergeArray(e,n)}get items(){return this._def.items}rest(t){return new q({...this._def,rest:t})}}q.create=(r,t)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new q({items:r,typeName:x.ZodTuple,rest:null,...T(t)})};class $t extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.parsedType!==m.object)return g(i,{code:u.invalid_type,expected:m.object,received:i.parsedType}),k;const s=[],n=this._def.keyType,a=this._def.valueType;for(const o in i.data)s.push({key:n._parse(new K(i,o,i.path,o)),value:a._parse(new K(i,i.data[o],i.path,o)),alwaysSet:o in i.data});return i.common.async?L.mergeObjectAsync(e,s):L.mergeObjectSync(e,s)}get element(){return this._def.valueType}static create(t,e,i){return e instanceof w?new $t({keyType:t,valueType:e,typeName:x.ZodRecord,...T(i)}):new $t({keyType:X.create(),valueType:t,typeName:x.ZodRecord,...T(e)})}}class ve extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.parsedType!==m.map)return g(i,{code:u.invalid_type,expected:m.map,received:i.parsedType}),k;const s=this._def.keyType,n=this._def.valueType,a=[...i.data.entries()].map(([o,l],c)=>({key:s._parse(new K(i,o,i.path,[c,"key"])),value:n._parse(new K(i,l,i.path,[c,"value"]))}));if(i.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const l of a){const c=await l.key,h=await l.value;if(c.status==="aborted"||h.status==="aborted")return k;(c.status==="dirty"||h.status==="dirty")&&e.dirty(),o.set(c.value,h.value)}return{status:e.value,value:o}})}else{const o=new Map;for(const l of a){const c=l.key,h=l.value;if(c.status==="aborted"||h.status==="aborted")return k;(c.status==="dirty"||h.status==="dirty")&&e.dirty(),o.set(c.value,h.value)}return{status:e.value,value:o}}}}ve.create=(r,t,e)=>new ve({valueType:t,keyType:r,typeName:x.ZodMap,...T(e)});class Tt extends w{_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.parsedType!==m.set)return g(i,{code:u.invalid_type,expected:m.set,received:i.parsedType}),k;const s=this._def;s.minSize!==null&&i.data.size<s.minSize.value&&(g(i,{code:u.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),e.dirty()),s.maxSize!==null&&i.data.size>s.maxSize.value&&(g(i,{code:u.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),e.dirty());const n=this._def.valueType;function a(l){const c=new Set;for(const h of l){if(h.status==="aborted")return k;h.status==="dirty"&&e.dirty(),c.add(h.value)}return{status:e.value,value:c}}const o=[...i.data.values()].map((l,c)=>n._parse(new K(i,l,i.path,c)));return i.common.async?Promise.all(o).then(l=>a(l)):a(o)}min(t,e){return new Tt({...this._def,minSize:{value:t,message:y.toString(e)}})}max(t,e){return new Tt({...this._def,maxSize:{value:t,message:y.toString(e)}})}size(t,e){return this.min(t,e).max(t,e)}nonempty(t){return this.min(1,t)}}Tt.create=(r,t)=>new Tt({valueType:r,minSize:null,maxSize:null,typeName:x.ZodSet,...T(t)});class Rt extends w{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:e}=this._processInputParams(t);if(e.parsedType!==m.function)return g(e,{code:u.invalid_type,expected:m.function,received:e.parsedType}),k;function i(o,l){return he({data:o,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,ce(),Pt].filter(c=>!!c),issueData:{code:u.invalid_arguments,argumentsError:l}})}function s(o,l){return he({data:o,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,ce(),Pt].filter(c=>!!c),issueData:{code:u.invalid_return_type,returnTypeError:l}})}const n={errorMap:e.common.contextualErrorMap},a=e.data;if(this._def.returns instanceof Lt){const o=this;return z(async function(...l){const c=new V([]),h=await o._def.args.parseAsync(l,n).catch(v=>{throw c.addIssue(i(l,v)),c}),p=await Reflect.apply(a,this,h);return await o._def.returns._def.type.parseAsync(p,n).catch(v=>{throw c.addIssue(s(p,v)),c})})}else{const o=this;return z(function(...l){const c=o._def.args.safeParse(l,n);if(!c.success)throw new V([i(l,c.error)]);const h=Reflect.apply(a,this,c.data),p=o._def.returns.safeParse(h,n);if(!p.success)throw new V([s(h,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new Rt({...this._def,args:q.create(t).rest(xt.create())})}returns(t){return new Rt({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,e,i){return new Rt({args:t||q.create([]).rest(xt.create()),returns:e||xt.create(),typeName:x.ZodFunction,...T(i)})}}class Yt extends w{get schema(){return this._def.getter()}_parse(t){const{ctx:e}=this._processInputParams(t);return this._def.getter()._parse({data:e.data,path:e.path,parent:e})}}Yt.create=(r,t)=>new Yt({getter:r,typeName:x.ZodLazy,...T(t)});class Xt extends w{_parse(t){if(t.data!==this._def.value){const e=this._getOrReturnCtx(t);return g(e,{received:e.data,code:u.invalid_literal,expected:this._def.value}),k}return{status:"valid",value:t.data}}get value(){return this._def.value}}Xt.create=(r,t)=>new Xt({value:r,typeName:x.ZodLiteral,...T(t)});function Me(r,t){return new dt({values:r,typeName:x.ZodEnum,...T(t)})}class dt extends w{constructor(){super(...arguments),At.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const e=this._getOrReturnCtx(t),i=this._def.values;return g(e,{expected:S.joinValues(i),received:e.parsedType,code:u.invalid_type}),k}if(Gt(this,At)||Oe(this,At,new Set(this._def.values)),!Gt(this,At).has(t.data)){const e=this._getOrReturnCtx(t),i=this._def.values;return g(e,{received:e.data,code:u.invalid_enum_value,options:i}),k}return z(t.data)}get options(){return this._def.values}get enum(){const t={};for(const e of this._def.values)t[e]=e;return t}get Values(){const t={};for(const e of this._def.values)t[e]=e;return t}get Enum(){const t={};for(const e of this._def.values)t[e]=e;return t}extract(t,e=this._def){return dt.create(t,{...this._def,...e})}exclude(t,e=this._def){return dt.create(this.options.filter(i=>!t.includes(i)),{...this._def,...e})}}At=new WeakMap,dt.create=Me;class jt extends w{constructor(){super(...arguments),Ot.set(this,void 0)}_parse(t){const e=S.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(t);if(i.parsedType!==m.string&&i.parsedType!==m.number){const s=S.objectValues(e);return g(i,{expected:S.joinValues(s),received:i.parsedType,code:u.invalid_type}),k}if(Gt(this,Ot)||Oe(this,Ot,new Set(S.getValidEnumValues(this._def.values))),!Gt(this,Ot).has(t.data)){const s=S.objectValues(e);return g(i,{received:i.data,code:u.invalid_enum_value,options:s}),k}return z(t.data)}get enum(){return this._def.values}}Ot=new WeakMap,jt.create=(r,t)=>new jt({values:r,typeName:x.ZodNativeEnum,...T(t)});class Lt extends w{unwrap(){return this._def.type}_parse(t){const{ctx:e}=this._processInputParams(t);if(e.parsedType!==m.promise&&e.common.async===!1)return g(e,{code:u.invalid_type,expected:m.promise,received:e.parsedType}),k;const i=e.parsedType===m.promise?e.data:Promise.resolve(e.data);return z(i.then(s=>this._def.type.parseAsync(s,{path:e.path,errorMap:e.common.contextualErrorMap})))}}Lt.create=(r,t)=>new Lt({type:r,typeName:x.ZodPromise,...T(t)});class Q extends w{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===x.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:e,ctx:i}=this._processInputParams(t),s=this._def.effect||null,n={addIssue:a=>{g(i,a),a.fatal?e.abort():e.dirty()},get path(){return i.path}};if(n.addIssue=n.addIssue.bind(n),s.type==="preprocess"){const a=s.transform(i.data,n);if(i.common.async)return Promise.resolve(a).then(async o=>{if(e.value==="aborted")return k;const l=await this._def.schema._parseAsync({data:o,path:i.path,parent:i});return l.status==="aborted"?k:l.status==="dirty"||e.value==="dirty"?Et(l.value):l});{if(e.value==="aborted")return k;const o=this._def.schema._parseSync({data:a,path:i.path,parent:i});return o.status==="aborted"?k:o.status==="dirty"||e.value==="dirty"?Et(o.value):o}}if(s.type==="refinement"){const a=o=>{const l=s.refinement(o,n);if(i.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(i.common.async===!1){const o=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return o.status==="aborted"?k:(o.status==="dirty"&&e.dirty(),a(o.value),{status:e.value,value:o.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(o=>o.status==="aborted"?k:(o.status==="dirty"&&e.dirty(),a(o.value).then(()=>({status:e.value,value:o.value}))))}if(s.type==="transform")if(i.common.async===!1){const a=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!yt(a))return a;const o=s.transform(a.value,n);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:e.value,value:o}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(a=>yt(a)?Promise.resolve(s.transform(a.value,n)).then(o=>({status:e.value,value:o})):a);S.assertNever(s)}}Q.create=(r,t,e)=>new Q({schema:r,typeName:x.ZodEffects,effect:t,...T(e)}),Q.createWithPreprocess=(r,t,e)=>new Q({schema:t,effect:{type:"preprocess",transform:r},typeName:x.ZodEffects,...T(e)});class J extends w{_parse(t){return this._getType(t)===m.undefined?z(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}J.create=(r,t)=>new J({innerType:r,typeName:x.ZodOptional,...T(t)});class ut extends w{_parse(t){return this._getType(t)===m.null?z(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}ut.create=(r,t)=>new ut({innerType:r,typeName:x.ZodNullable,...T(t)});class qt extends w{_parse(t){const{ctx:e}=this._processInputParams(t);let i=e.data;return e.parsedType===m.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:e.path,parent:e})}removeDefault(){return this._def.innerType}}qt.create=(r,t)=>new qt({innerType:r,typeName:x.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...T(t)});class Qt extends w{_parse(t){const{ctx:e}=this._processInputParams(t),i={...e,common:{...e.common,issues:[]}},s=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return Vt(s)?s.then(n=>({status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new V(i.common.issues)},input:i.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new V(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}Qt.create=(r,t)=>new Qt({innerType:r,typeName:x.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...T(t)});class Ce extends w{_parse(t){if(this._getType(t)!==m.nan){const i=this._getOrReturnCtx(t);return g(i,{code:u.invalid_type,expected:m.nan,received:i.parsedType}),k}return{status:"valid",value:t.data}}}Ce.create=r=>new Ce({typeName:x.ZodNaN,...T(r)});class He extends w{_parse(t){const{ctx:e}=this._processInputParams(t),i=e.data;return this._def.type._parse({data:i,path:e.path,parent:e})}unwrap(){return this._def.type}}class Jt extends w{_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.common.async)return(async()=>{const n=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return n.status==="aborted"?k:n.status==="dirty"?(e.dirty(),Et(n.value)):this._def.out._parseAsync({data:n.value,path:i.path,parent:i})})();{const s=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return s.status==="aborted"?k:s.status==="dirty"?(e.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:i.path,parent:i})}}static create(t,e){return new Jt({in:t,out:e,typeName:x.ZodPipeline})}}class te extends w{_parse(t){const e=this._def.innerType._parse(t),i=s=>(yt(s)&&(s.value=Object.freeze(s.value)),s);return Vt(e)?e.then(s=>i(s)):i(e)}unwrap(){return this._def.innerType}}te.create=(r,t)=>new te({innerType:r,typeName:x.ZodReadonly,...T(t)}),A.lazycreate;var x;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(x||(x={}));const M=X.create,C=vt.create;Ce.create,Ct.create,ue.create,Dt.create,pe.create,Ut.create,Zt.create,fe.create,xt.create,at.create,ge.create,$.create;const _=A.create;A.strictCreate;const Qi=Wt.create;me.create,Kt.create,q.create,$t.create,ve.create,Tt.create,Rt.create,Yt.create;const pt=Xt.create,ot=dt.create;jt.create,Lt.create,Q.create,J.create,ut.create,Q.createWithPreprocess,Jt.create;const Ji=ot(["linear","bezier","constant"]),ts=ot(["ease","easeIn","easeOut","easeInOut","easeInQuad","easeInCubic","easeInQuart","easeInQuint","easeInSine","easeInExpo","easeInCirc","easeInBack","easeOutQuad","easeOutCubic","easeOutQuart","easeOutQuint","easeOutSine","easeOutExpo","easeOutCirc","easeOutBack","easeInOutQuad","easeInOutCubic","easeInOutQuart","easeInOutQuint","easeInOutSine","easeInOutExpo","easeInOutCirc","easeInOutBack"]),ft=_({from:C(),to:C(),start:C().min(0),length:C().positive(),interpolation:Ji.optional(),easing:ts.optional()}),es=M().url("Invalid audio url format."),is=ft.extend({from:C().min(0).max(1),to:C().min(0).max(1)}).array().or(C().min(0).max(1)),ze=_({type:pt("audio"),src:es,trim:C().optional(),volume:is.optional()}),ss=ot(["top","topRight","right","bottomRight","bottom","bottomLeft","left","topLeft","center"]),Be=_({type:pt("html"),html:M(),css:M(),width:C().positive().optional(),height:C().positive().optional(),position:ss.optional()}),ns=M().url("Invalid image url format."),rs=_({top:C().min(0).optional(),right:C().min(0).optional(),bottom:C().min(0).optional(),left:C().min(0).optional()}),Fe=_({type:pt("image"),src:ns,crop:rs.optional()}),as=M().url("Invalid luma url format."),Ne=_({type:pt("luma"),src:as}),Ve=M().regex(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})|transparent$/,"Invalid color format."),Ge=_({width:C().positive(),height:C().positive()}),Ue=_({radius:C().positive()}),Ze=_({length:C().positive(),thickness:C().positive()}),os=_({color:Ve,opacity:C().min(0).max(1)}),ls=_({color:Ve,width:C().positive()}),We=_({type:pt("shape"),width:C().positive().optional(),height:C().positive().optional(),shape:ot(["rectangle","circle","line"]),fill:os.optional(),stroke:ls.optional(),rectangle:Ge.optional(),circle:Ue.optional(),line:Ze.optional()}).refine(r=>r.shape==="rectangle"?Ge.safeParse(r.rectangle):r.shape==="circle"?Ue.safeParse(r.circle):r.shape==="line"?Ze.safeParse(r.line):!1),xe=M().regex(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})|transparent$/,"Invalid color format."),cs=_({color:xe.optional(),family:M().optional(),size:C().positive().optional(),weight:C().optional(),lineHeight:C().optional()}),hs=_({horizontal:ot(["left","center","right"]).optional(),vertical:ot(["top","center","bottom"]).optional()}),ds=_({color:xe,opacity:C().min(0).max(1)}),us=_({width:C().positive(),color:xe}),Ke=_({type:pt("text"),text:M(),width:C().positive().optional(),height:C().positive().optional(),font:cs.optional(),alignment:hs.optional(),background:ds.optional(),stroke:us.optional()}),ps=M().url("Invalid video url format."),fs=_({top:C().min(0).optional(),right:C().min(0).optional(),bottom:C().min(0).optional(),left:C().min(0).optional()}),gs=ft.extend({from:C().min(0).max(1),to:C().min(0).max(1)}).array().or(C().min(0).max(1)),$e=_({type:pt("video"),src:ps,trim:C().optional(),crop:fs.optional(),volume:gs.optional()}),ms=Qi([Ke,We,Be,Fe,$e,Ne,ze]).refine(r=>r.type==="text"?Ke.safeParse(r):r.type==="shape"?We.safeParse(r):r.type==="html"?Be.safeParse(r):r.type==="image"?Fe.safeParse(r):r.type==="video"?$e.safeParse(r):r.type==="luma"?Ne.safeParse(r):r.type==="audio"?ze.safeParse(r):!1),ys=ot(["topLeft","top","topRight","left","center","right","bottomLeft","bottom","bottomRight"]),vs=ot(["crop","cover","contain","none"]),wt=C().min(-10).max(10).default(0),Cs=ft.extend({from:wt,to:wt}).array().or(wt),xs=ft.extend({from:wt,to:wt}).array().or(wt),ks=_({x:Cs.default(0),y:xs.default(0)}),Ts=ft.extend({from:C().min(0).max(1),to:C().min(0).max(1)}).array().or(C().min(0).max(1)),ws=ft.extend({from:C().min(0),to:C().min(0)}).array().or(C().min(0)),bs=_({angle:ft.extend({from:C(),to:C()}).array().or(C())}),Ss=M(),Ye=M(),Is=_({in:Ye.optional(),out:Ye.optional()}),_s=_({rotate:bs.default({angle:0})}),Xe=_({asset:ms,start:C().min(0),length:C().positive(),position:ys.default("center").optional(),fit:vs.default("crop").optional(),offset:ks.default({x:0,y:0}).optional(),opacity:Ts.default(1).optional(),scale:ws.default(1).optional(),transform:_s.default({rotate:{angle:0}}).optional(),effect:Ss.optional(),transition:Is.optional()});class Ps{constructor(t,e){this.trackIdx=t,this.clip=e}name="addClip";addedPlayer;async execute(t){if(!t)return;const e=Xe.parse(this.clip),i=t.createPlayerFromAssetType(e);i.layer=this.trackIdx+1,await t.addPlayer(this.trackIdx,i),t.updateDuration(),this.addedPlayer=i}async undo(t){!t||!this.addedPlayer||(t.queueDisposeClip(this.addedPlayer),t.updateDuration())}}class je{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(s=>{if(s.layer>=this.trackIdx){const n=1e5-s.layer*100,a=t.getContainer().getChildByLabel(`shotstack-track-${n}`,!1);a&&a.removeChild(s.getContainer()),s.layer+=1;const o=1e5-s.layer*100;let l=t.getContainer().getChildByLabel(`shotstack-track-${o}`,!1);l||(l=new d.Container({label:`shotstack-track-${o}`,zIndex:o}),t.getContainer().addChild(l)),l.addChild(s.getContainer())}}),t.updateDuration(),t.emitEvent("track:added",{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(s=>{s.layer>this.trackIdx&&(s.layer-=1)}),t.updateDuration()}}class Es{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("selection:cleared",{})}undo(t){if(this.previousSelection){const e=t.getClipAt(this.previousSelection.trackIndex,this.previousSelection.clipIndex);e&&(t.setSelectedClip(e),t.emitEvent("clip:selected",{clip:e.clipConfiguration,trackIndex:this.previousSelection.trackIndex,clipIndex:this.previousSelection.clipIndex}))}}}class As{constructor(t,e){this.trackIdx=t,this.clipIdx=e}name="deleteClip";deletedClip;execute(t){if(!t)return;const i=t.getClips().filter(s=>s.layer===this.trackIdx+1);this.deletedClip=i[this.clipIdx],this.deletedClip&&(t.queueDisposeClip(this.deletedClip),t.updateDuration())}undo(t){!t||!this.deletedClip||t.undeleteClip(this.trackIdx,this.deletedClip)}}class Os{constructor(t){this.trackIdx=t}name="deleteTrack";deletedClips=[];execute(t){if(!t)return;const e=t.getClips(),i=t.getTracks();this.deletedClips=e.filter(a=>a.layer===this.trackIdx+1).map(a=>({config:structuredClone(a.clipConfiguration)})),e.forEach((a,o)=>{a.layer===this.trackIdx+1&&(e[o].shouldDispose=!0)}),t.disposeClips(),i.splice(this.trackIdx,1);const s=t.getClips(),n=t.getContainer();s.forEach((a,o)=>{if(a.layer>this.trackIdx+1){n.getChildByLabel(`shotstack-track-${1e5-a.layer*100}`,!1)?.removeChild(a.getContainer()),s[o].layer-=1;const c=1e5-s[o].layer*100;let h=n.getChildByLabel(`shotstack-track-${c}`,!1);h||(h=new d.Container({label:`shotstack-track-${c}`,zIndex:c}),n.addChild(h)),h.addChild(s[o].getContainer())}}),t.updateDuration()}async undo(t){if(!t||this.deletedClips.length===0)return;const e=t.getTracks(),i=t.getClips();e.splice(this.trackIdx,0,[]),i.forEach((s,n)=>{s.layer>=this.trackIdx+1&&(i[n].layer+=1)});for(const{config:s}of this.deletedClips){const n=t.createPlayerFromAssetType(s);n.layer=this.trackIdx+1,await t.addPlayer(this.trackIdx,n)}t.updateDuration()}}class Ds{constructor(t,e){this.trackIndex=t,this.clipIndex=e}name="SelectClip";previousSelection=null;execute(t){const e=t.getSelectedClip();if(e){const s=t.findClipIndices(e);s&&(this.previousSelection=s)}const i=t.getClipAt(this.trackIndex,this.clipIndex);i&&(t.setSelectedClip(i),t.emitEvent("clip:selected",{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("clip:selected",{clip:e.clipConfiguration,trackIndex:this.previousSelection.trackIndex,clipIndex:this.previousSelection.clipIndex}))}else t.emitEvent("selection:cleared",{})}}class Rs{constructor(t,e,i){this.clip=t,this.initialClipConfig=e,this.finalClipConfig=i,this.storedInitialConfig=e?structuredClone(e):null,this.storedFinalConfig=i?structuredClone(i):structuredClone(this.clip.clipConfiguration)}name="setUpdatedClip";storedInitialConfig;storedFinalConfig;execute(t){if(!t)return;this.storedFinalConfig&&t.restoreClipConfiguration(this.clip,this.storedFinalConfig),t.setUpdatedClip(this.clip);const e=this.clip.layer-1,n=t.getClips().filter(a=>a.layer===this.clip.layer).indexOf(this.clip);t.emitEvent("clip:updated",{previous:{clip:this.storedInitialConfig||this.initialClipConfig,trackIndex:e,clipIndex:n},current:{clip:this.storedFinalConfig||this.clip.clipConfiguration,trackIndex:e,clipIndex:n}})}undo(t){if(!t||!this.storedInitialConfig)return;t.restoreClipConfiguration(this.clip,this.storedInitialConfig),t.setUpdatedClip(this.clip);const e=this.clip.layer-1,n=t.getClips().filter(a=>a.layer===this.clip.layer).indexOf(this.clip);t.emitEvent("clip:updated",{previous:{clip:this.storedFinalConfig,trackIndex:e,clipIndex:n},current:{clip:this.storedInitialConfig,trackIndex:e,clipIndex:n}})}}class Ls{constructor(t,e,i){this.trackIndex=t,this.clipIndex=e,this.splitTime=i}name="SplitClip";originalClipConfig=null;rightClipPlayer=null;splitSuccessful=!1;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,s=i.start||0,n=i.length,a=.1,o=this.splitTime-s;if(o<=a||o>=n-a)throw new Error("Cannot split clip: split point too close to clip boundaries");this.originalClipConfig={...i};const l={...i,length:o},c={...i,start:s+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 v=i.asset.trim||0;l.asset&&(l.asset.type==="video"||l.asset.type==="audio")&&(l.asset.trim=v),c.asset&&(c.asset.type==="video"||c.asset.type==="audio")&&(c.asset.trim=v+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;const h=t.getTrack(this.trackIndex);if(!h)throw new Error("Invalid track index");h.splice(this.clipIndex+1,0,this.rightClipPlayer);const p=t.getClips(),f=p.indexOf(e);f!==-1&&p.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("timeline:updated",{current:t.getEditState()})}).catch(v=>{console.error("Failed to load split clip:",v)})}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 a=i.indexOf(this.rightClipPlayer);a!==-1&&i.splice(a,1)}const s=t.getClips(),n=s.indexOf(this.rightClipPlayer);n!==-1&&s.splice(n,1),t.queueDisposeClip(this.rightClipPlayer),this.rightClipPlayer=null}t.updateDuration(),t.emitEvent("timeline:updated",{current:t.getEditState()})}}}class Ms{constructor(t,e,i){this.clip=t,this.newText=e,this.initialConfig=i;const{asset:s}=this.clip.clipConfiguration;this.previousText=s&&"text"in s?s.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,a=t.getClips().filter(o=>o.layer===this.clip.layer).indexOf(this.clip);t.emitEvent("clip:updated",{previous:{clip:this.initialConfig,trackIndex:i,clipIndex:a},current:{clip:this.clip.clipConfiguration,trackIndex:i,clipIndex:a}})}}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,a=t.getClips().filter(o=>o.layer===this.clip.layer).indexOf(this.clip);t.emitEvent("clip:updated",{previous:{clip:this.clip.clipConfiguration,trackIndex:i,clipIndex:a},current:{clip:this.initialConfig,trackIndex:i,clipIndex:a}})}}}class Mt{events;constructor(){this.events={}}on(t,e){this.events[t]||(this.events[t]=new Set),this.events[t].add(e)}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])for(const i of this.events[t])i(e)}}class Hs extends Mt{registry;constructor(){super(),this.registry={}}}class ee{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 Hs;async load(t,e){this.updateAssetLoadMetadata(t,"pending",0);try{if(await this.shouldUseSafariVideoLoader(e))return await this.loadVideoForSafari(t,e);const i=await d.Assets.load(e,s=>{this.updateAssetLoadMetadata(t,"loading",s)});return this.updateAssetLoadMetadata(t,"success",1),i}catch{return this.updateAssetLoadMetadata(t,"failed",1),null}}getProgress(){const t=Object.keys(this.loadTracker.registry);return t.length===0?0:t.reduce((i,s)=>i+this.loadTracker.registry[s].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 ee.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(".")),s=ee.VIDEO_MIME[i];return s?document.createElement("video").canPlayType(s)!=="":!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),s=typeof e=="object"?e.data??{}:{},n=await new Promise((a,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 d.VideoSource({resource:l,autoPlay:s.autoPlay??!1,...s});a(new d.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 s={...this.loadTracker.registry};this.loadTracker.emit("onAssetLoadInfoUpdated",{registry:s})}}class ie{static Name="FontLoadParser";name;extension;validFontExtensions;woff2Decompressor;constructor(){this.name=ie.Name,this.extension={type:[d.ExtensionType.LoadParser],priority:d.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 s=t.split("?")[0]?.split(".").pop()?.toLowerCase()??"",n=await fetch(t).then(f=>f.arrayBuffer());if(s!=="woff2"){const f=Ie.parse(new Uint8Array(n).buffer),v=f.names.fontFamily.en||f.names.fontFamily[Object.keys(f.names.fontFamily)[0]],I=new FontFace(v,`url(${t})`);return await I.load(),document.fonts.add(I),I}if(await this.loadWoff2Decompressor(),!this.woff2Decompressor)throw new Error("Cannot initialize Woff2 decompressor.");const a=this.woff2Decompressor.decompress(n),o=Ie.parse(new Uint8Array(a).buffer),l=o.names.fontFamily.en||o.names.fontFamily[Object.keys(o.names.fontFamily)[0]],c=new Blob([a],{type:"font/ttf"}),h=URL.createObjectURL(c),p=new FontFace(l,`url(${h})`);return await p.load(),document.fonts.add(p),p}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)}}const zs=_({clips:Xe.array()}),Bs=M().url("Invalid image url format."),Fs=_({src:Bs}),Ns=_({background:M().optional(),fonts:Fs.array().optional(),tracks:zs.array()}),Vs=_({size:_({width:C().positive(),height:C().positive()}),fps:C().positive().optional(),format:M()}),Gs=_({timeline:Ns,output:Vs});class bt extends nt{static ZIndexPadding=100;assetLoader;events;edit;tracks;clipsToDispose;clips;commandHistory=[];commandIndex=-1;playbackTime;size;backgroundColor;totalDuration;isPlaying;selectedClip;updatedClip;viewportMask;constructor(t,e="#ffffff"){super(),this.assetLoader=new ee,this.edit=null,this.tracks=[],this.clipsToDispose=[],this.clips=[],this.events=new Mt,this.size=t,this.playbackTime=0,this.totalDuration=0,this.isPlaying=!1,this.selectedClip=null,this.updatedClip=null,this.backgroundColor=e,this.setupIntentListeners()}async load(){const t=new d.Graphics;t.fillStyle={color:this.backgroundColor},t.rect(0,0,this.size.width,this.size.height),t.fill(),this.getContainer().addChild(t),this.viewportMask=new d.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})}update(t,e){for(const i of this.clips)i.shouldDispose&&this.queueDisposeClip(i),i.update(t,e);this.disposeClips(),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.viewportMask){try{this.getContainer().setMask(null)}catch{}this.viewportMask.destroy(),this.viewportMask=void 0}}play(){this.isPlaying=!0,this.events.emit("playback:play",{})}pause(){this.isPlaying=!1,this.events.emit("playback:pause",{})}seek(t){this.playbackTime=Math.max(0,Math.min(t,this.totalDuration)),this.pause()}stop(){this.seek(0)}async loadEdit(t){this.clearClips(),this.edit=Gs.parse(t),this.backgroundColor=this.edit.timeline.background||"#000000",await Promise.all((this.edit.timeline.fonts??[]).map(async e=>{const i=e.src,s={src:i,loadParser:ie.Name};return this.assetLoader.load(i,s)}));for(const[e,i]of this.edit.timeline.tracks.entries())for(const s of i.clips){const n=this.createPlayerFromAssetType(s);n.layer=e+1,await this.addPlayer(e,n)}this.updateTotalDuration()}getEdit(){const t=this.tracks.map((e,i)=>({clips:e.filter(n=>n&&!this.clipsToDispose.includes(n)).map(n=>n.clipConfiguration)}));return{timeline:{background:this.backgroundColor,tracks:t,fonts:this.edit?.timeline.fonts||[]},output:this.edit?.output||{size:this.size,format:"mp4"}}}addClip(t,e){const i=new Ps(t,e);this.executeCommand(i)}getClip(t,e){const i=this.clips.filter(s=>s.layer===t+1);return e<0||e>=i.length?null:i[e].clipConfiguration}getPlayerClip(t,e){const i=this.clips.filter(s=>s.layer===t+1);return e<0||e>=i.length?null:i[e]}deleteClip(t,e){const i=new As(t,e);this.executeCommand(i)}splitClip(t,e,i){const s=new Ls(t,e,i);this.executeCommand(s)}addTrack(t,e){const i=new je(t);this.executeCommand(i),e?.clips?.forEach(s=>this.addClip(t,s))}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 Os(t);this.executeCommand(e)}getTotalDuration(){return this.totalDuration}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("edit:undo",{command: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("edit:redo",{command:t.name})}}setUpdatedClip(t,e=null,i=null){const s=new Rs(t,e,i);this.executeCommand(s)}updateTextContent(t,e,i){const s=new Ms(t,e,i);this.executeCommand(s)}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}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(),undeleteClip:(t,e)=>{this.clips.push(e),this.updateTotalDuration()},setUpdatedClip:t=>{this.updatedClip=t},restoreClipConfiguration:(t,e)=>{Object.assign(t.clipConfiguration,structuredClone(e)),t.reconfigureAfterRestore(),t.draw()},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.getEdit()}}queueDisposeClip(t){this.clipsToDispose.push(t)}disposeClips(){if(this.clipsToDispose.length!==0){for(const t of this.clipsToDispose)this.disposeClip(t);this.clips=this.clips.filter(t=>!this.clipsToDispose.includes(t)),this.clipsToDispose=[],this.updateTotalDuration()}}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 d.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),t.dispose()}unloadClipAssets(t){const{asset:e}=t.clipConfiguration;if(e&&"src"in e&&typeof e.src=="string")try{d.Assets.unload(e.src)}catch(i){console.warn(`Failed to unload asset: ${e.src}`,i)}}clearClips(){for(const t of this.clips)this.disposeClip(t);this.clips=[],this.clipsToDispose=[],this.updateTotalDuration()}updateTotalDuration(){let t=0;for(const i of this.tracks)for(const s of i)t=Math.max(t,s.getEnd());const e=this.totalDuration;this.totalDuration=t,e!==this.totalDuration&&this.events.emit("duration:changed",{duration:this.totalDuration})}addPlayerToContainer(t,e){const i=1e5-(t+1)*bt.ZIndexPadding,s=`shotstack-track-${i}`;let n=this.getContainer().getChildByLabel(s,!1);n||(n=new d.Container({label:s,zIndex:i}),this.getContainer().addChild(n)),n.addChild(e.getContainer())}movePlayerToTrackContainer(t,e,i){if(e===i)return;const s=1e5-(e+1)*bt.ZIndexPadding,n=1e5-(i+1)*bt.ZIndexPadding,a=`shotstack-track-${s}`,o=`shotstack-track-${n}`,l=this.getContainer().getChildByLabel(a,!1);let c=this.getContainer().getChildByLabel(o,!1);c||(c=new d.Container({label:o,zIndex:n}),this.getContainer().addChild(c)),l&&l.removeChild(t.getContainer()),c.addChild(t.getContainer())}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 _i(this,t);break}case"shape":{e=new Ii(this,t);break}case"html":{e=new bi(this,t);break}case"image":{e=new Si(this,t);break}case"video":{e=new Pi(this,t);break}case"audio":{e=new oe(this,t);break}case"luma":{e=new _e(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([]);this.tracks[t].push(e),this.clips.push(e);const i=1e5-(t+1)*bt.ZIndexPadding,s=`shotstack-track-${i}`;let n=this.getContainer().getChildByLabel(s,!1);n||(n=new d.Container({label:s,zIndex:i}),this.getContainer().addChild(n)),n.addChild(e.getContainer());const a=e instanceof _e;await e.load(),a&&n.setMask({mask:e.getMask(),inverse:!0}),this.updateTotalDuration()}selectClip(t,e){const i=new Ds(t,e);this.executeCommand(i)}clearSelection(){const t=new Es;this.executeCommand(t)}isClipSelected(t,e){if(!this.selectedClip)return!1;const i=this.selectedClip.layer-1,s=this.tracks[i].indexOf(this.selectedClip);return t===i&&e===s}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}}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.selectedClip===t}setupIntentListeners(){this.events.on("timeline:clip:clicked",t=>{t.player?this.selectPlayer(t.player):this.selectClip(t.trackIndex,t.clipIndex)}),this.events.on("timeline:background:clicked",()=>{this.clearSelection()}),this.events.on("canvas:clip:clicked",t=>{this.selectPlayer(t.player)}),this.events.on("canvas:background:clicked",()=>{this.clearSelection()})}}class Ht extends nt{static Width=250;static Height=100;fps;playbackTime;playbackDuration;isPlaying;background;text;constructor(){super(),this.background=null,this.text=null,this.fps=0,this.playbackTime=0,this.playbackDuration=0,this.isPlaying=!1}async load(){const t=new d.Graphics;t.fillStyle={color:"#424242",alpha:.5},t.rect(0,0,Ht.Width,Ht.Height),t.fill(),this.getContainer().addChild(t),this.background=t;const e=new d.Text;e.text="",e.style={fontFamily:"monospace",fontSize:14,fill:"#ffffff",wordWrap:!0,wordWrapWidth:Ht.Width},this.getContainer().addChild(e),this.text=e}update(t,e){if(!this.text)return;const i=this.getMemoryInfo(),s=[`FPS: ${this.fps}`,`Playback: ${(this.playbackTime/1e3).toFixed(2)}/${(this.playbackDuration/1e3).toFixed(2)}`,`Playing: ${this.isPlaying}`,`Total Heap Size: ${i.totalHeapSize?`${this.bytesToMegabytes(i.totalHeapSize)}MB`:"N/A"}`,`Used Heap Size: ${i.usedHeapSize?`${this.bytesToMegabytes(i.usedHeapSize)}MB`:"N/A"}`,`Heap Size Limit: ${i.heapSizeLimit?`${this.bytesToMegabytes(i.heapSizeLimit)}MB`:"N/A"}`];this.text.text=s.join(`
185
- `)}draw(){}dispose(){this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null}getMemoryInfo(){const t={};return"memory"in performance&&(t.totalHeapSize=performance.memory.totalJSHeapSize,t.usedHeapSize=performance.memory.usedJSHeapSize,t.heapSizeLimit=performance.memory.jsHeapSizeLimit),t}bytesToMegabytes(t){return Math.round(t/1024/1024)}}class gt{static CanvasSelector="[data-shotstack-studio]";static extensionsRegistered=!1;size;application;edit;inspector;container;background;timeline;minZoom=.1;maxZoom=4;currentZoom=.8;constructor(t,e){this.size=t,this.application=new d.Application,this.edit=e,this.inspector=new Ht}async load(){const t=document.querySelector(gt.CanvasSelector);if(!t)throw new Error(`Shotstack canvas root element '${gt.CanvasSelector}' not found.`);this.registerExtensions(),this.container=new d.Container,this.background=new d.Graphics,this.background.fillStyle={color:"#424242"},this.background.rect(0,0,this.size.width,this.size.height),this.background.fill(),await this.configureApplication(),this.configureStage(),this.setupTouchHandling(t),this.edit.getContainer().scale=this.currentZoom,t.appendChild(this.application.canvas)}setupTouchHandling(t){const e=this.edit.getContainer();t.addEventListener("wheel",i=>{if(i.preventDefault(),i.stopPropagation(),i.ctrlKey){const s=Math.exp(-i.deltaY/100),n=this.currentZoom*s,a=this.currentZoom;this.currentZoom=Math.min(Math.max(n,this.minZoom),this.maxZoom);const o={x:this.application.canvas.width/2,y:this.application.canvas.height/2},l={x:e.position.x-o.x,y:e.position.y-o.y},c=this.currentZoom/a;e.position.x=o.x+l.x*c,e.position.y=o.y+l.y*c,e.scale.x=this.currentZoom,e.scale.y=this.currentZoom}},{passive:!1,capture:!0})}centerEdit(){if(!this.edit)return;const t=this.edit.getContainer();t.position={x:this.application.canvas.width/2-this.edit.size.width*this.currentZoom/2,y:this.application.canvas.height/2-this.edit.size.height*this.currentZoom/2}}zoomToFit(){if(!this.edit)return;const t=this.application.canvas.width/this.edit.size.width,e=this.application.canvas.height/this.edit.size.height,i=Math.min(t,e);this.currentZoom=Math.min(Math.max(i,this.minZoom),this.maxZoom);const s=this.edit.getContainer();s.scale.x=this.currentZoom,s.scale.y=this.currentZoom,this.centerEdit()}setZoom(t){this.currentZoom=Math.min(Math.max(t,this.minZoom),this.maxZoom);const e=this.edit.getContainer();e.scale.x=this.currentZoom,e.scale.y=this.currentZoom}registerTimeline(t){this.timeline=t}registerExtensions(){gt.extensionsRegistered||(d.extensions.add(new Bt),d.extensions.add(new ie),gt.extensionsRegistered=!0)}async configureApplication(){const t={background:"#000000",width:this.size.width,height:this.size.height,antialias:!0};await this.application.init(t),this.application.ticker.add(this.onTick.bind(this)),this.application.ticker.minFPS=60,this.application.ticker.maxFPS=60}onTick(t){this.edit.update(t.deltaTime,t.deltaMS),this.edit.draw(),this.inspector.fps=Math.ceil(t.FPS),this.inspector.playbackTime=this.edit.playbackTime,this.inspector.playbackDuration=this.edit.totalDuration,this.inspector.isPlaying=this.edit.isPlaying,this.inspector.update(t.deltaTime,t.deltaMS),this.inspector.draw(),this.timeline&&(this.timeline.update(t.deltaTime,t.deltaMS),this.timeline.draw())}configureStage(){if(!this.container||!this.background)throw new Error("Shotstack canvas container not set up.");this.container.addChild(this.background),this.container.addChild(this.edit.getContainer()),this.container.addChild(this.inspector.getContainer()),this.application.stage.addChild(this.container),this.application.stage.eventMode="static",this.application.stage.hitArea=new d.Rectangle(0,0,this.size.width,this.size.height),this.background.eventMode="static",this.background.on("pointerdown",this.onBackgroundClick.bind(this)),this.application.stage.on("click",this.onClick.bind(this)),this.edit.getContainer().position={x:this.application.canvas.width/2-this.edit.size.width*this.currentZoom/2,y:this.application.canvas.height/2-this.edit.size.height*this.currentZoom/2}}onClick(){this.edit.pause()}onBackgroundClick(t){t.target===this.background&&this.edit.events.emit("canvas:background:clicked",{})}dispose(){const t=document.querySelector(gt.CanvasSelector);t&&t.contains(this.application.canvas)&&t.removeChild(this.application.canvas),this.application.ticker.remove(this.onTick,this),this.application.stage.off("click",this.onClick,this),this.background?.off("pointerdown",this.onBackgroundClick,this),this.background?.destroy(),this.container?.destroy(),this.inspector.dispose(),this.application.destroy(!0,{children:!0,texture:!0})}}class Us{edit;seekDistance=50;seekDistanceLarge=500;frameTime=16.67;constructor(t){this.edit=t}async load(){document.addEventListener("keydown",this.handleKeyDown),document.addEventListener("keyup",this.handleKeyUp)}dispose(){document.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("keyup",this.handleKeyUp)}handleKeyDown=t=>{if(!(t.target instanceof HTMLInputElement||t.target instanceof HTMLTextAreaElement))switch(t.code){case"Space":{this.edit.isPlaying?this.edit.pause():this.edit.play();break}case"ArrowLeft":{if(t.metaKey)this.edit.seek(0);else{const e=t.shiftKey?this.seekDistanceLarge:this.seekDistance;this.edit.seek(this.edit.playbackTime-e)}break}case"ArrowRight":{if(t.metaKey)this.edit.seek(this.edit.getTotalDuration());else{const e=t.shiftKey?this.seekDistanceLarge:this.seekDistance;this.edit.seek(this.edit.playbackTime+e)}break}case"KeyJ":{this.edit.stop();break}case"KeyK":{this.edit.pause();break}case"KeyL":{this.edit.play();break}case"Comma":{this.edit.seek(this.edit.playbackTime-this.frameTime);break}case"Period":{this.edit.seek(this.edit.playbackTime+this.frameTime);break}case"KeyZ":{(t.metaKey||t.ctrlKey)&&(t.preventDefault(),t.shiftKey?this.edit.redo():this.edit.undo());break}case"Delete":case"Backspace":{const e=this.edit.getSelectedClipInfo();e&&(t.preventDefault(),this.edit.deleteClip(e.trackIndex,e.clipIndex));break}}};handleKeyUp=t=>{if(!(t.target instanceof HTMLInputElement||t.target instanceof HTMLTextAreaElement))switch(t.code){case"KeyI":console.log(this.edit.getEdit());break}}}class Zs{ffmpeg;isReady=!1;edit;application;constructor(t,e){this.edit=t,this.application=e.application,this.ffmpeg=new di.FFmpeg}async init(){if(!this.isReady)try{await this.ffmpeg.load(),this.isReady=!0}catch(t){throw console.error("FFmpeg initialization failed:",t),t}}async export(t="shotstack-export.mp4",e=30){this.isReady||await this.init();const i=this.edit.isPlaying,s=this.edit.playbackTime;this.edit.pause();const n=this.edit.getContainer(),a=n.visible,{x:o,y:l}=n.position,{x:c,y:h}=n.scale;n.visible=!1;const p=this.createProgressOverlay();try{const f=this.edit.getSize?this.edit.getSize():{width:1920,height:1080},v=Math.ceil(this.edit.totalDuration*e/1e3),I=1e3/e,b=100,O=50,N=50,lt=P=>Math.round(P/v*O);this.updateProgressOverlay(p,0,b);const et=document.createElement("canvas");et.width=f.width,et.height=f.height;const It=et.getContext("2d");if(!It)throw new Error("Could not get 2D context for canvas");const Te=this.findAudioPlayers();this.updateProgressOverlay(p,2,b);const it=[];if(Te.length>0){this.updateProgressOverlay(p,3,b);for(let P=0;P<Te.length;P+=1){const U=await this.processAudioTrack(Te[P],P);U&&it.push(U),this.updateProgressOverlay(p,4+P,b)}}n.position.x=0,n.position.y=0,n.scale.x=1,n.scale.y=1;for(let P=0;P<v;P+=1){this.edit.seek(P*I),this.edit.tick?this.edit.tick(0,0):(this.edit.update?.(0,0),this.edit.draw?.());try{const{extract:U}=this.application.renderer,B=U.canvas(n);It.clearRect(0,0,et.width,et.height),It.drawImage(B,0,0);const st=et.toDataURL("image/png"),re=await(await fetch(st)).arrayBuffer(),Cn=`frame_${P.toString().padStart(6,"0")}.png`;await this.ffmpeg.writeFile(Cn,new Uint8Array(re))}catch(U){console.error(`Error capturing frame ${P}:`,U)}this.updateProgressOverlay(p,lt(P+1),b)}this.updateProgressOverlay(p,O,b);let ct=["-framerate",e.toString(),"-i","frame_%06d.png"];for(const P of it)ct=ct.concat(["-i",P.filename]);if(ct=ct.concat(["-c:v","libx264","-pix_fmt","yuv420p","-crf","23"]),it.length>0){let P="";for(let B=0;B<it.length;B+=1){const st=it[B],li=B+1,re=Math.max(0,st.start);P+=`[${li}:a]aformat=sample_fmts=fltp:sample_rates=44100:channel_layouts=stereo,apad,afade=t=in:st=0:d=0.05,atrim=start=0:end=${st.duration/1e3+.1},adelay=${re}|${re},volume=${st.volume}[a${B}];`}const U=it.length>1?`${it.map((B,st)=>`[a${st}]`).join("")}amix=inputs=${it.length}:duration=longest:dropout_transition=0.5:normalize=0[aout]`:"[a0]aformat=sample_fmts=fltp:sample_rates=44100:channel_layouts=stereo[aout]";P+=U,ct=ct.concat(["-filter_complex",P,"-map","0:v","-map","[aout]","-c:a","aac","-b:a","192k","-shortest"])}const we="output.mp4";ct.push(we);let ri=0;const ai=({message:P})=>{const U=P.includes("frame=")&&P.includes("fps=")?P.match(/frame=\s*(\d+)/):null;if(U?.[1]){const B=parseInt(U[1],10);if(!Number.isNaN(B)&&B>ri&&(ri=B,B<=v)){const st=Math.round(B/v*N);this.updateProgressOverlay(p,O+st,b)}}};this.ffmpeg.on("log",ai),await this.ffmpeg.exec(ct),this.ffmpeg.off("log",ai),this.updateProgressOverlay(p,O+N,b);const be=await this.ffmpeg.readFile(we),yn=be instanceof Uint8Array?be:new TextEncoder().encode(be.toString()),vn=new Blob([yn],{type:"video/mp4"}),oi=URL.createObjectURL(vn),Se=document.createElement("a");Se.href=oi,Se.download=t,Se.click(),URL.revokeObjectURL(oi);for(let P=0;P<v;P+=1)try{await this.ffmpeg.deleteFile(`frame_${P.toString().padStart(6,"0")}.png`)}catch{}for(const P of it)try{await this.ffmpeg.deleteFile(P.filename)}catch{}await this.ffmpeg.deleteFile(we),this.updateProgressOverlay(p,b,b)}catch(f){throw console.error("Error during export:",f),f}finally{this.removeProgressOverlay(p),n.position.x=o,n.position.y=l,n.scale.x=c,n.scale.y=h,n.visible=a,this.edit.seek(s),i&&this.edit.play()}}findAudioPlayers(){const t=[],e=this.edit.tracks;if(e&&Array.isArray(e))for(let i=0;i<e.length;i+=1){const s=e[i];if(Array.isArray(s))for(let n=0;n<s.length;n+=1){const a=s[n];(a instanceof oe||a.constructor.name==="AudioPlayer"||a.clipConfiguration?.asset?.type==="audio")&&(t.includes(a)||t.push(a))}}return this.searchContainerForPlayers(this.edit.getContainer(),t),t}searchContainerForPlayers(t,e){if(t){for(const i of t.children)if(i instanceof d.Container){if(i.label?.startsWith("shotstack-track-")){for(const n of i.children)if(n instanceof d.Container){const a=n,o=["player","clip","audioPlayer","entity"];for(const l of o){const c=a[l];c instanceof oe&&!e.includes(c)&&e.push(c)}}}this.searchContainerForPlayers(i,e)}}}async processAudioTrack(t,e){try{const{clipConfiguration:i}=t;if(!i?.asset)return null;const s=i.asset;if(!s.src)return console.warn("Audio asset does not have a valid src property"),null;const n=await fetch(s.src);if(!n.ok)return console.error(`Failed to fetch audio file: ${s.src}`),null;const a=await n.arrayBuffer(),o=`audio_${e}.mp3`;return await this.ffmpeg.writeFile(o,new Uint8Array(a)),{filename:o,start:t.getStart(),duration:t.getLength(),volume:t.getVolume()}}catch(i){return console.error(`Error processing audio track ${e}:`,i),null}}createProgressOverlay(){const t=document.createElement("div");t.className="video-export-progress-overlay",Object.assign(t.style,{position:"fixed",top:"0",left:"0",width:"100%",height:"100%",backgroundColor:"rgba(0, 0, 0, 0.5)",zIndex:"9999",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",color:"white",fontFamily:"Arial, sans-serif"});const e=document.createElement("div");Object.assign(e.style,{backgroundColor:"#222",borderRadius:"8px",padding:"20px",boxShadow:"0 4px 8px rgba(0, 0, 0, 0.2)",width:"300px",textAlign:"center"}),t.appendChild(e);const i=document.createElement("h3");i.innerText="Exporting Video",i.style.margin="0 0 15px 0",i.style.fontWeight="normal",e.appendChild(i);const s=document.createElement("div");Object.assign(s.style,{width:"100%",height:"6px",backgroundColor:"#444",borderRadius:"3px",overflow:"hidden",marginBottom:"10px"}),e.appendChild(s);const n=document.createElement("div");n.className="video-export-progress-bar",Object.assign(n.style,{width:"0%",height:"100%",backgroundColor:"#3498db",transition:"width 0.3s"}),s.appendChild(n);const a=document.createElement("div");return a.className="video-export-percent",a.innerText="0%",a.style.fontSize="12px",e.appendChild(a),document.body.appendChild(t),t}updateProgressOverlay(t,e,i){if(!t)return;const s=Math.round(e/i*100),n=t.querySelector(".video-export-progress-bar"),a=t.querySelector(".video-export-percent");n&&(n.style.width=`${s}%`),a&&(a.innerText=`${s}%`)}removeProgressOverlay(t){t?.parentNode?.removeChild(t)}}function qe(r){const t=r.replace("#",""),e=parseInt(t,16);return Number.isNaN(e)?(console.warn(`Invalid hex color: ${r}, defaulting to black`),0):e}function Ws(r){const t=e=>{if(typeof e=="string")return qe(e);if(typeof e=="object"&&e!==null){const i=Array.isArray(e)?[]:{};for(const s in e)Object.prototype.hasOwnProperty.call(e,s)&&(i[s]=t(e[s]));return i}return e};return t(r)}function Qe(r){if(typeof r=="string")return qe(r);if(typeof r=="object"&&r!==null){const t=Array.isArray(r)?[]:{};for(const e in r)Object.prototype.hasOwnProperty.call(r,e)&&(t[e]=Qe(r[e]));return t}return r}const Je=Ws({timeline:{background:"#1a1a1a",divider:"#1a1a1a",toolbar:{background:"#1a1a1a",surface:"#2a2a2a",hover:"#3a3a3a",active:"#007acc",divider:"#3a3a3a",icon:"#888888",text:"#ffffff",height:36},ruler:{background:"#404040",text:"#ffffff",markers:"#666666",height:40},tracks:{surface:"#2a2a2a",surfaceAlt:"#242424",border:"#3a3a3a",height:60},clips:{video:"#4a90e2",audio:"#7ed321",image:"#f5a623",text:"#d0021b",shape:"#9013fe",html:"#50e3c2",luma:"#b8e986",default:"#8e8e93",selected:"#007acc",radius:4},playhead:"#ff4444",snapGuide:"#888888",dropZone:"#00ff00",trackInsertion:"#00ff00"}});class ti{static resolveTheme(t){if(!t||!t.theme)return this.deepClone(Je);const e=Qe(t.theme),i=this.deepClone(Je);return this.deepMerge(i,e)}static validateTheme(t){try{if(!t.timeline)return!1;const{timeline:e}=t;if(typeof e.background!="number"||typeof e.divider!="number"||typeof e.playhead!="number"||typeof e.snapGuide!="number"||typeof e.dropZone!="number"||typeof e.trackInsertion!="number"||!e.toolbar)return!1;const i=e.toolbar;if(typeof i.background!="number"||typeof i.surface!="number"||typeof i.hover!="number"||typeof i.active!="number"||typeof i.divider!="number"||typeof i.icon!="number"||typeof i.text!="number"||typeof i.height!="number"||i.height<=0||!e.ruler)return!1;const s=e.ruler;if(typeof s.background!="number"||typeof s.text!="number"||typeof s.markers!="number"||typeof s.height!="number"||s.height<=0||!e.tracks)return!1;const n=e.tracks;if(typeof n.surface!="number"||typeof n.surfaceAlt!="number"||typeof n.border!="number"||typeof n.height!="number"||n.height<=0||!e.clips)return!1;const a=e.clips,o=["video","audio","image","text","shape","html","luma","default","selected"];for(const l of o)if(typeof a[l]!="number")return!1;return!(typeof a.radius!="number"||a.radius<0)}catch(e){return console.error("Theme validation error:",e),!1}}static deepClone(t){if(t===null||typeof t!="object")return t;if(t instanceof Array)return t.map(i=>this.deepClone(i));const e={};for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=this.deepClone(t[i]));return e}static deepMerge(t,e){const i={...t};for(const s in e)if(Object.prototype.hasOwnProperty.call(e,s)){const n=e[s],a=i[s];n!==void 0&&(typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof a=="object"&&a!==null&&!Array.isArray(a)?i[s]=this.deepMerge(a,n):i[s]=n)}return i}}class Ks{timeline;constructor(t){this.timeline=t}getValidDropPosition(t,e,i,s){const n=this.timeline.getVisualTracks()[i];if(!n)return{validTime:t,wouldOverlap:!1};const a=this.getOtherClipBounds(n,s),o=t+e,l=a.find(v=>!(o<=v.start||t>=v.end));if(!l)return{validTime:t,wouldOverlap:!1};const c=l.start-e,h=l.end,p=Math.abs(t-c)<Math.abs(t-h)&&c>=0?c:h;return{validTime:this.getValidDropPosition(p,e,i,s).validTime,wouldOverlap:!0}}checkOverlap(t,e,i,s){const n=this.timeline.getVisualTracks()[i];if(!n)return!1;const a=this.getOtherClipBounds(n,s),o=t+e;return a.some(l=>!(o<=l.start||t>=l.end))}getOtherClipBounds(t,e){return t.getClips().map((i,s)=>({clip:i,index:s})).filter(({index:i})=>i!==e).map(({clip:i})=>{const s=i.getClipConfig();return s?{start:s.start||0,end:(s.start||0)+(s.length||0)}:null}).filter(i=>i!==null).sort((i,s)=>i.start-s.start)}findAvailableGaps(t,e){const i=this.timeline.getVisualTracks()[t];if(!i)return[];const s=this.getOtherClipBounds(i),n=[];s.length>0&&s[0].start>=e&&n.push({start:0,end:s[0].start});for(let a=0;a<s.length-1;a+=1)s[a+1].start-s[a].end>=e&&n.push({start:s[a].end,end:s[a+1].start});return n}}class ei{constructor(t,e,i,s){this.fromTrackIndex=t,this.fromClipIndex=e,this.toTrackIndex=i,this.newStart=s,this.originalTrackIndex=t,this.originalClipIndex=e}name="moveClip";player;originalTrackIndex;originalClipIndex;originalStart;execute(t){if(!t)return;const e=t.getTracks();if(this.fromTrackIndex<0||this.fromTrackIndex>=e.length){console.warn(`Invalid source track index: ${this.fromTrackIndex}`);return}const i=e[this.fromTrackIndex];if(this.fromClipIndex<0||this.fromClipIndex>=i.length){console.warn(`Invalid clip index: ${this.fromClipIndex}`);return}if(this.player=i[this.fromClipIndex],this.originalStart=this.player.clipConfiguration.start,this.fromTrackIndex!==this.toTrackIndex){if(this.toTrackIndex<0||this.toTrackIndex>=e.length){console.warn(`Invalid destination track index: ${this.toTrackIndex}`);return}i.splice(this.fromClipIndex,1),this.player.layer=this.toTrackIndex+1;const s=e[this.toTrackIndex];let n=0;for(let a=0;a<s.length;a+=1){const o=s[a];if(o.clipConfiguration&&o.clipConfiguration.start!==void 0&&this.newStart<o.clipConfiguration.start)break;n+=1}s.splice(n,0,this.player),this.originalClipIndex=n}if(this.player.clipConfiguration.start=this.newStart,t.movePlayerToTrackContainer(this.player,this.fromTrackIndex,this.toTrackIndex),this.player.reconfigureAfterRestore(),this.player.draw(),t.updateDuration(),this.fromTrackIndex!==this.toTrackIndex){const s=e[this.fromTrackIndex],n=e[this.toTrackIndex];[...s,...n].forEach(a=>{a&&a!==this.player&&a.draw()})}t.emitEvent("clip:updated",{previous:{clip:{...this.player.clipConfiguration,start:this.originalStart},trackIndex:this.fromTrackIndex,clipIndex:this.fromClipIndex},current:{clip:this.player.clipConfiguration,trackIndex:this.toTrackIndex,clipIndex:this.originalClipIndex}})}undo(t){if(!t||!this.player||this.originalStart===void 0)return;const e=t.getTracks();if(this.fromTrackIndex!==this.toTrackIndex){const i=e[this.toTrackIndex],s=i.indexOf(this.player);s!==-1&&i.splice(s,1),this.player.layer=this.fromTrackIndex+1,e[this.fromTrackIndex].splice(this.fromClipIndex,0,this.player)}this.player.clipConfiguration.start=this.originalStart,t.movePlayerToTrackContainer(this.player,this.toTrackIndex,this.fromTrackIndex),this.player.reconfigureAfterRestore(),this.player.draw(),t.updateDuration(),t.emitEvent("clip:updated",{previous:{clip:{...this.player.clipConfiguration,start:this.newStart},trackIndex:this.toTrackIndex,clipIndex:this.originalClipIndex},current:{clip:this.player.clipConfiguration,trackIndex:this.fromTrackIndex,clipIndex:this.fromClipIndex}})}}class $s{constructor(t,e,i,s){this.insertionIndex=t,this.fromTrackIndex=e,this.fromClipIndex=i,this.newStart=s,this.addTrackCommand=new je(t);const n=e>=t?e+1:e;this.moveClipCommand=new ei(n,i,t,s)}name="createTrackAndMoveClip";addTrackCommand;moveClipCommand;wasExecuted=!1;async execute(t){if(t)try{this.addTrackCommand.execute(t),this.moveClipCommand.execute(t),this.wasExecuted=!0}catch(e){if(this.wasExecuted)try{this.undo(t)}catch{}throw e}}undo(t){!t||!this.wasExecuted||(this.moveClipCommand.undo(t),this.addTrackCommand.undo(t),this.wasExecuted=!1,t.emitEvent("track:created:undone",{trackIndex:this.insertionIndex}))}}class Ys{timeline;thresholds;snapManager;collisionDetector;visualFeedback;dragInfo=null;currentDropZone=null;constructor(t,e,i,s,n){this.timeline=t,this.thresholds=e,this.snapManager=i,this.collisionDetector=s,this.visualFeedback=n}activate(){}deactivate(){this.endDrag()}canStartDrag(t,e){const i=Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2),{trackHeight:s}=this.timeline.getLayout(),n=s<20?2:this.thresholds.drag.base;return i>n}startDrag(t,e){const i=this.timeline.getClipData(t.trackIndex,t.clipIndex);if(!i)return console.warn(`Clip data not found for track ${t.trackIndex}, clip ${t.clipIndex}`),!1;const s=this.timeline.getContainer().toLocal(e.global),n=this.timeline.getLayout(),a=n.getXAtTime(i.start||0),o=t.trackIndex*n.trackHeight;return this.dragInfo={trackIndex:t.trackIndex,clipIndex:t.clipIndex,startTime:i.start||0,offsetX:s.x-a,offsetY:s.y-o},this.timeline.getPixiApp().canvas.style.cursor="grabbing",this.timeline.getEdit().events.emit("drag:started",this.dragInfo),!0}updateDrag(t){if(!this.dragInfo)return;const e=this.calculateDragPosition(t),i=this.detectDropZone(e.y);i?this.handleDropZonePreview(i,e):this.handleNormalDragPreview(e),this.emitDragUpdate(e,i)}completeDrag(t){if(!this.dragInfo)return;const e={...this.dragInfo},i=this.calculateDragPosition(t),s=this.detectDropZone(i.y);this.endDrag(),s?this.executeDropZoneMove(s,e,i):this.executeNormalMove(e,i)}calculateDragPosition(t){if(!this.dragInfo)throw new Error("No drag info available");const e=this.timeline.getContainer().toLocal(t.global),i=this.timeline.getLayout(),s=Math.max(0,i.getTimeAtX(e.x-this.dragInfo.offsetX)),n=e.y-this.dragInfo.offsetY,a=n+i.trackHeight/2,o=Math.max(0,Math.floor(a/i.trackHeight)),l=this.timeline.getVisualTracks().length-1,c=Math.max(0,Math.min(l,o));return{x:e.x,y:e.y+i.viewportY,time:s,track:c,ghostY:n}}detectDropZone(t){const e=this.timeline.getLayout(),i=this.timeline.getVisualTracks(),s=e.trackHeight*this.thresholds.dropZone.ratio;for(let n=0;n<=i.length;n+=1){const a=e.tracksY+n*e.trackHeight;if(Math.abs(t-a)<s){let o;return n===0?o="above":n===i.length?o="below":o="between",{type:o,position:n}}}return null}handleDropZonePreview(t,e){(!this.currentDropZone||this.currentDropZone.type!==t.type||this.currentDropZone.position!==t.position)&&(this.currentDropZone=t,this.visualFeedback.showDropZone(t)),this.timeline.hideDragGhost(),this.visualFeedback.hideSnapGuidelines(),this.visualFeedback.hideTargetTrack()}handleNormalDragPreview(t){if(!this.dragInfo)return;this.currentDropZone&&(this.visualFeedback.hideDropZone(),this.currentDropZone=null);const e=this.timeline.getClipData(this.dragInfo.trackIndex,this.dragInfo.clipIndex);if(!e)return;const i=e.length||0,s=t.track===this.dragInfo.trackIndex?this.dragInfo.clipIndex:void 0,n=this.calculateFinalPosition(t.time,t.track,i,s),a=this.snapManager.findAlignedElements(n,i,t.track,s);a.length>0?this.visualFeedback.showSnapGuidelines(a):this.visualFeedback.hideSnapGuidelines(),this.visualFeedback.showTargetTrack(t.track),this.timeline.showDragGhost(t.track,n,t.ghostY)}calculateFinalPosition(t,e,i,s){const n=this.snapManager.calculateSnapPosition(t,e,i,s);return this.collisionDetector.getValidDropPosition(n.time,i,e,s).validTime}emitDragUpdate(t,e){if(!this.dragInfo)return;const i=this.timeline.getClipData(this.dragInfo.trackIndex,this.dragInfo.clipIndex);if(!i)return;const s=i.length||0,n=e?t.time:this.calculateFinalPosition(t.time,t.track,s,t.track===this.dragInfo.trackIndex?this.dragInfo.clipIndex:void 0);this.timeline.getEdit().events.emit("drag:moved",{...this.dragInfo,currentTime:n,currentTrack:e?-1:t.track})}executeDropZoneMove(t,e,i){const s=new $s(t.position,e.trackIndex,e.clipIndex,i.time);this.timeline.getEdit().executeEditCommand(s)}executeNormalMove(t,e){const i=this.timeline.getClipData(t.trackIndex,t.clipIndex);if(!i)return;const s=i.length||0,n=e.track===t.trackIndex?t.clipIndex:void 0,a=this.calculateFinalPosition(e.time,e.track,s,n);if(e.track!==t.trackIndex||Math.abs(a-t.startTime)>.01){const l=new ei(t.trackIndex,t.clipIndex,e.track,a);this.timeline.getEdit().executeEditCommand(l)}}endDrag(){this.dragInfo=null,this.currentDropZone=null,this.visualFeedback.hideAll(),this.timeline.getPixiApp().canvas.style.cursor="default",this.timeline.getEdit().events.emit("drag:ended",{})}getDragInfo(){return this.dragInfo}dispose(){this.endDrag()}}class Xs{constructor(t,e,i){this.trackIndex=t,this.clipIndex=e,this.newLength=i}name="resizeClip";originalLength;player;execute(t){if(!t)return;const e=t.getTrack(this.trackIndex);if(!e){console.warn(`Invalid track index: ${this.trackIndex}`);return}if(this.clipIndex<0||this.clipIndex>=e.length){console.warn(`Invalid clip index: ${this.clipIndex} for track ${this.trackIndex}`);return}this.player=e[this.clipIndex],this.originalLength=this.player.clipConfiguration.length,this.player.clipConfiguration.length=this.newLength,this.player.reconfigureAfterRestore(),this.player.draw(),t.updateDuration(),t.emitEvent("clip:updated",{previous:{clip:{...this.player.clipConfiguration,length:this.originalLength},trackIndex:this.trackIndex,clipIndex:this.clipIndex},current:{clip:this.player.clipConfiguration,trackIndex:this.trackIndex,clipIndex:this.clipIndex}})}undo(t){!t||!this.player||this.originalLength===void 0||(this.player.clipConfiguration.length=this.originalLength,this.player.reconfigureAfterRestore(),this.player.draw(),t.updateDuration(),t.emitEvent("clip:updated",{previous:{clip:{...this.player.clipConfiguration,length:this.newLength},trackIndex:this.trackIndex,clipIndex:this.clipIndex},current:{clip:this.player.clipConfiguration,trackIndex:this.trackIndex,clipIndex:this.clipIndex}}))}}class js{timeline;thresholds;resizeInfo=null;constructor(t,e){this.timeline=t,this.thresholds=e}activate(){}deactivate(){this.endResize()}isOnClipRightEdge(t,e){const i=this.timeline.getVisualTracks()[t.trackIndex];if(!i)return!1;const s=i.getClip(t.clipIndex);if(!s)return!1;const a=s.getContainer().getBounds(),o=a.x+a.width,l=Math.abs(e.global.x-o),c=this.getResizeThreshold();return l<=c}startResize(t,e){const i=this.timeline.getClipData(t.trackIndex,t.clipIndex);if(!i)return!1;this.resizeInfo={trackIndex:t.trackIndex,clipIndex:t.clipIndex,originalLength:i.length||0,startX:e.global.x},this.timeline.getPixiApp().canvas.style.cursor="ew-resize";const s=this.timeline.getVisualTracks()[t.trackIndex];if(s){const n=s.getClip(t.clipIndex);n&&n.setResizing(!0)}return this.timeline.getEdit().events.emit("resize:started",this.resizeInfo),!0}updateResize(t){if(!this.resizeInfo)return;const e=t.global.x-this.resizeInfo.startX,i=this.timeline.getOptions().pixelsPerSecond||50,s=e/i,n=Math.max(.1,this.resizeInfo.originalLength+s),a=this.timeline.getVisualTracks()[this.resizeInfo.trackIndex];if(a){const o=a.getClip(this.resizeInfo.clipIndex);if(o){const l=n*i;o.setPreviewWidth(l),this.timeline.getEdit().events.emit("resize:updated",{width:l})}}}completeResize(t){if(!this.resizeInfo)return;const e=t.global.x-this.resizeInfo.startX,i=this.timeline.getOptions().pixelsPerSecond||50,s=e/i,n=Math.max(.1,this.resizeInfo.originalLength+s),a=this.timeline.getVisualTracks()[this.resizeInfo.trackIndex];if(a){const o=a.getClip(this.resizeInfo.clipIndex);o&&(o.setResizing(!1),o.setPreviewWidth(null))}if(Math.abs(n-this.resizeInfo.originalLength)>.01){const o=new Xs(this.resizeInfo.trackIndex,this.resizeInfo.clipIndex,n);this.timeline.getEdit().executeEditCommand(o),this.timeline.getEdit().events.emit("resize:ended",{newLength:n})}this.endResize()}getCursorForPosition(t,e){return t&&this.isOnClipRightEdge(t,e)?"ew-resize":""}getResizeThreshold(){const{trackHeight:t}=this.timeline.getLayout();return Math.max(this.thresholds.resize.min,Math.min(this.thresholds.resize.max,t*this.thresholds.resize.ratio))}endResize(){this.resizeInfo=null,this.timeline.getPixiApp().canvas.style.cursor="default"}getResizeInfo(){return this.resizeInfo}dispose(){this.endResize()}}class qs{timeline;thresholds;constructor(t,e){this.timeline=t,this.thresholds=e}getAllSnapPoints(t,e){const i=[];this.timeline.getVisualTracks().forEach((a,o)=>{a.getClips().forEach((c,h)=>{if(o===t&&h===e)return;const p=c.getClipConfig();p&&(i.push({time:p.start||0,type:"clip-start",trackIndex:o,clipIndex:h}),i.push({time:(p.start||0)+(p.length||0),type:"clip-end",trackIndex:o,clipIndex:h}))})});const n=this.timeline.getPlayheadTime();return i.push({time:n,type:"playhead"}),i}getTrackSnapPoints(t,e){return this.getAllSnapPoints(t,e).filter(i=>i.trackIndex===void 0||i.trackIndex===t)}calculateSnapPosition(t,e,i,s){const n=this.timeline.getOptions().pixelsPerSecond||50,a=this.thresholds.snap.pixels/n,o=this.getTrackSnapPoints(e,s);let l=null;for(const c of o){const h=Math.abs(t-c.time);h<a&&(!l||h<l.distance)&&(l={time:c.time,type:c.type,distance:h});const p=Math.abs(t+i-c.time);p<a&&(!l||p<l.distance)&&(l={time:c.time-i,type:c.type,distance:p})}return l?{time:l.time,snapped:!0,snapType:l.type}:{time:t,snapped:!1}}findAlignedElements(t,e,i,s){const a=t+e,o=new Map;this.timeline.getVisualTracks().forEach((c,h)=>{c.getClips().forEach((p,f)=>{if(h===i&&f===s)return;const v=p.getClipConfig();if(!v)return;const I=v.start||0,b=I+(v.length||0);[{time:I,aligns:[t,a]},{time:b,aligns:[t,a]}].forEach(({time:O,aligns:N})=>{N.some(lt=>Math.abs(lt-O)<.1)&&(o.has(O)||o.set(O,{tracks:new Set,isPlayhead:!1}),o.get(O).tracks.add(h))})})});const l=this.timeline.getPlayheadTime();return(Math.abs(t-l)<.1||Math.abs(a-l)<.1)&&(o.has(l)||o.set(l,{tracks:new Set,isPlayhead:!0}),o.get(l).isPlayhead=!0),Array.from(o.entries()).map(([c,h])=>({time:c,tracks:Array.from(h.tracks).concat(i),isPlayhead:h.isPlayhead}))}}class Qs{timeline;graphics=new Map;constructor(t){this.timeline=t}showDropZone(t){this.hideDropZone();const e=new d.Graphics,i=this.timeline.getLayout(),s=this.timeline.getExtendedTimelineWidth(),n=t.position*i.trackHeight,o=this.timeline.getTheme().timeline.trackInsertion;e.setStrokeStyle({width:4,color:o,alpha:.8}),e.moveTo(0,n),e.lineTo(s,n),e.stroke(),e.setStrokeStyle({width:8,color:o,alpha:.3}),e.moveTo(0,n),e.lineTo(s,n),e.stroke(),this.timeline.getContainer().addChild(e),this.graphics.set("dropZone",e)}hideDropZone(){this.hideGraphics("dropZone")}showSnapGuidelines(t){this.hideSnapGuidelines();const e=new d.Graphics,i=this.timeline.getLayout(),s=this.timeline.getTheme();t.forEach(({time:n,tracks:a,isPlayhead:o})=>{const l=i.getXAtTime(n),c=Math.min(...a),h=Math.max(...a),p=c*i.trackHeight,f=(h+1)*i.trackHeight,v=o?s.timeline.playhead:s.timeline.snapGuide;e.setStrokeStyle({width:3,color:v,alpha:.3}),e.moveTo(l,p),e.lineTo(l,f),e.stroke(),e.setStrokeStyle({width:1,color:v,alpha:.8}),e.moveTo(l,p),e.lineTo(l,f),e.stroke()}),this.timeline.getContainer().addChild(e),this.graphics.set("snapGuidelines",e)}hideSnapGuidelines(){this.hideGraphics("snapGuidelines")}showTargetTrack(t){this.hideTargetTrack();const e=new d.Graphics,i=this.timeline.getLayout(),s=this.timeline.getExtendedTimelineWidth(),n=t*i.trackHeight,a=i.trackHeight,l=this.timeline.getTheme().timeline.dropZone;e.rect(0,n,s,a),e.fill({color:l,alpha:.1}),e.setStrokeStyle({width:1,color:l,alpha:.3}),e.rect(0,n,s,a),e.stroke(),this.timeline.getContainer().addChild(e),this.graphics.set("targetTrack",e)}hideTargetTrack(){this.hideGraphics("targetTrack")}hideAll(){this.graphics.forEach((t,e)=>this.hideGraphics(e))}hideGraphics(t){const e=this.graphics.get(t);e&&(e.clear(),e.parent&&e.parent.removeChild(e),e.destroy(),this.graphics.delete(t))}dispose(){this.hideAll(),this.graphics.clear()}}class Js{timeline;state={type:"idle"};abortController;dragHandler;resizeHandler;snapManager;collisionDetector;visualFeedback;thresholds={drag:{base:3,small:2},resize:{min:12,max:20,ratio:.4},dropZone:{ratio:.15},snap:{pixels:10,time:.1}};constructor(t,e){if(this.timeline=t,e){const i=structuredClone(this.thresholds);e.drag&&Object.assign(i.drag,e.drag),e.resize&&Object.assign(i.resize,e.resize),e.dropZone&&Object.assign(i.dropZone,e.dropZone),e.snap&&Object.assign(i.snap,e.snap),this.thresholds=i}this.snapManager=new qs(t,this.thresholds),this.collisionDetector=new Ks(t),this.visualFeedback=new Qs(t),this.dragHandler=new Ys(t,this.thresholds,this.snapManager,this.collisionDetector,this.visualFeedback),this.resizeHandler=new js(t,this.thresholds)}activate(){this.abortController=new AbortController,this.setupEventListeners(),this.dragHandler.activate(),this.resizeHandler.activate()}deactivate(){this.abortController&&(this.abortController.abort(),this.abortController=void 0),this.resetState(),this.dragHandler.deactivate(),this.resizeHandler.deactivate()}setupEventListeners(){const t=this.timeline.getPixiApp();t.stage.interactive=!0,t.stage.on("pointerdown",this.handlePointerDown.bind(this),{signal:this.abortController?.signal}),t.stage.on("pointermove",this.handlePointerMove.bind(this),{signal:this.abortController?.signal}),t.stage.on("pointerup",this.handlePointerUp.bind(this),{signal:this.abortController?.signal}),t.stage.on("pointerupoutside",this.handlePointerUp.bind(this),{signal:this.abortController?.signal})}handlePointerDown(t){const e=t.target;if(e.label){const i=this.parseClipLabel(e.label);if(i){if(this.resizeHandler.isOnClipRightEdge(i,t)){if(this.resizeHandler.startResize(i,t)){const s=this.resizeHandler.getResizeInfo();s&&(this.state={type:"resizing",resizeInfo:s})}return}this.state={type:"selecting",startPos:{x:t.global.x,y:t.global.y},clipInfo:i},this.timeline.getPixiApp().canvas.style.cursor="grab";return}}this.timeline.getEdit().clearSelection()}handlePointerMove(t){switch(this.state.type){case"selecting":this.handleSelectingMove(t);break;case"dragging":this.timeline.getPixiApp().canvas.style.cursor="grabbing",this.dragHandler.updateDrag(t);break;case"resizing":this.timeline.getPixiApp().canvas.style.cursor="ew-resize",this.resizeHandler.updateResize(t);break;case"idle":this.updateCursorForPosition(t);break}}handlePointerUp(t){switch(this.state.type){case"selecting":this.timeline.getEdit().selectClip(this.state.clipInfo.trackIndex,this.state.clipInfo.clipIndex);break;case"dragging":this.dragHandler.completeDrag(t);break;case"resizing":this.resizeHandler.completeResize(t);break}this.resetState()}handleSelectingMove(t){if(this.state.type!=="selecting")return;const e={x:t.global.x,y:t.global.y};if(this.dragHandler.canStartDrag(this.state.startPos,e)&&this.dragHandler.startDrag(this.state.clipInfo,t)){const i=this.dragHandler.getDragInfo();i&&(this.state={type:"dragging",dragInfo:i})}}updateCursorForPosition(t){const e=t.target;if(e.label){const i=this.parseClipLabel(e.label);if(i){const s=this.resizeHandler.getCursorForPosition(i,t);if(s){this.timeline.getPixiApp().canvas.style.cursor=s;return}this.timeline.getPixiApp().canvas.style.cursor="grab";return}}this.timeline.getPixiApp().canvas.style.cursor="default"}parseClipLabel(t){if(!t?.startsWith("clip-"))return null;const e=t.split("-");if(e.length!==3)return null;const i=parseInt(e[1],10),s=parseInt(e[2],10);return Number.isNaN(i)||Number.isNaN(s)?null:{trackIndex:i,clipIndex:s}}resetState(){this.state={type:"idle"},this.visualFeedback.hideAll(),this.timeline.getPixiApp().canvas.style.cursor="default"}dispose(){this.deactivate(),this.dragHandler.dispose(),this.resizeHandler.dispose(),this.visualFeedback.dispose()}}class tn{constructor(t,e,i,s,n){this.container=t,this.layout=e,this.getPixelsPerSecond=i,this.getTrackHeight=s,this.getVisualTracks=n}dragPreviewContainer=null;dragPreviewGraphics=null;draggedClipInfo=null;showDragPreview(t,e,i){if(!i)return;this.draggedClipInfo={trackIndex:t,clipIndex:e,clipConfig:i},this.dragPreviewContainer=new d.Container,this.dragPreviewGraphics=new d.Graphics,this.dragPreviewContainer.addChild(this.dragPreviewGraphics),this.container.addChild(this.dragPreviewContainer),this.getVisualTracks()[t]?.getClip(e)?.setDragging(!0),this.drawDragPreview(t,i.start||0)}drawDragPreview(t,e){if(!this.dragPreviewContainer||!this.dragPreviewGraphics||!this.draggedClipInfo)return;const{clipConfig:i}=this.draggedClipInfo,s=this.layout.getXAtTime(e),n=t*this.layout.trackHeight,a=(i.length||0)*this.getPixelsPerSecond();this.dragPreviewGraphics.clear(),this.dragPreviewGraphics.roundRect(0,0,a,this.getTrackHeight(),4),this.dragPreviewGraphics.fill({color:9342611,alpha:.6}),this.dragPreviewGraphics.stroke({width:2,color:65280}),this.dragPreviewContainer.position.set(s,n)}drawDragPreviewAtPosition(t,e,i){if(!this.dragPreviewContainer||!this.dragPreviewGraphics||!this.draggedClipInfo)return;const{clipConfig:s}=this.draggedClipInfo,n=this.layout.getXAtTime(t),a=(s.length||0)*this.getPixelsPerSecond(),o=this.getTrackHeight();this.dragPreviewGraphics.clear(),this.dragPreviewGraphics.roundRect(0,0,a,o,4),this.dragPreviewGraphics.fill({color:9342611,alpha:.6});const l=i*this.layout.trackHeight,h=Math.abs(e-l)<5?65280:16755200;this.dragPreviewGraphics.stroke({width:2,color:h}),this.dragPreviewContainer.position.set(n,e)}hideDragPreview(){this.dragPreviewContainer&&(this.dragPreviewContainer.destroy({children:!0}),this.dragPreviewContainer=null,this.dragPreviewGraphics=null),this.draggedClipInfo&&(this.getVisualTracks()[this.draggedClipInfo.trackIndex]?.getClip(this.draggedClipInfo.clipIndex)?.setDragging(!1),this.draggedClipInfo=null)}hideDragGhost(){this.dragPreviewContainer&&(this.dragPreviewContainer.visible=!1)}showDragGhost(t,e,i){!this.dragPreviewContainer||!this.draggedClipInfo||(this.dragPreviewContainer.visible=!0,i!==void 0?this.drawDragPreviewAtPosition(e,i,t):this.drawDragPreview(t,e))}getDraggedClipInfo(){return this.draggedClipInfo}hasActivePreview(){return this.dragPreviewContainer!==null}dispose(){this.hideDragPreview()}}class en{constructor(t,e,i,s,n){this.layout=t,this.trackLayer=e,this.overlayLayer=i,this.entityContainer=s,this.onRender=n}scrollX=0;scrollY=0;zoomLevel=1;viewport;rulerViewport;playheadContainer;async setupViewport(){this.rulerViewport=new d.Container,this.rulerViewport.label="ruler-viewport",this.overlayLayer.addChild(this.rulerViewport),this.playheadContainer=new d.Container,this.playheadContainer.label="playhead-container",this.overlayLayer.addChild(this.playheadContainer),this.viewport=new d.Container,this.viewport.label="viewport",this.trackLayer.addChild(this.viewport),this.viewport.addChild(this.entityContainer)}updateViewportTransform(){const t=this.layout.calculateViewportPosition(this.scrollX,this.scrollY);this.viewport.position.set(t.x,t.y),this.viewport.scale.set(this.zoomLevel,this.zoomLevel),this.rulerViewport.position.x=t.x,this.rulerViewport.scale.x=this.zoomLevel,this.playheadContainer.position.x=t.x,this.playheadContainer.scale.x=this.zoomLevel}setScroll(t,e){this.scrollX=t,this.scrollY=e,this.updateViewportTransform(),this.onRender()}setZoom(t){this.zoomLevel=Math.max(.1,Math.min(10,t)),this.updateViewportTransform(),this.onRender()}getViewport(){return{x:this.scrollX,y:this.scrollY,zoom:this.zoomLevel}}getMainViewport(){return this.viewport}getRulerViewport(){return this.rulerViewport}getPlayheadContainer(){return this.playheadContainer}}const F={MIN_WIDTH:50,PADDING:4,DEFAULT_ALPHA:1,DRAG_OPACITY:.6,RESIZE_OPACITY:.9,BORDER_WIDTH:2,CORNER_RADIUS:4,SELECTED_BORDER_MULTIPLIER:2,TEXT_FONT_SIZE:12,TEXT_TRUNCATE_SUFFIX_LENGTH:3},zt={PADDING:2,LABEL_PADDING:8,DEFAULT_OPACITY:.8,BORDER_WIDTH:1},G={TOOLBAR_HEIGHT_RATIO:.12,RULER_HEIGHT_RATIO:.133,TOOLBAR_HEIGHT_DEFAULT:36,RULER_HEIGHT_DEFAULT:40,TRACK_HEIGHT_DEFAULT:80,BORDER_WIDTH:2,CORNER_RADIUS:4,CLIP_PADDING:4,LABEL_PADDING:8,TRACK_PADDING:2,MIN_CLIP_WIDTH:50};function se(r){const t=r.split("/");return t[t.length-1]||r}function sn(r){switch(r.type){case"video":return r.src?se(r.src):"Video";case"audio":return r.src?se(r.src):"Audio";case"image":return r.src?se(r.src):"Image";case"text":return r.text||"Text";case"shape":return r.shape||"Shape";case"html":return"HTML";case"luma":return r.src?se(r.src):"Luma";default:return"Unknown Asset"}}class nn extends nt{clipConfig;options;graphics;background;text;selectionRenderer;lastGlobalX=-1;lastGlobalY=-1;visualState={mode:"normal"};CLIP_PADDING=F.PADDING;BORDER_WIDTH=F.BORDER_WIDTH;get CORNER_RADIUS(){return this.options.theme.timeline.clips.radius||F.CORNER_RADIUS}constructor(t,e){super(),this.clipConfig=t,this.options=e,this.selectionRenderer=e.selectionRenderer,this.graphics=new d.Graphics,this.background=new d.Graphics,this.text=new d.Text,this.setupContainer()}async load(){this.setupGraphics(),this.updateVisualState()}setupContainer(){const t=this.getContainer();t.label=`clip-${this.options.trackIndex}-${this.options.clipIndex}`,t.interactive=!0,t.cursor="pointer",t.addChild(this.background),t.addChild(this.graphics),t.addChild(this.text)}setupGraphics(){this.text.style=new d.TextStyle({fontSize:F.TEXT_FONT_SIZE,fill:this.options.theme.timeline.toolbar.text,fontWeight:"bold",wordWrap:!1,fontFamily:"Arial, sans-serif"}),this.text.anchor.set(0,0),this.text.x=this.CLIP_PADDING,this.text.y=this.CLIP_PADDING}updateFromConfig(t){this.clipConfig=t,this.updateVisualState()}updateVisualState(){this.updatePosition(),this.updateAppearance(),this.updateSize(),this.updateText()}setVisualState(t){this.visualState={...this.visualState,...t},this.updateVisualState()}updatePosition(){const t=this.getContainer(),e=this.clipConfig.start||0;t.x=e*this.options.pixelsPerSecond,t.y=0}updateSize(){const t=this.getEffectiveWidth(),e=this.options.trackHeight;this.drawClipBackground(t,e),this.drawClipBorder(t,e)}getEffectiveWidth(){if(this.visualState.previewWidth!==void 0)return this.visualState.previewWidth;const e=(this.clipConfig.length||0)*this.options.pixelsPerSecond;return Math.max(F.MIN_WIDTH,e)}drawClipBackground(t,e){const i=this.getClipColor(),s=this.getStateStyles();this.background.clear(),this.background.roundRect(0,0,t,e,this.CORNER_RADIUS),this.background.fill({color:i,alpha:s.alpha})}drawClipBorder(t,e){const i=this.getStateStyles(),s=this.BORDER_WIDTH;this.graphics.clear(),this.graphics.roundRect(0,0,t,e,this.CORNER_RADIUS),this.graphics.stroke({width:s,color:i.borderColor}),this.updateSelectionState(t,e)}updateSelectionState(t,e){if(!this.selectionRenderer)return;const i=this.visualState.mode==="selected",s=this.getClipId();if(!i){this.selectionRenderer.clearSelection(s);return}const a=this.getContainer().toGlobal(new d.Point(0,0)),l=this.selectionRenderer.getOverlay().toLocal(a);this.selectionRenderer.renderSelection(s,{x:l.x,y:l.y,width:t,height:e,cornerRadius:this.CORNER_RADIUS,borderWidth:this.BORDER_WIDTH},i)}getClipColor(){const t=this.clipConfig.asset?.type,e=this.options.theme.timeline.clips;switch(t){case"video":return e.video;case"audio":return e.audio;case"image":return e.image;case"text":return e.text;case"shape":return e.shape;case"html":return e.html;case"luma":return e.luma;default:return e.default}}updateAppearance(){const t=this.getContainer();t.alpha=this.visualState.mode==="dragging"?F.DRAG_OPACITY:F.DEFAULT_ALPHA}updateText(){const t=this.clipConfig.asset?sn(this.clipConfig.asset):"Clip";this.text.text=t;const i=(this.clipConfig.length||0)*this.options.pixelsPerSecond-this.CLIP_PADDING*2;if(this.text.width>i){const s=i/this.text.width,n=Math.floor(t.length*s)-F.TEXT_TRUNCATE_SUFFIX_LENGTH;this.text.text=`${t.substring(0,Math.max(1,n))}...`}}getStateStyles(){const{theme:t}=this.options;switch(this.visualState.mode){case"dragging":return{alpha:F.DRAG_OPACITY,borderColor:t.timeline.tracks.border};case"resizing":return{alpha:F.RESIZE_OPACITY,borderColor:t.timeline.dropZone};case"selected":return{alpha:F.DEFAULT_ALPHA,borderColor:t.timeline.clips.selected};default:return{alpha:F.DEFAULT_ALPHA,borderColor:t.timeline.tracks.border}}}setSelected(t){this.setVisualState({mode:t?"selected":"normal"})}setDragging(t){this.setVisualState({mode:t?"dragging":"normal"})}setResizing(t){this.setVisualState({mode:t?"resizing":"normal",...t?{}:{previewWidth:void 0}})}setPreviewWidth(t){this.setVisualState({previewWidth:t||void 0})}setPixelsPerSecond(t){if(this.updateOptions({pixelsPerSecond:t}),this.visualState.mode==="selected"){const e=this.getEffectiveWidth(),i=this.options.trackHeight;this.updateSelectionState(e,i)}}updateOptions(t){this.options={...this.options,...t},this.updateVisualState()}getClipConfig(){return this.clipConfig}getOptions(){return{...this.options}}getVisualState(){return{...this.visualState}}getSelected(){return this.visualState.mode==="selected"}getClipId(){return`${this.options.trackIndex}-${this.options.clipIndex}`}getDragging(){return this.visualState.mode==="dragging"}getRightEdgeX(){const t=this.getEffectiveWidth();return(this.clipConfig.start||0)*this.options.pixelsPerSecond+t}update(t,e){if(this.visualState.mode==="selected"&&this.selectionRenderer){const s=this.getContainer().toGlobal(new d.Point(0,0));if(s.x!==this.lastGlobalX||s.y!==this.lastGlobalY){this.lastGlobalX=s.x,this.lastGlobalY=s.y;const n=this.getEffectiveWidth(),a=this.options.trackHeight;this.updateSelectionState(n,a)}}}draw(){}dispose(){this.selectionRenderer&&this.selectionRenderer.clearSelection(this.getClipId()),this.background.destroy(),this.graphics.destroy(),this.text.destroy()}}class rn extends nt{clips=[];options;background;TRACK_PADDING=zt.PADDING;LABEL_PADDING=zt.LABEL_PADDING;constructor(t){super(),this.options=t,this.background=new d.Graphics,this.setupContainer()}async load(){this.updateTrackAppearance()}setupContainer(){const t=this.getContainer();t.label=`track-${this.options.trackIndex}`,t.addChild(this.background),t.y=this.options.trackIndex*this.options.trackHeight}updateTrackAppearance(){const{width:t}=this.options,e=this.options.trackHeight,{theme:i}=this.options;this.background.clear();const s=this.options.trackIndex%2===0?i.timeline.tracks.surface:i.timeline.tracks.surfaceAlt;this.background.rect(0,0,t,e),this.background.fill({color:s,alpha:zt.DEFAULT_OPACITY}),this.background.rect(0,0,t,e),this.background.stroke({width:zt.BORDER_WIDTH,color:i.timeline.tracks.border}),this.background.moveTo(0,e-1),this.background.lineTo(t,e-1),this.background.stroke({width:zt.BORDER_WIDTH,color:i.timeline.divider})}rebuildFromTrackData(t,e){this.options={...this.options,pixelsPerSecond:e},this.clearAllClips(),t.clips&&t.clips.forEach((i,s)=>{const n={pixelsPerSecond:this.options.pixelsPerSecond,trackHeight:this.options.trackHeight,trackIndex:this.options.trackIndex,clipIndex:s,theme:this.options.theme,selectionRenderer:this.options.selectionRenderer},a=new nn(i,n);this.addClip(a)}),this.updateTrackAppearance()}async addClip(t){this.clips.push(t),await t.load(),this.getContainer().addChild(t.getContainer())}clearAllClips(){const t=this.getContainer();for(const e of this.clips)t.removeChild(e.getContainer()),e.dispose();this.clips=[]}removeClip(t){if(t>=0&&t<this.clips.length){const e=this.clips[t];this.getContainer().removeChild(e.getContainer()),e.dispose(),this.clips.splice(t,1)}}updateClip(t,e){t>=0&&t<this.clips.length&&this.clips[t].updateFromConfig(e)}setPixelsPerSecond(t){this.options={...this.options,pixelsPerSecond:t},this.clips.forEach(e=>{e.setPixelsPerSecond(t)})}setWidth(t){this.options={...this.options,width:t},this.updateTrackAppearance()}setTrackIndex(t){this.options={...this.options,trackIndex:t};const e=this.getContainer();e.y=t*this.options.trackHeight,this.clips.forEach((i,s)=>{i.updateOptions({trackIndex:t})})}selectClip(t){this.clearAllSelections(),t>=0&&t<this.clips.length&&this.clips[t].setSelected(!0)}clearAllSelections(){this.clips.forEach(t=>{t.setSelected(!1)})}getSelectedClip(){return this.clips.find(t=>t.getSelected())||null}getSelectedClipIndex(){return this.clips.findIndex(t=>t.getSelected())}getClips(){return[...this.clips]}getClip(t){return this.clips[t]||null}getClipCount(){return this.clips.length}getTrackIndex(){return this.options.trackIndex}getTrackHeight(){return this.options.trackHeight}getOptions(){return{...this.options}}findClipAtPosition(t,e){if(e<0||e>this.options.trackHeight)return null;const i=t/this.options.pixelsPerSecond;for(let s=0;s<this.clips.length;s+=1){const n=this.clips[s],a=n.getClipConfig(),o=a.start||0,l=o+(a.length||0);if(i>=o&&i<=l)return{clip:n,clipIndex:s}}return null}update(t,e){this.clips.forEach(i=>{i.update(t,e)})}draw(){this.clips.forEach(t=>{t.draw()})}dispose(){this.clearAllClips(),this.background.destroy()}}class an{constructor(t,e){this.overlay=t,this.theme=e}selectionGraphics=new Map;renderSelection(t,e,i){if(!i){this.clearSelection(t);return}let s=this.selectionGraphics.get(t);s||(s=new d.Graphics,s.label=`selection-border-${t}`,this.selectionGraphics.set(t,s),this.overlay.addChild(s)),s.position.set(e.x,e.y),s.clear(),s.setStrokeStyle({width:e.borderWidth*F.SELECTED_BORDER_MULTIPLIER,color:this.theme.timeline.clips.selected}),s.roundRect(0,0,e.width,e.height,e.cornerRadius),s.stroke()}clearSelection(t){const e=this.selectionGraphics.get(t);e&&(this.overlay.removeChild(e),e.destroy(),this.selectionGraphics.delete(t))}clearAllSelections(){this.selectionGraphics.forEach((t,e)=>{this.clearSelection(e)})}updateTheme(t){this.theme=t,this.selectionGraphics.forEach(e=>{e.clear()})}getOverlay(){return this.overlay}dispose(){this.clearAllSelections()}}class on{constructor(t,e,i,s,n){this.container=t,this.layout=e,this.theme=i,this.getPixelsPerSecond=s,this.getExtendedTimelineWidth=n,this.selectionOverlay=new d.Container,this.selectionOverlay.label="selectionOverlay",this.container.addChild(this.selectionOverlay),this.selectionRenderer=new an(this.selectionOverlay,this.theme)}visualTracks=[];selectionOverlay;selectionRenderer;async rebuildFromEdit(t,e){if(t?.timeline?.tracks){this.clearAllVisualState();for(let i=0;i<t.timeline.tracks.length;i+=1){const s=t.timeline.tracks[i],n={pixelsPerSecond:e,trackHeight:this.layout.trackHeight,trackIndex:i,width:this.getExtendedTimelineWidth(),theme:this.theme,selectionRenderer:this.selectionRenderer},a=new rn(n);await a.load(),a.rebuildFromTrackData(s,e),this.container.addChild(a.getContainer()),this.visualTracks.push(a)}this.container.setChildIndex(this.selectionOverlay,this.container.children.length-1)}}clearAllVisualState(){this.visualTracks.forEach(t=>{this.container.removeChild(t.getContainer()),t.dispose()}),this.visualTracks=[],this.selectionRenderer.clearAllSelections()}updateVisualSelection(t,e){this.clearVisualSelection();const i=this.visualTracks[t];if(i){const s=i.getClip(e);s&&s.setSelected(!0)}}clearVisualSelection(){this.visualTracks.forEach(t=>{t.getClips().forEach(i=>{i.setSelected(!1)})})}findClipAtPosition(t,e){const i=Math.floor(e/this.layout.trackHeight);if(i<0||i>=this.visualTracks.length)return null;const s=this.visualTracks[i],n=e-i*this.layout.trackHeight,a=s.findClipAtPosition(t,n);return a?{trackIndex:i,clipIndex:a.clipIndex,clipConfig:a.clip.getClipConfig(),x:(a.clip.getClipConfig().start||0)*this.getPixelsPerSecond(),y:i*this.layout.trackHeight,width:(a.clip.getClipConfig().length||0)*this.getPixelsPerSecond(),height:this.layout.trackHeight}:null}updateTrackWidths(t){this.visualTracks.forEach(e=>{e.setWidth(t)})}getVisualTracks(){return this.visualTracks}updatePixelsPerSecond(t){this.visualTracks.forEach(e=>{e.setPixelsPerSecond(t)})}getSelectionOverlay(){return this.selectionOverlay}getSelectionRenderer(){return this.selectionRenderer}dispose(){this.clearAllVisualState(),this.selectionRenderer&&this.selectionRenderer.dispose(),this.selectionOverlay&&this.container&&(this.container.removeChild(this.selectionOverlay),this.selectionOverlay.destroy())}}class ln{constructor(t,e){this.edit=t,this.callbacks=e}setupEventListeners(){this.edit.events.on("timeline:updated",this.handleTimelineUpdated.bind(this)),this.edit.events.on("clip:updated",this.handleClipUpdated.bind(this)),this.edit.events.on("clip:selected",this.handleClipSelected.bind(this)),this.edit.events.on("selection:cleared",this.handleSelectionCleared.bind(this)),this.edit.events.on("drag:started",this.handleDragStarted.bind(this)),this.edit.events.on("drag:ended",this.handleDragEnded.bind(this)),this.edit.events.on("track:created",this.handleTrackCreated.bind(this))}async handleTimelineUpdated(t){await this.callbacks.onEditChange(t.current)}async handleClipUpdated(){await this.callbacks.onEditChange()}handleClipSelected(t){this.callbacks.onClipSelected(t.trackIndex,t.clipIndex)}handleSelectionCleared(){this.callbacks.onSelectionCleared()}handleDragStarted(t){this.callbacks.onDragStarted(t.trackIndex,t.clipIndex)}handleDragEnded(){this.callbacks.onDragEnded()}async handleTrackCreated(){await this.callbacks.onEditChange()}handleSeek(t){this.callbacks.onSeek(t.time*1e3)}dispose(){this.edit.events.off("timeline:updated",this.handleTimelineUpdated.bind(this)),this.edit.events.off("clip:updated",this.handleClipUpdated.bind(this)),this.edit.events.off("clip:selected",this.handleClipSelected.bind(this)),this.edit.events.off("selection:cleared",this.handleSelectionCleared.bind(this)),this.edit.events.off("drag:started",this.handleDragStarted.bind(this)),this.edit.events.off("drag:ended",this.handleDragEnded.bind(this)),this.edit.events.off("track:created",this.handleTrackCreated.bind(this))}}class cn{constructor(t,e){this.options=t,this.onUpdate=e}app;trackLayer;overlayLayer;animationFrameId=null;async initializePixiApp(){this.app=new d.Application,await this.app.init({width:this.options.width,height:this.options.height,backgroundColor:this.options.backgroundColor,antialias:this.options.antialias,resolution:this.options.resolution,autoDensity:!0,preference:"webgl"});const t=document.querySelector("[data-shotstack-timeline]");if(!t)throw new Error("Timeline container element [data-shotstack-timeline] not found");t.appendChild(this.app.canvas)}async setupRenderLayers(){this.trackLayer=new d.Container,this.overlayLayer=new d.Container,this.trackLayer.label="track-layer",this.overlayLayer.label="overlay-layer",this.app.stage.addChild(this.trackLayer),this.app.stage.addChild(this.overlayLayer)}startAnimationLoop(){let t=performance.now();const e=i=>{const s=i-t;t=i;const n=s/16.667;this.onUpdate(n,s),this.draw(),this.animationFrameId=requestAnimationFrame(e)};this.animationFrameId=requestAnimationFrame(e)}draw(){this.app.render()}render(){this.app.render()}updateBackgroundColor(t){this.app&&(this.app.renderer.background.color=t)}getApp(){return this.app}getStage(){return this.app.stage}getTrackLayer(){return this.trackLayer}getOverlayLayer(){return this.overlayLayer}dispose(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.app&&this.app.destroy(!0)}}const St={RULER:{DEFAULT_HEIGHT:40,LABEL_FONT_SIZE:10,LABEL_PADDING_X:2},PLAYHEAD:{LINE_WIDTH:2},SCROLL:{HORIZONTAL_SPEED:2,VERTICAL_SPEED:.5}};class ii extends nt{events;rulerContainer;rulerBackground;timeMarkers;timeLabels;pixelsPerSecond;timelineDuration;rulerHeight;theme;constructor(t){super(),this.events=new Mt,this.pixelsPerSecond=t.pixelsPerSecond,this.timelineDuration=t.timelineDuration,this.rulerHeight=t.rulerHeight??St.RULER.DEFAULT_HEIGHT,this.theme=t.theme,this.rulerContainer=new d.Container,this.rulerBackground=new d.Graphics,this.timeMarkers=new d.Graphics,this.timeLabels=new d.Container}async load(){this.setupRuler(),this.draw()}setupRuler(){this.rulerContainer.label="ruler",this.rulerContainer.addChild(this.rulerBackground),this.rulerContainer.addChild(this.timeMarkers),this.rulerContainer.addChild(this.timeLabels),this.rulerContainer.eventMode="static",this.rulerContainer.cursor="pointer",this.rulerContainer.on("pointerdown",this.onRulerPointerDown.bind(this)),this.getContainer().addChild(this.rulerContainer)}drawRulerBackground(){this.rulerBackground.clear();const t=this.calculateRulerWidth(),e=this.theme?.timeline.ruler.background||4210752,i=this.theme?.timeline.tracks.border||6316128;this.rulerBackground.rect(0,0,t,this.rulerHeight),this.rulerBackground.fill(e),this.rulerBackground.rect(0,this.rulerHeight-1,t,1),this.rulerBackground.fill(i)}drawTimeMarkers(){this.timeMarkers.clear();const t=this.getTimeInterval(),e=this.getVisibleDuration(),i=this.theme?.timeline.ruler.markers||6710886,s=this.rulerHeight*.5;let n=4;t===10?n=9:(t===30||t===60)&&(n=5);const a=t/(n+1);for(let o=0;o<=e;o+=t)for(let l=1;l<=n;l+=1){const c=o+l*a;if(c<=e){const h=c*this.pixelsPerSecond;this.timeMarkers.circle(h,s,1.5),this.timeMarkers.fill(i)}}}drawTimeLabels(){this.timeLabels.removeChildren();const t=this.getTimeInterval(),e=this.getVisibleDuration(),i=this.theme?.timeline.ruler.text||16777215,s={fontSize:St.RULER.LABEL_FONT_SIZE,fill:i,fontFamily:"Arial"};for(let n=0;n<=e;n+=t){const a=new d.Text({text:this.formatTime(n),style:s}),o=n*this.pixelsPerSecond;n===0?(a.anchor.set(0,.5),a.x=o+St.RULER.LABEL_PADDING_X):(a.anchor.set(.5,.5),a.x=o),a.y=this.rulerHeight*.5,this.timeLabels.addChild(a)}}onRulerPointerDown(t){const e=this.rulerContainer.toLocal(t.global),i=Math.max(0,e.x/this.pixelsPerSecond);this.events.emit("ruler:seeked",{time:i})}updateRuler(t,e){this.pixelsPerSecond=t,this.timelineDuration=e,this.draw()}update(t,e){}draw(){this.drawRulerBackground(),this.drawTimeMarkers(),this.drawTimeLabels()}dispose(){this.timeLabels.removeChildren(),this.rulerContainer.removeChildren(),this.events.clear("*")}getViewportWidth(){return this.getContainer().parent?.width||800}calculateRulerWidth(){const t=this.timelineDuration*this.pixelsPerSecond;return Math.max(t,this.getViewportWidth())}getVisibleDuration(){return Math.max(this.timelineDuration,this.getViewportWidth()/this.pixelsPerSecond)}getTimeInterval(){const t=[1,5,10,30,60,120,300,600],e=80;for(const i of t)if(i*this.pixelsPerSecond>=e)return i;return Math.ceil(this.getVisibleDuration()/10)}formatTime(t){if(t===0)return"0s";const e=Math.floor(t/60),i=t%60;if(t<60)return`${t}s`;if(i===0)return`${e}m`;const s=i.toString().padStart(2,"0");return`${e}:${s}`}}class si extends nt{constructor(t){super(),this.options=t,this.graphics=new d.Graphics}events=new Mt;graphics;currentTime=0;isDragging=!1;async load(){this.setupPlayhead(),this.draw()}setupPlayhead(){this.graphics.label="playhead",this.graphics.eventMode="static",this.graphics.cursor="pointer",this.graphics.on("pointerdown",this.onPointerDown.bind(this)).on("pointermove",this.onPointerMove.bind(this)).on("pointerup",this.onPointerUp.bind(this)).on("pointerupoutside",this.onPointerUp.bind(this)),this.getContainer().addChild(this.graphics)}drawPlayhead(){const t=this.currentTime*this.options.pixelsPerSecond,e=this.options.theme?.timeline.playhead??16729156,i=St.PLAYHEAD.LINE_WIDTH,s=t+i/2;this.graphics.clear(),this.graphics.fill(e),this.graphics.rect(t,0,i,this.options.timelineHeight);const n=8;this.graphics.moveTo(s,10),this.graphics.lineTo(s-n,0),this.graphics.lineTo(s+n,0),this.graphics.closePath(),this.graphics.fill()}onPointerDown(t){this.isDragging=!0,this.graphics.cursor="grabbing",this.updateTimeFromPointer(t)}onPointerMove(t){this.isDragging&&this.updateTimeFromPointer(t)}onPointerUp(){this.isDragging=!1,this.graphics.cursor="pointer"}updateTimeFromPointer(t){const e=this.graphics.parent.toLocal(t.global),i=Math.max(0,e.x/this.options.pixelsPerSecond);this.setTime(i),this.events.emit("playhead:seeked",{time:i})}setTime(t){this.currentTime=t,this.draw(),this.events.emit("playhead:timeChanged",{time:t})}getTime(){return this.currentTime}updatePlayhead(t,e){this.options.pixelsPerSecond=t,this.options.timelineHeight=e,this.draw()}update(){}draw(){this.drawPlayhead()}dispose(){this.graphics.removeAllListeners(),this.events.clear("*")}}class hn{events;timeline;abortController;scrollX=0;scrollY=0;constructor(t){this.events=new Mt,this.timeline=t.timeline}async initialize(){this.setupEventListeners()}setupEventListeners(){this.abortController=new AbortController;const{canvas:t}=this.timeline.getPixiApp();t.addEventListener("wheel",this.handleWheel.bind(this),{passive:!1,signal:this.abortController.signal})}handleWheel(t){if(t.preventDefault(),t.ctrlKey||t.metaKey){this.handleZoom(t);return}this.handleScroll(t)}handleZoom(t){const e=t.deltaY>0?"out":"in",i=this.timeline.getPlayheadTime(),s=this.timeline.getActualEditDuration();e==="in"?this.timeline.zoomIn():this.timeline.zoomOut();const n=this.timeline.getOptions().pixelsPerSecond||50,a=i*n,o=this.timeline.getOptions().width||800,c=this.timeline.timeRange.endTime*n,h=s*n,p=this.calculateZoomScrollPosition({playheadXAfterZoom:a,viewportWidth:o,contentWidth:c,maxPlayheadX:h,actualEditDuration:s,playheadTime:i});this.scrollX=p,this.timeline.setScroll(this.scrollX,this.scrollY);const f=a-p;this.events.emit("zoom",{pixelsPerSecond:n,focusX:f,focusTime:i})}handleScroll(t){let{deltaX:e}=t,{deltaY:i}=t;t.shiftKey&&(e=i,i=0);const s=St.SCROLL.HORIZONTAL_SPEED,n=St.SCROLL.VERTICAL_SPEED;this.scrollX+=e*s,this.scrollY+=i*n,this.scrollX=this.clampScrollX(this.scrollX),this.scrollY=this.clampScrollY(this.scrollY),this.timeline.setScroll(this.scrollX,this.scrollY),this.events.emit("scroll",{x:this.scrollX,y:this.scrollY})}setScroll(t,e){this.scrollX=this.clampScrollX(t),this.scrollY=this.clampScrollY(e),this.timeline.setScroll(this.scrollX,this.scrollY),this.events.emit("scroll",{x:this.scrollX,y:this.scrollY})}clampScrollX(t){const e=this.timeline.getExtendedTimelineWidth(),i=this.timeline.getOptions().width||0,s=Math.max(0,e-i);return Math.max(0,Math.min(t,s))}clampScrollY(t){const e=this.timeline.getLayout(),i=this.timeline.getVisualTracks().length,s=this.timeline.getOptions().height||0,n=Math.max(0,i*e.trackHeight-(s-e.rulerHeight));return Math.max(0,Math.min(t,n))}getScroll(){return{x:this.scrollX,y:this.scrollY}}calculateZoomScrollPosition(t){const{playheadXAfterZoom:e,viewportWidth:i,contentWidth:s,maxPlayheadX:n,actualEditDuration:a,playheadTime:o}=t,l=e-i/2,c=Math.max(0,s-i);let h;const p=l+i,f=Math.max(0,n-i);s<=i||l<0?h=0:p>n&&o<=a?h=Math.min(f,c):l>c?h=c:h=l;const v=e-h;return(v<0||v>i)&&(e>s-i?h=Math.max(0,e-i+50):h=Math.max(0,e-50),h=Math.max(0,Math.min(h,c))),h}dispose(){this.abortController&&(this.abortController.abort(),this.abortController=void 0),this.events.clear("*")}}const E={BUTTON_SIZE:24,BUTTON_HOVER_PADDING:4,BORDER_RADIUS:4,TEXT_SPACING:16,EDGE_MARGIN:10,FRAME_TIME_MS:16.67,ICON:{PLAY:{LEFT:6,TOP:4,RIGHT:18,MIDDLE:12,BOTTOM:20},PAUSE:{RECT1_X:6,RECT2_X:14,TOP:4,WIDTH:4,HEIGHT:16},FRAME_STEP:{TRIANGLE1:{BACK:{LEFT:11,RIGHT:3,MIDDLE:12},FORWARD:{LEFT:4,RIGHT:12,MIDDLE:12}},TRIANGLE2:{BACK:{LEFT:20,RIGHT:12,MIDDLE:12},FORWARD:{LEFT:13,RIGHT:21,MIDDLE:12}},TOP:4,BOTTOM:20}},CUT_BUTTON:{WIDTH:60,HEIGHT:24,FONT_SIZE:12},TIME_DISPLAY:{FONT_SIZE:14,FONT_FAMILY:"monospace"},HOVER_ANIMATION_ALPHA:1,ACTIVE_ANIMATION_ALPHA:.3,DIVIDER_ALPHA:.5};class ne{static createIcon(t,e,i){const s=i?i/E.BUTTON_SIZE:1;switch(t){case"play":return this.createPlayIcon(e,s);case"pause":return this.createPauseIcon(e,s);case"frame-back":return this.createFrameBackIcon(e,s);case"frame-forward":return this.createFrameForwardIcon(e,s);default:throw new Error(`Unknown icon type: ${t}`)}}static createPlayIcon(t,e=1){const i=new d.Graphics,{PLAY:s}=E.ICON;return i.fill({color:t.timeline.toolbar.icon}),i.moveTo(s.LEFT*e,s.TOP*e),i.lineTo(s.RIGHT*e,s.MIDDLE*e),i.lineTo(s.LEFT*e,s.BOTTOM*e),i.closePath(),i.fill(),i}static createPauseIcon(t,e=1){const i=new d.Graphics,{PAUSE:s}=E.ICON;return i.fill({color:t.timeline.toolbar.icon}),i.rect(s.RECT1_X*e,s.TOP*e,s.WIDTH*e,s.HEIGHT*e),i.rect(s.RECT2_X*e,s.TOP*e,s.WIDTH*e,s.HEIGHT*e),i.fill(),i}static createFrameBackIcon(t,e=1){const i=new d.Graphics,{FRAME_STEP:s}=E.ICON;return i.fill({color:t.timeline.toolbar.icon}),i.moveTo(s.TRIANGLE1.BACK.LEFT*e,s.TOP*e),i.lineTo(s.TRIANGLE1.BACK.RIGHT*e,s.TRIANGLE1.BACK.MIDDLE*e),i.lineTo(s.TRIANGLE1.BACK.LEFT*e,s.BOTTOM*e),i.closePath(),i.moveTo(s.TRIANGLE2.BACK.LEFT*e,s.TOP*e),i.lineTo(s.TRIANGLE2.BACK.RIGHT*e,s.TRIANGLE2.BACK.MIDDLE*e),i.lineTo(s.TRIANGLE2.BACK.LEFT*e,s.BOTTOM*e),i.closePath(),i.fill(),i}static createFrameForwardIcon(t,e=1){const i=new d.Graphics,{FRAME_STEP:s}=E.ICON;return i.fill({color:t.timeline.toolbar.icon}),i.moveTo(s.TRIANGLE1.FORWARD.LEFT*e,s.TOP*e),i.lineTo(s.TRIANGLE1.FORWARD.RIGHT*e,s.TRIANGLE1.FORWARD.MIDDLE*e),i.lineTo(s.TRIANGLE1.FORWARD.LEFT*e,s.BOTTOM*e),i.closePath(),i.moveTo(s.TRIANGLE2.FORWARD.LEFT*e,s.TOP*e),i.lineTo(s.TRIANGLE2.FORWARD.RIGHT*e,s.TRIANGLE2.FORWARD.MIDDLE*e),i.lineTo(s.TRIANGLE2.FORWARD.LEFT*e,s.BOTTOM*e),i.closePath(),i.fill(),i}static updateIconColor(t,e){const i=t.getBounds();t.clear(),t.position.set(i.x,i.y)}}class ni extends d.Container{background;hoverBackground;icon;alternateIcon;state={isHovering:!1,isPressed:!1,isActive:!1};size;theme;onClick;constructor(t){super(),this.size=t.size||E.BUTTON_SIZE,this.theme=t.theme,this.onClick=t.onClick,this.eventMode="static",this.cursor="pointer",this.background=new d.Graphics,this.addChild(this.background),this.hoverBackground=new d.Graphics,this.addChild(this.hoverBackground);const i=this.size*.6,s=(this.size-i)/2;t.iconType&&(this.icon=ne.createIcon(t.iconType,this.theme,i),this.icon.position.set(s,s),this.addChild(this.icon)),t.alternateIconType&&(this.alternateIcon=ne.createIcon(t.alternateIconType,this.theme,i),this.alternateIcon.position.set(s,s),this.alternateIcon.visible=!1,this.addChild(this.alternateIcon)),this.setupEventListeners(),this.updateVisuals()}setupEventListeners(){this.on("pointerdown",this.handlePointerDown,this),this.on("pointerup",this.handlePointerUp,this),this.on("pointerupoutside",this.handlePointerUp,this),this.on("pointerover",this.handlePointerOver,this),this.on("pointerout",this.handlePointerOut,this)}handlePointerDown(){this.state.isPressed=!0,this.updateVisuals()}handlePointerUp(){this.state.isPressed&&this.onClick(),this.state.isPressed=!1,this.updateVisuals()}handlePointerOver(){this.state.isHovering=!0,this.updateVisuals()}handlePointerOut(){this.state.isHovering=!1,this.state.isPressed=!1,this.updateVisuals()}updateVisuals(){const t=E.BUTTON_HOVER_PADDING,e=this.size/2;this.background.clear(),this.background.circle(e,e,e),this.background.fill({color:this.theme.timeline.toolbar.surface,alpha:.8}),this.hoverBackground.clear(),this.hoverBackground.circle(e,e,e+t),this.state.isPressed?this.hoverBackground.fill({color:this.theme.timeline.toolbar.active,alpha:E.ACTIVE_ANIMATION_ALPHA}):this.state.isHovering?this.hoverBackground.fill({color:this.theme.timeline.toolbar.hover,alpha:E.HOVER_ANIMATION_ALPHA}):this.hoverBackground.fill({color:this.theme.timeline.toolbar.hover,alpha:0})}setActive(t){this.state.isActive=t,this.icon&&this.alternateIcon&&(this.icon.visible=!t,this.alternateIcon.visible=t)}updateTheme(t){this.theme=t;const i=this.size*.6,s=(this.size-i)/2;if(this.icon){const n=this.getIconType(this.icon);n&&(this.removeChild(this.icon),this.icon=ne.createIcon(n,t,i),this.icon.position.set(s,s),this.addChild(this.icon))}if(this.alternateIcon){const n=this.getIconType(this.alternateIcon);n&&(this.removeChild(this.alternateIcon),this.alternateIcon=ne.createIcon(n,t,i),this.alternateIcon.position.set(s,s),this.alternateIcon.visible=this.state.isActive,this.addChild(this.alternateIcon))}this.updateVisuals()}getIconType(t){return null}destroy(){this.removeAllListeners(),super.destroy()}}class dn extends d.Container{edit;theme;toolbarHeight;frameBackButton;playPauseButton;frameForwardButton;constructor(t,e,i){super(),this.edit=t,this.theme=e,this.toolbarHeight=i||36,this.createButtons(),this.subscribeToEditEvents(),this.updatePlayPauseState()}createButtons(){const t=this.calculateButtonSizes(),e=(t.playButton-t.regularButton)/2,i=(s,n,a,o)=>new ni({iconType:s,onClick:n,tooltip:a,theme:this.theme,size:o});this.frameBackButton=i("frame-back",()=>this.handleFrameBack(),"Previous frame",t.regularButton),this.frameBackButton.position.set(0,e),this.playPauseButton=new ni({iconType:"play",alternateIconType:"pause",onClick:()=>this.handlePlayPause(),tooltip:"Play/Pause",theme:this.theme,size:t.playButton}),this.playPauseButton.position.set(t.regularButton+t.spacing,0),this.frameForwardButton=i("frame-forward",()=>this.handleFrameForward(),"Next frame",t.regularButton),this.frameForwardButton.position.set(t.regularButton+t.spacing+t.playButton+t.spacing,e),this.addChild(this.frameBackButton,this.playPauseButton,this.frameForwardButton)}calculateButtonSizes(){const t=Math.round(this.toolbarHeight*.5);return{regularButton:t,playButton:Math.round(t*1.5),spacing:Math.round(this.toolbarHeight*.15)}}handleFrameBack(){this.edit.seek(this.edit.playbackTime-E.FRAME_TIME_MS)}handlePlayPause(){this.edit.isPlaying?this.edit.pause():this.edit.play()}handleFrameForward(){this.edit.seek(this.edit.playbackTime+E.FRAME_TIME_MS)}subscribeToEditEvents(){this.edit.events.on("playback:play",this.updatePlayPauseState),this.edit.events.on("playback:pause",this.updatePlayPauseState)}updatePlayPauseState=()=>{this.playPauseButton.setActive(this.edit.isPlaying)};update(){}resize(t){}updateTheme(t){this.theme=t,this.frameBackButton.updateTheme(t),this.playPauseButton.updateTheme(t),this.frameForwardButton.updateTheme(t)}destroy(){this.edit.events.off("playback:play",this.updatePlayPauseState),this.edit.events.off("playback:pause",this.updatePlayPauseState),this.frameBackButton.destroy(),this.playPauseButton.destroy(),this.frameForwardButton.destroy(),super.destroy()}getWidth(){const t=this.calculateButtonSizes();return t.regularButton*2+t.playButton+t.spacing*2}}class un extends d.Container{edit;theme;timeText;formatOptions;constructor(t,e,i={}){super(),this.edit=t,this.theme=e,this.formatOptions={showMilliseconds:!1,showHours:!1,...i},this.createDisplay(),this.subscribeToEditEvents(),this.updateTimeDisplay()}createDisplay(){const t=new d.TextStyle({fontFamily:E.TIME_DISPLAY.FONT_FAMILY,fontSize:E.TIME_DISPLAY.FONT_SIZE,fill:this.theme.timeline.toolbar.text});this.timeText=new d.Text("0:00 / 0:00",t),this.timeText.anchor.set(0,.5),this.addChild(this.timeText)}subscribeToEditEvents(){this.edit.events.on("playback:time",this.updateTimeDisplay),this.edit.events.on("duration:changed",this.updateTimeDisplay)}updateTimeDisplay=()=>{const t=this.formatTime(this.edit.playbackTime/1e3),e=this.formatTime(this.edit.getTotalDuration()/1e3);this.timeText.text=`${t} / ${e}`};formatTime(t){const e=Math.floor(t/3600),i=Math.floor(t%3600/60),s=Math.floor(t%60),n=Math.floor(t%1*10);let a="";return this.formatOptions.showHours||e>0?a+=`${e}:${i.toString().padStart(2,"0")}`:a+=`${i}`,a+=`:${s.toString().padStart(2,"0")}`,this.formatOptions.showMilliseconds?a+=`.${n}`:a+=`.${n}`,a}update(){this.updateTimeDisplay()}resize(t){}updateTheme(t){this.theme=t,this.timeText.style.fill=t.timeline.toolbar.text}destroy(){this.edit.events.off("playback:time",this.updateTimeDisplay),this.edit.events.off("duration:changed",this.updateTimeDisplay),super.destroy()}getWidth(){return this.timeText.width}}class pn extends d.Container{edit;theme;cutButton;cutButtonBackground;cutButtonText;constructor(t,e){super(),this.edit=t,this.theme=e,this.createCutButton()}createCutButton(){this.cutButton=new d.Container,this.cutButton.eventMode="static",this.cutButton.cursor="pointer";const{WIDTH:t,HEIGHT:e,FONT_SIZE:i}=E.CUT_BUTTON;this.cutButtonBackground=new d.Graphics,this.cutButtonBackground.roundRect(0,0,t,e,E.BORDER_RADIUS),this.cutButtonBackground.fill({color:this.theme.timeline.toolbar.surface||4473924}),this.cutButtonBackground.stroke({color:this.theme.timeline.tracks.border||6710886,width:1}),this.cutButton.addChild(this.cutButtonBackground);const s=new d.TextStyle({fontFamily:"Arial",fontSize:i,fill:this.theme.timeline.toolbar.text||16777215});this.cutButtonText=new d.Text("SPLIT",s),this.cutButtonText.anchor.set(.5),this.cutButtonText.position.set(t/2,e/2),this.cutButton.addChild(this.cutButtonText),this.cutButton.on("click",this.handleCutClick,this),this.cutButton.on("pointerdown",this.handlePointerDown,this),this.cutButton.on("pointerover",this.handlePointerOver,this),this.cutButton.on("pointerout",this.handlePointerOut,this),this.addChild(this.cutButton)}handleCutClick=t=>{t.stopPropagation(),this.performCutClip()};handlePointerDown=t=>{t.stopPropagation(),this.updateButtonVisual(!0,!1)};handlePointerOver=()=>{this.updateButtonVisual(!1,!0)};handlePointerOut=()=>{this.updateButtonVisual(!1,!1)};updateButtonVisual(t,e){this.cutButtonBackground.clear(),this.cutButtonBackground.roundRect(0,0,E.CUT_BUTTON.WIDTH,E.CUT_BUTTON.HEIGHT,E.BORDER_RADIUS);let i=this.theme.timeline.toolbar.surface||4473924;const s=1;t?i=this.theme.timeline.toolbar.active||3355443:e&&(i=this.theme.timeline.toolbar.hover||5592405),this.cutButtonBackground.fill({color:i,alpha:s}),this.cutButtonBackground.stroke({color:this.theme.timeline.tracks.border||6710886,width:1})}performCutClip(){const t=this.edit.getSelectedClipInfo();if(!t)return;const{trackIndex:e,clipIndex:i}=t,s=this.edit.playbackTime/1e3;this.edit.splitClip(e,i,s)}update(){const t=this.edit.getSelectedClipInfo()!==null;this.cutButton.alpha=t?1:.5,this.cutButton.eventMode=t?"static":"none",this.cutButton.cursor=t?"pointer":"default"}resize(t){}updateTheme(t){this.theme=t,this.updateButtonVisual(!1,!1),this.cutButtonText.style.fill=t.timeline.toolbar.text||16777215}destroy(){this.cutButton.removeAllListeners(),super.destroy()}getWidth(){return E.CUT_BUTTON.WIDTH}}class fn{config;constructor(t,e){this.config={width:t,height:e,buttonSize:Math.round(e*.5),buttonSpacing:Math.round(e*.15),edgeMargin:E.EDGE_MARGIN}}getPlaybackControlsPosition(){const t=this.calculatePlaybackControlsWidth(),e=(this.config.width-t)/2,i=(this.config.height-this.getMaxButtonHeight())/2;return{x:e,y:i}}getMaxButtonHeight(){const t=this.config.buttonSize;return Math.round(t*1.5)}getTimeDisplayPosition(t){const i=(this.config.width-t)/2+t+E.TEXT_SPACING,s=this.config.height/2;return{x:i,y:s}}getEditControlsPosition(){const t=this.config.width-E.CUT_BUTTON.WIDTH-this.config.edgeMargin,e=(this.config.height-E.CUT_BUTTON.HEIGHT)/2;return{x:t,y:e}}calculatePlaybackControlsWidth(){const t=this.config.buttonSize,e=Math.round(t*1.5);return t*2+e+this.config.buttonSpacing*2}updateWidth(t){this.config.width=t}getConfig(){return{...this.config}}}class gn extends d.Container{constructor(t,e,i,s){super(),this.edit=t,this.theme=e,this.layout=i,this.toolbarWidth=s,this.toolbarHeight=i.toolbarHeight,this.position.set(0,i.toolbarY),this.toolbarLayout=new fn(s,this.toolbarHeight),this.createBackground(),this.createComponents(),this.positionComponents(),this.subscribeToEditEvents()}background;playbackControls;timeDisplay;editControls;toolbarLayout;toolbarWidth;toolbarHeight;get width(){return this.toolbarWidth}get height(){return this.toolbarHeight}createBackground(){this.background=new d.Graphics,this.drawBackground(),this.addChild(this.background)}drawBackground(){this.background.clear(),this.background.rect(0,0,this.toolbarWidth,this.toolbarHeight),this.background.fill({color:this.theme.timeline.toolbar.background}),this.background.setStrokeStyle({width:1,color:this.theme.timeline.toolbar.divider,alpha:E.DIVIDER_ALPHA}),this.background.moveTo(0,this.toolbarHeight-.5),this.background.lineTo(this.toolbarWidth,this.toolbarHeight-.5),this.background.stroke()}createComponents(){this.playbackControls=new dn(this.edit,this.theme,this.toolbarHeight),this.addChild(this.playbackControls),this.timeDisplay=new un(this.edit,this.theme),this.addChild(this.timeDisplay),this.editControls=new pn(this.edit,this.theme),this.addChild(this.editControls)}positionComponents(){const t=this.toolbarLayout.getPlaybackControlsPosition();this.playbackControls.position.set(t.x,t.y);const e=this.toolbarLayout.getTimeDisplayPosition(this.playbackControls.getWidth());this.timeDisplay.position.set(e.x,e.y);const i=this.toolbarLayout.getEditControlsPosition();this.editControls.position.set(i.x,i.y)}subscribeToEditEvents(){this.edit.events.on("clip:selected",this.updateEditControls),this.edit.events.on("selection:cleared",this.updateEditControls)}updateEditControls=()=>{this.editControls.update()};resize(t){this.toolbarWidth=t,this.toolbarLayout.updateWidth(t),this.drawBackground(),this.positionComponents(),this.playbackControls.resize(t),this.timeDisplay.resize(t),this.editControls.resize(t)}updateTheme(t){this.theme=t,this.drawBackground(),this.playbackControls.updateTheme(t),this.timeDisplay.updateTheme(t),this.editControls.updateTheme(t)}updateTimeDisplay=()=>{this.timeDisplay.update()};destroy(){this.edit.events.off("clip:selected",this.updateEditControls),this.edit.events.off("selection:cleared",this.updateEditControls),this.playbackControls.destroy(),this.timeDisplay.destroy(),this.editControls.destroy(),super.destroy()}}class mn{constructor(t,e,i,s,n,a){this.edit=t,this.layout=e,this.renderer=i,this.viewportManager=s,this.eventHandler=n,this.getTimelineContext=a}toolbar;ruler;playhead;scroll;async setupTimelineFeatures(t,e,i,s,n){this.toolbar=new gn(this.edit,t,this.layout,i),this.renderer.getStage().addChild(this.toolbar);const a={pixelsPerSecond:e,timelineDuration:n,rulerHeight:this.layout.rulerHeight,theme:t};this.ruler=new ii(a),await this.ruler.load(),this.ruler.getContainer().y=this.layout.rulerY,this.viewportManager.getRulerViewport().addChild(this.ruler.getContainer()),this.ruler.events.on("ruler:seeked",this.eventHandler.handleSeek.bind(this.eventHandler));const o={pixelsPerSecond:e,timelineHeight:s,theme:t};this.playhead=new si(o),await this.playhead.load(),this.playhead.getContainer().y=this.layout.rulerY,this.viewportManager.getPlayheadContainer().addChild(this.playhead.getContainer()),this.playhead.events.on("playhead:seeked",this.eventHandler.handleSeek.bind(this.eventHandler));const l={timeline:this.getTimelineContext()};this.scroll=new hn(l),await this.scroll.initialize(),this.viewportManager.updateViewportTransform()}recreateTimelineFeatures(t,e,i,s){if(this.ruler){this.ruler.dispose();const n=t.dimensions?.rulerHeight||this.layout.rulerHeight,a={pixelsPerSecond:e,timelineDuration:s,rulerHeight:n,theme:t};this.ruler=new ii(a),this.ruler.load(),this.ruler.getContainer().y=this.layout.rulerY,this.viewportManager.getRulerViewport().addChild(this.ruler.getContainer()),this.ruler.events.on("ruler:seeked",this.eventHandler.handleSeek.bind(this.eventHandler))}if(this.playhead){this.playhead.dispose();const n={pixelsPerSecond:e,timelineHeight:i,theme:t};this.playhead=new si(n),this.playhead.load(),this.playhead.getContainer().y=this.layout.rulerY,this.viewportManager.getPlayheadContainer().addChild(this.playhead.getContainer()),this.playhead.events.on("playhead:seeked",this.eventHandler.handleSeek.bind(this.eventHandler))}}updateRuler(t,e){this.ruler.updateRuler(t,e)}updatePlayhead(t,e){this.playhead&&this.playhead.updatePlayhead(t,e)}getFeatures(){return{toolbar:this.toolbar,ruler:this.ruler,playhead:this.playhead,scroll:this.scroll}}getToolbar(){return this.toolbar}getPlayhead(){return this.playhead}dispose(){this.toolbar&&this.toolbar.destroy(),this.ruler&&this.ruler.dispose(),this.playhead&&this.playhead.dispose(),this.scroll&&this.scroll.dispose()}}class tt{constructor(t,e){this.options=t,this.theme=e,this.config=this.calculateLayout()}static TOOLBAR_HEIGHT_RATIO=G.TOOLBAR_HEIGHT_RATIO;static RULER_HEIGHT_RATIO=G.RULER_HEIGHT_RATIO;static TOOLBAR_HEIGHT_DEFAULT=G.TOOLBAR_HEIGHT_DEFAULT;static RULER_HEIGHT_DEFAULT=G.RULER_HEIGHT_DEFAULT;static TRACK_HEIGHT_DEFAULT=G.TRACK_HEIGHT_DEFAULT;static CLIP_PADDING=G.CLIP_PADDING;static BORDER_WIDTH=G.BORDER_WIDTH;static CORNER_RADIUS=G.CORNER_RADIUS;static LABEL_PADDING=G.LABEL_PADDING;static TRACK_PADDING=G.TRACK_PADDING;config;calculateLayout(){const t=this.options.height;let e=this.theme?.timeline.toolbar.height||Math.round(t*tt.TOOLBAR_HEIGHT_RATIO),i=this.theme?.timeline.ruler.height||Math.round(t*tt.RULER_HEIGHT_RATIO);e=Math.max(e,tt.TOOLBAR_HEIGHT_DEFAULT),i=Math.max(i,tt.RULER_HEIGHT_DEFAULT);const{trackHeight:s}=this.options;return{toolbarHeight:e,rulerHeight:i,trackHeight:s,toolbarY:0,rulerY:e,tracksY:e+i,gridY:e+i,playheadY:e,viewportY:e+i}}get toolbarHeight(){return this.config.toolbarHeight}get toolbarY(){return this.config.toolbarY}get rulerHeight(){return this.config.rulerHeight}get trackHeight(){return this.config.trackHeight}get rulerY(){return this.config.rulerY}get tracksY(){return this.config.tracksY}get gridY(){return this.config.gridY}get playheadY(){return this.config.playheadY}get viewportY(){return this.config.viewportY}positionTrack(t){return t*this.trackHeight}positionClip(t){return t*this.options.pixelsPerSecond}calculateClipWidth(t){return Math.max(G.MIN_CLIP_WIDTH,t*this.options.pixelsPerSecond)}calculateDropPosition(t,e){const i=e-this.tracksY,s=Math.floor(i/this.trackHeight),n=Math.max(0,t/this.options.pixelsPerSecond);return{track:Math.max(0,s),time:n,x:t,y:i}}getTrackAtY(t){const e=t-this.tracksY;return Math.floor(e/this.trackHeight)}getTimeAtX(t){return t/this.options.pixelsPerSecond}getXAtTime(t){return t*this.options.pixelsPerSecond}getYAtTrack(t){return this.tracksY+t*this.trackHeight}getGridHeight(){return this.options.height-this.toolbarHeight-this.rulerHeight}getRulerWidth(){return this.options.width}getGridWidth(){return this.options.width}calculateViewportPosition(t,e){return{x:-t,y:this.viewportY-e}}updateOptions(t,e){this.options=t,this.theme=e,this.config=this.calculateLayout()}isPointInToolbar(t,e){return e>=this.toolbarY&&e<=this.toolbarY+this.toolbarHeight}isPointInRuler(t,e){return e>=this.rulerY&&e<=this.rulerY+this.rulerHeight}isPointInTracks(t,e){return e>=this.tracksY&&e<=this.options.height}getVisibleTrackRange(t,e){const i=t,s=Math.floor(i/this.trackHeight),n=Math.ceil((i+e)/this.trackHeight);return{start:Math.max(0,s),end:Math.max(0,n)}}}class Y{constructor(t,e,i,s){this.layout=i,this.onResize=s,this.width=t.width,this.height=t.height,this.pixelsPerSecond=50;const n=e.timeline.tracks.height||tt.TRACK_HEIGHT_DEFAULT;this.trackHeight=Math.max(40,n),this.backgroundColor=e.timeline.background,this.antialias=!0,this.resolution=window.devicePixelRatio||1}pixelsPerSecond;trackHeight;backgroundColor;antialias;resolution;width;height;static MIN_PIXELS_PER_SECOND=10;static MAX_PIXELS_PER_SECOND=500;static ZOOM_FACTOR=1.1;getOptions(){return{width:this.width,height:this.height,pixelsPerSecond:this.pixelsPerSecond,trackHeight:this.trackHeight,backgroundColor:this.backgroundColor,antialias:this.antialias,resolution:this.resolution}}setOptions(t){t.width!==void 0&&(this.width=t.width,this.onResize&&this.onResize(this.width)),t.height!==void 0&&(this.height=t.height),t.pixelsPerSecond!==void 0&&(this.pixelsPerSecond=t.pixelsPerSecond),t.trackHeight!==void 0&&(this.trackHeight=t.trackHeight),t.backgroundColor!==void 0&&(this.backgroundColor=t.backgroundColor),t.antialias!==void 0&&(this.antialias=t.antialias),t.resolution!==void 0&&(this.resolution=t.resolution),this.layout.updateOptions(this.getOptions())}updateFromTheme(t){this.backgroundColor=t.timeline.background;const e=t.timeline.tracks.height||tt.TRACK_HEIGHT_DEFAULT;this.trackHeight=Math.max(40,e),this.layout.updateOptions(this.getOptions(),t)}getWidth(){return this.width}getHeight(){return this.height}getPixelsPerSecond(){return this.pixelsPerSecond}getTrackHeight(){return this.trackHeight}getBackgroundColor(){return this.backgroundColor}getAntialias(){return this.antialias}getResolution(){return this.resolution}zoomIn(){const t=Math.min(this.pixelsPerSecond*Y.ZOOM_FACTOR,Y.MAX_PIXELS_PER_SECOND);this.setPixelsPerSecond(t)}zoomOut(){const t=Math.max(this.pixelsPerSecond/Y.ZOOM_FACTOR,Y.MIN_PIXELS_PER_SECOND);this.setPixelsPerSecond(t)}setPixelsPerSecond(t){this.pixelsPerSecond=Math.max(Y.MIN_PIXELS_PER_SECOND,Math.min(Y.MAX_PIXELS_PER_SECOND,t)),this.layout.updateOptions(this.getOptions())}canZoomIn(){return this.pixelsPerSecond<Y.MAX_PIXELS_PER_SECOND}canZoomOut(){return this.pixelsPerSecond>Y.MIN_PIXELS_PER_SECOND}}class ke extends nt{constructor(t,e,i){super(),this.edit=t,this.theme=ti.resolveTheme(i),this.layout=new tt({width:e.width,height:e.height,pixelsPerSecond:50,trackHeight:Math.max(40,this.theme.timeline.tracks.height||tt.TRACK_HEIGHT_DEFAULT),backgroundColor:this.theme.timeline.background,antialias:!0,resolution:window.devicePixelRatio||1},this.theme),this.optionsManager=new Y(e,this.theme,this.layout,s=>this.featureManager?.getToolbar()?.resize(s)),this.initializeManagers(),this.setupInteraction()}currentEditType=null;layout;theme;lastPlaybackTime=0;static TIMELINE_BUFFER_MULTIPLIER=1.5;interaction;dragPreviewManager;viewportManager;visualTrackManager;eventHandler;renderer;featureManager;optionsManager;initializeManagers(){const t=this.optionsManager.getOptions();this.renderer=new cn({width:t.width||800,height:t.height||600,backgroundColor:t.backgroundColor||0,antialias:t.antialias??!0,resolution:t.resolution||window.devicePixelRatio||1},(e,i)=>this.update(e,i)),this.eventHandler=new ln(this.edit,{onEditChange:this.handleEditChange.bind(this),onSeek:e=>this.edit.seek(e),onClipSelected:(e,i)=>this.visualTrackManager.updateVisualSelection(e,i),onSelectionCleared:()=>this.visualTrackManager.clearVisualSelection(),onDragStarted:(e,i)=>{const s=this.getClipData(e,i);s&&this.dragPreviewManager.showDragPreview(e,i,s)},onDragEnded:()=>this.dragPreviewManager.hideDragPreview()}),this.eventHandler.setupEventListeners()}async load(){await this.renderer.initializePixiApp(),await this.renderer.setupRenderLayers(),await this.setupViewport(),await this.setupTimelineFeatures(),this.interaction.activate();try{const t=this.edit.getEdit();t&&(this.currentEditType=t,await this.rebuildFromEdit(t))}catch{}this.renderer.startAnimationLoop()}async setupViewport(){this.viewportManager=new en(this.layout,this.renderer.getTrackLayer(),this.renderer.getOverlayLayer(),this.getContainer(),()=>this.renderer.render()),await this.viewportManager.setupViewport(),this.visualTrackManager=new on(this.getContainer(),this.layout,this.theme,()=>this.optionsManager.getPixelsPerSecond(),()=>this.getExtendedTimelineWidth()),this.dragPreviewManager=new tn(this.getContainer(),this.layout,()=>this.optionsManager.getPixelsPerSecond(),()=>this.optionsManager.getTrackHeight(),()=>this.visualTrackManager.getVisualTracks()),this.featureManager=new mn(this.edit,this.layout,this.renderer,this.viewportManager,this.eventHandler,()=>this)}async setupTimelineFeatures(){const t=this.getExtendedTimelineDuration();await this.featureManager.setupTimelineFeatures(this.theme,this.optionsManager.getPixelsPerSecond(),this.optionsManager.getWidth(),this.optionsManager.getHeight(),t)}recreateTimelineFeatures(){const t=this.getExtendedTimelineDuration();this.featureManager.recreateTimelineFeatures(this.theme,this.optionsManager.getPixelsPerSecond(),this.optionsManager.getHeight(),t)}setScroll(t,e){this.viewportManager.setScroll(t,e)}setZoom(t){this.viewportManager.setZoom(t)}getViewport(){return this.viewportManager.getViewport()}getPixiApp(){return this.renderer.getApp()}getTrackLayer(){return this.renderer.getTrackLayer()}getOverlayLayer(){return this.renderer.getOverlayLayer()}getClipData(t,e){return this.currentEditType?.timeline?.tracks&&this.currentEditType.timeline.tracks[t]?.clips?.[e]||null}getLayout(){return this.layout}getVisualTracks(){return this.visualTrackManager.getVisualTracks()}getEdit(){return this.edit}getExtendedTimelineWidth(){const t=this.getExtendedTimelineDuration()*this.optionsManager.getPixelsPerSecond(),e=this.optionsManager.getWidth();return Math.max(t,e)}hideDragGhost(){this.dragPreviewManager.hideDragGhost()}showDragGhost(t,e,i){this.dragPreviewManager.showDragGhost(t,e,i)}setPlayheadTime(t){this.featureManager.getPlayhead().setTime(t)}getPlayheadTime(){return this.featureManager.getPlayhead().getTime()}getActualEditDuration(){return this.edit.totalDuration/1e3||60}setupInteraction(){this.interaction=new Js(this)}async handleEditChange(t){this.dragPreviewManager.hideDragPreview();const e=t||this.edit.getEdit();e&&(this.currentEditType=e,this.updateRulerDuration(),this.clearAllVisualState(),await this.rebuildFromEdit(e))}getExtendedTimelineDuration(){const t=this.edit.totalDuration/1e3||60;return Math.max(60,t*ke.TIMELINE_BUFFER_MULTIPLIER)}updateRulerDuration(){const t=this.getExtendedTimelineDuration(),e=this.getExtendedTimelineWidth();this.featureManager.updateRuler(this.optionsManager.getPixelsPerSecond(),t),this.visualTrackManager.updateTrackWidths(e)}clearAllVisualState(){this.dragPreviewManager.hideDragPreview(),this.visualTrackManager.clearAllVisualState()}async rebuildFromEdit(t){await this.visualTrackManager.rebuildFromEdit(t,this.optionsManager.getPixelsPerSecond()),this.renderer.render()}findClipAtPosition(t,e){return this.currentEditType?this.visualTrackManager.findClipAtPosition(t,e):null}setTheme(t){this.theme=ti.resolveTheme(t),this.optionsManager.updateFromTheme(this.theme),this.featureManager.getToolbar()&&this.featureManager.getToolbar().updateTheme(this.theme),this.recreateTimelineFeatures(),this.currentEditType&&(this.clearAllVisualState(),this.rebuildFromEdit(this.currentEditType)),this.renderer.updateBackgroundColor(this.optionsManager.getBackgroundColor()),this.renderer.render()}getTheme(){return this.theme}getCurrentEditType(){return this.currentEditType}getOptions(){return this.optionsManager.getOptions()}setOptions(t){this.optionsManager.setOptions(t)}update(t,e){(this.edit.isPlaying||this.lastPlaybackTime!==this.edit.playbackTime)&&(this.featureManager.getPlayhead().setTime(this.edit.playbackTime/1e3),this.lastPlaybackTime=this.edit.playbackTime,this.featureManager.getToolbar()&&this.featureManager.getToolbar().updateTimeDisplay())}draw(){this.renderer.draw()}getTimeDisplay(){return this.featureManager.getToolbar()}updateTime(t,e){this.setPlayheadTime(t),e&&this.edit.seek(t*1e3)}get timeRange(){return{startTime:0,endTime:this.getExtendedTimelineDuration()}}get viewportHeight(){return this.optionsManager.getHeight()}get zoomLevelIndex(){const t=this.viewportManager.getViewport();return Math.round(Math.log2(t.zoom)+5)}zoomIn(){this.optionsManager.zoomIn(),this.onZoomChanged()}zoomOut(){this.optionsManager.zoomOut(),this.onZoomChanged()}onZoomChanged(){const t=this.optionsManager.getPixelsPerSecond();this.visualTrackManager.updatePixelsPerSecond(t);const e=this.getExtendedTimelineWidth();this.visualTrackManager.updateTrackWidths(e),this.featureManager.updateRuler(t,this.getExtendedTimelineDuration()),this.featureManager.updatePlayhead(t,this.optionsManager.getHeight()),this.renderer.render()}dispose(){this.dragPreviewManager.dispose(),this.visualTrackManager.dispose(),this.eventHandler.dispose(),this.featureManager.dispose(),this.interaction&&this.interaction.dispose(),this.renderer.dispose()}}H.Canvas=gt,H.Controls=Us,H.Edit=bt,H.Timeline=ke,H.VideoExporter=Zs,Object.defineProperty(H,Symbol.toStringTag,{value:"Module"})});
182
+ const DOUBLE_PI: f32 = 3.14159265358979323846264 * 2.;`,Qn=Object.defineProperty,Jn=(s,e,t)=>e in s?Qn(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,pt=(s,e,t)=>(Jn(s,typeof e!="symbol"?e+"":e,t),t);const oi=class kt extends Be.Filter{constructor(...e){let t=e[0]??{};typeof t=="number"&&(Be.deprecation("6.0.0","OutlineFilter constructor params are now options object. See params: { thickness, color, quality, alpha, knockout }"),t={thickness:t},e[1]!==void 0&&(t.color=e[1]),e[2]!==void 0&&(t.quality=e[2]),e[3]!==void 0&&(t.alpha=e[3]),e[4]!==void 0&&(t.knockout=e[4])),t={...kt.DEFAULT_OPTIONS,...t};const i=t.quality??.1,r=Be.GpuProgram.from({vertex:{source:qn,entryPoint:"mainVertex"},fragment:{source:Yn,entryPoint:"mainFragment"}}),n=Be.GlProgram.from({vertex:Kn,fragment:Xn.replace(/\$\{ANGLE_STEP\}/,kt.getAngleStep(i).toFixed(7)),name:"outline-filter"});super({gpuProgram:r,glProgram:n,resources:{outlineUniforms:{uThickness:{value:new Float32Array(2),type:"vec2<f32>"},uColor:{value:new Float32Array(3),type:"vec3<f32>"},uAlpha:{value:t.alpha,type:"f32"},uAngleStep:{value:0,type:"f32"},uKnockout:{value:t.knockout?1:0,type:"f32"}}}}),pt(this,"uniforms"),pt(this,"_thickness"),pt(this,"_quality"),pt(this,"_color"),this.uniforms=this.resources.outlineUniforms.uniforms,this.uniforms.uAngleStep=kt.getAngleStep(i),this._color=new Be.Color,this.color=t.color??0,Object.assign(this,t)}apply(e,t,i,r){this.uniforms.uThickness[0]=this.thickness/t.source.width,this.uniforms.uThickness[1]=this.thickness/t.source.height,e.applyFilter(this,t,i,r)}static getAngleStep(e){return parseFloat((Math.PI*2/Math.max(e*kt.MAX_SAMPLES,kt.MIN_SAMPLES)).toFixed(7))}get thickness(){return this._thickness}set thickness(e){this._thickness=this.padding=e}get color(){return this._color.value}set color(e){this._color.setValue(e);const[t,i,r]=this._color.toArray();this.uniforms.uColor[0]=t,this.uniforms.uColor[1]=i,this.uniforms.uColor[2]=r}get alpha(){return this.uniforms.uAlpha}set alpha(e){this.uniforms.uAlpha=e}get quality(){return this._quality}set quality(e){this._quality=e,this.uniforms.uAngleStep=kt.getAngleStep(e)}get knockout(){return this.uniforms.uKnockout===1}set knockout(e){this.uniforms.uKnockout=e?1:0}};pt(oi,"DEFAULT_OPTIONS",{thickness:1,color:0,alpha:1,quality:.1,knockout:!1}),pt(oi,"MIN_SAMPLES",1),pt(oi,"MAX_SAMPLES",100);let Fi=oi;class ea extends we{background;text;constructor(e,t){super(e,t),this.background=null,this.text=null}async load(){await super.load();const e=this.clipConfiguration.asset,t=await this.parseDocument();if(!t)return;const i=new R.Graphics;t.background.color&&(i.fillStyle={color:t.background.color,alpha:t.background.opacity??1},i.rect(0,0,e.width??this.edit.size.width,e.height??this.edit.size.height),i.fill());const r=new R.Text;r.text=t.text;const{horizontal:n,vertical:o}=t.alignment;r.style={fontFamily:t.font?.family??"Open Sans",fontSize:t.font?.size??32,fill:t.font?.color??"#ffffff",fontWeight:(t.font?.weight??"400").toString(),wordWrap:!0,wordWrapWidth:e.width??this.edit.size.width,lineHeight:(t.font?.lineHeight??1)*(t.font?.size??32),align:n};let a=(e.width??this.edit.size.width)/2-r.width/2,p=(e.height??this.edit.size.height)/2-r.height/2;if(n==="left"&&(a=0),n==="right"&&(a=(e.width??this.edit.size.width)-r.width),o==="top"&&(p=0),o==="bottom"&&(p=(e.height??this.edit.size.height)-r.height),r.position={x:a,y:p},t.stroke.color&&t.stroke.width){const m=new Fi({thickness:t.stroke.width,color:t.stroke.color});r.filters=[m]}this.background=i,this.text=r,this.contentContainer.addChild(i),this.contentContainer.addChild(r),this.configureKeyframes()}update(e,t){super.update(e,t)}draw(){super.draw()}dispose(){super.dispose(),this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null}getSize(){const e=this.clipConfiguration.asset;return{width:e.width??this.edit.size.width,height:e.height??this.edit.size.height}}getFitScale(){return 1}async parseDocument(){const e=this.clipConfiguration.asset,{html:t,css:i,position:r}=e;if(!t.includes('data-html-type="text"'))return console.warn("Unsupported html format."),null;const o=new DOMParser().parseFromString(t,"text/html").body.textContent??"",p=(await new CSSStyleSheet().replace(i)).cssRules[0],m={text:o,font:{},alignment:{},background:{},stroke:{}};if(p?.constructor.name!=="CSSStyleRule"||!("style"in p))return console.warn("Unsupported css format."),m;const d=p.style,l=this.parseAlignment(r??"center");m.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},m.alignment=l;let c="";return d.background.length&&(c=d.background),d.backgroundColor.length&&(c=d.backgroundColor),m.background={color:c.length?c:void 0,opacity:d.opacity.length?parseInt(d.opacity,10):void 0},m.stroke={width:d.strokeWidth.length?parseInt(d.strokeWidth,10):void 0,color:d.stroke.length?d.stroke:void 0},m}parseAlignment(e){switch(e){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 ta extends we{texture;sprite;originalSize;constructor(e,t){super(e,t),this.texture=null,this.sprite=null,this.originalSize=null}async load(){await super.load();const e=this.clipConfiguration.asset,t=e.src,i={src:t,crossovern:"anonymous",data:{}},r=await this.edit.assetLoader.load(t,i);if(!(r?.source instanceof R.ImageSource))throw new Error(`Invalid image source '${e.src}'.`);this.texture=this.createCroppedTexture(r),this.sprite=new R.Sprite(this.texture),this.contentContainer.addChild(this.sprite),this.clipConfiguration.width&&this.clipConfiguration.height&&this.applyFixedDimensions(),this.configureKeyframes()}update(e,t){super.update(e,t)}draw(){super.draw()}dispose(){super.dispose(),this.sprite?.destroy(),this.sprite=null,this.texture?.destroy(),this.texture=null,this.originalSize=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}}createCroppedTexture(e){const t=this.clipConfiguration.asset;if(!t.crop)return e;const i=e.width,r=e.height,n=Math.floor((t.crop?.left??0)*i),o=Math.floor((t.crop?.right??0)*i),a=Math.floor((t.crop?.top??0)*r),p=Math.floor((t.crop?.bottom??0)*r),m=n,d=a,l=i-n-o,c=r-a-p,u=new R.Rectangle(m,d,l,c);return new R.Texture({source:e.source,frame:u})}}class Fs extends we{texture;sprite;isPlaying;constructor(e,t){super(e,t),this.texture=null,this.sprite=null,this.isPlaying=!1}async load(){await super.load();const e=this.clipConfiguration.asset,t=e.src,i={src:t,data:{autoPlay:!1,muted:!0}},r=await this.edit.assetLoader.load(t,i);if(!(r?.source instanceof R.ImageSource||r?.source instanceof R.VideoSource))throw new Error(`Invalid luma source '${e.src}'.`);this.texture=r,this.sprite=new R.Sprite(this.texture),this.contentContainer.addChild(this.sprite),this.configureKeyframes()}update(e,t){if(super.update(e,t),!this.texture||!(this.texture.source instanceof R.VideoSource))return;const i=this.getPlaybackTime(),r=this.edit.isPlaying&&this.isActive();r&&(this.isPlaying||(this.isPlaying=!0,this.texture.source.resource.currentTime=i/1e3,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*1e3-i)>100&&(this.texture.source.resource.currentTime=i/1e3)),!r&&this.isPlaying&&(this.isPlaying=!1,this.texture.source.resource.pause()),!this.edit.isPlaying&&this.isActive()&&(this.texture.source.resource.currentTime=i/1e3)}draw(){super.draw()}dispose(){super.dispose(),this.sprite?.destroy(),this.sprite=null,this.texture?.destroy(),this.texture=null}getSize(){return{width:this.sprite?.width??0,height:this.sprite?.height??0}}getVolume(){return 0}getMask(){return this.sprite}}var oe;(function(s){s.assertEqual=r=>{};function e(r){}s.assertIs=e;function t(r){throw new Error}s.assertNever=t,s.arrayToEnum=r=>{const n={};for(const o of r)n[o]=o;return n},s.getValidEnumValues=r=>{const n=s.objectKeys(r).filter(a=>typeof r[r[a]]!="number"),o={};for(const a of n)o[a]=r[a];return s.objectValues(o)},s.objectValues=r=>s.objectKeys(r).map(function(n){return r[n]}),s.objectKeys=typeof Object.keys=="function"?r=>Object.keys(r):r=>{const n=[];for(const o in r)Object.prototype.hasOwnProperty.call(r,o)&&n.push(o);return n},s.find=(r,n)=>{for(const o of r)if(n(o))return o},s.isInteger=typeof Number.isInteger=="function"?r=>Number.isInteger(r):r=>typeof r=="number"&&Number.isFinite(r)&&Math.floor(r)===r;function i(r,n=" | "){return r.map(o=>typeof o=="string"?`'${o}'`:o).join(n)}s.joinValues=i,s.jsonStringifyReplacer=(r,n)=>typeof n=="bigint"?n.toString():n})(oe||(oe={}));var Ms;(function(s){s.mergeShapes=(e,t)=>({...e,...t})})(Ms||(Ms={}));const j=oe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),et=s=>{switch(typeof s){case"undefined":return j.undefined;case"string":return j.string;case"number":return Number.isNaN(s)?j.nan:j.number;case"boolean":return j.boolean;case"function":return j.function;case"bigint":return j.bigint;case"symbol":return j.symbol;case"object":return Array.isArray(s)?j.array:s===null?j.null:s.then&&typeof s.then=="function"&&s.catch&&typeof s.catch=="function"?j.promise:typeof Map<"u"&&s instanceof Map?j.map:typeof Set<"u"&&s instanceof Set?j.set:typeof Date<"u"&&s instanceof Date?j.date:j.object;default:return j.unknown}},M=oe.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class qe extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};const t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(n){return n.message},i={_errors:[]},r=n=>{for(const o of n.issues)if(o.code==="invalid_union")o.unionErrors.map(r);else if(o.code==="invalid_return_type")r(o.returnTypeError);else if(o.code==="invalid_arguments")r(o.argumentsError);else if(o.path.length===0)i._errors.push(t(o));else{let a=i,p=0;for(;p<o.path.length;){const m=o.path[p];p===o.path.length-1?(a[m]=a[m]||{_errors:[]},a[m]._errors.push(t(o))):a[m]=a[m]||{_errors:[]},a=a[m],p++}}};return r(this),i}static assert(e){if(!(e instanceof qe))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,oe.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},i=[];for(const r of this.issues)if(r.path.length>0){const n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else i.push(e(r));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}}qe.create=s=>new qe(s);const Mi=(s,e)=>{let t;switch(s.code){case M.invalid_type:s.received===j.undefined?t="Required":t=`Expected ${s.expected}, received ${s.received}`;break;case M.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(s.expected,oe.jsonStringifyReplacer)}`;break;case M.unrecognized_keys:t=`Unrecognized key(s) in object: ${oe.joinValues(s.keys,", ")}`;break;case M.invalid_union:t="Invalid input";break;case M.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${oe.joinValues(s.options)}`;break;case M.invalid_enum_value:t=`Invalid enum value. Expected ${oe.joinValues(s.options)}, received '${s.received}'`;break;case M.invalid_arguments:t="Invalid function arguments";break;case M.invalid_return_type:t="Invalid function return type";break;case M.invalid_date:t="Invalid date";break;case M.invalid_string:typeof s.validation=="object"?"includes"in s.validation?(t=`Invalid input: must include "${s.validation.includes}"`,typeof s.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${s.validation.position}`)):"startsWith"in s.validation?t=`Invalid input: must start with "${s.validation.startsWith}"`:"endsWith"in s.validation?t=`Invalid input: must end with "${s.validation.endsWith}"`:oe.assertNever(s.validation):s.validation!=="regex"?t=`Invalid ${s.validation}`:t="Invalid";break;case M.too_small:s.type==="array"?t=`Array must contain ${s.exact?"exactly":s.inclusive?"at least":"more than"} ${s.minimum} element(s)`:s.type==="string"?t=`String must contain ${s.exact?"exactly":s.inclusive?"at least":"over"} ${s.minimum} character(s)`:s.type==="number"?t=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="bigint"?t=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="date"?t=`Date must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(s.minimum))}`:t="Invalid input";break;case M.too_big:s.type==="array"?t=`Array must contain ${s.exact?"exactly":s.inclusive?"at most":"less than"} ${s.maximum} element(s)`:s.type==="string"?t=`String must contain ${s.exact?"exactly":s.inclusive?"at most":"under"} ${s.maximum} character(s)`:s.type==="number"?t=`Number must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="bigint"?t=`BigInt must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="date"?t=`Date must be ${s.exact?"exactly":s.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(s.maximum))}`:t="Invalid input";break;case M.custom:t="Invalid input";break;case M.invalid_intersection_types:t="Intersection results could not be merged";break;case M.not_multiple_of:t=`Number must be a multiple of ${s.multipleOf}`;break;case M.not_finite:t="Number must be finite";break;default:t=e.defaultError,oe.assertNever(s)}return{message:t}};let ia=Mi;function sa(){return ia}const ra=s=>{const{data:e,path:t,errorMaps:i,issueData:r}=s,n=[...t,...r.path||[]],o={...r,path:n};if(r.message!==void 0)return{...r,path:n,message:r.message};let a="";const p=i.filter(m=>!!m).slice().reverse();for(const m of p)a=m(o,{data:e,defaultError:a}).message;return{...r,path:n,message:a}};function H(s,e){const t=sa(),i=ra({issueData:e,data:s.data,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,t,t===Mi?void 0:Mi].filter(r=>!!r)});s.common.issues.push(i)}class Ie{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const i=[];for(const r of t){if(r.status==="aborted")return J;r.status==="dirty"&&e.dirty(),i.push(r.value)}return{status:e.value,value:i}}static async mergeObjectAsync(e,t){const i=[];for(const r of t){const n=await r.key,o=await r.value;i.push({key:n,value:o})}return Ie.mergeObjectSync(e,i)}static mergeObjectSync(e,t){const i={};for(const r of t){const{key:n,value:o}=r;if(n.status==="aborted"||o.status==="aborted")return J;n.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),n.value!=="__proto__"&&(typeof o.value<"u"||r.alwaysSet)&&(i[n.value]=o.value)}return{status:e.value,value:i}}}const J=Object.freeze({status:"aborted"}),Ht=s=>({status:"dirty",value:s}),Re=s=>({status:"valid",value:s}),Ls=s=>s.status==="aborted",Bs=s=>s.status==="dirty",Tt=s=>s.status==="valid",li=s=>typeof Promise<"u"&&s instanceof Promise;var V;(function(s){s.errToObj=e=>typeof e=="string"?{message:e}:e||{},s.toString=e=>typeof e=="string"?e:e?.message})(V||(V={}));class tt{constructor(e,t,i,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=i,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const $s=(s,e)=>{if(Tt(e))return{success:!0,data:e.value};if(!s.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new qe(s.common.issues);return this._error=t,this._error}}};function ie(s){if(!s)return{};const{errorMap:e,invalid_type_error:t,required_error:i,description:r}=s;if(e&&(t||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:r}:{errorMap:(o,a)=>{const{message:p}=s;return o.code==="invalid_enum_value"?{message:p??a.defaultError}:typeof a.data>"u"?{message:p??i??a.defaultError}:o.code!=="invalid_type"?{message:a.defaultError}:{message:p??t??a.defaultError}},description:r}}class ae{get description(){return this._def.description}_getType(e){return et(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:et(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ie,ctx:{common:e.parent.common,data:e.data,parsedType:et(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(li(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const i=this.safeParse(e,t);if(i.success)return i.data;throw i.error}safeParse(e,t){const i={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:et(e)},r=this._parseSync({data:e,path:i.path,parent:i});return $s(i,r)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:et(e)};if(!this["~standard"].async)try{const i=this._parseSync({data:e,path:[],parent:t});return Tt(i)?{value:i.value}:{issues:t.common.issues}}catch(i){i?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(i=>Tt(i)?{value:i.value}:{issues:t.common.issues})}async parseAsync(e,t){const i=await this.safeParseAsync(e,t);if(i.success)return i.data;throw i.error}async safeParseAsync(e,t){const i={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:et(e)},r=this._parse({data:e,path:i.path,parent:i}),n=await(li(r)?r:Promise.resolve(r));return $s(i,n)}refine(e,t){const i=r=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(r):t;return this._refinement((r,n)=>{const o=e(r),a=()=>n.addIssue({code:M.custom,...i(r)});return typeof Promise<"u"&&o instanceof Promise?o.then(p=>p?!0:(a(),!1)):o?!0:(a(),!1)})}refinement(e,t){return this._refinement((i,r)=>e(i)?!0:(r.addIssue(typeof t=="function"?t(i,r):t),!1))}_refinement(e){return new It({schema:this,typeName:ee.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return rt.create(this,this._def)}nullable(){return Pt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return $e.create(this)}promise(){return di.create(this,this._def)}or(e){return hi.create([this,e],this._def)}and(e){return ui.create(this,e,this._def)}transform(e){return new It({...ie(this._def),schema:this,typeName:ee.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new zi({...ie(this._def),innerType:this,defaultValue:t,typeName:ee.ZodDefault})}brand(){return new Ea({typeName:ee.ZodBranded,type:this,...ie(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Hi({...ie(this._def),innerType:this,catchValue:t,typeName:ee.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Ni.create(this,e)}readonly(){return Ui.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const na=/^c[^\s-]{8,}$/i,aa=/^[0-9a-z]+$/,oa=/^[0-9A-HJKMNP-TV-Z]{26}$/i,la=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ca=/^[a-z0-9_-]{21}$/i,ha=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ua=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,da=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,fa="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Li;const pa=/^(?:(?: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])$/,ma=/^(?:(?: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])\/(3[0-2]|[12]?[0-9])$/,ga=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ya=/^(([0-9a-fA-F]{1,4}:){7,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}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,ba=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,va=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ds="((\\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])))",wa=new RegExp(`^${Ds}$`);function zs(s){let e="[0-5]\\d";s.precision?e=`${e}\\.\\d{${s.precision}}`:s.precision==null&&(e=`${e}(\\.\\d+)?`);const t=s.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function _a(s){return new RegExp(`^${zs(s)}$`)}function xa(s){let e=`${Ds}T${zs(s)}`;const t=[];return t.push(s.local?"Z?":"Z"),s.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Ca(s,e){return!!((e==="v4"||!e)&&pa.test(s)||(e==="v6"||!e)&&ga.test(s))}function ka(s,e){if(!ha.test(s))return!1;try{const[t]=s.split(".");if(!t)return!1;const i=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),r=JSON.parse(atob(i));return!(typeof r!="object"||r===null||"typ"in r&&r?.typ!=="JWT"||!r.alg||e&&r.alg!==e)}catch{return!1}}function Ta(s,e){return!!((e==="v4"||!e)&&ma.test(s)||(e==="v6"||!e)&&ya.test(s))}class it extends ae{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==j.string){const n=this._getOrReturnCtx(e);return H(n,{code:M.invalid_type,expected:j.string,received:n.parsedType}),J}const i=new Ie;let r;for(const n of this._def.checks)if(n.kind==="min")e.data.length<n.value&&(r=this._getOrReturnCtx(e,r),H(r,{code:M.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),i.dirty());else if(n.kind==="max")e.data.length>n.value&&(r=this._getOrReturnCtx(e,r),H(r,{code:M.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),i.dirty());else if(n.kind==="length"){const o=e.data.length>n.value,a=e.data.length<n.value;(o||a)&&(r=this._getOrReturnCtx(e,r),o?H(r,{code:M.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):a&&H(r,{code:M.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),i.dirty())}else if(n.kind==="email")da.test(e.data)||(r=this._getOrReturnCtx(e,r),H(r,{validation:"email",code:M.invalid_string,message:n.message}),i.dirty());else if(n.kind==="emoji")Li||(Li=new RegExp(fa,"u")),Li.test(e.data)||(r=this._getOrReturnCtx(e,r),H(r,{validation:"emoji",code:M.invalid_string,message:n.message}),i.dirty());else if(n.kind==="uuid")la.test(e.data)||(r=this._getOrReturnCtx(e,r),H(r,{validation:"uuid",code:M.invalid_string,message:n.message}),i.dirty());else if(n.kind==="nanoid")ca.test(e.data)||(r=this._getOrReturnCtx(e,r),H(r,{validation:"nanoid",code:M.invalid_string,message:n.message}),i.dirty());else if(n.kind==="cuid")na.test(e.data)||(r=this._getOrReturnCtx(e,r),H(r,{validation:"cuid",code:M.invalid_string,message:n.message}),i.dirty());else if(n.kind==="cuid2")aa.test(e.data)||(r=this._getOrReturnCtx(e,r),H(r,{validation:"cuid2",code:M.invalid_string,message:n.message}),i.dirty());else if(n.kind==="ulid")oa.test(e.data)||(r=this._getOrReturnCtx(e,r),H(r,{validation:"ulid",code:M.invalid_string,message:n.message}),i.dirty());else if(n.kind==="url")try{new URL(e.data)}catch{r=this._getOrReturnCtx(e,r),H(r,{validation:"url",code:M.invalid_string,message:n.message}),i.dirty()}else n.kind==="regex"?(n.regex.lastIndex=0,n.regex.test(e.data)||(r=this._getOrReturnCtx(e,r),H(r,{validation:"regex",code:M.invalid_string,message:n.message}),i.dirty())):n.kind==="trim"?e.data=e.data.trim():n.kind==="includes"?e.data.includes(n.value,n.position)||(r=this._getOrReturnCtx(e,r),H(r,{code:M.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),i.dirty()):n.kind==="toLowerCase"?e.data=e.data.toLowerCase():n.kind==="toUpperCase"?e.data=e.data.toUpperCase():n.kind==="startsWith"?e.data.startsWith(n.value)||(r=this._getOrReturnCtx(e,r),H(r,{code:M.invalid_string,validation:{startsWith:n.value},message:n.message}),i.dirty()):n.kind==="endsWith"?e.data.endsWith(n.value)||(r=this._getOrReturnCtx(e,r),H(r,{code:M.invalid_string,validation:{endsWith:n.value},message:n.message}),i.dirty()):n.kind==="datetime"?xa(n).test(e.data)||(r=this._getOrReturnCtx(e,r),H(r,{code:M.invalid_string,validation:"datetime",message:n.message}),i.dirty()):n.kind==="date"?wa.test(e.data)||(r=this._getOrReturnCtx(e,r),H(r,{code:M.invalid_string,validation:"date",message:n.message}),i.dirty()):n.kind==="time"?_a(n).test(e.data)||(r=this._getOrReturnCtx(e,r),H(r,{code:M.invalid_string,validation:"time",message:n.message}),i.dirty()):n.kind==="duration"?ua.test(e.data)||(r=this._getOrReturnCtx(e,r),H(r,{validation:"duration",code:M.invalid_string,message:n.message}),i.dirty()):n.kind==="ip"?Ca(e.data,n.version)||(r=this._getOrReturnCtx(e,r),H(r,{validation:"ip",code:M.invalid_string,message:n.message}),i.dirty()):n.kind==="jwt"?ka(e.data,n.alg)||(r=this._getOrReturnCtx(e,r),H(r,{validation:"jwt",code:M.invalid_string,message:n.message}),i.dirty()):n.kind==="cidr"?Ta(e.data,n.version)||(r=this._getOrReturnCtx(e,r),H(r,{validation:"cidr",code:M.invalid_string,message:n.message}),i.dirty()):n.kind==="base64"?ba.test(e.data)||(r=this._getOrReturnCtx(e,r),H(r,{validation:"base64",code:M.invalid_string,message:n.message}),i.dirty()):n.kind==="base64url"?va.test(e.data)||(r=this._getOrReturnCtx(e,r),H(r,{validation:"base64url",code:M.invalid_string,message:n.message}),i.dirty()):oe.assertNever(n);return{status:i.value,value:e.data}}_regex(e,t,i){return this.refinement(r=>e.test(r),{validation:t,code:M.invalid_string,...V.errToObj(i)})}_addCheck(e){return new it({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...V.errToObj(e)})}url(e){return this._addCheck({kind:"url",...V.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...V.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...V.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...V.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...V.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...V.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...V.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...V.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...V.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...V.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...V.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...V.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...V.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...V.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...V.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...V.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...V.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...V.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...V.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...V.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...V.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...V.errToObj(t)})}nonempty(e){return this.min(1,V.errToObj(e))}trim(){return new it({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new it({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new it({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}it.create=s=>new it({checks:[],typeName:ee.ZodString,coerce:s?.coerce??!1,...ie(s)});function Sa(s,e){const t=(s.toString().split(".")[1]||"").length,i=(e.toString().split(".")[1]||"").length,r=t>i?t:i,n=Number.parseInt(s.toFixed(r).replace(".","")),o=Number.parseInt(e.toFixed(r).replace(".",""));return n%o/10**r}class St extends ae{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==j.number){const n=this._getOrReturnCtx(e);return H(n,{code:M.invalid_type,expected:j.number,received:n.parsedType}),J}let i;const r=new Ie;for(const n of this._def.checks)n.kind==="int"?oe.isInteger(e.data)||(i=this._getOrReturnCtx(e,i),H(i,{code:M.invalid_type,expected:"integer",received:"float",message:n.message}),r.dirty()):n.kind==="min"?(n.inclusive?e.data<n.value:e.data<=n.value)&&(i=this._getOrReturnCtx(e,i),H(i,{code:M.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty()):n.kind==="max"?(n.inclusive?e.data>n.value:e.data>=n.value)&&(i=this._getOrReturnCtx(e,i),H(i,{code:M.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),r.dirty()):n.kind==="multipleOf"?Sa(e.data,n.value)!==0&&(i=this._getOrReturnCtx(e,i),H(i,{code:M.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):n.kind==="finite"?Number.isFinite(e.data)||(i=this._getOrReturnCtx(e,i),H(i,{code:M.not_finite,message:n.message}),r.dirty()):oe.assertNever(n);return{status:r.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,V.toString(t))}gt(e,t){return this.setLimit("min",e,!1,V.toString(t))}lte(e,t){return this.setLimit("max",e,!0,V.toString(t))}lt(e,t){return this.setLimit("max",e,!1,V.toString(t))}setLimit(e,t,i,r){return new St({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:V.toString(r)}]})}_addCheck(e){return new St({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:V.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:V.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:V.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:V.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:V.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:V.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:V.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:V.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:V.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&oe.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(t===null||i.value>t)&&(t=i.value):i.kind==="max"&&(e===null||i.value<e)&&(e=i.value)}return Number.isFinite(t)&&Number.isFinite(e)}}St.create=s=>new St({checks:[],typeName:ee.ZodNumber,coerce:s?.coerce||!1,...ie(s)});class Nt extends ae{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==j.bigint)return this._getInvalidInput(e);let i;const r=new Ie;for(const n of this._def.checks)n.kind==="min"?(n.inclusive?e.data<n.value:e.data<=n.value)&&(i=this._getOrReturnCtx(e,i),H(i,{code:M.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty()):n.kind==="max"?(n.inclusive?e.data>n.value:e.data>=n.value)&&(i=this._getOrReturnCtx(e,i),H(i,{code:M.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),r.dirty()):n.kind==="multipleOf"?e.data%n.value!==BigInt(0)&&(i=this._getOrReturnCtx(e,i),H(i,{code:M.not_multiple_of,multipleOf:n.value,message:n.message}),r.dirty()):oe.assertNever(n);return{status:r.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return H(t,{code:M.invalid_type,expected:j.bigint,received:t.parsedType}),J}gte(e,t){return this.setLimit("min",e,!0,V.toString(t))}gt(e,t){return this.setLimit("min",e,!1,V.toString(t))}lte(e,t){return this.setLimit("max",e,!0,V.toString(t))}lt(e,t){return this.setLimit("max",e,!1,V.toString(t))}setLimit(e,t,i,r){return new Nt({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:V.toString(r)}]})}_addCheck(e){return new Nt({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:V.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:V.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:V.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:V.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:V.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}Nt.create=s=>new Nt({checks:[],typeName:ee.ZodBigInt,coerce:s?.coerce??!1,...ie(s)});class Bi extends ae{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==j.boolean){const i=this._getOrReturnCtx(e);return H(i,{code:M.invalid_type,expected:j.boolean,received:i.parsedType}),J}return Re(e.data)}}Bi.create=s=>new Bi({typeName:ee.ZodBoolean,coerce:s?.coerce||!1,...ie(s)});class ci extends ae{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==j.date){const n=this._getOrReturnCtx(e);return H(n,{code:M.invalid_type,expected:j.date,received:n.parsedType}),J}if(Number.isNaN(e.data.getTime())){const n=this._getOrReturnCtx(e);return H(n,{code:M.invalid_date}),J}const i=new Ie;let r;for(const n of this._def.checks)n.kind==="min"?e.data.getTime()<n.value&&(r=this._getOrReturnCtx(e,r),H(r,{code:M.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),i.dirty()):n.kind==="max"?e.data.getTime()>n.value&&(r=this._getOrReturnCtx(e,r),H(r,{code:M.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),i.dirty()):oe.assertNever(n);return{status:i.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ci({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:V.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:V.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}ci.create=s=>new ci({checks:[],coerce:s?.coerce||!1,typeName:ee.ZodDate,...ie(s)});class Hs extends ae{_parse(e){if(this._getType(e)!==j.symbol){const i=this._getOrReturnCtx(e);return H(i,{code:M.invalid_type,expected:j.symbol,received:i.parsedType}),J}return Re(e.data)}}Hs.create=s=>new Hs({typeName:ee.ZodSymbol,...ie(s)});class Ns extends ae{_parse(e){if(this._getType(e)!==j.undefined){const i=this._getOrReturnCtx(e);return H(i,{code:M.invalid_type,expected:j.undefined,received:i.parsedType}),J}return Re(e.data)}}Ns.create=s=>new Ns({typeName:ee.ZodUndefined,...ie(s)});class Us extends ae{_parse(e){if(this._getType(e)!==j.null){const i=this._getOrReturnCtx(e);return H(i,{code:M.invalid_type,expected:j.null,received:i.parsedType}),J}return Re(e.data)}}Us.create=s=>new Us({typeName:ee.ZodNull,...ie(s)});class js extends ae{constructor(){super(...arguments),this._any=!0}_parse(e){return Re(e.data)}}js.create=s=>new js({typeName:ee.ZodAny,...ie(s)});class Vs extends ae{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Re(e.data)}}Vs.create=s=>new Vs({typeName:ee.ZodUnknown,...ie(s)});class st extends ae{_parse(e){const t=this._getOrReturnCtx(e);return H(t,{code:M.invalid_type,expected:j.never,received:t.parsedType}),J}}st.create=s=>new st({typeName:ee.ZodNever,...ie(s)});class Ws extends ae{_parse(e){if(this._getType(e)!==j.undefined){const i=this._getOrReturnCtx(e);return H(i,{code:M.invalid_type,expected:j.void,received:i.parsedType}),J}return Re(e.data)}}Ws.create=s=>new Ws({typeName:ee.ZodVoid,...ie(s)});class $e extends ae{_parse(e){const{ctx:t,status:i}=this._processInputParams(e),r=this._def;if(t.parsedType!==j.array)return H(t,{code:M.invalid_type,expected:j.array,received:t.parsedType}),J;if(r.exactLength!==null){const o=t.data.length>r.exactLength.value,a=t.data.length<r.exactLength.value;(o||a)&&(H(t,{code:o?M.too_big:M.too_small,minimum:a?r.exactLength.value:void 0,maximum:o?r.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:r.exactLength.message}),i.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(H(t,{code:M.too_small,minimum:r.minLength.value,type:"array",inclusive:!0,exact:!1,message:r.minLength.message}),i.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(H(t,{code:M.too_big,maximum:r.maxLength.value,type:"array",inclusive:!0,exact:!1,message:r.maxLength.message}),i.dirty()),t.common.async)return Promise.all([...t.data].map((o,a)=>r.type._parseAsync(new tt(t,o,t.path,a)))).then(o=>Ie.mergeArray(i,o));const n=[...t.data].map((o,a)=>r.type._parseSync(new tt(t,o,t.path,a)));return Ie.mergeArray(i,n)}get element(){return this._def.type}min(e,t){return new $e({...this._def,minLength:{value:e,message:V.toString(t)}})}max(e,t){return new $e({...this._def,maxLength:{value:e,message:V.toString(t)}})}length(e,t){return new $e({...this._def,exactLength:{value:e,message:V.toString(t)}})}nonempty(e){return this.min(1,e)}}$e.create=(s,e)=>new $e({type:s,minLength:null,maxLength:null,exactLength:null,typeName:ee.ZodArray,...ie(e)});function Et(s){if(s instanceof ye){const e={};for(const t in s.shape){const i=s.shape[t];e[t]=rt.create(Et(i))}return new ye({...s._def,shape:()=>e})}else return s instanceof $e?new $e({...s._def,type:Et(s.element)}):s instanceof rt?rt.create(Et(s.unwrap())):s instanceof Pt?Pt.create(Et(s.unwrap())):s instanceof mt?mt.create(s.items.map(e=>Et(e))):s}class ye extends ae{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),t=oe.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==j.object){const m=this._getOrReturnCtx(e);return H(m,{code:M.invalid_type,expected:j.object,received:m.parsedType}),J}const{status:i,ctx:r}=this._processInputParams(e),{shape:n,keys:o}=this._getCached(),a=[];if(!(this._def.catchall instanceof st&&this._def.unknownKeys==="strip"))for(const m in r.data)o.includes(m)||a.push(m);const p=[];for(const m of o){const d=n[m],l=r.data[m];p.push({key:{status:"valid",value:m},value:d._parse(new tt(r,l,r.path,m)),alwaysSet:m in r.data})}if(this._def.catchall instanceof st){const m=this._def.unknownKeys;if(m==="passthrough")for(const d of a)p.push({key:{status:"valid",value:d},value:{status:"valid",value:r.data[d]}});else if(m==="strict")a.length>0&&(H(r,{code:M.unrecognized_keys,keys:a}),i.dirty());else if(m!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const m=this._def.catchall;for(const d of a){const l=r.data[d];p.push({key:{status:"valid",value:d},value:m._parse(new tt(r,l,r.path,d)),alwaysSet:d in r.data})}}return r.common.async?Promise.resolve().then(async()=>{const m=[];for(const d of p){const l=await d.key,c=await d.value;m.push({key:l,value:c,alwaysSet:d.alwaysSet})}return m}).then(m=>Ie.mergeObjectSync(i,m)):Ie.mergeObjectSync(i,p)}get shape(){return this._def.shape()}strict(e){return V.errToObj,new ye({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,i)=>{const r=this._def.errorMap?.(t,i).message??i.defaultError;return t.code==="unrecognized_keys"?{message:V.errToObj(e).message??r}:{message:r}}}:{}})}strip(){return new ye({...this._def,unknownKeys:"strip"})}passthrough(){return new ye({...this._def,unknownKeys:"passthrough"})}extend(e){return new ye({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new ye({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:ee.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new ye({...this._def,catchall:e})}pick(e){const t={};for(const i of oe.objectKeys(e))e[i]&&this.shape[i]&&(t[i]=this.shape[i]);return new ye({...this._def,shape:()=>t})}omit(e){const t={};for(const i of oe.objectKeys(this.shape))e[i]||(t[i]=this.shape[i]);return new ye({...this._def,shape:()=>t})}deepPartial(){return Et(this)}partial(e){const t={};for(const i of oe.objectKeys(this.shape)){const r=this.shape[i];e&&!e[i]?t[i]=r:t[i]=r.optional()}return new ye({...this._def,shape:()=>t})}required(e){const t={};for(const i of oe.objectKeys(this.shape))if(e&&!e[i])t[i]=this.shape[i];else{let n=this.shape[i];for(;n instanceof rt;)n=n._def.innerType;t[i]=n}return new ye({...this._def,shape:()=>t})}keyof(){return Ks(oe.objectKeys(this.shape))}}ye.create=(s,e)=>new ye({shape:()=>s,unknownKeys:"strip",catchall:st.create(),typeName:ee.ZodObject,...ie(e)}),ye.strictCreate=(s,e)=>new ye({shape:()=>s,unknownKeys:"strict",catchall:st.create(),typeName:ee.ZodObject,...ie(e)}),ye.lazycreate=(s,e)=>new ye({shape:s,unknownKeys:"strip",catchall:st.create(),typeName:ee.ZodObject,...ie(e)});class hi extends ae{_parse(e){const{ctx:t}=this._processInputParams(e),i=this._def.options;function r(n){for(const a of n)if(a.result.status==="valid")return a.result;for(const a of n)if(a.result.status==="dirty")return t.common.issues.push(...a.ctx.common.issues),a.result;const o=n.map(a=>new qe(a.ctx.common.issues));return H(t,{code:M.invalid_union,unionErrors:o}),J}if(t.common.async)return Promise.all(i.map(async n=>{const o={...t,common:{...t.common,issues:[]},parent:null};return{result:await n._parseAsync({data:t.data,path:t.path,parent:o}),ctx:o}})).then(r);{let n;const o=[];for(const p of i){const m={...t,common:{...t.common,issues:[]},parent:null},d=p._parseSync({data:t.data,path:t.path,parent:m});if(d.status==="valid")return d;d.status==="dirty"&&!n&&(n={result:d,ctx:m}),m.common.issues.length&&o.push(m.common.issues)}if(n)return t.common.issues.push(...n.ctx.common.issues),n.result;const a=o.map(p=>new qe(p));return H(t,{code:M.invalid_union,unionErrors:a}),J}}get options(){return this._def.options}}hi.create=(s,e)=>new hi({options:s,typeName:ee.ZodUnion,...ie(e)});function $i(s,e){const t=et(s),i=et(e);if(s===e)return{valid:!0,data:s};if(t===j.object&&i===j.object){const r=oe.objectKeys(e),n=oe.objectKeys(s).filter(a=>r.indexOf(a)!==-1),o={...s,...e};for(const a of n){const p=$i(s[a],e[a]);if(!p.valid)return{valid:!1};o[a]=p.data}return{valid:!0,data:o}}else if(t===j.array&&i===j.array){if(s.length!==e.length)return{valid:!1};const r=[];for(let n=0;n<s.length;n++){const o=s[n],a=e[n],p=$i(o,a);if(!p.valid)return{valid:!1};r.push(p.data)}return{valid:!0,data:r}}else return t===j.date&&i===j.date&&+s==+e?{valid:!0,data:s}:{valid:!1}}class ui extends ae{_parse(e){const{status:t,ctx:i}=this._processInputParams(e),r=(n,o)=>{if(Ls(n)||Ls(o))return J;const a=$i(n.value,o.value);return a.valid?((Bs(n)||Bs(o))&&t.dirty(),{status:t.value,value:a.data}):(H(i,{code:M.invalid_intersection_types}),J)};return i.common.async?Promise.all([this._def.left._parseAsync({data:i.data,path:i.path,parent:i}),this._def.right._parseAsync({data:i.data,path:i.path,parent:i})]).then(([n,o])=>r(n,o)):r(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}ui.create=(s,e,t)=>new ui({left:s,right:e,typeName:ee.ZodIntersection,...ie(t)});class mt extends ae{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==j.array)return H(i,{code:M.invalid_type,expected:j.array,received:i.parsedType}),J;if(i.data.length<this._def.items.length)return H(i,{code:M.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J;!this._def.rest&&i.data.length>this._def.items.length&&(H(i,{code:M.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...i.data].map((o,a)=>{const p=this._def.items[a]||this._def.rest;return p?p._parse(new tt(i,o,i.path,a)):null}).filter(o=>!!o);return i.common.async?Promise.all(n).then(o=>Ie.mergeArray(t,o)):Ie.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new mt({...this._def,rest:e})}}mt.create=(s,e)=>{if(!Array.isArray(s))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new mt({items:s,typeName:ee.ZodTuple,rest:null,...ie(e)})};class Gs extends ae{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==j.map)return H(i,{code:M.invalid_type,expected:j.map,received:i.parsedType}),J;const r=this._def.keyType,n=this._def.valueType,o=[...i.data.entries()].map(([a,p],m)=>({key:r._parse(new tt(i,a,i.path,[m,"key"])),value:n._parse(new tt(i,p,i.path,[m,"value"]))}));if(i.common.async){const a=new Map;return Promise.resolve().then(async()=>{for(const p of o){const m=await p.key,d=await p.value;if(m.status==="aborted"||d.status==="aborted")return J;(m.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(m.value,d.value)}return{status:t.value,value:a}})}else{const a=new Map;for(const p of o){const m=p.key,d=p.value;if(m.status==="aborted"||d.status==="aborted")return J;(m.status==="dirty"||d.status==="dirty")&&t.dirty(),a.set(m.value,d.value)}return{status:t.value,value:a}}}}Gs.create=(s,e,t)=>new Gs({valueType:e,keyType:s,typeName:ee.ZodMap,...ie(t)});class Ut extends ae{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==j.set)return H(i,{code:M.invalid_type,expected:j.set,received:i.parsedType}),J;const r=this._def;r.minSize!==null&&i.data.size<r.minSize.value&&(H(i,{code:M.too_small,minimum:r.minSize.value,type:"set",inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&i.data.size>r.maxSize.value&&(H(i,{code:M.too_big,maximum:r.maxSize.value,type:"set",inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());const n=this._def.valueType;function o(p){const m=new Set;for(const d of p){if(d.status==="aborted")return J;d.status==="dirty"&&t.dirty(),m.add(d.value)}return{status:t.value,value:m}}const a=[...i.data.values()].map((p,m)=>n._parse(new tt(i,p,i.path,m)));return i.common.async?Promise.all(a).then(p=>o(p)):o(a)}min(e,t){return new Ut({...this._def,minSize:{value:e,message:V.toString(t)}})}max(e,t){return new Ut({...this._def,maxSize:{value:e,message:V.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}Ut.create=(s,e)=>new Ut({valueType:s,minSize:null,maxSize:null,typeName:ee.ZodSet,...ie(e)});class Zs extends ae{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Zs.create=(s,e)=>new Zs({getter:s,typeName:ee.ZodLazy,...ie(e)});class Di extends ae{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return H(t,{received:t.data,code:M.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:e.data}}get value(){return this._def.value}}Di.create=(s,e)=>new Di({value:s,typeName:ee.ZodLiteral,...ie(e)});function Ks(s,e){return new At({values:s,typeName:ee.ZodEnum,...ie(e)})}class At extends ae{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),i=this._def.values;return H(t,{expected:oe.joinValues(i),received:t.parsedType,code:M.invalid_type}),J}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),i=this._def.values;return H(t,{received:t.data,code:M.invalid_enum_value,options:i}),J}return Re(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return At.create(e,{...this._def,...t})}exclude(e,t=this._def){return At.create(this.options.filter(i=>!e.includes(i)),{...this._def,...t})}}At.create=Ks;class qs extends ae{_parse(e){const t=oe.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(e);if(i.parsedType!==j.string&&i.parsedType!==j.number){const r=oe.objectValues(t);return H(i,{expected:oe.joinValues(r),received:i.parsedType,code:M.invalid_type}),J}if(this._cache||(this._cache=new Set(oe.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const r=oe.objectValues(t);return H(i,{received:i.data,code:M.invalid_enum_value,options:r}),J}return Re(e.data)}get enum(){return this._def.values}}qs.create=(s,e)=>new qs({values:s,typeName:ee.ZodNativeEnum,...ie(e)});class di extends ae{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==j.promise&&t.common.async===!1)return H(t,{code:M.invalid_type,expected:j.promise,received:t.parsedType}),J;const i=t.parsedType===j.promise?t.data:Promise.resolve(t.data);return Re(i.then(r=>this._def.type.parseAsync(r,{path:t.path,errorMap:t.common.contextualErrorMap})))}}di.create=(s,e)=>new di({type:s,typeName:ee.ZodPromise,...ie(e)});class It extends ae{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===ee.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:i}=this._processInputParams(e),r=this._def.effect||null,n={addIssue:o=>{H(i,o),o.fatal?t.abort():t.dirty()},get path(){return i.path}};if(n.addIssue=n.addIssue.bind(n),r.type==="preprocess"){const o=r.transform(i.data,n);if(i.common.async)return Promise.resolve(o).then(async a=>{if(t.value==="aborted")return J;const p=await this._def.schema._parseAsync({data:a,path:i.path,parent:i});return p.status==="aborted"?J:p.status==="dirty"||t.value==="dirty"?Ht(p.value):p});{if(t.value==="aborted")return J;const a=this._def.schema._parseSync({data:o,path:i.path,parent:i});return a.status==="aborted"?J:a.status==="dirty"||t.value==="dirty"?Ht(a.value):a}}if(r.type==="refinement"){const o=a=>{const p=r.refinement(a,n);if(i.common.async)return Promise.resolve(p);if(p instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(i.common.async===!1){const a=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return a.status==="aborted"?J:(a.status==="dirty"&&t.dirty(),o(a.value),{status:t.value,value:a.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(a=>a.status==="aborted"?J:(a.status==="dirty"&&t.dirty(),o(a.value).then(()=>({status:t.value,value:a.value}))))}if(r.type==="transform")if(i.common.async===!1){const o=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!Tt(o))return J;const a=r.transform(o.value,n);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:a}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(o=>Tt(o)?Promise.resolve(r.transform(o.value,n)).then(a=>({status:t.value,value:a})):J);oe.assertNever(r)}}It.create=(s,e,t)=>new It({schema:s,typeName:ee.ZodEffects,effect:e,...ie(t)}),It.createWithPreprocess=(s,e,t)=>new It({schema:e,effect:{type:"preprocess",transform:s},typeName:ee.ZodEffects,...ie(t)});class rt extends ae{_parse(e){return this._getType(e)===j.undefined?Re(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}rt.create=(s,e)=>new rt({innerType:s,typeName:ee.ZodOptional,...ie(e)});class Pt extends ae{_parse(e){return this._getType(e)===j.null?Re(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Pt.create=(s,e)=>new Pt({innerType:s,typeName:ee.ZodNullable,...ie(e)});class zi extends ae{_parse(e){const{ctx:t}=this._processInputParams(e);let i=t.data;return t.parsedType===j.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}zi.create=(s,e)=>new zi({innerType:s,typeName:ee.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ie(e)});class Hi extends ae{_parse(e){const{ctx:t}=this._processInputParams(e),i={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return li(r)?r.then(n=>({status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new qe(i.common.issues)},input:i.data})})):{status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new qe(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}Hi.create=(s,e)=>new Hi({innerType:s,typeName:ee.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ie(e)});class Xs extends ae{_parse(e){if(this._getType(e)!==j.nan){const i=this._getOrReturnCtx(e);return H(i,{code:M.invalid_type,expected:j.nan,received:i.parsedType}),J}return{status:"valid",value:e.data}}}Xs.create=s=>new Xs({typeName:ee.ZodNaN,...ie(s)});class Ea extends ae{_parse(e){const{ctx:t}=this._processInputParams(e),i=t.data;return this._def.type._parse({data:i,path:t.path,parent:t})}unwrap(){return this._def.type}}class Ni extends ae{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.common.async)return(async()=>{const n=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return n.status==="aborted"?J:n.status==="dirty"?(t.dirty(),Ht(n.value)):this._def.out._parseAsync({data:n.value,path:i.path,parent:i})})();{const r=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return r.status==="aborted"?J:r.status==="dirty"?(t.dirty(),{status:"dirty",value:r.value}):this._def.out._parseSync({data:r.value,path:i.path,parent:i})}}static create(e,t){return new Ni({in:e,out:t,typeName:ee.ZodPipeline})}}class Ui extends ae{_parse(e){const t=this._def.innerType._parse(e),i=r=>(Tt(r)&&(r.value=Object.freeze(r.value)),r);return li(t)?t.then(r=>i(r)):i(t)}unwrap(){return this._def.innerType}}Ui.create=(s,e)=>new Ui({innerType:s,typeName:ee.ZodReadonly,...ie(e)});var ee;(function(s){s.ZodString="ZodString",s.ZodNumber="ZodNumber",s.ZodNaN="ZodNaN",s.ZodBigInt="ZodBigInt",s.ZodBoolean="ZodBoolean",s.ZodDate="ZodDate",s.ZodSymbol="ZodSymbol",s.ZodUndefined="ZodUndefined",s.ZodNull="ZodNull",s.ZodAny="ZodAny",s.ZodUnknown="ZodUnknown",s.ZodNever="ZodNever",s.ZodVoid="ZodVoid",s.ZodArray="ZodArray",s.ZodObject="ZodObject",s.ZodUnion="ZodUnion",s.ZodDiscriminatedUnion="ZodDiscriminatedUnion",s.ZodIntersection="ZodIntersection",s.ZodTuple="ZodTuple",s.ZodRecord="ZodRecord",s.ZodMap="ZodMap",s.ZodSet="ZodSet",s.ZodFunction="ZodFunction",s.ZodLazy="ZodLazy",s.ZodLiteral="ZodLiteral",s.ZodEnum="ZodEnum",s.ZodEffects="ZodEffects",s.ZodNativeEnum="ZodNativeEnum",s.ZodOptional="ZodOptional",s.ZodNullable="ZodNullable",s.ZodDefault="ZodDefault",s.ZodCatch="ZodCatch",s.ZodPromise="ZodPromise",s.ZodBranded="ZodBranded",s.ZodPipeline="ZodPipeline",s.ZodReadonly="ZodReadonly"})(ee||(ee={}));const pe=it.create,D=St.create,Aa=Bi.create;st.create;const Ys=$e.create,te=ye.create,ji=hi.create;ui.create,mt.create;const nt=Di.create,_e=At.create;di.create,rt.create,Pt.create;const jt=pe().regex(/^#[A-Fa-f0-9]{6}$/,"Invalid hex color format"),Ia=te({offset:D().min(0).max(1),color:jt}).strict(),Pa=te({type:_e(["linear","radial"]).default("linear"),angle:D().min(0).max(360).default(0),stops:Ys(Ia).min(2)}).strict(),Ra=te({family:pe().default("Roboto"),size:D().min(8).max(500).default(48),weight:ji([pe(),D()]).default("400"),style:_e(["normal","italic","oblique"]).default("normal"),color:jt.default("#000000"),opacity:D().min(0).max(1).default(1)}).strict(),Oa=te({letterSpacing:D().default(0),lineHeight:D().min(.1).max(10).default(1.2),textTransform:_e(["none","uppercase","lowercase","capitalize"]).default("none"),textDecoration:_e(["none","underline","line-through"]).default("none"),gradient:Pa.optional()}).strict(),Fa=te({width:D().min(0).default(0),color:jt.default("#000000"),opacity:D().min(0).max(1).default(1)}).strict(),Ma=te({offsetX:D().default(0),offsetY:D().default(0),blur:D().min(0).default(0),color:jt.default("#000000"),opacity:D().min(0).max(1).default(.5)}).strict(),La=te({color:jt.optional(),opacity:D().min(0).max(1).default(1),borderRadius:D().min(0).default(0)}).strict(),Ba=te({horizontal:_e(["left","center","right"]).default("left"),vertical:_e(["top","middle","bottom"]).default("middle")}).strict(),$a=te({preset:_e(["fadeIn","slideIn","typewriter","shift","ascend","movingLetters","bounce","elastic","pulse"]),speed:D().min(.1).max(10).default(1),duration:D().min(.1).max(60).optional(),style:_e(["character","word"]).optional(),direction:_e(["left","right","up","down"]).optional()}).strict(),Da=te({src:pe().url("Invalid font URL"),family:pe(),weight:ji([pe(),D()]).default("400"),style:_e(["normal","italic","oblique"]).default("normal")}).strict(),fi=te({type:nt("rich-text"),text:pe().max(1e4).default(""),width:D().min(1).max(8192).optional(),height:D().min(1).max(8192).optional(),font:Ra.optional(),style:Oa.optional(),stroke:Fa.optional(),shadow:Ma.optional(),background:La.optional(),align:Ba.optional(),animation:$a.optional(),cacheEnabled:Aa().default(!0),pixelRatio:D().min(1).max(4).default(2),customFonts:Ys(Da).optional()}).strict();function Qs(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function za(s){if(s.__esModule)return s;var e=s.default;if(typeof e=="function"){var t=function i(){return this instanceof i?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,"__esModule",{value:!0}),Object.keys(s).forEach(function(i){var r=Object.getOwnPropertyDescriptor(s,i);Object.defineProperty(t,i,r.get?r:{enumerable:!0,get:function(){return s[i]}})}),t}var Js={exports:{}};(function(s,e){(function(t,i){s.exports=i()})(self,()=>{return t={7629:(r,n,o)=>{const a=o(375),p=o(8571),m=o(9474),d=o(1687),l=o(8652),c=o(8160),u=o(3292),h=o(6354),f=o(8901),b=o(9708),g=o(6914),y=o(2294),v=o(6133),_=o(1152),C=o(8863),S=o(2036),T={Base:class{constructor(w){this.type=w,this.$_root=null,this._definition={},this._reset()}_reset(){this._ids=new y.Ids,this._preferences=null,this._refs=new v.Manager,this._cache=null,this._valids=null,this._invalids=null,this._flags={},this._rules=[],this._singleRules=new Map,this.$_terms={},this.$_temp={ruleset:null,whens:{}}}describe(){return a(typeof b.describe=="function","Manifest functionality disabled"),b.describe(this)}allow(...w){return c.verifyFlat(w,"allow"),this._values(w,"_valids")}alter(w){a(w&&typeof w=="object"&&!Array.isArray(w),"Invalid targets argument"),a(!this._inRuleset(),"Cannot set alterations inside a ruleset");const x=this.clone();x.$_terms.alterations=x.$_terms.alterations||[];for(const k in w){const E=w[k];a(typeof E=="function","Alteration adjuster for",k,"must be a function"),x.$_terms.alterations.push({target:k,adjuster:E})}return x.$_temp.ruleset=!1,x}artifact(w){return a(w!==void 0,"Artifact cannot be undefined"),a(!this._cache,"Cannot set an artifact with a rule cache"),this.$_setFlag("artifact",w)}cast(w){return a(w===!1||typeof w=="string","Invalid to value"),a(w===!1||this._definition.cast[w],"Type",this.type,"does not support casting to",w),this.$_setFlag("cast",w===!1?void 0:w)}default(w,x){return this._default("default",w,x)}description(w){return a(w&&typeof w=="string","Description must be a non-empty string"),this.$_setFlag("description",w)}empty(w){const x=this.clone();return w!==void 0&&(w=x.$_compile(w,{override:!1})),x.$_setFlag("empty",w,{clone:!1})}error(w){return a(w,"Missing error"),a(w instanceof Error||typeof w=="function","Must provide a valid Error object or a function"),this.$_setFlag("error",w)}example(w,x={}){return a(w!==void 0,"Missing example"),c.assertOptions(x,["override"]),this._inner("examples",w,{single:!0,override:x.override})}external(w,x){return typeof w=="object"&&(a(!x,"Cannot combine options with description"),x=w.description,w=w.method),a(typeof w=="function","Method must be a function"),a(x===void 0||x&&typeof x=="string","Description must be a non-empty string"),this._inner("externals",{method:w,description:x},{single:!0})}failover(w,x){return this._default("failover",w,x)}forbidden(){return this.presence("forbidden")}id(w){return w?(a(typeof w=="string","id must be a non-empty string"),a(/^[^\.]+$/.test(w),"id cannot contain period character"),this.$_setFlag("id",w)):this.$_setFlag("id",void 0)}invalid(...w){return this._values(w,"_invalids")}label(w){return a(w&&typeof w=="string","Label name must be a non-empty string"),this.$_setFlag("label",w)}meta(w){return a(w!==void 0,"Meta cannot be undefined"),this._inner("metas",w,{single:!0})}note(...w){a(w.length,"Missing notes");for(const x of w)a(x&&typeof x=="string","Notes must be non-empty strings");return this._inner("notes",w)}only(w=!0){return a(typeof w=="boolean","Invalid mode:",w),this.$_setFlag("only",w)}optional(){return this.presence("optional")}prefs(w){a(w,"Missing preferences"),a(w.context===void 0,"Cannot override context"),a(w.externals===void 0,"Cannot override externals"),a(w.warnings===void 0,"Cannot override warnings"),a(w.debug===void 0,"Cannot override debug"),c.checkPreferences(w);const x=this.clone();return x._preferences=c.preferences(x._preferences,w),x}presence(w){return a(["optional","required","forbidden"].includes(w),"Unknown presence mode",w),this.$_setFlag("presence",w)}raw(w=!0){return this.$_setFlag("result",w?"raw":void 0)}result(w){return a(["raw","strip"].includes(w),"Unknown result mode",w),this.$_setFlag("result",w)}required(){return this.presence("required")}strict(w){const x=this.clone(),k=w!==void 0&&!w;return x._preferences=c.preferences(x._preferences,{convert:k}),x}strip(w=!0){return this.$_setFlag("result",w?"strip":void 0)}tag(...w){a(w.length,"Missing tags");for(const x of w)a(x&&typeof x=="string","Tags must be non-empty strings");return this._inner("tags",w)}unit(w){return a(w&&typeof w=="string","Unit name must be a non-empty string"),this.$_setFlag("unit",w)}valid(...w){c.verifyFlat(w,"valid");const x=this.allow(...w);return x.$_setFlag("only",!!x._valids,{clone:!1}),x}when(w,x){const k=this.clone();k.$_terms.whens||(k.$_terms.whens=[]);const E=u.when(k,w,x);if(!["any","link"].includes(k.type)){const P=E.is?[E]:E.switch;for(const O of P)a(!O.then||O.then.type==="any"||O.then.type===k.type,"Cannot combine",k.type,"with",O.then&&O.then.type),a(!O.otherwise||O.otherwise.type==="any"||O.otherwise.type===k.type,"Cannot combine",k.type,"with",O.otherwise&&O.otherwise.type)}return k.$_terms.whens.push(E),k.$_mutateRebuild()}cache(w){a(!this._inRuleset(),"Cannot set caching inside a ruleset"),a(!this._cache,"Cannot override schema cache"),a(this._flags.artifact===void 0,"Cannot cache a rule with an artifact");const x=this.clone();return x._cache=w||l.provider.provision(),x.$_temp.ruleset=!1,x}clone(){const w=Object.create(Object.getPrototypeOf(this));return this._assign(w)}concat(w){a(c.isSchema(w),"Invalid schema object"),a(this.type==="any"||w.type==="any"||w.type===this.type,"Cannot merge type",this.type,"with another type:",w.type),a(!this._inRuleset(),"Cannot concatenate onto a schema with open ruleset"),a(!w._inRuleset(),"Cannot concatenate a schema with open ruleset");let x=this.clone();if(this.type==="any"&&w.type!=="any"){const k=w.clone();for(const E of Object.keys(x))E!=="type"&&(k[E]=x[E]);x=k}x._ids.concat(w._ids),x._refs.register(w,v.toSibling),x._preferences=x._preferences?c.preferences(x._preferences,w._preferences):w._preferences,x._valids=S.merge(x._valids,w._valids,w._invalids),x._invalids=S.merge(x._invalids,w._invalids,w._valids);for(const k of w._singleRules.keys())x._singleRules.has(k)&&(x._rules=x._rules.filter(E=>E.keep||E.name!==k),x._singleRules.delete(k));for(const k of w._rules)w._definition.rules[k.method].multi||x._singleRules.set(k.name,k),x._rules.push(k);if(x._flags.empty&&w._flags.empty){x._flags.empty=x._flags.empty.concat(w._flags.empty);const k=Object.assign({},w._flags);delete k.empty,d(x._flags,k)}else if(w._flags.empty){x._flags.empty=w._flags.empty;const k=Object.assign({},w._flags);delete k.empty,d(x._flags,k)}else d(x._flags,w._flags);for(const k in w.$_terms){const E=w.$_terms[k];E?x.$_terms[k]?x.$_terms[k]=x.$_terms[k].concat(E):x.$_terms[k]=E.slice():x.$_terms[k]||(x.$_terms[k]=E)}return this.$_root._tracer&&this.$_root._tracer._combine(x,[this,w]),x.$_mutateRebuild()}extend(w){return a(!w.base,"Cannot extend type with another base"),f.type(this,w)}extract(w){return w=Array.isArray(w)?w:w.split("."),this._ids.reach(w)}fork(w,x){a(!this._inRuleset(),"Cannot fork inside a ruleset");let k=this;for(let E of[].concat(w))E=Array.isArray(E)?E:E.split("."),k=k._ids.fork(E,x,k);return k.$_temp.ruleset=!1,k}rule(w){const x=this._definition;c.assertOptions(w,Object.keys(x.modifiers)),a(this.$_temp.ruleset!==!1,"Cannot apply rules to empty ruleset or the last rule added does not support rule properties");const k=this.$_temp.ruleset===null?this._rules.length-1:this.$_temp.ruleset;a(k>=0&&k<this._rules.length,"Cannot apply rules to empty ruleset");const E=this.clone();for(let P=k;P<E._rules.length;++P){const O=E._rules[P],z=p(O);for(const I in w)x.modifiers[I](z,w[I]),a(z.name===O.name,"Cannot change rule name");E._rules[P]=z,E._singleRules.get(z.name)===O&&E._singleRules.set(z.name,z)}return E.$_temp.ruleset=!1,E.$_mutateRebuild()}get ruleset(){a(!this._inRuleset(),"Cannot start a new ruleset without closing the previous one");const w=this.clone();return w.$_temp.ruleset=w._rules.length,w}get $(){return this.ruleset}tailor(w){w=[].concat(w),a(!this._inRuleset(),"Cannot tailor inside a ruleset");let x=this;if(this.$_terms.alterations)for(const{target:k,adjuster:E}of this.$_terms.alterations)w.includes(k)&&(x=E(x),a(c.isSchema(x),"Alteration adjuster for",k,"failed to return a schema object"));return x=x.$_modify({each:k=>k.tailor(w),ref:!1}),x.$_temp.ruleset=!1,x.$_mutateRebuild()}tracer(){return _.location?_.location(this):this}validate(w,x){return C.entry(w,this,x)}validateAsync(w,x){return C.entryAsync(w,this,x)}$_addRule(w){typeof w=="string"&&(w={name:w}),a(w&&typeof w=="object","Invalid options"),a(w.name&&typeof w.name=="string","Invalid rule name");for(const O in w)a(O[0]!=="_","Cannot set private rule properties");const x=Object.assign({},w);x._resolve=[],x.method=x.method||x.name;const k=this._definition.rules[x.method],E=x.args;a(k,"Unknown rule",x.method);const P=this.clone();if(E){a(Object.keys(E).length===1||Object.keys(E).length===this._definition.rules[x.name].args.length,"Invalid rule definition for",this.type,x.name);for(const O in E){let z=E[O];if(k.argsByName){const I=k.argsByName.get(O);if(I.ref&&c.isResolvable(z))x._resolve.push(O),P.$_mutateRegister(z);else if(I.normalize&&(z=I.normalize(z),E[O]=z),I.assert){const L=c.validateArg(z,O,I);a(!L,L,"or reference")}}z!==void 0?E[O]=z:delete E[O]}}return k.multi||(P._ruleRemove(x.name,{clone:!1}),P._singleRules.set(x.name,x)),P.$_temp.ruleset===!1&&(P.$_temp.ruleset=null),k.priority?P._rules.unshift(x):P._rules.push(x),P}$_compile(w,x){return u.schema(this.$_root,w,x)}$_createError(w,x,k,E,P,O={}){const z=O.flags!==!1?this._flags:{},I=O.messages?g.merge(this._definition.messages,O.messages):this._definition.messages;return new h.Report(w,x,k,z,I,E,P)}$_getFlag(w){return this._flags[w]}$_getRule(w){return this._singleRules.get(w)}$_mapLabels(w){return w=Array.isArray(w)?w:w.split("."),this._ids.labels(w)}$_match(w,x,k,E){(k=Object.assign({},k)).abortEarly=!0,k._externals=!1,x.snapshot();const P=!C.validate(w,this,x,k,E).errors;return x.restore(),P}$_modify(w){return c.assertOptions(w,["each","once","ref","schema"]),y.schema(this,w)||this}$_mutateRebuild(){return a(!this._inRuleset(),"Cannot add this rule inside a ruleset"),this._refs.reset(),this._ids.reset(),this.$_modify({each:(w,{source:x,name:k,path:E,key:P})=>{const O=this._definition[x][k]&&this._definition[x][k].register;O!==!1&&this.$_mutateRegister(w,{family:O,key:P})}}),this._definition.rebuild&&this._definition.rebuild(this),this.$_temp.ruleset=!1,this}$_mutateRegister(w,{family:x,key:k}={}){this._refs.register(w,x),this._ids.register(w,{key:k})}$_property(w){return this._definition.properties[w]}$_reach(w){return this._ids.reach(w)}$_rootReferences(){return this._refs.roots()}$_setFlag(w,x,k={}){a(w[0]==="_"||!this._inRuleset(),"Cannot set flag inside a ruleset");const E=this._definition.flags[w]||{};if(m(x,E.default)&&(x=void 0),m(x,this._flags[w]))return this;const P=k.clone!==!1?this.clone():this;return x!==void 0?(P._flags[w]=x,P.$_mutateRegister(x)):delete P._flags[w],w[0]!=="_"&&(P.$_temp.ruleset=!1),P}$_parent(w,...x){return this[w][c.symbols.parent].call(this,...x)}$_validate(w,x,k){return C.validate(w,this,x,k)}_assign(w){w.type=this.type,w.$_root=this.$_root,w.$_temp=Object.assign({},this.$_temp),w.$_temp.whens={},w._ids=this._ids.clone(),w._preferences=this._preferences,w._valids=this._valids&&this._valids.clone(),w._invalids=this._invalids&&this._invalids.clone(),w._rules=this._rules.slice(),w._singleRules=p(this._singleRules,{shallow:!0}),w._refs=this._refs.clone(),w._flags=Object.assign({},this._flags),w._cache=null,w.$_terms={};for(const x in this.$_terms)w.$_terms[x]=this.$_terms[x]?this.$_terms[x].slice():null;w.$_super={};for(const x in this.$_super)w.$_super[x]=this._super[x].bind(w);return w}_bare(){const w=this.clone();w._reset();const x=w._definition.terms;for(const k in x){const E=x[k];w.$_terms[k]=E.init}return w.$_mutateRebuild()}_default(w,x,k={}){return c.assertOptions(k,"literal"),a(x!==void 0,"Missing",w,"value"),a(typeof x=="function"||!k.literal,"Only function value supports literal option"),typeof x=="function"&&k.literal&&(x={[c.symbols.literal]:!0,literal:x}),this.$_setFlag(w,x)}_generate(w,x,k){if(!this.$_terms.whens)return{schema:this};const E=[],P=[];for(let I=0;I<this.$_terms.whens.length;++I){const L=this.$_terms.whens[I];if(L.concat){E.push(L.concat),P.push(`${I}.concat`);continue}const F=L.ref?L.ref.resolve(w,x,k):w,Z=L.is?[L]:L.switch,Q=P.length;for(let X=0;X<Z.length;++X){const{is:Y,then:se,otherwise:re}=Z[X],Ce=`${I}${L.switch?"."+X:""}`;if(Y.$_match(F,x.nest(Y,`${Ce}.is`),k)){if(se){const ve=x.localize([...x.path,`${Ce}.then`],x.ancestors,x.schemas),{schema:ge,id:de}=se._generate(w,ve,k);E.push(ge),P.push(`${Ce}.then${de?`(${de})`:""}`);break}}else if(re){const ve=x.localize([...x.path,`${Ce}.otherwise`],x.ancestors,x.schemas),{schema:ge,id:de}=re._generate(w,ve,k);E.push(ge),P.push(`${Ce}.otherwise${de?`(${de})`:""}`);break}}if(L.break&&P.length>Q)break}const O=P.join(", ");if(x.mainstay.tracer.debug(x,"rule","when",O),!O)return{schema:this};if(!x.mainstay.tracer.active&&this.$_temp.whens[O])return{schema:this.$_temp.whens[O],id:O};let z=this;this._definition.generate&&(z=this._definition.generate(this,w,x,k));for(const I of E)z=z.concat(I);return this.$_root._tracer&&this.$_root._tracer._combine(z,[this,...E]),this.$_temp.whens[O]=z,{schema:z,id:O}}_inner(w,x,k={}){a(!this._inRuleset(),`Cannot set ${w} inside a ruleset`);const E=this.clone();return E.$_terms[w]&&!k.override||(E.$_terms[w]=[]),k.single?E.$_terms[w].push(x):E.$_terms[w].push(...x),E.$_temp.ruleset=!1,E}_inRuleset(){return this.$_temp.ruleset!==null&&this.$_temp.ruleset!==!1}_ruleRemove(w,x={}){if(!this._singleRules.has(w))return this;const k=x.clone!==!1?this.clone():this;k._singleRules.delete(w);const E=[];for(let P=0;P<k._rules.length;++P){const O=k._rules[P];O.name!==w||O.keep?E.push(O):k._inRuleset()&&P<k.$_temp.ruleset&&--k.$_temp.ruleset}return k._rules=E,k}_values(w,x){c.verifyFlat(w,x.slice(1,-1));const k=this.clone(),E=w[0]===c.symbols.override;if(E&&(w=w.slice(1)),!k[x]&&w.length?k[x]=new S:E&&(k[x]=w.length?new S:null,k.$_mutateRebuild()),!k[x])return k;E&&k[x].override();for(const P of w){a(P!==void 0,"Cannot call allow/valid/invalid with undefined"),a(P!==c.symbols.override,"Override must be the first value");const O=x==="_invalids"?"_valids":"_invalids";k[O]&&(k[O].remove(P),k[O].length||(a(x==="_valids"||!k._flags.only,"Setting invalid value",P,"leaves schema rejecting all values due to previous valid rule"),k[O]=null)),k[x].add(P,k._refs)}return k}}};T.Base.prototype[c.symbols.any]={version:c.version,compile:u.compile,root:"$_root"},T.Base.prototype.isImmutable=!0,T.Base.prototype.deny=T.Base.prototype.invalid,T.Base.prototype.disallow=T.Base.prototype.invalid,T.Base.prototype.equal=T.Base.prototype.valid,T.Base.prototype.exist=T.Base.prototype.required,T.Base.prototype.not=T.Base.prototype.invalid,T.Base.prototype.options=T.Base.prototype.prefs,T.Base.prototype.preferences=T.Base.prototype.prefs,r.exports=new T.Base},8652:(r,n,o)=>{const a=o(375),p=o(8571),m=o(8160),d={max:1e3,supported:new Set(["undefined","boolean","number","string"])};n.provider={provision:l=>new d.Cache(l)},d.Cache=class{constructor(l={}){m.assertOptions(l,["max"]),a(l.max===void 0||l.max&&l.max>0&&isFinite(l.max),"Invalid max cache size"),this._max=l.max||d.max,this._map=new Map,this._list=new d.List}get length(){return this._map.size}set(l,c){if(l!==null&&!d.supported.has(typeof l))return;let u=this._map.get(l);if(u)return u.value=c,void this._list.first(u);u=this._list.unshift({key:l,value:c}),this._map.set(l,u),this._compact()}get(l){const c=this._map.get(l);if(c)return this._list.first(c),p(c.value)}_compact(){if(this._map.size>this._max){const l=this._list.pop();this._map.delete(l.key)}}},d.List=class{constructor(){this.tail=null,this.head=null}unshift(l){return l.next=null,l.prev=this.head,this.head&&(this.head.next=l),this.head=l,this.tail||(this.tail=l),l}first(l){l!==this.head&&(this._remove(l),this.unshift(l))}pop(){return this._remove(this.tail)}_remove(l){const{next:c,prev:u}=l;return c.prev=u,u&&(u.next=c),l===this.tail&&(this.tail=c),l.prev=null,l.next=null,l}}},8160:(r,n,o)=>{const a=o(375),p=o(7916),m=o(5934);let d,l;const c={isoDate:/^(?:[-+]\d{2})?(?:\d{4}(?!\d{2}\b))(?:(-?)(?:(?:0[1-9]|1[0-2])(?:\1(?:[12]\d|0[1-9]|3[01]))?|W(?:[0-4]\d|5[0-2])(?:-?[1-7])?|(?:00[1-9]|0[1-9]\d|[12]\d{2}|3(?:[0-5]\d|6[1-6])))(?![T]$|[T][\d]+Z$)(?:[T\s](?:(?:(?:[01]\d|2[0-3])(?:(:?)[0-5]\d)?|24\:?00)(?:[.,]\d+(?!:))?)(?:\2[0-5]\d(?:[.,]\d+)?)?(?:[Z]|(?:[+-])(?:[01]\d|2[0-3])(?::?[0-5]\d)?)?)?)?$/};n.version=m.version,n.defaults={abortEarly:!0,allowUnknown:!1,artifacts:!1,cache:!0,context:null,convert:!0,dateFormat:"iso",errors:{escapeHtml:!1,label:"path",language:null,render:!0,stack:!1,wrap:{label:'"',array:"[]"}},externals:!0,messages:{},nonEnumerables:!1,noDefaults:!1,presence:"optional",skipFunctions:!1,stripUnknown:!1,warnings:!1},n.symbols={any:Symbol.for("@hapi/joi/schema"),arraySingle:Symbol("arraySingle"),deepDefault:Symbol("deepDefault"),errors:Symbol("errors"),literal:Symbol("literal"),override:Symbol("override"),parent:Symbol("parent"),prefs:Symbol("prefs"),ref:Symbol("ref"),template:Symbol("template"),values:Symbol("values")},n.assertOptions=function(u,h,f="Options"){a(u&&typeof u=="object"&&!Array.isArray(u),"Options must be of type object");const b=Object.keys(u).filter(g=>!h.includes(g));a(b.length===0,`${f} contain unknown keys: ${b}`)},n.checkPreferences=function(u){l=l||o(3378);const h=l.preferences.validate(u);if(h.error)throw new p([h.error.details[0].message])},n.compare=function(u,h,f){switch(f){case"=":return u===h;case">":return u>h;case"<":return u<h;case">=":return u>=h;case"<=":return u<=h}},n.default=function(u,h){return u===void 0?h:u},n.isIsoDate=function(u){return c.isoDate.test(u)},n.isNumber=function(u){return typeof u=="number"&&!isNaN(u)},n.isResolvable=function(u){return!!u&&(u[n.symbols.ref]||u[n.symbols.template])},n.isSchema=function(u,h={}){const f=u&&u[n.symbols.any];return!!f&&(a(h.legacy||f.version===n.version,"Cannot mix different versions of joi schemas"),!0)},n.isValues=function(u){return u[n.symbols.values]},n.limit=function(u){return Number.isSafeInteger(u)&&u>=0},n.preferences=function(u,h){d=d||o(6914),u=u||{},h=h||{};const f=Object.assign({},u,h);return h.errors&&u.errors&&(f.errors=Object.assign({},u.errors,h.errors),f.errors.wrap=Object.assign({},u.errors.wrap,h.errors.wrap)),h.messages&&(f.messages=d.compile(h.messages,u.messages)),delete f[n.symbols.prefs],f},n.tryWithPath=function(u,h,f={}){try{return u()}catch(b){throw b.path!==void 0?b.path=h+"."+b.path:b.path=h,f.append&&(b.message=`${b.message} (${b.path})`),b}},n.validateArg=function(u,h,{assert:f,message:b}){if(n.isSchema(f)){const g=f.validate(u);return g.error?g.error.message:void 0}if(!f(u))return h?`${h} ${b}`:b},n.verifyFlat=function(u,h){for(const f of u)a(!Array.isArray(f),"Method no longer accepts array arguments:",h)}},3292:(r,n,o)=>{const a=o(375),p=o(8160),m=o(6133),d={};n.schema=function(l,c,u={}){p.assertOptions(u,["appendPath","override"]);try{return d.schema(l,c,u)}catch(h){throw u.appendPath&&h.path!==void 0&&(h.message=`${h.message} (${h.path})`),h}},d.schema=function(l,c,u){a(c!==void 0,"Invalid undefined schema"),Array.isArray(c)&&(a(c.length,"Invalid empty array schema"),c.length===1&&(c=c[0]));const h=(f,...b)=>u.override!==!1?f.valid(l.override,...b):f.valid(...b);if(d.simple(c))return h(l,c);if(typeof c=="function")return l.custom(c);if(a(typeof c=="object","Invalid schema content:",typeof c),p.isResolvable(c))return h(l,c);if(p.isSchema(c))return c;if(Array.isArray(c)){for(const f of c)if(!d.simple(f))return l.alternatives().try(...c);return h(l,...c)}return c instanceof RegExp?l.string().regex(c):c instanceof Date?h(l.date(),c):(a(Object.getPrototypeOf(c)===Object.getPrototypeOf({}),"Schema can only contain plain objects"),l.object().keys(c))},n.ref=function(l,c){return m.isRef(l)?l:m.create(l,c)},n.compile=function(l,c,u={}){p.assertOptions(u,["legacy"]);const h=c&&c[p.symbols.any];if(h)return a(u.legacy||h.version===p.version,"Cannot mix different versions of joi schemas:",h.version,p.version),c;if(typeof c!="object"||!u.legacy)return n.schema(l,c,{appendPath:!0});const f=d.walk(c);return f?f.compile(f.root,c):n.schema(l,c,{appendPath:!0})},d.walk=function(l){if(typeof l!="object")return null;if(Array.isArray(l)){for(const u of l){const h=d.walk(u);if(h)return h}return null}const c=l[p.symbols.any];if(c)return{root:l[c.root],compile:c.compile};a(Object.getPrototypeOf(l)===Object.getPrototypeOf({}),"Schema can only contain plain objects");for(const u in l){const h=d.walk(l[u]);if(h)return h}return null},d.simple=function(l){return l===null||["boolean","string","number"].includes(typeof l)},n.when=function(l,c,u){if(u===void 0&&(a(c&&typeof c=="object","Missing options"),u=c,c=m.create(".")),Array.isArray(u)&&(u={switch:u}),p.assertOptions(u,["is","not","then","otherwise","switch","break"]),p.isSchema(c))return a(u.is===void 0,'"is" can not be used with a schema condition'),a(u.not===void 0,'"not" can not be used with a schema condition'),a(u.switch===void 0,'"switch" can not be used with a schema condition'),d.condition(l,{is:c,then:u.then,otherwise:u.otherwise,break:u.break});if(a(m.isRef(c)||typeof c=="string","Invalid condition:",c),a(u.not===void 0||u.is===void 0,'Cannot combine "is" with "not"'),u.switch===void 0){let f=u;u.not!==void 0&&(f={is:u.not,then:u.otherwise,otherwise:u.then,break:u.break});let b=f.is!==void 0?l.$_compile(f.is):l.$_root.invalid(null,!1,0,"").required();return a(f.then!==void 0||f.otherwise!==void 0,'options must have at least one of "then", "otherwise", or "switch"'),a(f.break===void 0||f.then===void 0||f.otherwise===void 0,"Cannot specify then, otherwise, and break all together"),u.is===void 0||m.isRef(u.is)||p.isSchema(u.is)||(b=b.required()),d.condition(l,{ref:n.ref(c),is:b,then:f.then,otherwise:f.otherwise,break:f.break})}a(Array.isArray(u.switch),'"switch" must be an array'),a(u.is===void 0,'Cannot combine "switch" with "is"'),a(u.not===void 0,'Cannot combine "switch" with "not"'),a(u.then===void 0,'Cannot combine "switch" with "then"');const h={ref:n.ref(c),switch:[],break:u.break};for(let f=0;f<u.switch.length;++f){const b=u.switch[f],g=f===u.switch.length-1;p.assertOptions(b,g?["is","then","otherwise"]:["is","then"]),a(b.is!==void 0,'Switch statement missing "is"'),a(b.then!==void 0,'Switch statement missing "then"');const y={is:l.$_compile(b.is),then:l.$_compile(b.then)};if(m.isRef(b.is)||p.isSchema(b.is)||(y.is=y.is.required()),g){a(u.otherwise===void 0||b.otherwise===void 0,'Cannot specify "otherwise" inside and outside a "switch"');const v=u.otherwise!==void 0?u.otherwise:b.otherwise;v!==void 0&&(a(h.break===void 0,"Cannot specify both otherwise and break"),y.otherwise=l.$_compile(v))}h.switch.push(y)}return h},d.condition=function(l,c){for(const u of["then","otherwise"])c[u]===void 0?delete c[u]:c[u]=l.$_compile(c[u]);return c}},6354:(r,n,o)=>{const a=o(5688),p=o(8160),m=o(3328);n.Report=class{constructor(d,l,c,u,h,f,b){if(this.code=d,this.flags=u,this.messages=h,this.path=f.path,this.prefs=b,this.state=f,this.value=l,this.message=null,this.template=null,this.local=c||{},this.local.label=n.label(this.flags,this.state,this.prefs,this.messages),this.value===void 0||this.local.hasOwnProperty("value")||(this.local.value=this.value),this.path.length){const g=this.path[this.path.length-1];typeof g!="object"&&(this.local.key=g)}}_setTemplate(d){if(this.template=d,!this.flags.label&&this.path.length===0){const l=this._template(this.template,"root");l&&(this.local.label=l)}}toString(){if(this.message)return this.message;const d=this.code;if(!this.prefs.errors.render)return this.code;const l=this._template(this.template)||this._template(this.prefs.messages)||this._template(this.messages);return l===void 0?`Error code "${d}" is not defined, your custom type is missing the correct messages definition`:(this.message=l.render(this.value,this.state,this.prefs,this.local,{errors:this.prefs.errors,messages:[this.prefs.messages,this.messages]}),this.prefs.errors.label||(this.message=this.message.replace(/^"" /,"").trim()),this.message)}_template(d,l){return n.template(this.value,d,l||this.code,this.state,this.prefs)}},n.path=function(d){let l="";for(const c of d)typeof c!="object"&&(typeof c=="string"?(l&&(l+="."),l+=c):l+=`[${c}]`);return l},n.template=function(d,l,c,u,h){if(!l)return;if(m.isTemplate(l))return c!=="root"?l:null;let f=h.errors.language;if(p.isResolvable(f)&&(f=f.resolve(d,u,h)),f&&l[f]){if(l[f][c]!==void 0)return l[f][c];if(l[f]["*"]!==void 0)return l[f]["*"]}return l[c]?l[c]:l["*"]},n.label=function(d,l,c,u){if(!c.errors.label)return"";if(d.label)return d.label;let h=l.path;return c.errors.label==="key"&&l.path.length>1&&(h=l.path.slice(-1)),n.path(h)||n.template(null,c.messages,"root",l,c)||u&&n.template(null,u,"root",l,c)||"value"},n.process=function(d,l,c){if(!d)return null;const{override:u,message:h,details:f}=n.details(d);if(u)return u;if(c.errors.stack)return new n.ValidationError(h,f,l);const b=Error.stackTraceLimit;Error.stackTraceLimit=0;const g=new n.ValidationError(h,f,l);return Error.stackTraceLimit=b,g},n.details=function(d,l={}){let c=[];const u=[];for(const h of d){if(h instanceof Error){if(l.override!==!1)return{override:h};const b=h.toString();c.push(b),u.push({message:b,type:"override",context:{error:h}});continue}const f=h.toString();c.push(f),u.push({message:f,path:h.path.filter(b=>typeof b!="object"),type:h.code,context:h.local})}return c.length>1&&(c=[...new Set(c)]),{message:c.join(". "),details:u}},n.ValidationError=class extends Error{constructor(d,l,c){super(d),this._original=c,this.details=l}static isError(d){return d instanceof n.ValidationError}},n.ValidationError.prototype.isJoi=!0,n.ValidationError.prototype.name="ValidationError",n.ValidationError.prototype.annotate=a.error},8901:(r,n,o)=>{const a=o(375),p=o(8571),m=o(8160),d=o(6914),l={};n.type=function(c,u){const h=Object.getPrototypeOf(c),f=p(h),b=c._assign(Object.create(f)),g=Object.assign({},u);delete g.base,f._definition=g;const y=h._definition||{};g.messages=d.merge(y.messages,g.messages),g.properties=Object.assign({},y.properties,g.properties),b.type=g.type,g.flags=Object.assign({},y.flags,g.flags);const v=Object.assign({},y.terms);if(g.terms)for(const T in g.terms){const w=g.terms[T];a(b.$_terms[T]===void 0,"Invalid term override for",g.type,T),b.$_terms[T]=w.init,v[T]=w}g.terms=v,g.args||(g.args=y.args),g.prepare=l.prepare(g.prepare,y.prepare),g.coerce&&(typeof g.coerce=="function"&&(g.coerce={method:g.coerce}),g.coerce.from&&!Array.isArray(g.coerce.from)&&(g.coerce={method:g.coerce.method,from:[].concat(g.coerce.from)})),g.coerce=l.coerce(g.coerce,y.coerce),g.validate=l.validate(g.validate,y.validate);const _=Object.assign({},y.rules);if(g.rules)for(const T in g.rules){const w=g.rules[T];a(typeof w=="object","Invalid rule definition for",g.type,T);let x=w.method;if(x===void 0&&(x=function(){return this.$_addRule(T)}),x&&(a(!f[T],"Rule conflict in",g.type,T),f[T]=x),a(!_[T],"Rule conflict in",g.type,T),_[T]=w,w.alias){const k=[].concat(w.alias);for(const E of k)f[E]=w.method}w.args&&(w.argsByName=new Map,w.args=w.args.map(k=>(typeof k=="string"&&(k={name:k}),a(!w.argsByName.has(k.name),"Duplicated argument name",k.name),m.isSchema(k.assert)&&(k.assert=k.assert.strict().label(k.name)),w.argsByName.set(k.name,k),k)))}g.rules=_;const C=Object.assign({},y.modifiers);if(g.modifiers)for(const T in g.modifiers){a(!f[T],"Rule conflict in",g.type,T);const w=g.modifiers[T];a(typeof w=="function","Invalid modifier definition for",g.type,T);const x=function(k){return this.rule({[T]:k})};f[T]=x,C[T]=w}if(g.modifiers=C,g.overrides){f._super=h,b.$_super={};for(const T in g.overrides)a(h[T],"Cannot override missing",T),g.overrides[T][m.symbols.parent]=h[T],b.$_super[T]=h[T].bind(b);Object.assign(f,g.overrides)}g.cast=Object.assign({},y.cast,g.cast);const S=Object.assign({},y.manifest,g.manifest);return S.build=l.build(g.manifest&&g.manifest.build,y.manifest&&y.manifest.build),g.manifest=S,g.rebuild=l.rebuild(g.rebuild,y.rebuild),b},l.build=function(c,u){return c&&u?function(h,f){return u(c(h,f),f)}:c||u},l.coerce=function(c,u){return c&&u?{from:c.from&&u.from?[...new Set([...c.from,...u.from])]:null,method(h,f){let b;if((!u.from||u.from.includes(typeof h))&&(b=u.method(h,f),b)){if(b.errors||b.value===void 0)return b;h=b.value}if(!c.from||c.from.includes(typeof h)){const g=c.method(h,f);if(g)return g}return b}}:c||u},l.prepare=function(c,u){return c&&u?function(h,f){const b=c(h,f);if(b){if(b.errors||b.value===void 0)return b;h=b.value}return u(h,f)||b}:c||u},l.rebuild=function(c,u){return c&&u?function(h){u(h),c(h)}:c||u},l.validate=function(c,u){return c&&u?function(h,f){const b=u(h,f);if(b){if(b.errors&&(!Array.isArray(b.errors)||b.errors.length))return b;h=b.value}return c(h,f)||b}:c||u}},5107:(r,n,o)=>{const a=o(375),p=o(8571),m=o(8652),d=o(8160),l=o(3292),c=o(6354),u=o(8901),h=o(9708),f=o(6133),b=o(3328),g=o(1152);let y;const v={types:{alternatives:o(4946),any:o(8068),array:o(546),boolean:o(4937),date:o(7500),function:o(390),link:o(8785),number:o(3832),object:o(8966),string:o(7417),symbol:o(8826)},aliases:{alt:"alternatives",bool:"boolean",func:"function"},root:function(){const _={_types:new Set(Object.keys(v.types))};for(const C of _._types)_[C]=function(...S){return a(!S.length||["alternatives","link","object"].includes(C),"The",C,"type does not allow arguments"),v.generate(this,v.types[C],S)};for(const C of["allow","custom","disallow","equal","exist","forbidden","invalid","not","only","optional","options","prefs","preferences","required","strip","valid","when"])_[C]=function(...S){return this.any()[C](...S)};Object.assign(_,v.methods);for(const C in v.aliases){const S=v.aliases[C];_[C]=_[S]}return _.x=_.expression,g.setup&&g.setup(_),_}};v.methods={ValidationError:c.ValidationError,version:d.version,cache:m.provider,assert(_,C,...S){v.assert(_,C,!0,S)},attempt:(_,C,...S)=>v.assert(_,C,!1,S),build(_){return a(typeof h.build=="function","Manifest functionality disabled"),h.build(this,_)},checkPreferences(_){d.checkPreferences(_)},compile(_,C){return l.compile(this,_,C)},defaults(_){a(typeof _=="function","modifier must be a function");const C=Object.assign({},this);for(const S of C._types){const T=_(C[S]());a(d.isSchema(T),"modifier must return a valid schema object"),C[S]=function(...w){return v.generate(this,T,w)}}return C},expression:(..._)=>new b(..._),extend(..._){d.verifyFlat(_,"extend"),y=y||o(3378),a(_.length,"You need to provide at least one extension"),this.assert(_,y.extensions);const C=Object.assign({},this);C._types=new Set(C._types);for(let S of _){typeof S=="function"&&(S=S(C)),this.assert(S,y.extension);const T=v.expandExtension(S,C);for(const w of T){a(C[w.type]===void 0||C._types.has(w.type),"Cannot override name",w.type);const x=w.base||this.any(),k=u.type(x,w);C._types.add(w.type),C[w.type]=function(...E){return v.generate(this,k,E)}}}return C},isError:c.ValidationError.isError,isExpression:b.isTemplate,isRef:f.isRef,isSchema:d.isSchema,in:(..._)=>f.in(..._),override:d.symbols.override,ref:(..._)=>f.create(..._),types(){const _={};for(const C of this._types)_[C]=this[C]();for(const C in v.aliases)_[C]=this[C]();return _}},v.assert=function(_,C,S,T){const w=T[0]instanceof Error||typeof T[0]=="string"?T[0]:null,x=w!==null?T[1]:T[0],k=C.validate(_,d.preferences({errors:{stack:!0}},x||{}));let E=k.error;if(!E)return k.value;if(w instanceof Error)throw w;const P=S&&typeof E.annotate=="function"?E.annotate():E.message;throw E instanceof c.ValidationError==0&&(E=p(E)),E.message=w?`${w} ${P}`:P,E},v.generate=function(_,C,S){return a(_,"Must be invoked on a Joi instance."),C.$_root=_,C._definition.args&&S.length?C._definition.args(C,...S):C},v.expandExtension=function(_,C){if(typeof _.type=="string")return[_];const S=[];for(const T of C._types)if(_.type.test(T)){const w=Object.assign({},_);w.type=T,w.base=C[T](),S.push(w)}return S},r.exports=v.root()},6914:(r,n,o)=>{const a=o(375),p=o(8571),m=o(3328);n.compile=function(d,l){if(typeof d=="string")return a(!l,"Cannot set single message string"),new m(d);if(m.isTemplate(d))return a(!l,"Cannot set single message template"),d;a(typeof d=="object"&&!Array.isArray(d),"Invalid message options"),l=l?p(l):{};for(let c in d){const u=d[c];if(c==="root"||m.isTemplate(u)){l[c]=u;continue}if(typeof u=="string"){l[c]=new m(u);continue}a(typeof u=="object"&&!Array.isArray(u),"Invalid message for",c);const h=c;for(c in l[h]=l[h]||{},u){const f=u[c];c==="root"||m.isTemplate(f)?l[h][c]=f:(a(typeof f=="string","Invalid message for",c,"in",h),l[h][c]=new m(f))}}return l},n.decompile=function(d){const l={};for(let c in d){const u=d[c];if(c==="root"){l.root=u;continue}if(m.isTemplate(u)){l[c]=u.describe({compact:!0});continue}const h=c;for(c in l[h]={},u){const f=u[c];c!=="root"?l[h][c]=f.describe({compact:!0}):l[h].root=f}}return l},n.merge=function(d,l){if(!d)return n.compile(l);if(!l)return d;if(typeof l=="string")return new m(l);if(m.isTemplate(l))return l;const c=p(d);for(let u in l){const h=l[u];if(u==="root"||m.isTemplate(h)){c[u]=h;continue}if(typeof h=="string"){c[u]=new m(h);continue}a(typeof h=="object"&&!Array.isArray(h),"Invalid message for",u);const f=u;for(u in c[f]=c[f]||{},h){const b=h[u];u==="root"||m.isTemplate(b)?c[f][u]=b:(a(typeof b=="string","Invalid message for",u,"in",f),c[f][u]=new m(b))}}return c}},2294:(r,n,o)=>{const a=o(375),p=o(8160),m=o(6133),d={};n.Ids=d.Ids=class{constructor(){this._byId=new Map,this._byKey=new Map,this._schemaChain=!1}clone(){const l=new d.Ids;return l._byId=new Map(this._byId),l._byKey=new Map(this._byKey),l._schemaChain=this._schemaChain,l}concat(l){l._schemaChain&&(this._schemaChain=!0);for(const[c,u]of l._byId.entries())a(!this._byKey.has(c),"Schema id conflicts with existing key:",c),this._byId.set(c,u);for(const[c,u]of l._byKey.entries())a(!this._byId.has(c),"Schema key conflicts with existing id:",c),this._byKey.set(c,u)}fork(l,c,u){const h=this._collect(l);h.push({schema:u});const f=h.shift();let b={id:f.id,schema:c(f.schema)};a(p.isSchema(b.schema),"adjuster function failed to return a joi schema type");for(const g of h)b={id:g.id,schema:d.fork(g.schema,b.id,b.schema)};return b.schema}labels(l,c=[]){const u=l[0],h=this._get(u);if(!h)return[...c,...l].join(".");const f=l.slice(1);return c=[...c,h.schema._flags.label||u],f.length?h.schema._ids.labels(f,c):c.join(".")}reach(l,c=[]){const u=l[0],h=this._get(u);a(h,"Schema does not contain path",[...c,...l].join("."));const f=l.slice(1);return f.length?h.schema._ids.reach(f,[...c,u]):h.schema}register(l,{key:c}={}){if(!l||!p.isSchema(l))return;(l.$_property("schemaChain")||l._ids._schemaChain)&&(this._schemaChain=!0);const u=l._flags.id;if(u){const h=this._byId.get(u);a(!h||h.schema===l,"Cannot add different schemas with the same id:",u),a(!this._byKey.has(u),"Schema id conflicts with existing key:",u),this._byId.set(u,{schema:l,id:u})}c&&(a(!this._byKey.has(c),"Schema already contains key:",c),a(!this._byId.has(c),"Schema key conflicts with existing id:",c),this._byKey.set(c,{schema:l,id:c}))}reset(){this._byId=new Map,this._byKey=new Map,this._schemaChain=!1}_collect(l,c=[],u=[]){const h=l[0],f=this._get(h);a(f,"Schema does not contain path",[...c,...l].join(".")),u=[f,...u];const b=l.slice(1);return b.length?f.schema._ids._collect(b,[...c,h],u):u}_get(l){return this._byId.get(l)||this._byKey.get(l)}},d.fork=function(l,c,u){const h=n.schema(l,{each:(f,{key:b})=>{if(c===(f._flags.id||b))return u},ref:!1});return h?h.$_mutateRebuild():l},n.schema=function(l,c){let u;for(const h in l._flags){if(h[0]==="_")continue;const f=d.scan(l._flags[h],{source:"flags",name:h},c);f!==void 0&&(u=u||l.clone(),u._flags[h]=f)}for(let h=0;h<l._rules.length;++h){const f=l._rules[h],b=d.scan(f.args,{source:"rules",name:f.name},c);if(b!==void 0){u=u||l.clone();const g=Object.assign({},f);g.args=b,u._rules[h]=g,u._singleRules.get(f.name)===f&&u._singleRules.set(f.name,g)}}for(const h in l.$_terms){if(h[0]==="_")continue;const f=d.scan(l.$_terms[h],{source:"terms",name:h},c);f!==void 0&&(u=u||l.clone(),u.$_terms[h]=f)}return u},d.scan=function(l,c,u,h,f){const b=h||[];if(l===null||typeof l!="object")return;let g;if(Array.isArray(l)){for(let y=0;y<l.length;++y){const v=c.source==="terms"&&c.name==="keys"&&l[y].key,_=d.scan(l[y],c,u,[y,...b],v);_!==void 0&&(g=g||l.slice(),g[y]=_)}return g}if(u.schema!==!1&&p.isSchema(l)||u.ref!==!1&&m.isRef(l)){const y=u.each(l,{...c,path:b,key:f});return y===l?void 0:y}for(const y in l){if(y[0]==="_")continue;const v=d.scan(l[y],c,u,[y,...b],f);v!==void 0&&(g=g||Object.assign({},l),g[y]=v)}return g}},6133:(r,n,o)=>{const a=o(375),p=o(8571),m=o(9621),d=o(8160);let l;const c={symbol:Symbol("ref"),defaults:{adjust:null,in:!1,iterables:null,map:null,separator:".",type:"value"}};n.create=function(u,h={}){a(typeof u=="string","Invalid reference key:",u),d.assertOptions(h,["adjust","ancestor","in","iterables","map","prefix","render","separator"]),a(!h.prefix||typeof h.prefix=="object","options.prefix must be of type object");const f=Object.assign({},c.defaults,h);delete f.prefix;const b=f.separator,g=c.context(u,b,h.prefix);if(f.type=g.type,u=g.key,f.type==="value")if(g.root&&(a(!b||u[0]!==b,"Cannot specify relative path with root prefix"),f.ancestor="root",u||(u=null)),b&&b===u)u=null,f.ancestor=0;else if(f.ancestor!==void 0)a(!b||!u||u[0]!==b,"Cannot combine prefix with ancestor option");else{const[y,v]=c.ancestor(u,b);v&&(u=u.slice(v))===""&&(u=null),f.ancestor=y}return f.path=b?u===null?[]:u.split(b):[u],new c.Ref(f)},n.in=function(u,h={}){return n.create(u,{...h,in:!0})},n.isRef=function(u){return!!u&&!!u[d.symbols.ref]},c.Ref=class{constructor(u){a(typeof u=="object","Invalid reference construction"),d.assertOptions(u,["adjust","ancestor","in","iterables","map","path","render","separator","type","depth","key","root","display"]),a([!1,void 0].includes(u.separator)||typeof u.separator=="string"&&u.separator.length===1,"Invalid separator"),a(!u.adjust||typeof u.adjust=="function","options.adjust must be a function"),a(!u.map||Array.isArray(u.map),"options.map must be an array"),a(!u.map||!u.adjust,"Cannot set both map and adjust options"),Object.assign(this,c.defaults,u),a(this.type==="value"||this.ancestor===void 0,"Non-value references cannot reference ancestors"),Array.isArray(this.map)&&(this.map=new Map(this.map)),this.depth=this.path.length,this.key=this.path.length?this.path.join(this.separator):null,this.root=this.path[0],this.updateDisplay()}resolve(u,h,f,b,g={}){return a(!this.in||g.in,"Invalid in() reference usage"),this.type==="global"?this._resolve(f.context,h,g):this.type==="local"?this._resolve(b,h,g):this.ancestor?this.ancestor==="root"?this._resolve(h.ancestors[h.ancestors.length-1],h,g):(a(this.ancestor<=h.ancestors.length,"Invalid reference exceeds the schema root:",this.display),this._resolve(h.ancestors[this.ancestor-1],h,g)):this._resolve(u,h,g)}_resolve(u,h,f){let b;if(this.type==="value"&&h.mainstay.shadow&&f.shadow!==!1&&(b=h.mainstay.shadow.get(this.absolute(h))),b===void 0&&(b=m(u,this.path,{iterables:this.iterables,functions:!0})),this.adjust&&(b=this.adjust(b)),this.map){const g=this.map.get(b);g!==void 0&&(b=g)}return h.mainstay&&h.mainstay.tracer.resolve(h,this,b),b}toString(){return this.display}absolute(u){return[...u.path.slice(0,-this.ancestor),...this.path]}clone(){return new c.Ref(this)}describe(){const u={path:this.path};this.type!=="value"&&(u.type=this.type),this.separator!=="."&&(u.separator=this.separator),this.type==="value"&&this.ancestor!==1&&(u.ancestor=this.ancestor),this.map&&(u.map=[...this.map]);for(const h of["adjust","iterables","render"])this[h]!==null&&this[h]!==void 0&&(u[h]=this[h]);return this.in!==!1&&(u.in=!0),{ref:u}}updateDisplay(){const u=this.key!==null?this.key:"";if(this.type!=="value")return void(this.display=`ref:${this.type}:${u}`);if(!this.separator)return void(this.display=`ref:${u}`);if(!this.ancestor)return void(this.display=`ref:${this.separator}${u}`);if(this.ancestor==="root")return void(this.display=`ref:root:${u}`);if(this.ancestor===1)return void(this.display=`ref:${u||".."}`);const h=new Array(this.ancestor+1).fill(this.separator).join("");this.display=`ref:${h}${u||""}`}},c.Ref.prototype[d.symbols.ref]=!0,n.build=function(u){return(u=Object.assign({},c.defaults,u)).type==="value"&&u.ancestor===void 0&&(u.ancestor=1),new c.Ref(u)},c.context=function(u,h,f={}){if(u=u.trim(),f){const b=f.global===void 0?"$":f.global;if(b!==h&&u.startsWith(b))return{key:u.slice(b.length),type:"global"};const g=f.local===void 0?"#":f.local;if(g!==h&&u.startsWith(g))return{key:u.slice(g.length),type:"local"};const y=f.root===void 0?"/":f.root;if(y!==h&&u.startsWith(y))return{key:u.slice(y.length),type:"value",root:!0}}return{key:u,type:"value"}},c.ancestor=function(u,h){if(!h)return[1,0];if(u[0]!==h)return[1,0];if(u[1]!==h)return[0,1];let f=2;for(;u[f]===h;)++f;return[f-1,f]},n.toSibling=0,n.toParent=1,n.Manager=class{constructor(){this.refs=[]}register(u,h){if(u)if(h=h===void 0?n.toParent:h,Array.isArray(u))for(const f of u)this.register(f,h);else if(d.isSchema(u))for(const f of u._refs.refs)f.ancestor-h>=0&&this.refs.push({ancestor:f.ancestor-h,root:f.root});else n.isRef(u)&&u.type==="value"&&u.ancestor-h>=0&&this.refs.push({ancestor:u.ancestor-h,root:u.root}),l=l||o(3328),l.isTemplate(u)&&this.register(u.refs(),h)}get length(){return this.refs.length}clone(){const u=new n.Manager;return u.refs=p(this.refs),u}reset(){this.refs=[]}roots(){return this.refs.filter(u=>!u.ancestor).map(u=>u.root)}}},3378:(r,n,o)=>{const a=o(5107),p={};p.wrap=a.string().min(1).max(2).allow(!1),n.preferences=a.object({allowUnknown:a.boolean(),abortEarly:a.boolean(),artifacts:a.boolean(),cache:a.boolean(),context:a.object(),convert:a.boolean(),dateFormat:a.valid("date","iso","string","time","utc"),debug:a.boolean(),errors:{escapeHtml:a.boolean(),label:a.valid("path","key",!1),language:[a.string(),a.object().ref()],render:a.boolean(),stack:a.boolean(),wrap:{label:p.wrap,array:p.wrap,string:p.wrap}},externals:a.boolean(),messages:a.object(),noDefaults:a.boolean(),nonEnumerables:a.boolean(),presence:a.valid("required","optional","forbidden"),skipFunctions:a.boolean(),stripUnknown:a.object({arrays:a.boolean(),objects:a.boolean()}).or("arrays","objects").allow(!0,!1),warnings:a.boolean()}).strict(),p.nameRx=/^[a-zA-Z0-9]\w*$/,p.rule=a.object({alias:a.array().items(a.string().pattern(p.nameRx)).single(),args:a.array().items(a.string(),a.object({name:a.string().pattern(p.nameRx).required(),ref:a.boolean(),assert:a.alternatives([a.function(),a.object().schema()]).conditional("ref",{is:!0,then:a.required()}),normalize:a.function(),message:a.string().when("assert",{is:a.function(),then:a.required()})})),convert:a.boolean(),manifest:a.boolean(),method:a.function().allow(!1),multi:a.boolean(),validate:a.function()}),n.extension=a.object({type:a.alternatives([a.string(),a.object().regex()]).required(),args:a.function(),cast:a.object().pattern(p.nameRx,a.object({from:a.function().maxArity(1).required(),to:a.function().minArity(1).maxArity(2).required()})),base:a.object().schema().when("type",{is:a.object().regex(),then:a.forbidden()}),coerce:[a.function().maxArity(3),a.object({method:a.function().maxArity(3).required(),from:a.array().items(a.string()).single()})],flags:a.object().pattern(p.nameRx,a.object({setter:a.string(),default:a.any()})),manifest:{build:a.function().arity(2)},messages:[a.object(),a.string()],modifiers:a.object().pattern(p.nameRx,a.function().minArity(1).maxArity(2)),overrides:a.object().pattern(p.nameRx,a.function()),prepare:a.function().maxArity(3),rebuild:a.function().arity(1),rules:a.object().pattern(p.nameRx,p.rule),terms:a.object().pattern(p.nameRx,a.object({init:a.array().allow(null).required(),manifest:a.object().pattern(/.+/,[a.valid("schema","single"),a.object({mapped:a.object({from:a.string().required(),to:a.string().required()}).required()})])})),validate:a.function().maxArity(3)}).strict(),n.extensions=a.array().items(a.object(),a.function().arity(1)).strict(),p.desc={buffer:a.object({buffer:a.string()}),func:a.object({function:a.function().required(),options:{literal:!0}}),override:a.object({override:!0}),ref:a.object({ref:a.object({type:a.valid("value","global","local"),path:a.array().required(),separator:a.string().length(1).allow(!1),ancestor:a.number().min(0).integer().allow("root"),map:a.array().items(a.array().length(2)).min(1),adjust:a.function(),iterables:a.boolean(),in:a.boolean(),render:a.boolean()}).required()}),regex:a.object({regex:a.string().min(3)}),special:a.object({special:a.valid("deep").required()}),template:a.object({template:a.string().required(),options:a.object()}),value:a.object({value:a.alternatives([a.object(),a.array()]).required()})},p.desc.entity=a.alternatives([a.array().items(a.link("...")),a.boolean(),a.function(),a.number(),a.string(),p.desc.buffer,p.desc.func,p.desc.ref,p.desc.regex,p.desc.special,p.desc.template,p.desc.value,a.link("/")]),p.desc.values=a.array().items(null,a.boolean(),a.function(),a.number().allow(1/0,-1/0),a.string().allow(""),a.symbol(),p.desc.buffer,p.desc.func,p.desc.override,p.desc.ref,p.desc.regex,p.desc.template,p.desc.value),p.desc.messages=a.object().pattern(/.+/,[a.string(),p.desc.template,a.object().pattern(/.+/,[a.string(),p.desc.template])]),n.description=a.object({type:a.string().required(),flags:a.object({cast:a.string(),default:a.any(),description:a.string(),empty:a.link("/"),failover:p.desc.entity,id:a.string(),label:a.string(),only:!0,presence:["optional","required","forbidden"],result:["raw","strip"],strip:a.boolean(),unit:a.string()}).unknown(),preferences:{allowUnknown:a.boolean(),abortEarly:a.boolean(),artifacts:a.boolean(),cache:a.boolean(),convert:a.boolean(),dateFormat:["date","iso","string","time","utc"],errors:{escapeHtml:a.boolean(),label:["path","key"],language:[a.string(),p.desc.ref],wrap:{label:p.wrap,array:p.wrap}},externals:a.boolean(),messages:p.desc.messages,noDefaults:a.boolean(),nonEnumerables:a.boolean(),presence:["required","optional","forbidden"],skipFunctions:a.boolean(),stripUnknown:a.object({arrays:a.boolean(),objects:a.boolean()}).or("arrays","objects").allow(!0,!1),warnings:a.boolean()},allow:p.desc.values,invalid:p.desc.values,rules:a.array().min(1).items({name:a.string().required(),args:a.object().min(1),keep:a.boolean(),message:[a.string(),p.desc.messages],warn:a.boolean()}),keys:a.object().pattern(/.*/,a.link("/")),link:p.desc.ref}).pattern(/^[a-z]\w*$/,a.any())},493:(r,n,o)=>{const a=o(8571),p=o(9621),m=o(8160),d={value:Symbol("value")};r.exports=d.State=class{constructor(l,c,u){this.path=l,this.ancestors=c,this.mainstay=u.mainstay,this.schemas=u.schemas,this.debug=null}localize(l,c=null,u=null){const h=new d.State(l,c,this);return u&&h.schemas&&(h.schemas=[d.schemas(u),...h.schemas]),h}nest(l,c){const u=new d.State(this.path,this.ancestors,this);return u.schemas=u.schemas&&[d.schemas(l),...u.schemas],u.debug=c,u}shadow(l,c){this.mainstay.shadow=this.mainstay.shadow||new d.Shadow,this.mainstay.shadow.set(this.path,l,c)}snapshot(){this.mainstay.shadow&&(this._snapshot=a(this.mainstay.shadow.node(this.path))),this.mainstay.snapshot()}restore(){this.mainstay.shadow&&(this.mainstay.shadow.override(this.path,this._snapshot),this._snapshot=void 0),this.mainstay.restore()}commit(){this.mainstay.shadow&&(this.mainstay.shadow.override(this.path,this._snapshot),this._snapshot=void 0),this.mainstay.commit()}},d.schemas=function(l){return m.isSchema(l)?{schema:l}:l},d.Shadow=class{constructor(){this._values=null}set(l,c,u){if(!l.length||u==="strip"&&typeof l[l.length-1]=="number")return;this._values=this._values||new Map;let h=this._values;for(let f=0;f<l.length;++f){const b=l[f];let g=h.get(b);g||(g=new Map,h.set(b,g)),h=g}h[d.value]=c}get(l){const c=this.node(l);if(c)return c[d.value]}node(l){if(this._values)return p(this._values,l,{iterables:!0})}override(l,c){if(!this._values)return;const u=l.slice(0,-1),h=l[l.length-1],f=p(this._values,u,{iterables:!0});c?f.set(h,c):f&&f.delete(h)}}},3328:(r,n,o)=>{const a=o(375),p=o(8571),m=o(5277),d=o(1447),l=o(8160),c=o(6354),u=o(6133),h={symbol:Symbol("template"),opens:new Array(1e3).join("\0"),closes:new Array(1e3).join(""),dateFormat:{date:Date.prototype.toDateString,iso:Date.prototype.toISOString,string:Date.prototype.toString,time:Date.prototype.toTimeString,utc:Date.prototype.toUTCString}};r.exports=h.Template=class{constructor(f,b){if(a(typeof f=="string","Template source must be a string"),a(!f.includes("\0")&&!f.includes(""),"Template source cannot contain reserved control characters"),this.source=f,this.rendered=f,this._template=null,b){const{functions:g,...y}=b;this._settings=Object.keys(y).length?p(y):void 0,this._functions=g,this._functions&&(a(Object.keys(this._functions).every(v=>typeof v=="string"),"Functions keys must be strings"),a(Object.values(this._functions).every(v=>typeof v=="function"),"Functions values must be functions"))}else this._settings=void 0,this._functions=void 0;this._parse()}_parse(){if(!this.source.includes("{"))return;const f=h.encode(this.source),b=h.split(f);let g=!1;const y=[],v=b.shift();v&&y.push(v);for(const _ of b){const C=_[0]!=="{",S=C?"}":"}}",T=_.indexOf(S);if(T===-1||_[1]==="{"){y.push(`{${h.decode(_)}`);continue}let w=_.slice(C?0:1,T);const x=w[0]===":";x&&(w=w.slice(1));const k=this._ref(h.decode(w),{raw:C,wrapped:x});y.push(k),typeof k!="string"&&(g=!0);const E=_.slice(T+S.length);E&&y.push(h.decode(E))}g?this._template=y:this.rendered=y.join("")}static date(f,b){return h.dateFormat[b.dateFormat].call(f)}describe(f={}){if(!this._settings&&f.compact)return this.source;const b={template:this.source};return this._settings&&(b.options=this._settings),this._functions&&(b.functions=this._functions),b}static build(f){return new h.Template(f.template,f.options||f.functions?{...f.options,functions:f.functions}:void 0)}isDynamic(){return!!this._template}static isTemplate(f){return!!f&&!!f[l.symbols.template]}refs(){if(!this._template)return;const f=[];for(const b of this._template)typeof b!="string"&&f.push(...b.refs);return f}resolve(f,b,g,y){return this._template&&this._template.length===1?this._part(this._template[0],f,b,g,y,{}):this.render(f,b,g,y)}_part(f,...b){return f.ref?f.ref.resolve(...b):f.formula.evaluate(b)}render(f,b,g,y,v={}){if(!this.isDynamic())return this.rendered;const _=[];for(const C of this._template)if(typeof C=="string")_.push(C);else{const S=this._part(C,f,b,g,y,v),T=h.stringify(S,f,b,g,y,v);if(T!==void 0){const w=C.raw||(v.errors&&v.errors.escapeHtml)===!1?T:m(T);_.push(h.wrap(w,C.wrapped&&g.errors.wrap.label))}}return _.join("")}_ref(f,{raw:b,wrapped:g}){const y=[],v=C=>{const S=u.create(C,this._settings);return y.push(S),T=>{const w=S.resolve(...T);return w!==void 0?w:null}};try{const C=this._functions?{...h.functions,...this._functions}:h.functions;var _=new d.Parser(f,{reference:v,functions:C,constants:h.constants})}catch(C){throw C.message=`Invalid template variable "${f}" fails due to: ${C.message}`,C}if(_.single){if(_.single.type==="reference"){const C=y[0];return{ref:C,raw:b,refs:y,wrapped:g||C.type==="local"&&C.key==="label"}}return h.stringify(_.single.value)}return{formula:_,raw:b,refs:y}}toString(){return this.source}},h.Template.prototype[l.symbols.template]=!0,h.Template.prototype.isImmutable=!0,h.encode=function(f){return f.replace(/\\(\{+)/g,(b,g)=>h.opens.slice(0,g.length)).replace(/\\(\}+)/g,(b,g)=>h.closes.slice(0,g.length))},h.decode=function(f){return f.replace(/\u0000/g,"{").replace(/\u0001/g,"}")},h.split=function(f){const b=[];let g="";for(let y=0;y<f.length;++y){const v=f[y];if(v==="{"){let _="";for(;y+1<f.length&&f[y+1]==="{";)_+="{",++y;b.push(g),g=_}else g+=v}return b.push(g),b},h.wrap=function(f,b){return b?b.length===1?`${b}${f}${b}`:`${b[0]}${f}${b[1]}`:f},h.stringify=function(f,b,g,y,v,_={}){const C=typeof f,S=y&&y.errors&&y.errors.wrap||{};let T=!1;if(u.isRef(f)&&f.render&&(T=f.in,f=f.resolve(b,g,y,v,{in:f.in,..._})),f===null)return"null";if(C==="string")return h.wrap(f,_.arrayItems&&S.string);if(C==="number"||C==="function"||C==="symbol")return f.toString();if(C!=="object")return JSON.stringify(f);if(f instanceof Date)return h.Template.date(f,y);if(f instanceof Map){const x=[];for(const[k,E]of f.entries())x.push(`${k.toString()} -> ${E.toString()}`);f=x}if(!Array.isArray(f))return f.toString();const w=[];for(const x of f)w.push(h.stringify(x,b,g,y,v,{arrayItems:!0,..._}));return h.wrap(w.join(", "),!T&&S.array)},h.constants={true:!0,false:!1,null:null,second:1e3,minute:6e4,hour:36e5,day:864e5},h.functions={if:(f,b,g)=>f?b:g,length:f=>typeof f=="string"?f.length:f&&typeof f=="object"?Array.isArray(f)?f.length:Object.keys(f).length:null,msg(f){const[b,g,y,v,_]=this,C=_.messages;if(!C)return"";const S=c.template(b,C[0],f,g,y)||c.template(b,C[1],f,g,y);return S?S.render(b,g,y,v,_):""},number:f=>typeof f=="number"?f:typeof f=="string"?parseFloat(f):typeof f=="boolean"?f?1:0:f instanceof Date?f.getTime():null}},4946:(r,n,o)=>{const a=o(375),p=o(1687),m=o(8068),d=o(8160),l=o(3292),c=o(6354),u=o(6133),h={};r.exports=m.extend({type:"alternatives",flags:{match:{default:"any"}},terms:{matches:{init:[],register:u.toSibling}},args:(f,...b)=>b.length===1&&Array.isArray(b[0])?f.try(...b[0]):f.try(...b),validate(f,b){const{schema:g,error:y,state:v,prefs:_}=b;if(g._flags.match){const S=[],T=[];for(let x=0;x<g.$_terms.matches.length;++x){const k=g.$_terms.matches[x],E=v.nest(k.schema,`match.${x}`);E.snapshot();const P=k.schema.$_validate(f,E,_);P.errors?(T.push(P.errors),E.restore()):(S.push(P.value),E.commit())}if(S.length===0)return{errors:y("alternatives.any",{details:T.map(x=>c.details(x,{override:!1}))})};if(g._flags.match==="one")return S.length===1?{value:S[0]}:{errors:y("alternatives.one")};if(S.length!==g.$_terms.matches.length)return{errors:y("alternatives.all",{details:T.map(x=>c.details(x,{override:!1}))})};const w=x=>x.$_terms.matches.some(k=>k.schema.type==="object"||k.schema.type==="alternatives"&&w(k.schema));return w(g)?{value:S.reduce((x,k)=>p(x,k,{mergeArrays:!1}))}:{value:S[S.length-1]}}const C=[];for(let S=0;S<g.$_terms.matches.length;++S){const T=g.$_terms.matches[S];if(T.schema){const k=v.nest(T.schema,`match.${S}`);k.snapshot();const E=T.schema.$_validate(f,k,_);if(!E.errors)return k.commit(),E;k.restore(),C.push({schema:T.schema,reports:E.errors});continue}const w=T.ref?T.ref.resolve(f,v,_):f,x=T.is?[T]:T.switch;for(let k=0;k<x.length;++k){const E=x[k],{is:P,then:O,otherwise:z}=E,I=`match.${S}${T.switch?"."+k:""}`;if(P.$_match(w,v.nest(P,`${I}.is`),_)){if(O)return O.$_validate(f,v.nest(O,`${I}.then`),_)}else if(z)return z.$_validate(f,v.nest(z,`${I}.otherwise`),_)}}return h.errors(C,b)},rules:{conditional:{method(f,b){a(!this._flags._endedSwitch,"Unreachable condition"),a(!this._flags.match,"Cannot combine match mode",this._flags.match,"with conditional rule"),a(b.break===void 0,"Cannot use break option with alternatives conditional");const g=this.clone(),y=l.when(g,f,b),v=y.is?[y]:y.switch;for(const _ of v)if(_.then&&_.otherwise){g.$_setFlag("_endedSwitch",!0,{clone:!1});break}return g.$_terms.matches.push(y),g.$_mutateRebuild()}},match:{method(f){if(a(["any","one","all"].includes(f),"Invalid alternatives match mode",f),f!=="any")for(const b of this.$_terms.matches)a(b.schema,"Cannot combine match mode",f,"with conditional rules");return this.$_setFlag("match",f)}},try:{method(...f){a(f.length,"Missing alternative schemas"),d.verifyFlat(f,"try"),a(!this._flags._endedSwitch,"Unreachable condition");const b=this.clone();for(const g of f)b.$_terms.matches.push({schema:b.$_compile(g)});return b.$_mutateRebuild()}}},overrides:{label(f){return this.$_parent("label",f).$_modify({each:(b,g)=>g.path[0]!=="is"&&typeof b._flags.label!="string"?b.label(f):void 0,ref:!1})}},rebuild(f){f.$_modify({each:b=>{d.isSchema(b)&&b.type==="array"&&f.$_setFlag("_arrayItems",!0,{clone:!1})}})},manifest:{build(f,b){if(b.matches)for(const g of b.matches){const{schema:y,ref:v,is:_,not:C,then:S,otherwise:T}=g;f=y?f.try(y):v?f.conditional(v,{is:_,then:S,not:C,otherwise:T,switch:g.switch}):f.conditional(_,{then:S,otherwise:T})}return f}},messages:{"alternatives.all":"{{#label}} does not match all of the required types","alternatives.any":"{{#label}} does not match any of the allowed types","alternatives.match":"{{#label}} does not match any of the allowed types","alternatives.one":"{{#label}} matches more than one allowed type","alternatives.types":"{{#label}} must be one of {{#types}}"}}),h.errors=function(f,{error:b,state:g}){if(!f.length)return{errors:b("alternatives.any")};if(f.length===1)return{errors:f[0].reports};const y=new Set,v=[];for(const{reports:_,schema:C}of f){if(_.length>1)return h.unmatched(f,b);const S=_[0];if(S instanceof c.Report==0)return h.unmatched(f,b);if(S.state.path.length!==g.path.length){v.push({type:C.type,report:S});continue}if(S.code==="any.only"){for(const x of S.local.valids)y.add(x);continue}const[T,w]=S.code.split(".");w!=="base"?v.push({type:C.type,report:S}):S.code==="object.base"?y.add(S.local.type):y.add(T)}return v.length?v.length===1?{errors:v[0].report}:h.unmatched(f,b):{errors:b("alternatives.types",{types:[...y]})}},h.unmatched=function(f,b){const g=[];for(const y of f)g.push(...y.reports);return{errors:b("alternatives.match",c.details(g,{override:!1}))}}},8068:(r,n,o)=>{const a=o(375),p=o(7629),m=o(8160),d=o(6914);r.exports=p.extend({type:"any",flags:{only:{default:!1}},terms:{alterations:{init:null},examples:{init:null},externals:{init:null},metas:{init:[]},notes:{init:[]},shared:{init:null},tags:{init:[]},whens:{init:null}},rules:{custom:{method(l,c){return a(typeof l=="function","Method must be a function"),a(c===void 0||c&&typeof c=="string","Description must be a non-empty string"),this.$_addRule({name:"custom",args:{method:l,description:c}})},validate(l,c,{method:u}){try{return u(l,c)}catch(h){return c.error("any.custom",{error:h})}},args:["method","description"],multi:!0},messages:{method(l){return this.prefs({messages:l})}},shared:{method(l){a(m.isSchema(l)&&l._flags.id,"Schema must be a schema with an id");const c=this.clone();return c.$_terms.shared=c.$_terms.shared||[],c.$_terms.shared.push(l),c.$_mutateRegister(l),c}},warning:{method(l,c){return a(l&&typeof l=="string","Invalid warning code"),this.$_addRule({name:"warning",args:{code:l,local:c},warn:!0})},validate:(l,c,{code:u,local:h})=>c.error(u,h),args:["code","local"],multi:!0}},modifiers:{keep(l,c=!0){l.keep=c},message(l,c){l.message=d.compile(c)},warn(l,c=!0){l.warn=c}},manifest:{build(l,c){for(const u in c){const h=c[u];if(["examples","externals","metas","notes","tags"].includes(u))for(const f of h)l=l[u.slice(0,-1)](f);else if(u!=="alterations")if(u!=="whens"){if(u==="shared")for(const f of h)l=l.shared(f)}else for(const f of h){const{ref:b,is:g,not:y,then:v,otherwise:_,concat:C}=f;l=C?l.concat(C):b?l.when(b,{is:g,not:y,then:v,otherwise:_,switch:f.switch,break:f.break}):l.when(g,{then:v,otherwise:_,break:f.break})}else{const f={};for(const{target:b,adjuster:g}of h)f[b]=g;l=l.alter(f)}}return l}},messages:{"any.custom":"{{#label}} failed custom validation because {{#error.message}}","any.default":"{{#label}} threw an error when running default method","any.failover":"{{#label}} threw an error when running failover method","any.invalid":"{{#label}} contains an invalid value","any.only":'{{#label}} must be {if(#valids.length == 1, "", "one of ")}{{#valids}}',"any.ref":"{{#label}} {{#arg}} references {{:#ref}} which {{#reason}}","any.required":"{{#label}} is required","any.unknown":"{{#label}} is not allowed"}})},546:(r,n,o)=>{const a=o(375),p=o(9474),m=o(9621),d=o(8068),l=o(8160),c=o(3292),u={};r.exports=d.extend({type:"array",flags:{single:{default:!1},sparse:{default:!1}},terms:{items:{init:[],manifest:"schema"},ordered:{init:[],manifest:"schema"},_exclusions:{init:[]},_inclusions:{init:[]},_requireds:{init:[]}},coerce:{from:"object",method(h,{schema:f,state:b,prefs:g}){if(!Array.isArray(h))return;const y=f.$_getRule("sort");return y?u.sort(f,h,y.args.options,b,g):void 0}},validate(h,{schema:f,error:b}){if(!Array.isArray(h)){if(f._flags.single){const g=[h];return g[l.symbols.arraySingle]=!0,{value:g}}return{errors:b("array.base")}}if(f.$_getRule("items")||f.$_terms.externals)return{value:h.slice()}},rules:{has:{method(h){h=this.$_compile(h,{appendPath:!0});const f=this.$_addRule({name:"has",args:{schema:h}});return f.$_mutateRegister(h),f},validate(h,{state:f,prefs:b,error:g},{schema:y}){const v=[h,...f.ancestors];for(let C=0;C<h.length;++C){const S=f.localize([...f.path,C],v,y);if(y.$_match(h[C],S,b))return h}const _=y._flags.label;return _?g("array.hasKnown",{patternLabel:_}):g("array.hasUnknown",null)},multi:!0},items:{method(...h){l.verifyFlat(h,"items");const f=this.$_addRule("items");for(let b=0;b<h.length;++b){const g=l.tryWithPath(()=>this.$_compile(h[b]),b,{append:!0});f.$_terms.items.push(g)}return f.$_mutateRebuild()},validate(h,{schema:f,error:b,state:g,prefs:y,errorsArray:v}){const _=f.$_terms._requireds.slice(),C=f.$_terms.ordered.slice(),S=[...f.$_terms._inclusions,..._],T=!h[l.symbols.arraySingle];delete h[l.symbols.arraySingle];const w=v();let x=h.length;for(let k=0;k<x;++k){const E=h[k];let P=!1,O=!1;const z=T?k:new Number(k),I=[...g.path,z];if(!f._flags.sparse&&E===void 0){if(w.push(b("array.sparse",{key:z,path:I,pos:k,value:void 0},g.localize(I))),y.abortEarly)return w;C.shift();continue}const L=[h,...g.ancestors];for(const X of f.$_terms._exclusions)if(X.$_match(E,g.localize(I,L,X),y,{presence:"ignore"})){if(w.push(b("array.excludes",{pos:k,value:E},g.localize(I))),y.abortEarly)return w;P=!0,C.shift();break}if(P)continue;if(f.$_terms.ordered.length){if(C.length){const X=C.shift(),Y=X.$_validate(E,g.localize(I,L,X),y);if(Y.errors){if(w.push(...Y.errors),y.abortEarly)return w}else if(X._flags.result==="strip")u.fastSplice(h,k),--k,--x;else{if(!f._flags.sparse&&Y.value===void 0){if(w.push(b("array.sparse",{key:z,path:I,pos:k,value:void 0},g.localize(I))),y.abortEarly)return w;continue}h[k]=Y.value}continue}if(!f.$_terms.items.length){if(w.push(b("array.orderedLength",{pos:k,limit:f.$_terms.ordered.length})),y.abortEarly)return w;break}}const F=[];let Z=_.length;for(let X=0;X<Z;++X){const Y=g.localize(I,L,_[X]);Y.snapshot();const se=_[X].$_validate(E,Y,y);if(F[X]=se,!se.errors){if(Y.commit(),h[k]=se.value,O=!0,u.fastSplice(_,X),--X,--Z,!f._flags.sparse&&se.value===void 0&&(w.push(b("array.sparse",{key:z,path:I,pos:k,value:void 0},g.localize(I))),y.abortEarly))return w;break}Y.restore()}if(O)continue;const Q=y.stripUnknown&&!!y.stripUnknown.arrays||!1;Z=S.length;for(const X of S){let Y;const se=_.indexOf(X);if(se!==-1)Y=F[se];else{const re=g.localize(I,L,X);if(re.snapshot(),Y=X.$_validate(E,re,y),!Y.errors){re.commit(),X._flags.result==="strip"?(u.fastSplice(h,k),--k,--x):f._flags.sparse||Y.value!==void 0?h[k]=Y.value:(w.push(b("array.sparse",{key:z,path:I,pos:k,value:void 0},g.localize(I))),P=!0),O=!0;break}re.restore()}if(Z===1){if(Q){u.fastSplice(h,k),--k,--x,O=!0;break}if(w.push(...Y.errors),y.abortEarly)return w;P=!0;break}}if(!P&&(f.$_terms._inclusions.length||f.$_terms._requireds.length)&&!O){if(Q){u.fastSplice(h,k),--k,--x;continue}if(w.push(b("array.includes",{pos:k,value:E},g.localize(I))),y.abortEarly)return w}}return _.length&&u.fillMissedErrors(f,w,_,h,g,y),C.length&&(u.fillOrderedErrors(f,w,C,h,g,y),w.length||u.fillDefault(C,h,g,y)),w.length?w:h},priority:!0,manifest:!1},length:{method(h){return this.$_addRule({name:"length",args:{limit:h},operator:"="})},validate:(h,f,{limit:b},{name:g,operator:y,args:v})=>l.compare(h.length,b,y)?h:f.error("array."+g,{limit:v.limit,value:h}),args:[{name:"limit",ref:!0,assert:l.limit,message:"must be a positive integer"}]},max:{method(h){return this.$_addRule({name:"max",method:"length",args:{limit:h},operator:"<="})}},min:{method(h){return this.$_addRule({name:"min",method:"length",args:{limit:h},operator:">="})}},ordered:{method(...h){l.verifyFlat(h,"ordered");const f=this.$_addRule("items");for(let b=0;b<h.length;++b){const g=l.tryWithPath(()=>this.$_compile(h[b]),b,{append:!0});u.validateSingle(g,f),f.$_mutateRegister(g),f.$_terms.ordered.push(g)}return f.$_mutateRebuild()}},single:{method(h){const f=h===void 0||!!h;return a(!f||!this._flags._arrayItems,"Cannot specify single rule when array has array items"),this.$_setFlag("single",f)}},sort:{method(h={}){l.assertOptions(h,["by","order"]);const f={order:h.order||"ascending"};return h.by&&(f.by=c.ref(h.by,{ancestor:0}),a(!f.by.ancestor,"Cannot sort by ancestor")),this.$_addRule({name:"sort",args:{options:f}})},validate(h,{error:f,state:b,prefs:g,schema:y},{options:v}){const{value:_,errors:C}=u.sort(y,h,v,b,g);if(C)return C;for(let S=0;S<h.length;++S)if(h[S]!==_[S])return f("array.sort",{order:v.order,by:v.by?v.by.key:"value"});return h},convert:!0},sparse:{method(h){const f=h===void 0||!!h;return this._flags.sparse===f?this:(f?this.clone():this.$_addRule("items")).$_setFlag("sparse",f,{clone:!1})}},unique:{method(h,f={}){a(!h||typeof h=="function"||typeof h=="string","comparator must be a function or a string"),l.assertOptions(f,["ignoreUndefined","separator"]);const b={name:"unique",args:{options:f,comparator:h}};if(h)if(typeof h=="string"){const g=l.default(f.separator,".");b.path=g?h.split(g):[h]}else b.comparator=h;return this.$_addRule(b)},validate(h,{state:f,error:b,schema:g},{comparator:y,options:v},{comparator:_,path:C}){const S={string:Object.create(null),number:Object.create(null),undefined:Object.create(null),boolean:Object.create(null),bigint:Object.create(null),object:new Map,function:new Map,custom:new Map},T=_||p,w=v.ignoreUndefined;for(let x=0;x<h.length;++x){const k=C?m(h[x],C):h[x],E=_?S.custom:S[typeof k];if(a(E,"Failed to find unique map container for type",typeof k),E instanceof Map){const P=E.entries();let O;for(;!(O=P.next()).done;)if(T(O.value[0],k)){const z=f.localize([...f.path,x],[h,...f.ancestors]),I={pos:x,value:h[x],dupePos:O.value[1],dupeValue:h[O.value[1]]};return C&&(I.path=y),b("array.unique",I,z)}E.set(k,x)}else{if((!w||k!==void 0)&&E[k]!==void 0){const P={pos:x,value:h[x],dupePos:E[k],dupeValue:h[E[k]]};return C&&(P.path=y),b("array.unique",P,f.localize([...f.path,x],[h,...f.ancestors]))}E[k]=x}}return h},args:["comparator","options"],multi:!0}},cast:{set:{from:Array.isArray,to:(h,f)=>new Set(h)}},rebuild(h){h.$_terms._inclusions=[],h.$_terms._exclusions=[],h.$_terms._requireds=[];for(const f of h.$_terms.items)u.validateSingle(f,h),f._flags.presence==="required"?h.$_terms._requireds.push(f):f._flags.presence==="forbidden"?h.$_terms._exclusions.push(f):h.$_terms._inclusions.push(f);for(const f of h.$_terms.ordered)u.validateSingle(f,h)},manifest:{build:(h,f)=>(f.items&&(h=h.items(...f.items)),f.ordered&&(h=h.ordered(...f.ordered)),h)},messages:{"array.base":"{{#label}} must be an array","array.excludes":"{{#label}} contains an excluded value","array.hasKnown":"{{#label}} does not contain at least one required match for type {:#patternLabel}","array.hasUnknown":"{{#label}} does not contain at least one required match","array.includes":"{{#label}} does not match any of the allowed types","array.includesRequiredBoth":"{{#label}} does not contain {{#knownMisses}} and {{#unknownMisses}} other required value(s)","array.includesRequiredKnowns":"{{#label}} does not contain {{#knownMisses}}","array.includesRequiredUnknowns":"{{#label}} does not contain {{#unknownMisses}} required value(s)","array.length":"{{#label}} must contain {{#limit}} items","array.max":"{{#label}} must contain less than or equal to {{#limit}} items","array.min":"{{#label}} must contain at least {{#limit}} items","array.orderedLength":"{{#label}} must contain at most {{#limit}} items","array.sort":"{{#label}} must be sorted in {#order} order by {{#by}}","array.sort.mismatching":"{{#label}} cannot be sorted due to mismatching types","array.sort.unsupported":"{{#label}} cannot be sorted due to unsupported type {#type}","array.sparse":"{{#label}} must not be a sparse array item","array.unique":"{{#label}} contains a duplicate value"}}),u.fillMissedErrors=function(h,f,b,g,y,v){const _=[];let C=0;for(const S of b){const T=S._flags.label;T?_.push(T):++C}_.length?C?f.push(h.$_createError("array.includesRequiredBoth",g,{knownMisses:_,unknownMisses:C},y,v)):f.push(h.$_createError("array.includesRequiredKnowns",g,{knownMisses:_},y,v)):f.push(h.$_createError("array.includesRequiredUnknowns",g,{unknownMisses:C},y,v))},u.fillOrderedErrors=function(h,f,b,g,y,v){const _=[];for(const C of b)C._flags.presence==="required"&&_.push(C);_.length&&u.fillMissedErrors(h,f,_,g,y,v)},u.fillDefault=function(h,f,b,g){const y=[];let v=!0;for(let _=h.length-1;_>=0;--_){const C=h[_],S=[f,...b.ancestors],T=C.$_validate(void 0,b.localize(b.path,S,C),g).value;if(v){if(T===void 0)continue;v=!1}y.unshift(T)}y.length&&f.push(...y)},u.fastSplice=function(h,f){let b=f;for(;b<h.length;)h[b++]=h[b];--h.length},u.validateSingle=function(h,f){(h.type==="array"||h._flags._arrayItems)&&(a(!f._flags.single,"Cannot specify array item with single rule enabled"),f.$_setFlag("_arrayItems",!0,{clone:!1}))},u.sort=function(h,f,b,g,y){const v=b.order==="ascending"?1:-1,_=-1*v,C=v,S=(T,w)=>{let x=u.compare(T,w,_,C);if(x!==null||(b.by&&(T=b.by.resolve(T,g,y),w=b.by.resolve(w,g,y)),x=u.compare(T,w,_,C),x!==null))return x;const k=typeof T;if(k!==typeof w)throw h.$_createError("array.sort.mismatching",f,null,g,y);if(k!=="number"&&k!=="string")throw h.$_createError("array.sort.unsupported",f,{type:k},g,y);return k==="number"?(T-w)*v:T<w?_:C};try{return{value:f.slice().sort(S)}}catch(T){return{errors:T}}},u.compare=function(h,f,b,g){return h===f?0:h===void 0?1:f===void 0?-1:h===null?g:f===null?b:null}},4937:(r,n,o)=>{const a=o(375),p=o(8068),m=o(8160),d=o(2036),l={isBool:function(c){return typeof c=="boolean"}};r.exports=p.extend({type:"boolean",flags:{sensitive:{default:!1}},terms:{falsy:{init:null,manifest:"values"},truthy:{init:null,manifest:"values"}},coerce(c,{schema:u}){if(typeof c!="boolean"){if(typeof c=="string"){const h=u._flags.sensitive?c:c.toLowerCase();c=h==="true"||h!=="false"&&c}return typeof c!="boolean"&&(c=u.$_terms.truthy&&u.$_terms.truthy.has(c,null,null,!u._flags.sensitive)||(!u.$_terms.falsy||!u.$_terms.falsy.has(c,null,null,!u._flags.sensitive))&&c),{value:c}}},validate(c,{error:u}){if(typeof c!="boolean")return{value:c,errors:u("boolean.base")}},rules:{truthy:{method(...c){m.verifyFlat(c,"truthy");const u=this.clone();u.$_terms.truthy=u.$_terms.truthy||new d;for(let h=0;h<c.length;++h){const f=c[h];a(f!==void 0,"Cannot call truthy with undefined"),u.$_terms.truthy.add(f)}return u}},falsy:{method(...c){m.verifyFlat(c,"falsy");const u=this.clone();u.$_terms.falsy=u.$_terms.falsy||new d;for(let h=0;h<c.length;++h){const f=c[h];a(f!==void 0,"Cannot call falsy with undefined"),u.$_terms.falsy.add(f)}return u}},sensitive:{method(c=!0){return this.$_setFlag("sensitive",c)}}},cast:{number:{from:l.isBool,to:(c,u)=>c?1:0},string:{from:l.isBool,to:(c,u)=>c?"true":"false"}},manifest:{build:(c,u)=>(u.truthy&&(c=c.truthy(...u.truthy)),u.falsy&&(c=c.falsy(...u.falsy)),c)},messages:{"boolean.base":"{{#label}} must be a boolean"}})},7500:(r,n,o)=>{const a=o(375),p=o(8068),m=o(8160),d=o(3328),l={isDate:function(c){return c instanceof Date}};r.exports=p.extend({type:"date",coerce:{from:["number","string"],method:(c,{schema:u})=>({value:l.parse(c,u._flags.format)||c})},validate(c,{schema:u,error:h,prefs:f}){if(c instanceof Date&&!isNaN(c.getTime()))return;const b=u._flags.format;return f.convert&&b&&typeof c=="string"?{value:c,errors:h("date.format",{format:b})}:{value:c,errors:h("date.base")}},rules:{compare:{method:!1,validate(c,u,{date:h},{name:f,operator:b,args:g}){const y=h==="now"?Date.now():h.getTime();return m.compare(c.getTime(),y,b)?c:u.error("date."+f,{limit:g.date,value:c})},args:[{name:"date",ref:!0,normalize:c=>c==="now"?c:l.parse(c),assert:c=>c!==null,message:"must have a valid date format"}]},format:{method(c){return a(["iso","javascript","unix"].includes(c),"Unknown date format",c),this.$_setFlag("format",c)}},greater:{method(c){return this.$_addRule({name:"greater",method:"compare",args:{date:c},operator:">"})}},iso:{method(){return this.format("iso")}},less:{method(c){return this.$_addRule({name:"less",method:"compare",args:{date:c},operator:"<"})}},max:{method(c){return this.$_addRule({name:"max",method:"compare",args:{date:c},operator:"<="})}},min:{method(c){return this.$_addRule({name:"min",method:"compare",args:{date:c},operator:">="})}},timestamp:{method(c="javascript"){return a(["javascript","unix"].includes(c),'"type" must be one of "javascript, unix"'),this.format(c)}}},cast:{number:{from:l.isDate,to:(c,u)=>c.getTime()},string:{from:l.isDate,to:(c,{prefs:u})=>d.date(c,u)}},messages:{"date.base":"{{#label}} must be a valid date","date.format":'{{#label}} must be in {msg("date.format." + #format) || #format} format',"date.greater":"{{#label}} must be greater than {{:#limit}}","date.less":"{{#label}} must be less than {{:#limit}}","date.max":"{{#label}} must be less than or equal to {{:#limit}}","date.min":"{{#label}} must be greater than or equal to {{:#limit}}","date.format.iso":"ISO 8601 date","date.format.javascript":"timestamp or number of milliseconds","date.format.unix":"timestamp or number of seconds"}}),l.parse=function(c,u){if(c instanceof Date)return c;if(typeof c!="string"&&(isNaN(c)||!isFinite(c))||/^\s*$/.test(c))return null;if(u==="iso")return m.isIsoDate(c)?l.date(c.toString()):null;const h=c;if(typeof c=="string"&&/^[+-]?\d+(\.\d+)?$/.test(c)&&(c=parseFloat(c)),u){if(u==="javascript")return l.date(1*c);if(u==="unix")return l.date(1e3*c);if(typeof h=="string")return null}return l.date(c)},l.date=function(c){const u=new Date(c);return isNaN(u.getTime())?null:u}},390:(r,n,o)=>{const a=o(375),p=o(7824);r.exports=p.extend({type:"function",properties:{typeof:"function"},rules:{arity:{method(m){return a(Number.isSafeInteger(m)&&m>=0,"n must be a positive integer"),this.$_addRule({name:"arity",args:{n:m}})},validate:(m,d,{n:l})=>m.length===l?m:d.error("function.arity",{n:l})},class:{method(){return this.$_addRule("class")},validate:(m,d)=>/^\s*class\s/.test(m.toString())?m:d.error("function.class",{value:m})},minArity:{method(m){return a(Number.isSafeInteger(m)&&m>0,"n must be a strict positive integer"),this.$_addRule({name:"minArity",args:{n:m}})},validate:(m,d,{n:l})=>m.length>=l?m:d.error("function.minArity",{n:l})},maxArity:{method(m){return a(Number.isSafeInteger(m)&&m>=0,"n must be a positive integer"),this.$_addRule({name:"maxArity",args:{n:m}})},validate:(m,d,{n:l})=>m.length<=l?m:d.error("function.maxArity",{n:l})}},messages:{"function.arity":"{{#label}} must have an arity of {{#n}}","function.class":"{{#label}} must be a class","function.maxArity":"{{#label}} must have an arity lesser or equal to {{#n}}","function.minArity":"{{#label}} must have an arity greater or equal to {{#n}}"}})},7824:(r,n,o)=>{const a=o(978),p=o(375),m=o(8571),d=o(3652),l=o(8068),c=o(8160),u=o(3292),h=o(6354),f=o(6133),b=o(3328),g={renameDefaults:{alias:!1,multiple:!1,override:!1}};r.exports=l.extend({type:"_keys",properties:{typeof:"object"},flags:{unknown:{default:void 0}},terms:{dependencies:{init:null},keys:{init:null,manifest:{mapped:{from:"schema",to:"key"}}},patterns:{init:null},renames:{init:null}},args:(y,v)=>y.keys(v),validate(y,{schema:v,error:_,state:C,prefs:S}){if(!y||typeof y!==v.$_property("typeof")||Array.isArray(y))return{value:y,errors:_("object.base",{type:v.$_property("typeof")})};if(!(v.$_terms.renames||v.$_terms.dependencies||v.$_terms.keys||v.$_terms.patterns||v.$_terms.externals))return;y=g.clone(y,S);const T=[];if(v.$_terms.renames&&!g.rename(v,y,C,S,T))return{value:y,errors:T};if(!v.$_terms.keys&&!v.$_terms.patterns&&!v.$_terms.dependencies)return{value:y,errors:T};const w=new Set(Object.keys(y));if(v.$_terms.keys){const x=[y,...C.ancestors];for(const k of v.$_terms.keys){const E=k.key,P=y[E];w.delete(E);const O=C.localize([...C.path,E],x,k),z=k.schema.$_validate(P,O,S);if(z.errors){if(S.abortEarly)return{value:y,errors:z.errors};z.value!==void 0&&(y[E]=z.value),T.push(...z.errors)}else k.schema._flags.result==="strip"||z.value===void 0&&P!==void 0?delete y[E]:z.value!==void 0&&(y[E]=z.value)}}if(w.size||v._flags._hasPatternMatch){const x=g.unknown(v,y,w,T,C,S);if(x)return x}if(v.$_terms.dependencies)for(const x of v.$_terms.dependencies){if(x.key!==null&&g.isPresent(x.options)(x.key.resolve(y,C,S,null,{shadow:!1}))===!1)continue;const k=g.dependencies[x.rel](v,x,y,C,S);if(k){const E=v.$_createError(k.code,y,k.context,C,S);if(S.abortEarly)return{value:y,errors:E};T.push(E)}}return{value:y,errors:T}},rules:{and:{method(...y){return c.verifyFlat(y,"and"),g.dependency(this,"and",null,y)}},append:{method(y){return y==null||Object.keys(y).length===0?this:this.keys(y)}},assert:{method(y,v,_){b.isTemplate(y)||(y=u.ref(y)),p(_===void 0||typeof _=="string","Message must be a string"),v=this.$_compile(v,{appendPath:!0});const C=this.$_addRule({name:"assert",args:{subject:y,schema:v,message:_}});return C.$_mutateRegister(y),C.$_mutateRegister(v),C},validate(y,{error:v,prefs:_,state:C},{subject:S,schema:T,message:w}){const x=S.resolve(y,C,_),k=f.isRef(S)?S.absolute(C):[];return T.$_match(x,C.localize(k,[y,...C.ancestors],T),_)?y:v("object.assert",{subject:S,message:w})},args:["subject","schema","message"],multi:!0},instance:{method(y,v){return p(typeof y=="function","constructor must be a function"),v=v||y.name,this.$_addRule({name:"instance",args:{constructor:y,name:v}})},validate:(y,v,{constructor:_,name:C})=>y instanceof _?y:v.error("object.instance",{type:C,value:y}),args:["constructor","name"]},keys:{method(y){p(y===void 0||typeof y=="object","Object schema must be a valid object"),p(!c.isSchema(y),"Object schema cannot be a joi schema");const v=this.clone();if(y)if(Object.keys(y).length){v.$_terms.keys=v.$_terms.keys?v.$_terms.keys.filter(_=>!y.hasOwnProperty(_.key)):new g.Keys;for(const _ in y)c.tryWithPath(()=>v.$_terms.keys.push({key:_,schema:this.$_compile(y[_])}),_)}else v.$_terms.keys=new g.Keys;else v.$_terms.keys=null;return v.$_mutateRebuild()}},length:{method(y){return this.$_addRule({name:"length",args:{limit:y},operator:"="})},validate:(y,v,{limit:_},{name:C,operator:S,args:T})=>c.compare(Object.keys(y).length,_,S)?y:v.error("object."+C,{limit:T.limit,value:y}),args:[{name:"limit",ref:!0,assert:c.limit,message:"must be a positive integer"}]},max:{method(y){return this.$_addRule({name:"max",method:"length",args:{limit:y},operator:"<="})}},min:{method(y){return this.$_addRule({name:"min",method:"length",args:{limit:y},operator:">="})}},nand:{method(...y){return c.verifyFlat(y,"nand"),g.dependency(this,"nand",null,y)}},or:{method(...y){return c.verifyFlat(y,"or"),g.dependency(this,"or",null,y)}},oxor:{method(...y){return g.dependency(this,"oxor",null,y)}},pattern:{method(y,v,_={}){const C=y instanceof RegExp;C||(y=this.$_compile(y,{appendPath:!0})),p(v!==void 0,"Invalid rule"),c.assertOptions(_,["fallthrough","matches"]),C&&p(!y.flags.includes("g")&&!y.flags.includes("y"),"pattern should not use global or sticky mode"),v=this.$_compile(v,{appendPath:!0});const S=this.clone();S.$_terms.patterns=S.$_terms.patterns||[];const T={[C?"regex":"schema"]:y,rule:v};return _.matches&&(T.matches=this.$_compile(_.matches),T.matches.type!=="array"&&(T.matches=T.matches.$_root.array().items(T.matches)),S.$_mutateRegister(T.matches),S.$_setFlag("_hasPatternMatch",!0,{clone:!1})),_.fallthrough&&(T.fallthrough=!0),S.$_terms.patterns.push(T),S.$_mutateRegister(v),S}},ref:{method(){return this.$_addRule("ref")},validate:(y,v)=>f.isRef(y)?y:v.error("object.refType",{value:y})},regex:{method(){return this.$_addRule("regex")},validate:(y,v)=>y instanceof RegExp?y:v.error("object.regex",{value:y})},rename:{method(y,v,_={}){p(typeof y=="string"||y instanceof RegExp,"Rename missing the from argument"),p(typeof v=="string"||v instanceof b,"Invalid rename to argument"),p(v!==y,"Cannot rename key to same name:",y),c.assertOptions(_,["alias","ignoreUndefined","override","multiple"]);const C=this.clone();C.$_terms.renames=C.$_terms.renames||[];for(const S of C.$_terms.renames)p(S.from!==y,"Cannot rename the same key multiple times");return v instanceof b&&C.$_mutateRegister(v),C.$_terms.renames.push({from:y,to:v,options:a(g.renameDefaults,_)}),C}},schema:{method(y="any"){return this.$_addRule({name:"schema",args:{type:y}})},validate:(y,v,{type:_})=>!c.isSchema(y)||_!=="any"&&y.type!==_?v.error("object.schema",{type:_}):y},unknown:{method(y){return this.$_setFlag("unknown",y!==!1)}},with:{method(y,v,_={}){return g.dependency(this,"with",y,v,_)}},without:{method(y,v,_={}){return g.dependency(this,"without",y,v,_)}},xor:{method(...y){return c.verifyFlat(y,"xor"),g.dependency(this,"xor",null,y)}}},overrides:{default(y,v){return y===void 0&&(y=c.symbols.deepDefault),this.$_parent("default",y,v)}},rebuild(y){if(y.$_terms.keys){const v=new d.Sorter;for(const _ of y.$_terms.keys)c.tryWithPath(()=>v.add(_,{after:_.schema.$_rootReferences(),group:_.key}),_.key);y.$_terms.keys=new g.Keys(...v.nodes)}},manifest:{build(y,v){if(v.keys&&(y=y.keys(v.keys)),v.dependencies)for(const{rel:_,key:C=null,peers:S,options:T}of v.dependencies)y=g.dependency(y,_,C,S,T);if(v.patterns)for(const{regex:_,schema:C,rule:S,fallthrough:T,matches:w}of v.patterns)y=y.pattern(_||C,S,{fallthrough:T,matches:w});if(v.renames)for(const{from:_,to:C,options:S}of v.renames)y=y.rename(_,C,S);return y}},messages:{"object.and":"{{#label}} contains {{#presentWithLabels}} without its required peers {{#missingWithLabels}}","object.assert":'{{#label}} is invalid because {if(#subject.key, `"` + #subject.key + `" failed to ` + (#message || "pass the assertion test"), #message || "the assertion failed")}',"object.base":"{{#label}} must be of type {{#type}}","object.instance":"{{#label}} must be an instance of {{:#type}}","object.length":'{{#label}} must have {{#limit}} key{if(#limit == 1, "", "s")}',"object.max":'{{#label}} must have less than or equal to {{#limit}} key{if(#limit == 1, "", "s")}',"object.min":'{{#label}} must have at least {{#limit}} key{if(#limit == 1, "", "s")}',"object.missing":"{{#label}} must contain at least one of {{#peersWithLabels}}","object.nand":"{{:#mainWithLabel}} must not exist simultaneously with {{#peersWithLabels}}","object.oxor":"{{#label}} contains a conflict between optional exclusive peers {{#peersWithLabels}}","object.pattern.match":"{{#label}} keys failed to match pattern requirements","object.refType":"{{#label}} must be a Joi reference","object.regex":"{{#label}} must be a RegExp object","object.rename.multiple":"{{#label}} cannot rename {{:#from}} because multiple renames are disabled and another key was already renamed to {{:#to}}","object.rename.override":"{{#label}} cannot rename {{:#from}} because override is disabled and target {{:#to}} exists","object.schema":"{{#label}} must be a Joi schema of {{#type}} type","object.unknown":"{{#label}} is not allowed","object.with":"{{:#mainWithLabel}} missing required peer {{:#peerWithLabel}}","object.without":"{{:#mainWithLabel}} conflict with forbidden peer {{:#peerWithLabel}}","object.xor":"{{#label}} contains a conflict between exclusive peers {{#peersWithLabels}}"}}),g.clone=function(y,v){if(typeof y=="object"){if(v.nonEnumerables)return m(y,{shallow:!0});const C=Object.create(Object.getPrototypeOf(y));return Object.assign(C,y),C}const _=function(...C){return y.apply(this,C)};return _.prototype=m(y.prototype),Object.defineProperty(_,"name",{value:y.name,writable:!1}),Object.defineProperty(_,"length",{value:y.length,writable:!1}),Object.assign(_,y),_},g.dependency=function(y,v,_,C,S){p(_===null||typeof _=="string",v,"key must be a strings"),S||(S=C.length>1&&typeof C[C.length-1]=="object"?C.pop():{}),c.assertOptions(S,["separator","isPresent"]),C=[].concat(C);const T=c.default(S.separator,"."),w=[];for(const k of C)p(typeof k=="string",v,"peers must be strings"),w.push(u.ref(k,{separator:T,ancestor:0,prefix:!1}));_!==null&&(_=u.ref(_,{separator:T,ancestor:0,prefix:!1}));const x=y.clone();return x.$_terms.dependencies=x.$_terms.dependencies||[],x.$_terms.dependencies.push(new g.Dependency(v,_,w,C,S)),x},g.dependencies={and(y,v,_,C,S){const T=[],w=[],x=v.peers.length,k=g.isPresent(v.options);for(const E of v.peers)k(E.resolve(_,C,S,null,{shadow:!1}))===!1?T.push(E.key):w.push(E.key);if(T.length!==x&&w.length!==x)return{code:"object.and",context:{present:w,presentWithLabels:g.keysToLabels(y,w),missing:T,missingWithLabels:g.keysToLabels(y,T)}}},nand(y,v,_,C,S){const T=[],w=g.isPresent(v.options);for(const E of v.peers)w(E.resolve(_,C,S,null,{shadow:!1}))&&T.push(E.key);if(T.length!==v.peers.length)return;const x=v.paths[0],k=v.paths.slice(1);return{code:"object.nand",context:{main:x,mainWithLabel:g.keysToLabels(y,x),peers:k,peersWithLabels:g.keysToLabels(y,k)}}},or(y,v,_,C,S){const T=g.isPresent(v.options);for(const w of v.peers)if(T(w.resolve(_,C,S,null,{shadow:!1})))return;return{code:"object.missing",context:{peers:v.paths,peersWithLabels:g.keysToLabels(y,v.paths)}}},oxor(y,v,_,C,S){const T=[],w=g.isPresent(v.options);for(const k of v.peers)w(k.resolve(_,C,S,null,{shadow:!1}))&&T.push(k.key);if(!T.length||T.length===1)return;const x={peers:v.paths,peersWithLabels:g.keysToLabels(y,v.paths)};return x.present=T,x.presentWithLabels=g.keysToLabels(y,T),{code:"object.oxor",context:x}},with(y,v,_,C,S){const T=g.isPresent(v.options);for(const w of v.peers)if(T(w.resolve(_,C,S,null,{shadow:!1}))===!1)return{code:"object.with",context:{main:v.key.key,mainWithLabel:g.keysToLabels(y,v.key.key),peer:w.key,peerWithLabel:g.keysToLabels(y,w.key)}}},without(y,v,_,C,S){const T=g.isPresent(v.options);for(const w of v.peers)if(T(w.resolve(_,C,S,null,{shadow:!1})))return{code:"object.without",context:{main:v.key.key,mainWithLabel:g.keysToLabels(y,v.key.key),peer:w.key,peerWithLabel:g.keysToLabels(y,w.key)}}},xor(y,v,_,C,S){const T=[],w=g.isPresent(v.options);for(const k of v.peers)w(k.resolve(_,C,S,null,{shadow:!1}))&&T.push(k.key);if(T.length===1)return;const x={peers:v.paths,peersWithLabels:g.keysToLabels(y,v.paths)};return T.length===0?{code:"object.missing",context:x}:(x.present=T,x.presentWithLabels=g.keysToLabels(y,T),{code:"object.xor",context:x})}},g.keysToLabels=function(y,v){return Array.isArray(v)?v.map(_=>y.$_mapLabels(_)):y.$_mapLabels(v)},g.isPresent=function(y){return typeof y.isPresent=="function"?y.isPresent:v=>v!==void 0},g.rename=function(y,v,_,C,S){const T={};for(const w of y.$_terms.renames){const x=[],k=typeof w.from!="string";if(k)for(const E in v){if(v[E]===void 0&&w.options.ignoreUndefined||E===w.to)continue;const P=w.from.exec(E);P&&x.push({from:E,to:w.to,match:P})}else!Object.prototype.hasOwnProperty.call(v,w.from)||v[w.from]===void 0&&w.options.ignoreUndefined||x.push(w);for(const E of x){const P=E.from;let O=E.to;if(O instanceof b&&(O=O.render(v,_,C,E.match)),P!==O){if(!w.options.multiple&&T[O]&&(S.push(y.$_createError("object.rename.multiple",v,{from:P,to:O,pattern:k},_,C)),C.abortEarly)||Object.prototype.hasOwnProperty.call(v,O)&&!w.options.override&&!T[O]&&(S.push(y.$_createError("object.rename.override",v,{from:P,to:O,pattern:k},_,C)),C.abortEarly))return!1;v[P]===void 0?delete v[O]:v[O]=v[P],T[O]=!0,w.options.alias||delete v[P]}}}return!0},g.unknown=function(y,v,_,C,S,T){if(y.$_terms.patterns){let w=!1;const x=y.$_terms.patterns.map(E=>{if(E.matches)return w=!0,[]}),k=[v,...S.ancestors];for(const E of _){const P=v[E],O=[...S.path,E];for(let z=0;z<y.$_terms.patterns.length;++z){const I=y.$_terms.patterns[z];if(I.regex){const Z=I.regex.test(E);if(S.mainstay.tracer.debug(S,"rule",`pattern.${z}`,Z?"pass":"error"),!Z)continue}else if(!I.schema.$_match(E,S.nest(I.schema,`pattern.${z}`),T))continue;_.delete(E);const L=S.localize(O,k,{schema:I.rule,key:E}),F=I.rule.$_validate(P,L,T);if(F.errors){if(T.abortEarly)return{value:v,errors:F.errors};C.push(...F.errors)}if(I.matches&&x[z].push(E),v[E]=F.value,!I.fallthrough)break}}if(w)for(let E=0;E<x.length;++E){const P=x[E];if(!P)continue;const O=y.$_terms.patterns[E].matches,z=S.localize(S.path,k,O),I=O.$_validate(P,z,T);if(I.errors){const L=h.details(I.errors,{override:!1});L.matches=P;const F=y.$_createError("object.pattern.match",v,L,S,T);if(T.abortEarly)return{value:v,errors:F};C.push(F)}}}if(_.size&&(y.$_terms.keys||y.$_terms.patterns)){if(T.stripUnknown&&y._flags.unknown===void 0||T.skipFunctions){const w=!(!T.stripUnknown||T.stripUnknown!==!0&&!T.stripUnknown.objects);for(const x of _)w?(delete v[x],_.delete(x)):typeof v[x]=="function"&&_.delete(x)}if(!c.default(y._flags.unknown,T.allowUnknown))for(const w of _){const x=S.localize([...S.path,w],[]),k=y.$_createError("object.unknown",v[w],{child:w},x,T,{flags:!1});if(T.abortEarly)return{value:v,errors:k};C.push(k)}}},g.Dependency=class{constructor(y,v,_,C,S){this.rel=y,this.key=v,this.peers=_,this.paths=C,this.options=S}describe(){const y={rel:this.rel,peers:this.paths};return this.key!==null&&(y.key=this.key.key),this.peers[0].separator!=="."&&(y.options={...y.options,separator:this.peers[0].separator}),this.options.isPresent&&(y.options={...y.options,isPresent:this.options.isPresent}),y}},g.Keys=class extends Array{concat(y){const v=this.slice(),_=new Map;for(let C=0;C<v.length;++C)_.set(v[C].key,C);for(const C of y){const S=C.key,T=_.get(S);T!==void 0?v[T]={key:S,schema:v[T].schema.concat(C.schema)}:v.push(C)}return v}}},8785:(r,n,o)=>{const a=o(375),p=o(8068),m=o(8160),d=o(3292),l=o(6354),c={};r.exports=p.extend({type:"link",properties:{schemaChain:!0},terms:{link:{init:null,manifest:"single",register:!1}},args:(u,h)=>u.ref(h),validate(u,{schema:h,state:f,prefs:b}){a(h.$_terms.link,"Uninitialized link schema");const g=c.generate(h,u,f,b),y=h.$_terms.link[0].ref;return g.$_validate(u,f.nest(g,`link:${y.display}:${g.type}`),b)},generate:(u,h,f,b)=>c.generate(u,h,f,b),rules:{ref:{method(u){a(!this.$_terms.link,"Cannot reinitialize schema"),u=d.ref(u),a(u.type==="value"||u.type==="local","Invalid reference type:",u.type),a(u.type==="local"||u.ancestor==="root"||u.ancestor>0,"Link cannot reference itself");const h=this.clone();return h.$_terms.link=[{ref:u}],h}},relative:{method(u=!0){return this.$_setFlag("relative",u)}}},overrides:{concat(u){a(this.$_terms.link,"Uninitialized link schema"),a(m.isSchema(u),"Invalid schema object"),a(u.type!=="link","Cannot merge type link with another link");const h=this.clone();return h.$_terms.whens||(h.$_terms.whens=[]),h.$_terms.whens.push({concat:u}),h.$_mutateRebuild()}},manifest:{build:(u,h)=>(a(h.link,"Invalid link description missing link"),u.ref(h.link))}}),c.generate=function(u,h,f,b){let g=f.mainstay.links.get(u);if(g)return g._generate(h,f,b).schema;const y=u.$_terms.link[0].ref,{perspective:v,path:_}=c.perspective(y,f);c.assert(v,"which is outside of schema boundaries",y,u,f,b);try{g=_.length?v.$_reach(_):v}catch{c.assert(!1,"to non-existing schema",y,u,f,b)}return c.assert(g.type!=="link","which is another link",y,u,f,b),u._flags.relative||f.mainstay.links.set(u,g),g._generate(h,f,b).schema},c.perspective=function(u,h){if(u.type==="local"){for(const{schema:f,key:b}of h.schemas){if((f._flags.id||b)===u.path[0])return{perspective:f,path:u.path.slice(1)};if(f.$_terms.shared){for(const g of f.$_terms.shared)if(g._flags.id===u.path[0])return{perspective:g,path:u.path.slice(1)}}}return{perspective:null,path:null}}return u.ancestor==="root"?{perspective:h.schemas[h.schemas.length-1].schema,path:u.path}:{perspective:h.schemas[u.ancestor]&&h.schemas[u.ancestor].schema,path:u.path}},c.assert=function(u,h,f,b,g,y){u||a(!1,`"${l.label(b._flags,g,y)}" contains link reference "${f.display}" ${h}`)}},3832:(r,n,o)=>{const a=o(375),p=o(8068),m=o(8160),d={numberRx:/^\s*[+-]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:e([+-]?\d+))?\s*$/i,precisionRx:/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/,exponentialPartRegex:/[eE][+-]?\d+$/,leadingSignAndZerosRegex:/^[+-]?(0*)?/,dotRegex:/\./,trailingZerosRegex:/0+$/,decimalPlaces(l){const c=l.toString(),u=c.indexOf("."),h=c.indexOf("e");return(u<0?0:(h<0?c.length:h)-u-1)+(h<0?0:Math.max(0,-parseInt(c.slice(h+1))))}};r.exports=p.extend({type:"number",flags:{unsafe:{default:!1}},coerce:{from:"string",method(l,{schema:c,error:u}){if(!l.match(d.numberRx))return;l=l.trim();const h={value:parseFloat(l)};if(h.value===0&&(h.value=0),!c._flags.unsafe)if(l.match(/e/i)){if(d.extractSignificantDigits(l)!==d.extractSignificantDigits(String(h.value)))return h.errors=u("number.unsafe"),h}else{const f=h.value.toString();if(f.match(/e/i))return h;if(f!==d.normalizeDecimal(l))return h.errors=u("number.unsafe"),h}return h}},validate(l,{schema:c,error:u,prefs:h}){if(l===1/0||l===-1/0)return{value:l,errors:u("number.infinity")};if(!m.isNumber(l))return{value:l,errors:u("number.base")};const f={value:l};if(h.convert){const b=c.$_getRule("precision");if(b){const g=Math.pow(10,b.args.limit);f.value=Math.round(f.value*g)/g}}return f.value===0&&(f.value=0),!c._flags.unsafe&&(l>Number.MAX_SAFE_INTEGER||l<Number.MIN_SAFE_INTEGER)&&(f.errors=u("number.unsafe")),f},rules:{compare:{method:!1,validate:(l,c,{limit:u},{name:h,operator:f,args:b})=>m.compare(l,u,f)?l:c.error("number."+h,{limit:b.limit,value:l}),args:[{name:"limit",ref:!0,assert:m.isNumber,message:"must be a number"}]},greater:{method(l){return this.$_addRule({name:"greater",method:"compare",args:{limit:l},operator:">"})}},integer:{method(){return this.$_addRule("integer")},validate:(l,c)=>Math.trunc(l)-l==0?l:c.error("number.integer")},less:{method(l){return this.$_addRule({name:"less",method:"compare",args:{limit:l},operator:"<"})}},max:{method(l){return this.$_addRule({name:"max",method:"compare",args:{limit:l},operator:"<="})}},min:{method(l){return this.$_addRule({name:"min",method:"compare",args:{limit:l},operator:">="})}},multiple:{method(l){const c=typeof l=="number"?d.decimalPlaces(l):null,u=Math.pow(10,c);return this.$_addRule({name:"multiple",args:{base:l,baseDecimalPlace:c,pfactor:u}})},validate:(l,c,{base:u,baseDecimalPlace:h,pfactor:f},b)=>d.decimalPlaces(l)>h?c.error("number.multiple",{multiple:b.args.base,value:l}):Math.round(f*l)%Math.round(f*u)==0?l:c.error("number.multiple",{multiple:b.args.base,value:l}),args:[{name:"base",ref:!0,assert:l=>typeof l=="number"&&isFinite(l)&&l>0,message:"must be a positive number"},"baseDecimalPlace","pfactor"],multi:!0},negative:{method(){return this.sign("negative")}},port:{method(){return this.$_addRule("port")},validate:(l,c)=>Number.isSafeInteger(l)&&l>=0&&l<=65535?l:c.error("number.port")},positive:{method(){return this.sign("positive")}},precision:{method(l){return a(Number.isSafeInteger(l),"limit must be an integer"),this.$_addRule({name:"precision",args:{limit:l}})},validate(l,c,{limit:u}){const h=l.toString().match(d.precisionRx);return Math.max((h[1]?h[1].length:0)-(h[2]?parseInt(h[2],10):0),0)<=u?l:c.error("number.precision",{limit:u,value:l})},convert:!0},sign:{method(l){return a(["negative","positive"].includes(l),"Invalid sign",l),this.$_addRule({name:"sign",args:{sign:l}})},validate:(l,c,{sign:u})=>u==="negative"&&l<0||u==="positive"&&l>0?l:c.error(`number.${u}`)},unsafe:{method(l=!0){return a(typeof l=="boolean","enabled must be a boolean"),this.$_setFlag("unsafe",l)}}},cast:{string:{from:l=>typeof l=="number",to:(l,c)=>l.toString()}},messages:{"number.base":"{{#label}} must be a number","number.greater":"{{#label}} must be greater than {{#limit}}","number.infinity":"{{#label}} cannot be infinity","number.integer":"{{#label}} must be an integer","number.less":"{{#label}} must be less than {{#limit}}","number.max":"{{#label}} must be less than or equal to {{#limit}}","number.min":"{{#label}} must be greater than or equal to {{#limit}}","number.multiple":"{{#label}} must be a multiple of {{#multiple}}","number.negative":"{{#label}} must be a negative number","number.port":"{{#label}} must be a valid port","number.positive":"{{#label}} must be a positive number","number.precision":"{{#label}} must have no more than {{#limit}} decimal places","number.unsafe":"{{#label}} must be a safe number"}}),d.extractSignificantDigits=function(l){return l.replace(d.exponentialPartRegex,"").replace(d.dotRegex,"").replace(d.trailingZerosRegex,"").replace(d.leadingSignAndZerosRegex,"")},d.normalizeDecimal=function(l){return(l=l.replace(/^\+/,"").replace(/\.0*$/,"").replace(/^(-?)\.([^\.]*)$/,"$10.$2").replace(/^(-?)0+([0-9])/,"$1$2")).includes(".")&&l.endsWith("0")&&(l=l.replace(/0+$/,"")),l==="-0"?"0":l}},8966:(r,n,o)=>{const a=o(7824);r.exports=a.extend({type:"object",cast:{map:{from:p=>p&&typeof p=="object",to:(p,m)=>new Map(Object.entries(p))}}})},7417:(r,n,o)=>{const a=o(375),p=o(5380),m=o(1745),d=o(9959),l=o(6064),c=o(9926),u=o(5752),h=o(8068),f=o(8160),b={tlds:c instanceof Set&&{tlds:{allow:c,deny:null}},base64Regex:{true:{true:/^(?:[\w\-]{2}[\w\-]{2})*(?:[\w\-]{2}==|[\w\-]{3}=)?$/,false:/^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/},false:{true:/^(?:[\w\-]{2}[\w\-]{2})*(?:[\w\-]{2}(==)?|[\w\-]{3}=?)?$/,false:/^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}(==)?|[A-Za-z0-9+\/]{3}=?)?$/}},dataUriRegex:/^data:[\w+.-]+\/[\w+.-]+;((charset=[\w-]+|base64),)?(.*)$/,hexRegex:{withPrefix:/^0x[0-9a-f]+$/i,withOptionalPrefix:/^(?:0x)?[0-9a-f]+$/i,withoutPrefix:/^[0-9a-f]+$/i},ipRegex:d.regex({cidr:"forbidden"}).regex,isoDurationRegex:/^P(?!$)(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?$/,guidBrackets:{"{":"}","[":"]","(":")","":""},guidVersions:{uuidv1:"1",uuidv2:"2",uuidv3:"3",uuidv4:"4",uuidv5:"5",uuidv6:"6",uuidv7:"7",uuidv8:"8"},guidSeparators:new Set([void 0,!0,!1,"-",":"]),normalizationForms:["NFC","NFD","NFKC","NFKD"]};r.exports=h.extend({type:"string",flags:{insensitive:{default:!1},truncate:{default:!1}},terms:{replacements:{init:null}},coerce:{from:"string",method(g,{schema:y,state:v,prefs:_}){const C=y.$_getRule("normalize");C&&(g=g.normalize(C.args.form));const S=y.$_getRule("case");S&&(g=S.args.direction==="upper"?g.toLocaleUpperCase():g.toLocaleLowerCase());const T=y.$_getRule("trim");if(T&&T.args.enabled&&(g=g.trim()),y.$_terms.replacements)for(const x of y.$_terms.replacements)g=g.replace(x.pattern,x.replacement);const w=y.$_getRule("hex");if(w&&w.args.options.byteAligned&&g.length%2!=0&&(g=`0${g}`),y.$_getRule("isoDate")){const x=b.isoDate(g);x&&(g=x)}if(y._flags.truncate){const x=y.$_getRule("max");if(x){let k=x.args.limit;if(f.isResolvable(k)&&(k=k.resolve(g,v,_),!f.limit(k)))return{value:g,errors:y.$_createError("any.ref",k,{ref:x.args.limit,arg:"limit",reason:"must be a positive integer"},v,_)};g=g.slice(0,k)}}return{value:g}}},validate(g,{schema:y,error:v}){if(typeof g!="string")return{value:g,errors:v("string.base")};if(g===""){const _=y.$_getRule("min");return _&&_.args.limit===0?void 0:{value:g,errors:v("string.empty")}}},rules:{alphanum:{method(){return this.$_addRule("alphanum")},validate:(g,y)=>/^[a-zA-Z0-9]+$/.test(g)?g:y.error("string.alphanum")},base64:{method(g={}){return f.assertOptions(g,["paddingRequired","urlSafe"]),g={urlSafe:!1,paddingRequired:!0,...g},a(typeof g.paddingRequired=="boolean","paddingRequired must be boolean"),a(typeof g.urlSafe=="boolean","urlSafe must be boolean"),this.$_addRule({name:"base64",args:{options:g}})},validate:(g,y,{options:v})=>b.base64Regex[v.paddingRequired][v.urlSafe].test(g)?g:y.error("string.base64")},case:{method(g){return a(["lower","upper"].includes(g),"Invalid case:",g),this.$_addRule({name:"case",args:{direction:g}})},validate:(g,y,{direction:v})=>v==="lower"&&g===g.toLocaleLowerCase()||v==="upper"&&g===g.toLocaleUpperCase()?g:y.error(`string.${v}case`),convert:!0},creditCard:{method(){return this.$_addRule("creditCard")},validate(g,y){let v=g.length,_=0,C=1;for(;v--;){const S=g.charAt(v)*C;_+=S-9*(S>9),C^=3}return _>0&&_%10==0?g:y.error("string.creditCard")}},dataUri:{method(g={}){return f.assertOptions(g,["paddingRequired"]),g={paddingRequired:!0,...g},a(typeof g.paddingRequired=="boolean","paddingRequired must be boolean"),this.$_addRule({name:"dataUri",args:{options:g}})},validate(g,y,{options:v}){const _=g.match(b.dataUriRegex);return _&&(!_[2]||_[2]!=="base64"||b.base64Regex[v.paddingRequired].false.test(_[3]))?g:y.error("string.dataUri")}},domain:{method(g){g&&f.assertOptions(g,["allowFullyQualified","allowUnicode","maxDomainSegments","minDomainSegments","tlds"]);const y=b.addressOptions(g);return this.$_addRule({name:"domain",args:{options:g},address:y})},validate:(g,y,v,{address:_})=>p.isValid(g,_)?g:y.error("string.domain")},email:{method(g={}){f.assertOptions(g,["allowFullyQualified","allowUnicode","ignoreLength","maxDomainSegments","minDomainSegments","multiple","separator","tlds"]),a(g.multiple===void 0||typeof g.multiple=="boolean","multiple option must be an boolean");const y=b.addressOptions(g),v=new RegExp(`\\s*[${g.separator?l(g.separator):","}]\\s*`);return this.$_addRule({name:"email",args:{options:g},regex:v,address:y})},validate(g,y,{options:v},{regex:_,address:C}){const S=v.multiple?g.split(_):[g],T=[];for(const w of S)m.isValid(w,C)||T.push(w);return T.length?y.error("string.email",{value:g,invalids:T}):g}},guid:{alias:"uuid",method(g={}){f.assertOptions(g,["version","separator"]);let y="";if(g.version){const C=[].concat(g.version);a(C.length>=1,"version must have at least 1 valid version specified");const S=new Set;for(let T=0;T<C.length;++T){const w=C[T];a(typeof w=="string","version at position "+T+" must be a string");const x=b.guidVersions[w.toLowerCase()];a(x,"version at position "+T+" must be one of "+Object.keys(b.guidVersions).join(", ")),a(!S.has(x),"version at position "+T+" must not be a duplicate"),y+=x,S.add(x)}}a(b.guidSeparators.has(g.separator),'separator must be one of true, false, "-", or ":"');const v=g.separator===void 0?"[:-]?":g.separator===!0?"[:-]":g.separator===!1?"[]?":`\\${g.separator}`,_=new RegExp(`^([\\[{\\(]?)[0-9A-F]{8}(${v})[0-9A-F]{4}\\2?[${y||"0-9A-F"}][0-9A-F]{3}\\2?[${y?"89AB":"0-9A-F"}][0-9A-F]{3}\\2?[0-9A-F]{12}([\\]}\\)]?)$`,"i");return this.$_addRule({name:"guid",args:{options:g},regex:_})},validate(g,y,v,{regex:_}){const C=_.exec(g);return C?b.guidBrackets[C[1]]!==C[C.length-1]?y.error("string.guid"):g:y.error("string.guid")}},hex:{method(g={}){return f.assertOptions(g,["byteAligned","prefix"]),g={byteAligned:!1,prefix:!1,...g},a(typeof g.byteAligned=="boolean","byteAligned must be boolean"),a(typeof g.prefix=="boolean"||g.prefix==="optional",'prefix must be boolean or "optional"'),this.$_addRule({name:"hex",args:{options:g}})},validate:(g,y,{options:v})=>(v.prefix==="optional"?b.hexRegex.withOptionalPrefix:v.prefix===!0?b.hexRegex.withPrefix:b.hexRegex.withoutPrefix).test(g)?v.byteAligned&&g.length%2!=0?y.error("string.hexAlign"):g:y.error("string.hex")},hostname:{method(){return this.$_addRule("hostname")},validate:(g,y)=>p.isValid(g,{minDomainSegments:1})||b.ipRegex.test(g)?g:y.error("string.hostname")},insensitive:{method(){return this.$_setFlag("insensitive",!0)}},ip:{method(g={}){f.assertOptions(g,["cidr","version"]);const{cidr:y,versions:v,regex:_}=d.regex(g),C=g.version?v:void 0;return this.$_addRule({name:"ip",args:{options:{cidr:y,version:C}},regex:_})},validate:(g,y,{options:v},{regex:_})=>_.test(g)?g:v.version?y.error("string.ipVersion",{value:g,cidr:v.cidr,version:v.version}):y.error("string.ip",{value:g,cidr:v.cidr})},isoDate:{method(){return this.$_addRule("isoDate")},validate:(g,{error:y})=>b.isoDate(g)?g:y("string.isoDate")},isoDuration:{method(){return this.$_addRule("isoDuration")},validate:(g,y)=>b.isoDurationRegex.test(g)?g:y.error("string.isoDuration")},length:{method(g,y){return b.length(this,"length",g,"=",y)},validate(g,y,{limit:v,encoding:_},{name:C,operator:S,args:T}){const w=!_&&g.length;return f.compare(w,v,S)?g:y.error("string."+C,{limit:T.limit,value:g,encoding:_})},args:[{name:"limit",ref:!0,assert:f.limit,message:"must be a positive integer"},"encoding"]},lowercase:{method(){return this.case("lower")}},max:{method(g,y){return b.length(this,"max",g,"<=",y)},args:["limit","encoding"]},min:{method(g,y){return b.length(this,"min",g,">=",y)},args:["limit","encoding"]},normalize:{method(g="NFC"){return a(b.normalizationForms.includes(g),"normalization form must be one of "+b.normalizationForms.join(", ")),this.$_addRule({name:"normalize",args:{form:g}})},validate:(g,{error:y},{form:v})=>g===g.normalize(v)?g:y("string.normalize",{value:g,form:v}),convert:!0},pattern:{alias:"regex",method(g,y={}){a(g instanceof RegExp,"regex must be a RegExp"),a(!g.flags.includes("g")&&!g.flags.includes("y"),"regex should not use global or sticky mode"),typeof y=="string"&&(y={name:y}),f.assertOptions(y,["invert","name"]);const v=["string.pattern",y.invert?".invert":"",y.name?".name":".base"].join("");return this.$_addRule({name:"pattern",args:{regex:g,options:y},errorCode:v})},validate:(g,y,{regex:v,options:_},{errorCode:C})=>v.test(g)^_.invert?g:y.error(C,{name:_.name,regex:v,value:g}),args:["regex","options"],multi:!0},replace:{method(g,y){typeof g=="string"&&(g=new RegExp(l(g),"g")),a(g instanceof RegExp,"pattern must be a RegExp"),a(typeof y=="string","replacement must be a String");const v=this.clone();return v.$_terms.replacements||(v.$_terms.replacements=[]),v.$_terms.replacements.push({pattern:g,replacement:y}),v}},token:{method(){return this.$_addRule("token")},validate:(g,y)=>/^\w+$/.test(g)?g:y.error("string.token")},trim:{method(g=!0){return a(typeof g=="boolean","enabled must be a boolean"),this.$_addRule({name:"trim",args:{enabled:g}})},validate:(g,y,{enabled:v})=>v&&g!==g.trim()?y.error("string.trim"):g,convert:!0},truncate:{method(g=!0){return a(typeof g=="boolean","enabled must be a boolean"),this.$_setFlag("truncate",g)}},uppercase:{method(){return this.case("upper")}},uri:{method(g={}){f.assertOptions(g,["allowRelative","allowQuerySquareBrackets","domain","relativeOnly","scheme","encodeUri"]),g.domain&&f.assertOptions(g.domain,["allowFullyQualified","allowUnicode","maxDomainSegments","minDomainSegments","tlds"]);const{regex:y,scheme:v}=u.regex(g),_=g.domain?b.addressOptions(g.domain):null;return this.$_addRule({name:"uri",args:{options:g},regex:y,domain:_,scheme:v})},validate(g,y,{options:v},{regex:_,domain:C,scheme:S}){if(["http:/","https:/"].includes(g))return y.error("string.uri");let T=_.exec(g);if(!T&&y.prefs.convert&&v.encodeUri){const w=encodeURI(g);T=_.exec(w),T&&(g=w)}if(T){const w=T[1]||T[2];return!C||v.allowRelative&&!w||p.isValid(w,C)?g:y.error("string.domain",{value:w})}return v.relativeOnly?y.error("string.uriRelativeOnly"):v.scheme?y.error("string.uriCustomScheme",{scheme:S,value:g}):y.error("string.uri")}}},manifest:{build(g,y){if(y.replacements)for(const{pattern:v,replacement:_}of y.replacements)g=g.replace(v,_);return g}},messages:{"string.alphanum":"{{#label}} must only contain alpha-numeric characters","string.base":"{{#label}} must be a string","string.base64":"{{#label}} must be a valid base64 string","string.creditCard":"{{#label}} must be a credit card","string.dataUri":"{{#label}} must be a valid dataUri string","string.domain":"{{#label}} must contain a valid domain name","string.email":"{{#label}} must be a valid email","string.empty":"{{#label}} is not allowed to be empty","string.guid":"{{#label}} must be a valid GUID","string.hex":"{{#label}} must only contain hexadecimal characters","string.hexAlign":"{{#label}} hex decoded representation must be byte aligned","string.hostname":"{{#label}} must be a valid hostname","string.ip":"{{#label}} must be a valid ip address with a {{#cidr}} CIDR","string.ipVersion":"{{#label}} must be a valid ip address of one of the following versions {{#version}} with a {{#cidr}} CIDR","string.isoDate":"{{#label}} must be in iso format","string.isoDuration":"{{#label}} must be a valid ISO 8601 duration","string.length":"{{#label}} length must be {{#limit}} characters long","string.lowercase":"{{#label}} must only contain lowercase characters","string.max":"{{#label}} length must be less than or equal to {{#limit}} characters long","string.min":"{{#label}} length must be at least {{#limit}} characters long","string.normalize":"{{#label}} must be unicode normalized in the {{#form}} form","string.token":"{{#label}} must only contain alpha-numeric and underscore characters","string.pattern.base":"{{#label}} with value {:[.]} fails to match the required pattern: {{#regex}}","string.pattern.name":"{{#label}} with value {:[.]} fails to match the {{#name}} pattern","string.pattern.invert.base":"{{#label}} with value {:[.]} matches the inverted pattern: {{#regex}}","string.pattern.invert.name":"{{#label}} with value {:[.]} matches the inverted {{#name}} pattern","string.trim":"{{#label}} must not have leading or trailing whitespace","string.uri":"{{#label}} must be a valid uri","string.uriCustomScheme":"{{#label}} must be a valid uri with a scheme matching the {{#scheme}} pattern","string.uriRelativeOnly":"{{#label}} must be a valid relative uri","string.uppercase":"{{#label}} must only contain uppercase characters"}}),b.addressOptions=function(g){if(!g)return b.tlds||g;if(a(g.minDomainSegments===void 0||Number.isSafeInteger(g.minDomainSegments)&&g.minDomainSegments>0,"minDomainSegments must be a positive integer"),a(g.maxDomainSegments===void 0||Number.isSafeInteger(g.maxDomainSegments)&&g.maxDomainSegments>0,"maxDomainSegments must be a positive integer"),g.tlds===!1)return g;if(g.tlds===!0||g.tlds===void 0)return a(b.tlds,"Built-in TLD list disabled"),Object.assign({},g,b.tlds);a(typeof g.tlds=="object","tlds must be true, false, or an object");const y=g.tlds.deny;if(y)return Array.isArray(y)&&(g=Object.assign({},g,{tlds:{deny:new Set(y)}})),a(g.tlds.deny instanceof Set,"tlds.deny must be an array, Set, or boolean"),a(!g.tlds.allow,"Cannot specify both tlds.allow and tlds.deny lists"),b.validateTlds(g.tlds.deny,"tlds.deny"),g;const v=g.tlds.allow;return v?v===!0?(a(b.tlds,"Built-in TLD list disabled"),Object.assign({},g,b.tlds)):(Array.isArray(v)&&(g=Object.assign({},g,{tlds:{allow:new Set(v)}})),a(g.tlds.allow instanceof Set,"tlds.allow must be an array, Set, or boolean"),b.validateTlds(g.tlds.allow,"tlds.allow"),g):g},b.validateTlds=function(g,y){for(const v of g)a(p.isValid(v,{minDomainSegments:1,maxDomainSegments:1}),`${y} must contain valid top level domain names`)},b.isoDate=function(g){if(!f.isIsoDate(g))return null;/.*T.*[+-]\d\d$/.test(g)&&(g+="00");const y=new Date(g);return isNaN(y.getTime())?null:y.toISOString()},b.length=function(g,y,v,_,C){return a(!C||!1,"Invalid encoding:",C),g.$_addRule({name:y,method:"length",args:{limit:v,encoding:C},operator:_})}},8826:(r,n,o)=>{const a=o(375),p=o(8068),m={};m.Map=class extends Map{slice(){return new m.Map(this)}},r.exports=p.extend({type:"symbol",terms:{map:{init:new m.Map}},coerce:{method(d,{schema:l,error:c}){const u=l.$_terms.map.get(d);return u&&(d=u),l._flags.only&&typeof d!="symbol"?{value:d,errors:c("symbol.map",{map:l.$_terms.map})}:{value:d}}},validate(d,{error:l}){if(typeof d!="symbol")return{value:d,errors:l("symbol.base")}},rules:{map:{method(d){d&&!d[Symbol.iterator]&&typeof d=="object"&&(d=Object.entries(d)),a(d&&d[Symbol.iterator],"Iterable must be an iterable or object");const l=this.clone(),c=[];for(const u of d){a(u&&u[Symbol.iterator],"Entry must be an iterable");const[h,f]=u;a(typeof h!="object"&&typeof h!="function"&&typeof h!="symbol","Key must not be of type object, function, or Symbol"),a(typeof f=="symbol","Value must be a Symbol"),l.$_terms.map.set(h,f),c.push(f)}return l.valid(...c)}}},manifest:{build:(d,l)=>(l.map&&(d=d.map(l.map)),d)},messages:{"symbol.base":"{{#label}} must be a symbol","symbol.map":"{{#label}} must be one of {{#map}}"}})},8863:(r,n,o)=>{const a=o(375),p=o(8571),m=o(738),d=o(9621),l=o(8160),c=o(6354),u=o(493),h={result:Symbol("result")};n.entry=function(f,b,g){let y=l.defaults;g&&(a(g.warnings===void 0,"Cannot override warnings preference in synchronous validation"),a(g.artifacts===void 0,"Cannot override artifacts preference in synchronous validation"),y=l.preferences(l.defaults,g));const v=h.entry(f,b,y);a(!v.mainstay.externals.length,"Schema with external rules must use validateAsync()");const _={value:v.value};return v.error&&(_.error=v.error),v.mainstay.warnings.length&&(_.warning=c.details(v.mainstay.warnings)),v.mainstay.debug&&(_.debug=v.mainstay.debug),v.mainstay.artifacts&&(_.artifacts=v.mainstay.artifacts),_},n.entryAsync=async function(f,b,g){let y=l.defaults;g&&(y=l.preferences(l.defaults,g));const v=h.entry(f,b,y),_=v.mainstay;if(v.error)throw _.debug&&(v.error.debug=_.debug),v.error;if(_.externals.length){let S=v.value;const T=[];for(const w of _.externals){const x=w.state.path,k=w.schema.type==="link"?_.links.get(w.schema):null;let E,P,O=S;const z=x.length?[S]:[],I=x.length?d(f,x):f;if(x.length){E=x[x.length-1];let L=S;for(const F of x.slice(0,-1))L=L[F],z.unshift(L);P=z[0],O=P[E]}try{const L=(Z,Q)=>(k||w.schema).$_createError(Z,O,Q,w.state,y),F=await w.method(O,{schema:w.schema,linked:k,state:w.state,prefs:g,original:I,error:L,errorsArray:h.errorsArray,warn:(Z,Q)=>_.warnings.push((k||w.schema).$_createError(Z,O,Q,w.state,y)),message:(Z,Q)=>(k||w.schema).$_createError("external",O,Q,w.state,y,{messages:Z})});if(F===void 0||F===O)continue;if(F instanceof c.Report){if(_.tracer.log(w.schema,w.state,"rule","external","error"),T.push(F),y.abortEarly)break;continue}if(Array.isArray(F)&&F[l.symbols.errors]){if(_.tracer.log(w.schema,w.state,"rule","external","error"),T.push(...F),y.abortEarly)break;continue}P?(_.tracer.value(w.state,"rule",O,F,"external"),P[E]=F):(_.tracer.value(w.state,"rule",S,F,"external"),S=F)}catch(L){throw y.errors.label&&(L.message+=` (${w.label})`),L}}if(v.value=S,T.length)throw v.error=c.process(T,f,y),_.debug&&(v.error.debug=_.debug),v.error}if(!y.warnings&&!y.debug&&!y.artifacts)return v.value;const C={value:v.value};return _.warnings.length&&(C.warning=c.details(_.warnings)),_.debug&&(C.debug=_.debug),_.artifacts&&(C.artifacts=_.artifacts),C},h.Mainstay=class{constructor(f,b,g){this.externals=[],this.warnings=[],this.tracer=f,this.debug=b,this.links=g,this.shadow=null,this.artifacts=null,this._snapshots=[]}snapshot(){this._snapshots.push({externals:this.externals.slice(),warnings:this.warnings.slice()})}restore(){const f=this._snapshots.pop();this.externals=f.externals,this.warnings=f.warnings}commit(){this._snapshots.pop()}},h.entry=function(f,b,g){const{tracer:y,cleanup:v}=h.tracer(b,g),_=g.debug?[]:null,C=b._ids._schemaChain?new Map:null,S=new h.Mainstay(y,_,C),T=b._ids._schemaChain?[{schema:b}]:null,w=new u([],[],{mainstay:S,schemas:T}),x=n.validate(f,b,w,g);v&&b.$_root.untrace();const k=c.process(x.errors,f,g);return{value:x.value,error:k,mainstay:S}},h.tracer=function(f,b){return f.$_root._tracer?{tracer:f.$_root._tracer._register(f)}:b.debug?(a(f.$_root.trace,"Debug mode not supported"),{tracer:f.$_root.trace()._register(f),cleanup:!0}):{tracer:h.ignore}},n.validate=function(f,b,g,y,v={}){if(b.$_terms.whens&&(b=b._generate(f,g,y).schema),b._preferences&&(y=h.prefs(b,y)),b._cache&&y.cache){const k=b._cache.get(f);if(g.mainstay.tracer.debug(g,"validate","cached",!!k),k)return k}const _=(k,E,P)=>b.$_createError(k,f,E,P||g,y),C={original:f,prefs:y,schema:b,state:g,error:_,errorsArray:h.errorsArray,warn:(k,E,P)=>g.mainstay.warnings.push(_(k,E,P)),message:(k,E)=>b.$_createError("custom",f,E,g,y,{messages:k})};g.mainstay.tracer.entry(b,g);const S=b._definition;if(S.prepare&&f!==void 0&&y.convert){const k=S.prepare(f,C);if(k){if(g.mainstay.tracer.value(g,"prepare",f,k.value),k.errors)return h.finalize(k.value,[].concat(k.errors),C);f=k.value}}if(S.coerce&&f!==void 0&&y.convert&&(!S.coerce.from||S.coerce.from.includes(typeof f))){const k=S.coerce.method(f,C);if(k){if(g.mainstay.tracer.value(g,"coerced",f,k.value),k.errors)return h.finalize(k.value,[].concat(k.errors),C);f=k.value}}const T=b._flags.empty;T&&T.$_match(h.trim(f,b),g.nest(T),l.defaults)&&(g.mainstay.tracer.value(g,"empty",f,void 0),f=void 0);const w=v.presence||b._flags.presence||(b._flags._endedSwitch?null:y.presence);if(f===void 0){if(w==="forbidden")return h.finalize(f,null,C);if(w==="required")return h.finalize(f,[b.$_createError("any.required",f,null,g,y)],C);if(w==="optional"){if(b._flags.default!==l.symbols.deepDefault)return h.finalize(f,null,C);g.mainstay.tracer.value(g,"default",f,{}),f={}}}else if(w==="forbidden")return h.finalize(f,[b.$_createError("any.unknown",f,null,g,y)],C);const x=[];if(b._valids){const k=b._valids.get(f,g,y,b._flags.insensitive);if(k)return y.convert&&(g.mainstay.tracer.value(g,"valids",f,k.value),f=k.value),g.mainstay.tracer.filter(b,g,"valid",k),h.finalize(f,null,C);if(b._flags.only){const E=b.$_createError("any.only",f,{valids:b._valids.values({display:!0})},g,y);if(y.abortEarly)return h.finalize(f,[E],C);x.push(E)}}if(b._invalids){const k=b._invalids.get(f,g,y,b._flags.insensitive);if(k){g.mainstay.tracer.filter(b,g,"invalid",k);const E=b.$_createError("any.invalid",f,{invalids:b._invalids.values({display:!0})},g,y);if(y.abortEarly)return h.finalize(f,[E],C);x.push(E)}}if(S.validate){const k=S.validate(f,C);if(k&&(g.mainstay.tracer.value(g,"base",f,k.value),f=k.value,k.errors)){if(!Array.isArray(k.errors))return x.push(k.errors),h.finalize(f,x,C);if(k.errors.length)return x.push(...k.errors),h.finalize(f,x,C)}}return b._rules.length?h.rules(f,x,C):h.finalize(f,x,C)},h.rules=function(f,b,g){const{schema:y,state:v,prefs:_}=g;for(const C of y._rules){const S=y._definition.rules[C.method];if(S.convert&&_.convert){v.mainstay.tracer.log(y,v,"rule",C.name,"full");continue}let T,w=C.args;if(C._resolve.length){w=Object.assign({},w);for(const k of C._resolve){const E=S.argsByName.get(k),P=w[k].resolve(f,v,_),O=E.normalize?E.normalize(P):P,z=l.validateArg(O,null,E);if(z){T=y.$_createError("any.ref",P,{arg:k,ref:w[k],reason:z},v,_);break}w[k]=O}}T=T||S.validate(f,g,w,C);const x=h.rule(T,C);if(x.errors){if(v.mainstay.tracer.log(y,v,"rule",C.name,"error"),C.warn){v.mainstay.warnings.push(...x.errors);continue}if(_.abortEarly)return h.finalize(f,x.errors,g);b.push(...x.errors)}else v.mainstay.tracer.log(y,v,"rule",C.name,"pass"),v.mainstay.tracer.value(v,"rule",f,x.value,C.name),f=x.value}return h.finalize(f,b,g)},h.rule=function(f,b){return f instanceof c.Report?(h.error(f,b),{errors:[f],value:null}):Array.isArray(f)&&f[l.symbols.errors]?(f.forEach(g=>h.error(g,b)),{errors:f,value:null}):{errors:null,value:f}},h.error=function(f,b){return b.message&&f._setTemplate(b.message),f},h.finalize=function(f,b,g){b=b||[];const{schema:y,state:v,prefs:_}=g;if(b.length){const S=h.default("failover",void 0,b,g);S!==void 0&&(v.mainstay.tracer.value(v,"failover",f,S),f=S,b=[])}if(b.length&&y._flags.error)if(typeof y._flags.error=="function"){b=y._flags.error(b),Array.isArray(b)||(b=[b]);for(const S of b)a(S instanceof Error||S instanceof c.Report,"error() must return an Error object")}else b=[y._flags.error];if(f===void 0){const S=h.default("default",f,b,g);v.mainstay.tracer.value(v,"default",f,S),f=S}if(y._flags.cast&&f!==void 0){const S=y._definition.cast[y._flags.cast];if(S.from(f)){const T=S.to(f,g);v.mainstay.tracer.value(v,"cast",f,T,y._flags.cast),f=T}}if(y.$_terms.externals&&_.externals&&_._externals!==!1)for(const{method:S}of y.$_terms.externals)v.mainstay.externals.push({method:S,schema:y,state:v,label:c.label(y._flags,v,_)});const C={value:f,errors:b.length?b:null};return y._flags.result&&(C.value=y._flags.result==="strip"?void 0:g.original,v.mainstay.tracer.value(v,y._flags.result,f,C.value),v.shadow(f,y._flags.result)),y._cache&&_.cache!==!1&&!y._refs.length&&y._cache.set(g.original,C),f===void 0||C.errors||y._flags.artifact===void 0||(v.mainstay.artifacts=v.mainstay.artifacts||new Map,v.mainstay.artifacts.has(y._flags.artifact)||v.mainstay.artifacts.set(y._flags.artifact,[]),v.mainstay.artifacts.get(y._flags.artifact).push(v.path)),C},h.prefs=function(f,b){const g=b===l.defaults;return g&&f._preferences[l.symbols.prefs]?f._preferences[l.symbols.prefs]:(b=l.preferences(b,f._preferences),g&&(f._preferences[l.symbols.prefs]=b),b)},h.default=function(f,b,g,y){const{schema:v,state:_,prefs:C}=y,S=v._flags[f];if(C.noDefaults||S===void 0)return b;if(_.mainstay.tracer.log(v,_,"rule",f,"full"),!S)return S;if(typeof S=="function"){const T=S.length?[p(_.ancestors[0]),y]:[];try{return S(...T)}catch(w){return void g.push(v.$_createError(`any.${f}`,null,{error:w},_,C))}}return typeof S!="object"?S:S[l.symbols.literal]?S.literal:l.isResolvable(S)?S.resolve(b,_,C):p(S)},h.trim=function(f,b){if(typeof f!="string")return f;const g=b.$_getRule("trim");return g&&g.args.enabled?f.trim():f},h.ignore={active:!1,debug:m,entry:m,filter:m,log:m,resolve:m,value:m},h.errorsArray=function(){const f=[];return f[l.symbols.errors]=!0,f}},2036:(r,n,o)=>{const a=o(375),p=o(9474),m=o(8160),d={};r.exports=d.Values=class{constructor(l,c){this._values=new Set(l),this._refs=new Set(c),this._lowercase=d.lowercases(l),this._override=!1}get length(){return this._values.size+this._refs.size}add(l,c){m.isResolvable(l)?this._refs.has(l)||(this._refs.add(l),c&&c.register(l)):this.has(l,null,null,!1)||(this._values.add(l),typeof l=="string"&&this._lowercase.set(l.toLowerCase(),l))}static merge(l,c,u){if(l=l||new d.Values,c){if(c._override)return c.clone();for(const h of[...c._values,...c._refs])l.add(h)}if(u)for(const h of[...u._values,...u._refs])l.remove(h);return l.length?l:null}remove(l){m.isResolvable(l)?this._refs.delete(l):(this._values.delete(l),typeof l=="string"&&this._lowercase.delete(l.toLowerCase()))}has(l,c,u,h){return!!this.get(l,c,u,h)}get(l,c,u,h){if(!this.length)return!1;if(this._values.has(l))return{value:l};if(typeof l=="string"&&l&&h){const f=this._lowercase.get(l.toLowerCase());if(f)return{value:f}}if(!this._refs.size&&typeof l!="object")return!1;if(typeof l=="object"){for(const f of this._values)if(p(f,l))return{value:f}}if(c)for(const f of this._refs){const b=f.resolve(l,c,u,null,{in:!0});if(b===void 0)continue;const g=f.in&&typeof b=="object"?Array.isArray(b)?b:Object.keys(b):[b];for(const y of g)if(typeof y==typeof l){if(h&&l&&typeof l=="string"){if(y.toLowerCase()===l.toLowerCase())return{value:y,ref:f}}else if(p(y,l))return{value:y,ref:f}}}return!1}override(){this._override=!0}values(l){if(l&&l.display){const c=[];for(const u of[...this._values,...this._refs])u!==void 0&&c.push(u);return c}return Array.from([...this._values,...this._refs])}clone(){const l=new d.Values(this._values,this._refs);return l._override=this._override,l}concat(l){a(!l._override,"Cannot concat override set of values");const c=new d.Values([...this._values,...l._values],[...this._refs,...l._refs]);return c._override=this._override,c}describe(){const l=[];this._override&&l.push({override:!0});for(const c of this._values.values())l.push(c&&typeof c=="object"?{value:c}:c);for(const c of this._refs.values())l.push(c.describe());return l}},d.Values.prototype[m.symbols.values]=!0,d.Values.prototype.slice=d.Values.prototype.clone,d.lowercases=function(l){const c=new Map;if(l)for(const u of l)typeof u=="string"&&c.set(u.toLowerCase(),u);return c}},978:(r,n,o)=>{const a=o(375),p=o(8571),m=o(1687),d=o(9621),l={};r.exports=function(c,u,h={}){if(a(c&&typeof c=="object","Invalid defaults value: must be an object"),a(!u||u===!0||typeof u=="object","Invalid source value: must be true, falsy or an object"),a(typeof h=="object","Invalid options: must be an object"),!u)return null;if(h.shallow)return l.applyToDefaultsWithShallow(c,u,h);const f=p(c);if(u===!0)return f;const b=h.nullOverride!==void 0&&h.nullOverride;return m(f,u,{nullOverride:b,mergeArrays:!1})},l.applyToDefaultsWithShallow=function(c,u,h){const f=h.shallow;a(Array.isArray(f),"Invalid keys");const b=new Map,g=u===!0?null:new Set;for(let _ of f){_=Array.isArray(_)?_:_.split(".");const C=d(c,_);C&&typeof C=="object"?b.set(C,g&&d(u,_)||C):g&&g.add(_)}const y=p(c,{},b);if(!g)return y;for(const _ of g)l.reachCopy(y,u,_);const v=h.nullOverride!==void 0&&h.nullOverride;return m(y,u,{nullOverride:v,mergeArrays:!1})},l.reachCopy=function(c,u,h){for(const g of h){if(!(g in u))return;const y=u[g];if(typeof y!="object"||y===null)return;u=y}const f=u;let b=c;for(let g=0;g<h.length-1;++g){const y=h[g];typeof b[y]!="object"&&(b[y]={}),b=b[y]}b[h[h.length-1]]=f}},375:(r,n,o)=>{const a=o(7916);r.exports=function(p,...m){if(!p)throw m.length===1&&m[0]instanceof Error?m[0]:new a(m)}},8571:(r,n,o)=>{const a=o(9621),p=o(4277),m=o(7043),d={needsProtoHack:new Set([p.set,p.map,p.weakSet,p.weakMap])};r.exports=d.clone=function(l,c={},u=null){if(typeof l!="object"||l===null)return l;let h=d.clone,f=u;if(c.shallow){if(c.shallow!==!0)return d.cloneWithShallow(l,c);h=v=>v}else if(f){const v=f.get(l);if(v)return v}else f=new Map;const b=p.getInternalProto(l);if(b===p.buffer)return!1;if(b===p.date)return new Date(l.getTime());if(b===p.regex)return new RegExp(l);const g=d.base(l,b,c);if(g===l)return l;if(f&&f.set(l,g),b===p.set)for(const v of l)g.add(h(v,c,f));else if(b===p.map)for(const[v,_]of l)g.set(v,h(_,c,f));const y=m.keys(l,c);for(const v of y){if(v==="__proto__")continue;if(b===p.array&&v==="length"){g.length=l.length;continue}const _=Object.getOwnPropertyDescriptor(l,v);_?_.get||_.set?Object.defineProperty(g,v,_):_.enumerable?g[v]=h(l[v],c,f):Object.defineProperty(g,v,{enumerable:!1,writable:!0,configurable:!0,value:h(l[v],c,f)}):Object.defineProperty(g,v,{enumerable:!0,writable:!0,configurable:!0,value:h(l[v],c,f)})}return g},d.cloneWithShallow=function(l,c){const u=c.shallow;(c=Object.assign({},c)).shallow=!1;const h=new Map;for(const f of u){const b=a(l,f);typeof b!="object"&&typeof b!="function"||h.set(b,b)}return d.clone(l,c,h)},d.base=function(l,c,u){if(u.prototype===!1)return d.needsProtoHack.has(c)?new c.constructor:c===p.array?[]:{};const h=Object.getPrototypeOf(l);if(h&&h.isImmutable)return l;if(c===p.array){const f=[];return h!==c&&Object.setPrototypeOf(f,h),f}if(d.needsProtoHack.has(c)){const f=new h.constructor;return h!==c&&Object.setPrototypeOf(f,h),f}return Object.create(h)}},9474:(r,n,o)=>{const a=o(4277),p={mismatched:null};r.exports=function(m,d,l){return l=Object.assign({prototype:!0},l),!!p.isDeepEqual(m,d,l,[])},p.isDeepEqual=function(m,d,l,c){if(m===d)return m!==0||1/m==1/d;const u=typeof m;if(u!==typeof d||m===null||d===null)return!1;if(u==="function"){if(!l.deepFunction||m.toString()!==d.toString())return!1}else if(u!=="object")return m!=m&&d!=d;const h=p.getSharedType(m,d,!!l.prototype);switch(h){case a.buffer:return!1;case a.promise:return m===d;case a.regex:return m.toString()===d.toString();case p.mismatched:return!1}for(let f=c.length-1;f>=0;--f)if(c[f].isSame(m,d))return!0;c.push(new p.SeenEntry(m,d));try{return!!p.isDeepEqualObj(h,m,d,l,c)}finally{c.pop()}},p.getSharedType=function(m,d,l){if(l)return Object.getPrototypeOf(m)!==Object.getPrototypeOf(d)?p.mismatched:a.getInternalProto(m);const c=a.getInternalProto(m);return c!==a.getInternalProto(d)?p.mismatched:c},p.valueOf=function(m){const d=m.valueOf;if(d===void 0)return m;try{return d.call(m)}catch(l){return l}},p.hasOwnEnumerableProperty=function(m,d){return Object.prototype.propertyIsEnumerable.call(m,d)},p.isSetSimpleEqual=function(m,d){for(const l of Set.prototype.values.call(m))if(!Set.prototype.has.call(d,l))return!1;return!0},p.isDeepEqualObj=function(m,d,l,c,u){const{isDeepEqual:h,valueOf:f,hasOwnEnumerableProperty:b}=p,{keys:g,getOwnPropertySymbols:y}=Object;if(m===a.array){if(!c.part){if(d.length!==l.length)return!1;for(let T=0;T<d.length;++T)if(!h(d[T],l[T],c,u))return!1;return!0}for(const T of d)for(const w of l)if(h(T,w,c,u))return!0}else if(m===a.set){if(d.size!==l.size)return!1;if(!p.isSetSimpleEqual(d,l)){const T=new Set(Set.prototype.values.call(l));for(const w of Set.prototype.values.call(d)){if(T.delete(w))continue;let x=!1;for(const k of T)if(h(w,k,c,u)){T.delete(k),x=!0;break}if(!x)return!1}}}else if(m===a.map){if(d.size!==l.size)return!1;for(const[T,w]of Map.prototype.entries.call(d))if(w===void 0&&!Map.prototype.has.call(l,T)||!h(w,Map.prototype.get.call(l,T),c,u))return!1}else if(m===a.error&&(d.name!==l.name||d.message!==l.message))return!1;const v=f(d),_=f(l);if((d!==v||l!==_)&&!h(v,_,c,u))return!1;const C=g(d);if(!c.part&&C.length!==g(l).length&&!c.skip)return!1;let S=0;for(const T of C)if(c.skip&&c.skip.includes(T))l[T]===void 0&&++S;else if(!b(l,T)||!h(d[T],l[T],c,u))return!1;if(!c.part&&C.length-S!==g(l).length)return!1;if(c.symbols!==!1){const T=y(d),w=new Set(y(l));for(const x of T){if(!c.skip||!c.skip.includes(x)){if(b(d,x)){if(!b(l,x)||!h(d[x],l[x],c,u))return!1}else if(b(l,x))return!1}w.delete(x)}for(const x of w)if(b(l,x))return!1}return!0},p.SeenEntry=class{constructor(m,d){this.obj=m,this.ref=d}isSame(m,d){return this.obj===m&&this.ref===d}}},7916:(r,n,o)=>{const a=o(8761);r.exports=class extends Error{constructor(p){super(p.filter(m=>m!=="").map(m=>typeof m=="string"?m:m instanceof Error?m.message:a(m)).join(" ")||"Unknown error"),typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,n.assert)}}},5277:r=>{const n={};r.exports=function(o){if(!o)return"";let a="";for(let p=0;p<o.length;++p){const m=o.charCodeAt(p);n.isSafe(m)?a+=o[p]:a+=n.escapeHtmlChar(m)}return a},n.escapeHtmlChar=function(o){return n.namedHtml.get(o)||(o>=256?"&#"+o+";":`&#x${o.toString(16).padStart(2,"0")};`)},n.isSafe=function(o){return n.safeCharCodes.has(o)},n.namedHtml=new Map([[38,"&amp;"],[60,"&lt;"],[62,"&gt;"],[34,"&quot;"],[160,"&nbsp;"],[162,"&cent;"],[163,"&pound;"],[164,"&curren;"],[169,"&copy;"],[174,"&reg;"]]),n.safeCharCodes=function(){const o=new Set;for(let a=32;a<123;++a)(a>=97||a>=65&&a<=90||a>=48&&a<=57||a===32||a===46||a===44||a===45||a===58||a===95)&&o.add(a);return o}()},6064:r=>{r.exports=function(n){return n.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g,"\\$&")}},738:r=>{r.exports=function(){}},1687:(r,n,o)=>{const a=o(375),p=o(8571),m=o(7043),d={};r.exports=d.merge=function(l,c,u){if(a(l&&typeof l=="object","Invalid target value: must be an object"),a(c==null||typeof c=="object","Invalid source value: must be null, undefined, or an object"),!c)return l;if(u=Object.assign({nullOverride:!0,mergeArrays:!0},u),Array.isArray(c)){a(Array.isArray(l),"Cannot merge array onto an object"),u.mergeArrays||(l.length=0);for(let f=0;f<c.length;++f)l.push(p(c[f],{symbols:u.symbols}));return l}const h=m.keys(c,u);for(let f=0;f<h.length;++f){const b=h[f];if(b==="__proto__"||!Object.prototype.propertyIsEnumerable.call(c,b))continue;const g=c[b];if(g&&typeof g=="object"){if(l[b]===g)continue;!l[b]||typeof l[b]!="object"||Array.isArray(l[b])!==Array.isArray(g)||g instanceof Date||g instanceof RegExp?l[b]=p(g,{symbols:u.symbols}):d.merge(l[b],g,u)}else(g!=null||u.nullOverride)&&(l[b]=g)}return l}},9621:(r,n,o)=>{const a=o(375),p={};r.exports=function(m,d,l){if(d===!1||d==null)return m;typeof(l=l||{})=="string"&&(l={separator:l});const c=Array.isArray(d);a(!c||!l.separator,"Separator option is not valid for array-based chain");const u=c?d:d.split(l.separator||".");let h=m;for(let f=0;f<u.length;++f){let b=u[f];const g=l.iterables&&p.iterables(h);if(Array.isArray(h)||g==="set"){const y=Number(b);Number.isInteger(y)&&(b=y<0?h.length+y:y)}if(!h||typeof h=="function"&&l.functions===!1||!g&&h[b]===void 0){a(!l.strict||f+1===u.length,"Missing segment",b,"in reach path ",d),a(typeof h=="object"||l.functions===!0||typeof h!="function","Invalid segment",b,"in reach path ",d),h=l.default;break}h=g?g==="set"?[...h][b]:h.get(b):h[b]}return h},p.iterables=function(m){return m instanceof Set?"set":m instanceof Map?"map":void 0}},8761:r=>{r.exports=function(...n){try{return JSON.stringify(...n)}catch(o){return"[Cannot display object: "+o.message+"]"}}},4277:(r,n)=>{const o={};n=r.exports={array:Array.prototype,buffer:!1,date:Date.prototype,error:Error.prototype,generic:Object.prototype,map:Map.prototype,promise:Promise.prototype,regex:RegExp.prototype,set:Set.prototype,weakMap:WeakMap.prototype,weakSet:WeakSet.prototype},o.typeMap=new Map([["[object Error]",n.error],["[object Map]",n.map],["[object Promise]",n.promise],["[object Set]",n.set],["[object WeakMap]",n.weakMap],["[object WeakSet]",n.weakSet]]),n.getInternalProto=function(a){if(Array.isArray(a))return n.array;if(a instanceof Date)return n.date;if(a instanceof RegExp)return n.regex;if(a instanceof Error)return n.error;const p=Object.prototype.toString.call(a);return o.typeMap.get(p)||n.generic}},7043:(r,n)=>{n.keys=function(o,a={}){return a.symbols!==!1?Reflect.ownKeys(o):Object.getOwnPropertyNames(o)}},3652:(r,n,o)=>{const a=o(375),p={};n.Sorter=class{constructor(){this._items=[],this.nodes=[]}add(m,d){const l=[].concat((d=d||{}).before||[]),c=[].concat(d.after||[]),u=d.group||"?",h=d.sort||0;a(!l.includes(u),`Item cannot come before itself: ${u}`),a(!l.includes("?"),"Item cannot come before unassociated items"),a(!c.includes(u),`Item cannot come after itself: ${u}`),a(!c.includes("?"),"Item cannot come after unassociated items"),Array.isArray(m)||(m=[m]);for(const f of m){const b={seq:this._items.length,sort:h,before:l,after:c,group:u,node:f};this._items.push(b)}if(!d.manual){const f=this._sort();a(f,"item",u!=="?"?`added into group ${u}`:"","created a dependencies error")}return this.nodes}merge(m){Array.isArray(m)||(m=[m]);for(const l of m)if(l)for(const c of l._items)this._items.push(Object.assign({},c));this._items.sort(p.mergeSort);for(let l=0;l<this._items.length;++l)this._items[l].seq=l;const d=this._sort();return a(d,"merge created a dependencies error"),this.nodes}sort(){const m=this._sort();return a(m,"sort created a dependencies error"),this.nodes}_sort(){const m={},d=Object.create(null),l=Object.create(null);for(const b of this._items){const g=b.seq,y=b.group;l[y]=l[y]||[],l[y].push(g),m[g]=b.before;for(const v of b.after)d[v]=d[v]||[],d[v].push(g)}for(const b in m){const g=[];for(const y in m[b]){const v=m[b][y];l[v]=l[v]||[],g.push(...l[v])}m[b]=g}for(const b in d)if(l[b])for(const g of l[b])m[g].push(...d[b]);const c={};for(const b in m){const g=m[b];for(const y of g)c[y]=c[y]||[],c[y].push(b)}const u={},h=[];for(let b=0;b<this._items.length;++b){let g=b;if(c[b]){g=null;for(let y=0;y<this._items.length;++y){if(u[y]===!0)continue;c[y]||(c[y]=[]);const v=c[y].length;let _=0;for(let C=0;C<v;++C)u[c[y][C]]&&++_;if(_===v){g=y;break}}}g!==null&&(u[g]=!0,h.push(g))}if(h.length!==this._items.length)return!1;const f={};for(const b of this._items)f[b.seq]=b;this._items=[],this.nodes=[];for(const b of h){const g=f[b];this.nodes.push(g.node),this._items.push(g)}return!0}},p.mergeSort=(m,d)=>m.sort===d.sort?0:m.sort<d.sort?-1:1},5380:(r,n,o)=>{const a=o(443),p=o(2178),m={minDomainSegments:2,nonAsciiRx:/[^\x00-\x7f]/,domainControlRx:/[\x00-\x20@\:\/\\#!\$&\'\(\)\*\+,;=\?]/,tldSegmentRx:/^[a-zA-Z](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?$/,domainSegmentRx:/^[a-zA-Z0-9](?:[a-zA-Z0-9\-]*[a-zA-Z0-9])?$/,URL:a.URL||URL};n.analyze=function(d,l={}){if(!d)return p.code("DOMAIN_NON_EMPTY_STRING");if(typeof d!="string")throw new Error("Invalid input: domain must be a string");if(d.length>256)return p.code("DOMAIN_TOO_LONG");if(m.nonAsciiRx.test(d)){if(l.allowUnicode===!1)return p.code("DOMAIN_INVALID_UNICODE_CHARS");d=d.normalize("NFC")}if(m.domainControlRx.test(d))return p.code("DOMAIN_INVALID_CHARS");d=m.punycode(d),l.allowFullyQualified&&d[d.length-1]==="."&&(d=d.slice(0,-1));const c=l.minDomainSegments||m.minDomainSegments,u=d.split(".");if(u.length<c)return p.code("DOMAIN_SEGMENTS_COUNT");if(l.maxDomainSegments&&u.length>l.maxDomainSegments)return p.code("DOMAIN_SEGMENTS_COUNT_MAX");const h=l.tlds;if(h){const f=u[u.length-1].toLowerCase();if(h.deny&&h.deny.has(f)||h.allow&&!h.allow.has(f))return p.code("DOMAIN_FORBIDDEN_TLDS")}for(let f=0;f<u.length;++f){const b=u[f];if(!b.length)return p.code("DOMAIN_EMPTY_SEGMENT");if(b.length>63)return p.code("DOMAIN_LONG_SEGMENT");if(f<u.length-1){if(!m.domainSegmentRx.test(b))return p.code("DOMAIN_INVALID_CHARS")}else if(!m.tldSegmentRx.test(b))return p.code("DOMAIN_INVALID_TLDS_CHARS")}return null},n.isValid=function(d,l){return!n.analyze(d,l)},m.punycode=function(d){d.includes("%")&&(d=d.replace(/%/g,"%25"));try{return new m.URL(`http://${d}`).host}catch{return d}}},1745:(r,n,o)=>{const a=o(9848),p=o(5380),m=o(2178),d={nonAsciiRx:/[^\x00-\x7f]/,encoder:new(a.TextEncoder||TextEncoder)};n.analyze=function(l,c){return d.email(l,c)},n.isValid=function(l,c){return!d.email(l,c)},d.email=function(l,c={}){if(typeof l!="string")throw new Error("Invalid input: email must be a string");if(!l)return m.code("EMPTY_STRING");const u=!d.nonAsciiRx.test(l);if(!u){if(c.allowUnicode===!1)return m.code("FORBIDDEN_UNICODE");l=l.normalize("NFC")}const h=l.split("@");if(h.length!==2)return h.length>2?m.code("MULTIPLE_AT_CHAR"):m.code("MISSING_AT_CHAR");const[f,b]=h;if(!f)return m.code("EMPTY_LOCAL");if(!c.ignoreLength){if(l.length>254)return m.code("ADDRESS_TOO_LONG");if(d.encoder.encode(f).length>64)return m.code("LOCAL_TOO_LONG")}return d.local(f,u)||p.analyze(b,c)},d.local=function(l,c){const u=l.split(".");for(const h of u){if(!h.length)return m.code("EMPTY_LOCAL_SEGMENT");if(c){if(!d.atextRx.test(h))return m.code("INVALID_LOCAL_CHARS")}else for(const f of h){if(d.atextRx.test(f))continue;const b=d.binary(f);if(!d.atomRx.test(b))return m.code("INVALID_LOCAL_CHARS")}}},d.binary=function(l){return Array.from(d.encoder.encode(l)).map(c=>String.fromCharCode(c)).join("")},d.atextRx=/^[\w!#\$%&'\*\+\-/=\?\^`\{\|\}~]+$/,d.atomRx=new RegExp(["(?:[\\xc2-\\xdf][\\x80-\\xbf])","(?:\\xe0[\\xa0-\\xbf][\\x80-\\xbf])|(?:[\\xe1-\\xec][\\x80-\\xbf]{2})|(?:\\xed[\\x80-\\x9f][\\x80-\\xbf])|(?:[\\xee-\\xef][\\x80-\\xbf]{2})","(?:\\xf0[\\x90-\\xbf][\\x80-\\xbf]{2})|(?:[\\xf1-\\xf3][\\x80-\\xbf]{3})|(?:\\xf4[\\x80-\\x8f][\\x80-\\xbf]{2})"].join("|"))},2178:(r,n)=>{n.codes={EMPTY_STRING:"Address must be a non-empty string",FORBIDDEN_UNICODE:"Address contains forbidden Unicode characters",MULTIPLE_AT_CHAR:"Address cannot contain more than one @ character",MISSING_AT_CHAR:"Address must contain one @ character",EMPTY_LOCAL:"Address local part cannot be empty",ADDRESS_TOO_LONG:"Address too long",LOCAL_TOO_LONG:"Address local part too long",EMPTY_LOCAL_SEGMENT:"Address local part contains empty dot-separated segment",INVALID_LOCAL_CHARS:"Address local part contains invalid character",DOMAIN_NON_EMPTY_STRING:"Domain must be a non-empty string",DOMAIN_TOO_LONG:"Domain too long",DOMAIN_INVALID_UNICODE_CHARS:"Domain contains forbidden Unicode characters",DOMAIN_INVALID_CHARS:"Domain contains invalid character",DOMAIN_INVALID_TLDS_CHARS:"Domain contains invalid tld character",DOMAIN_SEGMENTS_COUNT:"Domain lacks the minimum required number of segments",DOMAIN_SEGMENTS_COUNT_MAX:"Domain contains too many segments",DOMAIN_FORBIDDEN_TLDS:"Domain uses forbidden TLD",DOMAIN_EMPTY_SEGMENT:"Domain contains empty dot-separated segment",DOMAIN_LONG_SEGMENT:"Domain contains dot-separated segment that is too long"},n.code=function(o){return{code:o,error:n.codes[o]}}},9959:(r,n,o)=>{const a=o(375),p=o(5752);n.regex=function(m={}){a(m.cidr===void 0||typeof m.cidr=="string","options.cidr must be a string");const d=m.cidr?m.cidr.toLowerCase():"optional";a(["required","optional","forbidden"].includes(d),"options.cidr must be one of required, optional, forbidden"),a(m.version===void 0||typeof m.version=="string"||Array.isArray(m.version),"options.version must be a string or an array of string");let l=m.version||["ipv4","ipv6","ipvfuture"];Array.isArray(l)||(l=[l]),a(l.length>=1,"options.version must have at least 1 version specified");for(let h=0;h<l.length;++h)a(typeof l[h]=="string","options.version must only contain strings"),l[h]=l[h].toLowerCase(),a(["ipv4","ipv6","ipvfuture"].includes(l[h]),"options.version contains unknown version "+l[h]+" - must be one of ipv4, ipv6, ipvfuture");l=Array.from(new Set(l));const c=`(?:${l.map(h=>{if(d==="forbidden")return p.ip[h];const f=`\\/${h==="ipv4"?p.ip.v4Cidr:p.ip.v6Cidr}`;return d==="required"?`${p.ip[h]}${f}`:`${p.ip[h]}(?:${f})?`}).join("|")})`,u=new RegExp(`^${c}$`);return{cidr:d,versions:l,regex:u,raw:c}}},5752:(r,n,o)=>{const a=o(375),p=o(6064),m={generate:function(){const d={},l="\\dA-Fa-f",c="["+l+"]",u="\\w-\\.~",h="!\\$&'\\(\\)\\*\\+,;=",f="%"+l,b=u+f+h+":@",g="["+b+"]",y="(?:0{0,2}\\d|0?[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5])";d.ipv4address="(?:"+y+"\\.){3}"+y;const v=c+"{1,4}",_="(?:"+v+":"+v+"|"+d.ipv4address+")",C="(?:"+v+":){6}"+_,S="::(?:"+v+":){5}"+_,T="(?:"+v+")?::(?:"+v+":){4}"+_,w="(?:(?:"+v+":){0,1}"+v+")?::(?:"+v+":){3}"+_,x="(?:(?:"+v+":){0,2}"+v+")?::(?:"+v+":){2}"+_,k="(?:(?:"+v+":){0,3}"+v+")?::"+v+":"+_,E="(?:(?:"+v+":){0,4}"+v+")?::"+_,P="(?:(?:"+v+":){0,5}"+v+")?::"+v,O="(?:(?:"+v+":){0,6}"+v+")?::";d.ipv4Cidr="(?:\\d|[1-2]\\d|3[0-2])",d.ipv6Cidr="(?:0{0,2}\\d|0?[1-9]\\d|1[01]\\d|12[0-8])",d.ipv6address="(?:"+C+"|"+S+"|"+T+"|"+w+"|"+x+"|"+k+"|"+E+"|"+P+"|"+O+")",d.ipvFuture="v"+c+"+\\.["+u+h+":]+",d.scheme="[a-zA-Z][a-zA-Z\\d+-\\.]*",d.schemeRegex=new RegExp(d.scheme);const z="["+u+f+h+":]*",I="["+u+f+h+"]{1,255}",L="(?:\\[(?:"+d.ipv6address+"|"+d.ipvFuture+")\\]|"+d.ipv4address+"|"+I+")",F="(?:"+z+"@)?"+L+"(?::\\d*)?",Z="(?:"+z+"@)?("+L+")(?::\\d*)?",Q=g+"*",X=g+"+",Y="(?:\\/"+Q+")*",se="\\/(?:"+X+Y+")?",re=X+Y,Ce="["+u+f+h+"@]+"+Y,ve="(?:\\/\\/\\/"+Q+Y+")";return d.hierPart="(?:(?:\\/\\/"+F+Y+")|"+se+"|"+re+"|"+ve+")",d.hierPartCapture="(?:(?:\\/\\/"+Z+Y+")|"+se+"|"+re+")",d.relativeRef="(?:(?:\\/\\/"+F+Y+")|"+se+"|"+Ce+"|)",d.relativeRefCapture="(?:(?:\\/\\/"+Z+Y+")|"+se+"|"+Ce+"|)",d.query="["+b+"\\/\\?]*(?=#|$)",d.queryWithSquareBrackets="["+b+"\\[\\]\\/\\?]*(?=#|$)",d.fragment="["+b+"\\/\\?]*",d}};m.rfc3986=m.generate(),n.ip={v4Cidr:m.rfc3986.ipv4Cidr,v6Cidr:m.rfc3986.ipv6Cidr,ipv4:m.rfc3986.ipv4address,ipv6:m.rfc3986.ipv6address,ipvfuture:m.rfc3986.ipvFuture},m.createRegex=function(d){const l=m.rfc3986,c="(?:\\?"+(d.allowQuerySquareBrackets?l.queryWithSquareBrackets:l.query)+")?(?:#"+l.fragment+")?",u=d.domain?l.relativeRefCapture:l.relativeRef;if(d.relativeOnly)return m.wrap(u+c);let h="";if(d.scheme){a(d.scheme instanceof RegExp||typeof d.scheme=="string"||Array.isArray(d.scheme),"scheme must be a RegExp, String, or Array");const g=[].concat(d.scheme);a(g.length>=1,"scheme must have at least 1 scheme specified");const y=[];for(let v=0;v<g.length;++v){const _=g[v];a(_ instanceof RegExp||typeof _=="string","scheme at position "+v+" must be a RegExp or String"),_ instanceof RegExp?y.push(_.source.toString()):(a(l.schemeRegex.test(_),"scheme at position "+v+" must be a valid scheme"),y.push(p(_)))}h=y.join("|")}const f="(?:"+(h?"(?:"+h+")":l.scheme)+":"+(d.domain?l.hierPartCapture:l.hierPart)+")",b=d.allowRelative?"(?:"+f+"|"+u+")":f;return m.wrap(b+c,h)},m.wrap=function(d,l){return{raw:d=`(?=.)(?!https?:/(?:$|[^/]))(?!https?:///)(?!https?:[^/])${d}`,regex:new RegExp(`^${d}$`),scheme:l}},m.uriRegex=m.createRegex({}),n.regex=function(d={}){return d.scheme||d.allowRelative||d.relativeOnly||d.allowQuerySquareBrackets||d.domain?m.createRegex(d):m.uriRegex}},1447:(r,n)=>{const o={operators:["!","^","*","/","%","+","-","<","<=",">",">=","==","!=","&&","||","??"],operatorCharacters:["!","^","*","/","%","+","-","<","=",">","&","|","?"],operatorsOrder:[["^"],["*","/","%"],["+","-"],["<","<=",">",">="],["==","!="],["&&"],["||","??"]],operatorsPrefix:["!","n"],literals:{'"':'"',"`":"`","'":"'","[":"]"},numberRx:/^(?:[0-9]*(\.[0-9]*)?){1}$/,tokenRx:/^[\w\$\#\.\@\:\{\}]+$/,symbol:Symbol("formula"),settings:Symbol("settings")};n.Parser=class{constructor(a,p={}){if(!p[o.settings]&&p.constants)for(const m in p.constants){const d=p.constants[m];if(d!==null&&!["boolean","number","string"].includes(typeof d))throw new Error(`Formula constant ${m} contains invalid ${typeof d} value type`)}this.settings=p[o.settings]?p:Object.assign({[o.settings]:!0,constants:{},functions:{}},p),this.single=null,this._parts=null,this._parse(a)}_parse(a){let p=[],m="",d=0,l=!1;const c=h=>{if(d)throw new Error("Formula missing closing parenthesis");const f=p.length?p[p.length-1]:null;if(l||m||h){if(f&&f.type==="reference"&&h===")")return f.type="function",f.value=this._subFormula(m,f.value),void(m="");if(h===")"){const b=new n.Parser(m,this.settings);p.push({type:"segment",value:b})}else if(l){if(l==="]")return p.push({type:"reference",value:m}),void(m="");p.push({type:"literal",value:m})}else if(o.operatorCharacters.includes(m))f&&f.type==="operator"&&o.operators.includes(f.value+m)?f.value+=m:p.push({type:"operator",value:m});else if(m.match(o.numberRx))p.push({type:"constant",value:parseFloat(m)});else if(this.settings.constants[m]!==void 0)p.push({type:"constant",value:this.settings.constants[m]});else{if(!m.match(o.tokenRx))throw new Error(`Formula contains invalid token: ${m}`);p.push({type:"reference",value:m})}m=""}};for(const h of a)l?h===l?(c(),l=!1):m+=h:d?h==="("?(m+=h,++d):h===")"?(--d,d?m+=h:c(h)):m+=h:h in o.literals?l=o.literals[h]:h==="("?(c(),++d):o.operatorCharacters.includes(h)?(c(),m=h,c()):h!==" "?m+=h:c();c(),p=p.map((h,f)=>h.type!=="operator"||h.value!=="-"||f&&p[f-1].type!=="operator"?h:{type:"operator",value:"n"});let u=!1;for(const h of p){if(h.type==="operator"){if(o.operatorsPrefix.includes(h.value))continue;if(!u)throw new Error("Formula contains an operator in invalid position");if(!o.operators.includes(h.value))throw new Error(`Formula contains an unknown operator ${h.value}`)}else if(u)throw new Error("Formula missing expected operator");u=!u}if(!u)throw new Error("Formula contains invalid trailing operator");p.length===1&&["reference","literal","constant"].includes(p[0].type)&&(this.single={type:p[0].type==="reference"?"reference":"value",value:p[0].value}),this._parts=p.map(h=>{if(h.type==="operator")return o.operatorsPrefix.includes(h.value)?h:h.value;if(h.type!=="reference")return h.value;if(this.settings.tokenRx&&!this.settings.tokenRx.test(h.value))throw new Error(`Formula contains invalid reference ${h.value}`);return this.settings.reference?this.settings.reference(h.value):o.reference(h.value)})}_subFormula(a,p){const m=this.settings.functions[p];if(typeof m!="function")throw new Error(`Formula contains unknown function ${p}`);let d=[];if(a){let l="",c=0,u=!1;const h=()=>{if(!l)throw new Error(`Formula contains function ${p} with invalid arguments ${a}`);d.push(l),l=""};for(let f=0;f<a.length;++f){const b=a[f];u?(l+=b,b===u&&(u=!1)):b in o.literals&&!c?(l+=b,u=o.literals[b]):b!==","||c?(l+=b,b==="("?++c:b===")"&&--c):h()}h()}return d=d.map(l=>new n.Parser(l,this.settings)),function(l){const c=[];for(const u of d)c.push(u.evaluate(l));return m.call(l,...c)}}evaluate(a){const p=this._parts.slice();for(let m=p.length-2;m>=0;--m){const d=p[m];if(d&&d.type==="operator"){const l=p[m+1];p.splice(m+1,1);const c=o.evaluate(l,a);p[m]=o.single(d.value,c)}}return o.operatorsOrder.forEach(m=>{for(let d=1;d<p.length-1;)if(m.includes(p[d])){const l=p[d],c=o.evaluate(p[d-1],a),u=o.evaluate(p[d+1],a);p.splice(d,2);const h=o.calculate(l,c,u);p[d-1]=h===0?0:h}else d+=2}),o.evaluate(p[0],a)}},n.Parser.prototype[o.symbol]=!0,o.reference=function(a){return function(p){return p&&p[a]!==void 0?p[a]:null}},o.evaluate=function(a,p){return a===null?null:typeof a=="function"?a(p):a[o.symbol]?a.evaluate(p):a},o.single=function(a,p){if(a==="!")return!p;const m=-p;return m===0?0:m},o.calculate=function(a,p,m){if(a==="??")return o.exists(p)?p:m;if(typeof p=="string"||typeof m=="string"){if(a==="+")return(p=o.exists(p)?p:"")+(o.exists(m)?m:"")}else switch(a){case"^":return Math.pow(p,m);case"*":return p*m;case"/":return p/m;case"%":return p%m;case"+":return p+m;case"-":return p-m}switch(a){case"<":return p<m;case"<=":return p<=m;case">":return p>m;case">=":return p>=m;case"==":return p===m;case"!=":return p!==m;case"&&":return p&&m;case"||":return p||m}return null},o.exists=function(a){return a!=null}},9926:()=>{},5688:()=>{},9708:()=>{},1152:()=>{},443:()=>{},9848:()=>{},5934:r=>{r.exports=JSON.parse('{"version":"17.13.3"}')}},i={},function r(n){var o=i[n];if(o!==void 0)return o.exports;var a=i[n]={exports:{}};return t[n](a,a.exports,r),a.exports}(5107);var t,i})})(Js);var Ha=Js.exports;const N=Qs(Ha);var Na=Object.defineProperty,Ua=(s,e,t)=>e in s?Na(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,gt=(s,e,t)=>Ua(s,typeof e!="symbol"?e+"":e,t),be={DEFAULTS:{width:800,height:400,pixelRatio:2,fontFamily:"Roboto",fontSize:48,color:"#000000",textAlign:"left"},LIMITS:{minWidth:1,maxWidth:4096,minHeight:1,maxHeight:4096,minFontSize:1,maxFontSize:512,minDuration:.1,maxDuration:120,maxTextLength:1e4},ANIMATION_TYPES:["typewriter","fadeIn","slideIn","shift","ascend","movingLetters"]},Vt=/^#[A-Fa-f0-9]{6}$/,ja=N.object({type:N.string().valid("linear","radial").default("linear"),angle:N.number().min(0).max(360).default(0),stops:N.array().items(N.object({offset:N.number().min(0).max(1).required(),color:N.string().pattern(Vt).required()}).unknown(!1)).min(2).required()}).unknown(!1),Va=N.object({offsetX:N.number().default(0),offsetY:N.number().default(0),blur:N.number().min(0).default(0),color:N.string().pattern(Vt).default("#000000"),opacity:N.number().min(0).max(1).default(.5)}).unknown(!1),Wa=N.object({width:N.number().min(0).default(0),color:N.string().pattern(Vt).default("#000000"),opacity:N.number().min(0).max(1).default(1)}).unknown(!1),Ga=N.object({family:N.string().default(be.DEFAULTS.fontFamily),size:N.number().min(be.LIMITS.minFontSize).max(be.LIMITS.maxFontSize).default(be.DEFAULTS.fontSize),weight:N.alternatives().try(N.string(),N.number()).default("400"),style:N.string().valid("normal","italic","oblique").default("normal"),color:N.string().pattern(Vt).default(be.DEFAULTS.color),opacity:N.number().min(0).max(1).default(1)}).unknown(!1),Za=N.object({letterSpacing:N.number().default(0),lineHeight:N.number().min(0).max(10).default(1.2),textTransform:N.string().valid("none","uppercase","lowercase","capitalize").default("none"),textDecoration:N.string().valid("none","underline","line-through").default("none"),gradient:ja.optional()}).unknown(!1),Ka=N.object({horizontal:N.string().valid("left","center","right").default(be.DEFAULTS.textAlign),vertical:N.string().valid("top","middle","bottom").default("middle")}).unknown(!1),qa=N.object({preset:N.string().valid(...be.ANIMATION_TYPES),speed:N.number().min(.1).max(10).default(1),duration:N.number().min(be.LIMITS.minDuration).max(be.LIMITS.maxDuration).optional(),style:N.string().valid("character","word").optional().when("preset",{is:N.valid("typewriter","shift"),then:N.optional(),otherwise:N.forbidden()}),direction:N.string().optional().when("preset",{switch:[{is:"ascend",then:N.valid("up","down")},{is:"shift",then:N.valid("left","right","up","down")},{is:"slideIn",then:N.valid("left","right","up","down")},{is:"movingLetters",then:N.valid("left","right","up","down")}],otherwise:N.forbidden()})}).unknown(!1),Xa=N.object({color:N.string().pattern(Vt).optional(),opacity:N.number().min(0).max(1).default(1),borderRadius:N.number().min(0).default(0)}).unknown(!1),Ya=N.object({src:N.string().uri().required(),family:N.string().required(),weight:N.alternatives().try(N.string(),N.number()).optional(),style:N.string().optional(),originalFamily:N.string().optional()}).unknown(!1),Qa=N.object({type:N.string().valid("rich-text").required(),text:N.string().allow("").max(be.LIMITS.maxTextLength).default(""),width:N.number().min(be.LIMITS.minWidth).max(be.LIMITS.maxWidth).default(be.DEFAULTS.width).optional(),height:N.number().min(be.LIMITS.minHeight).max(be.LIMITS.maxHeight).default(be.DEFAULTS.height).optional(),font:Ga.optional(),style:Za.optional(),stroke:Wa.optional(),shadow:Va.optional(),background:Xa.optional(),align:Ka.optional(),animation:qa.optional(),customFonts:N.array().items(Ya).optional(),cacheEnabled:N.boolean().default(!0),pixelRatio:N.number().min(1).max(3).default(be.DEFAULTS.pixelRatio)}).unknown(!1),pi=null;async function Ja(s){if(pi)return pi;try{const t=(await Promise.resolve().then(()=>Yh)).default;let i;if(typeof t=="function"?i=await t():t&&typeof t.then=="function"?i=await t:i=t,!i||typeof i.createBuffer!="function"||typeof i.createFont!="function")throw new Error("Failed to initialize HarfBuzz: unexpected export shape from 'harfbuzzjs'.");return pi=i,pi}catch(e){throw new Error(`Failed to initialize HarfBuzz: ${e instanceof Error?e.message:String(e)}`)}}var er=class Ps{constructor(e){gt(this,"hb"),gt(this,"faces",new Map),gt(this,"fonts",new Map),gt(this,"blobs",new Map),gt(this,"wasmBaseURL"),gt(this,"initPromise"),this.wasmBaseURL=e}static setFallbackLoader(e){Ps.fallbackLoader=e}async init(){if(this.initPromise){await this.initPromise;return}if(!this.hb){this.initPromise=this._doInit();try{await this.initPromise}catch(e){throw new Error(`Failed to initialize FontRegistry: ${e instanceof Error?e.message:String(e)}`)}}}async _doInit(){try{this.hb=await Ja(this.wasmBaseURL)}catch(e){throw this.initPromise=void 0,e}}async getHB(){if(!this.hb)try{await this.init()}catch(e){throw new Error(`Failed to get HarfBuzz instance: ${e instanceof Error?e.message:String(e)}`)}return this.hb}key(e){return`${e.family}__${e.weight??"400"}__${e.style??"normal"}`}async registerFromBytes(e,t){try{this.hb||await this.init();const i=this.key(t);if(this.fonts.has(i))return;const r=this.hb.createBlob(e),n=this.hb.createFace(r,0),o=this.hb.createFont(n),a=n.upem||1e3;o.setScale(a,a),this.blobs.set(i,r),this.faces.set(i,n),this.fonts.set(i,o)}catch(i){throw new Error(`Failed to register font "${t.family}": ${i instanceof Error?i.message:String(i)}`)}}async tryFallbackInstall(e){const t=Ps.fallbackLoader;if(!t)return!1;try{const i=await t({family:e.family,weight:e.weight??"400",style:e.style??"normal"});return i?(await this.registerFromBytes(i,{family:e.family,weight:e.weight??"400",style:e.style??"normal"}),!0):!1}catch{return!1}}async getFont(e){try{this.hb||await this.init();const t=this.key(e);let i=this.fonts.get(t);if(i||(i=await this.tryFallbackInstall(e)?this.fonts.get(t):void 0),!i)throw new Error(`Font not registered for ${t}`);return i}catch(t){throw t instanceof Error&&t.message.includes("Font not registered")?t:new Error(`Failed to get font "${e.family}": ${t instanceof Error?t.message:String(t)}`)}}async getFace(e){try{this.hb||await this.init();const t=this.key(e);let i=this.faces.get(t);return i||(i=await this.tryFallbackInstall(e)?this.faces.get(t):void 0),i}catch(t){throw new Error(`Failed to get face for "${e.family}": ${t instanceof Error?t.message:String(t)}`)}}async getUnitsPerEm(e){try{return(await this.getFace(e))?.upem||1e3}catch(t){throw new Error(`Failed to get units per em for "${e.family}": ${t instanceof Error?t.message:String(t)}`)}}async glyphPath(e,t){try{const r=(await this.getFont(e)).glyphToPath(t);return r&&r!==""?r:"M 0 0"}catch(i){throw new Error(`Failed to get glyph path for glyph ${t} in font "${e.family}": ${i instanceof Error?i.message:String(i)}`)}}destroy(){try{for(const[,e]of this.fonts)try{e.destroy()}catch(t){console.error(`Error destroying font: ${t instanceof Error?t.message:String(t)}`)}for(const[,e]of this.faces)try{e.destroy()}catch(t){console.error(`Error destroying face: ${t instanceof Error?t.message:String(t)}`)}for(const[,e]of this.blobs)try{e.destroy()}catch(t){console.error(`Error destroying blob: ${t instanceof Error?t.message:String(t)}`)}this.fonts.clear(),this.faces.clear(),this.blobs.clear(),this.hb=void 0,this.initPromise=void 0}catch(e){console.error(`Error during FontRegistry cleanup: ${e instanceof Error?e.message:String(e)}`)}}};gt(er,"fallbackLoader");var tr=er,eo=class{constructor(s){this.fonts=s}transformText(s,e){switch(e){case"uppercase":return s.toUpperCase();case"lowercase":return s.toLowerCase();case"capitalize":return s.replace(/\b\w/g,t=>t.toUpperCase());default:return s}}async shapeFull(s,e){try{const t=await this.fonts.getHB(),i=t.createBuffer();try{i.addText(s),i.guessSegmentProperties();const r=await this.fonts.getFont(e),o=(await this.fonts.getFace(e))?.upem||1e3;return r.setScale(o,o),t.shape(r,i),i.json()}finally{try{i.destroy()}catch(r){console.error(`Error destroying HarfBuzz buffer: ${r instanceof Error?r.message:String(r)}`)}}}catch(t){throw new Error(`Failed to shape text with font "${e.family}": ${t instanceof Error?t.message:String(t)}`)}}async layout(s){try{const{textTransform:e,desc:t,fontSize:i,letterSpacing:r,width:n}=s,o=this.transformText(s.text,e);if(!o||o.length===0)return[];let a;try{a=await this.shapeFull(o,t)}catch(g){throw new Error(`Text shaping failed: ${g instanceof Error?g.message:String(g)}`)}let p;try{p=(await this.fonts.getFace(t))?.upem||1e3}catch(g){throw new Error(`Failed to get font metrics: ${g instanceof Error?g.message:String(g)}`)}const m=i/p,d=a.map(g=>{const y=g.cl;let v;return y>=0&&y<o.length&&(v=o[y]),{id:g.g,xAdvance:g.ax*m+r,xOffset:g.dx*m,yOffset:-g.dy*m,cluster:g.cl,char:v}}),l=[];let c=[],u=0;const h=new Set;for(let g=0;g<o.length;g++)o[g]===" "&&h.add(g);let f=-1;for(let g=0;g<d.length;g++){const y=d[g],v=y.xAdvance;if(y.char===`
183
+ `){c.length>0&&l.push({glyphs:c,width:u,y:0}),c=[],u=0,f=g;continue}if(u+v>n&&c.length>0){if(f>-1){const _=f-(g-c.length)+1,C=c.splice(_),S=c.reduce((T,w)=>T+w.xAdvance,0);l.push({glyphs:c,width:S,y:0}),c=C,u=C.reduce((T,w)=>T+w.xAdvance,0)}else l.push({glyphs:c,width:u,y:0}),c=[],u=0;f=-1}c.push(y),u+=v,h.has(y.cluster)&&(f=g)}c.length>0&&l.push({glyphs:c,width:u,y:0});const b=s.lineHeight*i;for(let g=0;g<l.length;g++)l[g].y=(g+1)*b;return l}catch(e){throw e instanceof Error?e:new Error(`Layout failed: ${String(e)}`)}}};function to(s,e){return s.type==="linear"?{kind:"linear",angle:s.angle,stops:s.stops,opacity:e}:{kind:"radial",stops:s.stops,opacity:e}}function io(s,e){const t=Math.max(1,Math.round(e.fontSize*.05));let i=e.baselineY+Math.round(e.fontSize*.1);return s==="line-through"&&(i=e.baselineY-Math.round(e.fontSize*.3)),{x1:e.xStart,x2:e.xStart+e.lineWidth,y:i,width:t}}async function so(s){const e=[];if(e.push({op:"BeginFrame",width:s.canvas.width,height:s.canvas.height,pixelRatio:s.canvas.pixelRatio,clear:!0,bg:s.background?{color:s.background.color,opacity:s.background.opacity,radius:s.background.borderRadius}:void 0}),s.lines.length===0)return e;const t=Math.max(1,await s.getUnitsPerEm()),i=s.font.size/t,r=s.lines[s.lines.length-1].y;let n;switch(s.align.vertical){case"top":n=s.font.size;break;case"bottom":n=s.textRect.height-r+s.font.size;break;case"middle":default:n=(s.textRect.height-r)/2+s.font.size;break}const o=s.style.gradient?to(s.style.gradient,1):{kind:"solid",color:s.font.color,opacity:s.font.opacity},a=s.style.gradient?s.style.gradient.stops[s.style.gradient.stops.length-1]?.color??s.font.color:s.font.color;let p=1/0,m=1/0,d=-1/0,l=-1/0;for(const c of s.lines){let u;switch(s.align.horizontal){case"left":u=0;break;case"right":u=s.textRect.width-c.width;break;case"center":default:u=(s.textRect.width-c.width)/2;break}let h=u;const f=n+c.y-s.font.size;for(const b of c.glyphs){const g=await s.glyphPathProvider(b.id);if(!g||g==="M 0 0"){h+=b.xAdvance;continue}const y=h+b.xOffset,v=f+b.yOffset,_=no(g),C=y+i*_.x,S=y+i*(_.x+_.w),T=v-i*(_.y+_.h),w=v-i*_.y;C<p&&(p=C),T<m&&(m=T),S>d&&(d=S),w>l&&(l=w),s.shadow&&s.shadow.blur>0&&e.push({isShadow:!0,op:"FillPath",path:g,x:y+s.shadow.offsetX,y:v+s.shadow.offsetY,scale:i,fill:{kind:"solid",color:s.shadow.color,opacity:s.shadow.opacity}}),s.stroke&&s.stroke.width>0&&e.push({op:"StrokePath",path:g,x:y,y:v,scale:i,width:s.stroke.width,color:s.stroke.color,opacity:s.stroke.opacity}),e.push({op:"FillPath",path:g,x:y,y:v,scale:i,fill:o}),h+=b.xAdvance}if(s.style.textDecoration!=="none"){const b=io(s.style.textDecoration,{baselineY:f,fontSize:s.font.size,lineWidth:c.width,xStart:u});e.push({op:"DecorationLine",from:{x:b.x1,y:b.y},to:{x:b.x2,y:b.y},width:b.width,color:a,opacity:s.font.opacity})}}if(p!==1/0){const c={x:p,y:m,w:Math.max(1,d-p),h:Math.max(1,l-m)};for(const u of e)u.op==="FillPath"&&!u.isShadow&&(u.gradientBBox=c)}return e}function ro(s){return s.match(/[MLCQZ]|-?\d*\.?\d+(?:e[-+]?\d+)?/gi)??[]}function no(s){const e=ro(s);let t=0,i=1/0,r=1/0,n=-1/0,o=-1/0;const a=(p,m)=>{p<i&&(i=p),m<r&&(r=m),p>n&&(n=p),m>o&&(o=m)};for(;t<e.length;)switch(e[t++]){case"M":case"L":{const m=parseFloat(e[t++]),d=parseFloat(e[t++]);a(m,d);break}case"C":{const m=parseFloat(e[t++]),d=parseFloat(e[t++]),l=parseFloat(e[t++]),c=parseFloat(e[t++]),u=parseFloat(e[t++]),h=parseFloat(e[t++]);a(m,d),a(l,c),a(u,h);break}case"Q":{const m=parseFloat(e[t++]),d=parseFloat(e[t++]),l=parseFloat(e[t++]),c=parseFloat(e[t++]);a(m,d),a(l,c);break}}return i===1/0?{x:0,y:0,w:0,h:0}:{x:i,y:r,w:n-i,h:o-r}}var Vi=.999;function ao(s,e,t){if(!t.anim||!t.anim.preset)return s;const{preset:i}=t.anim,r=e.reduce((a,p)=>a+p.glyphs.length,0),n=t.anim.duration??Math.max(.3,r/30/t.anim.speed),o=Math.max(0,Math.min(1,t.t/n));switch(i){case"typewriter":return lo(s,e,o,t.anim.style,t.fontSize,t.t);case"fadeIn":return uo(s,o);case"slideIn":return fo(s,o,t.anim.direction??"left",t.fontSize);case"shift":return ho(s,e,o,t.anim.direction??"left",t.fontSize,t.anim.style,n);case"ascend":return co(s,e,o,t.anim.direction??"up",t.fontSize,n);case"movingLetters":return po(s,o,t.anim.direction??"up",t.fontSize);default:return s}}var mi=s=>s.op==="FillPath"&&s.isShadow===!0,ir=s=>s.op==="FillPath"&&!s.isShadow;function oo(s){for(const e of s)if(e.op==="FillPath"){const t=e.fill;if(t?.kind==="solid")return t.color;if((t?.kind==="linear"||t?.kind==="radial")&&Array.isArray(t.stops)&&t.stops.length)return t.stops[t.stops.length-1].color||"#000000"}return"#000000"}function lo(s,e,t,i,r,n,o){if(i==="word"){const p=Wi(e),m=p.length,d=Math.floor(t*m);if(d===0)return s.filter(h=>h.op==="BeginFrame");let l=0;for(let h=0;h<Math.min(d,p.length);h++)l+=p[h].glyphCount;const c=sr(s,l),u=t>=Vi?c:c.filter(h=>h.op!=="DecorationLine");return t<1&&l>0?rr(u,l,r,n):u}else{const p=e.reduce((c,u)=>c+u.glyphs.length,0),m=Math.floor(t*p);if(m===0)return s.filter(c=>c.op==="BeginFrame");const d=sr(s,m),l=t>=Vi?d:d.filter(c=>c.op!=="DecorationLine");return t<1&&m>0?rr(l,m,r,n):l}}function co(s,e,t,i,r,n){const o=Wi(e),a=o.length;if(a===0)return s;const p=[];let m=0;for(const d of s)if(d.op==="BeginFrame"){p.push(d);break}for(const d of s)if(d.op==="FillPath"||d.op==="StrokePath"){let l=-1,c=0;for(let u=0;u<o.length;u++){const h=o[u].glyphCount;if(m>=c&&m<c+h){l=u;break}c+=h}if(l>=0){const u=l/Math.max(1,a)*(n/n),h=Math.min(1,u+.3);if(t>=h)p.push(d);else if(t>u){const f=(t-u)/Math.max(1e-6,h-u),b=Gi(Math.min(1,f)),g=i==="up"?r*.4:-r*.4,y={...d,y:d.y+g*(1-b)};d.op==="FillPath"?y.fill.kind==="solid"?y.fill={...y.fill,opacity:y.fill.opacity*b}:y.fill={...y.fill,opacity:(y.fill.opacity??1)*b}:y.opacity=y.opacity*b,p.push(y)}}ir(d)&&m++}else d.op==="DecorationLine"&&t>=Vi&&p.push(d);return p}function ho(s,e,t,i,r,n,o){const a=n==="word",m={left:{x:r*.6,y:0},right:{x:-r*.6,y:0},up:{x:0,y:r*.6},down:{x:0,y:-r*.6}}[i],d=a?Wi(e):[],l=e.reduce((v,_)=>v+_.glyphs.length,0),c=a?d.length:l;if(c===0)return s;const u=[];for(const v of s)if(v.op==="BeginFrame"){u.push(v);break}const h=.3,b=o*.7/Math.max(1,c-1),g=v=>{const _=v*b,C=_/o,S=Math.min(1,(_+h)/o);return{startF:C,endF:S}};let y=0;for(const v of s){if(v.op!=="FillPath"&&v.op!=="StrokePath"){v.op==="DecorationLine"&&t>.8&&u.push(v);continue}let _;if(!a)_=y;else{let T=-1,w=0;for(let x=0;x<d.length;x++){const k=d[x].glyphCount;if(y>=w&&y<w+k){T=x;break}w+=k}_=Math.max(0,T)}const{startF:C,endF:S}=g(_);if(t<=C){const T={...v,x:v.x+m.x,y:v.y+m.y};v.op==="FillPath"?T.fill.kind==="solid"?T.fill={...T.fill,opacity:0}:T.fill={...T.fill,opacity:0}:T.opacity=0,u.push(T)}else if(t>=S)u.push(v);else{const T=(t-C)/Math.max(1e-6,S-C),w=Gi(Math.min(1,T)),x=m.x*(1-w),k=m.y*(1-w),E={...v,x:v.x+x,y:v.y+k};if(v.op==="FillPath"){const P=E.fill.kind==="solid"?E.fill.opacity:E.fill.opacity??1;E.fill.kind==="solid"?E.fill={...E.fill,opacity:P*w}:E.fill={...E.fill,opacity:P*w}}else E.opacity=E.opacity*w;u.push(E)}ir(v)&&y++}return u}function uo(s,e){const t=nr(e),i=.95+.05*t;return go(s,t,i)}function fo(s,e,t,i){const r=Gi(e),n=vo(1-r,t,i*2),o=nr(e);return yo(s,n.dx,n.dy,o)}function po(s,e,t,i){const r=i*.3;return bo(s,t,r,e)}function Wi(s){const e=[];let t=0;for(let i=0;i<s.length;i++){const r=s[i],n=mo(r);for(const o of n)o.length>0&&e.push({startGlyph:t,glyphCount:o.length,lineIndex:i}),t+=o.length}return e}function mo(s){const e=[];let t=[];for(const i of s.glyphs)i.char===" "||i.char===" "||i.char===`
184
+ `?t.length&&(e.push([...t]),t=[]):t.push(i);return t.length&&e.push(t),e}function sr(s,e){const t=[];let i=0,r=!1;for(const n of s){if(n.op==="BeginFrame"){t.push(n);continue}if(n.op==="FillPath"&&!mi(n)){i<e&&(t.push(n),r=!0),i++;continue}if(n.op==="StrokePath"){i<e&&t.push(n);continue}if(n.op==="FillPath"&&mi(n)){i<e&&t.push(n);continue}if(n.op==="DecorationLine"&&r){t.push(n);continue}}return t}function rr(s,e,t,i){if(!(Math.floor(i*2*2)%2===0)||e===0)return s;let o=null,a=0;for(const p of s)if(p.op==="FillPath"&&!mi(p)&&(a++,a===e)){o=p;break}if(o&&o.op==="FillPath"){const p=oo(s),m=o.x+t*.5,d=o.y,l={op:"DecorationLine",from:{x:m,y:d-t*.7},to:{x:m,y:d+t*.1},width:Math.max(2,t/25),color:p,opacity:1};return[...s,l]}return s}function go(s,e,t){let i=0,r=0,n=0;return s.forEach(o=>{o.op==="FillPath"&&(i+=o.x,r+=o.y,n++)}),n>0&&(i/=n,r/=n),s.map(o=>{if(o.op==="FillPath"){const a={...o};if(a.fill.kind==="solid"?a.fill={...a.fill,opacity:a.fill.opacity*e}:a.fill={...a.fill,opacity:(a.fill.opacity??1)*e},t!==1&&n>0){const p=o.x-i,m=o.y-r;a.x=i+p*t,a.y=r+m*t}return a}if(o.op==="StrokePath"){const a={...o,opacity:o.opacity*e};if(t!==1&&n>0){const p=o.x-i,m=o.y-r;a.x=i+p*t,a.y=r+m*t}return a}return o.op==="DecorationLine"?{...o,opacity:o.opacity*e}:o})}function yo(s,e,t,i=1){return s.map(r=>{if(r.op==="FillPath"){const n={...r,x:r.x+e,y:r.y+t};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 r.op==="StrokePath"?{...r,x:r.x+e,y:r.y+t,opacity:r.opacity*i}:r.op==="DecorationLine"?{...r,from:{x:r.from.x+e,y:r.from.y+t},to:{x:r.to.x+e,y:r.to.y+t},opacity:r.opacity*i}:r})}function bo(s,e,t,i){let r=0;return s.map(n=>{if(n.op==="FillPath"||n.op==="StrokePath"){const o=Math.sin(r/5*Math.PI+i*Math.PI*4),a=e==="left"||e==="right"?o*t*(e==="left"?-1:1):0,p=e==="up"||e==="down"?o*t*(e==="up"?-1:1):0,m=Math.min(1,i*2);if(n.op==="FillPath"){mi(n)||r++;const d={...n,x:n.x+a,y:n.y+p};return d.fill.kind==="solid"?d.fill={...d.fill,opacity:d.fill.opacity*m}:d.fill={...d.fill,opacity:(d.fill.opacity??1)*m},d}return{...n,x:n.x+a,y:n.y+p,opacity:n.opacity*m}}return n})}function vo(s,e,t){const i=s*t;switch(e){case"left":return{dx:-i,dy:0};case"right":return{dx:i,dy:0};case"up":return{dx:0,dy:-i};case"down":return{dx:0,dy:i}}}function nr(s){return s*(2-s)}function Gi(s){return 1-Math.pow(1-s,3)}function Wt(s,e=1){const t=/^#?([a-f0-9]{6})$/i.exec(s);if(!t)throw new Error(`Invalid color ${s}`);const i=parseInt(t[1],16),r=i>>16&255,n=i>>8&255,o=i&255;return{r,g:n,b:o,a:e}}function wo(s){const e=s.getContext("2d");if(!e)throw new Error("2D context unavailable");return{async render(t){const i=Co(t);for(const r of t){if(r.op==="BeginFrame"){const n=r.pixelRatio,o=r.width,a=r.height;if("width"in s&&"height"in s&&(s.width=Math.floor(o*n),s.height=Math.floor(a*n)),"style"in s&&(s.style.width=`${o}px`,s.style.height=`${a}px`),e.setTransform(n,0,0,n,0,0),r.clear&&e.clearRect(0,0,o,a),r.bg){const{color:p,opacity:m,radius:d}=r.bg;if(p){const l=Wt(p,m);e.fillStyle=`rgba(${l.r},${l.g},${l.b},${l.a})`,d&&d>0?(_o(e,0,0,o,a,d),e.fill()):e.fillRect(0,0,o,a)}}continue}if(r.op==="FillPath"){const n=r,o=new Path2D(n.path);e.save(),e.translate(n.x,n.y);const a=n.scale??1;e.scale(a,-a);const p=n.gradientBBox??i,m=xo(e,n.fill,p);e.fillStyle=m,e.fill(o),e.restore();continue}if(r.op==="StrokePath"){const n=r,o=new Path2D(n.path);e.save(),e.translate(n.x,n.y);const a=n.scale??1;e.scale(a,-a);const p=1/Math.abs(a),m=Wt(n.color,n.opacity);e.strokeStyle=`rgba(${m.r},${m.g},${m.b},${m.a})`,e.lineWidth=n.width*p,e.lineJoin="round",e.lineCap="round",e.stroke(o),e.restore();continue}if(r.op==="DecorationLine"){e.save();const n=Wt(r.color,r.opacity);e.strokeStyle=`rgba(${n.r},${n.g},${n.b},${n.a})`,e.lineWidth=r.width,e.beginPath(),e.moveTo(r.from.x,r.from.y),e.lineTo(r.to.x,r.to.y),e.stroke(),e.restore();continue}}}}}function _o(s,e,t,i,r,n){const o=new Path2D;o.moveTo(e+n,t),o.arcTo(e+i,t,e+i,t+r,n),o.arcTo(e+i,t+r,e,t+r,n),o.arcTo(e,t+r,e,t,n),o.arcTo(e,t,e+i,t,n),o.closePath(),s.save(),s.fill(o),s.restore()}function xo(s,e,t){if(e.kind==="solid"){const a=Wt(e.color,e.opacity);return`rgba(${a.r},${a.g},${a.b},${a.a})`}const i=t.x+t.w/2,r=t.y+t.h/2,n=Math.max(t.w,t.h)/2,o=a=>{const p=e.kind==="linear"||e.kind==="radial"?e.opacity:1,m=e.kind==="linear"||e.kind==="radial"?e.stops:[];for(const d of m){const l=Wt(d.color,p);a.addColorStop(d.offset,`rgba(${l.r},${l.g},${l.b},${l.a})`)}return a};if(e.kind==="linear"){const a=e.angle*Math.PI/180,p=i+Math.cos(a+Math.PI)*n,m=r+Math.sin(a+Math.PI)*n,d=i+Math.cos(a)*n,l=r+Math.sin(a)*n;return o(s.createLinearGradient(p,m,d,l))}else return o(s.createRadialGradient(i,r,0,i,r,n))}function Co(s){let e=1/0,t=1/0,i=-1/0,r=-1/0;for(const n of s){if(n.op!=="FillPath")continue;const o=n;if(o.isShadow)continue;const a=ko(o.path),p=o.scale??1,m=o.x+p*a.x,d=o.x+p*(a.x+a.w),l=o.y-p*(a.y+a.h),c=o.y-p*a.y;m<e&&(e=m),l<t&&(t=l),d>i&&(i=d),c>r&&(r=c)}return e===1/0?{x:0,y:0,w:1,h:1}:{x:e,y:t,w:Math.max(1,i-e),h:Math.max(1,r-t)}}function ko(s){const e=To(s);let t=0,i=1/0,r=1/0,n=-1/0,o=-1/0;const a=(p,m)=>{p<i&&(i=p),m<r&&(r=m),p>n&&(n=p),m>o&&(o=m)};for(;t<e.length;)switch(e[t++]){case"M":case"L":{const m=parseFloat(e[t++]),d=parseFloat(e[t++]);a(m,d);break}case"C":{const m=parseFloat(e[t++]),d=parseFloat(e[t++]),l=parseFloat(e[t++]),c=parseFloat(e[t++]),u=parseFloat(e[t++]),h=parseFloat(e[t++]);a(m,d),a(l,c),a(u,h);break}case"Q":{const m=parseFloat(e[t++]),d=parseFloat(e[t++]),l=parseFloat(e[t++]),c=parseFloat(e[t++]);a(m,d),a(l,c);break}}return i===1/0?{x:0,y:0,w:0,h:0}:{x:i,y:r,w:n-i,h:o-r}}function To(s){return s.match(/[MLCQZ]|-?\d*\.?\d+(?:e[-+]?\d+)?/gi)??[]}async function Gt(s){try{const e=await fetch(s);if(!e.ok)throw new Error(`Failed to fetch ${s}: ${e.status} ${e.statusText}`);try{return await e.arrayBuffer()}catch(t){throw new Error(`Failed to read response body as ArrayBuffer from ${s}: ${t instanceof Error?t.message:String(t)}`)}}catch(e){throw e instanceof Error?e.message.includes("Failed to fetch")||e.message.includes("Failed to read")?e:new Error(`Failed to fetch ${s}: ${e.message}`):new Error(`Failed to fetch ${s}: ${String(e)}`)}}var ar="https://fonts.gstatic.com/s/roboto/v30/KFOmCnqEu92Fr1Mu4mxP.ttf";async function So(s={}){const e=s.width??be.DEFAULTS.width,t=s.height??be.DEFAULTS.height,i=s.pixelRatio??be.DEFAULTS.pixelRatio,r=s.wasmBaseURL,n=new tr(r),o=new eo(n);try{tr.setFallbackLoader(async p=>{const m=(p.family??"Roboto").toLowerCase(),d=`${p.weight??"400"}`,l=p.style??"normal";if(m==="roboto"&&d==="400"&&l==="normal")return Gt(ar)}),await n.init()}catch(p){throw new Error(`Failed to initialize font registry: ${p instanceof Error?p.message:String(p)}`)}async function a(p){try{if(p.customFonts)for(const c of p.customFonts)try{const u=await Gt(c.src);await n.registerFromBytes(u,{family:c.family,weight:c.weight??"400",style:c.style??"normal"})}catch(u){throw new Error(`Failed to load custom font "${c.family}" from ${c.src}: ${u instanceof Error?u.message:String(u)}`)}const m=p.font??{family:"Roboto",weight:"400",style:"normal",size:48,color:"#000000",opacity:1},d={family:m.family,weight:`${m.weight}`,style:m.style};return await(async()=>{try{await n.getFace(d)}catch{if((m.family||"Roboto").toLowerCase()==="roboto"&&`${m.weight}`=="400"&&m.style==="normal"){const u=await Gt(ar);await n.registerFromBytes(u,{family:"Roboto",weight:"400",style:"normal"})}else throw new Error(`Font not registered for ${d.family}__${d.weight}__${d.style}`)}})(),m}catch(m){throw m instanceof Error?m:new Error(`Failed to ensure fonts: ${String(m)}`)}}return{validate(p){try{const{value:m,error:d}=Qa.validate(p,{abortEarly:!1,convert:!0});if(d)throw d;return{value:m}}catch(m){throw m instanceof Error?new Error(`Validation failed: ${m.message}`):new Error(`Validation failed: ${String(m)}`)}},async registerFontFromUrl(p,m){try{const d=await Gt(p);await n.registerFromBytes(d,m)}catch(d){throw new Error(`Failed to register font "${m.family}" from URL ${p}: ${d instanceof Error?d.message:String(d)}`)}},async registerFontFromFile(p,m){try{let d;if(typeof p=="string")try{d=await Gt(p)}catch(l){throw new Error(`Failed to fetch font from ${p}: ${l instanceof Error?l.message:String(l)}`)}else try{d=await p.arrayBuffer()}catch(l){throw new Error(`Failed to read Blob as ArrayBuffer: ${l instanceof Error?l.message:String(l)}`)}await n.registerFromBytes(d,m)}catch(d){throw d instanceof Error?d:new Error(`Failed to register font "${m.family}" from ${typeof p=="string"?p:"Blob"}: ${String(d)}`)}},async renderFrame(p,m){try{const d=await a(p),l={family:d.family,weight:`${d.weight}`,style:d.style};let c;try{c=await o.layout({text:p.text,width:p.width??e,letterSpacing:p.style?.letterSpacing??0,fontSize:d.size,lineHeight:p.style?.lineHeight??1.2,desc:l,textTransform:p.style?.textTransform??"none"})}catch(y){throw new Error(`Failed to layout text: ${y instanceof Error?y.message:String(y)}`)}const u={x:0,y:0,width:p.width??e,height:p.height??t},h=p.width??e,f=p.height??t,b=p.pixelRatio??i;let g;try{g=await so({canvas:{width:h,height:f,pixelRatio:b},textRect:u,lines:c,font:{family:d.family,size:d.size,weight:`${d.weight}`,style:d.style,color:d.color,opacity:d.opacity},style:{lineHeight:p.style?.lineHeight??1.2,textDecoration:p.style?.textDecoration??"none",gradient:p.style?.gradient},stroke:p.stroke,shadow:p.shadow,align:p.align??{horizontal:"center",vertical:"middle"},background:p.background,glyphPathProvider:y=>n.glyphPath(l,y),getUnitsPerEm:()=>n.getUnitsPerEm(l)})}catch(y){throw new Error(`Failed to build draw operations: ${y instanceof Error?y.message:String(y)}`)}try{return ao(g,c,{t:m,fontSize:d.size,anim:p.animation?{preset:p.animation.preset,speed:p.animation.speed,duration:p.animation.duration,style:p.animation.style,direction:p.animation.direction}:void 0})}catch(y){throw new Error(`Failed to apply animation: ${y instanceof Error?y.message:String(y)}`)}}catch(d){throw d instanceof Error?d:new Error(`Failed to render frame at time ${m}s: ${String(d)}`)}},createRenderer(p){try{return wo(p)}catch(m){throw new Error(`Failed to create renderer: ${m instanceof Error?m.message:String(m)}`)}},destroy(){try{n.destroy()}catch(p){console.error(`Error during cleanup: ${p instanceof Error?p.message:String(p)}`)}}}}const or=s=>{const t=(s.split("/").pop()||"").replace(/\.(ttf|otf|woff|woff2)$/i,""),i=t.replace(/-(Bold|Light|Regular|Italic|Medium|SemiBold|Black|Thin|ExtraLight|ExtraBold|Heavy)$/i,"");return{full:t,base:i}};class Eo extends we{textEngine=null;renderer=null;canvas=null;texture=null;sprite=null;lastRenderedTime=-1;cachedFrames=new Map;isRendering=!1;targetFPS=30;validatedAsset=null;createFontMapping(){const e=new Map;return e.set("Arapey","/assets/fonts/Arapey-Regular.ttf"),e.set("ClearSans","/assets/fonts/ClearSans-Regular.ttf"),e.set("Clear Sans","/assets/fonts/ClearSans-Regular.ttf"),e.set("DidactGothic","/assets/fonts/DidactGothic-Regular.ttf"),e.set("Didact Gothic","/assets/fonts/DidactGothic-Regular.ttf"),e.set("Montserrat","/assets/fonts/Montserrat-SemiBold.ttf"),e.set("MovLette","/assets/fonts/MovLette.ttf"),e.set("OpenSans","/assets/fonts/OpenSans-Bold.ttf"),e.set("Open Sans","/assets/fonts/OpenSans-Bold.ttf"),e.set("PermanentMarker","/assets/fonts/PermanentMarker-Regular.ttf"),e.set("Permanent Marker","/assets/fonts/PermanentMarker-Regular.ttf"),e.set("Roboto","/assets/fonts/Roboto-BlackItalic.ttf"),e.set("SueEllenFrancisco","/assets/fonts/SueEllenFrancisco.ttf"),e.set("Sue Ellen Francisco","/assets/fonts/SueEllenFrancisco.ttf"),e.set("UniNeue","/assets/fonts/UniNeue-Bold.otf"),e.set("Uni Neue","/assets/fonts/UniNeue-Bold.otf"),e.set("WorkSans","/assets/fonts/WorkSans-Light.ttf"),e.set("Work Sans","/assets/fonts/WorkSans-Light.ttf"),e}async load(){await super.load();const e=this.clipConfiguration.asset;try{const t=this.edit.getEdit();if(this.targetFPS=t?.output?.fps||30,e.width=e.width||this.edit.size.width,e.height=e.height||this.edit.size.height,e.pixelRatio=e.pixelRatio||2,e.cacheEnabled=e.cacheEnabled??!0,Array.isArray(t?.timeline?.fonts)&&t.timeline.fonts.length>0){const a=e.font?.family;if(a){const p=t.timeline.fonts?.find(m=>{const{full:d,base:l}=or(m.src),c=a.toLowerCase();return d.toLowerCase()===c||l.toLowerCase()===c});p&&(e.customFonts=[{src:p.src,family:a,weight:e.font?.weight?.toString()||"400",style:e.font?.style||"normal"}])}}const i=fi.safeParse(e);if(!i.success){console.error("Rich-text asset validation failed:",i.error),this.createFallbackText(e);return}this.textEngine=await So({width:e.width,height:e.height,pixelRatio:e.pixelRatio,fps:this.targetFPS});const{value:r}=this.textEngine.validate(e);this.validatedAsset=r;const n=this.createFontMapping();this.canvas=document.createElement("canvas"),this.canvas.width=e.width*e.pixelRatio,this.canvas.height=e.height*e.pixelRatio,this.renderer=this.textEngine.createRenderer(this.canvas);const o=t?.timeline?.fonts||[];if(o.length>0){const a=e.font?.family;if(a){const p=o.find(m=>{const{full:d,base:l}=or(m.src),c=a.toLowerCase();return d.toLowerCase()===c||l.toLowerCase()===c});if(p)try{const m={family:a,weight:e.font?.weight?.toString()||"400",style:e.font?.style||"normal"};await this.textEngine.registerFontFromUrl(p.src,m)}catch(m){console.warn(`Failed to load font ${a}:`,m)}}}else if(e.font?.family){const a=e.font.family,p=n.get(a);if(p)try{const m={family:e.font.family,weight:e.font.weight||"400",style:e.font.style||"normal"};await this.textEngine.registerFontFromFile(p,m)}catch(m){console.warn(`Failed to load local font: ${a}`,m)}else console.warn(`Font ${a} not found in local assets. Available fonts:`,Array.from(n.keys()))}await this.renderFrame(0),this.configureKeyframes()}catch(t){console.error("Failed to initialize rich text player:",t),this.cleanupResources(),this.createFallbackText(e)}}cleanupResources(){if(this.textEngine){try{this.textEngine.destroy()}catch(e){console.warn("Error destroying text engine:",e)}this.textEngine=null}this.renderer=null,this.canvas=null,this.validatedAsset=null}async renderFrame(e){if(!this.textEngine||!this.renderer||!this.canvas||!this.validatedAsset)return;const t=Math.floor(e*this.targetFPS);if(this.validatedAsset.cacheEnabled&&this.cachedFrames.has(t)){const i=this.cachedFrames.get(t);this.sprite&&this.sprite.texture!==i&&(this.sprite.texture=i),this.lastRenderedTime=e;return}try{const i=await this.textEngine.renderFrame(this.validatedAsset,e),r=this.canvas.getContext("2d");r&&r.clearRect(0,0,this.canvas.width,this.canvas.height),await this.renderer.render(i);const n=R.Texture.from(this.canvas);this.sprite?(this.texture&&!this.cachedFrames.has(t)&&this.texture.destroy(),this.sprite.texture=n):(this.sprite=new R.Sprite(n),this.sprite.scale.set(1/this.validatedAsset.pixelRatio),this.contentContainer.addChild(this.sprite)),this.texture=n,this.validatedAsset.cacheEnabled&&this.cachedFrames.size<150&&this.cachedFrames.set(t,n),this.lastRenderedTime=e}catch(i){console.error("Failed to render rich text frame:",i)}}createFallbackText(e){const t=new R.TextStyle({fontFamily:e.font?.family||"Arial",fontSize:e.font?.size||48,fill:e.font?.color||"#ffffff",align:e.align?.horizontal||"center",wordWrap:!0,wordWrapWidth:e.width||this.edit.size.width}),i=new R.Text(e.text,t),r=e.width||this.edit.size.width,n=e.height||this.edit.size.height;switch(e.align?.horizontal){case"left":i.anchor.set(0,.5),i.x=0;break;case"right":i.anchor.set(1,.5),i.x=r;break;default:i.anchor.set(.5,.5),i.x=r/2}switch(e.align?.vertical){case"top":i.anchor.set(i.anchor.x,0),i.y=0;break;case"bottom":i.anchor.set(i.anchor.x,1),i.y=n;break;default:i.anchor.set(i.anchor.x,.5),i.y=n/2}this.contentContainer.addChild(i)}renderFrameSafe(e){this.isRendering||(this.isRendering=!0,this.renderFrame(e).catch(t=>console.error("Failed to render rich text frame:",t)).finally(()=>{this.isRendering=!1}))}update(e,t){if(super.update(e,t),this.textEngine&&this.renderer&&!this.isRendering){const i=this.getCurrentTime()/1e3,o=1/(this.edit.getEdit()?.output?.fps||30);Math.abs(i-this.lastRenderedTime)>o&&this.renderFrameSafe(i)}}dispose(){super.dispose();for(const e of this.cachedFrames.values())e.destroy();this.cachedFrames.clear(),this.texture&&!this.cachedFrames.has(Math.floor(this.lastRenderedTime*this.targetFPS))&&this.texture.destroy(),this.texture=null,this.sprite&&(this.sprite.destroy(),this.sprite=null),this.canvas&&(this.canvas=null),this.textEngine&&(this.textEngine.destroy(),this.textEngine=null),this.renderer=null,this.validatedAsset=null}getSize(){const e=this.clipConfiguration.asset;return{width:e.width||this.edit.size.width,height:e.height||this.edit.size.height}}getFitScale(){return 1}updateTextContent(e){const t=this.clipConfiguration.asset;if(t.text=e,this.textEngine){const{value:i}=this.textEngine.validate(t);this.validatedAsset=i}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}}class Ao extends we{shape;shapeBackground;constructor(e,t){super(e,t),this.shape=null,this.shapeBackground=null}async load(){await super.load();const e=this.clipConfiguration.asset,t=new R.Graphics,i=e.width??this.edit.size.width,r=e.height??this.edit.size.height;t.fillStyle={color:"transparent"},t.rect(0,0,i,r),t.fill();const n=new R.Graphics;switch(e.shape){case"rectangle":{const o=e.rectangle,a=i/2-o.width/2,p=r/2-o.height/2;n.rect(a,p,o.width,o.height);break}case"circle":{const o=e.circle,a=i/2,p=r/2;n.circle(a,p,o.radius);break}case"line":{const o=e.line,a=i/2-o.length/2,p=r/2-o.thickness/2;n.rect(a,p,o.length,o.thickness);break}default:console.warn("Unsupported shape asset type.");break}if(n.fillStyle={color:e.fill?.color??"#ffffff",alpha:e.fill?.opacity??1},n.fill(),e.stroke){const o=new Fi({thickness:e.stroke.width,color:e.stroke.color});n.filters=[o]}this.shapeBackground=t,this.shape=n,this.contentContainer.addChild(t),t.addChild(n),this.configureKeyframes()}update(e,t){super.update(e,t)}draw(){super.draw()}dispose(){super.dispose(),this.shape?.destroy(),this.shape=null,this.shapeBackground?.destroy(),this.shapeBackground=null}getSize(){const e=this.clipConfiguration.asset;return{width:e.width??this.edit.size.width,height:e.height??this.edit.size.height}}getFitScale(){return 1}}class Zt{static DEFAULT_BLINK_INTERVAL_MS=500;static DEFAULT_CURSOR_WIDTH_PX=2;static DEFAULT_CURSOR_COLOR=16777215;cursor=null;parent;textElement;clipConfig;textPosition=0;pixelX=0;pixelY=0;currentLine=0;isBlinking=!1;blinkInterval=null;blinkIntervalMs=500;width=2;color=16777215;isVisible=!0;constructor(e,t,i,r){this.parent=e,this.textElement=t,this.clipConfig=i,this.width=r?.width??Zt.DEFAULT_CURSOR_WIDTH_PX,this.color=r?.color??Zt.DEFAULT_CURSOR_COLOR,this.blinkIntervalMs=r?.blinkInterval??Zt.DEFAULT_BLINK_INTERVAL_MS,this.textPosition=0,this.isBlinking=!1,this.isVisible=!0,this.blinkInterval=null,this.createCursor()}updatePosition(e){if(!this.cursor||!this.textElement){console.warn("TextCursor: Cannot update position, cursor not initialized");return}this.textPosition=this.validateTextPosition(e),this.calculateAndApplyPixelPosition()}setPosition(e,t){if(!this.cursor){console.warn("TextCursor: Cannot set position, cursor not initialized");return}this.pixelX=e,this.pixelY=t,this.updateGraphicsPosition()}show(){this.setVisible(!0)}hide(){this.setVisible(!1)}setVisible(e){this.isVisible=e,this.cursor&&!this.isBlinking&&(this.cursor.visible=e)}startBlinking(){if(!this.cursor){console.warn("TextCursor: Cannot start blinking, cursor not initialized");return}this.isBlinking||this.startBlinkingAnimation()}stopBlinking(){this.stopBlinkingAnimation()}setBlinkInterval(e){this.blinkIntervalMs=e,this.isBlinking&&(this.stopBlinking(),this.startBlinking())}dispose(){if(this.stopBlinkingAnimation(),this.cursor&&this.parent)try{this.parent.removeChild(this.cursor)}catch(e){console.warn("TextCursor: Error removing cursor from parent:",e)}if(this.cursor)try{this.cursor.destroy()}catch(e){console.warn("TextCursor: Error destroying cursor graphics:",e)}finally{this.cursor=null}this.textPosition=0,this.pixelX=0,this.pixelY=0,this.currentLine=0,this.isVisible=!0}createCursor(){if(!this.textElement)return;this.cursor=new R.Graphics,this.cursor.fillStyle={color:this.color};const e=this.textElement.style.fontSize;this.cursor.rect(0,0,this.width,e),this.cursor.fill(),this.parent.addChild(this.cursor),this.cursor.visible=this.isVisible}validateTextPosition(e){return this.textElement?Math.max(0,Math.min(e,this.textElement.text.length)):0}calculateAndApplyPixelPosition(){this.calculatePixelPositionFromText(),this.updateGraphicsPosition()}calculatePixelPositionFromText(){if(!this.textElement)return;const{text:e}=this.textElement,t=this.textElement.style,i=e.substring(0,this.textPosition),r=i.match(/\n/g);this.currentLine=r?r.length:0;const n=e.split(`
185
+ `),o=this.currentLine<n.length?n[this.currentLine]:"",a=i.lastIndexOf(`
186
+ `),p=a===-1?this.textPosition:this.textPosition-a-1,m=o.substring(0,p);let d;m.length>0&&m.endsWith(" ")?d=this.measureText(`${m}x`,t)-this.measureText("x",t):d=this.measureText(m,t);const l=t.lineHeight;this.pixelY=this.currentLine*l;const u=this.clipConfig.asset.alignment?.horizontal??"center";let h=d;if(u!=="left"){const f=this.measureText(o,t),b=this.textElement.width;let g=0;u==="center"?g=(b-f)/2:u==="right"&&(g=b-f),h=g+d}this.pixelX=h}updateGraphicsPosition(){this.cursor&&this.cursor.position.set(this.pixelX,this.pixelY)}startBlinkingAnimation(){!this.cursor||this.isBlinking||(this.isBlinking=!0,this.blinkInterval=window.setInterval(()=>{this.cursor&&this.isBlinking&&(this.cursor.visible=!this.cursor.visible)},this.blinkIntervalMs))}stopBlinkingAnimation(){this.blinkInterval!==null&&(window.clearInterval(this.blinkInterval),this.blinkInterval=null),this.isBlinking=!1,this.cursor&&(this.cursor.visible=this.isVisible)}measureText(e,t){const i=new R.Text(e,t),{width:r}=i;return i.destroy(),r}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 gi{static DEFAULT_FOCUS_DELAY_MS=50;hiddenInput=null;isFocused=!1;focusRetryCount=0;maxFocusRetries=3;focusDelay=gi.DEFAULT_FOCUS_DELAY_MS;eventHandlers={};abortController=null;textChangeCallback=null;lastSyncedText="";isComposing=!1;setupInput(e,t){this.focusDelay=t?.focusDelay??gi.DEFAULT_FOCUS_DELAY_MS,this.createHiddenTextarea(),this.hiddenInput&&(this.hiddenInput.value=e,this.lastSyncedText=e),this.setupEventListeners(),t?.autoFocus!==!1&&this.focusInput()}updateInputValue(e){this.hiddenInput&&(this.hiddenInput.value=e,this.lastSyncedText=e)}focusInput(){this.hiddenInput&&setTimeout(()=>{this.hiddenInput&&!this.isFocused&&(this.hiddenInput.focus(),setTimeout(()=>{!this.isFocused&&this.focusRetryCount<this.maxFocusRetries&&(this.focusRetryCount+=1,this.focusInput())},10))},this.focusDelay)}blurInput(){this.hiddenInput&&this.hiddenInput.blur()}setSelectionRange(e,t){if(!this.hiddenInput)return;const i=this.hiddenInput.value.length,r=Math.max(0,Math.min(e,i)),n=Math.max(r,Math.min(t,i));this.hiddenInput.setSelectionRange(r,n)}getCursorPosition(){return this.hiddenInput?.selectionStart||0}getValue(){return this.hiddenInput?.value||""}setTextInputHandler(e){this.textChangeCallback=e}setEventHandlers(e){this.eventHandlers={...this.eventHandlers,...e}}isFocusedInput(){return this.isFocused}dispose(){this.removeAllEventListeners(),this.hiddenInput&&this.hiddenInput.parentNode&&this.hiddenInput.parentNode.removeChild(this.hiddenInput),this.hiddenInput=null,this.isFocused=!1,this.focusRetryCount=0,this.textChangeCallback=null,this.eventHandlers={}}createHiddenTextarea(){this.hiddenInput=document.createElement("textarea");const e={position:"absolute",opacity:"0.01",pointerEvents:"none",zIndex:"999",left:"0px",top:"0px",width:"1px",height:"1px",border:"none",outline:"none",resize:"none",backgroundColor:"transparent"};Object.assign(this.hiddenInput.style,e),this.hiddenInput.tabIndex=0,document.body.appendChild(this.hiddenInput)}setupEventListeners(){if(!this.hiddenInput)return;this.abortController=new AbortController;const{signal:e}=this.abortController;this.hiddenInput.addEventListener("input",this.handleTextInput,{signal:e}),this.hiddenInput.addEventListener("keydown",this.handleKeyDown,{signal:e}),this.hiddenInput.addEventListener("compositionstart",this.handleCompositionStart,{signal:e}),this.hiddenInput.addEventListener("compositionend",this.handleCompositionEnd,{signal:e}),this.hiddenInput.addEventListener("focus",this.handleFocus,{signal:e}),this.hiddenInput.addEventListener("blur",this.handleBlur,{signal:e}),this.hiddenInput.addEventListener("paste",this.handlePaste,{signal:e})}removeAllEventListeners(){this.abortController?.abort(),this.abortController=null}handleTextInput=e=>{if(!this.hiddenInput||this.isComposing)return;const t=this.hiddenInput.value,i=this.hiddenInput.selectionStart||0;this.lastSyncedText=t,this.textChangeCallback?.(t,i)};handleKeyDown=e=>{if(document.activeElement!==this.hiddenInput)return;let t=!1;if((e.ctrlKey||e.metaKey)&&(t=this.handleKeyboardShortcuts(e),t)){e.preventDefault();return}if(e.key==="Tab"){const i=e.shiftKey?"backward":"forward";this.eventHandlers.onTabNavigation?.(i),e.preventDefault();return}switch(e.key){case"Escape":this.eventHandlers.onEscape?.(e),t=!0;break;case"Enter":t=!1;break;case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"ArrowDown":setTimeout(()=>{if(this.hiddenInput){const i=this.hiddenInput.value,r=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(i,r)}},0),t=!1;break;case"Backspace":case"Delete":t=!1;break;default:t=this.eventHandlers.onCustomKey?.(e.key,e)||!1;break}t&&e.preventDefault()};handleKeyboardShortcuts(e){const{key:t}=e;switch(t.toLowerCase()){case"a":return this.selectAll(),!0;case"c":case"v":return!1;case"z":return this.eventHandlers.onCustomKey?.("undo",e),!0;case"y":return this.eventHandlers.onCustomKey?.("redo",e),!0;default:return!1}}handleCompositionStart=e=>{this.isComposing=!0};handleCompositionEnd=e=>{if(this.isComposing=!1,this.hiddenInput){const t=this.hiddenInput.value,i=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(t,i)}};handleFocus=e=>{this.isFocused=!0,this.focusRetryCount=0,this.eventHandlers.onFocus?.(e)};handleBlur=e=>{this.isFocused=!1,this.eventHandlers.onBlur?.(e)};handlePaste=e=>{setTimeout(()=>{this.handleTextInput(e)},0)};selectAll(){this.hiddenInput&&this.hiddenInput.select()}}class De{static DOUBLE_CLICK_THRESHOLD_MS=300;static EDITING_BG_PADDING_PX=5;static EDITING_BG_ALPHA=.2;static CLICK_HANDLER_DELAY_MS=100;parent;targetText;clipConfig;isEditing=!1;lastClickTime=0;editingContainer=null;editableText=null;textCursor=null;textInputHandler=null;outsideClickHandler=null;constructor(e,t,i){this.parent=e,this.targetText=t,this.clipConfig=i,this.parent.getContainer().eventMode="static",this.parent.getContainer().on("click",this.checkForDoubleClick)}dispose(){this.parent.getContainer().off("click",this.checkForDoubleClick),this.stopEditing(),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null)}startEditing(){if(this.isEditing||!this.targetText)return;const e=structuredClone(this.clipConfig);this.targetText.visible=!1,this.createEditingEnvironment(),this.setupOutsideClickHandler(e),this.isEditing=!0}stopEditing(e=!1,t){if(!this.isEditing)return;let i="";this.editableText&&(i=this.editableText.text),this.editingContainer&&(this.parent.getContainer().removeChild(this.editingContainer),this.editingContainer.destroy(),this.editingContainer=null),this.editableText=null,this.textCursor&&(this.textCursor.dispose(),this.textCursor=null),this.textInputHandler&&(this.textInputHandler.dispose(),this.textInputHandler=null),this.targetText.visible=!0,e&&t&&i!==""&&this.parent.updateTextContent(i,t),this.isEditing=!1}checkForDoubleClick=e=>{const t=Date.now();t-this.lastClickTime<De.DOUBLE_CLICK_THRESHOLD_MS&&this.startEditing(),this.lastClickTime=t};setupOutsideClickHandler(e){this.outsideClickHandler=t=>{const r=this.parent.getContainer().getBounds(),n=t.clientX,o=t.clientY;(n<r.x||n>r.x+r.width||o<r.y||o>r.y+r.height)&&(this.stopEditing(!0,e),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null))},setTimeout(()=>{this.outsideClickHandler&&window.addEventListener("click",this.outsideClickHandler)},De.CLICK_HANDLER_DELAY_MS)}createEditingEnvironment(){this.setupEditingContainer(),this.editingContainer&&this.editableText&&(this.textCursor=new Zt(this.editingContainer,this.editableText,this.clipConfig),this.textCursor.updatePosition(this.targetText.text.length),this.textCursor.startBlinking()),this.setupTextInputHandler(),this.updateTextAlignment()}setupEditingContainer(){this.editingContainer=new R.Container,this.parent.getContainer().addChild(this.editingContainer);const e=new R.Graphics;e.fillStyle={color:0,alpha:De.EDITING_BG_ALPHA},e.rect(-5,-5,this.targetText.width+2*De.EDITING_BG_PADDING_PX,this.targetText.height+2*De.EDITING_BG_PADDING_PX),e.fill(),this.editingContainer.addChild(e),this.editableText=new R.Text(this.targetText.text,this.targetText.style),this.editableText.eventMode="static",this.editableText.cursor="text",this.editingContainer.addChild(this.editableText)}setupTextInputHandler(){this.textInputHandler=new gi,this.textInputHandler.setTextInputHandler((e,t)=>{this.editableText&&(this.editableText.text=e,this.updateTextAlignment()),this.textCursor?.updatePosition(t)}),this.textInputHandler.setEventHandlers({onEscape:e=>this.stopEditing(!1),onTabNavigation:e=>this.stopEditing(!0)}),this.textInputHandler.setupInput(this.targetText.text,{autoFocus:!0})}updateTextAlignment(){if(!this.editableText||!this.editingContainer)return;const e=this.getContainerDimensions(),t=this.getAlignmentSettings(),i=this.calculateHorizontalPosition({width:this.editableText.width},e,t.horizontal),r=this.calculateVerticalPosition({height:this.editableText.height},e,t.vertical);if(this.editingContainer.position.set(i,r),this.editingContainer.children.length>0){const n=this.editingContainer.getChildAt(0);n instanceof R.Graphics&&(n.clear(),n.fillStyle={color:0,alpha:De.EDITING_BG_ALPHA},n.rect(-5,-5,this.editableText.width+2*De.EDITING_BG_PADDING_PX,this.editableText.height+2*De.EDITING_BG_PADDING_PX),n.fill())}}calculateHorizontalPosition(e,t,i="center"){switch(i){case"center":return t.width/2-e.width/2;case"right":return t.width-e.width;case"left":default:return 0}}calculateVerticalPosition(e,t,i="center"){switch(i){case"center":return t.height/2-e.height/2;case"bottom":return t.height-e.height;case"top":default:return 0}}getContainerDimensions(){const e=this.clipConfig.asset;return{width:e.width??this.parent.getSize().width,height:e.height??this.parent.getSize().height}}getAlignmentSettings(){const e=this.clipConfig.asset;return{horizontal:e.alignment?.horizontal??"center",vertical:e.alignment?.vertical??"center"}}}class Io extends we{background=null;text=null;textEditor=null;async load(){await super.load();const e=this.clipConfiguration.asset;if(this.background=new R.Graphics,e.background&&(this.background.fillStyle={color:e.background.color,alpha:e.background.opacity},this.background.rect(0,0,e.width??this.edit.size.width,e.height??this.edit.size.height),this.background.fill()),this.text=new R.Text(e.text,this.createTextStyle(e)),this.positionText(e),e.stroke){const t=new Fi({thickness:e.stroke.width,color:e.stroke.color});this.text.filters=[t]}this.contentContainer.addChild(this.background),this.contentContainer.addChild(this.text),this.configureKeyframes(),this.textEditor=new De(this,this.text,this.clipConfiguration)}update(e,t){super.update(e,t)}dispose(){super.dispose(),this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null,this.textEditor?.dispose(),this.textEditor=null}getSize(){const e=this.clipConfiguration.asset;return{width:e.width??this.edit.size.width,height:e.height??this.edit.size.height}}getFitScale(){return 1}createTextStyle(e){return new R.TextStyle({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:e.width??this.edit.size.width,lineHeight:(e.font?.lineHeight??1)*(e.font?.size??32),align:e.alignment?.horizontal??"center"})}positionText(e){if(!this.text)return;const t=e.alignment?.horizontal??"center",i=e.alignment?.vertical??"center",r=e.width??this.edit.size.width,n=e.height??this.edit.size.height;let o=r/2-this.text.width/2,a=n/2-this.text.height/2;t==="left"?o=0:t==="right"&&(o=r-this.text.width),i==="top"?a=0:i==="bottom"&&(a=n-this.text.height),this.text.position.set(o,a)}updateTextContent(e,t){this.edit.updateTextContent(this,e,t)}}class Po extends we{texture;sprite;isPlaying;originalSize;volumeKeyframeBuilder;syncTimer;skipVideoUpdate;constructor(e,t){super(e,t),this.texture=null,this.sprite=null,this.isPlaying=!1,this.originalSize=null;const i=this.clipConfiguration.asset;this.volumeKeyframeBuilder=new ke(i.volume??1,this.getLength()),this.syncTimer=0,this.skipVideoUpdate=!1}async load(){await super.load();const e=this.clipConfiguration.asset,t=e.src;if(t.endsWith(".mov")||t.endsWith(".webm"))throw new Error(`Video source '${e.src}' is not supported. .mov and .webm files are currently not supported.`);const i={src:t,data:{autoPlay:!1,muted:!1}},r=await this.edit.assetLoader.load(t,i);if(!(r?.source instanceof R.VideoSource))throw new Error(`Invalid video source '${e.src}'.`);this.texture=this.createCroppedTexture(r),this.sprite=new R.Sprite(this.texture),this.contentContainer.addChild(this.sprite),this.clipConfiguration.width&&this.clipConfiguration.height&&this.applyFixedDimensions(),this.configureKeyframes()}update(e,t){if(super.update(e,t),this.skipVideoUpdate)return;const{trim:i=0}=this.clipConfiguration.asset;if(this.syncTimer+=t,!this.texture)return;const r=this.getPlaybackTime(),n=this.edit.isPlaying&&this.isActive();n&&(this.isPlaying||(this.isPlaying=!0,this.texture.source.resource.currentTime=r/1e3+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)*1e3-r)>100&&(this.texture.source.resource.currentTime=r/1e3+i)),!n&&this.isPlaying&&(this.isPlaying=!1,this.texture.source.resource.pause());const o=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&o&&(this.syncTimer=0,this.texture.source.resource.currentTime=r/1e3+i)}draw(){super.draw()}dispose(){super.dispose(),this.sprite?.destroy(),this.sprite=null,this.texture?.destroy(),this.texture=null,this.originalSize=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 this.volumeKeyframeBuilder.getValue(this.getPlaybackTime())}createCroppedTexture(e){const t=this.clipConfiguration.asset;if(!t.crop)return e;const i=e.width,r=e.height,n=Math.floor((t.crop?.left??0)*i),o=Math.floor((t.crop?.right??0)*i),a=Math.floor((t.crop?.top??0)*r),p=Math.floor((t.crop?.bottom??0)*r),m=n,d=a,l=i-n-o,c=r-a-p,u=new R.Rectangle(m,d,l,c);return new R.Texture({source:e.source,frame:u})}}const lr=_e(["linear","bezier","constant"]),cr=_e(["ease","easeIn","easeOut","easeInOut","easeInQuad","easeInCubic","easeInQuart","easeInQuint","easeInSine","easeInExpo","easeInCirc","easeInBack","easeOutQuad","easeOutCubic","easeOutQuart","easeOutQuint","easeOutSine","easeOutExpo","easeOutCirc","easeOutBack","easeInOutQuad","easeInOutCubic","easeInOutQuart","easeInOutQuint","easeInOutSine","easeInOutExpo","easeInOutCirc","easeInOutBack"]),at=te({from:D(),to:D(),start:D().min(0),length:D().positive(),interpolation:lr.optional(),easing:cr.optional()}),hr=pe().url("Invalid audio url format."),ur=at.extend({from:D().min(0).max(1),to:D().min(0).max(1)}).array().or(D().min(0).max(1)),Zi=te({type:nt("audio"),src:hr,trim:D().optional(),volume:ur.optional()}),Ro=_e(["top","topRight","right","bottomRight","bottom","bottomLeft","left","topLeft","center"]),Ki=te({type:nt("html"),html:pe(),css:pe(),width:D().positive().optional(),height:D().positive().optional(),position:Ro.optional()}),dr=pe().url("Invalid image url format."),fr=te({top:D().min(0).optional(),right:D().min(0).optional(),bottom:D().min(0).optional(),left:D().min(0).optional()}),qi=te({type:nt("image"),src:dr,crop:fr.optional()}),pr=pe().url("Invalid luma url format."),Xi=te({type:nt("luma"),src:pr}),Yi=pe().regex(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})|transparent$/,"Invalid color format."),Qi=te({width:D().positive(),height:D().positive()}),Ji=te({radius:D().positive()}),es=te({length:D().positive(),thickness:D().positive()}),mr=te({color:Yi,opacity:D().min(0).max(1)}),gr=te({color:Yi,width:D().positive()}),ts=te({type:nt("shape"),width:D().positive().optional(),height:D().positive().optional(),shape:_e(["rectangle","circle","line"]),fill:mr.optional(),stroke:gr.optional(),rectangle:Qi.optional(),circle:Ji.optional(),line:es.optional()}).refine(s=>s.shape==="rectangle"?Qi.safeParse(s.rectangle):s.shape==="circle"?Ji.safeParse(s.circle):s.shape==="line"?es.safeParse(s.line):!1),yi=pe().regex(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})|transparent$/,"Invalid color format."),yr=te({color:yi.optional(),family:pe().optional(),size:D().positive().optional(),weight:D().optional(),lineHeight:D().optional()}),br=te({horizontal:_e(["left","center","right"]).optional(),vertical:_e(["top","center","bottom"]).optional()}),vr=te({color:yi,opacity:D().min(0).max(1)}),wr=te({width:D().positive(),color:yi}),is=te({type:nt("text"),text:pe(),width:D().positive().optional(),height:D().positive().optional(),font:yr.optional(),alignment:br.optional(),background:vr.optional(),stroke:wr.optional()}),_r=pe().url("Invalid video url format."),xr=te({top:D().min(0).optional(),right:D().min(0).optional(),bottom:D().min(0).optional(),left:D().min(0).optional()}),Cr=at.extend({from:D().min(0).max(1),to:D().min(0).max(1)}).array().or(D().min(0).max(1)),ss=te({type:nt("video"),src:_r,trim:D().optional(),crop:xr.optional(),volume:Cr.optional()}),kr=ji([is,fi,ts,Ki,qi,ss,Xi,Zi]).refine(s=>s.type==="text"?is.safeParse(s):s.type==="rich-text"?fi.safeParse(s):s.type==="shape"?ts.safeParse(s):s.type==="html"?Ki.safeParse(s):s.type==="image"?qi.safeParse(s):s.type==="video"?ss.safeParse(s):s.type==="luma"?Xi.safeParse(s):s.type==="audio"?Zi.safeParse(s):!1),Oo=_e(["topLeft","top","topRight","left","center","right","bottomLeft","bottom","bottomRight"]),Fo=_e(["crop","cover","contain","none"]),Rt=D().min(-10).max(10).default(0),Mo=at.extend({from:Rt,to:Rt}).array().or(Rt),Lo=at.extend({from:Rt,to:Rt}).array().or(Rt),Bo=te({x:Mo.default(0),y:Lo.default(0)}),$o=at.extend({from:D().min(0).max(1),to:D().min(0).max(1)}).array().or(D().min(0).max(1)),Do=at.extend({from:D().min(0),to:D().min(0)}).array().or(D().min(0)),zo=te({angle:at.extend({from:D(),to:D()}).array().or(D())}),Ho=pe(),Tr=pe(),No=te({in:Tr.optional(),out:Tr.optional()}),Uo=te({rotate:zo.default({angle:0})}),rs=te({asset:kr,start:D().min(0),length:D().positive(),position:Oo.default("center").optional(),fit:Fo.optional(),offset:Bo.default({x:0,y:0}).optional(),opacity:$o.default(1).optional(),scale:Do.default(1).optional(),transform:Uo.default({rotate:{angle:0}}).optional(),effect:Ho.optional(),transition:No.optional(),width:D().min(1).max(3840).optional(),height:D().min(1).max(2160).optional()}).transform(s=>{if(s.fit!==void 0)return s;const e=s.asset.type==="rich-text"?"none":"crop";return{...s,fit:e}});class jo{constructor(e,t){this.trackIdx=e,this.clip=t}name="addClip";addedPlayer;async execute(e){if(!e)return;const t=rs.parse(this.clip),i=e.createPlayerFromAssetType(t);i.layer=this.trackIdx+1,await e.addPlayer(this.trackIdx,i),e.updateDuration(),this.addedPlayer=i}async undo(e){!e||!this.addedPlayer||(e.queueDisposeClip(this.addedPlayer),e.updateDuration())}}class Sr{constructor(e){this.trackIdx=e}name="addTrack";execute(e){if(!e)return;const t=e.getTracks(),i=e.getClips();t.splice(this.trackIdx,0,[]),i.forEach(r=>{if(r.layer>=this.trackIdx){const n=1e5-r.layer*100,o=e.getContainer().getChildByLabel(`shotstack-track-${n}`,!1);o&&o.removeChild(r.getContainer()),r.layer+=1;const a=1e5-r.layer*100;let p=e.getContainer().getChildByLabel(`shotstack-track-${a}`,!1);p||(p=new R.Container({label:`shotstack-track-${a}`,zIndex:a}),e.getContainer().addChild(p)),p.addChild(r.getContainer())}}),e.updateDuration(),e.emitEvent("track:added",{trackIndex:this.trackIdx,totalTracks:t.length})}undo(e){if(!e)return;const t=e.getTracks(),i=e.getClips();t.splice(this.trackIdx,1),i.forEach(r=>{r.layer>this.trackIdx&&(r.layer-=1)}),e.updateDuration()}}class Vo{name="ClearSelection";previousSelection=null;execute(e){const t=e.getSelectedClip();if(t){const i=e.findClipIndices(t);i&&(this.previousSelection={player:t,trackIndex:i.trackIndex,clipIndex:i.clipIndex})}e.setSelectedClip(null),e.emitEvent("selection:cleared",{})}undo(e){if(this.previousSelection){const t=e.getClipAt(this.previousSelection.trackIndex,this.previousSelection.clipIndex);t&&(e.setSelectedClip(t),e.emitEvent("clip:selected",{clip:t.clipConfiguration,trackIndex:this.previousSelection.trackIndex,clipIndex:this.previousSelection.clipIndex}))}}}class Wo{constructor(e,t){this.trackIdx=e,this.clipIdx=t}name="deleteClip";deletedClip;execute(e){if(!e)return;const i=e.getClips().filter(r=>r.layer===this.trackIdx+1);this.deletedClip=i[this.clipIdx],this.deletedClip&&(e.queueDisposeClip(this.deletedClip),e.updateDuration())}undo(e){!e||!this.deletedClip||e.undeleteClip(this.trackIdx,this.deletedClip)}}class Go{constructor(e){this.trackIdx=e}name="deleteTrack";deletedClips=[];execute(e){if(!e)return;const t=e.getClips(),i=e.getTracks();this.deletedClips=t.filter(o=>o.layer===this.trackIdx+1).map(o=>({config:structuredClone(o.clipConfiguration)})),t.forEach((o,a)=>{o.layer===this.trackIdx+1&&(t[a].shouldDispose=!0)}),e.disposeClips(),i.splice(this.trackIdx,1);const r=e.getClips(),n=e.getContainer();r.forEach((o,a)=>{if(o.layer>this.trackIdx+1){n.getChildByLabel(`shotstack-track-${1e5-o.layer*100}`,!1)?.removeChild(o.getContainer()),r[a].layer-=1;const m=1e5-r[a].layer*100;let d=n.getChildByLabel(`shotstack-track-${m}`,!1);d||(d=new R.Container({label:`shotstack-track-${m}`,zIndex:m}),n.addChild(d)),d.addChild(r[a].getContainer())}}),e.updateDuration()}async undo(e){if(!e||this.deletedClips.length===0)return;const t=e.getTracks(),i=e.getClips();t.splice(this.trackIdx,0,[]),i.forEach((r,n)=>{r.layer>=this.trackIdx+1&&(i[n].layer+=1)});for(const{config:r}of this.deletedClips){const n=e.createPlayerFromAssetType(r);n.layer=this.trackIdx+1,await e.addPlayer(this.trackIdx,n)}e.updateDuration()}}class Zo{constructor(e,t){this.trackIndex=e,this.clipIndex=t}name="SelectClip";previousSelection=null;execute(e){const t=e.getSelectedClip();if(t){const r=e.findClipIndices(t);r&&(this.previousSelection=r)}const i=e.getClipAt(this.trackIndex,this.clipIndex);i&&(e.setSelectedClip(i),e.emitEvent("clip:selected",{clip:i.clipConfiguration,trackIndex:this.trackIndex,clipIndex:this.clipIndex}))}undo(e){if(e.setSelectedClip(null),this.previousSelection){const t=e.getClipAt(this.previousSelection.trackIndex,this.previousSelection.clipIndex);t&&(e.setSelectedClip(t),e.emitEvent("clip:selected",{clip:t.clipConfiguration,trackIndex:this.previousSelection.trackIndex,clipIndex:this.previousSelection.clipIndex}))}else e.emitEvent("selection:cleared",{})}}class Ko{constructor(e,t,i){this.clip=e,this.initialClipConfig=t,this.finalClipConfig=i,this.storedInitialConfig=t?structuredClone(t):null,this.storedFinalConfig=i?structuredClone(i):structuredClone(this.clip.clipConfiguration)}name="setUpdatedClip";storedInitialConfig;storedFinalConfig;execute(e){if(!e)return;this.storedFinalConfig&&e.restoreClipConfiguration(this.clip,this.storedFinalConfig),e.setUpdatedClip(this.clip);const t=this.clip.layer-1,n=e.getClips().filter(o=>o.layer===this.clip.layer).indexOf(this.clip);e.emitEvent("clip:updated",{previous:{clip:this.storedInitialConfig||this.initialClipConfig,trackIndex:t,clipIndex:n},current:{clip:this.storedFinalConfig||this.clip.clipConfiguration,trackIndex:t,clipIndex:n}})}undo(e){if(!e||!this.storedInitialConfig)return;e.restoreClipConfiguration(this.clip,this.storedInitialConfig),e.setUpdatedClip(this.clip);const t=this.clip.layer-1,n=e.getClips().filter(o=>o.layer===this.clip.layer).indexOf(this.clip);e.emitEvent("clip:updated",{previous:{clip:this.storedFinalConfig,trackIndex:t,clipIndex:n},current:{clip:this.storedInitialConfig,trackIndex:t,clipIndex:n}})}}class qo{constructor(e,t,i){this.trackIndex=e,this.clipIndex=t,this.splitTime=i}name="SplitClip";originalClipConfig=null;rightClipPlayer=null;splitSuccessful=!1;execute(e){const t=e.getClipAt(this.trackIndex,this.clipIndex);if(!t||!t.clipConfiguration)throw new Error("Cannot split clip: invalid player or clip configuration");const i=t.clipConfiguration,r=i.start||0,n=i.length,o=.1,a=this.splitTime-r;if(a<=o||a>=n-o)throw new Error("Cannot split clip: split point too close to clip boundaries");this.originalClipConfig={...i};const p={...i,length:a},m={...i,start:r+a,length:n-a};if(i.asset&&(p.asset={...i.asset},m.asset={...i.asset}),i.asset&&(i.asset.type==="video"||i.asset.type==="audio")){const u=i.asset.trim||0;p.asset&&(p.asset.type==="video"||p.asset.type==="audio")&&(p.asset.trim=u),m.asset&&(m.asset.type==="video"||m.asset.type==="audio")&&(m.asset.trim=u+a)}if(Object.assign(t.clipConfiguration,p),t.reconfigureAfterRestore(),t.draw(),this.rightClipPlayer=e.createPlayerFromAssetType(m),!this.rightClipPlayer)throw Object.assign(t.clipConfiguration,this.originalClipConfig),t.reconfigureAfterRestore(),new Error("Failed to create right clip player");this.rightClipPlayer.layer=this.trackIndex+1;const d=e.getTrack(this.trackIndex);if(!d)throw new Error("Invalid track index");d.splice(this.clipIndex+1,0,this.rightClipPlayer);const l=e.getClips(),c=l.indexOf(t);c!==-1&&l.splice(c+1,0,this.rightClipPlayer),e.addPlayerToContainer(this.trackIndex,this.rightClipPlayer),this.rightClipPlayer.reconfigureAfterRestore(),this.rightClipPlayer.load().then(()=>{this.splitSuccessful=!0,this.rightClipPlayer&&this.rightClipPlayer.draw(),e.updateDuration(),e.emitEvent("timeline:updated",{current:e.getEditState()})}).catch(u=>{console.error("Failed to load split clip:",u)})}undo(e){if(!this.originalClipConfig)return;const t=e.getClipAt(this.trackIndex,this.clipIndex);if(t){if(Object.assign(t.clipConfiguration,this.originalClipConfig),t.reconfigureAfterRestore(),this.rightClipPlayer){const i=e.getTrack(this.trackIndex);if(i){const o=i.indexOf(this.rightClipPlayer);o!==-1&&i.splice(o,1)}const r=e.getClips(),n=r.indexOf(this.rightClipPlayer);n!==-1&&r.splice(n,1),e.queueDisposeClip(this.rightClipPlayer),this.rightClipPlayer=null}e.updateDuration(),e.emitEvent("timeline:updated",{current:e.getEditState()})}}}class Xo{constructor(e,t,i){this.clip=e,this.newText=t,this.initialConfig=i;const{asset:r}=this.clip.clipConfiguration;this.previousText=r&&"text"in r?r.text:""}name="updateTextContent";previousText;execute(e){if(e&&this.clip.clipConfiguration.asset&&"text"in this.clip.clipConfiguration.asset){this.clip.clipConfiguration.asset.text=this.newText;const t=this.clip.text;t&&(t.text=this.newText,this.clip.positionText(this.clip.clipConfiguration.asset)),e.setUpdatedClip(this.clip);const i=this.clip.layer-1,o=e.getClips().filter(a=>a.layer===this.clip.layer).indexOf(this.clip);e.emitEvent("clip:updated",{previous:{clip:this.initialConfig,trackIndex:i,clipIndex:o},current:{clip:this.clip.clipConfiguration,trackIndex:i,clipIndex:o}})}}undo(e){if(e&&this.clip.clipConfiguration.asset&&"text"in this.clip.clipConfiguration.asset){this.clip.clipConfiguration.asset.text=this.previousText;const t=this.clip.text;t&&(t.text=this.previousText,this.clip.positionText(this.clip.clipConfiguration.asset)),e.setUpdatedClip(this.clip);const i=this.clip.layer-1,o=e.getClips().filter(a=>a.layer===this.clip.layer).indexOf(this.clip);e.emitEvent("clip:updated",{previous:{clip:this.clip.clipConfiguration,trackIndex:i,clipIndex:o},current:{clip:this.initialConfig,trackIndex:i,clipIndex:o}})}}}class Kt{events;constructor(){this.events={}}on(e,t){this.events[e]||(this.events[e]=new Set),this.events[e].add(t)}off(e,t){this.events[e]&&(this.events[e].delete(t),!(this.events[e].size>0)&&delete this.events[e])}clear(e){delete this.events[e]}emit(e,t){if(this.events[e])for(const i of this.events[e])i(t)}}class Yo extends Kt{registry;constructor(){super(),this.registry={}}}class bi{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 Yo;async load(e,t){this.updateAssetLoadMetadata(e,"pending",0);try{if(await this.shouldUseSafariVideoLoader(t))return await this.loadVideoForSafari(e,t);const i=await R.Assets.load(t,r=>{this.updateAssetLoadMetadata(e,"loading",r)});return this.updateAssetLoadMetadata(e,"success",1),i}catch{return this.updateAssetLoadMetadata(e,"failed",1),null}}getProgress(){const e=Object.keys(this.loadTracker.registry);return e.length===0?0:e.reduce((i,r)=>i+this.loadTracker.registry[r].progress,0)/e.length}extractUrl(e){if(typeof e=="string")return e;const t=Array.isArray(e.src)?e.src[0]:e.src;return typeof t=="string"?t:t?.src}hasVideoExtension(e){const t=new URL(e,window.location.origin).pathname.toLowerCase();return bi.VIDEO_EXTENSIONS.some(i=>t.endsWith(i))}async getContentType(e){try{return(await fetch(e,{method:"HEAD"})).headers.get("content-type")}catch{return null}}canPlayVideo(e){const t=new URL(e,window.location.origin).pathname.toLowerCase(),i=t.slice(t.lastIndexOf(".")),r=bi.VIDEO_MIME[i];return r?document.createElement("video").canPlayType(r)!=="":!1}async isPlayableVideo(e){if(this.hasVideoExtension(e))return this.canPlayVideo(e);const t=await this.getContentType(e);return t?.startsWith("video/")?document.createElement("video").canPlayType(t)!=="":!1}async shouldUseSafariVideoLoader(e){const t=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),i=this.extractUrl(e);return t&&i!==void 0&&await this.isPlayableVideo(i)}async loadVideoForSafari(e,t){const i=this.extractUrl(t),r=typeof t=="object"?t.data??{}:{},n=await new Promise((o,a)=>{const p=document.createElement("video");p.crossOrigin="anonymous",p.playsInline=!0,p.muted=!0,p.preload="metadata",p.addEventListener("loadedmetadata",()=>{try{const m=new R.VideoSource({resource:p,autoPlay:r.autoPlay??!1,...r});o(new R.Texture({source:m}))}catch(m){a(m)}},{once:!0}),p.addEventListener("error",()=>a(new Error("Video loading failed")),{once:!0}),this.updateAssetLoadMetadata(e,"loading",.5),p.src=i});return this.updateAssetLoadMetadata(e,"success",1),n}updateAssetLoadMetadata(e,t,i){this.loadTracker.registry[e]?(this.loadTracker.registry[e].progress=i,this.loadTracker.registry[e].status=t):this.loadTracker.registry[e]={progress:i,status:t};const r={...this.loadTracker.registry};this.loadTracker.emit("onAssetLoadInfoUpdated",{registry:r})}}class qt{static Name="FontLoadParser";id;name;extension;validFontExtensions;woff2Decompressor;constructor(){this.id=qt.Name,this.name=qt.Name,this.extension={type:[R.ExtensionType.LoadParser],priority:R.LoaderParserPriority.High,ref:null},this.validFontExtensions=["ttf","otf","woff","woff2"],this.woff2Decompressor=null}test(e){const t=e.split("?")[0]?.split(".").pop()?.toLowerCase()??"";return this.validFontExtensions.includes(t)}async load(e,t,i){const r=e.split("?")[0]?.split(".").pop()?.toLowerCase()??"",n=await fetch(e).then(c=>c.arrayBuffer());if(r!=="woff2"){const c=Rs.parse(new Uint8Array(n).buffer),u=c.names.fontFamily.en||c.names.fontFamily[Object.keys(c.names.fontFamily)[0]],h=new FontFace(u,`url(${e})`);return await h.load(),document.fonts.add(h),h}if(await this.loadWoff2Decompressor(),!this.woff2Decompressor)throw new Error("Cannot initialize Woff2 decompressor.");const o=this.woff2Decompressor.decompress(n),a=Rs.parse(new Uint8Array(o).buffer),p=a.names.fontFamily.en||a.names.fontFamily[Object.keys(a.names.fontFamily)[0]],m=new Blob([o],{type:"font/ttf"}),d=URL.createObjectURL(m),l=new FontFace(p,`url(${d})`);return await l.load(),document.fonts.add(l),l}async loadWoff2Decompressor(){if(this.woff2Decompressor)return;const t=`${await fetch("https://unpkg.com/wawoff2@2.0.1/build/decompress_binding.js").then(i=>i.text())}; return Module`;this.woff2Decompressor=new Function(t)(),await new Promise(i=>{this.woff2Decompressor.onRuntimeInitialized=i})}unload(e){e&&document.fonts.delete(e)}}const Er=te({clips:rs.array()}),Ar=pe().url("Invalid image url format."),Ir=te({src:Ar}),Pr=te({background:pe().optional(),fonts:Ir.array().optional(),tracks:Er.array()}),Rr=te({size:te({width:D().positive(),height:D().positive()}),fps:D().positive().optional(),format:pe()}),Or=te({timeline:Pr,output:Rr});class Ot extends Je{static ZIndexPadding=100;assetLoader;events;edit;tracks;clipsToDispose;clips;commandHistory=[];commandIndex=-1;playbackTime;size;backgroundColor;totalDuration;isPlaying;selectedClip;updatedClip;viewportMask;isExporting=!1;constructor(e,t="#ffffff"){super(),this.assetLoader=new bi,this.edit=null,this.tracks=[],this.clipsToDispose=[],this.clips=[],this.events=new Kt,this.size=e,this.playbackTime=0,this.totalDuration=0,this.isPlaying=!1,this.selectedClip=null,this.updatedClip=null,this.backgroundColor=t,this.setupIntentListeners()}async load(){const e=new R.Graphics;e.fillStyle={color:this.backgroundColor},e.rect(0,0,this.size.width,this.size.height),e.fill(),this.getContainer().addChild(e),this.viewportMask=new R.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})}update(e,t){for(const i of this.clips)i.shouldDispose&&this.queueDisposeClip(i),i.update(e,t);this.disposeClips(),this.isPlaying&&(this.playbackTime=Math.max(0,Math.min(this.playbackTime+t,this.totalDuration)),this.playbackTime===this.totalDuration&&this.pause())}draw(){for(const e of this.clips)e.draw()}dispose(){if(this.clearClips(),this.viewportMask){try{this.getContainer().setMask(null)}catch{}this.viewportMask.destroy(),this.viewportMask=void 0}}play(){this.isPlaying=!0,this.events.emit("playback:play",{})}pause(){this.isPlaying=!1,this.events.emit("playback:pause",{})}seek(e){this.playbackTime=Math.max(0,Math.min(e,this.totalDuration)),this.pause()}stop(){this.seek(0)}async loadEdit(e){this.clearClips(),this.edit=Or.parse(e),this.backgroundColor=this.edit.timeline.background||"#000000",await Promise.all((this.edit.timeline.fonts??[]).map(async t=>{const i=t.src,r={src:i,loadParser:qt.Name};return this.assetLoader.load(i,r)}));for(const[t,i]of this.edit.timeline.tracks.entries())for(const r of i.clips){const n=this.createPlayerFromAssetType(r);n.layer=t+1,await this.addPlayer(t,n)}this.updateTotalDuration()}getEdit(){const e=this.tracks.map((t,i)=>({clips:t.filter(n=>n&&!this.clipsToDispose.includes(n)).map(n=>n.clipConfiguration)}));return{timeline:{background:this.backgroundColor,tracks:e,fonts:this.edit?.timeline.fonts||[]},output:this.edit?.output||{size:this.size,format:"mp4"}}}addClip(e,t){const i=new jo(e,t);this.executeCommand(i)}getClip(e,t){const i=this.clips.filter(r=>r.layer===e+1);return t<0||t>=i.length?null:i[t].clipConfiguration}getPlayerClip(e,t){const i=this.clips.filter(r=>r.layer===e+1);return t<0||t>=i.length?null:i[t]}deleteClip(e,t){const i=new Wo(e,t);this.executeCommand(i)}splitClip(e,t,i){const r=new qo(e,t,i);this.executeCommand(r)}addTrack(e,t){const i=new Sr(e);this.executeCommand(i),t?.clips?.forEach(r=>this.addClip(e,r))}getTrack(e){const t=this.clips.filter(i=>i.layer===e+1);return t.length===0?null:{clips:t.map(i=>i.clipConfiguration)}}deleteTrack(e){const t=new Go(e);this.executeCommand(t)}getTotalDuration(){return this.totalDuration}undo(){if(this.commandIndex>=0){const e=this.commandHistory[this.commandIndex];if(e.undo){const t=this.createCommandContext();e.undo(t),this.commandIndex-=1,this.events.emit("edit:undo",{command:e.name})}}}redo(){if(this.commandIndex<this.commandHistory.length-1){this.commandIndex+=1;const e=this.commandHistory[this.commandIndex],t=this.createCommandContext();e.execute(t),this.events.emit("edit:redo",{command:e.name})}}setUpdatedClip(e,t=null,i=null){const r=new Ko(e,t,i);this.executeCommand(r)}updateTextContent(e,t,i){const r=new Xo(e,t,i);this.executeCommand(r)}executeEditCommand(e){return this.executeCommand(e)}executeCommand(e){const t=this.createCommandContext(),i=e.execute(t);return this.commandHistory=this.commandHistory.slice(0,this.commandIndex+1),this.commandHistory.push(e),this.commandIndex+=1,i}createCommandContext(){return{getClips:()=>this.clips,getTracks:()=>this.tracks,getTrack:e=>e>=0&&e<this.tracks.length?this.tracks[e]:null,getContainer:()=>this.getContainer(),addPlayer:(e,t)=>this.addPlayer(e,t),addPlayerToContainer:(e,t)=>{this.addPlayerToContainer(e,t)},createPlayerFromAssetType:e=>this.createPlayerFromAssetType(e),queueDisposeClip:e=>this.queueDisposeClip(e),disposeClips:()=>this.disposeClips(),undeleteClip:(e,t)=>{this.clips.push(t),this.updateTotalDuration()},setUpdatedClip:e=>{this.updatedClip=e},restoreClipConfiguration:(e,t)=>{Object.assign(e.clipConfiguration,structuredClone(t)),e.reconfigureAfterRestore(),e.draw()},updateDuration:()=>this.updateTotalDuration(),emitEvent:(e,t)=>this.events.emit(e,t),findClipIndices:e=>this.findClipIndices(e),getClipAt:(e,t)=>this.getClipAt(e,t),getSelectedClip:()=>this.selectedClip,setSelectedClip:e=>{this.selectedClip=e},movePlayerToTrackContainer:(e,t,i)=>this.movePlayerToTrackContainer(e,t,i),getEditState:()=>this.getEdit()}}queueDisposeClip(e){this.clipsToDispose.push(e)}disposeClips(){if(this.clipsToDispose.length!==0){for(const e of this.clipsToDispose)this.disposeClip(e);this.clips=this.clips.filter(e=>!this.clipsToDispose.includes(e)),this.clipsToDispose=[],this.updateTotalDuration()}}disposeClip(e){try{if(this.getContainer().children.includes(e.getContainer())){const t=this.getContainer().getChildIndex(e.getContainer());this.getContainer().removeChildAt(t)}else for(const t of this.getContainer().children)if(t instanceof R.Container&&t.label?.toString().startsWith("shotstack-track-")&&t.children.includes(e.getContainer())){t.removeChild(e.getContainer());break}}catch(t){console.warn(`Attempting to unmount an unmounted clip: ${t}`)}this.unloadClipAssets(e),e.dispose()}unloadClipAssets(e){const{asset:t}=e.clipConfiguration;if(t&&"src"in t&&typeof t.src=="string")try{R.Assets.unload(t.src)}catch(i){console.warn(`Failed to unload asset: ${t.src}`,i)}}clearClips(){for(const e of this.clips)this.disposeClip(e);this.clips=[],this.clipsToDispose=[],this.updateTotalDuration()}updateTotalDuration(){let e=0;for(const i of this.tracks)for(const r of i)e=Math.max(e,r.getEnd());const t=this.totalDuration;this.totalDuration=e,t!==this.totalDuration&&this.events.emit("duration:changed",{duration:this.totalDuration})}addPlayerToContainer(e,t){const i=1e5-(e+1)*Ot.ZIndexPadding,r=`shotstack-track-${i}`;let n=this.getContainer().getChildByLabel(r,!1);n||(n=new R.Container({label:r,zIndex:i}),this.getContainer().addChild(n)),n.addChild(t.getContainer())}movePlayerToTrackContainer(e,t,i){if(t===i)return;const r=1e5-(t+1)*Ot.ZIndexPadding,n=1e5-(i+1)*Ot.ZIndexPadding,o=`shotstack-track-${r}`,a=`shotstack-track-${n}`,p=this.getContainer().getChildByLabel(o,!1);let m=this.getContainer().getChildByLabel(a,!1);m||(m=new R.Container({label:a,zIndex:n}),this.getContainer().addChild(m)),p&&p.removeChild(e.getContainer()),m.addChild(e.getContainer())}createPlayerFromAssetType(e){if(!e.asset?.type)throw new Error("Invalid clip configuration: missing asset type");let t;switch(e.asset.type){case"text":{t=new Io(this,e);break}case"rich-text":{t=new Eo(this,e);break}case"shape":{t=new Ao(this,e);break}case"html":{t=new ea(this,e);break}case"image":{t=new ta(this,e);break}case"video":{t=new Po(this,e);break}case"audio":{t=new Os(this,e);break}case"luma":{t=new Fs(this,e);break}default:throw new Error(`Unsupported clip type: ${e.asset.type}`)}return t}async addPlayer(e,t){for(;this.tracks.length<=e;)this.tracks.push([]);this.tracks[e].push(t),this.clips.push(t);const i=1e5-(e+1)*Ot.ZIndexPadding,r=`shotstack-track-${i}`;let n=this.getContainer().getChildByLabel(r,!1);n||(n=new R.Container({label:r,zIndex:i}),this.getContainer().addChild(n)),n.addChild(t.getContainer());const o=t instanceof Fs;await t.load(),o&&n.setMask({mask:t.getMask(),inverse:!0}),this.updateTotalDuration()}selectClip(e,t){const i=new Zo(e,t);this.executeCommand(i)}clearSelection(){const e=new Vo;this.executeCommand(e)}isClipSelected(e,t){if(!this.selectedClip)return!1;const i=this.selectedClip.layer-1,r=this.tracks[i].indexOf(this.selectedClip);return e===i&&t===r}getSelectedClipInfo(){if(!this.selectedClip)return null;const e=this.selectedClip.layer-1,t=this.tracks[e].indexOf(this.selectedClip);return{trackIndex:e,clipIndex:t,player:this.selectedClip}}findClipIndices(e){for(let t=0;t<this.tracks.length;t+=1){const i=this.tracks[t].indexOf(e);if(i!==-1)return{trackIndex:t,clipIndex:i}}return null}getClipAt(e,t){return e>=0&&e<this.tracks.length&&t>=0&&t<this.tracks[e].length?this.tracks[e][t]:null}selectPlayer(e){const t=this.findClipIndices(e);t&&this.selectClip(t.trackIndex,t.clipIndex)}isPlayerSelected(e){return this.isExporting?!1:this.selectedClip===e}setExportMode(e){this.isExporting=e}isInExportMode(){return this.isExporting}setupIntentListeners(){this.events.on("timeline:clip:clicked",e=>{e.player?this.selectPlayer(e.player):this.selectClip(e.trackIndex,e.clipIndex)}),this.events.on("timeline:background:clicked",()=>{this.clearSelection()}),this.events.on("canvas:clip:clicked",e=>{this.selectPlayer(e.player)}),this.events.on("canvas:background:clicked",()=>{this.clearSelection()})}}class Xt extends Je{static Width=250;static Height=100;fps;playbackTime;playbackDuration;isPlaying;background;text;constructor(){super(),this.background=null,this.text=null,this.fps=0,this.playbackTime=0,this.playbackDuration=0,this.isPlaying=!1}async load(){const e=new R.Graphics;e.fillStyle={color:"#424242",alpha:.5},e.rect(0,0,Xt.Width,Xt.Height),e.fill(),this.getContainer().addChild(e),this.background=e;const t=new R.Text;t.text="",t.style={fontFamily:"monospace",fontSize:14,fill:"#ffffff",wordWrap:!0,wordWrapWidth:Xt.Width},this.getContainer().addChild(t),this.text=t}update(e,t){if(!this.text)return;const i=this.getMemoryInfo(),r=[`FPS: ${this.fps}`,`Playback: ${(this.playbackTime/1e3).toFixed(2)}/${(this.playbackDuration/1e3).toFixed(2)}`,`Playing: ${this.isPlaying}`,`Total Heap Size: ${i.totalHeapSize?`${this.bytesToMegabytes(i.totalHeapSize)}MB`:"N/A"}`,`Used Heap Size: ${i.usedHeapSize?`${this.bytesToMegabytes(i.usedHeapSize)}MB`:"N/A"}`,`Heap Size Limit: ${i.heapSizeLimit?`${this.bytesToMegabytes(i.heapSizeLimit)}MB`:"N/A"}`];this.text.text=r.join(`
187
+ `)}draw(){}dispose(){this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null}getMemoryInfo(){const e={};return"memory"in performance&&(e.totalHeapSize=performance.memory.totalJSHeapSize,e.usedHeapSize=performance.memory.usedJSHeapSize,e.heapSizeLimit=performance.memory.jsHeapSizeLimit),e}bytesToMegabytes(e){return Math.round(e/1024/1024)}}class yt{static CanvasSelector="[data-shotstack-studio]";static extensionsRegistered=!1;size;application;edit;inspector;container;background;timeline;minZoom=.1;maxZoom=4;currentZoom=.8;onTickBound;constructor(e,t){this.size=e,this.application=new R.Application,this.edit=t,this.inspector=new Xt,this.onTickBound=this.onTick.bind(this)}async load(){const e=document.querySelector(yt.CanvasSelector);if(!e)throw new Error(`Shotstack canvas root element '${yt.CanvasSelector}' not found.`);this.registerExtensions(),this.container=new R.Container,this.background=new R.Graphics,this.background.fillStyle={color:"#424242"},this.background.rect(0,0,this.size.width,this.size.height),this.background.fill(),await this.configureApplication(),this.configureStage(),this.setupTouchHandling(e),this.edit.getContainer().scale=this.currentZoom,e.appendChild(this.application.canvas)}setupTouchHandling(e){const t=this.edit.getContainer();e.addEventListener("wheel",i=>{if(i.preventDefault(),i.stopPropagation(),i.ctrlKey){const r=Math.exp(-i.deltaY/100),n=this.currentZoom*r,o=this.currentZoom;this.currentZoom=Math.min(Math.max(n,this.minZoom),this.maxZoom);const a={x:this.application.canvas.width/2,y:this.application.canvas.height/2},p={x:t.position.x-a.x,y:t.position.y-a.y},m=this.currentZoom/o;t.position.x=a.x+p.x*m,t.position.y=a.y+p.y*m,t.scale.x=this.currentZoom,t.scale.y=this.currentZoom}},{passive:!1,capture:!0})}centerEdit(){if(!this.edit)return;const e=this.edit.getContainer();e.position={x:this.application.canvas.width/2-this.edit.size.width*this.currentZoom/2,y:this.application.canvas.height/2-this.edit.size.height*this.currentZoom/2}}zoomToFit(){if(!this.edit)return;const e=this.application.canvas.width/this.edit.size.width,t=this.application.canvas.height/this.edit.size.height,i=Math.min(e,t);this.currentZoom=Math.min(Math.max(i,this.minZoom),this.maxZoom);const r=this.edit.getContainer();r.scale.x=this.currentZoom,r.scale.y=this.currentZoom,this.centerEdit()}setZoom(e){this.currentZoom=Math.min(Math.max(e,this.minZoom),this.maxZoom);const t=this.edit.getContainer();t.scale.x=this.currentZoom,t.scale.y=this.currentZoom}registerTimeline(e){this.timeline=e}registerExtensions(){yt.extensionsRegistered||(R.extensions.add(new zt),R.extensions.add(new qt),yt.extensionsRegistered=!0)}async configureApplication(){const e={background:"#000000",width:this.size.width,height:this.size.height,antialias:!0};await this.application.init(e),this.application.ticker.add(this.onTickBound),this.application.ticker.minFPS=60,this.application.ticker.maxFPS=60}onTick(e){this.edit.update(e.deltaTime,e.deltaMS),this.edit.draw(),this.inspector.fps=Math.ceil(e.FPS),this.inspector.playbackTime=this.edit.playbackTime,this.inspector.playbackDuration=this.edit.totalDuration,this.inspector.isPlaying=this.edit.isPlaying,this.inspector.update(e.deltaTime,e.deltaMS),this.inspector.draw(),this.timeline&&(this.timeline.update(e.deltaTime,e.deltaMS),this.timeline.draw())}configureStage(){if(!this.container||!this.background)throw new Error("Shotstack canvas container not set up.");this.container.addChild(this.background),this.container.addChild(this.edit.getContainer()),this.container.addChild(this.inspector.getContainer()),this.application.stage.addChild(this.container),this.application.stage.eventMode="static",this.application.stage.hitArea=new R.Rectangle(0,0,this.size.width,this.size.height),this.background.eventMode="static",this.background.on("pointerdown",this.onBackgroundClick.bind(this)),this.application.stage.on("click",this.onClick.bind(this)),this.edit.getContainer().position={x:this.application.canvas.width/2-this.edit.size.width*this.currentZoom/2,y:this.application.canvas.height/2-this.edit.size.height*this.currentZoom/2}}onClick(){this.edit.pause()}onBackgroundClick(e){e.target===this.background&&this.edit.events.emit("canvas:background:clicked",{})}pauseTicker(){this.application.ticker.remove(this.onTickBound)}resumeTicker(){this.application.ticker.add(this.onTickBound)}dispose(){const e=document.querySelector(yt.CanvasSelector);e&&e.contains(this.application.canvas)&&e.removeChild(this.application.canvas),this.application.ticker.remove(this.onTickBound),this.application.stage.off("click",this.onClick,this),this.background?.off("pointerdown",this.onBackgroundClick,this),this.background?.destroy(),this.container?.destroy(),this.inspector.dispose(),this.application.destroy(!0,{children:!0,texture:!0})}}class Qo{edit;seekDistance=50;seekDistanceLarge=500;frameTime=16.67;constructor(e){this.edit=e}async load(){document.addEventListener("keydown",this.handleKeyDown),document.addEventListener("keyup",this.handleKeyUp)}dispose(){document.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("keyup",this.handleKeyUp)}handleKeyDown=e=>{if(!(e.target instanceof HTMLInputElement||e.target instanceof HTMLTextAreaElement))switch(e.code){case"Space":{this.edit.isPlaying?this.edit.pause():this.edit.play();break}case"ArrowLeft":{if(e.metaKey)this.edit.seek(0);else{const t=e.shiftKey?this.seekDistanceLarge:this.seekDistance;this.edit.seek(this.edit.playbackTime-t)}break}case"ArrowRight":{if(e.metaKey)this.edit.seek(this.edit.getTotalDuration());else{const t=e.shiftKey?this.seekDistanceLarge:this.seekDistance;this.edit.seek(this.edit.playbackTime+t)}break}case"KeyJ":{this.edit.stop();break}case"KeyK":{this.edit.pause();break}case"KeyL":{this.edit.play();break}case"Comma":{this.edit.seek(this.edit.playbackTime-this.frameTime);break}case"Period":{this.edit.seek(this.edit.playbackTime+this.frameTime);break}case"KeyZ":{(e.metaKey||e.ctrlKey)&&(e.preventDefault(),e.shiftKey?this.edit.redo():this.edit.undo());break}case"Delete":case"Backspace":{const t=this.edit.getSelectedClipInfo();t&&(e.preventDefault(),this.edit.deleteClip(t.trackIndex,t.clipIndex));break}}};handleKeyUp=e=>{if(!(e.target instanceof HTMLInputElement||e.target instanceof HTMLTextAreaElement))switch(e.code){case"KeyI":console.log(this.edit.getEdit());break}}}class Jo{name="export";clips=[];tracks=[];execute(e){this.clips=e.getClips(),this.tracks=e.getTracks()}getClips(){return this.clips}getTracks(){return this.tracks}}/*!
188
+ * Copyright (c) 2025-present, Vanilagy and contributors
189
+ *
190
+ * This Source Code Form is subject to the terms of the Mozilla Public
191
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
192
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
193
+ */function $(s){if(!s)throw new Error("Assertion failed.")}const ze=s=>s&&s[s.length-1],Ft=s=>s>=0&&s<2**32;class Yt{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),t=this.bytes[e]??0,i=7-(this.pos&7),r=(t&1<<i)>>i;return this.pos++,r}readBits(e){if(e===1)return this.readBit();let t=0;for(let i=0;i<e;i++)t<<=1,t|=this.readBit();return t}writeBits(e,t){const i=this.pos+e;for(let r=this.pos;r<i;r++){const n=Math.floor(r/8);let o=this.bytes[n];const a=7-(r&7);o&=~(1<<a),o|=(t&1<<i-r-1)>>i-r-1<<a,this.bytes[n]=o}this.pos=i}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");const e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){const e=new Yt(this.bytes);return e.pos=this.pos,e}}const W=s=>{let e=0;for(;s.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+s.readBits(e)},Qt=s=>{const e=W(s);return e&1?e+1>>1:-(e>>1)},ot=s=>s.constructor===Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength),Fr=s=>s.constructor===DataView?s:s instanceof ArrayBuffer?new DataView(s):new DataView(s.buffer,s.byteOffset,s.byteLength);new TextDecoder;const He=new TextEncoder,ns=s=>Object.fromEntries(Object.entries(s).map(([e,t])=>[t,e])),vi={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12};ns(vi);const wi={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pg:16,hlg:18};ns(wi);const _i={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9};ns(_i);const el=s=>!!s&&!!s.primaries&&!!s.transfer&&!!s.matrix&&s.fullRange!==void 0,xi=s=>s instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&s instanceof SharedArrayBuffer||ArrayBuffer.isView(s);class Mr{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e;const t=new Promise(r=>{e=r}),i=this.currentPromise;return this.currentPromise=t,await i,e}}const tl=()=>{let s,e;return{promise:new Promise((i,r)=>{s=i,e=r}),resolve:s,reject:e}},as=s=>{throw new Error(`Unexpected value: ${s}`)},Lr=(s,e,t,i)=>{t=t>>>0,t=t&16777215,i?(s.setUint8(e,t&255),s.setUint8(e+1,t>>>8&255),s.setUint8(e+2,t>>>16&255)):(s.setUint8(e,t>>>16&255),s.setUint8(e+1,t>>>8&255),s.setUint8(e+2,t&255))},il=(s,e,t,i)=>{t=Se(t,-8388608,8388607),t<0&&(t=t+16777216&16777215),Lr(s,e,t,i)},Se=(s,e,t)=>Math.max(e,Math.min(t,s)),sl="und",rl=/^[a-z]{3}$/,nl=s=>rl.test(s),lt=1e6*(1+Number.EPSILON),al=(s,e)=>{const t=s<0?-1:1;s=Math.abs(s);let i=0,r=1,n=1,o=0,a=s;for(;;){const p=Math.floor(a),m=p*n+i,d=p*o+r;if(d>e)return{numerator:t*n,denominator:o};if(i=n,r=o,n=m,o=d,a=1/(a-p),!isFinite(a))break}return{numerator:t*n,denominator:o}};class Br{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let os=null;const ls=()=>os!==null?os:os=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox"),$r=function*(s){for(const e in s){const t=s[e];t!==void 0&&(yield{key:e,value:t})}},ol=()=>{Symbol.dispose??=Symbol("Symbol.dispose")};/*!
194
+ * Copyright (c) 2025-present, Vanilagy and contributors
195
+ *
196
+ * This Source Code Form is subject to the terms of the Mozilla Public
197
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
198
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
199
+ */class Dr{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof t!="string")throw new TypeError("mimeType must be a string.")}}class ll{constructor(e,t,i,r){if(this.data=e,this.mimeType=t,this.name=i,this.description=r,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!==void 0&&typeof t!="string")throw new TypeError("mimeType, when provided, must be a string.");if(i!==void 0&&typeof i!="string")throw new TypeError("name, when provided, must be a string.");if(r!==void 0&&typeof r!="string")throw new TypeError("description, when provided, must be a string.")}}const cl=s=>{if(!s||typeof s!="object")throw new TypeError("tags must be an object.");if(s.title!==void 0&&typeof s.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(s.description!==void 0&&typeof s.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(s.artist!==void 0&&typeof s.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(s.album!==void 0&&typeof s.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(s.albumArtist!==void 0&&typeof s.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(s.trackNumber!==void 0&&(!Number.isInteger(s.trackNumber)||s.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(s.tracksTotal!==void 0&&(!Number.isInteger(s.tracksTotal)||s.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(s.discNumber!==void 0&&(!Number.isInteger(s.discNumber)||s.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(s.discsTotal!==void 0&&(!Number.isInteger(s.discsTotal)||s.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(s.genre!==void 0&&typeof s.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(s.date!==void 0&&(!(s.date instanceof Date)||Number.isNaN(s.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(s.lyrics!==void 0&&typeof s.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(s.images!==void 0){if(!Array.isArray(s.images))throw new TypeError("tags.images, when provided, must be an array.");for(const e of s.images){if(!e||typeof e!="object")throw new TypeError("Each image in tags.images must be an object.");if(!(e.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if(typeof e.mimeType!="string")throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(e.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(s.comment!==void 0&&typeof s.comment!="string")throw new TypeError("tags.comment, when provided, must be a string.");if(s.raw!==void 0){if(!s.raw||typeof s.raw!="object")throw new TypeError("tags.raw, when provided, must be an object.");for(const e of Object.values(s.raw))if(e!==null&&typeof e!="string"&&!(e instanceof Uint8Array)&&!(e instanceof Dr)&&!(e instanceof ll))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, or null.")}};/*!
200
+ * Copyright (c) 2025-present, Vanilagy and contributors
201
+ *
202
+ * This Source Code Form is subject to the terms of the Mozilla Public
203
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
204
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
205
+ */const bt=["avc","hevc","vp9","av1","vp8"],Ne=["pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be","pcm-u8","pcm-s8","ulaw","alaw"],zr=["aac","opus","mp3","vorbis","flac"],Mt=[...zr,...Ne],Ci=["webvtt"],Hr=[{maxMacroblocks:99,maxBitrate:64e3,level:10},{maxMacroblocks:396,maxBitrate:192e3,level:11},{maxMacroblocks:396,maxBitrate:384e3,level:12},{maxMacroblocks:396,maxBitrate:768e3,level:13},{maxMacroblocks:396,maxBitrate:2e6,level:20},{maxMacroblocks:792,maxBitrate:4e6,level:21},{maxMacroblocks:1620,maxBitrate:4e6,level:22},{maxMacroblocks:1620,maxBitrate:1e7,level:30},{maxMacroblocks:3600,maxBitrate:14e6,level:31},{maxMacroblocks:5120,maxBitrate:2e7,level:32},{maxMacroblocks:8192,maxBitrate:2e7,level:40},{maxMacroblocks:8192,maxBitrate:5e7,level:41},{maxMacroblocks:8704,maxBitrate:5e7,level:42},{maxMacroblocks:22080,maxBitrate:135e6,level:50},{maxMacroblocks:36864,maxBitrate:24e7,level:51},{maxMacroblocks:36864,maxBitrate:24e7,level:52},{maxMacroblocks:139264,maxBitrate:24e7,level:60},{maxMacroblocks:139264,maxBitrate:48e7,level:61},{maxMacroblocks:139264,maxBitrate:8e8,level:62}],Nr=[{maxPictureSize:36864,maxBitrate:128e3,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:"L",level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:"L",level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:"L",level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:186}],Ur=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],jr=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:"H",level:19}],hl=(s,e,t,i)=>{if(s==="avc"){const n=Math.ceil(e/16)*Math.ceil(t/16),o=Hr.find(l=>n<=l.maxMacroblocks&&i<=l.maxBitrate)??ze(Hr),a=o?o.level:0,p="64".padStart(2,"0"),m="00",d=a.toString(16).padStart(2,"0");return`avc1.${p}${m}${d}`}else if(s==="hevc"){const r="",o="6",a=e*t,p=Nr.find(d=>a<=d.maxPictureSize&&i<=d.maxBitrate)??ze(Nr);return`hev1.${r}1.${o}.${p.tier}${p.level}.B0`}else{if(s==="vp8")return"vp8";if(s==="vp9"){const r="00",n=e*t,o=Ur.find(p=>n<=p.maxPictureSize&&i<=p.maxBitrate)??ze(Ur);return`vp09.${r}.${o.level.toString().padStart(2,"0")}.08`}else if(s==="av1"){const n=e*t,o=jr.find(m=>n<=m.maxPictureSize&&i<=m.maxBitrate)??ze(jr);return`av01.0.${o.level.toString().padStart(2,"0")}${o.tier}.08`}}throw new TypeError(`Unhandled codec '${s}'.`)},ul=s=>{const e=s.split("."),r=(1<<7)+1,n=Number(e[1]),o=e[2],a=Number(o.slice(0,-1)),p=(n<<5)+a,m=o.slice(-1)==="H"?1:0,l=Number(e[3])===8?0:1,c=0,u=e[4]?Number(e[4]):0,h=e[5]?Number(e[5][0]):1,f=e[5]?Number(e[5][1]):1,b=e[5]?Number(e[5][2]):0,g=(m<<7)+(l<<6)+(c<<5)+(u<<4)+(h<<3)+(f<<2)+b;return[r,p,g,0]},dl=(s,e,t)=>{if(s==="aac")return e>=2&&t<=24e3?"mp4a.40.29":t<=24e3?"mp4a.40.5":"mp4a.40.2";if(s==="mp3")return"mp3";if(s==="opus")return"opus";if(s==="vorbis")return"vorbis";if(s==="flac")return"flac";if(Ne.includes(s))return s;throw new TypeError(`Unhandled codec '${s}'.`)},Vr=/^pcm-([usf])(\d+)+(be)?$/,Lt=s=>{if($(Ne.includes(s)),s==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(s==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const e=Vr.exec(s);$(e);let t;e[1]==="u"?t="unsigned":e[1]==="s"?t="signed":t="float";const i=Number(e[2])/8,r=e[3]!=="be",n=s==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:i,littleEndian:r,silentValue:n}},Wr=s=>s.startsWith("avc1")||s.startsWith("avc3")?"avc":s.startsWith("hev1")||s.startsWith("hvc1")?"hevc":s==="vp8"?"vp8":s.startsWith("vp09")?"vp9":s.startsWith("av01")?"av1":s.startsWith("mp4a.40")||s==="mp4a.67"?"aac":s==="mp3"||s==="mp4a.69"||s==="mp4a.6B"||s==="mp4a.6b"?"mp3":s==="opus"?"opus":s==="vorbis"?"vorbis":s==="flac"?"flac":s==="ulaw"?"ulaw":s==="alaw"?"alaw":Vr.test(s)?s:s==="webvtt"?"webvtt":null,fl=s=>s==="avc"?{avc:{format:"avc"}}:s==="hevc"?{hevc:{format:"hevc"}}:{},pl=s=>s==="aac"?{aac:{format:"aac"}}:s==="opus"?{opus:{format:"opus"}}:{},ml=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],gl=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,yl=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,bl=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,vl=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,wl=s=>{if(!s)throw new TypeError("Video chunk metadata must be provided.");if(typeof s!="object")throw new TypeError("Video chunk metadata must be an object.");if(!s.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof s.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof s.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!ml.some(e=>s.decoderConfig.codec.startsWith(e)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(s.decoderConfig.codedWidth)||s.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(s.decoderConfig.codedHeight)||s.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(s.decoderConfig.description!==void 0&&!xi(s.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(s.decoderConfig.colorSpace!==void 0){const{colorSpace:e}=s.decoderConfig;if(typeof e!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const t=Object.keys(vi);if(e.primaries!=null&&!t.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${t.join(", ")}.`);const i=Object.keys(wi);if(e.transfer!=null&&!i.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${i.join(", ")}.`);const r=Object.keys(_i);if(e.matrix!=null&&!r.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${r.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(s.decoderConfig.codec.startsWith("avc1")||s.decoderConfig.codec.startsWith("avc3")){if(!gl.test(s.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(s.decoderConfig.codec.startsWith("hev1")||s.decoderConfig.codec.startsWith("hvc1")){if(!yl.test(s.decoderConfig.codec))throw new TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(s.decoderConfig.codec.startsWith("vp8")){if(s.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(s.decoderConfig.codec.startsWith("vp09")){if(!bl.test(s.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(s.decoderConfig.codec.startsWith("av01")&&!vl.test(s.decoderConfig.codec))throw new TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')},_l=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm"],xl=s=>{if(!s)throw new TypeError("Audio chunk metadata must be provided.");if(typeof s!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!s.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof s.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof s.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!_l.some(e=>s.decoderConfig.codec.startsWith(e)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the WebCodecs Codec Registry.");if(!Number.isInteger(s.decoderConfig.sampleRate)||s.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(s.decoderConfig.numberOfChannels)||s.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(s.decoderConfig.description!==void 0&&!xi(s.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(s.decoderConfig.codec.startsWith("mp4a")&&s.decoderConfig.codec!=="mp4a.69"&&s.decoderConfig.codec!=="mp4a.6B"&&s.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(s.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.");if(!s.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for AAC must include a description, which is expected to be an AudioSpecificConfig as specified in ISO 14496-3.")}else if(s.decoderConfig.codec.startsWith("mp3")||s.decoderConfig.codec.startsWith("mp4a")){if(s.decoderConfig.codec!=="mp3"&&s.decoderConfig.codec!=="mp4a.69"&&s.decoderConfig.codec!=="mp4a.6B"&&s.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(s.decoderConfig.codec.startsWith("opus")){if(s.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(s.decoderConfig.description&&s.decoderConfig.description.byteLength<18)throw new TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(s.decoderConfig.codec.startsWith("vorbis")){if(s.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!s.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(s.decoderConfig.codec.startsWith("flac")){if(s.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!s.decoderConfig.description||s.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if((s.decoderConfig.codec.startsWith("pcm")||s.decoderConfig.codec.startsWith("ulaw")||s.decoderConfig.codec.startsWith("alaw"))&&!Ne.includes(s.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${Ne.join(", ")}).`)},Cl=s=>{if(!s)throw new TypeError("Subtitle metadata must be provided.");if(typeof s!="object")throw new TypeError("Subtitle metadata must be an object.");if(!s.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof s.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof s.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")};/*!
206
+ * Copyright (c) 2025-present, Vanilagy and contributors
207
+ *
208
+ * This Source Code Form is subject to the terms of the Mozilla Public
209
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
210
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
211
+ */class kl{constructor(e){this.mutex=new Mr,this.firstMediaStreamTimestamp=null,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,t,i){t+=e.source._timestampOffset;let r=this.trackTimestampInfo.get(e);if(!r){if(!i)throw new Error("First frame must be a key frame.");r={maxTimestamp:t,maxTimestampBeforeLastKeyFrame:t},this.trackTimestampInfo.set(e,r)}if(t<0)throw new Error(`Timestamps must be non-negative (got ${t}s).`);if(i&&(r.maxTimestampBeforeLastKeyFrame=r.maxTimestamp),t<r.maxTimestampBeforeLastKeyFrame)throw new Error(`Timestamps cannot be smaller than the highest timestamp of the previous GOP (a GOP begins with a key frame and ends right before the next key frame). Got ${t}s, but highest timestamp is ${r.maxTimestampBeforeLastKeyFrame}s.`);return r.maxTimestamp=Math.max(r.maxTimestamp,t),t}}/*!
212
+ * Copyright (c) 2025-present, Vanilagy and contributors
213
+ *
214
+ * This Source Code Form is subject to the terms of the Mozilla Public
215
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
216
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
217
+ */var Jt;(function(s){s[s.IDR=5]="IDR",s[s.SPS=7]="SPS",s[s.PPS=8]="PPS",s[s.SPS_EXT=13]="SPS_EXT"})(Jt||(Jt={}));var Ue;(function(s){s[s.RASL_N=8]="RASL_N",s[s.RASL_R=9]="RASL_R",s[s.BLA_W_LP=16]="BLA_W_LP",s[s.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",s[s.VPS_NUT=32]="VPS_NUT",s[s.SPS_NUT=33]="SPS_NUT",s[s.PPS_NUT=34]="PPS_NUT",s[s.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",s[s.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(Ue||(Ue={}));const cs=s=>{const e=[];let t=0;for(;t<s.length;){let i=-1,r=0;for(let n=t;n<s.length-3;n++){if(s[n]===0&&s[n+1]===0&&s[n+2]===1){i=n,r=3;break}if(n<s.length-4&&s[n]===0&&s[n+1]===0&&s[n+2]===0&&s[n+3]===1){i=n,r=4;break}}if(i===-1)break;if(t>0&&i>t){const n=s.subarray(t,i);n.length>0&&e.push(n)}t=i+r}if(t<s.length){const i=s.subarray(t);i.length>0&&e.push(i)}return e},hs=s=>{const e=[],t=s.length;for(let i=0;i<t;i++)i+2<t&&s[i]===0&&s[i+1]===0&&s[i+2]===3?(e.push(0,0),i+=2):e.push(s[i]);return new Uint8Array(e)},Tl=s=>{const t=cs(s);if(t.length===0)return null;let i=0;for(const a of t)i+=4+a.byteLength;const r=new Uint8Array(i),n=new DataView(r.buffer);let o=0;for(const a of t){const p=a.byteLength;n.setUint32(o,p,!1),o+=4,r.set(a,o),o+=a.byteLength}return r},us=s=>s[0]&31,Sl=s=>{try{const e=cs(s),t=e.filter(c=>us(c)===Jt.SPS),i=e.filter(c=>us(c)===Jt.PPS),r=e.filter(c=>us(c)===Jt.SPS_EXT);if(t.length===0||i.length===0)return null;const n=t[0],o=new Yt(hs(n));if(o.skipBits(1),o.skipBits(2),o.readBits(5)!==7)return console.error("Invalid SPS NAL unit type"),null;const p=o.readAlignedByte(),m=o.readAlignedByte(),d=o.readAlignedByte(),l={configurationVersion:1,avcProfileIndication:p,profileCompatibility:m,avcLevelIndication:d,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:i,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if(p===100||p===110||p===122||p===144){W(o);const c=W(o);c===3&&o.skipBits(1);const u=W(o),h=W(o);l.chromaFormat=c,l.bitDepthLumaMinus8=u,l.bitDepthChromaMinus8=h,l.sequenceParameterSetExt=r}return l}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}},El=s=>{const e=[];e.push(s.configurationVersion),e.push(s.avcProfileIndication),e.push(s.profileCompatibility),e.push(s.avcLevelIndication),e.push(252|s.lengthSizeMinusOne&3),e.push(224|s.sequenceParameterSets.length&31);for(const t of s.sequenceParameterSets){const i=t.byteLength;e.push(i>>8),e.push(i&255);for(let r=0;r<i;r++)e.push(t[r])}e.push(s.pictureParameterSets.length);for(const t of s.pictureParameterSets){const i=t.byteLength;e.push(i>>8),e.push(i&255);for(let r=0;r<i;r++)e.push(t[r])}if(s.avcProfileIndication===100||s.avcProfileIndication===110||s.avcProfileIndication===122||s.avcProfileIndication===144){$(s.chromaFormat!==null),$(s.bitDepthLumaMinus8!==null),$(s.bitDepthChromaMinus8!==null),$(s.sequenceParameterSetExt!==null),e.push(252|s.chromaFormat&3),e.push(248|s.bitDepthLumaMinus8&7),e.push(248|s.bitDepthChromaMinus8&7),e.push(s.sequenceParameterSetExt.length);for(const t of s.sequenceParameterSetExt){const i=t.byteLength;e.push(i>>8),e.push(i&255);for(let r=0;r<i;r++)e.push(t[r])}}return new Uint8Array(e)},Bt=s=>s[0]>>1&63,Al=s=>{try{const e=cs(s),t=e.filter(k=>Bt(k)===Ue.VPS_NUT),i=e.filter(k=>Bt(k)===Ue.SPS_NUT),r=e.filter(k=>Bt(k)===Ue.PPS_NUT),n=e.filter(k=>Bt(k)===Ue.PREFIX_SEI_NUT||Bt(k)===Ue.SUFFIX_SEI_NUT);if(i.length===0||r.length===0)return null;const o=i[0],a=new Yt(hs(o));a.skipBits(16),a.readBits(4);const p=a.readBits(3),m=a.readBits(1),{general_profile_space:d,general_tier_flag:l,general_profile_idc:c,general_profile_compatibility_flags:u,general_constraint_indicator_flags:h,general_level_idc:f}=Il(a,p);W(a);const b=W(a);b===3&&a.skipBits(1),W(a),W(a),a.readBits(1)&&(W(a),W(a),W(a),W(a));const g=W(a),y=W(a);W(a);const _=a.readBits(1)?0:p;for(let k=_;k<=p;k++)W(a),W(a),W(a);W(a),W(a),W(a),W(a),W(a),W(a),a.readBits(1)&&a.readBits(1)&&Pl(a),a.skipBits(1),a.skipBits(1),a.readBits(1)&&(a.skipBits(4),a.skipBits(4),W(a),W(a),a.skipBits(1));const C=W(a);if(Rl(a,C),a.readBits(1)){const k=W(a);for(let E=0;E<k;E++)W(a),a.skipBits(1)}a.skipBits(1),a.skipBits(1);let S=0;a.readBits(1)&&(S=Fl(a,p));let T=0;if(r.length>0){const k=r[0],E=new Yt(hs(k));E.skipBits(16),W(E),W(E),E.skipBits(1),E.skipBits(1),E.skipBits(3),E.skipBits(1),E.skipBits(1),W(E),W(E),Qt(E),E.skipBits(1),E.skipBits(1),E.readBits(1)&&W(E),Qt(E),Qt(E),E.skipBits(1),E.skipBits(1),E.skipBits(1),E.skipBits(1);const P=E.readBits(1),O=E.readBits(1);!P&&!O?T=0:P&&!O?T=2:!P&&O?T=3:T=0}const w=[...t.length?[{arrayCompleteness:1,nalUnitType:Ue.VPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Ue.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Ue.PPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:Bt(n[0]),nalUnits:n}]:[]];return{configurationVersion:1,generalProfileSpace:d,generalTierFlag:l,generalProfileIdc:c,generalProfileCompatibilityFlags:u,generalConstraintIndicatorFlags:h,generalLevelIdc:f,minSpatialSegmentationIdc:S,parallelismType:T,chromaFormatIdc:b,bitDepthLumaMinus8:g,bitDepthChromaMinus8:y,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:p+1,temporalIdNested:m,lengthSizeMinusOne:3,arrays:w}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},Il=(s,e)=>{const t=s.readBits(2),i=s.readBits(1),r=s.readBits(5);let n=0;for(let d=0;d<32;d++)n=n<<1|s.readBits(1);const o=new Uint8Array(6);for(let d=0;d<6;d++)o[d]=s.readBits(8);const a=s.readBits(8),p=[],m=[];for(let d=0;d<e;d++)p.push(s.readBits(1)),m.push(s.readBits(1));if(e>0)for(let d=e;d<8;d++)s.skipBits(2);for(let d=0;d<e;d++)p[d]&&s.skipBits(88),m[d]&&s.skipBits(8);return{general_profile_space:t,general_tier_flag:i,general_profile_idc:r,general_profile_compatibility_flags:n,general_constraint_indicator_flags:o,general_level_idc:a}},Pl=s=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!s.readBits(1))W(s);else{const r=Math.min(64,1<<4+(e<<1));e>1&&Qt(s);for(let n=0;n<r;n++)Qt(s)}},Rl=(s,e)=>{const t=[];for(let i=0;i<e;i++)t[i]=Ol(s,i,e,t)},Ol=(s,e,t,i)=>{let r=0,n=0,o=0;if(e!==0&&(n=s.readBits(1)),n){if(e===t){const p=W(s);o=e-(p+1)}else o=e-1;s.readBits(1),W(s);const a=i[o]??0;for(let p=0;p<=a;p++)s.readBits(1)||s.readBits(1);r=i[o]}else{const a=W(s),p=W(s);for(let m=0;m<a;m++)W(s),s.readBits(1);for(let m=0;m<p;m++)W(s),s.readBits(1);r=a+p}return r},Fl=(s,e)=>{if(s.readBits(1)&&s.readBits(8)===255&&(s.readBits(16),s.readBits(16)),s.readBits(1)&&s.readBits(1),s.readBits(1)&&(s.readBits(3),s.readBits(1),s.readBits(1)&&(s.readBits(8),s.readBits(8),s.readBits(8))),s.readBits(1)&&(W(s),W(s)),s.readBits(1),s.readBits(1),s.readBits(1),s.readBits(1)&&(W(s),W(s),W(s),W(s)),s.readBits(1)&&(s.readBits(32),s.readBits(32),s.readBits(1)&&W(s),s.readBits(1)&&Ml(s,!0,e)),s.readBits(1)){s.readBits(1),s.readBits(1),s.readBits(1);const t=W(s);return W(s),W(s),W(s),W(s),t}return 0},Ml=(s,e,t)=>{let i=!1,r=!1,n=!1;i=s.readBits(1)===1,r=s.readBits(1)===1,(i||r)&&(n=s.readBits(1)===1,n&&(s.readBits(8),s.readBits(5),s.readBits(1),s.readBits(5)),s.readBits(4),s.readBits(4),n&&s.readBits(4),s.readBits(5),s.readBits(5),s.readBits(5));for(let o=0;o<=t;o++){const a=s.readBits(1)===1;let p=!0;a||(p=s.readBits(1)===1);let m=!1;p?W(s):m=s.readBits(1)===1;let d=1;m||(d=W(s)+1),i&&Gr(s,d,n),r&&Gr(s,d,n)}},Gr=(s,e,t)=>{for(let i=0;i<e;i++)W(s),W(s),t&&(W(s),W(s)),s.readBits(1)},Ll=s=>{const e=[];e.push(s.configurationVersion),e.push((s.generalProfileSpace&3)<<6|(s.generalTierFlag&1)<<5|s.generalProfileIdc&31),e.push(s.generalProfileCompatibilityFlags>>>24&255),e.push(s.generalProfileCompatibilityFlags>>>16&255),e.push(s.generalProfileCompatibilityFlags>>>8&255),e.push(s.generalProfileCompatibilityFlags&255),e.push(...s.generalConstraintIndicatorFlags),e.push(s.generalLevelIdc&255),e.push(240|s.minSpatialSegmentationIdc>>8&15),e.push(s.minSpatialSegmentationIdc&255),e.push(252|s.parallelismType&3),e.push(252|s.chromaFormatIdc&3),e.push(248|s.bitDepthLumaMinus8&7),e.push(248|s.bitDepthChromaMinus8&7),e.push(s.avgFrameRate>>8&255),e.push(s.avgFrameRate&255),e.push((s.constantFrameRate&3)<<6|(s.numTemporalLayers&7)<<3|(s.temporalIdNested&1)<<2|s.lengthSizeMinusOne&3),e.push(s.arrays.length&255);for(const t of s.arrays){e.push((t.arrayCompleteness&1)<<7|0|t.nalUnitType&63),e.push(t.nalUnits.length>>8&255),e.push(t.nalUnits.length&255);for(const i of t.nalUnits){e.push(i.length>>8&255),e.push(i.length&255);for(let r=0;r<i.length;r++)e.push(i[r])}}return new Uint8Array(e)},Bl=s=>{const e=Fr(s),t=e.getUint8(9),i=e.getUint16(10,!0),r=e.getUint32(12,!0),n=e.getInt16(16,!0),o=e.getUint8(18);let a=null;return o&&(a=s.subarray(19,21+t)),{outputChannelCount:t,preSkip:i,inputSampleRate:r,outputGain:n,channelMappingFamily:o,channelMappingTable:a}};var Zr;(function(s){s[s.STREAMINFO=0]="STREAMINFO",s[s.VORBIS_COMMENT=4]="VORBIS_COMMENT",s[s.PICTURE=6]="PICTURE"})(Zr||(Zr={}));/*!
218
+ * Copyright (c) 2025-present, Vanilagy and contributors
219
+ *
220
+ * This Source Code Form is subject to the terms of the Mozilla Public
221
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
222
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
223
+ */const $l=[],Dl=[];/*!
224
+ * Copyright (c) 2025-present, Vanilagy and contributors
225
+ *
226
+ * This Source Code Form is subject to the terms of the Mozilla Public
227
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
228
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
229
+ */const Kr=new Uint8Array(0);class ct{constructor(e,t,i,r,n=-1,o,a){if(this.data=e,this.type=t,this.timestamp=i,this.duration=r,this.sequenceNumber=n,e===Kr&&o===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(o===void 0&&(o=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!=="key"&&t!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(r)||r<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(n))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(o)||o<0)throw new TypeError("byteLength must be a non-negative integer.");if(a!==void 0&&(typeof a!="object"||!a))throw new TypeError("sideData, when provided, must be an object.");if(a?.alpha!==void 0&&!(a.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(a?.alphaByteLength!==void 0&&(!Number.isInteger(a.alphaByteLength)||a.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=o,this.sideData=a??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===Kr}get microsecondTimestamp(){return Math.trunc(lt*this.timestamp)}get microsecondDuration(){return Math.trunc(lt*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const i=new Uint8Array(e.byteLength);return e.copyTo(i),new ct(i,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if(e?.timestamp!==void 0&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");return new ct(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}}/*!
230
+ * Copyright (c) 2025-present, Vanilagy and contributors
231
+ *
232
+ * This Source Code Form is subject to the terms of the Mozilla Public
233
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
234
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
235
+ */const zl=s=>{let i=s,r=4096,n=0,o=12,a=0;for(i<0&&(i=-i,n=128),i+=33,i>8191&&(i=8191);(i&r)!==r&&o>=5;)r>>=1,o--;return a=i>>o-4&15,~(n|o-5<<4|a)&255},Hl=s=>{let t=2048,i=0,r=11,n=0,o=s;for(o<0&&(o=-o,i=128),o>4095&&(o=4095);(o&t)!==t&&r>=5;)t>>=1,r--;return n=o>>(r===4?1:r-4)&15,(i|r-4<<4|n)^85};/*!
236
+ * Copyright (c) 2025-present, Vanilagy and contributors
237
+ *
238
+ * This Source Code Form is subject to the terms of the Mozilla Public
239
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
240
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
241
+ */ol();class vt{get displayWidth(){return this.rotation%180===0?this.codedWidth:this.codedHeight}get displayHeight(){return this.rotation%180===0?this.codedHeight:this.codedWidth}get microsecondTimestamp(){return Math.trunc(lt*this.timestamp)}get microsecondDuration(){return Math.trunc(lt*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){if(this._closed=!1,e instanceof ArrayBuffer||ArrayBuffer.isView(e)){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(!("format"in t)||typeof t.format!="string")throw new TypeError("init.format must be a string.");if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=ot(e).slice(),this.format=t.format,this.codedWidth=t.codedWidth,this.codedHeight=t.codedHeight,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new VideoColorSpace(t.colorSpace)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if(t?.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(t?.timestamp!==void 0&&!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(t?.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");this._data=e,this.format=e.format,this.codedWidth=e.displayWidth,this.codedHeight=e.displayHeight,this.rotation=t?.rotation??0,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6,this.colorSpace=e.colorSpace}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof SVGImageElement<"u"&&e instanceof SVGImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new vt(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*lt),duration:Math.trunc((t.duration??0)*lt)||void 0}),t);let i=0,r=0;if("naturalWidth"in e?(i=e.naturalWidth,r=e.naturalHeight):"videoWidth"in e?(i=e.videoWidth,r=e.videoHeight):"width"in e&&(i=Number(e.width),r=Number(e.height)),!i||!r)throw new TypeError("Could not determine dimensions.");const n=new OffscreenCanvas(i,r),o=n.getContext("2d",{alpha:ls(),willReadFrequently:!0});$(o),o.drawImage(e,0,0),this._data=n,this.format="RGBX",this.codedWidth=i,this.codedHeight=r,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new VideoColorSpace({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.")}clone(){if(this._closed)throw new Error("VideoSample is closed.");return $(this._data!==null),ei(this._data)?new vt(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?new vt(this._data.slice(),{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation}):new vt(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})}close(){this._closed||(ei(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(){if(this._closed)throw new Error("VideoSample is closed.");return $(this._data!==null),ei(this._data)?this._data.allocationSize():this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e){if(!xi(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(this._closed)throw new Error("VideoSample is closed.");if($(this._data!==null),ei(this._data))await this._data.copyTo(e);else if(this._data instanceof Uint8Array)ot(e).set(this._data);else{const i=this._data.getContext("2d");$(i);const r=i.getImageData(0,0,this.codedWidth,this.codedHeight);ot(e).set(r.data)}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return $(this._data!==null),ei(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,i,r,n,o,a,p,m){let d=0,l=0,c=this.displayWidth,u=this.displayHeight,h=0,f=0,b=this.displayWidth,g=this.displayHeight;if(o!==void 0?(d=t,l=i,c=r,u=n,h=o,f=a,p!==void 0?(b=p,g=m):(b=c,g=u)):(h=t,f=i,r!==void 0&&(b=r,g=n)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(d))throw new TypeError("sx must be a number.");if(!Number.isFinite(l))throw new TypeError("sy must be a number.");if(!Number.isFinite(c)||c<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(u)||u<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(h))throw new TypeError("dx must be a number.");if(!Number.isFinite(f))throw new TypeError("dy must be a number.");if(!Number.isFinite(b)||b<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:d,sy:l,sWidth:c,sHeight:u}=this._rotateSourceRegion(d,l,c,u,this.rotation));const y=this.toCanvasImageSource();e.save();const v=h+b/2,_=f+g/2;e.translate(v,_),e.rotate(this.rotation*Math.PI/180);const C=this.rotation%180===0?1:b/g;e.scale(1/C,C),e.drawImage(y,d,l,c,u,-b/2,-g/2,b,g),e.restore()}drawWithFit(e,t){if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");t.crop!==void 0&&Ul(t.crop,"options.");const i=e.canvas.width,r=e.canvas.height,n=t.rotation??this.rotation,[o,a]=n%180===0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth];t.crop&&Nl(t.crop,o,a);let p,m,d,l;const{sx:c,sy:u,sWidth:h,sHeight:f}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??o,t.crop?.height??a,n);if(t.fit==="fill")p=0,m=0,d=i,l=r;else{const[g,y]=t.crop?[t.crop.width,t.crop.height]:[o,a],v=t.fit==="contain"?Math.min(i/g,r/y):Math.max(i/g,r/y);d=g*v,l=y*v,p=(i-d)/2,m=(r-l)/2}const b=n%180===0?1:d/l;e.translate(i/2,r/2),e.rotate(n*Math.PI/180),e.scale(1/b,b),e.translate(-i/2,-r/2),e.drawImage(this.toCanvasImageSource(),c,u,h,f,p,m,d,l)}_rotateSourceRegion(e,t,i,r,n){return n===90?[e,t,i,r]=[t,this.codedHeight-e-i,r,i]:n===180?[e,t]=[this.codedWidth-e-i,this.codedHeight-t-r]:n===270&&([e,t,i,r]=[this.codedWidth-t-r,e,r,i]),{sx:e,sy:t,sWidth:i,sHeight:r}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if($(this._data!==null),this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}[Symbol.dispose](){this.close()}}const ei=s=>typeof VideoFrame<"u"&&s instanceof VideoFrame,Nl=(s,e,t)=>{s.left=Math.min(s.left,e),s.top=Math.min(s.top,t),s.width=Math.min(s.width,e-s.left),s.height=Math.min(s.height,t-s.top),$(s.width>=0),$(s.height>=0)},Ul=(s,e)=>{if(!s||typeof s!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(s.left)||s.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(s.top)||s.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(s.width)||s.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(s.height)||s.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},ds=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class wt{get microsecondTimestamp(){return Math.trunc(lt*this.timestamp)}get microsecondDuration(){return Math.trunc(lt*this.duration)}constructor(e){if(this._closed=!1,ii(e)){if(e.format===null)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else{if(!e||typeof e!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!ds.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(ti(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate;let i;if(e.data instanceof ArrayBuffer)i=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))i=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");const r=this.numberOfFrames*this.numberOfChannels*ti(this.format);if(i.byteLength<r)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=i}}allocationSize(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(e.format!==void 0&&!ds.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const t=e.format??this.format,i=e.frameOffset??0;if(i>=this.numberOfFrames)throw new RangeError("frameOffset out of range");const r=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-i;if(r>this.numberOfFrames-i)throw new RangeError("frameCount out of range");const n=ti(t),o=ki(t);if(o&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!o&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(o?r:r*this.numberOfChannels)*n}copyTo(e,t){if(!xi(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(t.format!==void 0&&!ds.has(t.format))throw new TypeError("Invalid format.");if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{planeIndex:i,format:r,frameCount:n,frameOffset:o}=t,a=r??this.format;if(!a)throw new Error("Destination format not determined");const p=this.numberOfFrames,m=this.numberOfChannels,d=o??0;if(d>=p)throw new RangeError("frameOffset out of range");const l=n!==void 0?n:p-d;if(l>p-d)throw new RangeError("frameCount out of range");const c=ti(a),u=ki(a);if(u&&i>=m)throw new RangeError("planeIndex out of range");if(!u&&i!==0)throw new RangeError("planeIndex out of range");const f=(u?l:l*m)*c;if(e.byteLength<f)throw new RangeError("Destination buffer is too small");const b=Fr(e),g=Vl(a);if(ii(this._data))if(u)if(a==="f32-planar")this._data.copyTo(e,{planeIndex:i,frameOffset:d,frameCount:l,format:"f32-planar"});else{const y=new ArrayBuffer(l*4),v=new Float32Array(y);this._data.copyTo(v,{planeIndex:i,frameOffset:d,frameCount:l,format:"f32-planar"});const _=new DataView(y);for(let C=0;C<l;C++){const S=C*c,T=_.getFloat32(C*4,!0);g(b,S,T)}}else{const y=m,v=new Float32Array(l);for(let _=0;_<y;_++){this._data.copyTo(v,{planeIndex:_,frameOffset:d,frameCount:l,format:"f32-planar"});for(let C=0;C<l;C++){const T=(C*y+_)*c;g(b,T,v[C])}}}else{const y=this._data,v=new DataView(y.buffer,y.byteOffset,y.byteLength),_=this.format,C=jl(_),S=ti(_),T=ki(_);for(let w=0;w<l;w++)if(u){const x=w*c;let k;T?k=(i*p+(w+d))*S:k=((w+d)*m+i)*S;const E=C(v,k);g(b,x,E)}else for(let x=0;x<m;x++){const E=(w*m+x)*c;let P;T?P=(x*p+(w+d))*S:P=((w+d)*m+x)*S;const O=C(v,P);g(b,E,O)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(ii(this._data)){const e=new wt(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new wt({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(ii(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(ii(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(ki(this.format)){const e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(new Uint8Array(t,i*e,e),{planeIndex:i,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}else{const e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}else return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data})}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");const e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(t,{planeIndex:i,format:"f32-planar"}),e.copyToChannel(t,i);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const i=48e3*5,r=e.numberOfChannels,n=e.sampleRate,o=e.length,a=Math.floor(i/r);let p=0,m=o;for(;m>0;){const d=Math.min(a,m),l=new Float32Array(r*d);for(let c=0;c<r;c++)e.copyFromChannel(l.subarray(c*d,(c+1)*d),c,p);yield new wt({format:"f32-planar",sampleRate:n,numberOfFrames:d,numberOfChannels:r,timestamp:t+p/n,data:l}),p+=d,m-=d}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const i=48e3*5,r=e.numberOfChannels,n=e.sampleRate,o=e.length,a=Math.floor(i/r);let p=0,m=o;const d=[];for(;m>0;){const l=Math.min(a,m),c=new Float32Array(r*l);for(let h=0;h<r;h++)e.copyFromChannel(c.subarray(h*l,(h+1)*l),h,p);const u=new wt({format:"f32-planar",sampleRate:n,numberOfFrames:l,numberOfChannels:r,timestamp:t+p/n,data:c});d.push(u),p+=l,m-=l}return d}}const ti=s=>{switch(s){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},ki=s=>{switch(s){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},jl=s=>{switch(s){case"u8":case"u8-planar":return(e,t)=>(e.getUint8(t)-128)/128;case"s16":case"s16-planar":return(e,t)=>e.getInt16(t,!0)/32768;case"s32":case"s32-planar":return(e,t)=>e.getInt32(t,!0)/2147483648;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},Vl=s=>{switch(s){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,Se((i+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,Se(Math.round(i*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,Se(Math.round(i*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},ii=s=>typeof AudioData<"u"&&s instanceof AudioData;/*!
242
+ * Copyright (c) 2025-present, Vanilagy and contributors
243
+ *
244
+ * This Source Code Form is subject to the terms of the Mozilla Public
245
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
246
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
247
+ */const Wl=s=>{let t=(s.hasVideo?"video/":s.hasAudio?"audio/":"application/")+(s.isQuickTime?"quicktime":"mp4");if(s.codecStrings.length>0){const i=[...new Set(s.codecStrings)];t+=`; codecs="${i.join(", ")}"`}return t};/*!
248
+ * Copyright (c) 2025-present, Vanilagy and contributors
249
+ *
250
+ * This Source Code Form is subject to the terms of the Mozilla Public
251
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
252
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
253
+ */const fs=8,qr=16,Gl=Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"}));/*!
254
+ * Copyright (c) 2025-present, Vanilagy and contributors
255
+ *
256
+ * This Source Code Form is subject to the terms of the Mozilla Public
257
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
258
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
259
+ */const Xr=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Zl=s=>{const e=Math.floor(s/36e5),t=Math.floor(s%(60*60*1e3)/(60*1e3)),i=Math.floor(s%(60*1e3)/1e3),r=s%1e3;return e.toString().padStart(2,"0")+":"+t.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+"."+r.toString().padStart(3,"0")};/*!
260
+ * Copyright (c) 2025-present, Vanilagy and contributors
261
+ *
262
+ * This Source Code Form is subject to the terms of the Mozilla Public
263
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
264
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
265
+ */class Yr{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8===7&&this.writer.write(this.helper);e.length%8!==0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{const t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(const n of e.children)n&&this.writeBox(n);const i=this.writer.getPos(),r=e.size??i-t;this.writer.seek(t),this.writeBoxHeader(e,r),this.writer.seek(i)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){const t=this.offsets.get(e);$(t!==void 0);const i=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(i)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(const i of e.children)i&&(t+=this.measureBox(i));return t}}}const ne=new Uint8Array(8),je=new DataView(ne.buffer),me=s=>[(s%256+256)%256],G=s=>(je.setUint16(0,s,!1),[ne[0],ne[1]]),Qr=s=>(je.setInt16(0,s,!1),[ne[0],ne[1]]),Jr=s=>(je.setUint32(0,s,!1),[ne[1],ne[2],ne[3]]),B=s=>(je.setUint32(0,s,!1),[ne[0],ne[1],ne[2],ne[3]]),ht=s=>(je.setInt32(0,s,!1),[ne[0],ne[1],ne[2],ne[3]]),_t=s=>(je.setUint32(0,Math.floor(s/2**32),!1),je.setUint32(4,s,!1),[ne[0],ne[1],ne[2],ne[3],ne[4],ne[5],ne[6],ne[7]]),en=s=>(je.setInt16(0,2**8*s,!1),[ne[0],ne[1]]),Xe=s=>(je.setInt32(0,2**16*s,!1),[ne[0],ne[1],ne[2],ne[3]]),ps=s=>(je.setInt32(0,2**30*s,!1),[ne[0],ne[1],ne[2],ne[3]]),ms=(s,e)=>{const t=[];let i=s;do{let r=i&127;i>>=7,t.length>0&&(r|=128),t.push(r)}while(i>0||e);return t.reverse()},Te=(s,e=!1)=>{const t=Array(s.length).fill(null).map((i,r)=>s.charCodeAt(r));return e&&t.push(0),t},gs=s=>{let e=null;for(const t of s)(!e||t.timestamp>e.timestamp)&&(e=t);return e},tn=s=>{const e=s*(Math.PI/180),t=Math.round(Math.cos(e)),i=Math.round(Math.sin(e));return[t,i,0,-i,t,0,0,0,1]},sn=tn(0),rn=s=>[Xe(s[0]),Xe(s[1]),ps(s[2]),Xe(s[3]),Xe(s[4]),ps(s[5]),Xe(s[6]),Xe(s[7]),ps(s[8])],K=(s,e,t)=>({type:s,contents:e&&new Uint8Array(e.flat(10)),children:t}),le=(s,e,t,i,r)=>K(s,[me(e),Jr(t),i??[]],r),Kl=s=>s.isQuickTime?K("ftyp",[Te("qt "),B(512),Te("qt ")]):s.fragmented?K("ftyp",[Te("iso5"),B(512),Te("iso5"),Te("iso6"),Te("mp41")]):K("ftyp",[Te("isom"),B(512),Te("isom"),s.holdsAvc?Te("avc1"):[],Te("mp41")]),Ti=s=>({type:"mdat",largeSize:s}),ql=s=>({type:"free",size:s}),si=s=>K("moov",void 0,[Xl(s.creationTime,s.trackDatas),...s.trackDatas.map(e=>Yl(e,s.creationTime)),s.isFragmented?Ic(s.trackDatas):null,Uc(s)]),Xl=(s,e)=>{const t=xe(Math.max(0,...e.filter(o=>o.samples.length>0).map(o=>{const a=gs(o.samples);return a.timestamp+a.duration})),_s),i=Math.max(0,...e.map(o=>o.track.id))+1,r=!Ft(s)||!Ft(t),n=r?_t:B;return le("mvhd",+r,0,[n(s),n(s),B(_s),n(t),Xe(1),en(1),Array(10).fill(0),rn(sn),Array(24).fill(0),B(i)])},Yl=(s,e)=>{const t=Jc(s);return K("trak",void 0,[Ql(s,e),Jl(s,e),t.name!==void 0?K("udta",void 0,[K("name",[...He.encode(t.name)])]):null])},Ql=(s,e)=>{const t=gs(s.samples),i=xe(t?t.timestamp+t.duration:0,_s),r=!Ft(e)||!Ft(i),n=r?_t:B;let o;if(s.type==="video"){const a=s.track.metadata.rotation;o=tn(a??0)}else o=sn;return le("tkhd",+r,3,[n(e),n(e),B(s.track.id),B(0),n(i),Array(8).fill(0),G(0),G(s.track.id),en(s.type==="audio"?1:0),G(0),rn(o),Xe(s.type==="video"?s.info.width:0),Xe(s.type==="video"?s.info.height:0)])},Jl=(s,e)=>K("mdia",void 0,[ec(s,e),ys(!0,tc[s.type],ic[s.type]),sc(s)]),ec=(s,e)=>{const t=gs(s.samples),i=xe(t?t.timestamp+t.duration:0,s.timescale),r=!Ft(e)||!Ft(i),n=r?_t:B;return le("mdhd",+r,0,[n(e),n(e),B(s.timescale),n(i),G(un(s.track.metadata.languageCode??sl)),G(0)])},tc={video:"vide",audio:"soun",subtitle:"text"},ic={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},ys=(s,e,t,i="\0\0\0\0")=>le("hdlr",0,0,[s?Te("mhlr"):B(0),Te(e),Te(i),B(0),B(0),Te(t,!0)]),sc=s=>K("minf",void 0,[rc[s.type](),nc(),lc(s)]),rc={video:()=>le("vmhd",0,1,[G(0),G(0),G(0),G(0)]),audio:()=>le("smhd",0,0,[G(0),G(0)]),subtitle:()=>le("nmhd",0,0)},nc=()=>K("dinf",void 0,[ac()]),ac=()=>le("dref",0,0,[B(1)],[oc()]),oc=()=>le("url ",0,1),lc=s=>{const e=s.compositionTimeOffsetTable.length>1||s.compositionTimeOffsetTable.some(t=>t.sampleCompositionTimeOffset!==0);return K("stbl",void 0,[cc(s),xc(s),e?Ec(s):null,e?Ac(s):null,kc(s),Tc(s),Sc(s),Cc(s)])},cc=s=>{let e;if(s.type==="video")e=hc(Gc[s.track.source._codec],s);else if(s.type==="audio"){const t=hn(s.track.source._codec,s.muxer.isQuickTime);$(t),e=mc(t,s)}else s.type==="subtitle"&&(e=wc(qc[s.track.source._codec],s));return $(e),le("stsd",0,0,[B(1)],[e])},hc=(s,e)=>K(s,[Array(6).fill(0),G(1),G(0),G(0),Array(12).fill(0),G(e.info.width),G(e.info.height),B(4718592),B(4718592),B(0),G(1),Array(32).fill(0),G(24),Qr(65535)],[Zc[e.track.source._codec](e),el(e.info.decoderConfig.colorSpace)?uc(e):null]),uc=s=>K("colr",[Te("nclx"),G(vi[s.info.decoderConfig.colorSpace.primaries]),G(wi[s.info.decoderConfig.colorSpace.transfer]),G(_i[s.info.decoderConfig.colorSpace.matrix]),me((s.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),dc=s=>s.info.decoderConfig&&K("avcC",[...ot(s.info.decoderConfig.description)]),fc=s=>s.info.decoderConfig&&K("hvcC",[...ot(s.info.decoderConfig.description)]),nn=s=>{if(!s.info.decoderConfig)return null;const e=s.info.decoderConfig,t=e.codec.split("."),i=Number(t[1]),r=Number(t[2]),n=Number(t[3]),o=t[4]?Number(t[4]):1,a=t[8]?Number(t[8]):Number(e.colorSpace?.fullRange??0),p=(n<<4)+(o<<1)+a,m=t[5]?Number(t[5]):e.colorSpace?.primaries?vi[e.colorSpace.primaries]:2,d=t[6]?Number(t[6]):e.colorSpace?.transfer?wi[e.colorSpace.transfer]:2,l=t[7]?Number(t[7]):e.colorSpace?.matrix?_i[e.colorSpace.matrix]:2;return le("vpcC",1,0,[me(i),me(r),me(p),me(m),me(d),me(l),G(0)])},pc=s=>K("av1C",ul(s.info.decoderConfig.codec)),mc=(s,e)=>{let t=0,i,r=16;if(Ne.includes(e.track.source._codec)){const n=e.track.source._codec,{sampleSize:o}=Lt(n);r=8*o,r>16&&(t=1)}return t===0?i=[Array(6).fill(0),G(1),G(t),G(0),B(0),G(e.info.numberOfChannels),G(r),G(0),G(0),G(e.info.sampleRate<2**16?e.info.sampleRate:0),G(0)]:i=[Array(6).fill(0),G(1),G(t),G(0),B(0),G(e.info.numberOfChannels),G(Math.min(r,16)),G(0),G(0),G(e.info.sampleRate<2**16?e.info.sampleRate:0),G(0),B(1),B(r/8),B(e.info.numberOfChannels*r/8),B(2)],K(s,i,[Kc(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null])},bs=s=>{let e;switch(s.track.source._codec){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${s.track.source._codec}`)}let t=[...me(e),...me(21),...Jr(0),...B(0),...B(0)];if(s.info.decoderConfig.description){const i=ot(s.info.decoderConfig.description);t=[...t,...me(5),...ms(i.byteLength),...i]}return t=[...G(1),...me(0),...me(4),...ms(t.length),...t,...me(6),...me(1),...me(2)],t=[...me(3),...ms(t.length),...t],le("esds",0,0,t)},ut=s=>K("wave",void 0,[gc(s),yc(s),K("\0\0\0\0")]),gc=s=>K("frma",[Te(hn(s.track.source._codec,s.muxer.isQuickTime))]),yc=s=>{const{littleEndian:e}=Lt(s.track.source._codec);return K("enda",[G(+e)])},bc=s=>{let e=s.info.numberOfChannels,t=3840,i=s.info.sampleRate,r=0,n=0,o=new Uint8Array(0);const a=s.info.decoderConfig?.description;if(a){$(a.byteLength>=18);const p=ot(a),m=Bl(p);e=m.outputChannelCount,t=m.preSkip,i=m.inputSampleRate,r=m.outputGain,n=m.channelMappingFamily,m.channelMappingTable&&(o=m.channelMappingTable)}return K("dOps",[me(0),me(e),G(t),B(i),Qr(r),me(n),...o])},vc=s=>{const e=s.info.decoderConfig?.description;$(e);const t=ot(e);return le("dfLa",0,0,[...t.subarray(4)])},Ve=s=>{const{littleEndian:e,sampleSize:t}=Lt(s.track.source._codec),i=+e;return le("pcmC",0,0,[me(i),me(8*t)])},wc=(s,e)=>K(s,[Array(6).fill(0),G(1)],[Xc[e.track.source._codec](e)]),_c=s=>K("vttC",[...He.encode(s.info.config.description)]),xc=s=>le("stts",0,0,[B(s.timeToSampleTable.length),s.timeToSampleTable.map(e=>[B(e.sampleCount),B(e.sampleDelta)])]),Cc=s=>{if(s.samples.every(t=>t.type==="key"))return null;const e=[...s.samples.entries()].filter(([,t])=>t.type==="key");return le("stss",0,0,[B(e.length),e.map(([t])=>B(t+1))])},kc=s=>le("stsc",0,0,[B(s.compactlyCodedChunkTable.length),s.compactlyCodedChunkTable.map(e=>[B(e.firstChunk),B(e.samplesPerChunk),B(1)])]),Tc=s=>{if(s.type==="audio"&&s.info.requiresPcmTransformation){const{sampleSize:e}=Lt(s.track.source._codec);return le("stsz",0,0,[B(e*s.info.numberOfChannels),B(s.samples.reduce((t,i)=>t+xe(i.duration,s.timescale),0))])}return le("stsz",0,0,[B(0),B(s.samples.length),s.samples.map(e=>B(e.size))])},Sc=s=>s.finalizedChunks.length>0&&ze(s.finalizedChunks).offset>=2**32?le("co64",0,0,[B(s.finalizedChunks.length),s.finalizedChunks.map(e=>_t(e.offset))]):le("stco",0,0,[B(s.finalizedChunks.length),s.finalizedChunks.map(e=>B(e.offset))]),Ec=s=>le("ctts",1,0,[B(s.compositionTimeOffsetTable.length),s.compositionTimeOffsetTable.map(e=>[B(e.sampleCount),ht(e.sampleCompositionTimeOffset)])]),Ac=s=>{let e=1/0,t=-1/0,i=1/0,r=-1/0;$(s.compositionTimeOffsetTable.length>0),$(s.samples.length>0);for(let o=0;o<s.compositionTimeOffsetTable.length;o++){const a=s.compositionTimeOffsetTable[o];e=Math.min(e,a.sampleCompositionTimeOffset),t=Math.max(t,a.sampleCompositionTimeOffset)}for(let o=0;o<s.samples.length;o++){const a=s.samples[o];i=Math.min(i,xe(a.timestamp,s.timescale)),r=Math.max(r,xe(a.timestamp+a.duration,s.timescale))}const n=Math.max(-e,0);return r>=2**31?null:le("cslg",0,0,[ht(n),ht(e),ht(t),ht(i),ht(r)])},Ic=s=>K("mvex",void 0,s.map(Pc)),Pc=s=>le("trex",0,0,[B(s.track.id),B(1),B(0),B(0),B(0)]),an=(s,e)=>K("moof",void 0,[Rc(s),...e.map(Oc)]),Rc=s=>le("mfhd",0,0,[B(s)]),on=s=>{let e=0,t=0;const i=0,r=0,n=s.type==="delta";return t|=+n,n?e|=1:e|=2,e<<24|t<<16|i<<8|r},Oc=s=>K("traf",void 0,[Fc(s),Mc(s),Lc(s)]),Fc=s=>{$(s.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;const t=s.currentChunk.samples[1]??s.currentChunk.samples[0],i={duration:t.timescaleUnitsToNextSample,size:t.size,flags:on(t)};return le("tfhd",0,e,[B(s.track.id),B(i.duration),B(i.size),B(i.flags)])},Mc=s=>($(s.currentChunk),le("tfdt",1,0,[_t(xe(s.currentChunk.startTimestamp,s.timescale))])),Lc=s=>{$(s.currentChunk);const e=s.currentChunk.samples.map(f=>f.timescaleUnitsToNextSample),t=s.currentChunk.samples.map(f=>f.size),i=s.currentChunk.samples.map(on),r=s.currentChunk.samples.map(f=>xe(f.timestamp-f.decodeTimestamp,s.timescale)),n=new Set(e),o=new Set(t),a=new Set(i),p=new Set(r),m=a.size===2&&i[0]!==i[1],d=n.size>1,l=o.size>1,c=!m&&a.size>1,u=p.size>1||[...p].some(f=>f!==0);let h=0;return h|=1,h|=4*+m,h|=256*+d,h|=512*+l,h|=1024*+c,h|=2048*+u,le("trun",1,h,[B(s.currentChunk.samples.length),B(s.currentChunk.offset-s.currentChunk.moofOffset||0),m?B(i[0]):[],s.currentChunk.samples.map((f,b)=>[d?B(e[b]):[],l?B(t[b]):[],c?B(i[b]):[],u?ht(r[b]):[]])])},Bc=s=>K("mfra",void 0,[...s.map($c),Dc()]),$c=(s,e)=>le("tfra",1,0,[B(s.track.id),B(63),B(s.finalizedChunks.length),s.finalizedChunks.map(i=>[_t(xe(i.samples[0].timestamp,s.timescale)),_t(i.moofOffset),B(e+1),B(1),B(1)])]),Dc=()=>le("mfro",0,0,[B(0)]),zc=()=>K("vtte"),Hc=(s,e,t,i,r)=>K("vttc",void 0,[r!==null?K("vsid",[ht(r)]):null,t!==null?K("iden",[...He.encode(t)]):null,e!==null?K("ctim",[...He.encode(Zl(e))]):null,i!==null?K("sttg",[...He.encode(i)]):null,K("payl",[...He.encode(s)])]),Nc=s=>K("vtta",[...He.encode(s)]),Uc=s=>{const e=[],t=s.format._options.metadataFormat??"auto",i=s.output._metadataTags;if(t==="mdir"||t==="auto"&&!s.isQuickTime){const r=Vc(i);r&&e.push(r)}else if(t==="mdta"){const r=Wc(i);r&&e.push(r)}else(t==="udta"||t==="auto"&&s.isQuickTime)&&jc(e,s.output._metadataTags);return e.length===0?null:K("udta",void 0,e)},jc=(s,e)=>{for(const{key:t,value:i}of $r(e))switch(t){case"title":s.push(We("©nam",i));break;case"description":s.push(We("©des",i));break;case"artist":s.push(We("©ART",i));break;case"album":s.push(We("©alb",i));break;case"albumArtist":s.push(We("albr",i));break;case"genre":s.push(We("©gen",i));break;case"date":s.push(We("©day",i.toISOString().slice(0,10)));break;case"comment":s.push(We("©cmt",i));break;case"lyrics":s.push(We("©lyr",i));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:as(t)}if(e.raw)for(const t in e.raw){const i=e.raw[t];i==null||t.length!==4||s.some(r=>r.type===t)||(typeof i=="string"?s.push(We(t,i)):i instanceof Uint8Array&&s.push(K(t,Array.from(i))))}},We=(s,e)=>{const t=He.encode(e);return K(s,[G(t.length),G(un("und")),Array.from(t)])},ln={"image/jpeg":13,"image/png":14,"image/bmp":27},cn=(s,e)=>{const t=[];for(const{key:i,value:r}of $r(s))switch(i){case"title":t.push({key:e?"title":"©nam",value:Me(r)});break;case"description":t.push({key:e?"description":"©des",value:Me(r)});break;case"artist":t.push({key:e?"artist":"©ART",value:Me(r)});break;case"album":t.push({key:e?"album":"©alb",value:Me(r)});break;case"albumArtist":t.push({key:e?"album_artist":"aART",value:Me(r)});break;case"comment":t.push({key:e?"comment":"©cmt",value:Me(r)});break;case"genre":t.push({key:e?"genre":"©gen",value:Me(r)});break;case"lyrics":t.push({key:e?"lyrics":"©lyr",value:Me(r)});break;case"date":t.push({key:e?"date":"©day",value:Me(r.toISOString().slice(0,10))});break;case"images":for(const n of r)n.kind==="coverFront"&&t.push({key:"covr",value:K("data",[B(ln[n.mimeType]??0),B(0),Array.from(n.data)])});break;case"trackNumber":if(e){const n=s.tracksTotal!==void 0?`${r}/${s.tracksTotal}`:r.toString();t.push({key:"track",value:Me(n)})}else t.push({key:"trkn",value:K("data",[B(0),B(0),G(0),G(r),G(s.tracksTotal??0),G(0)])});break;case"discNumber":e||t.push({key:"disc",value:K("data",[B(0),B(0),G(0),G(r),G(s.discsTotal??0),G(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:as(i)}if(s.raw)for(const i in s.raw){const r=s.raw[i];r==null||!e&&i.length!==4||t.some(n=>n.key===i)||(typeof r=="string"?t.push({key:i,value:Me(r)}):r instanceof Uint8Array?t.push({key:i,value:K("data",[B(0),B(0),Array.from(r)])}):r instanceof Dr&&t.push({key:i,value:K("data",[B(ln[r.mimeType]??0),B(0),Array.from(r.data)])}))}return t},Vc=s=>{const e=cn(s,!1);return e.length===0?null:le("meta",0,0,void 0,[ys(!1,"mdir","","appl"),K("ilst",void 0,e.map(t=>K(t.key,void 0,[t.value])))])},Wc=s=>{const e=cn(s,!0);return e.length===0?null:K("meta",void 0,[ys(!1,"mdta",""),le("keys",0,0,[B(e.length)],e.map(t=>K("mdta",[...He.encode(t.key)]))),K("ilst",void 0,e.map((t,i)=>{const r=String.fromCharCode(...B(i+1));return K(r,void 0,[t.value])}))])},Me=s=>K("data",[B(1),B(0),...He.encode(s)]),Gc={avc:"avc1",hevc:"hvc1",vp8:"vp08",vp9:"vp09",av1:"av01"},Zc={avc:dc,hevc:fc,vp8:nn,vp9:nn,av1:pc},hn=(s,e)=>{switch(s){case"aac":return"mp4a";case"mp3":return"mp4a";case"opus":return"Opus";case"vorbis":return"mp4a";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt"}if(e)switch(s){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":return"in24";case"pcm-s24be":return"in24";case"pcm-s32":return"in32";case"pcm-s32be":return"in32";case"pcm-f32":return"fl32";case"pcm-f32be":return"fl32";case"pcm-f64":return"fl64";case"pcm-f64be":return"fl64"}else switch(s){case"pcm-s16":return"ipcm";case"pcm-s16be":return"ipcm";case"pcm-s24":return"ipcm";case"pcm-s24be":return"ipcm";case"pcm-s32":return"ipcm";case"pcm-s32be":return"ipcm";case"pcm-f32":return"fpcm";case"pcm-f32be":return"fpcm";case"pcm-f64":return"fpcm";case"pcm-f64be":return"fpcm"}},Kc=(s,e)=>{switch(s){case"aac":return bs;case"mp3":return bs;case"opus":return bc;case"vorbis":return bs;case"flac":return vc}if(e)switch(s){case"pcm-s24":return ut;case"pcm-s24be":return ut;case"pcm-s32":return ut;case"pcm-s32be":return ut;case"pcm-f32":return ut;case"pcm-f32be":return ut;case"pcm-f64":return ut;case"pcm-f64be":return ut}else switch(s){case"pcm-s16":return Ve;case"pcm-s16be":return Ve;case"pcm-s24":return Ve;case"pcm-s24be":return Ve;case"pcm-s32":return Ve;case"pcm-s32be":return Ve;case"pcm-f32":return Ve;case"pcm-f32be":return Ve;case"pcm-f64":return Ve;case"pcm-f64be":return Ve}return null},qc={webvtt:"wvtt"},Xc={webvtt:_c},un=s=>{$(s.length===3);let e=0;for(let t=0;t<3;t++)e<<=5,e+=s.charCodeAt(t)-96;return e};/*!
266
+ * Copyright (c) 2025-present, Vanilagy and contributors
267
+ *
268
+ * This Source Code Form is subject to the terms of the Mozilla Public
269
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
270
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
271
+ */class Yc{constructor(){this.ensureMonotonicity=!1,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1}start(){}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}const i=t+e.byteLength-this.trackedStart;let r=this.trackedWrites.byteLength;for(;r<i;)r*=2;if(r!==this.trackedWrites.byteLength){const n=new Uint8Array(r);n.set(this.trackedWrites,0),this.trackedWrites=n}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");const t={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,t}}const vs=2**16,ws=2**32;class dn extends Yc{constructor(e){if(super(),this.pos=0,this.maxPos=0,this.target=e,this.supportsResize="resize"in new ArrayBuffer(0),this.supportsResize)try{this.buffer=new ArrayBuffer(vs,{maxByteLength:ws})}catch{this.buffer=new ArrayBuffer(vs),this.supportsResize=!1}else this.buffer=new ArrayBuffer(vs);this.bytes=new Uint8Array(this.buffer)}ensureSize(e){let t=this.buffer.byteLength;for(;t<e;)t*=2;if(t!==this.buffer.byteLength){if(t>ws)throw new Error(`ArrayBuffer exceeded maximum size of ${ws} bytes. Please consider using another target.`);if(this.supportsResize)this.buffer.resize(t);else{const i=new ArrayBuffer(t),r=new Uint8Array(i);r.set(this.bytes,0),this.buffer=i,this.bytes=r}}}write(e){this.maybeTrackWrites(e),this.ensureSize(this.pos+e.byteLength),this.bytes.set(e,this.pos),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength,this.maxPos=Math.max(this.maxPos,this.pos)}seek(e){this.pos=e}getPos(){return this.pos}async flush(){}async finalize(){this.ensureSize(this.pos),this.target.buffer=this.buffer.slice(0,Math.max(this.maxPos,this.pos))}async close(){}getSlice(e,t){return this.bytes.slice(e,t)}}/*!
272
+ * Copyright (c) 2025-present, Vanilagy and contributors
273
+ *
274
+ * This Source Code Form is subject to the terms of the Mozilla Public
275
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
276
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
277
+ */class fn{constructor(){this._output=null,this.onwrite=null}}class pn extends fn{constructor(){super(...arguments),this.buffer=null}_createWriter(){return new dn(this)}}/*!
278
+ * Copyright (c) 2025-present, Vanilagy and contributors
279
+ *
280
+ * This Source Code Form is subject to the terms of the Mozilla Public
281
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
282
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
283
+ */const _s=1e3,Qc=2082844800,Jc=s=>{const e={},t=s.track;return t.metadata.name!==void 0&&(e.name=t.metadata.name),e},xe=(s,e,t=!0)=>{const i=s*e;return t?Math.round(i):i};class eh extends kl{constructor(e,t){super(e),this.auxTarget=new pn,this.auxWriter=this.auxTarget._createWriter(),this.auxBoxWriter=new Yr(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=tl(),this.creationTime=Math.floor(Date.now()/1e3)+Qc,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.format=t,this.writer=e._writer,this.boxWriter=new Yr(this.writer),this.isQuickTime=t instanceof bn;const i=this.writer instanceof dn?"in-memory":!1;this.fastStart=t._options.fastStart??i,this.isFragmented=this.fastStart==="fragmented",(this.fastStart==="in-memory"||this.isFragmented)&&(this.writer.ensureMonotonicity=!0),this.minimumFragmentDuration=t._options.minimumFragmentDuration??1}async start(){const e=await this.mutex.acquire(),t=this.output._tracks.some(i=>i.type==="video"&&i.source._codec==="avc");if(this.format._options.onFtyp&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(Kl({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented})),this.format._options.onFtyp){const{data:i,start:r}=this.writer.stopTrackingWrites();this.format._options.onFtyp(i,r)}if(this.ftypSize=this.writer.getPos(),this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(const i of this.output._tracks)if(i.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=Ti(!0),this.boxWriter.writeBox(this.mdat));await this.writer.flush(),e()}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(t=>t.type==="video"||t.type==="audio"?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source._codec]);return Wl({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(t=>t.type==="video"),hasAudio:this.trackDatas.some(t=>t.type==="audio"),codecStrings:e})}getVideoTrackData(e,t,i){const r=this.trackDatas.find(m=>m.track===e);if(r)return r;wl(i),$(i),$(i.decoderConfig);const n={...i.decoderConfig};$(n.codedWidth!==void 0),$(n.codedHeight!==void 0);let o=!1;if(e.source._codec==="avc"&&!n.description){const m=Sl(t.data);if(!m)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");n.description=El(m),o=!0}else if(e.source._codec==="hevc"&&!n.description){const m=Al(t.data);if(!m)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");n.description=Ll(m),o=!0}const a=al(1/(e.metadata.frameRate??57600),1e6).denominator,p={muxer:this,track:e,type:"video",info:{width:n.codedWidth,height:n.codedHeight,decoderConfig:n,requiresAnnexBTransformation:o},timescale:a,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(p),this.trackDatas.sort((m,d)=>m.track.id-d.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),p}getAudioTrackData(e,t){const i=this.trackDatas.find(n=>n.track===e);if(i)return i;xl(t),$(t),$(t.decoderConfig);const r={muxer:this,track:e,type:"audio",info:{numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate,decoderConfig:t.decoderConfig,requiresPcmTransformation:!this.isFragmented&&Ne.includes(e.source._codec)},timescale:t.decoderConfig.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(r),this.trackDatas.sort((n,o)=>n.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}getSubtitleTrackData(e,t){const i=this.trackDatas.find(n=>n.track===e);if(i)return i;Cl(t),$(t),$(t.config);const r={muxer:this,track:e,type:"subtitle",info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(r),this.trackDatas.sort((n,o)=>n.track.id-o.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(e,t,i){const r=await this.mutex.acquire();try{const n=this.getVideoTrackData(e,t,i);let o=t.data;if(n.info.requiresAnnexBTransformation){const m=Tl(o);if(!m)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");o=m}const a=this.validateAndNormalizeTimestamp(n.track,t.timestamp,t.type==="key"),p=this.createSampleForTrack(n,o,a,t.duration,t.type);await this.registerSample(n,p)}finally{r()}}async addEncodedAudioPacket(e,t,i){const r=await this.mutex.acquire();try{const n=this.getAudioTrackData(e,i),o=this.validateAndNormalizeTimestamp(n.track,t.timestamp,t.type==="key"),a=this.createSampleForTrack(n,t.data,o,t.duration,t.type);n.info.requiresPcmTransformation&&await this.maybePadWithSilence(n,o),await this.registerSample(n,a)}finally{r()}}async maybePadWithSilence(e,t){const i=ze(e.samples),r=i?i.timestamp+i.duration:0,n=t-r,o=xe(n,e.timescale);if(o>0){const{sampleSize:a,silentValue:p}=Lt(e.info.decoderConfig.codec),m=o*e.info.numberOfChannels,d=new Uint8Array(a*m).fill(p),l=this.createSampleForTrack(e,new Uint8Array(d.buffer),r,n,"key");await this.registerSample(e,l)}}async addSubtitleCue(e,t,i){const r=await this.mutex.acquire();try{const n=this.getSubtitleTrackData(e,i);this.validateAndNormalizeTimestamp(n.track,t.timestamp,!0),e.source._codec==="webvtt"&&(n.cueQueue.push(t),await this.processWebVTTCues(n,t.timestamp))}finally{r()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){const i=new Set([]);for(const m of e.cueQueue)$(m.timestamp<=t),$(e.lastCueEndTimestamp<=m.timestamp+m.duration),i.add(Math.max(m.timestamp,e.lastCueEndTimestamp)),i.add(m.timestamp+m.duration);const r=[...i].sort((m,d)=>m-d),n=r[0],o=r[1]??n;if(t<o)break;if(e.lastCueEndTimestamp<n){this.auxWriter.seek(0);const m=zc();this.auxBoxWriter.writeBox(m);const d=this.auxWriter.getSlice(0,this.auxWriter.getPos()),l=this.createSampleForTrack(e,d,e.lastCueEndTimestamp,n-e.lastCueEndTimestamp,"key");await this.registerSample(e,l),e.lastCueEndTimestamp=n}this.auxWriter.seek(0);for(let m=0;m<e.cueQueue.length;m++){const d=e.cueQueue[m];if(d.timestamp>=o)break;Xr.lastIndex=0;const l=Xr.test(d.text),c=d.timestamp+d.duration;let u=e.cueToSourceId.get(d);if(u===void 0&&o<c&&(u=e.nextSourceId++,e.cueToSourceId.set(d,u)),d.notes){const f=Nc(d.notes);this.auxBoxWriter.writeBox(f)}const h=Hc(d.text,l?n:null,d.identifier??null,d.settings??null,u??null);this.auxBoxWriter.writeBox(h),c===o&&e.cueQueue.splice(m--,1)}const a=this.auxWriter.getSlice(0,this.auxWriter.getPos()),p=this.createSampleForTrack(e,a,n,o-n,"key");await this.registerSample(e,p),e.lastCueEndTimestamp=o}}createSampleForTrack(e,t,i,r,n){return{timestamp:i,decodeTimestamp:i,duration:r,data:t,size:t.byteLength,type:n,timescaleUnitsToNextSample:xe(r,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){let r=0;for(let n=0;n<e.timestampProcessingQueue.length;n++){const o=e.timestampProcessingQueue[n],a=xe(o.duration,e.timescale);r+=a}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:r,sampleDelta:1});else{const n=ze(e.timeToSampleTable);n.sampleCount+=r}e.timestampProcessingQueue.length=0;return}const i=e.timestampProcessingQueue.map(r=>r.timestamp).sort((r,n)=>r-n);for(let r=0;r<e.timestampProcessingQueue.length;r++){const n=e.timestampProcessingQueue[r];n.decodeTimestamp=i[r],!this.isFragmented&&e.lastTimescaleUnits===null&&(n.decodeTimestamp=0);const o=xe(n.timestamp-n.decodeTimestamp,e.timescale),a=xe(n.duration,e.timescale);if(e.lastTimescaleUnits!==null){$(e.lastSample);const p=xe(n.decodeTimestamp,e.timescale,!1),m=Math.round(p-e.lastTimescaleUnits);if($(m>=0),e.lastTimescaleUnits+=m,e.lastSample.timescaleUnitsToNextSample=m,!this.isFragmented){let d=ze(e.timeToSampleTable);if($(d),d.sampleCount===1){d.sampleDelta=m;const c=e.timeToSampleTable[e.timeToSampleTable.length-2];c&&c.sampleDelta===m&&(c.sampleCount++,e.timeToSampleTable.pop(),d=c)}else d.sampleDelta!==m&&(d.sampleCount--,e.timeToSampleTable.push(d={sampleCount:1,sampleDelta:m}));d.sampleDelta===a?d.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:a});const l=ze(e.compositionTimeOffsetTable);$(l),l.sampleCompositionTimeOffset===o?l.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o})}}else e.lastTimescaleUnits=xe(n.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:a}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:o}));e.lastSample=n}if(e.timestampProcessingQueue.length=0,$(e.lastSample),$(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){$(t.type==="key");const r=xe(t.timestamp,e.timescale,!1),n=Math.round(r-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=n}}async registerSample(e,t){t.type==="key"&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart==="reserve")){const r=e.track.metadata.maximumPacketCount;if($(r!==void 0),e.samples.length>r)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${r}). Either add less packets or increase the maximum packet count.`)}let i=!1;if(!e.currentChunk)i=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);const r=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){const n=this.trackDatas.every(o=>{if(e===o)return t.type==="key";const a=o.sampleQueue[0];return a?a.type==="key":o.track.source._closed});r>=this.minimumFragmentDuration&&n&&t.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=r>=.5}i&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null}),$(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if($(!this.isFragmented),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((i,r)=>i+xe(r.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||ze(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(const i of e.currentChunk.samples)$(i.data),this.writer.write(i.data),i.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if($(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let t=null,i=1/0;for(const n of this.trackDatas){if(!e&&n.sampleQueue.length===0&&!n.track.source._closed)break e;n.sampleQueue.length>0&&n.sampleQueue[0].timestamp<i&&(t=n,i=n.sampleQueue[0].timestamp)}if(!t)break;const r=t.sampleQueue.shift();await this.addSampleToTrack(t,r)}}async finalizeFragment(e=!0){$(this.isFragmented);const t=this.nextFragmentNumber++;if(t===1){this.format._options.onMoov&&this.writer.startTrackingWrites();const u=si(this);if(this.boxWriter.writeBox(u),this.format._options.onMoov){const{data:h,start:f}=this.writer.stopTrackingWrites();this.format._options.onMoov(h,f)}}const i=this.trackDatas.filter(u=>u.currentChunk),r=an(t,i),n=this.writer.getPos(),o=n+this.boxWriter.measureBox(r);let a=o+fs,p=1/0;for(const u of i){u.currentChunk.offset=a,u.currentChunk.moofOffset=n;for(const h of u.currentChunk.samples)a+=h.size;p=Math.min(p,u.currentChunk.startTimestamp)}const m=a-o,d=m>=2**32;if(d)for(const u of i)u.currentChunk.offset+=qr-fs;this.format._options.onMoof&&this.writer.startTrackingWrites();const l=an(t,i);if(this.boxWriter.writeBox(l),this.format._options.onMoof){const{data:u,start:h}=this.writer.stopTrackingWrites();this.format._options.onMoof(u,h,p)}$(this.writer.getPos()===o),this.format._options.onMdat&&this.writer.startTrackingWrites();const c=Ti(d);c.size=m,this.boxWriter.writeBox(c),this.writer.seek(o+(d?qr:fs));for(const u of i)for(const h of u.currentChunk.samples)this.writer.write(h.data),h.data=null;if(this.format._options.onMdat){const{data:u,start:h}=this.writer.stopTrackingWrites();this.format._options.onMdat(u,h)}for(const u of i)u.finalizedChunks.push(u.currentChunk),this.finalizedChunks.push(u.currentChunk),u.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){if(this.allTracksAreKnown()){if(!this.mdat){const i=si(this),n=this.boxWriter.measureBox(i)+this.computeSampleTableSizeUpperBound()+4096;$(this.ftypSize!==null),this.writer.seek(this.ftypSize+n),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=Ti(!0),this.boxWriter.writeBox(this.mdat);for(const o of this.trackDatas){for(const a of o.sampleQueue)await this.addSampleToTrack(o,a);o.sampleQueue.length=0}}await this.addSampleToTrack(e,t)}else e.sampleQueue.push(t)}computeSampleTableSizeUpperBound(){$(this.fastStart==="reserve");let e=0;for(const t of this.trackDatas){const i=t.track.metadata.maximumPacketCount;$(i!==void 0),e+=8*Math.ceil(2/3*i),e+=4*i,e+=8*Math.ceil(2/3*i),e+=12*Math.ceil(2/3*i),e+=4*i,e+=8*i}return e}async onTrackClose(e){const t=await this.mutex.acquire();if(e.type==="subtitle"&&e.source._codec==="webvtt"){const i=this.trackDatas.find(r=>r.track===e);i&&await this.processWebVTTCues(i,1/0)}this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const t of this.trackDatas)t.type==="subtitle"&&t.track.source._codec==="webvtt"&&await this.processWebVTTCues(t,1/0);if(this.isFragmented){await this.interleaveSamples(!0);for(const t of this.trackDatas)this.processTimestamps(t);await this.finalizeFragment(!1)}else for(const t of this.trackDatas)this.processTimestamps(t),await this.finalizeCurrentChunk(t);if(this.fastStart==="in-memory"){this.mdat=Ti(!1);let t;for(let r=0;r<2;r++){const n=si(this),o=this.boxWriter.measureBox(n);t=this.boxWriter.measureBox(this.mdat);let a=this.writer.getPos()+o+t;for(const p of this.finalizedChunks){p.offset=a;for(const{data:m}of p.samples)$(m),a+=m.byteLength,t+=m.byteLength}if(a<2**32)break;t>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();const i=si(this);if(this.boxWriter.writeBox(i),this.format._options.onMoov){const{data:r,start:n}=this.writer.stopTrackingWrites();this.format._options.onMoov(r,n)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=t,this.boxWriter.writeBox(this.mdat);for(const r of this.finalizedChunks)for(const n of r.samples)$(n.data),this.writer.write(n.data),n.data=null;if(this.format._options.onMdat){const{data:r,start:n}=this.writer.stopTrackingWrites();this.format._options.onMdat(r,n)}}else if(this.isFragmented){const t=this.writer.getPos(),i=Bc(this.trackDatas);this.boxWriter.writeBox(i);const r=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(r)}else{$(this.mdat);const t=this.boxWriter.offsets.get(this.mdat);$(t!==void 0);const i=this.writer.getPos()-t;if(this.mdat.size=i,this.mdat.largeSize=i>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){const{data:n,start:o}=this.writer.stopTrackingWrites();this.format._options.onMdat(n,o)}const r=si(this);if(this.fastStart==="reserve"){$(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(r);const n=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(ql(n))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(r);if(this.format._options.onMoov){const{data:n,start:o}=this.writer.stopTrackingWrites();this.format._options.onMoov(n,o)}}e()}}/*!
284
+ * Copyright (c) 2025-present, Vanilagy and contributors
285
+ *
286
+ * This Source Code Form is subject to the terms of the Mozilla Public
287
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
288
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
289
+ */class mn{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>bt.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Mt.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Ci.includes(e))}_codecUnsupportedHint(e){return""}}class gn extends mn{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(e.minimumFragmentDuration!==void 0&&(!Number.isFinite(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(e.onFtyp!==void 0&&typeof e.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(e.onMoov!==void 0&&typeof e.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(e.onMdat!==void 0&&typeof e.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(e.onMoof!==void 0&&typeof e.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(e.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:1/0},audio:{min:0,max:1/0},subtitle:{min:0,max:1/0},total:{min:1,max:2**32-1}}}get supportsVideoRotationMetadata(){return!0}_createMuxer(e){return new eh(e,this)}}class yn extends gn{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...bt,...zr,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Ci]}_codecUnsupportedHint(e){return new bn().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class bn extends gn{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...bt,...Mt]}_codecUnsupportedHint(e){return new yn().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}/*!
290
+ * Copyright (c) 2025-present, Vanilagy and contributors
291
+ *
292
+ * This Source Code Form is subject to the terms of the Mozilla Public
293
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
294
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
295
+ */const th=s=>{if(!s||typeof s!="object")throw new TypeError("Encoding config must be an object.");if(!bt.includes(s.codec))throw new TypeError(`Invalid video codec '${s.codec}'. Must be one of: ${bt.join(", ")}.`);if(!(s.bitrate instanceof Si)&&(!Number.isInteger(s.bitrate)||s.bitrate<=0))throw new TypeError("config.bitrate must be a positive integer or a quality.");if(s.keyFrameInterval!==void 0&&(!Number.isFinite(s.keyFrameInterval)||s.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(s.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(s.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(s.onEncodedPacket!==void 0&&typeof s.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(s.onEncoderConfig!==void 0&&typeof s.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");ih(s.codec,s)},ih=(s,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.alpha!==void 0&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.latencyMode!==void 0&&!["quality","realtime"].includes(e.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&Wr(e.fullCodecString)!==s)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${s}).`);if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(e.scalabilityMode!==void 0&&typeof e.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(e.contentHint!==void 0&&typeof e.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},sh=s=>{const e=s.bitrate instanceof Si?s.bitrate._toVideoBitrate(s.codec,s.width,s.height):s.bitrate;return{codec:s.fullCodecString??hl(s.codec,s.width,s.height,e),width:s.width,height:s.height,bitrate:e,bitrateMode:s.bitrateMode,alpha:s.alpha??"discard",framerate:s.framerate,latencyMode:s.latencyMode,hardwareAcceleration:s.hardwareAcceleration,scalabilityMode:s.scalabilityMode,contentHint:s.contentHint,...fl(s.codec)}},rh=s=>{if(!s||typeof s!="object")throw new TypeError("Encoding config must be an object.");if(!Mt.includes(s.codec))throw new TypeError(`Invalid audio codec '${s.codec}'. Must be one of: ${Mt.join(", ")}.`);if(s.bitrate===void 0&&(!Ne.includes(s.codec)||s.codec==="flac"))throw new TypeError("config.bitrate must be provided for compressed audio codecs.");if(s.bitrate!==void 0&&!(s.bitrate instanceof Si)&&(!Number.isInteger(s.bitrate)||s.bitrate<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(s.onEncodedPacket!==void 0&&typeof s.onEncodedPacket!="function")throw new TypeError("config.onEncodedChunk, when provided, must be a function.");if(s.onEncoderConfig!==void 0&&typeof s.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");nh(s.codec,s)},nh=(s,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&Wr(e.fullCodecString)!==s)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${s}).`)},ah=s=>{const e=s.bitrate instanceof Si?s.bitrate._toAudioBitrate(s.codec):s.bitrate;return{codec:s.fullCodecString??dl(s.codec,s.numberOfChannels,s.sampleRate),numberOfChannels:s.numberOfChannels,sampleRate:s.sampleRate,bitrate:e,bitrateMode:s.bitrateMode,...pl(s.codec)}};class Si{constructor(e){this._factor=e}_toVideoBitrate(e,t,i){const r=t*i,n={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2},o=1920*1080,a=3e6,p=Math.pow(r/o,.95),l=a*p*n[e]*this._factor;return Math.ceil(l/1e3)*1e3}_toAudioBitrate(e){if(Ne.includes(e)||e==="flac")return;const i={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3}[e];if(!i)throw new Error(`Unhandled codec: ${e}`);let r=i*this._factor;return e==="aac"?r=[96e3,128e3,16e4,192e3].reduce((o,a)=>Math.abs(a-r)<Math.abs(o-r)?a:o):e==="opus"||e==="vorbis"?r=Math.max(6e3,r):e==="mp3"&&(r=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((o,a)=>Math.abs(a-r)<Math.abs(o-r)?a:o)),Math.round(r/1e3)*1e3}}/*!
296
+ * Copyright (c) 2025-present, Vanilagy and contributors
297
+ *
298
+ * This Source Code Form is subject to the terms of the Mozilla Public
299
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
300
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
301
+ */class xs{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._timestampOffset=0}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;const e=this._connectedTrack;if(!e)throw new Error("Cannot call close without connecting the source to an output track.");if(e.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(e.output.state==="finalizing"||e.output.state==="finalized")&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise?this._closingPromise:this._flushAndClose(e)}}class vn extends xs{constructor(e){if(super(),this._connectedTrack=null,!bt.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${bt.join(", ")}.`);this._codec=e}}class oh{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.codedWidth=null,this.codedHeight=null,this.resizeCanvas=null,this.customEncoder=null,this.customEncoderCallSerializer=new Br,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorNeedsNewStack=!0}async add(e,t,i){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.codedWidth!==null&&this.codedHeight!==null){if(e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight){const a=this.encodingConfig.sizeChangeBehavior??"deny";if(a!=="passThrough"){if(a==="deny")throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'strict' in the encoding options.`);{let p=!1;this.resizeCanvas||(typeof document<"u"?(this.resizeCanvas=document.createElement("canvas"),this.resizeCanvas.width=this.codedWidth,this.resizeCanvas.height=this.codedHeight):this.resizeCanvas=new OffscreenCanvas(this.codedWidth,this.codedHeight),p=!0);const m=this.resizeCanvas.getContext("2d",{alpha:ls()});$(m),p||(ls()?(m.fillStyle="black",m.fillRect(0,0,this.codedWidth,this.codedHeight)):m.clearRect(0,0,this.codedWidth,this.codedHeight)),e.drawWithFit(m,{fit:a}),t&&e.close(),e=new vt(this.resizeCanvas,{timestamp:e.timestamp,duration:e.duration,rotation:e.rotation}),t=!0}}}}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),$(this.encoderInitialized);const r=this.encodingConfig.keyFrameInterval??5,n=Math.floor(e.timestamp/r),o={...i,keyFrame:i?.keyFrame||r===0||n!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=n,this.customEncoder){this.customEncoderQueueSize++;const a=e.clone(),p=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(a,o)).then(()=>this.customEncoderQueueSize--).catch(m=>this.error??=m).finally(()=>{a.close()});this.customEncoderQueueSize>=4&&await p}else{$(this.encoder);const a=e.toVideoFrame();if(!this.alphaEncoder)this.encoder.encode(a,o),a.close();else if(!!a.format&&!a.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(a,o),a.close();else{const m=a.displayWidth,d=a.displayHeight;if(!this.splitter)try{this.splitter=new lh(m,d)}catch(l){console.error("Due to an error, only color data will be encoded.",l),this.splitterCreationFailed=!0,this.alphaFrameQueue.push(null),this.encoder.encode(a,o),a.close()}if(this.splitter){const l=this.splitter.extractColor(a),c=this.splitter.extractAlpha(a);this.alphaFrameQueue.push(c),this.encoder.encode(l,o),l.close(),a.close()}}t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(p=>this.encoder.addEventListener("dequeue",p,{once:!0}))}await this.muxer.mutex.currentPromise}finally{t&&e.close()}}ensureEncoder(e){const t=new Error;this.ensureEncoderPromise=(async()=>{const i=sh({width:e.codedWidth,height:e.codedHeight,...this.encodingConfig,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(i);const r=$l.find(n=>n.supports(this.encodingConfig.codec,i));if(r)this.customEncoder=new r,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=i,this.customEncoder.onPacket=(n,o)=>{if(!(n instanceof ct))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(o!==void 0&&(!o||typeof o!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(n,o),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,n,o).catch(a=>{this.error??=a,this.errorNeedsNewStack=!1})},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw new Error("VideoEncoder is not supported by this browser.");if(i.alpha="discard",this.encodingConfig.alpha==="keep"&&(i.latencyMode="quality"),(i.width%2===1||i.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${i.width}x${i.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);if(!(await VideoEncoder.isConfigSupported(i)).supported)throw new Error(`This specific encoder configuration (${i.codec}, ${i.bitrate} bps, ${i.width}x${i.height}, hardware acceleration: ${i.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);const a=[],p=[];let m=0,d=0;const l=(c,u,h)=>{const f={};if(u){const g=new Uint8Array(u.byteLength);u.copyTo(g),f.alpha=g}const b=ct.fromEncodedChunk(c,f);this.encodingConfig.onEncodedPacket?.(b,h),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,b,h).catch(g=>{this.error??=g,this.errorNeedsNewStack=!1})};this.encoder=new VideoEncoder({output:(c,u)=>{if(!this.alphaEncoder){l(c,null,u);return}const h=this.alphaFrameQueue.shift();$(h!==void 0),h?(this.alphaEncoder.encode(h,{keyFrame:c.type==="key"}),d++,h.close(),a.push({chunk:c,meta:u})):d===0?l(c,null,u):(p.push(m+d),a.push({chunk:c,meta:u}))},error:c=>{c.stack=t.stack,this.error??=c}}),this.encoder.configure(i),this.encodingConfig.alpha==="keep"&&(this.alphaEncoder=new VideoEncoder({output:(c,u)=>{d--;const h=a.shift();for($(h!==void 0),l(h.chunk,c,h.meta),m++;p.length>0&&p[0]===m;){p.shift();const f=a.shift();$(f!==void 0),l(f.chunk,null,f.meta)}},error:c=>{c.stack=t.stack,this.error??=c}}),this.alphaEncoder.configure(i))}$(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){e||this.checkForEncoderError(),this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||(await this.encoder.flush(),await this.alphaEncoder?.flush()),this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(t=>t?.close()),this.splitter?.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.errorNeedsNewStack&&(this.error.stack=new Error().stack),this.error}}class lh{constructor(e,t){this.lastFrame=null,typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(e,t):(this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=t);const i=this.canvas.getContext("webgl2",{alpha:!0});if(!i)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=i,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,"u_resolution"),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,"u_sourceTexture"),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,"u_sourceTexture"),0)}createVertexShader(){return this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
302
+ in vec2 a_position;
303
+ in vec2 a_texCoord;
304
+ out vec2 v_texCoord;
305
+
306
+ void main() {
307
+ gl_Position = vec4(a_position, 0.0, 1.0);
308
+ v_texCoord = a_texCoord;
309
+ }
310
+ `)}createColorProgram(){const e=this.createVertexShader(),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
311
+ precision highp float;
312
+
313
+ uniform sampler2D u_sourceTexture;
314
+ in vec2 v_texCoord;
315
+ out vec4 fragColor;
316
+
317
+ void main() {
318
+ vec4 source = texture(u_sourceTexture, v_texCoord);
319
+ fragColor = vec4(source.rgb, 1.0);
320
+ }
321
+ `),i=this.gl.createProgram();return this.gl.attachShader(i,e),this.gl.attachShader(i,t),this.gl.linkProgram(i),i}createAlphaProgram(){const e=this.createVertexShader(),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
322
+ precision highp float;
323
+
324
+ uniform sampler2D u_sourceTexture;
325
+ uniform vec2 u_resolution; // The width and height of the canvas
326
+ in vec2 v_texCoord;
327
+ out vec4 fragColor;
328
+
329
+ // This function determines the value for a single byte in the YUV stream
330
+ float getByteValue(float byteOffset) {
331
+ float width = u_resolution.x;
332
+ float height = u_resolution.y;
333
+
334
+ float yPlaneSize = width * height;
335
+
336
+ if (byteOffset < yPlaneSize) {
337
+ // This byte is in the luma plane. Find the corresponding pixel coordinates to sample from
338
+ float y = floor(byteOffset / width);
339
+ float x = mod(byteOffset, width);
340
+
341
+ // Add 0.5 to sample the center of the texel
342
+ vec2 sampleCoord = (vec2(x, y) + 0.5) / u_resolution;
343
+
344
+ // The luma value is the alpha from the source texture
345
+ return texture(u_sourceTexture, sampleCoord).a;
346
+ } else {
347
+ // Write a fixed value for chroma and beyond
348
+ return 128.0 / 255.0;
349
+ }
350
+ }
351
+
352
+ void main() {
353
+ // Each fragment writes 4 bytes (R, G, B, A)
354
+ float pixelIndex = floor(gl_FragCoord.y) * u_resolution.x + floor(gl_FragCoord.x);
355
+ float baseByteOffset = pixelIndex * 4.0;
356
+
357
+ vec4 result;
358
+ for (int i = 0; i < 4; i++) {
359
+ float currentByteOffset = baseByteOffset + float(i);
360
+ result[i] = getByteValue(currentByteOffset);
361
+ }
362
+
363
+ fragColor = result;
364
+ }
365
+ `),i=this.gl.createProgram();return this.gl.attachShader(i,e),this.gl.attachShader(i,t),this.gl.linkProgram(i),i}createShader(e,t){const i=this.gl.createShader(e);return this.gl.shaderSource(i,t),this.gl.compileShader(i),this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS)||console.error("Shader compile error:",this.gl.getShaderInfoLog(i)),i}createVAO(){const e=this.gl.createVertexArray();this.gl.bindVertexArray(e);const t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),i=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,i),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);const r=this.gl.getAttribLocation(this.colorProgram,"a_position"),n=this.gl.getAttribLocation(this.colorProgram,"a_texCoord");return this.gl.enableVertexAttribArray(r),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(n),this.gl.vertexAttribPointer(n,2,this.gl.FLOAT,!1,16,8),e}createTexture(){const e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}updateTexture(e){this.lastFrame!==e&&((e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.lastFrame=e)}extractColor(e){return this.updateTexture(e),this.gl.useProgram(this.colorProgram),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0,alpha:"discard"})}extractAlpha(e){this.updateTexture(e),this.gl.useProgram(this.alphaProgram),this.gl.uniform2f(this.alphaResolutionLocation,this.canvas.width,this.canvas.height),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);const{width:t,height:i}=this.canvas,r=Math.ceil(t/2)*Math.ceil(i/2),n=t*i+r*2,o=Math.ceil(n/(t*4));let a=new Uint8Array(4*t*o);this.gl.readPixels(0,0,t,o,this.gl.RGBA,this.gl.UNSIGNED_BYTE,a),a=a.subarray(0,n),$(a[t*i]===128),$(a[a.length-1]===128);const p={format:"I420",codedWidth:t,codedHeight:i,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[a.buffer]};return new VideoFrame(a,p)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}}class ch extends vn{constructor(e,t){if(!(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");th(t),super(t.codec),this._encoder=new oh(this,t),this._canvas=e}add(e,t=0,i){if(!Number.isFinite(e)||e<0)throw new TypeError("timestamp must be a non-negative number.");if(!Number.isFinite(t)||t<0)throw new TypeError("duration must be a non-negative number.");const r=new vt(this._canvas,{timestamp:e,duration:t});return this._encoder.add(r,!0,i)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class wn extends xs{constructor(e){if(super(),this._connectedTrack=null,!Mt.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${Mt.join(", ")}.`);this._codec=e}}class hh{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new Br,this.customEncoderQueueSize=0,this.error=null,this.errorNeedsNewStack=!0}async add(e,t){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;if(this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),$(this.encoderInitialized),this.customEncoder){this.customEncoderQueueSize++;const i=e.clone(),r=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(i)).then(()=>this.customEncoderQueueSize--).catch(n=>this.error??=n).finally(()=>{i.close()});this.customEncoderQueueSize>=4&&await r,await this.muxer.mutex.currentPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{$(this.encoder);const i=e.toAudioData();this.encoder.encode(i),i.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(r=>this.encoder.addEventListener("dequeue",r,{once:!0})),await this.muxer.mutex.currentPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){$(this.outputSampleSize),$(this.writeOutputValue);const{numberOfChannels:i,numberOfFrames:r,sampleRate:n,timestamp:o}=e,a=2048,p=[];for(let c=0;c<r;c+=a){const u=Math.min(a,e.numberOfFrames-c),h=u*i*this.outputSampleSize,f=new ArrayBuffer(h),b=new DataView(f);p.push({frameCount:u,view:b})}const m=e.allocationSize({planeIndex:0,format:"f32-planar"}),d=new Float32Array(m/Float32Array.BYTES_PER_ELEMENT);for(let c=0;c<i;c++){e.copyTo(d,{planeIndex:c,format:"f32-planar"});for(let u=0;u<p.length;u++){const{frameCount:h,view:f}=p[u];for(let b=0;b<h;b++)this.writeOutputValue(f,(b*i+c)*this.outputSampleSize,d[u*a+b])}}t&&e.close();const l={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:i,sampleRate:n}};for(let c=0;c<p.length;c++){const{frameCount:u,view:h}=p[c],f=h.buffer,b=c*a,g=new ct(new Uint8Array(f),"key",o+b/n,u/n);this.encodingConfig.onEncodedPacket?.(g,l),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,g,l)}}ensureEncoder(e){const t=new Error;this.ensureEncoderPromise=(async()=>{const{numberOfChannels:i,sampleRate:r}=e,n=ah({numberOfChannels:i,sampleRate:r,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(n);const o=Dl.find(a=>a.supports(this.encodingConfig.codec,n));if(o)this.customEncoder=new o,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=n,this.customEncoder.onPacket=(a,p)=>{if(!(a instanceof ct))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(p!==void 0&&(!p||typeof p!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(a,p),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,a,p).catch(m=>{this.error??=m,this.errorNeedsNewStack=!1})},await this.customEncoder.init();else if(Ne.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error("AudioEncoder is not supported by this browser.");if(!(await AudioEncoder.isConfigSupported(n)).supported)throw new Error(`This specific encoder configuration (${n.codec}, ${n.bitrate} bps, ${n.numberOfChannels} channels, ${n.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);this.encoder=new AudioEncoder({output:(p,m)=>{const d=ct.fromEncodedChunk(p);this.encodingConfig.onEncodedPacket?.(d,m),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,d,m).catch(l=>{this.error??=l,this.errorNeedsNewStack=!1})},error:p=>{p.stack=t.stack,this.error??=p}}),this.encoder.configure(n)}$(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;const e=this.encodingConfig.codec,{dataType:t,sampleSize:i,littleEndian:r}=Lt(e);switch(this.outputSampleSize=i,i){case 1:t==="unsigned"?this.writeOutputValue=(n,o,a)=>n.setUint8(o,Se((a+1)*127.5,0,255)):t==="signed"?this.writeOutputValue=(n,o,a)=>{n.setInt8(o,Se(Math.round(a*128),-128,127))}:t==="ulaw"?this.writeOutputValue=(n,o,a)=>{const p=Se(Math.floor(a*32767),-32768,32767);n.setUint8(o,zl(p))}:t==="alaw"?this.writeOutputValue=(n,o,a)=>{const p=Se(Math.floor(a*32767),-32768,32767);n.setUint8(o,Hl(p))}:$(!1);break;case 2:t==="unsigned"?this.writeOutputValue=(n,o,a)=>n.setUint16(o,Se((a+1)*32767.5,0,65535),r):t==="signed"?this.writeOutputValue=(n,o,a)=>n.setInt16(o,Se(Math.round(a*32767),-32768,32767),r):$(!1);break;case 3:t==="unsigned"?this.writeOutputValue=(n,o,a)=>Lr(n,o,Se((a+1)*83886075e-1,0,16777215),r):t==="signed"?this.writeOutputValue=(n,o,a)=>il(n,o,Se(Math.round(a*8388607),-8388608,8388607),r):$(!1);break;case 4:t==="unsigned"?this.writeOutputValue=(n,o,a)=>n.setUint32(o,Se((a+1)*21474836475e-1,0,4294967295),r):t==="signed"?this.writeOutputValue=(n,o,a)=>n.setInt32(o,Se(Math.round(a*2147483647),-2147483648,2147483647),r):t==="float"?this.writeOutputValue=(n,o,a)=>n.setFloat32(o,a,r):$(!1);break;case 8:t==="float"?this.writeOutputValue=(n,o,a)=>n.setFloat64(o,a,r):$(!1);break;default:as(i),$(!1)}}async flushAndClose(e){e||this.checkForEncoderError(),this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||await this.encoder.flush(),this.encoder.state!=="closed"&&this.encoder.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.errorNeedsNewStack&&(this.error.stack=new Error().stack),this.error}}class uh extends wn{constructor(e){rh(e),super(e.codec),this._encoder=new hh(this,e)}add(e){if(!(e instanceof wt))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class dh extends xs{constructor(e){if(super(),this._connectedTrack=null,!Ci.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${Ci.join(", ")}.`);this._codec=e}}/*!
366
+ * Copyright (c) 2025-present, Vanilagy and contributors
367
+ *
368
+ * This Source Code Form is subject to the terms of the Mozilla Public
369
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
370
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
371
+ */const fh=["video","audio","subtitle"],Cs=s=>{if(!s||typeof s!="object")throw new TypeError("metadata must be an object.");if(s.languageCode!==void 0&&!nl(s.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(s.name!==void 0&&typeof s.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(s.maximumPacketCount!==void 0&&(!Number.isInteger(s.maximumPacketCount)||s.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.")};class ph{constructor(e){if(this.state="pending",this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new Mr,this._metadataTags={},!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof mn))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof fn))throw new TypeError("options.target must be a Target.");if(e.target._output)throw new Error("Target is already used for another output.");e.target._output=this,this.format=e.format,this.target=e.target,this._writer=e.target._createWriter(),this._muxer=e.format._createMuxer(this)}addVideoTrack(e,t={}){if(!(e instanceof vn))throw new TypeError("source must be a VideoSource.");if(Cs(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw new Error(`${this.format._name} does not support video rotation metadata.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);this._addTrack("video",e,t)}addAudioTrack(e,t={}){if(!(e instanceof wn))throw new TypeError("source must be an AudioSource.");Cs(t),this._addTrack("audio",e,t)}addSubtitleTrack(e,t={}){if(!(e instanceof dh))throw new TypeError("source must be a SubtitleSource.");Cs(t),this._addTrack("subtitle",e,t)}setMetadataTags(e){if(cl(e),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e,t,i){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(t._connectedTrack)throw new Error("Source is already used for a track.");const r=this.format.getSupportedTrackCounts(),n=this._tracks.reduce((m,d)=>m+(d.type===e?1:0),0),o=r[e].max;if(n===o)throw new Error(o===0?`${this.format._name} does not support ${e} tracks.`:`${this.format._name} does not support more than ${o} ${e} track${o===1?"":"s"}.`);const a=r.total.max;if(this._tracks.length===a)throw new Error(`${this.format._name} does not support more than ${a} tracks${a===1?"":"s"} in total.`);const p={id:this._tracks.length+1,output:this,type:e,source:t,metadata:i};if(p.type==="video"){const m=this.format.getSupportedVideoCodecs();if(m.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(p.source._codec));if(!m.includes(p.source._codec))throw new Error(`Codec '${p.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${m.map(d=>`'${d}'`).join(", ")}.`+this.format._codecUnsupportedHint(p.source._codec))}else if(p.type==="audio"){const m=this.format.getSupportedAudioCodecs();if(m.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(p.source._codec));if(!m.includes(p.source._codec))throw new Error(`Codec '${p.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${m.map(d=>`'${d}'`).join(", ")}.`+this.format._codecUnsupportedHint(p.source._codec))}else if(p.type==="subtitle"){const m=this.format.getSupportedSubtitleCodecs();if(m.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(p.source._codec));if(!m.includes(p.source._codec))throw new Error(`Codec '${p.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${m.map(d=>`'${d}'`).join(", ")}.`+this.format._codecUnsupportedHint(p.source._codec))}this._tracks.push(p),t._connectedTrack=p}async start(){const e=this.format.getSupportedTrackCounts();for(const i of fh){const r=this._tracks.reduce((o,a)=>o+(a.type===i?1:0),0),n=e[i].min;if(r<n)throw new Error(n===e[i].max?`${this.format._name} requires exactly ${n} ${i} track${n===1?"":"s"}.`:`${this.format._name} requires at least ${n} ${i} track${n===1?"":"s"}.`)}const t=e.total.min;if(this._tracks.length<t)throw new Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?"":"s"}.`:`${this.format._name} requires at least ${t} track${t===1?"":"s"}.`);if(this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(console.warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started",this._writer.start();const i=await this._mutex.acquire();await this._muxer.start();const r=this._tracks.map(n=>n.source._start());await Promise.all(r),i()})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return console.warn("Output has already been canceled."),this._cancelPromise;if(this.state==="finalizing"||this.state==="finalized"){console.warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";const e=await this._mutex.acquire(),t=this._tracks.map(i=>i.source._flushOrWaitForOngoingClose(!0));await Promise.all(t),await this._writer.close(),e()})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(console.warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";const e=await this._mutex.acquire(),t=this._tracks.map(i=>i.source._flushOrWaitForOngoingClose(!1));await Promise.all(t),await this._muxer.finalize(),await this._writer.flush(),await this._writer.finalize(),this.state="finalized",e()})()}}class mh{audioTracks=[];async setupAudioTracks(e,t){const i=this.findAudioPlayers(e);if(!i.length)return null;this.audioTracks=[];for(const n of i){const o=await this.processAudioTrack(n);o&&this.audioTracks.push(o)}if(!this.audioTracks.length)return null;const r=new uh({codec:"aac",bitrate:128e3});return t.addAudioTrack(r),r}async processAudioSamples(e){if(!this.audioTracks?.length)return;const t=new AudioContext;for(const i of this.audioTracks){const r=await t.decodeAudioData(i.data.slice(0)),{numberOfChannels:n,sampleRate:o,length:a}=r,p=Math.min(a,Math.floor(o*i.duration/1e3)),m=new Float32Array(p*n);for(let d=0;d<n;d+=1){const l=r.getChannelData(d);for(let c=0;c<p;c+=1)m[c*n+d]=l[c]*i.volume}await e.add(new wt({data:m,format:"f32",numberOfChannels:n,sampleRate:o,timestamp:i.start/1e3}))}this.audioTracks=[]}findAudioPlayers(e){const t=[];for(const i of e)for(const r of i)this.isAudioPlayer(r)&&!t.includes(r)&&t.push(r);return t}async processAudioTrack(e){try{const t=e.clipConfiguration?.asset;if(!t?.src)return null;const i=await fetch(t.src);return i.ok?{data:await i.arrayBuffer(),start:e.getStart(),duration:e.getLength(),volume:e.getVolume()}:null}catch(t){return console.warn("Failed to process audio track:",t),null}}isAudioPlayer(e){if(e instanceof Os)return!0;if(!e||typeof e!="object")return!1;const t=e,i=t.constructor?.name==="AudioPlayer",o=t.clipConfiguration?.asset?.type==="audio";return i||o}}class gh{overlay=null;bar=null;percent=null;status=null;create(){this.overlay=Object.assign(document.createElement("div"),{style:"position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:9999;display:flex;justify-content:center;align-items:center;color:white;font-family:Arial"});const e=Object.assign(document.createElement("div"),{style:"background:#222;border-radius:8px;padding:20px;box-shadow:0 4px 8px rgba(0,0,0,0.2);width:300px;text-align:center"});e.innerHTML='<h3 style="margin:0 0 15px 0;font-weight:normal">Exporting Video</h3>',this.status=Object.assign(document.createElement("div"),{style:"font-size:12px;margin-bottom:10px;opacity:0.8"}),e.appendChild(this.status);const t=Object.assign(document.createElement("div"),{style:"width:100%;height:6px;background:#444;border-radius:3px;overflow:hidden;margin-bottom:10px"});this.bar=Object.assign(document.createElement("div"),{style:"width:0%;height:100%;background:#3498db;transition:width 0.3s"}),t.appendChild(this.bar),e.appendChild(t),this.percent=Object.assign(document.createElement("div"),{style:"font-size:12px",innerText:"0%"}),e.appendChild(this.percent),this.overlay.appendChild(e),document.body.appendChild(this.overlay)}update(e,t,i){if(!this.overlay)return;const r=Math.round(e/t*100);this.bar&&(this.bar.style.width=`${r}%`),this.percent&&(this.percent.innerText=`${r}%`),this.status&&i&&(this.status.innerText=i)}remove(){this.overlay?.remove(),this.overlay=null,this.bar=null,this.percent=null,this.status=null}}class _n extends Map{constructor(e){super(),this.maxSize=e}get(e){const t=super.get(e);if(t!==void 0)return super.delete(e),super.set(e,t),t}set(e,t){if(super.delete(e),super.set(e,t),this.size>this.maxSize){const i=this.keys().next().value;i&&this.delete(i)}return this}}class Ei extends Error{constructor(e,t="unknown",i={},r){super(e),this.phase=t,this.context=i,this.name="ExportError",this.cause=r}}class yh extends Ei{constructor(e,t){super(e,"initialization",{missingFeatures:t}),this.name="BrowserCompatibilityError"}}function xn(s){if(!s||typeof s!="object")return!1;const e=s,t=e.constructor?.name==="VideoPlayer",r=e.texture?.source?.resource instanceof HTMLVideoElement;return e.constructor?.name==="RichTextPlayer"?!1:t||r}class bh{frameCache=new _n(10);textureCache=new _n(5);videoElements=new Map;extractionCanvas=null;extractionContext=null;async initialize(e){for(const t of e)if(xn(t)){const i=t,r=i.texture?.source?.resource;r&&this.videoElements.set(this.getVideoKey(i),{element:r,player:i})}this.extractionCanvas=document.createElement("canvas"),this.extractionCanvas.width=3840,this.extractionCanvas.height=2160,this.extractionContext=this.extractionCanvas.getContext("2d",{willReadFrequently:!0,alpha:!0})}async extractFrame(e,t){const i=`${e}-${t}`,r=this.frameCache.get(i);if(r)return r;const n=this.videoElements.get(e);if(!n||!this.extractionContext||!this.extractionCanvas)return null;try{const{element:o,player:a}=n,p=(t-(a.getStart?.()||0))/1e3+(a.clipConfiguration?.asset?.trim||0);await this.seekToTime(o,p);const m=o.videoWidth||o.width||1920,d=o.videoHeight||o.height||1080;this.extractionContext.clearRect(0,0,m,d),this.extractionContext.drawImage(o,0,0,m,d);const l=this.extractionContext.getImageData(0,0,m,d);return this.frameCache.set(i,l),l}catch{return null}}async replaceVideoTexture(e,t){const i=await this.extractFrame(this.getVideoKey(e),t);if(!i)return;const r=`${this.getVideoKey(e)}-${t}`;let n=this.textureCache.get(r);if(!n){const o=document.createElement("canvas");o.width=i.width,o.height=i.height;const a=o.getContext("2d");a&&(a.putImageData(i,0,0),n=R.Texture.from(o),this.textureCache.set(r,n))}n&&e.texture&&(e.originalTextureSource||(e.originalTextureSource=e.texture.source,e.texture.source?.resource instanceof HTMLVideoElement&&(e.originalVideoElement=e.texture.source.resource)),e.texture=n,e.sprite?.texture&&(e.sprite.texture=n),e.lastReplacedTimestamp=t)}disableVideoPlayback(e){const t=[];for(const i of e)if(xn(i)){const r=i;t.push(r),r.texture?.source?.resource instanceof HTMLVideoElement&&r.texture.source.resource.pause(),r.skipVideoUpdate=!0}return t}getVideoKey(e){return e.clipConfiguration?.asset?.src||""}dispose(){this.frameCache.clear(),this.textureCache.clear(),this.videoElements.clear(),this.extractionCanvas=null,this.extractionContext=null}async seekToTime(e,t){return new Promise(i=>{if(Math.abs(e.currentTime-t)<.1){i();return}const r=()=>{e.removeEventListener("seeked",r),setTimeout(i,1)};e.addEventListener("seeked",r),e.currentTime=t})}}class vh{edit;canvas;app;isExporting=!1;videoProcessor=new bh;audioProcessor=new mh;progressUI=new gh;exportCommand=new Jo;constructor(e,t){this.edit=e,this.canvas=t,this.app=t.application,document.addEventListener("keydown",this.handleKeyDown)}async export(e="shotstack-export.mp4",t){if(typeof VideoEncoder>"u")throw new yh("WebCodecs API not supported",["VideoEncoder"]);if(this.isExporting)throw new Ei("Export in progress","init");this.isExporting=!0;const i=this.saveEditState();this.edit.setExportMode(!0);try{this.progressUI.create(),this.canvas.pauseTicker();const r=this.prepareConfig(t??this.edit.getEdit().output?.fps??30);this.progressUI.update(0,100,"Preparing..."),this.edit.executeEditCommand(this.exportCommand),await this.videoProcessor.initialize(this.exportCommand.getClips()),this.progressUI.update(10,100,"Video ready");const n=new ph({format:new yn,target:new pn}),o=document.createElement("canvas");o.width=r.size.width,o.height=r.size.height;const a=o.getContext("2d");if(!a)throw new Error("No 2D context");const p=new ch(o,{codec:"avc",bitrate:5e6});n.addVideoTrack(p),this.progressUI.update(15,100,"Audio...");const m=await this.audioProcessor.setupAudioTracks(this.exportCommand.getTracks(),n);await n.start(),m&&(this.progressUI.update(20,100,"Encoding audio..."),await this.audioProcessor.processAudioSamples(m)),this.progressUI.update(25,100,"Exporting..."),await this.processFrames(r,p,o,a),await n.finalize();const d=n.target.buffer;if(!d)throw new Error("No video data");const l=new Blob([d],{type:"video/mp4"}),c=URL.createObjectURL(l),u=document.createElement("a");u.href=c,u.download=e,u.click(),URL.revokeObjectURL(c),this.progressUI.update(100,100,"Complete!")}catch(r){throw r instanceof Ei?r:new Ei(`Export failed: ${r}`,"export")}finally{this.isExporting=!1,this.edit.setExportMode(!1),this.canvas.resumeTicker(),this.progressUI.remove(),this.restoreEditState(i)}}async processFrames(e,t,i,r){const n=this.edit.getContainer();this.edit.pause(),Object.assign(n.position,{x:0,y:0}),Object.assign(n.scale,{x:1,y:1}),n.visible=!0;const o=this.videoProcessor.disableVideoPlayback(this.exportCommand.getClips());for(let a=0;a<e.frames;a+=1){const p=a*e.frameDuration;this.edit.playbackTime=p;for(const l of this.exportCommand.getClips())l.update(0,0);for(const l of o){const c=l.getStart?.()||0,u=l.getEnd?.()||c+(l.getLength?.()||0);p>=c&&p<u&&await this.videoProcessor.replaceVideoTexture(l,p)}this.edit.draw(),this.app.renderer.render(this.app.stage);const m=this.app.renderer.extract.pixels({target:n,frame:new R.Rectangle(0,0,e.size.width,e.size.height)}),d=new ImageData(new Uint8ClampedArray(m.pixels),m.width,m.height);r.putImageData(d,0,0),await t.add(a/e.fps,1/e.fps),this.progressUI.update(25+Math.round((a+1)/e.frames*75),100,"Exporting...")}}handleKeyDown=e=>{e.target instanceof HTMLInputElement||e.target instanceof HTMLTextAreaElement||e.code==="KeyE"&&(e.metaKey||e.ctrlKey)&&!this.isExporting&&(e.preventDefault(),this.export("shotstack-export.mp4",this.edit.getEdit().output?.fps||30).catch(t=>console.error("Export failed:",t)))};dispose(){document.removeEventListener("keydown",this.handleKeyDown),this.videoProcessor.dispose(),this.progressUI.remove()}prepareConfig(e){const t=this.edit.getEdit().output?.size||{width:1920,height:1080},i=this.edit.totalDuration/1e3;return{fps:e,size:t,frames:Math.ceil(i*e),frameDuration:1e3/e}}saveEditState(){const e=this.edit.getContainer();return{wasPlaying:this.edit.isPlaying,time:this.edit.playbackTime,visible:e.visible,pos:{x:e.position.x,y:e.position.y},scale:{x:e.scale.x,y:e.scale.y}}}restoreEditState(e){const t=this.edit.getContainer();this.edit.setExportMode(!1);for(const i of this.exportCommand.getClips())if(this.isVideoPlayer(i)){const r=i;if(r.skipVideoUpdate=!1,r.originalVideoElement&&r.texture){const n=R.Texture.from(r.originalVideoElement);r.texture=n,r.sprite&&(r.sprite.texture=n),delete r.originalVideoElement,delete r.originalTextureSource,delete r.lastReplacedTimestamp}else r.originalTextureSource&&r.texture&&(r.texture.source=r.originalTextureSource,delete r.originalTextureSource,delete r.lastReplacedTimestamp)}Object.assign(t.position,e.pos),Object.assign(t.scale,e.scale),t.visible=e.visible,this.edit.seek(e.time),e.wasPlaying&&this.edit.play()}isVideoPlayer(e){if(!e||typeof e!="object")return!1;const t=e,i=t.constructor?.name==="VideoPlayer",n=t.texture?.source?.resource instanceof HTMLVideoElement;return i||n}}function Cn(s){const e=s.replace("#",""),t=parseInt(e,16);return Number.isNaN(t)?(console.warn(`Invalid hex color: ${s}, defaulting to black`),0):t}function wh(s){const e=t=>{if(typeof t=="string")return Cn(t);if(typeof t=="object"&&t!==null){const i=Array.isArray(t)?[]:{};for(const r in t)Object.prototype.hasOwnProperty.call(t,r)&&(i[r]=e(t[r]));return i}return t};return e(s)}function kn(s){if(typeof s=="string")return Cn(s);if(typeof s=="object"&&s!==null){const e=Array.isArray(s)?[]:{};for(const t in s)Object.prototype.hasOwnProperty.call(s,t)&&(e[t]=kn(s[t]));return e}return s}const Tn=wh({timeline:{background:"#1a1a1a",divider:"#1a1a1a",toolbar:{background:"#1a1a1a",surface:"#2a2a2a",hover:"#3a3a3a",active:"#007acc",divider:"#3a3a3a",icon:"#888888",text:"#ffffff",height:36},ruler:{background:"#404040",text:"#ffffff",markers:"#666666",height:40},tracks:{surface:"#2a2a2a",surfaceAlt:"#242424",border:"#3a3a3a",height:60},clips:{video:"#4a90e2",audio:"#7ed321",image:"#f5a623",text:"#d0021b",shape:"#9013fe",html:"#50e3c2",luma:"#b8e986",default:"#8e8e93",selected:"#007acc",radius:4},playhead:"#ff4444",snapGuide:"#888888",dropZone:"#00ff00",trackInsertion:"#00ff00"}});class Sn{static resolveTheme(e){if(!e||!e.theme)return this.deepClone(Tn);const t=kn(e.theme),i=this.deepClone(Tn);return this.deepMerge(i,t)}static validateTheme(e){try{if(!e.timeline)return!1;const{timeline:t}=e;if(typeof t.background!="number"||typeof t.divider!="number"||typeof t.playhead!="number"||typeof t.snapGuide!="number"||typeof t.dropZone!="number"||typeof t.trackInsertion!="number"||!t.toolbar)return!1;const{toolbar:i}=t;if(typeof i.background!="number"||typeof i.surface!="number"||typeof i.hover!="number"||typeof i.active!="number"||typeof i.divider!="number"||typeof i.icon!="number"||typeof i.text!="number"||typeof i.height!="number"||i.height<=0||!t.ruler)return!1;const{ruler:r}=t;if(typeof r.background!="number"||typeof r.text!="number"||typeof r.markers!="number"||typeof r.height!="number"||r.height<=0||!t.tracks)return!1;const{tracks:n}=t;if(typeof n.surface!="number"||typeof n.surfaceAlt!="number"||typeof n.border!="number"||typeof n.height!="number"||n.height<=0||!t.clips)return!1;const{clips:o}=t,a=["video","audio","image","text","shape","html","luma","default","selected"];for(const p of a)if(typeof o[p]!="number")return!1;return!(typeof o.radius!="number"||o.radius<0)}catch(t){return console.error("Theme validation error:",t),!1}}static deepClone(e){if(e===null||typeof e!="object")return e;if(e instanceof Array)return e.map(i=>this.deepClone(i));const t={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=this.deepClone(e[i]));return t}static deepMerge(e,t){const i={...e};for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const n=t[r],o=i[r];n!==void 0&&(typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof o=="object"&&o!==null&&!Array.isArray(o)?i[r]=this.deepMerge(o,n):i[r]=n)}return i}}class _h{timeline;constructor(e){this.timeline=e}getValidDropPosition(e,t,i,r){const n=this.timeline.getVisualTracks()[i];if(!n)return{validTime:e,wouldOverlap:!1};const o=this.getOtherClipBounds(n,r),a=e+t,p=o.find(u=>!(a<=u.start||e>=u.end));if(!p)return{validTime:e,wouldOverlap:!1};const m=p.start-t,d=p.end,l=Math.abs(e-m)<Math.abs(e-d)&&m>=0?m:d;return{validTime:this.getValidDropPosition(l,t,i,r).validTime,wouldOverlap:!0}}checkOverlap(e,t,i,r){const n=this.timeline.getVisualTracks()[i];if(!n)return!1;const o=this.getOtherClipBounds(n,r),a=e+t;return o.some(p=>!(a<=p.start||e>=p.end))}getOtherClipBounds(e,t){return e.getClips().map((i,r)=>({clip:i,index:r})).filter(({index:i})=>i!==t).map(({clip:i})=>{const r=i.getClipConfig();return r?{start:r.start||0,end:(r.start||0)+(r.length||0)}:null}).filter(i=>i!==null).sort((i,r)=>i.start-r.start)}findAvailableGaps(e,t){const i=this.timeline.getVisualTracks()[e];if(!i)return[];const r=this.getOtherClipBounds(i),n=[];r.length>0&&r[0].start>=t&&n.push({start:0,end:r[0].start});for(let o=0;o<r.length-1;o+=1)r[o+1].start-r[o].end>=t&&n.push({start:r[o].end,end:r[o+1].start});return n}}class En{constructor(e,t,i,r){this.fromTrackIndex=e,this.fromClipIndex=t,this.toTrackIndex=i,this.newStart=r,this.originalTrackIndex=e,this.originalClipIndex=t}name="moveClip";player;originalTrackIndex;originalClipIndex;originalStart;execute(e){if(!e)return;const t=e.getTracks();if(this.fromTrackIndex<0||this.fromTrackIndex>=t.length){console.warn(`Invalid source track index: ${this.fromTrackIndex}`);return}const i=t[this.fromTrackIndex];if(this.fromClipIndex<0||this.fromClipIndex>=i.length){console.warn(`Invalid clip index: ${this.fromClipIndex}`);return}if(this.player=i[this.fromClipIndex],this.originalStart=this.player.clipConfiguration.start,this.fromTrackIndex!==this.toTrackIndex){if(this.toTrackIndex<0||this.toTrackIndex>=t.length){console.warn(`Invalid destination track index: ${this.toTrackIndex}`);return}i.splice(this.fromClipIndex,1),this.player.layer=this.toTrackIndex+1;const r=t[this.toTrackIndex];let n=0;for(let o=0;o<r.length;o+=1){const a=r[o];if(a.clipConfiguration&&a.clipConfiguration.start!==void 0&&this.newStart<a.clipConfiguration.start)break;n+=1}r.splice(n,0,this.player),this.originalClipIndex=n}if(this.player.clipConfiguration.start=this.newStart,e.movePlayerToTrackContainer(this.player,this.fromTrackIndex,this.toTrackIndex),this.player.reconfigureAfterRestore(),this.player.draw(),e.updateDuration(),this.fromTrackIndex!==this.toTrackIndex){const r=t[this.fromTrackIndex],n=t[this.toTrackIndex];[...r,...n].forEach(o=>{o&&o!==this.player&&o.draw()})}e.emitEvent("clip:updated",{previous:{clip:{...this.player.clipConfiguration,start:this.originalStart},trackIndex:this.fromTrackIndex,clipIndex:this.fromClipIndex},current:{clip:this.player.clipConfiguration,trackIndex:this.toTrackIndex,clipIndex:this.originalClipIndex}})}undo(e){if(!e||!this.player||this.originalStart===void 0)return;const t=e.getTracks();if(this.fromTrackIndex!==this.toTrackIndex){const i=t[this.toTrackIndex],r=i.indexOf(this.player);r!==-1&&i.splice(r,1),this.player.layer=this.fromTrackIndex+1,t[this.fromTrackIndex].splice(this.fromClipIndex,0,this.player)}this.player.clipConfiguration.start=this.originalStart,e.movePlayerToTrackContainer(this.player,this.toTrackIndex,this.fromTrackIndex),this.player.reconfigureAfterRestore(),this.player.draw(),e.updateDuration(),e.emitEvent("clip:updated",{previous:{clip:{...this.player.clipConfiguration,start:this.newStart},trackIndex:this.toTrackIndex,clipIndex:this.originalClipIndex},current:{clip:this.player.clipConfiguration,trackIndex:this.fromTrackIndex,clipIndex:this.fromClipIndex}})}}class xh{constructor(e,t,i,r){this.insertionIndex=e,this.fromTrackIndex=t,this.fromClipIndex=i,this.newStart=r,this.addTrackCommand=new Sr(e);const n=t>=e?t+1:t;this.moveClipCommand=new En(n,i,e,r)}name="createTrackAndMoveClip";addTrackCommand;moveClipCommand;wasExecuted=!1;async execute(e){if(e)try{this.addTrackCommand.execute(e),this.moveClipCommand.execute(e),this.wasExecuted=!0}catch(t){if(this.wasExecuted)try{this.undo(e)}catch{}throw t}}undo(e){!e||!this.wasExecuted||(this.moveClipCommand.undo(e),this.addTrackCommand.undo(e),this.wasExecuted=!1,e.emitEvent("track:created:undone",{trackIndex:this.insertionIndex}))}}class Ch{timeline;thresholds;snapManager;collisionDetector;visualFeedback;dragInfo=null;currentDropZone=null;constructor(e,t,i,r,n){this.timeline=e,this.thresholds=t,this.snapManager=i,this.collisionDetector=r,this.visualFeedback=n}activate(){}deactivate(){this.endDrag()}canStartDrag(e,t){const i=Math.sqrt((t.x-e.x)**2+(t.y-e.y)**2),{trackHeight:r}=this.timeline.getLayout(),n=r<20?2:this.thresholds.drag.base;return i>n}startDrag(e,t){const i=this.timeline.getClipData(e.trackIndex,e.clipIndex);if(!i)return console.warn(`Clip data not found for track ${e.trackIndex}, clip ${e.clipIndex}`),!1;const r=this.timeline.getContainer().toLocal(t.global),n=this.timeline.getLayout(),o=n.getXAtTime(i.start||0),a=e.trackIndex*n.trackHeight;return this.dragInfo={trackIndex:e.trackIndex,clipIndex:e.clipIndex,startTime:i.start||0,offsetX:r.x-o,offsetY:r.y-a},this.timeline.getPixiApp().canvas.style.cursor="grabbing",this.timeline.getEdit().events.emit("drag:started",this.dragInfo),!0}updateDrag(e){if(!this.dragInfo)return;const t=this.calculateDragPosition(e),i=this.detectDropZone(t.y);i?this.handleDropZonePreview(i,t):this.handleNormalDragPreview(t),this.emitDragUpdate(t,i)}completeDrag(e){if(!this.dragInfo)return;const t={...this.dragInfo},i=this.calculateDragPosition(e),r=this.detectDropZone(i.y);this.endDrag(),r?this.executeDropZoneMove(r,t,i):this.executeNormalMove(t,i)}calculateDragPosition(e){if(!this.dragInfo)throw new Error("No drag info available");const t=this.timeline.getContainer().toLocal(e.global),i=this.timeline.getLayout(),r=Math.max(0,i.getTimeAtX(t.x-this.dragInfo.offsetX)),n=t.y-this.dragInfo.offsetY,o=n+i.trackHeight/2,a=Math.max(0,Math.floor(o/i.trackHeight)),p=this.timeline.getVisualTracks().length-1,m=Math.max(0,Math.min(p,a));return{x:t.x,y:t.y+i.viewportY,time:r,track:m,ghostY:n}}detectDropZone(e){const t=this.timeline.getLayout(),i=this.timeline.getVisualTracks(),r=t.trackHeight*this.thresholds.dropZone.ratio;for(let n=0;n<=i.length;n+=1){const o=t.tracksY+n*t.trackHeight;if(Math.abs(e-o)<r){let a;return n===0?a="above":n===i.length?a="below":a="between",{type:a,position:n}}}return null}handleDropZonePreview(e,t){(!this.currentDropZone||this.currentDropZone.type!==e.type||this.currentDropZone.position!==e.position)&&(this.currentDropZone=e,this.visualFeedback.showDropZone(e)),this.timeline.hideDragGhost(),this.visualFeedback.hideSnapGuidelines(),this.visualFeedback.hideTargetTrack()}handleNormalDragPreview(e){if(!this.dragInfo)return;this.currentDropZone&&(this.visualFeedback.hideDropZone(),this.currentDropZone=null);const t=this.timeline.getClipData(this.dragInfo.trackIndex,this.dragInfo.clipIndex);if(!t)return;const i=t.length||0,r=e.track===this.dragInfo.trackIndex?this.dragInfo.clipIndex:void 0,n=this.calculateFinalPosition(e.time,e.track,i,r),o=this.snapManager.findAlignedElements(n,i,e.track,r);o.length>0?this.visualFeedback.showSnapGuidelines(o):this.visualFeedback.hideSnapGuidelines(),this.visualFeedback.showTargetTrack(e.track),this.timeline.showDragGhost(e.track,n,e.ghostY)}calculateFinalPosition(e,t,i,r){const n=this.snapManager.calculateSnapPosition(e,t,i,r);return this.collisionDetector.getValidDropPosition(n.time,i,t,r).validTime}emitDragUpdate(e,t){if(!this.dragInfo)return;const i=this.timeline.getClipData(this.dragInfo.trackIndex,this.dragInfo.clipIndex);if(!i)return;const r=i.length||0,n=t?e.time:this.calculateFinalPosition(e.time,e.track,r,e.track===this.dragInfo.trackIndex?this.dragInfo.clipIndex:void 0);this.timeline.getEdit().events.emit("drag:moved",{...this.dragInfo,currentTime:n,currentTrack:t?-1:e.track})}executeDropZoneMove(e,t,i){const r=new xh(e.position,t.trackIndex,t.clipIndex,i.time);this.timeline.getEdit().executeEditCommand(r)}executeNormalMove(e,t){const i=this.timeline.getClipData(e.trackIndex,e.clipIndex);if(!i)return;const r=i.length||0,n=t.track===e.trackIndex?e.clipIndex:void 0,o=this.calculateFinalPosition(t.time,t.track,r,n);if(t.track!==e.trackIndex||Math.abs(o-e.startTime)>.01){const p=new En(e.trackIndex,e.clipIndex,t.track,o);this.timeline.getEdit().executeEditCommand(p)}}endDrag(){this.dragInfo=null,this.currentDropZone=null,this.visualFeedback.hideAll(),this.timeline.getPixiApp().canvas.style.cursor="default",this.timeline.getEdit().events.emit("drag:ended",{})}getDragInfo(){return this.dragInfo}dispose(){this.endDrag()}}class kh{constructor(e,t,i){this.trackIndex=e,this.clipIndex=t,this.newLength=i}name="resizeClip";originalLength;player;execute(e){if(!e)return;const t=e.getTrack(this.trackIndex);if(!t){console.warn(`Invalid track index: ${this.trackIndex}`);return}if(this.clipIndex<0||this.clipIndex>=t.length){console.warn(`Invalid clip index: ${this.clipIndex} for track ${this.trackIndex}`);return}this.player=t[this.clipIndex],this.originalLength=this.player.clipConfiguration.length,this.player.clipConfiguration.length=this.newLength,this.player.reconfigureAfterRestore(),this.player.draw(),e.updateDuration(),e.emitEvent("clip:updated",{previous:{clip:{...this.player.clipConfiguration,length:this.originalLength},trackIndex:this.trackIndex,clipIndex:this.clipIndex},current:{clip:this.player.clipConfiguration,trackIndex:this.trackIndex,clipIndex:this.clipIndex}})}undo(e){!e||!this.player||this.originalLength===void 0||(this.player.clipConfiguration.length=this.originalLength,this.player.reconfigureAfterRestore(),this.player.draw(),e.updateDuration(),e.emitEvent("clip:updated",{previous:{clip:{...this.player.clipConfiguration,length:this.newLength},trackIndex:this.trackIndex,clipIndex:this.clipIndex},current:{clip:this.player.clipConfiguration,trackIndex:this.trackIndex,clipIndex:this.clipIndex}}))}}class Th{timeline;thresholds;resizeInfo=null;constructor(e,t){this.timeline=e,this.thresholds=t}activate(){}deactivate(){this.endResize()}isOnClipRightEdge(e,t){const i=this.timeline.getVisualTracks()[e.trackIndex];if(!i)return!1;const r=i.getClip(e.clipIndex);if(!r)return!1;const o=r.getContainer().getBounds(),a=o.x+o.width,p=Math.abs(t.global.x-a),m=this.getResizeThreshold();return p<=m}startResize(e,t){const i=this.timeline.getClipData(e.trackIndex,e.clipIndex);if(!i)return!1;this.resizeInfo={trackIndex:e.trackIndex,clipIndex:e.clipIndex,originalLength:i.length||0,startX:t.global.x},this.timeline.getPixiApp().canvas.style.cursor="ew-resize";const r=this.timeline.getVisualTracks()[e.trackIndex];if(r){const n=r.getClip(e.clipIndex);n&&n.setResizing(!0)}return this.timeline.getEdit().events.emit("resize:started",this.resizeInfo),!0}updateResize(e){if(!this.resizeInfo)return;const t=e.global.x-this.resizeInfo.startX,i=this.timeline.getOptions().pixelsPerSecond||50,r=t/i,n=Math.max(.1,this.resizeInfo.originalLength+r),o=this.timeline.getVisualTracks()[this.resizeInfo.trackIndex];if(o){const a=o.getClip(this.resizeInfo.clipIndex);if(a){const p=n*i;a.setPreviewWidth(p),this.timeline.getEdit().events.emit("resize:updated",{width:p})}}}completeResize(e){if(!this.resizeInfo)return;const t=e.global.x-this.resizeInfo.startX,i=this.timeline.getOptions().pixelsPerSecond||50,r=t/i,n=Math.max(.1,this.resizeInfo.originalLength+r),o=this.timeline.getVisualTracks()[this.resizeInfo.trackIndex];if(o){const a=o.getClip(this.resizeInfo.clipIndex);a&&(a.setResizing(!1),a.setPreviewWidth(null))}if(Math.abs(n-this.resizeInfo.originalLength)>.01){const a=new kh(this.resizeInfo.trackIndex,this.resizeInfo.clipIndex,n);this.timeline.getEdit().executeEditCommand(a),this.timeline.getEdit().events.emit("resize:ended",{newLength:n})}this.endResize()}getCursorForPosition(e,t){return e&&this.isOnClipRightEdge(e,t)?"ew-resize":""}getResizeThreshold(){const{trackHeight:e}=this.timeline.getLayout();return Math.max(this.thresholds.resize.min,Math.min(this.thresholds.resize.max,e*this.thresholds.resize.ratio))}endResize(){this.resizeInfo=null,this.timeline.getPixiApp().canvas.style.cursor="default"}getResizeInfo(){return this.resizeInfo}dispose(){this.endResize()}}class Sh{timeline;thresholds;constructor(e,t){this.timeline=e,this.thresholds=t}getAllSnapPoints(e,t){const i=[];this.timeline.getVisualTracks().forEach((o,a)=>{o.getClips().forEach((m,d)=>{if(a===e&&d===t)return;const l=m.getClipConfig();l&&(i.push({time:l.start||0,type:"clip-start",trackIndex:a,clipIndex:d}),i.push({time:(l.start||0)+(l.length||0),type:"clip-end",trackIndex:a,clipIndex:d}))})});const n=this.timeline.getPlayheadTime();return i.push({time:n,type:"playhead"}),i}getTrackSnapPoints(e,t){return this.getAllSnapPoints(e,t).filter(i=>i.trackIndex===void 0||i.trackIndex===e)}calculateSnapPosition(e,t,i,r){const n=this.timeline.getOptions().pixelsPerSecond||50,o=this.thresholds.snap.pixels/n,a=this.getTrackSnapPoints(t,r);let p=null;for(const m of a){const d=Math.abs(e-m.time);d<o&&(!p||d<p.distance)&&(p={time:m.time,type:m.type,distance:d});const l=Math.abs(e+i-m.time);l<o&&(!p||l<p.distance)&&(p={time:m.time-i,type:m.type,distance:l})}return p?{time:p.time,snapped:!0,snapType:p.type}:{time:e,snapped:!1}}findAlignedElements(e,t,i,r){const o=e+t,a=new Map;this.timeline.getVisualTracks().forEach((m,d)=>{m.getClips().forEach((l,c)=>{if(d===i&&c===r)return;const u=l.getClipConfig();if(!u)return;const h=u.start||0,f=h+(u.length||0);[{time:h,aligns:[e,o]},{time:f,aligns:[e,o]}].forEach(({time:b,aligns:g})=>{g.some(y=>Math.abs(y-b)<.1)&&(a.has(b)||a.set(b,{tracks:new Set,isPlayhead:!1}),a.get(b).tracks.add(d))})})});const p=this.timeline.getPlayheadTime();return(Math.abs(e-p)<.1||Math.abs(o-p)<.1)&&(a.has(p)||a.set(p,{tracks:new Set,isPlayhead:!0}),a.get(p).isPlayhead=!0),Array.from(a.entries()).map(([m,d])=>({time:m,tracks:Array.from(d.tracks).concat(i),isPlayhead:d.isPlayhead}))}}class Eh{timeline;graphics=new Map;constructor(e){this.timeline=e}showDropZone(e){this.hideDropZone();const t=new R.Graphics,i=this.timeline.getLayout(),r=this.timeline.getExtendedTimelineWidth(),n=e.position*i.trackHeight,a=this.timeline.getTheme().timeline.trackInsertion;t.setStrokeStyle({width:4,color:a,alpha:.8}),t.moveTo(0,n),t.lineTo(r,n),t.stroke(),t.setStrokeStyle({width:8,color:a,alpha:.3}),t.moveTo(0,n),t.lineTo(r,n),t.stroke(),this.timeline.getContainer().addChild(t),this.graphics.set("dropZone",t)}hideDropZone(){this.hideGraphics("dropZone")}showSnapGuidelines(e){this.hideSnapGuidelines();const t=new R.Graphics,i=this.timeline.getLayout(),r=this.timeline.getTheme();e.forEach(({time:n,tracks:o,isPlayhead:a})=>{const p=i.getXAtTime(n),m=Math.min(...o),d=Math.max(...o),l=m*i.trackHeight,c=(d+1)*i.trackHeight,u=a?r.timeline.playhead:r.timeline.snapGuide;t.setStrokeStyle({width:3,color:u,alpha:.3}),t.moveTo(p,l),t.lineTo(p,c),t.stroke(),t.setStrokeStyle({width:1,color:u,alpha:.8}),t.moveTo(p,l),t.lineTo(p,c),t.stroke()}),this.timeline.getContainer().addChild(t),this.graphics.set("snapGuidelines",t)}hideSnapGuidelines(){this.hideGraphics("snapGuidelines")}showTargetTrack(e){this.hideTargetTrack();const t=new R.Graphics,i=this.timeline.getLayout(),r=this.timeline.getExtendedTimelineWidth(),n=e*i.trackHeight,o=i.trackHeight,p=this.timeline.getTheme().timeline.dropZone;t.rect(0,n,r,o),t.fill({color:p,alpha:.1}),t.setStrokeStyle({width:1,color:p,alpha:.3}),t.rect(0,n,r,o),t.stroke(),this.timeline.getContainer().addChild(t),this.graphics.set("targetTrack",t)}hideTargetTrack(){this.hideGraphics("targetTrack")}hideAll(){this.graphics.forEach((e,t)=>this.hideGraphics(t))}hideGraphics(e){const t=this.graphics.get(e);t&&(t.clear(),t.parent&&t.parent.removeChild(t),t.destroy(),this.graphics.delete(e))}dispose(){this.hideAll(),this.graphics.clear()}}class Ah{timeline;state={type:"idle"};abortController;dragHandler;resizeHandler;snapManager;collisionDetector;visualFeedback;thresholds={drag:{base:3,small:2},resize:{min:12,max:20,ratio:.4},dropZone:{ratio:.15},snap:{pixels:10,time:.1}};constructor(e,t){if(this.timeline=e,t){const i=structuredClone(this.thresholds);t.drag&&Object.assign(i.drag,t.drag),t.resize&&Object.assign(i.resize,t.resize),t.dropZone&&Object.assign(i.dropZone,t.dropZone),t.snap&&Object.assign(i.snap,t.snap),this.thresholds=i}this.snapManager=new Sh(e,this.thresholds),this.collisionDetector=new _h(e),this.visualFeedback=new Eh(e),this.dragHandler=new Ch(e,this.thresholds,this.snapManager,this.collisionDetector,this.visualFeedback),this.resizeHandler=new Th(e,this.thresholds)}activate(){this.abortController=new AbortController,this.setupEventListeners(),this.dragHandler.activate(),this.resizeHandler.activate()}deactivate(){this.abortController&&(this.abortController.abort(),this.abortController=void 0),this.resetState(),this.dragHandler.deactivate(),this.resizeHandler.deactivate()}setupEventListeners(){const e=this.timeline.getPixiApp();e.stage.interactive=!0,e.stage.on("pointerdown",this.handlePointerDown.bind(this),{signal:this.abortController?.signal}),e.stage.on("pointermove",this.handlePointerMove.bind(this),{signal:this.abortController?.signal}),e.stage.on("pointerup",this.handlePointerUp.bind(this),{signal:this.abortController?.signal}),e.stage.on("pointerupoutside",this.handlePointerUp.bind(this),{signal:this.abortController?.signal})}handlePointerDown(e){const t=e.target;if(t.label){const i=this.parseClipLabel(t.label);if(i){if(this.resizeHandler.isOnClipRightEdge(i,e)){if(this.resizeHandler.startResize(i,e)){const r=this.resizeHandler.getResizeInfo();r&&(this.state={type:"resizing",resizeInfo:r})}return}this.state={type:"selecting",startPos:{x:e.global.x,y:e.global.y},clipInfo:i},this.timeline.getPixiApp().canvas.style.cursor="grab";return}}this.timeline.getEdit().clearSelection()}handlePointerMove(e){switch(this.state.type){case"selecting":this.handleSelectingMove(e);break;case"dragging":this.timeline.getPixiApp().canvas.style.cursor="grabbing",this.dragHandler.updateDrag(e);break;case"resizing":this.timeline.getPixiApp().canvas.style.cursor="ew-resize",this.resizeHandler.updateResize(e);break;case"idle":this.updateCursorForPosition(e);break}}handlePointerUp(e){switch(this.state.type){case"selecting":this.timeline.getEdit().selectClip(this.state.clipInfo.trackIndex,this.state.clipInfo.clipIndex);break;case"dragging":this.dragHandler.completeDrag(e);break;case"resizing":this.resizeHandler.completeResize(e);break}this.resetState()}handleSelectingMove(e){if(this.state.type!=="selecting")return;const t={x:e.global.x,y:e.global.y};if(this.dragHandler.canStartDrag(this.state.startPos,t)&&this.dragHandler.startDrag(this.state.clipInfo,e)){const i=this.dragHandler.getDragInfo();i&&(this.state={type:"dragging",dragInfo:i})}}updateCursorForPosition(e){const t=e.target;if(t.label){const i=this.parseClipLabel(t.label);if(i){const r=this.resizeHandler.getCursorForPosition(i,e);if(r){this.timeline.getPixiApp().canvas.style.cursor=r;return}this.timeline.getPixiApp().canvas.style.cursor="grab";return}}this.timeline.getPixiApp().canvas.style.cursor="default"}parseClipLabel(e){if(!e?.startsWith("clip-"))return null;const t=e.split("-");if(t.length!==3)return null;const i=parseInt(t[1],10),r=parseInt(t[2],10);return Number.isNaN(i)||Number.isNaN(r)?null:{trackIndex:i,clipIndex:r}}resetState(){this.state={type:"idle"},this.visualFeedback.hideAll(),this.timeline.getPixiApp().canvas.style.cursor="default"}dispose(){this.deactivate(),this.dragHandler.dispose(),this.resizeHandler.dispose(),this.visualFeedback.dispose()}}class Ih{constructor(e,t,i,r,n){this.container=e,this.layout=t,this.getPixelsPerSecond=i,this.getTrackHeight=r,this.getVisualTracks=n}dragPreviewContainer=null;dragPreviewGraphics=null;draggedClipInfo=null;showDragPreview(e,t,i){if(!i)return;this.draggedClipInfo={trackIndex:e,clipIndex:t,clipConfig:i},this.dragPreviewContainer=new R.Container,this.dragPreviewGraphics=new R.Graphics,this.dragPreviewContainer.addChild(this.dragPreviewGraphics),this.container.addChild(this.dragPreviewContainer),this.getVisualTracks()[e]?.getClip(t)?.setDragging(!0),this.drawDragPreview(e,i.start||0)}drawDragPreview(e,t){if(!this.dragPreviewContainer||!this.dragPreviewGraphics||!this.draggedClipInfo)return;const{clipConfig:i}=this.draggedClipInfo,r=this.layout.getXAtTime(t),n=e*this.layout.trackHeight,o=(i.length||0)*this.getPixelsPerSecond();this.dragPreviewGraphics.clear(),this.dragPreviewGraphics.roundRect(0,0,o,this.getTrackHeight(),4),this.dragPreviewGraphics.fill({color:9342611,alpha:.6}),this.dragPreviewGraphics.stroke({width:2,color:65280}),this.dragPreviewContainer.position.set(r,n)}drawDragPreviewAtPosition(e,t,i){if(!this.dragPreviewContainer||!this.dragPreviewGraphics||!this.draggedClipInfo)return;const{clipConfig:r}=this.draggedClipInfo,n=this.layout.getXAtTime(e),o=(r.length||0)*this.getPixelsPerSecond(),a=this.getTrackHeight();this.dragPreviewGraphics.clear(),this.dragPreviewGraphics.roundRect(0,0,o,a,4),this.dragPreviewGraphics.fill({color:9342611,alpha:.6});const p=i*this.layout.trackHeight,d=Math.abs(t-p)<5?65280:16755200;this.dragPreviewGraphics.stroke({width:2,color:d}),this.dragPreviewContainer.position.set(n,t)}hideDragPreview(){this.dragPreviewContainer&&(this.dragPreviewContainer.destroy({children:!0}),this.dragPreviewContainer=null,this.dragPreviewGraphics=null),this.draggedClipInfo&&(this.getVisualTracks()[this.draggedClipInfo.trackIndex]?.getClip(this.draggedClipInfo.clipIndex)?.setDragging(!1),this.draggedClipInfo=null)}hideDragGhost(){this.dragPreviewContainer&&(this.dragPreviewContainer.visible=!1)}showDragGhost(e,t,i){!this.dragPreviewContainer||!this.draggedClipInfo||(this.dragPreviewContainer.visible=!0,i!==void 0?this.drawDragPreviewAtPosition(t,i,e):this.drawDragPreview(e,t))}getDraggedClipInfo(){return this.draggedClipInfo}hasActivePreview(){return this.dragPreviewContainer!==null}dispose(){this.hideDragPreview()}}class Ph{constructor(e,t,i,r,n){this.layout=e,this.trackLayer=t,this.overlayLayer=i,this.entityContainer=r,this.onRender=n}scrollX=0;scrollY=0;zoomLevel=1;viewport;rulerViewport;playheadContainer;async setupViewport(){this.rulerViewport=new R.Container,this.rulerViewport.label="ruler-viewport",this.overlayLayer.addChild(this.rulerViewport),this.playheadContainer=new R.Container,this.playheadContainer.label="playhead-container",this.overlayLayer.addChild(this.playheadContainer),this.viewport=new R.Container,this.viewport.label="viewport",this.trackLayer.addChild(this.viewport),this.viewport.addChild(this.entityContainer)}updateViewportTransform(){const e=this.layout.calculateViewportPosition(this.scrollX,this.scrollY);this.viewport.position.set(e.x,e.y),this.viewport.scale.set(this.zoomLevel,this.zoomLevel),this.rulerViewport.position.x=e.x,this.rulerViewport.scale.x=this.zoomLevel,this.playheadContainer.position.x=e.x,this.playheadContainer.scale.x=this.zoomLevel}setScroll(e,t){this.scrollX=e,this.scrollY=t,this.updateViewportTransform(),this.onRender()}setZoom(e){this.zoomLevel=Math.max(.1,Math.min(10,e)),this.updateViewportTransform(),this.onRender()}getViewport(){return{x:this.scrollX,y:this.scrollY,zoom:this.zoomLevel}}getMainViewport(){return this.viewport}getRulerViewport(){return this.rulerViewport}getPlayheadContainer(){return this.playheadContainer}}const Pe={MIN_WIDTH:50,PADDING:4,DEFAULT_ALPHA:1,DRAG_OPACITY:.6,RESIZE_OPACITY:.9,BORDER_WIDTH:2,CORNER_RADIUS:4,SELECTED_BORDER_MULTIPLIER:2,TEXT_FONT_SIZE:12,TEXT_TRUNCATE_SUFFIX_LENGTH:3},ri={PADDING:2,LABEL_PADDING:8,DEFAULT_OPACITY:.8,BORDER_WIDTH:1},Le={TOOLBAR_HEIGHT_RATIO:.12,RULER_HEIGHT_RATIO:.133,TOOLBAR_HEIGHT_DEFAULT:36,RULER_HEIGHT_DEFAULT:40,TRACK_HEIGHT_DEFAULT:80,BORDER_WIDTH:2,CORNER_RADIUS:4,CLIP_PADDING:4,LABEL_PADDING:8,TRACK_PADDING:2,MIN_CLIP_WIDTH:50};function Ai(s){const e=s.split("/");return e[e.length-1]||s}function Rh(s){switch(s.type){case"video":return s.src?Ai(s.src):"Video";case"audio":return s.src?Ai(s.src):"Audio";case"image":return s.src?Ai(s.src):"Image";case"text":return s.text||"Text";case"rich-text":return s.text||"Rich Text";case"shape":return s.shape||"Shape";case"html":return"HTML";case"luma":return s.src?Ai(s.src):"Luma";default:return"Unknown Asset"}}class Oh extends Je{clipConfig;options;graphics;background;text;selectionRenderer;lastGlobalX=-1;lastGlobalY=-1;visualState={mode:"normal"};CLIP_PADDING=Pe.PADDING;BORDER_WIDTH=Pe.BORDER_WIDTH;get CORNER_RADIUS(){return this.options.theme.timeline.clips.radius||Pe.CORNER_RADIUS}constructor(e,t){super(),this.clipConfig=e,this.options=t,this.selectionRenderer=t.selectionRenderer,this.graphics=new R.Graphics,this.background=new R.Graphics,this.text=new R.Text,this.setupContainer()}async load(){this.setupGraphics(),this.updateVisualState()}setupContainer(){const e=this.getContainer();e.label=`clip-${this.options.trackIndex}-${this.options.clipIndex}`,e.interactive=!0,e.cursor="pointer",e.addChild(this.background),e.addChild(this.graphics),e.addChild(this.text)}setupGraphics(){this.text.style=new R.TextStyle({fontSize:Pe.TEXT_FONT_SIZE,fill:this.options.theme.timeline.toolbar.text,fontWeight:"bold",wordWrap:!1,fontFamily:"Arial, sans-serif"}),this.text.anchor.set(0,0),this.text.x=this.CLIP_PADDING,this.text.y=this.CLIP_PADDING}updateFromConfig(e){this.clipConfig=e,this.updateVisualState()}updateVisualState(){this.updatePosition(),this.updateAppearance(),this.updateSize(),this.updateText()}setVisualState(e){this.visualState={...this.visualState,...e},this.updateVisualState()}updatePosition(){const e=this.getContainer(),t=this.clipConfig.start||0;e.x=t*this.options.pixelsPerSecond,e.y=0}updateSize(){const e=this.getEffectiveWidth(),t=this.options.trackHeight;this.drawClipBackground(e,t),this.drawClipBorder(e,t)}getEffectiveWidth(){if(this.visualState.previewWidth!==void 0)return this.visualState.previewWidth;const t=(this.clipConfig.length||0)*this.options.pixelsPerSecond;return Math.max(Pe.MIN_WIDTH,t)}drawClipBackground(e,t){const i=this.getClipColor(),r=this.getStateStyles();this.background.clear(),this.background.roundRect(0,0,e,t,this.CORNER_RADIUS),this.background.fill({color:i,alpha:r.alpha})}drawClipBorder(e,t){const i=this.getStateStyles(),r=this.BORDER_WIDTH;this.graphics.clear(),this.graphics.roundRect(0,0,e,t,this.CORNER_RADIUS),this.graphics.stroke({width:r,color:i.borderColor}),this.updateSelectionState(e,t)}updateSelectionState(e,t){if(!this.selectionRenderer)return;const i=this.visualState.mode==="selected",r=this.getClipId();if(!i){this.selectionRenderer.clearSelection(r);return}const o=this.getContainer().toGlobal(new R.Point(0,0)),p=this.selectionRenderer.getOverlay().toLocal(o);this.selectionRenderer.renderSelection(r,{x:p.x,y:p.y,width:e,height:t,cornerRadius:this.CORNER_RADIUS,borderWidth:this.BORDER_WIDTH},i)}getClipColor(){const e=this.clipConfig.asset?.type,t=this.options.theme.timeline.clips;switch(e){case"video":return t.video;case"audio":return t.audio;case"image":return t.image;case"text":return t.text;case"rich-text":return t["rich-text"]||t.text;case"shape":return t.shape;case"html":return t.html;case"luma":return t.luma;default:return t.default}}updateAppearance(){const e=this.getContainer();e.alpha=this.visualState.mode==="dragging"?Pe.DRAG_OPACITY:Pe.DEFAULT_ALPHA}updateText(){const e=this.clipConfig.asset?Rh(this.clipConfig.asset):"Clip";this.text.text=e;const i=(this.clipConfig.length||0)*this.options.pixelsPerSecond-this.CLIP_PADDING*2;if(this.text.width>i){const r=i/this.text.width,n=Math.floor(e.length*r)-Pe.TEXT_TRUNCATE_SUFFIX_LENGTH;this.text.text=`${e.substring(0,Math.max(1,n))}...`}}getStateStyles(){const{theme:e}=this.options;switch(this.visualState.mode){case"dragging":return{alpha:Pe.DRAG_OPACITY,borderColor:e.timeline.tracks.border};case"resizing":return{alpha:Pe.RESIZE_OPACITY,borderColor:e.timeline.dropZone};case"selected":return{alpha:Pe.DEFAULT_ALPHA,borderColor:e.timeline.clips.selected};default:return{alpha:Pe.DEFAULT_ALPHA,borderColor:e.timeline.tracks.border}}}setSelected(e){this.setVisualState({mode:e?"selected":"normal"})}setDragging(e){this.setVisualState({mode:e?"dragging":"normal"})}setResizing(e){this.setVisualState({mode:e?"resizing":"normal",...e?{}:{previewWidth:void 0}})}setPreviewWidth(e){this.setVisualState({previewWidth:e||void 0})}setPixelsPerSecond(e){if(this.updateOptions({pixelsPerSecond:e}),this.visualState.mode==="selected"){const t=this.getEffectiveWidth(),i=this.options.trackHeight;this.updateSelectionState(t,i)}}updateOptions(e){this.options={...this.options,...e},this.updateVisualState()}getClipConfig(){return this.clipConfig}getOptions(){return{...this.options}}getVisualState(){return{...this.visualState}}getSelected(){return this.visualState.mode==="selected"}getClipId(){return`${this.options.trackIndex}-${this.options.clipIndex}`}getDragging(){return this.visualState.mode==="dragging"}getRightEdgeX(){const e=this.getEffectiveWidth();return(this.clipConfig.start||0)*this.options.pixelsPerSecond+e}update(e,t){if(this.visualState.mode==="selected"&&this.selectionRenderer){const r=this.getContainer().toGlobal(new R.Point(0,0));if(r.x!==this.lastGlobalX||r.y!==this.lastGlobalY){this.lastGlobalX=r.x,this.lastGlobalY=r.y;const n=this.getEffectiveWidth(),o=this.options.trackHeight;this.updateSelectionState(n,o)}}}draw(){}dispose(){this.selectionRenderer&&this.selectionRenderer.clearSelection(this.getClipId()),this.background.destroy(),this.graphics.destroy(),this.text.destroy()}}class Fh extends Je{clips=[];options;background;TRACK_PADDING=ri.PADDING;LABEL_PADDING=ri.LABEL_PADDING;constructor(e){super(),this.options=e,this.background=new R.Graphics,this.setupContainer()}async load(){this.updateTrackAppearance()}setupContainer(){const e=this.getContainer();e.label=`track-${this.options.trackIndex}`,e.addChild(this.background),e.y=this.options.trackIndex*this.options.trackHeight}updateTrackAppearance(){const{width:e}=this.options,t=this.options.trackHeight,{theme:i}=this.options;this.background.clear();const r=this.options.trackIndex%2===0?i.timeline.tracks.surface:i.timeline.tracks.surfaceAlt;this.background.rect(0,0,e,t),this.background.fill({color:r,alpha:ri.DEFAULT_OPACITY}),this.background.rect(0,0,e,t),this.background.stroke({width:ri.BORDER_WIDTH,color:i.timeline.tracks.border}),this.background.moveTo(0,t-1),this.background.lineTo(e,t-1),this.background.stroke({width:ri.BORDER_WIDTH,color:i.timeline.divider})}rebuildFromTrackData(e,t){this.options={...this.options,pixelsPerSecond:t},this.clearAllClips(),e.clips&&e.clips.forEach((i,r)=>{const n={pixelsPerSecond:this.options.pixelsPerSecond,trackHeight:this.options.trackHeight,trackIndex:this.options.trackIndex,clipIndex:r,theme:this.options.theme,selectionRenderer:this.options.selectionRenderer},o=new Oh(i,n);this.addClip(o)}),this.updateTrackAppearance()}async addClip(e){this.clips.push(e),await e.load(),this.getContainer().addChild(e.getContainer())}clearAllClips(){const e=this.getContainer();for(const t of this.clips)e.removeChild(t.getContainer()),t.dispose();this.clips=[]}removeClip(e){if(e>=0&&e<this.clips.length){const t=this.clips[e];this.getContainer().removeChild(t.getContainer()),t.dispose(),this.clips.splice(e,1)}}updateClip(e,t){e>=0&&e<this.clips.length&&this.clips[e].updateFromConfig(t)}setPixelsPerSecond(e){this.options={...this.options,pixelsPerSecond:e},this.clips.forEach(t=>{t.setPixelsPerSecond(e)})}setWidth(e){this.options={...this.options,width:e},this.updateTrackAppearance()}setTrackIndex(e){this.options={...this.options,trackIndex:e};const t=this.getContainer();t.y=e*this.options.trackHeight,this.clips.forEach((i,r)=>{i.updateOptions({trackIndex:e})})}selectClip(e){this.clearAllSelections(),e>=0&&e<this.clips.length&&this.clips[e].setSelected(!0)}clearAllSelections(){this.clips.forEach(e=>{e.setSelected(!1)})}getSelectedClip(){return this.clips.find(e=>e.getSelected())||null}getSelectedClipIndex(){return this.clips.findIndex(e=>e.getSelected())}getClips(){return[...this.clips]}getClip(e){return this.clips[e]||null}getClipCount(){return this.clips.length}getTrackIndex(){return this.options.trackIndex}getTrackHeight(){return this.options.trackHeight}getOptions(){return{...this.options}}findClipAtPosition(e,t){if(t<0||t>this.options.trackHeight)return null;const i=e/this.options.pixelsPerSecond;for(let r=0;r<this.clips.length;r+=1){const n=this.clips[r],o=n.getClipConfig(),a=o.start||0,p=a+(o.length||0);if(i>=a&&i<=p)return{clip:n,clipIndex:r}}return null}update(e,t){this.clips.forEach(i=>{i.update(e,t)})}draw(){this.clips.forEach(e=>{e.draw()})}dispose(){this.clearAllClips(),this.background.destroy()}}class Mh{constructor(e,t){this.overlay=e,this.theme=t}selectionGraphics=new Map;renderSelection(e,t,i){if(!i){this.clearSelection(e);return}let r=this.selectionGraphics.get(e);r||(r=new R.Graphics,r.label=`selection-border-${e}`,this.selectionGraphics.set(e,r),this.overlay.addChild(r)),r.position.set(t.x,t.y),r.clear(),r.setStrokeStyle({width:t.borderWidth*Pe.SELECTED_BORDER_MULTIPLIER,color:this.theme.timeline.clips.selected}),r.roundRect(0,0,t.width,t.height,t.cornerRadius),r.stroke()}clearSelection(e){const t=this.selectionGraphics.get(e);t&&(this.overlay.removeChild(t),t.destroy(),this.selectionGraphics.delete(e))}clearAllSelections(){this.selectionGraphics.forEach((e,t)=>{this.clearSelection(t)})}updateTheme(e){this.theme=e,this.selectionGraphics.forEach(t=>{t.clear()})}getOverlay(){return this.overlay}dispose(){this.clearAllSelections()}}class Lh{constructor(e,t,i,r,n){this.container=e,this.layout=t,this.theme=i,this.getPixelsPerSecond=r,this.getExtendedTimelineWidth=n,this.selectionOverlay=new R.Container,this.selectionOverlay.label="selectionOverlay",this.container.addChild(this.selectionOverlay),this.selectionRenderer=new Mh(this.selectionOverlay,this.theme)}visualTracks=[];selectionOverlay;selectionRenderer;async rebuildFromEdit(e,t){if(e?.timeline?.tracks){this.clearAllVisualState();for(let i=0;i<e.timeline.tracks.length;i+=1){const r=e.timeline.tracks[i],n={pixelsPerSecond:t,trackHeight:this.layout.trackHeight,trackIndex:i,width:this.getExtendedTimelineWidth(),theme:this.theme,selectionRenderer:this.selectionRenderer},o=new Fh(n);await o.load(),o.rebuildFromTrackData(r,t),this.container.addChild(o.getContainer()),this.visualTracks.push(o)}this.container.setChildIndex(this.selectionOverlay,this.container.children.length-1)}}clearAllVisualState(){this.visualTracks.forEach(e=>{this.container.removeChild(e.getContainer()),e.dispose()}),this.visualTracks=[],this.selectionRenderer.clearAllSelections()}updateVisualSelection(e,t){this.clearVisualSelection();const i=this.visualTracks[e];if(i){const r=i.getClip(t);r&&r.setSelected(!0)}}clearVisualSelection(){this.visualTracks.forEach(e=>{e.getClips().forEach(i=>{i.setSelected(!1)})})}findClipAtPosition(e,t){const i=Math.floor(t/this.layout.trackHeight);if(i<0||i>=this.visualTracks.length)return null;const r=this.visualTracks[i],n=t-i*this.layout.trackHeight,o=r.findClipAtPosition(e,n);return o?{trackIndex:i,clipIndex:o.clipIndex,clipConfig:o.clip.getClipConfig(),x:(o.clip.getClipConfig().start||0)*this.getPixelsPerSecond(),y:i*this.layout.trackHeight,width:(o.clip.getClipConfig().length||0)*this.getPixelsPerSecond(),height:this.layout.trackHeight}:null}updateTrackWidths(e){this.visualTracks.forEach(t=>{t.setWidth(e)})}getVisualTracks(){return this.visualTracks}updatePixelsPerSecond(e){this.visualTracks.forEach(t=>{t.setPixelsPerSecond(e)})}getSelectionOverlay(){return this.selectionOverlay}getSelectionRenderer(){return this.selectionRenderer}dispose(){this.clearAllVisualState(),this.selectionRenderer&&this.selectionRenderer.dispose(),this.selectionOverlay&&this.container&&(this.container.removeChild(this.selectionOverlay),this.selectionOverlay.destroy())}}class Bh{constructor(e,t){this.edit=e,this.callbacks=t}setupEventListeners(){this.edit.events.on("timeline:updated",this.handleTimelineUpdated.bind(this)),this.edit.events.on("clip:updated",this.handleClipUpdated.bind(this)),this.edit.events.on("clip:selected",this.handleClipSelected.bind(this)),this.edit.events.on("selection:cleared",this.handleSelectionCleared.bind(this)),this.edit.events.on("drag:started",this.handleDragStarted.bind(this)),this.edit.events.on("drag:ended",this.handleDragEnded.bind(this)),this.edit.events.on("track:created",this.handleTrackCreated.bind(this))}async handleTimelineUpdated(e){await this.callbacks.onEditChange(e.current)}async handleClipUpdated(){await this.callbacks.onEditChange()}handleClipSelected(e){this.callbacks.onClipSelected(e.trackIndex,e.clipIndex)}handleSelectionCleared(){this.callbacks.onSelectionCleared()}handleDragStarted(e){this.callbacks.onDragStarted(e.trackIndex,e.clipIndex)}handleDragEnded(){this.callbacks.onDragEnded()}async handleTrackCreated(){await this.callbacks.onEditChange()}handleSeek(e){this.callbacks.onSeek(e.time*1e3)}dispose(){this.edit.events.off("timeline:updated",this.handleTimelineUpdated.bind(this)),this.edit.events.off("clip:updated",this.handleClipUpdated.bind(this)),this.edit.events.off("clip:selected",this.handleClipSelected.bind(this)),this.edit.events.off("selection:cleared",this.handleSelectionCleared.bind(this)),this.edit.events.off("drag:started",this.handleDragStarted.bind(this)),this.edit.events.off("drag:ended",this.handleDragEnded.bind(this)),this.edit.events.off("track:created",this.handleTrackCreated.bind(this))}}class $h{constructor(e,t){this.options=e,this.onUpdate=t}app;trackLayer;overlayLayer;animationFrameId=null;async initializePixiApp(){this.app=new R.Application,await this.app.init({width:this.options.width,height:this.options.height,backgroundColor:this.options.backgroundColor,antialias:this.options.antialias,resolution:this.options.resolution,autoDensity:!0,preference:"webgl"});const e=document.querySelector("[data-shotstack-timeline]");if(!e)throw new Error("Timeline container element [data-shotstack-timeline] not found");e.appendChild(this.app.canvas)}async setupRenderLayers(){this.trackLayer=new R.Container,this.overlayLayer=new R.Container,this.trackLayer.label="track-layer",this.overlayLayer.label="overlay-layer",this.app.stage.addChild(this.trackLayer),this.app.stage.addChild(this.overlayLayer)}startAnimationLoop(){let e=performance.now();const t=i=>{const r=i-e;e=i;const n=r/16.667;this.onUpdate(n,r),this.draw(),this.animationFrameId=requestAnimationFrame(t)};this.animationFrameId=requestAnimationFrame(t)}draw(){this.app.render()}render(){this.app.render()}updateBackgroundColor(e){this.app&&(this.app.renderer.background.color=e)}getApp(){return this.app}getStage(){return this.app.stage}getTrackLayer(){return this.trackLayer}getOverlayLayer(){return this.overlayLayer}dispose(){this.animationFrameId!==null&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=null),this.app&&this.app.destroy(!0)}}const $t={RULER:{DEFAULT_HEIGHT:40,LABEL_FONT_SIZE:10,LABEL_PADDING_X:2},PLAYHEAD:{LINE_WIDTH:2},SCROLL:{HORIZONTAL_SPEED:2,VERTICAL_SPEED:.5}};class An extends Je{events;rulerContainer;rulerBackground;timeMarkers;timeLabels;pixelsPerSecond;timelineDuration;rulerHeight;theme;constructor(e){super(),this.events=new Kt,this.pixelsPerSecond=e.pixelsPerSecond,this.timelineDuration=e.timelineDuration,this.rulerHeight=e.rulerHeight??$t.RULER.DEFAULT_HEIGHT,this.theme=e.theme,this.rulerContainer=new R.Container,this.rulerBackground=new R.Graphics,this.timeMarkers=new R.Graphics,this.timeLabels=new R.Container}async load(){this.setupRuler(),this.draw()}setupRuler(){this.rulerContainer.label="ruler",this.rulerContainer.addChild(this.rulerBackground),this.rulerContainer.addChild(this.timeMarkers),this.rulerContainer.addChild(this.timeLabels),this.rulerContainer.eventMode="static",this.rulerContainer.cursor="pointer",this.rulerContainer.on("pointerdown",this.onRulerPointerDown.bind(this)),this.getContainer().addChild(this.rulerContainer)}drawRulerBackground(){this.rulerBackground.clear();const e=this.calculateRulerWidth(),t=this.theme?.timeline.ruler.background||4210752,i=this.theme?.timeline.tracks.border||6316128;this.rulerBackground.rect(0,0,e,this.rulerHeight),this.rulerBackground.fill(t),this.rulerBackground.rect(0,this.rulerHeight-1,e,1),this.rulerBackground.fill(i)}drawTimeMarkers(){this.timeMarkers.clear();const e=this.getTimeInterval(),t=this.getVisibleDuration(),i=this.theme?.timeline.ruler.markers||6710886,r=this.rulerHeight*.5;let n=4;e===10?n=9:(e===30||e===60)&&(n=5);const o=e/(n+1);for(let a=0;a<=t;a+=e)for(let p=1;p<=n;p+=1){const m=a+p*o;if(m<=t){const d=m*this.pixelsPerSecond;this.timeMarkers.circle(d,r,1.5),this.timeMarkers.fill(i)}}}drawTimeLabels(){this.timeLabels.removeChildren();const e=this.getTimeInterval(),t=this.getVisibleDuration(),i=this.theme?.timeline.ruler.text||16777215,r={fontSize:$t.RULER.LABEL_FONT_SIZE,fill:i,fontFamily:"Arial"};for(let n=0;n<=t;n+=e){const o=new R.Text({text:this.formatTime(n),style:r}),a=n*this.pixelsPerSecond;n===0?(o.anchor.set(0,.5),o.x=a+$t.RULER.LABEL_PADDING_X):(o.anchor.set(.5,.5),o.x=a),o.y=this.rulerHeight*.5,this.timeLabels.addChild(o)}}onRulerPointerDown(e){const t=this.rulerContainer.toLocal(e.global),i=Math.max(0,t.x/this.pixelsPerSecond);this.events.emit("ruler:seeked",{time:i})}updateRuler(e,t){this.pixelsPerSecond=e,this.timelineDuration=t,this.draw()}update(e,t){}draw(){this.drawRulerBackground(),this.drawTimeMarkers(),this.drawTimeLabels()}dispose(){this.timeLabels.removeChildren(),this.rulerContainer.removeChildren(),this.events.clear("*")}getViewportWidth(){return this.getContainer().parent?.width||800}calculateRulerWidth(){const e=this.timelineDuration*this.pixelsPerSecond;return Math.max(e,this.getViewportWidth())}getVisibleDuration(){return Math.max(this.timelineDuration,this.getViewportWidth()/this.pixelsPerSecond)}getTimeInterval(){const e=[1,5,10,30,60,120,300,600],t=80;for(const i of e)if(i*this.pixelsPerSecond>=t)return i;return Math.ceil(this.getVisibleDuration()/10)}formatTime(e){if(e===0)return"0s";const t=Math.floor(e/60),i=e%60;if(e<60)return`${e}s`;if(i===0)return`${t}m`;const r=i.toString().padStart(2,"0");return`${t}:${r}`}}class In extends Je{constructor(e){super(),this.options=e,this.graphics=new R.Graphics}events=new Kt;graphics;currentTime=0;isDragging=!1;async load(){this.setupPlayhead(),this.draw()}setupPlayhead(){this.graphics.label="playhead",this.graphics.eventMode="static",this.graphics.cursor="pointer",this.graphics.on("pointerdown",this.onPointerDown.bind(this)).on("pointermove",this.onPointerMove.bind(this)).on("pointerup",this.onPointerUp.bind(this)).on("pointerupoutside",this.onPointerUp.bind(this)),this.getContainer().addChild(this.graphics)}drawPlayhead(){const e=this.currentTime*this.options.pixelsPerSecond,t=this.options.theme?.timeline.playhead??16729156,i=$t.PLAYHEAD.LINE_WIDTH,r=e+i/2;this.graphics.clear(),this.graphics.fill(t),this.graphics.rect(e,0,i,this.options.timelineHeight);const n=8;this.graphics.moveTo(r,10),this.graphics.lineTo(r-n,0),this.graphics.lineTo(r+n,0),this.graphics.closePath(),this.graphics.fill()}onPointerDown(e){this.isDragging=!0,this.graphics.cursor="grabbing",this.updateTimeFromPointer(e)}onPointerMove(e){this.isDragging&&this.updateTimeFromPointer(e)}onPointerUp(){this.isDragging=!1,this.graphics.cursor="pointer"}updateTimeFromPointer(e){if(!this.graphics.parent)return;const t=this.graphics.parent.toLocal(e.global),i=Math.max(0,t.x/this.options.pixelsPerSecond);this.setTime(i),this.events.emit("playhead:seeked",{time:i})}setTime(e){this.currentTime=e,this.draw(),this.events.emit("playhead:timeChanged",{time:e})}getTime(){return this.currentTime}updatePlayhead(e,t){this.options.pixelsPerSecond=e,this.options.timelineHeight=t,this.draw()}update(){}draw(){this.drawPlayhead()}dispose(){this.graphics.removeAllListeners(),this.events.clear("*")}}class Dh{events;timeline;abortController;scrollX=0;scrollY=0;constructor(e){this.events=new Kt,this.timeline=e.timeline}async initialize(){this.setupEventListeners()}setupEventListeners(){this.abortController=new AbortController;const{canvas:e}=this.timeline.getPixiApp();e.addEventListener("wheel",this.handleWheel.bind(this),{passive:!1,signal:this.abortController.signal})}handleWheel(e){if(e.preventDefault(),e.ctrlKey||e.metaKey){this.handleZoom(e);return}this.handleScroll(e)}handleZoom(e){const t=e.deltaY>0?"out":"in",i=this.timeline.getPlayheadTime(),r=this.timeline.getActualEditDuration();t==="in"?this.timeline.zoomIn():this.timeline.zoomOut();const n=this.timeline.getOptions().pixelsPerSecond||50,o=i*n,a=this.timeline.getOptions().width||800,m=this.timeline.timeRange.endTime*n,d=r*n,l=this.calculateZoomScrollPosition({playheadXAfterZoom:o,viewportWidth:a,contentWidth:m,maxPlayheadX:d,actualEditDuration:r,playheadTime:i});this.scrollX=l,this.timeline.setScroll(this.scrollX,this.scrollY);const c=o-l;this.events.emit("zoom",{pixelsPerSecond:n,focusX:c,focusTime:i})}handleScroll(e){let{deltaX:t}=e,{deltaY:i}=e;e.shiftKey&&(t=i,i=0);const r=$t.SCROLL.HORIZONTAL_SPEED,n=$t.SCROLL.VERTICAL_SPEED;this.scrollX+=t*r,this.scrollY+=i*n,this.scrollX=this.clampScrollX(this.scrollX),this.scrollY=this.clampScrollY(this.scrollY),this.timeline.setScroll(this.scrollX,this.scrollY),this.events.emit("scroll",{x:this.scrollX,y:this.scrollY})}setScroll(e,t){this.scrollX=this.clampScrollX(e),this.scrollY=this.clampScrollY(t),this.timeline.setScroll(this.scrollX,this.scrollY),this.events.emit("scroll",{x:this.scrollX,y:this.scrollY})}clampScrollX(e){const t=this.timeline.getExtendedTimelineWidth(),i=this.timeline.getOptions().width||0,r=Math.max(0,t-i);return Math.max(0,Math.min(e,r))}clampScrollY(e){const t=this.timeline.getLayout(),i=this.timeline.getVisualTracks().length,r=this.timeline.getOptions().height||0,n=Math.max(0,i*t.trackHeight-(r-t.rulerHeight));return Math.max(0,Math.min(e,n))}getScroll(){return{x:this.scrollX,y:this.scrollY}}calculateZoomScrollPosition(e){const{playheadXAfterZoom:t,viewportWidth:i,contentWidth:r,maxPlayheadX:n,actualEditDuration:o,playheadTime:a}=e,p=t-i/2,m=Math.max(0,r-i);let d;const l=p+i,c=Math.max(0,n-i);r<=i||p<0?d=0:l>n&&a<=o?d=Math.min(c,m):p>m?d=m:d=p;const u=t-d;return(u<0||u>i)&&(t>r-i?d=Math.max(0,t-i+50):d=Math.max(0,t-50),d=Math.max(0,Math.min(d,m))),d}dispose(){this.abortController&&(this.abortController.abort(),this.abortController=void 0),this.events.clear("*")}}const ue={BUTTON_SIZE:24,BUTTON_HOVER_PADDING:4,BORDER_RADIUS:4,TEXT_SPACING:16,EDGE_MARGIN:10,FRAME_TIME_MS:16.67,ICON:{PLAY:{LEFT:6,TOP:4,RIGHT:18,MIDDLE:12,BOTTOM:20},PAUSE:{RECT1_X:6,RECT2_X:14,TOP:4,WIDTH:4,HEIGHT:16},FRAME_STEP:{TRIANGLE1:{BACK:{LEFT:11,RIGHT:3,MIDDLE:12},FORWARD:{LEFT:4,RIGHT:12,MIDDLE:12}},TRIANGLE2:{BACK:{LEFT:20,RIGHT:12,MIDDLE:12},FORWARD:{LEFT:13,RIGHT:21,MIDDLE:12}},TOP:4,BOTTOM:20}},CUT_BUTTON:{WIDTH:60,HEIGHT:24,FONT_SIZE:12},TIME_DISPLAY:{FONT_SIZE:14,FONT_FAMILY:"monospace"},HOVER_ANIMATION_ALPHA:1,ACTIVE_ANIMATION_ALPHA:.3,DIVIDER_ALPHA:.5};class Ii{static createIcon(e,t,i){const r=i?i/ue.BUTTON_SIZE:1;switch(e){case"play":return this.createPlayIcon(t,r);case"pause":return this.createPauseIcon(t,r);case"frame-back":return this.createFrameBackIcon(t,r);case"frame-forward":return this.createFrameForwardIcon(t,r);default:throw new Error(`Unknown icon type: ${e}`)}}static createPlayIcon(e,t=1){const i=new R.Graphics,{PLAY:r}=ue.ICON;return i.fill({color:e.timeline.toolbar.icon}),i.moveTo(r.LEFT*t,r.TOP*t),i.lineTo(r.RIGHT*t,r.MIDDLE*t),i.lineTo(r.LEFT*t,r.BOTTOM*t),i.closePath(),i.fill(),i}static createPauseIcon(e,t=1){const i=new R.Graphics,{PAUSE:r}=ue.ICON;return i.fill({color:e.timeline.toolbar.icon}),i.rect(r.RECT1_X*t,r.TOP*t,r.WIDTH*t,r.HEIGHT*t),i.rect(r.RECT2_X*t,r.TOP*t,r.WIDTH*t,r.HEIGHT*t),i.fill(),i}static createFrameBackIcon(e,t=1){const i=new R.Graphics,{FRAME_STEP:r}=ue.ICON;return i.fill({color:e.timeline.toolbar.icon}),i.moveTo(r.TRIANGLE1.BACK.LEFT*t,r.TOP*t),i.lineTo(r.TRIANGLE1.BACK.RIGHT*t,r.TRIANGLE1.BACK.MIDDLE*t),i.lineTo(r.TRIANGLE1.BACK.LEFT*t,r.BOTTOM*t),i.closePath(),i.moveTo(r.TRIANGLE2.BACK.LEFT*t,r.TOP*t),i.lineTo(r.TRIANGLE2.BACK.RIGHT*t,r.TRIANGLE2.BACK.MIDDLE*t),i.lineTo(r.TRIANGLE2.BACK.LEFT*t,r.BOTTOM*t),i.closePath(),i.fill(),i}static createFrameForwardIcon(e,t=1){const i=new R.Graphics,{FRAME_STEP:r}=ue.ICON;return i.fill({color:e.timeline.toolbar.icon}),i.moveTo(r.TRIANGLE1.FORWARD.LEFT*t,r.TOP*t),i.lineTo(r.TRIANGLE1.FORWARD.RIGHT*t,r.TRIANGLE1.FORWARD.MIDDLE*t),i.lineTo(r.TRIANGLE1.FORWARD.LEFT*t,r.BOTTOM*t),i.closePath(),i.moveTo(r.TRIANGLE2.FORWARD.LEFT*t,r.TOP*t),i.lineTo(r.TRIANGLE2.FORWARD.RIGHT*t,r.TRIANGLE2.FORWARD.MIDDLE*t),i.lineTo(r.TRIANGLE2.FORWARD.LEFT*t,r.BOTTOM*t),i.closePath(),i.fill(),i}static updateIconColor(e,t){const i=e.getBounds();e.clear(),e.position.set(i.x,i.y)}}class Pn extends R.Container{background;hoverBackground;icon;alternateIcon;state={isHovering:!1,isPressed:!1,isActive:!1};size;theme;onClick;constructor(e){super(),this.size=e.size||ue.BUTTON_SIZE,this.theme=e.theme,this.onClick=e.onClick,this.eventMode="static",this.cursor="pointer",this.background=new R.Graphics,this.addChild(this.background),this.hoverBackground=new R.Graphics,this.addChild(this.hoverBackground);const i=this.size*.6,r=(this.size-i)/2;e.iconType&&(this.icon=Ii.createIcon(e.iconType,this.theme,i),this.icon.position.set(r,r),this.addChild(this.icon)),e.alternateIconType&&(this.alternateIcon=Ii.createIcon(e.alternateIconType,this.theme,i),this.alternateIcon.position.set(r,r),this.alternateIcon.visible=!1,this.addChild(this.alternateIcon)),this.setupEventListeners(),this.updateVisuals()}setupEventListeners(){this.on("pointerdown",this.handlePointerDown,this),this.on("pointerup",this.handlePointerUp,this),this.on("pointerupoutside",this.handlePointerUp,this),this.on("pointerover",this.handlePointerOver,this),this.on("pointerout",this.handlePointerOut,this)}handlePointerDown(){this.state.isPressed=!0,this.updateVisuals()}handlePointerUp(){this.state.isPressed&&this.onClick(),this.state.isPressed=!1,this.updateVisuals()}handlePointerOver(){this.state.isHovering=!0,this.updateVisuals()}handlePointerOut(){this.state.isHovering=!1,this.state.isPressed=!1,this.updateVisuals()}updateVisuals(){const e=ue.BUTTON_HOVER_PADDING,t=this.size/2;this.background.clear(),this.background.circle(t,t,t),this.background.fill({color:this.theme.timeline.toolbar.surface,alpha:.8}),this.hoverBackground.clear(),this.hoverBackground.circle(t,t,t+e),this.state.isPressed?this.hoverBackground.fill({color:this.theme.timeline.toolbar.active,alpha:ue.ACTIVE_ANIMATION_ALPHA}):this.state.isHovering?this.hoverBackground.fill({color:this.theme.timeline.toolbar.hover,alpha:ue.HOVER_ANIMATION_ALPHA}):this.hoverBackground.fill({color:this.theme.timeline.toolbar.hover,alpha:0})}setActive(e){this.state.isActive=e,this.icon&&this.alternateIcon&&(this.icon.visible=!e,this.alternateIcon.visible=e)}updateTheme(e){this.theme=e;const i=this.size*.6,r=(this.size-i)/2;if(this.icon){const n=this.getIconType(this.icon);n&&(this.removeChild(this.icon),this.icon=Ii.createIcon(n,e,i),this.icon.position.set(r,r),this.addChild(this.icon))}if(this.alternateIcon){const n=this.getIconType(this.alternateIcon);n&&(this.removeChild(this.alternateIcon),this.alternateIcon=Ii.createIcon(n,e,i),this.alternateIcon.position.set(r,r),this.alternateIcon.visible=this.state.isActive,this.addChild(this.alternateIcon))}this.updateVisuals()}getIconType(e){return null}destroy(){this.removeAllListeners(),super.destroy()}}class zh extends R.Container{edit;theme;toolbarHeight;frameBackButton;playPauseButton;frameForwardButton;constructor(e,t,i){super(),this.edit=e,this.theme=t,this.toolbarHeight=i||36,this.createButtons(),this.subscribeToEditEvents(),this.updatePlayPauseState()}createButtons(){const e=this.calculateButtonSizes(),t=(e.playButton-e.regularButton)/2,i=(r,n,o,a)=>new Pn({iconType:r,onClick:n,tooltip:o,theme:this.theme,size:a});this.frameBackButton=i("frame-back",()=>this.handleFrameBack(),"Previous frame",e.regularButton),this.frameBackButton.position.set(0,t),this.playPauseButton=new Pn({iconType:"play",alternateIconType:"pause",onClick:()=>this.handlePlayPause(),tooltip:"Play/Pause",theme:this.theme,size:e.playButton}),this.playPauseButton.position.set(e.regularButton+e.spacing,0),this.frameForwardButton=i("frame-forward",()=>this.handleFrameForward(),"Next frame",e.regularButton),this.frameForwardButton.position.set(e.regularButton+e.spacing+e.playButton+e.spacing,t),this.addChild(this.frameBackButton,this.playPauseButton,this.frameForwardButton)}calculateButtonSizes(){const e=Math.round(this.toolbarHeight*.5);return{regularButton:e,playButton:Math.round(e*1.5),spacing:Math.round(this.toolbarHeight*.15)}}handleFrameBack(){this.edit.seek(this.edit.playbackTime-ue.FRAME_TIME_MS)}handlePlayPause(){this.edit.isPlaying?this.edit.pause():this.edit.play()}handleFrameForward(){this.edit.seek(this.edit.playbackTime+ue.FRAME_TIME_MS)}subscribeToEditEvents(){this.edit.events.on("playback:play",this.updatePlayPauseState),this.edit.events.on("playback:pause",this.updatePlayPauseState)}updatePlayPauseState=()=>{this.playPauseButton.setActive(this.edit.isPlaying)};update(){}resize(e){}updateTheme(e){this.theme=e,this.frameBackButton.updateTheme(e),this.playPauseButton.updateTheme(e),this.frameForwardButton.updateTheme(e)}destroy(){this.edit.events.off("playback:play",this.updatePlayPauseState),this.edit.events.off("playback:pause",this.updatePlayPauseState),this.frameBackButton.destroy(),this.playPauseButton.destroy(),this.frameForwardButton.destroy(),super.destroy()}getWidth(){const e=this.calculateButtonSizes();return e.regularButton*2+e.playButton+e.spacing*2}}class Hh extends R.Container{edit;theme;timeText;formatOptions;constructor(e,t,i={}){super(),this.edit=e,this.theme=t,this.formatOptions={showMilliseconds:!1,showHours:!1,...i},this.createDisplay(),this.subscribeToEditEvents(),this.updateTimeDisplay()}createDisplay(){const e=new R.TextStyle({fontFamily:ue.TIME_DISPLAY.FONT_FAMILY,fontSize:ue.TIME_DISPLAY.FONT_SIZE,fill:this.theme.timeline.toolbar.text});this.timeText=new R.Text("0:00 / 0:00",e),this.timeText.anchor.set(0,.5),this.addChild(this.timeText)}subscribeToEditEvents(){this.edit.events.on("playback:time",this.updateTimeDisplay),this.edit.events.on("duration:changed",this.updateTimeDisplay)}updateTimeDisplay=()=>{const e=this.formatTime(this.edit.playbackTime/1e3),t=this.formatTime(this.edit.getTotalDuration()/1e3);this.timeText.text=`${e} / ${t}`};formatTime(e){const t=Math.floor(e/3600),i=Math.floor(e%3600/60),r=Math.floor(e%60),n=Math.floor(e%1*10);let o="";return this.formatOptions.showHours||t>0?o+=`${t}:${i.toString().padStart(2,"0")}`:o+=`${i}`,o+=`:${r.toString().padStart(2,"0")}`,this.formatOptions.showMilliseconds?o+=`.${n}`:o+=`.${n}`,o}update(){this.updateTimeDisplay()}resize(e){}updateTheme(e){this.theme=e,this.timeText.style.fill=e.timeline.toolbar.text}destroy(){this.edit.events.off("playback:time",this.updateTimeDisplay),this.edit.events.off("duration:changed",this.updateTimeDisplay),super.destroy()}getWidth(){return this.timeText.width}}class Nh extends R.Container{edit;theme;cutButton;cutButtonBackground;cutButtonText;constructor(e,t){super(),this.edit=e,this.theme=t,this.createCutButton()}createCutButton(){this.cutButton=new R.Container,this.cutButton.eventMode="static",this.cutButton.cursor="pointer";const{WIDTH:e,HEIGHT:t,FONT_SIZE:i}=ue.CUT_BUTTON;this.cutButtonBackground=new R.Graphics,this.cutButtonBackground.roundRect(0,0,e,t,ue.BORDER_RADIUS),this.cutButtonBackground.fill({color:this.theme.timeline.toolbar.surface||4473924}),this.cutButtonBackground.stroke({color:this.theme.timeline.tracks.border||6710886,width:1}),this.cutButton.addChild(this.cutButtonBackground);const r=new R.TextStyle({fontFamily:"Arial",fontSize:i,fill:this.theme.timeline.toolbar.text||16777215});this.cutButtonText=new R.Text("SPLIT",r),this.cutButtonText.anchor.set(.5),this.cutButtonText.position.set(e/2,t/2),this.cutButton.addChild(this.cutButtonText),this.cutButton.on("click",this.handleCutClick,this),this.cutButton.on("pointerdown",this.handlePointerDown,this),this.cutButton.on("pointerover",this.handlePointerOver,this),this.cutButton.on("pointerout",this.handlePointerOut,this),this.addChild(this.cutButton)}handleCutClick=e=>{e.stopPropagation(),this.performCutClip()};handlePointerDown=e=>{e.stopPropagation(),this.updateButtonVisual(!0,!1)};handlePointerOver=()=>{this.updateButtonVisual(!1,!0)};handlePointerOut=()=>{this.updateButtonVisual(!1,!1)};updateButtonVisual(e,t){this.cutButtonBackground.clear(),this.cutButtonBackground.roundRect(0,0,ue.CUT_BUTTON.WIDTH,ue.CUT_BUTTON.HEIGHT,ue.BORDER_RADIUS);let i=this.theme.timeline.toolbar.surface||4473924;const r=1;e?i=this.theme.timeline.toolbar.active||3355443:t&&(i=this.theme.timeline.toolbar.hover||5592405),this.cutButtonBackground.fill({color:i,alpha:r}),this.cutButtonBackground.stroke({color:this.theme.timeline.tracks.border||6710886,width:1})}performCutClip(){const e=this.edit.getSelectedClipInfo();if(!e)return;const{trackIndex:t,clipIndex:i}=e,r=this.edit.playbackTime/1e3;this.edit.splitClip(t,i,r)}update(){const e=this.edit.getSelectedClipInfo()!==null;this.cutButton.alpha=e?1:.5,this.cutButton.eventMode=e?"static":"none",this.cutButton.cursor=e?"pointer":"default"}resize(e){}updateTheme(e){this.theme=e,this.updateButtonVisual(!1,!1),this.cutButtonText.style.fill=e.timeline.toolbar.text||16777215}destroy(){this.cutButton.removeAllListeners(),super.destroy()}getWidth(){return ue.CUT_BUTTON.WIDTH}}class Uh{config;constructor(e,t){this.config={width:e,height:t,buttonSize:Math.round(t*.5),buttonSpacing:Math.round(t*.15),edgeMargin:ue.EDGE_MARGIN}}getPlaybackControlsPosition(){const e=this.calculatePlaybackControlsWidth(),t=(this.config.width-e)/2,i=(this.config.height-this.getMaxButtonHeight())/2;return{x:t,y:i}}getMaxButtonHeight(){const e=this.config.buttonSize;return Math.round(e*1.5)}getTimeDisplayPosition(e){const i=(this.config.width-e)/2+e+ue.TEXT_SPACING,r=this.config.height/2;return{x:i,y:r}}getEditControlsPosition(){const e=this.config.width-ue.CUT_BUTTON.WIDTH-this.config.edgeMargin,t=(this.config.height-ue.CUT_BUTTON.HEIGHT)/2;return{x:e,y:t}}calculatePlaybackControlsWidth(){const e=this.config.buttonSize,t=Math.round(e*1.5);return e*2+t+this.config.buttonSpacing*2}updateWidth(e){this.config.width=e}getConfig(){return{...this.config}}}class jh extends R.Container{constructor(e,t,i,r){super(),this.edit=e,this.theme=t,this.layout=i,this.toolbarWidth=r,this.toolbarHeight=i.toolbarHeight,this.position.set(0,i.toolbarY),this.toolbarLayout=new Uh(r,this.toolbarHeight),this.createBackground(),this.createComponents(),this.positionComponents(),this.subscribeToEditEvents()}background;playbackControls;timeDisplay;editControls;toolbarLayout;toolbarWidth;toolbarHeight;get width(){return this.toolbarWidth}get height(){return this.toolbarHeight}createBackground(){this.background=new R.Graphics,this.drawBackground(),this.addChild(this.background)}drawBackground(){this.background.clear(),this.background.rect(0,0,this.toolbarWidth,this.toolbarHeight),this.background.fill({color:this.theme.timeline.toolbar.background}),this.background.setStrokeStyle({width:1,color:this.theme.timeline.toolbar.divider,alpha:ue.DIVIDER_ALPHA}),this.background.moveTo(0,this.toolbarHeight-.5),this.background.lineTo(this.toolbarWidth,this.toolbarHeight-.5),this.background.stroke()}createComponents(){this.playbackControls=new zh(this.edit,this.theme,this.toolbarHeight),this.addChild(this.playbackControls),this.timeDisplay=new Hh(this.edit,this.theme),this.addChild(this.timeDisplay),this.editControls=new Nh(this.edit,this.theme),this.addChild(this.editControls)}positionComponents(){const e=this.toolbarLayout.getPlaybackControlsPosition();this.playbackControls.position.set(e.x,e.y);const t=this.toolbarLayout.getTimeDisplayPosition(this.playbackControls.getWidth());this.timeDisplay.position.set(t.x,t.y);const i=this.toolbarLayout.getEditControlsPosition();this.editControls.position.set(i.x,i.y)}subscribeToEditEvents(){this.edit.events.on("clip:selected",this.updateEditControls),this.edit.events.on("selection:cleared",this.updateEditControls)}updateEditControls=()=>{this.editControls.update()};resize(e){this.toolbarWidth=e,this.toolbarLayout.updateWidth(e),this.drawBackground(),this.positionComponents(),this.playbackControls.resize(e),this.timeDisplay.resize(e),this.editControls.resize(e)}updateTheme(e){this.theme=e,this.drawBackground(),this.playbackControls.updateTheme(e),this.timeDisplay.updateTheme(e),this.editControls.updateTheme(e)}updateTimeDisplay=()=>{this.timeDisplay.update()};destroy(){this.edit.events.off("clip:selected",this.updateEditControls),this.edit.events.off("selection:cleared",this.updateEditControls),this.playbackControls.destroy(),this.timeDisplay.destroy(),this.editControls.destroy(),super.destroy()}}class Vh{constructor(e,t,i,r,n,o){this.edit=e,this.layout=t,this.renderer=i,this.viewportManager=r,this.eventHandler=n,this.getTimelineContext=o}toolbar;ruler;playhead;scroll;async setupTimelineFeatures(e,t,i,r,n){this.toolbar=new jh(this.edit,e,this.layout,i),this.renderer.getStage().addChild(this.toolbar);const o={pixelsPerSecond:t,timelineDuration:n,rulerHeight:this.layout.rulerHeight,theme:e};this.ruler=new An(o),await this.ruler.load(),this.ruler.getContainer().y=this.layout.rulerY,this.viewportManager.getRulerViewport().addChild(this.ruler.getContainer()),this.ruler.events.on("ruler:seeked",this.eventHandler.handleSeek.bind(this.eventHandler));const a={pixelsPerSecond:t,timelineHeight:r,theme:e};this.playhead=new In(a),await this.playhead.load(),this.playhead.getContainer().y=this.layout.rulerY,this.viewportManager.getPlayheadContainer().addChild(this.playhead.getContainer()),this.playhead.events.on("playhead:seeked",this.eventHandler.handleSeek.bind(this.eventHandler));const p={timeline:this.getTimelineContext()};this.scroll=new Dh(p),await this.scroll.initialize(),this.viewportManager.updateViewportTransform()}recreateTimelineFeatures(e,t,i,r){if(this.ruler){this.ruler.dispose();const{rulerHeight:n}=this.layout,o={pixelsPerSecond:t,timelineDuration:r,rulerHeight:n,theme:e};this.ruler=new An(o),this.ruler.load(),this.ruler.getContainer().y=this.layout.rulerY,this.viewportManager.getRulerViewport().addChild(this.ruler.getContainer()),this.ruler.events.on("ruler:seeked",this.eventHandler.handleSeek.bind(this.eventHandler))}if(this.playhead){this.playhead.dispose();const n={pixelsPerSecond:t,timelineHeight:i,theme:e};this.playhead=new In(n),this.playhead.load(),this.playhead.getContainer().y=this.layout.rulerY,this.viewportManager.getPlayheadContainer().addChild(this.playhead.getContainer()),this.playhead.events.on("playhead:seeked",this.eventHandler.handleSeek.bind(this.eventHandler))}}updateRuler(e,t){this.ruler.updateRuler(e,t)}updatePlayhead(e,t){this.playhead&&this.playhead.updatePlayhead(e,t)}getFeatures(){return{toolbar:this.toolbar,ruler:this.ruler,playhead:this.playhead,scroll:this.scroll}}getToolbar(){return this.toolbar}getPlayhead(){return this.playhead}dispose(){this.toolbar&&this.toolbar.destroy(),this.ruler&&this.ruler.dispose(),this.playhead&&this.playhead.dispose(),this.scroll&&this.scroll.dispose()}}class Ye{constructor(e,t){this.options=e,this.theme=t,this.config=this.calculateLayout()}static TOOLBAR_HEIGHT_RATIO=Le.TOOLBAR_HEIGHT_RATIO;static RULER_HEIGHT_RATIO=Le.RULER_HEIGHT_RATIO;static TOOLBAR_HEIGHT_DEFAULT=Le.TOOLBAR_HEIGHT_DEFAULT;static RULER_HEIGHT_DEFAULT=Le.RULER_HEIGHT_DEFAULT;static TRACK_HEIGHT_DEFAULT=Le.TRACK_HEIGHT_DEFAULT;static CLIP_PADDING=Le.CLIP_PADDING;static BORDER_WIDTH=Le.BORDER_WIDTH;static CORNER_RADIUS=Le.CORNER_RADIUS;static LABEL_PADDING=Le.LABEL_PADDING;static TRACK_PADDING=Le.TRACK_PADDING;config;calculateLayout(){const e=this.options.height;let t=this.theme?.timeline.toolbar.height||Math.round(e*Ye.TOOLBAR_HEIGHT_RATIO),i=this.theme?.timeline.ruler.height||Math.round(e*Ye.RULER_HEIGHT_RATIO);t=Math.max(t,Ye.TOOLBAR_HEIGHT_DEFAULT),i=Math.max(i,Ye.RULER_HEIGHT_DEFAULT);const{trackHeight:r}=this.options;return{toolbarHeight:t,rulerHeight:i,trackHeight:r,toolbarY:0,rulerY:t,tracksY:t+i,gridY:t+i,playheadY:t,viewportY:t+i}}get toolbarHeight(){return this.config.toolbarHeight}get toolbarY(){return this.config.toolbarY}get rulerHeight(){return this.config.rulerHeight}get trackHeight(){return this.config.trackHeight}get rulerY(){return this.config.rulerY}get tracksY(){return this.config.tracksY}get gridY(){return this.config.gridY}get playheadY(){return this.config.playheadY}get viewportY(){return this.config.viewportY}positionTrack(e){return e*this.trackHeight}positionClip(e){return e*this.options.pixelsPerSecond}calculateClipWidth(e){return Math.max(Le.MIN_CLIP_WIDTH,e*this.options.pixelsPerSecond)}calculateDropPosition(e,t){const i=t-this.tracksY,r=Math.floor(i/this.trackHeight),n=Math.max(0,e/this.options.pixelsPerSecond);return{track:Math.max(0,r),time:n,x:e,y:i}}getTrackAtY(e){const t=e-this.tracksY;return Math.floor(t/this.trackHeight)}getTimeAtX(e){return e/this.options.pixelsPerSecond}getXAtTime(e){return e*this.options.pixelsPerSecond}getYAtTrack(e){return this.tracksY+e*this.trackHeight}getGridHeight(){return this.options.height-this.toolbarHeight-this.rulerHeight}getRulerWidth(){return this.options.width}getGridWidth(){return this.options.width}calculateViewportPosition(e,t){return{x:-e,y:this.viewportY-t}}updateOptions(e,t){this.options=e,this.theme=t,this.config=this.calculateLayout()}isPointInToolbar(e,t){return t>=this.toolbarY&&t<=this.toolbarY+this.toolbarHeight}isPointInRuler(e,t){return t>=this.rulerY&&t<=this.rulerY+this.rulerHeight}isPointInTracks(e,t){return t>=this.tracksY&&t<=this.options.height}getVisibleTrackRange(e,t){const i=e,r=Math.floor(i/this.trackHeight),n=Math.ceil((i+t)/this.trackHeight);return{start:Math.max(0,r),end:Math.max(0,n)}}}class Ge{constructor(e,t,i,r){this.layout=i,this.onResize=r,this.width=e.width,this.height=e.height,this.pixelsPerSecond=50;const n=t.timeline.tracks.height||Ye.TRACK_HEIGHT_DEFAULT;this.trackHeight=Math.max(40,n),this.backgroundColor=t.timeline.background,this.antialias=!0,this.resolution=window.devicePixelRatio||1}pixelsPerSecond;trackHeight;backgroundColor;antialias;resolution;width;height;static MIN_PIXELS_PER_SECOND=10;static MAX_PIXELS_PER_SECOND=500;static ZOOM_FACTOR=1.1;getOptions(){return{width:this.width,height:this.height,pixelsPerSecond:this.pixelsPerSecond,trackHeight:this.trackHeight,backgroundColor:this.backgroundColor,antialias:this.antialias,resolution:this.resolution}}setOptions(e){e.width!==void 0&&(this.width=e.width,this.onResize&&this.onResize(this.width)),e.height!==void 0&&(this.height=e.height),e.pixelsPerSecond!==void 0&&(this.pixelsPerSecond=e.pixelsPerSecond),e.trackHeight!==void 0&&(this.trackHeight=e.trackHeight),e.backgroundColor!==void 0&&(this.backgroundColor=e.backgroundColor),e.antialias!==void 0&&(this.antialias=e.antialias),e.resolution!==void 0&&(this.resolution=e.resolution),this.layout.updateOptions(this.getOptions())}updateFromTheme(e){this.backgroundColor=e.timeline.background;const t=e.timeline.tracks.height||Ye.TRACK_HEIGHT_DEFAULT;this.trackHeight=Math.max(40,t),this.layout.updateOptions(this.getOptions(),e)}getWidth(){return this.width}getHeight(){return this.height}getPixelsPerSecond(){return this.pixelsPerSecond}getTrackHeight(){return this.trackHeight}getBackgroundColor(){return this.backgroundColor}getAntialias(){return this.antialias}getResolution(){return this.resolution}zoomIn(){const e=Math.min(this.pixelsPerSecond*Ge.ZOOM_FACTOR,Ge.MAX_PIXELS_PER_SECOND);this.setPixelsPerSecond(e)}zoomOut(){const e=Math.max(this.pixelsPerSecond/Ge.ZOOM_FACTOR,Ge.MIN_PIXELS_PER_SECOND);this.setPixelsPerSecond(e)}setPixelsPerSecond(e){this.pixelsPerSecond=Math.max(Ge.MIN_PIXELS_PER_SECOND,Math.min(Ge.MAX_PIXELS_PER_SECOND,e)),this.layout.updateOptions(this.getOptions())}canZoomIn(){return this.pixelsPerSecond<Ge.MAX_PIXELS_PER_SECOND}canZoomOut(){return this.pixelsPerSecond>Ge.MIN_PIXELS_PER_SECOND}}class ks extends Je{constructor(e,t,i){super(),this.edit=e,this.theme=Sn.resolveTheme(i),this.layout=new Ye({width:t.width,height:t.height,pixelsPerSecond:50,trackHeight:Math.max(40,this.theme.timeline.tracks.height||Ye.TRACK_HEIGHT_DEFAULT),backgroundColor:this.theme.timeline.background,antialias:!0,resolution:window.devicePixelRatio||1},this.theme),this.optionsManager=new Ge(t,this.theme,this.layout,r=>this.featureManager?.getToolbar()?.resize(r)),this.initializeManagers(),this.setupInteraction()}currentEditType=null;layout;theme;lastPlaybackTime=0;static TIMELINE_BUFFER_MULTIPLIER=1.5;interaction;dragPreviewManager;viewportManager;visualTrackManager;eventHandler;renderer;featureManager;optionsManager;initializeManagers(){const e=this.optionsManager.getOptions();this.renderer=new $h({width:e.width||800,height:e.height||600,backgroundColor:e.backgroundColor||0,antialias:e.antialias??!0,resolution:e.resolution||window.devicePixelRatio||1},(t,i)=>this.update(t,i)),this.eventHandler=new Bh(this.edit,{onEditChange:this.handleEditChange.bind(this),onSeek:t=>this.edit.seek(t),onClipSelected:(t,i)=>this.visualTrackManager.updateVisualSelection(t,i),onSelectionCleared:()=>this.visualTrackManager.clearVisualSelection(),onDragStarted:(t,i)=>{const r=this.getClipData(t,i);r&&this.dragPreviewManager.showDragPreview(t,i,r)},onDragEnded:()=>this.dragPreviewManager.hideDragPreview()}),this.eventHandler.setupEventListeners()}async load(){await this.renderer.initializePixiApp(),await this.renderer.setupRenderLayers(),await this.setupViewport(),await this.setupTimelineFeatures(),this.interaction.activate();try{const e=this.edit.getEdit();e&&(this.currentEditType=e,await this.rebuildFromEdit(e))}catch{}this.renderer.startAnimationLoop()}async setupViewport(){this.viewportManager=new Ph(this.layout,this.renderer.getTrackLayer(),this.renderer.getOverlayLayer(),this.getContainer(),()=>this.renderer.render()),await this.viewportManager.setupViewport(),this.visualTrackManager=new Lh(this.getContainer(),this.layout,this.theme,()=>this.optionsManager.getPixelsPerSecond(),()=>this.getExtendedTimelineWidth()),this.dragPreviewManager=new Ih(this.getContainer(),this.layout,()=>this.optionsManager.getPixelsPerSecond(),()=>this.optionsManager.getTrackHeight(),()=>this.visualTrackManager.getVisualTracks()),this.featureManager=new Vh(this.edit,this.layout,this.renderer,this.viewportManager,this.eventHandler,()=>this)}async setupTimelineFeatures(){const e=this.getExtendedTimelineDuration();await this.featureManager.setupTimelineFeatures(this.theme,this.optionsManager.getPixelsPerSecond(),this.optionsManager.getWidth(),this.optionsManager.getHeight(),e)}recreateTimelineFeatures(){const e=this.getExtendedTimelineDuration();this.featureManager.recreateTimelineFeatures(this.theme,this.optionsManager.getPixelsPerSecond(),this.optionsManager.getHeight(),e)}setScroll(e,t){this.viewportManager.setScroll(e,t)}setZoom(e){this.viewportManager.setZoom(e)}getViewport(){return this.viewportManager.getViewport()}getPixiApp(){return this.renderer.getApp()}getTrackLayer(){return this.renderer.getTrackLayer()}getOverlayLayer(){return this.renderer.getOverlayLayer()}getClipData(e,t){return this.currentEditType?.timeline?.tracks&&this.currentEditType.timeline.tracks[e]?.clips?.[t]||null}getLayout(){return this.layout}getVisualTracks(){return this.visualTrackManager.getVisualTracks()}getEdit(){return this.edit}getExtendedTimelineWidth(){const e=this.getExtendedTimelineDuration()*this.optionsManager.getPixelsPerSecond(),t=this.optionsManager.getWidth();return Math.max(e,t)}hideDragGhost(){this.dragPreviewManager.hideDragGhost()}showDragGhost(e,t,i){this.dragPreviewManager.showDragGhost(e,t,i)}setPlayheadTime(e){this.featureManager.getPlayhead().setTime(e)}getPlayheadTime(){return this.featureManager.getPlayhead().getTime()}getActualEditDuration(){return this.edit.totalDuration/1e3||60}setupInteraction(){this.interaction=new Ah(this)}async handleEditChange(e){this.dragPreviewManager.hideDragPreview();const t=e||this.edit.getEdit();t&&(this.currentEditType=t,this.updateRulerDuration(),this.clearAllVisualState(),await this.rebuildFromEdit(t))}getExtendedTimelineDuration(){const e=this.edit.totalDuration/1e3||60;return Math.max(60,e*ks.TIMELINE_BUFFER_MULTIPLIER)}updateRulerDuration(){const e=this.getExtendedTimelineDuration(),t=this.getExtendedTimelineWidth();this.featureManager.updateRuler(this.optionsManager.getPixelsPerSecond(),e),this.visualTrackManager.updateTrackWidths(t)}clearAllVisualState(){this.dragPreviewManager.hideDragPreview(),this.visualTrackManager.clearAllVisualState()}async rebuildFromEdit(e){await this.visualTrackManager.rebuildFromEdit(e,this.optionsManager.getPixelsPerSecond()),this.renderer.render()}findClipAtPosition(e,t){return this.currentEditType?this.visualTrackManager.findClipAtPosition(e,t):null}setTheme(e){this.theme=Sn.resolveTheme(e),this.optionsManager.updateFromTheme(this.theme),this.featureManager.getToolbar()&&this.featureManager.getToolbar().updateTheme(this.theme),this.recreateTimelineFeatures(),this.currentEditType&&(this.clearAllVisualState(),this.rebuildFromEdit(this.currentEditType)),this.renderer.updateBackgroundColor(this.optionsManager.getBackgroundColor()),this.renderer.render()}getTheme(){return this.theme}getCurrentEditType(){return this.currentEditType}getOptions(){return this.optionsManager.getOptions()}setOptions(e){this.optionsManager.setOptions(e)}update(e,t){(this.edit.isPlaying||this.lastPlaybackTime!==this.edit.playbackTime)&&(this.featureManager.getPlayhead().setTime(this.edit.playbackTime/1e3),this.lastPlaybackTime=this.edit.playbackTime,this.featureManager.getToolbar()&&this.featureManager.getToolbar().updateTimeDisplay())}draw(){this.renderer.draw()}getTimeDisplay(){return this.featureManager.getToolbar()}updateTime(e,t){this.setPlayheadTime(e),t&&this.edit.seek(e*1e3)}get timeRange(){return{startTime:0,endTime:this.getExtendedTimelineDuration()}}get viewportHeight(){return this.optionsManager.getHeight()}get zoomLevelIndex(){const e=this.viewportManager.getViewport();return Math.round(Math.log2(e.zoom)+5)}zoomIn(){this.optionsManager.zoomIn(),this.onZoomChanged()}zoomOut(){this.optionsManager.zoomOut(),this.onZoomChanged()}onZoomChanged(){const e=this.optionsManager.getPixelsPerSecond();this.visualTrackManager.updatePixelsPerSecond(e);const t=this.getExtendedTimelineWidth();this.visualTrackManager.updateTrackWidths(t),this.featureManager.updateRuler(e,this.getExtendedTimelineDuration()),this.featureManager.updatePlayhead(e,this.optionsManager.getHeight()),this.renderer.render()}dispose(){this.dragPreviewManager.dispose(),this.visualTrackManager.dispose(),this.eventHandler.dispose(),this.featureManager.dispose(),this.interaction&&this.interaction.dispose(),this.renderer.dispose()}}var Rn={exports:{}};function Wh(s){var e=s.wasmExports,t=new TextDecoder("utf8");let i=s.addFunction,r=s.removeFunction;var n=i(function(I){e.free(I)},"vi"),o=2,a=-1,p=2,m=0,d=1,l=2;function c(I){return(I.charCodeAt(0)&255)<<24|(I.charCodeAt(1)&255)<<16|(I.charCodeAt(2)&255)<<8|(I.charCodeAt(3)&255)<<0}var u=c("JSON"),h=4;function f(I){return[String.fromCharCode(I>>24&255),String.fromCharCode(I>>16&255),String.fromCharCode(I>>8&255),String.fromCharCode(I>>0&255)].join("")}function b(I){return I=="BOT"?1:I=="EOT"?2:I=="PRESERVE_DEFAULT_IGNORABLES"?4:I=="REMOVE_DEFAULT_IGNORABLES"?8:I=="DO_NOT_INSERT_DOTTED_CIRCLE"?16:I=="PRODUCE_UNSAFE_TO_CONCAT"?64:0}function g(I){var L=e.malloc(I.byteLength);s.HEAPU8.set(new Uint8Array(I),L);var F=e.hb_blob_create(L,I.byteLength,o,L,n);return{ptr:F,destroy:function(){e.hb_blob_destroy(F)}}}function y(I){const L=e.hb_set_get_population(I),F=e.malloc(L<<2),Z=F>>2,Q=s.HEAPU32.subarray(Z,Z+L);return s.HEAPU32.set(Q,Z),e.hb_set_next_many(I,a,F,L),Q}function v(I,L){var F=e.hb_face_create(I.ptr,L);const Z=e.hb_face_get_upem(F);return{ptr:F,upem:Z,reference_table:function(Q){var X=e.hb_face_reference_table(F,c(Q)),Y=e.hb_blob_get_length(X);if(Y){var se=e.hb_blob_get_data(X,null),re=s.HEAPU8.subarray(se,se+Y);return re}},getAxisInfos:function(){var Q=e.malloc(2048),X=e.malloc(4);s.HEAPU32[X/4]=64,e.hb_ot_var_get_axis_infos(F,0,X,Q);var Y={};return Array.from({length:s.HEAPU32[X/4]}).forEach(function(se,re){Y[f(s.HEAPU32[Q/4+re*8+1])]={min:s.HEAPF32[Q/4+re*8+4],default:s.HEAPF32[Q/4+re*8+5],max:s.HEAPF32[Q/4+re*8+6]}}),e.free(X),e.free(Q),Y},collectUnicodes:function(){var Q=e.hb_set_create();e.hb_face_collect_unicodes(F,Q);var X=y(Q);return e.hb_set_destroy(Q),X},destroy:function(){e.hb_face_destroy(F)}}}var _="",C=256,S=e.malloc(C);function T(I){var L=e.hb_font_create(I.ptr),F=null,Z=null,Q=null,X=null,Y=null,se=null;function re(ve){if(!F){var ge=function(Fe,Dt,dt,Ze,Ke,xt){_+=`M${Ze},${Ke}`},de=function(Fe,Dt,dt,Ze,Ke,xt){_+=`L${Ze},${Ke}`},Oe=function(Fe,Dt,dt,Ze,Ke,xt,Qe,ni,Ri,Ts){_+=`C${Ze},${Ke} ${xt},${Qe} ${ni},${Ri}`},Ee=function(Fe,Dt,dt,Ze,Ke,xt,Qe,ni){_+=`Q${Ze},${Ke} ${xt},${Qe}`},Pi=function(Fe,Dt,dt,Ze){_+="Z"};Z=i(ge,"viiiffi"),Q=i(de,"viiiffi"),X=i(Oe,"viiiffffffi"),Y=i(Ee,"viiiffffi"),se=i(Pi,"viiii"),F=e.hb_draw_funcs_create(),e.hb_draw_funcs_set_move_to_func(F,Z,0,0),e.hb_draw_funcs_set_line_to_func(F,Q,0,0),e.hb_draw_funcs_set_cubic_to_func(F,X,0,0),e.hb_draw_funcs_set_quadratic_to_func(F,Y,0,0),e.hb_draw_funcs_set_close_path_func(F,se,0,0)}return _="",e.hb_font_draw_glyph(L,ve,F,0),_}function Ce(ve){e.hb_font_glyph_to_string(L,ve,S,C);var ge=s.HEAPU8.subarray(S,S+C);return t.decode(ge.slice(0,ge.indexOf(0)))}return{ptr:L,glyphName:Ce,glyphToPath:re,glyphToJson:function(ve){var ge=re(ve);return ge.replace(/([MLQCZ])/g,"|$1 ").split("|").filter(function(de){return de.length}).map(function(de){var Oe=de.split(/[ ,]/g);return{type:Oe[0],values:Oe.slice(1).filter(function(Ee){return Ee.length}).map(function(Ee){return+Ee})}})},setScale:function(ve,ge){e.hb_font_set_scale(L,ve,ge)},setVariations:function(ve){var ge=Object.entries(ve),de=e.malloc(8*ge.length);ge.forEach(function(Oe,Ee){s.HEAPU32[de/4+Ee*2+0]=c(Oe[0]),s.HEAPF32[de/4+Ee*2+1]=Oe[1]}),e.hb_font_set_variations(L,de,ge.length),e.free(de)},destroy:function(){e.hb_font_destroy(L),F&&(e.hb_draw_funcs_destroy(F),F=null,r(Z),r(Q),r(X),r(Y),r(se))}}}function w(I){var L=e.malloc(I.length+1);for(let F=0;F<I.length;++F){const Z=I.charCodeAt(F);if(Z>127)throw new Error("Expected ASCII text");s.HEAPU8[L+F]=Z}return s.HEAPU8[L+I.length]=0,{ptr:L,length:I.length,free:function(){e.free(L)}}}function x(I){const L=e.malloc(I.length*2),F=new Uint16Array(s.wasmMemory.buffer,L,I.length);for(let Z=0;Z<F.length;++Z)F[Z]=I.charCodeAt(Z);return{ptr:L,length:F.length,free:function(){e.free(L)}}}function k(){var I=e.hb_buffer_create();return{ptr:I,addText:function(L){const F=x(L);e.hb_buffer_add_utf16(I,F.ptr,F.length,0,F.length),F.free()},guessSegmentProperties:function(){return e.hb_buffer_guess_segment_properties(I)},setDirection:function(L){e.hb_buffer_set_direction(I,{ltr:4,rtl:5,ttb:6,btt:7}[L]||0)},setFlags:function(L){var F=0;L.forEach(function(Z){F|=b(Z)}),e.hb_buffer_set_flags(I,F)},setLanguage:function(L){var F=w(L);e.hb_buffer_set_language(I,e.hb_language_from_string(F.ptr,-1)),F.free()},setScript:function(L){var F=w(L);e.hb_buffer_set_script(I,e.hb_script_from_string(F.ptr,-1)),F.free()},setClusterLevel:function(L){e.hb_buffer_set_cluster_level(I,L)},json:function(){for(var L=e.hb_buffer_get_length(I),F=[],Z=e.hb_buffer_get_glyph_infos(I,0),Q=Z/4,X=e.hb_buffer_get_glyph_positions(I,0)/4,Y=s.HEAPU32.subarray(Q,Q+5*L),se=s.HEAP32.subarray(X,X+5*L),re=0;re<L;++re)F.push({g:Y[re*5+0],cl:Y[re*5+2],ax:se[re*5+0],ay:se[re*5+1],dx:se[re*5+2],dy:se[re*5+3],flags:e.hb_glyph_info_get_glyph_flags(Z+re*20)});return F},destroy:function(){e.hb_buffer_destroy(I)}}}function E(I,L,F){var Z=0,Q=0;F&&(F=F.split(","),Z=e.malloc(16*F.length),F.forEach(function(X,Y){var se=w(X);e.hb_feature_from_string(se.ptr,-1,Z+Q*16)&&Q++,se.free()})),e.hb_shape(I.ptr,L.ptr,Z,Q),Z&&e.free(Z)}function P(I,L,F,Z,Q){var X=[],Y=m,se=!1,re=1024*1024,Ce=e.malloc(re),ve=function(de,Oe,Ee,Pi){var Fe=t.decode(s.HEAPU8.subarray(Ee,s.HEAPU8.indexOf(0,Ee)));return Fe.startsWith("start table GSUB")?Y=d:Fe.startsWith("start table GPOS")&&(Y=l),Y!=Q&&(se=!1),Q!=m&&Y==Q&&Fe.startsWith("end lookup "+Z)&&(se=!0),se?0:(e.hb_buffer_serialize_glyphs(de,0,e.hb_buffer_get_length(de),Ce,re,0,Oe,u,h),X.push({m:Fe,t:JSON.parse(t.decode(s.HEAPU8.subarray(Ce,s.HEAPU8.indexOf(0,Ce)))),glyphs:e.hb_buffer_get_content_type(de)==p}),1)},ge=i(ve,"iiiii");return e.hb_buffer_set_message_func(L.ptr,ge,0,0),E(I,L,F),e.free(Ce),r(ge),X}function O(){var I=e.malloc(12);e.hb_version(I,I+4,I+8);var L={major:s.HEAPU32[I/4],minor:s.HEAPU32[(I+4)/4],micro:s.HEAPU32[(I+8)/4]};return e.free(I),L}function z(){var I=e.hb_version_string(),L=t.decode(s.HEAPU8.subarray(I,s.HEAPU8.indexOf(0,I)));return L}return{createBlob:g,createFace:v,createFont:T,createBuffer:k,shape:E,shapeWithTrace:P,version:O,version_string:z}}try{Rn.exports=Wh}catch{}var Gh=Rn.exports,On={exports:{}};const Zh=za(Gl);(function(s,e){var t=(()=>{var i=typeof document<"u"?document.currentScript?.src:void 0;return async function(r={}){var n,o=r,a=typeof window=="object",p=typeof WorkerGlobalScope<"u",m=typeof process=="object"&&process.versions?.node&&process.type!="renderer",d=(A,U)=>{throw U};typeof __filename<"u"?i=__filename:p&&(i=self.location.href);var l="";function c(A){return o.locateFile?o.locateFile(A,l):l+A}var u,h;if(m){var f=Zh;l=__dirname+"/",h=A=>{A=_(A)?new URL(A):A;var U=f.readFileSync(A);return U},u=async(A,U=!0)=>{A=_(A)?new URL(A):A;var ce=f.readFileSync(A,U?void 0:"utf8");return ce},process.argv.length>1&&process.argv[1].replace(/\\/g,"/"),process.argv.slice(2),d=(A,U)=>{throw process.exitCode=A,U}}else if(a||p){try{l=new URL(".",i).href}catch{}p&&(h=A=>{var U=new XMLHttpRequest;return U.open("GET",A,!1),U.responseType="arraybuffer",U.send(null),new Uint8Array(U.response)}),u=async A=>{if(_(A))return new Promise((ce,fe)=>{var he=new XMLHttpRequest;he.open("GET",A,!0),he.responseType="arraybuffer",he.onload=()=>{if(he.status==200||he.status==0&&he.response){ce(he.response);return}fe(he.status)},he.onerror=fe,he.send(null)});var U=await fetch(A,{credentials:"same-origin"});if(U.ok)return U.arrayBuffer();throw new Error(U.status+" : "+U.url)}}console.log.bind(console);var b=console.error.bind(console),g,y=!1,v,_=A=>A.startsWith("file://"),C,S,T,w,x=!1;function k(){var A=T.buffer;o.HEAP8=new Int8Array(A),o.HEAPU8=w=new Uint8Array(A),o.HEAP32=new Int32Array(A),o.HEAPU32=new Uint32Array(A),o.HEAPF32=new Float32Array(A),new BigInt64Array(A),new BigUint64Array(A)}function E(){if(o.preRun)for(typeof o.preRun=="function"&&(o.preRun=[o.preRun]);o.preRun.length;)Dt(o.preRun.shift());Oe(Fe)}function P(){x=!0,ft.__wasm_call_ctors()}function O(){if(o.postRun)for(typeof o.postRun=="function"&&(o.postRun=[o.postRun]);o.postRun.length;)Pi(o.postRun.shift());Oe(Ee)}var z=0,I=null;function L(A){z++,o.monitorRunDependencies?.(z)}function F(A){if(z--,o.monitorRunDependencies?.(z),z==0&&I){var U=I;I=null,U()}}function Z(A){o.onAbort?.(A),A="Aborted("+A+")",b(A),y=!0,A+=". Build with -sASSERTIONS for more info.";var U=new WebAssembly.RuntimeError(A);throw S?.(U),U}var Q;function X(){return c("hb.wasm")}function Y(A){if(A==Q&&g)return new Uint8Array(g);if(h)return h(A);throw"both async and sync fetching of the wasm failed"}async function se(A){if(!g)try{var U=await u(A);return new Uint8Array(U)}catch{}return Y(A)}async function re(A,U){try{var ce=await se(A),fe=await WebAssembly.instantiate(ce,U);return fe}catch(he){b(`failed to asynchronously prepare wasm: ${he}`),Z(he)}}async function Ce(A,U,ce){if(!A&&!_(U)&&!m)try{var fe=fetch(U,{credentials:"same-origin"}),he=await WebAssembly.instantiateStreaming(fe,ce);return he}catch(Ae){b(`wasm streaming compile failed: ${Ae}`),b("falling back to ArrayBuffer instantiation")}return re(U,ce)}function ve(){return{env:Dn,wasi_snapshot_preview1:Dn}}async function ge(){function A(Ae,Is){return ft=Ae.exports,o.wasmExports=ft,T=ft.memory,o.wasmMemory=T,k(),ai=ft.__indirect_function_table,mu(ft),F(),ft}L();function U(Ae){return A(Ae.instance)}var ce=ve();if(o.instantiateWasm)return new Promise((Ae,Is)=>{o.instantiateWasm(ce,(yu,ku)=>{Ae(A(yu))})});Q??=X();var fe=await Ce(g,Q,ce),he=U(fe);return he}class de{name="ExitStatus";constructor(U){this.message=`Program terminated with exit(${U})`,this.status=U}}var Oe=A=>{for(;A.length>0;)A.shift()(o)},Ee=[],Pi=A=>Ee.push(A),Fe=[],Dt=A=>Fe.push(A),dt=!0,Ze=()=>Z(""),Ke=0,xt=()=>{dt=!1,Ke=0},Qe={},ni=A=>{if(A instanceof de||A=="unwind")return v;d(1,A)},Ri=()=>dt||Ke>0,Ts=A=>{v=A,Ri()||(o.onExit?.(A),y=!0),d(A,new de(A))},Qh=(A,U)=>{v=A,Ts(A)},Jh=Qh,eu=()=>{if(!Ri())try{Jh(v)}catch(A){ni(A)}},tu=A=>{if(!y)try{A(),eu()}catch(U){ni(U)}},iu=()=>performance.now(),su=(A,U)=>{if(Qe[A]&&(clearTimeout(Qe[A].id),delete Qe[A]),!U)return 0;var ce=setTimeout(()=>{delete Qe[A],tu(()=>$n(A,iu()))},U);return Qe[A]={id:ce,timeout_ms:U},0},ru=()=>2147483648,nu=(A,U)=>Math.ceil(A/U)*U,au=A=>{var U=T.buffer.byteLength,ce=(A-U+65535)/65536|0;try{return T.grow(ce),k(),1}catch{}},ou=A=>{var U=w.length;A>>>=0;var ce=ru();if(A>ce)return!1;for(var fe=1;fe<=4;fe*=2){var he=U*(1+.2/fe);he=Math.min(he,A+100663296);var Ae=Math.min(ce,nu(Math.max(A,he),65536)),Is=au(Ae);if(Is)return!0}return!1},Mn=A=>{const U=A.length;return[U%128|128,U>>7,...A]},lu={i:127,p:127,j:126,f:125,d:124,e:111},Ln=A=>Mn(Array.from(A,U=>{var ce=lu[U];return ce})),cu=(A,U)=>{var ce=Uint8Array.of(0,97,115,109,1,0,0,0,1,...Mn([1,96,...Ln(U.slice(1)),...Ln(U[0]==="v"?"":U[0])]),2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0),fe=new WebAssembly.Module(ce),he=new WebAssembly.Instance(fe,{e:{f:A}}),Ae=he.exports.f;return Ae},ai,Bn=A=>ai.get(A),hu=(A,U)=>{if(Ct)for(var ce=A;ce<A+U;ce++){var fe=Bn(ce);fe&&Ct.set(fe,ce)}},Ct,uu=A=>(Ct||(Ct=new WeakMap,hu(0,ai.length)),Ct.get(A)||0),Ss=[],du=()=>Ss.length?Ss.pop():ai.grow(1),Es=(A,U)=>ai.set(A,U),fu=(A,U)=>{var ce=uu(A);if(ce)return ce;var fe=du();try{Es(fe,A)}catch(Ae){if(!(Ae instanceof TypeError))throw Ae;var he=cu(A,U);Es(fe,he)}return Ct.set(A,fe),fe},pu=A=>{Ct.delete(Bn(A)),Es(A,null),Ss.push(A)};o.noExitRuntime&&(dt=o.noExitRuntime),o.print&&o.print,o.printErr&&(b=o.printErr),o.wasmBinary&&(g=o.wasmBinary),o.arguments&&o.arguments,o.thisProgram&&o.thisProgram,o.wasmMemory=T,o.wasmExports=ft,o.addFunction=fu,o.removeFunction=pu;var $n;function mu(A){o._hb_blob_create=A.hb_blob_create,o._hb_blob_destroy=A.hb_blob_destroy,o._hb_blob_get_length=A.hb_blob_get_length,o._hb_blob_get_data=A.hb_blob_get_data,o._hb_buffer_serialize_glyphs=A.hb_buffer_serialize_glyphs,o._hb_buffer_create=A.hb_buffer_create,o._hb_buffer_destroy=A.hb_buffer_destroy,o._hb_buffer_get_content_type=A.hb_buffer_get_content_type,o._hb_buffer_set_direction=A.hb_buffer_set_direction,o._hb_buffer_set_script=A.hb_buffer_set_script,o._hb_buffer_set_language=A.hb_buffer_set_language,o._hb_buffer_set_flags=A.hb_buffer_set_flags,o._hb_buffer_set_cluster_level=A.hb_buffer_set_cluster_level,o._hb_buffer_get_length=A.hb_buffer_get_length,o._hb_buffer_get_glyph_infos=A.hb_buffer_get_glyph_infos,o._hb_buffer_get_glyph_positions=A.hb_buffer_get_glyph_positions,o._hb_glyph_info_get_glyph_flags=A.hb_glyph_info_get_glyph_flags,o._hb_buffer_guess_segment_properties=A.hb_buffer_guess_segment_properties,o._hb_buffer_add_utf8=A.hb_buffer_add_utf8,o._hb_buffer_add_utf16=A.hb_buffer_add_utf16,o._hb_buffer_set_message_func=A.hb_buffer_set_message_func,o._hb_language_from_string=A.hb_language_from_string,o._hb_script_from_string=A.hb_script_from_string,o._hb_version=A.hb_version,o._hb_version_string=A.hb_version_string,o._hb_feature_from_string=A.hb_feature_from_string,o._malloc=A.malloc,o._free=A.free,o._hb_draw_funcs_set_move_to_func=A.hb_draw_funcs_set_move_to_func,o._hb_draw_funcs_set_line_to_func=A.hb_draw_funcs_set_line_to_func,o._hb_draw_funcs_set_quadratic_to_func=A.hb_draw_funcs_set_quadratic_to_func,o._hb_draw_funcs_set_cubic_to_func=A.hb_draw_funcs_set_cubic_to_func,o._hb_draw_funcs_set_close_path_func=A.hb_draw_funcs_set_close_path_func,o._hb_draw_funcs_create=A.hb_draw_funcs_create,o._hb_draw_funcs_destroy=A.hb_draw_funcs_destroy,o._hb_face_create=A.hb_face_create,o._hb_face_destroy=A.hb_face_destroy,o._hb_face_reference_table=A.hb_face_reference_table,o._hb_face_get_upem=A.hb_face_get_upem,o._hb_face_collect_unicodes=A.hb_face_collect_unicodes,o._hb_font_draw_glyph=A.hb_font_draw_glyph,o._hb_font_glyph_to_string=A.hb_font_glyph_to_string,o._hb_font_create=A.hb_font_create,o._hb_font_set_variations=A.hb_font_set_variations,o._hb_font_destroy=A.hb_font_destroy,o._hb_font_set_scale=A.hb_font_set_scale,o._hb_set_create=A.hb_set_create,o._hb_set_destroy=A.hb_set_destroy,o._hb_ot_var_get_axis_infos=A.hb_ot_var_get_axis_infos,o._hb_set_get_population=A.hb_set_get_population,o._hb_set_next_many=A.hb_set_next_many,o._hb_shape=A.hb_shape,$n=A._emscripten_timeout}var Dn={_abort_js:Ze,_emscripten_runtime_keepalive_clear:xt,_setitimer_js:su,emscripten_resize_heap:ou,proc_exit:Ts},ft=await ge();function As(){if(z>0){I=As;return}if(E(),z>0){I=As;return}function A(){o.calledRun=!0,!y&&(P(),C?.(o),o.onRuntimeInitialized?.(),O())}o.setStatus?(o.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>o.setStatus(""),1),A()},1)):A()}function gu(){if(o.preInit)for(typeof o.preInit=="function"&&(o.preInit=[o.preInit]);o.preInit.length>0;)o.preInit.shift()()}return gu(),As(),x?n=o:n=new Promise((A,U)=>{C=A,S=U}),n}})();s.exports=t,s.exports.default=t})(On);var Kh=On.exports,qh=Gh,Xh=Kh,Fn=new Promise(function(s,e){Xh().then(t=>{s(qh(t))},e)});const Yh=Nn({__proto__:null,default:Qs(Fn)},[Fn]);q.AssetSchema=kr,q.AudioAssetSchema=Zi,q.AudioAssetUrlSchema=hr,q.AudioAssetVolumeSchema=ur,q.Canvas=yt,q.ClipSchema=rs,q.Controls=Qo,q.Edit=Ot,q.EditSchema=Or,q.FontSourceSchema=Ir,q.FontSourceUrlSchema=Ar,q.HtmlAssetSchema=Ki,q.ImageAssetCropSchema=fr,q.ImageAssetSchema=qi,q.ImageAssetUrlSchema=dr,q.KeyframeEasingSchema=cr,q.KeyframeInterpolationSchema=lr,q.KeyframeSchema=at,q.LumaAssetSchema=Xi,q.LumaAssetUrlSchema=pr,q.OutputSchema=Rr,q.RichTextAssetSchema=fi,q.ShapeAssetCircleSchema=Ji,q.ShapeAssetColorSchema=Yi,q.ShapeAssetFillSchema=mr,q.ShapeAssetLineSchema=es,q.ShapeAssetRectangleSchema=Qi,q.ShapeAssetSchema=ts,q.ShapeAssetStrokeSchema=gr,q.TextAssetAlignmentSchema=br,q.TextAssetBackgroundSchema=vr,q.TextAssetColorSchema=yi,q.TextAssetFontSchema=yr,q.TextAssetSchema=is,q.TextAssetStrokeSchema=wr,q.Timeline=ks,q.TimelineSchema=Pr,q.TrackSchema=Er,q.VideoAssetCropSchema=xr,q.VideoAssetSchema=ss,q.VideoAssetUrlSchema=_r,q.VideoAssetVolumeSchema=Cr,q.VideoExporter=vh,Object.defineProperty(q,Symbol.toStringTag,{value:"Module"})});