@imgly/plugin-ai-image-generation-web
Version:
AI image generation plugin for the CE.SDK editor
9 lines • 119 kB
JavaScript
var dr=class{constructor(e,t,i){this.assetStoreName="assets",this.blobStoreName="blobs",this.db=null,this.id=e,this.engine=t,this.dbName=i?.dbName??`ly.img.assetSource/${e}`,this.dbVersion=i?.dbVersion??1}async initialize(){if(!this.db)return new Promise((e,t)=>{let i=indexedDB.open(this.dbName,this.dbVersion);i.onerror=r=>{t(new Error(`Failed to open IndexedDB: ${r.target.error}`))},i.onupgradeneeded=r=>{let n=r.target.result;n.objectStoreNames.contains(this.assetStoreName)||n.createObjectStore(this.assetStoreName,{keyPath:"id"}),n.objectStoreNames.contains(this.blobStoreName)||n.createObjectStore(this.blobStoreName,{keyPath:"id"})},i.onsuccess=r=>{this.db=r.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,s)=>{let c=e.locale??"en",d="",p=[];s.label!=null&&typeof s.label=="object"&&s.label[c]&&(d=s.label[c]),s.tags!=null&&typeof s.tags=="object"&&s.tags[c]&&(p=s.tags[c]);let g={...s,label:d,tags:p};return this.filterAsset(g,e)&&u.push(g),u},[]);t=await this.restoreBlobUrls(t),t=this.sortAssets(t,e);let{page:i,perPage:r}=e,n=i*r,a=n+r,o=t.slice(n,a),l=a<t.length?i+1:void 0;return{assets:o,currentPage:i,nextPage:l,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 i=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).getAll();i.onsuccess=()=>{let r=new Set;i.result.forEach(a=>{a.groups&&Array.isArray(a.groups)&&a.groups.forEach(o=>r.add(o))});let n=[...r];e(n)},i.onerror=()=>{t(new Error(`Failed to get groups: ${i.error}`))}})}addAsset(e){this.initialize().then(async()=>{if(!this.db)throw new Error("Database not initialized");let t=this.db.transaction(this.assetStoreName,"readwrite"),i=t.objectStore(this.assetStoreName),r=new Set;J(e,a=>{r.add(a)}),setTimeout(()=>{this.storeBlobUrls([...r])});let n={...e,meta:{...e.meta,insertedAt:e.meta?.insertedAt||Date.now()}};i.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 i=this.db.transaction(this.assetStoreName,"readwrite");i.objectStore(this.assetStoreName).delete(e),i.oncomplete=()=>{J(t,r=>{this.removeBlob(r)}),this.engine.asset.assetSourceContentsChanged(this.id)},i.onerror=()=>{console.error(`Failed to remove asset: ${i.error}`)}}).catch(i=>{console.error("Error initializing database:",i)})}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,i)=>{let r=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).getAll();r.onsuccess=()=>{let n=r.result;n.sort((a,o)=>{let l=a.meta?.insertedAt||a._insertedAt||Date.now(),u=o.meta?.insertedAt||o._insertedAt||Date.now();return e==="asc"?l-u:u-l}),t(n)},r.onerror=()=>{i(new Error(`Failed to get assets: ${r.error}`))}})}async getAsset(e){return new Promise((t,i)=>{let r=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).get(e);r.onsuccess=()=>{t(r.result)},r.onerror=()=>{i(new Error(`Failed to get blob: ${r.error}`))}})}async getBlob(e){return new Promise((t,i)=>{let r=this.db.transaction(this.blobStoreName,"readonly").objectStore(this.blobStoreName).get(e);r.onsuccess=()=>{t(r.result)},r.onerror=()=>{i(new Error(`Failed to get blob: ${r.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 i=>{let r=await(await fetch(i)).blob();t[i]=r})),this.initialize().then(async()=>{if(!this.db)throw new Error("Database not initialized");let i=this.db.transaction(this.blobStoreName,"readwrite"),r=i.objectStore(this.blobStoreName);Object.entries(t).forEach(([n,a])=>{let o={id:n,blob:a};r.put(o)}),i.onerror=()=>{console.error(`Failed to add blobs: ${i.error}`)}}).catch(i=>{console.error("Error initializing database:",i)})}async restoreBlobUrls(e){let t={},i=new Set;return J(e,r=>{i.add(r)}),await Promise.all([...i].map(async r=>{let n=await this.createBlobUrlFromStore(r);t[r]=n})),J(e,r=>t[r]??r)}filterAsset(e,t){let{query:i,tags:r,groups:n,excludeGroups:a}=t;if(i&&i.trim()!==""){let o=i.trim().toLowerCase().split(" "),l=e.label?.toLowerCase()??"",u=e.tags?.map(s=>s.toLowerCase())??[];if(!o.every(s=>l.includes(s)||u.some(c=>c.includes(s))))return!1}if(r){let o=Array.isArray(r)?r:[r];if(o.length>0&&(!e.tags||!o.every(l=>e.tags?.includes(l))))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:i,sortKey:r,sortActiveFirst:n}=t,a=[...e];return!i||i==="None"||(r?a.sort((o,l)=>{let u,s;return r==="id"?(u=o.id,s=l.id):(u=o.meta?.[r]??null,s=l.meta?.[r]??null),u==null?i==="Ascending"?-1:1:s==null?i==="Ascending"?1:-1:typeof u=="string"&&typeof s=="string"?i==="Ascending"?u.localeCompare(s):s.localeCompare(u):i==="Ascending"?u<s?-1:u>s?1:0:u>s?-1:u<s?1:0}):i==="Descending"&&a.reverse(),n&&a.sort((o,l)=>o.active&&!l.active?-1:!o.active&&l.active?1:0)),a}};function J(e,t,i=""){if(e===null||typeof e!="object")return e;if(Array.isArray(e)){for(let r=0;r<e.length;r++){let n=i?`${i}[${r}]`:`[${r}]`;if(typeof e[r]=="string"&&e[r].startsWith("blob:")){let a=t(e[r],n);typeof a=="string"&&(e[r]=a)}else e[r]=J(e[r],t,n)}return e}for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)){let n=e[r],a=i?`${i}.${r}`:r;if(typeof n=="string"&&n.startsWith("blob:")){let o=t(n,a);typeof o=="string"&&(e[r]=o)}else e[r]=J(n,t,a)}return e}var pr=class{constructor(e,t,i){this.id=e,this.cesdk=t,this.assetSourceIds=i}async findAssets(e){try{let t=this.assetSourceIds.map(c=>this.cesdk.engine.asset.findAssets(c,{...e,perPage:9999,page:0})),i=await Promise.all(t),r=[];i.forEach(c=>{c?.assets&&(r=r.concat(c.assets))}),r.sort((c,d)=>{let p=c.meta?.insertedAt||0;return(d.meta?.insertedAt||0)-p});let{page:n,perPage:a}=e,o=n*a,l=o+a,u=r.slice(o,l),s=l<r.length?n+1:void 0;return{assets:u,currentPage:n,nextPage:s,total:r.length}}catch(t){console.error("Error finding assets:",t);return}}async getGroups(){let e=this.assetSourceIds.map(r=>this.cesdk.engine.asset.getGroups(r)),t=await Promise.all(e),i=new Set;return t.forEach(r=>{r.forEach(n=>i.add(n))}),Array.from(i)}addAsset(e){throw new Error("AggregatedAssetSource does not support adding assets")}removeAsset(e){throw new Error("AggregatedAssetSource does not support removing assets")}},gr=class{constructor(e,t){this.engine=e,this.key=t}hasData(e){return this.engine.block.isValid(e)&&this.engine.block.hasMetadata(e,this.key)}get(e){if(this.hasData(e))return JSON.parse(this.engine.block.getMetadata(e,this.key))}set(e,t){this.engine.block.setMetadata(e,this.key,JSON.stringify(t))}clear(e){this.engine.block.hasMetadata(e,this.key)&&this.engine.block.removeMetadata(e,this.key)}},Zt=gr,mr=typeof global=="object"&&global&&global.Object===Object&&global,Yt=mr,fr=typeof self=="object"&&self&&self.Object===Object&&self,br=Yt||fr||Function("return this")(),F=br,yr=F.Symbol,ee=yr,Wt=Object.prototype,hr=Wt.hasOwnProperty,vr=Wt.toString,de=ee?ee.toStringTag:void 0;function kr(e){var t=hr.call(e,de),i=e[de];try{e[de]=void 0;var r=!0}catch{}var n=vr.call(e);return r&&(t?e[de]=i:delete e[de]),n}var wr=kr,Ir=Object.prototype,Ar=Ir.toString;function Cr(e){return Ar.call(e)}var Sr=Cr,$r="[object Null]",xr="[object Undefined]",Tt=ee?ee.toStringTag:void 0;function Er(e){return e==null?e===void 0?xr:$r:Tt&&Tt in Object(e)?wr(e):Sr(e)}var he=Er;function Mr(e){return e!=null&&typeof e=="object"}var ft=Mr,kd=Array.isArray;function Tr(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var Kt=Tr,Pr="[object AsyncFunction]",jr="[object Function]",_r="[object GeneratorFunction]",Lr="[object Proxy]";function Dr(e){if(!Kt(e))return!1;var t=he(e);return t==jr||t==_r||t==Pr||t==Lr}var Nr=Dr,Or=F["__core-js_shared__"],rt=Or,Pt=function(){var e=/[^.]+$/.exec(rt&&rt.keys&&rt.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function Fr(e){return!!Pt&&Pt in e}var Rr=Fr,zr=Function.prototype,Ur=zr.toString;function Br(e){if(e!=null){try{return Ur.call(e)}catch{}try{return e+""}catch{}}return""}var W=Br,Vr=/[\\^$.*+?()[\]{}|]/g,qr=/^\[object .+?Constructor\]$/,Gr=Function.prototype,Hr=Object.prototype,Qr=Gr.toString,Zr=Hr.hasOwnProperty,Yr=RegExp("^"+Qr.call(Zr).replace(Vr,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Wr(e){if(!Kt(e)||Rr(e))return!1;var t=Nr(e)?Yr:qr;return t.test(W(e))}var Kr=Wr;function Xr(e,t){return e?.[t]}var Jr=Xr;function en(e,t){var i=Jr(e,t);return Kr(i)?i:void 0}var te=en,tn=te(F,"WeakMap"),st=tn;function rn(e,t){return e===t||e!==e&&t!==t}var nn=rn,an=9007199254740991;function on(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=an}var ln=on,wd=Object.prototype,sn="[object Arguments]";function cn(e){return ft(e)&&he(e)==sn}var jt=cn,Xt=Object.prototype,un=Xt.hasOwnProperty,dn=Xt.propertyIsEnumerable,Id=jt(function(){return arguments}())?jt:function(e){return ft(e)&&un.call(e,"callee")&&!dn.call(e,"callee")},Jt=typeof exports=="object"&&exports&&!exports.nodeType&&exports,_t=Jt&&typeof module=="object"&&module&&!module.nodeType&&module,pn=_t&&_t.exports===Jt,Lt=pn?F.Buffer:void 0,Ad=Lt?Lt.isBuffer:void 0,gn="[object Arguments]",mn="[object Array]",fn="[object Boolean]",bn="[object Date]",yn="[object Error]",hn="[object Function]",vn="[object Map]",kn="[object Number]",wn="[object Object]",In="[object RegExp]",An="[object Set]",Cn="[object String]",Sn="[object WeakMap]",$n="[object ArrayBuffer]",xn="[object DataView]",En="[object Float32Array]",Mn="[object Float64Array]",Tn="[object Int8Array]",Pn="[object Int16Array]",jn="[object Int32Array]",_n="[object Uint8Array]",Ln="[object Uint8ClampedArray]",Dn="[object Uint16Array]",Nn="[object Uint32Array]",E={};E[En]=E[Mn]=E[Tn]=E[Pn]=E[jn]=E[_n]=E[Ln]=E[Dn]=E[Nn]=!0;E[gn]=E[mn]=E[$n]=E[fn]=E[xn]=E[bn]=E[yn]=E[hn]=E[vn]=E[kn]=E[wn]=E[In]=E[An]=E[Cn]=E[Sn]=!1;function On(e){return ft(e)&&ln(e.length)&&!!E[he(e)]}var Fn=On;function Rn(e){return function(t){return e(t)}}var zn=Rn,ei=typeof exports=="object"&&exports&&!exports.nodeType&&exports,fe=ei&&typeof module=="object"&&module&&!module.nodeType&&module,Un=fe&&fe.exports===ei,nt=Un&&Yt.process,Bn=function(){try{var e=fe&&fe.require&&fe.require("util").types;return e||nt&&nt.binding&&nt.binding("util")}catch{}}(),Dt=Bn,Nt=Dt&&Dt.isTypedArray,Cd=Nt?zn(Nt):Fn,Vn=Object.prototype,Sd=Vn.hasOwnProperty;function qn(e,t){return function(i){return e(t(i))}}var Gn=qn,$d=Gn(Object.keys,Object),Hn=Object.prototype,xd=Hn.hasOwnProperty,Qn=te(Object,"create"),be=Qn;function Zn(){this.__data__=be?be(null):{},this.size=0}var Yn=Zn;function Wn(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var Kn=Wn,Xn="__lodash_hash_undefined__",Jn=Object.prototype,ea=Jn.hasOwnProperty;function ta(e){var t=this.__data__;if(be){var i=t[e];return i===Xn?void 0:i}return ea.call(t,e)?t[e]:void 0}var ia=ta,ra=Object.prototype,na=ra.hasOwnProperty;function aa(e){var t=this.__data__;return be?t[e]!==void 0:na.call(t,e)}var oa=aa,la="__lodash_hash_undefined__";function sa(e,t){var i=this.__data__;return this.size+=this.has(e)?0:1,i[e]=be&&t===void 0?la:t,this}var ca=sa;function ie(e){var t=-1,i=e==null?0:e.length;for(this.clear();++t<i;){var r=e[t];this.set(r[0],r[1])}}ie.prototype.clear=Yn;ie.prototype.delete=Kn;ie.prototype.get=ia;ie.prototype.has=oa;ie.prototype.set=ca;var Ot=ie;function ua(){this.__data__=[],this.size=0}var da=ua;function pa(e,t){for(var i=e.length;i--;)if(nn(e[i][0],t))return i;return-1}var Pe=pa,ga=Array.prototype,ma=ga.splice;function fa(e){var t=this.__data__,i=Pe(t,e);if(i<0)return!1;var r=t.length-1;return i==r?t.pop():ma.call(t,i,1),--this.size,!0}var ba=fa;function ya(e){var t=this.__data__,i=Pe(t,e);return i<0?void 0:t[i][1]}var ha=ya;function va(e){return Pe(this.__data__,e)>-1}var ka=va;function wa(e,t){var i=this.__data__,r=Pe(i,e);return r<0?(++this.size,i.push([e,t])):i[r][1]=t,this}var Ia=wa;function re(e){var t=-1,i=e==null?0:e.length;for(this.clear();++t<i;){var r=e[t];this.set(r[0],r[1])}}re.prototype.clear=da;re.prototype.delete=ba;re.prototype.get=ha;re.prototype.has=ka;re.prototype.set=Ia;var je=re,Aa=te(F,"Map"),ye=Aa;function Ca(){this.size=0,this.__data__={hash:new Ot,map:new(ye||je),string:new Ot}}var Sa=Ca;function $a(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var xa=$a;function Ea(e,t){var i=e.__data__;return xa(t)?i[typeof t=="string"?"string":"hash"]:i.map}var _e=Ea;function Ma(e){var t=_e(this,e).delete(e);return this.size-=t?1:0,t}var Ta=Ma;function Pa(e){return _e(this,e).get(e)}var ja=Pa;function _a(e){return _e(this,e).has(e)}var La=_a;function Da(e,t){var i=_e(this,e),r=i.size;return i.set(e,t),this.size+=i.size==r?0:1,this}var Na=Da;function ne(e){var t=-1,i=e==null?0:e.length;for(this.clear();++t<i;){var r=e[t];this.set(r[0],r[1])}}ne.prototype.clear=Sa;ne.prototype.delete=Ta;ne.prototype.get=ja;ne.prototype.has=La;ne.prototype.set=Na;var ti=ne;function Oa(){this.__data__=new je,this.size=0}var Fa=Oa;function Ra(e){var t=this.__data__,i=t.delete(e);return this.size=t.size,i}var za=Ra;function Ua(e){return this.__data__.get(e)}var Ba=Ua;function Va(e){return this.__data__.has(e)}var qa=Va,Ga=200;function Ha(e,t){var i=this.__data__;if(i instanceof je){var r=i.__data__;if(!ye||r.length<Ga-1)return r.push([e,t]),this.size=++i.size,this;i=this.__data__=new ti(r)}return i.set(e,t),this.size=i.size,this}var Qa=Ha;function ve(e){var t=this.__data__=new je(e);this.size=t.size}ve.prototype.clear=Fa;ve.prototype.delete=za;ve.prototype.get=Ba;ve.prototype.has=qa;ve.prototype.set=Qa;var Za=Object.prototype,Ed=Za.propertyIsEnumerable,Ya=te(F,"DataView"),ct=Ya,Wa=te(F,"Promise"),ut=Wa,Ka=te(F,"Set"),dt=Ka,Ft="[object Map]",Xa="[object Object]",Rt="[object Promise]",zt="[object Set]",Ut="[object WeakMap]",Bt="[object DataView]",Ja=W(ct),eo=W(ye),to=W(ut),io=W(dt),ro=W(st),X=he;(ct&&X(new ct(new ArrayBuffer(1)))!=Bt||ye&&X(new ye)!=Ft||ut&&X(ut.resolve())!=Rt||dt&&X(new dt)!=zt||st&&X(new st)!=Ut)&&(X=function(e){var t=he(e),i=t==Xa?e.constructor:void 0,r=i?W(i):"";if(r)switch(r){case Ja:return Bt;case eo:return Ft;case to:return Rt;case io:return zt;case ro:return Ut}return t});var Md=F.Uint8Array,no="__lodash_hash_undefined__";function ao(e){return this.__data__.set(e,no),this}var oo=ao;function lo(e){return this.__data__.has(e)}var so=lo;function pt(e){var t=-1,i=e==null?0:e.length;for(this.__data__=new ti;++t<i;)this.add(e[t])}pt.prototype.add=pt.prototype.push=oo;pt.prototype.has=so;var Vt=ee?ee.prototype:void 0,Td=Vt?Vt.valueOf:void 0,co=Object.prototype,Pd=co.hasOwnProperty,uo=Object.prototype,jd=uo.hasOwnProperty,_d=new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,"i"),Ld=new RegExp(/[A-Fa-f0-9]{1}/,"g"),Dd=new RegExp(/[A-Fa-f0-9]{2}/,"g");function po(e){return{"image/png":"png","image/jpeg":"jpg","image/webp":"webp","image/gif":"gif","image/svg+xml":"svg"}[e]??"png"}async function ii(e,t){if(e.startsWith("buffer:")){let i=await t.editor.getMimeType(e),r=t.editor.getBufferLength(e),n=t.editor.getBufferData(e,0,r),a=new Uint8Array(n),o=new Blob([a],{type:i});return URL.createObjectURL(o)}else return e}async function gt(e,t){let i=await ii(e,t);return new Promise((r,n)=>{let a=new Image;a.onload=()=>{r({width:a.width,height:a.height})},a.onerror=n,a.src=i})}async function go(e,t,i){let r,n=t.block.getFill(e),a=t.block.getSourceSet(n,"fill/image/sourceSet"),[o]=a;if(o==null){if(r=t.block.getString(n,"fill/image/imageFileURI"),r==null)throw new Error("No image source/uri found")}else r=o.uri;if(i?.throwErrorIfSvg&&await t.editor.getMimeType(r)==="image/svg+xml")throw new Error("SVG images are not supported");return ii(r,t)}function mo(e){return e!==void 0}var Le=mo;function ke(e,t){let i=t?.i18n?.getLocale?.()||"en";return{engine:e,cesdk:t,locale:i}}function we(e,t,i,r,n){if(t?.default!==void 0){let a=t.default;return typeof a!="function"?a:a(i)}return r!==void 0?r:n}var De=class ri{constructor(){this.actions=new Map,this.subscribers=new Map}static get(){let t="__imgly_action_registry__",i=typeof window<"u"?window:globalThis;return i[t]||(i[t]=new ri),i[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(i=>this.matchesFilters(i,t))}subscribe(t){return this.subscribers.set(t,null),()=>{this.subscribers.delete(t)}}subscribeBy(t,i){return this.subscribers.set(i,t),()=>{this.subscribers.delete(i)}}notifySubscribers(t,i){this.subscribers.forEach((r,n)=>{if(r===null){n(t,i);return}this.matchesFilters(t,r)&&n(t,i)})}matchesFilters(t,i){return!(i.type&&t.type!==i.type||i.pluginId&&t.type==="plugin"&&t.pluginId!==i.pluginId||i.id&&t.id!==i.id||i.kind&&(t.type!=="quick"||t.kind!==i.kind))}},ni=class ai{constructor(){this.providers=new Map}static get(){let t="__imgly_provider_registry__",i=typeof window<"u"?window:globalThis;return i[t]||(i[t]=new ai),i[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:i})=>i.kind===t)}};function fo(e){let t=e.filter(i=>!!i);return i=>async(r,n)=>{let a=[],o=s=>{a.push(s)},l=async(s,c,d)=>{if(s>=t.length)return i(c,d);let p=t[s],g=async(m,y)=>l(s+1,m,y),b={...d,addDisposer:o};return p(c,b,g)},u={...n,addDisposer:o};return{result:await l(0,r,u),dispose:async()=>{for(let s=a.length-1;s>=0;s--)try{await a[s]()}catch(c){console.error("Error in disposer:",c)}a.length=0}}}}function bo({enable:e=!0}){return async(t,i,r)=>{if(!e)return r(t,i);console.group("[GENERATION]"),console.log("Generating with input:",JSON.stringify(t,null,2));let n,a=Date.now();try{return n=await r(t,i),n}finally{n!=null&&(console.log(`Generation took ${Date.now()-a}ms`),console.log("Generation result:",JSON.stringify(n,null,2))),console.groupEnd()}}}var yo=bo;var at="ly.img.ai.temp";async function ho(e,t){return e.engine.asset.findAllSources().includes(at)||e.engine.asset.addLocalSource(at),e.engine.asset.apply(at,t)}function vo(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 i=e;return"message"in i&&typeof i.message=="string"?i.message:"cause"in i&&typeof i.cause=="string"?i.cause:"detail"in i&&typeof i.detail=="object"&&i.detail!==null&&"message"in i.detail&&typeof i.detail.message=="string"?i.detail.message:"error"in i&&typeof i.error=="object"&&i.error!==null&&"message"in i.error&&typeof i.error.message=="string"?i.error.message:t}return typeof e=="string"?e:String(e)||t}function oi(){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 ko(e,t=0,i="image/jpeg",r=.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 l=document.createElement("canvas");l.width=o.videoWidth,l.height=o.videoHeight;let u=l.getContext("2d");if(!u){document.body.removeChild(o),a(new Error("Failed to create canvas context"));return}u.drawImage(o,0,0,l.width,l.height);try{let s=l.toDataURL(i,r);document.body.removeChild(o),n(s)}catch(s){document.body.removeChild(o),a(new Error(`Failed to create thumbnail: ${s instanceof Error?s.message:String(s)}`))}},{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 wo(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 bt(e){return e instanceof Error&&e.name==="AbortError"}function Io(e,t,i){let r=`${t}.iconSetAdded`;e.ui.experimental.hasGlobalStateValue(r)||(e.ui.addIconSet(t,i),e.ui.experimental.setGlobalStateValue(r,!0))}function li(e,t,i){let r="ai-plugin-version",n="ai-plugin-version-warning-shown";try{let a=e.ui.experimental.getGlobalStateValue(r);a?a!==i&&(e.ui.experimental.getGlobalStateValue(n,!1)||(console.warn(`[IMG.LY AI Plugins] Version mismatch detected!
Plugin "${t}" is using version ${i}, 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(r,i)}catch(a){console.debug("[IMG.LY AI Plugins] Could not check plugin version consistency:",a)}}function Ao(e){let{cesdk:t,panelId:i}=e;i.startsWith("ly.img.ai.")||console.warn(`Dock components for AI generation should open a panel with an id starting with "ly.img.ai." \u2013 "${i}" was provided.`);let r=`${i}.dock`;t.ui.registerComponent(r,({builder:n})=>{let a=t.ui.isPanelOpen(i);n.Button(`${i}.dock.button`,{label:`${i}.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(i):t.ui.openPanel(i)}})})}var si=Ao;function Co(){return({engine:e})=>{let t=e.block.findAllSelected();if(t==null||t.length!==1)return!1;let[i]=t;if(!e.block.supportsFill(i)||e.block.getKind(i)==="sticker"||!["//ly.img.ubq/graphic","//ly.img.ubq/page"].includes(e.block.getType(i)))return!1;let r=e.block.getFill(i);return e.block.getType(r)==="//ly.img.ubq/fill/image"}}var N=Co;function So(e,t){let{cesdk:i,provider:r,getInput:n,middlewareOptions:a}=t;a?.defaultPrevented()||(console.error("Generation failed:",e),$o(i,r.output.notification,()=>({input:n?.().input,error:e}))||i.ui.showNotification({type:"error",message:vo(e)}))}function $o(e,t,i){let r=t?.error;if(r==null||!(typeof r.show=="function"?r.show(i()):r.show))return!1;let n=typeof r.message=="function"?r.message(i()):r.message??"common.ai-generation.failed",a=r.action!=null?{label:typeof r.action.label=="function"?r.action.label(i()):r.action.label,onClick:()=>{r?.action?.onClick(i())}}:void 0;return e.ui.showNotification({type:"error",message:n,action:a}),!0}var qt=So,xo="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIzIiBoZWlnaHQ9IjMyMyIgdmlld0JveD0iMCAwIDMyMyAzMjMiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIzMjMiIGhlaWdodD0iMzIzIiBmaWxsPSIjRTlFQkVEIi8+CjxnIG9wYWNpdHk9IjAuMyI+CjxwYXRoIGQ9Ik0xMTYgMTg0VjE5MS41QzExNiAxOTkuNzg0IDEyMi43MTYgMjA2LjUgMTMxIDIwNi41SDE5MUMxOTkuMjg0IDIwNi41IDIwNiAxOTkuNzg0IDIwNiAxOTEuNVYxMzEuNUMyMDYgMTIzLjIxNiAxOTkuMjg0IDExNi41IDE5MSAxMTYuNUwxOTAuOTk1IDEyNi41QzE5My43NTcgMTI2LjUgMTk2IDEyOC43MzkgMTk2IDEzMS41VjE5MS41QzE5NiAxOTQuMjYxIDE5My43NjEgMTk2LjUgMTkxIDE5Ni41SDEzMUMxMjguMjM5IDE5Ni41IDEyNiAxOTQuMjYxIDEyNiAxOTEuNVYxODRIMTE2WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTY2LjQ5NCAxMDUuOTI0QzE2NS44NjkgMTA0LjM0MiAxNjMuNjI5IDEwNC4zNDIgMTYzLjAwNSAxMDUuOTI0TDE1OS43NDUgMTE0LjE5MUMxNTkuNTU0IDExNC42NzQgMTU5LjE3MiAxMTUuMDU3IDE1OC42ODggMTE1LjI0N0wxNTAuNDIyIDExOC41MDhDMTQ4LjgzOSAxMTkuMTMyIDE0OC44MzkgMTIxLjM3MiAxNTAuNDIyIDEyMS45OTZMMTU4LjY4OCAxMjUuMjU2QzE1OS4xNzIgMTI1LjQ0NyAxNTkuNTU0IDEyNS44MjkgMTU5Ljc0NSAxMjYuMzEzTDE2My4wMDUgMTM0LjU3OUMxNjMuNjI5IDEzNi4xNjIgMTY1Ljg2OSAxMzYuMTYyIDE2Ni40OTQgMTM0LjU3OUwxNjkuNzU0IDEyNi4zMTNDMTY5Ljk0NCAxMjUuODI5IDE3MC4zMjcgMTI1LjQ0NyAxNzAuODEgMTI1LjI1NkwxNzkuMDc3IDEyMS45OTZDMTgwLjY2IDEyMS4zNzIgMTgwLjY2IDExOS4xMzIgMTc5LjA3NyAxMTguNTA4TDE3MC44MSAxMTUuMjQ3QzE3MC4zMjcgMTE1LjA1NyAxNjkuOTQ0IDExNC42NzQgMTY5Ljc1NCAxMTQuMTkxTDE2Ni40OTQgMTA1LjkyNFoiIGZpbGw9IiM4RjhGOEYiLz4KPHBhdGggZD0iTTEzMy4wMDUgMTI4LjQyNEMxMzMuNjI5IDEyNi44NDIgMTM1Ljg2OSAxMjYuODQyIDEzNi40OTQgMTI4LjQyNEwxNDEuODc1IDE0Mi4wN0MxNDIuMDY2IDE0Mi41NTMgMTQyLjQ0OCAxNDIuOTM1IDE0Mi45MzIgMTQzLjEyNkwxNTYuNTc3IDE0OC41MDhDMTU4LjE2IDE0OS4xMzIgMTU4LjE2IDE1MS4zNzIgMTU2LjU3NyAxNTEuOTk2TDE0Mi45MzIgMTU3LjM3OEMxNDIuNDQ4IDE1Ny41NjggMTQyLjA2NiAxNTcuOTUxIDE0MS44NzUgMTU4LjQzNEwxMzYuNDk0IDE3Mi4wNzlDMTM1Ljg2OSAxNzMuNjYyIDEzMy42MjkgMTczLjY2MiAxMzMuMDA1IDE3Mi4wNzlMMTI3LjYyMyAxNTguNDM0QzEyNy40MzMgMTU3Ljk1MSAxMjcuMDUgMTU3LjU2OCAxMjYuNTY3IDE1Ny4zNzhMMTEyLjkyMiAxNTEuOTk2QzExMS4zMzkgMTUxLjM3MiAxMTEuMzM5IDE0OS4xMzIgMTEyLjkyMiAxNDguNTA4TDEyNi41NjcgMTQzLjEyNkMxMjcuMDUgMTQyLjkzNSAxMjcuNDMzIDE0Mi41NTMgMTI3LjYyMyAxNDIuMDdMMTMzLjAwNSAxMjguNDI0WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTk1Ljk5OSAxODQuMDA0VjE5MS41MDJDMTk1Ljk5OSAxOTQuMjYzIDE5My43NjEgMTk2LjUwMiAxOTAuOTk5IDE5Ni41MDJIMTQ3LjY2OEwxNzIuODc5IDE1OC42ODRDMTc0LjM2MyAxNTYuNDU4IDE3Ny42MzUgMTU2LjQ1OCAxNzkuMTIgMTU4LjY4NEwxOTUuOTk5IDE4NC4wMDRaIiBmaWxsPSIjOEY4RjhGIi8+CjwvZz4KPC9zdmc+Cg==",yt=xo;function Eo(e,t,i){switch(t){case"image":return Mo(e,i[t]);case"video":return To(e,i[t]);case"sticker":return Po(e,i[t]);default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function Mo(e,t){let i=t.width,r=t.height;return{id:e,meta:{previewUri:yt,fillType:"//ly.img.ubq/fill/image",kind:"image",width:i,height:r}}}function To(e,t){let i=t.width,r=t.height;return{id:e,label:t.label,meta:{previewUri:yt,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:i,height:r}}}function Po(e,t){let i=t.width,r=t.height;return{id:e,meta:{previewUri:yt,fillType:"//ly.img.ubq/fill/image",kind:"sticker",width:i,height:r}}}var jo=Eo;async function _o(e,t,i,r){switch(t){case"image":{if(r.kind!=="image")throw new Error(`Output kind does not match the expected type: ${r.kind} (expected: image)`);return Lo(e,i[t],r)}case"video":{if(r.kind!=="video")throw new Error(`Output kind does not match the expected type: ${r.kind} (expected: video)`);return Do(e,i[t],r)}case"audio":{if(r.kind!=="audio")throw new Error(`Output kind does not match the expected type: ${r.kind} (expected: audio)`);return No(e,i[t],r)}case"sticker":{if(r.kind!=="sticker")throw new Error(`Output kind does not match the expected type: ${r.kind} (expected: sticker)`);return Oo(e,i[t],r)}default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function Lo(e,t,i){let r=t.width,n=t.height;return{id:e,label:t.label,meta:{uri:i.url,thumbUri:i.url,fillType:"//ly.img.ubq/fill/image",kind:"image",width:r,height:n},payload:{sourceSet:[{uri:i.url,width:r,height:n}]}}}async function Do(e,t,i){let r=t.width,n=t.height,a=await ko(i.url,0);return{id:e,label:t.label,meta:{uri:i.url,thumbUri:a,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:r,height:n}}}function No(e,t,i){return{id:e,label:t.label,meta:{uri:i.url,thumbUri:i.thumbnailUrl,blockType:"//ly.img.ubq/audio",mimeType:"audio/x-m4a",duration:i.duration.toString()}}}function Oo(e,t,i){let r=t.width,n=t.height;return{id:e,label:t.label,meta:{uri:i.url,thumbUri:i.url,fillType:"//ly.img.ubq/fill/image",kind:"sticker",width:r,height:n},payload:{sourceSet:[{uri:i.url,width:r,height:n}]}}}var ci=_o;function Fo(e){switch(e.userFlow){case"placeholder":return zo(e);case"generation-only":return Ro(e);default:throw new Error(`Unknown user flow: ${e.userFlow}. Expected 'placeholder' or 'generation-only'.`)}}function Ro(e){let{cesdk:t,abortSignal:i}=e;return async r=>{try{let n=e.kind,a=await e.getBlockInput(r);if(z(t,i))return{status:"aborted"};let o=await e.generate(r,{middlewares:[...e.middlewares??[]],debug:e.debug,dryRun:e.dryRun,abortSignal:i});if(z(t,i))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(z(t,i))return{status:"aborted"};if(e.historyAssetSourceId!=null){let l=oi(),u=await ci(l,n,a,o.output),s={...u,id:`${Date.now()}-${u.id}`,label:u.label!=null?{en:u.label}:{},tags:{}};t.engine.asset.addAssetToSource(e.historyAssetSourceId,s)}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 zo(e){let{cesdk:t,abortSignal:i}=e,r;return async n=>{try{let a=e.kind,o=await e.getBlockInput(n);if(z(t,i))return{status:"aborted"};let l=oi(),u=jo(l,a,o);if(r=await ho(t,u),z(t,i,r))return{status:"aborted"};if(r!=null&&e.kind==="video"){let d=t.engine.block.getPositionX(r),p=t.engine.block.getPositionY(r),g=t.engine.block.duplicate(r);t.engine.block.setPositionX(g,d),t.engine.block.setPositionY(g,p),t.engine.block.destroy(r),r=g}if(r==null)throw new Error("Could not create placeholder block");t.engine.block.setState(r,{type:"Pending",progress:0});let s=await e.generate(n,{blockIds:[r],middlewares:[...e.middlewares??[]],debug:e.debug,dryRun:e.dryRun,abortSignal:i});if(z(t,i,r))return{status:"aborted"};if(s.status!=="success")return s.middlewareOptions?.defaultPrevented()||r!=null&&t.engine.block.isValid(r)&&(s.status==="aborted"?t.engine.block.destroy(r):t.engine.block.setState(r,{type:"Error",error:"Unknown"})),s;if(s.type==="async")throw new Error("Async generation is not supported in this context yet.");if(!t.engine.block.isValid(r))return{status:"aborted",message:"Placeholder block was destroyed before generation completed."};let c=await ci(l,a,o,s.output);if(z(t,i,r))return{status:"aborted"};if(e.debug&&console.log("Updating placeholder in scene:",JSON.stringify(c,void 0,2)),await t.engine.asset.defaultApplyAssetToBlock(c,r),z(t,i,r))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(r)&&t.engine.block.setState(r,{type:"Ready"}),s}catch(a){return r!=null&&t.engine.block.isValid(r)&&(bt(a)?t.engine.block.destroy(r):t.engine.block.setState(r,{type:"Error",error:"Unknown"})),{status:"error",message:a instanceof Error?a.message:String(a)}}}}function z(e,t,i){return t.aborted?(i!=null&&e.engine.block.isValid(i)&&e.engine.block.destroy(i),!0):!1}var Uo=Fo;function ht(e){return`${e}.generating`}function Bo(e){return`${e}.abort`}function Vo(e,t,i,r,n,a,o){let{builder:l,experimental:u}=e,{cesdk:s,includeHistoryLibrary:c=!0}=a,{id:d,output:{abortable:p}}=t,g=u.global(Bo(d),()=>{}),b=u.global(ht(d),!1),m,y=b.value&&p,v=()=>{y&&(g.value(),b.setValue(!1),g.setValue(()=>{}))},k;if(a.requiredInputs!=null&&a.requiredInputs.length>0){let C=r();k=a.requiredInputs.every(f=>!C.input[f])}let I=u.global(`${d}.confirmationDialogId`,void 0);l.Section(`${d}.generate.section`,{children:()=>{l.Button(`${d}.generate`,{label:["common.generate",`panel.${d}.generate`],isLoading:b.value,color:"accent",isDisabled:k,suffix:y?{icon:"@imgly/Cross",color:"danger",tooltip:[`panel.${d}.abort`,"common.cancel"],onClick:()=>{let C=s.ui.showDialog({type:"warning",content:"panel.ly.img.ai.generation.confirmCancel.content",cancel:{label:"common.close",onClick:({id:f})=>{s.ui.closeDialog(f),I.setValue(void 0)}},actions:{label:"panel.ly.img.ai.generation.confirmCancel.confirm",color:"danger",onClick:({id:f})=>{v(),s.ui.closeDialog(f),I.setValue(void 0)}}});I.setValue(C)}}:void 0,onClick:async()=>{m=new AbortController;let C=m.signal;await(async()=>{try{b.setValue(!0),g.setValue(()=>{o.debug&&console.log("Aborting generation"),m?.abort()});let f=await Uo({kind:t.kind,generate:i,historyAssetSourceId:a.historyAssetSourceId,userFlow:a.createPlaceholderBlock?"placeholder":"generation-only",getBlockInput:n,abortSignal:C,cesdk:s,debug:o.debug,dryRun:o.dryRun})(r().input);if(f.status==="aborted")return;if(f.status==="error"){qt(f.message,{cesdk:s,provider:t,getInput:r,middlewareOptions:f.middlewareOptions});return}if(f.status==="success"&&f.type==="sync"&&!f.middlewareOptions?.defaultPrevented()){let h=t.output.notification;qo(s,h,()=>({input:r().input,output:f.output}))}}catch(f){if(bt(f))return;qt(f,{cesdk:s,provider:t,getInput:r})}finally{m=void 0,b.setValue(!1),g.setValue(()=>{}),I.value!=null&&(s.ui.closeDialog(I.value),I.setValue(void 0))}})()}}),t.output.generationHintText!=null&&l.Text(`${d}.generation-hint`,{align:"center",content:t.output.generationHintText})}}),c&&a.historyAssetLibraryEntryId!=null&&l.Library(`${d}.history.library`,{entries:[a.historyAssetLibraryEntryId]})}function qo(e,t,i){let r=t?.success;if(r==null||!(typeof r.show=="function"?r.show(i()):r.show))return!1;let n=typeof r.message=="function"?r.message(i()):r.message??"common.ai-generation.success",a=r.action!=null?{label:typeof r.action.label=="function"?r.action.label(i()):r.action.label,onClick:()=>{r?.action?.onClick(i())}}:void 0;return e.ui.showNotification({type:"success",message:n,action:a,duration:r.duration}),!0}var ui=Vo;async function Go({options:e,provider:t,panelInput:i,config:r},n){if(i==null)return;let{cesdk:a}=e,{id:o}=t;r.debug&&console.log(`Provider: ${o} (custom)`);let l=i.render;return u=>{let{state:s}=u,c=s(ht(o),{isGenerating:!1,abort:()=>{}}).value.isGenerating,{getInput:d,getBlockInput:p}=l(u,{cesdk:a,isGenerating:c});return ui(u,t,n,d,p,{...e,includeHistoryLibrary:i.includeHistoryLibrary??!0,createPlaceholderBlock:i.userFlow==="placeholder"},r),d}}var Ho=Go;function di(e,t){if(!t.startsWith("#/"))throw new Error(`External references are not supported: ${t}`);let i=t.substring(2).split("/"),r=e;for(let n of i){if(r==null)throw new Error(`Invalid reference path: ${t}`);r=r[n]}if(r===void 0)throw new Error(`Reference not found: ${t}`);return r}function ge(e,t,i=new Set){if(t==null||i.has(t))return t;if(i.add(t),t.$ref&&typeof t.$ref=="string"){let r=di(e,t.$ref),n={...ge(e,r,i)};for(let a in t)Object.prototype.hasOwnProperty.call(t,a)&&a!=="$ref"&&(n[a]=ge(e,t[a],i));return n}if(Array.isArray(t))return t.map(r=>ge(e,r,i));if(typeof t=="object"){let r={};for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=ge(e,t[n],i));return r}return t}function Qo(e){return ge(e,{...e})}function Zo(e,t=!1){let i=o=>(t&&console.log(`OpenAPI Schema validation failed: ${o}`),!1);if(typeof e!="object"||e===null)return i(`Input is ${e===null?"null":typeof e}, not an object`);let r=e;if(!(typeof r.type=="string"||Array.isArray(r.enum)||typeof r.properties=="object"||typeof r.items=="object"||typeof r.allOf=="object"||typeof r.anyOf=="object"||typeof r.oneOf=="object"||typeof r.not=="object"))return i("Missing required schema-defining properties (type, enum, properties, items, allOf, anyOf, oneOf, not)");if(r.type!==void 0){let o=["string","number","integer","boolean","array","object","null"];if(typeof r.type=="string"){if(!o.includes(r.type))return i(`Invalid type: ${r.type}. Must be one of ${o.join(", ")}`)}else if(Array.isArray(r.type)){for(let l of r.type)if(typeof l!="string"||!o.includes(l))return i(`Array of types contains invalid value: ${l}. Must be one of ${o.join(", ")}`)}else return i(`Type must be a string or array of strings, got ${typeof r.type}`)}if(r.items!==void 0&&(typeof r.items!="object"||r.items===null))return i(`Items must be an object, got ${r.items===null?"null":typeof r.items}`);if(r.properties!==void 0&&(typeof r.properties!="object"||r.properties===null))return i(`Properties must be an object, got ${r.properties===null?"null":typeof r.properties}`);let n=["allOf","anyOf","oneOf"];for(let o of n)if(r[o]!==void 0){if(!Array.isArray(r[o]))return i(`${o} must be an array, got ${typeof r[o]}`);for(let l=0;l<r[o].length;l++){let u=r[o][l];if(typeof u!="object"||u===null)return i(`Item ${l} in ${o} must be an object, got ${u===null?"null":typeof u}`)}}if(r.not!==void 0&&(typeof r.not!="object"||r.not===null))return i(`'not' must be an object, got ${r.not===null?"null":typeof r.not}`);if(r.additionalProperties!==void 0&&typeof r.additionalProperties!="boolean"&&(typeof r.additionalProperties!="object"||r.additionalProperties===null))return i(`additionalProperties must be a boolean or an object, got ${r.additionalProperties===null?"null":typeof r.additionalProperties}`);if(r.format!==void 0&&typeof r.format!="string")return i(`format must be a string, got ${typeof r.format}`);let a=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf"];for(let o of a)if(r[o]!==void 0&&typeof r[o]!="number")return i(`${o} must be a number, got ${typeof r[o]}`);if(r.minLength!==void 0&&(typeof r.minLength!="number"||r.minLength<0))return i(`minLength must be a non-negative number, got ${typeof r.minLength=="number"?r.minLength:typeof r.minLength}`);if(r.maxLength!==void 0&&(typeof r.maxLength!="number"||r.maxLength<0))return i(`maxLength must be a non-negative number, got ${typeof r.maxLength=="number"?r.maxLength:typeof r.maxLength}`);if(r.pattern!==void 0&&typeof r.pattern!="string")return i(`pattern must be a string, got ${typeof r.pattern}`);if(r.minItems!==void 0&&(typeof r.minItems!="number"||r.minItems<0))return i(`minItems must be a non-negative number, got ${typeof r.minItems=="number"?r.minItems:typeof r.minItems}`);if(r.maxItems!==void 0&&(typeof r.maxItems!="number"||r.maxItems<0))return i(`maxItems must be a non-negative number, got ${typeof r.maxItems=="number"?r.maxItems:typeof r.maxItems}`);if(r.uniqueItems!==void 0&&typeof r.uniqueItems!="boolean")return i(`uniqueItems must be a boolean, got ${typeof r.uniqueItems}`);if(r.minProperties!==void 0&&(typeof r.minProperties!="number"||r.minProperties<0))return i(`minProperties must be a non-negative number, got ${typeof r.minProperties=="number"?r.minProperties:typeof r.minProperties}`);if(r.maxProperties!==void 0&&(typeof r.maxProperties!="number"||r.maxProperties<0))return i(`maxProperties must be a non-negative number, got ${typeof r.maxProperties=="number"?r.maxProperties:typeof r.maxProperties}`);if(r.required!==void 0){if(!Array.isArray(r.required))return i(`required must be an array, got ${typeof r.required}`);for(let o=0;o<r.required.length;o++){let l=r.required[o];if(typeof l!="string")return i(`Item ${o} in required array must be a string, got ${typeof l}`)}}return!0}function Yo(e,t){if(e.properties==null)throw new Error("Input schema must have properties");let i=e.properties,r=[];return Wo(e,t).forEach(n=>{let a=n,o=i[n]??void 0;r.push({id:a,schema:o})}),r}function Wo(e,t){let i=t.order;if(i!=null&&Array.isArray(i))return i;if(e.properties==null)throw new Error("Input schema must have properties");let r=e.properties,n=Object.keys(r),a=Ko(e,t)??n;return i!=null&&typeof i=="function"&&(a=i(a)),[...new Set(a)]}function Ko(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 i=(typeof t.orderExtensionKeyword=="string"?[t.orderExtensionKeyword]:t.orderExtensionKeyword).find(r=>r in e);return i==null?void 0:e[i]}var pi=Yo;function U(e,t,i,r){let n=`property.${e.id}${r?`.${r}`:""}`,a=[`ly.img.plugin-ai-${i}-generation-web.${t.id}.${n}`,`ly.img.plugin-ai-generation-web.${n}`,`ly.img.plugin-ai-${i}-generation-web.${t.id}.defaults.${n}`,`ly.img.plugin-ai-generation-web.defaults.${n}`];return r==="placeholder"&&a.push("ly.img.plugin-ai-generation-web.fallback.property.placeholder"),a}function gi(e){let t="x-imgly-enum-labels"in e&&typeof e["x-imgly-enum-labels"]=="object"?e["x-imgly-enum-labels"]:{},i="x-imgly-enum-icons"in e&&typeof e["x-imgly-enum-icons"]=="object"?e["x-imgly-enum-icons"]:{};return{labels:t,icons:i}}function mi(e,t,i,r,n,a,o,l){if(t.schema==null)if(r.renderCustomProperty!=null&&r.renderCustomProperty[t.id]!=null){let c={...e,providerConfig:l,config:a};return r.renderCustomProperty[t.id](c,t)}else return;let u=t,s=t.schema.type;if(r.renderCustomProperty!=null&&r.renderCustomProperty[t.id]!=null){let c={...e,providerConfig:l,config:a};return r.renderCustomProperty[t.id](c,t)}switch(s){case"string":return t.schema.enum!=null?Xo(e,u,i,r,n,a,o,l):fi(e,u,i,r,n,a,o,l);case"boolean":return bi(e,u,i,r,n,a,o,l);case"number":case"integer":return yi(e,u,i,r,n,a,o,l);case"object":return mt(e,u,i,r,n,a,o,l);case"array":break;case void 0:{if(t.schema.anyOf!=null&&Array.isArray(t.schema.anyOf))return Jo(e,u,i,r,n,a,o,l);break}default:console.error(`Unsupported property type: ${s}`)}}function mt(e,t,i,r,n,a,o,l){let u=pi(t.schema??{},r).reduce((s,c)=>{let d=mi(e,c,i,r,n,a,o,l);return d!=null&&(s[c.id]=d()),s},{});return()=>({id:t.id,type:"object",value:u})}function fi(e,t,i,r,n,a,o,l){let{builder:u,experimental:{global:s},engine:c}=e,{id:d}=t,p=`${i.id}.${d}`,g=U(t,i,o),b=U(t,i,o,"placeholder"),m=ke(c,n.cesdk),y=l?.properties?.[d]??a.properties?.[d],v=we(d,y,m,t.schema.default,""),k=s(p,v),I=el(t.schema),C=I?.component!=null&&I?.component==="TextArea"?"TextArea":"TextInput",f=b.length>0?b:void 0;return u[C](p,{inputLabel:g,...f&&{placeholder:f},...k}),()=>({id:t.id,type:"string",value:k.value})}function Xo(e,t,i,r,n,a,o,l){let{builder:u,experimental:{global:s},engine:c}=e,{id:d}=t,p=`${i.id}.${d}`,g=U(t,i,o),{labels:b,icons:m}=gi(t.schema),y=(t.schema.enum??[]).map(h=>({id:h,label:U(t,i,o,h),icon:m[h]})),v=ke(c,n.cesdk),k=l?.properties?.[d]??a.properties?.[d],I=we(d,k,v,t.schema.default,y[0]?.id),C=I!=null?y.find(h=>h.id===I)??y[0]:y[0],f=s(p,C);return u.Select(p,{inputLabel:g,values:y,...f}),()=>({id:t.id,type:"string",value:f.value.id})}function bi(e,t,i,r,n,a,o,l){let{builder:u,experimental:{global:s},engine:c}=e,{id:d}=t,p=`${i.id}.${d}`,g=U(t,i,o),b=ke(c,n.cesdk),m=l?.properties?.[d]??a.properties?.[d],y=!!we(d,m,b,t.schema.default,!1),v=s(p,y);return u.Checkbox(p,{inputLabel:g,...v}),()=>({id:t.id,type:"boolean",value:v.value})}function yi(e,t,i,r,n,a,o,l){let{builder:u,experimental:{global:s},engine:c}=e,{id:d}=t,p=`${i.id}.${d}`,g=U(t,i,o),b=t.schema.minimum,m=t.schema.maximum,y=ke(c,n.cesdk),v=l?.properties?.[d]??a.properties?.[d],k=t.schema.default;k==null&&(b!=null?k=b:m!=null?k=m:k=0);let I=we(d,v,y,k,k),C=s(p,I);if(b!=null&&m!=null){let f=t.schema.type==="number"?.1:1;"x-imgly-step"in t.schema&&typeof t.schema["x-imgly-step"]=="number"&&(f=t.schema["x-imgly-step"]),u.Slider(p,{inputLabel:g,min:b,max:m,step:f,...C})}else u.NumberInput(p,{inputLabel:g,min:b,max:m,...C});return()=>({id:t.id,type:"integer",value:C.value})}function Jo(e,t,i,r,n,a,o,l){let{builder:u,experimental:{global:s},engine:c}=e,{id:d}=t,p=`${i.id}.${d}`,g=U(t,i,o),b=t.schema.anyOf??[],m=[],y={},v={},{labels:k,icons:I}=gi(t.schema),C=ke(c,n.cesdk),f=l?.properties?.[d]??a.properties?.[d],h={string:fi,boolean:bi,integer:yi,object:mt},S=(A,D)=>A.$ref?A.$ref.split("/").pop():D.split(".").pop()??D,w=(A,D)=>({id:A,label:U(t,i,o,D),icon:I[D]??I[A]});b.forEach((A,D)=>{let x=`${i.id}.${d}.anyOf[${D}]`;if(A.$ref||A.title){let j=A.$ref?A.$ref.split("/").pop():A.title;y[x]=()=>mt(e,{id:x,schema:{...A,title:k[j]||j}},i,r,n,a,o,l),m.push(w(x,j))}else if(A.type==="string"&&A.enum)A.enum.forEach(j=>{m.push(w(j,j))});else if(A.type&&h[A.type]){let j=h[A.type];y[x]=()=>j(e,{id:x,schema:{...A,title:A.title}},i,r,n,a,o,l);let it=S(A,x);m.push(A.type==="string"&&!A.enum?{id:x,label:A.title||it,icon:A.title&&I[A.title]||I[it]}:w(x,it))}});let T=we(d,f,C,t.schema.default,null),$=T!=null?m.find(A=>A.id===T)??m[0]:m[0],P=s(p,$);if(u.Select(p,{inputLabel:g,values:m,...P}),P.value.id in y){let A=y[P.value.id]();v[P.value.id]=A}return()=>{let A=v[P.value.id];return A!=null?{...A(),id:t.id}:{id:t.id,type:"string",value:P.value.id}}}function el(e){if("x-imgly-builder"in e)return e["x-imgly-builder"]}var tl=mi,il={"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 Gt(e){return e.replace(/_/g," ").replace(/\b3d\b/gi,"3D").replace(/\b2d\b/gi,"2D").replace(/\b\w/g,t=>t.toUpperCase())}function rl(e,t,i,r){let n={},a=(s,c)=>`ly.img.plugin-ai-${r}-generation-web.${t.id}.defaults.property.${s}${c?`.${c}`:""}`,o=s=>"x-imgly-enum-labels"in s&&typeof s["x-imgly-enum-labels"]=="object"?s["x-imgly-enum-labels"]:{},l=(s,c,d)=>{s.forEach(p=>{let g=String(p),b=d[g]||Gt(g);n[a(c,g)]=b})};e.forEach(s=>{if(s.schema?.title&&(n[a(s.id)]=s.schema.title),s.schema?.enum){let c=o(s.schema);l(s.schema.enum,s.id,c)}if(s.schema?.anyOf&&Array.isArray(s.schema.anyOf)){let c=o(s.schema);s.schema.anyOf.forEach(d=>{let p=d;if(p.enum&&Array.isArray(p.enum))l(p.enum,s.id,c);else if(p.$ref){let g=p.$ref.split("/").pop();g&&c[g]&&(n[a(s.id,g)]=c[g])}else if(p.title){let g=p.title,b=c[g]||Gt(g);n[a(s.id,g)]=b}})}});let u={...il,...n};Object.keys(u).length>0&&i.cesdk.i18n.setTranslations({en:u})}async function nl({options:e,provider:t,panelInput:i,config:r,providerConfig:n},a){let{id:o}=t;if(i==null)return;r.debug&&console.log(`Provider: ${o} (schema-based)`);let l=Qo(i.document),u=di(l,i.inputReference);if(!Zo(u,r.debug))throw new Error(`Input reference '${i.inputReference}' does not resolve to a valid OpenAPI schema`);let s=u,c=pi(s,i);return rl(c,t,e,t.kind),d=>{let{builder:p}=d,g=[];p.Section(`${o}.schema.section`,{children:()=>{c.forEach(v=>{let k=tl(d,v,t,i,e,r,t.kind,n);k!=null&&(Array.isArray(k)?g.push(...k):g.push(k))})}});let b=g.map(v=>v()),m=v=>v.type==="object"?Object.entries(v.value).reduce((k,[I,C])=>(k[I]=m(C),k),{}):v.value,y=b.reduce((v,k)=>(v[k.id]=m(k),v),{});ui(d,t,a,()=>({input:y}),()=>i.getBlockInput(y),{...e,requiredInputs:s.required,createPlaceholderBlock:i.userFlow==="placeholder"},r)}}var al=nl;async function ol(e,t){if(e.panelInput!=null)switch(e.panelInput.type){case"custom":return Ho(e,t);case"schema":return al(e,t);default:e.config.debug&&console.warn(`Invalid panel input type '${panelInput.type}' - skipping`)}}var ll=ol;function sl(e){let{provider:t,options:{engine:i}}=e,r=t.output.history??"@imgly/local";if(r==null||r===!1)return;let n=i.asset.findAllSources();function a(){let o=`${t.id}.history`;for(;n.includes(o);)o+=`-${Math.random().toString(36).substring(2,6)}`;return o}if(r==="@imgly/local"){let o=a();return i.asset.addLocalSource(o),o}if(r==="@imgly/indexedDB"){let o=a();return i.asset.addSource(new dr(o,i)),o}return r}var cl=sl;function ul(e,t){if(t==null||!t)return;let i=`${e.provider.id}.history`;return e.options.cesdk.ui.addAssetLibraryEntry({id:i,sourceIds:[t],sortBy:{sortKey:"insertedAt",sortingOrder:"Descending"},canRemove:!0,gridItemHeight:"square",gridBackgroundType:"cover"}),i}var dl=ul,ot="@imgly/plugin-ai-generation",pl=`
<svg>
<symbol
fill="none"
xmlns="http://www.w3.org/2000/svg"
viewBox="