@bylqwjc/media-editor-server 1.0.26 → 1.0.28

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/core/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@media-editor/core",
3
- "version": "1.0.26",
3
+ "version": "1.0.22",
4
4
  "description": "媒体编辑器框架无关内核:状态/时间轴/ffmpeg 参数/几何/标注渲染/VideoEditorEngine/图片编辑器纯配置工厂(零 React)",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -1 +1 @@
1
- import{ZodError as R,ZodIssueCode as o}from"./ZodError.js";import{defaultErrorMap as _e,getErrorMap as ye}from"./errors.js";import{errorUtil as l}from"./helpers/errorUtil.js";import{DIRTY as W,INVALID as f,OK as x,ParseStatus as w,addIssueToContext as c,isAborted as ge,isAsync as ie,isDirty as ve,isValid as D,makeIssue as ke}from"./helpers/parseUtil.js";import{util as k,ZodParsedType as h,getParsedType as j}from"./helpers/util.js";class C{constructor(e,t,s,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const xe=(n,e)=>{if(D(e))return{success:!0,data:e.value};if(!n.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 R(n.common.issues);return this._error=t,this._error}}};function _(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:s,description:a}=n;if(e&&(t||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:a}:{errorMap:(d,i)=>{const{message:r}=n;return d.code==="invalid_enum_value"?{message:r??i.defaultError}:typeof i.data>"u"?{message:r??s??i.defaultError}:d.code!=="invalid_type"?{message:i.defaultError}:{message:r??t??i.defaultError}},description:a}}class y{get description(){return this._def.description}_getType(e){return j(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:j(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new w,ctx:{common:e.parent.common,data:e.data,parsedType:j(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(ie(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 s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){const s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:j(e)},a=this._parseSync({data:e,path:s.path,parent:s});return xe(s,a)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:j(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:t});return D(s)?{value:s.value}:{issues:t.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(s=>D(s)?{value:s.value}:{issues:t.common.issues})}async parseAsync(e,t){const s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){const s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:j(e)},a=this._parse({data:e,path:s.path,parent:s}),d=await(ie(a)?a:Promise.resolve(a));return xe(s,d)}refine(e,t){const s=a=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(a):t;return this._refinement((a,d)=>{const i=e(a),r=()=>d.addIssue({code:o.custom,...s(a)});return typeof Promise<"u"&&i instanceof Promise?i.then(u=>u?!0:(r(),!1)):i?!0:(r(),!1)})}refinement(e,t){return this._refinement((s,a)=>e(s)?!0:(a.addIssue(typeof t=="function"?t(s,a):t),!1))}_refinement(e){return new b({schema:this,typeName:p.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 O.create(this,this._def)}nullable(){return I.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Z.create(this)}promise(){return K.create(this,this._def)}or(e){return J.create([this,e],this._def)}and(e){return G.create(this,e,this._def)}transform(e){return new b({..._(this._def),schema:this,typeName:p.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new te({..._(this._def),innerType:this,defaultValue:t,typeName:p.ZodDefault})}brand(){return new fe({typeName:p.ZodBranded,type:this,..._(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new se({..._(this._def),innerType:this,catchValue:t,typeName:p.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ne.create(this,e)}readonly(){return ae.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const je=/^c[^\s-]{8,}$/i,Pe=/^[0-9a-z]+$/,Ie=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ee=/^[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,Fe=/^[a-z0-9_-]{21}$/i,Me=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Le=/^[-+]?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)?)??$/,$e=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ze="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let pe;const De=/^(?:(?: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])$/,Ue=/^(?:(?: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])$/,Ve=/^(([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]))$/,Ke=/^(([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])$/,Be=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,We=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,we="((\\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])))",Ye=new RegExp(`^${we}$`);function be(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);const t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function qe(n){return new RegExp(`^${be(n)}$`)}function Ze(n){let e=`${we}T${be(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function He(n,e){return!!((e==="v4"||!e)&&De.test(n)||(e==="v6"||!e)&&Ve.test(n))}function Je(n,e){if(!Me.test(n))return!1;try{const[t]=n.split(".");if(!t)return!1;const s=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),a=JSON.parse(atob(s));return!(typeof a!="object"||a===null||"typ"in a&&a?.typ!=="JWT"||!a.alg||e&&a.alg!==e)}catch{return!1}}function Ge(n,e){return!!((e==="v4"||!e)&&Ue.test(n)||(e==="v6"||!e)&&Ke.test(n))}class T extends y{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==h.string){const a=this._getOrReturnCtx(e);return c(a,{code:o.invalid_type,expected:h.string,received:a.parsedType}),f}const t=new w;let s;for(const a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(s=this._getOrReturnCtx(e,s),c(s,{code:o.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),t.dirty());else if(a.kind==="max")e.data.length>a.value&&(s=this._getOrReturnCtx(e,s),c(s,{code:o.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),t.dirty());else if(a.kind==="length"){const d=e.data.length>a.value,i=e.data.length<a.value;(d||i)&&(s=this._getOrReturnCtx(e,s),d?c(s,{code:o.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):i&&c(s,{code:o.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),t.dirty())}else if(a.kind==="email")$e.test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"email",code:o.invalid_string,message:a.message}),t.dirty());else if(a.kind==="emoji")pe||(pe=new RegExp(ze,"u")),pe.test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"emoji",code:o.invalid_string,message:a.message}),t.dirty());else if(a.kind==="uuid")Ee.test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"uuid",code:o.invalid_string,message:a.message}),t.dirty());else if(a.kind==="nanoid")Fe.test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"nanoid",code:o.invalid_string,message:a.message}),t.dirty());else if(a.kind==="cuid")je.test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"cuid",code:o.invalid_string,message:a.message}),t.dirty());else if(a.kind==="cuid2")Pe.test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"cuid2",code:o.invalid_string,message:a.message}),t.dirty());else if(a.kind==="ulid")Ie.test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"ulid",code:o.invalid_string,message:a.message}),t.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),c(s,{validation:"url",code:o.invalid_string,message:a.message}),t.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"regex",code:o.invalid_string,message:a.message}),t.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(s=this._getOrReturnCtx(e,s),c(s,{code:o.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),t.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(s=this._getOrReturnCtx(e,s),c(s,{code:o.invalid_string,validation:{startsWith:a.value},message:a.message}),t.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(s=this._getOrReturnCtx(e,s),c(s,{code:o.invalid_string,validation:{endsWith:a.value},message:a.message}),t.dirty()):a.kind==="datetime"?Ze(a).test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{code:o.invalid_string,validation:"datetime",message:a.message}),t.dirty()):a.kind==="date"?Ye.test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{code:o.invalid_string,validation:"date",message:a.message}),t.dirty()):a.kind==="time"?qe(a).test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{code:o.invalid_string,validation:"time",message:a.message}),t.dirty()):a.kind==="duration"?Le.test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"duration",code:o.invalid_string,message:a.message}),t.dirty()):a.kind==="ip"?He(e.data,a.version)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"ip",code:o.invalid_string,message:a.message}),t.dirty()):a.kind==="jwt"?Je(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"jwt",code:o.invalid_string,message:a.message}),t.dirty()):a.kind==="cidr"?Ge(e.data,a.version)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"cidr",code:o.invalid_string,message:a.message}),t.dirty()):a.kind==="base64"?Be.test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"base64",code:o.invalid_string,message:a.message}),t.dirty()):a.kind==="base64url"?We.test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"base64url",code:o.invalid_string,message:a.message}),t.dirty()):k.assertNever(a);return{status:t.value,value:e.data}}_regex(e,t,s){return this.refinement(a=>e.test(a),{validation:t,code:o.invalid_string,...l.errToObj(s)})}_addCheck(e){return new T({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...l.errToObj(e)})}url(e){return this._addCheck({kind:"url",...l.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...l.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...l.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...l.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...l.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...l.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...l.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...l.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...l.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...l.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...l.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...l.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...l.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,...l.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...l.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...l.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...l.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...l.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...l.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...l.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...l.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...l.errToObj(t)})}nonempty(e){return this.min(1,l.errToObj(e))}trim(){return new T({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new T({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new T({...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}}T.create=n=>new T({checks:[],typeName:p.ZodString,coerce:n?.coerce??!1,..._(n)});function Xe(n,e){const t=(n.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,a=t>s?t:s,d=Number.parseInt(n.toFixed(a).replace(".","")),i=Number.parseInt(e.toFixed(a).replace(".",""));return d%i/10**a}class E extends y{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)!==h.number){const a=this._getOrReturnCtx(e);return c(a,{code:o.invalid_type,expected:h.number,received:a.parsedType}),f}let t;const s=new w;for(const a of this._def.checks)a.kind==="int"?k.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),c(t,{code:o.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(t=this._getOrReturnCtx(e,t),c(t,{code:o.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(t=this._getOrReturnCtx(e,t),c(t,{code:o.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?Xe(e.data,a.value)!==0&&(t=this._getOrReturnCtx(e,t),c(t,{code:o.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),c(t,{code:o.not_finite,message:a.message}),s.dirty()):k.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,l.toString(t))}gt(e,t){return this.setLimit("min",e,!1,l.toString(t))}lte(e,t){return this.setLimit("max",e,!0,l.toString(t))}lt(e,t){return this.setLimit("max",e,!1,l.toString(t))}setLimit(e,t,s,a){return new E({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:l.toString(a)}]})}_addCheck(e){return new E({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:l.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:l.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:l.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:l.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:l.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:l.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:l.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:l.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:l.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"&&k.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(t===null||s.value>t)&&(t=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}}E.create=n=>new E({checks:[],typeName:p.ZodNumber,coerce:n?.coerce||!1,..._(n)});class F extends y{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)!==h.bigint)return this._getInvalidInput(e);let t;const s=new w;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(t=this._getOrReturnCtx(e,t),c(t,{code:o.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(t=this._getOrReturnCtx(e,t),c(t,{code:o.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),c(t,{code:o.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):k.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return c(t,{code:o.invalid_type,expected:h.bigint,received:t.parsedType}),f}gte(e,t){return this.setLimit("min",e,!0,l.toString(t))}gt(e,t){return this.setLimit("min",e,!1,l.toString(t))}lte(e,t){return this.setLimit("max",e,!0,l.toString(t))}lt(e,t){return this.setLimit("max",e,!1,l.toString(t))}setLimit(e,t,s,a){return new F({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:l.toString(a)}]})}_addCheck(e){return new F({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:l.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:l.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:l.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:l.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:l.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}}F.create=n=>new F({checks:[],typeName:p.ZodBigInt,coerce:n?.coerce??!1,..._(n)});class Y extends y{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==h.boolean){const t=this._getOrReturnCtx(e);return c(t,{code:o.invalid_type,expected:h.boolean,received:t.parsedType}),f}return x(e.data)}}Y.create=n=>new Y({typeName:p.ZodBoolean,coerce:n?.coerce||!1,..._(n)});class $ extends y{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==h.date){const a=this._getOrReturnCtx(e);return c(a,{code:o.invalid_type,expected:h.date,received:a.parsedType}),f}if(Number.isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return c(a,{code:o.invalid_date}),f}const t=new w;let s;for(const a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),c(s,{code:o.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),t.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),c(s,{code:o.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),t.dirty()):k.assertNever(a);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new $({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:l.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:l.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}}$.create=n=>new $({checks:[],coerce:n?.coerce||!1,typeName:p.ZodDate,..._(n)});class de extends y{_parse(e){if(this._getType(e)!==h.symbol){const t=this._getOrReturnCtx(e);return c(t,{code:o.invalid_type,expected:h.symbol,received:t.parsedType}),f}return x(e.data)}}de.create=n=>new de({typeName:p.ZodSymbol,..._(n)});class q extends y{_parse(e){if(this._getType(e)!==h.undefined){const t=this._getOrReturnCtx(e);return c(t,{code:o.invalid_type,expected:h.undefined,received:t.parsedType}),f}return x(e.data)}}q.create=n=>new q({typeName:p.ZodUndefined,..._(n)});class H extends y{_parse(e){if(this._getType(e)!==h.null){const t=this._getOrReturnCtx(e);return c(t,{code:o.invalid_type,expected:h.null,received:t.parsedType}),f}return x(e.data)}}H.create=n=>new H({typeName:p.ZodNull,..._(n)});class U extends y{constructor(){super(...arguments),this._any=!0}_parse(e){return x(e.data)}}U.create=n=>new U({typeName:p.ZodAny,..._(n)});class L extends y{constructor(){super(...arguments),this._unknown=!0}_parse(e){return x(e.data)}}L.create=n=>new L({typeName:p.ZodUnknown,..._(n)});class N extends y{_parse(e){const t=this._getOrReturnCtx(e);return c(t,{code:o.invalid_type,expected:h.never,received:t.parsedType}),f}}N.create=n=>new N({typeName:p.ZodNever,..._(n)});class oe extends y{_parse(e){if(this._getType(e)!==h.undefined){const t=this._getOrReturnCtx(e);return c(t,{code:o.invalid_type,expected:h.void,received:t.parsedType}),f}return x(e.data)}}oe.create=n=>new oe({typeName:p.ZodVoid,..._(n)});class Z extends y{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),a=this._def;if(t.parsedType!==h.array)return c(t,{code:o.invalid_type,expected:h.array,received:t.parsedType}),f;if(a.exactLength!==null){const i=t.data.length>a.exactLength.value,r=t.data.length<a.exactLength.value;(i||r)&&(c(t,{code:i?o.too_big:o.too_small,minimum:r?a.exactLength.value:void 0,maximum:i?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),s.dirty())}if(a.minLength!==null&&t.data.length<a.minLength.value&&(c(t,{code:o.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),s.dirty()),a.maxLength!==null&&t.data.length>a.maxLength.value&&(c(t,{code:o.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((i,r)=>a.type._parseAsync(new C(t,i,t.path,r)))).then(i=>w.mergeArray(s,i));const d=[...t.data].map((i,r)=>a.type._parseSync(new C(t,i,t.path,r)));return w.mergeArray(s,d)}get element(){return this._def.type}min(e,t){return new Z({...this._def,minLength:{value:e,message:l.toString(t)}})}max(e,t){return new Z({...this._def,maxLength:{value:e,message:l.toString(t)}})}length(e,t){return new Z({...this._def,exactLength:{value:e,message:l.toString(t)}})}nonempty(e){return this.min(1,e)}}Z.create=(n,e)=>new Z({type:n,minLength:null,maxLength:null,exactLength:null,typeName:p.ZodArray,..._(e)});function V(n){if(n instanceof v){const e={};for(const t in n.shape){const s=n.shape[t];e[t]=O.create(V(s))}return new v({...n._def,shape:()=>e})}else return n instanceof Z?new Z({...n._def,type:V(n.element)}):n instanceof O?O.create(V(n.unwrap())):n instanceof I?I.create(V(n.unwrap())):n instanceof A?A.create(n.items.map(e=>V(e))):n}class v extends y{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=k.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==h.object){const u=this._getOrReturnCtx(e);return c(u,{code:o.invalid_type,expected:h.object,received:u.parsedType}),f}const{status:t,ctx:s}=this._processInputParams(e),{shape:a,keys:d}=this._getCached(),i=[];if(!(this._def.catchall instanceof N&&this._def.unknownKeys==="strip"))for(const u in s.data)d.includes(u)||i.push(u);const r=[];for(const u of d){const m=a[u],g=s.data[u];r.push({key:{status:"valid",value:u},value:m._parse(new C(s,g,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof N){const u=this._def.unknownKeys;if(u==="passthrough")for(const m of i)r.push({key:{status:"valid",value:m},value:{status:"valid",value:s.data[m]}});else if(u==="strict")i.length>0&&(c(s,{code:o.unrecognized_keys,keys:i}),t.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const m of i){const g=s.data[m];r.push({key:{status:"valid",value:m},value:u._parse(new C(s,g,s.path,m)),alwaysSet:m in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const u=[];for(const m of r){const g=await m.key,S=await m.value;u.push({key:g,value:S,alwaysSet:m.alwaysSet})}return u}).then(u=>w.mergeObjectSync(t,u)):w.mergeObjectSync(t,r)}get shape(){return this._def.shape()}strict(e){return l.errToObj,new v({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,s)=>{const a=this._def.errorMap?.(t,s).message??s.defaultError;return t.code==="unrecognized_keys"?{message:l.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new v({...this._def,unknownKeys:"strip"})}passthrough(){return new v({...this._def,unknownKeys:"passthrough"})}extend(e){return new v({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new v({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:p.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new v({...this._def,catchall:e})}pick(e){const t={};for(const s of k.objectKeys(e))e[s]&&this.shape[s]&&(t[s]=this.shape[s]);return new v({...this._def,shape:()=>t})}omit(e){const t={};for(const s of k.objectKeys(this.shape))e[s]||(t[s]=this.shape[s]);return new v({...this._def,shape:()=>t})}deepPartial(){return V(this)}partial(e){const t={};for(const s of k.objectKeys(this.shape)){const a=this.shape[s];e&&!e[s]?t[s]=a:t[s]=a.optional()}return new v({...this._def,shape:()=>t})}required(e){const t={};for(const s of k.objectKeys(this.shape))if(e&&!e[s])t[s]=this.shape[s];else{let a=this.shape[s];for(;a instanceof O;)a=a._def.innerType;t[s]=a}return new v({...this._def,shape:()=>t})}keyof(){return Te(k.objectKeys(this.shape))}}v.create=(n,e)=>new v({shape:()=>n,unknownKeys:"strip",catchall:N.create(),typeName:p.ZodObject,..._(e)}),v.strictCreate=(n,e)=>new v({shape:()=>n,unknownKeys:"strict",catchall:N.create(),typeName:p.ZodObject,..._(e)}),v.lazycreate=(n,e)=>new v({shape:n,unknownKeys:"strip",catchall:N.create(),typeName:p.ZodObject,..._(e)});class J extends y{_parse(e){const{ctx:t}=this._processInputParams(e),s=this._def.options;function a(d){for(const r of d)if(r.result.status==="valid")return r.result;for(const r of d)if(r.result.status==="dirty")return t.common.issues.push(...r.ctx.common.issues),r.result;const i=d.map(r=>new R(r.ctx.common.issues));return c(t,{code:o.invalid_union,unionErrors:i}),f}if(t.common.async)return Promise.all(s.map(async d=>{const i={...t,common:{...t.common,issues:[]},parent:null};return{result:await d._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(a);{let d;const i=[];for(const u of s){const m={...t,common:{...t.common,issues:[]},parent:null},g=u._parseSync({data:t.data,path:t.path,parent:m});if(g.status==="valid")return g;g.status==="dirty"&&!d&&(d={result:g,ctx:m}),m.common.issues.length&&i.push(m.common.issues)}if(d)return t.common.issues.push(...d.ctx.common.issues),d.result;const r=i.map(u=>new R(u));return c(t,{code:o.invalid_union,unionErrors:r}),f}}get options(){return this._def.options}}J.create=(n,e)=>new J({options:n,typeName:p.ZodUnion,..._(e)});const P=n=>n instanceof X?P(n.schema):n instanceof b?P(n.innerType()):n instanceof Q?[n.value]:n instanceof M?n.options:n instanceof ee?k.objectValues(n.enum):n instanceof te?P(n._def.innerType):n instanceof q?[void 0]:n instanceof H?[null]:n instanceof O?[void 0,...P(n.unwrap())]:n instanceof I?[null,...P(n.unwrap())]:n instanceof fe||n instanceof ae?P(n.unwrap()):n instanceof se?P(n._def.innerType):[];class le extends y{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.object)return c(t,{code:o.invalid_type,expected:h.object,received:t.parsedType}),f;const s=this.discriminator,a=t.data[s],d=this.optionsMap.get(a);return d?t.common.async?d._parseAsync({data:t.data,path:t.path,parent:t}):d._parseSync({data:t.data,path:t.path,parent:t}):(c(t,{code:o.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),f)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,s){const a=new Map;for(const d of t){const i=P(d.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const r of i){if(a.has(r))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(r)}`);a.set(r,d)}}return new le({typeName:p.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:a,..._(s)})}}function me(n,e){const t=j(n),s=j(e);if(n===e)return{valid:!0,data:n};if(t===h.object&&s===h.object){const a=k.objectKeys(e),d=k.objectKeys(n).filter(r=>a.indexOf(r)!==-1),i={...n,...e};for(const r of d){const u=me(n[r],e[r]);if(!u.valid)return{valid:!1};i[r]=u.data}return{valid:!0,data:i}}else if(t===h.array&&s===h.array){if(n.length!==e.length)return{valid:!1};const a=[];for(let d=0;d<n.length;d++){const i=n[d],r=e[d],u=me(i,r);if(!u.valid)return{valid:!1};a.push(u.data)}return{valid:!0,data:a}}else return t===h.date&&s===h.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class G extends y{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),a=(d,i)=>{if(ge(d)||ge(i))return f;const r=me(d.value,i.value);return r.valid?((ve(d)||ve(i))&&t.dirty(),{status:t.value,value:r.data}):(c(s,{code:o.invalid_intersection_types}),f)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([d,i])=>a(d,i)):a(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}G.create=(n,e,t)=>new G({left:n,right:e,typeName:p.ZodIntersection,..._(t)});class A extends y{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==h.array)return c(s,{code:o.invalid_type,expected:h.array,received:s.parsedType}),f;if(s.data.length<this._def.items.length)return c(s,{code:o.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),f;!this._def.rest&&s.data.length>this._def.items.length&&(c(s,{code:o.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...s.data].map((d,i)=>{const r=this._def.items[i]||this._def.rest;return r?r._parse(new C(s,d,s.path,i)):null}).filter(d=>!!d);return s.common.async?Promise.all(a).then(d=>w.mergeArray(t,d)):w.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new A({...this._def,rest:e})}}A.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new A({items:n,typeName:p.ZodTuple,rest:null,..._(e)})};class re extends y{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==h.object)return c(s,{code:o.invalid_type,expected:h.object,received:s.parsedType}),f;const a=[],d=this._def.keyType,i=this._def.valueType;for(const r in s.data)a.push({key:d._parse(new C(s,r,s.path,r)),value:i._parse(new C(s,s.data[r],s.path,r)),alwaysSet:r in s.data});return s.common.async?w.mergeObjectAsync(t,a):w.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof y?new re({keyType:e,valueType:t,typeName:p.ZodRecord,..._(s)}):new re({keyType:T.create(),valueType:e,typeName:p.ZodRecord,..._(t)})}}class ce extends y{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==h.map)return c(s,{code:o.invalid_type,expected:h.map,received:s.parsedType}),f;const a=this._def.keyType,d=this._def.valueType,i=[...s.data.entries()].map(([r,u],m)=>({key:a._parse(new C(s,r,s.path,[m,"key"])),value:d._parse(new C(s,u,s.path,[m,"value"]))}));if(s.common.async){const r=new Map;return Promise.resolve().then(async()=>{for(const u of i){const m=await u.key,g=await u.value;if(m.status==="aborted"||g.status==="aborted")return f;(m.status==="dirty"||g.status==="dirty")&&t.dirty(),r.set(m.value,g.value)}return{status:t.value,value:r}})}else{const r=new Map;for(const u of i){const m=u.key,g=u.value;if(m.status==="aborted"||g.status==="aborted")return f;(m.status==="dirty"||g.status==="dirty")&&t.dirty(),r.set(m.value,g.value)}return{status:t.value,value:r}}}}ce.create=(n,e,t)=>new ce({valueType:e,keyType:n,typeName:p.ZodMap,..._(t)});class z extends y{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==h.set)return c(s,{code:o.invalid_type,expected:h.set,received:s.parsedType}),f;const a=this._def;a.minSize!==null&&s.data.size<a.minSize.value&&(c(s,{code:o.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),t.dirty()),a.maxSize!==null&&s.data.size>a.maxSize.value&&(c(s,{code:o.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),t.dirty());const d=this._def.valueType;function i(u){const m=new Set;for(const g of u){if(g.status==="aborted")return f;g.status==="dirty"&&t.dirty(),m.add(g.value)}return{status:t.value,value:m}}const r=[...s.data.values()].map((u,m)=>d._parse(new C(s,u,s.path,m)));return s.common.async?Promise.all(r).then(u=>i(u)):i(r)}min(e,t){return new z({...this._def,minSize:{value:e,message:l.toString(t)}})}max(e,t){return new z({...this._def,maxSize:{value:e,message:l.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}z.create=(n,e)=>new z({valueType:n,minSize:null,maxSize:null,typeName:p.ZodSet,..._(e)});class B extends y{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.function)return c(t,{code:o.invalid_type,expected:h.function,received:t.parsedType}),f;function s(r,u){return ke({data:r,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ye(),_e].filter(m=>!!m),issueData:{code:o.invalid_arguments,argumentsError:u}})}function a(r,u){return ke({data:r,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ye(),_e].filter(m=>!!m),issueData:{code:o.invalid_return_type,returnTypeError:u}})}const d={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof K){const r=this;return x(async function(...u){const m=new R([]),g=await r._def.args.parseAsync(u,d).catch(he=>{throw m.addIssue(s(u,he)),m}),S=await Reflect.apply(i,this,g);return await r._def.returns._def.type.parseAsync(S,d).catch(he=>{throw m.addIssue(a(S,he)),m})})}else{const r=this;return x(function(...u){const m=r._def.args.safeParse(u,d);if(!m.success)throw new R([s(u,m.error)]);const g=Reflect.apply(i,this,m.data),S=r._def.returns.safeParse(g,d);if(!S.success)throw new R([a(g,S.error)]);return S.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new B({...this._def,args:A.create(e).rest(L.create())})}returns(e){return new B({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,s){return new B({args:e||A.create([]).rest(L.create()),returns:t||L.create(),typeName:p.ZodFunction,..._(s)})}}class X extends y{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})}}X.create=(n,e)=>new X({getter:n,typeName:p.ZodLazy,..._(e)});class Q extends y{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return c(t,{received:t.data,code:o.invalid_literal,expected:this._def.value}),f}return{status:"valid",value:e.data}}get value(){return this._def.value}}Q.create=(n,e)=>new Q({value:n,typeName:p.ZodLiteral,..._(e)});function Te(n,e){return new M({values:n,typeName:p.ZodEnum,..._(e)})}class M extends y{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),s=this._def.values;return c(t,{expected:k.joinValues(s),received:t.parsedType,code:o.invalid_type}),f}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),s=this._def.values;return c(t,{received:t.data,code:o.invalid_enum_value,options:s}),f}return x(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 M.create(e,{...this._def,...t})}exclude(e,t=this._def){return M.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}}M.create=Te;class ee extends y{_parse(e){const t=k.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==h.string&&s.parsedType!==h.number){const a=k.objectValues(t);return c(s,{expected:k.joinValues(a),received:s.parsedType,code:o.invalid_type}),f}if(this._cache||(this._cache=new Set(k.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const a=k.objectValues(t);return c(s,{received:s.data,code:o.invalid_enum_value,options:a}),f}return x(e.data)}get enum(){return this._def.values}}ee.create=(n,e)=>new ee({values:n,typeName:p.ZodNativeEnum,..._(e)});class K extends y{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.promise&&t.common.async===!1)return c(t,{code:o.invalid_type,expected:h.promise,received:t.parsedType}),f;const s=t.parsedType===h.promise?t.data:Promise.resolve(t.data);return x(s.then(a=>this._def.type.parseAsync(a,{path:t.path,errorMap:t.common.contextualErrorMap})))}}K.create=(n,e)=>new K({type:n,typeName:p.ZodPromise,..._(e)});class b extends y{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===p.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:s}=this._processInputParams(e),a=this._def.effect||null,d={addIssue:i=>{c(s,i),i.fatal?t.abort():t.dirty()},get path(){return s.path}};if(d.addIssue=d.addIssue.bind(d),a.type==="preprocess"){const i=a.transform(s.data,d);if(s.common.async)return Promise.resolve(i).then(async r=>{if(t.value==="aborted")return f;const u=await this._def.schema._parseAsync({data:r,path:s.path,parent:s});return u.status==="aborted"?f:u.status==="dirty"?W(u.value):t.value==="dirty"?W(u.value):u});{if(t.value==="aborted")return f;const r=this._def.schema._parseSync({data:i,path:s.path,parent:s});return r.status==="aborted"?f:r.status==="dirty"?W(r.value):t.value==="dirty"?W(r.value):r}}if(a.type==="refinement"){const i=r=>{const u=a.refinement(r,d);if(s.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return r};if(s.common.async===!1){const r=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return r.status==="aborted"?f:(r.status==="dirty"&&t.dirty(),i(r.value),{status:t.value,value:r.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(r=>r.status==="aborted"?f:(r.status==="dirty"&&t.dirty(),i(r.value).then(()=>({status:t.value,value:r.value}))))}if(a.type==="transform")if(s.common.async===!1){const i=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!D(i))return f;const r=a.transform(i.value,d);if(r instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:r}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(i=>D(i)?Promise.resolve(a.transform(i.value,d)).then(r=>({status:t.value,value:r})):f);k.assertNever(a)}}b.create=(n,e,t)=>new b({schema:n,typeName:p.ZodEffects,effect:e,..._(t)}),b.createWithPreprocess=(n,e,t)=>new b({schema:e,effect:{type:"preprocess",transform:n},typeName:p.ZodEffects,..._(t)});class O extends y{_parse(e){return this._getType(e)===h.undefined?x(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}O.create=(n,e)=>new O({innerType:n,typeName:p.ZodOptional,..._(e)});class I extends y{_parse(e){return this._getType(e)===h.null?x(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}I.create=(n,e)=>new I({innerType:n,typeName:p.ZodNullable,..._(e)});class te extends y{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===h.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}te.create=(n,e)=>new te({innerType:n,typeName:p.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,..._(e)});class se extends y{_parse(e){const{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return ie(a)?a.then(d=>({status:"valid",value:d.status==="valid"?d.value:this._def.catchValue({get error(){return new R(s.common.issues)},input:s.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new R(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}se.create=(n,e)=>new se({innerType:n,typeName:p.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,..._(e)});class ue extends y{_parse(e){if(this._getType(e)!==h.nan){const t=this._getOrReturnCtx(e);return c(t,{code:o.invalid_type,expected:h.nan,received:t.parsedType}),f}return{status:"valid",value:e.data}}}ue.create=n=>new ue({typeName:p.ZodNaN,..._(n)});const Qe=Symbol("zod_brand");class fe extends y{_parse(e){const{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}}class ne extends y{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?f:a.status==="dirty"?(t.dirty(),W(a.value)):this._def.out._parseAsync({data:a.value,path:s.path,parent:s})})();{const a=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?f:a.status==="dirty"?(t.dirty(),{status:"dirty",value:a.value}):this._def.out._parseSync({data:a.value,path:s.path,parent:s})}}static create(e,t){return new ne({in:e,out:t,typeName:p.ZodPipeline})}}class ae extends y{_parse(e){const t=this._def.innerType._parse(e),s=a=>(D(a)&&(a.value=Object.freeze(a.value)),a);return ie(t)?t.then(a=>s(a)):s(t)}unwrap(){return this._def.innerType}}ae.create=(n,e)=>new ae({innerType:n,typeName:p.ZodReadonly,..._(e)});function Ce(n,e){const t=typeof n=="function"?n(e):typeof n=="string"?{message:n}:n;return typeof t=="string"?{message:t}:t}function Oe(n,e={},t){return n?U.create().superRefine((s,a)=>{const d=n(s);if(d instanceof Promise)return d.then(i=>{if(!i){const r=Ce(e,s),u=r.fatal??t??!0;a.addIssue({code:"custom",...r,fatal:u})}});if(!d){const i=Ce(e,s),r=i.fatal??t??!0;a.addIssue({code:"custom",...i,fatal:r})}}):U.create()}const et={object:v.lazycreate};var p;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(p||(p={}));class Ut{constructor(...e){}}const tt=(n,e={message:`Input not instance of ${n.name}`})=>Oe(t=>t instanceof n,e),Ae=T.create,Ne=E.create,st=ue.create,at=F.create,Se=Y.create,nt=$.create,rt=de.create,it=q.create,dt=H.create,ot=U.create,ct=L.create,ut=N.create,lt=oe.create,ht=Z.create,pt=v.create,mt=v.strictCreate,ft=J.create,_t=le.create,yt=G.create,gt=A.create,vt=re.create,kt=ce.create,xt=z.create,wt=B.create,bt=X.create,Zt=Q.create,Tt=M.create,Ct=ee.create,Ot=K.create,Re=b.create,At=O.create,Nt=I.create,St=b.createWithPreprocess,Rt=ne.create,jt=()=>Ae().optional(),Pt=()=>Ne().optional(),It=()=>Se().optional(),Et={string:n=>T.create({...n,coerce:!0}),number:n=>E.create({...n,coerce:!0}),boolean:n=>Y.create({...n,coerce:!0}),bigint:n=>F.create({...n,coerce:!0}),date:n=>$.create({...n,coerce:!0})},Ft=f;export{Qe as BRAND,Ft as NEVER,y as Schema,U as ZodAny,Z as ZodArray,F as ZodBigInt,Y as ZodBoolean,fe as ZodBranded,se as ZodCatch,$ as ZodDate,te as ZodDefault,le as ZodDiscriminatedUnion,b as ZodEffects,M as ZodEnum,p as ZodFirstPartyTypeKind,B as ZodFunction,G as ZodIntersection,X as ZodLazy,Q as ZodLiteral,ce as ZodMap,ue as ZodNaN,ee as ZodNativeEnum,N as ZodNever,H as ZodNull,I as ZodNullable,E as ZodNumber,v as ZodObject,O as ZodOptional,ne as ZodPipeline,K as ZodPromise,ae as ZodReadonly,re as ZodRecord,y as ZodSchema,z as ZodSet,T as ZodString,de as ZodSymbol,b as ZodTransformer,A as ZodTuple,y as ZodType,q as ZodUndefined,J as ZodUnion,L as ZodUnknown,oe as ZodVoid,ot as any,ht as array,at as bigint,Se as boolean,Et as coerce,Oe as custom,nt as date,Ze as datetimeRegex,_t as discriminatedUnion,Re as effect,Tt as enum,wt as function,tt as instanceof,yt as intersection,et as late,bt as lazy,Zt as literal,kt as map,st as nan,Ct as nativeEnum,ut as never,dt as null,Nt as nullable,Ne as number,pt as object,It as oboolean,Pt as onumber,At as optional,jt as ostring,Rt as pipeline,St as preprocess,Ot as promise,vt as record,xt as set,mt as strictObject,Ae as string,rt as symbol,Re as transformer,gt as tuple,it as undefined,ft as union,ct as unknown,lt as void};
1
+ import{ZodError as R,ZodIssueCode as o}from"./ZodError.js";import{defaultErrorMap as _e,getErrorMap as ye}from"./errors.js";import{errorUtil as l}from"./helpers/errorUtil.js";import{DIRTY as W,INVALID as f,OK as x,ParseStatus as w,addIssueToContext as c,isAborted as ge,isAsync as ie,isDirty as ve,isValid as D,makeIssue as ke}from"./helpers/parseUtil.js";import{util as k,ZodParsedType as h,getParsedType as j}from"./helpers/util.js";class C{constructor(e,t,s,a){this._cachedPath=[],this.parent=e,this.data=t,this._path=s,this._key=a}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const xe=(r,e)=>{if(D(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new R(r.common.issues);return this._error=t,this._error}}};function _(r){if(!r)return{};const{errorMap:e,invalid_type_error:t,required_error:s,description:a}=r;if(e&&(t||s))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:a}:{errorMap:(d,i)=>{const{message:n}=r;return d.code==="invalid_enum_value"?{message:n??i.defaultError}:typeof i.data>"u"?{message:n??s??i.defaultError}:d.code!=="invalid_type"?{message:i.defaultError}:{message:n??t??i.defaultError}},description:a}}class y{get description(){return this._def.description}_getType(e){return j(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:j(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new w,ctx:{common:e.parent.common,data:e.data,parsedType:j(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(ie(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 s=this.safeParse(e,t);if(s.success)return s.data;throw s.error}safeParse(e,t){const s={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:j(e)},a=this._parseSync({data:e,path:s.path,parent:s});return xe(s,a)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:j(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:t});return D(s)?{value:s.value}:{issues:t.common.issues}}catch(s){s?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(s=>D(s)?{value:s.value}:{issues:t.common.issues})}async parseAsync(e,t){const s=await this.safeParseAsync(e,t);if(s.success)return s.data;throw s.error}async safeParseAsync(e,t){const s={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:j(e)},a=this._parse({data:e,path:s.path,parent:s}),d=await(ie(a)?a:Promise.resolve(a));return xe(s,d)}refine(e,t){const s=a=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(a):t;return this._refinement((a,d)=>{const i=e(a),n=()=>d.addIssue({code:o.custom,...s(a)});return typeof Promise<"u"&&i instanceof Promise?i.then(u=>u?!0:(n(),!1)):i?!0:(n(),!1)})}refinement(e,t){return this._refinement((s,a)=>e(s)?!0:(a.addIssue(typeof t=="function"?t(s,a):t),!1))}_refinement(e){return new b({schema:this,typeName:p.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 O.create(this,this._def)}nullable(){return I.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Z.create(this)}promise(){return K.create(this,this._def)}or(e){return J.create([this,e],this._def)}and(e){return G.create(this,e,this._def)}transform(e){return new b({..._(this._def),schema:this,typeName:p.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new te({..._(this._def),innerType:this,defaultValue:t,typeName:p.ZodDefault})}brand(){return new fe({typeName:p.ZodBranded,type:this,..._(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new se({..._(this._def),innerType:this,catchValue:t,typeName:p.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return re.create(this,e)}readonly(){return ae.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const je=/^c[^\s-]{8,}$/i,Pe=/^[0-9a-z]+$/,Ie=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ee=/^[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,Fe=/^[a-z0-9_-]{21}$/i,Le=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Me=/^[-+]?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)?)??$/,$e=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ze="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let pe;const De=/^(?:(?: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])$/,Ue=/^(?:(?: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])$/,Ve=/^(([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]))$/,Ke=/^(([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])$/,Be=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,We=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,we="((\\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])))",Ye=new RegExp(`^${we}$`);function be(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);const t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function qe(r){return new RegExp(`^${be(r)}$`)}function Ze(r){let e=`${we}T${be(r)}`;const t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function He(r,e){return!!((e==="v4"||!e)&&De.test(r)||(e==="v6"||!e)&&Ve.test(r))}function Je(r,e){if(!Le.test(r))return!1;try{const[t]=r.split(".");if(!t)return!1;const s=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),a=JSON.parse(atob(s));return!(typeof a!="object"||a===null||"typ"in a&&a?.typ!=="JWT"||!a.alg||e&&a.alg!==e)}catch{return!1}}function Ge(r,e){return!!((e==="v4"||!e)&&Ue.test(r)||(e==="v6"||!e)&&Ke.test(r))}class T extends y{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==h.string){const a=this._getOrReturnCtx(e);return c(a,{code:o.invalid_type,expected:h.string,received:a.parsedType}),f}const t=new w;let s;for(const a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(s=this._getOrReturnCtx(e,s),c(s,{code:o.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),t.dirty());else if(a.kind==="max")e.data.length>a.value&&(s=this._getOrReturnCtx(e,s),c(s,{code:o.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),t.dirty());else if(a.kind==="length"){const d=e.data.length>a.value,i=e.data.length<a.value;(d||i)&&(s=this._getOrReturnCtx(e,s),d?c(s,{code:o.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):i&&c(s,{code:o.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),t.dirty())}else if(a.kind==="email")$e.test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"email",code:o.invalid_string,message:a.message}),t.dirty());else if(a.kind==="emoji")pe||(pe=new RegExp(ze,"u")),pe.test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"emoji",code:o.invalid_string,message:a.message}),t.dirty());else if(a.kind==="uuid")Ee.test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"uuid",code:o.invalid_string,message:a.message}),t.dirty());else if(a.kind==="nanoid")Fe.test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"nanoid",code:o.invalid_string,message:a.message}),t.dirty());else if(a.kind==="cuid")je.test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"cuid",code:o.invalid_string,message:a.message}),t.dirty());else if(a.kind==="cuid2")Pe.test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"cuid2",code:o.invalid_string,message:a.message}),t.dirty());else if(a.kind==="ulid")Ie.test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"ulid",code:o.invalid_string,message:a.message}),t.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),c(s,{validation:"url",code:o.invalid_string,message:a.message}),t.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"regex",code:o.invalid_string,message:a.message}),t.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(s=this._getOrReturnCtx(e,s),c(s,{code:o.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),t.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(s=this._getOrReturnCtx(e,s),c(s,{code:o.invalid_string,validation:{startsWith:a.value},message:a.message}),t.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(s=this._getOrReturnCtx(e,s),c(s,{code:o.invalid_string,validation:{endsWith:a.value},message:a.message}),t.dirty()):a.kind==="datetime"?Ze(a).test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{code:o.invalid_string,validation:"datetime",message:a.message}),t.dirty()):a.kind==="date"?Ye.test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{code:o.invalid_string,validation:"date",message:a.message}),t.dirty()):a.kind==="time"?qe(a).test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{code:o.invalid_string,validation:"time",message:a.message}),t.dirty()):a.kind==="duration"?Me.test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"duration",code:o.invalid_string,message:a.message}),t.dirty()):a.kind==="ip"?He(e.data,a.version)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"ip",code:o.invalid_string,message:a.message}),t.dirty()):a.kind==="jwt"?Je(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"jwt",code:o.invalid_string,message:a.message}),t.dirty()):a.kind==="cidr"?Ge(e.data,a.version)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"cidr",code:o.invalid_string,message:a.message}),t.dirty()):a.kind==="base64"?Be.test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"base64",code:o.invalid_string,message:a.message}),t.dirty()):a.kind==="base64url"?We.test(e.data)||(s=this._getOrReturnCtx(e,s),c(s,{validation:"base64url",code:o.invalid_string,message:a.message}),t.dirty()):k.assertNever(a);return{status:t.value,value:e.data}}_regex(e,t,s){return this.refinement(a=>e.test(a),{validation:t,code:o.invalid_string,...l.errToObj(s)})}_addCheck(e){return new T({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...l.errToObj(e)})}url(e){return this._addCheck({kind:"url",...l.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...l.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...l.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...l.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...l.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...l.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...l.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...l.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...l.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...l.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...l.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...l.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...l.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,...l.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...l.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...l.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...l.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...l.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...l.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...l.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...l.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...l.errToObj(t)})}nonempty(e){return this.min(1,l.errToObj(e))}trim(){return new T({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new T({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new T({...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}}T.create=r=>new T({checks:[],typeName:p.ZodString,coerce:r?.coerce??!1,..._(r)});function Xe(r,e){const t=(r.toString().split(".")[1]||"").length,s=(e.toString().split(".")[1]||"").length,a=t>s?t:s,d=Number.parseInt(r.toFixed(a).replace(".","")),i=Number.parseInt(e.toFixed(a).replace(".",""));return d%i/10**a}class E extends y{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)!==h.number){const a=this._getOrReturnCtx(e);return c(a,{code:o.invalid_type,expected:h.number,received:a.parsedType}),f}let t;const s=new w;for(const a of this._def.checks)a.kind==="int"?k.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),c(t,{code:o.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(t=this._getOrReturnCtx(e,t),c(t,{code:o.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(t=this._getOrReturnCtx(e,t),c(t,{code:o.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?Xe(e.data,a.value)!==0&&(t=this._getOrReturnCtx(e,t),c(t,{code:o.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),c(t,{code:o.not_finite,message:a.message}),s.dirty()):k.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,l.toString(t))}gt(e,t){return this.setLimit("min",e,!1,l.toString(t))}lte(e,t){return this.setLimit("max",e,!0,l.toString(t))}lt(e,t){return this.setLimit("max",e,!1,l.toString(t))}setLimit(e,t,s,a){return new E({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:l.toString(a)}]})}_addCheck(e){return new E({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:l.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:l.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:l.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:l.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:l.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:l.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:l.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:l.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:l.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"&&k.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const s of this._def.checks){if(s.kind==="finite"||s.kind==="int"||s.kind==="multipleOf")return!0;s.kind==="min"?(t===null||s.value>t)&&(t=s.value):s.kind==="max"&&(e===null||s.value<e)&&(e=s.value)}return Number.isFinite(t)&&Number.isFinite(e)}}E.create=r=>new E({checks:[],typeName:p.ZodNumber,coerce:r?.coerce||!1,..._(r)});class F extends y{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)!==h.bigint)return this._getInvalidInput(e);let t;const s=new w;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(t=this._getOrReturnCtx(e,t),c(t,{code:o.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(t=this._getOrReturnCtx(e,t),c(t,{code:o.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),c(t,{code:o.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):k.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return c(t,{code:o.invalid_type,expected:h.bigint,received:t.parsedType}),f}gte(e,t){return this.setLimit("min",e,!0,l.toString(t))}gt(e,t){return this.setLimit("min",e,!1,l.toString(t))}lte(e,t){return this.setLimit("max",e,!0,l.toString(t))}lt(e,t){return this.setLimit("max",e,!1,l.toString(t))}setLimit(e,t,s,a){return new F({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:s,message:l.toString(a)}]})}_addCheck(e){return new F({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:l.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:l.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:l.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:l.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:l.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}}F.create=r=>new F({checks:[],typeName:p.ZodBigInt,coerce:r?.coerce??!1,..._(r)});class Y extends y{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==h.boolean){const t=this._getOrReturnCtx(e);return c(t,{code:o.invalid_type,expected:h.boolean,received:t.parsedType}),f}return x(e.data)}}Y.create=r=>new Y({typeName:p.ZodBoolean,coerce:r?.coerce||!1,..._(r)});class $ extends y{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==h.date){const a=this._getOrReturnCtx(e);return c(a,{code:o.invalid_type,expected:h.date,received:a.parsedType}),f}if(Number.isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return c(a,{code:o.invalid_date}),f}const t=new w;let s;for(const a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),c(s,{code:o.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),t.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),c(s,{code:o.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),t.dirty()):k.assertNever(a);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(e){return new $({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:l.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:l.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}}$.create=r=>new $({checks:[],coerce:r?.coerce||!1,typeName:p.ZodDate,..._(r)});class de extends y{_parse(e){if(this._getType(e)!==h.symbol){const t=this._getOrReturnCtx(e);return c(t,{code:o.invalid_type,expected:h.symbol,received:t.parsedType}),f}return x(e.data)}}de.create=r=>new de({typeName:p.ZodSymbol,..._(r)});class q extends y{_parse(e){if(this._getType(e)!==h.undefined){const t=this._getOrReturnCtx(e);return c(t,{code:o.invalid_type,expected:h.undefined,received:t.parsedType}),f}return x(e.data)}}q.create=r=>new q({typeName:p.ZodUndefined,..._(r)});class H extends y{_parse(e){if(this._getType(e)!==h.null){const t=this._getOrReturnCtx(e);return c(t,{code:o.invalid_type,expected:h.null,received:t.parsedType}),f}return x(e.data)}}H.create=r=>new H({typeName:p.ZodNull,..._(r)});class U extends y{constructor(){super(...arguments),this._any=!0}_parse(e){return x(e.data)}}U.create=r=>new U({typeName:p.ZodAny,..._(r)});class M extends y{constructor(){super(...arguments),this._unknown=!0}_parse(e){return x(e.data)}}M.create=r=>new M({typeName:p.ZodUnknown,..._(r)});class N extends y{_parse(e){const t=this._getOrReturnCtx(e);return c(t,{code:o.invalid_type,expected:h.never,received:t.parsedType}),f}}N.create=r=>new N({typeName:p.ZodNever,..._(r)});class oe extends y{_parse(e){if(this._getType(e)!==h.undefined){const t=this._getOrReturnCtx(e);return c(t,{code:o.invalid_type,expected:h.void,received:t.parsedType}),f}return x(e.data)}}oe.create=r=>new oe({typeName:p.ZodVoid,..._(r)});class Z extends y{_parse(e){const{ctx:t,status:s}=this._processInputParams(e),a=this._def;if(t.parsedType!==h.array)return c(t,{code:o.invalid_type,expected:h.array,received:t.parsedType}),f;if(a.exactLength!==null){const i=t.data.length>a.exactLength.value,n=t.data.length<a.exactLength.value;(i||n)&&(c(t,{code:i?o.too_big:o.too_small,minimum:n?a.exactLength.value:void 0,maximum:i?a.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:a.exactLength.message}),s.dirty())}if(a.minLength!==null&&t.data.length<a.minLength.value&&(c(t,{code:o.too_small,minimum:a.minLength.value,type:"array",inclusive:!0,exact:!1,message:a.minLength.message}),s.dirty()),a.maxLength!==null&&t.data.length>a.maxLength.value&&(c(t,{code:o.too_big,maximum:a.maxLength.value,type:"array",inclusive:!0,exact:!1,message:a.maxLength.message}),s.dirty()),t.common.async)return Promise.all([...t.data].map((i,n)=>a.type._parseAsync(new C(t,i,t.path,n)))).then(i=>w.mergeArray(s,i));const d=[...t.data].map((i,n)=>a.type._parseSync(new C(t,i,t.path,n)));return w.mergeArray(s,d)}get element(){return this._def.type}min(e,t){return new Z({...this._def,minLength:{value:e,message:l.toString(t)}})}max(e,t){return new Z({...this._def,maxLength:{value:e,message:l.toString(t)}})}length(e,t){return new Z({...this._def,exactLength:{value:e,message:l.toString(t)}})}nonempty(e){return this.min(1,e)}}Z.create=(r,e)=>new Z({type:r,minLength:null,maxLength:null,exactLength:null,typeName:p.ZodArray,..._(e)});function V(r){if(r instanceof v){const e={};for(const t in r.shape){const s=r.shape[t];e[t]=O.create(V(s))}return new v({...r._def,shape:()=>e})}else return r instanceof Z?new Z({...r._def,type:V(r.element)}):r instanceof O?O.create(V(r.unwrap())):r instanceof I?I.create(V(r.unwrap())):r instanceof A?A.create(r.items.map(e=>V(e))):r}class v extends y{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=k.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==h.object){const u=this._getOrReturnCtx(e);return c(u,{code:o.invalid_type,expected:h.object,received:u.parsedType}),f}const{status:t,ctx:s}=this._processInputParams(e),{shape:a,keys:d}=this._getCached(),i=[];if(!(this._def.catchall instanceof N&&this._def.unknownKeys==="strip"))for(const u in s.data)d.includes(u)||i.push(u);const n=[];for(const u of d){const m=a[u],g=s.data[u];n.push({key:{status:"valid",value:u},value:m._parse(new C(s,g,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof N){const u=this._def.unknownKeys;if(u==="passthrough")for(const m of i)n.push({key:{status:"valid",value:m},value:{status:"valid",value:s.data[m]}});else if(u==="strict")i.length>0&&(c(s,{code:o.unrecognized_keys,keys:i}),t.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const m of i){const g=s.data[m];n.push({key:{status:"valid",value:m},value:u._parse(new C(s,g,s.path,m)),alwaysSet:m in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const u=[];for(const m of n){const g=await m.key,S=await m.value;u.push({key:g,value:S,alwaysSet:m.alwaysSet})}return u}).then(u=>w.mergeObjectSync(t,u)):w.mergeObjectSync(t,n)}get shape(){return this._def.shape()}strict(e){return l.errToObj,new v({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,s)=>{const a=this._def.errorMap?.(t,s).message??s.defaultError;return t.code==="unrecognized_keys"?{message:l.errToObj(e).message??a}:{message:a}}}:{}})}strip(){return new v({...this._def,unknownKeys:"strip"})}passthrough(){return new v({...this._def,unknownKeys:"passthrough"})}extend(e){return new v({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new v({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:p.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new v({...this._def,catchall:e})}pick(e){const t={};for(const s of k.objectKeys(e))e[s]&&this.shape[s]&&(t[s]=this.shape[s]);return new v({...this._def,shape:()=>t})}omit(e){const t={};for(const s of k.objectKeys(this.shape))e[s]||(t[s]=this.shape[s]);return new v({...this._def,shape:()=>t})}deepPartial(){return V(this)}partial(e){const t={};for(const s of k.objectKeys(this.shape)){const a=this.shape[s];e&&!e[s]?t[s]=a:t[s]=a.optional()}return new v({...this._def,shape:()=>t})}required(e){const t={};for(const s of k.objectKeys(this.shape))if(e&&!e[s])t[s]=this.shape[s];else{let a=this.shape[s];for(;a instanceof O;)a=a._def.innerType;t[s]=a}return new v({...this._def,shape:()=>t})}keyof(){return Te(k.objectKeys(this.shape))}}v.create=(r,e)=>new v({shape:()=>r,unknownKeys:"strip",catchall:N.create(),typeName:p.ZodObject,..._(e)}),v.strictCreate=(r,e)=>new v({shape:()=>r,unknownKeys:"strict",catchall:N.create(),typeName:p.ZodObject,..._(e)}),v.lazycreate=(r,e)=>new v({shape:r,unknownKeys:"strip",catchall:N.create(),typeName:p.ZodObject,..._(e)});class J extends y{_parse(e){const{ctx:t}=this._processInputParams(e),s=this._def.options;function a(d){for(const n of d)if(n.result.status==="valid")return n.result;for(const n of d)if(n.result.status==="dirty")return t.common.issues.push(...n.ctx.common.issues),n.result;const i=d.map(n=>new R(n.ctx.common.issues));return c(t,{code:o.invalid_union,unionErrors:i}),f}if(t.common.async)return Promise.all(s.map(async d=>{const i={...t,common:{...t.common,issues:[]},parent:null};return{result:await d._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(a);{let d;const i=[];for(const u of s){const m={...t,common:{...t.common,issues:[]},parent:null},g=u._parseSync({data:t.data,path:t.path,parent:m});if(g.status==="valid")return g;g.status==="dirty"&&!d&&(d={result:g,ctx:m}),m.common.issues.length&&i.push(m.common.issues)}if(d)return t.common.issues.push(...d.ctx.common.issues),d.result;const n=i.map(u=>new R(u));return c(t,{code:o.invalid_union,unionErrors:n}),f}}get options(){return this._def.options}}J.create=(r,e)=>new J({options:r,typeName:p.ZodUnion,..._(e)});const P=r=>r instanceof X?P(r.schema):r instanceof b?P(r.innerType()):r instanceof Q?[r.value]:r instanceof L?r.options:r instanceof ee?k.objectValues(r.enum):r instanceof te?P(r._def.innerType):r instanceof q?[void 0]:r instanceof H?[null]:r instanceof O?[void 0,...P(r.unwrap())]:r instanceof I?[null,...P(r.unwrap())]:r instanceof fe||r instanceof ae?P(r.unwrap()):r instanceof se?P(r._def.innerType):[];class le extends y{_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.object)return c(t,{code:o.invalid_type,expected:h.object,received:t.parsedType}),f;const s=this.discriminator,a=t.data[s],d=this.optionsMap.get(a);return d?t.common.async?d._parseAsync({data:t.data,path:t.path,parent:t}):d._parseSync({data:t.data,path:t.path,parent:t}):(c(t,{code:o.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[s]}),f)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,s){const a=new Map;for(const d of t){const i=P(d.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const n of i){if(a.has(n))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(n)}`);a.set(n,d)}}return new le({typeName:p.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:a,..._(s)})}}function me(r,e){const t=j(r),s=j(e);if(r===e)return{valid:!0,data:r};if(t===h.object&&s===h.object){const a=k.objectKeys(e),d=k.objectKeys(r).filter(n=>a.indexOf(n)!==-1),i={...r,...e};for(const n of d){const u=me(r[n],e[n]);if(!u.valid)return{valid:!1};i[n]=u.data}return{valid:!0,data:i}}else if(t===h.array&&s===h.array){if(r.length!==e.length)return{valid:!1};const a=[];for(let d=0;d<r.length;d++){const i=r[d],n=e[d],u=me(i,n);if(!u.valid)return{valid:!1};a.push(u.data)}return{valid:!0,data:a}}else return t===h.date&&s===h.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}class G extends y{_parse(e){const{status:t,ctx:s}=this._processInputParams(e),a=(d,i)=>{if(ge(d)||ge(i))return f;const n=me(d.value,i.value);return n.valid?((ve(d)||ve(i))&&t.dirty(),{status:t.value,value:n.data}):(c(s,{code:o.invalid_intersection_types}),f)};return s.common.async?Promise.all([this._def.left._parseAsync({data:s.data,path:s.path,parent:s}),this._def.right._parseAsync({data:s.data,path:s.path,parent:s})]).then(([d,i])=>a(d,i)):a(this._def.left._parseSync({data:s.data,path:s.path,parent:s}),this._def.right._parseSync({data:s.data,path:s.path,parent:s}))}}G.create=(r,e,t)=>new G({left:r,right:e,typeName:p.ZodIntersection,..._(t)});class A extends y{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==h.array)return c(s,{code:o.invalid_type,expected:h.array,received:s.parsedType}),f;if(s.data.length<this._def.items.length)return c(s,{code:o.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),f;!this._def.rest&&s.data.length>this._def.items.length&&(c(s,{code:o.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...s.data].map((d,i)=>{const n=this._def.items[i]||this._def.rest;return n?n._parse(new C(s,d,s.path,i)):null}).filter(d=>!!d);return s.common.async?Promise.all(a).then(d=>w.mergeArray(t,d)):w.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new A({...this._def,rest:e})}}A.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new A({items:r,typeName:p.ZodTuple,rest:null,..._(e)})};class ne extends y{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==h.object)return c(s,{code:o.invalid_type,expected:h.object,received:s.parsedType}),f;const a=[],d=this._def.keyType,i=this._def.valueType;for(const n in s.data)a.push({key:d._parse(new C(s,n,s.path,n)),value:i._parse(new C(s,s.data[n],s.path,n)),alwaysSet:n in s.data});return s.common.async?w.mergeObjectAsync(t,a):w.mergeObjectSync(t,a)}get element(){return this._def.valueType}static create(e,t,s){return t instanceof y?new ne({keyType:e,valueType:t,typeName:p.ZodRecord,..._(s)}):new ne({keyType:T.create(),valueType:e,typeName:p.ZodRecord,..._(t)})}}class ce extends y{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==h.map)return c(s,{code:o.invalid_type,expected:h.map,received:s.parsedType}),f;const a=this._def.keyType,d=this._def.valueType,i=[...s.data.entries()].map(([n,u],m)=>({key:a._parse(new C(s,n,s.path,[m,"key"])),value:d._parse(new C(s,u,s.path,[m,"value"]))}));if(s.common.async){const n=new Map;return Promise.resolve().then(async()=>{for(const u of i){const m=await u.key,g=await u.value;if(m.status==="aborted"||g.status==="aborted")return f;(m.status==="dirty"||g.status==="dirty")&&t.dirty(),n.set(m.value,g.value)}return{status:t.value,value:n}})}else{const n=new Map;for(const u of i){const m=u.key,g=u.value;if(m.status==="aborted"||g.status==="aborted")return f;(m.status==="dirty"||g.status==="dirty")&&t.dirty(),n.set(m.value,g.value)}return{status:t.value,value:n}}}}ce.create=(r,e,t)=>new ce({valueType:e,keyType:r,typeName:p.ZodMap,..._(t)});class z extends y{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.parsedType!==h.set)return c(s,{code:o.invalid_type,expected:h.set,received:s.parsedType}),f;const a=this._def;a.minSize!==null&&s.data.size<a.minSize.value&&(c(s,{code:o.too_small,minimum:a.minSize.value,type:"set",inclusive:!0,exact:!1,message:a.minSize.message}),t.dirty()),a.maxSize!==null&&s.data.size>a.maxSize.value&&(c(s,{code:o.too_big,maximum:a.maxSize.value,type:"set",inclusive:!0,exact:!1,message:a.maxSize.message}),t.dirty());const d=this._def.valueType;function i(u){const m=new Set;for(const g of u){if(g.status==="aborted")return f;g.status==="dirty"&&t.dirty(),m.add(g.value)}return{status:t.value,value:m}}const n=[...s.data.values()].map((u,m)=>d._parse(new C(s,u,s.path,m)));return s.common.async?Promise.all(n).then(u=>i(u)):i(n)}min(e,t){return new z({...this._def,minSize:{value:e,message:l.toString(t)}})}max(e,t){return new z({...this._def,maxSize:{value:e,message:l.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}z.create=(r,e)=>new z({valueType:r,minSize:null,maxSize:null,typeName:p.ZodSet,..._(e)});class B extends y{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.function)return c(t,{code:o.invalid_type,expected:h.function,received:t.parsedType}),f;function s(n,u){return ke({data:n,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ye(),_e].filter(m=>!!m),issueData:{code:o.invalid_arguments,argumentsError:u}})}function a(n,u){return ke({data:n,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,ye(),_e].filter(m=>!!m),issueData:{code:o.invalid_return_type,returnTypeError:u}})}const d={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof K){const n=this;return x(async function(...u){const m=new R([]),g=await n._def.args.parseAsync(u,d).catch(he=>{throw m.addIssue(s(u,he)),m}),S=await Reflect.apply(i,this,g);return await n._def.returns._def.type.parseAsync(S,d).catch(he=>{throw m.addIssue(a(S,he)),m})})}else{const n=this;return x(function(...u){const m=n._def.args.safeParse(u,d);if(!m.success)throw new R([s(u,m.error)]);const g=Reflect.apply(i,this,m.data),S=n._def.returns.safeParse(g,d);if(!S.success)throw new R([a(g,S.error)]);return S.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new B({...this._def,args:A.create(e).rest(M.create())})}returns(e){return new B({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,s){return new B({args:e||A.create([]).rest(M.create()),returns:t||M.create(),typeName:p.ZodFunction,..._(s)})}}class X extends y{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})}}X.create=(r,e)=>new X({getter:r,typeName:p.ZodLazy,..._(e)});class Q extends y{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return c(t,{received:t.data,code:o.invalid_literal,expected:this._def.value}),f}return{status:"valid",value:e.data}}get value(){return this._def.value}}Q.create=(r,e)=>new Q({value:r,typeName:p.ZodLiteral,..._(e)});function Te(r,e){return new L({values:r,typeName:p.ZodEnum,..._(e)})}class L extends y{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),s=this._def.values;return c(t,{expected:k.joinValues(s),received:t.parsedType,code:o.invalid_type}),f}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),s=this._def.values;return c(t,{received:t.data,code:o.invalid_enum_value,options:s}),f}return x(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 L.create(e,{...this._def,...t})}exclude(e,t=this._def){return L.create(this.options.filter(s=>!e.includes(s)),{...this._def,...t})}}L.create=Te;class ee extends y{_parse(e){const t=k.getValidEnumValues(this._def.values),s=this._getOrReturnCtx(e);if(s.parsedType!==h.string&&s.parsedType!==h.number){const a=k.objectValues(t);return c(s,{expected:k.joinValues(a),received:s.parsedType,code:o.invalid_type}),f}if(this._cache||(this._cache=new Set(k.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const a=k.objectValues(t);return c(s,{received:s.data,code:o.invalid_enum_value,options:a}),f}return x(e.data)}get enum(){return this._def.values}}ee.create=(r,e)=>new ee({values:r,typeName:p.ZodNativeEnum,..._(e)});class K extends y{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==h.promise&&t.common.async===!1)return c(t,{code:o.invalid_type,expected:h.promise,received:t.parsedType}),f;const s=t.parsedType===h.promise?t.data:Promise.resolve(t.data);return x(s.then(a=>this._def.type.parseAsync(a,{path:t.path,errorMap:t.common.contextualErrorMap})))}}K.create=(r,e)=>new K({type:r,typeName:p.ZodPromise,..._(e)});class b extends y{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===p.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:s}=this._processInputParams(e),a=this._def.effect||null,d={addIssue:i=>{c(s,i),i.fatal?t.abort():t.dirty()},get path(){return s.path}};if(d.addIssue=d.addIssue.bind(d),a.type==="preprocess"){const i=a.transform(s.data,d);if(s.common.async)return Promise.resolve(i).then(async n=>{if(t.value==="aborted")return f;const u=await this._def.schema._parseAsync({data:n,path:s.path,parent:s});return u.status==="aborted"?f:u.status==="dirty"?W(u.value):t.value==="dirty"?W(u.value):u});{if(t.value==="aborted")return f;const n=this._def.schema._parseSync({data:i,path:s.path,parent:s});return n.status==="aborted"?f:n.status==="dirty"?W(n.value):t.value==="dirty"?W(n.value):n}}if(a.type==="refinement"){const i=n=>{const u=a.refinement(n,d);if(s.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return n};if(s.common.async===!1){const n=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});return n.status==="aborted"?f:(n.status==="dirty"&&t.dirty(),i(n.value),{status:t.value,value:n.value})}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(n=>n.status==="aborted"?f:(n.status==="dirty"&&t.dirty(),i(n.value).then(()=>({status:t.value,value:n.value}))))}if(a.type==="transform")if(s.common.async===!1){const i=this._def.schema._parseSync({data:s.data,path:s.path,parent:s});if(!D(i))return f;const n=a.transform(i.value,d);if(n instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:n}}else return this._def.schema._parseAsync({data:s.data,path:s.path,parent:s}).then(i=>D(i)?Promise.resolve(a.transform(i.value,d)).then(n=>({status:t.value,value:n})):f);k.assertNever(a)}}b.create=(r,e,t)=>new b({schema:r,typeName:p.ZodEffects,effect:e,..._(t)}),b.createWithPreprocess=(r,e,t)=>new b({schema:e,effect:{type:"preprocess",transform:r},typeName:p.ZodEffects,..._(t)});class O extends y{_parse(e){return this._getType(e)===h.undefined?x(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}O.create=(r,e)=>new O({innerType:r,typeName:p.ZodOptional,..._(e)});class I extends y{_parse(e){return this._getType(e)===h.null?x(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}I.create=(r,e)=>new I({innerType:r,typeName:p.ZodNullable,..._(e)});class te extends y{_parse(e){const{ctx:t}=this._processInputParams(e);let s=t.data;return t.parsedType===h.undefined&&(s=this._def.defaultValue()),this._def.innerType._parse({data:s,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}te.create=(r,e)=>new te({innerType:r,typeName:p.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,..._(e)});class se extends y{_parse(e){const{ctx:t}=this._processInputParams(e),s={...t,common:{...t.common,issues:[]}},a=this._def.innerType._parse({data:s.data,path:s.path,parent:{...s}});return ie(a)?a.then(d=>({status:"valid",value:d.status==="valid"?d.value:this._def.catchValue({get error(){return new R(s.common.issues)},input:s.data})})):{status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new R(s.common.issues)},input:s.data})}}removeCatch(){return this._def.innerType}}se.create=(r,e)=>new se({innerType:r,typeName:p.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,..._(e)});class ue extends y{_parse(e){if(this._getType(e)!==h.nan){const t=this._getOrReturnCtx(e);return c(t,{code:o.invalid_type,expected:h.nan,received:t.parsedType}),f}return{status:"valid",value:e.data}}}ue.create=r=>new ue({typeName:p.ZodNaN,..._(r)});const Qe=Symbol("zod_brand");class fe extends y{_parse(e){const{ctx:t}=this._processInputParams(e),s=t.data;return this._def.type._parse({data:s,path:t.path,parent:t})}unwrap(){return this._def.type}}class re extends y{_parse(e){const{status:t,ctx:s}=this._processInputParams(e);if(s.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?f:a.status==="dirty"?(t.dirty(),W(a.value)):this._def.out._parseAsync({data:a.value,path:s.path,parent:s})})();{const a=this._def.in._parseSync({data:s.data,path:s.path,parent:s});return a.status==="aborted"?f:a.status==="dirty"?(t.dirty(),{status:"dirty",value:a.value}):this._def.out._parseSync({data:a.value,path:s.path,parent:s})}}static create(e,t){return new re({in:e,out:t,typeName:p.ZodPipeline})}}class ae extends y{_parse(e){const t=this._def.innerType._parse(e),s=a=>(D(a)&&(a.value=Object.freeze(a.value)),a);return ie(t)?t.then(a=>s(a)):s(t)}unwrap(){return this._def.innerType}}ae.create=(r,e)=>new ae({innerType:r,typeName:p.ZodReadonly,..._(e)});function Ce(r,e){const t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Oe(r,e={},t){return r?U.create().superRefine((s,a)=>{const d=r(s);if(d instanceof Promise)return d.then(i=>{if(!i){const n=Ce(e,s),u=n.fatal??t??!0;a.addIssue({code:"custom",...n,fatal:u})}});if(!d){const i=Ce(e,s),n=i.fatal??t??!0;a.addIssue({code:"custom",...i,fatal:n})}}):U.create()}const et={object:v.lazycreate};var p;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(p||(p={}));class Ut{constructor(...e){}}const tt=(r,e={message:`Input not instance of ${r.name}`})=>Oe(t=>t instanceof r,e),Ae=T.create,Ne=E.create,st=ue.create,at=F.create,Se=Y.create,rt=$.create,nt=de.create,it=q.create,dt=H.create,ot=U.create,ct=M.create,ut=N.create,lt=oe.create,ht=Z.create,pt=v.create,mt=v.strictCreate,ft=J.create,_t=le.create,yt=G.create,gt=A.create,vt=ne.create,kt=ce.create,xt=z.create,wt=B.create,bt=X.create,Zt=Q.create,Tt=L.create,Ct=ee.create,Ot=K.create,Re=b.create,At=O.create,Nt=I.create,St=b.createWithPreprocess,Rt=re.create,jt=()=>Ae().optional(),Pt=()=>Ne().optional(),It=()=>Se().optional(),Et={string:r=>T.create({...r,coerce:!0}),number:r=>E.create({...r,coerce:!0}),boolean:r=>Y.create({...r,coerce:!0}),bigint:r=>F.create({...r,coerce:!0}),date:r=>$.create({...r,coerce:!0})},Ft=f;export{Qe as BRAND,Ft as NEVER,y as Schema,U as ZodAny,Z as ZodArray,F as ZodBigInt,Y as ZodBoolean,fe as ZodBranded,se as ZodCatch,$ as ZodDate,te as ZodDefault,le as ZodDiscriminatedUnion,b as ZodEffects,L as ZodEnum,p as ZodFirstPartyTypeKind,B as ZodFunction,G as ZodIntersection,X as ZodLazy,Q as ZodLiteral,ce as ZodMap,ue as ZodNaN,ee as ZodNativeEnum,N as ZodNever,H as ZodNull,I as ZodNullable,E as ZodNumber,v as ZodObject,O as ZodOptional,re as ZodPipeline,K as ZodPromise,ae as ZodReadonly,ne as ZodRecord,y as ZodSchema,z as ZodSet,T as ZodString,de as ZodSymbol,b as ZodTransformer,A as ZodTuple,y as ZodType,q as ZodUndefined,J as ZodUnion,M as ZodUnknown,oe as ZodVoid,ot as any,ht as array,at as bigint,Se as boolean,Et as coerce,Oe as custom,rt as date,Ze as datetimeRegex,_t as discriminatedUnion,Re as effect,Tt as enum,wt as function,tt as instanceof,yt as intersection,et as late,bt as lazy,Zt as literal,kt as map,st as nan,Ct as nativeEnum,ut as never,dt as null,Nt as nullable,Ne as number,pt as object,It as oboolean,Pt as onumber,At as optional,jt as ostring,Rt as pipeline,St as preprocess,Ot as promise,vt as record,xt as set,mt as strictObject,Ae as string,nt as symbol,Re as transformer,gt as tuple,it as undefined,ft as union,ct as unknown,lt as void};
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var __create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(e,t)=>{for(var r in t)__defProp(e,r,{get:t[r],enumerable:!0})},__copyProps=(e,t,r,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of __getOwnPropNames(t))__hasOwnProp.call(e,i)||i===r||__defProp(e,i,{get:()=>t[i],enumerable:!(o=__getOwnPropDesc(t,i))||o.enumerable});return e},__toESM=(e,t,r)=>(r=null!=e?__create(__getProtoOf(e)):{},__copyProps(!t&&e&&e.__esModule?r:__defProp(r,"default",{value:e,enumerable:!0}),e)),__toCommonJS=e=>__copyProps(__defProp({},"__esModule",{value:!0}),e),src_exports={};__export(src_exports,{DEFAULT_LIMITS:()=>DEFAULT_LIMITS,composeVideo:()=>composeVideo,createPosterHandler:()=>createPosterHandler,createVideoExportHandler:()=>createVideoExportHandler,extractAudio:()=>extractAudio,probeHasAudio:()=>probeHasAudio,probeVideoDuration:()=>probeVideoDuration,runVideoEdit:()=>runVideoEdit,runVideoEditWithCover:()=>runVideoEditWithCover}),module.exports=__toCommonJS(src_exports);var _resolvedPath,import_core=require("../core/dist/index.cjs"),import_core2=require("../core/dist/index.cjs"),import_node_child_process=require("child_process"),import_promises=require("fs/promises"),import_node_fs=require("fs"),import_node_os=require("os"),import_node_path=require("path"),import_meta={};async function resolveFfmpegPath(){const e=[],t=t=>{e.push(t),t.toLowerCase().endsWith(".exe")||e.push(`${t}.exe`)};try{const e=(await import("ffmpeg-static")).default;"string"==typeof e&&t(e)}catch{}try{const{createRequire:e}=await import("module"),r=e(import_meta.url).resolve("ffmpeg-static/package.json"),o=Math.max(r.lastIndexOf("/"),r.lastIndexOf("\\")),i=o>=0?r.substring(0,o):r;t((0,import_node_path.join)(i,"ffmpeg"))}catch{}(()=>{let e=process.cwd();for(;;){t((0,import_node_path.join)(e,"node_modules","ffmpeg-static","ffmpeg")),t((0,import_node_path.join)(e,"node_modules",".pnpm","ffmpeg-static@5.3.0","node_modules","ffmpeg-static","ffmpeg"));const r=(0,import_node_path.dirname)(e);if(r===e)break;e=r}})();for(const t of e)if(t&&!t.startsWith("/ROOT/"))try{return await(0,import_promises.access)(t,import_node_fs.constants.X_OK),t}catch{}return null}async function getFfmpegPath(){return void 0!==_resolvedPath||(_resolvedPath=await resolveFfmpegPath())||console.warn("[ffmpeg-runner] ffmpeg-static 二进制未找到 (尝试了多个 fallback 路径)"),_resolvedPath}async function runFfmpeg({args:e,timeoutMs:t=18e4}){const r=await getFfmpegPath();if(!r)throw new Error("ffmpeg-static 二进制缺失 — 请检查 node_modules/ffmpeg-static/ffmpeg 是否存在");return console.log("[ffmpeg-runner] args:",JSON.stringify(e)),new Promise((o,i)=>{const n=(0,import_node_child_process.spawn)(r,e,{stdio:["ignore","pipe","pipe"]});let s="",a=!1;const p=setTimeout(()=>{a=!0,n.kill("SIGKILL"),i(new Error(`ffmpeg 超时 (${t}ms)`))},t);n.stderr.on("data",e=>{s+=e.toString(),s.length>8192&&(s=s.slice(-8192))}),n.on("close",e=>{if(clearTimeout(p),a)return;const t=s.slice(-2500);console.log(`[ffmpeg-runner] exit=${e}, stderr tail:\n${t}\n---end---`),0===e?o():i(new Error(`ffmpeg 退出码 ${e}: ${t.slice(-800)}`))}),n.on("error",e=>{clearTimeout(p),i(e)})})}async function withTempDir(e){const t=await(0,import_promises.mkdtemp)((0,import_node_path.join)((0,import_node_os.tmpdir)(),"vtrans-"));try{return await e(t)}finally{(0,import_promises.rm)(t,{recursive:!0,force:!0}).catch(()=>{})}}async function probeHasAudio(e){const t=await getFfmpegPath();return!!t&&withTempDir(async r=>{const o=(0,import_node_path.join)(r,"probe.mp4");return await(0,import_promises.writeFile)(o,e),new Promise(e=>{const r=(0,import_node_child_process.spawn)(t,["-hide_banner","-i",o],{stdio:["ignore","ignore","pipe"]});let i="";const n=setTimeout(()=>{r.kill("SIGKILL"),e(!1)},15e3);r.stderr.on("data",e=>{i+=e.toString(),i.length>16384&&(i=i.slice(-16384))}),r.on("close",()=>{clearTimeout(n),e(/Stream #[^\n]*Audio:/.test(i))}),r.on("error",()=>{clearTimeout(n),e(!1)})})})}async function extractAudio(e){return withTempDir(async t=>{const r=(0,import_node_path.join)(t,"in.mp4"),o=(0,import_node_path.join)(t,"audio.mp3");return await(0,import_promises.writeFile)(r,e),await runFfmpeg({args:["-y","-i",r,"-vn","-acodec","libmp3lame","-ar","16000","-ac","1","-b:a","64k",o],timeoutMs:6e4}),(0,import_promises.readFile)(o)})}var SUBTITLE_STYLE=["Fontsize=14","PrimaryColour=&H00FFFFFF","OutlineColour=&H00000000","BackColour=&H80000000","BorderStyle=1","Outline=2","Shadow=0","Alignment=2","MarginV=80","Bold=1"].join(",");async function composeVideo(e){const t=(await probeVideoDuration(e.videoBytes)).durationSeconds;return withTempDir(async r=>{const o=(0,import_node_path.join)(r,"in.mp4"),i=(0,import_node_path.join)(r,"out.mp4");await(0,import_promises.writeFile)(o,e.videoBytes);const n=["-i",o];let s=-1,a=-1;if(e.newAudioBytes){const t=(0,import_node_path.join)(r,"new.mp3");await(0,import_promises.writeFile)(t,e.newAudioBytes),s=(n.length-0)/2,n.push("-i",t)}if(e.bgmAudioBytes){const t=(0,import_node_path.join)(r,"bgm.mp3");await(0,import_promises.writeFile)(t,e.bgmAudioBytes),a=n.length/2,n.push("-i",t)}const p=e.srtContent&&e.srtContent.trim().length>0;let m=null;p&&(m=(0,import_node_path.join)(r,"subs.srt"),await(0,import_promises.writeFile)(m,e.srtContent));const c=e.bgmVolume??.18;console.log(`[ffmpeg-runner] composeVideo: video=${e.videoBytes.length}B (${t.toFixed(2)}s), newAudio=${e.newAudioBytes?.length??0}B, bgm=${e.bgmAudioBytes?.length??0}B@${c}, srt=${e.srtContent?.length??0}chars`);const l=SUBTITLE_STYLE.replace(/,/g,"\\,"),u=[];let d,f=!1;p&&m?(u.push(`[0:v]subtitles=${m}:force_style=${l}[v]`),d="[v]",f=!0):d="0:v:0";const _=[];s>=0&&_.push({idx:s,isBgm:!1}),a>=0&&_.push({idx:a,isBgm:!0});let g=null;if(1===_.length)g=`${_[0].idx}:a:0`;else if(_.length>=2){const e=[];for(const t of _)t.isBgm?(u.push(`[${t.idx}:a]volume=${c}[bgm]`),e.push("[bgm]")):e.push(`[${t.idx}:a]`);u.push(`${e.join("")}amix=inputs=${e.length}:duration=first:dropout_transition=0[a]`),g="[a]"}const h=["-y",...n];u.length>0&&h.push("-filter_complex",u.join(";")),h.push("-map",d),g&&h.push("-map",g),f?h.push("-c:v","libx264","-preset","fast","-crf","22","-pix_fmt","yuv420p"):h.push("-c:v","copy"),h.push("-c:a","aac","-b:a","128k","-ar","44100","-ac","2","-movflags","+faststart","-t",t.toFixed(3)),h.push(i),await runFfmpeg({args:h,timeoutMs:18e4});const y=g?await getFfmpegPath():null;if(y)try{const e=await new Promise(e=>{const t=(0,import_node_child_process.spawn)(y,["-i",i],{stdio:["ignore","pipe","pipe"]});let r="";t.stderr.on("data",e=>r+=e.toString()),t.on("close",()=>e(r))});if(!/Audio:/.test(e))throw console.error("[ffmpeg-runner] 产物缺少音轨,ffmpeg 流概览:\n",e.slice(-2e3)),new Error("合成失败: 输出 mp4 缺少音轨 (检查 filter_complex 语法)");console.log("[ffmpeg-runner] composeVideo 完成,已含音视频双流")}catch(e){if(e instanceof Error&&e.message.includes("合成失败"))throw e}return(0,import_promises.readFile)(i)})}async function probeVideoDuration(e){return withTempDir(async t=>{const r=(0,import_node_path.join)(t,"in.mp4");await(0,import_promises.writeFile)(r,e);const o=await getFfmpegPath();if(!o)throw new Error("ffmpeg-static 二进制缺失");return new Promise((e,t)=>{const i=(0,import_node_child_process.spawn)(o,["-i",r],{stdio:["ignore","pipe","pipe"]});let n="";i.stderr.on("data",e=>n+=e.toString()),i.on("close",()=>{const r=n.match(/Duration:\s*(\d+):(\d+):(\d+(?:\.\d+)?)/);if(!r)return t(new Error("无法解析视频时长"));const o=parseInt(r[1]),i=parseInt(r[2]),s=parseFloat(r[3]);e({durationSeconds:3600*o+60*i+s})}),i.on("error",t)})})}async function runVideoEdit(e,t,r="mp4",o=[],i=24e4){return withTempDir(async n=>{const s=(0,import_node_path.join)(n,"input.mp4"),a=(0,import_node_path.join)(n,`output.${r}`);await(0,import_promises.writeFile)(s,e);const p={};for(const e of o){const t=e.name.replace(/[^a-zA-Z0-9._-]/g,"_"),r=(0,import_node_path.join)(n,t);await(0,import_promises.writeFile)(r,e.bytes),p[e.name]=r}return await runFfmpeg({args:t(s,a,p),timeoutMs:i}),(0,import_promises.readFile)(a)})}function canMuxVideoCover(e){const t=String(e||"").toLowerCase();return"mp4"===t||"mov"===t}function coverFileExtFromBytes(e){return e.length>=8&&137===e[0]&&80===e[1]&&78===e[2]&&71===e[3]&&13===e[4]&&10===e[5]&&26===e[6]&&10===e[7]?"png":"jpg"}function coverConcatArgs(e,t,r){return["-y","-fflags","+genpts","-loop","1","-t","0.04","-i",t,"-i",e,"-filter_complex","[0:v][1:v]scale2ref=w=main_w:h=main_h[vcover][vmainref];[vcover]setsar=1,setpts=PTS-STARTPTS,fps=30,format=yuv420p[vcoverf];[vmainref]setsar=1,setpts=PTS-STARTPTS,fps=30,format=yuv420p[vmain];[vcoverf][vmain]concat=n=2:v=1:a=0[v]","-map","[v]","-map","1:a?","-c:v","libx264","-preset","fast","-crf","18","-pix_fmt","yuv420p","-c:a","aac","-b:a","192k","-ar","44100","-ac","2","-movflags","+faststart",r]}async function runVideoEditWithCover(e,t,r="mp4",o=[],i,n=24e4){return withTempDir(async s=>{const a=(0,import_node_path.join)(s,"input.mp4"),p=(0,import_node_path.join)(s,`output.${r}`),m=(0,import_node_path.join)(s,`output-with-cover.${r}`);await(0,import_promises.writeFile)(a,e);const c={};for(const e of o){const t=e.name.replace(/[^a-zA-Z0-9._-]/g,"_"),r=(0,import_node_path.join)(s,t);await(0,import_promises.writeFile)(r,e.bytes),c[e.name]=r}if(await runFfmpeg({args:t(a,p,c),timeoutMs:n}),!i?.length||!canMuxVideoCover(r))return(0,import_promises.readFile)(p);const l=(0,import_node_path.join)(s,`video-cover.${coverFileExtFromBytes(i)}`);return await(0,import_promises.writeFile)(l,i),await runFfmpeg({args:coverConcatArgs(p,l,m),timeoutMs:n}),(0,import_promises.readFile)(m)})}var MB=1048576,limitLabel=e=>`${Math.round(e/MB)}MB`,DEFAULT_LIMITS={maxVideos:6,maxAudios:3,maxVideoBytes:512*MB,maxTotalVideoBytes:1024*MB,maxAudioBytes:30*MB,maxOverlayBytes:20*MB},err=(e,t,r)=>({ok:!1,status:e,error:t,message:r});function isExportErr(e){return"object"==typeof e&&null!==e&&"ok"in e&&!1===e.ok}var REMOTE_VIDEO_TIMEOUT_MS=12e4;function inferVideoTypeFromUrl(e){const t=(()=>{try{return new URL(e).pathname.toLowerCase()}catch{return e.toLowerCase()}})();return t.endsWith(".mov")?"video/quicktime":t.endsWith(".webm")?"video/webm":t.endsWith(".mkv")?"video/x-matroska":t.endsWith(".mxf")?"application/mxf":t.endsWith(".avi")?"video/x-msvideo":"video/mp4"}function resolveRemoteVideoType(e,t){if(e.type?.startsWith("video/")||"application/mxf"===e.type)return e.type;const r=t?.split(";")[0]?.trim().toLowerCase()??"";return r.startsWith("video/")||"application/mxf"===r||"application/octet-stream"!==r&&r?r:inferVideoTypeFromUrl(e.url)}async function downloadRemoteVideo(e,t){let r;try{r=new URL(e.url)}catch{return err(400,"BAD_REMOTE_URL","videoUrl 不是合法 URL")}if("http:"!==r.protocol&&"https:"!==r.protocol)return err(400,"BAD_REMOTE_URL","videoUrl 只支持 http/https");if(null!=e.size&&e.size>t)return err(413,"TOO_LARGE",`视频超过 ${limitLabel(t)}`);const o=new AbortController,i=setTimeout(()=>o.abort(),REMOTE_VIDEO_TIMEOUT_MS);try{const i=await fetch(r,{signal:o.signal});if(!i.ok)return err(502,"REMOTE_FETCH_FAILED",`远程视频下载失败(${i.status})`);if(Number(i.headers.get("content-length")??0)>t)return err(413,"TOO_LARGE",`视频超过 ${limitLabel(t)}`);const n=[];let s=0;if(i.body){const e=i.body.getReader();for(;;){const{done:r,value:o}=await e.read();if(r)break;if(s+=o.byteLength,s>t)return await e.cancel().catch(()=>{}),err(413,"TOO_LARGE",`视频超过 ${limitLabel(t)}`);n.push(Buffer.from(o))}}else{const e=Buffer.from(await i.arrayBuffer());if(e.length>t)return err(413,"TOO_LARGE",`视频超过 ${limitLabel(t)}`);n.push(e),s=e.length}return s<=0?err(502,"REMOTE_FETCH_FAILED","远程视频为空"):{type:resolveRemoteVideoType(e,i.headers.get("content-type")),bytes:Buffer.concat(n,s)}}catch(e){const t="AbortError"===e.name?"远程视频下载超时":"远程视频下载失败";return err(502,"REMOTE_FETCH_FAILED",t)}finally{clearTimeout(i)}}async function resolveVideoInputs(e,t,r){const o=[],i=Math.max(e.length,t?.length??0);for(let n=0;n<i;n++){const i=e[n];if(i){o[n]=i;continue}const s=t?.[n];if(!s?.url)continue;const a=await downloadRemoteVideo(s,r);if(isExportErr(a))return a;o[n]=a}return o.filter(Boolean)}function audioExt(e){return e.startsWith("video/")?"mp4":e.includes("mpeg")||e.includes("mp3")?"mp3":e.includes("wav")?"wav":e.includes("aac")?"aac":e.includes("ogg")?"ogg":e.includes("mp4")||e.includes("m4a")?"m4a":e.includes("flac")?"flac":"bin"}function exportFormat(e){const t=String(e.exportSettings?.format??"mp4").toLowerCase();return"mov"===t||"mxf"===t?t:"mp4"}function videoContentType(e){return"mov"===e?"video/quicktime":"mxf"===e?"application/mxf":"video/mp4"}function posterPreviewBytes(e){const t=e.poster;if(!t?.useAsVideoCover)return;const r=("string"==typeof t.preview?t.preview:"string"==typeof t.src?t.src:"").match(/^data:image\/(?:png|jpe?g);base64,([a-z0-9+/=]+)$/i);return r?Buffer.from(r[1],"base64"):void 0}function createVideoExportHandler(e){const t={...DEFAULT_LIMITS,...e?.limits};return{async handle(e){const{videos:r,videoUrls:o,audios:i,overlay:n,videoCover:s,textOverlays:a=[],editStateRaw:p}=e,m=await resolveVideoInputs(r,o,t.maxVideoBytes);if(isExportErr(m))return m;const c=m;if(c.length>t.maxVideos)return err(413,"TOO_MANY",`视频数超过 ${t.maxVideos}`);for(let e=0;e<c.length;e++){if(!/^video\//.test(c[e].type))return err(415,"BAD_TYPE",`video_${e} 不是视频文件`);if(c[e].bytes.length>t.maxVideoBytes)return err(413,"TOO_LARGE",`视频 ${e+1} 超过 ${limitLabel(t.maxVideoBytes)}`)}if(!c.length)return err(400,"BAD_REQUEST","缺少视频文件(video_0)");if(c.reduce((e,t)=>e+t.bytes.length,0)>t.maxTotalVideoBytes)return err(413,"TOO_LARGE",`视频总大小超过 ${limitLabel(t.maxTotalVideoBytes)},请减少素材或压缩`);if(i.length>t.maxAudios)return err(413,"TOO_MANY",`音频数超过 ${t.maxAudios}`);for(let e=0;e<i.length;e++){const r=/^audio\//.test(i[e].type),o=/^video\//.test(i[e].type);if(!r&&!o)return err(415,"BAD_TYPE",`audio_${e} 不是音频或视频文件`);if(i[e].bytes.length>(o?t.maxVideoBytes:t.maxAudioBytes))return err(413,"TOO_LARGE",`音频 ${e+1} 超过 ${limitLabel(o?t.maxVideoBytes:t.maxAudioBytes)}`)}if("string"!=typeof p)return err(400,"BAD_REQUEST","缺少 editState");if(n&&n.length>t.maxOverlayBytes)return err(413,"OVERLAY_TOO_LARGE","overlay 过大");if(a.some(e=>e.length>t.maxOverlayBytes))return err(413,"OVERLAY_TOO_LARGE","textOverlay 过大");if(s&&s.length>t.maxOverlayBytes)return err(413,"COVER_TOO_LARGE","videoCover too large");let l;try{l=import_core.VideoEditState.parse(JSON.parse(p))}catch{return err(400,"BAD_STATE","编辑参数不合法")}if(l.clips.some(e=>e.srcIdx>=c.length))return err(400,"BAD_STATE","clips.srcIdx 超出上传视频数");if((l.audioClips??[]).some(e=>e.srcIdx>=i.length))return err(400,"BAD_STATE","audioClips.srcIdx 超出上传音频数");try{const e=c.map(e=>e.bytes),t=i.map(e=>e.bytes),r=new Map,o=e=>{let t=r.get(e);return t||(t=probeHasAudio(e),r.set(e,t)),t},p=[...new Set((l.audioClips??[]).map(e=>e.srcIdx))];for(const e of p)if(/^video\//.test(i[e].type)&&!await o(t[e]))return err(400,"BAD_TYPE",`音频 ${e+1} 是视频文件但没有音轨,无法提取声音`);const m=c.map(()=>!1);if(l.keepAudio){const t=[...new Set(l.clips.map(e=>e.srcIdx))];await Promise.all(t.map(async t=>{m[t]=await o(e[t])})),m.some(Boolean)||(l.audioClips??[]).length||(l={...l,keepAudio:!1})}const u=[];for(let t=1;t<e.length;t++)u.push({name:`video_${t}.mp4`,bytes:e[t]});t.forEach((e,t)=>u.push({name:`audio_${t}.${audioExt(i[t].type)}`,bytes:e})),n&&u.push({name:"overlay.png",bytes:n}),a.forEach((e,t)=>u.push({name:`textOverlay_${t}.png`,bytes:e}));const d=exportFormat(l),f=s?.length?s:posterPreviewBytes(l),_=(r,o,s)=>{const p={videoPaths:[r,...e.slice(1).map((e,t)=>s[`video_${t+1}.mp4`])],videoHasAudio:m,audioPaths:t.map((e,t)=>s[`audio_${t}.${audioExt(i[t].type)}`]),overlayPath:n?s["overlay.png"]:void 0,textOverlayPaths:a.map((e,t)=>s[`textOverlay_${t}.png`]).filter(Boolean),overlayLayerPaths:a.map((e,t)=>s[`textOverlay_${t}.png`]).filter(Boolean)};return(0,import_core2.buildFfmpegArgs)(l,p,o)};return{ok:!0,bytes:f?.length?await runVideoEditWithCover(e[0],_,d,u,f,28e4):await runVideoEdit(e[0],_,d,u,28e4),contentType:videoContentType(d),filename:`edited.${d}`}}catch(e){return(e.message??"").includes("二进制缺失")?err(503,"SERVER_NOT_READY","服务端编码组件未就绪(ffmpeg 缺失),请联系管理员"):err(502,"ENCODE_FAILED","视频处理失败,请重试或换更短的视频")}}}}function createPosterHandler(e){const t=e?.maxBytes??DEFAULT_LIMITS.maxVideoBytes;return{async handle(e,r){if(!/^video\//.test(e.type))return err(415,"BAD_TYPE","只支持视频文件");if(e.bytes.length>t)return err(413,"TOO_LARGE",`文件超过 ${limitLabel(t)}`);if(!isFinite(r)||r<0)return err(400,"BAD_TIME","time 参数不合法");try{return{ok:!0,bytes:await runVideoEdit(e.bytes,(e,t)=>(0,import_core2.buildPosterArgs)(e,r,t),"jpg"),contentType:"image/jpeg",filename:"poster.jpg"}}catch(e){return(e.message??"").includes("二进制缺失")?err(503,"SERVER_NOT_READY","服务端编码组件未就绪(ffmpeg 缺失),请联系管理员"):err(502,"EXTRACT_FAILED","封面抽取失败,请重试")}}}}
1
+ "use strict";var __create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(e,t)=>{for(var r in t)__defProp(e,r,{get:t[r],enumerable:!0})},__copyProps=(e,t,r,o)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let i of __getOwnPropNames(t))__hasOwnProp.call(e,i)||i===r||__defProp(e,i,{get:()=>t[i],enumerable:!(o=__getOwnPropDesc(t,i))||o.enumerable});return e},__toESM=(e,t,r)=>(r=null!=e?__create(__getProtoOf(e)):{},__copyProps(!t&&e&&e.__esModule?r:__defProp(r,"default",{value:e,enumerable:!0}),e)),__toCommonJS=e=>__copyProps(__defProp({},"__esModule",{value:!0}),e),src_exports={};__export(src_exports,{DEFAULT_LIMITS:()=>DEFAULT_LIMITS,composeVideo:()=>composeVideo,createPosterHandler:()=>createPosterHandler,createVideoExportHandler:()=>createVideoExportHandler,extractAudio:()=>extractAudio,probeHasAudio:()=>probeHasAudio,probeVideoDuration:()=>probeVideoDuration,runVideoEdit:()=>runVideoEdit,runVideoEditWithCover:()=>runVideoEditWithCover}),module.exports=__toCommonJS(src_exports);var _resolvedPath,import_core=require("@media-editor/core"),import_core2=require("@media-editor/core"),import_node_child_process=require("child_process"),import_promises=require("fs/promises"),import_node_fs=require("fs"),import_node_os=require("os"),import_node_path=require("path"),import_meta={};async function resolveFfmpegPath(){const e=[],t=t=>{e.push(t),t.toLowerCase().endsWith(".exe")||e.push(`${t}.exe`)};try{const e=(await import("ffmpeg-static")).default;"string"==typeof e&&t(e)}catch{}try{const{createRequire:e}=await import("module"),r=e(import_meta.url).resolve("ffmpeg-static/package.json"),o=Math.max(r.lastIndexOf("/"),r.lastIndexOf("\\")),i=o>=0?r.substring(0,o):r;t((0,import_node_path.join)(i,"ffmpeg"))}catch{}(()=>{let e=process.cwd();for(;;){t((0,import_node_path.join)(e,"node_modules","ffmpeg-static","ffmpeg")),t((0,import_node_path.join)(e,"node_modules",".pnpm","ffmpeg-static@5.3.0","node_modules","ffmpeg-static","ffmpeg"));const r=(0,import_node_path.dirname)(e);if(r===e)break;e=r}})();for(const t of e)if(t&&!t.startsWith("/ROOT/"))try{return await(0,import_promises.access)(t,import_node_fs.constants.X_OK),t}catch{}return null}async function getFfmpegPath(){return void 0!==_resolvedPath||(_resolvedPath=await resolveFfmpegPath())||console.warn("[ffmpeg-runner] ffmpeg-static 二进制未找到 (尝试了多个 fallback 路径)"),_resolvedPath}async function runFfmpeg({args:e,timeoutMs:t=18e4}){const r=await getFfmpegPath();if(!r)throw new Error("ffmpeg-static 二进制缺失 — 请检查 node_modules/ffmpeg-static/ffmpeg 是否存在");return console.log("[ffmpeg-runner] args:",JSON.stringify(e)),new Promise((o,i)=>{const n=(0,import_node_child_process.spawn)(r,e,{stdio:["ignore","pipe","pipe"]});let s="",a=!1;const p=setTimeout(()=>{a=!0,n.kill("SIGKILL"),i(new Error(`ffmpeg 超时 (${t}ms)`))},t);n.stderr.on("data",e=>{s+=e.toString(),s.length>8192&&(s=s.slice(-8192))}),n.on("close",e=>{if(clearTimeout(p),a)return;const t=s.slice(-2500);console.log(`[ffmpeg-runner] exit=${e}, stderr tail:\n${t}\n---end---`),0===e?o():i(new Error(`ffmpeg 退出码 ${e}: ${t.slice(-800)}`))}),n.on("error",e=>{clearTimeout(p),i(e)})})}async function withTempDir(e){const t=await(0,import_promises.mkdtemp)((0,import_node_path.join)((0,import_node_os.tmpdir)(),"vtrans-"));try{return await e(t)}finally{(0,import_promises.rm)(t,{recursive:!0,force:!0}).catch(()=>{})}}async function probeHasAudio(e){const t=await getFfmpegPath();return!!t&&withTempDir(async r=>{const o=(0,import_node_path.join)(r,"probe.mp4");return await(0,import_promises.writeFile)(o,e),new Promise(e=>{const r=(0,import_node_child_process.spawn)(t,["-hide_banner","-i",o],{stdio:["ignore","ignore","pipe"]});let i="";const n=setTimeout(()=>{r.kill("SIGKILL"),e(!1)},15e3);r.stderr.on("data",e=>{i+=e.toString(),i.length>16384&&(i=i.slice(-16384))}),r.on("close",()=>{clearTimeout(n),e(/Stream #[^\n]*Audio:/.test(i))}),r.on("error",()=>{clearTimeout(n),e(!1)})})})}async function extractAudio(e){return withTempDir(async t=>{const r=(0,import_node_path.join)(t,"in.mp4"),o=(0,import_node_path.join)(t,"audio.mp3");return await(0,import_promises.writeFile)(r,e),await runFfmpeg({args:["-y","-i",r,"-vn","-acodec","libmp3lame","-ar","16000","-ac","1","-b:a","64k",o],timeoutMs:6e4}),(0,import_promises.readFile)(o)})}var SUBTITLE_STYLE=["Fontsize=14","PrimaryColour=&H00FFFFFF","OutlineColour=&H00000000","BackColour=&H80000000","BorderStyle=1","Outline=2","Shadow=0","Alignment=2","MarginV=80","Bold=1"].join(",");async function composeVideo(e){const t=(await probeVideoDuration(e.videoBytes)).durationSeconds;return withTempDir(async r=>{const o=(0,import_node_path.join)(r,"in.mp4"),i=(0,import_node_path.join)(r,"out.mp4");await(0,import_promises.writeFile)(o,e.videoBytes);const n=["-i",o];let s=-1,a=-1;if(e.newAudioBytes){const t=(0,import_node_path.join)(r,"new.mp3");await(0,import_promises.writeFile)(t,e.newAudioBytes),s=(n.length-0)/2,n.push("-i",t)}if(e.bgmAudioBytes){const t=(0,import_node_path.join)(r,"bgm.mp3");await(0,import_promises.writeFile)(t,e.bgmAudioBytes),a=n.length/2,n.push("-i",t)}const p=e.srtContent&&e.srtContent.trim().length>0;let m=null;p&&(m=(0,import_node_path.join)(r,"subs.srt"),await(0,import_promises.writeFile)(m,e.srtContent));const c=e.bgmVolume??.18;console.log(`[ffmpeg-runner] composeVideo: video=${e.videoBytes.length}B (${t.toFixed(2)}s), newAudio=${e.newAudioBytes?.length??0}B, bgm=${e.bgmAudioBytes?.length??0}B@${c}, srt=${e.srtContent?.length??0}chars`);const l=SUBTITLE_STYLE.replace(/,/g,"\\,"),u=[];let d,f=!1;p&&m?(u.push(`[0:v]subtitles=${m}:force_style=${l}[v]`),d="[v]",f=!0):d="0:v:0";const _=[];s>=0&&_.push({idx:s,isBgm:!1}),a>=0&&_.push({idx:a,isBgm:!0});let g=null;if(1===_.length)g=`${_[0].idx}:a:0`;else if(_.length>=2){const e=[];for(const t of _)t.isBgm?(u.push(`[${t.idx}:a]volume=${c}[bgm]`),e.push("[bgm]")):e.push(`[${t.idx}:a]`);u.push(`${e.join("")}amix=inputs=${e.length}:duration=first:dropout_transition=0[a]`),g="[a]"}const h=["-y",...n];u.length>0&&h.push("-filter_complex",u.join(";")),h.push("-map",d),g&&h.push("-map",g),f?h.push("-c:v","libx264","-preset","fast","-crf","22","-pix_fmt","yuv420p"):h.push("-c:v","copy"),h.push("-c:a","aac","-b:a","128k","-ar","44100","-ac","2","-movflags","+faststart","-t",t.toFixed(3)),h.push(i),await runFfmpeg({args:h,timeoutMs:18e4});const y=g?await getFfmpegPath():null;if(y)try{const e=await new Promise(e=>{const t=(0,import_node_child_process.spawn)(y,["-i",i],{stdio:["ignore","pipe","pipe"]});let r="";t.stderr.on("data",e=>r+=e.toString()),t.on("close",()=>e(r))});if(!/Audio:/.test(e))throw console.error("[ffmpeg-runner] 产物缺少音轨,ffmpeg 流概览:\n",e.slice(-2e3)),new Error("合成失败: 输出 mp4 缺少音轨 (检查 filter_complex 语法)");console.log("[ffmpeg-runner] composeVideo 完成,已含音视频双流")}catch(e){if(e instanceof Error&&e.message.includes("合成失败"))throw e}return(0,import_promises.readFile)(i)})}async function probeVideoDuration(e){return withTempDir(async t=>{const r=(0,import_node_path.join)(t,"in.mp4");await(0,import_promises.writeFile)(r,e);const o=await getFfmpegPath();if(!o)throw new Error("ffmpeg-static 二进制缺失");return new Promise((e,t)=>{const i=(0,import_node_child_process.spawn)(o,["-i",r],{stdio:["ignore","pipe","pipe"]});let n="";i.stderr.on("data",e=>n+=e.toString()),i.on("close",()=>{const r=n.match(/Duration:\s*(\d+):(\d+):(\d+(?:\.\d+)?)/);if(!r)return t(new Error("无法解析视频时长"));const o=parseInt(r[1]),i=parseInt(r[2]),s=parseFloat(r[3]);e({durationSeconds:3600*o+60*i+s})}),i.on("error",t)})})}async function runVideoEdit(e,t,r="mp4",o=[],i=24e4){return withTempDir(async n=>{const s=(0,import_node_path.join)(n,"input.mp4"),a=(0,import_node_path.join)(n,`output.${r}`);await(0,import_promises.writeFile)(s,e);const p={};for(const e of o){const t=e.name.replace(/[^a-zA-Z0-9._-]/g,"_"),r=(0,import_node_path.join)(n,t);await(0,import_promises.writeFile)(r,e.bytes),p[e.name]=r}return await runFfmpeg({args:t(s,a,p),timeoutMs:i}),(0,import_promises.readFile)(a)})}function canMuxVideoCover(e){const t=String(e||"").toLowerCase();return"mp4"===t||"mov"===t}function coverFileExtFromBytes(e){return e.length>=8&&137===e[0]&&80===e[1]&&78===e[2]&&71===e[3]&&13===e[4]&&10===e[5]&&26===e[6]&&10===e[7]?"png":"jpg"}function coverConcatArgs(e,t,r){return["-y","-fflags","+genpts","-loop","1","-t","0.04","-i",t,"-i",e,"-filter_complex","[0:v][1:v]scale2ref=w=main_w:h=main_h[vcover][vmainref];[vcover]setsar=1,setpts=PTS-STARTPTS,fps=30,format=yuv420p[vcoverf];[vmainref]setsar=1,setpts=PTS-STARTPTS,fps=30,format=yuv420p[vmain];[vcoverf][vmain]concat=n=2:v=1:a=0[v]","-map","[v]","-map","1:a?","-c:v","libx264","-preset","fast","-crf","18","-pix_fmt","yuv420p","-c:a","aac","-b:a","192k","-ar","44100","-ac","2","-movflags","+faststart",r]}async function runVideoEditWithCover(e,t,r="mp4",o=[],i,n=24e4){return withTempDir(async s=>{const a=(0,import_node_path.join)(s,"input.mp4"),p=(0,import_node_path.join)(s,`output.${r}`),m=(0,import_node_path.join)(s,`output-with-cover.${r}`);await(0,import_promises.writeFile)(a,e);const c={};for(const e of o){const t=e.name.replace(/[^a-zA-Z0-9._-]/g,"_"),r=(0,import_node_path.join)(s,t);await(0,import_promises.writeFile)(r,e.bytes),c[e.name]=r}if(await runFfmpeg({args:t(a,p,c),timeoutMs:n}),!i?.length||!canMuxVideoCover(r))return(0,import_promises.readFile)(p);const l=(0,import_node_path.join)(s,`video-cover.${coverFileExtFromBytes(i)}`);return await(0,import_promises.writeFile)(l,i),await runFfmpeg({args:coverConcatArgs(p,l,m),timeoutMs:n}),(0,import_promises.readFile)(m)})}var MB=1048576,limitLabel=e=>`${Math.round(e/MB)}MB`,DEFAULT_LIMITS={maxVideos:6,maxAudios:3,maxVideoBytes:512*MB,maxTotalVideoBytes:1024*MB,maxAudioBytes:30*MB,maxOverlayBytes:20*MB},err=(e,t,r)=>({ok:!1,status:e,error:t,message:r});function isExportErr(e){return"object"==typeof e&&null!==e&&"ok"in e&&!1===e.ok}var REMOTE_VIDEO_TIMEOUT_MS=12e4;function inferVideoTypeFromUrl(e){const t=(()=>{try{return new URL(e).pathname.toLowerCase()}catch{return e.toLowerCase()}})();return t.endsWith(".mov")?"video/quicktime":t.endsWith(".webm")?"video/webm":t.endsWith(".mkv")?"video/x-matroska":t.endsWith(".mxf")?"application/mxf":t.endsWith(".avi")?"video/x-msvideo":"video/mp4"}function resolveRemoteVideoType(e,t){if(e.type?.startsWith("video/")||"application/mxf"===e.type)return e.type;const r=t?.split(";")[0]?.trim().toLowerCase()??"";return r.startsWith("video/")||"application/mxf"===r||"application/octet-stream"!==r&&r?r:inferVideoTypeFromUrl(e.url)}async function downloadRemoteVideo(e,t){let r;try{r=new URL(e.url)}catch{return err(400,"BAD_REMOTE_URL","videoUrl 不是合法 URL")}if("http:"!==r.protocol&&"https:"!==r.protocol)return err(400,"BAD_REMOTE_URL","videoUrl 只支持 http/https");if(null!=e.size&&e.size>t)return err(413,"TOO_LARGE",`视频超过 ${limitLabel(t)}`);const o=new AbortController,i=setTimeout(()=>o.abort(),REMOTE_VIDEO_TIMEOUT_MS);try{const i=await fetch(r,{signal:o.signal});if(!i.ok)return err(502,"REMOTE_FETCH_FAILED",`远程视频下载失败(${i.status})`);if(Number(i.headers.get("content-length")??0)>t)return err(413,"TOO_LARGE",`视频超过 ${limitLabel(t)}`);const n=[];let s=0;if(i.body){const e=i.body.getReader();for(;;){const{done:r,value:o}=await e.read();if(r)break;if(s+=o.byteLength,s>t)return await e.cancel().catch(()=>{}),err(413,"TOO_LARGE",`视频超过 ${limitLabel(t)}`);n.push(Buffer.from(o))}}else{const e=Buffer.from(await i.arrayBuffer());if(e.length>t)return err(413,"TOO_LARGE",`视频超过 ${limitLabel(t)}`);n.push(e),s=e.length}return s<=0?err(502,"REMOTE_FETCH_FAILED","远程视频为空"):{type:resolveRemoteVideoType(e,i.headers.get("content-type")),bytes:Buffer.concat(n,s)}}catch(e){const t="AbortError"===e.name?"远程视频下载超时":"远程视频下载失败";return err(502,"REMOTE_FETCH_FAILED",t)}finally{clearTimeout(i)}}async function resolveVideoInputs(e,t,r){const o=[],i=Math.max(e.length,t?.length??0);for(let n=0;n<i;n++){const i=e[n];if(i){o[n]=i;continue}const s=t?.[n];if(!s?.url)continue;const a=await downloadRemoteVideo(s,r);if(isExportErr(a))return a;o[n]=a}return o.filter(Boolean)}function audioExt(e){return e.startsWith("video/")?"mp4":e.includes("mpeg")||e.includes("mp3")?"mp3":e.includes("wav")?"wav":e.includes("aac")?"aac":e.includes("ogg")?"ogg":e.includes("mp4")||e.includes("m4a")?"m4a":e.includes("flac")?"flac":"bin"}function exportFormat(e){const t=String(e.exportSettings?.format??"mp4").toLowerCase();return"mov"===t||"mxf"===t?t:"mp4"}function videoContentType(e){return"mov"===e?"video/quicktime":"mxf"===e?"application/mxf":"video/mp4"}function posterPreviewBytes(e){const t=e.poster;if(!t?.useAsVideoCover)return;const r=("string"==typeof t.preview?t.preview:"string"==typeof t.src?t.src:"").match(/^data:image\/(?:png|jpe?g);base64,([a-z0-9+/=]+)$/i);return r?Buffer.from(r[1],"base64"):void 0}function createVideoExportHandler(e){const t={...DEFAULT_LIMITS,...e?.limits};return{async handle(e){const{videos:r,videoUrls:o,audios:i,overlay:n,videoCover:s,textOverlays:a=[],editStateRaw:p}=e,m=await resolveVideoInputs(r,o,t.maxVideoBytes);if(isExportErr(m))return m;const c=m;if(c.length>t.maxVideos)return err(413,"TOO_MANY",`视频数超过 ${t.maxVideos}`);for(let e=0;e<c.length;e++){if(!/^video\//.test(c[e].type))return err(415,"BAD_TYPE",`video_${e} 不是视频文件`);if(c[e].bytes.length>t.maxVideoBytes)return err(413,"TOO_LARGE",`视频 ${e+1} 超过 ${limitLabel(t.maxVideoBytes)}`)}if(!c.length)return err(400,"BAD_REQUEST","缺少视频文件(video_0)");if(c.reduce((e,t)=>e+t.bytes.length,0)>t.maxTotalVideoBytes)return err(413,"TOO_LARGE",`视频总大小超过 ${limitLabel(t.maxTotalVideoBytes)},请减少素材或压缩`);if(i.length>t.maxAudios)return err(413,"TOO_MANY",`音频数超过 ${t.maxAudios}`);for(let e=0;e<i.length;e++){const r=/^audio\//.test(i[e].type),o=/^video\//.test(i[e].type);if(!r&&!o)return err(415,"BAD_TYPE",`audio_${e} 不是音频或视频文件`);if(i[e].bytes.length>(o?t.maxVideoBytes:t.maxAudioBytes))return err(413,"TOO_LARGE",`音频 ${e+1} 超过 ${limitLabel(o?t.maxVideoBytes:t.maxAudioBytes)}`)}if("string"!=typeof p)return err(400,"BAD_REQUEST","缺少 editState");if(n&&n.length>t.maxOverlayBytes)return err(413,"OVERLAY_TOO_LARGE","overlay 过大");if(a.some(e=>e.length>t.maxOverlayBytes))return err(413,"OVERLAY_TOO_LARGE","textOverlay 过大");if(s&&s.length>t.maxOverlayBytes)return err(413,"COVER_TOO_LARGE","videoCover too large");let l;try{l=import_core.VideoEditState.parse(JSON.parse(p))}catch{return err(400,"BAD_STATE","编辑参数不合法")}if(l.clips.some(e=>e.srcIdx>=c.length))return err(400,"BAD_STATE","clips.srcIdx 超出上传视频数");if((l.audioClips??[]).some(e=>e.srcIdx>=i.length))return err(400,"BAD_STATE","audioClips.srcIdx 超出上传音频数");try{const e=c.map(e=>e.bytes),t=i.map(e=>e.bytes),r=new Map,o=e=>{let t=r.get(e);return t||(t=probeHasAudio(e),r.set(e,t)),t},p=[...new Set((l.audioClips??[]).map(e=>e.srcIdx))];for(const e of p)if(/^video\//.test(i[e].type)&&!await o(t[e]))return err(400,"BAD_TYPE",`音频 ${e+1} 是视频文件但没有音轨,无法提取声音`);const m=c.map(()=>!1);if(l.keepAudio){const t=[...new Set(l.clips.map(e=>e.srcIdx))];await Promise.all(t.map(async t=>{m[t]=await o(e[t])})),m.some(Boolean)||(l.audioClips??[]).length||(l={...l,keepAudio:!1})}const u=[];for(let t=1;t<e.length;t++)u.push({name:`video_${t}.mp4`,bytes:e[t]});t.forEach((e,t)=>u.push({name:`audio_${t}.${audioExt(i[t].type)}`,bytes:e})),n&&u.push({name:"overlay.png",bytes:n}),a.forEach((e,t)=>u.push({name:`textOverlay_${t}.png`,bytes:e}));const d=exportFormat(l),f=s?.length?s:posterPreviewBytes(l),_=(r,o,s)=>{const p={videoPaths:[r,...e.slice(1).map((e,t)=>s[`video_${t+1}.mp4`])],videoHasAudio:m,audioPaths:t.map((e,t)=>s[`audio_${t}.${audioExt(i[t].type)}`]),overlayPath:n?s["overlay.png"]:void 0,textOverlayPaths:a.map((e,t)=>s[`textOverlay_${t}.png`]).filter(Boolean),overlayLayerPaths:a.map((e,t)=>s[`textOverlay_${t}.png`]).filter(Boolean)};return(0,import_core2.buildFfmpegArgs)(l,p,o)};return{ok:!0,bytes:f?.length?await runVideoEditWithCover(e[0],_,d,u,f,28e4):await runVideoEdit(e[0],_,d,u,28e4),contentType:videoContentType(d),filename:`edited.${d}`}}catch(e){return(e.message??"").includes("二进制缺失")?err(503,"SERVER_NOT_READY","服务端编码组件未就绪(ffmpeg 缺失),请联系管理员"):err(502,"ENCODE_FAILED","视频处理失败,请重试或换更短的视频")}}}}function createPosterHandler(e){const t=e?.maxBytes??DEFAULT_LIMITS.maxVideoBytes;return{async handle(e,r){if(!/^video\//.test(e.type))return err(415,"BAD_TYPE","只支持视频文件");if(e.bytes.length>t)return err(413,"TOO_LARGE",`文件超过 ${limitLabel(t)}`);if(!isFinite(r)||r<0)return err(400,"BAD_TIME","time 参数不合法");try{return{ok:!0,bytes:await runVideoEdit(e.bytes,(e,t)=>(0,import_core2.buildPosterArgs)(e,r,t),"jpg"),contentType:"image/jpeg",filename:"poster.jpg"}}catch(e){return(e.message??"").includes("二进制缺失")?err(503,"SERVER_NOT_READY","服务端编码组件未就绪(ffmpeg 缺失),请联系管理员"):err(502,"EXTRACT_FAILED","封面抽取失败,请重试")}}}}
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{VideoEditState as t}from"../core/dist/index.js";import{buildFfmpegArgs as e,buildPosterArgs as o}from"../core/dist/index.js";import{spawn as n}from"child_process";import{writeFile as r,readFile as s,mkdtemp as i,rm as a,access as c}from"fs/promises";import{constants as u}from"fs";import{tmpdir as m}from"os";import{dirname as l,join as p}from"path";var f;async function d(){return void 0!==f||(f=await async function(){const t=[],e=e=>{t.push(e),e.toLowerCase().endsWith(".exe")||t.push(`${e}.exe`)};try{const t=(await import("ffmpeg-static")).default;"string"==typeof t&&e(t)}catch{}try{const{createRequire:t}=await import("module"),o=t(import.meta.url).resolve("ffmpeg-static/package.json"),n=Math.max(o.lastIndexOf("/"),o.lastIndexOf("\\")),r=n>=0?o.substring(0,n):o;e(p(r,"ffmpeg"))}catch{}(()=>{let t=process.cwd();for(;;){e(p(t,"node_modules","ffmpeg-static","ffmpeg")),e(p(t,"node_modules",".pnpm","ffmpeg-static@5.3.0","node_modules","ffmpeg-static","ffmpeg"));const o=l(t);if(o===t)break;t=o}})();for(const e of t)if(e&&!e.startsWith("/ROOT/"))try{return await c(e,u.X_OK),e}catch{}return null}())||console.warn("[ffmpeg-runner] ffmpeg-static 二进制未找到 (尝试了多个 fallback 路径)"),f}async function g({args:t,timeoutMs:e=18e4}){const o=await d();if(!o)throw new Error("ffmpeg-static 二进制缺失 — 请检查 node_modules/ffmpeg-static/ffmpeg 是否存在");return console.log("[ffmpeg-runner] args:",JSON.stringify(t)),new Promise((r,s)=>{const i=n(o,t,{stdio:["ignore","pipe","pipe"]});let a="",c=!1;const u=setTimeout(()=>{c=!0,i.kill("SIGKILL"),s(new Error(`ffmpeg 超时 (${e}ms)`))},e);i.stderr.on("data",t=>{a+=t.toString(),a.length>8192&&(a=a.slice(-8192))}),i.on("close",t=>{if(clearTimeout(u),c)return;const e=a.slice(-2500);console.log(`[ffmpeg-runner] exit=${t}, stderr tail:\n${e}\n---end---`),0===t?r():s(new Error(`ffmpeg 退出码 ${t}: ${e.slice(-800)}`))}),i.on("error",t=>{clearTimeout(u),s(t)})})}async function y(t){const e=await i(p(m(),"vtrans-"));try{return await t(e)}finally{a(e,{recursive:!0,force:!0}).catch(()=>{})}}async function h(t){const e=await d();return!!e&&y(async o=>{const s=p(o,"probe.mp4");return await r(s,t),new Promise(t=>{const o=n(e,["-hide_banner","-i",s],{stdio:["ignore","ignore","pipe"]});let r="";const i=setTimeout(()=>{o.kill("SIGKILL"),t(!1)},15e3);o.stderr.on("data",t=>{r+=t.toString(),r.length>16384&&(r=r.slice(-16384))}),o.on("close",()=>{clearTimeout(i),t(/Stream #[^\n]*Audio:/.test(r))}),o.on("error",()=>{clearTimeout(i),t(!1)})})})}async function v(t){return y(async e=>{const o=p(e,"in.mp4"),n=p(e,"audio.mp3");return await r(o,t),await g({args:["-y","-i",o,"-vn","-acodec","libmp3lame","-ar","16000","-ac","1","-b:a","64k",n],timeoutMs:6e4}),s(n)})}var w=["Fontsize=14","PrimaryColour=&H00FFFFFF","OutlineColour=&H00000000","BackColour=&H80000000","BorderStyle=1","Outline=2","Shadow=0","Alignment=2","MarginV=80","Bold=1"].join(",");async function _(t){const e=(await x(t.videoBytes)).durationSeconds;return y(async o=>{const i=p(o,"in.mp4"),a=p(o,"out.mp4");await r(i,t.videoBytes);const c=["-i",i];let u=-1,m=-1;if(t.newAudioBytes){const e=p(o,"new.mp3");await r(e,t.newAudioBytes),u=(c.length-0)/2,c.push("-i",e)}if(t.bgmAudioBytes){const e=p(o,"bgm.mp3");await r(e,t.bgmAudioBytes),m=c.length/2,c.push("-i",e)}const l=t.srtContent&&t.srtContent.trim().length>0;let f=null;l&&(f=p(o,"subs.srt"),await r(f,t.srtContent));const y=t.bgmVolume??.18;console.log(`[ffmpeg-runner] composeVideo: video=${t.videoBytes.length}B (${e.toFixed(2)}s), newAudio=${t.newAudioBytes?.length??0}B, bgm=${t.bgmAudioBytes?.length??0}B@${y}, srt=${t.srtContent?.length??0}chars`);const h=w.replace(/,/g,"\\,"),v=[];let _,x=!1;l&&f?(v.push(`[0:v]subtitles=${f}:force_style=${h}[v]`),_="[v]",x=!0):_="0:v:0";const A=[];u>=0&&A.push({idx:u,isBgm:!1}),m>=0&&A.push({idx:m,isBgm:!0});let E=null;if(1===A.length)E=`${A[0].idx}:a:0`;else if(A.length>=2){const t=[];for(const e of A)e.isBgm?(v.push(`[${e.idx}:a]volume=${y}[bgm]`),t.push("[bgm]")):t.push(`[${e.idx}:a]`);v.push(`${t.join("")}amix=inputs=${t.length}:duration=first:dropout_transition=0[a]`),E="[a]"}const T=["-y",...c];v.length>0&&T.push("-filter_complex",v.join(";")),T.push("-map",_),E&&T.push("-map",E),x?T.push("-c:v","libx264","-preset","fast","-crf","22","-pix_fmt","yuv420p"):T.push("-c:v","copy"),T.push("-c:a","aac","-b:a","128k","-ar","44100","-ac","2","-movflags","+faststart","-t",e.toFixed(3)),T.push(a),await g({args:T,timeoutMs:18e4});const B=E?await d():null;if(B)try{const t=await new Promise(t=>{const e=n(B,["-i",a],{stdio:["ignore","pipe","pipe"]});let o="";e.stderr.on("data",t=>o+=t.toString()),e.on("close",()=>t(o))});if(!/Audio:/.test(t))throw console.error("[ffmpeg-runner] 产物缺少音轨,ffmpeg 流概览:\n",t.slice(-2e3)),new Error("合成失败: 输出 mp4 缺少音轨 (检查 filter_complex 语法)");console.log("[ffmpeg-runner] composeVideo 完成,已含音视频双流")}catch(t){if(t instanceof Error&&t.message.includes("合成失败"))throw t}return s(a)})}async function x(t){return y(async e=>{const o=p(e,"in.mp4");await r(o,t);const s=await d();if(!s)throw new Error("ffmpeg-static 二进制缺失");return new Promise((t,e)=>{const r=n(s,["-i",o],{stdio:["ignore","pipe","pipe"]});let i="";r.stderr.on("data",t=>i+=t.toString()),r.on("close",()=>{const o=i.match(/Duration:\s*(\d+):(\d+):(\d+(?:\.\d+)?)/);if(!o)return e(new Error("无法解析视频时长"));const n=parseInt(o[1]),r=parseInt(o[2]),s=parseFloat(o[3]);t({durationSeconds:3600*n+60*r+s})}),r.on("error",e)})})}async function A(t,e,o="mp4",n=[],i=24e4){return y(async a=>{const c=p(a,"input.mp4"),u=p(a,`output.${o}`);await r(c,t);const m={};for(const t of n){const e=t.name.replace(/[^a-zA-Z0-9._-]/g,"_"),o=p(a,e);await r(o,t.bytes),m[t.name]=o}return await g({args:e(c,u,m),timeoutMs:i}),s(u)})}function E(t,e,o){return["-y","-fflags","+genpts","-loop","1","-t","0.04","-i",e,"-i",t,"-filter_complex","[0:v][1:v]scale2ref=w=main_w:h=main_h[vcover][vmainref];[vcover]setsar=1,setpts=PTS-STARTPTS,fps=30,format=yuv420p[vcoverf];[vmainref]setsar=1,setpts=PTS-STARTPTS,fps=30,format=yuv420p[vmain];[vcoverf][vmain]concat=n=2:v=1:a=0[v]","-map","[v]","-map","1:a?","-c:v","libx264","-preset","fast","-crf","18","-pix_fmt","yuv420p","-c:a","aac","-b:a","192k","-ar","44100","-ac","2","-movflags","+faststart",o]}async function T(t,e,o="mp4",n=[],i,a=24e4){return y(async c=>{const u=p(c,"input.mp4"),m=p(c,`output.${o}`),l=p(c,`output-with-cover.${o}`);await r(u,t);const f={};for(const t of n){const e=t.name.replace(/[^a-zA-Z0-9._-]/g,"_"),o=p(c,e);await r(o,t.bytes),f[t.name]=o}if(await g({args:e(u,m,f),timeoutMs:a}),!i?.length||!function(t){const e=String(t||"").toLowerCase();return"mp4"===e||"mov"===e}(o))return s(m);const d=p(c,"video-cover."+((y=i).length>=8&&137===y[0]&&80===y[1]&&78===y[2]&&71===y[3]&&13===y[4]&&10===y[5]&&26===y[6]&&10===y[7]?"png":"jpg"));var y;return await r(d,i),await g({args:E(m,d,l),timeoutMs:a}),s(l)})}var B=1048576,O=t=>`${Math.round(t/B)}MB`,b={maxVideos:6,maxAudios:3,maxVideoBytes:512*B,maxTotalVideoBytes:1024*B,maxAudioBytes:30*B,maxOverlayBytes:20*B},$=(t,e,o)=>({ok:!1,status:t,error:e,message:o});function R(t){return"object"==typeof t&&null!==t&&"ok"in t&&!1===t.ok}function L(t,e){if(t.type?.startsWith("video/")||"application/mxf"===t.type)return t.type;const o=e?.split(";")[0]?.trim().toLowerCase()??"";return o.startsWith("video/")||"application/mxf"===o||"application/octet-stream"!==o&&o?o:function(t){const e=(()=>{try{return new URL(t).pathname.toLowerCase()}catch{return t.toLowerCase()}})();return e.endsWith(".mov")?"video/quicktime":e.endsWith(".webm")?"video/webm":e.endsWith(".mkv")?"video/x-matroska":e.endsWith(".mxf")?"application/mxf":e.endsWith(".avi")?"video/x-msvideo":"video/mp4"}(t.url)}async function S(t,e){let o;try{o=new URL(t.url)}catch{return $(400,"BAD_REMOTE_URL","videoUrl 不是合法 URL")}if("http:"!==o.protocol&&"https:"!==o.protocol)return $(400,"BAD_REMOTE_URL","videoUrl 只支持 http/https");if(null!=t.size&&t.size>e)return $(413,"TOO_LARGE",`视频超过 ${O(e)}`);const n=new AbortController,r=setTimeout(()=>n.abort(),12e4);try{const r=await fetch(o,{signal:n.signal});if(!r.ok)return $(502,"REMOTE_FETCH_FAILED",`远程视频下载失败(${r.status})`);if(Number(r.headers.get("content-length")??0)>e)return $(413,"TOO_LARGE",`视频超过 ${O(e)}`);const s=[];let i=0;if(r.body){const t=r.body.getReader();for(;;){const{done:o,value:n}=await t.read();if(o)break;if(i+=n.byteLength,i>e)return await t.cancel().catch(()=>{}),$(413,"TOO_LARGE",`视频超过 ${O(e)}`);s.push(Buffer.from(n))}}else{const t=Buffer.from(await r.arrayBuffer());if(t.length>e)return $(413,"TOO_LARGE",`视频超过 ${O(e)}`);s.push(t),i=t.length}return i<=0?$(502,"REMOTE_FETCH_FAILED","远程视频为空"):{type:L(t,r.headers.get("content-type")),bytes:Buffer.concat(s,i)}}catch(t){const e="AbortError"===t.name?"远程视频下载超时":"远程视频下载失败";return $(502,"REMOTE_FETCH_FAILED",e)}finally{clearTimeout(r)}}function C(t){return t.startsWith("video/")?"mp4":t.includes("mpeg")||t.includes("mp3")?"mp3":t.includes("wav")?"wav":t.includes("aac")?"aac":t.includes("ogg")?"ogg":t.includes("mp4")||t.includes("m4a")?"m4a":t.includes("flac")?"flac":"bin"}function V(o){const n={...b,...o?.limits};return{async handle(o){const{videos:r,videoUrls:s,audios:i,overlay:a,videoCover:c,textOverlays:u=[],editStateRaw:m}=o,l=await async function(t,e,o){const n=[],r=Math.max(t.length,e?.length??0);for(let s=0;s<r;s++){const r=t[s];if(r){n[s]=r;continue}const i=e?.[s];if(!i?.url)continue;const a=await S(i,o);if(R(a))return a;n[s]=a}return n.filter(Boolean)}(r,s,n.maxVideoBytes);if(R(l))return l;const p=l;if(p.length>n.maxVideos)return $(413,"TOO_MANY",`视频数超过 ${n.maxVideos}`);for(let t=0;t<p.length;t++){if(!/^video\//.test(p[t].type))return $(415,"BAD_TYPE",`video_${t} 不是视频文件`);if(p[t].bytes.length>n.maxVideoBytes)return $(413,"TOO_LARGE",`视频 ${t+1} 超过 ${O(n.maxVideoBytes)}`)}if(!p.length)return $(400,"BAD_REQUEST","缺少视频文件(video_0)");if(p.reduce((t,e)=>t+e.bytes.length,0)>n.maxTotalVideoBytes)return $(413,"TOO_LARGE",`视频总大小超过 ${O(n.maxTotalVideoBytes)},请减少素材或压缩`);if(i.length>n.maxAudios)return $(413,"TOO_MANY",`音频数超过 ${n.maxAudios}`);for(let t=0;t<i.length;t++){const e=/^audio\//.test(i[t].type),o=/^video\//.test(i[t].type);if(!e&&!o)return $(415,"BAD_TYPE",`audio_${t} 不是音频或视频文件`);if(i[t].bytes.length>(o?n.maxVideoBytes:n.maxAudioBytes))return $(413,"TOO_LARGE",`音频 ${t+1} 超过 ${O(o?n.maxVideoBytes:n.maxAudioBytes)}`)}if("string"!=typeof m)return $(400,"BAD_REQUEST","缺少 editState");if(a&&a.length>n.maxOverlayBytes)return $(413,"OVERLAY_TOO_LARGE","overlay 过大");if(u.some(t=>t.length>n.maxOverlayBytes))return $(413,"OVERLAY_TOO_LARGE","textOverlay 过大");if(c&&c.length>n.maxOverlayBytes)return $(413,"COVER_TOO_LARGE","videoCover too large");let f;try{f=t.parse(JSON.parse(m))}catch{return $(400,"BAD_STATE","编辑参数不合法")}if(f.clips.some(t=>t.srcIdx>=p.length))return $(400,"BAD_STATE","clips.srcIdx 超出上传视频数");if((f.audioClips??[]).some(t=>t.srcIdx>=i.length))return $(400,"BAD_STATE","audioClips.srcIdx 超出上传音频数");try{const t=p.map(t=>t.bytes),o=i.map(t=>t.bytes),n=new Map,r=t=>{let e=n.get(t);return e||(e=h(t),n.set(t,e)),e},s=[...new Set((f.audioClips??[]).map(t=>t.srcIdx))];for(const t of s)if(/^video\//.test(i[t].type)&&!await r(o[t]))return $(400,"BAD_TYPE",`音频 ${t+1} 是视频文件但没有音轨,无法提取声音`);const m=p.map(()=>!1);if(f.keepAudio){const e=[...new Set(f.clips.map(t=>t.srcIdx))];await Promise.all(e.map(async e=>{m[e]=await r(t[e])})),m.some(Boolean)||(f.audioClips??[]).length||(f={...f,keepAudio:!1})}const l=[];for(let e=1;e<t.length;e++)l.push({name:`video_${e}.mp4`,bytes:t[e]});o.forEach((t,e)=>l.push({name:`audio_${e}.${C(i[e].type)}`,bytes:t})),a&&l.push({name:"overlay.png",bytes:a}),u.forEach((t,e)=>l.push({name:`textOverlay_${e}.png`,bytes:t}));const g=function(t){const e=String(t.exportSettings?.format??"mp4").toLowerCase();return"mov"===e||"mxf"===e?e:"mp4"}(f),y=c?.length?c:function(t){const e=t.poster;if(!e?.useAsVideoCover)return;const o=("string"==typeof e.preview?e.preview:"string"==typeof e.src?e.src:"").match(/^data:image\/(?:png|jpe?g);base64,([a-z0-9+/=]+)$/i);return o?Buffer.from(o[1],"base64"):void 0}(f),v=(n,r,s)=>{const c={videoPaths:[n,...t.slice(1).map((t,e)=>s[`video_${e+1}.mp4`])],videoHasAudio:m,audioPaths:o.map((t,e)=>s[`audio_${e}.${C(i[e].type)}`]),overlayPath:a?s["overlay.png"]:void 0,textOverlayPaths:u.map((t,e)=>s[`textOverlay_${e}.png`]).filter(Boolean),overlayLayerPaths:u.map((t,e)=>s[`textOverlay_${e}.png`]).filter(Boolean)};return e(f,c,r)};return{ok:!0,bytes:y?.length?await T(t[0],v,g,l,y,28e4):await A(t[0],v,g,l,28e4),contentType:(d=g,"mov"===d?"video/quicktime":"mxf"===d?"application/mxf":"video/mp4"),filename:`edited.${g}`}}catch(t){return(t.message??"").includes("二进制缺失")?$(503,"SERVER_NOT_READY","服务端编码组件未就绪(ffmpeg 缺失),请联系管理员"):$(502,"ENCODE_FAILED","视频处理失败,请重试或换更短的视频")}var d}}}function k(t){const e=t?.maxBytes??b.maxVideoBytes;return{async handle(t,n){if(!/^video\//.test(t.type))return $(415,"BAD_TYPE","只支持视频文件");if(t.bytes.length>e)return $(413,"TOO_LARGE",`文件超过 ${O(e)}`);if(!isFinite(n)||n<0)return $(400,"BAD_TIME","time 参数不合法");try{return{ok:!0,bytes:await A(t.bytes,(t,e)=>o(t,n,e),"jpg"),contentType:"image/jpeg",filename:"poster.jpg"}}catch(t){return(t.message??"").includes("二进制缺失")?$(503,"SERVER_NOT_READY","服务端编码组件未就绪(ffmpeg 缺失),请联系管理员"):$(502,"EXTRACT_FAILED","封面抽取失败,请重试")}}}}export{b as DEFAULT_LIMITS,_ as composeVideo,k as createPosterHandler,V as createVideoExportHandler,v as extractAudio,h as probeHasAudio,x as probeVideoDuration,A as runVideoEdit,T as runVideoEditWithCover};
1
+ import{VideoEditState as t}from"@media-editor/core";import{buildFfmpegArgs as e,buildPosterArgs as o}from"@media-editor/core";import{spawn as n}from"child_process";import{writeFile as r,readFile as i,mkdtemp as a,rm as s,access as c}from"fs/promises";import{constants as u}from"fs";import{tmpdir as m}from"os";import{dirname as l,join as p}from"path";var f;async function d(){return void 0!==f||(f=await async function(){const t=[],e=e=>{t.push(e),e.toLowerCase().endsWith(".exe")||t.push(`${e}.exe`)};try{const t=(await import("ffmpeg-static")).default;"string"==typeof t&&e(t)}catch{}try{const{createRequire:t}=await import("module"),o=t(import.meta.url).resolve("ffmpeg-static/package.json"),n=Math.max(o.lastIndexOf("/"),o.lastIndexOf("\\")),r=n>=0?o.substring(0,n):o;e(p(r,"ffmpeg"))}catch{}(()=>{let t=process.cwd();for(;;){e(p(t,"node_modules","ffmpeg-static","ffmpeg")),e(p(t,"node_modules",".pnpm","ffmpeg-static@5.3.0","node_modules","ffmpeg-static","ffmpeg"));const o=l(t);if(o===t)break;t=o}})();for(const e of t)if(e&&!e.startsWith("/ROOT/"))try{return await c(e,u.X_OK),e}catch{}return null}())||console.warn("[ffmpeg-runner] ffmpeg-static 二进制未找到 (尝试了多个 fallback 路径)"),f}async function g({args:t,timeoutMs:e=18e4}){const o=await d();if(!o)throw new Error("ffmpeg-static 二进制缺失 — 请检查 node_modules/ffmpeg-static/ffmpeg 是否存在");return console.log("[ffmpeg-runner] args:",JSON.stringify(t)),new Promise((r,i)=>{const a=n(o,t,{stdio:["ignore","pipe","pipe"]});let s="",c=!1;const u=setTimeout(()=>{c=!0,a.kill("SIGKILL"),i(new Error(`ffmpeg 超时 (${e}ms)`))},e);a.stderr.on("data",t=>{s+=t.toString(),s.length>8192&&(s=s.slice(-8192))}),a.on("close",t=>{if(clearTimeout(u),c)return;const e=s.slice(-2500);console.log(`[ffmpeg-runner] exit=${t}, stderr tail:\n${e}\n---end---`),0===t?r():i(new Error(`ffmpeg 退出码 ${t}: ${e.slice(-800)}`))}),a.on("error",t=>{clearTimeout(u),i(t)})})}async function y(t){const e=await a(p(m(),"vtrans-"));try{return await t(e)}finally{s(e,{recursive:!0,force:!0}).catch(()=>{})}}async function h(t){const e=await d();return!!e&&y(async o=>{const i=p(o,"probe.mp4");return await r(i,t),new Promise(t=>{const o=n(e,["-hide_banner","-i",i],{stdio:["ignore","ignore","pipe"]});let r="";const a=setTimeout(()=>{o.kill("SIGKILL"),t(!1)},15e3);o.stderr.on("data",t=>{r+=t.toString(),r.length>16384&&(r=r.slice(-16384))}),o.on("close",()=>{clearTimeout(a),t(/Stream #[^\n]*Audio:/.test(r))}),o.on("error",()=>{clearTimeout(a),t(!1)})})})}async function v(t){return y(async e=>{const o=p(e,"in.mp4"),n=p(e,"audio.mp3");return await r(o,t),await g({args:["-y","-i",o,"-vn","-acodec","libmp3lame","-ar","16000","-ac","1","-b:a","64k",n],timeoutMs:6e4}),i(n)})}var w=["Fontsize=14","PrimaryColour=&H00FFFFFF","OutlineColour=&H00000000","BackColour=&H80000000","BorderStyle=1","Outline=2","Shadow=0","Alignment=2","MarginV=80","Bold=1"].join(",");async function _(t){const e=(await x(t.videoBytes)).durationSeconds;return y(async o=>{const a=p(o,"in.mp4"),s=p(o,"out.mp4");await r(a,t.videoBytes);const c=["-i",a];let u=-1,m=-1;if(t.newAudioBytes){const e=p(o,"new.mp3");await r(e,t.newAudioBytes),u=(c.length-0)/2,c.push("-i",e)}if(t.bgmAudioBytes){const e=p(o,"bgm.mp3");await r(e,t.bgmAudioBytes),m=c.length/2,c.push("-i",e)}const l=t.srtContent&&t.srtContent.trim().length>0;let f=null;l&&(f=p(o,"subs.srt"),await r(f,t.srtContent));const y=t.bgmVolume??.18;console.log(`[ffmpeg-runner] composeVideo: video=${t.videoBytes.length}B (${e.toFixed(2)}s), newAudio=${t.newAudioBytes?.length??0}B, bgm=${t.bgmAudioBytes?.length??0}B@${y}, srt=${t.srtContent?.length??0}chars`);const h=w.replace(/,/g,"\\,"),v=[];let _,x=!1;l&&f?(v.push(`[0:v]subtitles=${f}:force_style=${h}[v]`),_="[v]",x=!0):_="0:v:0";const A=[];u>=0&&A.push({idx:u,isBgm:!1}),m>=0&&A.push({idx:m,isBgm:!0});let E=null;if(1===A.length)E=`${A[0].idx}:a:0`;else if(A.length>=2){const t=[];for(const e of A)e.isBgm?(v.push(`[${e.idx}:a]volume=${y}[bgm]`),t.push("[bgm]")):t.push(`[${e.idx}:a]`);v.push(`${t.join("")}amix=inputs=${t.length}:duration=first:dropout_transition=0[a]`),E="[a]"}const T=["-y",...c];v.length>0&&T.push("-filter_complex",v.join(";")),T.push("-map",_),E&&T.push("-map",E),x?T.push("-c:v","libx264","-preset","fast","-crf","22","-pix_fmt","yuv420p"):T.push("-c:v","copy"),T.push("-c:a","aac","-b:a","128k","-ar","44100","-ac","2","-movflags","+faststart","-t",e.toFixed(3)),T.push(s),await g({args:T,timeoutMs:18e4});const B=E?await d():null;if(B)try{const t=await new Promise(t=>{const e=n(B,["-i",s],{stdio:["ignore","pipe","pipe"]});let o="";e.stderr.on("data",t=>o+=t.toString()),e.on("close",()=>t(o))});if(!/Audio:/.test(t))throw console.error("[ffmpeg-runner] 产物缺少音轨,ffmpeg 流概览:\n",t.slice(-2e3)),new Error("合成失败: 输出 mp4 缺少音轨 (检查 filter_complex 语法)");console.log("[ffmpeg-runner] composeVideo 完成,已含音视频双流")}catch(t){if(t instanceof Error&&t.message.includes("合成失败"))throw t}return i(s)})}async function x(t){return y(async e=>{const o=p(e,"in.mp4");await r(o,t);const i=await d();if(!i)throw new Error("ffmpeg-static 二进制缺失");return new Promise((t,e)=>{const r=n(i,["-i",o],{stdio:["ignore","pipe","pipe"]});let a="";r.stderr.on("data",t=>a+=t.toString()),r.on("close",()=>{const o=a.match(/Duration:\s*(\d+):(\d+):(\d+(?:\.\d+)?)/);if(!o)return e(new Error("无法解析视频时长"));const n=parseInt(o[1]),r=parseInt(o[2]),i=parseFloat(o[3]);t({durationSeconds:3600*n+60*r+i})}),r.on("error",e)})})}async function A(t,e,o="mp4",n=[],a=24e4){return y(async s=>{const c=p(s,"input.mp4"),u=p(s,`output.${o}`);await r(c,t);const m={};for(const t of n){const e=t.name.replace(/[^a-zA-Z0-9._-]/g,"_"),o=p(s,e);await r(o,t.bytes),m[t.name]=o}return await g({args:e(c,u,m),timeoutMs:a}),i(u)})}function E(t,e,o){return["-y","-fflags","+genpts","-loop","1","-t","0.04","-i",e,"-i",t,"-filter_complex","[0:v][1:v]scale2ref=w=main_w:h=main_h[vcover][vmainref];[vcover]setsar=1,setpts=PTS-STARTPTS,fps=30,format=yuv420p[vcoverf];[vmainref]setsar=1,setpts=PTS-STARTPTS,fps=30,format=yuv420p[vmain];[vcoverf][vmain]concat=n=2:v=1:a=0[v]","-map","[v]","-map","1:a?","-c:v","libx264","-preset","fast","-crf","18","-pix_fmt","yuv420p","-c:a","aac","-b:a","192k","-ar","44100","-ac","2","-movflags","+faststart",o]}async function T(t,e,o="mp4",n=[],a,s=24e4){return y(async c=>{const u=p(c,"input.mp4"),m=p(c,`output.${o}`),l=p(c,`output-with-cover.${o}`);await r(u,t);const f={};for(const t of n){const e=t.name.replace(/[^a-zA-Z0-9._-]/g,"_"),o=p(c,e);await r(o,t.bytes),f[t.name]=o}if(await g({args:e(u,m,f),timeoutMs:s}),!a?.length||!function(t){const e=String(t||"").toLowerCase();return"mp4"===e||"mov"===e}(o))return i(m);const d=p(c,"video-cover."+((y=a).length>=8&&137===y[0]&&80===y[1]&&78===y[2]&&71===y[3]&&13===y[4]&&10===y[5]&&26===y[6]&&10===y[7]?"png":"jpg"));var y;return await r(d,a),await g({args:E(m,d,l),timeoutMs:s}),i(l)})}var B=1048576,O=t=>`${Math.round(t/B)}MB`,b={maxVideos:6,maxAudios:3,maxVideoBytes:512*B,maxTotalVideoBytes:1024*B,maxAudioBytes:30*B,maxOverlayBytes:20*B},$=(t,e,o)=>({ok:!1,status:t,error:e,message:o});function R(t){return"object"==typeof t&&null!==t&&"ok"in t&&!1===t.ok}function L(t,e){if(t.type?.startsWith("video/")||"application/mxf"===t.type)return t.type;const o=e?.split(";")[0]?.trim().toLowerCase()??"";return o.startsWith("video/")||"application/mxf"===o||"application/octet-stream"!==o&&o?o:function(t){const e=(()=>{try{return new URL(t).pathname.toLowerCase()}catch{return t.toLowerCase()}})();return e.endsWith(".mov")?"video/quicktime":e.endsWith(".webm")?"video/webm":e.endsWith(".mkv")?"video/x-matroska":e.endsWith(".mxf")?"application/mxf":e.endsWith(".avi")?"video/x-msvideo":"video/mp4"}(t.url)}async function S(t,e){let o;try{o=new URL(t.url)}catch{return $(400,"BAD_REMOTE_URL","videoUrl 不是合法 URL")}if("http:"!==o.protocol&&"https:"!==o.protocol)return $(400,"BAD_REMOTE_URL","videoUrl 只支持 http/https");if(null!=t.size&&t.size>e)return $(413,"TOO_LARGE",`视频超过 ${O(e)}`);const n=new AbortController,r=setTimeout(()=>n.abort(),12e4);try{const r=await fetch(o,{signal:n.signal});if(!r.ok)return $(502,"REMOTE_FETCH_FAILED",`远程视频下载失败(${r.status})`);if(Number(r.headers.get("content-length")??0)>e)return $(413,"TOO_LARGE",`视频超过 ${O(e)}`);const i=[];let a=0;if(r.body){const t=r.body.getReader();for(;;){const{done:o,value:n}=await t.read();if(o)break;if(a+=n.byteLength,a>e)return await t.cancel().catch(()=>{}),$(413,"TOO_LARGE",`视频超过 ${O(e)}`);i.push(Buffer.from(n))}}else{const t=Buffer.from(await r.arrayBuffer());if(t.length>e)return $(413,"TOO_LARGE",`视频超过 ${O(e)}`);i.push(t),a=t.length}return a<=0?$(502,"REMOTE_FETCH_FAILED","远程视频为空"):{type:L(t,r.headers.get("content-type")),bytes:Buffer.concat(i,a)}}catch(t){const e="AbortError"===t.name?"远程视频下载超时":"远程视频下载失败";return $(502,"REMOTE_FETCH_FAILED",e)}finally{clearTimeout(r)}}function C(t){return t.startsWith("video/")?"mp4":t.includes("mpeg")||t.includes("mp3")?"mp3":t.includes("wav")?"wav":t.includes("aac")?"aac":t.includes("ogg")?"ogg":t.includes("mp4")||t.includes("m4a")?"m4a":t.includes("flac")?"flac":"bin"}function V(o){const n={...b,...o?.limits};return{async handle(o){const{videos:r,videoUrls:i,audios:a,overlay:s,videoCover:c,textOverlays:u=[],editStateRaw:m}=o,l=await async function(t,e,o){const n=[],r=Math.max(t.length,e?.length??0);for(let i=0;i<r;i++){const r=t[i];if(r){n[i]=r;continue}const a=e?.[i];if(!a?.url)continue;const s=await S(a,o);if(R(s))return s;n[i]=s}return n.filter(Boolean)}(r,i,n.maxVideoBytes);if(R(l))return l;const p=l;if(p.length>n.maxVideos)return $(413,"TOO_MANY",`视频数超过 ${n.maxVideos}`);for(let t=0;t<p.length;t++){if(!/^video\//.test(p[t].type))return $(415,"BAD_TYPE",`video_${t} 不是视频文件`);if(p[t].bytes.length>n.maxVideoBytes)return $(413,"TOO_LARGE",`视频 ${t+1} 超过 ${O(n.maxVideoBytes)}`)}if(!p.length)return $(400,"BAD_REQUEST","缺少视频文件(video_0)");if(p.reduce((t,e)=>t+e.bytes.length,0)>n.maxTotalVideoBytes)return $(413,"TOO_LARGE",`视频总大小超过 ${O(n.maxTotalVideoBytes)},请减少素材或压缩`);if(a.length>n.maxAudios)return $(413,"TOO_MANY",`音频数超过 ${n.maxAudios}`);for(let t=0;t<a.length;t++){const e=/^audio\//.test(a[t].type),o=/^video\//.test(a[t].type);if(!e&&!o)return $(415,"BAD_TYPE",`audio_${t} 不是音频或视频文件`);if(a[t].bytes.length>(o?n.maxVideoBytes:n.maxAudioBytes))return $(413,"TOO_LARGE",`音频 ${t+1} 超过 ${O(o?n.maxVideoBytes:n.maxAudioBytes)}`)}if("string"!=typeof m)return $(400,"BAD_REQUEST","缺少 editState");if(s&&s.length>n.maxOverlayBytes)return $(413,"OVERLAY_TOO_LARGE","overlay 过大");if(u.some(t=>t.length>n.maxOverlayBytes))return $(413,"OVERLAY_TOO_LARGE","textOverlay 过大");if(c&&c.length>n.maxOverlayBytes)return $(413,"COVER_TOO_LARGE","videoCover too large");let f;try{f=t.parse(JSON.parse(m))}catch{return $(400,"BAD_STATE","编辑参数不合法")}if(f.clips.some(t=>t.srcIdx>=p.length))return $(400,"BAD_STATE","clips.srcIdx 超出上传视频数");if((f.audioClips??[]).some(t=>t.srcIdx>=a.length))return $(400,"BAD_STATE","audioClips.srcIdx 超出上传音频数");try{const t=p.map(t=>t.bytes),o=a.map(t=>t.bytes),n=new Map,r=t=>{let e=n.get(t);return e||(e=h(t),n.set(t,e)),e},i=[...new Set((f.audioClips??[]).map(t=>t.srcIdx))];for(const t of i)if(/^video\//.test(a[t].type)&&!await r(o[t]))return $(400,"BAD_TYPE",`音频 ${t+1} 是视频文件但没有音轨,无法提取声音`);const m=p.map(()=>!1);if(f.keepAudio){const e=[...new Set(f.clips.map(t=>t.srcIdx))];await Promise.all(e.map(async e=>{m[e]=await r(t[e])})),m.some(Boolean)||(f.audioClips??[]).length||(f={...f,keepAudio:!1})}const l=[];for(let e=1;e<t.length;e++)l.push({name:`video_${e}.mp4`,bytes:t[e]});o.forEach((t,e)=>l.push({name:`audio_${e}.${C(a[e].type)}`,bytes:t})),s&&l.push({name:"overlay.png",bytes:s}),u.forEach((t,e)=>l.push({name:`textOverlay_${e}.png`,bytes:t}));const g=function(t){const e=String(t.exportSettings?.format??"mp4").toLowerCase();return"mov"===e||"mxf"===e?e:"mp4"}(f),y=c?.length?c:function(t){const e=t.poster;if(!e?.useAsVideoCover)return;const o=("string"==typeof e.preview?e.preview:"string"==typeof e.src?e.src:"").match(/^data:image\/(?:png|jpe?g);base64,([a-z0-9+/=]+)$/i);return o?Buffer.from(o[1],"base64"):void 0}(f),v=(n,r,i)=>{const c={videoPaths:[n,...t.slice(1).map((t,e)=>i[`video_${e+1}.mp4`])],videoHasAudio:m,audioPaths:o.map((t,e)=>i[`audio_${e}.${C(a[e].type)}`]),overlayPath:s?i["overlay.png"]:void 0,textOverlayPaths:u.map((t,e)=>i[`textOverlay_${e}.png`]).filter(Boolean),overlayLayerPaths:u.map((t,e)=>i[`textOverlay_${e}.png`]).filter(Boolean)};return e(f,c,r)};return{ok:!0,bytes:y?.length?await T(t[0],v,g,l,y,28e4):await A(t[0],v,g,l,28e4),contentType:(d=g,"mov"===d?"video/quicktime":"mxf"===d?"application/mxf":"video/mp4"),filename:`edited.${g}`}}catch(t){return(t.message??"").includes("二进制缺失")?$(503,"SERVER_NOT_READY","服务端编码组件未就绪(ffmpeg 缺失),请联系管理员"):$(502,"ENCODE_FAILED","视频处理失败,请重试或换更短的视频")}var d}}}function k(t){const e=t?.maxBytes??b.maxVideoBytes;return{async handle(t,n){if(!/^video\//.test(t.type))return $(415,"BAD_TYPE","只支持视频文件");if(t.bytes.length>e)return $(413,"TOO_LARGE",`文件超过 ${O(e)}`);if(!isFinite(n)||n<0)return $(400,"BAD_TIME","time 参数不合法");try{return{ok:!0,bytes:await A(t.bytes,(t,e)=>o(t,n,e),"jpg"),contentType:"image/jpeg",filename:"poster.jpg"}}catch(t){return(t.message??"").includes("二进制缺失")?$(503,"SERVER_NOT_READY","服务端编码组件未就绪(ffmpeg 缺失),请联系管理员"):$(502,"EXTRACT_FAILED","封面抽取失败,请重试")}}}}export{b as DEFAULT_LIMITS,_ as composeVideo,k as createPosterHandler,V as createVideoExportHandler,v as extractAudio,h as probeHasAudio,x as probeVideoDuration,A as runVideoEdit,T as runVideoEditWithCover};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bylqwjc/media-editor-server",
3
- "version": "1.0.26",
3
+ "version": "1.0.28",
4
4
  "description": "媒体编辑器服务端:框架无关的视频导出/封面处理器 + Web(Next)/Express 适配器(Node + ffmpeg-static)",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -1 +0,0 @@
1
- var t=.1;function n(t){return t.out-t.in}function e(t){return t.reduce((t,e)=>t+n(e),0)}function r(t,e){let r=0;for(let u=0;u<e&&u<t.length;u++)r+=n(t[u]);return r}function u(t,e){if(!t.length||e<0)return null;let r=0;for(let u=0;u<t.length;u++){const i=n(t[u]);if(e<r+i)return{idx:u,srcTime:t[u].in+(e-r)};r+=i}if(Math.abs(e-r)<1e-9||e<=r){const n=t.length-1;return{idx:n,srcTime:t[n].out}}return null}function i(n,e){const r=u(n,e);if(!r)return n;const i=n[r.idx];return r.srcTime<i.in+t||r.srcTime>i.out-t?n:[...n.slice(0,r.idx),{...i,out:r.srcTime},{...i,in:r.srcTime},...n.slice(r.idx+1)]}function s(t,n){return t.length<=1||!t[n]?t:t.filter((t,e)=>e!==n)}function c(t,n){const e=t[n];return e?[...t.slice(0,n+1),{...e},...t.slice(n+1)]:t}function o(t,n,e){if(n===e||!t[n]||e<0||e>=t.length)return t;const r=[...t],[u]=r.splice(n,1);return r.splice(e,0,u),r}function a(n,e,r,u,i){if(!n[e])return n;const s=n.map(t=>({...t}));return"in"===r?s[e].in=Math.min(Math.max(u,0),s[e].out-t):s[e].out=Math.max(Math.min(u,i),s[e].in+t),s}function f(n,e,r){const u=Math.max(Math.min(n.out,e),t),i=Math.min(Math.max(n.in,0),u-t),s=Math.min(Math.max(n.startAt,0),Math.max(0,r-t));return{...n,in:i,out:u,startAt:s}}function p(t,n=[]){const r=e(t),u=n.reduce((t,n)=>Math.max(t,n.startAt+(n.out-n.in)/Math.max(.01,n.speed??1)),0);return Math.max(r,u)}function h(t){return[...new Set(t.map(t=>t.srcIdx))].sort((t,n)=>t-n)}function l(t,n){const e=new Map(n.map((t,n)=>[t,n]));return t.map(t=>({...t,srcIdx:e.get(t.srcIdx)??0}))}function m(t){return{past:[],present:t,future:[]}}function x(t,n){if(n===t.present)return t;const e=[...t.past,t.present];return e.length>100&&e.shift(),{past:e,present:n,future:[]}}function M(t,n){return n===t.present?t:{...t,present:n}}function d(t){return t.past.length>0}function g(t){return t.future.length>0}function T(t){return d(t)?{past:t.past.slice(0,-1),present:t.past[t.past.length-1],future:[t.present,...t.future]}:t}function A(t){if(!g(t))return t;const[n,...e]=t.future;return{past:[...t.past,t.present],present:n,future:e}}export{t as MIN_CLIP,g as canRedo,d as canUndo,f as clampAudioClip,n as clipDuration,r as clipStartsAt,p as contentDuration,m as createHistory,c as duplicateClip,u as locateOutput,x as pushHistory,A as redo,l as remapSrcIndices,s as removeClip,o as reorderClips,M as replacePresent,i as splitAtOutput,e as totalDuration,a as trimClipEdge,T as undo,h as usedVideoSrcIndices};
@@ -1 +0,0 @@
1
- import{z as e}from"../zod/index.js";var t={color:e.string().max(32),width:e.number().positive().max(200)},n={rotation:e.number().min(-180).max(180).optional()},i={startAt:e.number().min(0).optional(),endAt:e.number().min(0).optional(),timelineTrack:e.number().int().min(0).max(99).optional(),hidden:e.boolean().optional(),locked:e.boolean().optional()},a={brightness:e.number().min(-1).max(1).default(0),contrast:e.number().min(-1).max(1).default(0),saturation:e.number().min(-1).max(1).default(0),temperature:e.number().min(-1).max(1).default(0),tint:e.number().min(-1).max(1).default(0),vibrance:e.number().min(-1).max(1).default(0),gamma:e.number().min(-1).max(1).default(0),highlights:e.number().min(-1).max(1).default(0),shadows:e.number().min(-1).max(1).default(0),whites:e.number().min(-1).max(1).default(0),blacks:e.number().min(-1).max(1).default(0),lightSense:e.number().min(-1).max(1).default(0),sharpen:e.number().min(0).max(1).default(0),clarity:e.number().min(0).max(1).default(0),grain:e.number().min(0).max(1).default(0),fade:e.number().min(0).max(1).default(0),vignette:e.number().min(0).max(1).default(0)},o=e.discriminatedUnion("type",[e.object({type:e.literal("pen"),points:e.array(e.number()).min(4),...t,...i,...n}),e.object({type:e.literal("line"),x1:e.number(),y1:e.number(),x2:e.number(),y2:e.number(),...t,...i,...n}),e.object({type:e.literal("arrow"),x1:e.number(),y1:e.number(),x2:e.number(),y2:e.number(),...t,...i,...n}),e.object({type:e.literal("rect"),x:e.number(),y:e.number(),w:e.number(),h:e.number(),...t,...i,...n}),e.object({type:e.literal("ellipse"),x:e.number(),y:e.number(),w:e.number(),h:e.number(),...t,...i,...n}),e.object({type:e.literal("text"),x:e.number(),y:e.number(),text:e.string().max(500),color:e.string().max(32),fontSize:e.number().positive().max(512),fontFamily:e.string().max(120).optional(),fontWeight:e.string().max(20).optional(),italic:e.boolean().optional(),underline:e.boolean().optional(),strikethrough:e.boolean().optional(),align:e.enum(["left","center","right"]).optional(),width:e.number().positive().max(8192).optional(),backgroundColor:e.string().max(32).optional(),strokeColor:e.string().max(32).optional(),borderWidth:e.number().min(0).max(64).optional(),paddingX:e.number().min(0).max(256).optional(),paddingY:e.number().min(0).max(256).optional(),lineHeight:e.number().positive().max(4).optional(),opacity:e.number().min(0).max(100).optional(),...i,...n}),e.object({type:e.literal("sticker"),x:e.number(),y:e.number(),w:e.number().positive(),h:e.number().positive(),emoji:e.string().max(16).optional(),src:e.string().optional(),...i,...n}),e.object({type:e.literal("adjust"),x:e.number(),y:e.number(),w:e.number().positive(),h:e.number().positive(),layerKind:e.enum(["adjust","filter"]).optional(),filterPreset:e.string().max(32).optional(),...a,...i,...n})]),m=e.object({srcIdx:e.number().int().min(0).max(7),in:e.number().min(0),out:e.number().min(0),hidden:e.boolean().optional(),locked:e.boolean().optional()}),r=e.object({srcIdx:e.number().int().min(0).max(2),track:e.number().int().min(0).default(0),startAt:e.number().min(0),in:e.number().min(0),out:e.number().min(0),speed:e.number().min(.5).max(2).default(1),volume:e.number().min(0).max(10),muted:e.boolean().optional(),locked:e.boolean().optional(),fadeIn:e.number().min(0).default(0),fadeOut:e.number().min(0).default(0)}),u=e.object({type:e.enum(["none","fade","slide","wipe","flip","clockWipe","star","circle","rectangle"]).default("none"),duration:e.number().min(0).max(2).default(.4)}),l=e.object({fileName:e.string().max(120).optional(),format:e.enum(["mp4","mov","mxf"]).default("mp4"),width:e.number().int().min(2).max(8192).optional(),height:e.number().int().min(2).max(8192).optional(),frameRate:e.number().int().min(12).max(120).default(30),bitrateMode:e.enum(["auto","custom"]).optional(),videoBitrateKbps:e.number().int().min(100).max(5e4).optional(),audioBitrateKbps:e.number().int().min(32).max(1024).optional(),audioCodec:e.enum(["aac","mp3"]).default("aac")}).optional(),s={brightness:0,contrast:0,saturation:0,temperature:0,tint:0,vibrance:0,gamma:0,highlights:0,shadows:0,whites:0,blacks:0,lightSense:0,sharpen:0,clarity:0,grain:0,fade:0,vignette:0},b=e.object({clips:e.array(m).min(1).max(50),audioClips:e.array(r).max(8).default([]),canvas:e.object({w:e.number().int().min(2).max(4096),h:e.number().int().min(2).max(4096)}),crop:e.object({x:e.number().min(0),y:e.number().min(0),width:e.number().positive(),height:e.number().positive()}).optional(),scale:e.object({width:e.number().positive(),height:e.number().positive(),fit:e.enum(["contain","cover","force"]),backgroundColor:e.string().max(32).optional()}).optional(),rotation:e.number().min(-180).max(180).default(0),flipX:e.boolean().default(!1),flipY:e.boolean().default(!1),filters:e.object(a).default(s),filterPreset:e.string().max(32).optional(),overlays:e.array(o).max(200).optional(),transitions:e.array(u).max(49).default([]),keepAudio:e.boolean().default(!0),poster:e.object({time:e.number().min(0),src:e.string().optional(),useAsVideoCover:e.boolean().optional(),preview:e.string().optional()}).optional(),exportSettings:l}).superRefine((t,n)=>{t.clips.forEach((t,i)=>{t.out<=t.in&&n.addIssue({code:e.ZodIssueCode.custom,message:`clips[${i}].out 必须大于 in`,path:["clips",i,"out"]})}),t.audioClips?.forEach((t,i)=>{t.out<=t.in&&n.addIssue({code:e.ZodIssueCode.custom,message:`audioClips[${i}].out 必须大于 in`,path:["audioClips",i,"out"]})}),t.canvas.w%2==0&&t.canvas.h%2==0||n.addIssue({code:e.ZodIssueCode.custom,message:"canvas 宽高必须为偶数",path:["canvas"]}),null!=t.exportSettings?.width&&t.exportSettings.width%2!=0&&n.addIssue({code:e.ZodIssueCode.custom,message:"exportSettings.width must be even",path:["exportSettings","width"]}),null!=t.exportSettings?.height&&t.exportSettings.height%2!=0&&n.addIssue({code:e.ZodIssueCode.custom,message:"exportSettings.height must be even",path:["exportSettings","height"]})});function p(){return{clips:[],audioClips:[],canvas:{w:2,h:2},rotation:0,flipX:!1,flipY:!1,filters:s,transitions:[],keepAudio:!0}}export{r as AudioClip,m as Clip,s as DEFAULT_FILTERS,l as ExportSettings,o as Overlay,u as Transition,b as VideoEditState,p as defaultVideoEditState};
@@ -1 +0,0 @@
1
- var e={"tool.trim":"剪辑","tool.crop":"裁剪","tool.tune":"调色","tool.filter":"滤镜","tool.annotate":"标注","tool.sticker":"贴纸","tool.resize":"比例","tune.brightness":"亮度","tune.contrast":"对比","tune.saturation":"饱和","tune.gamma":"Gamma","tune.temperature":"色温","tune.tint":"色调","tune.vibrance":"自然饱和","tune.highlights":"高光","tune.shadows":"阴影","tune.whites":"白色","tune.blacks":"黑色","tune.lightSense":"光感","tune.sharpen":"锐化","tune.clarity":"清晰度","tune.grain":"颗粒","tune.fade":"褪色","tune.vignette":"暗角","overlay.select":"选择","overlay.pen":"画笔","overlay.eraser":"橡皮","overlay.line":"直线","overlay.arrow":"箭头","overlay.rect":"矩形","overlay.ellipse":"椭圆","overlay.text":"文字","overlay.color":"线色","overlay.width":"线宽","overlay.fontSize":"字号","overlay.font":"字体","overlay.align":"对齐","overlay.background":"背景","overlay.copySelected":"复制","overlay.delSelected":"删除选中","overlay.editSelected":"编辑","overlay.pickImage":"选择图片","overlay.hint":"点 emoji/图片添加 → 画布上拖动摆位,拖右下角紫色把手缩放","overlay.textPlaceholder":"输入文字,回车确认","filter.none":"原图","filter.bw":"黑白","filter.sepia":"复古","filter.warm":"暖阳","filter.cool":"冷调","filter.vivid":"鲜艳","ratio.orig":"原始","ratio.free":"自由比例","ratio.9:16":"竖屏 9:16","ratio.16:9":"横屏 16:9","ratio.1:1":"方形 1:1","ratio.4:5":"竖图 4:5","ratio.3:4":"竖图 3:4","ratio.2:3":"竖图 2:3","ratio.1.91:1":"横幅 1.91:1","act.fit":"适应","act.zoomFit":"缩放至适当大小","act.zoomTo":"缩放至 {value}%","act.split":"分割","act.copy":"复制","act.delete":"删除","act.restore":"还原","act.deleteMusic":"删除音乐","act.cancel":"取消","act.exportPoster":"导出封面","act.exporting":"导出中…","act.poster":"🖼 封面","act.again":"再次下载","act.saveDrive":"存网盘","act.changeImage":"← 换一张","act.changeVideo":"← 换一个","crop.rotateLeft":"↺ 向左旋转","crop.flipX":"⇋ 水平翻转","crop.flipY":"⇵ 垂直翻转","crop.rotateLeftShort":"左转","crop.flipXShort":"横翻","crop.flipYShort":"竖翻","tip.close":"关闭(换文件)","tip.undo":"撤销","tip.redo":"重做","tip.resetOpened":"重置到打开文件时","tip.previewZoom":"预览缩放比例","tip.previewZoomOut":"缩小预览","tip.previewZoomIn":"放大预览","tip.previewZoomFit":"适应预览","tip.previewPointer":"指针工具","tip.previewPan":"手工具:拖动画面","tip.poster":"预览并选择封面帧","tip.keepAudio":"原视频声音开关(与音乐混音;预览同步)","tip.split":"在播放头处把当前片段一分为二","tip.zoomOut":"缩小时间轴(Ctrl+滚轮)","tip.zoomIn":"放大时间轴(Ctrl+滚轮)","tip.fit":"缩放到适应宽度","tip.addVideo":"添加视频片段","tip.addAudio":"添加音乐(音频文件,或选含声音的视频自动提取音轨;与原声混音)","tip.dupClip":"复制该片段(插到其后)","tip.delClip":"删除该片段","tip.lockAspect":"锁定纵横比","tip.dblConfirm":"双击确认裁剪","err.notVideo":"请选择视频文件","err.maxVideo":"最多 {max} 个视频素材","err.videoLoad":"视频加载失败,请换一个文件","err.notAudio":"请选择音频文件(mp3/wav/m4a),或含声音的视频(自动提取音轨)","err.maxAudio":"最多 {max} 个音频素材","err.audioLoad":"音频加载失败,请换一个文件","err.processFailed":"处理失败","err.posterFailed":"封面渲染失败","err.canvas":"canvas 不可用","err.imageRead":"图片读取失败,请换一张","err.notImage":"请选择图片文件","err.fileType":"只支持图片或视频文件","err.saveDrive":"存网盘失败","msg.processing":"正在导出中…","msg.exportPrepare":"正在准备素材…","msg.exportUpload":"正在上传素材…","msg.exportEncode":"正在编码视频…","msg.exportDownload":"正在接收结果…","msg.exportingHint":"请稍候,导出完成后会自动返回结果。","msg.done":"完成 ✓","msg.loading":"素材加载中…","msg.exported":"已导出:","msg.saving":"存网盘中…","msg.saved":"已存到网盘 ✓","lbl.ratioSection":"画面比例(裁剪,不变形)","lbl.dragToReposition":"↔ 拖动预览可调整裁剪位置","lbl.sizeSection":"导出尺寸(像素;比例不符时 cover 居中裁剪)","lbl.currentOut":"当前输出","lbl.zoomSize":"大小","lbl.noScale":"(未缩放)","lbl.coverNote":"· 比例不一致时居中裁剪(cover),不变形","lbl.audioTrackHint":"♪ 音频轨(右侧 + 添加音乐,与原声混音)","lbl.volume":"音量","lbl.volNote":"(预览最大 100%,导出按设定值)","lbl.music":"音乐","kbd.fit":"⇧ F","poster.title":"选择封面帧","panel.title":"媒体编辑器","panel.subtitle":"上传图片 / 视频,裁剪 · 滤镜 · 文字 · 导出","panel.pick":"点击选择图片或视频","panel.pickHint":"图片用 Filerobot · 视频可裁剪/静音/封面"},o={"简":"簡","体":"體","图":"圖","频":"頻","视":"視","辑":"輯","调":"調","滤":"濾","标":"標","注":"註","贴":"貼","选":"選","择":"擇","线":"線","箭":"箭","头":"頭","复":"複","删":"刪","除":"除","编":"編","边":"邊","输":"輸","入":"入","确":"確","认":"認","饱":"飽","对":"對","暖":"暖","阳":"陽","冷":"冷","纵":"縱","横":"橫","适":"適","应":"應","缩":"縮","实":"實","际":"際","导":"導","出":"出","封":"封","面":"面","换":"換","张":"張","预":"預","览":"覽","动":"動","声":"聲","开":"開","关":"關","与":"與","乐":"樂","混":"混","处":"處","载":"載","错":"錯","误":"誤","读":"讀","仅":"僅","终":"終","稍":"稍","候":"候","返回":"返回","当前":"目前","输出":"輸出","画":"畫","变":"變","音频":"音訊","音轨":"音軌","添加":"新增","删除":"刪除","保存":"儲存","加载":"載入","网盘":"網盤"},t=e=>{let t=e;for(const[e,a]of Object.entries(o).sort((e,o)=>o[0].length-e[0].length))t=t.replaceAll(e,a);return t},a={zh:e,en:{"tool.trim":"Trim","tool.crop":"Crop","tool.tune":"Tune","tool.filter":"Filters","tool.annotate":"Annotate","tool.sticker":"Stickers","tool.resize":"Ratio","tune.brightness":"Brightness","tune.contrast":"Contrast","tune.saturation":"Saturation","tune.gamma":"Gamma","tune.temperature":"Temperature","tune.tint":"Tint","tune.vibrance":"Vibrance","tune.highlights":"Highlights","tune.shadows":"Shadows","tune.whites":"Whites","tune.blacks":"Blacks","tune.lightSense":"Light","tune.sharpen":"Sharpen","tune.clarity":"Clarity","tune.grain":"Grain","tune.fade":"Fade","tune.vignette":"Vignette","overlay.select":"Select","overlay.pen":"Pen","overlay.eraser":"Eraser","overlay.line":"Line","overlay.arrow":"Arrow","overlay.rect":"Rect","overlay.ellipse":"Ellipse","overlay.text":"Text","overlay.color":"Color","overlay.width":"Width","overlay.fontSize":"Size","overlay.font":"Font","overlay.align":"Align","overlay.background":"Background","overlay.copySelected":"Copy","overlay.delSelected":"Delete selected","overlay.editSelected":"Edit","overlay.pickImage":"Pick image","overlay.hint":"Tap emoji/image to add → drag to place, drag the purple corner handle to scale","overlay.textPlaceholder":"Type text, Enter to confirm","filter.none":"Original","filter.bw":"B&W","filter.sepia":"Sepia","filter.warm":"Warm","filter.cool":"Cool","filter.vivid":"Vivid","ratio.orig":"Original","ratio.free":"Free ratio","ratio.9:16":"Portrait 9:16","ratio.16:9":"Landscape 16:9","ratio.1:1":"Square 1:1","ratio.4:5":"Vertical 4:5","ratio.3:4":"Vertical 3:4","ratio.2:3":"Vertical 2:3","ratio.1.91:1":"Wide 1.91:1","act.fit":"Fit","act.zoomFit":"Zoom to fit","act.zoomTo":"Zoom to {value}%","act.split":"Split","act.copy":"Copy","act.delete":"Delete","act.restore":"Reset","act.deleteMusic":"Remove music","act.cancel":"Cancel","act.exportPoster":"Export cover","act.exporting":"Exporting…","act.poster":"🖼 Cover","act.again":"Download again","act.saveDrive":"Save to drive","act.changeImage":"← Change image","act.changeVideo":"← Change file","crop.rotateLeft":"↺ Rotate left","crop.flipX":"⇋ Flip horizontal","crop.flipY":"⇵ Flip vertical","crop.rotateLeftShort":"Rot","crop.flipXShort":"Flip","crop.flipYShort":"Flip","tip.close":"Close (change file)","tip.undo":"Undo","tip.redo":"Redo","tip.resetOpened":"Reset to opened file","tip.previewZoom":"Preview zoom","tip.previewZoomOut":"Zoom out preview","tip.previewZoomIn":"Zoom in preview","tip.previewZoomFit":"Fit preview","tip.previewPointer":"Pointer tool","tip.previewPan":"Hand tool: pan canvas","tip.poster":"Preview and pick a cover frame","tip.keepAudio":"Original audio on/off (mixed with music; preview follows)","tip.split":"Split the current clip at the playhead","tip.zoomOut":"Zoom out timeline (Ctrl+wheel)","tip.zoomIn":"Zoom in timeline (Ctrl+wheel)","tip.fit":"Fit to width","tip.addVideo":"Add video clip","tip.addAudio":"Add music (audio file, or a video with sound to extract its track; mixed with original)","tip.dupClip":"Duplicate clip (insert after)","tip.delClip":"Delete clip","tip.lockAspect":"Lock aspect ratio","tip.dblConfirm":"Double-click to confirm crop","err.notVideo":"Please choose a video file","err.maxVideo":"Up to {max} video sources","err.videoLoad":"Failed to load video, try another file","err.notAudio":"Choose an audio file (mp3/wav/m4a), or a video with sound (audio auto-extracted)","err.maxAudio":"Up to {max} audio sources","err.audioLoad":"Failed to load audio, try another file","err.processFailed":"Processing failed","err.posterFailed":"Failed to render cover","err.canvas":"Canvas unavailable","err.imageRead":"Failed to read image, try another","err.notImage":"Please choose an image file","err.fileType":"Only image or video files are supported","err.saveDrive":"Failed to save to drive","msg.processing":"Exporting…","msg.exportPrepare":"Preparing media…","msg.exportUpload":"Uploading media…","msg.exportEncode":"Encoding video…","msg.exportDownload":"Receiving result…","msg.exportingHint":"Please wait. The result will be returned automatically when export finishes.","msg.done":"Done ✓","msg.loading":"Loading media…","msg.exported":"Exported: ","msg.saving":"Saving…","msg.saved":"Saved to drive ✓","lbl.ratioSection":"Frame ratio (crop, no distortion)","lbl.dragToReposition":"↔ Drag the preview to reposition the crop","lbl.sizeSection":"Export size (px; cover center-crop when ratios differ)","lbl.currentOut":"Output","lbl.zoomSize":"Size","lbl.noScale":"(no scaling)","lbl.coverNote":"· center-cropped (cover) when ratios differ, no distortion","lbl.audioTrackHint":"♪ Audio track (+ on the right to add music, mixed with original)","lbl.volume":"Volume","lbl.volNote":"(preview caps at 100%, export uses the set value)","lbl.music":"Music","kbd.fit":"⇧ F","poster.title":"Pick a cover frame","panel.title":"Media Editor","panel.subtitle":"Upload an image / video — crop · filters · text · export","panel.pick":"Click to choose an image or video","panel.pickHint":"Images via Filerobot · videos: trim/mute/cover"},es:{"tool.trim":"Editar","tool.crop":"Recortar","tool.tune":"Ajustar color","tool.filter":"Filtros","tool.annotate":"Anotar","tool.sticker":"Stickers","tool.resize":"Proporción","tune.brightness":"Brillo","tune.contrast":"Contraste","tune.saturation":"Saturación","tune.gamma":"Gamma","tune.temperature":"Temperatura","tune.tint":"Tinte","tune.vibrance":"Intensidad","tune.highlights":"Altas luces","tune.shadows":"Sombras","tune.whites":"Blancos","tune.blacks":"Negros","tune.lightSense":"Luz","tune.sharpen":"Enfoque","tune.clarity":"Claridad","tune.grain":"Grano","tune.fade":"Desvanecer","tune.vignette":"Viñeta","overlay.select":"Seleccionar","overlay.pen":"Pincel","overlay.eraser":"Borrador","overlay.line":"Línea","overlay.arrow":"Flecha","overlay.rect":"Rectángulo","overlay.ellipse":"Elipse","overlay.text":"Texto","overlay.color":"Color","overlay.width":"Grosor","overlay.fontSize":"Tamaño","overlay.font":"Fuente","overlay.align":"Alinear","overlay.background":"Fondo","overlay.copySelected":"Copiar","overlay.delSelected":"Eliminar seleccionado","overlay.editSelected":"Editar","overlay.pickImage":"Elegir imagen","overlay.hint":"Toca un emoji/imagen para añadirlo → arrastra para colocarlo, arrastra el tirador morado para escalar","overlay.textPlaceholder":"Escribe texto, Enter para confirmar","filter.none":"Original","filter.bw":"Blanco y negro","filter.sepia":"Sepia","filter.warm":"Cálido","filter.cool":"Frío","filter.vivid":"Intenso","ratio.orig":"Original","ratio.free":"Libre","ratio.9:16":"Vertical 9:16","ratio.16:9":"Horizontal 16:9","ratio.1:1":"Cuadrado 1:1","ratio.4:5":"Vertical 4:5","ratio.3:4":"Vertical 3:4","ratio.2:3":"Vertical 2:3","ratio.1.91:1":"Panorámico 1.91:1","act.fit":"Ajustar","act.zoomFit":"Ajustar a pantalla","act.zoomTo":"Zoom al {value}%","act.split":"Dividir","act.copy":"Copiar","act.delete":"Eliminar","act.restore":"Restablecer","act.deleteMusic":"Quitar música","act.cancel":"Cancelar","act.exportPoster":"Exportar portada","act.exporting":"Exportando…","act.poster":"🖼 Portada","act.again":"Descargar de nuevo","act.saveDrive":"Guardar en disco","act.changeImage":"← Cambiar imagen","act.changeVideo":"← Cambiar archivo","crop.rotateLeft":"↺ Girar a la izquierda","crop.flipX":"⇋ Voltear horizontal","crop.flipY":"⇵ Voltear vertical","crop.rotateLeftShort":"Giro","crop.flipXShort":"Flip","crop.flipYShort":"Flip","tip.close":"Cerrar (cambiar archivo)","tip.undo":"Deshacer","tip.redo":"Rehacer","tip.resetOpened":"Restablecer al archivo abierto","tip.previewZoom":"Zoom de vista previa","tip.previewZoomOut":"Reducir vista previa","tip.previewZoomIn":"Ampliar vista previa","tip.previewZoomFit":"Ajustar vista previa","tip.previewPointer":"Herramienta de puntero","tip.previewPan":"Mano: desplazar lienzo","tip.poster":"Previsualizar y elegir portada","tip.keepAudio":"Activar/desactivar audio original (mezclado con música; la vista previa lo refleja)","tip.split":"Dividir el clip actual en el cursor","tip.zoomOut":"Reducir línea de tiempo (Ctrl+rueda)","tip.zoomIn":"Ampliar línea de tiempo (Ctrl+rueda)","tip.fit":"Ajustar al ancho","tip.addVideo":"Añadir clip de vídeo","tip.addAudio":"Añadir música (archivo de audio o vídeo con sonido para extraer la pista; se mezcla con el original)","tip.dupClip":"Duplicar clip (insertar después)","tip.delClip":"Eliminar clip","tip.lockAspect":"Bloquear proporción","tip.dblConfirm":"Doble clic para confirmar recorte","err.notVideo":"Elige un archivo de vídeo","err.maxVideo":"Máximo {max} vídeos","err.videoLoad":"No se pudo cargar el vídeo, prueba con otro archivo","err.notAudio":"Elige un audio (mp3/wav/m4a) o un vídeo con sonido (se extrae automáticamente)","err.maxAudio":"Máximo {max} audios","err.audioLoad":"No se pudo cargar el audio, prueba con otro archivo","err.processFailed":"Error de procesamiento","err.posterFailed":"No se pudo renderizar la portada","err.canvas":"Canvas no disponible","err.imageRead":"No se pudo leer la imagen, prueba con otra","err.notImage":"Elige un archivo de imagen","err.fileType":"Solo se admiten archivos de imagen o vídeo","err.saveDrive":"No se pudo guardar en disco","msg.processing":"Exportando…","msg.exportPrepare":"Preparando medios…","msg.exportUpload":"Subiendo medios…","msg.exportEncode":"Codificando video…","msg.exportDownload":"Recibiendo resultado…","msg.exportingHint":"Espera un momento. El resultado se devolverá automáticamente al finalizar.","msg.done":"Listo ✓","msg.loading":"Cargando medios…","msg.exported":"Exportado: ","msg.saving":"Guardando…","msg.saved":"Guardado en disco ✓","lbl.ratioSection":"Proporción de imagen (recorte, sin deformar)","lbl.dragToReposition":"↔ Arrastra la vista previa para reposicionar el recorte","lbl.sizeSection":"Tamaño de exportación (px; recorte cover centrado si la proporción difiere)","lbl.currentOut":"Salida","lbl.zoomSize":"Tamaño","lbl.noScale":"(sin escala)","lbl.coverNote":"· recorte centrado (cover) cuando la proporción difiere, sin deformar","lbl.audioTrackHint":"♪ Pista de audio (+ a la derecha para añadir música, mezclada con el original)","lbl.volume":"Volumen","lbl.volNote":"(la vista previa limita a 100%, la exportación usa el valor definido)","lbl.music":"Música","kbd.fit":"⇧ F","poster.title":"Elegir portada","panel.title":"Editor multimedia","panel.subtitle":"Sube una imagen / vídeo — recorta · filtros · texto · exporta","panel.pick":"Haz clic para elegir una imagen o vídeo","panel.pickHint":"Imágenes con Filerobot · vídeos: cortar/silenciar/portada"},"zh-Hant":Object.fromEntries(Object.entries(e).map(([e,o])=>[e,t(o)]))};function i(e,o,t){let i=a[e]?.[o]??a.zh[o]??o;if(t)for(const[e,o]of Object.entries(t))i=i.replaceAll(`{${e}}`,String(o));return i}var r=[{platform:"tiktok",postType:"video",label:"TikTok Video",shortLabel:"TT·Video",ratio:"9:16",imageSize:"1440x2560",videoRatio:"9:16",videoResolution:"720p"},{platform:"instagram",postType:"post",label:"Instagram Post",shortLabel:"IG·Post",ratio:"1:1",imageSize:"2048x2048"},{platform:"instagram",postType:"reels",label:"Instagram Reels",shortLabel:"IG·Reels",ratio:"9:16",imageSize:"1440x2560",videoRatio:"9:16",videoResolution:"720p"},{platform:"instagram",postType:"story",label:"Instagram Story",shortLabel:"IG·Story",ratio:"9:16",imageSize:"1440x2560",videoRatio:"9:16",videoResolution:"720p"},{platform:"facebook",postType:"post",label:"Facebook Post",shortLabel:"FB·Post",ratio:"1:1",imageSize:"2048x2048"},{platform:"facebook",postType:"reels",label:"Facebook Reels",shortLabel:"FB·Reels",ratio:"9:16",imageSize:"1440x2560",videoRatio:"9:16",videoResolution:"720p"},{platform:"youtube",postType:"video",label:"YouTube Video",shortLabel:"YT·Video",ratio:"16:9",imageSize:"2560x1440",videoRatio:"16:9",videoResolution:"1080p"},{platform:"youtube",postType:"shorts",label:"YouTube Shorts",shortLabel:"YT·Shorts",ratio:"9:16",imageSize:"1440x2560",videoRatio:"9:16",videoResolution:"720p"},{platform:"pinterest",postType:"pin",label:"Pinterest Pin",shortLabel:"PIN",ratio:"2:3",imageSize:"1664x2496",videoRatio:"9:16",videoResolution:"720p"},{platform:"x",postType:"post",label:"X Post",shortLabel:"X·Post",ratio:"16:9",imageSize:"2560x1440",videoRatio:"16:9",videoResolution:"720p"},{platform:"linkedin",postType:"post",label:"LinkedIn Post",shortLabel:"LI·Post",ratio:"1:1",imageSize:"2048x2048"},{platform:"linkedin",postType:"video",label:"LinkedIn Video",shortLabel:"LI·Video",ratio:"16:9",imageSize:"2560x1440",videoRatio:"16:9",videoResolution:"1080p"},{platform:"threads",postType:"post",label:"Threads Post",shortLabel:"TH·Post",ratio:"1:1",imageSize:"2048x2048"},{platform:"telegram",postType:"post",label:"Telegram Post",shortLabel:"TG·Post",ratio:"1:1",imageSize:"2048x2048",videoRatio:"9:16",videoResolution:"720p"},{platform:"reddit",postType:"post",label:"Reddit Post",shortLabel:"RD·Post",ratio:"16:9",imageSize:"2560x1440",videoRatio:"16:9",videoResolution:"720p"}],l={"1:1":"方形 1:1","4:5":"竖图 4:5","3:4":"竖图 3:4","9:16":"竖屏 9:16","16:9":"横屏 16:9","2:3":"竖图 2:3","1.91:1":"横幅 1.91:1"};function n(e){const[o,t]=e.split(":").map(Number);return o&&t?o/t:1}function p(e){const o=new Set,t=[];for(const a of e)a&&!o.has(a)&&(o.add(a),t.push({ratio:a,value:n(a),label:l[a]??a}));return t}var s=p(["1:1","4:5","3:4","2:3","9:16","16:9","1.91:1"]),c=p(["9:16","16:9","1:1","4:5","3:4","2:3","1.91:1"]);function d(e=r){const o=new Set,t=[];for(const a of e){if(!a.videoRatio)continue;const e=`${a.platform}:${a.postType}:${a.videoRatio}`;if(o.has(e))continue;o.add(e);const i=a.label.split(" ").slice(0,-1).join(" ")||a.label;t.push({platform:a.platform,postType:a.postType,label:`${i} ${a.videoRatio}`,ratio:a.videoRatio,value:n(a.videoRatio)})}return t}var m=d();function u(e=r){const o=new Map;for(const t of e){const e=o.get(t.platform);(!e||"post"!==e.postType&&"post"===t.postType)&&o.set(t.platform,t)}return Array.from(o.values()).map(e=>{const[o,t]=e.imageSize.split("x").map(Number),a=e.label.split(" ").slice(0,-1).join(" ")||e.label;return{platform:e.platform,label:`${a} ${e.ratio}`,ratio:e.ratio,value:n(e.ratio),w:o,h:t}})}var v=u();function g(e,o){return e>=1?{w:2*Math.round(o*e/2),h:o}:{w:o,h:2*Math.round(o/e/2)}}function f(e=r){const o=new Set,t=[];for(const a of e){if(!a.videoRatio||!a.videoResolution)continue;const e="1080p"===a.videoResolution?1080:720,{w:i,h:r}=g(n(a.videoRatio),e),l=`${i}x${r}`;o.has(l)||(o.add(l),t.push({label:`${a.shortLabel} ${i}×${r}`,w:i,h:r}))}return t}var h=f();function b(e,o){if(e.isDuplicated)return{};if(0!==(e.rotation??0))return{};const t=o.adjustments?.rotation??0;return t?{rotation:-t}:{}}export{r as DEFAULT_PLATFORM_TARGETS,a as EDITOR_MESSAGES,v as IMAGE_PLATFORM_PRESETS,s as IMAGE_RATIO_PRESETS,m as VIDEO_PLATFORM_RATIO_PRESETS,c as VIDEO_RATIO_PRESETS,h as VIDEO_SIZE_PRESETS,u as buildImagePlatformPresets,d as buildVideoPlatformRatioPresets,f as buildVideoSizePresets,b as compensateAnnotationRotation,n as parseRatio,i as tEditor,t as toHant};