@imgly/plugin-ai-audio-generation-web 0.2.2 → 0.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  var qt=class{constructor(e,t,r){this.assetStoreName="assets",this.blobStoreName="blobs",this.db=null,this.id=e,this.engine=t,this.dbName=r?.dbName??`ly.img.assetSource/${e}`,this.dbVersion=r?.dbVersion??1}async initialize(){if(!this.db)return new Promise((e,t)=>{let r=indexedDB.open(this.dbName,this.dbVersion);r.onerror=i=>{t(new Error(`Failed to open IndexedDB: ${i.target.error}`))},r.onupgradeneeded=i=>{let n=i.target.result;n.objectStoreNames.contains(this.assetStoreName)||n.createObjectStore(this.assetStoreName,{keyPath:"id"}),n.objectStoreNames.contains(this.blobStoreName)||n.createObjectStore(this.blobStoreName,{keyPath:"id"})},r.onsuccess=i=>{this.db=i.target.result,e()}})}close(){this.db&&(this.db.close(),this.db=null)}async findAssets(e){if(await this.initialize(),!this.db)throw new Error("Database not initialized");try{let t=(await this.getAllAssets("asc")).reduce((u,l)=>{let c=e.locale??"en",d="",p=[];l.label!=null&&typeof l.label=="object"&&l.label[c]&&(d=l.label[c]),l.tags!=null&&typeof l.tags=="object"&&l.tags[c]&&(p=l.tags[c]);let g={...l,label:d,tags:p};return this.filterAsset(g,e)&&u.push(g),u},[]);t=await this.restoreBlobUrls(t),t=this.sortAssets(t,e);let{page:r,perPage:i}=e,n=r*i,o=n+i,a=t.slice(n,o),s=o<t.length?r+1:void 0;return{assets:a,currentPage:r,nextPage:s,total:t.length}}catch(t){console.error("Error finding assets:",t);return}}async getGroups(){if(await this.initialize(),!this.db)throw new Error("Database not initialized");return new Promise((e,t)=>{let r=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).getAll();r.onsuccess=()=>{let i=new Set;r.result.forEach(o=>{o.groups&&Array.isArray(o.groups)&&o.groups.forEach(a=>i.add(a))});let n=[...i];e(n)},r.onerror=()=>{t(new Error(`Failed to get groups: ${r.error}`))}})}addAsset(e){this.initialize().then(async()=>{if(!this.db)throw new Error("Database not initialized");let t=this.db.transaction(this.assetStoreName,"readwrite"),r=t.objectStore(this.assetStoreName),i=new Set;O(e,o=>{i.add(o)}),setTimeout(()=>{this.storeBlobUrls([...i])});let n={...e,meta:{...e.meta,insertedAt:e.meta?.insertedAt||Date.now()}};r.put(n),t.onerror=()=>{console.error(`Failed to add asset: ${t.error}`)}}).catch(t=>{console.error("Error initializing database:",t)})}async removeAsset(e){let t=await this.getAsset(e);return this.initialize().then(()=>{if(!this.db)throw new Error("Database not initialized");let r=this.db.transaction(this.assetStoreName,"readwrite");r.objectStore(this.assetStoreName).delete(e),r.oncomplete=()=>{O(t,i=>{this.removeBlob(i)}),this.engine.asset.assetSourceContentsChanged(this.id)},r.onerror=()=>{console.error(`Failed to remove asset: ${r.error}`)}}).catch(r=>{console.error("Error initializing database:",r)})}async removeBlob(e){return this.initialize().then(()=>{if(!this.db)throw new Error("Database not initialized");let t=this.db.transaction(this.blobStoreName,"readwrite");t.objectStore(this.blobStoreName).delete(e),t.onerror=()=>{console.error(`Failed to remove blob: ${t.error}`)}}).catch(t=>{console.error("Error initializing database:",t)})}async getAllAssets(e="desc"){return new Promise((t,r)=>{let i=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).getAll();i.onsuccess=()=>{let n=i.result;n.sort((o,a)=>{let s=o.meta?.insertedAt||o._insertedAt||Date.now(),u=a.meta?.insertedAt||a._insertedAt||Date.now();return e==="asc"?s-u:u-s}),t(n)},i.onerror=()=>{r(new Error(`Failed to get assets: ${i.error}`))}})}async getAsset(e){return new Promise((t,r)=>{let i=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).get(e);i.onsuccess=()=>{t(i.result)},i.onerror=()=>{r(new Error(`Failed to get blob: ${i.error}`))}})}async getBlob(e){return new Promise((t,r)=>{let i=this.db.transaction(this.blobStoreName,"readonly").objectStore(this.blobStoreName).get(e);i.onsuccess=()=>{t(i.result)},i.onerror=()=>{r(new Error(`Failed to get blob: ${i.error}`))}})}async createBlobUrlFromStore(e){let t=await this.getBlob(e);return t!=null?URL.createObjectURL(t.blob):e}async storeBlobUrls(e){let t={};return await Promise.all(e.map(async r=>{let i=await(await fetch(r)).blob();t[r]=i})),this.initialize().then(async()=>{if(!this.db)throw new Error("Database not initialized");let r=this.db.transaction(this.blobStoreName,"readwrite"),i=r.objectStore(this.blobStoreName);Object.entries(t).forEach(([n,o])=>{let a={id:n,blob:o};i.put(a)}),r.onerror=()=>{console.error(`Failed to add blobs: ${r.error}`)}}).catch(r=>{console.error("Error initializing database:",r)})}async restoreBlobUrls(e){let t={},r=new Set;return O(e,i=>{r.add(i)}),await Promise.all([...r].map(async i=>{let n=await this.createBlobUrlFromStore(i);t[i]=n})),O(e,i=>t[i]??i)}filterAsset(e,t){let{query:r,tags:i,groups:n,excludeGroups:o}=t;if(r&&r.trim()!==""){let a=r.trim().toLowerCase().split(" "),s=e.label?.toLowerCase()??"",u=e.tags?.map(l=>l.toLowerCase())??[];if(!a.every(l=>s.includes(l)||u.some(c=>c.includes(l))))return!1}if(i){let a=Array.isArray(i)?i:[i];if(a.length>0&&(!e.tags||!a.every(s=>e.tags?.includes(s))))return!1}return!(n&&n.length>0&&(!e.groups||!n.some(a=>e.groups?.includes(a)))||o&&o.length>0&&e.groups&&e.groups.some(a=>o.includes(a)))}sortAssets(e,t){let{sortingOrder:r,sortKey:i,sortActiveFirst:n}=t,o=[...e];return!r||r==="None"||(i?o.sort((a,s)=>{let u,l;return i==="id"?(u=a.id,l=s.id):(u=a.meta?.[i]??null,l=s.meta?.[i]??null),u==null?r==="Ascending"?-1:1:l==null?r==="Ascending"?1:-1:typeof u=="string"&&typeof l=="string"?r==="Ascending"?u.localeCompare(l):l.localeCompare(u):r==="Ascending"?u<l?-1:u>l?1:0:u>l?-1:u<l?1:0}):r==="Descending"&&o.reverse(),n&&o.sort((a,s)=>a.active&&!s.active?-1:!a.active&&s.active?1:0)),o}};function O(e,t,r=""){if(e===null||typeof e!="object")return e;if(Array.isArray(e)){for(let i=0;i<e.length;i++){let n=r?`${r}[${i}]`:`[${i}]`;if(typeof e[i]=="string"&&e[i].startsWith("blob:")){let o=t(e[i],n);typeof o=="string"&&(e[i]=o)}else e[i]=O(e[i],t,n)}return e}for(let i in e)if(Object.prototype.hasOwnProperty.call(e,i)){let n=e[i],o=r?`${r}.${i}`:i;if(typeof n=="string"&&n.startsWith("blob:")){let a=t(n,o);typeof a=="string"&&(e[i]=a)}else e[i]=O(n,t,o)}return e}var Zt=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:o}=e,a=n*o,s=a+o,u=i.slice(a,s),l=s<i.length?n+1:void 0;return{assets:u,currentPage:n,nextPage:l,total:i.length}}catch(t){console.error("Error finding assets:",t);return}}async getGroups(){let e=this.assetSourceIds.map(i=>this.cesdk.engine.asset.getGroups(i)),t=await Promise.all(e),r=new Set;return t.forEach(i=>{i.forEach(n=>r.add(n))}),Array.from(r)}addAsset(e){throw new Error("AggregatedAssetSource does not support adding assets")}removeAsset(e){throw new Error("AggregatedAssetSource does not support removing assets")}};var Yt=typeof global=="object"&&global&&global.Object===Object&&global,et=Yt,Qt=typeof self=="object"&&self&&self.Object===Object&&self,Wt=et||Qt||Function("return this")(),A=Wt,Kt=A.Symbol,$=Kt,tt=Object.prototype,Jt=tt.hasOwnProperty,Xt=tt.toString,q=$?$.toStringTag:void 0;function er(e){var t=Jt.call(e,q),r=e[q];try{e[q]=void 0;var i=!0}catch{}var n=Xt.call(e);return i&&(t?e[q]=r:delete e[q]),n}var tr=er,rr=Object.prototype,ir=rr.toString;function nr(e){return ir.call(e)}var or=nr,ar="[object Null]",sr="[object Undefined]",ze=$?$.toStringTag:void 0;function lr(e){return e==null?e===void 0?sr:ar:ze&&ze in Object(e)?tr(e):or(e)}var J=lr;function ur(e){return e!=null&&typeof e=="object"}var Ae=ur,pu=Array.isArray;function cr(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var rt=cr,dr="[object AsyncFunction]",pr="[object Function]",gr="[object GeneratorFunction]",fr="[object Proxy]";function hr(e){if(!rt(e))return!1;var t=J(e);return t==pr||t==gr||t==dr||t==fr}var mr=hr,br=A["__core-js_shared__"],ge=br,Re=function(){var e=/[^.]+$/.exec(ge&&ge.keys&&ge.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function yr(e){return!!Re&&Re in e}var vr=yr,wr=Function.prototype,kr=wr.toString;function Ir(e){if(e!=null){try{return kr.call(e)}catch{}try{return e+""}catch{}}return""}var M=Ir,Ar=/[\\^$.*+?()[\]{}|]/g,xr=/^\[object .+?Constructor\]$/,Sr=Function.prototype,Cr=Object.prototype,Er=Sr.toString,Mr=Cr.hasOwnProperty,jr=RegExp("^"+Er.call(Mr).replace(Ar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function _r(e){if(!rt(e)||vr(e))return!1;var t=mr(e)?jr:xr;return t.test(M(e))}var Lr=_r;function Nr(e,t){return e?.[t]}var Pr=Nr;function Or(e,t){var r=Pr(e,t);return Lr(r)?r:void 0}var D=Or,$r=D(A,"WeakMap"),ye=$r;function Dr(e,t){return e===t||e!==e&&t!==t}var Tr=Dr,zr=9007199254740991;function Rr(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=zr}var Fr=Rr,gu=Object.prototype,Ur="[object Arguments]";function Vr(e){return Ae(e)&&J(e)==Ur}var Fe=Vr,it=Object.prototype,Br=it.hasOwnProperty,Gr=it.propertyIsEnumerable,fu=Fe(function(){return arguments}())?Fe:function(e){return Ae(e)&&Br.call(e,"callee")&&!Gr.call(e,"callee")},nt=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ue=nt&&typeof module=="object"&&module&&!module.nodeType&&module,Hr=Ue&&Ue.exports===nt,Ve=Hr?A.Buffer:void 0,hu=Ve?Ve.isBuffer:void 0,qr="[object Arguments]",Zr="[object Array]",Yr="[object Boolean]",Qr="[object Date]",Wr="[object Error]",Kr="[object Function]",Jr="[object Map]",Xr="[object Number]",ei="[object Object]",ti="[object RegExp]",ri="[object Set]",ii="[object String]",ni="[object WeakMap]",oi="[object ArrayBuffer]",ai="[object DataView]",si="[object Float32Array]",li="[object Float64Array]",ui="[object Int8Array]",ci="[object Int16Array]",di="[object Int32Array]",pi="[object Uint8Array]",gi="[object Uint8ClampedArray]",fi="[object Uint16Array]",hi="[object Uint32Array]",v={};v[si]=v[li]=v[ui]=v[ci]=v[di]=v[pi]=v[gi]=v[fi]=v[hi]=!0;v[qr]=v[Zr]=v[oi]=v[Yr]=v[ai]=v[Qr]=v[Wr]=v[Kr]=v[Jr]=v[Xr]=v[ei]=v[ti]=v[ri]=v[ii]=v[ni]=!1;function mi(e){return Ae(e)&&Fr(e.length)&&!!v[J(e)]}var bi=mi;function yi(e){return function(t){return e(t)}}var vi=yi,ot=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Q=ot&&typeof module=="object"&&module&&!module.nodeType&&module,wi=Q&&Q.exports===ot,fe=wi&&et.process,ki=function(){try{var e=Q&&Q.require&&Q.require("util").types;return e||fe&&fe.binding&&fe.binding("util")}catch{}}(),Be=ki,Ge=Be&&Be.isTypedArray,mu=Ge?vi(Ge):bi,Ii=Object.prototype,bu=Ii.hasOwnProperty;function Ai(e,t){return function(r){return e(t(r))}}var xi=Ai,yu=xi(Object.keys,Object),Si=Object.prototype,vu=Si.hasOwnProperty,Ci=D(Object,"create"),W=Ci;function Ei(){this.__data__=W?W(null):{},this.size=0}var Mi=Ei;function ji(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var _i=ji,Li="__lodash_hash_undefined__",Ni=Object.prototype,Pi=Ni.hasOwnProperty;function Oi(e){var t=this.__data__;if(W){var r=t[e];return r===Li?void 0:r}return Pi.call(t,e)?t[e]:void 0}var $i=Oi,Di=Object.prototype,Ti=Di.hasOwnProperty;function zi(e){var t=this.__data__;return W?t[e]!==void 0:Ti.call(t,e)}var Ri=zi,Fi="__lodash_hash_undefined__";function Ui(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=W&&t===void 0?Fi:t,this}var Vi=Ui;function T(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var i=e[t];this.set(i[0],i[1])}}T.prototype.clear=Mi;T.prototype.delete=_i;T.prototype.get=$i;T.prototype.has=Ri;T.prototype.set=Vi;var He=T;function Bi(){this.__data__=[],this.size=0}var Gi=Bi;function Hi(e,t){for(var r=e.length;r--;)if(Tr(e[r][0],t))return r;return-1}var se=Hi,qi=Array.prototype,Zi=qi.splice;function Yi(e){var t=this.__data__,r=se(t,e);if(r<0)return!1;var i=t.length-1;return r==i?t.pop():Zi.call(t,r,1),--this.size,!0}var Qi=Yi;function Wi(e){var t=this.__data__,r=se(t,e);return r<0?void 0:t[r][1]}var Ki=Wi;function Ji(e){return se(this.__data__,e)>-1}var Xi=Ji;function en(e,t){var r=this.__data__,i=se(r,e);return i<0?(++this.size,r.push([e,t])):r[i][1]=t,this}var tn=en;function z(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var i=e[t];this.set(i[0],i[1])}}z.prototype.clear=Gi;z.prototype.delete=Qi;z.prototype.get=Ki;z.prototype.has=Xi;z.prototype.set=tn;var le=z,rn=D(A,"Map"),K=rn;function nn(){this.size=0,this.__data__={hash:new He,map:new(K||le),string:new He}}var on=nn;function an(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var sn=an;function ln(e,t){var r=e.__data__;return sn(t)?r[typeof t=="string"?"string":"hash"]:r.map}var ue=ln;function un(e){var t=ue(this,e).delete(e);return this.size-=t?1:0,t}var cn=un;function dn(e){return ue(this,e).get(e)}var pn=dn;function gn(e){return ue(this,e).has(e)}var fn=gn;function hn(e,t){var r=ue(this,e),i=r.size;return r.set(e,t),this.size+=r.size==i?0:1,this}var mn=hn;function R(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var i=e[t];this.set(i[0],i[1])}}R.prototype.clear=on;R.prototype.delete=cn;R.prototype.get=pn;R.prototype.has=fn;R.prototype.set=mn;var at=R;function bn(){this.__data__=new le,this.size=0}var yn=bn;function vn(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var wn=vn;function kn(e){return this.__data__.get(e)}var In=kn;function An(e){return this.__data__.has(e)}var xn=An,Sn=200;function Cn(e,t){var r=this.__data__;if(r instanceof le){var i=r.__data__;if(!K||i.length<Sn-1)return i.push([e,t]),this.size=++r.size,this;r=this.__data__=new at(i)}return r.set(e,t),this.size=r.size,this}var En=Cn;function X(e){var t=this.__data__=new le(e);this.size=t.size}X.prototype.clear=yn;X.prototype.delete=wn;X.prototype.get=In;X.prototype.has=xn;X.prototype.set=En;var Mn=Object.prototype,wu=Mn.propertyIsEnumerable,jn=D(A,"DataView"),ve=jn,_n=D(A,"Promise"),we=_n,Ln=D(A,"Set"),ke=Ln,qe="[object Map]",Nn="[object Object]",Ze="[object Promise]",Ye="[object Set]",Qe="[object WeakMap]",We="[object DataView]",Pn=M(ve),On=M(K),$n=M(we),Dn=M(ke),Tn=M(ye),P=J;(ve&&P(new ve(new ArrayBuffer(1)))!=We||K&&P(new K)!=qe||we&&P(we.resolve())!=Ze||ke&&P(new ke)!=Ye||ye&&P(new ye)!=Qe)&&(P=function(e){var t=J(e),r=t==Nn?e.constructor:void 0,i=r?M(r):"";if(i)switch(i){case Pn:return We;case On:return qe;case $n:return Ze;case Dn:return Ye;case Tn:return Qe}return t});var ku=A.Uint8Array,zn="__lodash_hash_undefined__";function Rn(e){return this.__data__.set(e,zn),this}var Fn=Rn;function Un(e){return this.__data__.has(e)}var Vn=Un;function Ie(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new at;++t<r;)this.add(e[t])}Ie.prototype.add=Ie.prototype.push=Fn;Ie.prototype.has=Vn;var Ke=$?$.prototype:void 0,Iu=Ke?Ke.valueOf:void 0,Bn=Object.prototype,Au=Bn.hasOwnProperty,Gn=Object.prototype,xu=Gn.hasOwnProperty,Su=new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,"i"),Cu=new RegExp(/[A-Fa-f0-9]{1}/,"g"),Eu=new RegExp(/[A-Fa-f0-9]{2}/,"g");async function st(e,t){if(e.startsWith("buffer:")){let r=await t.editor.getMimeType(e),i=t.editor.getBufferLength(e),n=t.editor.getBufferData(e,0,i),o=new Blob([n],{type:r});return URL.createObjectURL(o)}else return e}async function Hn(e,t){let r=await st(e,t);return new Promise((i,n)=>{let o=new Image;o.onload=()=>{i({width:o.width,height:o.height})},o.onerror=n,o.src=r})}async function qn(e,t,r){let i,n=t.block.getFill(e),o=t.block.getSourceSet(n,"fill/image/sourceSet"),[a]=o;if(a==null){if(i=t.block.getString(n,"fill/image/imageFileURI"),i==null)throw new Error("No image source/uri found")}else i=a.uri;if(r?.throwErrorIfSvg&&await t.editor.getMimeType(i)==="image/svg+xml")throw new Error("SVG images are not supported");return st(i,t)}function Zn(e){return e!==void 0}var Yn=Zn;var lt=class ut{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 ut),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))}},Qn=class ct{constructor(){this.providers=new Map}static get(){let t="__imgly_provider_registry__",r=typeof window<"u"?window:globalThis;return r[t]||(r[t]=new ct),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 Wn(e){let t=e.filter(r=>!!r);return r=>async(i,n)=>{let o=[],a=l=>{o.push(l)},s=async(l,c,d)=>{if(l>=t.length)return r(c,d);let p=t[l],g=async(b,m)=>s(l+1,b,m),h={...d,addDisposer:a};return p(c,h,g)},u={...n,addDisposer:a};return{result:await s(0,i,u),dispose:async()=>{for(let l=o.length-1;l>=0;l--)try{await o[l]()}catch(c){console.error("Error in disposer:",c)}o.length=0}}}}function Kn({enable:e=!0}){return async(t,r,i)=>{if(!e)return i(t,r);console.group("[GENERATION]"),console.log("Generating with input:",JSON.stringify(t,null,2));let n,o=Date.now();try{return n=await i(t,r),n}finally{n!=null&&(console.log(`Generation took ${Date.now()-o}ms`),console.log("Generation result:",JSON.stringify(n,null,2))),console.groupEnd()}}}var Jn=Kn;var he="ly.img.ai.temp";async function Xn(e,t){return e.engine.asset.findAllSources().includes(he)||e.engine.asset.addLocalSource(he),e.engine.asset.apply(he,t)}function eo(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 dt(){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 to(e,t=0,r="image/jpeg",i=.8){return new Promise((n,o)=>{try{let a=document.createElement("video");a.crossOrigin="anonymous",a.style.display="none",a.addEventListener("loadedmetadata",()=>{a.currentTime=Math.min(t,a.duration),a.addEventListener("seeked",()=>{let s=document.createElement("canvas");s.width=a.videoWidth,s.height=a.videoHeight;let u=s.getContext("2d");if(!u){document.body.removeChild(a),o(new Error("Failed to create canvas context"));return}u.drawImage(a,0,0,s.width,s.height);try{let l=s.toDataURL(r,i);document.body.removeChild(a),n(l)}catch(l){document.body.removeChild(a),o(new Error(`Failed to create thumbnail: ${l instanceof Error?l.message:String(l)}`))}},{once:!0})}),a.addEventListener("error",()=>{document.body.removeChild(a),o(new Error(`Failed to load video from ${e}`))}),a.src=e,document.body.appendChild(a)}catch(a){o(a)}})}function pt(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 ro(e){return typeof e=="object"&&e!==null&&"next"in e&&"return"in e&&"throw"in e&&typeof e.next=="function"&&typeof e.return=="function"&&typeof e.throw=="function"&&Symbol.asyncIterator in e&&typeof e[Symbol.asyncIterator]=="function"}function xe(e){return e instanceof Error&&e.name==="AbortError"}function io(e,t,r){let i=`${t}.iconSetAdded`;e.ui.experimental.hasGlobalStateValue(i)||(e.ui.addIconSet(t,r),e.ui.experimental.setGlobalStateValue(i,!0))}function gt(e,t,r){let i="ai-plugin-version",n="ai-plugin-version-warning-shown";try{let o=e.ui.experimental.getGlobalStateValue(i);o?o!==r&&(e.ui.experimental.getGlobalStateValue(n,!1)||(console.warn(`[IMG.LY AI Plugins] Version mismatch detected!
2
2
  Plugin "${t}" is using version ${r}, but other AI plugins are using version ${o}.
3
3
  This may cause compatibility issues. Please ensure all AI plugins (@imgly/plugin-ai-*) use the same version.
4
- Consider updating all AI plugins to the same version for optimal compatibility.`),e.ui.experimental.setGlobalStateValue(n,!0))):e.ui.experimental.setGlobalStateValue(i,r)}catch(o){console.debug("[IMG.LY AI Plugins] Could not check plugin version consistency:",o)}}function no(e){let{cesdk:t,panelId:r}=e;r.startsWith("ly.img.ai.")||console.warn(`Dock components for AI generation should open a panel with an id starting with "ly.img.ai." \u2013 "${r}" was provided.`);let i=`${r}.dock`;t.ui.registerComponent(i,({builder:n})=>{let o=t.ui.isPanelOpen(r);n.Button(`${r}.dock.button`,{label:`${r}.dock.label`,isSelected:o,icon:"@imgly/Sparkle",onClick:()=>{t.ui.findAllPanels().forEach(a=>{a.startsWith("ly.img.ai.")&&t.ui.closePanel(a),!o&&a==="//ly.img.panel/assetLibrary"&&t.ui.closePanel(a)}),o?t.ui.closePanel(r):t.ui.openPanel(r)}})})}var Se=no;function oo(e,t){let{cesdk:r,provider:i,getInput:n}=t;console.error("Generation failed:",e),ao(r,i.output.notification,()=>({input:n?.().input,error:e}))||r.ui.showNotification({type:"error",message:eo(e)})}function ao(e,t,r){let i=t?.error;if(i==null||!(typeof i.show=="function"?i.show(r()):i.show))return!1;let n=typeof i.message=="function"?i.message(r()):i.message??"common.ai-generation.failed",o=i.action!=null?{label:typeof i.action.label=="function"?i.action.label(r()):i.action.label,onClick:()=>{i?.action?.onClick(r())}}:void 0;return e.ui.showNotification({type:"error",message:n,action:o}),!0}var Je=oo,so="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIzIiBoZWlnaHQ9IjMyMyIgdmlld0JveD0iMCAwIDMyMyAzMjMiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIzMjMiIGhlaWdodD0iMzIzIiBmaWxsPSIjRTlFQkVEIi8+CjxnIG9wYWNpdHk9IjAuMyI+CjxwYXRoIGQ9Ik0xMTYgMTg0VjE5MS41QzExNiAxOTkuNzg0IDEyMi43MTYgMjA2LjUgMTMxIDIwNi41SDE5MUMxOTkuMjg0IDIwNi41IDIwNiAxOTkuNzg0IDIwNiAxOTEuNVYxMzEuNUMyMDYgMTIzLjIxNiAxOTkuMjg0IDExNi41IDE5MSAxMTYuNUwxOTAuOTk1IDEyNi41QzE5My43NTcgMTI2LjUgMTk2IDEyOC43MzkgMTk2IDEzMS41VjE5MS41QzE5NiAxOTQuMjYxIDE5My43NjEgMTk2LjUgMTkxIDE5Ni41SDEzMUMxMjguMjM5IDE5Ni41IDEyNiAxOTQuMjYxIDEyNiAxOTEuNVYxODRIMTE2WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTY2LjQ5NCAxMDUuOTI0QzE2NS44NjkgMTA0LjM0MiAxNjMuNjI5IDEwNC4zNDIgMTYzLjAwNSAxMDUuOTI0TDE1OS43NDUgMTE0LjE5MUMxNTkuNTU0IDExNC42NzQgMTU5LjE3MiAxMTUuMDU3IDE1OC42ODggMTE1LjI0N0wxNTAuNDIyIDExOC41MDhDMTQ4LjgzOSAxMTkuMTMyIDE0OC44MzkgMTIxLjM3MiAxNTAuNDIyIDEyMS45OTZMMTU4LjY4OCAxMjUuMjU2QzE1OS4xNzIgMTI1LjQ0NyAxNTkuNTU0IDEyNS44MjkgMTU5Ljc0NSAxMjYuMzEzTDE2My4wMDUgMTM0LjU3OUMxNjMuNjI5IDEzNi4xNjIgMTY1Ljg2OSAxMzYuMTYyIDE2Ni40OTQgMTM0LjU3OUwxNjkuNzU0IDEyNi4zMTNDMTY5Ljk0NCAxMjUuODI5IDE3MC4zMjcgMTI1LjQ0NyAxNzAuODEgMTI1LjI1NkwxNzkuMDc3IDEyMS45OTZDMTgwLjY2IDEyMS4zNzIgMTgwLjY2IDExOS4xMzIgMTc5LjA3NyAxMTguNTA4TDE3MC44MSAxMTUuMjQ3QzE3MC4zMjcgMTE1LjA1NyAxNjkuOTQ0IDExNC42NzQgMTY5Ljc1NCAxMTQuMTkxTDE2Ni40OTQgMTA1LjkyNFoiIGZpbGw9IiM4RjhGOEYiLz4KPHBhdGggZD0iTTEzMy4wMDUgMTI4LjQyNEMxMzMuNjI5IDEyNi44NDIgMTM1Ljg2OSAxMjYuODQyIDEzNi40OTQgMTI4LjQyNEwxNDEuODc1IDE0Mi4wN0MxNDIuMDY2IDE0Mi41NTMgMTQyLjQ0OCAxNDIuOTM1IDE0Mi45MzIgMTQzLjEyNkwxNTYuNTc3IDE0OC41MDhDMTU4LjE2IDE0OS4xMzIgMTU4LjE2IDE1MS4zNzIgMTU2LjU3NyAxNTEuOTk2TDE0Mi45MzIgMTU3LjM3OEMxNDIuNDQ4IDE1Ny41NjggMTQyLjA2NiAxNTcuOTUxIDE0MS44NzUgMTU4LjQzNEwxMzYuNDk0IDE3Mi4wNzlDMTM1Ljg2OSAxNzMuNjYyIDEzMy42MjkgMTczLjY2MiAxMzMuMDA1IDE3Mi4wNzlMMTI3LjYyMyAxNTguNDM0QzEyNy40MzMgMTU3Ljk1MSAxMjcuMDUgMTU3LjU2OCAxMjYuNTY3IDE1Ny4zNzhMMTEyLjkyMiAxNTEuOTk2QzExMS4zMzkgMTUxLjM3MiAxMTEuMzM5IDE0OS4xMzIgMTEyLjkyMiAxNDguNTA4TDEyNi41NjcgMTQzLjEyNkMxMjcuMDUgMTQyLjkzNSAxMjcuNDMzIDE0Mi41NTMgMTI3LjYyMyAxNDIuMDdMMTMzLjAwNSAxMjguNDI0WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTk1Ljk5OSAxODQuMDA0VjE5MS41MDJDMTk1Ljk5OSAxOTQuMjYzIDE5My43NjEgMTk2LjUwMiAxOTAuOTk5IDE5Ni41MDJIMTQ3LjY2OEwxNzIuODc5IDE1OC42ODRDMTc0LjM2MyAxNTYuNDU4IDE3Ny42MzUgMTU2LjQ1OCAxNzkuMTIgMTU4LjY4NEwxOTUuOTk5IDE4NC4wMDRaIiBmaWxsPSIjOEY4RjhGIi8+CjwvZz4KPC9zdmc+Cg==",Ce=so;function lo(e,t,r){switch(t){case"image":return uo(e,r[t]);case"video":return co(e,r[t]);case"sticker":return po(e,r[t]);default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function uo(e,t){let r=t.width,i=t.height;return{id:e,meta:{previewUri:Ce,fillType:"//ly.img.ubq/fill/image",kind:"image",width:r,height:i}}}function co(e,t){let r=t.width,i=t.height;return{id:e,label:t.label,meta:{previewUri:Ce,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:r,height:i}}}function po(e,t){let r=t.width,i=t.height;return{id:e,meta:{previewUri:Ce,fillType:"//ly.img.ubq/fill/image",kind:"sticker",width:r,height:i}}}var go=lo;async function fo(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 ho(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 mo(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 bo(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 yo(e,r[t],i)}default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function ho(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 mo(e,t,r){let i=t.width,n=t.height,o=await to(r.url,0);return{id:e,label:t.label,meta:{uri:r.url,thumbUri:o,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:i,height:n}}}function bo(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 yo(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 ft=fo;function vo(e){switch(e.userFlow){case"placeholder":return ko(e);case"generation-only":return wo(e);default:throw new Error(`Unknown user flow: ${e.userFlow}. Expected 'placeholder' or 'generation-only'.`)}}function wo(e){let{cesdk:t,abortSignal:r}=e;return async i=>{try{let n=e.kind,o=await e.getBlockInput(i);if(C(t,r))return{status:"aborted"};let a=await e.generate(i,{middlewares:[...e.middlewares??[]],debug:e.debug,dryRun:e.dryRun,abortSignal:r});if(C(t,r))return{status:"aborted"};if(a.status!=="success")return a;if(a.type==="async")throw new Error("Async generation is not supported in this context yet.");if(C(t,r))return{status:"aborted"};if(e.historyAssetSourceId!=null){let s=dt(),u=await ft(s,n,o,a.output),l={...u,id:`${Date.now()}-${u.id}`,label:u.label!=null?{en:u.label}:{},tags:{}};t.engine.asset.addAssetToSource(e.historyAssetSourceId,l)}else e.debug&&console.log("No asset source ID found in history and generation only was requested. Doing nothing. If no middleware is adding functionality this could be a bug.");return a}catch(n){return{status:"error",message:n instanceof Error?n.message:String(n)}}}}function ko(e){let{cesdk:t,abortSignal:r}=e,i;return async n=>{try{let o=e.kind,a=await e.getBlockInput(n);if(C(t,r))return{status:"aborted"};let s=dt(),u=go(s,o,a);if(i=await Xn(t,u),C(t,r,i))return{status:"aborted"};if(i!=null&&e.kind==="video"){let d=t.engine.block.getPositionX(i),p=t.engine.block.getPositionY(i),g=t.engine.block.duplicate(i);t.engine.block.setPositionX(g,d),t.engine.block.setPositionY(g,p),t.engine.block.destroy(i),i=g}if(i==null)throw new Error("Could not create placeholder block");t.engine.block.setState(i,{type:"Pending",progress:0});let l=await e.generate(n,{middlewares:[...e.middlewares??[]],debug:e.debug,dryRun:e.dryRun,abortSignal:r});if(C(t,r,i))return{status:"aborted"};if(l.status!=="success")return l;if(l.type==="async")throw new Error("Async generation is not supported in this context yet.");if(!t.engine.block.isValid(i))return{status:"aborted",message:"Placeholder block was destroyed before generation completed."};let c=await ft(s,o,a,l.output);if(C(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),C(t,r,i))return{status:"aborted"};if(e.historyAssetSourceId!=null){let d={...c,id:`${Date.now()}-${c.id}`,label:c.label!=null?{en:c.label}:{},tags:{}};t.engine.asset.addAssetToSource(e.historyAssetSourceId,d)}return t.engine.block.isValid(i)&&t.engine.block.setState(i,{type:"Ready"}),l}catch(o){return i!=null&&t.engine.block.isValid(i)&&(xe(o)?t.engine.block.destroy(i):t.engine.block.setState(i,{type:"Error",error:"Unknown"})),{status:"error",message:o instanceof Error?o.message:String(o)}}}}function C(e,t,r){return t.aborted?(r!=null&&e.engine.block.isValid(r)&&e.engine.block.destroy(r),!0):!1}var Io=vo;function Ee(e){return`${e}.generating`}function Ao(e){return`${e}.abort`}function xo(e,t,r,i,n,o,a){let{builder:s,experimental:u}=e,{cesdk:l,includeHistoryLibrary:c=!0}=o,{id:d,output:{abortable:p}}=t,g=u.global(Ao(d),()=>{}),h=u.global(Ee(d),!1),b,m=h.value&&p,f=()=>{m&&(g.value(),h.setValue(!1),g.setValue(()=>{}))},N;if(o.requiredInputs!=null&&o.requiredInputs.length>0){let I=i();N=o.requiredInputs.every(k=>!I.input[k])}let y=u.global(`${d}.confirmationDialogId`,void 0);s.Section(`${d}.generate.section`,{children:()=>{s.Button(`${d}.generate`,{label:["common.generate",`panel.${d}.generate`],isLoading:h.value,color:"accent",isDisabled:N,suffix:m?{icon:"@imgly/Cross",color:"danger",tooltip:[`panel.${d}.abort`,"common.cancel"],onClick:()=>{let I=l.ui.showDialog({type:"warning",content:"panel.ly.img.ai.generation.confirmCancel.content",cancel:{label:"common.close",onClick:({id:k})=>{l.ui.closeDialog(k),y.setValue(void 0)}},actions:{label:"panel.ly.img.ai.generation.confirmCancel.confirm",color:"danger",onClick:({id:k})=>{f(),l.ui.closeDialog(k),y.setValue(void 0)}}});y.setValue(I)}}:void 0,onClick:async()=>{b=new AbortController;let I=b.signal;await(async()=>{try{h.setValue(!0),g.setValue(()=>{a.debug&&console.log("Aborting generation"),b?.abort()});let k=await Io({kind:t.kind,generate:r,historyAssetSourceId:o.historyAssetSourceId,userFlow:o.createPlaceholderBlock?"placeholder":"generation-only",getBlockInput:n,abortSignal:I,cesdk:l,debug:a.debug,dryRun:a.dryRun})(i().input);if(k.status==="aborted")return;if(k.status==="error"){Je(k.message,{cesdk:l,provider:t,getInput:i});return}if(k.status==="success"&&k.type==="sync"){let E=t.output.notification;So(l,E,()=>({input:i().input,output:k.output}))}}catch(k){if(xe(k))return;Je(k,{cesdk:l,provider:t,getInput:i})}finally{b=void 0,h.setValue(!1),g.setValue(()=>{}),y.value!=null&&(l.ui.closeDialog(y.value),y.setValue(void 0))}})()}}),t.output.generationHintText!=null&&s.Text(`${d}.generation-hint`,{align:"center",content:t.output.generationHintText})}}),c&&o.historyAssetLibraryEntryId!=null&&s.Library(`${d}.history.library`,{entries:[o.historyAssetLibraryEntryId]})}function So(e,t,r){let i=t?.success;if(i==null||!(typeof i.show=="function"?i.show(r()):i.show))return!1;let n=typeof i.message=="function"?i.message(r()):i.message??"common.ai-generation.success",o=i.action!=null?{label:typeof i.action.label=="function"?i.action.label(r()):i.action.label,onClick:()=>{i?.action?.onClick(r())}}:void 0;return e.ui.showNotification({type:"success",message:n,action:o,duration:i.duration}),!0}var ht=xo;async function Co({options:e,provider:t,panelInput:r,config:i},n){if(r==null)return;let{cesdk:o}=e,{id:a}=t,s=r.render;return u=>{let{state:l}=u,c=l(Ee(a),{isGenerating:!1,abort:()=>{}}).value.isGenerating,{getInput:d,getBlockInput:p}=s(u,{cesdk:o,isGenerating:c});return ht(u,t,n,d,p,{...e,includeHistoryLibrary:r.includeHistoryLibrary??!0,createPlaceholderBlock:r.userFlow==="placeholder"},i),d}}var Eo=Co;function mt(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 Y(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=mt(e,t.$ref),n={...Y(e,i,r)};for(let o in t)Object.prototype.hasOwnProperty.call(t,o)&&o!=="$ref"&&(n[o]=Y(e,t[o],r));return n}if(Array.isArray(t))return t.map(i=>Y(e,i,r));if(typeof t=="object"){let i={};for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[n]=Y(e,t[n],r));return i}return t}function Mo(e){return Y(e,{...e})}function jo(e,t=!1){let r=a=>(t&&console.log(`OpenAPI Schema validation failed: ${a}`),!1);if(typeof e!="object"||e===null)return r(`Input is ${e===null?"null":typeof e}, not an object`);let i=e;if(!(typeof i.type=="string"||Array.isArray(i.enum)||typeof i.properties=="object"||typeof i.items=="object"||typeof i.allOf=="object"||typeof i.anyOf=="object"||typeof i.oneOf=="object"||typeof i.not=="object"))return r("Missing required schema-defining properties (type, enum, properties, items, allOf, anyOf, oneOf, not)");if(i.type!==void 0){let a=["string","number","integer","boolean","array","object","null"];if(typeof i.type=="string"){if(!a.includes(i.type))return r(`Invalid type: ${i.type}. Must be one of ${a.join(", ")}`)}else if(Array.isArray(i.type)){for(let s of i.type)if(typeof s!="string"||!a.includes(s))return r(`Array of types contains invalid value: ${s}. Must be one of ${a.join(", ")}`)}else return r(`Type must be a string or array of strings, got ${typeof i.type}`)}if(i.items!==void 0&&(typeof i.items!="object"||i.items===null))return r(`Items must be an object, got ${i.items===null?"null":typeof i.items}`);if(i.properties!==void 0&&(typeof i.properties!="object"||i.properties===null))return r(`Properties must be an object, got ${i.properties===null?"null":typeof i.properties}`);let n=["allOf","anyOf","oneOf"];for(let a of n)if(i[a]!==void 0){if(!Array.isArray(i[a]))return r(`${a} must be an array, got ${typeof i[a]}`);for(let s=0;s<i[a].length;s++){let u=i[a][s];if(typeof u!="object"||u===null)return r(`Item ${s} in ${a} 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 o=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf"];for(let a of o)if(i[a]!==void 0&&typeof i[a]!="number")return r(`${a} must be a number, got ${typeof i[a]}`);if(i.minLength!==void 0&&(typeof i.minLength!="number"||i.minLength<0))return r(`minLength must be a non-negative number, got ${typeof i.minLength=="number"?i.minLength:typeof i.minLength}`);if(i.maxLength!==void 0&&(typeof i.maxLength!="number"||i.maxLength<0))return r(`maxLength must be a non-negative number, got ${typeof i.maxLength=="number"?i.maxLength:typeof i.maxLength}`);if(i.pattern!==void 0&&typeof i.pattern!="string")return r(`pattern must be a string, got ${typeof i.pattern}`);if(i.minItems!==void 0&&(typeof i.minItems!="number"||i.minItems<0))return r(`minItems must be a non-negative number, got ${typeof i.minItems=="number"?i.minItems:typeof i.minItems}`);if(i.maxItems!==void 0&&(typeof i.maxItems!="number"||i.maxItems<0))return r(`maxItems must be a non-negative number, got ${typeof i.maxItems=="number"?i.maxItems:typeof i.maxItems}`);if(i.uniqueItems!==void 0&&typeof i.uniqueItems!="boolean")return r(`uniqueItems must be a boolean, got ${typeof i.uniqueItems}`);if(i.minProperties!==void 0&&(typeof i.minProperties!="number"||i.minProperties<0))return r(`minProperties must be a non-negative number, got ${typeof i.minProperties=="number"?i.minProperties:typeof i.minProperties}`);if(i.maxProperties!==void 0&&(typeof i.maxProperties!="number"||i.maxProperties<0))return r(`maxProperties must be a non-negative number, got ${typeof i.maxProperties=="number"?i.maxProperties:typeof i.maxProperties}`);if(i.required!==void 0){if(!Array.isArray(i.required))return r(`required must be an array, got ${typeof i.required}`);for(let a=0;a<i.required.length;a++){let s=i.required[a];if(typeof s!="string")return r(`Item ${a} in required array must be a string, got ${typeof s}`)}}return!0}function _o(e,t){if(e.properties==null)throw new Error("Input schema must have properties");let r=e.properties,i=[];return Lo(e,t).forEach(n=>{let o=n,a=r[n]??void 0;i.push({id:o,schema:a})}),i}function Lo(e,t){let r=t.order;if(r!=null&&Array.isArray(r))return r;if(e.properties==null)throw new Error("Input schema must have properties");let i=e.properties,n=Object.keys(i),o=No(e,t)??n;return r!=null&&typeof r=="function"&&(o=r(o)),[...new Set(o)]}function No(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 bt=_o;function yt(e,t,r,i,n,o){if(t.schema==null)return i.renderCustomProperty!=null&&i.renderCustomProperty[t.id]!=null?i.renderCustomProperty[t.id](e,t):void 0;let a=t,s=t.schema.type;if(i.renderCustomProperty!=null&&i.renderCustomProperty[t.id]!=null)return i.renderCustomProperty[t.id](e,t);switch(s){case"string":return t.schema.enum!=null?Po(e,a,r,i,n,o):wt(e,a,r,i,n,o);case"boolean":return kt(e,a,r,i,n,o);case"number":case"integer":return It(e,a,r,i,n,o);case"object":return vt(e,a,r,i,n,o);case"array":break;case void 0:{if(t.schema.anyOf!=null&&Array.isArray(t.schema.anyOf))return Oo(e,a,r,i,n,o);break}default:console.error(`Unsupported property type: ${s}`)}}function vt(e,t,r,i,n,o){let a=bt(t.schema??{},i).reduce((s,u)=>{let l=yt(e,u,r,i,n,o);return l!=null&&(s[u.id]=l()),s},{});return()=>({id:t.id,type:"object",value:a})}function wt(e,t,r,i,n,o){let{builder:a,experimental:{global:s}}=e,{id:u}=t,l=`${r.id}.${u}`,c=t.schema.title??l,d=s(l,t.schema.default??""),p=$o(t.schema),g=p?.component!=null&&p?.component==="TextArea"?"TextArea":"TextInput";return a[g](l,{inputLabel:c,placeholder:n.i18n?.prompt,...d}),()=>({id:t.id,type:"string",value:d.value})}function Po(e,t,r,i,n,o){let{builder:a,experimental:{global:s}}=e,{id:u}=t,l=`${r.id}.${u}`,c=t.schema.title??l,d=t.schema.enum!=null&&"x-imgly-enum-labels"in t.schema.enum&&typeof t.schema.enum["x-imgly-enum-labels"]=="object"?t.schema.enum["x-imgly-enum-labels"]:"x-imgly-enum-labels"in t.schema&&typeof t.schema["x-imgly-enum-labels"]=="object"?t.schema["x-imgly-enum-labels"]:{},p="x-imgly-enum-icons"in t.schema&&typeof t.schema["x-imgly-enum-icons"]=="object"?t.schema["x-imgly-enum-icons"]:{},g=(t.schema.enum??[]).map(m=>({id:m,label:d[m]??pt(m),icon:p[m]})),h=t.schema.default!=null?g.find(m=>m.id===t.schema.default)??g[0]:g[0],b=s(l,h);return a.Select(l,{inputLabel:c,values:g,...b}),()=>({id:t.id,type:"string",value:b.value.id})}function kt(e,t,r,i,n,o){let{builder:a,experimental:{global:s}}=e,{id:u}=t,l=`${r.id}.${u}`,c=t.schema.title??l,d=!!t.schema.default,p=s(l,d);return a.Checkbox(l,{inputLabel:c,...p}),()=>({id:t.id,type:"boolean",value:p.value})}function It(e,t,r,i,n,o){let{builder:a,experimental:{global:s}}=e,{id:u}=t,l=`${r.id}.${u}`,c=t.schema.title??l,d=t.schema.minimum,p=t.schema.maximum,g=t.schema.default;g==null&&(d!=null?g=d:p!=null?g=p:g=0);let h=s(l,g);if(d!=null&&p!=null){let b=t.schema.type==="number"?.1:1;"x-imgly-step"in t.schema&&typeof t.schema["x-imgly-step"]=="number"&&(b=t.schema["x-imgly-step"]),a.Slider(l,{inputLabel:c,min:d,max:p,step:b,...h})}else a.NumberInput(l,{inputLabel:c,min:d,max:p,...h});return()=>({id:t.id,type:"integer",value:h.value})}function Oo(e,t,r,i,n,o){let{builder:a,experimental:{global:s}}=e,{id:u}=t,l=`${r.id}.${u}`,c=t.schema.title??l,d=t.schema.anyOf??[],p=[],g={},h={};d.forEach((f,N)=>{let y=f.title??"common.custom",I=`${r.id}.${u}.anyOf[${N}]`,k="x-imgly-enum-labels"in t.schema&&typeof t.schema["x-imgly-enum-labels"]=="object"?t.schema["x-imgly-enum-labels"]:{},E="x-imgly-enum-icons"in t.schema&&typeof t.schema["x-imgly-enum-icons"]=="object"?t.schema["x-imgly-enum-icons"]:{};f.type==="string"?f.enum!=null?f.enum.forEach(ae=>{p.push({id:ae,label:k[ae]??pt(ae),icon:E[ae]})}):(g[I]=()=>wt(e,{id:I,schema:{...f,title:y}},r,i,n,o),p.push({id:I,label:k[y]??y,icon:E[y]})):f.type==="boolean"?(g[I]=()=>kt(e,{id:I,schema:{...f,title:y}},r,i,n,o),p.push({id:I,label:k[y]??y,icon:E[y]})):f.type==="integer"?(g[I]=()=>It(e,{id:I,schema:{...f,title:y}},r,i,n,o),p.push({id:I,label:k[y]??y,icon:E[y]})):f.type==="array"||f.type==="object"&&(g[I]=()=>vt(e,{id:I,schema:{...f,title:y}},r,i,n,o),p.push({id:I,label:k[y]??y,icon:E[y]}))});let b=t.schema.default!=null?p.find(f=>f.id===t.schema.default)??p[0]:p[0],m=s(l,b);if(a.Select(l,{inputLabel:c,values:p,...m}),m.value.id in g){let f=g[m.value.id]();h[m.value.id]=f}return()=>{let f=h[m.value.id];return f!=null?{...f(),id:t.id}:{id:t.id,type:"string",value:m.value.id}}}function $o(e){if("x-imgly-builder"in e)return e["x-imgly-builder"]}var Do=yt;async function To({options:e,provider:t,panelInput:r,config:i},n){let{id:o}=t;if(r==null)return;i.debug&&console.log(`Registering schema-based panel input for provider ${o}`);let a=Mo(r.document),s=mt(a,r.inputReference);if(!jo(s,i.debug))throw new Error(`Input reference '${r.inputReference}' does not resolve to a valid OpenAPI schema`);let u=s,l=bt(u,r);return c=>{let{builder:d}=c,p=[];d.Section(`${o}.schema.section`,{children:()=>{l.forEach(m=>{let f=Do(c,m,t,r,e,i);f!=null&&(Array.isArray(f)?p.push(...f):p.push(f))})}});let g=p.map(m=>m()),h=m=>m.type==="object"?Object.entries(m.value).reduce((f,[N,y])=>(f[N]=h(y),f),{}):m.value,b=g.reduce((m,f)=>(m[f.id]=h(f),m),{});ht(c,t,n,()=>({input:b}),()=>r.getBlockInput(b),{...e,requiredInputs:u.required,createPlaceholderBlock:r.userFlow==="placeholder"},i)}}var zo=To;async function Ro(e,t){if(e.panelInput!=null)switch(e.panelInput.type){case"custom":return Eo(e,t);case"schema":return zo(e,t);default:e.config.debug&&console.warn(`Invalid panel input type '${panelInput.type}' - skipping`)}}var Fo=Ro;function Uo(e){let{provider:t,options:{engine:r}}=e,i=t.output.history??"@imgly/local";if(i==null||i===!1)return;let n=r.asset.findAllSources();function o(){let a=`${t.id}.history`;for(;n.includes(a);)a+=`-${Math.random().toString(36).substring(2,6)}`;return a}if(i==="@imgly/local"){let a=o();return r.asset.addLocalSource(a),a}if(i==="@imgly/indexedDB"){let a=o();return r.asset.addSource(new qt(a,r)),a}return i}var Vo=Uo;function Bo(e,t){if(t==null||!t)return;let r=`${e.provider.id}.history.entry`;return e.options.cesdk.ui.addAssetLibraryEntry({id:r,sourceIds:[t],sortBy:{sortKey:"insertedAt",sortingOrder:"Descending"},canRemove:!0,gridItemHeight:"square",gridBackgroundType:"cover"}),r}var Go=Bo,me="@imgly/plugin-ai-generation",Ho=`
4
+ Consider updating all AI plugins to the same version for optimal compatibility.`),e.ui.experimental.setGlobalStateValue(n,!0))):e.ui.experimental.setGlobalStateValue(i,r)}catch(o){console.debug("[IMG.LY AI Plugins] Could not check plugin version consistency:",o)}}function no(e){let{cesdk:t,panelId:r}=e;r.startsWith("ly.img.ai.")||console.warn(`Dock components for AI generation should open a panel with an id starting with "ly.img.ai." \u2013 "${r}" was provided.`);let i=`${r}.dock`;t.ui.registerComponent(i,({builder:n})=>{let o=t.ui.isPanelOpen(r);n.Button(`${r}.dock.button`,{label:`${r}.dock.label`,isSelected:o,icon:"@imgly/Sparkle",onClick:()=>{t.ui.findAllPanels().forEach(a=>{a.startsWith("ly.img.ai.")&&t.ui.closePanel(a),!o&&a==="//ly.img.panel/assetLibrary"&&t.ui.closePanel(a)}),o?t.ui.closePanel(r):t.ui.openPanel(r)}})})}var Se=no;function oo(e,t){let{cesdk:r,provider:i,getInput:n}=t;console.error("Generation failed:",e),ao(r,i.output.notification,()=>({input:n?.().input,error:e}))||r.ui.showNotification({type:"error",message:eo(e)})}function ao(e,t,r){let i=t?.error;if(i==null||!(typeof i.show=="function"?i.show(r()):i.show))return!1;let n=typeof i.message=="function"?i.message(r()):i.message??"common.ai-generation.failed",o=i.action!=null?{label:typeof i.action.label=="function"?i.action.label(r()):i.action.label,onClick:()=>{i?.action?.onClick(r())}}:void 0;return e.ui.showNotification({type:"error",message:n,action:o}),!0}var Je=oo,so="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIzIiBoZWlnaHQ9IjMyMyIgdmlld0JveD0iMCAwIDMyMyAzMjMiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIzMjMiIGhlaWdodD0iMzIzIiBmaWxsPSIjRTlFQkVEIi8+CjxnIG9wYWNpdHk9IjAuMyI+CjxwYXRoIGQ9Ik0xMTYgMTg0VjE5MS41QzExNiAxOTkuNzg0IDEyMi43MTYgMjA2LjUgMTMxIDIwNi41SDE5MUMxOTkuMjg0IDIwNi41IDIwNiAxOTkuNzg0IDIwNiAxOTEuNVYxMzEuNUMyMDYgMTIzLjIxNiAxOTkuMjg0IDExNi41IDE5MSAxMTYuNUwxOTAuOTk1IDEyNi41QzE5My43NTcgMTI2LjUgMTk2IDEyOC43MzkgMTk2IDEzMS41VjE5MS41QzE5NiAxOTQuMjYxIDE5My43NjEgMTk2LjUgMTkxIDE5Ni41SDEzMUMxMjguMjM5IDE5Ni41IDEyNiAxOTQuMjYxIDEyNiAxOTEuNVYxODRIMTE2WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTY2LjQ5NCAxMDUuOTI0QzE2NS44NjkgMTA0LjM0MiAxNjMuNjI5IDEwNC4zNDIgMTYzLjAwNSAxMDUuOTI0TDE1OS43NDUgMTE0LjE5MUMxNTkuNTU0IDExNC42NzQgMTU5LjE3MiAxMTUuMDU3IDE1OC42ODggMTE1LjI0N0wxNTAuNDIyIDExOC41MDhDMTQ4LjgzOSAxMTkuMTMyIDE0OC44MzkgMTIxLjM3MiAxNTAuNDIyIDEyMS45OTZMMTU4LjY4OCAxMjUuMjU2QzE1OS4xNzIgMTI1LjQ0NyAxNTkuNTU0IDEyNS44MjkgMTU5Ljc0NSAxMjYuMzEzTDE2My4wMDUgMTM0LjU3OUMxNjMuNjI5IDEzNi4xNjIgMTY1Ljg2OSAxMzYuMTYyIDE2Ni40OTQgMTM0LjU3OUwxNjkuNzU0IDEyNi4zMTNDMTY5Ljk0NCAxMjUuODI5IDE3MC4zMjcgMTI1LjQ0NyAxNzAuODEgMTI1LjI1NkwxNzkuMDc3IDEyMS45OTZDMTgwLjY2IDEyMS4zNzIgMTgwLjY2IDExOS4xMzIgMTc5LjA3NyAxMTguNTA4TDE3MC44MSAxMTUuMjQ3QzE3MC4zMjcgMTE1LjA1NyAxNjkuOTQ0IDExNC42NzQgMTY5Ljc1NCAxMTQuMTkxTDE2Ni40OTQgMTA1LjkyNFoiIGZpbGw9IiM4RjhGOEYiLz4KPHBhdGggZD0iTTEzMy4wMDUgMTI4LjQyNEMxMzMuNjI5IDEyNi44NDIgMTM1Ljg2OSAxMjYuODQyIDEzNi40OTQgMTI4LjQyNEwxNDEuODc1IDE0Mi4wN0MxNDIuMDY2IDE0Mi41NTMgMTQyLjQ0OCAxNDIuOTM1IDE0Mi45MzIgMTQzLjEyNkwxNTYuNTc3IDE0OC41MDhDMTU4LjE2IDE0OS4xMzIgMTU4LjE2IDE1MS4zNzIgMTU2LjU3NyAxNTEuOTk2TDE0Mi45MzIgMTU3LjM3OEMxNDIuNDQ4IDE1Ny41NjggMTQyLjA2NiAxNTcuOTUxIDE0MS44NzUgMTU4LjQzNEwxMzYuNDk0IDE3Mi4wNzlDMTM1Ljg2OSAxNzMuNjYyIDEzMy42MjkgMTczLjY2MiAxMzMuMDA1IDE3Mi4wNzlMMTI3LjYyMyAxNTguNDM0QzEyNy40MzMgMTU3Ljk1MSAxMjcuMDUgMTU3LjU2OCAxMjYuNTY3IDE1Ny4zNzhMMTEyLjkyMiAxNTEuOTk2QzExMS4zMzkgMTUxLjM3MiAxMTEuMzM5IDE0OS4xMzIgMTEyLjkyMiAxNDguNTA4TDEyNi41NjcgMTQzLjEyNkMxMjcuMDUgMTQyLjkzNSAxMjcuNDMzIDE0Mi41NTMgMTI3LjYyMyAxNDIuMDdMMTMzLjAwNSAxMjguNDI0WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTk1Ljk5OSAxODQuMDA0VjE5MS41MDJDMTk1Ljk5OSAxOTQuMjYzIDE5My43NjEgMTk2LjUwMiAxOTAuOTk5IDE5Ni41MDJIMTQ3LjY2OEwxNzIuODc5IDE1OC42ODRDMTc0LjM2MyAxNTYuNDU4IDE3Ny42MzUgMTU2LjQ1OCAxNzkuMTIgMTU4LjY4NEwxOTUuOTk5IDE4NC4wMDRaIiBmaWxsPSIjOEY4RjhGIi8+CjwvZz4KPC9zdmc+Cg==",Ce=so;function lo(e,t,r){switch(t){case"image":return uo(e,r[t]);case"video":return co(e,r[t]);case"sticker":return po(e,r[t]);default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function uo(e,t){let r=t.width,i=t.height;return{id:e,meta:{previewUri:Ce,fillType:"//ly.img.ubq/fill/image",kind:"image",width:r,height:i}}}function co(e,t){let r=t.width,i=t.height;return{id:e,label:t.label,meta:{previewUri:Ce,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:r,height:i}}}function po(e,t){let r=t.width,i=t.height;return{id:e,meta:{previewUri:Ce,fillType:"//ly.img.ubq/fill/image",kind:"sticker",width:r,height:i}}}var go=lo;async function fo(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 ho(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 mo(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 bo(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 yo(e,r[t],i)}default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function ho(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 mo(e,t,r){let i=t.width,n=t.height,o=await to(r.url,0);return{id:e,label:t.label,meta:{uri:r.url,thumbUri:o,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:i,height:n}}}function bo(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 yo(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 ft=fo;function vo(e){switch(e.userFlow){case"placeholder":return ko(e);case"generation-only":return wo(e);default:throw new Error(`Unknown user flow: ${e.userFlow}. Expected 'placeholder' or 'generation-only'.`)}}function wo(e){let{cesdk:t,abortSignal:r}=e;return async i=>{try{let n=e.kind,o=await e.getBlockInput(i);if(C(t,r))return{status:"aborted"};let a=await e.generate(i,{middlewares:[...e.middlewares??[]],debug:e.debug,dryRun:e.dryRun,abortSignal:r});if(C(t,r))return{status:"aborted"};if(a.status!=="success")return a;if(a.type==="async")throw new Error("Async generation is not supported in this context yet.");if(C(t,r))return{status:"aborted"};if(e.historyAssetSourceId!=null){let s=dt(),u=await ft(s,n,o,a.output),l={...u,id:`${Date.now()}-${u.id}`,label:u.label!=null?{en:u.label}:{},tags:{}};t.engine.asset.addAssetToSource(e.historyAssetSourceId,l)}else e.debug&&console.log("No asset source ID found in history and generation only was requested. Doing nothing. If no middleware is adding functionality this could be a bug.");return a}catch(n){return{status:"error",message:n instanceof Error?n.message:String(n)}}}}function ko(e){let{cesdk:t,abortSignal:r}=e,i;return async n=>{try{let o=e.kind,a=await e.getBlockInput(n);if(C(t,r))return{status:"aborted"};let s=dt(),u=go(s,o,a);if(i=await Xn(t,u),C(t,r,i))return{status:"aborted"};if(i!=null&&e.kind==="video"){let d=t.engine.block.getPositionX(i),p=t.engine.block.getPositionY(i),g=t.engine.block.duplicate(i);t.engine.block.setPositionX(g,d),t.engine.block.setPositionY(g,p),t.engine.block.destroy(i),i=g}if(i==null)throw new Error("Could not create placeholder block");t.engine.block.setState(i,{type:"Pending",progress:0});let l=await e.generate(n,{middlewares:[...e.middlewares??[]],debug:e.debug,dryRun:e.dryRun,abortSignal:r});if(C(t,r,i))return{status:"aborted"};if(l.status!=="success")return l;if(l.type==="async")throw new Error("Async generation is not supported in this context yet.");if(!t.engine.block.isValid(i))return{status:"aborted",message:"Placeholder block was destroyed before generation completed."};let c=await ft(s,o,a,l.output);if(C(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),C(t,r,i))return{status:"aborted"};if(e.historyAssetSourceId!=null){let d={...c,id:`${Date.now()}-${c.id}`,label:c.label!=null?{en:c.label}:{},tags:{}};t.engine.asset.addAssetToSource(e.historyAssetSourceId,d)}return t.engine.block.isValid(i)&&t.engine.block.setState(i,{type:"Ready"}),l}catch(o){return i!=null&&t.engine.block.isValid(i)&&(xe(o)?t.engine.block.destroy(i):t.engine.block.setState(i,{type:"Error",error:"Unknown"})),{status:"error",message:o instanceof Error?o.message:String(o)}}}}function C(e,t,r){return t.aborted?(r!=null&&e.engine.block.isValid(r)&&e.engine.block.destroy(r),!0):!1}var Io=vo;function Ee(e){return`${e}.generating`}function Ao(e){return`${e}.abort`}function xo(e,t,r,i,n,o,a){let{builder:s,experimental:u}=e,{cesdk:l,includeHistoryLibrary:c=!0}=o,{id:d,output:{abortable:p}}=t,g=u.global(Ao(d),()=>{}),h=u.global(Ee(d),!1),b,m=h.value&&p,f=()=>{m&&(g.value(),h.setValue(!1),g.setValue(()=>{}))},N;if(o.requiredInputs!=null&&o.requiredInputs.length>0){let I=i();N=o.requiredInputs.every(k=>!I.input[k])}let y=u.global(`${d}.confirmationDialogId`,void 0);s.Section(`${d}.generate.section`,{children:()=>{s.Button(`${d}.generate`,{label:["common.generate",`panel.${d}.generate`],isLoading:h.value,color:"accent",isDisabled:N,suffix:m?{icon:"@imgly/Cross",color:"danger",tooltip:[`panel.${d}.abort`,"common.cancel"],onClick:()=>{let I=l.ui.showDialog({type:"warning",content:"panel.ly.img.ai.generation.confirmCancel.content",cancel:{label:"common.close",onClick:({id:k})=>{l.ui.closeDialog(k),y.setValue(void 0)}},actions:{label:"panel.ly.img.ai.generation.confirmCancel.confirm",color:"danger",onClick:({id:k})=>{f(),l.ui.closeDialog(k),y.setValue(void 0)}}});y.setValue(I)}}:void 0,onClick:async()=>{b=new AbortController;let I=b.signal;await(async()=>{try{h.setValue(!0),g.setValue(()=>{a.debug&&console.log("Aborting generation"),b?.abort()});let k=await Io({kind:t.kind,generate:r,historyAssetSourceId:o.historyAssetSourceId,userFlow:o.createPlaceholderBlock?"placeholder":"generation-only",getBlockInput:n,abortSignal:I,cesdk:l,debug:a.debug,dryRun:a.dryRun})(i().input);if(k.status==="aborted")return;if(k.status==="error"){Je(k.message,{cesdk:l,provider:t,getInput:i});return}if(k.status==="success"&&k.type==="sync"){let E=t.output.notification;So(l,E,()=>({input:i().input,output:k.output}))}}catch(k){if(xe(k))return;Je(k,{cesdk:l,provider:t,getInput:i})}finally{b=void 0,h.setValue(!1),g.setValue(()=>{}),y.value!=null&&(l.ui.closeDialog(y.value),y.setValue(void 0))}})()}}),t.output.generationHintText!=null&&s.Text(`${d}.generation-hint`,{align:"center",content:t.output.generationHintText})}}),c&&o.historyAssetLibraryEntryId!=null&&s.Library(`${d}.history.library`,{entries:[o.historyAssetLibraryEntryId]})}function So(e,t,r){let i=t?.success;if(i==null||!(typeof i.show=="function"?i.show(r()):i.show))return!1;let n=typeof i.message=="function"?i.message(r()):i.message??"common.ai-generation.success",o=i.action!=null?{label:typeof i.action.label=="function"?i.action.label(r()):i.action.label,onClick:()=>{i?.action?.onClick(r())}}:void 0;return e.ui.showNotification({type:"success",message:n,action:o,duration:i.duration}),!0}var ht=xo;async function Co({options:e,provider:t,panelInput:r,config:i},n){if(r==null)return;let{cesdk:o}=e,{id:a}=t,s=r.render;return u=>{let{state:l}=u,c=l(Ee(a),{isGenerating:!1,abort:()=>{}}).value.isGenerating,{getInput:d,getBlockInput:p}=s(u,{cesdk:o,isGenerating:c});return ht(u,t,n,d,p,{...e,includeHistoryLibrary:r.includeHistoryLibrary??!0,createPlaceholderBlock:r.userFlow==="placeholder"},i),d}}var Eo=Co;function mt(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 Y(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=mt(e,t.$ref),n={...Y(e,i,r)};for(let o in t)Object.prototype.hasOwnProperty.call(t,o)&&o!=="$ref"&&(n[o]=Y(e,t[o],r));return n}if(Array.isArray(t))return t.map(i=>Y(e,i,r));if(typeof t=="object"){let i={};for(let n in t)Object.prototype.hasOwnProperty.call(t,n)&&(i[n]=Y(e,t[n],r));return i}return t}function Mo(e){return Y(e,{...e})}function jo(e,t=!1){let r=a=>(t&&console.log(`OpenAPI Schema validation failed: ${a}`),!1);if(typeof e!="object"||e===null)return r(`Input is ${e===null?"null":typeof e}, not an object`);let i=e;if(!(typeof i.type=="string"||Array.isArray(i.enum)||typeof i.properties=="object"||typeof i.items=="object"||typeof i.allOf=="object"||typeof i.anyOf=="object"||typeof i.oneOf=="object"||typeof i.not=="object"))return r("Missing required schema-defining properties (type, enum, properties, items, allOf, anyOf, oneOf, not)");if(i.type!==void 0){let a=["string","number","integer","boolean","array","object","null"];if(typeof i.type=="string"){if(!a.includes(i.type))return r(`Invalid type: ${i.type}. Must be one of ${a.join(", ")}`)}else if(Array.isArray(i.type)){for(let s of i.type)if(typeof s!="string"||!a.includes(s))return r(`Array of types contains invalid value: ${s}. Must be one of ${a.join(", ")}`)}else return r(`Type must be a string or array of strings, got ${typeof i.type}`)}if(i.items!==void 0&&(typeof i.items!="object"||i.items===null))return r(`Items must be an object, got ${i.items===null?"null":typeof i.items}`);if(i.properties!==void 0&&(typeof i.properties!="object"||i.properties===null))return r(`Properties must be an object, got ${i.properties===null?"null":typeof i.properties}`);let n=["allOf","anyOf","oneOf"];for(let a of n)if(i[a]!==void 0){if(!Array.isArray(i[a]))return r(`${a} must be an array, got ${typeof i[a]}`);for(let s=0;s<i[a].length;s++){let u=i[a][s];if(typeof u!="object"||u===null)return r(`Item ${s} in ${a} 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 o=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf"];for(let a of o)if(i[a]!==void 0&&typeof i[a]!="number")return r(`${a} must be a number, got ${typeof i[a]}`);if(i.minLength!==void 0&&(typeof i.minLength!="number"||i.minLength<0))return r(`minLength must be a non-negative number, got ${typeof i.minLength=="number"?i.minLength:typeof i.minLength}`);if(i.maxLength!==void 0&&(typeof i.maxLength!="number"||i.maxLength<0))return r(`maxLength must be a non-negative number, got ${typeof i.maxLength=="number"?i.maxLength:typeof i.maxLength}`);if(i.pattern!==void 0&&typeof i.pattern!="string")return r(`pattern must be a string, got ${typeof i.pattern}`);if(i.minItems!==void 0&&(typeof i.minItems!="number"||i.minItems<0))return r(`minItems must be a non-negative number, got ${typeof i.minItems=="number"?i.minItems:typeof i.minItems}`);if(i.maxItems!==void 0&&(typeof i.maxItems!="number"||i.maxItems<0))return r(`maxItems must be a non-negative number, got ${typeof i.maxItems=="number"?i.maxItems:typeof i.maxItems}`);if(i.uniqueItems!==void 0&&typeof i.uniqueItems!="boolean")return r(`uniqueItems must be a boolean, got ${typeof i.uniqueItems}`);if(i.minProperties!==void 0&&(typeof i.minProperties!="number"||i.minProperties<0))return r(`minProperties must be a non-negative number, got ${typeof i.minProperties=="number"?i.minProperties:typeof i.minProperties}`);if(i.maxProperties!==void 0&&(typeof i.maxProperties!="number"||i.maxProperties<0))return r(`maxProperties must be a non-negative number, got ${typeof i.maxProperties=="number"?i.maxProperties:typeof i.maxProperties}`);if(i.required!==void 0){if(!Array.isArray(i.required))return r(`required must be an array, got ${typeof i.required}`);for(let a=0;a<i.required.length;a++){let s=i.required[a];if(typeof s!="string")return r(`Item ${a} in required array must be a string, got ${typeof s}`)}}return!0}function _o(e,t){if(e.properties==null)throw new Error("Input schema must have properties");let r=e.properties,i=[];return Lo(e,t).forEach(n=>{let o=n,a=r[n]??void 0;i.push({id:o,schema:a})}),i}function Lo(e,t){let r=t.order;if(r!=null&&Array.isArray(r))return r;if(e.properties==null)throw new Error("Input schema must have properties");let i=e.properties,n=Object.keys(i),o=No(e,t)??n;return r!=null&&typeof r=="function"&&(o=r(o)),[...new Set(o)]}function No(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 bt=_o;function yt(e,t,r,i,n,o){if(t.schema==null)return i.renderCustomProperty!=null&&i.renderCustomProperty[t.id]!=null?i.renderCustomProperty[t.id](e,t):void 0;let a=t,s=t.schema.type;if(i.renderCustomProperty!=null&&i.renderCustomProperty[t.id]!=null)return i.renderCustomProperty[t.id](e,t);switch(s){case"string":return t.schema.enum!=null?Po(e,a,r,i,n,o):wt(e,a,r,i,n,o);case"boolean":return kt(e,a,r,i,n,o);case"number":case"integer":return It(e,a,r,i,n,o);case"object":return vt(e,a,r,i,n,o);case"array":break;case void 0:{if(t.schema.anyOf!=null&&Array.isArray(t.schema.anyOf))return Oo(e,a,r,i,n,o);break}default:console.error(`Unsupported property type: ${s}`)}}function vt(e,t,r,i,n,o){let a=bt(t.schema??{},i).reduce((s,u)=>{let l=yt(e,u,r,i,n,o);return l!=null&&(s[u.id]=l()),s},{});return()=>({id:t.id,type:"object",value:a})}function wt(e,t,r,i,n,o){let{builder:a,experimental:{global:s}}=e,{id:u}=t,l=`${r.id}.${u}`,c=t.schema.title??l,d=s(l,t.schema.default??""),p=$o(t.schema),g=p?.component!=null&&p?.component==="TextArea"?"TextArea":"TextInput";return a[g](l,{inputLabel:c,placeholder:n.i18n?.prompt,...d}),()=>({id:t.id,type:"string",value:d.value})}function Po(e,t,r,i,n,o){let{builder:a,experimental:{global:s}}=e,{id:u}=t,l=`${r.id}.${u}`,c=t.schema.title??l,d=t.schema.enum!=null&&"x-imgly-enum-labels"in t.schema.enum&&typeof t.schema.enum["x-imgly-enum-labels"]=="object"?t.schema.enum["x-imgly-enum-labels"]:"x-imgly-enum-labels"in t.schema&&typeof t.schema["x-imgly-enum-labels"]=="object"?t.schema["x-imgly-enum-labels"]:{},p="x-imgly-enum-icons"in t.schema&&typeof t.schema["x-imgly-enum-icons"]=="object"?t.schema["x-imgly-enum-icons"]:{},g=(t.schema.enum??[]).map(m=>({id:m,label:d[m]??pt(m),icon:p[m]})),h=t.schema.default!=null?g.find(m=>m.id===t.schema.default)??g[0]:g[0],b=s(l,h);return a.Select(l,{inputLabel:c,values:g,...b}),()=>({id:t.id,type:"string",value:b.value.id})}function kt(e,t,r,i,n,o){let{builder:a,experimental:{global:s}}=e,{id:u}=t,l=`${r.id}.${u}`,c=t.schema.title??l,d=!!t.schema.default,p=s(l,d);return a.Checkbox(l,{inputLabel:c,...p}),()=>({id:t.id,type:"boolean",value:p.value})}function It(e,t,r,i,n,o){let{builder:a,experimental:{global:s}}=e,{id:u}=t,l=`${r.id}.${u}`,c=t.schema.title??l,d=t.schema.minimum,p=t.schema.maximum,g=t.schema.default;g==null&&(d!=null?g=d:p!=null?g=p:g=0);let h=s(l,g);if(d!=null&&p!=null){let b=t.schema.type==="number"?.1:1;"x-imgly-step"in t.schema&&typeof t.schema["x-imgly-step"]=="number"&&(b=t.schema["x-imgly-step"]),a.Slider(l,{inputLabel:c,min:d,max:p,step:b,...h})}else a.NumberInput(l,{inputLabel:c,min:d,max:p,...h});return()=>({id:t.id,type:"integer",value:h.value})}function Oo(e,t,r,i,n,o){let{builder:a,experimental:{global:s}}=e,{id:u}=t,l=`${r.id}.${u}`,c=t.schema.title??l,d=t.schema.anyOf??[],p=[],g={},h={};d.forEach((f,N)=>{let y=f.title??"common.custom",I=`${r.id}.${u}.anyOf[${N}]`,k="x-imgly-enum-labels"in t.schema&&typeof t.schema["x-imgly-enum-labels"]=="object"?t.schema["x-imgly-enum-labels"]:{},E="x-imgly-enum-icons"in t.schema&&typeof t.schema["x-imgly-enum-icons"]=="object"?t.schema["x-imgly-enum-icons"]:{};f.type==="string"?f.enum!=null?f.enum.forEach(ae=>{p.push({id:ae,label:k[ae]??pt(ae),icon:E[ae]})}):(g[I]=()=>wt(e,{id:I,schema:{...f,title:y}},r,i,n,o),p.push({id:I,label:k[y]??y,icon:E[y]})):f.type==="boolean"?(g[I]=()=>kt(e,{id:I,schema:{...f,title:y}},r,i,n,o),p.push({id:I,label:k[y]??y,icon:E[y]})):f.type==="integer"?(g[I]=()=>It(e,{id:I,schema:{...f,title:y}},r,i,n,o),p.push({id:I,label:k[y]??y,icon:E[y]})):f.type==="array"||f.type==="object"&&(g[I]=()=>vt(e,{id:I,schema:{...f,title:y}},r,i,n,o),p.push({id:I,label:k[y]??y,icon:E[y]}))});let b=t.schema.default!=null?p.find(f=>f.id===t.schema.default)??p[0]:p[0],m=s(l,b);if(a.Select(l,{inputLabel:c,values:p,...m}),m.value.id in g){let f=g[m.value.id]();h[m.value.id]=f}return()=>{let f=h[m.value.id];return f!=null?{...f(),id:t.id}:{id:t.id,type:"string",value:m.value.id}}}function $o(e){if("x-imgly-builder"in e)return e["x-imgly-builder"]}var Do=yt;async function To({options:e,provider:t,panelInput:r,config:i},n){let{id:o}=t;if(r==null)return;i.debug&&console.log(`Registering schema-based panel input for provider ${o}`);let a=Mo(r.document),s=mt(a,r.inputReference);if(!jo(s,i.debug))throw new Error(`Input reference '${r.inputReference}' does not resolve to a valid OpenAPI schema`);let u=s,l=bt(u,r);return c=>{let{builder:d}=c,p=[];d.Section(`${o}.schema.section`,{children:()=>{l.forEach(m=>{let f=Do(c,m,t,r,e,i);f!=null&&(Array.isArray(f)?p.push(...f):p.push(f))})}});let g=p.map(m=>m()),h=m=>m.type==="object"?Object.entries(m.value).reduce((f,[N,y])=>(f[N]=h(y),f),{}):m.value,b=g.reduce((m,f)=>(m[f.id]=h(f),m),{});ht(c,t,n,()=>({input:b}),()=>r.getBlockInput(b),{...e,requiredInputs:u.required,createPlaceholderBlock:r.userFlow==="placeholder"},i)}}var zo=To;async function Ro(e,t){if(e.panelInput!=null)switch(e.panelInput.type){case"custom":return Eo(e,t);case"schema":return zo(e,t);default:e.config.debug&&console.warn(`Invalid panel input type '${panelInput.type}' - skipping`)}}var Fo=Ro;function Uo(e){let{provider:t,options:{engine:r}}=e,i=t.output.history??"@imgly/local";if(i==null||i===!1)return;let n=r.asset.findAllSources();function o(){let a=`${t.id}.history`;for(;n.includes(a);)a+=`-${Math.random().toString(36).substring(2,6)}`;return a}if(i==="@imgly/local"){let a=o();return r.asset.addLocalSource(a),a}if(i==="@imgly/indexedDB"){let a=o();return r.asset.addSource(new qt(a,r)),a}return i}var Vo=Uo;function Bo(e,t){if(t==null||!t)return;let r=`${e.provider.id}.history`;return e.options.cesdk.ui.addAssetLibraryEntry({id:r,sourceIds:[t],sortBy:{sortKey:"insertedAt",sortingOrder:"Descending"},canRemove:!0,gridItemHeight:"square",gridBackgroundType:"cover"}),r}var Go=Bo,me="@imgly/plugin-ai-generation",Ho=`
5
5
  <svg>
6
6
  <symbol
7
7
  fill="none"
@@ -63,7 +63,7 @@ Consider updating all AI plugins to the same version for optimal compatibility.`
63
63
  </symbol>
64
64
  </svg>
65
65
  `,qo=Ho;function Zo(e){return async(t,r,i)=>e.enable?(console.log(`[DRY RUN]: Requesting dummy AI generation for kind '${e.kind}' with inputs: `,JSON.stringify(t,void 0,2)),await At(2e3),await Yo(t,e,r)):i(t,r)}async function Yo(e,t,r){switch(t.kind){case"image":return Qo(e,t,r);case"video":return Wo(e,t,r);case"text":return Ko(e,t,r);case"audio":return Xo(e,t,r);default:throw new Error(`Unsupported output kind for creating dry run output: ${t.kind}`)}}async function Qo(e,t,{engine:r}){let i,n,o=e!=null&&typeof e=="object"&&"prompt"in e&&typeof e.prompt=="string"?e.prompt:"AI Generated Image",a=o.match(/(\d+)x(\d+)/);if(a!=null)i=parseInt(a[1],10),n=parseInt(a[2],10);else if(t.blockInputs!=null&&(i=t.blockInputs.image.width,n=t.blockInputs.image.height),t.blockIds!=null&&Array.isArray(t.blockIds)&&t.blockIds.length>0){let[s]=t.blockIds,u=await qn(s,r),l=await Hn(u,r);i=l.width,n=l.height}else i=512,n=512;return{kind:"image",url:`https://placehold.co/${i}x${n}/000000/FFF?text=${o.replace(" ","+").replace(`
66
- `,"+")}`}}async function Wo(e,t,r){return Promise.resolve({kind:"video",url:"https://storage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"})}async function Ko(e,t,r){let i="";if(t.blockIds&&t.blockIds.length>0){let[a]=t.blockIds;r.engine.block.isValid(a)&&(i=r.engine.block.getString(a,"text/text"))}if(!i&&e!=null&&typeof e=="object"&&"prompt"in e&&typeof e.prompt=="string"){let a=e.prompt,s=a.match(/text:\s*"([^"]+)"/i)||a.match(/content:\s*"([^"]+)"/i)||a.match(/"([^"]+)"/);s&&s[1]&&(i=s[1])}let n=i.length||50,o="";if(e!=null&&typeof e=="object")if("language"in e&&typeof e.language=="string")o=Z(n,"translation");else if("type"in e&&typeof e.type=="string"){let a=e.type;o=Z(n,a)}else"customPrompt"in e?o=Z(n,"custom"):o=Z(n,"improved");else o=Z(n,"generated");return Jo(o,r.abortSignal)}async function*Jo(e,t){let r=Math.max(1,Math.ceil(e.length/20)),i=0;for(;i<e.length;){if(t?.aborted)return;let n=Math.min(i+r,e.length);yield{kind:"text",text:e.substring(0,n)},i=n,i<e.length&&await At(100)}return{kind:"text",text:e}}function Z(e,t){let r="[DRY RUN - Dummy Text] ",i=r.length;if(e<=i)return r.substring(0,e);let n=e-i,o={translation:"Ceci est un texte fictif traduit qui maintient la longueur approximative.",professional:"Enhanced professional content with improved clarity and structure.",casual:"Relaxed, friendly text that keeps things simple and approachable.",formal:"Refined formal documentation that preserves original structure.",humorous:"Amusing content that brings lighthearted fun to the text.",improved:"Enhanced text that demonstrates better clarity and readability.",custom:"Customized content reflecting the requested modifications.",generated:"AI-generated content maintaining original length and structure."},a=o[t]||o.generated,s="";if(n<=a.length)s=a.substring(0,n);else{s=a;let u=[" Additional content continues with similar phrasing."," Further elaboration maintains the established tone."," Extended content preserves the original style."," Continued text follows the same pattern."],l=0;for(;s.length<n;){let c=u[l%u.length];if(s.length+c.length<=n)s+=c;else{s+=c.substring(0,n-s.length);break}l++}}return r+s}async function Xo(e,t,r){let i=3;if(e!=null&&typeof e=="object"){if("duration"in e&&typeof e.duration=="number")i=e.duration;else if("prompt"in e&&typeof e.prompt=="string"){let n=e.prompt.match(/(\d+)\s*(?:seconds?|secs?|s)\b/i);n&&(i=parseInt(n[1],10))}}return t.blockInputs?.audio?.duration&&(i=t.blockInputs.audio.duration),{kind:"audio",url:ea(220,i),duration:i,thumbnailUrl:void 0}}function ea(e,t){let r=Math.floor(44100*t),i=new Float32Array(r);for(let n=0;n<r;n++)i[n]=Math.sin(2*Math.PI*e*n/44100);return ta(i,44100)}function ta(e,t){let r=e.length,i=2,n=1,o=n*i,a=t*o,s=r*i,u=44+s,l=new ArrayBuffer(u),c=new DataView(l),d=(b,m)=>{for(let f=0;f<m.length;f++)c.setUint8(b+f,m.charCodeAt(f))};d(0,"RIFF"),c.setUint32(4,u-8,!0),d(8,"WAVE"),d(12,"fmt "),c.setUint32(16,16,!0),c.setUint16(20,1,!0),c.setUint16(22,n,!0),c.setUint32(24,t,!0),c.setUint32(28,a,!0),c.setUint16(32,o,!0),c.setUint16(34,16,!0),d(36,"data"),c.setUint32(40,s,!0);let p=44;for(let b=0;b<r;b++){let m=Math.max(-1,Math.min(1,e[b])),f=Math.round(m*32767);c.setInt16(p,f,!0),p+=2}let g=new Uint8Array(l),h="";for(let b=0;b<g.length;b++)h+=String.fromCharCode(g[b]);return`data:audio/wav;base64,${btoa(h)}`}async function At(e){return new Promise(t=>{setTimeout(t,e)})}var ra=Zo,ia="USER_CANCEL";function na(e){return async(t,r)=>{if(r?.abortSignal?.aborted)return{status:"aborted"};let i=Wn([...e.provider.output.middleware??[],...r?.middlewares??[],Jn({enable:r?.debug}),ra({enable:r?.dryRun,kind:e.provider.kind})]);try{let{result:n}=await i(e.provider.output.generate)(t,{abortSignal:r?.abortSignal,engine:e.engine,cesdk:e.cesdk});return r?.abortSignal?.aborted?{status:"aborted"}:n instanceof Error?{status:"error",message:n.message}:n==null?{status:"error",message:"No output generated"}:ro(n)?{status:"success",type:"async",output:n}:{status:"success",type:"sync",output:n}}catch(n){return xe(n)?{status:"aborted",message:n.message}:n===ia?{status:"aborted",message:n}:{status:"error",message:n instanceof Error?n.message:String(n)}}}}var oa=na;async function aa(e,t,r,i){let n={...i,provider:t},o={provider:t,panelInput:t.input?.panel,options:{cesdk:r.cesdk,engine:r.cesdk.engine},config:n};await t.initialize?.({...r,engine:r.cesdk.engine});let a=Vo(o),s=Go(o,a);o.options.historyAssetSourceId=a,o.options.historyAssetLibraryEntryId=s;let u=oa({provider:t,cesdk:r.cesdk,engine:r.cesdk.engine}),l=await Fo(o,u);io(r.cesdk,"@imgly/plugin-ai-generation",qo);let c={provider:t,panel:{builderRenderFunction:l},history:{assetSourceId:a,assetLibraryEntryId:s},generate:u};return Qn.get().register(c),c}var be=aa;function sa(e){let{kind:t,cesdk:r,historAssetSourceIds:i}=e,n=`ly.img.ai.${t}-generation.history`;if(r.engine.asset.findAllSources().includes(n))return n;let o=new Zt(n,r,i);return r.engine.asset.addSource(o),o.id}var la=sa;async function ua(e,t,r,i){let n,o=[];if(Array.isArray(t)){let s=await Promise.all(t.map(u=>be(e,u,r,i)));o.push(...s),n=da({prefix:e,providerInitializationResults:o})}else{let s=await Promise.all(t.fromText.map(l=>be(e,l,r,i)));o.push(...s);let u=await Promise.all(t.fromImage.map(l=>be(e,l,r,i)));o.push(...u),n=ca({prefix:`ly.img.ai.${e}-generation`,initializedFromTextProviders:s,initializedFromImageProviders:u})}let a=la({kind:e,cesdk:r.cesdk,historAssetSourceIds:o.map(s=>s.history?.assetSourceId).filter(Yn)});return{panel:{builderRenderFunction:n},history:{assetSourceId:a},providerInitializationResults:o}}function ca({prefix:e,initializedFromTextProviders:t,initializedFromImageProviders:r}){let i=t.length>0&&r.length>0;return n=>{let{builder:o,experimental:a}=n,s=a.global(`${e}.fromType`,i?"fromText":void 0),u=[];s.value==="fromText"?u.push(...t):s.value==="fromImage"?u.push(...r):u.push(...t,...r);let l=t.map(({provider:h,panel:b})=>({id:h.id,label:h.name??h.id,builderRenderFunction:b?.builderRenderFunction})),c=r.map(({provider:h,panel:b})=>({id:h.id,label:h.name??h.id,builderRenderFunction:b?.builderRenderFunction})),d=n.experimental.global(`${e}.selectedProvider.fromText`,l[0]),p=n.experimental.global(`${e}.selectedProvider.fromImage`,c[0]),g=s.value==="fromText"?d:s.value==="fromImage"?p:void 0;if((i||u.length>1)&&o.Section(`${e}.providerSelection.section`,{children:()=>{if(i&&o.ButtonGroup(`${e}.fromType.buttonGroup`,{inputLabel:"Input",children:()=>{o.Button(`${e}.fromType.buttonGroup.fromText`,{label:"Text",icon:s.value!=="fromText"&&Xe(t,n)?"@imgly/LoadingSpinner":void 0,isActive:s.value==="fromText",onClick:()=>{s.setValue("fromText")}}),o.Button(`${e}.fromType.buttonGroup.fromImage`,{label:"Image",icon:s.value!=="fromImage"&&Xe(r,n)?"@imgly/LoadingSpinner":void 0,isActive:s.value==="fromImage",onClick:()=>{s.setValue("fromImage")}})}}),u.length>1){let h=s.value==="fromText"?l:s.value==="fromImage"?c:[...l,...c];g!=null&&o.Select(`${e}.providerSelect.select`,{inputLabel:"Provider",values:h,...g})}}}),u.length>1)g?.value.builderRenderFunction?.(n);else{let h=u[0];h&&h.panel?.builderRenderFunction?.(n)}}}function da({prefix:e,providerInitializationResults:t}){return r=>{let{builder:i}=r;if(t.length===0)return;let n=t.map(({provider:a,panel:s})=>({id:a.id,label:a.name??a.id,builderRenderFunction:s?.builderRenderFunction})),o=r.state(`${e}.selectedProvider`,n[0]);t.length>1&&o!=null&&i.Section(`${e}.providerSelection.section`,{children:()=>{i.Select(`${e}.providerSelect.select`,{inputLabel:"Provider",values:n,...o})}}),o.value.builderRenderFunction?.(r)}}function Xe(e,t){return e.length===0?!1:e.some(({provider:r})=>r.id==null?!1:t.experimental.global(Ee(r.id),!1).value)}var Me=ua;var pa=typeof global=="object"&&global&&global.Object===Object&&global,zt=pa,ga=typeof self=="object"&&self&&self.Object===Object&&self,fa=zt||ga||Function("return this")(),x=fa,ha=x.Symbol,U=ha,Rt=Object.prototype,ma=Rt.hasOwnProperty,ba=Rt.toString,ee=U?U.toStringTag:void 0;function ya(e){var t=ma.call(e,ee),r=e[ee];try{e[ee]=void 0;var i=!0}catch{}var n=ba.call(e);return i&&(t?e[ee]=r:delete e[ee]),n}var va=ya,wa=Object.prototype,ka=wa.toString;function Ia(e){return ka.call(e)}var Aa=Ia,xa="[object Null]",Sa="[object Undefined]",xt=U?U.toStringTag:void 0;function Ca(e){return e==null?e===void 0?Sa:xa:xt&&xt in Object(e)?va(e):Aa(e)}var ne=Ca;function Ea(e){return e!=null&&typeof e=="object"}var De=Ea,Lu=Array.isArray;function Ma(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var Ft=Ma,ja="[object AsyncFunction]",_a="[object Function]",La="[object GeneratorFunction]",Na="[object Proxy]";function Pa(e){if(!Ft(e))return!1;var t=ne(e);return t==_a||t==La||t==ja||t==Na}var Oa=Pa,$a=x["__core-js_shared__"],je=$a,St=function(){var e=/[^.]+$/.exec(je&&je.keys&&je.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function Da(e){return!!St&&St in e}var Ta=Da,za=Function.prototype,Ra=za.toString;function Fa(e){if(e!=null){try{return Ra.call(e)}catch{}try{return e+""}catch{}}return""}var j=Fa,Ua=/[\\^$.*+?()[\]{}|]/g,Va=/^\[object .+?Constructor\]$/,Ba=Function.prototype,Ga=Object.prototype,Ha=Ba.toString,qa=Ga.hasOwnProperty,Za=RegExp("^"+Ha.call(qa).replace(Ua,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Ya(e){if(!Ft(e)||Ta(e))return!1;var t=Oa(e)?Za:Va;return t.test(j(e))}var Qa=Ya;function Wa(e,t){return e?.[t]}var Ka=Wa;function Ja(e,t){var r=Ka(e,t);return Qa(r)?r:void 0}var V=Ja,Xa=V(x,"WeakMap"),Le=Xa;function es(e,t){return e===t||e!==e&&t!==t}var ts=es,rs=9007199254740991;function is(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=rs}var ns=is;var Nu=Object.prototype;var os="[object Arguments]";function as(e){return De(e)&&ne(e)==os}var Ct=as,Ut=Object.prototype,ss=Ut.hasOwnProperty,ls=Ut.propertyIsEnumerable,Pu=Ct(function(){return arguments}())?Ct:function(e){return De(e)&&ss.call(e,"callee")&&!ls.call(e,"callee")};var Vt=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Et=Vt&&typeof module=="object"&&module&&!module.nodeType&&module,us=Et&&Et.exports===Vt,Mt=us?x.Buffer:void 0,Ou=Mt?Mt.isBuffer:void 0;var cs="[object Arguments]",ds="[object Array]",ps="[object Boolean]",gs="[object Date]",fs="[object Error]",hs="[object Function]",ms="[object Map]",bs="[object Number]",ys="[object Object]",vs="[object RegExp]",ws="[object Set]",ks="[object String]",Is="[object WeakMap]",As="[object ArrayBuffer]",xs="[object DataView]",Ss="[object Float32Array]",Cs="[object Float64Array]",Es="[object Int8Array]",Ms="[object Int16Array]",js="[object Int32Array]",_s="[object Uint8Array]",Ls="[object Uint8ClampedArray]",Ns="[object Uint16Array]",Ps="[object Uint32Array]",w={};w[Ss]=w[Cs]=w[Es]=w[Ms]=w[js]=w[_s]=w[Ls]=w[Ns]=w[Ps]=!0;w[cs]=w[ds]=w[As]=w[ps]=w[xs]=w[gs]=w[fs]=w[hs]=w[ms]=w[bs]=w[ys]=w[vs]=w[ws]=w[ks]=w[Is]=!1;function Os(e){return De(e)&&ns(e.length)&&!!w[ne(e)]}var $s=Os;function Ds(e){return function(t){return e(t)}}var Ts=Ds,Bt=typeof exports=="object"&&exports&&!exports.nodeType&&exports,te=Bt&&typeof module=="object"&&module&&!module.nodeType&&module,zs=te&&te.exports===Bt,_e=zs&&zt.process,Rs=function(){try{var e=te&&te.require&&te.require("util").types;return e||_e&&_e.binding&&_e.binding("util")}catch{}}(),jt=Rs,_t=jt&&jt.isTypedArray,$u=_t?Ts(_t):$s;var Fs=Object.prototype,Du=Fs.hasOwnProperty;function Us(e,t){return function(r){return e(t(r))}}var Vs=Us,Tu=Vs(Object.keys,Object);var Bs=Object.prototype,zu=Bs.hasOwnProperty;var Gs=V(Object,"create"),re=Gs;function Hs(){this.__data__=re?re(null):{},this.size=0}var qs=Hs;function Zs(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var Ys=Zs,Qs="__lodash_hash_undefined__",Ws=Object.prototype,Ks=Ws.hasOwnProperty;function Js(e){var t=this.__data__;if(re){var r=t[e];return r===Qs?void 0:r}return Ks.call(t,e)?t[e]:void 0}var Xs=Js,el=Object.prototype,tl=el.hasOwnProperty;function rl(e){var t=this.__data__;return re?t[e]!==void 0:tl.call(t,e)}var il=rl,nl="__lodash_hash_undefined__";function ol(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=re&&t===void 0?nl:t,this}var al=ol;function B(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])}}B.prototype.clear=qs;B.prototype.delete=Ys;B.prototype.get=Xs;B.prototype.has=il;B.prototype.set=al;var Lt=B;function sl(){this.__data__=[],this.size=0}var ll=sl;function ul(e,t){for(var r=e.length;r--;)if(ts(e[r][0],t))return r;return-1}var ce=ul,cl=Array.prototype,dl=cl.splice;function pl(e){var t=this.__data__,r=ce(t,e);if(r<0)return!1;var i=t.length-1;return r==i?t.pop():dl.call(t,r,1),--this.size,!0}var gl=pl;function fl(e){var t=this.__data__,r=ce(t,e);return r<0?void 0:t[r][1]}var hl=fl;function ml(e){return ce(this.__data__,e)>-1}var bl=ml;function yl(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 vl=yl;function G(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var i=e[t];this.set(i[0],i[1])}}G.prototype.clear=ll;G.prototype.delete=gl;G.prototype.get=hl;G.prototype.has=bl;G.prototype.set=vl;var de=G,wl=V(x,"Map"),ie=wl;function kl(){this.size=0,this.__data__={hash:new Lt,map:new(ie||de),string:new Lt}}var Il=kl;function Al(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var xl=Al;function Sl(e,t){var r=e.__data__;return xl(t)?r[typeof t=="string"?"string":"hash"]:r.map}var pe=Sl;function Cl(e){var t=pe(this,e).delete(e);return this.size-=t?1:0,t}var El=Cl;function Ml(e){return pe(this,e).get(e)}var jl=Ml;function _l(e){return pe(this,e).has(e)}var Ll=_l;function Nl(e,t){var r=pe(this,e),i=r.size;return r.set(e,t),this.size+=r.size==i?0:1,this}var Pl=Nl;function H(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var i=e[t];this.set(i[0],i[1])}}H.prototype.clear=Il;H.prototype.delete=El;H.prototype.get=jl;H.prototype.has=Ll;H.prototype.set=Pl;var Gt=H;function Ol(){this.__data__=new de,this.size=0}var $l=Ol;function Dl(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var Tl=Dl;function zl(e){return this.__data__.get(e)}var Rl=zl;function Fl(e){return this.__data__.has(e)}var Ul=Fl,Vl=200;function Bl(e,t){var r=this.__data__;if(r instanceof de){var i=r.__data__;if(!ie||i.length<Vl-1)return i.push([e,t]),this.size=++r.size,this;r=this.__data__=new Gt(i)}return r.set(e,t),this.size=r.size,this}var Gl=Bl;function oe(e){var t=this.__data__=new de(e);this.size=t.size}oe.prototype.clear=$l;oe.prototype.delete=Tl;oe.prototype.get=Rl;oe.prototype.has=Ul;oe.prototype.set=Gl;var Hl=Object.prototype,Ru=Hl.propertyIsEnumerable;var ql=V(x,"DataView"),Ne=ql,Zl=V(x,"Promise"),Pe=Zl,Yl=V(x,"Set"),Oe=Yl,Nt="[object Map]",Ql="[object Object]",Pt="[object Promise]",Ot="[object Set]",$t="[object WeakMap]",Dt="[object DataView]",Wl=j(Ne),Kl=j(ie),Jl=j(Pe),Xl=j(Oe),eu=j(Le),F=ne;(Ne&&F(new Ne(new ArrayBuffer(1)))!=Dt||ie&&F(new ie)!=Nt||Pe&&F(Pe.resolve())!=Pt||Oe&&F(new Oe)!=Ot||Le&&F(new Le)!=$t)&&(F=function(e){var t=ne(e),r=t==Ql?e.constructor:void 0,i=r?j(r):"";if(i)switch(i){case Wl:return Dt;case Kl:return Nt;case Jl:return Pt;case Xl:return Ot;case eu:return $t}return t});var Fu=x.Uint8Array;var tu="__lodash_hash_undefined__";function ru(e){return this.__data__.set(e,tu),this}var iu=ru;function nu(e){return this.__data__.has(e)}var ou=nu;function $e(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new Gt;++t<r;)this.add(e[t])}$e.prototype.add=$e.prototype.push=iu;$e.prototype.has=ou;var Tt=U?U.prototype:void 0,Uu=Tt?Tt.valueOf:void 0;var au=Object.prototype,Vu=au.hasOwnProperty;var su=Object.prototype,Bu=su.hasOwnProperty;var Gu=new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,"i"),Hu=new RegExp(/[A-Fa-f0-9]{1}/,"g"),qu=new RegExp(/[A-Fa-f0-9]{2}/,"g");function lu(e){return e==null?[]:Array.isArray(e)?e:[e]}var Te=lu;var S="@imgly/plugin-ai-audio-generation-web";var _="ly.img.ai.audio-generation.speech",L="ly.img.ai.audio-generation.sound";function uu(e){return{async initialize({cesdk:t}){if(t==null)return;gt(t,S,"0.2.2"),t.setTranslations({en:{[`panel.${_}`]:"AI Voice",[`panel.${L}`]:"Sound Generation"}}),cu(e);let r=lt.get(),i=r.register({type:"plugin",sceneMode:"Video",id:`${S}/sound`,pluginId:S,label:"Generate Sound",meta:{panelId:L},execute:()=>{t.ui.isPanelOpen(L)?t.ui.closePanel(L):t.ui.openPanel(L)}}),n=r.register({type:"plugin",sceneMode:"Video",id:`${S}/speech`,pluginId:S,label:"AI Voice",meta:{panelId:_},execute:()=>{t.ui.isPanelOpen(_)?t.ui.closePanel(_):t.ui.openPanel(_)}}),o=e.providers?.text2speech??e.text2speech,a=e.providers?.text2sound??e.text2sound,s=await Promise.all(Te(o).map(g=>g({cesdk:t}))),u=await Promise.all(Te(a).map(g=>g({cesdk:t}))),l=s.length>0,c=u.length>0;if(!l&&!c){i(),n();return}c||i(),l||n();let d=await Me("audio",s,{cesdk:t},e),p=await Me("audio",u,{cesdk:t},e);p.panel.builderRenderFunction!=null?(t.ui.registerPanel(L,p.panel.builderRenderFunction),Se({cesdk:t,panelId:L})):i(),d.panel.builderRenderFunction!=null?(t.ui.registerPanel(_,d.panel.builderRenderFunction),Se({cesdk:t,panelId:_})):n()}}}function cu(e){e.debug&&(e.providers?.text2speech!=null&&e.text2speech!=null&&console.warn("[AudioGeneration]: Both `providers.text2speech` and `text2speech` configuration is provided. Since `text2speech` is deprecated, only `providers.text2speech` will be used."),e.providers?.text2sound!=null&&e.text2sound!=null&&console.warn("[AudioGeneration]: Both `providers.text2sound` and `text2sound` configuration is provided. Since `text2sound` is deprecated, only `providers.text2sound` will be used."))}var Ht=uu;var du=e=>({name:S,version:"0.2.2",...Ht(e)}),rc=du;export{rc as default};
66
+ `,"+")}`}}async function Wo(e,t,r){return Promise.resolve({kind:"video",url:"https://storage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"})}async function Ko(e,t,r){let i="";if(t.blockIds&&t.blockIds.length>0){let[a]=t.blockIds;r.engine.block.isValid(a)&&(i=r.engine.block.getString(a,"text/text"))}if(!i&&e!=null&&typeof e=="object"&&"prompt"in e&&typeof e.prompt=="string"){let a=e.prompt,s=a.match(/text:\s*"([^"]+)"/i)||a.match(/content:\s*"([^"]+)"/i)||a.match(/"([^"]+)"/);s&&s[1]&&(i=s[1])}let n=i.length||50,o="";if(e!=null&&typeof e=="object")if("language"in e&&typeof e.language=="string")o=Z(n,"translation");else if("type"in e&&typeof e.type=="string"){let a=e.type;o=Z(n,a)}else"customPrompt"in e?o=Z(n,"custom"):o=Z(n,"improved");else o=Z(n,"generated");return Jo(o,r.abortSignal)}async function*Jo(e,t){let r=Math.max(1,Math.ceil(e.length/20)),i=0;for(;i<e.length;){if(t?.aborted)return;let n=Math.min(i+r,e.length);yield{kind:"text",text:e.substring(0,n)},i=n,i<e.length&&await At(100)}return{kind:"text",text:e}}function Z(e,t){let r="[DRY RUN - Dummy Text] ",i=r.length;if(e<=i)return r.substring(0,e);let n=e-i,o={translation:"Ceci est un texte fictif traduit qui maintient la longueur approximative.",professional:"Enhanced professional content with improved clarity and structure.",casual:"Relaxed, friendly text that keeps things simple and approachable.",formal:"Refined formal documentation that preserves original structure.",humorous:"Amusing content that brings lighthearted fun to the text.",improved:"Enhanced text that demonstrates better clarity and readability.",custom:"Customized content reflecting the requested modifications.",generated:"AI-generated content maintaining original length and structure."},a=o[t]||o.generated,s="";if(n<=a.length)s=a.substring(0,n);else{s=a;let u=[" Additional content continues with similar phrasing."," Further elaboration maintains the established tone."," Extended content preserves the original style."," Continued text follows the same pattern."],l=0;for(;s.length<n;){let c=u[l%u.length];if(s.length+c.length<=n)s+=c;else{s+=c.substring(0,n-s.length);break}l++}}return r+s}async function Xo(e,t,r){let i=3;if(e!=null&&typeof e=="object"){if("duration"in e&&typeof e.duration=="number")i=e.duration;else if("prompt"in e&&typeof e.prompt=="string"){let n=e.prompt.match(/(\d+)\s*(?:seconds?|secs?|s)\b/i);n&&(i=parseInt(n[1],10))}}return t.blockInputs?.audio?.duration&&(i=t.blockInputs.audio.duration),{kind:"audio",url:ea(220,i),duration:i,thumbnailUrl:void 0}}function ea(e,t){let r=Math.floor(44100*t),i=new Float32Array(r);for(let n=0;n<r;n++)i[n]=Math.sin(2*Math.PI*e*n/44100);return ta(i,44100)}function ta(e,t){let r=e.length,i=2,n=1,o=n*i,a=t*o,s=r*i,u=44+s,l=new ArrayBuffer(u),c=new DataView(l),d=(b,m)=>{for(let f=0;f<m.length;f++)c.setUint8(b+f,m.charCodeAt(f))};d(0,"RIFF"),c.setUint32(4,u-8,!0),d(8,"WAVE"),d(12,"fmt "),c.setUint32(16,16,!0),c.setUint16(20,1,!0),c.setUint16(22,n,!0),c.setUint32(24,t,!0),c.setUint32(28,a,!0),c.setUint16(32,o,!0),c.setUint16(34,16,!0),d(36,"data"),c.setUint32(40,s,!0);let p=44;for(let b=0;b<r;b++){let m=Math.max(-1,Math.min(1,e[b])),f=Math.round(m*32767);c.setInt16(p,f,!0),p+=2}let g=new Uint8Array(l),h="";for(let b=0;b<g.length;b++)h+=String.fromCharCode(g[b]);return`data:audio/wav;base64,${btoa(h)}`}async function At(e){return new Promise(t=>{setTimeout(t,e)})}var ra=Zo,ia="USER_CANCEL";function na(e){return async(t,r)=>{if(r?.abortSignal?.aborted)return{status:"aborted"};let i=Wn([...e.provider.output.middleware??[],...r?.middlewares??[],Jn({enable:r?.debug}),ra({enable:r?.dryRun,kind:e.provider.kind})]);try{let{result:n}=await i(e.provider.output.generate)(t,{abortSignal:r?.abortSignal,engine:e.engine,cesdk:e.cesdk});return r?.abortSignal?.aborted?{status:"aborted"}:n instanceof Error?{status:"error",message:n.message}:n==null?{status:"error",message:"No output generated"}:ro(n)?{status:"success",type:"async",output:n}:{status:"success",type:"sync",output:n}}catch(n){return xe(n)?{status:"aborted",message:n.message}:n===ia?{status:"aborted",message:n}:{status:"error",message:n instanceof Error?n.message:String(n)}}}}var oa=na;async function aa(e,t,r,i){let n={...i,provider:t},o={provider:t,panelInput:t.input?.panel,options:{cesdk:r.cesdk,engine:r.cesdk.engine},config:n};await t.initialize?.({...r,engine:r.cesdk.engine});let a=Vo(o),s=Go(o,a);o.options.historyAssetSourceId=a,o.options.historyAssetLibraryEntryId=s;let u=oa({provider:t,cesdk:r.cesdk,engine:r.cesdk.engine}),l=await Fo(o,u);io(r.cesdk,"@imgly/plugin-ai-generation",qo);let c={provider:t,panel:{builderRenderFunction:l},history:{assetSourceId:a,assetLibraryEntryId:s},generate:u};return Qn.get().register(c),c}var be=aa;function sa(e){let{kind:t,cesdk:r,historAssetSourceIds:i}=e,n=`ly.img.ai.${t}-generation.history`;if(r.engine.asset.findAllSources().includes(n))return n;let o=new Zt(n,r,i);return r.engine.asset.addSource(o),o.id}var la=sa;async function ua(e,t,r,i){let n,o=[];if(Array.isArray(t)){let u=await Promise.all(t.map(l=>be(e,l,r,i)));o.push(...u),n=da({prefix:e,providerInitializationResults:o})}else{let u=await Promise.all(t.fromText.map(c=>be(e,c,r,i)));o.push(...u);let l=await Promise.all(t.fromImage.map(c=>be(e,c,r,i)));o.push(...l),n=ca({prefix:`ly.img.ai.${e}-generation`,initializedFromTextProviders:u,initializedFromImageProviders:l})}let a=la({kind:e,cesdk:r.cesdk,historAssetSourceIds:o.map(u=>u.history?.assetSourceId).filter(Yn)}),s;return a!=null&&(s=a,r.cesdk.ui.addAssetLibraryEntry({id:s,sourceIds:[a],sortBy:{sortKey:"insertedAt",sortingOrder:"Descending"},canRemove:!0,gridItemHeight:"square",gridBackgroundType:"cover"})),{panel:{builderRenderFunction:n},history:{assetSourceId:a,assetLibraryEntryId:s},providerInitializationResults:o}}function ca({prefix:e,initializedFromTextProviders:t,initializedFromImageProviders:r}){let i=t.length>0&&r.length>0;return n=>{let{builder:o,experimental:a}=n,s=a.global(`${e}.fromType`,i?"fromText":void 0),u=[];s.value==="fromText"?u.push(...t):s.value==="fromImage"?u.push(...r):u.push(...t,...r);let l=t.map(({provider:h,panel:b})=>({id:h.id,label:h.name??h.id,builderRenderFunction:b?.builderRenderFunction})),c=r.map(({provider:h,panel:b})=>({id:h.id,label:h.name??h.id,builderRenderFunction:b?.builderRenderFunction})),d=n.experimental.global(`${e}.selectedProvider.fromText`,l[0]),p=n.experimental.global(`${e}.selectedProvider.fromImage`,c[0]),g=s.value==="fromText"?d:s.value==="fromImage"?p:void 0;if((i||u.length>1)&&o.Section(`${e}.providerSelection.section`,{children:()=>{if(i&&o.ButtonGroup(`${e}.fromType.buttonGroup`,{inputLabel:"Input",children:()=>{o.Button(`${e}.fromType.buttonGroup.fromText`,{label:"Text",icon:s.value!=="fromText"&&Xe(t,n)?"@imgly/LoadingSpinner":void 0,isActive:s.value==="fromText",onClick:()=>{s.setValue("fromText")}}),o.Button(`${e}.fromType.buttonGroup.fromImage`,{label:"Image",icon:s.value!=="fromImage"&&Xe(r,n)?"@imgly/LoadingSpinner":void 0,isActive:s.value==="fromImage",onClick:()=>{s.setValue("fromImage")}})}}),u.length>1){let h=s.value==="fromText"?l:s.value==="fromImage"?c:[...l,...c];g!=null&&o.Select(`${e}.providerSelect.select`,{inputLabel:"Provider",values:h,...g})}}}),u.length>1)g?.value.builderRenderFunction?.(n);else{let h=u[0];h&&h.panel?.builderRenderFunction?.(n)}}}function da({prefix:e,providerInitializationResults:t}){return r=>{let{builder:i}=r;if(t.length===0)return;let n=t.map(({provider:a,panel:s})=>({id:a.id,label:a.name??a.id,builderRenderFunction:s?.builderRenderFunction})),o=r.state(`${e}.selectedProvider`,n[0]);t.length>1&&o!=null&&i.Section(`${e}.providerSelection.section`,{children:()=>{i.Select(`${e}.providerSelect.select`,{inputLabel:"Provider",values:n,...o})}}),o.value.builderRenderFunction?.(r)}}function Xe(e,t){return e.length===0?!1:e.some(({provider:r})=>r.id==null?!1:t.experimental.global(Ee(r.id),!1).value)}var Me=ua;var pa=typeof global=="object"&&global&&global.Object===Object&&global,zt=pa,ga=typeof self=="object"&&self&&self.Object===Object&&self,fa=zt||ga||Function("return this")(),x=fa,ha=x.Symbol,U=ha,Rt=Object.prototype,ma=Rt.hasOwnProperty,ba=Rt.toString,ee=U?U.toStringTag:void 0;function ya(e){var t=ma.call(e,ee),r=e[ee];try{e[ee]=void 0;var i=!0}catch{}var n=ba.call(e);return i&&(t?e[ee]=r:delete e[ee]),n}var va=ya,wa=Object.prototype,ka=wa.toString;function Ia(e){return ka.call(e)}var Aa=Ia,xa="[object Null]",Sa="[object Undefined]",xt=U?U.toStringTag:void 0;function Ca(e){return e==null?e===void 0?Sa:xa:xt&&xt in Object(e)?va(e):Aa(e)}var ne=Ca;function Ea(e){return e!=null&&typeof e=="object"}var De=Ea,Lu=Array.isArray;function Ma(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var Ft=Ma,ja="[object AsyncFunction]",_a="[object Function]",La="[object GeneratorFunction]",Na="[object Proxy]";function Pa(e){if(!Ft(e))return!1;var t=ne(e);return t==_a||t==La||t==ja||t==Na}var Oa=Pa,$a=x["__core-js_shared__"],je=$a,St=function(){var e=/[^.]+$/.exec(je&&je.keys&&je.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function Da(e){return!!St&&St in e}var Ta=Da,za=Function.prototype,Ra=za.toString;function Fa(e){if(e!=null){try{return Ra.call(e)}catch{}try{return e+""}catch{}}return""}var j=Fa,Ua=/[\\^$.*+?()[\]{}|]/g,Va=/^\[object .+?Constructor\]$/,Ba=Function.prototype,Ga=Object.prototype,Ha=Ba.toString,qa=Ga.hasOwnProperty,Za=RegExp("^"+Ha.call(qa).replace(Ua,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Ya(e){if(!Ft(e)||Ta(e))return!1;var t=Oa(e)?Za:Va;return t.test(j(e))}var Qa=Ya;function Wa(e,t){return e?.[t]}var Ka=Wa;function Ja(e,t){var r=Ka(e,t);return Qa(r)?r:void 0}var V=Ja,Xa=V(x,"WeakMap"),Le=Xa;function es(e,t){return e===t||e!==e&&t!==t}var ts=es,rs=9007199254740991;function is(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=rs}var ns=is;var Nu=Object.prototype;var os="[object Arguments]";function as(e){return De(e)&&ne(e)==os}var Ct=as,Ut=Object.prototype,ss=Ut.hasOwnProperty,ls=Ut.propertyIsEnumerable,Pu=Ct(function(){return arguments}())?Ct:function(e){return De(e)&&ss.call(e,"callee")&&!ls.call(e,"callee")};var Vt=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Et=Vt&&typeof module=="object"&&module&&!module.nodeType&&module,us=Et&&Et.exports===Vt,Mt=us?x.Buffer:void 0,Ou=Mt?Mt.isBuffer:void 0;var cs="[object Arguments]",ds="[object Array]",ps="[object Boolean]",gs="[object Date]",fs="[object Error]",hs="[object Function]",ms="[object Map]",bs="[object Number]",ys="[object Object]",vs="[object RegExp]",ws="[object Set]",ks="[object String]",Is="[object WeakMap]",As="[object ArrayBuffer]",xs="[object DataView]",Ss="[object Float32Array]",Cs="[object Float64Array]",Es="[object Int8Array]",Ms="[object Int16Array]",js="[object Int32Array]",_s="[object Uint8Array]",Ls="[object Uint8ClampedArray]",Ns="[object Uint16Array]",Ps="[object Uint32Array]",w={};w[Ss]=w[Cs]=w[Es]=w[Ms]=w[js]=w[_s]=w[Ls]=w[Ns]=w[Ps]=!0;w[cs]=w[ds]=w[As]=w[ps]=w[xs]=w[gs]=w[fs]=w[hs]=w[ms]=w[bs]=w[ys]=w[vs]=w[ws]=w[ks]=w[Is]=!1;function Os(e){return De(e)&&ns(e.length)&&!!w[ne(e)]}var $s=Os;function Ds(e){return function(t){return e(t)}}var Ts=Ds,Bt=typeof exports=="object"&&exports&&!exports.nodeType&&exports,te=Bt&&typeof module=="object"&&module&&!module.nodeType&&module,zs=te&&te.exports===Bt,_e=zs&&zt.process,Rs=function(){try{var e=te&&te.require&&te.require("util").types;return e||_e&&_e.binding&&_e.binding("util")}catch{}}(),jt=Rs,_t=jt&&jt.isTypedArray,$u=_t?Ts(_t):$s;var Fs=Object.prototype,Du=Fs.hasOwnProperty;function Us(e,t){return function(r){return e(t(r))}}var Vs=Us,Tu=Vs(Object.keys,Object);var Bs=Object.prototype,zu=Bs.hasOwnProperty;var Gs=V(Object,"create"),re=Gs;function Hs(){this.__data__=re?re(null):{},this.size=0}var qs=Hs;function Zs(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var Ys=Zs,Qs="__lodash_hash_undefined__",Ws=Object.prototype,Ks=Ws.hasOwnProperty;function Js(e){var t=this.__data__;if(re){var r=t[e];return r===Qs?void 0:r}return Ks.call(t,e)?t[e]:void 0}var Xs=Js,el=Object.prototype,tl=el.hasOwnProperty;function rl(e){var t=this.__data__;return re?t[e]!==void 0:tl.call(t,e)}var il=rl,nl="__lodash_hash_undefined__";function ol(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=re&&t===void 0?nl:t,this}var al=ol;function B(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])}}B.prototype.clear=qs;B.prototype.delete=Ys;B.prototype.get=Xs;B.prototype.has=il;B.prototype.set=al;var Lt=B;function sl(){this.__data__=[],this.size=0}var ll=sl;function ul(e,t){for(var r=e.length;r--;)if(ts(e[r][0],t))return r;return-1}var ce=ul,cl=Array.prototype,dl=cl.splice;function pl(e){var t=this.__data__,r=ce(t,e);if(r<0)return!1;var i=t.length-1;return r==i?t.pop():dl.call(t,r,1),--this.size,!0}var gl=pl;function fl(e){var t=this.__data__,r=ce(t,e);return r<0?void 0:t[r][1]}var hl=fl;function ml(e){return ce(this.__data__,e)>-1}var bl=ml;function yl(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 vl=yl;function G(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var i=e[t];this.set(i[0],i[1])}}G.prototype.clear=ll;G.prototype.delete=gl;G.prototype.get=hl;G.prototype.has=bl;G.prototype.set=vl;var de=G,wl=V(x,"Map"),ie=wl;function kl(){this.size=0,this.__data__={hash:new Lt,map:new(ie||de),string:new Lt}}var Il=kl;function Al(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var xl=Al;function Sl(e,t){var r=e.__data__;return xl(t)?r[typeof t=="string"?"string":"hash"]:r.map}var pe=Sl;function Cl(e){var t=pe(this,e).delete(e);return this.size-=t?1:0,t}var El=Cl;function Ml(e){return pe(this,e).get(e)}var jl=Ml;function _l(e){return pe(this,e).has(e)}var Ll=_l;function Nl(e,t){var r=pe(this,e),i=r.size;return r.set(e,t),this.size+=r.size==i?0:1,this}var Pl=Nl;function H(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var i=e[t];this.set(i[0],i[1])}}H.prototype.clear=Il;H.prototype.delete=El;H.prototype.get=jl;H.prototype.has=Ll;H.prototype.set=Pl;var Gt=H;function Ol(){this.__data__=new de,this.size=0}var $l=Ol;function Dl(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var Tl=Dl;function zl(e){return this.__data__.get(e)}var Rl=zl;function Fl(e){return this.__data__.has(e)}var Ul=Fl,Vl=200;function Bl(e,t){var r=this.__data__;if(r instanceof de){var i=r.__data__;if(!ie||i.length<Vl-1)return i.push([e,t]),this.size=++r.size,this;r=this.__data__=new Gt(i)}return r.set(e,t),this.size=r.size,this}var Gl=Bl;function oe(e){var t=this.__data__=new de(e);this.size=t.size}oe.prototype.clear=$l;oe.prototype.delete=Tl;oe.prototype.get=Rl;oe.prototype.has=Ul;oe.prototype.set=Gl;var Hl=Object.prototype,Ru=Hl.propertyIsEnumerable;var ql=V(x,"DataView"),Ne=ql,Zl=V(x,"Promise"),Pe=Zl,Yl=V(x,"Set"),Oe=Yl,Nt="[object Map]",Ql="[object Object]",Pt="[object Promise]",Ot="[object Set]",$t="[object WeakMap]",Dt="[object DataView]",Wl=j(Ne),Kl=j(ie),Jl=j(Pe),Xl=j(Oe),eu=j(Le),F=ne;(Ne&&F(new Ne(new ArrayBuffer(1)))!=Dt||ie&&F(new ie)!=Nt||Pe&&F(Pe.resolve())!=Pt||Oe&&F(new Oe)!=Ot||Le&&F(new Le)!=$t)&&(F=function(e){var t=ne(e),r=t==Ql?e.constructor:void 0,i=r?j(r):"";if(i)switch(i){case Wl:return Dt;case Kl:return Nt;case Jl:return Pt;case Xl:return Ot;case eu:return $t}return t});var Fu=x.Uint8Array;var tu="__lodash_hash_undefined__";function ru(e){return this.__data__.set(e,tu),this}var iu=ru;function nu(e){return this.__data__.has(e)}var ou=nu;function $e(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new Gt;++t<r;)this.add(e[t])}$e.prototype.add=$e.prototype.push=iu;$e.prototype.has=ou;var Tt=U?U.prototype:void 0,Uu=Tt?Tt.valueOf:void 0;var au=Object.prototype,Vu=au.hasOwnProperty;var su=Object.prototype,Bu=su.hasOwnProperty;var Gu=new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,"i"),Hu=new RegExp(/[A-Fa-f0-9]{1}/,"g"),qu=new RegExp(/[A-Fa-f0-9]{2}/,"g");function lu(e){return e==null?[]:Array.isArray(e)?e:[e]}var Te=lu;var S="@imgly/plugin-ai-audio-generation-web";var _="ly.img.ai.audio-generation.speech",L="ly.img.ai.audio-generation.sound";function uu(e){return{async initialize({cesdk:t}){if(t==null)return;gt(t,S,"0.2.3"),t.setTranslations({en:{[`panel.${_}`]:"AI Voice",[`panel.${L}`]:"Sound Generation"}}),cu(e);let r=lt.get(),i=r.register({type:"plugin",sceneMode:"Video",id:`${S}/sound`,pluginId:S,label:"Generate Sound",meta:{panelId:L},execute:()=>{t.ui.isPanelOpen(L)?t.ui.closePanel(L):t.ui.openPanel(L)}}),n=r.register({type:"plugin",sceneMode:"Video",id:`${S}/speech`,pluginId:S,label:"AI Voice",meta:{panelId:_},execute:()=>{t.ui.isPanelOpen(_)?t.ui.closePanel(_):t.ui.openPanel(_)}}),o=e.providers?.text2speech??e.text2speech,a=e.providers?.text2sound??e.text2sound,s=await Promise.all(Te(o).map(g=>g({cesdk:t}))),u=await Promise.all(Te(a).map(g=>g({cesdk:t}))),l=s.length>0,c=u.length>0;if(!l&&!c){i(),n();return}c||i(),l||n();let d=await Me("audio",s,{cesdk:t},e),p=await Me("audio",u,{cesdk:t},e);p.panel.builderRenderFunction!=null?(t.ui.registerPanel(L,p.panel.builderRenderFunction),Se({cesdk:t,panelId:L})):i(),d.panel.builderRenderFunction!=null?(t.ui.registerPanel(_,d.panel.builderRenderFunction),Se({cesdk:t,panelId:_})):n()}}}function cu(e){e.debug&&(e.providers?.text2speech!=null&&e.text2speech!=null&&console.warn("[AudioGeneration]: Both `providers.text2speech` and `text2speech` configuration is provided. Since `text2speech` is deprecated, only `providers.text2speech` will be used."),e.providers?.text2sound!=null&&e.text2sound!=null&&console.warn("[AudioGeneration]: Both `providers.text2sound` and `text2sound` configuration is provided. Since `text2sound` is deprecated, only `providers.text2sound` will be used."))}var Ht=uu;var du=e=>({name:S,version:"0.2.3",...Ht(e)}),rc=du;export{rc as default};
67
67
  /*! Bundled license information:
68
68
 
69
69
  @imgly/plugin-ai-generation-web/dist/index.mjs: