@shotstack/shotstack-studio 1.6.0 → 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(ee,re){typeof exports=="object"&&typeof module<"u"?re(exports,require("pixi.js"),require("howler"),require("opentype.js")):typeof define=="function"&&define.amd?define(["exports","pixi.js","howler","opentype.js"],re):(ee=typeof globalThis<"u"?globalThis:ee||self,re(ee.ShotstackStudio={},ee.PIXI,ee.Howler,ee.opentype))})(this,function(ee,re,Xs,Ys){"use strict";function Qt(s){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(s){for(const t in s)if(t!=="default"){const i=Object.getOwnPropertyDescriptor(s,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:()=>s[t]})}}return e.default=s,Object.freeze(e)}const f=Qt(re),qs=Qt(Xs),Pi=Qt(Ys);class Qs{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,n){const r=this.curves[n??""]??this.curves.ease,[[a,o],[l,c]]=r,h=i+(3*a-3*l+1)*i*(1-i),d=e,u=e+(t-e)*o,p=e+(t-e)*c,g=t,b=h,_=1-b;return _**3*d+3*_**2*b*u+3*_*b**2*p+b**3*g}}class K{property;length;cubicBuilder;constructor(e,t,i=0){this.property=this.createKeyframes(e,t,i),this.length=t,this.cubicBuilder=new Qs}getValue(e){const t=this.property.find(n=>e>=n.start&&e<n.start+n.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 n=this.createNormalizedKeyframes(e);try{this.validateKeyframes(n)}catch(r){console.warn("Keyframe configuration issues detected:",r)}return this.insertFillerKeyframes(n,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],n=e[t+1];if(!n){if(i.start+i.length>this.length)throw new Error("Last keyframe exceeds the maximum duration.");break}if(i.start+i.length>n.start)throw new Error("Overlapping keyframes detected.")}}insertFillerKeyframes(e,t,i=0){const n=[];for(let r=0;r<e.length;r+=1){const a=e[r],o=e[r+1];if(r===0&&a.start!==0){const h={start:0,length:a.start,from:i,to:a.from};n.push(h)}if(n.push(a),!o){if(a.start+a.length<t){const d=a.start+a.length,u={start:d,length:t-d,from:a.to,to:a.to};n.push(u)}break}if(a.start+a.length!==o.start){const h={start:a.start+a.length,length:o.start,from:a.to,to:o.from};n.push(h)}}return n}}class Tt{static Name="AudioLoadParser";name;extension;validAudioExtensions;constructor(){this.name=Tt.Name,this.extension={type:[f.ExtensionType.LoadParser],priority:f.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(n=>{const r={src:e},a=new Howl(r);a.on("load",()=>n(a)),a.on("loaderror",()=>n(null))})}unload(e){e?.unload()}}class Js{clipConfiguration;constructor(e){this.clipConfiguration=e}build(e,t){const i=[],n=[],r=[],a=[],o=[],{effect:l,length:c}=this.clipConfiguration;if(!l)return{offsetXKeyframes:i,offsetYKeyframes:n,opacityKeyframes:r,scaleKeyframes:a,rotationKeyframes:o};const h=0;switch(this.getPresetName()){case"zoomIn":{const u=this.getZoomSpeed(),p=1*this.clipConfiguration.scale,g=u*this.clipConfiguration.scale;a.push({from:p,to:g,start:h,length:c,interpolation:"linear"});break}case"zoomOut":{const p=this.getZoomSpeed()*this.clipConfiguration.scale,g=1*this.clipConfiguration.scale;a.push({from:p,to:g,start:h,length:c,interpolation:"linear"});break}case"slideLeft":{let u=this.getSlideStart();const p=e.width+e.width*u*2,g=t.height/t.width*e.height;if(g<p){const b=Math.abs(p/e.width);a.push({from:b,to:b,start:h,length:c,interpolation:"linear"})}else u=(g-e.width)/2/e.width;i.push({from:u,to:-u,start:h,length:c});break}case"slideRight":{let u=this.getSlideStart();const p=e.width+e.width*u*2,g=t.height/t.width*e.height;if(g<p){const b=Math.abs(p/e.width);a.push({from:b,to:b,start:h,length:c,interpolation:"linear"})}else u=(g-e.width)/2/e.width;i.push({from:-u,to:u,start:h,length:c});break}case"slideUp":{let u=this.getSlideStart();const p=e.height+e.height*u*2,g=t.height/t.width*e.width;if(g<p){const b=Math.abs(p/e.height);a.push({from:b,to:b,start:h,length:c,interpolation:"linear"})}else u=(g-e.height)/2/e.height;n.push({from:u,to:-u,start:h,length:c});break}case"slideDown":{let u=this.getSlideStart();const p=e.height+e.height*u*2,g=t.height/t.width*e.width;if(g<p){const b=Math.abs(p/e.height);a.push({from:b,to:b,start:h,length:c,interpolation:"linear"})}else u=(g-e.height)/2/e.height;n.push({from:-u,to:u,start:h,length:c});break}}return{offsetXKeyframes:i,offsetYKeyframes:n,opacityKeyframes:r,scaleKeyframes:a,rotationKeyframes:o}}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 en{clipConfiguration;constructor(e){this.clipConfiguration=e}build(){const e=[],t=[],i=[],n=[],r=[],a=this.buildInPreset();e.push(...a.offsetXKeyframes),t.push(...a.offsetYKeyframes),i.push(...a.opacityKeyframes),n.push(...a.scaleKeyframes),r.push(...a.rotationKeyframes);const o=this.buildOutPreset();return e.push(...o.offsetXKeyframes),t.push(...o.offsetYKeyframes),i.push(...o.opacityKeyframes),n.push(...o.scaleKeyframes),r.push(...o.rotationKeyframes),{offsetXKeyframes:e,offsetYKeyframes:t,opacityKeyframes:i,scaleKeyframes:n,rotationKeyframes:r}}buildInPreset(){const e=[],t=[],i=[],n=[],r=[];if(!this.clipConfiguration.transition?.in)return{offsetXKeyframes:e,offsetYKeyframes:t,opacityKeyframes:i,scaleKeyframes:n,rotationKeyframes:r};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,d=this.clipConfiguration.scale;n.push({from:h,to:d,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;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"slideRight":{const c=this.clipConfiguration.offset?.x-.025,h=this.clipConfiguration.offset?.x;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"slideUp":{const c=this.clipConfiguration.offset?.y+.025,h=this.clipConfiguration.offset?.y;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"slideDown":{const c=this.clipConfiguration.offset?.y-.025,h=this.clipConfiguration.offset?.y;t.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:e,offsetYKeyframes:t,opacityKeyframes:i,scaleKeyframes:n,rotationKeyframes:r}}buildOutPreset(){const e=[],t=[],i=[],n=[],r=[];if(!this.clipConfiguration.transition?.out)return{offsetXKeyframes:e,offsetYKeyframes:t,opacityKeyframes:i,scaleKeyframes:n,rotationKeyframes:r};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,d=h+9;n.push({from:h,to:d,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;e.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;e.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;t.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;t.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:e,offsetYKeyframes:t,opacityKeyframes:i,scaleKeyframes:n,rotationKeyframes:r}}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 tn{static ButtonLeftClick=0;static ButtonRightClick=3}class sn{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 be{container;constructor(){this.container=new f.Container}getContainer(){return this.container}}class G extends be{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 sn(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 f.Container,this.getContainer().addChild(this.contentContainer)}reconfigureAfterRestore(){this.configureKeyframes()}configureKeyframes(){if(this.offsetXKeyframeBuilder=new K(this.clipConfiguration.offset?.x??0,this.getLength()),this.offsetYKeyframeBuilder=new K(this.clipConfiguration.offset?.y??0,this.getLength()),this.scaleKeyframeBuilder=new K(this.clipConfiguration.scale??1,this.getLength(),1),this.opacityKeyframeBuilder=new K(this.clipConfiguration.opacity??1,this.getLength(),1),this.rotationKeyframeBuilder=new K(this.clipConfiguration.transform?.rotate?.angle??0,this.getLength()),this.clipHasKeyframes())return;const e=[],t=[],i=[],n=[],r=[],a=new Js(this.clipConfiguration).build(this.edit.size,this.getSize());e.push(...a.offsetXKeyframes),t.push(...a.offsetYKeyframes),i.push(...a.opacityKeyframes),n.push(...a.scaleKeyframes),r.push(...a.rotationKeyframes);const o=new en(this.clipConfiguration).build();e.push(...o.offsetXKeyframes),t.push(...o.offsetYKeyframes),i.push(...o.opacityKeyframes),n.push(...o.scaleKeyframes),r.push(...o.rotationKeyframes),e.length&&(this.offsetXKeyframeBuilder=new K(e,this.getLength())),t.length&&(this.offsetYKeyframeBuilder=new K(t,this.getLength())),i.length&&(this.opacityKeyframeBuilder=new K(i,this.getLength(),1)),n.length&&(this.scaleKeyframeBuilder=new K(n,this.getLength(),1)),r.length&&(this.rotationKeyframeBuilder=new K(r,this.getLength()))}async load(){this.outline=new f.Graphics,this.getContainer().addChild(this.outline),this.topLeftScaleHandle=new f.Graphics,this.topRightScaleHandle=new f.Graphics,this.bottomRightScaleHandle=new f.Graphics,this.bottomLeftScaleHandle=new f.Graphics,this.rotationHandle=new f.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(),n=this.getPosition(),r=this.getContainerScale();this.getContainer().scale.set(r.x,r.y),this.getContainer().pivot.set(i.x,i.y),this.getContainer().position.set(n.x+i.x,n.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 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,n=this.getSize(),r=this.getScale();if(this.outline.clear(),this.outline.strokeStyle={width:G.OutlineWidth/r,color:i},this.outline.rect(0,0,n.width,n.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 a=G.ScaleHandleRadius*2/r;if(this.topLeftScaleHandle.rect(-a/2,-a/2,a,a),this.topLeftScaleHandle.fill(),this.topRightScaleHandle.fillStyle={color:i},this.topRightScaleHandle.clear(),this.topRightScaleHandle.rect(n.width-a/2,-a/2,a,a),this.topRightScaleHandle.fill(),this.bottomRightScaleHandle.fillStyle={color:i},this.bottomRightScaleHandle.clear(),this.bottomRightScaleHandle.rect(n.width-a/2,n.height-a/2,a,a),this.bottomRightScaleHandle.fill(),this.bottomLeftScaleHandle.fillStyle={color:i},this.bottomLeftScaleHandle.clear(),this.bottomLeftScaleHandle.rect(-a/2,n.height-a/2,a,a),this.bottomLeftScaleHandle.fill(),!this.rotationHandle)return;const o=n.width/2,l=-50/r;this.rotationHandle.clear(),this.rotationHandle.fillStyle={color:i},this.rotationHandle.circle(o,l,G.RotationHandleRadius/r),this.rotationHandle.fill(),this.outline.strokeStyle={width:G.OutlineWidth/r,color:i},this.outline.moveTo(o,0),this.outline.lineTo(o,l),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(){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(){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 n=this.edit.size.width/t.width,r=this.edit.size.height/t.height;switch(i){case"contain":{const a=Math.min(n,r)*e;return{x:a,y:a}}case"crop":{const o=(this.edit.size.height>=this.edit.size.width?r:n)*e;return{x:o,y:o}}case"cover":return{x:n*e,y:r*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()<G.DiscardedFrameCount}onPointerStart(e){if(e.button!==tn.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 l=e.getLocalPosition(this.edit.getContainer());this.scaleOffset=l;return}if(this.rotationHandle?.getBounds().containsPoint(e.globalX,e.globalY)){this.isRotating=!0,this.rotationStart=this.getRotation();const l=e.getLocalPosition(this.edit.getContainer());this.rotationOffset=l;return}this.isDragging=!0;const o=e.getLocalPosition(this.edit.getContainer());this.dragOffset={x:o.x-this.getContainer().position.x,y:o.y-this.getContainer().position.y}}onPointerMove(e){if(this.scaleDirection!==null&&this.scaleStart!==null){const t=e.getLocalPosition(this.edit.getContainer()),i=this.getPosition(),n=this.getPivot(),r={x:i.x+n.x,y:i.y+n.y},a=Math.sqrt((this.scaleOffset.x-r.x)**2+(this.scaleOffset.y-r.y)**2),l=Math.sqrt((t.x-r.x)**2+(t.y-r.y)**2)/a,c=this.scaleStart*l;this.clipConfiguration.scale=Math.max(G.MinScale,Math.min(c,G.MaxScale)),this.scaleKeyframeBuilder=new K(this.clipConfiguration.scale,this.getLength(),1);return}if(this.isRotating&&this.rotationStart!==null){const t=e.getLocalPosition(this.edit.getContainer()),i=this.getPosition(),n=this.getPivot(),r={x:i.x+n.x,y:i.y+n.y},a=Math.atan2(this.rotationOffset.y-r.y,this.rotationOffset.x-r.x),l=(Math.atan2(t.y-r.y,t.x-r.x)-a)*(180/Math.PI);let c=this.rotationStart+l;const h=45,d=c%h,u=2;Math.abs(d)<u?c=Math.floor(c/h)*h:Math.abs(d-h)<u&&(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 K(this.clipConfiguration.transform.rotate.angle,this.getLength());return}if(this.isDragging){const t=e.getLocalPosition(this.edit.getContainer()),i=this.getPivot(),n={x:t.x-this.dragOffset.x,y:t.y-this.dragOffset.y},r={x:n.x-i.x,y:n.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:r.x,y:r.y},{x:r.x+this.getSize().width,y:r.y},{x:r.x,y:r.y+this.getSize().height},{x:r.x+this.getSize().width,y:r.y+this.getSize().height}],h={x:r.x+this.getSize().width/2,y:r.y+this.getSize().height/2},d=[...c,h];let u=G.SnapThreshold,p=G.SnapThreshold,g=null,b=null;for(const B of d)for(const N of l){const J=Math.abs(B.x-N.x);J<u&&(u=J,g=r.x+(N.x-B.x));const $=Math.abs(B.y-N.y);$<p&&(p=$,b=r.y+(N.y-B.y))}g!==null&&(r.x=g),b!==null&&(r.y=b);const _=this.positionBuilder.absoluteToRelative(this.getSize(),this.clipConfiguration.position??"center",r);this.clipConfiguration.offset||(this.clipConfiguration.offset={x:0,y:0}),this.clipConfiguration.offset.x=_.x,this.clipConfiguration.offset.y=_.y,this.offsetXKeyframeBuilder=new K(this.clipConfiguration.offset.x,this.getLength()),this.offsetYKeyframeBuilder=new K(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,n=Number(this.clipConfiguration.transform?.rotate?.angle??0),r=this.initialClipConfiguration.offset?.x,a=this.initialClipConfiguration.offset?.y,o=this.initialClipConfiguration.scale,l=Number(this.initialClipConfiguration.transform?.rotate?.angle??0);return r!==void 0&&e!==r||a!==void 0&&t!==a||o!==void 0&&i!==o||n!==l}}class Ai extends G{audioResource;isPlaying;volumeKeyframeBuilder;syncTimer;constructor(e,t){super(e,t),this.audioResource=null,this.isPlaying=!1;const i=t.asset;this.volumeKeyframeBuilder=new K(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:Tt.Name},n=await this.edit.assetLoader.load(t,i);if(!(n instanceof qs.Howl))throw new Error(`Invalid audio source '${e.src}'.`);this.audioResource=n,this.configureKeyframes()}update(e,t){super.update(e,t);const{trim:i=0}=this.clipConfiguration.asset;if(this.syncTimer+=t,this.getContainer().alpha=0,!this.audioResource)return;const n=this.edit.isPlaying&&this.isActive(),r=this.getPlaybackTime();n&&(this.isPlaying||(this.isPlaying=!0,this.audioResource.seek(r/1e3+i),this.audioResource.play()),this.audioResource.volume()!==this.getVolume()&&this.audioResource.volume(this.getVolume()),Math.abs((this.audioResource.seek()-i)*1e3-r)>100&&this.audioResource.seek(r/1e3+i)),this.isPlaying&&!n&&(this.isPlaying=!1,this.audioResource.pause());const a=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&a&&(this.syncTimer=0,this.audioResource.seek(r/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 nn=`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
- `,rn=`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
- }`,an=`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
- `,on=`struct OutlineUniforms {
118
+ `,Yn=`struct OutlineUniforms {
119
119
  uThickness:vec2<f32>,
120
120
  uColor:vec3<f32>,
121
121
  uAlpha:f32,
@@ -179,121 +179,193 @@ fn outlineMaxAlphaAtPos(uv: vec2<f32>) -> f32 {
179
179
  return maxAlpha;
180
180
  }
181
181
 
182
- const DOUBLE_PI: f32 = 3.14159265358979323846264 * 2.;`,cn=Object.defineProperty,ln=(s,e,t)=>e in s?cn(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Re=(s,e,t)=>(ln(s,typeof e!="symbol"?e+"":e,t),t);const bt=class $e extends re.Filter{constructor(...e){let t=e[0]??{};typeof t=="number"&&(re.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={...$e.DEFAULT_OPTIONS,...t};const i=t.quality??.1,n=re.GpuProgram.from({vertex:{source:rn,entryPoint:"mainVertex"},fragment:{source:on,entryPoint:"mainFragment"}}),r=re.GlProgram.from({vertex:nn,fragment:an.replace(/\$\{ANGLE_STEP\}/,$e.getAngleStep(i).toFixed(7)),name:"outline-filter"});super({gpuProgram:n,glProgram:r,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"}}}}),Re(this,"uniforms"),Re(this,"_thickness"),Re(this,"_quality"),Re(this,"_color"),this.uniforms=this.resources.outlineUniforms.uniforms,this.uniforms.uAngleStep=$e.getAngleStep(i),this._color=new re.Color,this.color=t.color??0,Object.assign(this,t)}apply(e,t,i,n){this.uniforms.uThickness[0]=this.thickness/t.source.width,this.uniforms.uThickness[1]=this.thickness/t.source.height,e.applyFilter(this,t,i,n)}static getAngleStep(e){return parseFloat((Math.PI*2/Math.max(e*$e.MAX_SAMPLES,$e.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,n]=this._color.toArray();this.uniforms.uColor[0]=t,this.uniforms.uColor[1]=i,this.uniforms.uColor[2]=n}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=$e.getAngleStep(e)}get knockout(){return this.uniforms.uKnockout===1}set knockout(e){this.uniforms.uKnockout=e?1:0}};Re(bt,"DEFAULT_OPTIONS",{thickness:1,color:0,alpha:1,quality:.1,knockout:!1}),Re(bt,"MIN_SAMPLES",1),Re(bt,"MAX_SAMPLES",100);let Jt=bt;class hn extends G{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 f.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 n=new f.Text;n.text=t.text;const{horizontal:r,vertical:a}=t.alignment;n.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:r};let o=(e.width??this.edit.size.width)/2-n.width/2,l=(e.height??this.edit.size.height)/2-n.height/2;if(r==="left"&&(o=0),r==="right"&&(o=(e.width??this.edit.size.width)-n.width),a==="top"&&(l=0),a==="bottom"&&(l=(e.height??this.edit.size.height)-n.height),n.position={x:o,y:l},t.stroke.color&&t.stroke.width){const c=new Jt({thickness:t.stroke.width,color:t.stroke.color});n.filters=[c]}this.background=i,this.text=n,this.contentContainer.addChild(i),this.contentContainer.addChild(n),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:n}=e;if(!t.includes('data-html-type="text"'))return console.warn("Unsupported html format."),null;const a=new DOMParser().parseFromString(t,"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,d=this.parseAlignment(n??"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=d;let u="";return h.background.length&&(u=h.background),h.backgroundColor.length&&(u=h.backgroundColor),c.background={color:u.length?u: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(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 dn extends G{texture;sprite;constructor(e,t){super(e,t),this.texture=null,this.sprite=null}async load(){await super.load();const e=this.clipConfiguration.asset,t=e.src,i={src:t,crossovern:"anonymous",data:{}},n=await this.edit.assetLoader.load(t,i);if(!(n?.source instanceof f.ImageSource))throw new Error(`Invalid image source '${e.src}'.`);this.texture=this.createCroppedTexture(n),this.sprite=new f.Sprite(this.texture),this.contentContainer.addChild(this.sprite),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}getSize(){return{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,n=e.height,r=Math.floor((t.crop?.left??0)*i),a=Math.floor((t.crop?.right??0)*i),o=Math.floor((t.crop?.top??0)*n),l=Math.floor((t.crop?.bottom??0)*n),c=r,h=o,d=i-r-a,u=n-o-l,p=new f.Rectangle(c,h,d,u);return new f.Texture({source:e.source,frame:p})}}class Oi extends G{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}},n=await this.edit.assetLoader.load(t,i);if(!(n?.source instanceof f.ImageSource||n?.source instanceof f.VideoSource))throw new Error(`Invalid luma source '${e.src}'.`);this.texture=n,this.sprite=new f.Sprite(this.texture),this.contentContainer.addChild(this.sprite),this.configureKeyframes()}update(e,t){if(super.update(e,t),!this.texture||!(this.texture.source instanceof f.VideoSource))return;const i=this.getPlaybackTime(),n=this.edit.isPlaying&&this.isActive();n&&(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)),!n&&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 un extends G{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 f.Graphics,i=e.width??this.edit.size.width,n=e.height??this.edit.size.height;t.fillStyle={color:"transparent"},t.rect(0,0,i,n),t.fill();const r=new f.Graphics;switch(e.shape){case"rectangle":{const a=e.rectangle,o=i/2-a.width/2,l=n/2-a.height/2;r.rect(o,l,a.width,a.height);break}case"circle":{const a=e.circle,o=i/2,l=n/2;r.circle(o,l,a.radius);break}case"line":{const a=e.line,o=i/2-a.length/2,l=n/2-a.thickness/2;r.rect(o,l,a.length,a.thickness);break}default:console.warn("Unsupported shape asset type.");break}if(r.fillStyle={color:e.fill?.color??"#ffffff",alpha:e.fill?.opacity??1},r.fill(),e.stroke){const a=new Jt({thickness:e.stroke.width,color:e.stroke.color});r.filters=[a]}this.shapeBackground=t,this.shape=r,this.contentContainer.addChild(t),t.addChild(r),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 rt{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,n){this.parent=e,this.textElement=t,this.clipConfig=i,this.width=n?.width??rt.DEFAULT_CURSOR_WIDTH_PX,this.color=n?.color??rt.DEFAULT_CURSOR_COLOR,this.blinkIntervalMs=n?.blinkInterval??rt.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 f.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),n=i.match(/\n/g);this.currentLine=n?n.length:0;const r=e.split(`
183
- `),a=this.currentLine<r.length?r[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`,t)-this.measureText("x",t):h=this.measureText(c,t);const d=t.lineHeight;this.pixelY=this.currentLine*d;const p=this.clipConfig.asset.alignment?.horizontal??"center";let g=h;if(p!=="left"){const b=this.measureText(a,t),_=this.textElement.width;let B=0;p==="center"?B=(_-b)/2:p==="right"&&(B=_-b),g=B+h}this.pixelX=g}updateGraphicsPosition(){this.cursor&&this.cursor.position.set(this.pixelX,this.pixelY)}startBlinkingAnimation(){!this.cursor||this.isBlinking||(this.isBlinking=!0,this.blinkInterval=window.setInterval(()=>{this.cursor&&this.isBlinking&&(this.cursor.visible=!this.cursor.visible)},this.blinkIntervalMs))}stopBlinkingAnimation(){this.blinkInterval!==null&&(window.clearInterval(this.blinkInterval),this.blinkInterval=null),this.isBlinking=!1,this.cursor&&(this.cursor.visible=this.isVisible)}measureText(e,t){const i=new f.Text(e,t),{width:n}=i;return i.destroy(),n}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 kt{static DEFAULT_FOCUS_DELAY_MS=50;hiddenInput=null;isFocused=!1;focusRetryCount=0;maxFocusRetries=3;focusDelay=kt.DEFAULT_FOCUS_DELAY_MS;eventHandlers={};abortController=null;textChangeCallback=null;lastSyncedText="";isComposing=!1;setupInput(e,t){this.focusDelay=t?.focusDelay??kt.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,n=Math.max(0,Math.min(e,i)),r=Math.max(n,Math.min(t,i));this.hiddenInput.setSelectionRange(n,r)}getCursorPosition(){return this.hiddenInput?.selectionStart||0}getValue(){return this.hiddenInput?.value||""}setTextInputHandler(e){this.textChangeCallback=e}setEventHandlers(e){this.eventHandlers={...this.eventHandlers,...e}}isFocusedInput(){return this.isFocused}dispose(){this.removeAllEventListeners(),this.hiddenInput&&this.hiddenInput.parentNode&&this.hiddenInput.parentNode.removeChild(this.hiddenInput),this.hiddenInput=null,this.isFocused=!1,this.focusRetryCount=0,this.textChangeCallback=null,this.eventHandlers={}}createHiddenTextarea(){this.hiddenInput=document.createElement("textarea");const e={position:"absolute",opacity:"0.01",pointerEvents:"none",zIndex:"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,n=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(i,n)}},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 ae{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<ae.DOUBLE_CLICK_THRESHOLD_MS&&this.startEditing(),this.lastClickTime=t};setupOutsideClickHandler(e){this.outsideClickHandler=t=>{const n=this.parent.getContainer().getBounds(),r=t.clientX,a=t.clientY;(r<n.x||r>n.x+n.width||a<n.y||a>n.y+n.height)&&(this.stopEditing(!0,e),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null))},setTimeout(()=>{this.outsideClickHandler&&window.addEventListener("click",this.outsideClickHandler)},ae.CLICK_HANDLER_DELAY_MS)}createEditingEnvironment(){this.setupEditingContainer(),this.editingContainer&&this.editableText&&(this.textCursor=new rt(this.editingContainer,this.editableText,this.clipConfig),this.textCursor.updatePosition(this.targetText.text.length),this.textCursor.startBlinking()),this.setupTextInputHandler(),this.updateTextAlignment()}setupEditingContainer(){this.editingContainer=new f.Container,this.parent.getContainer().addChild(this.editingContainer);const e=new f.Graphics;e.fillStyle={color:0,alpha:ae.EDITING_BG_ALPHA},e.rect(-5,-5,this.targetText.width+2*ae.EDITING_BG_PADDING_PX,this.targetText.height+2*ae.EDITING_BG_PADDING_PX),e.fill(),this.editingContainer.addChild(e),this.editableText=new f.Text(this.targetText.text,this.targetText.style),this.editableText.eventMode="static",this.editableText.cursor="text",this.editingContainer.addChild(this.editableText)}setupTextInputHandler(){this.textInputHandler=new kt,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),n=this.calculateVerticalPosition({height:this.editableText.height},e,t.vertical);if(this.editingContainer.position.set(i,n),this.editingContainer.children.length>0){const r=this.editingContainer.getChildAt(0);r instanceof f.Graphics&&(r.clear(),r.fillStyle={color:0,alpha:ae.EDITING_BG_ALPHA},r.rect(-5,-5,this.editableText.width+2*ae.EDITING_BG_PADDING_PX,this.editableText.height+2*ae.EDITING_BG_PADDING_PX),r.fill())}}calculateHorizontalPosition(e,t,i="center"){switch(i){case"center":return t.width/2-e.width/2;case"right":return t.width-e.width;case"left":default:return 0}}calculateVerticalPosition(e,t,i="center"){switch(i){case"center":return t.height/2-e.height/2;case"bottom":return t.height-e.height;case"top":default:return 0}}getContainerDimensions(){const e=this.clipConfig.asset;return{width:e.width??this.parent.getSize().width,height:e.height??this.parent.getSize().height}}getAlignmentSettings(){const e=this.clipConfig.asset;return{horizontal:e.alignment?.horizontal??"center",vertical:e.alignment?.vertical??"center"}}}class pn extends G{background=null;text=null;textEditor=null;async load(){await super.load();const e=this.clipConfiguration.asset;if(this.background=new f.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 f.Text(e.text,this.createTextStyle(e)),this.positionText(e),e.stroke){const t=new Jt({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 ae(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 f.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",n=e.width??this.edit.size.width,r=e.height??this.edit.size.height;let a=n/2-this.text.width/2,o=r/2-this.text.height/2;t==="left"?a=0:t==="right"&&(a=n-this.text.width),i==="top"?o=0:i==="bottom"&&(o=r-this.text.height),this.text.position.set(a,o)}updateTextContent(e,t){this.edit.updateTextContent(this,e,t)}}class fn extends G{texture;sprite;isPlaying;volumeKeyframeBuilder;syncTimer;skipVideoUpdate;constructor(e,t){super(e,t),this.texture=null,this.sprite=null,this.isPlaying=!1;const i=this.clipConfiguration.asset;this.volumeKeyframeBuilder=new K(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}},n=await this.edit.assetLoader.load(t,i);if(!(n?.source instanceof f.VideoSource))throw new Error(`Invalid video source '${e.src}'.`);this.texture=this.createCroppedTexture(n),this.sprite=new f.Sprite(this.texture),this.contentContainer.addChild(this.sprite),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 n=this.getPlaybackTime(),r=this.edit.isPlaying&&this.isActive();r&&(this.isPlaying||(this.isPlaying=!0,this.texture.source.resource.currentTime=n/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-n)>100&&(this.texture.source.resource.currentTime=n/1e3+i)),!r&&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=n/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(e){const t=this.clipConfiguration.asset;if(!t.crop)return e;const i=e.width,n=e.height,r=Math.floor((t.crop?.left??0)*i),a=Math.floor((t.crop?.right??0)*i),o=Math.floor((t.crop?.top??0)*n),l=Math.floor((t.crop?.bottom??0)*n),c=r,h=o,d=i-r-a,u=n-o-l,p=new f.Rectangle(c,h,d,u);return new f.Texture({source:e.source,frame:p})}}var R;(function(s){s.assertEqual=n=>n;function e(n){}s.assertIs=e;function t(n){throw new Error}s.assertNever=t,s.arrayToEnum=n=>{const r={};for(const a of n)r[a]=a;return r},s.getValidEnumValues=n=>{const r=s.objectKeys(n).filter(o=>typeof n[n[o]]!="number"),a={};for(const o of r)a[o]=n[o];return s.objectValues(a)},s.objectValues=n=>s.objectKeys(n).map(function(r){return n[r]}),s.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{const r=[];for(const a in n)Object.prototype.hasOwnProperty.call(n,a)&&r.push(a);return r},s.find=(n,r)=>{for(const a of n)if(r(a))return a},s.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&isFinite(n)&&Math.floor(n)===n;function i(n,r=" | "){return n.map(a=>typeof a=="string"?`'${a}'`:a).join(r)}s.joinValues=i,s.jsonStringifyReplacer=(n,r)=>typeof r=="bigint"?r.toString():r})(R||(R={}));var Mi;(function(s){s.mergeShapes=(e,t)=>({...e,...t})})(Mi||(Mi={}));const C=R.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ke=s=>{switch(typeof s){case"undefined":return C.undefined;case"string":return C.string;case"number":return isNaN(s)?C.nan:C.number;case"boolean":return C.boolean;case"function":return C.function;case"bigint":return C.bigint;case"symbol":return C.symbol;case"object":return Array.isArray(s)?C.array:s===null?C.null:s.then&&typeof s.then=="function"&&s.catch&&typeof s.catch=="function"?C.promise:typeof Map<"u"&&s instanceof Map?C.map:typeof Set<"u"&&s instanceof Set?C.set:typeof Date<"u"&&s instanceof Date?C.date:C.object;default:return C.unknown}},m=R.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 ie 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(r){return r.message},i={_errors:[]},n=r=>{for(const a of r.issues)if(a.code==="invalid_union")a.unionErrors.map(n);else if(a.code==="invalid_return_type")n(a.returnTypeError);else if(a.code==="invalid_arguments")n(a.argumentsError);else if(a.path.length===0)i._errors.push(t(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(t(a))):o[c]=o[c]||{_errors:[]},o=o[c],l++}}};return n(this),i}static assert(e){if(!(e instanceof ie))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,R.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},i=[];for(const n of this.issues)n.path.length>0?(t[n.path[0]]=t[n.path[0]]||[],t[n.path[0]].push(e(n))):i.push(e(n));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}}ie.create=s=>new ie(s);const at=(s,e)=>{let t;switch(s.code){case m.invalid_type:s.received===C.undefined?t="Required":t=`Expected ${s.expected}, received ${s.received}`;break;case m.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(s.expected,R.jsonStringifyReplacer)}`;break;case m.unrecognized_keys:t=`Unrecognized key(s) in object: ${R.joinValues(s.keys,", ")}`;break;case m.invalid_union:t="Invalid input";break;case m.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${R.joinValues(s.options)}`;break;case m.invalid_enum_value:t=`Invalid enum value. Expected ${R.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}"`:R.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==="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,R.assertNever(s)}return{message:t}};let mn=at;function ei(){return mn}const ti=s=>{const{data:e,path:t,errorMaps:i,issueData:n}=s,r=[...t,...n.path||[]],a={...n,path:r};if(n.message!==void 0)return{...n,path:r,message:n.message};let o="";const l=i.filter(c=>!!c).slice().reverse();for(const c of l)o=c(a,{data:e,defaultError:o}).message;return{...n,path:r,message:o}};function y(s,e){const t=ei(),i=ti({issueData:e,data:s.data,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,t,t===at?void 0:at].filter(n=>!!n)});s.common.issues.push(i)}class j{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 n of t){if(n.status==="aborted")return E;n.status==="dirty"&&e.dirty(),i.push(n.value)}return{status:e.value,value:i}}static async mergeObjectAsync(e,t){const i=[];for(const n of t){const r=await n.key,a=await n.value;i.push({key:r,value:a})}return j.mergeObjectSync(e,i)}static mergeObjectSync(e,t){const i={};for(const n of t){const{key:r,value:a}=n;if(r.status==="aborted"||a.status==="aborted")return E;r.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),r.value!=="__proto__"&&(typeof a.value<"u"||n.alwaysSet)&&(i[r.value]=a.value)}return{status:e.value,value:i}}}const E=Object.freeze({status:"aborted"}),ot=s=>({status:"dirty",value:s}),q=s=>({status:"valid",value:s}),Ri=s=>s.status==="aborted",Bi=s=>s.status==="dirty",Ze=s=>s.status==="valid",St=s=>typeof Promise<"u"&&s instanceof Promise;function _t(s,e,t,i){if(typeof e=="function"?s!==e||!0:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(s)}function Li(s,e,t,i,n){if(typeof e=="function"?s!==e||!0:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(s,t),t}typeof SuppressedError=="function"&&SuppressedError;var v;(function(s){s.errToObj=e=>typeof e=="string"?{message:e}:e||{},s.toString=e=>typeof e=="string"?e:e?.message})(v||(v={}));var ct,lt;class oe{constructor(e,t,i,n){this._cachedPath=[],this.parent=e,this.data=t,this._path=i,this._key=n}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 Fi=(s,e)=>{if(Ze(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 ie(s.common.issues);return this._error=t,this._error}}};function P(s){if(!s)return{};const{errorMap:e,invalid_type_error:t,required_error:i,description:n}=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:n}:{errorMap:(a,o)=>{var l,c;const{message:h}=s;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??t)!==null&&c!==void 0?c:o.defaultError}},description:n}}class A{get description(){return this._def.description}_getType(e){return ke(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ke(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new j,ctx:{common:e.parent.common,data:e.data,parsedType:ke(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(St(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){var i;const n={common:{issues:[],async:(i=t?.async)!==null&&i!==void 0?i:!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ke(e)},r=this._parseSync({data:e,path:n.path,parent:n});return Fi(n,r)}"~validate"(e){var t,i;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ke(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:n});return Ze(r)?{value:r.value}:{issues:n.common.issues}}catch(r){!((i=(t=r?.message)===null||t===void 0?void 0:t.toLowerCase())===null||i===void 0)&&i.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>Ze(r)?{value:r.value}:{issues:n.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:ke(e)},n=this._parse({data:e,path:i.path,parent:i}),r=await(St(n)?n:Promise.resolve(n));return Fi(i,r)}refine(e,t){const i=n=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(n):t;return this._refinement((n,r)=>{const a=e(n),o=()=>r.addIssue({code:m.custom,...i(n)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,t){return this._refinement((i,n)=>e(i)?!0:(n.addIssue(typeof t=="function"?t(i,n):t),!1))}_refinement(e){return new Ce({schema:this,typeName:S.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 xe.create(this,this._def)}nullable(){return Le.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ce.create(this)}promise(){return ut.create(this,this._def)}or(e){return Pt.create([this,e],this._def)}and(e){return At.create(this,e,this._def)}transform(e){return new Ce({...P(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Lt({...P(this._def),innerType:this,defaultValue:t,typeName:S.ZodDefault})}brand(){return new Vi({typeName:S.ZodBranded,type:this,...P(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Ft({...P(this._def),innerType:this,catchValue:t,typeName:S.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return zt.create(this,e)}readonly(){return Dt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const gn=/^c[^\s-]{8,}$/i,yn=/^[0-9a-z]+$/,wn=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Cn=/^[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,xn=/^[a-z0-9_-]{21}$/i,vn=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Tn=/^[-+]?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)?)??$/,bn=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,kn="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let ii;const Sn=/^(?:(?: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])$/,_n=/^(?:(?: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])$/,En=/^(([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]))$/,In=/^(([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])$/,Pn=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,An=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,zi="((\\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])))",On=new RegExp(`^${zi}$`);function Di(s){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return s.precision?e=`${e}\\.\\d{${s.precision}}`:s.precision==null&&(e=`${e}(\\.\\d+)?`),e}function Mn(s){return new RegExp(`^${Di(s)}$`)}function Rn(s){let e=`${zi}T${Di(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 Bn(s,e){return!!((e==="v4"||!e)&&Sn.test(s)||(e==="v6"||!e)&&En.test(s))}function Ln(s,e){if(!vn.test(s))return!1;try{const[t]=s.split("."),i=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),n=JSON.parse(atob(i));return!(typeof n!="object"||n===null||!n.typ||!n.alg||e&&n.alg!==e)}catch{return!1}}function Fn(s,e){return!!((e==="v4"||!e)&&_n.test(s)||(e==="v6"||!e)&&In.test(s))}class ge extends A{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==C.string){const r=this._getOrReturnCtx(e);return y(r,{code:m.invalid_type,expected:C.string,received:r.parsedType}),E}const i=new j;let n;for(const r of this._def.checks)if(r.kind==="min")e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),y(n,{code:m.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),i.dirty());else if(r.kind==="max")e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),y(n,{code:m.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!1,message:r.message}),i.dirty());else if(r.kind==="length"){const a=e.data.length>r.value,o=e.data.length<r.value;(a||o)&&(n=this._getOrReturnCtx(e,n),a?y(n,{code:m.too_big,maximum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}):o&&y(n,{code:m.too_small,minimum:r.value,type:"string",inclusive:!0,exact:!0,message:r.message}),i.dirty())}else if(r.kind==="email")bn.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"email",code:m.invalid_string,message:r.message}),i.dirty());else if(r.kind==="emoji")ii||(ii=new RegExp(kn,"u")),ii.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"emoji",code:m.invalid_string,message:r.message}),i.dirty());else if(r.kind==="uuid")Cn.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"uuid",code:m.invalid_string,message:r.message}),i.dirty());else if(r.kind==="nanoid")xn.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"nanoid",code:m.invalid_string,message:r.message}),i.dirty());else if(r.kind==="cuid")gn.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"cuid",code:m.invalid_string,message:r.message}),i.dirty());else if(r.kind==="cuid2")yn.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"cuid2",code:m.invalid_string,message:r.message}),i.dirty());else if(r.kind==="ulid")wn.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"ulid",code:m.invalid_string,message:r.message}),i.dirty());else if(r.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),y(n,{validation:"url",code:m.invalid_string,message:r.message}),i.dirty()}else r.kind==="regex"?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"regex",code:m.invalid_string,message:r.message}),i.dirty())):r.kind==="trim"?e.data=e.data.trim():r.kind==="includes"?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),y(n,{code:m.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),i.dirty()):r.kind==="toLowerCase"?e.data=e.data.toLowerCase():r.kind==="toUpperCase"?e.data=e.data.toUpperCase():r.kind==="startsWith"?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),y(n,{code:m.invalid_string,validation:{startsWith:r.value},message:r.message}),i.dirty()):r.kind==="endsWith"?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),y(n,{code:m.invalid_string,validation:{endsWith:r.value},message:r.message}),i.dirty()):r.kind==="datetime"?Rn(r).test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{code:m.invalid_string,validation:"datetime",message:r.message}),i.dirty()):r.kind==="date"?On.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{code:m.invalid_string,validation:"date",message:r.message}),i.dirty()):r.kind==="time"?Mn(r).test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{code:m.invalid_string,validation:"time",message:r.message}),i.dirty()):r.kind==="duration"?Tn.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"duration",code:m.invalid_string,message:r.message}),i.dirty()):r.kind==="ip"?Bn(e.data,r.version)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"ip",code:m.invalid_string,message:r.message}),i.dirty()):r.kind==="jwt"?Ln(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"jwt",code:m.invalid_string,message:r.message}),i.dirty()):r.kind==="cidr"?Fn(e.data,r.version)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"cidr",code:m.invalid_string,message:r.message}),i.dirty()):r.kind==="base64"?Pn.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"base64",code:m.invalid_string,message:r.message}),i.dirty()):r.kind==="base64url"?An.test(e.data)||(n=this._getOrReturnCtx(e,n),y(n,{validation:"base64url",code:m.invalid_string,message:r.message}),i.dirty()):R.assertNever(r);return{status:i.value,value:e.data}}_regex(e,t,i){return this.refinement(n=>e.test(n),{validation:t,code:m.invalid_string,...v.errToObj(i)})}_addCheck(e){return new ge({...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){var t,i;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:(t=e?.offset)!==null&&t!==void 0?t:!1,local:(i=e?.local)!==null&&i!==void 0?i:!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 ge({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new ge({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new ge({...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}}ge.create=s=>{var e;return new ge({checks:[],typeName:S.ZodString,coerce:(e=s?.coerce)!==null&&e!==void 0?e:!1,...P(s)})};function zn(s,e){const t=(s.toString().split(".")[1]||"").length,i=(e.toString().split(".")[1]||"").length,n=t>i?t:i,r=parseInt(s.toFixed(n).replace(".","")),a=parseInt(e.toFixed(n).replace(".",""));return r%a/Math.pow(10,n)}class Ke extends A{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)!==C.number){const r=this._getOrReturnCtx(e);return y(r,{code:m.invalid_type,expected:C.number,received:r.parsedType}),E}let i;const n=new j;for(const r of this._def.checks)r.kind==="int"?R.isInteger(e.data)||(i=this._getOrReturnCtx(e,i),y(i,{code:m.invalid_type,expected:"integer",received:"float",message:r.message}),n.dirty()):r.kind==="min"?(r.inclusive?e.data<r.value:e.data<=r.value)&&(i=this._getOrReturnCtx(e,i),y(i,{code:m.too_small,minimum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind==="max"?(r.inclusive?e.data>r.value:e.data>=r.value)&&(i=this._getOrReturnCtx(e,i),y(i,{code:m.too_big,maximum:r.value,type:"number",inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind==="multipleOf"?zn(e.data,r.value)!==0&&(i=this._getOrReturnCtx(e,i),y(i,{code:m.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind==="finite"?Number.isFinite(e.data)||(i=this._getOrReturnCtx(e,i),y(i,{code:m.not_finite,message:r.message}),n.dirty()):R.assertNever(r);return{status:n.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,n){return new Ke({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:v.toString(n)}]})}_addCheck(e){return new Ke({...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"&&R.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)}}Ke.create=s=>new Ke({checks:[],typeName:S.ZodNumber,coerce:s?.coerce||!1,...P(s)});class je extends A{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)!==C.bigint)return this._getInvalidInput(e);let i;const n=new j;for(const r of this._def.checks)r.kind==="min"?(r.inclusive?e.data<r.value:e.data<=r.value)&&(i=this._getOrReturnCtx(e,i),y(i,{code:m.too_small,type:"bigint",minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind==="max"?(r.inclusive?e.data>r.value:e.data>=r.value)&&(i=this._getOrReturnCtx(e,i),y(i,{code:m.too_big,type:"bigint",maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind==="multipleOf"?e.data%r.value!==BigInt(0)&&(i=this._getOrReturnCtx(e,i),y(i,{code:m.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):R.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return y(t,{code:m.invalid_type,expected:C.bigint,received:t.parsedType}),E}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,n){return new je({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:v.toString(n)}]})}_addCheck(e){return new je({...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}}je.create=s=>{var e;return new je({checks:[],typeName:S.ZodBigInt,coerce:(e=s?.coerce)!==null&&e!==void 0?e:!1,...P(s)})};class si extends A{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==C.boolean){const i=this._getOrReturnCtx(e);return y(i,{code:m.invalid_type,expected:C.boolean,received:i.parsedType}),E}return q(e.data)}}si.create=s=>new si({typeName:S.ZodBoolean,coerce:s?.coerce||!1,...P(s)});class ht extends A{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==C.date){const r=this._getOrReturnCtx(e);return y(r,{code:m.invalid_type,expected:C.date,received:r.parsedType}),E}if(isNaN(e.data.getTime())){const r=this._getOrReturnCtx(e);return y(r,{code:m.invalid_date}),E}const i=new j;let n;for(const r of this._def.checks)r.kind==="min"?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),y(n,{code:m.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:"date"}),i.dirty()):r.kind==="max"?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),y(n,{code:m.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:"date"}),i.dirty()):R.assertNever(r);return{status:i.value,value:new Date(e.data.getTime())}}_addCheck(e){return new ht({...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}}ht.create=s=>new ht({checks:[],coerce:s?.coerce||!1,typeName:S.ZodDate,...P(s)});class ni extends A{_parse(e){if(this._getType(e)!==C.symbol){const i=this._getOrReturnCtx(e);return y(i,{code:m.invalid_type,expected:C.symbol,received:i.parsedType}),E}return q(e.data)}}ni.create=s=>new ni({typeName:S.ZodSymbol,...P(s)});class Et extends A{_parse(e){if(this._getType(e)!==C.undefined){const i=this._getOrReturnCtx(e);return y(i,{code:m.invalid_type,expected:C.undefined,received:i.parsedType}),E}return q(e.data)}}Et.create=s=>new Et({typeName:S.ZodUndefined,...P(s)});class It extends A{_parse(e){if(this._getType(e)!==C.null){const i=this._getOrReturnCtx(e);return y(i,{code:m.invalid_type,expected:C.null,received:i.parsedType}),E}return q(e.data)}}It.create=s=>new It({typeName:S.ZodNull,...P(s)});class ri extends A{constructor(){super(...arguments),this._any=!0}_parse(e){return q(e.data)}}ri.create=s=>new ri({typeName:S.ZodAny,...P(s)});class Xe extends A{constructor(){super(...arguments),this._unknown=!0}_parse(e){return q(e.data)}}Xe.create=s=>new Xe({typeName:S.ZodUnknown,...P(s)});class Se extends A{_parse(e){const t=this._getOrReturnCtx(e);return y(t,{code:m.invalid_type,expected:C.never,received:t.parsedType}),E}}Se.create=s=>new Se({typeName:S.ZodNever,...P(s)});class ai extends A{_parse(e){if(this._getType(e)!==C.undefined){const i=this._getOrReturnCtx(e);return y(i,{code:m.invalid_type,expected:C.void,received:i.parsedType}),E}return q(e.data)}}ai.create=s=>new ai({typeName:S.ZodVoid,...P(s)});class ce extends A{_parse(e){const{ctx:t,status:i}=this._processInputParams(e),n=this._def;if(t.parsedType!==C.array)return y(t,{code:m.invalid_type,expected:C.array,received:t.parsedType}),E;if(n.exactLength!==null){const a=t.data.length>n.exactLength.value,o=t.data.length<n.exactLength.value;(a||o)&&(y(t,{code:a?m.too_big:m.too_small,minimum:o?n.exactLength.value:void 0,maximum:a?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),i.dirty())}if(n.minLength!==null&&t.data.length<n.minLength.value&&(y(t,{code:m.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),i.dirty()),n.maxLength!==null&&t.data.length>n.maxLength.value&&(y(t,{code:m.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),i.dirty()),t.common.async)return Promise.all([...t.data].map((a,o)=>n.type._parseAsync(new oe(t,a,t.path,o)))).then(a=>j.mergeArray(i,a));const r=[...t.data].map((a,o)=>n.type._parseSync(new oe(t,a,t.path,o)));return j.mergeArray(i,r)}get element(){return this._def.type}min(e,t){return new ce({...this._def,minLength:{value:e,message:v.toString(t)}})}max(e,t){return new ce({...this._def,maxLength:{value:e,message:v.toString(t)}})}length(e,t){return new ce({...this._def,exactLength:{value:e,message:v.toString(t)}})}nonempty(e){return this.min(1,e)}}ce.create=(s,e)=>new ce({type:s,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...P(e)});function Ye(s){if(s instanceof H){const e={};for(const t in s.shape){const i=s.shape[t];e[t]=xe.create(Ye(i))}return new H({...s._def,shape:()=>e})}else return s instanceof ce?new ce({...s._def,type:Ye(s.element)}):s instanceof xe?xe.create(Ye(s.unwrap())):s instanceof Le?Le.create(Ye(s.unwrap())):s instanceof we?we.create(s.items.map(e=>Ye(e))):s}class H extends A{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=R.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==C.object){const c=this._getOrReturnCtx(e);return y(c,{code:m.invalid_type,expected:C.object,received:c.parsedType}),E}const{status:i,ctx:n}=this._processInputParams(e),{shape:r,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof Se&&this._def.unknownKeys==="strip"))for(const c in n.data)a.includes(c)||o.push(c);const l=[];for(const c of a){const h=r[c],d=n.data[c];l.push({key:{status:"valid",value:c},value:h._parse(new oe(n,d,n.path,c)),alwaysSet:c in n.data})}if(this._def.catchall instanceof Se){const c=this._def.unknownKeys;if(c==="passthrough")for(const h of o)l.push({key:{status:"valid",value:h},value:{status:"valid",value:n.data[h]}});else if(c==="strict")o.length>0&&(y(n,{code:m.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 d=n.data[h];l.push({key:{status:"valid",value:h},value:c._parse(new oe(n,d,n.path,h)),alwaysSet:h in n.data})}}return n.common.async?Promise.resolve().then(async()=>{const c=[];for(const h of l){const d=await h.key,u=await h.value;c.push({key:d,value:u,alwaysSet:h.alwaysSet})}return c}).then(c=>j.mergeObjectSync(i,c)):j.mergeObjectSync(i,l)}get shape(){return this._def.shape()}strict(e){return v.errToObj,new H({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,i)=>{var n,r,a,o;const l=(a=(r=(n=this._def).errorMap)===null||r===void 0?void 0:r.call(n,t,i).message)!==null&&a!==void 0?a:i.defaultError;return t.code==="unrecognized_keys"?{message:(o=v.errToObj(e).message)!==null&&o!==void 0?o:l}:{message:l}}}:{}})}strip(){return new H({...this._def,unknownKeys:"strip"})}passthrough(){return new H({...this._def,unknownKeys:"passthrough"})}extend(e){return new H({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new H({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:S.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new H({...this._def,catchall:e})}pick(e){const t={};return R.objectKeys(e).forEach(i=>{e[i]&&this.shape[i]&&(t[i]=this.shape[i])}),new H({...this._def,shape:()=>t})}omit(e){const t={};return R.objectKeys(this.shape).forEach(i=>{e[i]||(t[i]=this.shape[i])}),new H({...this._def,shape:()=>t})}deepPartial(){return Ye(this)}partial(e){const t={};return R.objectKeys(this.shape).forEach(i=>{const n=this.shape[i];e&&!e[i]?t[i]=n:t[i]=n.optional()}),new H({...this._def,shape:()=>t})}required(e){const t={};return R.objectKeys(this.shape).forEach(i=>{if(e&&!e[i])t[i]=this.shape[i];else{let r=this.shape[i];for(;r instanceof xe;)r=r._def.innerType;t[i]=r}}),new H({...this._def,shape:()=>t})}keyof(){return Hi(R.objectKeys(this.shape))}}H.create=(s,e)=>new H({shape:()=>s,unknownKeys:"strip",catchall:Se.create(),typeName:S.ZodObject,...P(e)}),H.strictCreate=(s,e)=>new H({shape:()=>s,unknownKeys:"strict",catchall:Se.create(),typeName:S.ZodObject,...P(e)}),H.lazycreate=(s,e)=>new H({shape:s,unknownKeys:"strip",catchall:Se.create(),typeName:S.ZodObject,...P(e)});class Pt extends A{_parse(e){const{ctx:t}=this._processInputParams(e),i=this._def.options;function n(r){for(const o of r)if(o.result.status==="valid")return o.result;for(const o of r)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;const a=r.map(o=>new ie(o.ctx.common.issues));return y(t,{code:m.invalid_union,unionErrors:a}),E}if(t.common.async)return Promise.all(i.map(async r=>{const a={...t,common:{...t.common,issues:[]},parent:null};return{result:await r._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(n);{let r;const a=[];for(const l of i){const c={...t,common:{...t.common,issues:[]},parent:null},h=l._parseSync({data:t.data,path:t.path,parent:c});if(h.status==="valid")return h;h.status==="dirty"&&!r&&(r={result:h,ctx:c}),c.common.issues.length&&a.push(c.common.issues)}if(r)return t.common.issues.push(...r.ctx.common.issues),r.result;const o=a.map(l=>new ie(l));return y(t,{code:m.invalid_union,unionErrors:o}),E}}get options(){return this._def.options}}Pt.create=(s,e)=>new Pt({options:s,typeName:S.ZodUnion,...P(e)});const ye=s=>s instanceof Mt?ye(s.schema):s instanceof Ce?ye(s.innerType()):s instanceof Rt?[s.value]:s instanceof Be?s.options:s instanceof Bt?R.objectValues(s.enum):s instanceof Lt?ye(s._def.innerType):s instanceof Et?[void 0]:s instanceof It?[null]:s instanceof xe?[void 0,...ye(s.unwrap())]:s instanceof Le?[null,...ye(s.unwrap())]:s instanceof Vi||s instanceof Dt?ye(s.unwrap()):s instanceof Ft?ye(s._def.innerType):[];class oi extends A{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==C.object)return y(t,{code:m.invalid_type,expected:C.object,received:t.parsedType}),E;const i=this.discriminator,n=t.data[i],r=this.optionsMap.get(n);return r?t.common.async?r._parseAsync({data:t.data,path:t.path,parent:t}):r._parseSync({data:t.data,path:t.path,parent:t}):(y(t,{code:m.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),E)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,i){const n=new Map;for(const r of t){const a=ye(r.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of a){if(n.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);n.set(o,r)}}return new oi({typeName:S.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:n,...P(i)})}}function ci(s,e){const t=ke(s),i=ke(e);if(s===e)return{valid:!0,data:s};if(t===C.object&&i===C.object){const n=R.objectKeys(e),r=R.objectKeys(s).filter(o=>n.indexOf(o)!==-1),a={...s,...e};for(const o of r){const l=ci(s[o],e[o]);if(!l.valid)return{valid:!1};a[o]=l.data}return{valid:!0,data:a}}else if(t===C.array&&i===C.array){if(s.length!==e.length)return{valid:!1};const n=[];for(let r=0;r<s.length;r++){const a=s[r],o=e[r],l=ci(a,o);if(!l.valid)return{valid:!1};n.push(l.data)}return{valid:!0,data:n}}else return t===C.date&&i===C.date&&+s==+e?{valid:!0,data:s}:{valid:!1}}class At extends A{_parse(e){const{status:t,ctx:i}=this._processInputParams(e),n=(r,a)=>{if(Ri(r)||Ri(a))return E;const o=ci(r.value,a.value);return o.valid?((Bi(r)||Bi(a))&&t.dirty(),{status:t.value,value:o.data}):(y(i,{code:m.invalid_intersection_types}),E)};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(([r,a])=>n(r,a)):n(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}At.create=(s,e,t)=>new At({left:s,right:e,typeName:S.ZodIntersection,...P(t)});class we extends A{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==C.array)return y(i,{code:m.invalid_type,expected:C.array,received:i.parsedType}),E;if(i.data.length<this._def.items.length)return y(i,{code:m.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),E;!this._def.rest&&i.data.length>this._def.items.length&&(y(i,{code:m.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const r=[...i.data].map((a,o)=>{const l=this._def.items[o]||this._def.rest;return l?l._parse(new oe(i,a,i.path,o)):null}).filter(a=>!!a);return i.common.async?Promise.all(r).then(a=>j.mergeArray(t,a)):j.mergeArray(t,r)}get items(){return this._def.items}rest(e){return new we({...this._def,rest:e})}}we.create=(s,e)=>{if(!Array.isArray(s))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new we({items:s,typeName:S.ZodTuple,rest:null,...P(e)})};class Ot extends A{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!==C.object)return y(i,{code:m.invalid_type,expected:C.object,received:i.parsedType}),E;const n=[],r=this._def.keyType,a=this._def.valueType;for(const o in i.data)n.push({key:r._parse(new oe(i,o,i.path,o)),value:a._parse(new oe(i,i.data[o],i.path,o)),alwaysSet:o in i.data});return i.common.async?j.mergeObjectAsync(t,n):j.mergeObjectSync(t,n)}get element(){return this._def.valueType}static create(e,t,i){return t instanceof A?new Ot({keyType:e,valueType:t,typeName:S.ZodRecord,...P(i)}):new Ot({keyType:ge.create(),valueType:e,typeName:S.ZodRecord,...P(t)})}}class li extends A{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!==C.map)return y(i,{code:m.invalid_type,expected:C.map,received:i.parsedType}),E;const n=this._def.keyType,r=this._def.valueType,a=[...i.data.entries()].map(([o,l],c)=>({key:n._parse(new oe(i,o,i.path,[c,"key"])),value:r._parse(new oe(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 E;(c.status==="dirty"||h.status==="dirty")&&t.dirty(),o.set(c.value,h.value)}return{status:t.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 E;(c.status==="dirty"||h.status==="dirty")&&t.dirty(),o.set(c.value,h.value)}return{status:t.value,value:o}}}}li.create=(s,e,t)=>new li({valueType:e,keyType:s,typeName:S.ZodMap,...P(t)});class qe extends A{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==C.set)return y(i,{code:m.invalid_type,expected:C.set,received:i.parsedType}),E;const n=this._def;n.minSize!==null&&i.data.size<n.minSize.value&&(y(i,{code:m.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),t.dirty()),n.maxSize!==null&&i.data.size>n.maxSize.value&&(y(i,{code:m.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),t.dirty());const r=this._def.valueType;function a(l){const c=new Set;for(const h of l){if(h.status==="aborted")return E;h.status==="dirty"&&t.dirty(),c.add(h.value)}return{status:t.value,value:c}}const o=[...i.data.values()].map((l,c)=>r._parse(new oe(i,l,i.path,c)));return i.common.async?Promise.all(o).then(l=>a(l)):a(o)}min(e,t){return new qe({...this._def,minSize:{value:e,message:v.toString(t)}})}max(e,t){return new qe({...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)}}qe.create=(s,e)=>new qe({valueType:s,minSize:null,maxSize:null,typeName:S.ZodSet,...P(e)});class dt extends A{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==C.function)return y(t,{code:m.invalid_type,expected:C.function,received:t.parsedType}),E;function i(o,l){return ti({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ei(),at].filter(c=>!!c),issueData:{code:m.invalid_arguments,argumentsError:l}})}function n(o,l){return ti({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ei(),at].filter(c=>!!c),issueData:{code:m.invalid_return_type,returnTypeError:l}})}const r={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof ut){const o=this;return q(async function(...l){const c=new ie([]),h=await o._def.args.parseAsync(l,r).catch(p=>{throw c.addIssue(i(l,p)),c}),d=await Reflect.apply(a,this,h);return await o._def.returns._def.type.parseAsync(d,r).catch(p=>{throw c.addIssue(n(d,p)),c})})}else{const o=this;return q(function(...l){const c=o._def.args.safeParse(l,r);if(!c.success)throw new ie([i(l,c.error)]);const h=Reflect.apply(a,this,c.data),d=o._def.returns.safeParse(h,r);if(!d.success)throw new ie([n(h,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new dt({...this._def,args:we.create(e).rest(Xe.create())})}returns(e){return new dt({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,i){return new dt({args:e||we.create([]).rest(Xe.create()),returns:t||Xe.create(),typeName:S.ZodFunction,...P(i)})}}class Mt extends A{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})}}Mt.create=(s,e)=>new Mt({getter:s,typeName:S.ZodLazy,...P(e)});class Rt extends A{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return y(t,{received:t.data,code:m.invalid_literal,expected:this._def.value}),E}return{status:"valid",value:e.data}}get value(){return this._def.value}}Rt.create=(s,e)=>new Rt({value:s,typeName:S.ZodLiteral,...P(e)});function Hi(s,e){return new Be({values:s,typeName:S.ZodEnum,...P(e)})}class Be extends A{constructor(){super(...arguments),ct.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),i=this._def.values;return y(t,{expected:R.joinValues(i),received:t.parsedType,code:m.invalid_type}),E}if(_t(this,ct)||Li(this,ct,new Set(this._def.values)),!_t(this,ct).has(e.data)){const t=this._getOrReturnCtx(e),i=this._def.values;return y(t,{received:t.data,code:m.invalid_enum_value,options:i}),E}return q(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 Be.create(e,{...this._def,...t})}exclude(e,t=this._def){return Be.create(this.options.filter(i=>!e.includes(i)),{...this._def,...t})}}ct=new WeakMap,Be.create=Hi;class Bt extends A{constructor(){super(...arguments),lt.set(this,void 0)}_parse(e){const t=R.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(e);if(i.parsedType!==C.string&&i.parsedType!==C.number){const n=R.objectValues(t);return y(i,{expected:R.joinValues(n),received:i.parsedType,code:m.invalid_type}),E}if(_t(this,lt)||Li(this,lt,new Set(R.getValidEnumValues(this._def.values))),!_t(this,lt).has(e.data)){const n=R.objectValues(t);return y(i,{received:i.data,code:m.invalid_enum_value,options:n}),E}return q(e.data)}get enum(){return this._def.values}}lt=new WeakMap,Bt.create=(s,e)=>new Bt({values:s,typeName:S.ZodNativeEnum,...P(e)});class ut extends A{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==C.promise&&t.common.async===!1)return y(t,{code:m.invalid_type,expected:C.promise,received:t.parsedType}),E;const i=t.parsedType===C.promise?t.data:Promise.resolve(t.data);return q(i.then(n=>this._def.type.parseAsync(n,{path:t.path,errorMap:t.common.contextualErrorMap})))}}ut.create=(s,e)=>new ut({type:s,typeName:S.ZodPromise,...P(e)});class Ce extends A{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===S.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:i}=this._processInputParams(e),n=this._def.effect||null,r={addIssue:a=>{y(i,a),a.fatal?t.abort():t.dirty()},get path(){return i.path}};if(r.addIssue=r.addIssue.bind(r),n.type==="preprocess"){const a=n.transform(i.data,r);if(i.common.async)return Promise.resolve(a).then(async o=>{if(t.value==="aborted")return E;const l=await this._def.schema._parseAsync({data:o,path:i.path,parent:i});return l.status==="aborted"?E:l.status==="dirty"||t.value==="dirty"?ot(l.value):l});{if(t.value==="aborted")return E;const o=this._def.schema._parseSync({data:a,path:i.path,parent:i});return o.status==="aborted"?E:o.status==="dirty"||t.value==="dirty"?ot(o.value):o}}if(n.type==="refinement"){const a=o=>{const l=n.refinement(o,r);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"?E:(o.status==="dirty"&&t.dirty(),a(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(o=>o.status==="aborted"?E:(o.status==="dirty"&&t.dirty(),a(o.value).then(()=>({status:t.value,value:o.value}))))}if(n.type==="transform")if(i.common.async===!1){const a=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!Ze(a))return a;const o=n.transform(a.value,r);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(a=>Ze(a)?Promise.resolve(n.transform(a.value,r)).then(o=>({status:t.value,value:o})):a);R.assertNever(n)}}Ce.create=(s,e,t)=>new Ce({schema:s,typeName:S.ZodEffects,effect:e,...P(t)}),Ce.createWithPreprocess=(s,e,t)=>new Ce({schema:e,effect:{type:"preprocess",transform:s},typeName:S.ZodEffects,...P(t)});class xe extends A{_parse(e){return this._getType(e)===C.undefined?q(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}xe.create=(s,e)=>new xe({innerType:s,typeName:S.ZodOptional,...P(e)});class Le extends A{_parse(e){return this._getType(e)===C.null?q(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Le.create=(s,e)=>new Le({innerType:s,typeName:S.ZodNullable,...P(e)});class Lt extends A{_parse(e){const{ctx:t}=this._processInputParams(e);let i=t.data;return t.parsedType===C.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Lt.create=(s,e)=>new Lt({innerType:s,typeName:S.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...P(e)});class Ft extends A{_parse(e){const{ctx:t}=this._processInputParams(e),i={...t,common:{...t.common,issues:[]}},n=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return St(n)?n.then(r=>({status:"valid",value:r.status==="valid"?r.value:this._def.catchValue({get error(){return new ie(i.common.issues)},input:i.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new ie(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}Ft.create=(s,e)=>new Ft({innerType:s,typeName:S.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...P(e)});class hi extends A{_parse(e){if(this._getType(e)!==C.nan){const i=this._getOrReturnCtx(e);return y(i,{code:m.invalid_type,expected:C.nan,received:i.parsedType}),E}return{status:"valid",value:e.data}}}hi.create=s=>new hi({typeName:S.ZodNaN,...P(s)});class Vi extends A{_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 zt extends A{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.common.async)return(async()=>{const r=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return r.status==="aborted"?E:r.status==="dirty"?(t.dirty(),ot(r.value)):this._def.out._parseAsync({data:r.value,path:i.path,parent:i})})();{const n=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return n.status==="aborted"?E:n.status==="dirty"?(t.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:i.path,parent:i})}}static create(e,t){return new zt({in:e,out:t,typeName:S.ZodPipeline})}}class Dt extends A{_parse(e){const t=this._def.innerType._parse(e),i=n=>(Ze(n)&&(n.value=Object.freeze(n.value)),n);return St(t)?t.then(n=>i(n)):i(t)}unwrap(){return this._def.innerType}}Dt.create=(s,e)=>new Dt({innerType:s,typeName:S.ZodReadonly,...P(e)}),H.lazycreate;var S;(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"})(S||(S={}));const X=ge.create,k=Ke.create;hi.create,je.create,si.create,ht.create,ni.create,Et.create,It.create,ri.create,Xe.create,Se.create,ai.create,ce.create;const L=H.create;H.strictCreate;const Dn=Pt.create;oi.create,At.create,we.create,Ot.create,li.create,qe.create,dt.create,Mt.create;const Fe=Rt.create,_e=Be.create;Bt.create,ut.create,Ce.create,xe.create,Le.create,Ce.createWithPreprocess,zt.create;const Hn=_e(["linear","bezier","constant"]),Vn=_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"]),ze=L({from:k(),to:k(),start:k().min(0),length:k().positive(),interpolation:Hn.optional(),easing:Vn.optional()}),Nn=X().url("Invalid audio url format."),Un=ze.extend({from:k().min(0).max(1),to:k().min(0).max(1)}).array().or(k().min(0).max(1)),Ni=L({type:Fe("audio"),src:Nn,trim:k().optional(),volume:Un.optional()}),Wn=_e(["top","topRight","right","bottomRight","bottom","bottomLeft","left","topLeft","center"]),Ui=L({type:Fe("html"),html:X(),css:X(),width:k().positive().optional(),height:k().positive().optional(),position:Wn.optional()}),Gn=X().url("Invalid image url format."),$n=L({top:k().min(0).optional(),right:k().min(0).optional(),bottom:k().min(0).optional(),left:k().min(0).optional()}),Wi=L({type:Fe("image"),src:Gn,crop:$n.optional()}),Zn=X().url("Invalid luma url format."),Gi=L({type:Fe("luma"),src:Zn}),$i=X().regex(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})|transparent$/,"Invalid color format."),Zi=L({width:k().positive(),height:k().positive()}),Ki=L({radius:k().positive()}),ji=L({length:k().positive(),thickness:k().positive()}),Kn=L({color:$i,opacity:k().min(0).max(1)}),jn=L({color:$i,width:k().positive()}),Xi=L({type:Fe("shape"),width:k().positive().optional(),height:k().positive().optional(),shape:_e(["rectangle","circle","line"]),fill:Kn.optional(),stroke:jn.optional(),rectangle:Zi.optional(),circle:Ki.optional(),line:ji.optional()}).refine(s=>s.shape==="rectangle"?Zi.safeParse(s.rectangle):s.shape==="circle"?Ki.safeParse(s.circle):s.shape==="line"?ji.safeParse(s.line):!1),di=X().regex(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})|transparent$/,"Invalid color format."),Xn=L({color:di.optional(),family:X().optional(),size:k().positive().optional(),weight:k().optional(),lineHeight:k().optional()}),Yn=L({horizontal:_e(["left","center","right"]).optional(),vertical:_e(["top","center","bottom"]).optional()}),qn=L({color:di,opacity:k().min(0).max(1)}),Qn=L({width:k().positive(),color:di}),Yi=L({type:Fe("text"),text:X(),width:k().positive().optional(),height:k().positive().optional(),font:Xn.optional(),alignment:Yn.optional(),background:qn.optional(),stroke:Qn.optional()}),Jn=X().url("Invalid video url format."),er=L({top:k().min(0).optional(),right:k().min(0).optional(),bottom:k().min(0).optional(),left:k().min(0).optional()}),tr=ze.extend({from:k().min(0).max(1),to:k().min(0).max(1)}).array().or(k().min(0).max(1)),qi=L({type:Fe("video"),src:Jn,trim:k().optional(),crop:er.optional(),volume:tr.optional()}),ir=Dn([Yi,Xi,Ui,Wi,qi,Gi,Ni]).refine(s=>s.type==="text"?Yi.safeParse(s):s.type==="shape"?Xi.safeParse(s):s.type==="html"?Ui.safeParse(s):s.type==="image"?Wi.safeParse(s):s.type==="video"?qi.safeParse(s):s.type==="luma"?Gi.safeParse(s):s.type==="audio"?Ni.safeParse(s):!1),sr=_e(["topLeft","top","topRight","left","center","right","bottomLeft","bottom","bottomRight"]),nr=_e(["crop","cover","contain","none"]),Qe=k().min(-10).max(10).default(0),rr=ze.extend({from:Qe,to:Qe}).array().or(Qe),ar=ze.extend({from:Qe,to:Qe}).array().or(Qe),or=L({x:rr.default(0),y:ar.default(0)}),cr=ze.extend({from:k().min(0).max(1),to:k().min(0).max(1)}).array().or(k().min(0).max(1)),lr=ze.extend({from:k().min(0),to:k().min(0)}).array().or(k().min(0)),hr=L({angle:ze.extend({from:k(),to:k()}).array().or(k())}),dr=X(),Qi=X(),ur=L({in:Qi.optional(),out:Qi.optional()}),pr=L({rotate:hr.default({angle:0})}),Ji=L({asset:ir,start:k().min(0),length:k().positive(),position:sr.default("center").optional(),fit:nr.default("crop").optional(),offset:or.default({x:0,y:0}).optional(),opacity:cr.default(1).optional(),scale:lr.default(1).optional(),transform:pr.default({rotate:{angle:0}}).optional(),effect:dr.optional(),transition:ur.optional()});class fr{constructor(e,t){this.trackIdx=e,this.clip=t}name="addClip";addedPlayer;async execute(e){if(!e)return;const t=Ji.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 es{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(n=>{if(n.layer>=this.trackIdx){const r=1e5-n.layer*100,a=e.getContainer().getChildByLabel(`shotstack-track-${r}`,!1);a&&a.removeChild(n.getContainer()),n.layer+=1;const o=1e5-n.layer*100;let l=e.getContainer().getChildByLabel(`shotstack-track-${o}`,!1);l||(l=new f.Container({label:`shotstack-track-${o}`,zIndex:o}),e.getContainer().addChild(l)),l.addChild(n.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(n=>{n.layer>this.trackIdx&&(n.layer-=1)}),e.updateDuration()}}class mr{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 gr{constructor(e,t){this.trackIdx=e,this.clipIdx=t}name="deleteClip";deletedClip;execute(e){if(!e)return;const i=e.getClips().filter(n=>n.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 yr{constructor(e){this.trackIdx=e}name="deleteTrack";deletedClips=[];execute(e){if(!e)return;const t=e.getClips(),i=e.getTracks();this.deletedClips=t.filter(a=>a.layer===this.trackIdx+1).map(a=>({config:structuredClone(a.clipConfiguration)})),t.forEach((a,o)=>{a.layer===this.trackIdx+1&&(t[o].shouldDispose=!0)}),e.disposeClips(),i.splice(this.trackIdx,1);const n=e.getClips(),r=e.getContainer();n.forEach((a,o)=>{if(a.layer>this.trackIdx+1){r.getChildByLabel(`shotstack-track-${1e5-a.layer*100}`,!1)?.removeChild(a.getContainer()),n[o].layer-=1;const c=1e5-n[o].layer*100;let h=r.getChildByLabel(`shotstack-track-${c}`,!1);h||(h=new f.Container({label:`shotstack-track-${c}`,zIndex:c}),r.addChild(h)),h.addChild(n[o].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((n,r)=>{n.layer>=this.trackIdx+1&&(i[r].layer+=1)});for(const{config:n}of this.deletedClips){const r=e.createPlayerFromAssetType(n);r.layer=this.trackIdx+1,await e.addPlayer(this.trackIdx,r)}e.updateDuration()}}class wr{constructor(e,t){this.trackIndex=e,this.clipIndex=t}name="SelectClip";previousSelection=null;execute(e){const t=e.getSelectedClip();if(t){const n=e.findClipIndices(t);n&&(this.previousSelection=n)}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 Cr{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,r=e.getClips().filter(a=>a.layer===this.clip.layer).indexOf(this.clip);e.emitEvent("clip:updated",{previous:{clip:this.storedInitialConfig||this.initialClipConfig,trackIndex:t,clipIndex:r},current:{clip:this.storedFinalConfig||this.clip.clipConfiguration,trackIndex:t,clipIndex:r}})}undo(e){if(!e||!this.storedInitialConfig)return;e.restoreClipConfiguration(this.clip,this.storedInitialConfig),e.setUpdatedClip(this.clip);const t=this.clip.layer-1,r=e.getClips().filter(a=>a.layer===this.clip.layer).indexOf(this.clip);e.emitEvent("clip:updated",{previous:{clip:this.storedFinalConfig,trackIndex:t,clipIndex:r},current:{clip:this.storedInitialConfig,trackIndex:t,clipIndex:r}})}}class xr{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,n=i.start||0,r=i.length,a=.1,o=this.splitTime-n;if(o<=a||o>=r-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:n+o,length:r-o};if(i.asset&&(l.asset={...i.asset},c.asset={...i.asset}),i.asset&&(i.asset.type==="video"||i.asset.type==="audio")){const p=i.asset.trim||0;l.asset&&(l.asset.type==="video"||l.asset.type==="audio")&&(l.asset.trim=p),c.asset&&(c.asset.type==="video"||c.asset.type==="audio")&&(c.asset.trim=p+o)}if(Object.assign(t.clipConfiguration,l),t.reconfigureAfterRestore(),t.draw(),this.rightClipPlayer=e.createPlayerFromAssetType(c),!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 h=e.getTrack(this.trackIndex);if(!h)throw new Error("Invalid track index");h.splice(this.clipIndex+1,0,this.rightClipPlayer);const d=e.getClips(),u=d.indexOf(t);u!==-1&&d.splice(u+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(p=>{console.error("Failed to load split clip:",p)})}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 a=i.indexOf(this.rightClipPlayer);a!==-1&&i.splice(a,1)}const n=e.getClips(),r=n.indexOf(this.rightClipPlayer);r!==-1&&n.splice(r,1),e.queueDisposeClip(this.rightClipPlayer),this.rightClipPlayer=null}e.updateDuration(),e.emitEvent("timeline:updated",{current:e.getEditState()})}}}class vr{constructor(e,t,i){this.clip=e,this.newText=t,this.initialConfig=i;const{asset:n}=this.clip.clipConfiguration;this.previousText=n&&"text"in n?n.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,a=e.getClips().filter(o=>o.layer===this.clip.layer).indexOf(this.clip);e.emitEvent("clip:updated",{previous:{clip:this.initialConfig,trackIndex:i,clipIndex:a},current:{clip:this.clip.clipConfiguration,trackIndex:i,clipIndex:a}})}}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,a=e.getClips().filter(o=>o.layer===this.clip.layer).indexOf(this.clip);e.emitEvent("clip:updated",{previous:{clip:this.clip.clipConfiguration,trackIndex:i,clipIndex:a},current:{clip:this.initialConfig,trackIndex:i,clipIndex:a}})}}}class pt{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 Tr extends pt{registry;constructor(){super(),this.registry={}}}class Ht{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 Tr;async load(e,t){this.updateAssetLoadMetadata(e,"pending",0);try{if(await this.shouldUseSafariVideoLoader(t))return await this.loadVideoForSafari(e,t);const i=await f.Assets.load(t,n=>{this.updateAssetLoadMetadata(e,"loading",n)});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,n)=>i+this.loadTracker.registry[n].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 Ht.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(".")),n=Ht.VIDEO_MIME[i];return n?document.createElement("video").canPlayType(n)!=="":!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),n=typeof t=="object"?t.data??{}:{},r=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 f.VideoSource({resource:l,autoPlay:n.autoPlay??!1,...n});a(new f.Texture({source:c}))}catch(c){o(c)}},{once:!0}),l.addEventListener("error",()=>o(new Error("Video loading failed")),{once:!0}),this.updateAssetLoadMetadata(e,"loading",.5),l.src=i});return this.updateAssetLoadMetadata(e,"success",1),r}updateAssetLoadMetadata(e,t,i){this.loadTracker.registry[e]?(this.loadTracker.registry[e].progress=i,this.loadTracker.registry[e].status=t):this.loadTracker.registry[e]={progress:i,status:t};const n={...this.loadTracker.registry};this.loadTracker.emit("onAssetLoadInfoUpdated",{registry:n})}}class Vt{static Name="FontLoadParser";name;extension;validFontExtensions;woff2Decompressor;constructor(){this.name=Vt.Name,this.extension={type:[f.ExtensionType.LoadParser],priority:f.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 n=e.split("?")[0]?.split(".").pop()?.toLowerCase()??"",r=await fetch(e).then(u=>u.arrayBuffer());if(n!=="woff2"){const u=Pi.parse(new Uint8Array(r).buffer),p=u.names.fontFamily.en||u.names.fontFamily[Object.keys(u.names.fontFamily)[0]],g=new FontFace(p,`url(${e})`);return await g.load(),document.fonts.add(g),g}if(await this.loadWoff2Decompressor(),!this.woff2Decompressor)throw new Error("Cannot initialize Woff2 decompressor.");const a=this.woff2Decompressor.decompress(r),o=Pi.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),d=new FontFace(l,`url(${h})`);return await d.load(),document.fonts.add(d),d}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 br=L({clips:Ji.array()}),kr=X().url("Invalid image url format."),Sr=L({src:kr}),_r=L({background:X().optional(),fonts:Sr.array().optional(),tracks:br.array()}),Er=L({size:L({width:k().positive(),height:k().positive()}),fps:k().positive().optional(),format:X()}),Ir=L({timeline:_r,output:Er});class Je extends be{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 Ht,this.edit=null,this.tracks=[],this.clipsToDispose=[],this.clips=[],this.events=new pt,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 f.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 f.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=Ir.parse(e),this.backgroundColor=this.edit.timeline.background||"#000000",await Promise.all((this.edit.timeline.fonts??[]).map(async t=>{const i=t.src,n={src:i,loadParser:Vt.Name};return this.assetLoader.load(i,n)}));for(const[t,i]of this.edit.timeline.tracks.entries())for(const n of i.clips){const r=this.createPlayerFromAssetType(n);r.layer=t+1,await this.addPlayer(t,r)}this.updateTotalDuration()}getEdit(){const e=this.tracks.map((t,i)=>({clips:t.filter(r=>r&&!this.clipsToDispose.includes(r)).map(r=>r.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 fr(e,t);this.executeCommand(i)}getClip(e,t){const i=this.clips.filter(n=>n.layer===e+1);return t<0||t>=i.length?null:i[t].clipConfiguration}getPlayerClip(e,t){const i=this.clips.filter(n=>n.layer===e+1);return t<0||t>=i.length?null:i[t]}deleteClip(e,t){const i=new gr(e,t);this.executeCommand(i)}splitClip(e,t,i){const n=new xr(e,t,i);this.executeCommand(n)}addTrack(e,t){const i=new es(e);this.executeCommand(i),t?.clips?.forEach(n=>this.addClip(e,n))}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 yr(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 n=new Cr(e,t,i);this.executeCommand(n)}updateTextContent(e,t,i){const n=new vr(e,t,i);this.executeCommand(n)}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 f.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{f.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 n of i)e=Math.max(e,n.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)*Je.ZIndexPadding,n=`shotstack-track-${i}`;let r=this.getContainer().getChildByLabel(n,!1);r||(r=new f.Container({label:n,zIndex:i}),this.getContainer().addChild(r)),r.addChild(t.getContainer())}movePlayerToTrackContainer(e,t,i){if(t===i)return;const n=1e5-(t+1)*Je.ZIndexPadding,r=1e5-(i+1)*Je.ZIndexPadding,a=`shotstack-track-${n}`,o=`shotstack-track-${r}`,l=this.getContainer().getChildByLabel(a,!1);let c=this.getContainer().getChildByLabel(o,!1);c||(c=new f.Container({label:o,zIndex:r}),this.getContainer().addChild(c)),l&&l.removeChild(e.getContainer()),c.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 pn(this,e);break}case"shape":{t=new un(this,e);break}case"html":{t=new hn(this,e);break}case"image":{t=new dn(this,e);break}case"video":{t=new fn(this,e);break}case"audio":{t=new Ai(this,e);break}case"luma":{t=new Oi(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)*Je.ZIndexPadding,n=`shotstack-track-${i}`;let r=this.getContainer().getChildByLabel(n,!1);r||(r=new f.Container({label:n,zIndex:i}),this.getContainer().addChild(r)),r.addChild(t.getContainer());const a=t instanceof Oi;await t.load(),a&&r.setMask({mask:t.getMask(),inverse:!0}),this.updateTotalDuration()}selectClip(e,t){const i=new wr(e,t);this.executeCommand(i)}clearSelection(){const e=new mr;this.executeCommand(e)}isClipSelected(e,t){if(!this.selectedClip)return!1;const i=this.selectedClip.layer-1,n=this.tracks[i].indexOf(this.selectedClip);return e===i&&t===n}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 ft extends be{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 f.Graphics;e.fillStyle={color:"#424242",alpha:.5},e.rect(0,0,ft.Width,ft.Height),e.fill(),this.getContainer().addChild(e),this.background=e;const t=new f.Text;t.text="",t.style={fontFamily:"monospace",fontSize:14,fill:"#ffffff",wordWrap:!0,wordWrapWidth:ft.Width},this.getContainer().addChild(t),this.text=t}update(e,t){if(!this.text)return;const i=this.getMemoryInfo(),n=[`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=n.join(`
185
- `)}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 De{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 f.Application,this.edit=t,this.inspector=new ft,this.onTickBound=this.onTick.bind(this)}async load(){const e=document.querySelector(De.CanvasSelector);if(!e)throw new Error(`Shotstack canvas root element '${De.CanvasSelector}' not found.`);this.registerExtensions(),this.container=new f.Container,this.background=new f.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 n=Math.exp(-i.deltaY/100),r=this.currentZoom*n,a=this.currentZoom;this.currentZoom=Math.min(Math.max(r,this.minZoom),this.maxZoom);const o={x:this.application.canvas.width/2,y:this.application.canvas.height/2},l={x:t.position.x-o.x,y:t.position.y-o.y},c=this.currentZoom/a;t.position.x=o.x+l.x*c,t.position.y=o.y+l.y*c,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 n=this.edit.getContainer();n.scale.x=this.currentZoom,n.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(){De.extensionsRegistered||(f.extensions.add(new Tt),f.extensions.add(new Vt),De.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 f.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(De.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 Pr{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 Ar{name="export";clips=[];tracks=[];execute(e){this.clips=e.getClips(),this.tracks=e.getTracks()}getClips(){return this.clips}getTracks(){return this.tracks}}/*!
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}}/*!
186
188
  * Copyright (c) 2025-present, Vanilagy and contributors
187
189
  *
188
190
  * This Source Code Form is subject to the terms of the Mozilla Public
189
191
  * License, v. 2.0. If a copy of the MPL was not distributed with this
190
192
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
191
- */function x(s){if(!s)throw new Error("Assertion failed.")}const le=s=>s&&s[s.length-1],et=s=>s>=0&&s<2**32;class mt{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),n=(t&1<<i)>>i;return this.pos++,n}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 n=this.pos;n<i;n++){const r=Math.floor(n/8);let a=this.bytes[r];const o=7-(n&7);a&=~(1<<o),a|=(t&1<<i-n-1)>>i-n-1<<o,this.bytes[r]=a}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 mt(this.bytes);return e.pos=this.pos,e}}const T=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)},gt=s=>{const e=T(s);return e&1?e+1>>1:-(e>>1)},Ee=s=>s instanceof Uint8Array?s:s instanceof ArrayBuffer?new Uint8Array(s):new Uint8Array(s.buffer,s.byteOffset,s.byteLength),ts=s=>s instanceof DataView?s:s instanceof ArrayBuffer?new DataView(s):new DataView(s.buffer,s.byteOffset,s.byteLength);new TextDecoder;const He=new TextEncoder,ui=s=>Object.fromEntries(Object.entries(s).map(([e,t])=>[t,e])),Nt={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12};ui(Nt);const Ut={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pg:16,hlg:18};ui(Ut);const Wt={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9};ui(Wt);const Or=s=>!!s&&!!s.primaries&&!!s.transfer&&!!s.matrix&&s.fullRange!==void 0,Gt=s=>s instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&s instanceof SharedArrayBuffer||ArrayBuffer.isView(s);class is{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e;const t=new Promise(n=>{e=n}),i=this.currentPromise;return this.currentPromise=t,await i,e}}const Mr=()=>{let s,e;return{promise:new Promise((i,n)=>{s=i,e=n}),resolve:s,reject:e}},Rr=s=>{throw new Error(`Unexpected value: ${s}`)},ss=(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))},Br=(s,e,t,i)=>{t=Q(t,-8388608,8388607),t<0&&(t=t+16777216&16777215),ss(s,e,t,i)},Q=(s,e,t)=>Math.max(e,Math.min(t,s)),Lr="und",Fr=/^[a-z]{3}$/,zr=s=>Fr.test(s),Ie=1e6*(1+Number.EPSILON),Dr=(s,e)=>{const t=s<0?-1:1;s=Math.abs(s);let i=0,n=1,r=1,a=0,o=s;for(;;){const l=Math.floor(o),c=l*r+i,h=l*a+n;if(h>e)return{numerator:t*r,denominator:a};if(i=r,n=a,r=c,a=h,o=1/(o-l),!isFinite(o))break}return{numerator:t*r,denominator:a}};class ns{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}/*!
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")};/*!
192
194
  * Copyright (c) 2025-present, Vanilagy and contributors
193
195
  *
194
196
  * This Source Code Form is subject to the terms of the Mozilla Public
195
197
  * License, v. 2.0. If a copy of the MPL was not distributed with this
196
198
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
197
- */const Ve=["avc","hevc","vp9","av1","vp8"],he=["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"],rs=["aac","opus","mp3","vorbis","flac"],tt=[...rs,...he],$t=["webvtt"],as=[{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}],os=[{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}],cs=[{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}],ls=[{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}],Hr=(s,e,t,i)=>{if(s==="avc"){const r=Math.ceil(e/16)*Math.ceil(t/16),a=as.find(d=>r<=d.maxMacroblocks&&i<=d.maxBitrate)??le(as),o=a?a.level:0,l="64".padStart(2,"0"),c="00",h=o.toString(16).padStart(2,"0");return`avc1.${l}${c}${h}`}else if(s==="hevc"){const n="",a="6",o=e*t,l=os.find(h=>o<=h.maxPictureSize&&i<=h.maxBitrate)??le(os);return`hev1.${n}1.${a}.${l.tier}${l.level}.B0`}else{if(s==="vp8")return"vp8";if(s==="vp9"){const n="00",r=e*t,a=cs.find(l=>r<=l.maxPictureSize&&i<=l.maxBitrate)??le(cs);return`vp09.${n}.${a.level.toString().padStart(2,"0")}.08`}else if(s==="av1"){const r=e*t,a=ls.find(c=>r<=c.maxPictureSize&&i<=c.maxBitrate)??le(ls);return`av01.0.${a.level.toString().padStart(2,"0")}${a.tier}.08`}}throw new TypeError(`Unhandled codec '${s}'.`)},Vr=s=>{const e=s.split("."),n=(1<<7)+1,r=Number(e[1]),a=e[2],o=Number(a.slice(0,-1)),l=(r<<5)+o,c=a.slice(-1)==="H"?1:0,d=Number(e[3])===8?0:1,u=0,p=e[4]?Number(e[4]):0,g=e[5]?Number(e[5][0]):1,b=e[5]?Number(e[5][1]):1,_=e[5]?Number(e[5][2]):0,B=(c<<7)+(d<<6)+(u<<5)+(p<<4)+(g<<3)+(b<<2)+_;return[n,l,B,0]},Nr=(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(he.includes(s))return s;throw new TypeError(`Unhandled codec '${s}'.`)},hs=/^pcm-([usf])(\d+)+(be)?$/,it=s=>{if(x(he.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=hs.exec(s);x(e);let t;e[1]==="u"?t="unsigned":e[1]==="s"?t="signed":t="float";const i=Number(e[2])/8,n=e[3]!=="be",r=s==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:i,littleEndian:n,silentValue:r}},ds=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":hs.test(s)?s:s==="webvtt"?"webvtt":null,Ur=s=>s==="avc"?{avc:{format:"avc"}}:s==="hevc"?{hevc:{format:"hevc"}}:{},Wr=s=>s==="aac"?{aac:{format:"aac"}}:s==="opus"?{opus:{format:"opus"}}:{};class Zt{constructor(e){this._factor=e}_toVideoBitrate(e,t,i){const n=t*i,r={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2},a=1920*1080,o=3e6,l=Math.pow(n/a,.95),d=o*l*r[e]*this._factor;return Math.ceil(d/1e3)*1e3}_toAudioBitrate(e){if(he.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 n=i*this._factor;return e==="aac"?n=[96e3,128e3,16e4,192e3].reduce((a,o)=>Math.abs(o-n)<Math.abs(a-n)?o:a):e==="opus"||e==="vorbis"?n=Math.max(6e3,n):e==="mp3"&&(n=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((a,o)=>Math.abs(o-n)<Math.abs(a-n)?o:a)),Math.round(n/1e3)*1e3}}const Gr=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],$r=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,Zr=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,Kr=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,jr=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,Xr=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(!Gr.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&&!Gt(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(Nt);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(Ut);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 n=Object.keys(Wt);if(e.matrix!=null&&!n.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${n.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(!$r.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(!Zr.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(!Kr.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")&&!jr.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/.')},Yr=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm"],qr=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(!Yr.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&&!Gt(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"))&&!he.includes(s.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${he.join(", ")}).`)},Qr=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.")};/*!
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.")}};/*!
198
200
  * Copyright (c) 2025-present, Vanilagy and contributors
199
201
  *
200
202
  * This Source Code Form is subject to the terms of the Mozilla Public
201
203
  * License, v. 2.0. If a copy of the MPL was not distributed with this
202
204
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
203
- */class Jr{constructor(e){this.mutex=new is,this.firstMediaStreamTimestamp=null,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,t,i){t+=e.source._timestampOffset;let n=this.trackTimestampInfo.get(e);if(!n){if(!i)throw new Error("First frame must be a key frame.");n={maxTimestamp:t,maxTimestampBeforeLastKeyFrame:t},this.trackTimestampInfo.set(e,n)}if(t<0)throw new Error(`Timestamps must be non-negative (got ${t}s).`);if(i&&(n.maxTimestampBeforeLastKeyFrame=n.maxTimestamp),t<n.maxTimestampBeforeLastKeyFrame)throw new Error(`Timestamps cannot be smaller than the highest timestamp of the previous run (a run begins with a key frame and ends right before the next key frame). Got ${t}s, but highest timestamp is ${n.maxTimestampBeforeLastKeyFrame}s.`);return n.maxTimestamp=Math.max(n.maxTimestamp,t),t}}/*!
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.")};/*!
204
206
  * Copyright (c) 2025-present, Vanilagy and contributors
205
207
  *
206
208
  * This Source Code Form is subject to the terms of the Mozilla Public
207
209
  * License, v. 2.0. If a copy of the MPL was not distributed with this
208
210
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
209
- */const us=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,ea=s=>{const e=Math.floor(s/36e5),t=Math.floor(s%(60*60*1e3)/(60*1e3)),i=Math.floor(s%(60*1e3)/1e3),n=s%1e3;return e.toString().padStart(2,"0")+":"+t.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+"."+n.toString().padStart(3,"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}}/*!
210
212
  * Copyright (c) 2025-present, Vanilagy and contributors
211
213
  *
212
214
  * This Source Code Form is subject to the terms of the Mozilla Public
213
215
  * License, v. 2.0. If a copy of the MPL was not distributed with this
214
216
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
215
- */const pi=s=>{const e=[];let t=0;for(;t<s.length;){let i=-1,n=0;for(let r=t;r<s.length-3;r++){if(s[r]===0&&s[r+1]===0&&s[r+2]===1){i=r,n=3;break}if(r<s.length-4&&s[r]===0&&s[r+1]===0&&s[r+2]===0&&s[r+3]===1){i=r,n=4;break}}if(i===-1)break;if(t>0&&i>t){const r=s.subarray(t,i);r.length>0&&e.push(r)}t=i+n}if(t<s.length){const i=s.subarray(t);i.length>0&&e.push(i)}return e},fi=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)},ta=s=>{const t=pi(s);if(t.length===0)return null;let i=0;for(const o of t)i+=4+o.byteLength;const n=new Uint8Array(i),r=new DataView(n.buffer);let a=0;for(const o of t){const l=o.byteLength;r.setUint32(a,l,!1),a+=4,n.set(o,a),a+=o.byteLength}return n},mi=s=>s[0]&31,ia=s=>{try{const e=pi(s),t=e.filter(u=>mi(u)===7),i=e.filter(u=>mi(u)===8),n=e.filter(u=>mi(u)===13);if(t.length===0||i.length===0)return null;const r=t[0],a=new mt(fi(r));if(a.skipBits(1),a.skipBits(2),a.readBits(5)!==7)return console.error("Invalid SPS NAL unit type"),null;const l=a.readAlignedByte(),c=a.readAlignedByte(),h=a.readAlignedByte(),d={configurationVersion:1,avcProfileIndication:l,profileCompatibility:c,avcLevelIndication:h,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:i,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if(l===100||l===110||l===122||l===144){T(a);const u=T(a);u===3&&a.skipBits(1);const p=T(a),g=T(a);d.chromaFormat=u,d.bitDepthLumaMinus8=p,d.bitDepthChromaMinus8=g,d.sequenceParameterSetExt=n}return d}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}},sa=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 n=0;n<i;n++)e.push(t[n])}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 n=0;n<i;n++)e.push(t[n])}if(s.avcProfileIndication===100||s.avcProfileIndication===110||s.avcProfileIndication===122||s.avcProfileIndication===144){x(s.chromaFormat!==null),x(s.bitDepthLumaMinus8!==null),x(s.bitDepthChromaMinus8!==null),x(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 n=0;n<i;n++)e.push(t[n])}}return new Uint8Array(e)},ps=32,fs=33,ms=34,na=39,ra=40,st=s=>s[0]>>1&63,aa=s=>{try{const e=pi(s),t=e.filter(U=>st(U)===ps),i=e.filter(U=>st(U)===fs),n=e.filter(U=>st(U)===ms),r=e.filter(U=>st(U)===na||st(U)===ra);if(i.length===0||n.length===0)return null;const a=i[0],o=new mt(fi(a));o.skipBits(16),o.readBits(4);const l=o.readBits(3),c=o.readBits(1),{general_profile_space:h,general_tier_flag:d,general_profile_idc:u,general_profile_compatibility_flags:p,general_constraint_indicator_flags:g,general_level_idc:b}=oa(o,l);T(o);const _=T(o);_===3&&o.skipBits(1),T(o),T(o),o.readBits(1)&&(T(o),T(o),T(o),T(o));const B=T(o),N=T(o);T(o);const $=o.readBits(1)?0:l;for(let U=$;U<=l;U++)T(o),T(o),T(o);T(o),T(o),T(o),T(o),T(o),T(o),o.readBits(1)&&o.readBits(1)&&ca(o),o.skipBits(1),o.skipBits(1),o.readBits(1)&&(o.skipBits(4),o.skipBits(4),T(o),T(o),o.skipBits(1));const Z=T(o);if(la(o,Z),o.readBits(1)){const U=T(o);for(let z=0;z<U;z++)T(o),o.skipBits(1)}o.skipBits(1),o.skipBits(1);let fe=0;o.readBits(1)&&(fe=da(o,l));let se=0;if(n.length>0){const U=n[0],z=new mt(fi(U));z.skipBits(16),T(z),T(z),z.skipBits(1),z.skipBits(1),z.skipBits(3),z.skipBits(1),z.skipBits(1),T(z),T(z),gt(z),z.skipBits(1),z.skipBits(1),z.readBits(1)&&T(z),gt(z),gt(z),z.skipBits(1),z.skipBits(1),z.skipBits(1),z.skipBits(1);const Ge=z.readBits(1),vt=z.readBits(1);!Ge&&!vt?se=0:Ge&&!vt?se=2:!Ge&&vt?se=3:se=0}const me=[...t.length?[{arrayCompleteness:1,nalUnitType:ps,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:fs,nalUnits:i}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:ms,nalUnits:n}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:st(r[0]),nalUnits:r}]:[]];return{configurationVersion:1,generalProfileSpace:h,generalTierFlag:d,generalProfileIdc:u,generalProfileCompatibilityFlags:p,generalConstraintIndicatorFlags:g,generalLevelIdc:b,minSpatialSegmentationIdc:fe,parallelismType:se,chromaFormatIdc:_,bitDepthLumaMinus8:B,bitDepthChromaMinus8:N,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:l+1,temporalIdNested:c,lengthSizeMinusOne:3,arrays:me}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},oa=(s,e)=>{const t=s.readBits(2),i=s.readBits(1),n=s.readBits(5);let r=0;for(let h=0;h<32;h++)r=r<<1|s.readBits(1);const a=new Uint8Array(6);for(let h=0;h<6;h++)a[h]=s.readBits(8);const o=s.readBits(8),l=[],c=[];for(let h=0;h<e;h++)l.push(s.readBits(1)),c.push(s.readBits(1));if(e>0)for(let h=e;h<8;h++)s.skipBits(2);for(let h=0;h<e;h++)l[h]&&s.skipBits(88),c[h]&&s.skipBits(8);return{general_profile_space:t,general_tier_flag:i,general_profile_idc:n,general_profile_compatibility_flags:r,general_constraint_indicator_flags:a,general_level_idc:o}},ca=s=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!s.readBits(1))T(s);else{const n=Math.min(64,1<<4+(e<<1));e>1&&gt(s);for(let r=0;r<n;r++)gt(s)}},la=(s,e)=>{const t=[];for(let i=0;i<e;i++)t[i]=ha(s,i,e,t)},ha=(s,e,t,i)=>{let n=0,r=0,a=0;if(e!==0&&(r=s.readBits(1)),r){if(e===t){const l=T(s);a=e-(l+1)}else a=e-1;s.readBits(1),T(s);const o=i[a]??0;for(let l=0;l<=o;l++)s.readBits(1)||s.readBits(1);n=i[a]}else{const o=T(s),l=T(s);for(let c=0;c<o;c++)T(s),s.readBits(1);for(let c=0;c<l;c++)T(s),s.readBits(1);n=o+l}return n},da=(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)&&(T(s),T(s)),s.readBits(1),s.readBits(1),s.readBits(1),s.readBits(1)&&(T(s),T(s),T(s),T(s)),s.readBits(1)&&(s.readBits(32),s.readBits(32),s.readBits(1)&&T(s),s.readBits(1)&&ua(s,!0,e)),s.readBits(1)){s.readBits(1),s.readBits(1),s.readBits(1);const t=T(s);return T(s),T(s),T(s),T(s),t}return 0},ua=(s,e,t)=>{let i=!1,n=!1,r=!1;i=s.readBits(1)===1,n=s.readBits(1)===1,(i||n)&&(r=s.readBits(1)===1,r&&(s.readBits(8),s.readBits(5),s.readBits(1),s.readBits(5)),s.readBits(4),s.readBits(4),r&&s.readBits(4),s.readBits(5),s.readBits(5),s.readBits(5));for(let a=0;a<=t;a++){const o=s.readBits(1)===1;let l=!0;o||(l=s.readBits(1)===1);let c=!1;l?T(s):c=s.readBits(1)===1;let h=1;c||(h=T(s)+1),i&&gs(s,h,r),n&&gs(s,h,r)}},gs=(s,e,t)=>{for(let i=0;i<e;i++)T(s),T(s),t&&(T(s),T(s)),s.readBits(1)},pa=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 n=0;n<i.length;n++)e.push(i[n])}}return new Uint8Array(e)},fa=s=>{const e=ts(s),t=e.getUint8(9),i=e.getUint16(10,!0),n=e.getUint32(12,!0),r=e.getInt16(16,!0),a=e.getUint8(18);let o=null;return a&&(o=s.subarray(19,21+t)),{outputChannelCount:t,preSkip:i,inputSampleRate:n,outputGain:r,channelMappingFamily:a,channelMappingTable:o}};/*!
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={}));/*!
216
218
  * Copyright (c) 2025-present, Vanilagy and contributors
217
219
  *
218
220
  * This Source Code Form is subject to the terms of the Mozilla Public
219
221
  * License, v. 2.0. If a copy of the MPL was not distributed with this
220
222
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
221
- */class ys{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 r of e.children)r&&this.writeBox(r);const i=this.writer.getPos(),n=e.size??i-t;this.writer.seek(t),this.writeBoxHeader(e,n),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);x(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 M=new Uint8Array(8),de=new DataView(M.buffer),V=s=>[(s%256+256)%256],I=s=>(de.setUint16(0,s,!1),[M[0],M[1]]),ws=s=>(de.setInt16(0,s,!1),[M[0],M[1]]),Cs=s=>(de.setUint32(0,s,!1),[M[1],M[2],M[3]]),w=s=>(de.setUint32(0,s,!1),[M[0],M[1],M[2],M[3]]),Pe=s=>(de.setInt32(0,s,!1),[M[0],M[1],M[2],M[3]]),Ne=s=>(de.setUint32(0,Math.floor(s/2**32),!1),de.setUint32(4,s,!1),[M[0],M[1],M[2],M[3],M[4],M[5],M[6],M[7]]),xs=s=>(de.setInt16(0,2**8*s,!1),[M[0],M[1]]),ve=s=>(de.setInt32(0,2**16*s,!1),[M[0],M[1],M[2],M[3]]),gi=s=>(de.setInt32(0,2**30*s,!1),[M[0],M[1],M[2],M[3]]),yi=(s,e)=>{const t=[];let i=s;do{let n=i&127;i>>=7,t.length>0&&(n|=128),t.push(n)}while(i>0||e);return t.reverse()},Y=(s,e=!1)=>{const t=Array(s.length).fill(null).map((i,n)=>s.charCodeAt(n));return e&&t.push(0),t},wi=s=>{let e=null;for(const t of s)(!e||t.timestamp>e.timestamp)&&(e=t);return e},vs=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]},Ts=vs(0),bs=s=>[ve(s[0]),ve(s[1]),gi(s[2]),ve(s[3]),ve(s[4]),gi(s[5]),ve(s[6]),ve(s[7]),gi(s[8])],O=(s,e,t)=>({type:s,contents:e&&new Uint8Array(e.flat(10)),children:t}),F=(s,e,t,i,n)=>O(s,[V(e),Cs(t),i??[]],n),ma=s=>s.isQuickTime?O("ftyp",[Y("qt "),w(512),Y("qt ")]):s.fragmented?O("ftyp",[Y("iso5"),w(512),Y("iso5"),Y("iso6"),Y("mp41")]):O("ftyp",[Y("isom"),w(512),Y("isom"),s.holdsAvc?Y("avc1"):[],Y("mp41")]),Ci=s=>({type:"mdat",largeSize:s}),Kt=(s,e,t=!1)=>O("moov",void 0,[ga(e,s),...s.map(i=>ya(i,e)),t?Ya(s):null]),ga=(s,e)=>{const t=W(Math.max(0,...e.filter(a=>a.samples.length>0).map(a=>{const o=wi(a.samples);return o.timestamp+o.duration})),ki),i=Math.max(0,...e.map(a=>a.track.id))+1,n=!et(s)||!et(t),r=n?Ne:w;return F("mvhd",+n,0,[r(s),r(s),w(ki),r(t),ve(1),xs(1),Array(10).fill(0),bs(Ts),Array(24).fill(0),w(i)])},ya=(s,e)=>{const t=wo(s);return O("trak",void 0,[wa(s,e),Ca(s,e),t.name!==void 0?O("udta",void 0,[O("©nam",[...He.encode(t.name)])]):null])},wa=(s,e)=>{const t=wi(s.samples),i=W(t?t.timestamp+t.duration:0,ki),n=!et(e)||!et(i),r=n?Ne:w;let a;if(s.type==="video"){const o=s.track.metadata.rotation;a=vs(o??0)}else a=Ts;return F("tkhd",+n,3,[r(e),r(e),w(s.track.id),w(0),r(i),Array(8).fill(0),I(0),I(s.track.id),xs(s.type==="audio"?1:0),I(0),bs(a),ve(s.type==="video"?s.info.width:0),ve(s.type==="video"?s.info.height:0)])},Ca=(s,e)=>O("mdia",void 0,[xa(s,e),ba(!0,va[s.type],Ta[s.type]),ka(s)]),xa=(s,e)=>{const t=wi(s.samples),i=W(t?t.timestamp+t.duration:0,s.timescale),n=!et(e)||!et(i),r=n?Ne:w;let a=0;for(const o of s.track.metadata.languageCode??Lr)a<<=5,a+=o.charCodeAt(0)-96;return F("mdhd",+n,0,[r(e),r(e),w(s.timescale),r(i),I(a),I(0)])},va={video:"vide",audio:"soun",subtitle:"text"},Ta={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},ba=(s,e,t)=>F("hdlr",0,0,[Y("mhlr"),Y(e),w(0),w(0),w(0),Y(t,!0)]),ka=s=>O("minf",void 0,[Sa[s.type](),_a(),Pa(s)]),Sa={video:()=>F("vmhd",0,1,[I(0),I(0),I(0),I(0)]),audio:()=>F("smhd",0,0,[I(0),I(0)]),subtitle:()=>F("nmhd",0,0)},_a=()=>O("dinf",void 0,[Ea()]),Ea=()=>F("dref",0,0,[w(1)],[Ia()]),Ia=()=>F("url ",0,1),Pa=s=>{const e=s.compositionTimeOffsetTable.length>1||s.compositionTimeOffsetTable.some(t=>t.sampleCompositionTimeOffset!==0);return O("stbl",void 0,[Aa(s),Wa(s),e?ja(s):null,e?Xa(s):null,$a(s),Za(s),Ka(s),Ga(s)])},Aa=s=>{let e;if(s.type==="video")e=Oa(lo[s.track.source._codec],s);else if(s.type==="audio"){const t=Es(s.track.source._codec,s.muxer.isQuickTime);x(t),e=Fa(t,s)}else s.type==="subtitle"&&(e=Na(po[s.track.source._codec],s));return x(e),F("stsd",0,0,[w(1)],[e])},Oa=(s,e)=>O(s,[Array(6).fill(0),I(1),I(0),I(0),Array(12).fill(0),I(e.info.width),I(e.info.height),w(4718592),w(4718592),w(0),I(1),Array(32).fill(0),I(24),ws(65535)],[ho[e.track.source._codec](e),Or(e.info.decoderConfig.colorSpace)?Ma(e):null]),Ma=s=>O("colr",[Y("nclx"),I(Nt[s.info.decoderConfig.colorSpace.primaries]),I(Ut[s.info.decoderConfig.colorSpace.transfer]),I(Wt[s.info.decoderConfig.colorSpace.matrix]),V((s.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),Ra=s=>s.info.decoderConfig&&O("avcC",[...Ee(s.info.decoderConfig.description)]),Ba=s=>s.info.decoderConfig&&O("hvcC",[...Ee(s.info.decoderConfig.description)]),ks=s=>{if(!s.info.decoderConfig)return null;const e=s.info.decoderConfig,t=e.codec.split("."),i=Number(t[1]),n=Number(t[2]),r=Number(t[3]),a=t[4]?Number(t[4]):1,o=t[8]?Number(t[8]):Number(e.colorSpace?.fullRange??0),l=(r<<4)+(a<<1)+o,c=t[5]?Number(t[5]):e.colorSpace?.primaries?Nt[e.colorSpace.primaries]:2,h=t[6]?Number(t[6]):e.colorSpace?.transfer?Ut[e.colorSpace.transfer]:2,d=t[7]?Number(t[7]):e.colorSpace?.matrix?Wt[e.colorSpace.matrix]:2;return F("vpcC",1,0,[V(i),V(n),V(l),V(c),V(h),V(d),I(0)])},La=s=>O("av1C",Vr(s.info.decoderConfig.codec)),Fa=(s,e)=>{let t=0,i,n=16;if(he.includes(e.track.source._codec)){const r=e.track.source._codec,{sampleSize:a}=it(r);n=8*a,n>16&&(t=1)}return t===0?i=[Array(6).fill(0),I(1),I(t),I(0),w(0),I(e.info.numberOfChannels),I(n),I(0),I(0),I(e.info.sampleRate<2**16?e.info.sampleRate:0),I(0)]:i=[Array(6).fill(0),I(1),I(t),I(0),w(0),I(e.info.numberOfChannels),I(Math.min(n,16)),I(0),I(0),I(e.info.sampleRate<2**16?e.info.sampleRate:0),I(0),w(1),w(n/8),w(e.info.numberOfChannels*n/8),w(2)],O(s,i,[uo(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null])},xi=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=[...V(e),...V(21),...Cs(0),...w(0),...w(0)];if(s.info.decoderConfig.description){const i=Ee(s.info.decoderConfig.description);t=[...t,...V(5),...yi(i.byteLength),...i]}return t=[...I(1),...V(0),...V(4),...yi(t.length),...t,...V(6),...V(1),...V(2)],t=[...V(3),...yi(t.length),...t],F("esds",0,0,t)},Ae=s=>O("wave",void 0,[za(s),Da(s),O("\0\0\0\0")]),za=s=>O("frma",[Y(Es(s.track.source._codec,s.muxer.isQuickTime))]),Da=s=>{const{littleEndian:e}=it(s.track.source._codec);return O("enda",[I(+e)])},Ha=s=>{let e=s.info.numberOfChannels,t=3840,i=s.info.sampleRate,n=0,r=0,a=new Uint8Array(0);const o=s.info.decoderConfig?.description;if(o){x(o.byteLength>=18);const l=Ee(o),c=fa(l);e=c.outputChannelCount,t=c.preSkip,i=c.inputSampleRate,n=c.outputGain,r=c.channelMappingFamily,c.channelMappingTable&&(a=c.channelMappingTable)}return O("dOps",[V(0),V(e),I(t),w(i),ws(n),V(r),...a])},Va=s=>{const e=s.info.decoderConfig?.description;x(e);const t=Ee(e);return F("dfLa",0,0,[...t.subarray(4)])},ue=s=>{const{littleEndian:e,sampleSize:t}=it(s.track.source._codec),i=+e;return F("pcmC",0,0,[V(i),V(8*t)])},Na=(s,e)=>O(s,[Array(6).fill(0),I(1)],[fo[e.track.source._codec](e)]),Ua=s=>O("vttC",[...He.encode(s.info.config.description)]),Wa=s=>F("stts",0,0,[w(s.timeToSampleTable.length),s.timeToSampleTable.map(e=>[w(e.sampleCount),w(e.sampleDelta)])]),Ga=s=>{if(s.samples.every(t=>t.type==="key"))return null;const e=[...s.samples.entries()].filter(([,t])=>t.type==="key");return F("stss",0,0,[w(e.length),e.map(([t])=>w(t+1))])},$a=s=>F("stsc",0,0,[w(s.compactlyCodedChunkTable.length),s.compactlyCodedChunkTable.map(e=>[w(e.firstChunk),w(e.samplesPerChunk),w(1)])]),Za=s=>{if(s.type==="audio"&&s.info.requiresPcmTransformation){const{sampleSize:e}=it(s.track.source._codec);return F("stsz",0,0,[w(e*s.info.numberOfChannels),w(s.samples.reduce((t,i)=>t+W(i.duration,s.timescale),0))])}return F("stsz",0,0,[w(0),w(s.samples.length),s.samples.map(e=>w(e.size))])},Ka=s=>s.finalizedChunks.length>0&&le(s.finalizedChunks).offset>=2**32?F("co64",0,0,[w(s.finalizedChunks.length),s.finalizedChunks.map(e=>Ne(e.offset))]):F("stco",0,0,[w(s.finalizedChunks.length),s.finalizedChunks.map(e=>w(e.offset))]),ja=s=>F("ctts",1,0,[w(s.compositionTimeOffsetTable.length),s.compositionTimeOffsetTable.map(e=>[w(e.sampleCount),Pe(e.sampleCompositionTimeOffset)])]),Xa=s=>{let e=1/0,t=-1/0,i=1/0,n=-1/0;x(s.compositionTimeOffsetTable.length>0),x(s.samples.length>0);for(let a=0;a<s.compositionTimeOffsetTable.length;a++){const o=s.compositionTimeOffsetTable[a];e=Math.min(e,o.sampleCompositionTimeOffset),t=Math.max(t,o.sampleCompositionTimeOffset)}for(let a=0;a<s.samples.length;a++){const o=s.samples[a];i=Math.min(i,W(o.timestamp,s.timescale)),n=Math.max(n,W(o.timestamp+o.duration,s.timescale))}const r=Math.max(-e,0);return n>=2**31?null:F("cslg",0,0,[Pe(r),Pe(e),Pe(t),Pe(i),Pe(n)])},Ya=s=>O("mvex",void 0,s.map(qa)),qa=s=>F("trex",0,0,[w(s.track.id),w(1),w(0),w(0),w(0)]),Ss=(s,e)=>O("moof",void 0,[Qa(s),...e.map(Ja)]),Qa=s=>F("mfhd",0,0,[w(s)]),_s=s=>{let e=0,t=0;const i=0,n=0,r=s.type==="delta";return t|=+r,r?e|=1:e|=2,e<<24|t<<16|i<<8|n},Ja=s=>O("traf",void 0,[eo(s),to(s),io(s)]),eo=s=>{x(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:_s(t)};return F("tfhd",0,e,[w(s.track.id),w(i.duration),w(i.size),w(i.flags)])},to=s=>(x(s.currentChunk),F("tfdt",1,0,[Ne(W(s.currentChunk.startTimestamp,s.timescale))])),io=s=>{x(s.currentChunk);const e=s.currentChunk.samples.map(b=>b.timescaleUnitsToNextSample),t=s.currentChunk.samples.map(b=>b.size),i=s.currentChunk.samples.map(_s),n=s.currentChunk.samples.map(b=>W(b.timestamp-b.decodeTimestamp,s.timescale)),r=new Set(e),a=new Set(t),o=new Set(i),l=new Set(n),c=o.size===2&&i[0]!==i[1],h=r.size>1,d=a.size>1,u=!c&&o.size>1,p=l.size>1||[...l].some(b=>b!==0);let g=0;return g|=1,g|=4*+c,g|=256*+h,g|=512*+d,g|=1024*+u,g|=2048*+p,F("trun",1,g,[w(s.currentChunk.samples.length),w(s.currentChunk.offset-s.currentChunk.moofOffset||0),c?w(i[0]):[],s.currentChunk.samples.map((b,_)=>[h?w(e[_]):[],d?w(t[_]):[],u?w(i[_]):[],p?Pe(n[_]):[]])])},so=s=>O("mfra",void 0,[...s.map(no),ro()]),no=(s,e)=>F("tfra",1,0,[w(s.track.id),w(63),w(s.finalizedChunks.length),s.finalizedChunks.map(i=>[Ne(W(i.samples[0].timestamp,s.timescale)),Ne(i.moofOffset),w(e+1),w(1),w(1)])]),ro=()=>F("mfro",0,0,[w(0)]),ao=()=>O("vtte"),oo=(s,e,t,i,n)=>O("vttc",void 0,[n!==null?O("vsid",[Pe(n)]):null,t!==null?O("iden",[...He.encode(t)]):null,e!==null?O("ctim",[...He.encode(ea(e))]):null,i!==null?O("sttg",[...He.encode(i)]):null,O("payl",[...He.encode(s)])]),co=s=>O("vtta",[...He.encode(s)]),lo={avc:"avc1",hevc:"hvc1",vp8:"vp08",vp9:"vp09",av1:"av01"},ho={avc:Ra,hevc:Ba,vp8:ks,vp9:ks,av1:La},Es=(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"}},uo=(s,e)=>{switch(s){case"aac":return xi;case"mp3":return xi;case"opus":return Ha;case"vorbis":return xi;case"flac":return Va}if(e)switch(s){case"pcm-s24":return Ae;case"pcm-s24be":return Ae;case"pcm-s32":return Ae;case"pcm-s32be":return Ae;case"pcm-f32":return Ae;case"pcm-f32be":return Ae;case"pcm-f64":return Ae;case"pcm-f64be":return Ae}else switch(s){case"pcm-s16":return ue;case"pcm-s16be":return ue;case"pcm-s24":return ue;case"pcm-s24be":return ue;case"pcm-s32":return ue;case"pcm-s32be":return ue;case"pcm-f32":return ue;case"pcm-f32be":return ue;case"pcm-f64":return ue;case"pcm-f64be":return ue}return null},po={webvtt:"wvtt"},fo={webvtt:Ua};/*!
223
+ */const $l=[],Dl=[];/*!
222
224
  * Copyright (c) 2025-present, Vanilagy and contributors
223
225
  *
224
226
  * This Source Code Form is subject to the terms of the Mozilla Public
225
227
  * License, v. 2.0. If a copy of the MPL was not distributed with this
226
228
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
227
- */class mo{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 n=this.trackedWrites.byteLength;for(;n<i;)n*=2;if(n!==this.trackedWrites.byteLength){const r=new Uint8Array(n);r.set(this.trackedWrites,0),this.trackedWrites=r}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 vi=2**16,Ti=2**32;class Is extends mo{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(vi,{maxByteLength:Ti})}catch{this.buffer=new ArrayBuffer(vi),this.supportsResize=!1}else this.buffer=new ArrayBuffer(vi);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>Ti)throw new Error(`ArrayBuffer exceeded maximum size of ${Ti} bytes. Please consider using another target.`);if(this.supportsResize)this.buffer.resize(t);else{const i=new ArrayBuffer(t),n=new Uint8Array(i);n.set(this.bytes,0),this.buffer=i,this.bytes=n}}}write(e){this.maybeTrackWrites(e),this.ensureSize(this.pos+e.byteLength),this.bytes.set(e,this.pos),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)}}/*!
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)}}/*!
228
230
  * Copyright (c) 2025-present, Vanilagy and contributors
229
231
  *
230
232
  * This Source Code Form is subject to the terms of the Mozilla Public
231
233
  * License, v. 2.0. If a copy of the MPL was not distributed with this
232
234
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
233
- */class Ps{constructor(){this._output=null}}class As extends Ps{constructor(){super(...arguments),this.buffer=null}_createWriter(){return new Is(this)}}/*!
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};/*!
234
236
  * Copyright (c) 2025-present, Vanilagy and contributors
235
237
  *
236
238
  * This Source Code Form is subject to the terms of the Mozilla Public
237
239
  * License, v. 2.0. If a copy of the MPL was not distributed with this
238
240
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
239
- */const go=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};/*!
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;/*!
240
242
  * Copyright (c) 2025-present, Vanilagy and contributors
241
243
  *
242
244
  * This Source Code Form is subject to the terms of the Mozilla Public
243
245
  * License, v. 2.0. If a copy of the MPL was not distributed with this
244
246
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
245
- */const bi=8,Os=16;/*!
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};/*!
246
248
  * Copyright (c) 2025-present, Vanilagy and contributors
247
249
  *
248
250
  * This Source Code Form is subject to the terms of the Mozilla Public
249
251
  * License, v. 2.0. If a copy of the MPL was not distributed with this
250
252
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
251
- */const ki=1e3,yo=2082844800,wo=s=>{const e={},t=s.track;return t.metadata.name!==void 0&&(e.name=t.metadata.name),e},W=(s,e,t=!0)=>{const i=s*e;return t?Math.round(i):i};class Co extends Jr{constructor(e,t){super(e),this.auxTarget=new As,this.auxWriter=this.auxTarget._createWriter(),this.auxBoxWriter=new ys(this.auxWriter),this.mdat=null,this.trackDatas=[],this.allTracksKnown=Mr(),this.creationTime=Math.floor(Date.now()/1e3)+yo,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.format=t,this.writer=e._writer,this.boxWriter=new ys(this.writer),this.isQuickTime=t instanceof Fs;const i=this.writer instanceof Is?"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(ma({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented})),this.format._options.onFtyp){const{data:i,start:n}=this.writer.stopTrackingWrites();this.format._options.onFtyp(i,n)}this.fastStart==="in-memory"?this.mdat=Ci(!1):this.isFragmented||(this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=Ci(!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 go({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 n=this.trackDatas.find(c=>c.track===e);if(n)return n;Xr(i),x(i),x(i.decoderConfig);const r={...i.decoderConfig};x(r.codedWidth!==void 0),x(r.codedHeight!==void 0);let a=!1;if(e.source._codec==="avc"&&!r.description){const c=ia(t.data);if(!c)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.");r.description=sa(c),a=!0}else if(e.source._codec==="hevc"&&!r.description){const c=aa(t.data);if(!c)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.");r.description=pa(c),a=!0}const o=Dr(1/(e.metadata.frameRate??57600),1e6).denominator,l={muxer:this,track:e,type:"video",info:{width:r.codedWidth,height:r.codedHeight,decoderConfig:r,requiresAnnexBTransformation:a},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(l),this.trackDatas.sort((c,h)=>c.track.id-h.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),l}getAudioTrackData(e,t){const i=this.trackDatas.find(r=>r.track===e);if(i)return i;qr(t),x(t),x(t.decoderConfig);const n={muxer:this,track:e,type:"audio",info:{numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate,decoderConfig:t.decoderConfig,requiresPcmTransformation:!this.isFragmented&&he.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(n),this.trackDatas.sort((r,a)=>r.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}getSubtitleTrackData(e,t){const i=this.trackDatas.find(r=>r.track===e);if(i)return i;Qr(t),x(t),x(t.config);const n={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(n),this.trackDatas.sort((r,a)=>r.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}async addEncodedVideoPacket(e,t,i){const n=await this.mutex.acquire();try{const r=this.getVideoTrackData(e,t,i);let a=t.data;if(r.info.requiresAnnexBTransformation){const c=ta(a);if(!c)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.");a=c}const o=this.validateAndNormalizeTimestamp(r.track,t.timestamp,t.type==="key"),l=this.createSampleForTrack(r,a,o,t.duration,t.type);await this.registerSample(r,l)}finally{n()}}async addEncodedAudioPacket(e,t,i){const n=await this.mutex.acquire();try{const r=this.getAudioTrackData(e,i),a=this.validateAndNormalizeTimestamp(r.track,t.timestamp,t.type==="key"),o=this.createSampleForTrack(r,t.data,a,t.duration,t.type);r.info.requiresPcmTransformation&&await this.maybePadWithSilence(r,a),await this.registerSample(r,o)}finally{n()}}async maybePadWithSilence(e,t){const i=le(e.samples),n=i?i.timestamp+i.duration:0,r=t-n,a=W(r,e.timescale);if(a>0){const{sampleSize:o,silentValue:l}=it(e.info.decoderConfig.codec),c=a*e.info.numberOfChannels,h=new Uint8Array(o*c).fill(l),d=this.createSampleForTrack(e,new Uint8Array(h.buffer),n,r,"key");await this.registerSample(e,d)}}async addSubtitleCue(e,t,i){const n=await this.mutex.acquire();try{const r=this.getSubtitleTrackData(e,i);this.validateAndNormalizeTimestamp(r.track,t.timestamp,!0),e.source._codec==="webvtt"&&(r.cueQueue.push(t),await this.processWebVTTCues(r,t.timestamp))}finally{n()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){const i=new Set([]);for(const c of e.cueQueue)x(c.timestamp<=t),x(e.lastCueEndTimestamp<=c.timestamp+c.duration),i.add(Math.max(c.timestamp,e.lastCueEndTimestamp)),i.add(c.timestamp+c.duration);const n=[...i].sort((c,h)=>c-h),r=n[0],a=n[1]??r;if(t<a)break;if(e.lastCueEndTimestamp<r){this.auxWriter.seek(0);const c=ao();this.auxBoxWriter.writeBox(c);const h=this.auxWriter.getSlice(0,this.auxWriter.getPos()),d=this.createSampleForTrack(e,h,e.lastCueEndTimestamp,r-e.lastCueEndTimestamp,"key");await this.registerSample(e,d),e.lastCueEndTimestamp=r}this.auxWriter.seek(0);for(let c=0;c<e.cueQueue.length;c++){const h=e.cueQueue[c];if(h.timestamp>=a)break;us.lastIndex=0;const d=us.test(h.text),u=h.timestamp+h.duration;let p=e.cueToSourceId.get(h);if(p===void 0&&a<u&&(p=e.nextSourceId++,e.cueToSourceId.set(h,p)),h.notes){const b=co(h.notes);this.auxBoxWriter.writeBox(b)}const g=oo(h.text,d?r:null,h.identifier??null,h.settings??null,p??null);this.auxBoxWriter.writeBox(g),u===a&&e.cueQueue.splice(c--,1)}const o=this.auxWriter.getSlice(0,this.auxWriter.getPos()),l=this.createSampleForTrack(e,o,r,a-r,"key");await this.registerSample(e,l),e.lastCueEndTimestamp=a}}createSampleForTrack(e,t,i,n,r){return{timestamp:i,decodeTimestamp:i,duration:n,data:t,size:t.byteLength,type:r,timescaleUnitsToNextSample:W(n,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){let n=0;for(let r=0;r<e.timestampProcessingQueue.length;r++){const a=e.timestampProcessingQueue[r],o=W(a.duration,e.timescale);n+=o}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:n,sampleDelta:1});else{const r=le(e.timeToSampleTable);r.sampleCount+=n}e.timestampProcessingQueue.length=0;return}const i=e.timestampProcessingQueue.map(n=>n.timestamp).sort((n,r)=>n-r);for(let n=0;n<e.timestampProcessingQueue.length;n++){const r=e.timestampProcessingQueue[n];r.decodeTimestamp=i[n],!this.isFragmented&&e.lastTimescaleUnits===null&&(r.decodeTimestamp=0);const a=W(r.timestamp-r.decodeTimestamp,e.timescale),o=W(r.duration,e.timescale);if(e.lastTimescaleUnits!==null){x(e.lastSample);const l=W(r.decodeTimestamp,e.timescale,!1),c=Math.round(l-e.lastTimescaleUnits);if(x(c>=0),e.lastTimescaleUnits+=c,e.lastSample.timescaleUnitsToNextSample=c,!this.isFragmented){let h=le(e.timeToSampleTable);if(x(h),h.sampleCount===1){h.sampleDelta=c;const u=e.timeToSampleTable[e.timeToSampleTable.length-2];u&&u.sampleDelta===c&&(u.sampleCount++,e.timeToSampleTable.pop(),h=u)}else h.sampleDelta!==c&&(h.sampleCount--,e.timeToSampleTable.push(h={sampleCount:1,sampleDelta:c}));h.sampleDelta===o?h.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:o});const d=le(e.compositionTimeOffsetTable);x(d),d.sampleCompositionTimeOffset===a?d.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a})}}else e.lastTimescaleUnits=W(r.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a}));e.lastSample=r}if(e.timestampProcessingQueue.length=0,x(e.lastSample),x(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){x(t.type==="key");const n=W(t.timestamp,e.timescale,!1),r=Math.round(n-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=r}}async registerSample(e,t){t.type==="key"&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){this.isFragmented||e.samples.push(t);let i=!1;if(!e.currentChunk)i=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);const n=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){const r=this.trackDatas.every(a=>{if(e===a)return t.type==="key";const o=a.sampleQueue[0];return o?o.type==="key":a.track.source._closed});n>=this.minimumFragmentDuration&&r&&t.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=n>=.5}i&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null}),x(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(x(!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,n)=>i+W(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||le(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)x(i.data),this.writer.write(i.data),i.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(x(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let t=null,i=1/0;for(const r of this.trackDatas){if(!e&&r.sampleQueue.length===0&&!r.track.source._closed)break e;r.sampleQueue.length>0&&r.sampleQueue[0].timestamp<i&&(t=r,i=r.sampleQueue[0].timestamp)}if(!t)break;const n=t.sampleQueue.shift();await this.addSampleToTrack(t,n)}}async finalizeFragment(e=!0){x(this.isFragmented);const t=this.nextFragmentNumber++;if(t===1){this.format._options.onMoov&&this.writer.startTrackingWrites();const p=Kt(this.trackDatas,this.creationTime,!0);if(this.boxWriter.writeBox(p),this.format._options.onMoov){const{data:g,start:b}=this.writer.stopTrackingWrites();this.format._options.onMoov(g,b)}}const i=this.trackDatas.filter(p=>p.currentChunk),n=Ss(t,i),r=this.writer.getPos(),a=r+this.boxWriter.measureBox(n);let o=a+bi,l=1/0;for(const p of i){p.currentChunk.offset=o,p.currentChunk.moofOffset=r;for(const g of p.currentChunk.samples)o+=g.size;l=Math.min(l,p.currentChunk.startTimestamp)}const c=o-a,h=c>=2**32;if(h)for(const p of i)p.currentChunk.offset+=Os-bi;this.format._options.onMoof&&this.writer.startTrackingWrites();const d=Ss(t,i);if(this.boxWriter.writeBox(d),this.format._options.onMoof){const{data:p,start:g}=this.writer.stopTrackingWrites();this.format._options.onMoof(p,g,l)}x(this.writer.getPos()===a),this.format._options.onMdat&&this.writer.startTrackingWrites();const u=Ci(h);u.size=c,this.boxWriter.writeBox(u),this.writer.seek(a+(h?Os:bi));for(const p of i)for(const g of p.currentChunk.samples)this.writer.write(g.data),g.data=null;if(this.format._options.onMdat){const{data:p,start:g}=this.writer.stopTrackingWrites();this.format._options.onMdat(p,g)}for(const p of i)p.finalizedChunks.push(p.currentChunk),this.finalizedChunks.push(p.currentChunk),p.currentChunk=null;e&&await this.writer.flush()}async onTrackClose(e){const t=await this.mutex.acquire();if(e.type==="subtitle"&&e.source._codec==="webvtt"){const i=this.trackDatas.find(n=>n.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"){x(this.mdat);let t;for(let n=0;n<2;n++){const r=Kt(this.trackDatas,this.creationTime),a=this.boxWriter.measureBox(r);t=this.boxWriter.measureBox(this.mdat);let o=this.writer.getPos()+a+t;for(const l of this.finalizedChunks){l.offset=o;for(const{data:c}of l.samples)x(c),o+=c.byteLength,t+=c.byteLength}if(o<2**32)break;t>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();const i=Kt(this.trackDatas,this.creationTime);if(this.boxWriter.writeBox(i),this.format._options.onMoov){const{data:n,start:r}=this.writer.stopTrackingWrites();this.format._options.onMoov(n,r)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=t,this.boxWriter.writeBox(this.mdat);for(const n of this.finalizedChunks)for(const r of n.samples)x(r.data),this.writer.write(r.data),r.data=null;if(this.format._options.onMdat){const{data:n,start:r}=this.writer.stopTrackingWrites();this.format._options.onMdat(n,r)}}else if(this.isFragmented){const t=this.writer.getPos(),i=so(this.trackDatas);this.boxWriter.writeBox(i);const n=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{x(this.mdat);const t=this.boxWriter.offsets.get(this.mdat);x(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:r,start:a}=this.writer.stopTrackingWrites();this.format._options.onMdat(r,a)}this.format._options.onMoov&&this.writer.startTrackingWrites();const n=Kt(this.trackDatas,this.creationTime);if(this.boxWriter.writeBox(n),this.format._options.onMoov){const{data:r,start:a}=this.writer.stopTrackingWrites();this.format._options.onMoov(r,a)}}e()}}/*!
253
+ */const fs=8,qr=16,Gl=Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"}));/*!
252
254
  * Copyright (c) 2025-present, Vanilagy and contributors
253
255
  *
254
256
  * This Source Code Form is subject to the terms of the Mozilla Public
255
257
  * License, v. 2.0. If a copy of the MPL was not distributed with this
256
258
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
257
- */const xo=[],vo=[];/*!
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")};/*!
258
260
  * Copyright (c) 2025-present, Vanilagy and contributors
259
261
  *
260
262
  * This Source Code Form is subject to the terms of the Mozilla Public
261
263
  * License, v. 2.0. If a copy of the MPL was not distributed with this
262
264
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
263
- */const Ms=new Uint8Array(0);class Oe{constructor(e,t,i,n,r=-1,a){if(this.data=e,this.type=t,this.timestamp=i,this.duration=n,this.sequenceNumber=r,e===Ms&&a===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(a===void 0&&(a=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(n)||n<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(r))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(a)||a<0)throw new TypeError("byteLength must be a non-negative integer.");this.byteLength=a}get isMetadataOnly(){return this.data===Ms}get microsecondTimestamp(){return Math.trunc(Ie*this.timestamp)}get microsecondDuration(){return Math.trunc(Ie*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})}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){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const t=new Uint8Array(e.byteLength);return e.copyTo(t),new Oe(t,e.type,e.timestamp/1e6,(e.duration??0)/1e6)}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 Oe(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}}/*!
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};/*!
264
266
  * Copyright (c) 2025-present, Vanilagy and contributors
265
267
  *
266
268
  * This Source Code Form is subject to the terms of the Mozilla Public
267
269
  * License, v. 2.0. If a copy of the MPL was not distributed with this
268
270
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
269
- */const To=s=>{let i=s,n=4096,r=0,a=12,o=0;for(i<0&&(i=-i,r=128),i+=33,i>8191&&(i=8191);(i&n)!==n&&a>=5;)n>>=1,a--;return o=i>>a-4&15,~(r|a-5<<4|o)&255},bo=s=>{let t=2048,i=0,n=11,r=0,a=s;for(a<0&&(a=-a,i=128),a>4095&&(a=4095);(a&t)!==t&&n>=5;)t>>=1,n--;return r=a>>(n===4?1:n-4)&15,(i|n-4<<4|r)^85};/*!
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)}}/*!
270
272
  * Copyright (c) 2025-present, Vanilagy and contributors
271
273
  *
272
274
  * This Source Code Form is subject to the terms of the Mozilla Public
273
275
  * License, v. 2.0. If a copy of the MPL was not distributed with this
274
276
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
275
- */class Ue{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(Ie*this.timestamp)}get microsecondDuration(){return Math.trunc(Ie*this.duration)}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=Ee(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.codedWidth,this.codedHeight=e.codedHeight,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 Ue(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*Ie),duration:Math.trunc((t.duration??0)*Ie)}),t);let i=0,n=0;if("naturalWidth"in e?(i=e.naturalWidth,n=e.naturalHeight):"videoWidth"in e?(i=e.videoWidth,n=e.videoHeight):"width"in e&&(i=Number(e.width),n=Number(e.height)),!i||!n)throw new TypeError("Could not determine dimensions.");const r=new OffscreenCanvas(i,n),a=r.getContext("2d",{alpha:!1,willReadFrequently:!0});x(a),a.drawImage(e,0,0),this._data=r,this.format="RGBX",this.codedWidth=i,this.codedHeight=n,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 x(this._data!==null),yt(this._data)?new Ue(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?new Ue(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 Ue(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||(yt(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(){if(this._closed)throw new Error("VideoSample is closed.");return x(this._data!==null),yt(this._data)?this._data.allocationSize():this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e){if(!Gt(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(this._closed)throw new Error("VideoSample is closed.");if(x(this._data!==null),yt(this._data))await this._data.copyTo(e);else if(this._data instanceof Uint8Array)Ee(e).set(this._data);else{const i=this._data.getContext("2d",{alpha:!1});x(i);const n=i.getImageData(0,0,this.codedWidth,this.codedHeight);Ee(e).set(n.data)}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return x(this._data!==null),yt(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,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}draw(e,t,i,n,r,a,o,l,c){let h=0,d=0,u=this.displayWidth,p=this.displayHeight,g=0,b=0,_=this.displayWidth,B=this.displayHeight;if(a!==void 0?(h=t,d=i,u=n,p=r,g=a,b=o,l!==void 0?(_=l,B=c):(_=u,B=p)):(g=t,b=i,n!==void 0&&(_=n,B=r)),!(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(h))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))throw new TypeError("sy must be a number.");if(!Number.isFinite(u)||u<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(p)||p<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(g))throw new TypeError("dx must be a number.");if(!Number.isFinite(b))throw new TypeError("dy must be a number.");if(!Number.isFinite(_)||_<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(B)||B<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");this.rotation===90?[h,d,u,p]=[d,this.codedHeight-h-u,p,u]:this.rotation===180?[h,d]=[this.codedWidth-h-u,this.codedHeight-d-p]:this.rotation===270&&([h,d,u,p]=[this.codedWidth-d-p,h,p,u]);const N=this.toCanvasImageSource();e.save();const J=g+_/2,$=b+B/2;e.translate(J,$),e.rotate(this.rotation*Math.PI/180);const Z=this.rotation%180===0?1:_/B;e.scale(1/Z,Z),e.drawImage(N,h,d,u,p,-_/2,-B/2,_,B),e.restore()}drawWithFit(e,t){const i=e.canvas.width,n=e.canvas.height,r=t.rotation??this.rotation;let a,o,l,c;if(t.fit==="fill")a=0,o=0,l=i,c=n;else{const[d,u]=r%180===0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth],p=t.fit==="contain"?Math.min(i/d,n/u):Math.max(i/d,n/u);l=d*p,c=u*p,a=(i-l)/2,o=(n-c)/2}const h=r%180===0?1:l/c;e.translate(i/2,n/2),e.rotate(r*Math.PI/180),e.scale(1/h,h),e.translate(-i/2,-n/2),e.drawImage(this.toCanvasImageSource(),a,o,l,c)}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(x(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}}const yt=s=>typeof VideoFrame<"u"&&s instanceof VideoFrame,Si=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class We{get microsecondTimestamp(){return Math.trunc(Ie*this.timestamp)}get microsecondDuration(){return Math.trunc(Ie*this.duration)}constructor(e){if(this._closed=!1,Ct(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(!Si.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/(wt(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 n=this.numberOfFrames*this.numberOfChannels*wt(this.format);if(i.byteLength<n)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&&!Si.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 n=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-i;if(n>this.numberOfFrames-i)throw new RangeError("frameCount out of range");const r=wt(t),a=jt(t);if(a&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!a&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(a?n:n*this.numberOfChannels)*r}copyTo(e,t){if(!Gt(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&&!Si.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:n,frameCount:r,frameOffset:a}=t,o=n??this.format;if(!o)throw new Error("Destination format not determined");const l=this.numberOfFrames,c=this.numberOfChannels,h=a??0;if(h>=l)throw new RangeError("frameOffset out of range");const d=r!==void 0?r:l-h;if(d>l-h)throw new RangeError("frameCount out of range");const u=wt(o),p=jt(o);if(p&&i>=c)throw new RangeError("planeIndex out of range");if(!p&&i!==0)throw new RangeError("planeIndex out of range");const b=(p?d:d*c)*u;if(e.byteLength<b)throw new RangeError("Destination buffer is too small");const _=ts(e),B=So(o);if(Ct(this._data))if(p)if(o==="f32-planar")this._data.copyTo(e,{planeIndex:i,frameOffset:h,frameCount:d,format:"f32-planar"});else{const N=new ArrayBuffer(d*4),J=new Float32Array(N);this._data.copyTo(J,{planeIndex:i,frameOffset:h,frameCount:d,format:"f32-planar"});const $=new DataView(N);for(let Z=0;Z<d;Z++){const fe=Z*u,se=$.getFloat32(Z*4,!0);B(_,fe,se)}}else{const N=c,J=new Float32Array(d);for(let $=0;$<N;$++){this._data.copyTo(J,{planeIndex:$,frameOffset:h,frameCount:d,format:"f32-planar"});for(let Z=0;Z<d;Z++){const se=(Z*N+$)*u;B(_,se,J[Z])}}}else{const N=this._data,J=new DataView(N.buffer,N.byteOffset,N.byteLength),$=this.format,Z=ko($),fe=wt($),se=jt($);for(let me=0;me<d;me++)if(p){const Me=me*u;let U;se?U=(i*l+(me+h))*fe:U=((me+h)*c+i)*fe;const z=Z(J,U);B(_,Me,z)}else for(let Me=0;Me<c;Me++){const z=(me*c+Me)*u;let Ge;se?Ge=(Me*l+(me+h))*fe:Ge=((me+h)*c+Me)*fe;const vt=Z(J,Ge);B(_,z,vt)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(Ct(this._data)){const e=new We(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new We({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(Ct(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(Ct(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(jt(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}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const i=48e3*5,n=e.numberOfChannels,r=e.sampleRate,a=e.length,o=Math.floor(i/n);let l=0,c=a;for(;c>0;){const h=Math.min(o,c),d=new Float32Array(n*h);for(let u=0;u<n;u++)e.copyFromChannel(d.subarray(u*h,(u+1)*h),u,l);yield new We({format:"f32-planar",sampleRate:r,numberOfFrames:h,numberOfChannels:n,timestamp:t+l/r,data:d}),l+=h,c-=h}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const i=48e3*5,n=e.numberOfChannels,r=e.sampleRate,a=e.length,o=Math.floor(i/n);let l=0,c=a;const h=[];for(;c>0;){const d=Math.min(o,c),u=new Float32Array(n*d);for(let g=0;g<n;g++)e.copyFromChannel(u.subarray(g*d,(g+1)*d),g,l);const p=new We({format:"f32-planar",sampleRate:r,numberOfFrames:d,numberOfChannels:n,timestamp:t+l/r,data:u});h.push(p),l+=d,c-=d}return h}}const wt=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")}},jt=s=>{switch(s){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},ko=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)}},So=s=>{switch(s){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,Q((i+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,Q(Math.round(i*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,Q(Math.round(i*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},Ct=s=>typeof AudioData<"u"&&s instanceof AudioData;/*!
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)}}/*!
276
278
  * Copyright (c) 2025-present, Vanilagy and contributors
277
279
  *
278
280
  * This Source Code Form is subject to the terms of the Mozilla Public
279
281
  * License, v. 2.0. If a copy of the MPL was not distributed with this
280
282
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
281
- */class Rs{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>Ve.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>tt.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>$t.includes(e))}_codecUnsupportedHint(e){return""}}class Bs extends Rs{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.fastStart!==void 0&&![!1,"in-memory","fragmented"].includes(e.fastStart))throw new TypeError('options.fastStart, when provided, must be false, "in-memory", 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.");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 Co(e,this)}}class Ls extends Bs{get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Ve,...rs,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...$t]}_codecUnsupportedHint(e){return new Fs().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class Fs extends Bs{get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...Ve,...tt]}_codecUnsupportedHint(e){return new Ls().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}/*!
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()}}/*!
282
284
  * Copyright (c) 2025-present, Vanilagy and contributors
283
285
  *
284
286
  * This Source Code Form is subject to the terms of the Mozilla Public
285
287
  * License, v. 2.0. If a copy of the MPL was not distributed with this
286
288
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
287
- */const _o=s=>{if(!s||typeof s!="object")throw new TypeError("Encoding config must be an object.");if(!Ve.includes(s.codec))throw new TypeError(`Invalid video codec '${s.codec}'. Must be one of: ${Ve.join(", ")}.`);if(!(s.bitrate instanceof Zt)&&(!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.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.");Eo(s.codec,s)},Eo=(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.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&&ds(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.")},Io=s=>{const e=s.bitrate instanceof Zt?s.bitrate._toVideoBitrate(s.codec,s.width,s.height):s.bitrate;return{codec:s.fullCodecString??Hr(s.codec,s.width,s.height,e),width:s.width,height:s.height,bitrate:e,bitrateMode:s.bitrateMode,framerate:s.framerate,latencyMode:s.latencyMode,hardwareAcceleration:s.hardwareAcceleration,scalabilityMode:s.scalabilityMode,contentHint:s.contentHint,...Ur(s.codec)}},Po=s=>{if(!s||typeof s!="object")throw new TypeError("Encoding config must be an object.");if(!tt.includes(s.codec))throw new TypeError(`Invalid audio codec '${s.codec}'. Must be one of: ${tt.join(", ")}.`);if(s.bitrate===void 0&&(!he.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 Zt)&&(!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.");Ao(s.codec,s)},Ao=(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&&ds(e.fullCodecString)!==s)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${s}).`)},Oo=s=>{const e=s.bitrate instanceof Zt?s.bitrate._toAudioBitrate(s.codec):s.bitrate;return{codec:s.fullCodecString??Nr(s.codec,s.numberOfChannels,s.sampleRate),numberOfChannels:s.numberOfChannels,sampleRate:s.sampleRate,bitrate:e,bitrateMode:s.bitrateMode,...Wr(s.codec)}};/*!
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.":""}}/*!
288
290
  * Copyright (c) 2025-present, Vanilagy and contributors
289
291
  *
290
292
  * This Source Code Form is subject to the terms of the Mozilla Public
291
293
  * License, v. 2.0. If a copy of the MPL was not distributed with this
292
294
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
293
- */class _i{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 zs extends _i{constructor(e){if(super(),this._connectedTrack=null,!Ve.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${Ve.join(", ")}.`);this._codec=e}}class Mo{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 ns,this.customEncoderQueueSize=0,this.encoderError=null}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 o=this.encodingConfig.sizeChangeBehavior??"deny";if(o!=="passThrough"){if(o==="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 l=!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),l=!0);const c=this.resizeCanvas.getContext("2d",{alpha:!1});x(c),l||c.clearRect(0,0,this.codedWidth,this.codedHeight),e.drawWithFit(c,{fit:o}),t&&e.close(),e=new Ue(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),x(this.encoderInitialized);const n=this.encodingConfig.keyFrameInterval??5,r=Math.floor(e.timestamp/n),a={...i,keyFrame:i?.keyFrame||n===0||r!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=r,this.customEncoder){this.customEncoderQueueSize++;const o=e.clone(),l=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(o,a)).then(()=>this.customEncoderQueueSize--).catch(c=>this.encoderError??=c).finally(()=>{o.close()});this.customEncoderQueueSize>=4&&await l}else{x(this.encoder);const o=e.toVideoFrame();this.encoder.encode(o,a),o.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(l=>this.encoder.addEventListener("dequeue",l,{once:!0}))}await this.muxer.mutex.currentPromise}finally{t&&e.close()}}async ensureEncoder(e){if(!this.encoder)return this.ensureEncoderPromise=(async()=>{const t=Io({width:e.codedWidth,height:e.codedHeight,...this.encodingConfig,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(t);const i=xo.find(n=>n.supports(this.encodingConfig.codec,t));if(i)this.customEncoder=new i,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=t,this.customEncoder.onPacket=(n,r)=>{if(!(n instanceof Oe))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(r!==void 0&&(!r||typeof r!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(n,r),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,n,r)},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw new Error("VideoEncoder is not supported by this browser.");if(!(await VideoEncoder.isConfigSupported(t)).supported)throw new Error(`This specific encoder configuration (${t.codec}, ${t.bitrate} bps, ${t.width}x${t.height}, hardware acceleration: ${t.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);this.encoder=new VideoEncoder({output:(r,a)=>{const o=Oe.fromEncodedChunk(r);this.encodingConfig.onEncodedPacket?.(o,a),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,o,a)},error:r=>{r.stack=new Error().stack,this.encoderError??=r}}),this.encoder.configure(t)}x(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(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.close()),this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.encoderError)throw this.encoderError}}class Ro extends zs{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.");_o(t),super(t.codec),this._encoder=new Mo(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 n=new Ue(this._canvas,{timestamp:e,duration:t});return this._encoder.add(n,!0,i)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class Ds extends _i{constructor(e){if(super(),this._connectedTrack=null,!tt.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${tt.join(", ")}.`);this._codec=e}}class Bo{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 ns,this.customEncoderQueueSize=0,this.encoderError=null}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),x(this.encoderInitialized),this.customEncoder){this.customEncoderQueueSize++;const i=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(i)).then(()=>this.customEncoderQueueSize--).catch(r=>this.encoderError??=r).finally(()=>{i.close()});this.customEncoderQueueSize>=4&&await n,await this.muxer.mutex.currentPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{x(this.encoder);const i=e.toAudioData();this.encoder.encode(i),i.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(n=>this.encoder.addEventListener("dequeue",n,{once:!0})),await this.muxer.mutex.currentPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){x(this.outputSampleSize),x(this.writeOutputValue);const{numberOfChannels:i,numberOfFrames:n,sampleRate:r,timestamp:a}=e,o=2048,l=[];for(let u=0;u<n;u+=o){const p=Math.min(o,e.numberOfFrames-u),g=p*i*this.outputSampleSize,b=new ArrayBuffer(g),_=new DataView(b);l.push({frameCount:p,view:_})}const c=e.allocationSize({planeIndex:0,format:"f32-planar"}),h=new Float32Array(c/Float32Array.BYTES_PER_ELEMENT);for(let u=0;u<i;u++){e.copyTo(h,{planeIndex:u,format:"f32-planar"});for(let p=0;p<l.length;p++){const{frameCount:g,view:b}=l[p];for(let _=0;_<g;_++)this.writeOutputValue(b,(_*i+u)*this.outputSampleSize,h[p*o+_])}}t&&e.close();const d={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:i,sampleRate:r}};for(let u=0;u<l.length;u++){const{frameCount:p,view:g}=l[u],b=g.buffer,_=u*o,B=new Oe(new Uint8Array(b),"key",a+_/r,p/r);this.encodingConfig.onEncodedPacket?.(B,d),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,B,d)}}ensureEncoder(e){if(!this.encoderInitialized)return this.ensureEncoderPromise=(async()=>{const{numberOfChannels:t,sampleRate:i}=e,n=Oo({numberOfChannels:t,sampleRate:i,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(n);const r=vo.find(a=>a.supports(this.encodingConfig.codec,n));if(r)this.customEncoder=new r,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=n,this.customEncoder.onPacket=(a,o)=>{if(!(a instanceof Oe))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?.(a,o),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,a,o)},await this.customEncoder.init();else if(he.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:(o,l)=>{const c=Oe.fromEncodedChunk(o);this.encodingConfig.onEncodedPacket?.(c,l),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,c,l)},error:o=>{o.stack=new Error().stack,this.encoderError??=o}}),this.encoder.configure(n)}x(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:n}=it(e);switch(this.outputSampleSize=i,i){case 1:t==="unsigned"?this.writeOutputValue=(r,a,o)=>r.setUint8(a,Q((o+1)*127.5,0,255)):t==="signed"?this.writeOutputValue=(r,a,o)=>{r.setInt8(a,Q(Math.round(o*128),-128,127))}:t==="ulaw"?this.writeOutputValue=(r,a,o)=>{const l=Q(Math.floor(o*32767),-32768,32767);r.setUint8(a,To(l))}:t==="alaw"?this.writeOutputValue=(r,a,o)=>{const l=Q(Math.floor(o*32767),-32768,32767);r.setUint8(a,bo(l))}:x(!1);break;case 2:t==="unsigned"?this.writeOutputValue=(r,a,o)=>r.setUint16(a,Q((o+1)*32767.5,0,65535),n):t==="signed"?this.writeOutputValue=(r,a,o)=>r.setInt16(a,Q(Math.round(o*32767),-32768,32767),n):x(!1);break;case 3:t==="unsigned"?this.writeOutputValue=(r,a,o)=>ss(r,a,Q((o+1)*83886075e-1,0,16777215),n):t==="signed"?this.writeOutputValue=(r,a,o)=>Br(r,a,Q(Math.round(o*8388607),-8388608,8388607),n):x(!1);break;case 4:t==="unsigned"?this.writeOutputValue=(r,a,o)=>r.setUint32(a,Q((o+1)*21474836475e-1,0,4294967295),n):t==="signed"?this.writeOutputValue=(r,a,o)=>r.setInt32(a,Q(Math.round(o*2147483647),-2147483648,2147483647),n):t==="float"?this.writeOutputValue=(r,a,o)=>r.setFloat32(a,o,n):x(!1);break;case 8:t==="float"?this.writeOutputValue=(r,a,o)=>r.setFloat64(a,o,n):x(!1);break;default:Rr(i),x(!1)}}async flushAndClose(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.close()),this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.encoderError)throw this.encoderError}}class Lo extends Ds{constructor(e){Po(e),super(e.codec),this._encoder=new Bo(this,e)}add(e){if(!(e instanceof We))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class Fo extends _i{constructor(e){if(super(),this._connectedTrack=null,!$t.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${$t.join(", ")}.`);this._codec=e}}/*!
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}}/*!
294
296
  * Copyright (c) 2025-present, Vanilagy and contributors
295
297
  *
296
298
  * This Source Code Form is subject to the terms of the Mozilla Public
297
299
  * License, v. 2.0. If a copy of the MPL was not distributed with this
298
300
  * file, You can obtain one at https://mozilla.org/MPL/2.0/.
299
- */const zo=["video","audio","subtitle"],Ei=s=>{if(!s||typeof s!="object")throw new TypeError("metadata must be an object.");if(s.languageCode!==void 0&&!zr(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.")};class Do{constructor(e){if(this.state="pending",this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new is,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof Rs))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof Ps))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 zs))throw new TypeError("source must be a VideoSource.");if(Ei(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 Ds))throw new TypeError("source must be an AudioSource.");Ei(t),this._addTrack("audio",e,t)}addSubtitleTrack(e,t={}){if(!(e instanceof Fo))throw new TypeError("source must be a SubtitleSource.");Ei(t),this._addTrack("subtitle",e,t)}_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 n=this.format.getSupportedTrackCounts(),r=this._tracks.reduce((c,h)=>c+(h.type===e?1:0),0),a=n[e].max;if(r===a)throw new Error(a===0?`${this.format._name} does not support ${e} tracks.`:`${this.format._name} does not support more than ${a} ${e} track${a===1?"":"s"}.`);const o=n.total.max;if(this._tracks.length===o)throw new Error(`${this.format._name} does not support more than ${o} tracks${o===1?"":"s"} in total.`);const l={id:this._tracks.length+1,output:this,type:e,source:t,metadata:i};if(l.type==="video"){const c=this.format.getSupportedVideoCodecs();if(c.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(l.source._codec));if(!c.includes(l.source._codec))throw new Error(`Codec '${l.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${c.map(h=>`'${h}'`).join(", ")}.`+this.format._codecUnsupportedHint(l.source._codec))}else if(l.type==="audio"){const c=this.format.getSupportedAudioCodecs();if(c.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(l.source._codec));if(!c.includes(l.source._codec))throw new Error(`Codec '${l.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${c.map(h=>`'${h}'`).join(", ")}.`+this.format._codecUnsupportedHint(l.source._codec))}else if(l.type==="subtitle"){const c=this.format.getSupportedSubtitleCodecs();if(c.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(l.source._codec));if(!c.includes(l.source._codec))throw new Error(`Codec '${l.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${c.map(h=>`'${h}'`).join(", ")}.`+this.format._codecUnsupportedHint(l.source._codec))}this._tracks.push(l),t._connectedTrack=l}async start(){const e=this.format.getSupportedTrackCounts();for(const i of zo){const n=this._tracks.reduce((a,o)=>a+(o.type===i?1:0),0),r=e[i].min;if(n<r)throw new Error(r===e[i].max?`${this.format._name} requires exactly ${r} ${i} track${r===1?"":"s"}.`:`${this.format._name} requires at least ${r} ${i} track${r===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 n=this._tracks.map(r=>r.source._start());await Promise.all(n),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 Ho{audioTracks=[];async setupAudioTracks(e,t){const i=this.findAudioPlayers(e);if(!i.length)return null;this.audioTracks=[];for(const r of i){const a=await this.processAudioTrack(r);a&&this.audioTracks.push(a)}if(!this.audioTracks.length)return null;const n=new Lo({codec:"aac",bitrate:128e3});return t.addAudioTrack(n),n}async processAudioSamples(e){if(!this.audioTracks?.length)return;const t=new AudioContext;for(const i of this.audioTracks){const n=await t.decodeAudioData(i.data.slice(0)),{numberOfChannels:r,sampleRate:a,length:o}=n,l=Math.min(o,Math.floor(a*i.duration/1e3)),c=new Float32Array(l*r);for(let h=0;h<r;h+=1){const d=n.getChannelData(h);for(let u=0;u<l;u+=1)c[u*r+h]=d[u]*i.volume}await e.add(new We({data:c,format:"f32",numberOfChannels:r,sampleRate:a,timestamp:i.start/1e3}))}this.audioTracks=[]}findAudioPlayers(e){const t=[];for(const i of e)for(const n of i)this.isAudioPlayer(n)&&!t.includes(n)&&t.push(n);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 Ai)return!0;if(!e||typeof e!="object")return!1;const t=e,i=t.constructor?.name==="AudioPlayer",a=t.clipConfiguration?.asset?.type==="audio";return i||a}}class Vo{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 n=Math.round(e/t*100);this.bar&&(this.bar.style.width=`${n}%`),this.percent&&(this.percent.innerText=`${n}%`),this.status&&i&&(this.status.innerText=i)}remove(){this.overlay?.remove(),this.overlay=null,this.bar=null,this.percent=null,this.status=null}}class Hs 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 Xt extends Error{constructor(e,t="unknown",i={},n){super(e),this.phase=t,this.context=i,this.name="ExportError",this.cause=n}}class No extends Xt{constructor(e,t){super(e,"initialization",{missingFeatures:t}),this.name="BrowserCompatibilityError"}}function Vs(s){if(!s||typeof s!="object")return!1;const e=s,t=e.constructor?.name==="VideoPlayer",n=e.texture?.source?.resource instanceof HTMLVideoElement;return t||n}class Uo{frameCache=new Hs(10);textureCache=new Hs(5);videoElements=new Map;extractionCanvas=null;extractionContext=null;async initialize(e){for(const t of e)if(Vs(t)){const i=t,n=i.texture?.source?.resource;n&&this.videoElements.set(this.getVideoKey(i),{element:n,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}`,n=this.frameCache.get(i);if(n)return n;const r=this.videoElements.get(e);if(!r||!this.extractionContext||!this.extractionCanvas)return null;try{const{element:a,player:o}=r,l=(t-(o.getStart?.()||0))/1e3+(o.clipConfiguration?.asset?.trim||0);await this.seekToTime(a,l);const c=a.videoWidth||a.width||1920,h=a.videoHeight||a.height||1080;this.extractionContext.clearRect(0,0,c,h),this.extractionContext.drawImage(a,0,0,c,h);const d=this.extractionContext.getImageData(0,0,c,h);return this.frameCache.set(i,d),d}catch(a){return console.warn("Failed to extract frame:",a),null}}async replaceVideoTexture(e,t){const i=await this.extractFrame(this.getVideoKey(e),t);if(!i)return;const n=`${this.getVideoKey(e)}-${t}`;let r=this.textureCache.get(n);if(!r){const a=document.createElement("canvas");a.width=i.width,a.height=i.height;const o=a.getContext("2d");o&&(o.putImageData(i,0,0),r=f.Texture.from(a),this.textureCache.set(n,r))}r&&e.texture&&(e.originalTextureSource||(e.originalTextureSource=e.texture.source,e.texture.source?.resource instanceof HTMLVideoElement&&(e.originalVideoElement=e.texture.source.resource)),e.texture=r,e.sprite?.texture&&(e.sprite.texture=r),e.lastReplacedTimestamp=t)}disableVideoPlayback(e){const t=[];for(const i of e)if(Vs(i)){const n=i;t.push(n),n.texture?.source?.resource instanceof HTMLVideoElement&&n.texture.source.resource.pause(),n.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 n=()=>{e.removeEventListener("seeked",n),setTimeout(i,1)};e.addEventListener("seeked",n),e.currentTime=t})}}class Wo{edit;canvas;app;isExporting=!1;videoProcessor=new Uo;audioProcessor=new Ho;progressUI=new Vo;exportCommand=new Ar;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 No("WebCodecs API not supported",["VideoEncoder"]);if(this.isExporting)throw new Xt("Export in progress","init");this.isExporting=!0;const i=this.saveEditState();this.edit.setExportMode(!0);try{this.progressUI.create(),this.canvas.pauseTicker();const n=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 r=new Do({format:new Ls,target:new As}),a=document.createElement("canvas");a.width=n.size.width,a.height=n.size.height;const o=a.getContext("2d");if(!o)throw new Error("No 2D context");const l=new Ro(a,{codec:"avc",bitrate:5e6});r.addVideoTrack(l),this.progressUI.update(15,100,"Audio...");const c=await this.audioProcessor.setupAudioTracks(this.exportCommand.getTracks(),r);await r.start(),c&&(this.progressUI.update(20,100,"Encoding audio..."),await this.audioProcessor.processAudioSamples(c)),this.progressUI.update(25,100,"Exporting..."),await this.processFrames(n,l,a,o),await r.finalize();const h=r.target.buffer;if(!h)throw new Error("No video data");const d=new Blob([h],{type:"video/mp4"}),u=URL.createObjectURL(d),p=document.createElement("a");p.href=u,p.download=e,p.click(),URL.revokeObjectURL(u),this.progressUI.update(100,100,"Complete!")}catch(n){throw n instanceof Xt?n:new Xt(`Export failed: ${n}`,"export")}finally{this.isExporting=!1,this.edit.setExportMode(!1),this.canvas.resumeTicker(),this.progressUI.remove(),this.restoreEditState(i)}}async processFrames(e,t,i,n){const r=this.edit.getContainer();this.edit.pause(),Object.assign(r.position,{x:0,y:0}),Object.assign(r.scale,{x:1,y:1}),r.visible=!0;const a=this.videoProcessor.disableVideoPlayback(this.exportCommand.getClips());for(let o=0;o<e.frames;o+=1){const l=o*e.frameDuration;this.edit.playbackTime=l;for(const d of this.exportCommand.getClips())d.update(0,0);for(const d of a){const u=d.getStart?.()||0,p=d.getEnd?.()||u+(d.getLength?.()||0);l>=u&&l<p&&await this.videoProcessor.replaceVideoTexture(d,l)}this.edit.draw(),this.app.renderer.render(this.app.stage);const c=this.app.renderer.extract.pixels({target:r,frame:new f.Rectangle(0,0,e.size.width,e.size.height)}),h=new ImageData(new Uint8ClampedArray(c.pixels),c.width,c.height);n.putImageData(h,0,0),await t.add(o/e.fps,1/e.fps),this.progressUI.update(25+Math.round((o+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 n=i;if(n.skipVideoUpdate=!1,n.originalVideoElement&&n.texture){const r=f.Texture.from(n.originalVideoElement);n.texture=r,n.sprite&&(n.sprite.texture=r),delete n.originalVideoElement,delete n.originalTextureSource,delete n.lastReplacedTimestamp}else n.originalTextureSource&&n.texture&&(n.texture.source=n.originalTextureSource,delete n.originalTextureSource,delete n.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",r=t.texture?.source?.resource instanceof HTMLVideoElement;return i||r}}function Ns(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 Go(s){const e=t=>{if(typeof t=="string")return Ns(t);if(typeof t=="object"&&t!==null){const i=Array.isArray(t)?[]:{};for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[n]=e(t[n]));return i}return t};return e(s)}function Us(s){if(typeof s=="string")return Ns(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]=Us(s[t]));return e}return s}const Ws=Go({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 Gs{static resolveTheme(e){if(!e||!e.theme)return this.deepClone(Ws);const t=Us(e.theme),i=this.deepClone(Ws);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:n}=t;if(typeof n.background!="number"||typeof n.text!="number"||typeof n.markers!="number"||typeof n.height!="number"||n.height<=0||!t.tracks)return!1;const{tracks:r}=t;if(typeof r.surface!="number"||typeof r.surfaceAlt!="number"||typeof r.border!="number"||typeof r.height!="number"||r.height<=0||!t.clips)return!1;const{clips:a}=t,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(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 n in t)if(Object.prototype.hasOwnProperty.call(t,n)){const r=t[n],a=i[n];r!==void 0&&(typeof r=="object"&&r!==null&&!Array.isArray(r)&&typeof a=="object"&&a!==null&&!Array.isArray(a)?i[n]=this.deepMerge(a,r):i[n]=r)}return i}}class $o{timeline;constructor(e){this.timeline=e}getValidDropPosition(e,t,i,n){const r=this.timeline.getVisualTracks()[i];if(!r)return{validTime:e,wouldOverlap:!1};const a=this.getOtherClipBounds(r,n),o=e+t,l=a.find(p=>!(o<=p.start||e>=p.end));if(!l)return{validTime:e,wouldOverlap:!1};const c=l.start-t,h=l.end,d=Math.abs(e-c)<Math.abs(e-h)&&c>=0?c:h;return{validTime:this.getValidDropPosition(d,t,i,n).validTime,wouldOverlap:!0}}checkOverlap(e,t,i,n){const r=this.timeline.getVisualTracks()[i];if(!r)return!1;const a=this.getOtherClipBounds(r,n),o=e+t;return a.some(l=>!(o<=l.start||e>=l.end))}getOtherClipBounds(e,t){return e.getClips().map((i,n)=>({clip:i,index:n})).filter(({index:i})=>i!==t).map(({clip:i})=>{const n=i.getClipConfig();return n?{start:n.start||0,end:(n.start||0)+(n.length||0)}:null}).filter(i=>i!==null).sort((i,n)=>i.start-n.start)}findAvailableGaps(e,t){const i=this.timeline.getVisualTracks()[e];if(!i)return[];const n=this.getOtherClipBounds(i),r=[];n.length>0&&n[0].start>=t&&r.push({start:0,end:n[0].start});for(let a=0;a<n.length-1;a+=1)n[a+1].start-n[a].end>=t&&r.push({start:n[a].end,end:n[a+1].start});return r}}class $s{constructor(e,t,i,n){this.fromTrackIndex=e,this.fromClipIndex=t,this.toTrackIndex=i,this.newStart=n,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 n=t[this.toTrackIndex];let r=0;for(let a=0;a<n.length;a+=1){const o=n[a];if(o.clipConfiguration&&o.clipConfiguration.start!==void 0&&this.newStart<o.clipConfiguration.start)break;r+=1}n.splice(r,0,this.player),this.originalClipIndex=r}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 n=t[this.fromTrackIndex],r=t[this.toTrackIndex];[...n,...r].forEach(a=>{a&&a!==this.player&&a.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],n=i.indexOf(this.player);n!==-1&&i.splice(n,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 Zo{constructor(e,t,i,n){this.insertionIndex=e,this.fromTrackIndex=t,this.fromClipIndex=i,this.newStart=n,this.addTrackCommand=new es(e);const r=t>=e?t+1:t;this.moveClipCommand=new $s(r,i,e,n)}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 Ko{timeline;thresholds;snapManager;collisionDetector;visualFeedback;dragInfo=null;currentDropZone=null;constructor(e,t,i,n,r){this.timeline=e,this.thresholds=t,this.snapManager=i,this.collisionDetector=n,this.visualFeedback=r}activate(){}deactivate(){this.endDrag()}canStartDrag(e,t){const i=Math.sqrt((t.x-e.x)**2+(t.y-e.y)**2),{trackHeight:n}=this.timeline.getLayout(),r=n<20?2:this.thresholds.drag.base;return i>r}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 n=this.timeline.getContainer().toLocal(t.global),r=this.timeline.getLayout(),a=r.getXAtTime(i.start||0),o=e.trackIndex*r.trackHeight;return this.dragInfo={trackIndex:e.trackIndex,clipIndex:e.clipIndex,startTime:i.start||0,offsetX:n.x-a,offsetY:n.y-o},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),n=this.detectDropZone(i.y);this.endDrag(),n?this.executeDropZoneMove(n,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(),n=Math.max(0,i.getTimeAtX(t.x-this.dragInfo.offsetX)),r=t.y-this.dragInfo.offsetY,a=r+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:t.x,y:t.y+i.viewportY,time:n,track:c,ghostY:r}}detectDropZone(e){const t=this.timeline.getLayout(),i=this.timeline.getVisualTracks(),n=t.trackHeight*this.thresholds.dropZone.ratio;for(let r=0;r<=i.length;r+=1){const a=t.tracksY+r*t.trackHeight;if(Math.abs(e-a)<n){let o;return r===0?o="above":r===i.length?o="below":o="between",{type:o,position:r}}}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,n=e.track===this.dragInfo.trackIndex?this.dragInfo.clipIndex:void 0,r=this.calculateFinalPosition(e.time,e.track,i,n),a=this.snapManager.findAlignedElements(r,i,e.track,n);a.length>0?this.visualFeedback.showSnapGuidelines(a):this.visualFeedback.hideSnapGuidelines(),this.visualFeedback.showTargetTrack(e.track),this.timeline.showDragGhost(e.track,r,e.ghostY)}calculateFinalPosition(e,t,i,n){const r=this.snapManager.calculateSnapPosition(e,t,i,n);return this.collisionDetector.getValidDropPosition(r.time,i,t,n).validTime}emitDragUpdate(e,t){if(!this.dragInfo)return;const i=this.timeline.getClipData(this.dragInfo.trackIndex,this.dragInfo.clipIndex);if(!i)return;const n=i.length||0,r=t?e.time:this.calculateFinalPosition(e.time,e.track,n,e.track===this.dragInfo.trackIndex?this.dragInfo.clipIndex:void 0);this.timeline.getEdit().events.emit("drag:moved",{...this.dragInfo,currentTime:r,currentTrack:t?-1:e.track})}executeDropZoneMove(e,t,i){const n=new Zo(e.position,t.trackIndex,t.clipIndex,i.time);this.timeline.getEdit().executeEditCommand(n)}executeNormalMove(e,t){const i=this.timeline.getClipData(e.trackIndex,e.clipIndex);if(!i)return;const n=i.length||0,r=t.track===e.trackIndex?e.clipIndex:void 0,a=this.calculateFinalPosition(t.time,t.track,n,r);if(t.track!==e.trackIndex||Math.abs(a-e.startTime)>.01){const l=new $s(e.trackIndex,e.clipIndex,t.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 jo{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 Xo{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 n=i.getClip(e.clipIndex);if(!n)return!1;const a=n.getContainer().getBounds(),o=a.x+a.width,l=Math.abs(t.global.x-o),c=this.getResizeThreshold();return l<=c}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 n=this.timeline.getVisualTracks()[e.trackIndex];if(n){const r=n.getClip(e.clipIndex);r&&r.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,n=t/i,r=Math.max(.1,this.resizeInfo.originalLength+n),a=this.timeline.getVisualTracks()[this.resizeInfo.trackIndex];if(a){const o=a.getClip(this.resizeInfo.clipIndex);if(o){const l=r*i;o.setPreviewWidth(l),this.timeline.getEdit().events.emit("resize:updated",{width:l})}}}completeResize(e){if(!this.resizeInfo)return;const t=e.global.x-this.resizeInfo.startX,i=this.timeline.getOptions().pixelsPerSecond||50,n=t/i,r=Math.max(.1,this.resizeInfo.originalLength+n),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(r-this.resizeInfo.originalLength)>.01){const o=new jo(this.resizeInfo.trackIndex,this.resizeInfo.clipIndex,r);this.timeline.getEdit().executeEditCommand(o),this.timeline.getEdit().events.emit("resize:ended",{newLength:r})}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 Yo{timeline;thresholds;constructor(e,t){this.timeline=e,this.thresholds=t}getAllSnapPoints(e,t){const i=[];this.timeline.getVisualTracks().forEach((a,o)=>{a.getClips().forEach((c,h)=>{if(o===e&&h===t)return;const d=c.getClipConfig();d&&(i.push({time:d.start||0,type:"clip-start",trackIndex:o,clipIndex:h}),i.push({time:(d.start||0)+(d.length||0),type:"clip-end",trackIndex:o,clipIndex:h}))})});const r=this.timeline.getPlayheadTime();return i.push({time:r,type:"playhead"}),i}getTrackSnapPoints(e,t){return this.getAllSnapPoints(e,t).filter(i=>i.trackIndex===void 0||i.trackIndex===e)}calculateSnapPosition(e,t,i,n){const r=this.timeline.getOptions().pixelsPerSecond||50,a=this.thresholds.snap.pixels/r,o=this.getTrackSnapPoints(t,n);let l=null;for(const c of o){const h=Math.abs(e-c.time);h<a&&(!l||h<l.distance)&&(l={time:c.time,type:c.type,distance:h});const d=Math.abs(e+i-c.time);d<a&&(!l||d<l.distance)&&(l={time:c.time-i,type:c.type,distance:d})}return l?{time:l.time,snapped:!0,snapType:l.type}:{time:e,snapped:!1}}findAlignedElements(e,t,i,n){const a=e+t,o=new Map;this.timeline.getVisualTracks().forEach((c,h)=>{c.getClips().forEach((d,u)=>{if(h===i&&u===n)return;const p=d.getClipConfig();if(!p)return;const g=p.start||0,b=g+(p.length||0);[{time:g,aligns:[e,a]},{time:b,aligns:[e,a]}].forEach(({time:_,aligns:B})=>{B.some(N=>Math.abs(N-_)<.1)&&(o.has(_)||o.set(_,{tracks:new Set,isPlayhead:!1}),o.get(_).tracks.add(h))})})});const l=this.timeline.getPlayheadTime();return(Math.abs(e-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 qo{timeline;graphics=new Map;constructor(e){this.timeline=e}showDropZone(e){this.hideDropZone();const t=new f.Graphics,i=this.timeline.getLayout(),n=this.timeline.getExtendedTimelineWidth(),r=e.position*i.trackHeight,o=this.timeline.getTheme().timeline.trackInsertion;t.setStrokeStyle({width:4,color:o,alpha:.8}),t.moveTo(0,r),t.lineTo(n,r),t.stroke(),t.setStrokeStyle({width:8,color:o,alpha:.3}),t.moveTo(0,r),t.lineTo(n,r),t.stroke(),this.timeline.getContainer().addChild(t),this.graphics.set("dropZone",t)}hideDropZone(){this.hideGraphics("dropZone")}showSnapGuidelines(e){this.hideSnapGuidelines();const t=new f.Graphics,i=this.timeline.getLayout(),n=this.timeline.getTheme();e.forEach(({time:r,tracks:a,isPlayhead:o})=>{const l=i.getXAtTime(r),c=Math.min(...a),h=Math.max(...a),d=c*i.trackHeight,u=(h+1)*i.trackHeight,p=o?n.timeline.playhead:n.timeline.snapGuide;t.setStrokeStyle({width:3,color:p,alpha:.3}),t.moveTo(l,d),t.lineTo(l,u),t.stroke(),t.setStrokeStyle({width:1,color:p,alpha:.8}),t.moveTo(l,d),t.lineTo(l,u),t.stroke()}),this.timeline.getContainer().addChild(t),this.graphics.set("snapGuidelines",t)}hideSnapGuidelines(){this.hideGraphics("snapGuidelines")}showTargetTrack(e){this.hideTargetTrack();const t=new f.Graphics,i=this.timeline.getLayout(),n=this.timeline.getExtendedTimelineWidth(),r=e*i.trackHeight,a=i.trackHeight,l=this.timeline.getTheme().timeline.dropZone;t.rect(0,r,n,a),t.fill({color:l,alpha:.1}),t.setStrokeStyle({width:1,color:l,alpha:.3}),t.rect(0,r,n,a),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 Qo{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 Yo(e,this.thresholds),this.collisionDetector=new $o(e),this.visualFeedback=new qo(e),this.dragHandler=new Ko(e,this.thresholds,this.snapManager,this.collisionDetector,this.visualFeedback),this.resizeHandler=new Xo(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 n=this.resizeHandler.getResizeInfo();n&&(this.state={type:"resizing",resizeInfo:n})}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 n=this.resizeHandler.getCursorForPosition(i,e);if(n){this.timeline.getPixiApp().canvas.style.cursor=n;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),n=parseInt(t[2],10);return Number.isNaN(i)||Number.isNaN(n)?null:{trackIndex:i,clipIndex:n}}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 Jo{constructor(e,t,i,n,r){this.container=e,this.layout=t,this.getPixelsPerSecond=i,this.getTrackHeight=n,this.getVisualTracks=r}dragPreviewContainer=null;dragPreviewGraphics=null;draggedClipInfo=null;showDragPreview(e,t,i){if(!i)return;this.draggedClipInfo={trackIndex:e,clipIndex:t,clipConfig:i},this.dragPreviewContainer=new f.Container,this.dragPreviewGraphics=new f.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,n=this.layout.getXAtTime(t),r=e*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(n,r)}drawDragPreviewAtPosition(e,t,i){if(!this.dragPreviewContainer||!this.dragPreviewGraphics||!this.draggedClipInfo)return;const{clipConfig:n}=this.draggedClipInfo,r=this.layout.getXAtTime(e),a=(n.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(t-l)<5?65280:16755200;this.dragPreviewGraphics.stroke({width:2,color:h}),this.dragPreviewContainer.position.set(r,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 ec{constructor(e,t,i,n,r){this.layout=e,this.trackLayer=t,this.overlayLayer=i,this.entityContainer=n,this.onRender=r}scrollX=0;scrollY=0;zoomLevel=1;viewport;rulerViewport;playheadContainer;async setupViewport(){this.rulerViewport=new f.Container,this.rulerViewport.label="ruler-viewport",this.overlayLayer.addChild(this.rulerViewport),this.playheadContainer=new f.Container,this.playheadContainer.label="playhead-container",this.overlayLayer.addChild(this.playheadContainer),this.viewport=new f.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 te={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},xt={PADDING:2,LABEL_PADDING:8,DEFAULT_OPACITY:.8,BORDER_WIDTH:1},ne={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 Yt(s){const e=s.split("/");return e[e.length-1]||s}function tc(s){switch(s.type){case"video":return s.src?Yt(s.src):"Video";case"audio":return s.src?Yt(s.src):"Audio";case"image":return s.src?Yt(s.src):"Image";case"text":return s.text||"Text";case"shape":return s.shape||"Shape";case"html":return"HTML";case"luma":return s.src?Yt(s.src):"Luma";default:return"Unknown Asset"}}class ic extends be{clipConfig;options;graphics;background;text;selectionRenderer;lastGlobalX=-1;lastGlobalY=-1;visualState={mode:"normal"};CLIP_PADDING=te.PADDING;BORDER_WIDTH=te.BORDER_WIDTH;get CORNER_RADIUS(){return this.options.theme.timeline.clips.radius||te.CORNER_RADIUS}constructor(e,t){super(),this.clipConfig=e,this.options=t,this.selectionRenderer=t.selectionRenderer,this.graphics=new f.Graphics,this.background=new f.Graphics,this.text=new f.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 f.TextStyle({fontSize:te.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(te.MIN_WIDTH,t)}drawClipBackground(e,t){const i=this.getClipColor(),n=this.getStateStyles();this.background.clear(),this.background.roundRect(0,0,e,t,this.CORNER_RADIUS),this.background.fill({color:i,alpha:n.alpha})}drawClipBorder(e,t){const i=this.getStateStyles(),n=this.BORDER_WIDTH;this.graphics.clear(),this.graphics.roundRect(0,0,e,t,this.CORNER_RADIUS),this.graphics.stroke({width:n,color:i.borderColor}),this.updateSelectionState(e,t)}updateSelectionState(e,t){if(!this.selectionRenderer)return;const i=this.visualState.mode==="selected",n=this.getClipId();if(!i){this.selectionRenderer.clearSelection(n);return}const a=this.getContainer().toGlobal(new f.Point(0,0)),l=this.selectionRenderer.getOverlay().toLocal(a);this.selectionRenderer.renderSelection(n,{x:l.x,y:l.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"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"?te.DRAG_OPACITY:te.DEFAULT_ALPHA}updateText(){const e=this.clipConfig.asset?tc(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 n=i/this.text.width,r=Math.floor(e.length*n)-te.TEXT_TRUNCATE_SUFFIX_LENGTH;this.text.text=`${e.substring(0,Math.max(1,r))}...`}}getStateStyles(){const{theme:e}=this.options;switch(this.visualState.mode){case"dragging":return{alpha:te.DRAG_OPACITY,borderColor:e.timeline.tracks.border};case"resizing":return{alpha:te.RESIZE_OPACITY,borderColor:e.timeline.dropZone};case"selected":return{alpha:te.DEFAULT_ALPHA,borderColor:e.timeline.clips.selected};default:return{alpha:te.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 n=this.getContainer().toGlobal(new f.Point(0,0));if(n.x!==this.lastGlobalX||n.y!==this.lastGlobalY){this.lastGlobalX=n.x,this.lastGlobalY=n.y;const r=this.getEffectiveWidth(),a=this.options.trackHeight;this.updateSelectionState(r,a)}}}draw(){}dispose(){this.selectionRenderer&&this.selectionRenderer.clearSelection(this.getClipId()),this.background.destroy(),this.graphics.destroy(),this.text.destroy()}}class sc extends be{clips=[];options;background;TRACK_PADDING=xt.PADDING;LABEL_PADDING=xt.LABEL_PADDING;constructor(e){super(),this.options=e,this.background=new f.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 n=this.options.trackIndex%2===0?i.timeline.tracks.surface:i.timeline.tracks.surfaceAlt;this.background.rect(0,0,e,t),this.background.fill({color:n,alpha:xt.DEFAULT_OPACITY}),this.background.rect(0,0,e,t),this.background.stroke({width:xt.BORDER_WIDTH,color:i.timeline.tracks.border}),this.background.moveTo(0,t-1),this.background.lineTo(e,t-1),this.background.stroke({width:xt.BORDER_WIDTH,color:i.timeline.divider})}rebuildFromTrackData(e,t){this.options={...this.options,pixelsPerSecond:t},this.clearAllClips(),e.clips&&e.clips.forEach((i,n)=>{const r={pixelsPerSecond:this.options.pixelsPerSecond,trackHeight:this.options.trackHeight,trackIndex:this.options.trackIndex,clipIndex:n,theme:this.options.theme,selectionRenderer:this.options.selectionRenderer},a=new ic(i,r);this.addClip(a)}),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,n)=>{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 n=0;n<this.clips.length;n+=1){const r=this.clips[n],a=r.getClipConfig(),o=a.start||0,l=o+(a.length||0);if(i>=o&&i<=l)return{clip:r,clipIndex:n}}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 nc{constructor(e,t){this.overlay=e,this.theme=t}selectionGraphics=new Map;renderSelection(e,t,i){if(!i){this.clearSelection(e);return}let n=this.selectionGraphics.get(e);n||(n=new f.Graphics,n.label=`selection-border-${e}`,this.selectionGraphics.set(e,n),this.overlay.addChild(n)),n.position.set(t.x,t.y),n.clear(),n.setStrokeStyle({width:t.borderWidth*te.SELECTED_BORDER_MULTIPLIER,color:this.theme.timeline.clips.selected}),n.roundRect(0,0,t.width,t.height,t.cornerRadius),n.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 rc{constructor(e,t,i,n,r){this.container=e,this.layout=t,this.theme=i,this.getPixelsPerSecond=n,this.getExtendedTimelineWidth=r,this.selectionOverlay=new f.Container,this.selectionOverlay.label="selectionOverlay",this.container.addChild(this.selectionOverlay),this.selectionRenderer=new nc(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 n=e.timeline.tracks[i],r={pixelsPerSecond:t,trackHeight:this.layout.trackHeight,trackIndex:i,width:this.getExtendedTimelineWidth(),theme:this.theme,selectionRenderer:this.selectionRenderer},a=new sc(r);await a.load(),a.rebuildFromTrackData(n,t),this.container.addChild(a.getContainer()),this.visualTracks.push(a)}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 n=i.getClip(t);n&&n.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 n=this.visualTracks[i],r=t-i*this.layout.trackHeight,a=n.findClipAtPosition(e,r);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(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 ac{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 oc{constructor(e,t){this.options=e,this.onUpdate=t}app;trackLayer;overlayLayer;animationFrameId=null;async initializePixiApp(){this.app=new f.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 f.Container,this.overlayLayer=new f.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 n=i-e;e=i;const r=n/16.667;this.onUpdate(r,n),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 nt={RULER:{DEFAULT_HEIGHT:40,LABEL_FONT_SIZE:10,LABEL_PADDING_X:2},PLAYHEAD:{LINE_WIDTH:2},SCROLL:{HORIZONTAL_SPEED:2,VERTICAL_SPEED:.5}};class Zs extends be{events;rulerContainer;rulerBackground;timeMarkers;timeLabels;pixelsPerSecond;timelineDuration;rulerHeight;theme;constructor(e){super(),this.events=new pt,this.pixelsPerSecond=e.pixelsPerSecond,this.timelineDuration=e.timelineDuration,this.rulerHeight=e.rulerHeight??nt.RULER.DEFAULT_HEIGHT,this.theme=e.theme,this.rulerContainer=new f.Container,this.rulerBackground=new f.Graphics,this.timeMarkers=new f.Graphics,this.timeLabels=new f.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,n=this.rulerHeight*.5;let r=4;e===10?r=9:(e===30||e===60)&&(r=5);const a=e/(r+1);for(let o=0;o<=t;o+=e)for(let l=1;l<=r;l+=1){const c=o+l*a;if(c<=t){const h=c*this.pixelsPerSecond;this.timeMarkers.circle(h,n,1.5),this.timeMarkers.fill(i)}}}drawTimeLabels(){this.timeLabels.removeChildren();const e=this.getTimeInterval(),t=this.getVisibleDuration(),i=this.theme?.timeline.ruler.text||16777215,n={fontSize:nt.RULER.LABEL_FONT_SIZE,fill:i,fontFamily:"Arial"};for(let r=0;r<=t;r+=e){const a=new f.Text({text:this.formatTime(r),style:n}),o=r*this.pixelsPerSecond;r===0?(a.anchor.set(0,.5),a.x=o+nt.RULER.LABEL_PADDING_X):(a.anchor.set(.5,.5),a.x=o),a.y=this.rulerHeight*.5,this.timeLabels.addChild(a)}}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 n=i.toString().padStart(2,"0");return`${t}:${n}`}}class Ks extends be{constructor(e){super(),this.options=e,this.graphics=new f.Graphics}events=new pt;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=nt.PLAYHEAD.LINE_WIDTH,n=e+i/2;this.graphics.clear(),this.graphics.fill(t),this.graphics.rect(e,0,i,this.options.timelineHeight);const r=8;this.graphics.moveTo(n,10),this.graphics.lineTo(n-r,0),this.graphics.lineTo(n+r,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){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 cc{events;timeline;abortController;scrollX=0;scrollY=0;constructor(e){this.events=new pt,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(),n=this.timeline.getActualEditDuration();t==="in"?this.timeline.zoomIn():this.timeline.zoomOut();const r=this.timeline.getOptions().pixelsPerSecond||50,a=i*r,o=this.timeline.getOptions().width||800,c=this.timeline.timeRange.endTime*r,h=n*r,d=this.calculateZoomScrollPosition({playheadXAfterZoom:a,viewportWidth:o,contentWidth:c,maxPlayheadX:h,actualEditDuration:n,playheadTime:i});this.scrollX=d,this.timeline.setScroll(this.scrollX,this.scrollY);const u=a-d;this.events.emit("zoom",{pixelsPerSecond:r,focusX:u,focusTime:i})}handleScroll(e){let{deltaX:t}=e,{deltaY:i}=e;e.shiftKey&&(t=i,i=0);const n=nt.SCROLL.HORIZONTAL_SPEED,r=nt.SCROLL.VERTICAL_SPEED;this.scrollX+=t*n,this.scrollY+=i*r,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,n=Math.max(0,t-i);return Math.max(0,Math.min(e,n))}clampScrollY(e){const t=this.timeline.getLayout(),i=this.timeline.getVisualTracks().length,n=this.timeline.getOptions().height||0,r=Math.max(0,i*t.trackHeight-(n-t.rulerHeight));return Math.max(0,Math.min(e,r))}getScroll(){return{x:this.scrollX,y:this.scrollY}}calculateZoomScrollPosition(e){const{playheadXAfterZoom:t,viewportWidth:i,contentWidth:n,maxPlayheadX:r,actualEditDuration:a,playheadTime:o}=e,l=t-i/2,c=Math.max(0,n-i);let h;const d=l+i,u=Math.max(0,r-i);n<=i||l<0?h=0:d>r&&o<=a?h=Math.min(u,c):l>c?h=c:h=l;const p=t-h;return(p<0||p>i)&&(t>n-i?h=Math.max(0,t-i+50):h=Math.max(0,t-50),h=Math.max(0,Math.min(h,c))),h}dispose(){this.abortController&&(this.abortController.abort(),this.abortController=void 0),this.events.clear("*")}}const D={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 qt{static createIcon(e,t,i){const n=i?i/D.BUTTON_SIZE:1;switch(e){case"play":return this.createPlayIcon(t,n);case"pause":return this.createPauseIcon(t,n);case"frame-back":return this.createFrameBackIcon(t,n);case"frame-forward":return this.createFrameForwardIcon(t,n);default:throw new Error(`Unknown icon type: ${e}`)}}static createPlayIcon(e,t=1){const i=new f.Graphics,{PLAY:n}=D.ICON;return i.fill({color:e.timeline.toolbar.icon}),i.moveTo(n.LEFT*t,n.TOP*t),i.lineTo(n.RIGHT*t,n.MIDDLE*t),i.lineTo(n.LEFT*t,n.BOTTOM*t),i.closePath(),i.fill(),i}static createPauseIcon(e,t=1){const i=new f.Graphics,{PAUSE:n}=D.ICON;return i.fill({color:e.timeline.toolbar.icon}),i.rect(n.RECT1_X*t,n.TOP*t,n.WIDTH*t,n.HEIGHT*t),i.rect(n.RECT2_X*t,n.TOP*t,n.WIDTH*t,n.HEIGHT*t),i.fill(),i}static createFrameBackIcon(e,t=1){const i=new f.Graphics,{FRAME_STEP:n}=D.ICON;return i.fill({color:e.timeline.toolbar.icon}),i.moveTo(n.TRIANGLE1.BACK.LEFT*t,n.TOP*t),i.lineTo(n.TRIANGLE1.BACK.RIGHT*t,n.TRIANGLE1.BACK.MIDDLE*t),i.lineTo(n.TRIANGLE1.BACK.LEFT*t,n.BOTTOM*t),i.closePath(),i.moveTo(n.TRIANGLE2.BACK.LEFT*t,n.TOP*t),i.lineTo(n.TRIANGLE2.BACK.RIGHT*t,n.TRIANGLE2.BACK.MIDDLE*t),i.lineTo(n.TRIANGLE2.BACK.LEFT*t,n.BOTTOM*t),i.closePath(),i.fill(),i}static createFrameForwardIcon(e,t=1){const i=new f.Graphics,{FRAME_STEP:n}=D.ICON;return i.fill({color:e.timeline.toolbar.icon}),i.moveTo(n.TRIANGLE1.FORWARD.LEFT*t,n.TOP*t),i.lineTo(n.TRIANGLE1.FORWARD.RIGHT*t,n.TRIANGLE1.FORWARD.MIDDLE*t),i.lineTo(n.TRIANGLE1.FORWARD.LEFT*t,n.BOTTOM*t),i.closePath(),i.moveTo(n.TRIANGLE2.FORWARD.LEFT*t,n.TOP*t),i.lineTo(n.TRIANGLE2.FORWARD.RIGHT*t,n.TRIANGLE2.FORWARD.MIDDLE*t),i.lineTo(n.TRIANGLE2.FORWARD.LEFT*t,n.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 js extends f.Container{background;hoverBackground;icon;alternateIcon;state={isHovering:!1,isPressed:!1,isActive:!1};size;theme;onClick;constructor(e){super(),this.size=e.size||D.BUTTON_SIZE,this.theme=e.theme,this.onClick=e.onClick,this.eventMode="static",this.cursor="pointer",this.background=new f.Graphics,this.addChild(this.background),this.hoverBackground=new f.Graphics,this.addChild(this.hoverBackground);const i=this.size*.6,n=(this.size-i)/2;e.iconType&&(this.icon=qt.createIcon(e.iconType,this.theme,i),this.icon.position.set(n,n),this.addChild(this.icon)),e.alternateIconType&&(this.alternateIcon=qt.createIcon(e.alternateIconType,this.theme,i),this.alternateIcon.position.set(n,n),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=D.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:D.ACTIVE_ANIMATION_ALPHA}):this.state.isHovering?this.hoverBackground.fill({color:this.theme.timeline.toolbar.hover,alpha:D.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,n=(this.size-i)/2;if(this.icon){const r=this.getIconType(this.icon);r&&(this.removeChild(this.icon),this.icon=qt.createIcon(r,e,i),this.icon.position.set(n,n),this.addChild(this.icon))}if(this.alternateIcon){const r=this.getIconType(this.alternateIcon);r&&(this.removeChild(this.alternateIcon),this.alternateIcon=qt.createIcon(r,e,i),this.alternateIcon.position.set(n,n),this.alternateIcon.visible=this.state.isActive,this.addChild(this.alternateIcon))}this.updateVisuals()}getIconType(e){return null}destroy(){this.removeAllListeners(),super.destroy()}}class lc extends f.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=(n,r,a,o)=>new js({iconType:n,onClick:r,tooltip:a,theme:this.theme,size:o});this.frameBackButton=i("frame-back",()=>this.handleFrameBack(),"Previous frame",e.regularButton),this.frameBackButton.position.set(0,t),this.playPauseButton=new js({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-D.FRAME_TIME_MS)}handlePlayPause(){this.edit.isPlaying?this.edit.pause():this.edit.play()}handleFrameForward(){this.edit.seek(this.edit.playbackTime+D.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 hc extends f.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 f.TextStyle({fontFamily:D.TIME_DISPLAY.FONT_FAMILY,fontSize:D.TIME_DISPLAY.FONT_SIZE,fill:this.theme.timeline.toolbar.text});this.timeText=new f.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),n=Math.floor(e%60),r=Math.floor(e%1*10);let a="";return this.formatOptions.showHours||t>0?a+=`${t}:${i.toString().padStart(2,"0")}`:a+=`${i}`,a+=`:${n.toString().padStart(2,"0")}`,this.formatOptions.showMilliseconds?a+=`.${r}`:a+=`.${r}`,a}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 dc extends f.Container{edit;theme;cutButton;cutButtonBackground;cutButtonText;constructor(e,t){super(),this.edit=e,this.theme=t,this.createCutButton()}createCutButton(){this.cutButton=new f.Container,this.cutButton.eventMode="static",this.cutButton.cursor="pointer";const{WIDTH:e,HEIGHT:t,FONT_SIZE:i}=D.CUT_BUTTON;this.cutButtonBackground=new f.Graphics,this.cutButtonBackground.roundRect(0,0,e,t,D.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 n=new f.TextStyle({fontFamily:"Arial",fontSize:i,fill:this.theme.timeline.toolbar.text||16777215});this.cutButtonText=new f.Text("SPLIT",n),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,D.CUT_BUTTON.WIDTH,D.CUT_BUTTON.HEIGHT,D.BORDER_RADIUS);let i=this.theme.timeline.toolbar.surface||4473924;const n=1;e?i=this.theme.timeline.toolbar.active||3355443:t&&(i=this.theme.timeline.toolbar.hover||5592405),this.cutButtonBackground.fill({color:i,alpha:n}),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,n=this.edit.playbackTime/1e3;this.edit.splitClip(t,i,n)}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 D.CUT_BUTTON.WIDTH}}class uc{config;constructor(e,t){this.config={width:e,height:t,buttonSize:Math.round(t*.5),buttonSpacing:Math.round(t*.15),edgeMargin:D.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+D.TEXT_SPACING,n=this.config.height/2;return{x:i,y:n}}getEditControlsPosition(){const e=this.config.width-D.CUT_BUTTON.WIDTH-this.config.edgeMargin,t=(this.config.height-D.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 pc extends f.Container{constructor(e,t,i,n){super(),this.edit=e,this.theme=t,this.layout=i,this.toolbarWidth=n,this.toolbarHeight=i.toolbarHeight,this.position.set(0,i.toolbarY),this.toolbarLayout=new uc(n,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 f.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:D.DIVIDER_ALPHA}),this.background.moveTo(0,this.toolbarHeight-.5),this.background.lineTo(this.toolbarWidth,this.toolbarHeight-.5),this.background.stroke()}createComponents(){this.playbackControls=new lc(this.edit,this.theme,this.toolbarHeight),this.addChild(this.playbackControls),this.timeDisplay=new hc(this.edit,this.theme),this.addChild(this.timeDisplay),this.editControls=new dc(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 fc{constructor(e,t,i,n,r,a){this.edit=e,this.layout=t,this.renderer=i,this.viewportManager=n,this.eventHandler=r,this.getTimelineContext=a}toolbar;ruler;playhead;scroll;async setupTimelineFeatures(e,t,i,n,r){this.toolbar=new pc(this.edit,e,this.layout,i),this.renderer.getStage().addChild(this.toolbar);const a={pixelsPerSecond:t,timelineDuration:r,rulerHeight:this.layout.rulerHeight,theme:e};this.ruler=new Zs(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:t,timelineHeight:n,theme:e};this.playhead=new Ks(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 cc(l),await this.scroll.initialize(),this.viewportManager.updateViewportTransform()}recreateTimelineFeatures(e,t,i,n){if(this.ruler){this.ruler.dispose();const{rulerHeight:r}=this.layout,a={pixelsPerSecond:t,timelineDuration:n,rulerHeight:r,theme:e};this.ruler=new Zs(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 r={pixelsPerSecond:t,timelineHeight:i,theme:e};this.playhead=new Ks(r),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 Te{constructor(e,t){this.options=e,this.theme=t,this.config=this.calculateLayout()}static TOOLBAR_HEIGHT_RATIO=ne.TOOLBAR_HEIGHT_RATIO;static RULER_HEIGHT_RATIO=ne.RULER_HEIGHT_RATIO;static TOOLBAR_HEIGHT_DEFAULT=ne.TOOLBAR_HEIGHT_DEFAULT;static RULER_HEIGHT_DEFAULT=ne.RULER_HEIGHT_DEFAULT;static TRACK_HEIGHT_DEFAULT=ne.TRACK_HEIGHT_DEFAULT;static CLIP_PADDING=ne.CLIP_PADDING;static BORDER_WIDTH=ne.BORDER_WIDTH;static CORNER_RADIUS=ne.CORNER_RADIUS;static LABEL_PADDING=ne.LABEL_PADDING;static TRACK_PADDING=ne.TRACK_PADDING;config;calculateLayout(){const e=this.options.height;let t=this.theme?.timeline.toolbar.height||Math.round(e*Te.TOOLBAR_HEIGHT_RATIO),i=this.theme?.timeline.ruler.height||Math.round(e*Te.RULER_HEIGHT_RATIO);t=Math.max(t,Te.TOOLBAR_HEIGHT_DEFAULT),i=Math.max(i,Te.RULER_HEIGHT_DEFAULT);const{trackHeight:n}=this.options;return{toolbarHeight:t,rulerHeight:i,trackHeight:n,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(ne.MIN_CLIP_WIDTH,e*this.options.pixelsPerSecond)}calculateDropPosition(e,t){const i=t-this.tracksY,n=Math.floor(i/this.trackHeight),r=Math.max(0,e/this.options.pixelsPerSecond);return{track:Math.max(0,n),time:r,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,n=Math.floor(i/this.trackHeight),r=Math.ceil((i+t)/this.trackHeight);return{start:Math.max(0,n),end:Math.max(0,r)}}}class pe{constructor(e,t,i,n){this.layout=i,this.onResize=n,this.width=e.width,this.height=e.height,this.pixelsPerSecond=50;const r=t.timeline.tracks.height||Te.TRACK_HEIGHT_DEFAULT;this.trackHeight=Math.max(40,r),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||Te.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*pe.ZOOM_FACTOR,pe.MAX_PIXELS_PER_SECOND);this.setPixelsPerSecond(e)}zoomOut(){const e=Math.max(this.pixelsPerSecond/pe.ZOOM_FACTOR,pe.MIN_PIXELS_PER_SECOND);this.setPixelsPerSecond(e)}setPixelsPerSecond(e){this.pixelsPerSecond=Math.max(pe.MIN_PIXELS_PER_SECOND,Math.min(pe.MAX_PIXELS_PER_SECOND,e)),this.layout.updateOptions(this.getOptions())}canZoomIn(){return this.pixelsPerSecond<pe.MAX_PIXELS_PER_SECOND}canZoomOut(){return this.pixelsPerSecond>pe.MIN_PIXELS_PER_SECOND}}class Ii extends be{constructor(e,t,i){super(),this.edit=e,this.theme=Gs.resolveTheme(i),this.layout=new Te({width:t.width,height:t.height,pixelsPerSecond:50,trackHeight:Math.max(40,this.theme.timeline.tracks.height||Te.TRACK_HEIGHT_DEFAULT),backgroundColor:this.theme.timeline.background,antialias:!0,resolution:window.devicePixelRatio||1},this.theme),this.optionsManager=new pe(t,this.theme,this.layout,n=>this.featureManager?.getToolbar()?.resize(n)),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 oc({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 ac(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 n=this.getClipData(t,i);n&&this.dragPreviewManager.showDragPreview(t,i,n)},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 ec(this.layout,this.renderer.getTrackLayer(),this.renderer.getOverlayLayer(),this.getContainer(),()=>this.renderer.render()),await this.viewportManager.setupViewport(),this.visualTrackManager=new rc(this.getContainer(),this.layout,this.theme,()=>this.optionsManager.getPixelsPerSecond(),()=>this.getExtendedTimelineWidth()),this.dragPreviewManager=new Jo(this.getContainer(),this.layout,()=>this.optionsManager.getPixelsPerSecond(),()=>this.optionsManager.getTrackHeight(),()=>this.visualTrackManager.getVisualTracks()),this.featureManager=new fc(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 Qo(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*Ii.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=Gs.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()}}ee.Canvas=De,ee.Controls=Pr,ee.Edit=Je,ee.Timeline=Ii,ee.VideoExporter=Wo,Object.defineProperty(ee,Symbol.toStringTag,{value:"Module"})});
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"})});