@imgly/plugin-ai-audio-generation-web
Version:
AI audio generation plugin for the CE.SDK editor
12 lines • 79.1 kB
JavaScript
var Zt=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="",f=[];l.label!=null&&typeof l.label=="object"&&l.label[c]&&(d=l.label[c]),l.tags!=null&&typeof l.tags=="object"&&l.tags[c]&&(f=l.tags[c]);let p={...l,label:d,tags:f};return this.filterAsset(p,e)&&u.push(p),u},[]);t=await this.restoreBlobUrls(t),t=this.sortAssets(t,e);let{page:r,perPage:i}=e,n=r*i,a=n+i,o=t.slice(n,a),s=a<t.length?r+1:void 0;return{assets:o,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(a=>{a.groups&&Array.isArray(a.groups)&&a.groups.forEach(o=>i.add(o))});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;P(e,a=>{i.add(a)}),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=()=>{P(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((a,o)=>{let s=a.meta?.insertedAt||a._insertedAt||Date.now(),u=o.meta?.insertedAt||o._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,a])=>{let o={id:n,blob:a};i.put(o)}),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 P(e,i=>{r.add(i)}),await Promise.all([...r].map(async i=>{let n=await this.createBlobUrlFromStore(i);t[i]=n})),P(e,i=>t[i]??i)}filterAsset(e,t){let{query:r,tags:i,groups:n,excludeGroups:a}=t;if(r&&r.trim()!==""){let o=r.trim().toLowerCase().split(" "),s=e.label?.toLowerCase()??"",u=e.tags?.map(l=>l.toLowerCase())??[];if(!o.every(l=>s.includes(l)||u.some(c=>c.includes(l))))return!1}if(i){let o=Array.isArray(i)?i:[i];if(o.length>0&&(!e.tags||!o.every(s=>e.tags?.includes(s))))return!1}return!(n&&n.length>0&&(!e.groups||!n.some(o=>e.groups?.includes(o)))||a&&a.length>0&&e.groups&&e.groups.some(o=>a.includes(o)))}sortAssets(e,t){let{sortingOrder:r,sortKey:i,sortActiveFirst:n}=t,a=[...e];return!r||r==="None"||(i?a.sort((o,s)=>{let u,l;return i==="id"?(u=o.id,l=s.id):(u=o.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"&&a.reverse(),n&&a.sort((o,s)=>o.active&&!s.active?-1:!o.active&&s.active?1:0)),a}};function P(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 a=t(e[i],n);typeof a=="string"&&(e[i]=a)}else e[i]=P(e[i],t,n)}return e}for(let i in e)if(Object.prototype.hasOwnProperty.call(e,i)){let n=e[i],a=r?`${r}.${i}`:i;if(typeof n=="string"&&n.startsWith("blob:")){let o=t(n,a);typeof o=="string"&&(e[i]=o)}else e[i]=P(n,t,a)}return e}var Yt=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 f=c.meta?.insertedAt||0;return(d.meta?.insertedAt||0)-f});let{page:n,perPage:a}=e,o=n*a,s=o+a,u=i.slice(o,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 Qt=typeof global=="object"&&global&&global.Object===Object&&global,rt=Qt,Wt=typeof self=="object"&&self&&self.Object===Object&&self,Kt=rt||Wt||Function("return this")(),S=Kt,Jt=S.Symbol,O=Jt,it=Object.prototype,Xt=it.hasOwnProperty,er=it.toString,Z=O?O.toStringTag:void 0;function tr(e){var t=Xt.call(e,Z),r=e[Z];try{e[Z]=void 0;var i=!0}catch{}var n=er.call(e);return i&&(t?e[Z]=r:delete e[Z]),n}var rr=tr,ir=Object.prototype,nr=ir.toString;function or(e){return nr.call(e)}var ar=or,sr="[object Null]",lr="[object Undefined]",Re=O?O.toStringTag:void 0;function ur(e){return e==null?e===void 0?lr:sr:Re&&Re in Object(e)?rr(e):ar(e)}var X=ur;function cr(e){return e!=null&&typeof e=="object"}var Se=cr,hu=Array.isArray;function dr(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var nt=dr,pr="[object AsyncFunction]",gr="[object Function]",fr="[object GeneratorFunction]",mr="[object Proxy]";function hr(e){if(!nt(e))return!1;var t=X(e);return t==gr||t==fr||t==pr||t==mr}var br=hr,yr=S["__core-js_shared__"],fe=yr,Fe=function(){var e=/[^.]+$/.exec(fe&&fe.keys&&fe.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function vr(e){return!!Fe&&Fe in e}var wr=vr,kr=Function.prototype,Ir=kr.toString;function Ar(e){if(e!=null){try{return Ir.call(e)}catch{}try{return e+""}catch{}}return""}var j=Ar,Sr=/[\\^$.*+?()[\]{}|]/g,xr=/^\[object .+?Constructor\]$/,Cr=Function.prototype,Er=Object.prototype,Mr=Cr.toString,jr=Er.hasOwnProperty,$r=RegExp("^"+Mr.call(jr).replace(Sr,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function _r(e){if(!nt(e)||wr(e))return!1;var t=br(e)?$r:xr;return t.test(j(e))}var Lr=_r;function Nr(e,t){return e?.[t]}var Pr=Nr;function Or(e,t){var r=Pr(e,t);return Lr(r)?r:void 0}var D=Or,Dr=D(S,"WeakMap"),ve=Dr;function Tr(e,t){return e===t||e!==e&&t!==t}var zr=Tr,Rr=9007199254740991;function Fr(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=Rr}var Ur=Fr,bu=Object.prototype,Vr="[object Arguments]";function Br(e){return Se(e)&&X(e)==Vr}var Ue=Br,ot=Object.prototype,Gr=ot.hasOwnProperty,Hr=ot.propertyIsEnumerable,yu=Ue(function(){return arguments}())?Ue:function(e){return Se(e)&&Gr.call(e,"callee")&&!Hr.call(e,"callee")},at=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ve=at&&typeof module=="object"&&module&&!module.nodeType&&module,qr=Ve&&Ve.exports===at,Be=qr?S.Buffer:void 0,vu=Be?Be.isBuffer:void 0,Zr="[object Arguments]",Yr="[object Array]",Qr="[object Boolean]",Wr="[object Date]",Kr="[object Error]",Jr="[object Function]",Xr="[object Map]",ei="[object Number]",ti="[object Object]",ri="[object RegExp]",ii="[object Set]",ni="[object String]",oi="[object WeakMap]",ai="[object ArrayBuffer]",si="[object DataView]",li="[object Float32Array]",ui="[object Float64Array]",ci="[object Int8Array]",di="[object Int16Array]",pi="[object Int32Array]",gi="[object Uint8Array]",fi="[object Uint8ClampedArray]",mi="[object Uint16Array]",hi="[object Uint32Array]",v={};v[li]=v[ui]=v[ci]=v[di]=v[pi]=v[gi]=v[fi]=v[mi]=v[hi]=!0;v[Zr]=v[Yr]=v[ai]=v[Qr]=v[si]=v[Wr]=v[Kr]=v[Jr]=v[Xr]=v[ei]=v[ti]=v[ri]=v[ii]=v[ni]=v[oi]=!1;function bi(e){return Se(e)&&Ur(e.length)&&!!v[X(e)]}var yi=bi;function vi(e){return function(t){return e(t)}}var wi=vi,st=typeof exports=="object"&&exports&&!exports.nodeType&&exports,W=st&&typeof module=="object"&&module&&!module.nodeType&&module,ki=W&&W.exports===st,me=ki&&rt.process,Ii=function(){try{var e=W&&W.require&&W.require("util").types;return e||me&&me.binding&&me.binding("util")}catch{}}(),Ge=Ii,He=Ge&&Ge.isTypedArray,wu=He?wi(He):yi,Ai=Object.prototype,ku=Ai.hasOwnProperty;function Si(e,t){return function(r){return e(t(r))}}var xi=Si,Iu=xi(Object.keys,Object),Ci=Object.prototype,Au=Ci.hasOwnProperty,Ei=D(Object,"create"),K=Ei;function Mi(){this.__data__=K?K(null):{},this.size=0}var ji=Mi;function $i(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var _i=$i,Li="__lodash_hash_undefined__",Ni=Object.prototype,Pi=Ni.hasOwnProperty;function Oi(e){var t=this.__data__;if(K){var r=t[e];return r===Li?void 0:r}return Pi.call(t,e)?t[e]:void 0}var Di=Oi,Ti=Object.prototype,zi=Ti.hasOwnProperty;function Ri(e){var t=this.__data__;return K?t[e]!==void 0:zi.call(t,e)}var Fi=Ri,Ui="__lodash_hash_undefined__";function Vi(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=K&&t===void 0?Ui:t,this}var Bi=Vi;function T(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])}}T.prototype.clear=ji;T.prototype.delete=_i;T.prototype.get=Di;T.prototype.has=Fi;T.prototype.set=Bi;var qe=T;function Gi(){this.__data__=[],this.size=0}var Hi=Gi;function qi(e,t){for(var r=e.length;r--;)if(zr(e[r][0],t))return r;return-1}var le=qi,Zi=Array.prototype,Yi=Zi.splice;function Qi(e){var t=this.__data__,r=le(t,e);if(r<0)return!1;var i=t.length-1;return r==i?t.pop():Yi.call(t,r,1),--this.size,!0}var Wi=Qi;function Ki(e){var t=this.__data__,r=le(t,e);return r<0?void 0:t[r][1]}var Ji=Ki;function Xi(e){return le(this.__data__,e)>-1}var en=Xi;function tn(e,t){var r=this.__data__,i=le(r,e);return i<0?(++this.size,r.push([e,t])):r[i][1]=t,this}var rn=tn;function z(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])}}z.prototype.clear=Hi;z.prototype.delete=Wi;z.prototype.get=Ji;z.prototype.has=en;z.prototype.set=rn;var ue=z,nn=D(S,"Map"),J=nn;function on(){this.size=0,this.__data__={hash:new qe,map:new(J||ue),string:new qe}}var an=on;function sn(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var ln=sn;function un(e,t){var r=e.__data__;return ln(t)?r[typeof t=="string"?"string":"hash"]:r.map}var ce=un;function cn(e){var t=ce(this,e).delete(e);return this.size-=t?1:0,t}var dn=cn;function pn(e){return ce(this,e).get(e)}var gn=pn;function fn(e){return ce(this,e).has(e)}var mn=fn;function hn(e,t){var r=ce(this,e),i=r.size;return r.set(e,t),this.size+=r.size==i?0:1,this}var bn=hn;function R(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])}}R.prototype.clear=an;R.prototype.delete=dn;R.prototype.get=gn;R.prototype.has=mn;R.prototype.set=bn;var lt=R;function yn(){this.__data__=new ue,this.size=0}var vn=yn;function wn(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var kn=wn;function In(e){return this.__data__.get(e)}var An=In;function Sn(e){return this.__data__.has(e)}var xn=Sn,Cn=200;function En(e,t){var r=this.__data__;if(r instanceof ue){var i=r.__data__;if(!J||i.length<Cn-1)return i.push([e,t]),this.size=++r.size,this;r=this.__data__=new lt(i)}return r.set(e,t),this.size=r.size,this}var Mn=En;function ee(e){var t=this.__data__=new ue(e);this.size=t.size}ee.prototype.clear=vn;ee.prototype.delete=kn;ee.prototype.get=An;ee.prototype.has=xn;ee.prototype.set=Mn;var jn=Object.prototype,Su=jn.propertyIsEnumerable,$n=D(S,"DataView"),we=$n,_n=D(S,"Promise"),ke=_n,Ln=D(S,"Set"),Ie=Ln,Ze="[object Map]",Nn="[object Object]",Ye="[object Promise]",Qe="[object Set]",We="[object WeakMap]",Ke="[object DataView]",Pn=j(we),On=j(J),Dn=j(ke),Tn=j(Ie),zn=j(ve),N=X;(we&&N(new we(new ArrayBuffer(1)))!=Ke||J&&N(new J)!=Ze||ke&&N(ke.resolve())!=Ye||Ie&&N(new Ie)!=Qe||ve&&N(new ve)!=We)&&(N=function(e){var t=X(e),r=t==Nn?e.constructor:void 0,i=r?j(r):"";if(i)switch(i){case Pn:return Ke;case On:return Ze;case Dn:return Ye;case Tn:return Qe;case zn:return We}return t});var xu=S.Uint8Array,Rn="__lodash_hash_undefined__";function Fn(e){return this.__data__.set(e,Rn),this}var Un=Fn;function Vn(e){return this.__data__.has(e)}var Bn=Vn;function Ae(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new lt;++t<r;)this.add(e[t])}Ae.prototype.add=Ae.prototype.push=Un;Ae.prototype.has=Bn;var Je=O?O.prototype:void 0,Cu=Je?Je.valueOf:void 0,Gn=Object.prototype,Eu=Gn.hasOwnProperty,Hn=Object.prototype,Mu=Hn.hasOwnProperty,ju=new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,"i"),$u=new RegExp(/[A-Fa-f0-9]{1}/,"g"),_u=new RegExp(/[A-Fa-f0-9]{2}/,"g");async function ut(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),a=new Blob([n],{type:r});return URL.createObjectURL(a)}else return e}async function qn(e,t){let r=await ut(e,t);return new Promise((i,n)=>{let a=new Image;a.onload=()=>{i({width:a.width,height:a.height})},a.onerror=n,a.src=r})}async function Zn(e,t,r){let i,n=t.block.getFill(e),a=t.block.getSourceSet(n,"fill/image/sourceSet"),[o]=a;if(o==null){if(i=t.block.getString(n,"fill/image/imageFileURI"),i==null)throw new Error("No image source/uri found")}else i=o.uri;if(r?.throwErrorIfSvg&&await t.editor.getMimeType(i)==="image/svg+xml")throw new Error("SVG images are not supported");return ut(i,t)}function Yn(e){return e!==void 0}var Qn=Yn;var ct=class dt{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 dt),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))}},Wn=class pt{constructor(){this.providers=new Map}static get(){let t="__imgly_provider_registry__",r=typeof window<"u"?window:globalThis;return r[t]||(r[t]=new pt),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 Kn(e){let t=e.filter(r=>!!r);return r=>async(i,n)=>{let a=[],o=l=>{a.push(l)},s=async(l,c,d)=>{if(l>=t.length)return r(c,d);let f=t[l],p=async(h,b)=>s(l+1,h,b),g={...d,addDisposer:o};return f(c,g,p)},u={...n,addDisposer:o};return{result:await s(0,i,u),dispose:async()=>{for(let l=a.length-1;l>=0;l--)try{await a[l]()}catch(c){console.error("Error in disposer:",c)}a.length=0}}}}function Jn({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,a=Date.now();try{return n=await i(t,r),n}finally{n!=null&&(console.log(`Generation took ${Date.now()-a}ms`),console.log("Generation result:",JSON.stringify(n,null,2))),console.groupEnd()}}}var Xn=Jn;var he="ly.img.ai.temp";async function eo(e,t){return e.engine.asset.findAllSources().includes(he)||e.engine.asset.addLocalSource(he),e.engine.asset.apply(he,t)}function to(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 gt(){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 ro(e,t=0,r="image/jpeg",i=.8){return new Promise((n,a)=>{try{let o=document.createElement("video");o.crossOrigin="anonymous",o.style.display="none",o.addEventListener("loadedmetadata",()=>{o.currentTime=Math.min(t,o.duration),o.addEventListener("seeked",()=>{let s=document.createElement("canvas");s.width=o.videoWidth,s.height=o.videoHeight;let u=s.getContext("2d");if(!u){document.body.removeChild(o),a(new Error("Failed to create canvas context"));return}u.drawImage(o,0,0,s.width,s.height);try{let l=s.toDataURL(r,i);document.body.removeChild(o),n(l)}catch(l){document.body.removeChild(o),a(new Error(`Failed to create thumbnail: ${l instanceof Error?l.message:String(l)}`))}},{once:!0})}),o.addEventListener("error",()=>{document.body.removeChild(o),a(new Error(`Failed to load video from ${e}`))}),o.src=e,document.body.appendChild(o)}catch(o){a(o)}})}function io(e){return e?e.replace(/[_-]/g," ").replace(/([A-Z])/g," $1").trim().split(" ").filter(t=>t.length>0).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join(" "):""}function no(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 xe(e){return e instanceof Error&&e.name==="AbortError"}function oo(e,t,r){let i=`${t}.iconSetAdded`;e.ui.experimental.hasGlobalStateValue(i)||(e.ui.addIconSet(t,r),e.ui.experimental.setGlobalStateValue(i,!0))}function ft(e,t,r){let i="ai-plugin-version",n="ai-plugin-version-warning-shown";try{let a=e.ui.experimental.getGlobalStateValue(i);a?a!==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 ${a}.
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(a){console.debug("[IMG.LY AI Plugins] Could not check plugin version consistency:",a)}}function ao(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 a=t.ui.isPanelOpen(r);n.Button(`${r}.dock.button`,{label:`${r}.dock.label`,isSelected:a,icon:"@imgly/Sparkle",onClick:()=>{t.ui.findAllPanels().forEach(o=>{o.startsWith("ly.img.ai.")&&t.ui.closePanel(o),!a&&o==="//ly.img.panel/assetLibrary"&&t.ui.closePanel(o)}),a?t.ui.closePanel(r):t.ui.openPanel(r)}})})}var Ce=ao;function so(e,t){let{cesdk:r,provider:i,getInput:n}=t;console.error("Generation failed:",e),lo(r,i.output.notification,()=>({input:n?.().input,error:e}))||r.ui.showNotification({type:"error",message:to(e)})}function lo(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",a=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:a}),!0}var Xe=so,uo="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIzIiBoZWlnaHQ9IjMyMyIgdmlld0JveD0iMCAwIDMyMyAzMjMiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIzMjMiIGhlaWdodD0iMzIzIiBmaWxsPSIjRTlFQkVEIi8+CjxnIG9wYWNpdHk9IjAuMyI+CjxwYXRoIGQ9Ik0xMTYgMTg0VjE5MS41QzExNiAxOTkuNzg0IDEyMi43MTYgMjA2LjUgMTMxIDIwNi41SDE5MUMxOTkuMjg0IDIwNi41IDIwNiAxOTkuNzg0IDIwNiAxOTEuNVYxMzEuNUMyMDYgMTIzLjIxNiAxOTkuMjg0IDExNi41IDE5MSAxMTYuNUwxOTAuOTk1IDEyNi41QzE5My43NTcgMTI2LjUgMTk2IDEyOC43MzkgMTk2IDEzMS41VjE5MS41QzE5NiAxOTQuMjYxIDE5My43NjEgMTk2LjUgMTkxIDE5Ni41SDEzMUMxMjguMjM5IDE5Ni41IDEyNiAxOTQuMjYxIDEyNiAxOTEuNVYxODRIMTE2WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTY2LjQ5NCAxMDUuOTI0QzE2NS44NjkgMTA0LjM0MiAxNjMuNjI5IDEwNC4zNDIgMTYzLjAwNSAxMDUuOTI0TDE1OS43NDUgMTE0LjE5MUMxNTkuNTU0IDExNC42NzQgMTU5LjE3MiAxMTUuMDU3IDE1OC42ODggMTE1LjI0N0wxNTAuNDIyIDExOC41MDhDMTQ4LjgzOSAxMTkuMTMyIDE0OC44MzkgMTIxLjM3MiAxNTAuNDIyIDEyMS45OTZMMTU4LjY4OCAxMjUuMjU2QzE1OS4xNzIgMTI1LjQ0NyAxNTkuNTU0IDEyNS44MjkgMTU5Ljc0NSAxMjYuMzEzTDE2My4wMDUgMTM0LjU3OUMxNjMuNjI5IDEzNi4xNjIgMTY1Ljg2OSAxMzYuMTYyIDE2Ni40OTQgMTM0LjU3OUwxNjkuNzU0IDEyNi4zMTNDMTY5Ljk0NCAxMjUuODI5IDE3MC4zMjcgMTI1LjQ0NyAxNzAuODEgMTI1LjI1NkwxNzkuMDc3IDEyMS45OTZDMTgwLjY2IDEyMS4zNzIgMTgwLjY2IDExOS4xMzIgMTc5LjA3NyAxMTguNTA4TDE3MC44MSAxMTUuMjQ3QzE3MC4zMjcgMTE1LjA1NyAxNjkuOTQ0IDExNC42NzQgMTY5Ljc1NCAxMTQuMTkxTDE2Ni40OTQgMTA1LjkyNFoiIGZpbGw9IiM4RjhGOEYiLz4KPHBhdGggZD0iTTEzMy4wMDUgMTI4LjQyNEMxMzMuNjI5IDEyNi44NDIgMTM1Ljg2OSAxMjYuODQyIDEzNi40OTQgMTI4LjQyNEwxNDEuODc1IDE0Mi4wN0MxNDIuMDY2IDE0Mi41NTMgMTQyLjQ0OCAxNDIuOTM1IDE0Mi45MzIgMTQzLjEyNkwxNTYuNTc3IDE0OC41MDhDMTU4LjE2IDE0OS4xMzIgMTU4LjE2IDE1MS4zNzIgMTU2LjU3NyAxNTEuOTk2TDE0Mi45MzIgMTU3LjM3OEMxNDIuNDQ4IDE1Ny41NjggMTQyLjA2NiAxNTcuOTUxIDE0MS44NzUgMTU4LjQzNEwxMzYuNDk0IDE3Mi4wNzlDMTM1Ljg2OSAxNzMuNjYyIDEzMy42MjkgMTczLjY2MiAxMzMuMDA1IDE3Mi4wNzlMMTI3LjYyMyAxNTguNDM0QzEyNy40MzMgMTU3Ljk1MSAxMjcuMDUgMTU3LjU2OCAxMjYuNTY3IDE1Ny4zNzhMMTEyLjkyMiAxNTEuOTk2QzExMS4zMzkgMTUxLjM3MiAxMTEuMzM5IDE0OS4xMzIgMTEyLjkyMiAxNDguNTA4TDEyNi41NjcgMTQzLjEyNkMxMjcuMDUgMTQyLjkzNSAxMjcuNDMzIDE0Mi41NTMgMTI3LjYyMyAxNDIuMDdMMTMzLjAwNSAxMjguNDI0WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTk1Ljk5OSAxODQuMDA0VjE5MS41MDJDMTk1Ljk5OSAxOTQuMjYzIDE5My43NjEgMTk2LjUwMiAxOTAuOTk5IDE5Ni41MDJIMTQ3LjY2OEwxNzIuODc5IDE1OC42ODRDMTc0LjM2MyAxNTYuNDU4IDE3Ny42MzUgMTU2LjQ1OCAxNzkuMTIgMTU4LjY4NEwxOTUuOTk5IDE4NC4wMDRaIiBmaWxsPSIjOEY4RjhGIi8+CjwvZz4KPC9zdmc+Cg==",Ee=uo;function co(e,t,r){switch(t){case"image":return po(e,r[t]);case"video":return go(e,r[t]);case"sticker":return fo(e,r[t]);default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function po(e,t){let r=t.width,i=t.height;return{id:e,meta:{previewUri:Ee,fillType:"//ly.img.ubq/fill/image",kind:"image",width:r,height:i}}}function go(e,t){let r=t.width,i=t.height;return{id:e,label:t.label,meta:{previewUri:Ee,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:r,height:i}}}function fo(e,t){let r=t.width,i=t.height;return{id:e,meta:{previewUri:Ee,fillType:"//ly.img.ubq/fill/image",kind:"sticker",width:r,height:i}}}var mo=co;async function ho(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 bo(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 yo(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 vo(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 wo(e,r[t],i)}default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function bo(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 yo(e,t,r){let i=t.width,n=t.height,a=await ro(r.url,0);return{id:e,label:t.label,meta:{uri:r.url,thumbUri:a,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:i,height:n}}}function vo(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 wo(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 mt=ho;function ko(e){switch(e.userFlow){case"placeholder":return Ao(e);case"generation-only":return Io(e);default:throw new Error(`Unknown user flow: ${e.userFlow}. Expected 'placeholder' or 'generation-only'.`)}}function Io(e){let{cesdk:t,abortSignal:r}=e;return async i=>{try{let n=e.kind,a=await e.getBlockInput(i);if(E(t,r))return{status:"aborted"};let o=await e.generate(i,{middlewares:[...e.middlewares??[]],debug:e.debug,dryRun:e.dryRun,abortSignal:r});if(E(t,r))return{status:"aborted"};if(o.status!=="success")return o;if(o.type==="async")throw new Error("Async generation is not supported in this context yet.");if(E(t,r))return{status:"aborted"};if(e.historyAssetSourceId!=null){let s=gt(),u=await mt(s,n,a,o.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 o}catch(n){return{status:"error",message:n instanceof Error?n.message:String(n)}}}}function Ao(e){let{cesdk:t,abortSignal:r}=e,i;return async n=>{try{let a=e.kind,o=await e.getBlockInput(n);if(E(t,r))return{status:"aborted"};let s=gt(),u=mo(s,a,o);if(i=await eo(t,u),E(t,r,i))return{status:"aborted"};if(i!=null&&e.kind==="video"){let d=t.engine.block.getPositionX(i),f=t.engine.block.getPositionY(i),p=t.engine.block.duplicate(i);t.engine.block.setPositionX(p,d),t.engine.block.setPositionY(p,f),t.engine.block.destroy(i),i=p}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,{middlewares:[...e.middlewares??[]],debug:e.debug,dryRun:e.dryRun,abortSignal:r});if(E(t,r,i))return{status:"aborted"};if(l.status!=="success")return 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 mt(s,a,o,l.output);if(E(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),E(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(a){return i!=null&&t.engine.block.isValid(i)&&(xe(a)?t.engine.block.destroy(i):t.engine.block.setState(i,{type:"Error",error:"Unknown"})),{status:"error",message:a instanceof Error?a.message:String(a)}}}}function E(e,t,r){return t.aborted?(r!=null&&e.engine.block.isValid(r)&&e.engine.block.destroy(r),!0):!1}var So=ko;function Me(e){return`${e}.generating`}function xo(e){return`${e}.abort`}function Co(e,t,r,i,n,a,o){let{builder:s,experimental:u}=e,{cesdk:l,includeHistoryLibrary:c=!0}=a,{id:d,output:{abortable:f}}=t,p=u.global(xo(d),()=>{}),g=u.global(Me(d),!1),h,b=g.value&&f,m=()=>{b&&(p.value(),g.setValue(!1),p.setValue(()=>{}))},k;if(a.requiredInputs!=null&&a.requiredInputs.length>0){let I=i();k=a.requiredInputs.every(y=>!I.input[y])}let A=u.global(`${d}.confirmationDialogId`,void 0);s.Section(`${d}.generate.section`,{children:()=>{s.Button(`${d}.generate`,{label:["common.generate",`panel.${d}.generate`],isLoading:g.value,color:"accent",isDisabled:k,suffix:b?{icon:"@imgly/Cross",color:"danger",tooltip:[`panel.${d}.abort`,"common.cancel"],onClick:()=>{let I=l.ui.showDialog({type:"warning",content:"panel.ly.img.ai.generation.confirmCancel.content",cancel:{label:"common.close",onClick:({id:y})=>{l.ui.closeDialog(y),A.setValue(void 0)}},actions:{label:"panel.ly.img.ai.generation.confirmCancel.confirm",color:"danger",onClick:({id:y})=>{m(),l.ui.closeDialog(y),A.setValue(void 0)}}});A.setValue(I)}}:void 0,onClick:async()=>{h=new AbortController;let I=h.signal;await(async()=>{try{g.setValue(!0),p.setValue(()=>{o.debug&&console.log("Aborting generation"),h?.abort()});let y=await So({kind:t.kind,generate:r,historyAssetSourceId:a.historyAssetSourceId,userFlow:a.createPlaceholderBlock?"placeholder":"generation-only",getBlockInput:n,abortSignal:I,cesdk:l,debug:o.debug,dryRun:o.dryRun})(i().input);if(y.status==="aborted")return;if(y.status==="error"){Xe(y.message,{cesdk:l,provider:t,getInput:i});return}if(y.status==="success"&&y.type==="sync"){let M=t.output.notification;Eo(l,M,()=>({input:i().input,output:y.output}))}}catch(y){if(xe(y))return;Xe(y,{cesdk:l,provider:t,getInput:i})}finally{h=void 0,g.setValue(!1),p.setValue(()=>{}),A.value!=null&&(l.ui.closeDialog(A.value),A.setValue(void 0))}})()}}),t.output.generationHintText!=null&&s.Text(`${d}.generation-hint`,{align:"center",content:t.output.generationHintText})}}),c&&a.historyAssetLibraryEntryId!=null&&s.Library(`${d}.history.library`,{entries:[a.historyAssetLibraryEntryId]})}function Eo(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",a=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:a,duration:i.duration}),!0}var ht=Co;async function Mo({options:e,provider:t,panelInput:r,config:i},n){if(r==null)return;let{cesdk:a}=e,{id:o}=t,s=r.render;return u=>{let{state:l}=u,c=l(Me(o),{isGenerating:!1,abort:()=>{}}).value.isGenerating,{getInput:d,getBlockInput:f}=s(u,{cesdk:a,isGenerating:c});return ht(u,t,n,d,f,{...e,includeHistoryLibrary:r.includeHistoryLibrary??!0,createPlaceholderBlock:r.userFlow==="placeholder"},i),d}}var jo=Mo;function bt(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 Q(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=bt(e,t.$ref),n={...Q(e,i,r)};for(let a in t)Object.prototype.hasOwnProperty.call(t,a)&&a!=="$ref"&&(n[a]=Q(e,t[a],r));return n}if(Array.isArray(t))return t.map(i=>Q(e,i,r));if(typeof t=="object"){let i={};for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[n]=Q(e,t[n],r));return i}return t}function $o(e){return Q(e,{...e})}function _o(e,t=!1){let r=o=>(t&&console.log(`OpenAPI Schema validation failed: ${o}`),!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 o=["string","number","integer","boolean","array","object","null"];if(typeof i.type=="string"){if(!o.includes(i.type))return r(`Invalid type: ${i.type}. Must be one of ${o.join(", ")}`)}else if(Array.isArray(i.type)){for(let s of i.type)if(typeof s!="string"||!o.includes(s))return r(`Array of types contains invalid value: ${s}. Must be one of ${o.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 o of n)if(i[o]!==void 0){if(!Array.isArray(i[o]))return r(`${o} must be an array, got ${typeof i[o]}`);for(let s=0;s<i[o].length;s++){let u=i[o][s];if(typeof u!="object"||u===null)return r(`Item ${s} in ${o} 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 a=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf"];for(let o of a)if(i[o]!==void 0&&typeof i[o]!="number")return r(`${o} must be a number, got ${typeof i[o]}`);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 o=0;o<i.required.length;o++){let s=i.required[o];if(typeof s!="string")return r(`Item ${o} in required array must be a string, got ${typeof s}`)}}return!0}function Lo(e,t){if(e.properties==null)throw new Error("Input schema must have properties");let r=e.properties,i=[];return No(e,t).forEach(n=>{let a=n,o=r[n]??void 0;i.push({id:a,schema:o})}),i}function No(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),a=Po(e,t)??n;return r!=null&&typeof r=="function"&&(a=r(a)),[...new Set(a)]}function Po(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 yt=Lo;function vt(e,t,r,i,n,a,o){if(t.schema==null)return i.renderCustomProperty!=null&&i.renderCustomProperty[t.id]!=null?i.renderCustomProperty[t.id](e,t):void 0;let s=t,u=t.schema.type;if(i.renderCustomProperty!=null&&i.renderCustomProperty[t.id]!=null)return i.renderCustomProperty[t.id](e,t);switch(u){case"string":return t.schema.enum!=null?Oo(e,s,r,i,n,a,o):kt(e,s,r,i,n,a,o);case"boolean":return It(e,s,r,i,n,a,o);case"number":case"integer":return At(e,s,r,i,n,a,o);case"object":return wt(e,s,r,i,n,a,o);case"array":break;case void 0:{if(t.schema.anyOf!=null&&Array.isArray(t.schema.anyOf))return Do(e,s,r,i,n,a,o);break}default:console.error(`Unsupported property type: ${u}`)}}function wt(e,t,r,i,n,a,o){let s=yt(t.schema??{},i).reduce((u,l)=>{let c=vt(e,l,r,i,n,a,o);return c!=null&&(u[l.id]=c()),u},{});return()=>({id:t.id,type:"object",value:s})}function kt(e,t,r,i,n,a,o){let{builder:s,experimental:{global:u}}=e,{id:l}=t,c=`${r.id}.${l}`,d=[`ly.img.plugin-ai-${o}-generation-web.${r.id}.property.${t.id}`,`ly.img.plugin-ai-generation-web.property.${t.id}`,`ly.img.plugin-ai-${o}-generation-web.${r.id}.defaults.property.${t.id}`,`ly.img.plugin-ai-generation-web.defaults.property.${t.id}`],f=u(c,t.schema.default??""),p=To(t.schema),g=p?.component!=null&&p?.component==="TextArea"?"TextArea":"TextInput";return s[g](c,{inputLabel:d,placeholder:n.i18n?.prompt,...f}),()=>({id:t.id,type:"string",value:f.value})}function Oo(e,t,r,i,n,a,o){let{builder:s,experimental:{global:u}}=e,{id:l}=t,c=`${r.id}.${l}`,d=[`ly.img.plugin-ai-${o}-generation-web.${r.id}.property.${t.id}`,`ly.img.plugin-ai-generation-web.property.${t.id}`,`ly.img.plugin-ai-${o}-generation-web.${r.id}.defaults.property.${t.id}`,`ly.img.plugin-ai-generation-web.defaults.property.${t.id}`],f="x-imgly-enum-icons"in t.schema&&typeof t.schema["x-imgly-enum-icons"]=="object"?t.schema["x-imgly-enum-icons"]:{},p="x-imgly-enum-labels"in t.schema&&typeof t.schema["x-imgly-enum-labels"]=="object"?t.schema["x-imgly-enum-labels"]:{},g=(t.schema.enum??[]).map(m=>({id:m,label:[`ly.img.plugin-ai-${o}-generation-web.${r.id}.property.${t.id}.${m}`,`ly.img.plugin-ai-generation-web.property.${t.id}.${m}`,`ly.img.plugin-ai-${o}-generation-web.${r.id}.defaults.property.${t.id}.${m}`,`ly.img.plugin-ai-generation-web.defaults.property.${t.id}.${m}`],icon:f[m]})),h=t.schema.default!=null?g.find(m=>m.id===t.schema.default)??g[0]:g[0],b=u(c,h);return s.Select(c,{inputLabel:d,values:g,...b}),()=>({id:t.id,type:"string",value:b.value.id})}function It(e,t,r,i,n,a,o){let{builder:s,experimental:{global:u}}=e,{id:l}=t,c=`${r.id}.${l}`,d=[`ly.img.plugin-ai-${o}-generation-web.${r.id}.property.${t.id}`,`ly.img.plugin-ai-generation-web.property.${t.id}`,`ly.img.plugin-ai-${o}-generation-web.${r.id}.defaults.property.${t.id}`,`ly.img.plugin-ai-generation-web.defaults.property.${t.id}`],f=!!t.schema.default,p=u(c,f);return s.Checkbox(c,{inputLabel:d,...p}),()=>({id:t.id,type:"boolean",value:p.value})}function At(e,t,r,i,n,a,o){let{builder:s,experimental:{global:u}}=e,{id:l}=t,c=`${r.id}.${l}`,d=[`ly.img.plugin-ai-${o}-generation-web.${r.id}.property.${t.id}`,`ly.img.plugin-ai-generation-web.property.${t.id}`,`ly.img.plugin-ai-${o}-generation-web.${r.id}.defaults.property.${t.id}`,`ly.img.plugin-ai-generation-web.defaults.property.${t.id}`],f=t.schema.minimum,p=t.schema.maximum,g=t.schema.default;g==null&&(f!=null?g=f:p!=null?g=p:g=0);let h=u(c,g);if(f!=null&&p!=null){let b=t.schema.type==="number"?.1:1;"x-imgly-step"in t.schema&&typeof t.schema["x-imgly-step"]=="number"&&(b=t.schema["x-imgly-step"]),s.Slider(c,{inputLabel:d,min:f,max:p,step:b,...h})}else s.NumberInput(c,{inputLabel:d,min:f,max:p,...h});return()=>({id:t.id,type:"integer",value:h.value})}function Do(e,t,r,i,n,a,o){let{builder:s,experimental:{global:u}}=e,{id:l}=t,c=`${r.id}.${l}`,d=[`ly.img.plugin-ai-${o}-generation-web.${r.id}.property.${t.id}`,`ly.img.plugin-ai-generation-web.property.${t.id}`,`ly.img.plugin-ai-${o}-generation-web.${r.id}.defaults.property.${t.id}`,`ly.img.plugin-ai-generation-web.defaults.property.${t.id}`],f=t.schema.anyOf??[],p=[],g={},h={};f.forEach((k,A)=>{let I=k.title??"common.custom",y=`${r.id}.${l}.anyOf[${A}]`,M="x-imgly-enum-labels"in t.schema&&typeof t.schema["x-imgly-enum-labels"]=="object"?t.schema["x-imgly-enum-labels"]:{},q="x-imgly-enum-icons"in t.schema&&typeof t.schema["x-imgly-enum-icons"]=="object"?t.schema["x-imgly-enum-icons"]:{};k.type==="string"?k.enum!=null?k.enum.forEach(se=>{p.push({id:se,label:M[se]??io(se),icon:q[se]})}):(g[y]=()=>kt(e,{id:y,schema:{...k,title:I}},r,i,n,a,o),p.push({id:y,label:M[I]??I,icon:q[I]})):k.type==="boolean"?(g[y]=()=>It(e,{id:y,schema:{...k,title:I}},r,i,n,a,o),p.push({id:y,label:M[I]??I,icon:q[I]})):k.type==="integer"?(g[y]=()=>At(e,{id:y,schema:{...k,title:I}},r,i,n,a,o),p.push({id:y,label:M[I]??I,icon:q[I]})):k.type==="array"||k.type==="object"&&(g[y]=()=>wt(e,{id:y,schema:{...k,title:I}},r,i,n,a,o),p.push({id:y,label:M[I]??I,icon:q[I]}))});let b=t.schema.default!=null?p.find(k=>k.id===t.schema.default)??p[0]:p[0],m=u(c,b);if(s.Select(c,{inputLabel:d,values:p,...m}),m.value.id in g){let k=g[m.value.id]();h[m.value.id]=k}return()=>{let k=h[m.value.id];return k!=null?{...k(),id:t.id}:{id:t.id,type:"string",value:m.value.id}}}function To(e){if("x-imgly-builder"in e)return e["x-imgly-builder"]}var zo=vt,Ro={"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 et(e){return e.replace(/_/g," ").replace(/\b3d\b/gi,"3D").replace(/\b2d\b/gi,"2D").replace(/\b\w/g,t=>t.toUpperCase())}function Fo(e,t,r,i){let n={};e.forEach(o=>{if(o.schema?.title&&(n[`ly.img.plugin-ai-${i}-generation-web.${t.id}.defaults.property.${o.id}`]=o.schema.title),o.schema?.enum){let s="x-imgly-enum-labels"in o.schema&&typeof o.schema["x-imgly-enum-labels"]=="object"?o.schema["x-imgly-enum-labels"]:{};o.schema.enum.forEach(u=>{let l=String(u),c=s[l]||et(l);n[`ly.img.plugin-ai-${i}-generation-web.${t.id}.defaults.property.${o.id}.${l}`]=c})}if(o.schema?.anyOf&&Array.isArray(o.schema.anyOf)){let s="x-imgly-enum-labels"in o.schema&&typeof o.schema["x-imgly-enum-labels"]=="object"?o.schema["x-imgly-enum-labels"]:{};o.schema.anyOf.forEach(u=>{let l=u;l.enum&&Array.isArray(l.enum)&&l.enum.forEach(c=>{let d=String(c),f=s[d]||et(d);n[`ly.img.plugin-ai-${i}-generation-web.defaults.property.${t.id}.${o.id}.${d}`]=f})})}});let a={...Ro,...n};Object.keys(a).length>0&&r.cesdk.i18n.setTranslations({en:a})}async function Uo({options:e,provider:t,panelInput:r,config:i},n){let{id:a}=t;if(r==null)return;i.debug&&console.log(`Registering schema-based panel input for provider ${a}`);let o=$o(r.document),s=bt(o,r.inputReference);if(!_o(s,i.debug))throw new Error(`Input reference '${r.inputReference}' does not resolve to a valid OpenAPI schema`);let u=s,l=yt(u,r);return Fo(l,t,e,t.kind),c=>{let{builder:d}=c,f=[];d.Section(`${a}.schema.section`,{children:()=>{l.forEach(b=>{let m=zo(c,b,t,r,e,i,t.kind);m!=null&&(Array.isArray(m)?f.push(...m):f.push(m))})}});let p=f.map(b=>b()),g=b=>b.type==="object"?Object.entries(b.value).reduce((m,[k,A])=>(m[k]=g(A),m),{}):b.value,h=p.reduce((b,m)=>(b[m.id]=g(m),b),{});ht(c,t,n,()=>({input:h}),()=>r.getBlockInput(h),{...e,requiredInputs:u.required,createPlaceholderBlock:r.userFlow==="placeholder"},i)}}var Vo=Uo;async function Bo(e,t){if(e.panelInput!=null)switch(e.panelInput.type){case"custom":return jo(e,t);case"schema":return Vo(e,t);default:e.config.debug&&console.warn(`Invalid panel input type '${panelInput.type}' - skipping`)}}var Go=Bo;function Ho(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 a(){let o=`${t.id}.history`;for(;n.includes(o);)o+=`-${Math.random().toString(36).substring(2,6)}`;return o}if(i==="@imgly/local"){let o=a();return r.asset.addLocalSource(o),o}if(i==="@imgly/indexedDB"){let o=a();return r.asset.addSource(new Zt(o,r)),o}return i}var qo=Ho;function Zo(e,t){if(t==null||!t)return;let r=`${e.provider.id}.history`;return e.options.cesdk.ui.addAssetLibraryEntry({id:r,sourceIds:[t],sortBy:{sortKey:"insertedAt",sortingOrder:"Descending"},canRemove:!0,gridItemHeight:"square",gridBackgroundType:"cover"}),r}var Yo=Zo,be="@imgly/plugin-ai-generation",Qo=`
<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="currentCol