@imgly/plugin-ai-generation-web
Version:
AI generation plugin for the CE.SDK editor
4 lines • 96.5 kB
JavaScript
function Ht(t,e){let{cesdk:r}=e,n=e.propertyKey??"image_url",i=pe(t);return r.i18n.setTranslations({en:{[`panel.${i}`]:"Select Image To Change"}}),Qt(t,r),{[n]:(o,s)=>{let{builder:l,experimental:{global:u},payload:c}=o,d=c?.url??e.defaultUrl,p=u(`${t}.${s.id}`,d);return l.MediaPreview(s.id,{preview:{type:"image",uri:p.value},action:{label:"Select Image",onClick:()=>{r?.ui.openPanel(i,{payload:{onSelect:m=>{m.meta?.uri!=null&&p.setValue(m.meta?.uri)}}})}}}),()=>({id:s.id,type:"string",value:p.value})}}}function Qt(t,e){e?.ui.registerPanel(pe(t),({builder:r,payload:n})=>{r.Library(`${t}.library.image`,{entries:["ly.img.image"],onSelect:async i=>{let a=i?.meta?.uri;if(a==null)return;let o=await e.engine.editor.getMimeType(a);o==="image/svg+xml"?e.ui.showNotification({type:"warning",message:"SVG images are not supported. Please choose a different image."}):o.startsWith("image/")?(n?.onSelect(i),e?.ui.closePanel(pe(t))):e.ui.showNotification({type:"warning",message:`Only images are supported. Found '${o}'. Please choose a different image.`})}})})}function pe(t){return`ly.img.ai.${t}.imageSelection`}var Ne=Ht;var et=class{constructor(t,e=[]){this.id=t,this.assets=e.map(r=>{if(typeof r.label=="string"&&!(r.label&&typeof r.label=="object")){let n=r;return{id:n.id,label:{en:n.label},meta:n.thumbUri?{...n.meta??{},thumbUri:n.thumbUri}:n.meta}}return r}),this.activeAssetIds=new Set}async findAssets(t){let{page:e,perPage:r,locale:n="en",sortActiveFirst:i,query:a,tags:o,groups:s,excludeGroups:l,sortingOrder:u,sortKey:c}=t,d=[...this.assets];if(s&&s.length>0&&(d=d.filter(g=>g.groups&&s.some(f=>g.groups?.includes(f)))),l&&l.length>0&&(d=d.filter(g=>!g.groups||!l.some(f=>g.groups?.includes(f)))),a){let g=a.toLowerCase();d=d.filter(f=>{let k=f.label?.[n]?.toLowerCase(),y=f.tags?.[n]||[];return k&&k.includes(g)||y.some(h=>h.toLowerCase().includes(g))})}if(o&&o.length>0){let g=Array.isArray(o)?o:[o];d=d.filter(f=>{let k=f.tags?.[n]||[];return g.some(y=>k.includes(y))})}i&&d.sort((g,f)=>{let k=this.activeAssetIds.has(g.id),y=this.activeAssetIds.has(f.id);return k&&!y?-1:!k&&y?1:0}),c&&c!=="id"?d.sort((g,f)=>{let k=g.meta?.[c],y=f.meta?.[c];return k===void 0?1:y===void 0?-1:typeof k=="string"&&typeof y=="string"?u==="Descending"?y.localeCompare(k):k.localeCompare(y):typeof k=="number"&&typeof y=="number"?u==="Descending"?y-k:k-y:0}):c==="id"&&d.sort((g,f)=>u==="Descending"?f.id.localeCompare(g.id):g.id.localeCompare(f.id));let p=d.length,m=e*r,b=m+r,I=d.slice(m,b).map(g=>({id:g.id,groups:g.groups,meta:g.meta,payload:g.payload,locale:n,label:g.label?.[n],tags:g.tags?.[n],active:this.activeAssetIds.has(g.id)})),v=b<p?e+1:void 0;return{assets:I,currentPage:e,nextPage:v,total:p}}updateLabel(t,e,r){this.assets.forEach(n=>{n.id===t&&(n.label=n.label||{},n.label[r]=e)})}getAssetSelectValue(t){let e=this.assets.find(({id:r})=>r===t);if(e)return{id:e.id,label:e.label?.en||"",thumbUri:e.meta?.thumbUri}}getAsset(t){return this.assets.find(e=>e.id===t)}setAssetActive(t){this.activeAssetIds.add(t)}getActiveAssetIds(){return Array.from(this.activeAssetIds)}setAssetsActive(t){t.forEach(e=>this.activeAssetIds.add(e))}setAssetInactive(t){this.activeAssetIds.delete(t)}clearActiveAssets(){this.activeAssetIds.clear()}isAssetActive(t){return this.activeAssetIds.has(t)}addAsset(t){let e=this.assets.findIndex(r=>r.id===t.id);e>=0?this.assets[e]=t:this.assets.push(t)}removeAsset(t){let e=this.assets.findIndex(r=>r.id===t);e!==-1&&(this.assets.splice(e,1),this.activeAssetIds.delete(t))}async getGroups(){let t=new Set;return this.assets.forEach(e=>{e.groups&&e.groups.forEach(r=>t.add(r))}),Array.from(t)}getSupportedMimeTypes(){return["image/jpeg","image/png","image/svg+xml","image/webp","video/mp4","audio/mpeg"]}},tt=class{constructor(t,e,r){this.assetStoreName="assets",this.blobStoreName="blobs",this.db=null,this.id=t,this.engine=e,this.dbName=r?.dbName??`ly.img.assetSource/${t}`,this.dbVersion=r?.dbVersion??1}async initialize(){if(!this.db)return new Promise((t,e)=>{let r=indexedDB.open(this.dbName,this.dbVersion);r.onerror=n=>{e(new Error(`Failed to open IndexedDB: ${n.target.error}`))},r.onupgradeneeded=n=>{let i=n.target.result;i.objectStoreNames.contains(this.assetStoreName)||i.createObjectStore(this.assetStoreName,{keyPath:"id"}),i.objectStoreNames.contains(this.blobStoreName)||i.createObjectStore(this.blobStoreName,{keyPath:"id"})},r.onsuccess=n=>{this.db=n.target.result,t()}})}close(){this.db&&(this.db.close(),this.db=null)}async findAssets(t){if(await this.initialize(),!this.db)throw new Error("Database not initialized");try{let e=(await this.getAllAssets("asc")).reduce((l,u)=>{let c=t.locale??"en",d="",p=[];u.label!=null&&typeof u.label=="object"&&u.label[c]&&(d=u.label[c]),u.tags!=null&&typeof u.tags=="object"&&u.tags[c]&&(p=u.tags[c]);let m={...u,label:d,tags:p};return this.filterAsset(m,t)&&l.push(m),l},[]);e=await this.restoreBlobUrls(e),e=this.sortAssets(e,t);let{page:r,perPage:n}=t,i=r*n,a=i+n,o=e.slice(i,a),s=a<e.length?r+1:void 0;return{assets:o,currentPage:r,nextPage:s,total:e.length}}catch(e){console.error("Error finding assets:",e);return}}async getGroups(){if(await this.initialize(),!this.db)throw new Error("Database not initialized");return new Promise((t,e)=>{let r=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).getAll();r.onsuccess=()=>{let n=new Set;r.result.forEach(a=>{a.groups&&Array.isArray(a.groups)&&a.groups.forEach(o=>n.add(o))});let i=[...n];t(i)},r.onerror=()=>{e(new Error(`Failed to get groups: ${r.error}`))}})}addAsset(t){this.initialize().then(async()=>{if(!this.db)throw new Error("Database not initialized");let e=this.db.transaction(this.assetStoreName,"readwrite"),r=e.objectStore(this.assetStoreName),n=new Set;L(t,a=>{n.add(a)}),setTimeout(()=>{this.storeBlobUrls([...n])});let i={...t,meta:{...t.meta,insertedAt:t.meta?.insertedAt||Date.now()}};r.put(i),e.onerror=()=>{console.error(`Failed to add asset: ${e.error}`)}}).catch(e=>{console.error("Error initializing database:",e)})}async removeAsset(t){let e=await this.getAsset(t);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(t),r.oncomplete=()=>{L(e,n=>{this.removeBlob(n)}),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(t){return this.initialize().then(()=>{if(!this.db)throw new Error("Database not initialized");let e=this.db.transaction(this.blobStoreName,"readwrite");e.objectStore(this.blobStoreName).delete(t),e.onerror=()=>{console.error(`Failed to remove blob: ${e.error}`)}}).catch(e=>{console.error("Error initializing database:",e)})}async getAllAssets(t="desc"){return new Promise((e,r)=>{let n=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).getAll();n.onsuccess=()=>{let i=n.result;i.sort((a,o)=>{let s=a.meta?.insertedAt||a._insertedAt||Date.now(),l=o.meta?.insertedAt||o._insertedAt||Date.now();return t==="asc"?s-l:l-s}),e(i)},n.onerror=()=>{r(new Error(`Failed to get assets: ${n.error}`))}})}async getAsset(t){return new Promise((e,r)=>{let n=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).get(t);n.onsuccess=()=>{e(n.result)},n.onerror=()=>{r(new Error(`Failed to get blob: ${n.error}`))}})}async getBlob(t){return new Promise((e,r)=>{let n=this.db.transaction(this.blobStoreName,"readonly").objectStore(this.blobStoreName).get(t);n.onsuccess=()=>{e(n.result)},n.onerror=()=>{r(new Error(`Failed to get blob: ${n.error}`))}})}async createBlobUrlFromStore(t){let e=await this.getBlob(t);return e!=null?URL.createObjectURL(e.blob):t}async storeBlobUrls(t){let e={};return await Promise.all(t.map(async r=>{let n=await(await fetch(r)).blob();e[r]=n})),this.initialize().then(async()=>{if(!this.db)throw new Error("Database not initialized");let r=this.db.transaction(this.blobStoreName,"readwrite"),n=r.objectStore(this.blobStoreName);Object.entries(e).forEach(([i,a])=>{let o={id:i,blob:a};n.put(o)}),r.onerror=()=>{console.error(`Failed to add blobs: ${r.error}`)}}).catch(r=>{console.error("Error initializing database:",r)})}async restoreBlobUrls(t){let e={},r=new Set;return L(t,n=>{r.add(n)}),await Promise.all([...r].map(async n=>{let i=await this.createBlobUrlFromStore(n);e[n]=i})),L(t,n=>e[n]??n)}filterAsset(t,e){let{query:r,tags:n,groups:i,excludeGroups:a}=e;if(r&&r.trim()!==""){let o=r.trim().toLowerCase().split(" "),s=t.label?.toLowerCase()??"",l=t.tags?.map(u=>u.toLowerCase())??[];if(!o.every(u=>s.includes(u)||l.some(c=>c.includes(u))))return!1}if(n){let o=Array.isArray(n)?n:[n];if(o.length>0&&(!t.tags||!o.every(s=>t.tags?.includes(s))))return!1}return!(i&&i.length>0&&(!t.groups||!i.some(o=>t.groups?.includes(o)))||a&&a.length>0&&t.groups&&t.groups.some(o=>a.includes(o)))}sortAssets(t,e){let{sortingOrder:r,sortKey:n,sortActiveFirst:i}=e,a=[...t];return!r||r==="None"||(n?a.sort((o,s)=>{let l,u;return n==="id"?(l=o.id,u=s.id):(l=o.meta?.[n]??null,u=s.meta?.[n]??null),l==null?r==="Ascending"?-1:1:u==null?r==="Ascending"?1:-1:typeof l=="string"&&typeof u=="string"?r==="Ascending"?l.localeCompare(u):u.localeCompare(l):r==="Ascending"?l<u?-1:l>u?1:0:l>u?-1:l<u?1:0}):r==="Descending"&&a.reverse(),i&&a.sort((o,s)=>o.active&&!s.active?-1:!o.active&&s.active?1:0)),a}};function L(t,e,r=""){if(t===null||typeof t!="object")return t;if(Array.isArray(t)){for(let n=0;n<t.length;n++){let i=r?`${r}[${n}]`:`[${n}]`;if(typeof t[n]=="string"&&t[n].startsWith("blob:")){let a=e(t[n],i);typeof a=="string"&&(t[n]=a)}else t[n]=L(t[n],e,i)}return t}for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)){let i=t[n],a=r?`${r}.${n}`:n;if(typeof i=="string"&&i.startsWith("blob:")){let o=e(i,a);typeof o=="string"&&(t[n]=o)}else t[n]=L(i,e,a)}return t}var rt=class{constructor(t,e,r){this.id=t,this.cesdk=e,this.assetSourceIds=r}async findAssets(t){try{let e=this.assetSourceIds.map(c=>this.cesdk.engine.asset.findAssets(c,{...t,perPage:9999,page:0})),r=await Promise.all(e),n=[];r.forEach(c=>{c?.assets&&(n=n.concat(c.assets))}),n.sort((c,d)=>{let p=c.meta?.insertedAt||0;return(d.meta?.insertedAt||0)-p});let{page:i,perPage:a}=t,o=i*a,s=o+a,l=n.slice(o,s),u=s<n.length?i+1:void 0;return{assets:l,currentPage:i,nextPage:u,total:n.length}}catch(e){console.error("Error finding assets:",e);return}}async getGroups(){let t=this.assetSourceIds.map(n=>this.cesdk.engine.asset.getGroups(n)),e=await Promise.all(t),r=new Set;return e.forEach(n=>{n.forEach(i=>r.add(i))}),Array.from(r)}addAsset(t){throw new Error("AggregatedAssetSource does not support adding assets")}removeAsset(t){throw new Error("AggregatedAssetSource does not support removing assets")}},qt=class{constructor(t,e){this.engine=t,this.key=e}hasData(t){return this.engine.block.isValid(t)&&this.engine.block.hasMetadata(t,this.key)}get(t){if(this.hasData(t))return JSON.parse(this.engine.block.getMetadata(t,this.key))}set(t,e){this.engine.block.setMetadata(t,this.key,JSON.stringify(e))}clear(t){this.engine.block.hasMetadata(t,this.key)&&this.engine.block.removeMetadata(t,this.key)}},re=qt,Yt=typeof global=="object"&&global&&global.Object===Object&&global,nt=Yt,Zt=typeof self=="object"&&self&&self.Object===Object&&self,Wt=nt||Zt||Function("return this")(),A=Wt,Jt=A.Symbol,$=Jt,it=Object.prototype,Xt=it.hasOwnProperty,er=it.toString,G=$?$.toStringTag:void 0;function tr(t){var e=Xt.call(t,G),r=t[G];try{t[G]=void 0;var n=!0}catch{}var i=er.call(t);return n&&(e?t[G]=r:delete t[G]),i}var rr=tr,nr=Object.prototype,ir=nr.toString;function or(t){return ir.call(t)}var ar=or,sr="[object Null]",lr="[object Undefined]",Be=$?$.toStringTag:void 0;function ur(t){return t==null?t===void 0?lr:sr:Be&&Be in Object(t)?rr(t):ar(t)}var Q=ur;function cr(t){return t!=null&&typeof t=="object"}var ve=cr,Aa=Array.isArray;function dr(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var ot=dr,pr="[object AsyncFunction]",gr="[object Function]",mr="[object GeneratorFunction]",fr="[object Proxy]";function yr(t){if(!ot(t))return!1;var e=Q(t);return e==gr||e==mr||e==pr||e==fr}var br=yr,hr=A["__core-js_shared__"],ge=hr,Ve=function(){var t=/[^.]+$/.exec(ge&&ge.keys&&ge.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}();function Ir(t){return!!Ve&&Ve in t}var vr=Ir,Or=Function.prototype,wr=Or.toString;function kr(t){if(t!=null){try{return wr.call(t)}catch{}try{return t+""}catch{}}return""}var M=kr,Sr=/[\\^$.*+?()[\]{}|]/g,Cr=/^\[object .+?Constructor\]$/,xr=Function.prototype,Ar=Object.prototype,Rr=xr.toString,Er=Ar.hasOwnProperty,Pr=RegExp("^"+Rr.call(Er).replace(Sr,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Mr(t){if(!ot(t)||vr(t))return!1;var e=br(t)?Pr:Cr;return e.test(M(t))}var Dr=Mr;function Kr(t,e){return t?.[e]}var Tr=Kr;function Lr(t,e){var r=Tr(t,e);return Dr(r)?r:void 0}var F=Lr,$r=F(A,"WeakMap"),fe=$r;function Fr(t,e){return t===e||t!==t&&e!==e}var jr=Fr,Nr=9007199254740991;function Br(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=Nr}var Vr=Br;var Ra=Object.prototype;var _r="[object Arguments]";function Gr(t){return ve(t)&&Q(t)==_r}var _e=Gr,at=Object.prototype,zr=at.hasOwnProperty,Ur=at.propertyIsEnumerable,Ea=_e(function(){return arguments}())?_e:function(t){return ve(t)&&zr.call(t,"callee")&&!Ur.call(t,"callee")};var st=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ge=st&&typeof module=="object"&&module&&!module.nodeType&&module,Hr=Ge&&Ge.exports===st,ze=Hr?A.Buffer:void 0,Pa=ze?ze.isBuffer:void 0;var Qr="[object Arguments]",qr="[object Array]",Yr="[object Boolean]",Zr="[object Date]",Wr="[object Error]",Jr="[object Function]",Xr="[object Map]",en="[object Number]",tn="[object Object]",rn="[object RegExp]",nn="[object Set]",on="[object String]",an="[object WeakMap]",sn="[object ArrayBuffer]",ln="[object DataView]",un="[object Float32Array]",cn="[object Float64Array]",dn="[object Int8Array]",pn="[object Int16Array]",gn="[object Int32Array]",mn="[object Uint8Array]",fn="[object Uint8ClampedArray]",yn="[object Uint16Array]",bn="[object Uint32Array]",S={};S[un]=S[cn]=S[dn]=S[pn]=S[gn]=S[mn]=S[fn]=S[yn]=S[bn]=!0;S[Qr]=S[qr]=S[sn]=S[Yr]=S[ln]=S[Zr]=S[Wr]=S[Jr]=S[Xr]=S[en]=S[tn]=S[rn]=S[nn]=S[on]=S[an]=!1;function hn(t){return ve(t)&&Vr(t.length)&&!!S[Q(t)]}var In=hn;function vn(t){return function(e){return t(e)}}var On=vn,lt=typeof exports=="object"&&exports&&!exports.nodeType&&exports,z=lt&&typeof module=="object"&&module&&!module.nodeType&&module,wn=z&&z.exports===lt,me=wn&&nt.process,kn=function(){try{var t=z&&z.require&&z.require("util").types;return t||me&&me.binding&&me.binding("util")}catch{}}(),Ue=kn,He=Ue&&Ue.isTypedArray,Ma=He?On(He):In;var Sn=Object.prototype,Da=Sn.hasOwnProperty;function Cn(t,e){return function(r){return t(e(r))}}var xn=Cn,Ka=xn(Object.keys,Object);var An=Object.prototype,Ta=An.hasOwnProperty;var Rn=F(Object,"create"),U=Rn;function En(){this.__data__=U?U(null):{},this.size=0}var Pn=En;function Mn(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var Dn=Mn,Kn="__lodash_hash_undefined__",Tn=Object.prototype,Ln=Tn.hasOwnProperty;function $n(t){var e=this.__data__;if(U){var r=e[t];return r===Kn?void 0:r}return Ln.call(e,t)?e[t]:void 0}var Fn=$n,jn=Object.prototype,Nn=jn.hasOwnProperty;function Bn(t){var e=this.__data__;return U?e[t]!==void 0:Nn.call(e,t)}var Vn=Bn,_n="__lodash_hash_undefined__";function Gn(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=U&&e===void 0?_n:e,this}var zn=Gn;function j(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}j.prototype.clear=Pn;j.prototype.delete=Dn;j.prototype.get=Fn;j.prototype.has=Vn;j.prototype.set=zn;var Qe=j;function Un(){this.__data__=[],this.size=0}var Hn=Un;function Qn(t,e){for(var r=t.length;r--;)if(jr(t[r][0],e))return r;return-1}var ne=Qn,qn=Array.prototype,Yn=qn.splice;function Zn(t){var e=this.__data__,r=ne(e,t);if(r<0)return!1;var n=e.length-1;return r==n?e.pop():Yn.call(e,r,1),--this.size,!0}var Wn=Zn;function Jn(t){var e=this.__data__,r=ne(e,t);return r<0?void 0:e[r][1]}var Xn=Jn;function ei(t){return ne(this.__data__,t)>-1}var ti=ei;function ri(t,e){var r=this.__data__,n=ne(r,t);return n<0?(++this.size,r.push([t,e])):r[n][1]=e,this}var ni=ri;function N(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}N.prototype.clear=Hn;N.prototype.delete=Wn;N.prototype.get=Xn;N.prototype.has=ti;N.prototype.set=ni;var ie=N,ii=F(A,"Map"),H=ii;function oi(){this.size=0,this.__data__={hash:new Qe,map:new(H||ie),string:new Qe}}var ai=oi;function si(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}var li=si;function ui(t,e){var r=t.__data__;return li(e)?r[typeof e=="string"?"string":"hash"]:r.map}var oe=ui;function ci(t){var e=oe(this,t).delete(t);return this.size-=e?1:0,e}var di=ci;function pi(t){return oe(this,t).get(t)}var gi=pi;function mi(t){return oe(this,t).has(t)}var fi=mi;function yi(t,e){var r=oe(this,t),n=r.size;return r.set(t,e),this.size+=r.size==n?0:1,this}var bi=yi;function B(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var n=t[e];this.set(n[0],n[1])}}B.prototype.clear=ai;B.prototype.delete=di;B.prototype.get=gi;B.prototype.has=fi;B.prototype.set=bi;var ut=B;function hi(){this.__data__=new ie,this.size=0}var Ii=hi;function vi(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r}var Oi=vi;function wi(t){return this.__data__.get(t)}var ki=wi;function Si(t){return this.__data__.has(t)}var Ci=Si,xi=200;function Ai(t,e){var r=this.__data__;if(r instanceof ie){var n=r.__data__;if(!H||n.length<xi-1)return n.push([t,e]),this.size=++r.size,this;r=this.__data__=new ut(n)}return r.set(t,e),this.size=r.size,this}var Ri=Ai;function q(t){var e=this.__data__=new ie(t);this.size=e.size}q.prototype.clear=Ii;q.prototype.delete=Oi;q.prototype.get=ki;q.prototype.has=Ci;q.prototype.set=Ri;var Ei=Object.prototype,La=Ei.propertyIsEnumerable;var Pi=F(A,"DataView"),ye=Pi,Mi=F(A,"Promise"),be=Mi,Di=F(A,"Set"),he=Di,qe="[object Map]",Ki="[object Object]",Ye="[object Promise]",Ze="[object Set]",We="[object WeakMap]",Je="[object DataView]",Ti=M(ye),Li=M(H),$i=M(be),Fi=M(he),ji=M(fe),T=Q;(ye&&T(new ye(new ArrayBuffer(1)))!=Je||H&&T(new H)!=qe||be&&T(be.resolve())!=Ye||he&&T(new he)!=Ze||fe&&T(new fe)!=We)&&(T=function(t){var e=Q(t),r=e==Ki?t.constructor:void 0,n=r?M(r):"";if(n)switch(n){case Ti:return Je;case Li:return qe;case $i:return Ye;case Fi:return Ze;case ji:return We}return e});var $a=A.Uint8Array;var Ni="__lodash_hash_undefined__";function Bi(t){return this.__data__.set(t,Ni),this}var Vi=Bi;function _i(t){return this.__data__.has(t)}var Gi=_i;function Ie(t){var e=-1,r=t==null?0:t.length;for(this.__data__=new ut;++e<r;)this.add(t[e])}Ie.prototype.add=Ie.prototype.push=Vi;Ie.prototype.has=Gi;var Xe=$?$.prototype:void 0,Fa=Xe?Xe.valueOf:void 0;var zi=Object.prototype,ja=zi.hasOwnProperty;var Ui=Object.prototype,Na=Ui.hasOwnProperty;var Ba=new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,"i"),Va=new RegExp(/[A-Fa-f0-9]{1}/,"g"),_a=new RegExp(/[A-Fa-f0-9]{2}/,"g");function ct(t){return{"image/png":"png","image/jpeg":"jpg","image/webp":"webp","image/gif":"gif","image/svg+xml":"svg"}[t]??"png"}async function dt(t,e){if(t.startsWith("buffer:")){let r=await e.editor.getMimeType(t),n=e.editor.getBufferLength(t),i=e.editor.getBufferData(t,0,n),a=new Blob([i],{type:r});return URL.createObjectURL(a)}else return t}async function Y(t,e){let r=await dt(t,e);return new Promise((n,i)=>{let a=new Image;a.onload=()=>{n({width:a.width,height:a.height})},a.onerror=i,a.src=r})}async function pt(t,e,r){let n,i=e.block.getFill(t),a=e.block.getSourceSet(i,"fill/image/sourceSet"),[o]=a;if(o==null){if(n=e.block.getString(i,"fill/image/imageFileURI"),n==null)throw new Error("No image source/uri found")}else n=o.uri;if(r?.throwErrorIfSvg&&await e.editor.getMimeType(n)==="image/svg+xml")throw new Error("SVG images are not supported");return dt(n,e)}function Hi(t){return t!==void 0}var R=Hi;function Qi(t,e){let{cesdk:r}=e;if(r==null)return{};let n=e.propertyKey??"style",i=Yi(t);r.i18n.setTranslations({en:{[`panel.${i}`]:"Select Style",[`${t}.${n}`]:"Style"}});let a=Wi({baseURL:e.baseURL??"https://cdn.img.ly/assets/plugins/plugin-ai-image-generation-web/v1/gpt-image-1/",includeNone:!0}),o=a;e.styles!=null&&(Array.isArray(e.styles)?o=e.styles:typeof e.styles=="function"&&(o=e.styles(a)));let s=Ji({cesdk:r,providerId:t,styles:o}),l=s.id;return Xi(s,{cesdk:r}),qi({providerId:t,cesdk:r,panelId:i,entryId:l}),{[e.propertyKeyForPrompt??"prompt"]:(c,d)=>{let p=c.state("prompt","");return c.builder.TextArea(`${d.id}`,{inputLabel:e.i18n?.prompt?.inputLabel??e.propertyKeyForPrompt??"prompt",placeholder:e.i18n?.prompt?.placeholder,...p}),()=>{let[m]=s.getActiveAssetIds(),b=s.getAsset(m);return{id:d.id,type:"string",value:b?.meta?.prompt==null?p.value:`${p.value}; ${b.meta.prompt}`}}},[n]:(c,d)=>{let{builder:p,state:m}=c;if(o.length>0){let b=m("style",o[0]);return p.Button(`${d.id}`,{inputLabel:`${t}.${d.id}`,icon:"@imgly/Appearance",isDisabled:o.length===0,trailingIcon:"@imgly/ChevronRight",label:b.value.label,labelAlignment:"left",onClick:()=>{let I={onSelect:async v=>{s.clearActiveAssets(),s.setAssetActive(v.id),b.setValue({id:v.id,label:v.label??v.id}),r.ui.closePanel(i)}};r.ui.openPanel(i,{payload:I})}}),()=>({id:d.id,type:"string",value:b.value.id})}return()=>({id:d.id,type:"string",value:"none"})}}}function qi(t){let{providerId:e,cesdk:r,panelId:n,entryId:i}=t;r?.ui.registerPanel(n,({builder:a,payload:o})=>{o?.onSelect==null&&a.Section(`${e}.error`,{children:()=>{a.Text("error",{content:"No onSelect function provided for the style selection panel."})}}),a.Library(`${e}.library.image`,{entries:[i],onSelect:async s=>{o?.onSelect?.(s)}})})}function Yi(t){return`ly.img.ai.${t}.styleSelection`}var Zi=[{id:"none",label:"None",prompt:""},{id:"anime-celshaded",label:"Anime",prompt:"anime cel\u2011shaded, bright pastel palette, expressive eyes, clean line art "},{id:"cyberpunk-neon",label:"Cyberpunk",prompt:"cyberpunk cityscape, glowing neon signage, reflective puddles, dark atmosphere"},{id:"kodak-portra-400",label:"Kodak 400",prompt:"shot on Kodak Portra 400, soft grain, golden\u2011hour warmth, 35 mm photo"},{id:"watercolor-storybook",label:"Watercolor",prompt:"loose watercolor washes, gentle gradients, dreamy storybook feel"},{id:"dark-fantasy-realism",label:"Dark Fantasy",prompt:"dark fantasy realm, moody chiaroscuro lighting, hyper\u2011real textures"},{id:"vaporwave-retrofuturism",label:"Vaporwave",prompt:"retro\u2011futuristic vaporwave, pastel sunset gradient, chrome text, VHS scanlines"},{id:"minimal-vector-flat",label:"Vector Flat",prompt:"minimalist flat vector illustration, bold geometry, two\u2011tone palette"},{id:"pixarstyle-3d-render",label:"3D Animation",prompt:"Pixar\u2011style 3D render, oversized eyes, subtle subsurface scattering, cinematic lighting"},{id:"ukiyoe-woodblock",label:"Ukiyo\u2011e",prompt:"ukiyo\u2011e woodblock print, Edo\u2011period style, visible washi texture, limited color ink"},{id:"surreal-dreamscape",label:"Surreal",prompt:"surreal dreamscape, floating objects, impossible architecture, vivid clouds"},{id:"steampunk-victorian",label:"Steampunk",prompt:"Victorian steampunk world, ornate brass gears, leather attire, atmospheric fog"},{id:"nightstreet-photo-bokeh",label:"Night Bokeh",prompt:"night\u2011time street shot, large aperture bokeh lights, candid urban mood"},{id:"comicbook-pop-art",label:"Pop Art",prompt:"classic comic\u2011book panel, halftone shading, exaggerated action lines, CMYK pop colors"}];function Wi(t){return Zi.map(e=>e.id==="none"?t.includeNone?{...e,thumbUri:`${t.baseURL}/thumbnails/None.svg`}:void 0:{...e,thumbUri:`${t.baseURL}/thumbnails/${e.id}.jpeg`}).filter(R)}var Ji=t=>{let e=t.styles.map(o=>({...o,meta:{prompt:o.prompt}})),r=t.cesdk.engine.asset.findAllSources(),n=`${t.providerId}/styles`;for(;r.includes(n);)n+=`-${Math.random().toString(36).substring(2,5)}`;let i=new et(n,e),a=t.styles[0];return i.setAssetActive(a.id),i},Xi=(t,e)=>{e.cesdk.engine.asset.addSource(t),e.cesdk.ui.addAssetLibraryEntry({id:t.id,sourceIds:[t.id],gridItemHeight:"square",gridBackgroundType:"cover",cardLabel:({label:r})=>r,cardLabelPosition:()=>"below"})},gt=Qi;function eo(t,e,r){let n=`ly.img.${t}`,i=r.ui.getAssetLibraryEntry(n);if(i!=null)return r.ui.updateAssetLibraryEntry(n,{sourceIds:[...i.sourceIds,...e]}),i.id}var to=eo;var Z=class t{constructor(){this.actions=new Map;this.subscribers=new Map}static get(){let e="__imgly_action_registry__",r=typeof window<"u"?window:globalThis;return r[e]||(r[e]=new t),r[e]}register(e){return this.actions.set(e.id,e),this.notifySubscribers(e,"registered"),()=>{this.actions.get(e.id)===e&&(this.actions.delete(e.id),this.notifySubscribers(e,"unregistered"))}}getAll(){return Array.from(this.actions.values())}getBy(e){return this.getAll().filter(n=>this.matchesFilters(n,e))}subscribe(e){return this.subscribers.set(e,null),()=>{this.subscribers.delete(e)}}subscribeBy(e,r){return this.subscribers.set(r,e),()=>{this.subscribers.delete(r)}}notifySubscribers(e,r){this.subscribers.forEach((n,i)=>{if(n===null){i(e,r);return}this.matchesFilters(e,n)&&i(e,r)})}matchesFilters(e,r){return!(r.type&&e.type!==r.type||r.pluginId&&e.type==="plugin"&&e.pluginId!==r.pluginId||r.id&&e.id!==r.id||r.kind&&(e.type!=="quick"||e.kind!==r.kind))}};var D=class t{constructor(){this.providers=new Map}static get(){let e="__imgly_provider_registry__",r=typeof window<"u"?window:globalThis;return r[e]||(r[e]=new t),r[e]}register(e){return this.providers.has(e.provider.id)&&console.warn(`Provider with ID "${e.provider.id}" is already registered`),this.providers.set(e.provider.id,e),()=>{this.providers.get(e.provider.id)===e&&this.providers.delete(e.provider.id)}}getAll(){return Array.from(this.providers.values())}getById(e){return this.providers.get(e)}getByKind(e){return this.getAll().filter(({provider:r})=>r.kind===e)}};function Oe(t){let e=t.filter(r=>!!r);return r=>async(n,i)=>{let a=[],o=d=>{a.push(d)},s=async(d,p,m)=>{if(d>=e.length)return r(p,m);let b=e[d],I=async(g,f)=>s(d+1,g,f),v={...m,addDisposer:o};return b(p,v,I)},l={...i,addDisposer:o};return{result:await s(0,n,l),dispose:async()=>{for(let d=a.length-1;d>=0;d--)try{await a[d]()}catch(p){console.error("Error in disposer:",p)}a.length=0}}}}function ro({enable:t=!0}){return async(r,n,i)=>{if(!t)return i(r,n);console.group("[GENERATION]"),console.log("Generating with input:",JSON.stringify(r,null,2));let a,o=Date.now();try{return a=await i(r,n),a}finally{a!=null&&(console.log(`Generation took ${Date.now()-o}ms`),console.log("Generation result:",JSON.stringify(a,null,2))),console.groupEnd()}}}var we=ro;var no="ly.img.ai",ke="ly.img.ai.temp";async function mt(t,e){return t.engine.asset.findAllSources().includes(ke)||t.engine.asset.addLocalSource(ke),t.engine.asset.apply(ke,e)}function io(t){return`${no}.${t}`}function ft(t,e="We encountered an unknown error while generating the asset. Please try again."){if(t===null)return e;if(t instanceof Error)return t.message;if(typeof t=="object"){let r=t;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:e}return typeof t=="string"?t:String(t)||e}function Se(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}function oo(t){return new Promise((e,r)=>{try{let n=document.createElement("video");n.style.display="none",n.addEventListener("loadedmetadata",()=>{n.duration===1/0?(n.currentTime=1e101,setTimeout(()=>{n.currentTime=0,e(n.duration),document.body.removeChild(n)},50)):(e(n.duration),document.body.removeChild(n))}),n.addEventListener("error",()=>{document.body.removeChild(n),r(new Error(`Failed to load video from ${t}`))}),n.src=t,document.body.appendChild(n)}catch(n){r(n)}})}function Ce(t,e=0,r="image/jpeg",n=.8){return new Promise((i,a)=>{try{let o=document.createElement("video");o.crossOrigin="anonymous",o.style.display="none",o.addEventListener("loadedmetadata",()=>{o.currentTime=Math.min(e,o.duration),o.addEventListener("seeked",()=>{let s=document.createElement("canvas");s.width=o.videoWidth,s.height=o.videoHeight;let l=s.getContext("2d");if(!l){document.body.removeChild(o),a(new Error("Failed to create canvas context"));return}l.drawImage(o,0,0,s.width,s.height);try{let u=s.toDataURL(r,n);document.body.removeChild(o),i(u)}catch(u){document.body.removeChild(o),a(new Error(`Failed to create thumbnail: ${u instanceof Error?u.message:String(u)}`))}},{once:!0})}),o.addEventListener("error",()=>{document.body.removeChild(o),a(new Error(`Failed to load video from ${t}`))}),o.src=t,document.body.appendChild(o)}catch(o){a(o)}})}function xe(t){return t?t.replace(/[_-]/g," ").replace(/([A-Z])/g," $1").trim().split(" ").filter(e=>e.length>0).map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join(" "):""}function W(t){return typeof t=="object"&&t!==null&&"next"in t&&"return"in t&&"throw"in t&&typeof t.next=="function"&&typeof t.return=="function"&&typeof t.throw=="function"&&Symbol.asyncIterator in t&&typeof t[Symbol.asyncIterator]=="function"}function V(t){return t instanceof Error&&t.name==="AbortError"}function Ae(t,e,r){let n=`${e}.iconSetAdded`;t.ui.experimental.hasGlobalStateValue(n)||(t.ui.addIconSet(e,r),t.ui.experimental.setGlobalStateValue(n,!0))}function ao(t){return async(r,n,i)=>{let a=await i(r,n);return W(a)?a:await t(a)}}var so=ao;function lo(t,e){let r={...t};if(!e)return r;for(let[n,i]of Object.entries(e))i===!1||i===null||i===void 0?delete r[n]:i===!0?n in t||(r[n]=!0):r[n]=i;return r}var Re=new Map,ae=class{constructor(e,r,n){this.db=null;this.dbVersion=1;this.isInitializing=!1;this.initPromise=null;this.instanceId=e,this.dbName=r??"ly.img.ai.rateLimit",this.storeName=n??"rateLimits"}async initialize(){if(!this.db)return this.isInitializing?this.initPromise:(this.isInitializing=!0,this.initPromise=new Promise((e,r)=>{try{let n=indexedDB.open(this.dbName,this.dbVersion);n.onerror=i=>{this.isInitializing=!1,console.error("Failed to open IndexedDB for rate limiting:",i),r(new Error("Failed to open IndexedDB for rate limiting"))},n.onupgradeneeded=i=>{let a=i.target.result;a.objectStoreNames.contains(this.storeName)||a.createObjectStore(this.storeName,{keyPath:"id"})},n.onsuccess=i=>{this.db=i.target.result,this.isInitializing=!1,e()}}catch(n){this.isInitializing=!1,console.error("Error initializing IndexedDB:",n),r(n)}}),this.initPromise)}async getTracker(e){try{await this.initialize();let n=`${typeof this.instanceId=="symbol"?this.instanceId.description||"":this.instanceId}_${e}`;return await new Promise((i,a)=>{let l=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).get(n);l.onsuccess=()=>{l.result?i(l.result.data):i(null)},l.onerror=()=>{console.error(`Failed to get tracker for key ${n}:`,l.error),a(l.error)}})}catch(r){return console.error("Error getting tracker from IndexedDB:",r),Promise.reject(r)}}async saveTracker(e,r){try{await this.initialize();let i=`${typeof this.instanceId=="symbol"?this.instanceId.description||"":this.instanceId}_${e}`;return await new Promise((a,o)=>{let s=this.db.transaction(this.storeName,"readwrite");s.objectStore(this.storeName).put({id:i,data:r}),s.oncomplete=()=>{a()},s.onerror=()=>{console.error(`Failed to save tracker for key ${i}:`,s.error),o(s.error)}})}catch(n){return console.error("Error saving tracker to IndexedDB:",n),Promise.reject(n)}}static isAvailable(){return typeof indexedDB<"u"}close(){this.db&&(this.db.close(),this.db=null)}};function uo(t){let{maxRequests:e,timeWindowMs:r,keyFn:n=()=>"global",onRateLimitExceeded:i,dbName:a}=t,s=`rate-limit-middleware-${e}-${r}`,l=ae.isAvailable(),u=l?new ae(s,a):null;Re.has(s)||Re.set(s,{});let c=Re.get(s);return async(p,m,b)=>{if(typeof t.disable=="function"?t.disable():t.disable)return b(p,m);let I=typeof n=="string"?n:n(p,m),v=Date.now(),g;if(l&&u)try{let f=await u.getTracker(I);f?g=f:g={timestamps:[],lastCleanup:v}}catch(f){console.error("IndexedDB access failed, using in-memory fallback:",f),c[I]||(c[I]={timestamps:[],lastCleanup:v}),g=c[I]}else c[I]||(c[I]={timestamps:[],lastCleanup:v}),g=c[I];if(v-g.lastCleanup>r&&(g.timestamps=g.timestamps.filter(f=>v-f<r),g.lastCleanup=v),g.timestamps.length>=e){let f=Math.min(...g.timestamps),k=Math.max(0,r-(v-f));if(i){let y={key:I,currentCount:g.timestamps.length,maxRequests:e,timeWindowMs:r,remainingTimeMs:k};if(!await i(p,m,y))throw new DOMException("Operation aborted: Rate limit exceeded","AbortError")}else throw new Error("Rate limit exceeded. Please try again later.")}if(g.timestamps.push(v),l&&u)try{await u.saveTracker(I,g)}catch(f){console.error("Failed to save tracker to IndexedDB:",f),c[I]=g}else c[I]=g;return b(p,m)}}var co=uo;function po(t,e,r){let n="ai-plugin-version",i="ai-plugin-version-warning-shown";try{let a=t.ui.experimental.getGlobalStateValue(n);a?a!==r&&(t.ui.experimental.getGlobalStateValue(i,!1)||(console.warn(`[IMG.LY AI Plugins] Version mismatch detected!
Plugin "${e}" 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.`),t.ui.experimental.setGlobalStateValue(i,!0))):t.ui.experimental.setGlobalStateValue(n,r)}catch(a){console.debug("[IMG.LY AI Plugins] Could not check plugin version consistency:",a)}}function go(t){let{cesdk:e,panelId:r}=t;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 n=`${r}.dock`;e.ui.registerComponent(n,({builder:i})=>{let a=e.ui.isPanelOpen(r);i.Button(`${r}.dock.button`,{label:`${r}.dock.label`,isSelected:a,icon:"@imgly/Sparkle",onClick:()=>{e.ui.findAllPanels().forEach(o=>{o.startsWith("ly.img.ai.")&&e.ui.closePanel(o),!a&&o==="//ly.img.panel/assetLibrary"&&e.ui.closePanel(o)}),a?e.ui.closePanel(r):e.ui.openPanel(r)}})})}var mo=go;function fo(){return({engine:t})=>{let e=t.block.findAllSelected();if(e==null||e.length!==1)return!1;let[r]=e;if(!t.block.supportsFill(r)||t.block.getKind(r)==="sticker"||!["//ly.img.ubq/graphic","//ly.img.ubq/page"].includes(t.block.getType(r)))return!1;let n=t.block.getFill(r);return t.block.getType(n)==="//ly.img.ubq/fill/image"}}var yo=fo;function bo(t,e){let{cesdk:r,provider:n,getInput:i}=e;console.error("Generation failed:",t),ho(r,n.output.notification,()=>({input:i?.().input,error:t}))||r.ui.showNotification({type:"error",message:ft(t)})}function ho(t,e,r){let n=e?.error;if(n==null||!(typeof n.show=="function"?n.show(r()):n.show))return!1;let a=typeof n.message=="function"?n.message(r()):n.message??"common.ai-generation.failed",o=n.action!=null?{label:typeof n.action.label=="function"?n.action.label(r()):n.action.label,onClick:()=>{n?.action?.onClick(r())}}:void 0;return t.ui.showNotification({type:"error",message:a,action:o}),!0}var Ee=bo;var Io="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIzIiBoZWlnaHQ9IjMyMyIgdmlld0JveD0iMCAwIDMyMyAzMjMiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIzMjMiIGhlaWdodD0iMzIzIiBmaWxsPSIjRTlFQkVEIi8+CjxnIG9wYWNpdHk9IjAuMyI+CjxwYXRoIGQ9Ik0xMTYgMTg0VjE5MS41QzExNiAxOTkuNzg0IDEyMi43MTYgMjA2LjUgMTMxIDIwNi41SDE5MUMxOTkuMjg0IDIwNi41IDIwNiAxOTkuNzg0IDIwNiAxOTEuNVYxMzEuNUMyMDYgMTIzLjIxNiAxOTkuMjg0IDExNi41IDE5MSAxMTYuNUwxOTAuOTk1IDEyNi41QzE5My43NTcgMTI2LjUgMTk2IDEyOC43MzkgMTk2IDEzMS41VjE5MS41QzE5NiAxOTQuMjYxIDE5My43NjEgMTk2LjUgMTkxIDE5Ni41SDEzMUMxMjguMjM5IDE5Ni41IDEyNiAxOTQuMjYxIDEyNiAxOTEuNVYxODRIMTE2WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTY2LjQ5NCAxMDUuOTI0QzE2NS44NjkgMTA0LjM0MiAxNjMuNjI5IDEwNC4zNDIgMTYzLjAwNSAxMDUuOTI0TDE1OS43NDUgMTE0LjE5MUMxNTkuNTU0IDExNC42NzQgMTU5LjE3MiAxMTUuMDU3IDE1OC42ODggMTE1LjI0N0wxNTAuNDIyIDExOC41MDhDMTQ4LjgzOSAxMTkuMTMyIDE0OC44MzkgMTIxLjM3MiAxNTAuNDIyIDEyMS45OTZMMTU4LjY4OCAxMjUuMjU2QzE1OS4xNzIgMTI1LjQ0NyAxNTkuNTU0IDEyNS44MjkgMTU5Ljc0NSAxMjYuMzEzTDE2My4wMDUgMTM0LjU3OUMxNjMuNjI5IDEzNi4xNjIgMTY1Ljg2OSAxMzYuMTYyIDE2Ni40OTQgMTM0LjU3OUwxNjkuNzU0IDEyNi4zMTNDMTY5Ljk0NCAxMjUuODI5IDE3MC4zMjcgMTI1LjQ0NyAxNzAuODEgMTI1LjI1NkwxNzkuMDc3IDEyMS45OTZDMTgwLjY2IDEyMS4zNzIgMTgwLjY2IDExOS4xMzIgMTc5LjA3NyAxMTguNTA4TDE3MC44MSAxMTUuMjQ3QzE3MC4zMjcgMTE1LjA1NyAxNjkuOTQ0IDExNC42NzQgMTY5Ljc1NCAxMTQuMTkxTDE2Ni40OTQgMTA1LjkyNFoiIGZpbGw9IiM4RjhGOEYiLz4KPHBhdGggZD0iTTEzMy4wMDUgMTI4LjQyNEMxMzMuNjI5IDEyNi44NDIgMTM1Ljg2OSAxMjYuODQyIDEzNi40OTQgMTI4LjQyNEwxNDEuODc1IDE0Mi4wN0MxNDIuMDY2IDE0Mi41NTMgMTQyLjQ0OCAxNDIuOTM1IDE0Mi45MzIgMTQzLjEyNkwxNTYuNTc3IDE0OC41MDhDMTU4LjE2IDE0OS4xMzIgMTU4LjE2IDE1MS4zNzIgMTU2LjU3NyAxNTEuOTk2TDE0Mi45MzIgMTU3LjM3OEMxNDIuNDQ4IDE1Ny41NjggMTQyLjA2NiAxNTcuOTUxIDE0MS44NzUgMTU4LjQzNEwxMzYuNDk0IDE3Mi4wNzlDMTM1Ljg2OSAxNzMuNjYyIDEzMy42MjkgMTczLjY2MiAxMzMuMDA1IDE3Mi4wNzlMMTI3LjYyMyAxNTguNDM0QzEyNy40MzMgMTU3Ljk1MSAxMjcuMDUgMTU3LjU2OCAxMjYuNTY3IDE1Ny4zNzhMMTEyLjkyMiAxNTEuOTk2QzExMS4zMzkgMTUxLjM3MiAxMTEuMzM5IDE0OS4xMzIgMTEyLjkyMiAxNDguNTA4TDEyNi41NjcgMTQzLjEyNkMxMjcuMDUgMTQyLjkzNSAxMjcuNDMzIDE0Mi41NTMgMTI3LjYyMyAxNDIuMDdMMTMzLjAwNSAxMjguNDI0WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTk1Ljk5OSAxODQuMDA0VjE5MS41MDJDMTk1Ljk5OSAxOTQuMjYzIDE5My43NjEgMTk2LjUwMiAxOTAuOTk5IDE5Ni41MDJIMTQ3LjY2OEwxNzIuODc5IDE1OC42ODRDMTc0LjM2MyAxNTYuNDU4IDE3Ny42MzUgMTU2LjQ1OCAxNzkuMTIgMTU4LjY4NEwxOTUuOTk5IDE4NC4wMDRaIiBmaWxsPSIjOEY4RjhGIi8+CjwvZz4KPC9zdmc+Cg==",se=Io;function vo(t,e,r){switch(e){case"image":return Oo(t,r[e]);case"video":return wo(t,r[e]);case"sticker":return ko(t,r[e]);default:throw new Error(`Unsupported output kind for creating placeholder block: ${e}`)}}function Oo(t,e){let r=e.width,n=e.height;return{id:t,meta:{previewUri:se,fillType:"//ly.img.ubq/fill/image",kind:"image",width:r,height:n}}}function wo(t,e){let r=e.width,n=e.height;return{id:t,label:e.label,meta:{previewUri:se,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:e.duration.toString(),width:r,height:n}}}function ko(t,e){let r=e.width,n=e.height;return{id:t,meta:{previewUri:se,fillType:"//ly.img.ubq/fill/image",kind:"sticker",width:r,height:n}}}var yt=vo;async function So(t,e,r,n){switch(e){case"image":{if(n.kind!=="image")throw new Error(`Output kind does not match the expected type: ${n.kind} (expected: image)`);return Co(t,r[e],n)}case"video":{if(n.kind!=="video")throw new Error(`Output kind does not match the expected type: ${n.kind} (expected: video)`);return xo(t,r[e],n)}case"audio":{if(n.kind!=="audio")throw new Error(`Output kind does not match the expected type: ${n.kind} (expected: audio)`);return Ao(t,r[e],n)}case"sticker":{if(n.kind!=="sticker")throw new Error(`Output kind does not match the expected type: ${n.kind} (expected: sticker)`);return Ro(t,r[e],n)}default:throw new Error(`Unsupported output kind for creating placeholder block: ${e}`)}}function Co(t,e,r){let n=e.width,i=e.height;return{id:t,label:e.label,meta:{uri:r.url,thumbUri:r.url,fillType:"//ly.img.ubq/fill/image",kind:"image",width:n,height:i},payload:{sourceSet:[{uri:r.url,width:n,height:i}]}}}async function xo(t,e,r){let n=e.width,i=e.height,a=await Ce(r.url,0);return{id:t,label:e.label,meta:{uri:r.url,thumbUri:a,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:e.duration.toString(),width:n,height:i}}}function Ao(t,e,r){return{id:t,label:e.label,meta:{uri:r.url,thumbUri:r.thumbnailUrl,blockType:"//ly.img.ubq/audio",mimeType:"audio/x-m4a",duration:r.duration.toString()}}}function Ro(t,e,r){let n=e.width,i=e.height;return{id:t,label:e.label,meta:{uri:r.url,thumbUri:r.url,fillType:"//ly.img.ubq/fill/image",kind:"sticker",width:n,height:i},payload:{sourceSet:[{uri:r.url,width:n,height:i}]}}}var Pe=So;function Eo(t){switch(t.userFlow){case"placeholder":return Mo(t);case"generation-only":return Po(t);default:throw new Error(`Unknown user flow: ${t.userFlow}. Expected 'placeholder' or 'generation-only'.`)}}function Po(t){let{cesdk:e,abortSignal:r}=t;return async n=>{try{let i=t.kind,a=await t.getBlockInput(n);if(P(e,r))return{status:"aborted"};let o=await t.generate(n,{middlewares:[...t.middlewares??[]],debug:t.debug,dryRun:t.dryRun,abortSignal:r});if(P(e,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(P(e,r))return{status:"aborted"};if(t.historyAssetSourceId!=null){let s=Se(),l=await Pe(s,i,a,o.output),u={...l,id:`${Date.now()}-${l.id}`,label:l.label!=null?{en:l.label}:{},tags:{}};e.engine.asset.addAssetToSource(t.historyAssetSourceId,u)}else t.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(i){return{status:"error",message:i instanceof Error?i.message:String(i)}}}}function Mo(t){let{cesdk:e,abortSignal:r}=t,n;return async i=>{try{let a=t.kind,o=await t.getBlockInput(i);if(P(e,r))return{status:"aborted"};let s=Se(),l=yt(s,a,o);if(n=await mt(e,l),P(e,r,n))return{status:"aborted"};if(n!=null&&t.kind==="video"){let d=e.engine.block.getPositionX(n),p=e.engine.block.getPositionY(n),m=e.engine.block.duplicate(n);e.engine.block.setPositionX(m,d),e.engine.block.setPositionY(m,p),e.engine.block.destroy(n),n=m}if(n==null)throw new Error("Could not create placeholder block");e.engine.block.setState(n,{type:"Pending",progress:0});let u=await t.generate(i,{middlewares:[...t.middlewares??[]],debug:t.debug,dryRun:t.dryRun,abortSignal:r});if(P(e,r,n))return{status:"aborted"};if(u.status!=="success")return u;if(u.type==="async")throw new Error("Async generation is not supported in this context yet.");if(!e.engine.block.isValid(n))return{status:"aborted",message:"Placeholder block was destroyed before generation completed."};let c=await Pe(s,a,o,u.output);if(P(e,r,n))return{status:"aborted"};if(t.debug&&console.log("Updating placeholder in scene:",JSON.stringify(c,void 0,2)),await e.engine.asset.defaultApplyAssetToBlock(c,n),P(e,r,n))return{status:"aborted"};if(t.historyAssetSourceId!=null){let d={...c,id:`${Date.now()}-${c.id}`,label:c.label!=null?{en:c.label}:{},tags:{}};e.engine.asset.addAssetToSource(t.historyAssetSourceId,d)}return e.engine.block.isValid(n)&&e.engine.block.setState(n,{type:"Ready"}),u}catch(a){return n!=null&&e.engine.block.isValid(n)&&(V(a)?e.engine.block.destroy(n):e.engine.block.setState(n,{type:"Error",error:"Unknown"})),{status:"error",message:a instanceof Error?a.message:String(a)}}}}function P(t,e,r){return e.aborted?(r!=null&&t.engine.block.isValid(r)&&t.engine.block.destroy(r),!0):!1}var bt=Eo;function _(t){return`${t}.generating`}function ht(t){return`${t}.abort`}function Do(t,e,r,n,i,a,o){let{builder:s,experimental:l}=t,{cesdk:u,includeHistoryLibrary:c=!0}=a,{id:d,output:{abortable:p}}=e,m=l.global(ht(d),()=>{}),b=l.global(_(d),!1),I,v=b.value&&p,g=()=>{v&&(m.value(),b.setValue(!1),m.setValue(()=>{}))},f;if(a.requiredInputs!=null&&a.requiredInputs.length>0){let y=n();f=a.requiredInputs.every(h=>!y.input[h])}let k=l.global(`${d}.confirmationDialogId`,void 0);s.Section(`${d}.generate.section`,{children:()=>{s.Button(`${d}.generate`,{label:["common.generate",`panel.${d}.generate`],isLoading:b.value,color:"accent",isDisabled:f,suffix:v?{icon:"@imgly/Cross",color:"danger",tooltip:[`panel.${d}.abort`,"common.cancel"],onClick:()=>{let y=u.ui.showDialog({type:"warning",content:"panel.ly.img.ai.generation.confirmCancel.content",cancel:{label:"common.close",onClick:({id:h})=>{u.ui.closeDialog(h),k.setValue(void 0)}},actions:{label:"panel.ly.img.ai.generation.confirmCancel.confirm",color:"danger",onClick:({id:h})=>{g(),u.ui.closeDialog(h),k.setValue(void 0)}}});k.setValue(y)}}:void 0,onClick:async()=>{I=new AbortController;let y=I.signal;await(async()=>{try{b.setValue(!0),m.setValue(()=>{o.debug&&console.log("Aborting generation"),I?.abort()});let O=await bt({kind:e.kind,generate:r,historyAssetSourceId:a.historyAssetSourceId,userFlow:a.createPlaceholderBlock?"placeholder":"generation-only",getBlockInput:i,abortSignal:y,cesdk:u,debug:o.debug,dryRun:o.dryRun})(n().input);if(O.status==="aborted")return;if(O.status==="error"){Ee(O.message,{cesdk:u,provider:e,getInput:n});return}if(O.status==="success"&&O.type==="sync"){let w=e.output.notification;Ko(u,w,()=>({input:n().input,output:O.output}))}}catch(O){if(V(O))return;Ee(O,{cesdk:u,provider:e,getInput:n})}finally{I=void 0,b.setValue(!1),m.setValue(()=>{}),k.value!=null&&(u.ui.closeDialog(k.value),k.setValue(void 0))}})()}}),e.output.generationHintText!=null&&s.Text(`${d}.generation-hint`,{align:"center",content:e.output.generationHintText})}}),c&&a.historyAssetLibraryEntryId!=null&&s.Library(`${d}.history.library`,{entries:[a.historyAssetLibraryEntryId]})}function Ko(t,e,r){let n=e?.success;if(n==null||!(typeof n.show=="function"?n.show(r()):n.show))return!1;let a=typeof n.message=="function"?n.message(r()):n.message??"common.ai-generation.success",o=n.action!=null?{label:typeof n.action.label=="function"?n.action.label(r()):n.action.label,onClick:()=>{n?.action?.onClick(r())}}:void 0;return t.ui.showNotification({type:"success",message:a,action:o,duration:n.duration}),!0}var le=Do;async function To({options:t,provider:e,panelInput:r,config:n},i){if(r==null)return;let{cesdk:a}=t,{id:o}=e,s=r.render;return u=>{let{state:c}=u,d=c(_(o),{isGenerating:!1,abort:()=>{}}).value.isGenerating,{getInput:p,getBlockInput:m}=s(u,{cesdk:a,isGenerating:d});return le(u,e,i,p,m,{...t,includeHistoryLibrary:r.includeHistoryLibrary??!0,createPlaceholderBlock:r.userFlow==="placeholder"},n),p}}var It=To;function Me(t,e){if(!e.startsWith("#/"))throw new Error(`External references are not supported: ${e}`);let r=e.substring(2).split("/"),n=t;for(let i of r){if(n==null)throw new Error(`Invalid reference path: ${e}`);n=n[i]}if(n===void 0)throw new Error(`Reference not found: ${e}`);return n}function J(t,e,r=new Set){if(e==null||r.has(e))return e;if(r.add(e),e.$ref&&typeof e.$ref=="string"){let n=Me(t,e.$ref),a={...J(t,n,r)};for(let o in e)Object.prototype.hasOwnProperty.call(e,o)&&o!=="$ref"&&(a[o]=J(t,e[o],r));return a}if(Array.isArray(e))return e.map(n=>J(t,n,r));if(typeof e=="object"){let n={};for(let i in e)Object.prototype.hasOwnProperty.call(e,i)&&(n[i]=J(t,e[i],r));return n}return e}function De(t){return J(t,{...t})}function vt(t,e=!1){let r=s=>(e&&console.log(`OpenAPI Schema validation failed: ${s}`),!1);if(typeof t!="object"||t===null)return r(`Input is ${t===null?"null":typeof t}, not an object`);let n=t;if(!(typeof n.type=="string"||Array.isArray(n.enum)||typeof n.properties=="object"||typeof n.items=="object"||typeof n.allOf=="object"||typeof n.anyOf=="object"||typeof n.oneOf=="object"||typeof n.not=="object"))return r("Missing required schema-defining properties (type, enum, properties, items, allOf, anyOf, oneOf, not)");if(n.type!==void 0){let s=["string","number","integer","boolean","array","object","null"];if(typeof n.type=="string"){if(!s.includes(n.type))return r(`Invalid type: ${n.type}. Must be one of ${s.join(", ")}`)}else if(Array.isArray(n.type)){for(let l of n.type)if(typeof l!="string"||!s.includes(l))return r(`Array of types contains invalid value: ${l}. Must be one of ${s.join(", ")}`)}else return r(`Type must be a string or array of strings, got ${typeof n.type}`)}if(n.items!==void 0&&(typeof n.items!="object"||n.items===null))return r(`Items must be an object, got ${n.items===null?"null":typeof n.items}`);if(n.properties!==void 0&&(typeof n.properties!="object"||n.properties===null))return r(`Properties must be an object, got ${n.properties===null?"null":typeof n.properties}`);let a=["allOf","anyOf","oneOf"];for(let s of a)if(n[s]!==void 0){if(!Array.isArray(n[s]))return r(`${s} must be an array, got ${typeof n[s]}`);for(let l=0;l<n[s].length;l++){let u=n[s][l];if(typeof u!="object"||u===null)return r(`Item ${l} in ${s} must be an object, got ${u===null?"null":typeof u}`)}}if(n.not!==void 0&&(typeof n.not!="object"||n.not===null))return r(`'not' must be an object, got ${n.not===null?"null":typeof n.not}`);if(n.additionalProperties!==void 0&&typeof n.additionalProperties!="boolean"&&(typeof n.additionalProperties!="object"||n.additionalProperties===null))return r(`additionalProperties must be a boolean or an object, got ${n.additionalProperties===null?"null":typeof n.additionalProperties}`);if(n.format!==void 0&&typeof n.format!="string")return r(`format must be a string, got ${typeof n.format}`);let o=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf"];for(let s of o)if(n[s]!==void 0&&typeof n[s]!="number")return r(`${s} must be a number, got ${typeof n[s]}`);if(n.minLength!==void 0&&(typeof n.minLength!="number"||n.minLength<0))return r(`minLength must be a non-negative number, got ${typeof n.minLength=="number"?n.minLength:typeof n.minLength}`);if(n.maxLength!==void 0&&(typeof n.maxLength!="number"||n.maxLength<0))return r(`maxLength must be a non-negative number, got ${typeof n.maxLength=="number"?n.maxLength:typeof n.maxLength}`);if(n.pattern!==void 0&&typeof n.pattern!="string")return r(`pattern must be a string, got ${typeof n.pattern}`);if(n.minItems!==void 0&&(typeof n.minItems!="number"||n.minItems<0))return r(`minItems must be a non-negative number, got ${typeof n.minItems=="number"?n.minItems:typeof n.minItems}`);if(n.maxItems!==void 0&&(typeof n.maxItems!="number"||n.maxItems<0))return r(`maxItems must be a non-negative number, got ${typeof n.maxIt