@imgly/plugin-ai-audio-generation-web 0.1.9 → 0.2.0

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.d.ts CHANGED
@@ -1,5 +1,6 @@
1
+ import { Output } from '@imgly/plugin-ai-generation-web';
1
2
  import { type PluginConfiguration } from './types';
2
- declare const Plugin: (pluginConfiguration: PluginConfiguration) => {
3
+ declare const Plugin: <I, O extends Output>(pluginConfiguration: PluginConfiguration<I, O>) => {
3
4
  initialize: (context: import("@cesdk/engine").EnginePluginContext & {
4
5
  cesdk?: import("@cesdk/cesdk-js").default;
5
6
  }) => void;
package/dist/index.mjs CHANGED
@@ -1,5 +1,7 @@
1
- var lt=class{constructor(e,t,i){this.assetStoreName="assets",this.blobStoreName="blobs",this.db=null,this.id=e,this.engine=t,this.dbName=i?.dbName??`ly.img.assetSource/${e}`,this.dbVersion=i?.dbVersion??1}async initialize(){if(!this.db)return new Promise((e,t)=>{let i=indexedDB.open(this.dbName,this.dbVersion);i.onerror=n=>{t(new Error(`Failed to open IndexedDB: ${n.target.error}`))},i.onupgradeneeded=n=>{let a=n.target.result;a.objectStoreNames.contains(this.assetStoreName)||a.createObjectStore(this.assetStoreName,{keyPath:"id"}),a.objectStoreNames.contains(this.blobStoreName)||a.createObjectStore(this.blobStoreName,{keyPath:"id"})},i.onsuccess=n=>{this.db=n.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((c,s)=>{let u=e.locale??"en",d="",g=[];s.label!=null&&typeof s.label=="object"&&s.label[u]&&(d=s.label[u]),s.tags!=null&&typeof s.tags=="object"&&s.tags[u]&&(g=s.tags[u]);let m={...s,label:d,tags:g};return this.filterAsset(m,e)&&c.push(m),c},[]);t=await this.restoreBlobUrls(t),t=this.sortAssets(t,e);let{page:i,perPage:n}=e,a=i*n,o=a+n,r=t.slice(a,o),l=o<t.length?i+1:void 0;return{assets:r,currentPage:i,nextPage:l,total:t.length}}catch(t){console.error("Error finding assets:",t);return}}async getGroups(){if(await this.initialize(),!this.db)throw new Error("Database not initialized");return new Promise((e,t)=>{let i=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).getAll();i.onsuccess=()=>{let n=new Set;i.result.forEach(o=>{o.groups&&Array.isArray(o.groups)&&o.groups.forEach(r=>n.add(r))});let a=[...n];e(a)},i.onerror=()=>{t(new Error(`Failed to get groups: ${i.error}`))}})}addAsset(e){this.initialize().then(async()=>{if(!this.db)throw new Error("Database not initialized");let t=this.db.transaction(this.assetStoreName,"readwrite"),i=t.objectStore(this.assetStoreName),n=new Set;j(e,o=>{n.add(o)}),setTimeout(()=>{this.storeBlobUrls([...n])});let a={...e,meta:{...e.meta,insertedAt:e.meta?.insertedAt||Date.now()}};i.put(a),t.onerror=()=>{console.error(`Failed to add asset: ${t.error}`)}}).catch(t=>{console.error("Error initializing database:",t)})}async removeAsset(e){let t=await this.getAsset(e);return this.initialize().then(()=>{if(!this.db)throw new Error("Database not initialized");let i=this.db.transaction(this.assetStoreName,"readwrite");i.objectStore(this.assetStoreName).delete(e),i.oncomplete=()=>{j(t,n=>{this.removeBlob(n)}),this.engine.asset.assetSourceContentsChanged(this.id)},i.onerror=()=>{console.error(`Failed to remove asset: ${i.error}`)}}).catch(i=>{console.error("Error initializing database:",i)})}async removeBlob(e){return this.initialize().then(()=>{if(!this.db)throw new Error("Database not initialized");let t=this.db.transaction(this.blobStoreName,"readwrite");t.objectStore(this.blobStoreName).delete(e),t.onerror=()=>{console.error(`Failed to remove blob: ${t.error}`)}}).catch(t=>{console.error("Error initializing database:",t)})}async getAllAssets(e="desc"){return new Promise((t,i)=>{let n=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).getAll();n.onsuccess=()=>{let a=n.result;a.sort((o,r)=>{let l=o.meta?.insertedAt||o._insertedAt||Date.now(),c=r.meta?.insertedAt||r._insertedAt||Date.now();return e==="asc"?l-c:c-l}),t(a)},n.onerror=()=>{i(new Error(`Failed to get assets: ${n.error}`))}})}async getAsset(e){return new Promise((t,i)=>{let n=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).get(e);n.onsuccess=()=>{t(n.result)},n.onerror=()=>{i(new Error(`Failed to get blob: ${n.error}`))}})}async getBlob(e){return new Promise((t,i)=>{let n=this.db.transaction(this.blobStoreName,"readonly").objectStore(this.blobStoreName).get(e);n.onsuccess=()=>{t(n.result)},n.onerror=()=>{i(new Error(`Failed to get blob: ${n.error}`))}})}async createBlobUrlFromStore(e){let t=await this.getBlob(e);return t!=null?URL.createObjectURL(t.blob):e}async storeBlobUrls(e){let t={};return await Promise.all(e.map(async i=>{let n=await(await fetch(i)).blob();t[i]=n})),this.initialize().then(async()=>{if(!this.db)throw new Error("Database not initialized");let i=this.db.transaction(this.blobStoreName,"readwrite"),n=i.objectStore(this.blobStoreName);Object.entries(t).forEach(([a,o])=>{let r={id:a,blob:o};n.put(r)}),i.onerror=()=>{console.error(`Failed to add blobs: ${i.error}`)}}).catch(i=>{console.error("Error initializing database:",i)})}async restoreBlobUrls(e){let t={},i=new Set;return j(e,n=>{i.add(n)}),await Promise.all([...i].map(async n=>{let a=await this.createBlobUrlFromStore(n);t[n]=a})),j(e,n=>t[n]??n)}filterAsset(e,t){let{query:i,tags:n,groups:a,excludeGroups:o}=t;if(i&&i.trim()!==""){let r=i.trim().toLowerCase().split(" "),l=e.label?.toLowerCase()??"",c=e.tags?.map(s=>s.toLowerCase())??[];if(!r.every(s=>l.includes(s)||c.some(u=>u.includes(s))))return!1}if(n){let r=Array.isArray(n)?n:[n];if(r.length>0&&(!e.tags||!r.every(l=>e.tags?.includes(l))))return!1}return!(a&&a.length>0&&(!e.groups||!a.some(r=>e.groups?.includes(r)))||o&&o.length>0&&e.groups&&e.groups.some(r=>o.includes(r)))}sortAssets(e,t){let{sortingOrder:i,sortKey:n,sortActiveFirst:a}=t,o=[...e];return!i||i==="None"||(n?o.sort((r,l)=>{let c,s;return n==="id"?(c=r.id,s=l.id):(c=r.meta?.[n]??null,s=l.meta?.[n]??null),c==null?i==="Ascending"?-1:1:s==null?i==="Ascending"?1:-1:typeof c=="string"&&typeof s=="string"?i==="Ascending"?c.localeCompare(s):s.localeCompare(c):i==="Ascending"?c<s?-1:c>s?1:0:c>s?-1:c<s?1:0}):i==="Descending"&&o.reverse(),a&&o.sort((r,l)=>r.active&&!l.active?-1:!r.active&&l.active?1:0)),o}};function j(e,t,i=""){if(e===null||typeof e!="object")return e;if(Array.isArray(e)){for(let n=0;n<e.length;n++){let a=i?`${i}[${n}]`:`[${n}]`;if(typeof e[n]=="string"&&e[n].startsWith("blob:")){let o=t(e[n],a);typeof o=="string"&&(e[n]=o)}else e[n]=j(e[n],t,a)}return e}for(let n in e)if(Object.prototype.hasOwnProperty.call(e,n)){let a=e[n],o=i?`${i}.${n}`:n;if(typeof a=="string"&&a.startsWith("blob:")){let r=t(a,o);typeof r=="string"&&(e[n]=r)}else e[n]=j(a,t,o)}return e}var st=class{constructor(e,t){this.engine=e,this.key=t}hasData(e){return this.engine.block.isValid(e)&&this.engine.block.hasMetadata(e,this.key)}get(e){if(this.hasData(e))return JSON.parse(this.engine.block.getMetadata(e,this.key))}set(e,t){this.engine.block.setMetadata(e,this.key,JSON.stringify(t))}clear(e){this.engine.block.hasMetadata(e,this.key)&&this.engine.block.removeMetadata(e,this.key)}},De=st,ct=typeof global=="object"&&global&&global.Object===Object&&global,Oe=ct,ut=typeof self=="object"&&self&&self.Object===Object&&self,dt=Oe||ut||Function("return this")(),M=dt,pt=M.Symbol,L=pt,Pe=Object.prototype,gt=Pe.hasOwnProperty,mt=Pe.toString,z=L?L.toStringTag:void 0;function yt(e){var t=gt.call(e,z),i=e[z];try{e[z]=void 0;var n=!0}catch{}var a=mt.call(e);return n&&(t?e[z]=i:delete e[z]),a}var bt=yt,ft=Object.prototype,ht=ft.toString;function kt(e){return ht.call(e)}var vt=kt,wt="[object Null]",At="[object Undefined]",fe=L?L.toStringTag:void 0;function It(e){return e==null?e===void 0?At:wt:fe&&fe in Object(e)?bt(e):vt(e)}var G=It;function Ct(e){return e!=null&&typeof e=="object"}var ue=Ct,So=Array.isArray;function xt(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var _e=xt,Mt="[object AsyncFunction]",Et="[object Function]",St="[object GeneratorFunction]",$t="[object Proxy]";function jt(e){if(!_e(e))return!1;var t=G(e);return t==Et||t==St||t==Mt||t==$t}var Lt=jt,Tt=M["__core-js_shared__"],X=Tt,he=function(){var e=/[^.]+$/.exec(X&&X.keys&&X.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function Nt(e){return!!he&&he in e}var Dt=Nt,Ot=Function.prototype,Pt=Ot.toString;function _t(e){if(e!=null){try{return Pt.call(e)}catch{}try{return e+""}catch{}}return""}var S=_t,zt=/[\\^$.*+?()[\]{}|]/g,Ut=/^\[object .+?Constructor\]$/,qt=Function.prototype,Bt=Object.prototype,Qt=qt.toString,Vt=Bt.hasOwnProperty,Ft=RegExp("^"+Qt.call(Vt).replace(zt,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Gt(e){if(!_e(e)||Dt(e))return!1;var t=Lt(e)?Ft:Ut;return t.test(S(e))}var Rt=Gt;function Yt(e,t){return e?.[t]}var Ht=Yt;function Zt(e,t){var i=Ht(e,t);return Rt(i)?i:void 0}var N=Zt,Wt=N(M,"WeakMap"),re=Wt;function Kt(e,t){return e===t||e!==e&&t!==t}var Jt=Kt,Xt=9007199254740991;function en(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=Xt}var tn=en,$o=Object.prototype,nn="[object Arguments]";function rn(e){return ue(e)&&G(e)==nn}var ke=rn,ze=Object.prototype,on=ze.hasOwnProperty,an=ze.propertyIsEnumerable,jo=ke(function(){return arguments}())?ke:function(e){return ue(e)&&on.call(e,"callee")&&!an.call(e,"callee")},Ue=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ve=Ue&&typeof module=="object"&&module&&!module.nodeType&&module,ln=ve&&ve.exports===Ue,we=ln?M.Buffer:void 0,Lo=we?we.isBuffer:void 0,sn="[object Arguments]",cn="[object Array]",un="[object Boolean]",dn="[object Date]",pn="[object Error]",gn="[object Function]",mn="[object Map]",yn="[object Number]",bn="[object Object]",fn="[object RegExp]",hn="[object Set]",kn="[object String]",vn="[object WeakMap]",wn="[object ArrayBuffer]",An="[object DataView]",In="[object Float32Array]",Cn="[object Float64Array]",xn="[object Int8Array]",Mn="[object Int16Array]",En="[object Int32Array]",Sn="[object Uint8Array]",$n="[object Uint8ClampedArray]",jn="[object Uint16Array]",Ln="[object Uint32Array]",A={};A[In]=A[Cn]=A[xn]=A[Mn]=A[En]=A[Sn]=A[$n]=A[jn]=A[Ln]=!0;A[sn]=A[cn]=A[wn]=A[un]=A[An]=A[dn]=A[pn]=A[gn]=A[mn]=A[yn]=A[bn]=A[fn]=A[hn]=A[kn]=A[vn]=!1;function Tn(e){return ue(e)&&tn(e.length)&&!!A[G(e)]}var Nn=Tn;function Dn(e){return function(t){return e(t)}}var On=Dn,qe=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Q=qe&&typeof module=="object"&&module&&!module.nodeType&&module,Pn=Q&&Q.exports===qe,ee=Pn&&Oe.process,_n=function(){try{var e=Q&&Q.require&&Q.require("util").types;return e||ee&&ee.binding&&ee.binding("util")}catch{}}(),Ae=_n,Ie=Ae&&Ae.isTypedArray,To=Ie?On(Ie):Nn,zn=Object.prototype,No=zn.hasOwnProperty;function Un(e,t){return function(i){return e(t(i))}}var qn=Un,Do=qn(Object.keys,Object),Bn=Object.prototype,Oo=Bn.hasOwnProperty,Qn=N(Object,"create"),V=Qn;function Vn(){this.__data__=V?V(null):{},this.size=0}var Fn=Vn;function Gn(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var Rn=Gn,Yn="__lodash_hash_undefined__",Hn=Object.prototype,Zn=Hn.hasOwnProperty;function Wn(e){var t=this.__data__;if(V){var i=t[e];return i===Yn?void 0:i}return Zn.call(t,e)?t[e]:void 0}var Kn=Wn,Jn=Object.prototype,Xn=Jn.hasOwnProperty;function ei(e){var t=this.__data__;return V?t[e]!==void 0:Xn.call(t,e)}var ti=ei,ni="__lodash_hash_undefined__";function ii(e,t){var i=this.__data__;return this.size+=this.has(e)?0:1,i[e]=V&&t===void 0?ni:t,this}var ri=ii;function D(e){var t=-1,i=e==null?0:e.length;for(this.clear();++t<i;){var n=e[t];this.set(n[0],n[1])}}D.prototype.clear=Fn;D.prototype.delete=Rn;D.prototype.get=Kn;D.prototype.has=ti;D.prototype.set=ri;var Ce=D;function oi(){this.__data__=[],this.size=0}var ai=oi;function li(e,t){for(var i=e.length;i--;)if(Jt(e[i][0],t))return i;return-1}var Z=li,si=Array.prototype,ci=si.splice;function ui(e){var t=this.__data__,i=Z(t,e);if(i<0)return!1;var n=t.length-1;return i==n?t.pop():ci.call(t,i,1),--this.size,!0}var di=ui;function pi(e){var t=this.__data__,i=Z(t,e);return i<0?void 0:t[i][1]}var gi=pi;function mi(e){return Z(this.__data__,e)>-1}var yi=mi;function bi(e,t){var i=this.__data__,n=Z(i,e);return n<0?(++this.size,i.push([e,t])):i[n][1]=t,this}var fi=bi;function O(e){var t=-1,i=e==null?0:e.length;for(this.clear();++t<i;){var n=e[t];this.set(n[0],n[1])}}O.prototype.clear=ai;O.prototype.delete=di;O.prototype.get=gi;O.prototype.has=yi;O.prototype.set=fi;var W=O,hi=N(M,"Map"),F=hi;function ki(){this.size=0,this.__data__={hash:new Ce,map:new(F||W),string:new Ce}}var vi=ki;function wi(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var Ai=wi;function Ii(e,t){var i=e.__data__;return Ai(t)?i[typeof t=="string"?"string":"hash"]:i.map}var K=Ii;function Ci(e){var t=K(this,e).delete(e);return this.size-=t?1:0,t}var xi=Ci;function Mi(e){return K(this,e).get(e)}var Ei=Mi;function Si(e){return K(this,e).has(e)}var $i=Si;function ji(e,t){var i=K(this,e),n=i.size;return i.set(e,t),this.size+=i.size==n?0:1,this}var Li=ji;function P(e){var t=-1,i=e==null?0:e.length;for(this.clear();++t<i;){var n=e[t];this.set(n[0],n[1])}}P.prototype.clear=vi;P.prototype.delete=xi;P.prototype.get=Ei;P.prototype.has=$i;P.prototype.set=Li;var Be=P;function Ti(){this.__data__=new W,this.size=0}var Ni=Ti;function Di(e){var t=this.__data__,i=t.delete(e);return this.size=t.size,i}var Oi=Di;function Pi(e){return this.__data__.get(e)}var _i=Pi;function zi(e){return this.__data__.has(e)}var Ui=zi,qi=200;function Bi(e,t){var i=this.__data__;if(i instanceof W){var n=i.__data__;if(!F||n.length<qi-1)return n.push([e,t]),this.size=++i.size,this;i=this.__data__=new Be(n)}return i.set(e,t),this.size=i.size,this}var Qi=Bi;function R(e){var t=this.__data__=new W(e);this.size=t.size}R.prototype.clear=Ni;R.prototype.delete=Oi;R.prototype.get=_i;R.prototype.has=Ui;R.prototype.set=Qi;var Vi=Object.prototype,Po=Vi.propertyIsEnumerable,Fi=N(M,"DataView"),oe=Fi,Gi=N(M,"Promise"),ae=Gi,Ri=N(M,"Set"),le=Ri,xe="[object Map]",Yi="[object Object]",Me="[object Promise]",Ee="[object Set]",Se="[object WeakMap]",$e="[object DataView]",Hi=S(oe),Zi=S(F),Wi=S(ae),Ki=S(le),Ji=S(re),$=G;(oe&&$(new oe(new ArrayBuffer(1)))!=$e||F&&$(new F)!=xe||ae&&$(ae.resolve())!=Me||le&&$(new le)!=Ee||re&&$(new re)!=Se)&&($=function(e){var t=G(e),i=t==Yi?e.constructor:void 0,n=i?S(i):"";if(n)switch(n){case Hi:return $e;case Zi:return xe;case Wi:return Me;case Ki:return Ee;case Ji:return Se}return t});var _o=M.Uint8Array,Xi="__lodash_hash_undefined__";function er(e){return this.__data__.set(e,Xi),this}var tr=er;function nr(e){return this.__data__.has(e)}var ir=nr;function se(e){var t=-1,i=e==null?0:e.length;for(this.__data__=new Be;++t<i;)this.add(e[t])}se.prototype.add=se.prototype.push=tr;se.prototype.has=ir;var je=L?L.prototype:void 0,zo=je?je.valueOf:void 0,rr=Object.prototype,Uo=rr.hasOwnProperty,or=Object.prototype,qo=or.hasOwnProperty,Bo=new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,"i"),Qo=new RegExp(/[A-Fa-f0-9]{1}/,"g"),Vo=new RegExp(/[A-Fa-f0-9]{2}/,"g");function ar(e){return{"image/png":"png","image/jpeg":"jpg","image/webp":"webp","image/gif":"gif","image/svg+xml":"svg"}[e]??"png"}async function Qe(e,t){if(e.startsWith("buffer:")){let i=await t.editor.getMimeType(e),n=t.editor.getBufferLength(e),a=t.editor.getBufferData(e,0,n),o=new Blob([a],{type:i});return URL.createObjectURL(o)}else return e}async function ce(e,t){let i=await Qe(e,t);return new Promise((n,a)=>{let o=new Image;o.onload=()=>{n({width:o.width,height:o.height})},o.onerror=a,o.src=i})}async function lr(e,t,i){let n,a=t.block.getFill(e),o=t.block.getSourceSet(a,"fill/image/sourceSet"),[r]=o;if(r==null){if(n=t.block.getString(a,"fill/image/imageFileURI"),n==null)throw new Error("No image source/uri found")}else n=r.uri;if(i?.throwErrorIfSvg&&await t.editor.getMimeType(n)==="image/svg+xml")throw new Error("SVG images are not supported");return Qe(n,t)}function Ve(e,t){if(!t.startsWith("#/"))throw new Error(`External references are not supported: ${t}`);let i=t.substring(2).split("/"),n=e;for(let a of i){if(n==null)throw new Error(`Invalid reference path: ${t}`);n=n[a]}if(n===void 0)throw new Error(`Reference not found: ${t}`);return n}function q(e,t,i=new Set){if(t==null||i.has(t))return t;if(i.add(t),t.$ref&&typeof t.$ref=="string"){let n=Ve(e,t.$ref),a={...q(e,n,i)};for(let o in t)Object.prototype.hasOwnProperty.call(t,o)&&o!=="$ref"&&(a[o]=q(e,t[o],i));return a}if(Array.isArray(t))return t.map(n=>q(e,n,i));if(typeof t=="object"){let n={};for(let a in t)Object.prototype.hasOwnProperty.call(t,a)&&(n[a]=q(e,t[a],i));return n}return t}function sr(e){return q(e,{...e})}function cr(e,t=!1){let i=r=>(t&&console.log(`OpenAPI Schema validation failed: ${r}`),!1);if(typeof e!="object"||e===null)return i(`Input is ${e===null?"null":typeof e}, not an object`);let n=e;if(!(typeof n.type=="string"||Array.isArray(n.enum)||typeof n.properties=="object"||typeof n.items=="object"||typeof n.allOf=="object"||typeof n.anyOf=="object"||typeof n.oneOf=="object"||typeof n.not=="object"))return i("Missing required schema-defining properties (type, enum, properties, items, allOf, anyOf, oneOf, not)");if(n.type!==void 0){let r=["string","number","integer","boolean","array","object","null"];if(typeof n.type=="string"){if(!r.includes(n.type))return i(`Invalid type: ${n.type}. Must be one of ${r.join(", ")}`)}else if(Array.isArray(n.type)){for(let l of n.type)if(typeof l!="string"||!r.includes(l))return i(`Array of types contains invalid value: ${l}. Must be one of ${r.join(", ")}`)}else return i(`Type must be a string or array of strings, got ${typeof n.type}`)}if(n.items!==void 0&&(typeof n.items!="object"||n.items===null))return i(`Items must be an object, got ${n.items===null?"null":typeof n.items}`);if(n.properties!==void 0&&(typeof n.properties!="object"||n.properties===null))return i(`Properties must be an object, got ${n.properties===null?"null":typeof n.properties}`);let a=["allOf","anyOf","oneOf"];for(let r of a)if(n[r]!==void 0){if(!Array.isArray(n[r]))return i(`${r} must be an array, got ${typeof n[r]}`);for(let l=0;l<n[r].length;l++){let c=n[r][l];if(typeof c!="object"||c===null)return i(`Item ${l} in ${r} must be an object, got ${c===null?"null":typeof c}`)}}if(n.not!==void 0&&(typeof n.not!="object"||n.not===null))return i(`'not' must be an object, got ${n.not===null?"null":typeof n.not}`);if(n.additionalProperties!==void 0&&typeof n.additionalProperties!="boolean"&&(typeof n.additionalProperties!="object"||n.additionalProperties===null))return i(`additionalProperties must be a boolean or an object, got ${n.additionalProperties===null?"null":typeof n.additionalProperties}`);if(n.format!==void 0&&typeof n.format!="string")return i(`format must be a string, got ${typeof n.format}`);let o=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf"];for(let r of o)if(n[r]!==void 0&&typeof n[r]!="number")return i(`${r} must be a number, got ${typeof n[r]}`);if(n.minLength!==void 0&&(typeof n.minLength!="number"||n.minLength<0))return i(`minLength must be a non-negative number, got ${typeof n.minLength=="number"?n.minLength:typeof n.minLength}`);if(n.maxLength!==void 0&&(typeof n.maxLength!="number"||n.maxLength<0))return i(`maxLength must be a non-negative number, got ${typeof n.maxLength=="number"?n.maxLength:typeof n.maxLength}`);if(n.pattern!==void 0&&typeof n.pattern!="string")return i(`pattern must be a string, got ${typeof n.pattern}`);if(n.minItems!==void 0&&(typeof n.minItems!="number"||n.minItems<0))return i(`minItems must be a non-negative number, got ${typeof n.minItems=="number"?n.minItems:typeof n.minItems}`);if(n.maxItems!==void 0&&(typeof n.maxItems!="number"||n.maxItems<0))return i(`maxItems must be a non-negative number, got ${typeof n.maxItems=="number"?n.maxItems:typeof n.maxItems}`);if(n.uniqueItems!==void 0&&typeof n.uniqueItems!="boolean")return i(`uniqueItems must be a boolean, got ${typeof n.uniqueItems}`);if(n.minProperties!==void 0&&(typeof n.minProperties!="number"||n.minProperties<0))return i(`minProperties must be a non-negative number, got ${typeof n.minProperties=="number"?n.minProperties:typeof n.minProperties}`);if(n.maxProperties!==void 0&&(typeof n.maxProperties!="number"||n.maxProperties<0))return i(`maxProperties must be a non-negative number, got ${typeof n.maxProperties=="number"?n.maxProperties:typeof n.maxProperties}`);if(n.required!==void 0){if(!Array.isArray(n.required))return i(`required must be an array, got ${typeof n.required}`);for(let r=0;r<n.required.length;r++){let l=n.required[r];if(typeof l!="string")return i(`Item ${r} in required array must be a string, got ${typeof l}`)}}return!0}function ur(e,t){if(e.properties==null)throw new Error("Input schema must have properties");let i=e.properties,n=[];return dr(e,t).forEach(a=>{let o=a,r=i[a]??void 0;n.push({id:o,schema:r})}),n}function dr(e,t){let i=t.order;if(i!=null&&Array.isArray(i))return i;if(e.properties==null)throw new Error("Input schema must have properties");let n=e.properties,a=Object.keys(n),o=pr(e,t)??a;return i!=null&&typeof i=="function"&&(o=i(o)),[...new Set(o)]}function pr(e,t){if(t.orderExtensionKeyword==null)return;if(typeof t.orderExtensionKeyword!="string"&&!Array.isArray(t.orderExtensionKeyword))throw new Error("orderExtensionKeyword must be a string or an array of strings");let i=(typeof t.orderExtensionKeyword=="string"?[t.orderExtensionKeyword]:t.orderExtensionKeyword).find(n=>n in e);return i==null?void 0:e[i]}var Fe=ur,gr="ly.img.ai",te="ly.img.ai/temp";async function mr(e,t){return e.engine.asset.findAllSources().includes(te)||e.engine.asset.addLocalSource(te),e.engine.asset.apply(te,t)}function Ge(e){return`${gr}/${e}`}function yr(e,t="We encountered an unknown error while generating the asset. Please try again."){if(e===null)return t;if(e instanceof Error)return e.message;if(typeof e=="object"){let i=e;return"message"in i&&typeof i.message=="string"?i.message:"cause"in i&&typeof i.cause=="string"?i.cause:"detail"in i&&typeof i.detail=="object"&&i.detail!==null&&"message"in i.detail&&typeof i.detail.message=="string"?i.detail.message:"error"in i&&typeof i.error=="object"&&i.error!==null&&"message"in i.error&&typeof i.error.message=="string"?i.error.message:t}return typeof e=="string"?e:String(e)||t}function br(){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 fr(e,t=0,i="image/jpeg",n=.8){return new Promise((a,o)=>{try{let r=document.createElement("video");r.crossOrigin="anonymous",r.style.display="none",r.addEventListener("loadedmetadata",()=>{r.currentTime=Math.min(t,r.duration),r.addEventListener("seeked",()=>{let l=document.createElement("canvas");l.width=r.videoWidth,l.height=r.videoHeight;let c=l.getContext("2d");if(!c){document.body.removeChild(r),o(new Error("Failed to create canvas context"));return}c.drawImage(r,0,0,l.width,l.height);try{let s=l.toDataURL(i,n);document.body.removeChild(r),a(s)}catch(s){document.body.removeChild(r),o(new Error(`Failed to create thumbnail: ${s instanceof Error?s.message:String(s)}`))}},{once:!0})}),r.addEventListener("error",()=>{document.body.removeChild(r),o(new Error(`Failed to load video from ${e}`))}),r.src=e,document.body.appendChild(r)}catch(r){o(r)}})}function Re(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 de(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 T(e){return e instanceof Error&&e.name==="AbortError"}function Ye(e,t,i,n,a,o){if(t.schema==null)return n.renderCustomProperty!=null&&n.renderCustomProperty[t.id]!=null?n.renderCustomProperty[t.id](e,t):void 0;let r=t,l=t.schema.type;if(n.renderCustomProperty!=null&&n.renderCustomProperty[t.id]!=null)return n.renderCustomProperty[t.id](e,t);switch(l){case"string":return t.schema.enum!=null?hr(e,r,i,n,a,o):Ze(e,r,i,n,a,o);case"boolean":return We(e,r,i,n,a,o);case"number":case"integer":return Ke(e,r,i,n,a,o);case"object":return He(e,r,i,n,a,o);case"array":break;case void 0:{if(t.schema.anyOf!=null&&Array.isArray(t.schema.anyOf))return kr(e,r,i,n,a,o);break}default:console.error(`Unsupported property type: ${l}`)}}function He(e,t,i,n,a,o){let r=Fe(t.schema??{},n).reduce((l,c)=>{let s=Ye(e,c,i,n,a,o);return s!=null&&(l[c.id]=s()),l},{});return()=>({id:t.id,type:"object",value:r})}function Ze(e,t,i,n,a,o){let{builder:r,experimental:{global:l}}=e,{id:c}=t,s=`${i.id}.${c}`,u=t.schema.title??s,d=l(s,t.schema.default??""),g=vr(t.schema),m=g?.component!=null&&g?.component==="TextArea"?"TextArea":"TextInput";return r[m](s,{inputLabel:u,placeholder:a.i18n?.prompt,...d}),()=>({id:t.id,type:"string",value:d.value})}function hr(e,t,i,n,a,o){let{builder:r,experimental:{global:l}}=e,{id:c}=t,s=`${i.id}.${c}`,u=t.schema.title??s,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"]:{},g="x-imgly-enum-icons"in t.schema&&typeof t.schema["x-imgly-enum-icons"]=="object"?t.schema["x-imgly-enum-icons"]:{},m=(t.schema.enum??[]).map(f=>({id:f,label:d[f]??Re(f),icon:g[f]})),k=t.schema.default!=null?m.find(f=>f.id===t.schema.default)??m[0]:m[0],w=l(s,k);return r.Select(s,{inputLabel:u,values:m,...w}),()=>({id:t.id,type:"string",value:w.value.id})}function We(e,t,i,n,a,o){let{builder:r,experimental:{global:l}}=e,{id:c}=t,s=`${i.id}.${c}`,u=t.schema.title??s,d=!!t.schema.default,g=l(s,d);return r.Checkbox(s,{inputLabel:u,...g}),()=>({id:t.id,type:"boolean",value:g.value})}function Ke(e,t,i,n,a,o){let{builder:r,experimental:{global:l}}=e,{id:c}=t,s=`${i.id}.${c}`,u=t.schema.title??s,d=t.schema.minimum,g=t.schema.maximum,m=t.schema.default;m==null&&(d!=null?m=d:g!=null?m=g:m=0);let k=l(s,m);if(d!=null&&g!=null){let w=t.schema.type==="number"?.1:1;"x-imgly-step"in t.schema&&typeof t.schema["x-imgly-step"]=="number"&&(w=t.schema["x-imgly-step"]),r.Slider(s,{inputLabel:u,min:d,max:g,step:w,...k})}else r.NumberInput(s,{inputLabel:u,min:d,max:g,...k});return()=>({id:t.id,type:"integer",value:k.value})}function kr(e,t,i,n,a,o){let{builder:r,experimental:{global:l}}=e,{id:c}=t,s=`${i.id}.${c}`,u=t.schema.title??s,d=t.schema.anyOf??[],g=[],m={},k={};d.forEach((p,h)=>{let y=p.title??"common.custom",b=`${i.id}.${c}.anyOf[${h}]`,v="x-imgly-enum-labels"in t.schema&&typeof t.schema["x-imgly-enum-labels"]=="object"?t.schema["x-imgly-enum-labels"]:{},I="x-imgly-enum-icons"in t.schema&&typeof t.schema["x-imgly-enum-icons"]=="object"?t.schema["x-imgly-enum-icons"]:{};p.type==="string"?p.enum!=null?p.enum.forEach(C=>{g.push({id:C,label:v[C]??Re(C),icon:I[C]})}):(m[b]=()=>Ze(e,{id:b,schema:{...p,title:y}},i,n,a,o),g.push({id:b,label:v[y]??y,icon:I[y]})):p.type==="boolean"?(m[b]=()=>We(e,{id:b,schema:{...p,title:y}},i,n,a,o),g.push({id:b,label:v[y]??y,icon:I[y]})):p.type==="integer"?(m[b]=()=>Ke(e,{id:b,schema:{...p,title:y}},i,n,a,o),g.push({id:b,label:v[y]??y,icon:I[y]})):p.type==="array"||p.type==="object"&&(m[b]=()=>He(e,{id:b,schema:{...p,title:y}},i,n,a,o),g.push({id:b,label:v[y]??y,icon:I[y]}))});let w=t.schema.default!=null?g.find(p=>p.id===t.schema.default)??g[0]:g[0],f=l(s,w);if(r.Select(s,{inputLabel:u,values:g,...f}),f.value.id in m){let p=m[f.value.id]();k[f.value.id]=p}return()=>{let p=k[f.value.id];return p!=null?{...p(),id:t.id}:{id:t.id,type:"string",value:f.value.id}}}function vr(e){if("x-imgly-builder"in e)return e["x-imgly-builder"]}var wr=Ye,Ar="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIzIiBoZWlnaHQ9IjMyMyIgdmlld0JveD0iMCAwIDMyMyAzMjMiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIzMjMiIGhlaWdodD0iMzIzIiBmaWxsPSIjRTlFQkVEIi8+CjxnIG9wYWNpdHk9IjAuMyI+CjxwYXRoIGQ9Ik0xMTYgMTg0VjE5MS41QzExNiAxOTkuNzg0IDEyMi43MTYgMjA2LjUgMTMxIDIwNi41SDE5MUMxOTkuMjg0IDIwNi41IDIwNiAxOTkuNzg0IDIwNiAxOTEuNVYxMzEuNUMyMDYgMTIzLjIxNiAxOTkuMjg0IDExNi41IDE5MSAxMTYuNUwxOTAuOTk1IDEyNi41QzE5My43NTcgMTI2LjUgMTk2IDEyOC43MzkgMTk2IDEzMS41VjE5MS41QzE5NiAxOTQuMjYxIDE5My43NjEgMTk2LjUgMTkxIDE5Ni41SDEzMUMxMjguMjM5IDE5Ni41IDEyNiAxOTQuMjYxIDEyNiAxOTEuNVYxODRIMTE2WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTY2LjQ5NCAxMDUuOTI0QzE2NS44NjkgMTA0LjM0MiAxNjMuNjI5IDEwNC4zNDIgMTYzLjAwNSAxMDUuOTI0TDE1OS43NDUgMTE0LjE5MUMxNTkuNTU0IDExNC42NzQgMTU5LjE3MiAxMTUuMDU3IDE1OC42ODggMTE1LjI0N0wxNTAuNDIyIDExOC41MDhDMTQ4LjgzOSAxMTkuMTMyIDE0OC44MzkgMTIxLjM3MiAxNTAuNDIyIDEyMS45OTZMMTU4LjY4OCAxMjUuMjU2QzE1OS4xNzIgMTI1LjQ0NyAxNTkuNTU0IDEyNS44MjkgMTU5Ljc0NSAxMjYuMzEzTDE2My4wMDUgMTM0LjU3OUMxNjMuNjI5IDEzNi4xNjIgMTY1Ljg2OSAxMzYuMTYyIDE2Ni40OTQgMTM0LjU3OUwxNjkuNzU0IDEyNi4zMTNDMTY5Ljk0NCAxMjUuODI5IDE3MC4zMjcgMTI1LjQ0NyAxNzAuODEgMTI1LjI1NkwxNzkuMDc3IDEyMS45OTZDMTgwLjY2IDEyMS4zNzIgMTgwLjY2IDExOS4xMzIgMTc5LjA3NyAxMTguNTA4TDE3MC44MSAxMTUuMjQ3QzE3MC4zMjcgMTE1LjA1NyAxNjkuOTQ0IDExNC42NzQgMTY5Ljc1NCAxMTQuMTkxTDE2Ni40OTQgMTA1LjkyNFoiIGZpbGw9IiM4RjhGOEYiLz4KPHBhdGggZD0iTTEzMy4wMDUgMTI4LjQyNEMxMzMuNjI5IDEyNi44NDIgMTM1Ljg2OSAxMjYuODQyIDEzNi40OTQgMTI4LjQyNEwxNDEuODc1IDE0Mi4wN0MxNDIuMDY2IDE0Mi41NTMgMTQyLjQ0OCAxNDIuOTM1IDE0Mi45MzIgMTQzLjEyNkwxNTYuNTc3IDE0OC41MDhDMTU4LjE2IDE0OS4xMzIgMTU4LjE2IDE1MS4zNzIgMTU2LjU3NyAxNTEuOTk2TDE0Mi45MzIgMTU3LjM3OEMxNDIuNDQ4IDE1Ny41NjggMTQyLjA2NiAxNTcuOTUxIDE0MS44NzUgMTU4LjQzNEwxMzYuNDk0IDE3Mi4wNzlDMTM1Ljg2OSAxNzMuNjYyIDEzMy42MjkgMTczLjY2MiAxMzMuMDA1IDE3Mi4wNzlMMTI3LjYyMyAxNTguNDM0QzEyNy40MzMgMTU3Ljk1MSAxMjcuMDUgMTU3LjU2OCAxMjYuNTY3IDE1Ny4zNzhMMTEyLjkyMiAxNTEuOTk2QzExMS4zMzkgMTUxLjM3MiAxMTEuMzM5IDE0OS4xMzIgMTEyLjkyMiAxNDguNTA4TDEyNi41NjcgMTQzLjEyNkMxMjcuMDUgMTQyLjkzNSAxMjcuNDMzIDE0Mi41NTMgMTI3LjYyMyAxNDIuMDdMMTMzLjAwNSAxMjguNDI0WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTk1Ljk5OSAxODQuMDA0VjE5MS41MDJDMTk1Ljk5OSAxOTQuMjYzIDE5My43NjEgMTk2LjUwMiAxOTAuOTk5IDE5Ni41MDJIMTQ3LjY2OEwxNzIuODc5IDE1OC42ODRDMTc0LjM2MyAxNTYuNDU4IDE3Ny42MzUgMTU2LjQ1OCAxNzkuMTIgMTU4LjY4NEwxOTUuOTk5IDE4NC4wMDRaIiBmaWxsPSIjOEY4RjhGIi8+CjwvZz4KPC9zdmc+Cg==",Je=Ar;function Ir(e,t,i){switch(t){case"image":return Cr(e,i[t]);case"video":return xr(e,i[t]);default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function Cr(e,t){let i=t.width,n=t.height;return{id:e,meta:{previewUri:Je,fillType:"//ly.img.ubq/fill/image",kind:"image",width:i,height:n}}}function xr(e,t){let i=t.width,n=t.height;return{id:e,label:t.label,meta:{previewUri:Je,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:i,height:n}}}var Mr=Ir;async function Er(e,t,i,n){switch(t){case"image":{if(n.kind!=="image")throw new Error(`Output kind does not match the expected type: ${n.kind} (expected: image)`);return Sr(e,i[t],n)}case"video":{if(n.kind!=="video")throw new Error(`Output kind does not match the expected type: ${n.kind} (expected: video)`);return $r(e,i[t],n)}case"audio":{if(n.kind!=="audio")throw new Error(`Output kind does not match the expected type: ${n.kind} (expected: audio)`);return jr(e,i[t],n)}default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function Sr(e,t,i){let n=t.width,a=t.height;return{id:e,label:t.label,meta:{uri:i.url,thumbUri:i.url,fillType:"//ly.img.ubq/fill/image",kind:"image",width:n,height:a},payload:{sourceSet:[{uri:i.url,width:n,height:a}]}}}async function $r(e,t,i){let n=t.width,a=t.height,o=await fr(i.url,0);return{id:e,label:t.label,meta:{uri:i.url,thumbUri:o,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:n,height:a}}}function jr(e,t,i){return{id:e,label:t.label,meta:{uri:i.url,thumbUri:i.thumbnailUrl,blockType:"//ly.img.ubq/audio",mimeType:"audio/x-m4a",duration:i.duration.toString()}}}var Le=Er;function Xe(e){let t=e.filter(i=>!!i);return i=>async(n,a)=>{let o=[],r=s=>{o.push(s)},l=async(s,u,d)=>{if(s>=t.length)return i(u,d);let g=t[s],m=async(w,f)=>l(s+1,w,f),k={...d,addDisposer:r};return g(u,k,m)},c={...a,addDisposer:r};return{result:await l(0,n,c),dispose:async()=>{for(let s=o.length-1;s>=0;s--)try{await o[s]()}catch(u){console.error("Error in disposer:",u)}o.length=0}}}}function Lr(){return async(e,t,i)=>{console.group("[GENERATION]"),console.log("Generating with input:",JSON.stringify(e,null,2));let n,a=Date.now();try{return n=await i(e,t),n}finally{n!=null&&(console.log(`Generation took ${Date.now()-a}ms`),console.log("Generation result:",JSON.stringify(n,null,2))),console.groupEnd()}}}var et=Lr;function Tr(e){return async(t,i)=>(console.log(`[DRY RUN]: Requesting dummy AI generation for kind '${e.kind}' with inputs: `,JSON.stringify(t,void 0,2)),await Pr(2e3),await Nr(t,e,i))}async function Nr(e,t,i){switch(t.kind){case"image":return Dr(e,t,i);case"video":return Or(e,t,i);default:throw new Error(`Unsupported output kind for creating dry run output: ${t.kind}`)}}async function Dr(e,t,{engine:i}){let n,a,o=e!=null&&typeof e=="object"&&"prompt"in e&&typeof e.prompt=="string"?e.prompt:"AI Generated Image",r=o.match(/(\d+)x(\d+)/);if(r!=null)n=parseInt(r[1],10),a=parseInt(r[2],10);else if(t.blockInputs!=null&&(n=t.blockInputs.image.width,a=t.blockInputs.image.height),t.blockIds!=null&&Array.isArray(t.blockIds)&&t.blockIds.length>0){let[l]=t.blockIds,c=await lr(l,i),s=await ce(c,i);n=s.width,a=s.height}else n=512,a=512;return{kind:"image",url:`https://placehold.co/${n}x${a}/000000/FFF?text=${o.replace(" ","+").replace(`
2
- `,"+")}`}}async function Or(e,t,i){return Promise.resolve({kind:"video",url:"https://storage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"})}async function Pr(e){return new Promise(t=>{setTimeout(t,e)})}var tt=Tr;async function _r(e,t,i,n,a,o,r){let{cesdk:l,createPlaceholderBlock:c,historyAssetSourceId:s}=a,u;try{o.debug&&console.group(`Starting Generation for '${e}'`);let d=t(),g=await i(d.input),m=br(),k;if(c){if(k=Mr(m,e,g),o.debug&&console.log("Adding as asset to scene:",JSON.stringify(k,void 0,2)),u=await mr(l,k),u!=null&&n.kind==="video"){let h=l.engine.block.getPositionX(u),y=l.engine.block.getPositionY(u),b=l.engine.block.duplicate(u);l.engine.block.setPositionX(b,h),l.engine.block.setPositionY(b,y),l.engine.block.destroy(u),u=b}if(H(l,r,u))return{status:"aborted"};if(u==null)throw new Error("Could not create placeholder block");l.engine.block.setState(u,{type:"Pending",progress:0})}let w=Xe([...n.output.middleware??[],o.debug?et():void 0,o.dryRun?tt({kind:n.kind,blockInputs:g}):void 0]),{result:f}=await w(n.output.generate)(d.input,{abortSignal:r,engine:a.engine,cesdk:l});if(de(f))throw new Error("Streaming generation is not supported yet from a panel");if(H(l,r,u))return{status:"aborted"};if(f==null)throw new Error("Generation failed");o.debug&&console.log("Generated output:",JSON.stringify(f,void 0,2));let p;if(u!=null&&l.engine.block.isValid(u)&&(p=await Le(m,e,g,f),o.debug&&console.log("Updating asset in scene:",JSON.stringify(p,void 0,2)),await l.engine.asset.defaultApplyAssetToBlock(p,u)),H(l,r,u))return{status:"aborted"};if(s!=null){if(p==null&&(p=await Le(m,e,g,f),H(l,r,u)))return{status:"aborted"};let h={...p,id:`${Date.now()}-${p.id}`,label:p.label!=null?{en:p.label}:{},tags:{}};l.engine.asset.addAssetToSource(s,h)}return u!=null&&l.engine.block.isValid(u)&&l.engine.block.setState(u,{type:"Ready"}),{status:"success",output:f}}catch(d){throw u!=null&&l.engine.block.isValid(u)&&(T(d)?l.engine.block.destroy(u):l.engine.block.setState(u,{type:"Error",error:"Unknown"})),d}finally{o.debug&&console.groupEnd()}}function H(e,t,i){return t.aborted?(i!=null&&e.engine.block.isValid(i)&&e.engine.block.destroy(i),!0):!1}var zr=_r;function Ur(e,t,i){let{cesdk:n,provider:a,getInput:o}=t;i.onError!=null&&typeof i.onError=="function"?i.onError(e):(console.error("Generation failed:",e),qr(n,a.output.notification,()=>({input:o?.().input,error:e}))||n.ui.showNotification({type:"error",message:yr(e)}))}function qr(e,t,i){let n=t?.error;if(n==null||!(typeof n.show=="function"?n.show(i()):n.show))return!1;let a=typeof n.message=="function"?n.message(i()):n.message??"common.ai-generation.failed",o=n.action!=null?{label:typeof n.action.label=="function"?n.action.label(i()):n.action.label,onClick:()=>{n?.action?.onClick(i())}}:void 0;return e.ui.showNotification({type:"error",message:a,action:o}),!0}var B=Ur;function nt(e){return`${e}.generating`}function Br(e){return`${e}.abort`}function Qr(e,t,i,n,a,o){let{builder:r,experimental:l}=e,{cesdk:c,includeHistoryLibrary:s=!0}=a,{id:u,output:{abortable:d}}=t,g=l.global(Br(u),()=>{}),m=l.global(nt(u),!1),k,w=m.value&&d,f=()=>{w&&(g.value(),m.setValue(!1),g.setValue(()=>{}))},p;if(a.requiredInputs!=null&&a.requiredInputs.length>0){let y=i();p=a.requiredInputs.every(b=>!y.input[b])}let h=l.global(`${u}.confirmationDialogId`,void 0);r.Section(`${u}.generate.section`,{children:()=>{r.Button(`${u}.generate`,{label:["common.ai-generation.generate",`panel.${u}.generate`],isLoading:m.value,color:"accent",isDisabled:p,suffix:w?{icon:"@imgly/Cross",color:"danger",tooltip:[`panel.${u}.abort`,"common.cancel"],onClick:()=>{let y=c.ui.showDialog({type:"warning",content:"panel.ly.img.ai.generation.confirmCancel.content",cancel:{label:"common.close",onClick:({id:b})=>{c.ui.closeDialog(b),h.setValue(void 0)}},actions:{label:"panel.ly.img.ai.generation.confirmCancel.confirm",color:"danger",onClick:({id:b})=>{f(),c.ui.closeDialog(b),h.setValue(void 0)}}});h.setValue(y)}}:void 0,onClick:async()=>{k=new AbortController;let y=k.signal,b=async()=>{try{m.setValue(!0),g.setValue(()=>{o.debug&&console.log("Aborting generation"),k?.abort()});let v=await zr(t.kind,i,n,t,a,o,y);if(v.status==="aborted")return;let I=t.output.notification;Vr(c,I,()=>({input:i().input,output:v.output}))}catch(v){if(T(v))return;B(v,{cesdk:c,provider:t,getInput:i},o)}finally{k=void 0,m.setValue(!1),g.setValue(()=>{}),h.value!=null&&(c.ui.closeDialog(h.value),h.setValue(void 0))}};o.middleware!=null?await o.middleware(b,{provider:t,abort:f}):await b()}}),t.output.generationHintText!=null&&r.Text(`${u}.generation-hint`,{align:"center",content:t.output.generationHintText})}}),s&&a.historyAssetLibraryEntryId!=null&&r.Library(`${u}.history.library`,{entries:[a.historyAssetLibraryEntryId]})}function Vr(e,t,i){let n=t?.success;if(n==null||!(typeof n.show=="function"?n.show(i()):n.show))return!1;let a=typeof n.message=="function"?n.message(i()):n.message??"common.ai-generation.success",o=n.action!=null?{label:typeof n.action.label=="function"?n.action.label(i()):n.action.label,onClick:()=>{n?.action?.onClick(i())}}:void 0;return e.ui.showNotification({type:"success",message:a,action:o,duration:n.duration}),!0}var it=Qr;async function Fr(e,t,i,n){let{cesdk:a}=i,{id:o}=e;n.debug&&console.log(`Registering schema-based panel input for provider ${o}`);let r=sr(t.document),l=Ve(r,t.inputReference);if(!cr(l,n.debug))throw new Error(`Input reference '${t.inputReference}' does not resolve to a valid OpenAPI schema`);let c=l,s=Fe(c,t),u=d=>{let{builder:g}=d,m=[];g.Section(`${o}.schema.section`,{children:()=>{s.forEach(p=>{let h=wr(d,p,e,t,i,n);h!=null&&(Array.isArray(h)?m.push(...h):m.push(h))})}});let k=m.map(p=>p()),w=p=>p.type==="object"?Object.entries(p.value).reduce((h,[y,b])=>(h[y]=w(b),h),{}):p.value,f=k.reduce((p,h)=>(p[h.id]=w(h),p),{});it(d,e,()=>({input:f}),()=>t.getBlockInput(f),{...i,requiredInputs:c.required,createPlaceholderBlock:t.userFlow==="placeholder"},n)};return a.ui.registerPanel(Ge(o),u),u}var Gr=Fr;async function Rr(e,t,i,n){let{cesdk:a}=i,{id:o}=e,r=t.render,l=c=>{let{state:s}=c,u=s(nt(o),{isGenerating:!1,abort:()=>{}}).value.isGenerating,{getInput:d,getBlockInput:g}=r(c,{cesdk:a,isGenerating:u});return it(c,e,d,g,{...i,includeHistoryLibrary:t.includeHistoryLibrary??!0,createPlaceholderBlock:t.userFlow==="placeholder"},n),d};return a.ui.registerPanel(Ge(o),l),l}var Yr=Rr,ne="@imgly/plugin-ai-generation",Hr=`
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
+ Plugin "${t}" is using version ${r}, but other AI plugins are using version ${o}.
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=`
3
5
  <svg>
4
6
  <symbol
5
7
  fill="none"
@@ -17,7 +19,7 @@ var lt=class{constructor(e,t,i){this.assetStoreName="assets",this.blobStoreName=
17
19
  fill="none"
18
20
  xmlns="http://www.w3.org/2000/svg"
19
21
  viewBox="0 0 24 24"
20
- id="${ne}/image"
22
+ id="${me}/image"
21
23
  >
22
24
  <path d="M3 16.5V18C3 19.6569 4.34315 21 6 21H18C19.6569 21 21 19.6569 21 18V6C21 4.34315 19.6569 3 18 3L17.999 5C18.5513 5 19 5.44772 19 6V18C19 18.5523 18.5523 19 18 19H6C5.44772 19 5 18.5523 5 18V16.5H3Z" fill="currentColor"/>
23
25
  <path d="M13.0982 0.884877C12.9734 0.568323 12.5254 0.568322 12.4005 0.884876L11.7485 2.53819C11.7104 2.63483 11.6339 2.71134 11.5372 2.74945L9.8839 3.40151C9.56735 3.52636 9.56734 3.97436 9.8839 4.09921L11.5372 4.75126C11.6339 4.78938 11.7104 4.86588 11.7485 4.96253L12.4005 6.61584C12.5254 6.93239 12.9734 6.9324 13.0982 6.61584L13.7503 4.96253C13.7884 4.86588 13.8649 4.78938 13.9616 4.75126L15.6149 4.09921C15.9314 3.97436 15.9314 3.52636 15.6149 3.40151L13.9616 2.74945C13.8649 2.71134 13.7884 2.63483 13.7503 2.53819L13.0982 0.884877Z" fill="currentColor"/>
@@ -29,7 +31,7 @@ var lt=class{constructor(e,t,i){this.assetStoreName="assets",this.blobStoreName=
29
31
  fill="none"
30
32
  xmlns="http://www.w3.org/2000/svg"
31
33
  viewBox="0 0 24 24"
32
- id="${ne}/video"
34
+ id="${me}/video"
33
35
  >
34
36
  <path d="M6 3C4.34315 3 3 4.34315 3 6V18C3 19.6569 4.34315 21 6 21H18C19.6569 21 21 19.6569 21 18V16.5H19V18C19 18.5523 18.5523 19 18 19H6C5.44772 19 5 18.5523 5 18V6C5 5.44772 5.44772 5 6 5V3Z" fill="currentColor"/>
35
37
  <path d="M10.9025 0.8839C11.0273 0.567345 11.4753 0.567346 11.6002 0.883901L12.2522 2.53721C12.2904 2.63386 12.3669 2.71036 12.4635 2.74848L14.1168 3.40053C14.4334 3.52538 14.4334 3.97338 14.1168 4.09823L12.4635 4.75029C12.3669 4.7884 12.2904 4.86491 12.2522 4.96155L11.6002 6.61486C11.4753 6.93142 11.0273 6.93142 10.9025 6.61486L10.2504 4.96155C10.2123 4.86491 10.1358 4.7884 10.0392 4.75029L8.38585 4.09823C8.0693 3.97338 8.0693 3.52538 8.38585 3.40053L10.0392 2.74848C10.1358 2.71036 10.2123 2.63386 10.2504 2.53721L10.9025 0.8839Z" fill="currentColor"/>
@@ -40,7 +42,7 @@ var lt=class{constructor(e,t,i){this.assetStoreName="assets",this.blobStoreName=
40
42
  fill="none"
41
43
  xmlns="http://www.w3.org/2000/svg"
42
44
  viewBox="0 0 24 24"
43
- id="${ne}/audio"
45
+ id="${me}/audio"
44
46
  >
45
47
  <path d="M6 3.80273C4.2066 4.84016 3 6.77919 3 9.00004V12.8153C3 15.931 5.39501 18.4873 8.44444 18.7436V20.9645C8.44444 22.2198 9.89427 22.9198 10.8773 22.1392L15.1265 18.7647H15.5C17.8285 18.7647 19.8472 17.4384 20.8417 15.5H18.4187C17.6889 16.2784 16.6512 16.7647 15.5 16.7647H14.9522C14.6134 16.7647 14.2846 16.8794 14.0193 17.0901L10.4444 19.929V18.2597C10.4444 17.4341 9.77513 16.7647 8.9495 16.7647C7.80494 16.7647 6.77409 16.2779 6.05276 15.5H6V15.4419C5.37798 14.7439 5 13.8237 5 12.8153V9.00004C5 7.98559 5.37764 7.05935 6 6.35422V3.80273Z" fill="currentColor"/>
46
48
  <path d="M11.6002 1.8839C11.4753 1.56735 11.0273 1.56735 10.9025 1.8839L10.2504 3.53721C10.2123 3.63386 10.1358 3.71036 10.0392 3.74848L8.38585 4.40053C8.0693 4.52538 8.0693 4.97338 8.38585 5.09823L10.0392 5.75029C10.1358 5.7884 10.2123 5.86491 10.2504 5.96155L10.9025 7.61486C11.0273 7.93142 11.4753 7.93142 11.6002 7.61486L12.2522 5.96155C12.2904 5.86491 12.3669 5.7884 12.4635 5.75029L14.1168 5.09823C14.4334 4.97338 14.4334 4.52538 14.1168 4.40053L12.4635 3.74848C12.3669 3.71036 12.2904 3.63386 12.2522 3.53721L11.6002 1.8839Z" fill="currentColor"/>
@@ -60,7 +62,8 @@ var lt=class{constructor(e,t,i){this.assetStoreName="assets",this.blobStoreName=
60
62
 
61
63
  </symbol>
62
64
  </svg>
63
- `,Zr=Hr,Te="ly.img.ai.quickAction.order",U="ly.img.ai.quickAction.actions";function Wr(e,t){return{id:t,setQuickActionMenuOrder:i=>{e.ui.experimental.setGlobalStateValue(`${Te}.${t}`,i)},getQuickActionMenuOrder:()=>e.ui.experimental.getGlobalStateValue(`${Te}.${t}`,[]),registerQuickAction:i=>{if(!e.ui.experimental.hasGlobalStateValue(`${U}.${t}`))e.ui.experimental.setGlobalStateValue(`${U}.${t}`,{[i.id]:i});else{let n=e.ui.experimental.getGlobalStateValue(`${U}.${t}`,{});e.ui.experimental.setGlobalStateValue(`${U}.${t}`,{...n,[i.id]:i})}},getQuickAction:i=>e.ui.experimental.getGlobalStateValue(`${U}.${t}`,{})[i]}}var pe=Wr,ie="ly.img.ai.inference.editMode",rt="ly.img.ai.inference.metadata";function ot(e){return`ly.img.ai.quickAction.${e.quickActionMenuId}.${e.quickActionId}`}function Kr(e){if(e.length===0)return[];let t=[...e];for(;t.length>0&&t[0]==="ly.img.separator";)t.shift();for(;t.length>0&&t[t.length-1]==="ly.img.separator";)t.pop();return t.reduce((i,n)=>(n==="ly.img.separator"&&i.length>0&&i[i.length-1]==="ly.img.separator"||i.push(n),i),[])}function Jr({alwaysOnTop:e=!0,disableClipping:t=!0}){return async(i,n,a)=>{let o={},r={},l=e||t?n.blockIds??n.engine.block.findAllSelected():[];return l.forEach(c=>{if(n.engine.block.isValid(c)&&e&&(o[c]=n.engine.block.isAlwaysOnTop(c),n.engine.block.setAlwaysOnTop(c,!0)),t){let s=n.engine.block.getParent(c);s!=null&&n.engine.block.getType(s)!=="//ly.img.ubq/scene"&&(r[s]=n.engine.block.isClipped(s),n.engine.block.setClipped(s,!1))}}),n.addDisposer(async()=>{l.forEach(c=>{if(n.engine.block.isValid(c)&&e&&n.engine.block.setAlwaysOnTop(c,o[c]),t){let s=n.engine.block.getParent(c);s!=null&&n.engine.block.getType(s)!=="//ly.img.ubq/scene"&&r[s]!=null&&n.engine.block.setClipped(s,r[s])}})}),await a(i,n)}}var Xr=Jr;function eo({pending:e=!0}){return async(t,i,n)=>{let a=e?i.blockIds??i.engine.block.findAllSelected():[];try{return a.forEach(o=>{i.engine.block.isValid(o)&&i.engine.block.setState(o,{type:"Pending",progress:0})}),await n(t,i)}finally{a.forEach(o=>{i.engine.block.isValid(o)&&i.engine.block.setState(o,{type:"Ready"})})}}}var to=eo;function no({editMode:e,automaticallyUnlock:t=!1}){return async(i,n,a)=>{let o=n.blockIds??n.engine.block.findAllSelected(),r=()=>{};t||n.addDisposer(async()=>{r?.()});try{return r=io(n.engine,o,e),await a(i,n)}catch(l){throw T(l)&&r(),l}finally{t&&r()}}}function io(e,t,i){let n=e.editor.getGlobalScope("editor/select"),a=e.editor.getEditMode();l(),e.editor.setGlobalScope("editor/select","Deny"),e.editor.setEditMode(i);let o=e.editor.createHistory(),r=e.editor.getActiveHistory();e.editor.setActiveHistory(o);function l(){e.block.findAllSelected().forEach(u=>{t.includes(u)||e.block.setSelected(u,!1)}),t.forEach(u=>{e.block.setSelected(u,!0)})}let c=e.editor.onStateChanged(()=>{e.editor.getEditMode()!==i&&e.editor.setEditMode(i)}),s=e.block.onSelectionChanged(l);return()=>{n!=null&&e.editor.setGlobalScope("editor/select",n),e.editor.setEditMode(a),e.editor.setActiveHistory(r),e.editor.destroyHistory(o),s(),c()}}var ro=no;function oo(e,t){switch(t.kind){case"text":return ao(e,t);case"image":return lo(e,t);case"video":return so(e,t);case"audio":return co(e,t);default:throw new Error(`Unsupported output kind for quick actions: ${t.kind}`)}}async function ao(e,t){let{cesdk:i,blockIds:n,abortSignal:a}=t,o=n.map(s=>i.engine.block.getString(s,"text/text")),r;if(de(e)){let s="";for await(let u of e){if(a.aborted)break;typeof u=="string"?s=u:u.kind==="text"&&(s=u.text),n.forEach(d=>{i.engine.block.setString(d,"text/text",s)}),r={kind:"text",text:s}}}else r=e;if(r==null||r.kind!=="text")throw new Error("Output kind from generation is not text");let l=()=>{t.blockIds.forEach(s=>{t.cesdk.engine.block.setString(s,"text/text",r.text)})},c=()=>{t.blockIds.forEach((s,u)=>{t.cesdk.engine.block.setString(s,"text/text",o[u])})};return{consumedGenerationResult:r,applyCallbacks:{onBefore:c,onAfter:l,onCancel:c,onApply:()=>{l(),t.cesdk.engine.editor.addUndoStep()}}}}async function lo(e,t){let{cesdk:i,blockIds:n,abortSignal:a}=t;if(n.length!==1)throw new Error("Only one block is supported for image generation");let[o]=n,r=i.engine.block.getFill(o),l=i.engine.block.getSourceSet(r,"fill/image/sourceSet"),[c]=l,s;c==null&&(s=i.engine.block.getString(r,"fill/image/imageFileURI"));let u=await i.engine.editor.getMimeType(c?.uri??s),d=await ce(c?.uri??s,t.cesdk.engine),g=d.width/d.height;if(a.throwIfAborted(),u==="image/svg+xml")throw new Error("SVG images are not supported");let m=i.engine.block.getCropScaleX(o),k=i.engine.block.getCropScaleY(o),w=i.engine.block.getCropTranslationX(o),f=i.engine.block.getCropTranslationY(o),p=i.engine.block.getCropRotation(o),h=()=>{i.engine.block.setCropScaleX(o,m),i.engine.block.setCropScaleY(o,k),i.engine.block.setCropTranslationX(o,w),i.engine.block.setCropTranslationY(o,f),i.engine.block.setCropRotation(o,p)};if(de(e))throw new Error("Streaming generation is not supported yet from a panel");if(e.kind!=="image"||typeof e.url!="string")throw new Error("Output kind from generation is not an image");let y=e.url,b=await i.engine.editor.getMimeType(y),v=await uo(i,y,b),I=await ce(v,t.cesdk.engine),C=I.width/I.height,x=Math.abs(g-C)>.001,E=c?[{uri:v,width:I.width,height:I.height}]:void 0,_=v;E==null?i.engine.block.setString(r,"fill/image/imageFileURI",_):(i.engine.block.setString(r,"fill/image/imageFileURI",""),i.engine.block.setSourceSet(r,"fill/image/sourceSet",E)),x?i.engine.block.setContentFillMode(o,"Cover"):h();let ye=()=>{if(l==null||l.length===0){if(s==null)throw new Error("No image URI found");i.engine.block.setString(r,"fill/image/imageFileURI",s)}else i.engine.block.setSourceSet(r,"fill/image/sourceSet",l);h()},be=()=>{if(E==null){if(_==null)throw new Error("No image URI found");i.engine.block.setString(r,"fill/image/imageFileURI",_)}else i.engine.block.setSourceSet(r,"fill/image/sourceSet",E);x?i.engine.block.setContentFillMode(o,"Cover"):h()};return{consumedGenerationResult:e,applyCallbacks:{onBefore:ye,onAfter:be,onCancel:()=>{ye()},onApply:()=>{be(),t.cesdk.engine.editor.addUndoStep()}}}}async function so(e,t){throw new Error("Function not implemented.")}async function co(e,t){throw new Error("Function not implemented.")}async function uo(e,t,i){let n=await(await fetch(t)).blob(),a=new File([n],`image.${ar(i)}`,{type:i}),o=await e.unstable_upload(a,()=>{});return o?.meta?.uri??(console.warn("Failed to upload image:",o),t)}var po=oo;function go({editMode:e,automaticallyUnlock:t=!1,showNotification:i=!0}){return async(n,a,o)=>{let r=a.blockIds??a.engine.block.findAllSelected(),l=()=>{};t||a.addDisposer(async()=>{l?.()});try{l=mo(a.engine,r,e);let c=await o(n,a);if(i){let s=a.engine.block.findAllSelected();r.some(u=>s.includes(u))||a.cesdk?.ui.showNotification({type:"success",message:"AI generation complete",action:{label:"Select",onClick:()=>{r.forEach(u=>{a.engine.block.select(u)})}}})}return c}catch(c){throw T(c)&&l(),c}finally{t&&l()}}}function mo(e,t,i){function n(){let r=e.block.findAllSelected();return t.some(l=>r.includes(l))}let a=e.editor.onStateChanged(()=>{e.editor.getEditMode()!==i&&n()&&e.editor.setEditMode(i)}),o=e.block.onSelectionChanged(()=>{n()?e.editor.setEditMode(i):e.editor.setEditMode("Transform")});return n()&&e.editor.setEditMode(i),()=>{o(),a(),e.editor.setEditMode("Transform")}}var yo=go;async function bo(e,t){let{cesdk:i,input:n,blockIds:a,provider:o,quickAction:r,confirmationComponentId:l,abortSignal:c}=e;r.confirmation&&i.ui.setCanvasMenuOrder([l],{editMode:ie});let s=new De(i.engine,rt);a.forEach(p=>{s.set(p,{status:"processing",quickActionId:r.id})});let u={cesdk:i,engine:i.engine,abortSignal:c},d=Xe([...o.output.middleware??[],t.debug?et():void 0,to({}),...r.confirmation?[r.lockDuringConfirmation?ro({editMode:ie}):yo({editMode:ie}),r.confirmation&&Xr({})]:[],t.dryRun?tt({kind:o.kind,blockIds:a}):void 0]),{result:g,dispose:m}=await d(o.output.generate)(n,u),{consumedGenerationResult:k,applyCallbacks:w}=await po(g,{abortSignal:c,kind:o.kind,blockIds:a,cesdk:i});r.confirmation?a.forEach(p=>{s.set(p,{status:"confirmation",quickActionId:r.id})}):(w.onApply(),a.forEach(p=>{s.clear(p)}));let f=()=>{m(),a.forEach(p=>{s.clear(p)})};return c.addEventListener("abort",f),{dispose:f,returnValue:k,applyCallbacks:w}}var Ne=bo;function fo(e,t){let{cesdk:i,quickActionMenu:n,provider:a}=e,o=`ly.img.ai.${n.id}`,r=`${o}.confirmation`;i.setTranslations({en:{[`${r}.apply`]:"Apply",[`${r}.before`]:"Before",[`${r}.after`]:"After",[`${o}.cancel`]:"Cancel",[`${o}.processing`]:"Generating..."}});let l=`${r}.canvasnMenu`,c={unlock:()=>{},abort:()=>{},applyCallbacks:void 0},s=()=>{let d=new AbortController,g=d.signal;return c.abort=()=>{d.abort()},g};i.ui.registerComponent(l,({builder:d,engine:g,state:m})=>{let k=g.block.findAllSelected();if(k.length===0)return null;let w=new De(i.engine,rt),f=w.get(k[0]);if(f==null)return null;let p=()=>{k.forEach(h=>{w.clear(h)})};switch(f.status){case"processing":{d.Button(`${o}.spinner`,{label:[`ly.img.ai.inference.${f.quickActionId}.processing`,`${o}.cancel`],isLoading:!0}),d.Separator(`${o}.separator`),d.Button(`${o}.cancel`,{icon:"@imgly/Cross",tooltip:`${o}.cancel`,onClick:()=>{c.abort(),p()}});break}case"confirmation":{let h=m(`${r}.comparing`,"after"),y=c.applyCallbacks?.onCancel;y!=null&&d.Button(`${r}.cancel`,{icon:"@imgly/Cross",tooltip:`${o}.cancel`,onClick:()=>{c.unlock(),y(),p()}});let b=c.applyCallbacks?.onBefore,v=c.applyCallbacks?.onAfter;b!=null&&v!=null&&d.ButtonGroup(`${r}.compare`,{children:()=>{d.Button(`${r}.compare.before`,{label:`${r}.before`,variant:"regular",isActive:h.value==="before",onClick:()=>{b(),h.setValue("before")}}),d.Button(`${r}.compare.after`,{label:`${r}.after`,variant:"regular",isActive:h.value==="after",onClick:()=>{v(),h.setValue("after")}})}});let I=c.applyCallbacks?.onApply;I!=null&&d.Button(`${r}.apply`,{icon:"@imgly/Checkmark",tooltip:`${r}.apply`,color:"accent",isDisabled:h.value!=="after",onClick:()=>{c.unlock(),p(),i.engine.editor._update(),I()}});break}default:}});let u=`${o}.canvasMenu`;return i.ui.registerComponent(u,d=>{let g=d.engine.block.findAllSelected(),m=g.every(y=>d.engine.block.getState(y).type==="Ready"),k=n.getQuickActionMenuOrder().map(y=>{if(y==="ly.img.separator")return y;let b=n.getQuickAction(y);if(b==null||!i.feature.isEnabled(ot({quickActionId:y,quickActionMenuId:n.id}),{engine:d.engine}))return null;let v=b.scopes;return v!=null&&v.length>0&&!g.every(I=>v.every(C=>d.engine.block.isAllowedByScope(I,C)))?null:b}).filter(y=>y!=null);if(k=Kr(k),k.length===0||k.every(y=>y==="ly.img.separator"))return null;let{builder:w,experimental:f,state:p}=d,h=p(`${o}.toggleExpandedState`,void 0);f.builder.Popover(`${o}.popover`,{icon:"@imgly/Sparkle",variant:"plain",isDisabled:!m,trailingIcon:null,children:({close:y})=>{w.Section(`${o}.popover.section`,{children:()=>{if(h.value!=null){let b=h.value,v=n.getQuickAction(b);if(v!=null&&v.renderExpanded!=null){v.renderExpanded(d,{blockIds:g,closeMenu:y,toggleExpand:()=>{h.setValue(void 0)},handleGenerationError:I=>{B(I,{cesdk:i,provider:a},t)},generate:async(I,C)=>{try{let{returnValue:x,applyCallbacks:E,dispose:_}=await Ne({input:I,quickAction:v,quickActionMenu:n,provider:a,cesdk:i,abortSignal:s(),blockIds:C?.blockIds??g,confirmationComponentId:l},t);return c.unlock=_,c.applyCallbacks=E,x}catch(x){throw T(x)||B(x,{cesdk:i,provider:a},t),x}}});return}}f.builder.Menu(`${o}.menu`,{children:()=>{k.forEach(b=>{b==="ly.img.separator"?w.Separator(`${o}.separator.${Math.random().toString()}`):b.render(d,{blockIds:g,closeMenu:y,handleGenerationError:v=>{B(v,{cesdk:i,provider:a},t)},toggleExpand:()=>{h.setValue(b.id)},generate:async(v,I)=>{try{let{returnValue:C,applyCallbacks:x,dispose:E}=await Ne({input:v,quickAction:b,quickActionMenu:n,provider:a,cesdk:i,abortSignal:s(),blockIds:I?.blockIds??g,confirmationComponentId:l},t);return c.unlock=E,c.applyCallbacks=x,C}catch(C){throw T(C)||B(C,{cesdk:i,provider:a},t),C}}})})}})}})}})}),{canvasMenuComponentId:u}}var ho=fo;async function ko(e,t,i){await e.initialize?.(t);let n=await wo(t.engine,e.id,e.output.history??"@imgly/local");if(t.cesdk==null)return{};let a=n?`${e.id}.history.entry`:void 0,o={...t,cesdk:t.cesdk,historyAssetSourceId:n,historyAssetLibraryEntryId:a,i18n:{prompt:"common.ai-generation.prompt.placeholder"}};a!=null&&n!=null&&t.cesdk.ui.addAssetLibraryEntry({id:a,sourceIds:[n],sortBy:{sortKey:"insertedAt",sortingOrder:"Descending"},canRemove:!0,gridItemHeight:"square",gridBackgroundType:"cover"}),t.cesdk.i18n.setTranslations({en:{"common.ai-generation.success":"Generation Successful","common.ai-generation.failed":"Generation Failed","common.ai-generation.generate":"Generate","common.ai-generation.prompt.placeholder":"Describe what you want to create...",[`panel.${e.id}`]:vo(e)}});let r="@imgly/plugin-ai-generation.iconSetAdded";return t.cesdk.ui.experimental.hasGlobalStateValue(r)||(t.cesdk.ui.addIconSet("@imgly/plugin-ai-generation",Zr),t.cesdk.ui.experimental.setGlobalStateValue(r,!0)),{renderBuilderFunctions:await Ao(e,o,i)}}function vo(e){if(e.name!=null)return e.name;switch(e.kind){case"image":return"Generate Image";case"video":return"Generate Video";case"audio":return"Generate Audio";default:return"Generate Asset"}}async function wo(e,t,i){if(!(i==null||i===!1)){if(i==="@imgly/local"){let n=`${t}.history`;return e.asset.addLocalSource(n),n}if(i==="@imgly/indexedDB"){let n=`${t}.history`;return e.asset.addSource(new lt(n,e)),n}return i}}async function Ao(e,t,i){let n={panel:void 0};return e.input?.panel!=null&&(n.panel=await Io(e,e.input.panel,t,i)),e.input?.quickActions!=null&&(i.debug&&console.log(`Initializing quick actions for provider '${e.kind}' (${e.id})`),Co(e,e.input.quickActions,t,i)),n}async function Io(e,t,i,n){switch(t.type){case"custom":return Yr(e,t,i,n);case"schema":return Gr(e,t,i,n);default:n.debug&&console.warn(`Invalid panel input type '${t.type}' - skipping`)}}async function Co(e,t,i,n){let{cesdk:a}=i,o={};t.actions.forEach(r=>{let l=r.kind??e.kind;o[l]==null&&(o[l]=pe(a,l));let c=o[l],s=r.enable??!0;a.feature.enable(ot({quickActionId:r.id,quickActionMenuId:l}),s),c.registerQuickAction(r),n.debug&&console.log(`Registered quick action: '${r.id}' (v${r.version}) to menu '${l}'`)}),Object.values(o).forEach(r=>{let{canvasMenuComponentId:l}=ho({cesdk:a,quickActionMenu:r,provider:e},n);n.debug&&console.log(`Registered quick action menu component: ${l}`)})}var ge=ko;var me="@imgly/plugin-ai-audio-generation-web";var Y="ly.img.ai/audio-generation/speech",J="ly.img.ai/audio-generation/sound";function xo(e){return{async initialize({cesdk:t}){if(t==null)return;let i={debug:e.debug??!1,dryRun:e.dryRun??!1,middleware:e.middleware};t.setTranslations({en:{[`panel.${Y}`]:"AI Voice",[`panel.${J}`]:"Sound Generation","ly.img.ai.audio-generation.speech.success":"Generation Successful","ly.img.ai.audio-generation.speech.success.action":"Show","ly.img.ai.audio-generation.sound.success":"Sound Generation Successful","ly.img.ai.audio-generation.sound.success.action":"Show"}});let n=e?.text2speech,a=e?.text2sound,o=await n?.({cesdk:t}),r=await a?.({cesdk:t});o!=null&&(o.output.notification={success:{show:()=>!t?.ui.isPanelOpen(Y),message:"ly.img.ai.audio-generation.speech.success",action:{label:"ly.img.ai.audio-generation.speech.success.action",onClick:()=>{t.ui.openPanel(Y)}},duration:"long"}}),r!=null&&(r.output.notification={success:{show:()=>!t?.ui.isPanelOpen(J),message:"ly.img.ai.audio-generation.sound.success",action:{label:"ly.img.ai.audio-generation.sound.success.action",onClick:()=>{t.ui.openPanel(J)}}}});let l=o!=null?await ge(o,{cesdk:t,engine:t.engine},i):void 0,c=r!=null?await ge(r,{cesdk:t,engine:t.engine},i):void 0;c?.renderBuilderFunctions?.panel!=null&&t.ui.registerPanel(J,c.renderBuilderFunctions.panel),l?.renderBuilderFunctions?.panel!=null&&(Mo(t,s=>{t.ui.openPanel(Y),t.ui.experimental.setGlobalStateValue(`${o?.id}.prompt`,s)}),t.ui.registerPanel(Y,l.renderBuilderFunctions.panel))}}}function Mo(e,t){let i=pe(e,"text"),n="generateSpeech";i.registerQuickAction({id:n,version:"1",confirmation:!1,enable:({engine:a})=>{let o=a.block.findAllSelected();if(o.length!==1)return!1;let[r]=o;return a.block.getType(r)==="//ly.img.ubq/text"},render:({builder:a},o)=>{a.Button(n,{icon:"@imgly/Audio",variant:"plain",labelAlignment:"left",label:"AI Voice...",onClick:()=>{let[r]=e.engine.block.findAllSelected(),l=e.engine.block.getString(r,"text/text");t(l),o.closeMenu()}})}}),i.setQuickActionMenuOrder([...i.getQuickActionMenuOrder(),"ly.img.separator",n])}var at=xo;var Eo=e=>({name:me,version:"0.1.9",...at(e)}),Jo=Eo;export{Jo as default};
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.0"),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(d=>d({cesdk:t}))),u=await Promise.all(Te(a).map(d=>d({cesdk:t}))),l=await Me("audio",s,{cesdk:t},e),c=await Me("audio",u,{cesdk:t},e);c.panel.builderRenderFunction!=null?(t.ui.registerPanel(L,c.panel.builderRenderFunction),Se({cesdk:t,panelId:L})):i(),l.panel.builderRenderFunction!=null?(t.ui.registerPanel(_,l.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.0",...Ht(e)}),rc=du;export{rc as default};
64
67
  /*! Bundled license information:
65
68
 
66
69
  @imgly/plugin-ai-generation-web/dist/index.mjs:
@@ -81,5 +84,20 @@ var lt=class{constructor(e,t,i){this.assetStoreName="assets",this.blobStoreName=
81
84
  *)
82
85
  *)
83
86
  *)
87
+
88
+ @imgly/plugin-utils/dist/index.mjs:
89
+ (*! Bundled license information:
90
+
91
+ lodash-es/lodash.js:
92
+ (**
93
+ * @license
94
+ * Lodash (Custom Build) <https://lodash.com/>
95
+ * Build: `lodash modularize exports="es" -o ./`
96
+ * Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
97
+ * Released under MIT license <https://lodash.com/license>
98
+ * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
99
+ * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
100
+ *)
101
+ *)
84
102
  */
85
103
  //# sourceMappingURL=index.mjs.map