@imgly/plugin-ai-generation-web 0.1.0-rc.0 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +1 -0
- package/README.md +49 -0
- package/dist/__tests__/middleware-upload.test.d.ts +1 -0
- package/dist/generation/middleware/rateLimitMiddleware.d.ts +16 -7
- package/dist/generation/middleware/uploadMiddleware.d.ts +13 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.mjs +6 -6
- package/dist/index.mjs.map +4 -4
- package/package.json +3 -3
package/LICENSE.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
The licensed code may be used by the customer solely in connection with an IMG.LY licensed product and for commercial purposes under the terms set forth in this agreement. Any other use of the licensed code is strictly prohibited unless otherwise agreed in writing by IMG.LY.
|
package/README.md
CHANGED
|
@@ -763,6 +763,8 @@ CreativeEditorSDK.create(domElement, {
|
|
|
763
763
|
|
|
764
764
|
The package includes a middleware system to augment the generation flow:
|
|
765
765
|
|
|
766
|
+
#### Rate Limiting Middleware
|
|
767
|
+
|
|
766
768
|
```typescript
|
|
767
769
|
// NOTE:: This middleware will not protect against calling the server directly as
|
|
768
770
|
// many times as you want. It is only meant to be used for rate-limiting the UI before it
|
|
@@ -793,6 +795,53 @@ const provider = {
|
|
|
793
795
|
};
|
|
794
796
|
```
|
|
795
797
|
|
|
798
|
+
#### Upload Middleware
|
|
799
|
+
|
|
800
|
+
The `uploadMiddleware` allows you to upload the output of a generation process to a server or cloud storage before it's returned to the user. This is useful when:
|
|
801
|
+
|
|
802
|
+
- You need to store generated content on your own servers
|
|
803
|
+
- You want to process or transform the content before it's used
|
|
804
|
+
- You need to handle licensing or attribution for the generated content
|
|
805
|
+
- You need to apply additional validation or security checks
|
|
806
|
+
|
|
807
|
+
```typescript
|
|
808
|
+
import { uploadMiddleware } from '@imgly/plugin-ai-generation-web';
|
|
809
|
+
|
|
810
|
+
// Create an upload middleware with your custom upload function
|
|
811
|
+
const upload = uploadMiddleware(async (output) => {
|
|
812
|
+
// Upload the output to your server/storage
|
|
813
|
+
const response = await fetch('https://your-api.example.com/upload', {
|
|
814
|
+
method: 'POST',
|
|
815
|
+
headers: { 'Content-Type': 'application/json' },
|
|
816
|
+
body: JSON.stringify(output)
|
|
817
|
+
});
|
|
818
|
+
|
|
819
|
+
// Get the response which should include the new URL
|
|
820
|
+
const result = await response.json();
|
|
821
|
+
|
|
822
|
+
// Return the output with the updated URL from your server
|
|
823
|
+
return {
|
|
824
|
+
...output,
|
|
825
|
+
url: result.url
|
|
826
|
+
};
|
|
827
|
+
});
|
|
828
|
+
|
|
829
|
+
// Apply middleware to your provider
|
|
830
|
+
const provider = {
|
|
831
|
+
// ...provider config
|
|
832
|
+
output: {
|
|
833
|
+
middleware: [upload]
|
|
834
|
+
// ...other output config
|
|
835
|
+
}
|
|
836
|
+
};
|
|
837
|
+
```
|
|
838
|
+
|
|
839
|
+
**Important notes about uploadMiddleware:**
|
|
840
|
+
- It automatically detects and skips async generators (streaming results)
|
|
841
|
+
- For non-streaming results, it awaits the upload function and returns the updated output
|
|
842
|
+
- The upload function should return the same type of output object (but with modified properties like URL)
|
|
843
|
+
- You can chain it with other middleware functions
|
|
844
|
+
|
|
796
845
|
## TypeScript Support
|
|
797
846
|
|
|
798
847
|
This package is fully typed with TypeScript, providing excellent IntelliSense support during development.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { GenerationOptions, Output } from '../provider';
|
|
2
2
|
import { Middleware } from './middleware';
|
|
3
|
-
export interface RateLimitOptions {
|
|
3
|
+
export interface RateLimitOptions<I> {
|
|
4
4
|
/**
|
|
5
5
|
* Maximum number of requests allowed in the time window
|
|
6
6
|
*/
|
|
@@ -10,31 +10,40 @@ export interface RateLimitOptions {
|
|
|
10
10
|
*/
|
|
11
11
|
timeWindowMs: number;
|
|
12
12
|
/**
|
|
13
|
-
* Optional key function to create different rate limits for different inputs
|
|
14
|
-
* If not provided, all requests share the same rate limit
|
|
13
|
+
* Optional key function or string to create different rate limits for different inputs
|
|
14
|
+
* - If not provided, all requests share the same 'global' rate limit
|
|
15
|
+
* - If a string is provided, that string is used as a static key
|
|
16
|
+
* - If a function is provided, it generates a key based on input and options
|
|
15
17
|
*/
|
|
16
|
-
keyFn?:
|
|
18
|
+
keyFn?: string | ((input: I, options: GenerationOptions) => string);
|
|
17
19
|
/**
|
|
18
20
|
* Callback function that is called when rate limit is exceeded
|
|
19
21
|
* Return value determines if the operation should be rejected (throw error) or allowed
|
|
20
22
|
* If true is returned, the operation will proceed despite exceeding the rate limit
|
|
21
23
|
* If false or undefined is returned, the operation will be rejected with a default error
|
|
22
24
|
*/
|
|
23
|
-
onRateLimitExceeded?:
|
|
25
|
+
onRateLimitExceeded?: (input: I, options: GenerationOptions, rateLimitInfo: {
|
|
24
26
|
key: string;
|
|
25
27
|
currentCount: number;
|
|
26
28
|
maxRequests: number;
|
|
27
29
|
timeWindowMs: number;
|
|
28
30
|
remainingTimeMs: number;
|
|
29
31
|
}) => boolean | Promise<boolean> | void;
|
|
32
|
+
/**
|
|
33
|
+
* Optional database name for the IndexedDB store
|
|
34
|
+
* If not provided, a default name will be used
|
|
35
|
+
*/
|
|
36
|
+
dbName?: string;
|
|
30
37
|
}
|
|
31
38
|
interface RequestTracker {
|
|
32
39
|
timestamps: number[];
|
|
33
40
|
lastCleanup: number;
|
|
34
41
|
}
|
|
35
|
-
export declare const
|
|
42
|
+
export declare const inMemoryStores: Map<symbol | string, Record<string, RequestTracker>>;
|
|
36
43
|
/**
|
|
37
44
|
* Middleware that implements rate limiting for AI generation requests
|
|
45
|
+
* Uses IndexedDB for storage when available, with in-memory fallback
|
|
46
|
+
* Each middleware instance has its own isolated set of rate limits
|
|
38
47
|
*/
|
|
39
|
-
declare function rateLimitMiddleware<I, O extends Output>(middlewareOptions: RateLimitOptions): Middleware<I, O>;
|
|
48
|
+
declare function rateLimitMiddleware<I, O extends Output>(middlewareOptions: RateLimitOptions<I>): Middleware<I, O>;
|
|
40
49
|
export default rateLimitMiddleware;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { Output } from '../provider';
|
|
2
|
+
import { Middleware } from './middleware';
|
|
3
|
+
/**
|
|
4
|
+
* Middleware to upload the output of a generation process.
|
|
5
|
+
*
|
|
6
|
+
* Sometimes it is not possible to use the result of a provider or
|
|
7
|
+
* not even allowed to use it directly. This middleware allows you to upload
|
|
8
|
+
* the result of a generation process to a server or a cloud storage.
|
|
9
|
+
*
|
|
10
|
+
* @param upload The function to upload the output. It should return a promise
|
|
11
|
+
*/
|
|
12
|
+
declare function uploadMiddleware<I, O extends Output>(upload: (output: O) => Promise<O>): Middleware<I, O>;
|
|
13
|
+
export default uploadMiddleware;
|
package/dist/index.d.ts
CHANGED
|
@@ -9,6 +9,7 @@ export { default as initProvider } from './generation/initProvider';
|
|
|
9
9
|
export { type GenerationMiddleware } from './generation/types';
|
|
10
10
|
export { composeMiddlewares, type Middleware } from './generation/middleware/middleware';
|
|
11
11
|
export { default as loggingMiddleware } from './generation/middleware/loggingMiddleware';
|
|
12
|
+
export { default as uploadMiddleware } from './generation/middleware/uploadMiddleware';
|
|
12
13
|
export { default as rateLimitMiddleware, type RateLimitOptions } from './generation/middleware/rateLimitMiddleware';
|
|
13
14
|
export { getPanelId, getDurationForVideo, getThumbnailForVideo, getLabelFromId } from './utils';
|
|
14
15
|
export { default as registerDockComponent } from './registerDockComponent';
|
package/dist/index.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
function vt(e,t){let{cesdk:n}=t,r=t.propertyKey??"image_url";return Ot(e,n),{[r]:(o,a)=>{let{builder:s,experimental:{global:l},payload:c}=o,d=c?.url??t.defaultUrl,u=l(`${e}.${a.id}`,d);return s.MediaPreview(a.id,{preview:{type:"image",uri:u.value},action:{label:"Select Image",onClick:()=>{n?.ui.openPanel(`${e}.imageSelection`,{payload:{onSelect:p=>{p.meta?.uri!=null&&u.setValue(p.meta?.uri)}}})}}}),()=>({id:a.id,type:"string",value:u.value})}}}function Ot(e,t){t?.ui.registerPanel(`${e}.imageSelection`,({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(`${e}.imageSelection`)):t.ui.showNotification({type:"warning",message:`Only images are supported. Found '${a}'. Please choose a different image.`})}})})}var ke=vt;function oe(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 $(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=oe(e,t.$ref),o={...$(e,r,n)};for(let a in t)Object.prototype.hasOwnProperty.call(t,a)&&a!=="$ref"&&(o[a]=$(e,t[a],n));return o}if(Array.isArray(t))return t.map(r=>$(e,r,n));if(typeof t=="object"){let r={};for(let i in t)Object.prototype.hasOwnProperty.call(t,i)&&(r[i]=$(e,t[i],n));return r}return t}function ae(e){return $(e,{...e})}function Me(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 c=r[s][l];if(typeof c!="object"||c===null)return n(`Item ${l} in ${s} must be an object, got ${c===null?"null":typeof c}`)}}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 Ct(e,t){if(e.properties==null)throw new Error("Input schema must have properties");let n=[],r=wt(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 wt(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=Ct;var xt="ly.img.ai",se="ly.img.ai/temp";async function Ae(e,t){return e.engine.asset.findAllSources().includes(se)||e.engine.asset.addLocalSource(se),e.engine.asset.apply(se,t)}function G(e){return`${xt}/${e}`}function Ee(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 Se(){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 kt(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 le(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 c=s.toDataURL(n,r);document.body.removeChild(a),i(c)}catch(c){document.body.removeChild(a),o(new Error(`Failed to create thumbnail: ${c instanceof Error?c.message:String(c)}`))}},{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 V(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 Pe(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?Mt(e,t,n,r,i,o):Re(e,t,n,r,i,o);case"boolean":return je(e,t,n,r,i,o);case"number":case"integer":return Le(e,t,n,r,i,o);case"object":return De(e,t,n,r,i,o);case"array":break;case void 0:{if(t.schema.anyOf!=null&&Array.isArray(t.schema.anyOf))return At(e,t,n,r,i,o);break}default:console.error(`Unsupported property type: ${a}`)}}function De(e,t,n,r,i,o){let s=q(t.schema??{},r).reduce((l,c)=>{let d=Pe(e,c,n,r,i,o);return d!=null&&(l[c.id]=d()),l},{});return()=>({id:t.id,type:"object",value:s})}function Re(e,t,n,r,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,c=`${n.id}.${l}`,d=t.schema.title??c,u=s(c,t.schema.default??""),p=Et(t.schema),g=p?.component!=null&&p?.component==="TextArea"?"TextArea":"TextInput";return a[g](c,{inputLabel:d,placeholder:i.i18n?.prompt,...u}),()=>({id:t.id,type:"string",value:u.value})}function Mt(e,t,n,r,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,c=`${n.id}.${l}`,d=t.schema.title??c,u=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(v=>({id:v,label:u[v]??Y(v)})),g=t.schema.default!=null?p.find(v=>v.id===t.schema.default)??p[0]:p[0],h=s(c,g);return a.Select(c,{inputLabel:d,values:p,...h}),()=>({id:t.id,type:"string",value:h.value.id})}function je(e,t,n,r,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,c=`${n.id}.${l}`,d=t.schema.title??c,u=!!t.schema.default,p=s(c,u);return a.Checkbox(c,{inputLabel:d,...p}),()=>({id:t.id,type:"boolean",value:p.value})}function Le(e,t,n,r,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,c=`${n.id}.${l}`,d=t.schema.title??c,u=t.schema.minimum,p=t.schema.maximum,g=t.schema.default;g==null&&(u!=null?g=u:p!=null?g=p:g=0);let h=s(c,g);if(u!=null&&p!=null){let v=t.schema.type==="number"?.1:1;"x-imgly-step"in t.schema&&typeof t.schema["x-imgly-step"]=="number"&&(v=t.schema["x-imgly-step"]),a.Slider(c,{inputLabel:d,min:u,max:p,step:v,...h})}else a.NumberInput(c,{inputLabel:d,min:u,max:p,...h});return()=>({id:t.id,type:"integer",value:h.value})}function At(e,t,n,r,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,c=`${n.id}.${l}`,d=t.schema.title??c,u=t.schema.anyOf??[],p=[],g={},h={};u.forEach((f,m)=>{let y=f.title??"common.custom",b=`${n.id}.${l}.anyOf[${m}]`,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]})}):(g[b]=()=>Re(e,{id:b,schema:{...f,title:y}},n,r,i,o),p.push({id:b,label:O[y]??y,icon:w[y]})):f.type==="boolean"?(g[b]=()=>je(e,{id:b,schema:{...f,title:y}},n,r,i,o),p.push({id:b,label:O[y]??y,icon:w[y]})):f.type==="integer"?(g[b]=()=>Le(e,{id:b,schema:{...f,title:y}},n,r,i,o),p.push({id:b,label:O[y]??y,icon:w[y]})):f.type==="array"||f.type==="object"&&(g[b]=()=>De(e,{id:b,schema:{...f,title:y}},n,r,i,o),p.push({id:b,label:O[y]??y,icon:w[y]}))});let v=t.schema.default!=null?p.find(f=>f.id===t.schema.default)??p[0]:p[0],I=s(c,v);if(a.Select(c,{inputLabel:d,values:p,...I}),I.value.id in g){let f=g[I.value.id]();h[I.value.id]=f}return()=>{let f=h[I.value.id];return f!=null?{...f(),id:t.id}:{id:t.id,type:"string",value:I.value.id}}}function Et(e){if("x-imgly-builder"in e)return e["x-imgly-builder"]}var Ne=Pe;var St="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIzIiBoZWlnaHQ9IjMyMyIgdmlld0JveD0iMCAwIDMyMyAzMjMiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIzMjMiIGhlaWdodD0iMzIzIiBmaWxsPSIjRTlFQkVEIi8+CjxnIG9wYWNpdHk9IjAuMyI+CjxwYXRoIGQ9Ik0xMTYgMTg0VjE5MS41QzExNiAxOTkuNzg0IDEyMi43MTYgMjA2LjUgMTMxIDIwNi41SDE5MUMxOTkuMjg0IDIwNi41IDIwNiAxOTkuNzg0IDIwNiAxOTEuNVYxMzEuNUMyMDYgMTIzLjIxNiAxOTkuMjg0IDExNi41IDE5MSAxMTYuNUwxOTAuOTk1IDEyNi41QzE5My43NTcgMTI2LjUgMTk2IDEyOC43MzkgMTk2IDEzMS41VjE5MS41QzE5NiAxOTQuMjYxIDE5My43NjEgMTk2LjUgMTkxIDE5Ni41SDEzMUMxMjguMjM5IDE5Ni41IDEyNiAxOTQuMjYxIDEyNiAxOTEuNVYxODRIMTE2WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTY2LjQ5NCAxMDUuOTI0QzE2NS44NjkgMTA0LjM0MiAxNjMuNjI5IDEwNC4zNDIgMTYzLjAwNSAxMDUuOTI0TDE1OS43NDUgMTE0LjE5MUMxNTkuNTU0IDExNC42NzQgMTU5LjE3MiAxMTUuMDU3IDE1OC42ODggMTE1LjI0N0wxNTAuNDIyIDExOC41MDhDMTQ4LjgzOSAxMTkuMTMyIDE0OC44MzkgMTIxLjM3MiAxNTAuNDIyIDEyMS45OTZMMTU4LjY4OCAxMjUuMjU2QzE1OS4xNzIgMTI1LjQ0NyAxNTkuNTU0IDEyNS44MjkgMTU5Ljc0NSAxMjYuMzEzTDE2My4wMDUgMTM0LjU3OUMxNjMuNjI5IDEzNi4xNjIgMTY1Ljg2OSAxMzYuMTYyIDE2Ni40OTQgMTM0LjU3OUwxNjkuNzU0IDEyNi4zMTNDMTY5Ljk0NCAxMjUuODI5IDE3MC4zMjcgMTI1LjQ0NyAxNzAuODEgMTI1LjI1NkwxNzkuMDc3IDEyMS45OTZDMTgwLjY2IDEyMS4zNzIgMTgwLjY2IDExOS4xMzIgMTc5LjA3NyAxMTguNTA4TDE3MC44MSAxMTUuMjQ3QzE3MC4zMjcgMTE1LjA1NyAxNjkuOTQ0IDExNC42NzQgMTY5Ljc1NCAxMTQuMTkxTDE2Ni40OTQgMTA1LjkyNFoiIGZpbGw9IiM4RjhGOEYiLz4KPHBhdGggZD0iTTEzMy4wMDUgMTI4LjQyNEMxMzMuNjI5IDEyNi44NDIgMTM1Ljg2OSAxMjYuODQyIDEzNi40OTQgMTI4LjQyNEwxNDEuODc1IDE0Mi4wN0MxNDIuMDY2IDE0Mi41NTMgMTQyLjQ0OCAxNDIuOTM1IDE0Mi45MzIgMTQzLjEyNkwxNTYuNTc3IDE0OC41MDhDMTU4LjE2IDE0OS4xMzIgMTU4LjE2IDE1MS4zNzIgMTU2LjU3NyAxNTEuOTk2TDE0Mi45MzIgMTU3LjM3OEMxNDIuNDQ4IDE1Ny41NjggMTQyLjA2NiAxNTcuOTUxIDE0MS44NzUgMTU4LjQzNEwxMzYuNDk0IDE3Mi4wNzlDMTM1Ljg2OSAxNzMuNjYyIDEzMy42MjkgMTczLjY2MiAxMzMuMDA1IDE3Mi4wNzlMMTI3LjYyMyAxNTguNDM0QzEyNy40MzMgMTU3Ljk1MSAxMjcuMDUgMTU3LjU2OCAxMjYuNTY3IDE1Ny4zNzhMMTEyLjkyMiAxNTEuOTk2QzExMS4zMzkgMTUxLjM3MiAxMTEuMzM5IDE0OS4xMzIgMTEyLjkyMiAxNDguNTA4TDEyNi41NjcgMTQzLjEyNkMxMjcuMDUgMTQyLjkzNSAxMjcuNDMzIDE0Mi41NTMgMTI3LjYyMyAxNDIuMDdMMTMzLjAwNSAxMjguNDI0WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTk1Ljk5OSAxODQuMDA0VjE5MS41MDJDMTk1Ljk5OSAxOTQuMjYzIDE5My43NjEgMTk2LjUwMiAxOTAuOTk5IDE5Ni41MDJIMTQ3LjY2OEwxNzIuODc5IDE1OC42ODRDMTc0LjM2MyAxNTYuNDU4IDE3Ny42MzUgMTU2LjQ1OCAxNzkuMTIgMTU4LjY4NEwxOTUuOTk5IDE4NC4wMDRaIiBmaWxsPSIjOEY4RjhGIi8+CjwvZz4KPC9zdmc+Cg==",ue=St;function Pt(e,t,n){switch(t){case"image":return Dt(e,n[t]);case"video":return Rt(e,n[t]);default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function Dt(e,t){let n=t.width,r=t.height;return{id:e,meta:{previewUri:ue,fillType:"//ly.img.ubq/fill/image",kind:"image",width:n,height:r}}}function Rt(e,t){let n=t.width,r=t.height;return{id:e,label:t.label,meta:{previewUri:ue,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:n,height:r}}}var Te=Pt;function jt(e,t){switch(e){case"image":return Lt(t[e]);case"video":return Nt(t[e]);default:throw new Error(`Unsupported output kind for creating dry run output: ${e}`)}}function Lt(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 Nt(e){return{kind:"video",url:"https://storage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"}}var $e=jt;async function Tt(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 $t(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 Gt(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 Vt(e,n[t],r)}default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function $t(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 Gt(e,t,n){let r=t.width,i=t.height,o=await le(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 Vt(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 ce=Tt;function B(e){let t=e.filter(n=>!!n);return n=>async(r,i)=>{let o=[],a=u=>{o.push(u)},s=async(u,p,g)=>{if(u>=t.length)return n(p,g);let h=t[u],v=async(f,m)=>s(u+1,f,m),I={...g,addDisposer:a};return h(p,I,v)},l={...i,addDisposer:a};return{result:await s(0,r,l),dispose:async()=>{for(let u=o.length-1;u>=0;u--)try{await o[u]()}catch(p){console.error("Error in disposer:",p)}o.length=0}}}}function Bt(){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 _=Bt;async function _t(e,t,n,r,i,o,a){let{cesdk:s,createPlaceholderBlock:l,historyAssetSourceId:c}=i,d;try{o.debug&&console.group(`Starting Generation for '${e}'`);let u=t(),p=await n(u.input),g=Se(),h;if(l){if(h=Te(g,e,p),o.debug&&console.log("Adding as asset to scene:",JSON.stringify(h,void 0,2)),d=await Ae(s,h),d!=null&&r.kind==="video"){let m=s.engine.block.getPositionX(d),y=s.engine.block.getPositionY(d),b=s.engine.block.duplicate(d);s.engine.block.setPositionX(b,m),s.engine.block.setPositionY(b,y),s.engine.block.destroy(d),d=b}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 v=B([...r.output.middleware??[],o.debug?_():void 0]),I;if(o.dryRun?I=await Ft(e,p):I=(await v(r.output.generate)(u.input,{abortSignal:a,engine:i.engine,cesdk:s})).result,V(I))throw new Error("Streaming generation is not supported yet from a panel");if(W(s,a,d))return{status:"aborted"};if(I==null)throw new Error("Generation failed");o.debug&&console.log("Generated output:",JSON.stringify(I,void 0,2));let f;if(d!=null&&s.engine.block.isValid(d)&&(f=await ce(g,e,p,I),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(c!=null){if(f==null&&(f=await ce(g,e,p,I),W(s,a,d)))return{status:"aborted"};let m={...f,id:`${Date.now()}-${f.id}`,label:f.label!=null?{en:f.label}:{},tags:{}};s.engine.asset.addAssetToSource(c,m)}return d!=null&&s.engine.block.isValid(d)&&s.engine.block.setState(d,{type:"Ready"}),{status:"success",output:I}}catch(u){throw d!=null&&s.engine.block.isValid(d)&&(k(u)?s.engine.block.destroy(d):s.engine.block.setState(d,{type:"Error",error:"Unknown"})),u}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 Ft(e,t){console.log("[DRY RUN]: Requesting dummy AI generation with block inputs: ",JSON.stringify(t,void 0,2));let n=$e(e,t);return await Kt(3e3),n}async function Kt(e){return new Promise(t=>{setTimeout(t,e)})}var Ge=_t;function Ut(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),zt(r,i.output.notification,()=>({input:o?.().input,error:e}))||r.ui.showNotification({type:"error",message:Ee(e)}))}function zt(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 A=Ut;function J(e){return`${e}.generating`}function Ve(e){return`${e}.abort`}function Ht(e,t,n,r,i,o){let{builder:a,experimental:s}=e,{cesdk:l,includeHistoryLibrary:c=!0}=i,{id:d,output:{abortable:u}}=t,p=s.global(Ve(d),()=>{}),g=s.global(J(d),!1),h,v=g.value&&u,I=()=>{v&&(p.value(),g.setValue(!1),p.setValue(()=>{}))},f;if(i.requiredInputs!=null&&i.requiredInputs.length>0){let y=n();f=i.requiredInputs.every(b=>!y.input[b])}let m=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:g.value,color:"accent",isDisabled:f,suffix:v?{icon:"@imgly/Cross",color:"danger",tooltip:[`panel.${d}.abort`,"common.cancel"],onClick:()=>{let y=l.ui.showDialog({type:"warning",content:"panel.ly.img.ai.generation.confirmCancel.content",cancel:{label:"common.close",onClick:({id:b})=>{l.ui.closeDialog(b),m.setValue(void 0)}},actions:{label:"panel.ly.img.ai.generation.confirmCancel.confirm",color:"danger",onClick:({id:b})=>{I(),l.ui.closeDialog(b),m.setValue(void 0)}}});m.setValue(y)}}:void 0,onClick:async()=>{h=new AbortController;let y=h.signal,b=async()=>{try{g.setValue(!0),p.setValue(()=>{o.debug&&console.log("Aborting generation"),h?.abort()});let O=await Ge(t.kind,n,r,t,i,o,y);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;A(O,{cesdk:l,provider:t,getInput:n},o)}finally{h=void 0,g.setValue(!1),p.setValue(()=>{}),m.value!=null&&(l.ui.closeDialog(m.value),m.setValue(void 0))}};o.middleware!=null?await o.middleware(b,{provider:t,abort:I}):await b()}}),t.output.generationHintText!=null&&a.Text(`${d}.generation-hint`,{align:"center",content:t.output.generationHintText})}}),c&&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=Ht;async function Zt(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=ae(t.document),s=oe(a,t.inputReference);if(!Me(s,r.debug))throw new Error(`Input reference '${t.inputReference}' does not resolve to a valid OpenAPI schema`);let l=s,c=q(l,t),d=u=>{let{builder:p}=u,g=[];p.Section(`${o}.schema.section`,{children:()=>{c.forEach(f=>{let m=Ne(u,f,e,t,n,r);m!=null&&(Array.isArray(m)?g.push(...m):g.push(m))})}});let h=g.map(f=>f()),v=f=>f.type==="object"?Object.entries(f.value).reduce((m,[y,b])=>(m[y]=v(b),m),{}):f.value,I=h.reduce((f,m)=>(f[m.id]=v(m),f),{});X(u,e,()=>({input:I}),()=>t.getBlockInput(I),{...n,requiredInputs:l.required,createPlaceholderBlock:t.userFlow==="placeholder"},r)};return i.ui.registerPanel(G(o),d),d}var Be=Zt;async function qt(e,t,n,r){let{cesdk:i}=n,{id:o}=e,a=t.render,s=l=>{let{state:c}=l,d=c(J(o),{isGenerating:!1,abort:()=>{}}).value.isGenerating,{getInput:u,getBlockInput:p}=a(l,{cesdk:i,isGenerating:d});return X(l,e,u,p,{...n,includeHistoryLibrary:t.includeHistoryLibrary??!0,createPlaceholderBlock:t.userFlow==="placeholder"},r),u};return i.ui.registerPanel(G(o),s),s}var _e=qt;var rt=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,c)=>{let d=e.locale??"en",u="",p=[];c.label!=null&&typeof c.label=="object"&&c.label[d]&&(u=c.label[d]),c.tags!=null&&typeof c.tags=="object"&&c.tags[d]&&(p=c.tags[d]);let g={...c,label:u,tags:p};return this.filterAsset(g,e)&&l.push(g),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;P(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=()=>{P(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 P(e,r=>{n.add(r)}),await Promise.all([...n].map(async r=>{let i=await this.createBlobUrlFromStore(r);t[r]=i})),P(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(c=>c.toLowerCase())??[];if(!a.every(c=>s.includes(c)||l.some(d=>d.includes(c))))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,c;return r==="id"?(l=a.id,c=s.id):(l=a.meta?.[r]??null,c=s.meta?.[r]??null),l==null?n==="Ascending"?-1:1:c==null?n==="Ascending"?1:-1:typeof l=="string"&&typeof c=="string"?n==="Ascending"?l.localeCompare(c):c.localeCompare(l):n==="Ascending"?l<c?-1:l>c?1:0:l>c?-1:l<c?1:0}):n==="Descending"&&o.reverse(),i&&o.sort((a,s)=>a.active&&!s.active?-1:!a.active&&s.active?1:0)),o}};function P(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]=P(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]=P(i,t,o)}return e}var Yt=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)}},he=Yt,Wt=typeof global=="object"&&global&&global.Object===Object&&global,nt=Wt,Jt=typeof self=="object"&&self&&self.Object===Object&&self,Xt=nt||Jt||Function("return this")(),M=Xt,er=M.Symbol,D=er,it=Object.prototype,tr=it.hasOwnProperty,rr=it.toString,F=D?D.toStringTag:void 0;function nr(e){var t=tr.call(e,F),n=e[F];try{e[F]=void 0;var r=!0}catch{}var i=rr.call(e);return r&&(t?e[F]=n:delete e[F]),i}var ir=nr,or=Object.prototype,ar=or.toString;function sr(e){return ar.call(e)}var lr=sr,ur="[object Null]",cr="[object Undefined]",Fe=D?D.toStringTag:void 0;function dr(e){return e==null?e===void 0?cr:ur:Fe&&Fe in Object(e)?ir(e):lr(e)}var H=dr;function pr(e){return e!=null&&typeof e=="object"}var Ie=pr,sa=Array.isArray;function fr(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var ot=fr,gr="[object AsyncFunction]",mr="[object Function]",yr="[object GeneratorFunction]",br="[object Proxy]";function hr(e){if(!ot(e))return!1;var t=H(e);return t==mr||t==yr||t==gr||t==br}var Ir=hr,vr=M["__core-js_shared__"],de=vr,Ke=function(){var e=/[^.]+$/.exec(de&&de.keys&&de.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function Or(e){return!!Ke&&Ke in e}var Cr=Or,wr=Function.prototype,xr=wr.toString;function kr(e){if(e!=null){try{return xr.call(e)}catch{}try{return e+""}catch{}}return""}var E=kr,Mr=/[\\^$.*+?()[\]{}|]/g,Ar=/^\[object .+?Constructor\]$/,Er=Function.prototype,Sr=Object.prototype,Pr=Er.toString,Dr=Sr.hasOwnProperty,Rr=RegExp("^"+Pr.call(Dr).replace(Mr,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function jr(e){if(!ot(e)||Cr(e))return!1;var t=Ir(e)?Rr:Ar;return t.test(E(e))}var Lr=jr;function Nr(e,t){return e?.[t]}var Tr=Nr;function $r(e,t){var n=Tr(e,t);return Lr(n)?n:void 0}var R=$r,Gr=R(M,"WeakMap"),fe=Gr;function Vr(e,t){return e===t||e!==e&&t!==t}var Br=Vr,_r=9007199254740991;function Fr(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=_r}var Kr=Fr;var la=Object.prototype;var Ur="[object Arguments]";function zr(e){return Ie(e)&&H(e)==Ur}var Ue=zr,at=Object.prototype,Hr=at.hasOwnProperty,Qr=at.propertyIsEnumerable,ua=Ue(function(){return arguments}())?Ue:function(e){return Ie(e)&&Hr.call(e,"callee")&&!Qr.call(e,"callee")};var st=typeof exports=="object"&&exports&&!exports.nodeType&&exports,ze=st&&typeof module=="object"&&module&&!module.nodeType&&module,Zr=ze&&ze.exports===st,He=Zr?M.Buffer:void 0,ca=He?He.isBuffer:void 0;var qr="[object Arguments]",Yr="[object Array]",Wr="[object Boolean]",Jr="[object Date]",Xr="[object Error]",en="[object Function]",tn="[object Map]",rn="[object Number]",nn="[object Object]",on="[object RegExp]",an="[object Set]",sn="[object String]",ln="[object WeakMap]",un="[object ArrayBuffer]",cn="[object DataView]",dn="[object Float32Array]",pn="[object Float64Array]",fn="[object Int8Array]",gn="[object Int16Array]",mn="[object Int32Array]",yn="[object Uint8Array]",bn="[object Uint8ClampedArray]",hn="[object Uint16Array]",In="[object Uint32Array]",C={};C[dn]=C[pn]=C[fn]=C[gn]=C[mn]=C[yn]=C[bn]=C[hn]=C[In]=!0;C[qr]=C[Yr]=C[un]=C[Wr]=C[cn]=C[Jr]=C[Xr]=C[en]=C[tn]=C[rn]=C[nn]=C[on]=C[an]=C[sn]=C[ln]=!1;function vn(e){return Ie(e)&&Kr(e.length)&&!!C[H(e)]}var On=vn;function Cn(e){return function(t){return e(t)}}var wn=Cn,lt=typeof exports=="object"&&exports&&!exports.nodeType&&exports,K=lt&&typeof module=="object"&&module&&!module.nodeType&&module,xn=K&&K.exports===lt,pe=xn&&nt.process,kn=function(){try{var e=K&&K.require&&K.require("util").types;return e||pe&&pe.binding&&pe.binding("util")}catch{}}(),Qe=kn,Ze=Qe&&Qe.isTypedArray,da=Ze?wn(Ze):On;var Mn=Object.prototype,pa=Mn.hasOwnProperty;function An(e,t){return function(n){return e(t(n))}}var En=An,fa=En(Object.keys,Object);var Sn=Object.prototype,ga=Sn.hasOwnProperty;var Pn=R(Object,"create"),U=Pn;function Dn(){this.__data__=U?U(null):{},this.size=0}var Rn=Dn;function jn(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var Ln=jn,Nn="__lodash_hash_undefined__",Tn=Object.prototype,$n=Tn.hasOwnProperty;function Gn(e){var t=this.__data__;if(U){var n=t[e];return n===Nn?void 0:n}return $n.call(t,e)?t[e]:void 0}var Vn=Gn,Bn=Object.prototype,_n=Bn.hasOwnProperty;function Fn(e){var t=this.__data__;return U?t[e]!==void 0:_n.call(t,e)}var Kn=Fn,Un="__lodash_hash_undefined__";function zn(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=U&&t===void 0?Un:t,this}var Hn=zn;function j(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])}}j.prototype.clear=Rn;j.prototype.delete=Ln;j.prototype.get=Vn;j.prototype.has=Kn;j.prototype.set=Hn;var qe=j;function Qn(){this.__data__=[],this.size=0}var Zn=Qn;function qn(e,t){for(var n=e.length;n--;)if(Br(e[n][0],t))return n;return-1}var ee=qn,Yn=Array.prototype,Wn=Yn.splice;function Jn(e){var t=this.__data__,n=ee(t,e);if(n<0)return!1;var r=t.length-1;return n==r?t.pop():Wn.call(t,n,1),--this.size,!0}var Xn=Jn;function ei(e){var t=this.__data__,n=ee(t,e);return n<0?void 0:t[n][1]}var ti=ei;function ri(e){return ee(this.__data__,e)>-1}var ni=ri;function ii(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 oi=ii;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=Zn;L.prototype.delete=Xn;L.prototype.get=ti;L.prototype.has=ni;L.prototype.set=oi;var te=L,ai=R(M,"Map"),z=ai;function si(){this.size=0,this.__data__={hash:new qe,map:new(z||te),string:new qe}}var li=si;function ui(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var ci=ui;function di(e,t){var n=e.__data__;return ci(t)?n[typeof t=="string"?"string":"hash"]:n.map}var re=di;function pi(e){var t=re(this,e).delete(e);return this.size-=t?1:0,t}var fi=pi;function gi(e){return re(this,e).get(e)}var mi=gi;function yi(e){return re(this,e).has(e)}var bi=yi;function hi(e,t){var n=re(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this}var Ii=hi;function N(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])}}N.prototype.clear=li;N.prototype.delete=fi;N.prototype.get=mi;N.prototype.has=bi;N.prototype.set=Ii;var ut=N;function vi(){this.__data__=new te,this.size=0}var Oi=vi;function Ci(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n}var wi=Ci;function xi(e){return this.__data__.get(e)}var ki=xi;function Mi(e){return this.__data__.has(e)}var Ai=Mi,Ei=200;function Si(e,t){var n=this.__data__;if(n instanceof te){var r=n.__data__;if(!z||r.length<Ei-1)return r.push([e,t]),this.size=++n.size,this;n=this.__data__=new ut(r)}return n.set(e,t),this.size=n.size,this}var Pi=Si;function Q(e){var t=this.__data__=new te(e);this.size=t.size}Q.prototype.clear=Oi;Q.prototype.delete=wi;Q.prototype.get=ki;Q.prototype.has=Ai;Q.prototype.set=Pi;var Di=Object.prototype,ma=Di.propertyIsEnumerable;var Ri=R(M,"DataView"),ge=Ri,ji=R(M,"Promise"),me=ji,Li=R(M,"Set"),ye=Li,Ye="[object Map]",Ni="[object Object]",We="[object Promise]",Je="[object Set]",Xe="[object WeakMap]",et="[object DataView]",Ti=E(ge),$i=E(z),Gi=E(me),Vi=E(ye),Bi=E(fe),S=H;(ge&&S(new ge(new ArrayBuffer(1)))!=et||z&&S(new z)!=Ye||me&&S(me.resolve())!=We||ye&&S(new ye)!=Je||fe&&S(new fe)!=Xe)&&(S=function(e){var t=H(e),n=t==Ni?e.constructor:void 0,r=n?E(n):"";if(r)switch(r){case Ti:return et;case $i:return Ye;case Gi:return We;case Vi:return Je;case Bi:return Xe}return t});var ya=M.Uint8Array;var _i="__lodash_hash_undefined__";function Fi(e){return this.__data__.set(e,_i),this}var Ki=Fi;function Ui(e){return this.__data__.has(e)}var zi=Ui;function be(e){var t=-1,n=e==null?0:e.length;for(this.__data__=new ut;++t<n;)this.add(e[t])}be.prototype.add=be.prototype.push=Ki;be.prototype.has=zi;var tt=D?D.prototype:void 0,ba=tt?tt.valueOf:void 0;var Hi=Object.prototype,ha=Hi.hasOwnProperty;var Qi=Object.prototype,Ia=Qi.hasOwnProperty;var va=new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,"i"),Oa=new RegExp(/[A-Fa-f0-9]{1}/,"g"),Ca=new RegExp(/[A-Fa-f0-9]{2}/,"g");var ve="@imgly/plugin-ai-generation",Zi=`
|
|
1
|
+
function Ot(e,t){let{cesdk:n}=t,r=t.propertyKey??"image_url";return Ct(e,n),{[r]:(o,a)=>{let{builder:s,experimental:{global:l},payload:c}=o,d=c?.url??t.defaultUrl,u=l(`${e}.${a.id}`,d);return s.MediaPreview(a.id,{preview:{type:"image",uri:u.value},action:{label:"Select Image",onClick:()=>{n?.ui.openPanel(`${e}.imageSelection`,{payload:{onSelect:p=>{p.meta?.uri!=null&&u.setValue(p.meta?.uri)}}})}}}),()=>({id:a.id,type:"string",value:u.value})}}}function Ct(e,t){t?.ui.registerPanel(`${e}.imageSelection`,({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(`${e}.imageSelection`)):t.ui.showNotification({type:"warning",message:`Only images are supported. Found '${a}'. Please choose a different image.`})}})})}var Me=Ot;function ae(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=ae(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 se(e){return B(e,{...e})}function Ae(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 c=r[s][l];if(typeof c!="object"||c===null)return n(`Item ${l} in ${s} must be an object, got ${c===null?"null":typeof c}`)}}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 wt(e,t){if(e.properties==null)throw new Error("Input schema must have properties");let n=[],r=xt(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 xt(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=wt;var kt="ly.img.ai",le="ly.img.ai/temp";async function Ee(e,t){return e.engine.asset.findAllSources().includes(le)||e.engine.asset.addLocalSource(le),e.engine.asset.apply(le,t)}function G(e){return`${kt}/${e}`}function Se(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 Pe(){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 Mt(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 ue(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 c=s.toDataURL(n,r);document.body.removeChild(a),i(c)}catch(c){document.body.removeChild(a),o(new Error(`Failed to create thumbnail: ${c instanceof Error?c.message:String(c)}`))}},{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 De(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?At(e,t,n,r,i,o):Ne(e,t,n,r,i,o);case"boolean":return je(e,t,n,r,i,o);case"number":case"integer":return Le(e,t,n,r,i,o);case"object":return Re(e,t,n,r,i,o);case"array":break;case void 0:{if(t.schema.anyOf!=null&&Array.isArray(t.schema.anyOf))return Et(e,t,n,r,i,o);break}default:console.error(`Unsupported property type: ${a}`)}}function Re(e,t,n,r,i,o){let s=q(t.schema??{},r).reduce((l,c)=>{let d=De(e,c,n,r,i,o);return d!=null&&(l[c.id]=d()),l},{});return()=>({id:t.id,type:"object",value:s})}function Ne(e,t,n,r,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,c=`${n.id}.${l}`,d=t.schema.title??c,u=s(c,t.schema.default??""),p=St(t.schema),g=p?.component!=null&&p?.component==="TextArea"?"TextArea":"TextInput";return a[g](c,{inputLabel:d,placeholder:i.i18n?.prompt,...u}),()=>({id:t.id,type:"string",value:u.value})}function At(e,t,n,r,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,c=`${n.id}.${l}`,d=t.schema.title??c,u=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(h=>({id:h,label:u[h]??Y(h)})),g=t.schema.default!=null?p.find(h=>h.id===t.schema.default)??p[0]:p[0],v=s(c,g);return a.Select(c,{inputLabel:d,values:p,...v}),()=>({id:t.id,type:"string",value:v.value.id})}function je(e,t,n,r,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,c=`${n.id}.${l}`,d=t.schema.title??c,u=!!t.schema.default,p=s(c,u);return a.Checkbox(c,{inputLabel:d,...p}),()=>({id:t.id,type:"boolean",value:p.value})}function Le(e,t,n,r,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,c=`${n.id}.${l}`,d=t.schema.title??c,u=t.schema.minimum,p=t.schema.maximum,g=t.schema.default;g==null&&(u!=null?g=u:p!=null?g=p:g=0);let v=s(c,g);if(u!=null&&p!=null){let h=t.schema.type==="number"?.1:1;"x-imgly-step"in t.schema&&typeof t.schema["x-imgly-step"]=="number"&&(h=t.schema["x-imgly-step"]),a.Slider(c,{inputLabel:d,min:u,max:p,step:h,...v})}else a.NumberInput(c,{inputLabel:d,min:u,max:p,...v});return()=>({id:t.id,type:"integer",value:v.value})}function Et(e,t,n,r,i,o){let{builder:a,experimental:{global:s}}=e,{id:l}=t,c=`${n.id}.${l}`,d=t.schema.title??c,u=t.schema.anyOf??[],p=[],g={},v={};u.forEach((f,m)=>{let y=f.title??"common.custom",b=`${n.id}.${l}.anyOf[${m}]`,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]})}):(g[b]=()=>Ne(e,{id:b,schema:{...f,title:y}},n,r,i,o),p.push({id:b,label:O[y]??y,icon:w[y]})):f.type==="boolean"?(g[b]=()=>je(e,{id:b,schema:{...f,title:y}},n,r,i,o),p.push({id:b,label:O[y]??y,icon:w[y]})):f.type==="integer"?(g[b]=()=>Le(e,{id:b,schema:{...f,title:y}},n,r,i,o),p.push({id:b,label:O[y]??y,icon:w[y]})):f.type==="array"||f.type==="object"&&(g[b]=()=>Re(e,{id:b,schema:{...f,title:y}},n,r,i,o),p.push({id:b,label:O[y]??y,icon:w[y]}))});let h=t.schema.default!=null?p.find(f=>f.id===t.schema.default)??p[0]:p[0],I=s(c,h);if(a.Select(c,{inputLabel:d,values:p,...I}),I.value.id in g){let f=g[I.value.id]();v[I.value.id]=f}return()=>{let f=v[I.value.id];return f!=null?{...f(),id:t.id}:{id:t.id,type:"string",value:I.value.id}}}function St(e){if("x-imgly-builder"in e)return e["x-imgly-builder"]}var Te=De;var Pt="data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzIzIiBoZWlnaHQ9IjMyMyIgdmlld0JveD0iMCAwIDMyMyAzMjMiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHdpZHRoPSIzMjMiIGhlaWdodD0iMzIzIiBmaWxsPSIjRTlFQkVEIi8+CjxnIG9wYWNpdHk9IjAuMyI+CjxwYXRoIGQ9Ik0xMTYgMTg0VjE5MS41QzExNiAxOTkuNzg0IDEyMi43MTYgMjA2LjUgMTMxIDIwNi41SDE5MUMxOTkuMjg0IDIwNi41IDIwNiAxOTkuNzg0IDIwNiAxOTEuNVYxMzEuNUMyMDYgMTIzLjIxNiAxOTkuMjg0IDExNi41IDE5MSAxMTYuNUwxOTAuOTk1IDEyNi41QzE5My43NTcgMTI2LjUgMTk2IDEyOC43MzkgMTk2IDEzMS41VjE5MS41QzE5NiAxOTQuMjYxIDE5My43NjEgMTk2LjUgMTkxIDE5Ni41SDEzMUMxMjguMjM5IDE5Ni41IDEyNiAxOTQuMjYxIDEyNiAxOTEuNVYxODRIMTE2WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTY2LjQ5NCAxMDUuOTI0QzE2NS44NjkgMTA0LjM0MiAxNjMuNjI5IDEwNC4zNDIgMTYzLjAwNSAxMDUuOTI0TDE1OS43NDUgMTE0LjE5MUMxNTkuNTU0IDExNC42NzQgMTU5LjE3MiAxMTUuMDU3IDE1OC42ODggMTE1LjI0N0wxNTAuNDIyIDExOC41MDhDMTQ4LjgzOSAxMTkuMTMyIDE0OC44MzkgMTIxLjM3MiAxNTAuNDIyIDEyMS45OTZMMTU4LjY4OCAxMjUuMjU2QzE1OS4xNzIgMTI1LjQ0NyAxNTkuNTU0IDEyNS44MjkgMTU5Ljc0NSAxMjYuMzEzTDE2My4wMDUgMTM0LjU3OUMxNjMuNjI5IDEzNi4xNjIgMTY1Ljg2OSAxMzYuMTYyIDE2Ni40OTQgMTM0LjU3OUwxNjkuNzU0IDEyNi4zMTNDMTY5Ljk0NCAxMjUuODI5IDE3MC4zMjcgMTI1LjQ0NyAxNzAuODEgMTI1LjI1NkwxNzkuMDc3IDEyMS45OTZDMTgwLjY2IDEyMS4zNzIgMTgwLjY2IDExOS4xMzIgMTc5LjA3NyAxMTguNTA4TDE3MC44MSAxMTUuMjQ3QzE3MC4zMjcgMTE1LjA1NyAxNjkuOTQ0IDExNC42NzQgMTY5Ljc1NCAxMTQuMTkxTDE2Ni40OTQgMTA1LjkyNFoiIGZpbGw9IiM4RjhGOEYiLz4KPHBhdGggZD0iTTEzMy4wMDUgMTI4LjQyNEMxMzMuNjI5IDEyNi44NDIgMTM1Ljg2OSAxMjYuODQyIDEzNi40OTQgMTI4LjQyNEwxNDEuODc1IDE0Mi4wN0MxNDIuMDY2IDE0Mi41NTMgMTQyLjQ0OCAxNDIuOTM1IDE0Mi45MzIgMTQzLjEyNkwxNTYuNTc3IDE0OC41MDhDMTU4LjE2IDE0OS4xMzIgMTU4LjE2IDE1MS4zNzIgMTU2LjU3NyAxNTEuOTk2TDE0Mi45MzIgMTU3LjM3OEMxNDIuNDQ4IDE1Ny41NjggMTQyLjA2NiAxNTcuOTUxIDE0MS44NzUgMTU4LjQzNEwxMzYuNDk0IDE3Mi4wNzlDMTM1Ljg2OSAxNzMuNjYyIDEzMy42MjkgMTczLjY2MiAxMzMuMDA1IDE3Mi4wNzlMMTI3LjYyMyAxNTguNDM0QzEyNy40MzMgMTU3Ljk1MSAxMjcuMDUgMTU3LjU2OCAxMjYuNTY3IDE1Ny4zNzhMMTEyLjkyMiAxNTEuOTk2QzExMS4zMzkgMTUxLjM3MiAxMTEuMzM5IDE0OS4xMzIgMTEyLjkyMiAxNDguNTA4TDEyNi41NjcgMTQzLjEyNkMxMjcuMDUgMTQyLjkzNSAxMjcuNDMzIDE0Mi41NTMgMTI3LjYyMyAxNDIuMDdMMTMzLjAwNSAxMjguNDI0WiIgZmlsbD0iIzhGOEY4RiIvPgo8cGF0aCBkPSJNMTk1Ljk5OSAxODQuMDA0VjE5MS41MDJDMTk1Ljk5OSAxOTQuMjYzIDE5My43NjEgMTk2LjUwMiAxOTAuOTk5IDE5Ni41MDJIMTQ3LjY2OEwxNzIuODc5IDE1OC42ODRDMTc0LjM2MyAxNTYuNDU4IDE3Ny42MzUgMTU2LjQ1OCAxNzkuMTIgMTU4LjY4NEwxOTUuOTk5IDE4NC4wMDRaIiBmaWxsPSIjOEY4RjhGIi8+CjwvZz4KPC9zdmc+Cg==",ce=Pt;function Dt(e,t,n){switch(t){case"image":return Rt(e,n[t]);case"video":return Nt(e,n[t]);default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function Rt(e,t){let n=t.width,r=t.height;return{id:e,meta:{previewUri:ce,fillType:"//ly.img.ubq/fill/image",kind:"image",width:n,height:r}}}function Nt(e,t){let n=t.width,r=t.height;return{id:e,label:t.label,meta:{previewUri:ce,mimeType:"video/mp4",kind:"video",fillType:"//ly.img.ubq/fill/video",duration:t.duration.toString(),width:n,height:r}}}var $e=Dt;function jt(e,t){switch(e){case"image":return Lt(t[e]);case"video":return Tt(t[e]);default:throw new Error(`Unsupported output kind for creating dry run output: ${e}`)}}function Lt(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 Tt(e){return{kind:"video",url:"https://storage.googleapis.com/gtv-videos-bucket/sample/ForBiggerBlazes.mp4"}}var Be=jt;async function $t(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 Bt(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 Gt(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 Vt(e,n[t],r)}default:throw new Error(`Unsupported output kind for creating placeholder block: ${t}`)}}function Bt(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 Gt(e,t,n){let r=t.width,i=t.height,o=await ue(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 Vt(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 de=$t;function V(e){let t=e.filter(n=>!!n);return n=>async(r,i)=>{let o=[],a=u=>{o.push(u)},s=async(u,p,g)=>{if(u>=t.length)return n(p,g);let v=t[u],h=async(f,m)=>s(u+1,f,m),I={...g,addDisposer:a};return v(p,I,h)},l={...i,addDisposer:a};return{result:await s(0,r,l),dispose:async()=>{for(let u=o.length-1;u>=0;u--)try{await o[u]()}catch(p){console.error("Error in disposer:",p)}o.length=0}}}}function Ft(){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=Ft;async function _t(e,t,n,r,i,o,a){let{cesdk:s,createPlaceholderBlock:l,historyAssetSourceId:c}=i,d;try{o.debug&&console.group(`Starting Generation for '${e}'`);let u=t(),p=await n(u.input),g=Pe(),v;if(l){if(v=$e(g,e,p),o.debug&&console.log("Adding as asset to scene:",JSON.stringify(v,void 0,2)),d=await Ee(s,v),d!=null&&r.kind==="video"){let m=s.engine.block.getPositionX(d),y=s.engine.block.getPositionY(d),b=s.engine.block.duplicate(d);s.engine.block.setPositionX(b,m),s.engine.block.setPositionY(b,y),s.engine.block.destroy(d),d=b}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 h=V([...r.output.middleware??[],o.debug?F():void 0]),I;if(o.dryRun?I=await Kt(e,p):I=(await h(r.output.generate)(u.input,{abortSignal:a,engine:i.engine,cesdk:s})).result,A(I))throw new Error("Streaming generation is not supported yet from a panel");if(W(s,a,d))return{status:"aborted"};if(I==null)throw new Error("Generation failed");o.debug&&console.log("Generated output:",JSON.stringify(I,void 0,2));let f;if(d!=null&&s.engine.block.isValid(d)&&(f=await de(g,e,p,I),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(c!=null){if(f==null&&(f=await de(g,e,p,I),W(s,a,d)))return{status:"aborted"};let m={...f,id:`${Date.now()}-${f.id}`,label:f.label!=null?{en:f.label}:{},tags:{}};s.engine.asset.addAssetToSource(c,m)}return d!=null&&s.engine.block.isValid(d)&&s.engine.block.setState(d,{type:"Ready"}),{status:"success",output:I}}catch(u){throw d!=null&&s.engine.block.isValid(d)&&(k(u)?s.engine.block.destroy(d):s.engine.block.setState(d,{type:"Error",error:"Unknown"})),u}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 Kt(e,t){console.log("[DRY RUN]: Requesting dummy AI generation with block inputs: ",JSON.stringify(t,void 0,2));let n=Be(e,t);return await Ut(3e3),n}async function Ut(e){return new Promise(t=>{setTimeout(t,e)})}var Ge=_t;function zt(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),Ht(r,i.output.notification,()=>({input:o?.().input,error:e}))||r.ui.showNotification({type:"error",message:Se(e)}))}function Ht(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=zt;function J(e){return`${e}.generating`}function Ve(e){return`${e}.abort`}function Qt(e,t,n,r,i,o){let{builder:a,experimental:s}=e,{cesdk:l,includeHistoryLibrary:c=!0}=i,{id:d,output:{abortable:u}}=t,p=s.global(Ve(d),()=>{}),g=s.global(J(d),!1),v,h=g.value&&u,I=()=>{h&&(p.value(),g.setValue(!1),p.setValue(()=>{}))},f;if(i.requiredInputs!=null&&i.requiredInputs.length>0){let y=n();f=i.requiredInputs.every(b=>!y.input[b])}let m=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:g.value,color:"accent",isDisabled:f,suffix:h?{icon:"@imgly/Cross",color:"danger",tooltip:[`panel.${d}.abort`,"common.cancel"],onClick:()=>{let y=l.ui.showDialog({type:"warning",content:"panel.ly.img.ai.generation.confirmCancel.content",cancel:{label:"common.close",onClick:({id:b})=>{l.ui.closeDialog(b),m.setValue(void 0)}},actions:{label:"panel.ly.img.ai.generation.confirmCancel.confirm",color:"danger",onClick:({id:b})=>{I(),l.ui.closeDialog(b),m.setValue(void 0)}}});m.setValue(y)}}:void 0,onClick:async()=>{v=new AbortController;let y=v.signal,b=async()=>{try{g.setValue(!0),p.setValue(()=>{o.debug&&console.log("Aborting generation"),v?.abort()});let O=await Ge(t.kind,n,r,t,i,o,y);if(O.status==="aborted")return;let w=t.output.notification;Zt(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,g.setValue(!1),p.setValue(()=>{}),m.value!=null&&(l.ui.closeDialog(m.value),m.setValue(void 0))}};o.middleware!=null?await o.middleware(b,{provider:t,abort:I}):await b()}}),t.output.generationHintText!=null&&a.Text(`${d}.generation-hint`,{align:"center",content:t.output.generationHintText})}}),c&&i.historyAssetLibraryEntryId!=null&&a.Library(`${d}.history.library`,{entries:[i.historyAssetLibraryEntryId]})}function Zt(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=Qt;async function qt(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=se(t.document),s=ae(a,t.inputReference);if(!Ae(s,r.debug))throw new Error(`Input reference '${t.inputReference}' does not resolve to a valid OpenAPI schema`);let l=s,c=q(l,t),d=u=>{let{builder:p}=u,g=[];p.Section(`${o}.schema.section`,{children:()=>{c.forEach(f=>{let m=Te(u,f,e,t,n,r);m!=null&&(Array.isArray(m)?g.push(...m):g.push(m))})}});let v=g.map(f=>f()),h=f=>f.type==="object"?Object.entries(f.value).reduce((m,[y,b])=>(m[y]=h(b),m),{}):f.value,I=v.reduce((f,m)=>(f[m.id]=h(m),f),{});X(u,e,()=>({input:I}),()=>t.getBlockInput(I),{...n,requiredInputs:l.required,createPlaceholderBlock:t.userFlow==="placeholder"},r)};return i.ui.registerPanel(G(o),d),d}var Fe=qt;async function Yt(e,t,n,r){let{cesdk:i}=n,{id:o}=e,a=t.render,s=l=>{let{state:c}=l,d=c(J(o),{isGenerating:!1,abort:()=>{}}).value.isGenerating,{getInput:u,getBlockInput:p}=a(l,{cesdk:i,isGenerating:d});return X(l,e,u,p,{...n,includeHistoryLibrary:t.includeHistoryLibrary??!0,createPlaceholderBlock:t.userFlow==="placeholder"},r),u};return i.ui.registerPanel(G(o),s),s}var _e=Yt;var nt=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,c)=>{let d=e.locale??"en",u="",p=[];c.label!=null&&typeof c.label=="object"&&c.label[d]&&(u=c.label[d]),c.tags!=null&&typeof c.tags=="object"&&c.tags[d]&&(p=c.tags[d]);let g={...c,label:u,tags:p};return this.filterAsset(g,e)&&l.push(g),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;D(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=()=>{D(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 D(e,r=>{n.add(r)}),await Promise.all([...n].map(async r=>{let i=await this.createBlobUrlFromStore(r);t[r]=i})),D(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(c=>c.toLowerCase())??[];if(!a.every(c=>s.includes(c)||l.some(d=>d.includes(c))))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,c;return r==="id"?(l=a.id,c=s.id):(l=a.meta?.[r]??null,c=s.meta?.[r]??null),l==null?n==="Ascending"?-1:1:c==null?n==="Ascending"?1:-1:typeof l=="string"&&typeof c=="string"?n==="Ascending"?l.localeCompare(c):c.localeCompare(l):n==="Ascending"?l<c?-1:l>c?1:0:l>c?-1:l<c?1:0}):n==="Descending"&&o.reverse(),i&&o.sort((a,s)=>a.active&&!s.active?-1:!a.active&&s.active?1:0)),o}};function D(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]=D(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]=D(i,t,o)}return e}var Wt=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)}},Ie=Wt,Jt=typeof global=="object"&&global&&global.Object===Object&&global,it=Jt,Xt=typeof self=="object"&&self&&self.Object===Object&&self,er=it||Xt||Function("return this")(),M=er,tr=M.Symbol,R=tr,ot=Object.prototype,rr=ot.hasOwnProperty,nr=ot.toString,_=R?R.toStringTag:void 0;function ir(e){var t=rr.call(e,_),n=e[_];try{e[_]=void 0;var r=!0}catch{}var i=nr.call(e);return r&&(t?e[_]=n:delete e[_]),i}var or=ir,ar=Object.prototype,sr=ar.toString;function lr(e){return sr.call(e)}var ur=lr,cr="[object Null]",dr="[object Undefined]",Ke=R?R.toStringTag:void 0;function pr(e){return e==null?e===void 0?dr:cr:Ke&&Ke in Object(e)?or(e):ur(e)}var H=pr;function fr(e){return e!=null&&typeof e=="object"}var ve=fr,ca=Array.isArray;function mr(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var at=mr,gr="[object AsyncFunction]",yr="[object Function]",br="[object GeneratorFunction]",hr="[object Proxy]";function Ir(e){if(!at(e))return!1;var t=H(e);return t==yr||t==br||t==gr||t==hr}var vr=Ir,Or=M["__core-js_shared__"],pe=Or,Ue=function(){var e=/[^.]+$/.exec(pe&&pe.keys&&pe.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();function Cr(e){return!!Ue&&Ue in e}var wr=Cr,xr=Function.prototype,kr=xr.toString;function Mr(e){if(e!=null){try{return kr.call(e)}catch{}try{return e+""}catch{}}return""}var S=Mr,Ar=/[\\^$.*+?()[\]{}|]/g,Er=/^\[object .+?Constructor\]$/,Sr=Function.prototype,Pr=Object.prototype,Dr=Sr.toString,Rr=Pr.hasOwnProperty,Nr=RegExp("^"+Dr.call(Rr).replace(Ar,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function jr(e){if(!at(e)||wr(e))return!1;var t=vr(e)?Nr:Er;return t.test(S(e))}var Lr=jr;function Tr(e,t){return e?.[t]}var $r=Tr;function Br(e,t){var n=$r(e,t);return Lr(n)?n:void 0}var N=Br,Gr=N(M,"WeakMap"),me=Gr;function Vr(e,t){return e===t||e!==e&&t!==t}var Fr=Vr,_r=9007199254740991;function Kr(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=_r}var Ur=Kr;var da=Object.prototype;var zr="[object Arguments]";function Hr(e){return ve(e)&&H(e)==zr}var ze=Hr,st=Object.prototype,Qr=st.hasOwnProperty,Zr=st.propertyIsEnumerable,pa=ze(function(){return arguments}())?ze:function(e){return ve(e)&&Qr.call(e,"callee")&&!Zr.call(e,"callee")};var lt=typeof exports=="object"&&exports&&!exports.nodeType&&exports,He=lt&&typeof module=="object"&&module&&!module.nodeType&&module,qr=He&&He.exports===lt,Qe=qr?M.Buffer:void 0,fa=Qe?Qe.isBuffer:void 0;var Yr="[object Arguments]",Wr="[object Array]",Jr="[object Boolean]",Xr="[object Date]",en="[object Error]",tn="[object Function]",rn="[object Map]",nn="[object Number]",on="[object Object]",an="[object RegExp]",sn="[object Set]",ln="[object String]",un="[object WeakMap]",cn="[object ArrayBuffer]",dn="[object DataView]",pn="[object Float32Array]",fn="[object Float64Array]",mn="[object Int8Array]",gn="[object Int16Array]",yn="[object Int32Array]",bn="[object Uint8Array]",hn="[object Uint8ClampedArray]",In="[object Uint16Array]",vn="[object Uint32Array]",C={};C[pn]=C[fn]=C[mn]=C[gn]=C[yn]=C[bn]=C[hn]=C[In]=C[vn]=!0;C[Yr]=C[Wr]=C[cn]=C[Jr]=C[dn]=C[Xr]=C[en]=C[tn]=C[rn]=C[nn]=C[on]=C[an]=C[sn]=C[ln]=C[un]=!1;function On(e){return ve(e)&&Ur(e.length)&&!!C[H(e)]}var Cn=On;function wn(e){return function(t){return e(t)}}var xn=wn,ut=typeof exports=="object"&&exports&&!exports.nodeType&&exports,K=ut&&typeof module=="object"&&module&&!module.nodeType&&module,kn=K&&K.exports===ut,fe=kn&&it.process,Mn=function(){try{var e=K&&K.require&&K.require("util").types;return e||fe&&fe.binding&&fe.binding("util")}catch{}}(),Ze=Mn,qe=Ze&&Ze.isTypedArray,ma=qe?xn(qe):Cn;var An=Object.prototype,ga=An.hasOwnProperty;function En(e,t){return function(n){return e(t(n))}}var Sn=En,ya=Sn(Object.keys,Object);var Pn=Object.prototype,ba=Pn.hasOwnProperty;var Dn=N(Object,"create"),U=Dn;function Rn(){this.__data__=U?U(null):{},this.size=0}var Nn=Rn;function jn(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var Ln=jn,Tn="__lodash_hash_undefined__",$n=Object.prototype,Bn=$n.hasOwnProperty;function Gn(e){var t=this.__data__;if(U){var n=t[e];return n===Tn?void 0:n}return Bn.call(t,e)?t[e]:void 0}var Vn=Gn,Fn=Object.prototype,_n=Fn.hasOwnProperty;function Kn(e){var t=this.__data__;return U?t[e]!==void 0:_n.call(t,e)}var Un=Kn,zn="__lodash_hash_undefined__";function Hn(e,t){var n=this.__data__;return this.size+=this.has(e)?0:1,n[e]=U&&t===void 0?zn:t,this}var Qn=Hn;function j(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])}}j.prototype.clear=Nn;j.prototype.delete=Ln;j.prototype.get=Vn;j.prototype.has=Un;j.prototype.set=Qn;var Ye=j;function Zn(){this.__data__=[],this.size=0}var qn=Zn;function Yn(e,t){for(var n=e.length;n--;)if(Fr(e[n][0],t))return n;return-1}var ee=Yn,Wn=Array.prototype,Jn=Wn.splice;function Xn(e){var t=this.__data__,n=ee(t,e);if(n<0)return!1;var r=t.length-1;return n==r?t.pop():Jn.call(t,n,1),--this.size,!0}var ei=Xn;function ti(e){var t=this.__data__,n=ee(t,e);return n<0?void 0:t[n][1]}var ri=ti;function ni(e){return ee(this.__data__,e)>-1}var ii=ni;function oi(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 ai=oi;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=qn;L.prototype.delete=ei;L.prototype.get=ri;L.prototype.has=ii;L.prototype.set=ai;var te=L,si=N(M,"Map"),z=si;function li(){this.size=0,this.__data__={hash:new Ye,map:new(z||te),string:new Ye}}var ui=li;function ci(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var di=ci;function pi(e,t){var n=e.__data__;return di(t)?n[typeof t=="string"?"string":"hash"]:n.map}var re=pi;function fi(e){var t=re(this,e).delete(e);return this.size-=t?1:0,t}var mi=fi;function gi(e){return re(this,e).get(e)}var yi=gi;function bi(e){return re(this,e).has(e)}var hi=bi;function Ii(e,t){var n=re(this,e),r=n.size;return n.set(e,t),this.size+=n.size==r?0:1,this}var vi=Ii;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=ui;T.prototype.delete=mi;T.prototype.get=yi;T.prototype.has=hi;T.prototype.set=vi;var ct=T;function Oi(){this.__data__=new te,this.size=0}var Ci=Oi;function wi(e){var t=this.__data__,n=t.delete(e);return this.size=t.size,n}var xi=wi;function ki(e){return this.__data__.get(e)}var Mi=ki;function Ai(e){return this.__data__.has(e)}var Ei=Ai,Si=200;function Pi(e,t){var n=this.__data__;if(n instanceof te){var r=n.__data__;if(!z||r.length<Si-1)return r.push([e,t]),this.size=++n.size,this;n=this.__data__=new ct(r)}return n.set(e,t),this.size=n.size,this}var Di=Pi;function Q(e){var t=this.__data__=new te(e);this.size=t.size}Q.prototype.clear=Ci;Q.prototype.delete=xi;Q.prototype.get=Mi;Q.prototype.has=Ei;Q.prototype.set=Di;var Ri=Object.prototype,ha=Ri.propertyIsEnumerable;var Ni=N(M,"DataView"),ge=Ni,ji=N(M,"Promise"),ye=ji,Li=N(M,"Set"),be=Li,We="[object Map]",Ti="[object Object]",Je="[object Promise]",Xe="[object Set]",et="[object WeakMap]",tt="[object DataView]",$i=S(ge),Bi=S(z),Gi=S(ye),Vi=S(be),Fi=S(me),P=H;(ge&&P(new ge(new ArrayBuffer(1)))!=tt||z&&P(new z)!=We||ye&&P(ye.resolve())!=Je||be&&P(new be)!=Xe||me&&P(new me)!=et)&&(P=function(e){var t=H(e),n=t==Ti?e.constructor:void 0,r=n?S(n):"";if(r)switch(r){case $i:return tt;case Bi:return We;case Gi:return Je;case Vi:return Xe;case Fi:return et}return t});var Ia=M.Uint8Array;var _i="__lodash_hash_undefined__";function Ki(e){return this.__data__.set(e,_i),this}var Ui=Ki;function zi(e){return this.__data__.has(e)}var Hi=zi;function he(e){var t=-1,n=e==null?0:e.length;for(this.__data__=new ct;++t<n;)this.add(e[t])}he.prototype.add=he.prototype.push=Ui;he.prototype.has=Hi;var rt=R?R.prototype:void 0,va=rt?rt.valueOf:void 0;var Qi=Object.prototype,Oa=Qi.hasOwnProperty;var Zi=Object.prototype,Ca=Zi.hasOwnProperty;var wa=new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,"i"),xa=new RegExp(/[A-Fa-f0-9]{1}/,"g"),ka=new RegExp(/[A-Fa-f0-9]{2}/,"g");var Oe="@imgly/plugin-ai-generation",qi=`
|
|
3
3
|
<svg>
|
|
4
4
|
<symbol
|
|
5
5
|
fill="none"
|
|
@@ -17,7 +17,7 @@ function vt(e,t){let{cesdk:n}=t,r=t.propertyKey??"image_url";return Ot(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="${
|
|
20
|
+
id="${Oe}/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 vt(e,t){let{cesdk:n}=t,r=t.propertyKey??"image_url";return Ot(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="${
|
|
32
|
+
id="${Oe}/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 vt(e,t){let{cesdk:n}=t,r=t.propertyKey??"image_url";return Ot(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="${
|
|
43
|
+
id="${Oe}/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 vt(e,t){let{cesdk:n}=t,r=t.propertyKey??"image_url";return Ot(e,n),{[r]
|
|
|
60
60
|
|
|
61
61
|
</symbol>
|
|
62
62
|
</svg>
|
|
63
|
-
`,ct=Zi;var dt="ly.img.ai.quickAction.order",Z="ly.img.ai.quickAction.actions";function qi(e,t){return{id:t,setQuickActionMenuOrder:r=>{e.ui.experimental.setGlobalStateValue(`${dt}.${t}`,r)},getQuickActionMenuOrder:()=>e.ui.experimental.getGlobalStateValue(`${dt}.${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 Oe=qi;var ne="ly.img.ai.inference.editMode",Ce="ly.img.ai.inference.metadata";function ie(e){return`ly.img.ai.quickAction.${e.quickActionMenuId}.${e.quickActionId}`}function pt(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 Yi({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 u=i.engine.block.getParent(d);u!=null&&i.engine.block.getType(u)!=="//ly.img.ubq/scene"&&(s[u]=i.engine.block.isClipped(u),i.engine.block.setClipped(u,!1))}}),i.addDisposer(async()=>{l.forEach(d=>{if(i.engine.block.isValid(d)&&e&&i.engine.block.setAlwaysOnTop(d,a[d]),t){let u=i.engine.block.getParent(d);u!=null&&i.engine.block.getType(u)!=="//ly.img.ubq/scene"&&s[u]!=null&&i.engine.block.setClipped(u,s[u])}})}),await o(r,i)}}var ft=Yi;function Wi({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 gt=Wi;function Ji({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=Xi(i.engine,a,e),await o(r,i)}catch(l){throw k(l)&&s(),l}finally{t&&s()}}}function Xi(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(u=>{t.includes(u)||e.block.setSelected(u,!1)}),t.forEach(u=>{e.block.setSelected(u,!0)})}let l=e.editor.onStateChanged(()=>{e.editor.getEditMode()!==n&&e.editor.setEditMode(n)}),c=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),c(),l()}}var mt=Ji;function eo(e,t){switch(t.kind){case"text":return to(e,t);case"image":return ro(e,t);case"video":return no(e,t);case"audio":return io(e,t);default:throw new Error(`Unsupported output kind for quick actions: ${t.kind}`)}}async function to(e,t){let{cesdk:n,blockIds:r,abortSignal:i}=t,o=r.map(u=>n.engine.block.getString(u,"text/text")),a;if(V(e)){let u="";for await(let p of e){if(i.aborted)break;typeof p=="string"?u=p:p.kind==="text"&&(u=p.text),r.forEach(h=>{n.engine.block.setString(h,"text/text",u)}),a={kind:"text",text:u}}}else a=e;if(a==null||a.kind!=="text")throw new Error("Output kind from generation is not text");let s=()=>{t.blockIds.forEach(u=>{t.cesdk.engine.block.setString(u,"text/text",a.text)})},l=()=>{t.blockIds.forEach((u,p)=>{t.cesdk.engine.block.setString(u,"text/text",o[p])})};return{consumedGenerationResult:a,applyCallbacks:{onBefore:l,onAfter:s,onCancel:l,onApply:s}}}async function ro(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,c=await n.engine.editor.getMimeType(l.uri);if(i.throwIfAborted(),c==="image/svg+xml")throw new Error("SVG images are not supported");let d=n.engine.block.getCropScaleX(o),u=n.engine.block.getCropScaleY(o),p=n.engine.block.getCropTranslationX(o),g=n.engine.block.getCropTranslationY(o),h=n.engine.block.getCropRotation(o),v=()=>{n.engine.block.setCropScaleX(o,d),n.engine.block.setCropScaleY(o,u),n.engine.block.setCropTranslationX(o,p),n.engine.block.setCropTranslationY(o,g),n.engine.block.setCropRotation(o,h)};if(V(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 I=e.url,f=await n.engine.editor.getMimeType(I),y=[{uri:await oo(n,I,f),width:l.width,height:l.height}];n.engine.block.setSourceSet(a,"fill/image/sourceSet",y),v();let b=()=>{n.engine.block.setSourceSet(a,"fill/image/sourceSet",s),v()},O=()=>{n.engine.block.setSourceSet(a,"fill/image/sourceSet",y),v()};return{consumedGenerationResult:e,applyCallbacks:{onBefore:b,onAfter:O,onCancel:()=>{b()},onApply:()=>{O()}}}}async function no(e,t){throw new Error("Function not implemented.")}async function io(e,t){throw new Error("Function not implemented.")}async function oo(e,t,n){let i=await(await fetch(t)).blob(),o=new File([i],`image.${ao(n)}`,{type:n}),a=await e.unstable_upload(o,()=>{}),s=a?.meta?.uri;return s??(console.warn("Failed to upload image:",a),t)}function ao(e){return{"image/png":"png","image/jpeg":"jpg","image/webp":"webp","image/gif":"gif","image/svg+xml":"svg"}[e]??"png"}var yt=eo;function so({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=lo(o.engine,s,e);let c=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 c}catch(c){throw k(c)&&l(),c}finally{t&&l()}}}function lo(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 bt=so;function uo(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},c=()=>{let u=new AbortController,p=u.signal;return l.abort=()=>{u.abort()},p};n.ui.registerComponent(s,({builder:u,engine:p,state:g})=>{let h=p.block.findAllSelected();if(h.length===0)return null;let v=new he(n.engine,Ce),I=v.get(h[0]);if(I==null)return null;let f=()=>{h.forEach(m=>{v.clear(m)})};switch(I.status){case"processing":{u.Button(`${o}.spinner`,{label:[`ly.img.ai.inference.${I.quickActionId}.processing`,`${o}.cancel`],isLoading:!0}),u.Separator(`${o}.separator`),u.Button(`${o}.cancel`,{icon:"@imgly/Cross",tooltip:`${o}.cancel`,onClick:()=>{l.abort(),f()}});break}case"confirmation":{let m=g(`${a}.comparing`,"after"),y=l.applyCallbacks?.onCancel;y!=null&&u.Button(`${a}.cancel`,{icon:"@imgly/Cross",tooltip:`${o}.cancel`,onClick:()=>{l.unlock(),y(),f()}});let b=l.applyCallbacks?.onBefore,O=l.applyCallbacks?.onAfter;b!=null&&O!=null&&u.ButtonGroup(`${a}.compare`,{children:()=>{u.Button(`${a}.compare.before`,{label:`${a}.before`,variant:"regular",isActive:m.value==="before",onClick:()=>{b(),m.setValue("before")}}),u.Button(`${a}.compare.after`,{label:`${a}.after`,variant:"regular",isActive:m.value==="after",onClick:()=>{O(),m.setValue("after")}})}});let w=l.applyCallbacks?.onApply;w!=null&&u.Button(`${a}.apply`,{icon:"@imgly/Checkmark",tooltip:`${a}.apply`,color:"accent",isDisabled:m.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,u=>{let p=u.engine.block.findAllSelected(),g=r.getQuickActionMenuOrder().map(m=>{if(m==="ly.img.separator")return m;let y=r.getQuickAction(m);if(y==null||!n.feature.isEnabled(ie({quickActionId:m,quickActionMenuId:r.id}),{engine:u.engine}))return null;let O=y.scopes;return O!=null&&O.length>0&&!p.every(x=>O.every(T=>u.engine.block.isAllowedByScope(x,T)))?null:y}).filter(m=>m!=null);if(g=pt(g),g.length===0||g.every(m=>m==="ly.img.separator"))return null;let{builder:h,experimental:v,state:I}=u,f=I(`${o}.toggleExpandedState`,void 0);v.builder.Popover(`${o}.popover`,{icon:"@imgly/Sparkle",variant:"plain",trailingIcon:null,children:({close:m})=>{h.Section(`${o}.popover.section`,{children:()=>{if(f.value!=null){let y=f.value,b=r.getQuickAction(y);if(b!=null&&b.renderExpanded!=null){b.renderExpanded(u,{blockIds:p,closeMenu:m,toggleExpand:()=>{f.setValue(void 0)},handleGenerationError:O=>{A(O,{cesdk:n,provider:i},t)},generate:async(O,w)=>{try{let{returnValue:x,applyCallbacks:T,dispose:It}=await ht({input:O,quickAction:b,quickActionMenu:r,provider:i,cesdk:n,abortSignal:c(),blockIds:w?.blockIds??p,confirmationComponentId:s},t);return l.unlock=It,l.applyCallbacks=T,x}catch(x){throw k(x)||A(x,{cesdk:n,provider:i},t),x}}});return}}v.builder.Menu(`${o}.menu`,{children:()=>{g.forEach(y=>{y==="ly.img.separator"?h.Separator(`${o}.separator.${Math.random().toString()}`):y.render(u,{blockIds:p,closeMenu:m,handleGenerationError:b=>{A(b,{cesdk:n,provider:i},t)},toggleExpand:()=>{f.setValue(y.id)},generate:async(b,O)=>{try{let{returnValue:w,applyCallbacks:x,dispose:T}=await ht({input:b,quickAction:y,quickActionMenu:r,provider:i,cesdk:n,abortSignal:c(),blockIds:O?.blockIds??p,confirmationComponentId:s},t);return l.unlock=T,l.applyCallbacks=x,w}catch(w){throw k(w)||A(w,{cesdk:n,provider:i},t),w}}})})}})}})}})}),{canvasMenuComponentId:d}}async function ht(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 c=new he(n.engine,Ce);i.forEach(f=>{c.set(f,{status:"processing",quickActionId:a.id})});let d={cesdk:n,engine:n.engine,abortSignal:l},u=B([...o.output.middleware??[],t.debug?_():void 0,gt({}),...a.confirmation?[a.lockDuringConfirmation?mt({editMode:ne}):bt({editMode:ne}),a.confirmation&&ft({})]:[]]),{result:p,dispose:g}=await u(o.output.generate)(r,d),{consumedGenerationResult:h,applyCallbacks:v}=await yt(p,{abortSignal:l,kind:o.kind,blockIds:i,cesdk:n});a.confirmation?i.forEach(f=>{c.set(f,{status:"confirmation",quickActionId:a.id})}):i.forEach(f=>{c.clear(f)});let I=()=>{g(),i.forEach(f=>{c.clear(f)})};return l.addEventListener("abort",I),{dispose:I,returnValue:h,applyCallbacks:v}}var we=uo;async function co(e,t,n){await e.initialize(t);let r=await fo(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}`]:po(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 go(e,o,n)}}function po(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 fo(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 rt(r,e)),r}return n}}async function go(e,t,n){let r={panel:void 0};return e.input?.panel!=null&&(r.panel=await mo(e,e.input.panel,t,n)),e.input?.quickActions!=null&&(n.debug&&console.log(`Initializing quick actions for provider '${e.kind}' (${e.id})`),yo(e,e.input.quickActions,t,n)),r}async function mo(e,t,n,r){switch(t.type){case"custom":return _e(e,t,n,r);case"schema":return Be(e,t,n,r);default:r.debug&&console.warn(`Invalid panel input type '${t.type}' - skipping`)}}async function yo(e,t,n,r){let{cesdk:i}=n,o=e.kind,a=Oe(i,o);t.actions.forEach(l=>{let c=l.enable??!0;i.feature.enable(ie({quickActionId:l.id,quickActionMenuId:o}),c),a.registerQuickAction(l),r.debug&&console.log(`Registered quick action: '${l.id}' (v${l.version}) to menu '${o}'`)});let{canvasMenuComponentId:s}=we({cesdk:i,quickActionMenu:a,provider:e},r);r.debug&&console.log(`Registered quick action menu component: ${s}`)}var bo=co;var xe={};function ho(e){let{maxRequests:t,timeWindowMs:n,keyFn:r=()=>"global",onRateLimitExceeded:i}=e;return async(a,s,l)=>{let c=r(a,s);xe[c]||(xe[c]={timestamps:[],lastCleanup:Date.now()});let d=xe[c],u=Date.now();if(u-d.lastCleanup>n&&(d.timestamps=d.timestamps.filter(p=>u-p<n),d.lastCleanup=u),d.timestamps.length>=t){let p=Math.min(...d.timestamps),g=Math.max(0,n-(u-p));if(i){let h={key:c,currentCount:d.timestamps.length,maxRequests:t,timeWindowMs:n,remainingTimeMs:g};if(!await i(a,s,h))throw new Error("Rate limit exceeded. Please try again later.")}else throw new Error("Rate limit exceeded. Please try again later.")}return d.timestamps.push(u),l(a,s)}}var Io=ho;function vo(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 Oo=vo;var as={ImageUrl:ke};export{as as CommonProperties,Ve as abortGenerationStateKey,B as composeMiddlewares,kt as getDurationForVideo,Y as getLabelFromId,G as getPanelId,Oe as getQuickActionMenu,le as getThumbnailForVideo,bo as initProvider,J as isGeneratingStateKey,_ as loggingMiddleware,Io as rateLimitMiddleware,Oo as registerDockComponent,we as registerQuickActionMenuComponent};
|
|
63
|
+
`,dt=qi;var pt="ly.img.ai.quickAction.order",Z="ly.img.ai.quickAction.actions";function Yi(e,t){return{id:t,setQuickActionMenuOrder:r=>{e.ui.experimental.setGlobalStateValue(`${pt}.${t}`,r)},getQuickActionMenuOrder:()=>e.ui.experimental.getGlobalStateValue(`${pt}.${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 Ce=Yi;var ne="ly.img.ai.inference.editMode",we="ly.img.ai.inference.metadata";function ie(e){return`ly.img.ai.quickAction.${e.quickActionMenuId}.${e.quickActionId}`}function ft(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 Wi({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 u=i.engine.block.getParent(d);u!=null&&i.engine.block.getType(u)!=="//ly.img.ubq/scene"&&(s[u]=i.engine.block.isClipped(u),i.engine.block.setClipped(u,!1))}}),i.addDisposer(async()=>{l.forEach(d=>{if(i.engine.block.isValid(d)&&e&&i.engine.block.setAlwaysOnTop(d,a[d]),t){let u=i.engine.block.getParent(d);u!=null&&i.engine.block.getType(u)!=="//ly.img.ubq/scene"&&s[u]!=null&&i.engine.block.setClipped(u,s[u])}})}),await o(r,i)}}var mt=Wi;function Ji({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 gt=Ji;function Xi({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=eo(i.engine,a,e),await o(r,i)}catch(l){throw k(l)&&s(),l}finally{t&&s()}}}function eo(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(u=>{t.includes(u)||e.block.setSelected(u,!1)}),t.forEach(u=>{e.block.setSelected(u,!0)})}let l=e.editor.onStateChanged(()=>{e.editor.getEditMode()!==n&&e.editor.setEditMode(n)}),c=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),c(),l()}}var yt=Xi;function to(e,t){switch(t.kind){case"text":return ro(e,t);case"image":return no(e,t);case"video":return io(e,t);case"audio":return oo(e,t);default:throw new Error(`Unsupported output kind for quick actions: ${t.kind}`)}}async function ro(e,t){let{cesdk:n,blockIds:r,abortSignal:i}=t,o=r.map(u=>n.engine.block.getString(u,"text/text")),a;if(A(e)){let u="";for await(let p of e){if(i.aborted)break;typeof p=="string"?u=p:p.kind==="text"&&(u=p.text),r.forEach(v=>{n.engine.block.setString(v,"text/text",u)}),a={kind:"text",text:u}}}else a=e;if(a==null||a.kind!=="text")throw new Error("Output kind from generation is not text");let s=()=>{t.blockIds.forEach(u=>{t.cesdk.engine.block.setString(u,"text/text",a.text)})},l=()=>{t.blockIds.forEach((u,p)=>{t.cesdk.engine.block.setString(u,"text/text",o[p])})};return{consumedGenerationResult:a,applyCallbacks:{onBefore:l,onAfter:s,onCancel:l,onApply:s}}}async function no(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,c=await n.engine.editor.getMimeType(l.uri);if(i.throwIfAborted(),c==="image/svg+xml")throw new Error("SVG images are not supported");let d=n.engine.block.getCropScaleX(o),u=n.engine.block.getCropScaleY(o),p=n.engine.block.getCropTranslationX(o),g=n.engine.block.getCropTranslationY(o),v=n.engine.block.getCropRotation(o),h=()=>{n.engine.block.setCropScaleX(o,d),n.engine.block.setCropScaleY(o,u),n.engine.block.setCropTranslationX(o,p),n.engine.block.setCropTranslationY(o,g),n.engine.block.setCropRotation(o,v)};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 I=e.url,f=await n.engine.editor.getMimeType(I),y=[{uri:await ao(n,I,f),width:l.width,height:l.height}];n.engine.block.setSourceSet(a,"fill/image/sourceSet",y),h();let b=()=>{n.engine.block.setSourceSet(a,"fill/image/sourceSet",s),h()},O=()=>{n.engine.block.setSourceSet(a,"fill/image/sourceSet",y),h()};return{consumedGenerationResult:e,applyCallbacks:{onBefore:b,onAfter:O,onCancel:()=>{b()},onApply:()=>{O()}}}}async function io(e,t){throw new Error("Function not implemented.")}async function oo(e,t){throw new Error("Function not implemented.")}async function ao(e,t,n){let i=await(await fetch(t)).blob(),o=new File([i],`image.${so(n)}`,{type:n}),a=await e.unstable_upload(o,()=>{}),s=a?.meta?.uri;return s??(console.warn("Failed to upload image:",a),t)}function so(e){return{"image/png":"png","image/jpeg":"jpg","image/webp":"webp","image/gif":"gif","image/svg+xml":"svg"}[e]??"png"}var bt=to;function lo({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=uo(o.engine,s,e);let c=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 c}catch(c){throw k(c)&&l(),c}finally{t&&l()}}}function uo(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 ht=lo;function co(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},c=()=>{let u=new AbortController,p=u.signal;return l.abort=()=>{u.abort()},p};n.ui.registerComponent(s,({builder:u,engine:p,state:g})=>{let v=p.block.findAllSelected();if(v.length===0)return null;let h=new Ie(n.engine,we),I=h.get(v[0]);if(I==null)return null;let f=()=>{v.forEach(m=>{h.clear(m)})};switch(I.status){case"processing":{u.Button(`${o}.spinner`,{label:[`ly.img.ai.inference.${I.quickActionId}.processing`,`${o}.cancel`],isLoading:!0}),u.Separator(`${o}.separator`),u.Button(`${o}.cancel`,{icon:"@imgly/Cross",tooltip:`${o}.cancel`,onClick:()=>{l.abort(),f()}});break}case"confirmation":{let m=g(`${a}.comparing`,"after"),y=l.applyCallbacks?.onCancel;y!=null&&u.Button(`${a}.cancel`,{icon:"@imgly/Cross",tooltip:`${o}.cancel`,onClick:()=>{l.unlock(),y(),f()}});let b=l.applyCallbacks?.onBefore,O=l.applyCallbacks?.onAfter;b!=null&&O!=null&&u.ButtonGroup(`${a}.compare`,{children:()=>{u.Button(`${a}.compare.before`,{label:`${a}.before`,variant:"regular",isActive:m.value==="before",onClick:()=>{b(),m.setValue("before")}}),u.Button(`${a}.compare.after`,{label:`${a}.after`,variant:"regular",isActive:m.value==="after",onClick:()=>{O(),m.setValue("after")}})}});let w=l.applyCallbacks?.onApply;w!=null&&u.Button(`${a}.apply`,{icon:"@imgly/Checkmark",tooltip:`${a}.apply`,color:"accent",isDisabled:m.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,u=>{let p=u.engine.block.findAllSelected(),g=r.getQuickActionMenuOrder().map(m=>{if(m==="ly.img.separator")return m;let y=r.getQuickAction(m);if(y==null||!n.feature.isEnabled(ie({quickActionId:m,quickActionMenuId:r.id}),{engine:u.engine}))return null;let O=y.scopes;return O!=null&&O.length>0&&!p.every(x=>O.every($=>u.engine.block.isAllowedByScope(x,$)))?null:y}).filter(m=>m!=null);if(g=ft(g),g.length===0||g.every(m=>m==="ly.img.separator"))return null;let{builder:v,experimental:h,state:I}=u,f=I(`${o}.toggleExpandedState`,void 0);h.builder.Popover(`${o}.popover`,{icon:"@imgly/Sparkle",variant:"plain",trailingIcon:null,children:({close:m})=>{v.Section(`${o}.popover.section`,{children:()=>{if(f.value!=null){let y=f.value,b=r.getQuickAction(y);if(b!=null&&b.renderExpanded!=null){b.renderExpanded(u,{blockIds:p,closeMenu:m,toggleExpand:()=>{f.setValue(void 0)},handleGenerationError:O=>{E(O,{cesdk:n,provider:i},t)},generate:async(O,w)=>{try{let{returnValue:x,applyCallbacks:$,dispose:vt}=await It({input:O,quickAction:b,quickActionMenu:r,provider:i,cesdk:n,abortSignal:c(),blockIds:w?.blockIds??p,confirmationComponentId:s},t);return l.unlock=vt,l.applyCallbacks=$,x}catch(x){throw k(x)||E(x,{cesdk:n,provider:i},t),x}}});return}}h.builder.Menu(`${o}.menu`,{children:()=>{g.forEach(y=>{y==="ly.img.separator"?v.Separator(`${o}.separator.${Math.random().toString()}`):y.render(u,{blockIds:p,closeMenu:m,handleGenerationError:b=>{E(b,{cesdk:n,provider:i},t)},toggleExpand:()=>{f.setValue(y.id)},generate:async(b,O)=>{try{let{returnValue:w,applyCallbacks:x,dispose:$}=await It({input:b,quickAction:y,quickActionMenu:r,provider:i,cesdk:n,abortSignal:c(),blockIds:O?.blockIds??p,confirmationComponentId:s},t);return l.unlock=$,l.applyCallbacks=x,w}catch(w){throw k(w)||E(w,{cesdk:n,provider:i},t),w}}})})}})}})}})}),{canvasMenuComponentId:d}}async function It(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 c=new Ie(n.engine,we);i.forEach(f=>{c.set(f,{status:"processing",quickActionId:a.id})});let d={cesdk:n,engine:n.engine,abortSignal:l},u=V([...o.output.middleware??[],t.debug?F():void 0,gt({}),...a.confirmation?[a.lockDuringConfirmation?yt({editMode:ne}):ht({editMode:ne}),a.confirmation&&mt({})]:[]]),{result:p,dispose:g}=await u(o.output.generate)(r,d),{consumedGenerationResult:v,applyCallbacks:h}=await bt(p,{abortSignal:l,kind:o.kind,blockIds:i,cesdk:n});a.confirmation?i.forEach(f=>{c.set(f,{status:"confirmation",quickActionId:a.id})}):i.forEach(f=>{c.clear(f)});let I=()=>{g(),i.forEach(f=>{c.clear(f)})};return l.addEventListener("abort",I),{dispose:I,returnValue:v,applyCallbacks:h}}var xe=co;async function po(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}`]:fo(e)}});let a="@imgly/plugin-ai-generation.iconSetAdded";return t.cesdk.ui.experimental.hasGlobalStateValue(a)||(t.cesdk.ui.addIconSet("@imgly/plugin-ai-generation",dt),t.cesdk.ui.experimental.setGlobalStateValue(a,!0)),{renderBuilderFunctions:await go(e,o,n)}}function fo(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 nt(r,e)),r}return n}}async function go(e,t,n){let r={panel:void 0};return e.input?.panel!=null&&(r.panel=await yo(e,e.input.panel,t,n)),e.input?.quickActions!=null&&(n.debug&&console.log(`Initializing quick actions for provider '${e.kind}' (${e.id})`),bo(e,e.input.quickActions,t,n)),r}async function yo(e,t,n,r){switch(t.type){case"custom":return _e(e,t,n,r);case"schema":return Fe(e,t,n,r);default:r.debug&&console.warn(`Invalid panel input type '${t.type}' - skipping`)}}async function bo(e,t,n,r){let{cesdk:i}=n,o=e.kind,a=Ce(i,o);t.actions.forEach(l=>{let c=l.enable??!0;i.feature.enable(ie({quickActionId:l.id,quickActionMenuId:o}),c),a.registerQuickAction(l),r.debug&&console.log(`Registered quick action: '${l.id}' (v${l.version}) to menu '${o}'`)});let{canvasMenuComponentId:s}=xe({cesdk:i,quickActionMenu:a,provider:e},r);r.debug&&console.log(`Registered quick action menu component: ${s}`)}var ho=po;function Io(e){return async(n,r,i)=>{let o=await i(n,r);return A(o)?o:await e(o)}}var vo=Io;var ke=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 Oo(e){let{maxRequests:t,timeWindowMs:n,keyFn:r=()=>"global",onRateLimitExceeded:i,dbName:o}=e,s=`rate-limit-middleware-${t}-${n}`,l=oe.isAvailable(),c=l?new oe(s,o):null;ke.has(s)||ke.set(s,{});let d=ke.get(s);return async(p,g,v)=>{let h=typeof r=="string"?r:r(p,g),I=Date.now(),f;if(l&&c)try{let m=await c.getTracker(h);m?f=m:f={timestamps:[],lastCleanup:I}}catch(m){console.error("IndexedDB access failed, using in-memory fallback:",m),d[h]||(d[h]={timestamps:[],lastCleanup:I}),f=d[h]}else d[h]||(d[h]={timestamps:[],lastCleanup:I}),f=d[h];if(I-f.lastCleanup>n&&(f.timestamps=f.timestamps.filter(m=>I-m<n),f.lastCleanup=I),f.timestamps.length>=t){let m=Math.min(...f.timestamps),y=Math.max(0,n-(I-m));if(i){let b={key:h,currentCount:f.timestamps.length,maxRequests:t,timeWindowMs:n,remainingTimeMs:y};if(!await i(p,g,b))throw new DOMException("Operation aborted: Rate limit exceeded","AbortError")}else throw new Error("Rate limit exceeded. Please try again later.")}if(f.timestamps.push(I),l&&c)try{await c.saveTracker(h,f)}catch(m){console.error("Failed to save tracker to IndexedDB:",m),d[h]=f}else d[h]=f;return v(p,g)}}var Co=Oo;function wo(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 xo=wo;var ds={ImageUrl:Me};export{ds as CommonProperties,Ve as abortGenerationStateKey,V as composeMiddlewares,Mt as getDurationForVideo,Y as getLabelFromId,G as getPanelId,Ce as getQuickActionMenu,ue as getThumbnailForVideo,ho as initProvider,J as isGeneratingStateKey,F as loggingMiddleware,Co as rateLimitMiddleware,xo as registerDockComponent,xe as registerQuickActionMenuComponent,vo as uploadMiddleware};
|
|
64
64
|
/*! Bundled license information:
|
|
65
65
|
|
|
66
66
|
@imgly/plugin-utils/dist/index.mjs:
|