handler-playable-sdk 0.3.34 → 0.3.36

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,10 +1,9 @@
1
- "use strict";var Jg=Object.create;var hr=Object.defineProperty;var Qg=Object.getOwnPropertyDescriptor;var em=Object.getOwnPropertyNames;var tm=Object.getPrototypeOf,im=Object.prototype.hasOwnProperty;var Ve=(e,t)=>()=>(e&&(t=e(e=0)),t);var k=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),an=(e,t)=>{for(var i in t)hr(e,i,{get:t[i],enumerable:!0})},Oc=(e,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of em(t))!im.call(e,r)&&r!==i&&hr(e,r,{get:()=>t[r],enumerable:!(n=Qg(t,r))||n.enumerable});return e};var di=(e,t,i)=>(i=e!=null?Jg(tm(e)):{},Oc(t||!e||!e.__esModule?hr(i,"default",{value:e,enumerable:!0}):i,e)),nm=e=>Oc(hr({},"__esModule",{value:!0}),e);var Ye,Ss=Ve(()=>{"use strict";Ye=class{static get(t){var i;return(i=this.store.get(t))==null?void 0:i.data}static set(t,i){this.store.set(t,{data:i})}static has(t){return this.store.has(t)}static clear(){this.store.clear()}};Ye.store=new Map});function um(){var e,t;try{let i=typeof window!="undefined"&&(document.querySelector('script[src*="inline-assets.js"]')||((t=(e=document.querySelector("script"))==null?void 0:e.textContent)==null?void 0:t.includes("inline-assets.js"))||window.INLINE_ASSETS),n=typeof window!="undefined"&&document.querySelector('link[href*="assets/"], script[src*="assets/"]');return!!(i&&!n)}catch{return!1}}async function pm(){try{if(typeof window!="undefined"){let e=await fetch("./build-settings.json");if(e.ok){let t=await e.json();return console.log("[AssetLoader] Loaded build settings:",t),t}}}catch{}return null}function fm(){try{if(typeof window!="undefined"){let e=new XMLHttpRequest;if(e.open("GET","./build-settings.json",!1),e.send(),e.status===200&&e.responseText){let t=JSON.parse(e.responseText);return console.log("[AssetLoader] Loaded build settings (sync):",t),t}}}catch{}return null}async function hm(){if(console.log(`[AssetLoader] getInlineAssets() called - Effective mode: ${V}`),Object.keys(Ke).length>0)return console.log("[AssetLoader] Returning cached inline assets:",Object.keys(Ke)),Ke;if(typeof window!="undefined"&&window.INLINE_ASSETS)return console.log("[AssetLoader] Using pre-loaded INLINE_ASSETS from window:",Object.keys(window.INLINE_ASSETS)),Ke={...window.INLINE_ASSETS},Ke;if(!(V==="publish"&&De!==!1))return console.log("[AssetLoader] Inline assets disabled for this build mode."),Ke;if(!As){let t=typeof window!="undefined"?new URL("inline-assets.js",window.location.href).href:"./inline-assets.js";console.log("[AssetLoader] Loading inline assets from:",t),As=(async()=>{try{try{let a=await import(t+"?t="+Date.now());if(a.INLINE_ASSETS)return console.log("[AssetLoader] Loaded INLINE_ASSETS via ES module:",Object.keys(a.INLINE_ASSETS)),a.INLINE_ASSETS}catch(a){console.warn("[AssetLoader] ES module import failed, trying text parse:",a)}let i=await fetch(t);if(!i.ok)throw new Error(`HTTP ${i.status}: ${i.statusText}`);let n=await i.text();console.log("[AssetLoader] Received JS code, length:",n.length);let r=n.match(/export\s+const\s+INLINE_ASSETS\s*=\s*({[\s\S]*?});?\s*$/m);if(r)try{let a=r[1];console.log("[AssetLoader] Found INLINE_ASSETS export, parsing...");let s=new Function("return "+a)();return console.log("[AssetLoader] Parsed inline assets:",Object.keys(s)),s}catch(a){return console.warn("[AssetLoader] Failed to parse inline assets:",a),{}}else return console.warn("[AssetLoader] INLINE_ASSETS export not found in response"),console.log("[AssetLoader] JS code preview:",n.substring(0,500)),{}}catch(i){return console.warn("[AssetLoader] Failed to load inline assets:",i),{}}})()}return Ke=await As,console.log("[AssetLoader] Final inline assets cache:",Object.keys(Ke)),Ke}function Cs(e){return e===null||typeof e!="object"||(Object.freeze(e),Object.values(e).forEach(t=>Cs(t))),e}function gm(e=64,t=64,i=16711680){let n=document.createElement("canvas");n.width=e,n.height=t;let r=n.getContext("2d");return r.fillStyle=`#${i.toString(16).padStart(6,"0")}`,r.fillRect(0,0,e,t),r.strokeStyle="#000",r.strokeRect(0,0,e,t),r.fillStyle="#fff",r.font="10px sans-serif",r.textAlign="center",r.fillText("MISSING",e/2,t/2),Xe.Texture.from(n)}function Ts(e,t){cd.set(e,t)}var Xe,od,ld,Nt,V,De,gt,Ke,As,cd,Bt,yr=Ve(()=>{"use strict";Xe=require("pixi.js");Ss();od=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",ld=um(),Nt=typeof window!="undefined"?window.__BUILD_SETTINGS__:null,V=ld?"publish":od,De=Nt==null?void 0:Nt.assetsInlined;Nt!=null&&Nt.buildMode&&(V=Nt.buildMode,console.log(`[AssetLoader] Build mode overridden by inline settings: ${V}`));gt=fm();gt!=null&&gt.buildMode&&(V=gt.buildMode,console.log(`[AssetLoader] Build mode overridden by sync settings: ${V}`));(gt==null?void 0:gt.assetsInlined)!==void 0&&(De=gt.assetsInlined);pm().then(e=>{e!=null&&e.buildMode&&e.buildMode!==V&&(V=e.buildMode,console.log(`[AssetLoader] Build mode overridden by settings: ${V}`)),(e==null?void 0:e.assetsInlined)!==void 0&&(De=e.assetsInlined)}).catch(()=>{});console.log(`[AssetLoader] MODULE LOADED - Compile: ${od}, Runtime: ${ld?"publish":"dev"}, Effective: ${V}`);Ke={},As=null;cd=new Map;Bt=class{static async load(t,i,n,r){let a=`${t}:${i.path}`,s=Ye.get(a);if(s!==void 0)return s;console.log(`[AssetLoader] Loading asset: ${t}, type: ${i.type}, Effective mode: ${V}`),console.log(`[AssetLoader] Window defined: ${typeof window!="undefined"}, INLINE_ASSETS exists: ${!!(typeof window!="undefined"&&window.INLINE_ASSETS)}, keys: ${typeof window!="undefined"&&window.INLINE_ASSETS?Object.keys(window.INLINE_ASSETS).length:"N/A"}`);let o=await hm(),l=o[t];if(!l&&r&&(l=o[r],l&&console.log(`[AssetLoader] Found inline data for ${t} using configId: ${r}`)),!l&&i.path){let u=i.path.split("/");if(u.length>=2){let p=u[u.length-1].split(".")[0];o[p]&&(l=o[p],console.log(`[AssetLoader] Found inline data for ${t} using assetName: ${p}`))}}if(console.log("[AssetLoader] Inline data for",t,":",l?"FOUND":"NOT FOUND"),V==="publish"&&De!==!1&&(console.log("[AssetLoader] \u26A0\uFE0F PUBLISH MODE DETECTED - inline assets are MANDATORY"),!l))throw new Error(`[AssetLoader] PUBLISH MODE: Inline asset required but NOT FOUND for object: ${t}, path: ${i.path}`);let d=cd.get(i.type);if(d)try{let u=await d(i.path,l,t,n);return Ye.set(a,u),u}catch(u){return this.handleFailure(t,i.type,u)}try{let u;switch(i.type){case"image":u=await this.loadImage(i.path,l);break;case"json":u=await this.loadJSON(i.path,l),u=Cs(u);break;default:throw new Error(`Unknown asset type: ${i.type}`)}return Ye.set(a,u),u}catch(u){return this.handleFailure(t,i.type,u)}}static async loadImage(t,i){let n=V==="publish",r=n&&De!==!1;if(console.log(`[AssetLoader] loadImage - Effective mode: ${V}, isPublishMode: ${n}, inlineData: ${i?"EXISTS":"MISSING"}`),r){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!i)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for object. Path: ${t}`);if(typeof i!="string"||!i.startsWith("data:"))throw new Error(`[AssetLoader] Publish mode: inline asset must be data URI string, got: ${typeof i}`);try{return await Xe.Assets.load(i)}catch(a){throw console.error("[AssetLoader] Failed to load texture from data URI:",a),a}}if(i&&typeof i=="string"&&i.startsWith("data:"))try{return await Xe.Assets.load(i)}catch(a){return console.error("[AssetLoader] Failed to load texture from data URI, falling back to path:",a),await Xe.Assets.load(t)}return await Xe.Assets.load(t)}static async loadJSON(t,i){let n=V==="publish",r=n&&De!==!1;if(console.log(`[AssetLoader] loadJSON - Effective mode: ${V}, isPublishMode: ${n}, inlineData: ${i?"EXISTS":"MISSING"}`),r){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!i)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${t}`);if(typeof i=="object"&&i!==null)return i;if(typeof i=="string"&&i.startsWith("data:")){let s=atob(i.split(",")[1]);return JSON.parse(s)}return JSON.parse(i)}if(i){if(typeof i=="object"&&i!==null)return i;if(typeof i=="string"&&i.startsWith("data:")){let s=atob(i.split(",")[1]);return JSON.parse(s)}return JSON.parse(i)}let a=await fetch(t);if(!a.ok)throw new Error(`JSON fetch failed: ${t}`);return a.json()}static handleFailure(t,i,n){if(V==="dev"){let a=i==="image"?gm():Cs({__placeholder:!0,type:i});return Ye.set(t+":"+((n==null?void 0:n.path)||"missing"),a),a}throw n}};Ts("image",async(e,t)=>{let i=V==="publish",n=i&&De!==!1,r=V==="brand",a=i&&De===!1;if(console.log(`[AssetLoader] registerType('image') - Effective mode: ${V}, isPublishMode: ${i}, isBrandMode: ${r}, inlineData: ${t?"EXISTS":"MISSING"}`),n){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!t)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${e}`);if(typeof t!="string"||!t.startsWith("data:"))throw new Error(`[AssetLoader] Publish mode: inline asset must be data URI string, got: ${typeof t}`);return Xe.Assets.load(t)}let s=e;return(r||a)&&e&&!e.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(s=e,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${e}" as-is`)):(s=`assets/${e}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${e}" -> "${s}"`))),Xe.Assets.load(t||s)});Ts("json",async(e,t)=>{let i=V==="publish",n=i&&De!==!1,r=V==="brand",a=i&&De===!1;if(console.log(`[AssetLoader] registerType('json') - Effective mode: ${V}, isPublishMode: ${i}, isBrandMode: ${r}, inlineData: ${t?"EXISTS":"MISSING"}`),n){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!t)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${e}`);return typeof t=="object"&&t!==null?t:typeof t=="string"&&t.startsWith("data:")?JSON.parse(atob(t.split(",")[1])):JSON.parse(t)}let s=e;if((r||a)&&e&&!e.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(s=e,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${e}" as-is`)):(s=`assets/${e}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${e}" -> "${s}"`))),t)return typeof t=="object"&&t!==null?t:typeof t=="string"&&t.startsWith("data:")?JSON.parse(atob(t.split(",")[1])):JSON.parse(t);let o=await fetch(s);if(!o.ok)throw new Error(`JSON fetch failed: ${e}`);return o.json()})});var ud={};an(ud,{AssetTextures:()=>ze,initAssetTextures:()=>Os});function Os(e,t){dd.init(e,t),typeof window!="undefined"&&(window.__AssetTextures=ze)}var Ls,dd,ze,hi=Ve(()=>{"use strict";yr();Ls=class{constructor(){this.textures=new Map;this.readyPromise=null;this.priorityReadyPromise=null;this.priorityReadyResolve=null;this.config=null;this.app=null;this.attempted=new Set;this.waiters=new Set}init(t,i){if(this.config===t&&this.app===i&&this.priorityReadyPromise){console.log("[AssetTextures] init called with same config/app; keeping existing state");return}this.textures.clear(),this.readyPromise=null,this.priorityReadyPromise=null,this.priorityReadyResolve=null,this.attempted.clear(),this.waiters.clear(),this.priorityReadyPromise=new Promise(n=>{this.priorityReadyResolve=n}),this.config=t,this.app=i,console.log("[AssetTextures] Initialized with config, cleared previous textures")}async ready(){if(this.readyPromise){await this.readyPromise;return}if(!this.config)throw new Error("[AssetTextures] Must call init() before ready() - config is null");if(!this.app)throw new Error("[AssetTextures] Must call init() before ready() - app is null");let t=this.config,i=this.app;return this.readyPromise=(async()=>{var s;console.log("[AssetTextures] Loading all assets...");let n=new Set(["background_loading_1"]),r=[],a=[];for(let[o,l]of t.objects.entries()){let c=(s=l.render)==null?void 0:s.asset;if(!c)continue;let d=async()=>{var u;try{let p=(u=l.identity)==null?void 0:u.id;console.log(`[AssetTextures] Loading ${c.type}: ${o} (${p})`);let f=await Bt.load(o,c,i,p);this.textures.set(o,f),console.log(`[AssetTextures] \u2713 Loaded: ${o}`)}catch(p){console.error(`[AssetTextures] \u2717 Failed to load: ${o}`,p)}finally{this.attempted.add(o);try{for(let p of Array.from(this.waiters))p()}catch{}}};n.has(o)?r.push(d()):a.push(d())}r.length>0&&(console.log("[AssetTextures] Phase 1: Loading priority assets (loading screen)..."),await Promise.all(r),console.log("[AssetTextures] Phase 1: Priority assets ready")),this.priorityReadyResolve&&this.priorityReadyResolve(),console.log("[AssetTextures] Phase 2: Loading remaining assets..."),await Promise.all(a),console.log("[AssetTextures] All textures loaded:",Array.from(this.textures.keys()))})(),this.readyPromise}async priorityReady(){return this.priorityReadyPromise?this.priorityReadyPromise:Promise.resolve()}async waitFor(t,i={}){if(!this.config)throw new Error("[AssetTextures] Must call init() before waitFor() - config is null");if(!this.app)throw new Error("[AssetTextures] Must call init() before waitFor() - app is null");let r=Array.from(new Set((t||[]).filter(o=>typeof o=="string"&&o))).filter(o=>{var l,c,d,u;try{let p=(d=(c=(l=this.config)==null?void 0:l.objects)==null?void 0:c.get)==null?void 0:d.call(c,o);return!!((u=p==null?void 0:p.render)!=null&&u.asset)}catch{return!1}});if(r.length===0)return;this.ready().catch(()=>{});let a=()=>r.every(o=>this.textures.has(o)||this.attempted.has(o));if(a())return;let s=typeof i.timeoutMs=="number"?i.timeoutMs:15e3;await new Promise(o=>{let l=!1,c=()=>{l||a()&&(l=!0,this.waiters.delete(c),o())};this.waiters.add(c),c(),s>0&&setTimeout(()=>{l||(l=!0,this.waiters.delete(c),console.warn("[AssetTextures] waitFor timed out; continuing",{ids:r}),o())},s)})}get(t){return this.textures.get(t)}set(t,i){this.textures.set(t,i),console.log(`[AssetTextures] Updated texture: ${t}`)}clear(){this.textures.clear(),this.readyPromise=null,console.log("[AssetTextures] Cleared all textures")}getAllIds(){return Array.from(this.textures.keys())}},dd=new Ls,ze=new Proxy(dd,{get(e,t){return t in e&&typeof e[t]=="function"?e[t].bind(e):e.get(t)},set(e,t,i){return e.set(t,i),!0}})});var Mr={};an(Mr,{applyConfigOverride:()=>bt,applyConfigOverrides:()=>yt,applyConfigsToDisk:()=>hn,clearConfigOverrides:()=>vt,clearConfigOverridesForObject:()=>Ed,configOverrideManager:()=>Sd,deepClone:()=>ne,exportConfigsAsJSON:()=>fn,getConfigOverrides:()=>de,getConfigStateSummary:()=>Or,getOverrideMode:()=>pn,removeConfigOverride:()=>Lr,resetToApplied:()=>gn,resetToOriginal:()=>Ir,setOverrideMode:()=>Rs});function Tr(){return typeof window=="undefined"?null:window.__editableConfig||null}function yd(){return typeof window=="undefined"?null:window.__editableConfigBaseline||null}function md(e,t){var i,n;if(!e)return null;try{if(e instanceof Map)return(i=e.get(t))!=null?i:null;if(typeof e=="object")return(n=e[t])!=null?n:null}catch{}return null}function Fm(e,t,i){if(e){if(e instanceof Map){e.set(t,i);return}typeof e=="object"&&(e[t]=i)}}function vd(e,t){for(let i of t)un(e,i.path,i.value)}function xd(e){var o;if(typeof window=="undefined")return;let t=Tr();if(!t)return;let i=yd(),n=(o=i?md(i.objects,e):null)!=null?o:md(t.objects,e);if(!n)return;let r=ne(n),a=de().filter(l=>l.objectId===e);try{vd(r,a)}catch(l){console.error("[CONFIG] Failed to reapply overrides for object",e,l);return}Fm(t.objects,e,r);let s=window.applyEditableObjectConfig;if(typeof s=="function")try{s(e,r)}catch{}}function $m(){var r;if(typeof window=="undefined")return;let e=Tr();if(!(e!=null&&e.engine))return;let t=yd(),i=ne(((r=t==null?void 0:t.engine)!=null?r:e.engine)||{}),n=de().filter(a=>!a.objectId&&!a.sceneId);try{vd(i,n)}catch(a){console.error("[CONFIG] Failed to reapply engine overrides",a);return}try{let a=e.engine;for(let s of Object.keys(a))s in i||delete a[s];for(let[s,o]of Object.entries(i))a[s]=o}catch{e.engine=i}}function Hm(){if(typeof window=="undefined")return"unknown";let e=window;return typeof e.__HANDLER_PROJECT_ID=="string"?e.__HANDLER_PROJECT_ID:"handler-default"}function wd(){return`handler_preview_config_overrides::${Hm()}`}function Um(){if(typeof window=="undefined")return[];try{let e=window.localStorage.getItem(wd());if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function kr(e){if(typeof window!="undefined")try{window.localStorage.setItem(wd(),JSON.stringify(e))}catch{}}function pn(){return typeof window=="undefined"?!1:window.__enableConfigOverrides===!0}function Rs(e){if(typeof window!="undefined"){window.__enableConfigOverrides=e;try{window.localStorage.setItem(_d,e?"true":"false")}catch{}}}function bt(e,t={}){var p,f;let{objectId:i,path:n,value:r}=e,{silent:a=!1,persist:s=!0,emitEvent:o=!0}=t,l=Tr();if(!l){console.warn("[CONFIG] applyConfigOverride: No editable config found in window.__editableConfig");return}let c=i?(f=(p=l.objects)==null?void 0:p.get)==null?void 0:f.call(p,i):l.engine;if(!c){console.warn("[CONFIG] applyConfigOverride: Override target not found:",{objectId:i,path:n,hasObjects:!!l.objects});return}a||console.log("[CONFIG] applyConfigOverride: Target found, applying...",{objectId:i,path:n,value:r});let d;try{d=Gm(c,n),un(c,n,r)}catch(g){console.error("[CONFIG] applyConfigOverride failed:",{objectId:i,path:n,value:r},g);return}window.__configChanges=window.__configChanges||[];let u=window.__configChanges;if(u.push({objectId:i,path:n,oldValue:d,newValue:r,ts:Date.now()}),u.length>qm&&u.shift(),s){let g=de(),h=g.findIndex(m=>m.objectId===i&&m.sceneId===e.sceneId&&m.path===n);h>=0?g[h].value=r:g.push(e),window.__configOverrides=g,kr(g),pn()||Rs(!0)}a||console.log("[CONFIG] Applied override:",e),o&&typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("config:changed",{detail:e}))}function yt(e,t={}){let i=t.emitEvent!==!1,n=[];for(let r of e)r!=null&&r.objectId&&typeof r.objectId=="string"&&n.push(r.objectId),bt(r,{...t,emitEvent:!1});if(i&&typeof window!="undefined"){let r=Array.from(new Set(n));window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"batch",objectIds:r,count:e.length}}))}}function vt(){window.__configOverrides=[],window.__configChanges=[],kr([]),console.log("[CONFIG] Cleared all overrides")}function Ed(e){let t=de().filter(n=>n.objectId!==e);window.__configOverrides=t,kr(t);let i=window.__configChanges||[];window.__configChanges=i.filter(n=>n.objectId!==e),xd(e),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"clear_object",objectId:e}}))}function Lr(e,t){let i=de().filter(r=>r.objectId!==e||r.path!==t);window.__configOverrides=i,kr(i);let n=window.__configChanges||[];window.__configChanges=n.filter(r=>r.objectId!==e||r.path!==t),e?xd(e):$m(),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"remove",objectId:e,path:t}}))}function de(){return typeof window=="undefined"?[]:(window.__configOverrides||(window.__configOverrides=Um()),window.__configOverrides||[])}function un(e,t,i){var s;let n=t.split("."),r=n.pop(),a=e;for(let o of n){if(a[o]!==void 0&&typeof a[o]!="object")throw new Error(`Invalid override path: ${t} (hit primitive at ${o})`);a[o]=(s=a[o])!=null?s:{},a=a[o]}a[r]=i}function Gm(e,t){return t.split(".").reduce((i,n)=>i?i[n]:void 0,e)}function ne(e){if(e===null||typeof e!="object")return e;if(e instanceof Date)return new Date(e.getTime());if(e instanceof Set)return new Set([...e].map(i=>ne(i)));if(ArrayBuffer.isView(e))return e.slice();if(e instanceof Array)return e.map(i=>ne(i));if(e instanceof Map){let i=new Map;return e.forEach((n,r)=>i.set(r,ne(n))),i}let t={};for(let i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=ne(e[i]));return t}function fn(){let e=window.__editableConfigBaseline;if(!e){let t=window.__editableConfig;if(!t)throw new Error("Cannot export: no config loaded");return bd(t)}return bd(e)}function bd(e){let t={objects:{},scenes:{},engine:ne(e.engine||{})},i=e.objects;if(i instanceof Map)i.forEach((a,s)=>{t.objects[s]=ne(a)});else if(i&&typeof i=="object")for(let a in i)t.objects[a]=ne(i[a]);let n=e.scenes;if(n instanceof Map)n.forEach((a,s)=>{t.scenes[s]=ne(a)});else if(n&&typeof n=="object")for(let a in n)t.scenes[a]=ne(n[a]);let r=de();for(let a of r)a.objectId?(t.objects[a.objectId]||(t.objects[a.objectId]={}),un(t.objects[a.objectId],a.path,a.value)):a.sceneId?(t.scenes[a.sceneId]||(t.scenes[a.sceneId]={}),un(t.scenes[a.sceneId],a.path,a.value)):un(t.engine,a.path,a.value);return t}function Or(){let e=de(),t=new Set;for(let i of e)i.objectId?t.add(i.objectId):t.add("__engine__");return{modifiedObjects:Array.from(t),overrideCount:e.length,hasChanges:e.length>0,overrides:e}}async function hn(e){let t=fn(),i={};for(let[r,a]of Object.entries(t.objects)){let s=a,o=r;/^(json\.|ui\.|effects\.|engine\.)/.test(o)||(o=`json.${r}`),s&&typeof s=="object"&&(s.identity||(s.identity={}),s.identity.id=o),i[`objects/${o}.json`]=s}t.engine&&(t.engine.runtime&&(i["engine/engine.runtime.json"]=t.engine.runtime),t.engine.assets&&(i["engine/engine.assets.json"]=t.engine.assets),t.engine.splash&&(i["engine/engine.splash.json"]=t.engine.splash),t.engine.loading&&(i["engine/engine.loading.json"]=t.engine.loading),t.engine.start&&(i["engine/engine.start.json"]=t.engine.start),t.engine.tutorial&&(i["engine/engine.tutorial.json"]=t.engine.tutorial),t.engine.endgame&&(i["engine/engine.endgame.json"]=t.engine.endgame),!t.engine.runtime&&!t.engine.assets&&(i["engine/engine.json"]=t.engine));for(let[r,a]of Object.entries(t.scenes)){let s=r.startsWith("scene.")?r:`scene.${r}`;i[`scenes/${s}.json`]=a}let n=await fetch("/api/apply",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:i,assets:{},hadCacheAtApply:de().length>0,versionName:e})});if(!n.ok){let r=await n.json();throw new Error(`Apply failed: ${r.error||"Unknown error"}`)}vt();try{let r=Tr();r&&(window.__editableConfigBaseline=ne(r))}catch{}localStorage.setItem("handler_last_applied",Date.now().toString()),console.log("[Config Persistence] \u2705 Applied to disk successfully")}function gn(){vt(),window.location.reload()}async function Ir(){if(!confirm("This will restore all configs to their original state. All uncommitted changes in cache AND applied changes will be lost. Continue?"))return;let t=await fetch("/api/reset-to-original",{method:"POST"});if(!t.ok){let i=await t.json();throw new Error(`Reset failed: ${i.error||"Unknown error"}`)}vt(),window.location.reload()}var _d,qm,Sd,Te=Ve(()=>{"use strict";_d="handler_preview_override_mode";if(typeof window!="undefined"){let e=window.localStorage.getItem(_d);window.__enableConfigOverrides=e===null?!0:e==="true"}qm=500;Sd={getCurrentConfig(){return window.__editableConfig||null},getChanges(){return window.__configChanges||[]},clearChanges(){window.__configChanges=[]}}});function Wm(e,t){try{if(typeof e=="object"&&e!==null)return e;if(typeof e!="string")return null;if(e.startsWith("data:")){let n=e.indexOf(",");if(n===-1)return null;let r=e.slice(0,n);if(!r.includes("application/json")&&!r.includes("text/plain"))return null;let a=e.slice(n+1),s=r.includes("base64")?typeof atob=="function"?atob(a):a:decodeURIComponent(a);return JSON.parse(s)}let i=e.trim();return i.startsWith("{")||i.startsWith("[")?JSON.parse(e):null}catch{return null}}function Vm(e){if(typeof window=="undefined"||!window.INLINE_ASSETS)return null;let t=window.INLINE_ASSETS,i=e.replace(/^\.\/+/,""),n=i.split("/").pop()||i,r=[i,n,i.replace(/\.json$/,""),n.replace(/\.json$/,"")];for(let a of r){let s=t[a];if(s){let o=Wm(s,a);if(o!==null)return o}}return null}async function mn(e){if(js.has(e)&&!Ds)return console.log(`[CONFIG] Using cached config for: "${e}"`),js.get(e);if(console.log(`[CONFIG] loadConfigFile called with: "${e}", MODE: ${G.toUpperCase()}, CACHE: ${Ds?"DISABLED":"ENABLED"}`),G==="publish"){let n=Vm(e);return n?(console.log(`[CONFIG] \u2713 Loaded ${e} via INLINE_ASSETS`),n):(console.log(`[CONFIG] \u2139\uFE0F Optional config ${e} not in INLINE_ASSETS, skipping fetch in publish mode`),{})}G==="brand"||console.log(`[CONFIG] DEV MODE: Trying nested paths first, then flattened for "${e}"`);let t;G==="brand"?t=[`./${e.split("/").pop()||e}`,`./${e}`,`./${e.replace(/^configs\//,"")}`,`./${e.replace(/^configs\//,"").replace(/\//g,".")}`]:t=[`./${e}`,`./${e.replace(/^configs\//,"")}`,`./${e.replace(/^configs\//,"").replace(/\//g,".")}`],t=Array.from(new Set(t.flatMap(n=>n.startsWith("./")?[n,`/${n.slice(2)}`]:n.startsWith("/")?[n]:[n,`/${n}`]))),console.log("[CONFIG] Will try candidates:",t);let i=(async()=>{let n=Ds?"no-store":"force-cache";for(let r of t)try{let a=await fetch(r,{cache:n});if(!a.ok)continue;let s=await a.json();return console.log(`[CONFIG] \u2713 Loaded ${e} via ${r}`,s),s}catch(a){console.warn(`[CONFIG] \u2717 Failed to load ${r} (mode: ${G}):`,a)}return console.warn(`[CONFIG] \u2717 All attempts failed for ${e}; using defaults`),{}})();return js.set(e,i),i}async function Pr(){console.log("[CONFIG] Loading component schemas...");let e=["components/identity.schema.json","components/transform.schema.json","components/render.schema.json","components/motion.schema.json","components/effects.schema.json","components/interaction.schema.json","components/gameplay.rules.schema.json","components/gameplay.tuning.schema.json","components/visibility.schema.json","components/audio.schema.json","components/physics.schema.json","components/ui.schema.json"],t=new Map;for(let i of e)try{let n=G==="publish"||G==="brand"?i.split("/").pop()||i:`configs/${i}`,r=await mn(n);r.component&&(t.set(r.component,r),console.log(`[CONFIG] \u2713 Schema loaded: ${r.component} ${G==="publish"||G==="brand"?"(flattened)":"(nested)"}`))}catch(n){console.warn(`[CONFIG] \u2717 Failed to load schema ${i}:`,n)}return console.log(`[CONFIG] Loaded ${t.size} component schemas`),t}async function xt(e){console.log(`[CONFIG] Loading object config: ${e}`);let t=G==="publish"||G==="brand"?`${e}.json`:`configs/objects/${e}.json`;return await mn(t)}async function Rr(e){let t=new Map;if(e.objects&&Array.isArray(e.objects)){for(let i of e.objects)if(i.enabled&&i.object_config)try{let n=i.instance_id;/^(json\.|ui\.|effects\.|engine\.)/.test(n)||(n=`json.${n}`);let r=await xt(n);(!r||Object.keys(r).length===0)&&n!==i.instance_id&&(r=await xt(i.instance_id)),!r||Object.keys(r).length===0?(console.log(`[CONFIG] No instance snapshot for ${i.instance_id}, using template ${i.object_config}`),r=await xt(i.object_config)):console.log(`[CONFIG] \u2713 Loaded instance snapshot for ${i.instance_id}`),t.set(i.instance_id,{...r,instance_id:i.instance_id,object_config:i.object_config})}catch(n){console.warn(`Failed to load object ${i.object_config}:`,n)}}return t}async function jr(){console.log("[CONFIG] Loading engine configs...");let e=["runtime","assets","splash","loading","start","tutorial","endgame"],t=await Promise.all(e.map(n=>{let r=`engine.${n}.json`,a=G==="publish"||G==="brand"?r:`configs/engine/${r}`;return mn(a)})),i=Object.fromEntries(e.map((n,r)=>[n,t[r]]));return console.log("[CONFIG] Engine configs loaded:",Object.fromEntries(e.map(n=>{var s;let r=(s=i[n])!=null?s:{},a=Object.keys(r);return[n,a.length>0?a:"empty"]}))),i}async function zs(){return await mn(G==="publish"||G==="brand"?"game.prompt.json":"configs/engine/game.prompt.json")}async function Dr(e="scene.main"){console.log(`[CONFIG] Loading scene config: ${e}`);let t=G==="publish"||G==="brand"?`${e}.json`:`configs/scenes/${e}.json`;return await mn(t)}function gi(e,t){let i=[];if(!e.identity)return i.push("Missing required identity component"),{valid:!1,errors:i};let n=t.get("identity");if(n)for(let r of n.required||[])e.identity[r]||i.push(`Missing required identity field: ${r}`);for(let[r,a]of Object.entries(e)){if(r==="identity")continue;let s=t.get(r);if(s&&a&&typeof a=="object"){let o=a;for(let l of s.required||[])o[l]===void 0&&i.push(`Missing required field in ${r}: ${l}`);if(s.constraints&&typeof s.constraints=="object")for(let[l,c]of Object.entries(s.constraints)){let d=o[l];if(d!==void 0&&c&&typeof c=="object"){let u=c;typeof d=="number"&&(u.min!==void 0&&d<u.min&&i.push(`${r}.${l} value ${d} is below minimum ${u.min}`),u.max!==void 0&&d>u.max&&i.push(`${r}.${l} value ${d} is above maximum ${u.max}`))}}}}return{valid:i.length===0,errors:i}}function $t(e,t){let i={...e},n=["identity","transform","render"];for(let[r,a]of t.entries())a.defaults&&Object.keys(a.defaults).length>0&&(n.includes(r)||i[r])&&(i[r]||(i[r]={}),i[r]={...a.defaults,...i[r]});return i}function xe(e,t,i,n){return typeof e!="number"||!Number.isFinite(e)?t:Math.min(Math.max(e,i),n)}function Cd(e,t){if(Array.isArray(e))return{x:xe(e[0],t.x,-2e3,2e3),y:xe(e[1],t.y,-2e3,2e3)};if(!e||typeof e!="object")return t;let{x:i,y:n}=e;return{x:xe(i,t.x,-2e3,2e3),y:xe(n,t.y,-2e3,2e3)}}function Ym(e,t){if(Array.isArray(e))return{x:xe(e[0],t.x,0,1),y:xe(e[1],t.y,0,1)};if(!e||typeof e!="object")return t;let{x:i,y:n}=e;return{x:xe(i,t.x,0,1),y:xe(n,t.y,0,1)}}function Km(e){if(Array.isArray(e))return{x:xe(e[0],.5,-10,10),y:xe(e[1],.5,-10,10)};if(e&&typeof e=="object"){let{x:t,y:i}=e;return{x:xe(t,.5,-10,10),y:xe(i,.5,-10,10)}}return typeof e=="string"?e:null}async function et(e="scene.main",t){var l,c,d,u,p,f,g,h,m,b,y,v,x,w;console.log("[CONFIG] ===== Starting Object-Centric Config Load =====");let i=await Pr(),n=de();n.length>0&&console.log(`[CONFIG] Applying ${n.length} active overrides`);let r=await Dr(e);console.log(`[CONFIG] Scene config loaded: ${((l=r.objects)==null?void 0:l.length)||0} objects`);let a=await jr();console.log("[CONFIG] Loading object configs...");let s=await Rr(r);console.log(`[CONFIG] Loaded ${s.size} object configs:`,Array.from(s.keys()));for(let[E,A]of s.entries()){let _=$t(A,i),T=gi(_,i);T.valid||console.warn(`Object ${E} validation errors:`,T.errors),(c=_.transform)!=null&&c.position&&(_.transform.position=Cd(_.transform.position,{x:0,y:0})),(d=_.transform)!=null&&d.offset&&(_.transform.offset=Cd(_.transform.offset,{x:0,y:0})),((u=_.transform)==null?void 0:u.anchor)!==void 0&&(_.transform.anchor=Km(_.transform.anchor)),((p=_.transform)==null?void 0:p.position_ratio)!==void 0&&_.transform.position_ratio!==null&&(_.transform.position_ratio=Ym(_.transform.position_ratio,{x:.5,y:.5})),s.set(E,_)}if(t){if(t.objects)for(let[E,A]of t.objects.entries())s.set(E,A);t.engine&&(a.runtime={...a.runtime,...t.engine.runtime},a.assets={...a.assets,...t.engine.assets},a.splash={...(f=a.splash)!=null?f:{},...(g=t.engine.splash)!=null?g:{}})}let o={objects:s,engine:a,scene:r,schemas:i,theme:{background_color:"#ffffff",text_color:"#000000",square_color:"#cccccc",cta_background:"#007bff",cta_text:"#ffffff"},gameplay:{}};return typeof window!="undefined"&&(window.__editableConfig=o,window.__editableConfigBaseline||(window.__editableConfigBaseline=$t(o,i))),n.length>0&&pn()&&yt(n,{silent:!0,persist:!1}),console.log("[CONFIG] ===== Object-Centric Config Load Complete ====="),console.log("[CONFIG] Summary:",{schemas:Array.from(i.keys()),objects:Array.from(s.keys()),engine:{runtime:Object.keys((h=a.runtime)!=null?h:{}),assets:Object.keys((m=a.assets)!=null?m:{}),splash:Object.keys((b=a.splash)!=null?b:{}),loading:Object.keys((y=a.loading)!=null?y:{}),start:Object.keys((v=a.start)!=null?v:{}),tutorial:Object.keys((x=a.tutorial)!=null?x:{}),endgame:Object.keys((w=a.endgame)!=null?w:{})},scene:r.scene_id||"unknown"}),o}function Ns(e){var i,n,r,a,s,o,l,c,d,u,p,f,g,h,m,b,y,v,x,w,E,A,_,T,P,S,L,z,D,B,O,R,C;let t={gameplay:{},ui:{},theme:{},assets:{}};for(let[I,j]of e.objects.entries()){let Q=((i=j.identity)==null?void 0:i.id)||I;Q.includes("character")&&(t.gameplay.character_pos=((n=j.transform)==null?void 0:n.position)||{x:0,y:0},t.gameplay.character_scale=((r=j.transform)==null?void 0:r.scale)||1,t.gameplay.character_anim_speed=((s=(a=j.gameplay)==null?void 0:a.tuning)==null?void 0:s.anim_speed)||.003,t.gameplay.character_relief_scale=((l=(o=j.gameplay)==null?void 0:o.tuning)==null?void 0:l.relief_scale)||1.22,t.gameplay.character_relief_speed=((d=(c=j.gameplay)==null?void 0:c.tuning)==null?void 0:d.relief_speed)||.22),(Q.includes("gun")||Q.includes("flame"))&&(t.gameplay.gun=j.gun||{},t.gameplay.gunmuzzle=((u=j.effects)==null?void 0:u.gunmuzzle)||{},t.gameplay.muzzle_levels=((p=j.effects)==null?void 0:p.muzzle_levels)||{},t.gameplay.flame=((f=j.effects)==null?void 0:f.flame)||{}),Q.includes("diamond")&&(t.gameplay.diamond=j),Q.includes("ice")&&(t.gameplay.melt=j.melt||{},t.gameplay.melt_anchor=((g=j.transform)==null?void 0:g.melt_anchor)||{x:0,y:0},t.gameplay.melt_pos=((h=j.transform)==null?void 0:h.position)||{x:0,y:0},t.gameplay.hybrid_melting=((m=j.effects)==null?void 0:m.hybrid_melting)||{},t.gameplay.physics_chunks=((b=j.effects)==null?void 0:b.physics_chunks)||{},t.gameplay.melting_particles=((y=j.effects)==null?void 0:y.melting_particles)||{},t.gameplay.hard_ice=j.hard_ice||{}),Q.includes("water")&&(t.gameplay.water_drops=j),Q.includes("crack")&&(t.gameplay.crack=j),Q.includes("hand")&&(t.gameplay.hand=((v=j.gameplay)==null?void 0:v.tuning)||{},t.gameplay.brush_start_pos=((x=j.transform)==null?void 0:x.brush_start_pos)||{x:0,y:-120},t.gameplay.hand_scale=((w=j.transform)==null?void 0:w.scale)||1.5),Q.includes("hazard")&&(t.gameplay.hazard=((E=j.gameplay)==null?void 0:E.tuning)||{},t.gameplay.danger_pos=((A=j.transform)==null?void 0:A.danger_pos)||{x:0,y:235},t.gameplay.danger_pulse=((T=(_=j.gameplay)==null?void 0:_.tuning)==null?void 0:T.danger_pulse)||{},t.gameplay.hazard_height=((S=(P=j.gameplay)==null?void 0:P.tuning)==null?void 0:S.hazard_height)||140)}return t.gameplay.timeline=((L=e.engine.runtime)==null?void 0:L.timeline)||{},t.gameplay.drag_surface=((z=e.engine.runtime)==null?void 0:z.drag_surface)||{},t.gameplay.background=((D=e.engine.runtime)==null?void 0:D.background)||{},t.gameplay.ui_styles=((B=e.engine.runtime)==null?void 0:B.ui_styles)||{},t.gameplay.label_pulse=((O=e.engine.runtime)==null?void 0:O.label_pulse)||{},t.ui=((R=e.engine.runtime)==null?void 0:R.ui)||{},t.theme=((C=e.engine.runtime)==null?void 0:C.theme)||{},t.assets=e.engine.assets||{},t}var Ad,G,js,Ds,Bs=Ve(()=>{"use strict";Te();Ad=null,G="dev";if(typeof window!="undefined"){let e=window.__BUILD_SETTINGS__;if(e!=null&&e.buildMode)Ad=e,G=e.buildMode,console.log("[CONFIG] Loaded inline build settings:",e,"buildMode:",G);else try{let t=new XMLHttpRequest;if(t.open("GET","./build-settings.json",!1),t.send(),t.status===200&&t.responseText){let i=JSON.parse(t.responseText);Ad=i,G=i.buildMode||"dev",console.log("[CONFIG] Loaded build settings:",i,"buildMode:",G)}else console.log("[CONFIG] No build-settings.json found, using default buildMode:",G)}catch(t){console.log("[CONFIG] Failed to load build-settings.json:",t instanceof Error?t.message:String(t))}}console.log("[CONFIG] Final buildMode:",G);js=new Map,Ds=G==="dev"||typeof window!="undefined"&&window.location.search.includes("hot-reload")});function Fs(e,t){let i=[];function n(r,a,s=""){if(r!==a){if(typeof r!=typeof a){i.push(`${s}: type changed`);return}if(typeof r=="object"&&r!==null&&a!==null){let o=new Set([...Object.keys(r),...Object.keys(a)]);for(let l of o){let c=s?`${s}.${l}`:l;l in r?l in a?n(r[l],a[l],c):i.push(`${c}: removed`):i.push(`${c}: added`)}}else i.push(`${s}: changed`)}}return n(e,t),i}function $s(e,t,i,n){let r={...i};for(let[a,s]of n.entries())r[a]&&s.defaults&&(r[a]={...s.defaults,...r[a]});return r}var bn,Ht,Hs=Ve(()=>{"use strict";bn=class{shouldFullReload(t){return t.type==="component"||t.type==="scene"}getAffectedObjects(t){return t.type==="object"&&t.objectId?[t.objectId]:[]}},Ht=class{constructor(t=1e3){this.pollingInterval=null;this.fileHashes=new Map;this.callbacks=new Map;this.intervalMs=t}watch(t,i){this.callbacks.set(t,i),this.pollingInterval===null&&(this.pollingInterval=window.setInterval(()=>{this.checkAllFiles()},this.intervalMs))}async checkAllFiles(){for(let[t,i]of this.callbacks.entries())try{let n=`${t}?t=${Date.now()}&r=${Math.random()}`,r=await fetch(n,{cache:"no-cache",headers:{"Cache-Control":"no-cache"}});if(r.ok){let a=await r.text(),s=this.hashString(a),o=this.fileHashes.get(t);if(o&&o!==s&&console.log(`[HOT-RELOAD] File changed: ${t}`),o&&o!==s){console.log(`[HOT-RELOAD] File changed: ${t}`);let l=this.determineEventType(t);i(l),this.fileHashes.set(t,s)}else o||this.fileHashes.set(t,s)}}catch(n){console.warn(`Failed to check ${t}:`,n)}}determineEventType(t){var i,n;return t.includes("/components/")?{type:"component",path:t,componentName:(i=t.split("/").pop())==null?void 0:i.replace(".schema.json","")}:t.includes("/engine/")?{type:"engine",path:t}:t.includes("/scenes/")?{type:"scene",path:t}:t.includes("/objects/")?{type:"object",path:t,objectId:(n=t.split("/").pop())==null?void 0:n.replace(".json","")}:{type:"object",path:t}}hashString(t){let i=0;for(let n=0;n<t.length;n++){let r=t.charCodeAt(n);i=(i<<5)-i+r,i=i&i}return i.toString()}unwatch(t){this.callbacks.delete(t),this.fileHashes.delete(t)}stop(){this.pollingInterval!==null&&(clearInterval(this.pollingInterval),this.pollingInterval=null),this.callbacks.clear(),this.fileHashes.clear()}}});function qs(e){if(typeof window=="undefined")return;let t=typeof Us!="undefined"&&!!Us.hot,i=window.location.search.includes("hot-reload");if(!(t||i))return;let r=null,a=!1,s=null;if(i){s=new Ht;let g=window.__configWatcher;g!=null&&g.stop&&g.stop(),window.__configWatcher=s}let o=new Set,l=g=>{var b,y;if(!s)return;let h=new Set;h.add("configs/engine/engine.runtime.json"),h.add("configs/engine/engine.assets.json"),h.add("configs/engine/engine.splash.json"),h.add("configs/scenes/scene.main.json");let m=(y=(b=g.scene)==null?void 0:b.objects)!=null?y:[];for(let v of m)v!=null&&v.object_config&&h.add(`configs/objects/${v.object_config}.json`);for(let v of o)h.has(v)||s.unwatch(v);for(let v of h)o.has(v)||s.watch(v,x=>f(x));o=h},c=new Set,d=!1,u=async g=>{let h=await xt(g),m=$t(h,e.activeConfig.schemas),b=gi(m,e.activeConfig.schemas);b.valid||console.warn(`[HOT-RELOAD] ${g} validation errors:`,b.errors),await e.liveEditBridge.applyObjectConfig(g,m)};async function p(g){if(!a){a=!0;try{if(d||c.size===0){e.audioSystem.destroy();let h=await et("scene.main");e.setActiveConfig(h),e.gameObjectManager.updateConfig(h),e.CustomAssets.updateConfig(h),await e.CustomAssets.ready();let m=e.createAudioSystem(h);e.setAudioSystem(m),window.__audioSystem=m,await m.start(),e.liveEditBridge.rebuildIndexes(),l(h),console.log(`[GAME] Hot-reload complete (${g})`)}else{let h=Array.from(c);c.clear();for(let m of h)await u(m);console.log(`[GAME] Hot-reload updated objects: ${h.join(", ")}`)}}catch(h){console.warn("[GAME] Hot-reload failed:",h)}finally{a=!1,d=!1,c.clear()}}}function f(g){g.type==="object"&&g.objectId?c.add(g.objectId):d=!0,r&&window.clearTimeout(r),r=window.setTimeout(()=>{p(g.type)},120)}t&&Us.hot.on("config-change",()=>{f({type:"hmr"})}),i&&(l(e.activeConfig),console.log(`[GAME] Hot-reload watcher enabled (${o.size} files)`))}var Us,Td=Ve(()=>{"use strict";Hs();Bs();Us={}});var kd={};an(kd,{ConfigWatcher:()=>Ht,DefaultReloadStrategy:()=>bn,applyDefaults:()=>$t,diffConfigs:()=>Fs,loadAllObjectConfigs:()=>Rr,loadComponentSchemas:()=>Pr,loadEngineConfig:()=>jr,loadGamePromptConfig:()=>zs,loadObjectCentricConfig:()=>et,loadObjectConfig:()=>xt,loadSceneConfig:()=>Dr,rehydrateObject:()=>$s,setupHotReload:()=>qs,toLegacyFormat:()=>Ns,validateObjectConfig:()=>gi});var zr=Ve(()=>{"use strict";Bs();Hs();Td()});var yn=k((y1,Ys)=>{"use strict";typeof process=="undefined"||!process.version||process.version.indexOf("v0.")===0||process.version.indexOf("v1.")===0&&process.version.indexOf("v1.8.")!==0?Ys.exports={nextTick:Jm}:Ys.exports=process;function Jm(e,t,i,n){if(typeof e!="function")throw new TypeError('"callback" argument must be a function');var r=arguments.length,a,s;switch(r){case 0:case 1:return process.nextTick(e);case 2:return process.nextTick(function(){e.call(null,t)});case 3:return process.nextTick(function(){e.call(null,t,i)});case 4:return process.nextTick(function(){e.call(null,t,i,n)});default:for(a=new Array(r-1),s=0;s<a.length;)a[s++]=arguments[s];return process.nextTick(function(){e.apply(null,a)})}}});var Od=k((v1,Ld)=>{"use strict";var Qm={}.toString;Ld.exports=Array.isArray||function(e){return Qm.call(e)=="[object Array]"}});var Ks=k((x1,Id)=>{"use strict";Id.exports=require("stream")});var vn=k((Xs,Pd)=>{"use strict";var ea=require("buffer"),tt=ea.Buffer;function Md(e,t){for(var i in e)t[i]=e[i]}tt.from&&tt.alloc&&tt.allocUnsafe&&tt.allocUnsafeSlow?Pd.exports=ea:(Md(ea,Xs),Xs.Buffer=bi);function bi(e,t,i){return tt(e,t,i)}Md(tt,bi);bi.from=function(e,t,i){if(typeof e=="number")throw new TypeError("Argument must not be a number");return tt(e,t,i)};bi.alloc=function(e,t,i){if(typeof e!="number")throw new TypeError("Argument must be a number");var n=tt(e);return t!==void 0?typeof i=="string"?n.fill(t,i):n.fill(t):n.fill(0),n};bi.allocUnsafe=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return tt(e)};bi.allocUnsafeSlow=function(e){if(typeof e!="number")throw new TypeError("Argument must be a number");return ea.SlowBuffer(e)}});var yi=k(oe=>{"use strict";function eb(e){return Array.isArray?Array.isArray(e):ta(e)==="[object Array]"}oe.isArray=eb;function tb(e){return typeof e=="boolean"}oe.isBoolean=tb;function ib(e){return e===null}oe.isNull=ib;function nb(e){return e==null}oe.isNullOrUndefined=nb;function rb(e){return typeof e=="number"}oe.isNumber=rb;function ab(e){return typeof e=="string"}oe.isString=ab;function sb(e){return typeof e=="symbol"}oe.isSymbol=sb;function ob(e){return e===void 0}oe.isUndefined=ob;function lb(e){return ta(e)==="[object RegExp]"}oe.isRegExp=lb;function cb(e){return typeof e=="object"&&e!==null}oe.isObject=cb;function db(e){return ta(e)==="[object Date]"}oe.isDate=db;function ub(e){return ta(e)==="[object Error]"||e instanceof Error}oe.isError=ub;function pb(e){return typeof e=="function"}oe.isFunction=pb;function fb(e){return e===null||typeof e=="boolean"||typeof e=="number"||typeof e=="string"||typeof e=="symbol"||typeof e=="undefined"}oe.isPrimitive=fb;oe.isBuffer=require("buffer").Buffer.isBuffer;function ta(e){return Object.prototype.toString.call(e)}});var Rd=k((_1,Zs)=>{"use strict";typeof Object.create=="function"?Zs.exports=function(t,i){i&&(t.super_=i,t.prototype=Object.create(i.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}))}:Zs.exports=function(t,i){if(i){t.super_=i;var n=function(){};n.prototype=i.prototype,t.prototype=new n,t.prototype.constructor=t}}});var vi=k((E1,Qs)=>{"use strict";try{if(Js=require("util"),typeof Js.inherits!="function")throw"";Qs.exports=Js.inherits}catch{Qs.exports=Rd()}var Js});var Dd=k((S1,eo)=>{"use strict";function hb(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}var jd=vn().Buffer,xn=require("util");function gb(e,t,i){e.copy(t,i)}eo.exports=(function(){function e(){hb(this,e),this.head=null,this.tail=null,this.length=0}return e.prototype.push=function(i){var n={data:i,next:null};this.length>0?this.tail.next=n:this.head=n,this.tail=n,++this.length},e.prototype.unshift=function(i){var n={data:i,next:this.head};this.length===0&&(this.tail=n),this.head=n,++this.length},e.prototype.shift=function(){if(this.length!==0){var i=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,i}},e.prototype.clear=function(){this.head=this.tail=null,this.length=0},e.prototype.join=function(i){if(this.length===0)return"";for(var n=this.head,r=""+n.data;n=n.next;)r+=i+n.data;return r},e.prototype.concat=function(i){if(this.length===0)return jd.alloc(0);for(var n=jd.allocUnsafe(i>>>0),r=this.head,a=0;r;)gb(r.data,n,a),a+=r.data.length,r=r.next;return n},e})();xn&&xn.inspect&&xn.inspect.custom&&(eo.exports.prototype[xn.inspect.custom]=function(){var e=xn.inspect({length:this.length});return this.constructor.name+" "+e})});var to=k((A1,zd)=>{"use strict";var ia=yn();function mb(e,t){var i=this,n=this._readableState&&this._readableState.destroyed,r=this._writableState&&this._writableState.destroyed;return n||r?(t?t(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,ia.nextTick(na,this,e)):ia.nextTick(na,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(a){!t&&a?i._writableState?i._writableState.errorEmitted||(i._writableState.errorEmitted=!0,ia.nextTick(na,i,a)):ia.nextTick(na,i,a):t&&t(a)}),this)}function bb(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function na(e,t){e.emit("error",t)}zd.exports={destroy:mb,undestroy:bb}});var Bd=k((C1,Nd)=>{"use strict";Nd.exports=require("util").deprecate});var no=k((T1,Vd)=>{"use strict";var qt=yn();Vd.exports=Z;function $d(e){var t=this;this.next=null,this.entry=null,this.finish=function(){jb(t,e)}}var yb=!process.browser&&["v0.10","v0.9."].indexOf(process.version.slice(0,5))>-1?setImmediate:qt.nextTick,xi;Z.WritableState=_n;var Hd=Object.create(yi());Hd.inherits=vi();var vb={deprecate:Bd()},Ud=Ks(),aa=vn().Buffer,xb=(typeof global!="undefined"?global:typeof window!="undefined"?window:typeof self!="undefined"?self:{}).Uint8Array||function(){};function wb(e){return aa.from(e)}function _b(e){return aa.isBuffer(e)||e instanceof xb}var qd=to();Hd.inherits(Z,Ud);function Eb(){}function _n(e,t){xi=xi||Gt(),e=e||{};var i=t instanceof xi;this.objectMode=!!e.objectMode,i&&(this.objectMode=this.objectMode||!!e.writableObjectMode);var n=e.highWaterMark,r=e.writableHighWaterMark,a=this.objectMode?16:16*1024;n||n===0?this.highWaterMark=n:i&&(r||r===0)?this.highWaterMark=r:this.highWaterMark=a,this.highWaterMark=Math.floor(this.highWaterMark),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var s=e.decodeStrings===!1;this.decodeStrings=!s,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(o){Ob(t,o)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.bufferedRequestCount=0,this.corkedRequestsFree=new $d(this)}_n.prototype.getBuffer=function(){for(var t=this.bufferedRequest,i=[];t;)i.push(t),t=t.next;return i};(function(){try{Object.defineProperty(_n.prototype,"buffer",{get:vb.deprecate(function(){return this.getBuffer()},"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch{}})();var ra;typeof Symbol=="function"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]=="function"?(ra=Function.prototype[Symbol.hasInstance],Object.defineProperty(Z,Symbol.hasInstance,{value:function(e){return ra.call(this,e)?!0:this!==Z?!1:e&&e._writableState instanceof _n}})):ra=function(e){return e instanceof this};function Z(e){if(xi=xi||Gt(),!ra.call(Z,this)&&!(this instanceof xi))return new Z(e);this._writableState=new _n(e,this),this.writable=!0,e&&(typeof e.write=="function"&&(this._write=e.write),typeof e.writev=="function"&&(this._writev=e.writev),typeof e.destroy=="function"&&(this._destroy=e.destroy),typeof e.final=="function"&&(this._final=e.final)),Ud.call(this)}Z.prototype.pipe=function(){this.emit("error",new Error("Cannot pipe, not readable"))};function Sb(e,t){var i=new Error("write after end");e.emit("error",i),qt.nextTick(t,i)}function Ab(e,t,i,n){var r=!0,a=!1;return i===null?a=new TypeError("May not write null values to stream"):typeof i!="string"&&i!==void 0&&!t.objectMode&&(a=new TypeError("Invalid non-string/buffer chunk")),a&&(e.emit("error",a),qt.nextTick(n,a),r=!1),r}Z.prototype.write=function(e,t,i){var n=this._writableState,r=!1,a=!n.objectMode&&_b(e);return a&&!aa.isBuffer(e)&&(e=wb(e)),typeof t=="function"&&(i=t,t=null),a?t="buffer":t||(t=n.defaultEncoding),typeof i!="function"&&(i=Eb),n.ended?Sb(this,i):(a||Ab(this,n,e,i))&&(n.pendingcb++,r=Tb(this,n,a,e,t,i)),r};Z.prototype.cork=function(){var e=this._writableState;e.corked++};Z.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,!e.writing&&!e.corked&&!e.bufferProcessing&&e.bufferedRequest&&Gd(this,e))};Z.prototype.setDefaultEncoding=function(t){if(typeof t=="string"&&(t=t.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((t+"").toLowerCase())>-1))throw new TypeError("Unknown encoding: "+t);return this._writableState.defaultEncoding=t,this};function Cb(e,t,i){return!e.objectMode&&e.decodeStrings!==!1&&typeof t=="string"&&(t=aa.from(t,i)),t}Object.defineProperty(Z.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function Tb(e,t,i,n,r,a){if(!i){var s=Cb(t,n,r);n!==s&&(i=!0,r="buffer",n=s)}var o=t.objectMode?1:n.length;t.length+=o;var l=t.length<t.highWaterMark;if(l||(t.needDrain=!0),t.writing||t.corked){var c=t.lastBufferedRequest;t.lastBufferedRequest={chunk:n,encoding:r,isBuf:i,callback:a,next:null},c?c.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else io(e,t,!1,o,n,r,a);return l}function io(e,t,i,n,r,a,s){t.writelen=n,t.writecb=s,t.writing=!0,t.sync=!0,i?e._writev(r,t.onwrite):e._write(r,a,t.onwrite),t.sync=!1}function kb(e,t,i,n,r){--t.pendingcb,i?(qt.nextTick(r,n),qt.nextTick(wn,e,t),e._writableState.errorEmitted=!0,e.emit("error",n)):(r(n),e._writableState.errorEmitted=!0,e.emit("error",n),wn(e,t))}function Lb(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}function Ob(e,t){var i=e._writableState,n=i.sync,r=i.writecb;if(Lb(i),t)kb(e,i,n,t,r);else{var a=Wd(i);!a&&!i.corked&&!i.bufferProcessing&&i.bufferedRequest&&Gd(e,i),n?yb(Fd,e,i,a,r):Fd(e,i,a,r)}}function Fd(e,t,i,n){i||Ib(e,t),t.pendingcb--,n(),wn(e,t)}function Ib(e,t){t.length===0&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}function Gd(e,t){t.bufferProcessing=!0;var i=t.bufferedRequest;if(e._writev&&i&&i.next){var n=t.bufferedRequestCount,r=new Array(n),a=t.corkedRequestsFree;a.entry=i;for(var s=0,o=!0;i;)r[s]=i,i.isBuf||(o=!1),i=i.next,s+=1;r.allBuffers=o,io(e,t,!0,t.length,r,"",a.finish),t.pendingcb++,t.lastBufferedRequest=null,a.next?(t.corkedRequestsFree=a.next,a.next=null):t.corkedRequestsFree=new $d(t),t.bufferedRequestCount=0}else{for(;i;){var l=i.chunk,c=i.encoding,d=i.callback,u=t.objectMode?1:l.length;if(io(e,t,!1,u,l,c,d),i=i.next,t.bufferedRequestCount--,t.writing)break}i===null&&(t.lastBufferedRequest=null)}t.bufferedRequest=i,t.bufferProcessing=!1}Z.prototype._write=function(e,t,i){i(new Error("_write() is not implemented"))};Z.prototype._writev=null;Z.prototype.end=function(e,t,i){var n=this._writableState;typeof e=="function"?(i=e,e=null,t=null):typeof t=="function"&&(i=t,t=null),e!=null&&this.write(e,t),n.corked&&(n.corked=1,this.uncork()),n.ending||Rb(this,n,i)};function Wd(e){return e.ending&&e.length===0&&e.bufferedRequest===null&&!e.finished&&!e.writing}function Mb(e,t){e._final(function(i){t.pendingcb--,i&&e.emit("error",i),t.prefinished=!0,e.emit("prefinish"),wn(e,t)})}function Pb(e,t){!t.prefinished&&!t.finalCalled&&(typeof e._final=="function"?(t.pendingcb++,t.finalCalled=!0,qt.nextTick(Mb,e,t)):(t.prefinished=!0,e.emit("prefinish")))}function wn(e,t){var i=Wd(t);return i&&(Pb(e,t),t.pendingcb===0&&(t.finished=!0,e.emit("finish"))),i}function Rb(e,t,i){t.ending=!0,wn(e,t),i&&(t.finished?qt.nextTick(i):e.once("finish",i)),t.ended=!0,e.writable=!1}function jb(e,t,i){var n=e.entry;for(e.entry=null;n;){var r=n.callback;t.pendingcb--,r(i),n=n.next}t.corkedRequestsFree.next=e}Object.defineProperty(Z.prototype,"destroyed",{get:function(){return this._writableState===void 0?!1:this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}});Z.prototype.destroy=qd.destroy;Z.prototype._undestroy=qd.undestroy;Z.prototype._destroy=function(e,t){this.end(),t(e)}});var Gt=k((k1,Zd)=>{"use strict";var Yd=yn(),Db=Object.keys||function(e){var t=[];for(var i in e)t.push(i);return t};Zd.exports=it;var Kd=Object.create(yi());Kd.inherits=vi();var Xd=so(),ao=no();Kd.inherits(it,Xd);for(ro=Db(ao.prototype),sa=0;sa<ro.length;sa++)oa=ro[sa],it.prototype[oa]||(it.prototype[oa]=ao.prototype[oa]);var ro,oa,sa;function it(e){if(!(this instanceof it))return new it(e);Xd.call(this,e),ao.call(this,e),e&&e.readable===!1&&(this.readable=!1),e&&e.writable===!1&&(this.writable=!1),this.allowHalfOpen=!0,e&&e.allowHalfOpen===!1&&(this.allowHalfOpen=!1),this.once("end",zb)}Object.defineProperty(it.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function zb(){this.allowHalfOpen||this._writableState.ended||Yd.nextTick(Nb,this)}function Nb(e){e.end()}Object.defineProperty(it.prototype,"destroyed",{get:function(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set:function(e){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=e,this._writableState.destroyed=e)}});it.prototype._destroy=function(e,t){this.push(null),this.end(),Yd.nextTick(t,e)}});var co=k(Qd=>{"use strict";var lo=vn().Buffer,Jd=lo.isEncoding||function(e){switch(e=""+e,e&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function Bb(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}function Fb(e){var t=Bb(e);if(typeof t!="string"&&(lo.isEncoding===Jd||!Jd(e)))throw new Error("Unknown encoding: "+e);return t||e}Qd.StringDecoder=En;function En(e){this.encoding=Fb(e);var t;switch(this.encoding){case"utf16le":this.text=Wb,this.end=Vb,t=4;break;case"utf8":this.fillLast=Ub,t=4;break;case"base64":this.text=Yb,this.end=Kb,t=3;break;default:this.write=Xb,this.end=Zb;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=lo.allocUnsafe(t)}En.prototype.write=function(e){if(e.length===0)return"";var t,i;if(this.lastNeed){if(t=this.fillLast(e),t===void 0)return"";i=this.lastNeed,this.lastNeed=0}else i=0;return i<e.length?t?t+this.text(e,i):this.text(e,i):t||""};En.prototype.end=Gb;En.prototype.text=qb;En.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length};function oo(e){return e<=127?0:e>>5===6?2:e>>4===14?3:e>>3===30?4:e>>6===2?-1:-2}function $b(e,t,i){var n=t.length-1;if(n<i)return 0;var r=oo(t[n]);return r>=0?(r>0&&(e.lastNeed=r-1),r):--n<i||r===-2?0:(r=oo(t[n]),r>=0?(r>0&&(e.lastNeed=r-2),r):--n<i||r===-2?0:(r=oo(t[n]),r>=0?(r>0&&(r===2?r=0:e.lastNeed=r-3),r):0))}function Hb(e,t,i){if((t[0]&192)!==128)return e.lastNeed=0,"\uFFFD";if(e.lastNeed>1&&t.length>1){if((t[1]&192)!==128)return e.lastNeed=1,"\uFFFD";if(e.lastNeed>2&&t.length>2&&(t[2]&192)!==128)return e.lastNeed=2,"\uFFFD"}}function Ub(e){var t=this.lastTotal-this.lastNeed,i=Hb(this,e,t);if(i!==void 0)return i;if(this.lastNeed<=e.length)return e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,t,0,e.length),this.lastNeed-=e.length}function qb(e,t){var i=$b(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=i;var n=e.length-(i-this.lastNeed);return e.copy(this.lastChar,0,n),e.toString("utf8",t,n)}function Gb(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"\uFFFD":t}function Wb(e,t){if((e.length-t)%2===0){var i=e.toString("utf16le",t);if(i){var n=i.charCodeAt(i.length-1);if(n>=55296&&n<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],i.slice(0,-1)}return i}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function Vb(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var i=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,i)}return t}function Yb(e,t){var i=(e.length-t)%3;return i===0?e.toString("base64",t):(this.lastNeed=3-i,this.lastTotal=3,i===1?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-i))}function Kb(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function Xb(e){return e.toString(this.encoding)}function Zb(e){return e&&e.length?this.write(e):""}});var so=k((I1,uu)=>{"use strict";var _i=yn();uu.exports=q;var Jb=Od(),Sn;q.ReadableState=su;var O1=require("events").EventEmitter,nu=function(e,t){return e.listeners(t).length},go=Ks(),An=vn().Buffer,Qb=(typeof global!="undefined"?global:typeof window!="undefined"?window:typeof self!="undefined"?self:{}).Uint8Array||function(){};function ey(e){return An.from(e)}function ty(e){return An.isBuffer(e)||e instanceof Qb}var ru=Object.create(yi());ru.inherits=vi();var uo=require("util"),$=void 0;uo&&uo.debuglog?$=uo.debuglog("stream"):$=function(){};var iy=Dd(),au=to(),wi;ru.inherits(q,go);var po=["error","close","destroy","pause","resume"];function ny(e,t,i){if(typeof e.prependListener=="function")return e.prependListener(t,i);!e._events||!e._events[t]?e.on(t,i):Jb(e._events[t])?e._events[t].unshift(i):e._events[t]=[i,e._events[t]]}function su(e,t){Sn=Sn||Gt(),e=e||{};var i=t instanceof Sn;this.objectMode=!!e.objectMode,i&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var n=e.highWaterMark,r=e.readableHighWaterMark,a=this.objectMode?16:16*1024;n||n===0?this.highWaterMark=n:i&&(r||r===0)?this.highWaterMark=r:this.highWaterMark=a,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new iy,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(wi||(wi=co().StringDecoder),this.decoder=new wi(e.encoding),this.encoding=e.encoding)}function q(e){if(Sn=Sn||Gt(),!(this instanceof q))return new q(e);this._readableState=new su(e,this),this.readable=!0,e&&(typeof e.read=="function"&&(this._read=e.read),typeof e.destroy=="function"&&(this._destroy=e.destroy)),go.call(this)}Object.defineProperty(q.prototype,"destroyed",{get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}});q.prototype.destroy=au.destroy;q.prototype._undestroy=au.undestroy;q.prototype._destroy=function(e,t){this.push(null),t(e)};q.prototype.push=function(e,t){var i=this._readableState,n;return i.objectMode?n=!0:typeof e=="string"&&(t=t||i.defaultEncoding,t!==i.encoding&&(e=An.from(e,t),t=""),n=!0),ou(this,e,t,!1,n)};q.prototype.unshift=function(e){return ou(this,e,null,!0,!1)};function ou(e,t,i,n,r){var a=e._readableState;if(t===null)a.reading=!1,oy(e,a);else{var s;r||(s=ry(a,t)),s?e.emit("error",s):a.objectMode||t&&t.length>0?(typeof t!="string"&&!a.objectMode&&Object.getPrototypeOf(t)!==An.prototype&&(t=ey(t)),n?a.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):fo(e,a,t,!0):a.ended?e.emit("error",new Error("stream.push() after EOF")):(a.reading=!1,a.decoder&&!i?(t=a.decoder.write(t),a.objectMode||t.length!==0?fo(e,a,t,!1):lu(e,a)):fo(e,a,t,!1))):n||(a.reading=!1)}return ay(a)}function fo(e,t,i,n){t.flowing&&t.length===0&&!t.sync?(e.emit("data",i),e.read(0)):(t.length+=t.objectMode?1:i.length,n?t.buffer.unshift(i):t.buffer.push(i),t.needReadable&&la(e)),lu(e,t)}function ry(e,t){var i;return!ty(t)&&typeof t!="string"&&t!==void 0&&!e.objectMode&&(i=new TypeError("Invalid non-string/buffer chunk")),i}function ay(e){return!e.ended&&(e.needReadable||e.length<e.highWaterMark||e.length===0)}q.prototype.isPaused=function(){return this._readableState.flowing===!1};q.prototype.setEncoding=function(e){return wi||(wi=co().StringDecoder),this._readableState.decoder=new wi(e),this._readableState.encoding=e,this};var eu=8388608;function sy(e){return e>=eu?e=eu:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}function tu(e,t){return e<=0||t.length===0&&t.ended?0:t.objectMode?1:e!==e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=sy(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}q.prototype.read=function(e){$("read",e),e=parseInt(e,10);var t=this._readableState,i=e;if(e!==0&&(t.emittedReadable=!1),e===0&&t.needReadable&&(t.length>=t.highWaterMark||t.ended))return $("read: emitReadable",t.length,t.ended),t.length===0&&t.ended?ho(this):la(this),null;if(e=tu(e,t),e===0&&t.ended)return t.length===0&&ho(this),null;var n=t.needReadable;$("need readable",n),(t.length===0||t.length-e<t.highWaterMark)&&(n=!0,$("length less than watermark",n)),t.ended||t.reading?(n=!1,$("reading or ended",n)):n&&($("do read"),t.reading=!0,t.sync=!0,t.length===0&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=tu(i,t)));var r;return e>0?r=cu(e,t):r=null,r===null?(t.needReadable=!0,e=0):t.length-=e,t.length===0&&(t.ended||(t.needReadable=!0),i!==e&&t.ended&&ho(this)),r!==null&&this.emit("data",r),r};function oy(e,t){if(!t.ended){if(t.decoder){var i=t.decoder.end();i&&i.length&&(t.buffer.push(i),t.length+=t.objectMode?1:i.length)}t.ended=!0,la(e)}}function la(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||($("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?_i.nextTick(iu,e):iu(e))}function iu(e){$("emit readable"),e.emit("readable"),mo(e)}function lu(e,t){t.readingMore||(t.readingMore=!0,_i.nextTick(ly,e,t))}function ly(e,t){for(var i=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length<t.highWaterMark&&($("maybeReadMore read 0"),e.read(0),i!==t.length);)i=t.length;t.readingMore=!1}q.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))};q.prototype.pipe=function(e,t){var i=this,n=this._readableState;switch(n.pipesCount){case 0:n.pipes=e;break;case 1:n.pipes=[n.pipes,e];break;default:n.pipes.push(e);break}n.pipesCount+=1,$("pipe count=%d opts=%j",n.pipesCount,t);var r=(!t||t.end!==!1)&&e!==process.stdout&&e!==process.stderr,a=r?o:m;n.endEmitted?_i.nextTick(a):i.once("end",a),e.on("unpipe",s);function s(b,y){$("onunpipe"),b===i&&y&&y.hasUnpiped===!1&&(y.hasUnpiped=!0,d())}function o(){$("onend"),e.end()}var l=cy(i);e.on("drain",l);var c=!1;function d(){$("cleanup"),e.removeListener("close",g),e.removeListener("finish",h),e.removeListener("drain",l),e.removeListener("error",f),e.removeListener("unpipe",s),i.removeListener("end",o),i.removeListener("end",m),i.removeListener("data",p),c=!0,n.awaitDrain&&(!e._writableState||e._writableState.needDrain)&&l()}var u=!1;i.on("data",p);function p(b){$("ondata"),u=!1;var y=e.write(b);y===!1&&!u&&((n.pipesCount===1&&n.pipes===e||n.pipesCount>1&&du(n.pipes,e)!==-1)&&!c&&($("false write response, pause",n.awaitDrain),n.awaitDrain++,u=!0),i.pause())}function f(b){$("onerror",b),m(),e.removeListener("error",f),nu(e,"error")===0&&e.emit("error",b)}ny(e,"error",f);function g(){e.removeListener("finish",h),m()}e.once("close",g);function h(){$("onfinish"),e.removeListener("close",g),m()}e.once("finish",h);function m(){$("unpipe"),i.unpipe(e)}return e.emit("pipe",i),n.flowing||($("pipe resume"),i.resume()),e};function cy(e){return function(){var t=e._readableState;$("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,t.awaitDrain===0&&nu(e,"data")&&(t.flowing=!0,mo(e))}}q.prototype.unpipe=function(e){var t=this._readableState,i={hasUnpiped:!1};if(t.pipesCount===0)return this;if(t.pipesCount===1)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,i),this);if(!e){var n=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var a=0;a<r;a++)n[a].emit("unpipe",this,{hasUnpiped:!1});return this}var s=du(t.pipes,e);return s===-1?this:(t.pipes.splice(s,1),t.pipesCount-=1,t.pipesCount===1&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,i),this)};q.prototype.on=function(e,t){var i=go.prototype.on.call(this,e,t);if(e==="data")this._readableState.flowing!==!1&&this.resume();else if(e==="readable"){var n=this._readableState;!n.endEmitted&&!n.readableListening&&(n.readableListening=n.needReadable=!0,n.emittedReadable=!1,n.reading?n.length&&la(this):_i.nextTick(dy,this))}return i};q.prototype.addListener=q.prototype.on;function dy(e){$("readable nexttick read 0"),e.read(0)}q.prototype.resume=function(){var e=this._readableState;return e.flowing||($("resume"),e.flowing=!0,uy(this,e)),this};function uy(e,t){t.resumeScheduled||(t.resumeScheduled=!0,_i.nextTick(py,e,t))}function py(e,t){t.reading||($("resume read 0"),e.read(0)),t.resumeScheduled=!1,t.awaitDrain=0,e.emit("resume"),mo(e),t.flowing&&!t.reading&&e.read(0)}q.prototype.pause=function(){return $("call pause flowing=%j",this._readableState.flowing),this._readableState.flowing!==!1&&($("pause"),this._readableState.flowing=!1,this.emit("pause")),this};function mo(e){var t=e._readableState;for($("flow",t.flowing);t.flowing&&e.read()!==null;);}q.prototype.wrap=function(e){var t=this,i=this._readableState,n=!1;e.on("end",function(){if($("wrapped end"),i.decoder&&!i.ended){var s=i.decoder.end();s&&s.length&&t.push(s)}t.push(null)}),e.on("data",function(s){if($("wrapped data"),i.decoder&&(s=i.decoder.write(s)),!(i.objectMode&&s==null)&&!(!i.objectMode&&(!s||!s.length))){var o=t.push(s);o||(n=!0,e.pause())}});for(var r in e)this[r]===void 0&&typeof e[r]=="function"&&(this[r]=(function(s){return function(){return e[s].apply(e,arguments)}})(r));for(var a=0;a<po.length;a++)e.on(po[a],this.emit.bind(this,po[a]));return this._read=function(s){$("wrapped _read",s),n&&(n=!1,e.resume())},this};Object.defineProperty(q.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}});q._fromList=cu;function cu(e,t){if(t.length===0)return null;var i;return t.objectMode?i=t.buffer.shift():!e||e>=t.length?(t.decoder?i=t.buffer.join(""):t.buffer.length===1?i=t.buffer.head.data:i=t.buffer.concat(t.length),t.buffer.clear()):i=fy(e,t.buffer,t.decoder),i}function fy(e,t,i){var n;return e<t.head.data.length?(n=t.head.data.slice(0,e),t.head.data=t.head.data.slice(e)):e===t.head.data.length?n=t.shift():n=i?hy(e,t):gy(e,t),n}function hy(e,t){var i=t.head,n=1,r=i.data;for(e-=r.length;i=i.next;){var a=i.data,s=e>a.length?a.length:e;if(s===a.length?r+=a:r+=a.slice(0,e),e-=s,e===0){s===a.length?(++n,i.next?t.head=i.next:t.head=t.tail=null):(t.head=i,i.data=a.slice(s));break}++n}return t.length-=n,r}function gy(e,t){var i=An.allocUnsafe(e),n=t.head,r=1;for(n.data.copy(i),e-=n.data.length;n=n.next;){var a=n.data,s=e>a.length?a.length:e;if(a.copy(i,i.length-e,0,s),e-=s,e===0){s===a.length?(++r,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=a.slice(s));break}++r}return t.length-=r,i}function ho(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,_i.nextTick(my,t,e))}function my(e,t){!e.endEmitted&&e.length===0&&(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function du(e,t){for(var i=0,n=e.length;i<n;i++)if(e[i]===t)return i;return-1}});var bo=k((M1,hu)=>{"use strict";hu.exports=nt;var ca=Gt(),fu=Object.create(yi());fu.inherits=vi();fu.inherits(nt,ca);function by(e,t){var i=this._transformState;i.transforming=!1;var n=i.writecb;if(!n)return this.emit("error",new Error("write callback called multiple times"));i.writechunk=null,i.writecb=null,t!=null&&this.push(t),n(e);var r=this._readableState;r.reading=!1,(r.needReadable||r.length<r.highWaterMark)&&this._read(r.highWaterMark)}function nt(e){if(!(this instanceof nt))return new nt(e);ca.call(this,e),this._transformState={afterTransform:by.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&(typeof e.transform=="function"&&(this._transform=e.transform),typeof e.flush=="function"&&(this._flush=e.flush)),this.on("prefinish",yy)}function yy(){var e=this;typeof this._flush=="function"?this._flush(function(t,i){pu(e,t,i)}):pu(this,null,null)}nt.prototype.push=function(e,t){return this._transformState.needTransform=!1,ca.prototype.push.call(this,e,t)};nt.prototype._transform=function(e,t,i){throw new Error("_transform() is not implemented")};nt.prototype._write=function(e,t,i){var n=this._transformState;if(n.writecb=i,n.writechunk=e,n.writeencoding=t,!n.transforming){var r=this._readableState;(n.needTransform||r.needReadable||r.length<r.highWaterMark)&&this._read(r.highWaterMark)}};nt.prototype._read=function(e){var t=this._transformState;t.writechunk!==null&&t.writecb&&!t.transforming?(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform)):t.needTransform=!0};nt.prototype._destroy=function(e,t){var i=this;ca.prototype._destroy.call(this,e,function(n){t(n),i.emit("close")})};function pu(e,t,i){if(t)return e.emit("error",t);if(i!=null&&e.push(i),e._writableState.length)throw new Error("Calling transform done when ws.length != 0");if(e._transformState.transforming)throw new Error("Calling transform done when still transforming");return e.push(null)}});var yu=k((P1,bu)=>{"use strict";bu.exports=Cn;var gu=bo(),mu=Object.create(yi());mu.inherits=vi();mu.inherits(Cn,gu);function Cn(e){if(!(this instanceof Cn))return new Cn(e);gu.call(this,e)}Cn.prototype._transform=function(e,t,i){i(null,e)}});var yo=k((re,da)=>{"use strict";var Ne=require("stream");process.env.READABLE_STREAM==="disable"&&Ne?(da.exports=Ne,re=da.exports=Ne.Readable,re.Readable=Ne.Readable,re.Writable=Ne.Writable,re.Duplex=Ne.Duplex,re.Transform=Ne.Transform,re.PassThrough=Ne.PassThrough,re.Stream=Ne):(re=da.exports=so(),re.Stream=Ne||re,re.Readable=re,re.Writable=no(),re.Duplex=Gt(),re.Transform=bo(),re.PassThrough=yu())});var rt=k(he=>{"use strict";he.base64=!0;he.array=!0;he.string=!0;he.arraybuffer=typeof ArrayBuffer!="undefined"&&typeof Uint8Array!="undefined";he.nodebuffer=typeof Buffer!="undefined";he.uint8array=typeof Uint8Array!="undefined";if(typeof ArrayBuffer=="undefined")he.blob=!1;else{vo=new ArrayBuffer(0);try{he.blob=new Blob([vo],{type:"application/zip"}).size===0}catch{try{vu=self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder,xo=new vu,xo.append(vo),he.blob=xo.getBlob("application/zip").size===0}catch{he.blob=!1}}}var vo,vu,xo;try{he.nodestream=!!yo().Readable}catch{he.nodestream=!1}});var _o=k(wo=>{"use strict";var vy=Y(),xy=rt(),Be="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";wo.encode=function(e){for(var t=[],i,n,r,a,s,o,l,c=0,d=e.length,u=d,p=vy.getTypeOf(e)!=="string";c<e.length;)u=d-c,p?(i=e[c++],n=c<d?e[c++]:0,r=c<d?e[c++]:0):(i=e.charCodeAt(c++),n=c<d?e.charCodeAt(c++):0,r=c<d?e.charCodeAt(c++):0),a=i>>2,s=(i&3)<<4|n>>4,o=u>1?(n&15)<<2|r>>6:64,l=u>2?r&63:64,t.push(Be.charAt(a)+Be.charAt(s)+Be.charAt(o)+Be.charAt(l));return t.join("")};wo.decode=function(e){var t,i,n,r,a,s,o,l=0,c=0,d="data:";if(e.substr(0,d.length)===d)throw new Error("Invalid base64 input, it looks like a data url.");e=e.replace(/[^A-Za-z0-9+/=]/g,"");var u=e.length*3/4;if(e.charAt(e.length-1)===Be.charAt(64)&&u--,e.charAt(e.length-2)===Be.charAt(64)&&u--,u%1!==0)throw new Error("Invalid base64 input, bad content length.");var p;for(xy.uint8array?p=new Uint8Array(u|0):p=new Array(u|0);l<e.length;)r=Be.indexOf(e.charAt(l++)),a=Be.indexOf(e.charAt(l++)),s=Be.indexOf(e.charAt(l++)),o=Be.indexOf(e.charAt(l++)),t=r<<2|a>>4,i=(a&15)<<4|s>>2,n=(s&3)<<6|o,p[c++]=t,s!==64&&(p[c++]=i),o!==64&&(p[c++]=n);return p}});var Tn=k((D1,xu)=>{"use strict";xu.exports={isNode:typeof Buffer!="undefined",newBufferFrom:function(e,t){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(e,t);if(typeof e=="number")throw new Error('The "data" argument must not be a number');return new Buffer(e,t)},allocBuffer:function(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t},isBuffer:function(e){return Buffer.isBuffer(e)},isStream:function(e){return e&&typeof e.on=="function"&&typeof e.pause=="function"&&typeof e.resume=="function"}}});var Su=k((z1,Eu)=>{"use strict";var wu=global.MutationObserver||global.WebKitMutationObserver,Ei;process.browser?wu?(Eo=0,_u=new wu(kn),So=global.document.createTextNode(""),_u.observe(So,{characterData:!0}),Ei=function(){So.data=Eo=++Eo%2}):!global.setImmediate&&typeof global.MessageChannel!="undefined"?(Ao=new global.MessageChannel,Ao.port1.onmessage=kn,Ei=function(){Ao.port2.postMessage(0)}):"document"in global&&"onreadystatechange"in global.document.createElement("script")?Ei=function(){var e=global.document.createElement("script");e.onreadystatechange=function(){kn(),e.onreadystatechange=null,e.parentNode.removeChild(e),e=null},global.document.documentElement.appendChild(e)}:Ei=function(){setTimeout(kn,0)}:Ei=function(){process.nextTick(kn)};var Eo,_u,So,Ao,Co,Ln=[];function kn(){Co=!0;for(var e,t,i=Ln.length;i;){for(t=Ln,Ln=[],e=-1;++e<i;)t[e]();i=Ln.length}Co=!1}Eu.exports=wy;function wy(e){Ln.push(e)===1&&!Co&&Ei()}});var Iu=k((N1,Ou)=>{"use strict";var Au=Su();function Si(){}var le={},Cu=["REJECTED"],To=["FULFILLED"],Tu=["PENDING"];process.browser||(On=["UNHANDLED"]);var On;Ou.exports=wt;function wt(e){if(typeof e!="function")throw new TypeError("resolver must be a function");this.state=Tu,this.queue=[],this.outcome=void 0,process.browser||(this.handled=On),e!==Si&&ku(this,e)}wt.prototype.finally=function(e){if(typeof e!="function")return this;var t=this.constructor;return this.then(i,n);function i(r){function a(){return r}return t.resolve(e()).then(a)}function n(r){function a(){throw r}return t.resolve(e()).then(a)}};wt.prototype.catch=function(e){return this.then(null,e)};wt.prototype.then=function(e,t){if(typeof e!="function"&&this.state===To||typeof t!="function"&&this.state===Cu)return this;var i=new this.constructor(Si);if(process.browser||this.handled===On&&(this.handled=null),this.state!==Tu){var n=this.state===To?e:t;ko(i,n,this.outcome)}else this.queue.push(new In(i,e,t));return i};function In(e,t,i){this.promise=e,typeof t=="function"&&(this.onFulfilled=t,this.callFulfilled=this.otherCallFulfilled),typeof i=="function"&&(this.onRejected=i,this.callRejected=this.otherCallRejected)}In.prototype.callFulfilled=function(e){le.resolve(this.promise,e)};In.prototype.otherCallFulfilled=function(e){ko(this.promise,this.onFulfilled,e)};In.prototype.callRejected=function(e){le.reject(this.promise,e)};In.prototype.otherCallRejected=function(e){ko(this.promise,this.onRejected,e)};function ko(e,t,i){Au(function(){var n;try{n=t(i)}catch(r){return le.reject(e,r)}n===e?le.reject(e,new TypeError("Cannot resolve promise with itself")):le.resolve(e,n)})}le.resolve=function(e,t){var i=Lu(_y,t);if(i.status==="error")return le.reject(e,i.value);var n=i.value;if(n)ku(e,n);else{e.state=To,e.outcome=t;for(var r=-1,a=e.queue.length;++r<a;)e.queue[r].callFulfilled(t)}return e};le.reject=function(e,t){e.state=Cu,e.outcome=t,process.browser||e.handled===On&&Au(function(){e.handled===On&&process.emit("unhandledRejection",t,e)});for(var i=-1,n=e.queue.length;++i<n;)e.queue[i].callRejected(t);return e};function _y(e){var t=e&&e.then;if(e&&(typeof e=="object"||typeof e=="function")&&typeof t=="function")return function(){t.apply(e,arguments)}}function ku(e,t){var i=!1;function n(o){i||(i=!0,le.reject(e,o))}function r(o){i||(i=!0,le.resolve(e,o))}function a(){t(r,n)}var s=Lu(a);s.status==="error"&&n(s.value)}function Lu(e,t){var i={};try{i.value=e(t),i.status="success"}catch(n){i.status="error",i.value=n}return i}wt.resolve=Ey;function Ey(e){return e instanceof this?e:le.resolve(new this(Si),e)}wt.reject=Sy;function Sy(e){var t=new this(Si);return le.reject(t,e)}wt.all=Ay;function Ay(e){var t=this;if(Object.prototype.toString.call(e)!=="[object Array]")return this.reject(new TypeError("must be an array"));var i=e.length,n=!1;if(!i)return this.resolve([]);for(var r=new Array(i),a=0,s=-1,o=new this(Si);++s<i;)l(e[s],s);return o;function l(c,d){t.resolve(c).then(u,function(p){n||(n=!0,le.reject(o,p))});function u(p){r[d]=p,++a===i&&!n&&(n=!0,le.resolve(o,r))}}}wt.race=Cy;function Cy(e){var t=this;if(Object.prototype.toString.call(e)!=="[object Array]")return this.reject(new TypeError("must be an array"));var i=e.length,n=!1;if(!i)return this.resolve([]);for(var r=-1,a=new this(Si);++r<i;)s(e[r]);return a;function s(o){t.resolve(o).then(function(l){n||(n=!0,le.resolve(a,l))},function(l){n||(n=!0,le.reject(a,l))})}}});var Ai=k((B1,Mu)=>{"use strict";var Lo=null;typeof Promise!="undefined"?Lo=Promise:Lo=Iu();Mu.exports={Promise:Lo}});var Ru=k(Pu=>{"use strict";(function(e,t){"use strict";if(e.setImmediate)return;var i=1,n={},r=!1,a=e.document,s;function o(y){typeof y!="function"&&(y=new Function(""+y));for(var v=new Array(arguments.length-1),x=0;x<v.length;x++)v[x]=arguments[x+1];var w={callback:y,args:v};return n[i]=w,s(i),i++}function l(y){delete n[y]}function c(y){var v=y.callback,x=y.args;switch(x.length){case 0:v();break;case 1:v(x[0]);break;case 2:v(x[0],x[1]);break;case 3:v(x[0],x[1],x[2]);break;default:v.apply(t,x);break}}function d(y){if(r)setTimeout(d,0,y);else{var v=n[y];if(v){r=!0;try{c(v)}finally{l(y),r=!1}}}}function u(){s=function(y){process.nextTick(function(){d(y)})}}function p(){if(e.postMessage&&!e.importScripts){var y=!0,v=e.onmessage;return e.onmessage=function(){y=!1},e.postMessage("","*"),e.onmessage=v,y}}function f(){var y="setImmediate$"+Math.random()+"$",v=function(x){x.source===e&&typeof x.data=="string"&&x.data.indexOf(y)===0&&d(+x.data.slice(y.length))};e.addEventListener?e.addEventListener("message",v,!1):e.attachEvent("onmessage",v),s=function(x){e.postMessage(y+x,"*")}}function g(){var y=new MessageChannel;y.port1.onmessage=function(v){var x=v.data;d(x)},s=function(v){y.port2.postMessage(v)}}function h(){var y=a.documentElement;s=function(v){var x=a.createElement("script");x.onreadystatechange=function(){d(v),x.onreadystatechange=null,y.removeChild(x),x=null},y.appendChild(x)}}function m(){s=function(y){setTimeout(d,0,y)}}var b=Object.getPrototypeOf&&Object.getPrototypeOf(e);b=b&&b.setTimeout?b:e,{}.toString.call(e.process)==="[object process]"?u():p()?f():e.MessageChannel?g():a&&"onreadystatechange"in a.createElement("script")?h():m(),b.setImmediate=o,b.clearImmediate=l})(typeof self=="undefined"?typeof global=="undefined"?Pu:global:self)});var Y=k(J=>{"use strict";var _t=rt(),Ty=_o(),Ci=Tn(),Oo=Ai();Ru();function ky(e){var t=null;return _t.uint8array?t=new Uint8Array(e.length):t=new Array(e.length),pa(e,t)}J.newBlob=function(e,t){J.checkSupport("blob");try{return new Blob([e],{type:t})}catch{try{var i=self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder,n=new i;return n.append(e),n.getBlob(t)}catch{throw new Error("Bug : can't construct the Blob.")}}};function Mn(e){return e}function pa(e,t){for(var i=0;i<e.length;++i)t[i]=e.charCodeAt(i)&255;return t}var ua={stringifyByChunk:function(e,t,i){var n=[],r=0,a=e.length;if(a<=i)return String.fromCharCode.apply(null,e);for(;r<a;)t==="array"||t==="nodebuffer"?n.push(String.fromCharCode.apply(null,e.slice(r,Math.min(r+i,a)))):n.push(String.fromCharCode.apply(null,e.subarray(r,Math.min(r+i,a)))),r+=i;return n.join("")},stringifyByChar:function(e){for(var t="",i=0;i<e.length;i++)t+=String.fromCharCode(e[i]);return t},applyCanBeUsed:{uint8array:(function(){try{return _t.uint8array&&String.fromCharCode.apply(null,new Uint8Array(1)).length===1}catch{return!1}})(),nodebuffer:(function(){try{return _t.nodebuffer&&String.fromCharCode.apply(null,Ci.allocBuffer(1)).length===1}catch{return!1}})()}};function Pn(e){var t=65536,i=J.getTypeOf(e),n=!0;if(i==="uint8array"?n=ua.applyCanBeUsed.uint8array:i==="nodebuffer"&&(n=ua.applyCanBeUsed.nodebuffer),n)for(;t>1;)try{return ua.stringifyByChunk(e,i,t)}catch{t=Math.floor(t/2)}return ua.stringifyByChar(e)}J.applyFromCharCode=Pn;function fa(e,t){for(var i=0;i<e.length;i++)t[i]=e[i];return t}var Et={};Et.string={string:Mn,array:function(e){return pa(e,new Array(e.length))},arraybuffer:function(e){return Et.string.uint8array(e).buffer},uint8array:function(e){return pa(e,new Uint8Array(e.length))},nodebuffer:function(e){return pa(e,Ci.allocBuffer(e.length))}};Et.array={string:Pn,array:Mn,arraybuffer:function(e){return new Uint8Array(e).buffer},uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return Ci.newBufferFrom(e)}};Et.arraybuffer={string:function(e){return Pn(new Uint8Array(e))},array:function(e){return fa(new Uint8Array(e),new Array(e.byteLength))},arraybuffer:Mn,uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return Ci.newBufferFrom(new Uint8Array(e))}};Et.uint8array={string:Pn,array:function(e){return fa(e,new Array(e.length))},arraybuffer:function(e){return e.buffer},uint8array:Mn,nodebuffer:function(e){return Ci.newBufferFrom(e)}};Et.nodebuffer={string:Pn,array:function(e){return fa(e,new Array(e.length))},arraybuffer:function(e){return Et.nodebuffer.uint8array(e).buffer},uint8array:function(e){return fa(e,new Uint8Array(e.length))},nodebuffer:Mn};J.transformTo=function(e,t){if(t||(t=""),!e)return t;J.checkSupport(e);var i=J.getTypeOf(t),n=Et[i][e](t);return n};J.resolve=function(e){for(var t=e.split("/"),i=[],n=0;n<t.length;n++){var r=t[n];r==="."||r===""&&n!==0&&n!==t.length-1||(r===".."?i.pop():i.push(r))}return i.join("/")};J.getTypeOf=function(e){if(typeof e=="string")return"string";if(Object.prototype.toString.call(e)==="[object Array]")return"array";if(_t.nodebuffer&&Ci.isBuffer(e))return"nodebuffer";if(_t.uint8array&&e instanceof Uint8Array)return"uint8array";if(_t.arraybuffer&&e instanceof ArrayBuffer)return"arraybuffer"};J.checkSupport=function(e){var t=_t[e.toLowerCase()];if(!t)throw new Error(e+" is not supported by this platform")};J.MAX_VALUE_16BITS=65535;J.MAX_VALUE_32BITS=-1;J.pretty=function(e){var t="",i,n;for(n=0;n<(e||"").length;n++)i=e.charCodeAt(n),t+="\\x"+(i<16?"0":"")+i.toString(16).toUpperCase();return t};J.delay=function(e,t,i){setImmediate(function(){e.apply(i||null,t||[])})};J.inherits=function(e,t){var i=function(){};i.prototype=t.prototype,e.prototype=new i};J.extend=function(){var e={},t,i;for(t=0;t<arguments.length;t++)for(i in arguments[t])Object.prototype.hasOwnProperty.call(arguments[t],i)&&typeof e[i]=="undefined"&&(e[i]=arguments[t][i]);return e};J.prepareContent=function(e,t,i,n,r){var a=Oo.Promise.resolve(t).then(function(s){var o=_t.blob&&(s instanceof Blob||["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(s))!==-1);return o&&typeof FileReader!="undefined"?new Oo.Promise(function(l,c){var d=new FileReader;d.onload=function(u){l(u.target.result)},d.onerror=function(u){c(u.target.error)},d.readAsArrayBuffer(s)}):s});return a.then(function(s){var o=J.getTypeOf(s);return o?(o==="arraybuffer"?s=J.transformTo("uint8array",s):o==="string"&&(r?s=Ty.decode(s):i&&n!==!0&&(s=ky(s))),s):Oo.Promise.reject(new Error("Can't read the data of '"+e+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}});var ge=k((H1,Du)=>{"use strict";function ju(e){this.name=e||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}ju.prototype={push:function(e){this.emit("data",e)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(e){this.emit("error",e)}return!0},error:function(e){return this.isFinished?!1:(this.isPaused?this.generatedError=e:(this.isFinished=!0,this.emit("error",e),this.previous&&this.previous.error(e),this.cleanUp()),!0)},on:function(e,t){return this._listeners[e].push(t),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(e,t){if(this._listeners[e])for(var i=0;i<this._listeners[e].length;i++)this._listeners[e][i].call(this,t)},pipe:function(e){return e.registerPrevious(this)},registerPrevious:function(e){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=e.streamInfo,this.mergeStreamInfo(),this.previous=e;var t=this;return e.on("data",function(i){t.processChunk(i)}),e.on("end",function(){t.end()}),e.on("error",function(i){t.error(i)}),this},pause:function(){return this.isPaused||this.isFinished?!1:(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;this.isPaused=!1;var e=!1;return this.generatedError&&(this.error(this.generatedError),e=!0),this.previous&&this.previous.resume(),!e},flush:function(){},processChunk:function(e){this.push(e)},withStreamInfo:function(e,t){return this.extraStreamInfo[e]=t,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var e in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,e)&&(this.streamInfo[e]=this.extraStreamInfo[e])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var e="Worker "+this.name;return this.previous?this.previous+" -> "+e:e}};Du.exports=ju});var ki=k(St=>{"use strict";var Ti=Y(),Wt=rt(),Ly=Tn(),ha=ge(),Rn=new Array(256);for(at=0;at<256;at++)Rn[at]=at>=252?6:at>=248?5:at>=240?4:at>=224?3:at>=192?2:1;var at;Rn[254]=Rn[254]=1;var Oy=function(e){var t,i,n,r,a,s=e.length,o=0;for(r=0;r<s;r++)i=e.charCodeAt(r),(i&64512)===55296&&r+1<s&&(n=e.charCodeAt(r+1),(n&64512)===56320&&(i=65536+(i-55296<<10)+(n-56320),r++)),o+=i<128?1:i<2048?2:i<65536?3:4;for(Wt.uint8array?t=new Uint8Array(o):t=new Array(o),a=0,r=0;a<o;r++)i=e.charCodeAt(r),(i&64512)===55296&&r+1<s&&(n=e.charCodeAt(r+1),(n&64512)===56320&&(i=65536+(i-55296<<10)+(n-56320),r++)),i<128?t[a++]=i:i<2048?(t[a++]=192|i>>>6,t[a++]=128|i&63):i<65536?(t[a++]=224|i>>>12,t[a++]=128|i>>>6&63,t[a++]=128|i&63):(t[a++]=240|i>>>18,t[a++]=128|i>>>12&63,t[a++]=128|i>>>6&63,t[a++]=128|i&63);return t},Iy=function(e,t){var i;for(t=t||e.length,t>e.length&&(t=e.length),i=t-1;i>=0&&(e[i]&192)===128;)i--;return i<0||i===0?t:i+Rn[e[i]]>t?i:t},My=function(e){var t,i,n,r,a=e.length,s=new Array(a*2);for(i=0,t=0;t<a;){if(n=e[t++],n<128){s[i++]=n;continue}if(r=Rn[n],r>4){s[i++]=65533,t+=r-1;continue}for(n&=r===2?31:r===3?15:7;r>1&&t<a;)n=n<<6|e[t++]&63,r--;if(r>1){s[i++]=65533;continue}n<65536?s[i++]=n:(n-=65536,s[i++]=55296|n>>10&1023,s[i++]=56320|n&1023)}return s.length!==i&&(s.subarray?s=s.subarray(0,i):s.length=i),Ti.applyFromCharCode(s)};St.utf8encode=function(t){return Wt.nodebuffer?Ly.newBufferFrom(t,"utf-8"):Oy(t)};St.utf8decode=function(t){return Wt.nodebuffer?Ti.transformTo("nodebuffer",t).toString("utf-8"):(t=Ti.transformTo(Wt.uint8array?"uint8array":"array",t),My(t))};function ga(){ha.call(this,"utf-8 decode"),this.leftOver=null}Ti.inherits(ga,ha);ga.prototype.processChunk=function(e){var t=Ti.transformTo(Wt.uint8array?"uint8array":"array",e.data);if(this.leftOver&&this.leftOver.length){if(Wt.uint8array){var i=t;t=new Uint8Array(i.length+this.leftOver.length),t.set(this.leftOver,0),t.set(i,this.leftOver.length)}else t=this.leftOver.concat(t);this.leftOver=null}var n=Iy(t),r=t;n!==t.length&&(Wt.uint8array?(r=t.subarray(0,n),this.leftOver=t.subarray(n,t.length)):(r=t.slice(0,n),this.leftOver=t.slice(n,t.length))),this.push({data:St.utf8decode(r),meta:e.meta})};ga.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:St.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)};St.Utf8DecodeWorker=ga;function Io(){ha.call(this,"utf-8 encode")}Ti.inherits(Io,ha);Io.prototype.processChunk=function(e){this.push({data:St.utf8encode(e.data),meta:e.meta})};St.Utf8EncodeWorker=Io});var Fu=k((q1,Bu)=>{"use strict";var zu=ge(),Nu=Y();function Mo(e){zu.call(this,"ConvertWorker to "+e),this.destType=e}Nu.inherits(Mo,zu);Mo.prototype.processChunk=function(e){this.push({data:Nu.transformTo(this.destType,e.data),meta:e.meta})};Bu.exports=Mo});var Uu=k((G1,Hu)=>{"use strict";var $u=yo().Readable,Py=Y();Py.inherits(Po,$u);function Po(e,t,i){$u.call(this,t),this._helper=e;var n=this;e.on("data",function(r,a){n.push(r)||n._helper.pause(),i&&i(a)}).on("error",function(r){n.emit("error",r)}).on("end",function(){n.push(null)})}Po.prototype._read=function(){this._helper.resume()};Hu.exports=Po});var Ro=k((W1,Wu)=>{"use strict";var Vt=Y(),Ry=Fu(),jy=ge(),Dy=_o(),zy=rt(),Ny=Ai(),qu=null;if(zy.nodestream)try{qu=Uu()}catch{}function By(e,t,i){switch(e){case"blob":return Vt.newBlob(Vt.transformTo("arraybuffer",t),i);case"base64":return Dy.encode(t);default:return Vt.transformTo(e,t)}}function Fy(e,t){var i,n=0,r=null,a=0;for(i=0;i<t.length;i++)a+=t[i].length;switch(e){case"string":return t.join("");case"array":return Array.prototype.concat.apply([],t);case"uint8array":for(r=new Uint8Array(a),i=0;i<t.length;i++)r.set(t[i],n),n+=t[i].length;return r;case"nodebuffer":return Buffer.concat(t);default:throw new Error("concat : unsupported type '"+e+"'")}}function $y(e,t){return new Ny.Promise(function(i,n){var r=[],a=e._internalType,s=e._outputType,o=e._mimeType;e.on("data",function(l,c){r.push(l),t&&t(c)}).on("error",function(l){r=[],n(l)}).on("end",function(){try{var l=By(s,Fy(a,r),o);i(l)}catch(c){n(c)}r=[]}).resume()})}function Gu(e,t,i){var n=t;switch(t){case"blob":case"arraybuffer":n="uint8array";break;case"base64":n="string";break}try{this._internalType=n,this._outputType=t,this._mimeType=i,Vt.checkSupport(n),this._worker=e.pipe(new Ry(n)),e.lock()}catch(r){this._worker=new jy("error"),this._worker.error(r)}}Gu.prototype={accumulate:function(e){return $y(this,e)},on:function(e,t){var i=this;return e==="data"?this._worker.on(e,function(n){t.call(i,n.data,n.meta)}):this._worker.on(e,function(){Vt.delay(t,arguments,i)}),this},resume:function(){return Vt.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(e){if(Vt.checkSupport("nodestream"),this._outputType!=="nodebuffer")throw new Error(this._outputType+" is not supported by this method");return new qu(this,{objectMode:this._outputType!=="nodebuffer"},e)}};Wu.exports=Gu});var jo=k(ke=>{"use strict";ke.base64=!1;ke.binary=!1;ke.dir=!1;ke.createFolders=!0;ke.date=null;ke.compression=null;ke.compressionOptions=null;ke.comment=null;ke.unixPermissions=null;ke.dosPermissions=null});var Do=k((Y1,Vu)=>{"use strict";var ma=Y(),ba=ge(),Hy=16*1024;function Li(e){ba.call(this,"DataWorker");var t=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,e.then(function(i){t.dataIsReady=!0,t.data=i,t.max=i&&i.length||0,t.type=ma.getTypeOf(i),t.isPaused||t._tickAndRepeat()},function(i){t.error(i)})}ma.inherits(Li,ba);Li.prototype.cleanUp=function(){ba.prototype.cleanUp.call(this),this.data=null};Li.prototype.resume=function(){return ba.prototype.resume.call(this)?(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,ma.delay(this._tickAndRepeat,[],this)),!0):!1};Li.prototype._tickAndRepeat=function(){this._tickScheduled=!1,!(this.isPaused||this.isFinished)&&(this._tick(),this.isFinished||(ma.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))};Li.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var e=Hy,t=null,i=Math.min(this.max,this.index+e);if(this.index>=this.max)return this.end();switch(this.type){case"string":t=this.data.substring(this.index,i);break;case"uint8array":t=this.data.subarray(this.index,i);break;case"array":case"nodebuffer":t=this.data.slice(this.index,i);break}return this.index=i,this.push({data:t,meta:{percent:this.max?this.index/this.max*100:0}})};Vu.exports=Li});var ya=k((K1,Ku)=>{"use strict";var Uy=Y();function qy(){for(var e,t=[],i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=e&1?3988292384^e>>>1:e>>>1;t[i]=e}return t}var Yu=qy();function Gy(e,t,i,n){var r=Yu,a=n+i;e=e^-1;for(var s=n;s<a;s++)e=e>>>8^r[(e^t[s])&255];return e^-1}function Wy(e,t,i,n){var r=Yu,a=n+i;e=e^-1;for(var s=n;s<a;s++)e=e>>>8^r[(e^t.charCodeAt(s))&255];return e^-1}Ku.exports=function(t,i){if(typeof t=="undefined"||!t.length)return 0;var n=Uy.getTypeOf(t)!=="string";return n?Gy(i|0,t,t.length,0):Wy(i|0,t,t.length,0)}});var No=k((X1,Zu)=>{"use strict";var Xu=ge(),Vy=ya(),Yy=Y();function zo(){Xu.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}Yy.inherits(zo,Xu);zo.prototype.processChunk=function(e){this.streamInfo.crc32=Vy(e.data,this.streamInfo.crc32||0),this.push(e)};Zu.exports=zo});var Qu=k((Z1,Ju)=>{"use strict";var Ky=Y(),Bo=ge();function Fo(e){Bo.call(this,"DataLengthProbe for "+e),this.propName=e,this.withStreamInfo(e,0)}Ky.inherits(Fo,Bo);Fo.prototype.processChunk=function(e){if(e){var t=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=t+e.data.length}Bo.prototype.processChunk.call(this,e)};Ju.exports=Fo});var va=k((J1,ip)=>{"use strict";var ep=Ai(),tp=Do(),Xy=No(),$o=Qu();function Ho(e,t,i,n,r){this.compressedSize=e,this.uncompressedSize=t,this.crc32=i,this.compression=n,this.compressedContent=r}Ho.prototype={getContentWorker:function(){var e=new tp(ep.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new $o("data_length")),t=this;return e.on("end",function(){if(this.streamInfo.data_length!==t.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),e},getCompressedWorker:function(){return new tp(ep.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}};Ho.createWorkerFrom=function(e,t,i){return e.pipe(new Xy).pipe(new $o("uncompressedSize")).pipe(t.compressWorker(i)).pipe(new $o("compressedSize")).withStreamInfo("compression",t)};ip.exports=Ho});var sp=k((Q1,ap)=>{"use strict";var Zy=Ro(),Jy=Do(),Uo=ki(),qo=va(),np=ge(),Go=function(e,t,i){this.name=e,this.dir=i.dir,this.date=i.date,this.comment=i.comment,this.unixPermissions=i.unixPermissions,this.dosPermissions=i.dosPermissions,this._data=t,this._dataBinary=i.binary,this.options={compression:i.compression,compressionOptions:i.compressionOptions}};Go.prototype={internalStream:function(e){var t=null,i="string";try{if(!e)throw new Error("No output type specified.");i=e.toLowerCase();var n=i==="string"||i==="text";(i==="binarystring"||i==="text")&&(i="string"),t=this._decompressWorker();var r=!this._dataBinary;r&&!n&&(t=t.pipe(new Uo.Utf8EncodeWorker)),!r&&n&&(t=t.pipe(new Uo.Utf8DecodeWorker))}catch(a){t=new np("error"),t.error(a)}return new Zy(t,i,"")},async:function(e,t){return this.internalStream(e).accumulate(t)},nodeStream:function(e,t){return this.internalStream(e||"nodebuffer").toNodejsStream(t)},_compressWorker:function(e,t){if(this._data instanceof qo&&this._data.compression.magic===e.magic)return this._data.getCompressedWorker();var i=this._decompressWorker();return this._dataBinary||(i=i.pipe(new Uo.Utf8EncodeWorker)),qo.createWorkerFrom(i,e,t)},_decompressWorker:function(){return this._data instanceof qo?this._data.getContentWorker():this._data instanceof np?this._data:new Jy(this._data)}};var rp=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],Qy=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")};for(xa=0;xa<rp.length;xa++)Go.prototype[rp[xa]]=Qy;var xa;ap.exports=Go});var st=k(ue=>{"use strict";var ev=typeof Uint8Array!="undefined"&&typeof Uint16Array!="undefined"&&typeof Int32Array!="undefined";function tv(e,t){return Object.prototype.hasOwnProperty.call(e,t)}ue.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var i=t.shift();if(i){if(typeof i!="object")throw new TypeError(i+"must be non-object");for(var n in i)tv(i,n)&&(e[n]=i[n])}}return e};ue.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var iv={arraySet:function(e,t,i,n,r){if(t.subarray&&e.subarray){e.set(t.subarray(i,i+n),r);return}for(var a=0;a<n;a++)e[r+a]=t[i+a]},flattenChunks:function(e){var t,i,n,r,a,s;for(n=0,t=0,i=e.length;t<i;t++)n+=e[t].length;for(s=new Uint8Array(n),r=0,t=0,i=e.length;t<i;t++)a=e[t],s.set(a,r),r+=a.length;return s}},nv={arraySet:function(e,t,i,n,r){for(var a=0;a<n;a++)e[r+a]=t[i+a]},flattenChunks:function(e){return[].concat.apply([],e)}};ue.setTyped=function(e){e?(ue.Buf8=Uint8Array,ue.Buf16=Uint16Array,ue.Buf32=Int32Array,ue.assign(ue,iv)):(ue.Buf8=Array,ue.Buf16=Array,ue.Buf32=Array,ue.assign(ue,nv))};ue.setTyped(ev)});var Lp=k(Mi=>{"use strict";var rv=st(),av=4,op=0,lp=1,sv=2;function Ii(e){for(var t=e.length;--t>=0;)e[t]=0}var ov=0,hp=1,lv=2,cv=3,dv=258,Jo=29,Fn=256,Dn=Fn+1+Jo,Oi=30,Qo=19,gp=2*Dn+1,Yt=15,Wo=16,uv=7,el=256,mp=16,bp=17,yp=18,Xo=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],wa=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],pv=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],vp=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],fv=512,ot=new Array((Dn+2)*2);Ii(ot);var jn=new Array(Oi*2);Ii(jn);var zn=new Array(fv);Ii(zn);var Nn=new Array(dv-cv+1);Ii(Nn);var tl=new Array(Jo);Ii(tl);var _a=new Array(Oi);Ii(_a);function Vo(e,t,i,n,r){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=n,this.max_length=r,this.has_stree=e&&e.length}var xp,wp,_p;function Yo(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function Ep(e){return e<256?zn[e]:zn[256+(e>>>7)]}function Bn(e,t){e.pending_buf[e.pending++]=t&255,e.pending_buf[e.pending++]=t>>>8&255}function fe(e,t,i){e.bi_valid>Wo-i?(e.bi_buf|=t<<e.bi_valid&65535,Bn(e,e.bi_buf),e.bi_buf=t>>Wo-e.bi_valid,e.bi_valid+=i-Wo):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=i)}function Fe(e,t,i){fe(e,i[t*2],i[t*2+1])}function Sp(e,t){var i=0;do i|=e&1,e>>>=1,i<<=1;while(--t>0);return i>>>1}function hv(e){e.bi_valid===16?(Bn(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=e.bi_buf&255,e.bi_buf>>=8,e.bi_valid-=8)}function gv(e,t){var i=t.dyn_tree,n=t.max_code,r=t.stat_desc.static_tree,a=t.stat_desc.has_stree,s=t.stat_desc.extra_bits,o=t.stat_desc.extra_base,l=t.stat_desc.max_length,c,d,u,p,f,g,h=0;for(p=0;p<=Yt;p++)e.bl_count[p]=0;for(i[e.heap[e.heap_max]*2+1]=0,c=e.heap_max+1;c<gp;c++)d=e.heap[c],p=i[i[d*2+1]*2+1]+1,p>l&&(p=l,h++),i[d*2+1]=p,!(d>n)&&(e.bl_count[p]++,f=0,d>=o&&(f=s[d-o]),g=i[d*2],e.opt_len+=g*(p+f),a&&(e.static_len+=g*(r[d*2+1]+f)));if(h!==0){do{for(p=l-1;e.bl_count[p]===0;)p--;e.bl_count[p]--,e.bl_count[p+1]+=2,e.bl_count[l]--,h-=2}while(h>0);for(p=l;p!==0;p--)for(d=e.bl_count[p];d!==0;)u=e.heap[--c],!(u>n)&&(i[u*2+1]!==p&&(e.opt_len+=(p-i[u*2+1])*i[u*2],i[u*2+1]=p),d--)}}function Ap(e,t,i){var n=new Array(Yt+1),r=0,a,s;for(a=1;a<=Yt;a++)n[a]=r=r+i[a-1]<<1;for(s=0;s<=t;s++){var o=e[s*2+1];o!==0&&(e[s*2]=Sp(n[o]++,o))}}function mv(){var e,t,i,n,r,a=new Array(Yt+1);for(i=0,n=0;n<Jo-1;n++)for(tl[n]=i,e=0;e<1<<Xo[n];e++)Nn[i++]=n;for(Nn[i-1]=n,r=0,n=0;n<16;n++)for(_a[n]=r,e=0;e<1<<wa[n];e++)zn[r++]=n;for(r>>=7;n<Oi;n++)for(_a[n]=r<<7,e=0;e<1<<wa[n]-7;e++)zn[256+r++]=n;for(t=0;t<=Yt;t++)a[t]=0;for(e=0;e<=143;)ot[e*2+1]=8,e++,a[8]++;for(;e<=255;)ot[e*2+1]=9,e++,a[9]++;for(;e<=279;)ot[e*2+1]=7,e++,a[7]++;for(;e<=287;)ot[e*2+1]=8,e++,a[8]++;for(Ap(ot,Dn+1,a),e=0;e<Oi;e++)jn[e*2+1]=5,jn[e*2]=Sp(e,5);xp=new Vo(ot,Xo,Fn+1,Dn,Yt),wp=new Vo(jn,wa,0,Oi,Yt),_p=new Vo(new Array(0),pv,0,Qo,uv)}function Cp(e){var t;for(t=0;t<Dn;t++)e.dyn_ltree[t*2]=0;for(t=0;t<Oi;t++)e.dyn_dtree[t*2]=0;for(t=0;t<Qo;t++)e.bl_tree[t*2]=0;e.dyn_ltree[el*2]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function Tp(e){e.bi_valid>8?Bn(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function bv(e,t,i,n){Tp(e),n&&(Bn(e,i),Bn(e,~i)),rv.arraySet(e.pending_buf,e.window,t,i,e.pending),e.pending+=i}function cp(e,t,i,n){var r=t*2,a=i*2;return e[r]<e[a]||e[r]===e[a]&&n[t]<=n[i]}function Ko(e,t,i){for(var n=e.heap[i],r=i<<1;r<=e.heap_len&&(r<e.heap_len&&cp(t,e.heap[r+1],e.heap[r],e.depth)&&r++,!cp(t,n,e.heap[r],e.depth));)e.heap[i]=e.heap[r],i=r,r<<=1;e.heap[i]=n}function dp(e,t,i){var n,r,a=0,s,o;if(e.last_lit!==0)do n=e.pending_buf[e.d_buf+a*2]<<8|e.pending_buf[e.d_buf+a*2+1],r=e.pending_buf[e.l_buf+a],a++,n===0?Fe(e,r,t):(s=Nn[r],Fe(e,s+Fn+1,t),o=Xo[s],o!==0&&(r-=tl[s],fe(e,r,o)),n--,s=Ep(n),Fe(e,s,i),o=wa[s],o!==0&&(n-=_a[s],fe(e,n,o)));while(a<e.last_lit);Fe(e,el,t)}function Zo(e,t){var i=t.dyn_tree,n=t.stat_desc.static_tree,r=t.stat_desc.has_stree,a=t.stat_desc.elems,s,o,l=-1,c;for(e.heap_len=0,e.heap_max=gp,s=0;s<a;s++)i[s*2]!==0?(e.heap[++e.heap_len]=l=s,e.depth[s]=0):i[s*2+1]=0;for(;e.heap_len<2;)c=e.heap[++e.heap_len]=l<2?++l:0,i[c*2]=1,e.depth[c]=0,e.opt_len--,r&&(e.static_len-=n[c*2+1]);for(t.max_code=l,s=e.heap_len>>1;s>=1;s--)Ko(e,i,s);c=a;do s=e.heap[1],e.heap[1]=e.heap[e.heap_len--],Ko(e,i,1),o=e.heap[1],e.heap[--e.heap_max]=s,e.heap[--e.heap_max]=o,i[c*2]=i[s*2]+i[o*2],e.depth[c]=(e.depth[s]>=e.depth[o]?e.depth[s]:e.depth[o])+1,i[s*2+1]=i[o*2+1]=c,e.heap[1]=c++,Ko(e,i,1);while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],gv(e,t),Ap(i,l,e.bl_count)}function up(e,t,i){var n,r=-1,a,s=t[1],o=0,l=7,c=4;for(s===0&&(l=138,c=3),t[(i+1)*2+1]=65535,n=0;n<=i;n++)a=s,s=t[(n+1)*2+1],!(++o<l&&a===s)&&(o<c?e.bl_tree[a*2]+=o:a!==0?(a!==r&&e.bl_tree[a*2]++,e.bl_tree[mp*2]++):o<=10?e.bl_tree[bp*2]++:e.bl_tree[yp*2]++,o=0,r=a,s===0?(l=138,c=3):a===s?(l=6,c=3):(l=7,c=4))}function pp(e,t,i){var n,r=-1,a,s=t[1],o=0,l=7,c=4;for(s===0&&(l=138,c=3),n=0;n<=i;n++)if(a=s,s=t[(n+1)*2+1],!(++o<l&&a===s)){if(o<c)do Fe(e,a,e.bl_tree);while(--o!==0);else a!==0?(a!==r&&(Fe(e,a,e.bl_tree),o--),Fe(e,mp,e.bl_tree),fe(e,o-3,2)):o<=10?(Fe(e,bp,e.bl_tree),fe(e,o-3,3)):(Fe(e,yp,e.bl_tree),fe(e,o-11,7));o=0,r=a,s===0?(l=138,c=3):a===s?(l=6,c=3):(l=7,c=4)}}function yv(e){var t;for(up(e,e.dyn_ltree,e.l_desc.max_code),up(e,e.dyn_dtree,e.d_desc.max_code),Zo(e,e.bl_desc),t=Qo-1;t>=3&&e.bl_tree[vp[t]*2+1]===0;t--);return e.opt_len+=3*(t+1)+5+5+4,t}function vv(e,t,i,n){var r;for(fe(e,t-257,5),fe(e,i-1,5),fe(e,n-4,4),r=0;r<n;r++)fe(e,e.bl_tree[vp[r]*2+1],3);pp(e,e.dyn_ltree,t-1),pp(e,e.dyn_dtree,i-1)}function xv(e){var t=4093624447,i;for(i=0;i<=31;i++,t>>>=1)if(t&1&&e.dyn_ltree[i*2]!==0)return op;if(e.dyn_ltree[18]!==0||e.dyn_ltree[20]!==0||e.dyn_ltree[26]!==0)return lp;for(i=32;i<Fn;i++)if(e.dyn_ltree[i*2]!==0)return lp;return op}var fp=!1;function wv(e){fp||(mv(),fp=!0),e.l_desc=new Yo(e.dyn_ltree,xp),e.d_desc=new Yo(e.dyn_dtree,wp),e.bl_desc=new Yo(e.bl_tree,_p),e.bi_buf=0,e.bi_valid=0,Cp(e)}function kp(e,t,i,n){fe(e,(ov<<1)+(n?1:0),3),bv(e,t,i,!0)}function _v(e){fe(e,hp<<1,3),Fe(e,el,ot),hv(e)}function Ev(e,t,i,n){var r,a,s=0;e.level>0?(e.strm.data_type===sv&&(e.strm.data_type=xv(e)),Zo(e,e.l_desc),Zo(e,e.d_desc),s=yv(e),r=e.opt_len+3+7>>>3,a=e.static_len+3+7>>>3,a<=r&&(r=a)):r=a=i+5,i+4<=r&&t!==-1?kp(e,t,i,n):e.strategy===av||a===r?(fe(e,(hp<<1)+(n?1:0),3),dp(e,ot,jn)):(fe(e,(lv<<1)+(n?1:0),3),vv(e,e.l_desc.max_code+1,e.d_desc.max_code+1,s+1),dp(e,e.dyn_ltree,e.dyn_dtree)),Cp(e),n&&Tp(e)}function Sv(e,t,i){return e.pending_buf[e.d_buf+e.last_lit*2]=t>>>8&255,e.pending_buf[e.d_buf+e.last_lit*2+1]=t&255,e.pending_buf[e.l_buf+e.last_lit]=i&255,e.last_lit++,t===0?e.dyn_ltree[i*2]++:(e.matches++,t--,e.dyn_ltree[(Nn[i]+Fn+1)*2]++,e.dyn_dtree[Ep(t)*2]++),e.last_lit===e.lit_bufsize-1}Mi._tr_init=wv;Mi._tr_stored_block=kp;Mi._tr_flush_block=Ev;Mi._tr_tally=Sv;Mi._tr_align=_v});var il=k((iE,Op)=>{"use strict";function Av(e,t,i,n){for(var r=e&65535|0,a=e>>>16&65535|0,s=0;i!==0;){s=i>2e3?2e3:i,i-=s;do r=r+t[n++]|0,a=a+r|0;while(--s);r%=65521,a%=65521}return r|a<<16|0}Op.exports=Av});var nl=k((nE,Ip)=>{"use strict";function Cv(){for(var e,t=[],i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=e&1?3988292384^e>>>1:e>>>1;t[i]=e}return t}var Tv=Cv();function kv(e,t,i,n){var r=Tv,a=n+i;e^=-1;for(var s=n;s<a;s++)e=e>>>8^r[(e^t[s])&255];return e^-1}Ip.exports=kv});var Ea=k((rE,Mp)=>{"use strict";Mp.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}});var $p=k(Ue=>{"use strict";var pe=st(),we=Lp(),Dp=il(),At=nl(),Lv=Ea(),Jt=0,Ov=1,Iv=3,Ot=4,Pp=5,He=0,Rp=1,_e=-2,Mv=-3,rl=-5,Pv=-1,Rv=1,Sa=2,jv=3,Dv=4,zv=0,Nv=2,ka=8,Bv=9,Fv=15,$v=8,Hv=29,Uv=256,sl=Uv+1+Hv,qv=30,Gv=19,Wv=2*sl+1,Vv=15,N=3,kt=258,Le=kt+N+1,Yv=32,La=42,ol=69,Aa=73,Ca=91,Ta=103,Kt=113,Hn=666,ie=1,Un=2,Xt=3,ji=4,Kv=3;function Lt(e,t){return e.msg=Lv[t],t}function jp(e){return(e<<1)-(e>4?9:0)}function Tt(e){for(var t=e.length;--t>=0;)e[t]=0}function Ct(e){var t=e.state,i=t.pending;i>e.avail_out&&(i=e.avail_out),i!==0&&(pe.arraySet(e.output,t.pending_buf,t.pending_out,i,e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,t.pending===0&&(t.pending_out=0))}function ae(e,t){we._tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,Ct(e.strm)}function F(e,t){e.pending_buf[e.pending++]=t}function $n(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=t&255}function Xv(e,t,i,n){var r=e.avail_in;return r>n&&(r=n),r===0?0:(e.avail_in-=r,pe.arraySet(t,e.input,e.next_in,r,i),e.state.wrap===1?e.adler=Dp(e.adler,t,r,i):e.state.wrap===2&&(e.adler=At(e.adler,t,r,i)),e.next_in+=r,e.total_in+=r,r)}function zp(e,t){var i=e.max_chain_length,n=e.strstart,r,a,s=e.prev_length,o=e.nice_match,l=e.strstart>e.w_size-Le?e.strstart-(e.w_size-Le):0,c=e.window,d=e.w_mask,u=e.prev,p=e.strstart+kt,f=c[n+s-1],g=c[n+s];e.prev_length>=e.good_match&&(i>>=2),o>e.lookahead&&(o=e.lookahead);do if(r=t,!(c[r+s]!==g||c[r+s-1]!==f||c[r]!==c[n]||c[++r]!==c[n+1])){n+=2,r++;do;while(c[++n]===c[++r]&&c[++n]===c[++r]&&c[++n]===c[++r]&&c[++n]===c[++r]&&c[++n]===c[++r]&&c[++n]===c[++r]&&c[++n]===c[++r]&&c[++n]===c[++r]&&n<p);if(a=kt-(p-n),n=p-kt,a>s){if(e.match_start=t,s=a,a>=o)break;f=c[n+s-1],g=c[n+s]}}while((t=u[t&d])>l&&--i!==0);return s<=e.lookahead?s:e.lookahead}function Zt(e){var t=e.w_size,i,n,r,a,s;do{if(a=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-Le)){pe.arraySet(e.window,e.window,t,t,0),e.match_start-=t,e.strstart-=t,e.block_start-=t,n=e.hash_size,i=n;do r=e.head[--i],e.head[i]=r>=t?r-t:0;while(--n);n=t,i=n;do r=e.prev[--i],e.prev[i]=r>=t?r-t:0;while(--n);a+=t}if(e.strm.avail_in===0)break;if(n=Xv(e.strm,e.window,e.strstart+e.lookahead,a),e.lookahead+=n,e.lookahead+e.insert>=N)for(s=e.strstart-e.insert,e.ins_h=e.window[s],e.ins_h=(e.ins_h<<e.hash_shift^e.window[s+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[s+N-1])&e.hash_mask,e.prev[s&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=s,s++,e.insert--,!(e.lookahead+e.insert<N)););}while(e.lookahead<Le&&e.strm.avail_in!==0)}function Zv(e,t){var i=65535;for(i>e.pending_buf_size-5&&(i=e.pending_buf_size-5);;){if(e.lookahead<=1){if(Zt(e),e.lookahead===0&&t===Jt)return ie;if(e.lookahead===0)break}e.strstart+=e.lookahead,e.lookahead=0;var n=e.block_start+i;if((e.strstart===0||e.strstart>=n)&&(e.lookahead=e.strstart-n,e.strstart=n,ae(e,!1),e.strm.avail_out===0)||e.strstart-e.block_start>=e.w_size-Le&&(ae(e,!1),e.strm.avail_out===0))return ie}return e.insert=0,t===Ot?(ae(e,!0),e.strm.avail_out===0?Xt:ji):(e.strstart>e.block_start&&(ae(e,!1),e.strm.avail_out===0),ie)}function al(e,t){for(var i,n;;){if(e.lookahead<Le){if(Zt(e),e.lookahead<Le&&t===Jt)return ie;if(e.lookahead===0)break}if(i=0,e.lookahead>=N&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+N-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),i!==0&&e.strstart-i<=e.w_size-Le&&(e.match_length=zp(e,i)),e.match_length>=N)if(n=we._tr_tally(e,e.strstart-e.match_start,e.match_length-N),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=N){e.match_length--;do e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+N-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart;while(--e.match_length!==0);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else n=we._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(ae(e,!1),e.strm.avail_out===0))return ie}return e.insert=e.strstart<N-1?e.strstart:N-1,t===Ot?(ae(e,!0),e.strm.avail_out===0?Xt:ji):e.last_lit&&(ae(e,!1),e.strm.avail_out===0)?ie:Un}function Pi(e,t){for(var i,n,r;;){if(e.lookahead<Le){if(Zt(e),e.lookahead<Le&&t===Jt)return ie;if(e.lookahead===0)break}if(i=0,e.lookahead>=N&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+N-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=N-1,i!==0&&e.prev_length<e.max_lazy_match&&e.strstart-i<=e.w_size-Le&&(e.match_length=zp(e,i),e.match_length<=5&&(e.strategy===Rv||e.match_length===N&&e.strstart-e.match_start>4096)&&(e.match_length=N-1)),e.prev_length>=N&&e.match_length<=e.prev_length){r=e.strstart+e.lookahead-N,n=we._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-N),e.lookahead-=e.prev_length-1,e.prev_length-=2;do++e.strstart<=r&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+N-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart);while(--e.prev_length!==0);if(e.match_available=0,e.match_length=N-1,e.strstart++,n&&(ae(e,!1),e.strm.avail_out===0))return ie}else if(e.match_available){if(n=we._tr_tally(e,0,e.window[e.strstart-1]),n&&ae(e,!1),e.strstart++,e.lookahead--,e.strm.avail_out===0)return ie}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(n=we._tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<N-1?e.strstart:N-1,t===Ot?(ae(e,!0),e.strm.avail_out===0?Xt:ji):e.last_lit&&(ae(e,!1),e.strm.avail_out===0)?ie:Un}function Jv(e,t){for(var i,n,r,a,s=e.window;;){if(e.lookahead<=kt){if(Zt(e),e.lookahead<=kt&&t===Jt)return ie;if(e.lookahead===0)break}if(e.match_length=0,e.lookahead>=N&&e.strstart>0&&(r=e.strstart-1,n=s[r],n===s[++r]&&n===s[++r]&&n===s[++r])){a=e.strstart+kt;do;while(n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&n===s[++r]&&r<a);e.match_length=kt-(a-r),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=N?(i=we._tr_tally(e,1,e.match_length-N),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=we._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(ae(e,!1),e.strm.avail_out===0))return ie}return e.insert=0,t===Ot?(ae(e,!0),e.strm.avail_out===0?Xt:ji):e.last_lit&&(ae(e,!1),e.strm.avail_out===0)?ie:Un}function Qv(e,t){for(var i;;){if(e.lookahead===0&&(Zt(e),e.lookahead===0)){if(t===Jt)return ie;break}if(e.match_length=0,i=we._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(ae(e,!1),e.strm.avail_out===0))return ie}return e.insert=0,t===Ot?(ae(e,!0),e.strm.avail_out===0?Xt:ji):e.last_lit&&(ae(e,!1),e.strm.avail_out===0)?ie:Un}function $e(e,t,i,n,r){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=n,this.func=r}var Ri;Ri=[new $e(0,0,0,0,Zv),new $e(4,4,8,4,al),new $e(4,5,16,8,al),new $e(4,6,32,32,al),new $e(4,4,16,16,Pi),new $e(8,16,32,32,Pi),new $e(8,16,128,128,Pi),new $e(8,32,128,256,Pi),new $e(32,128,258,1024,Pi),new $e(32,258,258,4096,Pi)];function ex(e){e.window_size=2*e.w_size,Tt(e.head),e.max_lazy_match=Ri[e.level].max_lazy,e.good_match=Ri[e.level].good_length,e.nice_match=Ri[e.level].nice_length,e.max_chain_length=Ri[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=N-1,e.match_available=0,e.ins_h=0}function tx(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=ka,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new pe.Buf16(Wv*2),this.dyn_dtree=new pe.Buf16((2*qv+1)*2),this.bl_tree=new pe.Buf16((2*Gv+1)*2),Tt(this.dyn_ltree),Tt(this.dyn_dtree),Tt(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new pe.Buf16(Vv+1),this.heap=new pe.Buf16(2*sl+1),Tt(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new pe.Buf16(2*sl+1),Tt(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function Np(e){var t;return!e||!e.state?Lt(e,_e):(e.total_in=e.total_out=0,e.data_type=Nv,t=e.state,t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?La:Kt,e.adler=t.wrap===2?0:1,t.last_flush=Jt,we._tr_init(t),He)}function Bp(e){var t=Np(e);return t===He&&ex(e.state),t}function ix(e,t){return!e||!e.state||e.state.wrap!==2?_e:(e.state.gzhead=t,He)}function Fp(e,t,i,n,r,a){if(!e)return _e;var s=1;if(t===Pv&&(t=6),n<0?(s=0,n=-n):n>15&&(s=2,n-=16),r<1||r>Bv||i!==ka||n<8||n>15||t<0||t>9||a<0||a>Dv)return Lt(e,_e);n===8&&(n=9);var o=new tx;return e.state=o,o.strm=e,o.wrap=s,o.gzhead=null,o.w_bits=n,o.w_size=1<<o.w_bits,o.w_mask=o.w_size-1,o.hash_bits=r+7,o.hash_size=1<<o.hash_bits,o.hash_mask=o.hash_size-1,o.hash_shift=~~((o.hash_bits+N-1)/N),o.window=new pe.Buf8(o.w_size*2),o.head=new pe.Buf16(o.hash_size),o.prev=new pe.Buf16(o.w_size),o.lit_bufsize=1<<r+6,o.pending_buf_size=o.lit_bufsize*4,o.pending_buf=new pe.Buf8(o.pending_buf_size),o.d_buf=1*o.lit_bufsize,o.l_buf=3*o.lit_bufsize,o.level=t,o.strategy=a,o.method=i,Bp(e)}function nx(e,t){return Fp(e,t,ka,Fv,$v,zv)}function rx(e,t){var i,n,r,a;if(!e||!e.state||t>Pp||t<0)return e?Lt(e,_e):_e;if(n=e.state,!e.output||!e.input&&e.avail_in!==0||n.status===Hn&&t!==Ot)return Lt(e,e.avail_out===0?rl:_e);if(n.strm=e,i=n.last_flush,n.last_flush=t,n.status===La)if(n.wrap===2)e.adler=0,F(n,31),F(n,139),F(n,8),n.gzhead?(F(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),F(n,n.gzhead.time&255),F(n,n.gzhead.time>>8&255),F(n,n.gzhead.time>>16&255),F(n,n.gzhead.time>>24&255),F(n,n.level===9?2:n.strategy>=Sa||n.level<2?4:0),F(n,n.gzhead.os&255),n.gzhead.extra&&n.gzhead.extra.length&&(F(n,n.gzhead.extra.length&255),F(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(e.adler=At(e.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=ol):(F(n,0),F(n,0),F(n,0),F(n,0),F(n,0),F(n,n.level===9?2:n.strategy>=Sa||n.level<2?4:0),F(n,Kv),n.status=Kt);else{var s=ka+(n.w_bits-8<<4)<<8,o=-1;n.strategy>=Sa||n.level<2?o=0:n.level<6?o=1:n.level===6?o=2:o=3,s|=o<<6,n.strstart!==0&&(s|=Yv),s+=31-s%31,n.status=Kt,$n(n,s),n.strstart!==0&&($n(n,e.adler>>>16),$n(n,e.adler&65535)),e.adler=1}if(n.status===ol)if(n.gzhead.extra){for(r=n.pending;n.gzindex<(n.gzhead.extra.length&65535)&&!(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>r&&(e.adler=At(e.adler,n.pending_buf,n.pending-r,r)),Ct(e),r=n.pending,n.pending===n.pending_buf_size));)F(n,n.gzhead.extra[n.gzindex]&255),n.gzindex++;n.gzhead.hcrc&&n.pending>r&&(e.adler=At(e.adler,n.pending_buf,n.pending-r,r)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=Aa)}else n.status=Aa;if(n.status===Aa)if(n.gzhead.name){r=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>r&&(e.adler=At(e.adler,n.pending_buf,n.pending-r,r)),Ct(e),r=n.pending,n.pending===n.pending_buf_size)){a=1;break}n.gzindex<n.gzhead.name.length?a=n.gzhead.name.charCodeAt(n.gzindex++)&255:a=0,F(n,a)}while(a!==0);n.gzhead.hcrc&&n.pending>r&&(e.adler=At(e.adler,n.pending_buf,n.pending-r,r)),a===0&&(n.gzindex=0,n.status=Ca)}else n.status=Ca;if(n.status===Ca)if(n.gzhead.comment){r=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>r&&(e.adler=At(e.adler,n.pending_buf,n.pending-r,r)),Ct(e),r=n.pending,n.pending===n.pending_buf_size)){a=1;break}n.gzindex<n.gzhead.comment.length?a=n.gzhead.comment.charCodeAt(n.gzindex++)&255:a=0,F(n,a)}while(a!==0);n.gzhead.hcrc&&n.pending>r&&(e.adler=At(e.adler,n.pending_buf,n.pending-r,r)),a===0&&(n.status=Ta)}else n.status=Ta;if(n.status===Ta&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&Ct(e),n.pending+2<=n.pending_buf_size&&(F(n,e.adler&255),F(n,e.adler>>8&255),e.adler=0,n.status=Kt)):n.status=Kt),n.pending!==0){if(Ct(e),e.avail_out===0)return n.last_flush=-1,He}else if(e.avail_in===0&&jp(t)<=jp(i)&&t!==Ot)return Lt(e,rl);if(n.status===Hn&&e.avail_in!==0)return Lt(e,rl);if(e.avail_in!==0||n.lookahead!==0||t!==Jt&&n.status!==Hn){var l=n.strategy===Sa?Qv(n,t):n.strategy===jv?Jv(n,t):Ri[n.level].func(n,t);if((l===Xt||l===ji)&&(n.status=Hn),l===ie||l===Xt)return e.avail_out===0&&(n.last_flush=-1),He;if(l===Un&&(t===Ov?we._tr_align(n):t!==Pp&&(we._tr_stored_block(n,0,0,!1),t===Iv&&(Tt(n.head),n.lookahead===0&&(n.strstart=0,n.block_start=0,n.insert=0))),Ct(e),e.avail_out===0))return n.last_flush=-1,He}return t!==Ot?He:n.wrap<=0?Rp:(n.wrap===2?(F(n,e.adler&255),F(n,e.adler>>8&255),F(n,e.adler>>16&255),F(n,e.adler>>24&255),F(n,e.total_in&255),F(n,e.total_in>>8&255),F(n,e.total_in>>16&255),F(n,e.total_in>>24&255)):($n(n,e.adler>>>16),$n(n,e.adler&65535)),Ct(e),n.wrap>0&&(n.wrap=-n.wrap),n.pending!==0?He:Rp)}function ax(e){var t;return!e||!e.state?_e:(t=e.state.status,t!==La&&t!==ol&&t!==Aa&&t!==Ca&&t!==Ta&&t!==Kt&&t!==Hn?Lt(e,_e):(e.state=null,t===Kt?Lt(e,Mv):He))}function sx(e,t){var i=t.length,n,r,a,s,o,l,c,d;if(!e||!e.state||(n=e.state,s=n.wrap,s===2||s===1&&n.status!==La||n.lookahead))return _e;for(s===1&&(e.adler=Dp(e.adler,t,i,0)),n.wrap=0,i>=n.w_size&&(s===0&&(Tt(n.head),n.strstart=0,n.block_start=0,n.insert=0),d=new pe.Buf8(n.w_size),pe.arraySet(d,t,i-n.w_size,n.w_size,0),t=d,i=n.w_size),o=e.avail_in,l=e.next_in,c=e.input,e.avail_in=i,e.next_in=0,e.input=t,Zt(n);n.lookahead>=N;){r=n.strstart,a=n.lookahead-(N-1);do n.ins_h=(n.ins_h<<n.hash_shift^n.window[r+N-1])&n.hash_mask,n.prev[r&n.w_mask]=n.head[n.ins_h],n.head[n.ins_h]=r,r++;while(--a);n.strstart=r,n.lookahead=N-1,Zt(n)}return n.strstart+=n.lookahead,n.block_start=n.strstart,n.insert=n.lookahead,n.lookahead=0,n.match_length=n.prev_length=N-1,n.match_available=0,e.next_in=l,e.input=c,e.avail_in=o,n.wrap=s,He}Ue.deflateInit=nx;Ue.deflateInit2=Fp;Ue.deflateReset=Bp;Ue.deflateResetKeep=Np;Ue.deflateSetHeader=ix;Ue.deflate=rx;Ue.deflateEnd=ax;Ue.deflateSetDictionary=sx;Ue.deflateInfo="pako deflate (from Nodeca project)"});var ll=k(Di=>{"use strict";var Oa=st(),Hp=!0,Up=!0;try{String.fromCharCode.apply(null,[0])}catch{Hp=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{Up=!1}var qn=new Oa.Buf8(256);for(lt=0;lt<256;lt++)qn[lt]=lt>=252?6:lt>=248?5:lt>=240?4:lt>=224?3:lt>=192?2:1;var lt;qn[254]=qn[254]=1;Di.string2buf=function(e){var t,i,n,r,a,s=e.length,o=0;for(r=0;r<s;r++)i=e.charCodeAt(r),(i&64512)===55296&&r+1<s&&(n=e.charCodeAt(r+1),(n&64512)===56320&&(i=65536+(i-55296<<10)+(n-56320),r++)),o+=i<128?1:i<2048?2:i<65536?3:4;for(t=new Oa.Buf8(o),a=0,r=0;a<o;r++)i=e.charCodeAt(r),(i&64512)===55296&&r+1<s&&(n=e.charCodeAt(r+1),(n&64512)===56320&&(i=65536+(i-55296<<10)+(n-56320),r++)),i<128?t[a++]=i:i<2048?(t[a++]=192|i>>>6,t[a++]=128|i&63):i<65536?(t[a++]=224|i>>>12,t[a++]=128|i>>>6&63,t[a++]=128|i&63):(t[a++]=240|i>>>18,t[a++]=128|i>>>12&63,t[a++]=128|i>>>6&63,t[a++]=128|i&63);return t};function qp(e,t){if(t<65534&&(e.subarray&&Up||!e.subarray&&Hp))return String.fromCharCode.apply(null,Oa.shrinkBuf(e,t));for(var i="",n=0;n<t;n++)i+=String.fromCharCode(e[n]);return i}Di.buf2binstring=function(e){return qp(e,e.length)};Di.binstring2buf=function(e){for(var t=new Oa.Buf8(e.length),i=0,n=t.length;i<n;i++)t[i]=e.charCodeAt(i);return t};Di.buf2string=function(e,t){var i,n,r,a,s=t||e.length,o=new Array(s*2);for(n=0,i=0;i<s;){if(r=e[i++],r<128){o[n++]=r;continue}if(a=qn[r],a>4){o[n++]=65533,i+=a-1;continue}for(r&=a===2?31:a===3?15:7;a>1&&i<s;)r=r<<6|e[i++]&63,a--;if(a>1){o[n++]=65533;continue}r<65536?o[n++]=r:(r-=65536,o[n++]=55296|r>>10&1023,o[n++]=56320|r&1023)}return qp(o,n)};Di.utf8border=function(e,t){var i;for(t=t||e.length,t>e.length&&(t=e.length),i=t-1;i>=0&&(e[i]&192)===128;)i--;return i<0||i===0?t:i+qn[e[i]]>t?i:t}});var cl=k((oE,Gp)=>{"use strict";function ox(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}Gp.exports=ox});var Kp=k(Vn=>{"use strict";var Gn=$p(),Wn=st(),ul=ll(),pl=Ea(),lx=cl(),Yp=Object.prototype.toString,cx=0,dl=4,zi=0,Wp=1,Vp=2,dx=-1,ux=0,px=8;function Qt(e){if(!(this instanceof Qt))return new Qt(e);this.options=Wn.assign({level:dx,method:px,chunkSize:16384,windowBits:15,memLevel:8,strategy:ux,to:""},e||{});var t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new lx,this.strm.avail_out=0;var i=Gn.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==zi)throw new Error(pl[i]);if(t.header&&Gn.deflateSetHeader(this.strm,t.header),t.dictionary){var n;if(typeof t.dictionary=="string"?n=ul.string2buf(t.dictionary):Yp.call(t.dictionary)==="[object ArrayBuffer]"?n=new Uint8Array(t.dictionary):n=t.dictionary,i=Gn.deflateSetDictionary(this.strm,n),i!==zi)throw new Error(pl[i]);this._dict_set=!0}}Qt.prototype.push=function(e,t){var i=this.strm,n=this.options.chunkSize,r,a;if(this.ended)return!1;a=t===~~t?t:t===!0?dl:cx,typeof e=="string"?i.input=ul.string2buf(e):Yp.call(e)==="[object ArrayBuffer]"?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;do{if(i.avail_out===0&&(i.output=new Wn.Buf8(n),i.next_out=0,i.avail_out=n),r=Gn.deflate(i,a),r!==Wp&&r!==zi)return this.onEnd(r),this.ended=!0,!1;(i.avail_out===0||i.avail_in===0&&(a===dl||a===Vp))&&(this.options.to==="string"?this.onData(ul.buf2binstring(Wn.shrinkBuf(i.output,i.next_out))):this.onData(Wn.shrinkBuf(i.output,i.next_out)))}while((i.avail_in>0||i.avail_out===0)&&r!==Wp);return a===dl?(r=Gn.deflateEnd(this.strm),this.onEnd(r),this.ended=!0,r===zi):(a===Vp&&(this.onEnd(zi),i.avail_out=0),!0)};Qt.prototype.onData=function(e){this.chunks.push(e)};Qt.prototype.onEnd=function(e){e===zi&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=Wn.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};function fl(e,t){var i=new Qt(t);if(i.push(e,!0),i.err)throw i.msg||pl[i.err];return i.result}function fx(e,t){return t=t||{},t.raw=!0,fl(e,t)}function hx(e,t){return t=t||{},t.gzip=!0,fl(e,t)}Vn.Deflate=Qt;Vn.deflate=fl;Vn.deflateRaw=fx;Vn.gzip=hx});var Zp=k((cE,Xp)=>{"use strict";var Ia=30,gx=12;Xp.exports=function(t,i){var n,r,a,s,o,l,c,d,u,p,f,g,h,m,b,y,v,x,w,E,A,_,T,P,S;n=t.state,r=t.next_in,P=t.input,a=r+(t.avail_in-5),s=t.next_out,S=t.output,o=s-(i-t.avail_out),l=s+(t.avail_out-257),c=n.dmax,d=n.wsize,u=n.whave,p=n.wnext,f=n.window,g=n.hold,h=n.bits,m=n.lencode,b=n.distcode,y=(1<<n.lenbits)-1,v=(1<<n.distbits)-1;e:do{h<15&&(g+=P[r++]<<h,h+=8,g+=P[r++]<<h,h+=8),x=m[g&y];t:for(;;){if(w=x>>>24,g>>>=w,h-=w,w=x>>>16&255,w===0)S[s++]=x&65535;else if(w&16){E=x&65535,w&=15,w&&(h<w&&(g+=P[r++]<<h,h+=8),E+=g&(1<<w)-1,g>>>=w,h-=w),h<15&&(g+=P[r++]<<h,h+=8,g+=P[r++]<<h,h+=8),x=b[g&v];i:for(;;){if(w=x>>>24,g>>>=w,h-=w,w=x>>>16&255,w&16){if(A=x&65535,w&=15,h<w&&(g+=P[r++]<<h,h+=8,h<w&&(g+=P[r++]<<h,h+=8)),A+=g&(1<<w)-1,A>c){t.msg="invalid distance too far back",n.mode=Ia;break e}if(g>>>=w,h-=w,w=s-o,A>w){if(w=A-w,w>u&&n.sane){t.msg="invalid distance too far back",n.mode=Ia;break e}if(_=0,T=f,p===0){if(_+=d-w,w<E){E-=w;do S[s++]=f[_++];while(--w);_=s-A,T=S}}else if(p<w){if(_+=d+p-w,w-=p,w<E){E-=w;do S[s++]=f[_++];while(--w);if(_=0,p<E){w=p,E-=w;do S[s++]=f[_++];while(--w);_=s-A,T=S}}}else if(_+=p-w,w<E){E-=w;do S[s++]=f[_++];while(--w);_=s-A,T=S}for(;E>2;)S[s++]=T[_++],S[s++]=T[_++],S[s++]=T[_++],E-=3;E&&(S[s++]=T[_++],E>1&&(S[s++]=T[_++]))}else{_=s-A;do S[s++]=S[_++],S[s++]=S[_++],S[s++]=S[_++],E-=3;while(E>2);E&&(S[s++]=S[_++],E>1&&(S[s++]=S[_++]))}}else if((w&64)===0){x=b[(x&65535)+(g&(1<<w)-1)];continue i}else{t.msg="invalid distance code",n.mode=Ia;break e}break}}else if((w&64)===0){x=m[(x&65535)+(g&(1<<w)-1)];continue t}else if(w&32){n.mode=gx;break e}else{t.msg="invalid literal/length code",n.mode=Ia;break e}break}}while(r<a&&s<l);E=h>>3,r-=E,h-=E<<3,g&=(1<<h)-1,t.next_in=r,t.next_out=s,t.avail_in=r<a?5+(a-r):5-(r-a),t.avail_out=s<l?257+(l-s):257-(s-l),n.hold=g,n.bits=h}});var af=k((dE,rf)=>{"use strict";var Jp=st(),Ni=15,Qp=852,ef=592,tf=0,hl=1,nf=2,mx=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],bx=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],yx=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],vx=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];rf.exports=function(t,i,n,r,a,s,o,l){var c=l.bits,d=0,u=0,p=0,f=0,g=0,h=0,m=0,b=0,y=0,v=0,x,w,E,A,_,T=null,P=0,S,L=new Jp.Buf16(Ni+1),z=new Jp.Buf16(Ni+1),D=null,B=0,O,R,C;for(d=0;d<=Ni;d++)L[d]=0;for(u=0;u<r;u++)L[i[n+u]]++;for(g=c,f=Ni;f>=1&&L[f]===0;f--);if(g>f&&(g=f),f===0)return a[s++]=1<<24|64<<16|0,a[s++]=1<<24|64<<16|0,l.bits=1,0;for(p=1;p<f&&L[p]===0;p++);for(g<p&&(g=p),b=1,d=1;d<=Ni;d++)if(b<<=1,b-=L[d],b<0)return-1;if(b>0&&(t===tf||f!==1))return-1;for(z[1]=0,d=1;d<Ni;d++)z[d+1]=z[d]+L[d];for(u=0;u<r;u++)i[n+u]!==0&&(o[z[i[n+u]]++]=u);if(t===tf?(T=D=o,S=19):t===hl?(T=mx,P-=257,D=bx,B-=257,S=256):(T=yx,D=vx,S=-1),v=0,u=0,d=p,_=s,h=g,m=0,E=-1,y=1<<g,A=y-1,t===hl&&y>Qp||t===nf&&y>ef)return 1;for(;;){O=d-m,o[u]<S?(R=0,C=o[u]):o[u]>S?(R=D[B+o[u]],C=T[P+o[u]]):(R=96,C=0),x=1<<d-m,w=1<<h,p=w;do w-=x,a[_+(v>>m)+w]=O<<24|R<<16|C|0;while(w!==0);for(x=1<<d-1;v&x;)x>>=1;if(x!==0?(v&=x-1,v+=x):v=0,u++,--L[d]===0){if(d===f)break;d=i[n+o[u]]}if(d>g&&(v&A)!==E){for(m===0&&(m=g),_+=p,h=d-m,b=1<<h;h+m<f&&(b-=L[h+m],!(b<=0));)h++,b<<=1;if(y+=1<<h,t===hl&&y>Qp||t===nf&&y>ef)return 1;E=v&A,a[E]=g<<24|h<<16|_-s|0}}return v!==0&&(a[_+v]=d-m<<24|64<<16|0),l.bits=g,0}});var Ff=k(Oe=>{"use strict";var me=st(),xl=il(),qe=nl(),xx=Zp(),Yn=af(),wx=0,If=1,Mf=2,sf=4,_x=5,Ma=6,ei=0,Ex=1,Sx=2,Ee=-2,Pf=-3,wl=-4,Ax=-5,of=8,Rf=1,lf=2,cf=3,df=4,uf=5,pf=6,ff=7,hf=8,gf=9,mf=10,ja=11,ct=12,gl=13,bf=14,ml=15,yf=16,vf=17,xf=18,wf=19,Pa=20,Ra=21,_f=22,Ef=23,Sf=24,Af=25,Cf=26,bl=27,Tf=28,kf=29,W=30,_l=31,Cx=32,Tx=852,kx=592,Lx=15,Ox=Lx;function Lf(e){return(e>>>24&255)+(e>>>8&65280)+((e&65280)<<8)+((e&255)<<24)}function Ix(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new me.Buf16(320),this.work=new me.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function jf(e){var t;return!e||!e.state?Ee:(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=t.wrap&1),t.mode=Rf,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new me.Buf32(Tx),t.distcode=t.distdyn=new me.Buf32(kx),t.sane=1,t.back=-1,ei)}function Df(e){var t;return!e||!e.state?Ee:(t=e.state,t.wsize=0,t.whave=0,t.wnext=0,jf(e))}function zf(e,t){var i,n;return!e||!e.state||(n=e.state,t<0?(i=0,t=-t):(i=(t>>4)+1,t<48&&(t&=15)),t&&(t<8||t>15))?Ee:(n.window!==null&&n.wbits!==t&&(n.window=null),n.wrap=i,n.wbits=t,Df(e))}function Nf(e,t){var i,n;return e?(n=new Ix,e.state=n,n.window=null,i=zf(e,t),i!==ei&&(e.state=null),i):Ee}function Mx(e){return Nf(e,Ox)}var Of=!0,yl,vl;function Px(e){if(Of){var t;for(yl=new me.Buf32(512),vl=new me.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(Yn(If,e.lens,0,288,yl,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;Yn(Mf,e.lens,0,32,vl,0,e.work,{bits:5}),Of=!1}e.lencode=yl,e.lenbits=9,e.distcode=vl,e.distbits=5}function Bf(e,t,i,n){var r,a=e.state;return a.window===null&&(a.wsize=1<<a.wbits,a.wnext=0,a.whave=0,a.window=new me.Buf8(a.wsize)),n>=a.wsize?(me.arraySet(a.window,t,i-a.wsize,a.wsize,0),a.wnext=0,a.whave=a.wsize):(r=a.wsize-a.wnext,r>n&&(r=n),me.arraySet(a.window,t,i-n,r,a.wnext),n-=r,n?(me.arraySet(a.window,t,i-n,n,0),a.wnext=n,a.whave=a.wsize):(a.wnext+=r,a.wnext===a.wsize&&(a.wnext=0),a.whave<a.wsize&&(a.whave+=r))),0}function Rx(e,t){var i,n,r,a,s,o,l,c,d,u,p,f,g,h,m=0,b,y,v,x,w,E,A,_,T=new me.Buf8(4),P,S,L=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&e.avail_in!==0)return Ee;i=e.state,i.mode===ct&&(i.mode=gl),s=e.next_out,r=e.output,l=e.avail_out,a=e.next_in,n=e.input,o=e.avail_in,c=i.hold,d=i.bits,u=o,p=l,_=ei;e:for(;;)switch(i.mode){case Rf:if(i.wrap===0){i.mode=gl;break}for(;d<16;){if(o===0)break e;o--,c+=n[a++]<<d,d+=8}if(i.wrap&2&&c===35615){i.check=0,T[0]=c&255,T[1]=c>>>8&255,i.check=qe(i.check,T,2,0),c=0,d=0,i.mode=lf;break}if(i.flags=0,i.head&&(i.head.done=!1),!(i.wrap&1)||(((c&255)<<8)+(c>>8))%31){e.msg="incorrect header check",i.mode=W;break}if((c&15)!==of){e.msg="unknown compression method",i.mode=W;break}if(c>>>=4,d-=4,A=(c&15)+8,i.wbits===0)i.wbits=A;else if(A>i.wbits){e.msg="invalid window size",i.mode=W;break}i.dmax=1<<A,e.adler=i.check=1,i.mode=c&512?mf:ct,c=0,d=0;break;case lf:for(;d<16;){if(o===0)break e;o--,c+=n[a++]<<d,d+=8}if(i.flags=c,(i.flags&255)!==of){e.msg="unknown compression method",i.mode=W;break}if(i.flags&57344){e.msg="unknown header flags set",i.mode=W;break}i.head&&(i.head.text=c>>8&1),i.flags&512&&(T[0]=c&255,T[1]=c>>>8&255,i.check=qe(i.check,T,2,0)),c=0,d=0,i.mode=cf;case cf:for(;d<32;){if(o===0)break e;o--,c+=n[a++]<<d,d+=8}i.head&&(i.head.time=c),i.flags&512&&(T[0]=c&255,T[1]=c>>>8&255,T[2]=c>>>16&255,T[3]=c>>>24&255,i.check=qe(i.check,T,4,0)),c=0,d=0,i.mode=df;case df:for(;d<16;){if(o===0)break e;o--,c+=n[a++]<<d,d+=8}i.head&&(i.head.xflags=c&255,i.head.os=c>>8),i.flags&512&&(T[0]=c&255,T[1]=c>>>8&255,i.check=qe(i.check,T,2,0)),c=0,d=0,i.mode=uf;case uf:if(i.flags&1024){for(;d<16;){if(o===0)break e;o--,c+=n[a++]<<d,d+=8}i.length=c,i.head&&(i.head.extra_len=c),i.flags&512&&(T[0]=c&255,T[1]=c>>>8&255,i.check=qe(i.check,T,2,0)),c=0,d=0}else i.head&&(i.head.extra=null);i.mode=pf;case pf:if(i.flags&1024&&(f=i.length,f>o&&(f=o),f&&(i.head&&(A=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Array(i.head.extra_len)),me.arraySet(i.head.extra,n,a,f,A)),i.flags&512&&(i.check=qe(i.check,n,f,a)),o-=f,a+=f,i.length-=f),i.length))break e;i.length=0,i.mode=ff;case ff:if(i.flags&2048){if(o===0)break e;f=0;do A=n[a+f++],i.head&&A&&i.length<65536&&(i.head.name+=String.fromCharCode(A));while(A&&f<o);if(i.flags&512&&(i.check=qe(i.check,n,f,a)),o-=f,a+=f,A)break e}else i.head&&(i.head.name=null);i.length=0,i.mode=hf;case hf:if(i.flags&4096){if(o===0)break e;f=0;do A=n[a+f++],i.head&&A&&i.length<65536&&(i.head.comment+=String.fromCharCode(A));while(A&&f<o);if(i.flags&512&&(i.check=qe(i.check,n,f,a)),o-=f,a+=f,A)break e}else i.head&&(i.head.comment=null);i.mode=gf;case gf:if(i.flags&512){for(;d<16;){if(o===0)break e;o--,c+=n[a++]<<d,d+=8}if(c!==(i.check&65535)){e.msg="header crc mismatch",i.mode=W;break}c=0,d=0}i.head&&(i.head.hcrc=i.flags>>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=ct;break;case mf:for(;d<32;){if(o===0)break e;o--,c+=n[a++]<<d,d+=8}e.adler=i.check=Lf(c),c=0,d=0,i.mode=ja;case ja:if(i.havedict===0)return e.next_out=s,e.avail_out=l,e.next_in=a,e.avail_in=o,i.hold=c,i.bits=d,Sx;e.adler=i.check=1,i.mode=ct;case ct:if(t===_x||t===Ma)break e;case gl:if(i.last){c>>>=d&7,d-=d&7,i.mode=bl;break}for(;d<3;){if(o===0)break e;o--,c+=n[a++]<<d,d+=8}switch(i.last=c&1,c>>>=1,d-=1,c&3){case 0:i.mode=bf;break;case 1:if(Px(i),i.mode=Pa,t===Ma){c>>>=2,d-=2;break e}break;case 2:i.mode=vf;break;case 3:e.msg="invalid block type",i.mode=W}c>>>=2,d-=2;break;case bf:for(c>>>=d&7,d-=d&7;d<32;){if(o===0)break e;o--,c+=n[a++]<<d,d+=8}if((c&65535)!==(c>>>16^65535)){e.msg="invalid stored block lengths",i.mode=W;break}if(i.length=c&65535,c=0,d=0,i.mode=ml,t===Ma)break e;case ml:i.mode=yf;case yf:if(f=i.length,f){if(f>o&&(f=o),f>l&&(f=l),f===0)break e;me.arraySet(r,n,a,f,s),o-=f,a+=f,l-=f,s+=f,i.length-=f;break}i.mode=ct;break;case vf:for(;d<14;){if(o===0)break e;o--,c+=n[a++]<<d,d+=8}if(i.nlen=(c&31)+257,c>>>=5,d-=5,i.ndist=(c&31)+1,c>>>=5,d-=5,i.ncode=(c&15)+4,c>>>=4,d-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=W;break}i.have=0,i.mode=xf;case xf:for(;i.have<i.ncode;){for(;d<3;){if(o===0)break e;o--,c+=n[a++]<<d,d+=8}i.lens[L[i.have++]]=c&7,c>>>=3,d-=3}for(;i.have<19;)i.lens[L[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,P={bits:i.lenbits},_=Yn(wx,i.lens,0,19,i.lencode,0,i.work,P),i.lenbits=P.bits,_){e.msg="invalid code lengths set",i.mode=W;break}i.have=0,i.mode=wf;case wf:for(;i.have<i.nlen+i.ndist;){for(;m=i.lencode[c&(1<<i.lenbits)-1],b=m>>>24,y=m>>>16&255,v=m&65535,!(b<=d);){if(o===0)break e;o--,c+=n[a++]<<d,d+=8}if(v<16)c>>>=b,d-=b,i.lens[i.have++]=v;else{if(v===16){for(S=b+2;d<S;){if(o===0)break e;o--,c+=n[a++]<<d,d+=8}if(c>>>=b,d-=b,i.have===0){e.msg="invalid bit length repeat",i.mode=W;break}A=i.lens[i.have-1],f=3+(c&3),c>>>=2,d-=2}else if(v===17){for(S=b+3;d<S;){if(o===0)break e;o--,c+=n[a++]<<d,d+=8}c>>>=b,d-=b,A=0,f=3+(c&7),c>>>=3,d-=3}else{for(S=b+7;d<S;){if(o===0)break e;o--,c+=n[a++]<<d,d+=8}c>>>=b,d-=b,A=0,f=11+(c&127),c>>>=7,d-=7}if(i.have+f>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=W;break}for(;f--;)i.lens[i.have++]=A}}if(i.mode===W)break;if(i.lens[256]===0){e.msg="invalid code -- missing end-of-block",i.mode=W;break}if(i.lenbits=9,P={bits:i.lenbits},_=Yn(If,i.lens,0,i.nlen,i.lencode,0,i.work,P),i.lenbits=P.bits,_){e.msg="invalid literal/lengths set",i.mode=W;break}if(i.distbits=6,i.distcode=i.distdyn,P={bits:i.distbits},_=Yn(Mf,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,P),i.distbits=P.bits,_){e.msg="invalid distances set",i.mode=W;break}if(i.mode=Pa,t===Ma)break e;case Pa:i.mode=Ra;case Ra:if(o>=6&&l>=258){e.next_out=s,e.avail_out=l,e.next_in=a,e.avail_in=o,i.hold=c,i.bits=d,xx(e,p),s=e.next_out,r=e.output,l=e.avail_out,a=e.next_in,n=e.input,o=e.avail_in,c=i.hold,d=i.bits,i.mode===ct&&(i.back=-1);break}for(i.back=0;m=i.lencode[c&(1<<i.lenbits)-1],b=m>>>24,y=m>>>16&255,v=m&65535,!(b<=d);){if(o===0)break e;o--,c+=n[a++]<<d,d+=8}if(y&&(y&240)===0){for(x=b,w=y,E=v;m=i.lencode[E+((c&(1<<x+w)-1)>>x)],b=m>>>24,y=m>>>16&255,v=m&65535,!(x+b<=d);){if(o===0)break e;o--,c+=n[a++]<<d,d+=8}c>>>=x,d-=x,i.back+=x}if(c>>>=b,d-=b,i.back+=b,i.length=v,y===0){i.mode=Cf;break}if(y&32){i.back=-1,i.mode=ct;break}if(y&64){e.msg="invalid literal/length code",i.mode=W;break}i.extra=y&15,i.mode=_f;case _f:if(i.extra){for(S=i.extra;d<S;){if(o===0)break e;o--,c+=n[a++]<<d,d+=8}i.length+=c&(1<<i.extra)-1,c>>>=i.extra,d-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=Ef;case Ef:for(;m=i.distcode[c&(1<<i.distbits)-1],b=m>>>24,y=m>>>16&255,v=m&65535,!(b<=d);){if(o===0)break e;o--,c+=n[a++]<<d,d+=8}if((y&240)===0){for(x=b,w=y,E=v;m=i.distcode[E+((c&(1<<x+w)-1)>>x)],b=m>>>24,y=m>>>16&255,v=m&65535,!(x+b<=d);){if(o===0)break e;o--,c+=n[a++]<<d,d+=8}c>>>=x,d-=x,i.back+=x}if(c>>>=b,d-=b,i.back+=b,y&64){e.msg="invalid distance code",i.mode=W;break}i.offset=v,i.extra=y&15,i.mode=Sf;case Sf:if(i.extra){for(S=i.extra;d<S;){if(o===0)break e;o--,c+=n[a++]<<d,d+=8}i.offset+=c&(1<<i.extra)-1,c>>>=i.extra,d-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=W;break}i.mode=Af;case Af:if(l===0)break e;if(f=p-l,i.offset>f){if(f=i.offset-f,f>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=W;break}f>i.wnext?(f-=i.wnext,g=i.wsize-f):g=i.wnext-f,f>i.length&&(f=i.length),h=i.window}else h=r,g=s-i.offset,f=i.length;f>l&&(f=l),l-=f,i.length-=f;do r[s++]=h[g++];while(--f);i.length===0&&(i.mode=Ra);break;case Cf:if(l===0)break e;r[s++]=i.length,l--,i.mode=Ra;break;case bl:if(i.wrap){for(;d<32;){if(o===0)break e;o--,c|=n[a++]<<d,d+=8}if(p-=l,e.total_out+=p,i.total+=p,p&&(e.adler=i.check=i.flags?qe(i.check,r,p,s-p):xl(i.check,r,p,s-p)),p=l,(i.flags?c:Lf(c))!==i.check){e.msg="incorrect data check",i.mode=W;break}c=0,d=0}i.mode=Tf;case Tf:if(i.wrap&&i.flags){for(;d<32;){if(o===0)break e;o--,c+=n[a++]<<d,d+=8}if(c!==(i.total&4294967295)){e.msg="incorrect length check",i.mode=W;break}c=0,d=0}i.mode=kf;case kf:_=Ex;break e;case W:_=Pf;break e;case _l:return wl;case Cx:default:return Ee}return e.next_out=s,e.avail_out=l,e.next_in=a,e.avail_in=o,i.hold=c,i.bits=d,(i.wsize||p!==e.avail_out&&i.mode<W&&(i.mode<bl||t!==sf))&&Bf(e,e.output,e.next_out,p-e.avail_out)?(i.mode=_l,wl):(u-=e.avail_in,p-=e.avail_out,e.total_in+=u,e.total_out+=p,i.total+=p,i.wrap&&p&&(e.adler=i.check=i.flags?qe(i.check,r,p,e.next_out-p):xl(i.check,r,p,e.next_out-p)),e.data_type=i.bits+(i.last?64:0)+(i.mode===ct?128:0)+(i.mode===Pa||i.mode===ml?256:0),(u===0&&p===0||t===sf)&&_===ei&&(_=Ax),_)}function jx(e){if(!e||!e.state)return Ee;var t=e.state;return t.window&&(t.window=null),e.state=null,ei}function Dx(e,t){var i;return!e||!e.state||(i=e.state,(i.wrap&2)===0)?Ee:(i.head=t,t.done=!1,ei)}function zx(e,t){var i=t.length,n,r,a;return!e||!e.state||(n=e.state,n.wrap!==0&&n.mode!==ja)?Ee:n.mode===ja&&(r=1,r=xl(r,t,i,0),r!==n.check)?Pf:(a=Bf(e,t,i,i),a?(n.mode=_l,wl):(n.havedict=1,ei))}Oe.inflateReset=Df;Oe.inflateReset2=zf;Oe.inflateResetKeep=jf;Oe.inflateInit=Mx;Oe.inflateInit2=Nf;Oe.inflate=Rx;Oe.inflateEnd=jx;Oe.inflateGetHeader=Dx;Oe.inflateSetDictionary=zx;Oe.inflateInfo="pako inflate (from Nodeca project)"});var El=k((pE,$f)=>{"use strict";$f.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}});var Uf=k((fE,Hf)=>{"use strict";function Nx(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}Hf.exports=Nx});var Gf=k(Xn=>{"use strict";var Bi=Ff(),Kn=st(),Da=ll(),X=El(),Sl=Ea(),Bx=cl(),Fx=Uf(),qf=Object.prototype.toString;function ti(e){if(!(this instanceof ti))return new ti(e);this.options=Kn.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,t.windowBits===0&&(t.windowBits=-15)),t.windowBits>=0&&t.windowBits<16&&!(e&&e.windowBits)&&(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(t.windowBits&15)===0&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new Bx,this.strm.avail_out=0;var i=Bi.inflateInit2(this.strm,t.windowBits);if(i!==X.Z_OK)throw new Error(Sl[i]);if(this.header=new Fx,Bi.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=Da.string2buf(t.dictionary):qf.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=Bi.inflateSetDictionary(this.strm,t.dictionary),i!==X.Z_OK)))throw new Error(Sl[i])}ti.prototype.push=function(e,t){var i=this.strm,n=this.options.chunkSize,r=this.options.dictionary,a,s,o,l,c,d=!1;if(this.ended)return!1;s=t===~~t?t:t===!0?X.Z_FINISH:X.Z_NO_FLUSH,typeof e=="string"?i.input=Da.binstring2buf(e):qf.call(e)==="[object ArrayBuffer]"?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;do{if(i.avail_out===0&&(i.output=new Kn.Buf8(n),i.next_out=0,i.avail_out=n),a=Bi.inflate(i,X.Z_NO_FLUSH),a===X.Z_NEED_DICT&&r&&(a=Bi.inflateSetDictionary(this.strm,r)),a===X.Z_BUF_ERROR&&d===!0&&(a=X.Z_OK,d=!1),a!==X.Z_STREAM_END&&a!==X.Z_OK)return this.onEnd(a),this.ended=!0,!1;i.next_out&&(i.avail_out===0||a===X.Z_STREAM_END||i.avail_in===0&&(s===X.Z_FINISH||s===X.Z_SYNC_FLUSH))&&(this.options.to==="string"?(o=Da.utf8border(i.output,i.next_out),l=i.next_out-o,c=Da.buf2string(i.output,o),i.next_out=l,i.avail_out=n-l,l&&Kn.arraySet(i.output,i.output,o,l,0),this.onData(c)):this.onData(Kn.shrinkBuf(i.output,i.next_out))),i.avail_in===0&&i.avail_out===0&&(d=!0)}while((i.avail_in>0||i.avail_out===0)&&a!==X.Z_STREAM_END);return a===X.Z_STREAM_END&&(s=X.Z_FINISH),s===X.Z_FINISH?(a=Bi.inflateEnd(this.strm),this.onEnd(a),this.ended=!0,a===X.Z_OK):(s===X.Z_SYNC_FLUSH&&(this.onEnd(X.Z_OK),i.avail_out=0),!0)};ti.prototype.onData=function(e){this.chunks.push(e)};ti.prototype.onEnd=function(e){e===X.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=Kn.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};function Al(e,t){var i=new ti(t);if(i.push(e,!0),i.err)throw i.msg||Sl[i.err];return i.result}function $x(e,t){return t=t||{},t.raw=!0,Al(e,t)}Xn.Inflate=ti;Xn.inflate=Al;Xn.inflateRaw=$x;Xn.ungzip=Al});var Yf=k((gE,Vf)=>{"use strict";var Hx=st().assign,Ux=Kp(),qx=Gf(),Gx=El(),Wf={};Hx(Wf,Ux,qx,Gx);Vf.exports=Wf});var Xf=k(Na=>{"use strict";var Wx=typeof Uint8Array!="undefined"&&typeof Uint16Array!="undefined"&&typeof Uint32Array!="undefined",Vx=Yf(),Kf=Y(),za=ge(),Yx=Wx?"uint8array":"array";Na.magic="\b\0";function ii(e,t){za.call(this,"FlateWorker/"+e),this._pako=null,this._pakoAction=e,this._pakoOptions=t,this.meta={}}Kf.inherits(ii,za);ii.prototype.processChunk=function(e){this.meta=e.meta,this._pako===null&&this._createPako(),this._pako.push(Kf.transformTo(Yx,e.data),!1)};ii.prototype.flush=function(){za.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)};ii.prototype.cleanUp=function(){za.prototype.cleanUp.call(this),this._pako=null};ii.prototype._createPako=function(){this._pako=new Vx[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var e=this;this._pako.onData=function(t){e.push({data:t,meta:e.meta})}};Na.compressWorker=function(e){return new ii("Deflate",e)};Na.uncompressWorker=function(){return new ii("Inflate",{})}});var Tl=k(Cl=>{"use strict";var Zf=ge();Cl.STORE={magic:"\0\0",compressWorker:function(){return new Zf("STORE compression")},uncompressWorker:function(){return new Zf("STORE decompression")}};Cl.DEFLATE=Xf()});var kl=k(ni=>{"use strict";ni.LOCAL_FILE_HEADER="PK";ni.CENTRAL_FILE_HEADER="PK";ni.CENTRAL_DIRECTORY_END="PK";ni.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07";ni.ZIP64_CENTRAL_DIRECTORY_END="PK";ni.DATA_DESCRIPTOR="PK\x07\b"});var th=k((vE,eh)=>{"use strict";var Fi=Y(),$i=ge(),Ll=ki(),Jf=ya(),Ba=kl(),U=function(e,t){var i="",n;for(n=0;n<t;n++)i+=String.fromCharCode(e&255),e=e>>>8;return i},Kx=function(e,t){var i=e;return e||(i=t?16893:33204),(i&65535)<<16},Xx=function(e){return(e||0)&63},Qf=function(e,t,i,n,r,a){var s=e.file,o=e.compression,l=a!==Ll.utf8encode,c=Fi.transformTo("string",a(s.name)),d=Fi.transformTo("string",Ll.utf8encode(s.name)),u=s.comment,p=Fi.transformTo("string",a(u)),f=Fi.transformTo("string",Ll.utf8encode(u)),g=d.length!==s.name.length,h=f.length!==u.length,m,b,y="",v="",x="",w=s.dir,E=s.date,A={crc32:0,compressedSize:0,uncompressedSize:0};(!t||i)&&(A.crc32=e.crc32,A.compressedSize=e.compressedSize,A.uncompressedSize=e.uncompressedSize);var _=0;t&&(_|=8),!l&&(g||h)&&(_|=2048);var T=0,P=0;w&&(T|=16),r==="UNIX"?(P=798,T|=Kx(s.unixPermissions,w)):(P=20,T|=Xx(s.dosPermissions,w)),m=E.getUTCHours(),m=m<<6,m=m|E.getUTCMinutes(),m=m<<5,m=m|E.getUTCSeconds()/2,b=E.getUTCFullYear()-1980,b=b<<4,b=b|E.getUTCMonth()+1,b=b<<5,b=b|E.getUTCDate(),g&&(v=U(1,1)+U(Jf(c),4)+d,y+="up"+U(v.length,2)+v),h&&(x=U(1,1)+U(Jf(p),4)+f,y+="uc"+U(x.length,2)+x);var S="";S+=`
2
- \0`,S+=U(_,2),S+=o.magic,S+=U(m,2),S+=U(b,2),S+=U(A.crc32,4),S+=U(A.compressedSize,4),S+=U(A.uncompressedSize,4),S+=U(c.length,2),S+=U(y.length,2);var L=Ba.LOCAL_FILE_HEADER+S+c+y,z=Ba.CENTRAL_FILE_HEADER+U(P,2)+S+U(p.length,2)+"\0\0\0\0"+U(T,4)+U(n,4)+c+y+p;return{fileRecord:L,dirRecord:z}},Zx=function(e,t,i,n,r){var a="",s=Fi.transformTo("string",r(n));return a=Ba.CENTRAL_DIRECTORY_END+"\0\0\0\0"+U(e,2)+U(e,2)+U(t,4)+U(i,4)+U(s.length,2)+s,a},Jx=function(e){var t="";return t=Ba.DATA_DESCRIPTOR+U(e.crc32,4)+U(e.compressedSize,4)+U(e.uncompressedSize,4),t};function Ie(e,t,i,n){$i.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=t,this.zipPlatform=i,this.encodeFileName=n,this.streamFiles=e,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}Fi.inherits(Ie,$i);Ie.prototype.push=function(e){var t=e.meta.percent||0,i=this.entriesCount,n=this._sources.length;this.accumulate?this.contentBuffer.push(e):(this.bytesWritten+=e.data.length,$i.prototype.push.call(this,{data:e.data,meta:{currentFile:this.currentFile,percent:i?(t+100*(i-n-1))/i:100}}))};Ie.prototype.openedSource=function(e){this.currentSourceOffset=this.bytesWritten,this.currentFile=e.file.name;var t=this.streamFiles&&!e.file.dir;if(t){var i=Qf(e,t,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:i.fileRecord,meta:{percent:0}})}else this.accumulate=!0};Ie.prototype.closedSource=function(e){this.accumulate=!1;var t=this.streamFiles&&!e.file.dir,i=Qf(e,t,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(i.dirRecord),t)this.push({data:Jx(e),meta:{percent:100}});else for(this.push({data:i.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null};Ie.prototype.flush=function(){for(var e=this.bytesWritten,t=0;t<this.dirRecords.length;t++)this.push({data:this.dirRecords[t],meta:{percent:100}});var i=this.bytesWritten-e,n=Zx(this.dirRecords.length,i,e,this.zipComment,this.encodeFileName);this.push({data:n,meta:{percent:100}})};Ie.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()};Ie.prototype.registerPrevious=function(e){this._sources.push(e);var t=this;return e.on("data",function(i){t.processChunk(i)}),e.on("end",function(){t.closedSource(t.previous.streamInfo),t._sources.length?t.prepareNextSource():t.end()}),e.on("error",function(i){t.error(i)}),this};Ie.prototype.resume=function(){if(!$i.prototype.resume.call(this))return!1;if(!this.previous&&this._sources.length)return this.prepareNextSource(),!0;if(!this.previous&&!this._sources.length&&!this.generatedError)return this.end(),!0};Ie.prototype.error=function(e){var t=this._sources;if(!$i.prototype.error.call(this,e))return!1;for(var i=0;i<t.length;i++)try{t[i].error(e)}catch{}return!0};Ie.prototype.lock=function(){$i.prototype.lock.call(this);for(var e=this._sources,t=0;t<e.length;t++)e[t].lock()};eh.exports=Ie});var nh=k(ih=>{"use strict";var Qx=Tl(),ew=th(),tw=function(e,t){var i=e||t,n=Qx[i];if(!n)throw new Error(i+" is not a valid compression method !");return n};ih.generateWorker=function(e,t,i){var n=new ew(t.streamFiles,i,t.platform,t.encodeFileName),r=0;try{e.forEach(function(a,s){r++;var o=tw(s.options.compression,t.compression),l=s.options.compressionOptions||t.compressionOptions||{},c=s.dir,d=s.date;s._compressWorker(o,l).withStreamInfo("file",{name:a,dir:c,date:d,comment:s.comment||"",unixPermissions:s.unixPermissions,dosPermissions:s.dosPermissions}).pipe(n)}),n.entriesCount=r}catch(a){n.error(a)}return n}});var ah=k((wE,rh)=>{"use strict";var iw=Y(),Fa=ge();function Zn(e,t){Fa.call(this,"Nodejs stream input adapter for "+e),this._upstreamEnded=!1,this._bindStream(t)}iw.inherits(Zn,Fa);Zn.prototype._bindStream=function(e){var t=this;this._stream=e,e.pause(),e.on("data",function(i){t.push({data:i,meta:{percent:0}})}).on("error",function(i){t.isPaused?this.generatedError=i:t.error(i)}).on("end",function(){t.isPaused?t._upstreamEnded=!0:t.end()})};Zn.prototype.pause=function(){return Fa.prototype.pause.call(this)?(this._stream.pause(),!0):!1};Zn.prototype.resume=function(){return Fa.prototype.resume.call(this)?(this._upstreamEnded?this.end():this._stream.resume(),!0):!1};rh.exports=Zn});var gh=k((_E,hh)=>{"use strict";var nw=ki(),Jn=Y(),ch=ge(),rw=Ro(),dh=jo(),sh=va(),aw=sp(),sw=nh(),oh=Tn(),ow=ah(),uh=function(e,t,i){var n=Jn.getTypeOf(t),r,a=Jn.extend(i||{},dh);a.date=a.date||new Date,a.compression!==null&&(a.compression=a.compression.toUpperCase()),typeof a.unixPermissions=="string"&&(a.unixPermissions=parseInt(a.unixPermissions,8)),a.unixPermissions&&a.unixPermissions&16384&&(a.dir=!0),a.dosPermissions&&a.dosPermissions&16&&(a.dir=!0),a.dir&&(e=ph(e)),a.createFolders&&(r=lw(e))&&fh.call(this,r,!0);var s=n==="string"&&a.binary===!1&&a.base64===!1;(!i||typeof i.binary=="undefined")&&(a.binary=!s);var o=t instanceof sh&&t.uncompressedSize===0;(o||a.dir||!t||t.length===0)&&(a.base64=!1,a.binary=!0,t="",a.compression="STORE",n="string");var l=null;t instanceof sh||t instanceof ch?l=t:oh.isNode&&oh.isStream(t)?l=new ow(e,t):l=Jn.prepareContent(e,t,a.binary,a.optimizedBinaryString,a.base64);var c=new aw(e,l,a);this.files[e]=c},lw=function(e){e.slice(-1)==="/"&&(e=e.substring(0,e.length-1));var t=e.lastIndexOf("/");return t>0?e.substring(0,t):""},ph=function(e){return e.slice(-1)!=="/"&&(e+="/"),e},fh=function(e,t){return t=typeof t!="undefined"?t:dh.createFolders,e=ph(e),this.files[e]||uh.call(this,e,null,{dir:!0,createFolders:t}),this.files[e]};function lh(e){return Object.prototype.toString.call(e)==="[object RegExp]"}var cw={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(e){var t,i,n;for(t in this.files)n=this.files[t],i=t.slice(this.root.length,t.length),i&&t.slice(0,this.root.length)===this.root&&e(i,n)},filter:function(e){var t=[];return this.forEach(function(i,n){e(i,n)&&t.push(n)}),t},file:function(e,t,i){if(arguments.length===1)if(lh(e)){var n=e;return this.filter(function(a,s){return!s.dir&&n.test(a)})}else{var r=this.files[this.root+e];return r&&!r.dir?r:null}else e=this.root+e,uh.call(this,e,t,i);return this},folder:function(e){if(!e)return this;if(lh(e))return this.filter(function(r,a){return a.dir&&e.test(r)});var t=this.root+e,i=fh.call(this,t),n=this.clone();return n.root=i.name,n},remove:function(e){e=this.root+e;var t=this.files[e];if(t||(e.slice(-1)!=="/"&&(e+="/"),t=this.files[e]),t&&!t.dir)delete this.files[e];else for(var i=this.filter(function(r,a){return a.name.slice(0,e.length)===e}),n=0;n<i.length;n++)delete this.files[i[n].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(e){var t,i={};try{if(i=Jn.extend(e||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:nw.utf8encode}),i.type=i.type.toLowerCase(),i.compression=i.compression.toUpperCase(),i.type==="binarystring"&&(i.type="string"),!i.type)throw new Error("No output type specified.");Jn.checkSupport(i.type),(i.platform==="darwin"||i.platform==="freebsd"||i.platform==="linux"||i.platform==="sunos")&&(i.platform="UNIX"),i.platform==="win32"&&(i.platform="DOS");var n=i.comment||this.comment||"";t=sw.generateWorker(this,i,n)}catch(r){t=new ch("error"),t.error(r)}return new rw(t,i.type||"string",i.mimeType)},generateAsync:function(e,t){return this.generateInternalStream(e).accumulate(t)},generateNodeStream:function(e,t){return e=e||{},e.type||(e.type="nodebuffer"),this.generateInternalStream(e).toNodejsStream(t)}};hh.exports=cw});var Ol=k((EE,bh)=>{"use strict";var dw=Y();function mh(e){this.data=e,this.length=e.length,this.index=0,this.zero=0}mh.prototype={checkOffset:function(e){this.checkIndex(this.index+e)},checkIndex:function(e){if(this.length<this.zero+e||e<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+e+"). Corrupted zip ?")},setIndex:function(e){this.checkIndex(e),this.index=e},skip:function(e){this.setIndex(this.index+e)},byteAt:function(){},readInt:function(e){var t=0,i;for(this.checkOffset(e),i=this.index+e-1;i>=this.index;i--)t=(t<<8)+this.byteAt(i);return this.index+=e,t},readString:function(e){return dw.transformTo("string",this.readData(e))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var e=this.readInt(4);return new Date(Date.UTC((e>>25&127)+1980,(e>>21&15)-1,e>>16&31,e>>11&31,e>>5&63,(e&31)<<1))}};bh.exports=mh});var Il=k((SE,vh)=>{"use strict";var yh=Ol(),uw=Y();function Hi(e){yh.call(this,e);for(var t=0;t<this.data.length;t++)e[t]=e[t]&255}uw.inherits(Hi,yh);Hi.prototype.byteAt=function(e){return this.data[this.zero+e]};Hi.prototype.lastIndexOfSignature=function(e){for(var t=e.charCodeAt(0),i=e.charCodeAt(1),n=e.charCodeAt(2),r=e.charCodeAt(3),a=this.length-4;a>=0;--a)if(this.data[a]===t&&this.data[a+1]===i&&this.data[a+2]===n&&this.data[a+3]===r)return a-this.zero;return-1};Hi.prototype.readAndCheckSignature=function(e){var t=e.charCodeAt(0),i=e.charCodeAt(1),n=e.charCodeAt(2),r=e.charCodeAt(3),a=this.readData(4);return t===a[0]&&i===a[1]&&n===a[2]&&r===a[3]};Hi.prototype.readData=function(e){if(this.checkOffset(e),e===0)return[];var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t};vh.exports=Hi});var _h=k((AE,wh)=>{"use strict";var xh=Ol(),pw=Y();function Ui(e){xh.call(this,e)}pw.inherits(Ui,xh);Ui.prototype.byteAt=function(e){return this.data.charCodeAt(this.zero+e)};Ui.prototype.lastIndexOfSignature=function(e){return this.data.lastIndexOf(e)-this.zero};Ui.prototype.readAndCheckSignature=function(e){var t=this.readData(4);return e===t};Ui.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t};wh.exports=Ui});var Pl=k((CE,Sh)=>{"use strict";var Eh=Il(),fw=Y();function Ml(e){Eh.call(this,e)}fw.inherits(Ml,Eh);Ml.prototype.readData=function(e){if(this.checkOffset(e),e===0)return new Uint8Array(0);var t=this.data.subarray(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t};Sh.exports=Ml});var Th=k((TE,Ch)=>{"use strict";var Ah=Pl(),hw=Y();function Rl(e){Ah.call(this,e)}hw.inherits(Rl,Ah);Rl.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t};Ch.exports=Rl});var jl=k((kE,Lh)=>{"use strict";var $a=Y(),kh=rt(),gw=Il(),mw=_h(),bw=Th(),yw=Pl();Lh.exports=function(e){var t=$a.getTypeOf(e);return $a.checkSupport(t),t==="string"&&!kh.uint8array?new mw(e):t==="nodebuffer"?new bw(e):kh.uint8array?new yw($a.transformTo("uint8array",e)):new gw($a.transformTo("array",e))}});var Ph=k((LE,Mh)=>{"use strict";var Dl=jl(),It=Y(),vw=va(),Oh=ya(),Ha=ki(),Ua=Tl(),xw=rt(),ww=0,_w=3,Ew=function(e){for(var t in Ua)if(Object.prototype.hasOwnProperty.call(Ua,t)&&Ua[t].magic===e)return Ua[t];return null};function Ih(e,t){this.options=e,this.loadOptions=t}Ih.prototype={isEncrypted:function(){return(this.bitFlag&1)===1},useUTF8:function(){return(this.bitFlag&2048)===2048},readLocalPart:function(e){var t,i;if(e.skip(22),this.fileNameLength=e.readInt(2),i=e.readInt(2),this.fileName=e.readData(this.fileNameLength),e.skip(i),this.compressedSize===-1||this.uncompressedSize===-1)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if(t=Ew(this.compressionMethod),t===null)throw new Error("Corrupted zip : compression "+It.pretty(this.compressionMethod)+" unknown (inner file : "+It.transformTo("string",this.fileName)+")");this.decompressed=new vw(this.compressedSize,this.uncompressedSize,this.crc32,t,e.readData(this.compressedSize))},readCentralPart:function(e){this.versionMadeBy=e.readInt(2),e.skip(2),this.bitFlag=e.readInt(2),this.compressionMethod=e.readString(2),this.date=e.readDate(),this.crc32=e.readInt(4),this.compressedSize=e.readInt(4),this.uncompressedSize=e.readInt(4);var t=e.readInt(2);if(this.extraFieldsLength=e.readInt(2),this.fileCommentLength=e.readInt(2),this.diskNumberStart=e.readInt(2),this.internalFileAttributes=e.readInt(2),this.externalFileAttributes=e.readInt(4),this.localHeaderOffset=e.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");e.skip(t),this.readExtraFields(e),this.parseZIP64ExtraField(e),this.fileComment=e.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var e=this.versionMadeBy>>8;this.dir=!!(this.externalFileAttributes&16),e===ww&&(this.dosPermissions=this.externalFileAttributes&63),e===_w&&(this.unixPermissions=this.externalFileAttributes>>16&65535),!this.dir&&this.fileNameStr.slice(-1)==="/"&&(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var e=Dl(this.extraFields[1].value);this.uncompressedSize===It.MAX_VALUE_32BITS&&(this.uncompressedSize=e.readInt(8)),this.compressedSize===It.MAX_VALUE_32BITS&&(this.compressedSize=e.readInt(8)),this.localHeaderOffset===It.MAX_VALUE_32BITS&&(this.localHeaderOffset=e.readInt(8)),this.diskNumberStart===It.MAX_VALUE_32BITS&&(this.diskNumberStart=e.readInt(4))}},readExtraFields:function(e){var t=e.index+this.extraFieldsLength,i,n,r;for(this.extraFields||(this.extraFields={});e.index+4<t;)i=e.readInt(2),n=e.readInt(2),r=e.readData(n),this.extraFields[i]={id:i,length:n,value:r};e.setIndex(t)},handleUTF8:function(){var e=xw.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=Ha.utf8decode(this.fileName),this.fileCommentStr=Ha.utf8decode(this.fileComment);else{var t=this.findExtraFieldUnicodePath();if(t!==null)this.fileNameStr=t;else{var i=It.transformTo(e,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(i)}var n=this.findExtraFieldUnicodeComment();if(n!==null)this.fileCommentStr=n;else{var r=It.transformTo(e,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(r)}}},findExtraFieldUnicodePath:function(){var e=this.extraFields[28789];if(e){var t=Dl(e.value);return t.readInt(1)!==1||Oh(this.fileName)!==t.readInt(4)?null:Ha.utf8decode(t.readData(e.length-5))}return null},findExtraFieldUnicodeComment:function(){var e=this.extraFields[25461];if(e){var t=Dl(e.value);return t.readInt(1)!==1||Oh(this.fileComment)!==t.readInt(4)?null:Ha.utf8decode(t.readData(e.length-5))}return null}};Mh.exports=Ih});var Dh=k((OE,jh)=>{"use strict";var Sw=jl(),dt=Y(),Me=kl(),Aw=Ph(),Cw=rt();function Rh(e){this.files=[],this.loadOptions=e}Rh.prototype={checkSignature:function(e){if(!this.reader.readAndCheckSignature(e)){this.reader.index-=4;var t=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+dt.pretty(t)+", expected "+dt.pretty(e)+")")}},isSignature:function(e,t){var i=this.reader.index;this.reader.setIndex(e);var n=this.reader.readString(4),r=n===t;return this.reader.setIndex(i),r},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var e=this.reader.readData(this.zipCommentLength),t=Cw.uint8array?"uint8array":"array",i=dt.transformTo(t,e);this.zipComment=this.loadOptions.decodeFileName(i)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var e=this.zip64EndOfCentralSize-44,t=0,i,n,r;t<e;)i=this.reader.readInt(2),n=this.reader.readInt(4),r=this.reader.readData(n),this.zip64ExtensibleData[i]={id:i,length:n,value:r}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),this.disksCount>1)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var e,t;for(e=0;e<this.files.length;e++)t=this.files[e],this.reader.setIndex(t.localHeaderOffset),this.checkSignature(Me.LOCAL_FILE_HEADER),t.readLocalPart(this.reader),t.handleUTF8(),t.processAttributes()},readCentralDir:function(){var e;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(Me.CENTRAL_FILE_HEADER);)e=new Aw({zip64:this.zip64},this.loadOptions),e.readCentralPart(this.reader),this.files.push(e);if(this.centralDirRecords!==this.files.length&&this.centralDirRecords!==0&&this.files.length===0)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var e=this.reader.lastIndexOfSignature(Me.CENTRAL_DIRECTORY_END);if(e<0){var t=!this.isSignature(0,Me.LOCAL_FILE_HEADER);throw t?new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html"):new Error("Corrupted zip: can't find end of central directory")}this.reader.setIndex(e);var i=e;if(this.checkSignature(Me.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===dt.MAX_VALUE_16BITS||this.diskWithCentralDirStart===dt.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===dt.MAX_VALUE_16BITS||this.centralDirRecords===dt.MAX_VALUE_16BITS||this.centralDirSize===dt.MAX_VALUE_32BITS||this.centralDirOffset===dt.MAX_VALUE_32BITS){if(this.zip64=!0,e=this.reader.lastIndexOfSignature(Me.ZIP64_CENTRAL_DIRECTORY_LOCATOR),e<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(e),this.checkSignature(Me.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,Me.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(Me.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(Me.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var n=this.centralDirOffset+this.centralDirSize;this.zip64&&(n+=20,n+=12+this.zip64EndOfCentralSize);var r=i-n;if(r>0)this.isSignature(i,Me.CENTRAL_FILE_HEADER)||(this.reader.zero=r);else if(r<0)throw new Error("Corrupted zip: missing "+Math.abs(r)+" bytes.")},prepareReader:function(e){this.reader=Sw(e)},load:function(e){this.prepareReader(e),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}};jh.exports=Rh});var Bh=k((IE,Nh)=>{"use strict";var zl=Y(),qa=Ai(),Tw=ki(),kw=Dh(),Lw=No(),zh=Tn();function Ow(e){return new qa.Promise(function(t,i){var n=e.decompressed.getContentWorker().pipe(new Lw);n.on("error",function(r){i(r)}).on("end",function(){n.streamInfo.crc32!==e.decompressed.crc32?i(new Error("Corrupted zip : CRC32 mismatch")):t()}).resume()})}Nh.exports=function(e,t){var i=this;return t=zl.extend(t||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:Tw.utf8decode}),zh.isNode&&zh.isStream(e)?qa.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):zl.prepareContent("the loaded zip file",e,!0,t.optimizedBinaryString,t.base64).then(function(n){var r=new kw(t);return r.load(n),r}).then(function(r){var a=[qa.Promise.resolve(r)],s=r.files;if(t.checkCRC32)for(var o=0;o<s.length;o++)a.push(Ow(s[o]));return qa.Promise.all(a)}).then(function(r){for(var a=r.shift(),s=a.files,o=0;o<s.length;o++){var l=s[o],c=l.fileNameStr,d=zl.resolve(l.fileNameStr);i.file(d,l.decompressed,{binary:!0,optimizedBinaryString:!0,date:l.date,dir:l.dir,comment:l.fileCommentStr.length?l.fileCommentStr:null,unixPermissions:l.unixPermissions,dosPermissions:l.dosPermissions,createFolders:t.createFolders}),l.dir||(i.file(d).unsafeOriginalName=c)}return a.zipComment.length&&(i.comment=a.zipComment),i})}});var $h=k((ME,Fh)=>{"use strict";function Se(){if(!(this instanceof Se))return new Se;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var e=new Se;for(var t in this)typeof this[t]!="function"&&(e[t]=this[t]);return e}}Se.prototype=gh();Se.prototype.loadAsync=Bh();Se.support=rt();Se.defaults=jo();Se.version="3.10.1";Se.loadAsync=function(e,t){return new Se().loadAsync(e,t)};Se.external=Ai();Fh.exports=Se});var Tg={};an(Tg,{AssetEditorModal:()=>dc});var dc,uc=Ve(()=>{"use strict";dc=class{constructor(){this.modal=null;this.currentObjectId=null;this.currentPath=null;this.currentAsset="";this.onApplyCallback=null}show(t,i,n,r){this.currentObjectId=t,this.currentPath=i,this.currentAsset=n,this.onApplyCallback=r,this.createModal(t,n),document.body.appendChild(this.modal),this.attachModalListeners()}createModal(t,i){let n=document.createElement("div");n.className="asset-editor-modal",n.innerHTML=`
1
+ "use strict";var Rr=Object.create;var Ht=Object.defineProperty;var jr=Object.getOwnPropertyDescriptor;var Dr=Object.getOwnPropertyNames;var $r=Object.getPrototypeOf,zr=Object.prototype.hasOwnProperty;var se=(i,e)=>()=>(i&&(e=i(i=0)),e);var qe=(i,e)=>{for(var t in e)Ht(i,t,{get:e[t],enumerable:!0})},Ca=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Dr(e))!zr.call(i,a)&&a!==t&&Ht(i,a,{get:()=>e[a],enumerable:!(n=jr(e,a))||n.enumerable});return i};var Ve=(i,e,t)=>(t=i!=null?Rr($r(i)):{},Ca(e||!i||!i.__esModule?Ht(t,"default",{value:i,enumerable:!0}):t,i)),La=i=>Ca(Ht({},"__esModule",{value:!0}),i);var de,ri=se(()=>{"use strict";de=class{static get(e){var t;return(t=this.store.get(e))==null?void 0:t.data}static set(e,t){this.store.set(e,{data:t})}static has(e){return this.store.has(e)}static clear(){this.store.clear()}};de.store=new Map});function Vr(){var i,e;try{let t=typeof window!="undefined"&&(document.querySelector('script[src*="inline-assets.js"]')||((e=(i=document.querySelector("script"))==null?void 0:i.textContent)==null?void 0:e.includes("inline-assets.js"))||window.INLINE_ASSETS),n=typeof window!="undefined"&&document.querySelector('link[href*="assets/"], script[src*="assets/"]');return!!(t&&!n)}catch{return!1}}async function Wr(){try{if(typeof window!="undefined"){let i=await fetch("./build-settings.json");if(i.ok){let e=await i.json();return console.log("[AssetLoader] Loaded build settings:",e),e}}}catch{}return null}function Yr(){try{if(typeof window!="undefined"){let i=new XMLHttpRequest;if(i.open("GET","./build-settings.json",!1),i.send(),i.status===200&&i.responseText){let e=JSON.parse(i.responseText);return console.log("[AssetLoader] Loaded build settings (sync):",e),e}}}catch{}return null}async function Kr(){if(console.log(`[AssetLoader] getInlineAssets() called - Effective mode: ${N}`),Object.keys(pe).length>0)return console.log("[AssetLoader] Returning cached inline assets:",Object.keys(pe)),pe;if(typeof window!="undefined"&&window.INLINE_ASSETS)return console.log("[AssetLoader] Using pre-loaded INLINE_ASSETS from window:",Object.keys(window.INLINE_ASSETS)),pe={...window.INLINE_ASSETS},pe;if(!(N==="publish"&&re!==!1))return console.log("[AssetLoader] Inline assets disabled for this build mode."),pe;if(!oi){let e=typeof window!="undefined"?new URL("inline-assets.js",window.location.href).href:"./inline-assets.js";console.log("[AssetLoader] Loading inline assets from:",e),oi=(async()=>{try{try{let s=await import(e+"?t="+Date.now());if(s.INLINE_ASSETS)return console.log("[AssetLoader] Loaded INLINE_ASSETS via ES module:",Object.keys(s.INLINE_ASSETS)),s.INLINE_ASSETS}catch(s){console.warn("[AssetLoader] ES module import failed, trying text parse:",s)}let t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status}: ${t.statusText}`);let n=await t.text();console.log("[AssetLoader] Received JS code, length:",n.length);let a=n.match(/export\s+const\s+INLINE_ASSETS\s*=\s*({[\s\S]*?});?\s*$/m);if(a)try{let s=a[1];console.log("[AssetLoader] Found INLINE_ASSETS export, parsing...");let r=new Function("return "+s)();return console.log("[AssetLoader] Parsed inline assets:",Object.keys(r)),r}catch(s){return console.warn("[AssetLoader] Failed to parse inline assets:",s),{}}else return console.warn("[AssetLoader] INLINE_ASSETS export not found in response"),console.log("[AssetLoader] JS code preview:",n.substring(0,500)),{}}catch(t){return console.warn("[AssetLoader] Failed to load inline assets:",t),{}}})()}return pe=await oi,console.log("[AssetLoader] Final inline assets cache:",Object.keys(pe)),pe}function li(i){return i===null||typeof i!="object"||(Object.freeze(i),Object.values(i).forEach(e=>li(e))),i}function Xr(i=64,e=64,t=16711680){let n=document.createElement("canvas");n.width=i,n.height=e;let a=n.getContext("2d");return a.fillStyle=`#${t.toString(16).padStart(6,"0")}`,a.fillRect(0,0,i,e),a.strokeStyle="#000",a.strokeRect(0,0,i,e),a.fillStyle="#fff",a.font="10px sans-serif",a.textAlign="center",a.fillText("MISSING",i/2,e/2),ue.Texture.from(n)}function ci(i,e){ss.set(i,e)}var ue,is,as,Ie,N,re,we,pe,oi,ss,Re,Ut=se(()=>{"use strict";ue=require("pixi.js");ri();is=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",as=Vr(),Ie=typeof window!="undefined"?window.__BUILD_SETTINGS__:null,N=as?"publish":is,re=Ie==null?void 0:Ie.assetsInlined;Ie!=null&&Ie.buildMode&&(N=Ie.buildMode,console.log(`[AssetLoader] Build mode overridden by inline settings: ${N}`));we=Yr();we!=null&&we.buildMode&&(N=we.buildMode,console.log(`[AssetLoader] Build mode overridden by sync settings: ${N}`));(we==null?void 0:we.assetsInlined)!==void 0&&(re=we.assetsInlined);Wr().then(i=>{i!=null&&i.buildMode&&i.buildMode!==N&&(N=i.buildMode,console.log(`[AssetLoader] Build mode overridden by settings: ${N}`)),(i==null?void 0:i.assetsInlined)!==void 0&&(re=i.assetsInlined)}).catch(()=>{});console.log(`[AssetLoader] MODULE LOADED - Compile: ${is}, Runtime: ${as?"publish":"dev"}, Effective: ${N}`);pe={},oi=null;ss=new Map;Re=class{static async load(e,t,n,a){let s=`${e}:${t.path}`,r=de.get(s);if(r!==void 0)return r;console.log(`[AssetLoader] Loading asset: ${e}, type: ${t.type}, Effective mode: ${N}`),console.log(`[AssetLoader] Window defined: ${typeof window!="undefined"}, INLINE_ASSETS exists: ${!!(typeof window!="undefined"&&window.INLINE_ASSETS)}, keys: ${typeof window!="undefined"&&window.INLINE_ASSETS?Object.keys(window.INLINE_ASSETS).length:"N/A"}`);let o=await Kr(),l=o[e];if(!l&&a&&(l=o[a],l&&console.log(`[AssetLoader] Found inline data for ${e} using configId: ${a}`)),!l&&t.path){let d=t.path.split("/");if(d.length>=2){let u=d[d.length-1].split(".")[0];o[u]&&(l=o[u],console.log(`[AssetLoader] Found inline data for ${e} using assetName: ${u}`))}}if(console.log("[AssetLoader] Inline data for",e,":",l?"FOUND":"NOT FOUND"),N==="publish"&&re!==!1&&(console.log("[AssetLoader] \u26A0\uFE0F PUBLISH MODE DETECTED - inline assets are MANDATORY"),!l))throw new Error(`[AssetLoader] PUBLISH MODE: Inline asset required but NOT FOUND for object: ${e}, path: ${t.path}`);let p=ss.get(t.type);if(p)try{let d=await p(t.path,l,e,n);return de.set(s,d),d}catch(d){return this.handleFailure(e,t.type,d)}try{let d;switch(t.type){case"image":d=await this.loadImage(t.path,l);break;case"json":d=await this.loadJSON(t.path,l),d=li(d);break;default:throw new Error(`Unknown asset type: ${t.type}`)}return de.set(s,d),d}catch(d){return this.handleFailure(e,t.type,d)}}static async loadImage(e,t){let n=N==="publish",a=n&&re!==!1;if(console.log(`[AssetLoader] loadImage - Effective mode: ${N}, isPublishMode: ${n}, inlineData: ${t?"EXISTS":"MISSING"}`),a){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!t)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for object. Path: ${e}`);if(typeof t!="string"||!t.startsWith("data:"))throw new Error(`[AssetLoader] Publish mode: inline asset must be data URI string, got: ${typeof t}`);try{return await ue.Assets.load(t)}catch(s){throw console.error("[AssetLoader] Failed to load texture from data URI:",s),s}}if(t&&typeof t=="string"&&t.startsWith("data:"))try{return await ue.Assets.load(t)}catch(s){return console.error("[AssetLoader] Failed to load texture from data URI, falling back to path:",s),await ue.Assets.load(e)}return await ue.Assets.load(e)}static async loadJSON(e,t){let n=N==="publish",a=n&&re!==!1;if(console.log(`[AssetLoader] loadJSON - Effective mode: ${N}, isPublishMode: ${n}, inlineData: ${t?"EXISTS":"MISSING"}`),a){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!t)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${e}`);if(typeof t=="object"&&t!==null)return t;if(typeof t=="string"&&t.startsWith("data:")){let r=atob(t.split(",")[1]);return JSON.parse(r)}return JSON.parse(t)}if(t){if(typeof t=="object"&&t!==null)return t;if(typeof t=="string"&&t.startsWith("data:")){let r=atob(t.split(",")[1]);return JSON.parse(r)}return JSON.parse(t)}let s=await fetch(e);if(!s.ok)throw new Error(`JSON fetch failed: ${e}`);return s.json()}static handleFailure(e,t,n){if(N==="dev"){let s=t==="image"?Xr():li({__placeholder:!0,type:t});return de.set(e+":"+((n==null?void 0:n.path)||"missing"),s),s}throw n}};ci("image",async(i,e)=>{let t=N==="publish",n=t&&re!==!1,a=N==="brand",s=t&&re===!1;if(console.log(`[AssetLoader] registerType('image') - Effective mode: ${N}, isPublishMode: ${t}, isBrandMode: ${a}, inlineData: ${e?"EXISTS":"MISSING"}`),n){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!e)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${i}`);if(typeof e!="string"||!e.startsWith("data:"))throw new Error(`[AssetLoader] Publish mode: inline asset must be data URI string, got: ${typeof e}`);return ue.Assets.load(e)}let r=i;return(a||s)&&i&&!i.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(r=i,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${i}" as-is`)):(r=`assets/${i}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${i}" -> "${r}"`))),ue.Assets.load(e||r)});ci("json",async(i,e)=>{let t=N==="publish",n=t&&re!==!1,a=N==="brand",s=t&&re===!1;if(console.log(`[AssetLoader] registerType('json') - Effective mode: ${N}, isPublishMode: ${t}, isBrandMode: ${a}, inlineData: ${e?"EXISTS":"MISSING"}`),n){if(console.log("[AssetLoader] PUBLISH MODE ACTIVATED - inline assets are MANDATORY"),!e)throw new Error(`[AssetLoader] Publish mode: inline asset required but not found for path: ${i}`);return typeof e=="object"&&e!==null?e:typeof e=="string"&&e.startsWith("data:")?JSON.parse(atob(e.split(",")[1])):JSON.parse(e)}let r=i;if((a||s)&&i&&!i.startsWith("assets/")&&(typeof window!="undefined"&&!document.querySelector('link[href*="assets/"], script[src*="assets/"]')&&!document.querySelector('link[href*="configs/"], script[src*="configs/"]')?(r=i,console.log(`[AssetLoader] BRAND MODE: flattened build, using path "${i}" as-is`)):(r=`assets/${i}`,console.log(`[AssetLoader] BRAND MODE: transformed path "${i}" -> "${r}"`))),e)return typeof e=="object"&&e!==null?e:typeof e=="string"&&e.startsWith("data:")?JSON.parse(atob(e.split(",")[1])):JSON.parse(e);let o=await fetch(r);if(!o.ok)throw new Error(`JSON fetch failed: ${i}`);return o.json()})});var os={};qe(os,{AssetTextures:()=>oe,initAssetTextures:()=>ui});function ui(i,e){rs.init(i,e),typeof window!="undefined"&&(window.__AssetTextures=oe)}var pi,rs,oe,Xe=se(()=>{"use strict";Ut();pi=class{constructor(){this.textures=new Map;this.readyPromise=null;this.priorityReadyPromise=null;this.priorityReadyResolve=null;this.config=null;this.app=null;this.attempted=new Set;this.waiters=new Set}init(e,t){if(this.config===e&&this.app===t&&this.priorityReadyPromise){console.log("[AssetTextures] init called with same config/app; keeping existing state");return}this.textures.clear(),this.readyPromise=null,this.priorityReadyPromise=null,this.priorityReadyResolve=null,this.attempted.clear(),this.waiters.clear(),this.priorityReadyPromise=new Promise(n=>{this.priorityReadyResolve=n}),this.config=e,this.app=t,console.log("[AssetTextures] Initialized with config, cleared previous textures")}async ready(){if(this.readyPromise){await this.readyPromise;return}if(!this.config)throw new Error("[AssetTextures] Must call init() before ready() - config is null");if(!this.app)throw new Error("[AssetTextures] Must call init() before ready() - app is null");let e=this.config,t=this.app;return this.readyPromise=(async()=>{var r;console.log("[AssetTextures] Loading all assets...");let n=new Set(["background_loading_1"]),a=[],s=[];for(let[o,l]of e.objects.entries()){let c=(r=l.render)==null?void 0:r.asset;if(!c)continue;let p=async()=>{var d;try{let u=(d=l.identity)==null?void 0:d.id;console.log(`[AssetTextures] Loading ${c.type}: ${o} (${u})`);let g=await Re.load(o,c,t,u);this.textures.set(o,g),console.log(`[AssetTextures] \u2713 Loaded: ${o}`)}catch(u){console.error(`[AssetTextures] \u2717 Failed to load: ${o}`,u)}finally{this.attempted.add(o);try{for(let u of Array.from(this.waiters))u()}catch{}}};n.has(o)?a.push(p()):s.push(p())}a.length>0&&(console.log("[AssetTextures] Phase 1: Loading priority assets (loading screen)..."),await Promise.all(a),console.log("[AssetTextures] Phase 1: Priority assets ready")),this.priorityReadyResolve&&this.priorityReadyResolve(),console.log("[AssetTextures] Phase 2: Loading remaining assets..."),await Promise.all(s),console.log("[AssetTextures] All textures loaded:",Array.from(this.textures.keys()))})(),this.readyPromise}async priorityReady(){return this.priorityReadyPromise?this.priorityReadyPromise:Promise.resolve()}async waitFor(e,t={}){if(!this.config)throw new Error("[AssetTextures] Must call init() before waitFor() - config is null");if(!this.app)throw new Error("[AssetTextures] Must call init() before waitFor() - app is null");let a=Array.from(new Set((e||[]).filter(o=>typeof o=="string"&&o))).filter(o=>{var l,c,p,d;try{let u=(p=(c=(l=this.config)==null?void 0:l.objects)==null?void 0:c.get)==null?void 0:p.call(c,o);return!!((d=u==null?void 0:u.render)!=null&&d.asset)}catch{return!1}});if(a.length===0)return;this.ready().catch(()=>{});let s=()=>a.every(o=>this.textures.has(o)||this.attempted.has(o));if(s())return;let r=typeof t.timeoutMs=="number"?t.timeoutMs:15e3;await new Promise(o=>{let l=!1,c=()=>{l||s()&&(l=!0,this.waiters.delete(c),o())};this.waiters.add(c),c(),r>0&&setTimeout(()=>{l||(l=!0,this.waiters.delete(c),console.warn("[AssetTextures] waitFor timed out; continuing",{ids:a}),o())},r)})}get(e){return this.textures.get(e)}set(e,t){this.textures.set(e,t),console.log(`[AssetTextures] Updated texture: ${e}`)}clear(){this.textures.clear(),this.readyPromise=null,console.log("[AssetTextures] Cleared all textures")}getAllIds(){return Array.from(this.textures.keys())}},rs=new pi,oe=new Proxy(rs,{get(i,e){return e in i&&typeof i[e]=="function"?i[e].bind(i):i.get(e)},set(i,e,t){return i.set(e,t),!0}})});var sn={};qe(sn,{applyConfigOverride:()=>Ae,applyConfigOverrides:()=>Se,applyConfigsToDisk:()=>wt,clearConfigOverrides:()=>Ce,clearConfigOverridesForObject:()=>vs,configOverrideManager:()=>xs,deepClone:()=>U,exportConfigsAsJSON:()=>xt,getConfigOverrides:()=>Y,getConfigStateSummary:()=>nn,getOverrideMode:()=>vt,removeConfigOverride:()=>tn,resetToApplied:()=>Et,resetToOriginal:()=>an,setOverrideMode:()=>mi});function Qt(){return typeof window=="undefined"?null:window.__editableConfig||null}function fs(){return typeof window=="undefined"?null:window.__editableConfigBaseline||null}function us(i,e){var t,n;if(!i)return null;try{if(i instanceof Map)return(t=i.get(e))!=null?t:null;if(typeof i=="object")return(n=i[e])!=null?n:null}catch{}return null}function Eo(i,e,t){if(i){if(i instanceof Map){i.set(e,t);return}typeof i=="object"&&(i[e]=t)}}function hs(i,e){for(let t of e)yt(i,t.path,t.value)}function ms(i){var o;if(typeof window=="undefined")return;let e=Qt();if(!e)return;let t=fs(),n=(o=t?us(t.objects,i):null)!=null?o:us(e.objects,i);if(!n)return;let a=U(n),s=Y().filter(l=>l.objectId===i);try{hs(a,s)}catch(l){console.error("[CONFIG] Failed to reapply overrides for object",i,l);return}Eo(e.objects,i,a);let r=window.applyEditableObjectConfig;if(typeof r=="function")try{r(i,a)}catch{}}function Ao(){var a;if(typeof window=="undefined")return;let i=Qt();if(!(i!=null&&i.engine))return;let e=fs(),t=U(((a=e==null?void 0:e.engine)!=null?a:i.engine)||{}),n=Y().filter(s=>!s.objectId&&!s.sceneId);try{hs(t,n)}catch(s){console.error("[CONFIG] Failed to reapply engine overrides",s);return}try{let s=i.engine;for(let r of Object.keys(s))r in t||delete s[r];for(let[r,o]of Object.entries(t))s[r]=o}catch{i.engine=t}}function So(){if(typeof window=="undefined")return"unknown";let i=window;return typeof i.__HANDLER_PROJECT_ID=="string"?i.__HANDLER_PROJECT_ID:"handler-default"}function bs(){return`handler_preview_config_overrides::${So()}`}function Co(){if(typeof window=="undefined")return[];try{let i=window.localStorage.getItem(bs());if(!i)return[];let e=JSON.parse(i);return Array.isArray(e)?e:[]}catch{return[]}}function en(i){if(typeof window!="undefined")try{window.localStorage.setItem(bs(),JSON.stringify(i))}catch{}}function vt(){return typeof window=="undefined"?!1:window.__enableConfigOverrides===!0}function mi(i){if(typeof window!="undefined"){window.__enableConfigOverrides=i;try{window.localStorage.setItem(ys,i?"true":"false")}catch{}}}function Ae(i,e={}){var u,g;let{objectId:t,path:n,value:a}=i,{silent:s=!1,persist:r=!0,emitEvent:o=!0}=e,l=Qt();if(!l){console.warn("[CONFIG] applyConfigOverride: No editable config found in window.__editableConfig");return}let c=t?(g=(u=l.objects)==null?void 0:u.get)==null?void 0:g.call(u,t):l.engine;if(!c){console.warn("[CONFIG] applyConfigOverride: Override target not found:",{objectId:t,path:n,hasObjects:!!l.objects});return}s||console.log("[CONFIG] applyConfigOverride: Target found, applying...",{objectId:t,path:n,value:a});let p;try{p=To(c,n),yt(c,n,a)}catch(h){console.error("[CONFIG] applyConfigOverride failed:",{objectId:t,path:n,value:a},h);return}window.__configChanges=window.__configChanges||[];let d=window.__configChanges;if(d.push({objectId:t,path:n,oldValue:p,newValue:a,ts:Date.now()}),d.length>Lo&&d.shift(),r){let h=Y(),f=h.findIndex(m=>m.objectId===t&&m.sceneId===i.sceneId&&m.path===n);f>=0?h[f].value=a:h.push(i),window.__configOverrides=h,en(h),vt()||mi(!0)}s||console.log("[CONFIG] Applied override:",i),o&&typeof window!="undefined"&&window.dispatchEvent(new CustomEvent("config:changed",{detail:i}))}function Se(i,e={}){let t=e.emitEvent!==!1,n=[];for(let a of i)a!=null&&a.objectId&&typeof a.objectId=="string"&&n.push(a.objectId),Ae(a,{...e,emitEvent:!1});if(t&&typeof window!="undefined"){let a=Array.from(new Set(n));window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"batch",objectIds:a,count:i.length}}))}}function Ce(){window.__configOverrides=[],window.__configChanges=[],en([]),console.log("[CONFIG] Cleared all overrides")}function vs(i){let e=Y().filter(n=>n.objectId!==i);window.__configOverrides=e,en(e);let t=window.__configChanges||[];window.__configChanges=t.filter(n=>n.objectId!==i),ms(i),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"clear_object",objectId:i}}))}function tn(i,e){let t=Y().filter(a=>a.objectId!==i||a.path!==e);window.__configOverrides=t,en(t);let n=window.__configChanges||[];window.__configChanges=n.filter(a=>a.objectId!==i||a.path!==e),i?ms(i):Ao(),window.dispatchEvent(new CustomEvent("config:changed",{detail:{action:"remove",objectId:i,path:e}}))}function Y(){return typeof window=="undefined"?[]:(window.__configOverrides||(window.__configOverrides=Co()),window.__configOverrides||[])}function yt(i,e,t){var r;let n=e.split("."),a=n.pop(),s=i;for(let o of n){if(s[o]!==void 0&&typeof s[o]!="object")throw new Error(`Invalid override path: ${e} (hit primitive at ${o})`);s[o]=(r=s[o])!=null?r:{},s=s[o]}s[a]=t}function To(i,e){return e.split(".").reduce((t,n)=>t?t[n]:void 0,i)}function U(i){if(i===null||typeof i!="object")return i;if(i instanceof Date)return new Date(i.getTime());if(i instanceof Set)return new Set([...i].map(t=>U(t)));if(ArrayBuffer.isView(i))return i.slice();if(i instanceof Array)return i.map(t=>U(t));if(i instanceof Map){let t=new Map;return i.forEach((n,a)=>t.set(a,U(n))),t}let e={};for(let t in i)Object.prototype.hasOwnProperty.call(i,t)&&(e[t]=U(i[t]));return e}function xt(){let i=window.__editableConfigBaseline;if(!i){let e=window.__editableConfig;if(!e)throw new Error("Cannot export: no config loaded");return gs(e)}return gs(i)}function gs(i){let e={objects:{},scenes:{},engine:U(i.engine||{})},t=i.objects;if(t instanceof Map)t.forEach((s,r)=>{e.objects[r]=U(s)});else if(t&&typeof t=="object")for(let s in t)e.objects[s]=U(t[s]);let n=i.scenes;if(n instanceof Map)n.forEach((s,r)=>{e.scenes[r]=U(s)});else if(n&&typeof n=="object")for(let s in n)e.scenes[s]=U(n[s]);let a=Y();for(let s of a)s.objectId?(e.objects[s.objectId]||(e.objects[s.objectId]={}),yt(e.objects[s.objectId],s.path,s.value)):s.sceneId?(e.scenes[s.sceneId]||(e.scenes[s.sceneId]={}),yt(e.scenes[s.sceneId],s.path,s.value)):yt(e.engine,s.path,s.value);return e}function nn(){let i=Y(),e=new Set;for(let t of i)t.objectId?e.add(t.objectId):e.add("__engine__");return{modifiedObjects:Array.from(e),overrideCount:i.length,hasChanges:i.length>0,overrides:i}}async function wt(i){let e=xt(),t={};for(let[a,s]of Object.entries(e.objects)){let r=s,o=a;/^(json\.|ui\.|effects\.|engine\.)/.test(o)||(o=`json.${a}`),r&&typeof r=="object"&&(r.identity||(r.identity={}),r.identity.id=o),t[`objects/${o}.json`]=r}e.engine&&(e.engine.runtime&&(t["engine/engine.runtime.json"]=e.engine.runtime),e.engine.assets&&(t["engine/engine.assets.json"]=e.engine.assets),e.engine.splash&&(t["engine/engine.splash.json"]=e.engine.splash),e.engine.loading&&(t["engine/engine.loading.json"]=e.engine.loading),e.engine.start&&(t["engine/engine.start.json"]=e.engine.start),e.engine.tutorial&&(t["engine/engine.tutorial.json"]=e.engine.tutorial),e.engine.endgame&&(t["engine/engine.endgame.json"]=e.engine.endgame),!e.engine.runtime&&!e.engine.assets&&(t["engine/engine.json"]=e.engine));for(let[a,s]of Object.entries(e.scenes)){let r=a.startsWith("scene.")?a:`scene.${a}`;t[`scenes/${r}.json`]=s}let n=await fetch("/api/apply",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:t,assets:{},hadCacheAtApply:Y().length>0,versionName:i})});if(!n.ok){let a=await n.json();throw new Error(`Apply failed: ${a.error||"Unknown error"}`)}Ce();try{let a=Qt();a&&(window.__editableConfigBaseline=U(a))}catch{}localStorage.setItem("handler_last_applied",Date.now().toString()),console.log("[Config Persistence] \u2705 Applied to disk successfully")}function Et(){Ce(),window.location.reload()}async function an(){if(!confirm("This will restore all configs to their original state. All uncommitted changes in cache AND applied changes will be lost. Continue?"))return;let e=await fetch("/api/reset-to-original",{method:"POST"});if(!e.ok){let t=await e.json();throw new Error(`Reset failed: ${t.error||"Unknown error"}`)}Ce(),window.location.reload()}var ys,Lo,xs,ee=se(()=>{"use strict";ys="handler_preview_override_mode";if(typeof window!="undefined"){let i=window.localStorage.getItem(ys);window.__enableConfigOverrides=i===null?!0:i==="true"}Lo=500;xs={getCurrentConfig(){return window.__editableConfig||null},getChanges(){return window.__configChanges||[]},clearChanges(){window.__configChanges=[]}}});function _o(i,e){try{if(typeof i=="object"&&i!==null)return i;if(typeof i!="string")return null;if(i.startsWith("data:")){let n=i.indexOf(",");if(n===-1)return null;let a=i.slice(0,n);if(!a.includes("application/json")&&!a.includes("text/plain"))return null;let s=i.slice(n+1),r=a.includes("base64")?typeof atob=="function"?atob(s):s:decodeURIComponent(s);return JSON.parse(r)}let t=i.trim();return t.startsWith("{")||t.startsWith("[")?JSON.parse(i):null}catch{return null}}function Po(i){if(typeof window=="undefined"||!window.INLINE_ASSETS)return null;let e=window.INLINE_ASSETS,t=i.replace(/^\.\/+/,""),n=t.split("/").pop()||t,a=[t,n,t.replace(/\.json$/,""),n.replace(/\.json$/,"")];for(let s of a){let r=e[s];if(r){let o=_o(r,s);if(o!==null)return o}}return null}async function At(i){if(bi.has(i)&&!yi)return console.log(`[CONFIG] Using cached config for: "${i}"`),bi.get(i);if(console.log(`[CONFIG] loadConfigFile called with: "${i}", MODE: ${z.toUpperCase()}, CACHE: ${yi?"DISABLED":"ENABLED"}`),z==="publish"){let n=Po(i);return n?(console.log(`[CONFIG] \u2713 Loaded ${i} via INLINE_ASSETS`),n):(console.log(`[CONFIG] \u2139\uFE0F Optional config ${i} not in INLINE_ASSETS, skipping fetch in publish mode`),{})}z==="brand"||console.log(`[CONFIG] DEV MODE: Trying nested paths first, then flattened for "${i}"`);let e;z==="brand"?e=[`./${i.split("/").pop()||i}`,`./${i}`,`./${i.replace(/^configs\//,"")}`,`./${i.replace(/^configs\//,"").replace(/\//g,".")}`]:e=[`./${i}`,`./${i.replace(/^configs\//,"")}`,`./${i.replace(/^configs\//,"").replace(/\//g,".")}`],e=Array.from(new Set(e.flatMap(n=>n.startsWith("./")?[n,`/${n.slice(2)}`]:n.startsWith("/")?[n]:[n,`/${n}`]))),console.log("[CONFIG] Will try candidates:",e);let t=(async()=>{let n=yi?"no-store":"force-cache";for(let a of e)try{let s=await fetch(a,{cache:n});if(!s.ok)continue;let r=await s.json();return console.log(`[CONFIG] \u2713 Loaded ${i} via ${a}`,r),r}catch(s){console.warn(`[CONFIG] \u2717 Failed to load ${a} (mode: ${z}):`,s)}return console.warn(`[CONFIG] \u2717 All attempts failed for ${i}; using defaults`),{}})();return bi.set(i,t),t}async function rn(){console.log("[CONFIG] Loading component schemas...");let i=["components/identity.schema.json","components/transform.schema.json","components/render.schema.json","components/motion.schema.json","components/effects.schema.json","components/interaction.schema.json","components/gameplay.rules.schema.json","components/gameplay.tuning.schema.json","components/visibility.schema.json","components/audio.schema.json","components/physics.schema.json","components/ui.schema.json"],e=new Map;for(let t of i)try{let n=z==="publish"||z==="brand"?t.split("/").pop()||t:`configs/${t}`,a=await At(n);a.component&&(e.set(a.component,a),console.log(`[CONFIG] \u2713 Schema loaded: ${a.component} ${z==="publish"||z==="brand"?"(flattened)":"(nested)"}`))}catch(n){console.warn(`[CONFIG] \u2717 Failed to load schema ${t}:`,n)}return console.log(`[CONFIG] Loaded ${e.size} component schemas`),e}async function Le(i){console.log(`[CONFIG] Loading object config: ${i}`);let e=z==="publish"||z==="brand"?`${i}.json`:`configs/objects/${i}.json`;return await At(e)}async function on(i){let e=new Map;if(i.objects&&Array.isArray(i.objects)){for(let t of i.objects)if(t.enabled&&t.object_config)try{let n=t.instance_id;/^(json\.|ui\.|effects\.|engine\.)/.test(n)||(n=`json.${n}`);let a=await Le(n);(!a||Object.keys(a).length===0)&&n!==t.instance_id&&(a=await Le(t.instance_id)),!a||Object.keys(a).length===0?(console.log(`[CONFIG] No instance snapshot for ${t.instance_id}, using template ${t.object_config}`),a=await Le(t.object_config)):console.log(`[CONFIG] \u2713 Loaded instance snapshot for ${t.instance_id}`),e.set(t.instance_id,{...a,instance_id:t.instance_id,object_config:t.object_config})}catch(n){console.warn(`Failed to load object ${t.object_config}:`,n)}}return e}async function ln(){console.log("[CONFIG] Loading engine configs...");let i=["runtime","assets","splash","loading","start","tutorial","endgame"],e=await Promise.all(i.map(n=>{let a=`engine.${n}.json`,s=z==="publish"||z==="brand"?a:`configs/engine/${a}`;return At(s)})),t=Object.fromEntries(i.map((n,a)=>[n,e[a]]));return console.log("[CONFIG] Engine configs loaded:",Object.fromEntries(i.map(n=>{var r;let a=(r=t[n])!=null?r:{},s=Object.keys(a);return[n,s.length>0?s:"empty"]}))),t}async function vi(){return await At(z==="publish"||z==="brand"?"game.prompt.json":"configs/engine/game.prompt.json")}async function cn(i="scene.main"){console.log(`[CONFIG] Loading scene config: ${i}`);let e=z==="publish"||z==="brand"?`${i}.json`:`configs/scenes/${i}.json`;return await At(e)}function Je(i,e){let t=[];if(!i.identity)return t.push("Missing required identity component"),{valid:!1,errors:t};let n=e.get("identity");if(n)for(let a of n.required||[])i.identity[a]||t.push(`Missing required identity field: ${a}`);for(let[a,s]of Object.entries(i)){if(a==="identity")continue;let r=e.get(a);if(r&&s&&typeof s=="object"){let o=s;for(let l of r.required||[])o[l]===void 0&&t.push(`Missing required field in ${a}: ${l}`);if(r.constraints&&typeof r.constraints=="object")for(let[l,c]of Object.entries(r.constraints)){let p=o[l];if(p!==void 0&&c&&typeof c=="object"){let d=c;typeof p=="number"&&(d.min!==void 0&&p<d.min&&t.push(`${a}.${l} value ${p} is below minimum ${d.min}`),d.max!==void 0&&p>d.max&&t.push(`${a}.${l} value ${p} is above maximum ${d.max}`))}}}}return{valid:t.length===0,errors:t}}function De(i,e){let t={...i},n=["identity","transform","render"];for(let[a,s]of e.entries())s.defaults&&Object.keys(s.defaults).length>0&&(n.includes(a)||t[a])&&(t[a]||(t[a]={}),t[a]={...s.defaults,...t[a]});return t}function Z(i,e,t,n){return typeof i!="number"||!Number.isFinite(i)?e:Math.min(Math.max(i,t),n)}function Es(i,e){if(Array.isArray(i))return{x:Z(i[0],e.x,-2e3,2e3),y:Z(i[1],e.y,-2e3,2e3)};if(!i||typeof i!="object")return e;let{x:t,y:n}=i;return{x:Z(t,e.x,-2e3,2e3),y:Z(n,e.y,-2e3,2e3)}}function Mo(i,e){if(Array.isArray(i))return{x:Z(i[0],e.x,0,1),y:Z(i[1],e.y,0,1)};if(!i||typeof i!="object")return e;let{x:t,y:n}=i;return{x:Z(t,e.x,0,1),y:Z(n,e.y,0,1)}}function ko(i){if(Array.isArray(i))return{x:Z(i[0],.5,-10,10),y:Z(i[1],.5,-10,10)};if(i&&typeof i=="object"){let{x:e,y:t}=i;return{x:Z(e,.5,-10,10),y:Z(t,.5,-10,10)}}return typeof i=="string"?i:null}async function me(i="scene.main",e){var l,c,p,d,u,g,h,f,m,b,y,v,x,E;console.log("[CONFIG] ===== Starting Object-Centric Config Load =====");let t=await rn(),n=Y();n.length>0&&console.log(`[CONFIG] Applying ${n.length} active overrides`);let a=await cn(i);console.log(`[CONFIG] Scene config loaded: ${((l=a.objects)==null?void 0:l.length)||0} objects`);let s=await ln();console.log("[CONFIG] Loading object configs...");let r=await on(a);console.log(`[CONFIG] Loaded ${r.size} object configs:`,Array.from(r.keys()));for(let[w,T]of r.entries()){let S=De(T,t),O=Je(S,t);O.valid||console.warn(`Object ${w} validation errors:`,O.errors),(c=S.transform)!=null&&c.position&&(S.transform.position=Es(S.transform.position,{x:0,y:0})),(p=S.transform)!=null&&p.offset&&(S.transform.offset=Es(S.transform.offset,{x:0,y:0})),((d=S.transform)==null?void 0:d.anchor)!==void 0&&(S.transform.anchor=ko(S.transform.anchor)),((u=S.transform)==null?void 0:u.position_ratio)!==void 0&&S.transform.position_ratio!==null&&(S.transform.position_ratio=Mo(S.transform.position_ratio,{x:.5,y:.5})),r.set(w,S)}if(e){if(e.objects)for(let[w,T]of e.objects.entries())r.set(w,T);e.engine&&(s.runtime={...s.runtime,...e.engine.runtime},s.assets={...s.assets,...e.engine.assets},s.splash={...(g=s.splash)!=null?g:{},...(h=e.engine.splash)!=null?h:{}})}let o={objects:r,engine:s,scene:a,schemas:t,theme:{background_color:"#ffffff",text_color:"#000000",square_color:"#cccccc",cta_background:"#007bff",cta_text:"#ffffff"},gameplay:{}};return typeof window!="undefined"&&(window.__editableConfig=o,window.__editableConfigBaseline||(window.__editableConfigBaseline=De(o,t))),n.length>0&&vt()&&Se(n,{silent:!0,persist:!1}),console.log("[CONFIG] ===== Object-Centric Config Load Complete ====="),console.log("[CONFIG] Summary:",{schemas:Array.from(t.keys()),objects:Array.from(r.keys()),engine:{runtime:Object.keys((f=s.runtime)!=null?f:{}),assets:Object.keys((m=s.assets)!=null?m:{}),splash:Object.keys((b=s.splash)!=null?b:{}),loading:Object.keys((y=s.loading)!=null?y:{}),start:Object.keys((v=s.start)!=null?v:{}),tutorial:Object.keys((x=s.tutorial)!=null?x:{}),endgame:Object.keys((E=s.endgame)!=null?E:{})},scene:a.scene_id||"unknown"}),o}function xi(i){var t,n,a,s,r,o,l,c,p,d,u,g,h,f,m,b,y,v,x,E,w,T,S,O,B,M,C,I,k,D,R,$,A;let e={gameplay:{},ui:{},theme:{},assets:{}};for(let[_,P]of i.objects.entries()){let q=((t=P.identity)==null?void 0:t.id)||_;q.includes("character")&&(e.gameplay.character_pos=((n=P.transform)==null?void 0:n.position)||{x:0,y:0},e.gameplay.character_scale=((a=P.transform)==null?void 0:a.scale)||1,e.gameplay.character_anim_speed=((r=(s=P.gameplay)==null?void 0:s.tuning)==null?void 0:r.anim_speed)||.003,e.gameplay.character_relief_scale=((l=(o=P.gameplay)==null?void 0:o.tuning)==null?void 0:l.relief_scale)||1.22,e.gameplay.character_relief_speed=((p=(c=P.gameplay)==null?void 0:c.tuning)==null?void 0:p.relief_speed)||.22),(q.includes("gun")||q.includes("flame"))&&(e.gameplay.gun=P.gun||{},e.gameplay.gunmuzzle=((d=P.effects)==null?void 0:d.gunmuzzle)||{},e.gameplay.muzzle_levels=((u=P.effects)==null?void 0:u.muzzle_levels)||{},e.gameplay.flame=((g=P.effects)==null?void 0:g.flame)||{}),q.includes("diamond")&&(e.gameplay.diamond=P),q.includes("ice")&&(e.gameplay.melt=P.melt||{},e.gameplay.melt_anchor=((h=P.transform)==null?void 0:h.melt_anchor)||{x:0,y:0},e.gameplay.melt_pos=((f=P.transform)==null?void 0:f.position)||{x:0,y:0},e.gameplay.hybrid_melting=((m=P.effects)==null?void 0:m.hybrid_melting)||{},e.gameplay.physics_chunks=((b=P.effects)==null?void 0:b.physics_chunks)||{},e.gameplay.melting_particles=((y=P.effects)==null?void 0:y.melting_particles)||{},e.gameplay.hard_ice=P.hard_ice||{}),q.includes("water")&&(e.gameplay.water_drops=P),q.includes("crack")&&(e.gameplay.crack=P),q.includes("hand")&&(e.gameplay.hand=((v=P.gameplay)==null?void 0:v.tuning)||{},e.gameplay.brush_start_pos=((x=P.transform)==null?void 0:x.brush_start_pos)||{x:0,y:-120},e.gameplay.hand_scale=((E=P.transform)==null?void 0:E.scale)||1.5),q.includes("hazard")&&(e.gameplay.hazard=((w=P.gameplay)==null?void 0:w.tuning)||{},e.gameplay.danger_pos=((T=P.transform)==null?void 0:T.danger_pos)||{x:0,y:235},e.gameplay.danger_pulse=((O=(S=P.gameplay)==null?void 0:S.tuning)==null?void 0:O.danger_pulse)||{},e.gameplay.hazard_height=((M=(B=P.gameplay)==null?void 0:B.tuning)==null?void 0:M.hazard_height)||140)}return e.gameplay.timeline=((C=i.engine.runtime)==null?void 0:C.timeline)||{},e.gameplay.drag_surface=((I=i.engine.runtime)==null?void 0:I.drag_surface)||{},e.gameplay.background=((k=i.engine.runtime)==null?void 0:k.background)||{},e.gameplay.ui_styles=((D=i.engine.runtime)==null?void 0:D.ui_styles)||{},e.gameplay.label_pulse=((R=i.engine.runtime)==null?void 0:R.label_pulse)||{},e.ui=(($=i.engine.runtime)==null?void 0:$.ui)||{},e.theme=((A=i.engine.runtime)==null?void 0:A.theme)||{},e.assets=i.engine.assets||{},e}var ws,z,bi,yi,wi=se(()=>{"use strict";ee();ws=null,z="dev";if(typeof window!="undefined"){let i=window.__BUILD_SETTINGS__;if(i!=null&&i.buildMode)ws=i,z=i.buildMode,console.log("[CONFIG] Loaded inline build settings:",i,"buildMode:",z);else try{let e=new XMLHttpRequest;if(e.open("GET","./build-settings.json",!1),e.send(),e.status===200&&e.responseText){let t=JSON.parse(e.responseText);ws=t,z=t.buildMode||"dev",console.log("[CONFIG] Loaded build settings:",t,"buildMode:",z)}else console.log("[CONFIG] No build-settings.json found, using default buildMode:",z)}catch(e){console.log("[CONFIG] Failed to load build-settings.json:",e instanceof Error?e.message:String(e))}}console.log("[CONFIG] Final buildMode:",z);bi=new Map,yi=z==="dev"||typeof window!="undefined"&&window.location.search.includes("hot-reload")});function Ei(i,e){let t=[];function n(a,s,r=""){if(a!==s){if(typeof a!=typeof s){t.push(`${r}: type changed`);return}if(typeof a=="object"&&a!==null&&s!==null){let o=new Set([...Object.keys(a),...Object.keys(s)]);for(let l of o){let c=r?`${r}.${l}`:l;l in a?l in s?n(a[l],s[l],c):t.push(`${c}: removed`):t.push(`${c}: added`)}}else t.push(`${r}: changed`)}}return n(i,e),t}function Ai(i,e,t,n){let a={...t};for(let[s,r]of n.entries())a[s]&&r.defaults&&(a[s]={...r.defaults,...a[s]});return a}var St,$e,Si=se(()=>{"use strict";St=class{shouldFullReload(e){return e.type==="component"||e.type==="scene"}getAffectedObjects(e){return e.type==="object"&&e.objectId?[e.objectId]:[]}},$e=class{constructor(e=1e3){this.pollingInterval=null;this.fileHashes=new Map;this.callbacks=new Map;this.intervalMs=e}watch(e,t){this.callbacks.set(e,t),this.pollingInterval===null&&(this.pollingInterval=window.setInterval(()=>{this.checkAllFiles()},this.intervalMs))}async checkAllFiles(){for(let[e,t]of this.callbacks.entries())try{let n=`${e}?t=${Date.now()}&r=${Math.random()}`,a=await fetch(n,{cache:"no-cache",headers:{"Cache-Control":"no-cache"}});if(a.ok){let s=await a.text(),r=this.hashString(s),o=this.fileHashes.get(e);if(o&&o!==r&&console.log(`[HOT-RELOAD] File changed: ${e}`),o&&o!==r){console.log(`[HOT-RELOAD] File changed: ${e}`);let l=this.determineEventType(e);t(l),this.fileHashes.set(e,r)}else o||this.fileHashes.set(e,r)}}catch(n){console.warn(`Failed to check ${e}:`,n)}}determineEventType(e){var t,n;return e.includes("/components/")?{type:"component",path:e,componentName:(t=e.split("/").pop())==null?void 0:t.replace(".schema.json","")}:e.includes("/engine/")?{type:"engine",path:e}:e.includes("/scenes/")?{type:"scene",path:e}:e.includes("/objects/")?{type:"object",path:e,objectId:(n=e.split("/").pop())==null?void 0:n.replace(".json","")}:{type:"object",path:e}}hashString(e){let t=0;for(let n=0;n<e.length;n++){let a=e.charCodeAt(n);t=(t<<5)-t+a,t=t&t}return t.toString()}unwatch(e){this.callbacks.delete(e),this.fileHashes.delete(e)}stop(){this.pollingInterval!==null&&(clearInterval(this.pollingInterval),this.pollingInterval=null),this.callbacks.clear(),this.fileHashes.clear()}}});function Li(i){if(typeof window=="undefined")return;let e=typeof Ci!="undefined"&&!!Ci.hot,t=window.location.search.includes("hot-reload");if(!(e||t))return;let a=null,s=!1,r=null;if(t){r=new $e;let h=window.__configWatcher;h!=null&&h.stop&&h.stop(),window.__configWatcher=r}let o=new Set,l=h=>{var b,y;if(!r)return;let f=new Set;f.add("configs/engine/engine.runtime.json"),f.add("configs/engine/engine.assets.json"),f.add("configs/engine/engine.splash.json"),f.add("configs/scenes/scene.main.json");let m=(y=(b=h.scene)==null?void 0:b.objects)!=null?y:[];for(let v of m)v!=null&&v.object_config&&f.add(`configs/objects/${v.object_config}.json`);for(let v of o)f.has(v)||r.unwatch(v);for(let v of f)o.has(v)||r.watch(v,x=>g(x));o=f},c=new Set,p=!1,d=async h=>{let f=await Le(h),m=De(f,i.activeConfig.schemas),b=Je(m,i.activeConfig.schemas);b.valid||console.warn(`[HOT-RELOAD] ${h} validation errors:`,b.errors),await i.liveEditBridge.applyObjectConfig(h,m)};async function u(h){if(!s){s=!0;try{if(p||c.size===0){i.audioSystem.destroy();let f=await me("scene.main");i.setActiveConfig(f),i.gameObjectManager.updateConfig(f),i.CustomAssets.updateConfig(f),await i.CustomAssets.ready();let m=i.createAudioSystem(f);i.setAudioSystem(m),window.__audioSystem=m,await m.start(),i.liveEditBridge.rebuildIndexes(),l(f),console.log(`[GAME] Hot-reload complete (${h})`)}else{let f=Array.from(c);c.clear();for(let m of f)await d(m);console.log(`[GAME] Hot-reload updated objects: ${f.join(", ")}`)}}catch(f){console.warn("[GAME] Hot-reload failed:",f)}finally{s=!1,p=!1,c.clear()}}}function g(h){h.type==="object"&&h.objectId?c.add(h.objectId):p=!0,a&&window.clearTimeout(a),a=window.setTimeout(()=>{u(h.type)},120)}e&&Ci.hot.on("config-change",()=>{g({type:"hmr"})}),t&&(l(i.activeConfig),console.log(`[GAME] Hot-reload watcher enabled (${o.size} files)`))}var Ci,As=se(()=>{"use strict";Si();wi();Ci={}});var Ss={};qe(Ss,{ConfigWatcher:()=>$e,DefaultReloadStrategy:()=>St,applyDefaults:()=>De,diffConfigs:()=>Ei,loadAllObjectConfigs:()=>on,loadComponentSchemas:()=>rn,loadEngineConfig:()=>ln,loadGamePromptConfig:()=>vi,loadObjectCentricConfig:()=>me,loadObjectConfig:()=>Le,loadSceneConfig:()=>cn,rehydrateObject:()=>Ai,setupHotReload:()=>Li,toLegacyFormat:()=>xi,validateObjectConfig:()=>Je});var dn=se(()=>{"use strict";wi();Si();As()});var Cs={};qe(Cs,{makePanelDraggable:()=>Mi,makePanelResizable:()=>ki});function Mi(i,e,t){let n=t!=null?t:i.offsetParent;if(!n)return;e.style.cursor="move";let a=0,s=0,r=0,o=0,l=!1,c=d=>{if(!l)return;let u=d.clientX-a,g=d.clientY-s;i.style.left=`${r+u}px`,i.style.top=`${o+g}px`},p=()=>{l&&(l=!1,window.removeEventListener("pointermove",c),window.removeEventListener("pointerup",p))};e.addEventListener("pointerdown",d=>{if(d.button!==0)return;let u=d.target;if(u!=null&&u.closest("button, input, select, textarea"))return;d.preventDefault();let g=i.getBoundingClientRect(),h=n.getBoundingClientRect();r=Math.max(0,g.left-h.left),o=Math.max(0,g.top-h.top);let f=g.width,m=g.height,b=h.width,y=h.height;r=Math.min(r,b-f),o=Math.min(o,y-m),a=d.clientX,s=d.clientY,i.style.left=`${r}px`,i.style.top=`${o}px`,i.style.right="auto",i.style.bottom="auto",i.style.zIndex=String(++Io);let v=i.getBoundingClientRect();(v.left<0||v.top<0||v.right>window.innerWidth||v.bottom>window.innerHeight)&&(i.style.left="16px",i.style.top="72px",i.style.right="auto",i.style.bottom="auto"),l=!0,window.addEventListener("pointermove",c),window.addEventListener("pointerup",p)})}function ki(i,e,t){e.style.cursor="nwse-resize";let n=0,a=0,s=0,r=0,o=!1,l=p=>{if(!o)return;let d=p.clientX-s,u=p.clientY-r,g=Math.max(100,n+d),h=Math.max(100,a+u);i.style.width=`${g}px`,i.style.height=`${h}px`,t==null||t(g,h)},c=()=>{o&&(o=!1,window.removeEventListener("pointermove",l),window.removeEventListener("pointerup",c))};e.addEventListener("pointerdown",p=>{if(p.button!==0)return;p.preventDefault(),p.stopPropagation();let d=i.getBoundingClientRect();n=d.width,a=d.height,s=p.clientX,r=p.clientY,o=!0,window.addEventListener("pointermove",l),window.addEventListener("pointerup",c)})}var Io,Oi=se(()=>{"use strict";Io=3e3});var cr={};qe(cr,{AssetEditorModal:()=>sa});var sa,ra=se(()=>{"use strict";sa=class{constructor(){this.modal=null;this.currentObjectId=null;this.currentPath=null;this.currentAsset="";this.onApplyCallback=null}show(e,t,n,a){this.currentObjectId=e,this.currentPath=t,this.currentAsset=n,this.onApplyCallback=a,this.createModal(e,n),document.body.appendChild(this.modal),this.attachModalListeners()}createModal(e,t){let n=document.createElement("div");n.className="asset-editor-modal",n.innerHTML=`
3
2
  <div class="asset-editor-card">
4
3
  <div class="asset-editor-header">
5
4
  <div>
6
- <div class="asset-editor-title">Edit Asset: ${t}</div>
7
- <div class="asset-editor-subtitle">Current: ${i||"None"}</div>
5
+ <div class="asset-editor-title">Edit Asset: ${e}</div>
6
+ <div class="asset-editor-subtitle">Current: ${t||"None"}</div>
8
7
  </div>
9
8
  <button class="asset-editor-close" data-modal-close>\xD7</button>
10
9
  </div>
@@ -44,7 +43,7 @@
44
43
  <button class="debug-btn primary" data-modal-apply>Apply</button>
45
44
  </div>
46
45
  </div>
47
- `,this.modal=n}attachModalListeners(){if(!this.modal)return;this.modal.querySelectorAll("[data-modal-close]").forEach(s=>{s.addEventListener("click",()=>this.close())}),this.modal.querySelectorAll("[data-tab]").forEach(s=>{s.addEventListener("click",o=>{let c=o.target.dataset.tab;c&&this.switchTab(c)})});let n=this.modal.querySelector("[data-ai-generate]");n==null||n.addEventListener("click",()=>{this.openAiEditor("generate")});let r=this.modal.querySelector("[data-ai-edit]");r==null||r.addEventListener("click",()=>{this.openAiEditor("edit")});let a=this.modal.querySelector("[data-modal-apply]");a==null||a.addEventListener("click",()=>{this.apply()}),this.modal.addEventListener("click",s=>{s.target===this.modal&&this.close()})}switchTab(t){if(!this.modal)return;this.modal.querySelectorAll("[data-tab]").forEach(r=>{r.classList.toggle("active",r.getAttribute("data-tab")===t)}),this.modal.querySelectorAll("[data-tab-panel]").forEach(r=>{r.classList.toggle("active",r.getAttribute("data-tab-panel")===t)})}openAiEditor(t){let i=window.__openAiEditor;if(typeof i!="function"){alert("AI Editor not available. Please check your setup.");return}let n="";t==="edit"&&this.currentAsset?n=`Edit this image: ${this.currentObjectId}`:n=`Create an image for: ${this.currentObjectId}`,i(this.currentObjectId||"unknown",n,this.currentAsset,{path:this.currentPath,onApply:r=>{this.onApplyCallback&&this.onApplyCallback(r),this.close()}})}apply(){this.onApplyCallback&&this.onApplyCallback("library/placeholder.png"),this.close()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),this.modal=null,this.currentObjectId=null,this.currentPath=null,this.onApplyCallback=null}}});var l0={};an(l0,{COLORS:()=>We,ConfigWatcher:()=>Ht,DebugPanel:()=>rr,DefaultReloadStrategy:()=>bn,Handler:()=>Pe,PlayableLoadingScreen:()=>ss,PreviewShell:()=>ns,STROKE_WIDTH:()=>jg,THEME:()=>Dg,applyConfigOverride:()=>bt,applyConfigOverrides:()=>yt,applyConfigsToDisk:()=>hn,applyDefaults:()=>$t,baseLottie:()=>ws,bootstrap:()=>Zw,clearConfigOverrides:()=>vt,clearConfigOverridesForObject:()=>Ed,configOverrideManager:()=>Sd,createPreviewShell:()=>hc,deepClone:()=>ne,default:()=>zt,defaultPreset:()=>Nr,deviceGroups:()=>Vs,devicePresets:()=>Ws,diffConfigs:()=>Fs,exportConfigsAsJSON:()=>fn,getConfigOverrides:()=>de,getConfigStateSummary:()=>Or,getOverrideMode:()=>pn,getPresetById:()=>Ut,getPresetsByCategory:()=>Xm,loadAllObjectConfigs:()=>Rr,loadComponentSchemas:()=>Pr,loadEngineConfig:()=>jr,loadGamePromptConfig:()=>zs,loadObjectCentricConfig:()=>et,loadObjectConfig:()=>xt,loadSceneConfig:()=>Dr,rehydrateObject:()=>$s,removeConfigOverride:()=>Lr,resetToApplied:()=>gn,resetToOriginal:()=>Ir,setBootstrapDependencies:()=>Kw,setOverrideMode:()=>Rs,setupHotReload:()=>qs,setupLiveEditBridge:()=>rs,toLegacyFormat:()=>Ns,validateObjectConfig:()=>gi});module.exports=nm(l0);var ht={};function gr(e,t,i=!1){ht[e]||(ht[e]=[]),ht[e].push({fn:t,once:i})}function bs(e,t){if(ht[e]){if(!t){delete ht[e];return}ht[e]=ht[e].filter(i=>i.fn!==t)}}function mr(e,...t){let i=ht[e];if(i)for(let n of[...i])n.fn(...t),n.once&&bs(e,n.fn)}function be(e,t){gr(e,t,!0)}var ee=null,Ce=[],ui=null;function Pc(e){ee=e,Ce=[],ui!==null&&(clearTimeout(ui),ui=null)}function Rc(){var e,t,i;return{endpoint:(ee==null?void 0:ee.endpoint)||"",transport:(ee==null?void 0:ee.transport)||"beacon",batchSize:(e=ee==null?void 0:ee.batchSize)!=null?e:10,flushIntervalMs:(t=ee==null?void 0:ee.flushIntervalMs)!=null?t:300,maxQueue:(i=ee==null?void 0:ee.maxQueue)!=null?i:200,debug:!!(ee!=null&&ee.debug)}}async function Ic(e,t,i,n){let r=JSON.stringify(t);if(i==="beacon"&&typeof navigator!="undefined"&&typeof navigator.sendBeacon=="function")try{let a=navigator.sendBeacon(e,new Blob([r],{type:"application/json"}));n&&console.log("[handler.telemetry] beacon",a,t);return}catch(a){n&&console.warn("[handler.telemetry] beacon failed, fallback to fetch",a)}try{await fetch(e,{method:"POST",headers:{"Content-Type":"application/json"},body:r,keepalive:!0}),n&&console.log("[handler.telemetry] fetch",t)}catch(a){n&&console.warn("[handler.telemetry] fetch failed",a)}}function ys(e,t){let i=Rc();if(t&&i.endpoint){if(Ce.push(e),Ce.length>i.maxQueue&&(Ce=Ce.slice(Ce.length-i.maxQueue)),Ce.length>=i.batchSize){Mc();return}ui===null&&(ui=window.setTimeout(()=>{ui=null,Mc()},i.flushIntervalMs))}}async function Mc(){let e=Rc();if(!e.endpoint||Ce.length===0)return;let t=Ce.splice(0,e.batchSize);await Ic(e.endpoint,{events:t},e.transport,e.debug),Ce.length>0&&await Ic(e.endpoint,{events:Ce.splice(0,e.batchSize)},e.transport,e.debug)}function jc(e){return Math.max(0,Math.min(1,e))}function rm(e){let t=String(e!=null?e:"power2.out");if(t==="linear")return i=>i;if(t==="sine.inOut")return i=>.5-Math.cos(Math.PI*i)/2;if(t==="power2.out"||t==="easeOutQuad")return i=>1-(1-i)*(1-i);if(t.startsWith("back.out")){let i=t.match(/back\.out\(([\d.]+)\)/),n=i?Number(i[1]):1.8;return r=>1+(n+1)*Math.pow(r-1,3)+n*Math.pow(r-1,2)}return i=>1-(1-i)*(1-i)}function sn(){return typeof performance!="undefined"&&performance.now?performance.now():Date.now()}function am(e,t){let i=e==null?void 0:e[t];return typeof i=="number"?i:0}function Dc(e,t,i){try{e[t]=i}catch{}}function sm(e){let t=e==null?void 0:e.scale;if(!t)return null;let i=typeof t.x=="number"?t.x:1,n=typeof t.y=="number"?t.y:1;return{x:i,y:n}}function zc(e,t){let i=e==null?void 0:e.scale;if(i)try{typeof i.set=="function"?i.set(t.x,t.y):(typeof i.x=="number"&&(i.x=t.x),typeof i.y=="number"&&(i.y=t.y))}catch{}}function Nc(e,t){let i=sm(e);if(!i)return{from:null,to:null};let n=null,r=null;return typeof t.scale=="number"?(n=t.scale,r=t.scale):t.scale&&typeof t.scale=="object"&&(typeof t.scale.x=="number"&&(n=t.scale.x),typeof t.scale.y=="number"&&(r=t.scale.y)),typeof t.scaleX=="number"&&(n=t.scaleX),typeof t.scaleY=="number"&&(r=t.scaleY),n===null&&r===null?{from:null,to:null}:{from:{x:i.x,y:i.y},to:{x:n!=null?n:i.x,y:r!=null?r:i.y}}}function Bc(){let e=new Set,t=new WeakMap,i=null,n=()=>{if(i!=null)return;i=requestAnimationFrame(()=>{i=null,o(),e.size>0&&n()})},r=d=>{var p;e.add(d);let u=(p=t.get(d.target))!=null?p:new Set;u.add(d),t.set(d.target,u),n()},a=d=>{e.delete(d);let u=t.get(d.target);u&&(u.delete(d),u.size===0&&t.delete(d.target))},s=d=>{d.killed||(d.killed=!0,a(d))},o=()=>{var u,p;let d=sn();for(let f of Array.from(e)){if(f.killed||f.paused)continue;let g=d-f.startMs-f.delayMs;if(g<0)continue;let h=f.durationMs>0?g/f.durationMs:1,m=jc(h),b=f.repeat>=0?f.repeat+1:1,y=f.repeat>0?Math.min(Math.floor(h),b-1):0;if(f.repeat>0&&h>=1){let w=h-y;m=jc(w)}let v=f.ease(m);f.yoyo&&y%2===1&&(v=1-v);for(let w of f.props)Dc(f.target,w.key,w.from+(w.to-w.from)*v);f.scaleFrom&&f.scaleTo&&zc(f.target,{x:f.scaleFrom.x+(f.scaleTo.x-f.scaleFrom.x)*v,y:f.scaleFrom.y+(f.scaleTo.y-f.scaleFrom.y)*v});try{(u=f.onUpdate)==null||u.call(f)}catch{}if(h>=b){s(f);try{(p=f.onComplete)==null||p.call(f)}catch{}}}},l=(d,u,p)=>{var w;let f=Math.max(0,(typeof u.duration=="number"?u.duration:.5)*1e3),g=Math.max(0,(typeof u.delay=="number"?u.delay:0)*1e3+((w=p==null?void 0:p.delayMsOverride)!=null?w:0)),h=rm(u.ease),m=typeof u.repeat=="number"?Math.max(0,u.repeat|0):0,b=u.yoyo===!0,y=new Set(["duration","delay","ease","repeat","yoyo","onUpdate","onComplete","scale","scaleX","scaleY"]),v=[];for(let E of Object.keys(u)){if(y.has(E))continue;let A=u[E];typeof A=="number"&&v.push({key:E,from:am(d,E),to:A})}let x=Nc(d,u);return{target:d,startMs:sn(),delayMs:g,durationMs:f,ease:h,props:v,scaleFrom:x.from,scaleTo:x.to,repeat:m,yoyo:b,onUpdate:typeof u.onUpdate=="function"?u.onUpdate:void 0,onComplete:typeof u.onComplete=="function"?u.onComplete:void 0,killed:!1,paused:!1,pauseAtMs:null}},c={to(d,u){let p=l(d,u);return r(p),{kill:()=>s(p),pause:()=>{p.paused||(p.paused=!0,p.pauseAtMs=sn())},resume:()=>{var h;if(!p.paused)return;let f=(h=p.pauseAtMs)!=null?h:sn(),g=sn()-f;p.startMs+=g,p.paused=!1,p.pauseAtMs=null},isActive:()=>!p.killed&&!p.paused}},fromTo(d,u,p){return c.set(d,u),c.to(d,p)},set(d,u){if(!d||!u)return;for(let f of Object.keys(u)){let g=u[f];f==="scale"||f==="scaleX"||f==="scaleY"||typeof g=="number"&&Dc(d,f,g)}let p=Nc(d,u);p.to&&zc(d,p.to)},killTweensOf(d){let u=t.get(d);if(u)for(let p of Array.from(u))s(p)},timeline(d={}){let u=[],p=0,f=!1,g=[],h=y=>{if(typeof y=="number")return Math.max(0,y*1e3);let v=typeof y=="string"?y.trim():"";return v.startsWith("+=")?p+Math.max(0,Number(v.slice(2))*1e3||0):v?Math.max(0,Number(v)*1e3||0):p},m=y=>{u.push(y);let v=Math.max(0,(typeof y.vars.duration=="number"?y.vars.duration:.5)*1e3);p=Math.max(p,y.atMs+v)},b={to(y,v,x){return m({kind:"to",target:y,vars:v,atMs:h(x)}),b},fromTo(y,v,x,w){return m({kind:"fromTo",target:y,vars:x,from:v,atMs:h(w)}),b},play(){var y,v;if(f)return b;f=!0,g=[];for(let x of u)x.kind==="fromTo"&&c.set(x.target,(y=x.from)!=null?y:{}),g.push(c.to(x.target,{...x.vars,delay:x.atMs/1e3+((v=x.vars.delay)!=null?v:0)}));return b},pause(){for(let y of g)y.pause();return b},kill(){for(let y of g)y.kill();g=[],f=!1}};return d.paused||b.play(),b}};return c}function Fc(){if(typeof window=="undefined")return;let e=window;if(!e.gsap)try{e.gsap=Bc()}catch{}}var $c={name:"handler-playable-sdk",version:"0.3.34",type:"module",description:"Handler Playable SDK v0.1 with contract-aligned surface (root sandbox, canonical event envelope).",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./pixi":{types:"./dist/pixi/index.d.ts",import:"./dist/pixi/index.js",require:"./dist/pixi/index.cjs"},"./pixi/index.css":{import:"./dist/pixi/index.css",require:"./dist/pixi/index.css"},"./three":{types:"./dist/three/index.d.ts",import:"./dist/three/index.js",require:"./dist/three/index.cjs"},"./cli":{types:"./dist/cli/index.d.ts",import:"./dist/cli/index.js",require:"./dist/cli/index.cjs"}},bin:{"handler-student-helper":"./bin/student-helper.mjs","handler-validate":"./bin/validate.mjs","handler-sync-screens":"./bin/sync-screens.mjs","handler-brand-dna":"./bin/brand-dna.mjs","handler-setup-library":"./bin/setup-library.mjs","handler-screen-helper":"./bin/screen-helper.mjs"},scripts:{prebuild:"python3 src/preview/build-css.py",build:"tsup src/index.ts src/pixi/index.ts src/three/index.ts src/cli/index.ts --format cjs,esm --dts --clean --minify --external lottie-web && npm run create-mjs-symlinks && npm run postbuild-cli && npm run obfuscate && npm run postbuild",postbuild:"python3 src/preview/copy-css-to-dist.py","postbuild-cli":"cp src/cli/*.mjs dist/cli/ && chmod +x dist/cli/*.mjs && chmod +x bin/*.mjs","create-mjs-symlinks":"cd dist && ln -sf index.js index.mjs && cd pixi && ln -sf index.js index.mjs && cd ../three && ln -sf index.js index.mjs","build:dev":"tsup src/index.ts src/pixi/index.ts src/three/index.ts src/cli/index.ts --format cjs,esm --dts --clean --external lottie-web && npm run create-mjs-symlinks && npm run postbuild-cli",obfuscate:"javascript-obfuscator dist/pixi/index.js --output dist/pixi/index.js --config obfuscator.config.json && javascript-obfuscator dist/three/index.js --output dist/three/index.js --config obfuscator.config.json && javascript-obfuscator dist/cli/index.js --output dist/cli/index.js --config obfuscator.config.json && npm run obfuscate-cli","obfuscate-cli":'for file in dist/cli/*.mjs; do javascript-obfuscator "$file" --output "$file" --config obfuscator.config.json; done',lint:"eslint 'src/**/*.{ts,tsx}'",typecheck:"tsc --noEmit",prepublishOnly:"npm run build","publish:update":"node scripts/publish-and-update.cjs patch","publish:update:minor":"node scripts/publish-and-update.cjs minor","publish:update:major":"node scripts/publish-and-update.cjs major"},author:"Handler",license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/HandlerAIGames/handler-playable-sdk.git"},files:["dist","bin","LICENSE","README.md"],peerDependencies:{"lottie-web":"^5.0.0","pixi.js":"^8.0.0",three:"^0.182.0"},peerDependenciesMeta:{"pixi.js":{optional:!0},three:{optional:!0},"lottie-web":{optional:!0}},devDependencies:{"@types/three":"^0.182.0",eslint:"^9.39.2","javascript-obfuscator":"^5.1.0","pixi.js":"8.8.1",three:"^0.182.0","ts-node":"^10.9.2",tsup:"^8.4.0",typescript:"^5.7.2","typescript-eslint":"^8.53.0"},dependencies:{"@google/genai":"^1.35.0","@google/generative-ai":"^0.24.1",sharp:"^0.34.5"}};var ye=0,lm=ye++,Hc=ye++,Uc=ye++,qc=ye++,Gc=ye++,Wc=ye++,Vc=ye++,Yc=ye++,Kc=ye++,Xc=ye++,Zc=ye++,Jc=ye++,K=lm;function Qc(){return K===Hc}function ed(){return K===Uc}function td(){return K===qc}function id(){return K===Gc}function pi(){return K===Wc}function fi(){return K===Vc}function nd(){return K===Yc}function rd(){return K===Kc}function ad(){return K===Xc}function vs(){return K===Zc}function xs(){return K===Jc}function sd(){let e=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none",t=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed";if(e==="mraid")try{mraid.getState(),K=Hc;return}catch{}else if(e==="dapi")try{dapi.isReady(),K=Uc;return}catch{}if(t==="facebook")try{typeof FbPlayableAd!="undefined"&&(K=qc)}catch{}else if(t==="google")try{typeof ExitApi!="undefined"&&(K=Gc)}catch{}else if(t==="mintegral")window.gameReady&&(K=Wc);else if(t==="tapjoy")window.TJ_API&&(K=Vc);else if(t==="tiktok")window.openAppStore&&(K=Yc);else if(t==="smadex")try{window.smxTracking&&(K=Kc)}catch{}else if(t==="snapchat")try{window.ScPlayableAd&&(K=Xc)}catch{}else t==="vungle"?K=Zc:(e==="nucleo"||t==="nucleo")&&(K=Jc)}var br=di(require("lottie-web"),1),ws=br.default;typeof window!="undefined"&&(window.lottie=br.default,window.__baseLottie=br.default);var cm=require("pixi.js");var _s=require("pixi.js");var dm=null;function Es(e){dm=e}yr();Ss();var on=require("pixi.js");yr();var mm=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",ks=mm;if(typeof window!="undefined")try{let e=new XMLHttpRequest;if(e.open("GET","./build-settings.json",!1),e.send(),e.status===200&&e.responseText){let t=JSON.parse(e.responseText);t!=null&&t.buildMode&&(ks=t.buildMode,console.log(`[ObjectFactory] Build mode overridden by settings: ${ks}`))}}catch{}var mt=class{static async create(t,i,n){var l,c,d,u,p,f,g;console.log(`[ObjectFactory] create() called for: ${t}, __BUILD_MODE__: ${ks}`);let r=(l=i==null?void 0:i.render)==null?void 0:l.asset;if(!r){console.log(`[ObjectFactory] No asset definition for: ${t}, returning empty container`);let h=new on.Container;return this.applyTransform(h,i==null?void 0:i.transform),h}let a=(c=i==null?void 0:i.identity)==null?void 0:c.id;console.log(`[ObjectFactory] Calling AssetLoader.load() for: ${t}, configId: ${a}, type: ${r.type}, path: ${r.path}`);let s=await Bt.load(t,r,n,a);console.log(`[ObjectFactory] AssetLoader.load() completed for: ${t}, rawAsset type: ${(d=s==null?void 0:s.constructor)==null?void 0:d.name}`);let o;if(r.type==="image")console.log("[ObjectFactory] Creating Sprite from texture:",s,"for object:",t),o=new on.Sprite(s),console.log("[ObjectFactory] Created object:",o,"type:",(u=o==null?void 0:o.constructor)==null?void 0:u.name),this.applyTransform(o,i==null?void 0:i.transform);else if(r.type==="json")if(console.log("[ObjectFactory] JSON asset for",t,"rawAsset type:",(p=s==null?void 0:s.constructor)==null?void 0:p.name,s),s&&(((f=s.constructor)==null?void 0:f.name)==="Container"||s instanceof on.Container)){console.warn("[ObjectFactory] JSON asset is Container (from cache), reloading JSON directly");let h=[r.path,`/assets/${r.path}`,`assets/${r.path}`,`../assets/${r.path}`],m=!1;for(let b of h)try{let y=await fetch(b);if(y.ok){o=await y.json(),console.log("[ObjectFactory] Reloaded JSON directly from:",b,"type:",(g=o==null?void 0:o.constructor)==null?void 0:g.name),m=!0;break}}catch{continue}m||(console.error("[ObjectFactory] Failed to reload JSON from any path"),o=s)}else o=s;else o=s,o&&typeof o=="object"&&("x"in o||"position"in o)&&this.applyTransform(o,i==null?void 0:i.transform);return o}static applyTransform(t,i){var n,r,a,s;!i||!t||(i.position&&("x"in t&&"y"in t?(t.x=(n=i.position.x)!=null?n:0,t.y=(r=i.position.y)!=null?r:0):"position"in t&&t.position&&t.position.set((a=i.position.x)!=null?a:0,(s=i.position.y)!=null?s:0)),i.scale!==void 0&&"scale"in t&&t.scale&&(typeof t.scale=="object"&&"set"in t.scale?t.scale.set(i.scale):t.scale=i.scale),i.rotation!==void 0&&"rotation"in t&&(t.rotation=i.rotation),i.anchor&&"anchor"in t&&t.anchor&&Array.isArray(i.anchor)&&("set"in t.anchor?t.anchor.set(i.anchor[0],i.anchor[1]):(t.anchor.x=i.anchor[0],t.anchor.y=i.anchor[1])))}};var ln=class{constructor(){this.config=null}init(t){this.config=t}get(t){if(!this.config)throw new Error("RuntimeObjectRegistry not initialized. Call init() first.");return this.config.objects.get(t)}getAllIds(){if(!this.config)throw new Error("RuntimeObjectRegistry not initialized. Call init() first.");return Array.from(this.config.objects.keys())}has(t){return this.config?this.config.objects.has(t):!1}};var vm=di(require("pixi.js"),1);typeof window!="undefined"&&(window.__basePixi=vm);hi();var vr=require("pixi.js");hi();var Is=class{constructor(){this.instanceCache=new Map;this.readyPromise=null;this.app=null;this.registry=new ln}init(t,i){this.registry.init(t),this.app=i}updateConfig(t){this.registry.init(t),this.instanceCache.clear(),this.readyPromise=null}async ready(){this.readyPromise&&await this.readyPromise;let i=this.registry.getAllIds().filter(r=>!this.instanceCache.has(r));if(i.length===0)return;let n=async r=>{r.length&&(console.log("[Assets] Loading objects:",r),await Promise.all(r.map(async a=>{var o;let s=this.registry.get(a);if(!s){console.warn("[Assets] No config found for object:",a);return}try{let l=await mt.create(a,s,this.app);this.instanceCache.set(a,l),console.log("[Assets] Loaded object:",a,(o=l==null?void 0:l.constructor)==null?void 0:o.name)}catch(l){console.error("[Assets] Failed to load object:",a,l)}})))};return this.readyPromise=(async()=>{await n(i);let r=this.registry.getAllIds().filter(a=>!this.instanceCache.has(a));r.length>0&&(console.warn("[Assets] Retrying missing assets:",r),await n(r)),console.log("[Assets] Ready. Cached objects:",Array.from(this.instanceCache.keys()))})(),this.readyPromise}resetScene(){this.instanceCache.clear(),this.readyPromise=null}async reloadObject(t){let i=this.registry.get(t);if(i){let n=await mt.create(t,i,this.app);this.instanceCache.set(t,n)}}get(t){return this.instanceCache.get(t)}},xm=new Is,wm=new Proxy(xm,{get(e,t){if(t in e&&typeof e[t]=="function")return e[t].bind(e);if(e.get(t))return e.get(t)}});hi();var pd=require("pixi.js"),Ze={width:400,height:600,designWidth:400,scaleFactor:1},wr={scale:1,position:1},Ps=[];function Em(e,t,i,n,r,a,s){Ps.push({element:e,originalScale:a,positionHelper:t,heightPercent:r}),t(e,i,n,r,a,s,!1)}function Sm(){Ps.forEach(({element:e,originalScale:t,positionHelper:i,heightPercent:n})=>{let r=t*Ze.scaleFactor;i(e,Ze.width,Ze.height,n,r,!0,!1)})}function Ms(e,t){console.log(`[SCREEN] updateScreenState called: ${e}x${t}`),Ze.width=e,Ze.height=t,Ze.scaleFactor=Math.min(e/Ze.designWidth,1.15),wr.scale=Ze.scaleFactor,wr.position=1,console.log(`[SCREEN] Global multipliers - scale: ${wr.scale.toFixed(3)}`),Sm()}var dn={layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1,screen_scale_y:1},engine:{scale:1,background_scale:1.05,background_offset_y:0,background_alpha:.98,label_pulse_speed:3,label_pulse_intensity:.03}};function Am(e,t,i){let n=dn[e];n&&n[t]!==void 0&&(n[t]=i,console.log(`Updated ${e}.${t} = ${i}`))}function Cm(){return dn}var Tm={center:{x:.5,y:.5},"center-center":{x:.5,y:.5},middle:{x:.5,y:.5},"middle-center":{x:.5,y:.5},"top-left":{x:0,y:0},"top-center":{x:.5,y:0},"top-right":{x:1,y:0},"bottom-left":{x:0,y:1},"bottom-center":{x:.5,y:1},"bottom-right":{x:1,y:1},"left-center":{x:0,y:.5},"right-center":{x:1,y:.5},"center-left":{x:0,y:.5},"center-right":{x:1,y:.5},left:{x:0,y:.5},right:{x:1,y:.5},top:{x:.5,y:0},bottom:{x:.5,y:1}};function xr(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}function _r(e,t={x:.5,y:.5}){var i;if(Array.isArray(e))return{x:xr(e[0],t.x),y:xr(e[1],t.y)};if(e&&typeof e=="object"){let n=e;return{x:xr(n.x,t.x),y:xr(n.y,t.y)}}if(typeof e=="string"){let n=e.trim().toLowerCase();return(i=Tm[n])!=null?i:t}return t}function fd(e,t,i,n={}){var f,g,h,m,b,y;let r=_r(i),a=(f=n.inset)!=null?f:{},s=(g=n.padding)!=null?g:{x:0,y:0},o=((h=a.left)!=null?h:0)+s.x,l=((m=a.right)!=null?m:0)+s.x,c=((b=a.top)!=null?b:0)+s.y,d=((y=a.bottom)!=null?y:0)+s.y,u=Math.max(0,e-o-l),p=Math.max(0,t-c-d);return{x:o+u*r.x,y:c+p*r.y}}function hd(e,t,i,n={}){var h,m,b,y,v,x;let r=(h=n.inset)!=null?h:{},a=(m=n.padding)!=null?m:{x:0,y:0},s=((b=r.left)!=null?b:0)+a.x,o=((y=r.right)!=null?y:0)+a.x,l=((v=r.top)!=null?v:0)+a.y,c=((x=r.bottom)!=null?x:0)+a.y,d=Math.max(0,e-s-o),u=Math.max(0,t-l-c),p=_r(i,{x:.5,y:.5}),f=Math.min(Math.max(p.x,0),1),g=Math.min(Math.max(p.y,0),1);return{x:s+d*f,y:l+u*g}}if(typeof window!="undefined"){let e=window.innerWidth,t=window.innerHeight,i=()=>{let n=window.innerWidth,r=window.innerHeight;(n!==e||r!==t)&&(e=n,t=r,Ms(n,r))};window.addEventListener("resize",i),window.addEventListener("orientationchange",()=>{setTimeout(i,100)}),window.mraid&&(window.mraid.addEventListener("viewableChange",i),window.mraid.addEventListener("sizeChange",i)),Ms(window.innerWidth,window.innerHeight),window.updateDebugConfig=Am,window.getDebugConfig=Cm,window.copyConfig=Nm,window.applyConfig=cn,window.applyConfigForRatio=Bm,window.positionAtBottom=gd,window.positionAtTop=Om,window.positionAtCenter=Im,window.positionAtLeft=Mm,window.positionAtRight=Pm,window.positionAtBottomLeft=Rm,window.positionAtBottomRight=jm,window.positionAtTopLeft=Dm,window.positionAtTopRight=zm,window.applyPositionContract=Lm,console.log("\u{1F3AE} Debug Config Functions Available:"),console.log("\u2022 updateDebugConfig(category, key, value)"),console.log("\u2022 getDebugConfig()"),console.log("\u2022 copyConfig(presetName)"),console.log("\u2022 applyConfig(config)"),console.log("\u2022 applyConfigForRatio(width, height)"),console.log("\u{1F4CD} Positioning Helpers Available (with scale):"),console.log("\u2022 positionAtBottom(element, w, h, percent, scale)"),console.log("\u2022 positionAtTop(element, w, h, percent, scale)"),console.log("\u2022 positionAtCenter(element, w, h, offsetX, offsetY, scale)"),console.log("\u2022 positionAtLeft/Right(element, w, h, percent, scale)"),console.log("\u2022 Corner positions: BottomLeft/Right, TopLeft/Right (all with scale)"),console.log("\u2022 applyPositionContract(element, w, h, contract)"),console.log("Example: positionAtCenter(mySprite, 400, 600, 0, -50, 1.2)")}function Er(e,t,i=0){return e*t+i}function Sr(e,t,i=0){return e*(1-t)+i}function Ar(e,t,i=0){return e*t+i}function Cr(e,t,i=0){return e*(1-t)+i}function ve(e,t=0){return e/2+t}function km(e,t){return e*t}function Lm(e,t,i,n){var s,o,l,c,d,u,p,f,g,h,m,b,y,v,x,w,E,A,_,T;let r=0,a=0;switch(n.type){case"top":r=ve(t,(o=(s=n.offset)==null?void 0:s.x)!=null?o:0),a=Er(i,n.percent,(c=(l=n.offset)==null?void 0:l.y)!=null?c:0);break;case"bottom":r=ve(t,(u=(d=n.offset)==null?void 0:d.x)!=null?u:0),a=Sr(i,n.percent,(f=(p=n.offset)==null?void 0:p.y)!=null?f:0);break;case"left":r=Ar(t,n.percent,(h=(g=n.offset)==null?void 0:g.x)!=null?h:0),a=ve(i,(b=(m=n.offset)==null?void 0:m.y)!=null?b:0);break;case"right":r=Cr(t,n.percent,(v=(y=n.offset)==null?void 0:y.x)!=null?v:0),a=ve(i,(w=(x=n.offset)==null?void 0:x.y)!=null?w:0);break;case"center":r=ve(t,(A=(E=n.offset)==null?void 0:E.x)!=null?A:0),a=ve(i,(T=(_=n.offset)==null?void 0:_.y)!=null?T:0);break}e.position?e.position.set(r,a):(e.x=r,e.y=a),n.scale!==void 0&&n.scale!==1&&e.scale&&(typeof e.scale.set=="function"?e.scale.set(n.scale,n.scale):(e.scale.x=n.scale,e.scale.y=n.scale))}function gd(e,t,i,n=.2,r=1,a=!0,s=!1){let o=km(i,n),l=Sr(i,n/2);Je(e,ve(t),l);let c=a?r*Ze.scaleFactor:r;Qe(e,c),s&&!Ps.find(d=>d.element===e)&&Em(e,gd,t,i,n,r,a)}function Om(e,t,i,n=.1,r=1){Je(e,ve(t),Er(i,n)),Qe(e,r)}function Im(e,t,i,n=0,r=0,a=1){Je(e,ve(t,n),ve(i,r)),Qe(e,a)}function Mm(e,t,i,n=.1,r=1){Je(e,Ar(t,n),ve(i)),Qe(e,r)}function Pm(e,t,i,n=.1,r=1){Je(e,Cr(t,n),ve(i)),Qe(e,r)}function Rm(e,t,i,n=.05,r=.05,a=1){Je(e,Ar(t,r),Sr(i,n)),Qe(e,a)}function jm(e,t,i,n=.05,r=.05,a=1){Je(e,Cr(t,r),Sr(i,n)),Qe(e,a)}function Dm(e,t,i,n=.05,r=.05,a=1){Je(e,Ar(t,r),Er(i,n)),Qe(e,a)}function zm(e,t,i,n=.05,r=.05,a=1){Je(e,Cr(t,r),Er(i,n)),Qe(e,a)}function Je(e,t,i){e&&e.position?typeof e.position.set=="function"?e.position.set(t,i):(e.position.x=t,e.position.y=i):e&&(e.x=t,e.y=i)}function Qe(e,t){t!==1&&e&&e.scale&&(typeof e.scale.set=="function"?e.scale.set(t,t):e.scale.x!==void 0&&e.scale.y!==void 0&&(e.scale.x=t,e.scale.y=t))}var Ft={default:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1,screen_scale_y:1},engine:{scale:1,background_scale:1.05,background_offset_y:0,background_alpha:.98,label_pulse_speed:3,label_pulse_intensity:.03}},wide:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:.9,screen_scale_y:1.1},engine:{scale:1,background_scale:1.1,background_offset_y:0,background_alpha:.95,label_pulse_speed:3,label_pulse_intensity:.03}},square:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:.85,screen_scale_y:.85},engine:{scale:1,background_scale:1,background_offset_y:0,background_alpha:1,label_pulse_speed:3,label_pulse_intensity:.03}},tall:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1.1,screen_scale_y:.9},engine:{scale:1,background_scale:.95,background_offset_y:0,background_alpha:1,label_pulse_speed:3,label_pulse_intensity:.03}}};function Nm(e){return e&&Ft[e]?JSON.parse(JSON.stringify(Ft[e])):JSON.parse(JSON.stringify(dn))}function cn(e){Object.keys(e).forEach(t=>{let i=t;dn[i]&&e[i]&&Object.assign(dn[i],e[i])}),console.log("Config applied:",e)}function Bm(e,t){let i=e/t;i>1.6?(cn(Ft.wide),console.log("Applied WIDE config for ratio:",i)):i<.7?(cn(Ft.tall),console.log("Applied TALL config for ratio:",i)):i>.8&&i<1.2?(cn(Ft.square),console.log("Applied SQUARE config for ratio:",i)):(cn(Ft.default),console.log("Applied DEFAULT config for ratio:",i))}if(typeof window!="undefined"){let e=window;e.configPresets=Ft,e.resolveAnchorVec2=e.resolveAnchorVec2||_r,e.resolveScreenAnchorPoint=e.resolveScreenAnchorPoint||fd,e.resolveScreenRatioPoint=e.resolveScreenRatioPoint||hd}zr();function te(e,t){let i=(r,a)=>a===0?r:i(a,r%a),n=i(e,t);return`${e/n}:${t/n}`}var D_=[{id:"iphone-15-pro-max",label:"iPhone 15 Pro Max",width:430,height:932,category:"iphone",ratio:te(430,932)},{id:"iphone-15-pro",label:"iPhone 15 Pro",width:393,height:852,category:"iphone",ratio:te(393,852)},{id:"iphone-15",label:"iPhone 15",width:393,height:852,category:"iphone",ratio:te(393,852)},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"iphone",ratio:te(390,844)},{id:"iphone-se",label:"iPhone SE",width:375,height:667,category:"iphone",ratio:te(375,667)},{id:"iphone-12-mini",label:"iPhone 12 Mini",width:360,height:780,category:"iphone",ratio:te(360,780)}],z_=[{id:"pixel-8-pro",label:"Pixel 8 Pro",width:448,height:998,category:"android",ratio:te(448,998)},{id:"pixel-8",label:"Pixel 8",width:412,height:915,category:"android",ratio:te(412,915)},{id:"samsung-s24-ultra",label:"Samsung S24 Ultra",width:412,height:915,category:"android",ratio:te(412,915)},{id:"samsung-s24",label:"Samsung S24",width:360,height:780,category:"android",ratio:te(360,780)},{id:"samsung-a54",label:"Samsung A54",width:412,height:915,category:"android",ratio:te(412,915)},{id:"oneplus-12",label:"OnePlus 12",width:412,height:915,category:"android",ratio:te(412,915)}],N_=[{id:"ipad-pro-12",label:'iPad Pro 12.9"',width:1024,height:1366,category:"tablet",ratio:te(1024,1366)},{id:"ipad-pro-11",label:'iPad Pro 11"',width:834,height:1194,category:"tablet",ratio:te(834,1194)},{id:"ipad-air",label:"iPad Air",width:820,height:1180,category:"tablet",ratio:te(820,1180)},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"tablet",ratio:te(768,1024)},{id:"samsung-tab-s9",label:"Samsung Tab S9",width:800,height:1280,category:"tablet",ratio:te(800,1280)}],Gs=[{id:"playable-portrait",label:"Playable Portrait",width:320,height:480,category:"playable",ratio:"2:3",mraidScale:1},{id:"mraid-320x480",label:"MRAID 320\xD7480",width:320,height:480,category:"playable",ratio:"2:3",mraidScale:1},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"playable",ratio:te(390,844),mraidScale:.7},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"playable",ratio:te(768,1024),mraidScale:.7}];var Ws=[...Gs],Vs=[{category:"playable",label:"Playable Ad",devices:Gs}],Nr=Gs[0];function Ut(e){return Ws.find(t=>t.id===e)||Nr}function Xm(e){return Ws.filter(t=>t.category===e)}var Br=class{constructor(){this.root=null;this.listContainer=null;this.searchInput=null;this.selectedId=null;this.options=null;this.retryTimer=null;this.screenFilter="all"}getScreenFilterStorageKey(){return`handler_preview_screen_filter::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}render(){return`
46
+ `,this.modal=n}attachModalListeners(){if(!this.modal)return;this.modal.querySelectorAll("[data-modal-close]").forEach(r=>{r.addEventListener("click",()=>this.close())}),this.modal.querySelectorAll("[data-tab]").forEach(r=>{r.addEventListener("click",o=>{let c=o.target.dataset.tab;c&&this.switchTab(c)})});let n=this.modal.querySelector("[data-ai-generate]");n==null||n.addEventListener("click",()=>{this.openAiEditor("generate")});let a=this.modal.querySelector("[data-ai-edit]");a==null||a.addEventListener("click",()=>{this.openAiEditor("edit")});let s=this.modal.querySelector("[data-modal-apply]");s==null||s.addEventListener("click",()=>{this.apply()}),this.modal.addEventListener("click",r=>{r.target===this.modal&&this.close()})}switchTab(e){if(!this.modal)return;this.modal.querySelectorAll("[data-tab]").forEach(a=>{a.classList.toggle("active",a.getAttribute("data-tab")===e)}),this.modal.querySelectorAll("[data-tab-panel]").forEach(a=>{a.classList.toggle("active",a.getAttribute("data-tab-panel")===e)})}openAiEditor(e){let t=window.__openAiEditor;if(typeof t!="function"){alert("AI Editor not available. Please check your setup.");return}let n="";e==="edit"&&this.currentAsset?n=`Edit this image: ${this.currentObjectId}`:n=`Create an image for: ${this.currentObjectId}`,t(this.currentObjectId||"unknown",n,this.currentAsset,{path:this.currentPath,onApply:a=>{this.onApplyCallback&&this.onApplyCallback(a),this.close()}})}apply(){this.onApplyCallback&&this.onApplyCallback("library/placeholder.png"),this.close()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),this.modal=null,this.currentObjectId=null,this.currentPath=null,this.onApplyCallback=null}}});var pl={};qe(pl,{COLORS:()=>ce,ConfigWatcher:()=>$e,DebugPanel:()=>Mt,DefaultReloadStrategy:()=>St,Handler:()=>ne,PlayableLoadingScreen:()=>Fn,PreviewShell:()=>Nn,STROKE_WIDTH:()=>br,THEME:()=>yr,applyConfigOverride:()=>Ae,applyConfigOverrides:()=>Se,applyConfigsToDisk:()=>wt,applyDefaults:()=>De,baseLottie:()=>ii,bootstrap:()=>el,clearConfigOverrides:()=>Ce,clearConfigOverridesForObject:()=>vs,configOverrideManager:()=>xs,createPreviewShell:()=>ca,deepClone:()=>U,default:()=>Oe,defaultPreset:()=>pn,deviceGroups:()=>Pi,devicePresets:()=>_i,diffConfigs:()=>Ei,exportConfigsAsJSON:()=>xt,getConfigOverrides:()=>Y,getConfigStateSummary:()=>nn,getOverrideMode:()=>vt,getPresetById:()=>ze,getPresetsByCategory:()=>Oo,loadAllObjectConfigs:()=>on,loadComponentSchemas:()=>rn,loadEngineConfig:()=>ln,loadGamePromptConfig:()=>vi,loadObjectCentricConfig:()=>me,loadObjectConfig:()=>Le,loadSceneConfig:()=>cn,rehydrateObject:()=>Ai,removeConfigOverride:()=>tn,resetToApplied:()=>Et,resetToOriginal:()=>an,setBootstrapDependencies:()=>Zo,setOverrideMode:()=>mi,setupHotReload:()=>Li,setupLiveEditBridge:()=>Hn,toLegacyFormat:()=>xi,validateObjectConfig:()=>Je});module.exports=La(pl);var xe={};function Bt(i,e,t=!1){xe[i]||(xe[i]=[]),xe[i].push({fn:e,once:t})}function Qn(i,e){if(xe[i]){if(!e){delete xe[i];return}xe[i]=xe[i].filter(t=>t.fn!==e)}}function Ft(i,...e){let t=xe[i];if(t)for(let n of[...t])n.fn(...e),n.once&&Qn(i,n.fn)}function K(i,e){Bt(i,e,!0)}var F=null,Q=[],We=null;function Pa(i){F=i,Q=[],We!==null&&(clearTimeout(We),We=null)}function Ma(){var i,e,t;return{endpoint:(F==null?void 0:F.endpoint)||"",transport:(F==null?void 0:F.transport)||"beacon",batchSize:(i=F==null?void 0:F.batchSize)!=null?i:10,flushIntervalMs:(e=F==null?void 0:F.flushIntervalMs)!=null?e:300,maxQueue:(t=F==null?void 0:F.maxQueue)!=null?t:200,debug:!!(F!=null&&F.debug)}}async function Ta(i,e,t,n){let a=JSON.stringify(e);if(t==="beacon"&&typeof navigator!="undefined"&&typeof navigator.sendBeacon=="function")try{let s=navigator.sendBeacon(i,new Blob([a],{type:"application/json"}));n&&console.log("[handler.telemetry] beacon",s,e);return}catch(s){n&&console.warn("[handler.telemetry] beacon failed, fallback to fetch",s)}try{await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:a,keepalive:!0}),n&&console.log("[handler.telemetry] fetch",e)}catch(s){n&&console.warn("[handler.telemetry] fetch failed",s)}}function ei(i,e){let t=Ma();if(e&&t.endpoint){if(Q.push(i),Q.length>t.maxQueue&&(Q=Q.slice(Q.length-t.maxQueue)),Q.length>=t.batchSize){_a();return}We===null&&(We=window.setTimeout(()=>{We=null,_a()},t.flushIntervalMs))}}async function _a(){let i=Ma();if(!i.endpoint||Q.length===0)return;let e=Q.splice(0,i.batchSize);await Ta(i.endpoint,{events:e},i.transport,i.debug),Q.length>0&&await Ta(i.endpoint,{events:Q.splice(0,i.batchSize)},i.transport,i.debug)}function ka(i){return Math.max(0,Math.min(1,i))}function Nr(i){let e=String(i!=null?i:"power2.out");if(e==="linear")return t=>t;if(e==="sine.inOut")return t=>.5-Math.cos(Math.PI*t)/2;if(e==="power2.out"||e==="easeOutQuad")return t=>1-(1-t)*(1-t);if(e.startsWith("back.out")){let t=e.match(/back\.out\(([\d.]+)\)/),n=t?Number(t[1]):1.8;return a=>1+(n+1)*Math.pow(a-1,3)+n*Math.pow(a-1,2)}return t=>1-(1-t)*(1-t)}function gt(){return typeof performance!="undefined"&&performance.now?performance.now():Date.now()}function Hr(i,e){let t=i==null?void 0:i[e];return typeof t=="number"?t:0}function Oa(i,e,t){try{i[e]=t}catch{}}function Br(i){let e=i==null?void 0:i.scale;if(!e)return null;let t=typeof e.x=="number"?e.x:1,n=typeof e.y=="number"?e.y:1;return{x:t,y:n}}function Ia(i,e){let t=i==null?void 0:i.scale;if(t)try{typeof t.set=="function"?t.set(e.x,e.y):(typeof t.x=="number"&&(t.x=e.x),typeof t.y=="number"&&(t.y=e.y))}catch{}}function Ra(i,e){let t=Br(i);if(!t)return{from:null,to:null};let n=null,a=null;return typeof e.scale=="number"?(n=e.scale,a=e.scale):e.scale&&typeof e.scale=="object"&&(typeof e.scale.x=="number"&&(n=e.scale.x),typeof e.scale.y=="number"&&(a=e.scale.y)),typeof e.scaleX=="number"&&(n=e.scaleX),typeof e.scaleY=="number"&&(a=e.scaleY),n===null&&a===null?{from:null,to:null}:{from:{x:t.x,y:t.y},to:{x:n!=null?n:t.x,y:a!=null?a:t.y}}}function ja(){let i=new Set,e=new WeakMap,t=null,n=()=>{if(t!=null)return;t=requestAnimationFrame(()=>{t=null,o(),i.size>0&&n()})},a=p=>{var u;i.add(p);let d=(u=e.get(p.target))!=null?u:new Set;d.add(p),e.set(p.target,d),n()},s=p=>{i.delete(p);let d=e.get(p.target);d&&(d.delete(p),d.size===0&&e.delete(p.target))},r=p=>{p.killed||(p.killed=!0,s(p))},o=()=>{var d,u;let p=gt();for(let g of Array.from(i)){if(g.killed||g.paused)continue;let h=p-g.startMs-g.delayMs;if(h<0)continue;let f=g.durationMs>0?h/g.durationMs:1,m=ka(f),b=g.repeat>=0?g.repeat+1:1,y=g.repeat>0?Math.min(Math.floor(f),b-1):0;if(g.repeat>0&&f>=1){let E=f-y;m=ka(E)}let v=g.ease(m);g.yoyo&&y%2===1&&(v=1-v);for(let E of g.props)Oa(g.target,E.key,E.from+(E.to-E.from)*v);g.scaleFrom&&g.scaleTo&&Ia(g.target,{x:g.scaleFrom.x+(g.scaleTo.x-g.scaleFrom.x)*v,y:g.scaleFrom.y+(g.scaleTo.y-g.scaleFrom.y)*v});try{(d=g.onUpdate)==null||d.call(g)}catch{}if(f>=b){r(g);try{(u=g.onComplete)==null||u.call(g)}catch{}}}},l=(p,d,u)=>{var E;let g=Math.max(0,(typeof d.duration=="number"?d.duration:.5)*1e3),h=Math.max(0,(typeof d.delay=="number"?d.delay:0)*1e3+((E=u==null?void 0:u.delayMsOverride)!=null?E:0)),f=Nr(d.ease),m=typeof d.repeat=="number"?Math.max(0,d.repeat|0):0,b=d.yoyo===!0,y=new Set(["duration","delay","ease","repeat","yoyo","onUpdate","onComplete","scale","scaleX","scaleY"]),v=[];for(let w of Object.keys(d)){if(y.has(w))continue;let T=d[w];typeof T=="number"&&v.push({key:w,from:Hr(p,w),to:T})}let x=Ra(p,d);return{target:p,startMs:gt(),delayMs:h,durationMs:g,ease:f,props:v,scaleFrom:x.from,scaleTo:x.to,repeat:m,yoyo:b,onUpdate:typeof d.onUpdate=="function"?d.onUpdate:void 0,onComplete:typeof d.onComplete=="function"?d.onComplete:void 0,killed:!1,paused:!1,pauseAtMs:null}},c={to(p,d){let u=l(p,d);return a(u),{kill:()=>r(u),pause:()=>{u.paused||(u.paused=!0,u.pauseAtMs=gt())},resume:()=>{var f;if(!u.paused)return;let g=(f=u.pauseAtMs)!=null?f:gt(),h=gt()-g;u.startMs+=h,u.paused=!1,u.pauseAtMs=null},isActive:()=>!u.killed&&!u.paused}},fromTo(p,d,u){return c.set(p,d),c.to(p,u)},set(p,d){if(!p||!d)return;for(let g of Object.keys(d)){let h=d[g];g==="scale"||g==="scaleX"||g==="scaleY"||typeof h=="number"&&Oa(p,g,h)}let u=Ra(p,d);u.to&&Ia(p,u.to)},killTweensOf(p){let d=e.get(p);if(d)for(let u of Array.from(d))r(u)},timeline(p={}){let d=[],u=0,g=!1,h=[],f=y=>{if(typeof y=="number")return Math.max(0,y*1e3);let v=typeof y=="string"?y.trim():"";return v.startsWith("+=")?u+Math.max(0,Number(v.slice(2))*1e3||0):v?Math.max(0,Number(v)*1e3||0):u},m=y=>{d.push(y);let v=Math.max(0,(typeof y.vars.duration=="number"?y.vars.duration:.5)*1e3);u=Math.max(u,y.atMs+v)},b={to(y,v,x){return m({kind:"to",target:y,vars:v,atMs:f(x)}),b},fromTo(y,v,x,E){return m({kind:"fromTo",target:y,vars:x,from:v,atMs:f(E)}),b},play(){var y,v;if(g)return b;g=!0,h=[];for(let x of d)x.kind==="fromTo"&&c.set(x.target,(y=x.from)!=null?y:{}),h.push(c.to(x.target,{...x.vars,delay:x.atMs/1e3+((v=x.vars.delay)!=null?v:0)}));return b},pause(){for(let y of h)y.pause();return b},kill(){for(let y of h)y.kill();h=[],g=!1}};return p.paused||b.play(),b}};return c}function Da(){if(typeof window=="undefined")return;let i=window;if(!i.gsap)try{i.gsap=ja()}catch{}}var $a={name:"handler-playable-sdk",version:"0.3.36",type:"module",description:"Handler Playable SDK v0.1 with contract-aligned surface (root sandbox, canonical event envelope).",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./pixi":{types:"./dist/pixi/index.d.ts",import:"./dist/pixi/index.js",require:"./dist/pixi/index.cjs"},"./pixi/index.css":{import:"./dist/pixi/index.css",require:"./dist/pixi/index.css"},"./three":{types:"./dist/three/index.d.ts",import:"./dist/three/index.js",require:"./dist/three/index.cjs"},"./cli":{types:"./dist/cli/index.d.ts",import:"./dist/cli/index.js",require:"./dist/cli/index.cjs"}},bin:{"handler-student-helper":"./bin/student-helper.mjs","handler-validate":"./bin/validate.mjs","handler-sync-screens":"./bin/sync-screens.mjs","handler-brand-dna":"./bin/brand-dna.mjs","handler-setup-library":"./bin/setup-library.mjs","handler-screen-helper":"./bin/screen-helper.mjs"},scripts:{prebuild:"python3 src/preview/build-css.py",build:"tsup src/index.ts src/pixi/index.ts src/three/index.ts src/cli/index.ts --format cjs,esm --dts --clean --minify --external lottie-web && npm run create-mjs-symlinks && npm run postbuild-cli && npm run obfuscate && npm run postbuild",postbuild:"python3 src/preview/copy-css-to-dist.py","postbuild-cli":"cp src/cli/*.mjs dist/cli/ && chmod +x dist/cli/*.mjs && chmod +x bin/*.mjs","create-mjs-symlinks":"cd dist && ln -sf index.js index.mjs && cd pixi && ln -sf index.js index.mjs && cd ../three && ln -sf index.js index.mjs","build:dev":"tsup src/index.ts src/pixi/index.ts src/three/index.ts src/cli/index.ts --format cjs,esm --dts --clean --external lottie-web && npm run create-mjs-symlinks && npm run postbuild-cli",obfuscate:"javascript-obfuscator dist/pixi/index.js --output dist/pixi/index.js --config obfuscator.config.json && javascript-obfuscator dist/three/index.js --output dist/three/index.js --config obfuscator.config.json && javascript-obfuscator dist/cli/index.js --output dist/cli/index.js --config obfuscator.config.json && npm run obfuscate-cli","obfuscate-cli":'for file in dist/cli/*.mjs; do javascript-obfuscator "$file" --output "$file" --config obfuscator.config.json; done',lint:"eslint 'src/**/*.{ts,tsx}'",typecheck:"tsc --noEmit",prepublishOnly:"npm run build","publish:update":"node scripts/publish-and-update.cjs patch","publish:update:minor":"node scripts/publish-and-update.cjs minor","publish:update:major":"node scripts/publish-and-update.cjs major"},author:"Handler",license:"MIT",publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/HandlerAIGames/handler-playable-sdk.git"},files:["dist","bin","LICENSE","README.md"],peerDependencies:{"lottie-web":"^5.0.0","pixi.js":"^8.0.0",three:"^0.182.0"},peerDependenciesMeta:{"pixi.js":{optional:!0},three:{optional:!0},"lottie-web":{optional:!0}},devDependencies:{"@types/three":"^0.182.0",eslint:"^9.39.2","javascript-obfuscator":"^5.1.0","pixi.js":"8.8.1",three:"^0.182.0","ts-node":"^10.9.2",tsup:"^8.4.0",typescript:"^5.7.2","typescript-eslint":"^8.53.0"},dependencies:{"@google/genai":"^1.35.0","@google/generative-ai":"^0.24.1",jszip:"^3.10.1",sharp:"^0.34.5"}};var X=0,Gr=X++,za=X++,Na=X++,Ha=X++,Ba=X++,Fa=X++,Ga=X++,Ua=X++,qa=X++,Va=X++,Wa=X++,Ya=X++,H=Gr;function Ka(){return H===za}function Xa(){return H===Na}function Ja(){return H===Ha}function Za(){return H===Ba}function Ye(){return H===Fa}function Ke(){return H===Ga}function Qa(){return H===Ua}function es(){return H===qa}function ts(){return H===Va}function ti(){return H===Wa}function ni(){return H===Ya}function ns(){let i=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none",e=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed";if(i==="mraid")try{mraid.getState(),H=za;return}catch{}else if(i==="dapi")try{dapi.isReady(),H=Na;return}catch{}if(e==="facebook")try{typeof FbPlayableAd!="undefined"&&(H=Ha)}catch{}else if(e==="google")try{typeof ExitApi!="undefined"&&(H=Ba)}catch{}else if(e==="mintegral")window.gameReady&&(H=Fa);else if(e==="tapjoy")window.TJ_API&&(H=Ga);else if(e==="tiktok")window.openAppStore&&(H=Ua);else if(e==="smadex")try{window.smxTracking&&(H=qa)}catch{}else if(e==="snapchat")try{window.ScPlayableAd&&(H=Va)}catch{}else e==="vungle"?H=Wa:(i==="nucleo"||e==="nucleo")&&(H=Ya)}var Gt=Ve(require("lottie-web"),1),ii=Gt.default;typeof window!="undefined"&&(window.lottie=Gt.default,window.__baseLottie=Gt.default);var Ur=require("pixi.js");var ai=require("pixi.js");var qr=null;function si(i){qr=i}Ut();ri();var ft=require("pixi.js");Ut();var Jr=typeof __BUILD_MODE__!="undefined"?__BUILD_MODE__:"undefined",di=Jr;if(typeof window!="undefined")try{let i=new XMLHttpRequest;if(i.open("GET","./build-settings.json",!1),i.send(),i.status===200&&i.responseText){let e=JSON.parse(i.responseText);e!=null&&e.buildMode&&(di=e.buildMode,console.log(`[ObjectFactory] Build mode overridden by settings: ${di}`))}}catch{}var Ee=class{static async create(e,t,n){var l,c,p,d,u,g,h;console.log(`[ObjectFactory] create() called for: ${e}, __BUILD_MODE__: ${di}`);let a=(l=t==null?void 0:t.render)==null?void 0:l.asset;if(!a){console.log(`[ObjectFactory] No asset definition for: ${e}, returning empty container`);let f=new ft.Container;return this.applyTransform(f,t==null?void 0:t.transform,t),f}let s=(c=t==null?void 0:t.identity)==null?void 0:c.id;console.log(`[ObjectFactory] Calling AssetLoader.load() for: ${e}, configId: ${s}, type: ${a.type}, path: ${a.path}`);let r=await Re.load(e,a,n,s);console.log(`[ObjectFactory] AssetLoader.load() completed for: ${e}, rawAsset type: ${(p=r==null?void 0:r.constructor)==null?void 0:p.name}`);let o;if(a.type==="image")console.log("[ObjectFactory] Creating Sprite from texture:",r,"for object:",e),o=new ft.Sprite(r),console.log("[ObjectFactory] Created object:",o,"type:",(d=o==null?void 0:o.constructor)==null?void 0:d.name),this.applyTransform(o,t==null?void 0:t.transform,t);else if(a.type==="json")if(console.log("[ObjectFactory] JSON asset for",e,"rawAsset type:",(u=r==null?void 0:r.constructor)==null?void 0:u.name,r),r&&(((g=r.constructor)==null?void 0:g.name)==="Container"||r instanceof ft.Container)){console.warn("[ObjectFactory] JSON asset is Container (from cache), reloading JSON directly");let f=[a.path,`/assets/${a.path}`,`assets/${a.path}`,`../assets/${a.path}`],m=!1;for(let b of f)try{let y=await fetch(b);if(y.ok){o=await y.json(),console.log("[ObjectFactory] Reloaded JSON directly from:",b,"type:",(h=o==null?void 0:o.constructor)==null?void 0:h.name),m=!0;break}}catch{continue}m||(console.error("[ObjectFactory] Failed to reload JSON from any path"),o=r)}else o=r;else o=r,o&&typeof o=="object"&&("x"in o||"position"in o)&&this.applyTransform(o,t==null?void 0:t.transform,t);return o}static applyTransform(e,t,n){var a,s,r,o,l;if(!(!t||!e)){if(t.position&&("x"in e&&"y"in e?(e.x=(a=t.position.x)!=null?a:0,e.y=(s=t.position.y)!=null?s:0):"position"in e&&e.position&&e.position.set((r=t.position.x)!=null?r:0,(o=t.position.y)!=null?o:0)),t.scale!==void 0){let c=(l=n==null?void 0:n.identity)==null?void 0:l.category,p=c==="ui"||c==="environment"?.2:1,d=t.scale*p;"scale"in e&&e.scale&&(typeof e.scale=="object"&&"set"in e.scale?e.scale.set(d):e.scale=d)}t.rotation!==void 0&&"rotation"in e&&(e.rotation=t.rotation),t.anchor&&"anchor"in e&&e.anchor&&Array.isArray(t.anchor)&&("set"in e.anchor?e.anchor.set(t.anchor[0],t.anchor[1]):(e.anchor.x=t.anchor[0],e.anchor.y=t.anchor[1]))}}};var ht=class{constructor(){this.config=null}init(e){this.config=e}get(e){if(!this.config)throw new Error("RuntimeObjectRegistry not initialized. Call init() first.");return this.config.objects.get(e)}getAllIds(){if(!this.config)throw new Error("RuntimeObjectRegistry not initialized. Call init() first.");return Array.from(this.config.objects.keys())}has(e){return this.config?this.config.objects.has(e):!1}};var eo=Ve(require("pixi.js"),1);typeof window!="undefined"&&(window.__basePixi=eo);Xe();var qt=require("pixi.js");Xe();var gi=class{constructor(){this.instanceCache=new Map;this.readyPromise=null;this.app=null;this.registry=new ht}init(e,t){this.registry.init(e),this.app=t}updateConfig(e){this.registry.init(e),this.instanceCache.clear(),this.readyPromise=null}async ready(){this.readyPromise&&await this.readyPromise;let t=this.registry.getAllIds().filter(a=>!this.instanceCache.has(a));if(t.length===0)return;let n=async a=>{a.length&&(console.log("[Assets] Loading objects:",a),await Promise.all(a.map(async s=>{var o;let r=this.registry.get(s);if(!r){console.warn("[Assets] No config found for object:",s);return}try{let l=await Ee.create(s,r,this.app);this.instanceCache.set(s,l),console.log("[Assets] Loaded object:",s,(o=l==null?void 0:l.constructor)==null?void 0:o.name)}catch(l){console.error("[Assets] Failed to load object:",s,l)}})))};return this.readyPromise=(async()=>{await n(t);let a=this.registry.getAllIds().filter(s=>!this.instanceCache.has(s));a.length>0&&(console.warn("[Assets] Retrying missing assets:",a),await n(a)),console.log("[Assets] Ready. Cached objects:",Array.from(this.instanceCache.keys()))})(),this.readyPromise}resetScene(){this.instanceCache.clear(),this.readyPromise=null}async reloadObject(e){let t=this.registry.get(e);if(t){let n=await Ee.create(e,t,this.app);this.instanceCache.set(e,n)}}get(e){return this.instanceCache.get(e)}},to=new gi,no=new Proxy(to,{get(i,e){if(e in i&&typeof i[e]=="function")return i[e].bind(i);if(i.get(e))return i.get(e)}});Xe();var ls=require("pixi.js"),ge={width:400,height:600,designWidth:400,scaleFactor:1},Wt={scale:1,position:1},hi=[];function ao(i,e,t,n,a,s,r){hi.push({element:i,originalScale:s,positionHelper:e,heightPercent:a}),e(i,t,n,a,s,r,!1)}function so(){hi.forEach(({element:i,originalScale:e,positionHelper:t,heightPercent:n})=>{let a=e*ge.scaleFactor;t(i,ge.width,ge.height,n,a,!0,!1)})}function fi(i,e){console.log(`[SCREEN] updateScreenState called: ${i}x${e}`),ge.width=i,ge.height=e,ge.scaleFactor=Math.min(i/ge.designWidth,1.15),Wt.scale=ge.scaleFactor,Wt.position=1,console.log(`[SCREEN] Global multipliers - scale: ${Wt.scale.toFixed(3)}`),so()}var bt={layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1,screen_scale_y:1},engine:{scale:1,background_scale:1.05,background_offset_y:0,background_alpha:.98,label_pulse_speed:3,label_pulse_intensity:.03}};function ro(i,e,t){let n=bt[i];n&&n[e]!==void 0&&(n[e]=t,console.log(`Updated ${i}.${e} = ${t}`))}function oo(){return bt}var lo={center:{x:.5,y:.5},"center-center":{x:.5,y:.5},middle:{x:.5,y:.5},"middle-center":{x:.5,y:.5},"top-left":{x:0,y:0},"top-center":{x:.5,y:0},"top-right":{x:1,y:0},"bottom-left":{x:0,y:1},"bottom-center":{x:.5,y:1},"bottom-right":{x:1,y:1},"left-center":{x:0,y:.5},"right-center":{x:1,y:.5},"center-left":{x:0,y:.5},"center-right":{x:1,y:.5},left:{x:0,y:.5},right:{x:1,y:.5},top:{x:.5,y:0},bottom:{x:.5,y:1}};function Vt(i,e){return typeof i=="number"&&Number.isFinite(i)?i:e}function Yt(i,e={x:.5,y:.5}){var t;if(Array.isArray(i))return{x:Vt(i[0],e.x),y:Vt(i[1],e.y)};if(i&&typeof i=="object"){let n=i;return{x:Vt(n.x,e.x),y:Vt(n.y,e.y)}}if(typeof i=="string"){let n=i.trim().toLowerCase();return(t=lo[n])!=null?t:e}return e}function cs(i,e,t,n={}){var g,h,f,m,b,y;let a=Yt(t),s=(g=n.inset)!=null?g:{},r=(h=n.padding)!=null?h:{x:0,y:0},o=((f=s.left)!=null?f:0)+r.x,l=((m=s.right)!=null?m:0)+r.x,c=((b=s.top)!=null?b:0)+r.y,p=((y=s.bottom)!=null?y:0)+r.y,d=Math.max(0,i-o-l),u=Math.max(0,e-c-p);return{x:o+d*a.x,y:c+u*a.y}}function ds(i,e,t,n={}){var f,m,b,y,v,x;let a=(f=n.inset)!=null?f:{},s=(m=n.padding)!=null?m:{x:0,y:0},r=((b=a.left)!=null?b:0)+s.x,o=((y=a.right)!=null?y:0)+s.x,l=((v=a.top)!=null?v:0)+s.y,c=((x=a.bottom)!=null?x:0)+s.y,p=Math.max(0,i-r-o),d=Math.max(0,e-l-c),u=Yt(t,{x:.5,y:.5}),g=Math.min(Math.max(u.x,0),1),h=Math.min(Math.max(u.y,0),1);return{x:r+p*g,y:l+d*h}}if(typeof window!="undefined"){let i=window.innerWidth,e=window.innerHeight,t=()=>{let n=window.innerWidth,a=window.innerHeight;(n!==i||a!==e)&&(i=n,e=a,fi(n,a))};window.addEventListener("resize",t),window.addEventListener("orientationchange",()=>{setTimeout(t,100)}),window.mraid&&(window.mraid.addEventListener("viewableChange",t),window.mraid.addEventListener("sizeChange",t)),fi(window.innerWidth,window.innerHeight),window.updateDebugConfig=ro,window.getDebugConfig=oo,window.copyConfig=xo,window.applyConfig=mt,window.applyConfigForRatio=wo,window.positionAtBottom=ps,window.positionAtTop=uo,window.positionAtCenter=go,window.positionAtLeft=fo,window.positionAtRight=ho,window.positionAtBottomLeft=mo,window.positionAtBottomRight=bo,window.positionAtTopLeft=yo,window.positionAtTopRight=vo,window.applyPositionContract=po,console.log("\u{1F3AE} Debug Config Functions Available:"),console.log("\u2022 updateDebugConfig(category, key, value)"),console.log("\u2022 getDebugConfig()"),console.log("\u2022 copyConfig(presetName)"),console.log("\u2022 applyConfig(config)"),console.log("\u2022 applyConfigForRatio(width, height)"),console.log("\u{1F4CD} Positioning Helpers Available (with scale):"),console.log("\u2022 positionAtBottom(element, w, h, percent, scale)"),console.log("\u2022 positionAtTop(element, w, h, percent, scale)"),console.log("\u2022 positionAtCenter(element, w, h, offsetX, offsetY, scale)"),console.log("\u2022 positionAtLeft/Right(element, w, h, percent, scale)"),console.log("\u2022 Corner positions: BottomLeft/Right, TopLeft/Right (all with scale)"),console.log("\u2022 applyPositionContract(element, w, h, contract)"),console.log("Example: positionAtCenter(mySprite, 400, 600, 0, -50, 1.2)")}function Kt(i,e,t=0){return i*e+t}function Xt(i,e,t=0){return i*(1-e)+t}function Jt(i,e,t=0){return i*e+t}function Zt(i,e,t=0){return i*(1-e)+t}function J(i,e=0){return i/2+e}function co(i,e){return i*e}function po(i,e,t,n){var r,o,l,c,p,d,u,g,h,f,m,b,y,v,x,E,w,T,S,O;let a=0,s=0;switch(n.type){case"top":a=J(e,(o=(r=n.offset)==null?void 0:r.x)!=null?o:0),s=Kt(t,n.percent,(c=(l=n.offset)==null?void 0:l.y)!=null?c:0);break;case"bottom":a=J(e,(d=(p=n.offset)==null?void 0:p.x)!=null?d:0),s=Xt(t,n.percent,(g=(u=n.offset)==null?void 0:u.y)!=null?g:0);break;case"left":a=Jt(e,n.percent,(f=(h=n.offset)==null?void 0:h.x)!=null?f:0),s=J(t,(b=(m=n.offset)==null?void 0:m.y)!=null?b:0);break;case"right":a=Zt(e,n.percent,(v=(y=n.offset)==null?void 0:y.x)!=null?v:0),s=J(t,(E=(x=n.offset)==null?void 0:x.y)!=null?E:0);break;case"center":a=J(e,(T=(w=n.offset)==null?void 0:w.x)!=null?T:0),s=J(t,(O=(S=n.offset)==null?void 0:S.y)!=null?O:0);break}i.position?i.position.set(a,s):(i.x=a,i.y=s),n.scale!==void 0&&n.scale!==1&&i.scale&&(typeof i.scale.set=="function"?i.scale.set(n.scale,n.scale):(i.scale.x=n.scale,i.scale.y=n.scale))}function ps(i,e,t,n=.2,a=1,s=!0,r=!1){let o=co(t,n),l=Xt(t,n/2);fe(i,J(e),l);let c=s?a*ge.scaleFactor:a;he(i,c),r&&!hi.find(p=>p.element===i)&&ao(i,ps,e,t,n,a,s)}function uo(i,e,t,n=.1,a=1){fe(i,J(e),Kt(t,n)),he(i,a)}function go(i,e,t,n=0,a=0,s=1){fe(i,J(e,n),J(t,a)),he(i,s)}function fo(i,e,t,n=.1,a=1){fe(i,Jt(e,n),J(t)),he(i,a)}function ho(i,e,t,n=.1,a=1){fe(i,Zt(e,n),J(t)),he(i,a)}function mo(i,e,t,n=.05,a=.05,s=1){fe(i,Jt(e,a),Xt(t,n)),he(i,s)}function bo(i,e,t,n=.05,a=.05,s=1){fe(i,Zt(e,a),Xt(t,n)),he(i,s)}function yo(i,e,t,n=.05,a=.05,s=1){fe(i,Jt(e,a),Kt(t,n)),he(i,s)}function vo(i,e,t,n=.05,a=.05,s=1){fe(i,Zt(e,a),Kt(t,n)),he(i,s)}function fe(i,e,t){i&&i.position?typeof i.position.set=="function"?i.position.set(e,t):(i.position.x=e,i.position.y=t):i&&(i.x=e,i.y=t)}function he(i,e){e!==1&&i&&i.scale&&(typeof i.scale.set=="function"?i.scale.set(e,e):i.scale.x!==void 0&&i.scale.y!==void 0&&(i.scale.x=e,i.scale.y=e))}var je={default:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1,screen_scale_y:1},engine:{scale:1,background_scale:1.05,background_offset_y:0,background_alpha:.98,label_pulse_speed:3,label_pulse_intensity:.03}},wide:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:.9,screen_scale_y:1.1},engine:{scale:1,background_scale:1.1,background_offset_y:0,background_alpha:.95,label_pulse_speed:3,label_pulse_intensity:.03}},square:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:.85,screen_scale_y:.85},engine:{scale:1,background_scale:1,background_offset_y:0,background_alpha:1,label_pulse_speed:3,label_pulse_intensity:.03}},tall:{layout:{scale_multiplier:1,position_offset:{x:0,y:0},debug_rect_visible:!0,debug_rect_color:16711680,debug_rect_thickness:4,debug_rect_scale_x:1,debug_rect_scale_y:1,screen_scale_x:1.1,screen_scale_y:.9},engine:{scale:1,background_scale:.95,background_offset_y:0,background_alpha:1,label_pulse_speed:3,label_pulse_intensity:.03}}};function xo(i){return i&&je[i]?JSON.parse(JSON.stringify(je[i])):JSON.parse(JSON.stringify(bt))}function mt(i){Object.keys(i).forEach(e=>{let t=e;bt[t]&&i[t]&&Object.assign(bt[t],i[t])}),console.log("Config applied:",i)}function wo(i,e){let t=i/e;t>1.6?(mt(je.wide),console.log("Applied WIDE config for ratio:",t)):t<.7?(mt(je.tall),console.log("Applied TALL config for ratio:",t)):t>.8&&t<1.2?(mt(je.square),console.log("Applied SQUARE config for ratio:",t)):(mt(je.default),console.log("Applied DEFAULT config for ratio:",t))}if(typeof window!="undefined"){let i=window;i.configPresets=je,i.resolveAnchorVec2=i.resolveAnchorVec2||Yt,i.resolveScreenAnchorPoint=i.resolveScreenAnchorPoint||cs,i.resolveScreenRatioPoint=i.resolveScreenRatioPoint||ds}dn();function G(i,e){let t=(a,s)=>s===0?a:t(s,a%s),n=t(i,e);return`${i/n}:${e/n}`}var Nc=[{id:"iphone-15-pro-max",label:"iPhone 15 Pro Max",width:430,height:932,category:"iphone",ratio:G(430,932)},{id:"iphone-15-pro",label:"iPhone 15 Pro",width:393,height:852,category:"iphone",ratio:G(393,852)},{id:"iphone-15",label:"iPhone 15",width:393,height:852,category:"iphone",ratio:G(393,852)},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"iphone",ratio:G(390,844)},{id:"iphone-se",label:"iPhone SE",width:375,height:667,category:"iphone",ratio:G(375,667)},{id:"iphone-12-mini",label:"iPhone 12 Mini",width:360,height:780,category:"iphone",ratio:G(360,780)}],Hc=[{id:"pixel-8-pro",label:"Pixel 8 Pro",width:448,height:998,category:"android",ratio:G(448,998)},{id:"pixel-8",label:"Pixel 8",width:412,height:915,category:"android",ratio:G(412,915)},{id:"samsung-s24-ultra",label:"Samsung S24 Ultra",width:412,height:915,category:"android",ratio:G(412,915)},{id:"samsung-s24",label:"Samsung S24",width:360,height:780,category:"android",ratio:G(360,780)},{id:"samsung-a54",label:"Samsung A54",width:412,height:915,category:"android",ratio:G(412,915)},{id:"oneplus-12",label:"OnePlus 12",width:412,height:915,category:"android",ratio:G(412,915)}],Bc=[{id:"ipad-pro-12",label:'iPad Pro 12.9"',width:1024,height:1366,category:"tablet",ratio:G(1024,1366)},{id:"ipad-pro-11",label:'iPad Pro 11"',width:834,height:1194,category:"tablet",ratio:G(834,1194)},{id:"ipad-air",label:"iPad Air",width:820,height:1180,category:"tablet",ratio:G(820,1180)},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"tablet",ratio:G(768,1024)},{id:"samsung-tab-s9",label:"Samsung Tab S9",width:800,height:1280,category:"tablet",ratio:G(800,1280)}],Ti=[{id:"playable-portrait",label:"Playable Portrait",width:320,height:480,category:"playable",ratio:"2:3",mraidScale:1},{id:"mraid-320x480",label:"MRAID 320\xD7480",width:320,height:480,category:"playable",ratio:"2:3",mraidScale:1},{id:"iphone-14",label:"iPhone 14",width:390,height:844,category:"playable",ratio:G(390,844),mraidScale:.7},{id:"ipad-mini",label:"iPad Mini",width:768,height:1024,category:"playable",ratio:G(768,1024),mraidScale:.7}];var _i=[...Ti],Pi=[{category:"playable",label:"Playable Ad",devices:Ti}],pn=Ti[0];function ze(i){return _i.find(e=>e.id===i)||pn}function Oo(i){return _i.filter(e=>e.category===i)}var un=class{constructor(){this.root=null;this.listContainer=null;this.searchInput=null;this.selectedId=null;this.options=null;this.retryTimer=null;this.screenFilter="all"}getScreenFilterStorageKey(){return`handler_preview_screen_filter::${typeof window!="undefined"&&window.__HANDLER_PROJECT_ID||"default"}`}render(){return`
48
47
  <div class="scene-panel scene-objects panel-accent-teal" data-panel="scene-objects" style="left:16px; top:72px;">
49
48
  <div class="scene-panel-header" data-panel-handle>
50
49
  <div class="panel-title">
@@ -55,6 +54,11 @@
55
54
  <button class="scene-panel-toggle" type="button" data-panel-toggle>\u25BE</button>
56
55
  </div>
57
56
  </div>
57
+ <div class="scene-breadcrumbs" data-breadcrumbs style="display: none;">
58
+ <span class="breadcrumb-item" data-breadcrumb-screen>\u2014</span>
59
+ <span class="breadcrumb-separator">\u203A</span>
60
+ <span class="breadcrumb-item" data-breadcrumb-object>\u2014</span>
61
+ </div>
58
62
  <div class="scene-panel-body">
59
63
  <div class="scene-panel-search">
60
64
  <input type="text" id="scene-object-search" placeholder="Search ids, tags, UI">
@@ -72,181 +76,79 @@
72
76
  <div class="scene-object-list" data-object-list></div>
73
77
  </div>
74
78
  </div>
75
- `}initialize(t,i){var r,a,s,o,l;this.options=i,this.root=t.querySelector('[data-panel="scene-objects"]'),this.listContainer=(r=this.root)==null?void 0:r.querySelector("[data-object-list]"),this.searchInput=(a=this.root)==null?void 0:a.querySelector("#scene-object-search"),(s=this.searchInput)==null||s.addEventListener("input",()=>this.refreshObjects());let n=(o=this.root)==null?void 0:o.querySelector("#scene-screen-filter");if(n){try{let c=window.localStorage.getItem(this.getScreenFilterStorageKey());c&&(this.screenFilter=c)}catch{}n.value=this.screenFilter;try{window.__HANDLER_ACTIVE_SCREEN=this.screenFilter,window.dispatchEvent(new CustomEvent("handler:active-screen-changed",{detail:{screen:this.screenFilter}}))}catch{}n.addEventListener("change",()=>{let c=n.value||"all";this.screenFilter=c;try{window.localStorage.setItem(this.getScreenFilterStorageKey(),this.screenFilter)}catch{}try{window.__HANDLER_ACTIVE_SCREEN=this.screenFilter,window.dispatchEvent(new CustomEvent("handler:active-screen-changed",{detail:{screen:this.screenFilter}}))}catch{}this.refreshObjects()})}(l=this.root)==null||l.addEventListener("click",c=>{let d=c.target;if(!d)return;let u=d.closest("[data-object-id]");if(!u)return;let p=u.dataset.objectId;p&&this.select(p)}),window.addEventListener("handler:screen-index-loaded",()=>this.refreshObjects())}setSelected(t){if(this.selectedId=t,!this.listContainer)return;Array.from(this.listContainer.querySelectorAll("[data-object-id]")).forEach(n=>{n.classList.toggle("selected",n.dataset.objectId===t)})}refreshObjects(){var d;if(!this.listContainer)return;let t=window.getEditableObjectList,i=window.getEditableObjectConfig,n=window.refreshEditableConfigIndex;if(typeof n=="function"&&n(),typeof t!="function"){this.scheduleRetry();return}let r=t();if(!Array.isArray(r)||r.length===0){let u=window.__editableObjectConfigs;u&&typeof u.keys=="function"&&(r=Array.from(u.keys()))}if(!Array.isArray(r)||r.length===0){this.scheduleRetry();return}let a=(((d=this.searchInput)==null?void 0:d.value)||"").trim().toLowerCase(),s=["loading","start","gameplay","tutorial","endgame"],o=Object.fromEntries(s.map(u=>[u,[]])),l=Object.fromEntries(s.map(u=>[u,[]]));r.forEach(u=>{var T,P,S,L;let p=typeof i=="function"?i(u):null;if(!p){let z=window.__editableObjectConfigs;z&&typeof z.get=="function"&&(p=(T=z.get(u))!=null?T:null)}let f=(((P=p==null?void 0:p.identity)==null?void 0:P.category)||"scene").toString(),g=(((S=p==null?void 0:p.identity)==null?void 0:S.id)||u).toString(),h=f.toLowerCase(),m=g.toLowerCase(),b=h.includes("ui")||m.startsWith("ui")||m.includes("label"),y=this.formatDisplayName(g||u),v=((L=p==null?void 0:p.render)==null?void 0:L.visible)===!1||(p==null?void 0:p.enabled)===!1,x=this.getObjectType(p),w={id:u,label:y,category:f,isUi:b,isUnused:v,objectType:x},E=this.inferScreen(w.id,p);if(this.screenFilter!=="all"&&E!==this.screenFilter||!(!a||w.id.toLowerCase().includes(a)||w.label.toLowerCase().includes(a)))return;(w.isUnused?l:o)[E].push(w)});let c={loading:"Loading Screen",start:"Start Screen",gameplay:"Gameplay",tutorial:"Tutorial",endgame:"Endgame"};this.listContainer.innerHTML=`
76
- ${s.map(u=>this.renderGroup(c[u],[...o[u],...l[u]])).join("")}
77
- `,this.setSelected(this.selectedId)}formatDisplayName(t){let i=t.replace(/^json\./,"").replace(/^ui\./,"").replace(/_\d+$/,"").replace(/\./g," ").replace(/_/g," ");return i=i.split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()).join(" "),i}inferScreen(t,i){var o,l;let n=window.__HANDLER_SCREEN_INDEX,r=(o=n==null?void 0:n.instanceToScreen)==null?void 0:o[t];if(r==="loading"||r==="start"||r==="gameplay"||r==="tutorial"||r==="endgame")return r;let a=(((l=i==null?void 0:i.identity)==null?void 0:l.id)||"").toString(),s=`${t} ${a}`.toLowerCase();return s.includes("loading")?"loading":s.includes("start")?"start":s.includes("tutorial")?"tutorial":s.includes("endgame")||s.includes("end_card")||s.includes("endcard")?"endgame":"gameplay"}getObjectType(t){var i,n,r,a,s,o,l,c,d;return t?(i=t.ui)!=null&&i.text?"text":(a=(r=(n=t.render)==null?void 0:n.asset)==null?void 0:r.path)!=null&&a.endsWith(".json")?"animation":((o=(s=t.render)==null?void 0:s.asset)==null?void 0:o.type)==="image"||(l=t.render)!=null&&l.texture?"sprite":(d=(c=t.gameplay)==null?void 0:c.tuning)!=null&&d.panel_width?"graphics":"container":"container"}renderGroup(t,i){if(!i.length)return"";let n=window.getEditableObjectConfig,r=i.map(a=>{var d,u;let s=typeof n=="function"?n(a.id):null;if(!s){let p=window.__editableObjectConfigs;p&&typeof p.get=="function"&&(s=(d=p.get(a.id))!=null?d:null)}let o=this.getTypeIconByType(a.objectType),l=this.getAssetPreview(s),c=(u=s==null?void 0:s.ui)!=null&&u.text?`"${s.ui.text.substring(0,12)}${s.ui.text.length>12?"...":""}"`:"";return`
78
- <button class="scene-object-item ${a.isUnused?"unused":""}" data-object-id="${a.id}">
79
- <span class="scene-object-label">${a.label}</span>
79
+ `}initialize(e,t){var a,s,r,o,l;this.options=t,this.root=e.querySelector('[data-panel="scene-objects"]'),this.listContainer=(a=this.root)==null?void 0:a.querySelector("[data-object-list]"),this.searchInput=(s=this.root)==null?void 0:s.querySelector("#scene-object-search"),(r=this.searchInput)==null||r.addEventListener("input",()=>this.refreshObjects());let n=(o=this.root)==null?void 0:o.querySelector("#scene-screen-filter");if(n){try{let c=window.localStorage.getItem(this.getScreenFilterStorageKey());c&&(this.screenFilter=c)}catch{}n.value=this.screenFilter;try{window.__HANDLER_ACTIVE_SCREEN=this.screenFilter,window.dispatchEvent(new CustomEvent("handler:active-screen-changed",{detail:{screen:this.screenFilter}}))}catch{}n.addEventListener("change",()=>{let c=n.value||"all";this.screenFilter=c;try{window.localStorage.setItem(this.getScreenFilterStorageKey(),this.screenFilter)}catch{}try{window.__HANDLER_ACTIVE_SCREEN=this.screenFilter,window.dispatchEvent(new CustomEvent("handler:active-screen-changed",{detail:{screen:this.screenFilter}}))}catch{}this.refreshObjects()})}(l=this.root)==null||l.addEventListener("click",c=>{let p=c.target;if(!p)return;let d=p.closest("[data-object-id]");if(!d)return;let u=d.dataset.objectId;u&&this.select(u)}),window.addEventListener("handler:screen-index-loaded",()=>this.refreshObjects())}setSelected(e){var r,o,l,c,p;if(this.selectedId=e,!this.listContainer)return;Array.from(this.listContainer.querySelectorAll("[data-object-id]")).forEach(d=>{d.classList.toggle("selected",d.dataset.objectId===e)});let n=(r=this.root)==null?void 0:r.querySelector("[data-breadcrumbs]"),a=(o=this.root)==null?void 0:o.querySelector("[data-breadcrumb-screen]"),s=(l=this.root)==null?void 0:l.querySelector("[data-breadcrumb-object]");if(n&&a&&s)if(e){let d=window.getEditableObjectConfig,u=typeof d=="function"?d(e):null;if(!u){let b=window.__editableObjectConfigs;b&&typeof b.get=="function"&&(u=(c=b.get(e))!=null?c:null)}let g=this.inferScreen(e,u),h={loading:"Loading",start:"Start",gameplay:"Gameplay",tutorial:"Tutorial",endgame:"Endgame"},f=(((p=u==null?void 0:u.identity)==null?void 0:p.id)||e).toString(),m=this.formatDisplayName(f);a.textContent=h[g]||g,s.textContent=m,n.style.display="flex"}else n.style.display="none"}refreshObjects(){var p;if(!this.listContainer)return;let e=window.getEditableObjectList,t=window.getEditableObjectConfig,n=window.refreshEditableConfigIndex;if(typeof n=="function"&&n(),typeof e!="function"){this.scheduleRetry();return}let a=e();if(!Array.isArray(a)||a.length===0){let d=window.__editableObjectConfigs;d&&typeof d.keys=="function"&&(a=Array.from(d.keys()))}if(!Array.isArray(a)||a.length===0){this.scheduleRetry();return}let s=(((p=this.searchInput)==null?void 0:p.value)||"").trim().toLowerCase(),r=["loading","start","gameplay","tutorial","endgame"],o=Object.fromEntries(r.map(d=>[d,[]])),l=Object.fromEntries(r.map(d=>[d,[]]));a.forEach(d=>{var O,B,M,C;let u=typeof t=="function"?t(d):null;if(!u){let I=window.__editableObjectConfigs;I&&typeof I.get=="function"&&(u=(O=I.get(d))!=null?O:null)}let g=(((B=u==null?void 0:u.identity)==null?void 0:B.category)||"scene").toString(),h=(((M=u==null?void 0:u.identity)==null?void 0:M.id)||d).toString(),f=g.toLowerCase(),m=h.toLowerCase(),b=f.includes("ui")||m.startsWith("ui")||m.includes("label"),y=this.formatDisplayName(h||d),v=((C=u==null?void 0:u.render)==null?void 0:C.visible)===!1||(u==null?void 0:u.enabled)===!1,x=this.getObjectType(u),E={id:d,label:y,category:g,isUi:b,isUnused:v,objectType:x},w=this.inferScreen(E.id,u);if(this.screenFilter!=="all"&&w!==this.screenFilter||!(!s||E.id.toLowerCase().includes(s)||E.label.toLowerCase().includes(s)))return;(E.isUnused?l:o)[w].push(E)});let c={loading:"Loading Screen",start:"Start Screen",gameplay:"Gameplay",tutorial:"Tutorial",endgame:"Endgame"};this.listContainer.innerHTML=`
80
+ ${r.map(d=>this.renderGroup(c[d],[...o[d],...l[d]])).join("")}
81
+ `,this.setSelected(this.selectedId)}formatDisplayName(e){let t=e.replace(/^json\./,"").replace(/^ui\./,"").replace(/_\d+$/,"").replace(/\./g," ").replace(/_/g," ");return t=t.split(" ").map(n=>n.charAt(0).toUpperCase()+n.slice(1).toLowerCase()).join(" "),t}inferScreen(e,t){var o,l;let n=window.__HANDLER_SCREEN_INDEX,a=(o=n==null?void 0:n.instanceToScreen)==null?void 0:o[e];if(a==="loading"||a==="start"||a==="gameplay"||a==="tutorial"||a==="endgame")return a;let s=(((l=t==null?void 0:t.identity)==null?void 0:l.id)||"").toString(),r=`${e} ${s}`.toLowerCase();return r.includes("loading")?"loading":r.includes("start")?"start":r.includes("tutorial")?"tutorial":r.includes("endgame")||r.includes("end_card")||r.includes("endcard")?"endgame":"gameplay"}getObjectType(e){var t,n,a,s,r,o,l,c,p;return e?(t=e.ui)!=null&&t.text?"text":(s=(a=(n=e.render)==null?void 0:n.asset)==null?void 0:a.path)!=null&&s.endsWith(".json")?"animation":((o=(r=e.render)==null?void 0:r.asset)==null?void 0:o.type)==="image"||(l=e.render)!=null&&l.texture?"sprite":(p=(c=e.gameplay)==null?void 0:c.tuning)!=null&&p.panel_width?"graphics":"container":"container"}renderGroup(e,t){if(!t.length)return"";let n=window.getEditableObjectConfig,a=t.map(s=>{var p,d;let r=typeof n=="function"?n(s.id):null;if(!r){let u=window.__editableObjectConfigs;u&&typeof u.get=="function"&&(r=(p=u.get(s.id))!=null?p:null)}let o=this.getTypeIconByType(s.objectType),l=this.getAssetPreview(r),c=(d=r==null?void 0:r.ui)!=null&&d.text?`"${r.ui.text.substring(0,12)}${r.ui.text.length>12?"...":""}"`:"";return`
82
+ <button class="scene-object-item ${s.isUnused?"unused":""}" data-object-id="${s.id}">
83
+ <span class="scene-object-label">${s.label}</span>
80
84
  ${c?`<span class="scene-object-text-preview">${c}</span>`:""}
81
- <span class="scene-object-badge ${a.isUi?"ui":"scene"}">${a.category}</span>
85
+ <span class="scene-object-badge ${s.isUi?"ui":"scene"}">${s.category}</span>
82
86
  </button>
83
87
  `}).join("");return`
84
88
  <div class="scene-object-group">
85
- <div class="scene-object-group-title">${t} <span class="scene-object-count">${i.length}</span></div>
89
+ <div class="scene-object-group-title">${e} <span class="scene-object-count">${t.length}</span></div>
86
90
  <div class="scene-object-group-items">
87
- ${r}
91
+ ${a}
88
92
  </div>
89
93
  </div>
90
- `}getTypeIconByType(t){return{text:"\u{1F4DD}",sprite:"\u{1F5BC}\uFE0F",graphics:"\u2B1C",container:"\u{1F4E6}",animation:"\u{1F3AC}"}[t]||"\u{1F4E6}"}getTypeIcon(t){var n,r,a,s,o,l;if(!t)return"\u{1F4E6}";if((n=t.render)!=null&&n.texture){let c=t.render.texture;return c.includes("button")?"\u{1F518}":c.includes("key")?"\u{1F511}":"\u{1F5BC}\uFE0F"}if((r=t.ui)!=null&&r.text)return"\u{1F4DD}";if(((a=t.identity)==null?void 0:a.category)==="ui")return"\u{1F3A8}";if(t.effects||(o=(s=t.identity)==null?void 0:s.id)!=null&&o.includes("effect"))return"\u2728";if(t.audio)return"\u{1F50A}";let i=((l=t.identity)==null?void 0:l.id)||"";return i.includes("background")?"\u{1F5BC}\uFE0F":i.includes("character")?"\u{1F464}":i.includes("key")?"\u{1F511}":i.includes("draggable")?"\u{1F3AF}":i.includes("machine")?"\u2699\uFE0F":i.includes("tutorial")||i.includes("hand")?"\u{1F446}":"\u{1F4E6}"}getAssetPreview(t){var n;if(!t)return null;let i=(n=t.render)==null?void 0:n.texture;return i&&(i.endsWith(".png")||i.endsWith(".jpg")||i.endsWith(".jpeg"))?i.startsWith("library/")||i.startsWith("/raw/")?`/raw/${i.replace(/^\/raw\//,"")}`:`/raw/${i}`:null}getColorIndicator(t){var n,r,a,s;if(!t)return"";let i=((n=t.render)==null?void 0:n.background_color)||((a=(r=t.gameplay)==null?void 0:r.tuning)==null?void 0:a.panel_bg_color)||((s=t.ui)==null?void 0:s.backgroundColor);return i?`<span class="scene-object-color-dot" style="background-color: ${i}" title="${i}"></span>`:""}getMetadata(t){var n,r,a,s;if(!t)return"";let i=[];return((n=t.render)==null?void 0:n.visible)===!1&&i.push("hidden"),((r=t.render)==null?void 0:r.z_index)!==void 0&&i.push(`z:${t.render.z_index}`),((a=t.interaction)!=null&&a.clickable||(s=t.ui)!=null&&s.button)&&i.push("clickable"),i.length>0?i.join(" \u2022 "):""}scheduleRetry(){this.retryTimer||(this.retryTimer=window.setTimeout(()=>{this.retryTimer=null,this.refreshObjects()},400))}select(t){var i;this.selectedId=t,this.setSelected(t),(i=this.options)==null||i.onSelect(t)}};var Fr=class{constructor(){this.root=null;this.infoEls={};this.options=null}render(){return`
91
- <div class="scene-panel scene-tools panel-accent-amber" data-panel="scene-tools">
92
- <div class="scene-panel-header" data-panel-handle>
93
- <div class="panel-title">
94
- <span class="panel-pill">Tools</span>
95
- <span class="panel-title-text">Scene Tools</span>
94
+ `}getTypeIconByType(e){return{text:"\u{1F4DD}",sprite:"\u{1F5BC}\uFE0F",graphics:"\u2B1C",container:"\u{1F4E6}",animation:"\u{1F3AC}"}[e]||"\u{1F4E6}"}getTypeIcon(e){var n,a,s,r,o,l;if(!e)return"\u{1F4E6}";if((n=e.render)!=null&&n.texture){let c=e.render.texture;return c.includes("button")?"\u{1F518}":c.includes("key")?"\u{1F511}":"\u{1F5BC}\uFE0F"}if((a=e.ui)!=null&&a.text)return"\u{1F4DD}";if(((s=e.identity)==null?void 0:s.category)==="ui")return"\u{1F3A8}";if(e.effects||(o=(r=e.identity)==null?void 0:r.id)!=null&&o.includes("effect"))return"\u2728";if(e.audio)return"\u{1F50A}";let t=((l=e.identity)==null?void 0:l.id)||"";return t.includes("background")?"\u{1F5BC}\uFE0F":t.includes("character")?"\u{1F464}":t.includes("key")?"\u{1F511}":t.includes("draggable")?"\u{1F3AF}":t.includes("machine")?"\u2699\uFE0F":t.includes("tutorial")||t.includes("hand")?"\u{1F446}":"\u{1F4E6}"}getAssetPreview(e){var n;if(!e)return null;let t=(n=e.render)==null?void 0:n.texture;return t&&(t.endsWith(".png")||t.endsWith(".jpg")||t.endsWith(".jpeg"))?t.startsWith("library/")||t.startsWith("/raw/")?`/raw/${t.replace(/^\/raw\//,"")}`:`/raw/${t}`:null}getColorIndicator(e){var n,a,s,r;if(!e)return"";let t=((n=e.render)==null?void 0:n.background_color)||((s=(a=e.gameplay)==null?void 0:a.tuning)==null?void 0:s.panel_bg_color)||((r=e.ui)==null?void 0:r.backgroundColor);return t?`<span class="scene-object-color-dot" style="background-color: ${t}" title="${t}"></span>`:""}getMetadata(e){var n,a,s,r;if(!e)return"";let t=[];return((n=e.render)==null?void 0:n.visible)===!1&&t.push("hidden"),((a=e.render)==null?void 0:a.z_index)!==void 0&&t.push(`z:${e.render.z_index}`),((s=e.interaction)!=null&&s.clickable||(r=e.ui)!=null&&r.button)&&t.push("clickable"),t.length>0?t.join(" \u2022 "):""}scheduleRetry(){this.retryTimer||(this.retryTimer=window.setTimeout(()=>{this.retryTimer=null,this.refreshObjects()},400))}select(e){var t;this.selectedId=e,this.setSelected(e),(t=this.options)==null||t.onSelect(e)}};var gn=class{constructor(){this.root=null;this.options=null;this.isCollapsed=!1}render(){return`
95
+ <div class="scene-tools-corner-panel ${this.isCollapsed?"collapsed":""}" data-panel="scene-tools-corner">
96
+ <div class="scene-tools-header" data-tools-header data-panel-handle>
97
+ <span class="scene-tools-title">Scene Tools</span>
98
+ <div class="scene-tools-header-actions">
99
+ <div class="scene-tools-status-icons" data-status-icons>
100
+ <span class="status-icon" data-status="bounds" title="Highlight Bounds">
101
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
102
+ <rect x="3" y="3" width="18" height="18" rx="2"></rect>
103
+ </svg>
104
+ </span>
105
+ <span class="status-icon" data-status="anchor" title="Highlight Anchor">
106
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
107
+ <circle cx="12" cy="12" r="3"></circle>
108
+ <path d="M12 3v6M12 15v6M3 12h6M15 12h6"></path>
109
+ </svg>
110
+ </span>
111
+ <span class="status-icon" data-status="nudge" title="Arrow Nudging">
112
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
113
+ <path d="M5 9l7-7 7 7M5 15l7 7 7-7"></path>
114
+ </svg>
115
+ </span>
116
+ </div>
117
+ <button class="scene-tools-collapse-btn" data-tools-collapse type="button" title="Collapse/Expand Panel">
118
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
119
+ <polyline points="18 15 12 9 6 15"></polyline>
120
+ </svg>
121
+ </button>
96
122
  </div>
97
- <button class="scene-panel-toggle" type="button" data-panel-toggle>\u25BE</button>
98
123
  </div>
99
- <div class="scene-panel-body">
100
- <div class="debug-section">
101
- <div class="debug-section-title">Visualize</div>
102
- <div class="debug-field">
103
- <label>Scene Scale</label>
104
- <input type="range" id="debug-scene-scale" min="0.4" max="1.6" step="0.05" value="1.0">
105
- <span class="debug-value-display" id="debug-scene-scale-value">1.0</span>
106
- </div>
107
- <div class="debug-field checkbox-field">
108
- <input type="checkbox" id="debug-highlight-object">
109
- <label>Highlight bounds</label>
110
- </div>
111
- <div class="debug-field checkbox-field">
112
- <input type="checkbox" id="debug-highlight-anchor">
113
- <label>Highlight config anchor</label>
114
- </div>
115
- <div class="debug-field checkbox-field">
116
- <input type="checkbox" id="debug-nudge-enabled">
117
- <label>Enable arrow nudging</label>
118
- </div>
119
- <div id="debug-nudge-controls" class="debug-nudge hidden">
120
- <div class="debug-field">
121
- <label>Nudge step (px)</label>
122
- <input type="number" id="debug-nudge-step" step="1" value="10">
123
- </div>
124
- <div class="debug-arrow-pad">
125
- <button class="debug-arrow-btn" data-nudge="up">\u2191</button>
126
- <button class="debug-arrow-btn" data-nudge="left">\u2190</button>
127
- <button class="debug-arrow-btn" data-nudge="down">\u2193</button>
128
- <button class="debug-arrow-btn" data-nudge="right">\u2192</button>
129
- </div>
130
- </div>
124
+ <div class="scene-tools-body" data-tools-body>
125
+ <div class="debug-field checkbox-field">
126
+ <input type="checkbox" id="debug-highlight-object">
127
+ <label for="debug-highlight-object" title="Show bounding boxes around all objects">Highlight bounds</label>
131
128
  </div>
132
-
133
- <div class="debug-section">
134
- <div class="debug-section-title">Splash Screen</div>
135
- <div class="debug-field">
136
- <label>Loading text</label>
137
- <input type="text" id="debug-loading-text" placeholder="Y\xFCkleniyor...">
138
- </div>
139
- <div class="debug-field">
140
- <label>Loading text scale</label>
141
- <input type="range" id="debug-loading-text-scale" min="0.2" max="1.2" step="0.05" value="0.6">
142
- <span class="debug-value-display" id="debug-loading-text-scale-value">0.6</span>
143
- </div>
144
- <div class="debug-field checkbox-field">
145
- <input type="checkbox" id="debug-splash-on-start">
146
- <label>Show on start</label>
147
- </div>
148
- <div class="debug-btn-group">
149
- <button class="debug-btn" id="debug-show-splash">Show Splash Screen</button>
150
- </div>
129
+ <div class="debug-field checkbox-field">
130
+ <input type="checkbox" id="debug-highlight-anchor">
131
+ <label for="debug-highlight-anchor" title="Show anchor points for all objects">Highlight config anchor</label>
151
132
  </div>
152
-
153
- <div class="debug-section">
154
- <div class="debug-section-title">Object Info</div>
155
- <div class="debug-info-grid">
156
- <div class="debug-info-row">
157
- <span class="debug-info-label">Instance</span>
158
- <span class="debug-info-value" id="debug-instance-id">\u2014</span>
159
- </div>
160
- <div class="debug-info-row">
161
- <span class="debug-info-label">World X</span>
162
- <span class="debug-info-value" id="debug-world-x">0</span>
163
- </div>
164
- <div class="debug-info-row">
165
- <span class="debug-info-label">World Y</span>
166
- <span class="debug-info-value" id="debug-world-y">0</span>
167
- </div>
168
- <div class="debug-info-row">
169
- <span class="debug-info-label">Anchor X</span>
170
- <span class="debug-info-value" id="debug-config-x">\u2014</span>
171
- </div>
172
- <div class="debug-info-row">
173
- <span class="debug-info-label">Anchor Y</span>
174
- <span class="debug-info-value" id="debug-config-y">\u2014</span>
175
- </div>
176
- </div>
133
+ <div class="debug-field checkbox-field">
134
+ <input type="checkbox" id="debug-nudge-enabled">
135
+ <label for="debug-nudge-enabled" title="Enable keyboard arrow keys to nudge selected object">Enable arrow nudging</label>
177
136
  </div>
178
-
179
- <div class="debug-collapsible collapsed" data-advanced-settings>
180
- <button class="debug-collapsible-header" type="button" data-advanced-toggle>
181
- <span>Advanced Settings</span>
182
- <span class="debug-collapsible-icon">\u25BE</span>
183
- </button>
184
- <div class="debug-collapsible-body">
185
- <div class="debug-section">
186
- <div class="debug-section-title">Global Settings</div>
187
- <div class="debug-field">
188
- <label>Scale Multiplier</label>
189
- <input type="range" id="debug-layout-scale" min="0.1" max="2.0" step="0.05" value="1.0">
190
- <span class="debug-value-display" id="debug-layout-scale-value">1.0</span>
191
- </div>
192
- <div class="debug-field">
193
- <label>Position Offset X</label>
194
- <input type="range" id="debug-layout-offset-x" min="-150" max="150" step="1" value="0">
195
- <span class="debug-value-display" id="debug-layout-offset-x-value">0</span>
196
- </div>
197
- <div class="debug-field">
198
- <label>Position Offset Y</label>
199
- <input type="range" id="debug-layout-offset-y" min="-150" max="150" step="1" value="0">
200
- <span class="debug-value-display" id="debug-layout-offset-y-value">0</span>
201
- </div>
202
- <div class="debug-field checkbox-field">
203
- <input type="checkbox" id="debug-rect-visible" checked>
204
- <label>Debug Rectangle Visible</label>
205
- </div>
206
- <div class="debug-field">
207
- <label>Debug Rect Color</label>
208
- <input type="color" id="debug-rect-color" value="#ff0000">
209
- </div>
210
- <div class="debug-field">
211
- <label>Debug Rect Thickness</label>
212
- <input type="range" id="debug-rect-thickness" min="1" max="10" step="1" value="4">
213
- <span class="debug-value-display" id="debug-rect-thickness-value">4</span>
214
- </div>
215
- <div class="debug-field">
216
- <label>Engine Scale</label>
217
- <input type="range" id="debug-engine-scale" min="0.1" max="2.0" step="0.05" value="1.0">
218
- <span class="debug-value-display" id="debug-engine-scale-value">1.0</span>
219
- </div>
220
- <div class="debug-field">
221
- <label>Background Scale</label>
222
- <input type="range" id="debug-background-scale" min="0.5" max="2.0" step="0.05" value="1.05">
223
- <span class="debug-value-display" id="debug-background-scale-value">1.05</span>
224
- </div>
225
- <div class="debug-field">
226
- <label>Label Pulse Speed</label>
227
- <input type="range" id="debug-label-pulse-speed" min="0" max="10" step="0.1" value="3.0">
228
- <span class="debug-value-display" id="debug-label-pulse-speed-value">3.0</span>
229
- </div>
230
- <div class="debug-field">
231
- <label>Label Pulse Intensity</label>
232
- <input type="range" id="debug-label-pulse-intensity" min="0" max="0.2" step="0.01" value="0.03">
233
- <span class="debug-value-display" id="debug-label-pulse-intensity-value">0.03</span>
234
- </div>
235
- <div class="debug-field">
236
- <label>Rope Length</label>
237
- <input type="range" id="debug-rope-length" min="200" max="800" step="10" value="420">
238
- <span class="debug-value-display" id="debug-rope-length-value">420</span>
239
- </div>
240
- <div class="debug-btn-group">
241
- <button class="debug-btn danger" id="debug-reset">Reset Debug</button>
242
- <button class="debug-btn" id="debug-export">Export Debug Config</button>
243
- </div>
244
- </div>
137
+ <div id="debug-nudge-controls" class="debug-nudge hidden">
138
+ <div class="debug-field">
139
+ <label for="debug-nudge-step" title="Number of pixels to move per nudge">Nudge step (px)</label>
140
+ <input type="number" id="debug-nudge-step" step="1" value="10" title="Pixels per nudge">
141
+ </div>
142
+ <div class="debug-arrow-pad">
143
+ <button class="debug-arrow-btn" data-nudge="up" title="Nudge Up">\u2191</button>
144
+ <button class="debug-arrow-btn" data-nudge="left" title="Nudge Left">\u2190</button>
145
+ <button class="debug-arrow-btn" data-nudge="down" title="Nudge Down">\u2193</button>
146
+ <button class="debug-arrow-btn" data-nudge="right" title="Nudge Right">\u2192</button>
245
147
  </div>
246
148
  </div>
247
149
  </div>
248
150
  </div>
249
- `}initialize(t,i){var m,b,y,v,x,w,E,A,_,T,P,S,L,z,D,B;this.options=i,this.root=t.querySelector('[data-panel="scene-tools"]');let n=(m=this.root)==null?void 0:m.querySelector("#debug-highlight-object");n==null||n.addEventListener("change",()=>{var O;return(O=this.options)==null?void 0:O.onHighlightObject(!!n.checked)});let r=(b=this.root)==null?void 0:b.querySelector("#debug-highlight-anchor");r==null||r.addEventListener("change",()=>{var O;return(O=this.options)==null?void 0:O.onHighlightAnchor(!!r.checked)});let a=(y=this.root)==null?void 0:y.querySelector("#debug-nudge-enabled"),s=(v=this.root)==null?void 0:v.querySelector("#debug-nudge-controls");if(a&&s){let O=()=>s.classList.toggle("hidden",!a.checked);a.addEventListener("change",O),O()}Array.from(((x=this.root)==null?void 0:x.querySelectorAll(".debug-arrow-btn"))||[]).forEach(O=>{O.addEventListener("click",()=>{var C,I,j,Q;switch(O.dataset.nudge){case"up":(C=this.options)==null||C.onNudge(0,-1);break;case"down":(I=this.options)==null||I.onNudge(0,1);break;case"left":(j=this.options)==null||j.onNudge(-1,0);break;case"right":(Q=this.options)==null||Q.onNudge(1,0);break;default:break}})});let c=(()=>{var R;let O=window.getEditableEngineConfig;if(typeof O=="function"){let C=O();return(R=C==null?void 0:C.splash)!=null?R:{}}return{}})(),d=(w=this.root)==null?void 0:w.querySelector("#debug-loading-text"),u=(E=this.root)==null?void 0:E.querySelector("#debug-loading-text-scale"),p=(A=this.root)==null?void 0:A.querySelector("#debug-loading-text-scale-value"),f=(_=this.root)==null?void 0:_.querySelector("#debug-splash-on-start"),g=(T=this.root)==null?void 0:T.querySelector("#debug-show-splash");if(d&&(d.value=typeof c.loading_text=="string"&&c.loading_text.length>0?c.loading_text:"Y\xFCkleniyor...",d.addEventListener("input",()=>{var O,R;(R=(O=this.options)==null?void 0:O.onUpdateSplash)==null||R.call(O,{loading_text:d.value})})),u){let O=typeof c.loading_text_scale=="number"?c.loading_text_scale:.6;u.value=O.toString(),p&&(p.textContent=O.toFixed(2)),u.addEventListener("input",()=>{var C,I;let R=Number(u.value);p&&(p.textContent=Number.isFinite(R)?R.toFixed(2):"0.6"),Number.isFinite(R)&&((I=(C=this.options)==null?void 0:C.onUpdateSplash)==null||I.call(C,{loading_text_scale:R}))})}f&&(f.checked=!!c.show_on_start,f.addEventListener("change",()=>{var O,R;(R=(O=this.options)==null?void 0:O.onUpdateSplash)==null||R.call(O,{show_on_start:!!f.checked})})),g==null||g.addEventListener("click",()=>{var O,R;(R=(O=this.options)==null?void 0:O.onShowSplash)==null||R.call(O)}),this.infoEls={instance:(P=this.root)==null?void 0:P.querySelector("#debug-instance-id"),worldX:(S=this.root)==null?void 0:S.querySelector("#debug-world-x"),worldY:(L=this.root)==null?void 0:L.querySelector("#debug-world-y"),anchorX:(z=this.root)==null?void 0:z.querySelector("#debug-config-x"),anchorY:(D=this.root)==null?void 0:D.querySelector("#debug-config-y")};let h=(B=this.root)==null?void 0:B.querySelector("[data-advanced-toggle]");h&&h.addEventListener("click",()=>{let O=h.closest(".debug-collapsible");O==null||O.classList.toggle("collapsed")})}getNudgeStep(){var n,r;let t=(n=this.root)==null?void 0:n.querySelector("#debug-nudge-step"),i=Number((r=t==null?void 0:t.value)!=null?r:10);return Number.isFinite(i)?i:10}updateInfo(t){if(!t){this.infoEls.instance&&(this.infoEls.instance.textContent="\u2014"),this.infoEls.worldX&&(this.infoEls.worldX.textContent="0"),this.infoEls.worldY&&(this.infoEls.worldY.textContent="0"),this.infoEls.anchorX&&(this.infoEls.anchorX.textContent="\u2014"),this.infoEls.anchorY&&(this.infoEls.anchorY.textContent="\u2014");return}this.infoEls.instance&&(this.infoEls.instance.textContent=t.instanceId),this.infoEls.worldX&&(this.infoEls.worldX.textContent=t.worldX.toFixed(1)),this.infoEls.worldY&&(this.infoEls.worldY.textContent=t.worldY.toFixed(1)),this.infoEls.anchorX&&(this.infoEls.anchorX.textContent=t.anchorX==null?"\u2014":t.anchorX.toFixed(1)),this.infoEls.anchorY&&(this.infoEls.anchorY.textContent=t.anchorY==null?"\u2014":t.anchorY.toFixed(1))}};var $r=class{constructor(){this.root=null;this.slotsContainer=null;this.options=null;this.registry=null;this.expandedSlot=null}mergeRegistries(t,i){let n=t||{},r=i||{},a={slots:Array.isArray(r.slots)?[...r.slots]:[],libraryAssets:typeof r.libraryAssets=="object"&&r.libraryAssets?{...r.libraryAssets}:{},categories:Array.isArray(r.categories)?[...r.categories]:[]},s=Array.isArray(n.slots)?n.slots:[];if(s.length>0&&a.slots.length>0)for(let c of a.slots){let d=s.find(u=>(u==null?void 0:u.slotId)&&u.slotId===(c==null?void 0:c.slotId));d!=null&&d.currentAsset&&d.currentAsset!==(c==null?void 0:c.currentAsset)&&(c.currentAsset=d.currentAsset)}let o=n.libraryAssets||{};for(let[c,d]of Object.entries(o)){if(!Array.isArray(d))continue;a.libraryAssets[c]||(a.libraryAssets[c]=[]);let u=new Set((a.libraryAssets[c]||[]).map(p=>p==null?void 0:p.filename));for(let p of d){let f=p==null?void 0:p.filename;!f||u.has(f)||(a.libraryAssets[c].unshift(p),u.add(f))}}let l=new Set(a.categories||[]);for(let c of n.categories||[])typeof c=="string"&&l.add(c);return a.categories=Array.from(l),a}render(){return`
151
+ `}initialize(e,t){if(this.options=t,this.root=e.querySelector('[data-panel="scene-tools-corner"]'),!this.root)return;let n=localStorage.getItem("scene-tools-collapsed");n!==null&&(this.isCollapsed=n==="true",this.root.classList.toggle("collapsed",this.isCollapsed));let a=this.root.querySelector("[data-panel-handle]");if(a){let{makePanelDraggable:u}=(Oi(),La(Cs));u(this.root,a)}let s=this.root.querySelector("[data-tools-collapse]");s==null||s.addEventListener("click",()=>{var u;this.isCollapsed=!this.isCollapsed,(u=this.root)==null||u.classList.toggle("collapsed",this.isCollapsed),localStorage.setItem("scene-tools-collapsed",String(this.isCollapsed))});let r=(u,g)=>{var f;let h=(f=this.root)==null?void 0:f.querySelector(`[data-status="${u}"]`);h&&h.classList.toggle("active",g)},o=this.root.querySelector("#debug-highlight-object");o==null||o.addEventListener("change",()=>{var u;(u=this.options)==null||u.onHighlightObject(!!o.checked),r("bounds",o.checked)});let l=this.root.querySelector("#debug-highlight-anchor");l==null||l.addEventListener("change",()=>{var u;(u=this.options)==null||u.onHighlightAnchor(!!l.checked),r("anchor",l.checked)});let c=this.root.querySelector("#debug-nudge-enabled"),p=this.root.querySelector("#debug-nudge-controls");if(c&&p){let u=()=>{var h;let g=c.checked;p.classList.toggle("hidden",!g),r("nudge",g),g&&this.isCollapsed&&(this.isCollapsed=!1,(h=this.root)==null||h.classList.remove("collapsed"),localStorage.setItem("scene-tools-collapsed","false"))};c.addEventListener("change",u),u()}Array.from(this.root.querySelectorAll(".debug-arrow-btn")||[]).forEach(u=>{u.addEventListener("click",()=>{var h,f,m,b;switch(u.dataset.nudge){case"up":(h=this.options)==null||h.onNudge(0,-1);break;case"down":(f=this.options)==null||f.onNudge(0,1);break;case"left":(m=this.options)==null||m.onNudge(-1,0);break;case"right":(b=this.options)==null||b.onNudge(1,0);break;default:break}})})}getNudgeStep(){var n,a;let e=(n=this.root)==null?void 0:n.querySelector("#debug-nudge-step"),t=Number((a=e==null?void 0:e.value)!=null?a:10);return Number.isFinite(t)?t:10}updateInfo(e){}};var fn=class{constructor(){this.root=null;this.slotsContainer=null;this.options=null;this.registry=null;this.expandedSlot=null}mergeRegistries(e,t){let n=e||{},a=t||{},s={slots:Array.isArray(a.slots)?[...a.slots]:[],libraryAssets:typeof a.libraryAssets=="object"&&a.libraryAssets?{...a.libraryAssets}:{},categories:Array.isArray(a.categories)?[...a.categories]:[]},r=Array.isArray(n.slots)?n.slots:[];if(r.length>0&&s.slots.length>0)for(let c of s.slots){let p=r.find(d=>(d==null?void 0:d.slotId)&&d.slotId===(c==null?void 0:c.slotId));p!=null&&p.currentAsset&&p.currentAsset!==(c==null?void 0:c.currentAsset)&&(c.currentAsset=p.currentAsset)}let o=n.libraryAssets||{};for(let[c,p]of Object.entries(o)){if(!Array.isArray(p))continue;s.libraryAssets[c]||(s.libraryAssets[c]=[]);let d=new Set((s.libraryAssets[c]||[]).map(u=>u==null?void 0:u.filename));for(let u of p){let g=u==null?void 0:u.filename;!g||d.has(g)||(s.libraryAssets[c].unshift(u),d.add(g))}}let l=new Set(s.categories||[]);for(let c of n.categories||[])typeof c=="string"&&l.add(c);return s.categories=Array.from(l),s}render(){return`
250
152
  <div class="scene-panel library-panel panel-accent-purple" data-panel="library">
251
153
  <div class="scene-panel-header" data-panel-handle>
252
154
  <div class="panel-title">
@@ -265,21 +167,21 @@
265
167
  </div>
266
168
  <div class="panel-resize-handle" data-panel-resize></div>
267
169
  </div>
268
- `}initialize(t,i){var a,s,o;this.options=i,this.root=t.querySelector('[data-panel="library"]'),this.slotsContainer=(a=this.root)==null?void 0:a.querySelector("[data-library-slots]");let n=(s=this.root)==null?void 0:s.querySelector("[data-create-ai]");n==null||n.addEventListener("click",()=>{this.handleCreateWithAI()});let r=(o=this.root)==null?void 0:o.querySelector("[data-refresh-library]");r==null||r.addEventListener("click",()=>{r.classList.add("pulse-anim"),this.refresh(),setTimeout(()=>r.classList.remove("pulse-anim"),500)}),this.loadAssetRegistry()}reRender(){console.log("[LIBRARY] Re-rendering slots..."),this.loadAssetRegistry()}async refresh(){console.log("[LIBRARY] Force refreshing asset registry...");try{let t=window.getEditableAssets,i=typeof t=="function"?t():null,n=await fetch(`/raw/assetRegistry.json?t=${Date.now()}`);if(n.ok){let r=await n.json(),a=this.mergeRegistries(i,r);window.getEditableAssets=()=>a,console.log("[LIBRARY] \u2705 Registry re-fetched successfully")}}catch(t){console.warn("[LIBRARY] Failed to re-fetch registry:",t)}this.loadAssetRegistry()}loadAssetRegistry(t=0){let i=window.getEditableAssets;if(typeof i=="function"){let n=i();if(n!=null&&n.slots&&Array.isArray(n.slots)&&n.slots.length>0){this.registry=n,console.log("[LIBRARY] Loaded slot-based registry:",this.registry.slots.length,"slots"),this.renderSlots();return}}t<15?(console.log(`[LIBRARY] Waiting for asset registry... (attempt ${t+1}/15)`),setTimeout(()=>this.loadAssetRegistry(t+1),200)):(console.warn("[LIBRARY] Failed to load asset registry"),this.slotsContainer&&(this.slotsContainer.innerHTML='<div class="library-info">No editable assets available</div>'))}renderSlots(){if(!this.slotsContainer||!this.registry)return;let t={};for(let n of this.registry.slots)t[n.category]||(t[n.category]=[]),t[n.category].push(n);let i=Date.now();this.slotsContainer.innerHTML="";for(let n of this.registry.categories){let r=t[n]||[];if(r.length===0)continue;let a=document.createElement("div");a.className="library-category";let s=document.createElement("div");s.className="library-category-header",s.textContent=this.formatCategoryName(n),a.appendChild(s);let o=document.createElement("div");o.className="library-category-slots";for(let l of r){let c=this.createSlotElement(l,i);o.appendChild(c)}a.appendChild(o),this.slotsContainer.appendChild(a)}}createSlotElement(t,i){let n=this.expandedSlot===t.slotId,r=document.createElement("div");r.className=`library-slot ${n?"expanded":""}`,r.dataset.slotId=t.slotId;let a=document.createElement("div");a.className="slot-header";let s=document.createElement("div");s.className="slot-current";let o=document.createElement("img");o.src=`/raw/${t.currentAsset}?t=${i}`,o.alt=t.displayName,o.className="slot-thumbnail",o.onerror=()=>{o.style.display="none"},s.appendChild(o),a.appendChild(s);let l=document.createElement("div");l.className="slot-info";let c=document.createElement("div");c.className="slot-name",c.textContent=t.displayName;let d=document.createElement("div");d.className="slot-asset",d.textContent=t.currentAsset,l.appendChild(c),l.appendChild(d),a.appendChild(l);let u=document.createElement("div");u.className="slot-actions";let p=document.createElement("button");p.className="slot-ai-edit",p.title="Edit with AI",p.textContent="\u2728 AI",p.addEventListener("click",async h=>{h.stopPropagation(),await this.handleAIEdit(t)}),u.appendChild(p);let f=document.createElement("button");f.className="slot-reset",f.title="Reset to default",f.textContent="\u21BA",f.addEventListener("click",async h=>{h.stopPropagation(),await this.handleReset(t)}),u.appendChild(f);let g=document.createElement("span");if(g.className="slot-expand-icon",g.textContent=n?"\u25BC":"\u25B6",u.appendChild(g),a.appendChild(u),a.addEventListener("click",()=>{this.expandedSlot=this.expandedSlot===t.slotId?null:t.slotId,this.renderSlots()}),r.appendChild(a),n){let h=this.createLibraryElement(t,i);r.appendChild(h)}return r}createLibraryElement(t,i){var a;let n=document.createElement("div");n.className="slot-library";let r=((a=this.registry)==null?void 0:a.libraryAssets[t.libraryFolder])||[];return this.fetchFolderAssets(t.libraryFolder,i).then(s=>{let o=new Map;for(let c of r)o.set(c.filename,c);for(let c of s)o.has(c.filename)||o.set(c.filename,c);let l=Array.from(o.values());if(l.length===0){n.innerHTML='<div class="library-empty">No alternative assets</div>';return}n.innerHTML="";for(let c of l){let d=document.createElement("div");d.className="library-item";let u=document.createElement("img");u.src=`/raw/library/${t.libraryFolder}/${c.filename}?t=${i}`,u.alt=c.displayName,u.className="library-thumbnail",u.onerror=()=>{u.style.opacity="0.3"},d.appendChild(u);let p=document.createElement("div");p.className="library-label",p.textContent=c.displayName,d.appendChild(p),d.addEventListener("click",async()=>{await this.handleApply(t,c.filename)}),n.appendChild(d)}}),n.innerHTML='<div class="library-loading">Loading assets...</div>',n}async fetchFolderAssets(t,i){try{let n=await fetch(`/raw/library/${t}/?t=${i}`);if(!n.ok)return[];let r=await n.text(),a=[],s=/href="([^"]+\.(png|jpg|jpeg))"/gi,o;for(;(o=s.exec(r))!==null;){let l=o[1];if(!l.startsWith("/")&&!l.startsWith("..")){let c=l.replace(/\.(png|jpg|jpeg)$/i,"").replace(/_/g," ");a.push({filename:l,displayName:c})}}return a}catch{return console.log("[LIBRARY] Could not fetch folder listing, using registry only"),[]}}async handleApply(t,i){var n;console.log("[LIBRARY] Applying asset:",i,"to slot:",t.slotId);try{await((n=this.options)==null?void 0:n.onApply(t.objectId,i,t.category)),t.currentAsset=i,this.renderSlots()}catch(r){console.error("[LIBRARY] Failed to apply asset:",r)}}async handleReset(t){var i;console.log("[LIBRARY] Resetting slot:",t.slotId,"to default:",t.defaultAsset);try{await((i=this.options)==null?void 0:i.onReset(t.objectId,t.defaultAsset,t.category)),t.currentAsset=t.defaultAsset,this.renderSlots()}catch(n){console.error("[LIBRARY] Failed to reset slot:",n)}}formatCategoryName(t){return t.replace(/_/g," ").split(" ").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(" ")}async handleAIEdit(t){console.log("[Library] Opening AI Edit for slot:",t);let i=window.__openAiEditor;if(typeof i=="function"){let n=t.slotId||t.objectId,r="render.texture";t.category==="ui"&&(r="ui.image"),t.category==="audio"&&(r="audio.src"),i(n,`Edit ${t.displayName} with AI`,t.currentAsset,{objectId:t.objectId,path:r})}else console.warn("[Library] AI Editor not available"),alert("AI Editor is not available. Please ensure the Settings panel is loaded.")}handleCreateWithAI(){console.log("[Library] Opening AI Create modal");let t=window.__openAiEditor;typeof t=="function"?t("new_asset","Create new asset with AI"):(console.warn("[Library] AI Editor not available"),alert("AI Editor is not available. Please ensure the Settings panel is loaded."))}highlightSlot(t,i){if(!this.registry||!this.slotsContainer)return;let n=t.startsWith("json.")?t.replace("json.",""):t,r=this.registry.slots.find(a=>(a.objectId===n||a.slotId===n)&&(!i||a.category===i));r?(console.log("[LIBRARY] Highlighting slot:",r.slotId),this.expandedSlot=r.slotId,this.renderSlots(),setTimeout(()=>{var s;let a=(s=this.slotsContainer)==null?void 0:s.querySelector(`[data-slot-id="${r.slotId}"]`);a&&(a.scrollIntoView({behavior:"smooth",block:"center"}),a.classList.add("highlight-pulse"),setTimeout(()=>a.classList.remove("highlight-pulse"),3e3))},100)):console.warn("[LIBRARY] No slot found for highlight:",t,i)}};var Hr=class{detectType(t,i,n){let r=t.toLowerCase();return r==="logic_id"||r==="logicid"?"select":typeof i=="string"&&i.match(/\.(png|jpg|jpeg|gif|webp)$/i)?"image":r.includes("color")||r.includes("tint")?"color":typeof i=="boolean"?"boolean":typeof i=="number"?"number":Array.isArray(i)?"array":typeof i=="object"&&i!==null?"object":"text"}isHexColor(t){return/^#[0-9a-fA-F]{6}$/i.test(t)}isImagePath(t){return/\.(png|jpg|jpeg|gif|svg)$/i.test(t)}};var Ur=class{render(t,i,n,r){let a=n&&n.trim(),s=a?`/raw/${n}`:"";return`
170
+ `}initialize(e,t){var s,r,o;this.options=t,this.root=e.querySelector('[data-panel="library"]'),this.slotsContainer=(s=this.root)==null?void 0:s.querySelector("[data-library-slots]");let n=(r=this.root)==null?void 0:r.querySelector("[data-create-ai]");n==null||n.addEventListener("click",()=>{this.handleCreateWithAI()});let a=(o=this.root)==null?void 0:o.querySelector("[data-refresh-library]");a==null||a.addEventListener("click",()=>{a.classList.add("pulse-anim"),this.refresh(),setTimeout(()=>a.classList.remove("pulse-anim"),500)}),this.loadAssetRegistry()}reRender(){console.log("[LIBRARY] Re-rendering slots..."),this.loadAssetRegistry()}async refresh(){console.log("[LIBRARY] Force refreshing asset registry...");try{let e=window.getEditableAssets,t=typeof e=="function"?e():null,n=await fetch(`/raw/assetRegistry.json?t=${Date.now()}`);if(n.ok){let a=await n.json(),s=this.mergeRegistries(t,a);window.getEditableAssets=()=>s,console.log("[LIBRARY] \u2705 Registry re-fetched successfully")}}catch(e){console.warn("[LIBRARY] Failed to re-fetch registry:",e)}this.loadAssetRegistry()}loadAssetRegistry(e=0){let t=window.getEditableAssets;if(typeof t=="function"){let n=t();if(n!=null&&n.slots&&Array.isArray(n.slots)&&n.slots.length>0){this.registry=n,console.log("[LIBRARY] Loaded slot-based registry:",this.registry.slots.length,"slots"),this.renderSlots();return}}e<15?(console.log(`[LIBRARY] Waiting for asset registry... (attempt ${e+1}/15)`),setTimeout(()=>this.loadAssetRegistry(e+1),200)):(console.warn("[LIBRARY] Failed to load asset registry"),this.slotsContainer&&(this.slotsContainer.innerHTML='<div class="library-info">No editable assets available</div>'))}renderSlots(){if(!this.slotsContainer||!this.registry)return;let e={};for(let n of this.registry.slots)e[n.category]||(e[n.category]=[]),e[n.category].push(n);let t=Date.now();this.slotsContainer.innerHTML="";for(let n of this.registry.categories){let a=e[n]||[];if(a.length===0)continue;let s=document.createElement("div");s.className="library-category";let r=document.createElement("div");r.className="library-category-header",r.textContent=this.formatCategoryName(n),s.appendChild(r);let o=document.createElement("div");o.className="library-category-slots";for(let l of a){let c=this.createSlotElement(l,t);o.appendChild(c)}s.appendChild(o),this.slotsContainer.appendChild(s)}}createSlotElement(e,t){let n=this.expandedSlot===e.slotId,a=document.createElement("div");a.className=`library-slot ${n?"expanded":""}`,a.dataset.slotId=e.slotId;let s=document.createElement("div");s.className="slot-header";let r=document.createElement("div");r.className="slot-current";let o=document.createElement("img");o.src=`/raw/${e.currentAsset}?t=${t}`,o.alt=e.displayName,o.className="slot-thumbnail",o.onerror=()=>{o.style.display="none"},r.appendChild(o),s.appendChild(r);let l=document.createElement("div");l.className="slot-info";let c=document.createElement("div");c.className="slot-name",c.textContent=e.displayName;let p=document.createElement("div");p.className="slot-asset",p.textContent=e.currentAsset,l.appendChild(c),l.appendChild(p),s.appendChild(l);let d=document.createElement("div");d.className="slot-actions";let u=document.createElement("button");u.className="slot-ai-edit",u.title="Edit with AI",u.textContent="\u2728 AI",u.addEventListener("click",async f=>{f.stopPropagation(),await this.handleAIEdit(e)}),d.appendChild(u);let g=document.createElement("button");g.className="slot-reset",g.title="Reset to default",g.textContent="\u21BA",g.addEventListener("click",async f=>{f.stopPropagation(),await this.handleReset(e)}),d.appendChild(g);let h=document.createElement("span");if(h.className="slot-expand-icon",h.textContent=n?"\u25BC":"\u25B6",d.appendChild(h),s.appendChild(d),s.addEventListener("click",()=>{this.expandedSlot=this.expandedSlot===e.slotId?null:e.slotId,this.renderSlots()}),a.appendChild(s),n){let f=this.createLibraryElement(e,t);a.appendChild(f)}return a}createLibraryElement(e,t){var s;let n=document.createElement("div");n.className="slot-library";let a=((s=this.registry)==null?void 0:s.libraryAssets[e.libraryFolder])||[];return this.fetchFolderAssets(e.libraryFolder,t).then(r=>{let o=new Map;for(let c of a)o.set(c.filename,c);for(let c of r)o.has(c.filename)||o.set(c.filename,c);let l=Array.from(o.values());if(l.length===0){n.innerHTML='<div class="library-empty">No alternative assets</div>';return}n.innerHTML="";for(let c of l){let p=document.createElement("div");p.className="library-item";let d=document.createElement("img");d.src=`/raw/library/${e.libraryFolder}/${c.filename}?t=${t}`,d.alt=c.displayName,d.className="library-thumbnail",d.onerror=()=>{d.style.opacity="0.3"},p.appendChild(d);let u=document.createElement("div");u.className="library-label",u.textContent=c.displayName,p.appendChild(u),p.addEventListener("click",async()=>{await this.handleApply(e,c.filename)}),n.appendChild(p)}}),n.innerHTML='<div class="library-loading">Loading assets...</div>',n}async fetchFolderAssets(e,t){try{let n=await fetch(`/raw/library/${e}/?t=${t}`);if(!n.ok)return[];let a=await n.text(),s=[],r=/href="([^"]+\.(png|jpg|jpeg))"/gi,o;for(;(o=r.exec(a))!==null;){let l=o[1];if(!l.startsWith("/")&&!l.startsWith("..")){let c=l.replace(/\.(png|jpg|jpeg)$/i,"").replace(/_/g," ");s.push({filename:l,displayName:c})}}return s}catch{return console.log("[LIBRARY] Could not fetch folder listing, using registry only"),[]}}async handleApply(e,t){var n;console.log("[LIBRARY] Applying asset:",t,"to slot:",e.slotId);try{await((n=this.options)==null?void 0:n.onApply(e.objectId,t,e.category)),e.currentAsset=t,this.renderSlots()}catch(a){console.error("[LIBRARY] Failed to apply asset:",a)}}async handleReset(e){var t;console.log("[LIBRARY] Resetting slot:",e.slotId,"to default:",e.defaultAsset);try{await((t=this.options)==null?void 0:t.onReset(e.objectId,e.defaultAsset,e.category)),e.currentAsset=e.defaultAsset,this.renderSlots()}catch(n){console.error("[LIBRARY] Failed to reset slot:",n)}}formatCategoryName(e){return e.replace(/_/g," ").split(" ").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}async handleAIEdit(e){console.log("[Library] Opening AI Edit for slot:",e);let t=window.__openAiEditor;if(typeof t=="function"){let n=e.slotId||e.objectId,a="render.texture";e.category==="ui"&&(a="ui.image"),e.category==="audio"&&(a="audio.src"),t(n,`Edit ${e.displayName} with AI`,e.currentAsset,{objectId:e.objectId,path:a})}else console.warn("[Library] AI Editor not available"),alert("AI Editor is not available. Please ensure the Settings panel is loaded.")}handleCreateWithAI(){console.log("[Library] Opening AI Create modal");let e=window.__openAiEditor;typeof e=="function"?e("new_asset","Create new asset with AI"):(console.warn("[Library] AI Editor not available"),alert("AI Editor is not available. Please ensure the Settings panel is loaded."))}highlightSlot(e,t){if(!this.registry||!this.slotsContainer)return;let n=e.startsWith("json.")?e.replace("json.",""):e,a=this.registry.slots.find(s=>(s.objectId===n||s.slotId===n)&&(!t||s.category===t));a?(console.log("[LIBRARY] Highlighting slot:",a.slotId),this.expandedSlot=a.slotId,this.renderSlots(),setTimeout(()=>{var r;let s=(r=this.slotsContainer)==null?void 0:r.querySelector(`[data-slot-id="${a.slotId}"]`);s&&(s.scrollIntoView({behavior:"smooth",block:"center"}),s.classList.add("highlight-pulse"),setTimeout(()=>s.classList.remove("highlight-pulse"),3e3))},100)):console.warn("[LIBRARY] No slot found for highlight:",e,t)}};var hn=class{detectType(e,t,n){let a=e.toLowerCase();return a==="logic_id"||a==="logicid"?"select":typeof t=="string"&&t.match(/\.(png|jpg|jpeg|gif|webp)$/i)?"image":a.includes("color")||a.includes("tint")?"color":typeof t=="boolean"?"boolean":typeof t=="number"?"number":Array.isArray(t)?"array":typeof t=="object"&&t!==null?"object":"text"}isHexColor(e){return/^#[0-9a-fA-F]{6}$/i.test(e)}isImagePath(e){return/\.(png|jpg|jpeg|gif|svg)$/i.test(e)}};var mn=class{render(e,t,n,a){let s=n&&n.trim(),r=s?`/raw/${n}`:"";return`
269
171
  <div class="inspector-property inspector-property-image">
270
172
  <div class="property-header">
271
- <label class="inspector-property-label">${this.formatLabel(i)}</label>
173
+ <label class="inspector-property-label">${this.formatLabel(t)}</label>
272
174
  <div class="property-badges">
273
175
  <span class="property-badge" title="Image Asset">IMG</span>
274
176
  </div>
275
177
  </div>
276
178
 
277
179
  <div class="inspector-image-container">
278
- ${a?`
180
+ ${s?`
279
181
  <div class="inspector-image-preview">
280
- <img src="${s}" alt="${i}" onclick="window.open('${s}', '_blank')" />
182
+ <img src="${r}" alt="${t}" onclick="window.open('${r}', '_blank')" />
281
183
  <div class="preview-overlay">
282
- <span class="preview-resolution" id="res-${t}-${i}">- x -</span>
184
+ <span class="preview-resolution" id="res-${e}-${t}">- x -</span>
283
185
  </div>
284
186
  </div>
285
187
  `:`
@@ -293,164 +195,164 @@
293
195
  <input type="text"
294
196
  class="inspector-input inspector-input-path"
295
197
  value="${n||""}"
296
- data-property-path="${r}"
297
- data-object-id="${t}"
198
+ data-property-path="${a}"
199
+ data-object-id="${e}"
298
200
  placeholder="path/to/asset.png" />
299
201
  </div>
300
202
 
301
203
  <div class="inspector-image-actions">
302
- <button class="inspector-btn inspector-btn-sm primary" data-action="library" data-path="${r}" data-object="${t}">
204
+ <button class="inspector-btn inspector-btn-sm primary" data-action="library" data-path="${a}" data-object="${e}">
303
205
  \u{1F4DA} Show in Library
304
206
  </button>
305
- <button class="inspector-btn inspector-btn-sm" data-action="ai-edit" data-path="${r}" data-object="${t}">
207
+ <button class="inspector-btn inspector-btn-sm" data-action="ai-edit" data-path="${a}" data-object="${e}">
306
208
  \u2728 AI Edit
307
209
  </button>
308
- <button class="inspector-btn inspector-btn-sm" data-action="upload" data-path="${r}" data-object="${t}">
210
+ <button class="inspector-btn inspector-btn-sm" data-action="upload" data-path="${a}" data-object="${e}">
309
211
  \u{1F4E4}
310
212
  </button>
311
- <button class="inspector-btn inspector-btn-sm" data-action="reset" data-path="${r}" data-object="${t}">
213
+ <button class="inspector-btn inspector-btn-sm" data-action="reset" data-path="${a}" data-object="${e}">
312
214
  \u21BA
313
215
  </button>
314
216
  </div>
315
217
  </div>
316
218
  </div>
317
219
  </div>
318
- `}formatLabel(t){return t.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,i=>i.toUpperCase())}};var qr=class{render(t,i,n,r){let a=n||"#000000";return`
220
+ `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var bn=class{render(e,t,n,a){let s=n||"#000000";return`
319
221
  <div class="inspector-property inspector-property-color">
320
- <label class="inspector-property-label">${this.formatLabel(i)}</label>
222
+ <label class="inspector-property-label">${this.formatLabel(t)}</label>
321
223
  <div class="inspector-color-group">
322
224
  <input type="color"
323
225
  class="inspector-color-picker"
324
- value="${a}"
325
- data-property-path="${r}"
326
- data-object-id="${t}" />
226
+ value="${s}"
227
+ data-property-path="${a}"
228
+ data-object-id="${e}" />
327
229
  <input type="text"
328
230
  class="inspector-input inspector-color-text"
329
- value="${a}"
330
- data-property-path="${r}"
331
- data-object-id="${t}" />
231
+ value="${s}"
232
+ data-property-path="${a}"
233
+ data-object-id="${e}" />
332
234
  </div>
333
235
  </div>
334
- `}formatLabel(t){return t.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,i=>i.toUpperCase())}};var Gr=class{render(t,i,n,r){return`
236
+ `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var yn=class{render(e,t,n,a){return`
335
237
  <div class="inspector-property inspector-property-number">
336
- <label class="inspector-property-label">${this.formatLabel(i)}</label>
238
+ <label class="inspector-property-label">${this.formatLabel(t)}</label>
337
239
  <input type="number"
338
240
  class="inspector-input"
339
241
  value="${n}"
340
- data-property-path="${r}"
341
- data-object-id="${t}"
242
+ data-property-path="${a}"
243
+ data-object-id="${e}"
342
244
  step="any" />
343
245
  </div>
344
- `}formatLabel(t){return t.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,i=>i.toUpperCase())}};var Wr=class{render(t,i,n,r){let a=String(n||"");return`
246
+ `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var vn=class{render(e,t,n,a){let s=String(n||"");return`
345
247
  <div class="inspector-property inspector-property-text">
346
- <label class="inspector-property-label">${this.formatLabel(i)}</label>
248
+ <label class="inspector-property-label">${this.formatLabel(t)}</label>
347
249
  <div class="inspector-input-group">
348
250
  <input type="text"
349
251
  class="inspector-input"
350
- value="${a}"
351
- data-property-path="${r}"
352
- data-object-id="${t}" />
252
+ value="${s}"
253
+ data-property-path="${a}"
254
+ data-object-id="${e}" />
353
255
  </div>
354
256
  </div>
355
- `}formatLabel(t){return t.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,i=>i.toUpperCase())}};var Vr=class{render(t,i,n,r){return`
257
+ `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var xn=class{render(e,t,n,a){return`
356
258
  <div class="inspector-property inspector-property-boolean">
357
259
  <label class="inspector-property-label">
358
260
  <input type="checkbox"
359
261
  class="inspector-checkbox"
360
262
  ${n?"checked":""}
361
- data-property-path="${r}"
362
- data-object-id="${t}" />
363
- <span>${this.formatLabel(i)}</span>
263
+ data-property-path="${a}"
264
+ data-object-id="${e}" />
265
+ <span>${this.formatLabel(t)}</span>
364
266
  </label>
365
267
  </div>
366
- `}formatLabel(t){return t.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,i=>i.toUpperCase())}};var Yr=class{render(t,i,n,r){if(!Array.isArray(n)||n.length===0)return`
268
+ `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var wn=class{render(e,t,n,a){if(!Array.isArray(n)||n.length===0)return`
367
269
  <div class="inspector-property inspector-property-array">
368
- <label class="inspector-property-label">${this.formatLabel(i)}</label>
270
+ <label class="inspector-property-label">${this.formatLabel(t)}</label>
369
271
  <div class="inspector-array-empty">Empty array</div>
370
272
  </div>
371
- `;let a=n.map((s,o)=>typeof s=="string"?`<div class="inspector-array-item">\u2022 ${s}</div>`:typeof s=="object"?`<div class="inspector-array-item">\u2022 ${JSON.stringify(s)}</div>`:`<div class="inspector-array-item">\u2022 ${String(s)}</div>`).join("");return`
273
+ `;let s=n.map((r,o)=>typeof r=="string"?`<div class="inspector-array-item">\u2022 ${r}</div>`:typeof r=="object"?`<div class="inspector-array-item">\u2022 ${JSON.stringify(r)}</div>`:`<div class="inspector-array-item">\u2022 ${String(r)}</div>`).join("");return`
372
274
  <div class="inspector-property inspector-property-array">
373
- <label class="inspector-property-label">${this.formatLabel(i)} (${n.length} items)</label>
275
+ <label class="inspector-property-label">${this.formatLabel(t)} (${n.length} items)</label>
374
276
  <div class="inspector-array-list">
375
- ${a}
277
+ ${s}
376
278
  </div>
377
279
  </div>
378
- `}formatLabel(t){return t.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,i=>i.toUpperCase())}};var Kr=class{constructor(t){this.registry=t}render(t,i,n,r){if(i==="logic"&&n&&typeof n=="object")return this.renderLogic(t,i,n,r);let a=[];for(let o in n){let l=n[o],c=`${r}.${o}`,d=this.registry.renderProperty(t,o,l,c);d&&a.push(d)}return a.length===0?"":a.length<=4&&a.every(o=>o.includes("inspector-property"))?`
280
+ `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var En=class{constructor(e){this.registry=e}render(e,t,n,a){if(t==="logic"&&n&&typeof n=="object")return this.renderLogic(e,t,n,a);let s=[];for(let o in n){let l=n[o],c=`${a}.${o}`,p=this.registry.renderProperty(e,o,l,c);p&&s.push(p)}return s.length===0?"":s.length<=4&&s.every(o=>o.includes("inspector-property"))?`
379
281
  <div class="inspector-subsection">
380
- <div class="inspector-subsection-title">${this.formatLabel(i)}</div>
282
+ <div class="inspector-subsection-title">${this.formatLabel(t)}</div>
381
283
  <div class="inspector-subsection-content">
382
- ${a.join("")}
284
+ ${s.join("")}
383
285
  </div>
384
286
  </div>
385
287
  `:`
386
288
  <div class="inspector-property inspector-property-object">
387
- <div class="inspector-object-header">${this.formatLabel(i)}</div>
289
+ <div class="inspector-object-header">${this.formatLabel(t)}</div>
388
290
  <div class="inspector-object-body">
389
- ${a.join("")}
291
+ ${s.join("")}
390
292
  </div>
391
293
  </div>
392
- `}renderLogic(t,i,n,r){let a=[],s=typeof(n==null?void 0:n.id)=="string"?n.id:"",o={zone:["bottom-left","bottom-right","top-left","top-right"],directionMode:["dominantAxis","free"],axis:["both","x","y"],ease:["power2.out","linear","sine.inOut","back.out(1.8)"]},l=(()=>{let d=window,u=Array.isArray(d==null?void 0:d.__HANDLER_LOGIC_OPTIONS)?d.__HANDLER_LOGIC_OPTIONS:[],f=[...["DragToWin","SwerveMove","DragSnap","JoystickMove"],...u].map(g=>String(g)).filter(g=>g.trim().length>0);return Array.from(new Set(f)).sort((g,h)=>g.localeCompare(h))})(),c=s&&!l.includes(s)?[s,...l]:l;a.push(`
294
+ `}renderLogic(e,t,n,a){let s=[],r=typeof(n==null?void 0:n.id)=="string"?n.id:"",o={zone:["bottom-left","bottom-right","top-left","top-right"],directionMode:["dominantAxis","free"],axis:["both","x","y"],ease:["power2.out","linear","sine.inOut","back.out(1.8)"]},l=(()=>{let p=window,d=Array.isArray(p==null?void 0:p.__HANDLER_LOGIC_OPTIONS)?p.__HANDLER_LOGIC_OPTIONS:[],g=[...["DragToWin","SwerveMove","DragSnap","JoystickMove"],...d].map(h=>String(h)).filter(h=>h.trim().length>0);return Array.from(new Set(g)).sort((h,f)=>h.localeCompare(f))})(),c=r&&!l.includes(r)?[r,...l]:l;s.push(`
393
295
  <div class="inspector-property inspector-property-text">
394
296
  <label class="inspector-property-label">Id</label>
395
297
  <div class="inspector-input-group">
396
298
  <select class="inspector-component-select inspector-input"
397
- data-property-path="${r}.id"
398
- data-object-id="${t}"
299
+ data-property-path="${a}.id"
300
+ data-object-id="${e}"
399
301
  data-logic-id-selector="true">
400
- <option value="" ${s?"":"selected"}>None</option>
401
- ${c.map(d=>`<option value="${d}" ${d===s?"selected":""}>${d}</option>`).join("")}
302
+ <option value="" ${r?"":"selected"}>None</option>
303
+ ${c.map(p=>`<option value="${p}" ${p===r?"selected":""}>${p}</option>`).join("")}
402
304
  </select>
403
305
  </div>
404
306
  </div>
405
- `);for(let d in n){if(d==="id")continue;let u=n[d],p=`${r}.${d}`;if(d==="props"&&u&&typeof u=="object"){let g=[];for(let h in u){let m=u[h],b=`${p}.${h}`,y=o[h];if((h==="targetId"||h==="inputId")&&typeof m=="string"){let v=(()=>{try{let E=window,A=E==null?void 0:E.__editableConfig;if(!(A!=null&&A.objects))return[];let _=[];if(A.objects instanceof Map)for(let T of A.objects.keys())_.push(T);else typeof A.objects=="object"&&_.push(...Object.keys(A.objects));return _.sort()}catch{return[]}})(),x=m||"",w=x&&!v.includes(x)?[x,...v]:v;g.push(`
307
+ `);for(let p in n){if(p==="id")continue;let d=n[p],u=`${a}.${p}`;if(p==="props"&&d&&typeof d=="object"){let h=[];for(let f in d){let m=d[f],b=`${u}.${f}`,y=o[f];if((f==="targetId"||f==="inputId")&&typeof m=="string"){let v=(()=>{try{let w=window,T=w==null?void 0:w.__editableConfig;if(!(T!=null&&T.objects))return[];let S=[];if(T.objects instanceof Map)for(let O of T.objects.keys())S.push(O);else typeof T.objects=="object"&&S.push(...Object.keys(T.objects));return S.sort()}catch{return[]}})(),x=m||"",E=x&&!v.includes(x)?[x,...v]:v;h.push(`
406
308
  <div class="inspector-property inspector-property-text">
407
- <label class="inspector-property-label">${this.formatLabel(h)}</label>
309
+ <label class="inspector-property-label">${this.formatLabel(f)}</label>
408
310
  <div class="inspector-input-group">
409
311
  <select class="inspector-component-select inspector-input"
410
312
  data-property-path="${b}"
411
- data-object-id="${t}">
313
+ data-object-id="${e}">
412
314
  <option value="" ${x?"":"selected"}>None</option>
413
- ${w.map(E=>`<option value="${E}" ${E===x?"selected":""}>${E}</option>`).join("")}
315
+ ${E.map(w=>`<option value="${w}" ${w===x?"selected":""}>${w}</option>`).join("")}
414
316
  </select>
415
317
  </div>
416
318
  </div>
417
- `);continue}if(Array.isArray(y)&&y.length)g.push(`
319
+ `);continue}if(Array.isArray(y)&&y.length)h.push(`
418
320
  <div class="inspector-property inspector-property-text">
419
- <label class="inspector-property-label">${this.formatLabel(h)}</label>
321
+ <label class="inspector-property-label">${this.formatLabel(f)}</label>
420
322
  <div class="inspector-input-group">
421
323
  <select class="inspector-component-select inspector-input"
422
324
  data-property-path="${b}"
423
- data-object-id="${t}">
325
+ data-object-id="${e}">
424
326
  ${y.map(v=>`<option value="${String(v)}" ${String(v)===String(m)?"selected":""}>${String(v)}</option>`).join("")}
425
327
  </select>
426
328
  </div>
427
329
  </div>
428
- `);else{let v=this.registry.renderProperty(t,h,m,b);v&&g.push(v)}}g.length&&a.push(`
330
+ `);else{let v=this.registry.renderProperty(e,f,m,b);v&&h.push(v)}}h.length&&s.push(`
429
331
  <div class="inspector-property inspector-property-object">
430
332
  <div class="inspector-object-header">Props</div>
431
333
  <div class="inspector-object-body">
432
- ${g.join("")}
334
+ ${h.join("")}
433
335
  </div>
434
336
  </div>
435
- `);continue}let f=this.registry.renderProperty(t,d,u,p);f&&a.push(f)}return a.length===0?"":`
337
+ `);continue}let g=this.registry.renderProperty(e,p,d,u);g&&s.push(g)}return s.length===0?"":`
436
338
  <div class="inspector-property inspector-property-object">
437
- <div class="inspector-object-header">${this.formatLabel(i)}</div>
339
+ <div class="inspector-object-header">${this.formatLabel(t)}</div>
438
340
  <div class="inspector-object-body">
439
- ${a.join("")}
341
+ ${s.join("")}
440
342
  </div>
441
343
  </div>
442
- `}formatLabel(t){return t.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,i=>i.toUpperCase())}};var Xr=class{render(t,i,n,r,a){let s=n==null?"":String(n),o=Array.from(new Set(a.map(c=>String(c)))),l=s&&!o.includes(s)?[s,...o]:o;return`
344
+ `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var An=class{render(e,t,n,a,s){let r=n==null?"":String(n),o=Array.from(new Set(s.map(c=>String(c)))),l=r&&!o.includes(r)?[r,...o]:o;return`
443
345
  <div class="inspector-property inspector-property-text">
444
- <label class="inspector-property-label">${this.formatLabel(i)}</label>
346
+ <label class="inspector-property-label">${this.formatLabel(t)}</label>
445
347
  <div class="inspector-input-group">
446
348
  <select class="inspector-component-select inspector-input"
447
- data-property-path="${r}"
448
- data-object-id="${t}">
449
- ${l.map(c=>`<option value="${c}" ${c===s?"selected":""}>${c}</option>`).join("")}
349
+ data-property-path="${a}"
350
+ data-object-id="${e}">
351
+ ${l.map(c=>`<option value="${c}" ${c===r?"selected":""}>${c}</option>`).join("")}
450
352
  </select>
451
353
  </div>
452
354
  </div>
453
- `}formatLabel(t){return t.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,i=>i.toUpperCase())}};var Zr=class{constructor(){this.typeDetector=new Hr,this.imageRenderer=new Ur,this.colorRenderer=new qr,this.numberRenderer=new Gr,this.textRenderer=new Wr,this.booleanRenderer=new Vr,this.arrayRenderer=new Yr,this.objectRenderer=new Kr(this),this.selectRenderer=new Xr}getObjectIds(){try{let t=window,i=t==null?void 0:t.__editableConfig;if(!(i!=null&&i.objects))return[];let n=[];if(i.objects instanceof Map)for(let r of i.objects.keys())n.push(r);else typeof i.objects=="object"&&n.push(...Object.keys(i.objects));return n.sort()}catch{return[]}}getEnumOptionsFromSchemas(t){var i;try{let n=window,r=n==null?void 0:n.__editableConfig,a=r==null?void 0:r.schemas;if(!a)return null;let s=String(t||"").split(".").filter(Boolean);if(s.length<2)return null;let o=s[0],l=s.slice(1).join("."),c=a instanceof Map?a.get(o):a==null?void 0:a[o];if(!c)return null;let d=(i=c==null?void 0:c.types)==null?void 0:i[l];if(typeof d!="string"||!d.startsWith("enum:"))return null;let p=d.slice(5).split("|").map(f=>f.trim()).filter(Boolean);return p.length?p:null}catch{return null}}getLogicOptions(){try{let t=window,i=Array.isArray(t==null?void 0:t.__HANDLER_LOGIC_OPTIONS)?t.__HANDLER_LOGIC_OPTIONS:[],r=[...["DragToWin","SwerveMove","DragSnap","JoystickMove"],...i].map(a=>String(a)).filter(a=>a.trim().length>0);return Array.from(new Set(r)).sort((a,s)=>a.localeCompare(s))}catch{return[]}}renderProperty(t,i,n,r){let a=i.toLowerCase(),s=a==="logic"||a==="logic_id"||a==="logicid",o=a==="id"&&r.toLowerCase().includes("logic");if((s||o)&&typeof n=="string"){let p=this.getLogicOptions();return this.selectRenderer.render(t,i,n,r,p)}let c={zone:["bottom-left","bottom-center","bottom-right","top-left","top-center","top-right"],directionMode:["dominantAxis","free"],axis:["both","x","y"],ease:["power2.out","linear","sine.inOut","back.out(1.8)"]}[i];if(c&&r.includes("logic.props"))return this.selectRenderer.render(t,i,n,r,c);if((i==="targetId"||i==="inputId")&&typeof n=="string"){let p=this.getObjectIds();return this.selectRenderer.render(t,i,n,r,["",...p])}let d=this.getEnumOptionsFromSchemas(r);if(d)return this.selectRenderer.render(t,i,n,r,d);switch(this.typeDetector.detectType(i,n)){case"image":return this.imageRenderer.render(t,i,n,r);case"color":return this.colorRenderer.render(t,i,n,r);case"number":return this.numberRenderer.render(t,i,n,r);case"boolean":return this.booleanRenderer.render(t,i,n,r);case"array":return this.arrayRenderer.render(t,i,n,r);case"object":return this.objectRenderer.render(t,i,n,r);case"select":return this.selectRenderer.render(t,i,n,r,[]);default:return this.textRenderer.render(t,i,n,r)}}getTypeDetector(){return this.typeDetector}};Te();var mi=class{async updateProperty(t,i,n,r={}){var l,c,d;console.log("[PropertyUpdateManager] Updating:",t,i,n);let a=window.getEditableObjectConfig;if(typeof a!="function"){console.error("[PropertyUpdateManager] getEditableObjectConfig not available");return}let s=a(t);if(!s){console.error("[PropertyUpdateManager] Config not found for:",t);return}bt({objectId:t,path:i,value:n},{persist:!0});let o=window.applyEditableObjectConfig;if(typeof o=="function"){let u=window.__editableConfig,p=(d=(c=(l=u==null?void 0:u.objects)==null?void 0:l.get)==null?void 0:c.call(l,t))!=null?d:s;await o(t,p),console.log("[PropertyUpdateManager] Applied config successfully")}else console.warn("[PropertyUpdateManager] applyEditableObjectConfig not available");this.triggerRefresh(t),r.refreshInspector&&window.dispatchEvent(new CustomEvent("inspector:refresh"))}getNestedProperty(t,i){let n=i.split("."),r=t;for(let a of n)if(r&&typeof r=="object"&&a in r)r=r[a];else return;return r}triggerRefresh(t){let i=window.__refreshHierarchy;typeof i=="function"&&i(),window.dispatchEvent(new CustomEvent("inspector:property-updated",{detail:{objectId:t}}))}};var Jr=class{constructor(){this.updateManager=new mi}async handleAction(t,i,n){console.log("[QuickActionsBar] Action:",t,i,n);let r=window.getEditableObjectConfig;if(typeof r!="function")return;let a=r(i);if(!a)return;let s=this.updateManager.getNestedProperty(a,n);if(t==="ai-convert"||t==="upload"||t==="library"){let o=n==="ui.text"||n==="render.asset.path",l=n==="render.asset.path";o&&(await this.prepareForImageConversion(i,a),t==="ai-convert"&&n!=="render.asset.path"&&(n="render.asset.path"))}switch(t){case"library":this.openLibrary(i,n,s);break;case"ai-edit":this.openAIEditor(i,n,s);break;case"upload":this.openUpload(i,n);break;case"reset":await this.resetToDefault(i,n);break;case"ai-convert":this.handleAiConvert(i,n,s);break;default:console.warn("[QuickActionsBar] Unknown action:",t)}}async prepareForImageConversion(t,i){var n,r;if(console.log("[QuickActionsBar] Preparing for image conversion:",t),i.render||(i.render={alpha:1,visible:!0}),(i.render.alpha===0||i.render.alpha===void 0)&&(i.render.alpha=1,await this.updateManager.updateProperty(t,"render.alpha",1)),(i.render.visible===!1||i.render.visible===void 0)&&(i.render.visible=!0,await this.updateManager.updateProperty(t,"render.visible",!0)),i.render.asset||(i.render.asset={type:"image",path:""}),i.render.asset.type!=="image"&&(i.render.asset.type="image",await this.updateManager.updateProperty(t,"render.asset",{type:"image",path:i.render.asset.path||""})),i.ui&&i.ui.renderMode!=="png"){await this.updateManager.updateProperty(t,"ui.renderMode","png",{refreshInspector:!0}),await this.updateManager.updateProperty(t,"render.tint","#ffffff");let s=((r=(n=i.transform)==null?void 0:n.scale)!=null?r:1)*.3;await this.updateManager.updateProperty(t,"transform.scale",s),console.log("[QuickActionsBar] Text to PNG conversion: set tint white, scale",s)}this.ensureSlotInRegistry(t,i)}ensureSlotInRegistry(t,i){var o,l,c;let n=window.getEditableAssets;if(typeof n!="function")return;let r=n();if(!r||!r.slots)return;let a=t.startsWith("json.")?t.replace("json.",""):t;if(!r.slots.some(d=>d.objectId===a||d.slotId===a)){let d=((o=i.identity)==null?void 0:o.category)||"ui";console.log("[QuickActionsBar] Adding new slot to registry for converted object:",a),r.slots.push({slotId:a,displayName:a.replace(/_/g," "),objectId:a,category:d,currentAsset:((c=(l=i.render)==null?void 0:l.asset)==null?void 0:c.path)||"",defaultAsset:"",libraryFolder:d,assetType:"image"}),r.categories&&!r.categories.includes(d)&&r.categories.push(d),r.libraryAssets&&!r.libraryAssets[d]&&(r.libraryAssets[d]=[]);let u=window.reRenderAssetLibrary;typeof u=="function"&&u()}}openLibrary(t,i,n){var a;let r=window.__debugContext;if(r){if(r.activeTab!=="library"){r.activeTab="library";let s=window.__updateWorkbenchTabs;typeof s=="function"&&s()}if(r.libraryPanel){let s=window.getEditableObjectConfig,o=s==null?void 0:s(t),l=(a=o==null?void 0:o.identity)==null?void 0:a.category;l||(l=i.split(".")[0]==="render"?"environment":"ui"),console.log("[QuickActionsBar] Highlighting library slot:",t,"category:",l),r.libraryPanel.highlightSlot(t,l)}}}openAIEditor(t,i,n){let r=window.__openAiEditor;if(typeof r=="function"){let a=i.split(".").pop()||i;r(a,`Edit ${a} for ${t}`,n,{objectId:t,path:i})}else console.warn("[QuickActionsBar] AI Editor not available")}openUpload(t,i){let n=document.createElement("input");n.type="file",n.accept="image/*",n.onchange=async r=>{var o;let a=(o=r.target.files)==null?void 0:o[0];if(!a)return;console.log("[QuickActionsBar] Preparing upload for:",a.name);let s=new FileReader;s.onload=async()=>{var c,d,u;let l=s.result;try{let p=window.getEditableObjectConfig,f=p==null?void 0:p(t),g=((c=f==null?void 0:f.identity)==null?void 0:c.category)||(i.split(".")[0]==="render"?"environment":"ui"),m=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:g,filename:a.name,data:l,overwrite:!0})})).json();if(m.success){console.log("[QuickActionsBar] \u2705 Uploaded and saved:",m.path),this.updateManager.updateProperty(t,i,m.path);let b=window.__debugContext;(u=(d=b==null?void 0:b.options)==null?void 0:d.onPropertyChange)==null||u.call(d,t,i,m.path);let y=window.addAssetToRegistry;typeof y=="function"&&y(g,a.name);let v=window.reRenderAssetLibrary;typeof v=="function"&&v(),window.dispatchEvent(new CustomEvent("inspector:refresh"))}else console.error("[QuickActionsBar] \u274C Upload failed:",m.error),alert(`Upload failed: ${m.error}`)}catch(p){console.error("[QuickActionsBar] \u274C Upload error:",p),alert("Upload failed. Check console.")}},s.readAsDataURL(a)},n.click()}async resetToDefault(t,i){console.log("[QuickActionsBar] Reset to default:",t,i);try{let n=await this.getDefaultValue(t,i);n!==void 0?(await this.updateManager.updateProperty(t,i,n),console.log("[QuickActionsBar] Reset to default value:",n)):alert("No default value found for this property.")}catch(n){console.error("[QuickActionsBar] Failed to reset to default:",n),alert("Failed to reset property. Check console for details.")}}async getDefaultValue(t,i){let n=i.split(".");if(n.length<2)return;let r=n[0],a=n.slice(1),s=window.__editableConfig;if(!(s!=null&&s.schemas))return;let o=null;if(s.schemas instanceof Map?o=s.schemas.get(r):typeof s.schemas=="object"&&(o=s.schemas[r]),!(o!=null&&o.defaults))return;let l=o.defaults;for(let c of a)if(l&&typeof l=="object")l=l[c];else return;return l}handleAiConvert(t,i,n){let r=window.__openAiEditor;if(typeof r=="function"){let s=`A single, high-quality, high-detail game UI icon/asset representing "${String(n||t.replace(/_/g," ").replace("json.",""))}". Modern stylized 3D rendered style, vibrant colors, soft lighting, isolated on solid magenta background, highly polished professional game art.`,o="render.asset.path";console.log("[QuickActionsBar] AI Convert for:",t,"from:",i,"to:",o),r(t,s,"",{objectId:t,path:o});let l=window.__debugContext;if(l){l.activeTab="ai";let c=window.__updateWorkbenchTabs;typeof c=="function"&&c()}}else console.warn("[QuickActionsBar] AI Editor not available")}};function Zm(e,t){let i;return function(...r){let a=()=>{clearTimeout(i),e(...r)};clearTimeout(i),i=setTimeout(a,t)}}var Qr=class{constructor(){this.root=null;this.contentContainer=null;this.selectedObjectId=null;this.options=null;this.showAdvanced=!1;this.rendererRegistry=new Zr,this.updateManager=new mi,this.quickActions=new Jr,window.addEventListener("inspector:refresh",()=>{this.selectedObjectId&&this.loadObject(this.selectedObjectId)}),window.addEventListener("config:changed",()=>{})}render(){return`
355
+ `}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}};var Sn=class{constructor(){this.typeDetector=new hn,this.imageRenderer=new mn,this.colorRenderer=new bn,this.numberRenderer=new yn,this.textRenderer=new vn,this.booleanRenderer=new xn,this.arrayRenderer=new wn,this.objectRenderer=new En(this),this.selectRenderer=new An}getObjectIds(){try{let e=window,t=e==null?void 0:e.__editableConfig;if(!(t!=null&&t.objects))return[];let n=[];if(t.objects instanceof Map)for(let a of t.objects.keys())n.push(a);else typeof t.objects=="object"&&n.push(...Object.keys(t.objects));return n.sort()}catch{return[]}}getEnumOptionsFromSchemas(e){var t;try{let n=window,a=n==null?void 0:n.__editableConfig,s=a==null?void 0:a.schemas;if(!s)return null;let r=String(e||"").split(".").filter(Boolean);if(r.length<2)return null;let o=r[0],l=r.slice(1).join("."),c=s instanceof Map?s.get(o):s==null?void 0:s[o];if(!c)return null;let p=(t=c==null?void 0:c.types)==null?void 0:t[l];if(typeof p!="string"||!p.startsWith("enum:"))return null;let u=p.slice(5).split("|").map(g=>g.trim()).filter(Boolean);return u.length?u:null}catch{return null}}getLogicOptions(){try{let e=window,t=Array.isArray(e==null?void 0:e.__HANDLER_LOGIC_OPTIONS)?e.__HANDLER_LOGIC_OPTIONS:[],a=[...["DragToWin","SwerveMove","DragSnap","JoystickMove"],...t].map(s=>String(s)).filter(s=>s.trim().length>0);return Array.from(new Set(a)).sort((s,r)=>s.localeCompare(r))}catch{return[]}}renderProperty(e,t,n,a){let s=t.toLowerCase(),r=s==="logic"||s==="logic_id"||s==="logicid",o=s==="id"&&a.toLowerCase().includes("logic");if((r||o)&&typeof n=="string"){let u=this.getLogicOptions();return this.selectRenderer.render(e,t,n,a,u)}let c={zone:["bottom-left","bottom-center","bottom-right","top-left","top-center","top-right"],directionMode:["dominantAxis","free"],axis:["both","x","y"],ease:["power2.out","linear","sine.inOut","back.out(1.8)"]}[t];if(c&&a.includes("logic.props"))return this.selectRenderer.render(e,t,n,a,c);if((t==="targetId"||t==="inputId")&&typeof n=="string"){let u=this.getObjectIds();return this.selectRenderer.render(e,t,n,a,["",...u])}let p=this.getEnumOptionsFromSchemas(a);if(p)return this.selectRenderer.render(e,t,n,a,p);switch(this.typeDetector.detectType(t,n)){case"image":return this.imageRenderer.render(e,t,n,a);case"color":return this.colorRenderer.render(e,t,n,a);case"number":return this.numberRenderer.render(e,t,n,a);case"boolean":return this.booleanRenderer.render(e,t,n,a);case"array":return this.arrayRenderer.render(e,t,n,a);case"object":return this.objectRenderer.render(e,t,n,a);case"select":return this.selectRenderer.render(e,t,n,a,[]);default:return this.textRenderer.render(e,t,n,a)}}getTypeDetector(){return this.typeDetector}};ee();var Ze=class{async updateProperty(e,t,n,a={}){var l,c,p;console.log("[PropertyUpdateManager] Updating:",e,t,n);let s=window.getEditableObjectConfig;if(typeof s!="function"){console.error("[PropertyUpdateManager] getEditableObjectConfig not available");return}let r=s(e);if(!r){console.error("[PropertyUpdateManager] Config not found for:",e);return}Ae({objectId:e,path:t,value:n},{persist:!0});let o=window.applyEditableObjectConfig;if(typeof o=="function"){let d=window.__editableConfig,u=(p=(c=(l=d==null?void 0:d.objects)==null?void 0:l.get)==null?void 0:c.call(l,e))!=null?p:r;await o(e,u),console.log("[PropertyUpdateManager] Applied config successfully")}else console.warn("[PropertyUpdateManager] applyEditableObjectConfig not available");this.triggerRefresh(e),a.refreshInspector&&window.dispatchEvent(new CustomEvent("inspector:refresh"))}getNestedProperty(e,t){let n=t.split("."),a=e;for(let s of n)if(a&&typeof a=="object"&&s in a)a=a[s];else return;return a}triggerRefresh(e){let t=window.__refreshHierarchy;typeof t=="function"&&t(),window.dispatchEvent(new CustomEvent("inspector:property-updated",{detail:{objectId:e}}))}};var Cn=class{constructor(){this.updateManager=new Ze}async handleAction(e,t,n){console.log("[QuickActionsBar] Action:",e,t,n);let a=window.getEditableObjectConfig;if(typeof a!="function")return;let s=a(t);if(!s)return;let r=this.updateManager.getNestedProperty(s,n);if(e==="ai-convert"||e==="upload"||e==="library"){let o=n==="ui.text"||n==="render.asset.path",l=n==="render.asset.path";o&&(await this.prepareForImageConversion(t,s),e==="ai-convert"&&n!=="render.asset.path"&&(n="render.asset.path"))}switch(e){case"library":this.openLibrary(t,n,r);break;case"ai-edit":this.openAIEditor(t,n,r);break;case"upload":this.openUpload(t,n);break;case"reset":await this.resetToDefault(t,n);break;case"ai-convert":this.handleAiConvert(t,n,r);break;default:console.warn("[QuickActionsBar] Unknown action:",e)}}async prepareForImageConversion(e,t){var n,a;if(console.log("[QuickActionsBar] Preparing for image conversion:",e),t.render||(t.render={alpha:1,visible:!0}),(t.render.alpha===0||t.render.alpha===void 0)&&(t.render.alpha=1,await this.updateManager.updateProperty(e,"render.alpha",1)),(t.render.visible===!1||t.render.visible===void 0)&&(t.render.visible=!0,await this.updateManager.updateProperty(e,"render.visible",!0)),t.render.asset||(t.render.asset={type:"image",path:""}),t.render.asset.type!=="image"&&(t.render.asset.type="image",await this.updateManager.updateProperty(e,"render.asset",{type:"image",path:t.render.asset.path||""})),t.ui&&t.ui.renderMode!=="png"){await this.updateManager.updateProperty(e,"ui.renderMode","png",{refreshInspector:!0}),await this.updateManager.updateProperty(e,"render.tint","#ffffff");let r=((a=(n=t.transform)==null?void 0:n.scale)!=null?a:1)*.3;await this.updateManager.updateProperty(e,"transform.scale",r),console.log("[QuickActionsBar] Text to PNG conversion: set tint white, scale",r)}this.ensureSlotInRegistry(e,t)}ensureSlotInRegistry(e,t){var o,l,c;let n=window.getEditableAssets;if(typeof n!="function")return;let a=n();if(!a||!a.slots)return;let s=e.startsWith("json.")?e.replace("json.",""):e;if(!a.slots.some(p=>p.objectId===s||p.slotId===s)){let p=((o=t.identity)==null?void 0:o.category)||"ui";console.log("[QuickActionsBar] Adding new slot to registry for converted object:",s),a.slots.push({slotId:s,displayName:s.replace(/_/g," "),objectId:s,category:p,currentAsset:((c=(l=t.render)==null?void 0:l.asset)==null?void 0:c.path)||"",defaultAsset:"",libraryFolder:p,assetType:"image"}),a.categories&&!a.categories.includes(p)&&a.categories.push(p),a.libraryAssets&&!a.libraryAssets[p]&&(a.libraryAssets[p]=[]);let d=window.reRenderAssetLibrary;typeof d=="function"&&d()}}openLibrary(e,t,n){var s;let a=window.__debugContext;if(a){if(a.activeTab!=="library"){a.activeTab="library";let r=window.__updateWorkbenchTabs;typeof r=="function"&&r()}if(a.libraryPanel){let r=window.getEditableObjectConfig,o=r==null?void 0:r(e),l=(s=o==null?void 0:o.identity)==null?void 0:s.category;l||(l=t.split(".")[0]==="render"?"environment":"ui"),console.log("[QuickActionsBar] Highlighting library slot:",e,"category:",l),a.libraryPanel.highlightSlot(e,l)}}}openAIEditor(e,t,n){let a=window.__openAiEditor;if(typeof a=="function"){let s=t.split(".").pop()||t;a(s,`Edit ${s} for ${e}`,n,{objectId:e,path:t})}else console.warn("[QuickActionsBar] AI Editor not available")}openUpload(e,t){let n=document.createElement("input");n.type="file",n.accept="image/*",n.onchange=async a=>{var o;let s=(o=a.target.files)==null?void 0:o[0];if(!s)return;console.log("[QuickActionsBar] Preparing upload for:",s.name);let r=new FileReader;r.onload=async()=>{var c,p,d;let l=r.result;try{let u=window.getEditableObjectConfig,g=u==null?void 0:u(e),h=((c=g==null?void 0:g.identity)==null?void 0:c.category)||(t.split(".")[0]==="render"?"environment":"ui"),m=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:h,filename:s.name,data:l,overwrite:!0})})).json();if(m.success){console.log("[QuickActionsBar] \u2705 Uploaded and saved:",m.path),this.updateManager.updateProperty(e,t,m.path);let b=window.__debugContext;(d=(p=b==null?void 0:b.options)==null?void 0:p.onPropertyChange)==null||d.call(p,e,t,m.path);let y=window.addAssetToRegistry;typeof y=="function"&&y(h,s.name);let v=window.reRenderAssetLibrary;typeof v=="function"&&v(),window.dispatchEvent(new CustomEvent("inspector:refresh"))}else console.error("[QuickActionsBar] \u274C Upload failed:",m.error),alert(`Upload failed: ${m.error}`)}catch(u){console.error("[QuickActionsBar] \u274C Upload error:",u),alert("Upload failed. Check console.")}},r.readAsDataURL(s)},n.click()}async resetToDefault(e,t){console.log("[QuickActionsBar] Reset to default:",e,t);try{let n=await this.getDefaultValue(e,t);n!==void 0?(await this.updateManager.updateProperty(e,t,n),console.log("[QuickActionsBar] Reset to default value:",n)):alert("No default value found for this property.")}catch(n){console.error("[QuickActionsBar] Failed to reset to default:",n),alert("Failed to reset property. Check console for details.")}}async getDefaultValue(e,t){let n=t.split(".");if(n.length<2)return;let a=n[0],s=n.slice(1),r=window.__editableConfig;if(!(r!=null&&r.schemas))return;let o=null;if(r.schemas instanceof Map?o=r.schemas.get(a):typeof r.schemas=="object"&&(o=r.schemas[a]),!(o!=null&&o.defaults))return;let l=o.defaults;for(let c of s)if(l&&typeof l=="object")l=l[c];else return;return l}handleAiConvert(e,t,n){let a=window.__openAiEditor;if(typeof a=="function"){let r=`A single, high-quality, high-detail game UI icon/asset representing "${String(n||e.replace(/_/g," ").replace("json.",""))}". Modern stylized 3D rendered style, vibrant colors, soft lighting, isolated on solid magenta background, highly polished professional game art.`,o="render.asset.path";console.log("[QuickActionsBar] AI Convert for:",e,"from:",t,"to:",o),a(e,r,"",{objectId:e,path:o});let l=window.__debugContext;if(l){l.activeTab="ai";let c=window.__updateWorkbenchTabs;typeof c=="function"&&c()}}else console.warn("[QuickActionsBar] AI Editor not available")}};function Ro(i,e){let t;return function(...a){let s=()=>{clearTimeout(t),i(...a)};clearTimeout(t),t=setTimeout(s,e)}}var Ln=class{constructor(){this.root=null;this.contentContainer=null;this.selectedObjectId=null;this.options=null;this.showAdvanced=!1;this.rendererRegistry=new Sn,this.updateManager=new Ze,this.quickActions=new Cn,window.addEventListener("inspector:refresh",()=>{this.selectedObjectId&&this.loadObject(this.selectedObjectId)}),window.addEventListener("config:changed",()=>{})}render(){return`
454
356
  <div class="scene-panel inspector-panel panel-accent-violet" data-panel="inspector" style="right:16px; top:72px;">
455
357
  <div class="scene-panel-header" data-panel-handle>
456
358
  <div class="panel-title">
@@ -471,77 +373,77 @@
471
373
  </div>
472
374
  </div>
473
375
  </div>
474
- `}initialize(t,i){var n;this.options=i,this.root=t.querySelector('[data-panel="inspector"]'),this.contentContainer=(n=this.root)==null?void 0:n.querySelector("[data-inspector-content]")}loadObject(t){this.selectedObjectId=t;let i=window.getEditableObjectConfig;if(typeof i!="function"){this.showError("Config system not ready");return}let n=i(t);if(!n){this.showError("Object not found");return}this.renderProperties(t,n)}renderProperties(t,i){if(!this.contentContainer)return;let n=[],r=i.identity||{},a=r.id||t,s=r.category||"unknown";n.push(`
376
+ `}initialize(e,t){var n;this.options=t,this.root=e.querySelector('[data-panel="inspector"]'),this.contentContainer=(n=this.root)==null?void 0:n.querySelector("[data-inspector-content]")}loadObject(e){this.selectedObjectId=e;let t=window.getEditableObjectConfig;if(typeof t!="function"){this.showError("Config system not ready");return}let n=t(e);if(!n){this.showError("Object not found");return}this.renderProperties(e,n)}renderProperties(e,t){if(!this.contentContainer)return;let n=[],a=t.identity||{},s=a.id||e,r=a.category||"unknown";n.push(`
475
377
  <div class="inspector-header">
476
378
  <div class="inspector-header-info">
477
- <div class="inspector-object-name">${a}</div>
478
- <div class="inspector-object-category">${s}</div>
379
+ <div class="inspector-object-name">${s}</div>
380
+ <div class="inspector-object-category">${r}</div>
479
381
  </div>
480
- ${this.renderConversionButtons(t,i)}
382
+ ${this.renderConversionButtons(e,t)}
481
383
  </div>
482
- `);let o=["ui","transform","render","gameplay","interaction","audio","effects","physics","motion","identity"];for(let l of o){let c=i[l];if(c){if(!this.showAdvanced&&!this.isSectionMeaningful(l,c,i))continue;n.push(this.renderSection(t,l,c,l))}}for(let l in i)if(!o.includes(l)&&typeof i[l]=="object"&&i[l]!==null){if(!this.showAdvanced&&!this.isSectionMeaningful(l,i[l],i))continue;n.push(this.renderSection(t,l,i[l],l))}this.contentContainer.innerHTML=n.join("")+this.renderFooter(i),this.attachEventListeners()}renderConversionButtons(t,i){var o,l,c,d;let n=!!i.ui,r=((o=i.ui)==null?void 0:o.renderMode)==="png"||((c=(l=i.render)==null?void 0:l.asset)==null?void 0:c.type)==="image";if(!(n||t.includes("ui_endgame")||t.includes("splash")||t.includes("button")||t.includes("label"))||r)return"";let s=(d=i.ui)!=null&&d.text?"ui.text":"render.asset.path";return`
384
+ `);let o=["ui","transform","render","gameplay","interaction","audio","effects","physics","motion","identity"];for(let l of o){let c=t[l];if(c){if(!this.showAdvanced&&!this.isSectionMeaningful(l,c,t))continue;n.push(this.renderSection(e,l,c,l))}}for(let l in t)if(!o.includes(l)&&typeof t[l]=="object"&&t[l]!==null){if(!this.showAdvanced&&!this.isSectionMeaningful(l,t[l],t))continue;n.push(this.renderSection(e,l,t[l],l))}this.contentContainer.innerHTML=n.join("")+this.renderFooter(t),this.attachEventListeners()}renderConversionButtons(e,t){var o,l,c,p;let n=!!t.ui,a=((o=t.ui)==null?void 0:o.renderMode)==="png"||((c=(l=t.render)==null?void 0:l.asset)==null?void 0:c.type)==="image";if(!(n||e.includes("ui_endgame")||e.includes("splash")||e.includes("button")||e.includes("label"))||a)return"";let r=(p=t.ui)!=null&&p.text?"ui.text":"render.asset.path";return`
483
385
  <div class="inspector-quick-actions">
484
386
  <button class="debug-btn debug-btn-sm success ai-simple-btn" type="button" data-convert-toggle>
485
387
  \u2728 Convert to PNG
486
388
  </button>
487
389
  <div class="inspector-convert-menu hidden" data-convert-menu>
488
- <button class="debug-btn debug-btn-sm" data-action="library" data-path="render.asset.path" data-object="${t}">\u{1F3A8} Library</button>
489
- <button class="debug-btn debug-btn-sm" data-action="ai-convert" data-path="${s}" data-object="${t}">\u2728 AI</button>
490
- <button class="debug-btn debug-btn-sm" data-action="upload" data-path="render.asset.path" data-object="${t}">\u{1F4E4} Upload</button>
390
+ <button class="debug-btn debug-btn-sm" data-action="library" data-path="render.asset.path" data-object="${e}">\u{1F3A8} Library</button>
391
+ <button class="debug-btn debug-btn-sm" data-action="ai-convert" data-path="${r}" data-object="${e}">\u2728 AI</button>
392
+ <button class="debug-btn debug-btn-sm" data-action="upload" data-path="render.asset.path" data-object="${e}">\u{1F4E4} Upload</button>
491
393
  </div>
492
394
  </div>
493
- `}renderFooter(t){let i=["motion","effects","ui","audio","physics","interaction","gameplay","visibility"],n=Object.keys(t),r=i.filter(a=>!n.includes(a));return r.length===0?"":`
395
+ `}renderFooter(e){let t=["motion","effects","ui","audio","physics","interaction","gameplay","visibility"],n=Object.keys(e),a=t.filter(s=>!n.includes(s));return a.length===0?"":`
494
396
  <div class="inspector-footer">
495
397
  <div class="inspector-add-component">
496
398
  <select class="inspector-component-select" data-inspector-component-select>
497
399
  <option value="" disabled selected>Add Component...</option>
498
- ${r.map(a=>`<option value="${a}">${this.formatLabel(a)}</option>`).join("")}
400
+ ${a.map(s=>`<option value="${s}">${this.formatLabel(s)}</option>`).join("")}
499
401
  </select>
500
402
  <button class="debug-btn debug-btn-sm primary" data-inspector-add-component-btn>Add</button>
501
403
  </div>
502
404
  </div>
503
- `}renderSection(t,i,n,r){let a=[],s=["kind","renderMode","position_ratio","position_mode","responsive","slot_id","asset_type"];for(let o in n){if(!this.showAdvanced&&s.includes(o))continue;let l=n[o],c=`${r}.${o}`,d=this.rendererRegistry.renderProperty(t,o,l,c);d&&a.push(d)}return a.length===0?"":`
504
- <div class="inspector-section" data-section="${i}">
505
- <div class="inspector-section-header" data-section-toggle="${i}">
405
+ `}renderSection(e,t,n,a){let s=[],r=["kind","renderMode","position_ratio","position_mode","responsive","slot_id","asset_type"];for(let o in n){if(!this.showAdvanced&&r.includes(o))continue;let l=n[o],c=`${a}.${o}`,p=this.rendererRegistry.renderProperty(e,o,l,c);p&&s.push(p)}return s.length===0?"":`
406
+ <div class="inspector-section" data-section="${t}">
407
+ <div class="inspector-section-header" data-section-toggle="${t}">
506
408
  <span class="inspector-section-arrow">\u25BC</span>
507
- <span class="inspector-section-icon">${this.getSectionIcon(i)}</span>
508
- <span class="inspector-section-title">${this.formatLabel(i)}</span>
409
+ <span class="inspector-section-icon">${this.getSectionIcon(t)}</span>
410
+ <span class="inspector-section-title">${this.formatLabel(t)}</span>
509
411
  </div>
510
- <div class="inspector-section-body" data-section-body="${i}">
511
- ${a.join("")}
412
+ <div class="inspector-section-body" data-section-body="${t}">
413
+ ${s.join("")}
512
414
  </div>
513
415
  </div>
514
- `}attachEventListeners(){var c,d,u,p;if(!this.contentContainer)return;let t=this.contentContainer.querySelectorAll("[data-property-path]"),i=Zm((f,g,h)=>{var m,b;this.updateManager.updateProperty(f,g,h),(b=(m=this.options)==null?void 0:m.onPropertyChange)==null||b.call(m,f,g,h)},300);t.forEach(f=>{let g=m=>{var x,w;let b=m.target,y=b.dataset.propertyPath,v=b.dataset.objectId;if(y&&v){let E=b.value;if(b.type==="checkbox")E=b.checked;else if(b.type==="number"&&(E=parseFloat(b.value),isNaN(E)))return;b.type==="text"||b.type==="range"||b.tagName==="TEXTAREA"?i(v,y,E):(this.updateManager.updateProperty(v,y,E),(w=(x=this.options)==null?void 0:x.onPropertyChange)==null||w.call(x,v,y,E))}},h=f.dataset.propertyPath;h==="logic.id"||h!=null&&h.endsWith(".logic.id")?(console.log("[Inspector v1.0.0] PATH-BASED DETECTION ACTIVE - logic ID found at:",h),f.addEventListener("change",async m=>{var T;let b=m.target,y=b.dataset.propertyPath,v=b.dataset.objectId,x=b.value;if(console.log("[Inspector v1.0.0] Logic ID changed to:",x),!y||!v)return;await this.updateManager.updateProperty(v,y,x),console.log("[Inspector v1.0.0] Logic ID updated");let w=window,E=(T=w==null?void 0:w.__HANDLER_LOGIC_META)==null?void 0:T[x],A=this.getDefaultPropsForLogic(x,E);console.log("[Inspector v1.0.0] New logic default props:",A);let _=y.replace(".id",".props");await this.updateManager.updateProperty(v,_,A),console.log("[Inspector v1.0.0] Logic props updated to:",A),console.log("[Inspector v1.0.0] Reloading inspector with updated config"),this.loadObject(v)})):(f.addEventListener("change",g),(f.tagName==="INPUT"||f.tagName==="TEXTAREA")&&f.addEventListener("input",g))}),this.contentContainer.querySelectorAll("[data-action]").forEach(f=>{f.addEventListener("click",g=>{let h=g.target,m=h.dataset.action,b=h.dataset.path,y=h.dataset.object;m&&b&&y&&this.quickActions.handleAction(m,y,b)})}),this.contentContainer.querySelectorAll("[data-section-toggle]").forEach(f=>{f.addEventListener("click",g=>{var b,y;let h=g.target,m=h.dataset.sectionToggle||((b=h.closest("[data-section-toggle]"))==null?void 0:b.getAttribute("data-section-toggle"));if(m){let v=(y=this.contentContainer)==null?void 0:y.querySelector(`[data-section="${m}"]`);v==null||v.classList.toggle("collapsed")}})});let a=(c=this.root)==null?void 0:c.querySelector("[data-inspector-advanced]");a==null||a.addEventListener("click",()=>{this.showAdvanced=!this.showAdvanced,this.selectedObjectId&&this.loadObject(this.selectedObjectId)});let s=(d=this.root)==null?void 0:d.querySelector("[data-convert-toggle]");s==null||s.addEventListener("click",()=>{var g;let f=(g=this.root)==null?void 0:g.querySelector("[data-convert-menu]");f==null||f.classList.toggle("hidden")});let o=(u=this.contentContainer)==null?void 0:u.querySelector("[data-inspector-add-component-btn]"),l=(p=this.contentContainer)==null?void 0:p.querySelector("[data-inspector-component-select]");o==null||o.addEventListener("click",async()=>{let f=l.value;f&&this.selectedObjectId&&await this.addComponent(this.selectedObjectId,f)})}async addComponent(t,i){console.log("[InspectorPanel] Adding component:",i,"to:",t);let n=window.getEditableObjectConfig,r=n==null?void 0:n(t);if(!r){console.error("[InspectorPanel] Failed to get config for:",t);return}let a=window.__editableConfig,s=a==null?void 0:a.schemas,o=null;s instanceof Map?o=s.get(i):s&&typeof s=="object"&&(o=s[i]),o||console.warn("[InspectorPanel] Schema not found for component:",i);let l=(o==null?void 0:o.defaults)||{enabled:!0};r[i]={...l},await this.updateManager.updateProperty(t,i,r[i]),this.loadObject(t),console.log("[InspectorPanel] Component added successfully")}isSectionMeaningful(t,i,n){var a,s;if(["identity","transform","render"].includes(t))return!0;if(!i||typeof i!="object"||t==="ui"&&((s=(a=n.render)==null?void 0:a.asset)==null?void 0:s.type)==="image")return!1;if(t==="interaction")return i.clickable===!0||i.draggable===!0;if(i.enabled===!0||i.active===!0||i.visible===!0)return!0;if(t==="ui")return!!(i.text||i.font||i.fontSize);let r=Object.keys(i);return r.length===0||r.length===1&&r[0]==="enabled"&&i.enabled===!1?!1:["audio","effects","physics","motion","gameplay"].includes(t)?i.enabled===!0:!0}showError(t){this.contentContainer&&(this.contentContainer.innerHTML=`
416
+ `}attachEventListeners(){var c,p,d,u;if(!this.contentContainer)return;let e=this.contentContainer.querySelectorAll("[data-property-path]"),t=Ro((g,h,f)=>{var m,b;this.updateManager.updateProperty(g,h,f),(b=(m=this.options)==null?void 0:m.onPropertyChange)==null||b.call(m,g,h,f)},300);e.forEach(g=>{let h=m=>{var x,E;let b=m.target,y=b.dataset.propertyPath,v=b.dataset.objectId;if(y&&v){let w=b.value;if(b.type==="checkbox")w=b.checked;else if(b.type==="number"&&(w=parseFloat(b.value),isNaN(w)))return;b.type==="text"||b.type==="range"||b.tagName==="TEXTAREA"?t(v,y,w):(this.updateManager.updateProperty(v,y,w),(E=(x=this.options)==null?void 0:x.onPropertyChange)==null||E.call(x,v,y,w))}},f=g.dataset.propertyPath;f==="logic.id"||f!=null&&f.endsWith(".logic.id")?(console.log("[Inspector v1.0.0] PATH-BASED DETECTION ACTIVE - logic ID found at:",f),g.addEventListener("change",async m=>{var O;let b=m.target,y=b.dataset.propertyPath,v=b.dataset.objectId,x=b.value;if(console.log("[Inspector v1.0.0] Logic ID changed to:",x),!y||!v)return;await this.updateManager.updateProperty(v,y,x),console.log("[Inspector v1.0.0] Logic ID updated");let E=window,w=(O=E==null?void 0:E.__HANDLER_LOGIC_META)==null?void 0:O[x],T=this.getDefaultPropsForLogic(x,w);console.log("[Inspector v1.0.0] New logic default props:",T);let S=y.replace(".id",".props");await this.updateManager.updateProperty(v,S,T),console.log("[Inspector v1.0.0] Logic props updated to:",T),console.log("[Inspector v1.0.0] Reloading inspector with updated config"),this.loadObject(v)})):(g.addEventListener("change",h),(g.tagName==="INPUT"||g.tagName==="TEXTAREA")&&g.addEventListener("input",h))}),this.contentContainer.querySelectorAll("[data-action]").forEach(g=>{g.addEventListener("click",h=>{let f=h.target,m=f.dataset.action,b=f.dataset.path,y=f.dataset.object;m&&b&&y&&this.quickActions.handleAction(m,y,b)})}),this.contentContainer.querySelectorAll("[data-section-toggle]").forEach(g=>{g.addEventListener("click",h=>{var b,y;let f=h.target,m=f.dataset.sectionToggle||((b=f.closest("[data-section-toggle]"))==null?void 0:b.getAttribute("data-section-toggle"));if(m){let v=(y=this.contentContainer)==null?void 0:y.querySelector(`[data-section="${m}"]`);v==null||v.classList.toggle("collapsed")}})});let s=(c=this.root)==null?void 0:c.querySelector("[data-inspector-advanced]");s==null||s.addEventListener("click",()=>{this.showAdvanced=!this.showAdvanced,this.selectedObjectId&&this.loadObject(this.selectedObjectId)});let r=(p=this.root)==null?void 0:p.querySelector("[data-convert-toggle]");r==null||r.addEventListener("click",()=>{var h;let g=(h=this.root)==null?void 0:h.querySelector("[data-convert-menu]");g==null||g.classList.toggle("hidden")});let o=(d=this.contentContainer)==null?void 0:d.querySelector("[data-inspector-add-component-btn]"),l=(u=this.contentContainer)==null?void 0:u.querySelector("[data-inspector-component-select]");o==null||o.addEventListener("click",async()=>{let g=l.value;g&&this.selectedObjectId&&await this.addComponent(this.selectedObjectId,g)})}async addComponent(e,t){console.log("[InspectorPanel] Adding component:",t,"to:",e);let n=window.getEditableObjectConfig,a=n==null?void 0:n(e);if(!a){console.error("[InspectorPanel] Failed to get config for:",e);return}let s=window.__editableConfig,r=s==null?void 0:s.schemas,o=null;r instanceof Map?o=r.get(t):r&&typeof r=="object"&&(o=r[t]),o||console.warn("[InspectorPanel] Schema not found for component:",t);let l=(o==null?void 0:o.defaults)||{enabled:!0};a[t]={...l},await this.updateManager.updateProperty(e,t,a[t]),this.loadObject(e),console.log("[InspectorPanel] Component added successfully")}isSectionMeaningful(e,t,n){var s,r;if(["identity","transform","render"].includes(e))return!0;if(!t||typeof t!="object"||e==="ui"&&((r=(s=n.render)==null?void 0:s.asset)==null?void 0:r.type)==="image")return!1;if(e==="interaction")return t.clickable===!0||t.draggable===!0;if(t.enabled===!0||t.active===!0||t.visible===!0)return!0;if(e==="ui")return!!(t.text||t.font||t.fontSize);let a=Object.keys(t);return a.length===0||a.length===1&&a[0]==="enabled"&&t.enabled===!1?!1:["audio","effects","physics","motion","gameplay"].includes(e)?t.enabled===!0:!0}showError(e){this.contentContainer&&(this.contentContainer.innerHTML=`
515
417
  <div class="inspector-empty">
516
418
  <span class="inspector-empty-icon">\u26A0\uFE0F</span>
517
- <span class="inspector-empty-text">${t}</span>
419
+ <span class="inspector-empty-text">${e}</span>
518
420
  </div>
519
- `)}formatLabel(t){return t.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,i=>i.toUpperCase())}getDefaultPropsForLogic(t,i){return{DragToWin:{targetDrags:3},DragSnap:{targetId:"",snapRadius:100,snapDuration:.5,returnOnMiss:!0,returnDuration:.3,ease:"power2.out"},SwerveMove:{speed:5,sensitivity:1,directionMode:"dominantAxis",axis:"both",bounds:{left:-400,right:400,top:-300,bottom:300}},JoystickMove:{speed:200,zone:"bottom-center",offsetX:0,offsetY:-50,inputId:""}}[t]||{}}getSectionIcon(t){return{identity:"\u{1F194}",transform:"\u{1F4D0}",render:"\u{1F3A8}",ui:"\u{1F4AC}",gameplay:"\u{1F3AE}",interaction:"\u{1F446}",audio:"\u{1F50A}",effects:"\u2728",motion:"\u{1F3AC}"}[t]||"\u{1F4E6}"}clear(){this.selectedObjectId=null,this.contentContainer&&(this.contentContainer.innerHTML=`
421
+ `)}formatLabel(e){return e.replace(/_/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/\b\w/g,t=>t.toUpperCase())}getDefaultPropsForLogic(e,t){return{DragToWin:{targetDrags:3},DragSnap:{targetId:"",snapRadius:100,snapDuration:.5,returnOnMiss:!0,returnDuration:.3,ease:"power2.out"},SwerveMove:{speed:5,sensitivity:1,directionMode:"dominantAxis",axis:"both",bounds:{left:-400,right:400,top:-300,bottom:300}},JoystickMove:{speed:200,zone:"bottom-center",offsetX:0,offsetY:-50,inputId:""}}[e]||{}}getSectionIcon(e){return{identity:"\u{1F194}",transform:"\u{1F4D0}",render:"\u{1F3A8}",ui:"\u{1F4AC}",gameplay:"\u{1F3AE}",interaction:"\u{1F446}",audio:"\u{1F50A}",effects:"\u2728",motion:"\u{1F3AC}"}[e]||"\u{1F4E6}"}clear(){this.selectedObjectId=null,this.contentContainer&&(this.contentContainer.innerHTML=`
520
422
  <div class="inspector-empty">
521
423
  <span class="inspector-empty-icon">\u{1F3AF}</span>
522
424
  <span class="inspector-empty-text">Select an object to inspect</span>
523
425
  </div>
524
- `)}};var ig=di($h(),1);function Nl(e){return new Promise((t,i)=>{let n=new FileReader;n.onerror=()=>i(new Error("FileReader failed")),n.onload=()=>t(String(n.result||"")),n.readAsDataURL(e)})}function Hh(e){var r;let[t,i]=e.split(","),n=t==null?void 0:t.match(/data:(.*?);base64/);return{base64:i!=null?i:"",mimeType:(r=n==null?void 0:n[1])!=null?r:"image/png"}}async function Uh(e){return await new Promise(t=>{let i=new Image;i.onload=()=>t({width:i.naturalWidth||i.width,height:i.naturalHeight||i.height}),i.onerror=()=>t(null),i.src=e})}async function Ga(e){var t,i;try{console.log("[ImageUtils] Fetching image data from URL:",e);let n=await fetch(e);if(!n.ok)return console.warn("[ImageUtils] Fetch failed with status:",n.status,e),null;let r=await n.blob();console.log("[ImageUtils] Blob received, size:",r.size,"type:",r.type);let a=await Nl(r),s=await Uh(a),o=Hh(a);return console.log("[ImageUtils] Success resolution:",s==null?void 0:s.width,"x",s==null?void 0:s.height,"mime:",o.mimeType),{base64:o.base64,mimeType:o.mimeType,dataUrl:a,width:(t=s==null?void 0:s.width)!=null?t:0,height:(i=s==null?void 0:s.height)!=null?i:0}}catch(n){return console.error("[ImageUtils] Error fetching image data:",n),null}}async function Mt(e){var t,i;try{let n=await Nl(e),r=await Uh(n),a=Hh(n);return{base64:a.base64,mimeType:a.mimeType,dataUrl:n,width:(t=r==null?void 0:r.width)!=null?t:0,height:(i=r==null?void 0:r.height)!=null?i:0}}catch{return null}}function qh(e){return Nl(e).then(t=>t).catch(()=>null)}function Bl(e,t){var i;try{let[n,r]=e.split(","),a=n.match(/data:(.*?);base64/),s=(i=a==null?void 0:a[1])!=null?i:"image/png",o=atob(r),l=new Uint8Array(o.length);for(let c=0;c<o.length;c++)l[c]=o.charCodeAt(c);return new File([l],t,{type:s})}catch{return null}}async function qi(e,t=30){try{console.log("[ImageUtils] Removing background color...");let i=await new Promise((u,p)=>{let f=new Image;f.onload=()=>u(f),f.onerror=()=>p(new Error("Failed to load image")),f.src=e}),n=document.createElement("canvas");n.width=i.width,n.height=i.height;let r=n.getContext("2d");if(!r)return console.error("[ImageUtils] Failed to get canvas context"),e;r.drawImage(i,0,0);let a=r.getImageData(0,0,n.width,n.height),s=a.data,l=[{name:"top-left",offset:0},{name:"top-right",offset:(n.width-1)*4},{name:"bottom-left",offset:(n.height-1)*n.width*4},{name:"bottom-right",offset:((n.height-1)*n.width+(n.width-1))*4}].map(u=>({r:s[u.offset],g:s[u.offset+1],b:s[u.offset+2]})),c=0;for(let u=0;u<s.length;u+=4){let p=s[u],f=s[u+1],g=s[u+2],h=!1;for(let m of l)if(Math.sqrt(Math.pow(p-m.r,2)+Math.pow(f-m.g,2)+Math.pow(g-m.b,2))<t){h=!0;break}h&&(s[u+3]=0,c++)}return console.log(`[ImageUtils] Removed background from ${c} pixels (4-corner sampling, tolerance: ${t})`),r.putImageData(a,0,0),n.toDataURL("image/png")}catch(i){return console.error("[ImageUtils] Error removing background:",i),e}}function Gh(e,t){if(!e||!t)return"1:1";let i=e/t;return i>1.3?"16:9":i<.77?"9:16":"1:1"}function ut(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ce(e){return typeof e=="string"?e:void 0}function Wh(e){return e.toLowerCase().endsWith(".png")?e.slice(0,-4):e}function Iw(e){var n,r,a;let t=(n=ce(e.id))!=null?n:ce(e.name);if(t)return t;let i=(r=ce(e.file))!=null?r:ce(e.asset);return i?Wh((a=i.split("/").pop())!=null?a:i):void 0}function Mw(e,t,i){var n,r,a;if(typeof t=="string")return{id:e,file:t,role:i};if(ut(t)){let s=(n=ce(t.file))!=null?n:ce(t.asset);return s?{id:(r=ce(t.id))!=null?r:e,file:s,role:(a=ce(t.role))!=null?a:i,dataUrl:ce(t.dataUrl),layout:t.layout}:null}return null}function Fl(e,t){var i,n,r;if(!e)return[];if(Array.isArray(e)){let a=[];for(let s of e){if(typeof s=="string"){let o=Wh((i=s.split("/").pop())!=null?i:s);a.push({id:o,file:s,role:t});continue}if(ut(s)){let o=Iw(s),l=(n=ce(s.file))!=null?n:ce(s.asset);if(!o||!l)continue;a.push({id:o,file:l,role:(r=ce(s.role))!=null?r:t,dataUrl:ce(s.dataUrl),layout:s.layout})}}return a}if(ut(e)){let a=[];for(let[s,o]of Object.entries(e)){let l=Mw(s,o,t);l&&a.push(l)}return a}return[]}function Pw(e){var t,i;return(i=(t=ce(e.brand_name))!=null?t:ce(e.brandName))!=null?i:ce(e.name)}function Rw(e){if(ut(e.brand_dna)&&ut(e.brand_dna.colors))return e.brand_dna;if(ut(e.colors)){let t={colors:e.colors};return typeof e.style=="string"&&(t.style=e.style),ut(e.fonts)&&(t.fonts=e.fonts),t}}function jw(e){var i;let t=new Map;for(let n of e){let r=t.get(n.id);if(!r){t.set(n.id,n);continue}t.set(n.id,{...r,...n,file:n.file||r.file,role:n.role||r.role,dataUrl:n.dataUrl||r.dataUrl,layout:(i=n.layout)!=null?i:r.layout})}return Array.from(t.values())}function $l(e,t={}){var s,o,l;let i=e.filter(ut),n=(o=(s=i.map(Pw).find(Boolean))!=null?s:t.defaultBrandName)!=null?o:"Imported Brand",r=(l=i.map(Rw).find(Boolean))!=null?l:{colors:{}},a=[];for(let c of i)"layers"in c&&a.push(...Fl(c.layers,"visual element")),"assets"in c&&a.push(...Fl(c.assets,"visual element")),ut(c.endgame)&&"assets"in c.endgame&&a.push(...Fl(c.endgame.assets,"endgame"));return{version:"1.0",brand_name:n,brand_dna:r,assets:jw(a)}}var Vh=require("@google/genai");async function Wa(e,t,i=[],n={}){var r,a,s,o,l,c,d;try{if(!(e!=null&&e.trim()))throw new Error("Gemini API key is required");if(!(t!=null&&t.trim()))throw new Error("Prompt is required");for(let b=0;b<i.length;b++){let y=i[b];if(!y.base64||!y.mimeType)throw new Error(`Image ${b+1} is missing required data`);if(y.base64.length<1e3&&console.warn(`Image ${b+1} data appears very small, may be corrupted`),!y.mimeType.startsWith("image/"))throw new Error(`Image ${b+1} has invalid MIME type: ${y.mimeType}`)}let u=new Vh.GoogleGenAI({apiKey:e}),p="gemini-2.5-flash",f=[t];i.length>0&&i.forEach((b,y)=>{f.push({inlineData:{data:b.base64,mimeType:b.mimeType}}),console.log(`[Gemini] Added image ${y+1}: ${b.mimeType}, size: ${Math.round(b.base64.length/1024)}KB`)}),console.log(`[Gemini] Making request with ${i.length} images and prompt length: ${t.length}`);let g=await u.models.generateContent({model:p,contents:f}),h="",m=(s=(a=(r=g.candidates)==null?void 0:r[0])==null?void 0:a.content)==null?void 0:s.parts;if(m)for(let b of m)b.text&&(h+=b.text);if(!h.trim())throw new Error("Empty response from Gemini API");return console.log(`[Gemini] Response received, length: ${h.length}`),h}catch(u){throw console.error("[Gemini] API error:",u),(o=u.message)!=null&&o.includes("Unable to process input image")?new Error("Unable to process the uploaded image. Please ensure it's a valid PNG, JPG, or JPEG file under 10MB and not corrupted."):(l=u.message)!=null&&l.includes("API_KEY_INVALID")?new Error("Invalid Gemini API key. Please check your API key configuration."):(c=u.message)!=null&&c.includes("QUOTA_EXCEEDED")?new Error("Gemini API quota exceeded. Please try again later or check your billing."):(d=u.message)!=null&&d.includes("SAFETY")?new Error("Content was flagged by Gemini safety filters. Please try with different images."):u}}var Yh=require("@google/genai");async function Gi(e,t,i=[],n={}){try{console.info("[GEMINI-REAL-SDK] Initializing GoogleGenAI...");let r=new Yh.GoogleGenAI({apiKey:e}),a=[{text:t}];i.length>0&&i.forEach((o,l)=>{console.info(`[GEMINI-REAL-SDK] Adding image part ${l}`),a.push({inlineData:{mimeType:o.mimeType,data:o.base64}})}),console.info("[GEMINI-REAL-SDK] Calling generateContent with model: gemini-2.5-flash-image");let s=await r.models.generateContent({model:"gemini-2.5-flash-image",contents:a});if(console.info("[GEMINI-REAL-SDK] Received response from model"),!s.candidates||!s.candidates[0]||!s.candidates[0].content||!s.candidates[0].content.parts)throw new Error("Gemini 2.5 Flash Image returned invalid response structure.");for(let o of s.candidates[0].content.parts)if(o.text)console.log(o.text);else if(o.inlineData){let l=o.inlineData.data,c=o.inlineData.mimeType||"image/png";return console.info("[GEMINI-REAL-SDK] Found inline image data in response"),`data:${c};base64,${l}`}throw new Error("Gemini 2.5 Flash Image returned no image data.")}catch(r){throw console.error("[GEMINI-REAL-SDK] Error in generateImageWithGemini25Flash:",JSON.stringify(r,Object.getOwnPropertyNames(r),2)),r}}function Kh(e){let t=e.brandAssets.map(a=>{let s=`- ${a.id}: ${a.role}`;return a.layout&&(s+=` [pos: ${a.layout.x.toFixed(0)},${a.layout.y.toFixed(0)}, size: ${a.layout.w.toFixed(0)}x${a.layout.h.toFixed(0)}, z: ${a.layout.z}, opacity: ${a.layout.opacity}]`),s}).join(`
525
- `)||"None",i=e.brandDna?`Colors: ${JSON.stringify(e.brandDna.colors)}, Style: ${e.brandDna.style||"not specified"}`:"Not provided",n=e.gameObjects.map(a=>typeof a=="string"?`- id: ${a}`:`- id: ${a.id}${a.category?`, category: ${a.category}`:""}${a.type?`, type: ${a.type}`:""}`).join(`
526
- `),r="";if(e.brandConfig){let a=e.brandConfig,s=[];a.splash&&s.push(`SPLASH: title="${a.splash.title||""}", subtitle="${a.splash.subtitle||""}", button="${a.splash.button_label||""}"`),a.endgame&&s.push(`ENDGAME: title="${a.endgame.title||""}", subtitle="${a.endgame.subtitle||""}", cta="${a.endgame.cta_label||""}"`),a.tutorial&&s.push(`TUTORIAL: text="${a.tutorial.label_text||""}", helper="${a.tutorial.helper_text||""}"`),s.length>0&&(r=`
426
+ `)}};var Hs=Ve(require("jszip"),1);function Ii(i){return new Promise((e,t)=>{let n=new FileReader;n.onerror=()=>t(new Error("FileReader failed")),n.onload=()=>e(String(n.result||"")),n.readAsDataURL(i)})}function Ls(i){var a;let[e,t]=i.split(","),n=e==null?void 0:e.match(/data:(.*?);base64/);return{base64:t!=null?t:"",mimeType:(a=n==null?void 0:n[1])!=null?a:"image/png"}}async function Ts(i){return await new Promise(e=>{let t=new Image;t.onload=()=>e({width:t.naturalWidth||t.width,height:t.naturalHeight||t.height}),t.onerror=()=>e(null),t.src=i})}async function Tn(i){var e,t;try{console.log("[ImageUtils] Fetching image data from URL:",i);let n=await fetch(i);if(!n.ok)return console.warn("[ImageUtils] Fetch failed with status:",n.status,i),null;let a=await n.blob();console.log("[ImageUtils] Blob received, size:",a.size,"type:",a.type);let s=await Ii(a),r=await Ts(s),o=Ls(s);return console.log("[ImageUtils] Success resolution:",r==null?void 0:r.width,"x",r==null?void 0:r.height,"mime:",o.mimeType),{base64:o.base64,mimeType:o.mimeType,dataUrl:s,width:(e=r==null?void 0:r.width)!=null?e:0,height:(t=r==null?void 0:r.height)!=null?t:0}}catch(n){return console.error("[ImageUtils] Error fetching image data:",n),null}}async function Te(i){var e,t;try{let n=await Ii(i),a=await Ts(n),s=Ls(n);return{base64:s.base64,mimeType:s.mimeType,dataUrl:n,width:(e=a==null?void 0:a.width)!=null?e:0,height:(t=a==null?void 0:a.height)!=null?t:0}}catch{return null}}function _s(i){return Ii(i).then(e=>e).catch(()=>null)}function Ri(i,e){var t;try{let[n,a]=i.split(","),s=n.match(/data:(.*?);base64/),r=(t=s==null?void 0:s[1])!=null?t:"image/png",o=atob(a),l=new Uint8Array(o.length);for(let c=0;c<o.length;c++)l[c]=o.charCodeAt(c);return new File([l],e,{type:r})}catch{return null}}async function Qe(i,e=30){try{console.log("[ImageUtils] Removing background color...");let t=await new Promise((d,u)=>{let g=new Image;g.onload=()=>d(g),g.onerror=()=>u(new Error("Failed to load image")),g.src=i}),n=document.createElement("canvas");n.width=t.width,n.height=t.height;let a=n.getContext("2d");if(!a)return console.error("[ImageUtils] Failed to get canvas context"),i;a.drawImage(t,0,0);let s=a.getImageData(0,0,n.width,n.height),r=s.data,l=[{name:"top-left",offset:0},{name:"top-right",offset:(n.width-1)*4},{name:"bottom-left",offset:(n.height-1)*n.width*4},{name:"bottom-right",offset:((n.height-1)*n.width+(n.width-1))*4}].map(d=>({r:r[d.offset],g:r[d.offset+1],b:r[d.offset+2]})),c=0;for(let d=0;d<r.length;d+=4){let u=r[d],g=r[d+1],h=r[d+2],f=!1;for(let m of l)if(Math.sqrt(Math.pow(u-m.r,2)+Math.pow(g-m.g,2)+Math.pow(h-m.b,2))<e){f=!0;break}f&&(r[d+3]=0,c++)}return console.log(`[ImageUtils] Removed background from ${c} pixels (4-corner sampling, tolerance: ${e})`),a.putImageData(s,0,0),n.toDataURL("image/png")}catch(t){return console.error("[ImageUtils] Error removing background:",t),i}}function Ps(i,e){if(!i||!e)return"1:1";let t=i/e;return t>1.3?"16:9":t<.77?"9:16":"1:1"}function be(i){return typeof i=="object"&&i!==null&&!Array.isArray(i)}function W(i){return typeof i=="string"?i:void 0}function Ms(i){return i.toLowerCase().endsWith(".png")?i.slice(0,-4):i}function jo(i){var n,a,s;let e=(n=W(i.id))!=null?n:W(i.name);if(e)return e;let t=(a=W(i.file))!=null?a:W(i.asset);return t?Ms((s=t.split("/").pop())!=null?s:t):void 0}function Do(i,e,t){var n,a,s;if(typeof e=="string")return{id:i,file:e,role:t};if(be(e)){let r=(n=W(e.file))!=null?n:W(e.asset);return r?{id:(a=W(e.id))!=null?a:i,file:r,role:(s=W(e.role))!=null?s:t,dataUrl:W(e.dataUrl),layout:e.layout}:null}return null}function ji(i,e){var t,n,a;if(!i)return[];if(Array.isArray(i)){let s=[];for(let r of i){if(typeof r=="string"){let o=Ms((t=r.split("/").pop())!=null?t:r);s.push({id:o,file:r,role:e});continue}if(be(r)){let o=jo(r),l=(n=W(r.file))!=null?n:W(r.asset);if(!o||!l)continue;s.push({id:o,file:l,role:(a=W(r.role))!=null?a:e,dataUrl:W(r.dataUrl),layout:r.layout})}}return s}if(be(i)){let s=[];for(let[r,o]of Object.entries(i)){let l=Do(r,o,e);l&&s.push(l)}return s}return[]}function $o(i){var e,t;return(t=(e=W(i.brand_name))!=null?e:W(i.brandName))!=null?t:W(i.name)}function zo(i){if(be(i.brand_dna)&&be(i.brand_dna.colors))return i.brand_dna;if(be(i.colors)){let e={colors:i.colors};return typeof i.style=="string"&&(e.style=i.style),be(i.fonts)&&(e.fonts=i.fonts),e}}function No(i){var t;let e=new Map;for(let n of i){let a=e.get(n.id);if(!a){e.set(n.id,n);continue}e.set(n.id,{...a,...n,file:n.file||a.file,role:n.role||a.role,dataUrl:n.dataUrl||a.dataUrl,layout:(t=n.layout)!=null?t:a.layout})}return Array.from(e.values())}function Di(i,e={}){var r,o,l;let t=i.filter(be),n=(o=(r=t.map($o).find(Boolean))!=null?r:e.defaultBrandName)!=null?o:"Imported Brand",a=(l=t.map(zo).find(Boolean))!=null?l:{colors:{}},s=[];for(let c of t)"layers"in c&&s.push(...ji(c.layers,"visual element")),"assets"in c&&s.push(...ji(c.assets,"visual element")),be(c.endgame)&&"assets"in c.endgame&&s.push(...ji(c.endgame.assets,"endgame"));return{version:"1.0",brand_name:n,brand_dna:a,assets:No(s)}}var ks=require("@google/genai");async function _n(i,e,t=[],n={}){var a,s,r,o,l,c,p;try{if(!(i!=null&&i.trim()))throw new Error("Gemini API key is required");if(!(e!=null&&e.trim()))throw new Error("Prompt is required");for(let b=0;b<t.length;b++){let y=t[b];if(!y.base64||!y.mimeType)throw new Error(`Image ${b+1} is missing required data`);if(y.base64.length<1e3&&console.warn(`Image ${b+1} data appears very small, may be corrupted`),!y.mimeType.startsWith("image/"))throw new Error(`Image ${b+1} has invalid MIME type: ${y.mimeType}`)}let d=new ks.GoogleGenAI({apiKey:i}),u="gemini-2.5-flash",g=[e];t.length>0&&t.forEach((b,y)=>{g.push({inlineData:{data:b.base64,mimeType:b.mimeType}}),console.log(`[Gemini] Added image ${y+1}: ${b.mimeType}, size: ${Math.round(b.base64.length/1024)}KB`)}),console.log(`[Gemini] Making request with ${t.length} images and prompt length: ${e.length}`);let h=await d.models.generateContent({model:u,contents:g}),f="",m=(r=(s=(a=h.candidates)==null?void 0:a[0])==null?void 0:s.content)==null?void 0:r.parts;if(m)for(let b of m)b.text&&(f+=b.text);if(!f.trim())throw new Error("Empty response from Gemini API");return console.log(`[Gemini] Response received, length: ${f.length}`),f}catch(d){throw console.error("[Gemini] API error:",d),(o=d.message)!=null&&o.includes("Unable to process input image")?new Error("Unable to process the uploaded image. Please ensure it's a valid PNG, JPG, or JPEG file under 10MB and not corrupted."):(l=d.message)!=null&&l.includes("API_KEY_INVALID")?new Error("Invalid Gemini API key. Please check your API key configuration."):(c=d.message)!=null&&c.includes("QUOTA_EXCEEDED")?new Error("Gemini API quota exceeded. Please try again later or check your billing."):(p=d.message)!=null&&p.includes("SAFETY")?new Error("Content was flagged by Gemini safety filters. Please try with different images."):d}}var Os=require("@google/genai");async function et(i,e,t=[],n={}){try{console.info("[GEMINI-REAL-SDK] Initializing GoogleGenAI...");let a=new Os.GoogleGenAI({apiKey:i}),s=[{text:e}];t.length>0&&t.forEach((o,l)=>{console.info(`[GEMINI-REAL-SDK] Adding image part ${l}`),s.push({inlineData:{mimeType:o.mimeType,data:o.base64}})}),console.info("[GEMINI-REAL-SDK] Calling generateContent with model: gemini-2.5-flash-image");let r=await a.models.generateContent({model:"gemini-2.5-flash-image",contents:s});if(console.info("[GEMINI-REAL-SDK] Received response from model"),!r.candidates||!r.candidates[0]||!r.candidates[0].content||!r.candidates[0].content.parts)throw new Error("Gemini 2.5 Flash Image returned invalid response structure.");for(let o of r.candidates[0].content.parts)if(o.text)console.log(o.text);else if(o.inlineData){let l=o.inlineData.data,c=o.inlineData.mimeType||"image/png";return console.info("[GEMINI-REAL-SDK] Found inline image data in response"),`data:${c};base64,${l}`}throw new Error("Gemini 2.5 Flash Image returned no image data.")}catch(a){throw console.error("[GEMINI-REAL-SDK] Error in generateImageWithGemini25Flash:",JSON.stringify(a,Object.getOwnPropertyNames(a),2)),a}}function Is(i){let e=i.brandAssets.map(s=>{let r=`- ${s.id}: ${s.role}`;return s.layout&&(r+=` [pos: ${s.layout.x.toFixed(0)},${s.layout.y.toFixed(0)}, size: ${s.layout.w.toFixed(0)}x${s.layout.h.toFixed(0)}, z: ${s.layout.z}, opacity: ${s.layout.opacity}]`),r}).join(`
427
+ `)||"None",t=i.brandDna?`Colors: ${JSON.stringify(i.brandDna.colors)}, Style: ${i.brandDna.style||"not specified"}`:"Not provided",n=i.gameObjects.map(s=>typeof s=="string"?`- id: ${s}`:`- id: ${s.id}${s.category?`, category: ${s.category}`:""}${s.type?`, type: ${s.type}`:""}`).join(`
428
+ `),a="";if(i.brandConfig){let s=i.brandConfig,r=[];s.splash&&r.push(`SPLASH: title="${s.splash.title||""}", subtitle="${s.splash.subtitle||""}", button="${s.splash.button_label||""}"`),s.endgame&&r.push(`ENDGAME: title="${s.endgame.title||""}", subtitle="${s.endgame.subtitle||""}", cta="${s.endgame.cta_label||""}"`),s.tutorial&&r.push(`TUTORIAL: text="${s.tutorial.label_text||""}", helper="${s.tutorial.helper_text||""}"`),r.length>0&&(a=`
527
429
  BRAND CONTENT:
528
- ${s.join(`
430
+ ${r.join(`
529
431
  `)}
530
432
  `)}return`
531
433
  You are analyzing a brand's visual design for use in a playable ad game.
532
434
 
533
435
  GAME CONTEXT:
534
- ${e.gamePrompt||"Simple game"}
436
+ ${i.gamePrompt||"Simple game"}
535
437
 
536
438
  GAME OBJECTS (need assets):
537
439
  ${n}
538
440
 
539
441
  BRAND ASSETS PROVIDED:
540
- ${t}
442
+ ${e}
541
443
 
542
444
  BRAND DNA:
543
- ${i}
544
- ${r}
445
+ ${t}
446
+ ${a}
545
447
  VISUAL REFERENCE: [See attached flat design image]
546
448
 
547
449
  TASK:
@@ -585,28 +487,28 @@ OUTPUT ONLY VALID JSON (no markdown, no explanation):
585
487
  }
586
488
  ]
587
489
  }
588
- `.trim()}function Xh(e){var r,a;let t=(r=e.brandDna)!=null&&r.colors?`Primary: ${e.brandDna.colors.primary}, Secondary: ${e.brandDna.colors.secondary||"N/A"}, Accent: ${e.brandDna.colors.accent||"N/A"}`:"Use provided reference colors",i=((a=e.brandDna)==null?void 0:a.style)||"modern gaming style",n=e.needsTransparency?"BACKGROUND: REQUIRED solid magenta #FF00FF (for transparency removal)":"BACKGROUND: Use brand colors naturally, fill the entire frame";return`
589
- TASK: ${e.prompt}
490
+ `.trim()}function Rs(i){var a,s;let e=(a=i.brandDna)!=null&&a.colors?`Primary: ${i.brandDna.colors.primary}, Secondary: ${i.brandDna.colors.secondary||"N/A"}, Accent: ${i.brandDna.colors.accent||"N/A"}`:"Use provided reference colors",t=((s=i.brandDna)==null?void 0:s.style)||"modern gaming style",n=i.needsTransparency?"BACKGROUND: REQUIRED solid magenta #FF00FF (for transparency removal)":"BACKGROUND: Use brand colors naturally, fill the entire frame";return`
491
+ TASK: ${i.prompt}
590
492
 
591
493
  BRAND STYLE:
592
- - Colors: ${t}
593
- - Style: ${i}
494
+ - Colors: ${e}
495
+ - Style: ${t}
594
496
 
595
497
  CHANGE_STRENGTH: 8/10
596
- REFERENCE: ${e.hasReference?"provided (use as style guide for colors and aesthetics)":"none"}
498
+ REFERENCE: ${i.hasReference?"provided (use as style guide for colors and aesthetics)":"none"}
597
499
  ${n}
598
500
 
599
501
  OUTPUT CONSTRAINTS (MUST FOLLOW):
600
502
  - Do NOT add extra text unless specifically requested
601
- - Preserve aspect ratio${e.aspectRatio?` (target: ${e.aspectRatio})`:""}
503
+ - Preserve aspect ratio${i.aspectRatio?` (target: ${i.aspectRatio})`:""}
602
504
  - Keep padding under 5% of asset size
603
505
  - No drop shadows unless explicitly requested
604
- - No gradients on the background (solid ${e.needsTransparency?"magenta":"colors"} only)
506
+ - No gradients on the background (solid ${i.needsTransparency?"magenta":"colors"} only)
605
507
  - Center the subject in frame
606
508
 
607
509
  OUTPUT:
608
- Generate the requested asset matching the brand style.${e.needsTransparency?" Background MUST be solid magenta (#FF00FF).":""}
609
- `.trim()}function Zh(e){return e.map(t=>{if(typeof t=="string"){let i=t,n,r;return i.includes("background")?(n="background",r="background"):i.includes("button")||i.includes("cta")?(n="ui",r="button"):i.includes("logo")?(n="ui",r="logo"):i.includes("title")||i.includes("subtitle")||i.includes("text")?(n="text",r="text"):i.includes("effect")||i.includes("confetti")||i.includes("particle")?(n="effects",r="effect"):i.includes("ui.")||i.includes("splash")||i.includes("endgame")?(n="ui",r="image"):(n="environment",r="interactive"),{id:i,category:n,type:r}}return t})}function Jh(e,t){return!(e.includes("background")&&(e.includes("_1")||e.includes("splash")||e.includes("endgame")||e.includes("main"))||t==="text"||t==="effects"&&e.includes("particle"))}async function Qh(e){var s,o;let t=Zh(e.gameObjects),i={gamePrompt:e.gamePrompt,gameObjects:t,brandAssets:e.manifest.assets,brandDna:e.manifest.brand_dna,brandName:e.manifest.brand_name},n=Kh(i),r=[];if(e.flatDesignDataUrl)try{let l=eg(e.flatDesignDataUrl);l&&l.base64&&l.mimeType?l.base64.length<100?console.warn("[Pipeline] Flat design data URL appears invalid (too short)"):(r.push(l),console.log("[Pipeline] Added flat design to analysis, size:",l.base64.length)):console.warn("[Pipeline] Failed to parse flat design data URL")}catch(l){console.warn("[Pipeline] Error processing flat design:",l)}console.log("[Pipeline] Running analysis chain with",r.length,"images...");let a;try{a=await Wa(e.apiKey,n,r,{model:"gemini-2.5-flash"}),console.log("[Pipeline] Analysis response received")}catch(l){throw console.error("[Pipeline] Gemini API error:",l),(s=l.message)!=null&&s.includes("Unable to process input image")?new Error("Gemini API unable to process the uploaded images. Please try with different images or ensure they are valid PNG/JPG files under 10MB."):(o=l.message)!=null&&o.includes("image")?new Error("Image processing failed. Please ensure your images are valid and not corrupted."):l}return Dw(a,e.gameObjects)}function Dw(e,t){try{let i=e,n=e.match(/```(?:json)?\s*([\s\S]*?)```/);if(n)i=n[1].trim();else{let a=e.match(/\{[\s\S]*\}/);a&&(i=a[0])}let r=JSON.parse(i);return r.mappings&&Array.isArray(r.mappings)?{mappingResult:r,rawResponse:e,parsed:!0}:{mappingResult:{mappings:t.map(a=>({game_object:a,action:"KEEP",status:"Analysis response missing mappings[]"}))},rawResponse:e,parsed:!1,parseError:"Missing mappings[] array"}}catch(i){return{mappingResult:{mappings:t.map(n=>({game_object:n,action:"KEEP",status:"Analysis response was not valid JSON"}))},rawResponse:e,parsed:!1,parseError:i!=null&&i.message?String(i.message):"JSON parse failed"}}}async function Hl(e,t,i={}){var r;let n=t.mappings.filter(a=>a.action==="GENERATE");if(n.length===0){console.log("[Pipeline] No assets to generate");return}console.log(`[Pipeline] Generating ${n.length} assets...`);for(let a=0;a<n.length;a++){let s=n[a];(r=i.onProgress)==null||r.call(i,a+1,n.length,s.game_object);try{let o=await zw(e,s);s.output_dataUrl=o,s.status="Generated \u2713"}catch(o){console.error(`[Pipeline] Failed to generate ${s.game_object}:`,o),s.status="Failed \u2717"}}console.log("[Pipeline] Generation chain complete")}async function zw(e,t){if(!t.generation_prompt)throw new Error("No generation prompt provided");let i=[];if(t.reference_asset&&e.manifest){let o=e.manifest.assets.find(l=>l.id===t.reference_asset);if(o){let l=e.assetFiles.get(o.file);if(l){let c=await Mt(l);c&&i.push({base64:c.base64,mimeType:c.mimeType})}}}if(e.flatDesignDataUrl){let o=eg(e.flatDesignDataUrl);o&&i.push(o)}let n=Jh(t.game_object),r={prompt:t.generation_prompt,hasReference:i.length>0,brandDna:e.manifest.brand_dna,needsTransparency:n},a=Xh(r);console.log(`[Pipeline] Generating asset for ${t.game_object}... (transparency: ${n})`);let s=await Gi(e.apiKey,a,i,{aspectRatio:"1:1",model:"gemini-2.5-flash-image"});return n&&await qi(s)||s}function eg(e){let[t,i]=e.split(","),n=t==null?void 0:t.match(/data:(.*?);base64/);return i&&n?{base64:i,mimeType:n[1]}:null}async function tg(e,t){let i=e.assets,n=[];Array.isArray(i)?n=i:i&&typeof i=="object"?n=Object.entries(i).map(([r,a])=>({id:r,file:String(a),role:"visual element"})):n=[],e.assets=n;for(let r of n){let a=t.get(r.file);if(a){let s=await Mt(a);s&&(r.dataUrl=s.dataUrl)}}}var Va=class{constructor(){this.root=null;this.currentTab="upload";this.uploadMethod="individual";this.uploadedJsons=new Map;this.normalizedManifest=null;this.flatDesignDataUrl=null;this.assetFiles=new Map;this.zipFile=null;this.mappingResult=null;this.analysisRawResponse=null;this.analysisParsedOk=null;this.analysisParseError=null;this.isAnalyzing=!1;this.isGenerating=!1}get manifest(){return this.normalizedManifest}render(){return`
510
+ Generate the requested asset matching the brand style.${i.needsTransparency?" Background MUST be solid magenta (#FF00FF).":""}
511
+ `.trim()}function js(i){return i.map(e=>{if(typeof e=="string"){let t=e,n,a;return t.includes("background")?(n="background",a="background"):t.includes("button")||t.includes("cta")?(n="ui",a="button"):t.includes("logo")?(n="ui",a="logo"):t.includes("title")||t.includes("subtitle")||t.includes("text")?(n="text",a="text"):t.includes("effect")||t.includes("confetti")||t.includes("particle")?(n="effects",a="effect"):t.includes("ui.")||t.includes("splash")||t.includes("endgame")?(n="ui",a="image"):(n="environment",a="interactive"),{id:t,category:n,type:a}}return e})}function Ds(i,e){return!(i.includes("background")&&(i.includes("_1")||i.includes("splash")||i.includes("endgame")||i.includes("main"))||e==="text"||e==="effects"&&i.includes("particle"))}async function $s(i){var r,o;let e=js(i.gameObjects),t={gamePrompt:i.gamePrompt,gameObjects:e,brandAssets:i.manifest.assets,brandDna:i.manifest.brand_dna,brandName:i.manifest.brand_name},n=Is(t),a=[];if(i.flatDesignDataUrl)try{let l=zs(i.flatDesignDataUrl);l&&l.base64&&l.mimeType?l.base64.length<100?console.warn("[Pipeline] Flat design data URL appears invalid (too short)"):(a.push(l),console.log("[Pipeline] Added flat design to analysis, size:",l.base64.length)):console.warn("[Pipeline] Failed to parse flat design data URL")}catch(l){console.warn("[Pipeline] Error processing flat design:",l)}console.log("[Pipeline] Running analysis chain with",a.length,"images...");let s;try{s=await _n(i.apiKey,n,a,{model:"gemini-2.5-flash"}),console.log("[Pipeline] Analysis response received")}catch(l){throw console.error("[Pipeline] Gemini API error:",l),(r=l.message)!=null&&r.includes("Unable to process input image")?new Error("Gemini API unable to process the uploaded images. Please try with different images or ensure they are valid PNG/JPG files under 10MB."):(o=l.message)!=null&&o.includes("image")?new Error("Image processing failed. Please ensure your images are valid and not corrupted."):l}return Ho(s,i.gameObjects)}function Ho(i,e){try{let t=i,n=i.match(/```(?:json)?\s*([\s\S]*?)```/);if(n)t=n[1].trim();else{let s=i.match(/\{[\s\S]*\}/);s&&(t=s[0])}let a=JSON.parse(t);return a.mappings&&Array.isArray(a.mappings)?{mappingResult:a,rawResponse:i,parsed:!0}:{mappingResult:{mappings:e.map(s=>({game_object:s,action:"KEEP",status:"Analysis response missing mappings[]"}))},rawResponse:i,parsed:!1,parseError:"Missing mappings[] array"}}catch(t){return{mappingResult:{mappings:e.map(n=>({game_object:n,action:"KEEP",status:"Analysis response was not valid JSON"}))},rawResponse:i,parsed:!1,parseError:t!=null&&t.message?String(t.message):"JSON parse failed"}}}async function $i(i,e,t={}){var a;let n=e.mappings.filter(s=>s.action==="GENERATE");if(n.length===0){console.log("[Pipeline] No assets to generate");return}console.log(`[Pipeline] Generating ${n.length} assets...`);for(let s=0;s<n.length;s++){let r=n[s];(a=t.onProgress)==null||a.call(t,s+1,n.length,r.game_object);try{let o=await Bo(i,r);r.output_dataUrl=o,r.status="Generated \u2713"}catch(o){console.error(`[Pipeline] Failed to generate ${r.game_object}:`,o),r.status="Failed \u2717"}}console.log("[Pipeline] Generation chain complete")}async function Bo(i,e){if(!e.generation_prompt)throw new Error("No generation prompt provided");let t=[];if(e.reference_asset&&i.manifest){let o=i.manifest.assets.find(l=>l.id===e.reference_asset);if(o){let l=i.assetFiles.get(o.file);if(l){let c=await Te(l);c&&t.push({base64:c.base64,mimeType:c.mimeType})}}}if(i.flatDesignDataUrl){let o=zs(i.flatDesignDataUrl);o&&t.push(o)}let n=Ds(e.game_object),a={prompt:e.generation_prompt,hasReference:t.length>0,brandDna:i.manifest.brand_dna,needsTransparency:n},s=Rs(a);console.log(`[Pipeline] Generating asset for ${e.game_object}... (transparency: ${n})`);let r=await et(i.apiKey,s,t,{aspectRatio:"1:1",model:"gemini-2.5-flash-image"});return n&&await Qe(r)||r}function zs(i){let[e,t]=i.split(","),n=e==null?void 0:e.match(/data:(.*?);base64/);return t&&n?{base64:t,mimeType:n[1]}:null}async function Ns(i,e){let t=i.assets,n=[];Array.isArray(t)?n=t:t&&typeof t=="object"?n=Object.entries(t).map(([a,s])=>({id:a,file:String(s),role:"visual element"})):n=[],i.assets=n;for(let a of n){let s=e.get(a.file);if(s){let r=await Te(s);r&&(a.dataUrl=r.dataUrl)}}}var Pn=class{constructor(){this.root=null;this.currentTab="upload";this.uploadMethod="individual";this.uploadedJsons=new Map;this.normalizedManifest=null;this.flatDesignDataUrl=null;this.assetFiles=new Map;this.zipFile=null;this.mappingResult=null;this.analysisRawResponse=null;this.analysisParsedOk=null;this.analysisParseError=null;this.isAnalyzing=!1;this.isGenerating=!1}get manifest(){return this.normalizedManifest}render(){return`
610
512
  <div class="scene-panel brand-vision-panel panel-accent-violet" data-panel="brand-vision">
611
513
  <div class="scene-panel-header" data-panel-handle>
612
514
  <div class="panel-title">
@@ -722,15 +624,15 @@ Generate the requested asset matching the brand style.${e.needsTransparency?" Ba
722
624
  </div>
723
625
  <div class="panel-resize-handle" data-panel-resize></div>
724
626
  </div>
725
- `}initialize(t,i){this.root=t.querySelector('[data-panel="brand-vision"]'),this.onClose=i,this.root&&(this.attachEventListeners(),this.setupResizeHandle())}attachEventListeners(){var i,n,r,a,s,o,l,c,d,u,p,f,g;if(!this.root)return;(i=this.root.querySelector("[data-panel-close]"))==null||i.addEventListener("click",()=>{if(this.onClose)this.onClose();else{let h="/dashboard";window.location.pathname!==h&&(window.location.href=h)}}),this.root.querySelectorAll("[data-vision-tab]").forEach(h=>{h.addEventListener("click",()=>{let m=h.dataset.visionTab;this.switchTab(m)})}),(n=this.root.querySelector("[data-vision-upload-method]"))==null||n.addEventListener("change",h=>{let m=h.target.value;this.switchUploadMethod(m)}),(r=this.root.querySelector("[data-vision-upload-manifest]"))==null||r.addEventListener("click",()=>{var h,m;(m=(h=this.root)==null?void 0:h.querySelector("[data-vision-manifest-input]"))==null||m.click()}),(a=this.root.querySelector("[data-vision-upload-zip]"))==null||a.addEventListener("click",()=>{var h,m;(m=(h=this.root)==null?void 0:h.querySelector("[data-vision-zip-input]"))==null||m.click()}),(s=this.root.querySelector("[data-vision-zip-input]"))==null||s.addEventListener("change",h=>{this.handleZipUpload(h)}),(o=this.root.querySelector("[data-vision-manifest-input]"))==null||o.addEventListener("change",h=>{this.handleManifestUpload(h)}),(l=this.root.querySelector("[data-vision-upload-assets]"))==null||l.addEventListener("click",()=>{var h,m;(m=(h=this.root)==null?void 0:h.querySelector("[data-vision-assets-input]"))==null||m.click()}),(c=this.root.querySelector("[data-vision-assets-input]"))==null||c.addEventListener("change",h=>{this.handleAssetsUpload(h)}),(d=this.root.querySelector("[data-vision-upload-flat]"))==null||d.addEventListener("click",()=>{var h,m;(m=(h=this.root)==null?void 0:h.querySelector("[data-vision-flat-input]"))==null||m.click()}),(u=this.root.querySelector("[data-vision-flat-input]"))==null||u.addEventListener("change",h=>{this.handleFlatDesignUpload(h)}),(p=this.root.querySelector("[data-vision-analyze]"))==null||p.addEventListener("click",()=>{this.runAnalysis()}),(f=this.root.querySelector("[data-vision-generate-all]"))==null||f.addEventListener("click",()=>{this.generateAllMissing()}),(g=this.root.querySelector("[data-vision-apply-all]"))==null||g.addEventListener("click",()=>{this.applyAll()});let t=this.root.querySelector("[data-vision-mappings]");t==null||t.addEventListener("click",h=>{let m=h.target;if(!m)return;let b=m.closest("[data-mapping-item]"),y=b==null?void 0:b.dataset.mappingItem;y&&(m.closest("[data-mapping-apply-one]")&&this.applyOne(y),m.closest("[data-mapping-save-one]")&&this.saveAndApplyOne(y),m.closest("[data-mapping-edit-one]")&&this.openEditorForOne(y),m.closest("[data-mapping-generate-one]")&&this.generateOne(y),m.closest("[data-mapping-copy-raw]")&&this.copyRawAnalysis())}),t==null||t.addEventListener("change",h=>{let m=h.target;if(!m||!this.mappingResult)return;let b=m.closest("[data-mapping-item]"),y=b==null?void 0:b.dataset.mappingItem;if(!y)return;let v=this.mappingResult.mappings.find(x=>x.game_object===y);v&&(m.matches("[data-mapping-action]")&&(v.action=String(m.value||"KEEP"),v.status="Edited",this.renderMappings()),m.matches("[data-mapping-brand-asset]")&&(v.brand_asset=String(m.value||""),v.status="Edited",this.renderMappings()))}),t==null||t.addEventListener("input",h=>{let m=h.target;if(!m||!this.mappingResult||!m.matches("[data-mapping-prompt]"))return;let b=m.closest("[data-mapping-item]"),y=b==null?void 0:b.dataset.mappingItem;if(!y)return;let v=this.mappingResult.mappings.find(x=>x.game_object===y);v&&(v.generation_prompt=String(m.value||""),v.status="Edited")})}switchTab(t){var i,n;this.root&&(this.currentTab=t,this.root.querySelectorAll("[data-vision-tab]").forEach(r=>r.classList.remove("active")),this.root.querySelectorAll("[data-vision-content]").forEach(r=>r.classList.remove("active")),(i=this.root.querySelector(`[data-vision-tab="${t}"]`))==null||i.classList.add("active"),(n=this.root.querySelector(`[data-vision-content="${t}"]`))==null||n.classList.add("active"))}switchUploadMethod(t){var i;this.root&&(this.uploadMethod=t,this.root.querySelectorAll("[data-vision-upload-section]").forEach(n=>{n.classList.remove("active")}),(i=this.root.querySelector(`[data-vision-upload-section="${t}"]`))==null||i.classList.add("active"))}async handleZipUpload(t){var r;let n=(r=t.target.files)==null?void 0:r[0];if(n){this.zipFile=n,this.setStatus("zip",`Selected: ${n.name} (${(n.size/1024/1024).toFixed(2)} MB)`);try{await this.processZipFile(n)}catch(a){console.error("[BrandVision] ZIP processing failed:",a),this.setStatus("zip",`Error: ${a instanceof Error?a.message:"Unknown error"}`)}}}async processZipFile(t){var s,o;let i=await ig.default.loadAsync(t),n=[],r=[];i.forEach((l,c)=>{let d=l.toLowerCase();d.endsWith(".json")?n.push({name:l,content:null}):d.startsWith("assets/")&&d.endsWith(".png")&&r.push({name:l,file:c})});for(let l of n)try{let c=await((s=i.file(l.name))==null?void 0:s.async("text"));c&&(l.content=JSON.parse(c))}catch(c){console.warn(`Failed to parse ${l.name}:`,c)}let a=new Map;for(let l of r)try{let c=await l.file.async("uint8array"),d=new Blob([c],{type:"image/png"}),u=l.name.split("/").pop()||l.name;console.log(`Processing ${u}, uint8array length: ${c.length}, blob size: ${d.size}`);let p;try{p=await this.blobToDataUrl(d)}catch(m){console.warn(`FileReader failed for ${u}, using fallback:`,m),p=`data:image/png;base64,${btoa(String.fromCharCode.apply(null,Array.from(c)))}`}if(console.log(`Data URL length: ${p.length}, starts with: ${p.substring(0,50)}...`),!p.startsWith("data:image/png;base64,")){console.warn(`Invalid data URL format for ${u}:`,p.substring(0,100));continue}let f=this.inferAssetCategory(u.replace(".png",""));console.log(`Saving ${u} to category: ${f}`);let h=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:f,filename:u,data:p,overwrite:!0})})).json();if(console.log(`Save result for ${u}:`,h),h.success){console.log(`\u2705 Saved PNG to library: ${u} (${f}) at ${h.path}`);let m=new File([d],u,{type:"image/png"});a.set(u,m)}else console.warn(`\u274C Failed to save ${u}:`,h.error)}catch(c){console.warn(`Failed to extract ${l.name}:`,c)}this.uploadedJsons.clear(),n.forEach(({name:l,content:c})=>{c&&this.uploadedJsons.set(l,c)}),this.assetFiles=a;try{this.normalizedManifest=$l(Array.from(this.uploadedJsons.values()),{defaultBrandName:"Imported Brand"});let l=[];for(let[d,u]of a){let p=await this.fileToDataUrl(u);l.push({id:d.replace(".png",""),filename:d,dataUrl:p,category:this.inferAssetCategory(d.replace(".png",""))})}this.normalizedManifest&&(this.normalizedManifest.assets=l);let c=l.length;this.setStatus("zip",`\u2705 Processed: ${n.length} JSONs, ${c} PNGs
726
- \u{1F3F7}\uFE0F Brand: ${((o=this.normalizedManifest)==null?void 0:o.brand_name)||"Imported Brand"}`),this.addAssetsToRegistry(l),this.refreshLibrary()}catch(l){console.error("[BrandVision] Failed to normalize ZIP manifest:",l),this.normalizedManifest=null,this.setStatus("zip","\u274C Failed to normalize manifest")}}async fileToDataUrl(t){return new Promise((i,n)=>{let r=new FileReader;r.onload=()=>i(r.result),r.onerror=n,r.readAsDataURL(t)})}async blobToDataUrl(t){return new Promise((i,n)=>{let r=new FileReader;r.onload=()=>{let a=r.result;console.log("FileReader result type:",typeof a,"length:",a.length),console.log("Data URL prefix:",a.substring(0,30)),i(a)},r.onerror=a=>{console.error("FileReader error:",a),n(a)},r.readAsDataURL(t)})}inferAssetCategory(t){let i=t.toLowerCase();return i.includes("background")||i.includes("bg")?"backgrounds":i.includes("ui")||i.includes("button")||i.includes("cta")||i.includes("logo")||i.includes("text")?"ui":i.includes("sparkle")||i.includes("effect")||i.includes("particle")?"effects":i.includes("bottle")||i.includes("product")||i.includes("item")?"products":"misc"}addAssetsToRegistry(t){let i=window.getEditableAssets;if(typeof i!="function")return;let n=i();if(!(n!=null&&n.libraryAssets))return;let r={};for(let a of t){let s=a.category||"misc";r[s]||(r[s]=[]),n.libraryAssets[s]||(n.libraryAssets[s]=[]),n.libraryAssets[s].some(l=>l.filename===a.filename)||(n.libraryAssets[s].unshift({filename:a.filename,displayName:a.id.replace(/_/g," ").replace(/\b\w/g,l=>l.toUpperCase())}),console.log(`[BrandVision] Added ${a.filename} to registry category ${s}`))}}refreshLibrary(){let t=window.refreshAssetLibrary;typeof t=="function"&&t();let i=window.reRenderAssetLibrary;typeof i=="function"&&i()}async handleManifestUpload(t){var a;let i=t.target,n=i.files;if(!n||n.length===0)return;this.uploadedJsons.clear(),this.normalizedManifest=null,this.mappingResult=null;let r="";for(let s of Array.from(n))try{let o=await s.text(),l=JSON.parse(o);this.uploadedJsons.set(s.name,l),l.layers?r+=`\u2705 Layers: ${s.name}
727
- `:l.brand_dna||l.colors?r+=`\u2705 Brand: ${s.name}
728
- `:r+=`\u2705 Loaded: ${s.name}
729
- `}catch{r+=`\u274C Error in ${s.name}
730
- `}try{this.normalizedManifest=$l(Array.from(this.uploadedJsons.values()),{defaultBrandName:"Imported Brand"});let s=Array.isArray((a=this.normalizedManifest)==null?void 0:a.assets)?this.normalizedManifest.assets.length:0;r+=`
731
- \u{1F4E6} Normalized manifest: ${s} assets`,r+=`
732
- \u{1F3F7}\uFE0F Brand: ${this.normalizedManifest.brand_name||"Imported Brand"}`,console.info("[BrandVision] Normalized manifest",{jsonFiles:Array.from(this.uploadedJsons.keys()),assetsType:typeof this.normalizedManifest.assets,assetsCount:s,brandName:this.normalizedManifest.brand_name})}catch(s){console.error("[BrandVision] Failed to normalize manifest:",s),this.normalizedManifest=null,r+=`
733
- \u274C Failed to normalize manifest`}i.value="",this.setStatus("manifest",r.trim())}async handleAssetsUpload(t){let n=t.target.files;if(!(!n||n.length===0)){for(let r of Array.from(n))this.assetFiles.set(r.name,r);this.setStatus("assets",`${this.assetFiles.size} files loaded`)}}async handleFlatDesignUpload(t){var a,s;let n=(a=t.target.files)==null?void 0:a[0];if(!n)return;let r=await Mt(n);if(r){this.flatDesignDataUrl=r.dataUrl,this.setStatus("flat",n.name);let o=(s=this.root)==null?void 0:s.querySelector("[data-vision-flat-preview]");o&&(o.innerHTML=`<img src="${r.dataUrl}" style="max-width:100%;max-height:100px;border-radius:4px;">`)}}async runAnalysis(){var n,r,a,s,o,l,c;if(this.isAnalyzing)return;let t=(a=(r=(n=this.root)==null?void 0:n.querySelector("[data-vision-api-key]"))==null?void 0:r.value)==null?void 0:a.trim();if(!t){this.setStatus("upload","Missing API key");return}let i=this.manifest;if(!i){this.setStatus("upload","Upload manifest first");return}Array.isArray(i.assets)||console.warn("[BrandVision] Manifest assets not array at analysis time; continuing with normalization fallback.",{assets:i.assets}),this.isAnalyzing=!0,this.setStatus("upload","Analyzing...");try{await tg(i,this.assetFiles);let d={apiKey:t,manifest:i,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()},u=await Qh(d);this.mappingResult=u.mappingResult,this.analysisRawResponse=u.rawResponse,this.analysisParsedOk=u.parsed,this.analysisParseError=(s=u.parseError)!=null?s:null,this.renderMappings(),u.parsed?(this.setStatus("upload","Analysis complete"),this.setStatus("mapping",`${(c=(l=(o=this.mappingResult)==null?void 0:o.mappings)==null?void 0:l.length)!=null?c:0} objects mapped`)):(this.setStatus("upload","Analysis response was not JSON"),this.setStatus("mapping",`Parse failed: ${u.parseError||"Unknown error"}`)),this.switchTab("mapping")}catch(d){console.error("[BrandVision] Analysis failed:",d),this.setStatus("upload","Analysis failed")}finally{this.isAnalyzing=!1}}async generateAllMissing(){var i,n,r;if(this.isGenerating||!this.mappingResult||!this.manifest)return;let t=(r=(n=(i=this.root)==null?void 0:i.querySelector("[data-vision-api-key]"))==null?void 0:n.value)==null?void 0:r.trim();if(!t){this.setStatus("apply","Missing API key");return}this.isGenerating=!0;try{let a={apiKey:t,manifest:this.manifest,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()};await Hl(a,this.mappingResult,{onProgress:(s,o,l)=>{this.setStatus("apply",`Generating ${s}/${o}: ${l}`),this.renderMappings()}}),this.setStatus("apply","Generation complete"),this.renderMappings()}catch(a){console.error("[BrandVision] Generation failed:",a),this.setStatus("apply","Generation failed")}finally{this.isGenerating=!1}}renderMappings(){var o;let t=(o=this.root)==null?void 0:o.querySelector("[data-vision-mappings]");if(!t||!this.mappingResult)return;let i=this.manifest,n=this.getEngineAssets(),r=!!this.analysisRawResponse&&this.analysisParsedOk===!1,a=((i==null?void 0:i.assets)||[]).map(l=>`<option value="${l.id}">${l.id}</option>`).join(""),s=r?`
627
+ `}initialize(e,t){this.root=e.querySelector('[data-panel="brand-vision"]'),this.onClose=t,this.root&&(this.attachEventListeners(),this.setupResizeHandle())}attachEventListeners(){var t,n,a,s,r,o,l,c,p,d,u,g,h;if(!this.root)return;(t=this.root.querySelector("[data-panel-close]"))==null||t.addEventListener("click",()=>{if(this.onClose)this.onClose();else{let f="/dashboard";window.location.pathname!==f&&(window.location.href=f)}}),this.root.querySelectorAll("[data-vision-tab]").forEach(f=>{f.addEventListener("click",()=>{let m=f.dataset.visionTab;this.switchTab(m)})}),(n=this.root.querySelector("[data-vision-upload-method]"))==null||n.addEventListener("change",f=>{let m=f.target.value;this.switchUploadMethod(m)}),(a=this.root.querySelector("[data-vision-upload-manifest]"))==null||a.addEventListener("click",()=>{var f,m;(m=(f=this.root)==null?void 0:f.querySelector("[data-vision-manifest-input]"))==null||m.click()}),(s=this.root.querySelector("[data-vision-upload-zip]"))==null||s.addEventListener("click",()=>{var f,m;(m=(f=this.root)==null?void 0:f.querySelector("[data-vision-zip-input]"))==null||m.click()}),(r=this.root.querySelector("[data-vision-zip-input]"))==null||r.addEventListener("change",f=>{this.handleZipUpload(f)}),(o=this.root.querySelector("[data-vision-manifest-input]"))==null||o.addEventListener("change",f=>{this.handleManifestUpload(f)}),(l=this.root.querySelector("[data-vision-upload-assets]"))==null||l.addEventListener("click",()=>{var f,m;(m=(f=this.root)==null?void 0:f.querySelector("[data-vision-assets-input]"))==null||m.click()}),(c=this.root.querySelector("[data-vision-assets-input]"))==null||c.addEventListener("change",f=>{this.handleAssetsUpload(f)}),(p=this.root.querySelector("[data-vision-upload-flat]"))==null||p.addEventListener("click",()=>{var f,m;(m=(f=this.root)==null?void 0:f.querySelector("[data-vision-flat-input]"))==null||m.click()}),(d=this.root.querySelector("[data-vision-flat-input]"))==null||d.addEventListener("change",f=>{this.handleFlatDesignUpload(f)}),(u=this.root.querySelector("[data-vision-analyze]"))==null||u.addEventListener("click",()=>{this.runAnalysis()}),(g=this.root.querySelector("[data-vision-generate-all]"))==null||g.addEventListener("click",()=>{this.generateAllMissing()}),(h=this.root.querySelector("[data-vision-apply-all]"))==null||h.addEventListener("click",()=>{this.applyAll()});let e=this.root.querySelector("[data-vision-mappings]");e==null||e.addEventListener("click",f=>{let m=f.target;if(!m)return;let b=m.closest("[data-mapping-item]"),y=b==null?void 0:b.dataset.mappingItem;y&&(m.closest("[data-mapping-apply-one]")&&this.applyOne(y),m.closest("[data-mapping-save-one]")&&this.saveAndApplyOne(y),m.closest("[data-mapping-edit-one]")&&this.openEditorForOne(y),m.closest("[data-mapping-generate-one]")&&this.generateOne(y),m.closest("[data-mapping-copy-raw]")&&this.copyRawAnalysis())}),e==null||e.addEventListener("change",f=>{let m=f.target;if(!m||!this.mappingResult)return;let b=m.closest("[data-mapping-item]"),y=b==null?void 0:b.dataset.mappingItem;if(!y)return;let v=this.mappingResult.mappings.find(x=>x.game_object===y);v&&(m.matches("[data-mapping-action]")&&(v.action=String(m.value||"KEEP"),v.status="Edited",this.renderMappings()),m.matches("[data-mapping-brand-asset]")&&(v.brand_asset=String(m.value||""),v.status="Edited",this.renderMappings()))}),e==null||e.addEventListener("input",f=>{let m=f.target;if(!m||!this.mappingResult||!m.matches("[data-mapping-prompt]"))return;let b=m.closest("[data-mapping-item]"),y=b==null?void 0:b.dataset.mappingItem;if(!y)return;let v=this.mappingResult.mappings.find(x=>x.game_object===y);v&&(v.generation_prompt=String(m.value||""),v.status="Edited")})}switchTab(e){var t,n;this.root&&(this.currentTab=e,this.root.querySelectorAll("[data-vision-tab]").forEach(a=>a.classList.remove("active")),this.root.querySelectorAll("[data-vision-content]").forEach(a=>a.classList.remove("active")),(t=this.root.querySelector(`[data-vision-tab="${e}"]`))==null||t.classList.add("active"),(n=this.root.querySelector(`[data-vision-content="${e}"]`))==null||n.classList.add("active"))}switchUploadMethod(e){var t;this.root&&(this.uploadMethod=e,this.root.querySelectorAll("[data-vision-upload-section]").forEach(n=>{n.classList.remove("active")}),(t=this.root.querySelector(`[data-vision-upload-section="${e}"]`))==null||t.classList.add("active"))}async handleZipUpload(e){var a;let n=(a=e.target.files)==null?void 0:a[0];if(n){this.zipFile=n,this.setStatus("zip",`Selected: ${n.name} (${(n.size/1024/1024).toFixed(2)} MB)`);try{await this.processZipFile(n)}catch(s){console.error("[BrandVision] ZIP processing failed:",s),this.setStatus("zip",`Error: ${s instanceof Error?s.message:"Unknown error"}`)}}}async processZipFile(e){var r,o;let t=await Hs.default.loadAsync(e),n=[],a=[];t.forEach((l,c)=>{let p=l.toLowerCase();p.endsWith(".json")?n.push({name:l,content:null}):p.startsWith("assets/")&&p.endsWith(".png")&&a.push({name:l,file:c})});for(let l of n)try{let c=await((r=t.file(l.name))==null?void 0:r.async("text"));c&&(l.content=JSON.parse(c))}catch(c){console.warn(`Failed to parse ${l.name}:`,c)}let s=new Map;for(let l of a)try{let c=await l.file.async("uint8array"),p=new Blob([c],{type:"image/png"}),d=l.name.split("/").pop()||l.name;console.log(`Processing ${d}, uint8array length: ${c.length}, blob size: ${p.size}`);let u;try{u=await this.blobToDataUrl(p)}catch(m){console.warn(`FileReader failed for ${d}, using fallback:`,m),u=`data:image/png;base64,${btoa(String.fromCharCode.apply(null,Array.from(c)))}`}if(console.log(`Data URL length: ${u.length}, starts with: ${u.substring(0,50)}...`),!u.startsWith("data:image/png;base64,")){console.warn(`Invalid data URL format for ${d}:`,u.substring(0,100));continue}let g=this.inferAssetCategory(d.replace(".png",""));console.log(`Saving ${d} to category: ${g}`);let f=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:g,filename:d,data:u,overwrite:!0})})).json();if(console.log(`Save result for ${d}:`,f),f.success){console.log(`\u2705 Saved PNG to library: ${d} (${g}) at ${f.path}`);let m=new File([p],d,{type:"image/png"});s.set(d,m)}else console.warn(`\u274C Failed to save ${d}:`,f.error)}catch(c){console.warn(`Failed to extract ${l.name}:`,c)}this.uploadedJsons.clear(),n.forEach(({name:l,content:c})=>{c&&this.uploadedJsons.set(l,c)}),this.assetFiles=s;try{this.normalizedManifest=Di(Array.from(this.uploadedJsons.values()),{defaultBrandName:"Imported Brand"});let l=[];for(let[p,d]of s){let u=await this.fileToDataUrl(d);l.push({id:p.replace(".png",""),filename:p,dataUrl:u,category:this.inferAssetCategory(p.replace(".png",""))})}this.normalizedManifest&&(this.normalizedManifest.assets=l);let c=l.length;this.setStatus("zip",`\u2705 Processed: ${n.length} JSONs, ${c} PNGs
628
+ \u{1F3F7}\uFE0F Brand: ${((o=this.normalizedManifest)==null?void 0:o.brand_name)||"Imported Brand"}`),this.addAssetsToRegistry(l),this.refreshLibrary()}catch(l){console.error("[BrandVision] Failed to normalize ZIP manifest:",l),this.normalizedManifest=null,this.setStatus("zip","\u274C Failed to normalize manifest")}}async fileToDataUrl(e){return new Promise((t,n)=>{let a=new FileReader;a.onload=()=>t(a.result),a.onerror=n,a.readAsDataURL(e)})}async blobToDataUrl(e){return new Promise((t,n)=>{let a=new FileReader;a.onload=()=>{let s=a.result;console.log("FileReader result type:",typeof s,"length:",s.length),console.log("Data URL prefix:",s.substring(0,30)),t(s)},a.onerror=s=>{console.error("FileReader error:",s),n(s)},a.readAsDataURL(e)})}inferAssetCategory(e){let t=e.toLowerCase();return t.includes("background")||t.includes("bg")?"backgrounds":t.includes("ui")||t.includes("button")||t.includes("cta")||t.includes("logo")||t.includes("text")?"ui":t.includes("sparkle")||t.includes("effect")||t.includes("particle")?"effects":t.includes("bottle")||t.includes("product")||t.includes("item")?"products":"misc"}addAssetsToRegistry(e){let t=window.getEditableAssets;if(typeof t!="function")return;let n=t();if(!(n!=null&&n.libraryAssets))return;let a={};for(let s of e){let r=s.category||"misc";a[r]||(a[r]=[]),n.libraryAssets[r]||(n.libraryAssets[r]=[]),n.libraryAssets[r].some(l=>l.filename===s.filename)||(n.libraryAssets[r].unshift({filename:s.filename,displayName:s.id.replace(/_/g," ").replace(/\b\w/g,l=>l.toUpperCase())}),console.log(`[BrandVision] Added ${s.filename} to registry category ${r}`))}}refreshLibrary(){let e=window.refreshAssetLibrary;typeof e=="function"&&e();let t=window.reRenderAssetLibrary;typeof t=="function"&&t()}async handleManifestUpload(e){var s;let t=e.target,n=t.files;if(!n||n.length===0)return;this.uploadedJsons.clear(),this.normalizedManifest=null,this.mappingResult=null;let a="";for(let r of Array.from(n))try{let o=await r.text(),l=JSON.parse(o);this.uploadedJsons.set(r.name,l),l.layers?a+=`\u2705 Layers: ${r.name}
629
+ `:l.brand_dna||l.colors?a+=`\u2705 Brand: ${r.name}
630
+ `:a+=`\u2705 Loaded: ${r.name}
631
+ `}catch{a+=`\u274C Error in ${r.name}
632
+ `}try{this.normalizedManifest=Di(Array.from(this.uploadedJsons.values()),{defaultBrandName:"Imported Brand"});let r=Array.isArray((s=this.normalizedManifest)==null?void 0:s.assets)?this.normalizedManifest.assets.length:0;a+=`
633
+ \u{1F4E6} Normalized manifest: ${r} assets`,a+=`
634
+ \u{1F3F7}\uFE0F Brand: ${this.normalizedManifest.brand_name||"Imported Brand"}`,console.info("[BrandVision] Normalized manifest",{jsonFiles:Array.from(this.uploadedJsons.keys()),assetsType:typeof this.normalizedManifest.assets,assetsCount:r,brandName:this.normalizedManifest.brand_name})}catch(r){console.error("[BrandVision] Failed to normalize manifest:",r),this.normalizedManifest=null,a+=`
635
+ \u274C Failed to normalize manifest`}t.value="",this.setStatus("manifest",a.trim())}async handleAssetsUpload(e){let n=e.target.files;if(!(!n||n.length===0)){for(let a of Array.from(n))this.assetFiles.set(a.name,a);this.setStatus("assets",`${this.assetFiles.size} files loaded`)}}async handleFlatDesignUpload(e){var s,r;let n=(s=e.target.files)==null?void 0:s[0];if(!n)return;let a=await Te(n);if(a){this.flatDesignDataUrl=a.dataUrl,this.setStatus("flat",n.name);let o=(r=this.root)==null?void 0:r.querySelector("[data-vision-flat-preview]");o&&(o.innerHTML=`<img src="${a.dataUrl}" style="max-width:100%;max-height:100px;border-radius:4px;">`)}}async runAnalysis(){var n,a,s,r,o,l,c;if(this.isAnalyzing)return;let e=(s=(a=(n=this.root)==null?void 0:n.querySelector("[data-vision-api-key]"))==null?void 0:a.value)==null?void 0:s.trim();if(!e){this.setStatus("upload","Missing API key");return}let t=this.manifest;if(!t){this.setStatus("upload","Upload manifest first");return}Array.isArray(t.assets)||console.warn("[BrandVision] Manifest assets not array at analysis time; continuing with normalization fallback.",{assets:t.assets}),this.isAnalyzing=!0,this.setStatus("upload","Analyzing...");try{await Ns(t,this.assetFiles);let p={apiKey:e,manifest:t,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()},d=await $s(p);this.mappingResult=d.mappingResult,this.analysisRawResponse=d.rawResponse,this.analysisParsedOk=d.parsed,this.analysisParseError=(r=d.parseError)!=null?r:null,this.renderMappings(),d.parsed?(this.setStatus("upload","Analysis complete"),this.setStatus("mapping",`${(c=(l=(o=this.mappingResult)==null?void 0:o.mappings)==null?void 0:l.length)!=null?c:0} objects mapped`)):(this.setStatus("upload","Analysis response was not JSON"),this.setStatus("mapping",`Parse failed: ${d.parseError||"Unknown error"}`)),this.switchTab("mapping")}catch(p){console.error("[BrandVision] Analysis failed:",p),this.setStatus("upload","Analysis failed")}finally{this.isAnalyzing=!1}}async generateAllMissing(){var t,n,a;if(this.isGenerating||!this.mappingResult||!this.manifest)return;let e=(a=(n=(t=this.root)==null?void 0:t.querySelector("[data-vision-api-key]"))==null?void 0:n.value)==null?void 0:a.trim();if(!e){this.setStatus("apply","Missing API key");return}this.isGenerating=!0;try{let s={apiKey:e,manifest:this.manifest,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()};await $i(s,this.mappingResult,{onProgress:(r,o,l)=>{this.setStatus("apply",`Generating ${r}/${o}: ${l}`),this.renderMappings()}}),this.setStatus("apply","Generation complete"),this.renderMappings()}catch(s){console.error("[BrandVision] Generation failed:",s),this.setStatus("apply","Generation failed")}finally{this.isGenerating=!1}}renderMappings(){var o;let e=(o=this.root)==null?void 0:o.querySelector("[data-vision-mappings]");if(!e||!this.mappingResult)return;let t=this.manifest,n=this.getEngineAssets(),a=!!this.analysisRawResponse&&this.analysisParsedOk===!1,s=((t==null?void 0:t.assets)||[]).map(l=>`<option value="${l.id}">${l.id}</option>`).join(""),r=a?`
734
636
  <div class="vision-raw-block">
735
637
  <div class="inspector-text-sm" style="white-space: pre-wrap;">
736
638
  \u26A0\uFE0F AI response was not valid JSON (${this.analysisParseError||"unknown error"}).
@@ -738,12 +640,12 @@ Generate the requested asset matching the brand style.${e.needsTransparency?" Ba
738
640
  </div>
739
641
  <textarea class="inspector-input vision-raw-textarea" readonly>${this.analysisRawResponse||""}</textarea>
740
642
  </div>
741
- `:"";t.innerHTML=`
742
- ${s}
743
- ${this.mappingResult.mappings.map(l=>{var b;let c=n[l.game_object]||"",d=l.brand_asset||"",u=(b=i==null?void 0:i.assets)==null?void 0:b.find(y=>y.id===d),p=(u==null?void 0:u.dataUrl)||"",f=l.output_dataUrl||"",g=l.action==="GENERATE"?f:l.action==="APPLY"?p:"",h=!!g,m=`
643
+ `:"";e.innerHTML=`
644
+ ${r}
645
+ ${this.mappingResult.mappings.map(l=>{var b;let c=n[l.game_object]||"",p=l.brand_asset||"",d=(b=t==null?void 0:t.assets)==null?void 0:b.find(y=>y.id===p),u=(d==null?void 0:d.dataUrl)||"",g=l.output_dataUrl||"",h=l.action==="GENERATE"?g:l.action==="APPLY"?u:"",f=!!h,m=`
744
646
  <select class="inspector-input" data-mapping-brand-asset style="flex:1; padding:6px 8px;">
745
647
  <option value="">Select brand asset\u2026</option>
746
- ${a.replace(`value="${d}"`,`value="${d}" selected`)}
648
+ ${s.replace(`value="${p}"`,`value="${p}" selected`)}
747
649
  </select>
748
650
  `;return`
749
651
  <div class="vision-mapping-item" data-mapping-item="${l.game_object}">
@@ -781,7 +683,7 @@ Generate the requested asset matching the brand style.${e.needsTransparency?" Ba
781
683
  </div>
782
684
  <div class="vision-mapping-preview">
783
685
  <div class="inspector-text-sm" style="opacity:0.8;">Preview</div>
784
- ${h?`<img src="${g}">`:'<div class="inspector-text-sm" style="opacity:0.6;">None</div>'}
686
+ ${f?`<img src="${h}">`:'<div class="inspector-text-sm" style="opacity:0.6;">None</div>'}
785
687
  </div>
786
688
  </div>
787
689
 
@@ -792,8 +694,8 @@ Generate the requested asset matching the brand style.${e.needsTransparency?" Ba
792
694
  </div>
793
695
  </div>
794
696
  `}).join("")}
795
- `}async applyAll(){let t=await this.stageOverridesFromMappings({saveToLibrary:!1});this.setStatus("apply",t>0?`Staged ${t} asset overrides`:"No assets to stage")}getEngineAssets(){let t=window.getEditableEngineConfig;if(typeof t!="function")return{};let i=t();return i!=null&&i.assets&&typeof i.assets=="object"?i.assets:{}}getPreviewValueForMapping(t){if(!this.mappingResult||!this.manifest)return{value:null,source:"none"};let i=this.mappingResult.mappings.find(n=>n.game_object===t);if(!i)return{value:null,source:"none"};if(i.action==="GENERATE"&&i.output_dataUrl)return{value:i.output_dataUrl,source:"generated"};if(i.action==="APPLY"&&i.brand_asset){let n=this.manifest.assets.find(r=>r.id===i.brand_asset);if(n!=null&&n.dataUrl)return{value:n.dataUrl,source:"brand"}}return{value:null,source:"none"}}async stageOverridesFromMappings(t){if(!this.mappingResult)return 0;let i=0;for(let n of this.mappingResult.mappings){if(n.action==="KEEP"||n.action==="APPLY"&&!n.brand_asset||n.action==="GENERATE"&&!n.output_dataUrl)continue;let r=n.game_object,a=this.getPreviewValueForMapping(r);if(!a.value)continue;let s=t.saveToLibrary?await this.saveToLibraryAndReturnPath(r,a.value):a.value;s&&(await this.stageEngineAssetOverride(r,s),n.status=t.saveToLibrary?"Saved + staged \u2713":"Staged \u2713",i++)}return this.renderMappings(),i}async applyOne(t){var r;let i=this.getPreviewValueForMapping(t);if(!i.value){this.setStatus("apply",`No output to apply for ${t}`);return}await this.stageEngineAssetOverride(t,i.value);let n=(r=this.mappingResult)==null?void 0:r.mappings.find(a=>a.game_object===t);n&&(n.status="Staged \u2713"),this.renderMappings(),this.setStatus("apply",`Staged override for ${t}`)}async saveAndApplyOne(t){var a;let i=this.getPreviewValueForMapping(t);if(!i.value){this.setStatus("apply",`No output to save for ${t}`);return}let n=await this.saveToLibraryAndReturnPath(t,i.value);if(!n){this.setStatus("apply",`Save failed for ${t}`);return}await this.stageEngineAssetOverride(t,n);let r=(a=this.mappingResult)==null?void 0:a.mappings.find(s=>s.game_object===t);r&&(r.status="Saved + staged \u2713"),this.renderMappings(),this.setStatus("apply",`Saved + staged ${t}`)}openEditorForOne(t){if(!this.mappingResult)return;let i=this.mappingResult.mappings.find(s=>s.game_object===t);if(!i)return;let n=this.getPreviewValueForMapping(t),r=window.__openAiEditor;if(typeof r!="function"){this.setStatus("apply","AI editor not available");return}let a=i.action==="GENERATE"?i.generation_prompt:void 0;r(t,a,n.value||void 0,{path:`assets.${t}`})}async generateOne(t){var r,a,s;if(!this.mappingResult||this.isGenerating)return;let i=this.mappingResult.mappings.find(o=>o.game_object===t);if(!i)return;if(i.action="GENERATE",!i.generation_prompt){i.status="Missing prompt",this.renderMappings();return}let n=(s=(a=(r=this.root)==null?void 0:r.querySelector("[data-vision-api-key]"))==null?void 0:a.value)==null?void 0:s.trim();if(!n||!this.manifest){this.setStatus("apply","Missing API key or manifest");return}this.isGenerating=!0,i.status="Generating\u2026",this.renderMappings();try{let o={apiKey:n,manifest:this.manifest,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()};await Hl(o,{mappings:[i]}),i.status=i.output_dataUrl?"Generated \u2713":i.status||"Done"}catch(o){console.error("[BrandVision] generateOne failed:",o),i.status="Failed \u2717"}finally{this.isGenerating=!1,this.renderMappings()}}async stageEngineAssetOverride(t,i){let{applyConfigOverride:n}=await Promise.resolve().then(()=>(Te(),Mr));n({path:`assets.${t}`,value:i},{silent:!0});let r=window.applyEditableEngineConfig;typeof r=="function"&&r({assets:{[t]:i}})}async saveToLibraryAndReturnPath(t,i){if(!/^(data:|blob:)/.test(i))return i;let n=this.inferCategoryFromAssetKey(t),r=`${t.replace(/[^a-zA-Z0-9_-]/g,"_")}_vision_${Date.now()}.png`;try{let s=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:n,filename:r,data:i,overwrite:!0})})).json();if(!(s!=null&&s.success)||!(s!=null&&s.path))return console.error("[BrandVision] Save to library failed:",(s==null?void 0:s.error)||s),null;let o=window.addAssetToRegistry;typeof o=="function"&&o(n,r);let l=window.refreshAssetLibrary;return typeof l=="function"&&l(),String(s.path)}catch(a){return console.error("[BrandVision] Save to library error:",a),null}}inferCategoryFromAssetKey(t){let i=window.getEditableAssets;if(typeof i=="function"){let r=i();if(r!=null&&r.slots&&Array.isArray(r.slots)){let s=r.slots.find(o=>o.slotId===t||o.currentAsset===t);if(s!=null&&s.category)return String(s.category)}let a=r==null?void 0:r.categories;if(Array.isArray(a)&&a.length>0){let s=t.toLowerCase(),o=l=>a.find(c=>c.toLowerCase().includes(l));return s.includes("bg")||s.includes("background")?o("background")||a[0]:(s.includes("cta")||s.includes("button")||s.includes("ui")||s.includes("logo"))&&o("ui")||a[0]}}let n=t.toLowerCase();return n.includes("bg")||n.includes("background")?"backgrounds":n.includes("cta")||n.includes("button")||n.includes("ui")||n.includes("logo")?"ui":"misc"}async copyRawAnalysis(){if(this.analysisRawResponse)try{await navigator.clipboard.writeText(this.analysisRawResponse),this.setStatus("mapping","Copied raw analysis to clipboard")}catch{this.setStatus("mapping","Clipboard not available")}}setStatus(t,i){var a;let n={manifest:"[data-vision-manifest-status]",assets:"[data-vision-assets-status]",flat:"[data-vision-flat-status]",zip:"[data-vision-zip-status]",upload:"[data-vision-upload-status]",mapping:"[data-vision-mapping-status]",apply:"[data-vision-apply-status]"},r=(a=this.root)==null?void 0:a.querySelector(n[t]);r&&(r.textContent=i)}getGameObjects(){let t=window.getEditableObjectList;return typeof t=="function"?t():[]}async getGamePrompt(){try{let t=await fetch("./configs/engine/game.prompt.json");if(t.ok)return(await t.json()).game_prompt||""}catch{}return""}setupResizeHandle(){if(!this.root)return;let t=this.root.querySelector("[data-panel-resize]");t&&t.addEventListener("pointerdown",i=>{let n=i.clientX,r=this.root.getBoundingClientRect().width,a=o=>{let l=Math.max(300,r+(o.clientX-n));this.root.style.width=`${l}px`},s=()=>{window.removeEventListener("pointermove",a),window.removeEventListener("pointerup",s)};window.addEventListener("pointermove",a),window.addEventListener("pointerup",s)})}refresh(){}};function ng(e,t={}){let{includeReference:i=!1,includeMagenta:n=!0,changeLevel:r=5}=t;return[`TASK: ${e}`,`CHANGE_STRENGTH: ${r}/10`,i?"REFERENCE: provided":"REFERENCE: none",n?"BACKGROUND: solid magenta #FF00FF (if possible)":""].filter(Boolean).join(`
796
- `)}var Nw=["background_color","text_color","cta_background","cta_text","warning_text_color","endgame_title_color","endgame_subtitle_color","endgame_cta_text_color","endgame_cta_hint_color","endgame_footer_color"],Bw=["cta_hint","cta_label_end"],rg=[{key:"warning_text",objectId:"label.warning",property:"ui.text"},{key:"endgame_title",objectId:"ui.endgame.title",property:"ui.text"},{key:"endgame_subtitle",objectId:"ui.endgame.subtitle",property:"ui.text"},{key:"endgame_cta_text",objectId:"ui.endgame.cta",property:"ui.text"},{key:"endgame_cta_hint_text",objectId:"ui.endgame.cta.hint",property:"ui.text"},{key:"endgame_footer_text",objectId:"ui.endgame.footer",property:"ui.text"}],Fw=["brand.primary","brand.heading","brand.body","brand.warning"],Ya=class{constructor(){this.root=null;this.assetsContainer=null;this.colorsContainer=null;this.fontsContainer=null;this.textsContainer=null;this.audioContainer=null;this.options=null;this.previewModal=null;this.autoApplyTimer=null;this.activePreviewKey=null;this.activePreviewValue=null;this.activePreviewFileInput=null;this.retryTimer=null;this.aiModal=null;this.aiTargetKey=null;this.aiKeyInput=null;this.aiPromptInput=null;this.aiStrengthInput=null;this.aiStrengthValue=null;this.aiModelSelect=null;this.aiModalSubtitle=null;this.aiGalleryToggle=null;this.aiGalleryEl=null;this.aiGalleryGrid=null;this.aiReferenceInput=null;this.aiReferenceName=null;this.aiReferenceFile=null;this.aiRemoveBgToggle=null;this.aiUseOutputToggle=null;this.aiGenerateBtn=null;this.aiApplyBtn=null;this.aiSaveLibraryBtn=null;this.aiCropBtn=null;this.aiDownloadBtn=null;this.aiPreviewImg=null;this.aiStatusEl=null;this.aiOutputDataUrl=null;this.aiBaseDataUrl=null;this.aiBaseValue=null;this.aiOutputKey=null;this.aiContext=null;this.aiBgToleranceInput=null;this.aiBgToleranceValue=null;this.aiRawOutputDataUrl=null;this.aiLoadingEl=null}render(){return`
697
+ `}async applyAll(){let e=await this.stageOverridesFromMappings({saveToLibrary:!1});this.setStatus("apply",e>0?`Staged ${e} asset overrides`:"No assets to stage")}getEngineAssets(){let e=window.getEditableEngineConfig;if(typeof e!="function")return{};let t=e();return t!=null&&t.assets&&typeof t.assets=="object"?t.assets:{}}getPreviewValueForMapping(e){if(!this.mappingResult||!this.manifest)return{value:null,source:"none"};let t=this.mappingResult.mappings.find(n=>n.game_object===e);if(!t)return{value:null,source:"none"};if(t.action==="GENERATE"&&t.output_dataUrl)return{value:t.output_dataUrl,source:"generated"};if(t.action==="APPLY"&&t.brand_asset){let n=this.manifest.assets.find(a=>a.id===t.brand_asset);if(n!=null&&n.dataUrl)return{value:n.dataUrl,source:"brand"}}return{value:null,source:"none"}}async stageOverridesFromMappings(e){if(!this.mappingResult)return 0;let t=0;for(let n of this.mappingResult.mappings){if(n.action==="KEEP"||n.action==="APPLY"&&!n.brand_asset||n.action==="GENERATE"&&!n.output_dataUrl)continue;let a=n.game_object,s=this.getPreviewValueForMapping(a);if(!s.value)continue;let r=e.saveToLibrary?await this.saveToLibraryAndReturnPath(a,s.value):s.value;r&&(await this.stageEngineAssetOverride(a,r),n.status=e.saveToLibrary?"Saved + staged \u2713":"Staged \u2713",t++)}return this.renderMappings(),t}async applyOne(e){var a;let t=this.getPreviewValueForMapping(e);if(!t.value){this.setStatus("apply",`No output to apply for ${e}`);return}await this.stageEngineAssetOverride(e,t.value);let n=(a=this.mappingResult)==null?void 0:a.mappings.find(s=>s.game_object===e);n&&(n.status="Staged \u2713"),this.renderMappings(),this.setStatus("apply",`Staged override for ${e}`)}async saveAndApplyOne(e){var s;let t=this.getPreviewValueForMapping(e);if(!t.value){this.setStatus("apply",`No output to save for ${e}`);return}let n=await this.saveToLibraryAndReturnPath(e,t.value);if(!n){this.setStatus("apply",`Save failed for ${e}`);return}await this.stageEngineAssetOverride(e,n);let a=(s=this.mappingResult)==null?void 0:s.mappings.find(r=>r.game_object===e);a&&(a.status="Saved + staged \u2713"),this.renderMappings(),this.setStatus("apply",`Saved + staged ${e}`)}openEditorForOne(e){if(!this.mappingResult)return;let t=this.mappingResult.mappings.find(r=>r.game_object===e);if(!t)return;let n=this.getPreviewValueForMapping(e),a=window.__openAiEditor;if(typeof a!="function"){this.setStatus("apply","AI editor not available");return}let s=t.action==="GENERATE"?t.generation_prompt:void 0;a(e,s,n.value||void 0,{path:`assets.${e}`})}async generateOne(e){var a,s,r;if(!this.mappingResult||this.isGenerating)return;let t=this.mappingResult.mappings.find(o=>o.game_object===e);if(!t)return;if(t.action="GENERATE",!t.generation_prompt){t.status="Missing prompt",this.renderMappings();return}let n=(r=(s=(a=this.root)==null?void 0:a.querySelector("[data-vision-api-key]"))==null?void 0:s.value)==null?void 0:r.trim();if(!n||!this.manifest){this.setStatus("apply","Missing API key or manifest");return}this.isGenerating=!0,t.status="Generating\u2026",this.renderMappings();try{let o={apiKey:n,manifest:this.manifest,flatDesignDataUrl:this.flatDesignDataUrl,assetFiles:this.assetFiles,gameObjects:this.getGameObjects(),gamePrompt:await this.getGamePrompt()};await $i(o,{mappings:[t]}),t.status=t.output_dataUrl?"Generated \u2713":t.status||"Done"}catch(o){console.error("[BrandVision] generateOne failed:",o),t.status="Failed \u2717"}finally{this.isGenerating=!1,this.renderMappings()}}async stageEngineAssetOverride(e,t){let{applyConfigOverride:n}=await Promise.resolve().then(()=>(ee(),sn));n({path:`assets.${e}`,value:t},{silent:!0});let a=window.applyEditableEngineConfig;typeof a=="function"&&a({assets:{[e]:t}})}async saveToLibraryAndReturnPath(e,t){if(!/^(data:|blob:)/.test(t))return t;let n=this.inferCategoryFromAssetKey(e),a=`${e.replace(/[^a-zA-Z0-9_-]/g,"_")}_vision_${Date.now()}.png`;try{let r=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:n,filename:a,data:t,overwrite:!0})})).json();if(!(r!=null&&r.success)||!(r!=null&&r.path))return console.error("[BrandVision] Save to library failed:",(r==null?void 0:r.error)||r),null;let o=window.addAssetToRegistry;typeof o=="function"&&o(n,a);let l=window.refreshAssetLibrary;return typeof l=="function"&&l(),String(r.path)}catch(s){return console.error("[BrandVision] Save to library error:",s),null}}inferCategoryFromAssetKey(e){let t=window.getEditableAssets;if(typeof t=="function"){let a=t();if(a!=null&&a.slots&&Array.isArray(a.slots)){let r=a.slots.find(o=>o.slotId===e||o.currentAsset===e);if(r!=null&&r.category)return String(r.category)}let s=a==null?void 0:a.categories;if(Array.isArray(s)&&s.length>0){let r=e.toLowerCase(),o=l=>s.find(c=>c.toLowerCase().includes(l));return r.includes("bg")||r.includes("background")?o("background")||s[0]:(r.includes("cta")||r.includes("button")||r.includes("ui")||r.includes("logo"))&&o("ui")||s[0]}}let n=e.toLowerCase();return n.includes("bg")||n.includes("background")?"backgrounds":n.includes("cta")||n.includes("button")||n.includes("ui")||n.includes("logo")?"ui":"misc"}async copyRawAnalysis(){if(this.analysisRawResponse)try{await navigator.clipboard.writeText(this.analysisRawResponse),this.setStatus("mapping","Copied raw analysis to clipboard")}catch{this.setStatus("mapping","Clipboard not available")}}setStatus(e,t){var s;let n={manifest:"[data-vision-manifest-status]",assets:"[data-vision-assets-status]",flat:"[data-vision-flat-status]",zip:"[data-vision-zip-status]",upload:"[data-vision-upload-status]",mapping:"[data-vision-mapping-status]",apply:"[data-vision-apply-status]"},a=(s=this.root)==null?void 0:s.querySelector(n[e]);a&&(a.textContent=t)}getGameObjects(){let e=window.getEditableObjectList;return typeof e=="function"?e():[]}async getGamePrompt(){try{let e=await fetch("./configs/engine/game.prompt.json");if(e.ok)return(await e.json()).game_prompt||""}catch{}return""}setupResizeHandle(){if(!this.root)return;let e=this.root.querySelector("[data-panel-resize]");e&&e.addEventListener("pointerdown",t=>{let n=t.clientX,a=this.root.getBoundingClientRect().width,s=o=>{let l=Math.max(300,a+(o.clientX-n));this.root.style.width=`${l}px`},r=()=>{window.removeEventListener("pointermove",s),window.removeEventListener("pointerup",r)};window.addEventListener("pointermove",s),window.addEventListener("pointerup",r)})}refresh(){}};function Bs(i,e={}){let{includeReference:t=!1,includeMagenta:n=!0,changeLevel:a=5}=e;return[`TASK: ${i}`,`CHANGE_STRENGTH: ${a}/10`,t?"REFERENCE: provided":"REFERENCE: none",n?"BACKGROUND: solid magenta #FF00FF (if possible)":""].filter(Boolean).join(`
698
+ `)}var Fo=["background_color","text_color","cta_background","cta_text","warning_text_color","endgame_title_color","endgame_subtitle_color","endgame_cta_text_color","endgame_cta_hint_color","endgame_footer_color"],Go=["cta_hint","cta_label_end"],Fs=[{key:"warning_text",objectId:"label.warning",property:"ui.text"},{key:"endgame_title",objectId:"ui.endgame.title",property:"ui.text"},{key:"endgame_subtitle",objectId:"ui.endgame.subtitle",property:"ui.text"},{key:"endgame_cta_text",objectId:"ui.endgame.cta",property:"ui.text"},{key:"endgame_cta_hint_text",objectId:"ui.endgame.cta.hint",property:"ui.text"},{key:"endgame_footer_text",objectId:"ui.endgame.footer",property:"ui.text"}],Uo=["brand.primary","brand.heading","brand.body","brand.warning"],Mn=class{constructor(){this.root=null;this.assetsContainer=null;this.colorsContainer=null;this.fontsContainer=null;this.textsContainer=null;this.audioContainer=null;this.options=null;this.previewModal=null;this.autoApplyTimer=null;this.activePreviewKey=null;this.activePreviewValue=null;this.activePreviewFileInput=null;this.retryTimer=null;this.aiModal=null;this.aiTargetKey=null;this.aiKeyInput=null;this.aiPromptInput=null;this.aiStrengthInput=null;this.aiStrengthValue=null;this.aiModelSelect=null;this.aiModalSubtitle=null;this.aiGalleryToggle=null;this.aiGalleryEl=null;this.aiGalleryGrid=null;this.aiReferenceInput=null;this.aiReferenceName=null;this.aiReferenceFile=null;this.aiRemoveBgToggle=null;this.aiUseOutputToggle=null;this.aiGenerateBtn=null;this.aiApplyBtn=null;this.aiSaveLibraryBtn=null;this.aiCropBtn=null;this.aiDownloadBtn=null;this.aiPreviewImg=null;this.aiStatusEl=null;this.aiOutputDataUrl=null;this.aiBaseDataUrl=null;this.aiBaseValue=null;this.aiOutputKey=null;this.aiContext=null;this.aiBgToleranceInput=null;this.aiBgToleranceValue=null;this.aiRawOutputDataUrl=null;this.aiLoadingEl=null}render(){return`
797
699
  <div class="scene-panel customize-panel panel-accent-blue" data-panel="customize-settings">
798
700
  <div class="scene-panel-header" data-panel-handle>
799
701
  <div class="panel-title">
@@ -851,22 +753,22 @@ Generate the requested asset matching the brand style.${e.needsTransparency?" Ba
851
753
  </div>
852
754
  <div class="panel-resize-handle" data-panel-resize></div>
853
755
  </div>
854
- `}initialize(t,i){var r,a,s,o,l,c;this.options=i,this.root=t.querySelector('[data-panel="customize-settings"]'),this.assetsContainer=(r=this.root)==null?void 0:r.querySelector("[data-customize-assets]"),this.colorsContainer=(a=this.root)==null?void 0:a.querySelector("[data-customize-colors]"),this.fontsContainer=(s=this.root)==null?void 0:s.querySelector("[data-customize-fonts]"),this.textsContainer=(o=this.root)==null?void 0:o.querySelector("[data-customize-texts]"),this.audioContainer=(l=this.root)==null?void 0:l.querySelector("[data-customize-audio]");let n=(c=this.root)==null?void 0:c.querySelector("[data-customize-apply]");n==null||n.addEventListener("click",()=>this.handleApply()),this.setupRenderModeHandlers(),this.setupResizeHandle(),this.refresh()}setupRenderModeHandlers(){var n,r;let t=(n=this.root)==null?void 0:n.querySelector('[data-render-mode="endgame-png"]'),i=(r=this.root)==null?void 0:r.querySelector('[data-render-mode="splash-png"]');t==null||t.addEventListener("change",()=>{this.applyEndgamePngMode(t.checked)}),i==null||i.addEventListener("change",()=>{this.applySplashPngMode(i.checked)})}applyEndgamePngMode(t){let i=window.getEditableObjectConfig,n=window.applyEditableObjectConfig;if(typeof i!="function"||typeof n!="function")return;let r=["ui_endgame_title_1","ui_endgame_subtitle_1","ui_endgame_logo_1","ui_endgame_cta_1"];for(let a of r){let s=i(a);s&&(s.ui||(s.ui={}),s.ui.renderMode=t?"png":"text",t&&(s.render||(s.render={}),s.render.asset||(s.render.asset={type:"image",path:""}),s.render.asset.type="image"),n(a,s))}console.log("[CustomizePanel] EndGame PNG mode:",t?"enabled":"disabled")}applySplashPngMode(t){let i=window.applyEditableEngineConfig;typeof i=="function"&&(i({splash:{type:t?"image":"text",image_path:t?"library/splash/splash.png":""}}),console.log("[CustomizePanel] Splash PNG mode:",t?"enabled":"disabled"))}openAiEditor(t,i,n,r){this.openAiModal(t,n,r),i&&this.aiPromptInput&&(this.aiPromptInput.value=i,this.setAiStatus("Prompt loaded."))}refresh(){var i,n,r,a,s,o,l,c;let t=this.getEngineSnapshot();if(console.log("[CustomizePanel] Refreshing with snapshot:",!!t),!t){this.scheduleRetry();return}console.log("[CustomizePanel] Snapshot assets count:",Object.keys(t.assets||{}).length),this.renderAssets(t.assets),this.renderColors((n=(i=t.runtime)==null?void 0:i.theme)!=null?n:{}),this.renderFonts((a=(r=t.runtime)==null?void 0:r.fonts)!=null?a:{}),this.renderTexts((o=(s=t.runtime)==null?void 0:s.ui)!=null?o:{}),this.renderAudio((c=(l=t.runtime)==null?void 0:l.audio)!=null?c:{})}getEngineSnapshot(){let t=window.getEditableEngineConfig;return typeof t!="function"?null:t()}renderAssets(t){if(!this.assetsContainer)return;this.assetsContainer.innerHTML="";let i=Object.entries(t!=null?t:{});if(!i.length){this.assetsContainer.innerHTML='<div class="customize-empty">No assets found.</div>',this.scheduleRetry();return}this.clearRetry(),i.forEach(([n,r])=>{var p;let a=document.createElement("div");a.className="customize-row";let s=document.createElement("span");s.className="customize-key",s.textContent=n;let o=document.createElement("input");o.type="text",o.value=r!=null?r:"",o.className="customize-input",o.dataset.assetKey=n,o.addEventListener("input",()=>{this.handleAssetValueChange(n,o)});let l=document.createElement("div");l.className="customize-actions";let c=document.createElement("button");c.type="button",c.className="customize-icon-btn",c.title="Preview asset",c.innerHTML=`
756
+ `}initialize(e,t){var a,s,r,o,l,c;this.options=t,this.root=e.querySelector('[data-panel="customize-settings"]'),this.assetsContainer=(a=this.root)==null?void 0:a.querySelector("[data-customize-assets]"),this.colorsContainer=(s=this.root)==null?void 0:s.querySelector("[data-customize-colors]"),this.fontsContainer=(r=this.root)==null?void 0:r.querySelector("[data-customize-fonts]"),this.textsContainer=(o=this.root)==null?void 0:o.querySelector("[data-customize-texts]"),this.audioContainer=(l=this.root)==null?void 0:l.querySelector("[data-customize-audio]");let n=(c=this.root)==null?void 0:c.querySelector("[data-customize-apply]");n==null||n.addEventListener("click",()=>this.handleApply()),this.setupRenderModeHandlers(),this.setupResizeHandle(),this.refresh()}setupRenderModeHandlers(){var n,a;let e=(n=this.root)==null?void 0:n.querySelector('[data-render-mode="endgame-png"]'),t=(a=this.root)==null?void 0:a.querySelector('[data-render-mode="splash-png"]');e==null||e.addEventListener("change",()=>{this.applyEndgamePngMode(e.checked)}),t==null||t.addEventListener("change",()=>{this.applySplashPngMode(t.checked)})}applyEndgamePngMode(e){let t=window.getEditableObjectConfig,n=window.applyEditableObjectConfig;if(typeof t!="function"||typeof n!="function")return;let a=["ui_endgame_title_1","ui_endgame_subtitle_1","ui_endgame_logo_1","ui_endgame_cta_1"];for(let s of a){let r=t(s);r&&(r.ui||(r.ui={}),r.ui.renderMode=e?"png":"text",e&&(r.render||(r.render={}),r.render.asset||(r.render.asset={type:"image",path:""}),r.render.asset.type="image"),n(s,r))}console.log("[CustomizePanel] EndGame PNG mode:",e?"enabled":"disabled")}applySplashPngMode(e){let t=window.applyEditableEngineConfig;typeof t=="function"&&(t({splash:{type:e?"image":"text",image_path:e?"library/splash/splash.png":""}}),console.log("[CustomizePanel] Splash PNG mode:",e?"enabled":"disabled"))}openAiEditor(e,t,n,a){this.openAiModal(e,n,a),t&&this.aiPromptInput&&(this.aiPromptInput.value=t,this.setAiStatus("Prompt loaded."))}refresh(){var t,n,a,s,r,o,l,c;let e=this.getEngineSnapshot();if(console.log("[CustomizePanel] Refreshing with snapshot:",!!e),!e){this.scheduleRetry();return}console.log("[CustomizePanel] Snapshot assets count:",Object.keys(e.assets||{}).length),this.renderAssets(e.assets),this.renderColors((n=(t=e.runtime)==null?void 0:t.theme)!=null?n:{}),this.renderFonts((s=(a=e.runtime)==null?void 0:a.fonts)!=null?s:{}),this.renderTexts((o=(r=e.runtime)==null?void 0:r.ui)!=null?o:{}),this.renderAudio((c=(l=e.runtime)==null?void 0:l.audio)!=null?c:{})}getEngineSnapshot(){let e=window.getEditableEngineConfig;return typeof e!="function"?null:e()}renderAssets(e){if(!this.assetsContainer)return;this.assetsContainer.innerHTML="";let t=Object.entries(e!=null?e:{});if(!t.length){this.assetsContainer.innerHTML='<div class="customize-empty">No assets found.</div>',this.scheduleRetry();return}this.clearRetry(),t.forEach(([n,a])=>{var u;let s=document.createElement("div");s.className="customize-row";let r=document.createElement("span");r.className="customize-key",r.textContent=n;let o=document.createElement("input");o.type="text",o.value=a!=null?a:"",o.className="customize-input",o.dataset.assetKey=n,o.addEventListener("input",()=>{this.handleAssetValueChange(n,o)});let l=document.createElement("div");l.className="customize-actions";let c=document.createElement("button");c.type="button",c.className="customize-icon-btn",c.title="Preview asset",c.innerHTML=`
855
757
  <svg viewBox="0 0 24 24" aria-hidden="true">
856
758
  <path d="M12 5c5.2 0 9.2 3.7 10 6.8-.8 3.1-4.8 6.8-10 6.8S2.8 14.9 2 11.8C2.8 8.7 6.8 5 12 5z" />
857
759
  <circle cx="12" cy="12" r="3.2" />
858
760
  </svg>
859
- `,c.addEventListener("click",()=>{this.previewAsset(n,o.value,o.dataset.assetType,u)});let d=document.createElement("button");d.type="button",d.className="customize-icon-btn",d.title="Upload asset",d.innerHTML=`
761
+ `,c.addEventListener("click",()=>{this.previewAsset(n,o.value,o.dataset.assetType,d)});let p=document.createElement("button");p.type="button",p.className="customize-icon-btn",p.title="Upload asset",p.innerHTML=`
860
762
  <svg viewBox="0 0 24 24" aria-hidden="true">
861
763
  <path d="M12 3l4 4h-3v6h-2V7H8l4-4z" />
862
764
  <path d="M5 14v4h14v-4h2v6H3v-6h2z" />
863
765
  </svg>
864
- `;let u=document.createElement("input");u.type="file",u.accept="image/*,audio/*,application/json",u.className="customize-file",u.addEventListener("change",()=>{var g;let f=(g=u.files)==null?void 0:g[0];f&&this.handleAssetUpload(f,o,n)}),d.addEventListener("click",()=>u.click()),l.appendChild(c),l.appendChild(d),l.appendChild(u),a.appendChild(s),a.appendChild(o),a.appendChild(l),(p=this.assetsContainer)==null||p.appendChild(a)})}renderColors(t){this.colorsContainer&&(this.colorsContainer.innerHTML="",Nw.forEach(i=>{var l,c,d;let n=(l=t==null?void 0:t[i])!=null?l:"#ffffff";if(i.includes("_text_color")||i.includes("_color")){let p={warning_text_color:{objectId:"label.warning",property:"render.tint"},endgame_title_color:{objectId:"ui.endgame.title",property:"render.tint"},endgame_subtitle_color:{objectId:"ui.endgame.subtitle",property:"render.tint"},endgame_cta_text_color:{objectId:"ui.endgame.cta",property:"render.tint"},endgame_cta_hint_color:{objectId:"ui.endgame.cta.hint",property:"render.tint"},endgame_footer_color:{objectId:"ui.endgame.footer",property:"render.tint"}}[i];p&&(n=(c=this.getObjectPropertyValue(p.objectId,p.property))!=null?c:"#ffffff")}let r=document.createElement("label");r.className="customize-color-field";let a=document.createElement("span");a.textContent=i.replace(/_/g," ");let s=document.createElement("input");s.type="color",s.value=n,s.dataset.colorKey=i;let o=document.createElement("input");o.type="text",o.value=n,o.className="customize-color-text",o.dataset.colorTextKey=i,s.addEventListener("input",()=>{o.value=s.value}),o.addEventListener("input",()=>{/^#([0-9a-fA-F]{6})$/.test(o.value)&&(s.value=o.value)}),r.appendChild(a),r.appendChild(s),r.appendChild(o),(d=this.colorsContainer)==null||d.appendChild(r)}))}renderFonts(t){this.fontsContainer&&(this.fontsContainer.innerHTML="",Fw.forEach(i=>{var s,o;let n=document.createElement("div");n.className="customize-row";let r=document.createElement("span");r.className="customize-key",r.textContent=i;let a=document.createElement("input");a.type="text",a.value=(s=t==null?void 0:t[i])!=null?s:i,a.className="customize-input",a.dataset.fontKey=i,n.appendChild(r),n.appendChild(a),(o=this.fontsContainer)==null||o.appendChild(n)}))}renderTexts(t){this.textsContainer&&(this.textsContainer.innerHTML="",Bw.forEach(i=>{var s,o;let n=document.createElement("div");n.className="customize-row";let r=document.createElement("span");r.className="customize-key",r.textContent=i;let a=document.createElement("input");a.type="text",a.value=(s=this.readUiValue(t,i))!=null?s:"",a.className="customize-input",a.dataset.textKey=i,n.appendChild(r),n.appendChild(a),(o=this.textsContainer)==null||o.appendChild(n)}),rg.forEach(({key:i,objectId:n})=>{var o,l;let r=document.createElement("div");r.className="customize-row";let a=document.createElement("span");a.className="customize-key",a.textContent=i;let s=document.createElement("input");s.type="text",s.value=(o=this.getObjectTextValue(n))!=null?o:"",s.className="customize-input",s.dataset.objectTextKey=i,r.appendChild(a),r.appendChild(s),(l=this.textsContainer)==null||l.appendChild(r)}))}renderAudio(t){if(!this.audioContainer)return;this.audioContainer.innerHTML="",["background_file","background_volume","click_file","click_volume","success_file","success_volume","complete_file","complete_volume"].forEach(n=>{var o,l;let r=document.createElement("div");r.className="customize-row";let a=document.createElement("span");a.className="customize-key",a.textContent=n.replace("_"," ");let s=document.createElement("input");s.type=n.includes("volume")?"number":"text",s.min="0",s.max="1",s.step="0.1",s.value=String((o=t==null?void 0:t[n])!=null?o:""),s.className="customize-input",s.dataset.audioKey=n,n.includes("file")&&(s.placeholder="audio file path"),r.appendChild(a),r.appendChild(s),(l=this.audioContainer)==null||l.appendChild(r)})}readUiValue(t,i){if(i.includes(".")){let r=i.split("."),a=t;for(let s of r){if(a==null)return null;a=a[s]}return typeof a=="string"?a:null}let n=t==null?void 0:t[i];return typeof n=="string"?n:null}getObjectTextValue(t){var r,a;let i=window.getEditableObjectConfig;if(typeof i!="function")return null;let n=i(t);return(a=(r=n==null?void 0:n.ui)==null?void 0:r.text)!=null?a:null}getObjectPropertyValue(t,i){let n=window.getEditableObjectConfig;if(typeof n!="function")return null;let r=n(t);if(!r)return null;let a=i.split("."),s=r;for(let o of a){if(s==null)return null;s=s[o]}return typeof s=="string"?s:null}handleApply(){this.handleApplyWithSource("manual")}handleApplyWithSource(t){if(console.log(`[CustomizePanel] handleApplyWithSource called with source: ${t}`),!this.root||!this.options)return;let i={};this.root.querySelectorAll("[data-asset-key]").forEach(o=>{let l=o;l.dataset.assetKey&&(i[l.dataset.assetKey]=l.value)}),console.log("[CustomizePanel] Assets being applied:",Object.keys(i).length,"total"),console.log("[CustomizePanel] Asset values:",i);let n={};this.root.querySelectorAll("[data-color-text-key]").forEach(o=>{let l=o,c=l.dataset.colorTextKey;c&&(c.includes("_text_color")||c.includes("_color")?this.applyTextColorToObject(c,l.value):n[c]=l.value)});let r={};this.root.querySelectorAll("[data-font-key]").forEach(o=>{let l=o,c=l.dataset.fontKey;c&&(r[c]=l.value)});let a={};this.root.querySelectorAll("[data-text-key]").forEach(o=>{let l=o,c=l.dataset.textKey;c&&(a[c]=l.value)});let s={};this.root.querySelectorAll("[data-audio-key]").forEach(o=>{let l=o,c=l.dataset.audioKey;if(c)if(c.includes("volume")){let d=parseFloat(l.value);s[c]=isNaN(d)?0:d}else s[c]=l.value}),this.root.querySelectorAll("[data-object-text-key]").forEach(o=>{let l=o,c=l.dataset.objectTextKey;if(!c)return;let d=rg.find(u=>u.key===c);d&&this.applyObjectPropertyValue(d.objectId,d.property,l.value)}),console.log("[CustomizePanel] Calling onApply callback to restart game with source:",t),this.options.onApply({assets:i,runtime:{theme:n,ui:a,fonts:r,audio:s}},{source:t})}setupAiPanel(){}setAiStatus(t){this.aiStatusEl&&(this.aiStatusEl.textContent=t)}getSelectedAssetKey(){return this.aiTargetKey}getSelectedAssetInput(){let t=this.getSelectedAssetKey();return!this.root||!t?null:this.root.querySelector(`input[data-asset-key="${t}"]`)}async getImageDataFromAsset(t){let i=this.resolveAssetUrls(t);console.log("[CustomizePanel] Resolving asset urls for AI:",t,i);for(let n of i)try{let r=await Ga(n);if(r)return console.log("[CustomizePanel] Successfully fetched image data for AI"),{input:{base64:r.base64,mimeType:r.mimeType},dataUrl:r.dataUrl,width:r.width,height:r.height}}catch(r){console.warn("[CustomizePanel] Failed to fetch image data from:",n,r)}return console.error("[CustomizePanel] Could not load image data for AI from any URL"),null}async updateAiBasePreview(t){var r,a,s;let i=(t==null?void 0:t.trim())||"";if(!i){let o=this.getSelectedAssetInput();i=(a=(r=o==null?void 0:o.value)==null?void 0:r.trim())!=null?a:""}if(console.log("[CustomizePanel] updateAiBasePreview using value:",i),!i){this.aiBaseDataUrl=null,this.updateAiPreview();return}let n=await this.getImageDataFromAsset(i);this.aiBaseDataUrl=(s=n==null?void 0:n.dataUrl)!=null?s:null,this.updateAiPreview()}updateAiPreview(){if(!this.aiPreviewImg)return;let t=this.aiOutputDataUrl||this.aiBaseDataUrl||"";if(!t){this.aiPreviewImg.removeAttribute("src");return}this.aiPreviewImg.src=t}updateAiModalPreview(t,i){if(!t)return;let n=i!=null?i:this.activePreviewKey;if(!n||!this.aiOutputDataUrl||this.aiOutputKey!==n){t.classList.add("hidden");return}let r=t.querySelector(".asset-preview-ai-image");r&&(r.src=this.aiOutputDataUrl),t.classList.remove("hidden")}setAiLoading(t){this.aiLoadingEl&&this.aiLoadingEl.classList.toggle("active",t),this.aiGenerateBtn&&(this.aiGenerateBtn.disabled=t)}toggleAiGallery(){if(!this.aiGalleryEl||!this.aiGalleryToggle)return;let t=this.aiGalleryEl.classList.toggle("hidden");this.aiGalleryToggle.textContent=t?"Gallery":"Hide Gallery",t||this.renderAiGallery()}renderAiGallery(){if(!this.aiGalleryGrid)return;let t=this.getAiGalleryEntries();if(!t.length){this.aiGalleryGrid.innerHTML='<div class="ai-gallery-empty">No image assets found.</div>';return}this.aiGalleryGrid.innerHTML="",t.forEach(({key:i,value:n})=>{var l;let r=document.createElement("button");r.type="button",r.className="ai-gallery-item",i===this.aiTargetKey&&r.classList.add("active");let a=document.createElement("img");a.className="ai-gallery-thumb",a.alt=i;let s=this.resolveAssetUrls(n);s[0]&&(a.src=s[0]);let o=document.createElement("span");o.className="ai-gallery-label",o.textContent=i,r.appendChild(a),r.appendChild(o),r.addEventListener("click",()=>this.selectAiGalleryAsset(i)),(l=this.aiGalleryGrid)==null||l.appendChild(r)})}getAiGalleryEntries(){if(!this.root)return[];let t=[];return this.root.querySelectorAll("[data-asset-key]").forEach(i=>{var s,o;let n=i,r=n.dataset.assetKey,a=(o=(s=n.value)==null?void 0:s.trim())!=null?o:"";!r||!a||this.isAiGalleryImage(a)&&t.push({key:r,value:a})}),t}isAiGalleryImage(t){let i=t.trim();if(!i)return!1;if(/^(data:image|blob:)/.test(i))return!0;let n=i.split("?")[0].toLowerCase();return![".mp3",".wav",".ogg",".json"].some(r=>n.endsWith(r))}selectAiGalleryAsset(t){this.aiTargetKey!==t&&(this.aiTargetKey=t,this.aiOutputDataUrl=null,this.aiOutputKey=null,this.aiReferenceFile=null,this.aiBaseDataUrl=null,this.aiReferenceInput&&(this.aiReferenceInput.value=""),this.aiReferenceName&&(this.aiReferenceName.textContent="Optional"),this.aiModalSubtitle&&(this.aiModalSubtitle.textContent=t),this.setAiOutputButtonsEnabled(!1),this.updateAiBasePreview(),this.updateAiPreview(),this.renderAiGallery())}openAiModal(t,i,n){var o,l,c,d,u,p,f,g,h,m;this.closeAiModal(),this.aiTargetKey=t,this.aiBaseValue=i||null,this.aiContext=n||null,this.aiOutputDataUrl=null,this.aiOutputKey=null,this.aiReferenceFile=null,this.aiBaseDataUrl=null;let r=document.createElement("div");r.className="ai-modal",r.innerHTML=`
766
+ `;let d=document.createElement("input");d.type="file",d.accept="image/*,audio/*,application/json",d.className="customize-file",d.addEventListener("change",()=>{var h;let g=(h=d.files)==null?void 0:h[0];g&&this.handleAssetUpload(g,o,n)}),p.addEventListener("click",()=>d.click()),l.appendChild(c),l.appendChild(p),l.appendChild(d),s.appendChild(r),s.appendChild(o),s.appendChild(l),(u=this.assetsContainer)==null||u.appendChild(s)})}renderColors(e){this.colorsContainer&&(this.colorsContainer.innerHTML="",Fo.forEach(t=>{var l,c,p;let n=(l=e==null?void 0:e[t])!=null?l:"#ffffff";if(t.includes("_text_color")||t.includes("_color")){let u={warning_text_color:{objectId:"label.warning",property:"render.tint"},endgame_title_color:{objectId:"ui.endgame.title",property:"render.tint"},endgame_subtitle_color:{objectId:"ui.endgame.subtitle",property:"render.tint"},endgame_cta_text_color:{objectId:"ui.endgame.cta",property:"render.tint"},endgame_cta_hint_color:{objectId:"ui.endgame.cta.hint",property:"render.tint"},endgame_footer_color:{objectId:"ui.endgame.footer",property:"render.tint"}}[t];u&&(n=(c=this.getObjectPropertyValue(u.objectId,u.property))!=null?c:"#ffffff")}let a=document.createElement("label");a.className="customize-color-field";let s=document.createElement("span");s.textContent=t.replace(/_/g," ");let r=document.createElement("input");r.type="color",r.value=n,r.dataset.colorKey=t;let o=document.createElement("input");o.type="text",o.value=n,o.className="customize-color-text",o.dataset.colorTextKey=t,r.addEventListener("input",()=>{o.value=r.value}),o.addEventListener("input",()=>{/^#([0-9a-fA-F]{6})$/.test(o.value)&&(r.value=o.value)}),a.appendChild(s),a.appendChild(r),a.appendChild(o),(p=this.colorsContainer)==null||p.appendChild(a)}))}renderFonts(e){this.fontsContainer&&(this.fontsContainer.innerHTML="",Uo.forEach(t=>{var r,o;let n=document.createElement("div");n.className="customize-row";let a=document.createElement("span");a.className="customize-key",a.textContent=t;let s=document.createElement("input");s.type="text",s.value=(r=e==null?void 0:e[t])!=null?r:t,s.className="customize-input",s.dataset.fontKey=t,n.appendChild(a),n.appendChild(s),(o=this.fontsContainer)==null||o.appendChild(n)}))}renderTexts(e){this.textsContainer&&(this.textsContainer.innerHTML="",Go.forEach(t=>{var r,o;let n=document.createElement("div");n.className="customize-row";let a=document.createElement("span");a.className="customize-key",a.textContent=t;let s=document.createElement("input");s.type="text",s.value=(r=this.readUiValue(e,t))!=null?r:"",s.className="customize-input",s.dataset.textKey=t,n.appendChild(a),n.appendChild(s),(o=this.textsContainer)==null||o.appendChild(n)}),Fs.forEach(({key:t,objectId:n})=>{var o,l;let a=document.createElement("div");a.className="customize-row";let s=document.createElement("span");s.className="customize-key",s.textContent=t;let r=document.createElement("input");r.type="text",r.value=(o=this.getObjectTextValue(n))!=null?o:"",r.className="customize-input",r.dataset.objectTextKey=t,a.appendChild(s),a.appendChild(r),(l=this.textsContainer)==null||l.appendChild(a)}))}renderAudio(e){if(!this.audioContainer)return;this.audioContainer.innerHTML="",["background_file","background_volume","click_file","click_volume","success_file","success_volume","complete_file","complete_volume"].forEach(n=>{var o,l;let a=document.createElement("div");a.className="customize-row";let s=document.createElement("span");s.className="customize-key",s.textContent=n.replace("_"," ");let r=document.createElement("input");r.type=n.includes("volume")?"number":"text",r.min="0",r.max="1",r.step="0.1",r.value=String((o=e==null?void 0:e[n])!=null?o:""),r.className="customize-input",r.dataset.audioKey=n,n.includes("file")&&(r.placeholder="audio file path"),a.appendChild(s),a.appendChild(r),(l=this.audioContainer)==null||l.appendChild(a)})}readUiValue(e,t){if(t.includes(".")){let a=t.split("."),s=e;for(let r of a){if(s==null)return null;s=s[r]}return typeof s=="string"?s:null}let n=e==null?void 0:e[t];return typeof n=="string"?n:null}getObjectTextValue(e){var a,s;let t=window.getEditableObjectConfig;if(typeof t!="function")return null;let n=t(e);return(s=(a=n==null?void 0:n.ui)==null?void 0:a.text)!=null?s:null}getObjectPropertyValue(e,t){let n=window.getEditableObjectConfig;if(typeof n!="function")return null;let a=n(e);if(!a)return null;let s=t.split("."),r=a;for(let o of s){if(r==null)return null;r=r[o]}return typeof r=="string"?r:null}handleApply(){this.handleApplyWithSource("manual")}handleApplyWithSource(e){if(console.log(`[CustomizePanel] handleApplyWithSource called with source: ${e}`),!this.root||!this.options)return;let t={};this.root.querySelectorAll("[data-asset-key]").forEach(o=>{let l=o;l.dataset.assetKey&&(t[l.dataset.assetKey]=l.value)}),console.log("[CustomizePanel] Assets being applied:",Object.keys(t).length,"total"),console.log("[CustomizePanel] Asset values:",t);let n={};this.root.querySelectorAll("[data-color-text-key]").forEach(o=>{let l=o,c=l.dataset.colorTextKey;c&&(c.includes("_text_color")||c.includes("_color")?this.applyTextColorToObject(c,l.value):n[c]=l.value)});let a={};this.root.querySelectorAll("[data-font-key]").forEach(o=>{let l=o,c=l.dataset.fontKey;c&&(a[c]=l.value)});let s={};this.root.querySelectorAll("[data-text-key]").forEach(o=>{let l=o,c=l.dataset.textKey;c&&(s[c]=l.value)});let r={};this.root.querySelectorAll("[data-audio-key]").forEach(o=>{let l=o,c=l.dataset.audioKey;if(c)if(c.includes("volume")){let p=parseFloat(l.value);r[c]=isNaN(p)?0:p}else r[c]=l.value}),this.root.querySelectorAll("[data-object-text-key]").forEach(o=>{let l=o,c=l.dataset.objectTextKey;if(!c)return;let p=Fs.find(d=>d.key===c);p&&this.applyObjectPropertyValue(p.objectId,p.property,l.value)}),console.log("[CustomizePanel] Calling onApply callback to restart game with source:",e),this.options.onApply({assets:t,runtime:{theme:n,ui:s,fonts:a,audio:r}},{source:e})}setupAiPanel(){}setAiStatus(e){this.aiStatusEl&&(this.aiStatusEl.textContent=e)}getSelectedAssetKey(){return this.aiTargetKey}getSelectedAssetInput(){let e=this.getSelectedAssetKey();return!this.root||!e?null:this.root.querySelector(`input[data-asset-key="${e}"]`)}async getImageDataFromAsset(e){let t=this.resolveAssetUrls(e);console.log("[CustomizePanel] Resolving asset urls for AI:",e,t);for(let n of t)try{let a=await Tn(n);if(a)return console.log("[CustomizePanel] Successfully fetched image data for AI"),{input:{base64:a.base64,mimeType:a.mimeType},dataUrl:a.dataUrl,width:a.width,height:a.height}}catch(a){console.warn("[CustomizePanel] Failed to fetch image data from:",n,a)}return console.error("[CustomizePanel] Could not load image data for AI from any URL"),null}async updateAiBasePreview(e){var a,s,r;let t=(e==null?void 0:e.trim())||"";if(!t){let o=this.getSelectedAssetInput();t=(s=(a=o==null?void 0:o.value)==null?void 0:a.trim())!=null?s:""}if(console.log("[CustomizePanel] updateAiBasePreview using value:",t),!t){this.aiBaseDataUrl=null,this.updateAiPreview();return}let n=await this.getImageDataFromAsset(t);this.aiBaseDataUrl=(r=n==null?void 0:n.dataUrl)!=null?r:null,this.updateAiPreview()}updateAiPreview(){if(!this.aiPreviewImg)return;let e=this.aiOutputDataUrl||this.aiBaseDataUrl||"";if(!e){this.aiPreviewImg.removeAttribute("src");return}this.aiPreviewImg.src=e}updateAiModalPreview(e,t){if(!e)return;let n=t!=null?t:this.activePreviewKey;if(!n||!this.aiOutputDataUrl||this.aiOutputKey!==n){e.classList.add("hidden");return}let a=e.querySelector(".asset-preview-ai-image");a&&(a.src=this.aiOutputDataUrl),e.classList.remove("hidden")}setAiLoading(e){this.aiLoadingEl&&this.aiLoadingEl.classList.toggle("active",e),this.aiGenerateBtn&&(this.aiGenerateBtn.disabled=e)}toggleAiGallery(){if(!this.aiGalleryEl||!this.aiGalleryToggle)return;let e=this.aiGalleryEl.classList.toggle("hidden");this.aiGalleryToggle.textContent=e?"Gallery":"Hide Gallery",e||this.renderAiGallery()}renderAiGallery(){if(!this.aiGalleryGrid)return;let e=this.getAiGalleryEntries();if(!e.length){this.aiGalleryGrid.innerHTML='<div class="ai-gallery-empty">No image assets found.</div>';return}this.aiGalleryGrid.innerHTML="",e.forEach(({key:t,value:n})=>{var l;let a=document.createElement("button");a.type="button",a.className="ai-gallery-item",t===this.aiTargetKey&&a.classList.add("active");let s=document.createElement("img");s.className="ai-gallery-thumb",s.alt=t;let r=this.resolveAssetUrls(n);r[0]&&(s.src=r[0]);let o=document.createElement("span");o.className="ai-gallery-label",o.textContent=t,a.appendChild(s),a.appendChild(o),a.addEventListener("click",()=>this.selectAiGalleryAsset(t)),(l=this.aiGalleryGrid)==null||l.appendChild(a)})}getAiGalleryEntries(){if(!this.root)return[];let e=[];return this.root.querySelectorAll("[data-asset-key]").forEach(t=>{var r,o;let n=t,a=n.dataset.assetKey,s=(o=(r=n.value)==null?void 0:r.trim())!=null?o:"";!a||!s||this.isAiGalleryImage(s)&&e.push({key:a,value:s})}),e}isAiGalleryImage(e){let t=e.trim();if(!t)return!1;if(/^(data:image|blob:)/.test(t))return!0;let n=t.split("?")[0].toLowerCase();return![".mp3",".wav",".ogg",".json"].some(a=>n.endsWith(a))}selectAiGalleryAsset(e){this.aiTargetKey!==e&&(this.aiTargetKey=e,this.aiOutputDataUrl=null,this.aiOutputKey=null,this.aiReferenceFile=null,this.aiBaseDataUrl=null,this.aiReferenceInput&&(this.aiReferenceInput.value=""),this.aiReferenceName&&(this.aiReferenceName.textContent="Optional"),this.aiModalSubtitle&&(this.aiModalSubtitle.textContent=e),this.setAiOutputButtonsEnabled(!1),this.updateAiBasePreview(),this.updateAiPreview(),this.renderAiGallery())}openAiModal(e,t,n){var o,l,c,p,d,u,g,h,f,m;this.closeAiModal(),this.aiTargetKey=e,this.aiBaseValue=t||null,this.aiContext=n||null,this.aiOutputDataUrl=null,this.aiOutputKey=null,this.aiReferenceFile=null,this.aiBaseDataUrl=null;let a=document.createElement("div");a.className="ai-modal",a.innerHTML=`
865
767
  <div class="ai-modal-card">
866
768
  <div class="ai-modal-header">
867
769
  <div>
868
770
  <div class="ai-modal-title">AI Image Edit</div>
869
- <div class="ai-modal-subtitle">${t}</div>
771
+ <div class="ai-modal-subtitle">${e}</div>
870
772
  </div>
871
773
  <div class="ai-modal-actions">
872
774
  <button class="ai-modal-gallery" type="button" data-ai-gallery-toggle>Gallery</button>
@@ -932,10 +834,10 @@ Generate the requested asset matching the brand style.${e.needsTransparency?" Ba
932
834
  </div>
933
835
  </div>
934
836
  </div>
935
- `;let a=r.querySelector(".ai-modal-close");a==null||a.addEventListener("click",()=>this.closeAiModal()),r.addEventListener("click",b=>{b.target===r&&this.closeAiModal()}),this.aiModal=r,this.aiKeyInput=r.querySelector("[data-ai-key]"),this.aiModelSelect=r.querySelector("[data-ai-model]"),this.aiPromptInput=r.querySelector("[data-ai-prompt]"),this.aiStrengthInput=r.querySelector("[data-ai-strength]"),this.aiStrengthValue=r.querySelector("[data-ai-strength-value]"),this.aiModalSubtitle=r.querySelector(".ai-modal-subtitle"),this.aiGalleryToggle=r.querySelector("[data-ai-gallery-toggle]"),this.aiGalleryEl=r.querySelector("[data-ai-gallery]"),this.aiGalleryGrid=r.querySelector("[data-ai-gallery-grid]"),this.aiReferenceInput=r.querySelector("[data-ai-ref-input]"),this.aiReferenceName=r.querySelector("[data-ai-ref-name]"),this.aiRemoveBgToggle=r.querySelector("[data-ai-remove-bg]"),this.aiUseOutputToggle=r.querySelector("[data-ai-use-output]"),this.aiGenerateBtn=r.querySelector("[data-ai-generate]"),this.aiApplyBtn=r.querySelector("[data-ai-apply]"),this.aiSaveLibraryBtn=r.querySelector("[data-ai-save-library]"),this.aiCropBtn=r.querySelector("[data-ai-crop]"),this.aiDownloadBtn=r.querySelector("[data-ai-download]"),this.aiPreviewImg=r.querySelector("[data-ai-preview]"),this.aiStatusEl=r.querySelector("[data-ai-status]"),this.aiLoadingEl=r.querySelector("[data-ai-loading]"),this.aiBgToleranceInput=r.querySelector("[data-ai-bg-tolerance]"),this.aiBgToleranceValue=r.querySelector("[data-ai-bg-tolerance-value]"),(o=this.aiRemoveBgToggle)==null||o.addEventListener("change",()=>{this.refreshAiOutputFromRaw()});let s=r.querySelector("[data-ai-ref-button]");s==null||s.addEventListener("click",()=>{var b;return(b=this.aiReferenceInput)==null?void 0:b.click()}),(l=this.aiGalleryToggle)==null||l.addEventListener("click",()=>this.toggleAiGallery()),(c=this.aiStrengthInput)==null||c.addEventListener("input",()=>{var y,v;let b=(v=(y=this.aiStrengthInput)==null?void 0:y.value)!=null?v:"5";this.aiStrengthValue&&(this.aiStrengthValue.textContent=b)}),(d=this.aiBgToleranceInput)==null||d.addEventListener("input",()=>{var y,v;let b=(v=(y=this.aiBgToleranceInput)==null?void 0:y.value)!=null?v:"30";this.aiBgToleranceValue&&(this.aiBgToleranceValue.textContent=b),this.refreshAiOutputFromRaw()}),(u=this.aiReferenceInput)==null||u.addEventListener("change",()=>{var y,v,x;let b=(x=(v=(y=this.aiReferenceInput)==null?void 0:y.files)==null?void 0:v[0])!=null?x:null;this.aiReferenceFile=b,this.aiReferenceName&&(this.aiReferenceName.textContent=b?`${b.name} (loaded)`:"Optional"),b&&this.setAiStatus(`Reference attached: ${b.name}`)}),(p=this.aiGenerateBtn)==null||p.addEventListener("click",()=>{this.handleAiGenerate()}),(f=this.aiApplyBtn)==null||f.addEventListener("click",()=>this.handleAiApply()),(g=this.aiSaveLibraryBtn)==null||g.addEventListener("click",()=>{this.handleAiSaveToLibrary()}),(h=this.aiCropBtn)==null||h.addEventListener("click",()=>{this.handleAiCrop()}),(m=this.aiDownloadBtn)==null||m.addEventListener("click",()=>this.handleAiDownload()),document.body.appendChild(r),this.setAiOutputButtonsEnabled(!1),this.setAiStatus("Ready."),this.updateAiBasePreview(i),this.updateAiPreview(),this.renderAiGallery()}closeAiModal(){this.aiModal&&(this.aiModal.remove(),this.aiModal=null),this.aiTargetKey=null,this.aiBaseValue=null,this.aiContext=null,this.aiKeyInput=null,this.aiModelSelect=null,this.aiPromptInput=null,this.aiStrengthInput=null,this.aiStrengthValue=null,this.aiModalSubtitle=null,this.aiGalleryToggle=null,this.aiGalleryEl=null,this.aiGalleryGrid=null,this.aiReferenceInput=null,this.aiReferenceName=null,this.aiReferenceFile=null,this.aiRemoveBgToggle=null,this.aiUseOutputToggle=null,this.aiGenerateBtn=null,this.aiApplyBtn=null,this.aiCropBtn=null,this.aiDownloadBtn=null,this.aiPreviewImg=null,this.aiStatusEl=null,this.aiLoadingEl=null,this.aiBgToleranceInput=null,this.aiBgToleranceValue=null}async handleAiGenerate(){var d,u,p,f,g,h,m,b,y,v,x,w,E,A,_,T,P,S,L,z;if(console.log("[CustomizePanel] handleAiGenerate clicked"),!this.aiGenerateBtn)return;let t=(p=(u=(d=this.aiKeyInput)==null?void 0:d.value)==null?void 0:u.trim())!=null?p:"",i=(g=(f=this.aiModelSelect)==null?void 0:f.value)!=null?g:"gemini-2.5-flash-image",n=(b=(m=(h=this.aiPromptInput)==null?void 0:h.value)==null?void 0:m.trim())!=null?b:"",r=(v=(y=this.aiRemoveBgToggle)==null?void 0:y.checked)!=null?v:!1,a=r,s=r,o=Number((w=(x=this.aiStrengthInput)==null?void 0:x.value)!=null?w:"5");if(!t){this.setAiStatus("Missing API key.");return}if(!n){this.setAiStatus("Add a prompt.");return}let l=this.getSelectedAssetInput(),c=((E=l==null?void 0:l.value)==null?void 0:E.trim())||((A=this.aiBaseValue)==null?void 0:A.trim())||"";if(!c&&!this.aiOutputDataUrl){this.setAiStatus("Select an asset first.");return}this.setAiLoading(!0),this.setAiStatus("Generating...");try{let D=null,B=(_=this.getSelectedAssetKey())!=null?_:"unknown",O=(T=this.aiUseOutputToggle)!=null&&T.checked&&this.aiOutputDataUrl?"ai-output":"asset-value";if((P=this.aiUseOutputToggle)!=null&&P.checked&&this.aiOutputDataUrl){let Re=Bl(this.aiOutputDataUrl,"ai-output.png");if(Re){let je=await Mt(Re);je&&(D={input:{base64:je.base64,mimeType:je.mimeType},dataUrl:je.dataUrl,width:je.width,height:je.height})}}if(D||(D=await this.getImageDataFromAsset(c)),!D){this.setAiStatus("Unable to load the base image.");return}let R=[D.input],C=!1;if(this.aiReferenceFile){let Re=await Mt(this.aiReferenceFile);Re?(R.push({base64:Re.base64,mimeType:Re.mimeType}),C=!0,this.setAiStatus(`Generating with reference: ${this.aiReferenceFile.name}`)):this.setAiStatus("Reference image failed to load, generating without reference.")}let I=ng(n,{includeReference:C,includeMagenta:a,changeLevel:o}),j=(L=(S=this.aiReferenceFile)==null?void 0:S.name)!=null?L:"none";console.info("[AI] Final prompt:",I),console.info("[AI] Image sources:",{assetKey:B,base:O,reference:j});let Q=Gh(D.width,D.height);console.info("[AI] CRITICAL: Calling generateImageWithGemini25Flash NOW...");let se=await Gi(t,I,R,{aspectRatio:Q,model:i});console.info("[AI] CRITICAL: generateImageWithGemini25Flash returned! Length:",se==null?void 0:se.length),this.aiRawOutputDataUrl=se,await this.refreshAiOutputFromRaw()}catch(D){console.error("[CustomizePanel] AI Generate Error:",D),this.setAiStatus("Generation failed. Check console.")}finally{this.setAiLoading(!1),((z=this.aiStatusEl)==null?void 0:z.textContent)==="Generating..."&&this.setAiStatus("Ready.")}}async refreshAiOutputFromRaw(){var r,a,s,o;if(!this.aiRawOutputDataUrl)return;let t=(a=(r=this.aiRemoveBgToggle)==null?void 0:r.checked)!=null?a:!1,i=Number((o=(s=this.aiBgToleranceInput)==null?void 0:s.value)!=null?o:"30"),n=this.aiRawOutputDataUrl;if(t){let l=await qi(this.aiRawOutputDataUrl,i);l&&(n=l)}this.setAiOutput(n),this.setAiStatus("Ready.")}setAiOutput(t){var n,r;this.aiOutputDataUrl=t,this.aiOutputKey=this.getSelectedAssetKey(),this.updateAiPreview(),this.setAiOutputButtonsEnabled(!0);let i=(n=this.previewModal)==null?void 0:n.querySelector("[data-asset-ai-preview]");this.updateAiModalPreview(i,(r=this.activePreviewKey)!=null?r:void 0)}setAiOutputButtonsEnabled(t){this.aiApplyBtn&&(this.aiApplyBtn.disabled=!t),this.aiSaveLibraryBtn&&(this.aiSaveLibraryBtn.disabled=!t),this.aiCropBtn&&(this.aiCropBtn.disabled=!t),this.aiDownloadBtn&&(this.aiDownloadBtn.disabled=!t)}handleAiApply(){var i,n,r;let t=this.getSelectedAssetInput();if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}if(t)console.log("[CustomizePanel] Applying AI output to brand asset:",t.dataset.assetKey),t.value=this.aiOutputDataUrl,this.handleAssetValueChange((i=t.dataset.assetKey)!=null?i:"",t),this.setAiStatus("Applied. Restarting game...");else{let a=((n=this.aiContext)==null?void 0:n.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),s=((r=this.aiContext)==null?void 0:r.path)||this.inferPathFromAssetKey(this.aiTargetKey||"");if(a&&s)console.log("[CustomizePanel] Applying AI output directly to object:",a,s),this.applyObjectPropertyValue(a,s,this.aiOutputDataUrl),this.setAiStatus("Applied directly. Restarting game..."),window.dispatchEvent(new CustomEvent("inspector:refresh"));else{this.setAiStatus("No target input found to apply.");return}}setTimeout(()=>{this.closeAiModal()},500)}async handleAiSaveToLibrary(){var a,s,o;if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}if(!this.getSelectedAssetKey()){this.setAiStatus("No asset selected.");return}let n=`${(this.aiTargetKey||"asset").replace(/[^a-zA-Z0-9_-]/g,"_")}_ai_${Date.now()}`,r=this.inferCategoryFromAssetKey(this.aiTargetKey||"");this.setAiStatus("Saving to library...");try{let c=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:r,filename:`${n}.png`,data:this.aiOutputDataUrl,overwrite:!0})})).json();if(c.success){console.log("[CustomizePanel] \u2705 Saved to library:",c.path),this.setAiStatus(`Saved as ${n}. Applying...`);let d=window.addAssetToRegistry;typeof d=="function"&&(console.log("[CustomizePanel] Logic: Adding to registry category:",r),d(r,`${n}.png`));let u=window.refreshAssetLibrary;typeof u=="function"&&(console.log("[CustomizePanel] Logic: Refreshing library panel"),u());let p=((a=this.aiContext)==null?void 0:a.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),f=((s=this.aiContext)==null?void 0:s.path)||this.inferPathFromAssetKey(this.aiTargetKey||""),g=this.getSelectedAssetInput();if(g&&(g.value=c.path,this.handleAssetValueChange((o=g.dataset.assetKey)!=null?o:"",g)),p&&f){console.log("[CustomizePanel] Saved and applying directly to object:",p,f);let h=window.applyAssetToSlot,m=/texture|image|sprite|asset\\.path/i.test(f)||/\\.(png|jpg|jpeg)$/i.test(String(c.path||""));if(typeof h=="function"&&m){let b=this.getFilenameFromPath(c.path);h(p,b,r)}else this.applyObjectPropertyValue(p,f,c.path);window.dispatchEvent(new CustomEvent("inspector:refresh"))}setTimeout(()=>{this.closeAiModal()},1e3)}else console.error("[CustomizePanel] \u274C Save failed:",c.error),this.setAiStatus(`Save failed: ${c.error}`)}catch(l){console.error("[CustomizePanel] \u274C Save error:",l),this.setAiStatus("Save failed. Check console.")}}inferCategoryFromAssetKey(t){var s;let i=(s=this.aiContext)==null?void 0:s.objectId,n=t||this.aiTargetKey||"",r=window.getEditableAssets;if(typeof r=="function"){let o=r();if(o!=null&&o.slots){let l=o.slots.find(c=>i&&c.objectId===i||c.currentAsset===n||c.slotId===n||c.currentAsset&&c.currentAsset.includes(n)||n.includes(c.slotId));if(l){let c=l.libraryFolder||l.category;if(c)return c}}}let a=n.toLowerCase();return a.includes("background")?"backgrounds":a.includes("character")?"characters":a.includes("key")?"collectedkeys":a.includes("draggable")?"draggables":a.includes("environment")||a.includes("env")||a.includes("hand")||a.includes("prop")||a.includes("item")||a.includes("decor")||a.includes("object")?"environment":a.includes("machine")?"machines":a.includes("tutorial")?"tutorial":a.includes("ui")||a.includes("button")||a.includes("label")||a.includes("icon")||a.includes("logo")||a.includes("cta")||a.includes("menu")||a.includes("overlay")?"ui":a.includes("effect")||a.includes("confetti")||a.includes("particle")?"effects":"ui"}inferObjectIdFromAssetKey(t){let i=window.getEditableAssets;if(typeof i!="function")return null;let n=i();if(!(n!=null&&n.slots))return null;let r=n.slots.find(a=>a.currentAsset===t||a.slotId===t);return(r==null?void 0:r.objectId)||null}inferPathFromAssetKey(t){let i=window.getEditableAssets;if(typeof i!="function")return null;let n=i();if(!(n!=null&&n.slots))return null;let r=n.slots.find(s=>s.currentAsset===t||s.slotId===t);if(!r)return null;let a=r.category;return a==="render"||a==="backgrounds"||a==="characters"?"render.texture":a==="ui"?"ui.image":a==="audio"?"audio.src":"render.texture"}getFilenameFromPath(t){if(!t)return"";let i=t.split("/");return i[i.length-1]}async handleAiCrop(){var o;if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}let t=this.getSelectedAssetInput(),i=(o=t==null?void 0:t.value)!=null?o:"",n=await this.getImageDimensions(i);if(!n){this.setAiStatus("Unable to read target dimensions.");return}let r=Bl(this.aiOutputDataUrl,"ai-output.png");if(!r)return;let a=await this.showManualCropModal(r,n,i);if(!a)return;let s=await qh(a);s&&this.setAiOutput(s)}handleAiDownload(){var n;if(!this.aiOutputDataUrl)return;let t=(n=this.getSelectedAssetKey())!=null?n:"ai-image",i=document.createElement("a");i.href=this.aiOutputDataUrl,i.download=`${t}-ai.png`,i.click()}handleAssetValueChange(t,i){this.previewModal&&this.closePreviewModal(),this.scheduleAutoApply(),this.updatePreviewIfOpen(t,i.value,i.dataset.assetType)}async handleAssetUpload(t,i,n){let r=i.value,a=t;if(t.type.startsWith("image/")){let l=await this.getImageDimensions(r);if(l){let c=await this.showManualCropModal(t,l,r);if(!c)return;a=c}}let s=URL.createObjectURL(a),o=i.dataset.objectUrl;if(o)try{URL.revokeObjectURL(o)}catch{}i.dataset.objectUrl=s,i.dataset.assetType=a.type,i.value=s,this.handleAssetValueChange(n,i)}scheduleAutoApply(){this.options&&(this.autoApplyTimer&&window.clearTimeout(this.autoApplyTimer),console.log("[CustomizePanel] Scheduling auto-apply in 250ms"),this.autoApplyTimer=window.setTimeout(()=>{this.autoApplyTimer=null,console.log("[CustomizePanel] Executing auto-apply now"),this.handleApplyWithSource("auto")},250))}previewAsset(t,i,n,r){if(!i)return;let a=this.resolveAssetUrls(i);if(a.length===0)return;let s=n||this.guessMimeType(i);this.activePreviewKey=t,this.activePreviewValue=i,this.activePreviewFileInput=r!=null?r:null,this.openPreviewModal(t,i,a,s)}resolveAssetUrls(t){let i=t.trim();if(!i)return[];if(console.log("[CustomizePanel] Resolving asset urls for:",i),/^(blob:|data:|https?:|\/)/.test(i))return console.log("[CustomizePanel] Path is absolute or data/blob, using as is"),[i];let n=i.replace(/^\.?\//,""),r=[];return n.startsWith("raw/")?r=[`/${n}`,`/assets/${n}`]:n.startsWith("assets/")?r=[`/${n}`]:r=[`/raw/${n}`,`/assets/raw/${n}`,`/assets/${n}`,`/${n}`],console.log("[CustomizePanel] Resolved to possible paths:",r),r}guessMimeType(t){let i=t.toLowerCase();return i.endsWith(".png")||i.endsWith(".jpg")||i.endsWith(".jpeg")||i.endsWith(".gif")||i.endsWith(".webp")||i.endsWith(".svg")?"image":i.endsWith(".mp3")||i.endsWith(".wav")||i.endsWith(".ogg")?"audio":i.endsWith(".json")?"json":"file"}openPreviewModal(t,i,n,r){this.closePreviewModal(!0);let a=document.createElement("div");a.className="asset-preview-modal",a.innerHTML=`
837
+ `;let s=a.querySelector(".ai-modal-close");s==null||s.addEventListener("click",()=>this.closeAiModal()),a.addEventListener("click",b=>{b.target===a&&this.closeAiModal()}),this.aiModal=a,this.aiKeyInput=a.querySelector("[data-ai-key]"),this.aiModelSelect=a.querySelector("[data-ai-model]"),this.aiPromptInput=a.querySelector("[data-ai-prompt]"),this.aiStrengthInput=a.querySelector("[data-ai-strength]"),this.aiStrengthValue=a.querySelector("[data-ai-strength-value]"),this.aiModalSubtitle=a.querySelector(".ai-modal-subtitle"),this.aiGalleryToggle=a.querySelector("[data-ai-gallery-toggle]"),this.aiGalleryEl=a.querySelector("[data-ai-gallery]"),this.aiGalleryGrid=a.querySelector("[data-ai-gallery-grid]"),this.aiReferenceInput=a.querySelector("[data-ai-ref-input]"),this.aiReferenceName=a.querySelector("[data-ai-ref-name]"),this.aiRemoveBgToggle=a.querySelector("[data-ai-remove-bg]"),this.aiUseOutputToggle=a.querySelector("[data-ai-use-output]"),this.aiGenerateBtn=a.querySelector("[data-ai-generate]"),this.aiApplyBtn=a.querySelector("[data-ai-apply]"),this.aiSaveLibraryBtn=a.querySelector("[data-ai-save-library]"),this.aiCropBtn=a.querySelector("[data-ai-crop]"),this.aiDownloadBtn=a.querySelector("[data-ai-download]"),this.aiPreviewImg=a.querySelector("[data-ai-preview]"),this.aiStatusEl=a.querySelector("[data-ai-status]"),this.aiLoadingEl=a.querySelector("[data-ai-loading]"),this.aiBgToleranceInput=a.querySelector("[data-ai-bg-tolerance]"),this.aiBgToleranceValue=a.querySelector("[data-ai-bg-tolerance-value]"),(o=this.aiRemoveBgToggle)==null||o.addEventListener("change",()=>{this.refreshAiOutputFromRaw()});let r=a.querySelector("[data-ai-ref-button]");r==null||r.addEventListener("click",()=>{var b;return(b=this.aiReferenceInput)==null?void 0:b.click()}),(l=this.aiGalleryToggle)==null||l.addEventListener("click",()=>this.toggleAiGallery()),(c=this.aiStrengthInput)==null||c.addEventListener("input",()=>{var y,v;let b=(v=(y=this.aiStrengthInput)==null?void 0:y.value)!=null?v:"5";this.aiStrengthValue&&(this.aiStrengthValue.textContent=b)}),(p=this.aiBgToleranceInput)==null||p.addEventListener("input",()=>{var y,v;let b=(v=(y=this.aiBgToleranceInput)==null?void 0:y.value)!=null?v:"30";this.aiBgToleranceValue&&(this.aiBgToleranceValue.textContent=b),this.refreshAiOutputFromRaw()}),(d=this.aiReferenceInput)==null||d.addEventListener("change",()=>{var y,v,x;let b=(x=(v=(y=this.aiReferenceInput)==null?void 0:y.files)==null?void 0:v[0])!=null?x:null;this.aiReferenceFile=b,this.aiReferenceName&&(this.aiReferenceName.textContent=b?`${b.name} (loaded)`:"Optional"),b&&this.setAiStatus(`Reference attached: ${b.name}`)}),(u=this.aiGenerateBtn)==null||u.addEventListener("click",()=>{this.handleAiGenerate()}),(g=this.aiApplyBtn)==null||g.addEventListener("click",()=>this.handleAiApply()),(h=this.aiSaveLibraryBtn)==null||h.addEventListener("click",()=>{this.handleAiSaveToLibrary()}),(f=this.aiCropBtn)==null||f.addEventListener("click",()=>{this.handleAiCrop()}),(m=this.aiDownloadBtn)==null||m.addEventListener("click",()=>this.handleAiDownload()),document.body.appendChild(a),this.setAiOutputButtonsEnabled(!1),this.setAiStatus("Ready."),this.updateAiBasePreview(t),this.updateAiPreview(),this.renderAiGallery()}closeAiModal(){this.aiModal&&(this.aiModal.remove(),this.aiModal=null),this.aiTargetKey=null,this.aiBaseValue=null,this.aiContext=null,this.aiKeyInput=null,this.aiModelSelect=null,this.aiPromptInput=null,this.aiStrengthInput=null,this.aiStrengthValue=null,this.aiModalSubtitle=null,this.aiGalleryToggle=null,this.aiGalleryEl=null,this.aiGalleryGrid=null,this.aiReferenceInput=null,this.aiReferenceName=null,this.aiReferenceFile=null,this.aiRemoveBgToggle=null,this.aiUseOutputToggle=null,this.aiGenerateBtn=null,this.aiApplyBtn=null,this.aiCropBtn=null,this.aiDownloadBtn=null,this.aiPreviewImg=null,this.aiStatusEl=null,this.aiLoadingEl=null,this.aiBgToleranceInput=null,this.aiBgToleranceValue=null}async handleAiGenerate(){var p,d,u,g,h,f,m,b,y,v,x,E,w,T,S,O,B,M,C,I;if(console.log("[CustomizePanel] handleAiGenerate clicked"),!this.aiGenerateBtn)return;let e=(u=(d=(p=this.aiKeyInput)==null?void 0:p.value)==null?void 0:d.trim())!=null?u:"",t=(h=(g=this.aiModelSelect)==null?void 0:g.value)!=null?h:"gemini-2.5-flash-image",n=(b=(m=(f=this.aiPromptInput)==null?void 0:f.value)==null?void 0:m.trim())!=null?b:"",a=(v=(y=this.aiRemoveBgToggle)==null?void 0:y.checked)!=null?v:!1,s=a,r=a,o=Number((E=(x=this.aiStrengthInput)==null?void 0:x.value)!=null?E:"5");if(!e){this.setAiStatus("Missing API key.");return}if(!n){this.setAiStatus("Add a prompt.");return}let l=this.getSelectedAssetInput(),c=((w=l==null?void 0:l.value)==null?void 0:w.trim())||((T=this.aiBaseValue)==null?void 0:T.trim())||"";if(!c&&!this.aiOutputDataUrl){this.setAiStatus("Select an asset first.");return}this.setAiLoading(!0),this.setAiStatus("Generating...");try{let k=null,D=(S=this.getSelectedAssetKey())!=null?S:"unknown",R=(O=this.aiUseOutputToggle)!=null&&O.checked&&this.aiOutputDataUrl?"ai-output":"asset-value";if((B=this.aiUseOutputToggle)!=null&&B.checked&&this.aiOutputDataUrl){let ie=Ri(this.aiOutputDataUrl,"ai-output.png");if(ie){let ae=await Te(ie);ae&&(k={input:{base64:ae.base64,mimeType:ae.mimeType},dataUrl:ae.dataUrl,width:ae.width,height:ae.height})}}if(k||(k=await this.getImageDataFromAsset(c)),!k){this.setAiStatus("Unable to load the base image.");return}let $=[k.input],A=!1;if(this.aiReferenceFile){let ie=await Te(this.aiReferenceFile);ie?($.push({base64:ie.base64,mimeType:ie.mimeType}),A=!0,this.setAiStatus(`Generating with reference: ${this.aiReferenceFile.name}`)):this.setAiStatus("Reference image failed to load, generating without reference.")}let _=Bs(n,{includeReference:A,includeMagenta:s,changeLevel:o}),P=(C=(M=this.aiReferenceFile)==null?void 0:M.name)!=null?C:"none";console.info("[AI] Final prompt:",_),console.info("[AI] Image sources:",{assetKey:D,base:R,reference:P});let q=Ps(k.width,k.height);console.info("[AI] CRITICAL: Calling generateImageWithGemini25Flash NOW...");let V=await et(e,_,$,{aspectRatio:q,model:t});console.info("[AI] CRITICAL: generateImageWithGemini25Flash returned! Length:",V==null?void 0:V.length),this.aiRawOutputDataUrl=V,await this.refreshAiOutputFromRaw()}catch(k){console.error("[CustomizePanel] AI Generate Error:",k),this.setAiStatus("Generation failed. Check console.")}finally{this.setAiLoading(!1),((I=this.aiStatusEl)==null?void 0:I.textContent)==="Generating..."&&this.setAiStatus("Ready.")}}async refreshAiOutputFromRaw(){var a,s,r,o;if(!this.aiRawOutputDataUrl)return;let e=(s=(a=this.aiRemoveBgToggle)==null?void 0:a.checked)!=null?s:!1,t=Number((o=(r=this.aiBgToleranceInput)==null?void 0:r.value)!=null?o:"30"),n=this.aiRawOutputDataUrl;if(e){let l=await Qe(this.aiRawOutputDataUrl,t);l&&(n=l)}this.setAiOutput(n),this.setAiStatus("Ready.")}setAiOutput(e){var n,a;this.aiOutputDataUrl=e,this.aiOutputKey=this.getSelectedAssetKey(),this.updateAiPreview(),this.setAiOutputButtonsEnabled(!0);let t=(n=this.previewModal)==null?void 0:n.querySelector("[data-asset-ai-preview]");this.updateAiModalPreview(t,(a=this.activePreviewKey)!=null?a:void 0)}setAiOutputButtonsEnabled(e){this.aiApplyBtn&&(this.aiApplyBtn.disabled=!e),this.aiSaveLibraryBtn&&(this.aiSaveLibraryBtn.disabled=!e),this.aiCropBtn&&(this.aiCropBtn.disabled=!e),this.aiDownloadBtn&&(this.aiDownloadBtn.disabled=!e)}handleAiApply(){var t,n,a;let e=this.getSelectedAssetInput();if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}if(e)console.log("[CustomizePanel] Applying AI output to brand asset:",e.dataset.assetKey),e.value=this.aiOutputDataUrl,this.handleAssetValueChange((t=e.dataset.assetKey)!=null?t:"",e),this.setAiStatus("Applied. Restarting game...");else{let s=((n=this.aiContext)==null?void 0:n.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),r=((a=this.aiContext)==null?void 0:a.path)||this.inferPathFromAssetKey(this.aiTargetKey||"");if(s&&r)console.log("[CustomizePanel] Applying AI output directly to object:",s,r),this.applyObjectPropertyValue(s,r,this.aiOutputDataUrl),this.setAiStatus("Applied directly. Restarting game..."),window.dispatchEvent(new CustomEvent("inspector:refresh"));else{this.setAiStatus("No target input found to apply.");return}}setTimeout(()=>{this.closeAiModal()},500)}async handleAiSaveToLibrary(){var s,r,o;if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}if(!this.getSelectedAssetKey()){this.setAiStatus("No asset selected.");return}let n=`${(this.aiTargetKey||"asset").replace(/[^a-zA-Z0-9_-]/g,"_")}_ai_${Date.now()}`,a=this.inferCategoryFromAssetKey(this.aiTargetKey||"");this.setAiStatus("Saving to library...");try{let c=await(await fetch("/api/library/save",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({category:a,filename:`${n}.png`,data:this.aiOutputDataUrl,overwrite:!0})})).json();if(c.success){console.log("[CustomizePanel] \u2705 Saved to library:",c.path),this.setAiStatus(`Saved as ${n}. Applying...`);let p=window.addAssetToRegistry;typeof p=="function"&&(console.log("[CustomizePanel] Logic: Adding to registry category:",a),p(a,`${n}.png`));let d=window.refreshAssetLibrary;typeof d=="function"&&(console.log("[CustomizePanel] Logic: Refreshing library panel"),d());let u=((s=this.aiContext)==null?void 0:s.objectId)||this.inferObjectIdFromAssetKey(this.aiTargetKey||""),g=((r=this.aiContext)==null?void 0:r.path)||this.inferPathFromAssetKey(this.aiTargetKey||""),h=this.getSelectedAssetInput();if(h&&(h.value=c.path,this.handleAssetValueChange((o=h.dataset.assetKey)!=null?o:"",h)),u&&g){console.log("[CustomizePanel] Saved and applying directly to object:",u,g);let f=window.applyAssetToSlot,m=/texture|image|sprite|asset\\.path/i.test(g)||/\\.(png|jpg|jpeg)$/i.test(String(c.path||""));if(typeof f=="function"&&m){let b=this.getFilenameFromPath(c.path);f(u,b,a)}else this.applyObjectPropertyValue(u,g,c.path);window.dispatchEvent(new CustomEvent("inspector:refresh"))}setTimeout(()=>{this.closeAiModal()},1e3)}else console.error("[CustomizePanel] \u274C Save failed:",c.error),this.setAiStatus(`Save failed: ${c.error}`)}catch(l){console.error("[CustomizePanel] \u274C Save error:",l),this.setAiStatus("Save failed. Check console.")}}inferCategoryFromAssetKey(e){var r;let t=(r=this.aiContext)==null?void 0:r.objectId,n=e||this.aiTargetKey||"",a=window.getEditableAssets;if(typeof a=="function"){let o=a();if(o!=null&&o.slots){let l=o.slots.find(c=>t&&c.objectId===t||c.currentAsset===n||c.slotId===n||c.currentAsset&&c.currentAsset.includes(n)||n.includes(c.slotId));if(l){let c=l.libraryFolder||l.category;if(c)return c}}}let s=n.toLowerCase();return s.includes("background")?"backgrounds":s.includes("character")?"characters":s.includes("key")?"collectedkeys":s.includes("draggable")?"draggables":s.includes("environment")||s.includes("env")||s.includes("hand")||s.includes("prop")||s.includes("item")||s.includes("decor")||s.includes("object")?"environment":s.includes("machine")?"machines":s.includes("tutorial")?"tutorial":s.includes("ui")||s.includes("button")||s.includes("label")||s.includes("icon")||s.includes("logo")||s.includes("cta")||s.includes("menu")||s.includes("overlay")?"ui":s.includes("effect")||s.includes("confetti")||s.includes("particle")?"effects":"ui"}inferObjectIdFromAssetKey(e){let t=window.getEditableAssets;if(typeof t!="function")return null;let n=t();if(!(n!=null&&n.slots))return null;let a=n.slots.find(s=>s.currentAsset===e||s.slotId===e);return(a==null?void 0:a.objectId)||null}inferPathFromAssetKey(e){let t=window.getEditableAssets;if(typeof t!="function")return null;let n=t();if(!(n!=null&&n.slots))return null;let a=n.slots.find(r=>r.currentAsset===e||r.slotId===e);if(!a)return null;let s=a.category;return s==="render"||s==="backgrounds"||s==="characters"?"render.texture":s==="ui"?"ui.image":s==="audio"?"audio.src":"render.texture"}getFilenameFromPath(e){if(!e)return"";let t=e.split("/");return t[t.length-1]}async handleAiCrop(){var o;if(!this.aiOutputDataUrl){this.setAiStatus("Generate output first.");return}let e=this.getSelectedAssetInput(),t=(o=e==null?void 0:e.value)!=null?o:"",n=await this.getImageDimensions(t);if(!n){this.setAiStatus("Unable to read target dimensions.");return}let a=Ri(this.aiOutputDataUrl,"ai-output.png");if(!a)return;let s=await this.showManualCropModal(a,n,t);if(!s)return;let r=await _s(s);r&&this.setAiOutput(r)}handleAiDownload(){var n;if(!this.aiOutputDataUrl)return;let e=(n=this.getSelectedAssetKey())!=null?n:"ai-image",t=document.createElement("a");t.href=this.aiOutputDataUrl,t.download=`${e}-ai.png`,t.click()}handleAssetValueChange(e,t){this.previewModal&&this.closePreviewModal(),this.scheduleAutoApply(),this.updatePreviewIfOpen(e,t.value,t.dataset.assetType)}async handleAssetUpload(e,t,n){let a=t.value,s=e;if(e.type.startsWith("image/")){let l=await this.getImageDimensions(a);if(l){let c=await this.showManualCropModal(e,l,a);if(!c)return;s=c}}let r=URL.createObjectURL(s),o=t.dataset.objectUrl;if(o)try{URL.revokeObjectURL(o)}catch{}t.dataset.objectUrl=r,t.dataset.assetType=s.type,t.value=r,this.handleAssetValueChange(n,t)}scheduleAutoApply(){this.options&&(this.autoApplyTimer&&window.clearTimeout(this.autoApplyTimer),console.log("[CustomizePanel] Scheduling auto-apply in 250ms"),this.autoApplyTimer=window.setTimeout(()=>{this.autoApplyTimer=null,console.log("[CustomizePanel] Executing auto-apply now"),this.handleApplyWithSource("auto")},250))}previewAsset(e,t,n,a){if(!t)return;let s=this.resolveAssetUrls(t);if(s.length===0)return;let r=n||this.guessMimeType(t);this.activePreviewKey=e,this.activePreviewValue=t,this.activePreviewFileInput=a!=null?a:null,this.openPreviewModal(e,t,s,r)}resolveAssetUrls(e){let t=e.trim();if(!t)return[];if(console.log("[CustomizePanel] Resolving asset urls for:",t),/^(blob:|data:|https?:|\/)/.test(t))return console.log("[CustomizePanel] Path is absolute or data/blob, using as is"),[t];let n=t.replace(/^\.?\//,""),a=[];return n.startsWith("raw/")?a=[`/${n}`,`/assets/${n}`]:n.startsWith("assets/")?a=[`/${n}`]:a=[`/raw/${n}`,`/assets/raw/${n}`,`/assets/${n}`,`/${n}`],console.log("[CustomizePanel] Resolved to possible paths:",a),a}guessMimeType(e){let t=e.toLowerCase();return t.endsWith(".png")||t.endsWith(".jpg")||t.endsWith(".jpeg")||t.endsWith(".gif")||t.endsWith(".webp")||t.endsWith(".svg")?"image":t.endsWith(".mp3")||t.endsWith(".wav")||t.endsWith(".ogg")?"audio":t.endsWith(".json")?"json":"file"}openPreviewModal(e,t,n,a){this.closePreviewModal(!0);let s=document.createElement("div");s.className="asset-preview-modal",s.innerHTML=`
936
838
  <div class="asset-preview-card">
937
839
  <div class="asset-preview-header">
938
- <div class="asset-preview-title">${t}</div>
840
+ <div class="asset-preview-title">${e}</div>
939
841
  <div class="asset-preview-actions">
940
842
  <button class="asset-preview-change" type="button">Change</button>
941
843
  <button class="asset-preview-ai" type="button">AI Edit</button>
@@ -948,12 +850,12 @@ Generate the requested asset matching the brand style.${e.needsTransparency?" Ba
948
850
  <img class="asset-preview-ai-image" alt="AI output preview">
949
851
  </div>
950
852
  </div>
951
- `;let s=a.querySelector(".asset-preview-body"),o=a.querySelector(".asset-preview-close"),l=a.querySelector(".asset-preview-change"),c=a.querySelector(".asset-preview-ai"),d=a.querySelector("[data-asset-ai-preview]");if(o==null||o.addEventListener("click",()=>this.closePreviewModal()),c==null||c.addEventListener("click",()=>{console.log("[CustomizePanel] AI Edit clicked for:",t),this.openAiModal(t,i)}),l==null||l.addEventListener("click",()=>{console.log("[CustomizePanel] Change clicked for:",t),this.activePreviewFileInput&&this.activePreviewFileInput.click()}),a.addEventListener("click",u=>{u.target===a&&this.closePreviewModal()}),s)if(r==="image"){let u=document.createElement("img");this.loadWithFallback(u,n),s.appendChild(u)}else if(r==="audio"){let u=document.createElement("audio");u.controls=!0,this.loadWithFallback(u,n),s.appendChild(u)}else if(r==="json"){let u=document.createElement("pre");this.fetchWithFallback(n).then(p=>{u.textContent=p!=null?p:"Unable to load JSON."}),s.appendChild(u)}else{let u=document.createElement("a");u.href=n[0],u.target="_blank",u.rel="noreferrer",u.textContent="Open asset",s.appendChild(u)}document.body.appendChild(a),this.previewModal=a,this.updateAiModalPreview(d,t)}loadWithFallback(t,i){if(i.length===0)return;let n=0,r=()=>{n>=i.length||(t.src=i[n],n+=1)};t.addEventListener("error",r),r()}async fetchWithFallback(t){for(let i of t)try{let n=await fetch(i);if(!n.ok)continue;return await n.text()}catch{}return null}applyObjectPropertyValue(t,i,n){let r=window.getEditableObjectConfig,a=window.applyEditableObjectConfig;if(typeof r!="function"||typeof a!="function")return;let s=r(t);if(!s)return;let o=JSON.parse(JSON.stringify(s)),l=i.split("."),c=o;for(let d=0;d<l.length-1;d++){let u=l[d];c[u]=c[u]||{},c=c[u]}c[l[l.length-1]]=n,a(t,o)}applyTextColorToObject(t,i){let r={warning_text_color:{objectId:"label.warning",property:"render.tint"},endgame_title_color:{objectId:"ui.endgame.title",property:"render.tint"},endgame_subtitle_color:{objectId:"ui.endgame.subtitle",property:"render.tint"},endgame_cta_text_color:{objectId:"ui.endgame.cta",property:"render.tint"},endgame_cta_hint_color:{objectId:"ui.endgame.cta.hint",property:"render.tint"},endgame_footer_color:{objectId:"ui.endgame.footer",property:"render.tint"}}[t];r&&this.applyObjectPropertyValue(r.objectId,r.property,i)}closePreviewModal(t){this.previewModal&&(this.previewModal.remove(),this.previewModal=null),t||(this.activePreviewKey=null,this.activePreviewValue=null,this.activePreviewFileInput=null)}updatePreviewIfOpen(t,i,n){var a;if(!this.previewModal||this.activePreviewKey!==t)return;let r=i!=null?i:"";this.activePreviewValue!==r&&this.previewAsset(t,r,n,(a=this.activePreviewFileInput)!=null?a:void 0)}scheduleRetry(){this.retryTimer||(this.retryTimer=window.setTimeout(()=>{this.retryTimer=null,this.refresh()},350))}clearRetry(){this.retryTimer&&(window.clearTimeout(this.retryTimer),this.retryTimer=null)}setupResizeHandle(){if(!this.root)return;let t=this.root.querySelector("[data-panel-resize]");if(!t)return;let i=window.localStorage.getItem("customizePanelWidth"),n=i?Number(i):NaN;Number.isFinite(n)&&n>0&&(this.root.style.width=`${n}px`);let r=a=>{var p,f;a.preventDefault();let s=a.clientX,o=(f=(p=this.root)==null?void 0:p.getBoundingClientRect().width)!=null?f:0,l=260,c=620,d=g=>{let h=g.clientX-s,m=Math.min(c,Math.max(l,o+h));this.root&&(this.root.style.width=`${m}px`)},u=()=>{var h,m;window.removeEventListener("pointermove",d),window.removeEventListener("pointerup",u);let g=(m=(h=this.root)==null?void 0:h.getBoundingClientRect().width)!=null?m:0;g>0&&window.localStorage.setItem("customizePanelWidth",String(Math.round(g)))};window.addEventListener("pointermove",d),window.addEventListener("pointerup",u)};t.addEventListener("pointerdown",r)}async getImageDimensions(t){let i=this.resolveAssetUrls(t);if(i.length===0)return null;for(let n of i){let r=await this.loadImage(n);if(r!=null&&r.naturalWidth&&(r!=null&&r.naturalHeight))return{width:r.naturalWidth,height:r.naturalHeight}}return null}async loadImage(t){return await new Promise(i=>{let n=new Image;n.onload=()=>i(n),n.onerror=()=>i(null),n.src=t})}async showManualCropModal(t,i,n){let r=i.width/i.height,a=URL.createObjectURL(t),s=await this.loadImage(a);try{URL.revokeObjectURL(a)}catch{}if(!(s!=null&&s.naturalWidth)||!(s!=null&&s.naturalHeight))return null;let o=await this.loadImageForValue(n);return await new Promise(l=>{let c=document.createElement("div");c.className="asset-crop-modal";let d=Math.min(860,window.innerWidth-60),g=Math.max(220,Math.floor((d-32-16)/2)),h=Math.min(520,window.innerHeight-240),m=g,b=m/r;b>h&&(b=h,m=b*r),c.innerHTML=`
952
- <div class="asset-crop-card" style="width:${d}px;">
853
+ `;let r=s.querySelector(".asset-preview-body"),o=s.querySelector(".asset-preview-close"),l=s.querySelector(".asset-preview-change"),c=s.querySelector(".asset-preview-ai"),p=s.querySelector("[data-asset-ai-preview]");if(o==null||o.addEventListener("click",()=>this.closePreviewModal()),c==null||c.addEventListener("click",()=>{console.log("[CustomizePanel] AI Edit clicked for:",e),this.openAiModal(e,t)}),l==null||l.addEventListener("click",()=>{console.log("[CustomizePanel] Change clicked for:",e),this.activePreviewFileInput&&this.activePreviewFileInput.click()}),s.addEventListener("click",d=>{d.target===s&&this.closePreviewModal()}),r)if(a==="image"){let d=document.createElement("img");this.loadWithFallback(d,n),r.appendChild(d)}else if(a==="audio"){let d=document.createElement("audio");d.controls=!0,this.loadWithFallback(d,n),r.appendChild(d)}else if(a==="json"){let d=document.createElement("pre");this.fetchWithFallback(n).then(u=>{d.textContent=u!=null?u:"Unable to load JSON."}),r.appendChild(d)}else{let d=document.createElement("a");d.href=n[0],d.target="_blank",d.rel="noreferrer",d.textContent="Open asset",r.appendChild(d)}document.body.appendChild(s),this.previewModal=s,this.updateAiModalPreview(p,e)}loadWithFallback(e,t){if(t.length===0)return;let n=0,a=()=>{n>=t.length||(e.src=t[n],n+=1)};e.addEventListener("error",a),a()}async fetchWithFallback(e){for(let t of e)try{let n=await fetch(t);if(!n.ok)continue;return await n.text()}catch{}return null}applyObjectPropertyValue(e,t,n){let a=window.getEditableObjectConfig,s=window.applyEditableObjectConfig;if(typeof a!="function"||typeof s!="function")return;let r=a(e);if(!r)return;let o=JSON.parse(JSON.stringify(r)),l=t.split("."),c=o;for(let p=0;p<l.length-1;p++){let d=l[p];c[d]=c[d]||{},c=c[d]}c[l[l.length-1]]=n,s(e,o)}applyTextColorToObject(e,t){let a={warning_text_color:{objectId:"label.warning",property:"render.tint"},endgame_title_color:{objectId:"ui.endgame.title",property:"render.tint"},endgame_subtitle_color:{objectId:"ui.endgame.subtitle",property:"render.tint"},endgame_cta_text_color:{objectId:"ui.endgame.cta",property:"render.tint"},endgame_cta_hint_color:{objectId:"ui.endgame.cta.hint",property:"render.tint"},endgame_footer_color:{objectId:"ui.endgame.footer",property:"render.tint"}}[e];a&&this.applyObjectPropertyValue(a.objectId,a.property,t)}closePreviewModal(e){this.previewModal&&(this.previewModal.remove(),this.previewModal=null),e||(this.activePreviewKey=null,this.activePreviewValue=null,this.activePreviewFileInput=null)}updatePreviewIfOpen(e,t,n){var s;if(!this.previewModal||this.activePreviewKey!==e)return;let a=t!=null?t:"";this.activePreviewValue!==a&&this.previewAsset(e,a,n,(s=this.activePreviewFileInput)!=null?s:void 0)}scheduleRetry(){this.retryTimer||(this.retryTimer=window.setTimeout(()=>{this.retryTimer=null,this.refresh()},350))}clearRetry(){this.retryTimer&&(window.clearTimeout(this.retryTimer),this.retryTimer=null)}setupResizeHandle(){if(!this.root)return;let e=this.root.querySelector("[data-panel-resize]");if(!e)return;let t=window.localStorage.getItem("customizePanelWidth"),n=t?Number(t):NaN;Number.isFinite(n)&&n>0&&(this.root.style.width=`${n}px`);let a=s=>{var u,g;s.preventDefault();let r=s.clientX,o=(g=(u=this.root)==null?void 0:u.getBoundingClientRect().width)!=null?g:0,l=260,c=620,p=h=>{let f=h.clientX-r,m=Math.min(c,Math.max(l,o+f));this.root&&(this.root.style.width=`${m}px`)},d=()=>{var f,m;window.removeEventListener("pointermove",p),window.removeEventListener("pointerup",d);let h=(m=(f=this.root)==null?void 0:f.getBoundingClientRect().width)!=null?m:0;h>0&&window.localStorage.setItem("customizePanelWidth",String(Math.round(h)))};window.addEventListener("pointermove",p),window.addEventListener("pointerup",d)};e.addEventListener("pointerdown",a)}async getImageDimensions(e){let t=this.resolveAssetUrls(e);if(t.length===0)return null;for(let n of t){let a=await this.loadImage(n);if(a!=null&&a.naturalWidth&&(a!=null&&a.naturalHeight))return{width:a.naturalWidth,height:a.naturalHeight}}return null}async loadImage(e){return await new Promise(t=>{let n=new Image;n.onload=()=>t(n),n.onerror=()=>t(null),n.src=e})}async showManualCropModal(e,t,n){let a=t.width/t.height,s=URL.createObjectURL(e),r=await this.loadImage(s);try{URL.revokeObjectURL(s)}catch{}if(!(r!=null&&r.naturalWidth)||!(r!=null&&r.naturalHeight))return null;let o=await this.loadImageForValue(n);return await new Promise(l=>{let c=document.createElement("div");c.className="asset-crop-modal";let p=Math.min(860,window.innerWidth-60),h=Math.max(220,Math.floor((p-32-16)/2)),f=Math.min(520,window.innerHeight-240),m=h,b=m/a;b>f&&(b=f,m=b*a),c.innerHTML=`
854
+ <div class="asset-crop-card" style="width:${p}px;">
953
855
  <div class="asset-crop-header">
954
856
  <div>
955
857
  <div class="asset-crop-title">Crop to match current asset</div>
956
- <div class="asset-crop-subtitle">${i.width}\xD7${i.height}px \u2022 ${r.toFixed(3)} ratio</div>
858
+ <div class="asset-crop-subtitle">${t.width}\xD7${t.height}px \u2022 ${a.toFixed(3)} ratio</div>
957
859
  </div>
958
860
  <button class="asset-crop-close" type="button">Close</button>
959
861
  </div>
@@ -978,7 +880,7 @@ Generate the requested asset matching the brand style.${e.needsTransparency?" Ba
978
880
  <button class="asset-crop-apply" type="button">Apply Crop</button>
979
881
  </div>
980
882
  </div>
981
- `;let y=c.querySelector(".asset-crop-canvas"),v=c.querySelector(".asset-crop-preview"),x=c.querySelector(".asset-crop-zoom"),w=c.querySelector(".asset-crop-zoom-value"),E=c.querySelector(".asset-crop-close"),A=c.querySelector(".asset-crop-cancel"),_=c.querySelector(".asset-crop-apply"),T=c.querySelector(".asset-crop-reset");if(!y||!v||!x||!w){l(null);return}let P=y.getContext("2d"),S=v.getContext("2d");if(!P||!S){l(null);return}let L=s.naturalWidth,z=s.naturalHeight,D=Math.max(y.width/L,y.height/z),B=1,O=0,R=0,C=!1,I=0,j=0,Q=0,se=0,Re=()=>{let H=D*B,Dt=Math.max(0,(L*H-y.width)/2),oi=Math.max(0,(z*H-y.height)/2);O=Math.min(Dt,Math.max(-Dt,O)),R=Math.min(oi,Math.max(-oi,R))},je=()=>{let H=D*B;P.clearRect(0,0,y.width,y.height);let Dt=y.width/2-L*H/2+O,oi=y.height/2-z*H/2+R;if(P.drawImage(s,Dt,oi,L*H,z*H),S.clearRect(0,0,v.width,v.height),o!=null&&o.naturalWidth&&(o!=null&&o.naturalHeight)){let ci=Math.max(v.width/o.naturalWidth,v.height/o.naturalHeight),ms=v.width/2-o.naturalWidth*ci/2,rn=v.height/2-o.naturalHeight*ci/2;S.drawImage(o,ms,rn,o.naturalWidth*ci,o.naturalHeight*ci)}else S.fillStyle="rgba(255, 255, 255, 0.04)",S.fillRect(0,0,v.width,v.height),S.strokeStyle="rgba(255, 255, 255, 0.08)",S.strokeRect(4,4,v.width-8,v.height-8);let nn=v.width/y.width*(D*B),li=O*(v.width/y.width),fr=R*(v.height/y.height),hs=v.width/2-L*nn/2+li,gs=v.height/2-z*nn/2+fr;S.save(),S.globalAlpha=.7,S.drawImage(s,hs,gs,L*nn,z*nn),S.restore()},Lc=()=>{O=0,R=0,Re(),je()};x.addEventListener("input",()=>{B=Number(x.value),w.textContent=`${B.toFixed(2)}\xD7`,Re(),je()}),y.addEventListener("pointerdown",H=>{C=!0,I=H.clientX,j=H.clientY,Q=O,se=R,y.setPointerCapture(H.pointerId)}),y.addEventListener("pointermove",H=>{C&&(O=Q+(H.clientX-I),R=se+(H.clientY-j),Re(),je())}),y.addEventListener("pointerup",H=>{C=!1,y.releasePointerCapture(H.pointerId)}),y.addEventListener("pointerleave",()=>{C=!1});let ps=()=>{c.remove()},fs=()=>{ps(),l(null)},Kg=async()=>{let H=document.createElement("canvas");H.width=i.width,H.height=i.height;let Dt=H.getContext("2d");if(!Dt){ps(),l(null);return}let oi=B,li=Math.max(H.width/L,H.height/z)*oi,fr=H.width/y.width,hs=O*fr,gs=R*fr,ci=H.width/2-L*li/2+hs,ms=H.height/2-z*li/2+gs;Dt.drawImage(s,ci,ms,L*li,z*li);let rn=await new Promise(Xg=>{H.toBlob(Zg=>Xg(Zg),t.type||"image/png")});if(ps(),!rn){l(null);return}l(new File([rn],t.name,{type:rn.type}))};E==null||E.addEventListener("click",fs),A==null||A.addEventListener("click",fs),T==null||T.addEventListener("click",Lc),_==null||_.addEventListener("click",()=>{Kg()}),c.addEventListener("click",H=>{H.target===c&&fs()}),document.body.appendChild(c),Lc()})}async loadImageForValue(t){let i=this.resolveAssetUrls(t);if(!i.length)return null;for(let n of i){let r=await this.loadImage(n);if(r)return r}return null}};var Ka=class{constructor(){this.root=null;this.options=null}render(){return`
883
+ `;let y=c.querySelector(".asset-crop-canvas"),v=c.querySelector(".asset-crop-preview"),x=c.querySelector(".asset-crop-zoom"),E=c.querySelector(".asset-crop-zoom-value"),w=c.querySelector(".asset-crop-close"),T=c.querySelector(".asset-crop-cancel"),S=c.querySelector(".asset-crop-apply"),O=c.querySelector(".asset-crop-reset");if(!y||!v||!x||!E){l(null);return}let B=y.getContext("2d"),M=v.getContext("2d");if(!B||!M){l(null);return}let C=r.naturalWidth,I=r.naturalHeight,k=Math.max(y.width/C,y.height/I),D=1,R=0,$=0,A=!1,_=0,P=0,q=0,V=0,ie=()=>{let j=k*D,ke=Math.max(0,(C*j-y.width)/2),Fe=Math.max(0,(I*j-y.height)/2);R=Math.min(ke,Math.max(-ke,R)),$=Math.min(Fe,Math.max(-Fe,$))},ae=()=>{let j=k*D;B.clearRect(0,0,y.width,y.height);let ke=y.width/2-C*j/2+R,Fe=y.height/2-I*j/2+$;if(B.drawImage(r,ke,Fe,C*j,I*j),M.clearRect(0,0,v.width,v.height),o!=null&&o.naturalWidth&&(o!=null&&o.naturalHeight)){let Ue=Math.max(v.width/o.naturalWidth,v.height/o.naturalHeight),Zn=v.width/2-o.naturalWidth*Ue/2,ut=v.height/2-o.naturalHeight*Ue/2;M.drawImage(o,Zn,ut,o.naturalWidth*Ue,o.naturalHeight*Ue)}else M.fillStyle="rgba(255, 255, 255, 0.04)",M.fillRect(0,0,v.width,v.height),M.strokeStyle="rgba(255, 255, 255, 0.08)",M.strokeRect(4,4,v.width-8,v.height-8);let pt=v.width/y.width*(k*D),Ge=R*(v.width/y.width),Nt=$*(v.height/y.height),Xn=v.width/2-C*pt/2+Ge,Jn=v.height/2-I*pt/2+Nt;M.save(),M.globalAlpha=.7,M.drawImage(r,Xn,Jn,C*pt,I*pt),M.restore()},Sa=()=>{R=0,$=0,ie(),ae()};x.addEventListener("input",()=>{D=Number(x.value),E.textContent=`${D.toFixed(2)}\xD7`,ie(),ae()}),y.addEventListener("pointerdown",j=>{A=!0,_=j.clientX,P=j.clientY,q=R,V=$,y.setPointerCapture(j.pointerId)}),y.addEventListener("pointermove",j=>{A&&(R=q+(j.clientX-_),$=V+(j.clientY-P),ie(),ae())}),y.addEventListener("pointerup",j=>{A=!1,y.releasePointerCapture(j.pointerId)}),y.addEventListener("pointerleave",()=>{A=!1});let Yn=()=>{c.remove()},Kn=()=>{Yn(),l(null)},kr=async()=>{let j=document.createElement("canvas");j.width=t.width,j.height=t.height;let ke=j.getContext("2d");if(!ke){Yn(),l(null);return}let Fe=D,Ge=Math.max(j.width/C,j.height/I)*Fe,Nt=j.width/y.width,Xn=R*Nt,Jn=$*Nt,Ue=j.width/2-C*Ge/2+Xn,Zn=j.height/2-I*Ge/2+Jn;ke.drawImage(r,Ue,Zn,C*Ge,I*Ge);let ut=await new Promise(Or=>{j.toBlob(Ir=>Or(Ir),e.type||"image/png")});if(Yn(),!ut){l(null);return}l(new File([ut],e.name,{type:ut.type}))};w==null||w.addEventListener("click",Kn),T==null||T.addEventListener("click",Kn),O==null||O.addEventListener("click",Sa),S==null||S.addEventListener("click",()=>{kr()}),c.addEventListener("click",j=>{j.target===c&&Kn()}),document.body.appendChild(c),Sa()})}async loadImageForValue(e){let t=this.resolveAssetUrls(e);if(!t.length)return null;for(let n of t){let a=await this.loadImage(n);if(a)return a}return null}};var kn=class{constructor(){this.root=null;this.options=null}render(){return`
982
884
  <div class="scene-panel loading-screen-panel panel-accent-purple" data-panel="loading-screen">
983
885
  <div class="scene-panel-header" data-panel-handle>
984
886
  <div class="panel-title">
@@ -1044,13 +946,13 @@ Generate the requested asset matching the brand style.${e.needsTransparency?" Ba
1044
946
  </div>
1045
947
  </div>
1046
948
  </div>
1047
- `}initialize(t,i){var y,v,x,w,E,A,_,T,P,S,L,z,D,B,O,R;this.options=i,this.root=t.querySelector('[data-panel="loading-screen"]');let r=(()=>{var I;let C=window.getEditableEngineConfig;if(typeof C=="function"){let j=C();return(I=j==null?void 0:j.loading)!=null?I:{}}return{}})(),a=(y=this.root)==null?void 0:y.querySelector("#loading-screen-type");a&&(a.value=r.type==="image"?"image":"color",a.addEventListener("change",()=>{var C,I;(I=(C=this.options)==null?void 0:C.onUpdateLoading)==null||I.call(C,{type:a.value}),this.updateFieldVisibility(a.value)}));let s=(v=this.root)==null?void 0:v.querySelector("#loading-background-color");s&&(s.value=r.background_color||"#160a17",s.addEventListener("input",()=>{var C,I;(I=(C=this.options)==null?void 0:C.onUpdateLoading)==null||I.call(C,{background_color:s.value})}));let o=(x=this.root)==null?void 0:x.querySelector("#loading-overlay-alpha"),l=(w=this.root)==null?void 0:w.querySelector("#loading-overlay-alpha-value");o&&(o.value=String((E=r.overlay_alpha)!=null?E:1),l&&(l.textContent=Number(o.value).toFixed(2)),o.addEventListener("input",()=>{var I,j;let C=Number(o.value);l&&(l.textContent=C.toFixed(2)),(j=(I=this.options)==null?void 0:I.onUpdateLoading)==null||j.call(I,{overlay_alpha:C})}));let c=(A=this.root)==null?void 0:A.querySelector("#loading-text");c&&(c.value=r.text||"",c.addEventListener("input",()=>{var C,I;(I=(C=this.options)==null?void 0:C.onUpdateLoading)==null||I.call(C,{text:c.value})}));let d=(_=this.root)==null?void 0:_.querySelector("#loading-text-scale"),u=(T=this.root)==null?void 0:T.querySelector("#loading-text-scale-value");d&&(d.value=String((P=r.text_scale)!=null?P:.6),u&&(u.textContent=Number(d.value).toFixed(2)),d.addEventListener("input",()=>{var I,j;let C=Number(d.value);u&&(u.textContent=C.toFixed(2)),(j=(I=this.options)==null?void 0:I.onUpdateLoading)==null||j.call(I,{text_scale:C})}));let p=(S=this.root)==null?void 0:S.querySelector("#loading-enabled");p&&(p.checked=r.enabled!==!1,p.addEventListener("change",()=>{var C,I;(I=(C=this.options)==null?void 0:C.onUpdateLoading)==null||I.call(C,{enabled:p.checked})}));let f=(L=this.root)==null?void 0:L.querySelector("#loading-blur-enabled");f&&(f.checked=r.blur_enabled!==!1,f.addEventListener("change",()=>{var C,I;(I=(C=this.options)==null?void 0:C.onUpdateLoading)==null||I.call(C,{blur_enabled:f.checked})}));let g=(z=this.root)==null?void 0:z.querySelector("#loading-blur-strength"),h=(D=this.root)==null?void 0:D.querySelector("#loading-blur-strength-value");g&&(g.value=String((B=r.blur_strength)!=null?B:8),h&&(h.textContent=g.value),g.addEventListener("input",()=>{var C,I;h&&(h.textContent=g.value),(I=(C=this.options)==null?void 0:C.onUpdateLoading)==null||I.call(C,{blur_strength:Number(g.value)})}));let m=(O=this.root)==null?void 0:O.querySelector("#loading-show-btn"),b=(R=this.root)==null?void 0:R.querySelector("#loading-hide-btn");m==null||m.addEventListener("click",()=>{var C,I;(I=(C=this.options)==null?void 0:C.onShowLoadingScreen)==null||I.call(C)}),b==null||b.addEventListener("click",()=>{var C,I;(I=(C=this.options)==null?void 0:C.onHideLoadingScreen)==null||I.call(C)}),this.updateFieldVisibility(r.type==="image"?"image":"color")}updateFieldVisibility(t){var r,a;let i=(r=this.root)==null?void 0:r.querySelector("#loading-color-field"),n=(a=this.root)==null?void 0:a.querySelector("#loading-alpha-field");t==="image"?(i&&(i.style.display="none"),n&&(n.style.display="none")):(i&&(i.style.display=""),n&&(n.style.display=""))}refresh(){}};var Qn=require("pixi.js");hi();Te();async function ag(e,t,i){var n,r;console.log("[LIBRARY] applyAssetChange called with:",t,i);try{let a=Date.now(),o=`/${`raw/library/${t}/${i}`}?t=${a}`;console.log("[LIBRARY] Loading texture from:",o);let l=await Qn.Assets.load(o);if(!l){console.error("[LIBRARY] Failed to load texture:",o);return}let c=window.CustomAssets,d=Object.keys(c||{}).filter(p=>{let f=t.replace(/s$/,"");return p.startsWith(f)||p.includes(f)});for(let p of d)ze[p]=l,console.log("[LIBRARY] \u2705 Updated AssetTextures."+p),(n=c[p])!=null&&n.texture&&(c[p].texture=l,console.log("[LIBRARY] \u2705 Updated CustomAssets."+p+".texture"));let u=window.gameObjectManager;if(u)for(let p of d){let f=u.get(p);if(f){let g=((r=f.getDisplayObject)==null?void 0:r.call(f))||f.pixiObject||f;g!=null&&g.texture&&(g.texture=l,console.log("[LIBRARY] \u2705 Applied to display object:",p))}}}catch(a){console.error("[LIBRARY] Error applying asset change:",a)}}async function sg(e,t){var i,n,r;console.log("[LIBRARY] resetAsset called for:",t);try{let a=window.getEditableAssets,s=typeof a=="function"?a():null,o=(i=s==null?void 0:s.slots)==null?void 0:i.find(m=>m.category===t),l=o==null?void 0:o.defaultAsset;if(!l){console.warn("[LIBRARY] Could not find default asset for:",t);return}let c=Date.now(),d=`/raw/${l}?t=${c}`;console.log("[LIBRARY] Loading default texture from:",d);let u=await Qn.Assets.load(d);if(!u){console.error("[LIBRARY] Failed to load default texture:",d);return}let p=window.CustomAssets,f=t.replace(/s$/,""),g=Object.keys(p||{}).filter(m=>m.startsWith(f)||m.includes(f));for(let m of g)ze[m]=u,console.log("[LIBRARY] \u2705 Reset AssetTextures."+m),(n=p[m])!=null&&n.texture&&(p[m].texture=u,console.log("[LIBRARY] \u2705 Reset CustomAssets."+m+" to default"));let h=window.gameObjectManager;if(h)for(let m of g){let b=h.get(m);if(b){let y=((r=b.getDisplayObject)==null?void 0:r.call(b))||b.pixiObject||b;y!=null&&y.texture&&(y.texture=u,console.log("[LIBRARY] \u2705 Reset display object:",m))}}}catch(a){console.error("[LIBRARY] Error resetting asset:",a)}}async function og(e,t,i,n){var r,a,s,o,l,c,d,u,p,f,g,h,m,b,y;console.log("[LIBRARY] applySlotAsset:",{objectId:t,assetFilename:i,category:n});try{let v=t.startsWith("json.")?t.replace("json.",""):t;console.log("[LIBRARY] Asset key:",v);let x=Date.now(),w=`/raw/library/${n}/${i}?t=${x}`;console.log("[LIBRARY] Loading texture from:",w);let E=await Qn.Assets.load(w);if(!E){console.error("[LIBRARY] Failed to load texture:",w);return}console.log("[LIBRARY] \u2705 Texture loaded"),ze[v]=E,console.log("[LIBRARY] \u2705 Updated AssetTextures."+v);let A=window.CustomAssets;A!=null&&A[v]&&(A[v].texture=E,console.log("[LIBRARY] \u2705 Updated legacy CustomAssets."+v));let _=window.gameObjectManager;if(console.log("[LIBRARY] gameObjectManager exists?",!!_),_){let P=Array.from(((r=_.keys)==null?void 0:r.call(_))||[]).slice(0,10);console.log("[LIBRARY] Available gameObject keys (first 10):",P);let S=_.get(v);if(console.log("[LIBRARY] gameObject for "+v+"?",!!S),S){let L=((a=S.getDisplayObject)==null?void 0:a.call(S))||S.pixiObject||S.pixi||S,z=(s=L==null?void 0:L.constructor)==null?void 0:s.name;if(console.log("[LIBRARY] displayObject:",L),console.log("[LIBRARY] displayObject type:",z),console.log("[LIBRARY] has texture?",!!(L!=null&&L.texture)),L!=null&&L.texture)L.texture=E,console.log("[LIBRARY] \u2705 Applied to display object:",v);else if(z==="Text"){console.log("[LIBRARY] \u{1F504} Converting Text to Sprite...");let{Sprite:D}=await import("pixi.js"),B=L.parent,O=(l=(o=B==null?void 0:B.getChildIndex)==null?void 0:o.call(B,L))!=null?l:0,R={x:L.x,y:L.y},C={x:(d=(c=L.anchor)==null?void 0:c.x)!=null?d:.5,y:(p=(u=L.anchor)==null?void 0:u.y)!=null?p:.5},I={x:(g=(f=L.scale)==null?void 0:f.x)!=null?g:1,y:(m=(h=L.scale)==null?void 0:h.y)!=null?m:1},j=(b=L.alpha)!=null?b:1,Q=(y=L.visible)!=null?y:!0,se=new D(E);se.anchor.set(C.x,C.y),se.position.set(R.x,R.y),se.scale.set(I.x,I.y),se.alpha=j,se.visible=Q,B&&(B.removeChild(L),B.addChildAt(se,O),console.log("[LIBRARY] \u2705 Replaced Text with Sprite in parent")),S.pixiObject&&(S.pixiObject=se),S.pixi&&(S.pixi=se),console.log("[LIBRARY] \u2705 Text \u2192 Sprite conversion complete")}else if(L!=null&&L.children){let D=L.children.find(B=>B.texture);D?(D.texture=E,console.log("[LIBRARY] \u2705 Applied to child sprite")):console.warn("[LIBRARY] \u26A0\uFE0F No texture found in displayObject or children")}}}let T=`raw/library/${n}/${i}`;bt({objectId:v,path:"render.asset.path",value:T}),console.log("[LIBRARY] \u2705 Staged config override for:",v,"path:",T)}catch(v){console.error("[LIBRARY] Error applying slot asset:",v)}}async function lg(e,t,i,n){var r;console.log("[LIBRARY] resetSlotAsset:",{objectId:t,defaultAsset:i,category:n});try{let a=t.startsWith("json.")?t.replace("json.",""):t,s=Date.now(),o=`/raw/${i}?t=${s}`;console.log("[LIBRARY] Loading default texture from:",o);let l=await Qn.Assets.load(o);if(!l){console.error("[LIBRARY] Failed to load default texture:",o);return}ze[a]=l,console.log("[LIBRARY] \u2705 Reset AssetTextures."+a);let c=window.CustomAssets;c!=null&&c[a]&&(c[a].texture=l,console.log("[LIBRARY] \u2705 Reset CustomAssets."+a+" to default"));let d=window.gameObjectManager;if(d){let u=d.get(a);if(u){let p=((r=u.getDisplayObject)==null?void 0:r.call(u))||u.pixiObject||u;p!=null&&p.texture&&(p.texture=l,console.log("[LIBRARY] \u2705 Reset display object:",a))}}bt({objectId:a,path:"render.asset.path",value:i}),console.log("[LIBRARY] \u2705 Reset config override for:",a)}catch(a){console.error("[LIBRARY] Error resetting slot asset:",a)}}var ir=require("pixi.js");var Ul=require("pixi.js"),Pt=()=>window.debugConfig||{},cg=()=>window.resolveAnchorVec2||(e=>({x:.5,y:.5})),dg=()=>window.resolveScreenAnchorPoint||(()=>new Ul.Point),ug=()=>window.resolveScreenRatioPoint||(()=>new Ul.Point);function pg(e){Xa(e)&&(e.objectDebugRaf||(e.objectDebugRaf=window.requestAnimationFrame(()=>Za(e))))}function fg(e){e.objectDebugRaf&&(window.cancelAnimationFrame(e.objectDebugRaf),e.objectDebugRaf=null),tr(e)}function Xa(e){return e.isDebugOpen}function Za(e){var a,s,o;if(!Xa(e)){e.objectDebugRaf=null;return}e.objectDebugRaf=window.requestAnimationFrame(()=>Za(e));let t=ql(e);if(!t){er(e,null),tr(e);return}let i=Gl(e,t);if(!i){er(e,null),tr(e);return}let n=new ir.Point;(a=i.getGlobalPosition)==null||a.call(i,n);let r=Wl(e,i);er(e,{instanceId:t,worldX:n.x,worldY:n.y,configX:(s=r==null?void 0:r.x)!=null?s:null,configY:(o=r==null?void 0:r.y)!=null?o:null}),e.highlightObject?Xl(e,i):Jl(e),e.highlightAnchor&&r?Zl(e,r):Ql(e)}function ql(e){var r;let t=e.selectedObjectId;if(!t)return null;let i=window.__editableObjectInstances,n=(r=i==null?void 0:i.get)==null?void 0:r.call(i,t);return Array.isArray(n)&&n.length>0?n[0]:t}function Gl(e,t){var r,a;let i=window.gameObjectManager,n=(r=i==null?void 0:i.get)==null?void 0:r.call(i,t);return n?((a=n.getDisplayObject)==null?void 0:a.call(n))||n.pixiObject||n:null}function nr(e){let t=e.selectedObjectId;if(!t)return null;let i=window.getEditableObjectConfig;return typeof i!="function"?null:i(t)}function Wl(e,t){var s,o;let i=nr(e);if(!i)return null;let n=(s=i.transform)!=null?s:{},r=Vl(e);if(!r)return null;if(n.position_ratio!=null)return ug()(r.width,r.height,n.position_ratio);let a=(o=n.anchor)!=null?o:"center";return dg()(r.width,r.height,a)}function Vl(e){var a;let t=(a=e.container)==null?void 0:a.querySelector(".game-container"),i=Number(t==null?void 0:t.dataset.screenWidth),n=Number(t==null?void 0:t.dataset.screenHeight);if(Number.isFinite(i)&&i>0&&Number.isFinite(n)&&n>0)return{width:i,height:n};let r=window.gameApp;return r!=null&&r.renderer?{width:r.renderer.width,height:r.renderer.height}:null}function Yl(e){let t=window.gameApp;return t!=null&&t.stage?(e.objectBoundsGfx&&e.objectBoundsGfx.parent!==t.stage&&(e.objectBoundsGfx.destroy(),e.objectBoundsGfx=null),e.objectBoundsGfx||(e.objectBoundsGfx=new ir.Graphics,e.objectBoundsGfx.zIndex=999999,t.stage.addChild(e.objectBoundsGfx)),e.objectBoundsGfx):null}function Kl(e){let t=window.gameApp;return t!=null&&t.stage?(e.objectAnchorGfx&&e.objectAnchorGfx.parent!==t.stage&&(e.objectAnchorGfx.destroy(),e.objectAnchorGfx=null),e.objectAnchorGfx||(e.objectAnchorGfx=new ir.Graphics,e.objectAnchorGfx.zIndex=1e6,t.stage.addChild(e.objectAnchorGfx)),e.objectAnchorGfx):null}function Xl(e,t){var r;let i=Yl(e);if(!i)return;let n=(r=t.getBounds)==null?void 0:r.call(t);n&&(i.clear(),i.rect(n.x,n.y,n.width,n.height).stroke({width:2,color:16726832,alpha:.9}))}function Zl(e,t){let i=Kl(e);if(!i)return;let n=6;i.clear(),i.moveTo(t.x-n,t.y),i.lineTo(t.x+n,t.y),i.moveTo(t.x,t.y-n),i.lineTo(t.x,t.y+n),i.stroke({width:2,color:3066993,alpha:.9})}function Jl(e){e.objectBoundsGfx&&e.objectBoundsGfx.clear()}function Ql(e){e.objectAnchorGfx&&e.objectAnchorGfx.clear()}function tr(e){e.objectBoundsGfx&&(e.objectBoundsGfx.destroy(),e.objectBoundsGfx=null),e.objectAnchorGfx&&(e.objectAnchorGfx.destroy(),e.objectAnchorGfx=null)}function er(e,t){e.sceneToolsPanel.updateInfo(t?{instanceId:t.instanceId,worldX:t.worldX,worldY:t.worldY,anchorX:t.configX,anchorY:t.configY}:null)}function hg(e,t){return t.split(".").reduce((i,n)=>i?i[n]:void 0,e)}function gg(e,t,i){var s;let n=t.split("."),r=n.pop(),a=e;for(let o of n)a[o]=(s=a[o])!=null?s:{},a=a[o];a[r]=i}function ec(e){var n,r,a,s,o;if(!e)return!1;if((n=e.transform)!=null&&n.offset)return!0;let t=((a=(r=e.identity)==null?void 0:r.category)!=null?a:"").toString().toLowerCase(),i=((o=(s=e.identity)==null?void 0:s.id)!=null?o:"").toString().toLowerCase();return t.includes("ui")||i.startsWith("ui")||i.includes("label")}function Qa(e){let t=Pt();t.layout&&(t.layout.scale_multiplier=1,t.layout.position_offset={x:0,y:0},t.layout.debug_rect_visible=!0,t.layout.debug_rect_color=16711680,t.layout.debug_rect_thickness=4),t.engine&&(t.engine.scale=1,t.engine.background_scale=1.05,t.engine.label_pulse_speed=3,t.engine.label_pulse_intensity=.03),t.physics&&(t.physics.rope_length=420),window.location.reload()}function mg(e){window.location.reload()}function es(e){let t=JSON.stringify(Pt(),null,2);navigator.clipboard.writeText(t).then(()=>{alert("Debug config copied to clipboard!")}).catch(()=>{console.log(t),alert("Config logged to console (clipboard not available)")})}async function bg(e,t){var i,n,r;if(!(!e.configViewer||!e.container))try{let a=window.getEditableObjectConfig,s=typeof a=="function"?a(t):null;if(!s){let{loadObjectCentricConfig:o,loadObjectConfig:l}=await Promise.resolve().then(()=>(zr(),kd)),u=(((i=(await o("scene.main")).scene)==null?void 0:i.objects)||[]).find(f=>f.object_config===t||f.instance_id===t);if(!u)return;let p=await l(u.object_config);console.log("[PREVIEW] Loaded object config (fallback)",t,p),Ja(e,p),(n=e.configViewer)==null||n.style.setProperty("display","block");return}console.log("[PREVIEW] Loaded object config",t,s),Ja(e,s),(r=e.configViewer)==null||r.style.setProperty("display","block");return}catch(a){console.error("[DEBUG] Failed to load object config:",a)}}function Ja(e,t){var u,p,f,g,h,m,b,y,v,x;if(!e.container)return;let i=e.container.querySelector("#config-pos-x"),n=e.container.querySelector("#config-pos-y"),r=e.container.querySelector("#config-scale"),a=e.container.querySelector("#config-anchor-x"),s=e.container.querySelector("#config-anchor-y"),l=ec(t)?(u=t.transform)==null?void 0:u.offset:(p=t.transform)==null?void 0:p.position;i&&(i.value=String((f=l==null?void 0:l.x)!=null?f:0)),n&&(n.value=String((g=l==null?void 0:l.y)!=null?g:0)),r&&(r.value=String((m=(h=t.transform)==null?void 0:h.scale)!=null?m:1));let c=(x=(v=(b=t.transform)==null?void 0:b.anchor)!=null?v:(y=t.render)==null?void 0:y.anchor)!=null?x:{x:.5,y:.5},d=cg()(c);a&&(a.value=String(d.x)),s&&(s.value=String(d.y))}function yg(e){var l,c,d,u,p,f,g,h,m,b;let t=e.selectedObjectId;if(!t||!e.container)return;let i=(c=(l=e.container.querySelector("#config-pos-x"))==null?void 0:l.value)!=null?c:"0",n=(u=(d=e.container.querySelector("#config-pos-y"))==null?void 0:d.value)!=null?u:"0",r=(f=(p=e.container.querySelector("#config-scale"))==null?void 0:p.value)!=null?f:"1",a=(h=(g=e.container.querySelector("#config-anchor-x"))==null?void 0:g.value)!=null?h:"0.5",s=(b=(m=e.container.querySelector("#config-anchor-y"))==null?void 0:m.value)!=null?b:"0.5",o=`${t}:
1048
- position: (${i}, ${n})
1049
- scale: ${r}
1050
- anchor: (${a}, ${s})`;navigator.clipboard.writeText(o).then(()=>console.log("[DEBUG] Config values copied to clipboard")).catch(y=>console.error("[DEBUG] Failed to copy config values:",y))}async function tc(e,t){var u,p,f,g,h,m,b,y,v,x,w;if(console.log("[INSPECTOR] \u{1F527} applyObjectConfig called"),!e.container)return;let i=e.selectedObjectId;if(!i){console.warn("[PREVIEW] Apply object config clicked with no selection");return}let n=Number((p=(u=e.container.querySelector("#config-pos-x"))==null?void 0:u.value)!=null?p:0),r=Number((g=(f=e.container.querySelector("#config-pos-y"))==null?void 0:f.value)!=null?g:0),a=Number((m=(h=e.container.querySelector("#config-scale"))==null?void 0:h.value)!=null?m:1),s=Number((y=(b=e.container.querySelector("#config-anchor-x"))==null?void 0:b.value)!=null?y:.5),o=Number((x=(v=e.container.querySelector("#config-anchor-y"))==null?void 0:v.value)!=null?x:.5);console.log("[INSPECTOR] Applying config for:",i,{posX:n,posY:r,scale:a,anchorX:s,anchorY:o});let{applyConfigOverride:l}=await Promise.resolve().then(()=>(Te(),Mr));l({objectId:i,path:"transform.position",value:{x:n,y:r}},{silent:t==null?void 0:t.silent}),l({objectId:i,path:"transform.scale",value:a},{silent:t==null?void 0:t.silent}),l({objectId:i,path:"transform.anchor",value:{x:s,y:o}},{silent:t==null?void 0:t.silent});let c=nr(e);ec(c)&&l({objectId:i,path:"transform.offset",value:{x:n,y:r}},{silent:!0}),console.log("[INSPECTOR] Calling applyEditableObjectConfig...");let d=window.applyEditableObjectConfig;if(typeof d=="function"){let E=(w=window.getEditableObjectConfig)==null?void 0:w.call(window,i);E?(console.log("[INSPECTOR] \u2705 Calling applyEditableObjectConfig for:",i),d(i,E)):console.warn("[INSPECTOR] \u26A0\uFE0F No config found for:",i)}else console.warn("[INSPECTOR] \u26A0\uFE0F applyEditableObjectConfig not available")}async function vg(e,t,i){let{applyConfigOverride:n}=await Promise.resolve().then(()=>(Te(),Mr));Object.entries(t.assets).forEach(([l,c])=>{n({path:`assets.${l}`,value:c},{silent:!0})}),Object.entries(t.runtime.theme).forEach(([l,c])=>{n({path:`runtime.theme.${l}`,value:c},{silent:!0})}),Object.entries(t.runtime.ui).forEach(([l,c])=>{n({path:`runtime.ui.${l}`,value:c},{silent:!0})}),Object.entries(t.runtime.fonts).forEach(([l,c])=>{n({path:`runtime.fonts.${l}`,value:c},{silent:!0})}),Object.entries(t.runtime.audio).forEach(([l,c])=>{n({path:`runtime.audio.${l}`,value:c},{silent:!0})});let r=window.applyEditableEngineConfig;if(typeof r=="function"){let l={theme:t.runtime.theme,fonts:t.runtime.fonts,audio:t.runtime.audio},c={};Object.entries(t.runtime.ui).forEach(([d,u])=>{var p;if(d)if(d.includes(".")){let f=d.split("."),g=c;for(let h=0;h<f.length-1;h++){let m=f[h];g[m]=(p=g[m])!=null?p:{},g=g[m]}g[f[f.length-1]]=u}else c[d]=u}),l.ui=c,r({runtime:l,assets:t.assets})}let a=Object.values(t.assets).some(l=>/^(blob:|data:)/.test(l)),s=(i==null?void 0:i.source)!=="auto"&&!a,o=window.__previewShell;s&&(o!=null&&o.refresh)&&o.refresh()}function xg(e){e.selectedObjectId&&(e.objectAutoApplyTimer&&window.clearTimeout(e.objectAutoApplyTimer),e.objectAutoApplyTimer=window.setTimeout(()=>{e.objectAutoApplyTimer=null,tc(e,{silent:!0})},150))}var $w=3e3;function wg(e,t,i){let n=i!=null?i:e.offsetParent;if(!n)return;t.style.cursor="move";let r=0,a=0,s=0,o=0,l=!1,c=u=>{if(!l)return;let p=u.clientX-r,f=u.clientY-a;e.style.left=`${s+p}px`,e.style.top=`${o+f}px`},d=()=>{l&&(l=!1,window.removeEventListener("pointermove",c),window.removeEventListener("pointerup",d))};t.addEventListener("pointerdown",u=>{if(u.button!==0)return;let p=u.target;if(p!=null&&p.closest("button, input, select, textarea"))return;u.preventDefault();let f=e.getBoundingClientRect(),g=n.getBoundingClientRect();s=Math.max(0,f.left-g.left),o=Math.max(0,f.top-g.top);let h=f.width,m=f.height,b=g.width,y=g.height;s=Math.min(s,b-h),o=Math.min(o,y-m),r=u.clientX,a=u.clientY,e.style.left=`${s}px`,e.style.top=`${o}px`,e.style.right="auto",e.style.bottom="auto",e.style.zIndex=String(++$w);let v=e.getBoundingClientRect();(v.left<0||v.top<0||v.right>window.innerWidth||v.bottom>window.innerHeight)&&(e.style.left="16px",e.style.top="72px",e.style.right="auto",e.style.bottom="auto"),l=!0,window.addEventListener("pointermove",c),window.addEventListener("pointerup",d)})}function _g(e,t,i){t.style.cursor="nwse-resize";let n=0,r=0,a=0,s=0,o=!1,l=d=>{if(!o)return;let u=d.clientX-a,p=d.clientY-s,f=Math.max(100,n+u),g=Math.max(100,r+p);e.style.width=`${f}px`,e.style.height=`${g}px`,i==null||i(f,g)},c=()=>{o&&(o=!1,window.removeEventListener("pointermove",l),window.removeEventListener("pointerup",c))};t.addEventListener("pointerdown",d=>{if(d.button!==0)return;d.preventDefault(),d.stopPropagation();let u=e.getBoundingClientRect();n=u.width,r=u.height,a=d.clientX,s=d.clientY,o=!0,window.addEventListener("pointermove",l),window.addEventListener("pointerup",c)})}function ic(e,t){var h,m,b;let i=(b=(m=(h=e.container)==null?void 0:h.querySelector("#debug-overlay"))!=null?m:e.debugOverlay)!=null?b:t.offsetParent;if(!i)return;let n=i.getBoundingClientRect(),r=t.getBoundingClientRect(),a=12,s=Math.max(250,Math.floor(n.width-a*2)),o=Math.max(200,Math.floor(n.height-a*2));r.width>s&&(t.style.width=`${s}px`),r.height>o&&(t.style.height=`${o}px`);let l=t.getBoundingClientRect(),c=l.left-n.left,d=l.top-n.top,u=Math.max(a,n.width-l.width-a),p=Math.max(a,n.height-l.height-a),f=Math.min(Math.max(c,a),u),g=Math.min(Math.max(d,a),p);t.style.left=`${Math.round(f)}px`,t.style.top=`${Math.round(g)}px`,t.style.right="auto",t.style.bottom="auto"}function ri(e){if(!e.container)return;let t=e.container.querySelector("#debug-workbench");if(!t)return;ic(e,t);let i={activeTab:e.activeTab,width:t.style.width,height:t.style.height,left:t.style.left,top:t.style.top};localStorage.setItem("preview_workbench_state",JSON.stringify(i))}function ts(e){try{let t=localStorage.getItem("preview_workbench_state");if(!t)return;let i=JSON.parse(t);i.activeTab&&(e.activeTab=i.activeTab),window.requestAnimationFrame(()=>{var r;let n=(r=e.container)==null?void 0:r.querySelector("#debug-workbench");n&&(i.width&&(n.style.width=i.width),i.height&&(n.style.height=i.height),i.left&&(n.style.left=i.left,n.style.right="auto"),i.top&&(n.style.top=i.top,n.style.bottom="auto"),ic(e,n))})}catch(t){console.warn("[PREVIEW] Failed to load workbench state",t)}}function Eg(e,t){let i=t.getBoundingClientRect();(i.left<0||i.top<0||i.right>window.innerWidth||i.bottom>window.innerHeight)&&(console.warn("[Workbench] Workbench positioned outside viewport, repositioning..."),t.style.left="16px",t.style.top="72px",t.style.right="auto",t.style.bottom="auto",ic(e,t),ri(e))}function Sg(e){var r,a,s;if(!e.container)return;let t=e.container,i=t.querySelector("#debug-toggle");i||console.warn("[PREVIEW] Debug toggle not found in DOM"),i==null||i.addEventListener("click",()=>{var o;console.log("[PREVIEW] Debug toggle clicked"),(o=e.toggleDebug)==null||o.call(e)}),(r=t.querySelector("#debug-close"))==null||r.addEventListener("click",()=>{var o;return(o=e.toggleDebug)==null?void 0:o.call(e,!1)}),(a=t.querySelector("#debug-reset"))==null||a.addEventListener("click",()=>Qa(e)),(s=t.querySelector("#debug-export"))==null||s.addEventListener("click",()=>es(e)),t.querySelectorAll(".workbench-tab").forEach(o=>{o.addEventListener("click",()=>{let l=o.dataset.tab;e.activeTab=l,nc(e),ri(e)})}),ac(e,t),rc(e,t)}function nc(e){if(!e.container)return;let t=e.container;t.querySelectorAll(".workbench-tab").forEach(r=>{let a=r.dataset.tab;r.classList.toggle("active",a===e.activeTab)}),t.querySelectorAll(".workbench-tab-panel").forEach(r=>{let a=r.dataset.tabPanel;r.classList.toggle("active",a===e.activeTab)})}function rc(e,t){Ae(e,t,"debug-scene-scale","engine.scale","#debug-scene-scale-value"),Ae(e,t,"debug-layout-scale","layout.scale_multiplier","#debug-layout-scale-value"),Ae(e,t,"debug-layout-offset-x","layout.position_offset.x","#debug-layout-offset-x-value"),Ae(e,t,"debug-layout-offset-y","layout.position_offset.y","#debug-layout-offset-y-value"),Ae(e,t,"debug-rect-thickness","layout.debug_rect_thickness","#debug-rect-thickness-value"),Ae(e,t,"debug-engine-scale","engine.scale","#debug-engine-scale-value"),Ae(e,t,"debug-background-scale","engine.background_scale","#debug-background-scale-value"),Ae(e,t,"debug-label-pulse-speed","engine.label_pulse_speed","#debug-label-pulse-speed-value"),Ae(e,t,"debug-label-pulse-intensity","engine.label_pulse_intensity","#debug-label-pulse-intensity-value"),Ae(e,t,"debug-rope-length","physics.rope_length","#debug-rope-length-value");let i=t.querySelector("#debug-rect-visible");i==null||i.addEventListener("change",()=>{let r=Pt();r.layout&&(r.layout.debug_rect_visible=!!i.checked)});let n=t.querySelector("#debug-rect-color");n==null||n.addEventListener("input",()=>{let r=n.value.replace("#",""),a=parseInt(r,16),s=Pt();s.layout&&(s.layout.debug_rect_color=Number.isFinite(a)?a:16711680)})}function Ag(e){if(!e.container||!e.debugOverlay)return;let t=e.container.querySelector("#debug-workbench"),i=e.container.querySelector("#workbench-handle"),n=e.container.querySelector("#workbench-resize");t&&i&&(!t.style.left&&!t.style.right&&!t.style.top&&!t.style.bottom&&(t.style.right="16px",t.style.top="72px"),wg(t,i,e.debugOverlay),i.addEventListener("pointerup",()=>{setTimeout(()=>{ri(e),Eg(e,t)},10)})),t&&n&&_g(t,n,()=>ri(e)),ts(e)}function ac(e,t){Array.from(t.querySelectorAll("[data-panel-toggle]")).forEach(n=>{n.addEventListener("click",()=>{let r=n.closest(".scene-panel");r&&r.classList.toggle("collapsed")})})}function Ae(e,t,i,n,r){let a=t.querySelector(`#${i}`),s=t.querySelector(r);if(!a||!s)return;let o=hg(Pt(),n);typeof o=="number"&&(a.value=String(o),s.textContent=String(o)),a.addEventListener("input",()=>{let l=Number(a.value);s.textContent=String(l),gg(Pt(),n,l)})}Te();var is=class{constructor(){this.container=null;this.currentVersion=null;this.availableVersions=[];this.isDevelopmentMode=!1}async initialize(t){this.container=t,this.isDevelopmentMode=typeof window!="undefined"&&document.querySelector('script[type="module"][src*="/@vite/"]')!==null,await this.loadVersionsList(),window.addEventListener("config:changed",()=>{this.refreshPanel()}),this.refreshPanel()}render(){let t=Or(),{hasChanges:i,overrideCount:n,overrides:r}=t,a={};for(let l of r){let c=l.objectId||"Engine";a[c]||(a[c]=[]),a[c].push(l)}let s=localStorage.getItem("handler_last_applied"),o=s?new Date(parseInt(s)).toLocaleString():"Never";return`
949
+ `}initialize(e,t){var y,v,x,E,w,T,S,O,B,M,C,I,k,D,R,$;this.options=t,this.root=e.querySelector('[data-panel="loading-screen"]');let a=(()=>{var _;let A=window.getEditableEngineConfig;if(typeof A=="function"){let P=A();return(_=P==null?void 0:P.loading)!=null?_:{}}return{}})(),s=(y=this.root)==null?void 0:y.querySelector("#loading-screen-type");s&&(s.value=a.type==="image"?"image":"color",s.addEventListener("change",()=>{var A,_;(_=(A=this.options)==null?void 0:A.onUpdateLoading)==null||_.call(A,{type:s.value}),this.updateFieldVisibility(s.value)}));let r=(v=this.root)==null?void 0:v.querySelector("#loading-background-color");r&&(r.value=a.background_color||"#160a17",r.addEventListener("input",()=>{var A,_;(_=(A=this.options)==null?void 0:A.onUpdateLoading)==null||_.call(A,{background_color:r.value})}));let o=(x=this.root)==null?void 0:x.querySelector("#loading-overlay-alpha"),l=(E=this.root)==null?void 0:E.querySelector("#loading-overlay-alpha-value");o&&(o.value=String((w=a.overlay_alpha)!=null?w:1),l&&(l.textContent=Number(o.value).toFixed(2)),o.addEventListener("input",()=>{var _,P;let A=Number(o.value);l&&(l.textContent=A.toFixed(2)),(P=(_=this.options)==null?void 0:_.onUpdateLoading)==null||P.call(_,{overlay_alpha:A})}));let c=(T=this.root)==null?void 0:T.querySelector("#loading-text");c&&(c.value=a.text||"",c.addEventListener("input",()=>{var A,_;(_=(A=this.options)==null?void 0:A.onUpdateLoading)==null||_.call(A,{text:c.value})}));let p=(S=this.root)==null?void 0:S.querySelector("#loading-text-scale"),d=(O=this.root)==null?void 0:O.querySelector("#loading-text-scale-value");p&&(p.value=String((B=a.text_scale)!=null?B:.6),d&&(d.textContent=Number(p.value).toFixed(2)),p.addEventListener("input",()=>{var _,P;let A=Number(p.value);d&&(d.textContent=A.toFixed(2)),(P=(_=this.options)==null?void 0:_.onUpdateLoading)==null||P.call(_,{text_scale:A})}));let u=(M=this.root)==null?void 0:M.querySelector("#loading-enabled");u&&(u.checked=a.enabled!==!1,u.addEventListener("change",()=>{var A,_;(_=(A=this.options)==null?void 0:A.onUpdateLoading)==null||_.call(A,{enabled:u.checked})}));let g=(C=this.root)==null?void 0:C.querySelector("#loading-blur-enabled");g&&(g.checked=a.blur_enabled!==!1,g.addEventListener("change",()=>{var A,_;(_=(A=this.options)==null?void 0:A.onUpdateLoading)==null||_.call(A,{blur_enabled:g.checked})}));let h=(I=this.root)==null?void 0:I.querySelector("#loading-blur-strength"),f=(k=this.root)==null?void 0:k.querySelector("#loading-blur-strength-value");h&&(h.value=String((D=a.blur_strength)!=null?D:8),f&&(f.textContent=h.value),h.addEventListener("input",()=>{var A,_;f&&(f.textContent=h.value),(_=(A=this.options)==null?void 0:A.onUpdateLoading)==null||_.call(A,{blur_strength:Number(h.value)})}));let m=(R=this.root)==null?void 0:R.querySelector("#loading-show-btn"),b=($=this.root)==null?void 0:$.querySelector("#loading-hide-btn");m==null||m.addEventListener("click",()=>{var A,_;(_=(A=this.options)==null?void 0:A.onShowLoadingScreen)==null||_.call(A)}),b==null||b.addEventListener("click",()=>{var A,_;(_=(A=this.options)==null?void 0:A.onHideLoadingScreen)==null||_.call(A)}),this.updateFieldVisibility(a.type==="image"?"image":"color")}updateFieldVisibility(e){var a,s;let t=(a=this.root)==null?void 0:a.querySelector("#loading-color-field"),n=(s=this.root)==null?void 0:s.querySelector("#loading-alpha-field");e==="image"?(t&&(t.style.display="none"),n&&(n.style.display="none")):(t&&(t.style.display=""),n&&(n.style.display=""))}refresh(){}};var Ct=require("pixi.js");Xe();ee();async function Gs(i,e,t){var n,a;console.log("[LIBRARY] applyAssetChange called with:",e,t);try{let s=Date.now(),o=`/${`raw/library/${e}/${t}`}?t=${s}`;console.log("[LIBRARY] Loading texture from:",o);let l=await Ct.Assets.load(o);if(!l){console.error("[LIBRARY] Failed to load texture:",o);return}let c=window.CustomAssets,p=Object.keys(c||{}).filter(u=>{let g=e.replace(/s$/,"");return u.startsWith(g)||u.includes(g)});for(let u of p)oe[u]=l,console.log("[LIBRARY] \u2705 Updated AssetTextures."+u),(n=c[u])!=null&&n.texture&&(c[u].texture=l,console.log("[LIBRARY] \u2705 Updated CustomAssets."+u+".texture"));let d=window.gameObjectManager;if(d)for(let u of p){let g=d.get(u);if(g){let h=((a=g.getDisplayObject)==null?void 0:a.call(g))||g.pixiObject||g;h!=null&&h.texture&&(h.texture=l,console.log("[LIBRARY] \u2705 Applied to display object:",u))}}}catch(s){console.error("[LIBRARY] Error applying asset change:",s)}}async function Us(i,e){var t,n,a;console.log("[LIBRARY] resetAsset called for:",e);try{let s=window.getEditableAssets,r=typeof s=="function"?s():null,o=(t=r==null?void 0:r.slots)==null?void 0:t.find(m=>m.category===e),l=o==null?void 0:o.defaultAsset;if(!l){console.warn("[LIBRARY] Could not find default asset for:",e);return}let c=Date.now(),p=`/raw/${l}?t=${c}`;console.log("[LIBRARY] Loading default texture from:",p);let d=await Ct.Assets.load(p);if(!d){console.error("[LIBRARY] Failed to load default texture:",p);return}let u=window.CustomAssets,g=e.replace(/s$/,""),h=Object.keys(u||{}).filter(m=>m.startsWith(g)||m.includes(g));for(let m of h)oe[m]=d,console.log("[LIBRARY] \u2705 Reset AssetTextures."+m),(n=u[m])!=null&&n.texture&&(u[m].texture=d,console.log("[LIBRARY] \u2705 Reset CustomAssets."+m+" to default"));let f=window.gameObjectManager;if(f)for(let m of h){let b=f.get(m);if(b){let y=((a=b.getDisplayObject)==null?void 0:a.call(b))||b.pixiObject||b;y!=null&&y.texture&&(y.texture=d,console.log("[LIBRARY] \u2705 Reset display object:",m))}}}catch(s){console.error("[LIBRARY] Error resetting asset:",s)}}async function qs(i,e,t,n){var a,s,r,o,l,c,p,d,u,g,h,f,m,b,y;console.log("[LIBRARY] applySlotAsset:",{objectId:e,assetFilename:t,category:n});try{let v=e.startsWith("json.")?e.replace("json.",""):e;console.log("[LIBRARY] Asset key:",v);let x=Date.now(),E=`/raw/library/${n}/${t}?t=${x}`;console.log("[LIBRARY] Loading texture from:",E);let w=await Ct.Assets.load(E);if(!w){console.error("[LIBRARY] Failed to load texture:",E);return}console.log("[LIBRARY] \u2705 Texture loaded"),oe[v]=w,console.log("[LIBRARY] \u2705 Updated AssetTextures."+v);let T=window.CustomAssets;T!=null&&T[v]&&(T[v].texture=w,console.log("[LIBRARY] \u2705 Updated legacy CustomAssets."+v));let S=window.gameObjectManager;if(console.log("[LIBRARY] gameObjectManager exists?",!!S),S){let B=Array.from(((a=S.keys)==null?void 0:a.call(S))||[]).slice(0,10);console.log("[LIBRARY] Available gameObject keys (first 10):",B);let M=S.get(v);if(console.log("[LIBRARY] gameObject for "+v+"?",!!M),M){let C=((s=M.getDisplayObject)==null?void 0:s.call(M))||M.pixiObject||M.pixi||M,I=(r=C==null?void 0:C.constructor)==null?void 0:r.name;if(console.log("[LIBRARY] displayObject:",C),console.log("[LIBRARY] displayObject type:",I),console.log("[LIBRARY] has texture?",!!(C!=null&&C.texture)),C!=null&&C.texture)C.texture=w,console.log("[LIBRARY] \u2705 Applied to display object:",v);else if(I==="Text"){console.log("[LIBRARY] \u{1F504} Converting Text to Sprite...");let{Sprite:k}=await import("pixi.js"),D=C.parent,R=(l=(o=D==null?void 0:D.getChildIndex)==null?void 0:o.call(D,C))!=null?l:0,$={x:C.x,y:C.y},A={x:(p=(c=C.anchor)==null?void 0:c.x)!=null?p:.5,y:(u=(d=C.anchor)==null?void 0:d.y)!=null?u:.5},_={x:(h=(g=C.scale)==null?void 0:g.x)!=null?h:1,y:(m=(f=C.scale)==null?void 0:f.y)!=null?m:1},P=(b=C.alpha)!=null?b:1,q=(y=C.visible)!=null?y:!0,V=new k(w);V.anchor.set(A.x,A.y),V.position.set($.x,$.y),V.scale.set(_.x,_.y),V.alpha=P,V.visible=q,D&&(D.removeChild(C),D.addChildAt(V,R),console.log("[LIBRARY] \u2705 Replaced Text with Sprite in parent")),M.pixiObject&&(M.pixiObject=V),M.pixi&&(M.pixi=V),console.log("[LIBRARY] \u2705 Text \u2192 Sprite conversion complete")}else if(C!=null&&C.children){let k=C.children.find(D=>D.texture);k?(k.texture=w,console.log("[LIBRARY] \u2705 Applied to child sprite")):console.warn("[LIBRARY] \u26A0\uFE0F No texture found in displayObject or children")}}}let O=`raw/library/${n}/${t}`;Ae({objectId:v,path:"render.asset.path",value:O}),console.log("[LIBRARY] \u2705 Staged config override for:",v,"path:",O)}catch(v){console.error("[LIBRARY] Error applying slot asset:",v)}}async function Vs(i,e,t,n){var a;console.log("[LIBRARY] resetSlotAsset:",{objectId:e,defaultAsset:t,category:n});try{let s=e.startsWith("json.")?e.replace("json.",""):e,r=Date.now(),o=`/raw/${t}?t=${r}`;console.log("[LIBRARY] Loading default texture from:",o);let l=await Ct.Assets.load(o);if(!l){console.error("[LIBRARY] Failed to load default texture:",o);return}oe[s]=l,console.log("[LIBRARY] \u2705 Reset AssetTextures."+s);let c=window.CustomAssets;c!=null&&c[s]&&(c[s].texture=l,console.log("[LIBRARY] \u2705 Reset CustomAssets."+s+" to default"));let p=window.gameObjectManager;if(p){let d=p.get(s);if(d){let u=((a=d.getDisplayObject)==null?void 0:a.call(d))||d.pixiObject||d;u!=null&&u.texture&&(u.texture=l,console.log("[LIBRARY] \u2705 Reset display object:",s))}}Ae({objectId:s,path:"render.asset.path",value:t}),console.log("[LIBRARY] \u2705 Reset config override for:",s)}catch(s){console.error("[LIBRARY] Error resetting slot asset:",s)}}var _t=require("pixi.js");var zi=require("pixi.js"),_e=()=>window.debugConfig||{},Ws=()=>window.resolveAnchorVec2||(i=>({x:.5,y:.5})),Ys=()=>window.resolveScreenAnchorPoint||(()=>new zi.Point),Ks=()=>window.resolveScreenRatioPoint||(()=>new zi.Point);function Xs(i){On(i)&&(i.objectDebugRaf||(i.objectDebugRaf=window.requestAnimationFrame(()=>In(i))))}function Js(i){i.objectDebugRaf&&(window.cancelAnimationFrame(i.objectDebugRaf),i.objectDebugRaf=null),Tt(i)}function On(i){return i.isDebugOpen}function In(i){var s,r,o;if(!On(i)){i.objectDebugRaf=null;return}i.objectDebugRaf=window.requestAnimationFrame(()=>In(i));let e=Ni(i);if(!e){Lt(i,null),Tt(i);return}let t=Hi(i,e);if(!t){Lt(i,null),Tt(i);return}let n=new _t.Point;(s=t.getGlobalPosition)==null||s.call(t,n);let a=Bi(i,t);Lt(i,{instanceId:e,worldX:n.x,worldY:n.y,configX:(r=a==null?void 0:a.x)!=null?r:null,configY:(o=a==null?void 0:a.y)!=null?o:null}),i.highlightObject?qi(i,t):Wi(i),i.highlightAnchor&&a?Vi(i,a):Yi(i)}function Ni(i){var a;let e=i.selectedObjectId;if(!e)return null;let t=window.__editableObjectInstances,n=(a=t==null?void 0:t.get)==null?void 0:a.call(t,e);return Array.isArray(n)&&n.length>0?n[0]:e}function Hi(i,e){var a,s;let t=window.gameObjectManager,n=(a=t==null?void 0:t.get)==null?void 0:a.call(t,e);return n?((s=n.getDisplayObject)==null?void 0:s.call(n))||n.pixiObject||n:null}function Pt(i){let e=i.selectedObjectId;if(!e)return null;let t=window.getEditableObjectConfig;return typeof t!="function"?null:t(e)}function Bi(i,e){var r,o;let t=Pt(i);if(!t)return null;let n=(r=t.transform)!=null?r:{},a=Fi(i);if(!a)return null;if(n.position_ratio!=null)return Ks()(a.width,a.height,n.position_ratio);let s=(o=n.anchor)!=null?o:"center";return Ys()(a.width,a.height,s)}function Fi(i){var s;let e=(s=i.container)==null?void 0:s.querySelector(".game-container"),t=Number(e==null?void 0:e.dataset.screenWidth),n=Number(e==null?void 0:e.dataset.screenHeight);if(Number.isFinite(t)&&t>0&&Number.isFinite(n)&&n>0)return{width:t,height:n};let a=window.gameApp;return a!=null&&a.renderer?{width:a.renderer.width,height:a.renderer.height}:null}function Gi(i){let e=window.gameApp;return e!=null&&e.stage?(i.objectBoundsGfx&&i.objectBoundsGfx.parent!==e.stage&&(i.objectBoundsGfx.destroy(),i.objectBoundsGfx=null),i.objectBoundsGfx||(i.objectBoundsGfx=new _t.Graphics,i.objectBoundsGfx.zIndex=999999,e.stage.addChild(i.objectBoundsGfx)),i.objectBoundsGfx):null}function Ui(i){let e=window.gameApp;return e!=null&&e.stage?(i.objectAnchorGfx&&i.objectAnchorGfx.parent!==e.stage&&(i.objectAnchorGfx.destroy(),i.objectAnchorGfx=null),i.objectAnchorGfx||(i.objectAnchorGfx=new _t.Graphics,i.objectAnchorGfx.zIndex=1e6,e.stage.addChild(i.objectAnchorGfx)),i.objectAnchorGfx):null}function qi(i,e){var a;let t=Gi(i);if(!t)return;let n=(a=e.getBounds)==null?void 0:a.call(e);n&&(t.clear(),t.rect(n.x,n.y,n.width,n.height).stroke({width:2,color:16726832,alpha:.9}))}function Vi(i,e){let t=Ui(i);if(!t)return;let n=6;t.clear(),t.moveTo(e.x-n,e.y),t.lineTo(e.x+n,e.y),t.moveTo(e.x,e.y-n),t.lineTo(e.x,e.y+n),t.stroke({width:2,color:3066993,alpha:.9})}function Wi(i){i.objectBoundsGfx&&i.objectBoundsGfx.clear()}function Yi(i){i.objectAnchorGfx&&i.objectAnchorGfx.clear()}function Tt(i){i.objectBoundsGfx&&(i.objectBoundsGfx.destroy(),i.objectBoundsGfx=null),i.objectAnchorGfx&&(i.objectAnchorGfx.destroy(),i.objectAnchorGfx=null)}function Lt(i,e){i.sceneToolsPanel.updateInfo(e?{instanceId:e.instanceId,worldX:e.worldX,worldY:e.worldY,anchorX:e.configX,anchorY:e.configY}:null)}function Zs(i,e){return e.split(".").reduce((t,n)=>t?t[n]:void 0,i)}function Qs(i,e,t){var r;let n=e.split("."),a=n.pop(),s=i;for(let o of n)s[o]=(r=s[o])!=null?r:{},s=s[o];s[a]=t}function Ki(i){var n,a,s,r,o;if(!i)return!1;if((n=i.transform)!=null&&n.offset)return!0;let e=((s=(a=i.identity)==null?void 0:a.category)!=null?s:"").toString().toLowerCase(),t=((o=(r=i.identity)==null?void 0:r.id)!=null?o:"").toString().toLowerCase();return e.includes("ui")||t.startsWith("ui")||t.includes("label")}function jn(i){let e=_e();e.layout&&(e.layout.scale_multiplier=1,e.layout.position_offset={x:0,y:0},e.layout.debug_rect_visible=!0,e.layout.debug_rect_color=16711680,e.layout.debug_rect_thickness=4),e.engine&&(e.engine.scale=1,e.engine.background_scale=1.05,e.engine.label_pulse_speed=3,e.engine.label_pulse_intensity=.03),e.physics&&(e.physics.rope_length=420),window.location.reload()}function er(i){window.location.reload()}function Dn(i){let e=JSON.stringify(_e(),null,2);navigator.clipboard.writeText(e).then(()=>{alert("Debug config copied to clipboard!")}).catch(()=>{console.log(e),alert("Config logged to console (clipboard not available)")})}async function tr(i,e){var t,n,a;if(!(!i.configViewer||!i.container))try{let s=window.getEditableObjectConfig,r=typeof s=="function"?s(e):null;if(!r){let{loadObjectCentricConfig:o,loadObjectConfig:l}=await Promise.resolve().then(()=>(dn(),Ss)),d=(((t=(await o("scene.main")).scene)==null?void 0:t.objects)||[]).find(g=>g.object_config===e||g.instance_id===e);if(!d)return;let u=await l(d.object_config);console.log("[PREVIEW] Loaded object config (fallback)",e,u),Rn(i,u),(n=i.configViewer)==null||n.style.setProperty("display","block");return}console.log("[PREVIEW] Loaded object config",e,r),Rn(i,r),(a=i.configViewer)==null||a.style.setProperty("display","block");return}catch(s){console.error("[DEBUG] Failed to load object config:",s)}}function Rn(i,e){var d,u,g,h,f,m,b,y,v,x;if(!i.container)return;let t=i.container.querySelector("#config-pos-x"),n=i.container.querySelector("#config-pos-y"),a=i.container.querySelector("#config-scale"),s=i.container.querySelector("#config-anchor-x"),r=i.container.querySelector("#config-anchor-y"),l=Ki(e)?(d=e.transform)==null?void 0:d.offset:(u=e.transform)==null?void 0:u.position;t&&(t.value=String((g=l==null?void 0:l.x)!=null?g:0)),n&&(n.value=String((h=l==null?void 0:l.y)!=null?h:0)),a&&(a.value=String((m=(f=e.transform)==null?void 0:f.scale)!=null?m:1));let c=(x=(v=(b=e.transform)==null?void 0:b.anchor)!=null?v:(y=e.render)==null?void 0:y.anchor)!=null?x:{x:.5,y:.5},p=Ws()(c);s&&(s.value=String(p.x)),r&&(r.value=String(p.y))}function nr(i){var l,c,p,d,u,g,h,f,m,b;let e=i.selectedObjectId;if(!e||!i.container)return;let t=(c=(l=i.container.querySelector("#config-pos-x"))==null?void 0:l.value)!=null?c:"0",n=(d=(p=i.container.querySelector("#config-pos-y"))==null?void 0:p.value)!=null?d:"0",a=(g=(u=i.container.querySelector("#config-scale"))==null?void 0:u.value)!=null?g:"1",s=(f=(h=i.container.querySelector("#config-anchor-x"))==null?void 0:h.value)!=null?f:"0.5",r=(b=(m=i.container.querySelector("#config-anchor-y"))==null?void 0:m.value)!=null?b:"0.5",o=`${e}:
950
+ position: (${t}, ${n})
951
+ scale: ${a}
952
+ anchor: (${s}, ${r})`;navigator.clipboard.writeText(o).then(()=>console.log("[DEBUG] Config values copied to clipboard")).catch(y=>console.error("[DEBUG] Failed to copy config values:",y))}async function Xi(i,e){var d,u,g,h,f,m,b,y,v,x,E;if(console.log("[INSPECTOR] \u{1F527} applyObjectConfig called"),!i.container)return;let t=i.selectedObjectId;if(!t){console.warn("[PREVIEW] Apply object config clicked with no selection");return}let n=Number((u=(d=i.container.querySelector("#config-pos-x"))==null?void 0:d.value)!=null?u:0),a=Number((h=(g=i.container.querySelector("#config-pos-y"))==null?void 0:g.value)!=null?h:0),s=Number((m=(f=i.container.querySelector("#config-scale"))==null?void 0:f.value)!=null?m:1),r=Number((y=(b=i.container.querySelector("#config-anchor-x"))==null?void 0:b.value)!=null?y:.5),o=Number((x=(v=i.container.querySelector("#config-anchor-y"))==null?void 0:v.value)!=null?x:.5);console.log("[INSPECTOR] Applying config for:",t,{posX:n,posY:a,scale:s,anchorX:r,anchorY:o});let{applyConfigOverride:l}=await Promise.resolve().then(()=>(ee(),sn));l({objectId:t,path:"transform.position",value:{x:n,y:a}},{silent:e==null?void 0:e.silent}),l({objectId:t,path:"transform.scale",value:s},{silent:e==null?void 0:e.silent}),l({objectId:t,path:"transform.anchor",value:{x:r,y:o}},{silent:e==null?void 0:e.silent});let c=Pt(i);Ki(c)&&l({objectId:t,path:"transform.offset",value:{x:n,y:a}},{silent:!0}),console.log("[INSPECTOR] Calling applyEditableObjectConfig...");let p=window.applyEditableObjectConfig;if(typeof p=="function"){let w=(E=window.getEditableObjectConfig)==null?void 0:E.call(window,t);w?(console.log("[INSPECTOR] \u2705 Calling applyEditableObjectConfig for:",t),p(t,w)):console.warn("[INSPECTOR] \u26A0\uFE0F No config found for:",t)}else console.warn("[INSPECTOR] \u26A0\uFE0F applyEditableObjectConfig not available")}async function ir(i,e,t){let{applyConfigOverride:n}=await Promise.resolve().then(()=>(ee(),sn));Object.entries(e.assets).forEach(([l,c])=>{n({path:`assets.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.theme).forEach(([l,c])=>{n({path:`runtime.theme.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.ui).forEach(([l,c])=>{n({path:`runtime.ui.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.fonts).forEach(([l,c])=>{n({path:`runtime.fonts.${l}`,value:c},{silent:!0})}),Object.entries(e.runtime.audio).forEach(([l,c])=>{n({path:`runtime.audio.${l}`,value:c},{silent:!0})});let a=window.applyEditableEngineConfig;if(typeof a=="function"){let l={theme:e.runtime.theme,fonts:e.runtime.fonts,audio:e.runtime.audio},c={};Object.entries(e.runtime.ui).forEach(([p,d])=>{var u;if(p)if(p.includes(".")){let g=p.split("."),h=c;for(let f=0;f<g.length-1;f++){let m=g[f];h[m]=(u=h[m])!=null?u:{},h=h[m]}h[g[g.length-1]]=d}else c[p]=d}),l.ui=c,a({runtime:l,assets:e.assets})}let s=Object.values(e.assets).some(l=>/^(blob:|data:)/.test(l)),r=(t==null?void 0:t.source)!=="auto"&&!s,o=window.__previewShell;r&&(o!=null&&o.refresh)&&o.refresh()}function ar(i){i.selectedObjectId&&(i.objectAutoApplyTimer&&window.clearTimeout(i.objectAutoApplyTimer),i.objectAutoApplyTimer=window.setTimeout(()=>{i.objectAutoApplyTimer=null,Xi(i,{silent:!0})},150))}Oi();function Ji(i,e){var f,m,b;let t=(b=(m=(f=i.container)==null?void 0:f.querySelector("#debug-overlay"))!=null?m:i.debugOverlay)!=null?b:e.offsetParent;if(!t)return;let n=t.getBoundingClientRect(),a=e.getBoundingClientRect(),s=12,r=Math.max(250,Math.floor(n.width-s*2)),o=Math.max(200,Math.floor(n.height-s*2));a.width>r&&(e.style.width=`${r}px`),a.height>o&&(e.style.height=`${o}px`);let l=e.getBoundingClientRect(),c=l.left-n.left,p=l.top-n.top,d=Math.max(s,n.width-l.width-s),u=Math.max(s,n.height-l.height-s),g=Math.min(Math.max(c,s),d),h=Math.min(Math.max(p,s),u);e.style.left=`${Math.round(g)}px`,e.style.top=`${Math.round(h)}px`,e.style.right="auto",e.style.bottom="auto"}function Ne(i){if(!i.container)return;let e=i.container.querySelector("#debug-workbench");if(!e)return;Ji(i,e);let t={activeTab:i.activeTab,width:e.style.width,height:e.style.height,left:e.style.left,top:e.style.top};localStorage.setItem("preview_workbench_state",JSON.stringify(t))}function $n(i){try{let e=localStorage.getItem("preview_workbench_state");if(!e)return;let t=JSON.parse(e);t.activeTab&&(i.activeTab=t.activeTab),window.requestAnimationFrame(()=>{var a;let n=(a=i.container)==null?void 0:a.querySelector("#debug-workbench");n&&(t.width&&(n.style.width=t.width),t.height&&(n.style.height=t.height),t.left&&(n.style.left=t.left,n.style.right="auto"),t.top&&(n.style.top=t.top,n.style.bottom="auto"),Ji(i,n))})}catch(e){console.warn("[PREVIEW] Failed to load workbench state",e)}}function sr(i,e){let t=e.getBoundingClientRect();(t.left<0||t.top<0||t.right>window.innerWidth||t.bottom>window.innerHeight)&&(console.warn("[Workbench] Workbench positioned outside viewport, repositioning..."),e.style.left="16px",e.style.top="72px",e.style.right="auto",e.style.bottom="auto",Ji(i,e),Ne(i))}function rr(i){var a,s,r;if(!i.container)return;let e=i.container,t=e.querySelector("#debug-toggle");t||console.warn("[PREVIEW] Debug toggle not found in DOM"),t==null||t.addEventListener("click",()=>{var o;console.log("[PREVIEW] Debug toggle clicked"),(o=i.toggleDebug)==null||o.call(i)}),(a=e.querySelector("#debug-close"))==null||a.addEventListener("click",()=>{var o;return(o=i.toggleDebug)==null?void 0:o.call(i,!1)}),(s=e.querySelector("#debug-reset"))==null||s.addEventListener("click",()=>jn(i)),(r=e.querySelector("#debug-export"))==null||r.addEventListener("click",()=>Dn(i)),e.querySelectorAll(".workbench-tab").forEach(o=>{o.addEventListener("click",()=>{let l=o.dataset.tab;i.activeTab=l,Zi(i),Ne(i)})}),ea(i,e),Qi(i,e)}function Zi(i){if(!i.container)return;let e=i.container;e.querySelectorAll(".workbench-tab").forEach(a=>{let s=a.dataset.tab;a.classList.toggle("active",s===i.activeTab)}),e.querySelectorAll(".workbench-tab-panel").forEach(a=>{let s=a.dataset.tabPanel;a.classList.toggle("active",s===i.activeTab)})}function Qi(i,e){te(i,e,"debug-layout-scale","layout.scale_multiplier","#debug-layout-scale-value"),te(i,e,"debug-layout-offset-x","layout.position_offset.x","#debug-layout-offset-x-value"),te(i,e,"debug-layout-offset-y","layout.position_offset.y","#debug-layout-offset-y-value"),te(i,e,"debug-rect-thickness","layout.debug_rect_thickness","#debug-rect-thickness-value"),te(i,e,"debug-engine-scale","engine.scale","#debug-engine-scale-value"),te(i,e,"debug-background-scale","engine.background_scale","#debug-background-scale-value"),te(i,e,"debug-label-pulse-speed","engine.label_pulse_speed","#debug-label-pulse-speed-value"),te(i,e,"debug-label-pulse-intensity","engine.label_pulse_intensity","#debug-label-pulse-intensity-value"),te(i,e,"debug-rope-length","physics.rope_length","#debug-rope-length-value");let t=e.querySelector("#debug-rect-visible");t==null||t.addEventListener("change",()=>{let a=_e();a.layout&&(a.layout.debug_rect_visible=!!t.checked)});let n=e.querySelector("#debug-rect-color");n==null||n.addEventListener("input",()=>{let a=n.value.replace("#",""),s=parseInt(a,16),r=_e();r.layout&&(r.layout.debug_rect_color=Number.isFinite(s)?s:16711680)})}function or(i){if(!i.container||!i.debugOverlay)return;let e=i.container.querySelector("#debug-workbench"),t=i.container.querySelector("#workbench-handle"),n=i.container.querySelector("#workbench-resize");e&&t&&(!e.style.left&&!e.style.right&&!e.style.top&&!e.style.bottom&&(e.style.right="16px",e.style.top="72px"),Mi(e,t,i.debugOverlay),t.addEventListener("pointerup",()=>{setTimeout(()=>{Ne(i),sr(i,e)},10)})),e&&n&&ki(e,n,()=>Ne(i)),$n(i)}function ea(i,e){Array.from(e.querySelectorAll("[data-panel-toggle]")).forEach(n=>{n.addEventListener("click",()=>{let a=n.closest(".scene-panel");a&&a.classList.toggle("collapsed")})})}function te(i,e,t,n,a){let s=e.querySelector(`#${t}`),r=e.querySelector(a);if(!s||!r)return;let o=Zs(_e(),n);typeof o=="number"&&(s.value=String(o),r.textContent=String(o)),s.addEventListener("input",()=>{let l=Number(s.value);r.textContent=String(l),Qs(_e(),n,l)})}ee();var zn=class{constructor(){this.container=null;this.currentVersion=null;this.availableVersions=[];this.isDevelopmentMode=!1}async initialize(e){this.container=e,this.isDevelopmentMode=typeof window!="undefined"&&document.querySelector('script[type="module"][src*="/@vite/"]')!==null,await this.loadVersionsList(),window.addEventListener("config:changed",()=>{this.refreshPanel()}),this.refreshPanel()}render(){let e=nn(),{hasChanges:t,overrideCount:n,overrides:a}=e,s={};for(let l of a){let c=l.objectId||"Engine";s[c]||(s[c]=[]),s[c].push(l)}let r=localStorage.getItem("handler_last_applied"),o=r?new Date(parseInt(r)).toLocaleString():"Never";return`
1051
953
  <div class="config-persistence-panel">
1052
- <div class="persistence-status-bar ${i?"has-changes":"no-changes"}">
1053
- ${i?`
954
+ <div class="persistence-status-bar ${t?"has-changes":"no-changes"}">
955
+ ${t?`
1054
956
  <div class="status-box">
1055
957
  <span class="status-badge">UNAPPLIED</span>
1056
958
  <span class="status-text">${n} staging changes</span>
@@ -1068,7 +970,7 @@ Generate the requested asset matching the brand style.${e.needsTransparency?" Ba
1068
970
  <button
1069
971
  id="apply-to-project-btn"
1070
972
  class="persistence-btn primary-action"
1071
- ${i?"":"disabled"}
973
+ ${t?"":"disabled"}
1072
974
  title="Saves all staged changes to the actual configuration files on disk."
1073
975
  >
1074
976
  \u{1F4BE} APPLY ALL CHANGES TO PROJECT
@@ -1091,13 +993,13 @@ Generate the requested asset matching the brand style.${e.needsTransparency?" Ba
1091
993
  `).join("")}
1092
994
  </select>
1093
995
  </div>
1094
- <button id="create-version-btn" class="persistence-btn" ${i?"":"disabled"}>
996
+ <button id="create-version-btn" class="persistence-btn" ${t?"":"disabled"}>
1095
997
  \u{1F4DD} Create New Version
1096
998
  </button>
1097
999
  </div>
1098
1000
  </div>
1099
1001
 
1100
- ${this.isDevelopmentMode&&i?`
1002
+ ${this.isDevelopmentMode&&t?`
1101
1003
  <div class="dev-only-section">
1102
1004
  <div class="dev-warning">
1103
1005
  \u26A0\uFE0F Developer Mode Only
@@ -1112,27 +1014,27 @@ Generate the requested asset matching the brand style.${e.needsTransparency?" Ba
1112
1014
  </div>
1113
1015
  `:""}
1114
1016
 
1115
- ${i?`
1017
+ ${t?`
1116
1018
  <div class="staging-area">
1117
1019
  <div class="staging-header">
1118
1020
  <span>Staging Area (Pending Review)</span>
1119
1021
  <button class="staging-clear-all" id="clear-all-overrides">Discard All</button>
1120
1022
  </div>
1121
1023
  <div class="staging-list">
1122
- ${Object.entries(a).map(([l,c])=>`
1024
+ ${Object.entries(s).map(([l,c])=>`
1123
1025
  <div class="staging-group">
1124
1026
  <div class="staging-group-title">
1125
1027
  <span class="group-icon">${l==="Engine"?"\u2699\uFE0F":"\u{1F4E6}"}</span>
1126
1028
  <span class="group-id">${l}</span>
1127
1029
  </div>
1128
1030
  <div class="staging-items">
1129
- ${c.map(d=>`
1031
+ ${c.map(p=>`
1130
1032
  <div class="staging-item">
1131
- <div class="item-path">${d.path}</div>
1132
- <div class="item-value" title="${JSON.stringify(d.value)}">
1133
- ${this.formatValue(d.value)}
1033
+ <div class="item-path">${p.path}</div>
1034
+ <div class="item-value" title="${JSON.stringify(p.value)}">
1035
+ ${this.formatValue(p.value)}
1134
1036
  </div>
1135
- <button class="item-remove" data-remove-path="${d.path}" data-remove-id="${d.objectId||""}" title="Discard this change">\xD7</button>
1037
+ <button class="item-remove" data-remove-path="${p.path}" data-remove-id="${p.objectId||""}" title="Discard this change">\xD7</button>
1136
1038
  </div>
1137
1039
  `).join("")}
1138
1040
  </div>
@@ -1154,7 +1056,7 @@ Generate the requested asset matching the brand style.${e.needsTransparency?" Ba
1154
1056
  <span class="footer-value">${o}</span>
1155
1057
  </div>
1156
1058
  <div class="footer-secondary-actions">
1157
- <button id="reset-to-applied-btn" class="footer-btn" ${i?"":"disabled"}>Reload State</button>
1059
+ <button id="reset-to-applied-btn" class="footer-btn" ${t?"":"disabled"}>Reload State</button>
1158
1060
  <button id="reset-to-original-btn" class="footer-btn danger">Factory Reset (Pristine)</button>
1159
1061
  </div>
1160
1062
  </div>
@@ -1163,21 +1065,21 @@ Generate the requested asset matching the brand style.${e.needsTransparency?" Ba
1163
1065
  <p><strong>Apply to Project</strong> writes the current preview state to your local .json files in /configs/ folder. This state will be used for the dashboard build.</p>
1164
1066
  </div>
1165
1067
  </div>
1166
- `}formatValue(t){return t===null?"null":typeof t=="string"?t.length>25?t.substring(0,22)+"...":t:typeof t=="object"?"{...}":String(t)}setupEventListeners(){if(!this.container)return;let t=this.container.querySelector("#apply-to-project-btn");t==null||t.addEventListener("click",async()=>{var d;if(!(t.getAttribute("disabled")!==null||!confirm("This will permanently update your project configuration files on disk. Are you sure?")))try{let u=localStorage.getItem("handler_last_version_name")||"",f=((d=prompt("Version name for this Apply (e.g. v1, ab_red_cta, 2026-01-17a):",u))!=null?d:"").trim();if(!f){alert("Version name is required to Apply. (No changes were written.)");return}localStorage.setItem("handler_last_version_name",f),t.textContent="\u23F3 Writing to disk...",t.setAttribute("disabled","true"),await hn(f),this.showSuccessNotification(),this.refreshPanel()}catch(u){console.error("[ConfigPersistence] Apply failed:",u),alert(`\u274C Apply failed: ${u.message}`),t.textContent="\u{1F4BE} APPLY ALL CHANGES TO PROJECT",t.removeAttribute("disabled")}}),this.container.querySelectorAll(".item-remove").forEach(c=>{c.addEventListener("click",()=>{let d=c.dataset.removePath,u=c.dataset.removeId;Lr(u||void 0,d)})});let n=this.container.querySelector("#clear-all-overrides");n==null||n.addEventListener("click",()=>{confirm("Discard all staged changes?")&&gn()});let r=this.container.querySelector("#reset-to-applied-btn");r==null||r.addEventListener("click",()=>{confirm("Discard changes and reload last applied state?")&&gn()});let a=this.container.querySelector("#reset-to-original-btn");a==null||a.addEventListener("click",async()=>{await Ir()});let s=this.container.querySelector("#version-selector");s==null||s.addEventListener("change",async c=>{let u=c.target.value;await this.switchVersion(u)});let o=this.container.querySelector("#create-version-btn");o==null||o.addEventListener("click",async()=>{var d;if(!(o.getAttribute("disabled")!==null||!confirm("This will create a new version snapshot and save your changes. Continue?")))try{let u=localStorage.getItem("handler_last_version_name")||"",f=((d=prompt("Version name (e.g. v1, test_2024):",u))!=null?d:"").trim();if(!f){alert("Version name is required. (No changes were written.)");return}localStorage.setItem("handler_last_version_name",f),o.textContent="\u23F3 Creating version...",o.setAttribute("disabled","true"),await hn(f),this.showSuccessNotification(),await this.loadVersionsList(),this.refreshPanel()}catch(u){console.error("[ConfigPersistence] Create version failed:",u),alert(`\u274C Failed to create version: ${u.message}`),o.textContent="\u{1F4DD} Create New Version",o.removeAttribute("disabled")}});let l=this.container.querySelector("#direct-apply-btn");l==null||l.addEventListener("click",async()=>{await this.directApply()})}showSuccessNotification(){let t=document.createElement("div");t.className="persistence-notification success",t.innerHTML=`
1068
+ `}formatValue(e){return e===null?"null":typeof e=="string"?e.length>25?e.substring(0,22)+"...":e:typeof e=="object"?"{...}":String(e)}setupEventListeners(){if(!this.container)return;let e=this.container.querySelector("#apply-to-project-btn");e==null||e.addEventListener("click",async()=>{var p;if(!(e.getAttribute("disabled")!==null||!confirm("This will permanently update your project configuration files on disk. Are you sure?")))try{let d=localStorage.getItem("handler_last_version_name")||"",g=((p=prompt("Version name for this Apply (e.g. v1, ab_red_cta, 2026-01-17a):",d))!=null?p:"").trim();if(!g){alert("Version name is required to Apply. (No changes were written.)");return}localStorage.setItem("handler_last_version_name",g),e.textContent="\u23F3 Writing to disk...",e.setAttribute("disabled","true"),await wt(g),this.showSuccessNotification(),this.refreshPanel()}catch(d){console.error("[ConfigPersistence] Apply failed:",d),alert(`\u274C Apply failed: ${d.message}`),e.textContent="\u{1F4BE} APPLY ALL CHANGES TO PROJECT",e.removeAttribute("disabled")}}),this.container.querySelectorAll(".item-remove").forEach(c=>{c.addEventListener("click",()=>{let p=c.dataset.removePath,d=c.dataset.removeId;tn(d||void 0,p)})});let n=this.container.querySelector("#clear-all-overrides");n==null||n.addEventListener("click",()=>{confirm("Discard all staged changes?")&&Et()});let a=this.container.querySelector("#reset-to-applied-btn");a==null||a.addEventListener("click",()=>{confirm("Discard changes and reload last applied state?")&&Et()});let s=this.container.querySelector("#reset-to-original-btn");s==null||s.addEventListener("click",async()=>{await an()});let r=this.container.querySelector("#version-selector");r==null||r.addEventListener("change",async c=>{let d=c.target.value;await this.switchVersion(d)});let o=this.container.querySelector("#create-version-btn");o==null||o.addEventListener("click",async()=>{var p;if(!(o.getAttribute("disabled")!==null||!confirm("This will create a new version snapshot and save your changes. Continue?")))try{let d=localStorage.getItem("handler_last_version_name")||"",g=((p=prompt("Version name (e.g. v1, test_2024):",d))!=null?p:"").trim();if(!g){alert("Version name is required. (No changes were written.)");return}localStorage.setItem("handler_last_version_name",g),o.textContent="\u23F3 Creating version...",o.setAttribute("disabled","true"),await wt(g),this.showSuccessNotification(),await this.loadVersionsList(),this.refreshPanel()}catch(d){console.error("[ConfigPersistence] Create version failed:",d),alert(`\u274C Failed to create version: ${d.message}`),o.textContent="\u{1F4DD} Create New Version",o.removeAttribute("disabled")}});let l=this.container.querySelector("#direct-apply-btn");l==null||l.addEventListener("click",async()=>{await this.directApply()})}showSuccessNotification(){let e=document.createElement("div");e.className="persistence-notification success",e.innerHTML=`
1167
1069
  <div class="notify-icon">\u2705</div>
1168
1070
  <div class="notify-content">
1169
1071
  <strong>Changes Applied!</strong>
1170
1072
  <span>Project files updated.</span>
1171
1073
  </div>
1172
- `,document.body.appendChild(t),setTimeout(()=>{t.classList.add("out"),setTimeout(()=>t.remove(),500)},3e3)}refreshPanel(){if(!this.container)return;let t=this.container.querySelector(".config-persistence-panel");t?t.outerHTML=this.render():this.container.innerHTML=this.render(),this.setupEventListeners()}async loadVersionsList(){try{let t=await fetch("/api/versions");if(!t.ok)throw new Error("Failed to fetch versions");let i=await t.json();this.availableVersions=i.versions||[],this.currentVersion=i.current||null}catch(t){console.error("[ConfigPersistence] Failed to load versions:",t),this.availableVersions=[],this.currentVersion=null}}async switchVersion(t){if(confirm(`Switch to version "${t||"original"}"?
1074
+ `,document.body.appendChild(e),setTimeout(()=>{e.classList.add("out"),setTimeout(()=>e.remove(),500)},3e3)}refreshPanel(){if(!this.container)return;let e=this.container.querySelector(".config-persistence-panel");e?e.outerHTML=this.render():this.container.innerHTML=this.render(),this.setupEventListeners()}async loadVersionsList(){try{let e=await fetch("/api/versions");if(!e.ok)throw new Error("Failed to fetch versions");let t=await e.json();this.availableVersions=t.versions||[],this.currentVersion=t.current||null}catch(e){console.error("[ConfigPersistence] Failed to load versions:",e),this.availableVersions=[],this.currentVersion=null}}async switchVersion(e){if(confirm(`Switch to version "${e||"original"}"?
1173
1075
 
1174
- All unsaved changes in the current version will be lost.`))try{let n=await fetch("/api/switch-version",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({versionName:t||null})});if(!n.ok){let r=await n.json();throw new Error(r.error||"Failed to switch version")}vt(),window.location.reload()}catch(n){alert(`\u274C Failed to switch version: ${n.message}`)}}async directApply(){if(!this.isDevelopmentMode){alert("Direct Apply is only available in development mode.");return}if(confirm(`\u26A0\uFE0F WARNING: Direct Apply
1076
+ All unsaved changes in the current version will be lost.`))try{let n=await fetch("/api/switch-version",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({versionName:e||null})});if(!n.ok){let a=await n.json();throw new Error(a.error||"Failed to switch version")}Ce(),window.location.reload()}catch(n){alert(`\u274C Failed to switch version: ${n.message}`)}}async directApply(){if(!this.isDevelopmentMode){alert("Direct Apply is only available in development mode.");return}if(confirm(`\u26A0\uFE0F WARNING: Direct Apply
1175
1077
 
1176
1078
  This will DIRECTLY MODIFY your base configuration files WITHOUT creating a snapshot.
1177
1079
 
1178
1080
  This cannot be undone unless you have git commits or backups.
1179
1081
 
1180
- Are you absolutely sure?`))try{let i=fn(),n={};for(let[a,s]of Object.entries(i.objects)){let o=s,l=a;/^(json\.|ui\.|effects\.|engine\.)/.test(l)||(l=`json.${a}`),o&&typeof o=="object"&&(o.identity||(o.identity={}),o.identity.id=l),n[`objects/${l}.json`]=o}i.engine&&(i.engine.runtime&&(n["engine/engine.runtime.json"]=i.engine.runtime),i.engine.assets&&(n["engine/engine.assets.json"]=i.engine.assets),i.engine.splash&&(n["engine/engine.splash.json"]=i.engine.splash),i.engine.loading&&(n["engine/engine.loading.json"]=i.engine.loading),i.engine.start&&(n["engine/engine.start.json"]=i.engine.start),i.engine.tutorial&&(n["engine/engine.tutorial.json"]=i.engine.tutorial),i.engine.endgame&&(n["engine/engine.endgame.json"]=i.engine.endgame),!i.engine.runtime&&!i.engine.assets&&(n["engine/engine.json"]=i.engine));for(let[a,s]of Object.entries(i.scenes)){let o=a.startsWith("scene.")?a:`scene.${a}`;n[`scenes/${o}.json`]=s}let r=await fetch("/api/apply-direct",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:n,assets:{}})});if(!r.ok){let a=await r.json();throw new Error(a.error||"Direct apply failed")}vt(),this.showSuccessNotification(),this.refreshPanel()}catch(i){console.error("[ConfigPersistence] Direct apply failed:",i),alert(`\u274C Direct apply failed: ${i.message}`)}}};var rr=class{constructor(){this.debugOverlay=null;this.isDebugOpen=!1;this.selectedObjectId=null;this.configViewer=null;this.container=null;this.objectAutoApplyTimer=null;this.objectDebugRaf=null;this.objectBoundsGfx=null;this.objectAnchorGfx=null;this.highlightObject=!1;this.highlightAnchor=!1;this.activeTab="hierarchy";this.sceneObjectsPanel=new Br;this.sceneToolsPanel=new Fr;this.inspectorPanel=new Qr;this.libraryPanel=new $r;this.brandVisionPanel=new Va;this.customizeSettingsPanel=new Ya;this.configPersistencePanel=new is;this.loadingScreenPanel=new Ka}applyAssetChange(t,i){return ag(this,t,i)}resetAsset(t){return sg(this,t)}applySlotAsset(t,i,n){return og(this,t,i,n)}resetSlotAsset(t,i,n){return lg(this,t,i,n)}startObjectVisuals(){return pg(this)}stopObjectVisuals(){return fg(this)}shouldRunObjectVisuals(){return Xa(this)}updateObjectVisuals(){return Za(this)}getSelectedInstanceId(){return ql(this)}getDisplayObjectById(t){return Gl(this,t)}getSelectedObjectConfig(){return nr(this)}getConfigAnchorWorldPoint(t){return Wl(this,t)}getScreenSize(){return Vl(this)}ensureBoundsGfx(){return Yl(this)}ensureAnchorGfx(){return Kl(this)}drawBounds(t){return Xl(this,t)}drawAnchor(t){return Zl(this,t)}clearBounds(){return Jl(this)}clearAnchor(){return Ql(this)}clearObjectVisuals(){return tr(this)}updateObjectInfo(t){return er(this,t)}resetDebugConfig(){return Qa(this)}applyDebugConfig(){return mg(this)}exportDebugConfig(){return es(this)}loadObjectConfig(t){return bg(this,t)}fillConfigViewer(t){return Ja(this,t)}copyConfigValues(){return yg(this)}applyObjectConfig(t){return tc(this,t)}applyCustomizeSettings(t,i){return vg(this,t,i)}scheduleObjectAutoApply(){return xg(this)}setupDebugEventListeners(){return Sg(this)}setupDebugInputListeners(t){return rc(this,t)}setupPanelLayout(){return Ag(this)}setupCollapsiblePanels(t){return ac(this,t)}setupRangeInput(t,i,n,r){return Ae(this,t,i,n,r)}updateWorkbenchTabs(){return nc(this)}saveWorkbenchState(){return ri(this)}loadWorkbenchState(){return ts(this)}initialize(t){var i;this.container=t,this.debugOverlay=t.querySelector(".debug-overlay"),this.configViewer=t.querySelector("#config-viewer");try{let n=localStorage.getItem("preview_workbench_state");if(n){let r=JSON.parse(n);r.activeTab&&(this.activeTab=r.activeTab)}}catch(n){console.warn("[PREVIEW] Failed to load workbench tab state",n)}this.sceneObjectsPanel.initialize(t,{onSelect:n=>this.handleObjectSelect(n)}),this.libraryPanel.initialize(t,{onApply:(n,r,a)=>this.applySlotAsset(n,r,a),onReset:(n,r,a)=>this.resetSlotAsset(n,r,a)}),this.inspectorPanel.initialize(t,{onPropertyChange:(n,r,a)=>{console.log("[Inspector] Property changed:",n,r,a)}}),this.brandVisionPanel.initialize(t,()=>{this.toggleDebug(!1);let n="/dashboard";window.location.pathname!==n&&(window.location.href=n)}),this.customizeSettingsPanel.initialize(t,{onApply:(n,r)=>this.applyCustomizeSettings(n,r)}),this.configPersistencePanel.initialize(t),this.loadingScreenPanel.initialize(t,{onShowLoadingScreen:()=>{let n=window;typeof n.__previewShowLoading=="function"?n.__previewShowLoading():console.warn("[DEBUG] __previewShowLoading not available")},onHideLoadingScreen:()=>{let n=window;typeof n.__previewHideLoading=="function"?n.__previewHideLoading():console.warn("[DEBUG] __previewHideLoading not available")},onUpdateLoading:n=>{let r=window;typeof r.applyEditableEngineConfig=="function"&&r.applyEditableEngineConfig({loading:n}),typeof r.__previewUpdateLoading=="function"?r.__previewUpdateLoading(n):console.warn("[DEBUG] __previewUpdateLoading not available")}}),window.__openAiEditor=(n,r,a,s)=>{this.customizeSettingsPanel.openAiEditor(n,r,a,s)},this.setupPanelLayout(),this.updateWorkbenchTabs(),window.__debugContext=this,window.__updateWorkbenchTabs=()=>this.updateWorkbenchTabs(),this.isDebugOpen=!0,(i=this.debugOverlay)==null||i.classList.remove("hidden"),this.updateDebugBadge(),this.sceneObjectsPanel.refreshObjects(),window.__previewSelectObject=n=>this.selectObject(n),window.addEventListener("config:changed",n=>{var r,a;((r=n.detail)==null?void 0:r.action)!=="remove"&&((a=n.detail)==null?void 0:a.action)!=="clear_object"&&this.highlightChangesTab()}),window.applyAssetToSlot=(n,r,a)=>this.applySlotAsset(n,r,a),window.refreshAssetLibrary=()=>this.libraryPanel.refresh(),window.reRenderAssetLibrary=()=>this.libraryPanel.reRender(),window.getEngineSplashConfig=()=>{var r;let n=window.getActiveConfig;if(typeof n=="function"){let a=n();return((r=a==null?void 0:a.engine)==null?void 0:r.splash)||null}return null},window.addAssetToRegistry=(n,r)=>{let a=window.getEditableAssets;if(typeof a=="function"){let s=a();if(s!=null&&s.libraryAssets&&(s.libraryAssets[n]||(s.libraryAssets[n]=[]),!s.libraryAssets[n].some(l=>l.filename===r))){let l=r.replace(/\.(png|jpg|jpeg)$/i,"").replace(/_/g," ");s.libraryAssets[n].unshift({filename:r,displayName:l}),console.log(`[DEBUG] Added ${r} to registry category ${n}`)}}}}selectObject(t){this.handleObjectSelect(t),this.activeTab!=="inspector"&&(this.activeTab="inspector",this.updateWorkbenchTabs())}highlightChangesTab(){var i;let t=(i=this.container)==null?void 0:i.querySelector('[data-tab="changes"]');t&&t.classList.add("has-pending-changes")}getDebugOverlayHTML(){return`
1082
+ Are you absolutely sure?`))try{let t=xt(),n={};for(let[s,r]of Object.entries(t.objects)){let o=r,l=s;/^(json\.|ui\.|effects\.|engine\.)/.test(l)||(l=`json.${s}`),o&&typeof o=="object"&&(o.identity||(o.identity={}),o.identity.id=l),n[`objects/${l}.json`]=o}t.engine&&(t.engine.runtime&&(n["engine/engine.runtime.json"]=t.engine.runtime),t.engine.assets&&(n["engine/engine.assets.json"]=t.engine.assets),t.engine.splash&&(n["engine/engine.splash.json"]=t.engine.splash),t.engine.loading&&(n["engine/engine.loading.json"]=t.engine.loading),t.engine.start&&(n["engine/engine.start.json"]=t.engine.start),t.engine.tutorial&&(n["engine/engine.tutorial.json"]=t.engine.tutorial),t.engine.endgame&&(n["engine/engine.endgame.json"]=t.engine.endgame),!t.engine.runtime&&!t.engine.assets&&(n["engine/engine.json"]=t.engine));for(let[s,r]of Object.entries(t.scenes)){let o=s.startsWith("scene.")?s:`scene.${s}`;n[`scenes/${o}.json`]=r}let a=await fetch("/api/apply-direct",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({configs:n,assets:{}})});if(!a.ok){let s=await a.json();throw new Error(s.error||"Direct apply failed")}Ce(),this.showSuccessNotification(),this.refreshPanel()}catch(t){console.error("[ConfigPersistence] Direct apply failed:",t),alert(`\u274C Direct apply failed: ${t.message}`)}}};var Mt=class{constructor(){this.debugOverlay=null;this.isDebugOpen=!1;this.selectedObjectId=null;this.configViewer=null;this.container=null;this.objectAutoApplyTimer=null;this.objectDebugRaf=null;this.objectBoundsGfx=null;this.objectAnchorGfx=null;this.highlightObject=!1;this.highlightAnchor=!1;this.activeTab="hierarchy";this.sceneObjectsPanel=new un;this.sceneToolsPanel=new gn;this.inspectorPanel=new Ln;this.libraryPanel=new fn;this.brandVisionPanel=new Pn;this.customizeSettingsPanel=new Mn;this.configPersistencePanel=new zn;this.loadingScreenPanel=new kn}applyAssetChange(e,t){return Gs(this,e,t)}resetAsset(e){return Us(this,e)}applySlotAsset(e,t,n){return qs(this,e,t,n)}resetSlotAsset(e,t,n){return Vs(this,e,t,n)}startObjectVisuals(){return Xs(this)}stopObjectVisuals(){return Js(this)}shouldRunObjectVisuals(){return On(this)}updateObjectVisuals(){return In(this)}getSelectedInstanceId(){return Ni(this)}getDisplayObjectById(e){return Hi(this,e)}getSelectedObjectConfig(){return Pt(this)}getConfigAnchorWorldPoint(e){return Bi(this,e)}getScreenSize(){return Fi(this)}ensureBoundsGfx(){return Gi(this)}ensureAnchorGfx(){return Ui(this)}drawBounds(e){return qi(this,e)}drawAnchor(e){return Vi(this,e)}clearBounds(){return Wi(this)}clearAnchor(){return Yi(this)}clearObjectVisuals(){return Tt(this)}updateObjectInfo(e){return Lt(this,e)}resetDebugConfig(){return jn(this)}applyDebugConfig(){return er(this)}exportDebugConfig(){return Dn(this)}loadObjectConfig(e){return tr(this,e)}fillConfigViewer(e){return Rn(this,e)}copyConfigValues(){return nr(this)}applyObjectConfig(e){return Xi(this,e)}applyCustomizeSettings(e,t){return ir(this,e,t)}scheduleObjectAutoApply(){return ar(this)}setupDebugEventListeners(){return rr(this)}setupDebugInputListeners(e){return Qi(this,e)}setupPanelLayout(){return or(this)}setupCollapsiblePanels(e){return ea(this,e)}setupRangeInput(e,t,n,a){return te(this,e,t,n,a)}updateWorkbenchTabs(){return Zi(this)}saveWorkbenchState(){return Ne(this)}loadWorkbenchState(){return $n(this)}initialize(e){var t;this.container=e,this.debugOverlay=e.querySelector(".debug-overlay"),this.configViewer=e.querySelector("#config-viewer");try{let n=localStorage.getItem("preview_workbench_state");if(n){let a=JSON.parse(n);a.activeTab&&(this.activeTab=a.activeTab)}}catch(n){console.warn("[PREVIEW] Failed to load workbench tab state",n)}this.sceneObjectsPanel.initialize(e,{onSelect:n=>this.handleObjectSelect(n)}),this.libraryPanel.initialize(e,{onApply:(n,a,s)=>this.applySlotAsset(n,a,s),onReset:(n,a,s)=>this.resetSlotAsset(n,a,s)}),this.inspectorPanel.initialize(e,{onPropertyChange:(n,a,s)=>{console.log("[Inspector] Property changed:",n,a,s)}}),this.brandVisionPanel.initialize(e,()=>{this.toggleDebug(!1);let n="/dashboard";window.location.pathname!==n&&(window.location.href=n)}),this.customizeSettingsPanel.initialize(e,{onApply:(n,a)=>this.applyCustomizeSettings(n,a)}),this.sceneToolsPanel.initialize(e,{onHighlightObject:n=>{this.highlightObject=n,n?this.selectedObjectId&&this.startObjectVisuals():this.stopObjectVisuals()},onHighlightAnchor:n=>{this.highlightAnchor=n,n?this.selectedObjectId&&this.startObjectVisuals():this.stopObjectVisuals()},onNudge:(n,a)=>this.nudgeSelectedObject(n,a),onShowSplash:()=>{let n=window;typeof n.__previewShowSplash=="function"&&n.__previewShowSplash()},onUpdateSplash:n=>{let a=window;typeof a.applyEditableEngineConfig=="function"&&a.applyEditableEngineConfig({splash:n})}}),this.configPersistencePanel.initialize(e),this.loadingScreenPanel.initialize(e,{onShowLoadingScreen:()=>{let n=window;typeof n.__previewShowLoading=="function"?n.__previewShowLoading():console.warn("[DEBUG] __previewShowLoading not available")},onHideLoadingScreen:()=>{let n=window;typeof n.__previewHideLoading=="function"?n.__previewHideLoading():console.warn("[DEBUG] __previewHideLoading not available")},onUpdateLoading:n=>{let a=window;typeof a.applyEditableEngineConfig=="function"&&a.applyEditableEngineConfig({loading:n}),typeof a.__previewUpdateLoading=="function"?a.__previewUpdateLoading(n):console.warn("[DEBUG] __previewUpdateLoading not available")}}),window.__openAiEditor=(n,a,s,r)=>{this.customizeSettingsPanel.openAiEditor(n,a,s,r)},this.setupPanelLayout(),this.updateWorkbenchTabs(),window.__debugContext=this,window.__updateWorkbenchTabs=()=>this.updateWorkbenchTabs(),this.isDebugOpen=!0,(t=this.debugOverlay)==null||t.classList.remove("hidden"),this.updateDebugBadge(),this.sceneObjectsPanel.refreshObjects(),window.__previewSelectObject=n=>this.selectObject(n),window.addEventListener("config:changed",n=>{var a,s;((a=n.detail)==null?void 0:a.action)!=="remove"&&((s=n.detail)==null?void 0:s.action)!=="clear_object"&&this.highlightChangesTab()}),window.applyAssetToSlot=(n,a,s)=>this.applySlotAsset(n,a,s),window.refreshAssetLibrary=()=>this.libraryPanel.refresh(),window.reRenderAssetLibrary=()=>this.libraryPanel.reRender(),window.getEngineSplashConfig=()=>{var a;let n=window.getActiveConfig;if(typeof n=="function"){let s=n();return((a=s==null?void 0:s.engine)==null?void 0:a.splash)||null}return null},window.addAssetToRegistry=(n,a)=>{let s=window.getEditableAssets;if(typeof s=="function"){let r=s();if(r!=null&&r.libraryAssets&&(r.libraryAssets[n]||(r.libraryAssets[n]=[]),!r.libraryAssets[n].some(l=>l.filename===a))){let l=a.replace(/\.(png|jpg|jpeg)$/i,"").replace(/_/g," ");r.libraryAssets[n].unshift({filename:a,displayName:l}),console.log(`[DEBUG] Added ${a} to registry category ${n}`)}}}}selectObject(e){this.handleObjectSelect(e),this.activeTab!=="inspector"&&(this.activeTab="inspector",this.updateWorkbenchTabs())}highlightChangesTab(){var t;let e=(t=this.container)==null?void 0:t.querySelector('[data-tab="changes"]');e&&e.classList.add("has-pending-changes")}getDebugOverlayHTML(){return`
1181
1083
  <div class="debug-overlay hidden" id="debug-overlay">
1182
1084
  <div class="debug-workbench" id="debug-workbench">
1183
1085
  <div class="workbench-header" id="workbench-handle">
@@ -1190,7 +1092,6 @@ Are you absolutely sure?`))try{let i=fn(),n={};for(let[a,s]of Object.entries(i.o
1190
1092
  </div>
1191
1093
  </div>
1192
1094
  <div class="workbench-tabs">
1193
- <button class="workbench-tab ${this.activeTab==="hierarchy"?"active":""}" data-tab="hierarchy">Hierarchy</button>
1194
1095
  <button class="workbench-tab ${this.activeTab==="inspector"?"active":""}" data-tab="inspector">Inspector</button>
1195
1096
  <button class="workbench-tab ${this.activeTab==="library"?"active":""}" data-tab="library">Library</button>
1196
1097
  <button class="workbench-tab ${this.activeTab==="ai"?"active":""}" data-tab="ai">\u2728 AI Suite</button>
@@ -1198,12 +1099,8 @@ Are you absolutely sure?`))try{let i=fn(),n={};for(let[a,s]of Object.entries(i.o
1198
1099
  <button class="workbench-tab ${this.activeTab==="changes"?"active":""}" data-tab="changes">\u{1F4BE} Changes</button>
1199
1100
  </div>
1200
1101
  <div class="workbench-content">
1201
- <div class="workbench-tab-panel ${this.activeTab==="hierarchy"?"active":""}" data-tab-panel="hierarchy">
1202
- ${this.sceneObjectsPanel.render()}
1203
- </div>
1204
1102
  <div class="workbench-tab-panel ${this.activeTab==="inspector"?"active":""}" data-tab-panel="inspector">
1205
1103
  ${this.inspectorPanel.render()}
1206
- ${this.sceneToolsPanel.render()}
1207
1104
  </div>
1208
1105
  <div class="workbench-tab-panel ${this.activeTab==="library"?"active":""}" data-tab-panel="library">
1209
1106
  ${this.libraryPanel.render()}
@@ -1221,8 +1118,14 @@ Are you absolutely sure?`))try{let i=fn(),n={};for(let[a,s]of Object.entries(i.o
1221
1118
  </div>
1222
1119
  <div class="workbench-resize-handle" id="workbench-resize"></div>
1223
1120
  </div>
1121
+
1122
+ <!-- Standalone Hierarchy Panel -->
1123
+ ${this.sceneObjectsPanel.render()}
1124
+
1125
+ <!-- Standalone Scene Tools Corner Panel -->
1126
+ ${this.sceneToolsPanel.render()}
1224
1127
  </div>
1225
- `}refresh(){this.isDebugOpen&&(this.sceneObjectsPanel.refreshObjects(),this.libraryPanel.refresh(),this.brandVisionPanel.refresh(),this.selectedObjectId&&this.handleObjectSelect(this.selectedObjectId))}toggleDebug(t){var i;this.isDebugOpen=t!=null?t:!this.isDebugOpen,(i=this.debugOverlay)==null||i.classList.toggle("hidden",!this.isDebugOpen),this.updateDebugBadge(),this.isDebugOpen?this.refresh():this.stopObjectVisuals()}updateDebugBadge(){if(!this.container)return;let t=this.container.querySelector("#debug-badge");t&&t.classList.toggle("active",this.isDebugOpen)}handleObjectSelect(t){this.selectedObjectId=t,this.sceneObjectsPanel.setSelected(t),this.inspectorPanel.loadObject(t),this.loadObjectConfig(t),this.startObjectVisuals()}nudgeSelectedObject(t,i){var u,p,f,g,h,m,b,y,v;if(!this.container||!this.selectedObjectId)return;let r=this.sceneToolsPanel.getNudgeStep(),a=this.container.querySelector("#config-pos-x"),s=this.container.querySelector("#config-pos-y"),o=Number((u=a==null?void 0:a.value)!=null?u:0),l=Number((p=s==null?void 0:s.value)!=null?p:0);if(!Number.isFinite(o)||!Number.isFinite(l)){let x=this.getSelectedObjectConfig();o=(h=(g=(f=x==null?void 0:x.transform)==null?void 0:f.position)==null?void 0:g.x)!=null?h:0,l=(y=(b=(m=x==null?void 0:x.transform)==null?void 0:m.position)==null?void 0:b.y)!=null?y:0}let c=o+t*r,d=l+i*r;a&&(a.value=String(c)),s&&(s.value=String(d)),(v=this.configViewer)==null||v.style.setProperty("display","block"),this.scheduleObjectAutoApply()}};function Hw(e){return new Promise((t,i)=>{let n=new FileReader;n.onerror=()=>i(new Error("FileReader failed")),n.onload=()=>t(String(n.result||"")),n.readAsDataURL(e)})}function Uw(e){var r;let[t,i]=e.split(","),n=t==null?void 0:t.match(/data:(.*?);base64/);return{base64:i!=null?i:"",mimeType:(r=n==null?void 0:n[1])!=null?r:"image/png"}}function qw(e){return`
1128
+ `}refresh(){this.isDebugOpen&&(this.sceneObjectsPanel.refreshObjects(),this.libraryPanel.refresh(),this.brandVisionPanel.refresh(),this.selectedObjectId&&this.handleObjectSelect(this.selectedObjectId))}toggleDebug(e){var t;this.isDebugOpen=e!=null?e:!this.isDebugOpen,(t=this.debugOverlay)==null||t.classList.toggle("hidden",!this.isDebugOpen),this.updateDebugBadge(),this.isDebugOpen?this.refresh():this.stopObjectVisuals()}updateDebugBadge(){if(!this.container)return;let e=this.container.querySelector("#debug-badge");e&&e.classList.toggle("active",this.isDebugOpen)}handleObjectSelect(e){this.selectedObjectId=e,this.sceneObjectsPanel.setSelected(e),this.inspectorPanel.loadObject(e),this.loadObjectConfig(e),this.startObjectVisuals()}nudgeSelectedObject(e,t){var d,u,g,h,f,m,b,y,v;if(!this.container||!this.selectedObjectId)return;let a=this.sceneToolsPanel.getNudgeStep(),s=this.container.querySelector("#config-pos-x"),r=this.container.querySelector("#config-pos-y"),o=Number((d=s==null?void 0:s.value)!=null?d:0),l=Number((u=r==null?void 0:r.value)!=null?u:0);if(!Number.isFinite(o)||!Number.isFinite(l)){let x=this.getSelectedObjectConfig();o=(f=(h=(g=x==null?void 0:x.transform)==null?void 0:g.position)==null?void 0:h.x)!=null?f:0,l=(y=(b=(m=x==null?void 0:x.transform)==null?void 0:m.position)==null?void 0:b.y)!=null?y:0}let c=o+e*a,p=l+t*a;s&&(s.value=String(c)),r&&(r.value=String(p)),(v=this.configViewer)==null||v.style.setProperty("display","block"),this.scheduleObjectAutoApply()}};function qo(i){return new Promise((e,t)=>{let n=new FileReader;n.onerror=()=>t(new Error("FileReader failed")),n.onload=()=>e(String(n.result||"")),n.readAsDataURL(i)})}function Vo(i){var a;let[e,t]=i.split(","),n=e==null?void 0:e.match(/data:(.*?);base64/);return{base64:t!=null?t:"",mimeType:(a=n==null?void 0:n[1])!=null?a:"image/png"}}function Wo(i){return`
1226
1129
  Analyze these screenshots of a brand or game and extract its "Brand DNA".
1227
1130
 
1228
1131
  Provide a concise summary (2-3 sentences) covering:
@@ -1236,12 +1139,12 @@ FORMAT:
1236
1139
  Summary: [Your summary here]
1237
1140
  Palette: [#RRGGBB, #RRGGBB, ...]
1238
1141
 
1239
- ${e?`
1142
+ ${i?`
1240
1143
  ADDITIONAL RULES/NOTES:
1241
- ${e}`:""}
1242
- `.trim()}function Cg(){let e=[],t="",i=null;return{async addSources(n){let r=[];for(let a of n){let s=await Hw(a),o=Uw(s),l={id:`${Date.now()}-${Math.random().toString(16).slice(2)}`,name:a.name,base64:o.base64,mimeType:o.mimeType,dataUrl:s};e.push(l),r.push(l)}return r},getSources(){return e.slice()},async analyze(n,r,a){if(e.length===0)throw new Error("No screenshots to analyze.");let s=qw(r),o=e.map(p=>({base64:p.base64,mimeType:p.mimeType})),l=await Wa(n,s,o,{model:a}),c=t,d=[],u=l.split(`
1243
- `);for(let p of u)if(p.toLowerCase().startsWith("summary:"))c=p.slice(8).trim();else if(p.toLowerCase().includes("palette:")){let f=p.match(/#[0-9A-Fa-f]{6}/g);f&&f.forEach(g=>{d.includes(g.toUpperCase())||d.push(g.toUpperCase())})}return(!c||c===t)&&(c=l.split(`
1244
- Palette:`)[0].replace(/^Summary:\s*/i,"").trim()),i={summary:c,palette:d.slice(0,10)},i},setSummary(n){t=n,i&&(i={...i,summary:n})},getResult(){return i}}}var ai="handler_api_key_";var Wi=class{static setKey(t,i,n){try{let r={key:this.encryptKey(i),created:Date.now(),lastUsed:Date.now(),label:n||t},a=`${ai}${t}`;localStorage.setItem(a,JSON.stringify(r))}catch(r){console.error("[ApiKeyStorage] Failed to store API key:",r)}}static getKey(t){try{let i=`${ai}${t}`,n=localStorage.getItem(i);if(!n)return null;let r=JSON.parse(n);return r.lastUsed=Date.now(),localStorage.setItem(i,JSON.stringify(r)),this.decryptKey(r.key)}catch(i){return console.error("[ApiKeyStorage] Failed to retrieve API key:",i),null}}static hasKey(t){let i=`${ai}${t}`;return localStorage.getItem(i)!==null}static removeKey(t){try{let i=`${ai}${t}`;localStorage.removeItem(i)}catch(i){console.error("[ApiKeyStorage] Failed to remove API key:",i)}}static getStoredServices(){let t=[];try{for(let i=0;i<localStorage.length;i++){let n=localStorage.key(i);if(n&&n.startsWith(ai)){let r=n.substring(ai.length),a=localStorage.getItem(n);if(a){let s=JSON.parse(a);t.push({service:r,label:s.label,created:s.created,lastUsed:s.lastUsed})}}}}catch(i){console.error("[ApiKeyStorage] Failed to get stored services:",i)}return t.sort((i,n)=>n.lastUsed-i.lastUsed)}static clearAll(){try{let t=[];for(let i=0;i<localStorage.length;i++){let n=localStorage.key(i);n&&n.startsWith(ai)&&t.push(n)}t.forEach(i=>localStorage.removeItem(i))}catch(t){console.error("[ApiKeyStorage] Failed to clear API keys:",t)}}static encryptKey(t){try{let n="handler_preview_salt_2024"+t;return btoa(n)}catch(i){return console.warn("[ApiKeyStorage] Encryption failed, storing as-is:",i),t}}static decryptKey(t){try{let i=atob(t),n="handler_preview_salt_2024";return i.startsWith(n)?i.substring(n.length):i}catch(i){return console.warn("[ApiKeyStorage] Decryption failed, returning as-is:",i),t}}},sc=()=>Wi.getKey("gemini"),oc=(e,t)=>Wi.setKey("gemini",e,t),Gw=()=>Wi.hasKey("gemini");window.ApiKeyStorage=Wi;window.getGeminiApiKey=sc;window.setGeminiApiKey=oc;window.hasGeminiApiKey=Gw;var cc=class{constructor(){this.modal=null;this.options=null;this.analyzer=Cg();this.currentPrompt="";this.isGenerating=!1;this.generatedImages=[];this.selectedImageIndex=-1;this.promptInput=null;this.generateBtn=null;this.loadingEl=null;this.galleryEl=null;this.previewEl=null}open(t){this.options=t,this.currentPrompt=t.initialPrompt||"",this.generatedImages=[],this.selectedImageIndex=-1,this.isGenerating=!1,this.createModal(),document.body.appendChild(this.modal),setTimeout(()=>{var i,n;(i=this.promptInput)==null||i.focus(),(n=this.promptInput)==null||n.select()},100)}createModal(){var i;let t=document.createElement("div");t.className="ai-modal",t.innerHTML=`
1144
+ ${i}`:""}
1145
+ `.trim()}function lr(){let i=[],e="",t=null;return{async addSources(n){let a=[];for(let s of n){let r=await qo(s),o=Vo(r),l={id:`${Date.now()}-${Math.random().toString(16).slice(2)}`,name:s.name,base64:o.base64,mimeType:o.mimeType,dataUrl:r};i.push(l),a.push(l)}return a},getSources(){return i.slice()},async analyze(n,a,s){if(i.length===0)throw new Error("No screenshots to analyze.");let r=Wo(a),o=i.map(u=>({base64:u.base64,mimeType:u.mimeType})),l=await _n(n,r,o,{model:s}),c=e,p=[],d=l.split(`
1146
+ `);for(let u of d)if(u.toLowerCase().startsWith("summary:"))c=u.slice(8).trim();else if(u.toLowerCase().includes("palette:")){let g=u.match(/#[0-9A-Fa-f]{6}/g);g&&g.forEach(h=>{p.includes(h.toUpperCase())||p.push(h.toUpperCase())})}return(!c||c===e)&&(c=l.split(`
1147
+ Palette:`)[0].replace(/^Summary:\s*/i,"").trim()),t={summary:c,palette:p.slice(0,10)},t},setSummary(n){e=n,t&&(t={...t,summary:n})},getResult(){return t}}}var He="handler_api_key_";var tt=class{static setKey(e,t,n){try{let a={key:this.encryptKey(t),created:Date.now(),lastUsed:Date.now(),label:n||e},s=`${He}${e}`;localStorage.setItem(s,JSON.stringify(a))}catch(a){console.error("[ApiKeyStorage] Failed to store API key:",a)}}static getKey(e){try{let t=`${He}${e}`,n=localStorage.getItem(t);if(!n)return null;let a=JSON.parse(n);return a.lastUsed=Date.now(),localStorage.setItem(t,JSON.stringify(a)),this.decryptKey(a.key)}catch(t){return console.error("[ApiKeyStorage] Failed to retrieve API key:",t),null}}static hasKey(e){let t=`${He}${e}`;return localStorage.getItem(t)!==null}static removeKey(e){try{let t=`${He}${e}`;localStorage.removeItem(t)}catch(t){console.error("[ApiKeyStorage] Failed to remove API key:",t)}}static getStoredServices(){let e=[];try{for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);if(n&&n.startsWith(He)){let a=n.substring(He.length),s=localStorage.getItem(n);if(s){let r=JSON.parse(s);e.push({service:a,label:r.label,created:r.created,lastUsed:r.lastUsed})}}}}catch(t){console.error("[ApiKeyStorage] Failed to get stored services:",t)}return e.sort((t,n)=>n.lastUsed-t.lastUsed)}static clearAll(){try{let e=[];for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);n&&n.startsWith(He)&&e.push(n)}e.forEach(t=>localStorage.removeItem(t))}catch(e){console.error("[ApiKeyStorage] Failed to clear API keys:",e)}}static encryptKey(e){try{let n="handler_preview_salt_2024"+e;return btoa(n)}catch(t){return console.warn("[ApiKeyStorage] Encryption failed, storing as-is:",t),e}}static decryptKey(e){try{let t=atob(e),n="handler_preview_salt_2024";return t.startsWith(n)?t.substring(n.length):t}catch(t){return console.warn("[ApiKeyStorage] Decryption failed, returning as-is:",t),e}}},ta=()=>tt.getKey("gemini"),na=(i,e)=>tt.setKey("gemini",i,e),Yo=()=>tt.hasKey("gemini");window.ApiKeyStorage=tt;window.getGeminiApiKey=ta;window.setGeminiApiKey=na;window.hasGeminiApiKey=Yo;var aa=class{constructor(){this.modal=null;this.options=null;this.analyzer=lr();this.currentPrompt="";this.isGenerating=!1;this.generatedImages=[];this.selectedImageIndex=-1;this.promptInput=null;this.generateBtn=null;this.loadingEl=null;this.galleryEl=null;this.previewEl=null}open(e){this.options=e,this.currentPrompt=e.initialPrompt||"",this.generatedImages=[],this.selectedImageIndex=-1,this.isGenerating=!1,this.createModal(),document.body.appendChild(this.modal),setTimeout(()=>{var t,n;(t=this.promptInput)==null||t.focus(),(n=this.promptInput)==null||n.select()},100)}createModal(){var t;let e=document.createElement("div");e.className="ai-modal",e.innerHTML=`
1245
1148
  <div class="ai-modal-card">
1246
1149
  <div class="ai-modal-header">
1247
1150
  <div class="ai-modal-actions">
@@ -1251,7 +1154,7 @@ Palette:`)[0].replace(/^Summary:\s*/i,"").trim()),i={summary:c,palette:d.slice(0
1251
1154
  </div>
1252
1155
  <div>
1253
1156
  <div class="ai-modal-title">AI Image Editor</div>
1254
- <div class="ai-modal-subtitle">${((i=this.options)==null?void 0:i.objectId)||"Unknown Object"}</div>
1157
+ <div class="ai-modal-subtitle">${((t=this.options)==null?void 0:t.objectId)||"Unknown Object"}</div>
1255
1158
  </div>
1256
1159
  <button class="ai-modal-close" type="button" data-action="close">\xD7</button>
1257
1160
  </div>
@@ -1320,41 +1223,41 @@ Palette:`)[0].replace(/^Summary:\s*/i,"").trim()),i={summary:c,palette:d.slice(0
1320
1223
  <button class="ai-btn primary" data-action="apply" disabled>Apply</button>
1321
1224
  </div>
1322
1225
  </div>
1323
- `,this.modal=t,this.attachEventListeners(),this.updatePromptFromDna()}attachEventListeners(){var n;if(!this.modal)return;this.promptInput=this.modal.querySelector(".ai-textarea"),this.generateBtn=this.modal.querySelector('[data-action="generate"]'),this.loadingEl=this.modal.querySelector("[data-loading]"),this.galleryEl=this.modal.querySelector("[data-gallery]"),this.previewEl=this.modal.querySelector("[data-preview]"),(n=this.promptInput)==null||n.addEventListener("input",()=>{var r;this.currentPrompt=((r=this.promptInput)==null?void 0:r.value)||"",this.updateGenerateButton()});let t=this.modal.querySelector('[data-strength="creativity"]'),i=this.modal.querySelector(".ai-strength-value");t==null||t.addEventListener("input",()=>{i.textContent=t.value}),this.modal.addEventListener("click",r=>{var o;let a=r.target;switch(a.dataset.action||((o=a.closest("[data-action]"))==null?void 0:o.getAttribute("data-action"))){case"generate":this.generateImage();break;case"apply":this.applySelectedImage();break;case"gallery":this.toggleGallery();break;case"close":case"cancel":this.close();break}}),this.modal.addEventListener("click",r=>{let a=r.target;if(a.classList.contains("ai-gallery-item")||a.closest(".ai-gallery-item")){let s=a.closest(".ai-gallery-item"),o=parseInt(s.dataset.index||"-1");o>=0&&this.selectImage(o)}}),this.modal.addEventListener("click",r=>{r.target===this.modal&&this.close()}),this.updateGenerateButton()}updateGenerateButton(){if(!this.generateBtn)return;let t=this.currentPrompt.trim().length>0;this.generateBtn.disabled=!t||this.isGenerating}async updatePromptFromDna(){var i;let t=(i=this.modal)==null?void 0:i.querySelector("#ai-use-dna");if(t!=null&&t.checked)try{let n=this.analyzer.getResult();if(n!=null&&n.summary&&this.promptInput){let r=`${this.currentPrompt}
1226
+ `,this.modal=e,this.attachEventListeners(),this.updatePromptFromDna()}attachEventListeners(){var n;if(!this.modal)return;this.promptInput=this.modal.querySelector(".ai-textarea"),this.generateBtn=this.modal.querySelector('[data-action="generate"]'),this.loadingEl=this.modal.querySelector("[data-loading]"),this.galleryEl=this.modal.querySelector("[data-gallery]"),this.previewEl=this.modal.querySelector("[data-preview]"),(n=this.promptInput)==null||n.addEventListener("input",()=>{var a;this.currentPrompt=((a=this.promptInput)==null?void 0:a.value)||"",this.updateGenerateButton()});let e=this.modal.querySelector('[data-strength="creativity"]'),t=this.modal.querySelector(".ai-strength-value");e==null||e.addEventListener("input",()=>{t.textContent=e.value}),this.modal.addEventListener("click",a=>{var o;let s=a.target;switch(s.dataset.action||((o=s.closest("[data-action]"))==null?void 0:o.getAttribute("data-action"))){case"generate":this.generateImage();break;case"apply":this.applySelectedImage();break;case"gallery":this.toggleGallery();break;case"close":case"cancel":this.close();break}}),this.modal.addEventListener("click",a=>{let s=a.target;if(s.classList.contains("ai-gallery-item")||s.closest(".ai-gallery-item")){let r=s.closest(".ai-gallery-item"),o=parseInt(r.dataset.index||"-1");o>=0&&this.selectImage(o)}}),this.modal.addEventListener("click",a=>{a.target===this.modal&&this.close()}),this.updateGenerateButton()}updateGenerateButton(){if(!this.generateBtn)return;let e=this.currentPrompt.trim().length>0;this.generateBtn.disabled=!e||this.isGenerating}async updatePromptFromDna(){var t;let e=(t=this.modal)==null?void 0:t.querySelector("#ai-use-dna");if(e!=null&&e.checked)try{let n=this.analyzer.getResult();if(n!=null&&n.summary&&this.promptInput){let a=`${this.currentPrompt}
1324
1227
 
1325
- Style guidelines: ${n.summary}`;this.promptInput.value=r,this.currentPrompt=r}}catch(n){console.warn("[AiEditorModal] Failed to apply brand DNA:",n)}}async generateImage(){var t,i,n,r;if(!(!this.options||this.isGenerating)){this.isGenerating=!0,this.updateGenerateButton(),(t=this.loadingEl)==null||t.classList.remove("hidden"),(i=this.previewEl)==null||i.classList.add("hidden");try{let a=this.getApiKey();if(!a){alert("Please set your Gemini API key first. You can do this in the AI Creative Suite panel.");return}let s=[];if(this.options.currentValue&&this.options.currentValue.startsWith("data:"))try{let c=await Ga(this.options.currentValue);c&&(s=[{base64:c.base64,mimeType:c.mimeType}])}catch(c){console.warn("[AiEditorModal] Failed to load current image:",c)}let o=await Gi(a,this.currentPrompt,s,{aspectRatio:"1:1"}),l=await qi(o);this.generatedImages.push(l||o),this.selectedImageIndex=this.generatedImages.length-1,this.updateGallery(),this.updatePreview(),this.updateApplyButton()}catch(a){console.error("[AiEditorModal] Generation failed:",a),alert(`Generation failed: ${a instanceof Error?a.message:"Unknown error"}`)}finally{this.isGenerating=!1,(n=this.loadingEl)==null||n.classList.add("hidden"),(r=this.previewEl)==null||r.classList.remove("hidden"),this.updateGenerateButton()}}}updateGallery(){if(!this.galleryEl)return;let t=this.galleryEl.querySelector("[data-gallery-grid]");t&&(t.innerHTML=this.generatedImages.map((i,n)=>`
1228
+ Style guidelines: ${n.summary}`;this.promptInput.value=a,this.currentPrompt=a}}catch(n){console.warn("[AiEditorModal] Failed to apply brand DNA:",n)}}async generateImage(){var e,t,n,a;if(!(!this.options||this.isGenerating)){this.isGenerating=!0,this.updateGenerateButton(),(e=this.loadingEl)==null||e.classList.remove("hidden"),(t=this.previewEl)==null||t.classList.add("hidden");try{let s=this.getApiKey();if(!s){alert("Please set your Gemini API key first. You can do this in the AI Creative Suite panel.");return}let r=[];if(this.options.currentValue&&this.options.currentValue.startsWith("data:"))try{let c=await Tn(this.options.currentValue);c&&(r=[{base64:c.base64,mimeType:c.mimeType}])}catch(c){console.warn("[AiEditorModal] Failed to load current image:",c)}let o=await et(s,this.currentPrompt,r,{aspectRatio:"1:1"}),l=await Qe(o);this.generatedImages.push(l||o),this.selectedImageIndex=this.generatedImages.length-1,this.updateGallery(),this.updatePreview(),this.updateApplyButton()}catch(s){console.error("[AiEditorModal] Generation failed:",s),alert(`Generation failed: ${s instanceof Error?s.message:"Unknown error"}`)}finally{this.isGenerating=!1,(n=this.loadingEl)==null||n.classList.add("hidden"),(a=this.previewEl)==null||a.classList.remove("hidden"),this.updateGenerateButton()}}}updateGallery(){if(!this.galleryEl)return;let e=this.galleryEl.querySelector("[data-gallery-grid]");e&&(e.innerHTML=this.generatedImages.map((t,n)=>`
1326
1229
  <div class="ai-gallery-item ${n===this.selectedImageIndex?"active":""}" data-index="${n}">
1327
- <img class="ai-gallery-thumb" src="${i}" alt="Generated ${n+1}" />
1230
+ <img class="ai-gallery-thumb" src="${t}" alt="Generated ${n+1}" />
1328
1231
  <div class="ai-gallery-label">#${n+1}</div>
1329
1232
  </div>
1330
- `).join(""))}updatePreview(){if(!this.previewEl||this.selectedImageIndex<0)return;let t=this.generatedImages[this.selectedImageIndex];this.previewEl.innerHTML=`<img src="${t}" alt="Selected image" />`}selectImage(t){t<0||t>=this.generatedImages.length||(this.selectedImageIndex=t,this.updateGallery(),this.updatePreview(),this.updateApplyButton())}toggleGallery(){this.galleryEl&&this.galleryEl.classList.toggle("hidden")}updateApplyButton(){var i;let t=(i=this.modal)==null?void 0:i.querySelector('[data-action="apply"]');t&&(t.disabled=this.selectedImageIndex<0)}applySelectedImage(){var i;if(this.selectedImageIndex<0||!((i=this.options)!=null&&i.onApply))return;let t=this.generatedImages[this.selectedImageIndex];this.options.onApply(t),this.close()}getApiKey(){let t=sc();if(t)return t;try{let i=this.analyzer.getResult();if(i&&i.apiKey)return oc(i.apiKey,"From Brand DNA"),i.apiKey}catch(i){console.warn("[AiEditorModal] Failed to get API key from brand DNA:",i)}return null}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),this.modal=null,this.options=null}},lc=null;window.__openAiEditor=function(e,t,i,n){lc||(lc=new cc),lc.open({objectId:e,initialPrompt:t,currentValue:i,path:n==null?void 0:n.path,onApply:r=>{if(n!=null&&n.path){let a=window.updateManager;if(a)a.updateProperty(e,n.path,r);else{let s=window.getEditableObjectConfig,o=s==null?void 0:s(e);if(o){let l=n.path.split("."),c=o;for(let d=0;d<l.length-1;d++)c[l[d]]||(c[l[d]]={}),c=c[l[d]];c[l[l.length-1]]=r}}}window.dispatchEvent(new CustomEvent("inspector:refresh"))}})};uc();var pc=class{constructor(){this.modal=null;this.options=null}open(t){this.options=t,this.createModal(),document.body.appendChild(this.modal)}createModal(){if(!this.options)return;let{assetPath:t,assetType:i,objectId:n}=this.options,r=n||"Asset Preview",a=document.createElement("div");a.className="asset-preview-modal",a.innerHTML=`
1233
+ `).join(""))}updatePreview(){if(!this.previewEl||this.selectedImageIndex<0)return;let e=this.generatedImages[this.selectedImageIndex];this.previewEl.innerHTML=`<img src="${e}" alt="Selected image" />`}selectImage(e){e<0||e>=this.generatedImages.length||(this.selectedImageIndex=e,this.updateGallery(),this.updatePreview(),this.updateApplyButton())}toggleGallery(){this.galleryEl&&this.galleryEl.classList.toggle("hidden")}updateApplyButton(){var t;let e=(t=this.modal)==null?void 0:t.querySelector('[data-action="apply"]');e&&(e.disabled=this.selectedImageIndex<0)}applySelectedImage(){var t;if(this.selectedImageIndex<0||!((t=this.options)!=null&&t.onApply))return;let e=this.generatedImages[this.selectedImageIndex];this.options.onApply(e),this.close()}getApiKey(){let e=ta();if(e)return e;try{let t=this.analyzer.getResult();if(t&&t.apiKey)return na(t.apiKey,"From Brand DNA"),t.apiKey}catch(t){console.warn("[AiEditorModal] Failed to get API key from brand DNA:",t)}return null}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),this.modal=null,this.options=null}},ia=null;window.__openAiEditor=function(i,e,t,n){ia||(ia=new aa),ia.open({objectId:i,initialPrompt:e,currentValue:t,path:n==null?void 0:n.path,onApply:a=>{if(n!=null&&n.path){let s=window.updateManager;if(s)s.updateProperty(i,n.path,a);else{let r=window.getEditableObjectConfig,o=r==null?void 0:r(i);if(o){let l=n.path.split("."),c=o;for(let p=0;p<l.length-1;p++)c[l[p]]||(c[l[p]]={}),c=c[l[p]];c[l[l.length-1]]=a}}}window.dispatchEvent(new CustomEvent("inspector:refresh"))}})};ra();var oa=class{constructor(){this.modal=null;this.options=null}open(e){this.options=e,this.createModal(),document.body.appendChild(this.modal)}createModal(){if(!this.options)return;let{assetPath:e,assetType:t,objectId:n}=this.options,a=n||"Asset Preview",s=document.createElement("div");s.className="asset-preview-modal",s.innerHTML=`
1331
1234
  <div class="asset-preview-card">
1332
1235
  <div class="asset-preview-header">
1333
- <div class="asset-preview-title">${r}</div>
1236
+ <div class="asset-preview-title">${a}</div>
1334
1237
  <button class="asset-preview-close" data-action="close">\xD7</button>
1335
1238
  </div>
1336
1239
 
1337
1240
  <div class="asset-preview-meta">
1338
- <div>Type: ${i.toUpperCase()}</div>
1339
- <div>Path: ${t||"None"}</div>
1241
+ <div>Type: ${t.toUpperCase()}</div>
1242
+ <div>Path: ${e||"None"}</div>
1340
1243
  </div>
1341
1244
 
1342
1245
  <div class="asset-preview-body">
1343
- ${this.renderAssetContent(t,i)}
1246
+ ${this.renderAssetContent(e,t)}
1344
1247
  </div>
1345
1248
 
1346
1249
  <div class="asset-preview-actions">
1347
1250
  <button class="asset-preview-change" data-action="change">Change Asset</button>
1348
- ${i==="image"?'<button class="asset-preview-ai" data-action="edit">\u2728 AI Edit</button>':""}
1251
+ ${t==="image"?'<button class="asset-preview-ai" data-action="edit">\u2728 AI Edit</button>':""}
1349
1252
  </div>
1350
1253
  </div>
1351
- `,this.modal=a,this.attachEventListeners()}renderAssetContent(t,i){if(!t)return'<div class="asset-preview-placeholder">No asset selected</div>';switch(i){case"image":return`<img src="${this.resolveAssetUrl(t)}" alt="Asset preview" style="max-width: 100%; max-height: 400px; object-fit: contain;" />`;case"audio":let r=this.resolveAssetUrl(t);return`
1254
+ `,this.modal=s,this.attachEventListeners()}renderAssetContent(e,t){if(!e)return'<div class="asset-preview-placeholder">No asset selected</div>';switch(t){case"image":return`<img src="${this.resolveAssetUrl(e)}" alt="Asset preview" style="max-width: 100%; max-height: 400px; object-fit: contain;" />`;case"audio":let a=this.resolveAssetUrl(e);return`
1352
1255
  <audio controls style="width: 100%;">
1353
- <source src="${r}" type="audio/mpeg">
1354
- <source src="${r}" type="audio/wav">
1256
+ <source src="${a}" type="audio/mpeg">
1257
+ <source src="${a}" type="audio/wav">
1355
1258
  Your browser does not support the audio element.
1356
1259
  </audio>
1357
- `;case"text":return`<pre style="background: rgba(0,0,0,0.2); padding: 16px; border-radius: 8px; max-height: 300px; overflow-y: auto; white-space: pre-wrap;">${t}</pre>`;default:return`<div class="asset-preview-placeholder">Cannot preview ${i} assets</div>`}}resolveAssetUrl(t){return t.startsWith("data:")||t.startsWith("blob:")||t.startsWith("/")?t:`/raw/${t}`}attachEventListeners(){if(!this.modal)return;this.modal.addEventListener("click",n=>{let r=n.target;(r.dataset.action==="close"||r===this.modal)&&this.close()});let t=this.modal.querySelector('[data-action="change"]');t&&t.addEventListener("click",()=>{this.openAssetEditor()});let i=this.modal.querySelector('[data-action="edit"]');i&&i.addEventListener("click",()=>{this.openAiEditor(),this.close()})}openAssetEditor(){this.options&&Promise.resolve().then(()=>(uc(),Tg)).then(({AssetEditorModal:t})=>{new t().show(this.options.objectId||"unknown",this.options.propertyPath||"",this.options.assetPath,n=>{var r;(r=this.options)!=null&&r.onChange&&this.options.onChange(n),this.close()})})}openAiEditor(){if(!this.options||this.options.assetType!=="image")return;let t=window.__openAiEditor;typeof t=="function"&&t(this.options.objectId||"asset","Edit this image asset",this.options.assetPath,{path:this.options.propertyPath,onApply:i=>{var n;(n=this.options)!=null&&n.onChange&&this.options.onChange(i)}})}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),this.modal=null,this.options=null}};window.openAssetPreview=function(e){new pc().open(e)};var fc=class{constructor(){this.modal=null;this.canvas=null;this.ctx=null;this.image=null;this.options=null;this.cropX=0;this.cropY=0;this.cropWidth=100;this.cropHeight=100;this.scale=1;this.panX=0;this.panY=0;this.isDragging=!1;this.dragStartX=0;this.dragStartY=0;this.lastPanX=0;this.lastPanY=0}open(t){this.options=t,this.createModal(),this.loadImage(),document.body.appendChild(this.modal)}createModal(){let t=document.createElement("div");t.className="asset-crop-modal",t.innerHTML=`
1260
+ `;case"text":return`<pre style="background: rgba(0,0,0,0.2); padding: 16px; border-radius: 8px; max-height: 300px; overflow-y: auto; white-space: pre-wrap;">${e}</pre>`;default:return`<div class="asset-preview-placeholder">Cannot preview ${t} assets</div>`}}resolveAssetUrl(e){return e.startsWith("data:")||e.startsWith("blob:")||e.startsWith("/")?e:`/raw/${e}`}attachEventListeners(){if(!this.modal)return;this.modal.addEventListener("click",n=>{let a=n.target;(a.dataset.action==="close"||a===this.modal)&&this.close()});let e=this.modal.querySelector('[data-action="change"]');e&&e.addEventListener("click",()=>{this.openAssetEditor()});let t=this.modal.querySelector('[data-action="edit"]');t&&t.addEventListener("click",()=>{this.openAiEditor(),this.close()})}openAssetEditor(){this.options&&Promise.resolve().then(()=>(ra(),cr)).then(({AssetEditorModal:e})=>{new e().show(this.options.objectId||"unknown",this.options.propertyPath||"",this.options.assetPath,n=>{var a;(a=this.options)!=null&&a.onChange&&this.options.onChange(n),this.close()})})}openAiEditor(){if(!this.options||this.options.assetType!=="image")return;let e=window.__openAiEditor;typeof e=="function"&&e(this.options.objectId||"asset","Edit this image asset",this.options.assetPath,{path:this.options.propertyPath,onApply:t=>{var n;(n=this.options)!=null&&n.onChange&&this.options.onChange(t)}})}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal),this.modal=null,this.options=null}};window.openAssetPreview=function(i){new oa().open(i)};var la=class{constructor(){this.modal=null;this.canvas=null;this.ctx=null;this.image=null;this.options=null;this.cropX=0;this.cropY=0;this.cropWidth=100;this.cropHeight=100;this.scale=1;this.panX=0;this.panY=0;this.isDragging=!1;this.dragStartX=0;this.dragStartY=0;this.lastPanX=0;this.lastPanY=0}open(e){this.options=e,this.createModal(),this.loadImage(),document.body.appendChild(this.modal)}createModal(){let e=document.createElement("div");e.className="asset-crop-modal",e.innerHTML=`
1358
1261
  <div class="asset-crop-card">
1359
1262
  <div class="asset-crop-header">
1360
1263
  <div>
@@ -1405,7 +1308,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=r,this.currentPrompt=r}}c
1405
1308
  <button class="asset-crop-apply primary" data-action="apply">Apply Crop</button>
1406
1309
  </div>
1407
1310
  </div>
1408
- `,this.modal=t,this.attachEventListeners(),this.initializeCanvas()}initializeCanvas(){this.modal&&(this.canvas=this.modal.querySelector(".asset-crop-canvas"),this.canvas&&(this.ctx=this.canvas.getContext("2d"),this.canvas.width=400,this.canvas.height=300))}loadImage(){this.options&&(this.image=new Image,this.image.crossOrigin="anonymous",this.image.onload=()=>{this.initializeCrop(),this.render()},this.image.src=this.options.imageSrc)}initializeCrop(){var n;if(!this.image||!this.canvas)return;let t=this.image.width/this.image.height,i=this.canvas.width/this.canvas.height;t>i?(this.cropHeight=this.image.height,this.cropWidth=this.cropHeight*i,this.cropX=(this.image.width-this.cropWidth)/2,this.cropY=0):(this.cropWidth=this.image.width,this.cropHeight=this.cropWidth/i,this.cropX=0,this.cropY=(this.image.height-this.cropHeight)/2),(n=this.options)!=null&&n.aspectRatio&&this.applyAspectRatio(this.options.aspectRatio),this.fitToCanvas()}applyAspectRatio(t){if(!this.image)return;let i=this.image.width/this.image.height,n=this.cropX+this.cropWidth/2,r=this.cropY+this.cropHeight/2;t>i?(this.cropWidth=Math.min(this.image.width,this.cropHeight*t),this.cropHeight=this.cropWidth/t):(this.cropHeight=Math.min(this.image.height,this.cropWidth/t),this.cropWidth=this.cropHeight*t),this.cropX=Math.max(0,Math.min(this.image.width-this.cropWidth,n-this.cropWidth/2)),this.cropY=Math.max(0,Math.min(this.image.height-this.cropHeight,r-this.cropHeight/2))}fitToCanvas(){if(!this.image||!this.canvas)return;let t=this.canvas.width/this.cropWidth,i=this.canvas.height/this.cropHeight;this.scale=Math.min(t,i)*.9,this.panX=(this.canvas.width-this.cropWidth*this.scale)/2,this.panY=(this.canvas.height-this.cropHeight*this.scale)/2}render(){!this.ctx||!this.image||!this.canvas||(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.save(),this.ctx.translate(this.panX,this.panY),this.ctx.scale(this.scale,this.scale),this.ctx.drawImage(this.image,-this.cropX,-this.cropY,this.image.width,this.image.height),this.ctx.restore(),this.drawCropOverlay(),this.updatePreview())}drawCropOverlay(){if(!this.ctx||!this.canvas)return;let t=this.panX,i=this.panY,n=this.cropWidth*this.scale,r=this.cropHeight*this.scale;this.ctx.fillStyle="rgba(0, 0, 0, 0.5)",this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height),this.ctx.clearRect(t,i,n,r),this.ctx.strokeStyle="#ffffff",this.ctx.lineWidth=2,this.ctx.strokeRect(t,i,n,r),this.ctx.fillStyle="#ffffff";let a=8;[[t,i],[t+n-a,i],[t,i+r-a],[t+n-a,i+r-a]].forEach(([o,l])=>{var c;(c=this.ctx)==null||c.fillRect(o,l,a,a)})}updatePreview(){if(!this.modal||!this.image)return;let t=this.modal.querySelector(".asset-crop-preview-canvas");if(!t)return;let i=t.getContext("2d");if(!i)return;let n=150;t.width=n,t.height=n;let r=n/this.cropWidth,a=n/this.cropHeight,s=Math.min(r,a),o=this.cropWidth*s,l=this.cropHeight*s,c=(n-o)/2,d=(n-l)/2;i.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,c,d,o,l)}attachEventListeners(){if(!this.modal||!this.canvas)return;this.canvas.addEventListener("mousedown",this.handleMouseDown.bind(this)),this.canvas.addEventListener("mousemove",this.handleMouseMove.bind(this)),this.canvas.addEventListener("mouseup",this.handleMouseUp.bind(this)),this.canvas.addEventListener("wheel",this.handleWheel.bind(this)),this.canvas.addEventListener("touchstart",this.handleTouchStart.bind(this)),this.canvas.addEventListener("touchmove",this.handleTouchMove.bind(this)),this.canvas.addEventListener("touchend",this.handleTouchEnd.bind(this));let t=this.modal.querySelector(".asset-crop-zoom-slider");t==null||t.addEventListener("input",n=>{let r=parseFloat(n.target.value);this.setZoom(r)});let i=this.modal.querySelector(".asset-crop-aspect-select");i==null||i.addEventListener("change",n=>{let r=n.target.value;this.setAspectRatio(r)}),this.modal.addEventListener("click",n=>{switch(n.target.dataset.action){case"reset":this.reset();break;case"apply":this.applyCrop();break;case"cancel":case"close":this.close();break}}),this.modal.addEventListener("click",n=>{n.target===this.modal&&this.close()})}handleMouseDown(t){this.isDragging=!0,this.dragStartX=t.clientX,this.dragStartY=t.clientY,this.lastPanX=this.panX,this.lastPanY=this.panY,this.canvas.style.cursor="grabbing"}handleMouseMove(t){if(!this.isDragging)return;let i=t.clientX-this.dragStartX,n=t.clientY-this.dragStartY;this.panX=this.lastPanX+i,this.panY=this.lastPanY+n,this.constrainPan(),this.render()}handleMouseUp(){this.isDragging=!1,this.canvas.style.cursor="grab"}handleWheel(t){t.preventDefault();let i=t.deltaY>0?.9:1.1;this.setZoom(this.scale*i)}handleTouchStart(t){t.touches.length===1&&(this.isDragging=!0,this.dragStartX=t.touches[0].clientX,this.dragStartY=t.touches[0].clientY,this.lastPanX=this.panX,this.lastPanY=this.panY)}handleTouchMove(t){if(!this.isDragging||t.touches.length!==1)return;t.preventDefault();let i=t.touches[0].clientX-this.dragStartX,n=t.touches[0].clientY-this.dragStartY;this.panX=this.lastPanX+i,this.panY=this.lastPanY+n,this.constrainPan(),this.render()}handleTouchEnd(){this.isDragging=!1}setZoom(t){this.scale=Math.max(.1,Math.min(3,t)),this.updateZoomUI(),this.constrainPan(),this.render()}setAspectRatio(t){let i;switch(t){case"1:1":i=1;break;case"4:3":i=4/3;break;case"16:9":i=16/9;break;case"3:2":i=3/2;break;default:i=void 0}i&&this.applyAspectRatio(i),this.fitToCanvas(),this.render()}updateZoomUI(){if(!this.modal)return;let t=this.modal.querySelector(".asset-crop-zoom-value"),i=this.modal.querySelector(".asset-crop-zoom-slider");t&&(t.textContent=`${this.scale.toFixed(1)}x`),i&&(i.value=this.scale.toString())}constrainPan(){if(!this.canvas)return;let t=this.cropWidth*this.scale,i=this.cropHeight*this.scale;this.panX=Math.max(this.canvas.width-t,Math.min(0,this.panX)),this.panY=Math.max(this.canvas.height-i,Math.min(0,this.panY))}reset(){this.initializeCrop(),this.render()}applyCrop(){var r;if(!this.image||!((r=this.options)!=null&&r.onCrop))return;let t=document.createElement("canvas"),i=t.getContext("2d");if(!i)return;t.width=this.cropWidth,t.height=this.cropHeight,i.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,0,0,this.cropWidth,this.cropHeight);let n=t.toDataURL("image/png");this.options.onCrop(n),this.close()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal);let t=this.options;this.modal=null,this.canvas=null,this.ctx=null,this.image=null,this.options=null,t!=null&&t.onCancel&&t.onCancel()}};window.openAssetCrop=function(e){new fc().open(e)};var ns=class{constructor(t={}){this.isLandscape=!1;this.autoScale=1;this.userScaleMultiplier=1;this.viewMode="single";this.comparePresets=[Ut("playable-portrait"),Ut("iphone-14"),Ut("ipad-mini")];this.activeCompareId="playable-portrait";this.compareViewports=new Map;this.resizeObserver=null;this.rafFitHandle=null;this.ignoreNextWindowResize=!1;this.frameDragOffsetX=0;this.frameDragOffsetY=0;this.frameDragActive=!1;this.frameDragStartX=0;this.frameDragStartY=0;this.frameDragOriginX=0;this.frameDragOriginY=0;this.consolePanel=null;this.consoleMessages=[];this.isConsoleOpen=!1;this.hasInitialFit=!1;this.isMounted=!1;this.isInitialized=!1;this.gameReady=!1;this.resizeListenersDisabled=!1;this.compareSnapshotTimer=null;this.onWindowResize=t=>{if(this.ignoreNextWindowResize){this.ignoreNextWindowResize=!1;return}this.resizeListenersDisabled||!this.gameReady||this.scheduleFit()};this.onFrameDragMove=t=>{if(!this.frameDragActive)return;let i=t.clientX-this.frameDragStartX,n=t.clientY-this.frameDragStartY;this.frameDragOffsetX=this.frameDragOriginX+i,this.frameDragOffsetY=this.frameDragOriginY+n,this.applyFrameDrag()};this.onFrameDragEnd=()=>{this.frameDragActive&&(this.frameDragActive=!1,window.removeEventListener("pointermove",this.onFrameDragMove),window.removeEventListener("pointerup",this.onFrameDragEnd))};this.options=t,this.currentPreset=Ut(t.defaultDevice||Nr.id),this.debugPanel=new rr,this.container=this.createShell(),this.previewContainer=this.mustQuery(".preview-container"),this.singleStage=this.mustQuery('[data-preview-stage="single"]'),this.compareStage=this.mustQuery('[data-preview-stage="compare"]'),this.frameDragger=this.mustQuery(".frame-dragger"),this.frameWrapper=this.mustQuery(".frame-wrapper"),this.deviceFrame=this.mustQuery(".device-frame"),this.gameContainer=this.mustQuery(".game-container"),this.lastSinglePresetId=this.currentPreset.id,this.consolePanel=this.container.querySelector(".console-panel"),this.debugPanel.initialize(this.container),this.debugPanel.setupDebugEventListeners(),this.applyDeviceFrameStyles(),this.setupCompareViewports(),this.setupConsoleInterceptor(),this.setupObserversAndListeners(),this.setupFrameDragging(),this.setDevice(this.currentPreset.id,{suppressCallback:!0}),this.isInitialized=!0}mount(t=document.body){t.innerHTML="",t.appendChild(this.container),this.isMounted=!0,this.scheduleFit()}destroy(){if(this.disableResizeListeners(),this.resizeObserver){try{this.resizeObserver.disconnect()}catch{}this.resizeObserver=null}window.removeEventListener("resize",this.onWindowResize),this.rafFitHandle&&(cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=null),this.compareSnapshotTimer&&(window.clearInterval(this.compareSnapshotTimer),this.compareSnapshotTimer=null),this.gameReady=!1}getGameContainer(){return this.gameContainer}getScreen(){let t=this.getEffectivePreset();return{width:t.width,height:t.height}}getEffectivePreset(){var t;return this.isLandscape?{...this.currentPreset,width:this.currentPreset.height,height:this.currentPreset.width,ratio:((t=this.currentPreset.ratio)==null?void 0:t.split(":").reverse().join(":"))||this.currentPreset.ratio}:this.currentPreset}notifyGameLoaded(){this.gameReady=!0,this.enableResizeListeners(),this.scheduleFit(),this.debugPanel.refresh()}notifyGameDestroyed(){this.gameReady=!1,this.disableResizeListeners()}disableResizeListeners(){this.resizeListenersDisabled=!0,this.rafFitHandle&&(cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=null)}enableResizeListeners(){this.resizeListenersDisabled=!1}refresh(){this.options.onRefresh?this.options.onRefresh():window.location.reload()}setDevice(t,i={}){var r,a;let n=this.autoScale*this.userScaleMultiplier;this.isLandscape=!1,this.currentPreset=Ut(t),this.viewMode==="single"&&(this.lastSinglePresetId=this.currentPreset.id),this.applyPresetDimensions(),this.fitToScreen({keepVisibleScale:n}),i.suppressCallback||(a=(r=this.options).onDeviceChange)==null||a.call(r,this.getEffectivePreset()),this.emitScreenChange()}createShell(){var i;let t=document.createElement("div");return t.className="preview-shell",t.innerHTML=`
1311
+ `,this.modal=e,this.attachEventListeners(),this.initializeCanvas()}initializeCanvas(){this.modal&&(this.canvas=this.modal.querySelector(".asset-crop-canvas"),this.canvas&&(this.ctx=this.canvas.getContext("2d"),this.canvas.width=400,this.canvas.height=300))}loadImage(){this.options&&(this.image=new Image,this.image.crossOrigin="anonymous",this.image.onload=()=>{this.initializeCrop(),this.render()},this.image.src=this.options.imageSrc)}initializeCrop(){var n;if(!this.image||!this.canvas)return;let e=this.image.width/this.image.height,t=this.canvas.width/this.canvas.height;e>t?(this.cropHeight=this.image.height,this.cropWidth=this.cropHeight*t,this.cropX=(this.image.width-this.cropWidth)/2,this.cropY=0):(this.cropWidth=this.image.width,this.cropHeight=this.cropWidth/t,this.cropX=0,this.cropY=(this.image.height-this.cropHeight)/2),(n=this.options)!=null&&n.aspectRatio&&this.applyAspectRatio(this.options.aspectRatio),this.fitToCanvas()}applyAspectRatio(e){if(!this.image)return;let t=this.image.width/this.image.height,n=this.cropX+this.cropWidth/2,a=this.cropY+this.cropHeight/2;e>t?(this.cropWidth=Math.min(this.image.width,this.cropHeight*e),this.cropHeight=this.cropWidth/e):(this.cropHeight=Math.min(this.image.height,this.cropWidth/e),this.cropWidth=this.cropHeight*e),this.cropX=Math.max(0,Math.min(this.image.width-this.cropWidth,n-this.cropWidth/2)),this.cropY=Math.max(0,Math.min(this.image.height-this.cropHeight,a-this.cropHeight/2))}fitToCanvas(){if(!this.image||!this.canvas)return;let e=this.canvas.width/this.cropWidth,t=this.canvas.height/this.cropHeight;this.scale=Math.min(e,t)*.9,this.panX=(this.canvas.width-this.cropWidth*this.scale)/2,this.panY=(this.canvas.height-this.cropHeight*this.scale)/2}render(){!this.ctx||!this.image||!this.canvas||(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.save(),this.ctx.translate(this.panX,this.panY),this.ctx.scale(this.scale,this.scale),this.ctx.drawImage(this.image,-this.cropX,-this.cropY,this.image.width,this.image.height),this.ctx.restore(),this.drawCropOverlay(),this.updatePreview())}drawCropOverlay(){if(!this.ctx||!this.canvas)return;let e=this.panX,t=this.panY,n=this.cropWidth*this.scale,a=this.cropHeight*this.scale;this.ctx.fillStyle="rgba(0, 0, 0, 0.5)",this.ctx.fillRect(0,0,this.canvas.width,this.canvas.height),this.ctx.clearRect(e,t,n,a),this.ctx.strokeStyle="#ffffff",this.ctx.lineWidth=2,this.ctx.strokeRect(e,t,n,a),this.ctx.fillStyle="#ffffff";let s=8;[[e,t],[e+n-s,t],[e,t+a-s],[e+n-s,t+a-s]].forEach(([o,l])=>{var c;(c=this.ctx)==null||c.fillRect(o,l,s,s)})}updatePreview(){if(!this.modal||!this.image)return;let e=this.modal.querySelector(".asset-crop-preview-canvas");if(!e)return;let t=e.getContext("2d");if(!t)return;let n=150;e.width=n,e.height=n;let a=n/this.cropWidth,s=n/this.cropHeight,r=Math.min(a,s),o=this.cropWidth*r,l=this.cropHeight*r,c=(n-o)/2,p=(n-l)/2;t.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,c,p,o,l)}attachEventListeners(){if(!this.modal||!this.canvas)return;this.canvas.addEventListener("mousedown",this.handleMouseDown.bind(this)),this.canvas.addEventListener("mousemove",this.handleMouseMove.bind(this)),this.canvas.addEventListener("mouseup",this.handleMouseUp.bind(this)),this.canvas.addEventListener("wheel",this.handleWheel.bind(this)),this.canvas.addEventListener("touchstart",this.handleTouchStart.bind(this)),this.canvas.addEventListener("touchmove",this.handleTouchMove.bind(this)),this.canvas.addEventListener("touchend",this.handleTouchEnd.bind(this));let e=this.modal.querySelector(".asset-crop-zoom-slider");e==null||e.addEventListener("input",n=>{let a=parseFloat(n.target.value);this.setZoom(a)});let t=this.modal.querySelector(".asset-crop-aspect-select");t==null||t.addEventListener("change",n=>{let a=n.target.value;this.setAspectRatio(a)}),this.modal.addEventListener("click",n=>{switch(n.target.dataset.action){case"reset":this.reset();break;case"apply":this.applyCrop();break;case"cancel":case"close":this.close();break}}),this.modal.addEventListener("click",n=>{n.target===this.modal&&this.close()})}handleMouseDown(e){this.isDragging=!0,this.dragStartX=e.clientX,this.dragStartY=e.clientY,this.lastPanX=this.panX,this.lastPanY=this.panY,this.canvas.style.cursor="grabbing"}handleMouseMove(e){if(!this.isDragging)return;let t=e.clientX-this.dragStartX,n=e.clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+n,this.constrainPan(),this.render()}handleMouseUp(){this.isDragging=!1,this.canvas.style.cursor="grab"}handleWheel(e){e.preventDefault();let t=e.deltaY>0?.9:1.1;this.setZoom(this.scale*t)}handleTouchStart(e){e.touches.length===1&&(this.isDragging=!0,this.dragStartX=e.touches[0].clientX,this.dragStartY=e.touches[0].clientY,this.lastPanX=this.panX,this.lastPanY=this.panY)}handleTouchMove(e){if(!this.isDragging||e.touches.length!==1)return;e.preventDefault();let t=e.touches[0].clientX-this.dragStartX,n=e.touches[0].clientY-this.dragStartY;this.panX=this.lastPanX+t,this.panY=this.lastPanY+n,this.constrainPan(),this.render()}handleTouchEnd(){this.isDragging=!1}setZoom(e){this.scale=Math.max(.1,Math.min(3,e)),this.updateZoomUI(),this.constrainPan(),this.render()}setAspectRatio(e){let t;switch(e){case"1:1":t=1;break;case"4:3":t=4/3;break;case"16:9":t=16/9;break;case"3:2":t=3/2;break;default:t=void 0}t&&this.applyAspectRatio(t),this.fitToCanvas(),this.render()}updateZoomUI(){if(!this.modal)return;let e=this.modal.querySelector(".asset-crop-zoom-value"),t=this.modal.querySelector(".asset-crop-zoom-slider");e&&(e.textContent=`${this.scale.toFixed(1)}x`),t&&(t.value=this.scale.toString())}constrainPan(){if(!this.canvas)return;let e=this.cropWidth*this.scale,t=this.cropHeight*this.scale;this.panX=Math.max(this.canvas.width-e,Math.min(0,this.panX)),this.panY=Math.max(this.canvas.height-t,Math.min(0,this.panY))}reset(){this.initializeCrop(),this.render()}applyCrop(){var a;if(!this.image||!((a=this.options)!=null&&a.onCrop))return;let e=document.createElement("canvas"),t=e.getContext("2d");if(!t)return;e.width=this.cropWidth,e.height=this.cropHeight,t.drawImage(this.image,this.cropX,this.cropY,this.cropWidth,this.cropHeight,0,0,this.cropWidth,this.cropHeight);let n=e.toDataURL("image/png");this.options.onCrop(n),this.close()}close(){this.modal&&this.modal.parentNode&&this.modal.parentNode.removeChild(this.modal);let e=this.options;this.modal=null,this.canvas=null,this.ctx=null,this.image=null,this.options=null,e!=null&&e.onCancel&&e.onCancel()}};window.openAssetCrop=function(i){new la().open(i)};var Nn=class{constructor(e={}){this.isLandscape=!1;this.autoScale=1;this.userScaleMultiplier=1;this.viewMode="single";this.comparePresets=[ze("playable-portrait"),ze("iphone-14"),ze("ipad-mini")];this.activeCompareId="playable-portrait";this.compareViewports=new Map;this.resizeObserver=null;this.rafFitHandle=null;this.ignoreNextWindowResize=!1;this.frameDragOffsetX=0;this.frameDragOffsetY=0;this.frameDragActive=!1;this.frameDragStartX=0;this.frameDragStartY=0;this.frameDragOriginX=0;this.frameDragOriginY=0;this.isSpaceKeyPressed=!1;this.consolePanel=null;this.consoleMessages=[];this.isConsoleOpen=!1;this.hasInitialFit=!1;this.isMounted=!1;this.isInitialized=!1;this.gameReady=!1;this.resizeListenersDisabled=!1;this.compareSnapshotTimer=null;this.onWindowResize=e=>{if(this.ignoreNextWindowResize){this.ignoreNextWindowResize=!1;return}this.resizeListenersDisabled||!this.gameReady||this.scheduleFit()};this.onFrameDragMove=e=>{if(!this.frameDragActive)return;let t=e.clientX-this.frameDragStartX,n=e.clientY-this.frameDragStartY;this.frameDragOffsetX=this.frameDragOriginX+t,this.frameDragOffsetY=this.frameDragOriginY+n,this.applyFrameDrag(),this.updateDragCursor()};this.onFrameDragEnd=()=>{this.frameDragActive&&(this.frameDragActive=!1,window.removeEventListener("pointermove",this.onFrameDragMove),window.removeEventListener("pointerup",this.onFrameDragEnd),this.updateDragCursor())};this.options=e,this.currentPreset=ze(e.defaultDevice||pn.id),this.debugPanel=new Mt,this.container=this.createShell(),this.previewContainer=this.mustQuery(".preview-container"),this.singleStage=this.mustQuery('[data-preview-stage="single"]'),this.compareStage=this.mustQuery('[data-preview-stage="compare"]'),this.frameDragger=this.mustQuery(".frame-dragger"),this.frameWrapper=this.mustQuery(".frame-wrapper"),this.deviceFrame=this.mustQuery(".device-frame"),this.gameContainer=this.mustQuery(".game-container"),this.lastSinglePresetId=this.currentPreset.id,this.consolePanel=this.container.querySelector(".console-panel"),this.debugPanel.initialize(this.container),this.debugPanel.setupDebugEventListeners(),this.applyDeviceFrameStyles(),this.setupCompareViewports(),this.setupConsoleInterceptor(),this.setupObserversAndListeners(),this.setupFrameDragging(),this.setupSpaceKeyListener(),this.setDevice(this.currentPreset.id,{suppressCallback:!0}),this.isInitialized=!0}mount(e=document.body){e.innerHTML="",e.appendChild(this.container),this.isMounted=!0,this.scheduleFit()}destroy(){if(this.disableResizeListeners(),this.resizeObserver){try{this.resizeObserver.disconnect()}catch{}this.resizeObserver=null}window.removeEventListener("resize",this.onWindowResize),this.rafFitHandle&&(cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=null),this.compareSnapshotTimer&&(window.clearInterval(this.compareSnapshotTimer),this.compareSnapshotTimer=null),this.gameReady=!1}getGameContainer(){return this.gameContainer}getScreen(){let e=this.getEffectivePreset();return{width:e.width,height:e.height}}getEffectivePreset(){var e;return this.isLandscape?{...this.currentPreset,width:this.currentPreset.height,height:this.currentPreset.width,ratio:((e=this.currentPreset.ratio)==null?void 0:e.split(":").reverse().join(":"))||this.currentPreset.ratio}:this.currentPreset}notifyGameLoaded(){this.gameReady=!0,this.enableResizeListeners(),this.scheduleFit(),this.debugPanel.refresh()}notifyGameDestroyed(){this.gameReady=!1,this.disableResizeListeners()}disableResizeListeners(){this.resizeListenersDisabled=!0,this.rafFitHandle&&(cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=null)}enableResizeListeners(){this.resizeListenersDisabled=!1}refresh(){this.options.onRefresh?this.options.onRefresh():window.location.reload()}setDevice(e,t={}){var a,s;let n=this.autoScale*this.userScaleMultiplier;this.isLandscape=!1,this.currentPreset=ze(e),this.viewMode==="single"&&(this.lastSinglePresetId=this.currentPreset.id),this.applyPresetDimensions(),this.fitToScreen({keepVisibleScale:n}),t.suppressCallback||(s=(a=this.options).onDeviceChange)==null||s.call(a,this.getEffectivePreset()),this.emitScreenChange()}createShell(){var t;let e=document.createElement("div");return e.className="preview-shell",e.innerHTML=`
1409
1312
  <div class="preview-toolbar">
1410
1313
  <div class="preview-toolbar-left">
1411
1314
  <span class="preview-logo">PREVIEWER</span>
@@ -1414,11 +1317,11 @@ Style guidelines: ${n.summary}`;this.promptInput.value=r,this.currentPrompt=r}}c
1414
1317
  <div class="preview-toolbar-center">
1415
1318
  <div class="device-selector-wrapper">
1416
1319
  <select class="device-dropdown" id="device-select">
1417
- ${Vs.map(n=>`
1320
+ ${Pi.map(n=>`
1418
1321
  <optgroup label="${n.label}">
1419
- ${n.devices.map(r=>`
1420
- <option value="${r.id}" ${r.id===this.currentPreset.id?"selected":""}>
1421
- ${r.label} (${r.width}\xD7${r.height})
1322
+ ${n.devices.map(a=>`
1323
+ <option value="${a.id}" ${a.id===this.currentPreset.id?"selected":""}>
1324
+ ${a.label} (${a.width}\xD7${a.height})
1422
1325
  </option>
1423
1326
  `).join("")}
1424
1327
  </optgroup>
@@ -1507,7 +1410,27 @@ Style guidelines: ${n.summary}`;this.promptInput.value=r,this.currentPrompt=r}}c
1507
1410
  </div>
1508
1411
  </div>
1509
1412
 
1510
- ${((i=this.debugPanel)==null?void 0:i.getDebugOverlayHTML())||""}
1413
+ <!-- Corner Controls -->
1414
+ <div class="preview-corner-controls">
1415
+ <button class="corner-control-btn" id="corner-grab-btn" title="Hold Space to drag preview">
1416
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1417
+ <path d="M9 11V6a2 2 0 0 1 4 0v5M9 11a2 2 0 1 0-4 0v5a6 6 0 0 0 12 0v-3a2 2 0 1 0-4 0M9 11h4"/>
1418
+ </svg>
1419
+ </button>
1420
+ <button class="corner-control-btn" id="corner-zoom-out-btn" title="Zoom Out">
1421
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1422
+ <line x1="5" y1="12" x2="19" y2="12"></line>
1423
+ </svg>
1424
+ </button>
1425
+ <button class="corner-control-btn" id="corner-zoom-in-btn" title="Zoom In">
1426
+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
1427
+ <line x1="12" y1="5" x2="12" y2="19"></line>
1428
+ <line x1="5" y1="12" x2="19" y2="12"></line>
1429
+ </svg>
1430
+ </button>
1431
+ </div>
1432
+
1433
+ ${((t=this.debugPanel)==null?void 0:t.getDebugOverlayHTML())||""}
1511
1434
 
1512
1435
  <div class="console-panel closed">
1513
1436
  <div class="console-header">
@@ -1520,7 +1443,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=r,this.currentPrompt=r}}c
1520
1443
  <div class="console-messages" id="console-messages"></div>
1521
1444
  </div>
1522
1445
  </div>
1523
- `,this.setupEventListeners(t),t}setupEventListeners(t){var r,a,s,o,l,c,d;let i=t.querySelector("#device-select");i==null||i.addEventListener("change",u=>{if(this.viewMode==="compare")return;let p=u.target.value;this.setDevice(p)}),Array.from(t.querySelectorAll("[data-view-toggle]")).forEach(u=>{u.addEventListener("click",()=>{let p=u.dataset.viewToggle;p&&this.setViewMode(p)})}),(r=t.querySelector("#rotate-btn"))==null||r.addEventListener("click",()=>this.toggleRotation()),(a=t.querySelector("#zoom-in-btn"))==null||a.addEventListener("click",()=>this.adjustUserZoom(.1)),(s=t.querySelector("#zoom-out-btn"))==null||s.addEventListener("click",()=>this.adjustUserZoom(-.1)),(o=t.querySelector("#refresh-btn"))==null||o.addEventListener("click",()=>this.refresh()),(l=t.querySelector("#console-toggle"))==null||l.addEventListener("click",()=>this.toggleConsole()),(c=t.querySelector("#console-close"))==null||c.addEventListener("click",()=>this.toggleConsole(!1)),(d=t.querySelector("#console-clear"))==null||d.addEventListener("click",()=>this.clearConsole())}applyDeviceFrameStyles(){Object.assign(this.frameDragger.style,{display:"flex",justifyContent:"center",alignItems:"center",transform:"translate(0px, 0px)",touchAction:"none"}),Object.assign(this.frameWrapper.style,{display:"flex",justifyContent:"center",alignItems:"center",transformOrigin:"center center",transition:"transform 0.2s cubic-bezier(0.25, 0.46, 0.45, 0.94)",boxShadow:"0 20px 50px rgba(0,0,0,0.5)",borderRadius:"0px",willChange:"transform"}),Object.assign(this.deviceFrame.style,{overflow:"hidden",position:"relative",borderRadius:"0px"}),Object.assign(this.gameContainer.style,{position:"relative",overflow:"hidden",minWidth:"0px",minHeight:"0px"})}setupObserversAndListeners(){this.resizeObserver=new ResizeObserver(()=>{this.resizeListenersDisabled||!this.gameReady||this.scheduleFit()}),this.resizeObserver.observe(this.previewContainer),window.addEventListener("resize",this.onWindowResize,{passive:!0})}scheduleFit(){this.rafFitHandle&&cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=requestAnimationFrame(()=>{this.rafFitHandle=null,this.fitToScreen()})}applyPresetDimensions(){let t=this.getEffectivePreset(),i=`${t.width}px`,n=`${t.height}px`;this.deviceFrame.style.width=i,this.deviceFrame.style.height=n,this.gameContainer.style.width=i,this.gameContainer.style.height=n,this.gameContainer.style.maxWidth=i,this.gameContainer.style.maxHeight=n,this.gameContainer.style.minWidth=i,this.gameContainer.style.minHeight=n,this.gameContainer.dataset.screenWidth=String(t.width),this.gameContainer.dataset.screenHeight=String(t.height),this.container.style.setProperty("--preview-screen-width",String(t.width)),this.container.style.setProperty("--preview-screen-height",String(t.height))}fitToScreen(t){if(!this.previewContainer)return;let i=this.getEffectivePreset(),n=this.getFitBounds(),r=Math.max(0,n.width),a=Math.max(0,n.height);if(r<=0||a<=0)return;this.applyPresetDimensions(),this.viewMode==="compare"&&this.applyCompareDimensions();let s=r/i.width,o=a/i.height;if(this.autoScale=Math.max(.01,Math.min(s,o)),!this.hasInitialFit){this.hasInitialFit=!0;let l=.6;this.userScaleMultiplier=l/this.autoScale}t!=null&&t.keepVisibleScale&&t.keepVisibleScale>0&&(this.userScaleMultiplier=t.keepVisibleScale/this.autoScale),this.applyTransform(),this.viewMode==="compare"&&this.fitCompareGhosts(),this.emitScreenChange()}applyTransform(){let t=this.autoScale*this.userScaleMultiplier;this.frameWrapper.style.transform=`scale(${t})`;let i=this.container.querySelector("#zoom-label");i&&(i.textContent=`${Math.round(t*100)}%`)}applyFrameDrag(){this.frameDragger.style.transform=`translate(${this.frameDragOffsetX}px, ${this.frameDragOffsetY}px)`}setupFrameDragging(){this.frameDragger.addEventListener("pointerdown",t=>{this.gameContainer.contains(t.target)||t.button===0&&(t.preventDefault(),this.frameDragActive=!0,this.frameDragStartX=t.clientX,this.frameDragStartY=t.clientY,this.frameDragOriginX=this.frameDragOffsetX,this.frameDragOriginY=this.frameDragOffsetY,window.addEventListener("pointermove",this.onFrameDragMove),window.addEventListener("pointerup",this.onFrameDragEnd))})}adjustUserZoom(t){this.userScaleMultiplier=Math.max(.1,Math.min(6,this.userScaleMultiplier+t)),this.applyTransform(),this.emitScreenChange()}toggleRotation(){var i,n;if(this.viewMode==="compare")return;let t=this.autoScale*this.userScaleMultiplier;this.isLandscape=!this.isLandscape,this.applyPresetDimensions(),this.fitToScreen({keepVisibleScale:t}),(n=(i=this.options).onDeviceChange)==null||n.call(i,this.getEffectivePreset()),this.emitScreenChange()}emitScreenChange(){if(!this.gameReady)return;let t=this.getEffectivePreset(),i={width:t.width,height:t.height,dpr:Math.max(1,Math.floor(window.devicePixelRatio||1)),presetId:t.id,isLandscape:this.isLandscape};if(window.dispatchEvent(new CustomEvent("handler-preview:screen",{detail:i})),this.viewMode==="compare"&&this.refreshCompareSnapshots(),this.isInitialized&&this.isMounted&&this.gameReady){let n=window.gameApp;if(!(n!=null&&n.renderer))return;this.ignoreNextWindowResize=!0,window.dispatchEvent(new Event("resize"))}}safeStringify(t){var n;let i=new WeakSet;try{return JSON.stringify(t,(r,a)=>{if(typeof a=="object"&&a!==null){if(i.has(a))return"[Circular]";i.add(a)}return a},2)}catch{try{if(t&&((n=t.constructor)!=null&&n.name))return`[object ${t.constructor.name}]`}catch{}return String(t)}}setupConsoleInterceptor(){let t=console.log.bind(console),i=console.warn.bind(console),n=console.error.bind(console),r=console.info.bind(console),a=(s,...o)=>{let l=o.map(d=>typeof d=="object"?this.safeStringify(d):String(d)).join(" ");this.consoleMessages.push({type:s,message:l,timestamp:new Date}),this.appendConsoleMessage(this.consoleMessages[this.consoleMessages.length-1]);let c=this.container.querySelector("#console-badge");if(c){let d=this.consoleMessages.filter(u=>u.type==="error").length;c.textContent=d>0?`${d}!`:"0",c.classList.toggle("has-errors",d>0)}};console.log=(...s)=>{t(...s),a("log",...s)},console.warn=(...s)=>{i(...s),a("warn",...s)},console.error=(...s)=>{n(...s),a("error",...s)},console.info=(...s)=>{r(...s),a("info",...s)}}appendConsoleMessage(t){let i=this.container.querySelector("#console-messages");if(!i)return;let n=document.createElement("div");n.className=`console-msg type-${t.type}`;let r=t.timestamp.toLocaleTimeString();n.innerHTML=`<span class="time">${this.escapeHtml(r)}</span> <pre>${this.escapeHtml(t.message)}</pre>`,i.appendChild(n),i.scrollTop=i.scrollHeight}escapeHtml(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}toggleConsole(t){var i;this.isConsoleOpen=t!=null?t:!this.isConsoleOpen,(i=this.consolePanel)==null||i.classList.toggle("closed",!this.isConsoleOpen)}clearConsole(){this.consoleMessages=[];let t=this.container.querySelector("#console-messages");t&&(t.innerHTML="");let i=this.container.querySelector("#console-badge");i&&(i.textContent="0")}setupCompareViewports(){Array.from(this.container.querySelectorAll("[data-viewport]")).forEach(i=>{let n=i.dataset.viewport;if(!n)return;let r=this.comparePresets.find(u=>u.id===n);if(!r)return;let a=i.querySelector("[data-compare-slot]"),s=i.querySelector("[data-compare-ghost]"),o=i.querySelector("[data-compare-wrapper]"),l=i.querySelector("[data-compare-frame]"),c=i.querySelector("[data-compare-snapshot]"),d=i.querySelector("[data-compare-focus]");!a||!s||!o||!l||(i.addEventListener("click",u=>{let p=u.target;if(p!=null&&p.closest("[data-compare-focus]")){u.preventDefault(),this.activateCompareViewport(n);return}i.classList.contains("is-active")||this.activateCompareViewport(n)}),this.compareViewports.set(n,{preset:r,root:i,slot:a,ghost:s,wrapper:o,frame:l,canvas:c,focus:d}))})}setViewMode(t){if(this.viewMode===t)return;this.viewMode=t,this.container.classList.toggle("compare-mode",t==="compare"),this.singleStage.classList.toggle("hidden",t!=="single"),this.compareStage.classList.toggle("hidden",t!=="compare");let i=this.container.querySelector("#device-select");i&&(i.disabled=t==="compare");let n=this.container.querySelector("#rotate-btn");if(n&&(n.disabled=t==="compare"),this.updateViewToggleUI(),t==="compare"){this.lastSinglePresetId=this.currentPreset.id,this.activateCompareViewport(this.activeCompareId),this.refreshCompareSnapshots(),this.startCompareSnapshots();return}this.stopCompareSnapshots(),this.singleStage.appendChild(this.frameDragger),this.setDevice(this.lastSinglePresetId,{suppressCallback:!0}),this.fitToScreen()}updateViewToggleUI(){Array.from(this.container.querySelectorAll("[data-view-toggle]")).forEach(i=>{i.classList.toggle("active",i.dataset.viewToggle===this.viewMode)})}activateCompareViewport(t){var a,s;let i=this.compareViewports.get(t);if(!i)return;let n=this.autoScale*this.userScaleMultiplier,r=this.activeCompareId;r&&r!==t&&this.captureCompareSnapshot(r),this.activeCompareId=t,this.currentPreset=i.preset,this.isLandscape=!1,i.slot.appendChild(this.frameDragger),this.frameDragOffsetX=0,this.frameDragOffsetY=0,this.applyFrameDrag(),this.compareViewports.forEach((o,l)=>{o.root.classList.toggle("is-active",l===t),o.ghost.classList.toggle("hidden",l===t),o.focus&&(o.focus.textContent=l===t?"Live":"Focus")}),this.applyPresetDimensions(),this.applyCompareDimensions(),this.fitToScreen({keepVisibleScale:n}),(s=(a=this.options).onDeviceChange)==null||s.call(a,this.getEffectivePreset())}applyCompareDimensions(){this.compareViewports.forEach(t=>{let i=t.preset,n=`${i.width}px`,r=`${i.height}px`;t.frame.style.width=n,t.frame.style.height=r,t.canvas&&(t.canvas.width=i.width,t.canvas.height=i.height)})}fitCompareGhosts(){this.compareViewports.forEach(t=>{let i=t.root.querySelector(".compare-body");if(!i)return;let n=Math.max(0,i.clientWidth-24),r=Math.max(0,i.clientHeight-24);if(n<=0||r<=0)return;let a=n/t.preset.width,s=r/t.preset.height,o=Math.max(.01,Math.min(a,s));t.wrapper.style.transform=`scale(${o})`})}captureCompareSnapshot(t){let i=this.compareViewports.get(t);if(!(i!=null&&i.canvas))return;let n=this.gameContainer.querySelector("canvas");if(!n)return;let r=i.canvas.getContext("2d");if(!r)return;let a=i.canvas.width,s=i.canvas.height,o=Math.min(a/n.width,s/n.height),l=n.width*o,c=n.height*o,d=(a-l)/2,u=(s-c)/2;r.clearRect(0,0,a,s),r.drawImage(n,d,u,l,c)}refreshCompareSnapshots(){this.compareViewports.forEach((t,i)=>{i!==this.activeCompareId&&this.captureCompareSnapshot(i)})}startCompareSnapshots(){this.compareSnapshotTimer||(this.compareSnapshotTimer=window.setInterval(()=>{this.viewMode==="compare"&&this.refreshCompareSnapshots()},500))}stopCompareSnapshots(){this.compareSnapshotTimer&&(window.clearInterval(this.compareSnapshotTimer),this.compareSnapshotTimer=null)}getFitBounds(){if(this.viewMode!=="compare")return{width:this.previewContainer.clientWidth-40,height:this.previewContainer.clientHeight-40};let t=this.compareViewports.get(this.activeCompareId),i=t==null?void 0:t.root.querySelector(".compare-body");return i?{width:i.clientWidth-24,height:i.clientHeight-24}:{width:this.previewContainer.clientWidth-40,height:this.previewContainer.clientHeight-40}}mustQuery(t){let i=this.container.querySelector(t);if(!i)throw new Error(`PreviewShell missing element: ${t}`);return i}};function hc(e={}){let t=new ns(e);return typeof window!="undefined"&&(window.__previewShell=t),t.mount(),t}Te();function gc(e){try{if(e&&typeof e.keys=="function")return Array.from(e.keys())}catch{}return[]}function kg(e){var t;return e?((t=e.getDisplayObject)==null?void 0:t.call(e))||e.pixiObject||e:null}function Ww(e,t){if(!e||!(t!=null&&t.interaction))return;let i=t.interaction,n=i.enabled!==!1&&(i.draggable===!0||i.clickable===!0);e.eventMode=n?"static":"none",e.interactive=n,n&&(e.cursor=i.draggable?"move":"pointer")}function Lg(e,t){var l,c,d,u,p;if(!e||!t)return;let i=t.transform||{};Ww(e,t);let n=i.position||{},r=i.offset||{},a=(typeof n.x=="number"?n.x:0)+(typeof r.x=="number"?r.x:0),s=(typeof n.y=="number"?n.y:0)+(typeof r.y=="number"?r.y:0);(l=e.position)!=null&&l.set?e.position.set(a,s):(typeof e.x=="number"&&(e.x=a),typeof e.y=="number"&&(e.y=s)),typeof i.scale=="number"&&((c=e.scale)!=null&&c.set?e.scale.set(i.scale):e.scale&&(e.scale.x=i.scale,e.scale.y=i.scale));let o=(u=i.anchor)!=null?u:(d=t.render)==null?void 0:d.anchor;o&&((p=e.anchor)!=null&&p.set)&&typeof o.x=="number"&&typeof o.y=="number"&&e.anchor.set(o.x,o.y)}function Og(e){if(typeof window=="undefined")return;let t=e==null?void 0:e.objects,i=gc(t),n=a=>{try{let s=window.__HANDLER_ACTIVE_SCREEN;if(!s||s==="all")return a;let o=window.__HANDLER_SCREEN_INDEX,l=o==null?void 0:o.instanceToScreen;return l?a.filter(c=>l[c]===s):a}catch{return a}};window.__editableObjectConfigs=t;let r=new Map;i.forEach(a=>r.set(a,[a])),window.__editableObjectInstances=r,window.refreshEditableConfigIndex=()=>Og(window.__editableConfig),window.getEditableObjectList=()=>{var a;return n(gc((a=window.__editableConfig)==null?void 0:a.objects))},window.getEditableObjectListAll=()=>{var a;return gc((a=window.__editableConfig)==null?void 0:a.objects)},window.getEditableObjectConfig=a=>{var d,u,p,f,g;let s=(f=(p=(u=(d=window.__editableConfig)==null?void 0:d.objects)==null?void 0:u.get)==null?void 0:p.call(u,a))!=null?f:null,o=window.__HANDLER_ACTIVE_SCREEN;if(!o||o==="all")return s;let l=window.__HANDLER_SCREEN_INDEX,c=(g=l==null?void 0:l.instanceToScreen)==null?void 0:g[a];return c&&c===o?s:null},window.getEditableEngineConfig=()=>{let a=window.__editableConfig;if(console.log("[BRIDGE] getEditableEngineConfig called, cfg present:",!!a),!a)return null;if(a.engine&&a.objects instanceof Map){console.log("[BRIDGE] Detected ObjectCentricConfig, flattening...");let s={...a.engine,objects:a.objects,scene:a.scene};return console.log("[BRIDGE] Returned assets:",Object.keys(s.assets||{})),s}return a}}function Vw(){if(typeof window=="undefined")return;let e=i=>{let n=String(i||"").trim();return n?/^(data:|blob:|https?:)/.test(n)||n.startsWith("/")?n:`/${n.replace(/^\.\//,"")}`:""},t=async(i,n)=>{var a,s,o;let r=e(n);if(r)try{let[{Assets:l},{AssetTextures:c}]=await Promise.all([import("pixi.js"),Promise.resolve().then(()=>(hi(),ud))]),d=Date.now(),u=/^(data:|blob:)/.test(r)?r:r+(r.includes("?")?`&t=${d}`:`?t=${d}`),p=await l.load(u);if(!p)return;c[i]=p;let f=window.CustomAssets;(a=f==null?void 0:f[i])!=null&&a.texture&&(f[i].texture=p);let g=window.gameObjectManager,h=(s=g==null?void 0:g.get)==null?void 0:s.call(g,i);if(h){let m=((o=h.getDisplayObject)==null?void 0:o.call(h))||h.pixiObject||h.pixi||h;if(m!=null&&m.texture)m.texture=p;else if(m!=null&&m.children){let b=m.children.find(y=>y==null?void 0:y.texture);b!=null&&b.texture&&(b.texture=p)}}}catch(l){console.warn("[LIVE-EDIT] Failed to reload Pixi texture for",i,l)}};window.applyLiveEditOverrides=i=>{try{let n=de();Array.isArray(n)&&n.length&&(window.__editableConfig=i,yt(n,{silent:!0,persist:!1}))}catch{}},window.applyEngineOverrides=i=>{try{let n=de();Array.isArray(n)&&n.length&&(window.__editableConfig=i,yt(n,{silent:!0,persist:!1}))}catch{}},window.applyEditableEngineConfig=i=>{let n=window.__editableConfig;if(!(n!=null&&n.engine))return;let r=[];if(i.runtime)for(let[a,s]of Object.entries(i.runtime))r.push({path:`runtime.${a}`,value:s});if(i.assets)for(let[a,s]of Object.entries(i.assets))r.push({path:`assets.${a}`,value:s}),typeof s=="string"&&t(a,s);if(i.splash)for(let[a,s]of Object.entries(i.splash))r.push({path:`splash.${a}`,value:s});if(i.loading)for(let[a,s]of Object.entries(i.loading))r.push({path:`loading.${a}`,value:s});if(i.start)for(let[a,s]of Object.entries(i.start))r.push({path:`start.${a}`,value:s});r.length&&yt(r,{silent:!0,persist:!0,emitEvent:!0})}}function rs(e){let{getConfig:t,gameObjectManager:i,onObjectConfigApplied:n}=e;i&&(i.onObjectRebuildRequired=async(a,s)=>{console.log(`[LIVE-EDIT] \u{1F3D7}\uFE0F Rebuilding object ${a} due to type change...`);let o=i.get(a),l=o==null?void 0:o.pixiObject,c=l==null?void 0:l.parent,d=c==null?void 0:c.children.indexOf(l);o?i.remove(a):l&&l.destroy();let u=window.gameApp,p=await mt.create(a,s,u);c&&(d!==void 0&&d!==-1?c.addChildAt(p,d):c.addChild(p));let f=i.create(a,p);return console.log(`[LIVE-EDIT] \u2705 Rebuild complete for ${a}`),f}),typeof window!="undefined"&&(Vw(),window.applyEditableObjectConfig=(a,s)=>{var o,l,c;console.log("[LIVE-EDIT] \u{1F504} applyEditableObjectConfig called for:",a);try{let d=window.__editableConfig;(o=d==null?void 0:d.objects)!=null&&o.set&&(d.objects.set(a,s),console.log("[LIVE-EDIT] \u2705 Updated config in __editableConfig"));let u=(l=i==null?void 0:i.get)==null?void 0:l.call(i,a);if(console.log("[LIVE-EDIT] gameObject found?",!!u),u&&(console.log("[LIVE-EDIT] gameObject type:",(c=u.constructor)==null?void 0:c.name),console.log("[LIVE-EDIT] has updateConfig?",typeof u.updateConfig=="function"),console.log("[LIVE-EDIT] has onConfigUpdate?",typeof u.onConfigUpdate=="function")),u&&typeof u.updateConfig=="function")console.log("[LIVE-EDIT] \u2705 Calling updateConfig()"),u.updateConfig(s);else if(u&&typeof u.onConfigUpdate=="function")console.log("[LIVE-EDIT] \u2705 Calling onConfigUpdate()"),u.onConfigUpdate();else{console.log("[LIVE-EDIT] \u26A0\uFE0F No updateConfig or onConfigUpdate, applying transform directly");let p=kg(u);Lg(p,s)}}catch(d){console.error("[LIVE-EDIT] \u274C Error in applyEditableObjectConfig:",d)}});let r={async applyObjectConfig(a,s){var d,u;console.log("[BRIDGE] \u{1F504} applyObjectConfig called for:",a);let o=t();(d=o==null?void 0:o.objects)!=null&&d.set&&(o.objects.set(a,s),console.log("[BRIDGE] \u2705 Updated config"));let l=(u=i==null?void 0:i.get)==null?void 0:u.call(i,a);if(console.log("[BRIDGE] gameObject found?",!!l),l&&(console.log("[BRIDGE] has updateConfig?",typeof l.updateConfig=="function"),console.log("[BRIDGE] has onConfigUpdate?",typeof l.onConfigUpdate=="function")),l&&typeof l.updateConfig=="function")console.log("[BRIDGE] \u2705 Calling updateConfig()"),l.updateConfig(s);else if(l&&typeof l.onConfigUpdate=="function")console.log("[BRIDGE] \u2705 Calling onConfigUpdate()"),l.onConfigUpdate();else{console.log("[BRIDGE] \u26A0\uFE0F Applying transform directly");let p=kg(l);Lg(p,s)}let c=[a];n==null||n(a,s,c)},rebuildIndexes(){let a=t();typeof window!="undefined"&&(window.__editableConfig=a,Og(a))}};return r.rebuildIndexes(),r}Te();var Pg=di(require("lottie-web"),1);Es(ws);typeof window!="undefined"&&!window.lottie&&(window.lottie=Pg.default);var Vi=null,Yw=async()=>{if(!Vi){let e=typeof window!="undefined"?window.INLINE_ASSETS:null,t=(e==null?void 0:e["handler.config"])||(e==null?void 0:e["handler.config.json"]);if(t)try{if(t.startsWith("data:")){let n=atob(t.split(",")[1]);Vi=JSON.parse(n)}else Vi=JSON.parse(t);return Vi}catch(n){console.warn("[CONFIG] Failed to parse inline handler.config.json:",n)}Vi=await(await fetch("./handler.config.json")).json()}return Vi},vc,sr,Rg,Yi,bc,yc;function Kw(e){vc=e.initGame,sr=e.CustomAssets,Rg=e.updateScreenState,Yi=e.globalResponsiveMultipliers,bc=e.layout,yc=e.clearResponsiveElements}var as="web_embed",ar="https://example.com",Ig={profile_id:as},Rt=null,Ge=null,mc={width:0,height:0},Xw=!0,Zw=async()=>{var c,d,u,p;document.title="Handler Pixi Game";let e=await Yw();Ig={...e.ids||{},profile_id:as},ar=e.destination_url||((d=(c=e.export_profiles)==null?void 0:c[as])==null?void 0:d.destination_url)||ar,zt.init({ids:Ig,profile:as,destinationUrl:ar});let t=zt.getRoot();if(typeof __PREVIEW_SHELL__!="undefined"&&__PREVIEW_SHELL__){console.log("[BOOTSTRAP] Initializing Preview Shell..."),Ge=hc({onDeviceChange:g=>{console.log(`[PREVIEW] Device switched to ${g.width}x${g.height}, restarting game...`),Mg()},onRefresh:Mg});let f=Ge.getGameContainer();f&&(t=f),window.addEventListener("handler-preview:screen",g=>{var v,x,w,E,A,_,T,P,S,L,z;let h=window.gameApp,m=window.gameObjectManager,{width:b,height:y}=g.detail;if(mc.width=b,mc.height=y,Rg(b,y),!(!h||!h.renderer)){m&&o(h,m);try{h.renderer.resize(b,y);let D=h.view;D&&(D.style.width="100%",D.style.height="100%",D.style.display="block")}catch(D){console.warn("[SCREEN] Error resizing renderer:",D);return}if(i&&m&&bc)try{let D=(v=window.__mainContainer)!=null?v:h.stage,B=(T=(_=(E=window.__tutorialLabel)!=null?E:(w=(x=m.get("label_1"))==null?void 0:x.getDisplayObject)==null?void 0:w.call(x))!=null?_:(A=m.get("label_1"))==null?void 0:A.pixiObject)!=null?T:m.get("label_1"),O=m.get("background_1"),R=(z=(L=(S=window.__background)!=null?S:(P=O==null?void 0:O.getDisplayObject)==null?void 0:P.call(O))!=null?L:O==null?void 0:O.pixiObject)!=null?z:O;if(D){let C=D===h.stage;bc({mainContainer:D,label:B,background:R,backgroundTexture:(R==null?void 0:R.texture)||null,app:h},i,0,mc,m,{skipMainContainerTransform:C})}}catch(D){console.warn("[SCREEN] Error in layout:",D)}}})}let i=await et("scene.main");window.__editableConfig=i,s(),window.__editableConfigBaseline||(window.__editableConfigBaseline=ne(i),console.log("[BOOTSTRAP] Frozen config baseline for persistence")),(p=(u=i.engine.runtime)==null?void 0:u.layout)!=null&&p.design_width_portrait||(console.warn("[BOOTSTRAP] Config layout missing, retrying..."),await new Promise(f=>setTimeout(f,100)),i=await et("scene.main"));let n=await vc(t,i,ar,Ge);Rt=n.app;let r=n.gameObjectManager;window.gameApp=Rt,window.gameObjectManager=r;try{window.__liveEditBridge=rs({getConfig:()=>window.__editableConfig,gameObjectManager:r,assets:sr})}catch(f){console.warn("[BOOTSTRAP] Failed to initialize live-edit bridge",f)}Ge&&Ge.notifyGameLoaded();let a=window.__debugScale;a&&typeof a=="number"&&(Yi.scale=a,console.log(`[DEBUG] Applied persisted debug scale: ${a}`)),o(Rt,r);async function s(){try{let f=async y=>{let v=y.startsWith("/")?y:`/${y}`,x=await fetch(v,{cache:"no-cache"});if(!x.ok)return null;let w=await x.text();try{return JSON.parse(w)}catch{return null}},g=await f("configs/flow/app.flow.json");if(!g||typeof g!="object")return;let h=g.screens;if(!h||typeof h!="object")return;let m={},b={};for(let[y,v]of Object.entries(h)){let x=v==null?void 0:v.source;if(typeof x!="string")continue;let w=await f(x),E=w==null?void 0:w.elements;if(!Array.isArray(E))continue;let A=E.map(_=>_==null?void 0:_.instance_id).filter(_=>typeof _=="string");m[y]=A;for(let _ of A)b[_]||(b[_]=y)}window.__HANDLER_APP_FLOW=g,window.__HANDLER_SCREEN_INDEX={screenToInstances:m,instanceToScreen:b},window.dispatchEvent(new CustomEvent("handler:screen-index-loaded"))}catch{}}function o(f,g){if(Xw){console.log("[RESPONSIVE] Skipping global scaling; using config-driven layout");return}if(console.log("[RESPONSIVE] ===== APPLYING GLOBAL RESPONSIVE SCALING ====="),console.log(`[RESPONSIVE] Scale multiplier: ${Yi.scale.toFixed(3)}`),f.stage){let m=function(b,y=0){if(!b||!b.children)return;let v=" ".repeat(y);b.children.forEach((x,w)=>{if(x&&x.zIndex===9999){console.log(`${v}[RESPONSIVE] Skipping debug border (zIndex 9999)`);return}if(x&&x.scale){let E=x.scale.x||1,A=x.scale.y||1;x.__originalScale||(x.__originalScale={x:E,y:A},console.log(`${v}[RESPONSIVE] Stored original scale for child[${w}]: ${E.toFixed(3)}, ${A.toFixed(3)}`));let _=x.__originalScale.x*Yi.scale,T=x.__originalScale.y*Yi.scale;typeof x.scale.set=="function"?x.scale.set(_,T):(x.scale.x=_,x.scale.y=T),console.log(`${v}[RESPONSIVE] Child[${w}] scale: ${E.toFixed(3)}\u2192${x.scale.x.toFixed(3)} (type: ${x.constructor.name})`),m(x,y+1)}else x&&console.log(`${v}[RESPONSIVE] Child[${w}] has no scale (type: ${x.constructor.name})`)})};var h=m;console.log("[RESPONSIVE] Applying scale to PIXI stage children"),m(f.stage)}else console.warn("[RESPONSIVE] No app.stage found!");console.log("[REDDEBUG] Debug border left unscaled (fixed boundaries)"),console.log("[RESPONSIVE] ===== GLOBAL RESPONSIVE SCALING COMPLETE =====")}function l(f){if(f!==void 0){Yi.scale=f,console.log(`[RESPONSIVE] Updated global scale multiplier to: ${f.toFixed(3)}`);let g=window.gameApp,h=window.gameObjectManager;g&&h?(o(g,h),g.renderer&&(g.renderer.render(g.stage),console.log("[RESPONSIVE] Forced PIXI renderer update"))):console.warn(`[RESPONSIVE] No gameApp (${!!g}) or gameObjectManager (${!!h}) found in window for live update`)}}window.updateGlobalResponsiveMultipliers=l,zt.start()},Mg=async()=>{var t,i,n,r;console.log("[PREVIEW] Restarting game in 1 seconds...");let e=(t=window.gameObjectManager)==null?void 0:t.get("character_1");if(e){let a=((i=e.getDisplayObject)==null?void 0:i.call(e))||e;a&&a.scale&&console.log(`[CHARACTER] Before restart - Current scale - x: ${((n=a.scale.x)!=null?n:1).toFixed(3)}, y: ${((r=a.scale.y)!=null?r:1).toFixed(3)}`)}if(Ge){Ge.notifyGameDestroyed();try{yc&&yc()}catch(a){console.warn("Failed to clear responsive elements",a)}setTimeout(()=>{console.log("[PREVIEW] Executing restart...");let a=Ge.getGameContainer(),s=window.gameObjectManager;if(s&&typeof s.clear=="function"&&(console.log("[PREVIEW] Clearing old GameObjectManager tickers..."),s.clear()),Rt){try{Rt.destroy(!0,{children:!0,texture:!1})}catch(o){console.warn("[PREVIEW] Destroy warning:",o)}Rt=null}window.gameApp=null,window.gameObjectManager=null,a&&(a.innerHTML="");try{typeof sr.resetScene=="function"&&sr.resetScene()}catch(o){console.warn("Asset reset failed",o)}setTimeout(()=>{et("scene.main").then(o=>{window.__editableConfig=o,window.__editableConfigBaseline||(window.__editableConfigBaseline=ne(o)),vc(a,o,ar).then(l=>{Rt=l.app,window.gameApp=Rt,window.gameObjectManager=l.gameObjectManager;try{window.__liveEditBridge=rs({getConfig:()=>window.__editableConfig,gameObjectManager:window.gameObjectManager,assets:sr})}catch(c){console.warn("[BOOTSTRAP] Failed to re-initialize live-edit bridge",c)}Ge&&Ge.notifyGameLoaded(),console.log("[PREVIEW] Game restarted successfully");try{zt.start()}catch{}})})},100)},1e3)}};zr();Te();var We={background:"#F6F3EF",ink:"#1E1E1E",secondaryText:"#8E8A84",primaryAccent:"#E38A5A",secondaryAccent:"#C9A28C",statusGreen:"#5F8F6B"},jg=1.25,Dg={fontFamily:"Inter, system-ui, sans-serif"};var ss=class{constructor(t={}){this.currentProgress=0;var i;this.currentProgress=(i=t.progress)!=null?i:0,this.container=this.createContainer()}createContainer(){let t=document.createElement("div");t.className="handler-loading-screen",t.style.cssText=`
1446
+ `,this.setupEventListeners(e),e}setupEventListeners(e){var a,s,r,o,l,c,p,d,u,g;let t=e.querySelector("#device-select");t==null||t.addEventListener("change",h=>{if(this.viewMode==="compare")return;let f=h.target.value;this.setDevice(f)}),Array.from(e.querySelectorAll("[data-view-toggle]")).forEach(h=>{h.addEventListener("click",()=>{let f=h.dataset.viewToggle;f&&this.setViewMode(f)})}),(a=e.querySelector("#rotate-btn"))==null||a.addEventListener("click",()=>this.toggleRotation()),(s=e.querySelector("#zoom-in-btn"))==null||s.addEventListener("click",()=>this.adjustUserZoom(.1)),(r=e.querySelector("#zoom-out-btn"))==null||r.addEventListener("click",()=>this.adjustUserZoom(-.1)),(o=e.querySelector("#refresh-btn"))==null||o.addEventListener("click",()=>this.refresh()),(l=e.querySelector("#console-toggle"))==null||l.addEventListener("click",()=>this.toggleConsole()),(c=e.querySelector("#console-close"))==null||c.addEventListener("click",()=>this.toggleConsole(!1)),(p=e.querySelector("#console-clear"))==null||p.addEventListener("click",()=>this.clearConsole()),(d=e.querySelector("#corner-zoom-in-btn"))==null||d.addEventListener("click",()=>this.adjustUserZoom(.1)),(u=e.querySelector("#corner-zoom-out-btn"))==null||u.addEventListener("click",()=>this.adjustUserZoom(-.1)),(g=e.querySelector("#corner-grab-btn"))==null||g.addEventListener("click",()=>{this.frameDragger.style.cursor="grab",setTimeout(()=>{this.isSpaceKeyPressed||(this.frameDragger.style.cursor="")},1e3)})}applyDeviceFrameStyles(){Object.assign(this.frameDragger.style,{display:"flex",justifyContent:"center",alignItems:"center",transform:"translate(0px, 0px)",touchAction:"none"}),Object.assign(this.frameWrapper.style,{display:"flex",justifyContent:"center",alignItems:"center",transformOrigin:"center center",transition:"transform 0.2s cubic-bezier(0.25, 0.46, 0.45, 0.94)",boxShadow:"0 20px 50px rgba(0,0,0,0.5)",borderRadius:"0px",willChange:"transform"}),Object.assign(this.deviceFrame.style,{overflow:"hidden",position:"relative",borderRadius:"0px"}),Object.assign(this.gameContainer.style,{position:"relative",overflow:"hidden",minWidth:"0px",minHeight:"0px"})}setupObserversAndListeners(){this.resizeObserver=new ResizeObserver(()=>{this.resizeListenersDisabled||!this.gameReady||this.scheduleFit()}),this.resizeObserver.observe(this.previewContainer),window.addEventListener("resize",this.onWindowResize,{passive:!0})}scheduleFit(){this.rafFitHandle&&cancelAnimationFrame(this.rafFitHandle),this.rafFitHandle=requestAnimationFrame(()=>{this.rafFitHandle=null,this.fitToScreen()})}applyPresetDimensions(){let e=this.getEffectivePreset(),t=`${e.width}px`,n=`${e.height}px`;this.deviceFrame.style.width=t,this.deviceFrame.style.height=n,this.gameContainer.style.width=t,this.gameContainer.style.height=n,this.gameContainer.style.maxWidth=t,this.gameContainer.style.maxHeight=n,this.gameContainer.style.minWidth=t,this.gameContainer.style.minHeight=n,this.gameContainer.dataset.screenWidth=String(e.width),this.gameContainer.dataset.screenHeight=String(e.height),this.container.style.setProperty("--preview-screen-width",String(e.width)),this.container.style.setProperty("--preview-screen-height",String(e.height))}fitToScreen(e){if(!this.previewContainer)return;let t=this.getEffectivePreset(),n=this.getFitBounds(),a=Math.max(0,n.width),s=Math.max(0,n.height);if(a<=0||s<=0)return;this.applyPresetDimensions(),this.viewMode==="compare"&&this.applyCompareDimensions();let r=a/t.width,o=s/t.height;if(this.autoScale=Math.max(.01,Math.min(r,o)),!this.hasInitialFit){this.hasInitialFit=!0;let l=.6;this.userScaleMultiplier=l/this.autoScale}e!=null&&e.keepVisibleScale&&e.keepVisibleScale>0&&(this.userScaleMultiplier=e.keepVisibleScale/this.autoScale),this.applyTransform(),this.viewMode==="compare"&&this.fitCompareGhosts(),this.emitScreenChange()}applyTransform(){let e=this.autoScale*this.userScaleMultiplier;this.frameWrapper.style.transform=`scale(${e})`;let t=this.container.querySelector("#zoom-label");t&&(t.textContent=`${Math.round(e*100)}%`)}applyFrameDrag(){this.frameDragger.style.transform=`translate(${this.frameDragOffsetX}px, ${this.frameDragOffsetY}px)`}setupFrameDragging(){this.frameDragger.addEventListener("pointerdown",e=>{let t=!this.gameContainer.contains(e.target);!this.isSpaceKeyPressed&&!t||e.button===0&&(e.preventDefault(),this.frameDragActive=!0,this.frameDragStartX=e.clientX,this.frameDragStartY=e.clientY,this.frameDragOriginX=this.frameDragOffsetX,this.frameDragOriginY=this.frameDragOffsetY,window.addEventListener("pointermove",this.onFrameDragMove),window.addEventListener("pointerup",this.onFrameDragEnd))})}setupSpaceKeyListener(){window.addEventListener("keydown",e=>{e.code==="Space"&&!this.isInputFocused()&&(this.isSpaceKeyPressed||(this.isSpaceKeyPressed=!0,this.updateDragCursor(),e.preventDefault()))}),window.addEventListener("keyup",e=>{e.code==="Space"&&(this.isSpaceKeyPressed=!1,this.updateDragCursor(),this.frameDragActive&&this.onFrameDragEnd())}),window.addEventListener("blur",()=>{this.isSpaceKeyPressed=!1,this.updateDragCursor(),this.frameDragActive&&this.onFrameDragEnd()})}isInputFocused(){let e=document.activeElement;if(!e)return!1;let t=e.tagName.toLowerCase();return t==="input"||t==="textarea"||t==="select"||e.isContentEditable}updateDragCursor(){this.isSpaceKeyPressed?(this.frameDragger.style.cursor="grab",this.frameDragActive&&(this.frameDragger.style.cursor="grabbing")):this.frameDragger.style.cursor=""}adjustUserZoom(e){this.userScaleMultiplier=Math.max(.1,Math.min(6,this.userScaleMultiplier+e)),this.applyTransform(),this.emitScreenChange()}toggleRotation(){var t,n;if(this.viewMode==="compare")return;let e=this.autoScale*this.userScaleMultiplier;this.isLandscape=!this.isLandscape,this.applyPresetDimensions(),this.fitToScreen({keepVisibleScale:e}),(n=(t=this.options).onDeviceChange)==null||n.call(t,this.getEffectivePreset()),this.emitScreenChange()}emitScreenChange(){if(!this.gameReady)return;let e=this.getEffectivePreset(),t={width:e.width,height:e.height,dpr:Math.max(1,Math.floor(window.devicePixelRatio||1)),presetId:e.id,isLandscape:this.isLandscape};if(window.dispatchEvent(new CustomEvent("handler-preview:screen",{detail:t})),this.viewMode==="compare"&&this.refreshCompareSnapshots(),this.isInitialized&&this.isMounted&&this.gameReady){let n=window.gameApp;if(!(n!=null&&n.renderer))return;this.ignoreNextWindowResize=!0,window.dispatchEvent(new Event("resize"))}}safeStringify(e){var n;let t=new WeakSet;try{return JSON.stringify(e,(a,s)=>{if(typeof s=="object"&&s!==null){if(t.has(s))return"[Circular]";t.add(s)}return s},2)}catch{try{if(e&&((n=e.constructor)!=null&&n.name))return`[object ${e.constructor.name}]`}catch{}return String(e)}}setupConsoleInterceptor(){let e=console.log.bind(console),t=console.warn.bind(console),n=console.error.bind(console),a=console.info.bind(console),s=(r,...o)=>{let l=o.map(p=>typeof p=="object"?this.safeStringify(p):String(p)).join(" ");this.consoleMessages.push({type:r,message:l,timestamp:new Date}),this.appendConsoleMessage(this.consoleMessages[this.consoleMessages.length-1]);let c=this.container.querySelector("#console-badge");if(c){let p=this.consoleMessages.filter(d=>d.type==="error").length;c.textContent=p>0?`${p}!`:"0",c.classList.toggle("has-errors",p>0)}};console.log=(...r)=>{e(...r),s("log",...r)},console.warn=(...r)=>{t(...r),s("warn",...r)},console.error=(...r)=>{n(...r),s("error",...r)},console.info=(...r)=>{a(...r),s("info",...r)}}appendConsoleMessage(e){let t=this.container.querySelector("#console-messages");if(!t)return;let n=document.createElement("div");n.className=`console-msg type-${e.type}`;let a=e.timestamp.toLocaleTimeString();n.innerHTML=`<span class="time">${this.escapeHtml(a)}</span> <pre>${this.escapeHtml(e.message)}</pre>`,t.appendChild(n),t.scrollTop=t.scrollHeight}escapeHtml(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}toggleConsole(e){var t;this.isConsoleOpen=e!=null?e:!this.isConsoleOpen,(t=this.consolePanel)==null||t.classList.toggle("closed",!this.isConsoleOpen)}clearConsole(){this.consoleMessages=[];let e=this.container.querySelector("#console-messages");e&&(e.innerHTML="");let t=this.container.querySelector("#console-badge");t&&(t.textContent="0")}setupCompareViewports(){Array.from(this.container.querySelectorAll("[data-viewport]")).forEach(t=>{let n=t.dataset.viewport;if(!n)return;let a=this.comparePresets.find(d=>d.id===n);if(!a)return;let s=t.querySelector("[data-compare-slot]"),r=t.querySelector("[data-compare-ghost]"),o=t.querySelector("[data-compare-wrapper]"),l=t.querySelector("[data-compare-frame]"),c=t.querySelector("[data-compare-snapshot]"),p=t.querySelector("[data-compare-focus]");!s||!r||!o||!l||(t.addEventListener("click",d=>{let u=d.target;if(u!=null&&u.closest("[data-compare-focus]")){d.preventDefault(),this.activateCompareViewport(n);return}t.classList.contains("is-active")||this.activateCompareViewport(n)}),this.compareViewports.set(n,{preset:a,root:t,slot:s,ghost:r,wrapper:o,frame:l,canvas:c,focus:p}))})}setViewMode(e){if(this.viewMode===e)return;this.viewMode=e,this.container.classList.toggle("compare-mode",e==="compare"),this.singleStage.classList.toggle("hidden",e!=="single"),this.compareStage.classList.toggle("hidden",e!=="compare");let t=this.container.querySelector("#device-select");t&&(t.disabled=e==="compare");let n=this.container.querySelector("#rotate-btn");if(n&&(n.disabled=e==="compare"),this.updateViewToggleUI(),e==="compare"){this.lastSinglePresetId=this.currentPreset.id,this.activateCompareViewport(this.activeCompareId),this.refreshCompareSnapshots(),this.startCompareSnapshots();return}this.stopCompareSnapshots(),this.singleStage.appendChild(this.frameDragger),this.setDevice(this.lastSinglePresetId,{suppressCallback:!0}),this.fitToScreen()}updateViewToggleUI(){Array.from(this.container.querySelectorAll("[data-view-toggle]")).forEach(t=>{t.classList.toggle("active",t.dataset.viewToggle===this.viewMode)})}activateCompareViewport(e){var s,r;let t=this.compareViewports.get(e);if(!t)return;let n=this.autoScale*this.userScaleMultiplier,a=this.activeCompareId;a&&a!==e&&this.captureCompareSnapshot(a),this.activeCompareId=e,this.currentPreset=t.preset,this.isLandscape=!1,t.slot.appendChild(this.frameDragger),this.frameDragOffsetX=0,this.frameDragOffsetY=0,this.applyFrameDrag(),this.compareViewports.forEach((o,l)=>{o.root.classList.toggle("is-active",l===e),o.ghost.classList.toggle("hidden",l===e),o.focus&&(o.focus.textContent=l===e?"Live":"Focus")}),this.applyPresetDimensions(),this.applyCompareDimensions(),this.fitToScreen({keepVisibleScale:n}),(r=(s=this.options).onDeviceChange)==null||r.call(s,this.getEffectivePreset())}applyCompareDimensions(){this.compareViewports.forEach(e=>{let t=e.preset,n=`${t.width}px`,a=`${t.height}px`;e.frame.style.width=n,e.frame.style.height=a,e.canvas&&(e.canvas.width=t.width,e.canvas.height=t.height)})}fitCompareGhosts(){this.compareViewports.forEach(e=>{let t=e.root.querySelector(".compare-body");if(!t)return;let n=Math.max(0,t.clientWidth-24),a=Math.max(0,t.clientHeight-24);if(n<=0||a<=0)return;let s=n/e.preset.width,r=a/e.preset.height,o=Math.max(.01,Math.min(s,r));e.wrapper.style.transform=`scale(${o})`})}captureCompareSnapshot(e){let t=this.compareViewports.get(e);if(!(t!=null&&t.canvas))return;let n=this.gameContainer.querySelector("canvas");if(!n)return;let a=t.canvas.getContext("2d");if(!a)return;let s=t.canvas.width,r=t.canvas.height,o=Math.min(s/n.width,r/n.height),l=n.width*o,c=n.height*o,p=(s-l)/2,d=(r-c)/2;a.clearRect(0,0,s,r),a.drawImage(n,p,d,l,c)}refreshCompareSnapshots(){this.compareViewports.forEach((e,t)=>{t!==this.activeCompareId&&this.captureCompareSnapshot(t)})}startCompareSnapshots(){this.compareSnapshotTimer||(this.compareSnapshotTimer=window.setInterval(()=>{this.viewMode==="compare"&&this.refreshCompareSnapshots()},500))}stopCompareSnapshots(){this.compareSnapshotTimer&&(window.clearInterval(this.compareSnapshotTimer),this.compareSnapshotTimer=null)}getFitBounds(){if(this.viewMode!=="compare")return{width:this.previewContainer.clientWidth-40,height:this.previewContainer.clientHeight-40};let e=this.compareViewports.get(this.activeCompareId),t=e==null?void 0:e.root.querySelector(".compare-body");return t?{width:t.clientWidth-24,height:t.clientHeight-24}:{width:this.previewContainer.clientWidth-40,height:this.previewContainer.clientHeight-40}}mustQuery(e){let t=this.container.querySelector(e);if(!t)throw new Error(`PreviewShell missing element: ${e}`);return t}};function ca(i={}){let e=new Nn(i);return typeof window!="undefined"&&(window.__previewShell=e),e.mount(),e}ee();function da(i){try{if(i&&typeof i.keys=="function")return Array.from(i.keys())}catch{}return[]}function dr(i){var e;return i?((e=i.getDisplayObject)==null?void 0:e.call(i))||i.pixiObject||i:null}function Ko(i,e){if(!i||!(e!=null&&e.interaction))return;let t=e.interaction,n=t.enabled!==!1&&(t.draggable===!0||t.clickable===!0);i.eventMode=n?"static":"none",i.interactive=n,n&&(i.cursor=t.draggable?"move":"pointer")}function pr(i,e){var l,c,p,d,u;if(!i||!e)return;let t=e.transform||{};Ko(i,e);let n=t.position||{},a=t.offset||{},s=(typeof n.x=="number"?n.x:0)+(typeof a.x=="number"?a.x:0),r=(typeof n.y=="number"?n.y:0)+(typeof a.y=="number"?a.y:0);(l=i.position)!=null&&l.set?i.position.set(s,r):(typeof i.x=="number"&&(i.x=s),typeof i.y=="number"&&(i.y=r)),typeof t.scale=="number"&&((c=i.scale)!=null&&c.set?i.scale.set(t.scale):i.scale&&(i.scale.x=t.scale,i.scale.y=t.scale));let o=(d=t.anchor)!=null?d:(p=e.render)==null?void 0:p.anchor;o&&((u=i.anchor)!=null&&u.set)&&typeof o.x=="number"&&typeof o.y=="number"&&i.anchor.set(o.x,o.y)}function ur(i){if(typeof window=="undefined")return;let e=i==null?void 0:i.objects,t=da(e),n=s=>{try{let r=window.__HANDLER_ACTIVE_SCREEN;if(!r||r==="all")return s;let o=window.__HANDLER_SCREEN_INDEX,l=o==null?void 0:o.instanceToScreen;return l?s.filter(c=>l[c]===r):s}catch{return s}};window.__editableObjectConfigs=e;let a=new Map;t.forEach(s=>a.set(s,[s])),window.__editableObjectInstances=a,window.refreshEditableConfigIndex=()=>ur(window.__editableConfig),window.getEditableObjectList=()=>{var s;return n(da((s=window.__editableConfig)==null?void 0:s.objects))},window.getEditableObjectListAll=()=>{var s;return da((s=window.__editableConfig)==null?void 0:s.objects)},window.getEditableObjectConfig=s=>{var p,d,u,g,h;let r=(g=(u=(d=(p=window.__editableConfig)==null?void 0:p.objects)==null?void 0:d.get)==null?void 0:u.call(d,s))!=null?g:null,o=window.__HANDLER_ACTIVE_SCREEN;if(!o||o==="all")return r;let l=window.__HANDLER_SCREEN_INDEX,c=(h=l==null?void 0:l.instanceToScreen)==null?void 0:h[s];return c&&c===o?r:null},window.getEditableEngineConfig=()=>{let s=window.__editableConfig;if(console.log("[BRIDGE] getEditableEngineConfig called, cfg present:",!!s),!s)return null;if(s.engine&&s.objects instanceof Map){console.log("[BRIDGE] Detected ObjectCentricConfig, flattening...");let r={...s.engine,objects:s.objects,scene:s.scene};return console.log("[BRIDGE] Returned assets:",Object.keys(r.assets||{})),r}return s}}function Xo(){if(typeof window=="undefined")return;let i=t=>{let n=String(t||"").trim();return n?/^(data:|blob:|https?:)/.test(n)||n.startsWith("/")?n:`/${n.replace(/^\.\//,"")}`:""},e=async(t,n)=>{var s,r,o;let a=i(n);if(a)try{let[{Assets:l},{AssetTextures:c}]=await Promise.all([import("pixi.js"),Promise.resolve().then(()=>(Xe(),os))]),p=Date.now(),d=/^(data:|blob:)/.test(a)?a:a+(a.includes("?")?`&t=${p}`:`?t=${p}`),u=await l.load(d);if(!u)return;c[t]=u;let g=window.CustomAssets;(s=g==null?void 0:g[t])!=null&&s.texture&&(g[t].texture=u);let h=window.gameObjectManager,f=(r=h==null?void 0:h.get)==null?void 0:r.call(h,t);if(f){let m=((o=f.getDisplayObject)==null?void 0:o.call(f))||f.pixiObject||f.pixi||f;if(m!=null&&m.texture)m.texture=u;else if(m!=null&&m.children){let b=m.children.find(y=>y==null?void 0:y.texture);b!=null&&b.texture&&(b.texture=u)}}}catch(l){console.warn("[LIVE-EDIT] Failed to reload Pixi texture for",t,l)}};window.applyLiveEditOverrides=t=>{try{let n=Y();Array.isArray(n)&&n.length&&(window.__editableConfig=t,Se(n,{silent:!0,persist:!1}))}catch{}},window.applyEngineOverrides=t=>{try{let n=Y();Array.isArray(n)&&n.length&&(window.__editableConfig=t,Se(n,{silent:!0,persist:!1}))}catch{}},window.applyEditableEngineConfig=t=>{let n=window.__editableConfig;if(!(n!=null&&n.engine))return;let a=[];if(t.runtime)for(let[s,r]of Object.entries(t.runtime))a.push({path:`runtime.${s}`,value:r});if(t.assets)for(let[s,r]of Object.entries(t.assets))a.push({path:`assets.${s}`,value:r}),typeof r=="string"&&e(s,r);if(t.splash)for(let[s,r]of Object.entries(t.splash))a.push({path:`splash.${s}`,value:r});if(t.loading)for(let[s,r]of Object.entries(t.loading))a.push({path:`loading.${s}`,value:r});if(t.start)for(let[s,r]of Object.entries(t.start))a.push({path:`start.${s}`,value:r});a.length&&Se(a,{silent:!0,persist:!0,emitEvent:!0})}}function Hn(i){let{getConfig:e,gameObjectManager:t,onObjectConfigApplied:n}=i;t&&(t.onObjectRebuildRequired=async(s,r)=>{console.log(`[LIVE-EDIT] \u{1F3D7}\uFE0F Rebuilding object ${s} due to type change...`);let o=t.get(s),l=o==null?void 0:o.pixiObject,c=l==null?void 0:l.parent,p=c==null?void 0:c.children.indexOf(l);o?t.remove(s):l&&l.destroy();let d=window.gameApp,u=await Ee.create(s,r,d);c&&(p!==void 0&&p!==-1?c.addChildAt(u,p):c.addChild(u));let g=t.create(s,u);return console.log(`[LIVE-EDIT] \u2705 Rebuild complete for ${s}`),g}),typeof window!="undefined"&&(Xo(),window.applyEditableObjectConfig=(s,r)=>{var o,l,c;console.log("[LIVE-EDIT] \u{1F504} applyEditableObjectConfig called for:",s);try{let p=window.__editableConfig;(o=p==null?void 0:p.objects)!=null&&o.set&&(p.objects.set(s,r),console.log("[LIVE-EDIT] \u2705 Updated config in __editableConfig"));let d=(l=t==null?void 0:t.get)==null?void 0:l.call(t,s);if(console.log("[LIVE-EDIT] gameObject found?",!!d),d&&(console.log("[LIVE-EDIT] gameObject type:",(c=d.constructor)==null?void 0:c.name),console.log("[LIVE-EDIT] has updateConfig?",typeof d.updateConfig=="function"),console.log("[LIVE-EDIT] has onConfigUpdate?",typeof d.onConfigUpdate=="function")),d&&typeof d.updateConfig=="function")console.log("[LIVE-EDIT] \u2705 Calling updateConfig()"),d.updateConfig(r);else if(d&&typeof d.onConfigUpdate=="function")console.log("[LIVE-EDIT] \u2705 Calling onConfigUpdate()"),d.onConfigUpdate();else{console.log("[LIVE-EDIT] \u26A0\uFE0F No updateConfig or onConfigUpdate, applying transform directly");let u=dr(d);pr(u,r)}}catch(p){console.error("[LIVE-EDIT] \u274C Error in applyEditableObjectConfig:",p)}});let a={async applyObjectConfig(s,r){var p,d;console.log("[BRIDGE] \u{1F504} applyObjectConfig called for:",s);let o=e();(p=o==null?void 0:o.objects)!=null&&p.set&&(o.objects.set(s,r),console.log("[BRIDGE] \u2705 Updated config"));let l=(d=t==null?void 0:t.get)==null?void 0:d.call(t,s);if(console.log("[BRIDGE] gameObject found?",!!l),l&&(console.log("[BRIDGE] has updateConfig?",typeof l.updateConfig=="function"),console.log("[BRIDGE] has onConfigUpdate?",typeof l.onConfigUpdate=="function")),l&&typeof l.updateConfig=="function")console.log("[BRIDGE] \u2705 Calling updateConfig()"),l.updateConfig(r);else if(l&&typeof l.onConfigUpdate=="function")console.log("[BRIDGE] \u2705 Calling onConfigUpdate()"),l.onConfigUpdate();else{console.log("[BRIDGE] \u26A0\uFE0F Applying transform directly");let u=dr(l);pr(u,r)}let c=[s];n==null||n(s,r,c)},rebuildIndexes(){let s=e();typeof window!="undefined"&&(window.__editableConfig=s,ur(s))}};return a.rebuildIndexes(),a}ee();var hr=Ve(require("lottie-web"),1);si(ii);typeof window!="undefined"&&!window.lottie&&(window.lottie=hr.default);var nt=null,Jo=async()=>{if(!nt){let i=typeof window!="undefined"?window.INLINE_ASSETS:null,e=(i==null?void 0:i["handler.config"])||(i==null?void 0:i["handler.config.json"]);if(e)try{if(e.startsWith("data:")){let n=atob(e.split(",")[1]);nt=JSON.parse(n)}else nt=JSON.parse(e);return nt}catch(n){console.warn("[CONFIG] Failed to parse inline handler.config.json:",n)}nt=await(await fetch("./handler.config.json")).json()}return nt},fa,Ot,mr,it,ua,ga;function Zo(i){fa=i.initGame,Ot=i.CustomAssets,mr=i.updateScreenState,it=i.globalResponsiveMultipliers,ua=i.layout,ga=i.clearResponsiveElements}var Bn="web_embed",kt="https://example.com",gr={profile_id:Bn},Pe=null,le=null,pa={width:0,height:0},Qo=!0,el=async()=>{var c,p,d,u;document.title="Handler Pixi Game";let i=await Jo();gr={...i.ids||{},profile_id:Bn},kt=i.destination_url||((p=(c=i.export_profiles)==null?void 0:c[Bn])==null?void 0:p.destination_url)||kt,Oe.init({ids:gr,profile:Bn,destinationUrl:kt});let e=Oe.getRoot();if(typeof __PREVIEW_SHELL__!="undefined"&&__PREVIEW_SHELL__){console.log("[BOOTSTRAP] Initializing Preview Shell..."),le=ca({onDeviceChange:h=>{console.log(`[PREVIEW] Device switched to ${h.width}x${h.height}, restarting game...`),fr()},onRefresh:fr});let g=le.getGameContainer();g&&(e=g),window.addEventListener("handler-preview:screen",h=>{var v,x,E,w,T,S,O,B,M,C,I;let f=window.gameApp,m=window.gameObjectManager,{width:b,height:y}=h.detail;if(pa.width=b,pa.height=y,mr(b,y),!(!f||!f.renderer)){m&&o(f,m);try{f.renderer.resize(b,y);let k=f.view;k&&(k.style.width="100%",k.style.height="100%",k.style.display="block")}catch(k){console.warn("[SCREEN] Error resizing renderer:",k);return}if(t&&m&&ua)try{let k=(v=window.__mainContainer)!=null?v:f.stage,D=(O=(S=(w=window.__tutorialLabel)!=null?w:(E=(x=m.get("label_1"))==null?void 0:x.getDisplayObject)==null?void 0:E.call(x))!=null?S:(T=m.get("label_1"))==null?void 0:T.pixiObject)!=null?O:m.get("label_1"),R=m.get("background_1"),$=(I=(C=(M=window.__background)!=null?M:(B=R==null?void 0:R.getDisplayObject)==null?void 0:B.call(R))!=null?C:R==null?void 0:R.pixiObject)!=null?I:R;if(k){let A=k===f.stage;ua({mainContainer:k,label:D,background:$,backgroundTexture:($==null?void 0:$.texture)||null,app:f},t,0,pa,m,{skipMainContainerTransform:A})}}catch(k){console.warn("[SCREEN] Error in layout:",k)}}})}let t=await me("scene.main");window.__editableConfig=t,r(),window.__editableConfigBaseline||(window.__editableConfigBaseline=U(t),console.log("[BOOTSTRAP] Frozen config baseline for persistence")),(u=(d=t.engine.runtime)==null?void 0:d.layout)!=null&&u.design_width_portrait||(console.warn("[BOOTSTRAP] Config layout missing, retrying..."),await new Promise(g=>setTimeout(g,100)),t=await me("scene.main"));let n=await fa(e,t,kt,le);Pe=n.app;let a=n.gameObjectManager;window.gameApp=Pe,window.gameObjectManager=a;try{window.__liveEditBridge=Hn({getConfig:()=>window.__editableConfig,gameObjectManager:a,assets:Ot})}catch(g){console.warn("[BOOTSTRAP] Failed to initialize live-edit bridge",g)}le&&le.notifyGameLoaded();let s=window.__debugScale;s&&typeof s=="number"&&(it.scale=s,console.log(`[DEBUG] Applied persisted debug scale: ${s}`)),o(Pe,a);async function r(){try{let g=async y=>{let v=y.startsWith("/")?y:`/${y}`,x=await fetch(v,{cache:"no-cache"});if(!x.ok)return null;let E=await x.text();try{return JSON.parse(E)}catch{return null}},h=await g("configs/flow/app.flow.json");if(!h||typeof h!="object")return;let f=h.screens;if(!f||typeof f!="object")return;let m={},b={};for(let[y,v]of Object.entries(f)){let x=v==null?void 0:v.source;if(typeof x!="string")continue;let E=await g(x),w=E==null?void 0:E.elements;if(!Array.isArray(w))continue;let T=w.map(S=>S==null?void 0:S.instance_id).filter(S=>typeof S=="string");m[y]=T;for(let S of T)b[S]||(b[S]=y)}window.__HANDLER_APP_FLOW=h,window.__HANDLER_SCREEN_INDEX={screenToInstances:m,instanceToScreen:b},window.dispatchEvent(new CustomEvent("handler:screen-index-loaded"))}catch{}}function o(g,h){if(Qo){console.log("[RESPONSIVE] Skipping global scaling; using config-driven layout");return}if(console.log("[RESPONSIVE] ===== APPLYING GLOBAL RESPONSIVE SCALING ====="),console.log(`[RESPONSIVE] Scale multiplier: ${it.scale.toFixed(3)}`),g.stage){let m=function(b,y=0){if(!b||!b.children)return;let v=" ".repeat(y);b.children.forEach((x,E)=>{if(x&&x.zIndex===9999){console.log(`${v}[RESPONSIVE] Skipping debug border (zIndex 9999)`);return}if(x&&x.scale){let w=x.scale.x||1,T=x.scale.y||1;x.__originalScale||(x.__originalScale={x:w,y:T},console.log(`${v}[RESPONSIVE] Stored original scale for child[${E}]: ${w.toFixed(3)}, ${T.toFixed(3)}`));let S=x.__originalScale.x*it.scale,O=x.__originalScale.y*it.scale;typeof x.scale.set=="function"?x.scale.set(S,O):(x.scale.x=S,x.scale.y=O),console.log(`${v}[RESPONSIVE] Child[${E}] scale: ${w.toFixed(3)}\u2192${x.scale.x.toFixed(3)} (type: ${x.constructor.name})`),m(x,y+1)}else x&&console.log(`${v}[RESPONSIVE] Child[${E}] has no scale (type: ${x.constructor.name})`)})};var f=m;console.log("[RESPONSIVE] Applying scale to PIXI stage children"),m(g.stage)}else console.warn("[RESPONSIVE] No app.stage found!");console.log("[REDDEBUG] Debug border left unscaled (fixed boundaries)"),console.log("[RESPONSIVE] ===== GLOBAL RESPONSIVE SCALING COMPLETE =====")}function l(g){if(g!==void 0){it.scale=g,console.log(`[RESPONSIVE] Updated global scale multiplier to: ${g.toFixed(3)}`);let h=window.gameApp,f=window.gameObjectManager;h&&f?(o(h,f),h.renderer&&(h.renderer.render(h.stage),console.log("[RESPONSIVE] Forced PIXI renderer update"))):console.warn(`[RESPONSIVE] No gameApp (${!!h}) or gameObjectManager (${!!f}) found in window for live update`)}}window.updateGlobalResponsiveMultipliers=l,Oe.start()},fr=async()=>{var e,t,n,a;console.log("[PREVIEW] Restarting game in 1 seconds...");let i=(e=window.gameObjectManager)==null?void 0:e.get("character_1");if(i){let s=((t=i.getDisplayObject)==null?void 0:t.call(i))||i;s&&s.scale&&console.log(`[CHARACTER] Before restart - Current scale - x: ${((n=s.scale.x)!=null?n:1).toFixed(3)}, y: ${((a=s.scale.y)!=null?a:1).toFixed(3)}`)}if(le){le.notifyGameDestroyed();try{ga&&ga()}catch(s){console.warn("Failed to clear responsive elements",s)}setTimeout(()=>{console.log("[PREVIEW] Executing restart...");let s=le.getGameContainer(),r=window.gameObjectManager;if(r&&typeof r.clear=="function"&&(console.log("[PREVIEW] Clearing old GameObjectManager tickers..."),r.clear()),Pe){try{Pe.destroy(!0,{children:!0,texture:!1})}catch(o){console.warn("[PREVIEW] Destroy warning:",o)}Pe=null}window.gameApp=null,window.gameObjectManager=null,s&&(s.innerHTML="");try{typeof Ot.resetScene=="function"&&Ot.resetScene()}catch(o){console.warn("Asset reset failed",o)}setTimeout(()=>{me("scene.main").then(o=>{window.__editableConfig=o,window.__editableConfigBaseline||(window.__editableConfigBaseline=U(o)),fa(s,o,kt).then(l=>{Pe=l.app,window.gameApp=Pe,window.gameObjectManager=l.gameObjectManager;try{window.__liveEditBridge=Hn({getConfig:()=>window.__editableConfig,gameObjectManager:window.gameObjectManager,assets:Ot})}catch(c){console.warn("[BOOTSTRAP] Failed to re-initialize live-edit bridge",c)}le&&le.notifyGameLoaded(),console.log("[PREVIEW] Game restarted successfully");try{Oe.start()}catch{}})})},100)},1e3)}};dn();ee();var ce={background:"#F6F3EF",ink:"#1E1E1E",secondaryText:"#8E8A84",primaryAccent:"#E38A5A",secondaryAccent:"#C9A28C",statusGreen:"#5F8F6B"},br=1.25,yr={fontFamily:"Inter, system-ui, sans-serif"};var Fn=class{constructor(e={}){this.currentProgress=0;var t;this.currentProgress=(t=e.progress)!=null?t:0,this.container=this.createContainer()}createContainer(){let e=document.createElement("div");e.className="handler-loading-screen",e.style.cssText=`
1524
1447
  position: fixed;
1525
1448
  inset: 0;
1526
1449
  display: flex;
@@ -1529,8 +1452,8 @@ Style guidelines: ${n.summary}`;this.promptInput.value=r,this.currentPrompt=r}}c
1529
1452
  z-index: 50;
1530
1453
  user-select: none;
1531
1454
  overflow: hidden;
1532
- background-color: ${We.background};
1533
- `;let i=document.createElement("div");i.style.cssText=`
1455
+ background-color: ${ce.background};
1456
+ `;let t=document.createElement("div");t.style.cssText=`
1534
1457
  position: relative;
1535
1458
  width: 288px;
1536
1459
  display: flex;
@@ -1543,29 +1466,29 @@ Style guidelines: ${n.summary}`;this.promptInput.value=r,this.currentPrompt=r}}c
1543
1466
  height: 96px;
1544
1467
  opacity: 0.9;
1545
1468
  transform: scale(0.9);
1546
- `,n.innerHTML='<div class="boxLoading"></div>',i.appendChild(n);let r=document.createElement("div");r.style.cssText=`
1469
+ `,n.innerHTML='<div class="boxLoading"></div>',t.appendChild(n);let a=document.createElement("div");a.style.cssText=`
1547
1470
  width: 100%;
1548
1471
  position: relative;
1549
1472
  display: flex;
1550
1473
  flex-direction: column;
1551
1474
  align-items: center;
1552
- `;let a=document.createElement("div");a.style.cssText=`
1475
+ `;let s=document.createElement("div");s.style.cssText=`
1553
1476
  width: 100%;
1554
1477
  display: flex;
1555
1478
  justify-content: space-between;
1556
1479
  align-items: flex-end;
1557
1480
  margin-bottom: 8px;
1558
- `;let s=document.createElement("span");s.style.cssText=`
1481
+ `;let r=document.createElement("span");r.style.cssText=`
1559
1482
  font-size: 12px;
1560
1483
  font-weight: 900;
1561
1484
  letter-spacing: 0.15em;
1562
- color: ${We.ink};
1563
- `,s.innerHTML='LOADING<span class="loading-dots" style="animation: pulse 1.5s infinite;">..</span>',this.progressText=document.createElement("span"),this.progressText.style.cssText=`
1485
+ color: ${ce.ink};
1486
+ `,r.innerHTML='LOADING<span class="loading-dots" style="animation: pulse 1.5s infinite;">..</span>',this.progressText=document.createElement("span"),this.progressText.style.cssText=`
1564
1487
  font-size: 10px;
1565
1488
  font-family: monospace;
1566
1489
  font-weight: bold;
1567
- color: ${We.primaryAccent};
1568
- `,this.progressText.textContent=`${Math.floor(this.currentProgress)}%`,a.appendChild(s),a.appendChild(this.progressText);let o=document.createElement("div");o.style.cssText=`
1490
+ color: ${ce.primaryAccent};
1491
+ `,this.progressText.textContent=`${Math.floor(this.currentProgress)}%`,s.appendChild(r),s.appendChild(this.progressText);let o=document.createElement("div");o.style.cssText=`
1569
1492
  height: 4px;
1570
1493
  width: 100%;
1571
1494
  background-color: #E0DDD8;
@@ -1579,7 +1502,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=r,this.currentPrompt=r}}c
1579
1502
  border-radius: 9999px;
1580
1503
  position: relative;
1581
1504
  width: ${this.currentProgress}%;
1582
- background-color: ${We.primaryAccent};
1505
+ background-color: ${ce.primaryAccent};
1583
1506
  `;let l=document.createElement("div");l.style.cssText=`
1584
1507
  position: absolute;
1585
1508
  inset: 0;
@@ -1595,11 +1518,11 @@ Style guidelines: ${n.summary}`;this.promptInput.value=r,this.currentPrompt=r}}c
1595
1518
  margin-top: 8px;
1596
1519
  padding: 0 4px;
1597
1520
  opacity: 0.4;
1598
- `;for(let p=0;p<9;p++){let f=document.createElement("div");f.style.cssText=`
1521
+ `;for(let u=0;u<9;u++){let g=document.createElement("div");g.style.cssText=`
1599
1522
  width: 1.5px;
1600
1523
  background-color: black;
1601
- height: ${p%4===0?"6px":"2px"};
1602
- `,c.appendChild(f)}r.appendChild(a),r.appendChild(o),r.appendChild(c);let d=document.createElement("div");return d.id="handler-load-centered",d.style.cssText=`
1524
+ height: ${u%4===0?"6px":"2px"};
1525
+ `,c.appendChild(g)}a.appendChild(s),a.appendChild(o),a.appendChild(c);let p=document.createElement("div");return p.id="handler-load-centered",p.style.cssText=`
1603
1526
  position: absolute;
1604
1527
  top: 48px;
1605
1528
  width: 600px;
@@ -1608,7 +1531,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=r,this.currentPrompt=r}}c
1608
1531
  left: 50%;
1609
1532
  transform: translateX(-50%);
1610
1533
  overflow: visible;
1611
- `,"HANDLER".split("").forEach((p,f)=>{let g=document.createElement("div");g.textContent=p,g.style.cssText=`
1534
+ `,"HANDLER".split("").forEach((u,g)=>{let h=document.createElement("div");h.textContent=u,h.style.cssText=`
1612
1535
  position: absolute;
1613
1536
  width: 28px;
1614
1537
  height: 40px;
@@ -1618,12 +1541,12 @@ Style guidelines: ${n.summary}`;this.promptInput.value=r,this.currentPrompt=r}}c
1618
1541
  font-size: 24px;
1619
1542
  letter-spacing: -0.05em;
1620
1543
  animation: handlerMove 2.5s linear infinite;
1621
- color: ${We.ink};
1544
+ color: ${ce.ink};
1622
1545
  display: flex;
1623
1546
  align-items: center;
1624
1547
  justify-content: center;
1625
- animation-delay: ${[1.05,.875,.7,.525,.35,.175,0][f]}s;
1626
- `,d.appendChild(g)}),i.appendChild(r),i.appendChild(d),this.authSeq=document.createElement("div"),this.authSeq.style.cssText=`
1548
+ animation-delay: ${[1.05,.875,.7,.525,.35,.175,0][g]}s;
1549
+ `,p.appendChild(h)}),t.appendChild(a),t.appendChild(p),this.authSeq=document.createElement("div"),this.authSeq.style.cssText=`
1627
1550
  position: absolute;
1628
1551
  bottom: 48px;
1629
1552
  font-size: 8px;
@@ -1631,8 +1554,8 @@ Style guidelines: ${n.summary}`;this.promptInput.value=r,this.currentPrompt=r}}c
1631
1554
  letter-spacing: 0.3em;
1632
1555
  opacity: 0.2;
1633
1556
  text-transform: uppercase;
1634
- color: ${We.ink};
1635
- `,this.authSeq.textContent=`Auth_Seq: 0x${Math.floor(this.currentProgress*2.55).toString(16).toUpperCase()} // System_Ready`,t.appendChild(i),t.appendChild(this.authSeq),this.injectStyles(),t}injectStyles(){if(document.getElementById("handler-loading-screen-styles"))return;let t=document.createElement("style");t.id="handler-loading-screen-styles",t.textContent=`
1557
+ color: ${ce.ink};
1558
+ `,this.authSeq.textContent=`Auth_Seq: 0x${Math.floor(this.currentProgress*2.55).toString(16).toUpperCase()} // System_Ready`,e.appendChild(t),e.appendChild(this.authSeq),this.injectStyles(),e}injectStyles(){if(document.getElementById("handler-loading-screen-styles"))return;let e=document.createElement("style");e.id="handler-loading-screen-styles",e.textContent=`
1636
1559
  /* Box Loading Styles */
1637
1560
  .boxLoading {
1638
1561
  width: 50px;
@@ -1662,7 +1585,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=r,this.currentPrompt=r}}c
1662
1585
  content: '';
1663
1586
  width: 50px;
1664
1587
  height: 50px;
1665
- background: ${We.primaryAccent};
1588
+ background: ${ce.primaryAccent};
1666
1589
  animation: animate 0.5s linear infinite;
1667
1590
  position: absolute;
1668
1591
  top: 0;
@@ -1719,7 +1642,7 @@ Style guidelines: ${n.summary}`;this.promptInput.value=r,this.currentPrompt=r}}c
1719
1642
  0%, 100% { opacity: 1; }
1720
1643
  50% { opacity: 0.3; }
1721
1644
  }
1722
- `,document.head.appendChild(t)}setProgress(t){this.currentProgress=Math.max(0,Math.min(100,t)),this.progressBar.style.width=`${this.currentProgress}%`,this.progressText.textContent=`${Math.floor(this.currentProgress)}%`,this.authSeq.textContent=`Auth_Seq: 0x${Math.floor(this.currentProgress*2.55).toString(16).toUpperCase()} // System_Ready`}mount(t=document.body){t.appendChild(this.container)}unmount(){this.container.parentElement&&this.container.parentElement.removeChild(this.container)}getElement(){return this.container}};var xc=$c.version,Jw=new Set(["init","boot","view","ready","start","pause","resume","complete","error","engagement","first_interaction","retry","cta_show","cta_click","cta_dismiss","clickout","conversion","session_time","level_time","load_time","level_start","level_complete","level_fail","checkpoint","reward","tutorial_start","tutorial_complete","tutorial_skip","ab_assign","fps","memory","asset_load_start","asset_load_complete"]);Fc();var Ug={mechanic_id:"TODO_mechanic_id",variant_id:"TODO_variant_id",deployment_id:"TODO_deployment_id",export_id:"TODO_export_id",profile_id:"TODO_profile_id",instance_id:"default"},qg=Math.random().toString(36).slice(2),Zi=null,Ki={...Ug},Gg="web_embed",Sc={},lr,wc=!1,or=!1,dr=!1,Wg=!1,kc=1,ls=0,us=!1,pt=!1,Xi="",Ji=Math.floor(window.innerWidth),Qi=Math.floor(window.innerHeight),Ac=Ji>Qi,ft=!1,cr=!1,zg=!1,Ng=!1,_c=!1,cs=null,si=null,Cc=!1,Tc=!1,os=new Map;function Vg(){if(!si)return null;let e=Date.now()-si;return!Number.isFinite(e)||e<0?null:e}function Ec(e){if(Cc)return;let t=Vg();t!==null&&(Cc=!0,M("session_time",{duration_ms:t,reason:e}))}function Bg(){if(Zi)return Zi;let e=document.createElement("div");return e.id="handler-root",e.setAttribute("data-handler-root","true"),document.body.appendChild(e),Zi=e,e}function ds(e){switch(e){case"interaction":return"engagement";case"finish":return"complete";case"install":return"cta_click";default:return e}}function Yg(e,t){return{event_name:e,ts:Date.now(),session_id:qg,deployment_id:Ki.deployment_id,variant_id:Ki.variant_id,export_profile_id:Ki.profile_id,instance_id:Ki.instance_id||"default",env:Gg==="mraid"?"mraid":"web",attribution:lr,payload:t}}function M(e,t){let i=ds(e),n=Yg(i,t);ys(n,!!Sc.analytics),mr(i,n),i!==e&&mr(e,n)}function ur(){cs&&(cs(Ji,Qi),cs=null)}function en(e){kc=e,M("volume",e)}function tn(e){e&&(Wg=!0),!dr&&(dr=!0,M("pause"),en(0))}function pr(e){!e&&Wg||dr&&(dr=!1,M("resume"),en(kc))}function jt(e,t){Ji=Math.floor(e||window.innerWidth),Qi=Math.floor(t||window.innerHeight),Ac=Ji>Qi,M("resize",{width:Ji,height:Qi})}function Qw(){if(Qc())try{let e=mraid.getMaxSize();jt(e.width,e.height);let t=()=>{mraid.isViewable()&&mraid.getState()!=="hidden"?pr():tn()};if(mraid.addEventListener("viewableChange",t),mraid.addEventListener("stateChange",t),mraid.addEventListener("sizeChange",()=>{let i=mraid.getMaxSize();jt(i.width,i.height)}),mraid.getAudioVolume){let i=mraid.getAudioVolume();en(i?1:0)}if(mraid.addEventListener("audioVolumeChange",i=>{i!==null&&en(i>0?1:0)}),mraid.addEventListener("error",(i,n)=>{console.warn("mraid error:",i,"action:",n)}),us=!0,mraid.isViewable()&&mraid.getState()!=="hidden")ft=!0,M("boot"),M("view"),M("ready"),pt=!0,ur();else{let i=()=>{ft=!0,M("boot"),M("view"),M("ready"),pt=!0,ur()};mraid.addEventListener("ready",i)}}catch(e){console.warn("MRAID hook skipped",e)}}function e0(){if(ed())try{let e=dapi.getScreenSize();jt(e.width,e.height),dapi.addEventListener("viewableChange",i=>{i.isViewable?pr():tn()}),dapi.addEventListener("adResized",i=>{let n=dapi.getScreenSize();jt(i.width||n.width,i.height||n.height)});let t=dapi.getAudioVolume();if(en(t?1:0),dapi.addEventListener("audioVolumeChange",i=>en(i?1:0)),us=!0,dapi.isViewable())ft=!0,M("boot"),M("view"),M("ready"),pt=!0,ur();else{let i=()=>{ft=!0,M("boot"),M("view"),M("ready"),pt=!0,ur()};dapi.addEventListener("ready",i)}}catch(e){console.warn("DAPI hook skipped",e)}}function Fg(){let e=()=>{ft||document.visibilityState==="visible"&&(document.readyState==="complete"||document.readyState==="interactive")&&(ft=!0,M("boot"),M("view"),M("ready"),pt=!0,ur(),cr&&(cr=!1,Pe.start()))};window.addEventListener("resize",()=>jt()),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"?(pr(),e()):tn()}),document.readyState==="complete"||document.readyState==="interactive"?e():window.addEventListener("load",e),us=!0}function t0(){let e=t=>{typeof TouchEvent!="undefined"&&t instanceof TouchEvent&&(zg=!0),!(zg&&t instanceof MouseEvent)&&(ls+=1,Tc||(Tc=!0,M("first_interaction",{count:ls})),M("interaction",ls))};document.addEventListener("mousedown",e),document.addEventListener("touchstart",e)}function $g(e){var n,r,a,s,o,l,c,d,u,p,f,g;let t=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none";if((typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed")==="google")try{(n=window.ExitApi)==null||n.exit();return}catch{}if(t==="mraid"&&typeof mraid!="undefined")mraid.open(e||"");else if(t==="dapi"&&typeof dapi!="undefined")dapi.openStoreUrl();else if(fi())(a=(r=window.TJ_API)==null?void 0:r.click)==null||a.call(r);else if(td())(o=(s=window.FbPlayableAd)==null?void 0:s.onCTAClick)==null||o.call(s);else if(ad())(c=(l=window.ScPlayableAd)==null?void 0:l.onCTAClick)==null||c.call(l);else if(rd())try{(u=(d=window.smxTracking)==null?void 0:d.redirect)==null||u.call(d)}catch(h){console.warn("Smadex redirect failed",h)}else if(id()){let h=window.ExitApi;h&&typeof h.exit=="function"?h.exit(e||Xi||""):e&&window.open(e)}else pi()?(p=window.install)==null||p.call(window):nd()?(f=window.openAppStore)==null||f.call(window):vs()?(g=parent==null?void 0:parent.postMessage)==null||g.call(parent,"download","*"):e&&window.open(e)}function i0(){let e=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed",t=i=>{if(!i)return;let n=new Image;n.src=i};if(e==="bigabid"){let i=window.BIGABID_BIDTIMEMACROS;if(!i)return;be("view",()=>t(i.mraid_viewable)),be("start",()=>t(i.game_viewable)),be("engagement",()=>t(i.engagement));let n=()=>t(i.complete);be("complete",n),gr("engagement",r=>{var a;((a=r==null?void 0:r.payload)==null?void 0:a.count)>3&&n()}),be("cta_click",()=>t(i.click))}else if(e==="inmobi"){let i=window.INMOBI_DSPMACROS;if(!i)return;be("view",()=>t(i.Ad_Load_Start)),be("start",()=>t(i.Ad_Viewable)),be("engagement",()=>t(i.First_Engagement)),be("complete",()=>t(i.Gameplay_Complete)),be("cta_click",()=>t(i.DSP_Click)),be("start",()=>{[5,10,15,20,25,30].forEach(n=>setTimeout(()=>t(i[`Spent_${n}_Seconds`]),n*1e3))})}}function n0(){if(!fi())return;let e=window.TJ_API;e&&e.setPlayableAPI&&e.setPlayableAPI({skipAd:()=>{try{Pe.finish()}catch(t){console.warn("Tapjoy skip failed",t)}}})}function Hg(){var t,i,n;let e=window.TJ_API;(t=e==null?void 0:e.objectiveComplete)==null||t.call(e),(i=e==null?void 0:e.playableFinished)==null||i.call(e),(n=e==null?void 0:e.gameplayFinished)==null||n.call(e)}function r0(){pi()&&(window.mintGameStart=()=>{pr(!0),jt()},window.mintGameClose=()=>{tn(!0)})}function a0(){if(!xs())return;let e=window.NUC;!e||!e.trigger||(Pe.on("cta_click",()=>{var t,i;return(i=(t=e.trigger).convert)==null?void 0:i.call(t,Xi)}),Pe.on("complete",()=>{var t,i;return(i=(t=e.trigger).tryAgain)==null?void 0:i.call(t)}))}var Pe={init(e={},t){var i;if(Gg=e.profile||"web_embed",Sc=e.consent||{},Ki={...Ug,...e.ids||{}},Zi=e.rootEl||Zi,lr=void 0,Pc((i=e.telemetry)!=null&&i.endpoint?e.telemetry:null),si=null,Cc=!1,Tc=!1,os.clear(),Xi=e.destinationUrl||(/android/i.test(navigator.userAgent)?"https://play.google.com/store":"https://www.apple.com/app-store/"),t&&(cs=t),M("init"),document.body.oncontextmenu=()=>!1,Bg(),o0(Zi),sd(),Qw(),e0(),!us){if(document.readyState==="complete")Fg();else if(!Ng){Ng=!0;let n=()=>{Fg(),window.removeEventListener("load",n),document.removeEventListener("DOMContentLoaded",n)};window.addEventListener("load",n),document.addEventListener("DOMContentLoaded",n)}}t0(),i0(),n0(),r0(),a0(),console.log(`%c @handler/playable-sdk %c v${xc} `,"background: #007acc; color: #fff; font-size: 14px; padding: 4px 8px; border-top-left-radius: 4px; border-bottom-left-radius: 4px;","background: #e1e4e8; color: #333; font-size: 14px; padding: 4px 8px; border-top-right-radius: 4px; border-bottom-right-radius: 4px;"),ft&&!pt&&(M("boot"),M("view"),M("ready"),cr&&(cr=!1,Pe.start()),pt=!0),pt=ft},getRoot(){return Bg()},get version(){return xc},get maxWidth(){return Ji},get maxHeight(){return Qi},get isLandscape(){return Ac},get isReady(){return pt},get isStarted(){return wc},get isPaused(){return dr},get isFinished(){return or},get volume(){return kc},get interactions(){return ls},on(e,t){gr(ds(e),t)},off(e,t){bs(ds(e),t)},start(){var e,t;if(!wc){if(!ft){cr=!0;return}if(wc=!0,si||(si=Date.now()),M("start"),jt(),pi())tn(),(e=window.gameReady)==null||e.call(window);else if(fi()){let i=window.TJ_API;(t=i==null?void 0:i.setPlayableBuild)==null||t.call(i,{orientation:Ac?"landscape":"portrait",buildID:xc})}}},finish(){var e,t;or||(or=!0,M("complete"),Ec("complete"),pi()?(e=window.gameEnd)==null||e.call(window):vs()?(t=parent==null?void 0:parent.postMessage)==null||t.call(parent,"complete","*"):fi()&&Hg())},install(e){if(!or){or=!0,fi()?(Hg(),setTimeout(()=>Pe.install(e),300)):(M("complete"),setTimeout(()=>Pe.install(e),0));return}_c||(_c=!0,setTimeout(()=>_c=!1,500),M("cta_click"),M("conversion"),Ec("cta"),$g(e||Xi))},emit(e,t){let i=ds(e);if(!Jw.has(i)&&i!=="resize"&&i!=="volume"&&!i.startsWith("custom."))throw new Error(`Event ${e} must be canonical or namespaced as custom.<mechanic_id>.<event>`);let n=Yg(i,t);ys(n,!!Sc.analytics),mr(i,n)},gameStart(){Pe.start()},gameEnd(){Pe.finish()},ctaClick(e,t){M("cta_click",{url:e||Xi,manual:!0}),(t==null?void 0:t.open)!==!1&&$g(e||Xi)},ctaShow(e){M("cta_show",e)},ctaDismiss(e){M("cta_dismiss",e)},getGameTimeMs(){return Vg()},endSession(e="manual"){Ec(e)},setAttribution(e){lr=e},abTest(e,t){if(!e)throw new Error("abTest requires experimentId");if(!Array.isArray(t)||t.length<2)throw new Error("abTest requires at least 2 variants");let i=Math.abs(s0(`${qg}:${e}`))%t.length,n=t[i];return lr={...lr||{},experiment_id:e},Ki.variant_id=n,M("ab_assign",{experiment_id:e,variant_id:n}),n},levelStart(e,t){si||(si=Date.now()),M("level_start",{level_id:e,...t})},levelComplete(e,t){M("level_complete",{level_id:e,...t})},levelFail(e,t){M("level_fail",{level_id:e,...t})},checkpoint(e,t){M("checkpoint",{checkpoint_id:e,...t})},reward(e,t){M("reward",{reward_id:e,...t})},tutorialStart(e,t){M("tutorial_start",{step_id:e,...t})},tutorialComplete(e,t){M("tutorial_complete",{step_id:e,...t})},tutorialSkip(e,t){M("tutorial_skip",{step_id:e,...t})},timerStart(e){e&&os.set(e,Date.now())},timerEnd(e,t="custom",i){if(!e)return;let n=os.get(e);if(!n)return;os.delete(e);let r=Date.now()-n;if(!(!Number.isFinite(r)||r<0)){if(t==="custom"){M("engagement",{action:"timer",key:e,duration_ms:r,...i});return}M(t,{key:e,duration_ms:r,...i})}},fps(e,t){M("fps",{value:e,...t})},memory(e,t){M("memory",{bytes:e,...t})},assetLoadStart(e,t){M("asset_load_start",{asset_id:e,...t})},assetLoadComplete(e,t){M("asset_load_complete",{asset_id:e,...t})},reportError(e,t,i){M("error",{code:e,message:t,...i})},retry(){var e,t,i;if(pi())(e=window.gameRetry)==null||e.call(window);else if(xs()){let n=window.NUC;(i=(t=n==null?void 0:n.trigger)==null?void 0:t.tryAgain)==null||i.call(t)}M("engagement",{action:"retry"})},pause(){tn(!0)},resume(){pr(!0)},resize(e,t){jt(e,t)}},zt=Pe;function s0(e){let t=2166136261;for(let i=0;i<e.length;i++)t^=e.charCodeAt(i),t=Math.imul(t,16777619);return t|0}function o0(e){let t=document.createElement("script");t.type="text/javascript",t.textContent=`
1645
+ `,document.head.appendChild(e)}setProgress(e){this.currentProgress=Math.max(0,Math.min(100,e)),this.progressBar.style.width=`${this.currentProgress}%`,this.progressText.textContent=`${Math.floor(this.currentProgress)}%`,this.authSeq.textContent=`Auth_Seq: 0x${Math.floor(this.currentProgress*2.55).toString(16).toUpperCase()} // System_Ready`}mount(e=document.body){e.appendChild(this.container)}unmount(){this.container.parentElement&&this.container.parentElement.removeChild(this.container)}getElement(){return this.container}};var ha=$a.version,tl=new Set(["init","boot","view","ready","start","pause","resume","complete","error","engagement","first_interaction","retry","cta_show","cta_click","cta_dismiss","clickout","conversion","session_time","level_time","load_time","level_start","level_complete","level_fail","checkpoint","reward","tutorial_start","tutorial_complete","tutorial_skip","ab_assign","fps","memory","asset_load_start","asset_load_complete"]);Da();var Cr={mechanic_id:"TODO_mechanic_id",variant_id:"TODO_variant_id",deployment_id:"TODO_deployment_id",export_id:"TODO_export_id",profile_id:"TODO_profile_id",instance_id:"default"},Lr=Math.random().toString(36).slice(2),rt=null,at={...Cr},Tr="web_embed",va={},Rt,ma=!1,It=!1,Dt=!1,_r=!1,Aa=1,Un=0,Wn=!1,ye=!1,st="",ot=Math.floor(window.innerWidth),lt=Math.floor(window.innerHeight),xa=ot>lt,ve=!1,jt=!1,vr=!1,xr=!1,ba=!1,qn=null,Be=null,wa=!1,Ea=!1,Gn=new Map;function Pr(){if(!Be)return null;let i=Date.now()-Be;return!Number.isFinite(i)||i<0?null:i}function ya(i){if(wa)return;let e=Pr();e!==null&&(wa=!0,L("session_time",{duration_ms:e,reason:i}))}function wr(){if(rt)return rt;let i=document.createElement("div");return i.id="handler-root",i.setAttribute("data-handler-root","true"),document.body.appendChild(i),rt=i,i}function Vn(i){switch(i){case"interaction":return"engagement";case"finish":return"complete";case"install":return"cta_click";default:return i}}function Mr(i,e){return{event_name:i,ts:Date.now(),session_id:Lr,deployment_id:at.deployment_id,variant_id:at.variant_id,export_profile_id:at.profile_id,instance_id:at.instance_id||"default",env:Tr==="mraid"?"mraid":"web",attribution:Rt,payload:e}}function L(i,e){let t=Vn(i),n=Mr(t,e);ei(n,!!va.analytics),Ft(t,n),t!==i&&Ft(i,n)}function $t(){qn&&(qn(ot,lt),qn=null)}function ct(i){Aa=i,L("volume",i)}function dt(i){i&&(_r=!0),!Dt&&(Dt=!0,L("pause"),ct(0))}function zt(i){!i&&_r||Dt&&(Dt=!1,L("resume"),ct(Aa))}function Me(i,e){ot=Math.floor(i||window.innerWidth),lt=Math.floor(e||window.innerHeight),xa=ot>lt,L("resize",{width:ot,height:lt})}function nl(){if(Ka())try{let i=mraid.getMaxSize();Me(i.width,i.height);let e=()=>{mraid.isViewable()&&mraid.getState()!=="hidden"?zt():dt()};if(mraid.addEventListener("viewableChange",e),mraid.addEventListener("stateChange",e),mraid.addEventListener("sizeChange",()=>{let t=mraid.getMaxSize();Me(t.width,t.height)}),mraid.getAudioVolume){let t=mraid.getAudioVolume();ct(t?1:0)}if(mraid.addEventListener("audioVolumeChange",t=>{t!==null&&ct(t>0?1:0)}),mraid.addEventListener("error",(t,n)=>{console.warn("mraid error:",t,"action:",n)}),Wn=!0,mraid.isViewable()&&mraid.getState()!=="hidden")ve=!0,L("boot"),L("view"),L("ready"),ye=!0,$t();else{let t=()=>{ve=!0,L("boot"),L("view"),L("ready"),ye=!0,$t()};mraid.addEventListener("ready",t)}}catch(i){console.warn("MRAID hook skipped",i)}}function il(){if(Xa())try{let i=dapi.getScreenSize();Me(i.width,i.height),dapi.addEventListener("viewableChange",t=>{t.isViewable?zt():dt()}),dapi.addEventListener("adResized",t=>{let n=dapi.getScreenSize();Me(t.width||n.width,t.height||n.height)});let e=dapi.getAudioVolume();if(ct(e?1:0),dapi.addEventListener("audioVolumeChange",t=>ct(t?1:0)),Wn=!0,dapi.isViewable())ve=!0,L("boot"),L("view"),L("ready"),ye=!0,$t();else{let t=()=>{ve=!0,L("boot"),L("view"),L("ready"),ye=!0,$t()};dapi.addEventListener("ready",t)}}catch(i){console.warn("DAPI hook skipped",i)}}function Er(){let i=()=>{ve||document.visibilityState==="visible"&&(document.readyState==="complete"||document.readyState==="interactive")&&(ve=!0,L("boot"),L("view"),L("ready"),ye=!0,$t(),jt&&(jt=!1,ne.start()))};window.addEventListener("resize",()=>Me()),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"?(zt(),i()):dt()}),document.readyState==="complete"||document.readyState==="interactive"?i():window.addEventListener("load",i),Wn=!0}function al(){let i=e=>{typeof TouchEvent!="undefined"&&e instanceof TouchEvent&&(vr=!0),!(vr&&e instanceof MouseEvent)&&(Un+=1,Ea||(Ea=!0,L("first_interaction",{count:Un})),L("interaction",Un))};document.addEventListener("mousedown",i),document.addEventListener("touchstart",i)}function Ar(i){var n,a,s,r,o,l,c,p,d,u,g,h;let e=typeof AD_PROTOCOL!="undefined"?AD_PROTOCOL:"none";if((typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed")==="google")try{(n=window.ExitApi)==null||n.exit();return}catch{}if(e==="mraid"&&typeof mraid!="undefined")mraid.open(i||"");else if(e==="dapi"&&typeof dapi!="undefined")dapi.openStoreUrl();else if(Ke())(s=(a=window.TJ_API)==null?void 0:a.click)==null||s.call(a);else if(Ja())(o=(r=window.FbPlayableAd)==null?void 0:r.onCTAClick)==null||o.call(r);else if(ts())(c=(l=window.ScPlayableAd)==null?void 0:l.onCTAClick)==null||c.call(l);else if(es())try{(d=(p=window.smxTracking)==null?void 0:p.redirect)==null||d.call(p)}catch(f){console.warn("Smadex redirect failed",f)}else if(Za()){let f=window.ExitApi;f&&typeof f.exit=="function"?f.exit(i||st||""):i&&window.open(i)}else Ye()?(u=window.install)==null||u.call(window):Qa()?(g=window.openAppStore)==null||g.call(window):ti()?(h=parent==null?void 0:parent.postMessage)==null||h.call(parent,"download","*"):i&&window.open(i)}function sl(){let i=typeof AD_NETWORK!="undefined"?AD_NETWORK:"web_embed",e=t=>{if(!t)return;let n=new Image;n.src=t};if(i==="bigabid"){let t=window.BIGABID_BIDTIMEMACROS;if(!t)return;K("view",()=>e(t.mraid_viewable)),K("start",()=>e(t.game_viewable)),K("engagement",()=>e(t.engagement));let n=()=>e(t.complete);K("complete",n),Bt("engagement",a=>{var s;((s=a==null?void 0:a.payload)==null?void 0:s.count)>3&&n()}),K("cta_click",()=>e(t.click))}else if(i==="inmobi"){let t=window.INMOBI_DSPMACROS;if(!t)return;K("view",()=>e(t.Ad_Load_Start)),K("start",()=>e(t.Ad_Viewable)),K("engagement",()=>e(t.First_Engagement)),K("complete",()=>e(t.Gameplay_Complete)),K("cta_click",()=>e(t.DSP_Click)),K("start",()=>{[5,10,15,20,25,30].forEach(n=>setTimeout(()=>e(t[`Spent_${n}_Seconds`]),n*1e3))})}}function rl(){if(!Ke())return;let i=window.TJ_API;i&&i.setPlayableAPI&&i.setPlayableAPI({skipAd:()=>{try{ne.finish()}catch(e){console.warn("Tapjoy skip failed",e)}}})}function Sr(){var e,t,n;let i=window.TJ_API;(e=i==null?void 0:i.objectiveComplete)==null||e.call(i),(t=i==null?void 0:i.playableFinished)==null||t.call(i),(n=i==null?void 0:i.gameplayFinished)==null||n.call(i)}function ol(){Ye()&&(window.mintGameStart=()=>{zt(!0),Me()},window.mintGameClose=()=>{dt(!0)})}function ll(){if(!ni())return;let i=window.NUC;!i||!i.trigger||(ne.on("cta_click",()=>{var e,t;return(t=(e=i.trigger).convert)==null?void 0:t.call(e,st)}),ne.on("complete",()=>{var e,t;return(t=(e=i.trigger).tryAgain)==null?void 0:t.call(e)}))}var ne={init(i={},e){var t;if(Tr=i.profile||"web_embed",va=i.consent||{},at={...Cr,...i.ids||{}},rt=i.rootEl||rt,Rt=void 0,Pa((t=i.telemetry)!=null&&t.endpoint?i.telemetry:null),Be=null,wa=!1,Ea=!1,Gn.clear(),st=i.destinationUrl||(/android/i.test(navigator.userAgent)?"https://play.google.com/store":"https://www.apple.com/app-store/"),e&&(qn=e),L("init"),document.body.oncontextmenu=()=>!1,wr(),dl(rt),ns(),nl(),il(),!Wn){if(document.readyState==="complete")Er();else if(!xr){xr=!0;let n=()=>{Er(),window.removeEventListener("load",n),document.removeEventListener("DOMContentLoaded",n)};window.addEventListener("load",n),document.addEventListener("DOMContentLoaded",n)}}al(),sl(),rl(),ol(),ll(),console.log(`%c @handler/playable-sdk %c v${ha} `,"background: #007acc; color: #fff; font-size: 14px; padding: 4px 8px; border-top-left-radius: 4px; border-bottom-left-radius: 4px;","background: #e1e4e8; color: #333; font-size: 14px; padding: 4px 8px; border-top-right-radius: 4px; border-bottom-right-radius: 4px;"),ve&&!ye&&(L("boot"),L("view"),L("ready"),jt&&(jt=!1,ne.start()),ye=!0),ye=ve},getRoot(){return wr()},get version(){return ha},get maxWidth(){return ot},get maxHeight(){return lt},get isLandscape(){return xa},get isReady(){return ye},get isStarted(){return ma},get isPaused(){return Dt},get isFinished(){return It},get volume(){return Aa},get interactions(){return Un},on(i,e){Bt(Vn(i),e)},off(i,e){Qn(Vn(i),e)},start(){var i,e;if(!ma){if(!ve){jt=!0;return}if(ma=!0,Be||(Be=Date.now()),L("start"),Me(),Ye())dt(),(i=window.gameReady)==null||i.call(window);else if(Ke()){let t=window.TJ_API;(e=t==null?void 0:t.setPlayableBuild)==null||e.call(t,{orientation:xa?"landscape":"portrait",buildID:ha})}}},finish(){var i,e;It||(It=!0,L("complete"),ya("complete"),Ye()?(i=window.gameEnd)==null||i.call(window):ti()?(e=parent==null?void 0:parent.postMessage)==null||e.call(parent,"complete","*"):Ke()&&Sr())},install(i){if(!It){It=!0,Ke()?(Sr(),setTimeout(()=>ne.install(i),300)):(L("complete"),setTimeout(()=>ne.install(i),0));return}ba||(ba=!0,setTimeout(()=>ba=!1,500),L("cta_click"),L("conversion"),ya("cta"),Ar(i||st))},emit(i,e){let t=Vn(i);if(!tl.has(t)&&t!=="resize"&&t!=="volume"&&!t.startsWith("custom."))throw new Error(`Event ${i} must be canonical or namespaced as custom.<mechanic_id>.<event>`);let n=Mr(t,e);ei(n,!!va.analytics),Ft(t,n)},gameStart(){ne.start()},gameEnd(){ne.finish()},ctaClick(i,e){L("cta_click",{url:i||st,manual:!0}),(e==null?void 0:e.open)!==!1&&Ar(i||st)},ctaShow(i){L("cta_show",i)},ctaDismiss(i){L("cta_dismiss",i)},getGameTimeMs(){return Pr()},endSession(i="manual"){ya(i)},setAttribution(i){Rt=i},abTest(i,e){if(!i)throw new Error("abTest requires experimentId");if(!Array.isArray(e)||e.length<2)throw new Error("abTest requires at least 2 variants");let t=Math.abs(cl(`${Lr}:${i}`))%e.length,n=e[t];return Rt={...Rt||{},experiment_id:i},at.variant_id=n,L("ab_assign",{experiment_id:i,variant_id:n}),n},levelStart(i,e){Be||(Be=Date.now()),L("level_start",{level_id:i,...e})},levelComplete(i,e){L("level_complete",{level_id:i,...e})},levelFail(i,e){L("level_fail",{level_id:i,...e})},checkpoint(i,e){L("checkpoint",{checkpoint_id:i,...e})},reward(i,e){L("reward",{reward_id:i,...e})},tutorialStart(i,e){L("tutorial_start",{step_id:i,...e})},tutorialComplete(i,e){L("tutorial_complete",{step_id:i,...e})},tutorialSkip(i,e){L("tutorial_skip",{step_id:i,...e})},timerStart(i){i&&Gn.set(i,Date.now())},timerEnd(i,e="custom",t){if(!i)return;let n=Gn.get(i);if(!n)return;Gn.delete(i);let a=Date.now()-n;if(!(!Number.isFinite(a)||a<0)){if(e==="custom"){L("engagement",{action:"timer",key:i,duration_ms:a,...t});return}L(e,{key:i,duration_ms:a,...t})}},fps(i,e){L("fps",{value:i,...e})},memory(i,e){L("memory",{bytes:i,...e})},assetLoadStart(i,e){L("asset_load_start",{asset_id:i,...e})},assetLoadComplete(i,e){L("asset_load_complete",{asset_id:i,...e})},reportError(i,e,t){L("error",{code:i,message:e,...t})},retry(){var i,e,t;if(Ye())(i=window.gameRetry)==null||i.call(window);else if(ni()){let n=window.NUC;(t=(e=n==null?void 0:n.trigger)==null?void 0:e.tryAgain)==null||t.call(e)}L("engagement",{action:"retry"})},pause(){dt(!0)},resume(){zt(!0)},resize(i,e){Me(i,e)}},Oe=ne;function cl(i){let e=2166136261;for(let t=0;t<i.length;t++)e^=i.charCodeAt(t),e=Math.imul(e,16777619);return e|0}function dl(i){let e=document.createElement("script");e.type="text/javascript",e.textContent=`
1723
1646
  (function(){
1724
1647
  var events = ['touchstart','touchend','mousedown','keydown'];
1725
1648
  function unlock(){
@@ -1735,4 +1658,4 @@ Style guidelines: ${n.summary}`;this.promptInput.value=r,this.currentPrompt=r}}c
1735
1658
  }
1736
1659
  events.forEach(function(e){ document.addEventListener(e, unlock, false); });
1737
1660
  })();
1738
- `,e.appendChild(t)}0&&(module.exports={COLORS,ConfigWatcher,DebugPanel,DefaultReloadStrategy,Handler,PlayableLoadingScreen,PreviewShell,STROKE_WIDTH,THEME,applyConfigOverride,applyConfigOverrides,applyConfigsToDisk,applyDefaults,baseLottie,bootstrap,clearConfigOverrides,clearConfigOverridesForObject,configOverrideManager,createPreviewShell,deepClone,defaultPreset,deviceGroups,devicePresets,diffConfigs,exportConfigsAsJSON,getConfigOverrides,getConfigStateSummary,getOverrideMode,getPresetById,getPresetsByCategory,loadAllObjectConfigs,loadComponentSchemas,loadEngineConfig,loadGamePromptConfig,loadObjectCentricConfig,loadObjectConfig,loadSceneConfig,rehydrateObject,removeConfigOverride,resetToApplied,resetToOriginal,setBootstrapDependencies,setOverrideMode,setupHotReload,setupLiveEditBridge,toLegacyFormat,validateObjectConfig});
1661
+ `,i.appendChild(e)}0&&(module.exports={COLORS,ConfigWatcher,DebugPanel,DefaultReloadStrategy,Handler,PlayableLoadingScreen,PreviewShell,STROKE_WIDTH,THEME,applyConfigOverride,applyConfigOverrides,applyConfigsToDisk,applyDefaults,baseLottie,bootstrap,clearConfigOverrides,clearConfigOverridesForObject,configOverrideManager,createPreviewShell,deepClone,defaultPreset,deviceGroups,devicePresets,diffConfigs,exportConfigsAsJSON,getConfigOverrides,getConfigStateSummary,getOverrideMode,getPresetById,getPresetsByCategory,loadAllObjectConfigs,loadComponentSchemas,loadEngineConfig,loadGamePromptConfig,loadObjectCentricConfig,loadObjectConfig,loadSceneConfig,rehydrateObject,removeConfigOverride,resetToApplied,resetToOriginal,setBootstrapDependencies,setOverrideMode,setupHotReload,setupLiveEditBridge,toLegacyFormat,validateObjectConfig});