@imgly/plugin-ai-video-generation-web
Version:
AI video generation plugin for the CE.SDK editor
12 lines • 85.6 kB
JavaScript
var yr=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((u,l)=>{let c=e.locale??"en",d="",p=[];l.label!=null&&typeof l.label=="object"&&l.label[c]&&(d=l.label[c]),l.tags!=null&&typeof l.tags=="object"&&l.tags[c]&&(p=l.tags[c]);let g={...l,label:d,tags:p};return this.filterAsset(g,e)&&u.push(g),u},[]);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;V(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=()=>{V(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(),u=a.meta?.insertedAt||a._insertedAt||Date.now();return e==="asc"?s-u:u-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 V(e,i=>{r.add(i)}),await Promise.all([...r].map(async i=>{let n=await this.createBlobUrlFromStore(i);t[i]=n})),V(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()??"",u=e.tags?.map(l=>l.toLowerCase())??[];if(!a.every(l=>s.includes(l)||u.some(c=>c.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 u,l;return i==="id"?(u=a.id,l=s.id):(u=a.meta?.[i]??null,l=s.meta?.[i]??null),u==null?r==="Ascending"?-1:1:l==null?r==="Ascending"?1:-1:typeof u=="string"&&typeof l=="string"?r==="Ascending"?u.localeCompare(l):l.localeCompare(u):r==="Ascending"?u<l?-1:u>l?1:0:u>l?-1:u<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 V(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]=V(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]=V(n,t,o)}return e}var hr=class{constructor(e,t,r){this.id=e,this.cesdk=t,this.assetSourceIds=r}async findAssets(e){try{let t=this.assetSourceIds.map(c=>this.cesdk.engine.asset.findAssets(c,{...e,perPage:9999,page:0})),r=await Promise.all(t),i=[];r.forEach(c=>{c?.assets&&(i=i.concat(c.assets))}),i.sort((c,d)=>{let p=c.meta?.insertedAt||0;return(d.meta?.insertedAt||0)-p});let{page:n,perPage:o}=e,a=n*o,s=a+o,u=i.slice(a,s),l=s<i.length?n+1:void 0;return{assets:u,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 vr=typeof global=="object"&&global&&global.Object===Object&&global,yt=vr,wr=typeof self=="object"&&self&&self.Object===Object&&self,kr=yt||wr||Function("return this")(),j=kr,Ir=j.Symbol,U=Ir,ht=Object.prototype,Ar=ht.hasOwnProperty,Sr=ht.toString,X=U?U.toStringTag:void 0;function Cr(e){var t=Ar.call(e,X),r=e[X];try{e[X]=void 0;var i=!0}catch{}var n=Sr.call(e);return i&&(t?e[X]=r:delete e[X]),n}var xr=Cr,Er=Object.prototype,Mr=Er.toString;function jr(e){return Mr.call(e)}var $r=jr,Tr="[object Null]",_r="[object Undefined]",et=U?U.toStringTag:void 0;function Lr(e){return e==null?e===void 0?_r:Tr:et&&et in Object(e)?xr(e):$r(e)}var oe=Lr;function Or(e){return e!=null&&typeof e=="object"}var Ve=Or,Ku=Array.isArray;function Pr(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var vt=Pr,Nr="[object AsyncFunction]",Dr="[object Function]",zr="[object GeneratorFunction]",Fr="[object Proxy]";function Rr(e){if(!vt(e))return!1;var t=oe(e);return t==Dr||t==zr||t==Nr||t==Fr}var Vr=Rr,Ur=j["__core-js_shared__"],$e=Ur,tt=function(){var e=/[^.]+$/.exec($e&&$e.keys&&$e.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function Br(e){return!!tt&&tt in e}var Gr=Br,qr=Function.prototype,Hr=qr.toString;function Zr(e){if(e!=null){try{return Hr.call(e)}catch{}try{return e+""}catch{}}return""}var z=Zr,Qr=/[\\^$.*+?()[\]{}|]/g,Yr=/^\[object .+?Constructor\]$/,Kr=Function.prototype,Wr=Object.prototype,Jr=Kr.toString,Xr=Wr.hasOwnProperty,ei=RegExp("^"+Jr.call(Xr).replace(Qr,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function ti(e){if(!vt(e)||Gr(e))return!1;var t=Vr(e)?ei:Yr;return t.test(z(e))}var ri=ti;function ii(e,t){return e?.[t]}var ni=ii;function ai(e,t){var r=ni(e,t);return ri(r)?r:void 0}var B=ai,oi=B(j,"WeakMap"),Pe=oi;function li(e,t){return e===t||e!==e&&t!==t}var si=li,ui=9007199254740991;function ci(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=ui}var di=ci,Wu=Object.prototype,gi="[object Arguments]";function pi(e){return Ve(e)&&oe(e)==gi}var rt=pi,wt=Object.prototype,fi=wt.hasOwnProperty,mi=wt.propertyIsEnumerable,Ju=rt(function(){return arguments}())?rt:function(e){return Ve(e)&&fi.call(e,"callee")&&!mi.call(e,"callee")},kt=typeof exports=="object"&&exports&&!exports.nodeType&&exports,it=kt&&typeof module=="object"&&module&&!module.nodeType&&module,bi=it&&it.exports===kt,nt=bi?j.Buffer:void 0,Xu=nt?nt.isBuffer:void 0,yi="[object Arguments]",hi="[object Array]",vi="[object Boolean]",wi="[object Date]",ki="[object Error]",Ii="[object Function]",Ai="[object Map]",Si="[object Number]",Ci="[object Object]",xi="[object RegExp]",Ei="[object Set]",Mi="[object String]",ji="[object WeakMap]",$i="[object ArrayBuffer]",Ti="[object DataView]",_i="[object Float32Array]",Li="[object Float64Array]",Oi="[object Int8Array]",Pi="[object Int16Array]",Ni="[object Int32Array]",Di="[object Uint8Array]",zi="[object Uint8ClampedArray]",Fi="[object Uint16Array]",Ri="[object Uint32Array]",I={};I[_i]=I[Li]=I[Oi]=I[Pi]=I[Ni]=I[Di]=I[zi]=I[Fi]=I[Ri]=!0;I[yi]=I[hi]=I[$i]=I[vi]=I[Ti]=I[wi]=I[ki]=I[Ii]=I[Ai]=I[Si]=I[Ci]=I[xi]=I[Ei]=I[Mi]=I[ji]=!1;function Vi(e){return Ve(e)&&di(e.length)&&!!I[oe(e)]}var Ui=Vi;function Bi(e){return function(t){return e(t)}}var Gi=Bi,It=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ie=It&&typeof module=="object"&&module&&!module.nodeType&&module,qi=ie&&ie.exports===It,Te=qi&&yt.process,Hi=function(){try{var e=ie&&ie.require&&ie.require("util").types;return e||Te&&Te.binding&&Te.binding("util")}catch{}}(),at=Hi,ot=at&&at.isTypedArray,ec=ot?Gi(ot):Ui,Zi=Object.prototype,tc=Zi.hasOwnProperty;function Qi(e,t){return function(r){return e(t(r))}}var Yi=Qi,rc=Yi(Object.keys,Object),Ki=Object.prototype,ic=Ki.hasOwnProperty,Wi=B(Object,"create"),ne=Wi;function Ji(){this.__data__=ne?ne(null):{},this.size=0}var Xi=Ji;function en(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var tn=en,rn="__lodash_hash_undefined__",nn=Object.prototype,an=nn.hasOwnProperty;function on(e){var t=this.__data__;if(ne){var r=t[e];return r===rn?void 0:r}return an.call(t,e)?t[e]:void 0}var ln=on,sn=Object.prototype,un=sn.hasOwnProperty;function cn(e){var t=this.__data__;return ne?t[e]!==void 0:un.call(t,e)}var dn=cn,gn="__lodash_hash_undefined__";function pn(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=ne&&t===void 0?gn:t,this}var fn=pn;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=Xi;G.prototype.delete=tn;G.prototype.get=ln;G.prototype.has=dn;G.prototype.set=fn;var lt=G;function mn(){this.__data__=[],this.size=0}var bn=mn;function yn(e,t){for(var r=e.length;r--;)if(si(e[r][0],t))return r;return-1}var ve=yn,hn=Array.prototype,vn=hn.splice;function wn(e){var t=this.__data__,r=ve(t,e);if(r<0)return!1;var i=t.length-1;return r==i?t.pop():vn.call(t,r,1),--this.size,!0}var kn=wn;function In(e){var t=this.__data__,r=ve(t,e);return r<0?void 0:t[r][1]}var An=In;function Sn(e){return ve(this.__data__,e)>-1}var Cn=Sn;function xn(e,t){var r=this.__data__,i=ve(r,e);return i<0?(++this.size,r.push([e,t])):r[i][1]=t,this}var En=xn;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=bn;q.prototype.delete=kn;q.prototype.get=An;q.prototype.has=Cn;q.prototype.set=En;var we=q,Mn=B(j,"Map"),ae=Mn;function jn(){this.size=0,this.__data__={hash:new lt,map:new(ae||we),string:new lt}}var $n=jn;function Tn(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var _n=Tn;function Ln(e,t){var r=e.__data__;return _n(t)?r[typeof t=="string"?"string":"hash"]:r.map}var ke=Ln;function On(e){var t=ke(this,e).delete(e);return this.size-=t?1:0,t}var Pn=On;function Nn(e){return ke(this,e).get(e)}var Dn=Nn;function zn(e){return ke(this,e).has(e)}var Fn=zn;function Rn(e,t){var r=ke(this,e),i=r.size;return r.set(e,t),this.size+=r.size==i?0:1,this}var Vn=Rn;function H(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])}}H.prototype.clear=$n;H.prototype.delete=Pn;H.prototype.get=Dn;H.prototype.has=Fn;H.prototype.set=Vn;var At=H;function Un(){this.__data__=new we,this.size=0}var Bn=Un;function Gn(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var qn=Gn;function Hn(e){return this.__data__.get(e)}var Zn=Hn;function Qn(e){return this.__data__.has(e)}var Yn=Qn,Kn=200;function Wn(e,t){var r=this.__data__;if(r instanceof we){var i=r.__data__;if(!ae||i.length<Kn-1)return i.push([e,t]),this.size=++r.size,this;r=this.__data__=new At(i)}return r.set(e,t),this.size=r.size,this}var Jn=Wn;function le(e){var t=this.__data__=new we(e);this.size=t.size}le.prototype.clear=Bn;le.prototype.delete=qn;le.prototype.get=Zn;le.prototype.has=Yn;le.prototype.set=Jn;var Xn=Object.prototype,nc=Xn.propertyIsEnumerable,ea=B(j,"DataView"),Ne=ea,ta=B(j,"Promise"),De=ta,ra=B(j,"Set"),ze=ra,st="[object Map]",ia="[object Object]",ut="[object Promise]",ct="[object Set]",dt="[object WeakMap]",gt="[object DataView]",na=z(Ne),aa=z(ae),oa=z(De),la=z(ze),sa=z(Pe),R=oe;(Ne&&R(new Ne(new ArrayBuffer(1)))!=gt||ae&&R(new ae)!=st||De&&R(De.resolve())!=ut||ze&&R(new ze)!=ct||Pe&&R(new Pe)!=dt)&&(R=function(e){var t=oe(e),r=t==ia?e.constructor:void 0,i=r?z(r):"";if(i)switch(i){case na:return gt;case aa:return st;case oa:return ut;case la:return ct;case sa:return dt}return t});var ac=j.Uint8Array,ua="__lodash_hash_undefined__";function ca(e){return this.__data__.set(e,ua),this}var da=ca;function ga(e){return this.__data__.has(e)}var pa=ga;function Fe(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new At;++t<r;)this.add(e[t])}Fe.prototype.add=Fe.prototype.push=da;Fe.prototype.has=pa;var pt=U?U.prototype:void 0,oc=pt?pt.valueOf:void 0,fa=Object.prototype,lc=fa.hasOwnProperty,ma=Object.prototype,sc=ma.hasOwnProperty,uc=new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,"i"),cc=new RegExp(/[A-Fa-f0-9]{1}/,"g"),dc=new RegExp(/[A-Fa-f0-9]{2}/,"g");async function St(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 ba(e,t){let r=await St(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 ya(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 St(i,t)}function ha(e){return e!==void 0}var va=ha;function O(e,t){if(typeof e.i18n?.getTranslations!="function"){e.i18n.setTranslations(t);return}let r=Object.keys(t),i=e.i18n.getTranslations(r),n={};for(let o of r){let a=t[o];if(!a)continue;let s=i[o]??{},u={};for(let[l,c]of Object.entries(a))!(l in s)&&c!==void 0&&(u[l]=c);Object.keys(u).length>0&&(n[o]=u)}Object.keys(n).length>0&&e.i18n.setTranslations(n)}function se(e,t){let r=t?.i18n?.getLocale?.()||"en";return{engine:e,cesdk:t,locale:r}}function ue(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 ce=class Ct{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 Ct),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))}},wa=class xt{constructor(){this.providers=new Map}static get(){let t="__imgly_provider_registry__",r=typeof window<"u"?window:globalThis;return r[t]||(r[t]=new xt),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 ka(e){let t=e.filter(r=>!!r);return r=>async(i,n)=>{let o=[],a=l=>{o.push(l)},s=async(l,c,d)=>{if(l>=t.length)return r(c,d);let p=t[l],g=async(f,y)=>s(l+1,f,y),m={...d,addDisposer:a};return p(c,m,g)},u={...n,addDisposer:a};return{result:await s(0,i,u),dispose:async()=>{for(let l=o.length-1;l>=0;l--)try{await o[l]()}catch(c){console.error("Error in disposer:",c)}o.length=0}}}}function Ia({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 Aa=Ia;var _e="ly.img.ai.temp";async function Sa(e,t){return e.engine.asset.findAllSources().includes(_e)||e.engine.asset.addLocalSource(_e),e.engine.asset.apply(_e,t)}function Ca(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 Et(){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 xa(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 u=s.getContext("2d");if(!u){document.body.removeChild(a),o(new Error("Failed to create canvas context"));return}u.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 Ea(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 Ue(e){return e instanceof Error&&e.name==="AbortError"}function Ma(e,t,r){let i=`${t}.iconSetAdded`;e.ui.experimental.hasGlobalStateValue(i)||(e.ui.addIconSet(t,r),e.ui.experimental.setGlobalStateValue(i,!0))}function Mt(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 ja(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 jt=ja;function $a(){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 $t=$a;function Ta(e,t){let{cesdk:r,provider:i,getInput:n,middlewareOptions:o}=t;o?.defaultPrevented()||(console.error("Generation failed:",e),_a(r,i.output.notification,()=>({input:n?.().input,error:e}))||r.ui.showNotification({type:"error",message:Ca(e)}))}function _a(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 ft=Ta,La="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIzIiBoZWlnaHQ9IjMyMyIgdmlld0JveD0iMCAwIDMyMyAzMjMiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIzMjMiIGhlaWdodD0iMzIzIiBmaWxsPSIjRTlFQkVEIi8+CjxnIG9wYWNpdHk9IjAuMyI+CjxwYXRoIGQ9Ik0xMTYgMTg0VjE5MS41QzExNiAxOTkuNzg0IDEyMi43MTYgMjA2LjUgMTMxIDIwNi41SDE5MUMxOTkuMjg0IDIwNi41IDIwNiAxOTkuNzg0IDIwNiAxOTEuNVYxMzEuNUMyMDYgMTIzLjIxNiAxOTkuMjg0IDExNi41IDE5MSAxMTYuNUwxOTAuOTk1IDEyNi41QzE5My43NTcgMTI2LjUgMTk2IDEyOC43MzkgMTk2IDEzMS41VjE5MS41QzE5NiAxOTQuMjYxIDE5My43NjEgMTk2LjUgMTkxIDE5Ni41SDEzMUMxMjguMjM5IDE5Ni41IDEyNiAxOTQuMjYxIDEyNiAxOTEuNVYxODRIMTE2WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTY2LjQ5NCAxMDUuOTI0QzE2NS44NjkgMTA0LjM0MiAxNjMuNjI5IDEwNC4zNDIgMTYzLjAwNSAxMDUuOTI0TDE1OS43NDUgMTE0LjE5MUMxNTkuNTU0IDExNC42NzQgMTU5LjE3MiAxMTUuMDU3IDE1OC42ODggMTE1LjI0N0wxNTAuNDIyIDExOC41MDhDMTQ4LjgzOSAxMTkuMTMyIDE0OC44MzkgMTIxLjM3MiAxNTAuNDIyIDEyMS45OTZMMTU4LjY4OCAxMjUuMjU2QzE1OS4xNzIgMTI1LjQ0NyAxNTkuNTU0IDEyNS44MjkgMTU5Ljc0NSAxMjYuMzEzTDE2My4wMDUgMTM0LjU3OUMxNjMuNjI5IDEzNi4xNjIgMTY1Ljg2OSAxMzYuMTYyIDE2Ni40OTQgMTM0LjU3OUwxNjkuNzU0IDEyNi4zMTNDMTY5Ljk0NCAxMjUuODI5IDE3MC4zMjcgMTI1LjQ0NyAxNzAuODEgMTI1LjI1NkwxNzkuMDc3IDEyMS45OTZDMTgwLjY2IDEyMS4zNzIgMTgwLjY2IDExOS4xMzIgMTc5LjA3NyAxMTguNTA4TDE3MC44MSAxMTUuMjQ3QzE3MC4zMjcgMTE1LjA1NyAxNjkuOTQ0IDExNC42NzQgMTY5Ljc1NCAxMTQuMTkxTDE2Ni40OTQgMTA1LjkyNFoiIGZpbGw9IiM4RjhGOEYiLz4KPHBhdGggZD0iTTEzMy4wMDUgMTI4LjQyNEMxMzMuNjI5IDEyNi44NDIgMTM1Ljg2OSAxMjYuODQyIDEzNi40OTQgMTI4LjQyNEwxNDEuODc1IDE0Mi4wN0MxNDIuMDY2IDE0Mi41NTMgMTQyLjQ0OCAxNDIuOTM1IDE0Mi45MzIgMTQzLjEyNkwxNTYuNTc3IDE0OC41MDhDMTU4LjE2IDE0OS4xMzIgMTU4LjE2IDE1MS4zNzIgMTU2LjU3NyAxNTEuOTk2TDE0Mi45MzIgMTU3LjM3OEMxNDIuNDQ4IDE1Ny41NjggMTQyLjA2NiAxNTcuOTUxIDE0MS44NzUgMTU4LjQzNEwxMzYuNDk0IDE3Mi4wNzlDMTM1Ljg2OSAxNzMuNjYyIDEzMy42MjkgMTczLjY2MiAxMzMuMDA1IDE3Mi4wNzlMMTI3LjYyMyAxNTguNDM0QzEyNy40MzMgMTU3Ljk1MSAxMjcuMDUgMTU3LjU2OCAxMjYuNTY3IDE1Ny4zNzhMMTEyLjkyMiAxNTEuOTk2QzExMS4zMzkgMTUxLjM3MiAxMTEuMzM5IDE0OS4xMzIgMTEyLjkyMiAxNDguNTA4TDEyNi41NjcgMTQzLjEyNkMxMjcuMDUgMTQyLjkzNSAxMjcuNDMzIDE0Mi41NTMgMTI3LjYyMyAxNDIuMDdMMTMzLjAwNSAxMjguNDI0WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTk1Ljk5OSAxODQuMDA0VjE5MS41MDJDMTk1Ljk5OSAxOTQuMjYzIDE5My43NjEgMTk2LjUwMiAxOTAuOTk5IDE5Ni41MDJIMTQ3LjY2OEwxNzIuODc5IDE1OC42ODRDMTc0LjM2MyAxNTYuNDU4IDE3Ny42MzUgMTU2LjQ1OCAxNzkuMTIgMTU4LjY4NEwxOTUuOTk5IDE4NC4wMDRaIiBmaWxsPSIjOEY4RjhGIi8+CjwvZz4KPC9zdmc+Cg==",Be=La;function Oa(e,t,r){switch(t){case"image":return Pa(e,r[t]);case"video":return Na(e,r[t]);case"sticker":return Da(e,r[t]);default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function Pa(e,t){let r=t.width,i=t.height;return{id:e,meta:{previewUri:Be,fillType:"//ly.img.ubq/fill/image",kind:"image",width:r,height:i}}}function Na(e,t){let r=t.width,i=t.height;return{id:e,label:t.label,meta:{previewUri:Be,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:r,height:i}}}function Da(e,t){let r=t.width,i=t.height;return{id:e,meta:{previewUri:Be,fillType:"//ly.img.ubq/fill/image",kind:"sticker",width:r,height:i}}}var za=Oa;async function Fa(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 Ra(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 Va(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 Ua(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 Ba(e,r[t],i)}default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function Ra(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 Va(e,t,r){let i=t.width,n=t.height,o=await xa(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 Ua(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 Ba(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 Tt=Fa;function Ga(e){switch(e.userFlow){case"placeholder":return Ha(e);case"generation-only":return qa(e);default:throw new Error(`Unknown user flow: ${e.userFlow}. Expected 'placeholder' or 'generation-only'.`)}}function qa(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=Et(),u=await Tt(s,n,o,a.output),l={...u,id:`${Date.now()}-${u.id}`,label:u.label!=null?{en:u.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 Ha(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=Et(),u=za(s,o,a);if(i=await Sa(t,u),_(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 c=await Tt(s,o,a,l.output);if(_(t,r,i))return{status:"aborted"};if(e.debug&&console.log("Updating placeholder in scene:",JSON.stringify(c,void 0,2)),await t.engine.asset.defaultApplyAssetToBlock(c,i),_(t,r,i))return{status:"aborted"};if(e.historyAssetSourceId!=null){let d={...c,id:`${Date.now()}-${c.id}`,label:c.label!=null?{en:c.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)&&(Ue(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 Za=Ga;function Ge(e){return`${e}.generating`}function Qa(e){return`${e}.abort`}function Ya(e,t,r,i,n,o,a){let{builder:s,experimental:u}=e,{cesdk:l,includeHistoryLibrary:c=!0}=o,{id:d,output:{abortable:p}}=t,g=u.global(Qa(d),()=>{}),m=u.global(Ge(d),!1),f,y=m.value&&p,b=()=>{y&&(g.value(),m.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=u.global(`${d}.confirmationDialogId`,void 0);s.Section(`${d}.generate.section`,{children:()=>{s.Button(`${d}.generate`,{label:["ly.img.plugin-ai-generation-web.generate","common.generate",`panel.${d}.generate`],isLoading:m.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})=>{b(),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{m.setValue(!0),g.setValue(()=>{a.debug&&console.log("Aborting generation"),f?.abort()});let w=await Za({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"){ft(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;Ka(l,E,()=>({input:i().input,output:w.output}))}}catch(w){if(Ue(w))return;ft(w,{cesdk:l,provider:t,getInput:i})}finally{f=void 0,m.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})}}),c&&o.historyAssetLibraryEntryId!=null&&s.Library(`${d}.history.library`,{entries:[o.historyAssetLibraryEntryId]})}function Ka(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 _t=Ya;async function Wa({options:e,provider:t,panelInput:r,config:i},n){if(r==null)return;let{cesdk:o}=e,{id:a}=t;i.debug&&console.log(`Provider: ${a} (custom)`);let s=r.render;return u=>{let{state:l}=u,c=l(Ge(a),{isGenerating:!1,abort:()=>{}}).value.isGenerating,{getInput:d,getBlockInput:p}=s(u,{cesdk:o,isGenerating:c});return _t(u,t,n,d,p,{...e,includeHistoryLibrary:r.includeHistoryLibrary??!0,createPlaceholderBlock:r.userFlow==="placeholder"},i),d}}var Ja=Wa;function Lt(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 te(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=Lt(e,t.$ref),n={...te(e,i,r)};for(let o in t)Object.prototype.hasOwnProperty.call(t,o)&&o!=="$ref"&&(n[o]=te(e,t[o],r));return n}if(Array.isArray(t))return t.map(i=>te(e,i,r));if(typeof t=="object"){let i={};for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[n]=te(e,t[n],r));return i}return t}function Xa(e){return te(e,{...e})}function eo(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 u=i[a][s];if(typeof u!="object"||u===null)return r(`Item ${s} in ${a} must be an object, got ${u===null?"null":typeof u}`)}}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 to(e,t){if(e.properties==null)throw new Error("Input schema must have properties");let r=e.properties,i=[];return ro(e,t).forEach(n=>{let o=n,a=r[n]??void 0;i.push({id:o,schema:a})}),i}function ro(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=io(e,t)??n;return r!=null&&typeof r=="function"&&(o=r(o)),[...new Set(o)]}function io(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 Ot=to;function L(e,t,r,i){let n=`property.${e.id}${i?`.${i}`:""}`,o=[`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}`];return i==="placeholder"&&o.push("ly.img.plugin-ai-generation-web.fallback.property.placeholder"),o}function Pt(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 Nt(e,t,r,i,n,o,a,s){if(t.schema==null)if(i.renderCustomProperty!=null&&i.renderCustomProperty[t.id]!=null){let c={...e,providerConfig:s,config:o};return i.renderCustomProperty[t.id](c,t)}else return;let u=t,l=t.schema.type;if(i.renderCustomProperty!=null&&i.renderCustomProperty[t.id]!=null){let c={...e,providerConfig:s,config:o};return i.renderCustomProperty[t.id](c,t)}switch(l){case"string":return t.schema.enum!=null?no(e,u,r,i,n,o,a,s):Dt(e,u,r,i,n,o,a,s);case"boolean":return zt(e,u,r,i,n,o,a,s);case"number":case"integer":return Ft(e,u,r,i,n,o,a,s);case"object":return Re(e,u,r,i,n,o,a,s);case"array":break;case void 0:{if(t.schema.anyOf!=null&&Array.isArray(t.schema.anyOf))return ao(e,u,r,i,n,o,a,s);break}default:console.error(`Unsupported property type: ${l}`)}}function Re(e,t,r,i,n,o,a,s){let u=Ot(t.schema??{},i).reduce((l,c)=>{let d=Nt(e,c,r,i,n,o,a,s);return d!=null&&(l[c.id]=d()),l},{});return()=>({id:t.id,type:"object",value:u})}function Dt(e,t,r,i,n,o,a,s){let{builder:u,experimental:{global:l},engine:c}=e,{id:d}=t,p=`${r.id}.${d}`,g=L(t,r,a),m=L(t,r,a,"placeholder"),f=se(c,n.cesdk),y=s?.properties?.[d]??o.properties?.[d],b=ue(d,y,f,t.schema.default,""),v=l(p,b),S=oo(t.schema),C=S?.component!=null&&S?.component==="TextArea"?"TextArea":"TextInput",w=m.length>0?m:void 0;return u[C](p,{inputLabel:g,...w&&{placeholder:w},...v}),()=>({id:t.id,type:"string",value:v.value})}function no(e,t,r,i,n,o,a,s){let{builder:u,experimental:{global:l},engine:c}=e,{id:d}=t,p=`${r.id}.${d}`,g=L(t,r,a),{labels:m,icons:f}=Pt(t.schema),y=(t.schema.enum??[]).map(E=>({id:E,label:L(t,r,a,E),icon:f[E]})),b=se(c,n.cesdk),v=s?.properties?.[d]??o.properties?.[d],S=ue(d,v,b,t.schema.default,y[0]?.id),C=S!=null?y.find(E=>E.id===S)??y[0]:y[0],w=l(p,C);return u.Select(p,{inputLabel:g,values:y,...w}),()=>({id:t.id,type:"string",value:w.value.id})}function zt(e,t,r,i,n,o,a,s){let{builder:u,experimental:{global:l},engine:c}=e,{id:d}=t,p=`${r.id}.${d}`,g=L(t,r,a),m=se(c,n.cesdk),f=s?.properties?.[d]??o.properties?.[d],y=!!ue(d,f,m,t.schema.default,!1),b=l(p,y);return u.Checkbox(p,{inputLabel:g,...b}),()=>({id:t.id,type:"boolean",value:b.value})}function Ft(e,t,r,i,n,o,a,s){let{builder:u,experimental:{global:l},engine:c}=e,{id:d}=t,p=`${r.id}.${d}`,g=L(t,r,a),m=t.schema.minimum,f=t.schema.maximum,y=se(c,n.cesdk),b=s?.properties?.[d]??o.properties?.[d],v=t.schema.default;v==null&&(m!=null?v=m:f!=null?v=f:v=0);let S=ue(d,b,y,v,v),C=l(p,S);if(m!=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"]),u.Slider(p,{inputLabel:g,min:m,max:f,step:w,...C})}else u.NumberInput(p,{inputLabel:g,min:m,max:f,...C});return()=>({id:t.id,type:"integer",value:C.value})}function ao(e,t,r,i,n,o,a,s){let{builder:u,experimental:{global:l},engine:c}=e,{id:d}=t,p=`${r.id}.${d}`,g=L(t,r,a),m=t.schema.anyOf??[],f=[],y={},b={},{labels:v,icons:S}=Pt(t.schema),C=se(c,n.cesdk),w=s?.properties?.[d]??o.properties?.[d],E={string:Dt,boolean:zt,integer:Ft,object:Re},ye=(h,M)=>h.$ref?h.$ref.split("/").pop():M.split(".").pop()??M,D=(h,M)=>({id:h,label:L(t,r,a,M),icon:S[M]??S[h]});m.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]=()=>Re(e,{id:k,schema:{...h,title:v[x]||x}},r,i,n,o,a,s),f.push(D(k,x))}else if(h.type==="string"&&h.enum)h.enum.forEach(x=>{f.push(D(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 je=ye(h,k);f.push(h.type==="string"&&!h.enum?{id:k,label:h.title||je,icon:h.title&&S[h.title]||S[je]}:D(k,je))}});let he=ue(d,w,C,t.schema.default,null),Me=he!=null?f.find(h=>h.id===he)??f[0]:f[0],T=l(p,Me);if(u.Select(p,{inputLabel:g,values:f,...T}),T.value.id in y){let h=y[T.value.id]();b[T.value.id]=h}return()=>{let h=b[T.value.id];return h!=null?{...h(),id:t.id}:{id:t.id,type:"string",value:T.value.id}}}function oo(e){if("x-imgly-builder"in e)return e["x-imgly-builder"]}var lo=Nt,so={"ly.img.plugin-ai-generation-web.fallback.property.placeholder":"","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 mt(e){return e.replace(/_/g," ").replace(/\b3d\b/gi,"3D").replace(/\b2d\b/gi,"2D").replace(/\b\w/g,t=>t.toUpperCase())}function uo(e,t,r,i){let n={},o=(l,c)=>`ly.img.plugin-ai-${i}-generation-web.${t.id}.defaults.property.${l}${c?`.${c}`:""}`,a=l=>"x-imgly-enum-labels"in l&&typeof l["x-imgly-enum-labels"]=="object"?l["x-imgly-enum-labels"]:{},s=(l,c,d)=>{l.forEach(p=>{let g=String(p),m=d[g]||mt(g);n[o(c,g)]=m})};e.forEach(l=>{if(l.schema?.title&&(n[o(l.id)]=l.schema.title),l.schema?.enum){let c=a(l.schema);s(l.schema.enum,l.id,c)}if(l.schema?.anyOf&&Array.isArray(l.schema.anyOf)){let c=a(l.schema);l.schema.anyOf.forEach(d=>{let p=d;if(p.enum&&Array.isArray(p.enum))s(p.enum,l.id,c);else if(p.$ref){let g=p.$ref.split("/").pop();g&&c[g]&&(n[o(l.id,g)]=c[g])}else if(p.title){let g=p.title,m=c[g]||mt(g);n[o(l.id,g)]=m}})}});let u={...so,...n};Object.keys(u).length>0&&O(r.cesdk,{en:u})}async function co({options:e,provider:t,panelInput:r,config:i,providerConfig:n},o){let{id:a}=t;if(r==null)return;i.debug&&console.log(`Provider: ${a} (schema-based)`);let s=Xa(r.document),u=Lt(s,r.inputReference);if(!eo(u,i.debug))throw new Error(`Input reference '${r.inputReference}' does not resolve to a valid OpenAPI schema`);let l=u,c=Ot(l,r);return uo(c,t,e,t.kind),d=>{let{builder:p}=d,g=[];p.Section(`${a}.schema.section`,{children:()=>{c.forEach(b=>{let v=lo(d,b,t,r,e,i,t.kind,n);v!=null&&(Array.isArray(v)?g.push(...v):g.push(v))})}});let m=g.map(b=>b()),f=b=>b.type==="object"?Object.entries(b.value).reduce((v,[S,C])=>(v[S]=f(C),v),{}):b.value,y=m.reduce((b,v)=>(b[v.id]=f(v),b),{});_t(d,t,o,()=>({input:y}),()=>r.getBlockInput(y),{...e,requiredInputs:l.required,createPlaceholderBlock:r.userFlow==="placeholder"},i)}}var go=co;async function po(e,t){if(e.panelInput!=null)switch(e.panelInput.type){case"custom":return Ja(e,t);case"schema":return go(e,t);default:e.config.debug&&console.warn(`Invalid panel input type '${panelInput.type}' - skipping`)}}var fo=po;function mo(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 yr(a,r)),a}return i}var bo=mo;function yo(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 ho=yo,Le="@imgly/plugin-ai-generation",vo=`
<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.0594