@storvia/sdk 0.3.0 → 0.3.1

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.js CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var M=Object.defineProperty;var A=Object.getOwnPropertyDescriptor;var F=Object.getOwnPropertyNames;var G=Object.prototype.hasOwnProperty;var z=(l,e)=>{for(var t in e)M(l,t,{get:e[t],enumerable:!0})},j=(l,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of F(e))!G.call(l,i)&&i!==t&&M(l,i,{get:()=>e[i],enumerable:!(n=A(e,i))||n.enumerable});return l};var V=l=>j(M({},"__esModule",{value:!0}),l);var se={};z(se,{StorviaError:()=>p,StorviaSDK:()=>T,createStorviaSDK:()=>H,extractFieldValue:()=>U,isRichFieldValue:()=>$});module.exports=V(se);var p=class extends Error{constructor(e,t){super(t),this.name="StorviaError",this.code=e}};var P=class{constructor(e,t,n=!1,i=""){this.baseUrl=e,this.token=t,this.debug=n,this.devApiKey=i}setToken(e){this.token=e}setDebug(e){this.debug=e}buildHeaders(){let e={"Content-Type":"application/json"};return this.token&&(e.Authorization=`Bearer ${this.token}`),this.devApiKey&&(e["x-api-key"]=this.devApiKey),e}log(e,t,n,i,s){if(!this.debug)return;let r="%c[Storvia SDK]",o="color: #6366f1; font-weight: bold";s?(console.groupCollapsed(`${r} %c${e} ${t} %c\u2717`,o,"color: #e0e0e0","color: #ef4444"),n&&console.log("Request:",n),console.error("Error:",s),console.groupEnd()):(console.groupCollapsed(`${r} %c${e} ${t} %c\u2713`,o,"color: #e0e0e0","color: #22c55e"),n&&console.log("Request:",n),i!==void 0&&console.log("Response:",i),console.groupEnd())}async get(e,t){let n=new URL(`${this.baseUrl}${e}`);t&&Object.entries(t).forEach(([i,s])=>n.searchParams.set(i,s));try{let i=await fetch(n.toString(),{method:"GET",headers:this.buildHeaders()}),s=await this.handleResponse(i);return this.log("GET",e,t,s),s}catch(i){throw this.log("GET",e,t,void 0,i),i}}async post(e,t){try{let n=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0}),i=await this.handleResponse(n);return this.log("POST",e,t,i),i}catch(n){throw this.log("POST",e,t,void 0,n),n}}async patch(e,t){try{let n=await fetch(`${this.baseUrl}${e}`,{method:"PATCH",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0}),i=await this.handleResponse(n);return this.log("PATCH",e,t,i),i}catch(n){throw this.log("PATCH",e,t,void 0,n),n}}async delete(e){try{let t=await fetch(`${this.baseUrl}${e}`,{method:"DELETE",headers:this.buildHeaders()}),n=await this.handleResponse(t);return this.log("DELETE",e,void 0,n),n}catch(t){throw this.log("DELETE",e,void 0,void 0,t),t}}async stream(e,t,n,i){this.log("STREAM",e,t);let s=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify(t)});if(!s.ok){let d=await s.json().catch(()=>({})),h=new p(d.code||"INTERNAL_ERROR",d.message||`HTTP ${s.status}`);throw this.log("STREAM",e,t,void 0,h),h}let r=s.body?.getReader();if(!r)throw new p("INTERNAL_ERROR","No response body for stream");let o=new TextDecoder,a="",c="";for(;;){let{done:d,value:h}=await r.read();if(d)break;let v=o.decode(h,{stream:!0}).split(`
2
- `);for(let f of v){if(!f.startsWith("data: "))continue;let L=f.slice(6);if(L==="[DONE]"){this.debug&&this.log("STREAM",e+" [done]",void 0,{id:a,contentLength:c.length}),i(a);return}try{let b=JSON.parse(L);b.type==="done"&&b.id?a=b.id:b.content&&(c+=b.content,n(b.content))}catch{}}}a&&i(a)}async handleResponse(e){if(!e.ok){let n={};try{n=await e.json()}catch{}let i={401:"UNAUTHORIZED",402:"INSUFFICIENT_BALANCE",404:"GAME_NOT_FOUND",429:"RATE_LIMITED"},s=n.code||i[e.status]||"INTERNAL_ERROR";throw new p(s,n.message||`HTTP ${e.status}`)}let t=await e.json();return t&&typeof t=="object"&&"data"in t?t.data:t}};var R=[{value:"zh-CN",label:"\u7B80\u4F53\u4E2D\u6587"},{value:"zh-TW",label:"\u7E41\u9AD4\u4E2D\u6587"},{value:"en",label:"English"},{value:"ja",label:"\u65E5\u672C\u8A9E"},{value:"ko",label:"\uD55C\uAD6D\uC5B4"}],N=[{value:"low",label:"\u7B80\u77ED"},{value:"medium",label:"\u9002\u4E2D"},{value:"high",label:"\u8BE6\u7EC6"}],Y="https://cdn.storvia.ai/default/logo.png",X="https://api.storvia.ai/storage/v1/object/public/storvia/default/credits.png",W=`
1
+ "use strict";var _=Object.defineProperty;var z=Object.getOwnPropertyDescriptor;var V=Object.getOwnPropertyNames;var Y=Object.prototype.hasOwnProperty;var X=(o,e)=>{for(var t in e)_(o,t,{get:e[t],enumerable:!0})},W=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of V(e))!Y.call(o,i)&&i!==t&&_(o,i,{get:()=>e[i],enumerable:!(n=z(e,i))||n.enumerable});return o};var K=o=>W(_({},"__esModule",{value:!0}),o);var le={};X(le,{StorviaError:()=>h,StorviaSDK:()=>T,createStorviaSDK:()=>G,extractFieldValue:()=>j,isRichFieldValue:()=>L});module.exports=K(le);var h=class extends Error{constructor(e,t){super(t),this.name="StorviaError",this.code=e}};var R=class{constructor(e,t,n=!1,i=""){this.baseUrl=e,this.token=t,this.debug=n,this.devApiKey=i}setToken(e){this.token=e}setDebug(e){this.debug=e}buildHeaders(){let e={"Content-Type":"application/json"};return this.token&&(e.Authorization=`Bearer ${this.token}`),this.devApiKey&&(e["x-api-key"]=this.devApiKey),e}log(e,t,n,i,s){if(!this.debug)return;let r="%c[Storvia SDK]",a="color: #6366f1; font-weight: bold";s?(console.groupCollapsed(`${r} %c${e} ${t} %c\u2717`,a,"color: #e0e0e0","color: #ef4444"),n&&console.log("Request:",n),console.error("Error:",s),console.groupEnd()):(console.groupCollapsed(`${r} %c${e} ${t} %c\u2713`,a,"color: #e0e0e0","color: #22c55e"),n&&console.log("Request:",n),i!==void 0&&console.log("Response:",i),console.groupEnd())}async get(e,t){let n=new URL(`${this.baseUrl}${e}`);t&&Object.entries(t).forEach(([i,s])=>n.searchParams.set(i,s));try{let i=await fetch(n.toString(),{method:"GET",headers:this.buildHeaders()}),s=await this.handleResponse(i);return this.log("GET",e,t,s),s}catch(i){throw this.log("GET",e,t,void 0,i),i}}async post(e,t){try{let n=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0}),i=await this.handleResponse(n);return this.log("POST",e,t,i),i}catch(n){throw this.log("POST",e,t,void 0,n),n}}async patch(e,t){try{let n=await fetch(`${this.baseUrl}${e}`,{method:"PATCH",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0}),i=await this.handleResponse(n);return this.log("PATCH",e,t,i),i}catch(n){throw this.log("PATCH",e,t,void 0,n),n}}async delete(e){try{let t=await fetch(`${this.baseUrl}${e}`,{method:"DELETE",headers:this.buildHeaders()}),n=await this.handleResponse(t);return this.log("DELETE",e,void 0,n),n}catch(t){throw this.log("DELETE",e,void 0,void 0,t),t}}async stream(e,t,n,i){this.log("STREAM",e,t);let s=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify(t)});if(!s.ok){let d=await s.json().catch(()=>({})),c=new h(d.code||"INTERNAL_ERROR",d.message||`HTTP ${s.status}`);throw this.log("STREAM",e,t,void 0,c),c}let r=s.body?.getReader();if(!r)throw new h("INTERNAL_ERROR","No response body for stream");let a=new TextDecoder,l="",p="";for(;;){let{done:d,value:c}=await r.read();if(d)break;let g=a.decode(c,{stream:!0}).split(`
2
+ `);for(let v of g){if(!v.startsWith("data: "))continue;let M=v.slice(6);if(M==="[DONE]"){this.debug&&this.log("STREAM",e+" [done]",void 0,{id:l,contentLength:p.length}),i(l);return}try{let b=JSON.parse(M);b.type==="done"&&b.id?l=b.id:b.content&&(p+=b.content,n(b.content))}catch{}}}l&&i(l)}async handleResponse(e){if(!e.ok){let n={};try{n=await e.json()}catch{}let i={401:"UNAUTHORIZED",402:"INSUFFICIENT_BALANCE",404:"GAME_NOT_FOUND",429:"RATE_LIMITED"},s=n.code||i[e.status]||"INTERNAL_ERROR";throw new h(s,n.message||`HTTP ${e.status}`)}let t=await e.json();return t&&typeof t=="object"&&"data"in t?t.data:t}};var k=[{value:"zh-CN",label:"\u7B80\u4F53\u4E2D\u6587"},{value:"zh-TW",label:"\u7E41\u9AD4\u4E2D\u6587"},{value:"en",label:"English"},{value:"ja",label:"\u65E5\u672C\u8A9E"},{value:"ko",label:"\uD55C\uAD6D\uC5B4"}],D=[{value:"low",label:"\u7B80\u77ED"},{value:"medium",label:"\u9002\u4E2D"},{value:"high",label:"\u8BE6\u7EC6"}],Z="https://cdn.storvia.ai/default/logo.png",q="https://api.storvia.ai/storage/v1/object/public/storvia/default/credits.png",J=`
3
3
  :host {
4
4
  position: fixed;
5
5
  z-index: 2147483647;
@@ -673,7 +673,7 @@
673
673
  padding-bottom: calc(16px + env(safe-area-inset-bottom, 0px));
674
674
  }
675
675
  }
676
- `,K='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 6L6 18M6 6l12 12"/></svg>',Z='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2v6h-6M3 12a9 9 0 0 1 15-6.7L21 8M3 22v-6h6M21 12a9 9 0 0 1-15 6.7L3 16"/></svg>',q='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="spin"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',J='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',Q='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>',D='<svg class="check" viewBox="0 0 24 24" fill="none" stroke="#8246FF" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',m=48,u=16,ee=5,y=class{constructor(e){this.selectedModelId="";this.models=[];this.settings={temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.activeTab="model";this.selectedCategory=null;this.hasWorldUpdate=!1;this.fabDot=null;this.syncHint=null;this.fabX=0;this.fabY=0;this.fab=null;this.panel=null;this.modelTabBtn=null;this.settingsTabBtn=null;this.modelBody=null;this.settingsBody=null;this.footer=null;this.modelGrid=null;this.modelDetail=null;this.tempValueEl=null;this.segmentBtns=[];this.langDropdown=null;this.langOptions=[];this.langArrow=null;this.langDropdownOpen=!1;this.noteCounter=null;this.saveBtn=null;this.syncBtn=null;this.syncState="idle";this.dragStartX=0;this.dragStartY=0;this.dragOffsetX=0;this.dragOffsetY=0;this.dragMoved=!1;this.dragging=!1;this.handlePointerDown=e=>{this.fab&&(e.preventDefault(),this.dragStartX=e.clientX,this.dragStartY=e.clientY,this.dragOffsetX=e.clientX-this.fabX,this.dragOffsetY=e.clientY-this.fabY,this.dragMoved=!1,this.dragging=!0,this.fab.setPointerCapture(e.pointerId),this.fab.addEventListener("pointermove",this.handlePointerMove),this.fab.addEventListener("pointerup",this.handlePointerUp),this.fab.addEventListener("pointercancel",this.handlePointerUp))};this.handlePointerMove=e=>{if(!this.dragging)return;let t=e.clientX-this.dragStartX,n=e.clientY-this.dragStartY;!this.dragMoved&&Math.hypot(t,n)>ee&&(this.dragMoved=!0,this.fab?.classList.add("dragging"),this.closePanel()),this.dragMoved&&(this.fabX=e.clientX-this.dragOffsetX,this.fabY=e.clientY-this.dragOffsetY,this.applyHostPosition())};this.handlePointerUp=e=>{if(!this.fab)return;this.fab.removeEventListener("pointermove",this.handlePointerMove),this.fab.removeEventListener("pointerup",this.handlePointerUp),this.fab.removeEventListener("pointercancel",this.handlePointerUp);try{this.fab.releasePointerCapture(e.pointerId)}catch{}if(this.dragging=!1,!this.dragMoved){this.togglePanel();return}this.fab.classList.remove("dragging");let n=this.fabX+m/2<window.innerWidth/2;this.fabX=n?u:window.innerWidth-m-u,this.fabY=Math.max(u,Math.min(window.innerHeight-m-u,this.fabY)),this.fab&&(this.fab.style.transition="left 0.25s cubic-bezier(0.32, 0.72, 0, 1), top 0.25s cubic-bezier(0.32, 0.72, 0, 1), transform 0.2s, box-shadow 0.2s"),this.applyHostPosition(),setTimeout(()=>{this.fab&&(this.fab.style.transition="")},260)};this.handleResize=()=>{this.fabX=Math.max(u,Math.min(window.innerWidth-m-u,this.fabX)),this.fabY=Math.max(u,Math.min(window.innerHeight-m-u,this.fabY)),this.applyHostPosition()};this.handleDocClick=e=>{this.host.contains(e.target)||(this.closePanel(),this.closeLangDropdown())};this.savedBodyOverflow=null;this.callbacks=e,this.host=document.createElement("div"),this.host.id="storvia-settings",this.shadowRoot=this.host.attachShadow({mode:"closed"})}mount(e,t,n,i=!1){this.models=e,this.selectedModelId=t,this.settings={...n},this.hasWorldUpdate=i,this.fabX=window.innerWidth-m-u,this.fabY=window.innerHeight-m-u,document.body.appendChild(this.host),this.render(),this.applyHostPosition(),window.addEventListener("resize",this.handleResize),document.addEventListener("click",this.handleDocClick)}unmount(){window.removeEventListener("resize",this.handleResize),document.removeEventListener("click",this.handleDocClick),this.host.remove()}getSelectedModelId(){return this.selectedModelId}getSettings(){return{...this.settings}}render(){let e=document.createElement("style");e.textContent=W;let t=document.createElement("div");t.className="fab-wrap";let n=document.createElement("div");n.className="fab",n.title="\u6E38\u620F\u8BBE\u7F6E";let i=document.createElement("img");i.src=Y,i.alt="Storvia",n.appendChild(i),this.fab=n;let s=document.createElement("div");s.className=`fab-dot${this.hasWorldUpdate?" visible":""}`,this.fabDot=s,t.appendChild(n),t.appendChild(s);let r=document.createElement("div");r.className="panel",this.panel=r;let o=document.createElement("div");o.className="panel-header";let a=document.createElement("h2");a.className="panel-title",a.textContent="\u6E38\u620F\u8BBE\u7F6E";let c=document.createElement("button");c.className="close-btn",c.innerHTML=K,c.addEventListener("click",()=>this.closePanel()),o.appendChild(a),o.appendChild(c),r.appendChild(o);let d=document.createElement("div");d.className="tabs",this.modelTabBtn=this.createTabBtn("model","\u6A21\u578B\u9009\u62E9"),this.settingsTabBtn=this.createTabBtn("settings","\u6E38\u620F\u8BBE\u7F6E"),this.models.length===0&&(this.activeTab="settings",this.modelTabBtn.style.display="none"),d.appendChild(this.modelTabBtn),d.appendChild(this.settingsTabBtn),r.appendChild(d);let h=document.createElement("div");h.className="panel-body",this.modelBody=this.buildModelTab(),this.settingsBody=this.buildSettingsTab(),h.appendChild(this.modelBody),h.appendChild(this.settingsBody),r.appendChild(h);let g=document.createElement("div");g.className="panel-footer";let v=document.createElement("button");v.className="btn btn-save",v.textContent="\u4FDD\u5B58",this.saveBtn=v,v.addEventListener("click",()=>this.handleSave()),g.appendChild(v),this.footer=g,r.appendChild(g),n.addEventListener("pointerdown",this.handlePointerDown);let f=document.createElement("div");f.appendChild(r),f.appendChild(t),this.shadowRoot.appendChild(e),this.shadowRoot.appendChild(f),this.applyTab()}createTabBtn(e,t){let n=document.createElement("button");return n.className=`tab-btn${this.activeTab===e?" active":""}`,n.textContent=t,n.addEventListener("click",()=>{this.activeTab=e,this.applyTab()}),n}applyTab(){this.modelTabBtn&&this.modelTabBtn.classList.toggle("active",this.activeTab==="model"),this.settingsTabBtn&&this.settingsTabBtn.classList.toggle("active",this.activeTab==="settings"),this.modelBody&&(this.modelBody.style.display=this.activeTab==="model"?"block":"none"),this.settingsBody&&(this.settingsBody.style.display=this.activeTab==="settings"?"block":"none"),this.footer&&(this.footer.style.display=this.activeTab==="settings"?"flex":"none")}buildModelTab(){let e=document.createElement("div"),t=this.getCategories();if(t.length>0){let s=document.createElement("div");s.className="category-tabs";let r=(o,a)=>{let c=document.createElement("button");return c.className=`category-tab${this.selectedCategory===a?" active":""}`,c.textContent=o,c.addEventListener("click",()=>{this.selectedCategory=a,s.querySelectorAll(".category-tab").forEach(d=>d.classList.remove("active")),c.classList.add("active"),this.renderModelGrid()}),c};s.appendChild(r("\u5168\u90E8",null)),t.forEach(o=>s.appendChild(r(o,o))),e.appendChild(s)}let n=document.createElement("div");n.className="models-grid",this.modelGrid=n,e.appendChild(n);let i=document.createElement("div");return i.className="model-detail",i.style.display="none",this.modelDetail=i,e.appendChild(i),this.renderModelGrid(),this.renderModelDetail(),e}getCategories(){let e=new Set;return this.models.forEach(t=>{t.category&&e.add(t.category)}),Array.from(e)}getFilteredModels(){return this.selectedCategory?this.models.filter(e=>e.category===this.selectedCategory):this.models}renderModelGrid(){this.modelGrid&&(this.modelGrid.innerHTML="",this.getFilteredModels().forEach(e=>{let t=document.createElement("button"),n=e.is_active!==!1;t.className=`model-card${e.id===this.selectedModelId?" selected":""}${n?"":" disabled"}`;let i=this.getStatusDotColor(e);t.innerHTML=`<span class="status-dot" style="background:${i}"></span><span class="model-name">${this.escapeHtml(e.name)}</span>`,t.addEventListener("click",()=>this.handleSelectModel(e)),this.modelGrid.appendChild(t)}))}handleSelectModel(e){if(this.selectedModelId=e.id,e.is_active!==!1){this.callbacks.onModelChange(e.id);try{localStorage.setItem("storvia_model_id",e.id)}catch{}}let t=this.getFilteredModels();this.modelGrid&&this.modelGrid.querySelectorAll(".model-card").forEach((n,i)=>{n.classList.toggle("selected",t[i].id===this.selectedModelId)}),this.renderModelDetail()}renderModelDetail(){if(!this.modelDetail)return;let e=this.models.find(r=>r.id===this.selectedModelId);if(!e){this.modelDetail.style.display="none";return}this.modelDetail.style.display="block";let t=this.getStatusClass(e),n=this.getStatusText(e),i=this.getCreditsRange(e),s=e.description||"";this.modelDetail.innerHTML=`
676
+ `,Q='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 6L6 18M6 6l12 12"/></svg>',ee='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2v6h-6M3 12a9 9 0 0 1 15-6.7L21 8M3 22v-6h6M21 12a9 9 0 0 1-15 6.7L3 16"/></svg>',te='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="spin"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',ne='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',ie='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>',N='<svg class="check" viewBox="0 0 24 24" fill="none" stroke="#8246FF" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',m=48,u=16,se=5,y=class{constructor(e){this.selectedModelId="";this.models=[];this.settings={temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.activeTab="model";this.selectedCategory=null;this.hasWorldUpdate=!1;this.fabDot=null;this.syncHint=null;this.fabX=0;this.fabY=0;this.fab=null;this.panel=null;this.modelTabBtn=null;this.settingsTabBtn=null;this.modelBody=null;this.settingsBody=null;this.footer=null;this.modelGrid=null;this.modelDetail=null;this.tempValueEl=null;this.segmentBtns=[];this.langDropdown=null;this.langOptions=[];this.langArrow=null;this.langDropdownOpen=!1;this.noteCounter=null;this.saveBtn=null;this.syncBtn=null;this.syncState="idle";this.dragStartX=0;this.dragStartY=0;this.dragOffsetX=0;this.dragOffsetY=0;this.dragMoved=!1;this.dragging=!1;this.handlePointerDown=e=>{this.fab&&(e.preventDefault(),this.dragStartX=e.clientX,this.dragStartY=e.clientY,this.dragOffsetX=e.clientX-this.fabX,this.dragOffsetY=e.clientY-this.fabY,this.dragMoved=!1,this.dragging=!0,this.fab.setPointerCapture(e.pointerId),this.fab.addEventListener("pointermove",this.handlePointerMove),this.fab.addEventListener("pointerup",this.handlePointerUp),this.fab.addEventListener("pointercancel",this.handlePointerUp))};this.handlePointerMove=e=>{if(!this.dragging)return;let t=e.clientX-this.dragStartX,n=e.clientY-this.dragStartY;!this.dragMoved&&Math.hypot(t,n)>se&&(this.dragMoved=!0,this.fab?.classList.add("dragging"),this.closePanel()),this.dragMoved&&(this.fabX=e.clientX-this.dragOffsetX,this.fabY=e.clientY-this.dragOffsetY,this.applyHostPosition())};this.handlePointerUp=e=>{if(!this.fab)return;this.fab.removeEventListener("pointermove",this.handlePointerMove),this.fab.removeEventListener("pointerup",this.handlePointerUp),this.fab.removeEventListener("pointercancel",this.handlePointerUp);try{this.fab.releasePointerCapture(e.pointerId)}catch{}if(this.dragging=!1,!this.dragMoved){this.togglePanel();return}this.fab.classList.remove("dragging");let n=this.fabX+m/2<window.innerWidth/2;this.fabX=n?u:window.innerWidth-m-u,this.fabY=Math.max(u,Math.min(window.innerHeight-m-u,this.fabY)),this.fab&&(this.fab.style.transition="left 0.25s cubic-bezier(0.32, 0.72, 0, 1), top 0.25s cubic-bezier(0.32, 0.72, 0, 1), transform 0.2s, box-shadow 0.2s"),this.applyHostPosition(),setTimeout(()=>{this.fab&&(this.fab.style.transition="")},260)};this.handleResize=()=>{this.fabX=Math.max(u,Math.min(window.innerWidth-m-u,this.fabX)),this.fabY=Math.max(u,Math.min(window.innerHeight-m-u,this.fabY)),this.applyHostPosition()};this.handleDocClick=e=>{this.host.contains(e.target)||(this.closePanel(),this.closeLangDropdown())};this.savedBodyOverflow=null;this.callbacks=e,this.host=document.createElement("div"),this.host.id="storvia-settings",this.shadowRoot=this.host.attachShadow({mode:"closed"})}mount(e,t,n,i=!1){this.models=e,this.selectedModelId=t,this.settings={...n},this.hasWorldUpdate=i,this.fabX=window.innerWidth-m-u,this.fabY=window.innerHeight-m-u,document.body.appendChild(this.host),this.render(),this.applyHostPosition(),window.addEventListener("resize",this.handleResize),document.addEventListener("click",this.handleDocClick)}unmount(){window.removeEventListener("resize",this.handleResize),document.removeEventListener("click",this.handleDocClick),this.host.remove()}getSelectedModelId(){return this.selectedModelId}getSettings(){return{...this.settings}}render(){let e=document.createElement("style");e.textContent=J;let t=document.createElement("div");t.className="fab-wrap";let n=document.createElement("div");n.className="fab",n.title="\u6E38\u620F\u8BBE\u7F6E";let i=document.createElement("img");i.src=Z,i.alt="Storvia",n.appendChild(i),this.fab=n;let s=document.createElement("div");s.className=`fab-dot${this.hasWorldUpdate?" visible":""}`,this.fabDot=s,t.appendChild(n),t.appendChild(s);let r=document.createElement("div");r.className="panel",this.panel=r;let a=document.createElement("div");a.className="panel-header";let l=document.createElement("h2");l.className="panel-title",l.textContent="\u6E38\u620F\u8BBE\u7F6E";let p=document.createElement("button");p.className="close-btn",p.innerHTML=Q,p.addEventListener("click",()=>this.closePanel()),a.appendChild(l),a.appendChild(p),r.appendChild(a);let d=document.createElement("div");d.className="tabs",this.modelTabBtn=this.createTabBtn("model","\u6A21\u578B\u9009\u62E9"),this.settingsTabBtn=this.createTabBtn("settings","\u6E38\u620F\u8BBE\u7F6E"),this.models.length===0&&(this.activeTab="settings",this.modelTabBtn.style.display="none"),d.appendChild(this.modelTabBtn),d.appendChild(this.settingsTabBtn),r.appendChild(d);let c=document.createElement("div");c.className="panel-body",this.modelBody=this.buildModelTab(),this.settingsBody=this.buildSettingsTab(),c.appendChild(this.modelBody),c.appendChild(this.settingsBody),r.appendChild(c);let f=document.createElement("div");f.className="panel-footer";let g=document.createElement("button");g.className="btn btn-save",g.textContent="\u4FDD\u5B58",this.saveBtn=g,g.addEventListener("click",()=>this.handleSave()),f.appendChild(g),this.footer=f,r.appendChild(f),n.addEventListener("pointerdown",this.handlePointerDown);let v=document.createElement("div");v.appendChild(r),v.appendChild(t),this.shadowRoot.appendChild(e),this.shadowRoot.appendChild(v),this.applyTab()}createTabBtn(e,t){let n=document.createElement("button");return n.className=`tab-btn${this.activeTab===e?" active":""}`,n.textContent=t,n.addEventListener("click",()=>{this.activeTab=e,this.applyTab()}),n}applyTab(){this.modelTabBtn&&this.modelTabBtn.classList.toggle("active",this.activeTab==="model"),this.settingsTabBtn&&this.settingsTabBtn.classList.toggle("active",this.activeTab==="settings"),this.modelBody&&(this.modelBody.style.display=this.activeTab==="model"?"block":"none"),this.settingsBody&&(this.settingsBody.style.display=this.activeTab==="settings"?"block":"none"),this.footer&&(this.footer.style.display=this.activeTab==="settings"?"flex":"none")}buildModelTab(){let e=document.createElement("div"),t=this.getCategories();if(t.length>0){let s=document.createElement("div");s.className="category-tabs";let r=(a,l)=>{let p=document.createElement("button");return p.className=`category-tab${this.selectedCategory===l?" active":""}`,p.textContent=a,p.addEventListener("click",()=>{this.selectedCategory=l,s.querySelectorAll(".category-tab").forEach(d=>d.classList.remove("active")),p.classList.add("active"),this.renderModelGrid()}),p};s.appendChild(r("\u5168\u90E8",null)),t.forEach(a=>s.appendChild(r(a,a))),e.appendChild(s)}let n=document.createElement("div");n.className="models-grid",this.modelGrid=n,e.appendChild(n);let i=document.createElement("div");return i.className="model-detail",i.style.display="none",this.modelDetail=i,e.appendChild(i),this.renderModelGrid(),this.renderModelDetail(),e}getCategories(){let e=new Set;return this.models.forEach(t=>{t.category&&e.add(t.category)}),Array.from(e)}getFilteredModels(){return this.selectedCategory?this.models.filter(e=>e.category===this.selectedCategory):this.models}renderModelGrid(){this.modelGrid&&(this.modelGrid.innerHTML="",this.getFilteredModels().forEach(e=>{let t=document.createElement("button"),n=e.is_active!==!1;t.className=`model-card${e.id===this.selectedModelId?" selected":""}${n?"":" disabled"}`;let i=this.getStatusDotColor(e);t.innerHTML=`<span class="status-dot" style="background:${i}"></span><span class="model-name">${this.escapeHtml(e.name)}</span>`,t.addEventListener("click",()=>this.handleSelectModel(e)),this.modelGrid.appendChild(t)}))}handleSelectModel(e){if(this.selectedModelId=e.id,e.is_active!==!1){this.callbacks.onModelChange(e.id);try{localStorage.setItem("storvia_model_id",e.id)}catch{}}let t=this.getFilteredModels();this.modelGrid&&this.modelGrid.querySelectorAll(".model-card").forEach((n,i)=>{n.classList.toggle("selected",t[i].id===this.selectedModelId)}),this.renderModelDetail()}renderModelDetail(){if(!this.modelDetail)return;let e=this.models.find(r=>r.id===this.selectedModelId);if(!e){this.modelDetail.style.display="none";return}this.modelDetail.style.display="block";let t=this.getStatusClass(e),n=this.getStatusText(e),i=this.getCreditsRange(e),s=e.description||"";this.modelDetail.innerHTML=`
677
677
  <div class="detail-header">
678
678
  <span class="detail-title">${this.escapeHtml(e.name)}</span>
679
679
  <span class="detail-status ${t}">${n}</span>
@@ -681,8 +681,8 @@
681
681
  ${i?`<div class="detail-credits">
682
682
  <span class="credits-label">\u6D88\u8017</span>
683
683
  <span class="credits-value">${i}</span>
684
- <img class="credits-icon" src="${X}" alt="credits" />
684
+ <img class="credits-icon" src="${q}" alt="credits" />
685
685
  <span class="credits-unit">/\u6B21</span>
686
686
  </div>`:""}
687
687
  ${s?`<div class="detail-description">${this.escapeHtml(s)}</div>`:""}
