@imgly/plugin-ai-generation-web 0.1.2 → 0.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- function Ct(e,t){let{cesdk:n}=t,r=t.propertyKey??"image_url";return wt(e,n),{[r]:(o,a)=>{let{builder:s,experimental:{global:l},payload:u}=o,d=u?.url??t.defaultUrl,c=l(`${e}.${a.id}`,d);return s.MediaPreview(a.id,{preview:{type:"image",uri:c.value},action:{label:"Select Image",onClick:()=>{if(n==null)return;let p=ae(e);n.ui.openPanel(p,{payload:{onSelect:m=>{m.meta?.uri!=null&&c.setValue(m.meta?.uri)}}})}}}),()=>({id:a.id,type:"string",value:c.value})}}}function wt(e,t){t?.ui.registerPanel(ae(e),({builder:n,payload:r})=>{n.Library(`${e}.library.image`,{entries:["ly.img.image"],onSelect:async i=>{let o=i?.meta?.uri;if(o==null)return;let a=await t.engine.editor.getMimeType(o);a==="image/svg+xml"?t.ui.showNotification({type:"warning",message:"SVG images are not supported. Please choose a different image."}):a.startsWith("image/")?(r?.onSelect(i),t?.ui.closePanel(ae(e))):t.ui.showNotification({type:"warning",message:`Only images are supported. Found '${a}'. Please choose a different image.`})}})})}function ae(e){return`ly.img.ai/${e}.imageSelection`}var Ee=Ct;function se(e,t){if(!t.startsWith("#/"))throw new Error(`External references are not supported: ${t}`);let n=t.substring(2).split("/"),r=e;for(let i of n){if(r==null)throw new Error(`Invalid reference path: ${t}`);r=r[i]}if(r===void 0)throw new Error(`Reference not found: ${t}`);return r}function B(e,t,n=new Set){if(t==null||n.has(t))return t;if(n.add(t),t.$ref&&typeof t.$ref=="string"){let r=se(e,t.$ref),o={...B(e,r,n)};for(let a in t)Object.prototype.hasOwnProperty.call(t,a)&&a!=="$ref"&&(o[a]=B(e,t[a],n));return o}if(Array.isArray(t))return t.map(r=>B(e,r,n));if(typeof t=="object"){let r={};for(let i in t)Object.prototype.hasOwnProperty.call(t,i)&&(r[i]=B(e,t[i],n));return r}return t}function le(e){return B(e,{...e})}function Se(e,t=!1){let n=s=>(t&&console.log(`OpenAPI Schema validation failed: ${s}`),!1);if(typeof e!="object"||e===null)return n(`Input is ${e===null?"null":typeof e}, not an object`);let r=e;if(!(typeof r.type=="string"||Array.isArray(r.enum)||typeof r.properties=="object"||typeof r.items=="object"||typeof r.allOf=="object"||typeof r.anyOf=="object"||typeof r.oneOf=="object"||typeof r.not=="object"))return n("Missing required schema-defining properties (type, enum, properties, items, allOf, anyOf, oneOf, not)");if(r.type!==void 0){let s=["string","number","integer","boolean","array","object","null"];if(typeof r.type=="string"){if(!s.includes(r.type))return n(`Invalid type: ${r.type}. Must be one of ${s.join(", ")}`)}else if(Array.isArray(r.type)){for(let l of r.type)if(typeof l!="string"||!s.includes(l))return n(`Array of types contains invalid value: ${l}. Must be one of ${s.join(", ")}`)}else return n(`Type must be a string or array of strings, got ${typeof r.type}`)}if(r.items!==void 0&&(typeof r.items!="object"||r.items===null))return n(`Items must be an object, got ${r.items===null?"null":typeof r.items}`);if(r.properties!==void 0&&(typeof r.properties!="object"||r.properties===null))return n(`Properties must be an object, got ${r.properties===null?"null":typeof r.properties}`);let o=["allOf","anyOf","oneOf"];for(let s of o)if(r[s]!==void 0){if(!Array.isArray(r[s]))return n(`${s} must be an array, got ${typeof r[s]}`);for(let l=0;l<r[s].length;l++){let u=r[s][l];if(typeof u!="object"||u===null)return n(`Item ${l} in ${s} must be an object, got ${u===null?"null":typeof u}`)}}if(r.not!==void 0&&(typeof r.not!="object"||r.not===null))return n(`'not' must be an object, got ${r.not===null?"null":typeof r.not}`);if(r.additionalProperties!==void 0&&typeof r.additionalProperties!="boolean"&&(typeof r.additionalProperties!="object"||r.additionalProperties===null))return n(`additionalProperties must be a boolean or an object, got ${r.additionalProperties===null?"null":typeof r.additionalProperties}`);if(r.format!==void 0&&typeof r.format!="string")return n(`format must be a string, got ${typeof r.format}`);let a=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf"];for(let s of a)if(r[s]!==void 0&&typeof r[s]!="number")return n(`${s} must be a number, got ${typeof r[s]}`);if(r.minLength!==void 0&&(typeof r.minLength!="number"||r.minLength<0))return n(`minLength must be a non-negative number, got ${typeof r.minLength=="number"?r.minLength:typeof r.minLength}`);if(r.maxLength!==void 0&&(typeof r.maxLength!="number"||r.maxLength<0))return n(`maxLength must be a non-negative number, got ${typeof r.maxLength=="number"?r.maxLength:typeof r.maxLength}`);if(r.pattern!==void 0&&typeof r.pattern!="string")return n(`pattern must be a string, got ${typeof r.pattern}`);if(r.minItems!==void 0&&(typeof r.minItems!="number"||r.minItems<0))return n(`minItems must be a non-negative number, got ${typeof r.minItems=="number"?r.minItems:typeof r.minItems}`);if(r.maxItems!==void 0&&(typeof r.maxItems!="number"||r.maxItems<0))return n(`maxItems must be a non-negative number, got ${typeof r.maxItems=="number"?r.maxItems:typeof r.maxItems}`);if(r.uniqueItems!==void 0&&typeof r.uniqueItems!="boolean")return n(`uniqueItems must be a boolean, got ${typeof r.uniqueItems}`);if(r.minProperties!==void 0&&(typeof r.minProperties!="number"||r.minProperties<0))return n(`minProperties must be a non-negative number, got ${typeof r.minProperties=="number"?r.minProperties:typeof r.minProperties}`);if(r.maxProperties!==void 0&&(typeof r.maxProperties!="number"||r.maxProperties<0))return n(`maxProperties must be a non-negative number, got ${typeof r.maxProperties=="number"?r.maxProperties:typeof r.maxProperties}`);if(r.required!==void 0){if(!Array.isArray(r.required))return n(`required must be an array, got ${typeof r.required}`);for(let s=0;s<r.required.length;s++){let l=r.required[s];if(typeof l!="string")return n(`Item ${s} in required array must be a string, got ${typeof l}`)}}return!0}function xt(e,t){if(e.properties==null)throw new Error("Input schema must have properties");let n=[],r=kt(e,t);return r??(Object.entries(e.properties).forEach(i=>{let o=i[0],a=i[1];n.push({id:o,schema:a})}),n)}function kt(e,t){if(t.orderExtensionKeyword==null)return;let n=[];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,i=r.find(a=>a in e);if(i==null)return;let o=e[i];if(o==null||Array.isArray(o)===!1)throw new Error(`Extension keyword ${i} must be an array of strings`);if([...new Set(o)].forEach(a=>{let s=e.properties?.[a];s!=null&&n.push({id:a,schema:s})}),n.length===0)throw new Error(`Could not find any properties with order extension keyword(s) ${r.join(", ")}`);return n}var q=xt;var Mt="ly.img.ai",ue="ly.img.ai/temp";async function Pe(e,t){return e.engine.asset.findAllSources().includes(ue)||e.engine.asset.addLocalSource(ue),e.engine.asset.apply(ue,t)}function G(e){return`${Mt}/${e}`}function De(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 n=e;return"message"in n&&typeof n.message=="string"?n.message:"cause"in n&&typeof n.cause=="string"?n.cause:"detail"in n&&typeof n.detail=="object"&&n.detail!==null&&"message"in n.detail&&typeof n.detail.message=="string"?n.detail.message:"error"in n&&typeof n.error=="object"&&n.error!==null&&"message"in n.error&&typeof n.error.message=="string"?n.error.message:t}return typeof e=="string"?e:String(e)||t}function Re(){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 At(e){return new Promise((t,n)=>{try{let r=document.createElement("video");r.style.display="none",r.addEventListener("loadedmetadata",()=>{r.duration===1/0?(r.currentTime=1e101,setTimeout(()=>{r.currentTime=0,t(r.duration),document.body.removeChild(r)},50)):(t(r.duration),document.body.removeChild(r))}),r.addEventListener("error",()=>{document.body.removeChild(r),n(new Error(`Failed to load video from ${e}`))}),r.src=e,document.body.appendChild(r)}catch(r){n(r)}})}function ce(e,t=0,n="image/jpeg",r=.8){return new Promise((i,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 l=s.getContext("2d");if(!l){document.body.removeChild(a),o(new Error("Failed to create canvas context"));return}l.drawImage(a,0,0,s.width,s.height);try{let u=s.toDataURL(n,r);document.body.removeChild(a),i(u)}catch(u){document.body.removeChild(a),o(new Error(`Failed to create thumbnail: ${u instanceof Error?u.message:String(u)}`))}},{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 Y(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 A(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 k(e){return e instanceof Error&&e.name==="AbortError"}function Ne(e,t,n,r,i,o){let a=t.schema.type;if(r.renderCustomProperty!=null&&r.renderCustomProperty[t.id]!=null)return r.renderCustomProperty[t.id](e,t);switch(a){case"string":return t.schema.enum!=null?Et(e,t,n,r,i,o):Le(e,t,n,r,i,o);case"boolean":return Te(e,t,n,r,i,o);case"number":case"integer":return $e(e,t,n,r,i,o);case"object":return je(e,t,n,r,i,o);case"array":break;case void 0:{if(t.schema.anyOf!=null&&Array.isArray(t.schema.anyOf))return St(e,t,n,r,i,o);break}default:console.error(`Unsupported property type: ${a}`)}}function je(e,t,n,r,i,o){let s=q(t.schema??{},r).reduce((l,u)=>{let d=Ne(e,u,n,r,i,o);return d!=null&&(l[u.id]=d()),l},{});return()=>({id:t.id,type:"object",value:s})}function Le(e,t,n,r,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,u=`${n.id}.${l}`,d=t.schema.title??u,c=s(u,t.schema.default??""),p=Pt(t.schema),m=p?.component!=null&&p?.component==="TextArea"?"TextArea":"TextInput";return a[m](u,{inputLabel:d,placeholder:i.i18n?.prompt,...c}),()=>({id:t.id,type:"string",value:c.value})}function Et(e,t,n,r,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,u=`${n.id}.${l}`,d=t.schema.title??u,c=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"]:{},p=(t.schema.enum??[]).map(I=>({id:I,label:c[I]??Y(I)})),m=t.schema.default!=null?p.find(I=>I.id===t.schema.default)??p[0]:p[0],v=s(u,m);return a.Select(u,{inputLabel:d,values:p,...v}),()=>({id:t.id,type:"string",value:v.value.id})}function Te(e,t,n,r,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,u=`${n.id}.${l}`,d=t.schema.title??u,c=!!t.schema.default,p=s(u,c);return a.Checkbox(u,{inputLabel:d,...p}),()=>({id:t.id,type:"boolean",value:p.value})}function $e(e,t,n,r,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,u=`${n.id}.${l}`,d=t.schema.title??u,c=t.schema.minimum,p=t.schema.maximum,m=t.schema.default;m==null&&(c!=null?m=c:p!=null?m=p:m=0);let v=s(u,m);if(c!=null&&p!=null){let I=t.schema.type==="number"?.1:1;"x-imgly-step"in t.schema&&typeof t.schema["x-imgly-step"]=="number"&&(I=t.schema["x-imgly-step"]),a.Slider(u,{inputLabel:d,min:c,max:p,step:I,...v})}else a.NumberInput(u,{inputLabel:d,min:c,max:p,...v});return()=>({id:t.id,type:"integer",value:v.value})}function St(e,t,n,r,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,u=`${n.id}.${l}`,d=t.schema.title??u,c=t.schema.anyOf??[],p=[],m={},v={};c.forEach((f,g)=>{let h=f.title??"common.custom",y=`${n.id}.${l}.anyOf[${g}]`,O="x-imgly-enum-labels"in t.schema&&typeof t.schema["x-imgly-enum-labels"]=="object"?t.schema["x-imgly-enum-labels"]:{},w="x-imgly-enum-icons"in t.schema&&typeof t.schema["x-imgly-enum-icons"]=="object"?t.schema["x-imgly-enum-icons"]:{};f.type==="string"?f.enum!=null?f.enum.forEach(x=>{p.push({id:x,label:O[x]??Y(x),icon:w[x]})}):(m[y]=()=>Le(e,{id:y,schema:{...f,title:h}},n,r,i,o),p.push({id:y,label:O[h]??h,icon:w[h]})):f.type==="boolean"?(m[y]=()=>Te(e,{id:y,schema:{...f,title:h}},n,r,i,o),p.push({id:y,label:O[h]??h,icon:w[h]})):f.type==="integer"?(m[y]=()=>$e(e,{id:y,schema:{...f,title:h}},n,r,i,o),p.push({id:y,label:O[h]??h,icon:w[h]})):f.type==="array"||f.type==="object"&&(m[y]=()=>je(e,{id:y,schema:{...f,title:h}},n,r,i,o),p.push({id:y,label:O[h]??h,icon:w[h]}))});let I=t.schema.default!=null?p.find(f=>f.id===t.schema.default)??p[0]:p[0],b=s(u,I);if(a.Select(u,{inputLabel:d,values:p,...b}),b.value.id in m){let f=m[b.value.id]();v[b.value.id]=f}return()=>{let f=v[b.value.id];return f!=null?{...f(),id:t.id}:{id:t.id,type:"string",value:b.value.id}}}function Pt(e){if("x-imgly-builder"in e)return e["x-imgly-builder"]}var Be=Ne;var Dt="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIzIiBoZWlnaHQ9IjMyMyIgdmlld0JveD0iMCAwIDMyMyAzMjMiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIzMjMiIGhlaWdodD0iMzIzIiBmaWxsPSIjRTlFQkVEIi8+CjxnIG9wYWNpdHk9IjAuMyI+CjxwYXRoIGQ9Ik0xMTYgMTg0VjE5MS41QzExNiAxOTkuNzg0IDEyMi43MTYgMjA2LjUgMTMxIDIwNi41SDE5MUMxOTkuMjg0IDIwNi41IDIwNiAxOTkuNzg0IDIwNiAxOTEuNVYxMzEuNUMyMDYgMTIzLjIxNiAxOTkuMjg0IDExNi41IDE5MSAxMTYuNUwxOTAuOTk1IDEyNi41QzE5My43NTcgMTI2LjUgMTk2IDEyOC43MzkgMTk2IDEzMS41VjE5MS41QzE5NiAxOTQuMjYxIDE5My43NjEgMTk2LjUgMTkxIDE5Ni41SDEzMUMxMjguMjM5IDE5Ni41IDEyNiAxOTQuMjYxIDEyNiAxOTEuNVYxODRIMTE2WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTY2LjQ5NCAxMDUuOTI0QzE2NS44NjkgMTA0LjM0MiAxNjMuNjI5IDEwNC4zNDIgMTYzLjAwNSAxMDUuOTI0TDE1OS43NDUgMTE0LjE5MUMxNTkuNTU0IDExNC42NzQgMTU5LjE3MiAxMTUuMDU3IDE1OC42ODggMTE1LjI0N0wxNTAuNDIyIDExOC41MDhDMTQ4LjgzOSAxMTkuMTMyIDE0OC44MzkgMTIxLjM3MiAxNTAuNDIyIDEyMS45OTZMMTU4LjY4OCAxMjUuMjU2QzE1OS4xNzIgMTI1LjQ0NyAxNTkuNTU0IDEyNS44MjkgMTU5Ljc0NSAxMjYuMzEzTDE2My4wMDUgMTM0LjU3OUMxNjMuNjI5IDEzNi4xNjIgMTY1Ljg2OSAxMzYuMTYyIDE2Ni40OTQgMTM0LjU3OUwxNjkuNzU0IDEyNi4zMTNDMTY5Ljk0NCAxMjUuODI5IDE3MC4zMjcgMTI1LjQ0NyAxNzAuODEgMTI1LjI1NkwxNzkuMDc3IDEyMS45OTZDMTgwLjY2IDEyMS4zNzIgMTgwLjY2IDExOS4xMzIgMTc5LjA3NyAxMTguNTA4TDE3MC44MSAxMTUuMjQ3QzE3MC4zMjcgMTE1LjA1NyAxNjkuOTQ0IDExNC42NzQgMTY5Ljc1NCAxMTQuMTkxTDE2Ni40OTQgMTA1LjkyNFoiIGZpbGw9IiM4RjhGOEYiLz4KPHBhdGggZD0iTTEzMy4wMDUgMTI4LjQyNEMxMzMuNjI5IDEyNi44NDIgMTM1Ljg2OSAxMjYuODQyIDEzNi40OTQgMTI4LjQyNEwxNDEuODc1IDE0Mi4wN0MxNDIuMDY2IDE0Mi41NTMgMTQyLjQ0OCAxNDIuOTM1IDE0Mi45MzIgMTQzLjEyNkwxNTYuNTc3IDE0OC41MDhDMTU4LjE2IDE0OS4xMzIgMTU4LjE2IDE1MS4zNzIgMTU2LjU3NyAxNTEuOTk2TDE0Mi45MzIgMTU3LjM3OEMxNDIuNDQ4IDE1Ny41NjggMTQyLjA2NiAxNTcuOTUxIDE0MS44NzUgMTU4LjQzNEwxMzYuNDk0IDE3Mi4wNzlDMTM1Ljg2OSAxNzMuNjYyIDEzMy42MjkgMTczLjY2MiAxMzMuMDA1IDE3Mi4wNzlMMTI3LjYyMyAxNTguNDM0QzEyNy40MzMgMTU3Ljk1MSAxMjcuMDUgMTU3LjU2OCAxMjYuNTY3IDE1Ny4zNzhMMTEyLjkyMiAxNTEuOTk2QzExMS4zMzkgMTUxLjM3MiAxMTEuMzM5IDE0OS4xMzIgMTEyLjkyMiAxNDguNTA4TDEyNi41NjcgMTQzLjEyNkMxMjcuMDUgMTQyLjkzNSAxMjcuNDMzIDE0Mi41NTMgMTI3LjYyMyAxNDIuMDdMMTMzLjAwNSAxMjguNDI0WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTk1Ljk5OSAxODQuMDA0VjE5MS41MDJDMTk1Ljk5OSAxOTQuMjYzIDE5My43NjEgMTk2LjUwMiAxOTAuOTk5IDE5Ni41MDJIMTQ3LjY2OEwxNzIuODc5IDE1OC42ODRDMTc0LjM2MyAxNTYuNDU4IDE3Ny42MzUgMTU2LjQ1OCAxNzkuMTIgMTU4LjY4NEwxOTUuOTk5IDE4NC4wMDRaIiBmaWxsPSIjOEY4RjhGIi8+CjwvZz4KPC9zdmc+Cg==",de=Dt;function Rt(e,t,n){switch(t){case"image":return Nt(e,n[t]);case"video":return jt(e,n[t]);default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function Nt(e,t){let n=t.width,r=t.height;return{id:e,meta:{previewUri:de,fillType:"//ly.img.ubq/fill/image",kind:"image",width:n,height:r}}}function jt(e,t){let n=t.width,r=t.height;return{id:e,label:t.label,meta:{previewUri:de,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:n,height:r}}}var Ge=Rt;function Lt(e,t){switch(e){case"image":return Tt(t[e]);case"video":return $t(t[e]);default:throw new Error(`Unsupported output kind for creating dry run output: ${e}`)}}function Tt(e){let t=e.width,n=e.height,r=e!=null&&typeof e=="object"&&"prompt"in e&&typeof e.prompt=="string"?e.prompt:"AI Generated Image";return{kind:"image",url:`https://placehold.co/${t}x${n}/000000/FFF?text=${r.replace(" ","+").replace(`
2
- `,"+")}`}}function $t(e){return{kind:"video",url:"https://storage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"}}var Ve=Lt;async function Bt(e,t,n,r){switch(t){case"image":{if(r.kind!=="image")throw new Error(`Output kind does not match the expected type: ${r.kind} (expected: image)`);return Gt(e,n[t],r)}case"video":{if(r.kind!=="video")throw new Error(`Output kind does not match the expected type: ${r.kind} (expected: video)`);return Vt(e,n[t],r)}case"audio":{if(r.kind!=="audio")throw new Error(`Output kind does not match the expected type: ${r.kind} (expected: audio)`);return Ft(e,n[t],r)}default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function Gt(e,t,n){let r=t.width,i=t.height;return{id:e,label:t.label,meta:{uri:n.url,thumbUri:n.url,fillType:"//ly.img.ubq/fill/image",kind:"image",width:r,height:i},payload:{sourceSet:[{uri:n.url,width:r,height:i}]}}}async function Vt(e,t,n){let r=t.width,i=t.height,o=await ce(n.url,0);return{id:e,label:t.label,meta:{uri:n.url,thumbUri:o,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:r,height:i}}}function Ft(e,t,n){return{id:e,label:t.label,meta:{uri:n.url,thumbUri:n.thumbnailUrl,blockType:"//ly.img.ubq/audio",mimeType:"audio/x-m4a",duration:n.duration.toString()}}}var pe=Bt;function V(e){let t=e.filter(n=>!!n);return n=>async(r,i)=>{let o=[],a=c=>{o.push(c)},s=async(c,p,m)=>{if(c>=t.length)return n(p,m);let v=t[c],I=async(f,g)=>s(c+1,f,g),b={...m,addDisposer:a};return v(p,b,I)},l={...i,addDisposer:a};return{result:await s(0,r,l),dispose:async()=>{for(let c=o.length-1;c>=0;c--)try{await o[c]()}catch(p){console.error("Error in disposer:",p)}o.length=0}}}}function _t(){return async(t,n,r)=>{console.group("[GENERATION]"),console.log("Generating with input:",JSON.stringify(t,null,2));let i,o=Date.now();try{return i=await r(t,n),i}finally{i!=null&&(console.log(`Generation took ${Date.now()-o}ms`),console.log("Generation result:",JSON.stringify(i,null,2))),console.groupEnd()}}}var F=_t;async function Kt(e,t,n,r,i,o,a){let{cesdk:s,createPlaceholderBlock:l,historyAssetSourceId:u}=i,d;try{o.debug&&console.group(`Starting Generation for '${e}'`);let c=t(),p=await n(c.input),m=Re(),v;if(l){if(v=Ge(m,e,p),o.debug&&console.log("Adding as asset to scene:",JSON.stringify(v,void 0,2)),d=await Pe(s,v),d!=null&&r.kind==="video"){let g=s.engine.block.getPositionX(d),h=s.engine.block.getPositionY(d),y=s.engine.block.duplicate(d);s.engine.block.setPositionX(y,g),s.engine.block.setPositionY(y,h),s.engine.block.destroy(d),d=y}if(W(s,a,d))return{status:"aborted"};if(d==null)throw new Error("Could not create placeholder block");s.engine.block.setState(d,{type:"Pending",progress:0})}let I=V([...r.output.middleware??[],o.debug?F():void 0]),b;if(o.dryRun?b=await Ut(e,p):b=(await I(r.output.generate)(c.input,{abortSignal:a,engine:i.engine,cesdk:s})).result,A(b))throw new Error("Streaming generation is not supported yet from a panel");if(W(s,a,d))return{status:"aborted"};if(b==null)throw new Error("Generation failed");o.debug&&console.log("Generated output:",JSON.stringify(b,void 0,2));let f;if(d!=null&&s.engine.block.isValid(d)&&(f=await pe(m,e,p,b),o.debug&&console.log("Updating asset in scene:",JSON.stringify(f,void 0,2)),await s.engine.asset.defaultApplyAssetToBlock(f,d)),W(s,a,d))return{status:"aborted"};if(u!=null){if(f==null&&(f=await pe(m,e,p,b),W(s,a,d)))return{status:"aborted"};let g={...f,id:`${Date.now()}-${f.id}`,label:f.label!=null?{en:f.label}:{},tags:{}};s.engine.asset.addAssetToSource(u,g)}return d!=null&&s.engine.block.isValid(d)&&s.engine.block.setState(d,{type:"Ready"}),{status:"success",output:b}}catch(c){throw d!=null&&s.engine.block.isValid(d)&&(k(c)?s.engine.block.destroy(d):s.engine.block.setState(d,{type:"Error",error:"Unknown"})),c}finally{o.debug&&console.groupEnd()}}function W(e,t,n){return t.aborted?(n!=null&&e.engine.block.isValid(n)&&e.engine.block.destroy(n),!0):!1}async function Ut(e,t){console.log("[DRY RUN]: Requesting dummy AI generation with block inputs: ",JSON.stringify(t,void 0,2));let n=Ve(e,t);return await zt(3e3),n}async function zt(e){return new Promise(t=>{setTimeout(t,e)})}var Fe=Kt;function Ht(e,t,n){let{cesdk:r,provider:i,getInput:o}=t;n.onError!=null&&typeof n.onError=="function"?n.onError(e):(console.error("Generation failed:",e),Qt(r,i.output.notification,()=>({input:o?.().input,error:e}))||r.ui.showNotification({type:"error",message:De(e)}))}function Qt(e,t,n){let r=t?.error;if(r==null||!(typeof r.show=="function"?r.show(n()):r.show))return!1;let o=typeof r.message=="function"?r.message(n()):r.message??"common.ai-generation.failed",a=r.action!=null?{label:typeof r.action.label=="function"?r.action.label(n()):r.action.label,onClick:()=>{r?.action?.onClick(n())}}:void 0;return e.ui.showNotification({type:"error",message:o,action:a}),!0}var E=Ht;function J(e){return`${e}.generating`}function _e(e){return`${e}.abort`}function Zt(e,t,n,r,i,o){let{builder:a,experimental:s}=e,{cesdk:l,includeHistoryLibrary:u=!0}=i,{id:d,output:{abortable:c}}=t,p=s.global(_e(d),()=>{}),m=s.global(J(d),!1),v,I=m.value&&c,b=()=>{I&&(p.value(),m.setValue(!1),p.setValue(()=>{}))},f;if(i.requiredInputs!=null&&i.requiredInputs.length>0){let h=n();f=i.requiredInputs.every(y=>!h.input[y])}let g=s.global(`${d}.confirmationDialogId`,void 0);a.Section(`${d}.generate.section`,{children:()=>{a.Button(`${d}.generate`,{label:["common.ai-generation.generate",`panel.${d}.generate`],isLoading:m.value,color:"accent",isDisabled:f,suffix:I?{icon:"@imgly/Cross",color:"danger",tooltip:[`panel.${d}.abort`,"common.cancel"],onClick:()=>{let h=l.ui.showDialog({type:"warning",content:"panel.ly.img.ai.generation.confirmCancel.content",cancel:{label:"common.close",onClick:({id:y})=>{l.ui.closeDialog(y),g.setValue(void 0)}},actions:{label:"panel.ly.img.ai.generation.confirmCancel.confirm",color:"danger",onClick:({id:y})=>{b(),l.ui.closeDialog(y),g.setValue(void 0)}}});g.setValue(h)}}:void 0,onClick:async()=>{v=new AbortController;let h=v.signal,y=async()=>{try{m.setValue(!0),p.setValue(()=>{o.debug&&console.log("Aborting generation"),v?.abort()});let O=await Fe(t.kind,n,r,t,i,o,h);if(O.status==="aborted")return;let w=t.output.notification;qt(l,w,()=>({input:n().input,output:O.output}))}catch(O){if(k(O))return;E(O,{cesdk:l,provider:t,getInput:n},o)}finally{v=void 0,m.setValue(!1),p.setValue(()=>{}),g.value!=null&&(l.ui.closeDialog(g.value),g.setValue(void 0))}};o.middleware!=null?await o.middleware(y,{provider:t,abort:b}):await y()}}),t.output.generationHintText!=null&&a.Text(`${d}.generation-hint`,{align:"center",content:t.output.generationHintText})}}),u&&i.historyAssetLibraryEntryId!=null&&a.Library(`${d}.history.library`,{entries:[i.historyAssetLibraryEntryId]})}function qt(e,t,n){let r=t?.success;if(r==null||!(typeof r.show=="function"?r.show(n()):r.show))return!1;let o=typeof r.message=="function"?r.message(n()):r.message??"common.ai-generation.success",a=r.action!=null?{label:typeof r.action.label=="function"?r.action.label(n()):r.action.label,onClick:()=>{r?.action?.onClick(n())}}:void 0;return e.ui.showNotification({type:"success",message:o,action:a,duration:r.duration}),!0}var X=Zt;async function Yt(e,t,n,r){let{cesdk:i}=n,{id:o}=e;r.debug&&console.log(`Registering schema-based panel input for provider ${o}`);let a=le(t.document),s=se(a,t.inputReference);if(!Se(s,r.debug))throw new Error(`Input reference '${t.inputReference}' does not resolve to a valid OpenAPI schema`);let l=s,u=q(l,t),d=c=>{let{builder:p}=c,m=[];p.Section(`${o}.schema.section`,{children:()=>{u.forEach(f=>{let g=Be(c,f,e,t,n,r);g!=null&&(Array.isArray(g)?m.push(...g):m.push(g))})}});let v=m.map(f=>f()),I=f=>f.type==="object"?Object.entries(f.value).reduce((g,[h,y])=>(g[h]=I(y),g),{}):f.value,b=v.reduce((f,g)=>(f[g.id]=I(g),f),{});X(c,e,()=>({input:b}),()=>t.getBlockInput(b),{...n,requiredInputs:l.required,createPlaceholderBlock:t.userFlow==="placeholder"},r)};return i.ui.registerPanel(G(o),d),d}var Ke=Yt;async function Wt(e,t,n,r){let{cesdk:i}=n,{id:o}=e,a=t.render,s=l=>{let{state:u}=l,d=u(J(o),{isGenerating:!1,abort:()=>{}}).value.isGenerating,{getInput:c,getBlockInput:p}=a(l,{cesdk:i,isGenerating:d});return X(l,e,c,p,{...n,includeHistoryLibrary:t.includeHistoryLibrary??!0,createPlaceholderBlock:t.userFlow==="placeholder"},r),c};return i.ui.registerPanel(G(o),s),s}var Ue=Wt;var ot=class{constructor(e,t,n){this.assetStoreName="assets",this.blobStoreName="blobs",this.db=null,this.id=e,this.engine=t,this.dbName=n?.dbName??`ly.img.assetSource/${e}`,this.dbVersion=n?.dbVersion??1}async initialize(){if(!this.db)return new Promise((e,t)=>{let n=indexedDB.open(this.dbName,this.dbVersion);n.onerror=r=>{t(new Error(`Failed to open IndexedDB: ${r.target.error}`))},n.onupgradeneeded=r=>{let i=r.target.result;i.objectStoreNames.contains(this.assetStoreName)||i.createObjectStore(this.assetStoreName,{keyPath:"id"}),i.objectStoreNames.contains(this.blobStoreName)||i.createObjectStore(this.blobStoreName,{keyPath:"id"})},n.onsuccess=r=>{this.db=r.target.result,e()}})}close(){this.db&&(this.db.close(),this.db=null)}async findAssets(e){if(await this.initialize(),!this.db)throw new Error("Database not initialized");try{let t=(await this.getAllAssets("asc")).reduce((l,u)=>{let d=e.locale??"en",c="",p=[];u.label!=null&&typeof u.label=="object"&&u.label[d]&&(c=u.label[d]),u.tags!=null&&typeof u.tags=="object"&&u.tags[d]&&(p=u.tags[d]);let m={...u,label:c,tags:p};return this.filterAsset(m,e)&&l.push(m),l},[]);t=await this.restoreBlobUrls(t),t=this.sortAssets(t,e);let{page:n,perPage:r}=e,i=n*r,o=i+r,a=t.slice(i,o),s=o<t.length?n+1:void 0;return{assets:a,currentPage:n,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 n=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).getAll();n.onsuccess=()=>{let r=new Set;n.result.forEach(o=>{o.groups&&Array.isArray(o.groups)&&o.groups.forEach(a=>r.add(a))});let i=[...r];e(i)},n.onerror=()=>{t(new Error(`Failed to get groups: ${n.error}`))}})}addAsset(e){this.initialize().then(async()=>{if(!this.db)throw new Error("Database not initialized");let t=this.db.transaction(this.assetStoreName,"readwrite"),n=t.objectStore(this.assetStoreName),r=new Set;R(e,o=>{r.add(o)}),setTimeout(()=>{this.storeBlobUrls([...r])});let i={...e,meta:{...e.meta,insertedAt:e.meta?.insertedAt||Date.now()}};n.put(i),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 n=this.db.transaction(this.assetStoreName,"readwrite");n.objectStore(this.assetStoreName).delete(e),n.oncomplete=()=>{R(t,r=>{this.removeBlob(r)}),this.engine.asset.assetSourceContentsChanged(this.id)},n.onerror=()=>{console.error(`Failed to remove asset: ${n.error}`)}}).catch(n=>{console.error("Error initializing database:",n)})}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,n)=>{let r=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).getAll();r.onsuccess=()=>{let i=r.result;i.sort((o,a)=>{let s=o.meta?.insertedAt||o._insertedAt||Date.now(),l=a.meta?.insertedAt||a._insertedAt||Date.now();return e==="asc"?s-l:l-s}),t(i)},r.onerror=()=>{n(new Error(`Failed to get assets: ${r.error}`))}})}async getAsset(e){return new Promise((t,n)=>{let r=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).get(e);r.onsuccess=()=>{t(r.result)},r.onerror=()=>{n(new Error(`Failed to get blob: ${r.error}`))}})}async getBlob(e){return new Promise((t,n)=>{let r=this.db.transaction(this.blobStoreName,"readonly").objectStore(this.blobStoreName).get(e);r.onsuccess=()=>{t(r.result)},r.onerror=()=>{n(new Error(`Failed to get blob: ${r.error}`))}})}async createBlobUrlFromStore(e){let t=await this.getBlob(e);return t!=null?URL.createObjectURL(t.blob):e}async storeBlobUrls(e){let t={};return await Promise.all(e.map(async n=>{let r=await(await fetch(n)).blob();t[n]=r})),this.initialize().then(async()=>{if(!this.db)throw new Error("Database not initialized");let n=this.db.transaction(this.blobStoreName,"readwrite"),r=n.objectStore(this.blobStoreName);Object.entries(t).forEach(([i,o])=>{let a={id:i,blob:o};r.put(a)}),n.onerror=()=>{console.error(`Failed to add blobs: ${n.error}`)}}).catch(n=>{console.error("Error initializing database:",n)})}async restoreBlobUrls(e){let t={},n=new Set;return R(e,r=>{n.add(r)}),await Promise.all([...n].map(async r=>{let i=await this.createBlobUrlFromStore(r);t[r]=i})),R(e,r=>t[r]??r)}filterAsset(e,t){let{query:n,tags:r,groups:i,excludeGroups:o}=t;if(n&&n.trim()!==""){let a=n.trim().toLowerCase().split(" "),s=e.label?.toLowerCase()??"",l=e.tags?.map(u=>u.toLowerCase())??[];if(!a.every(u=>s.includes(u)||l.some(d=>d.includes(u))))return!1}if(r){let a=Array.isArray(r)?r:[r];if(a.length>0&&(!e.tags||!a.every(s=>e.tags?.includes(s))))return!1}return!(i&&i.length>0&&(!e.groups||!i.some(a=>e.groups?.includes(a)))||o&&o.length>0&&e.groups&&e.groups.some(a=>o.includes(a)))}sortAssets(e,t){let{sortingOrder:n,sortKey:r,sortActiveFirst:i}=t,o=[...e];return!n||n==="None"||(r?o.sort((a,s)=>{let l,u;return r==="id"?(l=a.id,u=s.id):(l=a.meta?.[r]??null,u=s.meta?.[r]??null),l==null?n==="Ascending"?-1:1:u==null?n==="Ascending"?1:-1:typeof l=="string"&&typeof u=="string"?n==="Ascending"?l.localeCompare(u):u.localeCompare(l):n==="Ascending"?l<u?-1:l>u?1:0:l>u?-1:l<u?1:0}):n==="Descending"&&o.reverse(),i&&o.sort((a,s)=>a.active&&!s.active?-1:!a.active&&s.active?1:0)),o}};function R(e,t,n=""){if(e===null||typeof e!="object")return e;if(Array.isArray(e)){for(let r=0;r<e.length;r++){let i=n?`${n}[${r}]`:`[${r}]`;if(typeof e[r]=="string"&&e[r].startsWith("blob:")){let o=t(e[r],i);typeof o=="string"&&(e[r]=o)}else e[r]=R(e[r],t,i)}return e}for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)){let i=e[r],o=n?`${n}.${r}`:r;if(typeof i=="string"&&i.startsWith("blob:")){let a=t(i,o);typeof a=="string"&&(e[r]=a)}else e[r]=R(i,t,o)}return e}var Jt=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)}},ve=Jt,Xt=typeof global=="object"&&global&&global.Object===Object&&global,at=Xt,er=typeof self=="object"&&self&&self.Object===Object&&self,tr=at||er||Function("return this")(),M=tr,rr=M.Symbol,N=rr,st=Object.prototype,nr=st.hasOwnProperty,ir=st.toString,_=N?N.toStringTag:void 0;function or(e){var t=nr.call(e,_),n=e[_];try{e[_]=void 0;var r=!0}catch{}var i=ir.call(e);return r&&(t?e[_]=n:delete e[_]),i}var ar=or,sr=Object.prototype,lr=sr.toString;function ur(e){return lr.call(e)}var cr=ur,dr="[object Null]",pr="[object Undefined]",ze=N?N.toStringTag:void 0;function fr(e){return e==null?e===void 0?pr:dr:ze&&ze in Object(e)?ar(e):cr(e)}var H=fr;function gr(e){return e!=null&&typeof e=="object"}var Oe=gr,da=Array.isArray;function mr(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var lt=mr,yr="[object AsyncFunction]",br="[object Function]",hr="[object GeneratorFunction]",Ir="[object Proxy]";function vr(e){if(!lt(e))return!1;var t=H(e);return t==br||t==hr||t==yr||t==Ir}var Or=vr,Cr=M["__core-js_shared__"],fe=Cr,He=function(){var e=/[^.]+$/.exec(fe&&fe.keys&&fe.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function wr(e){return!!He&&He in e}var xr=wr,kr=Function.prototype,Mr=kr.toString;function Ar(e){if(e!=null){try{return Mr.call(e)}catch{}try{return e+""}catch{}}return""}var S=Ar,Er=/[\\^$.*+?()[\]{}|]/g,Sr=/^\[object .+?Constructor\]$/,Pr=Function.prototype,Dr=Object.prototype,Rr=Pr.toString,Nr=Dr.hasOwnProperty,jr=RegExp("^"+Rr.call(Nr).replace(Er,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Lr(e){if(!lt(e)||xr(e))return!1;var t=Or(e)?jr:Sr;return t.test(S(e))}var Tr=Lr;function $r(e,t){return e?.[t]}var Br=$r;function Gr(e,t){var n=Br(e,t);return Tr(n)?n:void 0}var j=Gr,Vr=j(M,"WeakMap"),me=Vr;function Fr(e,t){return e===t||e!==e&&t!==t}var _r=Fr,Kr=9007199254740991;function Ur(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=Kr}var zr=Ur;var pa=Object.prototype;var Hr="[object Arguments]";function Qr(e){return Oe(e)&&H(e)==Hr}var Qe=Qr,ut=Object.prototype,Zr=ut.hasOwnProperty,qr=ut.propertyIsEnumerable,fa=Qe(function(){return arguments}())?Qe:function(e){return Oe(e)&&Zr.call(e,"callee")&&!qr.call(e,"callee")};var ct=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Ze=ct&&typeof module=="object"&&module&&!module.nodeType&&module,Yr=Ze&&Ze.exports===ct,qe=Yr?M.Buffer:void 0,ga=qe?qe.isBuffer:void 0;var Wr="[object Arguments]",Jr="[object Array]",Xr="[object Boolean]",en="[object Date]",tn="[object Error]",rn="[object Function]",nn="[object Map]",on="[object Number]",an="[object Object]",sn="[object RegExp]",ln="[object Set]",un="[object String]",cn="[object WeakMap]",dn="[object ArrayBuffer]",pn="[object DataView]",fn="[object Float32Array]",gn="[object Float64Array]",mn="[object Int8Array]",yn="[object Int16Array]",bn="[object Int32Array]",hn="[object Uint8Array]",In="[object Uint8ClampedArray]",vn="[object Uint16Array]",On="[object Uint32Array]",C={};C[fn]=C[gn]=C[mn]=C[yn]=C[bn]=C[hn]=C[In]=C[vn]=C[On]=!0;C[Wr]=C[Jr]=C[dn]=C[Xr]=C[pn]=C[en]=C[tn]=C[rn]=C[nn]=C[on]=C[an]=C[sn]=C[ln]=C[un]=C[cn]=!1;function Cn(e){return Oe(e)&&zr(e.length)&&!!C[H(e)]}var wn=Cn;function xn(e){return function(t){return e(t)}}var kn=xn,dt=typeof exports=="object"&&exports&&!exports.nodeType&&exports,K=dt&&typeof module=="object"&&module&&!module.nodeType&&module,Mn=K&&K.exports===dt,ge=Mn&&at.process,An=function(){try{var e=K&&K.require&&K.require("util").types;return e||ge&&ge.binding&&ge.binding("util")}catch{}}(),Ye=An,We=Ye&&Ye.isTypedArray,ma=We?kn(We):wn;var En=Object.prototype,ya=En.hasOwnProperty;function Sn(e,t){return function(n){return e(t(n))}}var Pn=Sn,ba=Pn(Object.keys,Object);var Dn=Object.prototype,ha=Dn.hasOwnProperty;var Rn=j(Object,"create"),U=Rn;function Nn(){this.__data__=U?U(null):{},this.size=0}var jn=Nn;function Ln(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var Tn=Ln,$n="__lodash_hash_undefined__",Bn=Object.prototype,Gn=Bn.hasOwnProperty;function Vn(e){var t=this.__data__;if(U){var n=t[e];return n===$n?void 0:n}return Gn.call(t,e)?t[e]:void 0}var Fn=Vn,_n=Object.prototype,Kn=_n.hasOwnProperty;function Un(e){var t=this.__data__;return U?t[e]!==void 0:Kn.call(t,e)}var zn=Un,Hn="__lodash_hash_undefined__";function Qn(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=U&&t===void 0?Hn:t,this}var Zn=Qn;function L(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}L.prototype.clear=jn;L.prototype.delete=Tn;L.prototype.get=Fn;L.prototype.has=zn;L.prototype.set=Zn;var Je=L;function qn(){this.__data__=[],this.size=0}var Yn=qn;function Wn(e,t){for(var n=e.length;n--;)if(_r(e[n][0],t))return n;return-1}var ee=Wn,Jn=Array.prototype,Xn=Jn.splice;function ei(e){var t=this.__data__,n=ee(t,e);if(n<0)return!1;var r=t.length-1;return n==r?t.pop():Xn.call(t,n,1),--this.size,!0}var ti=ei;function ri(e){var t=this.__data__,n=ee(t,e);return n<0?void 0:t[n][1]}var ni=ri;function ii(e){return ee(this.__data__,e)>-1}var oi=ii;function ai(e,t){var n=this.__data__,r=ee(n,e);return r<0?(++this.size,n.push([e,t])):n[r][1]=t,this}var si=ai;function T(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}T.prototype.clear=Yn;T.prototype.delete=ti;T.prototype.get=ni;T.prototype.has=oi;T.prototype.set=si;var te=T,li=j(M,"Map"),z=li;function ui(){this.size=0,this.__data__={hash:new Je,map:new(z||te),string:new Je}}var ci=ui;function di(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var pi=di;function fi(e,t){var n=e.__data__;return pi(t)?n[typeof t=="string"?"string":"hash"]:n.map}var re=fi;function gi(e){var t=re(this,e).delete(e);return this.size-=t?1:0,t}var mi=gi;function yi(e){return re(this,e).get(e)}var bi=yi;function hi(e){return re(this,e).has(e)}var Ii=hi;function vi(e,t){var n=re(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this}var Oi=vi;function $(e){var t=-1,n=e==null?0:e.length;for(this.clear();++t<n;){var r=e[t];this.set(r[0],r[1])}}$.prototype.clear=ci;$.prototype.delete=mi;$.prototype.get=bi;$.prototype.has=Ii;$.prototype.set=Oi;var pt=$;function Ci(){this.__data__=new te,this.size=0}var wi=Ci;function xi(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n}var ki=xi;function Mi(e){return this.__data__.get(e)}var Ai=Mi;function Ei(e){return this.__data__.has(e)}var Si=Ei,Pi=200;function Di(e,t){var n=this.__data__;if(n instanceof te){var r=n.__data__;if(!z||r.length<Pi-1)return r.push([e,t]),this.size=++n.size,this;n=this.__data__=new pt(r)}return n.set(e,t),this.size=n.size,this}var Ri=Di;function Q(e){var t=this.__data__=new te(e);this.size=t.size}Q.prototype.clear=wi;Q.prototype.delete=ki;Q.prototype.get=Ai;Q.prototype.has=Si;Q.prototype.set=Ri;var Ni=Object.prototype,Ia=Ni.propertyIsEnumerable;var ji=j(M,"DataView"),ye=ji,Li=j(M,"Promise"),be=Li,Ti=j(M,"Set"),he=Ti,Xe="[object Map]",$i="[object Object]",et="[object Promise]",tt="[object Set]",rt="[object WeakMap]",nt="[object DataView]",Bi=S(ye),Gi=S(z),Vi=S(be),Fi=S(he),_i=S(me),D=H;(ye&&D(new ye(new ArrayBuffer(1)))!=nt||z&&D(new z)!=Xe||be&&D(be.resolve())!=et||he&&D(new he)!=tt||me&&D(new me)!=rt)&&(D=function(e){var t=H(e),n=t==$i?e.constructor:void 0,r=n?S(n):"";if(r)switch(r){case Bi:return nt;case Gi:return Xe;case Vi:return et;case Fi:return tt;case _i:return rt}return t});var va=M.Uint8Array;var Ki="__lodash_hash_undefined__";function Ui(e){return this.__data__.set(e,Ki),this}var zi=Ui;function Hi(e){return this.__data__.has(e)}var Qi=Hi;function Ie(e){var t=-1,n=e==null?0:e.length;for(this.__data__=new pt;++t<n;)this.add(e[t])}Ie.prototype.add=Ie.prototype.push=zi;Ie.prototype.has=Qi;var it=N?N.prototype:void 0,Oa=it?it.valueOf:void 0;var Zi=Object.prototype,Ca=Zi.hasOwnProperty;var qi=Object.prototype,wa=qi.hasOwnProperty;var xa=new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,"i"),ka=new RegExp(/[A-Fa-f0-9]{1}/,"g"),Ma=new RegExp(/[A-Fa-f0-9]{2}/,"g");var Ce="@imgly/plugin-ai-generation",Yi=`
1
+ function Dt(e,t){let{cesdk:r}=t,n=t.propertyKey??"image_url";return Rt(e,r),{[n]:(o,a)=>{let{builder:s,experimental:{global:l},payload:u}=o,d=u?.url??t.defaultUrl,c=l(`${e}.${a.id}`,d);return s.MediaPreview(a.id,{preview:{type:"image",uri:c.value},action:{label:"Select Image",onClick:()=>{if(r==null)return;let p=ge(e);r.ui.openPanel(p,{payload:{onSelect:f=>{f.meta?.uri!=null&&c.setValue(f.meta?.uri)}}})}}}),()=>({id:a.id,type:"string",value:c.value})}}}function Rt(e,t){t?.ui.registerPanel(ge(e),({builder:r,payload:n})=>{r.Library(`${e}.library.image`,{entries:["ly.img.image"],onSelect:async i=>{let o=i?.meta?.uri;if(o==null)return;let a=await t.engine.editor.getMimeType(o);a==="image/svg+xml"?t.ui.showNotification({type:"warning",message:"SVG images are not supported. Please choose a different image."}):a.startsWith("image/")?(n?.onSelect(i),t?.ui.closePanel(ge(e))):t.ui.showNotification({type:"warning",message:`Only images are supported. Found '${a}'. Please choose a different image.`})}})})}function ge(e){return`ly.img.ai/${e}.imageSelection`}var Te=Dt;function ye(e,t){if(!t.startsWith("#/"))throw new Error(`External references are not supported: ${t}`);let r=t.substring(2).split("/"),n=e;for(let i of r){if(n==null)throw new Error(`Invalid reference path: ${t}`);n=n[i]}if(n===void 0)throw new Error(`Reference not found: ${t}`);return n}function K(e,t,r=new Set){if(t==null||r.has(t))return t;if(r.add(t),t.$ref&&typeof t.$ref=="string"){let n=ye(e,t.$ref),o={...K(e,n,r)};for(let a in t)Object.prototype.hasOwnProperty.call(t,a)&&a!=="$ref"&&(o[a]=K(e,t[a],r));return o}if(Array.isArray(t))return t.map(n=>K(e,n,r));if(typeof t=="object"){let n={};for(let i in t)Object.prototype.hasOwnProperty.call(t,i)&&(n[i]=K(e,t[i],r));return n}return t}function be(e){return K(e,{...e})}function Be(e,t=!1){let r=s=>(t&&console.log(`OpenAPI Schema validation failed: ${s}`),!1);if(typeof e!="object"||e===null)return r(`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 r("Missing required schema-defining properties (type, enum, properties, items, allOf, anyOf, oneOf, not)");if(n.type!==void 0){let s=["string","number","integer","boolean","array","object","null"];if(typeof n.type=="string"){if(!s.includes(n.type))return r(`Invalid type: ${n.type}. Must be one of ${s.join(", ")}`)}else if(Array.isArray(n.type)){for(let l of n.type)if(typeof l!="string"||!s.includes(l))return r(`Array of types contains invalid value: ${l}. Must be one of ${s.join(", ")}`)}else return r(`Type must be a string or array of strings, got ${typeof n.type}`)}if(n.items!==void 0&&(typeof n.items!="object"||n.items===null))return r(`Items must be an object, got ${n.items===null?"null":typeof n.items}`);if(n.properties!==void 0&&(typeof n.properties!="object"||n.properties===null))return r(`Properties must be an object, got ${n.properties===null?"null":typeof n.properties}`);let o=["allOf","anyOf","oneOf"];for(let s of o)if(n[s]!==void 0){if(!Array.isArray(n[s]))return r(`${s} must be an array, got ${typeof n[s]}`);for(let l=0;l<n[s].length;l++){let u=n[s][l];if(typeof u!="object"||u===null)return r(`Item ${l} in ${s} must be an object, got ${u===null?"null":typeof u}`)}}if(n.not!==void 0&&(typeof n.not!="object"||n.not===null))return r(`'not' must be an object, got ${n.not===null?"null":typeof n.not}`);if(n.additionalProperties!==void 0&&typeof n.additionalProperties!="boolean"&&(typeof n.additionalProperties!="object"||n.additionalProperties===null))return r(`additionalProperties must be a boolean or an object, got ${n.additionalProperties===null?"null":typeof n.additionalProperties}`);if(n.format!==void 0&&typeof n.format!="string")return r(`format must be a string, got ${typeof n.format}`);let a=["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf"];for(let s of a)if(n[s]!==void 0&&typeof n[s]!="number")return r(`${s} must be a number, got ${typeof n[s]}`);if(n.minLength!==void 0&&(typeof n.minLength!="number"||n.minLength<0))return r(`minLength must be a non-negative number, got ${typeof n.minLength=="number"?n.minLength:typeof n.minLength}`);if(n.maxLength!==void 0&&(typeof n.maxLength!="number"||n.maxLength<0))return r(`maxLength must be a non-negative number, got ${typeof n.maxLength=="number"?n.maxLength:typeof n.maxLength}`);if(n.pattern!==void 0&&typeof n.pattern!="string")return r(`pattern must be a string, got ${typeof n.pattern}`);if(n.minItems!==void 0&&(typeof n.minItems!="number"||n.minItems<0))return r(`minItems must be a non-negative number, got ${typeof n.minItems=="number"?n.minItems:typeof n.minItems}`);if(n.maxItems!==void 0&&(typeof n.maxItems!="number"||n.maxItems<0))return r(`maxItems must be a non-negative number, got ${typeof n.maxItems=="number"?n.maxItems:typeof n.maxItems}`);if(n.uniqueItems!==void 0&&typeof n.uniqueItems!="boolean")return r(`uniqueItems must be a boolean, got ${typeof n.uniqueItems}`);if(n.minProperties!==void 0&&(typeof n.minProperties!="number"||n.minProperties<0))return r(`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 r(`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 r(`required must be an array, got ${typeof n.required}`);for(let s=0;s<n.required.length;s++){let l=n.required[s];if(typeof l!="string")return r(`Item ${s} in required array must be a string, got ${typeof l}`)}}return!0}function Nt(e,t){if(e.properties==null)throw new Error("Input schema must have properties");let r=[],n=Lt(e,t);return n??(Object.entries(e.properties).forEach(i=>{let o=i[0],a=i[1];r.push({id:o,schema:a})}),r)}function Lt(e,t){if(t.orderExtensionKeyword==null)return;let r=[];if(typeof t.orderExtensionKeyword!="string"&&!Array.isArray(t.orderExtensionKeyword))throw new Error("orderExtensionKeyword must be a string or an array of strings");let n=typeof t.orderExtensionKeyword=="string"?[t.orderExtensionKeyword]:t.orderExtensionKeyword,i=n.find(a=>a in e);if(i==null)return;let o=e[i];if(o==null||Array.isArray(o)===!1)throw new Error(`Extension keyword ${i} must be an array of strings`);if([...new Set(o)].forEach(a=>{let s=e.properties?.[a];s!=null&&r.push({id:a,schema:s})}),r.length===0)throw new Error(`Could not find any properties with order extension keyword(s) ${n.join(", ")}`);return r}var ee=Nt;var jt="ly.img.ai",he="ly.img.ai/temp";async function Fe(e,t){return e.engine.asset.findAllSources().includes(he)||e.engine.asset.addLocalSource(he),e.engine.asset.apply(he,t)}function _(e){return`${jt}/${e}`}function Ve(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 Ge(){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 $t(e){return new Promise((t,r)=>{try{let n=document.createElement("video");n.style.display="none",n.addEventListener("loadedmetadata",()=>{n.duration===1/0?(n.currentTime=1e101,setTimeout(()=>{n.currentTime=0,t(n.duration),document.body.removeChild(n)},50)):(t(n.duration),document.body.removeChild(n))}),n.addEventListener("error",()=>{document.body.removeChild(n),r(new Error(`Failed to load video from ${e}`))}),n.src=e,document.body.appendChild(n)}catch(n){r(n)}})}function Ie(e,t=0,r="image/jpeg",n=.8){return new Promise((i,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 l=s.getContext("2d");if(!l){document.body.removeChild(a),o(new Error("Failed to create canvas context"));return}l.drawImage(a,0,0,s.width,s.height);try{let u=s.toDataURL(r,n);document.body.removeChild(a),i(u)}catch(u){document.body.removeChild(a),o(new Error(`Failed to create thumbnail: ${u instanceof Error?u.message:String(u)}`))}},{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 te(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 S(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 A(e){return e instanceof Error&&e.name==="AbortError"}function Ke(e,t,r,n,i,o){let a=t.schema.type;if(n.renderCustomProperty!=null&&n.renderCustomProperty[t.id]!=null)return n.renderCustomProperty[t.id](e,t);switch(a){case"string":return t.schema.enum!=null?Tt(e,t,r,n,i,o):Ue(e,t,r,n,i,o);case"boolean":return Qe(e,t,r,n,i,o);case"number":case"integer":return ze(e,t,r,n,i,o);case"object":return _e(e,t,r,n,i,o);case"array":break;case void 0:{if(t.schema.anyOf!=null&&Array.isArray(t.schema.anyOf))return Bt(e,t,r,n,i,o);break}default:console.error(`Unsupported property type: ${a}`)}}function _e(e,t,r,n,i,o){let s=ee(t.schema??{},n).reduce((l,u)=>{let d=Ke(e,u,r,n,i,o);return d!=null&&(l[u.id]=d()),l},{});return()=>({id:t.id,type:"object",value:s})}function Ue(e,t,r,n,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,u=`${r.id}.${l}`,d=t.schema.title??u,c=s(u,t.schema.default??""),p=Ft(t.schema),f=p?.component!=null&&p?.component==="TextArea"?"TextArea":"TextInput";return a[f](u,{inputLabel:d,placeholder:i.i18n?.prompt,...c}),()=>({id:t.id,type:"string",value:c.value})}function Tt(e,t,r,n,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,u=`${r.id}.${l}`,d=t.schema.title??u,c=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"]:{},f=(t.schema.enum??[]).map(y=>({id:y,label:c[y]??te(y),icon:p[y]})),k=t.schema.default!=null?f.find(y=>y.id===t.schema.default)??f[0]:f[0],I=s(u,k);return a.Select(u,{inputLabel:d,values:f,...I}),()=>({id:t.id,type:"string",value:I.value.id})}function Qe(e,t,r,n,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,u=`${r.id}.${l}`,d=t.schema.title??u,c=!!t.schema.default,p=s(u,c);return a.Checkbox(u,{inputLabel:d,...p}),()=>({id:t.id,type:"boolean",value:p.value})}function ze(e,t,r,n,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,u=`${r.id}.${l}`,d=t.schema.title??u,c=t.schema.minimum,p=t.schema.maximum,f=t.schema.default;f==null&&(c!=null?f=c:p!=null?f=p:f=0);let k=s(u,f);if(c!=null&&p!=null){let I=t.schema.type==="number"?.1:1;"x-imgly-step"in t.schema&&typeof t.schema["x-imgly-step"]=="number"&&(I=t.schema["x-imgly-step"]),a.Slider(u,{inputLabel:d,min:c,max:p,step:I,...k})}else a.NumberInput(u,{inputLabel:d,min:c,max:p,...k});return()=>({id:t.id,type:"integer",value:k.value})}function Bt(e,t,r,n,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,u=`${r.id}.${l}`,d=t.schema.title??u,c=t.schema.anyOf??[],p=[],f={},k={};c.forEach((m,g)=>{let b=m.title??"common.custom",h=`${r.id}.${l}.anyOf[${g}]`,O="x-imgly-enum-labels"in t.schema&&typeof t.schema["x-imgly-enum-labels"]=="object"?t.schema["x-imgly-enum-labels"]:{},C="x-imgly-enum-icons"in t.schema&&typeof t.schema["x-imgly-enum-icons"]=="object"?t.schema["x-imgly-enum-icons"]:{};m.type==="string"?m.enum!=null?m.enum.forEach(w=>{p.push({id:w,label:O[w]??te(w),icon:C[w]})}):(f[h]=()=>Ue(e,{id:h,schema:{...m,title:b}},r,n,i,o),p.push({id:h,label:O[b]??b,icon:C[b]})):m.type==="boolean"?(f[h]=()=>Qe(e,{id:h,schema:{...m,title:b}},r,n,i,o),p.push({id:h,label:O[b]??b,icon:C[b]})):m.type==="integer"?(f[h]=()=>ze(e,{id:h,schema:{...m,title:b}},r,n,i,o),p.push({id:h,label:O[b]??b,icon:C[b]})):m.type==="array"||m.type==="object"&&(f[h]=()=>_e(e,{id:h,schema:{...m,title:b}},r,n,i,o),p.push({id:h,label:O[b]??b,icon:C[b]}))});let I=t.schema.default!=null?p.find(m=>m.id===t.schema.default)??p[0]:p[0],y=s(u,I);if(a.Select(u,{inputLabel:d,values:p,...y}),y.value.id in f){let m=f[y.value.id]();k[y.value.id]=m}return()=>{let m=k[y.value.id];return m!=null?{...m(),id:t.id}:{id:t.id,type:"string",value:y.value.id}}}function Ft(e){if("x-imgly-builder"in e)return e["x-imgly-builder"]}var qe=Ke;var Vt="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIzIiBoZWlnaHQ9IjMyMyIgdmlld0JveD0iMCAwIDMyMyAzMjMiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIzMjMiIGhlaWdodD0iMzIzIiBmaWxsPSIjRTlFQkVEIi8+CjxnIG9wYWNpdHk9IjAuMyI+CjxwYXRoIGQ9Ik0xMTYgMTg0VjE5MS41QzExNiAxOTkuNzg0IDEyMi43MTYgMjA2LjUgMTMxIDIwNi41SDE5MUMxOTkuMjg0IDIwNi41IDIwNiAxOTkuNzg0IDIwNiAxOTEuNVYxMzEuNUMyMDYgMTIzLjIxNiAxOTkuMjg0IDExNi41IDE5MSAxMTYuNUwxOTAuOTk1IDEyNi41QzE5My43NTcgMTI2LjUgMTk2IDEyOC43MzkgMTk2IDEzMS41VjE5MS41QzE5NiAxOTQuMjYxIDE5My43NjEgMTk2LjUgMTkxIDE5Ni41SDEzMUMxMjguMjM5IDE5Ni41IDEyNiAxOTQuMjYxIDEyNiAxOTEuNVYxODRIMTE2WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTY2LjQ5NCAxMDUuOTI0QzE2NS44NjkgMTA0LjM0MiAxNjMuNjI5IDEwNC4zNDIgMTYzLjAwNSAxMDUuOTI0TDE1OS43NDUgMTE0LjE5MUMxNTkuNTU0IDExNC42NzQgMTU5LjE3MiAxMTUuMDU3IDE1OC42ODggMTE1LjI0N0wxNTAuNDIyIDExOC41MDhDMTQ4LjgzOSAxMTkuMTMyIDE0OC44MzkgMTIxLjM3MiAxNTAuNDIyIDEyMS45OTZMMTU4LjY4OCAxMjUuMjU2QzE1OS4xNzIgMTI1LjQ0NyAxNTkuNTU0IDEyNS44MjkgMTU5Ljc0NSAxMjYuMzEzTDE2My4wMDUgMTM0LjU3OUMxNjMuNjI5IDEzNi4xNjIgMTY1Ljg2OSAxMzYuMTYyIDE2Ni40OTQgMTM0LjU3OUwxNjkuNzU0IDEyNi4zMTNDMTY5Ljk0NCAxMjUuODI5IDE3MC4zMjcgMTI1LjQ0NyAxNzAuODEgMTI1LjI1NkwxNzkuMDc3IDEyMS45OTZDMTgwLjY2IDEyMS4zNzIgMTgwLjY2IDExOS4xMzIgMTc5LjA3NyAxMTguNTA4TDE3MC44MSAxMTUuMjQ3QzE3MC4zMjcgMTE1LjA1NyAxNjkuOTQ0IDExNC42NzQgMTY5Ljc1NCAxMTQuMTkxTDE2Ni40OTQgMTA1LjkyNFoiIGZpbGw9IiM4RjhGOEYiLz4KPHBhdGggZD0iTTEzMy4wMDUgMTI4LjQyNEMxMzMuNjI5IDEyNi44NDIgMTM1Ljg2OSAxMjYuODQyIDEzNi40OTQgMTI4LjQyNEwxNDEuODc1IDE0Mi4wN0MxNDIuMDY2IDE0Mi41NTMgMTQyLjQ0OCAxNDIuOTM1IDE0Mi45MzIgMTQzLjEyNkwxNTYuNTc3IDE0OC41MDhDMTU4LjE2IDE0OS4xMzIgMTU4LjE2IDE1MS4zNzIgMTU2LjU3NyAxNTEuOTk2TDE0Mi45MzIgMTU3LjM3OEMxNDIuNDQ4IDE1Ny41NjggMTQyLjA2NiAxNTcuOTUxIDE0MS44NzUgMTU4LjQzNEwxMzYuNDk0IDE3Mi4wNzlDMTM1Ljg2OSAxNzMuNjYyIDEzMy42MjkgMTczLjY2MiAxMzMuMDA1IDE3Mi4wNzlMMTI3LjYyMyAxNTguNDM0QzEyNy40MzMgMTU3Ljk1MSAxMjcuMDUgMTU3LjU2OCAxMjYuNTY3IDE1Ny4zNzhMMTEyLjkyMiAxNTEuOTk2QzExMS4zMzkgMTUxLjM3MiAxMTEuMzM5IDE0OS4xMzIgMTEyLjkyMiAxNDguNTA4TDEyNi41NjcgMTQzLjEyNkMxMjcuMDUgMTQyLjkzNSAxMjcuNDMzIDE0Mi41NTMgMTI3LjYyMyAxNDIuMDdMMTMzLjAwNSAxMjguNDI0WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTk1Ljk5OSAxODQuMDA0VjE5MS41MDJDMTk1Ljk5OSAxOTQuMjYzIDE5My43NjEgMTk2LjUwMiAxOTAuOTk5IDE5Ni41MDJIMTQ3LjY2OEwxNzIuODc5IDE1OC42ODRDMTc0LjM2MyAxNTYuNDU4IDE3Ny42MzUgMTU2LjQ1OCAxNzkuMTIgMTU4LjY4NEwxOTUuOTk5IDE4NC4wMDRaIiBmaWxsPSIjOEY4RjhGIi8+CjwvZz4KPC9zdmc+Cg==",ke=Vt;function Gt(e,t,r){switch(t){case"image":return Kt(e,r[t]);case"video":return _t(e,r[t]);default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function Kt(e,t){let r=t.width,n=t.height;return{id:e,meta:{previewUri:ke,fillType:"//ly.img.ubq/fill/image",kind:"image",width:r,height:n}}}function _t(e,t){let r=t.width,n=t.height;return{id:e,label:t.label,meta:{previewUri:ke,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:r,height:n}}}var He=Gt;async function Ut(e,t,r,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 Qt(e,r[t],n)}case"video":{if(n.kind!=="video")throw new Error(`Output kind does not match the expected type: ${n.kind} (expected: video)`);return zt(e,r[t],n)}case"audio":{if(n.kind!=="audio")throw new Error(`Output kind does not match the expected type: ${n.kind} (expected: audio)`);return qt(e,r[t],n)}default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function Qt(e,t,r){let n=t.width,i=t.height;return{id:e,label:t.label,meta:{uri:r.url,thumbUri:r.url,fillType:"//ly.img.ubq/fill/image",kind:"image",width:n,height:i},payload:{sourceSet:[{uri:r.url,width:n,height:i}]}}}async function zt(e,t,r){let n=t.width,i=t.height,o=await Ie(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:n,height:i}}}function qt(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()}}}var Oe=Ut;function U(e){let t=e.filter(r=>!!r);return r=>async(n,i)=>{let o=[],a=c=>{o.push(c)},s=async(c,p,f)=>{if(c>=t.length)return r(p,f);let k=t[c],I=async(m,g)=>s(c+1,m,g),y={...f,addDisposer:a};return k(p,y,I)},l={...i,addDisposer:a};return{result:await s(0,n,l),dispose:async()=>{for(let c=o.length-1;c>=0;c--)try{await o[c]()}catch(p){console.error("Error in disposer:",p)}o.length=0}}}}function Ht(){return async(t,r,n)=>{console.group("[GENERATION]"),console.log("Generating with input:",JSON.stringify(t,null,2));let i,o=Date.now();try{return i=await n(t,r),i}finally{i!=null&&(console.log(`Generation took ${Date.now()-o}ms`),console.log("Generation result:",JSON.stringify(i,null,2))),console.groupEnd()}}}var Q=Ht;var ut=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=n=>{t(new Error(`Failed to open IndexedDB: ${n.target.error}`))},r.onupgradeneeded=n=>{let i=n.target.result;i.objectStoreNames.contains(this.assetStoreName)||i.createObjectStore(this.assetStoreName,{keyPath:"id"}),i.objectStoreNames.contains(this.blobStoreName)||i.createObjectStore(this.blobStoreName,{keyPath:"id"})},r.onsuccess=n=>{this.db=n.target.result,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((l,u)=>{let d=e.locale??"en",c="",p=[];u.label!=null&&typeof u.label=="object"&&u.label[d]&&(c=u.label[d]),u.tags!=null&&typeof u.tags=="object"&&u.tags[d]&&(p=u.tags[d]);let f={...u,label:c,tags:p};return this.filterAsset(f,e)&&l.push(f),l},[]);t=await this.restoreBlobUrls(t),t=this.sortAssets(t,e);let{page:r,perPage:n}=e,i=r*n,o=i+n,a=t.slice(i,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 n=new Set;r.result.forEach(o=>{o.groups&&Array.isArray(o.groups)&&o.groups.forEach(a=>n.add(a))});let i=[...n];e(i)},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),n=new Set;$(e,o=>{n.add(o)}),setTimeout(()=>{this.storeBlobUrls([...n])});let i={...e,meta:{...e.meta,insertedAt:e.meta?.insertedAt||Date.now()}};r.put(i),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=()=>{$(t,n=>{this.removeBlob(n)}),this.engine.asset.assetSourceContentsChanged(this.id)},r.onerror=()=>{console.error(`Failed to remove asset: ${r.error}`)}}).catch(r=>{console.error("Error initializing database:",r)})}async removeBlob(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 n=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).getAll();n.onsuccess=()=>{let i=n.result;i.sort((o,a)=>{let s=o.meta?.insertedAt||o._insertedAt||Date.now(),l=a.meta?.insertedAt||a._insertedAt||Date.now();return e==="asc"?s-l:l-s}),t(i)},n.onerror=()=>{r(new Error(`Failed to get assets: ${n.error}`))}})}async getAsset(e){return new Promise((t,r)=>{let n=this.db.transaction(this.assetStoreName,"readonly").objectStore(this.assetStoreName).get(e);n.onsuccess=()=>{t(n.result)},n.onerror=()=>{r(new Error(`Failed to get blob: ${n.error}`))}})}async getBlob(e){return new Promise((t,r)=>{let n=this.db.transaction(this.blobStoreName,"readonly").objectStore(this.blobStoreName).get(e);n.onsuccess=()=>{t(n.result)},n.onerror=()=>{r(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 r=>{let n=await(await fetch(r)).blob();t[r]=n})),this.initialize().then(async()=>{if(!this.db)throw new Error("Database not initialized");let r=this.db.transaction(this.blobStoreName,"readwrite"),n=r.objectStore(this.blobStoreName);Object.entries(t).forEach(([i,o])=>{let a={id:i,blob:o};n.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 $(e,n=>{r.add(n)}),await Promise.all([...r].map(async n=>{let i=await this.createBlobUrlFromStore(n);t[n]=i})),$(e,n=>t[n]??n)}filterAsset(e,t){let{query:r,tags:n,groups:i,excludeGroups:o}=t;if(r&&r.trim()!==""){let a=r.trim().toLowerCase().split(" "),s=e.label?.toLowerCase()??"",l=e.tags?.map(u=>u.toLowerCase())??[];if(!a.every(u=>s.includes(u)||l.some(d=>d.includes(u))))return!1}if(n){let a=Array.isArray(n)?n:[n];if(a.length>0&&(!e.tags||!a.every(s=>e.tags?.includes(s))))return!1}return!(i&&i.length>0&&(!e.groups||!i.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:n,sortActiveFirst:i}=t,o=[...e];return!r||r==="None"||(n?o.sort((a,s)=>{let l,u;return n==="id"?(l=a.id,u=s.id):(l=a.meta?.[n]??null,u=s.meta?.[n]??null),l==null?r==="Ascending"?-1:1:u==null?r==="Ascending"?1:-1:typeof l=="string"&&typeof u=="string"?r==="Ascending"?l.localeCompare(u):u.localeCompare(l):r==="Ascending"?l<u?-1:l>u?1:0:l>u?-1:l<u?1:0}):r==="Descending"&&o.reverse(),i&&o.sort((a,s)=>a.active&&!s.active?-1:!a.active&&s.active?1:0)),o}};function $(e,t,r=""){if(e===null||typeof e!="object")return e;if(Array.isArray(e)){for(let n=0;n<e.length;n++){let i=r?`${r}[${n}]`:`[${n}]`;if(typeof e[n]=="string"&&e[n].startsWith("blob:")){let o=t(e[n],i);typeof o=="string"&&(e[n]=o)}else e[n]=$(e[n],t,i)}return e}for(let n in e)if(Object.prototype.hasOwnProperty.call(e,n)){let i=e[n],o=r?`${r}.${n}`:n;if(typeof i=="string"&&i.startsWith("blob:")){let a=t(i,o);typeof a=="string"&&(e[n]=a)}else e[n]=$(i,t,o)}return e}var Zt=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)}},ne=Zt,Yt=typeof global=="object"&&global&&global.Object===Object&&global,ct=Yt,Wt=typeof self=="object"&&self&&self.Object===Object&&self,Xt=ct||Wt||Function("return this")(),M=Xt,Jt=M.Symbol,T=Jt,dt=Object.prototype,en=dt.hasOwnProperty,tn=dt.toString,z=T?T.toStringTag:void 0;function nn(e){var t=en.call(e,z),r=e[z];try{e[z]=void 0;var n=!0}catch{}var i=tn.call(e);return n&&(t?e[z]=r:delete e[z]),i}var rn=nn,on=Object.prototype,an=on.toString;function sn(e){return an.call(e)}var ln=sn,un="[object Null]",cn="[object Undefined]",Ze=T?T.toStringTag:void 0;function dn(e){return e==null?e===void 0?cn:un:Ze&&Ze in Object(e)?rn(e):ln(e)}var Y=dn;function pn(e){return e!=null&&typeof e=="object"}var Se=pn,ca=Array.isArray;function mn(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var pt=mn,fn="[object AsyncFunction]",gn="[object Function]",yn="[object GeneratorFunction]",bn="[object Proxy]";function hn(e){if(!pt(e))return!1;var t=Y(e);return t==gn||t==yn||t==fn||t==bn}var In=hn,kn=M["__core-js_shared__"],ve=kn,Ye=function(){var e=/[^.]+$/.exec(ve&&ve.keys&&ve.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function On(e){return!!Ye&&Ye in e}var vn=On,Cn=Function.prototype,wn=Cn.toString;function An(e){if(e!=null){try{return wn.call(e)}catch{}try{return e+""}catch{}}return""}var P=An,xn=/[\\^$.*+?()[\]{}|]/g,Mn=/^\[object .+?Constructor\]$/,En=Function.prototype,Sn=Object.prototype,Pn=En.toString,Dn=Sn.hasOwnProperty,Rn=RegExp("^"+Pn.call(Dn).replace(xn,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Nn(e){if(!pt(e)||vn(e))return!1;var t=In(e)?Rn:Mn;return t.test(P(e))}var Ln=Nn;function jn(e,t){return e?.[t]}var $n=jn;function Tn(e,t){var r=$n(e,t);return Ln(r)?r:void 0}var B=Tn,Bn=B(M,"WeakMap"),we=Bn;function Fn(e,t){return e===t||e!==e&&t!==t}var Vn=Fn,Gn=9007199254740991;function Kn(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=Gn}var _n=Kn;var da=Object.prototype;var Un="[object Arguments]";function Qn(e){return Se(e)&&Y(e)==Un}var We=Qn,mt=Object.prototype,zn=mt.hasOwnProperty,qn=mt.propertyIsEnumerable,pa=We(function(){return arguments}())?We:function(e){return Se(e)&&zn.call(e,"callee")&&!qn.call(e,"callee")};var ft=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Xe=ft&&typeof module=="object"&&module&&!module.nodeType&&module,Hn=Xe&&Xe.exports===ft,Je=Hn?M.Buffer:void 0,ma=Je?Je.isBuffer:void 0;var Zn="[object Arguments]",Yn="[object Array]",Wn="[object Boolean]",Xn="[object Date]",Jn="[object Error]",er="[object Function]",tr="[object Map]",nr="[object Number]",rr="[object Object]",ir="[object RegExp]",or="[object Set]",ar="[object String]",sr="[object WeakMap]",lr="[object ArrayBuffer]",ur="[object DataView]",cr="[object Float32Array]",dr="[object Float64Array]",pr="[object Int8Array]",mr="[object Int16Array]",fr="[object Int32Array]",gr="[object Uint8Array]",yr="[object Uint8ClampedArray]",br="[object Uint16Array]",hr="[object Uint32Array]",v={};v[cr]=v[dr]=v[pr]=v[mr]=v[fr]=v[gr]=v[yr]=v[br]=v[hr]=!0;v[Zn]=v[Yn]=v[lr]=v[Wn]=v[ur]=v[Xn]=v[Jn]=v[er]=v[tr]=v[nr]=v[rr]=v[ir]=v[or]=v[ar]=v[sr]=!1;function Ir(e){return Se(e)&&_n(e.length)&&!!v[Y(e)]}var kr=Ir;function Or(e){return function(t){return e(t)}}var vr=Or,gt=typeof exports=="object"&&exports&&!exports.nodeType&&exports,q=gt&&typeof module=="object"&&module&&!module.nodeType&&module,Cr=q&&q.exports===gt,Ce=Cr&&ct.process,wr=function(){try{var e=q&&q.require&&q.require("util").types;return e||Ce&&Ce.binding&&Ce.binding("util")}catch{}}(),et=wr,tt=et&&et.isTypedArray,fa=tt?vr(tt):kr;var Ar=Object.prototype,ga=Ar.hasOwnProperty;function xr(e,t){return function(r){return e(t(r))}}var Mr=xr,ya=Mr(Object.keys,Object);var Er=Object.prototype,ba=Er.hasOwnProperty;var Sr=B(Object,"create"),H=Sr;function Pr(){this.__data__=H?H(null):{},this.size=0}var Dr=Pr;function Rr(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var Nr=Rr,Lr="__lodash_hash_undefined__",jr=Object.prototype,$r=jr.hasOwnProperty;function Tr(e){var t=this.__data__;if(H){var r=t[e];return r===Lr?void 0:r}return $r.call(t,e)?t[e]:void 0}var Br=Tr,Fr=Object.prototype,Vr=Fr.hasOwnProperty;function Gr(e){var t=this.__data__;return H?t[e]!==void 0:Vr.call(t,e)}var Kr=Gr,_r="__lodash_hash_undefined__";function Ur(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=H&&t===void 0?_r:t,this}var Qr=Ur;function F(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}F.prototype.clear=Dr;F.prototype.delete=Nr;F.prototype.get=Br;F.prototype.has=Kr;F.prototype.set=Qr;var nt=F;function zr(){this.__data__=[],this.size=0}var qr=zr;function Hr(e,t){for(var r=e.length;r--;)if(Vn(e[r][0],t))return r;return-1}var re=Hr,Zr=Array.prototype,Yr=Zr.splice;function Wr(e){var t=this.__data__,r=re(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():Yr.call(t,r,1),--this.size,!0}var Xr=Wr;function Jr(e){var t=this.__data__,r=re(t,e);return r<0?void 0:t[r][1]}var ei=Jr;function ti(e){return re(this.__data__,e)>-1}var ni=ti;function ri(e,t){var r=this.__data__,n=re(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}var ii=ri;function V(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}V.prototype.clear=qr;V.prototype.delete=Xr;V.prototype.get=ei;V.prototype.has=ni;V.prototype.set=ii;var ie=V,oi=B(M,"Map"),Z=oi;function ai(){this.size=0,this.__data__={hash:new nt,map:new(Z||ie),string:new nt}}var si=ai;function li(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var ui=li;function ci(e,t){var r=e.__data__;return ui(t)?r[typeof t=="string"?"string":"hash"]:r.map}var oe=ci;function di(e){var t=oe(this,e).delete(e);return this.size-=t?1:0,t}var pi=di;function mi(e){return oe(this,e).get(e)}var fi=mi;function gi(e){return oe(this,e).has(e)}var yi=gi;function bi(e,t){var r=oe(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}var hi=bi;function G(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}G.prototype.clear=si;G.prototype.delete=pi;G.prototype.get=fi;G.prototype.has=yi;G.prototype.set=hi;var yt=G;function Ii(){this.__data__=new ie,this.size=0}var ki=Ii;function Oi(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var vi=Oi;function Ci(e){return this.__data__.get(e)}var wi=Ci;function Ai(e){return this.__data__.has(e)}var xi=Ai,Mi=200;function Ei(e,t){var r=this.__data__;if(r instanceof ie){var n=r.__data__;if(!Z||n.length<Mi-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new yt(n)}return r.set(e,t),this.size=r.size,this}var Si=Ei;function W(e){var t=this.__data__=new ie(e);this.size=t.size}W.prototype.clear=ki;W.prototype.delete=vi;W.prototype.get=wi;W.prototype.has=xi;W.prototype.set=Si;var Pi=Object.prototype,ha=Pi.propertyIsEnumerable;var Di=B(M,"DataView"),Ae=Di,Ri=B(M,"Promise"),xe=Ri,Ni=B(M,"Set"),Me=Ni,rt="[object Map]",Li="[object Object]",it="[object Promise]",ot="[object Set]",at="[object WeakMap]",st="[object DataView]",ji=P(Ae),$i=P(Z),Ti=P(xe),Bi=P(Me),Fi=P(we),j=Y;(Ae&&j(new Ae(new ArrayBuffer(1)))!=st||Z&&j(new Z)!=rt||xe&&j(xe.resolve())!=it||Me&&j(new Me)!=ot||we&&j(new we)!=at)&&(j=function(e){var t=Y(e),r=t==Li?e.constructor:void 0,n=r?P(r):"";if(n)switch(n){case ji:return st;case $i:return rt;case Ti:return it;case Bi:return ot;case Fi:return at}return t});var Ia=M.Uint8Array;var Vi="__lodash_hash_undefined__";function Gi(e){return this.__data__.set(e,Vi),this}var Ki=Gi;function _i(e){return this.__data__.has(e)}var Ui=_i;function Ee(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new yt;++t<r;)this.add(e[t])}Ee.prototype.add=Ee.prototype.push=Ki;Ee.prototype.has=Ui;var lt=T?T.prototype:void 0,ka=lt?lt.valueOf:void 0;var Qi=Object.prototype,Oa=Qi.hasOwnProperty;var zi=Object.prototype,va=zi.hasOwnProperty;var Ca=new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,"i"),wa=new RegExp(/[A-Fa-f0-9]{1}/,"g"),Aa=new RegExp(/[A-Fa-f0-9]{2}/,"g");function bt(e){return{"image/png":"png","image/jpeg":"jpg","image/webp":"webp","image/gif":"gif","image/svg+xml":"svg"}[e]??"png"}async function ht(e,t){if(e.startsWith("buffer:")){let r=await t.editor.getMimeType(e),n=t.editor.getBufferLength(e),i=t.editor.getBufferData(e,0,n),o=new Blob([i],{type:r});return URL.createObjectURL(o)}else return e}async function X(e,t){let r=await ht(e,t);return new Promise((n,i)=>{let o=new Image;o.onload=()=>{n({width:o.width,height:o.height})},o.onerror=i,o.src=r})}async function x(e,t,r){let n,i=t.block.getFill(e),o=t.block.getSourceSet(i,"fill/image/sourceSet"),[a]=o;if(a==null){if(n=t.block.getString(i,"fill/image/imageFileURI"),n==null)throw new Error("No image source/uri found")}else n=a.uri;if(r?.throwErrorIfSvg&&await t.editor.getMimeType(n)==="image/svg+xml")throw new Error("SVG images are not supported");return ht(n,t)}function qi(e){return async(r,n)=>(console.log(`[DRY RUN]: Requesting dummy AI generation for kind '${e.kind}' with inputs: `,JSON.stringify(r,void 0,2)),await Wi(2e3),await Hi(r,e,n))}async function Hi(e,t,r){switch(t.kind){case"image":return Zi(e,t,r);case"video":return Yi(e,t,r);default:throw new Error(`Unsupported output kind for creating dry run output: ${t.kind}`)}}async function Zi(e,t,{engine:r}){let n,i,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)n=parseInt(a[1],10),i=parseInt(a[2],10);else if(t.blockInputs!=null&&(n=t.blockInputs.image.width,i=t.blockInputs.image.height),t.blockIds!=null&&Array.isArray(t.blockIds)&&t.blockIds.length>0){let[l]=t.blockIds,u=await x(l,r),d=await X(u,r);n=d.width,i=d.height}else n=512,i=512;return{kind:"image",url:`https://placehold.co/${n}x${i}/000000/FFF?text=${o.replace(" ","+").replace(`
2
+ `,"+")}`}}async function Yi(e,t,r){return Promise.resolve({kind:"video",url:"https://storage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"})}async function Wi(e){return new Promise(t=>{setTimeout(t,e)})}var ae=qi;async function Xi(e,t,r,n,i,o,a){let{cesdk:s,createPlaceholderBlock:l,historyAssetSourceId:u}=i,d;try{o.debug&&console.group(`Starting Generation for '${e}'`);let c=t(),p=await r(c.input),f=Ge(),k;if(l){if(k=He(f,e,p),o.debug&&console.log("Adding as asset to scene:",JSON.stringify(k,void 0,2)),d=await Fe(s,k),d!=null&&n.kind==="video"){let g=s.engine.block.getPositionX(d),b=s.engine.block.getPositionY(d),h=s.engine.block.duplicate(d);s.engine.block.setPositionX(h,g),s.engine.block.setPositionY(h,b),s.engine.block.destroy(d),d=h}if(se(s,a,d))return{status:"aborted"};if(d==null)throw new Error("Could not create placeholder block");s.engine.block.setState(d,{type:"Pending",progress:0})}let I=U([...n.output.middleware??[],o.debug?Q():void 0,o.dryRun?ae({kind:n.kind,blockInputs:p}):void 0]),{result:y}=await I(n.output.generate)(c.input,{abortSignal:a,engine:i.engine,cesdk:s});if(S(y))throw new Error("Streaming generation is not supported yet from a panel");if(se(s,a,d))return{status:"aborted"};if(y==null)throw new Error("Generation failed");o.debug&&console.log("Generated output:",JSON.stringify(y,void 0,2));let m;if(d!=null&&s.engine.block.isValid(d)&&(m=await Oe(f,e,p,y),o.debug&&console.log("Updating asset in scene:",JSON.stringify(m,void 0,2)),await s.engine.asset.defaultApplyAssetToBlock(m,d)),se(s,a,d))return{status:"aborted"};if(u!=null){if(m==null&&(m=await Oe(f,e,p,y),se(s,a,d)))return{status:"aborted"};let g={...m,id:`${Date.now()}-${m.id}`,label:m.label!=null?{en:m.label}:{},tags:{}};s.engine.asset.addAssetToSource(u,g)}return d!=null&&s.engine.block.isValid(d)&&s.engine.block.setState(d,{type:"Ready"}),{status:"success",output:y}}catch(c){throw d!=null&&s.engine.block.isValid(d)&&(A(c)?s.engine.block.destroy(d):s.engine.block.setState(d,{type:"Error",error:"Unknown"})),c}finally{o.debug&&console.groupEnd()}}function se(e,t,r){return t.aborted?(r!=null&&e.engine.block.isValid(r)&&e.engine.block.destroy(r),!0):!1}var It=Xi;function Ji(e,t,r){let{cesdk:n,provider:i,getInput:o}=t;r.onError!=null&&typeof r.onError=="function"?r.onError(e):(console.error("Generation failed:",e),eo(n,i.output.notification,()=>({input:o?.().input,error:e}))||n.ui.showNotification({type:"error",message:Ve(e)}))}function eo(e,t,r){let n=t?.error;if(n==null||!(typeof n.show=="function"?n.show(r()):n.show))return!1;let o=typeof n.message=="function"?n.message(r()):n.message??"common.ai-generation.failed",a=n.action!=null?{label:typeof n.action.label=="function"?n.action.label(r()):n.action.label,onClick:()=>{n?.action?.onClick(r())}}:void 0;return e.ui.showNotification({type:"error",message:o,action:a}),!0}var D=Ji;function le(e){return`${e}.generating`}function kt(e){return`${e}.abort`}function to(e,t,r,n,i,o){let{builder:a,experimental:s}=e,{cesdk:l,includeHistoryLibrary:u=!0}=i,{id:d,output:{abortable:c}}=t,p=s.global(kt(d),()=>{}),f=s.global(le(d),!1),k,I=f.value&&c,y=()=>{I&&(p.value(),f.setValue(!1),p.setValue(()=>{}))},m;if(i.requiredInputs!=null&&i.requiredInputs.length>0){let b=r();m=i.requiredInputs.every(h=>!b.input[h])}let g=s.global(`${d}.confirmationDialogId`,void 0);a.Section(`${d}.generate.section`,{children:()=>{a.Button(`${d}.generate`,{label:["common.ai-generation.generate",`panel.${d}.generate`],isLoading:f.value,color:"accent",isDisabled:m,suffix:I?{icon:"@imgly/Cross",color:"danger",tooltip:[`panel.${d}.abort`,"common.cancel"],onClick:()=>{let b=l.ui.showDialog({type:"warning",content:"panel.ly.img.ai.generation.confirmCancel.content",cancel:{label:"common.close",onClick:({id:h})=>{l.ui.closeDialog(h),g.setValue(void 0)}},actions:{label:"panel.ly.img.ai.generation.confirmCancel.confirm",color:"danger",onClick:({id:h})=>{y(),l.ui.closeDialog(h),g.setValue(void 0)}}});g.setValue(b)}}:void 0,onClick:async()=>{k=new AbortController;let b=k.signal,h=async()=>{try{f.setValue(!0),p.setValue(()=>{o.debug&&console.log("Aborting generation"),k?.abort()});let O=await It(t.kind,r,n,t,i,o,b);if(O.status==="aborted")return;let C=t.output.notification;no(l,C,()=>({input:r().input,output:O.output}))}catch(O){if(A(O))return;D(O,{cesdk:l,provider:t,getInput:r},o)}finally{k=void 0,f.setValue(!1),p.setValue(()=>{}),g.value!=null&&(l.ui.closeDialog(g.value),g.setValue(void 0))}};o.middleware!=null?await o.middleware(h,{provider:t,abort:y}):await h()}}),t.output.generationHintText!=null&&a.Text(`${d}.generation-hint`,{align:"center",content:t.output.generationHintText})}}),u&&i.historyAssetLibraryEntryId!=null&&a.Library(`${d}.history.library`,{entries:[i.historyAssetLibraryEntryId]})}function no(e,t,r){let n=t?.success;if(n==null||!(typeof n.show=="function"?n.show(r()):n.show))return!1;let o=typeof n.message=="function"?n.message(r()):n.message??"common.ai-generation.success",a=n.action!=null?{label:typeof n.action.label=="function"?n.action.label(r()):n.action.label,onClick:()=>{n?.action?.onClick(r())}}:void 0;return e.ui.showNotification({type:"success",message:o,action:a,duration:n.duration}),!0}var ue=to;async function ro(e,t,r,n){let{cesdk:i}=r,{id:o}=e;n.debug&&console.log(`Registering schema-based panel input for provider ${o}`);let a=be(t.document),s=ye(a,t.inputReference);if(!Be(s,n.debug))throw new Error(`Input reference '${t.inputReference}' does not resolve to a valid OpenAPI schema`);let l=s,u=ee(l,t),d=c=>{let{builder:p}=c,f=[];p.Section(`${o}.schema.section`,{children:()=>{u.forEach(m=>{let g=qe(c,m,e,t,r,n);g!=null&&(Array.isArray(g)?f.push(...g):f.push(g))})}});let k=f.map(m=>m()),I=m=>m.type==="object"?Object.entries(m.value).reduce((g,[b,h])=>(g[b]=I(h),g),{}):m.value,y=k.reduce((m,g)=>(m[g.id]=I(g),m),{});ue(c,e,()=>({input:y}),()=>t.getBlockInput(y),{...r,requiredInputs:l.required,createPlaceholderBlock:t.userFlow==="placeholder"},n)};return i.ui.registerPanel(_(o),d),d}var Ot=ro;async function io(e,t,r,n){let{cesdk:i}=r,{id:o}=e,a=t.render,s=l=>{let{state:u}=l,d=u(le(o),{isGenerating:!1,abort:()=>{}}).value.isGenerating,{getInput:c,getBlockInput:p}=a(l,{cesdk:i,isGenerating:d});return ue(l,e,c,p,{...r,includeHistoryLibrary:t.includeHistoryLibrary??!0,createPlaceholderBlock:t.userFlow==="placeholder"},n),c};return i.ui.registerPanel(_(o),s),s}var vt=io;var Pe="@imgly/plugin-ai-generation",oo=`
3
3
  <svg>
4
4
  <symbol
5
5
  fill="none"
@@ -17,7 +17,7 @@ function Ct(e,t){let{cesdk:n}=t,r=t.propertyKey??"image_url";return wt(e,n),{[r]
17
17
  fill="none"
18
18
  xmlns="http://www.w3.org/2000/svg"
19
19
  viewBox="0 0 24 24"
20
- id="${Ce}/image"
20
+ id="${Pe}/image"
21
21
  >
22
22
  <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
23
  <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 +29,7 @@ function Ct(e,t){let{cesdk:n}=t,r=t.propertyKey??"image_url";return wt(e,n),{[r]
29
29
  fill="none"
30
30
  xmlns="http://www.w3.org/2000/svg"
31
31
  viewBox="0 0 24 24"
32
- id="${Ce}/video"
32
+ id="${Pe}/video"
33
33
  >
34
34
  <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
35
  <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 +40,7 @@ function Ct(e,t){let{cesdk:n}=t,r=t.propertyKey??"image_url";return wt(e,n),{[r]
40
40
  fill="none"
41
41
  xmlns="http://www.w3.org/2000/svg"
42
42
  viewBox="0 0 24 24"
43
- id="${Ce}/audio"
43
+ id="${Pe}/audio"
44
44
  >
45
45
  <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
46
  <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 +60,7 @@ function Ct(e,t){let{cesdk:n}=t,r=t.propertyKey??"image_url";return wt(e,n),{[r]
60
60
 
61
61
  </symbol>
62
62
  </svg>
63
- `,ft=Yi;var gt="ly.img.ai.quickAction.order",Z="ly.img.ai.quickAction.actions";function Wi(e,t){return{id:t,setQuickActionMenuOrder:r=>{e.ui.experimental.setGlobalStateValue(`${gt}.${t}`,r)},getQuickActionMenuOrder:()=>e.ui.experimental.getGlobalStateValue(`${gt}.${t}`,[]),registerQuickAction:r=>{if(!e.ui.experimental.hasGlobalStateValue(`${Z}.${t}`))e.ui.experimental.setGlobalStateValue(`${Z}.${t}`,{[r.id]:r});else{let i=e.ui.experimental.getGlobalStateValue(`${Z}.${t}`,{});e.ui.experimental.setGlobalStateValue(`${Z}.${t}`,{...i,[r.id]:r})}},getQuickAction:r=>e.ui.experimental.getGlobalStateValue(`${Z}.${t}`,{})[r]}}var we=Wi;var ne="ly.img.ai.inference.editMode",xe="ly.img.ai.inference.metadata";function ie(e){return`ly.img.ai.quickAction.${e.quickActionMenuId}.${e.quickActionId}`}function mt(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((n,r)=>(r==="ly.img.separator"&&n.length>0&&n[n.length-1]==="ly.img.separator"||n.push(r),n),[])}function Ji({alwaysOnTop:e=!0,disableClipping:t=!0}){return async(r,i,o)=>{let a={},s={},l=e||t?i.blockIds??i.engine.block.findAllSelected():[];return l.forEach(d=>{if(i.engine.block.isValid(d)&&e&&(a[d]=i.engine.block.isAlwaysOnTop(d),i.engine.block.setAlwaysOnTop(d,!0)),t){let c=i.engine.block.getParent(d);c!=null&&i.engine.block.getType(c)!=="//ly.img.ubq/scene"&&(s[c]=i.engine.block.isClipped(c),i.engine.block.setClipped(c,!1))}}),i.addDisposer(async()=>{l.forEach(d=>{if(i.engine.block.isValid(d)&&e&&i.engine.block.setAlwaysOnTop(d,a[d]),t){let c=i.engine.block.getParent(d);c!=null&&i.engine.block.getType(c)!=="//ly.img.ubq/scene"&&s[c]!=null&&i.engine.block.setClipped(c,s[c])}})}),await o(r,i)}}var yt=Ji;function Xi({pending:e=!0}){return async(n,r,i)=>{let o=e?r.blockIds??r.engine.block.findAllSelected():[];try{return o.forEach(s=>{r.engine.block.isValid(s)&&r.engine.block.setState(s,{type:"Pending",progress:0})}),await i(n,r)}finally{o.forEach(a=>{r.engine.block.isValid(a)&&r.engine.block.setState(a,{type:"Ready"})})}}}var bt=Xi;function eo({editMode:e,automaticallyUnlock:t=!1}){return async(r,i,o)=>{let a=i.blockIds??i.engine.block.findAllSelected(),s=()=>{};t||i.addDisposer(async()=>{s?.()});try{return s=to(i.engine,a,e),await o(r,i)}catch(l){throw k(l)&&s(),l}finally{t&&s()}}}function to(e,t,n){let r=e.editor.getGlobalScope("editor/select"),i=e.editor.getEditMode();s(),e.editor.setGlobalScope("editor/select","Deny"),e.editor.setEditMode(n);let o=e.editor.createHistory(),a=e.editor.getActiveHistory();e.editor.setActiveHistory(o);function s(){e.block.findAllSelected().forEach(c=>{t.includes(c)||e.block.setSelected(c,!1)}),t.forEach(c=>{e.block.setSelected(c,!0)})}let l=e.editor.onStateChanged(()=>{e.editor.getEditMode()!==n&&e.editor.setEditMode(n)}),u=e.block.onSelectionChanged(s);return()=>{r!=null&&e.editor.setGlobalScope("editor/select",r),e.editor.setEditMode(i),e.editor.setActiveHistory(a),e.editor.destroyHistory(o),u(),l()}}var ht=eo;function ro(e,t){switch(t.kind){case"text":return no(e,t);case"image":return io(e,t);case"video":return oo(e,t);case"audio":return ao(e,t);default:throw new Error(`Unsupported output kind for quick actions: ${t.kind}`)}}async function no(e,t){let{cesdk:n,blockIds:r,abortSignal:i}=t,o=r.map(c=>n.engine.block.getString(c,"text/text")),a;if(A(e)){let c="";for await(let p of e){if(i.aborted)break;typeof p=="string"?c=p:p.kind==="text"&&(c=p.text),r.forEach(v=>{n.engine.block.setString(v,"text/text",c)}),a={kind:"text",text:c}}}else a=e;if(a==null||a.kind!=="text")throw new Error("Output kind from generation is not text");let s=()=>{t.blockIds.forEach(c=>{t.cesdk.engine.block.setString(c,"text/text",a.text)})},l=()=>{t.blockIds.forEach((c,p)=>{t.cesdk.engine.block.setString(c,"text/text",o[p])})};return{consumedGenerationResult:a,applyCallbacks:{onBefore:l,onAfter:s,onCancel:l,onApply:s}}}async function io(e,t){let{cesdk:n,blockIds:r,abortSignal:i}=t;if(r.length!==1)throw new Error("Only one block is supported for image generation");let[o]=r,a=n.engine.block.getFill(o),s=n.engine.block.getSourceSet(a,"fill/image/sourceSet"),[l]=s,u;l==null&&(u=n.engine.block.getString(a,"fill/image/imageFileURI"));let d=await n.engine.editor.getMimeType(l?.uri??u);if(i.throwIfAborted(),d==="image/svg+xml")throw new Error("SVG images are not supported");let c=n.engine.block.getCropScaleX(o),p=n.engine.block.getCropScaleY(o),m=n.engine.block.getCropTranslationX(o),v=n.engine.block.getCropTranslationY(o),I=n.engine.block.getCropRotation(o),b=()=>{n.engine.block.setCropScaleX(o,c),n.engine.block.setCropScaleY(o,p),n.engine.block.setCropTranslationX(o,m),n.engine.block.setCropTranslationY(o,v),n.engine.block.setCropRotation(o,I)};if(A(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 f=e.url,g=await n.engine.editor.getMimeType(f),h=await so(n,f,g),y=l?[{uri:h,width:l.width,height:l.height}]:void 0,O=h;y==null?n.engine.block.setString(a,"fill/image/imageFileURI",O):n.engine.block.setSourceSet(a,"fill/image/sourceSet",y),b();let w=()=>{if(s==null){if(u==null)throw new Error("No image URI found");n.engine.block.setString(a,"fill/image/imageFileURI",u)}else n.engine.block.setSourceSet(a,"fill/image/sourceSet",s);b()},x=()=>{if(y==null){if(O==null)throw new Error("No image URI found");n.engine.block.setString(a,"fill/image/imageFileURI",O)}else n.engine.block.setSourceSet(a,"fill/image/sourceSet",y);b()};return{consumedGenerationResult:e,applyCallbacks:{onBefore:w,onAfter:x,onCancel:()=>{w()},onApply:()=>{x()}}}}async function oo(e,t){throw new Error("Function not implemented.")}async function ao(e,t){throw new Error("Function not implemented.")}async function so(e,t,n){let i=await(await fetch(t)).blob(),o=new File([i],`image.${lo(n)}`,{type:n}),a=await e.unstable_upload(o,()=>{}),s=a?.meta?.uri;return s??(console.warn("Failed to upload image:",a),t)}function lo(e){return{"image/png":"png","image/jpeg":"jpg","image/webp":"webp","image/gif":"gif","image/svg+xml":"svg"}[e]??"png"}var It=ro;function uo({editMode:e,automaticallyUnlock:t=!1,showNotification:n=!0}){return async(i,o,a)=>{let s=o.blockIds??o.engine.block.findAllSelected(),l=()=>{};t||o.addDisposer(async()=>{l?.()});try{l=co(o.engine,s,e);let u=await a(i,o);if(n){let d=o.engine.block.findAllSelected();s.some(p=>d.includes(p))||o.cesdk?.ui.showNotification({type:"success",message:"AI generation complete",action:{label:"Select",onClick:()=>{s.forEach(p=>{o.engine.block.select(p)})}}})}return u}catch(u){throw k(u)&&l(),u}finally{t&&l()}}}function co(e,t,n){function r(){let s=e.block.findAllSelected();return t.some(l=>s.includes(l))}let i=e.editor.onStateChanged(()=>{e.editor.getEditMode()!==n&&r()&&e.editor.setEditMode(n)}),o=e.block.onSelectionChanged(()=>{r()?e.editor.setEditMode(n):e.editor.setEditMode("Transform")});return r()&&e.editor.setEditMode(n),()=>{o(),i(),e.editor.setEditMode("Transform")}}var vt=uo;function po(e,t){let{cesdk:n,quickActionMenu:r,provider:i}=e,o=`ly.img.ai.${r.id}`,a=`${o}.confirmation`;n.setTranslations({en:{[`${a}.apply`]:"Apply",[`${a}.before`]:"Before",[`${a}.after`]:"After",[`${o}.cancel`]:"Cancel",[`${o}.processing`]:"Generating..."}});let s=`${a}.canvasnMenu`,l={unlock:()=>{},abort:()=>{},applyCallbacks:void 0},u=()=>{let c=new AbortController,p=c.signal;return l.abort=()=>{c.abort()},p};n.ui.registerComponent(s,({builder:c,engine:p,state:m})=>{let v=p.block.findAllSelected();if(v.length===0)return null;let I=new ve(n.engine,xe),b=I.get(v[0]);if(b==null)return null;let f=()=>{v.forEach(g=>{I.clear(g)})};switch(b.status){case"processing":{c.Button(`${o}.spinner`,{label:[`ly.img.ai.inference.${b.quickActionId}.processing`,`${o}.cancel`],isLoading:!0}),c.Separator(`${o}.separator`),c.Button(`${o}.cancel`,{icon:"@imgly/Cross",tooltip:`${o}.cancel`,onClick:()=>{l.abort(),f()}});break}case"confirmation":{let g=m(`${a}.comparing`,"after"),h=l.applyCallbacks?.onCancel;h!=null&&c.Button(`${a}.cancel`,{icon:"@imgly/Cross",tooltip:`${o}.cancel`,onClick:()=>{l.unlock(),h(),f()}});let y=l.applyCallbacks?.onBefore,O=l.applyCallbacks?.onAfter;y!=null&&O!=null&&c.ButtonGroup(`${a}.compare`,{children:()=>{c.Button(`${a}.compare.before`,{label:`${a}.before`,variant:"regular",isActive:g.value==="before",onClick:()=>{y(),g.setValue("before")}}),c.Button(`${a}.compare.after`,{label:`${a}.after`,variant:"regular",isActive:g.value==="after",onClick:()=>{O(),g.setValue("after")}})}});let w=l.applyCallbacks?.onApply;w!=null&&c.Button(`${a}.apply`,{icon:"@imgly/Checkmark",tooltip:`${a}.apply`,color:"accent",isDisabled:g.value!=="after",onClick:()=>{l.unlock(),f(),n.engine.editor._update(),w(),p.editor.addUndoStep()}});break}default:}});let d=`${o}.canvasMenu`;return n.ui.registerComponent(d,c=>{let p=c.engine.block.findAllSelected(),m=r.getQuickActionMenuOrder().map(g=>{if(g==="ly.img.separator")return g;let h=r.getQuickAction(g);if(h==null||!n.feature.isEnabled(ie({quickActionId:g,quickActionMenuId:r.id}),{engine:c.engine}))return null;let O=h.scopes;return O!=null&&O.length>0&&!p.every(x=>O.every(P=>c.engine.block.isAllowedByScope(x,P)))?null:h}).filter(g=>g!=null);if(m=mt(m),m.length===0||m.every(g=>g==="ly.img.separator"))return null;let{builder:v,experimental:I,state:b}=c,f=b(`${o}.toggleExpandedState`,void 0);I.builder.Popover(`${o}.popover`,{icon:"@imgly/Sparkle",variant:"plain",trailingIcon:null,children:({close:g})=>{v.Section(`${o}.popover.section`,{children:()=>{if(f.value!=null){let h=f.value,y=r.getQuickAction(h);if(y!=null&&y.renderExpanded!=null){y.renderExpanded(c,{blockIds:p,closeMenu:g,toggleExpand:()=>{f.setValue(void 0)},handleGenerationError:O=>{E(O,{cesdk:n,provider:i},t)},generate:async(O,w)=>{try{let{returnValue:x,applyCallbacks:P,dispose:Ae}=await Ot({input:O,quickAction:y,quickActionMenu:r,provider:i,cesdk:n,abortSignal:u(),blockIds:w?.blockIds??p,confirmationComponentId:s},t);return l.unlock=Ae,l.applyCallbacks=P,x}catch(x){throw k(x)||E(x,{cesdk:n,provider:i},t),x}}});return}}I.builder.Menu(`${o}.menu`,{children:()=>{m.forEach(h=>{h==="ly.img.separator"?v.Separator(`${o}.separator.${Math.random().toString()}`):h.render(c,{blockIds:p,closeMenu:g,handleGenerationError:y=>{E(y,{cesdk:n,provider:i},t)},toggleExpand:()=>{f.setValue(h.id)},generate:async(y,O)=>{try{let{returnValue:w,applyCallbacks:x,dispose:P}=await Ot({input:y,quickAction:h,quickActionMenu:r,provider:i,cesdk:n,abortSignal:u(),blockIds:O?.blockIds??p,confirmationComponentId:s},t);return l.unlock=P,l.applyCallbacks=x,w}catch(w){throw k(w)||E(w,{cesdk:n,provider:i},t),w}}})})}})}})}})}),{canvasMenuComponentId:d}}async function Ot(e,t){let{cesdk:n,input:r,blockIds:i,provider:o,quickAction:a,confirmationComponentId:s,abortSignal:l}=e;a.confirmation&&n.ui.setCanvasMenuOrder([s],{editMode:ne});let u=new ve(n.engine,xe);i.forEach(f=>{u.set(f,{status:"processing",quickActionId:a.id})});let d={cesdk:n,engine:n.engine,abortSignal:l},c=V([...o.output.middleware??[],t.debug?F():void 0,bt({}),...a.confirmation?[a.lockDuringConfirmation?ht({editMode:ne}):vt({editMode:ne}),a.confirmation&&yt({})]:[]]),{result:p,dispose:m}=await c(o.output.generate)(r,d),{consumedGenerationResult:v,applyCallbacks:I}=await It(p,{abortSignal:l,kind:o.kind,blockIds:i,cesdk:n});a.confirmation?i.forEach(f=>{u.set(f,{status:"confirmation",quickActionId:a.id})}):i.forEach(f=>{u.clear(f)});let b=()=>{m(),i.forEach(f=>{u.clear(f)})};return l.addEventListener("abort",b),{dispose:b,returnValue:v,applyCallbacks:I}}var ke=po;async function fo(e,t,n){await e.initialize(t);let r=await mo(t.engine,e.id,e.output.history??"@imgly/local");if(t.cesdk==null)return{};let i=r?`${e.id}.history.entry`:void 0,o={...t,cesdk:t.cesdk,historyAssetSourceId:r,historyAssetLibraryEntryId:i,i18n:{prompt:"common.ai-generation.prompt.placeholder"}};i!=null&&r!=null&&t.cesdk.ui.addAssetLibraryEntry({id:i,sourceIds:[r],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}`]:go(e)}});let a="@imgly/plugin-ai-generation.iconSetAdded";return t.cesdk.ui.experimental.hasGlobalStateValue(a)||(t.cesdk.ui.addIconSet("@imgly/plugin-ai-generation",ft),t.cesdk.ui.experimental.setGlobalStateValue(a,!0)),{renderBuilderFunctions:await yo(e,o,n)}}function go(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 mo(e,t,n){if(!(n==null||n===!1)){if(n==="@imgly/local"){let r=`${t}.history`;return e.asset.addLocalSource(r),r}if(n==="@imgly/indexedDB"){let r=`${t}.history`;return e.asset.addSource(new ot(r,e)),r}return n}}async function yo(e,t,n){let r={panel:void 0};return e.input?.panel!=null&&(r.panel=await bo(e,e.input.panel,t,n)),e.input?.quickActions!=null&&(n.debug&&console.log(`Initializing quick actions for provider '${e.kind}' (${e.id})`),ho(e,e.input.quickActions,t,n)),r}async function bo(e,t,n,r){switch(t.type){case"custom":return Ue(e,t,n,r);case"schema":return Ke(e,t,n,r);default:r.debug&&console.warn(`Invalid panel input type '${t.type}' - skipping`)}}async function ho(e,t,n,r){let{cesdk:i}=n,o=e.kind,a=we(i,o);t.actions.forEach(l=>{let u=l.enable??!0;i.feature.enable(ie({quickActionId:l.id,quickActionMenuId:o}),u),a.registerQuickAction(l),r.debug&&console.log(`Registered quick action: '${l.id}' (v${l.version}) to menu '${o}'`)});let{canvasMenuComponentId:s}=ke({cesdk:i,quickActionMenu:a,provider:e},r);r.debug&&console.log(`Registered quick action menu component: ${s}`)}var Io=fo;function vo(e){return async(n,r,i)=>{let o=await i(n,r);return A(o)?o:await e(o)}}var Oo=vo;var Me=new Map,oe=class{constructor(t,n,r){this.db=null;this.dbVersion=1;this.isInitializing=!1;this.initPromise=null;this.instanceId=t,this.dbName=n??"ly.img.ai.rateLimit",this.storeName=r??"rateLimits"}async initialize(){if(!this.db)return this.isInitializing?this.initPromise:(this.isInitializing=!0,this.initPromise=new Promise((t,n)=>{try{let r=indexedDB.open(this.dbName,this.dbVersion);r.onerror=i=>{this.isInitializing=!1,console.error("Failed to open IndexedDB for rate limiting:",i),n(new Error("Failed to open IndexedDB for rate limiting"))},r.onupgradeneeded=i=>{let o=i.target.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"})},r.onsuccess=i=>{this.db=i.target.result,this.isInitializing=!1,t()}}catch(r){this.isInitializing=!1,console.error("Error initializing IndexedDB:",r),n(r)}}),this.initPromise)}async getTracker(t){try{await this.initialize();let r=`${typeof this.instanceId=="symbol"?this.instanceId.description||"":this.instanceId}_${t}`;return await new Promise((i,o)=>{let l=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).get(r);l.onsuccess=()=>{l.result?i(l.result.data):i(null)},l.onerror=()=>{console.error(`Failed to get tracker for key ${r}:`,l.error),o(l.error)}})}catch(n){return console.error("Error getting tracker from IndexedDB:",n),Promise.reject(n)}}async saveTracker(t,n){try{await this.initialize();let i=`${typeof this.instanceId=="symbol"?this.instanceId.description||"":this.instanceId}_${t}`;return await new Promise((o,a)=>{let s=this.db.transaction(this.storeName,"readwrite");s.objectStore(this.storeName).put({id:i,data:n}),s.oncomplete=()=>{o()},s.onerror=()=>{console.error(`Failed to save tracker for key ${i}:`,s.error),a(s.error)}})}catch(r){return console.error("Error saving tracker to IndexedDB:",r),Promise.reject(r)}}static isAvailable(){return typeof indexedDB<"u"}close(){this.db&&(this.db.close(),this.db=null)}};function Co(e){let{maxRequests:t,timeWindowMs:n,keyFn:r=()=>"global",onRateLimitExceeded:i,dbName:o}=e,s=`rate-limit-middleware-${t}-${n}`,l=oe.isAvailable(),u=l?new oe(s,o):null;Me.has(s)||Me.set(s,{});let d=Me.get(s);return async(p,m,v)=>{if(e.disable)return v(p,m);let I=typeof r=="string"?r:r(p,m),b=Date.now(),f;if(l&&u)try{let g=await u.getTracker(I);g?f=g:f={timestamps:[],lastCleanup:b}}catch(g){console.error("IndexedDB access failed, using in-memory fallback:",g),d[I]||(d[I]={timestamps:[],lastCleanup:b}),f=d[I]}else d[I]||(d[I]={timestamps:[],lastCleanup:b}),f=d[I];if(b-f.lastCleanup>n&&(f.timestamps=f.timestamps.filter(g=>b-g<n),f.lastCleanup=b),f.timestamps.length>=t){let g=Math.min(...f.timestamps),h=Math.max(0,n-(b-g));if(i){let y={key:I,currentCount:f.timestamps.length,maxRequests:t,timeWindowMs:n,remainingTimeMs:h};if(!await i(p,m,y))throw new DOMException("Operation aborted: Rate limit exceeded","AbortError")}else throw new Error("Rate limit exceeded. Please try again later.")}if(f.timestamps.push(b),l&&u)try{await u.saveTracker(I,f)}catch(g){console.error("Failed to save tracker to IndexedDB:",g),d[I]=f}else d[I]=f;return v(p,m)}}var wo=Co;function xo(e){let{cesdk:t,panelId:n}=e;n.startsWith("ly.img.ai/")&&console.warn(`Dock components for AI generation should open a panel with an id starting with "ly.img.ai/" \u2013 "${n}" was provided.`);let r=`${n}.dock`;t.ui.registerComponent(r,({builder:i})=>{let o=t.ui.isPanelOpen(n);i.Button(`${n}.dock.button`,{label:`${n}.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(n):t.ui.openPanel(n)}})})}var ko=xo;var ps={ImageUrl:Ee};export{ps as CommonProperties,_e as abortGenerationStateKey,V as composeMiddlewares,At as getDurationForVideo,Y as getLabelFromId,G as getPanelId,we as getQuickActionMenu,ce as getThumbnailForVideo,Io as initProvider,J as isGeneratingStateKey,F as loggingMiddleware,wo as rateLimitMiddleware,ko as registerDockComponent,ke as registerQuickActionMenuComponent,Oo as uploadMiddleware};
63
+ `,Ct=oo;var wt="ly.img.ai.quickAction.order",J="ly.img.ai.quickAction.actions";function ao(e,t){return{id:t,setQuickActionMenuOrder:n=>{e.ui.experimental.setGlobalStateValue(`${wt}.${t}`,n)},getQuickActionMenuOrder:()=>e.ui.experimental.getGlobalStateValue(`${wt}.${t}`,[]),registerQuickAction:n=>{if(!e.ui.experimental.hasGlobalStateValue(`${J}.${t}`))e.ui.experimental.setGlobalStateValue(`${J}.${t}`,{[n.id]:n});else{let i=e.ui.experimental.getGlobalStateValue(`${J}.${t}`,{});e.ui.experimental.setGlobalStateValue(`${J}.${t}`,{...i,[n.id]:n})}},getQuickAction:n=>e.ui.experimental.getGlobalStateValue(`${J}.${t}`,{})[n]}}var De=ao;var ce="ly.img.ai.inference.editMode",de="ly.img.ai.inference.metadata";function pe(e){return`ly.img.ai.quickAction.${e.quickActionMenuId}.${e.quickActionId}`}function At(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((r,n)=>(n==="ly.img.separator"&&r.length>0&&r[r.length-1]==="ly.img.separator"||r.push(n),r),[])}function so({alwaysOnTop:e=!0,disableClipping:t=!0}){return async(n,i,o)=>{let a={},s={},l=e||t?i.blockIds??i.engine.block.findAllSelected():[];return l.forEach(d=>{if(i.engine.block.isValid(d)&&e&&(a[d]=i.engine.block.isAlwaysOnTop(d),i.engine.block.setAlwaysOnTop(d,!0)),t){let c=i.engine.block.getParent(d);c!=null&&i.engine.block.getType(c)!=="//ly.img.ubq/scene"&&(s[c]=i.engine.block.isClipped(c),i.engine.block.setClipped(c,!1))}}),i.addDisposer(async()=>{l.forEach(d=>{if(i.engine.block.isValid(d)&&e&&i.engine.block.setAlwaysOnTop(d,a[d]),t){let c=i.engine.block.getParent(d);c!=null&&i.engine.block.getType(c)!=="//ly.img.ubq/scene"&&s[c]!=null&&i.engine.block.setClipped(c,s[c])}})}),await o(n,i)}}var xt=so;function lo({pending:e=!0}){return async(r,n,i)=>{let o=e?n.blockIds??n.engine.block.findAllSelected():[];try{return o.forEach(s=>{n.engine.block.isValid(s)&&n.engine.block.setState(s,{type:"Pending",progress:0})}),await i(r,n)}finally{o.forEach(a=>{n.engine.block.isValid(a)&&n.engine.block.setState(a,{type:"Ready"})})}}}var Mt=lo;function uo({editMode:e,automaticallyUnlock:t=!1}){return async(n,i,o)=>{let a=i.blockIds??i.engine.block.findAllSelected(),s=()=>{};t||i.addDisposer(async()=>{s?.()});try{return s=co(i.engine,a,e),await o(n,i)}catch(l){throw A(l)&&s(),l}finally{t&&s()}}}function co(e,t,r){let n=e.editor.getGlobalScope("editor/select"),i=e.editor.getEditMode();s(),e.editor.setGlobalScope("editor/select","Deny"),e.editor.setEditMode(r);let o=e.editor.createHistory(),a=e.editor.getActiveHistory();e.editor.setActiveHistory(o);function s(){e.block.findAllSelected().forEach(c=>{t.includes(c)||e.block.setSelected(c,!1)}),t.forEach(c=>{e.block.setSelected(c,!0)})}let l=e.editor.onStateChanged(()=>{e.editor.getEditMode()!==r&&e.editor.setEditMode(r)}),u=e.block.onSelectionChanged(s);return()=>{n!=null&&e.editor.setGlobalScope("editor/select",n),e.editor.setEditMode(i),e.editor.setActiveHistory(a),e.editor.destroyHistory(o),u(),l()}}var Et=uo;function po(e,t){switch(t.kind){case"text":return mo(e,t);case"image":return fo(e,t);case"video":return go(e,t);case"audio":return yo(e,t);default:throw new Error(`Unsupported output kind for quick actions: ${t.kind}`)}}async function mo(e,t){let{cesdk:r,blockIds:n,abortSignal:i}=t,o=n.map(c=>r.engine.block.getString(c,"text/text")),a;if(S(e)){let c="";for await(let p of e){if(i.aborted)break;typeof p=="string"?c=p:p.kind==="text"&&(c=p.text),n.forEach(k=>{r.engine.block.setString(k,"text/text",c)}),a={kind:"text",text:c}}}else a=e;if(a==null||a.kind!=="text")throw new Error("Output kind from generation is not text");let s=()=>{t.blockIds.forEach(c=>{t.cesdk.engine.block.setString(c,"text/text",a.text)})},l=()=>{t.blockIds.forEach((c,p)=>{t.cesdk.engine.block.setString(c,"text/text",o[p])})};return{consumedGenerationResult:a,applyCallbacks:{onBefore:l,onAfter:s,onCancel:l,onApply:()=>{s(),t.cesdk.engine.editor.addUndoStep()}}}}async function fo(e,t){let{cesdk:r,blockIds:n,abortSignal:i}=t;if(n.length!==1)throw new Error("Only one block is supported for image generation");let[o]=n,a=r.engine.block.getFill(o),s=r.engine.block.getSourceSet(a,"fill/image/sourceSet"),[l]=s,u;l==null&&(u=r.engine.block.getString(a,"fill/image/imageFileURI"));let d=await r.engine.editor.getMimeType(l?.uri??u),c=await X(l?.uri??u,t.cesdk.engine),p=c.width/c.height;if(i.throwIfAborted(),d==="image/svg+xml")throw new Error("SVG images are not supported");let f=r.engine.block.getCropScaleX(o),k=r.engine.block.getCropScaleY(o),I=r.engine.block.getCropTranslationX(o),y=r.engine.block.getCropTranslationY(o),m=r.engine.block.getCropRotation(o),g=()=>{r.engine.block.setCropScaleX(o,f),r.engine.block.setCropScaleY(o,k),r.engine.block.setCropTranslationX(o,I),r.engine.block.setCropTranslationY(o,y),r.engine.block.setCropRotation(o,m)};if(S(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 b=e.url,h=await r.engine.editor.getMimeType(b),O=await bo(r,b,h),C=await X(O,t.cesdk.engine),w=C.width/C.height,E=Math.abs(p-w)>.001,L=l?[{uri:O,width:l.width,height:l.height}]:void 0,fe=O;L==null?r.engine.block.setString(a,"fill/image/imageFileURI",fe):r.engine.block.setSourceSet(a,"fill/image/sourceSet",L),E?r.engine.block.setContentFillMode(o,"Cover"):g();let je=()=>{if(s==null||s.length===0){if(u==null)throw new Error("No image URI found");r.engine.block.setString(a,"fill/image/imageFileURI",u)}else r.engine.block.setSourceSet(a,"fill/image/sourceSet",s);g()},$e=()=>{if(L==null){if(fe==null)throw new Error("No image URI found");r.engine.block.setString(a,"fill/image/imageFileURI",fe)}else r.engine.block.setSourceSet(a,"fill/image/sourceSet",L);E?r.engine.block.setContentFillMode(o,"Cover"):g()};return{consumedGenerationResult:e,applyCallbacks:{onBefore:je,onAfter:$e,onCancel:()=>{je()},onApply:()=>{$e(),t.cesdk.engine.editor.addUndoStep()}}}}async function go(e,t){throw new Error("Function not implemented.")}async function yo(e,t){throw new Error("Function not implemented.")}async function bo(e,t,r){let i=await(await fetch(t)).blob(),o=new File([i],`image.${bt(r)}`,{type:r}),a=await e.unstable_upload(o,()=>{}),s=a?.meta?.uri;return s??(console.warn("Failed to upload image:",a),t)}var St=po;function ho({editMode:e,automaticallyUnlock:t=!1,showNotification:r=!0}){return async(i,o,a)=>{let s=o.blockIds??o.engine.block.findAllSelected(),l=()=>{};t||o.addDisposer(async()=>{l?.()});try{l=Io(o.engine,s,e);let u=await a(i,o);if(r){let d=o.engine.block.findAllSelected();s.some(p=>d.includes(p))||o.cesdk?.ui.showNotification({type:"success",message:"AI generation complete",action:{label:"Select",onClick:()=>{s.forEach(p=>{o.engine.block.select(p)})}}})}return u}catch(u){throw A(u)&&l(),u}finally{t&&l()}}}function Io(e,t,r){function n(){let s=e.block.findAllSelected();return t.some(l=>s.includes(l))}let i=e.editor.onStateChanged(()=>{e.editor.getEditMode()!==r&&n()&&e.editor.setEditMode(r)}),o=e.block.onSelectionChanged(()=>{n()?e.editor.setEditMode(r):e.editor.setEditMode("Transform")});return n()&&e.editor.setEditMode(r),()=>{o(),i(),e.editor.setEditMode("Transform")}}var Pt=ho;async function ko(e,t){let{cesdk:r,input:n,blockIds:i,provider:o,quickAction:a,confirmationComponentId:s,abortSignal:l}=e;a.confirmation&&r.ui.setCanvasMenuOrder([s],{editMode:ce});let u=new ne(r.engine,de);i.forEach(m=>{u.set(m,{status:"processing",quickActionId:a.id})});let d={cesdk:r,engine:r.engine,abortSignal:l},c=U([...o.output.middleware??[],t.debug?Q():void 0,Mt({}),...a.confirmation?[a.lockDuringConfirmation?Et({editMode:ce}):Pt({editMode:ce}),a.confirmation&&xt({})]:[],t.dryRun?ae({kind:o.kind,blockIds:i}):void 0]),{result:p,dispose:f}=await c(o.output.generate)(n,d),{consumedGenerationResult:k,applyCallbacks:I}=await St(p,{abortSignal:l,kind:o.kind,blockIds:i,cesdk:r});a.confirmation?i.forEach(m=>{u.set(m,{status:"confirmation",quickActionId:a.id})}):(I.onApply(),i.forEach(m=>{u.clear(m)}));let y=()=>{f(),i.forEach(m=>{u.clear(m)})};return l.addEventListener("abort",y),{dispose:y,returnValue:k,applyCallbacks:I}}var Re=ko;function Oo(e,t){let{cesdk:r,quickActionMenu:n,provider:i}=e,o=`ly.img.ai.${n.id}`,a=`${o}.confirmation`;r.setTranslations({en:{[`${a}.apply`]:"Apply",[`${a}.before`]:"Before",[`${a}.after`]:"After",[`${o}.cancel`]:"Cancel",[`${o}.processing`]:"Generating..."}});let s=`${a}.canvasnMenu`,l={unlock:()=>{},abort:()=>{},applyCallbacks:void 0},u=()=>{let c=new AbortController,p=c.signal;return l.abort=()=>{c.abort()},p};r.ui.registerComponent(s,({builder:c,engine:p,state:f})=>{let k=p.block.findAllSelected();if(k.length===0)return null;let I=new ne(r.engine,de),y=I.get(k[0]);if(y==null)return null;let m=()=>{k.forEach(g=>{I.clear(g)})};switch(y.status){case"processing":{c.Button(`${o}.spinner`,{label:[`ly.img.ai.inference.${y.quickActionId}.processing`,`${o}.cancel`],isLoading:!0}),c.Separator(`${o}.separator`),c.Button(`${o}.cancel`,{icon:"@imgly/Cross",tooltip:`${o}.cancel`,onClick:()=>{l.abort(),m()}});break}case"confirmation":{let g=f(`${a}.comparing`,"after"),b=l.applyCallbacks?.onCancel;b!=null&&c.Button(`${a}.cancel`,{icon:"@imgly/Cross",tooltip:`${o}.cancel`,onClick:()=>{l.unlock(),b(),m()}});let h=l.applyCallbacks?.onBefore,O=l.applyCallbacks?.onAfter;h!=null&&O!=null&&c.ButtonGroup(`${a}.compare`,{children:()=>{c.Button(`${a}.compare.before`,{label:`${a}.before`,variant:"regular",isActive:g.value==="before",onClick:()=>{h(),g.setValue("before")}}),c.Button(`${a}.compare.after`,{label:`${a}.after`,variant:"regular",isActive:g.value==="after",onClick:()=>{O(),g.setValue("after")}})}});let C=l.applyCallbacks?.onApply;C!=null&&c.Button(`${a}.apply`,{icon:"@imgly/Checkmark",tooltip:`${a}.apply`,color:"accent",isDisabled:g.value!=="after",onClick:()=>{l.unlock(),m(),r.engine.editor._update(),C()}});break}default:}});let d=`${o}.canvasMenu`;return r.ui.registerComponent(d,c=>{let p=c.engine.block.findAllSelected(),f=n.getQuickActionMenuOrder().map(g=>{if(g==="ly.img.separator")return g;let b=n.getQuickAction(g);if(b==null||!r.feature.isEnabled(pe({quickActionId:g,quickActionMenuId:n.id}),{engine:c.engine}))return null;let O=b.scopes;return O!=null&&O.length>0&&!p.every(w=>O.every(E=>c.engine.block.isAllowedByScope(w,E)))?null:b}).filter(g=>g!=null);if(f=At(f),f.length===0||f.every(g=>g==="ly.img.separator"))return null;let{builder:k,experimental:I,state:y}=c,m=y(`${o}.toggleExpandedState`,void 0);I.builder.Popover(`${o}.popover`,{icon:"@imgly/Sparkle",variant:"plain",trailingIcon:null,children:({close:g})=>{k.Section(`${o}.popover.section`,{children:()=>{if(m.value!=null){let b=m.value,h=n.getQuickAction(b);if(h!=null&&h.renderExpanded!=null){h.renderExpanded(c,{blockIds:p,closeMenu:g,toggleExpand:()=>{m.setValue(void 0)},handleGenerationError:O=>{D(O,{cesdk:r,provider:i},t)},generate:async(O,C)=>{try{let{returnValue:w,applyCallbacks:E,dispose:L}=await Re({input:O,quickAction:h,quickActionMenu:n,provider:i,cesdk:r,abortSignal:u(),blockIds:C?.blockIds??p,confirmationComponentId:s},t);return l.unlock=L,l.applyCallbacks=E,w}catch(w){throw A(w)||D(w,{cesdk:r,provider:i},t),w}}});return}}I.builder.Menu(`${o}.menu`,{children:()=>{f.forEach(b=>{b==="ly.img.separator"?k.Separator(`${o}.separator.${Math.random().toString()}`):b.render(c,{blockIds:p,closeMenu:g,handleGenerationError:h=>{D(h,{cesdk:r,provider:i},t)},toggleExpand:()=>{m.setValue(b.id)},generate:async(h,O)=>{try{let{returnValue:C,applyCallbacks:w,dispose:E}=await Re({input:h,quickAction:b,quickActionMenu:n,provider:i,cesdk:r,abortSignal:u(),blockIds:O?.blockIds??p,confirmationComponentId:s},t);return l.unlock=E,l.applyCallbacks=w,C}catch(C){throw A(C)||D(C,{cesdk:r,provider:i},t),C}}})})}})}})}})}),{canvasMenuComponentId:d}}var Ne=Oo;async function vo(e,t,r){await e.initialize?.(t);let n=await wo(t.engine,e.id,e.output.history??"@imgly/local");if(t.cesdk==null)return{};let i=n?`${e.id}.history.entry`:void 0,o={...t,cesdk:t.cesdk,historyAssetSourceId:n,historyAssetLibraryEntryId:i,i18n:{prompt:"common.ai-generation.prompt.placeholder"}};i!=null&&n!=null&&t.cesdk.ui.addAssetLibraryEntry({id:i,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}`]:Co(e)}});let a="@imgly/plugin-ai-generation.iconSetAdded";return t.cesdk.ui.experimental.hasGlobalStateValue(a)||(t.cesdk.ui.addIconSet("@imgly/plugin-ai-generation",Ct),t.cesdk.ui.experimental.setGlobalStateValue(a,!0)),{renderBuilderFunctions:await Ao(e,o,r)}}function Co(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,r){if(!(r==null||r===!1)){if(r==="@imgly/local"){let n=`${t}.history`;return e.asset.addLocalSource(n),n}if(r==="@imgly/indexedDB"){let n=`${t}.history`;return e.asset.addSource(new ut(n,e)),n}return r}}async function Ao(e,t,r){let n={panel:void 0};return e.input?.panel!=null&&(n.panel=await xo(e,e.input.panel,t,r)),e.input?.quickActions!=null&&(r.debug&&console.log(`Initializing quick actions for provider '${e.kind}' (${e.id})`),Mo(e,e.input.quickActions,t,r)),n}async function xo(e,t,r,n){switch(t.type){case"custom":return vt(e,t,r,n);case"schema":return Ot(e,t,r,n);default:n.debug&&console.warn(`Invalid panel input type '${t.type}' - skipping`)}}async function Mo(e,t,r,n){let{cesdk:i}=r,o={};t.actions.forEach(a=>{let s=a.kind??e.kind;o[s]==null&&(o[s]=De(i,s));let l=o[s],u=a.enable??!0;i.feature.enable(pe({quickActionId:a.id,quickActionMenuId:s}),u),l.registerQuickAction(a),n.debug&&console.log(`Registered quick action: '${a.id}' (v${a.version}) to menu '${s}'`)}),Object.values(o).forEach(a=>{let{canvasMenuComponentId:s}=Ne({cesdk:i,quickActionMenu:a,provider:e},n);n.debug&&console.log(`Registered quick action menu component: ${s}`)})}var Eo=vo;function So(e){return async(r,n,i)=>{let o=await i(r,n);return S(o)?o:await e(o)}}var Po=So;var Le=new Map,me=class{constructor(t,r,n){this.db=null;this.dbVersion=1;this.isInitializing=!1;this.initPromise=null;this.instanceId=t,this.dbName=r??"ly.img.ai.rateLimit",this.storeName=n??"rateLimits"}async initialize(){if(!this.db)return this.isInitializing?this.initPromise:(this.isInitializing=!0,this.initPromise=new Promise((t,r)=>{try{let n=indexedDB.open(this.dbName,this.dbVersion);n.onerror=i=>{this.isInitializing=!1,console.error("Failed to open IndexedDB for rate limiting:",i),r(new Error("Failed to open IndexedDB for rate limiting"))},n.onupgradeneeded=i=>{let o=i.target.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"})},n.onsuccess=i=>{this.db=i.target.result,this.isInitializing=!1,t()}}catch(n){this.isInitializing=!1,console.error("Error initializing IndexedDB:",n),r(n)}}),this.initPromise)}async getTracker(t){try{await this.initialize();let n=`${typeof this.instanceId=="symbol"?this.instanceId.description||"":this.instanceId}_${t}`;return await new Promise((i,o)=>{let l=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).get(n);l.onsuccess=()=>{l.result?i(l.result.data):i(null)},l.onerror=()=>{console.error(`Failed to get tracker for key ${n}:`,l.error),o(l.error)}})}catch(r){return console.error("Error getting tracker from IndexedDB:",r),Promise.reject(r)}}async saveTracker(t,r){try{await this.initialize();let i=`${typeof this.instanceId=="symbol"?this.instanceId.description||"":this.instanceId}_${t}`;return await new Promise((o,a)=>{let s=this.db.transaction(this.storeName,"readwrite");s.objectStore(this.storeName).put({id:i,data:r}),s.oncomplete=()=>{o()},s.onerror=()=>{console.error(`Failed to save tracker for key ${i}:`,s.error),a(s.error)}})}catch(n){return console.error("Error saving tracker to IndexedDB:",n),Promise.reject(n)}}static isAvailable(){return typeof indexedDB<"u"}close(){this.db&&(this.db.close(),this.db=null)}};function Do(e){let{maxRequests:t,timeWindowMs:r,keyFn:n=()=>"global",onRateLimitExceeded:i,dbName:o}=e,s=`rate-limit-middleware-${t}-${r}`,l=me.isAvailable(),u=l?new me(s,o):null;Le.has(s)||Le.set(s,{});let d=Le.get(s);return async(p,f,k)=>{if(e.disable)return k(p,f);let I=typeof n=="string"?n:n(p,f),y=Date.now(),m;if(l&&u)try{let g=await u.getTracker(I);g?m=g:m={timestamps:[],lastCleanup:y}}catch(g){console.error("IndexedDB access failed, using in-memory fallback:",g),d[I]||(d[I]={timestamps:[],lastCleanup:y}),m=d[I]}else d[I]||(d[I]={timestamps:[],lastCleanup:y}),m=d[I];if(y-m.lastCleanup>r&&(m.timestamps=m.timestamps.filter(g=>y-g<r),m.lastCleanup=y),m.timestamps.length>=t){let g=Math.min(...m.timestamps),b=Math.max(0,r-(y-g));if(i){let h={key:I,currentCount:m.timestamps.length,maxRequests:t,timeWindowMs:r,remainingTimeMs:b};if(!await i(p,f,h))throw new DOMException("Operation aborted: Rate limit exceeded","AbortError")}else throw new Error("Rate limit exceeded. Please try again later.")}if(m.timestamps.push(y),l&&u)try{await u.saveTracker(I,m)}catch(g){console.error("Failed to save tracker to IndexedDB:",g),d[I]=m}else d[I]=m;return k(p,f)}}var Ro=Do;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 n=`${r}.dock`;t.ui.registerComponent(n,({builder:i})=>{let o=t.ui.isPanelOpen(r);i.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 Lo=No;function jo(e){let t=e.quickAction.id;return{...e.quickAction,render:({builder:r},{toggleExpand:n})=>{r.Button(`${t}.button`,{label:`ly.img.ai.quickAction.${t}`,icon:"@imgly/Sparkle",labelAlignment:"left",variant:"plain",...e.buttonOptions,onClick:n})},renderExpanded:({builder:r,state:n,experimental:i},o)=>{let a=n(`${t}.prompt`,"");r.TextArea(`${t}.textarea`,{inputLabel:`ly.img.ai.quickAction.${t}.prompt.inputLabel`,placeholder:`ly.img.ai.quickAction.${t}.prompt.placeholder`,...e.textAreaOptions,...a}),r.Separator(`${t}.separator`),i.builder.ButtonRow(`${t}.footer`,{justifyContent:"space-between",children:()=>{r.Button(`${t}.footer.cancel`,{label:"common.back",icon:"@imgly/ChevronLeft",onClick:o.toggleExpand}),r.Button(`${t}.footer.apply`,{label:`ly.img.ai.quickAction.${t}.apply`,icon:"@imgly/MagicWand",color:"accent",isDisabled:a.value.length===0,onClick:async()=>{try{let s=a.value;if(!s)return;e.onApply(s,o),o.toggleExpand(),o.closeMenu()}catch(s){o.handleGenerationError(s)}}})}})}}}var R=jo;function $o(e){let t=e.quickAction.id;return{...e.quickAction,render:({builder:r},n)=>{r.Button(`${t}.button`,{label:`ly.img.ai.quickAction.${t}`,icon:"@imgly/Sparkle",labelAlignment:"left",variant:"plain",...e.buttonOptions,onClick:async()=>{try{e.onClick(n),n.closeMenu()}catch(i){n.handleGenerationError(i)}}})}}}var To=$o;function Bo(e){let t=e.quickAction.id;if(e.mapInput==null&&e.onApply==null)throw new Error(`QuickAction '${t}': Either mapInput or onApply must be provided to QuickActionChangeImage`);if(e.mapInput!=null&&e.onApply!=null)throw new Error(`QuickAction '${t}': Only one of mapInput or onApply can be provided to QuickActionChangeImage, not both`);return{...e.quickAction,render:({builder:r,experimental:n},i)=>{n.builder.Popover(`${t}.popover`,{label:`ly.img.ai.quickAction.${t}`,icon:"@imgly/Appearance",labelAlignment:"left",variant:"plain",trailingIcon:"@imgly/ChevronRight",placement:"right",...e.buttonOptions,children:()=>{r.Section(`${t}.popover.section`,{children:()=>{n.builder.Menu(`${t}.popover.menu`,{children:()=>{e.items.forEach(o=>{r.Button(`${t}.popover.menu.${o.id}`,{label:o.label,labelAlignment:"left",variant:"plain",icon:o.icon,onClick:async()=>{let{generate:a,closeMenu:s,handleGenerationError:l}=i;try{s();let[u]=e.cesdk.engine.block.findAllSelected(),d=await x(u,e.cesdk.engine,{throwErrorIfSvg:!0});if(e.mapInput){let c=e.mapInput({item:o,uri:d,blockId:u});return await a(c)}else{if(e.onApply)return await e.onApply({item:o,uri:d,blockId:u},i);throw new Error("Please provide either mapInput or onApply")}}catch(u){l(u)}}})})}})}})}})}}}var Fo=Bo;function Vo(){return({engine:e})=>{let t=e.block.findAllSelected();if(t==null||t.length!==1)return!1;let[r]=t;if(e.block.getType(r)!=="//ly.img.ubq/graphic"&&!e.block.supportsFill(r))return!1;let n=e.block.getFill(r);return e.block.getType(n)==="//ly.img.ubq/fill/image"}}var N=Vo;function Go(e){let t=e.id??"changeImage";if(e.mapInput==null&&e.onApply==null)throw new Error(`QuickAction '${t}': Either mapInput or onApply must be provided to QuickActionChangeImage`);if(e.mapInput!=null&&e.onApply!=null)throw new Error(`QuickAction '${t}': Only one of mapInput or onApply can be provided to QuickActionChangeImage, not both`);return e.cesdk.i18n.setTranslations({en:{[`ly.img.ai.quickAction.${t}.apply`]:"Change",[`ly.img.ai.quickAction.${t}`]:"Edit Image...",[`ly.img.ai.quickAction.${t}.prompt.inputLabel`]:"Change image...",[`ly.img.ai.quickAction.${t}.prompt.placeholder`]:"Describe what you want to change..."}}),R({buttonOptions:{icon:"@imgly/plugin-ai-generation/image"},quickAction:{id:t,version:"1",confirmation:!1,scopes:["fill/change"],enable:N()},onApply:async(r,n)=>{let[i]=e.cesdk.engine.block.findAllSelected(),o=await x(i,e.cesdk.engine,{throwErrorIfSvg:!0});if(e.mapInput){let a=e.mapInput({prompt:r,uri:o,blockId:i});return n.generate(a)}else{if(e.onApply)return e.onApply({prompt:r,uri:o,blockId:i},n);throw new Error("Please provide either mapInput or onApply")}}})}var Ko=Go;function _o(e){let t=e.id??"createVariant";if(e.mapInput==null&&e.onApply==null)throw new Error(`QuickAction '${t}': Either mapInput or onApply must be provided to QuickActionChangeImage`);if(e.mapInput!=null&&e.onApply!=null)throw new Error(`QuickAction '${t}': Only one of mapInput or onApply can be provided to QuickActionChangeImage, not both`);return e.cesdk.i18n.setTranslations({en:{[`ly.img.ai.quickAction.${t}.apply`]:"Create",[`ly.img.ai.quickAction.${t}`]:"Create Variant...",[`ly.img.ai.quickAction.${t}.prompt.inputLabel`]:"Describe Your Variant...",[`ly.img.ai.quickAction.${t}.prompt.placeholder`]:"e.g., same character with arms raised"}}),R({buttonOptions:{icon:"@imgly/ImageVariation"},quickAction:{id:t,version:"1",confirmation:!1,scopes:["lifecycle/duplicate","fill/change"],enable:r=>{if(!N()(r))return!1;let[n]=r.engine.block.findAllSelected();if(!e.cesdk.feature.isEnabled("ly.img.duplicate",{engine:r.engine})||!r.engine.block.isAllowedByScope(n,"lifecycle/duplicate"))return!1;let i=r.engine.block.getParent(n);return!(i!=null&&r.engine.block.getType(i)==="//ly.img.ubq/track"&&r.engine.block.isPageDurationSource(i)||r.engine.block.getType(n)==="//ly.img.ubq/page")}},onApply:async(r,n)=>{let i=e.cesdk.engine,[o]=i.block.findAllSelected(),a=i.block.duplicate(o);i.block.setSelected(o,!1),i.block.setSelected(a,!0);let s=i.block.getParent(a);if(s==null)throw new Error("Parent not found");let l=1,u=i.block.getWidth(s),d=i.block.getHeight(s),c=.02*Math.min(u,d)*l;i.block.setPositionX(a,i.block.getPositionX(a)+c),i.block.setPositionY(a,i.block.getPositionY(a)+c);let p=await x(a,e.cesdk.engine,{throwErrorIfSvg:!0});if(e.mapInput){let f=e.mapInput({prompt:r,uri:p,duplicatedBlockId:a});return n.generate(f)}else{if(e.onApply)return e.onApply({prompt:r,uri:p,duplicatedBlockId:a},n);throw new Error("Please provide either mapInput or onApply")}}})}var Uo=_o;function Qo(e){let t=e.id??"swapBackground";if(e.mapInput==null&&e.onApply==null)throw new Error(`QuickAction '${t}': Either mapInput or onApply must be provided to QuickActionChangeImage`);if(e.mapInput!=null&&e.onApply!=null)throw new Error(`QuickAction '${t}': Only one of mapInput or onApply can be provided to QuickActionChangeImage, not both`);return e.cesdk.i18n.setTranslations({en:{[`ly.img.ai.quickAction.${t}.apply`]:"Change",[`ly.img.ai.quickAction.${t}`]:"Change Background...",[`ly.img.ai.quickAction.${t}.prompt.inputLabel`]:"Change background...",[`ly.img.ai.quickAction.${t}.prompt.placeholder`]:"Describe the background you want..."}}),R({buttonOptions:{icon:"@imgly/plugin-ai-generation/image"},quickAction:{id:t,version:"1",confirmation:!0,scopes:["fill/change"],enable:N()},onApply:async(r,n)=>{let[i]=e.cesdk.engine.block.findAllSelected(),o=await x(i,e.cesdk.engine,{throwErrorIfSvg:!0}),a=`Swap the background to ${r}`;if(e.mapInput){let s=e.mapInput({prompt:a,uri:o,blockId:i});return n.generate(s)}else{if(e.onApply)return e.onApply({prompt:a,uri:o,blockId:i},n);throw new Error("Please provide either mapInput or onApply")}}})}var zo=Qo;var ol={ImageUrl:Te};export{ol as CommonProperties,To as QuickActionBaseButton,R as QuickActionBasePrompt,Fo as QuickActionBaseSelect,Ko as QuickActionChangeImage,Uo as QuickActionImageVariant,zo as QuickActionSwapImageBackground,kt as abortGenerationStateKey,U as composeMiddlewares,N as enableQuickActionForImageFill,$t as getDurationForVideo,te as getLabelFromId,_ as getPanelId,De as getQuickActionMenu,Ie as getThumbnailForVideo,Eo as initProvider,le as isGeneratingStateKey,Q as loggingMiddleware,Ro as rateLimitMiddleware,Lo as registerDockComponent,Ne as registerQuickActionMenuComponent,Po as uploadMiddleware};
64
64
  /*! Bundled license information:
65
65
 
66
66
  @imgly/plugin-utils/dist/index.mjs: