@shotstack/shotstack-studio 1.2.2 → 1.3.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.
- package/dist/core/entities/{player.d.ts → base/player.d.ts} +3 -3
- package/dist/core/entities/index.d.ts +14 -0
- package/dist/core/entities/{audio-player.d.ts → players/audio-player.d.ts} +4 -4
- package/dist/core/entities/{html-player.d.ts → players/html-player.d.ts} +4 -4
- package/dist/core/entities/{image-player.d.ts → players/image-player.d.ts} +4 -4
- package/dist/core/entities/{luma-player.d.ts → players/luma-player.d.ts} +4 -4
- package/dist/core/entities/{shape-player.d.ts → players/shape-player.d.ts} +4 -4
- package/dist/core/entities/players/text-player.d.ts +19 -0
- package/dist/core/entities/{video-player.d.ts → players/video-player.d.ts} +4 -4
- package/dist/core/entities/{edit.d.ts → system/edit.d.ts} +7 -7
- package/dist/core/entities/{inspector.d.ts → system/inspector.d.ts} +1 -1
- package/dist/core/entities/text/text-cursor.d.ts +47 -0
- package/dist/core/entities/text/text-editor.d.ts +43 -0
- package/dist/core/entities/text/text-input-handler.d.ts +54 -0
- package/dist/core/export/video-exporter.d.ts +1 -1
- package/dist/core/inputs/controls.d.ts +1 -1
- package/dist/core/schemas/asset.d.ts +6 -10
- package/dist/core/schemas/audio-asset.d.ts +6 -10
- package/dist/core/schemas/clip.d.ts +21 -35
- package/dist/core/schemas/edit.d.ts +42 -70
- package/dist/core/schemas/track.d.ts +21 -35
- package/dist/core/schemas/video-asset.d.ts +6 -10
- package/dist/core/shotstack-canvas.d.ts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/shotstack-studio.es.js +2451 -2032
- package/dist/shotstack-studio.umd.js +8 -6
- package/package.json +1 -1
- package/readme.md +7 -6
- package/dist/core/entities/text-player.d.ts +0 -18
- /package/dist/core/entities/{entity.d.ts → base/entity.d.ts} +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(F,V){typeof exports=="object"&&typeof module<"u"?V(exports,require("pixi.js"),require("opentype.js"),require("howler"),require("@ffmpeg/ffmpeg")):typeof define=="function"&&define.amd?define(["exports","pixi.js","opentype.js","howler","@ffmpeg/ffmpeg"],V):(F=typeof globalThis<"u"?globalThis:F||self,V(F.ShotstackStudio={},F.PIXI,F.opentype,F.Howler,F.ffmpeg))})(this,function(F,V,Kt,Ht,Bt){"use strict";function Ue(a){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(a){for(const t in a)if(t!=="default"){const i=Object.getOwnPropertyDescriptor(a,t);Object.defineProperty(e,t,i.get?i:{enumerable:!0,get:()=>a[t]})}}return e.default=a,Object.freeze(e)}const v=Ue(V),dt=Ue(Kt),jt=Ue(Ht);class ft{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 $t extends ft{registry;constructor(){super(),this.registry={}}}class Oe{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 $t;async load(e,t){this.updateAssetLoadMetadata(e,"pending",0);try{if(await this.shouldUseSafariVideoLoader(t))return await this.loadVideoForSafari(e,t);const i=await v.Assets.load(t,s=>{this.updateAssetLoadMetadata(e,"loading",s)});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,s)=>i+this.loadTracker.registry[s].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 Oe.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(".")),s=Oe.VIDEO_MIME[i];return s?document.createElement("video").canPlayType(s)!=="":!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),s=typeof t=="object"?t.data??{}:{},n=await new Promise((r,o)=>{const l=document.createElement("video");l.crossOrigin="anonymous",l.playsInline=!0,l.muted=!0,l.preload="metadata",l.addEventListener("loadedmetadata",()=>{try{const c=new v.VideoSource({resource:l,autoPlay:s.autoPlay??!1,...s});r(new v.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),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 s={...this.loadTracker.registry};this.loadTracker.emit("onAssetLoadInfoUpdated",{registry:s})}}class Ae{static Name="FontLoadParser";name;extension;validFontExtensions;woff2Decompressor;constructor(){this.name=Ae.Name,this.extension={type:[v.ExtensionType.LoadParser],priority:v.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 s=e.split("?")[0]?.split(".").pop()?.toLowerCase()??"",n=await fetch(e).then(p=>p.arrayBuffer());if(s!=="woff2"){const p=dt.parse(new Uint8Array(n).buffer),k=p.names.fontFamily.en||p.names.fontFamily[Object.keys(p.names.fontFamily)[0]],A=new FontFace(k,`url(${e})`);return await A.load(),document.fonts.add(A),A}if(await this.loadWoff2Decompressor(),!this.woff2Decompressor)throw new Error("Cannot initialize Woff2 decompressor.");const r=this.woff2Decompressor.decompress(n),o=dt.parse(new Uint8Array(r).buffer),l=o.names.fontFamily.en||o.names.fontFamily[Object.keys(o.names.fontFamily)[0]],c=new Blob([r],{type:"font/ttf"}),h=URL.createObjectURL(c),g=new FontFace(l,`url(${h})`);return await g.load(),document.fonts.add(g),g}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)}}var C;(function(a){a.assertEqual=s=>s;function e(s){}a.assertIs=e;function t(s){throw new Error}a.assertNever=t,a.arrayToEnum=s=>{const n={};for(const r of s)n[r]=r;return n},a.getValidEnumValues=s=>{const n=a.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),r={};for(const o of n)r[o]=s[o];return a.objectValues(r)},a.objectValues=s=>a.objectKeys(s).map(function(n){return s[n]}),a.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const n=[];for(const r in s)Object.prototype.hasOwnProperty.call(s,r)&&n.push(r);return n},a.find=(s,n)=>{for(const r of s)if(n(r))return r},a.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function i(s,n=" | "){return s.map(r=>typeof r=="string"?`'${r}'`:r).join(n)}a.joinValues=i,a.jsonStringifyReplacer=(s,n)=>typeof n=="bigint"?n.toString():n})(C||(C={}));var pt;(function(a){a.mergeShapes=(e,t)=>({...e,...t})})(pt||(pt={}));const f=C.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),G=a=>{switch(typeof a){case"undefined":return f.undefined;case"string":return f.string;case"number":return isNaN(a)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(a)?f.array:a===null?f.null:a.then&&typeof a.then=="function"&&a.catch&&typeof a.catch=="function"?f.promise:typeof Map<"u"&&a instanceof Map?f.map:typeof Set<"u"&&a instanceof Set?f.set:typeof Date<"u"&&a instanceof Date?f.date:f.object;default:return f.unknown}},u=C.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 D 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:[]},s=n=>{for(const r of n.issues)if(r.code==="invalid_union")r.unionErrors.map(s);else if(r.code==="invalid_return_type")s(r.returnTypeError);else if(r.code==="invalid_arguments")s(r.argumentsError);else if(r.path.length===0)i._errors.push(t(r));else{let o=i,l=0;for(;l<r.path.length;){const c=r.path[l];l===r.path.length-1?(o[c]=o[c]||{_errors:[]},o[c]._errors.push(t(r))):o[c]=o[c]||{_errors:[]},o=o[c],l++}}};return s(this),i}static assert(e){if(!(e instanceof D))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,C.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},i=[];for(const s of this.issues)s.path.length>0?(t[s.path[0]]=t[s.path[0]]||[],t[s.path[0]].push(e(s))):i.push(e(s));return{formErrors:i,fieldErrors:t}}get formErrors(){return this.flatten()}}D.create=a=>new D(a);const xe=(a,e)=>{let t;switch(a.code){case u.invalid_type:a.received===f.undefined?t="Required":t=`Expected ${a.expected}, received ${a.received}`;break;case u.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(a.expected,C.jsonStringifyReplacer)}`;break;case u.unrecognized_keys:t=`Unrecognized key(s) in object: ${C.joinValues(a.keys,", ")}`;break;case u.invalid_union:t="Invalid input";break;case u.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${C.joinValues(a.options)}`;break;case u.invalid_enum_value:t=`Invalid enum value. Expected ${C.joinValues(a.options)}, received '${a.received}'`;break;case u.invalid_arguments:t="Invalid function arguments";break;case u.invalid_return_type:t="Invalid function return type";break;case u.invalid_date:t="Invalid date";break;case u.invalid_string:typeof a.validation=="object"?"includes"in a.validation?(t=`Invalid input: must include "${a.validation.includes}"`,typeof a.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${a.validation.position}`)):"startsWith"in a.validation?t=`Invalid input: must start with "${a.validation.startsWith}"`:"endsWith"in a.validation?t=`Invalid input: must end with "${a.validation.endsWith}"`:C.assertNever(a.validation):a.validation!=="regex"?t=`Invalid ${a.validation}`:t="Invalid";break;case u.too_small:a.type==="array"?t=`Array must contain ${a.exact?"exactly":a.inclusive?"at least":"more than"} ${a.minimum} element(s)`:a.type==="string"?t=`String must contain ${a.exact?"exactly":a.inclusive?"at least":"over"} ${a.minimum} character(s)`:a.type==="number"?t=`Number must be ${a.exact?"exactly equal to ":a.inclusive?"greater than or equal to ":"greater than "}${a.minimum}`:a.type==="date"?t=`Date must be ${a.exact?"exactly equal to ":a.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(a.minimum))}`:t="Invalid input";break;case u.too_big:a.type==="array"?t=`Array must contain ${a.exact?"exactly":a.inclusive?"at most":"less than"} ${a.maximum} element(s)`:a.type==="string"?t=`String must contain ${a.exact?"exactly":a.inclusive?"at most":"under"} ${a.maximum} character(s)`:a.type==="number"?t=`Number must be ${a.exact?"exactly":a.inclusive?"less than or equal to":"less than"} ${a.maximum}`:a.type==="bigint"?t=`BigInt must be ${a.exact?"exactly":a.inclusive?"less than or equal to":"less than"} ${a.maximum}`:a.type==="date"?t=`Date must be ${a.exact?"exactly":a.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(a.maximum))}`:t="Invalid input";break;case u.custom:t="Invalid input";break;case u.invalid_intersection_types:t="Intersection results could not be merged";break;case u.not_multiple_of:t=`Number must be a multiple of ${a.multipleOf}`;break;case u.not_finite:t="Number must be finite";break;default:t=e.defaultError,C.assertNever(a)}return{message:t}};let Ut=xe;function We(){return Ut}const Xe=a=>{const{data:e,path:t,errorMaps:i,issueData:s}=a,n=[...t,...s.path||[]],r={...s,path:n};if(s.message!==void 0)return{...s,path:n,message:s.message};let o="";const l=i.filter(c=>!!c).slice().reverse();for(const c of l)o=c(r,{data:e,defaultError:o}).message;return{...s,path:n,message:o}};function d(a,e){const t=We(),i=Xe({issueData:e,data:a.data,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,t,t===xe?void 0:xe].filter(s=>!!s)});a.common.issues.push(i)}class z{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 s of t){if(s.status==="aborted")return w;s.status==="dirty"&&e.dirty(),i.push(s.value)}return{status:e.value,value:i}}static async mergeObjectAsync(e,t){const i=[];for(const s of t){const n=await s.key,r=await s.value;i.push({key:n,value:r})}return z.mergeObjectSync(e,i)}static mergeObjectSync(e,t){const i={};for(const s of t){const{key:n,value:r}=s;if(n.status==="aborted"||r.status==="aborted")return w;n.status==="dirty"&&e.dirty(),r.status==="dirty"&&e.dirty(),n.value!=="__proto__"&&(typeof r.value<"u"||s.alwaysSet)&&(i[n.value]=r.value)}return{status:e.value,value:i}}}const w=Object.freeze({status:"aborted"}),we=a=>({status:"dirty",value:a}),E=a=>({status:"valid",value:a}),mt=a=>a.status==="aborted",gt=a=>a.status==="dirty",he=a=>a.status==="valid",Pe=a=>typeof Promise<"u"&&a instanceof Promise;function Ie(a,e,t,i){if(typeof e=="function"?a!==e||!0:!e.has(a))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(a)}function yt(a,e,t,i,s){if(typeof e=="function"?a!==e||!0:!e.has(a))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(a,t),t}typeof SuppressedError=="function"&&SuppressedError;var m;(function(a){a.errToObj=e=>typeof e=="string"?{message:e}:e||{},a.toString=e=>typeof e=="string"?e:e?.message})(m||(m={}));var _e,ke;class K{constructor(e,t,i,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=i,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const vt=(a,e)=>{if(he(e))return{success:!0,data:e.value};if(!a.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 D(a.common.issues);return this._error=t,this._error}}};function _(a){if(!a)return{};const{errorMap:e,invalid_type_error:t,required_error:i,description:s}=a;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:s}:{errorMap:(r,o)=>{var l,c;const{message:h}=a;return r.code==="invalid_enum_value"?{message:h??o.defaultError}:typeof o.data>"u"?{message:(l=h??i)!==null&&l!==void 0?l:o.defaultError}:r.code!=="invalid_type"?{message:o.defaultError}:{message:(c=h??t)!==null&&c!==void 0?c:o.defaultError}},description:s}}class b{get description(){return this._def.description}_getType(e){return G(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:G(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new z,ctx:{common:e.parent.common,data:e.data,parsedType:G(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(Pe(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 s={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:G(e)},n=this._parseSync({data:e,path:s.path,parent:s});return vt(s,n)}"~validate"(e){var t,i;const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:G(e)};if(!this["~standard"].async)try{const n=this._parseSync({data:e,path:[],parent:s});return he(n)?{value:n.value}:{issues:s.common.issues}}catch(n){!((i=(t=n?.message)===null||t===void 0?void 0:t.toLowerCase())===null||i===void 0)&&i.includes("encountered")&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:s}).then(n=>he(n)?{value:n.value}:{issues:s.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:G(e)},s=this._parse({data:e,path:i.path,parent:i}),n=await(Pe(s)?s:Promise.resolve(s));return vt(i,n)}refine(e,t){const i=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,n)=>{const r=e(s),o=()=>n.addIssue({code:u.custom,...i(s)});return typeof Promise<"u"&&r instanceof Promise?r.then(l=>l?!0:(o(),!1)):r?!0:(o(),!1)})}refinement(e,t){return this._refinement((i,s)=>e(i)?!0:(s.addIssue(typeof t=="function"?t(i,s):t),!1))}_refinement(e){return new U({schema:this,typeName:x.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 W.create(this,this._def)}nullable(){return ie.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return H.create(this)}promise(){return Se.create(this,this._def)}or(e){return Le.create([this,e],this._def)}and(e){return Ee.create(this,e,this._def)}transform(e){return new U({..._(this._def),schema:this,typeName:x.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Ze({..._(this._def),innerType:this,defaultValue:t,typeName:x.ZodDefault})}brand(){return new kt({typeName:x.ZodBranded,type:this,..._(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Ve({..._(this._def),innerType:this,catchValue:t,typeName:x.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return Ke.create(this,e)}readonly(){return He.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Wt=/^c[^\s-]{8,}$/i,Xt=/^[0-9a-z]+$/,Yt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,qt=/^[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,Gt=/^[a-z0-9_-]{21}$/i,Qt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Jt=/^[-+]?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)?)??$/,ei=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ti="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Ye;const ii=/^(?:(?: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])$/,si=/^(?:(?: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])$/,ni=/^(([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]))$/,ai=/^(([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])$/,ri=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,oi=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,xt="((\\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])))",ci=new RegExp(`^${xt}$`);function wt(a){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return a.precision?e=`${e}\\.\\d{${a.precision}}`:a.precision==null&&(e=`${e}(\\.\\d+)?`),e}function li(a){return new RegExp(`^${wt(a)}$`)}function hi(a){let e=`${xt}T${wt(a)}`;const t=[];return t.push(a.local?"Z?":"Z"),a.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function ui(a,e){return!!((e==="v4"||!e)&&ii.test(a)||(e==="v6"||!e)&&ni.test(a))}function di(a,e){if(!Qt.test(a))return!1;try{const[t]=a.split("."),i=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(i));return!(typeof s!="object"||s===null||!s.typ||!s.alg||e&&s.alg!==e)}catch{return!1}}function fi(a,e){return!!((e==="v4"||!e)&&si.test(a)||(e==="v6"||!e)&&ai.test(a))}class B extends b{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==f.string){const n=this._getOrReturnCtx(e);return d(n,{code:u.invalid_type,expected:f.string,received:n.parsedType}),w}const i=new z;let s;for(const n of this._def.checks)if(n.kind==="min")e.data.length<n.value&&(s=this._getOrReturnCtx(e,s),d(s,{code:u.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&&(s=this._getOrReturnCtx(e,s),d(s,{code:u.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),i.dirty());else if(n.kind==="length"){const r=e.data.length>n.value,o=e.data.length<n.value;(r||o)&&(s=this._getOrReturnCtx(e,s),r?d(s,{code:u.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):o&&d(s,{code:u.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),i.dirty())}else if(n.kind==="email")ei.test(e.data)||(s=this._getOrReturnCtx(e,s),d(s,{validation:"email",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="emoji")Ye||(Ye=new RegExp(ti,"u")),Ye.test(e.data)||(s=this._getOrReturnCtx(e,s),d(s,{validation:"emoji",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="uuid")qt.test(e.data)||(s=this._getOrReturnCtx(e,s),d(s,{validation:"uuid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="nanoid")Gt.test(e.data)||(s=this._getOrReturnCtx(e,s),d(s,{validation:"nanoid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="cuid")Wt.test(e.data)||(s=this._getOrReturnCtx(e,s),d(s,{validation:"cuid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="cuid2")Xt.test(e.data)||(s=this._getOrReturnCtx(e,s),d(s,{validation:"cuid2",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="ulid")Yt.test(e.data)||(s=this._getOrReturnCtx(e,s),d(s,{validation:"ulid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),d(s,{validation:"url",code:u.invalid_string,message:n.message}),i.dirty()}else n.kind==="regex"?(n.regex.lastIndex=0,n.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),d(s,{validation:"regex",code:u.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)||(s=this._getOrReturnCtx(e,s),d(s,{code:u.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)||(s=this._getOrReturnCtx(e,s),d(s,{code:u.invalid_string,validation:{startsWith:n.value},message:n.message}),i.dirty()):n.kind==="endsWith"?e.data.endsWith(n.value)||(s=this._getOrReturnCtx(e,s),d(s,{code:u.invalid_string,validation:{endsWith:n.value},message:n.message}),i.dirty()):n.kind==="datetime"?hi(n).test(e.data)||(s=this._getOrReturnCtx(e,s),d(s,{code:u.invalid_string,validation:"datetime",message:n.message}),i.dirty()):n.kind==="date"?ci.test(e.data)||(s=this._getOrReturnCtx(e,s),d(s,{code:u.invalid_string,validation:"date",message:n.message}),i.dirty()):n.kind==="time"?li(n).test(e.data)||(s=this._getOrReturnCtx(e,s),d(s,{code:u.invalid_string,validation:"time",message:n.message}),i.dirty()):n.kind==="duration"?Jt.test(e.data)||(s=this._getOrReturnCtx(e,s),d(s,{validation:"duration",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="ip"?ui(e.data,n.version)||(s=this._getOrReturnCtx(e,s),d(s,{validation:"ip",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="jwt"?di(e.data,n.alg)||(s=this._getOrReturnCtx(e,s),d(s,{validation:"jwt",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="cidr"?fi(e.data,n.version)||(s=this._getOrReturnCtx(e,s),d(s,{validation:"cidr",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="base64"?ri.test(e.data)||(s=this._getOrReturnCtx(e,s),d(s,{validation:"base64",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="base64url"?oi.test(e.data)||(s=this._getOrReturnCtx(e,s),d(s,{validation:"base64url",code:u.invalid_string,message:n.message}),i.dirty()):C.assertNever(n);return{status:i.value,value:e.data}}_regex(e,t,i){return this.refinement(s=>e.test(s),{validation:t,code:u.invalid_string,...m.errToObj(i)})}_addCheck(e){return new B({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...m.errToObj(e)})}url(e){return this._addCheck({kind:"url",...m.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...m.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...m.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...m.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...m.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...m.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...m.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...m.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...m.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...m.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...m.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...m.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,...m.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,...m.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...m.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...m.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...m.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...m.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...m.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...m.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...m.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...m.errToObj(t)})}nonempty(e){return this.min(1,m.errToObj(e))}trim(){return new B({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new B({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new B({...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}}B.create=a=>{var e;return new B({checks:[],typeName:x.ZodString,coerce:(e=a?.coerce)!==null&&e!==void 0?e:!1,..._(a)})};function pi(a,e){const t=(a.toString().split(".")[1]||"").length,i=(e.toString().split(".")[1]||"").length,s=t>i?t:i,n=parseInt(a.toFixed(s).replace(".","")),r=parseInt(e.toFixed(s).replace(".",""));return n%r/Math.pow(10,s)}class ue extends b{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)!==f.number){const n=this._getOrReturnCtx(e);return d(n,{code:u.invalid_type,expected:f.number,received:n.parsedType}),w}let i;const s=new z;for(const n of this._def.checks)n.kind==="int"?C.isInteger(e.data)||(i=this._getOrReturnCtx(e,i),d(i,{code:u.invalid_type,expected:"integer",received:"float",message:n.message}),s.dirty()):n.kind==="min"?(n.inclusive?e.data<n.value:e.data<=n.value)&&(i=this._getOrReturnCtx(e,i),d(i,{code:u.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),s.dirty()):n.kind==="max"?(n.inclusive?e.data>n.value:e.data>=n.value)&&(i=this._getOrReturnCtx(e,i),d(i,{code:u.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),s.dirty()):n.kind==="multipleOf"?pi(e.data,n.value)!==0&&(i=this._getOrReturnCtx(e,i),d(i,{code:u.not_multiple_of,multipleOf:n.value,message:n.message}),s.dirty()):n.kind==="finite"?Number.isFinite(e.data)||(i=this._getOrReturnCtx(e,i),d(i,{code:u.not_finite,message:n.message}),s.dirty()):C.assertNever(n);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,m.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.toString(t))}setLimit(e,t,i,s){return new ue({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:m.toString(s)}]})}_addCheck(e){return new ue({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:m.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:m.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:m.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:m.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"&&C.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)}}ue.create=a=>new ue({checks:[],typeName:x.ZodNumber,coerce:a?.coerce||!1,..._(a)});class de extends b{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)!==f.bigint)return this._getInvalidInput(e);let i;const s=new z;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),d(i,{code:u.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),s.dirty()):n.kind==="max"?(n.inclusive?e.data>n.value:e.data>=n.value)&&(i=this._getOrReturnCtx(e,i),d(i,{code:u.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),s.dirty()):n.kind==="multipleOf"?e.data%n.value!==BigInt(0)&&(i=this._getOrReturnCtx(e,i),d(i,{code:u.not_multiple_of,multipleOf:n.value,message:n.message}),s.dirty()):C.assertNever(n);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return d(t,{code:u.invalid_type,expected:f.bigint,received:t.parsedType}),w}gte(e,t){return this.setLimit("min",e,!0,m.toString(t))}gt(e,t){return this.setLimit("min",e,!1,m.toString(t))}lte(e,t){return this.setLimit("max",e,!0,m.toString(t))}lt(e,t){return this.setLimit("max",e,!1,m.toString(t))}setLimit(e,t,i,s){return new de({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:i,message:m.toString(s)}]})}_addCheck(e){return new de({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:m.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:m.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}}de.create=a=>{var e;return new de({checks:[],typeName:x.ZodBigInt,coerce:(e=a?.coerce)!==null&&e!==void 0?e:!1,..._(a)})};class qe extends b{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==f.boolean){const i=this._getOrReturnCtx(e);return d(i,{code:u.invalid_type,expected:f.boolean,received:i.parsedType}),w}return E(e.data)}}qe.create=a=>new qe({typeName:x.ZodBoolean,coerce:a?.coerce||!1,..._(a)});class be extends b{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==f.date){const n=this._getOrReturnCtx(e);return d(n,{code:u.invalid_type,expected:f.date,received:n.parsedType}),w}if(isNaN(e.data.getTime())){const n=this._getOrReturnCtx(e);return d(n,{code:u.invalid_date}),w}const i=new z;let s;for(const n of this._def.checks)n.kind==="min"?e.data.getTime()<n.value&&(s=this._getOrReturnCtx(e,s),d(s,{code:u.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),i.dirty()):n.kind==="max"?e.data.getTime()>n.value&&(s=this._getOrReturnCtx(e,s),d(s,{code:u.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),i.dirty()):C.assertNever(n);return{status:i.value,value:new Date(e.data.getTime())}}_addCheck(e){return new be({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:m.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:m.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}}be.create=a=>new be({checks:[],coerce:a?.coerce||!1,typeName:x.ZodDate,..._(a)});class Ge extends b{_parse(e){if(this._getType(e)!==f.symbol){const i=this._getOrReturnCtx(e);return d(i,{code:u.invalid_type,expected:f.symbol,received:i.parsedType}),w}return E(e.data)}}Ge.create=a=>new Ge({typeName:x.ZodSymbol,..._(a)});class Re extends b{_parse(e){if(this._getType(e)!==f.undefined){const i=this._getOrReturnCtx(e);return d(i,{code:u.invalid_type,expected:f.undefined,received:i.parsedType}),w}return E(e.data)}}Re.create=a=>new Re({typeName:x.ZodUndefined,..._(a)});class ze extends b{_parse(e){if(this._getType(e)!==f.null){const i=this._getOrReturnCtx(e);return d(i,{code:u.invalid_type,expected:f.null,received:i.parsedType}),w}return E(e.data)}}ze.create=a=>new ze({typeName:x.ZodNull,..._(a)});class Qe extends b{constructor(){super(...arguments),this._any=!0}_parse(e){return E(e.data)}}Qe.create=a=>new Qe({typeName:x.ZodAny,..._(a)});class fe extends b{constructor(){super(...arguments),this._unknown=!0}_parse(e){return E(e.data)}}fe.create=a=>new fe({typeName:x.ZodUnknown,..._(a)});class Q extends b{_parse(e){const t=this._getOrReturnCtx(e);return d(t,{code:u.invalid_type,expected:f.never,received:t.parsedType}),w}}Q.create=a=>new Q({typeName:x.ZodNever,..._(a)});class Je extends b{_parse(e){if(this._getType(e)!==f.undefined){const i=this._getOrReturnCtx(e);return d(i,{code:u.invalid_type,expected:f.void,received:i.parsedType}),w}return E(e.data)}}Je.create=a=>new Je({typeName:x.ZodVoid,..._(a)});class H extends b{_parse(e){const{ctx:t,status:i}=this._processInputParams(e),s=this._def;if(t.parsedType!==f.array)return d(t,{code:u.invalid_type,expected:f.array,received:t.parsedType}),w;if(s.exactLength!==null){const r=t.data.length>s.exactLength.value,o=t.data.length<s.exactLength.value;(r||o)&&(d(t,{code:r?u.too_big:u.too_small,minimum:o?s.exactLength.value:void 0,maximum:r?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),i.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(d(t,{code:u.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),i.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(d(t,{code:u.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),i.dirty()),t.common.async)return Promise.all([...t.data].map((r,o)=>s.type._parseAsync(new K(t,r,t.path,o)))).then(r=>z.mergeArray(i,r));const n=[...t.data].map((r,o)=>s.type._parseSync(new K(t,r,t.path,o)));return z.mergeArray(i,n)}get element(){return this._def.type}min(e,t){return new H({...this._def,minLength:{value:e,message:m.toString(t)}})}max(e,t){return new H({...this._def,maxLength:{value:e,message:m.toString(t)}})}length(e,t){return new H({...this._def,exactLength:{value:e,message:m.toString(t)}})}nonempty(e){return this.min(1,e)}}H.create=(a,e)=>new H({type:a,minLength:null,maxLength:null,exactLength:null,typeName:x.ZodArray,..._(e)});function pe(a){if(a instanceof P){const e={};for(const t in a.shape){const i=a.shape[t];e[t]=W.create(pe(i))}return new P({...a._def,shape:()=>e})}else return a instanceof H?new H({...a._def,type:pe(a.element)}):a instanceof W?W.create(pe(a.unwrap())):a instanceof ie?ie.create(pe(a.unwrap())):a instanceof $?$.create(a.items.map(e=>pe(e))):a}class P extends b{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=C.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==f.object){const c=this._getOrReturnCtx(e);return d(c,{code:u.invalid_type,expected:f.object,received:c.parsedType}),w}const{status:i,ctx:s}=this._processInputParams(e),{shape:n,keys:r}=this._getCached(),o=[];if(!(this._def.catchall instanceof Q&&this._def.unknownKeys==="strip"))for(const c in s.data)r.includes(c)||o.push(c);const l=[];for(const c of r){const h=n[c],g=s.data[c];l.push({key:{status:"valid",value:c},value:h._parse(new K(s,g,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof Q){const c=this._def.unknownKeys;if(c==="passthrough")for(const h of o)l.push({key:{status:"valid",value:h},value:{status:"valid",value:s.data[h]}});else if(c==="strict")o.length>0&&(d(s,{code:u.unrecognized_keys,keys:o}),i.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const h of o){const g=s.data[h];l.push({key:{status:"valid",value:h},value:c._parse(new K(s,g,s.path,h)),alwaysSet:h in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const c=[];for(const h of l){const g=await h.key,p=await h.value;c.push({key:g,value:p,alwaysSet:h.alwaysSet})}return c}).then(c=>z.mergeObjectSync(i,c)):z.mergeObjectSync(i,l)}get shape(){return this._def.shape()}strict(e){return m.errToObj,new P({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,i)=>{var s,n,r,o;const l=(r=(n=(s=this._def).errorMap)===null||n===void 0?void 0:n.call(s,t,i).message)!==null&&r!==void 0?r:i.defaultError;return t.code==="unrecognized_keys"?{message:(o=m.errToObj(e).message)!==null&&o!==void 0?o:l}:{message:l}}}:{}})}strip(){return new P({...this._def,unknownKeys:"strip"})}passthrough(){return new P({...this._def,unknownKeys:"passthrough"})}extend(e){return new P({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new P({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:x.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new P({...this._def,catchall:e})}pick(e){const t={};return C.objectKeys(e).forEach(i=>{e[i]&&this.shape[i]&&(t[i]=this.shape[i])}),new P({...this._def,shape:()=>t})}omit(e){const t={};return C.objectKeys(this.shape).forEach(i=>{e[i]||(t[i]=this.shape[i])}),new P({...this._def,shape:()=>t})}deepPartial(){return pe(this)}partial(e){const t={};return C.objectKeys(this.shape).forEach(i=>{const s=this.shape[i];e&&!e[i]?t[i]=s:t[i]=s.optional()}),new P({...this._def,shape:()=>t})}required(e){const t={};return C.objectKeys(this.shape).forEach(i=>{if(e&&!e[i])t[i]=this.shape[i];else{let n=this.shape[i];for(;n instanceof W;)n=n._def.innerType;t[i]=n}}),new P({...this._def,shape:()=>t})}keyof(){return _t(C.objectKeys(this.shape))}}P.create=(a,e)=>new P({shape:()=>a,unknownKeys:"strip",catchall:Q.create(),typeName:x.ZodObject,..._(e)}),P.strictCreate=(a,e)=>new P({shape:()=>a,unknownKeys:"strict",catchall:Q.create(),typeName:x.ZodObject,..._(e)}),P.lazycreate=(a,e)=>new P({shape:a,unknownKeys:"strip",catchall:Q.create(),typeName:x.ZodObject,..._(e)});class Le extends b{_parse(e){const{ctx:t}=this._processInputParams(e),i=this._def.options;function s(n){for(const o of n)if(o.result.status==="valid")return o.result;for(const o of n)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;const r=n.map(o=>new D(o.ctx.common.issues));return d(t,{code:u.invalid_union,unionErrors:r}),w}if(t.common.async)return Promise.all(i.map(async n=>{const r={...t,common:{...t.common,issues:[]},parent:null};return{result:await n._parseAsync({data:t.data,path:t.path,parent:r}),ctx:r}})).then(s);{let n;const r=[];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"&&!n&&(n={result:h,ctx:c}),c.common.issues.length&&r.push(c.common.issues)}if(n)return t.common.issues.push(...n.ctx.common.issues),n.result;const o=r.map(l=>new D(l));return d(t,{code:u.invalid_union,unionErrors:o}),w}}get options(){return this._def.options}}Le.create=(a,e)=>new Le({options:a,typeName:x.ZodUnion,..._(e)});const j=a=>a instanceof Fe?j(a.schema):a instanceof U?j(a.innerType()):a instanceof De?[a.value]:a instanceof te?a.options:a instanceof Ne?C.objectValues(a.enum):a instanceof Ze?j(a._def.innerType):a instanceof Re?[void 0]:a instanceof ze?[null]:a instanceof W?[void 0,...j(a.unwrap())]:a instanceof ie?[null,...j(a.unwrap())]:a instanceof kt||a instanceof He?j(a.unwrap()):a instanceof Ve?j(a._def.innerType):[];class et extends b{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.object)return d(t,{code:u.invalid_type,expected:f.object,received:t.parsedType}),w;const i=this.discriminator,s=t.data[i],n=this.optionsMap.get(s);return n?t.common.async?n._parseAsync({data:t.data,path:t.path,parent:t}):n._parseSync({data:t.data,path:t.path,parent:t}):(d(t,{code:u.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),w)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,i){const s=new Map;for(const n of t){const r=j(n.shape[e]);if(!r.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of r){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,n)}}return new et({typeName:x.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,..._(i)})}}function tt(a,e){const t=G(a),i=G(e);if(a===e)return{valid:!0,data:a};if(t===f.object&&i===f.object){const s=C.objectKeys(e),n=C.objectKeys(a).filter(o=>s.indexOf(o)!==-1),r={...a,...e};for(const o of n){const l=tt(a[o],e[o]);if(!l.valid)return{valid:!1};r[o]=l.data}return{valid:!0,data:r}}else if(t===f.array&&i===f.array){if(a.length!==e.length)return{valid:!1};const s=[];for(let n=0;n<a.length;n++){const r=a[n],o=e[n],l=tt(r,o);if(!l.valid)return{valid:!1};s.push(l.data)}return{valid:!0,data:s}}else return t===f.date&&i===f.date&&+a==+e?{valid:!0,data:a}:{valid:!1}}class Ee extends b{_parse(e){const{status:t,ctx:i}=this._processInputParams(e),s=(n,r)=>{if(mt(n)||mt(r))return w;const o=tt(n.value,r.value);return o.valid?((gt(n)||gt(r))&&t.dirty(),{status:t.value,value:o.data}):(d(i,{code:u.invalid_intersection_types}),w)};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,r])=>s(n,r)):s(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}Ee.create=(a,e,t)=>new Ee({left:a,right:e,typeName:x.ZodIntersection,..._(t)});class $ extends b{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==f.array)return d(i,{code:u.invalid_type,expected:f.array,received:i.parsedType}),w;if(i.data.length<this._def.items.length)return d(i,{code:u.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w;!this._def.rest&&i.data.length>this._def.items.length&&(d(i,{code:u.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const n=[...i.data].map((r,o)=>{const l=this._def.items[o]||this._def.rest;return l?l._parse(new K(i,r,i.path,o)):null}).filter(r=>!!r);return i.common.async?Promise.all(n).then(r=>z.mergeArray(t,r)):z.mergeArray(t,n)}get items(){return this._def.items}rest(e){return new $({...this._def,rest:e})}}$.create=(a,e)=>{if(!Array.isArray(a))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new $({items:a,typeName:x.ZodTuple,rest:null,..._(e)})};class Me extends b{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!==f.object)return d(i,{code:u.invalid_type,expected:f.object,received:i.parsedType}),w;const s=[],n=this._def.keyType,r=this._def.valueType;for(const o in i.data)s.push({key:n._parse(new K(i,o,i.path,o)),value:r._parse(new K(i,i.data[o],i.path,o)),alwaysSet:o in i.data});return i.common.async?z.mergeObjectAsync(t,s):z.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,i){return t instanceof b?new Me({keyType:e,valueType:t,typeName:x.ZodRecord,..._(i)}):new Me({keyType:B.create(),valueType:e,typeName:x.ZodRecord,..._(t)})}}class it extends b{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!==f.map)return d(i,{code:u.invalid_type,expected:f.map,received:i.parsedType}),w;const s=this._def.keyType,n=this._def.valueType,r=[...i.data.entries()].map(([o,l],c)=>({key:s._parse(new K(i,o,i.path,[c,"key"])),value:n._parse(new K(i,l,i.path,[c,"value"]))}));if(i.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const l of r){const c=await l.key,h=await l.value;if(c.status==="aborted"||h.status==="aborted")return w;(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 r){const c=l.key,h=l.value;if(c.status==="aborted"||h.status==="aborted")return w;(c.status==="dirty"||h.status==="dirty")&&t.dirty(),o.set(c.value,h.value)}return{status:t.value,value:o}}}}it.create=(a,e,t)=>new it({valueType:e,keyType:a,typeName:x.ZodMap,..._(t)});class me extends b{_parse(e){const{status:t,ctx:i}=this._processInputParams(e);if(i.parsedType!==f.set)return d(i,{code:u.invalid_type,expected:f.set,received:i.parsedType}),w;const s=this._def;s.minSize!==null&&i.data.size<s.minSize.value&&(d(i,{code:u.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&i.data.size>s.maxSize.value&&(d(i,{code:u.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const n=this._def.valueType;function r(l){const c=new Set;for(const h of l){if(h.status==="aborted")return w;h.status==="dirty"&&t.dirty(),c.add(h.value)}return{status:t.value,value:c}}const o=[...i.data.values()].map((l,c)=>n._parse(new K(i,l,i.path,c)));return i.common.async?Promise.all(o).then(l=>r(l)):r(o)}min(e,t){return new me({...this._def,minSize:{value:e,message:m.toString(t)}})}max(e,t){return new me({...this._def,maxSize:{value:e,message:m.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}me.create=(a,e)=>new me({valueType:a,minSize:null,maxSize:null,typeName:x.ZodSet,..._(e)});class Ce extends b{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.function)return d(t,{code:u.invalid_type,expected:f.function,received:t.parsedType}),w;function i(o,l){return Xe({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,We(),xe].filter(c=>!!c),issueData:{code:u.invalid_arguments,argumentsError:l}})}function s(o,l){return Xe({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,We(),xe].filter(c=>!!c),issueData:{code:u.invalid_return_type,returnTypeError:l}})}const n={errorMap:t.common.contextualErrorMap},r=t.data;if(this._def.returns instanceof Se){const o=this;return E(async function(...l){const c=new D([]),h=await o._def.args.parseAsync(l,n).catch(k=>{throw c.addIssue(i(l,k)),c}),g=await Reflect.apply(r,this,h);return await o._def.returns._def.type.parseAsync(g,n).catch(k=>{throw c.addIssue(s(g,k)),c})})}else{const o=this;return E(function(...l){const c=o._def.args.safeParse(l,n);if(!c.success)throw new D([i(l,c.error)]);const h=Reflect.apply(r,this,c.data),g=o._def.returns.safeParse(h,n);if(!g.success)throw new D([s(h,g.error)]);return g.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new Ce({...this._def,args:$.create(e).rest(fe.create())})}returns(e){return new Ce({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,i){return new Ce({args:e||$.create([]).rest(fe.create()),returns:t||fe.create(),typeName:x.ZodFunction,..._(i)})}}class Fe extends b{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})}}Fe.create=(a,e)=>new Fe({getter:a,typeName:x.ZodLazy,..._(e)});class De extends b{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return d(t,{received:t.data,code:u.invalid_literal,expected:this._def.value}),w}return{status:"valid",value:e.data}}get value(){return this._def.value}}De.create=(a,e)=>new De({value:a,typeName:x.ZodLiteral,..._(e)});function _t(a,e){return new te({values:a,typeName:x.ZodEnum,..._(e)})}class te extends b{constructor(){super(...arguments),_e.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),i=this._def.values;return d(t,{expected:C.joinValues(i),received:t.parsedType,code:u.invalid_type}),w}if(Ie(this,_e)||yt(this,_e,new Set(this._def.values)),!Ie(this,_e).has(e.data)){const t=this._getOrReturnCtx(e),i=this._def.values;return d(t,{received:t.data,code:u.invalid_enum_value,options:i}),w}return E(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 te.create(e,{...this._def,...t})}exclude(e,t=this._def){return te.create(this.options.filter(i=>!e.includes(i)),{...this._def,...t})}}_e=new WeakMap,te.create=_t;class Ne extends b{constructor(){super(...arguments),ke.set(this,void 0)}_parse(e){const t=C.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(e);if(i.parsedType!==f.string&&i.parsedType!==f.number){const s=C.objectValues(t);return d(i,{expected:C.joinValues(s),received:i.parsedType,code:u.invalid_type}),w}if(Ie(this,ke)||yt(this,ke,new Set(C.getValidEnumValues(this._def.values))),!Ie(this,ke).has(e.data)){const s=C.objectValues(t);return d(i,{received:i.data,code:u.invalid_enum_value,options:s}),w}return E(e.data)}get enum(){return this._def.values}}ke=new WeakMap,Ne.create=(a,e)=>new Ne({values:a,typeName:x.ZodNativeEnum,..._(e)});class Se extends b{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.promise&&t.common.async===!1)return d(t,{code:u.invalid_type,expected:f.promise,received:t.parsedType}),w;const i=t.parsedType===f.promise?t.data:Promise.resolve(t.data);return E(i.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}}Se.create=(a,e)=>new Se({type:a,typeName:x.ZodPromise,..._(e)});class U extends b{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===x.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:i}=this._processInputParams(e),s=this._def.effect||null,n={addIssue:r=>{d(i,r),r.fatal?t.abort():t.dirty()},get path(){return i.path}};if(n.addIssue=n.addIssue.bind(n),s.type==="preprocess"){const r=s.transform(i.data,n);if(i.common.async)return Promise.resolve(r).then(async o=>{if(t.value==="aborted")return w;const l=await this._def.schema._parseAsync({data:o,path:i.path,parent:i});return l.status==="aborted"?w:l.status==="dirty"||t.value==="dirty"?we(l.value):l});{if(t.value==="aborted")return w;const o=this._def.schema._parseSync({data:r,path:i.path,parent:i});return o.status==="aborted"?w:o.status==="dirty"||t.value==="dirty"?we(o.value):o}}if(s.type==="refinement"){const r=o=>{const l=s.refinement(o,n);if(i.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(i.common.async===!1){const o=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});return o.status==="aborted"?w:(o.status==="dirty"&&t.dirty(),r(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"?w:(o.status==="dirty"&&t.dirty(),r(o.value).then(()=>({status:t.value,value:o.value}))))}if(s.type==="transform")if(i.common.async===!1){const r=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!he(r))return r;const o=s.transform(r.value,n);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(r=>he(r)?Promise.resolve(s.transform(r.value,n)).then(o=>({status:t.value,value:o})):r);C.assertNever(s)}}U.create=(a,e,t)=>new U({schema:a,typeName:x.ZodEffects,effect:e,..._(t)}),U.createWithPreprocess=(a,e,t)=>new U({schema:e,effect:{type:"preprocess",transform:a},typeName:x.ZodEffects,..._(t)});class W extends b{_parse(e){return this._getType(e)===f.undefined?E(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}W.create=(a,e)=>new W({innerType:a,typeName:x.ZodOptional,..._(e)});class ie extends b{_parse(e){return this._getType(e)===f.null?E(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}ie.create=(a,e)=>new ie({innerType:a,typeName:x.ZodNullable,..._(e)});class Ze extends b{_parse(e){const{ctx:t}=this._processInputParams(e);let i=t.data;return t.parsedType===f.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Ze.create=(a,e)=>new Ze({innerType:a,typeName:x.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,..._(e)});class Ve extends b{_parse(e){const{ctx:t}=this._processInputParams(e),i={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return Pe(s)?s.then(n=>({status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new D(i.common.issues)},input:i.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new D(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}Ve.create=(a,e)=>new Ve({innerType:a,typeName:x.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,..._(e)});class st extends b{_parse(e){if(this._getType(e)!==f.nan){const i=this._getOrReturnCtx(e);return d(i,{code:u.invalid_type,expected:f.nan,received:i.parsedType}),w}return{status:"valid",value:e.data}}}st.create=a=>new st({typeName:x.ZodNaN,..._(a)});class kt extends b{_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 Ke extends b{_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"?w:n.status==="dirty"?(t.dirty(),we(n.value)):this._def.out._parseAsync({data:n.value,path:i.path,parent:i})})();{const s=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return s.status==="aborted"?w:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:i.path,parent:i})}}static create(e,t){return new Ke({in:e,out:t,typeName:x.ZodPipeline})}}class He extends b{_parse(e){const t=this._def.innerType._parse(e),i=s=>(he(s)&&(s.value=Object.freeze(s.value)),s);return Pe(t)?t.then(s=>i(s)):i(t)}unwrap(){return this._def.innerType}}He.create=(a,e)=>new He({innerType:a,typeName:x.ZodReadonly,..._(e)}),P.lazycreate;var x;(function(a){a.ZodString="ZodString",a.ZodNumber="ZodNumber",a.ZodNaN="ZodNaN",a.ZodBigInt="ZodBigInt",a.ZodBoolean="ZodBoolean",a.ZodDate="ZodDate",a.ZodSymbol="ZodSymbol",a.ZodUndefined="ZodUndefined",a.ZodNull="ZodNull",a.ZodAny="ZodAny",a.ZodUnknown="ZodUnknown",a.ZodNever="ZodNever",a.ZodVoid="ZodVoid",a.ZodArray="ZodArray",a.ZodObject="ZodObject",a.ZodUnion="ZodUnion",a.ZodDiscriminatedUnion="ZodDiscriminatedUnion",a.ZodIntersection="ZodIntersection",a.ZodTuple="ZodTuple",a.ZodRecord="ZodRecord",a.ZodMap="ZodMap",a.ZodSet="ZodSet",a.ZodFunction="ZodFunction",a.ZodLazy="ZodLazy",a.ZodLiteral="ZodLiteral",a.ZodEnum="ZodEnum",a.ZodEffects="ZodEffects",a.ZodNativeEnum="ZodNativeEnum",a.ZodOptional="ZodOptional",a.ZodNullable="ZodNullable",a.ZodDefault="ZodDefault",a.ZodCatch="ZodCatch",a.ZodPromise="ZodPromise",a.ZodBranded="ZodBranded",a.ZodPipeline="ZodPipeline",a.ZodReadonly="ZodReadonly"})(x||(x={}));const L=B.create,y=ue.create;st.create,de.create,qe.create,be.create,Ge.create,Re.create,ze.create,Qe.create,fe.create,Q.create,Je.create,H.create;const T=P.create;P.strictCreate;const mi=Le.create;et.create,Ee.create,$.create,Me.create,it.create,me.create,Ce.create,Fe.create;const se=De.create,J=te.create;Ne.create,Se.create,U.create,W.create,ie.create,U.createWithPreprocess,Ke.create;const gi=J(["linear","bezier","constant"]),yi=J(["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"]),ne=T({from:y(),to:y(),start:y().min(0),length:y().positive(),interpolation:gi.optional(),easing:yi.optional()}),vi=L().url("Invalid audio url format."),xi=ne.extend({from:y().min(0).max(1),to:y().min(0).max(1)}).array().or(y().min(0).max(1)),bt=T({type:se("audio"),src:vi,trim:y().optional(),volume:xi.optional()}),wi=J(["top","topRight","right","bottomRight","bottom","bottomLeft","left","topLeft","center"]),Ct=T({type:se("html"),html:L(),css:L(),width:y().positive().optional(),height:y().positive().optional(),position:wi.optional()}),_i=L().url("Invalid image url format."),ki=T({top:y().min(0).optional(),right:y().min(0).optional(),bottom:y().min(0).optional(),left:y().min(0).optional()}),St=T({type:se("image"),src:_i,crop:ki.optional()}),bi=L().url("Invalid luma url format."),Tt=T({type:se("luma"),src:bi}),Ot=L().regex(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})|transparent$/,"Invalid color format."),At=T({width:y().positive(),height:y().positive()}),Pt=T({radius:y().positive()}),It=T({length:y().positive(),thickness:y().positive()}),Ci=T({color:Ot,opacity:y().min(0).max(1)}),Si=T({color:Ot,width:y().positive()}),Rt=T({type:se("shape"),width:y().positive().optional(),height:y().positive().optional(),shape:J(["rectangle","circle","line"]),fill:Ci.optional(),stroke:Si.optional(),rectangle:At.optional(),circle:Pt.optional(),line:It.optional()}).refine(a=>a.shape==="rectangle"?At.safeParse(a.rectangle):a.shape==="circle"?Pt.safeParse(a.circle):a.shape==="line"?It.safeParse(a.line):!1),nt=L().regex(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})|transparent$/,"Invalid color format."),Ti=T({color:nt.optional(),family:L().optional(),size:y().positive().optional(),weight:y().optional(),lineHeight:y().optional()}),Oi=T({horizontal:J(["left","center","right"]).optional(),vertical:J(["top","center","bottom"]).optional()}),Ai=T({color:nt,opacity:y().min(0).max(1)}),Pi=T({width:y().positive(),color:nt}),zt=T({type:se("text"),text:L(),width:y().positive().optional(),height:y().positive().optional(),font:Ti.optional(),alignment:Oi.optional(),background:Ai.optional(),stroke:Pi.optional()}),Ii=L().url("Invalid video url format."),Ri=T({top:y().min(0).optional(),right:y().min(0).optional(),bottom:y().min(0).optional(),left:y().min(0).optional()}),zi=ne.extend({from:y().min(0).max(1),to:y().min(0).max(1)}).array().or(y().min(0).max(1)),Lt=T({type:se("video"),src:Ii,trim:y().optional(),crop:Ri.optional(),volume:zi.optional()}),Li=mi([zt,Rt,Ct,St,Lt,Tt,bt]).refine(a=>a.type==="text"?zt.safeParse(a):a.type==="shape"?Rt.safeParse(a):a.type==="html"?Ct.safeParse(a):a.type==="image"?St.safeParse(a):a.type==="video"?Lt.safeParse(a):a.type==="luma"?Tt.safeParse(a):a.type==="audio"?bt.safeParse(a):!1),Ei=J(["topLeft","top","topRight","left","center","right","bottomLeft","bottom","bottomRight"]),Mi=J(["crop","cover","contain","none"]),ge=y().min(-10).max(10).default(0),Fi=ne.extend({from:ge,to:ge}).array().or(ge),Di=ne.extend({from:ge,to:ge}).array().or(ge),Ni=T({x:Fi.default(0),y:Di.default(0)}),Zi=ne.extend({from:y().min(0).max(1),to:y().min(0).max(1)}).array().or(y().min(0).max(1)),Vi=ne.extend({from:y().min(0),to:y().min(0)}).array().or(y().min(0)),Ki=T({angle:ne.extend({from:y(),to:y()}).array().or(y())}),Hi=L(),Et=L(),Bi=T({in:Et.optional(),out:Et.optional()}),ji=T({rotate:Ki.default({angle:0})}),Mt=T({asset:Li,start:y().min(0),length:y().positive(),position:Ei.default("center").optional(),fit:Mi.default("crop").optional(),offset:Ni.default({x:0,y:0}).optional(),opacity:Zi.default(1).optional(),scale:Vi.default(1).optional(),transform:ji.default({rotate:{angle:0}}).optional(),effect:Hi.optional(),transition:Bi.optional()}),$i=T({clips:Mt.array()}),Ui=L().url("Invalid image url format."),Wi=T({src:Ui}),Xi=T({background:L().optional(),fonts:Wi.array().optional(),tracks:$i.array()}),Yi=T({size:T({width:y().positive(),height:y().positive()}),fps:y().positive().optional(),format:L()}),qi=T({timeline:Xi,output:Yi});class Gi{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,s){const n=this.curves[s??""]??this.curves.ease,[[r,o],[l,c]]=n,h=i+(3*r-3*l+1)*i*(1-i),g=e,p=e+(t-e)*o,k=e+(t-e)*c,A=t,S=h,N=1-S;return N**3*g+3*N**2*S*p+3*N*S**2*k+S**3*A}}class R{property;length;cubicBuilder;constructor(e,t,i=0){this.property=this.createKeyframes(e,t,i),this.length=t,this.cubicBuilder=new Gi}getValue(e){const t=this.property.find(s=>e>=s.start&&e<s.start+s.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 s=this.createNormalizedKeyframes(e);try{this.validateKeyframes(s)}catch(n){console.warn("Keyframe configuration issues detected:",n)}return this.insertFillerKeyframes(s,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],s=e[t+1];if(!s){if(i.start+i.length>this.length)throw new Error("Last keyframe exceeds the maximum duration.");break}if(i.start+i.length>s.start)throw new Error("Overlapping keyframes detected.")}}insertFillerKeyframes(e,t,i=0){const s=[];for(let n=0;n<e.length;n+=1){const r=e[n],o=e[n+1];if(n===0&&r.start!==0){const h={start:0,length:r.start,from:i,to:r.from};s.push(h)}if(s.push(r),!o){if(r.start+r.length<t){const g=r.start+r.length,p={start:g,length:t-g,from:r.to,to:r.to};s.push(p)}break}if(r.start+r.length!==o.start){const h={start:r.start+r.length,length:o.start,from:r.to,to:o.from};s.push(h)}}return s}}class Be{static Name="AudioLoadParser";name;extension;validAudioExtensions;constructor(){this.name=Be.Name,this.extension={type:[v.ExtensionType.LoadParser],priority:v.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(s=>{const n={src:e},r=new Howl(n);r.on("load",()=>s(r)),r.on("loaderror",()=>s(null))})}unload(e){e?.unload()}}class Qi{clipConfiguration;constructor(e){this.clipConfiguration=e}build(e,t){const i=[],s=[],n=[],r=[],o=[],{effect:l,length:c}=this.clipConfiguration;if(!l)return{offsetXKeyframes:i,offsetYKeyframes:s,opacityKeyframes:n,scaleKeyframes:r,rotationKeyframes:o};const h=0;switch(this.getPresetName()){case"zoomIn":{const p=this.getZoomSpeed(),k=1*this.clipConfiguration.scale,A=p*this.clipConfiguration.scale;r.push({from:k,to:A,start:h,length:c,interpolation:"linear"});break}case"zoomOut":{const k=this.getZoomSpeed()*this.clipConfiguration.scale,A=1*this.clipConfiguration.scale;r.push({from:k,to:A,start:h,length:c,interpolation:"linear"});break}case"slideLeft":{let p=this.getSlideStart();const k=e.width+e.width*p*2,A=t.height/t.width*e.height;if(A<k){const S=Math.abs(k/e.width);r.push({from:S,to:S,start:h,length:c,interpolation:"linear"})}else p=(A-e.width)/2/e.width;i.push({from:p,to:-p,start:h,length:c});break}case"slideRight":{let p=this.getSlideStart();const k=e.width+e.width*p*2,A=t.height/t.width*e.height;if(A<k){const S=Math.abs(k/e.width);r.push({from:S,to:S,start:h,length:c,interpolation:"linear"})}else p=(A-e.width)/2/e.width;i.push({from:-p,to:p,start:h,length:c});break}case"slideUp":{let p=this.getSlideStart();const k=e.height+e.height*p*2,A=t.height/t.width*e.width;if(A<k){const S=Math.abs(k/e.height);r.push({from:S,to:S,start:h,length:c,interpolation:"linear"})}else p=(A-e.height)/2/e.height;s.push({from:p,to:-p,start:h,length:c});break}case"slideDown":{let p=this.getSlideStart();const k=e.height+e.height*p*2,A=t.height/t.width*e.width;if(A<k){const S=Math.abs(k/e.height);r.push({from:S,to:S,start:h,length:c,interpolation:"linear"})}else p=(A-e.height)/2/e.height;s.push({from:-p,to:p,start:h,length:c});break}}return{offsetXKeyframes:i,offsetYKeyframes:s,opacityKeyframes:n,scaleKeyframes:r,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 Ji{clipConfiguration;constructor(e){this.clipConfiguration=e}build(){const e=[],t=[],i=[],s=[],n=[],r=this.buildInPreset();e.push(...r.offsetXKeyframes),t.push(...r.offsetYKeyframes),i.push(...r.opacityKeyframes),s.push(...r.scaleKeyframes),n.push(...r.rotationKeyframes);const o=this.buildOutPreset();return e.push(...o.offsetXKeyframes),t.push(...o.offsetYKeyframes),i.push(...o.opacityKeyframes),s.push(...o.scaleKeyframes),n.push(...o.rotationKeyframes),{offsetXKeyframes:e,offsetYKeyframes:t,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n}}buildInPreset(){const e=[],t=[],i=[],s=[],n=[];if(!this.clipConfiguration.transition?.in)return{offsetXKeyframes:e,offsetYKeyframes:t,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n};const r=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:r,length:o,interpolation:"linear"});break}case"zoom":{const h=this.clipConfiguration.scale+9,g=this.clipConfiguration.scale;s.push({from:h,to:g,start:r,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:r,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:r,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:r,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:r,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:r,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:r,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:r,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:r,length:o,interpolation:"bezier",easing:"easeOut"}),i.push({from:0,to:1,start:r,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:s,rotationKeyframes:n}}buildOutPreset(){const e=[],t=[],i=[],s=[],n=[];if(!this.clipConfiguration.transition?.out)return{offsetXKeyframes:e,offsetYKeyframes:t,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n};const r=this.getOutPresetLength(),o=this.clipConfiguration.length-r;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:r,interpolation:"linear"});break}case"zoom":{const h=this.clipConfiguration.scale,g=h+9;s.push({from:h,to:g,start:o,length:r,interpolation:"bezier",easing:"easeOut"}),i.push({from:1,to:0,start:o,length:r,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:r,interpolation:"bezier",easing:"easeOut"}),i.push({from:1,to:0,start:o,length:r,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:r,interpolation:"bezier",easing:"easeOut"}),i.push({from:1,to:0,start:o,length:r,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:r,interpolation:"bezier",easing:"easeIn"}),i.push({from:1,to:0,start:o,length:r,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:r,interpolation:"bezier",easing:"easeIn"}),i.push({from:1,to:0,start:o,length:r,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:s,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 es{static ButtonLeftClick=0;static ButtonRightClick=3}class ts{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 at{container;constructor(){this.container=new v.Container}getContainer(){return this.container}}class I extends at{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;constructor(e,t){super(),this.edit=e,this.layer=0,this.shouldDispose=!1,this.clipConfiguration=t,this.positionBuilder=new ts(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}configureKeyframes(){if(this.offsetXKeyframeBuilder=new R(this.clipConfiguration.offset?.x??0,this.getLength()),this.offsetYKeyframeBuilder=new R(this.clipConfiguration.offset?.y??0,this.getLength()),this.scaleKeyframeBuilder=new R(this.clipConfiguration.scale??1,this.getLength(),1),this.opacityKeyframeBuilder=new R(this.clipConfiguration.opacity??1,this.getLength(),1),this.rotationKeyframeBuilder=new R(this.clipConfiguration.transform?.rotate?.angle??0,this.getLength()),this.clipHasKeyframes())return;const e=[],t=[],i=[],s=[],n=[],r=new Qi(this.clipConfiguration).build(this.edit.size,this.getSize());e.push(...r.offsetXKeyframes),t.push(...r.offsetYKeyframes),i.push(...r.opacityKeyframes),s.push(...r.scaleKeyframes),n.push(...r.rotationKeyframes);const o=new Ji(this.clipConfiguration).build();e.push(...o.offsetXKeyframes),t.push(...o.offsetYKeyframes),i.push(...o.opacityKeyframes),s.push(...o.scaleKeyframes),n.push(...o.rotationKeyframes),e.length&&(this.offsetXKeyframeBuilder=new R(e,this.getLength())),t.length&&(this.offsetYKeyframeBuilder=new R(t,this.getLength())),i.length&&(this.opacityKeyframeBuilder=new R(i,this.getLength(),1)),s.length&&(this.scaleKeyframeBuilder=new R(s,this.getLength(),1)),n.length&&(this.rotationKeyframeBuilder=new R(n,this.getLength()))}async load(){this.outline=new v.Graphics,this.getContainer().addChild(this.outline),this.topLeftScaleHandle=new v.Graphics,this.topRightScaleHandle=new v.Graphics,this.bottomRightScaleHandle=new v.Graphics,this.bottomLeftScaleHandle=new v.Graphics,this.getContainer().addChild(this.topLeftScaleHandle),this.getContainer().addChild(this.topRightScaleHandle),this.getContainer().addChild(this.bottomRightScaleHandle),this.getContainer().addChild(this.bottomLeftScaleHandle),this.rotationHandle=new v.Graphics,this.getContainer().addChild(this.rotationHandle),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=this.layer,!this.isActive())return;const i=this.getPivot(),s=this.getPosition(),n=this.getScale();this.getContainer().scale.set(n),this.getContainer().pivot.set(i.x,i.y),this.getContainer().position.set(s.x+i.x,s.y+i.y);const r=this.getRotation();this.getContainer().alpha=this.getOpacity(),this.getContainer().angle=r,this.shouldDiscardFrame()&&(this.getContainer().alpha=0)}draw(){if(!this.outline)return;if((!this.isActive()||this.edit.getSelectedClip()!==this)&&!this.isHovering){this.outline.clear(),this.topLeftScaleHandle?.clear(),this.topRightScaleHandle?.clear(),this.bottomRightScaleHandle?.clear(),this.bottomLeftScaleHandle?.clear(),this.rotationHandle?.clear();return}const e=this.isHovering||this.isDragging?65535:16777215,t=this.getSize(),i=this.getScale();if(this.outline.clear(),this.outline.strokeStyle={width:I.OutlineWidth/i,color:e},this.outline.rect(0,0,t.width,t.height),this.outline.stroke(),!this.topLeftScaleHandle||!this.topRightScaleHandle||!this.bottomRightScaleHandle||!this.bottomLeftScaleHandle||!this.isActive()||this.edit.getSelectedClip()!==this)return;this.topLeftScaleHandle.fillStyle={color:e},this.topLeftScaleHandle.clear();const s=I.ScaleHandleRadius*2/i;if(this.topLeftScaleHandle.rect(-s/2,-s/2,s,s),this.topLeftScaleHandle.fill(),this.topRightScaleHandle.fillStyle={color:e},this.topRightScaleHandle.clear(),this.topRightScaleHandle.rect(t.width-s/2,-s/2,s,s),this.topRightScaleHandle.fill(),this.bottomRightScaleHandle.fillStyle={color:e},this.bottomRightScaleHandle.clear(),this.bottomRightScaleHandle.rect(t.width-s/2,t.height-s/2,s,s),this.bottomRightScaleHandle.fill(),this.bottomLeftScaleHandle.fillStyle={color:e},this.bottomLeftScaleHandle.clear(),this.bottomLeftScaleHandle.rect(-s/2,t.height-s/2,s,s),this.bottomLeftScaleHandle.fill(),!this.rotationHandle)return;const n=t.width/2,r=-50/i;this.rotationHandle.clear(),this.rotationHandle.fillStyle={color:e},this.rotationHandle.circle(n,r,I.RotationHandleRadius/i),this.rotationHandle.fill(),this.outline.strokeStyle={width:I.OutlineWidth/i,color:e},this.outline.moveTo(n,0),this.outline.lineTo(n,r),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}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":return Math.max(this.edit.size.width/this.getSize().width,this.edit.size.height/this.getSize().height);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()}getRotation(){return this.rotationKeyframeBuilder?.getValue(this.getPlaybackTime())??0}isActive(){return this.edit.playbackTime>=this.getStart()&&this.edit.playbackTime<this.getEnd()}shouldDiscardFrame(){return this.getPlaybackTime()<I.DiscardedFrameCount}onPointerStart(e){if(e.button!==es.ButtonLeftClick||(this.edit.setSelectedClip(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(),s=this.getPivot(),n={x:i.x+s.x,y:i.y+s.y},r=Math.sqrt((this.scaleOffset.x-n.x)**2+(this.scaleOffset.y-n.y)**2),l=Math.sqrt((t.x-n.x)**2+(t.y-n.y)**2)/r,c=this.scaleStart*l;this.clipConfiguration.scale=Math.max(I.MinScale,Math.min(c,I.MaxScale)),this.scaleKeyframeBuilder=new R(this.clipConfiguration.scale,this.getLength(),1);return}if(this.isRotating&&this.rotationStart!==null){const t=e.getLocalPosition(this.edit.getContainer()),i=this.getPosition(),s=this.getPivot(),n={x:i.x+s.x,y:i.y+s.y},r=Math.atan2(this.rotationOffset.y-n.y,this.rotationOffset.x-n.x),l=(Math.atan2(t.y-n.y,t.x-n.x)-r)*(180/Math.PI);let c=this.rotationStart+l;const h=45,g=c%h,p=2;Math.abs(g)<p?c=Math.floor(c/h)*h:Math.abs(g-h)<p&&(c=Math.ceil(c/h)*h),this.clipConfiguration.transform||(this.clipConfiguration.transform={rotate:{angle:0}}),this.clipConfiguration.transform.rotate||(this.clipConfiguration.transform.rotate={angle:0}),this.clipConfiguration.transform.rotate.angle=c,this.rotationKeyframeBuilder=new R(this.clipConfiguration.transform.rotate.angle,this.getLength());return}if(this.isDragging){const t=e.getLocalPosition(this.edit.getContainer()),i=this.getPivot(),s={x:t.x-this.dragOffset.x,y:t.y-this.dragOffset.y},n={x:s.x-i.x,y:s.y-i.y},r=[{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=[...r,o],c=[{x:n.x,y:n.y},{x:n.x+this.getSize().width,y:n.y},{x:n.x,y:n.y+this.getSize().height},{x:n.x+this.getSize().width,y:n.y+this.getSize().height}],h={x:n.x+this.getSize().width/2,y:n.y+this.getSize().height/2},g=[...c,h];let p=I.SnapThreshold,k=I.SnapThreshold,A=null,S=null;for(const ce of g)for(const ye of l){const X=Math.abs(ce.x-ye.x);X<p&&(p=X,A=n.x+(ye.x-ce.x));const ve=Math.abs(ce.y-ye.y);ve<k&&(k=ve,S=n.y+(ye.y-ce.y))}A!==null&&(n.x=A),S!==null&&(n.y=S);const N=this.positionBuilder.absoluteToRelative(this.getSize(),this.clipConfiguration.position??"center",n);this.clipConfiguration.offset||(this.clipConfiguration.offset={x:0,y:0}),this.clipConfiguration.offset.x=N.x,this.clipConfiguration.offset.y=N.y,this.offsetXKeyframeBuilder=new R(this.clipConfiguration.offset.x,this.getLength()),this.offsetYKeyframeBuilder=new R(this.clipConfiguration.offset.y,this.getLength())}}onPointerUp(){(this.isDragging||this.scaleDirection!==null||this.isRotating)&&this.hasStateChanged()&&this.edit.setUpdatedClip(this,this.initialClipConfiguration),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,s=Number(this.clipConfiguration.transform?.rotate?.angle??0),n=this.initialClipConfiguration.offset?.x,r=this.initialClipConfiguration.offset?.y,o=this.initialClipConfiguration.scale,l=Number(this.initialClipConfiguration.transform?.rotate?.angle??0);return n!==void 0&&e!==n||r!==void 0&&t!==r||o!==void 0&&i!==o||s!==l}}class rt extends I{audioResource;isPlaying;volumeKeyframeBuilder;syncTimer;constructor(e,t){super(e,t),this.audioResource=null,this.isPlaying=!1;const i=t.asset;this.volumeKeyframeBuilder=new R(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:Be.Name},s=await this.edit.assetLoader.load(t,i);if(!(s instanceof jt.Howl))throw new Error(`Invalid audio source '${e.src}'.`);this.audioResource=s,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 s=this.edit.isPlaying&&this.isActive(),n=this.getPlaybackTime();s&&(this.isPlaying||(this.isPlaying=!0,this.audioResource.seek(n/1e3+i),this.audioResource.play()),this.audioResource.volume()!==this.getVolume()&&this.audioResource.volume(this.getVolume()),Math.abs((this.audioResource.seek()-i)*1e3-n)>100&&this.audioResource.seek(n/1e3+i)),this.isPlaying&&!s&&(this.isPlaying=!1,this.audioResource.pause());const r=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&r&&(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 is=`in vec2 aPosition;
|
|
1
|
+
(function(F,V){typeof exports=="object"&&typeof module<"u"?V(exports,require("pixi.js"),require("opentype.js"),require("howler"),require("@ffmpeg/ffmpeg")):typeof define=="function"&&define.amd?define(["exports","pixi.js","opentype.js","howler","@ffmpeg/ffmpeg"],V):(F=typeof globalThis<"u"?globalThis:F||self,V(F.ShotstackStudio={},F.PIXI,F.opentype,F.Howler,F.ffmpeg))})(this,function(F,V,je,$e,Ue){"use strict";function Yt(a){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(a){for(const e in a)if(e!=="default"){const i=Object.getOwnPropertyDescriptor(a,e);Object.defineProperty(t,e,i.get?i:{enumerable:!0,get:()=>a[e]})}}return t.default=a,Object.freeze(t)}const y=Yt(V),ge=Yt(je),We=Yt($e);class me{events;constructor(){this.events={}}on(t,e){this.events[t]||(this.events[t]=new Set),this.events[t].add(e)}off(t,e){this.events[t]&&(this.events[t].delete(e),!(this.events[t].size>0)&&delete this.events[t])}clear(t){delete this.events[t]}emit(t,e){if(this.events[t])for(const i of this.events[t])i(e)}}class Xe extends me{registry;constructor(){super(),this.registry={}}}class At{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 Xe;async load(t,e){this.updateAssetLoadMetadata(t,"pending",0);try{if(await this.shouldUseSafariVideoLoader(e))return await this.loadVideoForSafari(t,e);const i=await y.Assets.load(e,s=>{this.updateAssetLoadMetadata(t,"loading",s)});return this.updateAssetLoadMetadata(t,"success",1),i}catch{return this.updateAssetLoadMetadata(t,"failed",1),null}}getProgress(){const t=Object.keys(this.loadTracker.registry);return t.length===0?0:t.reduce((i,s)=>i+this.loadTracker.registry[s].progress,0)/t.length}extractUrl(t){if(typeof t=="string")return t;const e=Array.isArray(t.src)?t.src[0]:t.src;return typeof e=="string"?e:e?.src}hasVideoExtension(t){const e=new URL(t,window.location.origin).pathname.toLowerCase();return At.VIDEO_EXTENSIONS.some(i=>e.endsWith(i))}async getContentType(t){try{return(await fetch(t,{method:"HEAD"})).headers.get("content-type")}catch{return null}}canPlayVideo(t){const e=new URL(t,window.location.origin).pathname.toLowerCase(),i=e.slice(e.lastIndexOf(".")),s=At.VIDEO_MIME[i];return s?document.createElement("video").canPlayType(s)!=="":!1}async isPlayableVideo(t){if(this.hasVideoExtension(t))return this.canPlayVideo(t);const e=await this.getContentType(t);return e?.startsWith("video/")?document.createElement("video").canPlayType(e)!=="":!1}async shouldUseSafariVideoLoader(t){const e=/^((?!chrome|android).)*safari/i.test(navigator.userAgent),i=this.extractUrl(t);return e&&i!==void 0&&await this.isPlayableVideo(i)}async loadVideoForSafari(t,e){const i=this.extractUrl(e),s=typeof e=="object"?e.data??{}:{},n=await new Promise((r,o)=>{const h=document.createElement("video");h.crossOrigin="anonymous",h.playsInline=!0,h.muted=!0,h.preload="metadata",h.addEventListener("loadedmetadata",()=>{try{const l=new y.VideoSource({resource:h,autoPlay:s.autoPlay??!1,...s});r(new y.Texture({source:l}))}catch(l){o(l)}},{once:!0}),h.addEventListener("error",()=>o(new Error("Video loading failed")),{once:!0}),this.updateAssetLoadMetadata(t,"loading",.5),h.src=i});return this.updateAssetLoadMetadata(t,"success",1),n}updateAssetLoadMetadata(t,e,i){this.loadTracker.registry[t]?(this.loadTracker.registry[t].progress=i,this.loadTracker.registry[t].status=e):this.loadTracker.registry[t]={progress:i,status:e};const s={...this.loadTracker.registry};this.loadTracker.emit("onAssetLoadInfoUpdated",{registry:s})}}class Pt{static Name="FontLoadParser";name;extension;validFontExtensions;woff2Decompressor;constructor(){this.name=Pt.Name,this.extension={type:[y.ExtensionType.LoadParser],priority:y.LoaderParserPriority.High,ref:null},this.validFontExtensions=["ttf","otf","woff","woff2"],this.woff2Decompressor=null}test(t){const e=t.split("?")[0]?.split(".").pop()?.toLowerCase()??"";return this.validFontExtensions.includes(e)}async load(t,e,i){const s=t.split("?")[0]?.split(".").pop()?.toLowerCase()??"",n=await fetch(t).then(p=>p.arrayBuffer());if(s!=="woff2"){const p=ge.parse(new Uint8Array(n).buffer),k=p.names.fontFamily.en||p.names.fontFamily[Object.keys(p.names.fontFamily)[0]],O=new FontFace(k,`url(${t})`);return await O.load(),document.fonts.add(O),O}if(await this.loadWoff2Decompressor(),!this.woff2Decompressor)throw new Error("Cannot initialize Woff2 decompressor.");const r=this.woff2Decompressor.decompress(n),o=ge.parse(new Uint8Array(r).buffer),h=o.names.fontFamily.en||o.names.fontFamily[Object.keys(o.names.fontFamily)[0]],l=new Blob([r],{type:"font/ttf"}),c=URL.createObjectURL(l),m=new FontFace(h,`url(${c})`);return await m.load(),document.fonts.add(m),m}async loadWoff2Decompressor(){if(this.woff2Decompressor)return;const e=`${await fetch("https://unpkg.com/wawoff2@2.0.1/build/decompress_binding.js").then(i=>i.text())}; return Module`;this.woff2Decompressor=new Function(e)(),await new Promise(i=>{this.woff2Decompressor.onRuntimeInitialized=i})}unload(t){t&&document.fonts.delete(t)}}var S;(function(a){a.assertEqual=s=>s;function t(s){}a.assertIs=t;function e(s){throw new Error}a.assertNever=e,a.arrayToEnum=s=>{const n={};for(const r of s)n[r]=r;return n},a.getValidEnumValues=s=>{const n=a.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),r={};for(const o of n)r[o]=s[o];return a.objectValues(r)},a.objectValues=s=>a.objectKeys(s).map(function(n){return s[n]}),a.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const n=[];for(const r in s)Object.prototype.hasOwnProperty.call(s,r)&&n.push(r);return n},a.find=(s,n)=>{for(const r of s)if(n(r))return r},a.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&isFinite(s)&&Math.floor(s)===s;function i(s,n=" | "){return s.map(r=>typeof r=="string"?`'${r}'`:r).join(n)}a.joinValues=i,a.jsonStringifyReplacer=(s,n)=>typeof n=="bigint"?n.toString():n})(S||(S={}));var ye;(function(a){a.mergeShapes=(t,e)=>({...t,...e})})(ye||(ye={}));const f=S.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),J=a=>{switch(typeof a){case"undefined":return f.undefined;case"string":return f.string;case"number":return isNaN(a)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(a)?f.array:a===null?f.null:a.then&&typeof a.then=="function"&&a.catch&&typeof a.catch=="function"?f.promise:typeof Map<"u"&&a instanceof Map?f.map:typeof Set<"u"&&a instanceof Set?f.set:typeof Date<"u"&&a instanceof Date?f.date:f.object;default:return f.unknown}},u=S.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class N extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=i=>{this.issues=[...this.issues,i]},this.addIssues=(i=[])=>{this.issues=[...this.issues,...i]};const e=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,e):this.__proto__=e,this.name="ZodError",this.issues=t}format(t){const e=t||function(n){return n.message},i={_errors:[]},s=n=>{for(const r of n.issues)if(r.code==="invalid_union")r.unionErrors.map(s);else if(r.code==="invalid_return_type")s(r.returnTypeError);else if(r.code==="invalid_arguments")s(r.argumentsError);else if(r.path.length===0)i._errors.push(e(r));else{let o=i,h=0;for(;h<r.path.length;){const l=r.path[h];h===r.path.length-1?(o[l]=o[l]||{_errors:[]},o[l]._errors.push(e(r))):o[l]=o[l]||{_errors:[]},o=o[l],h++}}};return s(this),i}static assert(t){if(!(t instanceof N))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,S.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=e=>e.message){const e={},i=[];for(const s of this.issues)s.path.length>0?(e[s.path[0]]=e[s.path[0]]||[],e[s.path[0]].push(t(s))):i.push(t(s));return{formErrors:i,fieldErrors:e}}get formErrors(){return this.flatten()}}N.create=a=>new N(a);const wt=(a,t)=>{let e;switch(a.code){case u.invalid_type:a.received===f.undefined?e="Required":e=`Expected ${a.expected}, received ${a.received}`;break;case u.invalid_literal:e=`Invalid literal value, expected ${JSON.stringify(a.expected,S.jsonStringifyReplacer)}`;break;case u.unrecognized_keys:e=`Unrecognized key(s) in object: ${S.joinValues(a.keys,", ")}`;break;case u.invalid_union:e="Invalid input";break;case u.invalid_union_discriminator:e=`Invalid discriminator value. Expected ${S.joinValues(a.options)}`;break;case u.invalid_enum_value:e=`Invalid enum value. Expected ${S.joinValues(a.options)}, received '${a.received}'`;break;case u.invalid_arguments:e="Invalid function arguments";break;case u.invalid_return_type:e="Invalid function return type";break;case u.invalid_date:e="Invalid date";break;case u.invalid_string:typeof a.validation=="object"?"includes"in a.validation?(e=`Invalid input: must include "${a.validation.includes}"`,typeof a.validation.position=="number"&&(e=`${e} at one or more positions greater than or equal to ${a.validation.position}`)):"startsWith"in a.validation?e=`Invalid input: must start with "${a.validation.startsWith}"`:"endsWith"in a.validation?e=`Invalid input: must end with "${a.validation.endsWith}"`:S.assertNever(a.validation):a.validation!=="regex"?e=`Invalid ${a.validation}`:e="Invalid";break;case u.too_small:a.type==="array"?e=`Array must contain ${a.exact?"exactly":a.inclusive?"at least":"more than"} ${a.minimum} element(s)`:a.type==="string"?e=`String must contain ${a.exact?"exactly":a.inclusive?"at least":"over"} ${a.minimum} character(s)`:a.type==="number"?e=`Number must be ${a.exact?"exactly equal to ":a.inclusive?"greater than or equal to ":"greater than "}${a.minimum}`:a.type==="date"?e=`Date must be ${a.exact?"exactly equal to ":a.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(a.minimum))}`:e="Invalid input";break;case u.too_big:a.type==="array"?e=`Array must contain ${a.exact?"exactly":a.inclusive?"at most":"less than"} ${a.maximum} element(s)`:a.type==="string"?e=`String must contain ${a.exact?"exactly":a.inclusive?"at most":"under"} ${a.maximum} character(s)`:a.type==="number"?e=`Number must be ${a.exact?"exactly":a.inclusive?"less than or equal to":"less than"} ${a.maximum}`:a.type==="bigint"?e=`BigInt must be ${a.exact?"exactly":a.inclusive?"less than or equal to":"less than"} ${a.maximum}`:a.type==="date"?e=`Date must be ${a.exact?"exactly":a.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(a.maximum))}`:e="Invalid input";break;case u.custom:e="Invalid input";break;case u.invalid_intersection_types:e="Intersection results could not be merged";break;case u.not_multiple_of:e=`Number must be a multiple of ${a.multipleOf}`;break;case u.not_finite:e="Number must be finite";break;default:e=t.defaultError,S.assertNever(a)}return{message:e}};let Ye=wt;function Gt(){return Ye}const qt=a=>{const{data:t,path:e,errorMaps:i,issueData:s}=a,n=[...e,...s.path||[]],r={...s,path:n};if(s.message!==void 0)return{...s,path:n,message:s.message};let o="";const h=i.filter(l=>!!l).slice().reverse();for(const l of h)o=l(r,{data:t,defaultError:o}).message;return{...s,path:n,message:o}};function d(a,t){const e=Gt(),i=qt({issueData:t,data:a.data,path:a.path,errorMaps:[a.common.contextualErrorMap,a.schemaErrorMap,e,e===wt?void 0:wt].filter(s=>!!s)});a.common.issues.push(i)}class L{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,e){const i=[];for(const s of e){if(s.status==="aborted")return w;s.status==="dirty"&&t.dirty(),i.push(s.value)}return{status:t.value,value:i}}static async mergeObjectAsync(t,e){const i=[];for(const s of e){const n=await s.key,r=await s.value;i.push({key:n,value:r})}return L.mergeObjectSync(t,i)}static mergeObjectSync(t,e){const i={};for(const s of e){const{key:n,value:r}=s;if(n.status==="aborted"||r.status==="aborted")return w;n.status==="dirty"&&t.dirty(),r.status==="dirty"&&t.dirty(),n.value!=="__proto__"&&(typeof r.value<"u"||s.alwaysSet)&&(i[n.value]=r.value)}return{status:t.value,value:i}}}const w=Object.freeze({status:"aborted"}),Ct=a=>({status:"dirty",value:a}),z=a=>({status:"valid",value:a}),ve=a=>a.status==="aborted",xe=a=>a.status==="dirty",ut=a=>a.status==="valid",Et=a=>typeof Promise<"u"&&a instanceof Promise;function Lt(a,t,e,i){if(typeof t=="function"?a!==t||!0:!t.has(a))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t.get(a)}function we(a,t,e,i,s){if(typeof t=="function"?a!==t||!0:!t.has(a))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(a,e),e}typeof SuppressedError=="function"&&SuppressedError;var g;(function(a){a.errToObj=t=>typeof t=="string"?{message:t}:t||{},a.toString=t=>typeof t=="string"?t:t?.message})(g||(g={}));var kt,bt;class Z{constructor(t,e,i,s){this._cachedPath=[],this.parent=t,this.data=e,this._path=i,this._key=s}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const Ce=(a,t)=>{if(ut(t))return{success:!0,data:t.value};if(!a.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const e=new N(a.common.issues);return this._error=e,this._error}}};function C(a){if(!a)return{};const{errorMap:t,invalid_type_error:e,required_error:i,description:s}=a;if(t&&(e||i))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:s}:{errorMap:(r,o)=>{var h,l;const{message:c}=a;return r.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:(h=c??i)!==null&&h!==void 0?h:o.defaultError}:r.code!=="invalid_type"?{message:o.defaultError}:{message:(l=c??e)!==null&&l!==void 0?l:o.defaultError}},description:s}}class b{get description(){return this._def.description}_getType(t){return J(t.data)}_getOrReturnCtx(t,e){return e||{common:t.parent.common,data:t.data,parsedType:J(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new L,ctx:{common:t.parent.common,data:t.data,parsedType:J(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){const e=this._parse(t);if(Et(e))throw new Error("Synchronous parse encountered promise.");return e}_parseAsync(t){const e=this._parse(t);return Promise.resolve(e)}parse(t,e){const i=this.safeParse(t,e);if(i.success)return i.data;throw i.error}safeParse(t,e){var i;const s={common:{issues:[],async:(i=e?.async)!==null&&i!==void 0?i:!1,contextualErrorMap:e?.errorMap},path:e?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:J(t)},n=this._parseSync({data:t,path:s.path,parent:s});return Ce(s,n)}"~validate"(t){var e,i;const s={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:J(t)};if(!this["~standard"].async)try{const n=this._parseSync({data:t,path:[],parent:s});return ut(n)?{value:n.value}:{issues:s.common.issues}}catch(n){!((i=(e=n?.message)===null||e===void 0?void 0:e.toLowerCase())===null||i===void 0)&&i.includes("encountered")&&(this["~standard"].async=!0),s.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:s}).then(n=>ut(n)?{value:n.value}:{issues:s.common.issues})}async parseAsync(t,e){const i=await this.safeParseAsync(t,e);if(i.success)return i.data;throw i.error}async safeParseAsync(t,e){const i={common:{issues:[],contextualErrorMap:e?.errorMap,async:!0},path:e?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:J(t)},s=this._parse({data:t,path:i.path,parent:i}),n=await(Et(s)?s:Promise.resolve(s));return Ce(i,n)}refine(t,e){const i=s=>typeof e=="string"||typeof e>"u"?{message:e}:typeof e=="function"?e(s):e;return this._refinement((s,n)=>{const r=t(s),o=()=>n.addIssue({code:u.custom,...i(s)});return typeof Promise<"u"&&r instanceof Promise?r.then(h=>h?!0:(o(),!1)):r?!0:(o(),!1)})}refinement(t,e){return this._refinement((i,s)=>t(i)?!0:(s.addIssue(typeof e=="function"?e(i,s):e),!1))}_refinement(t){return new X({schema:this,typeName:x.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:e=>this["~validate"](e)}}optional(){return Y.create(this,this._def)}nullable(){return nt.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return K.create(this)}promise(){return Tt.create(this,this._def)}or(t){return Dt.create([this,t],this._def)}and(t){return Mt.create(this,t,this._def)}transform(t){return new X({...C(this._def),schema:this,typeName:x.ZodEffects,effect:{type:"transform",transform:t}})}default(t){const e=typeof t=="function"?t:()=>t;return new Vt({...C(this._def),innerType:this,defaultValue:e,typeName:x.ZodDefault})}brand(){return new Se({typeName:x.ZodBranded,type:this,...C(this._def)})}catch(t){const e=typeof t=="function"?t:()=>t;return new Zt({...C(this._def),innerType:this,catchValue:e,typeName:x.ZodCatch})}describe(t){const e=this.constructor;return new e({...this._def,description:t})}pipe(t){return Kt.create(this,t)}readonly(){return jt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const Ge=/^c[^\s-]{8,}$/i,qe=/^[0-9a-z]+$/,Qe=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Je=/^[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,ti=/^[a-z0-9_-]{21}$/i,ei=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ii=/^[-+]?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)?)??$/,si=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ni="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Qt;const ai=/^(?:(?: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])$/,ri=/^(?:(?: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])$/,oi=/^(([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]))$/,li=/^(([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])$/,ci=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,hi=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ke="((\\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])))",ui=new RegExp(`^${ke}$`);function be(a){let t="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return a.precision?t=`${t}\\.\\d{${a.precision}}`:a.precision==null&&(t=`${t}(\\.\\d+)?`),t}function di(a){return new RegExp(`^${be(a)}$`)}function fi(a){let t=`${ke}T${be(a)}`;const e=[];return e.push(a.local?"Z?":"Z"),a.offset&&e.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${e.join("|")})`,new RegExp(`^${t}$`)}function pi(a,t){return!!((t==="v4"||!t)&&ai.test(a)||(t==="v6"||!t)&&oi.test(a))}function gi(a,t){if(!ei.test(a))return!1;try{const[e]=a.split("."),i=e.replace(/-/g,"+").replace(/_/g,"/").padEnd(e.length+(4-e.length%4)%4,"="),s=JSON.parse(atob(i));return!(typeof s!="object"||s===null||!s.typ||!s.alg||t&&s.alg!==t)}catch{return!1}}function mi(a,t){return!!((t==="v4"||!t)&&ri.test(a)||(t==="v6"||!t)&&li.test(a))}class $ extends b{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==f.string){const n=this._getOrReturnCtx(t);return d(n,{code:u.invalid_type,expected:f.string,received:n.parsedType}),w}const i=new L;let s;for(const n of this._def.checks)if(n.kind==="min")t.data.length<n.value&&(s=this._getOrReturnCtx(t,s),d(s,{code:u.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),i.dirty());else if(n.kind==="max")t.data.length>n.value&&(s=this._getOrReturnCtx(t,s),d(s,{code:u.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),i.dirty());else if(n.kind==="length"){const r=t.data.length>n.value,o=t.data.length<n.value;(r||o)&&(s=this._getOrReturnCtx(t,s),r?d(s,{code:u.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):o&&d(s,{code:u.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),i.dirty())}else if(n.kind==="email")si.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"email",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="emoji")Qt||(Qt=new RegExp(ni,"u")),Qt.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"emoji",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="uuid")Je.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"uuid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="nanoid")ti.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"nanoid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="cuid")Ge.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"cuid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="cuid2")qe.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"cuid2",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="ulid")Qe.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"ulid",code:u.invalid_string,message:n.message}),i.dirty());else if(n.kind==="url")try{new URL(t.data)}catch{s=this._getOrReturnCtx(t,s),d(s,{validation:"url",code:u.invalid_string,message:n.message}),i.dirty()}else n.kind==="regex"?(n.regex.lastIndex=0,n.regex.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"regex",code:u.invalid_string,message:n.message}),i.dirty())):n.kind==="trim"?t.data=t.data.trim():n.kind==="includes"?t.data.includes(n.value,n.position)||(s=this._getOrReturnCtx(t,s),d(s,{code:u.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),i.dirty()):n.kind==="toLowerCase"?t.data=t.data.toLowerCase():n.kind==="toUpperCase"?t.data=t.data.toUpperCase():n.kind==="startsWith"?t.data.startsWith(n.value)||(s=this._getOrReturnCtx(t,s),d(s,{code:u.invalid_string,validation:{startsWith:n.value},message:n.message}),i.dirty()):n.kind==="endsWith"?t.data.endsWith(n.value)||(s=this._getOrReturnCtx(t,s),d(s,{code:u.invalid_string,validation:{endsWith:n.value},message:n.message}),i.dirty()):n.kind==="datetime"?fi(n).test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{code:u.invalid_string,validation:"datetime",message:n.message}),i.dirty()):n.kind==="date"?ui.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{code:u.invalid_string,validation:"date",message:n.message}),i.dirty()):n.kind==="time"?di(n).test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{code:u.invalid_string,validation:"time",message:n.message}),i.dirty()):n.kind==="duration"?ii.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"duration",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="ip"?pi(t.data,n.version)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"ip",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="jwt"?gi(t.data,n.alg)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"jwt",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="cidr"?mi(t.data,n.version)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"cidr",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="base64"?ci.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"base64",code:u.invalid_string,message:n.message}),i.dirty()):n.kind==="base64url"?hi.test(t.data)||(s=this._getOrReturnCtx(t,s),d(s,{validation:"base64url",code:u.invalid_string,message:n.message}),i.dirty()):S.assertNever(n);return{status:i.value,value:t.data}}_regex(t,e,i){return this.refinement(s=>t.test(s),{validation:e,code:u.invalid_string,...g.errToObj(i)})}_addCheck(t){return new $({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...g.errToObj(t)})}url(t){return this._addCheck({kind:"url",...g.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...g.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...g.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...g.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...g.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...g.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...g.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...g.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...g.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...g.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...g.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...g.errToObj(t)})}datetime(t){var e,i;return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:(e=t?.offset)!==null&&e!==void 0?e:!1,local:(i=t?.local)!==null&&i!==void 0?i:!1,...g.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...g.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...g.errToObj(t)})}regex(t,e){return this._addCheck({kind:"regex",regex:t,...g.errToObj(e)})}includes(t,e){return this._addCheck({kind:"includes",value:t,position:e?.position,...g.errToObj(e?.message)})}startsWith(t,e){return this._addCheck({kind:"startsWith",value:t,...g.errToObj(e)})}endsWith(t,e){return this._addCheck({kind:"endsWith",value:t,...g.errToObj(e)})}min(t,e){return this._addCheck({kind:"min",value:t,...g.errToObj(e)})}max(t,e){return this._addCheck({kind:"max",value:t,...g.errToObj(e)})}length(t,e){return this._addCheck({kind:"length",value:t,...g.errToObj(e)})}nonempty(t){return this.min(1,g.errToObj(t))}trim(){return new $({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new $({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new $({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(const e of this._def.checks)e.kind==="min"&&(t===null||e.value>t)&&(t=e.value);return t}get maxLength(){let t=null;for(const e of this._def.checks)e.kind==="max"&&(t===null||e.value<t)&&(t=e.value);return t}}$.create=a=>{var t;return new $({checks:[],typeName:x.ZodString,coerce:(t=a?.coerce)!==null&&t!==void 0?t:!1,...C(a)})};function yi(a,t){const e=(a.toString().split(".")[1]||"").length,i=(t.toString().split(".")[1]||"").length,s=e>i?e:i,n=parseInt(a.toFixed(s).replace(".","")),r=parseInt(t.toFixed(s).replace(".",""));return n%r/Math.pow(10,s)}class dt extends b{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==f.number){const n=this._getOrReturnCtx(t);return d(n,{code:u.invalid_type,expected:f.number,received:n.parsedType}),w}let i;const s=new L;for(const n of this._def.checks)n.kind==="int"?S.isInteger(t.data)||(i=this._getOrReturnCtx(t,i),d(i,{code:u.invalid_type,expected:"integer",received:"float",message:n.message}),s.dirty()):n.kind==="min"?(n.inclusive?t.data<n.value:t.data<=n.value)&&(i=this._getOrReturnCtx(t,i),d(i,{code:u.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),s.dirty()):n.kind==="max"?(n.inclusive?t.data>n.value:t.data>=n.value)&&(i=this._getOrReturnCtx(t,i),d(i,{code:u.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),s.dirty()):n.kind==="multipleOf"?yi(t.data,n.value)!==0&&(i=this._getOrReturnCtx(t,i),d(i,{code:u.not_multiple_of,multipleOf:n.value,message:n.message}),s.dirty()):n.kind==="finite"?Number.isFinite(t.data)||(i=this._getOrReturnCtx(t,i),d(i,{code:u.not_finite,message:n.message}),s.dirty()):S.assertNever(n);return{status:s.value,value:t.data}}gte(t,e){return this.setLimit("min",t,!0,g.toString(e))}gt(t,e){return this.setLimit("min",t,!1,g.toString(e))}lte(t,e){return this.setLimit("max",t,!0,g.toString(e))}lt(t,e){return this.setLimit("max",t,!1,g.toString(e))}setLimit(t,e,i,s){return new dt({...this._def,checks:[...this._def.checks,{kind:t,value:e,inclusive:i,message:g.toString(s)}]})}_addCheck(t){return new dt({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:g.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:g.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:g.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:g.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:g.toString(t)})}multipleOf(t,e){return this._addCheck({kind:"multipleOf",value:t,message:g.toString(e)})}finite(t){return this._addCheck({kind:"finite",message:g.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:g.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:g.toString(t)})}get minValue(){let t=null;for(const e of this._def.checks)e.kind==="min"&&(t===null||e.value>t)&&(t=e.value);return t}get maxValue(){let t=null;for(const e of this._def.checks)e.kind==="max"&&(t===null||e.value<t)&&(t=e.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&S.isInteger(t.value))}get isFinite(){let t=null,e=null;for(const i of this._def.checks){if(i.kind==="finite"||i.kind==="int"||i.kind==="multipleOf")return!0;i.kind==="min"?(e===null||i.value>e)&&(e=i.value):i.kind==="max"&&(t===null||i.value<t)&&(t=i.value)}return Number.isFinite(e)&&Number.isFinite(t)}}dt.create=a=>new dt({checks:[],typeName:x.ZodNumber,coerce:a?.coerce||!1,...C(a)});class ft extends b{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==f.bigint)return this._getInvalidInput(t);let i;const s=new L;for(const n of this._def.checks)n.kind==="min"?(n.inclusive?t.data<n.value:t.data<=n.value)&&(i=this._getOrReturnCtx(t,i),d(i,{code:u.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),s.dirty()):n.kind==="max"?(n.inclusive?t.data>n.value:t.data>=n.value)&&(i=this._getOrReturnCtx(t,i),d(i,{code:u.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),s.dirty()):n.kind==="multipleOf"?t.data%n.value!==BigInt(0)&&(i=this._getOrReturnCtx(t,i),d(i,{code:u.not_multiple_of,multipleOf:n.value,message:n.message}),s.dirty()):S.assertNever(n);return{status:s.value,value:t.data}}_getInvalidInput(t){const e=this._getOrReturnCtx(t);return d(e,{code:u.invalid_type,expected:f.bigint,received:e.parsedType}),w}gte(t,e){return this.setLimit("min",t,!0,g.toString(e))}gt(t,e){return this.setLimit("min",t,!1,g.toString(e))}lte(t,e){return this.setLimit("max",t,!0,g.toString(e))}lt(t,e){return this.setLimit("max",t,!1,g.toString(e))}setLimit(t,e,i,s){return new ft({...this._def,checks:[...this._def.checks,{kind:t,value:e,inclusive:i,message:g.toString(s)}]})}_addCheck(t){return new ft({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:g.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:g.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:g.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:g.toString(t)})}multipleOf(t,e){return this._addCheck({kind:"multipleOf",value:t,message:g.toString(e)})}get minValue(){let t=null;for(const e of this._def.checks)e.kind==="min"&&(t===null||e.value>t)&&(t=e.value);return t}get maxValue(){let t=null;for(const e of this._def.checks)e.kind==="max"&&(t===null||e.value<t)&&(t=e.value);return t}}ft.create=a=>{var t;return new ft({checks:[],typeName:x.ZodBigInt,coerce:(t=a?.coerce)!==null&&t!==void 0?t:!1,...C(a)})};class Jt extends b{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==f.boolean){const i=this._getOrReturnCtx(t);return d(i,{code:u.invalid_type,expected:f.boolean,received:i.parsedType}),w}return z(t.data)}}Jt.create=a=>new Jt({typeName:x.ZodBoolean,coerce:a?.coerce||!1,...C(a)});class _t extends b{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==f.date){const n=this._getOrReturnCtx(t);return d(n,{code:u.invalid_type,expected:f.date,received:n.parsedType}),w}if(isNaN(t.data.getTime())){const n=this._getOrReturnCtx(t);return d(n,{code:u.invalid_date}),w}const i=new L;let s;for(const n of this._def.checks)n.kind==="min"?t.data.getTime()<n.value&&(s=this._getOrReturnCtx(t,s),d(s,{code:u.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),i.dirty()):n.kind==="max"?t.data.getTime()>n.value&&(s=this._getOrReturnCtx(t,s),d(s,{code:u.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),i.dirty()):S.assertNever(n);return{status:i.value,value:new Date(t.data.getTime())}}_addCheck(t){return new _t({...this._def,checks:[...this._def.checks,t]})}min(t,e){return this._addCheck({kind:"min",value:t.getTime(),message:g.toString(e)})}max(t,e){return this._addCheck({kind:"max",value:t.getTime(),message:g.toString(e)})}get minDate(){let t=null;for(const e of this._def.checks)e.kind==="min"&&(t===null||e.value>t)&&(t=e.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(const e of this._def.checks)e.kind==="max"&&(t===null||e.value<t)&&(t=e.value);return t!=null?new Date(t):null}}_t.create=a=>new _t({checks:[],coerce:a?.coerce||!1,typeName:x.ZodDate,...C(a)});class te extends b{_parse(t){if(this._getType(t)!==f.symbol){const i=this._getOrReturnCtx(t);return d(i,{code:u.invalid_type,expected:f.symbol,received:i.parsedType}),w}return z(t.data)}}te.create=a=>new te({typeName:x.ZodSymbol,...C(a)});class Rt extends b{_parse(t){if(this._getType(t)!==f.undefined){const i=this._getOrReturnCtx(t);return d(i,{code:u.invalid_type,expected:f.undefined,received:i.parsedType}),w}return z(t.data)}}Rt.create=a=>new Rt({typeName:x.ZodUndefined,...C(a)});class zt extends b{_parse(t){if(this._getType(t)!==f.null){const i=this._getOrReturnCtx(t);return d(i,{code:u.invalid_type,expected:f.null,received:i.parsedType}),w}return z(t.data)}}zt.create=a=>new zt({typeName:x.ZodNull,...C(a)});class ee extends b{constructor(){super(...arguments),this._any=!0}_parse(t){return z(t.data)}}ee.create=a=>new ee({typeName:x.ZodAny,...C(a)});class pt extends b{constructor(){super(...arguments),this._unknown=!0}_parse(t){return z(t.data)}}pt.create=a=>new pt({typeName:x.ZodUnknown,...C(a)});class tt extends b{_parse(t){const e=this._getOrReturnCtx(t);return d(e,{code:u.invalid_type,expected:f.never,received:e.parsedType}),w}}tt.create=a=>new tt({typeName:x.ZodNever,...C(a)});class ie extends b{_parse(t){if(this._getType(t)!==f.undefined){const i=this._getOrReturnCtx(t);return d(i,{code:u.invalid_type,expected:f.void,received:i.parsedType}),w}return z(t.data)}}ie.create=a=>new ie({typeName:x.ZodVoid,...C(a)});class K extends b{_parse(t){const{ctx:e,status:i}=this._processInputParams(t),s=this._def;if(e.parsedType!==f.array)return d(e,{code:u.invalid_type,expected:f.array,received:e.parsedType}),w;if(s.exactLength!==null){const r=e.data.length>s.exactLength.value,o=e.data.length<s.exactLength.value;(r||o)&&(d(e,{code:r?u.too_big:u.too_small,minimum:o?s.exactLength.value:void 0,maximum:r?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),i.dirty())}if(s.minLength!==null&&e.data.length<s.minLength.value&&(d(e,{code:u.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),i.dirty()),s.maxLength!==null&&e.data.length>s.maxLength.value&&(d(e,{code:u.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),i.dirty()),e.common.async)return Promise.all([...e.data].map((r,o)=>s.type._parseAsync(new Z(e,r,e.path,o)))).then(r=>L.mergeArray(i,r));const n=[...e.data].map((r,o)=>s.type._parseSync(new Z(e,r,e.path,o)));return L.mergeArray(i,n)}get element(){return this._def.type}min(t,e){return new K({...this._def,minLength:{value:t,message:g.toString(e)}})}max(t,e){return new K({...this._def,maxLength:{value:t,message:g.toString(e)}})}length(t,e){return new K({...this._def,exactLength:{value:t,message:g.toString(e)}})}nonempty(t){return this.min(1,t)}}K.create=(a,t)=>new K({type:a,minLength:null,maxLength:null,exactLength:null,typeName:x.ZodArray,...C(t)});function gt(a){if(a instanceof A){const t={};for(const e in a.shape){const i=a.shape[e];t[e]=Y.create(gt(i))}return new A({...a._def,shape:()=>t})}else return a instanceof K?new K({...a._def,type:gt(a.element)}):a instanceof Y?Y.create(gt(a.unwrap())):a instanceof nt?nt.create(gt(a.unwrap())):a instanceof W?W.create(a.items.map(t=>gt(t))):a}class A extends b{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const t=this._def.shape(),e=S.objectKeys(t);return this._cached={shape:t,keys:e}}_parse(t){if(this._getType(t)!==f.object){const l=this._getOrReturnCtx(t);return d(l,{code:u.invalid_type,expected:f.object,received:l.parsedType}),w}const{status:i,ctx:s}=this._processInputParams(t),{shape:n,keys:r}=this._getCached(),o=[];if(!(this._def.catchall instanceof tt&&this._def.unknownKeys==="strip"))for(const l in s.data)r.includes(l)||o.push(l);const h=[];for(const l of r){const c=n[l],m=s.data[l];h.push({key:{status:"valid",value:l},value:c._parse(new Z(s,m,s.path,l)),alwaysSet:l in s.data})}if(this._def.catchall instanceof tt){const l=this._def.unknownKeys;if(l==="passthrough")for(const c of o)h.push({key:{status:"valid",value:c},value:{status:"valid",value:s.data[c]}});else if(l==="strict")o.length>0&&(d(s,{code:u.unrecognized_keys,keys:o}),i.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const l=this._def.catchall;for(const c of o){const m=s.data[c];h.push({key:{status:"valid",value:c},value:l._parse(new Z(s,m,s.path,c)),alwaysSet:c in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const l=[];for(const c of h){const m=await c.key,p=await c.value;l.push({key:m,value:p,alwaysSet:c.alwaysSet})}return l}).then(l=>L.mergeObjectSync(i,l)):L.mergeObjectSync(i,h)}get shape(){return this._def.shape()}strict(t){return g.errToObj,new A({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(e,i)=>{var s,n,r,o;const h=(r=(n=(s=this._def).errorMap)===null||n===void 0?void 0:n.call(s,e,i).message)!==null&&r!==void 0?r:i.defaultError;return e.code==="unrecognized_keys"?{message:(o=g.errToObj(t).message)!==null&&o!==void 0?o:h}:{message:h}}}:{}})}strip(){return new A({...this._def,unknownKeys:"strip"})}passthrough(){return new A({...this._def,unknownKeys:"passthrough"})}extend(t){return new A({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new A({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:x.ZodObject})}setKey(t,e){return this.augment({[t]:e})}catchall(t){return new A({...this._def,catchall:t})}pick(t){const e={};return S.objectKeys(t).forEach(i=>{t[i]&&this.shape[i]&&(e[i]=this.shape[i])}),new A({...this._def,shape:()=>e})}omit(t){const e={};return S.objectKeys(this.shape).forEach(i=>{t[i]||(e[i]=this.shape[i])}),new A({...this._def,shape:()=>e})}deepPartial(){return gt(this)}partial(t){const e={};return S.objectKeys(this.shape).forEach(i=>{const s=this.shape[i];t&&!t[i]?e[i]=s:e[i]=s.optional()}),new A({...this._def,shape:()=>e})}required(t){const e={};return S.objectKeys(this.shape).forEach(i=>{if(t&&!t[i])e[i]=this.shape[i];else{let n=this.shape[i];for(;n instanceof Y;)n=n._def.innerType;e[i]=n}}),new A({...this._def,shape:()=>e})}keyof(){return _e(S.objectKeys(this.shape))}}A.create=(a,t)=>new A({shape:()=>a,unknownKeys:"strip",catchall:tt.create(),typeName:x.ZodObject,...C(t)}),A.strictCreate=(a,t)=>new A({shape:()=>a,unknownKeys:"strict",catchall:tt.create(),typeName:x.ZodObject,...C(t)}),A.lazycreate=(a,t)=>new A({shape:a,unknownKeys:"strip",catchall:tt.create(),typeName:x.ZodObject,...C(t)});class Dt extends b{_parse(t){const{ctx:e}=this._processInputParams(t),i=this._def.options;function s(n){for(const o of n)if(o.result.status==="valid")return o.result;for(const o of n)if(o.result.status==="dirty")return e.common.issues.push(...o.ctx.common.issues),o.result;const r=n.map(o=>new N(o.ctx.common.issues));return d(e,{code:u.invalid_union,unionErrors:r}),w}if(e.common.async)return Promise.all(i.map(async n=>{const r={...e,common:{...e.common,issues:[]},parent:null};return{result:await n._parseAsync({data:e.data,path:e.path,parent:r}),ctx:r}})).then(s);{let n;const r=[];for(const h of i){const l={...e,common:{...e.common,issues:[]},parent:null},c=h._parseSync({data:e.data,path:e.path,parent:l});if(c.status==="valid")return c;c.status==="dirty"&&!n&&(n={result:c,ctx:l}),l.common.issues.length&&r.push(l.common.issues)}if(n)return e.common.issues.push(...n.ctx.common.issues),n.result;const o=r.map(h=>new N(h));return d(e,{code:u.invalid_union,unionErrors:o}),w}}get options(){return this._def.options}}Dt.create=(a,t)=>new Dt({options:a,typeName:x.ZodUnion,...C(t)});const U=a=>a instanceof Nt?U(a.schema):a instanceof X?U(a.innerType()):a instanceof Ht?[a.value]:a instanceof st?a.options:a instanceof Bt?S.objectValues(a.enum):a instanceof Vt?U(a._def.innerType):a instanceof Rt?[void 0]:a instanceof zt?[null]:a instanceof Y?[void 0,...U(a.unwrap())]:a instanceof nt?[null,...U(a.unwrap())]:a instanceof Se||a instanceof jt?U(a.unwrap()):a instanceof Zt?U(a._def.innerType):[];class se extends b{_parse(t){const{ctx:e}=this._processInputParams(t);if(e.parsedType!==f.object)return d(e,{code:u.invalid_type,expected:f.object,received:e.parsedType}),w;const i=this.discriminator,s=e.data[i],n=this.optionsMap.get(s);return n?e.common.async?n._parseAsync({data:e.data,path:e.path,parent:e}):n._parseSync({data:e.data,path:e.path,parent:e}):(d(e,{code:u.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[i]}),w)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,e,i){const s=new Map;for(const n of e){const r=U(n.shape[t]);if(!r.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(const o of r){if(s.has(o))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(o)}`);s.set(o,n)}}return new se({typeName:x.ZodDiscriminatedUnion,discriminator:t,options:e,optionsMap:s,...C(i)})}}function ne(a,t){const e=J(a),i=J(t);if(a===t)return{valid:!0,data:a};if(e===f.object&&i===f.object){const s=S.objectKeys(t),n=S.objectKeys(a).filter(o=>s.indexOf(o)!==-1),r={...a,...t};for(const o of n){const h=ne(a[o],t[o]);if(!h.valid)return{valid:!1};r[o]=h.data}return{valid:!0,data:r}}else if(e===f.array&&i===f.array){if(a.length!==t.length)return{valid:!1};const s=[];for(let n=0;n<a.length;n++){const r=a[n],o=t[n],h=ne(r,o);if(!h.valid)return{valid:!1};s.push(h.data)}return{valid:!0,data:s}}else return e===f.date&&i===f.date&&+a==+t?{valid:!0,data:a}:{valid:!1}}class Mt extends b{_parse(t){const{status:e,ctx:i}=this._processInputParams(t),s=(n,r)=>{if(ve(n)||ve(r))return w;const o=ne(n.value,r.value);return o.valid?((xe(n)||xe(r))&&e.dirty(),{status:e.value,value:o.data}):(d(i,{code:u.invalid_intersection_types}),w)};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,r])=>s(n,r)):s(this._def.left._parseSync({data:i.data,path:i.path,parent:i}),this._def.right._parseSync({data:i.data,path:i.path,parent:i}))}}Mt.create=(a,t,e)=>new Mt({left:a,right:t,typeName:x.ZodIntersection,...C(e)});class W extends b{_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.parsedType!==f.array)return d(i,{code:u.invalid_type,expected:f.array,received:i.parsedType}),w;if(i.data.length<this._def.items.length)return d(i,{code:u.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),w;!this._def.rest&&i.data.length>this._def.items.length&&(d(i,{code:u.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),e.dirty());const n=[...i.data].map((r,o)=>{const h=this._def.items[o]||this._def.rest;return h?h._parse(new Z(i,r,i.path,o)):null}).filter(r=>!!r);return i.common.async?Promise.all(n).then(r=>L.mergeArray(e,r)):L.mergeArray(e,n)}get items(){return this._def.items}rest(t){return new W({...this._def,rest:t})}}W.create=(a,t)=>{if(!Array.isArray(a))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new W({items:a,typeName:x.ZodTuple,rest:null,...C(t)})};class Ft extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.parsedType!==f.object)return d(i,{code:u.invalid_type,expected:f.object,received:i.parsedType}),w;const s=[],n=this._def.keyType,r=this._def.valueType;for(const o in i.data)s.push({key:n._parse(new Z(i,o,i.path,o)),value:r._parse(new Z(i,i.data[o],i.path,o)),alwaysSet:o in i.data});return i.common.async?L.mergeObjectAsync(e,s):L.mergeObjectSync(e,s)}get element(){return this._def.valueType}static create(t,e,i){return e instanceof b?new Ft({keyType:t,valueType:e,typeName:x.ZodRecord,...C(i)}):new Ft({keyType:$.create(),valueType:t,typeName:x.ZodRecord,...C(e)})}}class ae extends b{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.parsedType!==f.map)return d(i,{code:u.invalid_type,expected:f.map,received:i.parsedType}),w;const s=this._def.keyType,n=this._def.valueType,r=[...i.data.entries()].map(([o,h],l)=>({key:s._parse(new Z(i,o,i.path,[l,"key"])),value:n._parse(new Z(i,h,i.path,[l,"value"]))}));if(i.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const h of r){const l=await h.key,c=await h.value;if(l.status==="aborted"||c.status==="aborted")return w;(l.status==="dirty"||c.status==="dirty")&&e.dirty(),o.set(l.value,c.value)}return{status:e.value,value:o}})}else{const o=new Map;for(const h of r){const l=h.key,c=h.value;if(l.status==="aborted"||c.status==="aborted")return w;(l.status==="dirty"||c.status==="dirty")&&e.dirty(),o.set(l.value,c.value)}return{status:e.value,value:o}}}}ae.create=(a,t,e)=>new ae({valueType:t,keyType:a,typeName:x.ZodMap,...C(e)});class mt extends b{_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.parsedType!==f.set)return d(i,{code:u.invalid_type,expected:f.set,received:i.parsedType}),w;const s=this._def;s.minSize!==null&&i.data.size<s.minSize.value&&(d(i,{code:u.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),e.dirty()),s.maxSize!==null&&i.data.size>s.maxSize.value&&(d(i,{code:u.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),e.dirty());const n=this._def.valueType;function r(h){const l=new Set;for(const c of h){if(c.status==="aborted")return w;c.status==="dirty"&&e.dirty(),l.add(c.value)}return{status:e.value,value:l}}const o=[...i.data.values()].map((h,l)=>n._parse(new Z(i,h,i.path,l)));return i.common.async?Promise.all(o).then(h=>r(h)):r(o)}min(t,e){return new mt({...this._def,minSize:{value:t,message:g.toString(e)}})}max(t,e){return new mt({...this._def,maxSize:{value:t,message:g.toString(e)}})}size(t,e){return this.min(t,e).max(t,e)}nonempty(t){return this.min(1,t)}}mt.create=(a,t)=>new mt({valueType:a,minSize:null,maxSize:null,typeName:x.ZodSet,...C(t)});class St extends b{constructor(){super(...arguments),this.validate=this.implement}_parse(t){const{ctx:e}=this._processInputParams(t);if(e.parsedType!==f.function)return d(e,{code:u.invalid_type,expected:f.function,received:e.parsedType}),w;function i(o,h){return qt({data:o,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,Gt(),wt].filter(l=>!!l),issueData:{code:u.invalid_arguments,argumentsError:h}})}function s(o,h){return qt({data:o,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,Gt(),wt].filter(l=>!!l),issueData:{code:u.invalid_return_type,returnTypeError:h}})}const n={errorMap:e.common.contextualErrorMap},r=e.data;if(this._def.returns instanceof Tt){const o=this;return z(async function(...h){const l=new N([]),c=await o._def.args.parseAsync(h,n).catch(k=>{throw l.addIssue(i(h,k)),l}),m=await Reflect.apply(r,this,c);return await o._def.returns._def.type.parseAsync(m,n).catch(k=>{throw l.addIssue(s(m,k)),l})})}else{const o=this;return z(function(...h){const l=o._def.args.safeParse(h,n);if(!l.success)throw new N([i(h,l.error)]);const c=Reflect.apply(r,this,l.data),m=o._def.returns.safeParse(c,n);if(!m.success)throw new N([s(c,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new St({...this._def,args:W.create(t).rest(pt.create())})}returns(t){return new St({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,e,i){return new St({args:t||W.create([]).rest(pt.create()),returns:e||pt.create(),typeName:x.ZodFunction,...C(i)})}}class Nt extends b{get schema(){return this._def.getter()}_parse(t){const{ctx:e}=this._processInputParams(t);return this._def.getter()._parse({data:e.data,path:e.path,parent:e})}}Nt.create=(a,t)=>new Nt({getter:a,typeName:x.ZodLazy,...C(t)});class Ht extends b{_parse(t){if(t.data!==this._def.value){const e=this._getOrReturnCtx(t);return d(e,{received:e.data,code:u.invalid_literal,expected:this._def.value}),w}return{status:"valid",value:t.data}}get value(){return this._def.value}}Ht.create=(a,t)=>new Ht({value:a,typeName:x.ZodLiteral,...C(t)});function _e(a,t){return new st({values:a,typeName:x.ZodEnum,...C(t)})}class st extends b{constructor(){super(...arguments),kt.set(this,void 0)}_parse(t){if(typeof t.data!="string"){const e=this._getOrReturnCtx(t),i=this._def.values;return d(e,{expected:S.joinValues(i),received:e.parsedType,code:u.invalid_type}),w}if(Lt(this,kt)||we(this,kt,new Set(this._def.values)),!Lt(this,kt).has(t.data)){const e=this._getOrReturnCtx(t),i=this._def.values;return d(e,{received:e.data,code:u.invalid_enum_value,options:i}),w}return z(t.data)}get options(){return this._def.values}get enum(){const t={};for(const e of this._def.values)t[e]=e;return t}get Values(){const t={};for(const e of this._def.values)t[e]=e;return t}get Enum(){const t={};for(const e of this._def.values)t[e]=e;return t}extract(t,e=this._def){return st.create(t,{...this._def,...e})}exclude(t,e=this._def){return st.create(this.options.filter(i=>!t.includes(i)),{...this._def,...e})}}kt=new WeakMap,st.create=_e;class Bt extends b{constructor(){super(...arguments),bt.set(this,void 0)}_parse(t){const e=S.getValidEnumValues(this._def.values),i=this._getOrReturnCtx(t);if(i.parsedType!==f.string&&i.parsedType!==f.number){const s=S.objectValues(e);return d(i,{expected:S.joinValues(s),received:i.parsedType,code:u.invalid_type}),w}if(Lt(this,bt)||we(this,bt,new Set(S.getValidEnumValues(this._def.values))),!Lt(this,bt).has(t.data)){const s=S.objectValues(e);return d(i,{received:i.data,code:u.invalid_enum_value,options:s}),w}return z(t.data)}get enum(){return this._def.values}}bt=new WeakMap,Bt.create=(a,t)=>new Bt({values:a,typeName:x.ZodNativeEnum,...C(t)});class Tt extends b{unwrap(){return this._def.type}_parse(t){const{ctx:e}=this._processInputParams(t);if(e.parsedType!==f.promise&&e.common.async===!1)return d(e,{code:u.invalid_type,expected:f.promise,received:e.parsedType}),w;const i=e.parsedType===f.promise?e.data:Promise.resolve(e.data);return z(i.then(s=>this._def.type.parseAsync(s,{path:e.path,errorMap:e.common.contextualErrorMap})))}}Tt.create=(a,t)=>new Tt({type:a,typeName:x.ZodPromise,...C(t)});class X extends b{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===x.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){const{status:e,ctx:i}=this._processInputParams(t),s=this._def.effect||null,n={addIssue:r=>{d(i,r),r.fatal?e.abort():e.dirty()},get path(){return i.path}};if(n.addIssue=n.addIssue.bind(n),s.type==="preprocess"){const r=s.transform(i.data,n);if(i.common.async)return Promise.resolve(r).then(async o=>{if(e.value==="aborted")return w;const h=await this._def.schema._parseAsync({data:o,path:i.path,parent:i});return h.status==="aborted"?w:h.status==="dirty"||e.value==="dirty"?Ct(h.value):h});{if(e.value==="aborted")return w;const o=this._def.schema._parseSync({data:r,path:i.path,parent:i});return o.status==="aborted"?w:o.status==="dirty"||e.value==="dirty"?Ct(o.value):o}}if(s.type==="refinement"){const r=o=>{const h=s.refinement(o,n);if(i.common.async)return Promise.resolve(h);if(h 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"?w:(o.status==="dirty"&&e.dirty(),r(o.value),{status:e.value,value:o.value})}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(o=>o.status==="aborted"?w:(o.status==="dirty"&&e.dirty(),r(o.value).then(()=>({status:e.value,value:o.value}))))}if(s.type==="transform")if(i.common.async===!1){const r=this._def.schema._parseSync({data:i.data,path:i.path,parent:i});if(!ut(r))return r;const o=s.transform(r.value,n);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:e.value,value:o}}else return this._def.schema._parseAsync({data:i.data,path:i.path,parent:i}).then(r=>ut(r)?Promise.resolve(s.transform(r.value,n)).then(o=>({status:e.value,value:o})):r);S.assertNever(s)}}X.create=(a,t,e)=>new X({schema:a,typeName:x.ZodEffects,effect:t,...C(e)}),X.createWithPreprocess=(a,t,e)=>new X({schema:t,effect:{type:"preprocess",transform:a},typeName:x.ZodEffects,...C(e)});class Y extends b{_parse(t){return this._getType(t)===f.undefined?z(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}Y.create=(a,t)=>new Y({innerType:a,typeName:x.ZodOptional,...C(t)});class nt extends b{_parse(t){return this._getType(t)===f.null?z(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}}nt.create=(a,t)=>new nt({innerType:a,typeName:x.ZodNullable,...C(t)});class Vt extends b{_parse(t){const{ctx:e}=this._processInputParams(t);let i=e.data;return e.parsedType===f.undefined&&(i=this._def.defaultValue()),this._def.innerType._parse({data:i,path:e.path,parent:e})}removeDefault(){return this._def.innerType}}Vt.create=(a,t)=>new Vt({innerType:a,typeName:x.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...C(t)});class Zt extends b{_parse(t){const{ctx:e}=this._processInputParams(t),i={...e,common:{...e.common,issues:[]}},s=this._def.innerType._parse({data:i.data,path:i.path,parent:{...i}});return Et(s)?s.then(n=>({status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new N(i.common.issues)},input:i.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new N(i.common.issues)},input:i.data})}}removeCatch(){return this._def.innerType}}Zt.create=(a,t)=>new Zt({innerType:a,typeName:x.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...C(t)});class re extends b{_parse(t){if(this._getType(t)!==f.nan){const i=this._getOrReturnCtx(t);return d(i,{code:u.invalid_type,expected:f.nan,received:i.parsedType}),w}return{status:"valid",value:t.data}}}re.create=a=>new re({typeName:x.ZodNaN,...C(a)});class Se extends b{_parse(t){const{ctx:e}=this._processInputParams(t),i=e.data;return this._def.type._parse({data:i,path:e.path,parent:e})}unwrap(){return this._def.type}}class Kt extends b{_parse(t){const{status:e,ctx:i}=this._processInputParams(t);if(i.common.async)return(async()=>{const n=await this._def.in._parseAsync({data:i.data,path:i.path,parent:i});return n.status==="aborted"?w:n.status==="dirty"?(e.dirty(),Ct(n.value)):this._def.out._parseAsync({data:n.value,path:i.path,parent:i})})();{const s=this._def.in._parseSync({data:i.data,path:i.path,parent:i});return s.status==="aborted"?w:s.status==="dirty"?(e.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:i.path,parent:i})}}static create(t,e){return new Kt({in:t,out:e,typeName:x.ZodPipeline})}}class jt extends b{_parse(t){const e=this._def.innerType._parse(t),i=s=>(ut(s)&&(s.value=Object.freeze(s.value)),s);return Et(e)?e.then(s=>i(s)):i(e)}unwrap(){return this._def.innerType}}jt.create=(a,t)=>new jt({innerType:a,typeName:x.ZodReadonly,...C(t)}),A.lazycreate;var x;(function(a){a.ZodString="ZodString",a.ZodNumber="ZodNumber",a.ZodNaN="ZodNaN",a.ZodBigInt="ZodBigInt",a.ZodBoolean="ZodBoolean",a.ZodDate="ZodDate",a.ZodSymbol="ZodSymbol",a.ZodUndefined="ZodUndefined",a.ZodNull="ZodNull",a.ZodAny="ZodAny",a.ZodUnknown="ZodUnknown",a.ZodNever="ZodNever",a.ZodVoid="ZodVoid",a.ZodArray="ZodArray",a.ZodObject="ZodObject",a.ZodUnion="ZodUnion",a.ZodDiscriminatedUnion="ZodDiscriminatedUnion",a.ZodIntersection="ZodIntersection",a.ZodTuple="ZodTuple",a.ZodRecord="ZodRecord",a.ZodMap="ZodMap",a.ZodSet="ZodSet",a.ZodFunction="ZodFunction",a.ZodLazy="ZodLazy",a.ZodLiteral="ZodLiteral",a.ZodEnum="ZodEnum",a.ZodEffects="ZodEffects",a.ZodNativeEnum="ZodNativeEnum",a.ZodOptional="ZodOptional",a.ZodNullable="ZodNullable",a.ZodDefault="ZodDefault",a.ZodCatch="ZodCatch",a.ZodPromise="ZodPromise",a.ZodBranded="ZodBranded",a.ZodPipeline="ZodPipeline",a.ZodReadonly="ZodReadonly"})(x||(x={}));const R=$.create,v=dt.create;re.create,ft.create,Jt.create,_t.create,te.create,Rt.create,zt.create,ee.create,pt.create,tt.create,ie.create,K.create;const T=A.create;A.strictCreate;const vi=Dt.create;se.create,Mt.create,W.create,Ft.create,ae.create,mt.create,St.create,Nt.create;const at=Ht.create,et=st.create;Bt.create,Tt.create,X.create,Y.create,nt.create,X.createWithPreprocess,Kt.create;const xi=et(["linear","bezier","constant"]),wi=et(["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"]),rt=T({from:v(),to:v(),start:v().min(0),length:v().positive(),interpolation:xi.optional(),easing:wi.optional()}),Ci=R().url("Invalid audio url format."),ki=rt.extend({from:v().min(0).max(1),to:v().min(0).max(1)}).array().or(v().min(0).max(1)),Te=T({type:at("audio"),src:Ci,trim:v().optional(),volume:ki.optional()}),bi=et(["top","topRight","right","bottomRight","bottom","bottomLeft","left","topLeft","center"]),Oe=T({type:at("html"),html:R(),css:R(),width:v().positive().optional(),height:v().positive().optional(),position:bi.optional()}),_i=R().url("Invalid image url format."),Si=T({top:v().min(0).optional(),right:v().min(0).optional(),bottom:v().min(0).optional(),left:v().min(0).optional()}),Ie=T({type:at("image"),src:_i,crop:Si.optional()}),Ti=R().url("Invalid luma url format."),Ae=T({type:at("luma"),src:Ti}),Pe=R().regex(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})|transparent$/,"Invalid color format."),Ee=T({width:v().positive(),height:v().positive()}),Le=T({radius:v().positive()}),Re=T({length:v().positive(),thickness:v().positive()}),Oi=T({color:Pe,opacity:v().min(0).max(1)}),Ii=T({color:Pe,width:v().positive()}),ze=T({type:at("shape"),width:v().positive().optional(),height:v().positive().optional(),shape:et(["rectangle","circle","line"]),fill:Oi.optional(),stroke:Ii.optional(),rectangle:Ee.optional(),circle:Le.optional(),line:Re.optional()}).refine(a=>a.shape==="rectangle"?Ee.safeParse(a.rectangle):a.shape==="circle"?Le.safeParse(a.circle):a.shape==="line"?Re.safeParse(a.line):!1),oe=R().regex(/^#([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})|transparent$/,"Invalid color format."),Ai=T({color:oe.optional(),family:R().optional(),size:v().positive().optional(),weight:v().optional(),lineHeight:v().optional()}),Pi=T({horizontal:et(["left","center","right"]).optional(),vertical:et(["top","center","bottom"]).optional()}),Ei=T({color:oe,opacity:v().min(0).max(1)}),Li=T({width:v().positive(),color:oe}),De=T({type:at("text"),text:R(),width:v().positive().optional(),height:v().positive().optional(),font:Ai.optional(),alignment:Pi.optional(),background:Ei.optional(),stroke:Li.optional()}),Ri=R().url("Invalid video url format."),zi=T({top:v().min(0).optional(),right:v().min(0).optional(),bottom:v().min(0).optional(),left:v().min(0).optional()}),Di=rt.extend({from:v().min(0).max(1),to:v().min(0).max(1)}).array().or(v().min(0).max(1)),Me=T({type:at("video"),src:Ri,trim:v().optional(),crop:zi.optional(),volume:Di.optional()}),Mi=vi([De,ze,Oe,Ie,Me,Ae,Te]).refine(a=>a.type==="text"?De.safeParse(a):a.type==="shape"?ze.safeParse(a):a.type==="html"?Oe.safeParse(a):a.type==="image"?Ie.safeParse(a):a.type==="video"?Me.safeParse(a):a.type==="luma"?Ae.safeParse(a):a.type==="audio"?Te.safeParse(a):!1),Fi=et(["topLeft","top","topRight","left","center","right","bottomLeft","bottom","bottomRight"]),Ni=et(["crop","cover","contain","none"]),yt=v().min(-10).max(10).default(0),Hi=rt.extend({from:yt,to:yt}).array().or(yt),Bi=rt.extend({from:yt,to:yt}).array().or(yt),Vi=T({x:Hi.default(0),y:Bi.default(0)}),Zi=rt.extend({from:v().min(0).max(1),to:v().min(0).max(1)}).array().or(v().min(0).max(1)),Ki=rt.extend({from:v().min(0),to:v().min(0)}).array().or(v().min(0)),ji=T({angle:rt.extend({from:v(),to:v()}).array().or(v())}),$i=R(),Fe=R(),Ui=T({in:Fe.optional(),out:Fe.optional()}),Wi=T({rotate:ji.default({angle:0})}),Ne=T({asset:Mi,start:v().min(0),length:v().positive(),position:Fi.default("center").optional(),fit:Ni.default("crop").optional(),offset:Vi.default({x:0,y:0}).optional(),opacity:Zi.default(1).optional(),scale:Ki.default(1).optional(),transform:Wi.default({rotate:{angle:0}}).optional(),effect:$i.optional(),transition:Ui.optional()}),Xi=T({clips:Ne.array()}),Yi=R().url("Invalid image url format."),Gi=T({src:Yi}),qi=T({background:R().optional(),fonts:Gi.array().optional(),tracks:Xi.array()}),Qi=T({size:T({width:v().positive(),height:v().positive()}),fps:v().positive().optional(),format:R()}),Ji=T({timeline:qi,output:Qi});class le{container;constructor(){this.container=new y.Container}getContainer(){return this.container}}class ts{curves={};constructor(){this.initializeCurves()}initializeCurves(){this.curves={ease:[[.25,.1],[.25,1]],easeIn:[[.42,0],[1,1]],easeOut:[[0,0],[.58,1]],easeInOut:[[.42,0],[.58,1]],easeInQuad:[[.55,.085],[.68,.53]],easeInCubic:[[.55,.055],[.675,.19]],easeInQuart:[[.895,.03],[.685,.22]],easeInQuint:[[.755,.05],[.855,.06]],easeInSine:[[.47,0],[.745,.715]],easeInExpo:[[.95,.05],[.795,.035]],easeInCirc:[[.6,.04],[.98,.335]],easeInBack:[[.6,-.28],[.735,.045]],easeOutQuad:[[.25,.46],[.45,.94]],easeOutCubic:[[.215,.61],[.355,1]],easeOutQuart:[[.165,.84],[.44,1]],easeOutQuint:[[.23,1],[.32,1]],easeOutSine:[[.39,.575],[.565,1]],easeOutExpo:[[.19,1],[.22,1]],easeOutCirc:[[.075,.82],[.165,1]],easeOutBack:[[.175,.885],[.32,1.275]],easeInOutQuad:[[.455,.03],[.515,.955]],easeInOutCubic:[[.645,.045],[.355,1]],easeInOutQuart:[[.77,0],[.175,1]],easeInOutQuint:[[.86,0],[.07,1]],easeInOutSine:[[.445,.05],[.55,.95]],easeInOutExpo:[[1,0],[0,1]],easeInOutCirc:[[.785,.135],[.15,.86]],easeInOutBack:[[.68,-.55],[.265,1.55]]}}getValue(t,e,i,s){const n=this.curves[s??""]??this.curves.ease,[[r,o],[h,l]]=n,c=i+(3*r-3*h+1)*i*(1-i),m=t,p=t+(e-t)*o,k=t+(e-t)*l,O=e,_=c,D=1-_;return D**3*m+3*D**2*_*p+3*D*_**2*k+_**3*O}}class E{property;length;cubicBuilder;constructor(t,e,i=0){this.property=this.createKeyframes(t,e,i),this.length=e,this.cubicBuilder=new ts}getValue(t){const e=this.property.find(s=>t>=s.start&&t<s.start+s.length);if(!e){if(this.property.length>0){if(t>=this.length)return this.property[this.property.length-1].to;if(t<0)return this.property[0].from}return 1}const i=(t-e.start)/e.length;switch(e.interpolation){case"bezier":return this.cubicBuilder.getValue(e.from,e.to,i,e.easing);case"constant":return e.from;case"linear":default:return e.from+(e.to-e.from)*i}}createKeyframes(t,e,i=0){if(typeof t=="number")return[{start:0,length:e,from:t,to:t}];if(!t.length)throw new Error("Keyframes should have at least one value.");const s=this.createNormalizedKeyframes(t);try{this.validateKeyframes(s)}catch(n){console.warn("Keyframe configuration issues detected:",n)}return this.insertFillerKeyframes(s,e,i)}createNormalizedKeyframes(t){return t.toSorted((e,i)=>e.start-i.start).map(e=>({...e,start:e.start*1e3,length:e.length*1e3}))}validateKeyframes(t){for(let e=0;e<t.length;e+=1){const i=t[e],s=t[e+1];if(!s){if(i.start+i.length>this.length)throw new Error("Last keyframe exceeds the maximum duration.");break}if(i.start+i.length>s.start)throw new Error("Overlapping keyframes detected.")}}insertFillerKeyframes(t,e,i=0){const s=[];for(let n=0;n<t.length;n+=1){const r=t[n],o=t[n+1];if(n===0&&r.start!==0){const c={start:0,length:r.start,from:i,to:r.from};s.push(c)}if(s.push(r),!o){if(r.start+r.length<e){const m=r.start+r.length,p={start:m,length:e-m,from:r.to,to:r.to};s.push(p)}break}if(r.start+r.length!==o.start){const c={start:r.start+r.length,length:o.start,from:r.to,to:o.from};s.push(c)}}return s}}class $t{static Name="AudioLoadParser";name;extension;validAudioExtensions;constructor(){this.name=$t.Name,this.extension={type:[y.ExtensionType.LoadParser],priority:y.LoaderParserPriority.Normal,ref:null},this.validAudioExtensions=["mp3","mpeg","ogg","wav"]}test(t){const e=t.split("?")[0]?.split(".").pop()??"";return this.validAudioExtensions.includes(e)}async load(t,e,i){return new Promise(s=>{const n={src:t},r=new Howl(n);r.on("load",()=>s(r)),r.on("loaderror",()=>s(null))})}unload(t){t?.unload()}}class es{clipConfiguration;constructor(t){this.clipConfiguration=t}build(t,e){const i=[],s=[],n=[],r=[],o=[],{effect:h,length:l}=this.clipConfiguration;if(!h)return{offsetXKeyframes:i,offsetYKeyframes:s,opacityKeyframes:n,scaleKeyframes:r,rotationKeyframes:o};const c=0;switch(this.getPresetName()){case"zoomIn":{const p=this.getZoomSpeed(),k=1*this.clipConfiguration.scale,O=p*this.clipConfiguration.scale;r.push({from:k,to:O,start:c,length:l,interpolation:"linear"});break}case"zoomOut":{const k=this.getZoomSpeed()*this.clipConfiguration.scale,O=1*this.clipConfiguration.scale;r.push({from:k,to:O,start:c,length:l,interpolation:"linear"});break}case"slideLeft":{let p=this.getSlideStart();const k=t.width+t.width*p*2,O=e.height/e.width*t.height;if(O<k){const _=Math.abs(k/t.width);r.push({from:_,to:_,start:c,length:l,interpolation:"linear"})}else p=(O-t.width)/2/t.width;i.push({from:p,to:-p,start:c,length:l});break}case"slideRight":{let p=this.getSlideStart();const k=t.width+t.width*p*2,O=e.height/e.width*t.height;if(O<k){const _=Math.abs(k/t.width);r.push({from:_,to:_,start:c,length:l,interpolation:"linear"})}else p=(O-t.width)/2/t.width;i.push({from:-p,to:p,start:c,length:l});break}case"slideUp":{let p=this.getSlideStart();const k=t.height+t.height*p*2,O=e.height/e.width*t.width;if(O<k){const _=Math.abs(k/t.height);r.push({from:_,to:_,start:c,length:l,interpolation:"linear"})}else p=(O-t.height)/2/t.height;s.push({from:p,to:-p,start:c,length:l});break}case"slideDown":{let p=this.getSlideStart();const k=t.height+t.height*p*2,O=e.height/e.width*t.width;if(O<k){const _=Math.abs(k/t.height);r.push({from:_,to:_,start:c,length:l,interpolation:"linear"})}else p=(O-t.height)/2/t.height;s.push({from:-p,to:p,start:c,length:l});break}}return{offsetXKeyframes:i,offsetYKeyframes:s,opacityKeyframes:n,scaleKeyframes:r,rotationKeyframes:o}}getPresetName(){const[t]=(this.clipConfiguration.effect??"").split(/(Slow|Fast)/);return t}getZoomSpeed(){const[t,e]=(this.clipConfiguration.effect??"").split(/(Slow|Fast)/);if(t.startsWith("zoom"))switch(e){case"Slow":return 1.1;case"Fast":return 1.7;default:return 1.3}return 0}getSlideStart(){const[t,e]=(this.clipConfiguration.effect??"").split(/(Slow|Fast)/);if(t.startsWith("slide"))switch(e){case"Slow":return .03;case"Fast":return 1.7;default:return .12}return 0}}class is{clipConfiguration;constructor(t){this.clipConfiguration=t}build(){const t=[],e=[],i=[],s=[],n=[],r=this.buildInPreset();t.push(...r.offsetXKeyframes),e.push(...r.offsetYKeyframes),i.push(...r.opacityKeyframes),s.push(...r.scaleKeyframes),n.push(...r.rotationKeyframes);const o=this.buildOutPreset();return t.push(...o.offsetXKeyframes),e.push(...o.offsetYKeyframes),i.push(...o.opacityKeyframes),s.push(...o.scaleKeyframes),n.push(...o.rotationKeyframes),{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n}}buildInPreset(){const t=[],e=[],i=[],s=[],n=[];if(!this.clipConfiguration.transition?.in)return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n};const r=0,o=this.getInPresetLength();switch(this.getInPresetName()){case"fade":{const c=Math.max(0,Math.min(this.clipConfiguration.opacity??1,1));i.push({from:0,to:c,start:r,length:o,interpolation:"linear"});break}case"zoom":{const c=this.clipConfiguration.scale+9,m=this.clipConfiguration.scale;s.push({from:c,to:m,start:r,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:r,length:o,interpolation:"bezier",easing:"easeIn"});break}case"slideLeft":{const l=this.clipConfiguration.offset?.x+.025,c=this.clipConfiguration.offset?.x;t.push({from:l,to:c,start:r,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:r,length:o,interpolation:"bezier",easing:"easeIn"});break}case"slideRight":{const l=this.clipConfiguration.offset?.x-.025,c=this.clipConfiguration.offset?.x;t.push({from:l,to:c,start:r,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:r,length:o,interpolation:"bezier",easing:"easeIn"});break}case"slideUp":{const l=this.clipConfiguration.offset?.y+.025,c=this.clipConfiguration.offset?.y;e.push({from:l,to:c,start:r,length:o,interpolation:"bezier",easing:"easeIn"}),i.push({from:0,to:1,start:r,length:o,interpolation:"bezier",easing:"easeIn"});break}case"slideDown":{const l=this.clipConfiguration.offset?.y-.025,c=this.clipConfiguration.offset?.y;e.push({from:l,to:c,start:r,length:o,interpolation:"bezier",easing:"easeOut"}),i.push({from:0,to:1,start:r,length:o,interpolation:"bezier",easing:"easeOut"});break}case"carouselLeft":case"carouselRight":case"carouselUp":case"carouselDown":case"shuffleTopRight":case"shuffleRightTop":case"shuffleRightBottom":case"shuffleBottomRight":case"shuffleBottomLeft":case"shuffleLeftBottom":case"shuffleLeftTop":case"shuffleTopLeft":default:console.warn(`Unimplemented transition:in preset "${this.clipConfiguration.transition.in}"`);break}return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n}}buildOutPreset(){const t=[],e=[],i=[],s=[],n=[];if(!this.clipConfiguration.transition?.out)return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n};const r=this.getOutPresetLength(),o=this.clipConfiguration.length-r;switch(this.getOutPresetName()){case"fade":{const l=Math.max(0,Math.min(this.clipConfiguration.opacity??1,1));i.push({from:l,to:0,start:o,length:r,interpolation:"linear"});break}case"zoom":{const c=this.clipConfiguration.scale,m=c+9;s.push({from:c,to:m,start:o,length:r,interpolation:"bezier",easing:"easeOut"}),i.push({from:1,to:0,start:o,length:r,interpolation:"bezier",easing:"easeOut"});break}case"slideLeft":{const l=this.clipConfiguration.offset?.x,c=l-.025;t.push({from:l,to:c,start:o,length:r,interpolation:"bezier",easing:"easeOut"}),i.push({from:1,to:0,start:o,length:r,interpolation:"bezier",easing:"easeOut"});break}case"slideRight":{const l=this.clipConfiguration.offset?.x,c=l+.025;t.push({from:l,to:c,start:o,length:r,interpolation:"bezier",easing:"easeOut"}),i.push({from:1,to:0,start:o,length:r,interpolation:"bezier",easing:"easeOut"});break}case"slideUp":{const l=this.clipConfiguration.offset?.y,c=l-.025;e.push({from:l,to:c,start:o,length:r,interpolation:"bezier",easing:"easeIn"}),i.push({from:1,to:0,start:o,length:r,interpolation:"bezier",easing:"easeIn"});break}case"slideDown":{const l=this.clipConfiguration.offset?.y,c=l+.025;e.push({from:l,to:c,start:o,length:r,interpolation:"bezier",easing:"easeIn"}),i.push({from:1,to:0,start:o,length:r,interpolation:"bezier",easing:"easeIn"});break}case"carouselLeft":case"carouselRight":case"carouselUp":case"carouselDown":case"shuffleTopRight":case"shuffleRightTop":case"shuffleRightBottom":case"shuffleBottomRight":case"shuffleBottomLeft":case"shuffleLeftBottom":case"shuffleLeftTop":case"shuffleTopLeft":default:console.warn(`Unimplemented transition:out preset "${this.clipConfiguration.transition.out}"`);break}return{offsetXKeyframes:t,offsetYKeyframes:e,opacityKeyframes:i,scaleKeyframes:s,rotationKeyframes:n}}getInPresetName(){const[t]=(this.clipConfiguration.transition?.in??"").split(/(Slow|Fast|VeryFast)/);return t}getOutPresetName(){const[t]=(this.clipConfiguration.transition?.out??"").split(/(Slow|Fast|VeryFast)/);return t}getInPresetLength(){const[,t]=(this.clipConfiguration.transition?.in??"").split(/(Slow|Fast|VeryFast)/);switch(t){case"Slow":return 2;case"Fast":return .5;case"VeryFast":return .25;default:return 1}}getOutPresetLength(){const[,t]=(this.clipConfiguration.transition?.out??"").split(/(Slow|Fast|VeryFast)/);switch(t){case"Slow":return 2;case"Fast":return .5;case"VeryFast":return .25;default:return 1}}}class ss{static ButtonLeftClick=0;static ButtonRightClick=3}class ns{containerSize;constructor(t){this.containerSize=t}relativeToAbsolute(t,e,i){switch(e){case"topLeft":return{x:i.x*this.containerSize.width,y:-i.y*this.containerSize.height};case"topRight":return{x:(i.x+1)*this.containerSize.width-t.width,y:-i.y*this.containerSize.height};case"bottomLeft":return{x:i.x*this.containerSize.width,y:(-i.y+1)*this.containerSize.height-t.height};case"bottomRight":return{x:(i.x+1)*this.containerSize.width-t.width,y:(-i.y+1)*this.containerSize.height-t.height};case"left":return{x:i.x*this.containerSize.width,y:(-i.y+.5)*this.containerSize.height-t.height/2};case"right":return{x:(i.x+1)*this.containerSize.width-t.width,y:(-i.y+.5)*this.containerSize.height-t.height/2};case"top":return{x:(i.x+.5)*this.containerSize.width-t.width/2,y:-i.y*this.containerSize.height};case"bottom":return{x:(i.x+.5)*this.containerSize.width-t.width/2,y:(-i.y+1)*this.containerSize.height-t.height};case"center":default:return{x:(i.x+.5)*this.containerSize.width-t.width/2,y:(-i.y+.5)*this.containerSize.height-t.height/2}}}absoluteToRelative(t,e,i){switch(e){case"topLeft":return{x:i.x/this.containerSize.width,y:-(i.y/this.containerSize.height)};case"topRight":return{x:(i.x+t.width)/this.containerSize.width-1,y:-(i.y/this.containerSize.height)};case"bottomLeft":return{x:i.x/this.containerSize.width,y:-((i.y+t.height)/this.containerSize.height-1)};case"bottomRight":return{x:(i.x+t.width)/this.containerSize.width-1,y:-((i.y+t.height)/this.containerSize.height-1)};case"left":return{x:i.x/this.containerSize.width,y:-((i.y+t.height/2)/this.containerSize.height-.5)};case"right":return{x:(i.x+t.width)/this.containerSize.width-1,y:-((i.y+t.height/2)/this.containerSize.height-.5)};case"top":return{x:(i.x+t.width/2)/this.containerSize.width-.5,y:-(i.y/this.containerSize.height)};case"bottom":return{x:(i.x+t.width/2)/this.containerSize.width-.5,y:-((i.y+t.height)/this.containerSize.height-1)};case"center":default:return{x:(i.x+t.width/2)/this.containerSize.width-.5,y:-((i.y+t.height/2)/this.containerSize.height-.5)}}}}class P extends le{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;constructor(t,e){super(),this.edit=t,this.layer=0,this.shouldDispose=!1,this.clipConfiguration=e,this.positionBuilder=new ns(t.size),this.outline=null,this.topLeftScaleHandle=null,this.topRightScaleHandle=null,this.bottomRightScaleHandle=null,this.bottomLeftScaleHandle=null,this.rotationHandle=null,this.isHovering=!1,this.isDragging=!1,this.dragOffset={x:0,y:0},this.scaleDirection=null,this.scaleStart=null,this.scaleOffset={x:0,y:0},this.isRotating=!1,this.rotationStart=null,this.rotationOffset={x:0,y:0},this.initialClipConfiguration=null}configureKeyframes(){if(this.offsetXKeyframeBuilder=new E(this.clipConfiguration.offset?.x??0,this.getLength()),this.offsetYKeyframeBuilder=new E(this.clipConfiguration.offset?.y??0,this.getLength()),this.scaleKeyframeBuilder=new E(this.clipConfiguration.scale??1,this.getLength(),1),this.opacityKeyframeBuilder=new E(this.clipConfiguration.opacity??1,this.getLength(),1),this.rotationKeyframeBuilder=new E(this.clipConfiguration.transform?.rotate?.angle??0,this.getLength()),this.clipHasKeyframes())return;const t=[],e=[],i=[],s=[],n=[],r=new es(this.clipConfiguration).build(this.edit.size,this.getSize());t.push(...r.offsetXKeyframes),e.push(...r.offsetYKeyframes),i.push(...r.opacityKeyframes),s.push(...r.scaleKeyframes),n.push(...r.rotationKeyframes);const o=new is(this.clipConfiguration).build();t.push(...o.offsetXKeyframes),e.push(...o.offsetYKeyframes),i.push(...o.opacityKeyframes),s.push(...o.scaleKeyframes),n.push(...o.rotationKeyframes),t.length&&(this.offsetXKeyframeBuilder=new E(t,this.getLength())),e.length&&(this.offsetYKeyframeBuilder=new E(e,this.getLength())),i.length&&(this.opacityKeyframeBuilder=new E(i,this.getLength(),1)),s.length&&(this.scaleKeyframeBuilder=new E(s,this.getLength(),1)),n.length&&(this.rotationKeyframeBuilder=new E(n,this.getLength()))}async load(){this.outline=new y.Graphics,this.getContainer().addChild(this.outline),this.topLeftScaleHandle=new y.Graphics,this.topRightScaleHandle=new y.Graphics,this.bottomRightScaleHandle=new y.Graphics,this.bottomLeftScaleHandle=new y.Graphics,this.getContainer().addChild(this.topLeftScaleHandle),this.getContainer().addChild(this.topRightScaleHandle),this.getContainer().addChild(this.bottomRightScaleHandle),this.getContainer().addChild(this.bottomLeftScaleHandle),this.rotationHandle=new y.Graphics,this.getContainer().addChild(this.rotationHandle),this.getContainer().cursor="pointer",this.getContainer().eventMode="static",this.getContainer().on("pointerdown",this.onPointerStart.bind(this)),this.getContainer().on("pointermove",this.onPointerMove.bind(this)),this.getContainer().on("globalpointermove",this.onPointerMove.bind(this)),this.getContainer().on("pointerup",this.onPointerUp.bind(this)),this.getContainer().on("pointerupoutside",this.onPointerUp.bind(this)),this.getContainer().on("pointerover",this.onPointerOver.bind(this)),this.getContainer().on("pointerout",this.onPointerOut.bind(this))}update(t,e){if(this.getContainer().visible=this.isActive(),this.getContainer().zIndex=this.layer,!this.isActive())return;const i=this.getPivot(),s=this.getPosition(),n=this.getScale();this.getContainer().scale.set(n),this.getContainer().pivot.set(i.x,i.y),this.getContainer().position.set(s.x+i.x,s.y+i.y);const r=this.getRotation();this.getContainer().alpha=this.getOpacity(),this.getContainer().angle=r,this.shouldDiscardFrame()&&(this.getContainer().alpha=0)}draw(){if(!this.outline)return;if((!this.isActive()||this.edit.getSelectedClip()!==this)&&!this.isHovering){this.outline.clear(),this.topLeftScaleHandle?.clear(),this.topRightScaleHandle?.clear(),this.bottomRightScaleHandle?.clear(),this.bottomLeftScaleHandle?.clear(),this.rotationHandle?.clear();return}const t=this.isHovering||this.isDragging?65535:16777215,e=this.getSize(),i=this.getScale();if(this.outline.clear(),this.outline.strokeStyle={width:P.OutlineWidth/i,color:t},this.outline.rect(0,0,e.width,e.height),this.outline.stroke(),!this.topLeftScaleHandle||!this.topRightScaleHandle||!this.bottomRightScaleHandle||!this.bottomLeftScaleHandle||!this.isActive()||this.edit.getSelectedClip()!==this)return;this.topLeftScaleHandle.fillStyle={color:t},this.topLeftScaleHandle.clear();const s=P.ScaleHandleRadius*2/i;if(this.topLeftScaleHandle.rect(-s/2,-s/2,s,s),this.topLeftScaleHandle.fill(),this.topRightScaleHandle.fillStyle={color:t},this.topRightScaleHandle.clear(),this.topRightScaleHandle.rect(e.width-s/2,-s/2,s,s),this.topRightScaleHandle.fill(),this.bottomRightScaleHandle.fillStyle={color:t},this.bottomRightScaleHandle.clear(),this.bottomRightScaleHandle.rect(e.width-s/2,e.height-s/2,s,s),this.bottomRightScaleHandle.fill(),this.bottomLeftScaleHandle.fillStyle={color:t},this.bottomLeftScaleHandle.clear(),this.bottomLeftScaleHandle.rect(-s/2,e.height-s/2,s,s),this.bottomLeftScaleHandle.fill(),!this.rotationHandle)return;const n=e.width/2,r=-50/i;this.rotationHandle.clear(),this.rotationHandle.fillStyle={color:t},this.rotationHandle.circle(n,r,P.RotationHandleRadius/i),this.rotationHandle.fill(),this.outline.strokeStyle={width:P.OutlineWidth/i,color:t},this.outline.moveTo(n,0),this.outline.lineTo(n,r),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}getStart(){return this.clipConfiguration.start*1e3}getLength(){return this.clipConfiguration.length*1e3}getEnd(){return this.getStart()+this.getLength()}getPlaybackTime(){const t=this.edit.playbackTime-this.getStart();return t<0?0:t>this.getLength()?this.getLength():t}getOpacity(){return this.opacityKeyframeBuilder?.getValue(this.getPlaybackTime())??1}getPosition(){const t={x:this.offsetXKeyframeBuilder?.getValue(this.getPlaybackTime())??0,y:this.offsetYKeyframeBuilder?.getValue(this.getPlaybackTime())??0};return this.positionBuilder.relativeToAbsolute(this.getSize(),this.clipConfiguration.position??"center",t)}getPivot(){const t=this.getSize();return{x:t.width/2,y:t.height/2}}getFitScale(){switch(this.clipConfiguration.fit??"crop"){case"crop":return Math.max(this.edit.size.width/this.getSize().width,this.edit.size.height/this.getSize().height);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()}getRotation(){return this.rotationKeyframeBuilder?.getValue(this.getPlaybackTime())??0}isActive(){return this.edit.playbackTime>=this.getStart()&&this.edit.playbackTime<this.getEnd()}shouldDiscardFrame(){return this.getPlaybackTime()<P.DiscardedFrameCount}onPointerStart(t){if(t.button!==ss.ButtonLeftClick||(this.edit.setSelectedClip(this),this.initialClipConfiguration=structuredClone(this.clipConfiguration),this.clipHasKeyframes()))return;if(this.scaleDirection=null,this.topLeftScaleHandle?.getBounds().containsPoint(t.globalX,t.globalY)&&(this.scaleDirection="topLeft"),this.topRightScaleHandle?.getBounds().containsPoint(t.globalX,t.globalY)&&(this.scaleDirection="topRight"),this.bottomRightScaleHandle?.getBounds().containsPoint(t.globalX,t.globalY)&&(this.scaleDirection="bottomRight"),this.bottomLeftScaleHandle?.getBounds().containsPoint(t.globalX,t.globalY)&&(this.scaleDirection="bottomLeft"),this.scaleDirection!==null){this.scaleStart=this.getScale()/this.getFitScale();const h=t.getLocalPosition(this.edit.getContainer());this.scaleOffset=h;return}if(this.rotationHandle?.getBounds().containsPoint(t.globalX,t.globalY)){this.isRotating=!0,this.rotationStart=this.getRotation();const h=t.getLocalPosition(this.edit.getContainer());this.rotationOffset=h;return}this.isDragging=!0;const o=t.getLocalPosition(this.edit.getContainer());this.dragOffset={x:o.x-this.getContainer().position.x,y:o.y-this.getContainer().position.y}}onPointerMove(t){if(this.scaleDirection!==null&&this.scaleStart!==null){const e=t.getLocalPosition(this.edit.getContainer()),i=this.getPosition(),s=this.getPivot(),n={x:i.x+s.x,y:i.y+s.y},r=Math.sqrt((this.scaleOffset.x-n.x)**2+(this.scaleOffset.y-n.y)**2),h=Math.sqrt((e.x-n.x)**2+(e.y-n.y)**2)/r,l=this.scaleStart*h;this.clipConfiguration.scale=Math.max(P.MinScale,Math.min(l,P.MaxScale)),this.scaleKeyframeBuilder=new E(this.clipConfiguration.scale,this.getLength(),1);return}if(this.isRotating&&this.rotationStart!==null){const e=t.getLocalPosition(this.edit.getContainer()),i=this.getPosition(),s=this.getPivot(),n={x:i.x+s.x,y:i.y+s.y},r=Math.atan2(this.rotationOffset.y-n.y,this.rotationOffset.x-n.x),h=(Math.atan2(e.y-n.y,e.x-n.x)-r)*(180/Math.PI);let l=this.rotationStart+h;const c=45,m=l%c,p=2;Math.abs(m)<p?l=Math.floor(l/c)*c:Math.abs(m-c)<p&&(l=Math.ceil(l/c)*c),this.clipConfiguration.transform||(this.clipConfiguration.transform={rotate:{angle:0}}),this.clipConfiguration.transform.rotate||(this.clipConfiguration.transform.rotate={angle:0}),this.clipConfiguration.transform.rotate.angle=l,this.rotationKeyframeBuilder=new E(this.clipConfiguration.transform.rotate.angle,this.getLength());return}if(this.isDragging){const e=t.getLocalPosition(this.edit.getContainer()),i=this.getPivot(),s={x:e.x-this.dragOffset.x,y:e.y-this.dragOffset.y},n={x:s.x-i.x,y:s.y-i.y},r=[{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},h=[...r,o],l=[{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}],c={x:n.x+this.getSize().width/2,y:n.y+this.getSize().height/2},m=[...l,c];let p=P.SnapThreshold,k=P.SnapThreshold,O=null,_=null;for(const H of m)for(const vt of h){const G=Math.abs(H.x-vt.x);G<p&&(p=G,O=n.x+(vt.x-H.x));const xt=Math.abs(H.y-vt.y);xt<k&&(k=xt,_=n.y+(vt.y-H.y))}O!==null&&(n.x=O),_!==null&&(n.y=_);const D=this.positionBuilder.absoluteToRelative(this.getSize(),this.clipConfiguration.position??"center",n);this.clipConfiguration.offset||(this.clipConfiguration.offset={x:0,y:0}),this.clipConfiguration.offset.x=D.x,this.clipConfiguration.offset.y=D.y,this.offsetXKeyframeBuilder=new E(this.clipConfiguration.offset.x,this.getLength()),this.offsetYKeyframeBuilder=new E(this.clipConfiguration.offset.y,this.getLength())}}onPointerUp(){(this.isDragging||this.scaleDirection!==null||this.isRotating)&&this.hasStateChanged()&&this.edit.setUpdatedClip(this,this.initialClipConfiguration),this.isDragging=!1,this.dragOffset={x:0,y:0},this.scaleDirection=null,this.scaleStart=null,this.scaleOffset={x:0,y:0},this.isRotating=!1,this.rotationStart=null,this.rotationOffset={x:0,y:0},this.initialClipConfiguration=null}onPointerOver(){this.isHovering=!0}onPointerOut(){this.isHovering=!1}clipHasPresets(){return!!this.clipConfiguration.effect||!!this.clipConfiguration.transition?.in||!!this.clipConfiguration.transition?.out}clipHasKeyframes(){return[this.clipConfiguration.scale,this.clipConfiguration.offset?.x,this.clipConfiguration.offset?.y,this.clipConfiguration.transform?.rotate?.angle].some(t=>t&&typeof t!="number")}hasStateChanged(){if(!this.initialClipConfiguration)return!1;const t=this.clipConfiguration.offset?.x,e=this.clipConfiguration.offset?.y,i=this.clipConfiguration.scale,s=Number(this.clipConfiguration.transform?.rotate?.angle??0),n=this.initialClipConfiguration.offset?.x,r=this.initialClipConfiguration.offset?.y,o=this.initialClipConfiguration.scale,h=Number(this.initialClipConfiguration.transform?.rotate?.angle??0);return n!==void 0&&t!==n||r!==void 0&&e!==r||o!==void 0&&i!==o||s!==h}}class ce extends P{audioResource;isPlaying;volumeKeyframeBuilder;syncTimer;constructor(t,e){super(t,e),this.audioResource=null,this.isPlaying=!1;const i=e.asset;this.volumeKeyframeBuilder=new E(i.volume??1,this.getLength()),this.syncTimer=0}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.src,i={src:e,loadParser:$t.Name},s=await this.edit.assetLoader.load(e,i);if(!(s instanceof We.Howl))throw new Error(`Invalid audio source '${t.src}'.`);this.audioResource=s,this.configureKeyframes()}update(t,e){super.update(t,e);const{trim:i=0}=this.clipConfiguration.asset;if(this.syncTimer+=e,this.getContainer().alpha=0,!this.audioResource)return;const s=this.edit.isPlaying&&this.isActive(),n=this.getPlaybackTime();s&&(this.isPlaying||(this.isPlaying=!0,this.audioResource.seek(n/1e3+i),this.audioResource.play()),this.audioResource.volume()!==this.getVolume()&&this.audioResource.volume(this.getVolume()),Math.abs((this.audioResource.seek()-i)*1e3-n)>100&&this.audioResource.seek(n/1e3+i)),this.isPlaying&&!s&&(this.isPlaying=!1,this.audioResource.pause());const r=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&r&&(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 as=`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
|
-
`,
|
|
28
|
+
`,rs=`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
|
-
}`,
|
|
77
|
+
}`,os=`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
|
-
`,
|
|
118
|
+
`,ls=`struct OutlineUniforms {
|
|
119
119
|
uThickness:vec2<f32>,
|
|
120
120
|
uColor:vec3<f32>,
|
|
121
121
|
uAlpha:f32,
|
|
@@ -179,5 +179,7 @@ fn outlineMaxAlphaAtPos(uv: vec2<f32>) -> f32 {
|
|
|
179
179
|
return maxAlpha;
|
|
180
180
|
}
|
|
181
181
|
|
|
182
|
-
const DOUBLE_PI: f32 = 3.14159265358979323846264 * 2.;`,rs=Object.defineProperty,os=(a,e,t)=>e in a?rs(a,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):a[e]=t,ae=(a,e,t)=>(os(a,typeof e!="symbol"?e+"":e,t),t);const je=class le extends V.Filter{constructor(...e){let t=e[0]??{};typeof t=="number"&&(V.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={...le.DEFAULT_OPTIONS,...t};const i=t.quality??.1,s=V.GpuProgram.from({vertex:{source:ss,entryPoint:"mainVertex"},fragment:{source:as,entryPoint:"mainFragment"}}),n=V.GlProgram.from({vertex:is,fragment:ns.replace(/\$\{ANGLE_STEP\}/,le.getAngleStep(i).toFixed(7)),name:"outline-filter"});super({gpuProgram:s,glProgram:n,resources:{outlineUniforms:{uThickness:{value:new Float32Array(2),type:"vec2<f32>"},uColor:{value:new Float32Array(3),type:"vec3<f32>"},uAlpha:{value:t.alpha,type:"f32"},uAngleStep:{value:0,type:"f32"},uKnockout:{value:t.knockout?1:0,type:"f32"}}}}),ae(this,"uniforms"),ae(this,"_thickness"),ae(this,"_quality"),ae(this,"_color"),this.uniforms=this.resources.outlineUniforms.uniforms,this.uniforms.uAngleStep=le.getAngleStep(i),this._color=new V.Color,this.color=t.color??0,Object.assign(this,t)}apply(e,t,i,s){this.uniforms.uThickness[0]=this.thickness/t.source.width,this.uniforms.uThickness[1]=this.thickness/t.source.height,e.applyFilter(this,t,i,s)}static getAngleStep(e){return parseFloat((Math.PI*2/Math.max(e*le.MAX_SAMPLES,le.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,s]=this._color.toArray();this.uniforms.uColor[0]=t,this.uniforms.uColor[1]=i,this.uniforms.uColor[2]=s}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=le.getAngleStep(e)}get knockout(){return this.uniforms.uKnockout===1}set knockout(e){this.uniforms.uKnockout=e?1:0}};ae(je,"DEFAULT_OPTIONS",{thickness:1,color:0,alpha:1,quality:.1,knockout:!1}),ae(je,"MIN_SAMPLES",1),ae(je,"MAX_SAMPLES",100);let ot=je;class cs extends I{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 v.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 s=new v.Text;s.text=t.text;const{horizontal:n,vertical:r}=t.alignment;s.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 o=(e.width??this.edit.size.width)/2-s.width/2,l=(e.height??this.edit.size.height)/2-s.height/2;if(n==="left"&&(o=0),n==="right"&&(o=(e.width??this.edit.size.width)-s.width),r==="top"&&(l=0),r==="bottom"&&(l=(e.height??this.edit.size.height)-s.height),s.position={x:o,y:l},t.stroke.color&&t.stroke.width){const c=new ot({thickness:t.stroke.width,color:t.stroke.color});s.filters=[c]}this.background=i,this.text=s,this.getContainer().addChild(i),this.getContainer().addChild(s),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:s}=e;if(!t.includes('data-html-type="text"'))return console.warn("Unsupported html format."),null;const r=new DOMParser().parseFromString(t,"text/html").body.textContent??"",l=(await new CSSStyleSheet().replace(i)).cssRules[0],c={text:r,font:{},alignment:{},background:{},stroke:{}};if(l?.constructor.name!=="CSSStyleRule"||!("style"in l))return console.warn("Unsupported css format."),c;const h=l.style,g=this.parseAlignment(s??"center");c.font={color:h.color.length?h.color:void 0,family:h.fontFamily.length?h.fontFamily:void 0,size:h.fontSize.length?parseInt(h.fontSize,10):void 0,weight:h.fontWeight.length?parseInt(h.fontWeight,10):void 0,lineHeight:h.lineHeight.length?parseInt(h.lineHeight,10):void 0},c.alignment=g;let p="";return h.background.length&&(p=h.background),h.backgroundColor.length&&(p=h.backgroundColor),c.background={color:p.length?p: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 ls extends I{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:{}},s=await this.edit.assetLoader.load(t,i);if(!(s?.source instanceof v.ImageSource))throw new Error(`Invalid image source '${e.src}'.`);this.texture=this.createCroppedTexture(s),this.sprite=new v.Sprite(this.texture),this.getContainer().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,s=e.height,n=Math.floor((t.crop?.left??0)*i),r=Math.floor((t.crop?.right??0)*i),o=Math.floor((t.crop?.top??0)*s),l=Math.floor((t.crop?.bottom??0)*s),c=n,h=o,g=i-n-r,p=s-o-l,k=new v.Rectangle(c,h,g,p);return new v.Texture({source:e.source,frame:k})}}class Ft extends I{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}},s=await this.edit.assetLoader.load(t,i);if(!(s?.source instanceof v.ImageSource||s?.source instanceof v.VideoSource))throw new Error(`Invalid luma source '${e.src}'.`);this.texture=s,this.sprite=new v.Sprite(this.texture),this.getContainer().addChild(this.sprite),this.configureKeyframes()}update(e,t){if(super.update(e,t),!this.texture||!(this.texture.source instanceof v.VideoSource))return;const i=this.getPlaybackTime(),s=this.edit.isPlaying&&this.isActive();s&&(this.isPlaying||(this.isPlaying=!0,this.texture.source.resource.currentTime=i/1e3,this.texture.source.resource.play().catch(console.error)),this.texture.source.resource.volume!==this.getVolume()&&(this.texture.source.resource.volume=this.getVolume()),Math.abs(this.texture.source.resource.currentTime*1e3-i)>100&&(this.texture.source.resource.currentTime=i/1e3)),!s&&this.isPlaying&&(this.isPlaying=!1,this.texture.source.resource.pause()),!this.edit.isPlaying&&this.isActive()&&(this.texture.source.resource.currentTime=i/1e3)}draw(){super.draw()}dispose(){super.dispose(),this.sprite?.destroy(),this.sprite=null,this.texture?.destroy(),this.texture=null}getSize(){return{width:this.sprite?.width??0,height:this.sprite?.height??0}}getVolume(){return 0}getMask(){return this.sprite}}class hs extends I{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 v.Graphics,i=e.width??this.edit.size.width,s=e.height??this.edit.size.height;t.fillStyle={color:"transparent"},t.rect(0,0,i,s),t.fill();const n=new v.Graphics;switch(e.shape){case"rectangle":{const r=e.rectangle,o=i/2-r.width/2,l=s/2-r.height/2;n.rect(o,l,r.width,r.height);break}case"circle":{const r=e.circle,o=i/2,l=s/2;n.circle(o,l,r.radius);break}case"line":{const r=e.line,o=i/2-r.length/2,l=s/2-r.thickness/2;n.rect(o,l,r.length,r.thickness);break}default:console.warn("Unsupported shape asset type.");break}if(n.fillStyle={color:e.fill?.color??"#ffffff",alpha:e.fill?.opacity??1},n.fill(),e.stroke){const r=new ot({thickness:e.stroke.width,color:e.stroke.color});n.filters=[r]}this.shapeBackground=t,this.shape=n,this.getContainer().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 us extends I{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=new v.Graphics;e.background&&(t.fillStyle={color:e.background.color,alpha:e.background.opacity},t.rect(0,0,e.width??this.edit.size.width,e.height??this.edit.size.height),t.fill());const i=new v.Text;i.text=e.text;const s=e.alignment?.horizontal??"center",n=e.alignment?.vertical??"center";i.style={fontFamily:e.font?.family??"Open Sans",fontSize:e.font?.size??32,fill:e.font?.color??"#ffffff",fontWeight:(e.font?.weight??"400").toString(),wordWrap:!0,wordWrapWidth:e.width??this.edit.size.width,lineHeight:(e.font?.lineHeight??1)*(e.font?.size??32),align:s};let r=(e.width??this.edit.size.width)/2-i.width/2,o=(e.height??this.edit.size.height)/2-i.height/2;if(s==="left"&&(r=0),s==="right"&&(r=(e.width??this.edit.size.width)-i.width),n==="top"&&(o=0),n==="bottom"&&(o=(e.height??this.edit.size.height)-i.height),i.position={x:r,y:o},e.stroke){const l=new ot({thickness:e.stroke.width,color:e.stroke.color});i.filters=[l]}this.background=t,this.text=i,this.getContainer().addChild(t),this.getContainer().addChild(i),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}}class ds extends I{texture;sprite;isPlaying;volumeKeyframeBuilder;syncTimer;constructor(e,t){super(e,t),this.texture=null,this.sprite=null,this.isPlaying=!1;const i=this.clipConfiguration.asset;this.volumeKeyframeBuilder=new R(i.volume??1,this.getLength()),this.syncTimer=0}async load(){await super.load();const 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}},s=await this.edit.assetLoader.load(t,i);if(!(s?.source instanceof v.VideoSource))throw new Error(`Invalid video source '${e.src}'.`);this.texture=this.createCroppedTexture(s),this.sprite=new v.Sprite(this.texture),this.getContainer().addChild(this.sprite),this.configureKeyframes()}update(e,t){super.update(e,t);const{trim:i=0}=this.clipConfiguration.asset;if(this.syncTimer+=t,!this.texture)return;const s=this.getPlaybackTime(),n=this.edit.isPlaying&&this.isActive();n&&(this.isPlaying||(this.isPlaying=!0,this.texture.source.resource.currentTime=s/1e3+i,this.texture.source.resource.play().catch(console.error)),this.texture.source.resource.volume!==this.getVolume()&&(this.texture.source.resource.volume=this.getVolume()),Math.abs((this.texture.source.resource.currentTime-i)*1e3-s)>100&&(this.texture.source.resource.currentTime=s/1e3+i)),!n&&this.isPlaying&&(this.isPlaying=!1,this.texture.source.resource.pause());const r=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&r&&(this.syncTimer=0,this.texture.source.resource.currentTime=s/1e3+i)}draw(){super.draw()}dispose(){super.dispose(),this.sprite?.destroy(),this.sprite=null,this.texture?.destroy(),this.texture=null}getSize(){return{width:this.sprite?.width??0,height:this.sprite?.height??0}}getVolume(){return this.volumeKeyframeBuilder.getValue(this.getPlaybackTime())}createCroppedTexture(e){const t=this.clipConfiguration.asset;if(!t.crop)return e;const i=e.width,s=e.height,n=Math.floor((t.crop?.left??0)*i),r=Math.floor((t.crop?.right??0)*i),o=Math.floor((t.crop?.top??0)*s),l=Math.floor((t.crop?.bottom??0)*s),c=n,h=o,g=i-n-r,p=s-o-l,k=new v.Rectangle(c,h,g,p);return new v.Texture({source:e.source,frame:k})}}class re extends at{static ZIndexPadding=100;assetLoader;events;edit;tracks;clipsToDispose;clips;playbackTime;size;backgroundColor;totalDuration;isPlaying;selectedClip;updatedClip;constructor(e,t="#ffffff"){super(),this.assetLoader=new Oe,this.edit=null,this.tracks=[],this.clipsToDispose=[],this.clips=[],this.events=new ft,this.size=e,this.playbackTime=0,this.totalDuration=0,this.isPlaying=!1,this.selectedClip=null,this.updatedClip=null,this.backgroundColor=t}async load(){const e=new v.Graphics;e.fillStyle={color:this.backgroundColor},e.rect(0,0,this.size.width,this.size.height),e.fill(),this.getContainer().addChild(e)}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(){this.clearClips()}play(){this.isPlaying=!0}pause(){this.isPlaying=!1}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=qi.parse(e),this.backgroundColor=this.edit.timeline.background||"#000000",await Promise.all((this.edit.timeline.fonts??[]).map(async t=>{const i=t.src,s={src:i,loadParser:Ae.Name};return this.assetLoader.load(i,s)}));for(const[t,i]of this.edit.timeline.tracks.entries())for(const s of i.clips){const n=this.createPlayerFromAssetType(s);n.layer=t+1,await this.addPlayer(t,n)}this.updateTotalDuration()}getEdit(){const e=[],t=new Map;for(const s of this.clips)t.has(s.layer)||t.set(s.layer,{clips:[]}),t.get(s.layer).clips.push(s.clipConfiguration);const i=Math.max(...t.keys(),0);for(let s=1;s<=i;s+=1)e[s-1]=t.get(s)||{clips:[]};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=Mt.parse(t),s=this.createPlayerFromAssetType(i);s.layer=e+1,this.addPlayer(e,s),this.updateTotalDuration()}getClip(e,t){const i=this.clips.filter(s=>s.layer===e+1);return t<0||t>=i.length?null:i[t].clipConfiguration}deleteClip(e,t){const i=this.clips.find(s=>s.layer===e+1&&this.clips.filter(n=>n.layer===e+1).indexOf(s)===t);i&&(this.queueDisposeClip(i),this.updateTotalDuration())}addTrack(e,t){this.tracks.splice(e,0,[]);const i=this.clips.map((s,n)=>({clip:s,index:n})).filter(({clip:s})=>s.layer>=e+1);i.forEach(({clip:s})=>{const r=`shotstack-track-${1e5-s.layer*re.ZIndexPadding}`;this.getContainer().getChildByLabel(r,!1)?.removeChild(s.getContainer())});for(const{index:s}of i)this.clips[s].layer+=1;i.forEach(({clip:s})=>{const n=1e5-s.layer*re.ZIndexPadding,r=`shotstack-track-${n}`;let o=this.getContainer().getChildByLabel(r,!1);o||(o=new v.Container({label:r,zIndex:n}),this.getContainer().addChild(o)),o.addChild(s.getContainer())}),t?.clips?.forEach(s=>this.addClip(e,s)),this.updateTotalDuration()}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=this.clips.filter(s=>s.layer===e+1);for(const s of t)s.shouldDispose=!0;this.disposeClips(),this.tracks.splice(e,1);const i=this.clips.map((s,n)=>({clip:s,index:n})).filter(({clip:s})=>s.layer>e+1);i.forEach(({clip:s})=>{const r=`shotstack-track-${1e5-s.layer*re.ZIndexPadding}`;this.getContainer().getChildByLabel(r,!1)?.removeChild(s.getContainer())});for(const{index:s}of i)this.clips[s].layer-=1;i.forEach(({clip:s})=>{const n=1e5-s.layer*re.ZIndexPadding,r=`shotstack-track-${n}`;let o=this.getContainer().getChildByLabel(r,!1);o||(o=new v.Container({label:r,zIndex:n}),this.getContainer().addChild(o)),o.addChild(s.getContainer())}),this.updateTotalDuration()}getTotalDuration(){return this.totalDuration}getSelectedClip(){return this.selectedClip}setSelectedClip(e){this.selectedClip=e;const t=e.layer-1,s=this.clips.filter(r=>r.layer===e.layer).indexOf(e),n={clip:e.clipConfiguration,trackIndex:t,clipIndex:s};this.events.emit("clip:selected",n)}setUpdatedClip(e,t=null){this.updatedClip=e;const i=e.layer-1,n=this.clips.filter(o=>o.layer===e.layer).indexOf(e),r={previous:{clip:t,trackIndex:i,clipIndex:n},current:{clip:e.clipConfiguration,trackIndex:i,clipIndex:n}};this.events.emit("clip:updated",r)}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 v.Container&&t.label?.toString().startsWith("shotstack-track-")&&t.children.includes(e.getContainer())){t.removeChild(e.getContainer());break}}catch{console.warn("Attempting to unmount an unmounted clip.")}this.unloadClipAssets(e),e.dispose()}unloadClipAssets(e){const{asset:t}=e.clipConfiguration;if(t&&"src"in t&&typeof t.src=="string")try{v.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 t of this.tracks)for(const i of t)e=Math.max(e,i.getEnd());this.totalDuration=e}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 us(this,e);break}case"shape":{t=new hs(this,e);break}case"html":{t=new cs(this,e);break}case"image":{t=new ls(this,e);break}case"video":{t=new ds(this,e);break}case"audio":{t=new rt(this,e);break}case"luma":{t=new Ft(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)*re.ZIndexPadding,s=`shotstack-track-${i}`;let n=this.getContainer().getChildByLabel(s,!1);n||(n=new v.Container({label:s,zIndex:i}),this.getContainer().addChild(n)),n.addChild(t.getContainer());const r=t instanceof Ft;await t.load(),r&&n.setMask({mask:t.getMask(),inverse:!0}),this.updateTotalDuration()}}class Te extends at{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 v.Graphics;e.fillStyle={color:"#424242",alpha:.5},e.rect(0,0,Te.Width,Te.Height),e.fill(),this.getContainer().addChild(e),this.background=e;const t=new v.Text;t.text="",t.style={fontFamily:"monospace",fontSize:14,fill:"#ffffff",wordWrap:!0,wordWrapWidth:Te.Width},this.getContainer().addChild(t),this.text=t}update(e,t){if(!this.text)return;const i=this.getMemoryInfo(),s=[`FPS: ${this.fps}`,`Playback: ${(this.playbackTime/1e3).toFixed(2)}/${(this.playbackDuration/1e3).toFixed(2)}`,`Playing: ${this.isPlaying}`,`Total Heap Size: ${i.totalHeapSize?`${this.bytesToMegabytes(i.totalHeapSize)}MB`:"N/A"}`,`Used Heap Size: ${i.usedHeapSize?`${this.bytesToMegabytes(i.usedHeapSize)}MB`:"N/A"}`,`Heap Size Limit: ${i.heapSizeLimit?`${this.bytesToMegabytes(i.heapSizeLimit)}MB`:"N/A"}`];this.text.text=s.join(`
|
|
183
|
-
`)}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 oe{static CanvasSelector="[data-shotstack-studio]";static extensionsRegistered=!1;size;application;edit;inspector;container;background;minZoom=.1;maxZoom=4;currentZoom=.8;constructor(e,t){this.size=e,this.application=new v.Application,this.edit=t,this.inspector=new Te}async load(){const e=document.querySelector(oe.CanvasSelector);if(!e)throw new Error(`Shotstack canvas root element '${oe.CanvasSelector}' not found.`);this.registerExtensions(),this.container=new v.Container,this.background=new v.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 s=Math.exp(-i.deltaY/100),n=this.currentZoom*s,r=this.currentZoom;this.currentZoom=Math.min(Math.max(n,this.minZoom),this.maxZoom);const o={x:this.application.canvas.width/2,y:this.application.canvas.height/2},l={x:t.position.x-o.x,y:t.position.y-o.y},c=this.currentZoom/r;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 s=this.edit.getContainer();s.scale.x=this.currentZoom,s.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}registerExtensions(){oe.extensionsRegistered||(v.extensions.add(new Be),v.extensions.add(new Ae),oe.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.onTick.bind(this)),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()}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 v.Rectangle(0,0,this.size.width,this.size.height),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()}dispose(){const e=document.querySelector(oe.CanvasSelector);e&&e.contains(this.application.canvas)&&e.removeChild(this.application.canvas),this.application.ticker.remove(this.onTick,this),this.application.stage.off("click",this.onClick,this),this.background?.destroy(),this.container?.destroy(),this.inspector.dispose(),this.application.destroy(!0,{children:!0,texture:!0})}}class fs{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}}};handleKeyUp=e=>{if(!(e.target instanceof HTMLInputElement||e.target instanceof HTMLTextAreaElement))switch(e.code){case"KeyI":console.log(this.edit.getEdit());break}}}class ps{ffmpeg;isReady=!1;edit;application;constructor(e,t){this.edit=e,this.application=t.application,this.ffmpeg=new Bt.FFmpeg}async init(){if(!this.isReady)try{await this.ffmpeg.load(),this.isReady=!0}catch(e){throw console.error("FFmpeg initialization failed:",e),e}}async export(e="shotstack-export.mp4",t=30){this.isReady||await this.init();const i=this.edit.isPlaying,s=this.edit.playbackTime;this.edit.pause();const n=this.edit.getContainer(),r=n.visible,{x:o,y:l}=n.position,{x:c,y:h}=n.scale;n.visible=!1;const g=this.createProgressOverlay();try{const p=this.edit.getSize?this.edit.getSize():{width:1920,height:1080},k=Math.ceil(this.edit.totalDuration*t/1e3),A=1e3/t,S=100,N=50,ce=50,ye=O=>Math.round(O/k*N);this.updateProgressOverlay(g,0,S);const X=document.createElement("canvas");X.width=p.width,X.height=p.height;const ve=X.getContext("2d");if(!ve)throw new Error("Could not get 2D context for canvas");const ct=this.findAudioPlayers();this.updateProgressOverlay(g,2,S);const Y=[];if(ct.length>0){this.updateProgressOverlay(g,3,S);for(let O=0;O<ct.length;O+=1){const Z=await this.processAudioTrack(ct[O],O);Z&&Y.push(Z),this.updateProgressOverlay(g,4+O,S)}}n.position.x=0,n.position.y=0,n.scale.x=1,n.scale.y=1;for(let O=0;O<k;O+=1){this.edit.seek(O*A),this.edit.tick?this.edit.tick(0,0):(this.edit.update?.(0,0),this.edit.draw?.());try{const{extract:Z}=this.application.renderer,M=Z.canvas(n);ve.clearRect(0,0,X.width,X.height),ve.drawImage(M,0,0);const q=X.toDataURL("image/png"),$e=await(await fetch(q)).arrayBuffer(),ys=`frame_${O.toString().padStart(6,"0")}.png`;await this.ffmpeg.writeFile(ys,new Uint8Array($e))}catch(Z){console.error(`Error capturing frame ${O}:`,Z)}this.updateProgressOverlay(g,ye(O+1),S)}this.updateProgressOverlay(g,N,S);let ee=["-framerate",t.toString(),"-i","frame_%06d.png"];for(const O of Y)ee=ee.concat(["-i",O.filename]);if(ee=ee.concat(["-c:v","libx264","-pix_fmt","yuv420p","-crf","23"]),Y.length>0){let O="";for(let M=0;M<Y.length;M+=1){const q=Y[M],Vt=M+1,$e=Math.max(0,q.start);O+=`[${Vt}:a]aformat=sample_fmts=fltp:sample_rates=44100:channel_layouts=stereo,apad,afade=t=in:st=0:d=0.05,atrim=start=0:end=${q.duration/1e3+.1},adelay=${$e}|${$e},volume=${q.volume}[a${M}];`}const Z=Y.length>1?`${Y.map((M,q)=>`[a${q}]`).join("")}amix=inputs=${Y.length}:duration=longest:dropout_transition=0.5:normalize=0[aout]`:"[a0]aformat=sample_fmts=fltp:sample_rates=44100:channel_layouts=stereo[aout]";O+=Z,ee=ee.concat(["-filter_complex",O,"-map","0:v","-map","[aout]","-c:a","aac","-b:a","192k","-shortest"])}const lt="output.mp4";ee.push(lt);let Dt=0;const Nt=({message:O})=>{const Z=O.includes("frame=")&&O.includes("fps=")?O.match(/frame=\s*(\d+)/):null;if(Z?.[1]){const M=parseInt(Z[1],10);if(!Number.isNaN(M)&&M>Dt&&(Dt=M,M<=k)){const q=Math.round(M/k*ce);this.updateProgressOverlay(g,N+q,S)}}};this.ffmpeg.on("log",Nt),await this.ffmpeg.exec(ee),this.ffmpeg.off("log",Nt),this.updateProgressOverlay(g,N+ce,S);const ht=await this.ffmpeg.readFile(lt),ms=ht instanceof Uint8Array?ht:new TextEncoder().encode(ht.toString()),gs=new Blob([ms],{type:"video/mp4"}),Zt=URL.createObjectURL(gs),ut=document.createElement("a");ut.href=Zt,ut.download=e,ut.click(),URL.revokeObjectURL(Zt);for(let O=0;O<k;O+=1)try{await this.ffmpeg.deleteFile(`frame_${O.toString().padStart(6,"0")}.png`)}catch{}for(const O of Y)try{await this.ffmpeg.deleteFile(O.filename)}catch{}await this.ffmpeg.deleteFile(lt),this.updateProgressOverlay(g,S,S)}catch(p){throw console.error("Error during export:",p),p}finally{this.removeProgressOverlay(g),n.position.x=o,n.position.y=l,n.scale.x=c,n.scale.y=h,n.visible=r,this.edit.seek(s),i&&this.edit.play()}}findAudioPlayers(){const e=[],t=this.edit.tracks;if(t&&Array.isArray(t))for(let i=0;i<t.length;i+=1){const s=t[i];if(Array.isArray(s))for(let n=0;n<s.length;n+=1){const r=s[n];(r instanceof rt||r.constructor.name==="AudioPlayer"||r.clipConfiguration?.asset?.type==="audio")&&(e.includes(r)||e.push(r))}}return this.searchContainerForPlayers(this.edit.getContainer(),e),e}searchContainerForPlayers(e,t){if(e){for(const i of e.children)if(i instanceof v.Container){if(i.label?.startsWith("shotstack-track-")){for(const n of i.children)if(n instanceof v.Container){const r=n,o=["player","clip","audioPlayer","entity"];for(const l of o){const c=r[l];c instanceof rt&&!t.includes(c)&&t.push(c)}}}this.searchContainerForPlayers(i,t)}}}async processAudioTrack(e,t){try{const{clipConfiguration:i}=e;if(!i?.asset)return null;const s=i.asset;if(!s.src)return console.warn("Audio asset does not have a valid src property"),null;const n=await fetch(s.src);if(!n.ok)return console.error(`Failed to fetch audio file: ${s.src}`),null;const r=await n.arrayBuffer(),o=`audio_${t}.mp3`;return await this.ffmpeg.writeFile(o,new Uint8Array(r)),{filename:o,start:e.getStart(),duration:e.getLength(),volume:e.getVolume()}}catch(i){return console.error(`Error processing audio track ${t}:`,i),null}}createProgressOverlay(){const e=document.createElement("div");e.className="video-export-progress-overlay",Object.assign(e.style,{position:"fixed",top:"0",left:"0",width:"100%",height:"100%",backgroundColor:"rgba(0, 0, 0, 0.5)",zIndex:"9999",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",color:"white",fontFamily:"Arial, sans-serif"});const t=document.createElement("div");Object.assign(t.style,{backgroundColor:"#222",borderRadius:"8px",padding:"20px",boxShadow:"0 4px 8px rgba(0, 0, 0, 0.2)",width:"300px",textAlign:"center"}),e.appendChild(t);const i=document.createElement("h3");i.innerText="Exporting Video",i.style.margin="0 0 15px 0",i.style.fontWeight="normal",t.appendChild(i);const s=document.createElement("div");Object.assign(s.style,{width:"100%",height:"6px",backgroundColor:"#444",borderRadius:"3px",overflow:"hidden",marginBottom:"10px"}),t.appendChild(s);const n=document.createElement("div");n.className="video-export-progress-bar",Object.assign(n.style,{width:"0%",height:"100%",backgroundColor:"#3498db",transition:"width 0.3s"}),s.appendChild(n);const r=document.createElement("div");return r.className="video-export-percent",r.innerText="0%",r.style.fontSize="12px",t.appendChild(r),document.body.appendChild(e),e}updateProgressOverlay(e,t,i){if(!e)return;const s=Math.round(t/i*100),n=e.querySelector(".video-export-progress-bar"),r=e.querySelector(".video-export-percent");n&&(n.style.width=`${s}%`),r&&(r.innerText=`${s}%`)}removeProgressOverlay(e){e?.parentNode?.removeChild(e)}}F.Canvas=oe,F.Controls=fs,F.Edit=re,F.VideoExporter=ps,Object.defineProperty(F,Symbol.toStringTag,{value:"Module"})});
|
|
182
|
+
const DOUBLE_PI: f32 = 3.14159265358979323846264 * 2.;`,cs=Object.defineProperty,hs=(a,t,e)=>t in a?cs(a,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):a[t]=e,ot=(a,t,e)=>(hs(a,typeof t!="symbol"?t+"":t,e),e);const Ut=class ht extends V.Filter{constructor(...t){let e=t[0]??{};typeof e=="number"&&(V.deprecation("6.0.0","OutlineFilter constructor params are now options object. See params: { thickness, color, quality, alpha, knockout }"),e={thickness:e},t[1]!==void 0&&(e.color=t[1]),t[2]!==void 0&&(e.quality=t[2]),t[3]!==void 0&&(e.alpha=t[3]),t[4]!==void 0&&(e.knockout=t[4])),e={...ht.DEFAULT_OPTIONS,...e};const i=e.quality??.1,s=V.GpuProgram.from({vertex:{source:rs,entryPoint:"mainVertex"},fragment:{source:ls,entryPoint:"mainFragment"}}),n=V.GlProgram.from({vertex:as,fragment:os.replace(/\$\{ANGLE_STEP\}/,ht.getAngleStep(i).toFixed(7)),name:"outline-filter"});super({gpuProgram:s,glProgram:n,resources:{outlineUniforms:{uThickness:{value:new Float32Array(2),type:"vec2<f32>"},uColor:{value:new Float32Array(3),type:"vec3<f32>"},uAlpha:{value:e.alpha,type:"f32"},uAngleStep:{value:0,type:"f32"},uKnockout:{value:e.knockout?1:0,type:"f32"}}}}),ot(this,"uniforms"),ot(this,"_thickness"),ot(this,"_quality"),ot(this,"_color"),this.uniforms=this.resources.outlineUniforms.uniforms,this.uniforms.uAngleStep=ht.getAngleStep(i),this._color=new V.Color,this.color=e.color??0,Object.assign(this,e)}apply(t,e,i,s){this.uniforms.uThickness[0]=this.thickness/e.source.width,this.uniforms.uThickness[1]=this.thickness/e.source.height,t.applyFilter(this,e,i,s)}static getAngleStep(t){return parseFloat((Math.PI*2/Math.max(t*ht.MAX_SAMPLES,ht.MIN_SAMPLES)).toFixed(7))}get thickness(){return this._thickness}set thickness(t){this._thickness=this.padding=t}get color(){return this._color.value}set color(t){this._color.setValue(t);const[e,i,s]=this._color.toArray();this.uniforms.uColor[0]=e,this.uniforms.uColor[1]=i,this.uniforms.uColor[2]=s}get alpha(){return this.uniforms.uAlpha}set alpha(t){this.uniforms.uAlpha=t}get quality(){return this._quality}set quality(t){this._quality=t,this.uniforms.uAngleStep=ht.getAngleStep(t)}get knockout(){return this.uniforms.uKnockout===1}set knockout(t){this.uniforms.uKnockout=t?1:0}};ot(Ut,"DEFAULT_OPTIONS",{thickness:1,color:0,alpha:1,quality:.1,knockout:!1}),ot(Ut,"MIN_SAMPLES",1),ot(Ut,"MAX_SAMPLES",100);let he=Ut;class us extends P{background;text;constructor(t,e){super(t,e),this.background=null,this.text=null}async load(){await super.load();const t=this.clipConfiguration.asset,e=await this.parseDocument();if(!e)return;const i=new y.Graphics;e.background.color&&(i.fillStyle={color:e.background.color,alpha:e.background.opacity??1},i.rect(0,0,t.width??this.edit.size.width,t.height??this.edit.size.height),i.fill());const s=new y.Text;s.text=e.text;const{horizontal:n,vertical:r}=e.alignment;s.style={fontFamily:e.font?.family??"Open Sans",fontSize:e.font?.size??32,fill:e.font?.color??"#ffffff",fontWeight:(e.font?.weight??"400").toString(),wordWrap:!0,wordWrapWidth:t.width??this.edit.size.width,lineHeight:(e.font?.lineHeight??1)*(e.font?.size??32),align:n};let o=(t.width??this.edit.size.width)/2-s.width/2,h=(t.height??this.edit.size.height)/2-s.height/2;if(n==="left"&&(o=0),n==="right"&&(o=(t.width??this.edit.size.width)-s.width),r==="top"&&(h=0),r==="bottom"&&(h=(t.height??this.edit.size.height)-s.height),s.position={x:o,y:h},e.stroke.color&&e.stroke.width){const l=new he({thickness:e.stroke.width,color:e.stroke.color});s.filters=[l]}this.background=i,this.text=s,this.getContainer().addChild(i),this.getContainer().addChild(s),this.configureKeyframes()}update(t,e){super.update(t,e)}draw(){super.draw()}dispose(){super.dispose(),this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null}getSize(){const t=this.clipConfiguration.asset;return{width:t.width??this.edit.size.width,height:t.height??this.edit.size.height}}getFitScale(){return 1}async parseDocument(){const t=this.clipConfiguration.asset,{html:e,css:i,position:s}=t;if(!e.includes('data-html-type="text"'))return console.warn("Unsupported html format."),null;const r=new DOMParser().parseFromString(e,"text/html").body.textContent??"",h=(await new CSSStyleSheet().replace(i)).cssRules[0],l={text:r,font:{},alignment:{},background:{},stroke:{}};if(h?.constructor.name!=="CSSStyleRule"||!("style"in h))return console.warn("Unsupported css format."),l;const c=h.style,m=this.parseAlignment(s??"center");l.font={color:c.color.length?c.color:void 0,family:c.fontFamily.length?c.fontFamily:void 0,size:c.fontSize.length?parseInt(c.fontSize,10):void 0,weight:c.fontWeight.length?parseInt(c.fontWeight,10):void 0,lineHeight:c.lineHeight.length?parseInt(c.lineHeight,10):void 0},l.alignment=m;let p="";return c.background.length&&(p=c.background),c.backgroundColor.length&&(p=c.backgroundColor),l.background={color:p.length?p:void 0,opacity:c.opacity.length?parseInt(c.opacity,10):void 0},l.stroke={width:c.strokeWidth.length?parseInt(c.strokeWidth,10):void 0,color:c.stroke.length?c.stroke:void 0},l}parseAlignment(t){switch(t){case"topLeft":return{horizontal:"left",vertical:"top"};case"top":return{horizontal:"center",vertical:"top"};case"topRight":return{horizontal:"right",vertical:"top"};case"left":return{horizontal:"left",vertical:"center"};case"right":return{horizontal:"right",vertical:"center"};case"bottomLeft":return{horizontal:"left",vertical:"bottom"};case"bottom":return{horizontal:"center",vertical:"bottom"};case"bottomRight":return{horizontal:"right",vertical:"bottom"};case"center":default:return{horizontal:"center",vertical:"center"}}}}class ds extends P{texture;sprite;constructor(t,e){super(t,e),this.texture=null,this.sprite=null}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.src,i={src:e,crossovern:"anonymous",data:{}},s=await this.edit.assetLoader.load(e,i);if(!(s?.source instanceof y.ImageSource))throw new Error(`Invalid image source '${t.src}'.`);this.texture=this.createCroppedTexture(s),this.sprite=new y.Sprite(this.texture),this.getContainer().addChild(this.sprite),this.configureKeyframes()}update(t,e){super.update(t,e)}draw(){super.draw()}dispose(){super.dispose(),this.sprite?.destroy(),this.sprite=null,this.texture?.destroy(),this.texture=null}getSize(){return{width:this.sprite?.width??0,height:this.sprite?.height??0}}createCroppedTexture(t){const e=this.clipConfiguration.asset;if(!e.crop)return t;const i=t.width,s=t.height,n=Math.floor((e.crop?.left??0)*i),r=Math.floor((e.crop?.right??0)*i),o=Math.floor((e.crop?.top??0)*s),h=Math.floor((e.crop?.bottom??0)*s),l=n,c=o,m=i-n-r,p=s-o-h,k=new y.Rectangle(l,c,m,p);return new y.Texture({source:t.source,frame:k})}}class He extends P{texture;sprite;isPlaying;constructor(t,e){super(t,e),this.texture=null,this.sprite=null,this.isPlaying=!1}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.src,i={src:e,data:{autoPlay:!1,muted:!0}},s=await this.edit.assetLoader.load(e,i);if(!(s?.source instanceof y.ImageSource||s?.source instanceof y.VideoSource))throw new Error(`Invalid luma source '${t.src}'.`);this.texture=s,this.sprite=new y.Sprite(this.texture),this.getContainer().addChild(this.sprite),this.configureKeyframes()}update(t,e){if(super.update(t,e),!this.texture||!(this.texture.source instanceof y.VideoSource))return;const i=this.getPlaybackTime(),s=this.edit.isPlaying&&this.isActive();s&&(this.isPlaying||(this.isPlaying=!0,this.texture.source.resource.currentTime=i/1e3,this.texture.source.resource.play().catch(console.error)),this.texture.source.resource.volume!==this.getVolume()&&(this.texture.source.resource.volume=this.getVolume()),Math.abs(this.texture.source.resource.currentTime*1e3-i)>100&&(this.texture.source.resource.currentTime=i/1e3)),!s&&this.isPlaying&&(this.isPlaying=!1,this.texture.source.resource.pause()),!this.edit.isPlaying&&this.isActive()&&(this.texture.source.resource.currentTime=i/1e3)}draw(){super.draw()}dispose(){super.dispose(),this.sprite?.destroy(),this.sprite=null,this.texture?.destroy(),this.texture=null}getSize(){return{width:this.sprite?.width??0,height:this.sprite?.height??0}}getVolume(){return 0}getMask(){return this.sprite}}class fs extends P{shape;shapeBackground;constructor(t,e){super(t,e),this.shape=null,this.shapeBackground=null}async load(){await super.load();const t=this.clipConfiguration.asset,e=new y.Graphics,i=t.width??this.edit.size.width,s=t.height??this.edit.size.height;e.fillStyle={color:"transparent"},e.rect(0,0,i,s),e.fill();const n=new y.Graphics;switch(t.shape){case"rectangle":{const r=t.rectangle,o=i/2-r.width/2,h=s/2-r.height/2;n.rect(o,h,r.width,r.height);break}case"circle":{const r=t.circle,o=i/2,h=s/2;n.circle(o,h,r.radius);break}case"line":{const r=t.line,o=i/2-r.length/2,h=s/2-r.thickness/2;n.rect(o,h,r.length,r.thickness);break}default:console.warn("Unsupported shape asset type.");break}if(n.fillStyle={color:t.fill?.color??"#ffffff",alpha:t.fill?.opacity??1},n.fill(),t.stroke){const r=new he({thickness:t.stroke.width,color:t.stroke.color});n.filters=[r]}this.shapeBackground=e,this.shape=n,this.getContainer().addChild(e),e.addChild(n),this.configureKeyframes()}update(t,e){super.update(t,e)}draw(){super.draw()}dispose(){super.dispose(),this.shape?.destroy(),this.shape=null,this.shapeBackground?.destroy(),this.shapeBackground=null}getSize(){const t=this.clipConfiguration.asset;return{width:t.width??this.edit.size.width,height:t.height??this.edit.size.height}}getFitScale(){return 1}}class Ot{static DEFAULT_BLINK_INTERVAL_MS=500;static DEFAULT_CURSOR_WIDTH_PX=2;static DEFAULT_CURSOR_COLOR=16777215;cursor=null;parent;textElement;clipConfig;textPosition=0;pixelX=0;pixelY=0;currentLine=0;isBlinking=!1;blinkInterval=null;blinkIntervalMs=500;width=2;color=16777215;isVisible=!0;constructor(t,e,i,s){this.parent=t,this.textElement=e,this.clipConfig=i,this.width=s?.width??Ot.DEFAULT_CURSOR_WIDTH_PX,this.color=s?.color??Ot.DEFAULT_CURSOR_COLOR,this.blinkIntervalMs=s?.blinkInterval??Ot.DEFAULT_BLINK_INTERVAL_MS,this.textPosition=0,this.isBlinking=!1,this.isVisible=!0,this.blinkInterval=null,this.createCursor()}updatePosition(t){if(!this.cursor||!this.textElement){console.warn("TextCursor: Cannot update position, cursor not initialized");return}this.textPosition=this.validateTextPosition(t),this.calculateAndApplyPixelPosition()}setPosition(t,e){if(!this.cursor){console.warn("TextCursor: Cannot set position, cursor not initialized");return}this.pixelX=t,this.pixelY=e,this.updateGraphicsPosition()}show(){this.setVisible(!0)}hide(){this.setVisible(!1)}setVisible(t){this.isVisible=t,this.cursor&&!this.isBlinking&&(this.cursor.visible=t)}startBlinking(){if(!this.cursor){console.warn("TextCursor: Cannot start blinking, cursor not initialized");return}this.isBlinking||this.startBlinkingAnimation()}stopBlinking(){this.stopBlinkingAnimation()}setBlinkInterval(t){this.blinkIntervalMs=t,this.isBlinking&&(this.stopBlinking(),this.startBlinking())}dispose(){if(this.stopBlinkingAnimation(),this.cursor&&this.parent)try{this.parent.removeChild(this.cursor)}catch(t){console.warn("TextCursor: Error removing cursor from parent:",t)}if(this.cursor)try{this.cursor.destroy()}catch(t){console.warn("TextCursor: Error destroying cursor graphics:",t)}finally{this.cursor=null}this.textPosition=0,this.pixelX=0,this.pixelY=0,this.currentLine=0,this.isVisible=!0}createCursor(){if(!this.textElement)return;this.cursor=new y.Graphics,this.cursor.fillStyle={color:this.color};const t=this.textElement.style.fontSize;this.cursor.rect(0,0,this.width,t),this.cursor.fill(),this.parent.addChild(this.cursor),this.cursor.visible=this.isVisible}validateTextPosition(t){return this.textElement?Math.max(0,Math.min(t,this.textElement.text.length)):0}calculateAndApplyPixelPosition(){this.calculatePixelPositionFromText(),this.updateGraphicsPosition()}calculatePixelPositionFromText(){if(!this.textElement)return;const{text:t}=this.textElement,e=this.textElement.style,i=t.substring(0,this.textPosition),s=i.match(/\n/g);this.currentLine=s?s.length:0;const n=t.split(`
|
|
183
|
+
`),r=this.currentLine<n.length?n[this.currentLine]:"",o=i.lastIndexOf(`
|
|
184
|
+
`),h=o===-1?this.textPosition:this.textPosition-o-1,l=r.substring(0,h);let c;l.length>0&&l.endsWith(" ")?c=this.measureText(`${l}x`,e)-this.measureText("x",e):c=this.measureText(l,e);const m=e.lineHeight;this.pixelY=this.currentLine*m;const k=this.clipConfig.asset.alignment?.horizontal??"center";let O=c;if(k!=="left"){const _=this.measureText(r,e),D=this.textElement.width;let H=0;k==="center"?H=(D-_)/2:k==="right"&&(H=D-_),O=H+c}this.pixelX=O}updateGraphicsPosition(){this.cursor&&this.cursor.position.set(this.pixelX,this.pixelY)}startBlinkingAnimation(){!this.cursor||this.isBlinking||(this.isBlinking=!0,this.blinkInterval=window.setInterval(()=>{this.cursor&&this.isBlinking&&(this.cursor.visible=!this.cursor.visible)},this.blinkIntervalMs))}stopBlinkingAnimation(){this.blinkInterval!==null&&(window.clearInterval(this.blinkInterval),this.blinkInterval=null),this.isBlinking=!1,this.cursor&&(this.cursor.visible=this.isVisible)}measureText(t,e){const i=new y.Text(t,e),{width:s}=i;return i.destroy(),s}isInitialized(){return this.cursor!==null}getState(){return{isInitialized:this.isInitialized(),isBlinking:this.isBlinking,isVisible:this.isVisible,textPosition:this.textPosition,pixelPosition:{x:this.pixelX,y:this.pixelY},currentLine:this.currentLine}}}class Wt{static DEFAULT_FOCUS_DELAY_MS=50;hiddenInput=null;isFocused=!1;focusRetryCount=0;maxFocusRetries=3;focusDelay=Wt.DEFAULT_FOCUS_DELAY_MS;eventHandlers={};abortController=null;textChangeCallback=null;lastSyncedText="";isComposing=!1;setupInput(t,e){this.focusDelay=e?.focusDelay??Wt.DEFAULT_FOCUS_DELAY_MS,this.createHiddenTextarea(),this.hiddenInput&&(this.hiddenInput.value=t,this.lastSyncedText=t),this.setupEventListeners(),e?.autoFocus!==!1&&this.focusInput()}updateInputValue(t){this.hiddenInput&&(this.hiddenInput.value=t,this.lastSyncedText=t)}focusInput(){this.hiddenInput&&setTimeout(()=>{this.hiddenInput&&!this.isFocused&&(this.hiddenInput.focus(),setTimeout(()=>{!this.isFocused&&this.focusRetryCount<this.maxFocusRetries&&(this.focusRetryCount+=1,this.focusInput())},10))},this.focusDelay)}blurInput(){this.hiddenInput&&this.hiddenInput.blur()}setSelectionRange(t,e){if(!this.hiddenInput)return;const i=this.hiddenInput.value.length,s=Math.max(0,Math.min(t,i)),n=Math.max(s,Math.min(e,i));this.hiddenInput.setSelectionRange(s,n)}getCursorPosition(){return this.hiddenInput?.selectionStart||0}getValue(){return this.hiddenInput?.value||""}setTextInputHandler(t){this.textChangeCallback=t}setEventHandlers(t){this.eventHandlers={...this.eventHandlers,...t}}isFocusedInput(){return this.isFocused}dispose(){this.removeAllEventListeners(),this.hiddenInput&&this.hiddenInput.parentNode&&this.hiddenInput.parentNode.removeChild(this.hiddenInput),this.hiddenInput=null,this.isFocused=!1,this.focusRetryCount=0,this.textChangeCallback=null,this.eventHandlers={}}createHiddenTextarea(){this.hiddenInput=document.createElement("textarea");const t={position:"absolute",opacity:"0.01",pointerEvents:"none",zIndex:"999",left:"0px",top:"0px",width:"1px",height:"1px",border:"none",outline:"none",resize:"none",backgroundColor:"transparent"};Object.assign(this.hiddenInput.style,t),this.hiddenInput.tabIndex=0,document.body.appendChild(this.hiddenInput)}setupEventListeners(){if(!this.hiddenInput)return;this.abortController=new AbortController;const{signal:t}=this.abortController;this.hiddenInput.addEventListener("input",this.handleTextInput,{signal:t}),this.hiddenInput.addEventListener("keydown",this.handleKeyDown,{signal:t}),this.hiddenInput.addEventListener("compositionstart",this.handleCompositionStart,{signal:t}),this.hiddenInput.addEventListener("compositionend",this.handleCompositionEnd,{signal:t}),this.hiddenInput.addEventListener("focus",this.handleFocus,{signal:t}),this.hiddenInput.addEventListener("blur",this.handleBlur,{signal:t}),this.hiddenInput.addEventListener("paste",this.handlePaste,{signal:t})}removeAllEventListeners(){this.abortController?.abort(),this.abortController=null}handleTextInput=t=>{if(!this.hiddenInput||this.isComposing)return;const e=this.hiddenInput.value,i=this.hiddenInput.selectionStart||0;this.lastSyncedText=e,this.textChangeCallback?.(e,i)};handleKeyDown=t=>{if(document.activeElement!==this.hiddenInput)return;let e=!1;if((t.ctrlKey||t.metaKey)&&(e=this.handleKeyboardShortcuts(t),e)){t.preventDefault();return}if(t.key==="Tab"){const i=t.shiftKey?"backward":"forward";this.eventHandlers.onTabNavigation?.(i),t.preventDefault();return}switch(t.key){case"Escape":this.eventHandlers.onEscape?.(t),e=!0;break;case"Enter":e=!1;break;case"ArrowLeft":case"ArrowRight":case"ArrowUp":case"ArrowDown":setTimeout(()=>{if(this.hiddenInput){const i=this.hiddenInput.value,s=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(i,s)}},0),e=!1;break;case"Backspace":case"Delete":e=!1;break;default:e=this.eventHandlers.onCustomKey?.(t.key,t)||!1;break}e&&t.preventDefault()};handleKeyboardShortcuts(t){const{key:e}=t;switch(e.toLowerCase()){case"a":return this.selectAll(),!0;case"c":case"v":return!1;case"z":return this.eventHandlers.onCustomKey?.("undo",t),!0;case"y":return this.eventHandlers.onCustomKey?.("redo",t),!0;default:return!1}}handleCompositionStart=t=>{this.isComposing=!0};handleCompositionEnd=t=>{if(this.isComposing=!1,this.hiddenInput){const e=this.hiddenInput.value,i=this.hiddenInput.selectionStart||0;this.textChangeCallback?.(e,i)}};handleFocus=t=>{this.isFocused=!0,this.focusRetryCount=0,this.eventHandlers.onFocus?.(t)};handleBlur=t=>{this.isFocused=!1,this.eventHandlers.onBlur?.(t)};handlePaste=t=>{setTimeout(()=>{this.handleTextInput(t)},0)};selectAll(){this.hiddenInput&&this.hiddenInput.select()}}class j{static DOUBLE_CLICK_THRESHOLD_MS=300;static EDITING_BG_PADDING_PX=5;static EDITING_BG_ALPHA=.2;static CLICK_HANDLER_DELAY_MS=100;parent;targetText;clipConfig;isEditing=!1;lastClickTime=0;editingContainer=null;editableText=null;textCursor=null;textInputHandler=null;outsideClickHandler=null;constructor(t,e,i){this.parent=t,this.targetText=e,this.clipConfig=i,this.parent.getContainer().eventMode="static",this.parent.getContainer().on("click",this.checkForDoubleClick)}dispose(){this.parent.getContainer().off("click",this.checkForDoubleClick),this.stopEditing(),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null)}startEditing(){if(this.isEditing||!this.targetText)return;const t=structuredClone(this.clipConfig);this.targetText.visible=!1,this.createEditingEnvironment(),this.setupOutsideClickHandler(t),this.isEditing=!0}stopEditing(t=!1,e){if(!this.isEditing)return;let i="";this.editableText&&(i=this.editableText.text),this.editingContainer&&(this.parent.getContainer().removeChild(this.editingContainer),this.editingContainer.destroy(),this.editingContainer=null),this.editableText=null,this.textCursor&&(this.textCursor.dispose(),this.textCursor=null),this.textInputHandler&&(this.textInputHandler.dispose(),this.textInputHandler=null),this.targetText.visible=!0,t&&e&&i!==""&&this.parent.updateTextContent(i,e),this.isEditing=!1}checkForDoubleClick=t=>{const e=Date.now();e-this.lastClickTime<j.DOUBLE_CLICK_THRESHOLD_MS&&this.startEditing(),this.lastClickTime=e};setupOutsideClickHandler(t){this.outsideClickHandler=e=>{const s=this.parent.getContainer().getBounds(),n=e.clientX,r=e.clientY;(n<s.x||n>s.x+s.width||r<s.y||r>s.y+s.height)&&(this.stopEditing(!0,t),this.outsideClickHandler&&(window.removeEventListener("click",this.outsideClickHandler),this.outsideClickHandler=null))},setTimeout(()=>{this.outsideClickHandler&&window.addEventListener("click",this.outsideClickHandler)},j.CLICK_HANDLER_DELAY_MS)}createEditingEnvironment(){this.setupEditingContainer(),this.editingContainer&&this.editableText&&(this.textCursor=new Ot(this.editingContainer,this.editableText,this.clipConfig),this.textCursor.updatePosition(this.targetText.text.length),this.textCursor.startBlinking()),this.setupTextInputHandler(),this.updateTextAlignment()}setupEditingContainer(){this.editingContainer=new y.Container,this.parent.getContainer().addChild(this.editingContainer);const t=new y.Graphics;t.fillStyle={color:0,alpha:j.EDITING_BG_ALPHA},t.rect(-5,-5,this.targetText.width+2*j.EDITING_BG_PADDING_PX,this.targetText.height+2*j.EDITING_BG_PADDING_PX),t.fill(),this.editingContainer.addChild(t),this.editableText=new y.Text(this.targetText.text,this.targetText.style),this.editableText.eventMode="static",this.editableText.cursor="text",this.editingContainer.addChild(this.editableText)}setupTextInputHandler(){this.textInputHandler=new Wt,this.textInputHandler.setTextInputHandler((t,e)=>{this.editableText&&(this.editableText.text=t,this.updateTextAlignment()),this.textCursor?.updatePosition(e)}),this.textInputHandler.setEventHandlers({onEscape:t=>this.stopEditing(!1),onTabNavigation:t=>this.stopEditing(!0)}),this.textInputHandler.setupInput(this.targetText.text,{autoFocus:!0})}updateTextAlignment(){if(!this.editableText||!this.editingContainer)return;const t=this.getContainerDimensions(),e=this.getAlignmentSettings(),i=this.calculateHorizontalPosition({width:this.editableText.width},t,e.horizontal),s=this.calculateVerticalPosition({height:this.editableText.height},t,e.vertical);if(this.editingContainer.position.set(i,s),this.editingContainer.children.length>0){const n=this.editingContainer.getChildAt(0);n instanceof y.Graphics&&(n.clear(),n.fillStyle={color:0,alpha:j.EDITING_BG_ALPHA},n.rect(-5,-5,this.editableText.width+2*j.EDITING_BG_PADDING_PX,this.editableText.height+2*j.EDITING_BG_PADDING_PX),n.fill())}}calculateHorizontalPosition(t,e,i="center"){switch(i){case"center":return e.width/2-t.width/2;case"right":return e.width-t.width;case"left":default:return 0}}calculateVerticalPosition(t,e,i="center"){switch(i){case"center":return e.height/2-t.height/2;case"bottom":return e.height-t.height;case"top":default:return 0}}getContainerDimensions(){const t=this.clipConfig.asset;return{width:t.width??this.parent.getSize().width,height:t.height??this.parent.getSize().height}}getAlignmentSettings(){const t=this.clipConfig.asset;return{horizontal:t.alignment?.horizontal??"center",vertical:t.alignment?.vertical??"center"}}}class ps extends P{background=null;text=null;textEditor=null;async load(){await super.load();const t=this.clipConfiguration.asset;if(this.background=new y.Graphics,t.background&&(this.background.fillStyle={color:t.background.color,alpha:t.background.opacity},this.background.rect(0,0,t.width??this.edit.size.width,t.height??this.edit.size.height),this.background.fill()),this.text=new y.Text(t.text,this.createTextStyle(t)),this.positionText(t),t.stroke){const e=new he({thickness:t.stroke.width,color:t.stroke.color});this.text.filters=[e]}this.getContainer().addChild(this.background),this.getContainer().addChild(this.text),this.configureKeyframes(),this.textEditor=new j(this,this.text,this.clipConfiguration)}update(t,e){super.update(t,e)}dispose(){super.dispose(),this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null,this.textEditor?.dispose(),this.textEditor=null}getSize(){const t=this.clipConfiguration.asset;return{width:t.width??this.edit.size.width,height:t.height??this.edit.size.height}}getFitScale(){return 1}createTextStyle(t){return new y.TextStyle({fontFamily:t.font?.family??"Open Sans",fontSize:t.font?.size??32,fill:t.font?.color??"#ffffff",fontWeight:(t.font?.weight??"400").toString(),wordWrap:!0,wordWrapWidth:t.width??this.edit.size.width,lineHeight:(t.font?.lineHeight??1)*(t.font?.size??32),align:t.alignment?.horizontal??"center"})}positionText(t){if(!this.text)return;const e=t.alignment?.horizontal??"center",i=t.alignment?.vertical??"center",s=t.width??this.edit.size.width,n=t.height??this.edit.size.height;let r=s/2-this.text.width/2,o=n/2-this.text.height/2;e==="left"?r=0:e==="right"&&(r=s-this.text.width),i==="top"?o=0:i==="bottom"&&(o=n-this.text.height),this.text.position.set(r,o)}updateTextContent(t,e){if(this.clipConfiguration.asset&&"text"in this.clipConfiguration.asset){if(this.clipConfiguration.asset.text=t,this.text){this.text.text=t;const i=this.clipConfiguration.asset;this.positionText(i)}this.edit.setUpdatedClip(this,e)}}}class gs extends P{texture;sprite;isPlaying;volumeKeyframeBuilder;syncTimer;constructor(t,e){super(t,e),this.texture=null,this.sprite=null,this.isPlaying=!1;const i=this.clipConfiguration.asset;this.volumeKeyframeBuilder=new E(i.volume??1,this.getLength()),this.syncTimer=0}async load(){await super.load();const t=this.clipConfiguration.asset,e=t.src;if(e.endsWith(".mov")||e.endsWith(".webm"))throw new Error(`Video source '${t.src}' is not supported. .mov and .webm files are currently not supported.`);const i={src:e,data:{autoPlay:!1,muted:!1}},s=await this.edit.assetLoader.load(e,i);if(!(s?.source instanceof y.VideoSource))throw new Error(`Invalid video source '${t.src}'.`);this.texture=this.createCroppedTexture(s),this.sprite=new y.Sprite(this.texture),this.getContainer().addChild(this.sprite),this.configureKeyframes()}update(t,e){super.update(t,e);const{trim:i=0}=this.clipConfiguration.asset;if(this.syncTimer+=e,!this.texture)return;const s=this.getPlaybackTime(),n=this.edit.isPlaying&&this.isActive();n&&(this.isPlaying||(this.isPlaying=!0,this.texture.source.resource.currentTime=s/1e3+i,this.texture.source.resource.play().catch(console.error)),this.texture.source.resource.volume!==this.getVolume()&&(this.texture.source.resource.volume=this.getVolume()),Math.abs((this.texture.source.resource.currentTime-i)*1e3-s)>100&&(this.texture.source.resource.currentTime=s/1e3+i)),!n&&this.isPlaying&&(this.isPlaying=!1,this.texture.source.resource.pause());const r=this.syncTimer>100;!this.edit.isPlaying&&this.isActive()&&r&&(this.syncTimer=0,this.texture.source.resource.currentTime=s/1e3+i)}draw(){super.draw()}dispose(){super.dispose(),this.sprite?.destroy(),this.sprite=null,this.texture?.destroy(),this.texture=null}getSize(){return{width:this.sprite?.width??0,height:this.sprite?.height??0}}getVolume(){return this.volumeKeyframeBuilder.getValue(this.getPlaybackTime())}createCroppedTexture(t){const e=this.clipConfiguration.asset;if(!e.crop)return t;const i=t.width,s=t.height,n=Math.floor((e.crop?.left??0)*i),r=Math.floor((e.crop?.right??0)*i),o=Math.floor((e.crop?.top??0)*s),h=Math.floor((e.crop?.bottom??0)*s),l=n,c=o,m=i-n-r,p=s-o-h,k=new y.Rectangle(l,c,m,p);return new y.Texture({source:t.source,frame:k})}}class lt extends le{static ZIndexPadding=100;assetLoader;events;edit;tracks;clipsToDispose;clips;playbackTime;size;backgroundColor;totalDuration;isPlaying;selectedClip;updatedClip;constructor(t,e="#ffffff"){super(),this.assetLoader=new At,this.edit=null,this.tracks=[],this.clipsToDispose=[],this.clips=[],this.events=new me,this.size=t,this.playbackTime=0,this.totalDuration=0,this.isPlaying=!1,this.selectedClip=null,this.updatedClip=null,this.backgroundColor=e}async load(){const t=new y.Graphics;t.fillStyle={color:this.backgroundColor},t.rect(0,0,this.size.width,this.size.height),t.fill(),this.getContainer().addChild(t)}update(t,e){for(const i of this.clips)i.shouldDispose&&this.queueDisposeClip(i),i.update(t,e);this.disposeClips(),this.isPlaying&&(this.playbackTime=Math.max(0,Math.min(this.playbackTime+e,this.totalDuration)),this.playbackTime===this.totalDuration&&this.pause())}draw(){for(const t of this.clips)t.draw()}dispose(){this.clearClips()}play(){this.isPlaying=!0}pause(){this.isPlaying=!1}seek(t){this.playbackTime=Math.max(0,Math.min(t,this.totalDuration)),this.pause()}stop(){this.seek(0)}async loadEdit(t){this.clearClips(),this.edit=Ji.parse(t),this.backgroundColor=this.edit.timeline.background||"#000000",await Promise.all((this.edit.timeline.fonts??[]).map(async e=>{const i=e.src,s={src:i,loadParser:Pt.Name};return this.assetLoader.load(i,s)}));for(const[e,i]of this.edit.timeline.tracks.entries())for(const s of i.clips){const n=this.createPlayerFromAssetType(s);n.layer=e+1,await this.addPlayer(e,n)}this.updateTotalDuration()}getEdit(){const t=[],e=new Map;for(const s of this.clips)e.has(s.layer)||e.set(s.layer,{clips:[]}),e.get(s.layer).clips.push(s.clipConfiguration);const i=Math.max(...e.keys(),0);for(let s=1;s<=i;s+=1)t[s-1]=e.get(s)||{clips:[]};return{timeline:{background:this.backgroundColor,tracks:t,fonts:this.edit?.timeline.fonts||[]},output:this.edit?.output||{size:this.size,format:"mp4"}}}addClip(t,e){const i=Ne.parse(e),s=this.createPlayerFromAssetType(i);s.layer=t+1,this.addPlayer(t,s),this.updateTotalDuration()}getClip(t,e){const i=this.clips.filter(s=>s.layer===t+1);return e<0||e>=i.length?null:i[e].clipConfiguration}deleteClip(t,e){const i=this.clips.find(s=>s.layer===t+1&&this.clips.filter(n=>n.layer===t+1).indexOf(s)===e);i&&(this.queueDisposeClip(i),this.updateTotalDuration())}addTrack(t,e){this.tracks.splice(t,0,[]);const i=this.clips.map((s,n)=>({clip:s,index:n})).filter(({clip:s})=>s.layer>=t+1);i.forEach(({clip:s})=>{const r=`shotstack-track-${1e5-s.layer*lt.ZIndexPadding}`;this.getContainer().getChildByLabel(r,!1)?.removeChild(s.getContainer())});for(const{index:s}of i)this.clips[s].layer+=1;i.forEach(({clip:s})=>{const n=1e5-s.layer*lt.ZIndexPadding,r=`shotstack-track-${n}`;let o=this.getContainer().getChildByLabel(r,!1);o||(o=new y.Container({label:r,zIndex:n}),this.getContainer().addChild(o)),o.addChild(s.getContainer())}),e?.clips?.forEach(s=>this.addClip(t,s)),this.updateTotalDuration()}getTrack(t){const e=this.clips.filter(i=>i.layer===t+1);return e.length===0?null:{clips:e.map(i=>i.clipConfiguration)}}deleteTrack(t){const e=this.clips.filter(s=>s.layer===t+1);for(const s of e)s.shouldDispose=!0;this.disposeClips(),this.tracks.splice(t,1);const i=this.clips.map((s,n)=>({clip:s,index:n})).filter(({clip:s})=>s.layer>t+1);i.forEach(({clip:s})=>{const r=`shotstack-track-${1e5-s.layer*lt.ZIndexPadding}`;this.getContainer().getChildByLabel(r,!1)?.removeChild(s.getContainer())});for(const{index:s}of i)this.clips[s].layer-=1;i.forEach(({clip:s})=>{const n=1e5-s.layer*lt.ZIndexPadding,r=`shotstack-track-${n}`;let o=this.getContainer().getChildByLabel(r,!1);o||(o=new y.Container({label:r,zIndex:n}),this.getContainer().addChild(o)),o.addChild(s.getContainer())}),this.updateTotalDuration()}getTotalDuration(){return this.totalDuration}getSelectedClip(){return this.selectedClip}setSelectedClip(t){this.selectedClip=t;const e=t.layer-1,s=this.clips.filter(r=>r.layer===t.layer).indexOf(t),n={clip:t.clipConfiguration,trackIndex:e,clipIndex:s};this.events.emit("clip:selected",n)}setUpdatedClip(t,e=null){this.updatedClip=t;const i=t.layer-1,n=this.clips.filter(o=>o.layer===t.layer).indexOf(t),r={previous:{clip:e,trackIndex:i,clipIndex:n},current:{clip:t.clipConfiguration,trackIndex:i,clipIndex:n}};this.events.emit("clip:updated",r)}queueDisposeClip(t){this.clipsToDispose.push(t)}disposeClips(){if(this.clipsToDispose.length!==0){for(const t of this.clipsToDispose)this.disposeClip(t);this.clips=this.clips.filter(t=>!this.clipsToDispose.includes(t)),this.clipsToDispose=[],this.updateTotalDuration()}}disposeClip(t){try{if(this.getContainer().children.includes(t.getContainer())){const e=this.getContainer().getChildIndex(t.getContainer());this.getContainer().removeChildAt(e)}else for(const e of this.getContainer().children)if(e instanceof y.Container&&e.label?.toString().startsWith("shotstack-track-")&&e.children.includes(t.getContainer())){e.removeChild(t.getContainer());break}}catch{console.warn("Attempting to unmount an unmounted clip.")}this.unloadClipAssets(t),t.dispose()}unloadClipAssets(t){const{asset:e}=t.clipConfiguration;if(e&&"src"in e&&typeof e.src=="string")try{y.Assets.unload(e.src)}catch(i){console.warn(`Failed to unload asset: ${e.src}`,i)}}clearClips(){for(const t of this.clips)this.disposeClip(t);this.clips=[],this.clipsToDispose=[],this.updateTotalDuration()}updateTotalDuration(){let t=0;for(const e of this.tracks)for(const i of e)t=Math.max(t,i.getEnd());this.totalDuration=t}createPlayerFromAssetType(t){if(!t.asset?.type)throw new Error("Invalid clip configuration: missing asset type");let e;switch(t.asset.type){case"text":{e=new ps(this,t);break}case"shape":{e=new fs(this,t);break}case"html":{e=new us(this,t);break}case"image":{e=new ds(this,t);break}case"video":{e=new gs(this,t);break}case"audio":{e=new ce(this,t);break}case"luma":{e=new He(this,t);break}default:throw new Error(`Unsupported clip type: ${t.asset.type}`)}return e}async addPlayer(t,e){for(;this.tracks.length<=t;)this.tracks.push([]);this.tracks[t].push(e),this.clips.push(e);const i=1e5-(t+1)*lt.ZIndexPadding,s=`shotstack-track-${i}`;let n=this.getContainer().getChildByLabel(s,!1);n||(n=new y.Container({label:s,zIndex:i}),this.getContainer().addChild(n)),n.addChild(e.getContainer());const r=e instanceof He;await e.load(),r&&n.setMask({mask:e.getMask(),inverse:!0}),this.updateTotalDuration()}}class It extends le{static Width=250;static Height=100;fps;playbackTime;playbackDuration;isPlaying;background;text;constructor(){super(),this.background=null,this.text=null,this.fps=0,this.playbackTime=0,this.playbackDuration=0,this.isPlaying=!1}async load(){const t=new y.Graphics;t.fillStyle={color:"#424242",alpha:.5},t.rect(0,0,It.Width,It.Height),t.fill(),this.getContainer().addChild(t),this.background=t;const e=new y.Text;e.text="",e.style={fontFamily:"monospace",fontSize:14,fill:"#ffffff",wordWrap:!0,wordWrapWidth:It.Width},this.getContainer().addChild(e),this.text=e}update(t,e){if(!this.text)return;const i=this.getMemoryInfo(),s=[`FPS: ${this.fps}`,`Playback: ${(this.playbackTime/1e3).toFixed(2)}/${(this.playbackDuration/1e3).toFixed(2)}`,`Playing: ${this.isPlaying}`,`Total Heap Size: ${i.totalHeapSize?`${this.bytesToMegabytes(i.totalHeapSize)}MB`:"N/A"}`,`Used Heap Size: ${i.usedHeapSize?`${this.bytesToMegabytes(i.usedHeapSize)}MB`:"N/A"}`,`Heap Size Limit: ${i.heapSizeLimit?`${this.bytesToMegabytes(i.heapSizeLimit)}MB`:"N/A"}`];this.text.text=s.join(`
|
|
185
|
+
`)}draw(){}dispose(){this.background?.destroy(),this.background=null,this.text?.destroy(),this.text=null}getMemoryInfo(){const t={};return"memory"in performance&&(t.totalHeapSize=performance.memory.totalJSHeapSize,t.usedHeapSize=performance.memory.usedJSHeapSize,t.heapSizeLimit=performance.memory.jsHeapSizeLimit),t}bytesToMegabytes(t){return Math.round(t/1024/1024)}}class ct{static CanvasSelector="[data-shotstack-studio]";static extensionsRegistered=!1;size;application;edit;inspector;container;background;minZoom=.1;maxZoom=4;currentZoom=.8;constructor(t,e){this.size=t,this.application=new y.Application,this.edit=e,this.inspector=new It}async load(){const t=document.querySelector(ct.CanvasSelector);if(!t)throw new Error(`Shotstack canvas root element '${ct.CanvasSelector}' not found.`);this.registerExtensions(),this.container=new y.Container,this.background=new y.Graphics,this.background.fillStyle={color:"#424242"},this.background.rect(0,0,this.size.width,this.size.height),this.background.fill(),await this.configureApplication(),this.configureStage(),this.setupTouchHandling(t),this.edit.getContainer().scale=this.currentZoom,t.appendChild(this.application.canvas)}setupTouchHandling(t){const e=this.edit.getContainer();t.addEventListener("wheel",i=>{if(i.preventDefault(),i.stopPropagation(),i.ctrlKey){const s=Math.exp(-i.deltaY/100),n=this.currentZoom*s,r=this.currentZoom;this.currentZoom=Math.min(Math.max(n,this.minZoom),this.maxZoom);const o={x:this.application.canvas.width/2,y:this.application.canvas.height/2},h={x:e.position.x-o.x,y:e.position.y-o.y},l=this.currentZoom/r;e.position.x=o.x+h.x*l,e.position.y=o.y+h.y*l,e.scale.x=this.currentZoom,e.scale.y=this.currentZoom}},{passive:!1,capture:!0})}centerEdit(){if(!this.edit)return;const t=this.edit.getContainer();t.position={x:this.application.canvas.width/2-this.edit.size.width*this.currentZoom/2,y:this.application.canvas.height/2-this.edit.size.height*this.currentZoom/2}}zoomToFit(){if(!this.edit)return;const t=this.application.canvas.width/this.edit.size.width,e=this.application.canvas.height/this.edit.size.height,i=Math.min(t,e);this.currentZoom=Math.min(Math.max(i,this.minZoom),this.maxZoom);const s=this.edit.getContainer();s.scale.x=this.currentZoom,s.scale.y=this.currentZoom,this.centerEdit()}setZoom(t){this.currentZoom=Math.min(Math.max(t,this.minZoom),this.maxZoom);const e=this.edit.getContainer();e.scale.x=this.currentZoom,e.scale.y=this.currentZoom}registerExtensions(){ct.extensionsRegistered||(y.extensions.add(new $t),y.extensions.add(new Pt),ct.extensionsRegistered=!0)}async configureApplication(){const t={background:"#000000",width:this.size.width,height:this.size.height,antialias:!0};await this.application.init(t),this.application.ticker.add(this.onTick.bind(this)),this.application.ticker.minFPS=60,this.application.ticker.maxFPS=60}onTick(t){this.edit.update(t.deltaTime,t.deltaMS),this.edit.draw(),this.inspector.fps=Math.ceil(t.FPS),this.inspector.playbackTime=this.edit.playbackTime,this.inspector.playbackDuration=this.edit.totalDuration,this.inspector.isPlaying=this.edit.isPlaying,this.inspector.update(t.deltaTime,t.deltaMS),this.inspector.draw()}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 y.Rectangle(0,0,this.size.width,this.size.height),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()}dispose(){const t=document.querySelector(ct.CanvasSelector);t&&t.contains(this.application.canvas)&&t.removeChild(this.application.canvas),this.application.ticker.remove(this.onTick,this),this.application.stage.off("click",this.onClick,this),this.background?.destroy(),this.container?.destroy(),this.inspector.dispose(),this.application.destroy(!0,{children:!0,texture:!0})}}class ms{edit;seekDistance=50;seekDistanceLarge=500;frameTime=16.67;constructor(t){this.edit=t}async load(){document.addEventListener("keydown",this.handleKeyDown),document.addEventListener("keyup",this.handleKeyUp)}dispose(){document.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("keyup",this.handleKeyUp)}handleKeyDown=t=>{if(!(t.target instanceof HTMLInputElement||t.target instanceof HTMLTextAreaElement))switch(t.code){case"Space":{this.edit.isPlaying?this.edit.pause():this.edit.play();break}case"ArrowLeft":{if(t.metaKey)this.edit.seek(0);else{const e=t.shiftKey?this.seekDistanceLarge:this.seekDistance;this.edit.seek(this.edit.playbackTime-e)}break}case"ArrowRight":{if(t.metaKey)this.edit.seek(this.edit.getTotalDuration());else{const e=t.shiftKey?this.seekDistanceLarge:this.seekDistance;this.edit.seek(this.edit.playbackTime+e)}break}case"KeyJ":{this.edit.stop();break}case"KeyK":{this.edit.pause();break}case"KeyL":{this.edit.play();break}case"Comma":{this.edit.seek(this.edit.playbackTime-this.frameTime);break}case"Period":{this.edit.seek(this.edit.playbackTime+this.frameTime);break}}};handleKeyUp=t=>{if(!(t.target instanceof HTMLInputElement||t.target instanceof HTMLTextAreaElement))switch(t.code){case"KeyI":console.log(this.edit.getEdit());break}}}class ys{ffmpeg;isReady=!1;edit;application;constructor(t,e){this.edit=t,this.application=e.application,this.ffmpeg=new Ue.FFmpeg}async init(){if(!this.isReady)try{await this.ffmpeg.load(),this.isReady=!0}catch(t){throw console.error("FFmpeg initialization failed:",t),t}}async export(t="shotstack-export.mp4",e=30){this.isReady||await this.init();const i=this.edit.isPlaying,s=this.edit.playbackTime;this.edit.pause();const n=this.edit.getContainer(),r=n.visible,{x:o,y:h}=n.position,{x:l,y:c}=n.scale;n.visible=!1;const m=this.createProgressOverlay();try{const p=this.edit.getSize?this.edit.getSize():{width:1920,height:1080},k=Math.ceil(this.edit.totalDuration*e/1e3),O=1e3/e,_=100,D=50,H=50,vt=I=>Math.round(I/k*D);this.updateProgressOverlay(m,0,_);const G=document.createElement("canvas");G.width=p.width,G.height=p.height;const xt=G.getContext("2d");if(!xt)throw new Error("Could not get 2D context for canvas");const ue=this.findAudioPlayers();this.updateProgressOverlay(m,2,_);const q=[];if(ue.length>0){this.updateProgressOverlay(m,3,_);for(let I=0;I<ue.length;I+=1){const B=await this.processAudioTrack(ue[I],I);B&&q.push(B),this.updateProgressOverlay(m,4+I,_)}}n.position.x=0,n.position.y=0,n.scale.x=1,n.scale.y=1;for(let I=0;I<k;I+=1){this.edit.seek(I*O),this.edit.tick?this.edit.tick(0,0):(this.edit.update?.(0,0),this.edit.draw?.());try{const{extract:B}=this.application.renderer,M=B.canvas(n);xt.clearRect(0,0,G.width,G.height),xt.drawImage(M,0,0);const Q=G.toDataURL("image/png"),Xt=await(await fetch(Q)).arrayBuffer(),ws=`frame_${I.toString().padStart(6,"0")}.png`;await this.ffmpeg.writeFile(ws,new Uint8Array(Xt))}catch(B){console.error(`Error capturing frame ${I}:`,B)}this.updateProgressOverlay(m,vt(I+1),_)}this.updateProgressOverlay(m,D,_);let it=["-framerate",e.toString(),"-i","frame_%06d.png"];for(const I of q)it=it.concat(["-i",I.filename]);if(it=it.concat(["-c:v","libx264","-pix_fmt","yuv420p","-crf","23"]),q.length>0){let I="";for(let M=0;M<q.length;M+=1){const Q=q[M],Ke=M+1,Xt=Math.max(0,Q.start);I+=`[${Ke}:a]aformat=sample_fmts=fltp:sample_rates=44100:channel_layouts=stereo,apad,afade=t=in:st=0:d=0.05,atrim=start=0:end=${Q.duration/1e3+.1},adelay=${Xt}|${Xt},volume=${Q.volume}[a${M}];`}const B=q.length>1?`${q.map((M,Q)=>`[a${Q}]`).join("")}amix=inputs=${q.length}:duration=longest:dropout_transition=0.5:normalize=0[aout]`:"[a0]aformat=sample_fmts=fltp:sample_rates=44100:channel_layouts=stereo[aout]";I+=B,it=it.concat(["-filter_complex",I,"-map","0:v","-map","[aout]","-c:a","aac","-b:a","192k","-shortest"])}const de="output.mp4";it.push(de);let Be=0;const Ve=({message:I})=>{const B=I.includes("frame=")&&I.includes("fps=")?I.match(/frame=\s*(\d+)/):null;if(B?.[1]){const M=parseInt(B[1],10);if(!Number.isNaN(M)&&M>Be&&(Be=M,M<=k)){const Q=Math.round(M/k*H);this.updateProgressOverlay(m,D+Q,_)}}};this.ffmpeg.on("log",Ve),await this.ffmpeg.exec(it),this.ffmpeg.off("log",Ve),this.updateProgressOverlay(m,D+H,_);const fe=await this.ffmpeg.readFile(de),vs=fe instanceof Uint8Array?fe:new TextEncoder().encode(fe.toString()),xs=new Blob([vs],{type:"video/mp4"}),Ze=URL.createObjectURL(xs),pe=document.createElement("a");pe.href=Ze,pe.download=t,pe.click(),URL.revokeObjectURL(Ze);for(let I=0;I<k;I+=1)try{await this.ffmpeg.deleteFile(`frame_${I.toString().padStart(6,"0")}.png`)}catch{}for(const I of q)try{await this.ffmpeg.deleteFile(I.filename)}catch{}await this.ffmpeg.deleteFile(de),this.updateProgressOverlay(m,_,_)}catch(p){throw console.error("Error during export:",p),p}finally{this.removeProgressOverlay(m),n.position.x=o,n.position.y=h,n.scale.x=l,n.scale.y=c,n.visible=r,this.edit.seek(s),i&&this.edit.play()}}findAudioPlayers(){const t=[],e=this.edit.tracks;if(e&&Array.isArray(e))for(let i=0;i<e.length;i+=1){const s=e[i];if(Array.isArray(s))for(let n=0;n<s.length;n+=1){const r=s[n];(r instanceof ce||r.constructor.name==="AudioPlayer"||r.clipConfiguration?.asset?.type==="audio")&&(t.includes(r)||t.push(r))}}return this.searchContainerForPlayers(this.edit.getContainer(),t),t}searchContainerForPlayers(t,e){if(t){for(const i of t.children)if(i instanceof y.Container){if(i.label?.startsWith("shotstack-track-")){for(const n of i.children)if(n instanceof y.Container){const r=n,o=["player","clip","audioPlayer","entity"];for(const h of o){const l=r[h];l instanceof ce&&!e.includes(l)&&e.push(l)}}}this.searchContainerForPlayers(i,e)}}}async processAudioTrack(t,e){try{const{clipConfiguration:i}=t;if(!i?.asset)return null;const s=i.asset;if(!s.src)return console.warn("Audio asset does not have a valid src property"),null;const n=await fetch(s.src);if(!n.ok)return console.error(`Failed to fetch audio file: ${s.src}`),null;const r=await n.arrayBuffer(),o=`audio_${e}.mp3`;return await this.ffmpeg.writeFile(o,new Uint8Array(r)),{filename:o,start:t.getStart(),duration:t.getLength(),volume:t.getVolume()}}catch(i){return console.error(`Error processing audio track ${e}:`,i),null}}createProgressOverlay(){const t=document.createElement("div");t.className="video-export-progress-overlay",Object.assign(t.style,{position:"fixed",top:"0",left:"0",width:"100%",height:"100%",backgroundColor:"rgba(0, 0, 0, 0.5)",zIndex:"9999",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:"center",color:"white",fontFamily:"Arial, sans-serif"});const e=document.createElement("div");Object.assign(e.style,{backgroundColor:"#222",borderRadius:"8px",padding:"20px",boxShadow:"0 4px 8px rgba(0, 0, 0, 0.2)",width:"300px",textAlign:"center"}),t.appendChild(e);const i=document.createElement("h3");i.innerText="Exporting Video",i.style.margin="0 0 15px 0",i.style.fontWeight="normal",e.appendChild(i);const s=document.createElement("div");Object.assign(s.style,{width:"100%",height:"6px",backgroundColor:"#444",borderRadius:"3px",overflow:"hidden",marginBottom:"10px"}),e.appendChild(s);const n=document.createElement("div");n.className="video-export-progress-bar",Object.assign(n.style,{width:"0%",height:"100%",backgroundColor:"#3498db",transition:"width 0.3s"}),s.appendChild(n);const r=document.createElement("div");return r.className="video-export-percent",r.innerText="0%",r.style.fontSize="12px",e.appendChild(r),document.body.appendChild(t),t}updateProgressOverlay(t,e,i){if(!t)return;const s=Math.round(e/i*100),n=t.querySelector(".video-export-progress-bar"),r=t.querySelector(".video-export-percent");n&&(n.style.width=`${s}%`),r&&(r.innerText=`${s}%`)}removeProgressOverlay(t){t?.parentNode?.removeChild(t)}}F.Canvas=ct,F.Controls=ms,F.Edit=lt,F.VideoExporter=ys,Object.defineProperty(F,Symbol.toStringTag,{value:"Module"})});
|