UNPKG

@imgly/plugin-ai-image-generation-web

Version:

AI image generation plugin for the CE.SDK editor

4 lines 113 kB
var Gr=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,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 m={...s,label:d,tags:p};return this.filterAsset(m,e)&&u.push(m),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),l=a<t.length?r+1:void 0;return{assets:o,currentPage:r,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 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;Y(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=()=>{Y(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 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)},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 Y(e,i=>{r.add(i)}),await Promise.all([...r].map(async i=>{let n=await this.createBlobUrlFromStore(i);t[i]=n})),Y(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(" "),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(i){let o=Array.isArray(i)?i:[i];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:r,sortKey:i,sortActiveFirst:n}=t,a=[...e];return!r||r==="None"||(i?a.sort((o,l)=>{let u,s;return i==="id"?(u=o.id,s=l.id):(u=o.meta?.[i]??null,s=l.meta?.[i]??null),u==null?r==="Ascending"?-1:1:s==null?r==="Ascending"?1:-1:typeof u=="string"&&typeof s=="string"?r==="Ascending"?u.localeCompare(s):s.localeCompare(u):r==="Ascending"?u<s?-1:u>s?1:0:u>s?-1:u<s?1:0}):r==="Descending"&&a.reverse(),n&&a.sort((o,l)=>o.active&&!l.active?-1:!o.active&&l.active?1:0)),a}};function Y(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]=Y(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]=Y(n,t,a)}return e}var qr=class{constructor(e,t,r){this.id=e,this.cesdk=t,this.assetSourceIds=r}async findAssets(e){try{let t=this.assetSourceIds.map(c=>this.cesdk.engine.asset.findAssets(c,{...e,perPage:9999,page:0})),r=await Promise.all(t),i=[];r.forEach(c=>{c?.assets&&(i=i.concat(c.assets))}),i.sort((c,d)=>{let p=c.meta?.insertedAt||0;return(d.meta?.insertedAt||0)-p});let{page:n,perPage:a}=e,o=n*a,l=o+a,u=i.slice(o,l),s=l<i.length?n+1:void 0;return{assets:u,currentPage:n,nextPage:s,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")}},Hr=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)}},$t=Hr,Qr=typeof global=="object"&&global&&global.Object===Object&&global,Et=Qr,Zr=typeof self=="object"&&self&&self.Object===Object&&self,Yr=Et||Zr||Function("return this")(),_=Yr,Wr=_.Symbol,W=Wr,Mt=Object.prototype,Kr=Mt.hasOwnProperty,Xr=Mt.toString,le=W?W.toStringTag:void 0;function Jr(e){var t=Kr.call(e,le),r=e[le];try{e[le]=void 0;var i=!0}catch{}var n=Xr.call(e);return i&&(t?e[le]=r:delete e[le]),n}var ei=Jr,ti=Object.prototype,ri=ti.toString;function ii(e){return ri.call(e)}var ni=ii,oi="[object Null]",ai="[object Undefined]",ct=W?W.toStringTag:void 0;function li(e){return e==null?e===void 0?ai:oi:ct&&ct in Object(e)?ei(e):ni(e)}var ge=li;function si(e){return e!=null&&typeof e=="object"}var He=si,Qu=Array.isArray;function ci(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var jt=ci,ui="[object AsyncFunction]",di="[object Function]",pi="[object GeneratorFunction]",gi="[object Proxy]";function mi(e){if(!jt(e))return!1;var t=ge(e);return t==di||t==pi||t==ui||t==gi}var fi=mi,bi=_["__core-js_shared__"],Ne=bi,ut=function(){var e=/[^.]+$/.exec(Ne&&Ne.keys&&Ne.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function yi(e){return!!ut&&ut in e}var hi=yi,vi=Function.prototype,ki=vi.toString;function wi(e){if(e!=null){try{return ki.call(e)}catch{}try{return e+""}catch{}}return""}var q=wi,Ii=/[\\^$.*+?()[\]{}|]/g,Ai=/^\[object .+?Constructor\]$/,Ci=Function.prototype,Si=Object.prototype,xi=Ci.toString,$i=Si.hasOwnProperty,Ei=RegExp("^"+xi.call($i).replace(Ii,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Mi(e){if(!jt(e)||hi(e))return!1;var t=fi(e)?Ei:Ai;return t.test(q(e))}var ji=Mi;function Pi(e,t){return e?.[t]}var Ti=Pi;function _i(e,t){var r=Ti(e,t);return ji(r)?r:void 0}var K=_i,Di=K(_,"WeakMap"),ze=Di;function Ni(e,t){return e===t||e!==e&&t!==t}var Li=Ni,Oi=9007199254740991;function Ri(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=Oi}var Fi=Ri,Zu=Object.prototype,zi="[object Arguments]";function Bi(e){return He(e)&&ge(e)==zi}var dt=Bi,Pt=Object.prototype,Ui=Pt.hasOwnProperty,Vi=Pt.propertyIsEnumerable,Yu=dt(function(){return arguments}())?dt:function(e){return He(e)&&Ui.call(e,"callee")&&!Vi.call(e,"callee")},Tt=typeof exports=="object"&&exports&&!exports.nodeType&&exports,pt=Tt&&typeof module=="object"&&module&&!module.nodeType&&module,Gi=pt&&pt.exports===Tt,gt=Gi?_.Buffer:void 0,Wu=gt?gt.isBuffer:void 0,qi="[object Arguments]",Hi="[object Array]",Qi="[object Boolean]",Zi="[object Date]",Yi="[object Error]",Wi="[object Function]",Ki="[object Map]",Xi="[object Number]",Ji="[object Object]",en="[object RegExp]",tn="[object Set]",rn="[object String]",nn="[object WeakMap]",on="[object ArrayBuffer]",an="[object DataView]",ln="[object Float32Array]",sn="[object Float64Array]",cn="[object Int8Array]",un="[object Int16Array]",dn="[object Int32Array]",pn="[object Uint8Array]",gn="[object Uint8ClampedArray]",mn="[object Uint16Array]",fn="[object Uint32Array]",A={};A[ln]=A[sn]=A[cn]=A[un]=A[dn]=A[pn]=A[gn]=A[mn]=A[fn]=!0;A[qi]=A[Hi]=A[on]=A[Qi]=A[an]=A[Zi]=A[Yi]=A[Wi]=A[Ki]=A[Xi]=A[Ji]=A[en]=A[tn]=A[rn]=A[nn]=!1;function bn(e){return He(e)&&Fi(e.length)&&!!A[ge(e)]}var yn=bn;function hn(e){return function(t){return e(t)}}var vn=hn,_t=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ue=_t&&typeof module=="object"&&module&&!module.nodeType&&module,kn=ue&&ue.exports===_t,Le=kn&&Et.process,wn=function(){try{var e=ue&&ue.require&&ue.require("util").types;return e||Le&&Le.binding&&Le.binding("util")}catch{}}(),mt=wn,ft=mt&&mt.isTypedArray,Ku=ft?vn(ft):yn,In=Object.prototype,Xu=In.hasOwnProperty;function An(e,t){return function(r){return e(t(r))}}var Cn=An,Ju=Cn(Object.keys,Object),Sn=Object.prototype,ed=Sn.hasOwnProperty,xn=K(Object,"create"),de=xn;function $n(){this.__data__=de?de(null):{},this.size=0}var En=$n;function Mn(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var jn=Mn,Pn="__lodash_hash_undefined__",Tn=Object.prototype,_n=Tn.hasOwnProperty;function Dn(e){var t=this.__data__;if(de){var r=t[e];return r===Pn?void 0:r}return _n.call(t,e)?t[e]:void 0}var Nn=Dn,Ln=Object.prototype,On=Ln.hasOwnProperty;function Rn(e){var t=this.__data__;return de?t[e]!==void 0:On.call(t,e)}var Fn=Rn,zn="__lodash_hash_undefined__";function Bn(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=de&&t===void 0?zn:t,this}var Un=Bn;function X(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])}}X.prototype.clear=En;X.prototype.delete=jn;X.prototype.get=Nn;X.prototype.has=Fn;X.prototype.set=Un;var bt=X;function Vn(){this.__data__=[],this.size=0}var Gn=Vn;function qn(e,t){for(var r=e.length;r--;)if(Li(e[r][0],t))return r;return-1}var Ce=qn,Hn=Array.prototype,Qn=Hn.splice;function Zn(e){var t=this.__data__,r=Ce(t,e);if(r<0)return!1;var i=t.length-1;return r==i?t.pop():Qn.call(t,r,1),--this.size,!0}var Yn=Zn;function Wn(e){var t=this.__data__,r=Ce(t,e);return r<0?void 0:t[r][1]}var Kn=Wn;function Xn(e){return Ce(this.__data__,e)>-1}var Jn=Xn;function eo(e,t){var r=this.__data__,i=Ce(r,e);return i<0?(++this.size,r.push([e,t])):r[i][1]=t,this}var to=eo;function J(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])}}J.prototype.clear=Gn;J.prototype.delete=Yn;J.prototype.get=Kn;J.prototype.has=Jn;J.prototype.set=to;var Se=J,ro=K(_,"Map"),pe=ro;function io(){this.size=0,this.__data__={hash:new bt,map:new(pe||Se),string:new bt}}var no=io;function oo(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var ao=oo;function lo(e,t){var r=e.__data__;return ao(t)?r[typeof t=="string"?"string":"hash"]:r.map}var xe=lo;function so(e){var t=xe(this,e).delete(e);return this.size-=t?1:0,t}var co=so;function uo(e){return xe(this,e).get(e)}var po=uo;function go(e){return xe(this,e).has(e)}var mo=go;function fo(e,t){var r=xe(this,e),i=r.size;return r.set(e,t),this.size+=r.size==i?0:1,this}var bo=fo;function ee(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])}}ee.prototype.clear=no;ee.prototype.delete=co;ee.prototype.get=po;ee.prototype.has=mo;ee.prototype.set=bo;var Dt=ee;function yo(){this.__data__=new Se,this.size=0}var ho=yo;function vo(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var ko=vo;function wo(e){return this.__data__.get(e)}var Io=wo;function Ao(e){return this.__data__.has(e)}var Co=Ao,So=200;function xo(e,t){var r=this.__data__;if(r instanceof Se){var i=r.__data__;if(!pe||i.length<So-1)return i.push([e,t]),this.size=++r.size,this;r=this.__data__=new Dt(i)}return r.set(e,t),this.size=r.size,this}var $o=xo;function me(e){var t=this.__data__=new Se(e);this.size=t.size}me.prototype.clear=ho;me.prototype.delete=ko;me.prototype.get=Io;me.prototype.has=Co;me.prototype.set=$o;var Eo=Object.prototype,td=Eo.propertyIsEnumerable,Mo=K(_,"DataView"),Be=Mo,jo=K(_,"Promise"),Ue=jo,Po=K(_,"Set"),Ve=Po,yt="[object Map]",To="[object Object]",ht="[object Promise]",vt="[object Set]",kt="[object WeakMap]",wt="[object DataView]",_o=q(Be),Do=q(pe),No=q(Ue),Lo=q(Ve),Oo=q(ze),Z=ge;(Be&&Z(new Be(new ArrayBuffer(1)))!=wt||pe&&Z(new pe)!=yt||Ue&&Z(Ue.resolve())!=ht||Ve&&Z(new Ve)!=vt||ze&&Z(new ze)!=kt)&&(Z=function(e){var t=ge(e),r=t==To?e.constructor:void 0,i=r?q(r):"";if(i)switch(i){case _o:return wt;case Do:return yt;case No:return ht;case Lo:return vt;case Oo:return kt}return t});var rd=_.Uint8Array,Ro="__lodash_hash_undefined__";function Fo(e){return this.__data__.set(e,Ro),this}var zo=Fo;function Bo(e){return this.__data__.has(e)}var Uo=Bo;function Ge(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new Dt;++t<r;)this.add(e[t])}Ge.prototype.add=Ge.prototype.push=zo;Ge.prototype.has=Uo;var It=W?W.prototype:void 0,id=It?It.valueOf:void 0,Vo=Object.prototype,nd=Vo.hasOwnProperty,Go=Object.prototype,od=Go.hasOwnProperty,ad=new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,"i"),ld=new RegExp(/[A-Fa-f0-9]{1}/,"g"),sd=new RegExp(/[A-Fa-f0-9]{2}/,"g");function qo(e){return{"image/png":"png","image/jpeg":"jpg","image/webp":"webp","image/gif":"gif","image/svg+xml":"svg"}[e]??"png"}async function Nt(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 qe(e,t){let r=await Nt(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 Ho(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 Nt(i,t)}function Qo(e){return e!==void 0}var $e=Qo;var Qe=class Lt{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 Lt),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))}},Ot=class Rt{constructor(){this.providers=new Map}static get(){let t="__imgly_provider_registry__",r=typeof window<"u"?window:globalThis;return r[t]||(r[t]=new Rt),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 Zo(e){let t=e.filter(r=>!!r);return r=>async(i,n)=>{let a=[],o=s=>{a.push(s)},l=async(s,c,d)=>{if(s>=t.length)return r(c,d);let p=t[s],m=async(b,v)=>l(s+1,b,v),g={...d,addDisposer:o};return p(c,g,m)},u={...n,addDisposer:o};return{result:await l(0,i,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 Yo({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 Wo=Yo;var Oe="ly.img.ai.temp";async function Ko(e,t){return e.engine.asset.findAllSources().includes(Oe)||e.engine.asset.addLocalSource(Oe),e.engine.asset.apply(Oe,t)}function Xo(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 Ft(){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 Jo(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 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(r,i);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 ea(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 ta(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 Ze(e){return e instanceof Error&&e.name==="AbortError"}function ra(e,t,r){let i=`${t}.iconSetAdded`;e.ui.experimental.hasGlobalStateValue(i)||(e.ui.addIconSet(t,r),e.ui.experimental.setGlobalStateValue(i,!0))}function zt(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 ia(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 Bt=ia;function na(){return({engine:e})=>{let t=e.block.findAllSelected();if(t==null||t.length!==1)return!1;let[r]=t;if(!e.block.supportsFill(r)||e.block.getKind(r)==="sticker"||!["//ly.img.ubq/graphic","//ly.img.ubq/page"].includes(e.block.getType(r)))return!1;let i=e.block.getFill(r);return e.block.getType(i)==="//ly.img.ubq/fill/image"}}var M=na;function oa(e,t){let{cesdk:r,provider:i,getInput:n}=t;console.error("Generation failed:",e),aa(r,i.output.notification,()=>({input:n?.().input,error:e}))||r.ui.showNotification({type:"error",message:Xo(e)})}function aa(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 At=oa,la="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIzIiBoZWlnaHQ9IjMyMyIgdmlld0JveD0iMCAwIDMyMyAzMjMiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIzMjMiIGhlaWdodD0iMzIzIiBmaWxsPSIjRTlFQkVEIi8+CjxnIG9wYWNpdHk9IjAuMyI+CjxwYXRoIGQ9Ik0xMTYgMTg0VjE5MS41QzExNiAxOTkuNzg0IDEyMi43MTYgMjA2LjUgMTMxIDIwNi41SDE5MUMxOTkuMjg0IDIwNi41IDIwNiAxOTkuNzg0IDIwNiAxOTEuNVYxMzEuNUMyMDYgMTIzLjIxNiAxOTkuMjg0IDExNi41IDE5MSAxMTYuNUwxOTAuOTk1IDEyNi41QzE5My43NTcgMTI2LjUgMTk2IDEyOC43MzkgMTk2IDEzMS41VjE5MS41QzE5NiAxOTQuMjYxIDE5My43NjEgMTk2LjUgMTkxIDE5Ni41SDEzMUMxMjguMjM5IDE5Ni41IDEyNiAxOTQuMjYxIDEyNiAxOTEuNVYxODRIMTE2WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTY2LjQ5NCAxMDUuOTI0QzE2NS44NjkgMTA0LjM0MiAxNjMuNjI5IDEwNC4zNDIgMTYzLjAwNSAxMDUuOTI0TDE1OS43NDUgMTE0LjE5MUMxNTkuNTU0IDExNC42NzQgMTU5LjE3MiAxMTUuMDU3IDE1OC42ODggMTE1LjI0N0wxNTAuNDIyIDExOC41MDhDMTQ4LjgzOSAxMTkuMTMyIDE0OC44MzkgMTIxLjM3MiAxNTAuNDIyIDEyMS45OTZMMTU4LjY4OCAxMjUuMjU2QzE1OS4xNzIgMTI1LjQ0NyAxNTkuNTU0IDEyNS44MjkgMTU5Ljc0NSAxMjYuMzEzTDE2My4wMDUgMTM0LjU3OUMxNjMuNjI5IDEzNi4xNjIgMTY1Ljg2OSAxMzYuMTYyIDE2Ni40OTQgMTM0LjU3OUwxNjkuNzU0IDEyNi4zMTNDMTY5Ljk0NCAxMjUuODI5IDE3MC4zMjcgMTI1LjQ0NyAxNzAuODEgMTI1LjI1NkwxNzkuMDc3IDEyMS45OTZDMTgwLjY2IDEyMS4zNzIgMTgwLjY2IDExOS4xMzIgMTc5LjA3NyAxMTguNTA4TDE3MC44MSAxMTUuMjQ3QzE3MC4zMjcgMTE1LjA1NyAxNjkuOTQ0IDExNC42NzQgMTY5Ljc1NCAxMTQuMTkxTDE2Ni40OTQgMTA1LjkyNFoiIGZpbGw9IiM4RjhGOEYiLz4KPHBhdGggZD0iTTEzMy4wMDUgMTI4LjQyNEMxMzMuNjI5IDEyNi44NDIgMTM1Ljg2OSAxMjYuODQyIDEzNi40OTQgMTI4LjQyNEwxNDEuODc1IDE0Mi4wN0MxNDIuMDY2IDE0Mi41NTMgMTQyLjQ0OCAxNDIuOTM1IDE0Mi45MzIgMTQzLjEyNkwxNTYuNTc3IDE0OC41MDhDMTU4LjE2IDE0OS4xMzIgMTU4LjE2IDE1MS4zNzIgMTU2LjU3NyAxNTEuOTk2TDE0Mi45MzIgMTU3LjM3OEMxNDIuNDQ4IDE1Ny41NjggMTQyLjA2NiAxNTcuOTUxIDE0MS44NzUgMTU4LjQzNEwxMzYuNDk0IDE3Mi4wNzlDMTM1Ljg2OSAxNzMuNjYyIDEzMy42MjkgMTczLjY2MiAxMzMuMDA1IDE3Mi4wNzlMMTI3LjYyMyAxNTguNDM0QzEyNy40MzMgMTU3Ljk1MSAxMjcuMDUgMTU3LjU2OCAxMjYuNTY3IDE1Ny4zNzhMMTEyLjkyMiAxNTEuOTk2QzExMS4zMzkgMTUxLjM3MiAxMTEuMzM5IDE0OS4xMzIgMTEyLjkyMiAxNDguNTA4TDEyNi41NjcgMTQzLjEyNkMxMjcuMDUgMTQyLjkzNSAxMjcuNDMzIDE0Mi41NTMgMTI3LjYyMyAxNDIuMDdMMTMzLjAwNSAxMjguNDI0WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTk1Ljk5OSAxODQuMDA0VjE5MS41MDJDMTk1Ljk5OSAxOTQuMjYzIDE5My43NjEgMTk2LjUwMiAxOTAuOTk5IDE5Ni41MDJIMTQ3LjY2OEwxNzIuODc5IDE1OC42ODRDMTc0LjM2MyAxNTYuNDU4IDE3Ny42MzUgMTU2LjQ1OCAxNzkuMTIgMTU4LjY4NEwxOTUuOTk5IDE4NC4wMDRaIiBmaWxsPSIjOEY4RjhGIi8+CjwvZz4KPC9zdmc+Cg==",Ye=la;function sa(e,t,r){switch(t){case"image":return ca(e,r[t]);case"video":return ua(e,r[t]);case"sticker":return da(e,r[t]);default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function ca(e,t){let r=t.width,i=t.height;return{id:e,meta:{previewUri:Ye,fillType:"//ly.img.ubq/fill/image",kind:"image",width:r,height:i}}}function ua(e,t){let r=t.width,i=t.height;return{id:e,label:t.label,meta:{previewUri:Ye,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:r,height:i}}}function da(e,t){let r=t.width,i=t.height;return{id:e,meta:{previewUri:Ye,fillType:"//ly.img.ubq/fill/image",kind:"sticker",width:r,height:i}}}var pa=sa;async function ga(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 ma(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 fa(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 ba(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 ya(e,r[t],i)}default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function ma(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 fa(e,t,r){let i=t.width,n=t.height,a=await Jo(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 ba(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 ya(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 Ut=ga;function ha(e){switch(e.userFlow){case"placeholder":return ka(e);case"generation-only":return va(e);default:throw new Error(`Unknown user flow: ${e.userFlow}. Expected 'placeholder' or 'generation-only'.`)}}function va(e){let{cesdk:t,abortSignal:r}=e;return async i=>{try{let n=e.kind,a=await e.getBlockInput(i);if(O(t,r))return{status:"aborted"};let o=await e.generate(i,{middlewares:[...e.middlewares??[]],debug:e.debug,dryRun:e.dryRun,abortSignal:r});if(O(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(O(t,r))return{status:"aborted"};if(e.historyAssetSourceId!=null){let l=Ft(),u=await Ut(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 ka(e){let{cesdk:t,abortSignal:r}=e,i;return async n=>{try{let a=e.kind,o=await e.getBlockInput(n);if(O(t,r))return{status:"aborted"};let l=Ft(),u=pa(l,a,o);if(i=await Ko(t,u),O(t,r,i))return{status:"aborted"};if(i!=null&&e.kind==="video"){let d=t.engine.block.getPositionX(i),p=t.engine.block.getPositionY(i),m=t.engine.block.duplicate(i);t.engine.block.setPositionX(m,d),t.engine.block.setPositionY(m,p),t.engine.block.destroy(i),i=m}if(i==null)throw new Error("Could not create placeholder block");t.engine.block.setState(i,{type:"Pending",progress:0});let s=await e.generate(n,{middlewares:[...e.middlewares??[]],debug:e.debug,dryRun:e.dryRun,abortSignal:r});if(O(t,r,i))return{status:"aborted"};if(s.status!=="success")return s;if(s.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 Ut(l,a,o,s.output);if(O(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),O(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"}),s}catch(a){return i!=null&&t.engine.block.isValid(i)&&(Ze(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 O(e,t,r){return t.aborted?(r!=null&&e.engine.block.isValid(r)&&e.engine.block.destroy(r),!0):!1}var wa=ha;function We(e){return`${e}.generating`}function Ia(e){return`${e}.abort`}function Aa(e,t,r,i,n,a,o){let{builder:l,experimental:u}=e,{cesdk:s,includeHistoryLibrary:c=!0}=a,{id:d,output:{abortable:p}}=t,m=u.global(Ia(d),()=>{}),g=u.global(We(d),!1),b,v=g.value&&p,h=()=>{v&&(m.value(),g.setValue(!1),m.setValue(()=>{}))},k;if(a.requiredInputs!=null&&a.requiredInputs.length>0){let y=i();k=a.requiredInputs.every(f=>!y.input[f])}let S=u.global(`${d}.confirmationDialogId`,void 0);l.Section(`${d}.generate.section`,{children:()=>{l.Button(`${d}.generate`,{label:["common.generate",`panel.${d}.generate`],isLoading:g.value,color:"accent",isDisabled:k,suffix:v?{icon:"@imgly/Cross",color:"danger",tooltip:[`panel.${d}.abort`,"common.cancel"],onClick:()=>{let y=s.ui.showDialog({type:"warning",content:"panel.ly.img.ai.generation.confirmCancel.content",cancel:{label:"common.close",onClick:({id:f})=>{s.ui.closeDialog(f),S.setValue(void 0)}},actions:{label:"panel.ly.img.ai.generation.confirmCancel.confirm",color:"danger",onClick:({id:f})=>{h(),s.ui.closeDialog(f),S.setValue(void 0)}}});S.setValue(y)}}:void 0,onClick:async()=>{b=new AbortController;let y=b.signal;await(async()=>{try{g.setValue(!0),m.setValue(()=>{o.debug&&console.log("Aborting generation"),b?.abort()});let f=await wa({kind:t.kind,generate:r,historyAssetSourceId:a.historyAssetSourceId,userFlow:a.createPlaceholderBlock?"placeholder":"generation-only",getBlockInput:n,abortSignal:y,cesdk:s,debug:o.debug,dryRun:o.dryRun})(i().input);if(f.status==="aborted")return;if(f.status==="error"){At(f.message,{cesdk:s,provider:t,getInput:i});return}if(f.status==="success"&&f.type==="sync"){let I=t.output.notification;Ca(s,I,()=>({input:i().input,output:f.output}))}}catch(f){if(Ze(f))return;At(f,{cesdk:s,provider:t,getInput:i})}finally{b=void 0,g.setValue(!1),m.setValue(()=>{}),S.value!=null&&(s.ui.closeDialog(S.value),S.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 Ca(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 Vt=Aa;async function Sa({options:e,provider:t,panelInput:r,config:i},n){if(r==null)return;let{cesdk:a}=e,{id:o}=t,l=r.render;return u=>{let{state:s}=u,c=s(We(o),{isGenerating:!1,abort:()=>{}}).value.isGenerating,{getInput:d,getBlockInput:p}=l(u,{cesdk:a,isGenerating:c});return Vt(u,t,n,d,p,{...e,includeHistoryLibrary:r.includeHistoryLibrary??!0,createPlaceholderBlock:r.userFlow==="placeholder"},i),d}}var xa=Sa;function Gt(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 ce(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=Gt(e,t.$ref),n={...ce(e,i,r)};for(let a in t)Object.prototype.hasOwnProperty.call(t,a)&&a!=="$ref"&&(n[a]=ce(e,t[a],r));return n}if(Array.isArray(t))return t.map(i=>ce(e,i,r));if(typeof t=="object"){let i={};for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[n]=ce(e,t[n],r));return i}return t}function $a(e){return ce(e,{...e})}function Ea(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 l of i.type)if(typeof l!="string"||!o.includes(l))return r(`Array of types contains invalid value: ${l}. 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 l=0;l<i[o].length;l++){let u=i[o][l];if(typeof u!="object"||u===null)return r(`Item ${l} 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 l=i.required[o];if(typeof l!="string")return r(`Item ${o} in required array must be a string, got ${typeof l}`)}}return!0}function Ma(e,t){if(e.properties==null)throw new Error("Input schema must have properties");let r=e.properties,i=[];return ja(e,t).forEach(n=>{let a=n,o=r[n]??void 0;i.push({id:a,schema:o})}),i}function ja(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=Pa(e,t)??n;return r!=null&&typeof r=="function"&&(a=r(a)),[...new Set(a)]}function Pa(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 qt=Ma;function Ht(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 l=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?Ta(e,l,r,i,n,a,o):Zt(e,l,r,i,n,a,o);case"boolean":return Yt(e,l,r,i,n,a,o);case"number":case"integer":return Wt(e,l,r,i,n,a,o);case"object":return Qt(e,l,r,i,n,a,o);case"array":break;case void 0:{if(t.schema.anyOf!=null&&Array.isArray(t.schema.anyOf))return _a(e,l,r,i,n,a,o);break}default:console.error(`Unsupported property type: ${u}`)}}function Qt(e,t,r,i,n,a,o){let l=qt(t.schema??{},i).reduce((u,s)=>{let c=Ht(e,s,r,i,n,a,o);return c!=null&&(u[s.id]=c()),u},{});return()=>({id:t.id,type:"object",value:l})}function Zt(e,t,r,i,n,a,o){let{builder:l,experimental:{global:u}}=e,{id:s}=t,c=`${r.id}.${s}`,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}`],p=u(c,t.schema.default??""),m=Da(t.schema),g=m?.component!=null&&m?.component==="TextArea"?"TextArea":"TextInput";return l[g](c,{inputLabel:d,placeholder:n.i18n?.prompt,...p}),()=>({id:t.id,type:"string",value:p.value})}function Ta(e,t,r,i,n,a,o){let{builder:l,experimental:{global:u}}=e,{id:s}=t,c=`${r.id}.${s}`,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}`],p="x-imgly-enum-icons"in t.schema&&typeof t.schema["x-imgly-enum-icons"]=="object"?t.schema["x-imgly-enum-icons"]:{},m="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(h=>({id:h,label:[`ly.img.plugin-ai-${o}-generation-web.${r.id}.property.${t.id}.${h}`,`ly.img.plugin-ai-generation-web.property.${t.id}.${h}`,`ly.img.plugin-ai-${o}-generation-web.${r.id}.defaults.property.${t.id}.${h}`,`ly.img.plugin-ai-generation-web.defaults.property.${t.id}.${h}`],icon:p[h]})),b=t.schema.default!=null?g.find(h=>h.id===t.schema.default)??g[0]:g[0],v=u(c,b);return l.Select(c,{inputLabel:d,values:g,...v}),()=>({id:t.id,type:"string",value:v.value.id})}function Yt(e,t,r,i,n,a,o){let{builder:l,experimental:{global:u}}=e,{id:s}=t,c=`${r.id}.${s}`,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}`],p=!!t.schema.default,m=u(c,p);return l.Checkbox(c,{inputLabel:d,...m}),()=>({id:t.id,type:"boolean",value:m.value})}function Wt(e,t,r,i,n,a,o){let{builder:l,experimental:{global:u}}=e,{id:s}=t,c=`${r.id}.${s}`,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}`],p=t.schema.minimum,m=t.schema.maximum,g=t.schema.default;g==null&&(p!=null?g=p:m!=null?g=m:g=0);let b=u(c,g);if(p!=null&&m!=null){let v=t.schema.type==="number"?.1:1;"x-imgly-step"in t.schema&&typeof t.schema["x-imgly-step"]=="number"&&(v=t.schema["x-imgly-step"]),l.Slider(c,{inputLabel:d,min:p,max:m,step:v,...b})}else l.NumberInput(c,{inputLabel:d,min:p,max:m,...b});return()=>({id:t.id,type:"integer",value:b.value})}function _a(e,t,r,i,n,a,o){let{builder:l,experimental:{global:u}}=e,{id:s}=t,c=`${r.id}.${s}`,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}`],p=t.schema.anyOf??[],m=[],g={},b={};p.forEach((k,S)=>{let y=k.title??"common.custom",f=`${r.id}.${s}.anyOf[${S}]`,I="x-imgly-enum-labels"in t.schema&&typeof t.schema["x-imgly-enum-labels"]=="object"?t.schema["x-imgly-enum-labels"]:{},w="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(x=>{m.push({id:x,label:I[x]??ea(x),icon:w[x]})}):(g[f]=()=>Zt(e,{id:f,schema:{...k,title:y}},r,i,n,a,o),m.push({id:f,label:I[y]??y,icon:w[y]})):k.type==="boolean"?(g[f]=()=>Yt(e,{id:f,schema:{...k,title:y}},r,i,n,a,o),m.push({id:f,label:I[y]??y,icon:w[y]})):k.type==="integer"?(g[f]=()=>Wt(e,{id:f,schema:{...k,title:y}},r,i,n,a,o),m.push({id:f,label:I[y]??y,icon:w[y]})):k.type==="array"||k.type==="object"&&(g[f]=()=>Qt(e,{id:f,schema:{...k,title:y}},r,i,n,a,o),m.push({id:f,label:I[y]??y,icon:w[y]}))});let v=t.schema.default!=null?m.find(k=>k.id===t.schema.default)??m[0]:m[0],h=u(c,v);if(l.Select(c,{inputLabel:d,values:m,...h}),h.value.id in g){let k=g[h.value.id]();b[h.value.id]=k}return()=>{let k=b[h.value.id];return k!=null?{...k(),id:t.id}:{id:t.id,type:"string",value:h.value.id}}}function Da(e){if("x-imgly-builder"in e)return e["x-imgly-builder"]}var Na=Ht,La={"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 Ct(e){return e.replace(/_/g," ").replace(/\b3d\b/gi,"3D").replace(/\b2d\b/gi,"2D").replace(/\b\w/g,t=>t.toUpperCase())}function Oa(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 l="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 s=String(u),c=l[s]||Ct(s);n[`ly.img.plugin-ai-${i}-generation-web.${t.id}.defaults.property.${o.id}.${s}`]=c})}if(o.schema?.anyOf&&Array.isArray(o.schema.anyOf)){let l="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 s=u;s.enum&&Array.isArray(s.enum)&&s.enum.forEach(c=>{let d=String(c),p=l[d]||Ct(d);n[`ly.img.plugin-ai-${i}-generation-web.defaults.property.${t.id}.${o.id}.${d}`]=p})})}});let a={...La,...n};Object.keys(a).length>0&&r.cesdk.i18n.setTranslations({en:a})}async function Ra({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=$a(r.document),l=Gt(o,r.inputReference);if(!Ea(l,i.debug))throw new Error(`Input reference '${r.inputReference}' does not resolve to a valid OpenAPI schema`);let u=l,s=qt(u,r);return Oa(s,t,e,t.kind),c=>{let{builder:d}=c,p=[];d.Section(`${a}.schema.section`,{children:()=>{s.forEach(v=>{let h=Na(c,v,t,r,e,i,t.kind);h!=null&&(Array.isArray(h)?p.push(...h):p.push(h))})}});let m=p.map(v=>v()),g=v=>v.type==="object"?Object.entries(v.value).reduce((h,[k,S])=>(h[k]=g(S),h),{}):v.value,b=m.reduce((v,h)=>(v[h.id]=g(h),v),{});Vt(c,t,n,()=>({input:b}),()=>r.getBlockInput(b),{...e,requiredInputs:u.required,createPlaceholderBlock:r.userFlow==="placeholder"},i)}}var Fa=Ra;async function za(e,t){if(e.panelInput!=null)switch(e.panelInput.type){case"custom":return xa(e,t);case"schema":return Fa(e,t);default:e.config.debug&&console.warn(`Invalid panel input type '${panelInput.type}' - skipping`)}}var Ba=za;function Ua(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 Gr(o,r)),o}return i}var Va=Ua;function Ga(e,t){if(t==null||!t)return;let r=`${e.provider.id}.history`;