@imgly/plugin-ai-video-generation-web
Version:
AI video generation plugin for the CE.SDK editor
13 lines • 84.9 kB
JavaScript
var br=class{constructor(e,t,r){this.assetStoreName="assets",this.blobStoreName="blobs",this.db=null,this.id=e,this.engine=t,this.dbName=r?.dbName??`ly.img.assetSource/${e}`,this.dbVersion=r?.dbVersion??1}async initialize(){if(!this.db)return new Promise((e,t)=>{let r=indexedDB.open(this.dbName,this.dbVersion);r.onerror=i=>{t(new Error(`Failed to open IndexedDB: ${i.target.error}`))},r.onupgradeneeded=i=>{let n=i.target.result;n.objectStoreNames.contains(this.assetStoreName)||n.createObjectStore(this.assetStoreName,{keyPath:"id"}),n.objectStoreNames.contains(this.blobStoreName)||n.createObjectStore(this.blobStoreName,{keyPath:"id"})},r.onsuccess=i=>{this.db=i.target.result,e()}})}close(){this.db&&(this.db.close(),this.db=null)}async findAssets(e){if(await this.initialize(),!this.db)throw new Error("Database not initialized");try{let t=(await this.getAllAssets("asc")).reduce((c,l)=>{let u=e.locale??"en",d="",p=[];l.label!=null&&typeof l.label=="object"&&l.label[u]&&(d=l.label[u]),l.tags!=null&&typeof l.tags=="object"&&l.tags[u]&&(p=l.tags[u]);let g={...l,label:d,tags:p};return this.filterAsset(g,e)&&c.push(g),c},[]);t=await this.restoreBlobUrls(t),t=this.sortAssets(t,e);let{page:r,perPage:i}=e,n=r*i,o=n+i,a=t.slice(n,o),s=o<t.length?r+1:void 0;return{assets:a,currentPage:r,nextPage:s,total:t.length}}catch(t){console.error("Error finding assets:",t);return}}async getGroups(){if(await this.initialize(),!this.db)throw new Error("Database not initialized");return new Promise((e,t)=>{let r=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).getAll();r.onsuccess=()=>{let i=new Set;r.result.forEach(o=>{o.groups&&Array.isArray(o.groups)&&o.groups.forEach(a=>i.add(a))});let n=[...i];e(n)},r.onerror=()=>{t(new Error(`Failed to get groups: ${r.error}`))}})}addAsset(e){this.initialize().then(async()=>{if(!this.db)throw new Error("Database not initialized");let t=this.db.transaction(this.assetStoreName,"readwrite"),r=t.objectStore(this.assetStoreName),i=new Set;R(e,o=>{i.add(o)}),setTimeout(()=>{this.storeBlobUrls([...i])});let n={...e,meta:{...e.meta,insertedAt:e.meta?.insertedAt||Date.now()}};r.put(n),t.onerror=()=>{console.error(`Failed to add asset: ${t.error}`)}}).catch(t=>{console.error("Error initializing database:",t)})}async removeAsset(e){let t=await this.getAsset(e);return this.initialize().then(()=>{if(!this.db)throw new Error("Database not initialized");let r=this.db.transaction(this.assetStoreName,"readwrite");r.objectStore(this.assetStoreName).delete(e),r.oncomplete=()=>{R(t,i=>{this.removeBlob(i)}),this.engine.asset.assetSourceContentsChanged(this.id)},r.onerror=()=>{console.error(`Failed to remove asset: ${r.error}`)}}).catch(r=>{console.error("Error initializing database:",r)})}async removeBlob(e){return this.initialize().then(()=>{if(!this.db)throw new Error("Database not initialized");let t=this.db.transaction(this.blobStoreName,"readwrite");t.objectStore(this.blobStoreName).delete(e),t.onerror=()=>{console.error(`Failed to remove blob: ${t.error}`)}}).catch(t=>{console.error("Error initializing database:",t)})}async getAllAssets(e="desc"){return new Promise((t,r)=>{let i=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).getAll();i.onsuccess=()=>{let n=i.result;n.sort((o,a)=>{let s=o.meta?.insertedAt||o._insertedAt||Date.now(),c=a.meta?.insertedAt||a._insertedAt||Date.now();return e==="asc"?s-c:c-s}),t(n)},i.onerror=()=>{r(new Error(`Failed to get assets: ${i.error}`))}})}async getAsset(e){return new Promise((t,r)=>{let i=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).get(e);i.onsuccess=()=>{t(i.result)},i.onerror=()=>{r(new Error(`Failed to get blob: ${i.error}`))}})}async getBlob(e){return new Promise((t,r)=>{let i=this.db.transaction(this.blobStoreName,"readonly").objectStore(this.blobStoreName).get(e);i.onsuccess=()=>{t(i.result)},i.onerror=()=>{r(new Error(`Failed to get blob: ${i.error}`))}})}async createBlobUrlFromStore(e){let t=await this.getBlob(e);return t!=null?URL.createObjectURL(t.blob):e}async storeBlobUrls(e){let t={};return await Promise.all(e.map(async r=>{let i=await(await fetch(r)).blob();t[r]=i})),this.initialize().then(async()=>{if(!this.db)throw new Error("Database not initialized");let r=this.db.transaction(this.blobStoreName,"readwrite"),i=r.objectStore(this.blobStoreName);Object.entries(t).forEach(([n,o])=>{let a={id:n,blob:o};i.put(a)}),r.onerror=()=>{console.error(`Failed to add blobs: ${r.error}`)}}).catch(r=>{console.error("Error initializing database:",r)})}async restoreBlobUrls(e){let t={},r=new Set;return R(e,i=>{r.add(i)}),await Promise.all([...r].map(async i=>{let n=await this.createBlobUrlFromStore(i);t[i]=n})),R(e,i=>t[i]??i)}filterAsset(e,t){let{query:r,tags:i,groups:n,excludeGroups:o}=t;if(r&&r.trim()!==""){let a=r.trim().toLowerCase().split(" "),s=e.label?.toLowerCase()??"",c=e.tags?.map(l=>l.toLowerCase())??[];if(!a.every(l=>s.includes(l)||c.some(u=>u.includes(l))))return!1}if(i){let a=Array.isArray(i)?i:[i];if(a.length>0&&(!e.tags||!a.every(s=>e.tags?.includes(s))))return!1}return!(n&&n.length>0&&(!e.groups||!n.some(a=>e.groups?.includes(a)))||o&&o.length>0&&e.groups&&e.groups.some(a=>o.includes(a)))}sortAssets(e,t){let{sortingOrder:r,sortKey:i,sortActiveFirst:n}=t,o=[...e];return!r||r==="None"||(i?o.sort((a,s)=>{let c,l;return i==="id"?(c=a.id,l=s.id):(c=a.meta?.[i]??null,l=s.meta?.[i]??null),c==null?r==="Ascending"?-1:1:l==null?r==="Ascending"?1:-1:typeof c=="string"&&typeof l=="string"?r==="Ascending"?c.localeCompare(l):l.localeCompare(c):r==="Ascending"?c<l?-1:c>l?1:0:c>l?-1:c<l?1:0}):r==="Descending"&&o.reverse(),n&&o.sort((a,s)=>a.active&&!s.active?-1:!a.active&&s.active?1:0)),o}};function R(e,t,r=""){if(e===null||typeof e!="object")return e;if(Array.isArray(e)){for(let i=0;i<e.length;i++){let n=r?`${r}[${i}]`:`[${i}]`;if(typeof e[i]=="string"&&e[i].startsWith("blob:")){let o=t(e[i],n);typeof o=="string"&&(e[i]=o)}else e[i]=R(e[i],t,n)}return e}for(let i in e)if(Object.prototype.hasOwnProperty.call(e,i)){let n=e[i],o=r?`${r}.${i}`:i;if(typeof n=="string"&&n.startsWith("blob:")){let a=t(n,o);typeof a=="string"&&(e[i]=a)}else e[i]=R(n,t,o)}return e}var yr=class{constructor(e,t,r){this.id=e,this.cesdk=t,this.assetSourceIds=r}async findAssets(e){try{let t=this.assetSourceIds.map(u=>this.cesdk.engine.asset.findAssets(u,{...e,perPage:9999,page:0})),r=await Promise.all(t),i=[];r.forEach(u=>{u?.assets&&(i=i.concat(u.assets))}),i.sort((u,d)=>{let p=u.meta?.insertedAt||0;return(d.meta?.insertedAt||0)-p});let{page:n,perPage:o}=e,a=n*o,s=a+o,c=i.slice(a,s),l=s<i.length?n+1:void 0;return{assets:c,currentPage:n,nextPage:l,total:i.length}}catch(t){console.error("Error finding assets:",t);return}}async getGroups(){let e=this.assetSourceIds.map(i=>this.cesdk.engine.asset.getGroups(i)),t=await Promise.all(e),r=new Set;return t.forEach(i=>{i.forEach(n=>r.add(n))}),Array.from(r)}addAsset(e){throw new Error("AggregatedAssetSource does not support adding assets")}removeAsset(e){throw new Error("AggregatedAssetSource does not support removing assets")}};var hr=typeof global=="object"&&global&&global.Object===Object&&global,bt=hr,vr=typeof self=="object"&&self&&self.Object===Object&&self,wr=bt||vr||Function("return this")(),j=wr,kr=j.Symbol,V=kr,yt=Object.prototype,Ir=yt.hasOwnProperty,Ar=yt.toString,J=V?V.toStringTag:void 0;function Sr(e){var t=Ir.call(e,J),r=e[J];try{e[J]=void 0;var i=!0}catch{}var n=Ar.call(e);return i&&(t?e[J]=r:delete e[J]),n}var Cr=Sr,xr=Object.prototype,Er=xr.toString;function Mr(e){return Er.call(e)}var jr=Mr,$r="[object Null]",Tr="[object Undefined]",Xe=V?V.toStringTag:void 0;function _r(e){return e==null?e===void 0?Tr:$r:Xe&&Xe in Object(e)?Cr(e):jr(e)}var ae=_r;function Lr(e){return e!=null&&typeof e=="object"}var Re=Lr,Yu=Array.isArray;function Or(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var ht=Or,Pr="[object AsyncFunction]",Nr="[object Function]",Dr="[object GeneratorFunction]",zr="[object Proxy]";function Fr(e){if(!ht(e))return!1;var t=ae(e);return t==Nr||t==Dr||t==Pr||t==zr}var Rr=Fr,Vr=j["__core-js_shared__"],je=Vr,et=function(){var e=/[^.]+$/.exec(je&&je.keys&&je.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function Ur(e){return!!et&&et in e}var Br=Ur,Gr=Function.prototype,qr=Gr.toString;function Hr(e){if(e!=null){try{return qr.call(e)}catch{}try{return e+""}catch{}}return""}var D=Hr,Zr=/[\\^$.*+?()[\]{}|]/g,Qr=/^\[object .+?Constructor\]$/,Yr=Function.prototype,Kr=Object.prototype,Wr=Yr.toString,Jr=Kr.hasOwnProperty,Xr=RegExp("^"+Wr.call(Jr).replace(Zr,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function ei(e){if(!ht(e)||Br(e))return!1;var t=Rr(e)?Xr:Qr;return t.test(D(e))}var ti=ei;function ri(e,t){return e?.[t]}var ii=ri;function ni(e,t){var r=ii(e,t);return ti(r)?r:void 0}var U=ni,ai=U(j,"WeakMap"),Oe=ai;function oi(e,t){return e===t||e!==e&&t!==t}var li=oi,si=9007199254740991;function ui(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=si}var ci=ui,Ku=Object.prototype,di="[object Arguments]";function gi(e){return Re(e)&&ae(e)==di}var tt=gi,vt=Object.prototype,pi=vt.hasOwnProperty,fi=vt.propertyIsEnumerable,Wu=tt(function(){return arguments}())?tt:function(e){return Re(e)&&pi.call(e,"callee")&&!fi.call(e,"callee")},wt=typeof exports=="object"&&exports&&!exports.nodeType&&exports,rt=wt&&typeof module=="object"&&module&&!module.nodeType&&module,mi=rt&&rt.exports===wt,it=mi?j.Buffer:void 0,Ju=it?it.isBuffer:void 0,bi="[object Arguments]",yi="[object Array]",hi="[object Boolean]",vi="[object Date]",wi="[object Error]",ki="[object Function]",Ii="[object Map]",Ai="[object Number]",Si="[object Object]",Ci="[object RegExp]",xi="[object Set]",Ei="[object String]",Mi="[object WeakMap]",ji="[object ArrayBuffer]",$i="[object DataView]",Ti="[object Float32Array]",_i="[object Float64Array]",Li="[object Int8Array]",Oi="[object Int16Array]",Pi="[object Int32Array]",Ni="[object Uint8Array]",Di="[object Uint8ClampedArray]",zi="[object Uint16Array]",Fi="[object Uint32Array]",I={};I[Ti]=I[_i]=I[Li]=I[Oi]=I[Pi]=I[Ni]=I[Di]=I[zi]=I[Fi]=!0;I[bi]=I[yi]=I[ji]=I[hi]=I[$i]=I[vi]=I[wi]=I[ki]=I[Ii]=I[Ai]=I[Si]=I[Ci]=I[xi]=I[Ei]=I[Mi]=!1;function Ri(e){return Re(e)&&ci(e.length)&&!!I[ae(e)]}var Vi=Ri;function Ui(e){return function(t){return e(t)}}var Bi=Ui,kt=typeof exports=="object"&&exports&&!exports.nodeType&&exports,re=kt&&typeof module=="object"&&module&&!module.nodeType&&module,Gi=re&&re.exports===kt,$e=Gi&&bt.process,qi=function(){try{var e=re&&re.require&&re.require("util").types;return e||$e&&$e.binding&&$e.binding("util")}catch{}}(),nt=qi,at=nt&&nt.isTypedArray,Xu=at?Bi(at):Vi,Hi=Object.prototype,ec=Hi.hasOwnProperty;function Zi(e,t){return function(r){return e(t(r))}}var Qi=Zi,tc=Qi(Object.keys,Object),Yi=Object.prototype,rc=Yi.hasOwnProperty,Ki=U(Object,"create"),ie=Ki;function Wi(){this.__data__=ie?ie(null):{},this.size=0}var Ji=Wi;function Xi(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var en=Xi,tn="__lodash_hash_undefined__",rn=Object.prototype,nn=rn.hasOwnProperty;function an(e){var t=this.__data__;if(ie){var r=t[e];return r===tn?void 0:r}return nn.call(t,e)?t[e]:void 0}var on=an,ln=Object.prototype,sn=ln.hasOwnProperty;function un(e){var t=this.__data__;return ie?t[e]!==void 0:sn.call(t,e)}var cn=un,dn="__lodash_hash_undefined__";function gn(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=ie&&t===void 0?dn:t,this}var pn=gn;function B(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var i=e[t];this.set(i[0],i[1])}}B.prototype.clear=Ji;B.prototype.delete=en;B.prototype.get=on;B.prototype.has=cn;B.prototype.set=pn;var ot=B;function fn(){this.__data__=[],this.size=0}var mn=fn;function bn(e,t){for(var r=e.length;r--;)if(li(e[r][0],t))return r;return-1}var he=bn,yn=Array.prototype,hn=yn.splice;function vn(e){var t=this.__data__,r=he(t,e);if(r<0)return!1;var i=t.length-1;return r==i?t.pop():hn.call(t,r,1),--this.size,!0}var wn=vn;function kn(e){var t=this.__data__,r=he(t,e);return r<0?void 0:t[r][1]}var In=kn;function An(e){return he(this.__data__,e)>-1}var Sn=An;function Cn(e,t){var r=this.__data__,i=he(r,e);return i<0?(++this.size,r.push([e,t])):r[i][1]=t,this}var xn=Cn;function G(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var i=e[t];this.set(i[0],i[1])}}G.prototype.clear=mn;G.prototype.delete=wn;G.prototype.get=In;G.prototype.has=Sn;G.prototype.set=xn;var ve=G,En=U(j,"Map"),ne=En;function Mn(){this.size=0,this.__data__={hash:new ot,map:new(ne||ve),string:new ot}}var jn=Mn;function $n(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var Tn=$n;function _n(e,t){var r=e.__data__;return Tn(t)?r[typeof t=="string"?"string":"hash"]:r.map}var we=_n;function Ln(e){var t=we(this,e).delete(e);return this.size-=t?1:0,t}var On=Ln;function Pn(e){return we(this,e).get(e)}var Nn=Pn;function Dn(e){return we(this,e).has(e)}var zn=Dn;function Fn(e,t){var r=we(this,e),i=r.size;return r.set(e,t),this.size+=r.size==i?0:1,this}var Rn=Fn;function q(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var i=e[t];this.set(i[0],i[1])}}q.prototype.clear=jn;q.prototype.delete=On;q.prototype.get=Nn;q.prototype.has=zn;q.prototype.set=Rn;var It=q;function Vn(){this.__data__=new ve,this.size=0}var Un=Vn;function Bn(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var Gn=Bn;function qn(e){return this.__data__.get(e)}var Hn=qn;function Zn(e){return this.__data__.has(e)}var Qn=Zn,Yn=200;function Kn(e,t){var r=this.__data__;if(r instanceof ve){var i=r.__data__;if(!ne||i.length<Yn-1)return i.push([e,t]),this.size=++r.size,this;r=this.__data__=new It(i)}return r.set(e,t),this.size=r.size,this}var Wn=Kn;function oe(e){var t=this.__data__=new ve(e);this.size=t.size}oe.prototype.clear=Un;oe.prototype.delete=Gn;oe.prototype.get=Hn;oe.prototype.has=Qn;oe.prototype.set=Wn;var Jn=Object.prototype,ic=Jn.propertyIsEnumerable,Xn=U(j,"DataView"),Pe=Xn,ea=U(j,"Promise"),Ne=ea,ta=U(j,"Set"),De=ta,lt="[object Map]",ra="[object Object]",st="[object Promise]",ut="[object Set]",ct="[object WeakMap]",dt="[object DataView]",ia=D(Pe),na=D(ne),aa=D(Ne),oa=D(De),la=D(Oe),F=ae;(Pe&&F(new Pe(new ArrayBuffer(1)))!=dt||ne&&F(new ne)!=lt||Ne&&F(Ne.resolve())!=st||De&&F(new De)!=ut||Oe&&F(new Oe)!=ct)&&(F=function(e){var t=ae(e),r=t==ra?e.constructor:void 0,i=r?D(r):"";if(i)switch(i){case ia:return dt;case na:return lt;case aa:return st;case oa:return ut;case la:return ct}return t});var nc=j.Uint8Array,sa="__lodash_hash_undefined__";function ua(e){return this.__data__.set(e,sa),this}var ca=ua;function da(e){return this.__data__.has(e)}var ga=da;function ze(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new It;++t<r;)this.add(e[t])}ze.prototype.add=ze.prototype.push=ca;ze.prototype.has=ga;var gt=V?V.prototype:void 0,ac=gt?gt.valueOf:void 0,pa=Object.prototype,oc=pa.hasOwnProperty,fa=Object.prototype,lc=fa.hasOwnProperty,sc=new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,"i"),uc=new RegExp(/[A-Fa-f0-9]{1}/,"g"),cc=new RegExp(/[A-Fa-f0-9]{2}/,"g");async function At(e,t){if(e.startsWith("buffer:")){let r=await t.editor.getMimeType(e),i=t.editor.getBufferLength(e),n=t.editor.getBufferData(e,0,i),o=new Uint8Array(n),a=new Blob([o],{type:r});return URL.createObjectURL(a)}else return e}async function ma(e,t){let r=await At(e,t);return new Promise((i,n)=>{let o=new Image;o.onload=()=>{i({width:o.width,height:o.height})},o.onerror=n,o.src=r})}async function ba(e,t,r){let i,n=t.block.getFill(e),o=t.block.getSourceSet(n,"fill/image/sourceSet"),[a]=o;if(a==null){if(i=t.block.getString(n,"fill/image/imageFileURI"),i==null)throw new Error("No image source/uri found")}else i=a.uri;if(r?.throwErrorIfSvg&&await t.editor.getMimeType(i)==="image/svg+xml")throw new Error("SVG images are not supported");return At(i,t)}function ya(e){return e!==void 0}var ha=ya;function le(e,t){let r=t?.i18n?.getLocale?.()||"en";return{engine:e,cesdk:t,locale:r}}function se(e,t,r,i,n){if(t?.default!==void 0){let o=t.default;return typeof o!="function"?o:o(r)}return i!==void 0?i:n}var ue=class St{constructor(){this.actions=new Map,this.subscribers=new Map}static get(){let t="__imgly_action_registry__",r=typeof window<"u"?window:globalThis;return r[t]||(r[t]=new St),r[t]}register(t){return this.actions.set(t.id,t),this.notifySubscribers(t,"registered"),()=>{this.actions.get(t.id)===t&&(this.actions.delete(t.id),this.notifySubscribers(t,"unregistered"))}}getAll(){return Array.from(this.actions.values())}getBy(t){return this.getAll().filter(r=>this.matchesFilters(r,t))}subscribe(t){return this.subscribers.set(t,null),()=>{this.subscribers.delete(t)}}subscribeBy(t,r){return this.subscribers.set(r,t),()=>{this.subscribers.delete(r)}}notifySubscribers(t,r){this.subscribers.forEach((i,n)=>{if(i===null){n(t,r);return}this.matchesFilters(t,i)&&n(t,r)})}matchesFilters(t,r){return!(r.type&&t.type!==r.type||r.pluginId&&t.type==="plugin"&&t.pluginId!==r.pluginId||r.id&&t.id!==r.id||r.kind&&(t.type!=="quick"||t.kind!==r.kind))}},va=class Ct{constructor(){this.providers=new Map}static get(){let t="__imgly_provider_registry__",r=typeof window<"u"?window:globalThis;return r[t]||(r[t]=new Ct),r[t]}register(t){return this.providers.has(t.provider.id)&&console.warn(`Provider with ID "${t.provider.id}" is already registered`),this.providers.set(t.provider.id,t),()=>{this.providers.get(t.provider.id)===t&&this.providers.delete(t.provider.id)}}getAll(){return Array.from(this.providers.values())}getById(t){return this.providers.get(t)}getByKind(t){return this.getAll().filter(({provider:r})=>r.kind===t)}};function wa(e){let t=e.filter(r=>!!r);return r=>async(i,n)=>{let o=[],a=l=>{o.push(l)},s=async(l,u,d)=>{if(l>=t.length)return r(u,d);let p=t[l],g=async(f,y)=>s(l+1,f,y),b={...d,addDisposer:a};return p(u,b,g)},c={...n,addDisposer:a};return{result:await s(0,i,c),dispose:async()=>{for(let l=o.length-1;l>=0;l--)try{await o[l]()}catch(u){console.error("Error in disposer:",u)}o.length=0}}}}function ka({enable:e=!0}){return async(t,r,i)=>{if(!e)return i(t,r);console.group("[GENERATION]"),console.log("Generating with input:",JSON.stringify(t,null,2));let n,o=Date.now();try{return n=await i(t,r),n}finally{n!=null&&(console.log(`Generation took ${Date.now()-o}ms`),console.log("Generation result:",JSON.stringify(n,null,2))),console.groupEnd()}}}var Ia=ka;var Te="ly.img.ai.temp";async function Aa(e,t){return e.engine.asset.findAllSources().includes(Te)||e.engine.asset.addLocalSource(Te),e.engine.asset.apply(Te,t)}function Sa(e,t="We encountered an unknown error while generating the asset. Please try again."){if(e===null)return t;if(e instanceof Error)return e.message;if(typeof e=="object"){let r=e;return"message"in r&&typeof r.message=="string"?r.message:"cause"in r&&typeof r.cause=="string"?r.cause:"detail"in r&&typeof r.detail=="object"&&r.detail!==null&&"message"in r.detail&&typeof r.detail.message=="string"?r.detail.message:"error"in r&&typeof r.error=="object"&&r.error!==null&&"message"in r.error&&typeof r.error.message=="string"?r.error.message:t}return typeof e=="string"?e:String(e)||t}function xt(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function Ca(e,t=0,r="image/jpeg",i=.8){return new Promise((n,o)=>{try{let a=document.createElement("video");a.crossOrigin="anonymous",a.style.display="none",a.addEventListener("loadedmetadata",()=>{a.currentTime=Math.min(t,a.duration),a.addEventListener("seeked",()=>{let s=document.createElement("canvas");s.width=a.videoWidth,s.height=a.videoHeight;let c=s.getContext("2d");if(!c){document.body.removeChild(a),o(new Error("Failed to create canvas context"));return}c.drawImage(a,0,0,s.width,s.height);try{let l=s.toDataURL(r,i);document.body.removeChild(a),n(l)}catch(l){document.body.removeChild(a),o(new Error(`Failed to create thumbnail: ${l instanceof Error?l.message:String(l)}`))}},{once:!0})}),a.addEventListener("error",()=>{document.body.removeChild(a),o(new Error(`Failed to load video from ${e}`))}),a.src=e,document.body.appendChild(a)}catch(a){o(a)}})}function xa(e){return typeof e=="object"&&e!==null&&"next"in e&&"return"in e&&"throw"in e&&typeof e.next=="function"&&typeof e.return=="function"&&typeof e.throw=="function"&&Symbol.asyncIterator in e&&typeof e[Symbol.asyncIterator]=="function"}function Ve(e){return e instanceof Error&&e.name==="AbortError"}function Ea(e,t,r){let i=`${t}.iconSetAdded`;e.ui.experimental.hasGlobalStateValue(i)||(e.ui.addIconSet(t,r),e.ui.experimental.setGlobalStateValue(i,!0))}function Et(e,t,r){let i="ai-plugin-version",n="ai-plugin-version-warning-shown";try{let o=e.ui.experimental.getGlobalStateValue(i);o?o!==r&&(e.ui.experimental.getGlobalStateValue(n,!1)||(console.warn(`[IMG.LY AI Plugins] Version mismatch detected!
Plugin "${t}" is using version ${r}, but other AI plugins are using version ${o}.
This may cause compatibility issues. Please ensure all AI plugins (@imgly/plugin-ai-*) use the same version.
Consider updating all AI plugins to the same version for optimal compatibility.`),e.ui.experimental.setGlobalStateValue(n,!0))):e.ui.experimental.setGlobalStateValue(i,r)}catch(o){console.debug("[IMG.LY AI Plugins] Could not check plugin version consistency:",o)}}function Ma(e){let{cesdk:t,panelId:r}=e;r.startsWith("ly.img.ai.")||console.warn(`Dock components for AI generation should open a panel with an id starting with "ly.img.ai." \u2013 "${r}" was provided.`);let i=`${r}.dock`;t.ui.registerComponent(i,({builder:n})=>{let o=t.ui.isPanelOpen(r);n.Button(`${r}.dock.button`,{label:`${r}.dock.label`,isSelected:o,icon:"@imgly/Sparkle",onClick:()=>{t.ui.findAllPanels().forEach(a=>{a.startsWith("ly.img.ai.")&&t.ui.closePanel(a),!o&&a==="//ly.img.panel/assetLibrary"&&t.ui.closePanel(a)}),o?t.ui.closePanel(r):t.ui.openPanel(r)}})})}var Mt=Ma;function ja(){return({engine:e})=>{let t=e.block.findAllSelected();if(t==null||t.length!==1)return!1;let[r]=t;if(!e.block.supportsFill(r)||e.block.getKind(r)==="sticker"||!["//ly.img.ubq/graphic","//ly.img.ubq/page"].includes(e.block.getType(r)))return!1;let i=e.block.getFill(r);return e.block.getType(i)==="//ly.img.ubq/fill/image"}}var jt=ja;function $a(e,t){let{cesdk:r,provider:i,getInput:n,middlewareOptions:o}=t;o?.defaultPrevented()||(console.error("Generation failed:",e),Ta(r,i.output.notification,()=>({input:n?.().input,error:e}))||r.ui.showNotification({type:"error",message:Sa(e)}))}function Ta(e,t,r){let i=t?.error;if(i==null||!(typeof i.show=="function"?i.show(r()):i.show))return!1;let n=typeof i.message=="function"?i.message(r()):i.message??"common.ai-generation.failed",o=i.action!=null?{label:typeof i.action.label=="function"?i.action.label(r()):i.action.label,onClick:()=>{i?.action?.onClick(r())}}:void 0;return e.ui.showNotification({type:"error",message:n,action:o}),!0}var pt=$a,_a="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIzIiBoZWlnaHQ9IjMyMyIgdmlld0JveD0iMCAwIDMyMyAzMjMiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIzMjMiIGhlaWdodD0iMzIzIiBmaWxsPSIjRTlFQkVEIi8+CjxnIG9wYWNpdHk9IjAuMyI+CjxwYXRoIGQ9Ik0xMTYgMTg0VjE5MS41QzExNiAxOTkuNzg0IDEyMi43MTYgMjA2LjUgMTMxIDIwNi41SDE5MUMxOTkuMjg0IDIwNi41IDIwNiAxOTkuNzg0IDIwNiAxOTEuNVYxMzEuNUMyMDYgMTIzLjIxNiAxOTkuMjg0IDExNi41IDE5MSAxMTYuNUwxOTAuOTk1IDEyNi41QzE5My43NTcgMTI2LjUgMTk2IDEyOC43MzkgMTk2IDEzMS41VjE5MS41QzE5NiAxOTQuMjYxIDE5My43NjEgMTk2LjUgMTkxIDE5Ni41SDEzMUMxMjguMjM5IDE5Ni41IDEyNiAxOTQuMjYxIDEyNiAxOTEuNVYxODRIMTE2WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTY2LjQ5NCAxMDUuOTI0QzE2NS44NjkgMTA0LjM0MiAxNjMuNjI5IDEwNC4zNDIgMTYzLjAwNSAxMDUuOTI0TDE1OS43NDUgMTE0LjE5MUMxNTkuNTU0IDExNC42NzQgMTU5LjE3MiAxMTUuMDU3IDE1OC42ODggMTE1LjI0N0wxNTAuNDIyIDExOC41MDhDMTQ4LjgzOSAxMTkuMTMyIDE0OC44MzkgMTIxLjM3MiAxNTAuNDIyIDEyMS45OTZMMTU4LjY4OCAxMjUuMjU2QzE1OS4xNzIgMTI1LjQ0NyAxNTkuNTU0IDEyNS44MjkgMTU5Ljc0NSAxMjYuMzEzTDE2My4wMDUgMTM0LjU3OUMxNjMuNjI5IDEzNi4xNjIgMTY1Ljg2OSAxMzYuMTYyIDE2Ni40OTQgMTM0LjU3OUwxNjkuNzU0IDEyNi4zMTNDMTY5Ljk0NCAxMjUuODI5IDE3MC4zMjcgMTI1LjQ0NyAxNzAuODEgMTI1LjI1NkwxNzkuMDc3IDEyMS45OTZDMTgwLjY2IDEyMS4zNzIgMTgwLjY2IDExOS4xMzIgMTc5LjA3NyAxMTguNTA4TDE3MC44MSAxMTUuMjQ3QzE3MC4zMjcgMTE1LjA1NyAxNjkuOTQ0IDExNC42NzQgMTY5Ljc1NCAxMTQuMTkxTDE2Ni40OTQgMTA1LjkyNFoiIGZpbGw9IiM4RjhGOEYiLz4KPHBhdGggZD0iTTEzMy4wMDUgMTI4LjQyNEMxMzMuNjI5IDEyNi44NDIgMTM1Ljg2OSAxMjYuODQyIDEzNi40OTQgMTI4LjQyNEwxNDEuODc1IDE0Mi4wN0MxNDIuMDY2IDE0Mi41NTMgMTQyLjQ0OCAxNDIuOTM1IDE0Mi45MzIgMTQzLjEyNkwxNTYuNTc3IDE0OC41MDhDMTU4LjE2IDE0OS4xMzIgMTU4LjE2IDE1MS4zNzIgMTU2LjU3NyAxNTEuOTk2TDE0Mi45MzIgMTU3LjM3OEMxNDIuNDQ4IDE1Ny41NjggMTQyLjA2NiAxNTcuOTUxIDE0MS44NzUgMTU4LjQzNEwxMzYuNDk0IDE3Mi4wNzlDMTM1Ljg2OSAxNzMuNjYyIDEzMy42MjkgMTczLjY2MiAxMzMuMDA1IDE3Mi4wNzlMMTI3LjYyMyAxNTguNDM0QzEyNy40MzMgMTU3Ljk1MSAxMjcuMDUgMTU3LjU2OCAxMjYuNTY3IDE1Ny4zNzhMMTEyLjkyMiAxNTEuOTk2QzExMS4zMzkgMTUxLjM3MiAxMTEuMzM5IDE0OS4xMzIgMTEyLjkyMiAxNDguNTA4TDEyNi41NjcgMTQzLjEyNkMxMjcuMDUgMTQyLjkzNSAxMjcuNDMzIDE0Mi41NTMgMTI3LjYyMyAxNDIuMDdMMTMzLjAwNSAxMjguNDI0WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTk1Ljk5OSAxODQuMDA0VjE5MS41MDJDMTk1Ljk5OSAxOTQuMjYzIDE5My43NjEgMTk2LjUwMiAxOTAuOTk5IDE5Ni41MDJIMTQ3LjY2OEwxNzIuODc5IDE1OC42ODRDMTc0LjM2MyAxNTYuNDU4IDE3Ny42MzUgMTU2LjQ1OCAxNzkuMTIgMTU4LjY4NEwxOTUuOTk5IDE4NC4wMDRaIiBmaWxsPSIjOEY4RjhGIi8+CjwvZz4KPC9zdmc+Cg==",Ue=_a;function La(e,t,r){switch(t){case"image":return Oa(e,r[t]);case"video":return Pa(e,r[t]);case"sticker":return Na(e,r[t]);default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function Oa(e,t){let r=t.width,i=t.height;return{id:e,meta:{previewUri:Ue,fillType:"//ly.img.ubq/fill/image",kind:"image",width:r,height:i}}}function Pa(e,t){let r=t.width,i=t.height;return{id:e,label:t.label,meta:{previewUri:Ue,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:r,height:i}}}function Na(e,t){let r=t.width,i=t.height;return{id:e,meta:{previewUri:Ue,fillType:"//ly.img.ubq/fill/image",kind:"sticker",width:r,height:i}}}var Da=La;async function za(e,t,r,i){switch(t){case"image":{if(i.kind!=="image")throw new Error(`Output kind does not match the expected type: ${i.kind} (expected: image)`);return Fa(e,r[t],i)}case"video":{if(i.kind!=="video")throw new Error(`Output kind does not match the expected type: ${i.kind} (expected: video)`);return Ra(e,r[t],i)}case"audio":{if(i.kind!=="audio")throw new Error(`Output kind does not match the expected type: ${i.kind} (expected: audio)`);return Va(e,r[t],i)}case"sticker":{if(i.kind!=="sticker")throw new Error(`Output kind does not match the expected type: ${i.kind} (expected: sticker)`);return Ua(e,r[t],i)}default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function Fa(e,t,r){let i=t.width,n=t.height;return{id:e,label:t.label,meta:{uri:r.url,thumbUri:r.url,fillType:"//ly.img.ubq/fill/image",kind:"image",width:i,height:n},payload:{sourceSet:[{uri:r.url,width:i,height:n}]}}}async function Ra(e,t,r){let i=t.width,n=t.height,o=await Ca(r.url,0);return{id:e,label:t.label,meta:{uri:r.url,thumbUri:o,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:i,height:n}}}function Va(e,t,r){return{id:e,label:t.label,meta:{uri:r.url,thumbUri:r.thumbnailUrl,blockType:"//ly.img.ubq/audio",mimeType:"audio/x-m4a",duration:r.duration.toString()}}}function Ua(e,t,r){let i=t.width,n=t.height;return{id:e,label:t.label,meta:{uri:r.url,thumbUri:r.url,fillType:"//ly.img.ubq/fill/image",kind:"sticker",width:i,height:n},payload:{sourceSet:[{uri:r.url,width:i,height:n}]}}}var $t=za;function Ba(e){switch(e.userFlow){case"placeholder":return qa(e);case"generation-only":return Ga(e);default:throw new Error(`Unknown user flow: ${e.userFlow}. Expected 'placeholder' or 'generation-only'.`)}}function Ga(e){let{cesdk:t,abortSignal:r}=e;return async i=>{try{let n=e.kind,o=await e.getBlockInput(i);if(_(t,r))return{status:"aborted"};let a=await e.generate(i,{middlewares:[...e.middlewares??[]],debug:e.debug,dryRun:e.dryRun,abortSignal:r});if(_(t,r))return{status:"aborted"};if(a.status!=="success")return a;if(a.type==="async")throw new Error("Async generation is not supported in this context yet.");if(_(t,r))return{status:"aborted"};if(e.historyAssetSourceId!=null){let s=xt(),c=await $t(s,n,o,a.output),l={...c,id:`${Date.now()}-${c.id}`,label:c.label!=null?{en:c.label}:{},tags:{}};t.engine.asset.addAssetToSource(e.historyAssetSourceId,l)}else e.debug&&console.log("No asset source ID found in history and generation only was requested. Doing nothing. If no middleware is adding functionality this could be a bug.");return a}catch(n){return{status:"error",message:n instanceof Error?n.message:String(n)}}}}function qa(e){let{cesdk:t,abortSignal:r}=e,i;return async n=>{try{let o=e.kind,a=await e.getBlockInput(n);if(_(t,r))return{status:"aborted"};let s=xt(),c=Da(s,o,a);if(i=await Aa(t,c),_(t,r,i))return{status:"aborted"};if(i!=null&&e.kind==="video"){let d=t.engine.block.getPositionX(i),p=t.engine.block.getPositionY(i),g=t.engine.block.duplicate(i);t.engine.block.setPositionX(g,d),t.engine.block.setPositionY(g,p),t.engine.block.destroy(i),i=g}if(i==null)throw new Error("Could not create placeholder block");t.engine.block.setState(i,{type:"Pending",progress:0});let l=await e.generate(n,{blockIds:[i],middlewares:[...e.middlewares??[]],debug:e.debug,dryRun:e.dryRun,abortSignal:r});if(_(t,r,i))return{status:"aborted"};if(l.status!=="success")return l.middlewareOptions?.defaultPrevented()||i!=null&&t.engine.block.isValid(i)&&(l.status==="aborted"?t.engine.block.destroy(i):t.engine.block.setState(i,{type:"Error",error:"Unknown"})),l;if(l.type==="async")throw new Error("Async generation is not supported in this context yet.");if(!t.engine.block.isValid(i))return{status:"aborted",message:"Placeholder block was destroyed before generation completed."};let u=await $t(s,o,a,l.output);if(_(t,r,i))return{status:"aborted"};if(e.debug&&console.log("Updating placeholder in scene:",JSON.stringify(u,void 0,2)),await t.engine.asset.defaultApplyAssetToBlock(u,i),_(t,r,i))return{status:"aborted"};if(e.historyAssetSourceId!=null){let d={...u,id:`${Date.now()}-${u.id}`,label:u.label!=null?{en:u.label}:{},tags:{}};t.engine.asset.addAssetToSource(e.historyAssetSourceId,d)}return t.engine.block.isValid(i)&&t.engine.block.setState(i,{type:"Ready"}),l}catch(o){return i!=null&&t.engine.block.isValid(i)&&(Ve(o)?t.engine.block.destroy(i):t.engine.block.setState(i,{type:"Error",error:"Unknown"})),{status:"error",message:o instanceof Error?o.message:String(o)}}}}function _(e,t,r){return t.aborted?(r!=null&&e.engine.block.isValid(r)&&e.engine.block.destroy(r),!0):!1}var Ha=Ba;function Be(e){return`${e}.generating`}function Za(e){return`${e}.abort`}function Qa(e,t,r,i,n,o,a){let{builder:s,experimental:c}=e,{cesdk:l,includeHistoryLibrary:u=!0}=o,{id:d,output:{abortable:p}}=t,g=c.global(Za(d),()=>{}),b=c.global(Be(d),!1),f,y=b.value&&p,m=()=>{y&&(g.value(),b.setValue(!1),g.setValue(()=>{}))},v;if(o.requiredInputs!=null&&o.requiredInputs.length>0){let C=i();v=o.requiredInputs.every(w=>!C.input[w])}let S=c.global(`${d}.confirmationDialogId`,void 0);s.Section(`${d}.generate.section`,{children:()=>{s.Button(`${d}.generate`,{label:["common.generate",`panel.${d}.generate`],isLoading:b.value,color:"accent",isDisabled:v,suffix:y?{icon:"@imgly/Cross",color:"danger",tooltip:[`panel.${d}.abort`,"common.cancel"],onClick:()=>{let C=l.ui.showDialog({type:"warning",content:"panel.ly.img.ai.generation.confirmCancel.content",cancel:{label:"common.close",onClick:({id:w})=>{l.ui.closeDialog(w),S.setValue(void 0)}},actions:{label:"panel.ly.img.ai.generation.confirmCancel.confirm",color:"danger",onClick:({id:w})=>{m(),l.ui.closeDialog(w),S.setValue(void 0)}}});S.setValue(C)}}:void 0,onClick:async()=>{f=new AbortController;let C=f.signal;await(async()=>{try{b.setValue(!0),g.setValue(()=>{a.debug&&console.log("Aborting generation"),f?.abort()});let w=await Ha({kind:t.kind,generate:r,historyAssetSourceId:o.historyAssetSourceId,userFlow:o.createPlaceholderBlock?"placeholder":"generation-only",getBlockInput:n,abortSignal:C,cesdk:l,debug:a.debug,dryRun:a.dryRun})(i().input);if(w.status==="aborted")return;if(w.status==="error"){pt(w.message,{cesdk:l,provider:t,getInput:i,middlewareOptions:w.middlewareOptions});return}if(w.status==="success"&&w.type==="sync"&&!w.middlewareOptions?.defaultPrevented()){let E=t.output.notification;Ya(l,E,()=>({input:i().input,output:w.output}))}}catch(w){if(Ve(w))return;pt(w,{cesdk:l,provider:t,getInput:i})}finally{f=void 0,b.setValue(!1),g.setValue(()=>{}),S.value!=null&&(l.ui.closeDialog(S.value),S.setValue(void 0))}})()}}),t.output.generationHintText!=null&&s.Text(`${d}.generation-hint`,{align:"center",content:t.output.generationHintText})}}),u&&o.historyAssetLibraryEntryId!=null&&s.Library(`${d}.history.library`,{entries:[o.historyAssetLibraryEntryId]})}function Ya(e,t,r){let i=t?.success;if(i==null||!(typeof i.show=="function"?i.show(r()):i.show))return!1;let n=typeof i.message=="function"?i.message(r()):i.message??"common.ai-generation.success",o=i.action!=null?{label:typeof i.action.label=="function"?i.action.label(r()):i.action.label,onClick:()=>{i?.action?.onClick(r())}}:void 0;return e.ui.showNotification({type:"success",message:n,action:o,duration:i.duration}),!0}var Tt=Qa;async function Ka({options:e,provider:t,panelInput:r,config:i},n){if(r==null)return;let{cesdk:o}=e,{id:a}=t,s=r.render;return c=>{let{state:l}=c,u=l(Be(a),{isGenerating:!1,abort:()=>{}}).value.isGenerating,{getInput:d,getBlockInput:p}=s(c,{cesdk:o,isGenerating:u});return Tt(c,t,n,d,p,{...e,includeHistoryLibrary:r.includeHistoryLibrary??!0,createPlaceholderBlock:r.userFlow==="placeholder"},i),d}}var Wa=Ka;function _t(e,t){if(!t.startsWith("#/"))throw new Error(`External references are not supported: ${t}`);let r=t.substring(2).split("/"),i=e;for(let n of r){if(i==null)throw new Error(`Invalid reference path: ${t}`);i=i[n]}if(i===void 0)throw new Error(`Reference not found: ${t}`);return i}function ee(e,t,r=new Set){if(t==null||r.has(t))return t;if(r.add(t),t.$ref&&typeof t.$ref=="string"){let i=_t(e,t.$ref),n={...ee(e,i,r)};for(let o in t)Object.prototype.hasOwnProperty.call(t,o)&&o!=="$ref"&&(n[o]=ee(e,t[o],r));return n}if(Array.isArray(t))return t.map(i=>ee(e,i,r));if(typeof t=="object"){let i={};for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[n]=ee(e,t[n],r));return i}return t}function Ja(e){return ee(e,{...e})}function Xa(e,t=!1){let r=a=>(t&&console.log(`OpenAPI Schema validation failed: ${a}`),!1);if(typeof e!="object"||e===null)return r(`Input is ${e===null?"null":typeof e}, not an object`);let i=e;if(!(typeof i.type=="string"||Array.isArray(i.enum)||typeof i.properties=="object"||typeof i.items=="object"||typeof i.allOf=="object"||typeof i.anyOf=="object"||typeof i.oneOf=="object"||typeof i.not=="object"))return r("Missing required schema-defining properties (type, enum, properties, items, allOf, anyOf, oneOf, not)");if(i.type!==void 0){let a=["string","number","integer","boolean","array","object","null"];if(typeof i.type=="string"){if(!a.includes(i.type))return r(`Invalid type: ${i.type}. Must be one of ${a.join(", ")}`)}else if(Array.isArray(i.type)){for(let s of i.type)if(typeof s!="string"||!a.includes(s))return r(`Array of types contains invalid value: ${s}. Must be one of ${a.join(", ")}`)}else return r(`Type must be a string or array of strings, got ${typeof i.type}`)}if(i.items!==void 0&&(typeof i.items!="object"||i.items===null))return r(`Items must be an object, got ${i.items===null?"null":typeof i.items}`);if(i.properties!==void 0&&(typeof i.properties!="object"||i.properties===null))return r(`Properties must be an object, got ${i.properties===null?"null":typeof i.properties}`);let n=["allOf","anyOf","oneOf"];for(let a of n)if(i[a]!==void 0){if(!Array.isArray(i[a]))return r(`${a} must be an array, got ${typeof i[a]}`);for(let s=0;s<i[a].length;s++){let c=i[a][s];if(typeof c!="object"||c===null)return r(`Item ${s} in ${a} must be an object, got ${c===null?"null":typeof c}`)}}if(i.not!==void 0&&(typeof i.not!="object"||i.not===null))return r(`'not' must be an object, got ${i.not===null?"null":typeof i.not}`);if(i.additionalProperties!==void 0&&typeof i.additionalProperties!="boolean"&&(typeof i.additionalProperties!="object"||i.additionalProperties===null))return r(`additionalProperties must be a boolean or an object, got ${i.additionalProperties===null?"null":typeof i.additionalProperties}`);if(i.format!==void 0&&typeof i.format!="string")return r(`format must be a string, got ${typeof i.format}`);let o=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf"];for(let a of o)if(i[a]!==void 0&&typeof i[a]!="number")return r(`${a} must be a number, got ${typeof i[a]}`);if(i.minLength!==void 0&&(typeof i.minLength!="number"||i.minLength<0))return r(`minLength must be a non-negative number, got ${typeof i.minLength=="number"?i.minLength:typeof i.minLength}`);if(i.maxLength!==void 0&&(typeof i.maxLength!="number"||i.maxLength<0))return r(`maxLength must be a non-negative number, got ${typeof i.maxLength=="number"?i.maxLength:typeof i.maxLength}`);if(i.pattern!==void 0&&typeof i.pattern!="string")return r(`pattern must be a string, got ${typeof i.pattern}`);if(i.minItems!==void 0&&(typeof i.minItems!="number"||i.minItems<0))return r(`minItems must be a non-negative number, got ${typeof i.minItems=="number"?i.minItems:typeof i.minItems}`);if(i.maxItems!==void 0&&(typeof i.maxItems!="number"||i.maxItems<0))return r(`maxItems must be a non-negative number, got ${typeof i.maxItems=="number"?i.maxItems:typeof i.maxItems}`);if(i.uniqueItems!==void 0&&typeof i.uniqueItems!="boolean")return r(`uniqueItems must be a boolean, got ${typeof i.uniqueItems}`);if(i.minProperties!==void 0&&(typeof i.minProperties!="number"||i.minProperties<0))return r(`minProperties must be a non-negative number, got ${typeof i.minProperties=="number"?i.minProperties:typeof i.minProperties}`);if(i.maxProperties!==void 0&&(typeof i.maxProperties!="number"||i.maxProperties<0))return r(`maxProperties must be a non-negative number, got ${typeof i.maxProperties=="number"?i.maxProperties:typeof i.maxProperties}`);if(i.required!==void 0){if(!Array.isArray(i.required))return r(`required must be an array, got ${typeof i.required}`);for(let a=0;a<i.required.length;a++){let s=i.required[a];if(typeof s!="string")return r(`Item ${a} in required array must be a string, got ${typeof s}`)}}return!0}function eo(e,t){if(e.properties==null)throw new Error("Input schema must have properties");let r=e.properties,i=[];return to(e,t).forEach(n=>{let o=n,a=r[n]??void 0;i.push({id:o,schema:a})}),i}function to(e,t){let r=t.order;if(r!=null&&Array.isArray(r))return r;if(e.properties==null)throw new Error("Input schema must have properties");let i=e.properties,n=Object.keys(i),o=ro(e,t)??n;return r!=null&&typeof r=="function"&&(o=r(o)),[...new Set(o)]}function ro(e,t){if(t.orderExtensionKeyword==null)return;if(typeof t.orderExtensionKeyword!="string"&&!Array.isArray(t.orderExtensionKeyword))throw new Error("orderExtensionKeyword must be a string or an array of strings");let r=(typeof t.orderExtensionKeyword=="string"?[t.orderExtensionKeyword]:t.orderExtensionKeyword).find(i=>i in e);return r==null?void 0:e[r]}var Lt=eo;function N(e,t,r,i){let n=`property.${e.id}${i?`.${i}`:""}`;return[`ly.img.plugin-ai-${r}-generation-web.${t.id}.${n}`,`ly.img.plugin-ai-generation-web.${n}`,`ly.img.plugin-ai-${r}-generation-web.${t.id}.defaults.${n}`,`ly.img.plugin-ai-generation-web.defaults.${n}`]}function Ot(e){let t="x-imgly-enum-labels"in e&&typeof e["x-imgly-enum-labels"]=="object"?e["x-imgly-enum-labels"]:{},r="x-imgly-enum-icons"in e&&typeof e["x-imgly-enum-icons"]=="object"?e["x-imgly-enum-icons"]:{};return{labels:t,icons:r}}function Pt(e,t,r,i,n,o,a,s){if(t.schema==null)if(i.renderCustomProperty!=null&&i.renderCustomProperty[t.id]!=null){let u={...e,providerConfig:s,config:o};return i.renderCustomProperty[t.id](u,t)}else return;let c=t,l=t.schema.type;if(i.renderCustomProperty!=null&&i.renderCustomProperty[t.id]!=null){let u={...e,providerConfig:s,config:o};return i.renderCustomProperty[t.id](u,t)}switch(l){case"string":return t.schema.enum!=null?io(e,c,r,i,n,o,a,s):Nt(e,c,r,i,n,o,a,s);case"boolean":return Dt(e,c,r,i,n,o,a,s);case"number":case"integer":return zt(e,c,r,i,n,o,a,s);case"object":return Fe(e,c,r,i,n,o,a,s);case"array":break;case void 0:{if(t.schema.anyOf!=null&&Array.isArray(t.schema.anyOf))return no(e,c,r,i,n,o,a,s);break}default:console.error(`Unsupported property type: ${l}`)}}function Fe(e,t,r,i,n,o,a,s){let c=Lt(t.schema??{},i).reduce((l,u)=>{let d=Pt(e,u,r,i,n,o,a,s);return d!=null&&(l[u.id]=d()),l},{});return()=>({id:t.id,type:"object",value:c})}function Nt(e,t,r,i,n,o,a,s){let{builder:c,experimental:{global:l},engine:u}=e,{id:d}=t,p=`${r.id}.${d}`,g=N(t,r,a),b=le(u,n.cesdk),f=s?.properties?.[d]??o.properties?.[d],y=se(d,f,b,t.schema.default,""),m=l(p,y),v=ao(t.schema),S=v?.component!=null&&v?.component==="TextArea"?"TextArea":"TextInput";return c[S](p,{inputLabel:g,placeholder:n.i18n?.prompt,...m}),()=>({id:t.id,type:"string",value:m.value})}function io(e,t,r,i,n,o,a,s){let{builder:c,experimental:{global:l},engine:u}=e,{id:d}=t,p=`${r.id}.${d}`,g=N(t,r,a),{labels:b,icons:f}=Ot(t.schema),y=(t.schema.enum??[]).map(E=>({id:E,label:N(t,r,a,E),icon:f[E]})),m=le(u,n.cesdk),v=s?.properties?.[d]??o.properties?.[d],S=se(d,v,m,t.schema.default,y[0]?.id),C=S!=null?y.find(E=>E.id===S)??y[0]:y[0],w=l(p,C);return c.Select(p,{inputLabel:g,values:y,...w}),()=>({id:t.id,type:"string",value:w.value.id})}function Dt(e,t,r,i,n,o,a,s){let{builder:c,experimental:{global:l},engine:u}=e,{id:d}=t,p=`${r.id}.${d}`,g=N(t,r,a),b=le(u,n.cesdk),f=s?.properties?.[d]??o.properties?.[d],y=!!se(d,f,b,t.schema.default,!1),m=l(p,y);return c.Checkbox(p,{inputLabel:g,...m}),()=>({id:t.id,type:"boolean",value:m.value})}function zt(e,t,r,i,n,o,a,s){let{builder:c,experimental:{global:l},engine:u}=e,{id:d}=t,p=`${r.id}.${d}`,g=N(t,r,a),b=t.schema.minimum,f=t.schema.maximum,y=le(u,n.cesdk),m=s?.properties?.[d]??o.properties?.[d],v=t.schema.default;v==null&&(b!=null?v=b:f!=null?v=f:v=0);let S=se(d,m,y,v,v),C=l(p,S);if(b!=null&&f!=null){let w=t.schema.type==="number"?.1:1;"x-imgly-step"in t.schema&&typeof t.schema["x-imgly-step"]=="number"&&(w=t.schema["x-imgly-step"]),c.Slider(p,{inputLabel:g,min:b,max:f,step:w,...C})}else c.NumberInput(p,{inputLabel:g,min:b,max:f,...C});return()=>({id:t.id,type:"integer",value:C.value})}function no(e,t,r,i,n,o,a,s){let{builder:c,experimental:{global:l},engine:u}=e,{id:d}=t,p=`${r.id}.${d}`,g=N(t,r,a),b=t.schema.anyOf??[],f=[],y={},m={},{labels:v,icons:S}=Ot(t.schema),C=le(u,n.cesdk),w=s?.properties?.[d]??o.properties?.[d],E={string:Nt,boolean:Dt,integer:zt,object:Fe},be=(h,M)=>h.$ref?h.$ref.split("/").pop():M.split(".").pop()??M,P=(h,M)=>({id:h,label:N(t,r,a,M),icon:S[M]??S[h]});b.forEach((h,M)=>{let k=`${r.id}.${d}.anyOf[${M}]`;if(h.$ref||h.title){let x=h.$ref?h.$ref.split("/").pop():h.title;y[k]=()=>Fe(e,{id:k,schema:{...h,title:v[x]||x}},r,i,n,o,a,s),f.push(P(k,x))}else if(h.type==="string"&&h.enum)h.enum.forEach(x=>{f.push(P(x,x))});else if(h.type&&E[h.type]){let x=E[h.type];y[k]=()=>x(e,{id:k,schema:{...h,title:h.title}},r,i,n,o,a,s);let Me=be(h,k);f.push(h.type==="string"&&!h.enum?{id:k,label:h.title||Me,icon:h.title&&S[h.title]||S[Me]}:P(k,Me))}});let ye=se(d,w,C,t.schema.default,null),Ee=ye!=null?f.find(h=>h.id===ye)??f[0]:f[0],T=l(p,Ee);if(c.Select(p,{inputLabel:g,values:f,...T}),T.value.id in y){let h=y[T.value.id]();m[T.value.id]=h}return()=>{let h=m[T.value.id];return h!=null?{...h(),id:t.id}:{id:t.id,type:"string",value:T.value.id}}}function ao(e){if("x-imgly-builder"in e)return e["x-imgly-builder"]}var oo=Pt,lo={"ly.img.plugin-ai-generation-web.defaults.property.prompt":"Prompt","ly.img.plugin-ai-generation-web.defaults.property.style":"Style","ly.img.plugin-ai-generation-web.defaults.property.image_size":"Image Size","ly.img.plugin-ai-generation-web.defaults.property.size":"Image Size","ly.img.plugin-ai-generation-web.defaults.property.colors":"Colors","ly.img.plugin-ai-generation-web.defaults.property.background":"Background","ly.img.plugin-ai-generation-web.defaults.property.width":"Width","ly.img.plugin-ai-generation-web.defaults.property.height":"Height","ly.img.plugin-ai-generation-web.defaults.property.aspect_ratio":"Aspect Ratio","ly.img.plugin-ai-generation-web.defaults.property.duration":"Duration","ly.img.plugin-ai-generation-web.defaults.property.resolution":"Resolution","ly.img.plugin-ai-generation-web.defaults.property.generate_audio":"Generate Audio","ly.img.plugin-ai-generation-web.defaults.property.voice_id":"Voice","ly.img.plugin-ai-generation-web.defaults.property.speed":"Speed","ly.img.plugin-ai-generation-web.defaults.property.text":"Text","ly.img.plugin-ai-generation-web.defaults.property.duration_seconds":"Duration (seconds)","ly.img.plugin-ai-generation-web.defaults.property.style.type":"Type","ly.img.plugin-ai-generation-web.defaults.property.style.type.image":"Image","ly.img.plugin-ai-generation-web.defaults.property.style.type.vector":"Vector","ly.img.plugin-ai-generation-web.defaults.property.style.type.icon":"Icon","ly.img.plugin-ai-generation-web.defaults.property.image_size.square":"Square","ly.img.plugin-ai-generation-web.defaults.property.image_size.portrait":"Portrait","ly.img.plugin-ai-generation-web.defaults.property.image_size.landscape":"Landscape","ly.img.plugin-ai-generation-web.defaults.property.background.auto":"Auto","ly.img.plugin-ai-generation-web.defaults.property.background.transparent":"Transparent","ly.img.plugin-ai-generation-web.defaults.property.aspect_ratio.1:1":"1:1 (Square)","ly.img.plugin-ai-generation-web.defaults.property.aspect_ratio.16:9":"16:9 (Widescreen)","ly.img.plugin-ai-generation-web.defaults.property.aspect_ratio.9:16":"9:16 (Vertical)","ly.img.plugin-ai-generation-web.defaults.property.aspect_ratio.4:3":"4:3","ly.img.plugin-ai-generation-web.defaults.property.aspect_ratio.3:4":"3:4","ly.img.plugin-ai-generation-web.defaults.property.resolution.720p":"720p HD","ly.img.plugin-ai-generation-web.defaults.property.resolution.1080p":"1080p Full HD"};function ft(e){return e.replace(/_/g," ").replace(/\b3d\b/gi,"3D").replace(/\b2d\b/gi,"2D").replace(/\b\w/g,t=>t.toUpperCase())}function so(e,t,r,i){let n={},o=(l,u)=>`ly.img.plugin-ai-${i}-generation-web.${t.id}.defaults.property.${l}${u?`.${u}`:""}`,a=l=>"x-imgly-enum-labels"in l&&typeof l["x-imgly-enum-labels"]=="object"?l["x-imgly-enum-labels"]:{},s=(l,u,d)=>{l.forEach(p=>{let g=String(p),b=d[g]||ft(g);n[o(u,g)]=b})};e.forEach(l=>{if(l.schema?.title&&(n[o(l.id)]=l.schema.title),l.schema?.enum){let u=a(l.schema);s(l.schema.enum,l.id,u)}if(l.schema?.anyOf&&Array.isArray(l.schema.anyOf)){let u=a(l.schema);l.schema.anyOf.forEach(d=>{let p=d;if(p.enum&&Array.isArray(p.enum))s(p.enum,l.id,u);else if(p.$ref){let g=p.$ref.split("/").pop();g&&u[g]&&(n[o(l.id,g)]=u[g])}else if(p.title){let g=p.title,b=u[g]||ft(g);n[o(l.id,g)]=b}})}});let c={...lo,...n};Object.keys(c).length>0&&r.cesdk.i18n.setTranslations({en:c})}async function uo({options:e,provider:t,panelInput:r,config:i,providerConfig:n},o){let{id:a}=t;if(r==null)return;i.debug&&console.log(`Registering schema-based panel input for provider ${a}`);let s=Ja(r.document),c=_t(s,r.inputReference);if(!Xa(c,i.debug))throw new Error(`Input reference '${r.inputReference}' does not resolve to a valid OpenAPI schema`);let l=c,u=Lt(l,r);return so(u,t,e,t.kind),d=>{let{builder:p}=d,g=[];p.Section(`${a}.schema.section`,{children:()=>{u.forEach(m=>{let v=oo(d,m,t,r,e,i,t.kind,n);v!=null&&(Array.isArray(v)?g.push(...v):g.push(v))})}});let b=g.map(m=>m()),f=m=>m.type==="object"?Object.entries(m.value).reduce((v,[S,C])=>(v[S]=f(C),v),{}):m.value,y=b.reduce((m,v)=>(m[v.id]=f(v),m),{});Tt(d,t,o,()=>({input:y}),()=>r.getBlockInput(y),{...e,requiredInputs:l.required,createPlaceholderBlock:r.userFlow==="placeholder"},i)}}var co=uo;async function go(e,t){if(e.panelInput!=null)switch(e.panelInput.type){case"custom":return Wa(e,t);case"schema":return co(e,t);default:e.config.debug&&console.warn(`Invalid panel input type '${panelInput.type}' - skipping`)}}var po=go;function fo(e){let{provider:t,options:{engine:r}}=e,i=t.output.history??"@imgly/local";if(i==null||i===!1)return;let n=r.asset.findAllSources();function o(){let a=`${t.id}.history`;for(;n.includes(a);)a+=`-${Math.random().toString(36).substring(2,6)}`;return a}if(i==="@imgly/local"){let a=o();return r.asset.addLocalSource(a),a}if(i==="@imgly/indexedDB"){let a=o();return r.asset.addSource(new br(a,r)),a}return i}var mo=fo;function bo(e,t){if(t==null||!t)return;let r=`${e.provider.id}.history`;return e.options.cesdk.ui.addAssetLibraryEntry({id:r,sourceIds:[t],sortBy:{sortKey:"insertedAt",sortingOrder:"Descending"},canRemove:!0,gridItemHeight:"square",gridBackgroundType:"cover"}),r}var yo=bo,_e="@imgly/plugin-ai-generation",ho=`
<svg>
<symbol
fill="none"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
id="@imgly/Sparkle"
>
<path d="M5.35545 2.06745C5.24149 1.72556 4.7579 1.72556 4.64394 2.06745L4.05898 3.82232C4.02166 3.93429 3.9338 4.02215 3.82184 4.05948L2.06694 4.64459C1.72506 4.75858 1.72509 5.24217 2.06699 5.3561L3.82179 5.9409C3.93378 5.97822 4.02166 6.06609 4.05899 6.17808L4.64394 7.93291C4.7579 8.2748 5.24149 8.2748 5.35545 7.93291L5.9404 6.17806C5.97773 6.06608 6.06559 5.97821 6.17757 5.94089L7.93242 5.35594C8.27431 5.24198 8.27431 4.75839 7.93242 4.64442L6.17757 4.05947C6.06559 4.02215 5.97773 3.93428 5.9404 3.8223L5.35545 2.06745Z" fill="currentColor"/>
<path d="M17.9632 3.23614C17.8026 2.80788 17.1968 2.80788 17.0362 3.23614L16.0787 5.78951C16.0285 5.92337 15.9229 6.02899 15.789 6.07918L13.2356 7.0367C12.8074 7.19729 12.8074 7.80307 13.2356 7.96366L