688
- `}getStatusDotColor(e){if(e.is_active===!1)return"#6b7280";let t=e.success_rate??100;return t>=95?"#10b981":t>=80?"#3b82f6":t>=60?"#eab308":"#f97316"}getStatusClass(e){if(e.is_active===!1)return"inactive";let t=e.success_rate??100;return t>=95?"excellent":t>=80?"good":t>=60?"normal":"crowded"}getStatusText(e){if(e.is_active===!1)return"\u505C\u7528";let t=e.success_rate??100;return t>=95?"\u6D41\u7545":t>=80?"\u826F\u597D":t>=60?"\u4E00\u822C":"\u62E5\u6324"}getCreditsRange(e){let t=e.credits_config?.min??0,n=e.credits_config?.max??0;return t===0&&n===0?"":t===n?`${t}`:`${t}\uFF5E${n}`}buildSettingsTab(){let e=document.createElement("div"),t=document.createElement("div");return t.className="form-stack",t.appendChild(this.buildTemperatureSection()),t.appendChild(this.buildReplyLengthSection()),t.appendChild(this.buildReplyLanguageSection()),t.appendChild(this.buildNoteSection()),t.appendChild(this.buildSyncSection()),e.appendChild(t),e}buildTemperatureSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label";let n=document.createElement("span");n.textContent="\u6E29\u5EA6";let i=document.createElement("span");i.className="temperature-value",i.textContent=this.settings.temperature.toFixed(1),this.tempValueEl=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("p");s.className="form-hint",s.textContent="\u66F4\u4F4E\u8BA9 AI \u56DE\u590D\u66F4\u7A33\u5B9A\u7406\u667A\uFF0C\u66F4\u9AD8\u8BA9\u56DE\u590D\u66F4\u5177\u591A\u6837\u6027",e.appendChild(s);let r=document.createElement("input");r.type="range",r.className="slider",r.min="0",r.max="1",r.step="0.1",r.value=String(this.settings.temperature),r.addEventListener("input",()=>{let a=parseFloat(r.value);this.settings.temperature=a,this.tempValueEl&&(this.tempValueEl.textContent=a.toFixed(1))}),e.appendChild(r);let o=document.createElement("div");return o.className="slider-labels",o.innerHTML="<span>\u7CBE\u786E</span><span>\u521B\u610F</span>",e.appendChild(o),e}buildReplyLengthSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label",t.textContent="\u56DE\u590D\u957F\u5EA6",e.appendChild(t);let n=document.createElement("div");return n.className="segment-control",this.segmentBtns=[],N.forEach(i=>{let s=document.createElement("button");s.className=`segment-button${i.value===this.settings.reply_length?" active":""}`,s.textContent=i.label,s.addEventListener("click",()=>{this.settings.reply_length=i.value,this.segmentBtns.forEach((r,o)=>{r.classList.toggle("active",N[o].value===i.value)})}),this.segmentBtns.push(s),n.appendChild(s)}),e.appendChild(n),e}buildReplyLanguageSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label",t.textContent="\u56DE\u590D\u8BED\u8A00",e.appendChild(t);let n=document.createElement("div");n.className="custom-select";let i=document.createElement("button");i.className="select-trigger";let s=document.createElement("span");s.textContent=R.find(a=>a.value===this.settings.reply_language)?.label||"";let r=document.createElement("span");r.className="select-arrow",r.textContent="\u25BE",this.langArrow=r,i.appendChild(s),i.appendChild(r),i.addEventListener("click",a=>{a.stopPropagation(),this.toggleLangDropdown()}),n.appendChild(i);let o=document.createElement("div");return o.className="select-dropdown",this.langDropdown=o,this.langOptions=[],R.forEach(a=>{let c=document.createElement("button");c.className=`select-option${a.value===this.settings.reply_language?" active":""}`,c.innerHTML=`<span>${a.label}</span>${a.value===this.settings.reply_language?D:""}`,c.addEventListener("click",()=>{this.settings.reply_language=a.value,s.textContent=a.label,this.langOptions.forEach((d,h)=>{d.classList.toggle("active",R[h].value===a.value),d.innerHTML=`<span>${R[h].label}</span>${R[h].value===a.value?D:""}`}),this.closeLangDropdown()}),this.langOptions.push(c),o.appendChild(c)}),n.appendChild(o),e.appendChild(n),e}toggleLangDropdown(){this.langDropdownOpen?this.closeLangDropdown():this.openLangDropdown()}openLangDropdown(){this.langDropdownOpen=!0,this.langDropdown?.classList.add("open"),this.langArrow&&(this.langArrow.textContent="\u25B4")}closeLangDropdown(){this.langDropdownOpen=!1,this.langDropdown?.classList.remove("open"),this.langArrow&&(this.langArrow.textContent="\u25BE")}buildNoteSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label";let n=document.createElement("span");n.textContent="\u5907\u6CE8";let i=document.createElement("span");i.className="char-count",i.textContent=`${this.settings.player_note.length}/50`,this.noteCounter=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("p");s.className="form-hint",s.textContent="\u5199\u4E0B\u4F60\u5BF9\u8FD9\u4E2A\u6E38\u620F\u7684\u5907\u6CE8\uFF0C\u4F1A\u663E\u793A\u5728\u5B58\u6863\u5217\u8868",e.appendChild(s);let r=document.createElement("textarea");return r.className="player-note-input",r.placeholder="\u5907\u6CE8",r.maxLength=50,r.rows=2,r.value=this.settings.player_note,r.addEventListener("input",()=>{this.settings.player_note=r.value,this.noteCounter&&(this.noteCounter.textContent=`${r.value.length}/50`)}),e.appendChild(r),e}buildSyncSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label",t.textContent="\u540C\u6B65\u6E38\u620F\u8BBE\u5B9A",e.appendChild(t);let n=document.createElement("p");n.className=`sync-hint${this.hasWorldUpdate?" visible":""}`,n.textContent="\u26A0 \u4F5C\u8005\u5DF2\u66F4\u65B0\u6E38\u620F\u5185\u5BB9\uFF0C\u5EFA\u8BAE\u70B9\u51FB\u540C\u6B65",this.syncHint=n,e.appendChild(n);let i=document.createElement("p");i.className="form-hint",i.textContent="\u5C06\u6700\u65B0\u6E38\u620F\u8BBE\u5B9A\u548C\u5F00\u5E55\u5C0F\u5267\u573A\u540C\u6B65\u5230\u5F53\u524D\u5BF9\u8BDD",e.appendChild(i);let s=document.createElement("button");return s.className="btn btn-sync",this.syncBtn=s,this.renderSyncBtn(),s.addEventListener("click",async()=>{if(this.syncState!=="loading"){this.setSyncState("loading");try{await this.callbacks.onSync(),this.setSyncState("success"),this.hasWorldUpdate=!1,this.fabDot&&this.fabDot.classList.remove("visible"),this.syncHint&&this.syncHint.classList.remove("visible"),setTimeout(()=>this.setSyncState("idle"),3e3)}catch{this.setSyncState("error"),setTimeout(()=>this.setSyncState("idle"),4e3)}}}),e.appendChild(s),e}setSyncState(e){this.syncState=e,this.renderSyncBtn()}renderSyncBtn(){if(!this.syncBtn)return;let e=this.syncState,t={idle:Z,loading:q,success:J,error:Q},n={idle:"\u540C\u6B65\u6700\u65B0\u8BBE\u5B9A",loading:"\u540C\u6B65\u4E2D...",success:"\u5DF2\u540C\u6B65",error:"\u540C\u6B65\u5931\u8D25"};this.syncBtn.className=`btn btn-sync${e==="success"||e==="error"?` ${e}`:""}`,this.syncBtn.disabled=e==="loading",this.syncBtn.innerHTML=`${t[e]}<span>${n[e]}</span>`}async handleSave(){if(!(!this.saveBtn||this.saveBtn.disabled)){this.saveBtn.disabled=!0,this.saveBtn.innerHTML='<span class="spinner"></span>\u4FDD\u5B58\u4E2D...';try{await this.callbacks.onSettingsChange({temperature:this.settings.temperature,reply_length:this.settings.reply_length,reply_language:this.settings.reply_language,player_note:this.settings.player_note}),this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1)}catch{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58\u5931\u8D25",setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1)},2e3))}}}escapeHtml(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}applyHostPosition(){this.host.style.left=`${this.fabX}px`,this.host.style.top=`${this.fabY}px`,this.host.style.right="auto",this.host.style.bottom="auto",this.applyPanelPosition()}isMobile(){return window.innerWidth<=768}applyPanelPosition(){if(!this.panel)return;if(this.isMobile()){this.panel.style.left="",this.panel.style.right="",this.panel.style.top="",this.panel.style.bottom="";return}let e=this.fabX+m/2<window.innerWidth/2,t=380;e?(this.panel.style.left="0",this.panel.style.right="auto"):(this.panel.style.left=`${m-t}px`,this.panel.style.right="auto"),this.fabY>500?(this.panel.style.bottom=`${m+8}px`,this.panel.style.top="auto"):(this.panel.style.top=`${m+8}px`,this.panel.style.bottom="auto")}togglePanel(){this.panel&&(this.panel.classList.contains("open")?this.closePanel():(this.applyPanelPosition(),this.panel.classList.add("open"),requestAnimationFrame(()=>{this.panel?.classList.contains("open")&&(this.fab&&(this.fab.style.visibility="hidden"),this.fabDot&&(this.fabDot.style.visibility="hidden"))}),this.isMobile()&&this.lockBodyScroll()))}closePanel(){this.panel&&this.panel.classList.remove("open"),this.fab&&(this.fab.style.visibility="visible"),this.fabDot&&(this.fabDot.style.visibility="visible"),this.unlockBodyScroll()}lockBodyScroll(){this.savedBodyOverflow===null&&(this.savedBodyOverflow=document.body.style.overflow||"",document.body.style.overflow="hidden")}unlockBodyScroll(){this.savedBodyOverflow!==null&&(document.body.style.overflow=this.savedBodyOverflow,this.savedBodyOverflow=null)}};var w=class{constructor(e,t,n,i,s=!1,r){this.http=e;this.getGameId=t;this.getConversationId=n;this.getModelId=i;this.isPreview=s;this.previewConfig=r}updatePreviewConfig(e){this.previewConfig=e}async send(e){if(this.isPreview)return this.sendPreview(e);let t={game_id:this.getGameId(),conversation_id:this.getConversationId(),model_id:this.getModelId(),message:e.message,topic:e.topic,scene_key:e.scene_key,stream:e.stream??!1};if(e.stream){await this.http.stream("/chat",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/chat",t)}async save(e){return this.isPreview?{id:`preview-${Date.now()}`}:this.http.post("/messages/save",{conversation_id:this.getConversationId(),role:e.role,content:e.content,topic:e.topic})}async generate(e){if(this.isPreview)return this.sendPreview({message:"",topic:e.topic,scene_key:e.scene_key,stream:e.stream,onChunk:e.onChunk,onDone:e.onDone});let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,scene_key:e.scene_key,stream:e.stream??!1,save:e.save??!0};if(e.stream){await this.http.stream("/generate",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/generate",t)}async retry(e={}){if(this.isPreview)throw new Error("Retry is not supported in preview mode");let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,scene_key:e.scene_key,stream:e.stream??!1};if(e.stream){await this.http.stream("/retry",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/retry",t)}async sendPreview(e){let t={model_id:this.getModelId(),message:e.message,topic:e.topic,scene_key:e.scene_key,history_messages:[]};if(this.previewConfig?t.prompt_config=this.previewConfig:t.game_id=this.getGameId(),e.stream){await this.http.stream("/preview",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}let n="";return await this.http.stream("/preview",t,i=>{n+=i},()=>{}),{id:"",content:n}}};var _=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){return this.isPreview?{...this.mem[e]||{}}:this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,t)}},C=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];this.state=new _(e,t,n)}async list(){return this.isPreview?this.mem.map(e=>({name:e.name,avatar:e.avatar,...e.gender?{gender:e.gender}:{}})):this.http.get(`/conversations/${this.getConversationId()}/characters`)}async get(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:t?.name||e,avatar:t?.avatar,...t?.gender?{gender:t.gender}:{}}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async add(e){if(this.isPreview){this.mem.push(e);return}await this.http.post(`/conversations/${this.getConversationId()}/characters`,e)}async update(e,t){if(this.isPreview){let n=this.mem.find(i=>i.name===e);n&&Object.assign(n,t);return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`,t)}async remove(e){if(this.isPreview){this.mem=this.mem.filter(t=>t.name!==e);return}await this.http.delete(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async detail(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:e,avatar:t?.avatar,state:await this.state.get(e)}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/detail`)}async setPriority(e,t){let n=Math.max(0,Math.min(100,Math.round(t)));this.isPreview||await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,{priority:n})}};var x=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[]}async list(){return this.isPreview?[...this.mem]:this.http.get(`/conversations/${this.getConversationId()}/relationships`)}async get(e,t){if(this.isPreview){let n=this.mem.find(i=>i.from===e&&i.to===t);if(n)return{...n};throw new Error("Relationship not found")}return this.http.get(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/relationships`,e)}async update(e,t,n){if(this.isPreview){let i=this.mem.find(s=>s.from===e&&s.to===t);i?Object.assign(i,n):this.mem.push({from:e,to:t,...n});return}await this.http.patch(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,n)}async remove(e,t){if(this.isPreview){this.mem=this.mem.filter(n=>!(n.from===e&&n.to===t));return}await this.http.delete(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var I=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async list(e){if(this.isPreview){if(e!==void 0)return{...this.mem[e]||{}};let t={};for(let[n,i]of Object.entries(this.mem))t[n]={...i};return t}return e!==void 0?this.http.get(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(e)}`):this.http.get(`/conversations/${this.getConversationId()}/inventory`)}async add(e){let{group:t,name:n,count:i=1,desc:s,iconUrl:r}=e;if(this.isPreview){if(!this.mem[t])throw new Error(`Group "${t}" does not exist`);if(n in this.mem[t])throw new Error(`Item "${n}" already exists in group "${t}"`);let o={count:i};s!==void 0&&(o.desc=s),r!==void 0&&(o.iconUrl=r),this.mem[t][n]=o;return}await this.http.post(`/conversations/${this.getConversationId()}/inventory`,{group:t,name:n,count:i,desc:s,iconUrl:r})}async update(e){let{group:t,name:n,...i}=e;if(this.isPreview){let s=this.mem[t];if(!s||!(n in s))throw new Error(`Item "${t}/${n}" not found`);Object.assign(s[n],i);return}await this.http.patch(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,i)}async remove(e){let{group:t,name:n}=e;if(this.isPreview){this.mem[t]&&delete this.mem[t][n];return}await this.http.delete(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(t)}/${encodeURIComponent(n)}`)}async move(e){let{fromGroup:t,toGroup:n,name:i,newName:s}=e;if(this.isPreview){let r=this.mem[t];if(!r||!(i in r))throw new Error(`Source item "${t}/${i}" not found`);if(!this.mem[n])throw new Error(`Target group "${n}" does not exist`);let o=s||i;if(t===n&&o===i)return;if(o in this.mem[n])throw new Error(`Item "${o}" already exists in target group`);this.mem[n][o]=r[i],delete r[i];return}await this.http.post(`/conversations/${this.getConversationId()}/inventory/move`,{fromGroup:t,toGroup:n,name:i,newName:s})}async ensureGroup(e){if(this.isPreview){this.mem[e]||(this.mem[e]={});return}await this.http.post(`/conversations/${this.getConversationId()}/inventory/groups/${encodeURIComponent(e)}`,{})}async removeGroup(e,t){let n=t?.cascade??!1;if(this.isPreview){let s=this.mem[e];if(s&&Object.keys(s).length>0&&!n)throw new Error(`Group "${e}" is not empty, pass cascade: true to force delete`);delete this.mem[e];return}let i=n?"?cascade=true":"";await this.http.delete(`/conversations/${this.getConversationId()}/inventory/groups/${encodeURIComponent(e)}${i}`)}};var E=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(){return this.isPreview?{...this.mem}:this.http.get(`/conversations/${this.getConversationId()}/world`)}async update(e){if(this.isPreview){Object.assign(this.mem,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/world`,e)}};var O=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e?{...this.mem[e]||{}}:{...this.mem};let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/player/state`,t)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/player/state`,{group:e,values:t})}},S=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.memPersona={name:""};this.state=new O(e,t,n)}async get(){return this.isPreview?{...this.memPersona}:this.http.get(`/conversations/${this.getConversationId()}/player`)}async update(e){if(this.isPreview){Object.assign(this.memPersona,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/player`,e)}};var k=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e!==void 0?this.mem[e]:{...this.mem};let t=await this.http.get(`/conversations/${this.getConversationId()}/custom`);return e!==void 0?t[e]:t}async set(e){if(this.isPreview){for(let[t,n]of Object.entries(e))typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof this.mem[t]=="object"&&this.mem[t]!==null?this.mem[t]={...this.mem[t],...n}:this.mem[t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom`,e)}async delete(e){if(this.isPreview){delete this.mem[e];return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}`)}async setGroupField(e,t,n){if(this.isPreview){(!this.mem[e]||typeof this.mem[e]!="object")&&(this.mem[e]={}),this.mem[e][t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{value:n})}async deleteGroupField(e,t){if(this.isPreview){if(typeof this.mem[e]=="object"&&this.mem[e]!==null){let n=this.mem[e];delete n[t]}return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var B="/functions/v1/world-engine/v1",te="https://api.storvia.ai";function ne(){return window.__STORVIA__||{}}function ie(l=5e3){let e=ne();return e.apiBase?Promise.resolve(e):new Promise((t,n)=>{let i=setTimeout(()=>{window.removeEventListener("message",s),n(new p("NOT_INITIALIZED","Timed out waiting for __STORVIA__ config from parent frame."))},l);function s(r){let o=null;if(r.data?.type==="storvia-init"&&r.data.apiBase?o={apiBase:r.data.apiBase,gameId:r.data.gameId,accessToken:r.data.accessToken}:r.data?.type==="storvia-preview-init"&&r.data.config&&(o=r.data.config),o&&o.apiBase){clearTimeout(i),window.removeEventListener("message",s);let a=window;a.__STORVIA__=o,t(o)}}window.addEventListener("message",s)})}var T=class{constructor(){this.baseUrl="";this.gameId="";this.conversationId="";this.modelId="";this.accessToken="";this.initialized=!1;this.isPreview=!1;this.previewConfig=void 0}async init(){if(this.initialized)return;let e=await ie(),t=e.apiBase;if(!t)throw new p("NOT_INITIALIZED","window.__STORVIA__.apiBase is not set. The platform must inject it before SDK init.");if(this.baseUrl=`${t}${B}`,this.isPreview=!!e.preview,this.previewConfig=e.previewConfig,!e.gameId)throw new p("GAME_NOT_FOUND","window.__STORVIA__.gameId is not set. The platform must inject it before SDK init.");if(this.gameId=e.gameId,!e.accessToken)throw new p("UNAUTHORIZED","window.__STORVIA__.accessToken is not set. The platform must inject the user token before SDK init.");if(this.accessToken=e.accessToken,this.http=new P(this.baseUrl,this.accessToken,!!e.debug),this.isPreview){this.conversationId="00000000-0000-0000-0000-000000000000";let d=await this.fetchModels();this.modelId=e.selectedModelId||d[0]?.id||"",this.settingsSheet=new y({onModelChange:f=>{this.modelId=f},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),d.length>0&&this.settingsSheet.mount(d,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let h=()=>this.gameId,g=()=>this.conversationId,v=()=>this.modelId;this.chat=new w(this.http,h,g,v,!0,this.previewConfig),this.characters=new C(this.http,g,!0),this.relationships=new x(this.http,g,!0),this.inventory=new I(this.http,g,!0),this.world=new E(this.http,g,!0),this.player=new S(this.http,g,!0),this.custom=new k(this.http,g,!0),this.initialized=!0,this.listenForPreviewMessages();return}let[n,i]=await Promise.all([this.authenticate(),this.fetchModels()]);this.conversationId=n.conversationId;let s=this.getSavedModelId();this.modelId=s&&i.some(d=>d.id===s)?s:i[0]?.id||"";let r=n.settings||{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.settingsSheet=new y({onModelChange:d=>{this.modelId=d},onSettingsChange:d=>this.saveSettings(d),onSync:()=>this.syncSettings()}),this.settingsSheet.mount(i,this.modelId,r,n.hasWorldUpdate??!1);let o=()=>this.gameId,a=()=>this.conversationId,c=()=>this.modelId;this.chat=new w(this.http,o,a,c),this.characters=new C(this.http,a),this.relationships=new x(this.http,a),this.inventory=new I(this.http,a),this.world=new E(this.http,a),this.player=new S(this.http,a),this.custom=new k(this.http,a),this.initialized=!0}listenForPreviewMessages(){window.addEventListener("message",e=>{!e.data||e.data.type!=="storvia-preview"||(e.data.action==="set-model"&&(this.modelId=e.data.modelId||""),e.data.action==="update-config"&&(this.previewConfig=e.data.previewConfig,this.chat&&this.chat.updatePreviewConfig(this.previewConfig)))})}async saveSettings(e){await this.http.patch("/settings",{conversation_id:this.conversationId,...e})}async syncSettings(){await this.http.post("/sync",{conversation_id:this.conversationId})}async fetchModels(){try{return await this.http.get("/models")}catch{}return[]}async authenticate(){let e=await fetch(`${this.baseUrl}/auth`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.accessToken}`},body:JSON.stringify({game_id:this.gameId})});if(!e.ok)throw e.status===401?new p("UNAUTHORIZED","User not authenticated"):e.status===404?new p("GAME_NOT_FOUND","Game not found or not published"):new p("INTERNAL_ERROR",`Auth failed: HTTP ${e.status}`);let t=await e.json();return t.data??t}getSavedModelId(){try{return localStorage.getItem("storvia_model_id")||""}catch{return""}}async initDev(e){if(this.initialized)return;this.baseUrl=`${te}${B}`,this.gameId=e.gameId,this.isPreview=!0,this.http=new P(this.baseUrl,"",!1,e.apiKey);let t=await this.fetchModels();this.modelId=t[0]?.id||"",this.conversationId="00000000-0000-0000-0000-000000000000",this.settingsSheet=new y({onModelChange:r=>{this.modelId=r},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),t.length>0&&this.settingsSheet.mount(t,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let n=()=>this.gameId,i=()=>this.conversationId,s=()=>this.modelId;this.chat=new w(this.http,n,i,s,!0,void 0),this.characters=new C(this.http,i,!0),this.relationships=new x(this.http,i,!0),this.inventory=new I(this.http,i,!0),this.world=new E(this.http,i,!0),this.player=new S(this.http,i,!0),this.custom=new k(this.http,i,!0),this.initialized=!0}};async function H(l){let e=new T;return l?.dev?await e.initDev(l.dev):await e.init(),e}function $(l){return typeof l=="object"&&l!==null&&"value"in l&&"type"in l&&(l.type==="number"||l.type==="text")}function U(l){return $(l)?l.value:l}0&&(module.exports={StorviaError,StorviaSDK,createStorviaSDK,extractFieldValue,isRichFieldValue});
688
+ `}getStatusDotColor(e){if(e.is_active===!1)return"#6b7280";let t=e.success_rate??100;return t>=95?"#10b981":t>=80?"#3b82f6":t>=60?"#eab308":"#f97316"}getStatusClass(e){if(e.is_active===!1)return"inactive";let t=e.success_rate??100;return t>=95?"excellent":t>=80?"good":t>=60?"normal":"crowded"}getStatusText(e){if(e.is_active===!1)return"\u505C\u7528";let t=e.success_rate??100;return t>=95?"\u6D41\u7545":t>=80?"\u826F\u597D":t>=60?"\u4E00\u822C":"\u62E5\u6324"}getCreditsRange(e){let t=e.credits_config?.min??0,n=e.credits_config?.max??0;return t===0&&n===0?"":t===n?`${t}`:`${t}\uFF5E${n}`}buildSettingsTab(){let e=document.createElement("div"),t=document.createElement("div");return t.className="form-stack",t.appendChild(this.buildTemperatureSection()),t.appendChild(this.buildReplyLengthSection()),t.appendChild(this.buildReplyLanguageSection()),t.appendChild(this.buildNoteSection()),t.appendChild(this.buildSyncSection()),e.appendChild(t),e}buildTemperatureSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label";let n=document.createElement("span");n.textContent="\u6E29\u5EA6";let i=document.createElement("span");i.className="temperature-value",i.textContent=this.settings.temperature.toFixed(1),this.tempValueEl=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("p");s.className="form-hint",s.textContent="\u66F4\u4F4E\u8BA9 AI \u56DE\u590D\u66F4\u7A33\u5B9A\u7406\u667A\uFF0C\u66F4\u9AD8\u8BA9\u56DE\u590D\u66F4\u5177\u591A\u6837\u6027",e.appendChild(s);let r=document.createElement("input");r.type="range",r.className="slider",r.min="0",r.max="1",r.step="0.1",r.value=String(this.settings.temperature),r.addEventListener("input",()=>{let l=parseFloat(r.value);this.settings.temperature=l,this.tempValueEl&&(this.tempValueEl.textContent=l.toFixed(1))}),e.appendChild(r);let a=document.createElement("div");return a.className="slider-labels",a.innerHTML="<span>\u7CBE\u786E</span><span>\u521B\u610F</span>",e.appendChild(a),e}buildReplyLengthSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label",t.textContent="\u56DE\u590D\u957F\u5EA6",e.appendChild(t);let n=document.createElement("div");return n.className="segment-control",this.segmentBtns=[],D.forEach(i=>{let s=document.createElement("button");s.className=`segment-button${i.value===this.settings.reply_length?" active":""}`,s.textContent=i.label,s.addEventListener("click",()=>{this.settings.reply_length=i.value,this.segmentBtns.forEach((r,a)=>{r.classList.toggle("active",D[a].value===i.value)})}),this.segmentBtns.push(s),n.appendChild(s)}),e.appendChild(n),e}buildReplyLanguageSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label",t.textContent="\u56DE\u590D\u8BED\u8A00",e.appendChild(t);let n=document.createElement("div");n.className="custom-select";let i=document.createElement("button");i.className="select-trigger";let s=document.createElement("span");s.textContent=k.find(l=>l.value===this.settings.reply_language)?.label||"";let r=document.createElement("span");r.className="select-arrow",r.textContent="\u25BE",this.langArrow=r,i.appendChild(s),i.appendChild(r),i.addEventListener("click",l=>{l.stopPropagation(),this.toggleLangDropdown()}),n.appendChild(i);let a=document.createElement("div");return a.className="select-dropdown",this.langDropdown=a,this.langOptions=[],k.forEach(l=>{let p=document.createElement("button");p.className=`select-option${l.value===this.settings.reply_language?" active":""}`,p.innerHTML=`<span>${l.label}</span>${l.value===this.settings.reply_language?N:""}`,p.addEventListener("click",()=>{this.settings.reply_language=l.value,s.textContent=l.label,this.langOptions.forEach((d,c)=>{d.classList.toggle("active",k[c].value===l.value),d.innerHTML=`<span>${k[c].label}</span>${k[c].value===l.value?N:""}`}),this.closeLangDropdown()}),this.langOptions.push(p),a.appendChild(p)}),n.appendChild(a),e.appendChild(n),e}toggleLangDropdown(){this.langDropdownOpen?this.closeLangDropdown():this.openLangDropdown()}openLangDropdown(){this.langDropdownOpen=!0,this.langDropdown?.classList.add("open"),this.langArrow&&(this.langArrow.textContent="\u25B4")}closeLangDropdown(){this.langDropdownOpen=!1,this.langDropdown?.classList.remove("open"),this.langArrow&&(this.langArrow.textContent="\u25BE")}buildNoteSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label";let n=document.createElement("span");n.textContent="\u5907\u6CE8";let i=document.createElement("span");i.className="char-count",i.textContent=`${this.settings.player_note.length}/50`,this.noteCounter=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("p");s.className="form-hint",s.textContent="\u5199\u4E0B\u4F60\u5BF9\u8FD9\u4E2A\u6E38\u620F\u7684\u5907\u6CE8\uFF0C\u4F1A\u663E\u793A\u5728\u5B58\u6863\u5217\u8868",e.appendChild(s);let r=document.createElement("textarea");return r.className="player-note-input",r.placeholder="\u5907\u6CE8",r.maxLength=50,r.rows=2,r.value=this.settings.player_note,r.addEventListener("input",()=>{this.settings.player_note=r.value,this.noteCounter&&(this.noteCounter.textContent=`${r.value.length}/50`)}),e.appendChild(r),e}buildSyncSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label",t.textContent="\u540C\u6B65\u6E38\u620F\u8BBE\u5B9A",e.appendChild(t);let n=document.createElement("p");n.className=`sync-hint${this.hasWorldUpdate?" visible":""}`,n.textContent="\u26A0 \u4F5C\u8005\u5DF2\u66F4\u65B0\u6E38\u620F\u5185\u5BB9\uFF0C\u5EFA\u8BAE\u70B9\u51FB\u540C\u6B65",this.syncHint=n,e.appendChild(n);let i=document.createElement("p");i.className="form-hint",i.textContent="\u5C06\u6700\u65B0\u6E38\u620F\u8BBE\u5B9A\u548C\u5F00\u5E55\u5C0F\u5267\u573A\u540C\u6B65\u5230\u5F53\u524D\u5BF9\u8BDD",e.appendChild(i);let s=document.createElement("button");return s.className="btn btn-sync",this.syncBtn=s,this.renderSyncBtn(),s.addEventListener("click",async()=>{if(this.syncState!=="loading"){this.setSyncState("loading");try{await this.callbacks.onSync(),this.setSyncState("success"),this.hasWorldUpdate=!1,this.fabDot&&this.fabDot.classList.remove("visible"),this.syncHint&&this.syncHint.classList.remove("visible"),setTimeout(()=>this.setSyncState("idle"),3e3)}catch{this.setSyncState("error"),setTimeout(()=>this.setSyncState("idle"),4e3)}}}),e.appendChild(s),e}setSyncState(e){this.syncState=e,this.renderSyncBtn()}renderSyncBtn(){if(!this.syncBtn)return;let e=this.syncState,t={idle:ee,loading:te,success:ne,error:ie},n={idle:"\u540C\u6B65\u6700\u65B0\u8BBE\u5B9A",loading:"\u540C\u6B65\u4E2D...",success:"\u5DF2\u540C\u6B65",error:"\u540C\u6B65\u5931\u8D25"};this.syncBtn.className=`btn btn-sync${e==="success"||e==="error"?` ${e}`:""}`,this.syncBtn.disabled=e==="loading",this.syncBtn.innerHTML=`${t[e]}<span>${n[e]}</span>`}async handleSave(){if(!(!this.saveBtn||this.saveBtn.disabled)){this.saveBtn.disabled=!0,this.saveBtn.innerHTML='<span class="spinner"></span>\u4FDD\u5B58\u4E2D...';try{await this.callbacks.onSettingsChange({temperature:this.settings.temperature,reply_length:this.settings.reply_length,reply_language:this.settings.reply_language,player_note:this.settings.player_note}),this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1)}catch{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58\u5931\u8D25",setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1)},2e3))}}}escapeHtml(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}applyHostPosition(){this.host.style.left=`${this.fabX}px`,this.host.style.top=`${this.fabY}px`,this.host.style.right="auto",this.host.style.bottom="auto",this.applyPanelPosition()}isMobile(){return window.innerWidth<=768}applyPanelPosition(){if(!this.panel)return;if(this.isMobile()){this.panel.style.left="",this.panel.style.right="",this.panel.style.top="",this.panel.style.bottom="";return}let e=this.fabX+m/2<window.innerWidth/2,t=380;e?(this.panel.style.left="0",this.panel.style.right="auto"):(this.panel.style.left=`${m-t}px`,this.panel.style.right="auto"),this.fabY>500?(this.panel.style.bottom=`${m+8}px`,this.panel.style.top="auto"):(this.panel.style.top=`${m+8}px`,this.panel.style.bottom="auto")}togglePanel(){this.panel&&(this.panel.classList.contains("open")?this.closePanel():(this.applyPanelPosition(),this.panel.classList.add("open"),requestAnimationFrame(()=>{this.panel?.classList.contains("open")&&(this.fab&&(this.fab.style.visibility="hidden"),this.fabDot&&(this.fabDot.style.visibility="hidden"))}),this.isMobile()&&this.lockBodyScroll()))}closePanel(){this.panel&&this.panel.classList.remove("open"),this.fab&&(this.fab.style.visibility="visible"),this.fabDot&&(this.fabDot.style.visibility="visible"),this.unlockBodyScroll()}lockBodyScroll(){this.savedBodyOverflow===null&&(this.savedBodyOverflow=document.body.style.overflow||"",document.body.style.overflow="hidden")}unlockBodyScroll(){this.savedBodyOverflow!==null&&(document.body.style.overflow=this.savedBodyOverflow,this.savedBodyOverflow=null)}};var w=class{constructor(e,t,n,i,s=!1,r){this.http=e;this.getGameId=t;this.getConversationId=n;this.getModelId=i;this.isPreview=s;this.previewConfig=r}updatePreviewConfig(e){this.previewConfig=e}async send(e){if(this.isPreview)return this.sendPreview(e);let t={game_id:this.getGameId(),conversation_id:this.getConversationId(),model_id:this.getModelId(),message:e.message,topic:e.topic,scene_key:e.scene_key,stream:e.stream??!1};if(e.stream){await this.http.stream("/chat",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/chat",t)}async save(e){return this.isPreview?{id:`preview-${Date.now()}`}:this.http.post("/messages/save",{conversation_id:this.getConversationId(),role:e.role,content:e.content,topic:e.topic})}async generate(e){if(this.isPreview)return this.sendPreview({message:"",topic:e.topic,scene_key:e.scene_key,stream:e.stream,onChunk:e.onChunk,onDone:e.onDone});let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,scene_key:e.scene_key,stream:e.stream??!1,save:e.save??!0};if(e.stream){await this.http.stream("/generate",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/generate",t)}async retry(e={}){if(this.isPreview)throw new Error("Retry is not supported in preview mode");let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,scene_key:e.scene_key,stream:e.stream??!1};if(e.stream){await this.http.stream("/retry",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/retry",t)}async sendPreview(e){let t={model_id:this.getModelId(),message:e.message,topic:e.topic,scene_key:e.scene_key,history_messages:[]};if(this.previewConfig?t.prompt_config=this.previewConfig:t.game_id=this.getGameId(),e.stream){await this.http.stream("/preview",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}let n="";return await this.http.stream("/preview",t,i=>{n+=i},()=>{}),{id:"",content:n}}};var O=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem={...i})}setInitial(e){this.mem=e?{...e}:{}}async get(e){return this.isPreview?{...this.mem[e]||{}}:this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,t)}},C=class{constructor(e,t,n=!1,i,s){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];i&&(this.mem=i.map(B)),this.state=new O(e,t,n,s)}setInitial(e,t){this.mem=e?e.map(B):[],this.state.setInitial(t)}async list(){return this.isPreview?this.mem.map(H):this.http.get(`/conversations/${this.getConversationId()}/characters`)}async get(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return t?H(t):{name:e}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async add(e){if(this.isPreview){this.mem.push({...e,isPreset:!1});return}await this.http.post(`/conversations/${this.getConversationId()}/characters`,e)}async update(e,t){if(this.isPreview){let n=this.mem.find(i=>i.name===e);n&&Object.assign(n,t);return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`,t)}async remove(e){if(this.isPreview){this.mem=this.mem.filter(t=>t.name!==e);return}await this.http.delete(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async detail(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:e,avatar:t?.avatar,description:t?.description,userDescription:t?.userDescription,...t?.gender?{gender:t.gender}:{},...t?.isPreset!==void 0?{isPreset:t.isPreset}:{},state:await this.state.get(e)}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/detail`)}async setPriority(e,t){let n=Math.max(0,Math.min(100,Math.round(t)));this.isPreview||await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,{priority:n})}};function B(o){return{name:o.name,description:o.description,avatar:o.avatar,...o.gender?{gender:o.gender}:{},...o.userDescription!==void 0?{userDescription:o.userDescription}:{},...o.isPreset!==void 0?{isPreset:o.isPreset}:{}}}function H(o){return{name:o.name,avatar:o.avatar,description:o.description,...o.userDescription!==void 0?{userDescription:o.userDescription}:{},...o.gender?{gender:o.gender}:{},...o.isPreset!==void 0?{isPreset:o.isPreset}:{}}}var x=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];i&&(this.mem=i.map(s=>({...s})))}setInitial(e){this.mem=e?e.map(t=>({...t})):[]}async list(){return this.isPreview?[...this.mem]:this.http.get(`/conversations/${this.getConversationId()}/relationships`)}async get(e,t){if(this.isPreview){let n=this.mem.find(i=>i.from===e&&i.to===t);if(n)return{...n};throw new Error("Relationship not found")}return this.http.get(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/relationships`,e)}async update(e,t,n){if(this.isPreview){let i=this.mem.find(s=>s.from===e&&s.to===t);i?Object.assign(i,n):this.mem.push({from:e,to:t,...n});return}await this.http.patch(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,n)}async remove(e,t){if(this.isPreview){this.mem=this.mem.filter(n=>!(n.from===e&&n.to===t));return}await this.http.delete(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var I=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem=U(i))}setInitial(e){this.mem=e?U(e):{}}async list(e){if(this.isPreview){if(e!==void 0)return{...this.mem[e]||{}};let t={};for(let[n,i]of Object.entries(this.mem))t[n]={...i};return t}return e!==void 0?this.http.get(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(e)}`):this.http.get(`/conversations/${this.getConversationId()}/inventory`)}async add(e){let{group:t,name:n,count:i=1,desc:s,iconUrl:r}=e;if(this.isPreview){if(!this.mem[t])throw new Error(`Group "${t}" does not exist`);if(n in this.mem[t])throw new Error(`Item "${n}" already exists in group "${t}"`);let a={count:i};s!==void 0&&(a.desc=s),r!==void 0&&(a.iconUrl=r),this.mem[t][n]=a;return}await this.http.post(`/conversations/${this.getConversationId()}/inventory`,{group:t,name:n,count:i,desc:s,iconUrl:r})}async update(e){let{group:t,name:n,...i}=e;if(this.isPreview){let s=this.mem[t];if(!s||!(n in s))throw new Error(`Item "${t}/${n}" not found`);Object.assign(s[n],i);return}await this.http.patch(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,i)}async remove(e){let{group:t,name:n}=e;if(this.isPreview){this.mem[t]&&delete this.mem[t][n];return}await this.http.delete(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(t)}/${encodeURIComponent(n)}`)}async move(e){let{fromGroup:t,toGroup:n,name:i,newName:s}=e;if(this.isPreview){let r=this.mem[t];if(!r||!(i in r))throw new Error(`Source item "${t}/${i}" not found`);if(!this.mem[n])throw new Error(`Target group "${n}" does not exist`);let a=s||i;if(t===n&&a===i)return;if(a in this.mem[n])throw new Error(`Item "${a}" already exists in target group`);this.mem[n][a]=r[i],delete r[i];return}await this.http.post(`/conversations/${this.getConversationId()}/inventory/move`,{fromGroup:t,toGroup:n,name:i,newName:s})}async ensureGroup(e){if(this.isPreview){this.mem[e]||(this.mem[e]={});return}await this.http.post(`/conversations/${this.getConversationId()}/inventory/groups/${encodeURIComponent(e)}`,{})}async removeGroup(e,t){let n=t?.cascade??!1;if(this.isPreview){let s=this.mem[e];if(s&&Object.keys(s).length>0&&!n)throw new Error(`Group "${e}" is not empty, pass cascade: true to force delete`);delete this.mem[e];return}let i=n?"?cascade=true":"";await this.http.delete(`/conversations/${this.getConversationId()}/inventory/groups/${encodeURIComponent(e)}${i}`)}};function U(o){let e={};for(let[t,n]of Object.entries(o)){let i={};for(let[s,r]of Object.entries(n))i[s]={...r};e[t]=i}return e}var P=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem={...i})}setInitial(e){this.mem=e?{...e}:{}}async get(){return this.isPreview?{...this.mem}:this.http.get(`/conversations/${this.getConversationId()}/world`)}async update(e){if(this.isPreview){Object.assign(this.mem,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/world`,e)}};var $=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem={...i})}setInitial(e){this.mem=e?{...e}:{}}async get(e){if(this.isPreview)return e?{...this.mem[e]||{}}:{...this.mem};let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/player/state`,t)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/player/state`,{group:e,values:t})}},S=class{constructor(e,t,n=!1,i,s){this.http=e;this.getConversationId=t;this.isPreview=n;this.memPersona={name:""};i&&(this.memPersona={...i}),this.state=new $(e,t,n,s)}setInitial(e,t){this.memPersona=e?{...e}:{name:""},this.state.setInitial(t)}async get(){return this.isPreview?{...this.memPersona}:this.http.get(`/conversations/${this.getConversationId()}/player`)}async update(e){if(this.isPreview){Object.assign(this.memPersona,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/player`,e)}};var E=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem=A(i))}setInitial(e){this.mem=e?A(e):{}}async get(e){if(this.isPreview)return e!==void 0?this.mem[e]:{...this.mem};let t=await this.http.get(`/conversations/${this.getConversationId()}/custom`);return e!==void 0?t[e]:t}async set(e){if(this.isPreview){for(let[t,n]of Object.entries(e))typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof this.mem[t]=="object"&&this.mem[t]!==null?this.mem[t]={...this.mem[t],...n}:this.mem[t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom`,e)}async delete(e){if(this.isPreview){delete this.mem[e];return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}`)}async setGroupField(e,t,n){if(this.isPreview){(!this.mem[e]||typeof this.mem[e]!="object")&&(this.mem[e]={}),this.mem[e][t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{value:n})}async deleteGroupField(e,t){if(this.isPreview){if(typeof this.mem[e]=="object"&&this.mem[e]!==null){let n=this.mem[e];delete n[t]}return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};function A(o){let e={};for(let[t,n]of Object.entries(o))typeof n=="object"&&n!==null&&!Array.isArray(n)?e[t]={...n}:e[t]=n;return e}var F="/functions/v1/world-engine/v1",re="https://api.storvia.ai";function oe(){return window.__STORVIA__||{}}function ae(o=5e3){let e=oe();return e.apiBase?Promise.resolve(e):new Promise((t,n)=>{let i=setTimeout(()=>{window.removeEventListener("message",s),n(new h("NOT_INITIALIZED","Timed out waiting for __STORVIA__ config from parent frame."))},o);function s(r){let a=null;if(r.data?.type==="storvia-init"&&r.data.apiBase?a={apiBase:r.data.apiBase,gameId:r.data.gameId,accessToken:r.data.accessToken}:r.data?.type==="storvia-preview-init"&&r.data.config&&(a=r.data.config),a&&a.apiBase){clearTimeout(i),window.removeEventListener("message",s);let l=window;l.__STORVIA__=a,t(a)}}window.addEventListener("message",s)})}var T=class{constructor(){this.baseUrl="";this.gameId="";this.conversationId="";this.modelId="";this.accessToken="";this.initialized=!1;this.isPreview=!1;this.previewConfig=void 0}async init(){if(this.initialized)return;let e=await ae(),t=e.apiBase;if(!t)throw new h("NOT_INITIALIZED","window.__STORVIA__.apiBase is not set. The platform must inject it before SDK init.");if(this.baseUrl=`${t}${F}`,this.isPreview=!!e.preview,this.previewConfig=e.previewConfig,!e.gameId)throw new h("GAME_NOT_FOUND","window.__STORVIA__.gameId is not set. The platform must inject it before SDK init.");if(this.gameId=e.gameId,!e.accessToken)throw new h("UNAUTHORIZED","window.__STORVIA__.accessToken is not set. The platform must inject the user token before SDK init.");if(this.accessToken=e.accessToken,this.http=new R(this.baseUrl,this.accessToken,!!e.debug),this.isPreview){this.conversationId="00000000-0000-0000-0000-000000000000";let[d,c]=await Promise.all([this.fetchModels(),this.fetchPreviewSnapshot()]);this.modelId=e.selectedModelId||d[0]?.id||"",this.settingsSheet=new y({onModelChange:M=>{this.modelId=M},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),d.length>0&&this.settingsSheet.mount(d,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let f=()=>this.gameId,g=()=>this.conversationId,v=()=>this.modelId;this.chat=new w(this.http,f,g,v,!0,this.previewConfig),this.characters=new C(this.http,g,!0,c?.characters,c?.characterStates),this.relationships=new x(this.http,g,!0,c?.relationships),this.inventory=new I(this.http,g,!0,c?.inventory),this.world=new P(this.http,g,!0,c?.world),this.player=new S(this.http,g,!0,c?.player,c?.playerState),this.custom=new E(this.http,g,!0,c?.custom),this.initialized=!0,this.listenForPreviewMessages();return}let[n,i]=await Promise.all([this.authenticate(),this.fetchModels()]);this.conversationId=n.conversationId;let s=this.getSavedModelId();this.modelId=s&&i.some(d=>d.id===s)?s:i[0]?.id||"";let r=n.settings||{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.settingsSheet=new y({onModelChange:d=>{this.modelId=d},onSettingsChange:d=>this.saveSettings(d),onSync:()=>this.syncSettings()}),this.settingsSheet.mount(i,this.modelId,r,n.hasWorldUpdate??!1);let a=()=>this.gameId,l=()=>this.conversationId,p=()=>this.modelId;this.chat=new w(this.http,a,l,p),this.characters=new C(this.http,l),this.relationships=new x(this.http,l),this.inventory=new I(this.http,l),this.world=new P(this.http,l),this.player=new S(this.http,l),this.custom=new E(this.http,l),this.initialized=!0}listenForPreviewMessages(){window.addEventListener("message",e=>{!e.data||e.data.type!=="storvia-preview"||(e.data.action==="set-model"&&(this.modelId=e.data.modelId||""),e.data.action==="update-config"&&(this.previewConfig=e.data.previewConfig,this.chat&&this.chat.updatePreviewConfig(this.previewConfig),this.refreshPreviewSnapshot().catch(t=>{console.warn("[Storvia SDK] refreshPreviewSnapshot failed:",t)})))})}async fetchPreviewSnapshot(){try{let e={game_id:this.gameId};return this.previewConfig&&("game_config"in this.previewConfig&&(e.game_config=this.previewConfig.game_config),"game_state"in this.previewConfig&&(e.game_state_override=this.previewConfig.game_state)),await this.http.post("/preview/initial-snapshot",e)}catch(e){return console.warn("[Storvia SDK] fetchPreviewSnapshot failed:",e),null}}async refreshPreviewSnapshot(){let e=await this.fetchPreviewSnapshot();e&&(this.characters?.setInitial(e.characters,e.characterStates),this.player?.setInitial(e.player,e.playerState),this.inventory?.setInitial(e.inventory),this.relationships?.setInitial(e.relationships),this.world?.setInitial(e.world),this.custom?.setInitial(e.custom))}async saveSettings(e){await this.http.patch("/settings",{conversation_id:this.conversationId,...e})}async syncSettings(){await this.http.post("/sync",{conversation_id:this.conversationId})}async fetchModels(){try{return await this.http.get("/models")}catch{}return[]}async authenticate(){let e=await fetch(`${this.baseUrl}/auth`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.accessToken}`},body:JSON.stringify({game_id:this.gameId})});if(!e.ok)throw e.status===401?new h("UNAUTHORIZED","User not authenticated"):e.status===404?new h("GAME_NOT_FOUND","Game not found or not published"):new h("INTERNAL_ERROR",`Auth failed: HTTP ${e.status}`);let t=await e.json();return t.data??t}getSavedModelId(){try{return localStorage.getItem("storvia_model_id")||""}catch{return""}}async initDev(e){if(this.initialized)return;this.baseUrl=`${re}${F}`,this.gameId=e.gameId,this.isPreview=!0,this.http=new R(this.baseUrl,"",!1,e.apiKey);let[t,n]=await Promise.all([this.fetchModels(),this.fetchPreviewSnapshot()]);this.modelId=t[0]?.id||"",this.conversationId="00000000-0000-0000-0000-000000000000",this.settingsSheet=new y({onModelChange:a=>{this.modelId=a},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),t.length>0&&this.settingsSheet.mount(t,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let i=()=>this.gameId,s=()=>this.conversationId,r=()=>this.modelId;this.chat=new w(this.http,i,s,r,!0,void 0),this.characters=new C(this.http,s,!0,n?.characters,n?.characterStates),this.relationships=new x(this.http,s,!0,n?.relationships),this.inventory=new I(this.http,s,!0,n?.inventory),this.world=new P(this.http,s,!0,n?.world),this.player=new S(this.http,s,!0,n?.player,n?.playerState),this.custom=new E(this.http,s,!0,n?.custom),this.initialized=!0}};async function G(o){let e=new T;return o?.dev?await e.initDev(o.dev):await e.init(),e}function L(o){return typeof o=="object"&&o!==null&&"value"in o&&"type"in o&&(o.type==="number"||o.type==="text")}function j(o){return L(o)?o.value:o}0&&(module.exports={StorviaError,StorviaSDK,createStorviaSDK,extractFieldValue,isRichFieldValue});
package/dist/index.d.mts CHANGED
@@ -182,8 +182,11 @@ declare class CharacterStateModule {
182
182
  private http;
183
183
  private getConversationId;
184
184
  private isPreview;
185
+ /** characterName → state(与正式模式 GET /characters/:name/state 同结构) */
185
186
  private mem;
186
- constructor(http: HttpClient, getConversationId: () => string, isPreview?: boolean);
187
+ constructor(http: HttpClient, getConversationId: () => string, isPreview?: boolean, initialStates?: Record<string, Record<string, FieldValue>>);
188
+ /** 预览模式下重新灌入初始数据(previewConfig 变更时调用) */
189
+ setInitial(initialStates: Record<string, Record<string, FieldValue>> | undefined): void;
187
190
  get(characterName: string): Promise<Record<string, FieldValue>>;
188
191
  update(characterName: string, values: Record<string, string | number | boolean>): Promise<void>;
189
192
  }
@@ -193,7 +196,9 @@ declare class CharactersModule {
193
196
  private isPreview;
194
197
  state: CharacterStateModule;
195
198
  private mem;
196
- constructor(http: HttpClient, getConversationId: () => string, isPreview?: boolean);
199
+ constructor(http: HttpClient, getConversationId: () => string, isPreview?: boolean, initialCharacters?: CharacterPersona[], initialStates?: Record<string, Record<string, FieldValue>>);
200
+ /** 预览模式下重新灌入初始数据(previewConfig 变更时调用) */
201
+ setInitial(initialCharacters: CharacterPersona[] | undefined, initialStates: Record<string, Record<string, FieldValue>> | undefined): void;
197
202
  list(): Promise<CharacterPersona[]>;
198
203
  get(name: string): Promise<CharacterPersona>;
199
204
  add(character: CharacterAddOptions): Promise<void>;
@@ -215,7 +220,9 @@ declare class RelationshipsModule {
215
220
  private getConversationId;
216
221
  private isPreview;
217
222
  private mem;
218
- constructor(http: HttpClient, getConversationId: () => string, isPreview?: boolean);
223
+ constructor(http: HttpClient, getConversationId: () => string, isPreview?: boolean, initialRelationships?: Relationship[]);
224
+ /** 预览模式下重新灌入初始数据(previewConfig 变更时调用) */
225
+ setInitial(initialRelationships: Relationship[] | undefined): void;
219
226
  list(): Promise<Relationship[]>;
220
227
  get(from: string, to: string): Promise<Relationship>;
221
228
  add(relationship: Relationship): Promise<void>;
@@ -233,7 +240,9 @@ declare class InventoryModule {
233
240
  private getConversationId;
234
241
  private isPreview;
235
242
  private mem;
236
- constructor(http: HttpClient, getConversationId: () => string, isPreview?: boolean);
243
+ constructor(http: HttpClient, getConversationId: () => string, isPreview?: boolean, initialInventory?: InventoryState);
244
+ /** 预览模式下重新灌入初始数据(previewConfig 变更时调用) */
245
+ setInitial(initialInventory: InventoryState | undefined): void;
237
246
  /** 返回整个物品栏(分组 → 物品名 → 数据) */
238
247
  list(): Promise<InventoryState>;
239
248
  /** 返回指定分组下的物品(物品名 → 数据) */
@@ -257,7 +266,9 @@ declare class WorldModule {
257
266
  private getConversationId;
258
267
  private isPreview;
259
268
  private mem;
260
- constructor(http: HttpClient, getConversationId: () => string, isPreview?: boolean);
269
+ constructor(http: HttpClient, getConversationId: () => string, isPreview?: boolean, initialWorld?: Record<string, unknown>);
270
+ /** 预览模式下重新灌入初始数据(previewConfig 变更时调用) */
271
+ setInitial(initialWorld: Record<string, unknown> | undefined): void;
261
272
  get(): Promise<Record<string, unknown>>;
262
273
  update(data: Record<string, unknown>): Promise<void>;
263
274
  }
@@ -267,7 +278,9 @@ declare class PlayerStateModule {
267
278
  private getConversationId;
268
279
  private isPreview;
269
280
  private mem;
270
- constructor(http: HttpClient, getConversationId: () => string, isPreview?: boolean);
281
+ constructor(http: HttpClient, getConversationId: () => string, isPreview?: boolean, initialState?: Record<string, Record<string, FieldValue>>);
282
+ /** 预览模式下重新灌入初始数据(previewConfig 变更时调用) */
283
+ setInitial(initialState: Record<string, Record<string, FieldValue>> | undefined): void;
271
284
  get(): Promise<Record<string, Record<string, FieldValue>>>;
272
285
  get(group: string): Promise<Record<string, FieldValue>>;
273
286
  update(group: string, values: Record<string, string | number | boolean>): Promise<void>;
@@ -278,7 +291,9 @@ declare class PlayerModule {
278
291
  private isPreview;
279
292
  state: PlayerStateModule;
280
293
  private memPersona;
281
- constructor(http: HttpClient, getConversationId: () => string, isPreview?: boolean);
294
+ constructor(http: HttpClient, getConversationId: () => string, isPreview?: boolean, initialPersona?: PlayerPersona, initialState?: Record<string, Record<string, FieldValue>>);
295
+ /** 预览模式下重新灌入初始数据(previewConfig 变更时调用) */
296
+ setInitial(initialPersona: PlayerPersona | undefined, initialState: Record<string, Record<string, FieldValue>> | undefined): void;
282
297
  get(): Promise<PlayerPersona>;
283
298
  update(data: Partial<PlayerPersona>): Promise<void>;
284
299
  }
@@ -288,7 +303,9 @@ declare class CustomModule {
288
303
  private getConversationId;
289
304
  private isPreview;
290
305
  private mem;
291
- constructor(http: HttpClient, getConversationId: () => string, isPreview?: boolean);
306
+ constructor(http: HttpClient, getConversationId: () => string, isPreview?: boolean, initialCustom?: Record<string, unknown>);
307
+ /** 预览模式下重新灌入初始数据(previewConfig 变更时调用) */
308
+ setInitial(initialCustom: Record<string, unknown> | undefined): void;
292
309
  get(): Promise<Record<string, unknown>>;
293
310
  get(key: string): Promise<unknown>;
294
311
  set(data: Record<string, unknown>): Promise<void>;
@@ -322,6 +339,15 @@ declare class StorviaSDK {
322
339
  init(): Promise<void>;
323
340
  /** 监听父页面 postMessage(预览模式) */
324
341
  private listenForPreviewMessages;
342
+ /**
343
+ * 调用 POST /preview/initial-snapshot 拉取与正式发布等价的初始数据
344
+ * - 预览模式:传 game_config + game_state_override(来自 previewConfig)
345
+ * - dev 模式:HttpClient 自动带 x-api-key,后端按 game_id 反查
346
+ * 失败时返回 null(不阻塞 init,list/get 仍能用空 mem 工作)
347
+ */
348
+ private fetchPreviewSnapshot;
349
+ /** 重新拉 snapshot 并把结果灌进每个 module 的 mem(用于 update-config 后同步) */
350
+ private refreshPreviewSnapshot;
325
351
  /** 保存设置到后端 */
326
352
  private saveSettings;
327
353
  /** 同步最新游戏设定到当前存档 */
package/dist/index.esm.js CHANGED
@@ -1,5 +1,5 @@
1
- var h=class extends Error{constructor(e,t){super(t),this.name="StorviaError",this.code=e}};var P=class{constructor(e,t,n=!1,i=""){this.baseUrl=e,this.token=t,this.debug=n,this.devApiKey=i}setToken(e){this.token=e}setDebug(e){this.debug=e}buildHeaders(){let e={"Content-Type":"application/json"};return this.token&&(e.Authorization=`Bearer ${this.token}`),this.devApiKey&&(e["x-api-key"]=this.devApiKey),e}log(e,t,n,i,s){if(!this.debug)return;let r="%c[Storvia SDK]",o="color: #6366f1; font-weight: bold";s?(console.groupCollapsed(`${r} %c${e} ${t} %c\u2717`,o,"color: #e0e0e0","color: #ef4444"),n&&console.log("Request:",n),console.error("Error:",s),console.groupEnd()):(console.groupCollapsed(`${r} %c${e} ${t} %c\u2713`,o,"color: #e0e0e0","color: #22c55e"),n&&console.log("Request:",n),i!==void 0&&console.log("Response:",i),console.groupEnd())}async get(e,t){let n=new URL(`${this.baseUrl}${e}`);t&&Object.entries(t).forEach(([i,s])=>n.searchParams.set(i,s));try{let i=await fetch(n.toString(),{method:"GET",headers:this.buildHeaders()}),s=await this.handleResponse(i);return this.log("GET",e,t,s),s}catch(i){throw this.log("GET",e,t,void 0,i),i}}async post(e,t){try{let n=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0}),i=await this.handleResponse(n);return this.log("POST",e,t,i),i}catch(n){throw this.log("POST",e,t,void 0,n),n}}async patch(e,t){try{let n=await fetch(`${this.baseUrl}${e}`,{method:"PATCH",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0}),i=await this.handleResponse(n);return this.log("PATCH",e,t,i),i}catch(n){throw this.log("PATCH",e,t,void 0,n),n}}async delete(e){try{let t=await fetch(`${this.baseUrl}${e}`,{method:"DELETE",headers:this.buildHeaders()}),n=await this.handleResponse(t);return this.log("DELETE",e,void 0,n),n}catch(t){throw this.log("DELETE",e,void 0,void 0,t),t}}async stream(e,t,n,i){this.log("STREAM",e,t);let s=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify(t)});if(!s.ok){let d=await s.json().catch(()=>({})),p=new h(d.code||"INTERNAL_ERROR",d.message||`HTTP ${s.status}`);throw this.log("STREAM",e,t,void 0,p),p}let r=s.body?.getReader();if(!r)throw new h("INTERNAL_ERROR","No response body for stream");let o=new TextDecoder,a="",c="";for(;;){let{done:d,value:p}=await r.read();if(d)break;let v=o.decode(p,{stream:!0}).split(`
2
- `);for(let f of v){if(!f.startsWith("data: "))continue;let O=f.slice(6);if(O==="[DONE]"){this.debug&&this.log("STREAM",e+" [done]",void 0,{id:a,contentLength:c.length}),i(a);return}try{let b=JSON.parse(O);b.type==="done"&&b.id?a=b.id:b.content&&(c+=b.content,n(b.content))}catch{}}}a&&i(a)}async handleResponse(e){if(!e.ok){let n={};try{n=await e.json()}catch{}let i={401:"UNAUTHORIZED",402:"INSUFFICIENT_BALANCE",404:"GAME_NOT_FOUND",429:"RATE_LIMITED"},s=n.code||i[e.status]||"INTERNAL_ERROR";throw new h(s,n.message||`HTTP ${e.status}`)}let t=await e.json();return t&&typeof t=="object"&&"data"in t?t.data:t}};var R=[{value:"zh-CN",label:"\u7B80\u4F53\u4E2D\u6587"},{value:"zh-TW",label:"\u7E41\u9AD4\u4E2D\u6587"},{value:"en",label:"English"},{value:"ja",label:"\u65E5\u672C\u8A9E"},{value:"ko",label:"\uD55C\uAD6D\uC5B4"}],$=[{value:"low",label:"\u7B80\u77ED"},{value:"medium",label:"\u9002\u4E2D"},{value:"high",label:"\u8BE6\u7EC6"}],B="https://cdn.storvia.ai/default/logo.png",H="https://api.storvia.ai/storage/v1/object/public/storvia/default/credits.png",U=`
1
+ var g=class extends Error{constructor(e,t){super(t),this.name="StorviaError",this.code=e}};var R=class{constructor(e,t,n=!1,i=""){this.baseUrl=e,this.token=t,this.debug=n,this.devApiKey=i}setToken(e){this.token=e}setDebug(e){this.debug=e}buildHeaders(){let e={"Content-Type":"application/json"};return this.token&&(e.Authorization=`Bearer ${this.token}`),this.devApiKey&&(e["x-api-key"]=this.devApiKey),e}log(e,t,n,i,s){if(!this.debug)return;let r="%c[Storvia SDK]",a="color: #6366f1; font-weight: bold";s?(console.groupCollapsed(`${r} %c${e} ${t} %c\u2717`,a,"color: #e0e0e0","color: #ef4444"),n&&console.log("Request:",n),console.error("Error:",s),console.groupEnd()):(console.groupCollapsed(`${r} %c${e} ${t} %c\u2713`,a,"color: #e0e0e0","color: #22c55e"),n&&console.log("Request:",n),i!==void 0&&console.log("Response:",i),console.groupEnd())}async get(e,t){let n=new URL(`${this.baseUrl}${e}`);t&&Object.entries(t).forEach(([i,s])=>n.searchParams.set(i,s));try{let i=await fetch(n.toString(),{method:"GET",headers:this.buildHeaders()}),s=await this.handleResponse(i);return this.log("GET",e,t,s),s}catch(i){throw this.log("GET",e,t,void 0,i),i}}async post(e,t){try{let n=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0}),i=await this.handleResponse(n);return this.log("POST",e,t,i),i}catch(n){throw this.log("POST",e,t,void 0,n),n}}async patch(e,t){try{let n=await fetch(`${this.baseUrl}${e}`,{method:"PATCH",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0}),i=await this.handleResponse(n);return this.log("PATCH",e,t,i),i}catch(n){throw this.log("PATCH",e,t,void 0,n),n}}async delete(e){try{let t=await fetch(`${this.baseUrl}${e}`,{method:"DELETE",headers:this.buildHeaders()}),n=await this.handleResponse(t);return this.log("DELETE",e,void 0,n),n}catch(t){throw this.log("DELETE",e,void 0,void 0,t),t}}async stream(e,t,n,i){this.log("STREAM",e,t);let s=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify(t)});if(!s.ok){let d=await s.json().catch(()=>({})),c=new g(d.code||"INTERNAL_ERROR",d.message||`HTTP ${s.status}`);throw this.log("STREAM",e,t,void 0,c),c}let r=s.body?.getReader();if(!r)throw new g("INTERNAL_ERROR","No response body for stream");let a=new TextDecoder,l="",p="";for(;;){let{done:d,value:c}=await r.read();if(d)break;let h=a.decode(c,{stream:!0}).split(`
2
+ `);for(let v of h){if(!v.startsWith("data: "))continue;let T=v.slice(6);if(T==="[DONE]"){this.debug&&this.log("STREAM",e+" [done]",void 0,{id:l,contentLength:p.length}),i(l);return}try{let b=JSON.parse(T);b.type==="done"&&b.id?l=b.id:b.content&&(p+=b.content,n(b.content))}catch{}}}l&&i(l)}async handleResponse(e){if(!e.ok){let n={};try{n=await e.json()}catch{}let i={401:"UNAUTHORIZED",402:"INSUFFICIENT_BALANCE",404:"GAME_NOT_FOUND",429:"RATE_LIMITED"},s=n.code||i[e.status]||"INTERNAL_ERROR";throw new g(s,n.message||`HTTP ${e.status}`)}let t=await e.json();return t&&typeof t=="object"&&"data"in t?t.data:t}};var k=[{value:"zh-CN",label:"\u7B80\u4F53\u4E2D\u6587"},{value:"zh-TW",label:"\u7E41\u9AD4\u4E2D\u6587"},{value:"en",label:"English"},{value:"ja",label:"\u65E5\u672C\u8A9E"},{value:"ko",label:"\uD55C\uAD6D\uC5B4"}],$=[{value:"low",label:"\u7B80\u77ED"},{value:"medium",label:"\u9002\u4E2D"},{value:"high",label:"\u8BE6\u7EC6"}],F="https://cdn.storvia.ai/default/logo.png",G="https://api.storvia.ai/storage/v1/object/public/storvia/default/credits.png",j=`
3
3
  :host {
4
4
  position: fixed;
5
5
  z-index: 2147483647;
@@ -673,7 +673,7 @@ var h=class extends Error{constructor(e,t){super(t),this.name="StorviaError",thi
673
673
  padding-bottom: calc(16px + env(safe-area-inset-bottom, 0px));
674
674
  }
675
675
  }
676
- `,A='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 6L6 18M6 6l12 12"/></svg>',F='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2v6h-6M3 12a9 9 0 0 1 15-6.7L21 8M3 22v-6h6M21 12a9 9 0 0 1-15 6.7L3 16"/></svg>',G='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="spin"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',z='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',j='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>',L='<svg class="check" viewBox="0 0 24 24" fill="none" stroke="#8246FF" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',m=48,u=16,V=5,y=class{constructor(e){this.selectedModelId="";this.models=[];this.settings={temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.activeTab="model";this.selectedCategory=null;this.hasWorldUpdate=!1;this.fabDot=null;this.syncHint=null;this.fabX=0;this.fabY=0;this.fab=null;this.panel=null;this.modelTabBtn=null;this.settingsTabBtn=null;this.modelBody=null;this.settingsBody=null;this.footer=null;this.modelGrid=null;this.modelDetail=null;this.tempValueEl=null;this.segmentBtns=[];this.langDropdown=null;this.langOptions=[];this.langArrow=null;this.langDropdownOpen=!1;this.noteCounter=null;this.saveBtn=null;this.syncBtn=null;this.syncState="idle";this.dragStartX=0;this.dragStartY=0;this.dragOffsetX=0;this.dragOffsetY=0;this.dragMoved=!1;this.dragging=!1;this.handlePointerDown=e=>{this.fab&&(e.preventDefault(),this.dragStartX=e.clientX,this.dragStartY=e.clientY,this.dragOffsetX=e.clientX-this.fabX,this.dragOffsetY=e.clientY-this.fabY,this.dragMoved=!1,this.dragging=!0,this.fab.setPointerCapture(e.pointerId),this.fab.addEventListener("pointermove",this.handlePointerMove),this.fab.addEventListener("pointerup",this.handlePointerUp),this.fab.addEventListener("pointercancel",this.handlePointerUp))};this.handlePointerMove=e=>{if(!this.dragging)return;let t=e.clientX-this.dragStartX,n=e.clientY-this.dragStartY;!this.dragMoved&&Math.hypot(t,n)>V&&(this.dragMoved=!0,this.fab?.classList.add("dragging"),this.closePanel()),this.dragMoved&&(this.fabX=e.clientX-this.dragOffsetX,this.fabY=e.clientY-this.dragOffsetY,this.applyHostPosition())};this.handlePointerUp=e=>{if(!this.fab)return;this.fab.removeEventListener("pointermove",this.handlePointerMove),this.fab.removeEventListener("pointerup",this.handlePointerUp),this.fab.removeEventListener("pointercancel",this.handlePointerUp);try{this.fab.releasePointerCapture(e.pointerId)}catch{}if(this.dragging=!1,!this.dragMoved){this.togglePanel();return}this.fab.classList.remove("dragging");let n=this.fabX+m/2<window.innerWidth/2;this.fabX=n?u:window.innerWidth-m-u,this.fabY=Math.max(u,Math.min(window.innerHeight-m-u,this.fabY)),this.fab&&(this.fab.style.transition="left 0.25s cubic-bezier(0.32, 0.72, 0, 1), top 0.25s cubic-bezier(0.32, 0.72, 0, 1), transform 0.2s, box-shadow 0.2s"),this.applyHostPosition(),setTimeout(()=>{this.fab&&(this.fab.style.transition="")},260)};this.handleResize=()=>{this.fabX=Math.max(u,Math.min(window.innerWidth-m-u,this.fabX)),this.fabY=Math.max(u,Math.min(window.innerHeight-m-u,this.fabY)),this.applyHostPosition()};this.handleDocClick=e=>{this.host.contains(e.target)||(this.closePanel(),this.closeLangDropdown())};this.savedBodyOverflow=null;this.callbacks=e,this.host=document.createElement("div"),this.host.id="storvia-settings",this.shadowRoot=this.host.attachShadow({mode:"closed"})}mount(e,t,n,i=!1){this.models=e,this.selectedModelId=t,this.settings={...n},this.hasWorldUpdate=i,this.fabX=window.innerWidth-m-u,this.fabY=window.innerHeight-m-u,document.body.appendChild(this.host),this.render(),this.applyHostPosition(),window.addEventListener("resize",this.handleResize),document.addEventListener("click",this.handleDocClick)}unmount(){window.removeEventListener("resize",this.handleResize),document.removeEventListener("click",this.handleDocClick),this.host.remove()}getSelectedModelId(){return this.selectedModelId}getSettings(){return{...this.settings}}render(){let e=document.createElement("style");e.textContent=U;let t=document.createElement("div");t.className="fab-wrap";let n=document.createElement("div");n.className="fab",n.title="\u6E38\u620F\u8BBE\u7F6E";let i=document.createElement("img");i.src=B,i.alt="Storvia",n.appendChild(i),this.fab=n;let s=document.createElement("div");s.className=`fab-dot${this.hasWorldUpdate?" visible":""}`,this.fabDot=s,t.appendChild(n),t.appendChild(s);let r=document.createElement("div");r.className="panel",this.panel=r;let o=document.createElement("div");o.className="panel-header";let a=document.createElement("h2");a.className="panel-title",a.textContent="\u6E38\u620F\u8BBE\u7F6E";let c=document.createElement("button");c.className="close-btn",c.innerHTML=A,c.addEventListener("click",()=>this.closePanel()),o.appendChild(a),o.appendChild(c),r.appendChild(o);let d=document.createElement("div");d.className="tabs",this.modelTabBtn=this.createTabBtn("model","\u6A21\u578B\u9009\u62E9"),this.settingsTabBtn=this.createTabBtn("settings","\u6E38\u620F\u8BBE\u7F6E"),this.models.length===0&&(this.activeTab="settings",this.modelTabBtn.style.display="none"),d.appendChild(this.modelTabBtn),d.appendChild(this.settingsTabBtn),r.appendChild(d);let p=document.createElement("div");p.className="panel-body",this.modelBody=this.buildModelTab(),this.settingsBody=this.buildSettingsTab(),p.appendChild(this.modelBody),p.appendChild(this.settingsBody),r.appendChild(p);let g=document.createElement("div");g.className="panel-footer";let v=document.createElement("button");v.className="btn btn-save",v.textContent="\u4FDD\u5B58",this.saveBtn=v,v.addEventListener("click",()=>this.handleSave()),g.appendChild(v),this.footer=g,r.appendChild(g),n.addEventListener("pointerdown",this.handlePointerDown);let f=document.createElement("div");f.appendChild(r),f.appendChild(t),this.shadowRoot.appendChild(e),this.shadowRoot.appendChild(f),this.applyTab()}createTabBtn(e,t){let n=document.createElement("button");return n.className=`tab-btn${this.activeTab===e?" active":""}`,n.textContent=t,n.addEventListener("click",()=>{this.activeTab=e,this.applyTab()}),n}applyTab(){this.modelTabBtn&&this.modelTabBtn.classList.toggle("active",this.activeTab==="model"),this.settingsTabBtn&&this.settingsTabBtn.classList.toggle("active",this.activeTab==="settings"),this.modelBody&&(this.modelBody.style.display=this.activeTab==="model"?"block":"none"),this.settingsBody&&(this.settingsBody.style.display=this.activeTab==="settings"?"block":"none"),this.footer&&(this.footer.style.display=this.activeTab==="settings"?"flex":"none")}buildModelTab(){let e=document.createElement("div"),t=this.getCategories();if(t.length>0){let s=document.createElement("div");s.className="category-tabs";let r=(o,a)=>{let c=document.createElement("button");return c.className=`category-tab${this.selectedCategory===a?" active":""}`,c.textContent=o,c.addEventListener("click",()=>{this.selectedCategory=a,s.querySelectorAll(".category-tab").forEach(d=>d.classList.remove("active")),c.classList.add("active"),this.renderModelGrid()}),c};s.appendChild(r("\u5168\u90E8",null)),t.forEach(o=>s.appendChild(r(o,o))),e.appendChild(s)}let n=document.createElement("div");n.className="models-grid",this.modelGrid=n,e.appendChild(n);let i=document.createElement("div");return i.className="model-detail",i.style.display="none",this.modelDetail=i,e.appendChild(i),this.renderModelGrid(),this.renderModelDetail(),e}getCategories(){let e=new Set;return this.models.forEach(t=>{t.category&&e.add(t.category)}),Array.from(e)}getFilteredModels(){return this.selectedCategory?this.models.filter(e=>e.category===this.selectedCategory):this.models}renderModelGrid(){this.modelGrid&&(this.modelGrid.innerHTML="",this.getFilteredModels().forEach(e=>{let t=document.createElement("button"),n=e.is_active!==!1;t.className=`model-card${e.id===this.selectedModelId?" selected":""}${n?"":" disabled"}`;let i=this.getStatusDotColor(e);t.innerHTML=`<span class="status-dot" style="background:${i}"></span><span class="model-name">${this.escapeHtml(e.name)}</span>`,t.addEventListener("click",()=>this.handleSelectModel(e)),this.modelGrid.appendChild(t)}))}handleSelectModel(e){if(this.selectedModelId=e.id,e.is_active!==!1){this.callbacks.onModelChange(e.id);try{localStorage.setItem("storvia_model_id",e.id)}catch{}}let t=this.getFilteredModels();this.modelGrid&&this.modelGrid.querySelectorAll(".model-card").forEach((n,i)=>{n.classList.toggle("selected",t[i].id===this.selectedModelId)}),this.renderModelDetail()}renderModelDetail(){if(!this.modelDetail)return;let e=this.models.find(r=>r.id===this.selectedModelId);if(!e){this.modelDetail.style.display="none";return}this.modelDetail.style.display="block";let t=this.getStatusClass(e),n=this.getStatusText(e),i=this.getCreditsRange(e),s=e.description||"";this.modelDetail.innerHTML=`
676
+ `,z='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 6L6 18M6 6l12 12"/></svg>',V='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2v6h-6M3 12a9 9 0 0 1 15-6.7L21 8M3 22v-6h6M21 12a9 9 0 0 1-15 6.7L3 16"/></svg>',Y='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="spin"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',X='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',W='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>',L='<svg class="check" viewBox="0 0 24 24" fill="none" stroke="#8246FF" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',m=48,u=16,K=5,y=class{constructor(e){this.selectedModelId="";this.models=[];this.settings={temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.activeTab="model";this.selectedCategory=null;this.hasWorldUpdate=!1;this.fabDot=null;this.syncHint=null;this.fabX=0;this.fabY=0;this.fab=null;this.panel=null;this.modelTabBtn=null;this.settingsTabBtn=null;this.modelBody=null;this.settingsBody=null;this.footer=null;this.modelGrid=null;this.modelDetail=null;this.tempValueEl=null;this.segmentBtns=[];this.langDropdown=null;this.langOptions=[];this.langArrow=null;this.langDropdownOpen=!1;this.noteCounter=null;this.saveBtn=null;this.syncBtn=null;this.syncState="idle";this.dragStartX=0;this.dragStartY=0;this.dragOffsetX=0;this.dragOffsetY=0;this.dragMoved=!1;this.dragging=!1;this.handlePointerDown=e=>{this.fab&&(e.preventDefault(),this.dragStartX=e.clientX,this.dragStartY=e.clientY,this.dragOffsetX=e.clientX-this.fabX,this.dragOffsetY=e.clientY-this.fabY,this.dragMoved=!1,this.dragging=!0,this.fab.setPointerCapture(e.pointerId),this.fab.addEventListener("pointermove",this.handlePointerMove),this.fab.addEventListener("pointerup",this.handlePointerUp),this.fab.addEventListener("pointercancel",this.handlePointerUp))};this.handlePointerMove=e=>{if(!this.dragging)return;let t=e.clientX-this.dragStartX,n=e.clientY-this.dragStartY;!this.dragMoved&&Math.hypot(t,n)>K&&(this.dragMoved=!0,this.fab?.classList.add("dragging"),this.closePanel()),this.dragMoved&&(this.fabX=e.clientX-this.dragOffsetX,this.fabY=e.clientY-this.dragOffsetY,this.applyHostPosition())};this.handlePointerUp=e=>{if(!this.fab)return;this.fab.removeEventListener("pointermove",this.handlePointerMove),this.fab.removeEventListener("pointerup",this.handlePointerUp),this.fab.removeEventListener("pointercancel",this.handlePointerUp);try{this.fab.releasePointerCapture(e.pointerId)}catch{}if(this.dragging=!1,!this.dragMoved){this.togglePanel();return}this.fab.classList.remove("dragging");let n=this.fabX+m/2<window.innerWidth/2;this.fabX=n?u:window.innerWidth-m-u,this.fabY=Math.max(u,Math.min(window.innerHeight-m-u,this.fabY)),this.fab&&(this.fab.style.transition="left 0.25s cubic-bezier(0.32, 0.72, 0, 1), top 0.25s cubic-bezier(0.32, 0.72, 0, 1), transform 0.2s, box-shadow 0.2s"),this.applyHostPosition(),setTimeout(()=>{this.fab&&(this.fab.style.transition="")},260)};this.handleResize=()=>{this.fabX=Math.max(u,Math.min(window.innerWidth-m-u,this.fabX)),this.fabY=Math.max(u,Math.min(window.innerHeight-m-u,this.fabY)),this.applyHostPosition()};this.handleDocClick=e=>{this.host.contains(e.target)||(this.closePanel(),this.closeLangDropdown())};this.savedBodyOverflow=null;this.callbacks=e,this.host=document.createElement("div"),this.host.id="storvia-settings",this.shadowRoot=this.host.attachShadow({mode:"closed"})}mount(e,t,n,i=!1){this.models=e,this.selectedModelId=t,this.settings={...n},this.hasWorldUpdate=i,this.fabX=window.innerWidth-m-u,this.fabY=window.innerHeight-m-u,document.body.appendChild(this.host),this.render(),this.applyHostPosition(),window.addEventListener("resize",this.handleResize),document.addEventListener("click",this.handleDocClick)}unmount(){window.removeEventListener("resize",this.handleResize),document.removeEventListener("click",this.handleDocClick),this.host.remove()}getSelectedModelId(){return this.selectedModelId}getSettings(){return{...this.settings}}render(){let e=document.createElement("style");e.textContent=j;let t=document.createElement("div");t.className="fab-wrap";let n=document.createElement("div");n.className="fab",n.title="\u6E38\u620F\u8BBE\u7F6E";let i=document.createElement("img");i.src=F,i.alt="Storvia",n.appendChild(i),this.fab=n;let s=document.createElement("div");s.className=`fab-dot${this.hasWorldUpdate?" visible":""}`,this.fabDot=s,t.appendChild(n),t.appendChild(s);let r=document.createElement("div");r.className="panel",this.panel=r;let a=document.createElement("div");a.className="panel-header";let l=document.createElement("h2");l.className="panel-title",l.textContent="\u6E38\u620F\u8BBE\u7F6E";let p=document.createElement("button");p.className="close-btn",p.innerHTML=z,p.addEventListener("click",()=>this.closePanel()),a.appendChild(l),a.appendChild(p),r.appendChild(a);let d=document.createElement("div");d.className="tabs",this.modelTabBtn=this.createTabBtn("model","\u6A21\u578B\u9009\u62E9"),this.settingsTabBtn=this.createTabBtn("settings","\u6E38\u620F\u8BBE\u7F6E"),this.models.length===0&&(this.activeTab="settings",this.modelTabBtn.style.display="none"),d.appendChild(this.modelTabBtn),d.appendChild(this.settingsTabBtn),r.appendChild(d);let c=document.createElement("div");c.className="panel-body",this.modelBody=this.buildModelTab(),this.settingsBody=this.buildSettingsTab(),c.appendChild(this.modelBody),c.appendChild(this.settingsBody),r.appendChild(c);let f=document.createElement("div");f.className="panel-footer";let h=document.createElement("button");h.className="btn btn-save",h.textContent="\u4FDD\u5B58",this.saveBtn=h,h.addEventListener("click",()=>this.handleSave()),f.appendChild(h),this.footer=f,r.appendChild(f),n.addEventListener("pointerdown",this.handlePointerDown);let v=document.createElement("div");v.appendChild(r),v.appendChild(t),this.shadowRoot.appendChild(e),this.shadowRoot.appendChild(v),this.applyTab()}createTabBtn(e,t){let n=document.createElement("button");return n.className=`tab-btn${this.activeTab===e?" active":""}`,n.textContent=t,n.addEventListener("click",()=>{this.activeTab=e,this.applyTab()}),n}applyTab(){this.modelTabBtn&&this.modelTabBtn.classList.toggle("active",this.activeTab==="model"),this.settingsTabBtn&&this.settingsTabBtn.classList.toggle("active",this.activeTab==="settings"),this.modelBody&&(this.modelBody.style.display=this.activeTab==="model"?"block":"none"),this.settingsBody&&(this.settingsBody.style.display=this.activeTab==="settings"?"block":"none"),this.footer&&(this.footer.style.display=this.activeTab==="settings"?"flex":"none")}buildModelTab(){let e=document.createElement("div"),t=this.getCategories();if(t.length>0){let s=document.createElement("div");s.className="category-tabs";let r=(a,l)=>{let p=document.createElement("button");return p.className=`category-tab${this.selectedCategory===l?" active":""}`,p.textContent=a,p.addEventListener("click",()=>{this.selectedCategory=l,s.querySelectorAll(".category-tab").forEach(d=>d.classList.remove("active")),p.classList.add("active"),this.renderModelGrid()}),p};s.appendChild(r("\u5168\u90E8",null)),t.forEach(a=>s.appendChild(r(a,a))),e.appendChild(s)}let n=document.createElement("div");n.className="models-grid",this.modelGrid=n,e.appendChild(n);let i=document.createElement("div");return i.className="model-detail",i.style.display="none",this.modelDetail=i,e.appendChild(i),this.renderModelGrid(),this.renderModelDetail(),e}getCategories(){let e=new Set;return this.models.forEach(t=>{t.category&&e.add(t.category)}),Array.from(e)}getFilteredModels(){return this.selectedCategory?this.models.filter(e=>e.category===this.selectedCategory):this.models}renderModelGrid(){this.modelGrid&&(this.modelGrid.innerHTML="",this.getFilteredModels().forEach(e=>{let t=document.createElement("button"),n=e.is_active!==!1;t.className=`model-card${e.id===this.selectedModelId?" selected":""}${n?"":" disabled"}`;let i=this.getStatusDotColor(e);t.innerHTML=`<span class="status-dot" style="background:${i}"></span><span class="model-name">${this.escapeHtml(e.name)}</span>`,t.addEventListener("click",()=>this.handleSelectModel(e)),this.modelGrid.appendChild(t)}))}handleSelectModel(e){if(this.selectedModelId=e.id,e.is_active!==!1){this.callbacks.onModelChange(e.id);try{localStorage.setItem("storvia_model_id",e.id)}catch{}}let t=this.getFilteredModels();this.modelGrid&&this.modelGrid.querySelectorAll(".model-card").forEach((n,i)=>{n.classList.toggle("selected",t[i].id===this.selectedModelId)}),this.renderModelDetail()}renderModelDetail(){if(!this.modelDetail)return;let e=this.models.find(r=>r.id===this.selectedModelId);if(!e){this.modelDetail.style.display="none";return}this.modelDetail.style.display="block";let t=this.getStatusClass(e),n=this.getStatusText(e),i=this.getCreditsRange(e),s=e.description||"";this.modelDetail.innerHTML=`
677
677
  <div class="detail-header">
678
678
  <span class="detail-title">${this.escapeHtml(e.name)}</span>
679
679
  <span class="detail-status ${t}">${n}</span>
@@ -681,8 +681,8 @@ var h=class extends Error{constructor(e,t){super(t),this.name="StorviaError",thi
681
681
  ${i?`<div class="detail-credits">
682
682
  <span class="credits-label">\u6D88\u8017</span>
683
683
  <span class="credits-value">${i}</span>
684
- <img class="credits-icon" src="${H}" alt="credits" />
684
+ <img class="credits-icon" src="${G}" alt="credits" />
685
685
  <span class="credits-unit">/\u6B21</span>
686
686
  </div>`:""}
687
687
  ${s?`<div class="detail-description">${this.escapeHtml(s)}</div>`:""}
688
- `}getStatusDotColor(e){if(e.is_active===!1)return"#6b7280";let t=e.success_rate??100;return t>=95?"#10b981":t>=80?"#3b82f6":t>=60?"#eab308":"#f97316"}getStatusClass(e){if(e.is_active===!1)return"inactive";let t=e.success_rate??100;return t>=95?"excellent":t>=80?"good":t>=60?"normal":"crowded"}getStatusText(e){if(e.is_active===!1)return"\u505C\u7528";let t=e.success_rate??100;return t>=95?"\u6D41\u7545":t>=80?"\u826F\u597D":t>=60?"\u4E00\u822C":"\u62E5\u6324"}getCreditsRange(e){let t=e.credits_config?.min??0,n=e.credits_config?.max??0;return t===0&&n===0?"":t===n?`${t}`:`${t}\uFF5E${n}`}buildSettingsTab(){let e=document.createElement("div"),t=document.createElement("div");return t.className="form-stack",t.appendChild(this.buildTemperatureSection()),t.appendChild(this.buildReplyLengthSection()),t.appendChild(this.buildReplyLanguageSection()),t.appendChild(this.buildNoteSection()),t.appendChild(this.buildSyncSection()),e.appendChild(t),e}buildTemperatureSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label";let n=document.createElement("span");n.textContent="\u6E29\u5EA6";let i=document.createElement("span");i.className="temperature-value",i.textContent=this.settings.temperature.toFixed(1),this.tempValueEl=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("p");s.className="form-hint",s.textContent="\u66F4\u4F4E\u8BA9 AI \u56DE\u590D\u66F4\u7A33\u5B9A\u7406\u667A\uFF0C\u66F4\u9AD8\u8BA9\u56DE\u590D\u66F4\u5177\u591A\u6837\u6027",e.appendChild(s);let r=document.createElement("input");r.type="range",r.className="slider",r.min="0",r.max="1",r.step="0.1",r.value=String(this.settings.temperature),r.addEventListener("input",()=>{let a=parseFloat(r.value);this.settings.temperature=a,this.tempValueEl&&(this.tempValueEl.textContent=a.toFixed(1))}),e.appendChild(r);let o=document.createElement("div");return o.className="slider-labels",o.innerHTML="<span>\u7CBE\u786E</span><span>\u521B\u610F</span>",e.appendChild(o),e}buildReplyLengthSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label",t.textContent="\u56DE\u590D\u957F\u5EA6",e.appendChild(t);let n=document.createElement("div");return n.className="segment-control",this.segmentBtns=[],$.forEach(i=>{let s=document.createElement("button");s.className=`segment-button${i.value===this.settings.reply_length?" active":""}`,s.textContent=i.label,s.addEventListener("click",()=>{this.settings.reply_length=i.value,this.segmentBtns.forEach((r,o)=>{r.classList.toggle("active",$[o].value===i.value)})}),this.segmentBtns.push(s),n.appendChild(s)}),e.appendChild(n),e}buildReplyLanguageSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label",t.textContent="\u56DE\u590D\u8BED\u8A00",e.appendChild(t);let n=document.createElement("div");n.className="custom-select";let i=document.createElement("button");i.className="select-trigger";let s=document.createElement("span");s.textContent=R.find(a=>a.value===this.settings.reply_language)?.label||"";let r=document.createElement("span");r.className="select-arrow",r.textContent="\u25BE",this.langArrow=r,i.appendChild(s),i.appendChild(r),i.addEventListener("click",a=>{a.stopPropagation(),this.toggleLangDropdown()}),n.appendChild(i);let o=document.createElement("div");return o.className="select-dropdown",this.langDropdown=o,this.langOptions=[],R.forEach(a=>{let c=document.createElement("button");c.className=`select-option${a.value===this.settings.reply_language?" active":""}`,c.innerHTML=`<span>${a.label}</span>${a.value===this.settings.reply_language?L:""}`,c.addEventListener("click",()=>{this.settings.reply_language=a.value,s.textContent=a.label,this.langOptions.forEach((d,p)=>{d.classList.toggle("active",R[p].value===a.value),d.innerHTML=`<span>${R[p].label}</span>${R[p].value===a.value?L:""}`}),this.closeLangDropdown()}),this.langOptions.push(c),o.appendChild(c)}),n.appendChild(o),e.appendChild(n),e}toggleLangDropdown(){this.langDropdownOpen?this.closeLangDropdown():this.openLangDropdown()}openLangDropdown(){this.langDropdownOpen=!0,this.langDropdown?.classList.add("open"),this.langArrow&&(this.langArrow.textContent="\u25B4")}closeLangDropdown(){this.langDropdownOpen=!1,this.langDropdown?.classList.remove("open"),this.langArrow&&(this.langArrow.textContent="\u25BE")}buildNoteSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label";let n=document.createElement("span");n.textContent="\u5907\u6CE8";let i=document.createElement("span");i.className="char-count",i.textContent=`${this.settings.player_note.length}/50`,this.noteCounter=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("p");s.className="form-hint",s.textContent="\u5199\u4E0B\u4F60\u5BF9\u8FD9\u4E2A\u6E38\u620F\u7684\u5907\u6CE8\uFF0C\u4F1A\u663E\u793A\u5728\u5B58\u6863\u5217\u8868",e.appendChild(s);let r=document.createElement("textarea");return r.className="player-note-input",r.placeholder="\u5907\u6CE8",r.maxLength=50,r.rows=2,r.value=this.settings.player_note,r.addEventListener("input",()=>{this.settings.player_note=r.value,this.noteCounter&&(this.noteCounter.textContent=`${r.value.length}/50`)}),e.appendChild(r),e}buildSyncSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label",t.textContent="\u540C\u6B65\u6E38\u620F\u8BBE\u5B9A",e.appendChild(t);let n=document.createElement("p");n.className=`sync-hint${this.hasWorldUpdate?" visible":""}`,n.textContent="\u26A0 \u4F5C\u8005\u5DF2\u66F4\u65B0\u6E38\u620F\u5185\u5BB9\uFF0C\u5EFA\u8BAE\u70B9\u51FB\u540C\u6B65",this.syncHint=n,e.appendChild(n);let i=document.createElement("p");i.className="form-hint",i.textContent="\u5C06\u6700\u65B0\u6E38\u620F\u8BBE\u5B9A\u548C\u5F00\u5E55\u5C0F\u5267\u573A\u540C\u6B65\u5230\u5F53\u524D\u5BF9\u8BDD",e.appendChild(i);let s=document.createElement("button");return s.className="btn btn-sync",this.syncBtn=s,this.renderSyncBtn(),s.addEventListener("click",async()=>{if(this.syncState!=="loading"){this.setSyncState("loading");try{await this.callbacks.onSync(),this.setSyncState("success"),this.hasWorldUpdate=!1,this.fabDot&&this.fabDot.classList.remove("visible"),this.syncHint&&this.syncHint.classList.remove("visible"),setTimeout(()=>this.setSyncState("idle"),3e3)}catch{this.setSyncState("error"),setTimeout(()=>this.setSyncState("idle"),4e3)}}}),e.appendChild(s),e}setSyncState(e){this.syncState=e,this.renderSyncBtn()}renderSyncBtn(){if(!this.syncBtn)return;let e=this.syncState,t={idle:F,loading:G,success:z,error:j},n={idle:"\u540C\u6B65\u6700\u65B0\u8BBE\u5B9A",loading:"\u540C\u6B65\u4E2D...",success:"\u5DF2\u540C\u6B65",error:"\u540C\u6B65\u5931\u8D25"};this.syncBtn.className=`btn btn-sync${e==="success"||e==="error"?` ${e}`:""}`,this.syncBtn.disabled=e==="loading",this.syncBtn.innerHTML=`${t[e]}<span>${n[e]}</span>`}async handleSave(){if(!(!this.saveBtn||this.saveBtn.disabled)){this.saveBtn.disabled=!0,this.saveBtn.innerHTML='<span class="spinner"></span>\u4FDD\u5B58\u4E2D...';try{await this.callbacks.onSettingsChange({temperature:this.settings.temperature,reply_length:this.settings.reply_length,reply_language:this.settings.reply_language,player_note:this.settings.player_note}),this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1)}catch{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58\u5931\u8D25",setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1)},2e3))}}}escapeHtml(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}applyHostPosition(){this.host.style.left=`${this.fabX}px`,this.host.style.top=`${this.fabY}px`,this.host.style.right="auto",this.host.style.bottom="auto",this.applyPanelPosition()}isMobile(){return window.innerWidth<=768}applyPanelPosition(){if(!this.panel)return;if(this.isMobile()){this.panel.style.left="",this.panel.style.right="",this.panel.style.top="",this.panel.style.bottom="";return}let e=this.fabX+m/2<window.innerWidth/2,t=380;e?(this.panel.style.left="0",this.panel.style.right="auto"):(this.panel.style.left=`${m-t}px`,this.panel.style.right="auto"),this.fabY>500?(this.panel.style.bottom=`${m+8}px`,this.panel.style.top="auto"):(this.panel.style.top=`${m+8}px`,this.panel.style.bottom="auto")}togglePanel(){this.panel&&(this.panel.classList.contains("open")?this.closePanel():(this.applyPanelPosition(),this.panel.classList.add("open"),requestAnimationFrame(()=>{this.panel?.classList.contains("open")&&(this.fab&&(this.fab.style.visibility="hidden"),this.fabDot&&(this.fabDot.style.visibility="hidden"))}),this.isMobile()&&this.lockBodyScroll()))}closePanel(){this.panel&&this.panel.classList.remove("open"),this.fab&&(this.fab.style.visibility="visible"),this.fabDot&&(this.fabDot.style.visibility="visible"),this.unlockBodyScroll()}lockBodyScroll(){this.savedBodyOverflow===null&&(this.savedBodyOverflow=document.body.style.overflow||"",document.body.style.overflow="hidden")}unlockBodyScroll(){this.savedBodyOverflow!==null&&(document.body.style.overflow=this.savedBodyOverflow,this.savedBodyOverflow=null)}};var w=class{constructor(e,t,n,i,s=!1,r){this.http=e;this.getGameId=t;this.getConversationId=n;this.getModelId=i;this.isPreview=s;this.previewConfig=r}updatePreviewConfig(e){this.previewConfig=e}async send(e){if(this.isPreview)return this.sendPreview(e);let t={game_id:this.getGameId(),conversation_id:this.getConversationId(),model_id:this.getModelId(),message:e.message,topic:e.topic,scene_key:e.scene_key,stream:e.stream??!1};if(e.stream){await this.http.stream("/chat",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/chat",t)}async save(e){return this.isPreview?{id:`preview-${Date.now()}`}:this.http.post("/messages/save",{conversation_id:this.getConversationId(),role:e.role,content:e.content,topic:e.topic})}async generate(e){if(this.isPreview)return this.sendPreview({message:"",topic:e.topic,scene_key:e.scene_key,stream:e.stream,onChunk:e.onChunk,onDone:e.onDone});let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,scene_key:e.scene_key,stream:e.stream??!1,save:e.save??!0};if(e.stream){await this.http.stream("/generate",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/generate",t)}async retry(e={}){if(this.isPreview)throw new Error("Retry is not supported in preview mode");let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,scene_key:e.scene_key,stream:e.stream??!1};if(e.stream){await this.http.stream("/retry",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/retry",t)}async sendPreview(e){let t={model_id:this.getModelId(),message:e.message,topic:e.topic,scene_key:e.scene_key,history_messages:[]};if(this.previewConfig?t.prompt_config=this.previewConfig:t.game_id=this.getGameId(),e.stream){await this.http.stream("/preview",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}let n="";return await this.http.stream("/preview",t,i=>{n+=i},()=>{}),{id:"",content:n}}};var M=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){return this.isPreview?{...this.mem[e]||{}}:this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,t)}},C=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];this.state=new M(e,t,n)}async list(){return this.isPreview?this.mem.map(e=>({name:e.name,avatar:e.avatar,...e.gender?{gender:e.gender}:{}})):this.http.get(`/conversations/${this.getConversationId()}/characters`)}async get(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:t?.name||e,avatar:t?.avatar,...t?.gender?{gender:t.gender}:{}}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async add(e){if(this.isPreview){this.mem.push(e);return}await this.http.post(`/conversations/${this.getConversationId()}/characters`,e)}async update(e,t){if(this.isPreview){let n=this.mem.find(i=>i.name===e);n&&Object.assign(n,t);return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`,t)}async remove(e){if(this.isPreview){this.mem=this.mem.filter(t=>t.name!==e);return}await this.http.delete(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async detail(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:e,avatar:t?.avatar,state:await this.state.get(e)}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/detail`)}async setPriority(e,t){let n=Math.max(0,Math.min(100,Math.round(t)));this.isPreview||await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,{priority:n})}};var x=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[]}async list(){return this.isPreview?[...this.mem]:this.http.get(`/conversations/${this.getConversationId()}/relationships`)}async get(e,t){if(this.isPreview){let n=this.mem.find(i=>i.from===e&&i.to===t);if(n)return{...n};throw new Error("Relationship not found")}return this.http.get(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/relationships`,e)}async update(e,t,n){if(this.isPreview){let i=this.mem.find(s=>s.from===e&&s.to===t);i?Object.assign(i,n):this.mem.push({from:e,to:t,...n});return}await this.http.patch(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,n)}async remove(e,t){if(this.isPreview){this.mem=this.mem.filter(n=>!(n.from===e&&n.to===t));return}await this.http.delete(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var I=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async list(e){if(this.isPreview){if(e!==void 0)return{...this.mem[e]||{}};let t={};for(let[n,i]of Object.entries(this.mem))t[n]={...i};return t}return e!==void 0?this.http.get(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(e)}`):this.http.get(`/conversations/${this.getConversationId()}/inventory`)}async add(e){let{group:t,name:n,count:i=1,desc:s,iconUrl:r}=e;if(this.isPreview){if(!this.mem[t])throw new Error(`Group "${t}" does not exist`);if(n in this.mem[t])throw new Error(`Item "${n}" already exists in group "${t}"`);let o={count:i};s!==void 0&&(o.desc=s),r!==void 0&&(o.iconUrl=r),this.mem[t][n]=o;return}await this.http.post(`/conversations/${this.getConversationId()}/inventory`,{group:t,name:n,count:i,desc:s,iconUrl:r})}async update(e){let{group:t,name:n,...i}=e;if(this.isPreview){let s=this.mem[t];if(!s||!(n in s))throw new Error(`Item "${t}/${n}" not found`);Object.assign(s[n],i);return}await this.http.patch(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,i)}async remove(e){let{group:t,name:n}=e;if(this.isPreview){this.mem[t]&&delete this.mem[t][n];return}await this.http.delete(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(t)}/${encodeURIComponent(n)}`)}async move(e){let{fromGroup:t,toGroup:n,name:i,newName:s}=e;if(this.isPreview){let r=this.mem[t];if(!r||!(i in r))throw new Error(`Source item "${t}/${i}" not found`);if(!this.mem[n])throw new Error(`Target group "${n}" does not exist`);let o=s||i;if(t===n&&o===i)return;if(o in this.mem[n])throw new Error(`Item "${o}" already exists in target group`);this.mem[n][o]=r[i],delete r[i];return}await this.http.post(`/conversations/${this.getConversationId()}/inventory/move`,{fromGroup:t,toGroup:n,name:i,newName:s})}async ensureGroup(e){if(this.isPreview){this.mem[e]||(this.mem[e]={});return}await this.http.post(`/conversations/${this.getConversationId()}/inventory/groups/${encodeURIComponent(e)}`,{})}async removeGroup(e,t){let n=t?.cascade??!1;if(this.isPreview){let s=this.mem[e];if(s&&Object.keys(s).length>0&&!n)throw new Error(`Group "${e}" is not empty, pass cascade: true to force delete`);delete this.mem[e];return}let i=n?"?cascade=true":"";await this.http.delete(`/conversations/${this.getConversationId()}/inventory/groups/${encodeURIComponent(e)}${i}`)}};var E=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(){return this.isPreview?{...this.mem}:this.http.get(`/conversations/${this.getConversationId()}/world`)}async update(e){if(this.isPreview){Object.assign(this.mem,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/world`,e)}};var _=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e?{...this.mem[e]||{}}:{...this.mem};let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/player/state`,t)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/player/state`,{group:e,values:t})}},S=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.memPersona={name:""};this.state=new _(e,t,n)}async get(){return this.isPreview?{...this.memPersona}:this.http.get(`/conversations/${this.getConversationId()}/player`)}async update(e){if(this.isPreview){Object.assign(this.memPersona,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/player`,e)}};var k=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e!==void 0?this.mem[e]:{...this.mem};let t=await this.http.get(`/conversations/${this.getConversationId()}/custom`);return e!==void 0?t[e]:t}async set(e){if(this.isPreview){for(let[t,n]of Object.entries(e))typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof this.mem[t]=="object"&&this.mem[t]!==null?this.mem[t]={...this.mem[t],...n}:this.mem[t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom`,e)}async delete(e){if(this.isPreview){delete this.mem[e];return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}`)}async setGroupField(e,t,n){if(this.isPreview){(!this.mem[e]||typeof this.mem[e]!="object")&&(this.mem[e]={}),this.mem[e][t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{value:n})}async deleteGroupField(e,t){if(this.isPreview){if(typeof this.mem[e]=="object"&&this.mem[e]!==null){let n=this.mem[e];delete n[t]}return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var N="/functions/v1/world-engine/v1",Y="https://api.storvia.ai";function X(){return window.__STORVIA__||{}}function W(l=5e3){let e=X();return e.apiBase?Promise.resolve(e):new Promise((t,n)=>{let i=setTimeout(()=>{window.removeEventListener("message",s),n(new h("NOT_INITIALIZED","Timed out waiting for __STORVIA__ config from parent frame."))},l);function s(r){let o=null;if(r.data?.type==="storvia-init"&&r.data.apiBase?o={apiBase:r.data.apiBase,gameId:r.data.gameId,accessToken:r.data.accessToken}:r.data?.type==="storvia-preview-init"&&r.data.config&&(o=r.data.config),o&&o.apiBase){clearTimeout(i),window.removeEventListener("message",s);let a=window;a.__STORVIA__=o,t(o)}}window.addEventListener("message",s)})}var T=class{constructor(){this.baseUrl="";this.gameId="";this.conversationId="";this.modelId="";this.accessToken="";this.initialized=!1;this.isPreview=!1;this.previewConfig=void 0}async init(){if(this.initialized)return;let e=await W(),t=e.apiBase;if(!t)throw new h("NOT_INITIALIZED","window.__STORVIA__.apiBase is not set. The platform must inject it before SDK init.");if(this.baseUrl=`${t}${N}`,this.isPreview=!!e.preview,this.previewConfig=e.previewConfig,!e.gameId)throw new h("GAME_NOT_FOUND","window.__STORVIA__.gameId is not set. The platform must inject it before SDK init.");if(this.gameId=e.gameId,!e.accessToken)throw new h("UNAUTHORIZED","window.__STORVIA__.accessToken is not set. The platform must inject the user token before SDK init.");if(this.accessToken=e.accessToken,this.http=new P(this.baseUrl,this.accessToken,!!e.debug),this.isPreview){this.conversationId="00000000-0000-0000-0000-000000000000";let d=await this.fetchModels();this.modelId=e.selectedModelId||d[0]?.id||"",this.settingsSheet=new y({onModelChange:f=>{this.modelId=f},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),d.length>0&&this.settingsSheet.mount(d,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let p=()=>this.gameId,g=()=>this.conversationId,v=()=>this.modelId;this.chat=new w(this.http,p,g,v,!0,this.previewConfig),this.characters=new C(this.http,g,!0),this.relationships=new x(this.http,g,!0),this.inventory=new I(this.http,g,!0),this.world=new E(this.http,g,!0),this.player=new S(this.http,g,!0),this.custom=new k(this.http,g,!0),this.initialized=!0,this.listenForPreviewMessages();return}let[n,i]=await Promise.all([this.authenticate(),this.fetchModels()]);this.conversationId=n.conversationId;let s=this.getSavedModelId();this.modelId=s&&i.some(d=>d.id===s)?s:i[0]?.id||"";let r=n.settings||{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.settingsSheet=new y({onModelChange:d=>{this.modelId=d},onSettingsChange:d=>this.saveSettings(d),onSync:()=>this.syncSettings()}),this.settingsSheet.mount(i,this.modelId,r,n.hasWorldUpdate??!1);let o=()=>this.gameId,a=()=>this.conversationId,c=()=>this.modelId;this.chat=new w(this.http,o,a,c),this.characters=new C(this.http,a),this.relationships=new x(this.http,a),this.inventory=new I(this.http,a),this.world=new E(this.http,a),this.player=new S(this.http,a),this.custom=new k(this.http,a),this.initialized=!0}listenForPreviewMessages(){window.addEventListener("message",e=>{!e.data||e.data.type!=="storvia-preview"||(e.data.action==="set-model"&&(this.modelId=e.data.modelId||""),e.data.action==="update-config"&&(this.previewConfig=e.data.previewConfig,this.chat&&this.chat.updatePreviewConfig(this.previewConfig)))})}async saveSettings(e){await this.http.patch("/settings",{conversation_id:this.conversationId,...e})}async syncSettings(){await this.http.post("/sync",{conversation_id:this.conversationId})}async fetchModels(){try{return await this.http.get("/models")}catch{}return[]}async authenticate(){let e=await fetch(`${this.baseUrl}/auth`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.accessToken}`},body:JSON.stringify({game_id:this.gameId})});if(!e.ok)throw e.status===401?new h("UNAUTHORIZED","User not authenticated"):e.status===404?new h("GAME_NOT_FOUND","Game not found or not published"):new h("INTERNAL_ERROR",`Auth failed: HTTP ${e.status}`);let t=await e.json();return t.data??t}getSavedModelId(){try{return localStorage.getItem("storvia_model_id")||""}catch{return""}}async initDev(e){if(this.initialized)return;this.baseUrl=`${Y}${N}`,this.gameId=e.gameId,this.isPreview=!0,this.http=new P(this.baseUrl,"",!1,e.apiKey);let t=await this.fetchModels();this.modelId=t[0]?.id||"",this.conversationId="00000000-0000-0000-0000-000000000000",this.settingsSheet=new y({onModelChange:r=>{this.modelId=r},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),t.length>0&&this.settingsSheet.mount(t,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let n=()=>this.gameId,i=()=>this.conversationId,s=()=>this.modelId;this.chat=new w(this.http,n,i,s,!0,void 0),this.characters=new C(this.http,i,!0),this.relationships=new x(this.http,i,!0),this.inventory=new I(this.http,i,!0),this.world=new E(this.http,i,!0),this.player=new S(this.http,i,!0),this.custom=new k(this.http,i,!0),this.initialized=!0}};async function K(l){let e=new T;return l?.dev?await e.initDev(l.dev):await e.init(),e}function D(l){return typeof l=="object"&&l!==null&&"value"in l&&"type"in l&&(l.type==="number"||l.type==="text")}function Z(l){return D(l)?l.value:l}export{h as StorviaError,T as StorviaSDK,K as createStorviaSDK,Z as extractFieldValue,D as isRichFieldValue};
688
+ `}getStatusDotColor(e){if(e.is_active===!1)return"#6b7280";let t=e.success_rate??100;return t>=95?"#10b981":t>=80?"#3b82f6":t>=60?"#eab308":"#f97316"}getStatusClass(e){if(e.is_active===!1)return"inactive";let t=e.success_rate??100;return t>=95?"excellent":t>=80?"good":t>=60?"normal":"crowded"}getStatusText(e){if(e.is_active===!1)return"\u505C\u7528";let t=e.success_rate??100;return t>=95?"\u6D41\u7545":t>=80?"\u826F\u597D":t>=60?"\u4E00\u822C":"\u62E5\u6324"}getCreditsRange(e){let t=e.credits_config?.min??0,n=e.credits_config?.max??0;return t===0&&n===0?"":t===n?`${t}`:`${t}\uFF5E${n}`}buildSettingsTab(){let e=document.createElement("div"),t=document.createElement("div");return t.className="form-stack",t.appendChild(this.buildTemperatureSection()),t.appendChild(this.buildReplyLengthSection()),t.appendChild(this.buildReplyLanguageSection()),t.appendChild(this.buildNoteSection()),t.appendChild(this.buildSyncSection()),e.appendChild(t),e}buildTemperatureSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label";let n=document.createElement("span");n.textContent="\u6E29\u5EA6";let i=document.createElement("span");i.className="temperature-value",i.textContent=this.settings.temperature.toFixed(1),this.tempValueEl=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("p");s.className="form-hint",s.textContent="\u66F4\u4F4E\u8BA9 AI \u56DE\u590D\u66F4\u7A33\u5B9A\u7406\u667A\uFF0C\u66F4\u9AD8\u8BA9\u56DE\u590D\u66F4\u5177\u591A\u6837\u6027",e.appendChild(s);let r=document.createElement("input");r.type="range",r.className="slider",r.min="0",r.max="1",r.step="0.1",r.value=String(this.settings.temperature),r.addEventListener("input",()=>{let l=parseFloat(r.value);this.settings.temperature=l,this.tempValueEl&&(this.tempValueEl.textContent=l.toFixed(1))}),e.appendChild(r);let a=document.createElement("div");return a.className="slider-labels",a.innerHTML="<span>\u7CBE\u786E</span><span>\u521B\u610F</span>",e.appendChild(a),e}buildReplyLengthSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label",t.textContent="\u56DE\u590D\u957F\u5EA6",e.appendChild(t);let n=document.createElement("div");return n.className="segment-control",this.segmentBtns=[],$.forEach(i=>{let s=document.createElement("button");s.className=`segment-button${i.value===this.settings.reply_length?" active":""}`,s.textContent=i.label,s.addEventListener("click",()=>{this.settings.reply_length=i.value,this.segmentBtns.forEach((r,a)=>{r.classList.toggle("active",$[a].value===i.value)})}),this.segmentBtns.push(s),n.appendChild(s)}),e.appendChild(n),e}buildReplyLanguageSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label",t.textContent="\u56DE\u590D\u8BED\u8A00",e.appendChild(t);let n=document.createElement("div");n.className="custom-select";let i=document.createElement("button");i.className="select-trigger";let s=document.createElement("span");s.textContent=k.find(l=>l.value===this.settings.reply_language)?.label||"";let r=document.createElement("span");r.className="select-arrow",r.textContent="\u25BE",this.langArrow=r,i.appendChild(s),i.appendChild(r),i.addEventListener("click",l=>{l.stopPropagation(),this.toggleLangDropdown()}),n.appendChild(i);let a=document.createElement("div");return a.className="select-dropdown",this.langDropdown=a,this.langOptions=[],k.forEach(l=>{let p=document.createElement("button");p.className=`select-option${l.value===this.settings.reply_language?" active":""}`,p.innerHTML=`<span>${l.label}</span>${l.value===this.settings.reply_language?L:""}`,p.addEventListener("click",()=>{this.settings.reply_language=l.value,s.textContent=l.label,this.langOptions.forEach((d,c)=>{d.classList.toggle("active",k[c].value===l.value),d.innerHTML=`<span>${k[c].label}</span>${k[c].value===l.value?L:""}`}),this.closeLangDropdown()}),this.langOptions.push(p),a.appendChild(p)}),n.appendChild(a),e.appendChild(n),e}toggleLangDropdown(){this.langDropdownOpen?this.closeLangDropdown():this.openLangDropdown()}openLangDropdown(){this.langDropdownOpen=!0,this.langDropdown?.classList.add("open"),this.langArrow&&(this.langArrow.textContent="\u25B4")}closeLangDropdown(){this.langDropdownOpen=!1,this.langDropdown?.classList.remove("open"),this.langArrow&&(this.langArrow.textContent="\u25BE")}buildNoteSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label";let n=document.createElement("span");n.textContent="\u5907\u6CE8";let i=document.createElement("span");i.className="char-count",i.textContent=`${this.settings.player_note.length}/50`,this.noteCounter=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("p");s.className="form-hint",s.textContent="\u5199\u4E0B\u4F60\u5BF9\u8FD9\u4E2A\u6E38\u620F\u7684\u5907\u6CE8\uFF0C\u4F1A\u663E\u793A\u5728\u5B58\u6863\u5217\u8868",e.appendChild(s);let r=document.createElement("textarea");return r.className="player-note-input",r.placeholder="\u5907\u6CE8",r.maxLength=50,r.rows=2,r.value=this.settings.player_note,r.addEventListener("input",()=>{this.settings.player_note=r.value,this.noteCounter&&(this.noteCounter.textContent=`${r.value.length}/50`)}),e.appendChild(r),e}buildSyncSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label",t.textContent="\u540C\u6B65\u6E38\u620F\u8BBE\u5B9A",e.appendChild(t);let n=document.createElement("p");n.className=`sync-hint${this.hasWorldUpdate?" visible":""}`,n.textContent="\u26A0 \u4F5C\u8005\u5DF2\u66F4\u65B0\u6E38\u620F\u5185\u5BB9\uFF0C\u5EFA\u8BAE\u70B9\u51FB\u540C\u6B65",this.syncHint=n,e.appendChild(n);let i=document.createElement("p");i.className="form-hint",i.textContent="\u5C06\u6700\u65B0\u6E38\u620F\u8BBE\u5B9A\u548C\u5F00\u5E55\u5C0F\u5267\u573A\u540C\u6B65\u5230\u5F53\u524D\u5BF9\u8BDD",e.appendChild(i);let s=document.createElement("button");return s.className="btn btn-sync",this.syncBtn=s,this.renderSyncBtn(),s.addEventListener("click",async()=>{if(this.syncState!=="loading"){this.setSyncState("loading");try{await this.callbacks.onSync(),this.setSyncState("success"),this.hasWorldUpdate=!1,this.fabDot&&this.fabDot.classList.remove("visible"),this.syncHint&&this.syncHint.classList.remove("visible"),setTimeout(()=>this.setSyncState("idle"),3e3)}catch{this.setSyncState("error"),setTimeout(()=>this.setSyncState("idle"),4e3)}}}),e.appendChild(s),e}setSyncState(e){this.syncState=e,this.renderSyncBtn()}renderSyncBtn(){if(!this.syncBtn)return;let e=this.syncState,t={idle:V,loading:Y,success:X,error:W},n={idle:"\u540C\u6B65\u6700\u65B0\u8BBE\u5B9A",loading:"\u540C\u6B65\u4E2D...",success:"\u5DF2\u540C\u6B65",error:"\u540C\u6B65\u5931\u8D25"};this.syncBtn.className=`btn btn-sync${e==="success"||e==="error"?` ${e}`:""}`,this.syncBtn.disabled=e==="loading",this.syncBtn.innerHTML=`${t[e]}<span>${n[e]}</span>`}async handleSave(){if(!(!this.saveBtn||this.saveBtn.disabled)){this.saveBtn.disabled=!0,this.saveBtn.innerHTML='<span class="spinner"></span>\u4FDD\u5B58\u4E2D...';try{await this.callbacks.onSettingsChange({temperature:this.settings.temperature,reply_length:this.settings.reply_length,reply_language:this.settings.reply_language,player_note:this.settings.player_note}),this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1)}catch{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58\u5931\u8D25",setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1)},2e3))}}}escapeHtml(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}applyHostPosition(){this.host.style.left=`${this.fabX}px`,this.host.style.top=`${this.fabY}px`,this.host.style.right="auto",this.host.style.bottom="auto",this.applyPanelPosition()}isMobile(){return window.innerWidth<=768}applyPanelPosition(){if(!this.panel)return;if(this.isMobile()){this.panel.style.left="",this.panel.style.right="",this.panel.style.top="",this.panel.style.bottom="";return}let e=this.fabX+m/2<window.innerWidth/2,t=380;e?(this.panel.style.left="0",this.panel.style.right="auto"):(this.panel.style.left=`${m-t}px`,this.panel.style.right="auto"),this.fabY>500?(this.panel.style.bottom=`${m+8}px`,this.panel.style.top="auto"):(this.panel.style.top=`${m+8}px`,this.panel.style.bottom="auto")}togglePanel(){this.panel&&(this.panel.classList.contains("open")?this.closePanel():(this.applyPanelPosition(),this.panel.classList.add("open"),requestAnimationFrame(()=>{this.panel?.classList.contains("open")&&(this.fab&&(this.fab.style.visibility="hidden"),this.fabDot&&(this.fabDot.style.visibility="hidden"))}),this.isMobile()&&this.lockBodyScroll()))}closePanel(){this.panel&&this.panel.classList.remove("open"),this.fab&&(this.fab.style.visibility="visible"),this.fabDot&&(this.fabDot.style.visibility="visible"),this.unlockBodyScroll()}lockBodyScroll(){this.savedBodyOverflow===null&&(this.savedBodyOverflow=document.body.style.overflow||"",document.body.style.overflow="hidden")}unlockBodyScroll(){this.savedBodyOverflow!==null&&(document.body.style.overflow=this.savedBodyOverflow,this.savedBodyOverflow=null)}};var w=class{constructor(e,t,n,i,s=!1,r){this.http=e;this.getGameId=t;this.getConversationId=n;this.getModelId=i;this.isPreview=s;this.previewConfig=r}updatePreviewConfig(e){this.previewConfig=e}async send(e){if(this.isPreview)return this.sendPreview(e);let t={game_id:this.getGameId(),conversation_id:this.getConversationId(),model_id:this.getModelId(),message:e.message,topic:e.topic,scene_key:e.scene_key,stream:e.stream??!1};if(e.stream){await this.http.stream("/chat",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/chat",t)}async save(e){return this.isPreview?{id:`preview-${Date.now()}`}:this.http.post("/messages/save",{conversation_id:this.getConversationId(),role:e.role,content:e.content,topic:e.topic})}async generate(e){if(this.isPreview)return this.sendPreview({message:"",topic:e.topic,scene_key:e.scene_key,stream:e.stream,onChunk:e.onChunk,onDone:e.onDone});let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,scene_key:e.scene_key,stream:e.stream??!1,save:e.save??!0};if(e.stream){await this.http.stream("/generate",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/generate",t)}async retry(e={}){if(this.isPreview)throw new Error("Retry is not supported in preview mode");let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,scene_key:e.scene_key,stream:e.stream??!1};if(e.stream){await this.http.stream("/retry",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/retry",t)}async sendPreview(e){let t={model_id:this.getModelId(),message:e.message,topic:e.topic,scene_key:e.scene_key,history_messages:[]};if(this.previewConfig?t.prompt_config=this.previewConfig:t.game_id=this.getGameId(),e.stream){await this.http.stream("/preview",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}let n="";return await this.http.stream("/preview",t,i=>{n+=i},()=>{}),{id:"",content:n}}};var _=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem={...i})}setInitial(e){this.mem=e?{...e}:{}}async get(e){return this.isPreview?{...this.mem[e]||{}}:this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,t)}},C=class{constructor(e,t,n=!1,i,s){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];i&&(this.mem=i.map(D)),this.state=new _(e,t,n,s)}setInitial(e,t){this.mem=e?e.map(D):[],this.state.setInitial(t)}async list(){return this.isPreview?this.mem.map(N):this.http.get(`/conversations/${this.getConversationId()}/characters`)}async get(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return t?N(t):{name:e}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async add(e){if(this.isPreview){this.mem.push({...e,isPreset:!1});return}await this.http.post(`/conversations/${this.getConversationId()}/characters`,e)}async update(e,t){if(this.isPreview){let n=this.mem.find(i=>i.name===e);n&&Object.assign(n,t);return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`,t)}async remove(e){if(this.isPreview){this.mem=this.mem.filter(t=>t.name!==e);return}await this.http.delete(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async detail(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:e,avatar:t?.avatar,description:t?.description,userDescription:t?.userDescription,...t?.gender?{gender:t.gender}:{},...t?.isPreset!==void 0?{isPreset:t.isPreset}:{},state:await this.state.get(e)}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/detail`)}async setPriority(e,t){let n=Math.max(0,Math.min(100,Math.round(t)));this.isPreview||await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,{priority:n})}};function D(o){return{name:o.name,description:o.description,avatar:o.avatar,...o.gender?{gender:o.gender}:{},...o.userDescription!==void 0?{userDescription:o.userDescription}:{},...o.isPreset!==void 0?{isPreset:o.isPreset}:{}}}function N(o){return{name:o.name,avatar:o.avatar,description:o.description,...o.userDescription!==void 0?{userDescription:o.userDescription}:{},...o.gender?{gender:o.gender}:{},...o.isPreset!==void 0?{isPreset:o.isPreset}:{}}}var x=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];i&&(this.mem=i.map(s=>({...s})))}setInitial(e){this.mem=e?e.map(t=>({...t})):[]}async list(){return this.isPreview?[...this.mem]:this.http.get(`/conversations/${this.getConversationId()}/relationships`)}async get(e,t){if(this.isPreview){let n=this.mem.find(i=>i.from===e&&i.to===t);if(n)return{...n};throw new Error("Relationship not found")}return this.http.get(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/relationships`,e)}async update(e,t,n){if(this.isPreview){let i=this.mem.find(s=>s.from===e&&s.to===t);i?Object.assign(i,n):this.mem.push({from:e,to:t,...n});return}await this.http.patch(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,n)}async remove(e,t){if(this.isPreview){this.mem=this.mem.filter(n=>!(n.from===e&&n.to===t));return}await this.http.delete(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var I=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem=B(i))}setInitial(e){this.mem=e?B(e):{}}async list(e){if(this.isPreview){if(e!==void 0)return{...this.mem[e]||{}};let t={};for(let[n,i]of Object.entries(this.mem))t[n]={...i};return t}return e!==void 0?this.http.get(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(e)}`):this.http.get(`/conversations/${this.getConversationId()}/inventory`)}async add(e){let{group:t,name:n,count:i=1,desc:s,iconUrl:r}=e;if(this.isPreview){if(!this.mem[t])throw new Error(`Group "${t}" does not exist`);if(n in this.mem[t])throw new Error(`Item "${n}" already exists in group "${t}"`);let a={count:i};s!==void 0&&(a.desc=s),r!==void 0&&(a.iconUrl=r),this.mem[t][n]=a;return}await this.http.post(`/conversations/${this.getConversationId()}/inventory`,{group:t,name:n,count:i,desc:s,iconUrl:r})}async update(e){let{group:t,name:n,...i}=e;if(this.isPreview){let s=this.mem[t];if(!s||!(n in s))throw new Error(`Item "${t}/${n}" not found`);Object.assign(s[n],i);return}await this.http.patch(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,i)}async remove(e){let{group:t,name:n}=e;if(this.isPreview){this.mem[t]&&delete this.mem[t][n];return}await this.http.delete(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(t)}/${encodeURIComponent(n)}`)}async move(e){let{fromGroup:t,toGroup:n,name:i,newName:s}=e;if(this.isPreview){let r=this.mem[t];if(!r||!(i in r))throw new Error(`Source item "${t}/${i}" not found`);if(!this.mem[n])throw new Error(`Target group "${n}" does not exist`);let a=s||i;if(t===n&&a===i)return;if(a in this.mem[n])throw new Error(`Item "${a}" already exists in target group`);this.mem[n][a]=r[i],delete r[i];return}await this.http.post(`/conversations/${this.getConversationId()}/inventory/move`,{fromGroup:t,toGroup:n,name:i,newName:s})}async ensureGroup(e){if(this.isPreview){this.mem[e]||(this.mem[e]={});return}await this.http.post(`/conversations/${this.getConversationId()}/inventory/groups/${encodeURIComponent(e)}`,{})}async removeGroup(e,t){let n=t?.cascade??!1;if(this.isPreview){let s=this.mem[e];if(s&&Object.keys(s).length>0&&!n)throw new Error(`Group "${e}" is not empty, pass cascade: true to force delete`);delete this.mem[e];return}let i=n?"?cascade=true":"";await this.http.delete(`/conversations/${this.getConversationId()}/inventory/groups/${encodeURIComponent(e)}${i}`)}};function B(o){let e={};for(let[t,n]of Object.entries(o)){let i={};for(let[s,r]of Object.entries(n))i[s]={...r};e[t]=i}return e}var P=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem={...i})}setInitial(e){this.mem=e?{...e}:{}}async get(){return this.isPreview?{...this.mem}:this.http.get(`/conversations/${this.getConversationId()}/world`)}async update(e){if(this.isPreview){Object.assign(this.mem,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/world`,e)}};var O=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem={...i})}setInitial(e){this.mem=e?{...e}:{}}async get(e){if(this.isPreview)return e?{...this.mem[e]||{}}:{...this.mem};let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/player/state`,t)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/player/state`,{group:e,values:t})}},S=class{constructor(e,t,n=!1,i,s){this.http=e;this.getConversationId=t;this.isPreview=n;this.memPersona={name:""};i&&(this.memPersona={...i}),this.state=new O(e,t,n,s)}setInitial(e,t){this.memPersona=e?{...e}:{name:""},this.state.setInitial(t)}async get(){return this.isPreview?{...this.memPersona}:this.http.get(`/conversations/${this.getConversationId()}/player`)}async update(e){if(this.isPreview){Object.assign(this.memPersona,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/player`,e)}};var E=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem=H(i))}setInitial(e){this.mem=e?H(e):{}}async get(e){if(this.isPreview)return e!==void 0?this.mem[e]:{...this.mem};let t=await this.http.get(`/conversations/${this.getConversationId()}/custom`);return e!==void 0?t[e]:t}async set(e){if(this.isPreview){for(let[t,n]of Object.entries(e))typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof this.mem[t]=="object"&&this.mem[t]!==null?this.mem[t]={...this.mem[t],...n}:this.mem[t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom`,e)}async delete(e){if(this.isPreview){delete this.mem[e];return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}`)}async setGroupField(e,t,n){if(this.isPreview){(!this.mem[e]||typeof this.mem[e]!="object")&&(this.mem[e]={}),this.mem[e][t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{value:n})}async deleteGroupField(e,t){if(this.isPreview){if(typeof this.mem[e]=="object"&&this.mem[e]!==null){let n=this.mem[e];delete n[t]}return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};function H(o){let e={};for(let[t,n]of Object.entries(o))typeof n=="object"&&n!==null&&!Array.isArray(n)?e[t]={...n}:e[t]=n;return e}var U="/functions/v1/world-engine/v1",Z="https://api.storvia.ai";function q(){return window.__STORVIA__||{}}function J(o=5e3){let e=q();return e.apiBase?Promise.resolve(e):new Promise((t,n)=>{let i=setTimeout(()=>{window.removeEventListener("message",s),n(new g("NOT_INITIALIZED","Timed out waiting for __STORVIA__ config from parent frame."))},o);function s(r){let a=null;if(r.data?.type==="storvia-init"&&r.data.apiBase?a={apiBase:r.data.apiBase,gameId:r.data.gameId,accessToken:r.data.accessToken}:r.data?.type==="storvia-preview-init"&&r.data.config&&(a=r.data.config),a&&a.apiBase){clearTimeout(i),window.removeEventListener("message",s);let l=window;l.__STORVIA__=a,t(a)}}window.addEventListener("message",s)})}var M=class{constructor(){this.baseUrl="";this.gameId="";this.conversationId="";this.modelId="";this.accessToken="";this.initialized=!1;this.isPreview=!1;this.previewConfig=void 0}async init(){if(this.initialized)return;let e=await J(),t=e.apiBase;if(!t)throw new g("NOT_INITIALIZED","window.__STORVIA__.apiBase is not set. The platform must inject it before SDK init.");if(this.baseUrl=`${t}${U}`,this.isPreview=!!e.preview,this.previewConfig=e.previewConfig,!e.gameId)throw new g("GAME_NOT_FOUND","window.__STORVIA__.gameId is not set. The platform must inject it before SDK init.");if(this.gameId=e.gameId,!e.accessToken)throw new g("UNAUTHORIZED","window.__STORVIA__.accessToken is not set. The platform must inject the user token before SDK init.");if(this.accessToken=e.accessToken,this.http=new R(this.baseUrl,this.accessToken,!!e.debug),this.isPreview){this.conversationId="00000000-0000-0000-0000-000000000000";let[d,c]=await Promise.all([this.fetchModels(),this.fetchPreviewSnapshot()]);this.modelId=e.selectedModelId||d[0]?.id||"",this.settingsSheet=new y({onModelChange:T=>{this.modelId=T},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),d.length>0&&this.settingsSheet.mount(d,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let f=()=>this.gameId,h=()=>this.conversationId,v=()=>this.modelId;this.chat=new w(this.http,f,h,v,!0,this.previewConfig),this.characters=new C(this.http,h,!0,c?.characters,c?.characterStates),this.relationships=new x(this.http,h,!0,c?.relationships),this.inventory=new I(this.http,h,!0,c?.inventory),this.world=new P(this.http,h,!0,c?.world),this.player=new S(this.http,h,!0,c?.player,c?.playerState),this.custom=new E(this.http,h,!0,c?.custom),this.initialized=!0,this.listenForPreviewMessages();return}let[n,i]=await Promise.all([this.authenticate(),this.fetchModels()]);this.conversationId=n.conversationId;let s=this.getSavedModelId();this.modelId=s&&i.some(d=>d.id===s)?s:i[0]?.id||"";let r=n.settings||{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.settingsSheet=new y({onModelChange:d=>{this.modelId=d},onSettingsChange:d=>this.saveSettings(d),onSync:()=>this.syncSettings()}),this.settingsSheet.mount(i,this.modelId,r,n.hasWorldUpdate??!1);let a=()=>this.gameId,l=()=>this.conversationId,p=()=>this.modelId;this.chat=new w(this.http,a,l,p),this.characters=new C(this.http,l),this.relationships=new x(this.http,l),this.inventory=new I(this.http,l),this.world=new P(this.http,l),this.player=new S(this.http,l),this.custom=new E(this.http,l),this.initialized=!0}listenForPreviewMessages(){window.addEventListener("message",e=>{!e.data||e.data.type!=="storvia-preview"||(e.data.action==="set-model"&&(this.modelId=e.data.modelId||""),e.data.action==="update-config"&&(this.previewConfig=e.data.previewConfig,this.chat&&this.chat.updatePreviewConfig(this.previewConfig),this.refreshPreviewSnapshot().catch(t=>{console.warn("[Storvia SDK] refreshPreviewSnapshot failed:",t)})))})}async fetchPreviewSnapshot(){try{let e={game_id:this.gameId};return this.previewConfig&&("game_config"in this.previewConfig&&(e.game_config=this.previewConfig.game_config),"game_state"in this.previewConfig&&(e.game_state_override=this.previewConfig.game_state)),await this.http.post("/preview/initial-snapshot",e)}catch(e){return console.warn("[Storvia SDK] fetchPreviewSnapshot failed:",e),null}}async refreshPreviewSnapshot(){let e=await this.fetchPreviewSnapshot();e&&(this.characters?.setInitial(e.characters,e.characterStates),this.player?.setInitial(e.player,e.playerState),this.inventory?.setInitial(e.inventory),this.relationships?.setInitial(e.relationships),this.world?.setInitial(e.world),this.custom?.setInitial(e.custom))}async saveSettings(e){await this.http.patch("/settings",{conversation_id:this.conversationId,...e})}async syncSettings(){await this.http.post("/sync",{conversation_id:this.conversationId})}async fetchModels(){try{return await this.http.get("/models")}catch{}return[]}async authenticate(){let e=await fetch(`${this.baseUrl}/auth`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.accessToken}`},body:JSON.stringify({game_id:this.gameId})});if(!e.ok)throw e.status===401?new g("UNAUTHORIZED","User not authenticated"):e.status===404?new g("GAME_NOT_FOUND","Game not found or not published"):new g("INTERNAL_ERROR",`Auth failed: HTTP ${e.status}`);let t=await e.json();return t.data??t}getSavedModelId(){try{return localStorage.getItem("storvia_model_id")||""}catch{return""}}async initDev(e){if(this.initialized)return;this.baseUrl=`${Z}${U}`,this.gameId=e.gameId,this.isPreview=!0,this.http=new R(this.baseUrl,"",!1,e.apiKey);let[t,n]=await Promise.all([this.fetchModels(),this.fetchPreviewSnapshot()]);this.modelId=t[0]?.id||"",this.conversationId="00000000-0000-0000-0000-000000000000",this.settingsSheet=new y({onModelChange:a=>{this.modelId=a},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),t.length>0&&this.settingsSheet.mount(t,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let i=()=>this.gameId,s=()=>this.conversationId,r=()=>this.modelId;this.chat=new w(this.http,i,s,r,!0,void 0),this.characters=new C(this.http,s,!0,n?.characters,n?.characterStates),this.relationships=new x(this.http,s,!0,n?.relationships),this.inventory=new I(this.http,s,!0,n?.inventory),this.world=new P(this.http,s,!0,n?.world),this.player=new S(this.http,s,!0,n?.player,n?.playerState),this.custom=new E(this.http,s,!0,n?.custom),this.initialized=!0}};async function Q(o){let e=new M;return o?.dev?await e.initDev(o.dev):await e.init(),e}function A(o){return typeof o=="object"&&o!==null&&"value"in o&&"type"in o&&(o.type==="number"||o.type==="text")}function ee(o){return A(o)?o.value:o}export{g as StorviaError,M as StorviaSDK,Q as createStorviaSDK,ee as extractFieldValue,A as isRichFieldValue};
package/dist/index.umd.js CHANGED
@@ -1,5 +1,5 @@
1
- "use strict";var StorviaSDK=(()=>{var M=Object.defineProperty;var A=Object.getOwnPropertyDescriptor;var F=Object.getOwnPropertyNames;var G=Object.prototype.hasOwnProperty;var z=(l,e)=>{for(var t in e)M(l,t,{get:e[t],enumerable:!0})},j=(l,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of F(e))!G.call(l,i)&&i!==t&&M(l,i,{get:()=>e[i],enumerable:!(n=A(e,i))||n.enumerable});return l};var V=l=>j(M({},"__esModule",{value:!0}),l);var se={};z(se,{StorviaError:()=>p,StorviaSDK:()=>T,createStorviaSDK:()=>H,extractFieldValue:()=>U,isRichFieldValue:()=>$});var p=class extends Error{constructor(e,t){super(t),this.name="StorviaError",this.code=e}};var P=class{constructor(e,t,n=!1,i=""){this.baseUrl=e,this.token=t,this.debug=n,this.devApiKey=i}setToken(e){this.token=e}setDebug(e){this.debug=e}buildHeaders(){let e={"Content-Type":"application/json"};return this.token&&(e.Authorization=`Bearer ${this.token}`),this.devApiKey&&(e["x-api-key"]=this.devApiKey),e}log(e,t,n,i,s){if(!this.debug)return;let r="%c[Storvia SDK]",o="color: #6366f1; font-weight: bold";s?(console.groupCollapsed(`${r} %c${e} ${t} %c\u2717`,o,"color: #e0e0e0","color: #ef4444"),n&&console.log("Request:",n),console.error("Error:",s),console.groupEnd()):(console.groupCollapsed(`${r} %c${e} ${t} %c\u2713`,o,"color: #e0e0e0","color: #22c55e"),n&&console.log("Request:",n),i!==void 0&&console.log("Response:",i),console.groupEnd())}async get(e,t){let n=new URL(`${this.baseUrl}${e}`);t&&Object.entries(t).forEach(([i,s])=>n.searchParams.set(i,s));try{let i=await fetch(n.toString(),{method:"GET",headers:this.buildHeaders()}),s=await this.handleResponse(i);return this.log("GET",e,t,s),s}catch(i){throw this.log("GET",e,t,void 0,i),i}}async post(e,t){try{let n=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0}),i=await this.handleResponse(n);return this.log("POST",e,t,i),i}catch(n){throw this.log("POST",e,t,void 0,n),n}}async patch(e,t){try{let n=await fetch(`${this.baseUrl}${e}`,{method:"PATCH",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0}),i=await this.handleResponse(n);return this.log("PATCH",e,t,i),i}catch(n){throw this.log("PATCH",e,t,void 0,n),n}}async delete(e){try{let t=await fetch(`${this.baseUrl}${e}`,{method:"DELETE",headers:this.buildHeaders()}),n=await this.handleResponse(t);return this.log("DELETE",e,void 0,n),n}catch(t){throw this.log("DELETE",e,void 0,void 0,t),t}}async stream(e,t,n,i){this.log("STREAM",e,t);let s=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify(t)});if(!s.ok){let d=await s.json().catch(()=>({})),h=new p(d.code||"INTERNAL_ERROR",d.message||`HTTP ${s.status}`);throw this.log("STREAM",e,t,void 0,h),h}let r=s.body?.getReader();if(!r)throw new p("INTERNAL_ERROR","No response body for stream");let o=new TextDecoder,a="",c="";for(;;){let{done:d,value:h}=await r.read();if(d)break;let v=o.decode(h,{stream:!0}).split(`
2
- `);for(let f of v){if(!f.startsWith("data: "))continue;let L=f.slice(6);if(L==="[DONE]"){this.debug&&this.log("STREAM",e+" [done]",void 0,{id:a,contentLength:c.length}),i(a);return}try{let b=JSON.parse(L);b.type==="done"&&b.id?a=b.id:b.content&&(c+=b.content,n(b.content))}catch{}}}a&&i(a)}async handleResponse(e){if(!e.ok){let n={};try{n=await e.json()}catch{}let i={401:"UNAUTHORIZED",402:"INSUFFICIENT_BALANCE",404:"GAME_NOT_FOUND",429:"RATE_LIMITED"},s=n.code||i[e.status]||"INTERNAL_ERROR";throw new p(s,n.message||`HTTP ${e.status}`)}let t=await e.json();return t&&typeof t=="object"&&"data"in t?t.data:t}};var R=[{value:"zh-CN",label:"\u7B80\u4F53\u4E2D\u6587"},{value:"zh-TW",label:"\u7E41\u9AD4\u4E2D\u6587"},{value:"en",label:"English"},{value:"ja",label:"\u65E5\u672C\u8A9E"},{value:"ko",label:"\uD55C\uAD6D\uC5B4"}],N=[{value:"low",label:"\u7B80\u77ED"},{value:"medium",label:"\u9002\u4E2D"},{value:"high",label:"\u8BE6\u7EC6"}],Y="https://cdn.storvia.ai/default/logo.png",X="https://api.storvia.ai/storage/v1/object/public/storvia/default/credits.png",W=`
1
+ "use strict";var StorviaSDK=(()=>{var _=Object.defineProperty;var z=Object.getOwnPropertyDescriptor;var V=Object.getOwnPropertyNames;var Y=Object.prototype.hasOwnProperty;var X=(o,e)=>{for(var t in e)_(o,t,{get:e[t],enumerable:!0})},W=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of V(e))!Y.call(o,i)&&i!==t&&_(o,i,{get:()=>e[i],enumerable:!(n=z(e,i))||n.enumerable});return o};var K=o=>W(_({},"__esModule",{value:!0}),o);var le={};X(le,{StorviaError:()=>h,StorviaSDK:()=>T,createStorviaSDK:()=>G,extractFieldValue:()=>j,isRichFieldValue:()=>L});var h=class extends Error{constructor(e,t){super(t),this.name="StorviaError",this.code=e}};var R=class{constructor(e,t,n=!1,i=""){this.baseUrl=e,this.token=t,this.debug=n,this.devApiKey=i}setToken(e){this.token=e}setDebug(e){this.debug=e}buildHeaders(){let e={"Content-Type":"application/json"};return this.token&&(e.Authorization=`Bearer ${this.token}`),this.devApiKey&&(e["x-api-key"]=this.devApiKey),e}log(e,t,n,i,s){if(!this.debug)return;let r="%c[Storvia SDK]",a="color: #6366f1; font-weight: bold";s?(console.groupCollapsed(`${r} %c${e} ${t} %c\u2717`,a,"color: #e0e0e0","color: #ef4444"),n&&console.log("Request:",n),console.error("Error:",s),console.groupEnd()):(console.groupCollapsed(`${r} %c${e} ${t} %c\u2713`,a,"color: #e0e0e0","color: #22c55e"),n&&console.log("Request:",n),i!==void 0&&console.log("Response:",i),console.groupEnd())}async get(e,t){let n=new URL(`${this.baseUrl}${e}`);t&&Object.entries(t).forEach(([i,s])=>n.searchParams.set(i,s));try{let i=await fetch(n.toString(),{method:"GET",headers:this.buildHeaders()}),s=await this.handleResponse(i);return this.log("GET",e,t,s),s}catch(i){throw this.log("GET",e,t,void 0,i),i}}async post(e,t){try{let n=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0}),i=await this.handleResponse(n);return this.log("POST",e,t,i),i}catch(n){throw this.log("POST",e,t,void 0,n),n}}async patch(e,t){try{let n=await fetch(`${this.baseUrl}${e}`,{method:"PATCH",headers:this.buildHeaders(),body:t?JSON.stringify(t):void 0}),i=await this.handleResponse(n);return this.log("PATCH",e,t,i),i}catch(n){throw this.log("PATCH",e,t,void 0,n),n}}async delete(e){try{let t=await fetch(`${this.baseUrl}${e}`,{method:"DELETE",headers:this.buildHeaders()}),n=await this.handleResponse(t);return this.log("DELETE",e,void 0,n),n}catch(t){throw this.log("DELETE",e,void 0,void 0,t),t}}async stream(e,t,n,i){this.log("STREAM",e,t);let s=await fetch(`${this.baseUrl}${e}`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify(t)});if(!s.ok){let d=await s.json().catch(()=>({})),c=new h(d.code||"INTERNAL_ERROR",d.message||`HTTP ${s.status}`);throw this.log("STREAM",e,t,void 0,c),c}let r=s.body?.getReader();if(!r)throw new h("INTERNAL_ERROR","No response body for stream");let a=new TextDecoder,l="",p="";for(;;){let{done:d,value:c}=await r.read();if(d)break;let g=a.decode(c,{stream:!0}).split(`
2
+ `);for(let v of g){if(!v.startsWith("data: "))continue;let M=v.slice(6);if(M==="[DONE]"){this.debug&&this.log("STREAM",e+" [done]",void 0,{id:l,contentLength:p.length}),i(l);return}try{let b=JSON.parse(M);b.type==="done"&&b.id?l=b.id:b.content&&(p+=b.content,n(b.content))}catch{}}}l&&i(l)}async handleResponse(e){if(!e.ok){let n={};try{n=await e.json()}catch{}let i={401:"UNAUTHORIZED",402:"INSUFFICIENT_BALANCE",404:"GAME_NOT_FOUND",429:"RATE_LIMITED"},s=n.code||i[e.status]||"INTERNAL_ERROR";throw new h(s,n.message||`HTTP ${e.status}`)}let t=await e.json();return t&&typeof t=="object"&&"data"in t?t.data:t}};var k=[{value:"zh-CN",label:"\u7B80\u4F53\u4E2D\u6587"},{value:"zh-TW",label:"\u7E41\u9AD4\u4E2D\u6587"},{value:"en",label:"English"},{value:"ja",label:"\u65E5\u672C\u8A9E"},{value:"ko",label:"\uD55C\uAD6D\uC5B4"}],D=[{value:"low",label:"\u7B80\u77ED"},{value:"medium",label:"\u9002\u4E2D"},{value:"high",label:"\u8BE6\u7EC6"}],Z="https://cdn.storvia.ai/default/logo.png",q="https://api.storvia.ai/storage/v1/object/public/storvia/default/credits.png",J=`
3
3
  :host {
4
4
  position: fixed;
5
5
  z-index: 2147483647;
@@ -673,7 +673,7 @@
673
673
  padding-bottom: calc(16px + env(safe-area-inset-bottom, 0px));
674
674
  }
675
675
  }
676
- `,K='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 6L6 18M6 6l12 12"/></svg>',Z='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2v6h-6M3 12a9 9 0 0 1 15-6.7L21 8M3 22v-6h6M21 12a9 9 0 0 1-15 6.7L3 16"/></svg>',q='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="spin"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',J='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',Q='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>',D='<svg class="check" viewBox="0 0 24 24" fill="none" stroke="#8246FF" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',m=48,u=16,ee=5,y=class{constructor(e){this.selectedModelId="";this.models=[];this.settings={temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.activeTab="model";this.selectedCategory=null;this.hasWorldUpdate=!1;this.fabDot=null;this.syncHint=null;this.fabX=0;this.fabY=0;this.fab=null;this.panel=null;this.modelTabBtn=null;this.settingsTabBtn=null;this.modelBody=null;this.settingsBody=null;this.footer=null;this.modelGrid=null;this.modelDetail=null;this.tempValueEl=null;this.segmentBtns=[];this.langDropdown=null;this.langOptions=[];this.langArrow=null;this.langDropdownOpen=!1;this.noteCounter=null;this.saveBtn=null;this.syncBtn=null;this.syncState="idle";this.dragStartX=0;this.dragStartY=0;this.dragOffsetX=0;this.dragOffsetY=0;this.dragMoved=!1;this.dragging=!1;this.handlePointerDown=e=>{this.fab&&(e.preventDefault(),this.dragStartX=e.clientX,this.dragStartY=e.clientY,this.dragOffsetX=e.clientX-this.fabX,this.dragOffsetY=e.clientY-this.fabY,this.dragMoved=!1,this.dragging=!0,this.fab.setPointerCapture(e.pointerId),this.fab.addEventListener("pointermove",this.handlePointerMove),this.fab.addEventListener("pointerup",this.handlePointerUp),this.fab.addEventListener("pointercancel",this.handlePointerUp))};this.handlePointerMove=e=>{if(!this.dragging)return;let t=e.clientX-this.dragStartX,n=e.clientY-this.dragStartY;!this.dragMoved&&Math.hypot(t,n)>ee&&(this.dragMoved=!0,this.fab?.classList.add("dragging"),this.closePanel()),this.dragMoved&&(this.fabX=e.clientX-this.dragOffsetX,this.fabY=e.clientY-this.dragOffsetY,this.applyHostPosition())};this.handlePointerUp=e=>{if(!this.fab)return;this.fab.removeEventListener("pointermove",this.handlePointerMove),this.fab.removeEventListener("pointerup",this.handlePointerUp),this.fab.removeEventListener("pointercancel",this.handlePointerUp);try{this.fab.releasePointerCapture(e.pointerId)}catch{}if(this.dragging=!1,!this.dragMoved){this.togglePanel();return}this.fab.classList.remove("dragging");let n=this.fabX+m/2<window.innerWidth/2;this.fabX=n?u:window.innerWidth-m-u,this.fabY=Math.max(u,Math.min(window.innerHeight-m-u,this.fabY)),this.fab&&(this.fab.style.transition="left 0.25s cubic-bezier(0.32, 0.72, 0, 1), top 0.25s cubic-bezier(0.32, 0.72, 0, 1), transform 0.2s, box-shadow 0.2s"),this.applyHostPosition(),setTimeout(()=>{this.fab&&(this.fab.style.transition="")},260)};this.handleResize=()=>{this.fabX=Math.max(u,Math.min(window.innerWidth-m-u,this.fabX)),this.fabY=Math.max(u,Math.min(window.innerHeight-m-u,this.fabY)),this.applyHostPosition()};this.handleDocClick=e=>{this.host.contains(e.target)||(this.closePanel(),this.closeLangDropdown())};this.savedBodyOverflow=null;this.callbacks=e,this.host=document.createElement("div"),this.host.id="storvia-settings",this.shadowRoot=this.host.attachShadow({mode:"closed"})}mount(e,t,n,i=!1){this.models=e,this.selectedModelId=t,this.settings={...n},this.hasWorldUpdate=i,this.fabX=window.innerWidth-m-u,this.fabY=window.innerHeight-m-u,document.body.appendChild(this.host),this.render(),this.applyHostPosition(),window.addEventListener("resize",this.handleResize),document.addEventListener("click",this.handleDocClick)}unmount(){window.removeEventListener("resize",this.handleResize),document.removeEventListener("click",this.handleDocClick),this.host.remove()}getSelectedModelId(){return this.selectedModelId}getSettings(){return{...this.settings}}render(){let e=document.createElement("style");e.textContent=W;let t=document.createElement("div");t.className="fab-wrap";let n=document.createElement("div");n.className="fab",n.title="\u6E38\u620F\u8BBE\u7F6E";let i=document.createElement("img");i.src=Y,i.alt="Storvia",n.appendChild(i),this.fab=n;let s=document.createElement("div");s.className=`fab-dot${this.hasWorldUpdate?" visible":""}`,this.fabDot=s,t.appendChild(n),t.appendChild(s);let r=document.createElement("div");r.className="panel",this.panel=r;let o=document.createElement("div");o.className="panel-header";let a=document.createElement("h2");a.className="panel-title",a.textContent="\u6E38\u620F\u8BBE\u7F6E";let c=document.createElement("button");c.className="close-btn",c.innerHTML=K,c.addEventListener("click",()=>this.closePanel()),o.appendChild(a),o.appendChild(c),r.appendChild(o);let d=document.createElement("div");d.className="tabs",this.modelTabBtn=this.createTabBtn("model","\u6A21\u578B\u9009\u62E9"),this.settingsTabBtn=this.createTabBtn("settings","\u6E38\u620F\u8BBE\u7F6E"),this.models.length===0&&(this.activeTab="settings",this.modelTabBtn.style.display="none"),d.appendChild(this.modelTabBtn),d.appendChild(this.settingsTabBtn),r.appendChild(d);let h=document.createElement("div");h.className="panel-body",this.modelBody=this.buildModelTab(),this.settingsBody=this.buildSettingsTab(),h.appendChild(this.modelBody),h.appendChild(this.settingsBody),r.appendChild(h);let g=document.createElement("div");g.className="panel-footer";let v=document.createElement("button");v.className="btn btn-save",v.textContent="\u4FDD\u5B58",this.saveBtn=v,v.addEventListener("click",()=>this.handleSave()),g.appendChild(v),this.footer=g,r.appendChild(g),n.addEventListener("pointerdown",this.handlePointerDown);let f=document.createElement("div");f.appendChild(r),f.appendChild(t),this.shadowRoot.appendChild(e),this.shadowRoot.appendChild(f),this.applyTab()}createTabBtn(e,t){let n=document.createElement("button");return n.className=`tab-btn${this.activeTab===e?" active":""}`,n.textContent=t,n.addEventListener("click",()=>{this.activeTab=e,this.applyTab()}),n}applyTab(){this.modelTabBtn&&this.modelTabBtn.classList.toggle("active",this.activeTab==="model"),this.settingsTabBtn&&this.settingsTabBtn.classList.toggle("active",this.activeTab==="settings"),this.modelBody&&(this.modelBody.style.display=this.activeTab==="model"?"block":"none"),this.settingsBody&&(this.settingsBody.style.display=this.activeTab==="settings"?"block":"none"),this.footer&&(this.footer.style.display=this.activeTab==="settings"?"flex":"none")}buildModelTab(){let e=document.createElement("div"),t=this.getCategories();if(t.length>0){let s=document.createElement("div");s.className="category-tabs";let r=(o,a)=>{let c=document.createElement("button");return c.className=`category-tab${this.selectedCategory===a?" active":""}`,c.textContent=o,c.addEventListener("click",()=>{this.selectedCategory=a,s.querySelectorAll(".category-tab").forEach(d=>d.classList.remove("active")),c.classList.add("active"),this.renderModelGrid()}),c};s.appendChild(r("\u5168\u90E8",null)),t.forEach(o=>s.appendChild(r(o,o))),e.appendChild(s)}let n=document.createElement("div");n.className="models-grid",this.modelGrid=n,e.appendChild(n);let i=document.createElement("div");return i.className="model-detail",i.style.display="none",this.modelDetail=i,e.appendChild(i),this.renderModelGrid(),this.renderModelDetail(),e}getCategories(){let e=new Set;return this.models.forEach(t=>{t.category&&e.add(t.category)}),Array.from(e)}getFilteredModels(){return this.selectedCategory?this.models.filter(e=>e.category===this.selectedCategory):this.models}renderModelGrid(){this.modelGrid&&(this.modelGrid.innerHTML="",this.getFilteredModels().forEach(e=>{let t=document.createElement("button"),n=e.is_active!==!1;t.className=`model-card${e.id===this.selectedModelId?" selected":""}${n?"":" disabled"}`;let i=this.getStatusDotColor(e);t.innerHTML=`<span class="status-dot" style="background:${i}"></span><span class="model-name">${this.escapeHtml(e.name)}</span>`,t.addEventListener("click",()=>this.handleSelectModel(e)),this.modelGrid.appendChild(t)}))}handleSelectModel(e){if(this.selectedModelId=e.id,e.is_active!==!1){this.callbacks.onModelChange(e.id);try{localStorage.setItem("storvia_model_id",e.id)}catch{}}let t=this.getFilteredModels();this.modelGrid&&this.modelGrid.querySelectorAll(".model-card").forEach((n,i)=>{n.classList.toggle("selected",t[i].id===this.selectedModelId)}),this.renderModelDetail()}renderModelDetail(){if(!this.modelDetail)return;let e=this.models.find(r=>r.id===this.selectedModelId);if(!e){this.modelDetail.style.display="none";return}this.modelDetail.style.display="block";let t=this.getStatusClass(e),n=this.getStatusText(e),i=this.getCreditsRange(e),s=e.description||"";this.modelDetail.innerHTML=`
676
+ `,Q='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M18 6L6 18M6 6l12 12"/></svg>',ee='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 2v6h-6M3 12a9 9 0 0 1 15-6.7L21 8M3 22v-6h6M21 12a9 9 0 0 1-15 6.7L3 16"/></svg>',te='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="spin"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',ne='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',ie='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>',N='<svg class="check" viewBox="0 0 24 24" fill="none" stroke="#8246FF" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>',m=48,u=16,se=5,y=class{constructor(e){this.selectedModelId="";this.models=[];this.settings={temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.activeTab="model";this.selectedCategory=null;this.hasWorldUpdate=!1;this.fabDot=null;this.syncHint=null;this.fabX=0;this.fabY=0;this.fab=null;this.panel=null;this.modelTabBtn=null;this.settingsTabBtn=null;this.modelBody=null;this.settingsBody=null;this.footer=null;this.modelGrid=null;this.modelDetail=null;this.tempValueEl=null;this.segmentBtns=[];this.langDropdown=null;this.langOptions=[];this.langArrow=null;this.langDropdownOpen=!1;this.noteCounter=null;this.saveBtn=null;this.syncBtn=null;this.syncState="idle";this.dragStartX=0;this.dragStartY=0;this.dragOffsetX=0;this.dragOffsetY=0;this.dragMoved=!1;this.dragging=!1;this.handlePointerDown=e=>{this.fab&&(e.preventDefault(),this.dragStartX=e.clientX,this.dragStartY=e.clientY,this.dragOffsetX=e.clientX-this.fabX,this.dragOffsetY=e.clientY-this.fabY,this.dragMoved=!1,this.dragging=!0,this.fab.setPointerCapture(e.pointerId),this.fab.addEventListener("pointermove",this.handlePointerMove),this.fab.addEventListener("pointerup",this.handlePointerUp),this.fab.addEventListener("pointercancel",this.handlePointerUp))};this.handlePointerMove=e=>{if(!this.dragging)return;let t=e.clientX-this.dragStartX,n=e.clientY-this.dragStartY;!this.dragMoved&&Math.hypot(t,n)>se&&(this.dragMoved=!0,this.fab?.classList.add("dragging"),this.closePanel()),this.dragMoved&&(this.fabX=e.clientX-this.dragOffsetX,this.fabY=e.clientY-this.dragOffsetY,this.applyHostPosition())};this.handlePointerUp=e=>{if(!this.fab)return;this.fab.removeEventListener("pointermove",this.handlePointerMove),this.fab.removeEventListener("pointerup",this.handlePointerUp),this.fab.removeEventListener("pointercancel",this.handlePointerUp);try{this.fab.releasePointerCapture(e.pointerId)}catch{}if(this.dragging=!1,!this.dragMoved){this.togglePanel();return}this.fab.classList.remove("dragging");let n=this.fabX+m/2<window.innerWidth/2;this.fabX=n?u:window.innerWidth-m-u,this.fabY=Math.max(u,Math.min(window.innerHeight-m-u,this.fabY)),this.fab&&(this.fab.style.transition="left 0.25s cubic-bezier(0.32, 0.72, 0, 1), top 0.25s cubic-bezier(0.32, 0.72, 0, 1), transform 0.2s, box-shadow 0.2s"),this.applyHostPosition(),setTimeout(()=>{this.fab&&(this.fab.style.transition="")},260)};this.handleResize=()=>{this.fabX=Math.max(u,Math.min(window.innerWidth-m-u,this.fabX)),this.fabY=Math.max(u,Math.min(window.innerHeight-m-u,this.fabY)),this.applyHostPosition()};this.handleDocClick=e=>{this.host.contains(e.target)||(this.closePanel(),this.closeLangDropdown())};this.savedBodyOverflow=null;this.callbacks=e,this.host=document.createElement("div"),this.host.id="storvia-settings",this.shadowRoot=this.host.attachShadow({mode:"closed"})}mount(e,t,n,i=!1){this.models=e,this.selectedModelId=t,this.settings={...n},this.hasWorldUpdate=i,this.fabX=window.innerWidth-m-u,this.fabY=window.innerHeight-m-u,document.body.appendChild(this.host),this.render(),this.applyHostPosition(),window.addEventListener("resize",this.handleResize),document.addEventListener("click",this.handleDocClick)}unmount(){window.removeEventListener("resize",this.handleResize),document.removeEventListener("click",this.handleDocClick),this.host.remove()}getSelectedModelId(){return this.selectedModelId}getSettings(){return{...this.settings}}render(){let e=document.createElement("style");e.textContent=J;let t=document.createElement("div");t.className="fab-wrap";let n=document.createElement("div");n.className="fab",n.title="\u6E38\u620F\u8BBE\u7F6E";let i=document.createElement("img");i.src=Z,i.alt="Storvia",n.appendChild(i),this.fab=n;let s=document.createElement("div");s.className=`fab-dot${this.hasWorldUpdate?" visible":""}`,this.fabDot=s,t.appendChild(n),t.appendChild(s);let r=document.createElement("div");r.className="panel",this.panel=r;let a=document.createElement("div");a.className="panel-header";let l=document.createElement("h2");l.className="panel-title",l.textContent="\u6E38\u620F\u8BBE\u7F6E";let p=document.createElement("button");p.className="close-btn",p.innerHTML=Q,p.addEventListener("click",()=>this.closePanel()),a.appendChild(l),a.appendChild(p),r.appendChild(a);let d=document.createElement("div");d.className="tabs",this.modelTabBtn=this.createTabBtn("model","\u6A21\u578B\u9009\u62E9"),this.settingsTabBtn=this.createTabBtn("settings","\u6E38\u620F\u8BBE\u7F6E"),this.models.length===0&&(this.activeTab="settings",this.modelTabBtn.style.display="none"),d.appendChild(this.modelTabBtn),d.appendChild(this.settingsTabBtn),r.appendChild(d);let c=document.createElement("div");c.className="panel-body",this.modelBody=this.buildModelTab(),this.settingsBody=this.buildSettingsTab(),c.appendChild(this.modelBody),c.appendChild(this.settingsBody),r.appendChild(c);let f=document.createElement("div");f.className="panel-footer";let g=document.createElement("button");g.className="btn btn-save",g.textContent="\u4FDD\u5B58",this.saveBtn=g,g.addEventListener("click",()=>this.handleSave()),f.appendChild(g),this.footer=f,r.appendChild(f),n.addEventListener("pointerdown",this.handlePointerDown);let v=document.createElement("div");v.appendChild(r),v.appendChild(t),this.shadowRoot.appendChild(e),this.shadowRoot.appendChild(v),this.applyTab()}createTabBtn(e,t){let n=document.createElement("button");return n.className=`tab-btn${this.activeTab===e?" active":""}`,n.textContent=t,n.addEventListener("click",()=>{this.activeTab=e,this.applyTab()}),n}applyTab(){this.modelTabBtn&&this.modelTabBtn.classList.toggle("active",this.activeTab==="model"),this.settingsTabBtn&&this.settingsTabBtn.classList.toggle("active",this.activeTab==="settings"),this.modelBody&&(this.modelBody.style.display=this.activeTab==="model"?"block":"none"),this.settingsBody&&(this.settingsBody.style.display=this.activeTab==="settings"?"block":"none"),this.footer&&(this.footer.style.display=this.activeTab==="settings"?"flex":"none")}buildModelTab(){let e=document.createElement("div"),t=this.getCategories();if(t.length>0){let s=document.createElement("div");s.className="category-tabs";let r=(a,l)=>{let p=document.createElement("button");return p.className=`category-tab${this.selectedCategory===l?" active":""}`,p.textContent=a,p.addEventListener("click",()=>{this.selectedCategory=l,s.querySelectorAll(".category-tab").forEach(d=>d.classList.remove("active")),p.classList.add("active"),this.renderModelGrid()}),p};s.appendChild(r("\u5168\u90E8",null)),t.forEach(a=>s.appendChild(r(a,a))),e.appendChild(s)}let n=document.createElement("div");n.className="models-grid",this.modelGrid=n,e.appendChild(n);let i=document.createElement("div");return i.className="model-detail",i.style.display="none",this.modelDetail=i,e.appendChild(i),this.renderModelGrid(),this.renderModelDetail(),e}getCategories(){let e=new Set;return this.models.forEach(t=>{t.category&&e.add(t.category)}),Array.from(e)}getFilteredModels(){return this.selectedCategory?this.models.filter(e=>e.category===this.selectedCategory):this.models}renderModelGrid(){this.modelGrid&&(this.modelGrid.innerHTML="",this.getFilteredModels().forEach(e=>{let t=document.createElement("button"),n=e.is_active!==!1;t.className=`model-card${e.id===this.selectedModelId?" selected":""}${n?"":" disabled"}`;let i=this.getStatusDotColor(e);t.innerHTML=`<span class="status-dot" style="background:${i}"></span><span class="model-name">${this.escapeHtml(e.name)}</span>`,t.addEventListener("click",()=>this.handleSelectModel(e)),this.modelGrid.appendChild(t)}))}handleSelectModel(e){if(this.selectedModelId=e.id,e.is_active!==!1){this.callbacks.onModelChange(e.id);try{localStorage.setItem("storvia_model_id",e.id)}catch{}}let t=this.getFilteredModels();this.modelGrid&&this.modelGrid.querySelectorAll(".model-card").forEach((n,i)=>{n.classList.toggle("selected",t[i].id===this.selectedModelId)}),this.renderModelDetail()}renderModelDetail(){if(!this.modelDetail)return;let e=this.models.find(r=>r.id===this.selectedModelId);if(!e){this.modelDetail.style.display="none";return}this.modelDetail.style.display="block";let t=this.getStatusClass(e),n=this.getStatusText(e),i=this.getCreditsRange(e),s=e.description||"";this.modelDetail.innerHTML=`
677
677
  <div class="detail-header">
678
678
  <span class="detail-title">${this.escapeHtml(e.name)}</span>
679
679
  <span class="detail-status ${t}">${n}</span>
@@ -681,9 +681,9 @@
681
681
  ${i?`<div class="detail-credits">
682
682
  <span class="credits-label">\u6D88\u8017</span>
683
683
  <span class="credits-value">${i}</span>
684
- <img class="credits-icon" src="${X}" alt="credits" />
684
+ <img class="credits-icon" src="${q}" alt="credits" />
685
685
  <span class="credits-unit">/\u6B21</span>
686
686
  </div>`:""}
687
687
  ${s?`<div class="detail-description">${this.escapeHtml(s)}</div>`:""}
688
- `}getStatusDotColor(e){if(e.is_active===!1)return"#6b7280";let t=e.success_rate??100;return t>=95?"#10b981":t>=80?"#3b82f6":t>=60?"#eab308":"#f97316"}getStatusClass(e){if(e.is_active===!1)return"inactive";let t=e.success_rate??100;return t>=95?"excellent":t>=80?"good":t>=60?"normal":"crowded"}getStatusText(e){if(e.is_active===!1)return"\u505C\u7528";let t=e.success_rate??100;return t>=95?"\u6D41\u7545":t>=80?"\u826F\u597D":t>=60?"\u4E00\u822C":"\u62E5\u6324"}getCreditsRange(e){let t=e.credits_config?.min??0,n=e.credits_config?.max??0;return t===0&&n===0?"":t===n?`${t}`:`${t}\uFF5E${n}`}buildSettingsTab(){let e=document.createElement("div"),t=document.createElement("div");return t.className="form-stack",t.appendChild(this.buildTemperatureSection()),t.appendChild(this.buildReplyLengthSection()),t.appendChild(this.buildReplyLanguageSection()),t.appendChild(this.buildNoteSection()),t.appendChild(this.buildSyncSection()),e.appendChild(t),e}buildTemperatureSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label";let n=document.createElement("span");n.textContent="\u6E29\u5EA6";let i=document.createElement("span");i.className="temperature-value",i.textContent=this.settings.temperature.toFixed(1),this.tempValueEl=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("p");s.className="form-hint",s.textContent="\u66F4\u4F4E\u8BA9 AI \u56DE\u590D\u66F4\u7A33\u5B9A\u7406\u667A\uFF0C\u66F4\u9AD8\u8BA9\u56DE\u590D\u66F4\u5177\u591A\u6837\u6027",e.appendChild(s);let r=document.createElement("input");r.type="range",r.className="slider",r.min="0",r.max="1",r.step="0.1",r.value=String(this.settings.temperature),r.addEventListener("input",()=>{let a=parseFloat(r.value);this.settings.temperature=a,this.tempValueEl&&(this.tempValueEl.textContent=a.toFixed(1))}),e.appendChild(r);let o=document.createElement("div");return o.className="slider-labels",o.innerHTML="<span>\u7CBE\u786E</span><span>\u521B\u610F</span>",e.appendChild(o),e}buildReplyLengthSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label",t.textContent="\u56DE\u590D\u957F\u5EA6",e.appendChild(t);let n=document.createElement("div");return n.className="segment-control",this.segmentBtns=[],N.forEach(i=>{let s=document.createElement("button");s.className=`segment-button${i.value===this.settings.reply_length?" active":""}`,s.textContent=i.label,s.addEventListener("click",()=>{this.settings.reply_length=i.value,this.segmentBtns.forEach((r,o)=>{r.classList.toggle("active",N[o].value===i.value)})}),this.segmentBtns.push(s),n.appendChild(s)}),e.appendChild(n),e}buildReplyLanguageSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label",t.textContent="\u56DE\u590D\u8BED\u8A00",e.appendChild(t);let n=document.createElement("div");n.className="custom-select";let i=document.createElement("button");i.className="select-trigger";let s=document.createElement("span");s.textContent=R.find(a=>a.value===this.settings.reply_language)?.label||"";let r=document.createElement("span");r.className="select-arrow",r.textContent="\u25BE",this.langArrow=r,i.appendChild(s),i.appendChild(r),i.addEventListener("click",a=>{a.stopPropagation(),this.toggleLangDropdown()}),n.appendChild(i);let o=document.createElement("div");return o.className="select-dropdown",this.langDropdown=o,this.langOptions=[],R.forEach(a=>{let c=document.createElement("button");c.className=`select-option${a.value===this.settings.reply_language?" active":""}`,c.innerHTML=`<span>${a.label}</span>${a.value===this.settings.reply_language?D:""}`,c.addEventListener("click",()=>{this.settings.reply_language=a.value,s.textContent=a.label,this.langOptions.forEach((d,h)=>{d.classList.toggle("active",R[h].value===a.value),d.innerHTML=`<span>${R[h].label}</span>${R[h].value===a.value?D:""}`}),this.closeLangDropdown()}),this.langOptions.push(c),o.appendChild(c)}),n.appendChild(o),e.appendChild(n),e}toggleLangDropdown(){this.langDropdownOpen?this.closeLangDropdown():this.openLangDropdown()}openLangDropdown(){this.langDropdownOpen=!0,this.langDropdown?.classList.add("open"),this.langArrow&&(this.langArrow.textContent="\u25B4")}closeLangDropdown(){this.langDropdownOpen=!1,this.langDropdown?.classList.remove("open"),this.langArrow&&(this.langArrow.textContent="\u25BE")}buildNoteSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label";let n=document.createElement("span");n.textContent="\u5907\u6CE8";let i=document.createElement("span");i.className="char-count",i.textContent=`${this.settings.player_note.length}/50`,this.noteCounter=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("p");s.className="form-hint",s.textContent="\u5199\u4E0B\u4F60\u5BF9\u8FD9\u4E2A\u6E38\u620F\u7684\u5907\u6CE8\uFF0C\u4F1A\u663E\u793A\u5728\u5B58\u6863\u5217\u8868",e.appendChild(s);let r=document.createElement("textarea");return r.className="player-note-input",r.placeholder="\u5907\u6CE8",r.maxLength=50,r.rows=2,r.value=this.settings.player_note,r.addEventListener("input",()=>{this.settings.player_note=r.value,this.noteCounter&&(this.noteCounter.textContent=`${r.value.length}/50`)}),e.appendChild(r),e}buildSyncSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label",t.textContent="\u540C\u6B65\u6E38\u620F\u8BBE\u5B9A",e.appendChild(t);let n=document.createElement("p");n.className=`sync-hint${this.hasWorldUpdate?" visible":""}`,n.textContent="\u26A0 \u4F5C\u8005\u5DF2\u66F4\u65B0\u6E38\u620F\u5185\u5BB9\uFF0C\u5EFA\u8BAE\u70B9\u51FB\u540C\u6B65",this.syncHint=n,e.appendChild(n);let i=document.createElement("p");i.className="form-hint",i.textContent="\u5C06\u6700\u65B0\u6E38\u620F\u8BBE\u5B9A\u548C\u5F00\u5E55\u5C0F\u5267\u573A\u540C\u6B65\u5230\u5F53\u524D\u5BF9\u8BDD",e.appendChild(i);let s=document.createElement("button");return s.className="btn btn-sync",this.syncBtn=s,this.renderSyncBtn(),s.addEventListener("click",async()=>{if(this.syncState!=="loading"){this.setSyncState("loading");try{await this.callbacks.onSync(),this.setSyncState("success"),this.hasWorldUpdate=!1,this.fabDot&&this.fabDot.classList.remove("visible"),this.syncHint&&this.syncHint.classList.remove("visible"),setTimeout(()=>this.setSyncState("idle"),3e3)}catch{this.setSyncState("error"),setTimeout(()=>this.setSyncState("idle"),4e3)}}}),e.appendChild(s),e}setSyncState(e){this.syncState=e,this.renderSyncBtn()}renderSyncBtn(){if(!this.syncBtn)return;let e=this.syncState,t={idle:Z,loading:q,success:J,error:Q},n={idle:"\u540C\u6B65\u6700\u65B0\u8BBE\u5B9A",loading:"\u540C\u6B65\u4E2D...",success:"\u5DF2\u540C\u6B65",error:"\u540C\u6B65\u5931\u8D25"};this.syncBtn.className=`btn btn-sync${e==="success"||e==="error"?` ${e}`:""}`,this.syncBtn.disabled=e==="loading",this.syncBtn.innerHTML=`${t[e]}<span>${n[e]}</span>`}async handleSave(){if(!(!this.saveBtn||this.saveBtn.disabled)){this.saveBtn.disabled=!0,this.saveBtn.innerHTML='<span class="spinner"></span>\u4FDD\u5B58\u4E2D...';try{await this.callbacks.onSettingsChange({temperature:this.settings.temperature,reply_length:this.settings.reply_length,reply_language:this.settings.reply_language,player_note:this.settings.player_note}),this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1)}catch{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58\u5931\u8D25",setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1)},2e3))}}}escapeHtml(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}applyHostPosition(){this.host.style.left=`${this.fabX}px`,this.host.style.top=`${this.fabY}px`,this.host.style.right="auto",this.host.style.bottom="auto",this.applyPanelPosition()}isMobile(){return window.innerWidth<=768}applyPanelPosition(){if(!this.panel)return;if(this.isMobile()){this.panel.style.left="",this.panel.style.right="",this.panel.style.top="",this.panel.style.bottom="";return}let e=this.fabX+m/2<window.innerWidth/2,t=380;e?(this.panel.style.left="0",this.panel.style.right="auto"):(this.panel.style.left=`${m-t}px`,this.panel.style.right="auto"),this.fabY>500?(this.panel.style.bottom=`${m+8}px`,this.panel.style.top="auto"):(this.panel.style.top=`${m+8}px`,this.panel.style.bottom="auto")}togglePanel(){this.panel&&(this.panel.classList.contains("open")?this.closePanel():(this.applyPanelPosition(),this.panel.classList.add("open"),requestAnimationFrame(()=>{this.panel?.classList.contains("open")&&(this.fab&&(this.fab.style.visibility="hidden"),this.fabDot&&(this.fabDot.style.visibility="hidden"))}),this.isMobile()&&this.lockBodyScroll()))}closePanel(){this.panel&&this.panel.classList.remove("open"),this.fab&&(this.fab.style.visibility="visible"),this.fabDot&&(this.fabDot.style.visibility="visible"),this.unlockBodyScroll()}lockBodyScroll(){this.savedBodyOverflow===null&&(this.savedBodyOverflow=document.body.style.overflow||"",document.body.style.overflow="hidden")}unlockBodyScroll(){this.savedBodyOverflow!==null&&(document.body.style.overflow=this.savedBodyOverflow,this.savedBodyOverflow=null)}};var w=class{constructor(e,t,n,i,s=!1,r){this.http=e;this.getGameId=t;this.getConversationId=n;this.getModelId=i;this.isPreview=s;this.previewConfig=r}updatePreviewConfig(e){this.previewConfig=e}async send(e){if(this.isPreview)return this.sendPreview(e);let t={game_id:this.getGameId(),conversation_id:this.getConversationId(),model_id:this.getModelId(),message:e.message,topic:e.topic,scene_key:e.scene_key,stream:e.stream??!1};if(e.stream){await this.http.stream("/chat",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/chat",t)}async save(e){return this.isPreview?{id:`preview-${Date.now()}`}:this.http.post("/messages/save",{conversation_id:this.getConversationId(),role:e.role,content:e.content,topic:e.topic})}async generate(e){if(this.isPreview)return this.sendPreview({message:"",topic:e.topic,scene_key:e.scene_key,stream:e.stream,onChunk:e.onChunk,onDone:e.onDone});let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,scene_key:e.scene_key,stream:e.stream??!1,save:e.save??!0};if(e.stream){await this.http.stream("/generate",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/generate",t)}async retry(e={}){if(this.isPreview)throw new Error("Retry is not supported in preview mode");let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,scene_key:e.scene_key,stream:e.stream??!1};if(e.stream){await this.http.stream("/retry",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/retry",t)}async sendPreview(e){let t={model_id:this.getModelId(),message:e.message,topic:e.topic,scene_key:e.scene_key,history_messages:[]};if(this.previewConfig?t.prompt_config=this.previewConfig:t.game_id=this.getGameId(),e.stream){await this.http.stream("/preview",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}let n="";return await this.http.stream("/preview",t,i=>{n+=i},()=>{}),{id:"",content:n}}};var _=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){return this.isPreview?{...this.mem[e]||{}}:this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,t)}},C=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];this.state=new _(e,t,n)}async list(){return this.isPreview?this.mem.map(e=>({name:e.name,avatar:e.avatar,...e.gender?{gender:e.gender}:{}})):this.http.get(`/conversations/${this.getConversationId()}/characters`)}async get(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:t?.name||e,avatar:t?.avatar,...t?.gender?{gender:t.gender}:{}}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async add(e){if(this.isPreview){this.mem.push(e);return}await this.http.post(`/conversations/${this.getConversationId()}/characters`,e)}async update(e,t){if(this.isPreview){let n=this.mem.find(i=>i.name===e);n&&Object.assign(n,t);return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`,t)}async remove(e){if(this.isPreview){this.mem=this.mem.filter(t=>t.name!==e);return}await this.http.delete(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async detail(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:e,avatar:t?.avatar,state:await this.state.get(e)}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/detail`)}async setPriority(e,t){let n=Math.max(0,Math.min(100,Math.round(t)));this.isPreview||await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,{priority:n})}};var x=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[]}async list(){return this.isPreview?[...this.mem]:this.http.get(`/conversations/${this.getConversationId()}/relationships`)}async get(e,t){if(this.isPreview){let n=this.mem.find(i=>i.from===e&&i.to===t);if(n)return{...n};throw new Error("Relationship not found")}return this.http.get(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/relationships`,e)}async update(e,t,n){if(this.isPreview){let i=this.mem.find(s=>s.from===e&&s.to===t);i?Object.assign(i,n):this.mem.push({from:e,to:t,...n});return}await this.http.patch(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,n)}async remove(e,t){if(this.isPreview){this.mem=this.mem.filter(n=>!(n.from===e&&n.to===t));return}await this.http.delete(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var I=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async list(e){if(this.isPreview){if(e!==void 0)return{...this.mem[e]||{}};let t={};for(let[n,i]of Object.entries(this.mem))t[n]={...i};return t}return e!==void 0?this.http.get(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(e)}`):this.http.get(`/conversations/${this.getConversationId()}/inventory`)}async add(e){let{group:t,name:n,count:i=1,desc:s,iconUrl:r}=e;if(this.isPreview){if(!this.mem[t])throw new Error(`Group "${t}" does not exist`);if(n in this.mem[t])throw new Error(`Item "${n}" already exists in group "${t}"`);let o={count:i};s!==void 0&&(o.desc=s),r!==void 0&&(o.iconUrl=r),this.mem[t][n]=o;return}await this.http.post(`/conversations/${this.getConversationId()}/inventory`,{group:t,name:n,count:i,desc:s,iconUrl:r})}async update(e){let{group:t,name:n,...i}=e;if(this.isPreview){let s=this.mem[t];if(!s||!(n in s))throw new Error(`Item "${t}/${n}" not found`);Object.assign(s[n],i);return}await this.http.patch(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,i)}async remove(e){let{group:t,name:n}=e;if(this.isPreview){this.mem[t]&&delete this.mem[t][n];return}await this.http.delete(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(t)}/${encodeURIComponent(n)}`)}async move(e){let{fromGroup:t,toGroup:n,name:i,newName:s}=e;if(this.isPreview){let r=this.mem[t];if(!r||!(i in r))throw new Error(`Source item "${t}/${i}" not found`);if(!this.mem[n])throw new Error(`Target group "${n}" does not exist`);let o=s||i;if(t===n&&o===i)return;if(o in this.mem[n])throw new Error(`Item "${o}" already exists in target group`);this.mem[n][o]=r[i],delete r[i];return}await this.http.post(`/conversations/${this.getConversationId()}/inventory/move`,{fromGroup:t,toGroup:n,name:i,newName:s})}async ensureGroup(e){if(this.isPreview){this.mem[e]||(this.mem[e]={});return}await this.http.post(`/conversations/${this.getConversationId()}/inventory/groups/${encodeURIComponent(e)}`,{})}async removeGroup(e,t){let n=t?.cascade??!1;if(this.isPreview){let s=this.mem[e];if(s&&Object.keys(s).length>0&&!n)throw new Error(`Group "${e}" is not empty, pass cascade: true to force delete`);delete this.mem[e];return}let i=n?"?cascade=true":"";await this.http.delete(`/conversations/${this.getConversationId()}/inventory/groups/${encodeURIComponent(e)}${i}`)}};var E=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(){return this.isPreview?{...this.mem}:this.http.get(`/conversations/${this.getConversationId()}/world`)}async update(e){if(this.isPreview){Object.assign(this.mem,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/world`,e)}};var O=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e?{...this.mem[e]||{}}:{...this.mem};let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/player/state`,t)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/player/state`,{group:e,values:t})}},S=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.memPersona={name:""};this.state=new O(e,t,n)}async get(){return this.isPreview?{...this.memPersona}:this.http.get(`/conversations/${this.getConversationId()}/player`)}async update(e){if(this.isPreview){Object.assign(this.memPersona,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/player`,e)}};var k=class{constructor(e,t,n=!1){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={}}async get(e){if(this.isPreview)return e!==void 0?this.mem[e]:{...this.mem};let t=await this.http.get(`/conversations/${this.getConversationId()}/custom`);return e!==void 0?t[e]:t}async set(e){if(this.isPreview){for(let[t,n]of Object.entries(e))typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof this.mem[t]=="object"&&this.mem[t]!==null?this.mem[t]={...this.mem[t],...n}:this.mem[t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom`,e)}async delete(e){if(this.isPreview){delete this.mem[e];return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}`)}async setGroupField(e,t,n){if(this.isPreview){(!this.mem[e]||typeof this.mem[e]!="object")&&(this.mem[e]={}),this.mem[e][t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{value:n})}async deleteGroupField(e,t){if(this.isPreview){if(typeof this.mem[e]=="object"&&this.mem[e]!==null){let n=this.mem[e];delete n[t]}return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var B="/functions/v1/world-engine/v1",te="https://api.storvia.ai";function ne(){return window.__STORVIA__||{}}function ie(l=5e3){let e=ne();return e.apiBase?Promise.resolve(e):new Promise((t,n)=>{let i=setTimeout(()=>{window.removeEventListener("message",s),n(new p("NOT_INITIALIZED","Timed out waiting for __STORVIA__ config from parent frame."))},l);function s(r){let o=null;if(r.data?.type==="storvia-init"&&r.data.apiBase?o={apiBase:r.data.apiBase,gameId:r.data.gameId,accessToken:r.data.accessToken}:r.data?.type==="storvia-preview-init"&&r.data.config&&(o=r.data.config),o&&o.apiBase){clearTimeout(i),window.removeEventListener("message",s);let a=window;a.__STORVIA__=o,t(o)}}window.addEventListener("message",s)})}var T=class{constructor(){this.baseUrl="";this.gameId="";this.conversationId="";this.modelId="";this.accessToken="";this.initialized=!1;this.isPreview=!1;this.previewConfig=void 0}async init(){if(this.initialized)return;let e=await ie(),t=e.apiBase;if(!t)throw new p("NOT_INITIALIZED","window.__STORVIA__.apiBase is not set. The platform must inject it before SDK init.");if(this.baseUrl=`${t}${B}`,this.isPreview=!!e.preview,this.previewConfig=e.previewConfig,!e.gameId)throw new p("GAME_NOT_FOUND","window.__STORVIA__.gameId is not set. The platform must inject it before SDK init.");if(this.gameId=e.gameId,!e.accessToken)throw new p("UNAUTHORIZED","window.__STORVIA__.accessToken is not set. The platform must inject the user token before SDK init.");if(this.accessToken=e.accessToken,this.http=new P(this.baseUrl,this.accessToken,!!e.debug),this.isPreview){this.conversationId="00000000-0000-0000-0000-000000000000";let d=await this.fetchModels();this.modelId=e.selectedModelId||d[0]?.id||"",this.settingsSheet=new y({onModelChange:f=>{this.modelId=f},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),d.length>0&&this.settingsSheet.mount(d,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let h=()=>this.gameId,g=()=>this.conversationId,v=()=>this.modelId;this.chat=new w(this.http,h,g,v,!0,this.previewConfig),this.characters=new C(this.http,g,!0),this.relationships=new x(this.http,g,!0),this.inventory=new I(this.http,g,!0),this.world=new E(this.http,g,!0),this.player=new S(this.http,g,!0),this.custom=new k(this.http,g,!0),this.initialized=!0,this.listenForPreviewMessages();return}let[n,i]=await Promise.all([this.authenticate(),this.fetchModels()]);this.conversationId=n.conversationId;let s=this.getSavedModelId();this.modelId=s&&i.some(d=>d.id===s)?s:i[0]?.id||"";let r=n.settings||{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.settingsSheet=new y({onModelChange:d=>{this.modelId=d},onSettingsChange:d=>this.saveSettings(d),onSync:()=>this.syncSettings()}),this.settingsSheet.mount(i,this.modelId,r,n.hasWorldUpdate??!1);let o=()=>this.gameId,a=()=>this.conversationId,c=()=>this.modelId;this.chat=new w(this.http,o,a,c),this.characters=new C(this.http,a),this.relationships=new x(this.http,a),this.inventory=new I(this.http,a),this.world=new E(this.http,a),this.player=new S(this.http,a),this.custom=new k(this.http,a),this.initialized=!0}listenForPreviewMessages(){window.addEventListener("message",e=>{!e.data||e.data.type!=="storvia-preview"||(e.data.action==="set-model"&&(this.modelId=e.data.modelId||""),e.data.action==="update-config"&&(this.previewConfig=e.data.previewConfig,this.chat&&this.chat.updatePreviewConfig(this.previewConfig)))})}async saveSettings(e){await this.http.patch("/settings",{conversation_id:this.conversationId,...e})}async syncSettings(){await this.http.post("/sync",{conversation_id:this.conversationId})}async fetchModels(){try{return await this.http.get("/models")}catch{}return[]}async authenticate(){let e=await fetch(`${this.baseUrl}/auth`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.accessToken}`},body:JSON.stringify({game_id:this.gameId})});if(!e.ok)throw e.status===401?new p("UNAUTHORIZED","User not authenticated"):e.status===404?new p("GAME_NOT_FOUND","Game not found or not published"):new p("INTERNAL_ERROR",`Auth failed: HTTP ${e.status}`);let t=await e.json();return t.data??t}getSavedModelId(){try{return localStorage.getItem("storvia_model_id")||""}catch{return""}}async initDev(e){if(this.initialized)return;this.baseUrl=`${te}${B}`,this.gameId=e.gameId,this.isPreview=!0,this.http=new P(this.baseUrl,"",!1,e.apiKey);let t=await this.fetchModels();this.modelId=t[0]?.id||"",this.conversationId="00000000-0000-0000-0000-000000000000",this.settingsSheet=new y({onModelChange:r=>{this.modelId=r},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),t.length>0&&this.settingsSheet.mount(t,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let n=()=>this.gameId,i=()=>this.conversationId,s=()=>this.modelId;this.chat=new w(this.http,n,i,s,!0,void 0),this.characters=new C(this.http,i,!0),this.relationships=new x(this.http,i,!0),this.inventory=new I(this.http,i,!0),this.world=new E(this.http,i,!0),this.player=new S(this.http,i,!0),this.custom=new k(this.http,i,!0),this.initialized=!0}};async function H(l){let e=new T;return l?.dev?await e.initDev(l.dev):await e.init(),e}function $(l){return typeof l=="object"&&l!==null&&"value"in l&&"type"in l&&(l.type==="number"||l.type==="text")}function U(l){return $(l)?l.value:l}return V(se);})();
688
+ `}getStatusDotColor(e){if(e.is_active===!1)return"#6b7280";let t=e.success_rate??100;return t>=95?"#10b981":t>=80?"#3b82f6":t>=60?"#eab308":"#f97316"}getStatusClass(e){if(e.is_active===!1)return"inactive";let t=e.success_rate??100;return t>=95?"excellent":t>=80?"good":t>=60?"normal":"crowded"}getStatusText(e){if(e.is_active===!1)return"\u505C\u7528";let t=e.success_rate??100;return t>=95?"\u6D41\u7545":t>=80?"\u826F\u597D":t>=60?"\u4E00\u822C":"\u62E5\u6324"}getCreditsRange(e){let t=e.credits_config?.min??0,n=e.credits_config?.max??0;return t===0&&n===0?"":t===n?`${t}`:`${t}\uFF5E${n}`}buildSettingsTab(){let e=document.createElement("div"),t=document.createElement("div");return t.className="form-stack",t.appendChild(this.buildTemperatureSection()),t.appendChild(this.buildReplyLengthSection()),t.appendChild(this.buildReplyLanguageSection()),t.appendChild(this.buildNoteSection()),t.appendChild(this.buildSyncSection()),e.appendChild(t),e}buildTemperatureSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label";let n=document.createElement("span");n.textContent="\u6E29\u5EA6";let i=document.createElement("span");i.className="temperature-value",i.textContent=this.settings.temperature.toFixed(1),this.tempValueEl=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("p");s.className="form-hint",s.textContent="\u66F4\u4F4E\u8BA9 AI \u56DE\u590D\u66F4\u7A33\u5B9A\u7406\u667A\uFF0C\u66F4\u9AD8\u8BA9\u56DE\u590D\u66F4\u5177\u591A\u6837\u6027",e.appendChild(s);let r=document.createElement("input");r.type="range",r.className="slider",r.min="0",r.max="1",r.step="0.1",r.value=String(this.settings.temperature),r.addEventListener("input",()=>{let l=parseFloat(r.value);this.settings.temperature=l,this.tempValueEl&&(this.tempValueEl.textContent=l.toFixed(1))}),e.appendChild(r);let a=document.createElement("div");return a.className="slider-labels",a.innerHTML="<span>\u7CBE\u786E</span><span>\u521B\u610F</span>",e.appendChild(a),e}buildReplyLengthSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label",t.textContent="\u56DE\u590D\u957F\u5EA6",e.appendChild(t);let n=document.createElement("div");return n.className="segment-control",this.segmentBtns=[],D.forEach(i=>{let s=document.createElement("button");s.className=`segment-button${i.value===this.settings.reply_length?" active":""}`,s.textContent=i.label,s.addEventListener("click",()=>{this.settings.reply_length=i.value,this.segmentBtns.forEach((r,a)=>{r.classList.toggle("active",D[a].value===i.value)})}),this.segmentBtns.push(s),n.appendChild(s)}),e.appendChild(n),e}buildReplyLanguageSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label",t.textContent="\u56DE\u590D\u8BED\u8A00",e.appendChild(t);let n=document.createElement("div");n.className="custom-select";let i=document.createElement("button");i.className="select-trigger";let s=document.createElement("span");s.textContent=k.find(l=>l.value===this.settings.reply_language)?.label||"";let r=document.createElement("span");r.className="select-arrow",r.textContent="\u25BE",this.langArrow=r,i.appendChild(s),i.appendChild(r),i.addEventListener("click",l=>{l.stopPropagation(),this.toggleLangDropdown()}),n.appendChild(i);let a=document.createElement("div");return a.className="select-dropdown",this.langDropdown=a,this.langOptions=[],k.forEach(l=>{let p=document.createElement("button");p.className=`select-option${l.value===this.settings.reply_language?" active":""}`,p.innerHTML=`<span>${l.label}</span>${l.value===this.settings.reply_language?N:""}`,p.addEventListener("click",()=>{this.settings.reply_language=l.value,s.textContent=l.label,this.langOptions.forEach((d,c)=>{d.classList.toggle("active",k[c].value===l.value),d.innerHTML=`<span>${k[c].label}</span>${k[c].value===l.value?N:""}`}),this.closeLangDropdown()}),this.langOptions.push(p),a.appendChild(p)}),n.appendChild(a),e.appendChild(n),e}toggleLangDropdown(){this.langDropdownOpen?this.closeLangDropdown():this.openLangDropdown()}openLangDropdown(){this.langDropdownOpen=!0,this.langDropdown?.classList.add("open"),this.langArrow&&(this.langArrow.textContent="\u25B4")}closeLangDropdown(){this.langDropdownOpen=!1,this.langDropdown?.classList.remove("open"),this.langArrow&&(this.langArrow.textContent="\u25BE")}buildNoteSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label";let n=document.createElement("span");n.textContent="\u5907\u6CE8";let i=document.createElement("span");i.className="char-count",i.textContent=`${this.settings.player_note.length}/50`,this.noteCounter=i,t.appendChild(n),t.appendChild(i),e.appendChild(t);let s=document.createElement("p");s.className="form-hint",s.textContent="\u5199\u4E0B\u4F60\u5BF9\u8FD9\u4E2A\u6E38\u620F\u7684\u5907\u6CE8\uFF0C\u4F1A\u663E\u793A\u5728\u5B58\u6863\u5217\u8868",e.appendChild(s);let r=document.createElement("textarea");return r.className="player-note-input",r.placeholder="\u5907\u6CE8",r.maxLength=50,r.rows=2,r.value=this.settings.player_note,r.addEventListener("input",()=>{this.settings.player_note=r.value,this.noteCounter&&(this.noteCounter.textContent=`${r.value.length}/50`)}),e.appendChild(r),e}buildSyncSection(){let e=document.createElement("div");e.className="form-group";let t=document.createElement("label");t.className="form-label",t.textContent="\u540C\u6B65\u6E38\u620F\u8BBE\u5B9A",e.appendChild(t);let n=document.createElement("p");n.className=`sync-hint${this.hasWorldUpdate?" visible":""}`,n.textContent="\u26A0 \u4F5C\u8005\u5DF2\u66F4\u65B0\u6E38\u620F\u5185\u5BB9\uFF0C\u5EFA\u8BAE\u70B9\u51FB\u540C\u6B65",this.syncHint=n,e.appendChild(n);let i=document.createElement("p");i.className="form-hint",i.textContent="\u5C06\u6700\u65B0\u6E38\u620F\u8BBE\u5B9A\u548C\u5F00\u5E55\u5C0F\u5267\u573A\u540C\u6B65\u5230\u5F53\u524D\u5BF9\u8BDD",e.appendChild(i);let s=document.createElement("button");return s.className="btn btn-sync",this.syncBtn=s,this.renderSyncBtn(),s.addEventListener("click",async()=>{if(this.syncState!=="loading"){this.setSyncState("loading");try{await this.callbacks.onSync(),this.setSyncState("success"),this.hasWorldUpdate=!1,this.fabDot&&this.fabDot.classList.remove("visible"),this.syncHint&&this.syncHint.classList.remove("visible"),setTimeout(()=>this.setSyncState("idle"),3e3)}catch{this.setSyncState("error"),setTimeout(()=>this.setSyncState("idle"),4e3)}}}),e.appendChild(s),e}setSyncState(e){this.syncState=e,this.renderSyncBtn()}renderSyncBtn(){if(!this.syncBtn)return;let e=this.syncState,t={idle:ee,loading:te,success:ne,error:ie},n={idle:"\u540C\u6B65\u6700\u65B0\u8BBE\u5B9A",loading:"\u540C\u6B65\u4E2D...",success:"\u5DF2\u540C\u6B65",error:"\u540C\u6B65\u5931\u8D25"};this.syncBtn.className=`btn btn-sync${e==="success"||e==="error"?` ${e}`:""}`,this.syncBtn.disabled=e==="loading",this.syncBtn.innerHTML=`${t[e]}<span>${n[e]}</span>`}async handleSave(){if(!(!this.saveBtn||this.saveBtn.disabled)){this.saveBtn.disabled=!0,this.saveBtn.innerHTML='<span class="spinner"></span>\u4FDD\u5B58\u4E2D...';try{await this.callbacks.onSettingsChange({temperature:this.settings.temperature,reply_length:this.settings.reply_length,reply_language:this.settings.reply_language,player_note:this.settings.player_note}),this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1)}catch{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58\u5931\u8D25",setTimeout(()=>{this.saveBtn&&(this.saveBtn.textContent="\u4FDD\u5B58",this.saveBtn.disabled=!1)},2e3))}}}escapeHtml(e){return e.replace(/[&<>"']/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"})[t])}applyHostPosition(){this.host.style.left=`${this.fabX}px`,this.host.style.top=`${this.fabY}px`,this.host.style.right="auto",this.host.style.bottom="auto",this.applyPanelPosition()}isMobile(){return window.innerWidth<=768}applyPanelPosition(){if(!this.panel)return;if(this.isMobile()){this.panel.style.left="",this.panel.style.right="",this.panel.style.top="",this.panel.style.bottom="";return}let e=this.fabX+m/2<window.innerWidth/2,t=380;e?(this.panel.style.left="0",this.panel.style.right="auto"):(this.panel.style.left=`${m-t}px`,this.panel.style.right="auto"),this.fabY>500?(this.panel.style.bottom=`${m+8}px`,this.panel.style.top="auto"):(this.panel.style.top=`${m+8}px`,this.panel.style.bottom="auto")}togglePanel(){this.panel&&(this.panel.classList.contains("open")?this.closePanel():(this.applyPanelPosition(),this.panel.classList.add("open"),requestAnimationFrame(()=>{this.panel?.classList.contains("open")&&(this.fab&&(this.fab.style.visibility="hidden"),this.fabDot&&(this.fabDot.style.visibility="hidden"))}),this.isMobile()&&this.lockBodyScroll()))}closePanel(){this.panel&&this.panel.classList.remove("open"),this.fab&&(this.fab.style.visibility="visible"),this.fabDot&&(this.fabDot.style.visibility="visible"),this.unlockBodyScroll()}lockBodyScroll(){this.savedBodyOverflow===null&&(this.savedBodyOverflow=document.body.style.overflow||"",document.body.style.overflow="hidden")}unlockBodyScroll(){this.savedBodyOverflow!==null&&(document.body.style.overflow=this.savedBodyOverflow,this.savedBodyOverflow=null)}};var w=class{constructor(e,t,n,i,s=!1,r){this.http=e;this.getGameId=t;this.getConversationId=n;this.getModelId=i;this.isPreview=s;this.previewConfig=r}updatePreviewConfig(e){this.previewConfig=e}async send(e){if(this.isPreview)return this.sendPreview(e);let t={game_id:this.getGameId(),conversation_id:this.getConversationId(),model_id:this.getModelId(),message:e.message,topic:e.topic,scene_key:e.scene_key,stream:e.stream??!1};if(e.stream){await this.http.stream("/chat",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/chat",t)}async save(e){return this.isPreview?{id:`preview-${Date.now()}`}:this.http.post("/messages/save",{conversation_id:this.getConversationId(),role:e.role,content:e.content,topic:e.topic})}async generate(e){if(this.isPreview)return this.sendPreview({message:"",topic:e.topic,scene_key:e.scene_key,stream:e.stream,onChunk:e.onChunk,onDone:e.onDone});let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,scene_key:e.scene_key,stream:e.stream??!1,save:e.save??!0};if(e.stream){await this.http.stream("/generate",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/generate",t)}async retry(e={}){if(this.isPreview)throw new Error("Retry is not supported in preview mode");let t={conversation_id:this.getConversationId(),model_id:this.getModelId(),topic:e.topic,scene_key:e.scene_key,stream:e.stream??!1};if(e.stream){await this.http.stream("/retry",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}return this.http.post("/retry",t)}async sendPreview(e){let t={model_id:this.getModelId(),message:e.message,topic:e.topic,scene_key:e.scene_key,history_messages:[]};if(this.previewConfig?t.prompt_config=this.previewConfig:t.game_id=this.getGameId(),e.stream){await this.http.stream("/preview",t,e.onChunk??(()=>{}),e.onDone??(()=>{}));return}let n="";return await this.http.stream("/preview",t,i=>{n+=i},()=>{}),{id:"",content:n}}};var O=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem={...i})}setInitial(e){this.mem=e?{...e}:{}}async get(e){return this.isPreview?{...this.mem[e]||{}}:this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,t)}},C=class{constructor(e,t,n=!1,i,s){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];i&&(this.mem=i.map(B)),this.state=new O(e,t,n,s)}setInitial(e,t){this.mem=e?e.map(B):[],this.state.setInitial(t)}async list(){return this.isPreview?this.mem.map(H):this.http.get(`/conversations/${this.getConversationId()}/characters`)}async get(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return t?H(t):{name:e}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async add(e){if(this.isPreview){this.mem.push({...e,isPreset:!1});return}await this.http.post(`/conversations/${this.getConversationId()}/characters`,e)}async update(e,t){if(this.isPreview){let n=this.mem.find(i=>i.name===e);n&&Object.assign(n,t);return}await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`,t)}async remove(e){if(this.isPreview){this.mem=this.mem.filter(t=>t.name!==e);return}await this.http.delete(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}`)}async detail(e){if(this.isPreview){let t=this.mem.find(n=>n.name===e);return{name:e,avatar:t?.avatar,description:t?.description,userDescription:t?.userDescription,...t?.gender?{gender:t.gender}:{},...t?.isPreset!==void 0?{isPreset:t.isPreset}:{},state:await this.state.get(e)}}return this.http.get(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/detail`)}async setPriority(e,t){let n=Math.max(0,Math.min(100,Math.round(t)));this.isPreview||await this.http.patch(`/conversations/${this.getConversationId()}/characters/${encodeURIComponent(e)}/state`,{priority:n})}};function B(o){return{name:o.name,description:o.description,avatar:o.avatar,...o.gender?{gender:o.gender}:{},...o.userDescription!==void 0?{userDescription:o.userDescription}:{},...o.isPreset!==void 0?{isPreset:o.isPreset}:{}}}function H(o){return{name:o.name,avatar:o.avatar,description:o.description,...o.userDescription!==void 0?{userDescription:o.userDescription}:{},...o.gender?{gender:o.gender}:{},...o.isPreset!==void 0?{isPreset:o.isPreset}:{}}}var x=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem=[];i&&(this.mem=i.map(s=>({...s})))}setInitial(e){this.mem=e?e.map(t=>({...t})):[]}async list(){return this.isPreview?[...this.mem]:this.http.get(`/conversations/${this.getConversationId()}/relationships`)}async get(e,t){if(this.isPreview){let n=this.mem.find(i=>i.from===e&&i.to===t);if(n)return{...n};throw new Error("Relationship not found")}return this.http.get(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}async add(e){if(this.isPreview){this.mem.push({...e});return}await this.http.post(`/conversations/${this.getConversationId()}/relationships`,e)}async update(e,t,n){if(this.isPreview){let i=this.mem.find(s=>s.from===e&&s.to===t);i?Object.assign(i,n):this.mem.push({from:e,to:t,...n});return}await this.http.patch(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,n)}async remove(e,t){if(this.isPreview){this.mem=this.mem.filter(n=>!(n.from===e&&n.to===t));return}await this.http.delete(`/conversations/${this.getConversationId()}/relationships/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};var I=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem=U(i))}setInitial(e){this.mem=e?U(e):{}}async list(e){if(this.isPreview){if(e!==void 0)return{...this.mem[e]||{}};let t={};for(let[n,i]of Object.entries(this.mem))t[n]={...i};return t}return e!==void 0?this.http.get(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(e)}`):this.http.get(`/conversations/${this.getConversationId()}/inventory`)}async add(e){let{group:t,name:n,count:i=1,desc:s,iconUrl:r}=e;if(this.isPreview){if(!this.mem[t])throw new Error(`Group "${t}" does not exist`);if(n in this.mem[t])throw new Error(`Item "${n}" already exists in group "${t}"`);let a={count:i};s!==void 0&&(a.desc=s),r!==void 0&&(a.iconUrl=r),this.mem[t][n]=a;return}await this.http.post(`/conversations/${this.getConversationId()}/inventory`,{group:t,name:n,count:i,desc:s,iconUrl:r})}async update(e){let{group:t,name:n,...i}=e;if(this.isPreview){let s=this.mem[t];if(!s||!(n in s))throw new Error(`Item "${t}/${n}" not found`);Object.assign(s[n],i);return}await this.http.patch(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(t)}/${encodeURIComponent(n)}`,i)}async remove(e){let{group:t,name:n}=e;if(this.isPreview){this.mem[t]&&delete this.mem[t][n];return}await this.http.delete(`/conversations/${this.getConversationId()}/inventory/${encodeURIComponent(t)}/${encodeURIComponent(n)}`)}async move(e){let{fromGroup:t,toGroup:n,name:i,newName:s}=e;if(this.isPreview){let r=this.mem[t];if(!r||!(i in r))throw new Error(`Source item "${t}/${i}" not found`);if(!this.mem[n])throw new Error(`Target group "${n}" does not exist`);let a=s||i;if(t===n&&a===i)return;if(a in this.mem[n])throw new Error(`Item "${a}" already exists in target group`);this.mem[n][a]=r[i],delete r[i];return}await this.http.post(`/conversations/${this.getConversationId()}/inventory/move`,{fromGroup:t,toGroup:n,name:i,newName:s})}async ensureGroup(e){if(this.isPreview){this.mem[e]||(this.mem[e]={});return}await this.http.post(`/conversations/${this.getConversationId()}/inventory/groups/${encodeURIComponent(e)}`,{})}async removeGroup(e,t){let n=t?.cascade??!1;if(this.isPreview){let s=this.mem[e];if(s&&Object.keys(s).length>0&&!n)throw new Error(`Group "${e}" is not empty, pass cascade: true to force delete`);delete this.mem[e];return}let i=n?"?cascade=true":"";await this.http.delete(`/conversations/${this.getConversationId()}/inventory/groups/${encodeURIComponent(e)}${i}`)}};function U(o){let e={};for(let[t,n]of Object.entries(o)){let i={};for(let[s,r]of Object.entries(n))i[s]={...r};e[t]=i}return e}var P=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem={...i})}setInitial(e){this.mem=e?{...e}:{}}async get(){return this.isPreview?{...this.mem}:this.http.get(`/conversations/${this.getConversationId()}/world`)}async update(e){if(this.isPreview){Object.assign(this.mem,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/world`,e)}};var $=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem={...i})}setInitial(e){this.mem=e?{...e}:{}}async get(e){if(this.isPreview)return e?{...this.mem[e]||{}}:{...this.mem};let t=e?{group:e}:void 0;return this.http.get(`/conversations/${this.getConversationId()}/player/state`,t)}async update(e,t){if(this.isPreview){this.mem[e]={...this.mem[e]||{},...t};return}await this.http.patch(`/conversations/${this.getConversationId()}/player/state`,{group:e,values:t})}},S=class{constructor(e,t,n=!1,i,s){this.http=e;this.getConversationId=t;this.isPreview=n;this.memPersona={name:""};i&&(this.memPersona={...i}),this.state=new $(e,t,n,s)}setInitial(e,t){this.memPersona=e?{...e}:{name:""},this.state.setInitial(t)}async get(){return this.isPreview?{...this.memPersona}:this.http.get(`/conversations/${this.getConversationId()}/player`)}async update(e){if(this.isPreview){Object.assign(this.memPersona,e);return}await this.http.patch(`/conversations/${this.getConversationId()}/player`,e)}};var E=class{constructor(e,t,n=!1,i){this.http=e;this.getConversationId=t;this.isPreview=n;this.mem={};i&&(this.mem=A(i))}setInitial(e){this.mem=e?A(e):{}}async get(e){if(this.isPreview)return e!==void 0?this.mem[e]:{...this.mem};let t=await this.http.get(`/conversations/${this.getConversationId()}/custom`);return e!==void 0?t[e]:t}async set(e){if(this.isPreview){for(let[t,n]of Object.entries(e))typeof n=="object"&&n!==null&&!Array.isArray(n)&&typeof this.mem[t]=="object"&&this.mem[t]!==null?this.mem[t]={...this.mem[t],...n}:this.mem[t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom`,e)}async delete(e){if(this.isPreview){delete this.mem[e];return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}`)}async setGroupField(e,t,n){if(this.isPreview){(!this.mem[e]||typeof this.mem[e]!="object")&&(this.mem[e]={}),this.mem[e][t]=n;return}await this.http.patch(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`,{value:n})}async deleteGroupField(e,t){if(this.isPreview){if(typeof this.mem[e]=="object"&&this.mem[e]!==null){let n=this.mem[e];delete n[t]}return}await this.http.delete(`/conversations/${this.getConversationId()}/custom/${encodeURIComponent(e)}/${encodeURIComponent(t)}`)}};function A(o){let e={};for(let[t,n]of Object.entries(o))typeof n=="object"&&n!==null&&!Array.isArray(n)?e[t]={...n}:e[t]=n;return e}var F="/functions/v1/world-engine/v1",re="https://api.storvia.ai";function oe(){return window.__STORVIA__||{}}function ae(o=5e3){let e=oe();return e.apiBase?Promise.resolve(e):new Promise((t,n)=>{let i=setTimeout(()=>{window.removeEventListener("message",s),n(new h("NOT_INITIALIZED","Timed out waiting for __STORVIA__ config from parent frame."))},o);function s(r){let a=null;if(r.data?.type==="storvia-init"&&r.data.apiBase?a={apiBase:r.data.apiBase,gameId:r.data.gameId,accessToken:r.data.accessToken}:r.data?.type==="storvia-preview-init"&&r.data.config&&(a=r.data.config),a&&a.apiBase){clearTimeout(i),window.removeEventListener("message",s);let l=window;l.__STORVIA__=a,t(a)}}window.addEventListener("message",s)})}var T=class{constructor(){this.baseUrl="";this.gameId="";this.conversationId="";this.modelId="";this.accessToken="";this.initialized=!1;this.isPreview=!1;this.previewConfig=void 0}async init(){if(this.initialized)return;let e=await ae(),t=e.apiBase;if(!t)throw new h("NOT_INITIALIZED","window.__STORVIA__.apiBase is not set. The platform must inject it before SDK init.");if(this.baseUrl=`${t}${F}`,this.isPreview=!!e.preview,this.previewConfig=e.previewConfig,!e.gameId)throw new h("GAME_NOT_FOUND","window.__STORVIA__.gameId is not set. The platform must inject it before SDK init.");if(this.gameId=e.gameId,!e.accessToken)throw new h("UNAUTHORIZED","window.__STORVIA__.accessToken is not set. The platform must inject the user token before SDK init.");if(this.accessToken=e.accessToken,this.http=new R(this.baseUrl,this.accessToken,!!e.debug),this.isPreview){this.conversationId="00000000-0000-0000-0000-000000000000";let[d,c]=await Promise.all([this.fetchModels(),this.fetchPreviewSnapshot()]);this.modelId=e.selectedModelId||d[0]?.id||"",this.settingsSheet=new y({onModelChange:M=>{this.modelId=M},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),d.length>0&&this.settingsSheet.mount(d,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let f=()=>this.gameId,g=()=>this.conversationId,v=()=>this.modelId;this.chat=new w(this.http,f,g,v,!0,this.previewConfig),this.characters=new C(this.http,g,!0,c?.characters,c?.characterStates),this.relationships=new x(this.http,g,!0,c?.relationships),this.inventory=new I(this.http,g,!0,c?.inventory),this.world=new P(this.http,g,!0,c?.world),this.player=new S(this.http,g,!0,c?.player,c?.playerState),this.custom=new E(this.http,g,!0,c?.custom),this.initialized=!0,this.listenForPreviewMessages();return}let[n,i]=await Promise.all([this.authenticate(),this.fetchModels()]);this.conversationId=n.conversationId;let s=this.getSavedModelId();this.modelId=s&&i.some(d=>d.id===s)?s:i[0]?.id||"";let r=n.settings||{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""};this.settingsSheet=new y({onModelChange:d=>{this.modelId=d},onSettingsChange:d=>this.saveSettings(d),onSync:()=>this.syncSettings()}),this.settingsSheet.mount(i,this.modelId,r,n.hasWorldUpdate??!1);let a=()=>this.gameId,l=()=>this.conversationId,p=()=>this.modelId;this.chat=new w(this.http,a,l,p),this.characters=new C(this.http,l),this.relationships=new x(this.http,l),this.inventory=new I(this.http,l),this.world=new P(this.http,l),this.player=new S(this.http,l),this.custom=new E(this.http,l),this.initialized=!0}listenForPreviewMessages(){window.addEventListener("message",e=>{!e.data||e.data.type!=="storvia-preview"||(e.data.action==="set-model"&&(this.modelId=e.data.modelId||""),e.data.action==="update-config"&&(this.previewConfig=e.data.previewConfig,this.chat&&this.chat.updatePreviewConfig(this.previewConfig),this.refreshPreviewSnapshot().catch(t=>{console.warn("[Storvia SDK] refreshPreviewSnapshot failed:",t)})))})}async fetchPreviewSnapshot(){try{let e={game_id:this.gameId};return this.previewConfig&&("game_config"in this.previewConfig&&(e.game_config=this.previewConfig.game_config),"game_state"in this.previewConfig&&(e.game_state_override=this.previewConfig.game_state)),await this.http.post("/preview/initial-snapshot",e)}catch(e){return console.warn("[Storvia SDK] fetchPreviewSnapshot failed:",e),null}}async refreshPreviewSnapshot(){let e=await this.fetchPreviewSnapshot();e&&(this.characters?.setInitial(e.characters,e.characterStates),this.player?.setInitial(e.player,e.playerState),this.inventory?.setInitial(e.inventory),this.relationships?.setInitial(e.relationships),this.world?.setInitial(e.world),this.custom?.setInitial(e.custom))}async saveSettings(e){await this.http.patch("/settings",{conversation_id:this.conversationId,...e})}async syncSettings(){await this.http.post("/sync",{conversation_id:this.conversationId})}async fetchModels(){try{return await this.http.get("/models")}catch{}return[]}async authenticate(){let e=await fetch(`${this.baseUrl}/auth`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.accessToken}`},body:JSON.stringify({game_id:this.gameId})});if(!e.ok)throw e.status===401?new h("UNAUTHORIZED","User not authenticated"):e.status===404?new h("GAME_NOT_FOUND","Game not found or not published"):new h("INTERNAL_ERROR",`Auth failed: HTTP ${e.status}`);let t=await e.json();return t.data??t}getSavedModelId(){try{return localStorage.getItem("storvia_model_id")||""}catch{return""}}async initDev(e){if(this.initialized)return;this.baseUrl=`${re}${F}`,this.gameId=e.gameId,this.isPreview=!0,this.http=new R(this.baseUrl,"",!1,e.apiKey);let[t,n]=await Promise.all([this.fetchModels(),this.fetchPreviewSnapshot()]);this.modelId=t[0]?.id||"",this.conversationId="00000000-0000-0000-0000-000000000000",this.settingsSheet=new y({onModelChange:a=>{this.modelId=a},onSettingsChange:()=>Promise.resolve(),onSync:()=>Promise.resolve()}),t.length>0&&this.settingsSheet.mount(t,this.modelId,{temperature:1,reply_length:"medium",reply_language:"zh-CN",player_note:""},!1);let i=()=>this.gameId,s=()=>this.conversationId,r=()=>this.modelId;this.chat=new w(this.http,i,s,r,!0,void 0),this.characters=new C(this.http,s,!0,n?.characters,n?.characterStates),this.relationships=new x(this.http,s,!0,n?.relationships),this.inventory=new I(this.http,s,!0,n?.inventory),this.world=new P(this.http,s,!0,n?.world),this.player=new S(this.http,s,!0,n?.player,n?.playerState),this.custom=new E(this.http,s,!0,n?.custom),this.initialized=!0}};async function G(o){let e=new T;return o?.dev?await e.initDev(o.dev):await e.init(),e}function L(o){return typeof o=="object"&&o!==null&&"value"in o&&"type"in o&&(o.type==="number"||o.type==="text")}function j(o){return L(o)?o.value:o}return K(le);})();
689
689
  if(typeof window!=="undefined"){window.createStorviaSDK=StorviaSDK.createStorviaSDK;}
package/package.json CHANGED
@@ -1,47 +1,47 @@
1
1
  {
2
- "name": "@storvia/sdk",
3
- "version": "0.3.0",
4
- "description": "Storvia World SDK - Build interactive text games on the Storvia platform",
5
- "main": "dist/index.cjs.js",
6
- "module": "dist/index.esm.js",
7
- "types": "dist/index.d.mts",
8
- "exports": {
9
- ".": {
10
- "types": "./dist/index.d.mts",
11
- "import": "./dist/index.esm.js",
12
- "require": "./dist/index.cjs.js"
2
+ "name": "@storvia/sdk",
3
+ "version": "0.3.1",
4
+ "description": "Storvia World SDK - Build interactive text games on the Storvia platform",
5
+ "main": "dist/index.cjs.js",
6
+ "module": "dist/index.esm.js",
7
+ "types": "dist/index.d.mts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.mts",
11
+ "import": "./dist/index.esm.js",
12
+ "require": "./dist/index.cjs.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "scripts": {
19
+ "build": "tsup",
20
+ "dev": "tsup --watch",
21
+ "typecheck": "tsc --noEmit",
22
+ "prepublishOnly": "npm run build",
23
+ "test": "vitest run",
24
+ "test:watch": "vitest",
25
+ "test:memory": "vitest run test/memory",
26
+ "test:production": "vitest run test/production",
27
+ "test:preview-studio": "vitest run test/preview-studio",
28
+ "test:preview-dev": "vitest run test/preview-dev"
29
+ },
30
+ "keywords": [
31
+ "storvia",
32
+ "world",
33
+ "sdk",
34
+ "interactive",
35
+ "text-game"
36
+ ],
37
+ "license": "UNLICENSED",
38
+ "devDependencies": {
39
+ "@supabase/supabase-js": "^2.45.0",
40
+ "@vitest/coverage-v8": "^2.1.0",
41
+ "dotenv": "^16.4.5",
42
+ "jsdom": "^25.0.0",
43
+ "tsup": "^8.0.0",
44
+ "typescript": "^5.4.0",
45
+ "vitest": "^2.1.0"
13
46
  }
14
- },
15
- "files": [
16
- "dist"
17
- ],
18
- "scripts": {
19
- "build": "tsup",
20
- "dev": "tsup --watch",
21
- "typecheck": "tsc --noEmit",
22
- "prepublishOnly": "npm run build",
23
- "test": "vitest run",
24
- "test:watch": "vitest",
25
- "test:memory": "vitest run test/memory",
26
- "test:production": "vitest run test/production",
27
- "test:preview-studio": "vitest run test/preview-studio",
28
- "test:preview-dev": "vitest run test/preview-dev"
29
- },
30
- "keywords": [
31
- "storvia",
32
- "world",
33
- "sdk",
34
- "interactive",
35
- "text-game"
36
- ],
37
- "license": "UNLICENSED",
38
- "devDependencies": {
39
- "@supabase/supabase-js": "^2.45.0",
40
- "@vitest/coverage-v8": "^2.1.0",
41
- "dotenv": "^16.4.5",
42
- "jsdom": "^25.0.0",
43
- "tsup": "^8.0.0",
44
- "typescript": "^5.4.0",
45
- "vitest": "^2.1.0"
46
- }
47
47
  }