@imgly/plugin-ai-audio-generation-web
Version:
AI audio generation plugin for the CE.SDK editor
13 lines • 81 kB
JavaScript
var lr=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;U(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=()=>{U(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 U(e,i=>{r.add(i)}),await Promise.all([...r].map(async i=>{let n=await this.createBlobUrlFromStore(i);t[i]=n})),U(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 U(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]=U(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]=U(n,t,o)}return e}var sr=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 ur=typeof global=="object"&&global&&global.Object===Object&&global,yt=ur,cr=typeof self=="object"&&self&&self.Object===Object&&self,dr=yt||cr||Function("return this")(),L=dr,gr=L.Symbol,V=gr,ht=Object.prototype,pr=ht.hasOwnProperty,fr=ht.toString,X=V?V.toStringTag:void 0;function mr(e){var t=pr.call(e,X),r=e[X];try{e[X]=void 0;var i=!0}catch{}var n=fr.call(e);return i&&(t?e[X]=r:delete e[X]),n}var br=mr,yr=Object.prototype,hr=yr.toString;function vr(e){return hr.call(e)}var wr=vr,kr="[object Null]",Ir="[object Undefined]",et=V?V.toStringTag:void 0;function Ar(e){return e==null?e===void 0?Ir:kr:et&&et in Object(e)?br(e):wr(e)}var oe=Ar;function Sr(e){return e!=null&&typeof e=="object"}var De=Sr,$u=Array.isArray;function Cr(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var vt=Cr,xr="[object AsyncFunction]",Er="[object Function]",Mr="[object GeneratorFunction]",jr="[object Proxy]";function Lr(e){if(!vt(e))return!1;var t=oe(e);return t==Er||t==Mr||t==xr||t==jr}var $r=Lr,_r=L["__core-js_shared__"],xe=_r,tt=function(){var e=/[^.]+$/.exec(xe&&xe.keys&&xe.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function Tr(e){return!!tt&&tt in e}var Pr=Tr,Nr=Function.prototype,Or=Nr.toString;function Dr(e){if(e!=null){try{return Or.call(e)}catch{}try{return e+""}catch{}}return""}var O=Dr,zr=/[\\^$.*+?()[\]{}|]/g,Rr=/^\[object .+?Constructor\]$/,Fr=Function.prototype,Ur=Object.prototype,Vr=Fr.toString,Br=Ur.hasOwnProperty,Gr=RegExp("^"+Vr.call(Br).replace(zr,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Hr(e){if(!vt(e)||Pr(e))return!1;var t=$r(e)?Gr:Rr;return t.test(O(e))}var qr=Hr;function Zr(e,t){return e?.[t]}var Yr=Zr;function Kr(e,t){var r=Yr(e,t);return qr(r)?r:void 0}var B=Kr,Qr=B(L,"WeakMap"),$e=Qr;function Wr(e,t){return e===t||e!==e&&t!==t}var Jr=Wr,Xr=9007199254740991;function ei(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=Xr}var ti=ei,_u=Object.prototype,ri="[object Arguments]";function ii(e){return De(e)&&oe(e)==ri}var rt=ii,wt=Object.prototype,ni=wt.hasOwnProperty,ai=wt.propertyIsEnumerable,Tu=rt(function(){return arguments}())?rt:function(e){return De(e)&&ni.call(e,"callee")&&!ai.call(e,"callee")},kt=typeof exports=="object"&&exports&&!exports.nodeType&&exports,it=kt&&typeof module=="object"&&module&&!module.nodeType&&module,oi=it&&it.exports===kt,nt=oi?L.Buffer:void 0,Pu=nt?nt.isBuffer:void 0,li="[object Arguments]",si="[object Array]",ui="[object Boolean]",ci="[object Date]",di="[object Error]",gi="[object Function]",pi="[object Map]",fi="[object Number]",mi="[object Object]",bi="[object RegExp]",yi="[object Set]",hi="[object String]",vi="[object WeakMap]",wi="[object ArrayBuffer]",ki="[object DataView]",Ii="[object Float32Array]",Ai="[object Float64Array]",Si="[object Int8Array]",Ci="[object Int16Array]",xi="[object Int32Array]",Ei="[object Uint8Array]",Mi="[object Uint8ClampedArray]",ji="[object Uint16Array]",Li="[object Uint32Array]",I={};I[Ii]=I[Ai]=I[Si]=I[Ci]=I[xi]=I[Ei]=I[Mi]=I[ji]=I[Li]=!0;I[li]=I[si]=I[wi]=I[ui]=I[ki]=I[ci]=I[di]=I[gi]=I[pi]=I[fi]=I[mi]=I[bi]=I[yi]=I[hi]=I[vi]=!1;function $i(e){return De(e)&&ti(e.length)&&!!I[oe(e)]}var _i=$i;function Ti(e){return function(t){return e(t)}}var Pi=Ti,It=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ie=It&&typeof module=="object"&&module&&!module.nodeType&&module,Ni=ie&&ie.exports===It,Ee=Ni&&yt.process,Oi=function(){try{var e=ie&&ie.require&&ie.require("util").types;return e||Ee&&Ee.binding&&Ee.binding("util")}catch{}}(),at=Oi,ot=at&&at.isTypedArray,Nu=ot?Pi(ot):_i,Di=Object.prototype,Ou=Di.hasOwnProperty;function zi(e,t){return function(r){return e(t(r))}}var Ri=zi,Du=Ri(Object.keys,Object),Fi=Object.prototype,zu=Fi.hasOwnProperty,Ui=B(Object,"create"),ne=Ui;function Vi(){this.__data__=ne?ne(null):{},this.size=0}var Bi=Vi;function Gi(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var Hi=Gi,qi="__lodash_hash_undefined__",Zi=Object.prototype,Yi=Zi.hasOwnProperty;function Ki(e){var t=this.__data__;if(ne){var r=t[e];return r===qi?void 0:r}return Yi.call(t,e)?t[e]:void 0}var Qi=Ki,Wi=Object.prototype,Ji=Wi.hasOwnProperty;function Xi(e){var t=this.__data__;return ne?t[e]!==void 0:Ji.call(t,e)}var en=Xi,tn="__lodash_hash_undefined__";function rn(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=ne&&t===void 0?tn:t,this}var nn=rn;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=Bi;G.prototype.delete=Hi;G.prototype.get=Qi;G.prototype.has=en;G.prototype.set=nn;var lt=G;function an(){this.__data__=[],this.size=0}var on=an;function ln(e,t){for(var r=e.length;r--;)if(Jr(e[r][0],t))return r;return-1}var he=ln,sn=Array.prototype,un=sn.splice;function cn(e){var t=this.__data__,r=he(t,e);if(r<0)return!1;var i=t.length-1;return r==i?t.pop():un.call(t,r,1),--this.size,!0}var dn=cn;function gn(e){var t=this.__data__,r=he(t,e);return r<0?void 0:t[r][1]}var pn=gn;function fn(e){return he(this.__data__,e)>-1}var mn=fn;function bn(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 yn=bn;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=on;H.prototype.delete=dn;H.prototype.get=pn;H.prototype.has=mn;H.prototype.set=yn;var ve=H,hn=B(L,"Map"),ae=hn;function vn(){this.size=0,this.__data__={hash:new lt,map:new(ae||ve),string:new lt}}var wn=vn;function kn(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var In=kn;function An(e,t){var r=e.__data__;return In(t)?r[typeof t=="string"?"string":"hash"]:r.map}var we=An;function Sn(e){var t=we(this,e).delete(e);return this.size-=t?1:0,t}var Cn=Sn;function xn(e){return we(this,e).get(e)}var En=xn;function Mn(e){return we(this,e).has(e)}var jn=Mn;function Ln(e,t){var r=we(this,e),i=r.size;return r.set(e,t),this.size+=r.size==i?0:1,this}var $n=Ln;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=wn;q.prototype.delete=Cn;q.prototype.get=En;q.prototype.has=jn;q.prototype.set=$n;var At=q;function _n(){this.__data__=new ve,this.size=0}var Tn=_n;function Pn(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var Nn=Pn;function On(e){return this.__data__.get(e)}var Dn=On;function zn(e){return this.__data__.has(e)}var Rn=zn,Fn=200;function Un(e,t){var r=this.__data__;if(r instanceof ve){var i=r.__data__;if(!ae||i.length<Fn-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 Vn=Un;function le(e){var t=this.__data__=new ve(e);this.size=t.size}le.prototype.clear=Tn;le.prototype.delete=Nn;le.prototype.get=Dn;le.prototype.has=Rn;le.prototype.set=Vn;var Bn=Object.prototype,Ru=Bn.propertyIsEnumerable,Gn=B(L,"DataView"),_e=Gn,Hn=B(L,"Promise"),Te=Hn,qn=B(L,"Set"),Pe=qn,st="[object Map]",Zn="[object Object]",ut="[object Promise]",ct="[object Set]",dt="[object WeakMap]",gt="[object DataView]",Yn=O(_e),Kn=O(ae),Qn=O(Te),Wn=O(Pe),Jn=O($e),F=oe;(_e&&F(new _e(new ArrayBuffer(1)))!=gt||ae&&F(new ae)!=st||Te&&F(Te.resolve())!=ut||Pe&&F(new Pe)!=ct||$e&&F(new $e)!=dt)&&(F=function(e){var t=oe(e),r=t==Zn?e.constructor:void 0,i=r?O(r):"";if(i)switch(i){case Yn:return gt;case Kn:return st;case Qn:return ut;case Wn:return ct;case Jn:return dt}return t});var Fu=L.Uint8Array,Xn="__lodash_hash_undefined__";function ea(e){return this.__data__.set(e,Xn),this}var ta=ea;function ra(e){return this.__data__.has(e)}var ia=ra;function Ne(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new At;++t<r;)this.add(e[t])}Ne.prototype.add=Ne.prototype.push=ta;Ne.prototype.has=ia;var pt=V?V.prototype:void 0,Uu=pt?pt.valueOf:void 0,na=Object.prototype,Vu=na.hasOwnProperty,aa=Object.prototype,Bu=aa.hasOwnProperty,Gu=new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,"i"),Hu=new RegExp(/[A-Fa-f0-9]{1}/,"g"),qu=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 oa(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 la(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 sa(e){return e!==void 0}var ua=sa;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 ze=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))}},ca=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 da(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),m={...d,addDisposer:a};return p(u,m,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 ga({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 pa=ga;var Me="ly.img.ai.temp";async function fa(e,t){return e.engine.asset.findAllSources().includes(Me)||e.engine.asset.addLocalSource(Me),e.engine.asset.apply(Me,t)}function ma(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 ba(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 ya(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 Re(e){return e instanceof Error&&e.name==="AbortError"}function ha(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 va(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 Fe=va;function wa(e,t){let{cesdk:r,provider:i,getInput:n,middlewareOptions:o}=t;o?.defaultPrevented()||(console.error("Generation failed:",e),ka(r,i.output.notification,()=>({input:n?.().input,error:e}))||r.ui.showNotification({type:"error",message:ma(e)}))}function ka(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=wa,Ia="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIzIiBoZWlnaHQ9IjMyMyIgdmlld0JveD0iMCAwIDMyMyAzMjMiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIzMjMiIGhlaWdodD0iMzIzIiBmaWxsPSIjRTlFQkVEIi8+CjxnIG9wYWNpdHk9IjAuMyI+CjxwYXRoIGQ9Ik0xMTYgMTg0VjE5MS41QzExNiAxOTkuNzg0IDEyMi43MTYgMjA2LjUgMTMxIDIwNi41SDE5MUMxOTkuMjg0IDIwNi41IDIwNiAxOTkuNzg0IDIwNiAxOTEuNVYxMzEuNUMyMDYgMTIzLjIxNiAxOTkuMjg0IDExNi41IDE5MSAxMTYuNUwxOTAuOTk1IDEyNi41QzE5My43NTcgMTI2LjUgMTk2IDEyOC43MzkgMTk2IDEzMS41VjE5MS41QzE5NiAxOTQuMjYxIDE5My43NjEgMTk2LjUgMTkxIDE5Ni41SDEzMUMxMjguMjM5IDE5Ni41IDEyNiAxOTQuMjYxIDEyNiAxOTEuNVYxODRIMTE2WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTY2LjQ5NCAxMDUuOTI0QzE2NS44NjkgMTA0LjM0MiAxNjMuNjI5IDEwNC4zNDIgMTYzLjAwNSAxMDUuOTI0TDE1OS43NDUgMTE0LjE5MUMxNTkuNTU0IDExNC42NzQgMTU5LjE3MiAxMTUuMDU3IDE1OC42ODggMTE1LjI0N0wxNTAuNDIyIDExOC41MDhDMTQ4LjgzOSAxMTkuMTMyIDE0OC44MzkgMTIxLjM3MiAxNTAuNDIyIDEyMS45OTZMMTU4LjY4OCAxMjUuMjU2QzE1OS4xNzIgMTI1LjQ0NyAxNTkuNTU0IDEyNS44MjkgMTU5Ljc0NSAxMjYuMzEzTDE2My4wMDUgMTM0LjU3OUMxNjMuNjI5IDEzNi4xNjIgMTY1Ljg2OSAxMzYuMTYyIDE2Ni40OTQgMTM0LjU3OUwxNjkuNzU0IDEyNi4zMTNDMTY5Ljk0NCAxMjUuODI5IDE3MC4zMjcgMTI1LjQ0NyAxNzAuODEgMTI1LjI1NkwxNzkuMDc3IDEyMS45OTZDMTgwLjY2IDEyMS4zNzIgMTgwLjY2IDExOS4xMzIgMTc5LjA3NyAxMTguNTA4TDE3MC44MSAxMTUuMjQ3QzE3MC4zMjcgMTE1LjA1NyAxNjkuOTQ0IDExNC42NzQgMTY5Ljc1NCAxMTQuMTkxTDE2Ni40OTQgMTA1LjkyNFoiIGZpbGw9IiM4RjhGOEYiLz4KPHBhdGggZD0iTTEzMy4wMDUgMTI4LjQyNEMxMzMuNjI5IDEyNi44NDIgMTM1Ljg2OSAxMjYuODQyIDEzNi40OTQgMTI4LjQyNEwxNDEuODc1IDE0Mi4wN0MxNDIuMDY2IDE0Mi41NTMgMTQyLjQ0OCAxNDIuOTM1IDE0Mi45MzIgMTQzLjEyNkwxNTYuNTc3IDE0OC41MDhDMTU4LjE2IDE0OS4xMzIgMTU4LjE2IDE1MS4zNzIgMTU2LjU3NyAxNTEuOTk2TDE0Mi45MzIgMTU3LjM3OEMxNDIuNDQ4IDE1Ny41NjggMTQyLjA2NiAxNTcuOTUxIDE0MS44NzUgMTU4LjQzNEwxMzYuNDk0IDE3Mi4wNzlDMTM1Ljg2OSAxNzMuNjYyIDEzMy42MjkgMTczLjY2MiAxMzMuMDA1IDE3Mi4wNzlMMTI3LjYyMyAxNTguNDM0QzEyNy40MzMgMTU3Ljk1MSAxMjcuMDUgMTU3LjU2OCAxMjYuNTY3IDE1Ny4zNzhMMTEyLjkyMiAxNTEuOTk2QzExMS4zMzkgMTUxLjM3MiAxMTEuMzM5IDE0OS4xMzIgMTEyLjkyMiAxNDguNTA4TDEyNi41NjcgMTQzLjEyNkMxMjcuMDUgMTQyLjkzNSAxMjcuNDMzIDE0Mi41NTMgMTI3LjYyMyAxNDIuMDdMMTMzLjAwNSAxMjguNDI0WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTk1Ljk5OSAxODQuMDA0VjE5MS41MDJDMTk1Ljk5OSAxOTQuMjYzIDE5My43NjEgMTk2LjUwMiAxOTAuOTk5IDE5Ni41MDJIMTQ3LjY2OEwxNzIuODc5IDE1OC42ODRDMTc0LjM2MyAxNTYuNDU4IDE3Ny42MzUgMTU2LjQ1OCAxNzkuMTIgMTU4LjY4NEwxOTUuOTk5IDE4NC4wMDRaIiBmaWxsPSIjOEY4RjhGIi8+CjwvZz4KPC9zdmc+Cg==",Ue=Ia;function Aa(e,t,r){switch(t){case"image":return Sa(e,r[t]);case"video":return Ca(e,r[t]);case"sticker":return xa(e,r[t]);default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function Sa(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 Ca(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 xa(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 Ea=Aa;async function Ma(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 ja(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 La(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 $a(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 _a(e,r[t],i)}default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function ja(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 La(e,t,r){let i=t.width,n=t.height,o=await ba(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 $a(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 _a(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 jt=Ma;function Ta(e){switch(e.userFlow){case"placeholder":return Na(e);case"generation-only":return Pa(e);default:throw new Error(`Unknown user flow: ${e.userFlow}. Expected 'placeholder' or 'generation-only'.`)}}function Pa(e){let{cesdk:t,abortSignal:r}=e;return async i=>{try{let n=e.kind,o=await e.getBlockInput(i);if(T(t,r))return{status:"aborted"};let a=await e.generate(i,{middlewares:[...e.middlewares??[]],debug:e.debug,dryRun:e.dryRun,abortSignal:r});if(T(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(t,r))return{status:"aborted"};if(e.historyAssetSourceId!=null){let s=Et(),c=await jt(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 Na(e){let{cesdk:t,abortSignal:r}=e,i;return async n=>{try{let o=e.kind,a=await e.getBlockInput(n);if(T(t,r))return{status:"aborted"};let s=Et(),c=Ea(s,o,a);if(i=await fa(t,c),T(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(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 jt(s,o,a,l.output);if(T(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(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)&&(Re(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 T(e,t,r){return t.aborted?(r!=null&&e.engine.block.isValid(r)&&e.engine.block.destroy(r),!0):!1}var Oa=Ta;function Ve(e){return`${e}.generating`}function Da(e){return`${e}.abort`}function za(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(Da(d),()=>{}),m=c.global(Ve(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=c.global(`${d}.confirmationDialogId`,void 0);s.Section(`${d}.generate.section`,{children:()=>{s.Button(`${d}.generate`,{label:["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 Oa({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;Ra(l,E,()=>({input:i().input,output:w.output}))}}catch(w){if(Re(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})}}),u&&o.historyAssetLibraryEntryId!=null&&s.Library(`${d}.history.library`,{entries:[o.historyAssetLibraryEntryId]})}function Ra(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 Lt=za;async function Fa({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 c=>{let{state:l}=c,u=l(Ve(a),{isGenerating:!1,abort:()=>{}}).value.isGenerating,{getInput:d,getBlockInput:p}=s(c,{cesdk:o,isGenerating:u});return Lt(c,t,n,d,p,{...e,includeHistoryLibrary:r.includeHistoryLibrary??!0,createPlaceholderBlock:r.userFlow==="placeholder"},i),d}}var Ua=Fa;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 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=$t(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 Va(e){return te(e,{...e})}function Ba(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 Ga(e,t){if(e.properties==null)throw new Error("Input schema must have properties");let r=e.properties,i=[];return Ha(e,t).forEach(n=>{let o=n,a=r[n]??void 0;i.push({id:o,schema:a})}),i}function Ha(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=qa(e,t)??n;return r!=null&&typeof r=="function"&&(o=r(o)),[...new Set(o)]}function qa(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 _t=Ga;function P(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 Tt(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?Za(e,c,r,i,n,o,a,s):Nt(e,c,r,i,n,o,a,s);case"boolean":return Ot(e,c,r,i,n,o,a,s);case"number":case"integer":return Dt(e,c,r,i,n,o,a,s);case"object":return Oe(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 Ya(e,c,r,i,n,o,a,s);break}default:console.error(`Unsupported property type: ${l}`)}}function Oe(e,t,r,i,n,o,a,s){let c=_t(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=P(t,r,a),m=P(t,r,a,"placeholder"),f=se(u,n.cesdk),y=s?.properties?.[d]??o.properties?.[d],b=ue(d,y,f,t.schema.default,""),v=l(p,b),S=Ka(t.schema),C=S?.component!=null&&S?.component==="TextArea"?"TextArea":"TextInput",w=m.length>0?m:void 0;return c[C](p,{inputLabel:g,...w&&{placeholder:w},...v}),()=>({id:t.id,type:"string",value:v.value})}function Za(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=P(t,r,a),{labels:m,icons:f}=Tt(t.schema),y=(t.schema.enum??[]).map(E=>({id:E,label:P(t,r,a,E),icon:f[E]})),b=se(u,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 c.Select(p,{inputLabel:g,values:y,...w}),()=>({id:t.id,type:"string",value:w.value.id})}function Ot(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=P(t,r,a),m=se(u,n.cesdk),f=s?.properties?.[d]??o.properties?.[d],y=!!ue(d,f,m,t.schema.default,!1),b=l(p,y);return c.Checkbox(p,{inputLabel:g,...b}),()=>({id:t.id,type:"boolean",value:b.value})}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=P(t,r,a),m=t.schema.minimum,f=t.schema.maximum,y=se(u,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"]),c.Slider(p,{inputLabel:g,min:m,max:f,step:w,...C})}else c.NumberInput(p,{inputLabel:g,min:m,max:f,...C});return()=>({id:t.id,type:"integer",value:C.value})}function Ya(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=P(t,r,a),m=t.schema.anyOf??[],f=[],y={},b={},{labels:v,icons:S}=Tt(t.schema),C=se(u,n.cesdk),w=s?.properties?.[d]??o.properties?.[d],E={string:Nt,boolean:Ot,integer:Dt,object:Oe},be=(h,j)=>h.$ref?h.$ref.split("/").pop():j.split(".").pop()??j,N=(h,j)=>({id:h,label:P(t,r,a,j),icon:S[j]??S[h]});m.forEach((h,j)=>{let k=`${r.id}.${d}.anyOf[${j}]`;if(h.$ref||h.title){let x=h.$ref?h.$ref.split("/").pop():h.title;y[k]=()=>Oe(e,{id:k,schema:{...h,title:v[x]||x}},r,i,n,o,a,s),f.push(N(k,x))}else if(h.type==="string"&&h.enum)h.enum.forEach(x=>{f.push(N(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 Ce=be(h,k);f.push(h.type==="string"&&!h.enum?{id:k,label:h.title||Ce,icon:h.title&&S[h.title]||S[Ce]}:N(k,Ce))}});let ye=ue(d,w,C,t.schema.default,null),Se=ye!=null?f.find(h=>h.id===ye)??f[0]:f[0],_=l(p,Se);if(c.Select(p,{inputLabel:g,values:f,..._}),_.value.id in y){let h=y[_.value.id]();b[_.value.id]=h}return()=>{let h=b[_.value.id];return h!=null?{...h(),id:t.id}:{id:t.id,type:"string",value:_.value.id}}}function Ka(e){if("x-imgly-builder"in e)return e["x-imgly-builder"]}var Qa=Pt,Wa={"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 Ja(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),m=d[g]||mt(g);n[o(u,g)]=m})};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,m=u[g]||mt(g);n[o(l.id,g)]=m}})}});let c={...Wa,...n};Object.keys(c).length>0&&r.cesdk.i18n.setTranslations({en:c})}async function Xa({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=Va(r.document),c=$t(s,r.inputReference);if(!Ba(c,i.debug))throw new Error(`Input reference '${r.inputReference}' does not resolve to a valid OpenAPI schema`);let l=c,u=_t(l,r);return Ja(u,t,e,t.kind),d=>{let{builder:p}=d,g=[];p.Section(`${a}.schema.section`,{children:()=>{u.forEach(b=>{let v=Qa(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),{});Lt(d,t,o,()=>({input:y}),()=>r.getBlockInput(y),{...e,requiredInputs:l.required,createPlaceholderBlock:r.userFlow==="placeholder"},i)}}var eo=Xa;async function to(e,t){if(e.panelInput!=null)switch(e.panelInput.type){case"custom":return Ua(e,t);case"schema":return eo(e,t);default:e.config.debug&&console.warn(`Invalid panel input type '${panelInput.type}' - skipping`)}}var ro=to;function io(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 lr(a,r)),a}return i}var no=io;function ao(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 oo=ao,je="@imgly/plugin-ai-generation",lo=`
<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.96366L15.789 8.92118C15.9229 8.97138 16.0285 9.077 16.0787 9.21085L17.0362 11.7642C17.1968 12.1925 17.8026 12.1925 17.9